blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
467a2381c22f495fdf098196f6a16273350d47ce | d5e8ed287ad0affe516498484fe478b45285919c | /Libs/Com/Communication/pcdebug.h | e16b3963345c86a38cc4a1b74b1d642a39149db2 | [] | no_license | kentkdf/ServoDriveTech | ca50434ebe602996d111833901fa2549b23b85b6 | a517a06a3893a16c4825cec40551e67658500fe2 | refs/heads/master | 2021-06-26T07:55:49.863621 | 2018-01-16T05:48:22 | 2018-01-16T05:48:22 | 141,222,484 | 3 | 0 | null | 2018-07-17T02:51:26 | 2018-07-17T02:51:26 | null | UTF-8 | C++ | false | false | 5,402 | h | #ifndef PCDEBUG_H
#define PCDEBUG_H
#include "icom.h"
COM_NAMESPACE_BEGIN
class PcDebugPrivate;
class COMSHARED_EXPORT PcDebug:public ICom
{
Q_DECLARE_PRIVATE(PcDebug)
public:
explicit PcDebug(const string &objectName="PcDebug");
virtual ~PcDebug();
errcode_t open(void(*processCallBack)(void *, short *), void *parameter)override;
errcode_t close()override;
//------伺服操作相关---------
errcode_t setServoEnable(uint8_t axis, bool on)override;
errcode_t checkServoIsEnable(uint8_t axis,bool &enable) override;
errcode_t setServoTaskMode(uint8_t axis,ServoTaskMode_t mode);
ServoTaskMode_t currentServoTaskMode(uint8_t axis,errcode_t &errcode);
errcode_t setIdRef(uint8_t axis ,double idRef)override;
errcode_t getIdRef(uint8_t axis ,double &value)override;
errcode_t setIqRef(uint8_t axis, double iqRef)override;
errcode_t getIqRef(uint8_t axis, double &value)override;
errcode_t setSpdRef(uint8_t axis,double spdRef)override;
errcode_t getSpdRef(uint8_t axis,double &value)override;
errcode_t setUdRef(uint8_t axis,double udRef)override;
errcode_t getUdRef(uint8_t axis,double &value)override;
errcode_t setUqRef(uint8_t axis,double uqRef)override;
errcode_t getUqRef(uint8_t axis,double &value)override;
errcode_t setUaRef(uint8_t axis,double uaRef)override;
errcode_t getUaRef(uint8_t axis,double &value)override;
errcode_t setUbRef(uint8_t axis,double ubRef)override;
errcode_t getUbRef(uint8_t axis,double &value)override;
errcode_t setUcRef(uint8_t axis,double ucRef)override;
errcode_t getUcRef(uint8_t axis,double &value)override;
errcode_t setPosAdjRef(uint8_t axis,double posAdjRef)override;
errcode_t getPosAdjRef(uint8_t axis,double &value)override;
errcode_t setPosRef(uint8_t axis,double posRef)override;
//--------读写通用指令-----------
//!读取后的结果也在pdu里面
errcode_t sendGeneralCmd(uint8_t axis, GeneralPDU &pdu)override;
//---------DSP操作相关---------------------------
errcode_t readDSPVersion(uint8_t dspInx,uint16_t &version)override;
errcode_t readFPGAVersion(uint8_t fpgaInx,uint16_t &version)override;
errcode_t readFPGAYearDay(uint8_t fpgaInx,uint16_t &year,uint16_t &day)override;
errcode_t hex2LdrFormat(const wstring &hexFile,const wstring &ldrFile)override;
errcode_t uartBootHandler(uint8_t dspInx,const wstring &filePath,int32_t baudRate, int16_t cmd, const string& inputKey, ProcessCallBackHandler, void* prm)override;
errcode_t resetDSP(uint8_t dspInx)override;
bool checkResetFinish(uint8_t dspInx,errcode_t &errCode)override;
//----------软件、固件烧写----------------
errcode_t downLoadDSPFLASH(uint8_t dspInx,const wstring &fileName,ProcessCallBackHandler,void *parameters)override;
errcode_t downLoadFPGAFLASH(uint8_t fpgaInx,const wstring &fileName,ProcessCallBackHandler,void *parameters)override;
//-----------EEPROM读写---------------------
errcode_t readEEPROM(uint16_t ofst, uint8_t* value, uint16_t num,uint8_t cs)override;
errcode_t writeEEPROM(uint16_t ofst, const uint8_t* value, uint16_t num,uint8_t cs)override;
//------------获得网卡信息------------------
NetCardInfo getNetCardInformation(void)override;
//------------画图相关---------------------
errcode_t startPlot(const PlotControlPrm &ctrPrm)override;
errcode_t stopPlot(const PlotControlPrm &ctrPrm)override;
errcode_t getPlotData(const PlotControlPrm &ctrPrm,CurveList &curveList)override;
errcode_t enableCRC(bool enable)override;
//--------读写RAM操作------------------
errcode_t writeRAM16(uint8_t axis,uint16_t ofst,uint8_t page,int16_t value)override;
errcode_t readRAM16(uint8_t axis,uint16_t ofst,uint8_t page,int16_t &value)override;
errcode_t writeRAM32(uint8_t axis,uint16_t ofst,uint8_t page,int32_t value)override;
errcode_t readRAM32(uint8_t axis,uint16_t ofst,uint8_t page,int32_t &value)override;
errcode_t writeRAM64(uint8_t axis,uint16_t ofst,uint8_t page,int64_t value)override;
errcode_t readRAM64(uint8_t axis,uint16_t ofst,uint8_t page,int64_t &value)override;
//--------读写铁电FLASH操作------------------
errcode_t writeFLASH16(uint8_t axis,uint16_t ofst,uint8_t page,int16_t value)override;
errcode_t readFLASH16(uint8_t axis,uint16_t ofst,uint8_t page,int16_t &value)override;
errcode_t writeFLASH32(uint8_t axis,uint16_t ofst,uint8_t page,int32_t value)override;
errcode_t readFLASH32(uint8_t axis,uint16_t ofst,uint8_t page,int32_t &value)override;
errcode_t writeFLASH64(uint8_t axis,uint16_t ofst,uint8_t page,int64_t value)override;
errcode_t readFLASH64(uint8_t axis,uint16_t ofst,uint8_t page,int64_t &value)override;
//------------FPGA寄存器操作----------------
errcode_t readFPGAReg16(uint8_t fpgaInx,uint16_t address,int16_t &value,uint16_t base)override;
errcode_t writeFPGAReg16(uint8_t fpgaInx,uint16_t address,int16_t value,uint16_t base)override;
errcode_t readFPGAReg32(uint8_t fpgaInx,uint16_t address,int32_t &value,uint16_t base)override;
errcode_t writeFPGAReg32(uint8_t fpgaInx,uint16_t address,int32_t value,uint16_t base)override;
errcode_t readFPGAReg64(uint8_t fpgaInx,uint16_t address,int64_t &value,uint16_t base)override;
errcode_t writeFPGAReg64(uint8_t fpgaInx,uint16_t address,int64_t value,uint16_t base)override;
protected:
PcDebug(PcDebugPrivate &d);
};
COM_NAMESPACE_END
#endif // PCDEBUG_H
| [
"chenchao_szu@163.comm"
] | chenchao_szu@163.comm |
e9b157ddfbe2609b2a11b215b2814918ffbf7d85 | 13500b849db6d62ac7ee94e32ddd76681af79d6b | /1003/1003. 猜数游戏.cpp | 668a702cd5f9709c46889ecf88660c9040235082 | [] | no_license | syjsu/noip-with-vue.js | 055a90d13dedd2c00b2d449a39fa4f3128270480 | 6076cd41b5343dd3ff18b4c4afec207021f8c78b | refs/heads/master | 2020-03-17T20:15:42.362689 | 2018-05-24T05:10:27 | 2018-05-24T05:10:27 | 133,900,801 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 141 | cpp | #include<cstdio>
using namespace std;
int main()
{
int x;
scanf("%d",&x);
if(x*1000+x%7%11%13)
printf("%d",x);
return 0;
}
| [
"syjsu@qq.com"
] | syjsu@qq.com |
5029573a30a45d02686b5141b1159fe5ae4b3bf3 | 84fd6d541f6a01c086d7d8f8ed4cb7e049a855b7 | /Week3/19.cpp | 374fc1b7a2fe109b5b20d1f2f244d948047f171c | [] | no_license | sarankaarthik/CPCprep | 23886f0d707be8b9e346279f4df67181f9d1962f | 15581b9008591099a85f29c286661fa64c3c04e0 | refs/heads/main | 2023-05-14T07:18:37.083813 | 2021-06-05T06:26:04 | 2021-06-05T06:26:04 | 352,126,895 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,713 | cpp | #include <iostream>
#include <map>
#include <random>
using namespace std;
struct node{
char x;
node* next;
};
class List{
public:
struct node* HEAD = NULL;
struct node* END = NULL;
template<typename T>
T push(T x)
{
struct node* n = new node();
n->x = x;
n->next = NULL;
if(HEAD == NULL)
{
HEAD = n;
END = n;
}
else
{
END->next = n;
END = n;
}
}
void deleteList(struct node* head)
{
struct node* temp = HEAD;
struct node* next = NULL;
while (temp != NULL)
{
next = temp->next;
free(temp);
temp = next;
}
HEAD = NULL;
}
void printList()
{
struct node* temp = HEAD;
while(temp != NULL)
{
cout<<temp->x<<"->";
temp = temp->next;
}
cout<<endl<<endl;
}
};
struct node* segConsVow(struct node* n)
{
List vowList, consList;
struct node* temp = n;
struct node* evenEnd = n;
while(temp != NULL)
{
if(temp->x == 'a' || temp->x == 'e' || temp->x == 'i' || temp->x == 'o' || temp->x == 'u')
vowList.push(temp->x);
else
consList.push(temp->x);
temp = temp->next;
}
vowList.END->next = consList.HEAD;
return vowList.HEAD;
}
int main()
{
List list;
cout<<endl;
list.push<char>('a');
list.push<char>('r');
list.push<char>('h');
list.push<char>('i');
list.push<char>('o');
list.push<char>('s');
list.printList();
list.HEAD = segConsVow(list.HEAD);
list.printList();
}
| [
"noreply@github.com"
] | sarankaarthik.noreply@github.com |
50177484775050bc3df4315c45f25229f35a9848 | a62342d6359a88b0aee911e549a4973fa38de9ea | /0.6.0.3/External/SDK/BP_RemovableFoliage_Blackthorn_d_functions.cpp | 2ea5abca38466c2872f6c8392f683dad9241c6e1 | [] | no_license | zanzo420/Medieval-Dynasty-SDK | d020ad634328ee8ee612ba4bd7e36b36dab740ce | d720e49ae1505e087790b2743506921afb28fc18 | refs/heads/main | 2023-06-20T03:00:17.986041 | 2021-07-15T04:51:34 | 2021-07-15T04:51:34 | 386,165,085 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 607 | cpp | // Name: Medieval Dynasty, Version: 0.6.0.3
#include "../pch.h"
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
void UBP_RemovableFoliage_Blackthorn_d_C::AfterRead()
{
UBP_RemovableFoliage_C::AfterRead();
}
void UBP_RemovableFoliage_Blackthorn_d_C::BeforeDelete()
{
UBP_RemovableFoliage_C::BeforeDelete();
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
c8481a947659725ef2dedbd749164efc65b3d421 | 720b6e481e75dc3efa2f65ae388977273b61aa05 | /Clove/include/Clove/Graphics/Core/CommandBuffer.hpp | f23cab15e64d9ad95b855cf60881313f097ad253 | [
"MIT"
] | permissive | asdlei99/Garlic | 9baf1ebf25dd7eec9fbe048f7ce11629b9f26b25 | fec9f1f14039a14e60db46ceb943b9e6be3c29f5 | refs/heads/master | 2021-01-02T20:54:38.559648 | 2020-02-10T22:45:06 | 2020-02-10T22:45:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 984 | hpp | #pragma once
#include "Clove/Graphics/Core/GraphicsTypes.hpp"
namespace clv::gfx{
class Buffer;
class Texture;
class PipelineObject;
class RenderTarget;
class Shader;
class Surface;
struct Viewport;
}
namespace clv::gfx{
class CommandBuffer{
//FUNCTIONS
public:
virtual ~CommandBuffer() = default;
virtual void beginEncoding() = 0;
virtual void bindIndexBuffer(const Buffer& buffer) = 0;
virtual void bindVertexBuffer(const Buffer& buffer, const uint32_t stride) = 0;
virtual void bindShaderResourceBuffer(const Buffer& buffer, const ShaderStage shaderType, const uint32_t bindingPoint) = 0;
virtual void bindPipelineObject(const PipelineObject& pipelineObject) = 0;
virtual void bindTexture(const Texture* texture, const uint32_t bindingPoint) = 0;
virtual void setViewport(const Viewport& viewport) = 0;
virtual void setDepthEnabled(bool enabled) = 0;
virtual void drawIndexed(const uint32_t count) = 0;
virtual void endEncoding() = 0;
};
} | [
"wolfplayeral@yahoo.co.uk"
] | wolfplayeral@yahoo.co.uk |
2ca5a26319f14294e07039d273d4d2dea8a45cec | 78eff93ad7129072ab580281d4dfcc2e89a24379 | /Qt_cam_backup/dataSources/DataProducer.h | 7a55537ad24b5b8c94a15e37954e831be29eb44b | [] | no_license | sebsgit/toolbox | 8b96ff8272e2a6ba6566f06d808511a4d26d7a1c | 78c3288d9143c287734cbb239bb5ba075eb9e730 | refs/heads/master | 2022-11-02T23:48:03.821855 | 2022-10-03T19:30:56 | 2022-10-03T19:30:56 | 37,983,019 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 675 | h | #ifndef DATAPRODUCER_H
#define DATAPRODUCER_H
#include "AbstractDataSource.h"
#include "AppSettings.h"
#include <QObject>
class DataProducer : public QObject {
Q_OBJECT
public:
explicit DataProducer(QObject* parent = nullptr);
~DataProducer() override;
signals:
void error(const QString& desc);
void configureDone();
void dataAvailable(AbstractDataSource* source, const QByteArray& data);
public slots:
void configure(const DataSources& sourceSettings);
void start();
void stop();
private slots:
void onDataAvailable(const QByteArray& data);
private:
class Priv;
std::unique_ptr<Priv> priv_;
};
#endif // DATAPRODUCER_H
| [
"s.baginski@mail.com"
] | s.baginski@mail.com |
5e4de3244fae087d034ab8ed02d2ba0fdc677619 | 9402c9f35b6d895c3b6f7ddcfc87241e6b9145d8 | /Spoj/edist.cpp | 96757f9f713ec44406dfbdc7201d6f06e7a67942 | [] | no_license | siddharth94/competitive | 586d42679558dcd1dcca3457c2ca7be089cbda30 | ecda01521a7a9908225771d9374d5c18fa646515 | refs/heads/master | 2021-07-06T05:27:13.395384 | 2017-09-29T10:16:20 | 2017-09-29T10:16:20 | 105,229,373 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,129 | cpp | #include <bits/stdc++.h>
using namespace std;
#define F(i,n) for(int i=0;i<n;i++)
#define FE(i,n) for(int i=0;i<=n;i++)
#define FR(i,n) for(int i=n;i>0;i--)
#define FRE(i,n) for(int i=n;i>=0;i--)
#define mp(a,b) make_pair(a,b)
#define pii pair <int, int>
#define pb push_back
#define ft first
#define sd second
#define LL long long
#define gc getchar_unlocked
#define pc putchar_unlocked
inline void get(int &x)
{
register int c = gc();
x = 0;
int neg = 0;
for(;((c<48 || c>57) && c != '-');c = gc());
if(c=='-') {neg=1;c=gc();}
for(;c>47 && c<58;c = gc()) {x = (x<<1) + (x<<3) + c - 48;}
if(neg) x=-x;
}
int dp[2005][2005];
int main()
{
int T;
get(T);
while (T--)
{
string a,b;
cin >> a >> b;
int la = a.length();
int lb = b.length();
FE(i,la)
{
FE(j,lb)
{
if (i==0)
dp[i][j] = j;
else if (j==0)
dp[i][j] = i;
else
{
if (a[i-1] == b[j-1])
dp[i][j] = min(min(dp[i-1][j]+1,dp[i][j-1]+1),dp[i-1][j-1]);
else
dp[i][j] = min(min(dp[i-1][j],dp[i][j-1]),dp[i-1][j-1])+1;
}
}
}
printf("%d\n",dp[la][lb]);
}
return 0;
} | [
"siddharthgg52@gmail.com"
] | siddharthgg52@gmail.com |
f867bfc5ff978645cc2cfe79c6b76652786d8af4 | 80370ce05cdf5c5187efde665d1c9ef0ef72db4c | /src/uniforms.cpp | ae5b5c7a6aefdbae99055188cba44a64e72f5055 | [
"BSD-3-Clause"
] | permissive | matteo-dirollo/glslViewer | c4158d5a9d331e46f7d7c120ed169334dc7923b6 | 18ebc908f0e2f977c94e26b3d97a0c898340d510 | refs/heads/master | 2020-09-01T16:52:23.753121 | 2019-10-23T18:12:22 | 2019-10-23T18:12:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,417 | cpp | #include "uniforms.h"
#include <regex>
#include <sstream>
#include <sys/stat.h>
#include "tools/text.h"
std::string UniformData::getType() {
if (size == 1 && bInt) {
return "int";
}
else if (size == 1 && !bInt) {
return "float";
}
else {
return (bInt ? "ivec" : "vec") + toString(size);
}
}
UniformFunction::UniformFunction() {
type = "-undefined-";
}
UniformFunction::UniformFunction(const std::string &_type) {
type = _type;
}
UniformFunction::UniformFunction(const std::string &_type, std::function<void(Shader&)> _assign) {
type = _type;
assign = _assign;
}
UniformFunction::UniformFunction(const std::string &_type, std::function<void(Shader&)> _assign, std::function<std::string()> _print) {
type = _type;
assign = _assign;
print = _print;
}
// UNIFORMS
Uniforms::Uniforms(): cubemap(nullptr), m_change(false) {
// set the right distance to the camera
// Set up camera
cameras.push_back( Camera() );
functions["u_iblLuminance"] = UniformFunction("float", [this](Shader& _shader) {
_shader.setUniform("u_iblLuminance", 30000.0f * getCamera().getExposure());
},
[this]() { return toString(30000.0f * getCamera().getExposure()); });
// CAMERA UNIFORMS
//
functions["u_camera"] = UniformFunction("vec3", [this](Shader& _shader) {
_shader.setUniform("u_camera", -getCamera().getPosition());
},
[this]() { return toString(-getCamera().getPosition(), ','); });
functions["u_cameraDistance"] = UniformFunction("float", [this](Shader& _shader) {
_shader.setUniform("u_cameraDistance", getCamera().getDistance());
},
[this]() { return toString(getCamera().getDistance()); });
functions["u_cameraNearClip"] = UniformFunction("float", [this](Shader& _shader) {
_shader.setUniform("u_cameraNearClip", getCamera().getNearClip());
},
[this]() { return toString(getCamera().getNearClip()); });
functions["u_cameraFarClip"] = UniformFunction("float", [this](Shader& _shader) {
_shader.setUniform("u_cameraFarClip", getCamera().getFarClip());
},
[this]() { return toString(getCamera().getFarClip()); });
functions["u_cameraEv100"] = UniformFunction("float", [this](Shader& _shader) {
_shader.setUniform("u_cameraEv100", getCamera().getEv100());
},
[this]() { return toString(getCamera().getEv100()); });
functions["u_cameraExposure"] = UniformFunction("float", [this](Shader& _shader) {
_shader.setUniform("u_cameraExposure", getCamera().getExposure());
},
[this]() { return toString(getCamera().getExposure()); });
functions["u_cameraAperture"] = UniformFunction("float", [this](Shader& _shader) {
_shader.setUniform("u_cameraAperture", getCamera().getAperture());
},
[this]() { return toString(getCamera().getAperture()); });
functions["u_cameraShutterSpeed"] = UniformFunction("float", [this](Shader& _shader) {
_shader.setUniform("u_cameraShutterSpeed", getCamera().getShutterSpeed());
},
[this]() { return toString(getCamera().getShutterSpeed()); });
functions["u_cameraSensitivity"] = UniformFunction("float", [this](Shader& _shader) {
_shader.setUniform("u_cameraSensitivity", getCamera().getSensitivity());
},
[this]() { return toString(getCamera().getSensitivity()); });
functions["u_normalMatrix"] = UniformFunction("mat3", [this](Shader& _shader) {
_shader.setUniform("u_normalMatrix", getCamera().getNormalMatrix());
});
// CAMERA MATRIX UNIFORMS
functions["u_viewMatrix"] = UniformFunction("mat4", [this](Shader& _shader) {
_shader.setUniform("u_viewMatrix", getCamera().getViewMatrix());
});
functions["u_projectionMatrix"] = UniformFunction("mat4", [this](Shader& _shader) {
_shader.setUniform("u_projectionMatrix", getCamera().getProjectionMatrix());
});
// IBL UNIFORM
functions["u_cubeMap"] = UniformFunction("samplerCube", [this](Shader& _shader) {
if (cubemap) {
_shader.setUniformTextureCube("u_cubeMap", (TextureCube*)cubemap);
}
});
functions["u_SH"] = UniformFunction("vec3", [this](Shader& _shader) {
if (cubemap) {
_shader.setUniform("u_SH", cubemap->SH, 9);
}
});
}
Uniforms::~Uniforms(){
}
bool parseUniformData(const std::string &_line, UniformDataList *_uniforms) {
bool rta = false;
std::regex re("^(\\w+)\\,");
std::smatch match;
if (std::regex_search(_line, match, re)) {
// Extract uniform name
std::string name = std::ssub_match(match[1]).str();
// Extract values
int index = 0;
std::stringstream ss(_line);
std::string item;
while (getline(ss, item, ',')) {
if (index != 0) {
(*_uniforms)[name].bInt = !isFloat(item);
(*_uniforms)[name].value[index-1] = toFloat(item);
(*_uniforms)[name].change = true;
}
index++;
}
// Set total amount of values
(*_uniforms)[name].size = index-1;
rta = true;
}
return rta;
}
bool Uniforms::parseLine( const std::string &_line ) {
bool somethingChange = parseUniformData(_line, &data);
m_change += somethingChange;
return somethingChange;
}
bool Uniforms::addTexture( const std::string& _name, Texture* _texture) {
if (textures.find(_name) == textures.end()) {
textures[ _name ] = _texture;
return true;
}
else {
if (textures[ _name ])
delete textures[ _name ];
textures[ _name ] = _texture;
}
return false;
}
bool Uniforms::addTexture(const std::string& _name, const std::string& _path, WatchFileList& _files, bool _flip, bool _verbose) {
if (textures.find(_name) == textures.end()) {
struct stat st;
// If we can not get file stamp proably is not a file
if (stat(_path.c_str(), &st) != 0 )
std::cerr << "Error watching for file " << _path << std::endl;
// If we can lets proceed creating a texgure
else {
Texture* tex = new Texture();
// load an image into the texture
if (tex->load(_path, true)) {
// the image is loaded finish add the texture to the uniform list
textures[ _name ] = tex;
// and the file to the watch list
WatchFile file;
file.type = IMAGE;
file.path = _path;
file.lastChange = st.st_mtime;
file.vFlip = _flip;
_files.push_back(file);
if (_verbose) {
std::cout << "// " << _path << " loaded as: " << std::endl;
std::cout << "// uniform sampler2D " << _name << ";"<< std::endl;
std::cout << "// uniform vec2 " << _name << "Resolution;"<< std::endl;
}
return true;
}
else
delete tex;
}
}
return false;
}
bool Uniforms::addBumpTexture(const std::string& _name, const std::string& _path, WatchFileList& _files, bool _flip, bool _verbose) {
if (textures.find(_name) == textures.end()) {
struct stat st;
// If we can not get file stamp proably is not a file
if (stat(_path.c_str(), &st) != 0 )
std::cerr << "Error watching for file " << _path << std::endl;
// If we can lets proceed creating a texgure
else {
Texture* tex = new Texture();
// load an image into the texture
if (tex->loadBump(_path, true)) {
// the image is loaded finish add the texture to the uniform list
textures[ _name ] = tex;
// and the file to the watch list
WatchFile file;
file.type = IMAGE_BUMPMAP;
file.path = _path;
file.lastChange = st.st_mtime;
file.vFlip = _flip;
_files.push_back(file);
if (_verbose) {
std::cout << "// " << _path << " loaded and transform to normalmap as: " << std::endl;
std::cout << "// uniform sampler2D " << _name << ";"<< std::endl;
std::cout << "// uniform vec2 " << _name << "Resolution;"<< std::endl;
}
return true;
}
else
delete tex;
}
}
return false;
}
void Uniforms::setCubeMap( TextureCube* _cubemap ) {
if (cubemap)
delete cubemap;
cubemap = _cubemap;
}
void Uniforms::setCubeMap( const std::string& _filename, WatchFileList& _files, bool _verbose ) {
struct stat st;
if ( stat(_filename.c_str(), &st) != 0 ) {
std::cerr << "Error watching for cubefile: " << _filename << std::endl;
}
else {
TextureCube* tex = new TextureCube();
if ( tex->load(_filename, true) ) {
setCubeMap(tex);
WatchFile file;
file.type = CUBEMAP;
file.path = _filename;
file.lastChange = st.st_mtime;
file.vFlip = true;
_files.push_back(file);
std::cout << "// " << _filename << " loaded as: " << std::endl;
std::cout << "// uniform samplerCube u_cubeMap;"<< std::endl;
std::cout << "// uniform vec3 u_SH[9];"<< std::endl;
}
else {
delete tex;
}
}
}
void Uniforms::checkPresenceIn( const std::string &_vert_src, const std::string &_frag_src ) {
// Check active native uniforms
for (UniformFunctionsList::iterator it = functions.begin(); it != functions.end(); ++it) {
bool present = ( find_id(_vert_src, it->first.c_str()) != 0 || find_id(_frag_src, it->first.c_str()) != 0 );
if ( it->second.present != present) {
it->second.present = present;
m_change = true;
}
}
}
bool Uniforms::feedTo( Shader &_shader ) {
bool update = false;
// Pass Native uniforms
for (UniformFunctionsList::iterator it=functions.begin(); it!=functions.end(); ++it)
if (it->second.present)
if (it->second.assign)
it->second.assign(_shader);
// Pass User defined uniforms
if (m_change) {
for (UniformDataList::iterator it=data.begin(); it!=data.end(); ++it) {
if (it->second.change) {
if (it->second.bInt) {
_shader.setUniform(it->first, int(it->second.value[0]));
update = true;
}
else {
_shader.setUniform(it->first, it->second.value, it->second.size);
update = true;
}
}
}
}
// Pass Textures Uniforms
for (TextureList::iterator it = textures.begin(); it != textures.end(); ++it) {
_shader.setUniformTexture(it->first, it->second, _shader.textureIndex++ );
_shader.setUniform(it->first+"Resolution", it->second->getWidth(), it->second->getHeight());
}
// Pass Buffers Uniforms
for (unsigned int i = 0; i < buffers.size(); i++) {
_shader.setUniformTexture("u_buffer" + toString(i), &buffers[i], _shader.textureIndex++ );
}
// Pass Light Uniforms
if (lights.size() == 1) {
if (lights[0].getType() != LIGHT_DIRECTIONAL)
_shader.setUniform("u_light", lights[0].getPosition());
_shader.setUniform("u_lightColor", lights[0].color);
if (lights[0].getType() == LIGHT_DIRECTIONAL || lights[0].getType() == LIGHT_SPOT)
_shader.setUniform("u_lightDirection", lights[0].direction);
_shader.setUniform("u_lightIntensity", lights[0].intensity);
if (lights[0].falloff > 0)
_shader.setUniform("u_lightFalloff", lights[0].falloff);
_shader.setUniform("u_lightMatrix", lights[0].getBiasMVPMatrix() );
// _shader.setUniformDepthTexture("u_lightShadowMap", lights[0].getShadowMap() );
}
else {
for (unsigned int i = 0; i < lights.size(); i++) {
if (lights[i].getType() != LIGHT_DIRECTIONAL)
_shader.setUniform("u_light", lights[i].getPosition());
_shader.setUniform("u_lightColor", lights[i].color);
if (lights[i].getType() == LIGHT_DIRECTIONAL || lights[i].getType() == LIGHT_SPOT)
_shader.setUniform("u_lightDirection", lights[i].direction);
_shader.setUniform("u_lightIntensity", lights[i].intensity);
if (lights[i].falloff > 0)
_shader.setUniform("u_lightFalloff", lights[i].falloff);
_shader.setUniform("u_lightMatrix", lights[i].getBiasMVPMatrix() );
// _shader.setUniformDepthTexture("u_lightShadowMap", lights[i].getShadowMap() );
}
}
return update;
}
void Uniforms::flagChange() {
// Flag all user uniforms as changed
for (UniformDataList::iterator it = data.begin(); it != data.end(); ++it) {
it->second.change = true;
}
m_change = true;
getCamera().bChange = true;
}
void Uniforms::unflagChange() {
if (m_change) {
// Flag all user uniforms as NOT changed
for (UniformDataList::iterator it = data.begin(); it != data.end(); ++it)
it->second.change = false;
m_change = false;
}
for (unsigned int i = 0; i < lights.size(); i++)
lights[i].bChange = false;
getCamera().bChange = false;
}
bool Uniforms::haveChange() {
bool lightChange = false;
for (unsigned int i = 0; i < lights.size(); i++) {
if (lights[i].bChange) {
lightChange = true;
break;
}
}
// std::cout << " change " << m_change << std::endl;
// std::cout << " lights " << lightChange << std::endl;
// std::cout << " u_time " << functions["u_time"].present << std::endl;
// std::cout << " u_delta " << functions["u_delta"].present << std::endl;
// std::cout << " u_mouse " << functions["u_mouse"].present << std::endl;
// std::cout << " u_camera " << getCamera().bChange << std::endl;
return m_change ||
functions["u_time"].present ||
functions["u_delta"].present ||
functions["u_mouse"].present ||
functions["u_date"].present ||
lightChange || getCamera().bChange;
}
void Uniforms::clear() {
if (cubemap) {
delete cubemap;
cubemap = nullptr;
}
// Delete Textures
for (TextureList::iterator i = textures.begin(); i != textures.end(); ++i) {
if (i->second) {
delete i->second;
i->second = nullptr;
}
}
textures.clear();
}
void Uniforms::print(bool _all) {
if (_all) {
// Print all Native Uniforms (they carry functions)
for (UniformFunctionsList::iterator it= functions.begin(); it != functions.end(); ++it) {
std::cout << it->second.type << ',' << it->first;
if (it->second.print) {
std::cout << "," << it->second.print();
}
std::cout << std::endl;
}
}
else {
// Print Native Uniforms (they carry functions) that are present on the shader
for (UniformFunctionsList::iterator it= functions.begin(); it != functions.end(); ++it) {
if (it->second.present) {
std::cout << it->second.type << ',' << it->first;
if (it->second.print) {
std::cout << "," << it->second.print();
}
std::cout << std::endl;
}
}
}
// Print user defined uniform data
for (UniformDataList::iterator it= data.begin(); it != data.end(); ++it) {
std::cout << it->second.getType() << "," << it->first;
for (int i = 0; i < it->second.size; i++) {
std::cout << ',' << it->second.value[i];
}
std::cout << std::endl;
}
printBuffers();
printTextures();
printLights();
}
void Uniforms::printBuffers() {
for (size_t i = 0; i < buffers.size(); i++)
std::cout << "sampler2D,u_buffer" << i << std::endl;
if (functions["u_scene"].present)
std::cout << "sampler2D,u_scene" << std::endl;
if (functions["u_sceneDepth"].present)
std::cout << "sampler2D,u_sceneDepth" << std::endl;
}
void Uniforms::printTextures(){
for (TextureList::iterator it = textures.begin(); it != textures.end(); ++it) {
std::cout << "sampler2D," << it->first << ',' << it->second->getFilePath() << std::endl;
}
}
void Uniforms::printLights() {
if (lights.size() == 1) {
if (lights[0].getType() != LIGHT_DIRECTIONAL)
std::cout << "u_light," << toString( lights[0].getPosition() ) << std::endl;
std::cout << "u_lightColor," << toString( lights[0].color ) << std::endl;
if (lights[0].getType() == LIGHT_DIRECTIONAL || lights[0].getType() == LIGHT_SPOT)
std::cout << "u_lightDirection," << toString( lights[0].direction ) << std::endl;
std::cout << "u_lightIntensity," << toString( lights[0].intensity, 3) << std::endl;
if (lights[0].falloff > 0.0)
std::cout << "u_lightFalloff," << toString( lights[0].falloff, 3) << std::endl;
// std::cout << "sampler2D,u_lightShadowMap" << std::endl;
}
else if (lights.size() > 1) {
for (unsigned int i = 0; i < lights.size(); i++) {
if (lights[i].getType() != LIGHT_DIRECTIONAL)
std::cout << "u_light," << toString( lights[i].getPosition() ) << std::endl;
std::cout << "u_lightColor," << toString( lights[i].color ) << std::endl;
if (lights[i].getType() == LIGHT_DIRECTIONAL || lights[i].getType() == LIGHT_SPOT)
std::cout << "u_lightDirection," << toString( lights[i].direction ) << std::endl;
std::cout << "u_lightIntensity," << toString( lights[i].intensity, 3) << std::endl;
if (lights[i].falloff > 0.0)
std::cout << "u_lightFalloff," << toString( lights[i].falloff, 3) << std::endl;
// std::cout << "sampler2D,u_lightShadowMap" << std::endl;
}
}
}
| [
"patriciogonzalezvivo@gmail.com"
] | patriciogonzalezvivo@gmail.com |
b4870002828a459fcec930df56ef8c19f019be76 | 1f5cb4d601635ef1fe5534572e85e20285b8ef9d | /Razor_IMU/_9DoF_Razor_M0_Firmware/DCM.ino | 8b8464b17857c608c194813f3df1dc36ffa7b0d1 | [] | no_license | RijadAlisic/F1-10-Test-Bed | 3412c9747706ac56e425632ecda0a0de7da02a59 | da1055ca086166422f7132717c89983d6ef451dd | refs/heads/master | 2021-01-01T16:38:39.991553 | 2017-10-01T16:40:48 | 2017-10-01T16:40:48 | 97,882,451 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,681 | ino | /* This file is part of the Razor AHRS Firmware */
// DCM algorithm
/**************************************************/
void Normalize()
{
float error=0;
float temporary[3][3];
float renorm=0;
error= -Vector_Dot_Product(&DCM_Matrix[0][0],&DCM_Matrix[1][0])*.5; //eq.19
Vector_Scale(&temporary[0][0], &DCM_Matrix[1][0], error); //eq.19
Vector_Scale(&temporary[1][0], &DCM_Matrix[0][0], error); //eq.19
Vector_Add(&temporary[0][0], &temporary[0][0], &DCM_Matrix[0][0]);//eq.19
Vector_Add(&temporary[1][0], &temporary[1][0], &DCM_Matrix[1][0]);//eq.19
Vector_Cross_Product(&temporary[2][0],&temporary[0][0],&temporary[1][0]); // c= a x b //eq.20
renorm= .5 *(3 - Vector_Dot_Product(&temporary[0][0],&temporary[0][0])); //eq.21
Vector_Scale(&DCM_Matrix[0][0], &temporary[0][0], renorm);
renorm= .5 *(3 - Vector_Dot_Product(&temporary[1][0],&temporary[1][0])); //eq.21
Vector_Scale(&DCM_Matrix[1][0], &temporary[1][0], renorm);
renorm= .5 *(3 - Vector_Dot_Product(&temporary[2][0],&temporary[2][0])); //eq.21
Vector_Scale(&DCM_Matrix[2][0], &temporary[2][0], renorm);
}
/**************************************************/
void Drift_correction()
{
float mag_heading_x;
float mag_heading_y;
float errorCourse;
//Compensation the Roll, Pitch and Yaw drift.
static float Scaled_Omega_P[3];
static float Scaled_Omega_I[3];
float Accel_magnitude;
float Accel_weight;
//*****Roll and Pitch***************
// Calculate the magnitude of the accelerometer vector
Accel_magnitude = sqrt(Accel_Vector[0]*Accel_Vector[0] + Accel_Vector[1]*Accel_Vector[1] + Accel_Vector[2]*Accel_Vector[2]);
Accel_magnitude = Accel_magnitude / GRAVITY; // Scale to gravity.
// Dynamic weighting of accelerometer info (reliability filter)
// Weight for accelerometer info (<0.5G = 0.0, 1G = 1.0 , >1.5G = 0.0)
Accel_weight = constrain(1 - 2*abs(1 - Accel_magnitude),0,1); //
Vector_Cross_Product(&errorRollPitch[0],&Accel_Vector[0],&DCM_Matrix[2][0]); //adjust the ground of reference
Vector_Scale(&Omega_P[0],&errorRollPitch[0],Kp_ROLLPITCH*Accel_weight);
Vector_Scale(&Scaled_Omega_I[0],&errorRollPitch[0],Ki_ROLLPITCH*Accel_weight);
Vector_Add(Omega_I,Omega_I,Scaled_Omega_I);
//*****YAW***************
// We make the gyro YAW drift correction based on compass magnetic heading
mag_heading_x = cos(MAG_Heading);
mag_heading_y = sin(MAG_Heading);
errorCourse=(DCM_Matrix[0][0]*mag_heading_y) - (DCM_Matrix[1][0]*mag_heading_x); //Calculating YAW error
Vector_Scale(errorYaw,&DCM_Matrix[2][0],errorCourse); //Applys the yaw correction to the XYZ rotation of the aircraft, depeding the position.
Vector_Scale(&Scaled_Omega_P[0],&errorYaw[0],Kp_YAW);//.01proportional of YAW.
Vector_Add(Omega_P,Omega_P,Scaled_Omega_P);//Adding Proportional.
Vector_Scale(&Scaled_Omega_I[0],&errorYaw[0],Ki_YAW);//.00001Integrator
Vector_Add(Omega_I,Omega_I,Scaled_Omega_I);//adding integrator to the Omega_I
}
void Matrix_update()
{
Gyro_Vector[0]=GYRO_SCALED_RAD(TO_RAD(gyro[0])); //gyro x roll
Gyro_Vector[1]=GYRO_SCALED_RAD(TO_RAD(gyro[1])); //gyro y pitch
Gyro_Vector[2]=GYRO_SCALED_RAD(TO_RAD(gyro[2])); //gyro z yaw
Accel_Vector[0]=accel[0];
Accel_Vector[1]=accel[1];
Accel_Vector[2]=accel[2];
Vector_Add(&Omega[0], &Gyro_Vector[0], &Omega_I[0]); //adding proportional term
Vector_Add(&Omega_Vector[0], &Omega[0], &Omega_P[0]); //adding Integrator term
#if DEBUG__NO_DRIFT_CORRECTION == true // Do not use drift correction
Update_Matrix[0][0]=0;
Update_Matrix[0][1]=-G_Dt*Gyro_Vector[2];//-z
Update_Matrix[0][2]=G_Dt*Gyro_Vector[1];//y
Update_Matrix[1][0]=G_Dt*Gyro_Vector[2];//z
Update_Matrix[1][1]=0;
Update_Matrix[1][2]=-G_Dt*Gyro_Vector[0];
Update_Matrix[2][0]=-G_Dt*Gyro_Vector[1];
Update_Matrix[2][1]=G_Dt*Gyro_Vector[0];
Update_Matrix[2][2]=0;
#else // Use drift correction
Update_Matrix[0][0]=0;
Update_Matrix[0][1]=-G_Dt*Omega_Vector[2];//-z
Update_Matrix[0][2]=G_Dt*Omega_Vector[1];//y
Update_Matrix[1][0]=G_Dt*Omega_Vector[2];//z
Update_Matrix[1][1]=0;
Update_Matrix[1][2]=-G_Dt*Omega_Vector[0];//-x
Update_Matrix[2][0]=-G_Dt*Omega_Vector[1];//-y
Update_Matrix[2][1]=G_Dt*Omega_Vector[0];//x
Update_Matrix[2][2]=0;
#endif
Matrix_Multiply(DCM_Matrix,Update_Matrix,Temporary_Matrix); //a*b=c
for(int x=0; x<3; x++) //Matrix Addition (update)
{
for(int y=0; y<3; y++)
{
DCM_Matrix[x][y]+=Temporary_Matrix[x][y];
}
}
}
void Euler_angles()
{
pitch = -asin(DCM_Matrix[2][0]);
roll = atan2(DCM_Matrix[2][1],DCM_Matrix[2][2]);
yaw = atan2(DCM_Matrix[1][0],DCM_Matrix[0][0]);
}
| [
"rijad_alisic@msn.com"
] | rijad_alisic@msn.com |
144bf7c5a31f8a0328b4f8bd6b56e40387f94f8a | b967295eb531575eb39ef0b2f0d83c4297808fd8 | /packages/eigen-eigen-323c052e1731/bench/btl/actions/action_syr2.hh | e242e9eb6a9640cf0822e2906795e4c5f508ae54 | [
"MPL-2.0",
"Minpack",
"LGPL-2.1-only",
"BSD-3-Clause",
"GPL-3.0-only",
"LGPL-2.0-or-later",
"LGPL-2.1-or-later",
"GPL-2.0-only",
"Apache-2.0"
] | permissive | ai-techsystems/dnnc-operators | de9dc196db343003b6f3506dc0e502d59df2689f | 55e682c0318091c4ee87a8e67134a31042c393e1 | refs/heads/master | 2020-07-02T16:08:37.965213 | 2019-08-29T14:38:52 | 2019-08-29T14:38:52 | 201,582,638 | 5 | 7 | Apache-2.0 | 2019-09-06T18:31:19 | 2019-08-10T05:06:16 | C++ | UTF-8 | C++ | false | false | 3,797 | hh | //=====================================================
// File : action_syr2.hh
// Author : L. Plagne <laurent.plagne@edf.fr)>
// Copyright (C) EDF R&D, lun sep 30 14:23:19 CEST 2002
//=====================================================
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
#ifndef ACTION_SYR2
#define ACTION_SYR2
#include "utilities.h"
#include "STL_interface.hh"
#include <string>
#include "init/init_function.hh"
#include "init/init_vector.hh"
#include "init/init_matrix.hh"
using namespace std;
template<class Interface>
class Action_syr2 {
public :
// Ctor
BTL_DONT_INLINE Action_syr2( int size ):_size(size)
{
// STL matrix and vector initialization
typename Interface::stl_matrix tmp;
init_matrix<pseudo_random>(A_stl,_size);
init_vector<pseudo_random>(B_stl,_size);
init_vector<pseudo_random>(X_stl,_size);
init_vector<null_function>(resu_stl,_size);
// generic matrix and vector initialization
Interface::matrix_from_stl(A_ref,A_stl);
Interface::matrix_from_stl(A,A_stl);
Interface::vector_from_stl(B_ref,B_stl);
Interface::vector_from_stl(B,B_stl);
Interface::vector_from_stl(X_ref,X_stl);
Interface::vector_from_stl(X,X_stl);
}
// invalidate copy ctor
Action_syr2( const Action_syr2 & )
{
INFOS("illegal call to Action_syr2 Copy Ctor");
exit(1);
}
// Dtor
BTL_DONT_INLINE ~Action_syr2( void ){
Interface::free_matrix(A,_size);
Interface::free_vector(B);
Interface::free_vector(X);
Interface::free_matrix(A_ref,_size);
Interface::free_vector(B_ref);
Interface::free_vector(X_ref);
}
// action name
static inline std::string name( void )
{
return "syr2_" + Interface::name();
}
double nb_op_base( void ){
return 2.0*_size*_size;
}
BTL_DONT_INLINE void initialize( void ){
Interface::copy_matrix(A_ref,A,_size);
Interface::copy_vector(B_ref,B,_size);
Interface::copy_vector(X_ref,X,_size);
}
BTL_DONT_INLINE void calculate( void ) {
BTL_ASM_COMMENT("#begin syr2");
Interface::syr2(A,B,X,_size);
BTL_ASM_COMMENT("end syr2");
}
BTL_DONT_INLINE void check_result( void ){
// calculation check
Interface::vector_to_stl(X,resu_stl);
STL_interface<typename Interface::real_type>::syr2(A_stl,B_stl,X_stl,_size);
typename Interface::real_type error=
STL_interface<typename Interface::real_type>::norm_diff(X_stl,resu_stl);
if (error>1.e-3){
INFOS("WRONG CALCULATION...residual=" << error);
// exit(0);
}
}
private :
typename Interface::stl_matrix A_stl;
typename Interface::stl_vector B_stl;
typename Interface::stl_vector X_stl;
typename Interface::stl_vector resu_stl;
typename Interface::gene_matrix A_ref;
typename Interface::gene_vector B_ref;
typename Interface::gene_vector X_ref;
typename Interface::gene_matrix A;
typename Interface::gene_vector B;
typename Interface::gene_vector X;
int _size;
};
#endif
| [
"gunjan@localhost.localdomain"
] | gunjan@localhost.localdomain |
320e1a072b99e532dfc928cf01cb6507887eebaf | e5dad8e72f6c89011ae030f8076ac25c365f0b5f | /caret_files/NodeRegionOfInterestFile.h | 59091d2686432994e47eb8e2109c9e140c5a5656 | [] | no_license | djsperka/caret | f9a99dc5b88c4ab25edf8b1aa557fe51588c2652 | 153f8e334e0cbe37d14f78c52c935c074b796370 | refs/heads/master | 2023-07-15T19:34:16.565767 | 2020-03-07T00:29:29 | 2020-03-07T00:29:29 | 122,994,146 | 0 | 1 | null | 2018-02-26T16:06:03 | 2018-02-26T16:06:03 | null | UTF-8 | C++ | false | false | 2,683 | h |
#ifndef __NODE_REGION_OF_INTEREST_FILE_H__
#define __NODE_REGION_OF_INTEREST_FILE_H__
/*LICENSE_START*/
/*
* Copyright 1995-2002 Washington University School of Medicine
*
* http://brainmap.wustl.edu
*
* This file is part of CARET.
*
* CARET is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* CARET 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 CARET; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*LICENSE_END*/
#include "PaintFile.h"
class CoordinateFile;
class TopologyFile;
class VolumeFile;
/// class for storing the nodes in a region of interest
class NodeRegionOfInterestFile : public PaintFile {
public:
// constructor
NodeRegionOfInterestFile();
// destructor
~ NodeRegionOfInterestFile();
// set number of nodes
void setNumberOfNodes(const int numNodes);
// get node selected
bool getNodeSelected(const int nodeNumber) const;
// set node selected
void setNodeSelected(const int nodeNumber,
const bool status);
// get the ROI description
QString getRegionOfInterestDescription() const;
// set the ROI description (number of nodes must have been set)
void setRegionOfInterestDescription(const QString& s);
// assign nodes in ROI by intersecting with a volume file
void assignSelectedNodesWithVolumeFile(const VolumeFile* vf,
const CoordinateFile* cf,
const TopologyFile* tf) throw (FileException);
protected:
/// set the number of nodes and columns in the file
virtual void setNumberOfNodesAndColumns(const int numNodes,
const int numCols,
const int numElementsPerCol = 1);
/// paint name index for selected nodes
int selectedPaintIndex;
/// paint name index for deselected nodes;
int deselectedPaintIndex;
};
#endif // __NODE_REGION_OF_INTEREST_FILE_H__
| [
"michael.hanke@gmail.com"
] | michael.hanke@gmail.com |
91233ab31b7d5abed231d3625f8fe1fdf3894318 | 996126a2ed07ab381b625c92be916f2607804db1 | /プロジェクト/β版プロジェクト/ver.0.8/source/fade.cpp | 4b12086ccb63c49c5230448564b609d8ba98f317 | [] | no_license | ReiKishida/KishidaStudio_Front_Line | 10630cc57274b73d22d78639e7c53ae0c8a8dfc8 | 93694415975d032c27bd7d81a5d8ad2763c4687a | refs/heads/master | 2020-09-10T00:58:36.353818 | 2020-02-06T00:40:50 | 2020-02-06T00:40:50 | 221,608,377 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 4,525 | cpp | //=============================================================================
//
// フェード処理 [fade.cpp]
// Author : Takuto Ishida
//
//=============================================================================
#include "fade.h"
#include "input.h"
#include "renderer.h"
//*****************************************************************************
// マクロ定義
//*****************************************************************************
//*****************************************************************************
// 静的メンバ変数
//*****************************************************************************
CFade::FADE CFade::m_fade = CFade::FADE_NONE; // フェード状態
CManager::MODE CFade::m_modeNext = CManager::MODE_TITLE; // 次のモード
D3DXCOLOR CFade::m_colFade = D3DXCOLOR(0.0f, 0.0f, 0.0f, 0.0f); // フェード色
//=============================================================================
// フェードの生成
//=============================================================================
CFade *CFade::Create(CManager::MODE modeNext)
{
CFade *pFade = NULL;
if (pFade == NULL && m_fade == FADE_NONE)
{// フェードの状態が何もないときのみ生成される
pFade = new CFade;
if (pFade != NULL)
{
pFade->Init(); // 初期化処理
// 値の初期化
m_fade = FADE_OUT; // フェードアウト状態に
m_modeNext = modeNext; // 次のシーンを記憶
}
}
return pFade;
}
//=============================================================================
// コンストラクタ
//=============================================================================
CFade::CFade(int nPriority, CScene::OBJTYPE objType) : CScene2D(nPriority, objType)
{
m_fade = FADE_NONE;
m_colFade = D3DXCOLOR(0.0f, 0.0f, 0.0f, 0.0f);
}
//=============================================================================
// デストラクタ
//=============================================================================
CFade::~CFade()
{
}
//=============================================================================
// 初期化処理
//=============================================================================
HRESULT CFade::Init(void)
{
CScene2D::Init();
// 位置の設定
CScene2D::SetPos(D3DXVECTOR3(SCREEN_WIDTH / 2.0f, SCREEN_HEIGHT / 2.0f, 0.0f));
// 大きさの設定
CScene2D::SetSize(SCREEN_WIDTH, SCREEN_HEIGHT);
// 色の設定
m_colFade = D3DXCOLOR(0.0f, 0.0f, 0.0f, 0.0f);
CScene2D::SetColor(m_colFade);
return S_OK;
}
//=============================================================================
// 終了処理
//=============================================================================
void CFade::Uninit(void)
{
CScene2D::Uninit();
}
//=============================================================================
// 更新処理
//=============================================================================
void CFade::Update(void)
{
bool bDelete = false;
if (m_fade != FADE_NONE)
{// フェードの状態が何もしていないときはスルー
if (m_fade == FADE_IN) //フェードイン状態
{
m_colFade.a -= 0.02f; //画面を透明にしていく
if (m_colFade.a <= 0.0f)
{
m_colFade.a = 0.0f;
m_fade = FADE_NONE; //何もしていない状態
bDelete = true;
}
}
else if (m_fade == FADE_OUT)
{
m_colFade.a += 0.02f; //画面を不透明にしていく
if (m_colFade.a >= 1.0f)
{
m_colFade.a = 1.0f;
m_fade = FADE_IN; //フェードイン状態に
//モードの設定
CManager::SetMode(m_modeNext);
}
}
// 色の設定
CScene2D::SetColor(m_colFade);
if (bDelete == true)
{// 終わったフェードを消す
Uninit();
}
}
}
//=============================================================================
// 描画処理
//=============================================================================
void CFade::Draw(void)
{
// デバイスの取得
CRenderer *pRenderer = CManager::GetRenderer();
LPDIRECT3DDEVICE9 pDevice;
pDevice = pRenderer->GetDevice();
// Zテストを無効にする
pDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
pDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
pDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
CScene2D::Draw();
// Zテストを有効にする
pDevice->SetRenderState(D3DRS_ZENABLE, TRUE);
pDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
pDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_LESSEQUAL);
}
| [
"maguro2525@icloud.com"
] | maguro2525@icloud.com |
ea528a660a669fc6373c39f2ea86d0fcf195d383 | 5f375d135086f82d097ebf67ebf3cdd4d89030f5 | /HW_(C++)_1.3.cpp | 97ec82f5057f77b10653ff38d8e31a26e0e13851 | [] | no_license | nickky2010/C-plus-plus-HW1 | 4a8645e94e81397736d4d8293a3c0748bb29a590 | 8b31ad8f1ae47fd89953ef8e74cd16c6cde228fb | refs/heads/master | 2020-04-08T05:19:33.773732 | 2018-11-25T17:28:46 | 2018-11-25T17:28:46 | 159,056,043 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 6,390 | cpp | // Курс.Объектно - ориентированное программирование на C++.
// Модуль 1. Введение в объектно - ориентированное программирование.
// Домашнее задание №3.
// Задание 1.
// Разработать класс String, который в дальнейшем будет использоваться для работы со строками.Класс должен содержать :
// -Конструктор по умолчанию, позволяющий создать строку длиной 80 символов;
// -Конструктор, позволяющий создавать строку произвольного размера;
// -Конструктор, который создаёт строку и инициализирует её строкой, полученной от пользователя.
// Необходимо создать деструктор.
// Класс должен содержать методы для ввода строк с клавиатуры и вывода строк на экран.
// Также нужно реализовать статическую функцию - член, которая будет возвращать количество созданных объектов строк.
#include <stdio.h>
#include <conio.h>
#include <iostream>
#include <string.h>
#include <windows.h>
using namespace std;
class String
{
private:
char *str;
int N1 = 80, N2, N3;
public:
static int num_obj_str;
String() // конструктор по умолчанию
{
str = new char[N1+1];
num_obj_str++;
}
String(int n) // конструктор, позволяющий создавать строку произвольного размера
{
str = new char[n + 1];
num_obj_str++;
N2 = n+1;
}
String(const char *s) // конструктор, который создаёт строку и инициализирует её строкой, полученной от пользователя
{
N3 = strlen(s) + 1;
str = new char[N3];
strcpy(str, s);
num_obj_str++;
}
/*String(const String& ob) // конструктор копии
{
str = new char;
*str = *ob.str; // значение копии
int i = 0;
while (ob.str[i] != '\0') {
str[i] = ob.str[i];
i++;
}
str[i] = '\0';
num_obj_str++;
}*/
~String() // деструктор
{
delete str;
num_obj_str--;
}
void inter() // метод для ввода строк с клавиатуры по умолчанию
{
int i = 0;
char c;
while ((c = getchar()) != '\n') {
if (i < N1) {
str[i] = c;
i++;
}
}
str[i] = '\0';
}
void inter(int n) // метод для ввода строки произвольного размера с клавиатуры
{
int i = 0;
char c;
while (cin.get() != '\n');
while ((c = getchar()) != '\n') {
if (i < n) {
str[i] = c;
i++;
}
}
str[i] = '\0';
}
void show() // метод для вывода строки на экран
{
cout << str << endl;
}
static int show_Num_obj_str() // статическая функция-член, которая будет возвращать количество созданных объектов строк
{
return num_obj_str;
}
};
int String::num_obj_str = 0;
int main() {
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
cout << "Cоздаем 1 объект класса String...\n";
String s1; // создаем 1 объект класса String
cout << "Количество созданных объектов строк = " << s1.num_obj_str << endl << endl;
cout << "Метод для ввода строк с клавиатуры по умолчанию\n";
cout << "Введите строку с клавиатуры по умолчанию: \n";
s1.inter();
cout << "Строка с клавиатуры по умолчанию: \n";
s1.show();
puts("====================================================================================");
int n;
cout << "Cоздаем 2 объект класса String...\n";
cout << "Задайте размер строки: ";
cin >> n;
String s2(n); // создаем 2 объект класса String
cout << "Введите строку заданного размера: \n";
s2.inter(n);
cout << "Введенная строка произвольного размера: \n";
s2.show();
cout << "Количество созданных объектов строк = " << s2.num_obj_str << endl;
puts("====================================================================================");
cout << "Cоздаем 3 объект класса String...\n";
char st[100];
cout << "Введите строку: \n";
std::cin.getline (st, 101);
String s3(st); // создаем 3 объект класса String
cout << "\nCтрока введенная пользователем: \n";
s3.show();
cout << "Количество созданных объектов строк = " << s3.num_obj_str << endl;
/*puts("====================================================================================");
cout << "Cоздаем 4 объект класса String...\nКопируем строку 2 объекта в 4 объект...\n";
String s4 = s2;
cout << "Исходная строка 4 объекта:\n";
s4.show();
puts("====================================================================================");
cout << "Cоздаем 5 объект класса String...\nКопируем строку 3 объекта в 5 объект...\n";
String s5 = s3;
cout << "Исходная строка 5 объекта:\n";
s5.show();
cout << "Количество созданных объектов строк = " << s3.num_obj_str << endl << endl;*/
system("pause");
return 0;
}
| [
"nickky2010@mail.ru"
] | nickky2010@mail.ru |
0cc6f130058924753afbf0197477f0ccb6342dd4 | 7ce91a98ae434dbb48099699b0b6bcaa705ba693 | /TestModule/HK1/Users/20110337/BAI3.cpp | b73cc241c2b21fddb5ac43d1ad8c88968ce53ca0 | [] | no_license | ngthvan1612/OJCore | ea2e33c1310c71f9375f7c5cd0a7944b53a1d6bd | 3ec0752a56c6335967e5bb4c0617f876caabecd8 | refs/heads/master | 2023-04-25T19:41:17.050412 | 2021-05-12T05:29:40 | 2021-05-12T05:29:40 | 357,612,534 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 644 | cpp | #include<stdio.h>
int kiemTra(int A[], int n);
int cung_tinh_chan_le(int x, int y);
void nhapMang(int A[], int&n);
void xuat(int x);
void main()
{
int A[100],n;
nhapMang(A,n);
int kq = kiemTra(A,n);
xuat(kq);
}
int kiemTra(int A[], int n)
{
int kq;
int d = 0;
for(int i=0; i<n-1; i++)
{
if(cung_tinh_chan_le(A[i],A[i+1]))
{
d++;
kq = i + 1;
}
}
if(d==0)
kq = -1;
return kq;
}
int cung_tinh_chan_le(int x, int y)
{
if((x%2==0 && y%2==0) || (x%2==1 && y%2==1))
return 1;
return 0;
}
void nhapMang(int A[], int&n)
{
scanf("%d",&n);
for(int i=0; i<n; i++)
scanf("%d",&A[i]);
}
void xuat(int x)
{
printf("%d",x);
} | [
"Nguyen Van@DESKTOP-8HI58DE"
] | Nguyen Van@DESKTOP-8HI58DE |
8fc9c823fa86d251ffc5ac3e7e98b615f125a90d | 2c5c2baacaeb5baf187d9f8cd00c4066b0af3f5f | /chatting/dao.cpp | 8bf73493b352aabdfcf3691a307ba384f3f721bc | [
"MIT"
] | permissive | blacknickwield/chatting-server | 276fe0f072b9d2fdc75f6aec68bc5152c9b3cf13 | 64bb3823d6fd6ece4e0b3af9f47be922de446e94 | refs/heads/main | 2023-07-16T09:06:52.321455 | 2021-09-11T08:06:21 | 2021-09-11T08:06:21 | 405,316,515 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,283 | cpp | #include "dao.h"
#include <QSqlQuery>
#include <QVariant>
#include <QDebug>
Dao* Dao::database = nullptr;
Dao::Dao()
{
db = QSqlDatabase::addDatabase(driverName);
db.setHostName(hostName);
db.setDatabaseName(databaseName);
db.setUserName(userName);
db.setPassword(userPassword);
db.setPort(port);
if (db.open()) {}
// qDebug() << "db ok";
else {
// qDebug() << "db no";
}
}
Dao* Dao::getInstance()
{
if (database == nullptr)
{
database = new Dao();
}
return database;
}
User* Dao::getUserByAccountAndPassword(QString account, QString password)
{
QSqlQuery query;
query.prepare("SELECT * FROM user WHERE account =:account AND password =:password");
query.bindValue(":account", QVariant(account));
query.bindValue(":password", QVariant(password));
query.exec();
while (query.next()) {
QString _account = query.value("account").toString();
QString _password = query.value("password").toString();
if (_account == account && _password == password)
return new User(query.value("id").toInt(),
account,
query.value("name").toString(),
password,
query.value("email").toString(),
query.value("gender").toString());
}
return nullptr;
}
User* Dao::getUserById(int id)
{
QSqlQuery query;
query.prepare("SELECT * FROM user WHERE id =:id");
query.bindValue(":id", QVariant(id));
query.exec();
if (query.next())
return new User(id,
query.value("account").toString(),
query.value("name").toString(),
1);
return nullptr;
}
QList<User*> Dao::getAllUsers()
{
QSqlQuery query;
query.exec("SELECT * FROM user");
QList<User*> result;
while (query.next())
result.append(new User(query.value("id").toInt(),
query.value("account").toString(),
query.value("name").toString(),
query.value("password").toString(),
query.value("email").toString(),
query.value("gender").toString()));
return result;
}
QList<User*> Dao::getFriendUserById(int id)
{
QList<User*> result;
QSqlQuery query;
query.prepare("SELECT * FROM friendship, user WHERE (friendship.uid = user.id AND friendship.fid =:id) OR (friendship.fid = user.id AND friendship.uid =:id)");
query.bindValue(":id", QVariant(id));
query.exec();
while (query.next()) {
result.append(new User(query.value("user.id").toInt(),
query.value("user.account").toString(),
query.value("user.name").toString(),
query.value("user.password").toString(),
query.value("user.email").toString(),
query.value("user.gender").toString()));
}
return result;
}
bool Dao::addNewUser(QString account, QString name, QString password, QString email, QString gender)
{
QSqlQuery query;
QString sql = QString("INSERT INTO user (account, name, password, email, gender) VALUES('%1', '%2', '%3', '%4', '%5')")
.arg(account)
.arg(name)
.arg(password)
.arg(email)
.arg(gender);
bool result = query.exec(sql);
return result;
}
bool Dao::saveChatLog(int senderId, int recevierId, QString content, QString sendTime)
{
QSqlQuery query;
QString sql = QString("INSERT INTO chatlog (senderId, recevierId, content, sendTime) VALUES('%1', '%2', '%3', '%4')")
.arg(senderId)
.arg(recevierId)
.arg(content)
.arg(sendTime);
bool result = query.exec(sql);
return result;
}
QList<ChatLog*> Dao::getChatLogByIds(int id1, int id2)
{
QList<ChatLog*> result;
QSqlQuery query;
query.prepare("SELECT * FROM chatlog WHERE (senderId =:id1 AND recevierId =:id2) OR (senderId =:id2 AND recevierId =:id1) ORDER BY sendTime");
query.bindValue(":id1", QVariant(id1));
query.bindValue(":id2", QVariant(id2));
query.exec();
while (query.next()) {
result.append(new ChatLog(query.value("id").toInt(),
query.value("senderId").toInt(),
query.value("recevierId").toInt(),
query.value("content").toString(),
query.value("sendTime").toString()));
}
return result;
}
bool Dao::addNewFriendShip(int uid, int fid)
{
QSqlQuery query;
QString sql = QString("INSERT INTO friendship (uid, fid) VALUES('%1', '%2')")
.arg(uid)
.arg(fid);
bool result = query.exec(sql);
return result;
}
bool Dao::deleteFriendship(int uid, int fid)
{
QSqlQuery query;
query.prepare("DELETE FROM friendship WHERE (uid =:uid AND fid=:fid) OR (uid =:fid AND fid =:uid)");
query.bindValue(":uid", QVariant(uid));
query.bindValue(":fid", QVariant(fid));
bool result = query.exec();
return result;
}
QList<int> Dao::getGroupIdByUserId(int userId)
{
QList<int> result;
QSqlQuery query;
query.prepare("SELECT * FROM grouprelationship WHERE userId =:userId");
query.bindValue(":userId", QVariant(userId));
query.exec();
while (query.next()) {
result.append(query.value("groupId").toInt());
}
return result;
}
QList<int> Dao::getGroupUserIdsByGroupId(int groupId)
{
QList<int> result;
QSqlQuery query;
query.prepare("SELECT * FROM grouprelationship WHERE groupId =:groupId");
query.bindValue(":groupId", QVariant(groupId));
query.exec();
while (query.next()) {
result.append(query.value("userId").toInt());
}
return result;
}
QString Dao::getGroupNameByGroupId(int groupId)
{
QSqlQuery query;
query.prepare("SELECT * FROM groupchat WHERE id =:groupId");
query.bindValue(":groupId", QVariant(groupId));
query.exec();
if (query.next())
return query.value("name").toString();
return nullptr;
}
| [
"blacknick123@163.com"
] | blacknick123@163.com |
d30832d1e6840e4e31c0d7d2596d334c8281d02a | dd97857a1e3ac34d48d1b980ede38771f6544259 | /finalProject/src/menu/mainMenu.cpp | 09e552a0c591a2cdfd2fdcc46684785da7b8e9c4 | [] | no_license | Scc33/Jumper | 8750c5c5529de9179c18d166877ad4e04bb685c2 | 063dba00bcfe5728ebe93b78141c43745b1c99ae | refs/heads/master | 2022-11-11T17:46:54.809225 | 2020-07-02T00:50:24 | 2020-07-02T00:50:24 | 276,139,109 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,691 | cpp | #include "mainMenu.hpp"
mainMenu::mainMenu() {
posX = 1;
posY = 1;
velX = ofRandom(0.1,0.5);
velY = ofRandom(0.1,0.5);
player.setPlayer(posX, posY, cellSize);
}
void mainMenu::setMainMenu(int setGameCols, int setGameRows, int setCellSize) {
gameCols = setGameCols;
gameRows = setGameRows;
cellSize = setCellSize;
}
void mainMenu::setMainMenuPlayer(Player &setPlayer) {
player = setPlayer;
}
void mainMenu::runStartMenu() {
posX += velX;
posY += velY;
//Bounces the player around the screen
if (posX < 1) {
posX = 1;
velX *= -1;
} else if (posX > gameCols - 2) {
posX = gameCols - 2;
velX *= -1;
}
if (posY < 1) {
posY = 1;
velY *= -1;
} else if (posY > gameRows - 4){
posY = gameRows - 4;
velY *= -1;
}
player.updatePlayerLocation(posX, posY);
startGameButton->update();
marketButton->update();
settingsButton->update();
highScoreButton->update();
exitButton->update();
loader::ReadMoney(moneyFileLoc, totalMoney);
}
void mainMenu::drawStartMenu() {
player.drawPlayer();
startGameButton->draw();
marketButton->draw();
settingsButton->draw();
highScoreButton->draw();
exitButton->draw();
ofSetColor(255,255,255);
ofDrawBitmapString("Your total money is " + ofToString(totalMoney), ofGetWidth() * 4 / 5, ofGetHeight() / 10);
}
void mainMenu::onButtonEvent(ofxDatGuiButtonEvent e) {
if (e.target == startGameButton) {
startMenuRunning = false;
gameRunning = true;
} else if (e.target == marketButton) {
startMenuRunning = false;
marketMenuRunning = true;
} else if (e.target == settingsButton) {
startMenuRunning = false;
settingsRunning = true;
} else if (e.target == highScoreButton) {
startMenuRunning = false;
hScoreMenuRunning = true;
} else if (e.target == exitButton) {
ofExit();
}
}
//Position the buttons in the middle of the screen and register to listen for events
void mainMenu::setupButtons() {
startGameButton = new ofxDatGuiButton("Start");
marketButton = new ofxDatGuiButton("Market");
settingsButton = new ofxDatGuiButton("Settings");
highScoreButton = new ofxDatGuiButton("High Scores");
exitButton = new ofxDatGuiButton("Exit");
startGameButton->onButtonEvent(this, &mainMenu::onButtonEvent);
marketButton->onButtonEvent(this, &mainMenu::onButtonEvent);
settingsButton->onButtonEvent(this, &mainMenu::onButtonEvent);
highScoreButton->onButtonEvent(this, &mainMenu::onButtonEvent);
exitButton->onButtonEvent(this, &mainMenu::onButtonEvent);
startGameButton->setPosition(ofGetWidth()/2 - settingsButton->getWidth()/2, ofGetHeight()/2 - 90);
marketButton->setPosition(startGameButton->getX(), startGameButton->getY() + 45);
settingsButton->setPosition(startGameButton->getX(), startGameButton->getY() + 90);
highScoreButton->setPosition(startGameButton->getX(), startGameButton->getY() + 135);
exitButton->setPosition(startGameButton->getX(), startGameButton->getY() + 180);
const ofxDatGuiGameTheme *gameTheme = new ofxDatGuiGameTheme(16);
startGameButton->setTheme(gameTheme);
marketButton->setTheme(gameTheme);
settingsButton->setTheme(gameTheme);
highScoreButton->setTheme(gameTheme);
exitButton->setTheme(gameTheme);
}
int mainMenu::getCols() const {
return gameCols;
}
int mainMenu::getRows() const {
return gameRows;
}
int mainMenu::getPosX() const {
return posX;
}
int mainMenu::getPosY() const {
return posY;
}
| [
"seanmc4@illinois.edu"
] | seanmc4@illinois.edu |
6ce9af8da865d384e66e9a0ca164322201ee9952 | 80600ab15fd4d3a4adaf1ae31c845660f34ce033 | /core/camera/Camera.h | 32c9d57c0fe132833f73ef65b3b3a5cef3c89765 | [] | no_license | perandersson/playstate2 | abc208478967f4388cd4cbee2c2d5cd6e9994395 | 46d5ae8fa8324b32aa97e64a7ca46024f4bc2cdf | refs/heads/master | 2021-01-19T07:54:13.417455 | 2015-01-07T17:01:06 | 2015-01-07T17:01:06 | 21,142,283 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,280 | h | #pragma once
#include "Frustum.h"
#include "../math/Matrix4x4.h"
#include "../script/ScriptObject.h"
namespace core
{
//
//
class Camera : public ScriptObject
{
DECLARE_SCRIPT_OBJECT(Camera);
public:
Camera();
Camera(const Camera& camera);
virtual ~Camera();
void SetPerspective(float32 near, float32 far, float32 fov, float32 ratio);
void SetOrtho2D(float32 left, float32 right, float32 bottom, float32 top);
void Move(const Vector3& direction);
void LookAt(const Vector3& eye, const Vector3& center, const Vector3& up);
/*!
\brief Retrieves the camera's view frustum
\return The camera's view frustum
*/
inline const Frustum* GetFrustum() const {
return &mFrustum;
}
/*!
\brief Retrieves the camera's view matrix
\return This camera's view matrix
*/
inline const Matrix4x4& GetViewMatrix() const {
return mViewMatrix;
}
/*!
\brief Retrieves the camera's projection matrix
\return This camera's projection matrix
*/
inline const Matrix4x4& GetProjectionMatrix() const {
return mProjectionMatrix;
}
/*!
\brief Retreives the projection view matrix
\return The projection view matrix
*/
inline Matrix4x4 GetProjectionViewMatrix() const {
return mProjectionMatrix * mViewMatrix;
}
/*!
\brief Retrieves the camera's position
*/
inline const Vector3& GetPosition() const {
return mPosition;
}
/*!
\brief Retrieves the up vector for the camera
*/
inline const Vector3& GetUp() const {
return mUp;
}
/*!
\brief Retrieves the position where this camera is focusing on
*/
inline const Vector3& GetCenter() const {
return mCenter;
}
/*!
\brief Retrieves the near clip distance
*/
inline float32 GetNearClipDistance() const {
return mNearPlane;
}
/*!
\brief Retrieves the far clip distance
*/
inline float32 GetFarClipDistance() const {
return mFarPlane;
}
/*!
\brief Retrieves the view direction
*/
inline const Vector3& GetViewDirection() const {
return mViewDirection;
}
private:
Frustum mFrustum;
Matrix4x4 mViewMatrix;
Matrix4x4 mProjectionMatrix;
Vector3 mPosition;
Vector3 mCenter;
Vector3 mUp;
float32 mNearPlane;
float32 mFarPlane;
Vector3 mViewDirection;
};
}
| [
"dim.raven@gmail.com"
] | dim.raven@gmail.com |
5962587e59790a50b423509f10e1b017370c64e6 | f6c11d71f88eee3e7cb3486436e407b806e8df24 | /ImageFlip2D/main0.cxx | dcef9c79b6af0d8cd5854dea0a49db0244263cce | [] | no_license | midmelody/ToolsITK | 7778f459ddea4e113d5f3eb7eef4ff8d8ea73179 | e627d6bde94e0a6e9f8b382261437ea00af6ea7d | refs/heads/master | 2020-04-18T00:16:59.913186 | 2019-04-12T13:37:39 | 2019-04-12T13:37:39 | 167,070,815 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,580 | cxx | #include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkResampleImageFilter.h"
#include "itkAffineTransform.h"
#include "itkImageFileWriter.h"
#include <iostream>
#include "math.h"
#include "string.h"
int main( int argc, char * argv[] )
{
if( argc < 5 )
{
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " inputImageFile outputImageFile degree" << std::endl;
return EXIT_FAILURE;
}
//ITK settings
const unsigned int Dimension = 2;
typedef unsigned char PixelType;
typedef itk::Image< PixelType, Dimension > ImageType;
typedef itk::ImageFileReader< ImageType > ReaderType;
typedef itk::FlipImageFilter<ImageType> FlipImageFilterType;
typedef itk::AffineTransform< double, Dimension > TransformType;
typedef itk::LinearInterpolateImageFunction< ImageType, double > InterpolatorType;
typedef itk::ResampleImageFilter<ImageType, ImageType> FilterType;
typedef itk::ImageFileWriter< ImageType > WriterType;
//Filters
ReaderType::Pointer reader = ReaderType::New();
FlipImageFilterType::Pointer flipFilter = FlipImageFilterType::New();
FilterType::Pointer filter = FilterType::New();
TransformType::Pointer transform = TransformType::New();
InterpolatorType::Pointer interpolator = InterpolatorType::New();
WriterType::Pointer writer = WriterType::New();
//Parameters
reader->SetFileName( argv[1] );
writer->SetFileName( argv[2] );
filter->SetInterpolator( interpolator );
filter->SetDefaultPixelValue( 0 );
//Pipeline
reader->Update();
//Flip version
FlipImageFilterType::FlipAxesArrayType flipAxes;
flipAxes[0] = true;
flipAxes[1] = false;
flipFilter->SetInput(reader->GetOutput());
flipFilter->SetFlipAxes(flipAxes);
flipFilter->Update();
int i,j;
int degree[15] = {30,45,60,90,120,135,150,180,210,225,240,270,300,315,330};
ImageType::Pointer inputImage = ImageType::New();
ImageType::Pointer outputImage = ImageType::New();
char filename[100];
for(i=0;i<2;i++)
{
if(i==0)
inputImage = reader->GetOutput();
else
inputImage = flipFilter->GetOutput();
ImageType::SpacingType spacing = inputImage->GetSpacing();
ImageType::PointType origin = inputImage->GetOrigin();
ImageType::SizeType size = inputImage->GetLargestPossibleRegion().GetSize();
filter->SetOutputOrigin( origin );
filter->SetOutputSpacing( spacing );
filter->SetOutputDirection( inputImage->GetDirection() );
filter->SetSize( size );
double imageCenterX = origin[0] + spacing[0] * size[0] / 2.0;
double imageCenterY = origin[1] + spacing[1] * size[1] / 2.0;
for(j=0;j<15;j++)
{
//std::cout<<degree[j]<<""<<imageCenterX<<""<<imageCenterY<<std::endl;
filter->SetInput(inputImage);
TransformType::OutputVectorType translation1;
translation1[0] = -imageCenterX;
translation1[1] = -imageCenterY;
transform->Translate( translation1 );
const double degreesToRadians = std::atan(1.0) / 45.0;
const double angle = degree[j] * degreesToRadians;
transform->Rotate2D( -angle, false );
TransformType::OutputVectorType translation2;
translation2[0] = imageCenterX;
translation2[1] = imageCenterY;
transform->Translate( translation2, false );
filter->SetTransform( transform );
outputImage = filter->GetOutput();
sprintf(filename, "%s_%d_%d.hdr", argv[1], i, j);
writer->SetFileName( filename );
writer->SetInput( outputImage );
writer->Update();
//outputImage->DisconnectPipeline();
}
}
return EXIT_SUCCESS;
}
| [
"ziyuex@nvidia.com"
] | ziyuex@nvidia.com |
72b3ee5ac159c1a37774b9a2e6c1e9988dfadb31 | 960ef14b9b9fb3c2a94757501a982298432104a6 | /reservation.cpp | 108b3f654a84c53b4116a9bbb3294e7260b7bab6 | [] | no_license | powtaytwo/128Final | 65a91df24ef525f99e074c0a416b84b535d673cf | 954f49229e96497027ce7ae7b209308f73713377 | refs/heads/master | 2020-04-08T05:28:49.500878 | 2018-12-13T04:15:04 | 2018-12-13T04:15:04 | 159,062,142 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,212 | cpp | #include "login.h"
#include "reservation.h"
#include "ui_reservation.h"
#include <QMessageBox>
#include <status.h>
#include <main_interface.h>
#include <QSqlDatabase>
#include <QSqlDriver>
#include <QSqlError>
#include <QtSql>
#include <QtDebug>
#include <QSqlQuery>
#include <QMessageBox>
#include <QString>
Reservation::Reservation(QWidget *parent) :
QDialog(parent),
ui(new Ui::Reservation)
{
ui->setupUi(this);
QPixmap bkgnd("C:/Users/Lilian C/Documents/qtworkspace/128v3/128v03/images/wait.jpg");
bkgnd = bkgnd.scaled(this->size(), Qt::IgnoreAspectRatio);
QPalette palette;
palette.setBrush(QPalette::Background, bkgnd);
this->setPalette(palette);
QString one = "lcdNumber";
QString two = "lcdNumber_2";
lCDNumber2 = Reservation::findChild<QLCDNumber *>(one);
lCDNumber3 = Reservation::findChild<QLCDNumber *>(two);
updatetimer = new QTimer(this);
initial();
connect(updatetimer, SIGNAL(timeout()), this, SLOT(update()));
}
Reservation::~Reservation()
{
delete ui;
}
void Reservation::status(){
QSqlQuery qry;
QString user, spot;
qry.prepare("select user_ID from User where user_status = 1");
qry.exec();
qry.next();
user = qry.value(0).toString();
qry.prepare("select spot_ID from Orderr where user_ID = '"+user+"' ");
qry.exec();
qry.next();
spot = qry.value(0).toString();
qry.exec("update Spot set spot_status = 1 where spot_ID = '"+spot+"' ");
qry.exec("update User set user_stat = 1 where user_ID = '"+user+"' ");
hide();
Status a;
a.setModal(true);
a.setWindowTitle("Status Page");
a.exec();
}
void Reservation::initial()
{
updatetimer->start(1000);
mcount = 19;
scount = 59;
lCDNumber2->display(mcount);
lCDNumber3->display(scount);
}
void Reservation::update()
{
scount--;
if(scount<0) {
scount = 59;
mcount--;
}
if(mcount<0) {
mcount = 59;
}
if(scount == 0 && mcount == 0){
status();
}
lCDNumber2->display(mcount);
lCDNumber3->display(scount);
}
void Reservation::on_pushButton_clicked() //GO
{
QMessageBox::StandardButton reply = QMessageBox::question(this, "Start Time? ",
"Are you ready to start the time? <br> Pressing YES would redirect you to the Status Page <br> Reservation fee is 10 pesos", QMessageBox::Yes | QMessageBox::No);
if(reply == QMessageBox::Yes){
status();
}
}
void Reservation::on_pushButton_2_clicked() //CANCEL
{
QMessageBox::StandardButton reply = QMessageBox::question(this, "Cancel Order? ",
"Are you sure you want to cancel your order? <br> Pressing NO would redirect you to your Profile Page. <br> Reservation fee of 10 pesos will be deducted from your account.", QMessageBox::Yes | QMessageBox::No);
if(reply == QMessageBox::Yes){
QSqlQuery qry;
QString user, spot, order, money;
int c = 0;
qry.prepare("select user_ID from User where user_status = 1");
qry.exec();
qry.next();
user = qry.value(0).toString();
qry.prepare("select credit from User where user_status = 1");
qry.exec();
qry.next();
c = qry.value(0).toInt();
c = c - 10;
money = QString::number(c);
qry.prepare("select spot_ID from Orderr where user_ID = '"+user+"' ");
qry.exec();
qry.next();
spot = qry.value(0).toString();
qry.prepare("select order_ID from Orderr where user_ID = '"+user+"' ");
qry.exec();
qry.next();
order = qry.value(0).toString();
qry.exec("update Spot set spot_status = 0 where spot_ID = '"+spot+"' "); //Vacant the spot
qry.exec("update User set credit = '"+money+"' where user_ID = '"+user+"' "); //decrease user's money
qry.exec("DELETE FROM Orderr WHERE order_ID = '"+order+"' ");
hide();
main_interface a;
a.setModal(true);
a.setWindowTitle("Profile Page");
a.exec();
}
}
| [
"noreply@github.com"
] | powtaytwo.noreply@github.com |
a5de87631f6dfb3b9e1b31f14527bfd6ae4439b8 | a6bfdf4d2dd1ea4ae285215c651c2b64479b6b6a | /bench/function/scalar/exp10.cpp | b513e131ef75e29c422f63d90fd066db7fd6b637 | [
"BSL-1.0"
] | permissive | jeffamstutz/boost.simd | fb62210c30680c3cb2ffcc8ed80f8a0050f675fd | 8afe9673c2a806976a77bc8bbca4cb1116a710cb | refs/heads/develop | 2021-01-13T04:06:02.762442 | 2017-01-05T02:56:52 | 2017-01-06T16:11:47 | 77,879,665 | 6 | 1 | null | 2017-01-03T03:08:57 | 2017-01-03T03:08:57 | null | UTF-8 | C++ | false | false | 748 | cpp | // -------------------------------------------------------------------------------------------------
// Copyright 2016 - NumScale SAS
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
// -------------------------------------------------------------------------------------------------
#include <simd_bench.hpp>
#include <boost/simd/function/simd/exp10.hpp>
namespace nsb = ns::bench;
namespace bs = boost::simd;
DEFINE_SCALAR_BENCH(scalar_exp10, bs::exp10);
DEFINE_BENCH_MAIN()
{
nsb::for_each<scalar_exp10, NS_BENCH_IEEE_TYPES>(-10, 10);
}
| [
"jtlapreste@gmail.com"
] | jtlapreste@gmail.com |
04ce9afe9675c068990139fa6e68ca25573dafa6 | ad3d54c195b1677339dab66d21753f18b19a4dfc | /acm/school1/acm305.cpp | 52a9dd29e26de77da197580cd7ef7200afb8e4c4 | [] | no_license | kylin0925/online_judge | 83e18dd3420a60a89984468ed3cf28f4041744c4 | 27ee1781dbacb702589c1775596bec03344018cd | refs/heads/master | 2021-11-24T00:04:44.648369 | 2021-11-21T07:17:13 | 2021-11-21T07:17:13 | 25,734,715 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 876 | cpp | /* @JUDGE_ID: 53xxxx 305 C++ */
#include <stdio.h>
int k;
int j[13]={0};
int test(int c)
{
int pos=c%(k*2)-1,wk=k;
int i,arr[30],len=k*2;
for(i=0;i<k*2;i++)
{
arr[i]=i+1;
}
while(wk>0)
{
if(pos<k) return 0;
for(i=pos+1;i<k*2;i++)
{
arr[i-1]=arr[i];
}
wk--;
len--;
pos=(pos+c-1)%len;
}
return 1;
}
int main(int argc, char* argv[])
{
int i;
while(1)
{
scanf("%d",&k);
if(k==0)
{
break;
}
if(k==1)
{
printf("2\n");
}
else if(j[k-1]>0)
{
printf("%d\n",j[k-1]);
}
else
{
for(i=k;;i++)
{
if(test(i)) break;
}
printf("%d\n",i);
j[k-1]=i;
}
}
return 0;
}
| [
"kylin@appleteki-imac.(none)"
] | kylin@appleteki-imac.(none) |
5a4cb650a1bdac13c18eb2a694f43fdd1b4e11a5 | b9bb0581b888788c1cb6744078fde0d43ee0bb50 | /main.cpp | 6b89a31c7e6a8c664cb6ec48bfa068d68ea304e5 | [] | no_license | Yasteer/Retro_Game---Asteroid-Destroyer | 9d7e6af8cbe12b35b797984d2d97541651de960c | 263a033de5077ba9693514de24423a0873bac655 | refs/heads/master | 2022-11-29T18:11:03.642284 | 2020-08-01T16:40:06 | 2020-08-01T16:40:06 | 277,209,677 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 510 | cpp | // Will link to lib files dynamically. This will save space on the .exe file and prevent the user from having to recompile
// in the event that the libraries are updated from the 3rd party.
// Will use composition as opposed to inheritence. Inheritence is designed to reuse code but composition is better suited to
// acheiving polymorhism.
#include "Splash_Screen.h"
#include "Run_Game.h"
int main()
{
Splash_Screen Begin;
Run_Game New_Game;
New_Game.Run();
return 0;
}
| [
"noreply@github.com"
] | Yasteer.noreply@github.com |
79ead73de2b2aeb146a083ff0fe23acf31903b68 | 71501709864eff17c873abbb97ffabbeba4cb5e3 | /llvm12.0.1/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp | fab13cdbfe9f46cf41764f219886f70895da8635 | [
"Apache-2.0",
"LLVM-exception",
"NCSA"
] | permissive | LEA0317/LLVM-VideoCore4 | d08ba6e6f26f7893709d3285bdbd67442b3e1651 | 7ae2304339760685e8b5556aacc7e9eee91de05c | refs/heads/master | 2022-06-22T15:15:52.112867 | 2022-06-09T08:45:24 | 2022-06-09T08:45:24 | 189,765,789 | 1 | 0 | NOASSERTION | 2019-06-01T18:31:29 | 2019-06-01T18:31:29 | null | UTF-8 | C++ | false | false | 16,827 | cpp | //===--- UseAutoCheck.cpp - clang-tidy-------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "UseAutoCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Tooling/FixIt.h"
using namespace clang;
using namespace clang::ast_matchers;
using namespace clang::ast_matchers::internal;
namespace clang {
namespace tidy {
namespace modernize {
namespace {
const char IteratorDeclStmtId[] = "iterator_decl";
const char DeclWithNewId[] = "decl_new";
const char DeclWithCastId[] = "decl_cast";
const char DeclWithTemplateCastId[] = "decl_template";
size_t GetTypeNameLength(bool RemoveStars, StringRef Text) {
enum CharType { Space, Alpha, Punctuation };
CharType LastChar = Space, BeforeSpace = Punctuation;
size_t NumChars = 0;
int TemplateTypenameCntr = 0;
for (const unsigned char C : Text) {
if (C == '<')
++TemplateTypenameCntr;
else if (C == '>')
--TemplateTypenameCntr;
const CharType NextChar =
isAlphanumeric(C)
? Alpha
: (isWhitespace(C) ||
(!RemoveStars && TemplateTypenameCntr == 0 && C == '*'))
? Space
: Punctuation;
if (NextChar != Space) {
++NumChars; // Count the non-space character.
if (LastChar == Space && NextChar == Alpha && BeforeSpace == Alpha)
++NumChars; // Count a single space character between two words.
BeforeSpace = NextChar;
}
LastChar = NextChar;
}
return NumChars;
}
/// Matches variable declarations that have explicit initializers that
/// are not initializer lists.
///
/// Given
/// \code
/// iterator I = Container.begin();
/// MyType A(42);
/// MyType B{2};
/// MyType C;
/// \endcode
///
/// varDecl(hasWrittenNonListInitializer()) maches \c I and \c A but not \c B
/// or \c C.
AST_MATCHER(VarDecl, hasWrittenNonListInitializer) {
const Expr *Init = Node.getAnyInitializer();
if (!Init)
return false;
Init = Init->IgnoreImplicit();
// The following test is based on DeclPrinter::VisitVarDecl() to find if an
// initializer is implicit or not.
if (const auto *Construct = dyn_cast<CXXConstructExpr>(Init)) {
return !Construct->isListInitialization() && Construct->getNumArgs() > 0 &&
!Construct->getArg(0)->isDefaultArgument();
}
return Node.getInitStyle() != VarDecl::ListInit;
}
/// Matches QualTypes that are type sugar for QualTypes that match \c
/// SugarMatcher.
///
/// Given
/// \code
/// class C {};
/// typedef C my_type;
/// typedef my_type my_other_type;
/// \endcode
///
/// qualType(isSugarFor(recordType(hasDeclaration(namedDecl(hasName("C"))))))
/// matches \c my_type and \c my_other_type.
AST_MATCHER_P(QualType, isSugarFor, Matcher<QualType>, SugarMatcher) {
QualType QT = Node;
while (true) {
if (SugarMatcher.matches(QT, Finder, Builder))
return true;
QualType NewQT = QT.getSingleStepDesugaredType(Finder->getASTContext());
if (NewQT == QT)
return false;
QT = NewQT;
}
}
/// Matches named declarations that have one of the standard iterator
/// names: iterator, reverse_iterator, const_iterator, const_reverse_iterator.
///
/// Given
/// \code
/// iterator I;
/// const_iterator CI;
/// \endcode
///
/// namedDecl(hasStdIteratorName()) matches \c I and \c CI.
Matcher<NamedDecl> hasStdIteratorName() {
static const StringRef IteratorNames[] = {"iterator", "reverse_iterator",
"const_iterator",
"const_reverse_iterator"};
return hasAnyName(IteratorNames);
}
/// Matches named declarations that have one of the standard container
/// names.
///
/// Given
/// \code
/// class vector {};
/// class forward_list {};
/// class my_ver{};
/// \endcode
///
/// recordDecl(hasStdContainerName()) matches \c vector and \c forward_list
/// but not \c my_vec.
Matcher<NamedDecl> hasStdContainerName() {
static StringRef ContainerNames[] = {"array", "deque",
"forward_list", "list",
"vector",
"map", "multimap",
"set", "multiset",
"unordered_map", "unordered_multimap",
"unordered_set", "unordered_multiset",
"queue", "priority_queue",
"stack"};
return hasAnyName(ContainerNames);
}
/// Matches declaration reference or member expressions with explicit template
/// arguments.
AST_POLYMORPHIC_MATCHER(hasExplicitTemplateArgs,
AST_POLYMORPHIC_SUPPORTED_TYPES(DeclRefExpr,
MemberExpr)) {
return Node.hasExplicitTemplateArgs();
}
/// Returns a DeclarationMatcher that matches standard iterators nested
/// inside records with a standard container name.
DeclarationMatcher standardIterator() {
return decl(
namedDecl(hasStdIteratorName()),
hasDeclContext(recordDecl(hasStdContainerName(), isInStdNamespace())));
}
/// Returns a TypeMatcher that matches typedefs for standard iterators
/// inside records with a standard container name.
TypeMatcher typedefIterator() {
return typedefType(hasDeclaration(standardIterator()));
}
/// Returns a TypeMatcher that matches records named for standard
/// iterators nested inside records named for standard containers.
TypeMatcher nestedIterator() {
return recordType(hasDeclaration(standardIterator()));
}
/// Returns a TypeMatcher that matches types declared with using
/// declarations and which name standard iterators for standard containers.
TypeMatcher iteratorFromUsingDeclaration() {
auto HasIteratorDecl = hasDeclaration(namedDecl(hasStdIteratorName()));
// Types resulting from using declarations are represented by elaboratedType.
return elaboratedType(
// Unwrap the nested name specifier to test for one of the standard
// containers.
hasQualifier(specifiesType(templateSpecializationType(hasDeclaration(
namedDecl(hasStdContainerName(), isInStdNamespace()))))),
// the named type is what comes after the final '::' in the type. It
// should name one of the standard iterator names.
namesType(
anyOf(typedefType(HasIteratorDecl), recordType(HasIteratorDecl))));
}
/// This matcher returns declaration statements that contain variable
/// declarations with written non-list initializer for standard iterators.
StatementMatcher makeIteratorDeclMatcher() {
return declStmt(unless(has(
varDecl(anyOf(unless(hasWrittenNonListInitializer()),
unless(hasType(isSugarFor(anyOf(
typedefIterator(), nestedIterator(),
iteratorFromUsingDeclaration())))))))))
.bind(IteratorDeclStmtId);
}
StatementMatcher makeDeclWithNewMatcher() {
return declStmt(
unless(has(varDecl(anyOf(
unless(hasInitializer(ignoringParenImpCasts(cxxNewExpr()))),
// FIXME: TypeLoc information is not reliable where CV
// qualifiers are concerned so these types can't be
// handled for now.
hasType(pointerType(
pointee(hasCanonicalType(hasLocalQualifiers())))),
// FIXME: Handle function pointers. For now we ignore them
// because the replacement replaces the entire type
// specifier source range which includes the identifier.
hasType(pointsTo(
pointsTo(parenType(innerType(functionType()))))))))))
.bind(DeclWithNewId);
}
StatementMatcher makeDeclWithCastMatcher() {
return declStmt(
unless(has(varDecl(unless(hasInitializer(explicitCastExpr()))))))
.bind(DeclWithCastId);
}
StatementMatcher makeDeclWithTemplateCastMatcher() {
auto ST =
substTemplateTypeParmType(hasReplacementType(equalsBoundNode("arg")));
auto ExplicitCall =
anyOf(has(memberExpr(hasExplicitTemplateArgs())),
has(ignoringImpCasts(declRefExpr(hasExplicitTemplateArgs()))));
auto TemplateArg =
hasTemplateArgument(0, refersToType(qualType().bind("arg")));
auto TemplateCall = callExpr(
ExplicitCall,
callee(functionDecl(TemplateArg,
returns(anyOf(ST, pointsTo(ST), references(ST))))));
return declStmt(unless(has(varDecl(
unless(hasInitializer(ignoringImplicit(TemplateCall)))))))
.bind(DeclWithTemplateCastId);
}
StatementMatcher makeCombinedMatcher() {
return declStmt(
// At least one varDecl should be a child of the declStmt to ensure
// it's a declaration list and avoid matching other declarations,
// e.g. using directives.
has(varDecl(unless(isImplicit()))),
// Skip declarations that are already using auto.
unless(has(varDecl(anyOf(hasType(autoType()),
hasType(qualType(hasDescendant(autoType()))))))),
anyOf(makeIteratorDeclMatcher(), makeDeclWithNewMatcher(),
makeDeclWithCastMatcher(), makeDeclWithTemplateCastMatcher()));
}
} // namespace
UseAutoCheck::UseAutoCheck(StringRef Name, ClangTidyContext *Context)
: ClangTidyCheck(Name, Context),
MinTypeNameLength(Options.get("MinTypeNameLength", 5)),
RemoveStars(Options.get("RemoveStars", false)) {}
void UseAutoCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
Options.store(Opts, "MinTypeNameLength", MinTypeNameLength);
Options.store(Opts, "RemoveStars", RemoveStars);
}
void UseAutoCheck::registerMatchers(MatchFinder *Finder) {
Finder->addMatcher(traverse(TK_AsIs, makeCombinedMatcher()), this);
}
void UseAutoCheck::replaceIterators(const DeclStmt *D, ASTContext *Context) {
for (const auto *Dec : D->decls()) {
const auto *V = cast<VarDecl>(Dec);
const Expr *ExprInit = V->getInit();
// Skip expressions with cleanups from the initializer expression.
if (const auto *E = dyn_cast<ExprWithCleanups>(ExprInit))
ExprInit = E->getSubExpr();
const auto *Construct = dyn_cast<CXXConstructExpr>(ExprInit);
if (!Construct)
continue;
// Ensure that the constructor receives a single argument.
if (Construct->getNumArgs() != 1)
return;
// Drill down to the as-written initializer.
const Expr *E = (*Construct->arg_begin())->IgnoreParenImpCasts();
if (E != E->IgnoreConversionOperatorSingleStep()) {
// We hit a conversion operator. Early-out now as they imply an implicit
// conversion from a different type. Could also mean an explicit
// conversion from the same type but that's pretty rare.
return;
}
if (const auto *NestedConstruct = dyn_cast<CXXConstructExpr>(E)) {
// If we ran into an implicit conversion constructor, can't convert.
//
// FIXME: The following only checks if the constructor can be used
// implicitly, not if it actually was. Cases where the converting
// constructor was used explicitly won't get converted.
if (NestedConstruct->getConstructor()->isConvertingConstructor(false))
return;
}
if (!Context->hasSameType(V->getType(), E->getType()))
return;
}
// Get the type location using the first declaration.
const auto *V = cast<VarDecl>(*D->decl_begin());
// WARNING: TypeLoc::getSourceRange() will include the identifier for things
// like function pointers. Not a concern since this action only works with
// iterators but something to keep in mind in the future.
SourceRange Range(V->getTypeSourceInfo()->getTypeLoc().getSourceRange());
diag(Range.getBegin(), "use auto when declaring iterators")
<< FixItHint::CreateReplacement(Range, "auto");
}
void UseAutoCheck::replaceExpr(
const DeclStmt *D, ASTContext *Context,
llvm::function_ref<QualType(const Expr *)> GetType, StringRef Message) {
const auto *FirstDecl = dyn_cast<VarDecl>(*D->decl_begin());
// Ensure that there is at least one VarDecl within the DeclStmt.
if (!FirstDecl)
return;
const QualType FirstDeclType = FirstDecl->getType().getCanonicalType();
std::vector<FixItHint> StarRemovals;
for (const auto *Dec : D->decls()) {
const auto *V = cast<VarDecl>(Dec);
// Ensure that every DeclStmt child is a VarDecl.
if (!V)
return;
const auto *Expr = V->getInit()->IgnoreParenImpCasts();
// Ensure that every VarDecl has an initializer.
if (!Expr)
return;
// If VarDecl and Initializer have mismatching unqualified types.
if (!Context->hasSameUnqualifiedType(V->getType(), GetType(Expr)))
return;
// All subsequent variables in this declaration should have the same
// canonical type. For example, we don't want to use `auto` in
// `T *p = new T, **pp = new T*;`.
if (FirstDeclType != V->getType().getCanonicalType())
return;
if (RemoveStars) {
// Remove explicitly written '*' from declarations where there's more than
// one declaration in the declaration list.
if (Dec == *D->decl_begin())
continue;
auto Q = V->getTypeSourceInfo()->getTypeLoc().getAs<PointerTypeLoc>();
while (!Q.isNull()) {
StarRemovals.push_back(FixItHint::CreateRemoval(Q.getStarLoc()));
Q = Q.getNextTypeLoc().getAs<PointerTypeLoc>();
}
}
}
// FIXME: There is, however, one case we can address: when the VarDecl pointee
// is the same as the initializer, just more CV-qualified. However, TypeLoc
// information is not reliable where CV qualifiers are concerned so we can't
// do anything about this case for now.
TypeLoc Loc = FirstDecl->getTypeSourceInfo()->getTypeLoc();
if (!RemoveStars) {
while (Loc.getTypeLocClass() == TypeLoc::Pointer ||
Loc.getTypeLocClass() == TypeLoc::Qualified)
Loc = Loc.getNextTypeLoc();
}
while (Loc.getTypeLocClass() == TypeLoc::LValueReference ||
Loc.getTypeLocClass() == TypeLoc::RValueReference ||
Loc.getTypeLocClass() == TypeLoc::Qualified) {
Loc = Loc.getNextTypeLoc();
}
SourceRange Range(Loc.getSourceRange());
if (MinTypeNameLength != 0 &&
GetTypeNameLength(RemoveStars,
tooling::fixit::getText(Loc.getSourceRange(),
FirstDecl->getASTContext())) <
MinTypeNameLength)
return;
auto Diag = diag(Range.getBegin(), Message);
// Space after 'auto' to handle cases where the '*' in the pointer type is
// next to the identifier. This avoids changing 'int *p' into 'autop'.
// FIXME: This doesn't work for function pointers because the variable name
// is inside the type.
Diag << FixItHint::CreateReplacement(Range, RemoveStars ? "auto " : "auto")
<< StarRemovals;
}
void UseAutoCheck::check(const MatchFinder::MatchResult &Result) {
if (const auto *Decl = Result.Nodes.getNodeAs<DeclStmt>(IteratorDeclStmtId)) {
replaceIterators(Decl, Result.Context);
} else if (const auto *Decl =
Result.Nodes.getNodeAs<DeclStmt>(DeclWithNewId)) {
replaceExpr(Decl, Result.Context,
[](const Expr *Expr) { return Expr->getType(); },
"use auto when initializing with new to avoid "
"duplicating the type name");
} else if (const auto *Decl =
Result.Nodes.getNodeAs<DeclStmt>(DeclWithCastId)) {
replaceExpr(
Decl, Result.Context,
[](const Expr *Expr) {
return cast<ExplicitCastExpr>(Expr)->getTypeAsWritten();
},
"use auto when initializing with a cast to avoid duplicating the type "
"name");
} else if (const auto *Decl =
Result.Nodes.getNodeAs<DeclStmt>(DeclWithTemplateCastId)) {
replaceExpr(
Decl, Result.Context,
[](const Expr *Expr) {
return cast<CallExpr>(Expr->IgnoreImplicit())
->getDirectCallee()
->getReturnType();
},
"use auto when initializing with a template cast to avoid duplicating "
"the type name");
} else {
llvm_unreachable("Bad Callback. No node provided.");
}
}
} // namespace modernize
} // namespace tidy
} // namespace clang
| [
"kontoshi0317@gmail.com"
] | kontoshi0317@gmail.com |
34fba54510fd002aa7783a11feba79869421ff74 | becdc5eaaee5e0063abe524a84e78c9c5f355032 | /emuDCS/FEDUtils/src/common/CrateParser.cc | 121da413d7c24f67828bb144be4480fce3b4632e | [] | no_license | slava77/emu | db6e59d6b0d694a75ebc8583d1f8c3696c8836e2 | c0036c238757d4283ebdcc20ed559d7b27a980c7 | refs/heads/svn-devel | 2021-01-21T05:00:47.307761 | 2016-06-03T14:12:10 | 2016-06-03T14:12:10 | 23,416,919 | 1 | 10 | null | 2016-05-09T21:16:14 | 2014-08-28T05:51:44 | C++ | UTF-8 | C++ | false | false | 1,370 | cc | /*****************************************************************************\
* $Id: CrateParser.cc,v 1.5 2009/12/10 16:30:04 paste Exp $
\*****************************************************************************/
#include "emu/fed/CrateParser.h"
#include <sstream>
#include "emu/fed/Crate.h"
emu::fed::Crate *emu::fed::CrateParser::parse(xercesc::DOMElement *pNode)
throw (emu::fed::exception::ParseException)
{
Parser parser(pNode);
unsigned int number;
try {
number = parser.extract<unsigned int>("CRATE_NUMBER");
} catch (emu::fed::exception::ParseException &e) {
std::ostringstream error;
error << "Unable to parse CRATE_NUMBER from element";
XCEPT_RETHROW(emu::fed::exception::ParseException, error.str(), e);
}
return new Crate(number);
}
xercesc::DOMElement *emu::fed::CrateParser::makeDOMElement(xercesc::DOMDocument *document, emu::fed::Crate *crate)
throw (emu::fed::exception::ParseException)
{
try {
// Make a crate element
xercesc::DOMElement *crateElement = document->createElement(X("FEDCrate"));
// Set attributes
Parser::insert(crateElement, "CRATE_NUMBER", crate->getNumber());
return crateElement;
} catch (xercesc::DOMException &e) {
std::ostringstream error;
error << "Unable to create FEDCrate element: " << X(e.getMessage());
XCEPT_RAISE(emu::fed::exception::ParseException, error.str());
}
}
| [
"paste@4525493e-7705-40b1-a816-d608a930855b"
] | paste@4525493e-7705-40b1-a816-d608a930855b |
22f82a3ec142c76a2c0169127b990498e4f1702d | 20b86902e71f9b5026d0ffe5ce35dd40c6dcee97 | /test/cctest/wasm/test-run-wasm.cc | 236624f5f0c0b29d343915b6256a0f9f297a1a4f | [
"BSD-3-Clause",
"bzip2-1.0.6"
] | permissive | LoveItachi/v8-crosswalk | a818d7c42109d0123afb307c35b8a67e70c74b16 | 1b92e4941ca9e1ceb4e73697694cc1104c3d0af2 | refs/heads/master | 2021-01-22T10:40:43.359294 | 2016-06-29T03:27:02 | 2016-08-01T22:15:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 88,638 | cc | // Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "src/base/platform/elapsed-timer.h"
#include "src/wasm/wasm-macro-gen.h"
#include "test/cctest/cctest.h"
#include "test/cctest/compiler/value-helper.h"
#include "test/cctest/wasm/test-signatures.h"
#include "test/cctest/wasm/wasm-run-utils.h"
using namespace v8::base;
using namespace v8::internal;
using namespace v8::internal::compiler;
using namespace v8::internal::wasm;
// for even shorter tests.
#define B2(a, b) kExprBlock, a, b, kExprEnd
#define B1(a) kExprBlock, a, kExprEnd
#define RET(x) x, kExprReturn, 1
#define RET_I8(x) kExprI8Const, x, kExprReturn, 1
WASM_EXEC_TEST(Int8Const) {
WasmRunner<int32_t> r;
const byte kExpectedValue = 121;
// return(kExpectedValue)
BUILD(r, WASM_I8(kExpectedValue));
CHECK_EQ(kExpectedValue, r.Call());
}
WASM_EXEC_TEST(Int8Const_fallthru1) {
WasmRunner<int32_t> r;
const byte kExpectedValue = 122;
// kExpectedValue
BUILD(r, WASM_I8(kExpectedValue));
CHECK_EQ(kExpectedValue, r.Call());
}
WASM_EXEC_TEST(Int8Const_fallthru2) {
WasmRunner<int32_t> r;
const byte kExpectedValue = 123;
// -99 kExpectedValue
BUILD(r, WASM_I8(-99), WASM_I8(kExpectedValue));
CHECK_EQ(kExpectedValue, r.Call());
}
WASM_EXEC_TEST(Int8Const_all) {
for (int value = -128; value <= 127; value++) {
WasmRunner<int32_t> r;
// return(value)
BUILD(r, WASM_I8(value));
int32_t result = r.Call();
CHECK_EQ(value, result);
}
}
WASM_EXEC_TEST(Int32Const) {
WasmRunner<int32_t> r;
const int32_t kExpectedValue = 0x11223344;
// return(kExpectedValue)
BUILD(r, WASM_I32V_5(kExpectedValue));
CHECK_EQ(kExpectedValue, r.Call());
}
WASM_EXEC_TEST(Int32Const_many) {
FOR_INT32_INPUTS(i) {
WasmRunner<int32_t> r;
const int32_t kExpectedValue = *i;
// return(kExpectedValue)
BUILD(r, WASM_I32V(kExpectedValue));
CHECK_EQ(kExpectedValue, r.Call());
}
}
WASM_EXEC_TEST(MemorySize) {
TestingModule module;
WasmRunner<int32_t> r(&module);
module.AddMemory(1024);
BUILD(r, kExprMemorySize);
CHECK_EQ(1024, r.Call());
}
WASM_EXEC_TEST(Int32Param0) {
WasmRunner<int32_t> r(MachineType::Int32());
// return(local[0])
BUILD(r, WASM_GET_LOCAL(0));
FOR_INT32_INPUTS(i) { CHECK_EQ(*i, r.Call(*i)); }
}
WASM_EXEC_TEST(Int32Param0_fallthru) {
WasmRunner<int32_t> r(MachineType::Int32());
// local[0]
BUILD(r, WASM_GET_LOCAL(0));
FOR_INT32_INPUTS(i) { CHECK_EQ(*i, r.Call(*i)); }
}
WASM_EXEC_TEST(Int32Param1) {
WasmRunner<int32_t> r(MachineType::Int32(), MachineType::Int32());
// local[1]
BUILD(r, WASM_GET_LOCAL(1));
FOR_INT32_INPUTS(i) { CHECK_EQ(*i, r.Call(-111, *i)); }
}
WASM_EXEC_TEST(Int32Add) {
WasmRunner<int32_t> r;
// 11 + 44
BUILD(r, WASM_I32_ADD(WASM_I8(11), WASM_I8(44)));
CHECK_EQ(55, r.Call());
}
WASM_EXEC_TEST(Int32Add_P) {
WasmRunner<int32_t> r(MachineType::Int32());
// p0 + 13
BUILD(r, WASM_I32_ADD(WASM_I8(13), WASM_GET_LOCAL(0)));
FOR_INT32_INPUTS(i) { CHECK_EQ(*i + 13, r.Call(*i)); }
}
WASM_EXEC_TEST(Int32Add_P_fallthru) {
WasmRunner<int32_t> r(MachineType::Int32());
// p0 + 13
BUILD(r, WASM_I32_ADD(WASM_I8(13), WASM_GET_LOCAL(0)));
FOR_INT32_INPUTS(i) { CHECK_EQ(*i + 13, r.Call(*i)); }
}
WASM_EXEC_TEST(Int32Add_P2) {
WasmRunner<int32_t> r(MachineType::Int32(), MachineType::Int32());
// p0 + p1
BUILD(r, WASM_I32_ADD(WASM_GET_LOCAL(0), WASM_GET_LOCAL(1)));
FOR_INT32_INPUTS(i) {
FOR_INT32_INPUTS(j) {
int32_t expected = static_cast<int32_t>(static_cast<uint32_t>(*i) +
static_cast<uint32_t>(*j));
CHECK_EQ(expected, r.Call(*i, *j));
}
}
}
WASM_EXEC_TEST(Float32Add) {
WasmRunner<int32_t> r;
// int(11.5f + 44.5f)
BUILD(r,
WASM_I32_SCONVERT_F32(WASM_F32_ADD(WASM_F32(11.5f), WASM_F32(44.5f))));
CHECK_EQ(56, r.Call());
}
WASM_EXEC_TEST(Float64Add) {
WasmRunner<int32_t> r;
// return int(13.5d + 43.5d)
BUILD(r, WASM_I32_SCONVERT_F64(WASM_F64_ADD(WASM_F64(13.5), WASM_F64(43.5))));
CHECK_EQ(57, r.Call());
}
void TestInt32Binop(WasmOpcode opcode, int32_t expected, int32_t a, int32_t b) {
{
WasmRunner<int32_t> r;
// K op K
BUILD(r, WASM_BINOP(opcode, WASM_I32V(a), WASM_I32V(b)));
CHECK_EQ(expected, r.Call());
}
{
WasmRunner<int32_t> r(MachineType::Int32(), MachineType::Int32());
// a op b
BUILD(r, WASM_BINOP(opcode, WASM_GET_LOCAL(0), WASM_GET_LOCAL(1)));
CHECK_EQ(expected, r.Call(a, b));
}
}
WASM_EXEC_TEST(Int32Binops) {
TestInt32Binop(kExprI32Add, 88888888, 33333333, 55555555);
TestInt32Binop(kExprI32Sub, -1111111, 7777777, 8888888);
TestInt32Binop(kExprI32Mul, 65130756, 88734, 734);
TestInt32Binop(kExprI32DivS, -66, -4777344, 72384);
TestInt32Binop(kExprI32DivU, 805306368, 0xF0000000, 5);
TestInt32Binop(kExprI32RemS, -3, -3003, 1000);
TestInt32Binop(kExprI32RemU, 4, 4004, 1000);
TestInt32Binop(kExprI32And, 0xEE, 0xFFEE, 0xFF0000FF);
TestInt32Binop(kExprI32Ior, 0xF0FF00FF, 0xF0F000EE, 0x000F0011);
TestInt32Binop(kExprI32Xor, 0xABCDEF01, 0xABCDEFFF, 0xFE);
TestInt32Binop(kExprI32Shl, 0xA0000000, 0xA, 28);
TestInt32Binop(kExprI32ShrU, 0x07000010, 0x70000100, 4);
TestInt32Binop(kExprI32ShrS, 0xFF000000, 0x80000000, 7);
TestInt32Binop(kExprI32Ror, 0x01000000, 0x80000000, 7);
TestInt32Binop(kExprI32Ror, 0x01000000, 0x80000000, 39);
TestInt32Binop(kExprI32Rol, 0x00000040, 0x80000000, 7);
TestInt32Binop(kExprI32Rol, 0x00000040, 0x80000000, 39);
TestInt32Binop(kExprI32Eq, 1, -99, -99);
TestInt32Binop(kExprI32Ne, 0, -97, -97);
TestInt32Binop(kExprI32LtS, 1, -4, 4);
TestInt32Binop(kExprI32LeS, 0, -2, -3);
TestInt32Binop(kExprI32LtU, 1, 0, -6);
TestInt32Binop(kExprI32LeU, 1, 98978, 0xF0000000);
TestInt32Binop(kExprI32GtS, 1, 4, -4);
TestInt32Binop(kExprI32GeS, 0, -3, -2);
TestInt32Binop(kExprI32GtU, 1, -6, 0);
TestInt32Binop(kExprI32GeU, 1, 0xF0000000, 98978);
}
void TestInt32Unop(WasmOpcode opcode, int32_t expected, int32_t a) {
{
WasmRunner<int32_t> r;
// return op K
BUILD(r, WASM_UNOP(opcode, WASM_I32V(a)));
CHECK_EQ(expected, r.Call());
}
{
WasmRunner<int32_t> r(MachineType::Int32());
// return op a
BUILD(r, WASM_UNOP(opcode, WASM_GET_LOCAL(0)));
CHECK_EQ(expected, r.Call(a));
}
}
WASM_EXEC_TEST(Int32Clz) {
TestInt32Unop(kExprI32Clz, 0, 0x80001000);
TestInt32Unop(kExprI32Clz, 1, 0x40000500);
TestInt32Unop(kExprI32Clz, 2, 0x20000300);
TestInt32Unop(kExprI32Clz, 3, 0x10000003);
TestInt32Unop(kExprI32Clz, 4, 0x08050000);
TestInt32Unop(kExprI32Clz, 5, 0x04006000);
TestInt32Unop(kExprI32Clz, 6, 0x02000000);
TestInt32Unop(kExprI32Clz, 7, 0x010000a0);
TestInt32Unop(kExprI32Clz, 8, 0x00800c00);
TestInt32Unop(kExprI32Clz, 9, 0x00400000);
TestInt32Unop(kExprI32Clz, 10, 0x0020000d);
TestInt32Unop(kExprI32Clz, 11, 0x00100f00);
TestInt32Unop(kExprI32Clz, 12, 0x00080000);
TestInt32Unop(kExprI32Clz, 13, 0x00041000);
TestInt32Unop(kExprI32Clz, 14, 0x00020020);
TestInt32Unop(kExprI32Clz, 15, 0x00010300);
TestInt32Unop(kExprI32Clz, 16, 0x00008040);
TestInt32Unop(kExprI32Clz, 17, 0x00004005);
TestInt32Unop(kExprI32Clz, 18, 0x00002050);
TestInt32Unop(kExprI32Clz, 19, 0x00001700);
TestInt32Unop(kExprI32Clz, 20, 0x00000870);
TestInt32Unop(kExprI32Clz, 21, 0x00000405);
TestInt32Unop(kExprI32Clz, 22, 0x00000203);
TestInt32Unop(kExprI32Clz, 23, 0x00000101);
TestInt32Unop(kExprI32Clz, 24, 0x00000089);
TestInt32Unop(kExprI32Clz, 25, 0x00000041);
TestInt32Unop(kExprI32Clz, 26, 0x00000022);
TestInt32Unop(kExprI32Clz, 27, 0x00000013);
TestInt32Unop(kExprI32Clz, 28, 0x00000008);
TestInt32Unop(kExprI32Clz, 29, 0x00000004);
TestInt32Unop(kExprI32Clz, 30, 0x00000002);
TestInt32Unop(kExprI32Clz, 31, 0x00000001);
TestInt32Unop(kExprI32Clz, 32, 0x00000000);
}
WASM_EXEC_TEST(Int32Ctz) {
TestInt32Unop(kExprI32Ctz, 32, 0x00000000);
TestInt32Unop(kExprI32Ctz, 31, 0x80000000);
TestInt32Unop(kExprI32Ctz, 30, 0x40000000);
TestInt32Unop(kExprI32Ctz, 29, 0x20000000);
TestInt32Unop(kExprI32Ctz, 28, 0x10000000);
TestInt32Unop(kExprI32Ctz, 27, 0xa8000000);
TestInt32Unop(kExprI32Ctz, 26, 0xf4000000);
TestInt32Unop(kExprI32Ctz, 25, 0x62000000);
TestInt32Unop(kExprI32Ctz, 24, 0x91000000);
TestInt32Unop(kExprI32Ctz, 23, 0xcd800000);
TestInt32Unop(kExprI32Ctz, 22, 0x09400000);
TestInt32Unop(kExprI32Ctz, 21, 0xaf200000);
TestInt32Unop(kExprI32Ctz, 20, 0xac100000);
TestInt32Unop(kExprI32Ctz, 19, 0xe0b80000);
TestInt32Unop(kExprI32Ctz, 18, 0x9ce40000);
TestInt32Unop(kExprI32Ctz, 17, 0xc7920000);
TestInt32Unop(kExprI32Ctz, 16, 0xb8f10000);
TestInt32Unop(kExprI32Ctz, 15, 0x3b9f8000);
TestInt32Unop(kExprI32Ctz, 14, 0xdb4c4000);
TestInt32Unop(kExprI32Ctz, 13, 0xe9a32000);
TestInt32Unop(kExprI32Ctz, 12, 0xfca61000);
TestInt32Unop(kExprI32Ctz, 11, 0x6c8a7800);
TestInt32Unop(kExprI32Ctz, 10, 0x8ce5a400);
TestInt32Unop(kExprI32Ctz, 9, 0xcb7d0200);
TestInt32Unop(kExprI32Ctz, 8, 0xcb4dc100);
TestInt32Unop(kExprI32Ctz, 7, 0xdfbec580);
TestInt32Unop(kExprI32Ctz, 6, 0x27a9db40);
TestInt32Unop(kExprI32Ctz, 5, 0xde3bcb20);
TestInt32Unop(kExprI32Ctz, 4, 0xd7e8a610);
TestInt32Unop(kExprI32Ctz, 3, 0x9afdbc88);
TestInt32Unop(kExprI32Ctz, 2, 0x9afdbc84);
TestInt32Unop(kExprI32Ctz, 1, 0x9afdbc82);
TestInt32Unop(kExprI32Ctz, 0, 0x9afdbc81);
}
WASM_EXEC_TEST(Int32Popcnt) {
TestInt32Unop(kExprI32Popcnt, 32, 0xffffffff);
TestInt32Unop(kExprI32Popcnt, 0, 0x00000000);
TestInt32Unop(kExprI32Popcnt, 1, 0x00008000);
TestInt32Unop(kExprI32Popcnt, 13, 0x12345678);
TestInt32Unop(kExprI32Popcnt, 19, 0xfedcba09);
}
WASM_EXEC_TEST(I32Eqz) {
TestInt32Unop(kExprI32Eqz, 0, 1);
TestInt32Unop(kExprI32Eqz, 0, -1);
TestInt32Unop(kExprI32Eqz, 0, -827343);
TestInt32Unop(kExprI32Eqz, 0, 8888888);
TestInt32Unop(kExprI32Eqz, 1, 0);
}
WASM_EXEC_TEST(I32Shl) {
WasmRunner<uint32_t> r(MachineType::Uint32(), MachineType::Uint32());
BUILD(r, WASM_I32_SHL(WASM_GET_LOCAL(0), WASM_GET_LOCAL(1)));
FOR_UINT32_INPUTS(i) {
FOR_UINT32_INPUTS(j) {
uint32_t expected = (*i) << (*j & 0x1f);
CHECK_EQ(expected, r.Call(*i, *j));
}
}
}
WASM_EXEC_TEST(I32Shr) {
WasmRunner<uint32_t> r(MachineType::Uint32(), MachineType::Uint32());
BUILD(r, WASM_I32_SHR(WASM_GET_LOCAL(0), WASM_GET_LOCAL(1)));
FOR_UINT32_INPUTS(i) {
FOR_UINT32_INPUTS(j) {
uint32_t expected = (*i) >> (*j & 0x1f);
CHECK_EQ(expected, r.Call(*i, *j));
}
}
}
WASM_EXEC_TEST(I32Sar) {
WasmRunner<int32_t> r(MachineType::Int32(), MachineType::Int32());
BUILD(r, WASM_I32_SAR(WASM_GET_LOCAL(0), WASM_GET_LOCAL(1)));
FOR_INT32_INPUTS(i) {
FOR_INT32_INPUTS(j) {
int32_t expected = (*i) >> (*j & 0x1f);
CHECK_EQ(expected, r.Call(*i, *j));
}
}
}
WASM_EXEC_TEST(Int32DivS_trap) {
WasmRunner<int32_t> r(MachineType::Int32(), MachineType::Int32());
BUILD(r, WASM_I32_DIVS(WASM_GET_LOCAL(0), WASM_GET_LOCAL(1)));
const int32_t kMin = std::numeric_limits<int32_t>::min();
CHECK_EQ(0, r.Call(0, 100));
CHECK_TRAP(r.Call(100, 0));
CHECK_TRAP(r.Call(-1001, 0));
CHECK_TRAP(r.Call(kMin, -1));
CHECK_TRAP(r.Call(kMin, 0));
}
WASM_EXEC_TEST(Int32RemS_trap) {
WasmRunner<int32_t> r(MachineType::Int32(), MachineType::Int32());
BUILD(r, WASM_I32_REMS(WASM_GET_LOCAL(0), WASM_GET_LOCAL(1)));
const int32_t kMin = std::numeric_limits<int32_t>::min();
CHECK_EQ(33, r.Call(133, 100));
CHECK_EQ(0, r.Call(kMin, -1));
CHECK_TRAP(r.Call(100, 0));
CHECK_TRAP(r.Call(-1001, 0));
CHECK_TRAP(r.Call(kMin, 0));
}
WASM_EXEC_TEST(Int32DivU_trap) {
WasmRunner<int32_t> r(MachineType::Int32(), MachineType::Int32());
BUILD(r, WASM_I32_DIVU(WASM_GET_LOCAL(0), WASM_GET_LOCAL(1)));
const int32_t kMin = std::numeric_limits<int32_t>::min();
CHECK_EQ(0, r.Call(0, 100));
CHECK_EQ(0, r.Call(kMin, -1));
CHECK_TRAP(r.Call(100, 0));
CHECK_TRAP(r.Call(-1001, 0));
CHECK_TRAP(r.Call(kMin, 0));
}
WASM_EXEC_TEST(Int32RemU_trap) {
WasmRunner<int32_t> r(MachineType::Int32(), MachineType::Int32());
BUILD(r, WASM_I32_REMU(WASM_GET_LOCAL(0), WASM_GET_LOCAL(1)));
CHECK_EQ(17, r.Call(217, 100));
const int32_t kMin = std::numeric_limits<int32_t>::min();
CHECK_TRAP(r.Call(100, 0));
CHECK_TRAP(r.Call(-1001, 0));
CHECK_TRAP(r.Call(kMin, 0));
CHECK_EQ(kMin, r.Call(kMin, -1));
}
WASM_EXEC_TEST(Int32DivS_byzero_const) {
for (int8_t denom = -2; denom < 8; denom++) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, WASM_I32_DIVS(WASM_GET_LOCAL(0), WASM_I8(denom)));
for (int32_t val = -7; val < 8; val++) {
if (denom == 0) {
CHECK_TRAP(r.Call(val));
} else {
CHECK_EQ(val / denom, r.Call(val));
}
}
}
}
WASM_EXEC_TEST(Int32DivU_byzero_const) {
for (uint32_t denom = 0xfffffffe; denom < 8; denom++) {
WasmRunner<uint32_t> r(MachineType::Uint32());
BUILD(r, WASM_I32_DIVU(WASM_GET_LOCAL(0), WASM_I32V_1(denom)));
for (uint32_t val = 0xfffffff0; val < 8; val++) {
if (denom == 0) {
CHECK_TRAP(r.Call(val));
} else {
CHECK_EQ(val / denom, r.Call(val));
}
}
}
}
WASM_EXEC_TEST(Int32DivS_trap_effect) {
TestingModule module;
module.AddMemoryElems<int32_t>(8);
WasmRunner<int32_t> r(&module, MachineType::Int32(), MachineType::Int32());
BUILD(r,
WASM_IF_ELSE(WASM_GET_LOCAL(0),
WASM_I32_DIVS(WASM_STORE_MEM(MachineType::Int8(),
WASM_ZERO, WASM_GET_LOCAL(0)),
WASM_GET_LOCAL(1)),
WASM_I32_DIVS(WASM_STORE_MEM(MachineType::Int8(),
WASM_ZERO, WASM_GET_LOCAL(0)),
WASM_GET_LOCAL(1))));
CHECK_EQ(0, r.Call(0, 100));
CHECK_TRAP(r.Call(8, 0));
CHECK_TRAP(r.Call(4, 0));
CHECK_TRAP(r.Call(0, 0));
}
void TestFloat32Binop(WasmOpcode opcode, int32_t expected, float a, float b) {
{
WasmRunner<int32_t> r;
// return K op K
BUILD(r, WASM_BINOP(opcode, WASM_F32(a), WASM_F32(b)));
CHECK_EQ(expected, r.Call());
}
{
WasmRunner<int32_t> r(MachineType::Float32(), MachineType::Float32());
// return a op b
BUILD(r, WASM_BINOP(opcode, WASM_GET_LOCAL(0), WASM_GET_LOCAL(1)));
CHECK_EQ(expected, r.Call(a, b));
}
}
void TestFloat32BinopWithConvert(WasmOpcode opcode, int32_t expected, float a,
float b) {
{
WasmRunner<int32_t> r;
// return int(K op K)
BUILD(r,
WASM_I32_SCONVERT_F32(WASM_BINOP(opcode, WASM_F32(a), WASM_F32(b))));
CHECK_EQ(expected, r.Call());
}
{
WasmRunner<int32_t> r(MachineType::Float32(), MachineType::Float32());
// return int(a op b)
BUILD(r, WASM_I32_SCONVERT_F32(
WASM_BINOP(opcode, WASM_GET_LOCAL(0), WASM_GET_LOCAL(1))));
CHECK_EQ(expected, r.Call(a, b));
}
}
void TestFloat32UnopWithConvert(WasmOpcode opcode, int32_t expected, float a) {
{
WasmRunner<int32_t> r;
// return int(op(K))
BUILD(r, WASM_I32_SCONVERT_F32(WASM_UNOP(opcode, WASM_F32(a))));
CHECK_EQ(expected, r.Call());
}
{
WasmRunner<int32_t> r(MachineType::Float32());
// return int(op(a))
BUILD(r, WASM_I32_SCONVERT_F32(WASM_UNOP(opcode, WASM_GET_LOCAL(0))));
CHECK_EQ(expected, r.Call(a));
}
}
void TestFloat64Binop(WasmOpcode opcode, int32_t expected, double a, double b) {
{
WasmRunner<int32_t> r;
// return K op K
BUILD(r, WASM_BINOP(opcode, WASM_F64(a), WASM_F64(b)));
CHECK_EQ(expected, r.Call());
}
{
WasmRunner<int32_t> r(MachineType::Float64(), MachineType::Float64());
// return a op b
BUILD(r, WASM_BINOP(opcode, WASM_GET_LOCAL(0), WASM_GET_LOCAL(1)));
CHECK_EQ(expected, r.Call(a, b));
}
}
void TestFloat64BinopWithConvert(WasmOpcode opcode, int32_t expected, double a,
double b) {
{
WasmRunner<int32_t> r;
// return int(K op K)
BUILD(r,
WASM_I32_SCONVERT_F64(WASM_BINOP(opcode, WASM_F64(a), WASM_F64(b))));
CHECK_EQ(expected, r.Call());
}
{
WasmRunner<int32_t> r(MachineType::Float64(), MachineType::Float64());
BUILD(r, WASM_I32_SCONVERT_F64(
WASM_BINOP(opcode, WASM_GET_LOCAL(0), WASM_GET_LOCAL(1))));
CHECK_EQ(expected, r.Call(a, b));
}
}
void TestFloat64UnopWithConvert(WasmOpcode opcode, int32_t expected, double a) {
{
WasmRunner<int32_t> r;
// return int(op(K))
BUILD(r, WASM_I32_SCONVERT_F64(WASM_UNOP(opcode, WASM_F64(a))));
CHECK_EQ(expected, r.Call());
}
{
WasmRunner<int32_t> r(MachineType::Float64());
// return int(op(a))
BUILD(r, WASM_I32_SCONVERT_F64(WASM_UNOP(opcode, WASM_GET_LOCAL(0))));
CHECK_EQ(expected, r.Call(a));
}
}
WASM_EXEC_TEST(Float32Binops) {
TestFloat32Binop(kExprF32Eq, 1, 8.125f, 8.125f);
TestFloat32Binop(kExprF32Ne, 1, 8.125f, 8.127f);
TestFloat32Binop(kExprF32Lt, 1, -9.5f, -9.0f);
TestFloat32Binop(kExprF32Le, 1, -1111.0f, -1111.0f);
TestFloat32Binop(kExprF32Gt, 1, -9.0f, -9.5f);
TestFloat32Binop(kExprF32Ge, 1, -1111.0f, -1111.0f);
TestFloat32BinopWithConvert(kExprF32Add, 10, 3.5f, 6.5f);
TestFloat32BinopWithConvert(kExprF32Sub, 2, 44.5f, 42.5f);
TestFloat32BinopWithConvert(kExprF32Mul, -66, -132.1f, 0.5f);
TestFloat32BinopWithConvert(kExprF32Div, 11, 22.1f, 2.0f);
}
WASM_EXEC_TEST(Float32Unops) {
TestFloat32UnopWithConvert(kExprF32Abs, 8, 8.125f);
TestFloat32UnopWithConvert(kExprF32Abs, 9, -9.125f);
TestFloat32UnopWithConvert(kExprF32Neg, -213, 213.125f);
TestFloat32UnopWithConvert(kExprF32Sqrt, 12, 144.4f);
}
WASM_EXEC_TEST(Float64Binops) {
TestFloat64Binop(kExprF64Eq, 1, 16.25, 16.25);
TestFloat64Binop(kExprF64Ne, 1, 16.25, 16.15);
TestFloat64Binop(kExprF64Lt, 1, -32.4, 11.7);
TestFloat64Binop(kExprF64Le, 1, -88.9, -88.9);
TestFloat64Binop(kExprF64Gt, 1, 11.7, -32.4);
TestFloat64Binop(kExprF64Ge, 1, -88.9, -88.9);
TestFloat64BinopWithConvert(kExprF64Add, 100, 43.5, 56.5);
TestFloat64BinopWithConvert(kExprF64Sub, 200, 12200.1, 12000.1);
TestFloat64BinopWithConvert(kExprF64Mul, -33, 134, -0.25);
TestFloat64BinopWithConvert(kExprF64Div, -1111, -2222.3, 2);
}
WASM_EXEC_TEST(Float64Unops) {
TestFloat64UnopWithConvert(kExprF64Abs, 108, 108.125);
TestFloat64UnopWithConvert(kExprF64Abs, 209, -209.125);
TestFloat64UnopWithConvert(kExprF64Neg, -209, 209.125);
TestFloat64UnopWithConvert(kExprF64Sqrt, 13, 169.4);
}
WASM_EXEC_TEST(Float32Neg) {
WasmRunner<float> r(MachineType::Float32());
BUILD(r, WASM_F32_NEG(WASM_GET_LOCAL(0)));
FOR_FLOAT32_INPUTS(i) {
CHECK_EQ(0x80000000,
bit_cast<uint32_t>(*i) ^ bit_cast<uint32_t>(r.Call(*i)));
}
}
WASM_EXEC_TEST(Float32SubMinusZero) {
WasmRunner<float> r(MachineType::Float32());
BUILD(r, WASM_F32_SUB(WASM_F32(-0.0), WASM_GET_LOCAL(0)));
CHECK_EQ(0x7fe00000, bit_cast<uint32_t>(r.Call(bit_cast<float>(0x7fa00000))));
}
WASM_EXEC_TEST(Float64SubMinusZero) {
WasmRunner<double> r(MachineType::Float64());
BUILD(r, WASM_F64_SUB(WASM_F64(-0.0), WASM_GET_LOCAL(0)));
CHECK_EQ(0x7ff8123456789abc,
bit_cast<uint64_t>(r.Call(bit_cast<double>(0x7ff0123456789abc))));
}
WASM_EXEC_TEST(Float64Neg) {
WasmRunner<double> r(MachineType::Float64());
BUILD(r, WASM_F64_NEG(WASM_GET_LOCAL(0)));
FOR_FLOAT64_INPUTS(i) {
CHECK_EQ(0x8000000000000000,
bit_cast<uint64_t>(*i) ^ bit_cast<uint64_t>(r.Call(*i)));
}
}
WASM_EXEC_TEST(IfElse_P) {
WasmRunner<int32_t> r(MachineType::Int32());
// if (p0) return 11; else return 22;
BUILD(r, WASM_IF_ELSE(WASM_GET_LOCAL(0), // --
WASM_I8(11), // --
WASM_I8(22))); // --
FOR_INT32_INPUTS(i) {
int32_t expected = *i ? 11 : 22;
CHECK_EQ(expected, r.Call(*i));
}
}
WASM_EXEC_TEST(If_empty1) {
WasmRunner<uint32_t> r(MachineType::Uint32(), MachineType::Uint32());
BUILD(r, WASM_GET_LOCAL(0), kExprIf, kExprEnd, WASM_GET_LOCAL(1));
FOR_UINT32_INPUTS(i) { CHECK_EQ(*i, r.Call(*i - 9, *i)); }
}
WASM_EXEC_TEST(IfElse_empty1) {
WasmRunner<uint32_t> r(MachineType::Uint32(), MachineType::Uint32());
BUILD(r, WASM_GET_LOCAL(0), kExprIf, kExprElse, kExprEnd, WASM_GET_LOCAL(1));
FOR_UINT32_INPUTS(i) { CHECK_EQ(*i, r.Call(*i - 8, *i)); }
}
WASM_EXEC_TEST(IfElse_empty2) {
WasmRunner<uint32_t> r(MachineType::Uint32(), MachineType::Uint32());
BUILD(r, WASM_GET_LOCAL(0), kExprIf, WASM_ZERO, kExprElse, kExprEnd,
WASM_GET_LOCAL(1));
FOR_UINT32_INPUTS(i) { CHECK_EQ(*i, r.Call(*i - 7, *i)); }
}
WASM_EXEC_TEST(IfElse_empty3) {
WasmRunner<uint32_t> r(MachineType::Uint32(), MachineType::Uint32());
BUILD(r, WASM_GET_LOCAL(0), kExprIf, kExprElse, WASM_ZERO, kExprEnd,
WASM_GET_LOCAL(1));
FOR_UINT32_INPUTS(i) { CHECK_EQ(*i, r.Call(*i - 6, *i)); }
}
WASM_EXEC_TEST(If_chain) {
WasmRunner<int32_t> r(MachineType::Int32());
// if (p0) 13; if (p0) 14; 15
BUILD(r, WASM_IF(WASM_GET_LOCAL(0), WASM_I8(13)),
WASM_IF(WASM_GET_LOCAL(0), WASM_I8(14)), WASM_I8(15));
FOR_INT32_INPUTS(i) { CHECK_EQ(15, r.Call(*i)); }
}
WASM_EXEC_TEST(If_chain_set) {
WasmRunner<int32_t> r(MachineType::Int32(), MachineType::Int32());
// if (p0) p1 = 73; if (p0) p1 = 74; p1
BUILD(r, WASM_IF(WASM_GET_LOCAL(0), WASM_SET_LOCAL(1, WASM_I8(73))),
WASM_IF(WASM_GET_LOCAL(0), WASM_SET_LOCAL(1, WASM_I8(74))),
WASM_GET_LOCAL(1));
FOR_INT32_INPUTS(i) {
int32_t expected = *i ? 74 : *i;
CHECK_EQ(expected, r.Call(*i, *i));
}
}
WASM_EXEC_TEST(IfElse_Unreachable1) {
WasmRunner<int32_t> r;
// if (0) unreachable; else return 22;
BUILD(r, WASM_IF_ELSE(WASM_ZERO, // --
WASM_UNREACHABLE, // --
WASM_I8(27))); // --
CHECK_EQ(27, r.Call());
}
WASM_EXEC_TEST(Return12) {
WasmRunner<int32_t> r;
BUILD(r, RET_I8(12));
CHECK_EQ(12, r.Call());
}
WASM_EXEC_TEST(Return17) {
WasmRunner<int32_t> r;
BUILD(r, B1(RET_I8(17)));
CHECK_EQ(17, r.Call());
}
WASM_EXEC_TEST(Return_I32) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, RET(WASM_GET_LOCAL(0)));
FOR_INT32_INPUTS(i) { CHECK_EQ(*i, r.Call(*i)); }
}
WASM_EXEC_TEST(Return_F32) {
WasmRunner<float> r(MachineType::Float32());
BUILD(r, RET(WASM_GET_LOCAL(0)));
FOR_FLOAT32_INPUTS(i) {
float expect = *i;
float result = r.Call(expect);
if (std::isnan(expect)) {
CHECK(std::isnan(result));
} else {
CHECK_EQ(expect, result);
}
}
}
WASM_EXEC_TEST(Return_F64) {
WasmRunner<double> r(MachineType::Float64());
BUILD(r, RET(WASM_GET_LOCAL(0)));
FOR_FLOAT64_INPUTS(i) {
double expect = *i;
double result = r.Call(expect);
if (std::isnan(expect)) {
CHECK(std::isnan(result));
} else {
CHECK_EQ(expect, result);
}
}
}
WASM_EXEC_TEST(Select) {
WasmRunner<int32_t> r(MachineType::Int32());
// return select(11, 22, a);
BUILD(r, WASM_SELECT(WASM_I8(11), WASM_I8(22), WASM_GET_LOCAL(0)));
FOR_INT32_INPUTS(i) {
int32_t expected = *i ? 11 : 22;
CHECK_EQ(expected, r.Call(*i));
}
}
WASM_EXEC_TEST(Select_strict1) {
WasmRunner<int32_t> r(MachineType::Int32());
// select(a=0, a=1, a=2); return a
BUILD(r, B2(WASM_SELECT(WASM_SET_LOCAL(0, WASM_I8(0)),
WASM_SET_LOCAL(0, WASM_I8(1)),
WASM_SET_LOCAL(0, WASM_I8(2))),
WASM_GET_LOCAL(0)));
FOR_INT32_INPUTS(i) { CHECK_EQ(2, r.Call(*i)); }
}
WASM_EXEC_TEST(Select_strict2) {
WasmRunner<int32_t> r(MachineType::Int32());
r.AllocateLocal(kAstI32);
r.AllocateLocal(kAstI32);
// select(b=5, c=6, a)
BUILD(r, WASM_SELECT(WASM_SET_LOCAL(1, WASM_I8(5)),
WASM_SET_LOCAL(2, WASM_I8(6)), WASM_GET_LOCAL(0)));
FOR_INT32_INPUTS(i) {
int32_t expected = *i ? 5 : 6;
CHECK_EQ(expected, r.Call(*i));
}
}
WASM_EXEC_TEST(Select_strict3) {
WasmRunner<int32_t> r(MachineType::Int32());
r.AllocateLocal(kAstI32);
r.AllocateLocal(kAstI32);
// select(b=5, c=6, a=b)
BUILD(r, WASM_SELECT(WASM_SET_LOCAL(1, WASM_I8(5)),
WASM_SET_LOCAL(2, WASM_I8(6)),
WASM_SET_LOCAL(0, WASM_GET_LOCAL(1))));
FOR_INT32_INPUTS(i) {
int32_t expected = 5;
CHECK_EQ(expected, r.Call(*i));
}
}
WASM_EXEC_TEST(BrIf_strict) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(
r,
B2(B1(WASM_BRV_IF(0, WASM_GET_LOCAL(0), WASM_SET_LOCAL(0, WASM_I8(99)))),
WASM_GET_LOCAL(0)));
FOR_INT32_INPUTS(i) { CHECK_EQ(99, r.Call(*i)); }
}
WASM_EXEC_TEST(BrTable0a) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r,
B2(B1(WASM_BR_TABLE(WASM_GET_LOCAL(0), 0, BR_TARGET(0))), WASM_I8(91)));
FOR_INT32_INPUTS(i) { CHECK_EQ(91, r.Call(*i)); }
}
WASM_EXEC_TEST(BrTable0b) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r,
B2(B1(WASM_BR_TABLE(WASM_GET_LOCAL(0), 1, BR_TARGET(0), BR_TARGET(0))),
WASM_I8(92)));
FOR_INT32_INPUTS(i) { CHECK_EQ(92, r.Call(*i)); }
}
WASM_EXEC_TEST(BrTable0c) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(
r,
B2(B2(B1(WASM_BR_TABLE(WASM_GET_LOCAL(0), 1, BR_TARGET(0), BR_TARGET(1))),
RET_I8(76)),
WASM_I8(77)));
FOR_INT32_INPUTS(i) {
int32_t expected = *i == 0 ? 76 : 77;
CHECK_EQ(expected, r.Call(*i));
}
}
WASM_EXEC_TEST(BrTable1) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, B1(WASM_BR_TABLE(WASM_GET_LOCAL(0), 0, BR_TARGET(0))), RET_I8(93));
FOR_INT32_INPUTS(i) { CHECK_EQ(93, r.Call(*i)); }
}
WASM_EXEC_TEST(BrTable_loop) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r,
B2(WASM_LOOP(1, WASM_BR_TABLE(WASM_INC_LOCAL_BY(0, 1), 2, BR_TARGET(2),
BR_TARGET(1), BR_TARGET(0))),
RET_I8(99)),
WASM_I8(98));
CHECK_EQ(99, r.Call(0));
CHECK_EQ(98, r.Call(-1));
CHECK_EQ(98, r.Call(-2));
CHECK_EQ(98, r.Call(-3));
CHECK_EQ(98, r.Call(-100));
}
WASM_EXEC_TEST(BrTable_br) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r,
B2(B1(WASM_BR_TABLE(WASM_GET_LOCAL(0), 1, BR_TARGET(1), BR_TARGET(0))),
RET_I8(91)),
WASM_I8(99));
CHECK_EQ(99, r.Call(0));
CHECK_EQ(91, r.Call(1));
CHECK_EQ(91, r.Call(2));
CHECK_EQ(91, r.Call(3));
}
WASM_EXEC_TEST(BrTable_br2) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, B2(B2(B2(B1(WASM_BR_TABLE(WASM_GET_LOCAL(0), 3, BR_TARGET(1),
BR_TARGET(2), BR_TARGET(3), BR_TARGET(0))),
RET_I8(85)),
RET_I8(86)),
RET_I8(87)),
WASM_I8(88));
CHECK_EQ(86, r.Call(0));
CHECK_EQ(87, r.Call(1));
CHECK_EQ(88, r.Call(2));
CHECK_EQ(85, r.Call(3));
CHECK_EQ(85, r.Call(4));
CHECK_EQ(85, r.Call(5));
}
WASM_EXEC_TEST(BrTable4) {
for (int i = 0; i < 4; i++) {
for (int t = 0; t < 4; t++) {
uint32_t cases[] = {0, 1, 2, 3};
cases[i] = t;
byte code[] = {B2(B2(B2(B2(B1(WASM_BR_TABLE(
WASM_GET_LOCAL(0), 3, BR_TARGET(cases[0]),
BR_TARGET(cases[1]), BR_TARGET(cases[2]),
BR_TARGET(cases[3]))),
RET_I8(70)),
RET_I8(71)),
RET_I8(72)),
RET_I8(73)),
WASM_I8(75)};
WasmRunner<int32_t> r(MachineType::Int32());
r.Build(code, code + arraysize(code));
for (int x = -3; x < 50; x++) {
int index = (x > 3 || x < 0) ? 3 : x;
int32_t expected = 70 + cases[index];
CHECK_EQ(expected, r.Call(x));
}
}
}
}
WASM_EXEC_TEST(BrTable4x4) {
for (byte a = 0; a < 4; a++) {
for (byte b = 0; b < 4; b++) {
for (byte c = 0; c < 4; c++) {
for (byte d = 0; d < 4; d++) {
for (int i = 0; i < 4; i++) {
uint32_t cases[] = {a, b, c, d};
byte code[] = {
B2(B2(B2(B2(B1(WASM_BR_TABLE(
WASM_GET_LOCAL(0), 3, BR_TARGET(cases[0]),
BR_TARGET(cases[1]), BR_TARGET(cases[2]),
BR_TARGET(cases[3]))),
RET_I8(50)),
RET_I8(51)),
RET_I8(52)),
RET_I8(53)),
WASM_I8(55)};
WasmRunner<int32_t> r(MachineType::Int32());
r.Build(code, code + arraysize(code));
for (int x = -6; x < 47; x++) {
int index = (x > 3 || x < 0) ? 3 : x;
int32_t expected = 50 + cases[index];
CHECK_EQ(expected, r.Call(x));
}
}
}
}
}
}
}
WASM_EXEC_TEST(BrTable4_fallthru) {
byte code[] = {
B2(B2(B2(B2(B1(WASM_BR_TABLE(WASM_GET_LOCAL(0), 3, BR_TARGET(0),
BR_TARGET(1), BR_TARGET(2), BR_TARGET(3))),
WASM_INC_LOCAL_BY(1, 1)),
WASM_INC_LOCAL_BY(1, 2)),
WASM_INC_LOCAL_BY(1, 4)),
WASM_INC_LOCAL_BY(1, 8)),
WASM_GET_LOCAL(1)};
WasmRunner<int32_t> r(MachineType::Int32(), MachineType::Int32());
r.Build(code, code + arraysize(code));
CHECK_EQ(15, r.Call(0, 0));
CHECK_EQ(14, r.Call(1, 0));
CHECK_EQ(12, r.Call(2, 0));
CHECK_EQ(8, r.Call(3, 0));
CHECK_EQ(8, r.Call(4, 0));
CHECK_EQ(115, r.Call(0, 100));
CHECK_EQ(114, r.Call(1, 100));
CHECK_EQ(112, r.Call(2, 100));
CHECK_EQ(108, r.Call(3, 100));
CHECK_EQ(108, r.Call(4, 100));
}
WASM_EXEC_TEST(F32ReinterpretI32) {
TestingModule module;
int32_t* memory = module.AddMemoryElems<int32_t>(8);
WasmRunner<int32_t> r(&module);
BUILD(r, WASM_I32_REINTERPRET_F32(
WASM_LOAD_MEM(MachineType::Float32(), WASM_ZERO)));
FOR_INT32_INPUTS(i) {
int32_t expected = *i;
memory[0] = expected;
CHECK_EQ(expected, r.Call());
}
}
WASM_EXEC_TEST(I32ReinterpretF32) {
TestingModule module;
int32_t* memory = module.AddMemoryElems<int32_t>(8);
WasmRunner<int32_t> r(&module, MachineType::Int32());
BUILD(r, WASM_BLOCK(
2, WASM_STORE_MEM(MachineType::Float32(), WASM_ZERO,
WASM_F32_REINTERPRET_I32(WASM_GET_LOCAL(0))),
WASM_I8(107)));
FOR_INT32_INPUTS(i) {
int32_t expected = *i;
CHECK_EQ(107, r.Call(expected));
CHECK_EQ(expected, memory[0]);
}
}
WASM_EXEC_TEST(ReturnStore) {
TestingModule module;
int32_t* memory = module.AddMemoryElems<int32_t>(8);
WasmRunner<int32_t> r(&module);
BUILD(r, WASM_STORE_MEM(MachineType::Int32(), WASM_ZERO,
WASM_LOAD_MEM(MachineType::Int32(), WASM_ZERO)));
FOR_INT32_INPUTS(i) {
int32_t expected = *i;
memory[0] = expected;
CHECK_EQ(expected, r.Call());
}
}
WASM_EXEC_TEST(VoidReturn1) {
// We use a wrapper function because WasmRunner<void> does not exist.
// Build the test function.
TestSignatures sigs;
TestingModule module;
WasmFunctionCompiler t(sigs.v_v(), &module);
BUILD(t, kExprNop);
uint32_t index = t.CompileAndAdd();
const int32_t kExpected = -414444;
// Build the calling function.
WasmRunner<int32_t> r(&module);
BUILD(r, B2(WASM_CALL_FUNCTION0(index), WASM_I32V_3(kExpected)));
int32_t result = r.Call();
CHECK_EQ(kExpected, result);
}
WASM_EXEC_TEST(VoidReturn2) {
// We use a wrapper function because WasmRunner<void> does not exist.
// Build the test function.
TestSignatures sigs;
TestingModule module;
WasmFunctionCompiler t(sigs.v_v(), &module);
BUILD(t, WASM_RETURN0);
uint32_t index = t.CompileAndAdd();
const int32_t kExpected = -414444;
// Build the calling function.
WasmRunner<int32_t> r(&module);
BUILD(r, B2(WASM_CALL_FUNCTION0(index), WASM_I32V_3(kExpected)));
int32_t result = r.Call();
CHECK_EQ(kExpected, result);
}
WASM_EXEC_TEST(Block_empty) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, kExprBlock, kExprEnd, WASM_GET_LOCAL(0));
FOR_INT32_INPUTS(i) { CHECK_EQ(*i, r.Call(*i)); }
}
WASM_EXEC_TEST(Block_empty_br1) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, B1(WASM_BR(0)), WASM_GET_LOCAL(0));
FOR_INT32_INPUTS(i) { CHECK_EQ(*i, r.Call(*i)); }
}
WASM_EXEC_TEST(Block_empty_brif1) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, B1(WASM_BR_IF(0, WASM_ZERO)), WASM_GET_LOCAL(0));
FOR_INT32_INPUTS(i) { CHECK_EQ(*i, r.Call(*i)); }
}
WASM_EXEC_TEST(Block_empty_brif2) {
WasmRunner<uint32_t> r(MachineType::Uint32(), MachineType::Uint32());
BUILD(r, B1(WASM_BR_IF(0, WASM_GET_LOCAL(1))), WASM_GET_LOCAL(0));
FOR_INT32_INPUTS(i) { CHECK_EQ(*i, r.Call(*i, *i + 1)); }
}
WASM_EXEC_TEST(Block_br2) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, B1(WASM_BRV(0, WASM_GET_LOCAL(0))));
FOR_UINT32_INPUTS(i) { CHECK_EQ(*i, r.Call(*i)); }
}
WASM_EXEC_TEST(Block_If_P) {
WasmRunner<int32_t> r(MachineType::Int32());
// { if (p0) return 51; return 52; }
BUILD(r, B2( // --
WASM_IF(WASM_GET_LOCAL(0), // --
WASM_BRV(1, WASM_I8(51))), // --
WASM_I8(52))); // --
FOR_INT32_INPUTS(i) {
int32_t expected = *i ? 51 : 52;
CHECK_EQ(expected, r.Call(*i));
}
}
WASM_EXEC_TEST(Loop_empty) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, kExprLoop, kExprEnd, WASM_GET_LOCAL(0));
FOR_INT32_INPUTS(i) { CHECK_EQ(*i, r.Call(*i)); }
}
WASM_EXEC_TEST(Loop_empty_br1) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, WASM_LOOP(1, WASM_BR(1)), WASM_GET_LOCAL(0));
FOR_INT32_INPUTS(i) { CHECK_EQ(*i, r.Call(*i)); }
}
WASM_EXEC_TEST(Loop_empty_brif1) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, WASM_LOOP(1, WASM_BR_IF(1, WASM_ZERO)), WASM_GET_LOCAL(0));
FOR_INT32_INPUTS(i) { CHECK_EQ(*i, r.Call(*i)); }
}
WASM_EXEC_TEST(Loop_empty_brif2) {
WasmRunner<uint32_t> r(MachineType::Uint32(), MachineType::Uint32());
BUILD(r, WASM_LOOP(1, WASM_BR_IF(1, WASM_GET_LOCAL(1))), WASM_GET_LOCAL(0));
FOR_UINT32_INPUTS(i) { CHECK_EQ(*i, r.Call(*i, *i + 1)); }
}
WASM_EXEC_TEST(Block_BrIf_P) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, B2(WASM_BRV_IF(0, WASM_I8(51), WASM_GET_LOCAL(0)), WASM_I8(52)));
FOR_INT32_INPUTS(i) {
int32_t expected = *i ? 51 : 52;
CHECK_EQ(expected, r.Call(*i));
}
}
WASM_EXEC_TEST(Block_IfElse_P_assign) {
WasmRunner<int32_t> r(MachineType::Int32());
// { if (p0) p0 = 71; else p0 = 72; return p0; }
BUILD(r, B2( // --
WASM_IF_ELSE(WASM_GET_LOCAL(0), // --
WASM_SET_LOCAL(0, WASM_I8(71)), // --
WASM_SET_LOCAL(0, WASM_I8(72))), // --
WASM_GET_LOCAL(0)));
FOR_INT32_INPUTS(i) {
int32_t expected = *i ? 71 : 72;
CHECK_EQ(expected, r.Call(*i));
}
}
WASM_EXEC_TEST(Block_IfElse_P_return) {
WasmRunner<int32_t> r(MachineType::Int32());
// if (p0) return 81; else return 82;
BUILD(r, // --
WASM_IF_ELSE(WASM_GET_LOCAL(0), // --
RET_I8(81), // --
RET_I8(82))); // --
FOR_INT32_INPUTS(i) {
int32_t expected = *i ? 81 : 82;
CHECK_EQ(expected, r.Call(*i));
}
}
WASM_EXEC_TEST(Block_If_P_assign) {
WasmRunner<int32_t> r(MachineType::Int32());
// { if (p0) p0 = 61; p0; }
BUILD(r, WASM_BLOCK(
2, WASM_IF(WASM_GET_LOCAL(0), WASM_SET_LOCAL(0, WASM_I8(61))),
WASM_GET_LOCAL(0)));
FOR_INT32_INPUTS(i) {
int32_t expected = *i ? 61 : *i;
CHECK_EQ(expected, r.Call(*i));
}
}
WASM_EXEC_TEST(DanglingAssign) {
WasmRunner<int32_t> r(MachineType::Int32());
// { return 0; p0 = 0; }
BUILD(r, B2(RET_I8(99), WASM_SET_LOCAL(0, WASM_ZERO)));
CHECK_EQ(99, r.Call(1));
}
WASM_EXEC_TEST(ExprIf_P) {
WasmRunner<int32_t> r(MachineType::Int32());
// p0 ? 11 : 22;
BUILD(r, WASM_IF_ELSE(WASM_GET_LOCAL(0), // --
WASM_I8(11), // --
WASM_I8(22))); // --
FOR_INT32_INPUTS(i) {
int32_t expected = *i ? 11 : 22;
CHECK_EQ(expected, r.Call(*i));
}
}
WASM_EXEC_TEST(ExprIf_P_fallthru) {
WasmRunner<int32_t> r(MachineType::Int32());
// p0 ? 11 : 22;
BUILD(r, WASM_IF_ELSE(WASM_GET_LOCAL(0), // --
WASM_I8(11), // --
WASM_I8(22))); // --
FOR_INT32_INPUTS(i) {
int32_t expected = *i ? 11 : 22;
CHECK_EQ(expected, r.Call(*i));
}
}
WASM_EXEC_TEST(CountDown) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r,
WASM_BLOCK(
2, WASM_LOOP(
1, WASM_IF(WASM_GET_LOCAL(0),
WASM_BRV(1, WASM_SET_LOCAL(
0, WASM_I32_SUB(WASM_GET_LOCAL(0),
WASM_I8(1)))))),
WASM_GET_LOCAL(0)));
CHECK_EQ(0, r.Call(1));
CHECK_EQ(0, r.Call(10));
CHECK_EQ(0, r.Call(100));
}
WASM_EXEC_TEST(CountDown_fallthru) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r,
WASM_BLOCK(
2, WASM_LOOP(3, WASM_IF(WASM_NOT(WASM_GET_LOCAL(0)), WASM_BREAK(1)),
WASM_SET_LOCAL(
0, WASM_I32_SUB(WASM_GET_LOCAL(0), WASM_I8(1))),
WASM_CONTINUE(0)),
WASM_GET_LOCAL(0)));
CHECK_EQ(0, r.Call(1));
CHECK_EQ(0, r.Call(10));
CHECK_EQ(0, r.Call(100));
}
WASM_EXEC_TEST(WhileCountDown) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, WASM_BLOCK(
2, WASM_WHILE(WASM_GET_LOCAL(0),
WASM_SET_LOCAL(0, WASM_I32_SUB(WASM_GET_LOCAL(0),
WASM_I8(1)))),
WASM_GET_LOCAL(0)));
CHECK_EQ(0, r.Call(1));
CHECK_EQ(0, r.Call(10));
CHECK_EQ(0, r.Call(100));
}
WASM_EXEC_TEST(Loop_if_break1) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, B2(WASM_LOOP(2, WASM_IF(WASM_GET_LOCAL(0), WASM_BREAK(1)),
WASM_SET_LOCAL(0, WASM_I8(99))),
WASM_GET_LOCAL(0)));
CHECK_EQ(99, r.Call(0));
CHECK_EQ(3, r.Call(3));
CHECK_EQ(10000, r.Call(10000));
CHECK_EQ(-29, r.Call(-29));
}
WASM_EXEC_TEST(Loop_if_break2) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, B2(WASM_LOOP(2, WASM_BR_IF(1, WASM_GET_LOCAL(0)),
WASM_SET_LOCAL(0, WASM_I8(99))),
WASM_GET_LOCAL(0)));
CHECK_EQ(99, r.Call(0));
CHECK_EQ(3, r.Call(3));
CHECK_EQ(10000, r.Call(10000));
CHECK_EQ(-29, r.Call(-29));
}
WASM_EXEC_TEST(Loop_if_break_fallthru) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, B1(WASM_LOOP(2, WASM_IF(WASM_GET_LOCAL(0), WASM_BREAK(1)),
WASM_SET_LOCAL(0, WASM_I8(93)))),
WASM_GET_LOCAL(0));
CHECK_EQ(93, r.Call(0));
CHECK_EQ(3, r.Call(3));
CHECK_EQ(10001, r.Call(10001));
CHECK_EQ(-22, r.Call(-22));
}
WASM_EXEC_TEST(IfBreak1) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, WASM_IF(WASM_GET_LOCAL(0), WASM_SEQ(WASM_BR(0), WASM_UNREACHABLE)),
WASM_I8(91));
CHECK_EQ(91, r.Call(0));
CHECK_EQ(91, r.Call(1));
CHECK_EQ(91, r.Call(-8734));
}
WASM_EXEC_TEST(IfBreak2) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, WASM_IF(WASM_GET_LOCAL(0), WASM_SEQ(WASM_BR(0), RET_I8(77))),
WASM_I8(81));
CHECK_EQ(81, r.Call(0));
CHECK_EQ(81, r.Call(1));
CHECK_EQ(81, r.Call(-8734));
}
WASM_EXEC_TEST(LoadMemI32) {
TestingModule module;
int32_t* memory = module.AddMemoryElems<int32_t>(8);
WasmRunner<int32_t> r(&module, MachineType::Int32());
module.RandomizeMemory(1111);
BUILD(r, WASM_LOAD_MEM(MachineType::Int32(), WASM_I8(0)));
memory[0] = 99999999;
CHECK_EQ(99999999, r.Call(0));
memory[0] = 88888888;
CHECK_EQ(88888888, r.Call(0));
memory[0] = 77777777;
CHECK_EQ(77777777, r.Call(0));
}
WASM_EXEC_TEST(LoadMemI32_oob) {
TestingModule module;
int32_t* memory = module.AddMemoryElems<int32_t>(8);
WasmRunner<int32_t> r(&module, MachineType::Uint32());
module.RandomizeMemory(1111);
BUILD(r, WASM_LOAD_MEM(MachineType::Int32(), WASM_GET_LOCAL(0)));
memory[0] = 88888888;
CHECK_EQ(88888888, r.Call(0u));
for (uint32_t offset = 29; offset < 40; offset++) {
CHECK_TRAP(r.Call(offset));
}
for (uint32_t offset = 0x80000000; offset < 0x80000010; offset++) {
CHECK_TRAP(r.Call(offset));
}
}
WASM_EXEC_TEST(LoadMem_offset_oob) {
TestingModule module;
module.AddMemoryElems<int32_t>(8);
static const MachineType machineTypes[] = {
MachineType::Int8(), MachineType::Uint8(), MachineType::Int16(),
MachineType::Uint16(), MachineType::Int32(), MachineType::Uint32(),
MachineType::Int64(), MachineType::Uint64(), MachineType::Float32(),
MachineType::Float64()};
for (size_t m = 0; m < arraysize(machineTypes); m++) {
module.RandomizeMemory(1116 + static_cast<int>(m));
WasmRunner<int32_t> r(&module, MachineType::Uint32());
uint32_t boundary = 24 - WasmOpcodes::MemSize(machineTypes[m]);
BUILD(r, WASM_LOAD_MEM_OFFSET(machineTypes[m], 8, WASM_GET_LOCAL(0)),
WASM_ZERO);
CHECK_EQ(0, r.Call(boundary)); // in bounds.
for (uint32_t offset = boundary + 1; offset < boundary + 19; offset++) {
CHECK_TRAP(r.Call(offset)); // out of bounds.
}
}
}
WASM_EXEC_TEST(LoadMemI32_offset) {
TestingModule module;
int32_t* memory = module.AddMemoryElems<int32_t>(4);
WasmRunner<int32_t> r(&module, MachineType::Int32());
module.RandomizeMemory(1111);
BUILD(r, WASM_LOAD_MEM_OFFSET(MachineType::Int32(), 4, WASM_GET_LOCAL(0)));
memory[0] = 66666666;
memory[1] = 77777777;
memory[2] = 88888888;
memory[3] = 99999999;
CHECK_EQ(77777777, r.Call(0));
CHECK_EQ(88888888, r.Call(4));
CHECK_EQ(99999999, r.Call(8));
memory[0] = 11111111;
memory[1] = 22222222;
memory[2] = 33333333;
memory[3] = 44444444;
CHECK_EQ(22222222, r.Call(0));
CHECK_EQ(33333333, r.Call(4));
CHECK_EQ(44444444, r.Call(8));
}
#if !V8_TARGET_ARCH_MIPS && !V8_TARGET_ARCH_MIPS64
WASM_EXEC_TEST(LoadMemI32_const_oob_misaligned) {
const int kMemSize = 12;
// TODO(titzer): Fix misaligned accesses on MIPS and re-enable.
for (int offset = 0; offset < kMemSize + 5; offset++) {
for (int index = 0; index < kMemSize + 5; index++) {
TestingModule module;
module.AddMemoryElems<byte>(kMemSize);
WasmRunner<int32_t> r(&module);
module.RandomizeMemory();
BUILD(r,
WASM_LOAD_MEM_OFFSET(MachineType::Int32(), offset, WASM_I8(index)));
if ((offset + index) <= (kMemSize - sizeof(int32_t))) {
CHECK_EQ(module.raw_val_at<int32_t>(offset + index), r.Call());
} else {
CHECK_TRAP(r.Call());
}
}
}
}
#endif
WASM_EXEC_TEST(LoadMemI32_const_oob) {
const int kMemSize = 24;
for (int offset = 0; offset < kMemSize + 5; offset += 4) {
for (int index = 0; index < kMemSize + 5; index += 4) {
TestingModule module;
module.AddMemoryElems<byte>(kMemSize);
WasmRunner<int32_t> r(&module);
module.RandomizeMemory();
BUILD(r,
WASM_LOAD_MEM_OFFSET(MachineType::Int32(), offset, WASM_I8(index)));
if ((offset + index) <= (kMemSize - sizeof(int32_t))) {
CHECK_EQ(module.raw_val_at<int32_t>(offset + index), r.Call());
} else {
CHECK_TRAP(r.Call());
}
}
}
}
WASM_EXEC_TEST(StoreMemI32_offset) {
TestingModule module;
int32_t* memory = module.AddMemoryElems<int32_t>(4);
WasmRunner<int32_t> r(&module, MachineType::Int32());
const int32_t kWritten = 0xaabbccdd;
BUILD(r, WASM_STORE_MEM_OFFSET(MachineType::Int32(), 4, WASM_GET_LOCAL(0),
WASM_I32V_5(kWritten)));
for (int i = 0; i < 2; i++) {
module.RandomizeMemory(1111);
memory[0] = 66666666;
memory[1] = 77777777;
memory[2] = 88888888;
memory[3] = 99999999;
CHECK_EQ(kWritten, r.Call(i * 4));
CHECK_EQ(66666666, memory[0]);
CHECK_EQ(i == 0 ? kWritten : 77777777, memory[1]);
CHECK_EQ(i == 1 ? kWritten : 88888888, memory[2]);
CHECK_EQ(i == 2 ? kWritten : 99999999, memory[3]);
}
}
WASM_EXEC_TEST(StoreMem_offset_oob) {
TestingModule module;
byte* memory = module.AddMemoryElems<byte>(32);
#if WASM_64
static const MachineType machineTypes[] = {
MachineType::Int8(), MachineType::Uint8(), MachineType::Int16(),
MachineType::Uint16(), MachineType::Int32(), MachineType::Uint32(),
MachineType::Int64(), MachineType::Uint64(), MachineType::Float32(),
MachineType::Float64()};
#else
static const MachineType machineTypes[] = {
MachineType::Int8(), MachineType::Uint8(), MachineType::Int16(),
MachineType::Uint16(), MachineType::Int32(), MachineType::Uint32(),
MachineType::Float32(), MachineType::Float64()};
#endif
for (size_t m = 0; m < arraysize(machineTypes); m++) {
module.RandomizeMemory(1119 + static_cast<int>(m));
WasmRunner<int32_t> r(&module, MachineType::Uint32());
BUILD(r, WASM_STORE_MEM_OFFSET(machineTypes[m], 8, WASM_GET_LOCAL(0),
WASM_LOAD_MEM(machineTypes[m], WASM_ZERO)),
WASM_ZERO);
byte memsize = WasmOpcodes::MemSize(machineTypes[m]);
uint32_t boundary = 24 - memsize;
CHECK_EQ(0, r.Call(boundary)); // in bounds.
CHECK_EQ(0, memcmp(&memory[0], &memory[8 + boundary], memsize));
for (uint32_t offset = boundary + 1; offset < boundary + 19; offset++) {
CHECK_TRAP(r.Call(offset)); // out of bounds.
}
}
}
WASM_EXEC_TEST(LoadMemI32_P) {
const int kNumElems = 8;
TestingModule module;
int32_t* memory = module.AddMemoryElems<int32_t>(kNumElems);
WasmRunner<int32_t> r(&module, MachineType::Int32());
module.RandomizeMemory(2222);
BUILD(r, WASM_LOAD_MEM(MachineType::Int32(), WASM_GET_LOCAL(0)));
for (int i = 0; i < kNumElems; i++) {
CHECK_EQ(memory[i], r.Call(i * 4));
}
}
WASM_EXEC_TEST(MemI32_Sum) {
const int kNumElems = 20;
TestingModule module;
uint32_t* memory = module.AddMemoryElems<uint32_t>(kNumElems);
WasmRunner<uint32_t> r(&module, MachineType::Int32());
const byte kSum = r.AllocateLocal(kAstI32);
BUILD(r, WASM_BLOCK(
2, WASM_WHILE(
WASM_GET_LOCAL(0),
WASM_BLOCK(
2, WASM_SET_LOCAL(
kSum, WASM_I32_ADD(
WASM_GET_LOCAL(kSum),
WASM_LOAD_MEM(MachineType::Int32(),
WASM_GET_LOCAL(0)))),
WASM_SET_LOCAL(
0, WASM_I32_SUB(WASM_GET_LOCAL(0), WASM_I8(4))))),
WASM_GET_LOCAL(1)));
// Run 4 trials.
for (int i = 0; i < 3; i++) {
module.RandomizeMemory(i * 33);
uint32_t expected = 0;
for (size_t j = kNumElems - 1; j > 0; j--) {
expected += memory[j];
}
uint32_t result = r.Call(static_cast<int>(4 * (kNumElems - 1)));
CHECK_EQ(expected, result);
}
}
WASM_EXEC_TEST(CheckMachIntsZero) {
const int kNumElems = 55;
TestingModule module;
module.AddMemoryElems<uint32_t>(kNumElems);
WasmRunner<uint32_t> r(&module, MachineType::Int32());
BUILD(r, kExprLoop, kExprGetLocal, 0, kExprIf, kExprGetLocal, 0,
kExprI32LoadMem, 0, 0, kExprIf, kExprI8Const, 255, kExprReturn, ARITY_1,
kExprEnd, kExprGetLocal, 0, kExprI8Const, 4, kExprI32Sub, kExprSetLocal,
0, kExprBr, ARITY_1, DEPTH_0, kExprEnd, kExprEnd, kExprI8Const, 0);
module.BlankMemory();
CHECK_EQ(0, r.Call((kNumElems - 1) * 4));
}
WASM_EXEC_TEST(MemF32_Sum) {
const int kSize = 5;
TestingModule module;
module.AddMemoryElems<float>(kSize);
float* buffer = module.raw_mem_start<float>();
buffer[0] = -99.25;
buffer[1] = -888.25;
buffer[2] = -77.25;
buffer[3] = 66666.25;
buffer[4] = 5555.25;
WasmRunner<int32_t> r(&module, MachineType::Int32());
const byte kSum = r.AllocateLocal(kAstF32);
BUILD(r, WASM_BLOCK(
3, WASM_WHILE(
WASM_GET_LOCAL(0),
WASM_BLOCK(
2, WASM_SET_LOCAL(
kSum, WASM_F32_ADD(
WASM_GET_LOCAL(kSum),
WASM_LOAD_MEM(MachineType::Float32(),
WASM_GET_LOCAL(0)))),
WASM_SET_LOCAL(
0, WASM_I32_SUB(WASM_GET_LOCAL(0), WASM_I8(4))))),
WASM_STORE_MEM(MachineType::Float32(), WASM_ZERO,
WASM_GET_LOCAL(kSum)),
WASM_GET_LOCAL(0)));
CHECK_EQ(0, r.Call(4 * (kSize - 1)));
CHECK_NE(-99.25, buffer[0]);
CHECK_EQ(71256.0f, buffer[0]);
}
template <typename T>
T GenerateAndRunFold(WasmOpcode binop, T* buffer, size_t size,
LocalType astType, MachineType memType) {
TestingModule module;
module.AddMemoryElems<T>(size);
for (size_t i = 0; i < size; i++) {
module.raw_mem_start<T>()[i] = buffer[i];
}
WasmRunner<int32_t> r(&module, MachineType::Int32());
const byte kAccum = r.AllocateLocal(astType);
BUILD(
r,
WASM_BLOCK(
4, WASM_SET_LOCAL(kAccum, WASM_LOAD_MEM(memType, WASM_ZERO)),
WASM_WHILE(
WASM_GET_LOCAL(0),
WASM_BLOCK(
2, WASM_SET_LOCAL(
kAccum,
WASM_BINOP(binop, WASM_GET_LOCAL(kAccum),
WASM_LOAD_MEM(memType, WASM_GET_LOCAL(0)))),
WASM_SET_LOCAL(
0, WASM_I32_SUB(WASM_GET_LOCAL(0), WASM_I8(sizeof(T)))))),
WASM_STORE_MEM(memType, WASM_ZERO, WASM_GET_LOCAL(kAccum)),
WASM_GET_LOCAL(0)));
r.Call(static_cast<int>(sizeof(T) * (size - 1)));
return module.raw_mem_at<double>(0);
}
WASM_EXEC_TEST(MemF64_Mul) {
const size_t kSize = 6;
double buffer[kSize] = {1, 2, 2, 2, 2, 2};
double result = GenerateAndRunFold<double>(kExprF64Mul, buffer, kSize,
kAstF64, MachineType::Float64());
CHECK_EQ(32, result);
}
TEST(Build_Wasm_Infinite_Loop) {
WasmRunner<int32_t> r(MachineType::Int32());
// Only build the graph and compile, don't run.
BUILD(r, WASM_INFINITE_LOOP);
}
TEST(Build_Wasm_Infinite_Loop_effect) {
TestingModule module;
module.AddMemoryElems<int8_t>(16);
WasmRunner<int32_t> r(&module, MachineType::Int32());
// Only build the graph and compile, don't run.
BUILD(r, WASM_LOOP(1, WASM_LOAD_MEM(MachineType::Int32(), WASM_ZERO)));
}
WASM_EXEC_TEST(Unreachable0a) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, B2(WASM_BRV(0, WASM_I8(9)), RET(WASM_GET_LOCAL(0))));
CHECK_EQ(9, r.Call(0));
CHECK_EQ(9, r.Call(1));
}
WASM_EXEC_TEST(Unreachable0b) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, B2(WASM_BRV(0, WASM_I8(7)), WASM_UNREACHABLE));
CHECK_EQ(7, r.Call(0));
CHECK_EQ(7, r.Call(1));
}
TEST(Build_Wasm_Unreachable1) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, WASM_UNREACHABLE);
}
TEST(Build_Wasm_Unreachable2) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, WASM_UNREACHABLE, WASM_UNREACHABLE);
}
TEST(Build_Wasm_Unreachable3) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, WASM_UNREACHABLE, WASM_UNREACHABLE, WASM_UNREACHABLE);
}
TEST(Build_Wasm_UnreachableIf1) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, WASM_UNREACHABLE, WASM_IF(WASM_GET_LOCAL(0), WASM_GET_LOCAL(0)));
}
TEST(Build_Wasm_UnreachableIf2) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, WASM_UNREACHABLE,
WASM_IF_ELSE(WASM_GET_LOCAL(0), WASM_GET_LOCAL(0), WASM_UNREACHABLE));
}
WASM_EXEC_TEST(Unreachable_Load) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, B2(WASM_BRV(0, WASM_GET_LOCAL(0)),
WASM_LOAD_MEM(MachineType::Int8(), WASM_GET_LOCAL(0))));
CHECK_EQ(11, r.Call(11));
CHECK_EQ(21, r.Call(21));
}
WASM_EXEC_TEST(Infinite_Loop_not_taken1) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, B2(WASM_IF(WASM_GET_LOCAL(0), WASM_INFINITE_LOOP), WASM_I8(45)));
// Run the code, but don't go into the infinite loop.
CHECK_EQ(45, r.Call(0));
}
WASM_EXEC_TEST(Infinite_Loop_not_taken2) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, B1(WASM_IF_ELSE(WASM_GET_LOCAL(0), WASM_BRV(1, WASM_I8(45)),
WASM_INFINITE_LOOP)));
// Run the code, but don't go into the infinite loop.
CHECK_EQ(45, r.Call(1));
}
WASM_EXEC_TEST(Infinite_Loop_not_taken2_brif) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r,
B2(WASM_BRV_IF(0, WASM_I8(45), WASM_GET_LOCAL(0)), WASM_INFINITE_LOOP));
// Run the code, but don't go into the infinite loop.
CHECK_EQ(45, r.Call(1));
}
static void TestBuildGraphForSimpleExpression(WasmOpcode opcode) {
Isolate* isolate = CcTest::InitIsolateOnce();
Zone zone(isolate->allocator());
HandleScope scope(isolate);
// Enable all optional operators.
CommonOperatorBuilder common(&zone);
MachineOperatorBuilder machine(&zone, MachineType::PointerRepresentation(),
MachineOperatorBuilder::kAllOptionalOps);
Graph graph(&zone);
JSGraph jsgraph(isolate, &graph, &common, nullptr, nullptr, &machine);
FunctionSig* sig = WasmOpcodes::Signature(opcode);
if (sig->parameter_count() == 1) {
byte code[] = {WASM_NO_LOCALS, kExprGetLocal, 0, static_cast<byte>(opcode)};
TestBuildingGraph(&zone, &jsgraph, nullptr, sig, nullptr, code,
code + arraysize(code));
} else {
CHECK_EQ(2, sig->parameter_count());
byte code[] = {WASM_NO_LOCALS, kExprGetLocal, 0, kExprGetLocal, 1,
static_cast<byte>(opcode)};
TestBuildingGraph(&zone, &jsgraph, nullptr, sig, nullptr, code,
code + arraysize(code));
}
}
TEST(Build_Wasm_SimpleExprs) {
// Test that the decoder can build a graph for all supported simple expressions.
#define GRAPH_BUILD_TEST(name, opcode, sig) \
TestBuildGraphForSimpleExpression(kExpr##name);
FOREACH_SIMPLE_OPCODE(GRAPH_BUILD_TEST);
#undef GRAPH_BUILD_TEST
}
WASM_EXEC_TEST(Int32LoadInt8_signext) {
TestingModule module;
const int kNumElems = 16;
int8_t* memory = module.AddMemoryElems<int8_t>(kNumElems);
module.RandomizeMemory();
memory[0] = -1;
WasmRunner<int32_t> r(&module, MachineType::Int32());
BUILD(r, WASM_LOAD_MEM(MachineType::Int8(), WASM_GET_LOCAL(0)));
for (size_t i = 0; i < kNumElems; i++) {
CHECK_EQ(memory[i], r.Call(static_cast<int>(i)));
}
}
WASM_EXEC_TEST(Int32LoadInt8_zeroext) {
TestingModule module;
const int kNumElems = 16;
byte* memory = module.AddMemory(kNumElems);
module.RandomizeMemory(77);
memory[0] = 255;
WasmRunner<int32_t> r(&module, MachineType::Int32());
BUILD(r, WASM_LOAD_MEM(MachineType::Uint8(), WASM_GET_LOCAL(0)));
for (size_t i = 0; i < kNumElems; i++) {
CHECK_EQ(memory[i], r.Call(static_cast<int>(i)));
}
}
WASM_EXEC_TEST(Int32LoadInt16_signext) {
TestingModule module;
const int kNumBytes = 16;
byte* memory = module.AddMemory(kNumBytes);
module.RandomizeMemory(888);
memory[1] = 200;
WasmRunner<int32_t> r(&module, MachineType::Int32());
BUILD(r, WASM_LOAD_MEM(MachineType::Int16(), WASM_GET_LOCAL(0)));
for (size_t i = 0; i < kNumBytes; i += 2) {
int32_t expected = memory[i] | (static_cast<int8_t>(memory[i + 1]) << 8);
CHECK_EQ(expected, r.Call(static_cast<int>(i)));
}
}
WASM_EXEC_TEST(Int32LoadInt16_zeroext) {
TestingModule module;
const int kNumBytes = 16;
byte* memory = module.AddMemory(kNumBytes);
module.RandomizeMemory(9999);
memory[1] = 204;
WasmRunner<int32_t> r(&module, MachineType::Int32());
BUILD(r, WASM_LOAD_MEM(MachineType::Uint16(), WASM_GET_LOCAL(0)));
for (size_t i = 0; i < kNumBytes; i += 2) {
int32_t expected = memory[i] | (memory[i + 1] << 8);
CHECK_EQ(expected, r.Call(static_cast<int>(i)));
}
}
WASM_EXEC_TEST(Int32Global) {
TestingModule module;
int32_t* global = module.AddGlobal<int32_t>(MachineType::Int32());
WasmRunner<int32_t> r(&module, MachineType::Int32());
// global = global + p0
BUILD(r, WASM_STORE_GLOBAL(
0, WASM_I32_ADD(WASM_LOAD_GLOBAL(0), WASM_GET_LOCAL(0))));
*global = 116;
for (int i = 9; i < 444444; i += 111111) {
int32_t expected = *global + i;
r.Call(i);
CHECK_EQ(expected, *global);
}
}
WASM_EXEC_TEST(Int32Globals_DontAlias) {
const int kNumGlobals = 3;
TestingModule module;
int32_t* globals[] = {module.AddGlobal<int32_t>(MachineType::Int32()),
module.AddGlobal<int32_t>(MachineType::Int32()),
module.AddGlobal<int32_t>(MachineType::Int32())};
for (int g = 0; g < kNumGlobals; g++) {
// global = global + p0
WasmRunner<int32_t> r(&module, MachineType::Int32());
BUILD(r, WASM_STORE_GLOBAL(
g, WASM_I32_ADD(WASM_LOAD_GLOBAL(g), WASM_GET_LOCAL(0))));
// Check that reading/writing global number {g} doesn't alter the others.
*globals[g] = 116 * g;
int32_t before[kNumGlobals];
for (int i = 9; i < 444444; i += 111113) {
int32_t sum = *globals[g] + i;
for (int j = 0; j < kNumGlobals; j++) before[j] = *globals[j];
r.Call(i);
for (int j = 0; j < kNumGlobals; j++) {
int32_t expected = j == g ? sum : before[j];
CHECK_EQ(expected, *globals[j]);
}
}
}
}
WASM_EXEC_TEST(Float32Global) {
TestingModule module;
float* global = module.AddGlobal<float>(MachineType::Float32());
WasmRunner<int32_t> r(&module, MachineType::Int32());
// global = global + p0
BUILD(r, B2(WASM_STORE_GLOBAL(
0, WASM_F32_ADD(WASM_LOAD_GLOBAL(0),
WASM_F32_SCONVERT_I32(WASM_GET_LOCAL(0)))),
WASM_ZERO));
*global = 1.25;
for (int i = 9; i < 4444; i += 1111) {
volatile float expected = *global + i;
r.Call(i);
CHECK_EQ(expected, *global);
}
}
WASM_EXEC_TEST(Float64Global) {
TestingModule module;
double* global = module.AddGlobal<double>(MachineType::Float64());
WasmRunner<int32_t> r(&module, MachineType::Int32());
// global = global + p0
BUILD(r, B2(WASM_STORE_GLOBAL(
0, WASM_F64_ADD(WASM_LOAD_GLOBAL(0),
WASM_F64_SCONVERT_I32(WASM_GET_LOCAL(0)))),
WASM_ZERO));
*global = 1.25;
for (int i = 9; i < 4444; i += 1111) {
volatile double expected = *global + i;
r.Call(i);
CHECK_EQ(expected, *global);
}
}
WASM_EXEC_TEST(MixedGlobals) {
TestingModule module;
int32_t* unused = module.AddGlobal<int32_t>(MachineType::Int32());
byte* memory = module.AddMemory(32);
int8_t* var_int8 = module.AddGlobal<int8_t>(MachineType::Int8());
uint8_t* var_uint8 = module.AddGlobal<uint8_t>(MachineType::Uint8());
int16_t* var_int16 = module.AddGlobal<int16_t>(MachineType::Int16());
uint16_t* var_uint16 = module.AddGlobal<uint16_t>(MachineType::Uint16());
int32_t* var_int32 = module.AddGlobal<int32_t>(MachineType::Int32());
uint32_t* var_uint32 = module.AddGlobal<uint32_t>(MachineType::Uint32());
float* var_float = module.AddGlobal<float>(MachineType::Float32());
double* var_double = module.AddGlobal<double>(MachineType::Float64());
WasmRunner<int32_t> r(&module, MachineType::Int32());
BUILD(
r,
WASM_BLOCK(
9,
WASM_STORE_GLOBAL(1, WASM_LOAD_MEM(MachineType::Int8(), WASM_ZERO)),
WASM_STORE_GLOBAL(2, WASM_LOAD_MEM(MachineType::Uint8(), WASM_ZERO)),
WASM_STORE_GLOBAL(3, WASM_LOAD_MEM(MachineType::Int16(), WASM_ZERO)),
WASM_STORE_GLOBAL(4, WASM_LOAD_MEM(MachineType::Uint16(), WASM_ZERO)),
WASM_STORE_GLOBAL(5, WASM_LOAD_MEM(MachineType::Int32(), WASM_ZERO)),
WASM_STORE_GLOBAL(6, WASM_LOAD_MEM(MachineType::Uint32(), WASM_ZERO)),
WASM_STORE_GLOBAL(7,
WASM_LOAD_MEM(MachineType::Float32(), WASM_ZERO)),
WASM_STORE_GLOBAL(8,
WASM_LOAD_MEM(MachineType::Float64(), WASM_ZERO)),
WASM_ZERO));
memory[0] = 0xaa;
memory[1] = 0xcc;
memory[2] = 0x55;
memory[3] = 0xee;
memory[4] = 0x33;
memory[5] = 0x22;
memory[6] = 0x11;
memory[7] = 0x99;
r.Call(1);
CHECK(static_cast<int8_t>(0xaa) == *var_int8);
CHECK(static_cast<uint8_t>(0xaa) == *var_uint8);
CHECK(static_cast<int16_t>(0xccaa) == *var_int16);
CHECK(static_cast<uint16_t>(0xccaa) == *var_uint16);
CHECK(static_cast<int32_t>(0xee55ccaa) == *var_int32);
CHECK(static_cast<uint32_t>(0xee55ccaa) == *var_uint32);
CHECK(bit_cast<float>(0xee55ccaa) == *var_float);
CHECK(bit_cast<double>(0x99112233ee55ccaaULL) == *var_double);
USE(unused);
}
WASM_EXEC_TEST(CallEmpty) {
const int32_t kExpected = -414444;
// Build the target function.
TestSignatures sigs;
TestingModule module;
WasmFunctionCompiler t(sigs.i_v(), &module);
BUILD(t, WASM_I32V_3(kExpected));
uint32_t index = t.CompileAndAdd();
// Build the calling function.
WasmRunner<int32_t> r(&module);
BUILD(r, WASM_CALL_FUNCTION0(index));
int32_t result = r.Call();
CHECK_EQ(kExpected, result);
}
WASM_EXEC_TEST(CallF32StackParameter) {
// Build the target function.
LocalType param_types[20];
for (int i = 0; i < 20; i++) param_types[i] = kAstF32;
FunctionSig sig(1, 19, param_types);
TestingModule module;
WasmFunctionCompiler t(&sig, &module);
BUILD(t, WASM_GET_LOCAL(17));
uint32_t index = t.CompileAndAdd();
// Build the calling function.
WasmRunner<float> r(&module);
BUILD(r, WASM_CALL_FUNCTIONN(
19, index, WASM_F32(1.0f), WASM_F32(2.0f), WASM_F32(4.0f),
WASM_F32(8.0f), WASM_F32(16.0f), WASM_F32(32.0f),
WASM_F32(64.0f), WASM_F32(128.0f), WASM_F32(256.0f),
WASM_F32(1.5f), WASM_F32(2.5f), WASM_F32(4.5f), WASM_F32(8.5f),
WASM_F32(16.5f), WASM_F32(32.5f), WASM_F32(64.5f),
WASM_F32(128.5f), WASM_F32(256.5f), WASM_F32(512.5f)));
float result = r.Call();
CHECK_EQ(256.5f, result);
}
WASM_EXEC_TEST(CallF64StackParameter) {
// Build the target function.
LocalType param_types[20];
for (int i = 0; i < 20; i++) param_types[i] = kAstF64;
FunctionSig sig(1, 19, param_types);
TestingModule module;
WasmFunctionCompiler t(&sig, &module);
BUILD(t, WASM_GET_LOCAL(17));
uint32_t index = t.CompileAndAdd();
// Build the calling function.
WasmRunner<double> r(&module);
BUILD(r, WASM_CALL_FUNCTIONN(19, index, WASM_F64(1.0), WASM_F64(2.0),
WASM_F64(4.0), WASM_F64(8.0), WASM_F64(16.0),
WASM_F64(32.0), WASM_F64(64.0), WASM_F64(128.0),
WASM_F64(256.0), WASM_F64(1.5), WASM_F64(2.5),
WASM_F64(4.5), WASM_F64(8.5), WASM_F64(16.5),
WASM_F64(32.5), WASM_F64(64.5), WASM_F64(128.5),
WASM_F64(256.5), WASM_F64(512.5)));
float result = r.Call();
CHECK_EQ(256.5, result);
}
WASM_EXEC_TEST(CallVoid) {
const byte kMemOffset = 8;
const int32_t kElemNum = kMemOffset / sizeof(int32_t);
const int32_t kExpected = -414444;
// Build the target function.
TestSignatures sigs;
TestingModule module;
module.AddMemory(16);
module.RandomizeMemory();
WasmFunctionCompiler t(sigs.v_v(), &module);
BUILD(t, WASM_STORE_MEM(MachineType::Int32(), WASM_I8(kMemOffset),
WASM_I32V_3(kExpected)));
uint32_t index = t.CompileAndAdd();
// Build the calling function.
WasmRunner<int32_t> r(&module);
BUILD(r, WASM_CALL_FUNCTION0(index),
WASM_LOAD_MEM(MachineType::Int32(), WASM_I8(kMemOffset)));
int32_t result = r.Call();
CHECK_EQ(kExpected, result);
CHECK_EQ(kExpected, module.raw_mem_start<int32_t>()[kElemNum]);
}
WASM_EXEC_TEST(Call_Int32Add) {
// Build the target function.
TestSignatures sigs;
TestingModule module;
WasmFunctionCompiler t(sigs.i_ii(), &module);
BUILD(t, WASM_I32_ADD(WASM_GET_LOCAL(0), WASM_GET_LOCAL(1)));
uint32_t index = t.CompileAndAdd();
// Build the caller function.
WasmRunner<int32_t> r(&module, MachineType::Int32(), MachineType::Int32());
BUILD(r, WASM_CALL_FUNCTION2(index, WASM_GET_LOCAL(0), WASM_GET_LOCAL(1)));
FOR_INT32_INPUTS(i) {
FOR_INT32_INPUTS(j) {
int32_t expected = static_cast<int32_t>(static_cast<uint32_t>(*i) +
static_cast<uint32_t>(*j));
CHECK_EQ(expected, r.Call(*i, *j));
}
}
}
WASM_EXEC_TEST(Call_Float32Sub) {
TestSignatures sigs;
TestingModule module;
WasmFunctionCompiler t(sigs.f_ff(), &module);
// Build the target function.
BUILD(t, WASM_F32_SUB(WASM_GET_LOCAL(0), WASM_GET_LOCAL(1)));
uint32_t index = t.CompileAndAdd();
// Builder the caller function.
WasmRunner<float> r(&module, MachineType::Float32(), MachineType::Float32());
BUILD(r, WASM_CALL_FUNCTION2(index, WASM_GET_LOCAL(0), WASM_GET_LOCAL(1)));
FOR_FLOAT32_INPUTS(i) {
FOR_FLOAT32_INPUTS(j) { CHECK_FLOAT_EQ(*i - *j, r.Call(*i, *j)); }
}
}
WASM_EXEC_TEST(Call_Float64Sub) {
TestingModule module;
double* memory = module.AddMemoryElems<double>(16);
WasmRunner<int32_t> r(&module);
BUILD(r, WASM_BLOCK(
2, WASM_STORE_MEM(
MachineType::Float64(), WASM_ZERO,
WASM_F64_SUB(
WASM_LOAD_MEM(MachineType::Float64(), WASM_ZERO),
WASM_LOAD_MEM(MachineType::Float64(), WASM_I8(8)))),
WASM_I8(107)));
FOR_FLOAT64_INPUTS(i) {
FOR_FLOAT64_INPUTS(j) {
memory[0] = *i;
memory[1] = *j;
double expected = *i - *j;
CHECK_EQ(107, r.Call());
if (expected != expected) {
CHECK(memory[0] != memory[0]);
} else {
CHECK_EQ(expected, memory[0]);
}
}
}
}
#define ADD_CODE(vec, ...) \
do { \
byte __buf[] = {__VA_ARGS__}; \
for (size_t i = 0; i < sizeof(__buf); i++) vec.push_back(__buf[i]); \
} while (false)
static void Run_WasmMixedCall_N(int start) {
const int kExpected = 6333;
const int kElemSize = 8;
TestSignatures sigs;
#if WASM_64
static MachineType mixed[] = {
MachineType::Int32(), MachineType::Float32(), MachineType::Int64(),
MachineType::Float64(), MachineType::Float32(), MachineType::Int64(),
MachineType::Int32(), MachineType::Float64(), MachineType::Float32(),
MachineType::Float64(), MachineType::Int32(), MachineType::Int64(),
MachineType::Int32(), MachineType::Int32()};
#else
static MachineType mixed[] = {
MachineType::Int32(), MachineType::Float32(), MachineType::Float64(),
MachineType::Float32(), MachineType::Int32(), MachineType::Float64(),
MachineType::Float32(), MachineType::Float64(), MachineType::Int32(),
MachineType::Int32(), MachineType::Int32()};
#endif
int num_params = static_cast<int>(arraysize(mixed)) - start;
for (int which = 0; which < num_params; which++) {
v8::base::AccountingAllocator allocator;
Zone zone(&allocator);
TestingModule module;
module.AddMemory(1024);
MachineType* memtypes = &mixed[start];
MachineType result = memtypes[which];
// =========================================================================
// Build the selector function.
// =========================================================================
uint32_t index;
FunctionSig::Builder b(&zone, 1, num_params);
b.AddReturn(WasmOpcodes::LocalTypeFor(result));
for (int i = 0; i < num_params; i++) {
b.AddParam(WasmOpcodes::LocalTypeFor(memtypes[i]));
}
WasmFunctionCompiler t(b.Build(), &module);
BUILD(t, WASM_GET_LOCAL(which));
index = t.CompileAndAdd();
// =========================================================================
// Build the calling function.
// =========================================================================
WasmRunner<int32_t> r(&module);
std::vector<byte> code;
// Load the offset for the store.
ADD_CODE(code, WASM_ZERO);
// Load the arguments.
for (int i = 0; i < num_params; i++) {
int offset = (i + 1) * kElemSize;
ADD_CODE(code, WASM_LOAD_MEM(memtypes[i], WASM_I8(offset)));
}
// Call the selector function.
ADD_CODE(code, kExprCallFunction, static_cast<byte>(num_params),
static_cast<byte>(index));
// Store the result in memory.
ADD_CODE(code,
static_cast<byte>(WasmOpcodes::LoadStoreOpcodeOf(result, true)),
ZERO_ALIGNMENT, ZERO_OFFSET);
// Return the expected value.
ADD_CODE(code, WASM_I32V_2(kExpected));
r.Build(&code[0], &code[0] + code.size());
// Run the code.
for (int t = 0; t < 10; t++) {
module.RandomizeMemory();
CHECK_EQ(kExpected, r.Call());
int size = WasmOpcodes::MemSize(result);
for (int i = 0; i < size; i++) {
int base = (which + 1) * kElemSize;
byte expected = module.raw_mem_at<byte>(base + i);
byte result = module.raw_mem_at<byte>(i);
CHECK_EQ(expected, result);
}
}
}
}
WASM_EXEC_TEST(MixedCall_0) { Run_WasmMixedCall_N(0); }
WASM_EXEC_TEST(MixedCall_1) { Run_WasmMixedCall_N(1); }
WASM_EXEC_TEST(MixedCall_2) { Run_WasmMixedCall_N(2); }
WASM_EXEC_TEST(MixedCall_3) { Run_WasmMixedCall_N(3); }
WASM_EXEC_TEST(AddCall) {
TestSignatures sigs;
TestingModule module;
WasmFunctionCompiler t1(sigs.i_ii(), &module);
BUILD(t1, WASM_I32_ADD(WASM_GET_LOCAL(0), WASM_GET_LOCAL(1)));
t1.CompileAndAdd();
WasmRunner<int32_t> r(&module, MachineType::Int32());
byte local = r.AllocateLocal(kAstI32);
BUILD(r, B2(WASM_SET_LOCAL(local, WASM_I8(99)),
WASM_I32_ADD(
WASM_CALL_FUNCTION2(t1.function_index_, WASM_GET_LOCAL(0),
WASM_GET_LOCAL(0)),
WASM_CALL_FUNCTION2(t1.function_index_, WASM_GET_LOCAL(1),
WASM_GET_LOCAL(local)))));
CHECK_EQ(198, r.Call(0));
CHECK_EQ(200, r.Call(1));
CHECK_EQ(100, r.Call(-49));
}
WASM_EXEC_TEST(CountDown_expr) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, WASM_LOOP(
3, WASM_IF(WASM_NOT(WASM_GET_LOCAL(0)),
WASM_BREAKV(1, WASM_GET_LOCAL(0))),
WASM_SET_LOCAL(0, WASM_I32_SUB(WASM_GET_LOCAL(0), WASM_I8(1))),
WASM_CONTINUE(0)));
CHECK_EQ(0, r.Call(1));
CHECK_EQ(0, r.Call(10));
CHECK_EQ(0, r.Call(100));
}
WASM_EXEC_TEST(ExprBlock2a) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, B2(WASM_IF(WASM_GET_LOCAL(0), WASM_BRV(1, WASM_I8(1))), WASM_I8(1)));
CHECK_EQ(1, r.Call(0));
CHECK_EQ(1, r.Call(1));
}
WASM_EXEC_TEST(ExprBlock2b) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, B2(WASM_IF(WASM_GET_LOCAL(0), WASM_BRV(1, WASM_I8(1))), WASM_I8(2)));
CHECK_EQ(2, r.Call(0));
CHECK_EQ(1, r.Call(1));
}
WASM_EXEC_TEST(ExprBlock2c) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, B2(WASM_BRV_IF(0, WASM_I8(1), WASM_GET_LOCAL(0)), WASM_I8(1)));
CHECK_EQ(1, r.Call(0));
CHECK_EQ(1, r.Call(1));
}
WASM_EXEC_TEST(ExprBlock2d) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, B2(WASM_BRV_IF(0, WASM_I8(1), WASM_GET_LOCAL(0)), WASM_I8(2)));
CHECK_EQ(2, r.Call(0));
CHECK_EQ(1, r.Call(1));
}
WASM_EXEC_TEST(ExprBlock_ManualSwitch) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, WASM_BLOCK(6, WASM_IF(WASM_I32_EQ(WASM_GET_LOCAL(0), WASM_I8(1)),
WASM_BRV(1, WASM_I8(11))),
WASM_IF(WASM_I32_EQ(WASM_GET_LOCAL(0), WASM_I8(2)),
WASM_BRV(1, WASM_I8(12))),
WASM_IF(WASM_I32_EQ(WASM_GET_LOCAL(0), WASM_I8(3)),
WASM_BRV(1, WASM_I8(13))),
WASM_IF(WASM_I32_EQ(WASM_GET_LOCAL(0), WASM_I8(4)),
WASM_BRV(1, WASM_I8(14))),
WASM_IF(WASM_I32_EQ(WASM_GET_LOCAL(0), WASM_I8(5)),
WASM_BRV(1, WASM_I8(15))),
WASM_I8(99)));
CHECK_EQ(99, r.Call(0));
CHECK_EQ(11, r.Call(1));
CHECK_EQ(12, r.Call(2));
CHECK_EQ(13, r.Call(3));
CHECK_EQ(14, r.Call(4));
CHECK_EQ(15, r.Call(5));
CHECK_EQ(99, r.Call(6));
}
WASM_EXEC_TEST(ExprBlock_ManualSwitch_brif) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r,
WASM_BLOCK(6, WASM_BRV_IF(0, WASM_I8(11),
WASM_I32_EQ(WASM_GET_LOCAL(0), WASM_I8(1))),
WASM_BRV_IF(0, WASM_I8(12),
WASM_I32_EQ(WASM_GET_LOCAL(0), WASM_I8(2))),
WASM_BRV_IF(0, WASM_I8(13),
WASM_I32_EQ(WASM_GET_LOCAL(0), WASM_I8(3))),
WASM_BRV_IF(0, WASM_I8(14),
WASM_I32_EQ(WASM_GET_LOCAL(0), WASM_I8(4))),
WASM_BRV_IF(0, WASM_I8(15),
WASM_I32_EQ(WASM_GET_LOCAL(0), WASM_I8(5))),
WASM_I8(99)));
CHECK_EQ(99, r.Call(0));
CHECK_EQ(11, r.Call(1));
CHECK_EQ(12, r.Call(2));
CHECK_EQ(13, r.Call(3));
CHECK_EQ(14, r.Call(4));
CHECK_EQ(15, r.Call(5));
CHECK_EQ(99, r.Call(6));
}
WASM_EXEC_TEST(nested_ifs) {
WasmRunner<int32_t> r(MachineType::Int32(), MachineType::Int32());
BUILD(r, WASM_IF_ELSE(
WASM_GET_LOCAL(0),
WASM_IF_ELSE(WASM_GET_LOCAL(1), WASM_I8(11), WASM_I8(12)),
WASM_IF_ELSE(WASM_GET_LOCAL(1), WASM_I8(13), WASM_I8(14))));
CHECK_EQ(11, r.Call(1, 1));
CHECK_EQ(12, r.Call(1, 0));
CHECK_EQ(13, r.Call(0, 1));
CHECK_EQ(14, r.Call(0, 0));
}
WASM_EXEC_TEST(ExprBlock_if) {
WasmRunner<int32_t> r(MachineType::Int32());
BUILD(r, B1(WASM_IF_ELSE(WASM_GET_LOCAL(0), WASM_BRV(0, WASM_I8(11)),
WASM_BRV(1, WASM_I8(14)))));
CHECK_EQ(11, r.Call(1));
CHECK_EQ(14, r.Call(0));
}
WASM_EXEC_TEST(ExprBlock_nested_ifs) {
WasmRunner<int32_t> r(MachineType::Int32(), MachineType::Int32());
BUILD(r, WASM_BLOCK(
1, WASM_IF_ELSE(
WASM_GET_LOCAL(0),
WASM_IF_ELSE(WASM_GET_LOCAL(1), WASM_BRV(0, WASM_I8(11)),
WASM_BRV(1, WASM_I8(12))),
WASM_IF_ELSE(WASM_GET_LOCAL(1), WASM_BRV(0, WASM_I8(13)),
WASM_BRV(1, WASM_I8(14))))));
CHECK_EQ(11, r.Call(1, 1));
CHECK_EQ(12, r.Call(1, 0));
CHECK_EQ(13, r.Call(0, 1));
CHECK_EQ(14, r.Call(0, 0));
}
WASM_EXEC_TEST(ExprLoop_nested_ifs) {
WasmRunner<int32_t> r(MachineType::Int32(), MachineType::Int32());
BUILD(r, WASM_LOOP(
1, WASM_IF_ELSE(
WASM_GET_LOCAL(0),
WASM_IF_ELSE(WASM_GET_LOCAL(1), WASM_BRV(1, WASM_I8(11)),
WASM_BRV(3, WASM_I8(12))),
WASM_IF_ELSE(WASM_GET_LOCAL(1), WASM_BRV(1, WASM_I8(13)),
WASM_BRV(3, WASM_I8(14))))));
CHECK_EQ(11, r.Call(1, 1));
CHECK_EQ(12, r.Call(1, 0));
CHECK_EQ(13, r.Call(0, 1));
CHECK_EQ(14, r.Call(0, 0));
}
WASM_EXEC_TEST(SimpleCallIndirect) {
TestSignatures sigs;
TestingModule module;
WasmFunctionCompiler t1(sigs.i_ii(), &module);
BUILD(t1, WASM_I32_ADD(WASM_GET_LOCAL(0), WASM_GET_LOCAL(1)));
t1.CompileAndAdd(/*sig_index*/ 1);
WasmFunctionCompiler t2(sigs.i_ii(), &module);
BUILD(t2, WASM_I32_SUB(WASM_GET_LOCAL(0), WASM_GET_LOCAL(1)));
t2.CompileAndAdd(/*sig_index*/ 1);
// Signature table.
module.AddSignature(sigs.f_ff());
module.AddSignature(sigs.i_ii());
module.AddSignature(sigs.d_dd());
// Function table.
int table[] = {0, 1};
module.AddIndirectFunctionTable(table, 2);
module.PopulateIndirectFunctionTable();
// Builder the caller function.
WasmRunner<int32_t> r(&module, MachineType::Int32());
BUILD(r, WASM_CALL_INDIRECT2(1, WASM_GET_LOCAL(0), WASM_I8(66), WASM_I8(22)));
CHECK_EQ(88, r.Call(0));
CHECK_EQ(44, r.Call(1));
CHECK_TRAP(r.Call(2));
}
WASM_EXEC_TEST(MultipleCallIndirect) {
TestSignatures sigs;
TestingModule module;
WasmFunctionCompiler t1(sigs.i_ii(), &module);
BUILD(t1, WASM_I32_ADD(WASM_GET_LOCAL(0), WASM_GET_LOCAL(1)));
t1.CompileAndAdd(/*sig_index*/ 1);
WasmFunctionCompiler t2(sigs.i_ii(), &module);
BUILD(t2, WASM_I32_SUB(WASM_GET_LOCAL(0), WASM_GET_LOCAL(1)));
t2.CompileAndAdd(/*sig_index*/ 1);
// Signature table.
module.AddSignature(sigs.f_ff());
module.AddSignature(sigs.i_ii());
module.AddSignature(sigs.d_dd());
// Function table.
int table[] = {0, 1};
module.AddIndirectFunctionTable(table, 2);
module.PopulateIndirectFunctionTable();
// Builder the caller function.
WasmRunner<int32_t> r(&module, MachineType::Int32(), MachineType::Int32(),
MachineType::Int32());
BUILD(r, WASM_I32_ADD(
WASM_CALL_INDIRECT2(1, WASM_GET_LOCAL(0), WASM_GET_LOCAL(1),
WASM_GET_LOCAL(2)),
WASM_CALL_INDIRECT2(1, WASM_GET_LOCAL(1), WASM_GET_LOCAL(2),
WASM_GET_LOCAL(0))));
CHECK_EQ(5, r.Call(0, 1, 2));
CHECK_EQ(19, r.Call(0, 1, 9));
CHECK_EQ(1, r.Call(1, 0, 2));
CHECK_EQ(1, r.Call(1, 0, 9));
CHECK_TRAP(r.Call(0, 2, 1));
CHECK_TRAP(r.Call(1, 2, 0));
CHECK_TRAP(r.Call(2, 0, 1));
CHECK_TRAP(r.Call(2, 1, 0));
}
WASM_EXEC_TEST(CallIndirect_NoTable) {
TestSignatures sigs;
TestingModule module;
// One function.
WasmFunctionCompiler t1(sigs.i_ii(), &module);
BUILD(t1, WASM_I32_ADD(WASM_GET_LOCAL(0), WASM_GET_LOCAL(1)));
t1.CompileAndAdd(/*sig_index*/ 1);
// Signature table.
module.AddSignature(sigs.f_ff());
module.AddSignature(sigs.i_ii());
// Builder the caller function.
WasmRunner<int32_t> r(&module, MachineType::Int32());
BUILD(r, WASM_CALL_INDIRECT2(1, WASM_GET_LOCAL(0), WASM_I8(66), WASM_I8(22)));
CHECK_TRAP(r.Call(0));
CHECK_TRAP(r.Call(1));
CHECK_TRAP(r.Call(2));
}
WASM_EXEC_TEST(F32Floor) {
WasmRunner<float> r(MachineType::Float32());
BUILD(r, WASM_F32_FLOOR(WASM_GET_LOCAL(0)));
FOR_FLOAT32_INPUTS(i) { CHECK_FLOAT_EQ(floorf(*i), r.Call(*i)); }
}
WASM_EXEC_TEST(F32Ceil) {
WasmRunner<float> r(MachineType::Float32());
BUILD(r, WASM_F32_CEIL(WASM_GET_LOCAL(0)));
FOR_FLOAT32_INPUTS(i) { CHECK_FLOAT_EQ(ceilf(*i), r.Call(*i)); }
}
WASM_EXEC_TEST(F32Trunc) {
WasmRunner<float> r(MachineType::Float32());
BUILD(r, WASM_F32_TRUNC(WASM_GET_LOCAL(0)));
FOR_FLOAT32_INPUTS(i) { CHECK_FLOAT_EQ(truncf(*i), r.Call(*i)); }
}
WASM_EXEC_TEST(F32NearestInt) {
WasmRunner<float> r(MachineType::Float32());
BUILD(r, WASM_F32_NEARESTINT(WASM_GET_LOCAL(0)));
FOR_FLOAT32_INPUTS(i) { CHECK_FLOAT_EQ(nearbyintf(*i), r.Call(*i)); }
}
WASM_EXEC_TEST(F64Floor) {
WasmRunner<double> r(MachineType::Float64());
BUILD(r, WASM_F64_FLOOR(WASM_GET_LOCAL(0)));
FOR_FLOAT64_INPUTS(i) { CHECK_DOUBLE_EQ(floor(*i), r.Call(*i)); }
}
WASM_EXEC_TEST(F64Ceil) {
WasmRunner<double> r(MachineType::Float64());
BUILD(r, WASM_F64_CEIL(WASM_GET_LOCAL(0)));
FOR_FLOAT64_INPUTS(i) { CHECK_DOUBLE_EQ(ceil(*i), r.Call(*i)); }
}
WASM_EXEC_TEST(F64Trunc) {
WasmRunner<double> r(MachineType::Float64());
BUILD(r, WASM_F64_TRUNC(WASM_GET_LOCAL(0)));
FOR_FLOAT64_INPUTS(i) { CHECK_DOUBLE_EQ(trunc(*i), r.Call(*i)); }
}
WASM_EXEC_TEST(F64NearestInt) {
WasmRunner<double> r(MachineType::Float64());
BUILD(r, WASM_F64_NEARESTINT(WASM_GET_LOCAL(0)));
FOR_FLOAT64_INPUTS(i) { CHECK_DOUBLE_EQ(nearbyint(*i), r.Call(*i)); }
}
WASM_EXEC_TEST(F32Min) {
WasmRunner<float> r(MachineType::Float32(), MachineType::Float32());
BUILD(r, WASM_F32_MIN(WASM_GET_LOCAL(0), WASM_GET_LOCAL(1)));
FOR_FLOAT32_INPUTS(i) {
FOR_FLOAT32_INPUTS(j) {
float expected;
if (*i < *j) {
expected = *i;
} else if (*j < *i) {
expected = *j;
} else if (*i != *i) {
// If *i or *j is NaN, then the result is NaN.
expected = *i;
} else {
expected = *j;
}
CHECK_FLOAT_EQ(expected, r.Call(*i, *j));
}
}
}
WASM_EXEC_TEST(F64Min) {
WasmRunner<double> r(MachineType::Float64(), MachineType::Float64());
BUILD(r, WASM_F64_MIN(WASM_GET_LOCAL(0), WASM_GET_LOCAL(1)));
FOR_FLOAT64_INPUTS(i) {
FOR_FLOAT64_INPUTS(j) {
double expected;
if (*i < *j) {
expected = *i;
} else if (*j < *i) {
expected = *j;
} else if (*i != *i) {
// If *i or *j is NaN, then the result is NaN.
expected = *i;
} else {
expected = *j;
}
CHECK_DOUBLE_EQ(expected, r.Call(*i, *j));
}
}
}
WASM_EXEC_TEST(F32Max) {
WasmRunner<float> r(MachineType::Float32(), MachineType::Float32());
BUILD(r, WASM_F32_MAX(WASM_GET_LOCAL(0), WASM_GET_LOCAL(1)));
FOR_FLOAT32_INPUTS(i) {
FOR_FLOAT32_INPUTS(j) {
float expected;
if (*i > *j) {
expected = *i;
} else if (*j > *i) {
expected = *j;
} else if (*i != *i) {
// If *i or *j is NaN, then the result is NaN.
expected = *i;
} else {
expected = *j;
}
CHECK_FLOAT_EQ(expected, r.Call(*i, *j));
}
}
}
WASM_EXEC_TEST(F64Max) {
WasmRunner<double> r(MachineType::Float64(), MachineType::Float64());
BUILD(r, WASM_F64_MAX(WASM_GET_LOCAL(0), WASM_GET_LOCAL(1)));
FOR_FLOAT64_INPUTS(i) {
FOR_FLOAT64_INPUTS(j) {
double expected;
if (*i > *j) {
expected = *i;
} else if (*j > *i) {
expected = *j;
} else if (*i != *i) {
// If *i or *j is NaN, then the result is NaN.
expected = *i;
} else {
expected = *j;
}
CHECK_DOUBLE_EQ(expected, r.Call(*i, *j));
}
}
}
// TODO(ahaas): Fix on mips and reenable.
#if !V8_TARGET_ARCH_MIPS && !V8_TARGET_ARCH_MIPS64
WASM_EXEC_TEST(F32Min_Snan) {
// Test that the instruction does not return a signalling NaN.
{
WasmRunner<float> r;
BUILD(r,
WASM_F32_MIN(WASM_F32(bit_cast<float>(0xff80f1e2)), WASM_F32(57.67)));
CHECK_EQ(0xffc0f1e2, bit_cast<uint32_t>(r.Call()));
}
{
WasmRunner<float> r;
BUILD(r,
WASM_F32_MIN(WASM_F32(45.73), WASM_F32(bit_cast<float>(0x7f80f1e2))));
CHECK_EQ(0x7fc0f1e2, bit_cast<uint32_t>(r.Call()));
}
}
WASM_EXEC_TEST(F32Max_Snan) {
// Test that the instruction does not return a signalling NaN.
{
WasmRunner<float> r;
BUILD(r,
WASM_F32_MAX(WASM_F32(bit_cast<float>(0xff80f1e2)), WASM_F32(57.67)));
CHECK_EQ(0xffc0f1e2, bit_cast<uint32_t>(r.Call()));
}
{
WasmRunner<float> r;
BUILD(r,
WASM_F32_MAX(WASM_F32(45.73), WASM_F32(bit_cast<float>(0x7f80f1e2))));
CHECK_EQ(0x7fc0f1e2, bit_cast<uint32_t>(r.Call()));
}
}
WASM_EXEC_TEST(F64Min_Snan) {
// Test that the instruction does not return a signalling NaN.
{
WasmRunner<double> r;
BUILD(r, WASM_F64_MIN(WASM_F64(bit_cast<double>(0xfff000000000f1e2)),
WASM_F64(57.67)));
CHECK_EQ(0xfff800000000f1e2, bit_cast<uint64_t>(r.Call()));
}
{
WasmRunner<double> r;
BUILD(r, WASM_F64_MIN(WASM_F64(45.73),
WASM_F64(bit_cast<double>(0x7ff000000000f1e2))));
CHECK_EQ(0x7ff800000000f1e2, bit_cast<uint64_t>(r.Call()));
}
}
WASM_EXEC_TEST(F64Max_Snan) {
// Test that the instruction does not return a signalling NaN.
{
WasmRunner<double> r;
BUILD(r, WASM_F64_MAX(WASM_F64(bit_cast<double>(0xfff000000000f1e2)),
WASM_F64(57.67)));
CHECK_EQ(0xfff800000000f1e2, bit_cast<uint64_t>(r.Call()));
}
{
WasmRunner<double> r;
BUILD(r, WASM_F64_MAX(WASM_F64(45.73),
WASM_F64(bit_cast<double>(0x7ff000000000f1e2))));
CHECK_EQ(0x7ff800000000f1e2, bit_cast<uint64_t>(r.Call()));
}
}
#endif
WASM_EXEC_TEST(I32SConvertF32) {
WasmRunner<int32_t> r(MachineType::Float32());
BUILD(r, WASM_I32_SCONVERT_F32(WASM_GET_LOCAL(0)));
FOR_FLOAT32_INPUTS(i) {
if (*i < static_cast<float>(INT32_MAX) &&
*i >= static_cast<float>(INT32_MIN)) {
CHECK_EQ(static_cast<int32_t>(*i), r.Call(*i));
} else {
CHECK_TRAP32(r.Call(*i));
}
}
}
WASM_EXEC_TEST(I32SConvertF64) {
WasmRunner<int32_t> r(MachineType::Float64());
BUILD(r, WASM_I32_SCONVERT_F64(WASM_GET_LOCAL(0)));
FOR_FLOAT64_INPUTS(i) {
if (*i < (static_cast<double>(INT32_MAX) + 1.0) &&
*i > (static_cast<double>(INT32_MIN) - 1.0)) {
CHECK_EQ(static_cast<int64_t>(*i), r.Call(*i));
} else {
CHECK_TRAP32(r.Call(*i));
}
}
}
WASM_EXEC_TEST(I32UConvertF32) {
WasmRunner<uint32_t> r(MachineType::Float32());
BUILD(r, WASM_I32_UCONVERT_F32(WASM_GET_LOCAL(0)));
FOR_FLOAT32_INPUTS(i) {
if (*i < (static_cast<float>(UINT32_MAX) + 1.0) && *i > -1) {
CHECK_EQ(static_cast<uint32_t>(*i), r.Call(*i));
} else {
CHECK_TRAP32(r.Call(*i));
}
}
}
WASM_EXEC_TEST(I32UConvertF64) {
WasmRunner<uint32_t> r(MachineType::Float64());
BUILD(r, WASM_I32_UCONVERT_F64(WASM_GET_LOCAL(0)));
FOR_FLOAT64_INPUTS(i) {
if (*i < (static_cast<float>(UINT32_MAX) + 1.0) && *i > -1) {
CHECK_EQ(static_cast<uint32_t>(*i), r.Call(*i));
} else {
CHECK_TRAP32(r.Call(*i));
}
}
}
WASM_EXEC_TEST(F64CopySign) {
WasmRunner<double> r(MachineType::Float64(), MachineType::Float64());
BUILD(r, WASM_F64_COPYSIGN(WASM_GET_LOCAL(0), WASM_GET_LOCAL(1)));
FOR_FLOAT64_INPUTS(i) {
FOR_FLOAT64_INPUTS(j) { CHECK_DOUBLE_EQ(copysign(*i, *j), r.Call(*i, *j)); }
}
}
WASM_EXEC_TEST(F32CopySign) {
WasmRunner<float> r(MachineType::Float32(), MachineType::Float32());
BUILD(r, WASM_F32_COPYSIGN(WASM_GET_LOCAL(0), WASM_GET_LOCAL(1)));
FOR_FLOAT32_INPUTS(i) {
FOR_FLOAT32_INPUTS(j) { CHECK_FLOAT_EQ(copysignf(*i, *j), r.Call(*i, *j)); }
}
}
void CompileCallIndirectMany(LocalType param) {
// Make sure we don't run out of registers when compiling indirect calls
// with many many parameters.
TestSignatures sigs;
for (byte num_params = 0; num_params < 40; num_params++) {
v8::base::AccountingAllocator allocator;
Zone zone(&allocator);
HandleScope scope(CcTest::InitIsolateOnce());
TestingModule module;
FunctionSig* sig = sigs.many(&zone, kAstStmt, param, num_params);
module.AddSignature(sig);
module.AddSignature(sig);
module.AddIndirectFunctionTable(nullptr, 0);
WasmFunctionCompiler t(sig, &module);
std::vector<byte> code;
ADD_CODE(code, kExprI8Const, 0);
for (byte p = 0; p < num_params; p++) {
ADD_CODE(code, kExprGetLocal, p);
}
ADD_CODE(code, kExprCallIndirect, static_cast<byte>(num_params), 1);
t.Build(&code[0], &code[0] + code.size());
t.Compile();
}
}
TEST(Compile_Wasm_CallIndirect_Many_i32) { CompileCallIndirectMany(kAstI32); }
#if WASM_64
TEST(Compile_Wasm_CallIndirect_Many_i64) { CompileCallIndirectMany(kAstI64); }
#endif
TEST(Compile_Wasm_CallIndirect_Many_f32) { CompileCallIndirectMany(kAstF32); }
TEST(Compile_Wasm_CallIndirect_Many_f64) { CompileCallIndirectMany(kAstF64); }
WASM_EXEC_TEST(Int32RemS_dead) {
WasmRunner<int32_t> r(MachineType::Int32(), MachineType::Int32());
BUILD(r, WASM_I32_REMS(WASM_GET_LOCAL(0), WASM_GET_LOCAL(1)), WASM_ZERO);
const int32_t kMin = std::numeric_limits<int32_t>::min();
CHECK_EQ(0, r.Call(133, 100));
CHECK_EQ(0, r.Call(kMin, -1));
CHECK_EQ(0, r.Call(0, 1));
CHECK_TRAP(r.Call(100, 0));
CHECK_TRAP(r.Call(-1001, 0));
CHECK_TRAP(r.Call(kMin, 0));
}
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
b7080c48e120dfe5e8b2c4a2fc548e667dec93c8 | f529a7dfbec16e1ba9253db7fb70e23195c7c203 | /src/rpcnet.cpp | 621fb27212615ef950e4813edd2b1312bec28e46 | [
"MIT"
] | permissive | ms40/sf60 | a6077623c7a494e27297262a7237ce7947e4264d | 95e4697934a8a058622b5d4e197999fe1b2b8bca | refs/heads/master | 2020-05-07T12:41:04.373732 | 2015-04-24T21:43:50 | 2015-04-24T21:43:50 | 34,542,990 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,647 | cpp | // Copyright (c) 2009-2012 Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "net.h"
#include "albatroscoinrpc.h"
#include "alert.h"
#include "wallet.h"
#include "db.h"
#include "walletdb.h"
using namespace json_spirit;
using namespace std;
Value getconnectioncount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getconnectioncount\n"
"Returns the number of connections to other nodes.");
LOCK(cs_vNodes);
return (int)vNodes.size();
}
static void CopyNodeStats(std::vector<CNodeStats>& vstats)
{
vstats.clear();
LOCK(cs_vNodes);
vstats.reserve(vNodes.size());
BOOST_FOREACH(CNode* pnode, vNodes) {
CNodeStats stats;
pnode->copyStats(stats);
vstats.push_back(stats);
}
}
Value getpeerinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getpeerinfo\n"
"Returns data about each connected network node.");
vector<CNodeStats> vstats;
CopyNodeStats(vstats);
Array ret;
BOOST_FOREACH(const CNodeStats& stats, vstats) {
Object obj;
obj.push_back(Pair("addr", stats.addrName));
obj.push_back(Pair("services", strprintf("%08"PRIx64, stats.nServices)));
obj.push_back(Pair("lastsend", (boost::int64_t)stats.nLastSend));
obj.push_back(Pair("lastrecv", (boost::int64_t)stats.nLastRecv));
obj.push_back(Pair("conntime", (boost::int64_t)stats.nTimeConnected));
obj.push_back(Pair("version", stats.nVersion));
obj.push_back(Pair("subver", stats.strSubVer));
obj.push_back(Pair("inbound", stats.fInbound));
obj.push_back(Pair("startingheight", stats.nStartingHeight));
obj.push_back(Pair("banscore", stats.nMisbehavior));
ret.push_back(obj);
}
return ret;
}
// albatroscoin: send alert.
// There is a known deadlock situation with ThreadMessageHandler
// ThreadMessageHandler: holds cs_vSend and acquiring cs_main in SendMessages()
// ThreadRPCServer: holds cs_main and acquiring cs_vSend in alert.RelayTo()/PushMessage()/BeginMessage()
Value sendalert(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 6)
throw runtime_error(
"sendalert <message> <privatekey> <minver> <maxver> <priority> <id> [cancelupto]\n"
"<message> is the alert text message\n"
"<privatekey> is hex string of alert master private key\n"
"<minver> is the minimum applicable internal client version\n"
"<maxver> is the maximum applicable internal client version\n"
"<priority> is integer priority number\n"
"<id> is the alert id\n"
"[cancelupto] cancels all alert id's up to this number\n"
"Returns true or false.");
CAlert alert;
CKey key;
alert.strStatusBar = params[0].get_str();
alert.nMinVer = params[2].get_int();
alert.nMaxVer = params[3].get_int();
alert.nPriority = params[4].get_int();
alert.nID = params[5].get_int();
if (params.size() > 6)
alert.nCancel = params[6].get_int();
alert.nVersion = PROTOCOL_VERSION;
alert.nRelayUntil = GetAdjustedTime() + 365*24*60*60;
alert.nExpiration = GetAdjustedTime() + 365*24*60*60;
CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
sMsg << (CUnsignedAlert)alert;
alert.vchMsg = vector<unsigned char>(sMsg.begin(), sMsg.end());
vector<unsigned char> vchPrivKey = ParseHex(params[1].get_str());
key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
if (!key.Sign(Hash(alert.vchMsg.begin(), alert.vchMsg.end()), alert.vchSig))
throw runtime_error(
"Unable to sign alert, check private key?\n");
if(!alert.ProcessAlert())
throw runtime_error(
"Failed to process alert.\n");
// Relay alert
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
alert.RelayTo(pnode);
}
Object result;
result.push_back(Pair("strStatusBar", alert.strStatusBar));
result.push_back(Pair("nVersion", alert.nVersion));
result.push_back(Pair("nMinVer", alert.nMinVer));
result.push_back(Pair("nMaxVer", alert.nMaxVer));
result.push_back(Pair("nPriority", alert.nPriority));
result.push_back(Pair("nID", alert.nID));
if (alert.nCancel > 0)
result.push_back(Pair("nCancel", alert.nCancel));
return result;
}
| [
"test@test.com"
] | test@test.com |
b356430fce05e0d174179a732b6e7b2807c10ae5 | b8e9e450d7aa18f170956b0c67ea80b5e9b17417 | /src/cmft/cubemapfilter.cpp | af0e03168376f73dda0f9215b7826d2754433c18 | [
"BSD-2-Clause"
] | permissive | davidlee80/cmft | 2c49d2b76db7129525f1d988c869a74fdb020cbb | b285a9627a66a2b451b56e60a3e85ea9ccaf65a0 | refs/heads/master | 2021-01-14T14:02:22.022326 | 2014-09-15T00:09:39 | 2014-09-15T00:09:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 63,964 | cpp | /*
* Copyright 2014 Dario Manesku. All rights reserved.
* License: http://www.opensource.org/licenses/BSD-2-Clause
*/
#include "cmft/cubemapfilter.h"
#include "cmft/clcontext.h"
#include "base/config.h"
#include "base/printcallback.h"
#include "base/macros.h"
#include "base/utils.h"
#include "cubemaputils.h"
#include "radiance.h"
#include <stdlib.h> //malloc
#include <string.h> //memset
#include <math.h> //pow, sqrt
#include <float.h> //FLT_MAX
#include <bx/timer.h> //bx::getHPFrequency
#include <bx/os.h> //bx::sleep
#include <bx/thread.h> //bx::thread
#include <bx/mutex.h> //bx::mutex
namespace cmft
{
#define PI 3.1415926535897932384626433832795028841971693993751058
#define PI4 12.566370614359172953850573533118011536788677597500423
#define PI16 50.265482457436691815402294132472046147154710390001693
#define PI64 201.06192982974676726160917652988818458861884156000677
#define SQRT_PI 1.7724538509055160272981674833411451827975494561223871
/// Creates a cubemap containing tap vectors and solid angle of each texel on the cubemap.
/// Output consists of 6 faces of specified size containing (x,y,z,angle) floats for each texel.
///
/// Memory should be freed outside of the function !
float* buildCubemapNormalSolidAngle(uint32_t _cubemapFaceSize)
{
const uint32_t size = _cubemapFaceSize /*width*/
* _cubemapFaceSize /*height*/
* 6 /*numFaces*/
* 4 /*numChannels*/
* 4 /*bytesPerChannel*/
;
float* dst = (float*)malloc(size);
MALLOC_CHECK(dst);
const float invFaceSize = 1.0f/float(int32_t(_cubemapFaceSize));
float* dstPtr = dst;
for(uint8_t face = 0; face < 6; ++face)
{
for (uint32_t yy = 0; yy < _cubemapFaceSize; ++yy)
{
for (uint32_t xx = 0; xx < _cubemapFaceSize; ++xx)
{
// From [0..size-1] to [-1.0+invSize .. 1.0-invSize].
const float xxf = float(int32_t(xx));
const float yyf = float(int32_t(yy));
const float uu = 2.0f*(xxf+0.5f)*invFaceSize - 1.0f;
const float vv = 2.0f*(yyf+0.5f)*invFaceSize - 1.0f;
texelCoordToVec(dstPtr, uu, vv, face, _cubemapFaceSize);
dstPtr[3] = texelSolidAngle(uu, vv, invFaceSize);
dstPtr += 4;
}
}
}
return dst;
}
// Irradiance.
//-----
void evalSHBasis5(double* _shBasis, const float* _dir)
{
const double x = double(_dir[0]);
const double y = double(_dir[1]);
const double z = double(_dir[2]);
const double x2 = x*x;
const double y2 = y*y;
const double z2 = z*z;
const double z3 = pow(z, 3.0);
const double x4 = pow(x, 4.0);
const double y4 = pow(y, 4.0);
const double z4 = pow(z, 4.0);
//Equations based on data from: http://ppsloan.org/publications/StupidSH36.pdf
_shBasis[ 0] = 1.0/(2.0*SQRT_PI);
_shBasis[ 1] = -sqrt(3.0/PI4)*y;
_shBasis[ 2] = sqrt(3.0/PI4)*z;
_shBasis[ 3] = -sqrt(3.0/PI4)*x;
_shBasis[ 4] = sqrt(15.0/PI4)*y*x;
_shBasis[ 5] = -sqrt(15.0/PI4)*y*z;
_shBasis[ 6] = sqrt(5.0/PI16)*(3.0*z2-1.0);
_shBasis[ 7] = -sqrt(15.0/PI4)*x*z;
_shBasis[ 8] = sqrt(15.0/PI16)*(x2-y2);
_shBasis[ 9] = -sqrt( 70.0/PI64)*y*(3*x2-y2);
_shBasis[10] = sqrt(105.0/ PI4)*y*x*z;
_shBasis[11] = -sqrt( 21.0/PI16)*y*(-1.0+5.0*z2);
_shBasis[12] = sqrt( 7.0/PI16)*(5.0*z3-3.0*z);
_shBasis[13] = -sqrt( 42.0/PI64)*x*(-1.0+5.0*z2);
_shBasis[14] = sqrt(105.0/PI16)*(x2-y2)*z;
_shBasis[15] = -sqrt( 70.0/PI64)*x*(x2-3.0*y2);
_shBasis[16] = 3.0*sqrt(35.0/PI16)*x*y*(x2-y2);
_shBasis[17] = -3.0*sqrt(70.0/PI64)*y*z*(3.0*x2-y2);
_shBasis[18] = 3.0*sqrt( 5.0/PI16)*y*x*(-1.0+7.0*z2);
_shBasis[19] = -3.0*sqrt(10.0/PI64)*y*z*(-3.0+7.0*z2);
_shBasis[20] = (105.0*z4-90.0*z2+9.0)/(16.0*SQRT_PI);
_shBasis[21] = -3.0*sqrt(10.0/PI64)*x*z*(-3.0+7.0*z2);
_shBasis[22] = 3.0*sqrt( 5.0/PI64)*(x2-y2)*(-1.0+7.0*z2);
_shBasis[23] = -3.0*sqrt(70.0/PI64)*x*z*(x2-3.0*y2);
_shBasis[24] = 3.0*sqrt(35.0/(4.0*PI64))*(x4-6.0*y2*x2+y4);
}
void cubemapShCoeffs(double _shCoeffs[SH_COEFF_NUM][3], void* _data, uint32_t _faceSize, uint32_t _faceOffsets[6])
{
memset(_shCoeffs, 0, SH_COEFF_NUM*3*sizeof(double));
double weightAccum = 0.0;
// Build cubemap vectors.
float* cubemapVectors = buildCubemapNormalSolidAngle(_faceSize);
ScopeFree cleanup(cubemapVectors);
const uint32_t bytesPerPixel = 4 /*numChannels*/ * 4 /*bytesPerChannel*/;
const uint32_t vectorPitch = _faceSize * bytesPerPixel;
const uint32_t vectorFaceDataSize = vectorPitch * _faceSize;
// Evaluate spherical harmonics coefficients.
for (uint8_t face = 0; face < 6; ++face)
{
const float* srcPtr = (const float*)((const uint8_t*)_data + _faceOffsets[face]);
const float* vecPtr = (const float*)((const uint8_t*)cubemapVectors + vectorFaceDataSize*face);
for (uint32_t texel = 0, count = _faceSize*_faceSize; texel < count; ++texel, srcPtr+=4, vecPtr+=4)
{
const double rr = double(srcPtr[0]);
const double gg = double(srcPtr[1]);
const double bb = double(srcPtr[2]);
double shBasis[SH_COEFF_NUM];
evalSHBasis5(shBasis, vecPtr);
const double weight = (double)vecPtr[3];
for (uint8_t ii = 0; ii < SH_COEFF_NUM; ++ii)
{
_shCoeffs[ii][0] += rr * shBasis[ii] * weight;
_shCoeffs[ii][1] += gg * shBasis[ii] * weight;
_shCoeffs[ii][2] += bb * shBasis[ii] * weight;
}
weightAccum += weight;
}
}
// Normalization.
// This is not really necesarry because usually PI*4 - weightAccum ~= 0.000003
// so it doesn't change almost anything, but it doesn't cost much to have more corectness.
const double norm = PI4 / weightAccum;
for (uint8_t ii = 0; ii < SH_COEFF_NUM; ++ii)
{
_shCoeffs[ii][0] *= norm;
_shCoeffs[ii][1] *= norm;
_shCoeffs[ii][2] *= norm;
}
}
bool imageShCoeffs(double _shCoeffs[SH_COEFF_NUM][3], const Image& _image)
{
// Input image must be a cubemap.
if (!imageIsCubemap(_image))
{
return false;
}
// Processing is done in Rgba32f format.
Image imageRgba32f;
imageRefOrConvert(imageRgba32f, TextureFormat::RGBA32F, _image);
// Get face data offsets.
uint32_t faceOffsets[6];
imageGetFaceOffsets(faceOffsets, imageRgba32f);
// Compute spherical harmonic coefficients.
cubemapShCoeffs(_shCoeffs, imageRgba32f.m_data, imageRgba32f.m_width, faceOffsets);
// Cleanup.
if (TextureFormat::RGBA32F != _image.m_format)
{
imageUnload(imageRgba32f);
}
return true;
}
bool imageIrradianceFilterSh(Image& _dst, uint32_t _dstFaceSize, const Image& _src)
{
// Input image must be a cubemap.
if (!imageIsCubemap(_src))
{
return false;
}
// Processing is done in Rgba32f format.
Image imageRgba32f;
imageRefOrConvert(imageRgba32f, TextureFormat::RGBA32F, _src);
// Get face data offsets.
uint32_t faceOffsets[6];
imageGetFaceOffsets(faceOffsets, imageRgba32f);
// Compute spherical harmonic coefficients.
double shRgb[SH_COEFF_NUM][3];
cubemapShCoeffs(shRgb, imageRgba32f.m_data, imageRgba32f.m_width, faceOffsets);
// Alloc dst data.
const uint32_t dstFaceSize = (0 == _dstFaceSize) ? _src.m_width : _dstFaceSize;
const uint8_t dstBytesPerPixel = 4 /*numChannels*/ * 4 /*bytesPerChannel*/;
const uint32_t dstPitch = dstFaceSize*dstBytesPerPixel;
const uint32_t dstFaceDataSize = dstPitch * dstFaceSize;
const uint32_t dstDataSize = dstFaceDataSize * 6 /*numFaces*/;
void* dstData = malloc(dstDataSize);
MALLOC_CHECK(dstData);
// Build cubemap texel vectors.
float* cubemapVectors = buildCubemapNormalSolidAngle(dstFaceSize);
ScopeFree cleanup(cubemapVectors);
const uint8_t vectorBytesPerPixel = 4 /*numChannels*/ * 4 /*bytesPerChannel*/;
const uint32_t vectorPitch = dstFaceSize * vectorBytesPerPixel;
const uint32_t vectorFaceDataSize = vectorPitch * dstFaceSize;
uint64_t totalTime = bx::getHPCounter();
// Output info.
INFO("Running irradiance filter for:\n"
"\t[srcFaceSize=%u]\n"
"\t[shOrder=5]\n"
"\t[dstFaceSize=%u]"
, imageRgba32f.m_width
, dstFaceSize
);
// Compute irradiance using SH data.
for (uint8_t face = 0; face < 6; ++face)
{
float* dstPtr = (float*)((uint8_t*)dstData + dstFaceDataSize*face);
const float* vecPtr = (const float*)((const uint8_t*)cubemapVectors + vectorFaceDataSize*face);
for (uint32_t texel = 0, count = dstFaceSize*dstFaceSize; texel < count ;++texel, dstPtr+=4, vecPtr+=4)
{
double shBasis[SH_COEFF_NUM];
evalSHBasis5(shBasis, vecPtr);
double rgb[3] = { 0.0, 0.0, 0.0 };
// Band 0 (factor 1.0)
rgb[0] += shRgb[0][0] * shBasis[0] * 1.0f;
rgb[1] += shRgb[0][1] * shBasis[0] * 1.0f;
rgb[2] += shRgb[0][2] * shBasis[0] * 1.0f;
// Band 1 (factor 2/3).
uint8_t ii = 1;
for (; ii < 4; ++ii)
{
rgb[0] += shRgb[ii][0] * shBasis[ii] * (2.0f/3.0f);
rgb[1] += shRgb[ii][1] * shBasis[ii] * (2.0f/3.0f);
rgb[2] += shRgb[ii][2] * shBasis[ii] * (2.0f/3.0f);
}
// Band 2 (factor 1/4).
for (; ii < 9; ++ii)
{
rgb[0] += shRgb[ii][0] * shBasis[ii] * (1.0f/4.0f);
rgb[1] += shRgb[ii][1] * shBasis[ii] * (1.0f/4.0f);
rgb[2] += shRgb[ii][2] * shBasis[ii] * (1.0f/4.0f);
}
// Band 3 (factor 0).
ii = 16;
// Band 4 (factor -1/24).
for (; ii < 25; ++ii)
{
rgb[0] += shRgb[ii][0] * shBasis[ii] * (-1.0f/24.0f);
rgb[1] += shRgb[ii][1] * shBasis[ii] * (-1.0f/24.0f);
rgb[2] += shRgb[ii][2] * shBasis[ii] * (-1.0f/24.0f);
}
dstPtr[0] = float(rgb[0]);
dstPtr[1] = float(rgb[1]);
dstPtr[2] = float(rgb[2]);
dstPtr[3] = 1.0f;
}
}
// Output progress info.
const double freq = double(bx::getHPFrequency());
const double toSec = 1.0/freq;
totalTime = bx::getHPCounter() - totalTime;
INFO("Irradiance -> Done! Total time: %.3f seconds.", double(totalTime)*toSec);
// Fill structure.
Image result;
result.m_width = dstFaceSize;
result.m_height = dstFaceSize;
result.m_dataSize = dstFaceSize /*width*/
* dstFaceSize /*height*/
* 6 /*numFaces*/
* 4 /*numChannels*/
* 4 /*bytesPerChannel*/
;
result.m_format = TextureFormat::RGBA32F;
result.m_numMips = 1;
result.m_numFaces = 6;
result.m_data = dstData;
// Convert back to source format.
if (TextureFormat::RGBA32F == _src.m_format)
{
imageMove(_dst, result);
}
else
{
imageConvert(_dst, (TextureFormat::Enum)_src.m_format, result);
imageUnload(result);
}
return true;
}
void imageIrradianceFilterSh(Image& _image, uint32_t _faceSize)
{
Image tmp;
if (imageIrradianceFilterSh(tmp, _faceSize, _image))
{
imageMove(_image, tmp);
}
}
// Radiance.
//-----
struct Aabb
{
Aabb()
{
m_min[0] = FLT_MAX;
m_min[1] = FLT_MAX;
m_max[0] = -FLT_MAX;
m_max[1] = -FLT_MAX;
}
void add(float _x, float _y)
{
m_min[0] = min(m_min[0], _x);
m_min[1] = min(m_min[1], _y);
m_max[0] = max(m_max[0], _x);
m_max[1] = max(m_max[1], _y);
}
inline void clampMin(float _x, float _y)
{
m_min[0] = max(m_min[0], _x);
m_min[1] = max(m_min[1], _y);
}
inline void clampMax(float _x, float _y)
{
m_max[0] = min(m_max[0], _x);
m_max[1] = min(m_max[1], _y);
}
void clamp(float _minX, float _minY, float _maxX, float _maxY)
{
clampMin(_minX, _minY);
clampMax(_maxX, _maxY);
}
void clamp(float _min, float _max)
{
clampMin(_min, _min);
clampMax(_max, _max);
}
bool isEmpty()
{
// Has to have at least two points added so that no value is equal to initial state.
return ((m_min[0] == FLT_MAX)
||(m_min[1] == FLT_MAX)
||(m_max[0] == -FLT_MAX)
||(m_max[1] == -FLT_MAX)
);
}
float m_min[2];
float m_max[2];
};
/// Computes filter area for each of the cubemap faces for given tap vector and filter size.
void determineFilterArea(Aabb _filterArea[6], const float* _tapVec, float _filterSize)
{
/// ______
/// | |
/// | |
/// | x |
/// |______|
///
// Get face and hit coordinates.
float uu, vv;
uint8_t hitFaceIdx;
vecToTexelCoord(uu, vv, hitFaceIdx, _tapVec);
/// ........
/// . .
/// . ___.
/// . | x |
/// ...|___|
///
// Calculate hit face filter bounds.
Aabb hitFaceFilterBounds;
hitFaceFilterBounds.add(uu-_filterSize, vv-_filterSize);
hitFaceFilterBounds.add(uu+_filterSize, vv+_filterSize);
hitFaceFilterBounds.clamp(0.0f, 1.0f);
// Output result for hit face.
DEBUG_CHECK(6 > hitFaceIdx, "Face idx should be in range 0-5");
memcpy(&_filterArea[hitFaceIdx], &hitFaceFilterBounds, sizeof(Aabb));
/// Filter area might extend on neighbour faces.
/// Case when extending over the right edge:
///
/// --> U
/// | ......
/// v . .
/// V . .
/// . .
/// ....... ...... .......
/// . . . .
/// . . .....__min .
/// . . . . | -> amount
/// ....... .....x.__|....
/// . . . max
/// . ........
/// . .
/// ......
/// . .
/// . .
/// . .
/// ......
///
enum NeighbourSides
{
Left,
Right,
Top,
Bottom,
Count,
};
struct NeighourFaceBleed
{
float m_amount;
float m_bbMin;
float m_bbMax;
} bleed[NeighbourSides::Count] =
{
{ // Left
_filterSize - uu,
hitFaceFilterBounds.m_min[1],
hitFaceFilterBounds.m_max[1],
},
{ // Right
uu + _filterSize - 1.0f,
hitFaceFilterBounds.m_min[1],
hitFaceFilterBounds.m_max[1],
},
{ // Top
_filterSize - vv,
hitFaceFilterBounds.m_min[0],
hitFaceFilterBounds.m_max[0],
},
{ // Bottom
vv + _filterSize - 1.0f,
hitFaceFilterBounds.m_min[0],
hitFaceFilterBounds.m_max[0],
},
};
// Determine bleeding for each side.
for (uint8_t side = 0; side < 4; ++side)
{
uint8_t currentFaceIdx = hitFaceIdx;
for (float bleedAmount = bleed[side].m_amount; bleedAmount > 0.0f; bleedAmount -= 1.0f)
{
uint8_t neighbourFaceIdx = s_cubeFaceNeighbours[currentFaceIdx][side].m_faceIdx;
uint8_t neighbourFaceEdge = s_cubeFaceNeighbours[currentFaceIdx][side].m_faceEdge;
currentFaceIdx = neighbourFaceIdx;
///
/// https://code.google.com/p/cubemapgen/source/browse/trunk/CCubeMapProcessor.cpp#773
///
/// Handle situations when bbMin and bbMax should be flipped.
///
/// L - Left ....................T-T
/// R - Right v .
/// T - Top __________ .
/// B - Bottom . | .
/// . | .
/// . |<...R-T .
/// . | v v
/// .......... ..........|__________ __________
/// . . . . .
/// . . . . .
/// . . . . .
/// . . . . .
/// __________ .......... .......... __________
/// ^ | . ^
/// . | . .
/// B-L..>| . .
/// | . .
/// |__________. .
/// ^ .
/// ....................B-B
///
/// Those are:
/// B-L, B-B
/// T-R, T-T
/// (and in reverse order, R-T and L-B)
///
/// If we add, R-R and L-L (which never occur), we get:
/// B-L, B-B
/// T-R, T-T
/// R-T, R-R
/// L-B, L-L
///
/// And if L = 0, R = 1, T = 2, B = 3 as in NeighbourSides enumeration,
/// a general rule can be derived for when to flip bbMin and bbMax:
/// if ((a+b) == 3 || (a == b))
/// {
/// ..flip bbMin and bbMax
/// }
///
float bbMin = bleed[side].m_bbMin;
float bbMax = bleed[side].m_bbMax;
if ((side == neighbourFaceEdge)
|| (3 == (side + neighbourFaceEdge)))
{
// Flip.
bbMin = 1.0f - bbMin;
bbMax = 1.0f - bbMax;
}
switch (neighbourFaceEdge)
{
case CMFT_EDGE_LEFT:
{
/// --> U
/// | .............
/// v . .
/// V x___ .
/// | | .
/// | | .
/// |___x .
/// . .
/// .............
///
_filterArea[neighbourFaceIdx].add(0.0f, bbMin);
_filterArea[neighbourFaceIdx].add(bleedAmount, bbMax);
}
break;
case CMFT_EDGE_RIGHT:
{
/// --> U
/// | .............
/// v . .
/// V . x___.
/// . | |
/// . | |
/// . |___x
/// . .
/// .............
///
_filterArea[neighbourFaceIdx].add(1.0f - bleedAmount, bbMin);
_filterArea[neighbourFaceIdx].add(1.0f, bbMax);
}
break;
case CMFT_EDGE_TOP:
{
/// --> U
/// | ...x____ ...
/// v . | | .
/// V . |____x .
/// . .
/// . .
/// . .
/// ............
///
_filterArea[neighbourFaceIdx].add(bbMin, 0.0f);
_filterArea[neighbourFaceIdx].add(bbMax, bleedAmount);
}
break;
case CMFT_EDGE_BOTTOM:
{
/// --> U
/// | ............
/// v . .
/// V . .
/// . .
/// . x____ .
/// . | | .
/// ...|____x...
///
_filterArea[neighbourFaceIdx].add(bbMin, 1.0f - bleedAmount);
_filterArea[neighbourFaceIdx].add(bbMax, 1.0f);
}
break;
}
// Clamp bounding box to face size.
_filterArea[neighbourFaceIdx].clamp(0.0f, 1.0f);
}
}
}
template <typename floatOrDouble>
void processFilterArea(floatOrDouble _res[3]
, float _specularPower
, float _specularAngle
, const float* _tapVec
, const float* _cubemapNormalSolidAngle
, Aabb _filterArea[6]
, uint32_t _srcFaceSize
, const void* _srcData
, const uint32_t _faceOffsets[6]
)
{
floatOrDouble colorWeight[4] = { floatOrDouble(0.0), floatOrDouble(0.0), floatOrDouble(0.0), floatOrDouble(0.0) };
const uint32_t bytesPerPixel = 4 /*numChannels*/ * 4 /*bytesPerChannel*/;
const uint32_t pitch = _srcFaceSize*bytesPerPixel;
const uint32_t normalFaceSize = pitch*_srcFaceSize;
const float faceSize_MinusOne = float(int32_t(_srcFaceSize-1));
for (uint8_t face = 0; face < 6; ++face)
{
if (_filterArea[face].isEmpty())
{
continue;
}
const uint32_t minX = uint32_t(_filterArea[face].m_min[0] * faceSize_MinusOne);
const uint32_t maxX = uint32_t(_filterArea[face].m_max[0] * faceSize_MinusOne);
const uint32_t minY = uint32_t(_filterArea[face].m_min[1] * faceSize_MinusOne);
const uint32_t maxY = uint32_t(_filterArea[face].m_max[1] * faceSize_MinusOne);
const uint8_t* faceData = (const uint8_t*)_srcData + _faceOffsets[face];
const uint8_t* faceNormals = (const uint8_t*)_cubemapNormalSolidAngle + normalFaceSize*face;
for (uint32_t yy = minY; yy <= maxY; ++yy)
{
const uint8_t* rowData = (const uint8_t*)faceData + yy*pitch;
const uint8_t* rowNormals = (const uint8_t*)faceNormals + yy*pitch;
for (uint32_t xx = minX; xx <= maxX; ++xx)
{
const float* normalPtr = (const float*)((const uint8_t*)rowNormals + xx*bytesPerPixel);
const float dotProduct = vec3Dot(normalPtr, _tapVec);
if (dotProduct >= _specularAngle)
{
const float solidAngle = normalPtr[3];
const floatOrDouble weight = floatOrDouble(solidAngle * powf(dotProduct, _specularPower));
const float* dataPtr = (const float*)((const uint8_t*)rowData + xx*bytesPerPixel);
colorWeight[0] += floatOrDouble(dataPtr[0]) * weight;
colorWeight[1] += floatOrDouble(dataPtr[1]) * weight;
colorWeight[2] += floatOrDouble(dataPtr[2]) * weight;
colorWeight[3] += floatOrDouble(1.0) * weight;
}
}
}
}
// Divide color by colorWeight and store result.
if (0.0f != colorWeight[3])
{
const floatOrDouble invWeight = floatOrDouble(1.0)/colorWeight[3];
_res[0] = colorWeight[0] * invWeight;
_res[1] = colorWeight[1] * invWeight;
_res[2] = colorWeight[2] * invWeight;
}
// Else if colorWeight == 0 (result of convolution is zero) take a direct color sample.
else
{
float uu, vv;
uint8_t hitFaceIdx;
vecToTexelCoord(uu, vv, hitFaceIdx, _tapVec);
const uint32_t xx = uint32_t(uu*float(_srcFaceSize));
const uint32_t yy = uint32_t(vv*float(_srcFaceSize));
const float* dataPtr = (const float*)((const uint8_t*)_srcData
+ _faceOffsets[hitFaceIdx]
+ yy*pitch
+ xx*bytesPerPixel
);
_res[0] = floatOrDouble(dataPtr[0]);
_res[1] = floatOrDouble(dataPtr[1]);
_res[2] = floatOrDouble(dataPtr[2]);
}
}
void radianceFilter(float *_dstPtr
, uint8_t _face
, uint32_t _mipFaceSize
, float _filterSize
, float _specularPower
, float _specularAngle
, const float* _cubemapVectors
, const Image* _imageRgba32f
, const uint32_t _faceOffsets[CUBE_FACE_NUM]
)
{
const float invFaceSize = 1.0f/float(int32_t(_mipFaceSize));
for (uint32_t yy = 0; yy < _mipFaceSize; ++yy)
{
for (uint32_t xx = 0; xx < _mipFaceSize; ++xx)
{
// From [0..size-1] to [-1.0+invSize .. 1.0-invSize].
const float xxf = float(int32_t(xx));
const float yyf = float(int32_t(yy));
const float uu = 2.0f*(xxf+0.5f)*invFaceSize - 1.0f;
const float vv = 2.0f*(yyf+0.5f)*invFaceSize - 1.0f;
float tapVec[3];
texelCoordToVec(tapVec, uu, vv, _face, _mipFaceSize);
Aabb facesBb[6];
determineFilterArea(facesBb, tapVec, _filterSize);
float color[3];
processFilterArea<float>(color
, _specularPower
, _specularAngle
, tapVec
, _cubemapVectors
, facesBb
, _imageRgba32f->m_width
, _imageRgba32f->m_data
, _faceOffsets
);
_dstPtr[0] = float(color[0]);
_dstPtr[1] = float(color[1]);
_dstPtr[2] = float(color[2]);
_dstPtr[3] = 1.0f;
_dstPtr += 4;
}
}
}
struct RadianceFilterGlobalState
{
RadianceFilterGlobalState()
: m_startTime(0)
, m_completedTasksGpu(0)
, m_completedTasksCpu(0)
, m_threadId(0)
{
}
uint8_t getThreadId()
{
bx::MutexScope lock(m_threadIdMutex);
return m_threadId++;
}
void incrCompletedTasksGpu()
{
bx::MutexScope lock(m_completedTasksCpuMutex);
m_completedTasksCpu++;
}
void incrCompletedTasksCpu()
{
bx::MutexScope lock(m_completedTasksGpuMutex);
m_completedTasksGpu++;
}
uint64_t m_startTime;
uint16_t m_completedTasksGpu;
uint16_t m_completedTasksCpu;
uint8_t m_threadId;
bx::Mutex m_threadIdMutex;
bx::Mutex m_completedTasksGpuMutex;
bx::Mutex m_completedTasksCpuMutex;
};
static RadianceFilterGlobalState s_globalState;
struct RadianceFilterParams
{
float* m_dstPtr;
uint8_t m_face;
uint32_t m_mipFaceSize;
float m_filterSize;
float m_specularPower;
float m_specularAngle;
const float* m_cubemapVectors;
const Image* m_imageRgba32f;
const uint32_t* m_faceOffsets;
};
struct RadianceFilterTaskList
{
RadianceFilterTaskList(uint8_t _mipStart, uint8_t _mipCount)
: m_topMipIndex(_mipStart)
, m_bottomMipIndex(_mipCount-1)
, m_totalMipCount(_mipCount)
{
memset(m_mipFaceIdx, 0, MAX_MIP_NUM);
}
// Returns cube face radiance filter parameters starting from the top mip level.
const RadianceFilterParams* getFromTop()
{
bx::MutexScope lock(m_indexMutex);
while (m_topMipIndex <= m_bottomMipIndex)
{
if (m_mipFaceIdx[m_topMipIndex] >= 6)
{
m_topMipIndex++;
}
else
{
return &m_params[m_topMipIndex][m_mipFaceIdx[m_topMipIndex]++];
}
}
return NULL;
}
// Returns cube face radiance filter parameters starting from the bottom mip level.
const RadianceFilterParams* getFromBottom(uint8_t _numLevels = 0)
{
bx::MutexScope lock(m_indexMutex);
const uint8_t barrier = (0 == _numLevels) ? m_topMipIndex : max(m_topMipIndex, uint8_t(m_totalMipCount-_numLevels));
while (barrier <= m_bottomMipIndex)
{
if (m_mipFaceIdx[m_bottomMipIndex] >= 6)
{
m_bottomMipIndex--;
}
else
{
return &m_params[m_bottomMipIndex][m_mipFaceIdx[m_bottomMipIndex]++];
}
}
return NULL;
}
bx::Mutex m_indexMutex;
uint8_t m_topMipIndex;
uint8_t m_bottomMipIndex;
uint8_t m_totalMipCount;
uint8_t m_mipFaceIdx[MAX_MIP_NUM];
RadianceFilterParams m_params[MAX_MIP_NUM][CUBE_FACE_NUM];
};
int32_t radianceFilterCpu(void* _taskList)
{
const uint8_t threadId = s_globalState.getThreadId();
const double freq = double(bx::getHPFrequency());
const double toSec = 1.0/freq;
RadianceFilterTaskList* taskList = (RadianceFilterTaskList*)_taskList;
// Gpu is processing from the top level mip map to the bottom.
const RadianceFilterParams* params;
while ((params = taskList->getFromTop()) != NULL)
{
// Start timer.
const uint64_t startTime = bx::getHPCounter();
// Process data.
radianceFilter(params->m_dstPtr
, params->m_face
, params->m_mipFaceSize
, params->m_filterSize
, params->m_specularPower
, params->m_specularAngle
, params->m_cubemapVectors
, params->m_imageRgba32f
, params->m_faceOffsets
);
// Determine task duration.
const uint64_t currentTime = bx::getHPCounter();
const uint64_t taskDuration = currentTime - startTime;
const uint64_t totalDuration = currentTime - s_globalState.m_startTime;
// Output process info.
char cpuId[16];
sprintf(cpuId, "[CPU%u]", threadId);
INFO("Radiance -> %-8s| %4u | %7.3fs | %7.3fs"
, cpuId
, params->m_mipFaceSize
, double(taskDuration)*toSec
, double(totalDuration)*toSec
);
// Update task counter.
s_globalState.incrCompletedTasksGpu();
}
return EXIT_SUCCESS;
}
struct RadianceProgram
{
RadianceProgram()
: m_clContext(NULL)
, m_program(NULL)
, m_kernel(NULL)
, m_event(NULL)
, m_memOut(NULL)
{
m_memSrcData[0] = NULL;
m_memSrcData[1] = NULL;
m_memSrcData[2] = NULL;
m_memSrcData[3] = NULL;
m_memSrcData[4] = NULL;
m_memSrcData[5] = NULL;
m_memNormalSolidAngle[0] = NULL;
m_memNormalSolidAngle[1] = NULL;
m_memNormalSolidAngle[2] = NULL;
m_memNormalSolidAngle[3] = NULL;
m_memNormalSolidAngle[4] = NULL;
m_memNormalSolidAngle[5] = NULL;
}
void setClContext(const ClContext* _clContext)
{
m_clContext = _clContext;
}
bool hasValidDeviceContext() const
{
return (NULL != m_clContext && NULL != m_clContext->m_context);
}
bool isValid() const
{
return (NULL != m_program);
}
bool createFromStr(const char* _sourceCode, const char* _kernelName)
{
cl_int err;
// Create program.
m_program = clCreateProgramWithSource(m_clContext->m_context, 1, (const char**)&_sourceCode, NULL, &err);
if (CL_SUCCESS != err)
{
WARN("Could not create OpenCL program. OpenCL source file probably missing!");
return false;
}
// Build program.
err = clBuildProgram(m_program, 1, &m_clContext->m_device, NULL, NULL, NULL);
if (CL_SUCCESS != err)
{
// Print error.
char buffer[10240];
clGetProgramBuildInfo(m_program, m_clContext->m_device, CL_PROGRAM_BUILD_LOG, sizeof(buffer), buffer, NULL);
WARN("CL Compilation failed:\n%s", buffer);
return false;
}
// Create OpenCL Kernel.
m_kernel = clCreateKernel(m_program, _kernelName, &err);
if (CL_SUCCESS != err)
{
WARN("Could not create OpenCL kernel. Kernel name probably inavlid! Should be: %s", _kernelName);
return false;
}
return true;
}
bool createFromFile(const char* _filePath, const char* _kernelName)
{
CMFT_UNUSED size_t read;
// Open file.
FILE* fp = fopen(_filePath, "rb");
if (NULL == fp)
{
WARN("Could not open file %s for reading.", _filePath);
return false;
}
ScopeFclose cleanup0(fp);
// Alloc data for string.
const long int fileSize = fsize(fp);
char* sourceData = (char*)malloc(fileSize+1);
ScopeFree cleanup1(sourceData);
// Read opencl source file.
read = fread(sourceData, fileSize, 1, fp);
sourceData[fileSize] = '\0';
DEBUG_CHECK(read == 1, "Could not read from file.");
FERROR_CHECK(fp);
bool result = createFromStr(sourceData, _kernelName);
return result;
}
void initDeviceMemory(const Image& _image, float* _cubemapNormalSolidAngle)
{
cl_int err;
uint32_t faceOffsets[CUBE_FACE_NUM];
imageGetFaceOffsets(faceOffsets, _image);
const cl_image_format imageFormat = { CL_RGBA, CL_FLOAT };
const uint32_t bytesPerPixel = 4 /*numChannels*/ * 4 /*bytesPerChannel*/;
const uint32_t normalFaceSize = _image.m_width * _image.m_width * bytesPerPixel;
for (uint8_t face = 0; face < 6; ++face)
{
m_memSrcData[face] = CL_CHECK_ERR(clCreateImage2D(m_clContext->m_context
, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR
, &imageFormat
, _image.m_width
, _image.m_height
, _image.m_width*bytesPerPixel
, (void*)((uint8_t*)_image.m_data + faceOffsets[face])
, &err
));
m_memNormalSolidAngle[face] = CL_CHECK_ERR(clCreateImage2D(m_clContext->m_context
, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR
, &imageFormat
, _image.m_width
, _image.m_height
, _image.m_width*bytesPerPixel
, (void*)((uint8_t*)_cubemapNormalSolidAngle + normalFaceSize*face)
, &err
));
}
CL_CHECK(clSetKernelArg(m_kernel, 5, sizeof(int32_t), (const void*)&_image.m_width));
CL_CHECK(clSetKernelArg(m_kernel, 6, sizeof(cl_mem), (const void*)&m_memSrcData[0]));
CL_CHECK(clSetKernelArg(m_kernel, 7, sizeof(cl_mem), (const void*)&m_memSrcData[1]));
CL_CHECK(clSetKernelArg(m_kernel, 8, sizeof(cl_mem), (const void*)&m_memSrcData[2]));
CL_CHECK(clSetKernelArg(m_kernel, 9, sizeof(cl_mem), (const void*)&m_memSrcData[3]));
CL_CHECK(clSetKernelArg(m_kernel, 10, sizeof(cl_mem), (const void*)&m_memSrcData[4]));
CL_CHECK(clSetKernelArg(m_kernel, 11, sizeof(cl_mem), (const void*)&m_memSrcData[5]));
CL_CHECK(clSetKernelArg(m_kernel, 12, sizeof(cl_mem), (const void*)&m_memNormalSolidAngle[0]));
CL_CHECK(clSetKernelArg(m_kernel, 13, sizeof(cl_mem), (const void*)&m_memNormalSolidAngle[1]));
CL_CHECK(clSetKernelArg(m_kernel, 14, sizeof(cl_mem), (const void*)&m_memNormalSolidAngle[2]));
CL_CHECK(clSetKernelArg(m_kernel, 15, sizeof(cl_mem), (const void*)&m_memNormalSolidAngle[3]));
CL_CHECK(clSetKernelArg(m_kernel, 16, sizeof(cl_mem), (const void*)&m_memNormalSolidAngle[4]));
CL_CHECK(clSetKernelArg(m_kernel, 17, sizeof(cl_mem), (const void*)&m_memNormalSolidAngle[5]));
}
void setupOutputBuffer(uint32_t _dstFaceSize)
{
cl_int err;
if (NULL != m_memOut)
{
clReleaseMemObject(m_memOut);
m_memOut = NULL;
}
const cl_image_format imageFormat = { CL_RGBA, CL_FLOAT };
m_memOut = CL_CHECK_ERR(clCreateImage2D(m_clContext->m_context
, CL_MEM_WRITE_ONLY
, &imageFormat
, _dstFaceSize
, _dstFaceSize
, 0
, NULL
, &err
));
CL_CHECK(clSetKernelArg(m_kernel, 0, sizeof(cl_mem), (const void*)&m_memOut));
}
void setArgs(uint8_t _faceId, uint32_t _dstFaceSize, float _specularPower, float _specularAngle) const
{
CL_CHECK(clSetKernelArg(m_kernel, 1, sizeof(float), (const void*)&_specularPower));
CL_CHECK(clSetKernelArg(m_kernel, 2, sizeof(float), (const void*)&_specularAngle));
CL_CHECK(clSetKernelArg(m_kernel, 3, sizeof(int32_t), (const void*)&_dstFaceSize));
CL_CHECK(clSetKernelArg(m_kernel, 4, sizeof(uint8_t), (const void*)&_faceId));
}
bool isIdle() const
{
cl_int status;
clGetEventInfo(m_event, CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof(cl_int), (void*)&status, NULL);
return ((CL_COMPLETE == status) || (NULL == m_event));
}
void run(uint32_t _dstFaceSize)
{
size_t workSize[2] = { _dstFaceSize, _dstFaceSize };
CL_CHECK(clEnqueueNDRangeKernel(m_clContext->m_commandQueue, m_kernel, 2, NULL, workSize, NULL, 0, NULL, &m_event));
}
void readResults(void* _out, uint32_t _dstFaceSize)
{
const uint32_t bytesPerPixel = 4 /*numChannels*/ * 4 /*bytesPerChannel*/;
const size_t origin[3] = { 0, 0, 0 };
const size_t region[3] = { _dstFaceSize, _dstFaceSize, 1 };
CL_CHECK(clEnqueueReadImage(m_clContext->m_commandQueue
, m_memOut
, CL_TRUE
, origin
, region
, _dstFaceSize*bytesPerPixel
, 0
, _out
, 0
, NULL
, &m_event
));
}
void finish() const
{
clFinish(m_clContext->m_commandQueue);
}
void releaseDeviceMemory()
{
#define RELEASE_CL_MEM(_mem) do { if (NULL != (_mem)) { clReleaseMemObject(_mem); (_mem) = NULL; } } while (0)
RELEASE_CL_MEM(m_memOut);
RELEASE_CL_MEM(m_memSrcData[0]);
RELEASE_CL_MEM(m_memSrcData[1]);
RELEASE_CL_MEM(m_memSrcData[2]);
RELEASE_CL_MEM(m_memSrcData[3]);
RELEASE_CL_MEM(m_memSrcData[4]);
RELEASE_CL_MEM(m_memSrcData[5]);
RELEASE_CL_MEM(m_memNormalSolidAngle[0]);
RELEASE_CL_MEM(m_memNormalSolidAngle[1]);
RELEASE_CL_MEM(m_memNormalSolidAngle[2]);
RELEASE_CL_MEM(m_memNormalSolidAngle[3]);
RELEASE_CL_MEM(m_memNormalSolidAngle[4]);
RELEASE_CL_MEM(m_memNormalSolidAngle[5]);
#undef RELEASE_CL_MEM
}
void destroy()
{
if (NULL != m_program)
{
clReleaseProgram(m_program);
m_program = NULL;
}
if (NULL != m_kernel)
{
clReleaseKernel(m_kernel);
m_kernel = NULL;
}
}
const ClContext* m_clContext;
cl_program m_program;
cl_kernel m_kernel;
cl_event m_event;
cl_mem m_memOut;
cl_mem m_memSrcData[6];
cl_mem m_memNormalSolidAngle[6];
};
RadianceProgram s_radianceProgram;
int32_t radianceFilterGpu(void* _taskList)
{
if (!s_radianceProgram.isValid())
{
return EXIT_FAILURE;
}
const double freq = double(bx::getHPFrequency());
const double toSec = 1.0/freq;
RadianceFilterTaskList* taskList = (RadianceFilterTaskList*)_taskList;
// Gpu is processing from the top level mip map to the bottom.
const RadianceFilterParams* params;
while ((params = taskList->getFromTop()) != NULL)
{
// Start timer.
const uint64_t startTime = bx::getHPCounter();
// Prepare parameters.
s_radianceProgram.setupOutputBuffer(params->m_mipFaceSize);
s_radianceProgram.setArgs(params->m_face
, params->m_mipFaceSize
, params->m_specularPower
, params->m_specularAngle
);
// Enqueue processing job.
s_radianceProgram.run(params->m_mipFaceSize);
// Read results.
s_radianceProgram.readResults(params->m_dstPtr, params->m_mipFaceSize);
// Determine task duration.
const uint64_t currentTime = bx::getHPCounter();
const uint64_t taskDuration = currentTime - startTime;
const uint64_t totalDuration = currentTime - s_globalState.m_startTime;
// Output process info.
INFO("Radiance -> <GPU> | %4u | %7.3fs | %7.3fs"
, params->m_mipFaceSize
, double(taskDuration)*toSec
, double(totalDuration)*toSec
);
// Update task counter.
s_globalState.incrCompletedTasksCpu();
}
return EXIT_SUCCESS;
}
static const char* s_lightingModelStr[LightingModel::Count] =
{
"phong",
"phongbrdf",
"blinn",
"blinnbrdf",
};
const char* getLightingModelStr(LightingModel::Enum _lightingModel)
{
DEBUG_CHECK(_lightingModel < LightingModel::Count, "Reading array out of bounds!");
return s_lightingModelStr[uint8_t(_lightingModel)];
}
/// Returns the angle of cosine power function where the results are above a small empirical treshold.
static float cosinePowerFilterAngle(float _cosinePower)
{
// Bigger value leads to performance improvement but might hurt the results.
// 0.00001f was tested empirically and it gives almost the same values as reference.
const float treshold = 0.00001f;
// Cosine power filter is: pow(cos(angle), power).
// We want the value of the angle above each result is <= treshold.
// So: angle = acos(pow(treshold, 1.0 / power))
return acosf(powf(treshold, 1.0f / _cosinePower));
}
float applyLightningModel(float _specularPowerRef, LightingModel::Enum _lightingModel)
{
/// http://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
/// http://seblagarde.wordpress.com/2012/03/29/relationship-between-phong-and-blinn-lighting-model/
switch (_lightingModel)
{
case LightingModel::Phong:
{
return _specularPowerRef;
}
break;
case LightingModel::PhongBrdf:
{
return _specularPowerRef + 1.0f;
}
break;
case LightingModel::Blinn:
{
return _specularPowerRef/4.0f;
}
break;
case LightingModel::BlinnBrdf:
{
return _specularPowerRef/4.0f + 1.0f;
}
break;
default:
{
DEBUG_CHECK(false, "ERROR! This should never happen!");
WARN("Lighting model error. Please check for invalid parameters!");
return _specularPowerRef;
}
break;
};
}
bool imageRadianceFilter(Image& _dst
, uint32_t _dstFaceSize
, LightingModel::Enum _lightingModel
, bool _excludeBase
, uint8_t _mipCount
, uint8_t _glossScale
, uint8_t _glossBias
, const Image& _src
, int8_t _numCpuProcessingThreads
, const ClContext* _clContext
)
{
// Input image must be a cubemap.
if (!imageIsCubemap(_src))
{
WARN("Image is not cubemap.");
return false;
}
// Multi-threading parameters.
bx::Thread cpuThreads[64];
uint8_t activeCpuThreads = 0;
const uint8_t maxActiveCpuThreads = (uint8_t)max(int8_t(0), min(_numCpuProcessingThreads, int8_t(64)));
// Prepare OpenCL kernel and device memory.
s_radianceProgram.setClContext(_clContext);
if (s_radianceProgram.hasValidDeviceContext())
{
s_radianceProgram.createFromStr(s_radianceProgramSource, "radianceFilter");
}
// Check at least some processig device is valid and choosen for filtering.
if (0 == maxActiveCpuThreads && !s_radianceProgram.isValid())
{
WARN("No hardware devices selected for processing."
" OpenCL context is invalid and 0 CPU processing theads are choosen for filtering."
);
return false;
}
// Don't use the same CPU device for OpenCL and CPU processing!
if (NULL != _clContext
&& _clContext->m_deviceType&CL_DEVICE_TYPE_CPU
&& maxActiveCpuThreads != 0)
{
WARN(" !! Choosing CPU device as OpenCL device and running CPU processing"
" threads on the SAME device is NOT a good idea. It will work, but it is"
" certainly not the best utilization of processing resources."
" In case OpenCL device type is CPU but it is a different processing"
" device other than the host device, simply ignore this warning. !!"
);
}
// Processing is done in Rgba32f format.
Image imageRgba32f;
imageRefOrConvert(imageRgba32f, TextureFormat::RGBA32F, _src);
// Alloc dst data.
const uint32_t dstFaceSize = (0 == _dstFaceSize) ? _src.m_width : _dstFaceSize;
const uint8_t mipMin = 1;
const uint8_t mipMax = (uint8_t)log2f(float(int32_t(dstFaceSize)))+uint8_t(1);
const uint8_t mipCount = clamp(_mipCount, mipMin, mipMax);
const uint32_t bytesPerPixel = 4 /*numChannels*/ * 4 /*bytesPerChannel*/;
uint32_t dstOffsets[CUBE_FACE_NUM][MAX_MIP_NUM];
uint32_t dstDataSize = 0;
for (uint8_t face = 0; face < 6; ++face)
{
for (uint8_t mip = 0; mip < mipCount; ++mip)
{
dstOffsets[face][mip] = dstDataSize;
uint32_t faceSize = max(uint32_t(1), dstFaceSize >> mip);
dstDataSize += faceSize * faceSize * bytesPerPixel;
}
}
void* dstData = malloc(dstDataSize);
MALLOC_CHECK(dstData);
// Get source image offsets.
uint32_t srcFaceOffsets[CUBE_FACE_NUM];
imageGetFaceOffsets(srcFaceOffsets, imageRgba32f);
// Output info.
INFO("Running radiance filter for:"
"\n\t[srcFaceSize=%u]"
"\n\t[lightingModel=%s]"
"\n\t[excludeBase=%s]"
"\n\t[mipCount=%u]"
"\n\t[glossScale=%u]"
"\n\t[glossBias=%u]"
"\n\t[dstFaceSize=%u]"
, imageRgba32f.m_width
, getLightingModelStr(_lightingModel)
, &"false\0true"[6*_excludeBase]
, mipCount
, _glossScale
, _glossBias
, dstFaceSize
);
// Resize and copy base image.
if (_excludeBase)
{
INFO("Radiance -> Excluding base image.");
const float dstToSrcRatio = float(int32_t(imageRgba32f.m_width))/float(int32_t(dstFaceSize));
const uint32_t dstFacePitch = dstFaceSize * bytesPerPixel;
const uint32_t srcFacePitch = imageRgba32f.m_width * bytesPerPixel;
// For all top level cubemap faces:
for(uint8_t face = 0; face < 6; ++face)
{
const uint8_t* srcFaceData = (const uint8_t*)imageRgba32f.m_data + srcFaceOffsets[face];
uint8_t* dstFaceData = (uint8_t*)dstData + dstOffsets[face][0];
// Iterate through destination pixels.
for (uint32_t yDst = 0; yDst < dstFaceSize; ++yDst)
{
uint8_t* dstFaceRow = (uint8_t*)dstFaceData + yDst*dstFacePitch;
for (uint32_t xDst = 0; xDst < dstFaceSize; ++xDst)
{
float* dstFaceColumn = (float*)((uint8_t*)dstFaceRow + xDst*bytesPerPixel);
// For each destination pixel, sample and accumulate color from source.
float color[3] = { 0.0f, 0.0f, 0.0f };
uint32_t weightAccum = 0;
for (uint32_t ySrc = uint32_t(float(yDst)*dstToSrcRatio)
, end = ySrc+max(uint32_t(1), uint32_t(dstToSrcRatio))
; ySrc < end
; ++ySrc)
{
const uint8_t* srcRowData = (const uint8_t*)srcFaceData + ySrc*srcFacePitch;
for (uint32_t xSrc = uint32_t(float(xDst)*dstToSrcRatio)
, end = xSrc+max(uint32_t(1), uint32_t(dstToSrcRatio))
; xSrc < end
; ++xSrc)
{
const float* srcColumnData = (const float*)((const uint8_t*)srcRowData + xSrc*bytesPerPixel);
color[0] += srcColumnData[0];
color[1] += srcColumnData[1];
color[2] += srcColumnData[2];
weightAccum++;
}
}
// Divide by weight and save to destination pixel.
const float invWeight = 1.0f/float(int32_t(weightAccum));
dstFaceColumn[0] = color[0] * invWeight;
dstFaceColumn[1] = color[1] * invWeight;
dstFaceColumn[2] = color[2] * invWeight;
dstFaceColumn[3] = 1.0f;
}
}
}
}
if (mipCount - uint8_t(_excludeBase) <= 0)
{
INFO("Radiance -> Nothing left for processing... Increase mip count or do not exclude base image.");
}
else
{
// Build cubemap vectors.
float* cubemapVectors = buildCubemapNormalSolidAngle(imageRgba32f.m_width);
ScopeFree cleanup(cubemapVectors);
// Enqueue memory transfer for cl device.
if (s_radianceProgram.isValid())
{
s_radianceProgram.initDeviceMemory(imageRgba32f, cubemapVectors);
}
// Start global timer.
s_globalState.m_startTime = bx::getHPCounter();
INFO("Radiance -> Starting filter...");
INFO("Radiance -> Utilizing %u CPU processing thread%s%s%s."
, maxActiveCpuThreads
, maxActiveCpuThreads==1?"":"s"
, !s_radianceProgram.isValid()?"":" and "
, !s_radianceProgram.isValid()?"":s_radianceProgram.m_clContext->m_deviceName
);
// Alloc data for tasks parameters.
const uint8_t mipStart = uint8_t(_excludeBase);
RadianceFilterTaskList taskList(mipStart, mipCount);
const float glossScalef = float(int32_t(_glossScale));
const float glossBiasf = float(int32_t(_glossBias));
//Prepare processing tasks parameters.
for (uint32_t mip = mipStart; mip < mipCount; ++mip)
{
// Determine filter parameters.
const uint32_t mipFaceSize = max(UINT32_C(1), dstFaceSize >> mip);
const float mipFaceSizef = float(int32_t(mipFaceSize));
const float minAngle = atan2f(1.0f, mipFaceSizef);
const float maxAngle = float(M_PI)/2.0f;
const float toFilterSize = 1.0f/(minAngle*mipFaceSizef*2.0f);
const float glossiness = (mipCount == 1)
? 1.0f
: max(0.0f, 1.0f - (float)(int32_t)mip/(float)(int32_t)(mipCount-1))
;
const float specularPowerRef = powf(2.0f, glossScalef * glossiness + glossBiasf);
const float specularPower = applyLightningModel(specularPowerRef, _lightingModel);
const float filterAngle = clamp(cosinePowerFilterAngle(specularPower), minAngle, maxAngle);
const float cosAngle = max(0.0f, cosf(filterAngle));
const float texelSize = 1.0f/mipFaceSizef;
const float filterSize = max(texelSize, filterAngle * toFilterSize);
for (uint8_t face = 0; face < 6; ++face)
{
float* dstPtr = (float*)((uint8_t*)dstData + dstOffsets[face][mip]);
RadianceFilterParams taskParams =
{
dstPtr,
face,
mipFaceSize,
filterSize,
specularPower,
cosAngle,
cubemapVectors,
&imageRgba32f,
srcFaceOffsets,
};
// Enqueue processing parameters.
memcpy(&taskList.m_params[mip][face], &taskParams, sizeof(RadianceFilterParams));
}
}
// Output process header info.
INFO("Radiance -> ------------------------------------");
INFO("Radiance -> Device / Face / Time / Total");
INFO("Radiance -> ------------------------------------");
// Single thread, no OpenCL.
if (maxActiveCpuThreads == 1 && !s_radianceProgram.isValid())
{
radianceFilterCpu((void*)&taskList);
}
// Multi thread (with or without OpenCL).
else
{
// Start CPU processing threads.
while (activeCpuThreads < maxActiveCpuThreads)
{
cpuThreads[activeCpuThreads++].init(radianceFilterCpu, (void*)&taskList);
}
// Start one GPU host thread.
if (s_radianceProgram.isValid() && s_radianceProgram.isIdle())
{
cpuThreads[activeCpuThreads++].init(radianceFilterGpu, (void*)&taskList);
}
// Wait for everything to finish.
for (uint8_t ii = 0; ii < activeCpuThreads; ++ii)
{
cpuThreads[ii].shutdown();
}
}
// Average 1x1 face size.
if ((dstFaceSize>>(mipCount-1)) <= 1)
{
float* face0 = (float*)((uint8_t*)dstData + dstOffsets[0][mipCount-1]);
float* face1 = (float*)((uint8_t*)dstData + dstOffsets[1][mipCount-1]);
float* face2 = (float*)((uint8_t*)dstData + dstOffsets[2][mipCount-1]);
float* face3 = (float*)((uint8_t*)dstData + dstOffsets[3][mipCount-1]);
float* face4 = (float*)((uint8_t*)dstData + dstOffsets[4][mipCount-1]);
float* face5 = (float*)((uint8_t*)dstData + dstOffsets[5][mipCount-1]);
const float color[3] =
{
(face0[0] + face1[0] + face2[0] + face3[0] + face4[0] + face5[0]) / 6.0f,
(face0[1] + face1[1] + face2[1] + face3[1] + face4[1] + face5[1]) / 6.0f,
(face0[2] + face1[2] + face2[2] + face3[2] + face4[2] + face5[2]) / 6.0f,
};
face0[0] = face1[0] = face2[0] = face3[0] = face4[0] = face5[0] = color[0];
face0[1] = face1[1] = face2[1] = face3[1] = face4[1] = face5[1] = color[1];
face0[2] = face1[2] = face2[2] = face3[2] = face4[2] = face5[2] = color[2];
}
// Get filter duration.
const double freq = double(bx::getHPFrequency());
const double toSec = 1.0/freq;
const uint64_t totalTime = bx::getHPCounter() - s_globalState.m_startTime;
// Output progress info.
INFO("Radiance -> ------------------------------------");
INFO("Radiance -> Total faces processed on [CPU]: %u", s_globalState.m_completedTasksCpu);
INFO("Radiance -> Total faces processed on <GPU>: %u", s_globalState.m_completedTasksGpu);
INFO("Radiance -> Total time: %.3f seconds.", double(totalTime)*toSec);
// Cleanup.
if (s_radianceProgram.isValid())
{
s_radianceProgram.releaseDeviceMemory();
s_radianceProgram.destroy();
}
}
// Fill result structure.
Image result;
result.m_width = dstFaceSize;
result.m_height = dstFaceSize;
result.m_dataSize = dstDataSize;
result.m_format = TextureFormat::RGBA32F;
result.m_numMips = mipCount;
result.m_numFaces = 6;
result.m_data = dstData;
// Convert back to source format.
if (TextureFormat::RGBA32F == _src.m_format)
{
imageMove(_dst, result);
}
else
{
imageConvert(_dst, (TextureFormat::Enum)_src.m_format, result);
imageUnload(result);
}
return true;
}
void imageRadianceFilter(Image& _image
, uint32_t _dstFaceSize
, LightingModel::Enum _lightingModel
, bool _excludeBase
, uint8_t _mipCount
, uint8_t _glossScale
, uint8_t _glossBias
, int8_t _numCpuProcessingThreads
, const ClContext* _clContext
)
{
Image tmp;
if(imageRadianceFilter(tmp, _dstFaceSize, _lightingModel, _excludeBase, _mipCount, _glossScale, _glossBias, _image, _numCpuProcessingThreads, _clContext))
{
imageMove(_image, tmp);
}
}
} // namespace cmft
/* vim: set sw=4 ts=4 expandtab: */
| [
"dariomanesku@gmail.com"
] | dariomanesku@gmail.com |
c8b789546a28fa492ea9fd4c4a0afe51f879ec9e | 8b4c4546f92e1f185fc666e645a5f32926a81666 | /thirdparty/physx/APEXSDK/framework/include/NxApexCudaProfileManager.h | 713bbb53f71a2a0fe9ce5327cc9815d8c79f9a39 | [
"MIT"
] | permissive | johndpope/echo | a5db22b07421f9c330c219cd5b0e841629c7543c | e9ce2f4037e8a5d49b74cc7a9d9ee09f296e7fa7 | refs/heads/master | 2020-04-03T03:52:59.454520 | 2018-11-22T20:55:32 | 2018-11-22T20:55:32 | 154,997,449 | 0 | 0 | MIT | 2018-11-22T20:55:33 | 2018-10-27T18:39:23 | C++ | UTF-8 | C++ | false | false | 1,499 | h | /*
* Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved.
*
* NVIDIA CORPORATION and its licensors retain all intellectual property
* and proprietary rights in and to this software, related documentation
* and any modifications thereto. Any use, reproduction, disclosure or
* distribution of this software and related documentation without an express
* license agreement from NVIDIA CORPORATION is strictly prohibited.
*/
#ifndef NX_APEX_CUDA_PROFILE_MANAGER_H
#define NX_APEX_CUDA_PROFILE_MANAGER_H
/*!
\file
\brief classes NxApexCudaProfileManager
*/
#include <NxApexDefs.h>
#include <foundation/PxSimpleTypes.h>
namespace physx
{
namespace apex
{
PX_PUSH_PACK_DEFAULT
/**
\brief Interface for options of ApexCudaProfileManager
*/
class NxApexCudaProfileManager
{
public:
/**
* Normalized time unit for profile data
*/
enum TimeFormat
{
MILLISECOND = 1,
MICROSECOND = 1000,
NANOSECOND = 1000000
};
/**
\brief Set path for writing results
*/
virtual void setPath(const char* path) = 0;
/**
\brief Set kernel for profile
*/
virtual void setKernel(const char* functionName, const char* moduleName) = 0;
/**
\brief Set normailized time unit
*/
virtual void setTimeFormat(TimeFormat tf) = 0;
/**
\brief Set state (on/off) for profile manager
*/
virtual void enable(bool state) = 0;
/**
\brief Get state (on/off) of profile manager
*/
virtual bool isEnabled() const = 0;
};
PX_POP_PACK
}
}
#endif // NX_APEX_CUDA_PROFILE_MANAGER_H
| [
"qq79402005@gmail.com"
] | qq79402005@gmail.com |
53b961ff6134a8c441bda493656f2e40103aaea1 | 184204d90009c8f75f645679be7e38e4af25b3a5 | /build-paper_exam-Desktop_Qt_5_2_1_MinGW_32bit-Debug/ui_practice_windows.h | f2b96cf1417c4cb621def703c557ffd92c478971 | [] | no_license | ProsperousLi/ExamSystem | 87313b3d49e64a95953b19bf588018a45f5f4fa5 | c09fbe9c3f9e5339388623b782ac3f72e14f650d | refs/heads/master | 2021-01-10T18:33:20.637271 | 2019-07-25T03:01:18 | 2019-07-25T03:01:18 | 57,092,607 | 8 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 12,513 | h | /********************************************************************************
** Form generated from reading UI file 'practice_windows.ui'
**
** Created by: Qt User Interface Compiler version 5.2.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_PRACTICE_WINDOWS_H
#define UI_PRACTICE_WINDOWS_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QFormLayout>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QMenu>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QRadioButton>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QTextEdit>
#include <QtWidgets/QToolBar>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_practice_windows
{
public:
QAction *action;
QAction *action_2;
QAction *action_3;
QWidget *centralWidget;
QPushButton *pushButton;
QPushButton *pushButton_2;
QPushButton *pushButton_3;
QPushButton *pushButton_6;
QLabel *label;
QWidget *formWidget;
QFormLayout *formLayout;
QRadioButton *radioButton;
QLineEdit *lineEdit;
QRadioButton *radioButton_2;
QLineEdit *lineEdit_2;
QRadioButton *radioButton_3;
QRadioButton *radioButton_4;
QLineEdit *lineEdit_4;
QLineEdit *lineEdit_3;
QRadioButton *radioButton_7;
QPushButton *pushButton_7;
QPushButton *pushButton_8;
QWidget *gridWidget;
QGridLayout *gridLayout;
QRadioButton *radioButton_6;
QRadioButton *radioButton_8;
QRadioButton *radioButton_5;
QTextEdit *textEdit;
QWidget *verticalLayoutWidget;
QVBoxLayout *verticalLayout;
QPushButton *pushButton_5;
QMenuBar *menuBar;
QMenu *menu;
QToolBar *mainToolBar;
QStatusBar *statusBar;
void setupUi(QMainWindow *practice_windows)
{
if (practice_windows->objectName().isEmpty())
practice_windows->setObjectName(QStringLiteral("practice_windows"));
practice_windows->resize(1003, 478);
action = new QAction(practice_windows);
action->setObjectName(QStringLiteral("action"));
action_2 = new QAction(practice_windows);
action_2->setObjectName(QStringLiteral("action_2"));
action_3 = new QAction(practice_windows);
action_3->setObjectName(QStringLiteral("action_3"));
centralWidget = new QWidget(practice_windows);
centralWidget->setObjectName(QStringLiteral("centralWidget"));
pushButton = new QPushButton(centralWidget);
pushButton->setObjectName(QStringLiteral("pushButton"));
pushButton->setGeometry(QRect(50, 40, 81, 31));
pushButton_2 = new QPushButton(centralWidget);
pushButton_2->setObjectName(QStringLiteral("pushButton_2"));
pushButton_2->setGeometry(QRect(50, 90, 81, 31));
pushButton_3 = new QPushButton(centralWidget);
pushButton_3->setObjectName(QStringLiteral("pushButton_3"));
pushButton_3->setGeometry(QRect(50, 140, 81, 31));
pushButton_6 = new QPushButton(centralWidget);
pushButton_6->setObjectName(QStringLiteral("pushButton_6"));
pushButton_6->setGeometry(QRect(870, 390, 71, 31));
label = new QLabel(centralWidget);
label->setObjectName(QStringLiteral("label"));
label->setGeometry(QRect(60, 220, 54, 12));
formWidget = new QWidget(centralWidget);
formWidget->setObjectName(QStringLiteral("formWidget"));
formWidget->setGeometry(QRect(430, 210, 441, 171));
formLayout = new QFormLayout(formWidget);
formLayout->setSpacing(6);
formLayout->setContentsMargins(11, 11, 11, 11);
formLayout->setObjectName(QStringLiteral("formLayout"));
formLayout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow);
radioButton = new QRadioButton(formWidget);
radioButton->setObjectName(QStringLiteral("radioButton"));
formLayout->setWidget(0, QFormLayout::LabelRole, radioButton);
lineEdit = new QLineEdit(formWidget);
lineEdit->setObjectName(QStringLiteral("lineEdit"));
lineEdit->setEnabled(false);
lineEdit->setFrame(false);
formLayout->setWidget(0, QFormLayout::FieldRole, lineEdit);
radioButton_2 = new QRadioButton(formWidget);
radioButton_2->setObjectName(QStringLiteral("radioButton_2"));
formLayout->setWidget(1, QFormLayout::LabelRole, radioButton_2);
lineEdit_2 = new QLineEdit(formWidget);
lineEdit_2->setObjectName(QStringLiteral("lineEdit_2"));
lineEdit_2->setEnabled(false);
lineEdit_2->setFrame(false);
formLayout->setWidget(1, QFormLayout::FieldRole, lineEdit_2);
radioButton_3 = new QRadioButton(formWidget);
radioButton_3->setObjectName(QStringLiteral("radioButton_3"));
formLayout->setWidget(2, QFormLayout::LabelRole, radioButton_3);
radioButton_4 = new QRadioButton(formWidget);
radioButton_4->setObjectName(QStringLiteral("radioButton_4"));
formLayout->setWidget(3, QFormLayout::LabelRole, radioButton_4);
lineEdit_4 = new QLineEdit(formWidget);
lineEdit_4->setObjectName(QStringLiteral("lineEdit_4"));
lineEdit_4->setEnabled(false);
lineEdit_4->setFrame(false);
formLayout->setWidget(3, QFormLayout::FieldRole, lineEdit_4);
lineEdit_3 = new QLineEdit(formWidget);
lineEdit_3->setObjectName(QStringLiteral("lineEdit_3"));
lineEdit_3->setEnabled(false);
lineEdit_3->setFrame(false);
formLayout->setWidget(2, QFormLayout::FieldRole, lineEdit_3);
radioButton_7 = new QRadioButton(formWidget);
radioButton_7->setObjectName(QStringLiteral("radioButton_7"));
formLayout->setWidget(4, QFormLayout::LabelRole, radioButton_7);
pushButton_7 = new QPushButton(centralWidget);
pushButton_7->setObjectName(QStringLiteral("pushButton_7"));
pushButton_7->setGeometry(QRect(270, 380, 121, 31));
pushButton_8 = new QPushButton(centralWidget);
pushButton_8->setObjectName(QStringLiteral("pushButton_8"));
pushButton_8->setGeometry(QRect(420, 380, 131, 31));
gridWidget = new QWidget(centralWidget);
gridWidget->setObjectName(QStringLiteral("gridWidget"));
gridWidget->setGeometry(QRect(250, 250, 151, 131));
gridLayout = new QGridLayout(gridWidget);
gridLayout->setSpacing(6);
gridLayout->setContentsMargins(11, 11, 11, 11);
gridLayout->setObjectName(QStringLiteral("gridLayout"));
radioButton_6 = new QRadioButton(gridWidget);
radioButton_6->setObjectName(QStringLiteral("radioButton_6"));
gridLayout->addWidget(radioButton_6, 2, 0, 1, 1);
radioButton_8 = new QRadioButton(gridWidget);
radioButton_8->setObjectName(QStringLiteral("radioButton_8"));
gridLayout->addWidget(radioButton_8, 3, 0, 1, 1);
radioButton_5 = new QRadioButton(gridWidget);
radioButton_5->setObjectName(QStringLiteral("radioButton_5"));
gridLayout->addWidget(radioButton_5, 0, 0, 1, 1);
textEdit = new QTextEdit(centralWidget);
textEdit->setObjectName(QStringLiteral("textEdit"));
textEdit->setEnabled(false);
textEdit->setGeometry(QRect(250, 30, 401, 181));
verticalLayoutWidget = new QWidget(centralWidget);
verticalLayoutWidget->setObjectName(QStringLiteral("verticalLayoutWidget"));
verticalLayoutWidget->setGeometry(QRect(670, 40, 160, 168));
verticalLayout = new QVBoxLayout(verticalLayoutWidget);
verticalLayout->setSpacing(6);
verticalLayout->setContentsMargins(11, 11, 11, 11);
verticalLayout->setObjectName(QStringLiteral("verticalLayout"));
verticalLayout->setContentsMargins(0, 0, 0, 0);
pushButton_5 = new QPushButton(centralWidget);
pushButton_5->setObjectName(QStringLiteral("pushButton_5"));
pushButton_5->setGeometry(QRect(250, 220, 81, 23));
practice_windows->setCentralWidget(centralWidget);
formWidget->raise();
pushButton->raise();
pushButton_2->raise();
pushButton_3->raise();
pushButton_6->raise();
label->raise();
pushButton_7->raise();
pushButton_8->raise();
gridWidget->raise();
textEdit->raise();
verticalLayoutWidget->raise();
pushButton_5->raise();
menuBar = new QMenuBar(practice_windows);
menuBar->setObjectName(QStringLiteral("menuBar"));
menuBar->setGeometry(QRect(0, 0, 1003, 23));
menu = new QMenu(menuBar);
menu->setObjectName(QStringLiteral("menu"));
practice_windows->setMenuBar(menuBar);
mainToolBar = new QToolBar(practice_windows);
mainToolBar->setObjectName(QStringLiteral("mainToolBar"));
practice_windows->addToolBar(Qt::TopToolBarArea, mainToolBar);
statusBar = new QStatusBar(practice_windows);
statusBar->setObjectName(QStringLiteral("statusBar"));
practice_windows->setStatusBar(statusBar);
menuBar->addAction(menu->menuAction());
menu->addAction(action);
menu->addAction(action_2);
menu->addAction(action_3);
retranslateUi(practice_windows);
QMetaObject::connectSlotsByName(practice_windows);
} // setupUi
void retranslateUi(QMainWindow *practice_windows)
{
practice_windows->setWindowTitle(QApplication::translate("practice_windows", "\347\273\203\344\271\240\347\225\214\351\235\242", 0));
action->setText(QApplication::translate("practice_windows", "\351\200\211\346\213\251\351\242\230", 0));
action_2->setText(QApplication::translate("practice_windows", "\345\241\253\347\251\272\351\242\230", 0));
action_3->setText(QApplication::translate("practice_windows", "\345\210\244\346\226\255\351\242\230", 0));
pushButton->setText(QApplication::translate("practice_windows", "\351\200\211\346\213\251\351\242\230", 0));
pushButton_2->setText(QApplication::translate("practice_windows", "\345\241\253\347\251\272\351\242\230", 0));
pushButton_3->setText(QApplication::translate("practice_windows", "\345\210\244\346\226\255\351\242\230", 0));
pushButton_6->setText(QApplication::translate("practice_windows", "\351\200\200\345\207\272", 0));
label->setText(QApplication::translate("practice_windows", "\345\205\250\351\203\250\351\242\230\345\236\213", 0));
radioButton->setText(QApplication::translate("practice_windows", "A", 0));
radioButton_2->setText(QApplication::translate("practice_windows", "B", 0));
radioButton_3->setText(QApplication::translate("practice_windows", "C", 0));
radioButton_4->setText(QApplication::translate("practice_windows", "D", 0));
radioButton_7->setText(QApplication::translate("practice_windows", "\351\200\211\346\213\251\351\242\230\344\274\217\347\254\224", 0));
pushButton_7->setText(QApplication::translate("practice_windows", "\344\270\212\344\270\200\351\242\230", 0));
pushButton_8->setText(QApplication::translate("practice_windows", "\344\270\213\344\270\200\351\242\230", 0));
radioButton_6->setText(QApplication::translate("practice_windows", "false", 0));
radioButton_8->setText(QApplication::translate("practice_windows", "\345\210\244\346\226\255\351\242\230\344\274\217\347\254\224", 0));
radioButton_5->setText(QApplication::translate("practice_windows", "true", 0));
pushButton_5->setText(QApplication::translate("practice_windows", "\346\230\276\347\244\272\347\255\224\346\241\210", 0));
menu->setTitle(QApplication::translate("practice_windows", "\346\226\207\344\273\266", 0));
} // retranslateUi
};
namespace Ui {
class practice_windows: public Ui_practice_windows {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_PRACTICE_WINDOWS_H
| [
"806966854@qq.com"
] | 806966854@qq.com |
53646f882026df41807360adcdf1a57efa80290e | 0185b0451c89d8758af022f2e15225317dba85c8 | /CPP_module_04/ex01/AWeapon.cpp | 56d1337180047b83fb4de221cbaa9365547658ae | [] | no_license | atomatoe/CPP_modules | 8c6acb03193f7ae39d732f44bd08a38678f6be7d | b0ca9d84a8fe4404caa1cc2e6f886abc151bb765 | refs/heads/master | 2023-03-24T05:47:03.209605 | 2021-03-16T20:21:22 | 2021-03-16T20:21:22 | 320,817,437 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,765 | cpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* AWeapon.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: atomatoe <atomatoe@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/12/05 15:42:22 by atomatoe #+# #+# */
/* Updated: 2020/12/08 14:15:35 by atomatoe ### ########.fr */
/* */
/* ************************************************************************** */
#include "AWeapon.hpp"
AWeapon::AWeapon()
{
// std::cout << "Standart AWeapon created!" << std::endl;
}
AWeapon::AWeapon(const AWeapon &type)
{
*this = type;
}
AWeapon::AWeapon(std::string const & name, int damage, int apcost)
{
this->name = name;
this->ap_cost = apcost;
this->damage = damage;
this->out_attack = "pew";
// std::cout << this->name << " AWeapon created!" << std::endl;
}
std::string AWeapon::getName() const
{
return(name);
}
int AWeapon::getDamage() const
{
return(damage);
}
AWeapon & AWeapon::operator=(const AWeapon &type)
{
this->name = type.name;
this->damage = type.damage;
this->ap_cost = type.ap_cost;
this->out_attack = type.out_attack;
return(*this);
}
int AWeapon::getAPCost() const
{
return(ap_cost);
}
AWeapon::~AWeapon()
{
std::cout << "AWeapon deleted!" << std::endl;
} | [
"atomatoe@si-g3.kzn.21-school.ru"
] | atomatoe@si-g3.kzn.21-school.ru |
c08a61ff81cfd8e0d43a79f34428a0576d729822 | c68f791005359cfec81af712aae0276c70b512b0 | /ACM International Collegiate Programming Contest, JUST Collegiate Programming Contest (2018)/d.cpp | 96fce2474cd41ac9a65cf9a68640b83240dd351f | [] | no_license | luqmanarifin/cp | 83b3435ba2fdd7e4a9db33ab47c409adb088eb90 | 08c2d6b6dd8c4eb80278ec34dc64fd4db5878f9f | refs/heads/master | 2022-10-16T14:30:09.683632 | 2022-10-08T20:35:42 | 2022-10-08T20:35:42 | 51,346,488 | 106 | 46 | null | 2017-04-16T11:06:18 | 2016-02-09T04:26:58 | C++ | UTF-8 | C++ | false | false | 704 | cpp | #include <iostream>
#include <cstdlib>
#include <fstream>
#include <cstdio>
#include <climits>
#include <vector>
#include <map>
#include <list>
#include <deque>
#include <queue>
#include <stack>
#include <set>
#include <sstream>
#include <string>
#include <cstring>
#include <algorithm>
#include <bitset>
#include <cmath>
#include <utility>
#include <functional>
#include <cassert>
using namespace std;
const int N = 105;
int a[N];
int main() {
int t;
scanf("%d", &t);
while (t--) {
int ans = 0;
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
int v;
scanf("%d", &v);
if (v) {
ans++;
}
}
printf("%d\n", ans);
}
return 0;
}
| [
"luqman.siswanto@shopee.com"
] | luqman.siswanto@shopee.com |
2688bb627d01fe8e9242e6e4f8423e6cf5a077e4 | 3d57fe4a401e13860a08de708bddb10129fa19b6 | /code/WPILib/CInterfaces/CSolenoid.cpp | c0bd9d26b61429299bd0639ae050489263360dea | [
"MIT"
] | permissive | trc492/Frc2011Logomotion | e2bf396a2dcaf030df4a2aeb14ce2c2bcd2bd741 | c0cf25c21acdf2eb965e60291955f9e3080eb319 | refs/heads/master | 2021-01-25T04:36:25.208325 | 2018-05-27T19:35:26 | 2018-05-27T19:35:26 | 93,456,304 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,323 | cpp | /*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */
/*----------------------------------------------------------------------------*/
#include "Solenoid.h"
#include "CSolenoid.h"
static Solenoid *solenoids[SensorBase::kSolenoidChannels];
static bool initialized = false;
/**
* Internal allocation function for Solenoid channels.
* The function is used interally to allocate the Solenoid object and keep track
* of the channel mapping to the object for subsequent calls.
*
* @param channel The channel for the solenoid
*/
static Solenoid *allocateSolenoid(UINT32 channel)
{
if (!initialized)
{
initialized = true;
for (unsigned i = 0; i < SensorBase::kSolenoidChannels; i++)
solenoids[i] = new Solenoid(i + 1);
}
if (channel < 1 || channel > SensorBase::kSolenoidChannels)
return NULL;
return solenoids[channel - 1];
}
/**
* Set the value of a solenoid.
*
* @param channel The channel on the Solenoid module
* @param on Turn the solenoid output off or on.
*/
void SetSolenoid(UINT32 channel, bool on)
{
Solenoid *s = allocateSolenoid(channel);
if (s != NULL)
s->Set(on);
}
/**
* Read the current value of the solenoid.
*
* @param channel The channel in the Solenoid module
* @return The current value of the solenoid.
*/
bool GetSolenoid(UINT32 channel)
{
Solenoid *s = allocateSolenoid(channel);
if (s == NULL)
return false;
return s->Get();
}
/**
* Free the resources associated with the Solenoid channel.
* Free the resources including the Solenoid object for this channel.
*
* @param channel The channel in the Solenoid module
*/
void DeleteSolenoid(UINT32 channel)
{
if (channel >= 1 && channel <= SensorBase::kSolenoidChannels)
{
delete solenoids[channel - 1];
solenoids[channel - 1] = NULL;
}
}
SolenoidObject CreateSolenoid(UINT32 channel)
{
return (SolenoidObject) new Solenoid(channel);
}
void DeleteSolenoid(SolenoidObject o)
{
delete (Solenoid *) o;
}
void SetSolenoid(SolenoidObject o, bool on)
{
((Solenoid *)o)->Set(on);
}
bool GetSolenoid(SolenoidObject o)
{
return ((Solenoid *)o)->Get();
}
| [
"trc492@live.com"
] | trc492@live.com |
7084c45facf2f0952b6d9962d5bc58b60c48567e | a8ec7ef01b6ecf0e53d03531996a551bb3df3c3b | /phone_problem.cpp | 559924f6ff2f75c7a06dd0437c3806d952e569d7 | [] | no_license | srikrishnabadi/Phone-number-problem | 435dd80c6ea37021738f23e0cfa8e981cf89e4a1 | 0fd6c4bf26efe734464453ced68004ebde71bc14 | refs/heads/master | 2020-12-18T13:13:48.484185 | 2020-01-21T17:13:14 | 2020-01-21T17:13:14 | 235,395,926 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 865 | cpp | #include<iostream>
#include<string>
#include<cctype>
using namespace std;
const int num = 10;
//string readValidNumber(string usernumber);
int main()
{
string usernumber;
cout << "Enter the valid number of 10 digit : ";
cin >> usernumber;
if(usernumber.length()==num)
{
cout << "You have entered a valid number!!" << endl;
}
else
{
cout << "Invalid number of digits\nEnter again..." << endl;
return 0;
}
usernumber.insert(0,"(");
usernumber.insert(4,") ");
usernumber.insert(9,"-");
cout << "The give number can be represented as " << usernumber << "." << endl;
cout << "The area code is represented in () brackets." << endl;
cout << "The Exchange code is represented within '-' symbol." << endl;
cout << "The Number code is the last 4 numbers of the usernumber." << endl;
//cout << usernumber;
return 0;
}
| [
"noreply@github.com"
] | srikrishnabadi.noreply@github.com |
de32d818dfd8c99d77a7f25814bff2e85c113d8e | e6fcafb89dbd566957283822b2f7b4c45a2c42a0 | /again.cpp | fb87a6e79eddd95ef10eaab8e9904fda0f47fc73 | [] | no_license | cardwizard/Facial-Expression-Recognition | 7ca93cdb755bcaf0906a971a26971fac4e98c7cd | ae97f08a1736dbe607c78cafe371cfc100cb21cf | refs/heads/master | 2020-12-24T17:25:57.533826 | 2014-08-08T17:29:49 | 2014-08-08T17:29:49 | 22,765,446 | 5 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 10,727 | cpp | /*
* Copyright (c) 2011. Philipp Wagner <bytefish[at]gmx[dot]de>.
* Released to public domain under terms of the BSD Simplified license.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the organization nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* See <http://www.opensource.org/licenses/bsd-license>
*/
#include "opencv2/core/core.hpp"
#include <opencv2/opencv.hpp>
#include "opencv2/contrib/contrib.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <sstream>
using namespace cv;
using namespace std;
CascadeClassifier face_cascade;
static Mat norm_0_255(InputArray _src) {
Mat src = _src.getMat();
// Create and return normalized image:
Mat dst;
switch(src.channels()) {
case 1:
cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC1);
break;
case 3:
cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC3);
break;
default:
src.copyTo(dst);
break;
}
return dst;
}
static void read_csv(const string& filename, vector<Mat>& images, vector<int>& labels, char separator = ';') {
std::ifstream file(filename.c_str(), ifstream::in);
if (!file) {
string error_message = "No valid input file was given, please check the given filename.";
CV_Error(CV_StsBadArg, error_message);
}
string line, path, classlabel;
Mat testSample = Mat ( 255 , 255 , CV_8UC1 );
while (getline(file, line)) {
stringstream liness(line);
getline(liness, path, separator);
getline(liness, classlabel);
if(!path.empty() && !classlabel.empty()) {
// cout<<"path and classlabel"<<path<<classlabel;
Mat grayscaleFrame = imread(path, 0);
equalizeHist(grayscaleFrame, grayscaleFrame);
std::vector<Rect> faces;
face_cascade.detectMultiScale(grayscaleFrame,faces,1.1,2,CV_HAAR_FIND_BIGGEST_OBJECT|CV_HAAR_SCALE_IMAGE,Size(30,30));
for(size_t i=0;i<faces.size();i++)
{
//ellipse (captureFrame,center,Size(faces[i].width*0.5,faces[i].height*0.5),0,0,360,Scalar(255,0,255),4,8,0);
//Rect facerect(faces[i].x - 20,faces[i].y- 20,faces[i].width + 20,faces[i].height+ 20);
Mat Roi = grayscaleFrame(faces[i]);
resize ( Roi , testSample , testSample.size());
imshow(string("Cropped ") + classlabel,testSample);
waitKey(10);
images.push_back(testSample.clone());
labels.push_back(atoi(classlabel.c_str()));
}
}
}
cout << images.size() << " " << labels.size() << " " << images[0].size().width << " x " << images[0].size().height;
}
int main(int argc, const char *argv[]) {
// Check for valid command line arguments, print usage
// if no arguments were given.
map <int, string> rec_op;
rec_op[2] = "sad";
rec_op[0] = "surprised";
rec_op[1] = "disgust";
rec_op[3] = "happy";
/* rec_op[4] = "normal";
rec_op[5] = "wink";
rec_op[6] = "happy";*/
VideoCapture stream1(0);
Mat captureFrame;
face_cascade.load("haarcascade_frontalface_alt.xml");
if (argc < 2) {
cout << "usage: " << argv[0] << " <csv.ext> <output_folder> " << endl;
exit(1);
}
string output_folder = ".";
if (argc == 3) {
output_folder = string(argv[2]);
}
// Get the path to your CSV.
string fn_csv = string(argv[1]);
// These vectors hold the images and corresponding labels.
vector<Mat> images;
vector<int> labels;
// Read in the data. This can fail if no valid
// input filename is given.
try {
read_csv(fn_csv, images, labels);
} catch (cv::Exception& e) {
cerr << "Error opening file \"" << fn_csv << "\". Reason: " << e.msg << endl;
// nothing more we can do
exit(1);
}
// Quit if there are not enough images for this demo.
if(images.size() <= 1) {
string error_message = "This demo needs at least 2 images to work. Please add more images to your data set!";
CV_Error(CV_StsError, error_message);
}
// Get the height from the first image. We'll need this
// later in code to reshape the images to their original
// size:
int height = images[0].rows;
// The following lines simply get the last images from
// your dataset and remove it from the vector. This is
// done, so that the training data (which we learn the
// cv::FaceRecognizer on) and the test data we test
// the model with, do not overlap.
Mat testSample = images[images.size() - 2];
int testLabel = labels[labels.size() - 2];
//cout<<images.size();
images.pop_back();
labels.pop_back();
// The following lines create an Eigenfaces model for
// face recognition and train it with the images and
// labels read from the given CSV file.
// This here is a full PCA, if you just want to keep
// 10 principal components (read Eigenfaces), then call
// the factory method like this:
//
// cv::createEigenFaceRecognizer(10);
//
// If you want to create a FaceRecognizer with a
// confidence threshold (e.g. 123.0), call it with:
//
// cv::createEigenFaceRecognizer(10, 123.0);
//
// If you want to use _all_ Eigenfaces and have a threshold,
// then call the method like this:
//
// cv::createEigenFaceRecognizer(0, 123.0);
//
Ptr<FaceRecognizer> model = createEigenFaceRecognizer();
model->train(images, labels);
// The following line predicts the label of a given
// test image:
int predictedLabel = model->predict(testSample);
//
// To get the confidence of a prediction call the model with:
//
// int predictedLabel = -1;
// double confidence = 0.0;
// model->predict(testSample, predictedLabel, confidence);
//
string result_message = format("Predicted class = %d / Actual class = %d.", predictedLabel, testLabel);
cout << result_message << endl;
// Here is how to get the eigenvalues of this Eigenfaces model:
Mat eigenvalues = model->getMat("eigenvalues");
// And we can do the same to display the Eigenvectors (read Eigenfaces):
Mat W = model->getMat("eigenvectors");
// Get the sample mean from the training data
Mat mean = model->getMat("mean");
// Display or save:
if(argc == 2) {
//imshow("mean", norm_0_255(mean.reshape(1, images[0].rows)));
} else {
imwrite(format("%s/mean.png", output_folder.c_str()), norm_0_255(mean.reshape(1, images[0].rows)));
}
// Display or save the Eigenfaces:
for (int i = 0; i < min(10, W.cols); i++) {
string msg = format("Eigenvalue #%d = %.5f", i, eigenvalues.at<double>(i));
cout << msg << endl;
// get eigenvector #i
Mat ev = W.col(i).clone();
// Reshape to original size & normalize to [0...255] for imshow.
Mat grayscale = norm_0_255(ev.reshape(1, height));
// Show the image & apply a Jet colormap for better sensing.
Mat cgrayscale;
applyColorMap(grayscale, cgrayscale, COLORMAP_JET);
// Display or save:
if(argc == 2) {
//imshow(format("eigenface_%d", i), cgrayscale);
} else {
imwrite(format("%s/eigenface_%d.png", output_folder.c_str(), i), norm_0_255(cgrayscale));
}
}
// Display or save the image reconstruction at some predefined steps:
for(int num_components = min(W.cols, 10); num_components < min(W.cols, 300); num_components+=15) {
// slice the eigenvectors from the model
Mat evs = Mat(W, Range::all(), Range(0, num_components));
Mat projection = subspaceProject(evs, mean, images[0].reshape(1,1));
Mat reconstruction = subspaceReconstruct(evs, mean, projection);
// Normalize the result:
reconstruction = norm_0_255(reconstruction.reshape(1, images[0].rows));
// Display or save:
if(argc == 2) {
//imshow(format("eigenface_reconstruction_%d", num_components), reconstruction);
} else {
imwrite(format("%s/eigenface_reconstruction_%d.png", output_folder.c_str(), num_components), reconstruction);
}
}
// Display if we are not writing to an output folder:
if(argc == 2) {
waitKey(0);
Mat grayscaleFrame , croppedImage;
while(true)
{
stream1.read(captureFrame);
cvtColor(captureFrame,grayscaleFrame,CV_BGR2GRAY);
equalizeHist(grayscaleFrame, grayscaleFrame);
std::vector<Rect> faces;
face_cascade.detectMultiScale(grayscaleFrame,faces,1.1,2,CV_HAAR_FIND_BIGGEST_OBJECT|CV_HAAR_SCALE_IMAGE,Size(30,30));
for(size_t i=0;i<faces.size();i++)
{
Point center(faces[i].x + faces[i].width*0.5,faces[i].y+faces[i].height*0.5);
ellipse (captureFrame,center,Size(faces[i].width*0.5,faces[i].height*0.5),0,0,360,Scalar(255,0,255),4,8,0);
//Rect facerect(faces[i].x - 20,faces[i].y- 20,faces[i].width + 20,faces[i].height+ 20);
Rect facerect(faces[i].x ,faces[i].y,faces[i].width ,faces[i].height);
croppedImage=captureFrame(facerect);
Mat Roi =grayscaleFrame(faces[i]);
resize ( Roi , testSample , testSample.size()) ;
int predictedLabel = model->predict(testSample);
imshow("Cropped",testSample);
Rect face_i=faces[i];
int pos_x = std::max(face_i.tl().x - 10, 0);
int pos_y = std::max(face_i.tl().y - 10, 0);
// And now put it into the image:
string box_text=format("%s",rec_op[predictedLabel].c_str());
putText(captureFrame, box_text, Point(pos_x, pos_y), FONT_HERSHEY_PLAIN, 1.5, CV_RGB(255,0,0), 2.0);
}
imshow("output",captureFrame);
int c = waitKey(10);
if (c == 27)
exit(0);
}
// And get a prediction from the cv::FaceRecognizer:
}
return 0;
}
| [
"aadeshbagmar@gmail.com"
] | aadeshbagmar@gmail.com |
83dc1b9828c4856027228e12e4f9c116bd700f57 | f520cb490d381e32fdee8f0ac0b6a7f8ed939ed1 | /list/CSignal.h | f0226e58b38b3c7fc39044a5b20191c70851ed02 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | DMLou/dmlist | b7ef8b6217a8f3d16eca9e89c49105be29048e95 | e2e8067491020a8d0c42e0d08e195098c0621e32 | refs/heads/master | 2021-01-25T06:37:06.872069 | 2013-03-11T05:15:15 | 2013-03-11T05:15:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,361 | h | /*****************************************************************************
CSignal
A class for an event object (a signal).
*****************************************************************************/
#ifndef _CSIGNAL_H
#define _CSIGNAL_H
#include <windows.h>
class CSignal
{
public:
CSignal ()
{
guard
{
Event = CreateEvent (NULL, TRUE, FALSE, NULL);
return;
} unguard;
}
CSignal (bool Signaled)
{
guard
{
Event = CreateEvent (NULL, TRUE, Signaled ? TRUE : FALSE, NULL);
return;
} unguard;
}
~CSignal ()
{
guard
{
CloseHandle (Event);
return;
} unguard;
}
void Signal (void)
{
guard
{
SetEvent (Event);
return;
} unguard;
}
void Unsignal (void)
{
guard
{
ResetEvent (Event);
return;
} unguard;
}
HANDLE GetEventObject (void)
{
guard
{
return (Event);
} unguard;
}
DWORD WaitUntilSignaled (DWORD TimeOut = INFINITE)
{
guard
{
return (WaitForSingleObject (Event, TimeOut));
} unguard;
}
protected:
HANDLE Event;
};
#endif // _CSIGNAL_H | [
"lou@tealstudios.com"
] | lou@tealstudios.com |
66db0ea079fb003e79912cf1e6bb4d0c4e015cbf | 7e08e17606593434908dd2d89e7e34952d0cdfbe | /v117/11799.cpp | 74b0436a29e25d4bfc86847d150398781ac4474e | [] | no_license | ellla/uva-online-judge-solutions | 7febbc20976ceabe71656bc4ac461a6b51922213 | 1b9ec731a8cbcff6e17b117d96b63ad6e28c477c | refs/heads/master | 2021-01-18T19:29:52.270877 | 2013-10-20T01:20:54 | 2013-10-20T01:20:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 527 | cpp | // UVa Online Judge
// Problem 11799 - Horror Dash
// Written by Tian Zhou
// Created 3/4/13
// Last Modified 3/4/13
#include <iostream>
using namespace std;
int main()
{
int cases;
int n;
int s;
int max;
cin >> cases;
for (int i = 0; i < cases; i++)
{
cin >> n;
max = 0;
for (int j = 0; j < n; j++)
{
cin >> s;
if (s > max)
max = s;
}
cout << "Case " << i + 1 << ": " << max << endl;
}
return 0;
}
| [
"tianzhou.cs@gmail.com"
] | tianzhou.cs@gmail.com |
d80de8dc97f573010b2e149be1ed0d95bfd47d8b | eddec2895bcc2fa6d7474f6ee3f72c0ffe77dbdc | /src/stbgl/utf8/checked.h | 8da71947cb7a89847962ce9997a16f39c68f5da7 | [
"Apache-2.0"
] | permissive | petrows/stb-gl | ab943fddc3cc79a855095afac612e876c72c5c3f | 22c3e78c59242bf8741c91eb79a8e70b6f4740f6 | refs/heads/master | 2021-01-19T03:51:25.498793 | 2016-03-13T16:32:14 | 2016-03-13T16:32:14 | 52,725,971 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,539 | h | // Copyright 2006 Nemanja Trifunovic
/*
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#ifndef UTF8_FOR_CPP_CHECKED_H_2675DCD0_9480_4c0c_B92A_CC14C027B731
#define UTF8_FOR_CPP_CHECKED_H_2675DCD0_9480_4c0c_B92A_CC14C027B731
#include "core.h"
#include <stdexcept>
namespace utf8 {
// Exceptions that may be thrown from the library functions.
class invalid_code_point : public std::exception {
uint32_t cp;
public:
invalid_code_point(uint32_t cp) : cp(cp) {}
virtual const char *what() const throw() { return "Invalid code point"; }
uint32_t code_point() const { return cp; }
};
class invalid_utf8 : public std::exception {
uint8_t u8;
public:
invalid_utf8(uint8_t u) : u8(u) {}
virtual const char *what() const throw() { return "Invalid UTF-8"; }
uint8_t utf8_octet() const { return u8; }
};
class invalid_utf16 : public std::exception {
uint16_t u16;
public:
invalid_utf16(uint16_t u) : u16(u) {}
virtual const char *what() const throw() { return "Invalid UTF-16"; }
uint16_t utf16_word() const { return u16; }
};
class not_enough_room : public std::exception {
public:
virtual const char *what() const throw() { return "Not enough space"; }
};
/// The library API - functions intended to be called by the users
template <typename octet_iterator, typename output_iterator> output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out, uint32_t replacement) {
while (start != end) {
octet_iterator sequence_start = start;
internal::utf_error err_code = internal::validate_next(start, end);
switch (err_code) {
case internal::UTF8_OK:
for (octet_iterator it = sequence_start; it != start; ++it)
*out++ = *it;
break;
case internal::NOT_ENOUGH_ROOM:
throw not_enough_room();
case internal::INVALID_LEAD:
append(replacement, out);
++start;
break;
case internal::INCOMPLETE_SEQUENCE:
case internal::OVERLONG_SEQUENCE:
case internal::INVALID_CODE_POINT:
append(replacement, out);
++start;
// just one replacement mark for the sequence
while (internal::is_trail(*start) && start != end)
++start;
break;
}
}
return out;
}
template <typename octet_iterator, typename output_iterator> inline output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out) {
static const uint32_t replacement_marker = internal::mask16(0xfffd);
return replace_invalid(start, end, out, replacement_marker);
}
template <typename octet_iterator> octet_iterator append(uint32_t cp, octet_iterator result) {
if (!internal::is_code_point_valid(cp))
throw invalid_code_point(cp);
if (cp < 0x80) // one octet
*(result++) = static_cast<uint8_t>(cp);
else if (cp < 0x800) { // two octets
*(result++) = static_cast<uint8_t>((cp >> 6) | 0xc0);
*(result++) = static_cast<uint8_t>((cp & 0x3f) | 0x80);
} else if (cp < 0x10000) { // three octets
*(result++) = static_cast<uint8_t>((cp >> 12) | 0xe0);
*(result++) = static_cast<uint8_t>(((cp >> 6) & 0x3f) | 0x80);
*(result++) = static_cast<uint8_t>((cp & 0x3f) | 0x80);
} else { // four octets
*(result++) = static_cast<uint8_t>((cp >> 18) | 0xf0);
*(result++) = static_cast<uint8_t>(((cp >> 12) & 0x3f) | 0x80);
*(result++) = static_cast<uint8_t>(((cp >> 6) & 0x3f) | 0x80);
*(result++) = static_cast<uint8_t>((cp & 0x3f) | 0x80);
}
return result;
}
template <typename octet_iterator> uint32_t next(octet_iterator &it, octet_iterator end) {
uint32_t cp = 0;
internal::utf_error err_code = internal::validate_next(it, end, &cp);
switch (err_code) {
case internal::UTF8_OK:
break;
case internal::NOT_ENOUGH_ROOM:
throw not_enough_room();
case internal::INVALID_LEAD:
case internal::INCOMPLETE_SEQUENCE:
case internal::OVERLONG_SEQUENCE:
throw invalid_utf8(*it);
case internal::INVALID_CODE_POINT:
throw invalid_code_point(cp);
}
return cp;
}
template <typename octet_iterator> uint32_t peek_next(octet_iterator it, octet_iterator end) { return next(it, end); }
template <typename octet_iterator> uint32_t prior(octet_iterator &it, octet_iterator start) {
octet_iterator end = it;
while (internal::is_trail(*(--it)))
if (it < start)
throw invalid_utf8(*it); // error - no lead byte in the sequence
octet_iterator temp = it;
return next(temp, end);
}
/// Deprecated in versions that include "prior"
template <typename octet_iterator> uint32_t previous(octet_iterator &it, octet_iterator pass_start) {
octet_iterator end = it;
while (internal::is_trail(*(--it)))
if (it == pass_start)
throw invalid_utf8(*it); // error - no lead byte in the sequence
octet_iterator temp = it;
return next(temp, end);
}
template <typename octet_iterator, typename distance_type> void advance(octet_iterator &it, distance_type n, octet_iterator end) {
for (distance_type i = 0; i < n; ++i)
next(it, end);
}
template <typename octet_iterator> typename std::iterator_traits<octet_iterator>::difference_type distance(octet_iterator first, octet_iterator last) {
typename std::iterator_traits<octet_iterator>::difference_type dist;
for (dist = 0; first < last; ++dist)
next(first, last);
return dist;
}
template <typename u16bit_iterator, typename octet_iterator> octet_iterator utf16to8(u16bit_iterator start, u16bit_iterator end, octet_iterator result) {
while (start != end) {
uint32_t cp = internal::mask16(*start++);
// Take care of surrogate pairs first
if (internal::is_lead_surrogate(cp)) {
if (start != end) {
uint32_t trail_surrogate = internal::mask16(*start++);
if (internal::is_trail_surrogate(trail_surrogate))
cp = (cp << 10) + trail_surrogate + internal::SURROGATE_OFFSET;
else
throw invalid_utf16(static_cast<uint16_t>(trail_surrogate));
} else
throw invalid_utf16(static_cast<uint16_t>(cp));
}
// Lone trail surrogate
else if (internal::is_trail_surrogate(cp))
throw invalid_utf16(static_cast<uint16_t>(cp));
result = append(cp, result);
}
return result;
}
template <typename u16bit_iterator, typename octet_iterator> u16bit_iterator utf8to16(octet_iterator start, octet_iterator end, u16bit_iterator result) {
while (start != end) {
uint32_t cp = next(start, end);
if (cp > 0xffff) { // make a surrogate pair
*result++ = static_cast<uint16_t>((cp >> 10) + internal::LEAD_OFFSET);
*result++ = static_cast<uint16_t>((cp & 0x3ff) + internal::TRAIL_SURROGATE_MIN);
} else
*result++ = static_cast<uint16_t>(cp);
}
return result;
}
template <typename octet_iterator, typename u32bit_iterator> octet_iterator utf32to8(u32bit_iterator start, u32bit_iterator end, octet_iterator result) {
while (start != end)
result = append(*(start++), result);
return result;
}
template <typename octet_iterator, typename u32bit_iterator> u32bit_iterator utf8to32(octet_iterator start, octet_iterator end, u32bit_iterator result) {
while (start < end)
(*result++) = next(start, end);
return result;
}
// The iterator class
template <typename octet_iterator> class iterator : public std::iterator<std::bidirectional_iterator_tag, uint32_t> {
octet_iterator it;
octet_iterator range_start;
octet_iterator range_end;
public:
iterator(){};
explicit iterator(const octet_iterator &octet_it, const octet_iterator &range_start, const octet_iterator &range_end) : it(octet_it), range_start(range_start), range_end(range_end) {
if (it < range_start || it > range_end)
throw std::out_of_range("Invalid utf-8 iterator position");
}
// the default "big three" are OK
octet_iterator base() const { return it; }
uint32_t operator*() const {
octet_iterator temp = it;
return next(temp, range_end);
}
bool operator==(const iterator &rhs) const {
if (range_start != rhs.range_start || range_end != rhs.range_end)
throw std::logic_error("Comparing utf-8 iterators defined with different ranges");
return (it == rhs.it);
}
bool operator!=(const iterator &rhs) const { return !(operator==(rhs)); }
iterator &operator++() {
next(it, range_end);
return *this;
}
iterator operator++(int) {
iterator temp = *this;
next(it, range_end);
return temp;
}
iterator &operator--() {
prior(it, range_start);
return *this;
}
iterator operator--(int) {
iterator temp = *this;
prior(it, range_start);
return temp;
}
}; // class iterator
} // namespace utf8
#endif // header guard
| [
"petro@petro.ws"
] | petro@petro.ws |
5b7a66e010f92d890dd452ed185e4696e63f42fe | 436623ee85c9d9444d700b56f2729b12b9f2c659 | /include/eepp/ui/uitablerow.hpp | 5fe7867cfada55569fd070cc96422a9979f096f9 | [
"MIT"
] | permissive | SpartanJ/eepp | 0bd271b33058ef119f5c34460ed94e44df882a25 | 9f64a2149f3a0842ced34b8b981ffe3a8efc6d13 | refs/heads/develop | 2023-09-01T01:17:30.155540 | 2023-08-27T20:58:19 | 2023-08-27T20:58:19 | 125,767,856 | 341 | 27 | MIT | 2023-04-01T20:10:26 | 2018-03-18T21:11:21 | C++ | UTF-8 | C++ | false | false | 1,399 | hpp | #ifndef EE_UI_UITABLEROW_HPP
#define EE_UI_UITABLEROW_HPP
#include <eepp/ui/models/modelindex.hpp>
#include <eepp/ui/uiwidget.hpp>
using namespace EE::UI::Models;
namespace EE { namespace UI {
class EE_API UITableRow : public UIWidget {
public:
static UITableRow* New( const std::string& tag ) { return eeNew( UITableRow, ( tag ) ); }
static UITableRow* New() { return eeNew( UITableRow, () ); }
ModelIndex getCurIndex() const { return mCurIndex; }
void setCurIndex( const ModelIndex& curIndex ) { mCurIndex = curIndex; }
void setTheme( UITheme* Theme ) {
UIWidget::setTheme( Theme );
setThemeSkin( Theme, "tablerow" );
onThemeLoaded();
}
protected:
UITableRow( const std::string& tag ) : UIWidget( tag ) { applyDefaultTheme(); }
UITableRow() : UIWidget( "table::row" ) {}
virtual Uint32 onMessage( const NodeMessage* msg ) {
EventDispatcher* eventDispatcher = getEventDispatcher();
Node* mouseDownNode = eventDispatcher->getMouseDownNode();
Node* draggingNode = eventDispatcher->getNodeDragging();
if ( msg->getMsg() == NodeMessage::MouseDown &&
( mouseDownNode == nullptr || mouseDownNode == this || isParentOf( mouseDownNode ) ) &&
draggingNode == nullptr ) {
sendMouseEvent( Event::MouseDown, eventDispatcher->getMousePos(), msg->getFlags() );
}
return 0;
}
ModelIndex mCurIndex;
};
}} // namespace EE::UI
#endif // EE_UI_UITABLEROW_HPP
| [
"spartanj@gmail.com"
] | spartanj@gmail.com |
cc1f0cf5ac64b4bc3ad3d1703ccc6f8dda968ac3 | fb5b25b4fbe66c532672c14dacc520b96ff90a04 | /export/release/macos/obj/src/openfl/display/_internal/DOMSimpleButton.cpp | bab360d83884e15121eb7c982075e193337e517e | [
"Apache-2.0"
] | permissive | Tyrcnex/tai-mod | c3849f817fe871004ed171245d63c5e447c4a9c3 | b83152693bb3139ee2ae73002623934f07d35baf | refs/heads/main | 2023-08-15T07:15:43.884068 | 2021-09-29T23:39:23 | 2021-09-29T23:39:23 | 383,313,424 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 6,322 | cpp | // Generated by Haxe 4.1.5
#include <hxcpp.h>
#ifndef INCLUDED_lime_app_IModule
#include <lime/app/IModule.h>
#endif
#ifndef INCLUDED_openfl__Vector_IVector
#include <openfl/_Vector/IVector.h>
#endif
#ifndef INCLUDED_openfl__Vector_ObjectVector
#include <openfl/_Vector/ObjectVector.h>
#endif
#ifndef INCLUDED_openfl_display_DOMRenderer
#include <openfl/display/DOMRenderer.h>
#endif
#ifndef INCLUDED_openfl_display_DisplayObject
#include <openfl/display/DisplayObject.h>
#endif
#ifndef INCLUDED_openfl_display_DisplayObjectContainer
#include <openfl/display/DisplayObjectContainer.h>
#endif
#ifndef INCLUDED_openfl_display_DisplayObjectRenderer
#include <openfl/display/DisplayObjectRenderer.h>
#endif
#ifndef INCLUDED_openfl_display_IBitmapDrawable
#include <openfl/display/IBitmapDrawable.h>
#endif
#ifndef INCLUDED_openfl_display_InteractiveObject
#include <openfl/display/InteractiveObject.h>
#endif
#ifndef INCLUDED_openfl_display_SimpleButton
#include <openfl/display/SimpleButton.h>
#endif
#ifndef INCLUDED_openfl_display_Stage
#include <openfl/display/Stage.h>
#endif
#ifndef INCLUDED_openfl_display__internal_DOMDisplayObject
#include <openfl/display/_internal/DOMDisplayObject.h>
#endif
#ifndef INCLUDED_openfl_display__internal_DOMSimpleButton
#include <openfl/display/_internal/DOMSimpleButton.h>
#endif
#ifndef INCLUDED_openfl_events_EventDispatcher
#include <openfl/events/EventDispatcher.h>
#endif
#ifndef INCLUDED_openfl_events_IEventDispatcher
#include <openfl/events/IEventDispatcher.h>
#endif
HX_LOCAL_STACK_FRAME(_hx_pos_528f7f21fd241d40_8_renderDrawable,"openfl.display._internal.DOMSimpleButton","renderDrawable",0xe7a92f18,"openfl.display._internal.DOMSimpleButton.renderDrawable","openfl/display/_internal/DOMSimpleButton.hx",8,0x036fd757)
HX_LOCAL_STACK_FRAME(_hx_pos_528f7f21fd241d40_37_renderDrawableClear,"openfl.display._internal.DOMSimpleButton","renderDrawableClear",0xedc5fb55,"openfl.display._internal.DOMSimpleButton.renderDrawableClear","openfl/display/_internal/DOMSimpleButton.hx",37,0x036fd757)
namespace openfl{
namespace display{
namespace _internal{
void DOMSimpleButton_obj::__construct() { }
Dynamic DOMSimpleButton_obj::__CreateEmpty() { return new DOMSimpleButton_obj; }
void *DOMSimpleButton_obj::_hx_vtable = 0;
Dynamic DOMSimpleButton_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< DOMSimpleButton_obj > _hx_result = new DOMSimpleButton_obj();
_hx_result->__construct();
return _hx_result;
}
bool DOMSimpleButton_obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x250e2278;
}
void DOMSimpleButton_obj::renderDrawable( ::openfl::display::SimpleButton simpleButton, ::openfl::display::DOMRenderer renderer){
HX_STACKFRAME(&_hx_pos_528f7f21fd241d40_8_renderDrawable)
HXLINE( 10) renderer->_hx___pushMaskObject(simpleButton,null());
HXLINE( 12) {
HXLINE( 12) ::Dynamic previousState = simpleButton->_hx___previousStates->iterator();
HXDLIN( 12) while(( (bool)(previousState->__Field(HX_("hasNext",6d,a5,46,18),::hx::paccDynamic)()) )){
HXLINE( 12) ::openfl::display::DisplayObject previousState1 = ( ( ::openfl::display::DisplayObject)(previousState->__Field(HX_("next",f3,84,02,49),::hx::paccDynamic)()) );
HXLINE( 14) renderer->_hx___renderDrawable(previousState1);
}
}
HXLINE( 17) simpleButton->_hx___previousStates->set_length(0);
HXLINE( 19) if (::hx::IsNotNull( simpleButton->_hx___currentState )) {
HXLINE( 21) if (::hx::IsNotEq( simpleButton->_hx___currentState->stage,simpleButton->stage )) {
HXLINE( 23) simpleButton->_hx___currentState->_hx___setStageReference(simpleButton->stage);
}
HXLINE( 26) renderer->_hx___renderDrawable(simpleButton->_hx___currentState);
}
HXLINE( 29) renderer->_hx___popMaskObject(simpleButton,null());
HXLINE( 31) renderer->_hx___renderEvent(simpleButton);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(DOMSimpleButton_obj,renderDrawable,(void))
void DOMSimpleButton_obj::renderDrawableClear( ::openfl::display::SimpleButton simpleButton, ::openfl::display::DOMRenderer renderer){
HX_STACKFRAME(&_hx_pos_528f7f21fd241d40_37_renderDrawableClear)
HXDLIN( 37) ::openfl::display::_internal::DOMDisplayObject_obj::renderDrawableClear(simpleButton,renderer);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(DOMSimpleButton_obj,renderDrawableClear,(void))
DOMSimpleButton_obj::DOMSimpleButton_obj()
{
}
bool DOMSimpleButton_obj::__GetStatic(const ::String &inName, Dynamic &outValue, ::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 14:
if (HX_FIELD_EQ(inName,"renderDrawable") ) { outValue = renderDrawable_dyn(); return true; }
break;
case 19:
if (HX_FIELD_EQ(inName,"renderDrawableClear") ) { outValue = renderDrawableClear_dyn(); return true; }
}
return false;
}
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo *DOMSimpleButton_obj_sMemberStorageInfo = 0;
static ::hx::StaticInfo *DOMSimpleButton_obj_sStaticStorageInfo = 0;
#endif
::hx::Class DOMSimpleButton_obj::__mClass;
static ::String DOMSimpleButton_obj_sStaticFields[] = {
HX_("renderDrawable",14,59,d0,dd),
HX_("renderDrawableClear",d9,1f,f9,ad),
::String(null())
};
void DOMSimpleButton_obj::__register()
{
DOMSimpleButton_obj _hx_dummy;
DOMSimpleButton_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("openfl.display._internal.DOMSimpleButton",ea,15,23,60);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &DOMSimpleButton_obj::__GetStatic;
__mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(DOMSimpleButton_obj_sStaticFields);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(0 /* sMemberFields */);
__mClass->mCanCast = ::hx::TCanCast< DOMSimpleButton_obj >;
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = DOMSimpleButton_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = DOMSimpleButton_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace openfl
} // end namespace display
} // end namespace _internal
| [
"80244419+Tyrcnex@users.noreply.github.com"
] | 80244419+Tyrcnex@users.noreply.github.com |
e4d420611e084927e721a727abb839dbb03c3e23 | b3c43a3a3f7eec264e09b93cfaf514d33afdfcd9 | /lib/env/baulkvenv.cc | 99cc508832c66a128075041a51ed33d4d538a5fc | [
"MIT"
] | permissive | skyformat99/baulk | 2de54891acf39a13377a058f62c34fbf3cbacacb | eb67e059b93b36057b64deb17615ba6c89c3a814 | refs/heads/master | 2022-12-01T09:22:12.668920 | 2020-08-06T14:03:30 | 2020-08-06T14:03:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,334 | cc | // baulk virtual env
#include <bela/io.hpp>
#include <bela/process.hpp> // run vswhere
#include <bela/path.hpp>
#include <bela/env.hpp>
#include <filesystem>
#include <regutils.hpp>
#include <jsonex.hpp>
#include <baulkenv.hpp>
namespace baulk::env {
// baulk virtual env
bool Searcher::InitializeVirtualEnv(const std::vector<std::wstring> &venvs, bela::error_code &ec) {
for (const auto &p : venvs) {
if (InitializeOneEnv(p, ec)) {
availableEnv.emplace_back(p);
}
}
return true;
}
bool Searcher::InitializeLocalEnv(std::wstring_view pkgname, BaulkVirtualEnv &venv,
bela::error_code &ec) {
auto localfile = bela::StringCat(baulkbindir, L"\\etc\\", pkgname, L".local.json");
if (!bela::PathExists(localfile)) {
return false;
}
FILE *fd = nullptr;
if (auto en = _wfopen_s(&fd, localfile.data(), L"rb"); en != 0) {
ec = bela::make_stdc_error_code(en, bela::StringCat(L"open ", pkgname, L".local.json' "));
return false;
}
auto closer = bela::finally([&] { fclose(fd); });
try {
auto j = nlohmann::json::parse(fd, nullptr, true, true);
baulk::json::JsonAssignor jea(j);
jea.array("path", venv.paths);
jea.array("env", venv.envs);
jea.array("include", venv.includes);
jea.array("lib", venv.libs);
} catch (const std::exception &e) {
ec = bela::make_error_code(1, pkgname, L".local.json: ", bela::ToWide(e.what()));
return false;
}
return true;
}
bool Searcher::InitializeOneEnv(std::wstring_view pkgname, bela::error_code &ec) {
auto lockfile = bela::StringCat(baulkbindir, L"\\locks\\", pkgname, L".json");
FILE *fd = nullptr;
if (auto en = _wfopen_s(&fd, lockfile.data(), L"rb"); en != 0) {
ec = bela::make_stdc_error_code(en, bela::StringCat(L"open 'locks\\", pkgname, L".json' "));
return false;
}
auto closer = bela::finally([&] { fclose(fd); });
BaulkVirtualEnv venv;
try {
auto j = nlohmann::json::parse(fd, nullptr, true, true);
if (auto it = j.find("venv"); it != j.end() && it.value().is_object()) {
baulk::json::JsonAssignor jea(it.value());
jea.array("path", venv.paths);
jea.array("env", venv.envs);
jea.array("include", venv.includes);
jea.array("lib", venv.libs);
}
} catch (const std::exception &e) {
ec = bela::make_error_code(1, L"parse package ", pkgname, L" json: ", bela::ToWide(e.what()));
return false;
}
InitializeLocalEnv(pkgname, venv, ec);
bela::env::Derivator expanddev;
auto baulkpkgroot = bela::StringCat(baulkbindir, L"\\pkgs\\", pkgname);
expanddev.SetEnv(L"BAULK_ROOT", baulkroot);
expanddev.SetEnv(L"BAULK_ETC", baulketc);
expanddev.SetEnv(L"BAULK_VFS", baulkvfs);
expanddev.SetEnv(L"BAULK_PKGROOT", baulkpkgroot);
expanddev.SetEnv(L"BAULK_BINDIR", baulkbindir);
std::wstring buffer;
auto joinExpandEnv = [&](const vector_t &load, vector_t &save) {
for (const auto &x : load) {
buffer.clear();
expanddev.ExpandEnv(x, buffer);
JoinForceEnv(save, buffer);
}
};
joinExpandEnv(venv.paths, paths);
joinExpandEnv(venv.includes, includes);
joinExpandEnv(venv.libs, libs);
// set env k=v
for (const auto &e : venv.envs) {
buffer.clear();
expanddev.ExpandEnv(e, buffer);
dev.PutEnv(buffer, true);
}
return true;
}
} // namespace baulk::env | [
"charlieio@outlook.com"
] | charlieio@outlook.com |
57d931264fe2d78ea0c4edb39e2434d996383571 | c195935fa449b83ad8fce5cc72da14d6329915da | /segmentation/segmentimage.h | de4eaeef0e327191c85ca7df06645ebed4293585 | [] | no_license | Armine13/Segmentation_Project | a65b381da2d7e533a86016ec2bd487c53f10916a | 5753f4d3c80e56c67b9ea55557714e72734053a0 | refs/heads/master | 2021-01-13T00:55:24.930550 | 2015-12-28T22:06:24 | 2015-12-28T22:06:24 | 44,073,025 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 414 | h | #ifndef SEGMENTIMAGE_H
#define SEGMENTIMAGE_H
#include "segmentationcore.h"
class SegmentImage: private SegmentationCore
{
public:
SegmentImage();
SegmentImage(String imageFile, String seedFile);
~SegmentImage();
void getSegmentedImage(QVector<QImage> &segmentedQImages, QImage& contourQImage);
private:
void getImageWithContour(const Mat& image, Mat& contourIm);
};
#endif // SEGMENTIMAGE_H
| [
"arminevardazaryan@gmail.com"
] | arminevardazaryan@gmail.com |
2457a8a84fa74dd8827779cd67613691c6983aa1 | 447608086159b389265df84edcb34126b97018df | /test/src/public/src/ysclass/src/ysadvgeometry.h | acf537fa9aab7fb5ca14e49c03e4e61275ce8660 | [] | no_license | jw995/Sequential-Line-Search-for-Efficient-Photo-Parameters-Tweaking | f121173eb0eec0e680c2dcfd7cf5824c8be67716 | 5110301d831f86b59b9d66338afe12587896ea7c | refs/heads/master | 2020-03-12T11:25:31.831320 | 2018-05-23T00:19:20 | 2018-05-23T00:19:20 | 130,596,465 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 67,202 | h | /* ////////////////////////////////////////////////////////////
File Name: ysadvgeometry.h
Copyright (c) 2017 Soji Yamakawa. All rights reserved.
http://www.ysflight.com
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//////////////////////////////////////////////////////////// */
#ifndef YSADVGEOMETRY_IS_INCLUDED
#define YSADVGEOMETRY_IS_INCLUDED
/* { */
/*! \file */
#include "ysgeometry.h"
#include "ysarray.h"
#include "ysrect.h"
/*! This function returns YSTRUE if the polygon given by p[0],p[1],...,p[np-1] is convex.
\param np [In] Number of points of the polygon.
\param p [In] Points of the polygon.
\param strictCheck [In] If it is YSTRUE, this function performs additional calculation to deal with a numerically difficult case.
*/
YSBOOL YsCheckConvex2(YSSIZE_T np,const YsVec2 p[],YSBOOL strictCheck=YSFALSE);
/*! Templated version of YsCheckConvex2. */
YSBOOL YsCheckConvex2(const YsConstArrayMask <YsVec2> &plg,YSBOOL strictCheck=YSFALSE);
/*! This function returns YSTRUE if the polygon given by p[0],p[1],...,p[np-1] is convex.
\param np [In] Number of points of the polygon.
\param p [In] Points of the polygon.
\param strictCheck [In] If it is YSTRUE, this function performs additional calculation to deal with a numerically difficult case.
*/
YSBOOL YsCheckConvex3(YSSIZE_T np,const YsVec3 p[],YSBOOL strictCheck=YSFALSE);
/*! Templated version of YsCheckConvex2. */
YSBOOL YsCheckConvex3(const YsConstArrayMask <YsVec3> &plg,YSBOOL strictCheck=YSFALSE);
/*! This function returns YSTRUE if the polygon given by p[0],p[1],...,p[np-1] is convex.
This function tests the convexity based on only angles. The result may become unstable
when more than three points are nearly co-linear.
\sa YsCheckConvex2
\param np [In] Number of points of the polygon.
\param p [In] Points of the polygon.
*/
YSBOOL YsCheckConvexByAngle2(YSSIZE_T np,const YsVec2 *p);
/*! Templated version of YsCheckConvexByAngle2 */
YSBOOL YsCheckConvexByAngle2(const YsConstArrayMask <YsVec2> &plg);
/*! This function returns YSTRUE if the polygon given by p[0],p[1],...,p[np-1] is convex.
This function tests the convexity based on only angles. The result may become unstable
when more than three points are nearly co-linear.
\sa YsCheckConvex3
\param np [In] Number of points of the polygon.
\param p [In] Points of the polygon.
*/
YSBOOL YsCheckConvexByAngle3(YSSIZE_T np,const YsVec3 *p);
/*! Templated version of YsCheckConvexByAngle3 */
YSBOOL YsCheckConvexByAngle3(const YsConstArrayMask <YsVec3> &plg);
/*! This function returns area of a triangle. */
double YsGetTriangleArea3(const YsVec3 &p1,const YsVec3 &p2,const YsVec3 &p3);
/*! This function returns area of a triangle. */
double YsGetTriangleArea2(const YsVec2 &p1,const YsVec2 &p2,const YsVec2 &p3);
/*! This function retusns area of the given polygon. */
double YsGetPolygonArea2(YSSIZE_T np,const YsVec2 p[]);
double YsGetPolygonArea2(const YsConstArrayMask <YsVec2> &plg);
/*! This function retusns area of the given polygon. */
double YsGetPolygonArea(YSSIZE_T np,const YsVec2 p[]);
double YsGetPolygonArea(const YsConstArrayMask <YsVec2> &plg);
double YsGetPolygonArea(YSSIZE_T np,const YsVec3 p[]);
double YsGetPolygonArea(const YsConstArrayMask <YsVec3> &plg);
/*! This function finds the largest triangle that consists of three points of the
points of the given polygon and returns pointers to the three points.
\param v [Out] The triangle will be returned in this.
\param np [In] Number of points of the polygon
\param p [In] Points of the polygon
*/
YSRESULT YsGetLargestTriangleFromPolygon3(const YsVec3 *v[3],YSSIZE_T np,const YsVec3 p[]);
/*! Templated version of YsGetLargestTriangleFromPolygon3 */
YSRESULT YsGetLargestTriangleFromPolygon3(const YsVec3 *v[3],const YsConstArrayMask <YsVec3> &plg);
/*! This function finds the largest triangle that consists of three
points of the given polygon and returns the three points of the triangle.
\param v [Out] The triangle will be returned in this.
\param np [In] Number of points of the polygon
\param p [In] Points of the polygon
*/
YSRESULT YsGetLargestTriangleFromPolygon3(YsVec3 v[3],YSSIZE_T np,const YsVec3 p[]);
/*! Templated version of YsGetLargestTriangleFromPolygon3 */
YSRESULT YsGetLargestTriangleFromPolygon3(YsVec3 v[3],const YsConstArrayMask <YsVec3> &plg);
/*! This function finds the largest triangle that consists of three points of
the given polygon and returns the three points of the triangle.
\param v [Out] The triangle will be returned in this.
\param np [In] Number of points of the polygon
\param p [In] Points of the polygon
*/
YSRESULT YsGetLargestTriangleFromPolygon2(const YsVec2 *v[3],YSSIZE_T np,const YsVec2 p[]);
/*! Templated version of YsGetLargestTriangleFromPolygon2 */
YSRESULT YsGetLargestTriangleFromPolygon2(const YsVec2 *v[3],const YsConstArrayMask <YsVec2> &plg);
/*! This function finds the largest triangle that consists of three
points of the given polygon and returns the three points of the triangle.
\param v [Out] The triangle will be returned in this.
\param np [In] Number of points of the polygon
\param p [In] Points of the polygon
*/
YSRESULT YsGetLargestTriangleFromPolygon2(YsVec2 v[3],YSSIZE_T np,const YsVec2 p[]);
/*! Templated version of YsGetLargestTriangleFromPolygon2 */
YSRESULT YsGetLargestTriangleFromPolygon2(YsVec2 v[3],const YsConstArrayMask <YsVec2> &plg);
/*! This function calculates normal vector of the polygon based on the largest triangle
that consists of three points of the given polygon.
If successful, the returned normal is a unit vector.
\sa YsGetLargestTriangleFromPolygon3
\param nom [Out] Calculated normal vector
\param np [In] Number of points of the polygon
\param p [In] Points of the polygon
*/
YSRESULT YsGetAverageNormalVector(YsVec3 &nom,YSSIZE_T np,const YsVec3 p[]);
/*! Templated version of YsGetAverageNormalVector. */
inline YSRESULT YsGetAverageNormalVector(YsVec3 &nom,YsConstArrayMask <YsVec3> plVtPos)
{
return YsGetAverageNormalVector(nom,plVtPos.GetN(),plVtPos);
}
/*! Convenient version of YsGetAverageNormalVector. The returned vector will be YsOrigin() if
the normal could not be calculated. */
YsVec3 YsGetAverageNormalVector(YSSIZE_T np,const YsVec3 p[]);
/*! Convenient version of YsGetAverageNormalVector. The returned vector will be YsOrigin() if
the normal could not be calculated. */
inline YsVec3 YsGetAverageNormalVector(YsConstArrayMask <YsVec3> plVtPos)
{
return YsGetAverageNormalVector(plVtPos.size(),plVtPos.data());
}
/*! This function returns YSTRUE if the projection of the reference point
on the line that passes through the given two end points is between
the two end points or is lying on one of the end points. It returns
YSFALSE otherwise.
\param ref [In] Reference point
\param p1 [In] One of the end points
\param p2 [In] The other end point
*/
YSBOOL YsCheckInBetween2(const YsVec2 &ref,const YsVec2 &p1,const YsVec2 &p2);
/*! This function returns YSTRUE if the projection of the reference point
on the line that passes through the given two end points is between
the two end points or is lying on one of the end points. It returns
YSFALSE otherwise.
\param ref [In] Reference point
\param p[2] [In] The end points
*/
YSBOOL YsCheckInBetween2(const YsVec2 &ref,const YsVec2 p[2]);
/*! This function returns YSTRUE if the projection of the reference point
on the line that passes through the given two end points is between
the two end points or is lying on one of the end points. It returns
YSFALSE otherwise.
\param ref [In] Reference point
\param p1 [In] One of the end points
\param p2 [In] The other end point
*/
YSBOOL YsCheckInBetween3(const YsVec3 &ref,const YsVec3 &p1,const YsVec3 &p2);
/*! This function returns YSTRUE if the projection of the reference point
on the line that passes through the given two end points is between
the two end points or is lying on one of the end points. It returns
YSFALSE otherwise.
\param ref [In] Reference point
\param p[2] [In] The end points
*/
YSBOOL YsCheckInBetween3(const YsVec3 &ref,const YsVec3 p[2]);
/*! This function calculates an intersection between the two lines defined by
the given passing point, and returns YSOK if the intersection was calculated,
or YSERR otherwise.
For lines passing through 3D space, use YsGetNearestPointOfTwoLine instead.
\sa YsGetNearestPointOfTwoLine
\param crs [Out]If the calculation is successful, the intersection point is returned to this.
\param p1 [In] A point that the first line passes through
\param p2 [In] The other point that the first line passes through
\param q1 [In] A point that the second line passes through
\param q2 [In] The other point that the second line passes through */
YSRESULT YsGetLineIntersection2(YsVec2 &crs,const YsVec2 &p1,const YsVec2 &p2,const YsVec2 &q1,const YsVec2 &q2);
/*! This function returns an intersection between the two lines p[0]-p[1] and q[0]-q[1]. */
inline YSRESULT YsGetLineIntersection2(YsVec2 &crs,const YsVec2 p[2],const YsVec2 q[2])
{
return YsGetLineIntersection2(crs,p[0],p[1],q[0],q[1]);
}
/*! This function returns YSTRUE if the given two lines are identical.
\param o1 [In] A point that the first line passes through
\param v1 [In] A vector that is parallel to the first line
\param o2 [In] A point that the second line passes through
\param v2 [In] A vector that is parallel to the second line */
YSBOOL YsCheckLineOverlap2(const YsVec2 &o1,const YsVec2 &v1,const YsVec2 &o2,const YsVec2 &v2);
/*! This function returns YSTRUE if the given two lines are identical.
\param o1 [In] A point that the first line passes through
\param v1 [In] A vector that is parallel to the first line
\param o2 [In] A point that the second line passes through
\param v2 [In] A vector that is parallel to the second line */
YSBOOL YsCheckLineOverlap3(const YsVec3 &o1,const YsVec3 &v1,const YsVec3 &o2,const YsVec3 &v2);
/*! This function returns if the reference point is inside, outside, or on the boundary of the
given polygon.
\param ref [In] Reference point
\param np [In] Number of points of the polygon
\param p [In] Points of the polygon
It returns one of:
YSINSIDE Inside
YSOUTSIDE Outside
YSBOUNDARY On the boundary
YSUNKNOWNSIDE Cannot tell due to an error.
*/
YSSIDE YsCheckInsidePolygon2(const YsVec2 &ref,YSSIZE_T np,const YsVec2 p[]);
/*! Templated version of YsCheckInsidePolygon2
std::vector <YsVec2> or YsArray <YsVec2,N> can be given as plg.
It returns one of:
YSINSIDE Inside
YSOUTSIDE Outside
YSBOUNDARY On the boundary
YSUNKNOWNSIDE Cannot tell due to an error. */
inline YSSIDE YsCheckInsidePolygon2(const YsVec2 &ref,YsConstArrayMask <YsVec2> plg)
{
return YsCheckInsidePolygon2(ref,plg.GetN(),plg);
}
/*! This function returns if the reference point is inside, outside, or on the boundary of the
given polygon. The result is the most accurate when all the points of the polygon and the
reference point is co-planar. When those points are not lying on the plane, the result
may becone inaccurate.
\param ref [In] Reference point
\param np [In] Number of points of the polygon
\param p [In] Points of the polygon
It returns one of:
YSINSIDE Inside
YSOUTSIDE Outside
YSBOUNDARY On the boundary
YSUNKNOWNSIDE Cannot tell due to an error. */
YSSIDE YsCheckInsidePolygon3(const YsVec3 &ref,YSSIZE_T np,const YsVec3 p[]);
/*! Templated version of YsCheckInsidePolygon3.
std::vector <YsVec3> or YsArray <YsVec3,N> can be given as plg.
It returns one of:
YSINSIDE Inside
YSOUTSIDE Outside
YSBOUNDARY On the boundary
YSUNKNOWNSIDE Cannot tell due to an error. */
inline YSSIDE YsCheckInsidePolygon3(const YsVec3 &ref,YsConstArrayMask <YsVec3> plg)
{
return YsCheckInsidePolygon3(ref,plg.GetN(),plg);
}
/*! This function returns if the reference point is inside, outside, or on the boundary of the
given polygon. The result is the most accurate when all the points of the polygon and the
reference point is co-planar. When those points are not lying on the plane, the result
may becone inaccurate.
\param ref [In] Reference point
\param np [In] Number of points of the polygon
\param p [In] Points of the polygon
\param nom [In] Normal of the polygon
It returns one of:
YSINSIDE Inside
YSOUTSIDE Outside
YSBOUNDARY On the boundary
YSUNKNOWNSIDE Cannot tell due to an error. */
YSSIDE YsCheckInsidePolygon3(const YsVec3 &ref,YSSIZE_T np,const YsVec3 p[],const YsVec3 &nom);
/*! Templated version of YsCheckInsidePolygon3
std::vector <YsVec3> or YsArray <YsVec3,N> can be given as plg.
It returns one of:
YSINSIDE Inside
YSOUTSIDE Outside
YSBOUNDARY On the boundary
YSUNKNOWNSIDE Cannot tell due to an error. */
inline YSSIDE YsCheckInsidePolygon3(const YsVec3 &ref,YsConstArrayMask <YsVec3> plg,const YsVec3 &nom)
{
return YsCheckInsidePolygon3(ref,plg.GetN(),plg,nom);
}
/*! This function returns if the reference point is inside, outside, or on the boundary of the
given triangle.
\param ref [In] Reference point
\param tri [In] Points of the triangle
It returns one of:
YSINSIDE Inside
YSOUTSIDE Outside
YSBOUNDARY On the boundary
YSUNKNOWNSIDE Cannot tell due to an error. */
YSSIDE YsCheckInsideTriangle2(const YsVec2 &ref,const YsVec2 tri[]);
/*! This function returns if the reference point is inside, outside, or on the boundary of the
given triangle. The result is the most accurate when all the points of the polygon and the
reference point is co-planar. When those points are not lying on the plane, the result
may becone inaccurate.
\param ref [In] Reference point
\param tri [In] Points of the triangle */
YSSIDE YsCheckInsideTriangle3(const YsVec3 &ref,const YsVec3 tri[]);
/*! This function calculates and returns the corner angle of the polygon. This function does not
distinguish convex and concave corner. The returned angle is always between 0.0 and YsPi.
The angle returned by this function is an inner angle at the corner. If the polygon makes a
sharp turn at the corner, the return value will be close to zero. Or, the polygon is round
and smooth at the corner, the return value will be close to YsPi. To get how much the polygon is
bending at the corner, subtract the return value from YsPi.
The calling function must make sure 0<=corner and corner<nPlvt. Also, the polygon must not have
a degenerate edge, or the result of this function will be undefined. */
const double YsGetPolygonCornerAngle(YSSIZE_T nPlVt,const YsVec3 plVtPos[],int corner);
/*! Templated version of YsGetPolygonCornerAngle */
inline const double YsGetPolygonCornerAngle(YsConstArrayMask <YsVec3> plg,int corner)
{
return YsGetPolygonCornerAngle(plg.GetN(),plg,corner);
}
/*! This function returns the minimum and maximum value that is calculated by
YsGetPolygonCornerAngle for the given polygon. */
void YsGetPolygonMinAndMaxCornerAngle(double &minAng,double &maxAng,YSSIZE_T nPlVt,const YsVec3 plVtPos[]);
/*! Templated version of YsGetPolygonMinAndMaxCornerAngle */
inline void YsGetPolygonMinAndMaxCornerAngle(double &minAng,double &maxAng,YsConstArrayMask <YsVec3> plg)
{
return YsGetPolygonMinAndMaxCornerAngle(minAng,maxAng,plg.GetN(),plg);
}
/*! Returns YSTRUE if the corner is a convex corner, or YSFALSE if not.
If the corner is straight, returns YSTFUNKNOWN.
This function will not return an accurate result if the polygon:
(1) has a self-intersecting edge,
(2) includes an 180-degree corner angle, or
(3) has a zero-length edge.
*/
YSBOOL YsIsConvexCorner2(YSSIZE_T np,const YsVec2 p[],YSSIZE_T idx);
/*! Returns YSTRUE if the corner is a convex corner, or YSFALSE if not.
If the corner is straight, returns YSTFUNKNOWN.
This function will not return an accurate result if the polygon:
(1) has a self-intersecting edge,
(2) includes an 180-degree corner angle, or
(3) has a zero-length edge.
*/
inline YSBOOL YsIsConvexCorner2(YsConstArrayMask <YsVec2> plg,YSSIZE_T idx)
{
return YsIsConvexCorner2(plg.GetN(),plg,idx);
}
/*! Returns YSTRUE if the corner is a convex corner, or YSFALSE if not.
If the corner is straight, returns YSTFUNKNOWN.
This function will not return an accurate result if the polygon:
(1) has a self-intersecting edge,
(2) includes an 180-degree corner angle, or
(3) has a zero-length edge.
*/
YSBOOL YsIsConvexCorner3(YSSIZE_T np,const YsVec3 p[],YSSIZE_T idx);
/*! Returns YSTRUE if the corner is a convex corner, or YSFALSE if not.
If the corner is straight, returns YSTFUNKNOWN.
This function will not return an accurate result if the polygon:
(1) has a self-intersecting edge,
(2) includes an 180-degree corner angle, or
(3) has a zero-length edge.
*/
inline YSBOOL YsIsConvexCorner3(YsConstArrayMask <YsVec3> plg,YSSIZE_T idx)
{
return YsIsConvexCorner3(plg.GetN(),plg,idx);
}
/// \cond
YSBOOL YsIsLineSegIntersectionReliable2(const YsVec2 &p1,const YsVec2 &p2,const YsVec2 &q1,const YsVec2 &q2);
YSBOOL YsPointEdgeDistanceIsWithinRangeOf(const YsVec3 &pnt,int np,const YsVec3 p[],const double &ratio);
/// \endcond
/*! This function returns the center of the largest triangle that consists of three points
of the given polygon.
Note that this does not return the gravity center of the polygon, which is often biased
by the non-uniform point distribution.
\param cen [Out] Center of the largest triangle that consists of three points of the given polygon.
\param np [In] Number of points of the polygon
\param p [In] Points of the polygon
*/
YSRESULT YsGetCenterOfPolygon3(YsVec3 &cen,YSSIZE_T np,const YsVec3 p[]);
/*! This function returns the center of the largest triangle that consists of three points
of the given polygon.
Note that this does not return the gravity center of the polygon, which is often biased
by the non-uniform point distribution.
\param cen [Out] Center of the largest triangle that consists of three points of the given polygon.
\param np [In] Number of points of the polygon
\param p [In] Points of the polygon
*/
YSRESULT YsGetCenterOfPolygon2(YsVec2 &cen,YSSIZE_T np,const YsVec2 p[]);
/*! This function calculates the average of the points p[0]...p[np-1] */
YsVec3 YsGetCenter(YSSIZE_T np,const YsVec3 p[]);
/*! This function calculates the average of the points p[0]...p[np-1] */
YsVec2 YsGetCenter(YSSIZE_T np,const YsVec2 p[]);
/*! Templated version of YsGetCenter */
inline YsVec3 YsGetCenter(YsConstArrayMask <YsVec3> p)
{
return YsGetCenter(p.GetN(),p);
}
/*! Templated version of YsGetCenter */
inline YsVec2 YsGetCenter(YsConstArrayMask <YsVec2> p)
{
return YsGetCenter(p.GetN(),p);
}
/*! This function calculates a 4x4 affine-trnasformation matrix that transforms the given polygon
on the XY plane. By the matrix returned by this function, a point of the polygon p[i] {0<=i<np}
is transformed to a point on XY plane p'[i] as:
p'[i]=mat*p[i]
\param mat [Out] A 4x4 matrix that receives the calculation result
\param np [In] Number of points of the polygon
\param p [In] Points of the polygon
*/
YSRESULT YsGetPolygonProjectionMatrix(YsMatrix4x4 &mat,YSSIZE_T np,const YsVec3 p[]);
// Returns a matrix that project a Polygon into XY plane.
// Note:Twist direction will be reversed in Left-Handed coordinate.
/*! Templated version of YsGetPolygonProjectionMatrix */
inline YSRESULT YsGetPolygonProjectionMatrix(YsMatrix4x4 &mat,YsConstArrayMask <YsVec3> plg)
{
return YsGetPolygonProjectionMatrix(mat,plg.GetN(),plg);
}
/*! This function checks if how two pieces of line are located.
\sa YSINTERSECTION
\param p1 [In] An end point of the first line
\param p2 [In] The other end point of the first line
\param q1 [In] An end point of the second line
\param q2 [In] The other end point of the second line
*/
YSINTERSECTION YsGetLinePenetration2(const YsVec2 &p1,const YsVec2 &p2,const YsVec2 &q1,const YsVec2 &q2);
/*! This function checks if how two pieces of line are located.
\sa YSINTERSECTION
\param p1 [In] An end point of the first line
\param p2 [In] The other end point of the first line
\param q1 [In] An end point of the second line
\param q2 [In] The other end point of the second line
*/
YSINTERSECTION YsGetLinePenetration3(const YsVec3 &p1,const YsVec3 &p2,const YsVec3 &q1,const YsVec3 &q2);
/*! This function checks if a polygon that consists of p[0], p[1], ..., p[np-1] can
be split by connecting p[idx1] and p[idx2].
*/
YSBOOL YsCheckSeparatability2(YSSIZE_T np,const YsVec2 p[],int idx1,int idx2);
/*! Templated version of YsCheckSeparatability2 */
inline YSBOOL YsCheckSeparatability2(YsConstArrayMask <YsVec2> plg,int idx1,int idx2)
{
return YsCheckSeparatability2(plg.GetN(),plg,idx1,idx2);
}
/*! This function checks if a polygon that consists of p[0], p[1], ..., p[np-1] can
be split by connecting p[idx1] and p[idx2].
*/
YSBOOL YsCheckSeparatability3(YSSIZE_T np,const YsVec3 p[],int idx1,int idx2);
// Note:YsCheckSeparatability3 is extremely slow function.
// Not recommended to used it in a loop.
// It is recommended to make PolygonProjectionMatrix
// and project the polygon into XY plane. Then, use it to
// Check separatability.
/*! Templated version of YsCheckSeparatability2 */
inline YSBOOL YsCheckSeparatability3(YsConstArrayMask <YsVec3> plg,int idx1,int idx2)
{
return YsCheckSeparatability3(plg.GetN(),plg,idx1,idx2);
}
/*! This function returns YSTRUE if two bounding boxes intersects or touches each other or YSFALSE otherwise.
\param min1 [In] Minimum x and y of bounding box 1
\param max1 [In] Maximum x and y of bounding box 1
\param min2 [In] Minimum x and y of bounding box 2
\param max2 [In] Maximum x and y of bounding box 2
*/
YSBOOL YsCheckBoundingBoxCollision3(const YsVec3 &min1,const YsVec3 &max1,const YsVec3 &min2,const YsVec3 &max2);
/*! This function returns YSTRUE if two bounding boxes intersects or touches each other or YSFALSE otherwise.
\param min1 [In] Minimum x, y, and z of bounding box 1
\param max1 [In] Maximum x, y, and z of bounding box 1
\param min2 [In] Minimum x, y, and z of bounding box 2
\param max2 [In] Maximum x, y, and z of bounding box 2
*/
YSBOOL YsCheckBoundingBoxCollision2(const YsVec2 &min1,const YsVec2 &max1,const YsVec2 &min2,const YsVec2 &max2);
/*! This function returns YSTRUE if the reference point is inside or on the boundary of the given bounding box
or YSFALSE otherwise.
\param ref [In] Reference point
\param min [In] Minimum x, y, and z of the bounding box
\param max [In] Maximum x, y, and z of the bounding box
*/
YSBOOL YsCheckInsideBoundingBox3(const YsVec3 &ref,const YsVec3 &min,const YsVec3 &max);
/*! This function returns YSTRUE if the reference point is inside or on the boundary of the given bounding box
or YSFALSE otherwise.
\param ref [In] Reference point
\param min [In] Minimum x and y of the bounding box
\param max [In] Maximum x and y of the bounding box
*/
YSBOOL YsCheckInsideBoundingBox2(const YsVec2 &ref,const YsVec2 &min,const YsVec2 &max);
/*! This function returns if the given polygon is oriented clockwise or counter clockwise. */
YSFLIPDIRECTION YsCheckFlipDirection2(YSSIZE_T np,const YsVec2 p[]);
/*! This function returns if the given polygon is oriented clockwise or counter clockwise. */
inline YSFLIPDIRECTION YsCheckFlipDirection2(YsConstArrayMask <YsVec2> plg)
{
return YsCheckFlipDirection2(plg.GetN(),plg);
}
/*! This function returns if the given polygon is oriented clockwise or counter clockwise
with respect to the given normal.
\param np [In] Number of points of the polygon
\param p [In] Points of the polygon
\param n [In] Normal vector */
YSFLIPDIRECTION YsCheckFlipDirection3(YSSIZE_T np,const YsVec3 p[],const YsVec3 &n);
/*! This function returns if the given polygon is oriented clockwise or counter clockwise
with respect to the given normal.
\param np [In] Number of points of the polygon
\param p [In] Points of the polygon
\param n [In] Normal vector */
inline YSFLIPDIRECTION YsCheckFlipDirection3(YsConstArrayMask <YsVec3> plg,const YsVec3 &n)
{
return YsCheckFlipDirection3(plg.GetN(),plg,n);
}
/*! This function calculates a line formed by intersecting two planes. This function returns YSOK
if the calculation is sucessful or YSERR if the line could not be calculated.
\param o [Out] A point that the line passes through
\param v [Out] A vector parallel so the line
\param pln1 [In] A plane
\param pln2 [In] A plane */
YSRESULT YsGetTwoPlaneCrossLine(YsVec3 &o,YsVec3 &v,const YsPlane &pln1,const YsPlane &pln2);
/*! This function calculates nearest points of two lines. Even when two lines defined in the
3D space are linearly independent, two lines may not intersect. Therefore, this function
calculates a point on each line that is closest to the other line.
If the calculation is successful, it returns YSOK and the points are returned in np and nq.
\param np [Out] A point on line 1 closest to line 2
\param nq [Out] A point on line 2 closest to line 1
\param p1 [In] A point that line 1 passes through
\param p2 [In] Another point that line 1 passes through
\param q1 [In] A point that line 2 passes through
\param q2 [In] Another point that line 2 passes through
*/
YSRESULT YsGetNearestPointOfTwoLine(YsVec3 &np,YsVec3 &nq,const YsVec3 &p1,const YsVec3 &p2,const YsVec3 &q1,const YsVec3 &q2);
/*! This function calculates the nearest point on the given line from the given reference point and
returns it in np. The line is defined by two points that the line passes through.
\param np [Out] Nearest point
\param p1 [In] A point that the line passes through
\param p2 [In] A point that the line passes through
\param ref [In] Reference point */
YSRESULT YsGetNearestPointOnLine3(YsVec3 &np,const YsVec3 &p1,const YsVec3 &p2,const YsVec3 &ref);
/*! This function calculates the nearest point on the given line from the given reference point and
returns it in np. The line is defined by two points that the line passes through.
\param np [Out] Nearest point
\param p1 [In] A point that the line passes through
\param p2 [In] A point that the line passes through
\param ref [In] Reference point */
inline YsVec3 YsGetNearestPointOnLine3(const YsVec3 p1p2[2],const YsVec3 &ref)
{
YsVec3 np;
YsGetNearestPointOnLine3(np,p1p2[0],p1p2[1],ref);
return np;
}
/*! This function calculates the nearest point on the given line from the given reference point and
returns it in np. The line is defined by two points that the line passes through.
\param np [Out] Nearest point
\param p1 [In] A point that the line passes through
\param p2 [In] A point that the line passes through
\param ref [In] Reference point */
YSRESULT YsGetNearestPointOnLine2(YsVec2 &np,const YsVec2 &p1,const YsVec2 &p2,const YsVec2 &ref);
/*! This function returns distance from a reference point to a line that passes through given points.
\param p1 [In] A point that the line passes through
\param p2 [In] A point that the line passes through
\param ref [In] Reference point */
const double YsGetPointLineDistance2(const YsVec2 &p1,const YsVec2 &p2,const YsVec2 &ref);
/*! This function returns distance from a reference point to a line that passes through given points.
\param p1 [In] A point that the line passes through
\param p2 [In] A point that the line passes through
\param ref [In] Reference point */
const double YsGetPointLineDistance3(const YsVec3 &p1,const YsVec3 &p2,const YsVec3 &ref);
/*! This function returns distance from a reference point to a line that passes through given points.
\param p1 [In] A point that the line passes through
\param p2 [In] A point that the line passes through
\param ref [In] Reference point */
inline const double YsGetPointLineDistance3(const YsVec3 p1p2[2],const YsVec3 &ref)
{
return YsGetPointLineDistance3(p1p2[0],p1p2[1],ref);
}
/*! This function returns the nearest point of a piece of line segment
(not infinite line) between p1 and p2. */
YsVec3 YsGetNearestPointOnLinePiece(const YsVec3 edVtPos[2],const YsVec3 &from);
/*! This function returns the nearest point of a piece of line segment
(not infinite line) between p1 and p2. */
YsVec2 YsGetNearestPointOnLinePiece(const YsVec2 edVtPos[2],const YsVec2 &from);
/*! This function returns distance between two pieces of line.
\param p1 [In] A end point of line 1
\param p2 [In] The other end point of line 1
\param q1 [In] A end point of line 2
\param q2 [In] The other end point of line 2 */
double YsGetDistanceBetweenTwoLineSegment(const YsVec3 &p1,const YsVec3 &p2,const YsVec3 &q1,const YsVec3 &q2);
/*! This function returns distance from a reference point to a piece of line
\param p1 [In] A end point of the line
\param p2 [In] The other end point of the line
\param ref [In] Reference point */
const double YsGetPointLineSegDistance2(const YsVec2 &p1,const YsVec2 &p2,const YsVec2 &ref);
/*! This function returns distance from a reference point to a piece of line
\param p1 [In] A end point of the line
\param p2 [In] The other end point of the line
\param ref [In] Reference point */
const double YsGetPointLineSegDistance3(const YsVec3 &p1,const YsVec3 &p2,const YsVec3 &ref);
/*! This function returns distance from a reference point to a piece of line
\param p[0] [In] A end point of the line
\param p[1] [In] The other end point of the line
\param ref [In] Reference point */
const double YsGetPointLineSegDistance3(const YsVec3 p[2],const YsVec3 &ref);
/*! This function returns YSTRUE if the projection of the reference point on the given line
is between two end points of the piece of the line.
\param ref [In] Reference point
\param p1 [In] One end point of the piece of line
\param p2 [In] The other end point of the piece of line */
YSBOOL YsCheckPointIsOnLineSegment3(const YsVec3 &ref,const YsVec3 &p1,const YsVec3 &p2);
/*! This function returns how two polygons are intersecting each other.
\sa YSINTERSECTION
\param np [In] Number of points of polygon 1
\param p [In] Points of polygon 1
\param nq [In] Number of points of polygon 2
\param q [In] Points of polygon 2
*/
YSINTERSECTION YsGetPolygonPenetration(YSSIZE_T np,const YsVec3 p[],YSSIZE_T nq,const YsVec3 q[]);
/*! This function returns a point inside the given polygon.
\param ret [Out] A point inside the given polygon
\param np [In] Number of points of the polygon
\param p [In] Points of the polygon
\param strictCheckOfConvexity [In] This parameter will be passed internally to YsCheckConvex2
*/
YSRESULT YsGetArbitraryInsidePointOfPolygon2(YsVec2 &ret,YSSIZE_T np,const YsVec2 p[],YSBOOL strictCheckOfConvexity=YSFALSE);
/*! Templated version of YsGetArbitraryInsidePointOfPolygon2 */
inline YSRESULT YsGetArbitraryInsidePointOfPolygon2(YsVec2 &ret,YsConstArrayMask <YsVec2> plg,YSBOOL strictCheckOfConvexity=YSFALSE)
{
return YsGetArbitraryInsidePointOfPolygon2(ret,plg.GetN(),plg,strictCheckOfConvexity);
}
/*! This function returns a point inside the given polygon.
\param ret [Out] A point inside the given polygon
\param np [In] Number of points of the polygon
\param p [In] Points of the polygon
\param strictCheckOfConvexity [In] This parameter will be passed internally to YsCheckConvex3
*/
YSRESULT YsGetArbitraryInsidePointOfPolygon3(YsVec3 &ret,YSSIZE_T np,const YsVec3 p[],YSBOOL strictCheckOfConvexity=YSFALSE);
/*! Templated version of YsGetArbitraryInsidePointOfPolygon3 */
inline YSRESULT YsGetArbitraryInsidePointOfPolygon3(YsVec3 &ret,YsConstArrayMask <YsVec3> plg,YSBOOL strictCheckOfConvexity=YSFALSE)
{
return YsGetArbitraryInsidePointOfPolygon3(ret,plg.GetN(),plg,strictCheckOfConvexity);
}
/*! This function sorts points p[0], p[1], ..., p[np-1].
The function first calculates the diameter of the given points (distance between two points
that are the farthest apart) and then sorts points based on the distance from one of the two points.
If each point is associated with an index, this function can sort indices together.
\sa YsSortPointSet3Template
\param np [In] Number of points
\param p [In/Out] Points
\param idx [In/Out] Indices associated with the points. Can be NULL.
*/
YSRESULT YsSortPointSet3(YSSIZE_T np,YsVec3 p[],int idx[]);
/*! This function sorts points p[0], p[1], ..., p[np-1] based on the distance from a reference point.
If each point is associated with an index, this function can sort indices together.
\sa YsSortPointSet3Template
\param np [In] Number of points
\param p [In/Out] Points
\param idx [In/Out] Indices associated with the points. Can be NULL.
\param ref [In] Reference point
*/
YSRESULT YsSortPointSet3(YSSIZE_T np,YsVec3 p[],int idx[],const YsVec3 &ref);
/*! This function sorts points p[0], p[1], ..., p[np-1] based on the distance from a reference point.
If each point is associated with an index, this function can sort indices together.
\sa YsSortPointSet3Template
\param np [In] Number of points
\param p [In/Out] Points
\param idx [In/Out] Indices associated with the points. Can be NULL.
\param ref [In] Reference point
\param sqKnownMaxDistance [In] Square of diameter of the set of points (Distance between two points that are the farthest apart)
*/
YSRESULT YsSortPointSet3(YsVec3 p[],int idx[],YSSIZE_T np,const YsVec3 ref,double sqKnownMaxDistance);
/*! This function calculates a circumscribed circle of the triangle.
\param cen [Out] Center of the circumscribed circle
\param rad [Out] Radius of the circumscribed circle
\param p1 [In] A point of the triangle
\param p2 [In] A point of the triangle
\param p3 [In] A point of the triangle
*/
YSRESULT YsGetCircumCircle(YsVec2 &cen,double &rad,const YsVec2 &p1,const YsVec2 &p2,const YsVec2 &p3);
/*! This function calculates a inscribed circle of the triangle.
\param cen [Out] Center of the inscribed circle
\param rad [Out] Radius of the inscribed circle
\param p1 [In] A point of the triangle
\param p2 [In] A point of the triangle
\param p3 [In] A point of the triangle
*/
YSRESULT YsGetInscribedCircle(YsVec2 &cen,double &rad,const YsVec2 &p1,const YsVec2 &p2,const YsVec2 &p3);
/*! This function calculates the radius of the circumscribed sphere of a tetrahedron. If the calculation
is successful, it returns YSOK, or YSERR otherwise.
\param rad [Out] Radius of the circumscribed sphere
\param p [In] Array of constant pointers to the points of the tetrahedron
*/
YSRESULT YsGetCircumSphereRadius(double &rad,YsVec3 const *p[4]);
/*! This function calculates the center and radius of the circumscribed sphere of a tetrahedron.
If the calculation is successful, it returns YSOK, or YSERR otherwise.
\param cen [Out] Center of the circumscribed sphere
\param rad [Out] Radius of the circumscribed sphere
\param p [In] Array of constant pointers to the points of the tetrahedron
*/
YSRESULT YsGetCircumSphere(YsVec3 &cen,double &rad,YsVec3 const *p[4]);
/*! This function calculates the radius of the circumscribed sphere of a tetrahedron.
If the calculation is successful, it returns YSOK, or YSERR otherwise.
\param rad [Out] Radius of the circumscribed sphere
\param p [In] Points of the tetrahedron
*/
YSRESULT YsGetCircumSphereRadius(double &rad,const YsVec3 p[4]);
/*! This function calculates the center and radius of the circumscribed sphere of a tetrahedron.
If the calculation is successful, it returns YSOK, or YSERR otherwise.
\param cen [Out] Center of the circumscribed sphere
\param rad [Out] Radius of the circumscribed sphere
\param p [In] Points of the tetrahedron
*/
YSRESULT YsGetCircumSphere(YsVec3 &cen,double &rad,const YsVec3 p[4]);
/*! This function calculates normal of the given triangle.
\param nom [Out] Unit normal vector of the triangle
\param t1 [In] A point of the triangle
\param t2 [In] A point of the triangle
\param t3 [In] A point of the triangle
*/
YSRESULT YsComputeNormalOfTriangle(YsVec3 &nom,const YsVec3 &t1,const YsVec3 &t2,const YsVec3 &t3);
/*! This function calculates normal vectors of the four faces of a tetrahedron.
\param nom [Out] Unit normal vectors of the faces of the tetrahedron
\param p [In] Constant pointers to the points of the tetrahedron.
*/
YSRESULT YsGetNormalOfTet(YsVec3 nom[4],YsVec3 const *p[4]);
/*! This function calculates the radius of the inscribed sphere of a tetrahedron.
If the calculation is successful, it returns YSOK, or YSERR otherwise.
\param rad [Out] Radius of the incribed sphere
\param p [In] Array of constant pointers to the points of the tetrahedron
*/
YSRESULT YsGetInscribedSphereRadius(double &rad,YsVec3 const *p[4]);
/*! This function calculates the center and radius of the incribed sphere of a tetrahedron.
If the calculation is successful, it returns YSOK, or YSERR otherwise.
\param cen [Out] Center of the inscribed sphere
\param rad [Out] Radius of the inscribed sphere
\param p [In] Array of constant pointers to the points of the tetrahedron
*/
YSRESULT YsGetInscribedSphere(YsVec3 &cen,double &rad,YsVec3 const *p[4]);
/*! This function calculates the radius of the inscribed sphere of a tetrahedron.
If the calculation is successful, it returns YSOK, or YSERR otherwise.
\param rad [Out] Radius of the incribed sphere
\param p [In] Array of pointsof the tetrahedron
*/
YSRESULT YsGetInscribedSphereRadius(double &rad,const YsVec3 p[4]);
/*! This function calculates the radius of the inscribed sphere of a tetrahedron.
If the calculation is successful, it returns YSOK, or YSERR otherwise.
\param cen [Out] Center of the inscribed sphere
\param rad [Out] Radius of the incribed sphere
\param p [In] Array of pointsof the tetrahedron
*/
YSRESULT YsGetInscribedSphere(YsVec3 &cen,double &rad,const YsVec3 p[4]);
/*! This function calculates a sphere that circumscribes the given triangle and whose center is
lying on the plane of the triangle.
If the calculation is successful, it returns YSOK, or YSERR otherwise.
\param cen [Out] Center of the circumscribed sphere
\param rad [Out] Radius of the circumscribed sphere
\param p1 [In] A point of the triangle
\param p2 [In] A point of the triangle
\param p3 [In] A point of the triangle
*/
YSRESULT YsGetCircumSphereOfTriangle(YsVec3 &cen,double &rad,const YsVec3 &p1,const YsVec3 &p2,const YsVec3 &p3);
/*! This function calculates a sphere that inscribes the given triangle and whose center is
lying on the plane of the triangle.
If the calculation is successful, it returns YSOK, or YSERR otherwise.
\param cen [Out] Center of the inscribed sphere
\param rad [Out] Radius of the inscribed sphere
\param p1 [In] A point of the triangle
\param p2 [In] A point of the triangle
\param p3 [In] A point of the triangle
*/
YSRESULT YsGetInscribedSphereOfTriangle(YsVec3 &cen,double &rad,const YsVec3 &p1,const YsVec3 &p2,const YsVec3 &p3);
/*! This function scales the input bounding box by given scaling ratio.
The center of the box stays unchanged.
Although this function is called 'Inflate', you can shrink the bounding box by giving
scaling ratio of less than 1.0.
\param newMin [Out] Minimum x,y, and z of the scaled bounding box
\param newMax [Out] Maximum x,y, and z of the scaled bounding box
\param min [In] Minimum x,y, and z of the input bounding box
\param max [In] Maximum x,y, and z of the input bounding box
\param ratio [In] Scaling ratio
*/
YSRESULT YsInflateBoundingBox(YsVec3 &newMin,YsVec3 &newMax,const YsVec3 &min,const YsVec3 &max,const double ratio);
/*! This function calculates a circle that is made by intersection of two spheres.
If the calculation is successful, this function returns YSOK, or YSERR otherwise.
\param o [Out] Center of the circle
\param n [Out] Normal of the circle
\param r [Out] Radius of the circle
\param c1 [In] Center of the first sphere
\param r1 [In] Radius of the first sphere
\param c2 [In] Center of the second sphere
\param r2 [In] Radius of the second sphere
*/
YSRESULT YsComputeTwoSphereIntersection
(YsVec3 &o,YsVec3 &n,double &r,const YsVec3 &c1,const double &r1,const YsVec3 &c2,const double &r2);
/*! This function calculates two intersection points of three spheres.
If the calculation is successful, this function returns YSOK, or YSERR otherwise.
\param i1 [Out] An intersection
\param i2 [Out] An intersection
\param c1 [In] Center of the first sphere
\param r1 [In] Radius of the first sphere
\param c2 [In] Center of the second sphere
\param r2 [In] Radius of the second sphere
\param c3 [In] Center of the third sphere
\param r3 [In] Radius of the third sphere
*/
YSRESULT YsComputeThreeSphereIntersection
(YsVec3 &i1,YsVec3 &i2,
const YsVec3 &c1,const double &r1,const YsVec3 &c2,const double &r2,const YsVec3 &c3,const double &r3);
/*! This function calculates intersection(s) between a line defined by two passing points p0 and p1
and a sphere defined by center c and radius r.
Returns YSOK if the calculation was successful. Returns YSERR if there is no intersection.
*/
YSRESULT YsComputeSphereLineIntersection
(YsVec3 &i1,YsVec3 &i2,const YsVec3 &c,double r,const YsVec3 &p0,const YsVec3 &p1);
/*! This function calculates a point on a sequence of line segments that is nearest to the reference point.
This function returns YSOK if the calculation is successful, or YSERR otherwise.
\param nearPos [Out] A point on the line segments that is nearest to the reference point
\param nearIdx [Out] Index to the segment on which nearPos is located.
\param nearNode [Out] If it is YSTRUE, the nearest point is p[nearIdx]. Or, the nearest point is between p[nearIdx] and p[nearIdx+1]
\param np [In] Number of points of the line segments
\param p [In] Pints of the line segments
\param ref [In] Reference point
*/
YSRESULT YsGetNearestPointOnLineSegments3(YsVec3 &nearPos,int &nearIdx,YSBOOL &nearNode,YSSIZE_T np,const YsVec3 p[],const YsVec3 &ref);
inline YSRESULT YsGetNearestPointOnLineSegments3(YsVec3 &nearPos,int &nearIdx,YSBOOL &nearNode,YsConstArrayMask <YsVec3> pos,const YsVec3 &ref)
{
return YsGetNearestPointOnLineSegments3(nearPos,nearIdx,nearNode,pos.GetN(),pos,ref);
}
/*! This function calculates a point on a sequence of line segments that is nearest to the reference point.
This function returns YSOK if the calculation is successful, or YSERR otherwise.
\param nearPos [Out] A point on the line segments that is nearest to the reference point
\param nearIdx [Out] Index to the segment on which nearPos is located.
\param nearNode [Out] If it is YSTRUE, the nearest point is p[nearIdx]. Or, the nearest point is between p[nearIdx] and p[nearIdx+1]
\param np [In] Number of points of the line segments
\param p [In] Pints of the line segments
\param ref [In] Reference point
*/
YSRESULT YsGetNearestPointOnLineSegments2(YsVec2 &nearPos,int &nearIdx,YSBOOL &nearNode,YSSIZE_T np,const YsVec2 p[],const YsVec2 &ref);
inline YSRESULT YsGetNearestPointOnLineSegments2(YsVec2 &nearPos,int &nearIdx,YSBOOL &nearNode,YsConstArrayMask <YsVec2> pos,const YsVec2 &ref)
{
return YsGetNearestPointOnLineSegments2(nearPos,nearIdx,nearNode,pos.GetN(),pos,ref);
}
/*! This function calculates tangential vector of line segments at a node.
\param unitTan [Out] Unit tangential vector
\param ndId [In] Index to the node where the tangential vector is calculated (0<=ndId<np)
\param np [In] Number of nodes of the line segments
\param p [In] Points of the line segments
*/
YSRESULT YsGetTangentialVectorAtNodeOfLineSegments3(YsVec3 &unitTan,YSSIZE_T ndId,YSSIZE_T np,const YsVec3 p[]);
/*! This function calculates tangential vector of line segments of a segment (p[ndId+1]-p[ndId]).
\param unitTan [Out] Unit tangential vector
\param edId [In] Index to the segment where the tangential vector is calculated (0<=ndId<np-1)
\param np [In] Number of nodes of the line segments
\param p [In] Points of the line segments
*/
YSRESULT YsGetTangentialVectorOnEdgeOfLineSegments3(YsVec3 &unitTan,int edId,int np,const YsVec3 p[]);
/*! This function calculates an intersection between a circle and a infinite line defined by two points p0 and p1 and returns them in itc[2].
It returns YSOK if the calculation was successful, or YSERR otherwise (such as no intersection.) */
YSRESULT YsComputeCircleLineIntersection(YsVec2 itsc[2],const YsVec2 &cen,const double rad,const YsVec2 &p0,const YsVec2 &p1);
/*! This function calculates an intersection between a circle and a infinite line defined by two points p[0] and p[1] and returns them in itc[2].
It returns YSOK if the calculation was successful, or YSERR otherwise (such as no intersection.) */
YSRESULT YsComputeCircleLineIntersection(YsVec2 itsc[2],const YsVec2 &cen,const double rad,const YsVec2 p[2]);
/*! This functioncalculates two points where a tangential line that passes through the given passing point touches the circle.
The tangential points are returned in tanPos[0] and tanPos[1].
Returns YSOK if successful, or YSERR if not. */
YSRESULT YsComputeCircleTangentPoint(YsVec2 tanPos[2],const YsVec2 &cen,const double rad,const YsVec2 &passingPoint);
/// \cond
template <class T>
int YsFindNearestPoint(const T &refp,int np,const T p[])
{
if(np>0)
{
int i,id;
double d,dMin;
id=0;
dMin=(p[0]-refp).GetSquareLength();
for(i=1; i<np; i++)
{
d=(p[i]-refp).GetSquareLength();
if(d<dMin)
{
id=i;
dMin=d;
}
}
return id;
}
return -1;
}
/// \endcond
/*! This function finds the point nearest to the reference point among the given set of points
and returns the index to the nearest point.
\param ref [In] Refernce point
\param np [In] Number of points
\param p [In] Set of points
*/
inline int YsFindNearestPoint3(const YsVec3 &ref,int np,const YsVec3 p[])
{
return YsFindNearestPoint <YsVec3> (ref,np,p);
}
/*! This function finds the point nearest to the reference point among the given set of points
and returns the index to the nearest point.
\param ref [In] Refernce point
\param np [In] Number of points
\param p [In] Set of points
*/
inline int YsFindNearestPoint2(const YsVec2 &ref,int np,const YsVec2 p[])
{
return YsFindNearestPoint <YsVec2> (ref,np,p);
}
/// \cond
template <class T>
int YsFindFarthestPoint(const T &refp,int np,const T p[])
{
if(np>0)
{
int i,id;
double d,dMax;
id=0;
dMax=(p[0]-refp).GetSquareLength();
for(i=1; i<np; i++)
{
d=(p[i]-refp).GetSquareLength();
if(d>dMax)
{
id=i;
dMax=d;
}
}
return id;
}
return -1;
}
/// \endcond
/*! This function finds the point farthest to the reference point among the given set of points
and returns the index to the nearest point.
\param ref [In] Refernce point
\param np [In] Number of points
\param p [In] Set of points
*/
inline int YsFindFarthestPoint3(const YsVec3 &ref,int np,const YsVec3 p[])
{
return YsFindFarthestPoint <YsVec3> (ref,np,p);
}
/*! This function finds the point farthest to the reference point among the given set of points
and returns the index to the nearest point.
\param ref [In] Refernce point
\param np [In] Number of points
\param p [In] Set of points
*/
inline int YsFindFarthestPoint2(const YsVec2 &ref,int np,const YsVec2 p[])
{
return YsFindFarthestPoint <YsVec2> (ref,np,p);
}
template <class T>
inline YSBOOL YsCheckSamePolygon(int nPlVt,const T plVt1[],const T plVt2[],YSBOOL takeReverse=YSTRUE)
{
int i;
int j0=-1;
for(i=0; i<nPlVt; i++)
{
if(plVt1[0]==plVt2[i])
{
j0=i;
break;
}
}
if(0<=j0)
{
YSBOOL different=YSFALSE;
for(i=1; i<nPlVt; i++)
{
if(plVt1[i]!=plVt2[(j0+i)%nPlVt])
{
different=YSTRUE;
break;
}
}
if(YSTRUE!=different)
{
return YSTRUE;
}
if(YSTRUE==takeReverse)
{
for(i=1; i<nPlVt; i++)
{
if(plVt1[i]!=plVt2[(j0+nPlVt-i)%nPlVt])
{
different=YSTRUE;
break;
}
}
if(YSTRUE!=different)
{
return YSTRUE;
}
}
}
return YSFALSE;
}
template <class T>
inline YSBOOL YsCheckSamePolygon(YsConstArrayMask <T> plg1,YsConstArrayMask <T> plg2,YSBOOL takeReverse=YSTRUE)
{
return YsCheckSamePolygon <T> (plg1.GetN(),plg1,plg2.GetN(),plg2(),takeReverse);
}
////////////////////////////////////////////////////////////
/// \cond
// Internal use only. Do not use this template function directly.
template <class T>
void YsQuickSortPointSet3Template(YsVec3 tab[],T idx[],YSSIZE_T nTab,const YsVec3 &refp,double mind,double maxd)
{
if(nTab>1)
{
double threshold;
threshold=(mind+maxd)/2.0;
// smaller comes first
YSBOOL allTheSame;
double d0;
YSSIZE_T i,nSmall;
nSmall=0;
allTheSame=YSTRUE;
d0=(tab[0]-refp).GetSquareLength();
for(i=0; i<nTab; i++) // Actually can begin with 1
{
double var;
var=(tab[i]-refp).GetSquareLength();
if(allTheSame==YSTRUE && YsAbs(sqrt(var)-sqrt(d0))>YsTolerance) // Modified 2000/11/10
{
allTheSame=YSFALSE;
}
if(var<=threshold)
{
YsVec3 a;
a=tab[i];
tab[i]=tab[nSmall];
tab[nSmall]=a;
if(idx!=NULL)
{
T x;
x=idx[i];
idx[i]=idx[nSmall];
idx[nSmall]=x;
}
nSmall++;
}
}
if(allTheSame!=YSTRUE)
{
if(idx!=NULL)
{
YsQuickSortPointSet3Template <T> (tab ,idx ,nSmall ,refp,mind,threshold);
YsQuickSortPointSet3Template <T> (tab+nSmall,idx+nSmall,(nTab-nSmall),refp,threshold,maxd);
}
else
{
YsQuickSortPointSet3Template <T> (tab ,NULL,nSmall ,refp,mind,threshold);
YsQuickSortPointSet3Template <T> (tab+nSmall,NULL,(nTab-nSmall),refp,threshold,maxd);
}
}
}
}
/// \endcond
/*! This function sorts set of points based on the distance from the reference point.
\tparam T A class that is associated with the points. If nothing is associated with the points, make it int and give NULL to idx
\param p [In/Out] Points to be sorted
\param idx [In/Out] Values associated with the points. If nothing is associated with the points, it can be NULL.
\param np [In] Number of points
\param ref [In] Reference point
\param sqKnownMaxDistance [In] Maximum distance from the reference point.
*/
template <class T>
YSRESULT YsSortPointSet3Template(YsVec3 p[],T idx[],YSSIZE_T np,const YsVec3 ref,double sqKnownMaxDistance)
{ // ^^^^ ref must not be a pointer/reference
YsQuickSortPointSet3Template(p,idx,np,ref,0.0,sqKnownMaxDistance);
return YSOK;
}
/*! This function sorts set of points based on the distance from the reference point.
The reference point is taken from one of the two points among the given points that
makes the maximum distance.
\tparam T A class that is associated with the points. If nothing is associated with the points, make it int and give NULL to idx
\param np [In] Number of points
\param p [In/Out] Points to be sorted
\param idx [In/Out] Values associated with the points. If nothing is associated with the points, it can be NULL.
*/
template <class T>
YSRESULT YsSortPointSet3Template(YSSIZE_T np,YsVec3 p[],T idx[])
{
double sqDist;
YSSIZE_T vt1,vt2;
vt1=0;
vt2=0;
sqDist=0.0;
for(YSSIZE_T i=0; i<np; i++)
{
for(YSSIZE_T j=i+1; j<np; j++)
{
if((p[i]-p[j]).GetSquareLength()>sqDist)
{
vt1=i;
vt2=j;
sqDist=(p[i]-p[j]).GetSquareLength();
}
}
}
return YsSortPointSet3(p,idx,np,p[vt1],sqDist);
}
/*! This function sorts set of points based on the distance from the reference point.
\tparam T A class that is associated with the points. If nothing is associated with the points, make it int and give NULL to idx
\param p [In/Out] Points to be sorted
\param idx [In/Out] Values associated with the points. If nothing is associated with the points, it can be NULL.
\param np [In] Number of points
\param ref [In] Reference point
*/
template <class T>
YSRESULT YsSortPointSet3Template(YSSIZE_T np,YsVec3 p[],T idx[],const YsVec3 &ref)
{
double sqDist;
sqDist=0.0;
for(YSSIZE_T i=0; i<np; i++)
{
if((ref-p[i]).GetSquareLength()>sqDist)
{
sqDist=(ref-p[i]).GetSquareLength();
}
}
return YsSortPointSet3Template(p,idx,np,ref,sqDist);
}
////////////////////////////////////////////////////////////
/*! This function finds an equation of the least-square fitting plane of the given set of points.
The plane equation will be: ax+by+cz+d=0
\param a [Out] A coefficient for x
\param b [Out] A coefficient for y
\param c [Out] A coefficient for z
\param d [Out] Constant term
\param np [In] Number of points
\param p [In] Array of points
*/
YSRESULT YsFindLeastSquareFittingPlane(double &a,double &b,double &c,double &d,YSSIZE_T np,const YsVec3 p[]);
/*! This function finds an equation of the least-square fitting plane of the given set of points.
The plane equation will be: ax+by+cz+d=0
\param a [Out] A coefficient for x
\param b [Out] A coefficient for y
\param c [Out] A coefficient for z
\param d [Out] Constant term
\param p [In] Array of points
*/
inline YSRESULT YsFindLeastSquareFittingPlane(double &a,double &b,double &c,double &d,YsConstArrayMask <YsVec3> vtxList)
{
return YsFindLeastSquareFittingPlane(a,b,c,d,vtxList.GetN(),vtxList);
}
/*! This function calculates a unit normal vector of the least-square fitting plane to the given set of points.
\param nom [Out] Unit normal vector
\param np [In] Number of points
\param p [In] Array of points
*/
YSRESULT YsFindLeastSquareFittingPlaneNormal(YsVec3 &nom,YSSIZE_T np,const YsVec3 p[]);
/*! This function calculates a unit normal vector of the least-square fitting plane to the given set of points.
\param nom [Out] Unit normal vector
\param p [In] Array of points
*/
inline YSRESULT YsFindLeastSquareFittingPlaneNormal(YsVec3 &nom,YsConstArrayMask <YsVec3> vtxList)
{
return YsFindLeastSquareFittingPlaneNormal(nom,vtxList.GetN(),vtxList);
}
/*! This function calculates a least-square fitting plane to the given set of points and returns
a point that the plane passes through and a unit normal vector.
\param org [Out] A point that the plane passes through
\param nom [Out] Unit normal vector
\param np [In] Number of points
\param p [In] Array of points
*/
YSRESULT YsFindLeastSquareFittingPlane(YsVec3 &org,YsVec3 &nom,YSSIZE_T np,const YsVec3 p[]);
/*! This function calculates a least-square fitting plane to the given set of points and returns
a point that the plane passes through and a unit normal vector.
\param org [Out] A point that the plane passes through
\param nom [Out] Unit normal vector
\param p [In] Array of points
*/
inline YSRESULT YsFindLeastSquareFittingPlane(YsVec3 &org,YsVec3 &nom,YsConstArrayMask <YsVec3> vtxList)
{
return YsFindLeastSquareFittingPlane(org,nom,vtxList.GetN(),vtxList);
}
/*! This function calculates a point that minimizes the sum of square distances from given set of lines.
\param pos [Out] The point
\param nLine [In] Number of lines
\param o [In] Points that lines passes through
\param v [In] Vectors parallel to the lines
*/
YSRESULT YsFindLeastSquarePointFromLine(YsVec3 &pos,const YSSIZE_T nLine,const YsVec3 o[],const YsVec3 v[]);
/*! This function calculates a point that minimizes the sum of square distances from given set of planes.
*/
template <class T>
YSRESULT YsFindLeastSquarePointFromPlane(YsVec3 &pos,const T &bunchOfPln)
{
YsMatrix3x3 mat(YSFALSE);
YsVec3 rhs=YsVec3::Origin();
mat.MakeZero();
for(auto &pln : bunchOfPln)
{
double on=pln.GetOrigin()*pln.GetNormal();
double nx=pln.GetNormal().x();
double ny=pln.GetNormal().y();
double nz=pln.GetNormal().z();
mat.Add(1,1,nx*nx);
mat.Add(1,2,nx*ny);
mat.Add(1,3,nx*nz);
mat.Add(2,1,nx*ny);
mat.Add(2,2,ny*ny);
mat.Add(2,3,ny*nz);
mat.Add(3,1,nx*nz);
mat.Add(3,2,ny*nz);
mat.Add(3,3,nz*nz);
rhs.AddX(nx*on);
rhs.AddY(ny*on);
rhs.AddZ(nz*on);
}
if(YSOK==mat.Invert())
{
pos=mat*rhs;
return YSOK;
}
return YSERR;
}
/*! This function returns the total length of the given line segments
\param np [In] Number of points
\param p [In] Points of the line segments
\param isLoop [In] If it is YSTRUE, the given line segment is a closed loop.
*/
double YsCalculateTotalLength2(YSSIZE_T np,const YsVec2 p[],YSBOOL isLoop);
/*! Templated version of YsCalculateTotalLength2 */
inline double YsCalculateTotalLength2(YsConstArrayMask <YsVec2> p,YSBOOL isLoop)
{
return YsCalculateTotalLength2(p.GetN(),p,isLoop);
}
/*! This function returns the total length of the given line segments
\param np [In] Number of points
\param p [In] Points of the line segments
\param isLoop [In] If it is YSTRUE, the given line segment is a closed loop.
*/
double YsCalculateTotalLength3(YSSIZE_T np,const YsVec3 p[],YSBOOL isLoop);
/*! Templated version of YsCalculateTotalLength3 */
inline double YsCalculateTotalLength3(YsConstArrayMask <YsVec3> p,YSBOOL isLoop)
{
return YsCalculateTotalLength3(p.GetN(),p,isLoop);
}
/*! This function returns cosine of maximum quadrilateral warpage angle. */
double YsCalculateQuadWarpage(const YsVec3 p[4]);
/*! This function returns an angle from the refVec to the tstVec counter-clockwise with respect to the unitClockFaceDir.
The angle is measured on the clock-face plane.
unitClockFaceDir must be a unit vector, but tstVec and refVec don't have to be of unit length.
*/
double YsCalculateCounterClockwiseAngle(const YsVec3 &tstVec,const YsVec3 &refVec,const YsVec3 &unitClockFaceDir);
/*! This function calculates number of blocks in x-, y-, and z-directions if the bounding box is divided into rougly nTotal cells.
If unitBox is non-NULL, size of the lattice cell that divides the box into nx,ny,nz will be returned.
unitBox can be NULL if this information is unnecessary. */
void YsCalculateLatticeDivision3(int &nx,int &ny,int &nz,YsVec3 *unitBox,const YsVec3 bbx[2],int nLatticeCell);
/*! This function calculates number of blocks in x-, y-, and z-directions if the bounding box is divided into rougly nTotal cells.
If unitBox is non-NULL, size of the lattice cell that divides the box into nx,ny,nz will be returned.
unitBox can be NULL if this information is unnecessary. */
void YsCalculateLatticeDivision3(int &nx,int &ny,int &nz,YsVec3 *unitBox,const YsVec3 &bbx0,const YsVec3 &bbx1,int nLatticeCell);
/*! This function compares axis[0] to axis[nAxis-1] and returns the index to the one that makes fabs(dir*axis[index]) maximum.
In other words, finds the one that is most parallel to dir. */
int YsFindClosestAxis(const YsVec3 &dir,YSSIZE_T nAxis,const YsVec3 axis[]);
/*! This function compares vec[0] to vec[nVec-1] and returns the index to the one that makes dir*axis[index] maximum.
In other words, finds the one that is closest to dir. */
int YsFindClosestVector(const YsVec3 &dir,YSSIZE_T nVec,const YsVec3 vec[]);
/*! This function calculates an intersection between an infinite cylinder defined by c1,c2, and radius and an infinite line defined by p1,p2.
This function returns YSOK if the calculation is successful, or YSERR if the intersection could not be calculated (means no intersection) */
YSRESULT YsCalculateCylinderLineIntersection(YsVec3 itsc[2],const YsVec3 &c1,const YsVec3 &c2,const double radius,const YsVec3 &p1,const YsVec3 &p2);
/*! This function finds and returns the index to the longest edge piece of the given 3D polygon.
The longest edge will be plg[returnValue]-plg[(returnValue+1)%np]. */
YSSIZE_T YsFindLongestEdgeIndexOfPolygon(YSSIZE_T np,const YsVec3 plg[]);
/*! This function finds and returns the index to the longest edge piece of the given 3D polygon.
The longest edge will be plg[returnValue]-plg[(returnValue+1)%np]. */
inline YSSIZE_T YsFindLongestEdgeIndexOfPolygon(YsConstArrayMask <YsVec3> plg)
{
return YsFindLongestEdgeIndexOfPolygon(plg.GetN(),plg);
}
/*! This function finds and returns the index to the longest edge piece of the given 2D polygon.
The longest edge will be plg[returnValue]-plg[(returnValue+1)%np]. */
YSSIZE_T YsFindLongestEdgeIndexOfPolygon(YSSIZE_T np,const YsVec2 plg[]);
/*! This function finds and returns the index to the longest edge piece of the given 3D polygon.
The longest edge will be plg[returnValue]-plg[(returnValue+1)%np]. */
inline YSSIZE_T YsFindLongestEdgeIndexOfPolygon(YsConstArrayMask <YsVec2> plg)
{
return YsFindLongestEdgeIndexOfPolygon(plg.GetN(),plg);
}
/*! This function finds and returns the index to the shortest edge piece of the given 3D polygon.
The shortest edge will be plg[returnValue]-plg[(returnValue+1)%np]. */
YSSIZE_T YsFindShortestEdgeIndexOfPolygon(YSSIZE_T np,const YsVec3 plg[]);
/*! This function finds and returns the index to the shortest edge piece of the given 3D polygon.
The shortest edge will be plg[returnValue]-plg[(returnValue+1)%np]. */
inline YSSIZE_T YsFindShortestEdgeIndexOfPolygon(YsConstArrayMask <YsVec3> plg)
{
return YsFindShortestEdgeIndexOfPolygon(plg.GetN(),plg);
}
/*! This function finds and returns the index to the shortest edge piece of the given 2D polygon.
The shortest edge will be plg[returnValue]-plg[(returnValue+1)%np]. */
YSSIZE_T YsFindShortestEdgeIndexOfPolygon(YSSIZE_T np,const YsVec2 plg[]);
/*! This function finds and returns the index to the shortest edge piece of the given 3D polygon.
The shortest edge will be plg[returnValue]-plg[(returnValue+1)%np]. */
inline YSSIZE_T YsFindShortestEdgeIndexOfPolygon(YsConstArrayMask <YsVec2> plg)
{
return YsFindShortestEdgeIndexOfPolygon(plg.GetN(),plg);
}
////////////////////////////////////////////////////////////
/*! This function returns a face angle (in-angle) of the polygon at corner specified by vtIdx.
It works even if the polygon has self-intersecting edges. */
double YsGetPolygonFaceAngle(YSSIZE_T np,const YsVec2 p[],YSSIZE_T vtIdx);
inline double YsGetPolygonFaceAngle(YsConstArrayMask <YsVec2> p,YSSIZE_T vtIdx)
{
return YsGetPolygonFaceAngle(p.GetN(),p,vtIdx);
}
/*! This function creates a matrix that projects a point onto the plane that passes through O and is perpedicular to N.
ProjDir is the direction of projection.
It returns YSOK if successful.
It fails when ProjDir and N are almost 90 degrees apart, and returns YSERR in that case.
*/
YSRESULT YsMakePlaneProjectionMatrix(YsMatrix4x4 &Tfm,const YsVec3 &R,const YsVec3 &N,const YsVec3 &ProjDir);
YSBOOL YsVectorPointingInside(YSSIZE_T nPlVt,const YsVec2 plVtPos[],YSSIZE_T vtIdx,const YsVec2 &vec);
YSBOOL YsVectorPointingInsideFromEdge(YSSIZE_T nPlVt,const YsVec2 plVtPos[],YSSIZE_T edIdx,const YsVec2 &vec);
/*! This function calculates a bi-sector plane of two lines defined by passing points p1,q1, and p2,q2.
If multiple bi-sector planes are possible, it returns one of them.
If successful, it returns YSOK. If no bi-sector plane can be calculated, it fails and returns YSERR.
It could faile when:
(1) Two lines are identical, or
(2) p1==q1 or p2==q2.
*/
YSRESULT YsGetBisectorPlane(YsPlane &pln,const YsVec3 &p1,const YsVec3 &q1,const YsVec3 &p2,const YsVec3 &q2);
/*! This function checks if two triangles intersects or touches each other.
*/
YSINTERSECTION YsCheckTriangleIntersection(const YsVec2 t0[3],const YsVec2 t1[3]);
YSINTERSECTION YsCheckTriangleIntersection(const YsVec3 t0[3],const YsVec3 t1[3],const YsVec3 &nom);
/*! Clip a 2D line with a polygon and divide it into outside and inside parts.
*/
void YsClipLineByPolygon(
YsArray <YsVec2,2> &inside,YsArray <YsVec2,2> &outside,
const YsVec2 p0,const YsVec2 p1,
YsConstArrayMask <YsVec2> plg,
YsRect2 plgBbx);
/*! Triangulate a convex polygon and returns indices to the triangles.
*/
YsArray <YSSIZE_T> YsTriangulateConvexPolygon(const YsConstArrayMask <YsVec2> &plg);
YsArray <YSSIZE_T> YsTriangulateConvexPolygon(const YsConstArrayMask <YsVec3> &plg);
/*! Returns YSTRUE if the polygon has a self-intersection. */
YSBOOL YsCheckPolygonSelfIntersection(YsConstArrayMask <YsVec2> plg);
YSBOOL YsCheckPolygonSelfIntersection(YsConstArrayMask <YsVec3> plg,const YsVec3 &nom);
YSBOOL YsCheckPolygonSelfIntersection(YsConstArrayMask <YsVec3> plg);
YSBOOL YsCheckPolygonSelfIntersection(YSSIZE_T np,const YsVec2 p[]);
YSBOOL YsCheckPolygonSelfIntersection(YSSIZE_T np,const YsVec3 p[],const YsVec3 &nom);
YSBOOL YsCheckPolygonSelfIntersection(YSSIZE_T np,const YsVec3 p[]);
/* } */
#endif
| [
"33561949+jw995@users.noreply.github.com"
] | 33561949+jw995@users.noreply.github.com |
d8917902e6ca3bf63892a68e82bb03860f96f0e9 | fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd | /ui/gfx/gpu_memory_buffer.h | 6d23c84ddc76074fc8bd5f13af1460e6b3c70531 | [
"BSD-3-Clause"
] | permissive | wzyy2/chromium-browser | 2644b0daf58f8b3caee8a6c09a2b448b2dfe059c | eb905f00a0f7e141e8d6c89be8fb26192a88c4b7 | refs/heads/master | 2022-11-23T20:25:08.120045 | 2018-01-16T06:41:26 | 2018-01-16T06:41:26 | 117,618,467 | 3 | 2 | BSD-3-Clause | 2022-11-20T22:03:57 | 2018-01-16T02:09:10 | null | UTF-8 | C++ | false | false | 3,802 | h | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_GFX_GPU_MEMORY_BUFFER_H_
#define UI_GFX_GPU_MEMORY_BUFFER_H_
#include <stddef.h>
#include <stdint.h>
#include "base/memory/shared_memory.h"
#include "base/trace_event/memory_allocator_dump_guid.h"
#include "build/build_config.h"
#include "ui/gfx/buffer_types.h"
#include "ui/gfx/generic_shared_memory_id.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/gfx_export.h"
#if defined(OS_LINUX)
#include "ui/gfx/native_pixmap_handle.h"
#elif defined(OS_MACOSX) && !defined(OS_IOS)
#include "ui/gfx/mac/io_surface.h"
#endif
extern "C" typedef struct _ClientBuffer* ClientBuffer;
namespace gfx {
class ColorSpace;
enum GpuMemoryBufferType {
EMPTY_BUFFER,
SHARED_MEMORY_BUFFER,
IO_SURFACE_BUFFER,
NATIVE_PIXMAP,
GPU_MEMORY_BUFFER_TYPE_LAST = NATIVE_PIXMAP
};
using GpuMemoryBufferId = GenericSharedMemoryId;
struct GFX_EXPORT GpuMemoryBufferHandle {
GpuMemoryBufferHandle();
GpuMemoryBufferHandle(const GpuMemoryBufferHandle& other);
~GpuMemoryBufferHandle();
bool is_null() const { return type == EMPTY_BUFFER; }
GpuMemoryBufferType type;
GpuMemoryBufferId id;
base::SharedMemoryHandle handle;
uint32_t offset;
int32_t stride;
#if defined(OS_LINUX)
NativePixmapHandle native_pixmap_handle;
#elif defined(OS_MACOSX) && !defined(OS_IOS)
ScopedRefCountedIOSurfaceMachPort mach_port;
#endif
};
// This interface typically correspond to a type of shared memory that is also
// shared with the GPU. A GPU memory buffer can be written to directly by
// regular CPU code, but can also be read by the GPU.
class GFX_EXPORT GpuMemoryBuffer {
public:
virtual ~GpuMemoryBuffer() {}
// Maps each plane of the buffer into the client's address space so it can be
// written to by the CPU. This call may block, for instance if the GPU needs
// to finish accessing the buffer or if CPU caches need to be synchronized.
// Returns false on failure.
virtual bool Map() = 0;
// Returns a pointer to the memory address of a plane. Buffer must have been
// successfully mapped using a call to Map() before calling this function.
virtual void* memory(size_t plane) = 0;
// Unmaps the buffer. It's illegal to use any pointer returned by memory()
// after this has been called.
virtual void Unmap() = 0;
// Returns the size for the buffer.
virtual Size GetSize() const = 0;
// Returns the format for the buffer.
virtual BufferFormat GetFormat() const = 0;
// Fills the stride in bytes for each plane of the buffer. The stride of
// plane K is stored at index K-1 of the |stride| array.
virtual int stride(size_t plane) const = 0;
// Set the color space in which this buffer should be interpreted when used
// for scanout. Note that this will not impact texturing from the buffer.
virtual void SetColorSpaceForScanout(const gfx::ColorSpace& color_space);
// Returns a unique identifier associated with buffer.
virtual GpuMemoryBufferId GetId() const = 0;
// Returns a platform specific handle for this buffer.
virtual GpuMemoryBufferHandle GetHandle() const = 0;
// Type-checking downcast routine.
virtual ClientBuffer AsClientBuffer() = 0;
// Returns the GUID for tracing.
virtual base::trace_event::MemoryAllocatorDumpGuid GetGUIDForTracing(
uint64_t tracing_process_id) const;
};
// Returns an instance of |handle| which can be sent over IPC. This duplicates
// the file-handles as appropriate, so that the IPC code take ownership of them,
// without invalidating |handle| itself.
GFX_EXPORT GpuMemoryBufferHandle
CloneHandleForIPC(const GpuMemoryBufferHandle& handle);
} // namespace gfx
#endif // UI_GFX_GPU_MEMORY_BUFFER_H_
| [
"jacob-chen@iotwrt.com"
] | jacob-chen@iotwrt.com |
48baa03f95030a46febe821fefb168856b159c42 | 1b541917c00dc1303089414bde0b1066912ee8c9 | /messages.h | 3a451f6f7370e670fcfed31eaa10f378d519b445 | [] | no_license | CatsSky/mLISP | 7d6f07caaa4baffd3fe426d8ea027d4ffcb025cb | dd911655c6144bfd9fec77178cd2ae886553cf7d | refs/heads/master | 2023-02-19T15:44:25.571945 | 2021-01-17T17:08:28 | 2021-01-17T17:08:28 | 323,868,375 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 186 | h | #ifndef MESSAGE_H
#define MESSAGE_H
void yyerror(const char* const s);
void error_argument(int expected, int got);
void error_undefined(const std::string& s);
void error_type();
#endif | [
"hank25521454@gmail.com"
] | hank25521454@gmail.com |
722825ba06f26b1cafe3c6262a4c58ca53754d6e | 73e4b5cb0db07f533c2c130c16bf7689beba5f51 | /xlw/xlw/xlw/InterfaceGenerator/FunctionModel.h | 5629b2151234af5f22c722d800595fb5c2d8df8c | [] | no_license | Laeeth/d_excelsdk | f054dbcb6ef9fd16916d72ea06c2b7d3a433db13 | 2fc993a89c6f620233fd29ea6daf233b1985b4e9 | refs/heads/master | 2021-01-17T08:58:37.477963 | 2016-04-14T01:03:31 | 2016-04-14T01:03:31 | 38,217,895 | 11 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 2,684 | h |
/*
Copyright (C) 2006 Mark Joshi
Copyright (C) 2007, 2008 Eric Ehlers
This file is part of XLW, a free-software/open-source C++ wrapper of the
Excel C API - http://xlw.sourceforge.net/
XLW is free software: you can redistribute it and/or modify it under the
terms of the XLW license. You should have received a copy of the
license along with this program; if not, please email xlw-users@lists.sf.net
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
#ifndef FUNCTION_MODEL_H
#define FUNCTION_MODEL_H
#include <vector>
#include <string>
class FunctionModel
{
public:
FunctionModel(std::string ReturnType_, std::string Name, std::string Description,
bool Volatile_=false, bool Time_=false, bool Threadsafe_=false,
std::string helpID_="",
bool asynchronous=false,bool macrosheet=false, bool clustersafe=false);
void AddArgument(std::string Type_, std::string Name_, std::string Description_);
size_t GetNumberArgs() const;
std::string GetReturnType() const
{
return ReturnType;
}
std::string GetFunctionName() const
{
return FunctionName;
}
std::string GetHelpID() const
{
return helpID;
}
std::string GetFunctionDescription() const
{
return FunctionDescription;
}
std::string GetArgumentReturnType(int i) const
{
return ArgumentTypes.at(i);
}
std::string GetArgumentFunctionName(int i) const
{
return ArgumentNames.at(i);
}
std::string GetArgumentFunctionDescription(int i) const
{
return ArgumentDescs.at(i);
}
bool GetVolatile() const
{
return Volatile;
}
bool DoTime() const
{
return Time;
}
void SetTime(bool doit)
{
Time=doit;
}
bool GetThreadsafe() const
{
return Threadsafe;
}
bool GetAsynchronous() const
{
return Asynchronous;
}
bool GetMacroSheet() const
{
return MacroSheet;
}
bool GetClusterSafe() const
{
return ClusterSafe;
}
private:
std::string ReturnType;
std::string FunctionName;
std::string FunctionDescription;
std::string helpID;
bool Volatile;
bool Time;
bool Threadsafe;
bool Asynchronous;
bool MacroSheet;
bool ClusterSafe;
std::vector<std::string > ArgumentTypes;
std::vector<std::string > ArgumentNames;
std::vector<std::string > ArgumentDescs;
};
#endif
| [
"laeeth@laeeth.com"
] | laeeth@laeeth.com |
d582461e232b9916acba5a5fff832b8ff45d4d5d | c319b3d26357e88aca78f752e391343d0eb43a3f | /src/client_driver.cc | 7d6e83e1796a7968ccb5aac17b1e6a48a0a72962 | [
"MIT"
] | permissive | goldonkey/foveated-360-video | 090c4506ecdf63d61f1dcaa75360c6d3063d11a7 | bd5cb585712cc67b20da1264430c33c8bc68cf49 | refs/heads/main | 2023-05-03T07:32:33.329922 | 2021-05-25T14:11:36 | 2021-05-25T14:11:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 354 | cc | #include <iostream>
#include <string>
#include "video_client.h"
int main(int argc, char* argv[]) {
std::vector<std::string> args(argv, argv + argc);
std::string uri = "ws://localhost:9562";
// uri = "ws://192.168.1.33:9562";
if (args.size() >= 2) {
uri = args[1];
}
VideoClient my_client(uri);
my_client.run();
return EXIT_SUCCESS;
} | [
"david@davidl.me"
] | david@davidl.me |
5b6391c35d104a898a004cfa72e83d5455ca6f35 | 684c9beb8bd972daeabe5278583195b9e652c0c5 | /src/starboard/raspi/shared/open_max/open_max_video_decode_component.h | 05df492d550b7781dbed5901a7afc7dbb6944373 | [
"Apache-2.0",
"BSD-3-Clause"
] | permissive | elgamar/cobalt-clone | a7d4e62630218f0d593fa74208456dd376059304 | 8a7c8792318a721e24f358c0403229570da8402b | refs/heads/master | 2022-11-27T11:30:31.314891 | 2018-10-26T15:54:41 | 2018-10-26T15:55:22 | 159,339,577 | 2 | 4 | null | 2022-11-17T01:03:37 | 2018-11-27T13:27:44 | C++ | UTF-8 | C++ | false | false | 1,979 | h | // Copyright 2016 The Cobalt Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef STARBOARD_RASPI_SHARED_OPEN_MAX_OPEN_MAX_VIDEO_DECODE_COMPONENT_H_
#define STARBOARD_RASPI_SHARED_OPEN_MAX_OPEN_MAX_VIDEO_DECODE_COMPONENT_H_
#include <map>
#include <queue>
#include "starboard/common/ref_counted.h"
#include "starboard/raspi/shared/dispmanx_util.h"
#include "starboard/raspi/shared/open_max/open_max_component.h"
namespace starboard {
namespace raspi {
namespace shared {
namespace open_max {
// Encapsulate a "OMX.broadcom.video_decode" component. Note that member
// functions of this class is expected to be called from ANY threads as this
// class works with the VideoDecoder filter, the OpenMAX component, and also
// manages the disposition of Dispmanx resource.
class OpenMaxVideoDecodeComponent : private OpenMaxComponent {
public:
using OpenMaxComponent::Start;
using OpenMaxComponent::Flush;
using OpenMaxComponent::WriteData;
using OpenMaxComponent::WriteEOS;
OpenMaxVideoDecodeComponent();
OMX_BUFFERHEADERTYPE* GetOutputBuffer();
void DropOutputBuffer(OMX_BUFFERHEADERTYPE* buffer);
private:
bool OnEnableOutputPort(OMXParamPortDefinition* port_definition) override;
OMXParamPortDefinition output_port_definition_;
};
} // namespace open_max
} // namespace shared
} // namespace raspi
} // namespace starboard
#endif // STARBOARD_RASPI_SHARED_OPEN_MAX_OPEN_MAX_VIDEO_DECODE_COMPONENT_H_
| [
"aabtop@google.com"
] | aabtop@google.com |
10a1e66d243834badc83a0bf9a33f7e350db27e2 | f0755c0ca52a0a278d75b76ee5d9b547d9668c0e | /atcoder.jp/abc121/abc121_b/Main.cpp | d052deab3db0c031bbbb7768935bdd0089df4872 | [] | no_license | nasama/procon | 7b70c9a67732d7d92775c40535fd54c0a5e91e25 | cd012065162650b8a5250a30a7acb1c853955b90 | refs/heads/master | 2022-07-28T12:37:21.113636 | 2020-05-19T14:11:30 | 2020-05-19T14:11:30 | 263,695,345 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 688 | cpp | #include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < (n); ++i)
#define rep2(i,n) for (int i = 1; i < (n); ++i)
using namespace std;
typedef long long ll;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int N, M, C;
cin >> N >> M >> C;
vector<int> B(M);
rep(i,M) cin >> B[i];
vector<vector<int>> A(N, vector<int>(M));
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
cin >> A[i][j];
}
}
int ans = 0;
rep(i,N) {
int sum = 0;
rep(j,M){
sum += A[i][j]*B[j];
}
sum += C;
if(sum > 0) ans++;
}
cout << ans << endl;
return 0;
}
| [
"g1620535@is.ocha.ac.jp"
] | g1620535@is.ocha.ac.jp |
ff60859aea21ccba5e57e067e040d107366f06a0 | 37f6c436ba092c5fc5f025e1cb84aef12e408c21 | /TemporalLookbackGame/KnightDemoApp.h | dbfd82123554b57739a07766201f11ee1afdb7c4 | [
"MIT"
] | permissive | dsamar/TemporalLookbackGame | db54134504e525ff2aebe9832a0f4e0b9955d82d | d0241f3b193052fb403a1ff2b6339337278c6732 | refs/heads/master | 2021-05-28T17:55:31.973898 | 2014-10-28T23:10:28 | 2014-10-28T23:10:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,612 | h | // *************************************************************************************************
//
// Horde3D
// Next-Generation Graphics Engine
//
// Sample Application
// --------------------------------------
// Copyright (C) 2006-2011 Nicolas Schulz
//
//
// This sample source file is not covered by the EPL as the rest of the SDK
// and may be used without any restrictions. However, the EPL's disclaimer of
// warranty and liability shall be in effect for this file.
//
// *************************************************************************************************
#ifndef _app_H_
#define _app_H_
#include "Horde3D.h"
#include <sstream>
#include <string>
class KnightDemoApp
{
public:
FACTORY_HOLDER(KnightDemoApp);
void setKeyState(int key, bool state) { _prevKeys[key] = _keys[key]; _keys[key] = state; }
const char *getTitle() { return "Knight - Horde3D Sample"; }
bool init();
void mainLoop(float fps);
void keyStateHandler();
void mouseMoveEvent(float dX, float dY);
private:
bool _keys[320], _prevKeys[320];
float _x, _y, _z, _rx, _ry; // Viewer position and orientation
float _velocity; // Velocity for movement
float _curFPS;
std::stringstream _text;
int _statMode;
int _freezeMode;
bool _debugViewMode, _wireframeMode;
float _animTime, _weight;
// Engine objects
H3DRes _fontMatRes, _panelMatRes;
H3DRes _logoMatRes;
H3DNode _knight, _particleSys;
std::string _contentDir;
};
#endif // _app_H_
| [
"samargiudan@gmail.com"
] | samargiudan@gmail.com |
0157fbe03e6230957c1854e89626cb84614137f1 | ecc970107f26e382b2e170c7201f7fa8b7d47050 | /2120/Lab4/lab04.cpp | 6653ffb4d3fa0eef86bc9661f4d8837420bdd286 | [] | no_license | OnyxKnight/Labs | 53315f93910072004561f1cf63eeeb6ce8d0cda5 | 5593e79f2da56de275858d0cae7d9e95bf6baebd | refs/heads/master | 2021-01-20T08:00:23.314252 | 2017-05-06T17:55:10 | 2017-05-06T17:55:10 | 90,075,679 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 806 | cpp | #include <iostream>
#include <string>
#include "List.h"
#include "Node.h"
using namespace std;
//Tests the functions in List.h
int main(){
List<int> list1;
list1.print("list1");
for(int i = 1, j = 1; i <= 10; i++){
j = -2 * j;
list1.insert(j);
list1.print("list1");
}
List<string> list2;
string s[] = {"Sisko", "Janeway", "Picard", "Kirk", "Zoey", "Frodo"};
for(int i = 0; i < 6; i++) {
list2.insert(s[i]);
list2.print("list2");
}
if(!list2.contains("Worf")){
cout << "Worf is not in list2 :(" << endl;
}
List<char> list3;
char c[] = {'z', 'p', 'r', 'p', 'd', 'a', 'h', 'q', 'o'};
for(int i = 0; i < 9; i++){
list3.insert(c[i]);
list3.print("list3");
}
if(list3.contains('r')){
cout << "r is in list3" << endl;
}
return 0;
}
| [
"noreply@github.com"
] | OnyxKnight.noreply@github.com |
a88ecbd1df1be050619a776bea62a2686462333b | d0fb46aecc3b69983e7f6244331a81dff42d9595 | /hiknoengine/include/alibabacloud/hiknoengine/model/TranslateTextRequest.h | c70cda36edae6828f6873ab921cb9745a503fa36 | [
"Apache-2.0"
] | permissive | aliyun/aliyun-openapi-cpp-sdk | 3d8d051d44ad00753a429817dd03957614c0c66a | e862bd03c844bcb7ccaa90571bceaa2802c7f135 | refs/heads/master | 2023-08-29T11:54:00.525102 | 2023-08-29T03:32:48 | 2023-08-29T03:32:48 | 115,379,460 | 104 | 82 | NOASSERTION | 2023-09-14T06:13:33 | 2017-12-26T02:53:27 | C++ | UTF-8 | C++ | false | false | 1,564 | h | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ALIBABACLOUD_HIKNOENGINE_MODEL_TRANSLATETEXTREQUEST_H_
#define ALIBABACLOUD_HIKNOENGINE_MODEL_TRANSLATETEXTREQUEST_H_
#include <string>
#include <vector>
#include <alibabacloud/core/RpcServiceRequest.h>
#include <alibabacloud/hiknoengine/HiknoengineExport.h>
namespace AlibabaCloud
{
namespace Hiknoengine
{
namespace Model
{
class ALIBABACLOUD_HIKNOENGINE_EXPORT TranslateTextRequest : public RpcServiceRequest
{
public:
TranslateTextRequest();
~TranslateTextRequest();
std::string getFromLang()const;
void setFromLang(const std::string& fromLang);
std::string getToLang()const;
void setToLang(const std::string& toLang);
std::string getText()const;
void setText(const std::string& text);
private:
std::string fromLang_;
std::string toLang_;
std::string text_;
};
}
}
}
#endif // !ALIBABACLOUD_HIKNOENGINE_MODEL_TRANSLATETEXTREQUEST_H_ | [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
97f2ac7c210e5cd4acf17cf7fb8a94b1ac1ee61b | f66fdee4f43241dd5a2491a92e4d85985f18b675 | /ExecuteStage.h | 32c532b92e8b106377b5bf4eaf5262d4906c007c | [] | no_license | freedzj/y86-Compiler | f221454c92bf94258407306795d13232b0db057a | a3589e00376ee078389db9adaa29d4e4c26e62c6 | refs/heads/master | 2020-05-02T08:14:58.041768 | 2019-03-26T17:36:41 | 2019-03-26T17:36:41 | 177,837,871 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,278 | h | class ExecuteStage: public Stage
{
private:
uint64_t e_dstE;
uint64_t e_valE;
bool M_bubble;
uint64_t Cnd;
void setMInput(M * mreg, uint64_t stat, uint64_t icode, uint64_t Cnd, uint64_t valE, uint64_t valA,
uint64_t dstE, uint64_t dstM);
uint64_t setaluA(uint64_t E_icode, uint64_t E_valA, uint64_t E_valC);
uint64_t setaluB(uint64_t E_icode, uint64_t E_valB);
uint64_t setalufun(uint64_t E_icode, uint64_t E_ifun);
bool setcc(uint64_t E_icode, Stage ** stages, W * wreg);
uint64_t setdstE(uint64_t E_icode, uint64_t e_Cnd, uint64_t E_dstE);
void setvalA(uint64_t icode, uint64_t & valA, uint64_t valC);
void setCC_component(uint64_t aluA, uint64_t aluB, uint64_t alufun, uint64_t aluoutput);
uint64_t doALU(uint64_t ifun, uint64_t aluA, uint64_t aluB);
uint64_t cond(uint64_t icode, uint64_t ifun);
bool ismStat(uint64_t m_stat);
bool iswStat(uint64_t W_stat);
bool calculateControlSignals(uint64_t m_stat, uint64_t W_stat);
public:
bool doClockLow(PipeReg ** pregs, Stage ** stages);
void doClockHigh(PipeReg ** pregs);
uint64_t gete_dstE();
uint64_t gete_valE();
uint64_t getCnd();
};
| [
"noreply@github.com"
] | freedzj.noreply@github.com |
e87417ff3b3bbf3356ac773eebd06c428a7ed9c4 | 34e7bf5c37d8401acc496c58a69936a912420c12 | /build-ParcialInfo-Desktop_Qt_5_9_1_MinGW_32bit-Debug/ui_entrada.h | ca5c7fad4feee87958b800d3a4b40e2ed002e2c1 | [] | no_license | davidmonsalvep/ExamenINFO2 | 9e6a2290e696f02908ccfb039b77f1f4bd94d9e3 | 0989fc2bf291053cbff8a2770cfa7828bf6c38f8 | refs/heads/master | 2022-06-21T04:58:57.249056 | 2020-05-15T07:37:41 | 2020-05-15T07:37:41 | 263,501,466 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,732 | h | /********************************************************************************
** Form generated from reading UI file 'entrada.ui'
**
** Created by: Qt User Interface Compiler version 5.9.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_ENTRADA_H
#define UI_ENTRADA_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_Entrada
{
public:
QLabel *fondo;
QPushButton *admon;
QPushButton *clientes;
QLineEdit *contra;
QLineEdit *nombre;
QLabel *labcpmtra;
QLabel *labnombre;
QLabel *labnombre_2;
QLineEdit *asiento;
QLabel *label;
QPushButton *pushButton_2;
void setupUi(QWidget *Entrada)
{
if (Entrada->objectName().isEmpty())
Entrada->setObjectName(QStringLiteral("Entrada"));
Entrada->resize(478, 334);
fondo = new QLabel(Entrada);
fondo->setObjectName(QStringLiteral("fondo"));
fondo->setGeometry(QRect(0, 0, 481, 331));
fondo->setPixmap(QPixmap(QString::fromUtf8(":/images.png")));
fondo->setScaledContents(true);
admon = new QPushButton(Entrada);
admon->setObjectName(QStringLiteral("admon"));
admon->setGeometry(QRect(110, 200, 81, 31));
clientes = new QPushButton(Entrada);
clientes->setObjectName(QStringLiteral("clientes"));
clientes->setGeometry(QRect(290, 200, 81, 31));
contra = new QLineEdit(Entrada);
contra->setObjectName(QStringLiteral("contra"));
contra->setGeometry(QRect(100, 140, 113, 20));
contra->setEchoMode(QLineEdit::Password);
nombre = new QLineEdit(Entrada);
nombre->setObjectName(QStringLiteral("nombre"));
nombre->setGeometry(QRect(270, 110, 113, 20));
labcpmtra = new QLabel(Entrada);
labcpmtra->setObjectName(QStringLiteral("labcpmtra"));
labcpmtra->setGeometry(QRect(70, 90, 161, 41));
labcpmtra->setTextFormat(Qt::AutoText);
labnombre = new QLabel(Entrada);
labnombre->setObjectName(QStringLiteral("labnombre"));
labnombre->setGeometry(QRect(270, 90, 121, 21));
labnombre_2 = new QLabel(Entrada);
labnombre_2->setObjectName(QStringLiteral("labnombre_2"));
labnombre_2->setGeometry(QRect(250, 140, 151, 21));
asiento = new QLineEdit(Entrada);
asiento->setObjectName(QStringLiteral("asiento"));
asiento->setGeometry(QRect(270, 160, 113, 20));
asiento->setEchoMode(QLineEdit::Normal);
label = new QLabel(Entrada);
label->setObjectName(QStringLiteral("label"));
label->setGeometry(QRect(160, 30, 181, 51));
pushButton_2 = new QPushButton(Entrada);
pushButton_2->setObjectName(QStringLiteral("pushButton_2"));
pushButton_2->setGeometry(QRect(400, 300, 71, 21));
retranslateUi(Entrada);
QMetaObject::connectSlotsByName(Entrada);
} // setupUi
void retranslateUi(QWidget *Entrada)
{
Entrada->setWindowTitle(QApplication::translate("Entrada", "Form", Q_NULLPTR));
fondo->setText(QString());
admon->setText(QApplication::translate("Entrada", "Administracion", Q_NULLPTR));
clientes->setText(QApplication::translate("Entrada", "Clientes", Q_NULLPTR));
labcpmtra->setText(QApplication::translate("Entrada", "<html><head/><body><p align=\"center\"><span style=\" font-size:10pt; font-weight:600; color:#ffff00;\">CONTRASE\303\221A DE ADMON</span></p></body></html>", Q_NULLPTR));
labnombre->setText(QApplication::translate("Entrada", "<html><head/><body><p align=\"center\"><span style=\" font-size:10pt; font-weight:600; color:#ffff00;\">NOMBRE CLIENTE</span></p></body></html>", Q_NULLPTR));
labnombre_2->setText(QApplication::translate("Entrada", "<html><head/><body><p align=\"center\"><span style=\" font-size:10pt; font-weight:600; color:#ffff00;\">NUMERO DE SU ASIENTO</span></p></body></html>", Q_NULLPTR));
label->setText(QApplication::translate("Entrada", "<html><head/><body><p><span style=\" font-size:14pt; font-weight:600; color:#ffff00;\">CINEMAS INFO II</span></p></body></html>", Q_NULLPTR));
pushButton_2->setText(QApplication::translate("Entrada", "Cinemas", Q_NULLPTR));
} // retranslateUi
};
namespace Ui {
class Entrada: public Ui_Entrada {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_ENTRADA_H
| [
"whatshappcolega@gmail.com"
] | whatshappcolega@gmail.com |
cda344cb1144996f8eccd84f20c8343cfc66f99c | 8ff320e31e8ad83c75c93cd8f71347a38e718e71 | /src/lib/views/models/libraryModel/tagItem.cpp | d72c4e98b282db0f3da04b08cddd8be945718731 | [] | no_license | tavu/karakaxa | 60ff6e3e79196f5a3e079c5dc1cc1c430d9ff1be | 03f3df0f22a6a001438589d72c42c34a3f3dd519 | refs/heads/master | 2021-01-01T18:22:49.392260 | 2013-09-04T13:42:02 | 2013-09-04T13:42:02 | 4,357,814 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,041 | cpp | #include"tagItem.h"
#include "tagItemHead.h"
#include<Basic/tagsTable.h>
#include "trackItem.h"
#include "headerItem.h"
#include<files/tagInfo.h>
#include<database/queries/queryTypes.h>
#include<database/queries/provider/queryProvider.h>
#include<database/queries/matchQuery.h>
#include<database/queries/tagQuery.h>
views::tagItem::tagItem(audioFiles::tagInfo &info) :standardItem(),_info(info)
{
_sort=-1;
_sortOrder=Qt::AscendingOrder;
}
views::tagItem::tagItem() :standardItem()
{
_sort=-1;
_sortOrder=Qt::AscendingOrder;
}
views::tagItem::~tagItem()
{
clear();
}
void views::tagItem::sort(int column, Qt::SortOrder order)
{
// _sort=headItem()->headerData(column,Qt::Horizontal,TAG_ROLE).toInt();
_sort=column;
_sortOrder=order;
if(rowCount()==0)
return;
int d=nextData();
if(d==Basic::FILES && rowCount()!=0)
{
clear();
populate();
}
else
{
foreach(standardItem *item, children)
{
item->sort(column,order);
}
}
}
bool views::tagItem::canFetchMore() const
{
if(rowCount()!=0)
{
return false;
}
int t=nextData();
if(t==Basic::INVALID)
{
return false;
}
return true;
}
void views::tagItem::fetchMore()
{
if(rowCount()!=0)
{
return ;
}
populate();
//
// appendData(t);
}
bool views::tagItem::populate()
{
int type=nextData();
if(type==Basic::INVALID)
{
return false;
}
if(type<0||type>Basic::FILES)
{
qDebug()<<"invalid type:"<<type;
return false;
}
database::queryProvider *pr=new database::queryProvider(type);
database::abstractQuery *f=filter();
/*
tagItem* parent=parentItem();
if(parent!=0)
{
f=parent->filter();
}
else
{
//this is the head item
f=filter();
}
*/
int sort;
if(type==Basic::FILES)
{
sort=headItem()->headerData(_sort,Qt::Horizontal,TAG_ROLE).toInt();
if(sort==Basic::INVALID)
{
sort=Basic::TRACK;
}
}
else
{
sort=type;
}
if(pr->select(f,sort,_sortOrder) !=Basic::OK )
{
qDebug()<<"query data provider returned false";
qDebug()<<pr->lastErrorStr();
delete pr;
return false;
}
QList<audioFiles::tagInfo> results=pr->results();
QList<standardItem*>l;
foreach(audioFiles::tagInfo info,results)
{
l<<newItemInstance(info);
}
insertRows(0,l);
_isDirty=false;
return true;
}
views::tagItem* views::tagItem::parentItem() const
{
return dynamic_cast<tagItem*>(QObject::parent() );
}
database::abstractQuery* views::tagItem::filter() const
{
tagItem *parent=parentItem();
database::abstractQuery *parentQ=0;
if(parent!=0)
{
parentQ=parent->filter();
}
database::matchQuery *match=new database::matchQuery(database::AND);
if(parentQ!=0)
{
match->append(parentQ);
}
if(_info.type()!=Basic::INVALID && _info.type()!=Basic::FILES )
{
database::abstractQuery *q;
q=new database::tagQuery( _info.type(),database::EQUAL,_info.data() );
match->append(q);
}
return match;
}
int views::tagItem::columnCount() const
{
return 1;
}
QVariant views::tagItem::data(int column, int role) const
{
if(role==TAG_ROLE)
{
if(column==0)
{
return QVariant(_info.type());
}
else
{
return QVariant(Basic::INVALID);
}
}
if(role==ID_ROLE)
{
return QVariant(_info.property(Basic::ID) );
}
if(column!=0)
{
return QVariant();
}
if(role==Qt::DisplayRole)
{
return views::pretyTag(_info.data(),_info.type() );
}
if(role==Qt::DecorationRole)
{
QString s=_info.property(Basic::IMAGE).toString();
if(!s.isEmpty())
{
return QPixmap(s);
}
return views::decor->tagIcon(_info.type());
}
return QVariant();
}
int views::tagItem::nextData() const
{
tagItemHead *head=static_cast<tagItemHead*>(headItem());
if(head->tagList().size() <= depth() +1 )
{
return Basic::INVALID;
}
return head->tagList().value(depth()+1 );
}
void views::tagItem::update()
{
clear();
fetchMore();
}
standardItem* views::tagItem::newItemInstance(audioFiles::tagInfo &info)
{
if(info.type()==Basic::FILES)
{
return new trackItem(info);
}
else
{
return new tagItem(info);
}
}
Qt::ItemFlags views::tagItem::flags(int column) const
{
return standardItem::flags(column)& ~Qt::ItemIsEditable;
}
void views::tagItem::insert(int row, standardItem* item)
{
standardItem::insert(row, item);
item->sort(_sort,_sortOrder);
}
| [
"tavu@linux-t06i.site"
] | tavu@linux-t06i.site |
39169aebedc6b92a1559b6d116f06bc82987dc54 | e7f40e3d6bf4419834db479b913bab26cd7f429a | /SaverLoader.h | 860a6d54389b9cc586f11ca0f78a62f03c605999 | [] | no_license | PeterUherek/TicTacToe | 138ed380702640fd0a22cedbcf30f6eefea6a5eb | e0cfc0ce35084bfd85c2221e7242f7140a951ccf | refs/heads/master | 2021-01-17T21:09:22.504931 | 2016-08-18T08:58:23 | 2016-08-18T08:58:23 | 64,935,854 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 269 | h | #pragma once
#include <boost/shared_ptr.hpp>
#include "game.pb.h"
class SaverLoader
{
public:
SaverLoader();
~SaverLoader();
static bool existFile(const std::string& name);
static const std::string saveFile;
protected:
boost::shared_ptr<game::Game> nGame;
};
| [
"peteruherek@gmail.com"
] | peteruherek@gmail.com |
fc4b6dcacd84893734d4881212caf87387b65241 | 42612848041c4f6809976f125056672f214c1afe | /FYP_matrix/google-api/google/genomics/v1alpha2/pipelines.grpc.pb.cc | 3ccba334eb5066c033b289e7522c311ec0cb84f8 | [] | no_license | Chen-Zhe/FYP_matrix | abc64a71dd730de35afe1a03c86a6771ccf7de07 | a791320d8fcd14c983db4db1422772ed69ad6089 | refs/heads/master | 2021-01-12T17:14:16.290658 | 2017-05-07T12:24:43 | 2017-05-07T12:24:43 | 69,989,506 | 3 | 2 | null | 2016-12-06T16:29:18 | 2016-10-04T17:36:17 | C++ | UTF-8 | C++ | false | true | 12,423 | cc | // Generated by the gRPC protobuf plugin.
// If you make any local change, they will be lost.
// source: google/genomics/v1alpha2/pipelines.proto
#include "google/genomics/v1alpha2/pipelines.pb.h"
#include "google/genomics/v1alpha2/pipelines.grpc.pb.h"
#include <grpc++/impl/codegen/async_stream.h>
#include <grpc++/impl/codegen/async_unary_call.h>
#include <grpc++/impl/codegen/channel_interface.h>
#include <grpc++/impl/codegen/client_unary_call.h>
#include <grpc++/impl/codegen/method_handler_impl.h>
#include <grpc++/impl/codegen/rpc_service_method.h>
#include <grpc++/impl/codegen/service_type.h>
#include <grpc++/impl/codegen/sync_stream.h>
namespace google {
namespace genomics {
namespace v1alpha2 {
static const char* PipelinesV1Alpha2_method_names[] = {
"/google.genomics.v1alpha2.PipelinesV1Alpha2/CreatePipeline",
"/google.genomics.v1alpha2.PipelinesV1Alpha2/RunPipeline",
"/google.genomics.v1alpha2.PipelinesV1Alpha2/GetPipeline",
"/google.genomics.v1alpha2.PipelinesV1Alpha2/ListPipelines",
"/google.genomics.v1alpha2.PipelinesV1Alpha2/DeletePipeline",
"/google.genomics.v1alpha2.PipelinesV1Alpha2/GetControllerConfig",
"/google.genomics.v1alpha2.PipelinesV1Alpha2/SetOperationStatus",
};
std::unique_ptr< PipelinesV1Alpha2::Stub> PipelinesV1Alpha2::NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options) {
std::unique_ptr< PipelinesV1Alpha2::Stub> stub(new PipelinesV1Alpha2::Stub(channel));
return stub;
}
PipelinesV1Alpha2::Stub::Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel)
: channel_(channel), rpcmethod_CreatePipeline_(PipelinesV1Alpha2_method_names[0], ::grpc::RpcMethod::NORMAL_RPC, channel)
, rpcmethod_RunPipeline_(PipelinesV1Alpha2_method_names[1], ::grpc::RpcMethod::NORMAL_RPC, channel)
, rpcmethod_GetPipeline_(PipelinesV1Alpha2_method_names[2], ::grpc::RpcMethod::NORMAL_RPC, channel)
, rpcmethod_ListPipelines_(PipelinesV1Alpha2_method_names[3], ::grpc::RpcMethod::NORMAL_RPC, channel)
, rpcmethod_DeletePipeline_(PipelinesV1Alpha2_method_names[4], ::grpc::RpcMethod::NORMAL_RPC, channel)
, rpcmethod_GetControllerConfig_(PipelinesV1Alpha2_method_names[5], ::grpc::RpcMethod::NORMAL_RPC, channel)
, rpcmethod_SetOperationStatus_(PipelinesV1Alpha2_method_names[6], ::grpc::RpcMethod::NORMAL_RPC, channel)
{}
::grpc::Status PipelinesV1Alpha2::Stub::CreatePipeline(::grpc::ClientContext* context, const ::google::genomics::v1alpha2::CreatePipelineRequest& request, ::google::genomics::v1alpha2::Pipeline* response) {
return ::grpc::BlockingUnaryCall(channel_.get(), rpcmethod_CreatePipeline_, context, request, response);
}
::grpc::ClientAsyncResponseReader< ::google::genomics::v1alpha2::Pipeline>* PipelinesV1Alpha2::Stub::AsyncCreatePipelineRaw(::grpc::ClientContext* context, const ::google::genomics::v1alpha2::CreatePipelineRequest& request, ::grpc::CompletionQueue* cq) {
return new ::grpc::ClientAsyncResponseReader< ::google::genomics::v1alpha2::Pipeline>(channel_.get(), cq, rpcmethod_CreatePipeline_, context, request);
}
::grpc::Status PipelinesV1Alpha2::Stub::RunPipeline(::grpc::ClientContext* context, const ::google::genomics::v1alpha2::RunPipelineRequest& request, ::google::longrunning::Operation* response) {
return ::grpc::BlockingUnaryCall(channel_.get(), rpcmethod_RunPipeline_, context, request, response);
}
::grpc::ClientAsyncResponseReader< ::google::longrunning::Operation>* PipelinesV1Alpha2::Stub::AsyncRunPipelineRaw(::grpc::ClientContext* context, const ::google::genomics::v1alpha2::RunPipelineRequest& request, ::grpc::CompletionQueue* cq) {
return new ::grpc::ClientAsyncResponseReader< ::google::longrunning::Operation>(channel_.get(), cq, rpcmethod_RunPipeline_, context, request);
}
::grpc::Status PipelinesV1Alpha2::Stub::GetPipeline(::grpc::ClientContext* context, const ::google::genomics::v1alpha2::GetPipelineRequest& request, ::google::genomics::v1alpha2::Pipeline* response) {
return ::grpc::BlockingUnaryCall(channel_.get(), rpcmethod_GetPipeline_, context, request, response);
}
::grpc::ClientAsyncResponseReader< ::google::genomics::v1alpha2::Pipeline>* PipelinesV1Alpha2::Stub::AsyncGetPipelineRaw(::grpc::ClientContext* context, const ::google::genomics::v1alpha2::GetPipelineRequest& request, ::grpc::CompletionQueue* cq) {
return new ::grpc::ClientAsyncResponseReader< ::google::genomics::v1alpha2::Pipeline>(channel_.get(), cq, rpcmethod_GetPipeline_, context, request);
}
::grpc::Status PipelinesV1Alpha2::Stub::ListPipelines(::grpc::ClientContext* context, const ::google::genomics::v1alpha2::ListPipelinesRequest& request, ::google::genomics::v1alpha2::ListPipelinesResponse* response) {
return ::grpc::BlockingUnaryCall(channel_.get(), rpcmethod_ListPipelines_, context, request, response);
}
::grpc::ClientAsyncResponseReader< ::google::genomics::v1alpha2::ListPipelinesResponse>* PipelinesV1Alpha2::Stub::AsyncListPipelinesRaw(::grpc::ClientContext* context, const ::google::genomics::v1alpha2::ListPipelinesRequest& request, ::grpc::CompletionQueue* cq) {
return new ::grpc::ClientAsyncResponseReader< ::google::genomics::v1alpha2::ListPipelinesResponse>(channel_.get(), cq, rpcmethod_ListPipelines_, context, request);
}
::grpc::Status PipelinesV1Alpha2::Stub::DeletePipeline(::grpc::ClientContext* context, const ::google::genomics::v1alpha2::DeletePipelineRequest& request, ::google::protobuf::Empty* response) {
return ::grpc::BlockingUnaryCall(channel_.get(), rpcmethod_DeletePipeline_, context, request, response);
}
::grpc::ClientAsyncResponseReader< ::google::protobuf::Empty>* PipelinesV1Alpha2::Stub::AsyncDeletePipelineRaw(::grpc::ClientContext* context, const ::google::genomics::v1alpha2::DeletePipelineRequest& request, ::grpc::CompletionQueue* cq) {
return new ::grpc::ClientAsyncResponseReader< ::google::protobuf::Empty>(channel_.get(), cq, rpcmethod_DeletePipeline_, context, request);
}
::grpc::Status PipelinesV1Alpha2::Stub::GetControllerConfig(::grpc::ClientContext* context, const ::google::genomics::v1alpha2::GetControllerConfigRequest& request, ::google::genomics::v1alpha2::ControllerConfig* response) {
return ::grpc::BlockingUnaryCall(channel_.get(), rpcmethod_GetControllerConfig_, context, request, response);
}
::grpc::ClientAsyncResponseReader< ::google::genomics::v1alpha2::ControllerConfig>* PipelinesV1Alpha2::Stub::AsyncGetControllerConfigRaw(::grpc::ClientContext* context, const ::google::genomics::v1alpha2::GetControllerConfigRequest& request, ::grpc::CompletionQueue* cq) {
return new ::grpc::ClientAsyncResponseReader< ::google::genomics::v1alpha2::ControllerConfig>(channel_.get(), cq, rpcmethod_GetControllerConfig_, context, request);
}
::grpc::Status PipelinesV1Alpha2::Stub::SetOperationStatus(::grpc::ClientContext* context, const ::google::genomics::v1alpha2::SetOperationStatusRequest& request, ::google::protobuf::Empty* response) {
return ::grpc::BlockingUnaryCall(channel_.get(), rpcmethod_SetOperationStatus_, context, request, response);
}
::grpc::ClientAsyncResponseReader< ::google::protobuf::Empty>* PipelinesV1Alpha2::Stub::AsyncSetOperationStatusRaw(::grpc::ClientContext* context, const ::google::genomics::v1alpha2::SetOperationStatusRequest& request, ::grpc::CompletionQueue* cq) {
return new ::grpc::ClientAsyncResponseReader< ::google::protobuf::Empty>(channel_.get(), cq, rpcmethod_SetOperationStatus_, context, request);
}
PipelinesV1Alpha2::Service::Service() {
(void)PipelinesV1Alpha2_method_names;
AddMethod(new ::grpc::RpcServiceMethod(
PipelinesV1Alpha2_method_names[0],
::grpc::RpcMethod::NORMAL_RPC,
new ::grpc::RpcMethodHandler< PipelinesV1Alpha2::Service, ::google::genomics::v1alpha2::CreatePipelineRequest, ::google::genomics::v1alpha2::Pipeline>(
std::mem_fn(&PipelinesV1Alpha2::Service::CreatePipeline), this)));
AddMethod(new ::grpc::RpcServiceMethod(
PipelinesV1Alpha2_method_names[1],
::grpc::RpcMethod::NORMAL_RPC,
new ::grpc::RpcMethodHandler< PipelinesV1Alpha2::Service, ::google::genomics::v1alpha2::RunPipelineRequest, ::google::longrunning::Operation>(
std::mem_fn(&PipelinesV1Alpha2::Service::RunPipeline), this)));
AddMethod(new ::grpc::RpcServiceMethod(
PipelinesV1Alpha2_method_names[2],
::grpc::RpcMethod::NORMAL_RPC,
new ::grpc::RpcMethodHandler< PipelinesV1Alpha2::Service, ::google::genomics::v1alpha2::GetPipelineRequest, ::google::genomics::v1alpha2::Pipeline>(
std::mem_fn(&PipelinesV1Alpha2::Service::GetPipeline), this)));
AddMethod(new ::grpc::RpcServiceMethod(
PipelinesV1Alpha2_method_names[3],
::grpc::RpcMethod::NORMAL_RPC,
new ::grpc::RpcMethodHandler< PipelinesV1Alpha2::Service, ::google::genomics::v1alpha2::ListPipelinesRequest, ::google::genomics::v1alpha2::ListPipelinesResponse>(
std::mem_fn(&PipelinesV1Alpha2::Service::ListPipelines), this)));
AddMethod(new ::grpc::RpcServiceMethod(
PipelinesV1Alpha2_method_names[4],
::grpc::RpcMethod::NORMAL_RPC,
new ::grpc::RpcMethodHandler< PipelinesV1Alpha2::Service, ::google::genomics::v1alpha2::DeletePipelineRequest, ::google::protobuf::Empty>(
std::mem_fn(&PipelinesV1Alpha2::Service::DeletePipeline), this)));
AddMethod(new ::grpc::RpcServiceMethod(
PipelinesV1Alpha2_method_names[5],
::grpc::RpcMethod::NORMAL_RPC,
new ::grpc::RpcMethodHandler< PipelinesV1Alpha2::Service, ::google::genomics::v1alpha2::GetControllerConfigRequest, ::google::genomics::v1alpha2::ControllerConfig>(
std::mem_fn(&PipelinesV1Alpha2::Service::GetControllerConfig), this)));
AddMethod(new ::grpc::RpcServiceMethod(
PipelinesV1Alpha2_method_names[6],
::grpc::RpcMethod::NORMAL_RPC,
new ::grpc::RpcMethodHandler< PipelinesV1Alpha2::Service, ::google::genomics::v1alpha2::SetOperationStatusRequest, ::google::protobuf::Empty>(
std::mem_fn(&PipelinesV1Alpha2::Service::SetOperationStatus), this)));
}
PipelinesV1Alpha2::Service::~Service() {
}
::grpc::Status PipelinesV1Alpha2::Service::CreatePipeline(::grpc::ServerContext* context, const ::google::genomics::v1alpha2::CreatePipelineRequest* request, ::google::genomics::v1alpha2::Pipeline* response) {
(void) context;
(void) request;
(void) response;
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
::grpc::Status PipelinesV1Alpha2::Service::RunPipeline(::grpc::ServerContext* context, const ::google::genomics::v1alpha2::RunPipelineRequest* request, ::google::longrunning::Operation* response) {
(void) context;
(void) request;
(void) response;
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
::grpc::Status PipelinesV1Alpha2::Service::GetPipeline(::grpc::ServerContext* context, const ::google::genomics::v1alpha2::GetPipelineRequest* request, ::google::genomics::v1alpha2::Pipeline* response) {
(void) context;
(void) request;
(void) response;
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
::grpc::Status PipelinesV1Alpha2::Service::ListPipelines(::grpc::ServerContext* context, const ::google::genomics::v1alpha2::ListPipelinesRequest* request, ::google::genomics::v1alpha2::ListPipelinesResponse* response) {
(void) context;
(void) request;
(void) response;
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
::grpc::Status PipelinesV1Alpha2::Service::DeletePipeline(::grpc::ServerContext* context, const ::google::genomics::v1alpha2::DeletePipelineRequest* request, ::google::protobuf::Empty* response) {
(void) context;
(void) request;
(void) response;
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
::grpc::Status PipelinesV1Alpha2::Service::GetControllerConfig(::grpc::ServerContext* context, const ::google::genomics::v1alpha2::GetControllerConfigRequest* request, ::google::genomics::v1alpha2::ControllerConfig* response) {
(void) context;
(void) request;
(void) response;
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
::grpc::Status PipelinesV1Alpha2::Service::SetOperationStatus(::grpc::ServerContext* context, const ::google::genomics::v1alpha2::SetOperationStatusRequest* request, ::google::protobuf::Empty* response) {
(void) context;
(void) request;
(void) response;
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
} // namespace google
} // namespace genomics
} // namespace v1alpha2
| [
"chenzhesg@gmail.com"
] | chenzhesg@gmail.com |
bd73181dd611cdd04ad2e3521e7129c097fecf26 | 17b772300ca681e99625e5f0149a7f00f6d15f2c | /Zoo_Managment_System/main.cpp | b8975afb945a357f24c8cffdb40cdbea2c323f66 | [] | no_license | ZoharBergman/C-second-part | 357d41848579f1742297152d98a135a62e19ba02 | e562a94bbb6ecea8260220e16ea347015bc5cb8b | refs/heads/master | 2021-07-11T05:38:51.434583 | 2017-10-14T19:06:35 | 2017-10-14T19:06:35 | 104,094,602 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 7,221 | cpp | //
// main.cpp
// Zoo_Management_System
//
// Created by Almog Segal on 01/08/2017.
// Copyright © 2017 Almog Segal. All rights reserved.
//
#pragma warning( disable : 4290 )
#include <iostream>
#include "Zoo.h"
#include "AreaManager.h"
#include "Veterinarian.h"
#include "Keeper.h"
#include "MaintenanceWorker.h"
#include "Elephant.h"
#include "Giraffe.h"
#include "Horse.h"
#include "Lion.h"
#include "Penguin.h"
#include "Zebra.h"
#include "Zebroid.h"
using namespace std;
AreaManager** createAreaManagers(int& numOfManagers);
Area** createAllAreas(AreaManager **managers, int& numOfAreas);
void addAreasToZoo(Zoo& zoo, Area** areas, int& numOfAreas);
Animal** createAnimals(int& numOfAnimals);
void addAllAnimalsToZoo(Zoo& myZoo, Animal** animals, int &numOfAnimals);
Keeper** createAllKeepers(int& numOfKeepers);
void addKeepersToZoo(Zoo& myZoo, Keeper** keepers, int numOfKeepers);
Veterinarian** createAllVeterinarian(int& numOfVeterinarian);
void addAllVeterinarianToZoo(Zoo& myZoo, Veterinarian**vets, int numOfVeterinarian);
void freeAllAreaManagers(AreaManager** areaManagers, int& numOfAreaManagers);
void freeAllAreas(Area** areas, int& numOfAreas);
void freeAllAnimals(Animal** animals, int& numOfAnimals);
void freeAllVeterinarian(Veterinarian** vets, int& numOfVeterinarian);
void freeAllKeepers(Keeper** keepers, int& numOfKeepers);
int main(int argc, const char * argv[]) {
Zoo myZoo("My Zoo", 10);
int numOfManagers, numOfAreas, numOfKeepers, numOfVeterinarian, numOfAnimals;
AreaManager** managers;
Area** areas;
Keeper** keepers;
Veterinarian** vets;
Animal** animals;
try
{
managers = createAreaManagers(numOfManagers);
areas = createAllAreas(managers, numOfAreas);
// add all areas
addAreasToZoo(myZoo, areas, numOfAreas);
animals = createAnimals(numOfAnimals);
// add animals
addAllAnimalsToZoo(myZoo, animals, numOfAnimals);
keepers = createAllKeepers(numOfKeepers);
// add all the keepers
addKeepersToZoo(myZoo, keepers, numOfKeepers);
vets = createAllVeterinarian(numOfVeterinarian);
// add all vets
addAllVeterinarianToZoo(myZoo, vets, numOfVeterinarian);
// print the whole zoo
cout << myZoo << endl;
cout << "=================================================================" << endl;
Area* a1 = myZoo.getAllAreas()[0];
Area* a2 = myZoo.getAllAreas()[1];
cout << "Area A1 before remove animal" << endl;
cout << *a1 << endl << endl;
a1->removeAnimal(animals[0]);
cout << "Area A1 after remove animal" << endl;
cout << *a1 << endl << endl;
cout << "Is area A1 smaller than area A2? ";
cout << ((*a1 < *a2 == true) ? "YES" : "NO") << endl << endl;
cout << "Fire the area manager of area A1" << endl;
a1->setAreaManager(nullptr);
cout << *a1 << endl << endl;
cout << "Try to print the area of the fired area manager" << endl;
cout << managers[0]->getArea() << endl << endl;
cout << "Area A2" << endl;
cout << *a2 << endl << endl;
cout << "Setting the area manager of A2 to be the area manager of A1" << endl;
a1->setAreaManager(a2->getAreaManager());
cout << *a1 << endl << endl;
cout << "Setting the fired area manager of area A1 to be the area manager of A2" << endl;
a2->setAreaManager(managers[0]);
cout << *a2 << endl << endl;
a1->removeWorker(vets[0]);
cout << "Area A1 after remove vet" << endl;
cout << *a1 << endl << endl;
cout << "Try to remove the vet again" << endl;
a1->removeWorker(vets[0]);
// free all memory
freeAllAnimals(animals, numOfAnimals);
freeAllAreaManagers(managers, numOfManagers);
freeAllAreas(areas, numOfAreas);
freeAllKeepers(keepers, numOfKeepers);
freeAllVeterinarian(vets, numOfVeterinarian);
}
catch (const char* e)
{
cout << e;
// free all memory
freeAllAnimals(animals, numOfAnimals);
freeAllAreaManagers(managers, numOfManagers);
freeAllAreas(areas, numOfAreas);
freeAllKeepers(keepers, numOfKeepers);
freeAllVeterinarian(vets, numOfVeterinarian);
}
return 0;
}
AreaManager** createAreaManagers(int& numOfManagers)
{
numOfManagers = 3;
AreaManager** managers = new AreaManager*[numOfManagers];
managers[0] = new AreaManager("Yogev", 5000);
managers[1] = new AreaManager("Moshe", 4500);
managers[2] = new AreaManager("Roie", 4800);
return managers;
}
Area** createAllAreas(AreaManager **managers, int& numOfAreas)
{
numOfAreas = 3;
Area** areas = new Area*[numOfAreas];
areas[0] = new Area("A1", 4, 4, managers[0]);
areas[1] = new Area("A2", 4, 4, managers[1]);
areas[2] = new Area("A3", 4, 4, managers[2]);
return areas;
}
void addAreasToZoo(Zoo& zoo, Area** areas, int& numOfAreas)
{
for (int i = 0; i < numOfAreas; i++)
{
//zoo.addArea(*areas[i]);
zoo += *areas[i];
}
}
Animal** createAnimals(int& numOfAnimals)
{
numOfAnimals = 4;
Animal** animals = new Animal*[numOfAnimals];
animals[0] = new Horse("Horsy", 208.5f, 1998, 40.2f);
animals[1] = new Penguin("Pini", 1.2f, 2005, Penguin::eSeaFood::CRAB);
animals[2] = new Elephant("Eli", 2.5f, 2003, 1.35f, 2.75f);
animals[3] = new Zebroid("Zeze", 1.45f, 2010, 128, 38.6f);
return animals;
}
void addAllAnimalsToZoo(Zoo& myZoo, Animal** animals, int &numOfAnimals)
{
for (int i = 0; i < numOfAnimals - 1; i++)
{
myZoo.addAnimal(*animals[i], myZoo.getAllAreas()[i]->getName());
}
// another animal to the last area
myZoo.addAnimal(*animals[3], myZoo.getAllAreas()[2]->getName());
}
Keeper** createAllKeepers(int& numOfKeepers)
{
numOfKeepers = 3;
Keeper** keepers = new Keeper*[numOfKeepers];
keepers[0] = new Keeper("Kipi", 7500, Keeper::eAnimal::PENGUIN);
keepers[1] = new Keeper("Keepi", 7500, Keeper::eAnimal::ELEPHANT);
keepers[2] = new Keeper("Keepee", 7500, Keeper::eAnimal::HORSE);
return keepers;
}
void addKeepersToZoo(Zoo& myZoo, Keeper** keepers, int numOfKeepers)
{
for (int i = 0; i < numOfKeepers; i++)
{
myZoo.addWorker(*keepers[i], myZoo.getAllAreas()[i]->getName());
}
}
Veterinarian** createAllVeterinarian(int& numOfVeterinarian)
{
numOfVeterinarian = 3;
Veterinarian** vets = new Veterinarian*[numOfVeterinarian];
vets[0] = new Veterinarian("Vivi", 10000, 5);
vets[1] = new Veterinarian("Vuvu", 10000, 8);
vets[2] = new Veterinarian("Kobi", 10000, 10);
return vets;
}
void addAllVeterinarianToZoo(Zoo& myZoo, Veterinarian**vets, int numOfVeterinarian)
{
for (int i = 0; i < numOfVeterinarian; i++)
{
myZoo.addWorker(*vets[i], myZoo.getAllAreas()[i]->getName());
}
}
void freeAllAreaManagers(AreaManager** areaManagers, int& numOfAreaManagers)
{
for (int i = 0; i < numOfAreaManagers; i++)
{
delete areaManagers[i];
}
delete[]areaManagers;
}
void freeAllAreas(Area** areas, int& numOfAreas)
{
for (int i = 0; i < numOfAreas; i++)
{
delete areas[i];
}
delete[]areas;
}
void freeAllAnimals(Animal** animals, int& numOfAnimals)
{
for (int i = 0; i < numOfAnimals; i++)
{
delete animals[i];
}
delete[]animals;
}
void freeAllVeterinarian(Veterinarian** vets, int& numOfVeterinarian)
{
for (int i = 0; i < numOfVeterinarian; i++)
{
delete vets[i];
}
delete[]vets;
}
void freeAllKeepers(Keeper** keepers, int& numOfKeepers)
{
for (int i = 0; i < numOfKeepers; i++)
{
delete keepers[i];
}
delete[]keepers;
} | [
"zohar.bergman@gmail.com"
] | zohar.bergman@gmail.com |
fe2906a83e1a15ea2bd3a981a8764ea35bd15680 | 3e27864309375d72adaf3d31c678f8066b536484 | /uline.h | 08359df42d105a6b361df40c3a87a57113ed3f61 | [] | no_license | Uking33/180622-QT-OilManageSystem | c83ca4a9a8f6865d6329dc3a8a70fcb0bb14a42a | 979c9fd5fbd849c3baaea5ccf2d0ec3b9aa41ef1 | refs/heads/main | 2023-04-13T21:44:56.319947 | 2021-04-23T05:55:05 | 2021-04-23T05:55:05 | 360,778,133 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,075 | h | #ifndef ULINE_H
#define ULINE_H
//窗口
#include <QHBoxLayout>
class QGridLayout;
//控件
class QLineEdit;
class QLabel;
class ULine:public QHBoxLayout{
Q_OBJECT
public:
ULine(const QString& text, const QString hitText="", int widthLabel=80, int heightLabel=25, int widthEdit=200, int heightEdit=25);
~ULine();
//值
void SetLabel(const QString& text);
void SetValue(const QString& value);
void SetValue(const int value);
void SetValue(const float value);
void SetValidator(QString rect);
QString GetValue();
void ReValue();
//设置
void SetReadOnly(bool isRead);
void SetFocus();
void SetDouble(int aft, int max, int min=0);//只能设置一次
void SetInt(int max, int min=0);//只能设置一次
void SetMaxLength(int count);//只能设置一次
void SetDoubleNotype(int aft, int max, int min=0);
void SetIntNotype(int max, int min=0);
void SetMaxLengthNotype(int count);
QLabel *m_label;
QLineEdit *m_edit;
int m_type;
signals:
void textEdited();
};
#endif // ULINE_H
| [
"60296340+Uking33@users.noreply.github.com"
] | 60296340+Uking33@users.noreply.github.com |
5a63f712abcaa27347fb49699ad7c71e0799e0a9 | 2deb946f9a78674b47b1ff474fc59191b12f28eb | /plot/include/plot/residualPlot.h | c23b97978cfbcbf707a951b08961c380c8b17c74 | [
"MIT"
] | permissive | dogjin/PlotLib | 292b60b6065172db2d6071bab539ac556bc738c3 | 36439335362b74ae002ce7e446d233c580b63d1a | refs/heads/master | 2020-04-25T04:49:17.163629 | 2018-06-01T11:40:21 | 2018-06-01T11:40:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,012 | h | /**
* @cond ___LICENSE___
*
* Copyright (c) 2016-2018 Zefiros Software.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @endcond
*/
#pragma once
#ifndef __RESIDUALPLOT_H__
#define __RESIDUALPLOT_H__
#include "plot/properties/scatterProperties.h"
#include "plot/properties/plotProperties.h"
class ResidualPlot
: public AbstractPlot
{
public:
ResidualPlot(const PVec &exogenous, const PVec &endogenous);
virtual std::string ToString() override;
ResidualPlot &Lowess(bool lowess);
ResidualPlot &SetXPartial(const PMat &mat);
ResidualPlot &SetYPartial(const PMat &mat);
ResidualPlot &SetOrder(size_t order);
ResidualPlot &Robust(bool robust);
ResidualPlot &SetLabel(const std::string &label);
ResidualPlot &SetColour(const std::string &colour);
ResidualPlot &SetScatter(Scatter &scatter);
ResidualPlot &SetLine(Line &scatter);
};
#ifndef PLOTLIB_NO_HEADER_ONLY
# include "../../src/residualPlot.cpp"
#endif
#endif | [
"paul.pev@hotmail.com"
] | paul.pev@hotmail.com |
314bb32b603dcec8a7490c1bea99564f654f2a60 | 3e8e01333b1e3dbb8b888ad7776b0288d3f5d775 | /src/wifi_manager.h | c904b03bcec6fb25ef842fb06916d3ad2a970d0f | [
"MIT"
] | permissive | aoinas/wifi-thermometer-esp32 | d0f09375618284d921c9a30bc4259efa4185cb16 | b46439abde2f31ebe927e59faf0b13169f0f7835 | refs/heads/main | 2023-02-05T19:48:32.830287 | 2020-12-20T15:37:00 | 2020-12-20T15:37:00 | 320,826,316 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 990 | h | #pragma once
#include "WiFi.h"
#include "config.h"
#define WIFI_TIMEOUT_MS 20000
class WifiManager
{
public:
WifiManager()
{
}
bool ConnectToWifi()
{
Serial.println("Connecting to WiFi");
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_NETWORK, WIFI_PASS);
unsigned long startAttemptTime = millis();
while ( WiFi.status() != WL_CONNECTED &&
millis() - startAttemptTime < WIFI_TIMEOUT_MS )
{
Serial.print(".");
delay(100);
}
if ( WiFi.status() != WL_CONNECTED )
{
Serial.print("failed");
return false;
}
else
{
Serial.print("Connected ");
Serial.println(WiFi.localIP());
return true;
}
}
WiFiClient& GetWifiClient()
{
return m_Client;
}
private:
WiFiClient m_Client;
}; | [
"ari@gbuilder.com"
] | ari@gbuilder.com |
bed6eaa8d2aa6affdf88d216e405663fd4b240eb | 1f9458bef84e98d10b3b68020e44a4abb8aaad09 | /BerlinMetro/src/application.cpp | 9484cc21f3a5b09c47911f389e8ed9fb8e387be3 | [] | no_license | paulpatzer/BerlinMetro | 4568c0a15813f72fd3e4440fc415d194e213f7c8 | ed94f04e492e9798f8ac0b6a74453b7654ca1668 | refs/heads/master | 2023-02-19T03:53:36.586815 | 2021-01-22T12:04:52 | 2021-01-22T12:04:52 | 331,942,452 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 128 | cpp | #include "ui.h"
#include "routes.h"
#include "edge.h"
#include <iostream>
int main()
{
Network n;
UI ui(n);
ui.loop();
}
| [
"roni.abusayeed@gmail.com"
] | roni.abusayeed@gmail.com |
95d5ea2622c034f1c7485864415fcaccbc86c803 | 333d5f2c8e995dd2085a3ddf6c00d384dc7b3c4d | /src/model/Floorplan.h | 828601b6fec29087915cacce633eade5542babf5 | [] | no_license | zzrpsd/MacroPlacer | 9787f2483734c671fa72dd047853ae83aa4d5f82 | 2eaf3c0a591866ad36c6af6f5cec108d661a698f | refs/heads/master | 2021-05-29T22:26:33.309852 | 2015-10-15T09:26:33 | 2015-10-15T09:26:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,152 | h | #ifndef MODEL_FLOORPLAN_H_
#define MODEL_FLOORPLAN_H_
#include <map>
#include <string>
#include <vector>
class Bin;
class Cell;
class ICPTree;
class Macro;
class Net;
class Terminal;
class Floorplan {
public:
//Floorplan();
/*
Add Macros by addMovableMacro().
*/
Floorplan(std::vector<Macro *> *movableMacros=0, ICPTree *icpTree=0);
/*
Delete all Bins, Macros, Cells, Terminals and Nets.
Pins are deleted when Modules are deleted.
*/
~Floorplan();
void setICPTree(ICPTree *icpTree);
ICPTree *getICPTree();
void addPreplacedMacro(Macro *macro);
void addMovableMacro(Macro *macro);
void addCell(Cell *cell);
void addTerminal(Terminal *terminal);
void addNet(Net *net);
/*
If the name does not match, returns 0.
*/
Macro *getMacroByName(std::string name);
/*
If the name does not match, returns 0.
*/
Cell *getCellByName(std::string name);
/*
If the name does not match, returns 0.
*/
Terminal *getTerminalByName(std::string name);
/*
If the name does not match, returns 0.
*/
Net *getNetByName(std::string name);
std::vector<Macro *> *getPreplacedMacros();
std::vector<Macro *> *getMovableMacros();
std::vector<Cell *> *getCells();
std::vector<Terminal *> *getTerminals();
std::vector<Net *> *getNets();
/*
Calculate the range of immovables.
It is called by createFromAuxFiles().
*/
void calculateMinMaxImmovablesXY();
/*
Use the expanded range of immovables in
calling createBins(double, double, double, double, double, double).
*/
void createBins(double binWidth, double binHeight);
/*
Create Bins with the four inputs are the range of Bins.
The Bins are still empty. Call addxxxMacrosToBins() to add Macros.
CALL IT OR FloorplanWindow cannot display.
*/
void createBins(double xStart, double yStart, double xEnd, double yEnd, double binWidth, double binHeight);
std::vector<std::vector<Bin *> *> *getBinsRows();
double getMinBinsX();
double getMinBinsY();
double getMaxBinsX();
double getMaxBinsY();
/*
Return a vector containing the Bins overlapping with the input x y range.
PLEASE DELETE the returned vector.
*/
std::vector<Bin *> *getBinsUnderRectangle(double xStart, double yStart, double xEnd, double yEnd);
/*
Set the desired region, where Macros are prefered to be placed.
Since the region will be converted to Bins,
MAKE SURE that the region is inside the Bins and
the region boundary is at leat one Bin from the Bins boundary.
Call it after calling createBins().
*/
void setDesiredRegion(double xStart, double yStart, double xEnd, double yEnd);
void addPreplacedMacrosToBins();
void clearBinsMovableMacros();
void addMovableMacrosToBins();
/*
Update the position of Pins of movableMacros.
*/
void updatePinsPosition();
void setRoutabilityWeightOfHpwl(double weight);
double getRoutabilityWeight();
/*
Calculate the total area of both preplaced and movable Macros.
*/
int calculateMacrosArea();
/*
Calculate the total area of Cells.
*/
int calculateCellsArea();
int calculateMacrosAreaUnderRectangle(double xStart, double yStart, double xEnd, double yEnd);
int calculateAreaOutOfBinsUnderRectangle(double xStart, double yStart, double xEnd, double yEnd);
/*
Calculate the sum of hpwl of all Nets except for those Nets that do not have
macroPins nor terminalPins. I.e., Nets with cellPins only are ignored.
*/
double calculateNetsHpwl();
double calculateNetsRoutabilityHpwl();
/*
More movable Macros outside the desired region and farther the Macros from the region,
higher the count. It is a weighted count.
The desired region is set by setDesiredRegion().
*/
double countMovableMacrosOutsideDesiredRegion();
/*
PLEASE read prototype first.
Calculate the sum of movableMacros' displacement from the prototype.
Use squared Euclidean distance.
*/
double calculateMacrosDisplacement();
int getMinX();
int getMinY();
int getMaxX();
int getMaxY();
double getMinImmovablesX();
double getMinImmovablesY();
double getMaxImmovablesX();
double getMaxImmovablesY();
int getDesiredRegionBinIStart();
int getDesiredRegionBinIEnd();
int getDesiredRegionBinJStart();
int getDesiredRegionBinJEnd();
void outputNodes(const char *nodesFilename, bool movableMacrosFixed);
void outputPl(const char *plFilename, bool movableMacrosFixed);
/*
Output the movable Macros and Cells movable, and preplaced Macros and
Terminals fixed.
*/
void outputNodesForPrototyping(const char *nodesFilename);
/*
Output the movable Macros and Cells movable, and preplaced Macros and
Terminals fixed.
*/
void outputPlForPrototyping(const char *plFilename);
/*
Read the Macro position in the pl file generated by NTUplace3,
and store the position in Floorplan.
*/
void readPlOfPrototype(const char *plFilename);
/*
Output the Cells movable, and the Macros and Terminals fixed.
*/
void outputNodesForEvaluation(const char *nodesFilename);
/*
Output the Cells movable, and the Macros and Terminals fixed.
*/
void outputPlForEvaluation(const char *plFilename);
/*
Output the Macros position of the prototype.
*/
void outputFpFromPrototypeForEvaluation(const char *fpFilename);
/*
Create a Floorplan from a .aux file and other related files.
The files follows 2015 ICCAD Contest format.
If read unsuccessful, return 0.
It calls calculateMinMaxImmovablesXY().
*/
static Floorplan *createFromAuxFiles(const char *auxFilename);
private:
std::vector<Macro *> *preplacedMacros;
std::vector<Macro *> *movableMacros;
std::vector<Cell *> *cells;
std::vector<Terminal *> *terminals;
std::vector<Net *> *nets;
std::vector<std::vector<Bin *> *> *binsRows;
std::map<std::string, Macro *> *macrosByName;
std::map<std::string, Cell *> *cellsByName;
std::map<std::string, Terminal *> *terminalsByName;
std::map<std::string, Net *> *netsByName;
/*
The x y range of Terminals and preplacedMacros.
*/
double minImmovablesX;
double minImmovablesY;
double maxImmovablesX;
double maxImmovablesY;
/*
The x y range of Bins.
*/
double minBinsX;
double minBinsY;
double maxBinsX;
double maxBinsY;
double binWidth;
double binHeight;
int numBinsRows;
int numBinsCols;
/*
Desired region. xxxEnd means the range excludes the value.
*/
int desiredRegionBinIStart;
int desiredRegionBinIEnd;
int desiredRegionBinJStart;
int desiredRegionBinJEnd;
std::vector<int> *iDistancesToDesiredRegion;
std::vector<int> *jDistancesToDesiredRegion;
int longestDistanceToDesiredRegion;
double routabilityWeight;
ICPTree *icpTree;
std::vector<int> *prototypeMacrosXStart;
std::vector<int> *prototypeMacrosYStart;
};
#endif | [
"areong6378@gmail.com"
] | areong6378@gmail.com |
800fdcdd26b59b920450afde7e2d232a599f122f | 76b35001069ff708f1fe5f34d04e4b98a7e9bde5 | /polar_charge_cells/src/gui/MathUtils.h | 54d4bde47530fa424e7fde22a1e3c915f36aadf7 | [] | no_license | devoworm/Morphozoic | 1154f6b4f5b476f829bc347dc1db82e73bdedff5 | 95735e6396ee13ea4b6836d9c6432ec99f751201 | refs/heads/master | 2020-05-23T06:08:25.443615 | 2016-10-16T04:12:31 | 2016-10-16T04:12:31 | 186,661,358 | 1 | 0 | null | 2019-05-14T16:34:26 | 2019-05-14T16:34:26 | null | UTF-8 | C++ | false | false | 13,423 | h | /*
*Author: Abdul Bezrati
*Email : abezrati@hotmail.com
*/
#ifndef MATHUTILS
#define MATHUTILS
#ifdef _WIN32
#ifndef WIN32
#define WIN32
#endif
#endif
#include <cmath>
#include <ctime>
#include <float.h>
#include <stdlib.h>
#include <iostream>
#define TWO_PI 6.2831853f
#define EPSILON 0.0001f
#define EPSILON_SQUARED EPSILON*EPSILON
#define RAD2DEG 57.2957f
#define DEG2RAD 0.0174532f
using namespace std;
template <class T>
inline T clamp(T x, T min, T max)
{
return (x < min) ? min : (x > max) ? max : x;
}
inline int roundToInt(float f)
{
return int(f + 0.5f);
}
inline float getNextRandom(){
return (float)((double)rand()/ ((double)RAND_MAX + (double)1));
}
inline int getClosest(int arg, int firstVal, int secondVal)
{
int difference1 = 0,
difference2 = 0;
difference1 = abs(arg - firstVal);
difference2 = abs(arg - secondVal);
if(difference1 < difference2)
return firstVal;
return secondVal;
}
inline int getClosestPowerOfTwo(int digit)
{
if(!digit)
return 1;
double log2 = log(double(abs(digit)))/log(2.0),
flog2 = floor(log2),
frac = log2 - flog2;
return (frac < 0.5) ? (int)pow(2.0, flog2) : (int)pow(2.0, flog2 + 1.0);
}
#ifdef WIN32
inline float fastSquareRoot(float x)
{
__asm{
fld x;
fsqrt;
fstp x;
}
return x;
}
inline float fastCos(float x)
{
__asm{
fld x;
fcos;
fstp x;
}
return x;
}
inline float fastSin(float x)
{
__asm{
fld x;
fsin;
fstp x;
}
return x;
}
#else
inline float fastSin(float x)
{ return sin(x);}
inline float fastCos(float x)
{ return cos(x);}
inline float fastSquareRoot(float x)
{ return sqrt(x);}
#endif
/*inline float fastSquareRootSSE(float f) {
__asm {
MOVSS xmm2,f
SQRTSS xmm1, xmm2
MOVSS f,xmm1
}
return f;
}*/
template <class T>
class Tuple2
{
public:
Tuple2(const T& X = 0, const T& Y = 0)
{
x = X;
y = Y;
}
Tuple2(const Tuple2& source)
{
x = source.x;
y = source.y;
}
inline Tuple2& operator = (const Tuple2& source)
{
x = source.x;
y = source.y;
return *this;
}
inline Tuple2 operator + (const Tuple2& right)
{
return Tuple2(right.x + x, right.y + y);
}
inline Tuple2 operator - (const Tuple2 &right)
{
return Tuple2(-right.x + x, -right.y + y);
}
inline Tuple2 operator * (const T& scale)
{
return Tuple2(x*scale, y*scale);
}
inline Tuple2 operator / (const T& scale)
{
return scale ? Tuple2(x/scale, y/scale) : Tuple2();
}
inline Tuple2 &operator += (const Tuple2 &right)
{
x+=right.x;
y+=right.y;
return *this;
}
inline Tuple2 &operator -= (const Tuple2 &right)
{
x-=right.x;
y-=right.y;
return *this;
}
inline Tuple2 &operator *= (const T& scale)
{
x*=scale;
y*=scale;
return *this;
}
inline Tuple2 &operator /= (const T& scale)
{
if(scale)
{
x/=scale;
y/=scale;
}
return *this;
}
inline operator const T*() const { return &x; }
inline operator T*() { return &x; }
inline const T operator[](int i) const { return ((T*)&x)[i]; }
inline T &operator[](int i) { return ((T*)&x)[i]; }
inline bool operator == (const Tuple2& right)
{
return (x == right.x && y == right.y);
}
inline bool operator != (const Tuple2& right)
{
return !(x == right.x && y == right.y );
}
inline void set(const T& nx, const T& ny)
{
x = nx;
y = ny;
}
inline Tuple2& clamp(const T& min, const T& max)
{
x = x > max ? max : x < min ? min : x;
y = y > max ? max : y < min ? min : y;
return *this;
}
friend std::ostream & operator<< ( std::ostream& streamOut, const Tuple2 & right){
return streamOut << "Tuple2( " << right.x << ", " << right.y << ")\n";
}
T x, y;
};
typedef Tuple2<int > Tuple2i;
typedef Tuple2<float > Tuple2f;
typedef Tuple2<double> Tuple2d;
template <class T>
class Tuple3
{
public:
Tuple3(const T& nx = 0, const T& ny = 0, const T& nz = 0)
{
x = nx;
y = ny;
z = nz;
}
Tuple3(const T& xyz)
{
x =
y =
z = xyz;
}
Tuple3(const Tuple3& source)
{
x = source.x;
y = source.y;
z = source.z;
}
Tuple3(const Tuple2<T>& source, const T& nz = 1)
{
x = source.x;
y = source.y;
z = nz;
}
inline Tuple3 &operator = (const Tuple3& right)
{
x = right.x;
y = right.y;
z = right.z;
return *this;
}
inline Tuple3 operator + (const Tuple3& right)
{
return Tuple3(right.x + x, right.y + y, right.z + z);
}
inline Tuple3 operator - (const Tuple3& right)
{
return Tuple3(-right.x + x, -right.y + y, -right.z + z);
}
inline Tuple3 operator * (const T& scale)
{
return Tuple3(x*scale, y*scale, z*scale);
}
inline Tuple3 operator / (const T& scale)
{
return scale? Tuple3f(x/scale, y/scale, z/scale) : Tuple3();
}
inline Tuple3& operator += (const Tuple3& right)
{
x+=right.x;
y+=right.y;
z+=right.z;
return *this;
}
inline Tuple3& operator += (const T& xyz)
{
x += xyz;
y += xyz;
z += xyz;
return *this;
}
inline Tuple3& operator -= (const Tuple3& right)
{
x-=right.x;
y-=right.y;
z-=right.z;
return *this;
}
inline Tuple3& operator -= (const T& xyz)
{
x -= xyz;
y -= xyz;
z -= xyz;
return *this;
}
inline Tuple3& operator *= (const T& scale)
{
x*=scale;
y*=scale;
z*=scale;
return *this;
}
inline Tuple3& operator /= (const T& scale)
{
if(scale)
{
x/=scale;
y/=scale;
z/=scale;
}
return *this;
}
bool operator == (const Tuple3& right)
{
return (x == right.x && y == right.y && z == right.z);
}
bool operator != (const Tuple3& right)
{
return !(x == right.x && y == right.y && z == right.z);
}
inline operator const T*() const { return &x; }
inline operator T*() { return &x; }
inline const T operator[](int i) const { return ((T*)&x)[i]; }
inline T &operator[](int i) { return ((T*)&x)[i]; }
inline void set(const T& nx, const T& ny, const T& nz)
{
x = nx;
y = ny;
z = nz;
}
inline void set(const Tuple2<T>& vec, const T& Z)
{
x = vec.x;
y = vec.y;
z = Z;
}
inline void set(const T& xyz)
{
x =
y =
z = xyz;
}
inline void set(const Tuple3& t)
{
x = t.x;
y = t.y;
z = t.z;
}
inline Tuple3 &normalize()
{
T length = sqrtf(x*x + y*y + z*z);
if(!length){
set(0,0,0);
return *this;
}
x/=length;
y/=length;
z/=length;
return *this;
}
inline T getLengthSquared() const { return x*x + y*y + z*z; }
inline T getLength() const { return sqrtf(x*x + y*y + z*z); }
inline T getDotProduct(const Tuple3& t) const
{
return x*t.x + y*t.y + z*t.z;
}
inline Tuple3 operator ^(const Tuple3 &t)
{
return Tuple3(y * t.z - z * t.y,
t.x * z - t.z * x,
x * t.y - y * t.x);
}
inline Tuple3 &operator ^=(const Tuple3 &t)
{
set(y * t.z - z * t.y,
t.x * z - t.z * x,
x * t.y - y * t.x);
return *this;
}
inline Tuple3 &crossProduct(const Tuple3& t1, const Tuple3& t2)
{
set(t1.y * t2.z - t1.z * t2.y,
t2.x * t1.z - t2.z * t1.x,
t1.x * t2.y - t1.y * t2.x);
return *this;
}
inline T getDistance(const Tuple3& v2) const
{
return sqrtf((v2.x - x) * (v2.x - x) +
(v2.y - y) * (v2.y - y) +
(v2.z - z) * (v2.z - z));
}
inline T getAngle(const Tuple3& v2) const
{
T angle = acos(getDotProduct(v2) / (getLength() * v2.getLength()));
if(_isnan(angle))
return 0;
return angle;
}
inline Tuple3& clamp(const T& min, const T& max)
{
x = x > max ? max : x < min ? min : x;
y = y > max ? max : y < min ? min : y;
z = z > max ? max : z < min ? min : z;
return *this;
}
friend std::ostream & operator << (std::ostream & streamOut, const Tuple3 & right){
return streamOut << "Tuple(" << right.x << ", " << right.y << ", " << right.z <<")";
}
T x, y, z;
};
typedef Tuple3<int> Tuple3i;
typedef Tuple3<float> Tuple3f;
typedef Tuple3<double> Tuple3d;
typedef Tuple3<char> Tuple3b;
typedef Tuple3<unsigned char> Tuple3ub;
template <class T>
class Tuple4
{
public:
Tuple4(const T& X = 0, const T& Y = 0, const T& Z = 0, const T& W = 0)
{
x = X;
y = Y;
z = Z;
w = W;
}
Tuple4(const T& XYZW)
{
x =
y =
z =
w = XYZW;
}
Tuple4(const Tuple4& source){
x = source.x;
y = source.y;
z = source.z;
w = source.w;
}
Tuple4(const Tuple3<T>& source, const T& Z)
{
x = source.x;
y = source.y;
z = source.z;
w = Z;
}
inline operator const T*() const { return &x; }
inline operator T*() { return &x; }
inline const T operator[](int i) const { return ((T*)&x)[i]; }
inline T &operator[](int i) { return ((T*)&x)[i]; }
inline Tuple4 &operator = (const Tuple4& source)
{
x = source.x;
y = source.y;
z = source.z;
w = source.w;
return *this;
}
inline Tuple4 &operator = (const Tuple3<T> &source)
{
x = source.x;
y = source.y;
z = source.z;
w = 1.0f;
return *this;
}
inline Tuple4 operator + (const Tuple4& right)
{
return Tuple4(right.x + x, right.y + y, right.z + z, right.w + w );
}
inline Tuple4 operator - (const Tuple4& right)
{
return Tuple4(-right.x + x, -right.y + y, -right.z + z, -right.w + w );
}
inline Tuple4 operator * (const T& scale)
{
return scale? Tuple4(x*scale, y*scale, z*scale, w*scale) : Tuple4();
}
inline Tuple4 operator / (const T& scale)
{
return scale? Tuple4(x/scale, y/scale, z/scale, w/scale) : Tuple4();
}
inline Tuple4& operator += (const Tuple4 &right)
{
x +=right.x;
y +=right.y;
z +=right.z;
w +=right.w;
return *this;
}
inline Tuple4& operator -= (const Tuple4 &right)
{
x-=right.x;
y-=right.y;
z-=right.z;
w-=right.w;
return *this;
}
inline Tuple4& clamp(const T& min, const T& max)
{
x = x < min ? min : x > max ? max : x;
y = y < min ? min : y > max ? max : y;
z = z < min ? min : z > max ? max : z;
w = w < min ? min : w > max ? max : w;
return *this;
}
inline Tuple4& operator *= (const T& scale)
{
x*=scale;
y*=scale;
z*=scale;
w*=scale;
return *this;
}
inline Tuple4& operator /= (const T& scale)
{
if(scale)
{
x/=scale;
y/=scale;
z/=scale;
w/=scale;
}
return *this;
}
inline bool operator == (const Tuple4& right)
{
return (x == right.x && y == right.y &&
z == right.z && w == right.w);
}
inline bool operator != (const Tuple4& right)
{
return (x != right.x || y != right.y ||
z != right.z || w != right.w);
}
inline void set(const T& xyzw)
{
x =
y =
z =
w = xyzw;
}
inline void set(const T& nx, const T& ny, const T& nz, const T& nw)
{
x = nx;
y = ny;
z = nz;
w = nw;
}
inline void set(const Tuple4& vec)
{
x = vec.x;
y = vec.y;
z = vec.z;
w = vec.w;
}
inline void set(const Tuple3<T>& vec, const T& W = 1)
{
x = vec.x;
y = vec.y;
z = vec.z;
w = W;
}
friend std::ostream & operator<< ( std::ostream & streamOut, const Tuple4& right)
{
return streamOut << "Tuple4( " << right.x << ", " << right.y
<< ", "
<< right.z << ", " << right.w << ")\n";
}
T x, y, z, w;
};
typedef Tuple4<int > Tuple4i;
typedef Tuple4<float > Tuple4f;
typedef Tuple4<double> Tuple4d;
#endif
| [
"portegys@gmail.com"
] | portegys@gmail.com |
a3c8f296dfb9a68f4805efa725b19e460b7684f1 | 2d360bb5581e231d76692f06cf024cda7a9e5875 | /badlang/asmjit/core/compiler.cpp | 1053ee995f395386c0a523a05677bfebf333490b | [
"Zlib"
] | permissive | sidsenkumar11/DVJIT | 7d5350a40e03d8eaf7a0d6dd4f33dd464528e530 | b582d269ab30b0f0954e191611eed1ab504ddc73 | refs/heads/master | 2022-09-12T13:08:28.188743 | 2020-05-29T04:00:20 | 2020-05-29T04:00:20 | 256,038,996 | 0 | 1 | null | 2020-05-19T23:18:37 | 2020-04-15T21:18:05 | C++ | UTF-8 | C++ | false | false | 18,508 | cpp | // AsmJit - Machine code generation for C++
//
// * Official AsmJit Home Page: https://asmjit.com
// * Official Github Repository: https://github.com/asmjit/asmjit
//
// Copyright (c) 2008-2020 The AsmJit Authors
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
#include "../core/api-build_p.h"
#ifndef ASMJIT_NO_COMPILER
#include "../core/assembler.h"
#include "../core/compiler.h"
#include "../core/cpuinfo.h"
#include "../core/logging.h"
#include "../core/rapass_p.h"
#include "../core/rastack_p.h"
#include "../core/support.h"
#include "../core/type.h"
ASMJIT_BEGIN_NAMESPACE
// ============================================================================
// [asmjit::GlobalConstPoolPass]
// ============================================================================
class GlobalConstPoolPass : public Pass {
ASMJIT_NONCOPYABLE(GlobalConstPoolPass)
typedef Pass Base;
GlobalConstPoolPass() noexcept : Pass("GlobalConstPoolPass") {}
Error run(Zone* zone, Logger* logger) noexcept override {
ASMJIT_UNUSED(zone);
ASMJIT_UNUSED(logger);
// Flush the global constant pool.
BaseCompiler* compiler = static_cast<BaseCompiler*>(_cb);
if (compiler->_globalConstPool) {
compiler->addAfter(compiler->_globalConstPool, compiler->lastNode());
compiler->_globalConstPool = nullptr;
}
return kErrorOk;
}
};
// ============================================================================
// [asmjit::FuncCallNode - Arg / Ret]
// ============================================================================
bool FuncCallNode::_setArg(uint32_t i, const Operand_& op) noexcept {
if ((i & ~kFuncArgHi) >= _funcDetail.argCount())
return false;
_args[i] = op;
return true;
}
bool FuncCallNode::_setRet(uint32_t i, const Operand_& op) noexcept {
if (i >= 2)
return false;
_rets[i] = op;
return true;
}
// ============================================================================
// [asmjit::BaseCompiler - Construction / Destruction]
// ============================================================================
BaseCompiler::BaseCompiler() noexcept
: BaseBuilder(),
_func(nullptr),
_vRegZone(4096 - Zone::kBlockOverhead),
_vRegArray(),
_localConstPool(nullptr),
_globalConstPool(nullptr) {
_type = kTypeCompiler;
}
BaseCompiler::~BaseCompiler() noexcept {}
// ============================================================================
// [asmjit::BaseCompiler - Function API]
// ============================================================================
FuncNode* BaseCompiler::newFunc(const FuncSignature& sign) noexcept {
Error err;
FuncNode* func = newNodeT<FuncNode>();
if (ASMJIT_UNLIKELY(!func)) {
reportError(DebugUtils::errored(kErrorOutOfMemory));
return nullptr;
}
err = registerLabelNode(func);
if (ASMJIT_UNLIKELY(err)) {
// TODO: Calls reportError, maybe rethink noexcept?
reportError(err);
return nullptr;
}
// Create helper nodes.
func->_exitNode = newLabelNode();
func->_end = newNodeT<SentinelNode>(SentinelNode::kSentinelFuncEnd);
if (ASMJIT_UNLIKELY(!func->_exitNode || !func->_end)) {
reportError(DebugUtils::errored(kErrorOutOfMemory));
return nullptr;
}
// Initialize the function info.
err = func->detail().init(sign);
if (ASMJIT_UNLIKELY(err)) {
reportError(err);
return nullptr;
}
// If the Target guarantees greater stack alignment than required by the
// calling convention then override it as we can prevent having to perform
// dynamic stack alignment
if (func->_funcDetail._callConv.naturalStackAlignment() < _codeInfo.stackAlignment())
func->_funcDetail._callConv.setNaturalStackAlignment(_codeInfo.stackAlignment());
// Initialize the function frame.
err = func->_frame.init(func->_funcDetail);
if (ASMJIT_UNLIKELY(err)) {
reportError(err);
return nullptr;
}
// Allocate space for function arguments.
func->_args = nullptr;
if (func->argCount() != 0) {
func->_args = _allocator.allocT<VirtReg*>(func->argCount() * sizeof(VirtReg*));
if (ASMJIT_UNLIKELY(!func->_args)) {
reportError(DebugUtils::errored(kErrorOutOfMemory));
return nullptr;
}
memset(func->_args, 0, func->argCount() * sizeof(VirtReg*));
}
return func;
}
FuncNode* BaseCompiler::addFunc(FuncNode* func) {
ASMJIT_ASSERT(_func == nullptr);
_func = func;
addNode(func); // Function node.
BaseNode* prev = cursor(); // {CURSOR}.
addNode(func->exitNode()); // Function exit label.
addNode(func->endNode()); // Function end marker.
_setCursor(prev);
return func;
}
FuncNode* BaseCompiler::addFunc(const FuncSignature& sign) {
FuncNode* func = newFunc(sign);
if (!func) {
reportError(DebugUtils::errored(kErrorOutOfMemory));
return nullptr;
}
return addFunc(func);
}
Error BaseCompiler::endFunc() {
FuncNode* func = _func;
if (ASMJIT_UNLIKELY(!func))
return reportError(DebugUtils::errored(kErrorInvalidState));
// Add the local constant pool at the end of the function (if exists).
if (_localConstPool) {
setCursor(func->endNode()->prev());
addNode(_localConstPool);
_localConstPool = nullptr;
}
// Mark as finished.
_func = nullptr;
SentinelNode* end = func->endNode();
setCursor(end);
return kErrorOk;
}
Error BaseCompiler::setArg(uint32_t argIndex, const BaseReg& r) {
FuncNode* func = _func;
if (ASMJIT_UNLIKELY(!func))
return reportError(DebugUtils::errored(kErrorInvalidState));
if (ASMJIT_UNLIKELY(!isVirtRegValid(r)))
return reportError(DebugUtils::errored(kErrorInvalidVirtId));
VirtReg* vReg = virtRegByReg(r);
func->setArg(argIndex, vReg);
return kErrorOk;
}
FuncRetNode* BaseCompiler::newRet(const Operand_& o0, const Operand_& o1) noexcept {
FuncRetNode* node = newNodeT<FuncRetNode>();
if (!node) {
reportError(DebugUtils::errored(kErrorOutOfMemory));
return nullptr;
}
node->setOp(0, o0);
node->setOp(1, o1);
node->setOpCount(!o1.isNone() ? 2u : !o0.isNone() ? 1u : 0u);
return node;
}
FuncRetNode* BaseCompiler::addRet(const Operand_& o0, const Operand_& o1) noexcept {
FuncRetNode* node = newRet(o0, o1);
if (!node) return nullptr;
return addNode(node)->as<FuncRetNode>();
}
// ============================================================================
// [asmjit::BaseCompiler - Call]
// ============================================================================
FuncCallNode* BaseCompiler::newCall(uint32_t instId, const Operand_& o0, const FuncSignature& sign) noexcept {
FuncCallNode* node = newNodeT<FuncCallNode>(instId, 0u);
if (ASMJIT_UNLIKELY(!node)) {
reportError(DebugUtils::errored(kErrorOutOfMemory));
return nullptr;
}
node->setOpCount(1);
node->setOp(0, o0);
node->resetOp(1);
node->resetOp(2);
node->resetOp(3);
Error err = node->detail().init(sign);
if (ASMJIT_UNLIKELY(err)) {
reportError(err);
return nullptr;
}
// If there are no arguments skip the allocation.
uint32_t nArgs = sign.argCount();
if (!nArgs) return node;
node->_args = static_cast<Operand*>(_allocator.alloc(nArgs * sizeof(Operand)));
if (!node->_args) {
reportError(DebugUtils::errored(kErrorOutOfMemory));
return nullptr;
}
memset(node->_args, 0, nArgs * sizeof(Operand));
return node;
}
FuncCallNode* BaseCompiler::addCall(uint32_t instId, const Operand_& o0, const FuncSignature& sign) noexcept {
FuncCallNode* node = newCall(instId, o0, sign);
if (!node) return nullptr;
return addNode(node)->as<FuncCallNode>();
}
// ============================================================================
// [asmjit::BaseCompiler - Vars]
// ============================================================================
static void CodeCompiler_assignGenericName(BaseCompiler* self, VirtReg* vReg) {
uint32_t index = unsigned(Operand::virtIdToIndex(vReg->_id));
char buf[64];
int size = snprintf(buf, ASMJIT_ARRAY_SIZE(buf), "%%%u", unsigned(index));
ASMJIT_ASSERT(size > 0 && size < int(ASMJIT_ARRAY_SIZE(buf)));
vReg->_name.setData(&self->_dataZone, buf, unsigned(size));
}
VirtReg* BaseCompiler::newVirtReg(uint32_t typeId, uint32_t signature, const char* name) noexcept {
uint32_t index = _vRegArray.size();
if (ASMJIT_UNLIKELY(index >= uint32_t(Operand::kVirtIdCount)))
return nullptr;
if (_vRegArray.willGrow(&_allocator) != kErrorOk)
return nullptr;
VirtReg* vReg = _vRegZone.allocZeroedT<VirtReg>();
if (ASMJIT_UNLIKELY(!vReg)) return nullptr;
uint32_t size = Type::sizeOf(typeId);
uint32_t alignment = Support::min<uint32_t>(size, 64);
vReg = new(vReg) VirtReg(Operand::indexToVirtId(index), signature, size, alignment, typeId);
#ifndef ASMJIT_NO_LOGGING
if (name && name[0] != '\0')
vReg->_name.setData(&_dataZone, name, SIZE_MAX);
else
CodeCompiler_assignGenericName(this, vReg);
#endif
_vRegArray.appendUnsafe(vReg);
return vReg;
}
Error BaseCompiler::_newReg(BaseReg& out, uint32_t typeId, const char* name) {
RegInfo regInfo;
Error err = ArchUtils::typeIdToRegInfo(archId(), typeId, regInfo);
if (ASMJIT_UNLIKELY(err)) return reportError(err);
VirtReg* vReg = newVirtReg(typeId, regInfo.signature(), name);
if (ASMJIT_UNLIKELY(!vReg)) {
out.reset();
return reportError(DebugUtils::errored(kErrorOutOfMemory));
}
out._initReg(regInfo.signature(), vReg->id());
return kErrorOk;
}
Error BaseCompiler::_newRegFmt(BaseReg& out, uint32_t typeId, const char* fmt, ...) {
va_list ap;
StringTmp<256> sb;
va_start(ap, fmt);
sb.appendVFormat(fmt, ap);
va_end(ap);
return _newReg(out, typeId, sb.data());
}
Error BaseCompiler::_newReg(BaseReg& out, const BaseReg& ref, const char* name) {
RegInfo regInfo;
uint32_t typeId;
if (isVirtRegValid(ref)) {
VirtReg* vRef = virtRegByReg(ref);
typeId = vRef->typeId();
// NOTE: It's possible to cast one register type to another if it's the
// same register group. However, VirtReg always contains the TypeId that
// was used to create the register. This means that in some cases we may
// end up having different size of `ref` and `vRef`. In such case we
// adjust the TypeId to match the `ref` register type instead of the
// original register type, which should be the expected behavior.
uint32_t typeSize = Type::sizeOf(typeId);
uint32_t refSize = ref.size();
if (typeSize != refSize) {
if (Type::isInt(typeId)) {
// GP register - change TypeId to match `ref`, but keep sign of `vRef`.
switch (refSize) {
case 1: typeId = Type::kIdI8 | (typeId & 1); break;
case 2: typeId = Type::kIdI16 | (typeId & 1); break;
case 4: typeId = Type::kIdI32 | (typeId & 1); break;
case 8: typeId = Type::kIdI64 | (typeId & 1); break;
default: typeId = Type::kIdVoid; break;
}
}
else if (Type::isMmx(typeId)) {
// MMX register - always use 64-bit.
typeId = Type::kIdMmx64;
}
else if (Type::isMask(typeId)) {
// Mask register - change TypeId to match `ref` size.
switch (refSize) {
case 1: typeId = Type::kIdMask8; break;
case 2: typeId = Type::kIdMask16; break;
case 4: typeId = Type::kIdMask32; break;
case 8: typeId = Type::kIdMask64; break;
default: typeId = Type::kIdVoid; break;
}
}
else {
// VEC register - change TypeId to match `ref` size, keep vector metadata.
uint32_t elementTypeId = Type::baseOf(typeId);
switch (refSize) {
case 16: typeId = Type::_kIdVec128Start + (elementTypeId - Type::kIdI8); break;
case 32: typeId = Type::_kIdVec256Start + (elementTypeId - Type::kIdI8); break;
case 64: typeId = Type::_kIdVec512Start + (elementTypeId - Type::kIdI8); break;
default: typeId = Type::kIdVoid; break;
}
}
if (typeId == Type::kIdVoid)
return reportError(DebugUtils::errored(kErrorInvalidState));
}
}
else {
typeId = ref.type();
}
Error err = ArchUtils::typeIdToRegInfo(archId(), typeId, regInfo);
if (ASMJIT_UNLIKELY(err)) return reportError(err);
VirtReg* vReg = newVirtReg(typeId, regInfo.signature(), name);
if (ASMJIT_UNLIKELY(!vReg)) {
out.reset();
return reportError(DebugUtils::errored(kErrorOutOfMemory));
}
out._initReg(regInfo.signature(), vReg->id());
return kErrorOk;
}
Error BaseCompiler::_newRegFmt(BaseReg& out, const BaseReg& ref, const char* fmt, ...) {
va_list ap;
StringTmp<256> sb;
va_start(ap, fmt);
sb.appendVFormat(fmt, ap);
va_end(ap);
return _newReg(out, ref, sb.data());
}
Error BaseCompiler::_newStack(BaseMem& out, uint32_t size, uint32_t alignment, const char* name) {
if (size == 0)
return reportError(DebugUtils::errored(kErrorInvalidArgument));
if (alignment == 0)
alignment = 1;
if (!Support::isPowerOf2(alignment))
return reportError(DebugUtils::errored(kErrorInvalidArgument));
if (alignment > 64)
alignment = 64;
VirtReg* vReg = newVirtReg(0, 0, name);
if (ASMJIT_UNLIKELY(!vReg)) {
out.reset();
return reportError(DebugUtils::errored(kErrorOutOfMemory));
}
vReg->_virtSize = size;
vReg->_isStack = true;
vReg->_alignment = uint8_t(alignment);
// Set the memory operand to GPD/GPQ and its id to VirtReg.
out = BaseMem(BaseMem::Decomposed { _gpRegInfo.type(), vReg->id(), BaseReg::kTypeNone, 0, 0, 0, BaseMem::kSignatureMemRegHomeFlag });
return kErrorOk;
}
Error BaseCompiler::setStackSize(uint32_t virtId, uint32_t newSize, uint32_t newAlignment) noexcept {
if (!isVirtIdValid(virtId))
return DebugUtils::errored(kErrorInvalidVirtId);
if (newAlignment && !Support::isPowerOf2(newAlignment))
return reportError(DebugUtils::errored(kErrorInvalidArgument));
if (newAlignment > 64)
newAlignment = 64;
VirtReg* vReg = virtRegById(virtId);
if (newSize)
vReg->_virtSize = newSize;
if (newAlignment)
vReg->_alignment = uint8_t(newAlignment);
// This is required if the RAPass is already running. There is a chance that
// a stack-slot has been already allocated and in that case it has to be
// updated as well, otherwise we would allocate wrong amount of memory.
RAWorkReg* workReg = vReg->_workReg;
if (workReg && workReg->_stackSlot) {
workReg->_stackSlot->_size = vReg->_virtSize;
workReg->_stackSlot->_alignment = vReg->_alignment;
}
return kErrorOk;
}
Error BaseCompiler::_newConst(BaseMem& out, uint32_t scope, const void* data, size_t size) {
ConstPoolNode** pPool;
if (scope == ConstPool::kScopeLocal)
pPool = &_localConstPool;
else if (scope == ConstPool::kScopeGlobal)
pPool = &_globalConstPool;
else
return reportError(DebugUtils::errored(kErrorInvalidArgument));
ConstPoolNode* pool = *pPool;
if (!pool) {
pool = newConstPoolNode();
if (ASMJIT_UNLIKELY(!pool))
return reportError(DebugUtils::errored(kErrorOutOfMemory));
*pPool = pool;
}
size_t off;
Error err = pool->add(data, size, off);
if (ASMJIT_UNLIKELY(err))
return reportError(err);
out = BaseMem(BaseMem::Decomposed {
Label::kLabelTag, // Base type.
pool->id(), // Base id.
0, // Index type.
0, // Index id.
int32_t(off), // Offset.
uint32_t(size), // Size.
0 // Flags.
});
return kErrorOk;
}
void BaseCompiler::rename(const BaseReg& reg, const char* fmt, ...) {
if (!reg.isVirtReg()) return;
VirtReg* vReg = virtRegById(reg.id());
if (!vReg) return;
if (fmt && fmt[0] != '\0') {
char buf[128];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, ASMJIT_ARRAY_SIZE(buf), fmt, ap);
va_end(ap);
vReg->_name.setData(&_dataZone, buf, SIZE_MAX);
}
else {
CodeCompiler_assignGenericName(this, vReg);
}
}
// ============================================================================
// [asmjit::BaseCompiler - Events]
// ============================================================================
Error BaseCompiler::onAttach(CodeHolder* code) noexcept {
ASMJIT_PROPAGATE(Base::onAttach(code));
Error err = addPassT<GlobalConstPoolPass>();
if (ASMJIT_UNLIKELY(err)) {
onDetach(code);
return err;
}
return kErrorOk;
}
Error BaseCompiler::onDetach(CodeHolder* code) noexcept {
_func = nullptr;
_localConstPool = nullptr;
_globalConstPool = nullptr;
_vRegArray.reset();
_vRegZone.reset();
return Base::onDetach(code);
}
// ============================================================================
// [asmjit::FuncPass - Construction / Destruction]
// ============================================================================
FuncPass::FuncPass(const char* name) noexcept
: Pass(name) {}
// ============================================================================
// [asmjit::FuncPass - Run]
// ============================================================================
Error FuncPass::run(Zone* zone, Logger* logger) noexcept {
BaseNode* node = cb()->firstNode();
if (!node) return kErrorOk;
do {
if (node->type() == BaseNode::kNodeFunc) {
FuncNode* func = node->as<FuncNode>();
node = func->endNode();
ASMJIT_PROPAGATE(runOnFunction(zone, logger, func));
}
// Find a function by skipping all nodes that are not `kNodeFunc`.
do {
node = node->next();
} while (node && node->type() != BaseNode::kNodeFunc);
} while (node);
return kErrorOk;
}
ASMJIT_END_NAMESPACE
#endif // !ASMJIT_NO_COMPILER
| [
"robert349@ucsb.edu"
] | robert349@ucsb.edu |
051d60801009591916142366d61ddf4a9c327213 | dd6147bf9433298a64bbceb7fdccaa4cc477fba6 | /8382/Nechepurenko/sources/facade.cpp | 9beccaee55c8a7805f6c48f93dc1c8b4d5354428 | [] | no_license | moevm/oop | 64a89677879341a3e8e91ba6d719ab598dcabb49 | faffa7e14003b13c658ccf8853d6189b51ee30e6 | refs/heads/master | 2023-03-16T15:48:35.226647 | 2020-06-08T16:16:31 | 2020-06-08T16:16:31 | 85,785,460 | 42 | 304 | null | 2023-03-06T23:46:08 | 2017-03-22T04:37:01 | C++ | UTF-8 | C++ | false | false | 9,360 | cpp | #include "../headers/facade.hpp"
#include <iostream>
#include <string>
#include "../headers/serializer.hpp"
#include "../headers/parser.hpp"
Facade::Facade(uint32_t height, uint32_t width) {
gc = GameSingleton::getGameController(height, width);
}
FacadeResultCode Facade::startGame() {
std::cout << "The game has started!" << std::endl;
return FacadeResultCode::SUCCESS;
}
FacadeResultCode Facade::updateState() {
auto gameController = GameSingleton::getGameController();
auto rules = gameController->getRules();
auto radiant = gameController->getRadiantBase();
auto dire = gameController->getDireBase();
auto logger = gameController->getLogger();
char result = rules->check(radiant, dire);
if (result == 0) {
logger->appendBuffer(std::string("Dire won!\n"));
return FacadeResultCode::ERROR;
}
if (result == 1) {
logger->appendBuffer(std::string("Radiant won!\n"));
return FacadeResultCode::ERROR;
}
return FacadeResultCode::SUCCESS;
}
FacadeResultCode Facade::updateScreen() {
for (int i = 0; i < 100; i++)
std::cout << "\n";
auto gameController = GameSingleton::getGameController();
gameController->getLogger()->log();
gameController->getLogger()->cleanBuffer();
gameController->getMap()->draw();
return FacadeResultCode::SUCCESS;
}
Facade::~Facade(){
delete gc;
}
FacadeResultCode Facade::handle(char command, char arg) {
FacadeResultCode res;
switch (command)
{
case 'q':
res = handleQ(arg);
break;
case 'e':
res = handleE(arg);
break;
case 'p':
res = handleP(arg);
break;
case 'l':
res = handleL(arg);
break;
case 'v':
res = handleV(arg);
break;
case 's':
res = handleS(arg);
break;
case 'c':
res = handleC(arg);
break;
//case 'b':
// res = handleB(arg);
// break;
case 'm':
res = handleM(arg);
break;
case 'a':
res = handleA(arg);
break;
case 'n':
res = handleN(arg);
break;
default:
throw UnknownCommandException(command);
break;
}
return res;
}
FacadeResultCode Facade::handleQ(char arg) {
return FacadeResultCode::ERROR;
}
FacadeResultCode Facade::handleE(char arg) {
try {
gc->setCurrentHero(gc->getCurrentBase()->next());
} catch (NoNextException& e) {
gc->getLogger()->appendBuffer(e.what());
} catch (std::exception& e) {
gc->getLogger()->appendBuffer(e.what());
}
return FacadeResultCode::SUCCESS;
}
FacadeResultCode Facade::handleP(char arg) {
if (gc->getCurrentBase() == gc->getRadiantBase()) {
gc->setBase(gc->getDireBase());
gc->setCurrentHero(gc->getDireBase()->getCurrentUnit());
}
else {
gc->setBase(gc->getRadiantBase());
gc->setCurrentHero(gc->getRadiantBase()->getCurrentUnit());
}
nullifystep();
return FacadeResultCode::SUCCESS;
}
FacadeResultCode Facade::handleL(char arg) {
std::string path;
std::cout << "Input path: ";
std::cin >> path;
std::cin.get();
try {
auto unserializer = new Unserializer(path);
unserializer->unserialize();
delete unserializer;
} catch (FileErrorException& e) {
gc->getLogger()->appendBuffer(e.what());
return FacadeResultCode::ERROR;
} catch (UnserializerException& e) {
gc->getLogger()->appendBuffer(e.what());
return FacadeResultCode::ERROR;
} catch (std::exception& e) {
gc->getLogger()->appendBuffer(e.what());
return FacadeResultCode::ERROR;
}
return FacadeResultCode::SUCCESS;
}
FacadeResultCode Facade::handleV(char arg) {
try {
if (arg == 't') {
gc->setLogger(new TerminalLogger());
}
if (arg == 'f') {
gc->setLogger(new FileLogger());
}
} catch (FileErrorException& e) {
gc->getLogger()->appendBuffer(e.what());
return FacadeResultCode::ERROR;
} catch (std::exception& e) {
gc->getLogger()->appendBuffer(e.what());
return FacadeResultCode::ERROR;
}
return FacadeResultCode::SUCCESS;
}
FacadeResultCode Facade::handleS(char arg) {
std::string path;
std::cout << "Input path: ";
std::cin >> path;
std::cin.get();
try {
auto serializer = new Serializer(path);
serializer->serialize();
delete serializer;
} catch (FileErrorException& e) {
gc->getLogger()->appendBuffer(e.what());
return FacadeResultCode::ERROR;
} catch (std::exception& e) {
gc->getLogger()->appendBuffer(e.what());
return FacadeResultCode::ERROR;
}
return FacadeResultCode::SUCCESS;
}
FacadeResultCode Facade::handleC(char arg) {
if (arg == 'b') {
Unit* u = gc->getCurrentBase()->createUnit(ObjectType::BOGATYR, new UnitParamList(
ObjectType::BOGATYR,
std::string("BOGATYR") + std::to_string(iter)
));
gc->setCurrentHero(u);
}
if (arg == 'm') {
Unit* u = gc->getCurrentBase()->createUnit(ObjectType::MULTIARCHER, new UnitParamList(
ObjectType::MULTIARCHER,
std::string("MULTIARCHER") + std::to_string(iter)
));
gc->setCurrentHero(u);
}
if (arg == 'w') {
Unit* u = gc->getCurrentBase()->createUnit(ObjectType::WINDARCHER, new UnitParamList(
ObjectType::WINDARCHER,
std::string("WINDARCHER") + std::to_string(iter)
));
gc->setCurrentHero(u);
}
if (arg == 't') {
Unit* u = gc->getCurrentBase()->createUnit(ObjectType::TAMPLIER, new UnitParamList(
ObjectType::TAMPLIER,
std::string("TAMPLIER") + std::to_string(iter)
));
gc->setCurrentHero(u);
}
step();
return FacadeResultCode::SUCCESS;
}
FacadeResultCode Facade::handleB(char arg) {
if (arg == 'd') {
gc->getDireBase()->describe();
}
if (arg == 'r'){
gc->getRadiantBase()->describe();
}
return FacadeResultCode::SUCCESS;
}
FacadeResultCode Facade::handleM(char arg) {
try {
if (arg == 'w') {
gc->getCurrentHero()->moveUp();
}
if (arg == 'a') {
gc->getCurrentHero()->moveLeft();
}
if (arg == 'd') {
gc->getCurrentHero()->moveRight();
}
if (arg == 's') {
gc->getCurrentHero()->moveDown();
}
} catch (NoCurrentPlayerException& e) {
gc->getLogger()->appendBuffer(e.what());
}
step();
return FacadeResultCode::SUCCESS;
}
FacadeResultCode Facade::handleA(char arg) {
try {
auto position = gc->getObjectStorage()->getCoords(gc->getCurrentHero());
gc->getCurrentHero()->attack(position.first, position.second);
} catch (NoCurrentPlayerException& e) {
gc->getLogger()->appendBuffer(e.what());
}
step();
return FacadeResultCode::SUCCESS;
}
FacadeResultCode Facade::handleN(char arg) {
try {
auto unserializer = new Unserializer(std::string("saves/newgame.sav"));
unserializer->unserialize();
delete unserializer;
nullifystep();
} catch (FileErrorException& e) {
gc->getLogger()->appendBuffer(e.what());
return FacadeResultCode::ERROR;
} catch (UnserializerException& e) {
gc->getLogger()->appendBuffer(e.what());
return FacadeResultCode::ERROR;
} catch (std::exception& e) {
gc->getLogger()->appendBuffer(e.what());
return FacadeResultCode::ERROR;
}
return FacadeResultCode::SUCCESS;
}
void Facade::inc() {
iter++;
}
void Facade::step() {
steps++;
}
void Facade::nullifystep() {
steps = 0;
}
void Facade::log() {
gc->getLogger()->log();
}
FacadeResultCode Facade::mainLoop() {
std::string commandBuffer;
CommandParser* commandParser = new CommandParser();
ParsedStruct command = {'.', '.'};
while (1) {
inc();
handleB(gc->getCurrentBase() == gc->getDireBase() ? 'd' : 'r');
updateScreen();
std::cout << "Command:";
std::getline(std::cin, commandBuffer);
try {
command = commandParser->parse(commandBuffer);
} catch(UnknownCommandException& e) {
gc->getLogger()->appendBuffer(e.what());
} catch (const std::exception& e) {
std::cout << "Error!" << e.what() << std::endl;
break;
}
try {
auto res = handle(command.command, command.arg);
if (res == FacadeResultCode::ERROR){
log();
break;
}
} catch (UnknownCommandException& e) {
gc->getLogger()->appendBuffer(e.what());
}
try {
auto res = updateState();
if (res == FacadeResultCode::ERROR){
log();
break;
}
} catch (std::exception& e) {
gc->getLogger()->appendBuffer(e.what());
break;
}
if (steps % gc->getRules()->getRule()->getMovesOnIter() == 0 && steps != 0)
handleP();
command = {'.', '.'};
}
delete commandParser;
return FacadeResultCode::SUCCESS;
} | [
"rufflerock@gmail.com"
] | rufflerock@gmail.com |
34a67bcf26aa0d693ee45fb7721b17e3b171df6b | 55bc47584303452a512d6de9634097078ef376c5 | /examples/example3.cpp | 305be04dfeb3be2081f1f739a1d801798c16ece9 | [] | no_license | DanilBukreev/BSTree | 49ffe19b21467e8316dd58f097b651e2975c0981 | 19a6b4a8a134a883a0da4ea154507c1af46c2e81 | refs/heads/master | 2021-04-27T00:27:54.892817 | 2018-04-20T11:08:06 | 2018-04-20T11:08:06 | 123,817,493 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,095 | cpp | #include <iostream>
#include "bstree.cpp"
using namespace std;
using namespace BSTree;
void menu(Tree *&tree) {
int ch;
char ch_2;
string s;
do {
cout << " " << endl;
cout << "1. Вывести дерево на экран" << endl;
cout << "2. Вывести список узлов дерева" << endl;
cout << "3. Добавить узел в дерево" << endl;
cout << "4. Удалить узел из дерева" << endl;
cout << "5. Сохранить дерево в файл" << endl;
cout << "6. Загрузить дерево из файла" << endl;
cout << "7. Проверить наличие узла" << endl;
cout << "8. Завершить работу программы" << endl;
cin >> ch;
switch (ch) {
case 1: {
tree->show();
break;
}
case 2:
if (!(tree->zero())) {
cout << "a.Прямой обход" << endl;
cout << "b.Поперечный обход" << endl;
cout << "c.Обратный обход" << endl;
cin >> ch_2;
switch (ch_2) {
case 'b':
tree->InOrder();
cout << endl;
break;
case 'a':
tree->PreOrder();
cout << endl;
break;
case 'c':
tree->PostOrder();
cout << endl;
break;
}
break;
} else
cout << "nothing to show" << endl;
break;
case 8: {
cout << "Вы хотите выйти из программы ? (Да|Нет):" << endl;
cin >> s;
if (s == "yes" || s == "YES" || s == "Yes" || s == "Y" || s == "y")
cout << "Всего доброго!" << endl;
break;
}
}
} while (s != "yes" && s != "YES" && s != "Да" && s != "Yes" && s != "Y" &&
s != "y");
}
int main(int argc, char *argv[]) {
Tree *tree = new Tree;
for (int i = 1; i < argc; i++) {
tree->insert(atoi(argv[i]));
};
menu(tree);
delete tree;
}
| [
"noreply@github.com"
] | DanilBukreev.noreply@github.com |
6c951138b41de3aebb7453f57b174a4e6c4392f4 | f8200b211d1af0bf08050ff11b8b7b61ae6c7483 | /TestTolua++WithLuaJit/pkg_source/global_func.cpp | ee2194f9ba6c96ac54bed700e1e7580fcef86c87 | [] | no_license | wanghui1966/LearnLua | 9b85ae804535fca0ec61fc4e13e1a22b8c88828a | 3e8d26bfeb2218ac5857e99b468c307f67f8d2a1 | refs/heads/master | 2021-01-16T19:23:46.659595 | 2020-06-10T10:47:07 | 2020-06-10T10:47:07 | 100,159,540 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 134 | cpp | #include "global_func.h"
bool global_func_example(int data)
{
if (data > 0)
{
return true;
}
return false;
}
| [
"wanghui1966@163.com"
] | wanghui1966@163.com |
3a9cd3d97605960a62fd1d3816eebdb461088a1f | 91f69c0d8608445bc104a0225af72789123e3c08 | /olcNoiseMaker.cpp | 9aa97f76782c40931e70ece4c3368dcca6c45e72 | [] | no_license | rcampbell1337/sound_Synth | 139ae560e6c6b8deb5e2b1aac4b711bd10eec174 | 8ee413c79444f0c83d813de55885f203ad18c3ce | refs/heads/master | 2022-06-12T06:08:18.061790 | 2020-04-14T15:50:55 | 2020-04-14T15:50:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,626 | cpp | /*
OneLoneCoder.com - Simple Audio Noisy Thing
"Allows you to simply listen to that waveform!" - @Javidx9
License
~~~~~~~
Copyright (C) 2018 Javidx9
This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it
under certain conditions; See license for details.
Original works located at:
https://www.github.com/onelonecoder
https://www.onelonecoder.com
https://www.youtube.com/javidx9
GNU GPLv3
https://github.com/OneLoneCoder/videos/blob/master/LICENSE
From Javidx9 :)
~~~~~~~~~~~~~~~
Hello! Ultimately I don't care what you use this for. It's intended to be
educational, and perhaps to the oddly minded - a little bit of fun.
Please hack this, change it and use it in any way you see fit. You acknowledge
that I am not responsible for anything bad that happens as a result of
your actions. However this code is protected by GNU GPLv3, see the license in the
github repo. This means you must attribute me if you use it. You can view this
license here: https://github.com/OneLoneCoder/videos/blob/master/LICENSE
Cheers!
Author
~~~~~~
Twitter: @javidx9
Blog: www.onelonecoder.com
Versions
~~~~~~~~
1.0 - 14/01/17
- Controls audio output hardware behind the scenes so you can just focus
on creating and listening to interesting waveforms.
- Currently MS Windows only
Documentation
~~~~~~~~~~~~~
See video: https://youtu.be/tgamhuQnOkM
This will improve as it grows!
*/
#pragma once
#pragma comment(lib, "winmm.lib")
#include <iostream>
#include <cmath>
#include <fstream>
#include <vector>
#include <string>
#include <thread>
#include <atomic>
#include <condition_variable>
using namespace std;
#include <Windows.h>
const double PI = 2.0 * acos(0.0);
template<class T>
class olcNoiseMaker
{
public:
olcNoiseMaker(wstring sOutputDevice, unsigned int nSampleRate = 44100, unsigned int nChannels = 1, unsigned int nBlocks = 8, unsigned int nBlockSamples = 512)
{
Create(sOutputDevice, nSampleRate, nChannels, nBlocks, nBlockSamples);
}
~olcNoiseMaker()
{
Destroy();
}
bool Create(wstring sOutputDevice, unsigned int nSampleRate = 44100, unsigned int nChannels = 1, unsigned int nBlocks = 8, unsigned int nBlockSamples = 512)
{
m_bReady = false;
m_nSampleRate = nSampleRate;
m_nChannels = nChannels;
m_nBlockCount = nBlocks;
m_nBlockSamples = nBlockSamples;
m_nBlockFree = m_nBlockCount;
m_nBlockCurrent = 0;
m_pBlockMemory = nullptr;
m_pWaveHeaders = nullptr;
m_userFunction = nullptr;
// Validate device
vector<wstring> devices = Enumerate();
auto d = std::find(devices.begin(), devices.end(), sOutputDevice);
if (d != devices.end())
{
// Device is available
int nDeviceID = distance(devices.begin(), d);
WAVEFORMATEX waveFormat;
waveFormat.wFormatTag = WAVE_FORMAT_PCM;
waveFormat.nSamplesPerSec = m_nSampleRate;
waveFormat.wBitsPerSample = sizeof(T) * 8;
waveFormat.nChannels = m_nChannels;
waveFormat.nBlockAlign = (waveFormat.wBitsPerSample / 8) * waveFormat.nChannels;
waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
waveFormat.cbSize = 0;
// Open Device if valid
if (waveOutOpen(&m_hwDevice, nDeviceID, &waveFormat, (DWORD_PTR)waveOutProcWrap, (DWORD_PTR)this, CALLBACK_FUNCTION) != S_OK)
return Destroy();
}
// Allocate Wave|Block Memory
m_pBlockMemory = new T[m_nBlockCount * m_nBlockSamples];
if (m_pBlockMemory == nullptr)
return Destroy();
ZeroMemory(m_pBlockMemory, sizeof(T) * m_nBlockCount * m_nBlockSamples);
m_pWaveHeaders = new WAVEHDR[m_nBlockCount];
if (m_pWaveHeaders == nullptr)
return Destroy();
ZeroMemory(m_pWaveHeaders, sizeof(WAVEHDR) * m_nBlockCount);
// Link headers to block memory
for (unsigned int n = 0; n < m_nBlockCount; n++)
{
m_pWaveHeaders[n].dwBufferLength = m_nBlockSamples * sizeof(T);
m_pWaveHeaders[n].lpData = (LPSTR)(m_pBlockMemory + (n * m_nBlockSamples));
}
m_bReady = true;
m_thread = thread(&olcNoiseMaker::MainThread, this);
// Start the ball rolling
unique_lock<mutex> lm(m_muxBlockNotZero);
m_cvBlockNotZero.notify_one();
return true;
}
bool Destroy()
{
return false;
}
void Stop()
{
m_bReady = false;
m_thread.join();
}
// Override to process current sample
virtual double UserProcess(double dTime)
{
return 0.0;
}
double GetTime()
{
return m_dGlobalTime;
}
public:
static vector<wstring> Enumerate()
{
int nDeviceCount = waveOutGetNumDevs();
vector<wstring> sDevices;
WAVEOUTCAPS woc;
for (int n = 0; n < nDeviceCount; n++)
if (waveOutGetDevCaps(n, &woc, sizeof(WAVEOUTCAPS)) == S_OK)
sDevices.push_back(woc.szPname);
return sDevices;
}
void SetUserFunction(double(*func)(double))
{
m_userFunction = func;
}
double clip(double dSample, double dMax)
{
if (dSample >= 0.0)
return fmin(dSample, dMax);
else
return fmax(dSample, -dMax);
}
private:
double(*m_userFunction)(double);
unsigned int m_nSampleRate;
unsigned int m_nChannels;
unsigned int m_nBlockCount;
unsigned int m_nBlockSamples;
unsigned int m_nBlockCurrent;
T* m_pBlockMemory;
WAVEHDR* m_pWaveHeaders;
HWAVEOUT m_hwDevice;
thread m_thread;
atomic<bool> m_bReady;
atomic<unsigned int> m_nBlockFree;
condition_variable m_cvBlockNotZero;
mutex m_muxBlockNotZero;
atomic<double> m_dGlobalTime;
// Handler for soundcard request for more data
void waveOutProc(HWAVEOUT hWaveOut, UINT uMsg, DWORD dwParam1, DWORD dwParam2)
{
if (uMsg != WOM_DONE) return;
m_nBlockFree++;
unique_lock<mutex> lm(m_muxBlockNotZero);
m_cvBlockNotZero.notify_one();
}
// Static wrapper for sound card handler
static void CALLBACK waveOutProcWrap(HWAVEOUT hWaveOut, UINT uMsg, DWORD dwInstance, DWORD dwParam1, DWORD dwParam2)
{
((olcNoiseMaker*)dwInstance)->waveOutProc(hWaveOut, uMsg, dwParam1, dwParam2);
}
// Main thread. This loop responds to requests from the soundcard to fill 'blocks'
// with audio data. If no requests are available it goes dormant until the sound
// card is ready for more data. The block is fille by the "user" in some manner
// and then issued to the soundcard.
void MainThread()
{
m_dGlobalTime = 0.0;
double dTimeStep = 1.0 / (double)m_nSampleRate;
// Goofy hack to get maximum integer for a type at run-time
T nMaxSample = (T)pow(2, (sizeof(T) * 8) - 1) - 1;
double dMaxSample = (double)nMaxSample;
T nPreviousSample = 0;
while (m_bReady)
{
// Wait for block to become available
if (m_nBlockFree == 0)
{
unique_lock<mutex> lm(m_muxBlockNotZero);
m_cvBlockNotZero.wait(lm);
}
// Block is here, so use it
m_nBlockFree--;
// Prepare block for processing
if (m_pWaveHeaders[m_nBlockCurrent].dwFlags & WHDR_PREPARED)
waveOutUnprepareHeader(m_hwDevice, &m_pWaveHeaders[m_nBlockCurrent], sizeof(WAVEHDR));
T nNewSample = 0;
int nCurrentBlock = m_nBlockCurrent * m_nBlockSamples;
for (unsigned int n = 0; n < m_nBlockSamples; n++)
{
// User Process
if (m_userFunction == nullptr)
nNewSample = (T)(clip(UserProcess(m_dGlobalTime), 1.0) * dMaxSample);
else
nNewSample = (T)(clip(m_userFunction(m_dGlobalTime), 1.0) * dMaxSample);
m_pBlockMemory[nCurrentBlock + n] = nNewSample;
nPreviousSample = nNewSample;
m_dGlobalTime = m_dGlobalTime + dTimeStep;
}
// Send block to sound device
waveOutPrepareHeader(m_hwDevice, &m_pWaveHeaders[m_nBlockCurrent], sizeof(WAVEHDR));
waveOutWrite(m_hwDevice, &m_pWaveHeaders[m_nBlockCurrent], sizeof(WAVEHDR));
m_nBlockCurrent++;
m_nBlockCurrent %= m_nBlockCount;
}
}
}; | [
"56073739+LFCRab@users.noreply.github.com"
] | 56073739+LFCRab@users.noreply.github.com |
5c0df8f1493524758adc61f4a2cfa0556be26fba | ba9322f7db02d797f6984298d892f74768193dcf | /dds/src/model/DescribeParametersResult.cc | 93af7d773ce1e69dbc5f525d6a8008a88a8a6a9c | [
"Apache-2.0"
] | permissive | sdk-team/aliyun-openapi-cpp-sdk | e27f91996b3bad9226c86f74475b5a1a91806861 | a27fc0000a2b061cd10df09cbe4fff9db4a7c707 | refs/heads/master | 2022-08-21T18:25:53.080066 | 2022-07-25T10:01:05 | 2022-07-25T10:01:05 | 183,356,893 | 3 | 0 | null | 2019-04-25T04:34:29 | 2019-04-25T04:34:28 | null | UTF-8 | C++ | false | false | 3,745 | cc | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/dds/model/DescribeParametersResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Dds;
using namespace AlibabaCloud::Dds::Model;
DescribeParametersResult::DescribeParametersResult() :
ServiceResult()
{}
DescribeParametersResult::DescribeParametersResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
DescribeParametersResult::~DescribeParametersResult()
{}
void DescribeParametersResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto allConfigParameters = value["ConfigParameters"]["Parameter"];
for (auto value : allConfigParameters)
{
Parameter configParametersObject;
if(!value["ParameterName"].isNull())
configParametersObject.parameterName = value["ParameterName"].asString();
if(!value["ParameterValue"].isNull())
configParametersObject.parameterValue = value["ParameterValue"].asString();
if(!value["ModifiableStatus"].isNull())
configParametersObject.modifiableStatus = value["ModifiableStatus"].asString() == "true";
if(!value["ForceRestart"].isNull())
configParametersObject.forceRestart = value["ForceRestart"].asString() == "true";
if(!value["CheckingCode"].isNull())
configParametersObject.checkingCode = value["CheckingCode"].asString();
if(!value["ParameterDescription"].isNull())
configParametersObject.parameterDescription = value["ParameterDescription"].asString();
configParameters_.push_back(configParametersObject);
}
auto allRunningParameters = value["RunningParameters"]["Parameter"];
for (auto value : allRunningParameters)
{
Parameter runningParametersObject;
if(!value["ParameterName"].isNull())
runningParametersObject.parameterName = value["ParameterName"].asString();
if(!value["ParameterValue"].isNull())
runningParametersObject.parameterValue = value["ParameterValue"].asString();
if(!value["ModifiableStatus"].isNull())
runningParametersObject.modifiableStatus = value["ModifiableStatus"].asString() == "true";
if(!value["ForceRestart"].isNull())
runningParametersObject.forceRestart = value["ForceRestart"].asString() == "true";
if(!value["CheckingCode"].isNull())
runningParametersObject.checkingCode = value["CheckingCode"].asString();
if(!value["ParameterDescription"].isNull())
runningParametersObject.parameterDescription = value["ParameterDescription"].asString();
runningParameters_.push_back(runningParametersObject);
}
if(!value["Engine"].isNull())
engine_ = value["Engine"].asString();
if(!value["EngineVersion"].isNull())
engineVersion_ = value["EngineVersion"].asString();
}
std::vector<DescribeParametersResult::Parameter> DescribeParametersResult::getRunningParameters()const
{
return runningParameters_;
}
std::string DescribeParametersResult::getEngineVersion()const
{
return engineVersion_;
}
std::vector<DescribeParametersResult::Parameter> DescribeParametersResult::getConfigParameters()const
{
return configParameters_;
}
std::string DescribeParametersResult::getEngine()const
{
return engine_;
}
| [
"haowei.yao@alibaba-inc.com"
] | haowei.yao@alibaba-inc.com |
cdcacf3c016cd83efc73f043c0516111e1479c96 | 6876dc01c1697d2a5f3a21d174cb649ecdd7639a | /practicum.cpp | d65696cd4fd879a100fc415eb5c6b8065b05b273 | [] | no_license | alam2didar/C-Codes-Only- | eb5ede3e543ef6e2ee7f1b11ee2f0a05bfe37027 | 6059d456d150509d2d82ce242591470968b4f075 | refs/heads/master | 2020-12-29T07:55:53.993487 | 2020-02-05T18:53:32 | 2020-02-05T18:53:32 | 238,524,126 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,029 | cpp | #include <iostream>
#include <fstream>
using namespace std;
int main ()
{
cout << "Welcome to MIDN Alam's(150084) Program"<< endl;
cout << "Enter Filename: ";
double avg, navg,a1,a2;
int a ,b,point,pt,salary,sal;
salary=0;
point=0;
string filename, s,t,name,mvp;
char ch;
cin >> filename;
ifstream fin(filename.c_str());
while (fin>> a )
{ fin >> s >> b >> t;
cout << "Number of games in season:"<<b<< endl;
while (fin>> name)
{ point=0;
fin >> ch >>sal;
for (int i=0; i<b;i++)
{
fin >> pt;
point= point+ pt;
}
salary = salary+sal;
double avg= double(point)/b;
a2 = avg;
cout<< "Player "<< name<<" had "<< (double(point)/b) << " average per game."<< endl;
}
}
double avg1= double(point)/b;
a1 = avg1;
if (a2>a1)
{
mvp = name;
navg =a2;
}
cout << "Total salary for team: " << salary << endl;
cout<< "MVP player was "<< mvp << " with " << navg <<" average."<< endl;
return 0;
}
| [
"noreply@github.com"
] | alam2didar.noreply@github.com |
c675e15da71e37aef08d06849266b094309d5a2a | 864c4b0691cfff9d1fc970dbc4a60935fb81d51e | /src/alfvm/IO/lightSensor.h | c4c6525e4ac3bb99a93c946a8621d1eed5495a7d | [] | no_license | guillep19/frob | 7b4ecb1d3d54ef3160e999badb80228b05ac53ba | ca25fab485ca24bc2910161956fc5f5d961d3c98 | refs/heads/master | 2021-01-22T03:39:51.534803 | 2015-12-18T03:20:36 | 2015-12-18T03:20:36 | 19,125,922 | 0 | 1 | null | 2015-10-26T03:06:35 | 2014-04-24T22:14:09 | C | UTF-8 | C++ | false | false | 990 | h |
#ifndef lightSensor_H
#define lightSensor_H
//BH1750
//#define LIGHTSENSOR_ADDR_VCC 0x5C
#define LIGHTSENSOR_ADDR_VCC 0x46
#define LIGHTSENSOR_ADDR_GND 0x23
// No active state
#define BH1750_POWER_DOWN 0x00
// Wating for measurment command
#define BH1750_POWER_ON 0x01
// Reset data register value - not accepted in POWER_DOWN mode
#define BH1750_RESET 0x07
// Start measurement at 1lx resolution. Measurement time is approx 120ms.
#define BH1750_CONTINUOUS_HIGH_RES_MODE 0x10
// Start measurement at 0.5lx resolution. Measurement time is approx 120ms.
#define BH1750_CONTINUOUS_HIGH_RES_MODE_2 0x11
// Start measurement at 4lx resolution. Measurement time is approx 16ms.
#define BH1750_CONTINUOUS_LOW_RES_MODE 0x13
#include "mbed.h"
#include "FrobDefinitions.h"
class LightSensor {
private:
I2C iic;
int addr;
char buffer[2];
public:
LightSensor(PinName sda, PinName scl,
int addr, char mode);
WORD read();
};
#endif /* lightSensor_H */
| [
"kurco19@gmail.com"
] | kurco19@gmail.com |
f5d054a5d1f96202de5f9e849c1155e7ee93980b | cf7b884da75872a446bd7c0dc76a2e1ab64c2f61 | /test_demo/LocalPlayer.cpp | 5b9e9d1e4870fce7b6f4f2ed77a7963abe1b2cf8 | [] | no_license | tcll321/video_decoder | 5726eb623da798835d7f76b38f2a72aa6f5023ef | efb5b77ff0d8d29c4f491bc1bd10e2db1593f42c | refs/heads/master | 2020-04-08T07:33:57.043529 | 2019-10-29T08:13:12 | 2019-10-29T08:13:12 | 159,143,197 | 3 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,432 | cpp | #include "stdafx.h"
#include "LocalPlayer.h"
CLocalPlayer::CLocalPlayer(const char* url, HWND hwnd)
:CPlayer(url, hwnd)
, m_fileID(NULL)
, m_bRunning(false)
, m_hThread(NULL)
{
}
CLocalPlayer::~CLocalPlayer()
{
StopReadThread();
if (m_fileID)
{
Video_Close(m_fileID);
m_fileID = NULL;
}
}
int CLocalPlayer::Play()
{
FileApiErr err = FILE_API_OK;
err = Video_Open(&m_fileID, m_strUrl.c_str());
if (err == FILE_API_OK)
{
StartReadThread();
}
return err;
}
int CLocalPlayer::StartReadThread()
{
m_bRunning = true;
m_hThread = CreateThread(NULL, 0, threadRead, this, 0, NULL);
return 0;
}
void CLocalPlayer::StopReadThread()
{
m_bRunning = false;
if (m_hThread)
{
CloseHandle(m_hThread);
m_hThread = NULL;
}
}
DWORD CLocalPlayer::threadRead(void * param)
{
CLocalPlayer* pPlayer = (CLocalPlayer*)param;
if (pPlayer)
{
pPlayer->ReadWorker();
}
return 0;
}
void CLocalPlayer::ReadWorker()
{
while (m_bRunning)
{
char *data;
int len;
if (m_deqDataPacket.size() > 128)
{
Sleep(5);
continue;
}
if (FILE_API_OK == Video_Read(m_fileID, &data, &len))
{
if (len > 0)
{
DATAPACKET *pDataPacket = new DATAPACKET();
pDataPacket->data = new BYTE[len];
pDataPacket->dataLen = len;
memcpy(pDataPacket->data, data, len);
Video_DataFree(data);
CARAutoLock lock(m_lock);
m_deqDataPacket.push_back(pDataPacket);
}
}
else
{
Sleep(1);
}
}
}
| [
"liuchuntao@accusyschina.com"
] | liuchuntao@accusyschina.com |
9e9bc2da94d25e3463634b22bcd7deb119686968 | 0da7c56eac776a6977907dcfa3c50c3f4098aecc | /src/main/arduino/smart_exp/DisplaySpeedTask.h | 0b8439b18b5b74260a599ef4be325fab1caccaac | [
"Apache-2.0"
] | permissive | rbattistini/SmartExperiment | ccd259c6f7be979749fb13c9505cee9e496854bd | df1523dd4bdfad8655af19bdf974760daaa35796 | refs/heads/main | 2023-02-21T22:59:23.437574 | 2021-01-24T14:17:11 | 2021-01-24T14:17:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 616 | h | #ifndef __DISPLAYSPEED_TASK_H_
#define __DISPLAYSPEED_TASK_H_
#include "Task.h"
#include "EnumState.h"
#include "ComputeDataTask.h"
#include "ServoMotorImpl.h"
#include "MeasurementObserver.h"
class DisplaySpeedTask: public Task, public MeasurementObserver {
public:
DisplaySpeedTask(uint8_t pin);
void init(uint16_t period);
void tick();
void update(ComputeDataTask* task);
private:
const uint8_t maxSpeed = 20; // m/s
uint8_t pin;
float lastSpeed;
float currentSpeed;
EnumState currentState;
ServoMotorImpl* servoMotor;
};
#endif // __DISPLAYSPEED_TASK_H_ | [
"riccardo.battistini@protonmail.com"
] | riccardo.battistini@protonmail.com |
05f43473cf7e4c8d37da2b9aaf02e45eff9f23d9 | e5b813461918dfc5ad0c71989f8b3be3707d38f1 | /day-today codes/GeeksforGeeks/partition-problem.cpp | 4e1a21577d54a92ffa0132fdbd989a9435324b05 | [] | no_license | Shashank-Hiremath/Algorithmic-Problem-Solving-2019 | ca3267ff25d9c55f263e21833b69a12ac5cefce2 | 6350b97d6d341f970b370f7dfc691e284d6d3d52 | refs/heads/master | 2020-04-19T11:29:48.557850 | 2019-03-17T10:42:02 | 2019-03-17T10:42:02 | 168,169,068 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 858 | cpp | #include<iostream>
using namespace std;
bool findPartition(int arr[], int n)
{
int sum = 0;
int i, j;
for(i=0; i< n ;i++)
sum+=arr[i];
if(sum%2!=0)
return 0;
bool part[sum/2][n+1];
for(i=0;i<=n;i++)
part[0][i]=true;
for(i = 1; i<=sum/2; i++)
part[i][0] = false;
for(i=1;i<=sum/2;i++)
for(j=1;j<=n;j++)
{
part[i][j] = part[i][j-1];
if(i>=arr[j-1])
part[i][j] || part[i-arr[j-1]][j-1];
}
return part[sum/2];
}
int main()
{
int arr[] = {3,1,1,2,2,1};
int n = sizeof(arr)/sizeof(arr[0]);
if(findPartition(arr, n) == true)
printf("Can be divided into two subsets of equal sum\n");
else
printf("Can not be divide into two subsets of equal sum\n");
return 0;
} | [
"shashankhiremath11@gmail.com"
] | shashankhiremath11@gmail.com |
9c10779b6c8512da9501a452821602a3cfcccbfc | 57fe95824977ae32972aadf266655fd5ce5e5ebc | /MinStack.cpp | 55553260f82314cdb7695bb205c571c96b108ee6 | [] | no_license | rainlee/leetcode-jecklee | 6ae74f42a0e4abe648b1ca10832ee4b60877081d | 284f743b447e593997a64c0123c7a7e56d92bf88 | refs/heads/master | 2020-05-16T22:45:25.464144 | 2014-12-10T05:48:00 | 2014-12-10T05:48:00 | 20,227,034 | 2 | 1 | null | null | null | null | GB18030 | C++ | false | false | 3,201 | cpp | /*
_ooOoo_
o8888888o
88" . "88
(| -_- |)
O\ = /O
____/`---'\____
.' \\| |// `.
/ \\||| : |||// \
/ _||||| -:- |||||- \
| | \\\ - /// | |
| \_| ''\---/'' | |
\ .-\__ `-` ___/-. /
___`. .' /--.--\ `. . __
."" '< `.___\_<|>_/___.' >'"".
| | : `- \`.;`\ _ /`;.`/ - ` : | |
\ \ `-. \_ __\ /__ _/ .-` / /
======`-.____`-.___\_____/___.-`____.-'======
`=---='
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
God Bless Me BUG Free Forever
*/
/***
* 法1:O(n)空间
* 用两个栈数据栈和最小值栈
* 压栈时,数据栈压原值,最小值栈压当前最小值
* 用了stl stack 没有自己实现栈
***/
/*
class MinStack {
public:
void push(int x) {
sdata.push(x);
smin.push(((smin.empty() || (x < smin.top()))) ? x : smin.top());
}
void pop() {
if (!sdata.empty())
{
sdata.pop();
smin.pop();
}
}
int top() {
return sdata.top();
}
int getMin() {
return smin.top();
}
private:
stack<int> sdata;
stack<int> smin;
};
*/
/***
* 法1 Memory Limit Exceeded
* 法2:优化最小栈
* 当最小值不发生变化时,不用重复压最小栈,增加一个计数,记录最小值的次数(方便弹栈)
* 如果没有计数,-2 -2,当第二个-2 pop时,最小栈也会pop -2,出错
***/
/*
class MinStack {
public:
void push(int x) {
sdata.push(x);
if (smin.empty() || (x < smin.top().first))
smin.push(make_pair(x, 1));
else
smin.top().second++;
}
void pop() {
if (!sdata.empty())
{
sdata.pop();
if (--smin.top().second == 0)
smin.pop();
}
}
int top() {
return sdata.top();
}
int getMin() {
return smin.top().first;
}
private:
stack<int> sdata;
stack<pair<int, int> > smin; // (value, count)
};
*/
/***
* 法3: O(n)时间 O(1)空间
* 不用额外的最小栈,只用一个全局的minv记录最小值
* push时
* 当 x >= minv时,压入原值,minv不变
* 当 x < minv, 压入x - 2*minv(该值 < x),更新 minv = x
* pop时
* 当 s.top() >= minv,直接弹出
* 当 s.top() < minv,还原上一个最小值 minv = (minv - s.top()) / 2, 弹出minv
* top时
* 返回max(s.top(), minv)
* 注:可能会溢出……
***/
class MinStack {
public:
MinStack(): minv(0) {}
void push(int x) {
if (sdata.empty() || (x < minv))
{
sdata.push(x - 2*minv);
minv = x;
}
else
sdata.push(x);
}
void pop() {
if (!sdata.empty())
{
if (sdata.top() < minv)
minv = (minv - sdata.top()) / 2;
sdata.pop();
}
}
int top() {
return max(sdata.top(), minv);
}
int getMin() {
return minv;
}
private:
stack<int> sdata;
int minv;
}; | [
"leeht2008@gmail.com"
] | leeht2008@gmail.com |
d98740e685280f60c10bce33c00ccde99a7e3c36 | 05c2287474e67c7b92a1f723ae1870ee63994609 | /CalibrateProjector/addons/ofxOpenNI2/src/ofxOpenNI.cpp | 3fe528566cf9ec0d065f1221e067c7aa32569343 | [] | no_license | jvcleave/artandcode.Camera-and-projector-calibration | 81df5a3e33acfca9a449b1d9e034d476ab111c6e | cf40c41d27cd6e80fe7a892a7cf01cdcceca3a40 | refs/heads/master | 2021-01-18T10:44:38.479690 | 2012-02-02T16:10:30 | 2012-02-02T16:10:30 | 2,889,675 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,310 | cpp | /*
* ofxOpenNI.cpp
*
* Created on: 11/10/2011
* Author: arturo
*/
#include "ofxOpenNI.h"
#include <XnLog.h>
#include "ofxOpenNIUtils.h"
#include "ofLog.h"
string ofxOpenNI::LOG_NAME = "ofxOpenNI";
using namespace xn;
static bool rainbowPalletInit = false;
XnUInt8 PalletIntsR [256] = {0};
XnUInt8 PalletIntsG [256] = {0};
XnUInt8 PalletIntsB [256] = {0};
//----------------------------------------
static void CreateRainbowPallet() {
if(rainbowPalletInit) return;
unsigned char r, g, b;
for (int i=1; i<255; i++) {
if (i<=29) {
r = (unsigned char)(129.36-i*4.36);
g = 0;
b = (unsigned char)255;
}
else if (i<=86) {
r = 0;
g = (unsigned char)(-133.54+i*4.52);
b = (unsigned char)255;
}
else if (i<=141) {
r = 0;
g = (unsigned char)255;
b = (unsigned char)(665.83-i*4.72);
}
else if (i<=199) {
r = (unsigned char)(-635.26+i*4.47);
g = (unsigned char)255;
b = 0;
}
else {
r = (unsigned char)255;
g = (unsigned char)(1166.81-i*4.57);
b = 0;
}
PalletIntsR[i] = r;
PalletIntsG[i] = g;
PalletIntsB[i] = b;
}
rainbowPalletInit = true;
}
//----------------------------------------
ofxOpenNI::ofxOpenNI(){
CreateRainbowPallet();
g_bIsDepthOn = false;
g_bIsImageOn = false;
g_bIsIROn = false;
g_bIsAudioOn = false;
g_bIsPlayerOn = false;
g_pPrimary = NULL;
depth_coloring = COLORING_RAINBOW;
useTexture = true;
bGeneratePCColors = false;
bGeneratePCTexCoords = false;
}
void ofxOpenNI::initConstants(){
// Primary Streams
int nIndex = 0;
g_PrimaryStream.pValues[nIndex++] = "Any";
g_PrimaryStream.pValues[nIndex++] = xnProductionNodeTypeToString(XN_NODE_TYPE_DEPTH);
g_PrimaryStream.pValues[nIndex++] = xnProductionNodeTypeToString(XN_NODE_TYPE_IMAGE);
g_PrimaryStream.pValues[nIndex++] = xnProductionNodeTypeToString(XN_NODE_TYPE_IR);
g_PrimaryStream.pValues[nIndex++] = xnProductionNodeTypeToString(XN_NODE_TYPE_AUDIO);
g_PrimaryStream.nValuesCount = nIndex;
// Registration
nIndex = 0;
g_Registration.pValues[nIndex++] = FALSE;
g_Registration.pValueToName[FALSE] = "Off";
g_Registration.pValues[nIndex++] = TRUE;
g_Registration.pValueToName[TRUE] = "Depth -> Image";
g_Registration.nValuesCount = nIndex;
// Resolutions
nIndex = 0;
g_Resolution.pValues[nIndex++] = XN_RES_QVGA;
g_Resolution.pValueToName[XN_RES_QVGA] = Resolution(XN_RES_QVGA).GetName();
g_Resolution.pValues[nIndex++] = XN_RES_VGA;
g_Resolution.pValueToName[XN_RES_VGA] = Resolution(XN_RES_VGA).GetName();
g_Resolution.pValues[nIndex++] = XN_RES_SXGA;
g_Resolution.pValueToName[XN_RES_SXGA] = Resolution(XN_RES_SXGA).GetName();
g_Resolution.pValues[nIndex++] = XN_RES_UXGA;
g_Resolution.pValueToName[XN_RES_UXGA] = Resolution(XN_RES_UXGA).GetName();
g_Resolution.nValuesCount = nIndex;
}
//----------------------------------------
void ofxOpenNI::allocateDepthBuffers(){
if(g_bIsDepthOn){
max_depth = g_Depth.GetDeviceMaxDepth();
depthPixels[0].allocate(640,480,OF_IMAGE_COLOR_ALPHA);
depthPixels[1].allocate(640,480,OF_IMAGE_COLOR_ALPHA);
currentDepthPixels = &depthPixels[0];
backDepthPixels = &depthPixels[1];
if(useTexture) depthTexture.allocate(640,480,GL_RGBA);
}
}
//----------------------------------------
void ofxOpenNI::allocateDepthRawBuffers(){
if(g_bIsDepthRawOnOption){
depthRawPixels[0].allocate(640,480,OF_PIXELS_MONO);
depthRawPixels[1].allocate(640,480,OF_PIXELS_MONO);
currentDepthRawPixels = &depthRawPixels[0];
backDepthRawPixels = &depthRawPixels[1];
}
}
//----------------------------------------
void ofxOpenNI::allocateRGBBuffers(){
if(g_bIsImageOn){
rgbPixels[0].allocate(640,480,OF_IMAGE_COLOR);
rgbPixels[1].allocate(640,480,OF_IMAGE_COLOR);
currentRGBPixels = &rgbPixels[0];
backRGBPixels = &rgbPixels[1];
if(useTexture) rgbTexture.allocate(640,480,GL_RGB);
}
}
//----------------------------------------
void XN_CALLBACK_TYPE ofxOpenNI::onErrorStateChanged(XnStatus errorState, void* pCookie){
if (errorState != XN_STATUS_OK){
ofLogError(LOG_NAME) << xnGetStatusString(errorState);
//setErrorState(xnGetStatusString(errorState));
}else{
//setErrorState(NULL);
}
}
//----------------------------------------
void ofxOpenNI::openCommon(){
XnStatus nRetVal = XN_STATUS_OK;
g_bIsDepthOn = false;
g_bIsImageOn = false;
g_bIsIROn = false;
g_bIsAudioOn = false;
g_bIsPlayerOn = false;
g_bIsDepthRawOnOption = false;
NodeInfoList list;
nRetVal = g_Context.EnumerateExistingNodes(list);
if (nRetVal == XN_STATUS_OK)
{
for (NodeInfoList::Iterator it = list.Begin(); it != list.End(); ++it)
{
switch ((*it).GetDescription().Type)
{
case XN_NODE_TYPE_DEVICE:
ofLogVerbose(LOG_NAME) << "Creating device";
(*it).GetInstance(g_Device);
break;
case XN_NODE_TYPE_DEPTH:
ofLogVerbose(LOG_NAME) << "Creating depth generator";
g_bIsDepthOn = true;
g_bIsDepthRawOnOption = true;
(*it).GetInstance(g_Depth);
break;
case XN_NODE_TYPE_IMAGE:
ofLogVerbose(LOG_NAME) << "Creating image generator";
g_bIsImageOn = true;
(*it).GetInstance(g_Image);
break;
case XN_NODE_TYPE_IR:
ofLogVerbose(LOG_NAME) << "Creating ir generator";
g_bIsIROn = true;
(*it).GetInstance(g_IR);
break;
case XN_NODE_TYPE_AUDIO:
ofLogVerbose(LOG_NAME) << "Creating audio generator";
g_bIsAudioOn = true;
(*it).GetInstance(g_Audio);
break;
case XN_NODE_TYPE_PLAYER:
ofLogVerbose(LOG_NAME) << "Creating player";
g_bIsPlayerOn = true;
(*it).GetInstance(g_Player);
break;
}
}
}
XnCallbackHandle hDummy;
g_Context.RegisterToErrorStateChange(onErrorStateChanged, this, hDummy);
initConstants();
allocateDepthBuffers();
allocateDepthRawBuffers();
allocateRGBBuffers();
pointCloud.setMode(OF_PRIMITIVE_POINTS);
pointCloud.getVertices().resize(640*480);
int i=0;
for(int y=0;y<480;y++){
for(int x=0;x<640;x++){
pointCloud.getVertices()[i].set(float(x)/640.f,float(y)/480.f,0);
i++;
}
}
isPointCloudValid = false;
readFrame();
}
//----------------------------------------
void ofxOpenNI::addLicense(string sVendor, string sKey) {
XnLicense license = {0};
XnStatus status = XN_STATUS_OK;
status = xnOSStrNCopy(license.strVendor, sVendor.c_str(),sVendor.size(), sizeof(license.strVendor));
if(status != XN_STATUS_OK) {
ofLogError(LOG_NAME) << "ofxOpenNIContext error creating license (vendor)";
return;
}
status = xnOSStrNCopy(license.strKey, sKey.c_str(), sKey.size(), sizeof(license.strKey));
if(status != XN_STATUS_OK) {
ofLogError(LOG_NAME) << "ofxOpenNIContext error creating license (key)";
return;
}
status = g_Context.AddLicense(license);
SHOW_RC(status, "AddLicense");
xnPrintRegisteredLicenses();
}
//----------------------------------------
bool ofxOpenNI::setupFromXML(string xml, bool _threaded){
threaded = _threaded;
XnStatus nRetVal = XN_STATUS_OK;
EnumerationErrors errors;
nRetVal = g_Context.InitFromXmlFile(ofToDataPath(xml).c_str(), &errors);
SHOW_RC(nRetVal, "setup from XML");
if(nRetVal!=XN_STATUS_OK) return false;
openCommon();
if(threaded) startThread(true,false);
return true;
}
//----------------------------------------
bool ofxOpenNI::setupFromRecording(string recording, bool _threaded){
threaded = _threaded;
xnLogInitFromXmlFile(ofToDataPath("openni/config/ofxopenni_config.xml").c_str());
XnStatus nRetVal = g_Context.Init();
if(nRetVal!=XN_STATUS_OK) return false;
addLicense("PrimeSense", "0KOIk2JeIBYClPWVnMoRKn5cdY4=");
nRetVal =0;
//nRetVal = g_Context.OpenFileRecording(ofToDataPath(recording).c_str(), g_Player);
SHOW_RC(nRetVal, "setup from recording");
if(nRetVal!=XN_STATUS_OK) return false;
openCommon();
if(threaded) startThread(true,false);
return true;
}
//----------------------------------------
void ofxOpenNI::setDepthColoring(DepthColoring coloring){
depth_coloring = coloring;
}
//----------------------------------------
void ofxOpenNI::readFrame(){
XnStatus rc = XN_STATUS_OK;
if (g_pPrimary != NULL){
rc = g_Context.WaitOneUpdateAll(*g_pPrimary);
}else{
rc = g_Context.WaitAnyUpdateAll();
}
if (rc != XN_STATUS_OK){
ofLogError(LOG_NAME) << "Error:" << xnGetStatusString(rc);
}
if (g_Depth.IsValid()){
g_Depth.GetMetaData(g_DepthMD);
}
if (g_Image.IsValid()){
g_Image.GetMetaData(g_ImageMD);
}
if (g_IR.IsValid()){
g_IR.GetMetaData(g_irMD);
}
if (g_Audio.IsValid()){
g_Audio.GetMetaData(g_AudioMD);
}
if(g_bIsDepthOn){
generateDepthPixels();
}
if(g_bIsImageOn){
generateImagePixels();
}
if(threaded) lock();
if(g_bIsDepthOn){
swap(backDepthPixels,currentDepthPixels);
if (g_bIsDepthRawOnOption) {
swap(backDepthRawPixels,currentDepthRawPixels);
}
}
if(g_bIsImageOn){
swap(backRGBPixels,currentRGBPixels);
}
bNewPixels = true;
if(threaded) unlock();
}
//----------------------------------------
void ofxOpenNI::threadedFunction(){
while(isThreadRunning()){
readFrame();
}
}
//----------------------------------------
bool ofxOpenNI::isNewFrame(){
return bNewFrame;
}
//----------------------------------------
void ofxOpenNI::update(){
if(!threaded){
readFrame();
}else{
lock();
}
if(bNewPixels){
if(g_bIsDepthOn && useTexture){
depthTexture.loadData(*currentDepthPixels);
}
if(g_bIsImageOn && useTexture){
rgbTexture.loadData(*currentRGBPixels);
}
bNewPixels = false;
bNewFrame = true;
isPointCloudValid = false;
}
if(threaded){
unlock();
}
}
//----------------------------------------
bool ofxOpenNI::toggleCalibratedRGBDepth(){
// TODO: make work with IR generator
if (!g_Image.IsValid()) {
printf("No Image generator found: cannot register viewport");
return false;
}
// Toggle registering view point to image map
if (g_Depth.IsCapabilitySupported(XN_CAPABILITY_ALTERNATIVE_VIEW_POINT))
{
if(g_Depth.GetAlternativeViewPointCap().IsViewPointAs(g_Image)) {
disableCalibratedRGBDepth();
} else {
enableCalibratedRGBDepth();
}
} else return false;
return true;
}
//----------------------------------------
bool ofxOpenNI::enableCalibratedRGBDepth(){
if (!g_Image.IsValid()) {
ofLogError(LOG_NAME) << ("No Image generator found: cannot register viewport");
return false;
}
// Register view point to image map
if(g_Depth.IsCapabilitySupported(XN_CAPABILITY_ALTERNATIVE_VIEW_POINT)){
XnStatus result = g_Depth.GetAlternativeViewPointCap().SetViewPoint(g_Image);
SHOW_RC(result, "Register viewport");
if(result!=XN_STATUS_OK){
return false;
}
}else{
ofLogError(LOG_NAME) << ("Can't enable calibrated RGB depth, alternative viewport capability not supported");
return false;
}
return true;
}
//----------------------------------------
bool ofxOpenNI::disableCalibratedRGBDepth(){
// Unregister view point from (image) any map
if (g_Depth.IsCapabilitySupported(XN_CAPABILITY_ALTERNATIVE_VIEW_POINT)) {
XnStatus result = g_Depth.GetAlternativeViewPointCap().ResetViewPoint();
SHOW_RC(result, "Unregister viewport");
if(result!=XN_STATUS_OK) return false;
}else{
return false;
}
return true;
}
//----------------------------------------
void ofxOpenNI::generateImagePixels(){
xn::ImageMetaData imd;
g_Image.GetMetaData(imd);
const XnUInt8* pImage = imd.Data();
backRGBPixels->setFromPixels(pImage, imd.XRes(),imd.YRes(),OF_IMAGE_COLOR);
}
//----------------------------------------
void ofxOpenNI::draw(int x, int y){
depthTexture.draw(x,y);
}
//----------------------------------------
void ofxOpenNI::drawRGB(int x, int y){
rgbTexture.draw(x,y);
}
//----------------------------------------
void ofxOpenNI::generateDepthPixels(){
// get the pixels
const XnDepthPixel* depth = g_DepthMD.Data();
XN_ASSERT(depth);
if (g_DepthMD.FrameID() == 0) return;
// copy raw values
if (g_bIsDepthRawOnOption)
backDepthRawPixels->setFromPixels(depth, 640, 480, 1);
// copy depth into texture-map
float max;
for (XnUInt16 y = g_DepthMD.YOffset(); y < g_DepthMD.YRes() + g_DepthMD.YOffset(); y++) {
unsigned char * texture = backDepthPixels->getPixels() + y * g_DepthMD.XRes() * 4 + g_DepthMD.XOffset() * 4;
for (XnUInt16 x = 0; x < g_DepthMD.XRes(); x++, depth++, texture += 4) {
XnUInt8 red = 0;
XnUInt8 green = 0;
XnUInt8 blue = 0;
XnUInt8 alpha = 255;
XnUInt16 col_index;
switch (depth_coloring){
case COLORING_PSYCHEDELIC_SHADES:
alpha *= (((XnFloat)(*depth % 10) / 20) + 0.5);
case COLORING_PSYCHEDELIC:
switch ((*depth/10) % 10){
case 0:
red = 255;
break;
case 1:
green = 255;
break;
case 2:
blue = 255;
break;
case 3:
red = 255;
green = 255;
break;
case 4:
green = 255;
blue = 255;
break;
case 5:
red = 255;
blue = 255;
break;
case 6:
red = 255;
green = 255;
blue = 255;
break;
case 7:
red = 127;
blue = 255;
break;
case 8:
red = 255;
blue = 127;
break;
case 9:
red = 127;
green = 255;
break;
}
break;
case COLORING_RAINBOW:
col_index = (XnUInt16)(((*depth) / (max_depth / 256)));
red = PalletIntsR[col_index];
green = PalletIntsG[col_index];
blue = PalletIntsB[col_index];
break;
case COLORING_CYCLIC_RAINBOW:
col_index = (*depth % 256);
red = PalletIntsR[col_index];
green = PalletIntsG[col_index];
blue = PalletIntsB[col_index];
break;
case COLORING_BLUES:
// 3 bytes of depth: black (R0G0B0) >> blue (001) >> cyan (011) >> white (111)
max = 256+255+255;
col_index = (XnUInt16)(((*depth) / ( max_depth / max)));
if ( col_index < 256 )
{
blue = col_index;
green = 0;
red = 0;
}
else if ( col_index < (256+255) )
{
blue = 255;
green = (col_index % 256) + 1;
red = 0;
}
else if ( col_index < (256+255+255) )
{
blue = 255;
green = 255;
red = (col_index % 256) + 1;
}
else
{
blue = 255;
green = 255;
red = 255;
}
break;
case COLORING_GREY:
max = 255; // half depth
{
XnUInt8 a = (XnUInt8)(((*depth) / ( max_depth / max)));
red = a;
green = a;
blue = a;
}
break;
case COLORING_STATUS:
// This is something to use on installations
// when the end user needs to know if the camera is tracking or not
// The scene will be painted GREEN if status == true
// The scene will be painted RED if status == false
// Usage: declare a global bool status and that's it!
// I'll keep it commented so you dont have to have a status on every project
#if 0
{
extern bool status;
max = 255; // half depth
XnUInt8 a = 255 - (XnUInt8)(((*depth) / ( max_depth / max)));
red = ( status ? 0 : a);
green = ( status ? a : 0);
blue = 0;
}
#endif
break;
}
texture[0] = red;
texture[1] = green;
texture[2] = blue;
if (*depth == 0)
texture[3] = 0;
else
texture[3] = alpha;
}
}
}
//----------------------------------------
xn::Context & ofxOpenNI::getXnContext(){
return g_Context;
}
//----------------------------------------
xn::Device & ofxOpenNI::getDevice(){
return g_Device;
}
//----------------------------------------
xn::DepthGenerator & ofxOpenNI::getDepthGenerator(){
return g_Depth;
}
//----------------------------------------
xn::ImageGenerator & ofxOpenNI::getImageGenerator(){
return g_Image;
}
//----------------------------------------
xn::IRGenerator & ofxOpenNI::getIRGenerator(){
return g_IR;
}
//----------------------------------------
xn::AudioGenerator & ofxOpenNI::getAudioGenerator(){
return g_Audio;
}
//----------------------------------------
xn::Player & ofxOpenNI::getPlayer(){
return g_Player;
}
//----------------------------------------
xn::DepthMetaData & ofxOpenNI::getDepthMetaData(){
return g_DepthMD;
}
//----------------------------------------
xn::ImageMetaData & ofxOpenNI::getImageMetaData(){
return g_ImageMD;
}
//----------------------------------------
xn::IRMetaData & ofxOpenNI::getIRMetaData(){
return g_irMD;
}
//----------------------------------------
xn::AudioMetaData & ofxOpenNI::getAudioMetaData(){
return g_AudioMD;
}
//----------------------------------------
ofPixels & ofxOpenNI::getDepthPixels(){
Poco::ScopedLock<ofMutex> lock(mutex);
return *currentDepthPixels;
}
//----------------------------------------
ofShortPixels & ofxOpenNI::getDepthRawPixels(){
Poco::ScopedLock<ofMutex> lock(mutex);
if (!g_bIsDepthRawOnOption) {
ofLogWarning(LOG_NAME) << "g_bIsDepthRawOnOption was disabled, enabling raw pixels";
g_bIsDepthRawOnOption = true;
}
return *currentDepthRawPixels;
}
//----------------------------------------
ofPixels & ofxOpenNI::getRGBPixels(){
Poco::ScopedLock<ofMutex> lock(mutex);
return *currentRGBPixels;
}
//----------------------------------------
ofTexture & ofxOpenNI::getDepthTextureReference(){
return depthTexture;
}
//----------------------------------------
ofTexture & ofxOpenNI::getRGBTextureReference(){
return rgbTexture;
}
//----------------------------------------
void ofxOpenNI::setGeneratePCColors(bool generateColors){
bGeneratePCColors = generateColors;
if(bGeneratePCColors){
pointCloud.getColors().resize(640*480);
}else{
pointCloud.getColors().clear();
}
}
//----------------------------------------
void ofxOpenNI::setGeneratePCTexCoords(bool generateTexCoords){
bGeneratePCTexCoords = generateTexCoords;
if(bGeneratePCTexCoords){
pointCloud.getTexCoords().resize(640*480);
int i=0;
for(int y=0;y<480;y++){
for(int x=0;x<640;x++){
pointCloud.getTexCoords()[i].set(x,y);
i++;
}
}
}else{
pointCloud.getTexCoords().clear();
}
}
//----------------------------------------
ofMesh & ofxOpenNI::getPointCloud(){
if(!isPointCloudValid){
mutex.lock();
const XnDepthPixel * depth = g_DepthMD.Data();
for (XnUInt16 y = g_DepthMD.YOffset(); y < g_DepthMD.YRes() + g_DepthMD.YOffset(); y++) {
ofVec3f * pcDepth = &pointCloud.getVertices()[0] + y * g_DepthMD.XRes() + g_DepthMD.XOffset();
for (XnUInt16 x = 0; x < g_DepthMD.XRes(); x++, depth++, pcDepth++) {
pcDepth->z = (*depth)/max_depth;
}
}
if(g_bIsImageOn && bGeneratePCColors){
unsigned char * rgbColorPtr = currentRGBPixels->getPixels();
for(int i=0;i<(int)pointCloud.getColors().size();i++){
pointCloud.getColors()[i] = ofColor(*rgbColorPtr, *(rgbColorPtr+1), *(rgbColorPtr+2));
rgbColorPtr+=3;
}
}
mutex.unlock();
isPointCloudValid = true;
}
return pointCloud;
}
//----------------------------------------
float ofxOpenNI::getWidth(){
if(g_bIsDepthOn){
return g_DepthMD.XRes();
}else if(g_bIsImageOn){
return g_ImageMD.XRes();
}else if(g_bIsIROn){
return g_irMD.XRes();
}else{
ofLogWarning(LOG_NAME) << "getWidth() : We haven't yet initialised any generators, so this value returned is returned as 0";
return 0;
}
}
//----------------------------------------
float ofxOpenNI::getHeight(){
if(g_bIsDepthOn){
return g_DepthMD.YRes();
}else if(g_bIsImageOn){
return g_ImageMD.YRes();
}else if(g_bIsIROn){
return g_irMD.YRes();
}else{
ofLogWarning(LOG_NAME) << "getHeight() : We haven't yet initialised any generators, so this value returned is returned as 0";
return 0;
}
}
//----------------------------------------
ofPoint ofxOpenNI::worldToProjective(const ofPoint & p){
XnVector3D world = toXn(p);
return worldToProjective(world);
}
//----------------------------------------
ofPoint ofxOpenNI::worldToProjective(const XnVector3D & p){
XnVector3D proj;
g_Depth.ConvertRealWorldToProjective(1, &p, &proj);
return toOf(proj);
}
//----------------------------------------
ofPoint ofxOpenNI::projectiveToWorld(const ofPoint & p){
XnVector3D proj = toXn(p);
return projectiveToWorld(proj);
}
//----------------------------------------
ofPoint ofxOpenNI::projectiveToWorld(const XnVector3D & p){
XnVector3D world;
g_Depth.ConvertProjectiveToRealWorld(1, &p, &world);
return toOf(world);
}
//----------------------------------------
ofPoint ofxOpenNI::cameraToWorld(const ofVec2f & c){
vector<ofVec2f> vc(1, c);
vector<ofVec3f> vw(1);
cameraToWorld(vc, vw);
return vw[0];
}
//----------------------------------------
void ofxOpenNI::cameraToWorld(const vector<ofVec2f>& c, vector<ofVec3f>& w){
const int nPoints = c.size();
w.resize(nPoints);
if (!g_bIsDepthRawOnOption) {
ofLogError(LOG_NAME) << "ofxOpenNI::cameraToWorld - cannot perform this function if g_bIsDepthRawOnOption is false. You can enabled g_bIsDepthRawOnOption by calling getDepthRawPixels(..).";
return;
}
vector<XnPoint3D> projective(nPoints);
XnPoint3D *out = &projective[0];
if(threaded) lock();
const XnDepthPixel* d = currentDepthRawPixels->getPixels();
unsigned int pixel;
for (int i=0; i<nPoints; ++i) {
pixel = (int)c[i].x + (int)c[i].y * 640;
if (pixel >= 640*480)
continue;
projective[i].X = c[i].x;
projective[i].Y = c[i].y;
projective[i].Z = float(d[pixel]) / 1000.0f;
}
if(threaded) unlock();
g_Depth.ConvertProjectiveToRealWorld(nPoints, &projective[0], (XnPoint3D*)&w[0]);
}
| [
"jvcleave@gmail.com"
] | jvcleave@gmail.com |
b395e092fe3ec72c71b313107e6128cff694235d | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/CMake/CMake-gumtree/Kitware_CMake_repos_basic_block_block_21236.cpp | 5efeea3aa59abb983abb294add512d814661c4cd | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 53 | cpp | (allocate)
utf16_buffer = uv__malloc(max_len) | [
"993273596@qq.com"
] | 993273596@qq.com |
58aa3417b9200175a321c6c42e5f273b5c52b25e | faab784fab39991e8de59d1e5ebb642cd4c08864 | /tensorflow/compiler/xla/service/gpu/gemm_thunk.cc | a719dc9e2a1b5ab62c4b40e589214dbd91c3e9ef | [
"MIT",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | ashahab/tensorflow | 9e091a65ba3b3b4c5342c5ceede01b97c5f8f816 | 8ac05fdf0378fe852484c0cfd208f56b728e464f | refs/heads/master | 2021-06-18T02:49:12.311530 | 2021-05-13T16:12:27 | 2021-05-13T16:12:27 | 210,268,552 | 1 | 0 | Apache-2.0 | 2019-09-23T05:05:05 | 2019-09-23T05:05:04 | null | UTF-8 | C++ | false | false | 13,100 | cc | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/gpu/gemm_thunk.h"
#include <functional>
#include "absl/container/flat_hash_map.h"
#include "absl/types/optional.h"
#include "tensorflow/compiler/xla/primitive_util.h"
#include "tensorflow/compiler/xla/service/gpu/backend_configs.pb.h"
#include "tensorflow/compiler/xla/service/gpu/ir_emission_utils.h"
#include "tensorflow/compiler/xla/service/gpu/stream_executor_util.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/stream_executor/blas.h"
#include "tensorflow/stream_executor/device_memory.h"
namespace xla {
namespace gpu {
GpuGemmConfig GetGpuGemmConfig(const HloInstruction *gemm) {
GpuGemmConfig config;
config.output_shape = gemm->shape();
config.lhs_shape = gemm->operand(0)->shape();
config.rhs_shape = gemm->operand(1)->shape();
auto backend_config_or = gemm->backend_config<GemmBackendConfig>();
config.backend_config = std::move(backend_config_or.ValueOrDie());
return config;
}
GemmThunk::GemmThunk(ThunkInfo thunk_info, GpuGemmConfig config,
const BufferAllocation::Slice &lhs_buffer,
const BufferAllocation::Slice &rhs_buffer,
const BufferAllocation::Slice &output_buffer,
bool implements_whole_instruction)
: Thunk(Kind::kGemm, thunk_info),
config_(std::move(config)),
lhs_buffer_(lhs_buffer),
rhs_buffer_(rhs_buffer),
output_buffer_(output_buffer),
implements_whole_instruction_(implements_whole_instruction) {}
Status GemmThunk::ExecuteOnStream(const ExecuteParams ¶ms) {
auto get_device_address = [&](const BufferAllocation::Slice &slice) {
return params.buffer_allocations->GetDeviceAddress(slice);
};
VLOG(3) << "Running GEMM thunk";
se::DeviceMemoryBase lhs_data = get_device_address(lhs_buffer_);
se::DeviceMemoryBase rhs_data = get_device_address(rhs_buffer_);
se::DeviceMemoryBase output_data = get_device_address(output_buffer_);
return RunGemm(config_, lhs_data, rhs_data, output_data, params.stream,
implements_whole_instruction_, profile_index(),
params.profiler);
}
// This struct contains the metadata of a matrix, e.g., its base address and
// dimensions.
struct MatrixDescriptor {
se::DeviceMemoryBase data;
bool transpose; // Whether this matrix needs to be transposed.
int64 num_rows;
int64 num_cols;
};
// Converts from an XLA PrimitiveType to a blas::ComputationType, which is
// used to specify the precision with which matmul computations should be
// performed, separately from the precision of the inputs and result.
static absl::optional<se::blas::ComputationType> ComputationTypeFromPrimitive(
PrimitiveType type) {
switch (type) {
case F16:
// Use F32 as computation type for F16 as we currently only implement
// the cuDNN pseudo half configuration for half precision.
return se::blas::ComputationType::kF32;
case F32:
return se::blas::ComputationType::kF32;
case F64:
return se::blas::ComputationType::kF64;
case C64:
return se::blas::ComputationType::kComplexF32;
case C128:
return se::blas::ComputationType::kComplexF64;
default:
return absl::nullopt;
}
}
template <typename Element>
static Status DoGemmWithAlgorithm(
int64 batch_size, MatrixDescriptor lhs_matrix, MatrixDescriptor rhs_matrix,
MatrixDescriptor output_matrix, Element alpha, Element beta,
se::Stream *stream, absl::optional<se::blas::AlgorithmType> algorithm,
se::blas::ProfileResult *output_profile_result) {
CHECK(!output_matrix.transpose);
PrimitiveType type = primitive_util::NativeToPrimitiveType<Element>();
se::blas::ComputationType computation_type =
*ComputationTypeFromPrimitive(type);
se::blas::Transpose lhs_transpose = lhs_matrix.transpose
? se::blas::Transpose::kTranspose
: se::blas::Transpose::kNoTranspose;
se::blas::Transpose rhs_transpose = rhs_matrix.transpose
? se::blas::Transpose::kTranspose
: se::blas::Transpose::kNoTranspose;
int64 k = lhs_matrix.transpose ? lhs_matrix.num_rows : lhs_matrix.num_cols;
se::DeviceMemory<Element> lhs_data(lhs_matrix.data);
se::DeviceMemory<Element> rhs_data(rhs_matrix.data);
se::DeviceMemory<Element> output_data(output_matrix.data);
if (algorithm) {
// Autotuning is disabled for batch_size != 1.
CHECK_EQ(1, batch_size);
return stream->ThenBlasGemmWithAlgorithm(
lhs_transpose, rhs_transpose, output_matrix.num_rows,
output_matrix.num_cols,
/*size of reduce dim=*/k,
/*alpha=*/alpha, lhs_data,
/*leading dim of LHS=*/lhs_matrix.num_rows, rhs_data,
/*leading dim of RHS=*/rhs_matrix.num_rows,
/*beta=*/beta, &output_data,
/*leading dim of output=*/output_matrix.num_rows, computation_type,
*algorithm, output_profile_result);
}
if (batch_size != 1) {
int64 lhs_stride = lhs_matrix.num_rows * lhs_matrix.num_cols;
int64 rhs_stride = rhs_matrix.num_rows * rhs_matrix.num_cols;
int64 output_stride = output_matrix.num_rows * output_matrix.num_cols;
return stream->ThenBlasGemmStridedBatched(
lhs_transpose, rhs_transpose, output_matrix.num_rows,
output_matrix.num_cols, /*size of reduce dim=*/k,
/*alpha=*/alpha, lhs_data,
/*leading dim of LHS=*/lhs_matrix.num_rows, lhs_stride, rhs_data,
/*leading dim of RHS=*/rhs_matrix.num_rows, rhs_stride,
/*beta=*/beta, &output_data,
/*leading dim of output=*/output_matrix.num_rows, output_stride,
batch_size);
}
return stream->ThenBlasGemm(
lhs_transpose, rhs_transpose, output_matrix.num_rows,
output_matrix.num_cols, /*size of reduce dim=*/k,
/*alpha=*/alpha, lhs_data,
/*leading dim of LHS=*/lhs_matrix.num_rows, rhs_data,
/*leading dim of RHS=*/rhs_matrix.num_rows,
/*beta=*/beta, &output_data,
/*leading dim of output=*/output_matrix.num_rows);
}
Status RunGemm(const GpuGemmConfig &gemm_config,
se::DeviceMemoryBase lhs_buffer, se::DeviceMemoryBase rhs_buffer,
se::DeviceMemoryBase output_buffer, se::Stream *stream,
bool implements_whole_instruction,
absl::optional<int64> profile_index,
HloExecutionProfiler *profiler,
se::blas::ProfileResult *profile_result,
absl::optional<se::blas::AlgorithmType> algorithm) {
VLOG(2) << "Executing a GemmThunk";
const Shape &output_shape = gemm_config.output_shape;
const Shape &lhs_shape = gemm_config.lhs_shape;
const Shape &rhs_shape = gemm_config.rhs_shape;
const GemmBackendConfig &backend_config = gemm_config.backend_config;
const DotDimensionNumbers &dim_nums = backend_config.dot_dimension_numbers();
CHECK_EQ(dim_nums.lhs_batch_dimensions_size(),
dim_nums.rhs_batch_dimensions_size());
CHECK_EQ(dim_nums.lhs_batch_dimensions_size() + 2, output_shape.rank());
int64 row_dim = dim_nums.lhs_batch_dimensions_size();
int64 col_dim = dim_nums.lhs_batch_dimensions_size() + 1;
int64 batch_size = backend_config.batch_size();
// Check that the batch dims don't cover the last two dims.
for (int64 batch_dim : dim_nums.lhs_batch_dimensions()) {
CHECK_NE(row_dim, batch_dim);
CHECK_NE(col_dim, batch_dim);
}
// Verify that the non-batch dimensions are minor-most. This is required for
// efficient access.
for (const auto *shape : {&lhs_shape, &rhs_shape, &output_shape}) {
CHECK_LT(shape->layout().minor_to_major(row_dim), 2);
CHECK_LT(shape->layout().minor_to_major(col_dim), 2);
}
int64 output_num_rows = output_shape.dimensions(row_dim);
int64 output_num_cols = output_shape.dimensions(col_dim);
// BLAS gemm expects the inputs and the output are in column-major order.
// Therefore, we need to convert dot between row-major matrices to that
// between column-major matrices. The key insight for the conversion is that,
// in linear storage, matrix M in column-major order is identical to the
// transpose of M in row-major order. In other words,
//
// column-major(M) = row-major(M^T).
//
// Leveraging this insight, we can perform dot between row-major matrices as
// follows.
//
// row-major(C)
// = row-major(A x B) = column-major((A x B)^T) = column-major(B^T x A^T)
// = gemm(column-major(B^T), column-major(A^T))
// = gemm(row-major(B), row-major(A))
//
// Although we do not modify the content of A and B in linear memory, we
// should use the dimensions of B^T and A^T when calling gemm. For example,
// the leading dimension of the LHS matrix of gemm is the number of rows in
// B^T and thus the number of columns in B.
auto make_descriptor = [&](se::DeviceMemoryBase data, const Shape &shape,
bool transpose) -> MatrixDescriptor {
bool is_row_major = LayoutUtil::Minor(shape.layout(), row_dim) != 0;
bool layout_mismatch = LayoutUtil::Minor(shape.layout(), row_dim) !=
LayoutUtil::Minor(output_shape.layout(), row_dim);
return MatrixDescriptor{
data, static_cast<bool>(transpose ^ layout_mismatch),
shape.dimensions(row_dim + static_cast<int64>(is_row_major)),
shape.dimensions(row_dim + static_cast<int64>(!is_row_major))};
};
MatrixDescriptor lhs_matrix = make_descriptor(
lhs_buffer, lhs_shape, dim_nums.lhs_contracting_dimensions(0) == row_dim);
MatrixDescriptor rhs_matrix = make_descriptor(
rhs_buffer, rhs_shape, dim_nums.rhs_contracting_dimensions(0) == col_dim);
std::unique_ptr<ScopedInstructionProfiler> op_profiler =
profiler ? profiler->MakeScopedInstructionProfiler(
implements_whole_instruction ? profile_index : -1)
: nullptr;
if (LayoutUtil::Minor(output_shape.layout(), row_dim) != 0) {
std::swap(lhs_matrix, rhs_matrix);
std::swap(output_num_cols, output_num_rows);
}
const MatrixDescriptor output_matrix{output_buffer, /*needs_transpose=*/false,
output_num_rows, output_num_cols};
auto best_algorithm = [&]() -> absl::optional<se::blas::AlgorithmType> {
if (algorithm) {
return *algorithm;
}
if (backend_config.algorithm_case() ==
GemmBackendConfig::ALGORITHM_NOT_SET) {
return absl::nullopt;
}
return backend_config.selected_algorithm();
}();
complex128 alpha = {backend_config.alpha_real(), backend_config.alpha_imag()};
double beta = backend_config.beta();
switch (output_shape.element_type()) {
case F16:
CHECK_EQ(alpha.imag(), 0);
return DoGemmWithAlgorithm<Eigen::half>(
batch_size, lhs_matrix, rhs_matrix, output_matrix,
static_cast<Eigen::half>(alpha.real()),
static_cast<Eigen::half>(beta), stream, best_algorithm,
/*output_profile_result=*/profile_result);
case F32:
CHECK_EQ(alpha.imag(), 0);
return DoGemmWithAlgorithm<float>(
batch_size, lhs_matrix, rhs_matrix, output_matrix, alpha.real(), beta,
stream, best_algorithm,
/*output_profile_result=*/profile_result);
case F64:
CHECK_EQ(alpha.imag(), 0);
return DoGemmWithAlgorithm<double>(
batch_size, lhs_matrix, rhs_matrix, output_matrix, alpha.real(), beta,
stream, best_algorithm,
/*output_profile_result=*/profile_result);
case C64:
return DoGemmWithAlgorithm<complex64>(
batch_size, lhs_matrix, rhs_matrix, output_matrix,
static_cast<complex64>(alpha), static_cast<complex64>(beta), stream,
best_algorithm,
/*output_profile_result=*/profile_result);
case C128:
return DoGemmWithAlgorithm<complex128>(
batch_size, lhs_matrix, rhs_matrix, output_matrix, alpha,
static_cast<complex128>(beta), stream, best_algorithm,
/*output_profile_result=*/profile_result);
default:
return InternalError("Unexpected GEMM datatype: %s",
output_shape.ToString());
}
}
} // namespace gpu
} // namespace xla
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
d0f50bbce86a91edeae5e8477c7ae0a9b10be1ca | f4bf36b028ec408f3f265547186efe96206d1da6 | /ProfessionalCpp2e/c27_code/ArticleCitations/FirstAttempt/ArticleCitations.h | bfcc9600cca3a207c58c7f228f21489fab0f2b44 | [] | no_license | yeyuzhen/EasonCodeShare | 12f0dbe6a0debdb31174bab410e3c302ca1ff300 | f5ec605f095f06d67653d0b61fdcc639b3979bba | refs/heads/master | 2022-01-10T01:29:57.979716 | 2018-02-19T08:24:37 | 2018-02-19T08:24:37 | 10,100,458 | 14 | 14 | null | null | null | null | UTF-8 | C++ | false | false | 538 | h | #include <string>
using std::string;
class ArticleCitations
{
public:
ArticleCitations(const string& fileName);
virtual ~ArticleCitations();
ArticleCitations(const ArticleCitations& src);
ArticleCitations& operator=(const ArticleCitations& rhs);
string getArticle() const { return mArticle; }
size_t getNumCitations() const { return mNumCitations; }
string getCitation(size_t i) const { return mCitations[i]; }
protected:
void readFile(const string& fileName);
string mArticle;
string* mCitations;
size_t mNumCitations;
};
| [
"mail.yeyuzhen@gmail.com"
] | mail.yeyuzhen@gmail.com |
24dd6e36e390b841bcf87717c6804cfda65411f0 | 5e430b2b5e686e45408ed806ed6c3b85d0f17bd8 | /StudyTest/mapQianTao/STL/ContainerAdapter.cpp | ca3940e025de733941433da51bf82701fe1e8877 | [] | no_license | Z21459/OtherDemo | 71090ca3b90dce6f996928fee40adca4350ec6fa | 56aae2886e67563d0184d235214274577ba3cc2c | refs/heads/master | 2022-12-21T05:36:13.129717 | 2020-09-21T12:17:13 | 2020-09-21T12:17:13 | 292,588,386 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 834 | cpp | #include <iostream>
#include <stack>
#include <queue>
using namespace std;
/*
容器适配器
stack 栈 先进后出
queue 队列 先进先出
priority_queue 最高优先级总是第一个出列
适配器 是容器的接口 本身不直接保存元素 其保存元素机制是调用另一种顺序容器实现
可以看做适配器是保存一个容器 容器再保存元素
*/
int main2()
{
stack<int>s1;
s1.push(1);
s1.push(2);
s1.push(3);
while (s1.size()>0)
{
std::cout << s1.top() << endl;
s1.pop();
}
queue<int>q1;
q1.push(1);
q1.push(2);
while (q1.size())
{
std::cout << q1.front() << endl;
q1.pop();
}
priority_queue<int>pr1;
pr1.push(1);//默认大堆 就是逆向输出
pr1.push(2);
while (pr1.size())
{
std::cout << pr1.top() << endl;
pr1.pop();
}
system("pause");
return 0;
} | [
"51356477+Z21459@users.noreply.github.com"
] | 51356477+Z21459@users.noreply.github.com |
be2eba063e4677d8f640d6bd0ff31622c3c41619 | 32546edc31bb199da5eb579a5908d2d6102f4ef1 | /第九组教材管理系统包/TUMMS/TUMMS/Dialog_sendMail.cpp | 296199af7134277e6edbd4f7edd50a9b5537ab47 | [] | no_license | ZhaoBeiChen/Home-Work | 91ecb3f7f0ddab49eaa434c0a4e18554512a839b | 1ed85fcb2cc463bd330f5cc5e07e22718b97e9dc | refs/heads/master | 2020-05-27T21:16:32.390520 | 2017-03-13T09:08:27 | 2017-03-13T09:08:27 | 83,647,793 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 10,097 | cpp | // Dialog_sendMail.cpp : 实现文件
//
#include "stdafx.h"
#include "TUMMS.h"
#include "Dialog_sendMail.h"
#include "afxdialogex.h"
#include<string>
using namespace std;
extern control CONTROL;
extern CDBOperation dbOper;
extern bool bConn;
// CDialog_sendMail 对话框
IMPLEMENT_DYNAMIC(CDialog_sendMail, CDialogEx)
CDialog_sendMail::CDialog_sendMail(CWnd* pParent /*=NULL*/)
: CDialogEx(CDialog_sendMail::IDD, pParent)
, Sender_num(_T(""))
, Send_content(_T(""))
{
}
CDialog_sendMail::~CDialog_sendMail()
{
}
void CDialog_sendMail::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Text(pDX, IDC_EDIT1, Sender_num);
DDV_MaxChars(pDX, Sender_num, 30);
DDX_Text(pDX, IDC_EDIT2, Send_content);
DDV_MaxChars(pDX, Send_content, 420);
}
BEGIN_MESSAGE_MAP(CDialog_sendMail, CDialogEx)
ON_BN_CLICKED(IDC_BUTTON1, &CDialog_sendMail::OnBnClickedButton1)
ON_BN_CLICKED(IDCANCEL, &CDialog_sendMail::OnBnClickedCancel)
END_MESSAGE_MAP()
// CDialog_sendMail 消息处理程序
void CDialog_sendMail::OnBnClickedButton1()
{
// TODO: 在此添加控件通知处理程序代码
UpdateData(true);
USES_CONVERSION;
_RecordsetPtr pRst;
char sql[255] = { 0 };
char* temp;
CString num;
temp = T2A(Sender_num);
sprintf_s(sql,"select * from SYS_USER where sno = '%s'", temp);
pRst = dbOper.ExecuteWithResSQL(sql);
if (pRst == NULL)
{
MessageBox(CString("数据库查询出错!"));
CDialog_sendMail::OnCancel();
}
else if (pRst->adoEOF)
{
sprintf_s(sql, "select * from SYS_ADMIN where MNO = '%s'", temp);
pRst = dbOper.ExecuteWithResSQL(sql);
if (pRst == NULL)
{
MessageBox(CString("数据库查询出错!"));
CDialog_sendMail::OnCancel();
}
if (pRst->adoEOF)
{
sprintf_s(sql, "select * from SYS_MANAGE where BMNO = '%s'", temp);
pRst = dbOper.ExecuteWithResSQL(sql);
if (pRst == NULL)
{
MessageBox(CString("数据库查询出错!"));
CDialog_sendMail::OnCancel();
}
if (pRst->adoEOF)
{
MessageBox(CString("该联系人不存在!"));
}
else
{
CString count_1;
strcpy_s(sql, "select count(mno) count from SYS_MAIL");
pRst = dbOper.ExecuteWithResSQL(sql);
if (NULL == pRst)
{
CString alter("查询数据出现错误!");
CDialog_sendMail a;
a.MessageBox(alter);
}
else if (pRst->adoEOF)
{
pRst->Close();
CDialog_sendMail a;
CString alter("未查询到结果!");
a.MessageBox(alter);
}
else
{
pRst->MoveFirst(); //记录集指针移动到查询结果集的前面
_variant_t vCount;
while (!pRst->adoEOF)
{
vCount = pRst->GetCollect(_variant_t("count"));
string count = (LPCSTR)_bstr_t(vCount);
count_1 = count.c_str();
count_1.Remove(' ');
int i = _ttoi(count_1);
i = i + 1;
count_1.Format(_T("%d"), i);
if (i < 10)
{
CString a("000");
num = a + count_1;
}
else if (i < 100)
{
CString a("00");
num = a + count_1;
}
else if (i < 1000)
{
CString a("0");
num = a + count_1;
}
_RecordsetPtr pRst_1;
char sql_1[255] = { 0 };
char *temp;
while (true)
{
temp = T2A(num);
sprintf_s(sql_1, "select * from SYS_MAIL where mno = '%s'", temp);
pRst_1 = dbOper.ExecuteWithResSQL(sql_1);
if (pRst_1 == NULL)
{
MessageBox(CString("查询出错!"));
break;
}
else if (pRst_1->adoEOF)
{
break;
}
else
{
i = i + 1;
count_1.Format(_T("%d"), i);
if (i < 10)
{
CString a("000");
num = a + count_1;
}
else if (i < 100)
{
CString a("00");
num = a + count_1;
}
else if (i < 1000)
{
CString a("0");
num = a + count_1;
}
}
}
pRst->MoveNext();
}
}
char* temp_1;
char* temp_2;
char* temp_3;
char* temp_4;
temp_1 = T2A(CONTROL.land.returnNumber());
temp_2 = T2A(CONTROL.land.returnUsername());
temp_3 = T2A(num);
temp_4 = T2A(Send_content);
sprintf_s(sql, "insert into SYS_MAIL(mno,sender,receiver,content,sender_name,ifread) values('%s','%s','%s','%s','%s','1')", temp_3, temp_1, temp, temp_4, temp_2);
pRst = dbOper.ExecuteWithResSQL(sql);
if (pRst != NULL)
{
MessageBox(CString("发送成功!"));
CDialog_sendMail::OnOK();
}
else
{
MessageBox(CString("发送失败"));
CDialog_sendMail::OnCancel();
}
}
}
else
{
CString count_1;
strcpy_s(sql, "select count(mno) count from SYS_MAIL");
pRst = dbOper.ExecuteWithResSQL(sql);
if (NULL == pRst)
{
CString alter("查询数据出现错误!");
CDialog_sendMail a;
a.MessageBox(alter);
}
else if (pRst->adoEOF)
{
pRst->Close();
CDialog_sendMail a;
CString alter("未查询到结果!");
a.MessageBox(alter);
}
else
{
pRst->MoveFirst(); //记录集指针移动到查询结果集的前面
_variant_t vCount;
while (!pRst->adoEOF)
{
vCount = pRst->GetCollect(_variant_t("count"));
string count = (LPCSTR)_bstr_t(vCount);
count_1 = count.c_str();
count_1.Remove(' ');
int i = _ttoi(count_1);
i = i + 1;
count_1.Format(_T("%d"), i);
if (i < 10)
{
CString a("000");
num = a + count_1;
}
else if (i < 100)
{
CString a("00");
num = a + count_1;
}
else if (i < 1000)
{
CString a("0");
num = a + count_1;
}
_RecordsetPtr pRst_1;
char sql_1[255] = { 0 };
char *temp;
while (true)
{
temp = T2A(num);
sprintf_s(sql_1, "select * from SYS_MAIL where mno = '%s'", temp);
pRst_1 = dbOper.ExecuteWithResSQL(sql_1);
if (pRst_1 == NULL)
{
MessageBox(CString("查询出错!"));
break;
}
else if (pRst_1->adoEOF)
{
break;
}
else
{
i = i + 1;
count_1.Format(_T("%d"), i);
if (i < 10)
{
CString a("000");
num = a + count_1;
}
else if (i < 100)
{
CString a("00");
num = a + count_1;
}
else if (i < 1000)
{
CString a("0");
num = a + count_1;
}
}
}
pRst->MoveNext();
}
}
char* temp_1;
char* temp_2;
char* temp_3;
char* temp_4;
temp_1 = T2A(CONTROL.land.returnNumber());
temp_2 = T2A(CONTROL.land.returnUsername());
temp_3 = T2A(num);
temp_4 = T2A(Send_content);
sprintf_s(sql, "insert into SYS_MAIL(mno,sender,receiver,content,sender_name,ifread) values('%s','%s','%s','%s','%s','1')", temp_3, temp_1, temp, temp_4, temp_2);
pRst = dbOper.ExecuteWithResSQL(sql);
if (pRst != NULL)
{
MessageBox(CString("发送成功!"));
CDialog_sendMail::OnOK();
}
else
{
MessageBox(CString("发送失败"));
CDialog_sendMail::OnCancel();
}
}
}
else
{
CString count_1;
strcpy_s(sql, "select count(mno) count from SYS_MAIL");
pRst = dbOper.ExecuteWithResSQL(sql);
if (NULL == pRst)
{
CString alter("查询数据出现错误!");
CDialog_sendMail a;
a.MessageBox(alter);
}
else if (pRst->adoEOF)
{
pRst->Close();
CDialog_sendMail a;
CString alter("未查询到结果!");
a.MessageBox(alter);
}
else
{
pRst->MoveFirst(); //记录集指针移动到查询结果集的前面
_variant_t vCount;
while (!pRst->adoEOF)
{
vCount = pRst->GetCollect(_variant_t("count"));
string count = (LPCSTR)_bstr_t(vCount);
count_1 = count.c_str();
count_1.Remove(' ');
int i = _ttoi(count_1);
i = i + 1;
count_1.Format(_T("%d"), i);
if (i < 10)
{
CString a("000");
num = a + count_1;
}
else if (i < 100)
{
CString a("00");
num = a + count_1;
}
else if (i < 1000)
{
CString a("0");
num = a + count_1;
}
_RecordsetPtr pRst_1;
char sql_1[255] = { 0 };
char *temp;
while (true)
{
temp = T2A(num);
sprintf_s(sql_1, "select * from SYS_MAIL where mno = '%s'", temp);
pRst_1 = dbOper.ExecuteWithResSQL(sql_1);
if (pRst_1 == NULL)
{
MessageBox(CString("查询出错!"));
break;
}
else if (pRst_1->adoEOF)
{
break;
}
else
{
i = i + 1;
count_1.Format(_T("%d"), i);
if (i < 10)
{
CString a("000");
num = a + count_1;
}
else if (i < 100)
{
CString a("00");
num = a + count_1;
}
else if (i < 1000)
{
CString a("0");
num = a + count_1;
}
}
}
pRst->MoveNext();
}
}
char* temp_1;
char* temp_2;
char* temp_3;
char* temp_4;
temp_1 = T2A(CONTROL.land.returnNumber());
temp_2 = T2A(CONTROL.land.returnUsername());
temp_3 = T2A(num);
temp_4 = T2A(Send_content);
sprintf_s(sql, "insert into SYS_MAIL(mno,sender,receiver,content,sender_name,ifread) values('%s','%s','%s','%s','%s','1')", temp_3,temp_1,temp,temp_4,temp_2);
pRst = dbOper.ExecuteWithResSQL(sql);
if (pRst != NULL)
{
MessageBox(CString("发送成功!"));
CDialog_sendMail::OnOK();
}
else
{
MessageBox(CString("发送失败"));
CDialog_sendMail::OnCancel();
}
}
}
void CDialog_sendMail::OnBnClickedCancel()
{
// TODO: 在此添加控件通知处理程序代码
CDialogEx::OnCancel();
}
| [
"zhaobeichen@imudges.com"
] | zhaobeichen@imudges.com |
ac87d0ecf3eebf322a3db83403c5cc21c091c197 | aecd4e947f1295ccfc877fd4c84aacf3a91ea3fa | /src/objimporter.cpp | 1cdf3315ffec6a3260d38927a55212f7fc927c20 | [
"MIT"
] | permissive | jiaguobing/ogre-v2-mesh-viewer | c4d43b8f3980d4d3984f0cf78895c2959211b375 | 21b5b98c984f0f7da6db3e1273eee70761af92d9 | refs/heads/master | 2021-03-25T16:18:35.543878 | 2020-01-14T06:18:04 | 2020-01-14T06:18:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,529 | cpp |
#include "stdafx.h"
#include "objimporter.h"
#define TINYOBJLOADER_IMPLEMENTATION
#include "tiny_obj_loader.h"
#include <QTemporaryDir>
#include <QXmlStreamWriter>
#include <QVector3D>
#include <QProgressDialog>
#include <QApplication>
#include "OgreMesh2.h"
#include "OgreMeshManager.h"
#include "OgreMeshManager2.h"
#include "OgreMesh2Serializer.h"
#include "OgreSubMesh2.h"
#include "OgreHlmsManager.h"
#include "OgreHlmsTextureManager.h"
#include "OgreHlmsPbs.h"
#include "OgreHlmsPbsDatablock.h"
#include "OgreHlmsJsonPbs.h"
#include "OgreXML/OgreXMLMeshSerializer.h"
#ifdef PROFILING
#define CLOCK_LINENUM_CAT( name, ln ) name##ln
#define CLOCK_LINENUM( name, ln ) CLOCK_LINENUM_CAT( name, ln )
#define CLOCK_BEGIN CLOCK_LINENUM(t1, __LINE__, begin_section)
#define CLOCK_END CLOCK_LINENUM(t2, __LINE__, end_section)
#define PROFILE( f ) \
clock_t CLOCK_BEGIN = clock(); \
f; \
clock_t CLOCK_END = clock(); \
qDebug() << #f << ": Use" << float( CLOCK_END - CLOCK_BEGIN ) / CLOCKS_PER_SEC << "sec";
#else
#define PROFILE( f ) f
#endif
bool operator<(const UniqueIndex& l, const UniqueIndex& r)
{
return std::tie(l.v, l.n, l.t) < std::tie(r.v, r.n, r.t);
}
bool operator==(const OgreDataVertex& l, const OgreDataVertex& r)
{
return
l.position[0] == r.position[0] &&
l.position[1] == r.position[1] &&
l.position[2] == r.position[2] &&
l.normal[0] == r.normal[0] &&
l.normal[1] == r.normal[1] &&
l.normal[2] == r.normal[2] &&
l.texcoord[0] == r.texcoord[0] &&
l.texcoord[1] == r.texcoord[1];
}
namespace std
{
template<> struct hash<OgreDataVertex>
{
size_t operator()(OgreDataVertex const& vertex) const
{
size_t ret = hash<float>()(vertex.position[0]);
ret = ret ^ (hash<float>()(vertex.position[1]) << 1);
ret = ret ^ (hash<float>()(vertex.position[2]) >> 1);
ret = ret << 1;
ret = ret ^ (hash<float>()(vertex.normal[0]) << 1);
ret = ret ^ (hash<float>()(vertex.normal[1]) >> 1);
ret = ret ^ (hash<float>()(vertex.normal[2]) << 1);
ret = ret >> 1;
ret = ret ^ (hash<float>()(vertex.texcoord[0]) << 1);
ret = ret ^ (hash<float>()(vertex.texcoord[1]) >> 1);
return ret;
}
};
}
ObjImporter::ObjImporter()
{
}
Ogre::MeshPtr ObjImporter::import(const QString& sObjFile, bool showProgress)
{
QFileInfo info(sObjFile);
mFileName = info.fileName();
QProgressDialog progress(nullptr, Qt::Dialog | Qt::WindowTitleHint);
progress.setLabelText(QString("Converting %1...").arg(info.fileName()));
progress.setRange(0, 100);
progress.setModal(true);
progress.show();
QApplication::processEvents();
std::string sError;
std::string sMtlBasePath = info.absolutePath().toStdString() + "/";
PROFILE(bool b = tinyobj::LoadObj(&mObjAttrib, &mTinyObjShapes, &mTinyObjMaterials, &sError, sObjFile.toStdString().c_str(), sMtlBasePath.c_str(), true));
if (!sError.empty())
{
qDebug() << "Error:" << sError.c_str();
}
progress.setValue(10);
QApplication::processEvents();
for (tinyobj::material_t& mtl : mTinyObjMaterials)
{
if (mImportedMaterials.count(mtl.name) == 0)
{
importMaterial(mtl);
mImportedMaterials.insert(mtl.name);
}
}
progress.setValue(30);
QApplication::processEvents();
convertToOgreData();
progress.setValue(40);
QApplication::processEvents();
Ogre::MeshPtr mesh = createOgreMeshes();
progress.setValue(80);
QApplication::processEvents();
return mesh;
}
OgreDataVertex ObjImporter::getVertex(const tinyobj::index_t& index)
{
OgreDataVertex v1;
{
float posX = mObjAttrib.vertices[index.vertex_index * 3 + 0];
float posY = mObjAttrib.vertices[index.vertex_index * 3 + 1];
float posZ = mObjAttrib.vertices[index.vertex_index * 3 + 2];
v1.position[0] = posX;
v1.position[1] = posY;
v1.position[2] = posZ;
if (index.normal_index != -1)
{
float normalX = mObjAttrib.normals[index.normal_index * 3 + 0];
float normalY = mObjAttrib.normals[index.normal_index * 3 + 1];
float normalZ = mObjAttrib.normals[index.normal_index * 3 + 2];
v1.normal[0] = normalX;
v1.normal[1] = normalY;
v1.normal[2] = normalZ;
}
else
{
//v1.bNeedGenerateNormals = true;
}
if (index.texcoord_index != -1)
{
float texCoordU = mObjAttrib.texcoords[index.texcoord_index * 2 + 0];
float texCoordV = mObjAttrib.texcoords[index.texcoord_index * 2 + 1];
v1.texcoord[0] = texCoordU;
v1.texcoord[1] = 1.0 - texCoordV;
}
else
{
v1.texcoord[0] = 0;
v1.texcoord[1] = 0;
}
}
return v1;
}
Ogre::MeshPtr ObjImporter::createOgreMeshes()
{
Ogre::Root& root = Ogre::Root::getSingleton();
Ogre::RenderSystem* renderSystem = root.getRenderSystem();
Ogre::VaoManager* vaoManager = renderSystem->getVaoManager();
//Create the mesh
Ogre::MeshPtr mesh = Ogre::MeshManager::getSingleton().createManual(
mFileName.toStdString(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
//Create one submesh
for (const OgreDataSubMesh& m : mOgreSubMeshes)
{
Ogre::SubMesh* subMesh = mesh->createSubMesh();
//Vertex declaration
Ogre::VertexElement2Vec vertexElements
{
Ogre::VertexElement2(Ogre::VET_FLOAT3, Ogre::VES_POSITION),
Ogre::VertexElement2(Ogre::VET_FLOAT3, Ogre::VES_NORMAL),
Ogre::VertexElement2(Ogre::VET_FLOAT2, Ogre::VES_TEXTURE_COORDINATES)
};
//For immutable buffers, it is mandatory that cubeVertices is not a null pointer.
auto vBuffer = reinterpret_cast<OgreDataVertex*>(OGRE_MALLOC_SIMD(sizeof(OgreDataVertex) * m.vertices.size(),
Ogre::MEMCATEGORY_GEOMETRY));
//Fill the data.
memcpy(vBuffer, m.vertices.data(), sizeof(OgreDataVertex) * m.vertices.size());
Ogre::VertexBufferPacked* vertexBuffer = 0;
try
{
// Create the actual vertex buffer.
vertexBuffer = vaoManager->createVertexBuffer(vertexElements, m.vertices.size(),
Ogre::BT_IMMUTABLE,
vBuffer, true);
}
catch (Ogre::Exception &e)
{
OGRE_FREE_SIMD(vertexBuffer, Ogre::MEMCATEGORY_GEOMETRY);
vertexBuffer = 0;
}
Ogre::VertexBufferPackedVec vertexBuffers{ vertexBuffer };
auto iBuffer = reinterpret_cast<Ogre::uint32*>(OGRE_MALLOC_SIMD(sizeof(Ogre::uint32) * m.indexes.size(),
Ogre::MEMCATEGORY_GEOMETRY));
memcpy(iBuffer, m.indexes.data(), sizeof(Ogre::uint32) * m.indexes.size());
Ogre::IndexBufferPacked* indexBuffer;
try
{
indexBuffer = vaoManager->createIndexBuffer(Ogre::IndexBufferPacked::IT_32BIT,
m.indexes.size(),
Ogre::BT_IMMUTABLE,
iBuffer, true);
}
catch (Ogre::Exception &e)
{
// When keepAsShadow = true, the memory will be freed when the index buffer is destroyed.
// However if for some weird reason there is an exception raised, the memory will
// not be freed, so it is up to us to do so.
// The reasons for exceptions are very rare. But we're doing this for correctness.
OGRE_FREE_SIMD(indexBuffer, Ogre::MEMCATEGORY_GEOMETRY);
indexBuffer = 0;
//throw e;
}
Ogre::VertexArrayObject* vao = vaoManager->createVertexArrayObject(vertexBuffers, indexBuffer, Ogre::OT_TRIANGLE_LIST);
//Each Vao pushed to the vector refers to an LOD level.
//Must be in sync with mesh->mLodValues & mesh->mNumLods if you use more than one level
subMesh->mVao[Ogre::VpNormal].push_back(vao);
//Use the same geometry for shadow casting.
subMesh->mVao[Ogre::VpShadow].push_back(vao);
}
//Set the bounds to get frustum culling and LOD to work correctly.
Ogre::Aabb aabb = mOgreSubMeshes[0].aabb;
for (OgreDataSubMesh& m : mOgreSubMeshes)
{
aabb.merge(m.aabb);
}
mesh->_setBounds(aabb);
return mesh;
}
void ObjImporter::convertToOgreData()
{
mOgreSubMeshes.clear();
for (int s = 0; s < mTinyObjShapes.size(); ++s)
{
tinyobj::mesh_t& mesh01 = mTinyObjShapes[s].mesh;
qDebug() << " Converting Mesh=" << mTinyObjShapes[s].name.c_str();
qDebug() << " face count=" << mesh01.indices.size() / 3;
Q_ASSERT(mesh01.indices.size() % 3 == 0);
std::vector<OgreDataVertex> verticesVec;
std::vector<int32_t> indexesVec;
std::unordered_map<OgreDataVertex, uint32_t> uniqueVertices;
// build indexes
for (tinyobj::index_t& i : mesh01.indices)
{
OgreDataVertex v = getVertex(i);
if (uniqueVertices.count(v) == 0)
{
uniqueVertices[v] = verticesVec.size();
verticesVec.push_back(v);
}
indexesVec.push_back(uniqueVertices[v]);
}
OgreDataSubMesh subMesh;
subMesh.meshName = mTinyObjShapes[s].name;
subMesh.vertices = verticesVec;
subMesh.indexes = indexesVec;
subMesh.bNeedGenerateNormals = (mesh01.indices[0].normal_index == -1);
if (subMesh.bNeedGenerateNormals)
{
generateNormalVectors(OUT subMesh);
}
if (mZUpToYUp)
{
convertFromZUpToYUp(subMesh);
}
generateAABB(subMesh);
if (mesh01.material_ids[0] >= 0)
{
subMesh.material = mTinyObjMaterials[mesh01.material_ids[0]].name;
}
subMesh.meshName = mTinyObjShapes[s].name;
mOgreSubMeshes.push_back(subMesh);
QApplication::processEvents();
}
}
void AssignVector(float f[3], const Ogre::Vector3& v)
{
f[0] = v.x;
f[1] = v.y;
f[2] = v.z;
}
void ObjImporter::generateNormalVectors(OgreDataSubMesh& submesh)
{
struct NormalSum
{
Ogre::Vector3 normal{ 0, 0, 0 };
int count = 0;
};
std::vector<NormalSum> normalSums;
normalSums.resize(submesh.vertices.size());
for (int i = 0; i < submesh.indexes.size(); i += 3)
{
Ogre::Vector3 p1(submesh.vertices[submesh.indexes[i + 0]].position);
Ogre::Vector3 p2(submesh.vertices[submesh.indexes[i + 1]].position);
Ogre::Vector3 p3(submesh.vertices[submesh.indexes[i + 2]].position);
Ogre::Vector3 v1 = p2 - p1;
Ogre::Vector3 v2 = p3 - p1;
Ogre::Vector3 theNormal = v2.crossProduct(v1);
theNormal.normalise();
normalSums[submesh.indexes[i + 0]].normal += theNormal;
normalSums[submesh.indexes[i + 0]].count += 1;
normalSums[submesh.indexes[i + 1]].normal += theNormal;
normalSums[submesh.indexes[i + 1]].count += 1;
normalSums[submesh.indexes[i + 2]].normal += theNormal;
normalSums[submesh.indexes[i + 2]].count += 1;
}
for (NormalSum& n : normalSums)
{
n.normal = n.normal / float(n.count);
}
for (int i = 0; i < submesh.vertices.size(); ++i)
{
AssignVector(submesh.vertices[i].normal, normalSums[i].normal);
}
}
void ObjImporter::convertFromZUpToYUp(OgreDataSubMesh& submesh)
{
for (OgreDataVertex& v : submesh.vertices)
{
std::swap(v.position[1], v.position[2]);
std::swap(v.normal[1], v.normal[2]);
v.position[2] = -v.position[2];
v.normal[2] = -v.normal[2];
}
}
void ObjImporter::generateAABB(OgreDataSubMesh& submesh)
{
Ogre::Vector3 minPos(99999, 99999, 99999);
Ogre::Vector3 maxPos(-99999, -99999, -99999);
for (const OgreDataVertex& v : submesh.vertices)
{
Ogre::Vector3 pos(v.position[0], v.position[1], v.position[2]);
minPos.x = std::min(pos.x, minPos.x);
minPos.y = std::min(pos.y, minPos.y);
minPos.z = std::min(pos.z, minPos.z);
maxPos.x = std::max(pos.x, maxPos.x);
maxPos.y = std::max(pos.y, maxPos.y);
maxPos.z = std::max(pos.z, maxPos.z);
}
submesh.aabb = Ogre::Aabb::newFromExtents(minPos, maxPos);
}
Ogre::HlmsPbsDatablock* ObjImporter::importMaterial(const tinyobj::material_t& srcMtl)
{
Ogre::Root& root = Ogre::Root::getSingleton();
Ogre::HlmsManager* hlmsManager = root.getHlmsManager();
Ogre::HlmsTextureManager* hlmsTextureManager = hlmsManager->getTextureManager();
Q_ASSERT(dynamic_cast<Ogre::HlmsPbs*>(hlmsManager->getHlms(Ogre::HLMS_PBS)));
Ogre::HlmsPbs* hlmsPbs = static_cast<Ogre::HlmsPbs*>(hlmsManager->getHlms(Ogre::HLMS_PBS));
std::string strBlockName(srcMtl.name);
Ogre::HlmsPbsDatablock* datablock = nullptr;
if (strBlockName.empty())
{
static int counter = 0;
std::ostringstream sout;
sout << "obj_mtl_" << counter;
strBlockName = sout.str();
counter++;
}
try
{
datablock = static_cast<Ogre::HlmsPbsDatablock*>(
hlmsPbs->createDatablock(strBlockName, strBlockName,
Ogre::HlmsMacroblock(),
Ogre::HlmsBlendblock(),
Ogre::HlmsParamVec()));
}
catch (std::exception& e)
{
qDebug() << "Cannot create datablock." << e.what();
return nullptr;
}
Ogre::HlmsSamplerblock samplerBlock;
samplerBlock.setAddressingMode(Ogre::TAM_WRAP);
samplerBlock.setFiltering(Ogre::TFO_ANISOTROPIC);
datablock->setWorkflow(Ogre::HlmsPbsDatablock::MetallicWorkflow);
auto envMap = hlmsTextureManager->createOrRetrieveTexture("env.dds", Ogre::HlmsTextureManager::TEXTURE_TYPE_ENV_MAP);
datablock->setTexture(Ogre::PBSM_REFLECTION, envMap.xIdx, envMap.texture);
datablock->setDiffuse(Ogre::Vector3(srcMtl.diffuse[0], srcMtl.diffuse[1], srcMtl.diffuse[2]));
datablock->setBackgroundDiffuse(Ogre::ColourValue(1, 1, 1, 1));
datablock->setSpecular(Ogre::Vector3(srcMtl.specular[0], srcMtl.specular[1], srcMtl.specular[2]));
datablock->setRoughness(srcMtl.roughness);
datablock->setMetalness(srcMtl.metallic);
if (!srcMtl.diffuse_texname.empty())
{
auto tex = hlmsTextureManager->createOrRetrieveTexture(srcMtl.diffuse_texname, Ogre::HlmsTextureManager::TEXTURE_TYPE_DIFFUSE);
datablock->setTexture(Ogre::PBSM_DIFFUSE, tex.xIdx, tex.texture);
datablock->setSamplerblock(Ogre::PBSM_DIFFUSE, samplerBlock);
}
if (!srcMtl.specular_texname.empty())
{
auto tex = hlmsTextureManager->createOrRetrieveTexture(srcMtl.specular_texname, Ogre::HlmsTextureManager::TEXTURE_TYPE_DIFFUSE);
datablock->setTexture(Ogre::PBSM_SPECULAR, tex.xIdx, tex.texture);
datablock->setSamplerblock(Ogre::PBSM_SPECULAR, samplerBlock);
}
if (!srcMtl.roughness_texname.empty())
{
auto tex = hlmsTextureManager->createOrRetrieveTexture(srcMtl.roughness_texname, Ogre::HlmsTextureManager::TEXTURE_TYPE_MONOCHROME);
datablock->setTexture(Ogre::PBSM_ROUGHNESS, tex.xIdx, tex.texture);
datablock->setSamplerblock(Ogre::PBSM_ROUGHNESS, samplerBlock);
}
if (!srcMtl.metallic_texname.empty())
{
auto tex = hlmsTextureManager->createOrRetrieveTexture(srcMtl.metallic_texname, Ogre::HlmsTextureManager::TEXTURE_TYPE_MONOCHROME);
datablock->setTexture(Ogre::PBSM_METALLIC, tex.xIdx, tex.texture);
datablock->setSamplerblock(Ogre::PBSM_METALLIC, samplerBlock);
}
if (!srcMtl.normal_texname.empty())
{
auto tex = hlmsTextureManager->createOrRetrieveTexture(srcMtl.normal_texname, Ogre::HlmsTextureManager::TEXTURE_TYPE_NORMALS);
datablock->setTexture(Ogre::PBSM_NORMAL, tex.xIdx, tex.texture);
datablock->setSamplerblock(Ogre::PBSM_NORMAL, samplerBlock);
}
return datablock;
}
| [
"chchwy@gmail.com"
] | chchwy@gmail.com |
debbb67f77d4c5010e1787286fe1029e6280b809 | c475cd8531a94ffae69cc92371d41531dbbddb6c | /Libraries/breakpad/src/client/windows/crash_generation/minidump_generator.h | a3c123056fa954ff38518773a3fc5f0bd9aa0753 | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown",
"BSD-3-Clause",
"LicenseRef-scancode-unicode-mappings"
] | permissive | WolfireGames/overgrowth | 72d3dd29cbd7254337265c29f8de3e5c32400114 | 594a2a4f9da0855304ee8cd5335d042f8e954ce1 | refs/heads/main | 2023-08-15T19:36:56.156578 | 2023-05-17T08:17:53 | 2023-05-17T08:20:36 | 467,448,492 | 2,264 | 245 | Apache-2.0 | 2023-05-09T07:29:58 | 2022-03-08T09:38:54 | C++ | UTF-8 | C++ | false | false | 7,511 | h | // Copyright (c) 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef CLIENT_WINDOWS_CRASH_GENERATION_MINIDUMP_GENERATOR_H_
#define CLIENT_WINDOWS_CRASH_GENERATION_MINIDUMP_GENERATOR_H_
#include <windows.h>
#include <dbghelp.h>
#include <rpc.h>
#include <list>
#include <string>
#include "google_breakpad/common/minidump_format.h"
namespace google_breakpad {
// Abstraction for various objects and operations needed to generate
// minidump on Windows. This abstraction is useful to hide all the gory
// details for minidump generation and provide a clean interface to
// the clients to generate minidumps.
class MinidumpGenerator {
public:
// Creates an instance with the given parameters.
// is_client_pointers specifies whether the exception_pointers and
// assert_info point into the process that is being dumped.
// Before calling WriteMinidump on the returned instance a dump file muct be
// specified by a call to either SetDumpFile() or GenerateDumpFile().
// If a full dump file will be requested via a subsequent call to either
// SetFullDumpFile or GenerateFullDumpFile() dump_type must include
// MiniDumpWithFullMemory.
MinidumpGenerator(const std::wstring& dump_path,
const HANDLE process_handle,
const DWORD process_id,
const DWORD thread_id,
const DWORD requesting_thread_id,
EXCEPTION_POINTERS* exception_pointers,
MDRawAssertionInfo* assert_info,
const MINIDUMP_TYPE dump_type,
const bool is_client_pointers);
~MinidumpGenerator();
void SetDumpFile(const HANDLE dump_file) { dump_file_ = dump_file; }
void SetFullDumpFile(const HANDLE full_dump_file) {
full_dump_file_ = full_dump_file;
}
// Generate the name for the dump file that will be written to once
// WriteMinidump() is called. Can only be called once and cannot be called
// if the dump file is set via SetDumpFile().
bool GenerateDumpFile(std::wstring* dump_path);
// Generate the name for the full dump file that will be written to once
// WriteMinidump() is called. Cannot be called unless the minidump type
// includes MiniDumpWithFullMemory. Can only be called once and cannot be
// called if the dump file is set via SetFullDumpFile().
bool GenerateFullDumpFile(std::wstring* full_dump_path);
void SetAdditionalStreams(
MINIDUMP_USER_STREAM_INFORMATION* additional_streams) {
additional_streams_ = additional_streams;
}
void SetCallback(MINIDUMP_CALLBACK_INFORMATION* callback_info) {
callback_info_ = callback_info;
}
// Writes the minidump with the given parameters. Stores the
// dump file path in the dump_path parameter if dump generation
// succeeds.
bool WriteMinidump();
private:
// Function pointer type for MiniDumpWriteDump, which is looked up
// dynamically.
typedef BOOL (WINAPI* MiniDumpWriteDumpType)(
HANDLE hProcess,
DWORD ProcessId,
HANDLE hFile,
MINIDUMP_TYPE DumpType,
CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam,
CONST PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,
CONST PMINIDUMP_CALLBACK_INFORMATION CallbackParam);
// Function pointer type for UuidCreate, which is looked up dynamically.
typedef RPC_STATUS (RPC_ENTRY* UuidCreateType)(UUID* Uuid);
// Loads the appropriate DLL lazily in a thread safe way.
HMODULE GetDbghelpModule();
// Loads the appropriate DLL and gets a pointer to the MiniDumpWriteDump
// function lazily and in a thread-safe manner.
MiniDumpWriteDumpType GetWriteDump();
// Loads the appropriate DLL lazily in a thread safe way.
HMODULE GetRpcrt4Module();
// Loads the appropriate DLL and gets a pointer to the UuidCreate
// function lazily and in a thread-safe manner.
UuidCreateType GetCreateUuid();
// Returns the path for the file to write dump to.
bool GenerateDumpFilePath(std::wstring* file_path);
// Handle to dynamically loaded DbgHelp.dll.
HMODULE dbghelp_module_;
// Pointer to the MiniDumpWriteDump function.
MiniDumpWriteDumpType write_dump_;
// Handle to dynamically loaded rpcrt4.dll.
HMODULE rpcrt4_module_;
// Pointer to the UuidCreate function.
UuidCreateType create_uuid_;
// Handle for the process to dump.
HANDLE process_handle_;
// Process ID for the process to dump.
DWORD process_id_;
// The crashing thread ID.
DWORD thread_id_;
// The thread ID which is requesting the dump.
DWORD requesting_thread_id_;
// Pointer to the exception information for the crash. This may point to an
// address in the crashing process so it should not be dereferenced.
EXCEPTION_POINTERS* exception_pointers_;
// Assertion info for the report.
MDRawAssertionInfo* assert_info_;
// Type of minidump to generate.
MINIDUMP_TYPE dump_type_;
// Specifies whether the exception_pointers_ reference memory in the crashing
// process.
bool is_client_pointers_;
// Folder path to store dump files.
std::wstring dump_path_;
// The file where the dump will be written.
HANDLE dump_file_;
// The file where the full dump will be written.
HANDLE full_dump_file_;
// Tracks whether the dump file handle is managed externally.
bool dump_file_is_internal_;
// Tracks whether the full dump file handle is managed externally.
bool full_dump_file_is_internal_;
// Additional streams to be written to the dump.
MINIDUMP_USER_STREAM_INFORMATION* additional_streams_;
// The user defined callback for the various stages of the dump process.
MINIDUMP_CALLBACK_INFORMATION* callback_info_;
// Critical section to sychronize action of loading modules dynamically.
CRITICAL_SECTION module_load_sync_;
// Critical section to synchronize action of dynamically getting function
// addresses from modules.
CRITICAL_SECTION get_proc_address_sync_;
};
} // namespace google_breakpad
#endif // CLIENT_WINDOWS_CRASH_GENERATION_MINIDUMP_GENERATOR_H_
| [
"max@autious.net"
] | max@autious.net |
a0f70c31ed9780cccf9bd9611bb0e4ff5cb59749 | e9db3ae00dcaf4a084d0b9ce4c1d04de24b5d143 | /BuildingEscape/Source/BuildingEscape/OpenDoor.h | 649aa331d6d50787bf68a454756dd54c618fc9b9 | [] | no_license | larsmagnusny/BuildingEscape | 2e79875519b3c7cfd34c6bd3b550eb57245d734b | a508747cb763a1cdbc9e3bd1507e0f4ea7471bf7 | refs/heads/master | 2021-01-11T23:57:52.350976 | 2017-01-13T20:07:34 | 2017-01-13T20:07:34 | 78,651,929 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,033 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Components/ActorComponent.h"
#include "OpenDoor.generated.h"
DECLARE_DYNAMIC_MULTICAST_DELEGATE(FDoorEvent);
UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )
class BUILDINGESCAPE_API UOpenDoor : public UActorComponent
{
GENERATED_BODY()
public:
// Sets default values for this component's properties
UOpenDoor();
void OpenDoor();
void CloseDoor();
// Called when the game starts
virtual void BeginPlay() override;
// Called every frame
virtual void TickComponent( float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction ) override;
UPROPERTY(BlueprintAssignable)
FDoorEvent OnOpen;
UPROPERTY(BlueprintAssignable)
FDoorEvent OnClose;
private:
UPROPERTY(EditAnywhere)
ATriggerVolume* PressurePlate = nullptr;
UPROPERTY(EditAnywhere)
float TriggerMass = 30.f;
AActor* Owner = nullptr;
// Returns total mass in kg
float GetTotalMassOfActorsOnPlate();
};
| [
"lars.magnus.nyland@gmail.com"
] | lars.magnus.nyland@gmail.com |
ac527b9087765b4ddac37c395cca968575e3cab9 | f956da1ca2d7487a547e432ab084c995195e0af8 | /genDLList.h | bbce252a6d58bdee021d1b7537e6a632857b565b | [
"MIT"
] | permissive | hilaltrfllu/BigInt | a02eb2563d44eb204bfe710cba2bbe51f7f8b93e | a1d6bb152a680d6d4a7d74ef8c200b38b30b412a | refs/heads/master | 2023-02-27T11:36:48.944505 | 2021-02-01T14:40:27 | 2021-02-01T14:40:27 | 334,979,030 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,059 | h | #ifndef DOUBLY_LINKED_LIST
#define DOUBLY_LINKED_LIST
#include <ostream>
#include <algorithm>
template<class T>
class DLLNode {
public:
DLLNode() {
next = prev = NULL;
}
DLLNode(const T& el, DLLNode<T> *n = NULL, DLLNode<T> *p = NULL) {
info = el; next = n; prev = p;
}
T info;
DLLNode<T> *next, *prev;
};
template<class T>
class DoublyLinkedList {
public:
DoublyLinkedList() {
head = tail = NULL;
}
~DoublyLinkedList() {
clear();
}
void addToDLLHead(const T&);
void addToDLLTail(const T&);
T deleteFromDLLHead();
T deleteFromDLLTail();
bool isEmpty() const {
return head == NULL;
}
void clear();
std::string getNumAsString();
void operator=(const DoublyLinkedList<T>&);
protected:
DLLNode<T> *head, *tail;
friend std::ostream& operator<<(std::ostream& out, const DoublyLinkedList<T>& dll) {
if (dll.head != NULL) {
for (DLLNode<T> *tmp = dll.head; tmp != NULL; tmp = tmp->next)
out << tmp->info;
}
else {
out << "0";
}
return out;
}
};
template<class T>
void DoublyLinkedList<T>::addToDLLHead(const T& el) {
if (head != NULL) {
head = new DLLNode<T>(el,head,NULL);
head->next->prev = head;
}
else head = tail = new DLLNode<T>(el);
}
template<class T>
void DoublyLinkedList<T>::addToDLLTail(const T& el) {
if (tail != NULL) {
tail = new DLLNode<T>(el,NULL,tail);
tail->prev->next = tail;
}
else head = tail = new DLLNode<T>(el);
}
template<class T>
T DoublyLinkedList<T>::deleteFromDLLHead() {
T el = head->info;
if (head == tail) { // if only one DLLNode on the list;
delete head;
head = tail = NULL;
}
else { // if more than one DLLNode in the list;
head = head->next;
delete head->prev;
head->prev = NULL;
}
return el;
}
template<class T>
T DoublyLinkedList<T>::deleteFromDLLTail() {
T el = tail->info;
if (head == tail) { // if only one DLLNode on the list;
delete head;
head = tail = NULL;
}
else { // if more than one DLLNode in the list;
tail = tail->prev;
delete tail->next;
tail->next = NULL;
}
return el;
}
template<class T>
void DoublyLinkedList<T>::clear() {
while (head != NULL) {
deleteFromDLLHead();
}
}
template<class T>
std::string DoublyLinkedList<T>::getNumAsString()
{
std::string a;
for (DLLNode<T> *tmp = head; tmp != NULL; tmp = tmp->next)
a.push_back(tmp->info + '0');
return a;
}
template<class T>
void DoublyLinkedList<T>::operator=(const DoublyLinkedList<T> &B)
{
if (this != &B)
{
clear();
for (DLLNode<T> * tmp = B.head; tmp != NULL; tmp = tmp->next)
this->addToDLLTail(tmp->info);
}
}
#endif
| [
"noreply@github.com"
] | hilaltrfllu.noreply@github.com |
f4b603093af6ec4a18da246d5f6e3ea9435f91e6 | 95c523234f29d055f79b76470d848ba7ecbfa9d3 | /0638 Tower of Hanoi/Main.cpp | cd9c7051b436b4575cf427dd18a55f808360cb42 | [] | no_license | maxtwain/Core-Cpp-Training | d86af5a00a2c5948816b9c0101c66894626f206e | d2c5e1bf8b00bf19716dcdd2e1c9c44e2e40f1dc | refs/heads/master | 2022-11-05T17:44:09.615493 | 2020-06-26T02:25:30 | 2020-06-26T02:25:30 | 274,889,256 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,635 | cpp | /*
In this chapter, you studied functions that can be easily implemented both recursively and iteratively. In this exercise, we present a problem whose recursive solution demonstrates the elegance of recursion, and whose iterative solution may not be as apparent.
The Towers of Hanoi is one of the most famous classic problems every budding computer scientist must grapple with. Legend has it that in a temple in the Far East, priests are attempting to move a stack of golden disks from one diamond peg to another. The initial stack has 64 disks threaded onto one peg and arranged from bottom to top by decreasing size. The priests are attempting to move the stack from one peg to another under the constraints that exactly one disk is moved at a time and at no time may a larger disk be placed above a smaller disk. These pegs are provided, one being used for temporarily holding disks. Supposedly, the world will end with the priests completed their tasks, so there is little incentive for us to facilitate their efforts.
Let's assume that the priests are attempting to move the disks from peg 1 to peg 32. We wish to develop and algorithm that prints the precise sequence of peg to peg disk transfers.
If we were to approach this problem with conventional methods, we should rapidly find ourselves hopelessly knotted up in managing the disks. Instead, attacking this problem with recursion in mind allows the steps to be simple. Moving n disks can be viewed in terms of moving only n - 1 disks (hence, the recursion), as follows:
A) Move n - 1 disks from peg 1 to peg 2, using peg 3 as a temporary holding area.
B) Move the last disk (the largest) from peg 1 to peg 3.
C) Move the n - 1 disks from peg 2 to peg 3, using peg 1 as a temporary holding area.
The process ends when the last task involves moving n = 1 disk (i.e., the base case). This tasks is accomplished by simply moving the disk, without the need for a temporary holding area. Write a program to solve the towers of Hanoi problem. Use a recursive function with four parameters.
A) The number of disks to be moved
B) The peg on which these disks are initially threaded
C) The peg to which this stack of disks is to be moved
D) The peg to be used as a temporary holding area
Display the precise instructions for moving the disks from the starting peg to the destination peg. To move a stack of three disks from peg 1 to peg 3, the program displays the following moves.
1 -> 3 (This means move one disk from peg 1 to peg 3.)
1 -> 2
3 -> 2
1 -> 3
2 -> 1
2 -> 3
1 -> 3
*/
#include <iostream>
#include <string>
#include <stack>
using std::cout;
using std::stack;
using std::string;
struct peg{
string name;
stack<int> diskStack;
} peg1, peg2, peg3;
void moveDisk(int diskSize, peg pegFrom, peg pegTo, peg pegHold);
int main() {
peg1.name = "peg1";
peg2.name = "peg2";
peg3.name = "peg3";
for (int disk = 64; disk >= 1; --disk) {
peg1.diskStack.push(disk);
}
moveDisk(64, peg1, peg3, peg2);
}
void moveDisk(int diskSize, peg pegFrom, peg pegTo, peg pegHold) {
if (diskSize > 0) {
// move the rest of the stack to pegHold.
moveDisk(diskSize - 1, pegFrom, pegHold, pegTo);
// move the remaining disk to pegTo
pegTo.diskStack.push(pegFrom.diskStack.top());
pegFrom.diskStack.pop();
// print the last disk move
cout << "Disk "
<< diskSize
<< ": "
<< pegFrom.name
<< " -> "
<< pegTo.name
<< '\n';
// move the rest of the stack on top of the moved disk
moveDisk(diskSize - 1, pegHold, pegTo, pegFrom);
}
} | [
"noreply@github.com"
] | maxtwain.noreply@github.com |
3c5a01f4b16972dd97983f030d349b761aa857b8 | f97dc3a18993e00bc03f30cc0a9efc58435c208d | /lab1/convert/convert.cpp | 2f7bdf86f7b0d6ebcc24f8709ed4a4a27478e797 | [] | no_license | sharminy/ECE244 | aad936efae2b4290abdfac8b956a78e706883a76 | 1909130875c3763e2142629c9967263852f49548 | refs/heads/master | 2020-08-17T18:16:14.360723 | 2019-10-17T03:54:43 | 2019-10-17T03:54:43 | 215,479,874 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,770 | cpp | #include <iostream>
using namespace std;
// Conversion constants
#define CtoFRatio 1.80
#define CtoFOffset 32.00
#define CtoKOffset 273.0
// Scale identifiers
#define DegC 'C'
#define Degc 'c'
#define DegF 'F'
#define Degf 'f'
#define DegK 'K'
#define Degk 'k'
// Conversion function prototypes
// Should be in a ".h" file, but placed here for lab1
double toFahrenheit( double T, char scale );
double toCelsius( double T, char scale );
double toKelvin( double T, char scale );
int main(void)
{
double inTemp;
char scale;
cout << "\nThis program converts a temperature between the scales\n"
<< "\t Fahrenheit, Celsius and Kelvin.\n";
// Get a temperature and scale
cout << "\nPlease enter the temperature you wish to convert,\n"
<< "\tfollowed by its scale (eg. 23 C): ";
cin >> inTemp >> scale;
// Check for validity of scale
if( scale != DegF && scale != Degf &&
scale != DegC && scale != Degc &&
scale != DegK && scale != Degk )
{
cerr << "\nError in input: Invalid scale `" << scale << "'\n";
return -1;
}
// Print the converted results
cout << "\n" << inTemp << " " << scale << " is equivalent to:\n"
<< "\t" << toFahrenheit( inTemp, scale ) << " F, "
<< toCelsius( inTemp, scale ) << " C, and "
<< toKelvin( inTemp, scale ) << " K\n";
return 0;
}
// Converts the temperate 'T' from scale 'scale' to Fahrenheit
double toFahrenheit( double T, char scale )
{
double outT;
switch( scale ) {
case DegF:
case Degf:
outT = T;
break;
case DegC:
case Degc:
outT = T * CtoFRatio + CtoFOffset;
break;
case DegK:
case Degk:
outT = ( T - CtoKOffset ) * CtoFRatio + CtoFOffset;
break;
default:
break;
}
return outT;
}
// Converts the temperate 'T' from scale 'scale' to Celsius
double toCelsius( double T, char scale )
{
double outT;
switch( scale ) {
case DegF:
case Degf:
outT = ( T - CtoFOffset ) / CtoFRatio;
break;
case DegC:
case Degc:
outT = T;
break;
case DegK:
case Degk:
outT = T - CtoKOffset;
break;
default:
break;
}
return outT;
}
// Converts the temperate 'T' from scale 'scale' to Kelvin
double toKelvin( double T, char scale )
{
double outT;
switch( scale ) {
case DegF:
case Degf:
outT = ( T - CtoFOffset ) / CtoFRatio + CtoKOffset;
break;
case DegC:
case Degc:
outT = T + CtoKOffset;
break;
case DegK:
case Degk:
outT = T;
break;
default:
break;
}
return outT;
}
| [
"sharminy@github.com"
] | sharminy@github.com |
f9d6dda03f26de766406804b4d390a137aebae34 | 365578c6584a1b9bd633a09e054de94f426fc449 | /assignment4/problem2/cell_concr.h | e41a1157b3d926b2646a244d2e5b28ea193f432c | [] | no_license | KoKoJarJar/CS246 | c060b672abb0de0e53ed788ce13bcf8357a569bd | 7e7db42164bb488d027635ccbf28ba7c5d6c0856 | refs/heads/master | 2021-09-11T13:50:12.077989 | 2018-04-08T08:48:11 | 2018-04-08T08:48:11 | 108,539,774 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 466 | h | #ifndef __CELL_CONCR__
#define __CELL_CONCR__
#include "cell.h"
#include "state.h"
#include <memory>
class Cell_concr : public Cell {
std::unique_ptr<Publisher> publisher;
std::unique_ptr<State> state;
void notify(State &prev_state, State &curr_state);
public:
Cell_concr(State &state);
State &get_state();
void update(State &state);
void add_publisher(Publisher &publisher);
bool operator==(Cell &cell);
bool operator!=(Cell &cell);
};
#endif
| [
"ardavan.behnia@gmail.com"
] | ardavan.behnia@gmail.com |
d5ff377253fa76d1784bfb3aa7effc1912c2cc90 | 44289ecb892b6f3df043bab40142cf8530ac2ba4 | /Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/core/v8/V8TypeConversions.h | c750621db636a6cc23b7d3a42afc437704d12303 | [
"Apache-2.0"
] | permissive | warrenween/Elastos | a6ef68d8fb699fd67234f376b171c1b57235ed02 | 5618eede26d464bdf739f9244344e3e87118d7fe | refs/heads/master | 2021-01-01T04:07:12.833674 | 2017-06-17T15:34:33 | 2017-06-17T15:34:33 | 97,120,576 | 2 | 1 | null | 2017-07-13T12:33:20 | 2017-07-13T12:33:20 | null | UTF-8 | C++ | false | false | 5,133 | h | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!
#ifndef V8TypeConversions_h
#define V8TypeConversions_h
#include "bindings/v8/V8Binding.h"
#include "bindings/v8/V8DOMWrapper.h"
#include "bindings/v8/WrapperTypeInfo.h"
#include "core/testing/TypeConversions.h"
#include "platform/heap/Handle.h"
namespace WebCore {
class V8TypeConversions {
public:
static bool hasInstance(v8::Handle<v8::Value>, v8::Isolate*);
static v8::Handle<v8::Object> findInstanceInPrototypeChain(v8::Handle<v8::Value>, v8::Isolate*);
static v8::Handle<v8::FunctionTemplate> domTemplate(v8::Isolate*);
static TypeConversions* toNative(v8::Handle<v8::Object> object)
{
return fromInternalPointer(object->GetAlignedPointerFromInternalField(v8DOMWrapperObjectIndex));
}
static TypeConversions* toNativeWithTypeCheck(v8::Isolate*, v8::Handle<v8::Value>);
static const WrapperTypeInfo wrapperTypeInfo;
static void derefObject(void*);
#if ENABLE(OILPAN)
static const int persistentHandleIndex = v8DefaultWrapperInternalFieldCount + 0;
static const int internalFieldCount = v8DefaultWrapperInternalFieldCount + 0 + 1;
#else
static const int internalFieldCount = v8DefaultWrapperInternalFieldCount + 0;
#endif
static inline void* toInternalPointer(TypeConversions* impl)
{
return impl;
}
static inline TypeConversions* fromInternalPointer(void* object)
{
return static_cast<TypeConversions*>(object);
}
static void installPerContextEnabledProperties(v8::Handle<v8::Object>, TypeConversions*, v8::Isolate*) { }
static void installPerContextEnabledMethods(v8::Handle<v8::Object>, v8::Isolate*) { }
private:
friend v8::Handle<v8::Object> wrap(TypeConversions*, v8::Handle<v8::Object> creationContext, v8::Isolate*);
static v8::Handle<v8::Object> createWrapper(PassRefPtrWillBeRawPtr<TypeConversions>, v8::Handle<v8::Object> creationContext, v8::Isolate*);
};
v8::Handle<v8::Object> wrap(TypeConversions* impl, v8::Handle<v8::Object> creationContext, v8::Isolate*);
inline v8::Handle<v8::Value> toV8(TypeConversions* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
if (UNLIKELY(!impl))
return v8::Null(isolate);
v8::Handle<v8::Value> wrapper = DOMDataStore::getWrapper<V8TypeConversions>(impl, isolate);
if (!wrapper.IsEmpty())
return wrapper;
return wrap(impl, creationContext, isolate);
}
template<typename CallbackInfo>
inline void v8SetReturnValue(const CallbackInfo& callbackInfo, TypeConversions* impl)
{
if (UNLIKELY(!impl)) {
v8SetReturnValueNull(callbackInfo);
return;
}
if (DOMDataStore::setReturnValueFromWrapper<V8TypeConversions>(callbackInfo.GetReturnValue(), impl))
return;
v8::Handle<v8::Object> wrapper = wrap(impl, callbackInfo.Holder(), callbackInfo.GetIsolate());
v8SetReturnValue(callbackInfo, wrapper);
}
template<typename CallbackInfo>
inline void v8SetReturnValueForMainWorld(const CallbackInfo& callbackInfo, TypeConversions* impl)
{
ASSERT(DOMWrapperWorld::current(callbackInfo.GetIsolate()).isMainWorld());
if (UNLIKELY(!impl)) {
v8SetReturnValueNull(callbackInfo);
return;
}
if (DOMDataStore::setReturnValueFromWrapperForMainWorld<V8TypeConversions>(callbackInfo.GetReturnValue(), impl))
return;
v8::Handle<v8::Value> wrapper = wrap(impl, callbackInfo.Holder(), callbackInfo.GetIsolate());
v8SetReturnValue(callbackInfo, wrapper);
}
template<class CallbackInfo, class Wrappable>
inline void v8SetReturnValueFast(const CallbackInfo& callbackInfo, TypeConversions* impl, Wrappable* wrappable)
{
if (UNLIKELY(!impl)) {
v8SetReturnValueNull(callbackInfo);
return;
}
if (DOMDataStore::setReturnValueFromWrapperFast<V8TypeConversions>(callbackInfo.GetReturnValue(), impl, callbackInfo.Holder(), wrappable))
return;
v8::Handle<v8::Object> wrapper = wrap(impl, callbackInfo.Holder(), callbackInfo.GetIsolate());
v8SetReturnValue(callbackInfo, wrapper);
}
inline v8::Handle<v8::Value> toV8(PassRefPtrWillBeRawPtr<TypeConversions> impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
return toV8(impl.get(), creationContext, isolate);
}
template<class CallbackInfo>
inline void v8SetReturnValue(const CallbackInfo& callbackInfo, PassRefPtrWillBeRawPtr<TypeConversions> impl)
{
v8SetReturnValue(callbackInfo, impl.get());
}
template<class CallbackInfo>
inline void v8SetReturnValueForMainWorld(const CallbackInfo& callbackInfo, PassRefPtrWillBeRawPtr<TypeConversions> impl)
{
v8SetReturnValueForMainWorld(callbackInfo, impl.get());
}
template<class CallbackInfo, class Wrappable>
inline void v8SetReturnValueFast(const CallbackInfo& callbackInfo, PassRefPtrWillBeRawPtr<TypeConversions> impl, Wrappable* wrappable)
{
v8SetReturnValueFast(callbackInfo, impl.get(), wrappable);
}
}
#endif // V8TypeConversions_h
| [
"gdsys@126.com"
] | gdsys@126.com |
81cf3c615eb18b06ef6630e2bfcfd11dcded6711 | cf8ddfc720bf6451c4ef4fa01684327431db1919 | /SDK/ARKSurvivalEvolved_PrimalItem_WeaponBaseClub_parameters.hpp | 66cdd601252529310e98555b8bd5ac6d587af729 | [
"MIT"
] | permissive | git-Charlie/ARK-SDK | 75337684b11e7b9f668da1f15e8054052a3b600f | c38ca9925309516b2093ad8c3a70ed9489e1d573 | refs/heads/master | 2023-06-20T06:30:33.550123 | 2021-07-11T13:41:45 | 2021-07-11T13:41:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 752 | hpp | #pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_PrimalItem_WeaponBaseClub_classes.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function PrimalItem_WeaponBaseClub.PrimalItem_WeaponBaseClub_C.ExecuteUbergraph_PrimalItem_WeaponBaseClub
struct UPrimalItem_WeaponBaseClub_C_ExecuteUbergraph_PrimalItem_WeaponBaseClub_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"sergey.2bite@gmail.com"
] | sergey.2bite@gmail.com |
3df7bdd39b99c25a7de15c4accbb4686f126d524 | ad273708d98b1f73b3855cc4317bca2e56456d15 | /aws-cpp-sdk-mediapackage-vod/source/model/ListAssetsRequest.cpp | c006b5d5d61e1ab60556073229935e8149fbd53e | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | novaquark/aws-sdk-cpp | b390f2e29f86f629f9efcf41c4990169b91f4f47 | a0969508545bec9ae2864c9e1e2bb9aff109f90c | refs/heads/master | 2022-08-28T18:28:12.742810 | 2020-05-27T15:46:18 | 2020-05-27T15:46:18 | 267,351,721 | 1 | 0 | Apache-2.0 | 2020-05-27T15:08:16 | 2020-05-27T15:08:15 | null | UTF-8 | C++ | false | false | 1,729 | cpp | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/mediapackage-vod/model/ListAssetsRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/http/URI.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <utility>
using namespace Aws::MediaPackageVod::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws::Http;
ListAssetsRequest::ListAssetsRequest() :
m_maxResults(0),
m_maxResultsHasBeenSet(false),
m_nextTokenHasBeenSet(false),
m_packagingGroupIdHasBeenSet(false)
{
}
Aws::String ListAssetsRequest::SerializePayload() const
{
return {};
}
void ListAssetsRequest::AddQueryStringParameters(URI& uri) const
{
Aws::StringStream ss;
if(m_maxResultsHasBeenSet)
{
ss << m_maxResults;
uri.AddQueryStringParameter("maxResults", ss.str());
ss.str("");
}
if(m_nextTokenHasBeenSet)
{
ss << m_nextToken;
uri.AddQueryStringParameter("nextToken", ss.str());
ss.str("");
}
if(m_packagingGroupIdHasBeenSet)
{
ss << m_packagingGroupId;
uri.AddQueryStringParameter("packagingGroupId", ss.str());
ss.str("");
}
}
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
e16626e493f255014f09eebacaeb797ab9022542 | a0b155ac197a6d07754490832a000a6716ab11be | /CFE_LeapMotion2/Plugins/LeapMotion/Intermediate/Build/Win64/UE4Editor/Inc/BodyState/BodyStateBPLibrary.generated.h | 3e582f35998f43c963f9a3798e61c63cbbb9a935 | [] | no_license | killercloss/CFE_RV | 7727905d2118faff834219e5dfb35a175742703c | 52018ce07dc275245ef9718dce1e7227b7391022 | refs/heads/master | 2022-01-15T10:22:11.730759 | 2019-07-01T00:03:14 | 2019-07-01T00:03:14 | 145,898,277 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,703 | h | // Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/ObjectMacros.h"
#include "UObject/ScriptMacros.h"
PRAGMA_DISABLE_DEPRECATION_WARNINGS
class UAnimInstance;
struct FTransform;
class UObject;
class UBodyStateSkeleton;
struct FBodyStateDeviceConfig;
class IBodyStateInputInterface;
#ifdef BODYSTATE_BodyStateBPLibrary_generated_h
#error "BodyStateBPLibrary.generated.h already included, missing '#pragma once' in BodyStateBPLibrary.h"
#endif
#define BODYSTATE_BodyStateBPLibrary_generated_h
#define CFE_LeapMotion2_Plugins_LeapMotion_Source_BodyState_Public_BodyStateBPLibrary_h_17_RPC_WRAPPERS \
\
DECLARE_FUNCTION(execTransformForBoneNamedInAnimInstance) \
{ \
P_GET_PROPERTY_REF(UNameProperty,Z_Param_Out_Bone); \
P_GET_OBJECT(UAnimInstance,Z_Param_Instance); \
P_FINISH; \
P_NATIVE_BEGIN; \
*(FTransform*)Z_Param__Result=UBodyStateBPLibrary::TransformForBoneNamedInAnimInstance(Z_Param_Out_Bone,Z_Param_Instance); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execSkeletonForDevice) \
{ \
P_GET_OBJECT(UObject,Z_Param_WorldContextObject); \
P_GET_PROPERTY(UIntProperty,Z_Param_DeviceID); \
P_FINISH; \
P_NATIVE_BEGIN; \
*(UBodyStateSkeleton**)Z_Param__Result=UBodyStateBPLibrary::SkeletonForDevice(Z_Param_WorldContextObject,Z_Param_DeviceID); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execDetachDevice) \
{ \
P_GET_PROPERTY(UIntProperty,Z_Param_DeviceID); \
P_FINISH; \
P_NATIVE_BEGIN; \
*(bool*)Z_Param__Result=UBodyStateBPLibrary::DetachDevice(Z_Param_DeviceID); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execAttachDevice) \
{ \
P_GET_STRUCT_REF(FBodyStateDeviceConfig,Z_Param_Out_Configuration); \
P_GET_TINTERFACE(IBodyStateInputInterface,Z_Param_InputCallbackDelegate); \
P_FINISH; \
P_NATIVE_BEGIN; \
*(int32*)Z_Param__Result=UBodyStateBPLibrary::AttachDevice(Z_Param_Out_Configuration,Z_Param_InputCallbackDelegate); \
P_NATIVE_END; \
}
#define CFE_LeapMotion2_Plugins_LeapMotion_Source_BodyState_Public_BodyStateBPLibrary_h_17_RPC_WRAPPERS_NO_PURE_DECLS \
\
DECLARE_FUNCTION(execTransformForBoneNamedInAnimInstance) \
{ \
P_GET_PROPERTY_REF(UNameProperty,Z_Param_Out_Bone); \
P_GET_OBJECT(UAnimInstance,Z_Param_Instance); \
P_FINISH; \
P_NATIVE_BEGIN; \
*(FTransform*)Z_Param__Result=UBodyStateBPLibrary::TransformForBoneNamedInAnimInstance(Z_Param_Out_Bone,Z_Param_Instance); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execSkeletonForDevice) \
{ \
P_GET_OBJECT(UObject,Z_Param_WorldContextObject); \
P_GET_PROPERTY(UIntProperty,Z_Param_DeviceID); \
P_FINISH; \
P_NATIVE_BEGIN; \
*(UBodyStateSkeleton**)Z_Param__Result=UBodyStateBPLibrary::SkeletonForDevice(Z_Param_WorldContextObject,Z_Param_DeviceID); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execDetachDevice) \
{ \
P_GET_PROPERTY(UIntProperty,Z_Param_DeviceID); \
P_FINISH; \
P_NATIVE_BEGIN; \
*(bool*)Z_Param__Result=UBodyStateBPLibrary::DetachDevice(Z_Param_DeviceID); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execAttachDevice) \
{ \
P_GET_STRUCT_REF(FBodyStateDeviceConfig,Z_Param_Out_Configuration); \
P_GET_TINTERFACE(IBodyStateInputInterface,Z_Param_InputCallbackDelegate); \
P_FINISH; \
P_NATIVE_BEGIN; \
*(int32*)Z_Param__Result=UBodyStateBPLibrary::AttachDevice(Z_Param_Out_Configuration,Z_Param_InputCallbackDelegate); \
P_NATIVE_END; \
}
#define CFE_LeapMotion2_Plugins_LeapMotion_Source_BodyState_Public_BodyStateBPLibrary_h_17_INCLASS_NO_PURE_DECLS \
private: \
static void StaticRegisterNativesUBodyStateBPLibrary(); \
friend struct Z_Construct_UClass_UBodyStateBPLibrary_Statics; \
public: \
DECLARE_CLASS(UBodyStateBPLibrary, UBlueprintFunctionLibrary, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/BodyState"), NO_API) \
DECLARE_SERIALIZER(UBodyStateBPLibrary)
#define CFE_LeapMotion2_Plugins_LeapMotion_Source_BodyState_Public_BodyStateBPLibrary_h_17_INCLASS \
private: \
static void StaticRegisterNativesUBodyStateBPLibrary(); \
friend struct Z_Construct_UClass_UBodyStateBPLibrary_Statics; \
public: \
DECLARE_CLASS(UBodyStateBPLibrary, UBlueprintFunctionLibrary, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/BodyState"), NO_API) \
DECLARE_SERIALIZER(UBodyStateBPLibrary)
#define CFE_LeapMotion2_Plugins_LeapMotion_Source_BodyState_Public_BodyStateBPLibrary_h_17_STANDARD_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API UBodyStateBPLibrary(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UBodyStateBPLibrary) \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UBodyStateBPLibrary); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UBodyStateBPLibrary); \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API UBodyStateBPLibrary(UBodyStateBPLibrary&&); \
NO_API UBodyStateBPLibrary(const UBodyStateBPLibrary&); \
public:
#define CFE_LeapMotion2_Plugins_LeapMotion_Source_BodyState_Public_BodyStateBPLibrary_h_17_ENHANCED_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API UBodyStateBPLibrary(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()) : Super(ObjectInitializer) { }; \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API UBodyStateBPLibrary(UBodyStateBPLibrary&&); \
NO_API UBodyStateBPLibrary(const UBodyStateBPLibrary&); \
public: \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UBodyStateBPLibrary); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UBodyStateBPLibrary); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UBodyStateBPLibrary)
#define CFE_LeapMotion2_Plugins_LeapMotion_Source_BodyState_Public_BodyStateBPLibrary_h_17_PRIVATE_PROPERTY_OFFSET
#define CFE_LeapMotion2_Plugins_LeapMotion_Source_BodyState_Public_BodyStateBPLibrary_h_14_PROLOG
#define CFE_LeapMotion2_Plugins_LeapMotion_Source_BodyState_Public_BodyStateBPLibrary_h_17_GENERATED_BODY_LEGACY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
CFE_LeapMotion2_Plugins_LeapMotion_Source_BodyState_Public_BodyStateBPLibrary_h_17_PRIVATE_PROPERTY_OFFSET \
CFE_LeapMotion2_Plugins_LeapMotion_Source_BodyState_Public_BodyStateBPLibrary_h_17_RPC_WRAPPERS \
CFE_LeapMotion2_Plugins_LeapMotion_Source_BodyState_Public_BodyStateBPLibrary_h_17_INCLASS \
CFE_LeapMotion2_Plugins_LeapMotion_Source_BodyState_Public_BodyStateBPLibrary_h_17_STANDARD_CONSTRUCTORS \
public: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#define CFE_LeapMotion2_Plugins_LeapMotion_Source_BodyState_Public_BodyStateBPLibrary_h_17_GENERATED_BODY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
CFE_LeapMotion2_Plugins_LeapMotion_Source_BodyState_Public_BodyStateBPLibrary_h_17_PRIVATE_PROPERTY_OFFSET \
CFE_LeapMotion2_Plugins_LeapMotion_Source_BodyState_Public_BodyStateBPLibrary_h_17_RPC_WRAPPERS_NO_PURE_DECLS \
CFE_LeapMotion2_Plugins_LeapMotion_Source_BodyState_Public_BodyStateBPLibrary_h_17_INCLASS_NO_PURE_DECLS \
CFE_LeapMotion2_Plugins_LeapMotion_Source_BodyState_Public_BodyStateBPLibrary_h_17_ENHANCED_CONSTRUCTORS \
static_assert(false, "Unknown access specifier for GENERATED_BODY() macro in class BodyStateBPLibrary."); \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#undef CURRENT_FILE_ID
#define CURRENT_FILE_ID CFE_LeapMotion2_Plugins_LeapMotion_Source_BodyState_Public_BodyStateBPLibrary_h
PRAGMA_ENABLE_DEPRECATION_WARNINGS
| [
"jerson.gamezc@gmail.com"
] | jerson.gamezc@gmail.com |
a333d2cb64e6ddffddf309f2e82e5abe89a0adcb | 30b8561243cff67f758633327004cb378e5c5cef | /source/src/NGE/Physics/RigidBody/CollisionDetector.cpp | 0926a21cf3ef28ffb2eaab3b7e0adc5cd6c33e2f | [] | no_license | tkubicz/ngengine | 56a7235de0c799f541d47841380da6fd90d3abed | 75413c8b77587e5ec8f03164fa9b5dcd7697c0c6 | refs/heads/master | 2021-01-12T06:02:57.202296 | 2016-06-15T16:42:43 | 2016-06-15T16:42:43 | 77,282,542 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,504 | cpp | #include <float.h>
#include "NGE/Physics/RigidBody/CollisionDetector.hpp"
#include "NGE/Physics/RigidBody/IntersectionTests.hpp"
using namespace NGE::Physics::RigidBody;
unsigned CollisionDetector::SphereAndTruePlane(const CollisionSphere& sphere, const CollisionPlane& plane, CollisionData* data) {
// Mamy kontakty
if (data->contactsLeft <= 0)
return 0;
// Pozycja kuli
Math::vec3f position = sphere.GetAxis(3);
// Odległość od płaszczyzny
float centreDistance = plane.direction.DotProduct(position) - plane.offset;
// Sprawdzenie czy jesteśmy w promieniu
if (centreDistance * centreDistance > sphere.radius * sphere.radius)
return 0;
// Sprawdzenie po której stronie płaszczyzny się znajdujemy
Math::vec3f normal = plane.direction;
float penetration = -centreDistance;
if (centreDistance < 0) {
normal *= -1;
penetration = -penetration;
}
penetration += sphere.radius;
// Utworzenie kontaktu
Contact* contact = data->contacts;
contact->contactNormal = normal;
contact->penetration = penetration;
contact->contactPoint = position - plane.direction * centreDistance;
contact->SetBodyData(sphere.body, NULL, data->friction, data->restitution);
data->AddContacts(1);
return 1;
}
unsigned CollisionDetector::SphereAndHalfSpace(const CollisionSphere& sphere, const CollisionPlane& plane, CollisionData* data) {
// Sprawdzenie czy mamy kontakty
if (data->contactsLeft <= 0)
return 0;
// Pozycja kuli
Math::vec3f position = sphere.GetAxis(3);
// Znalezienie odleglosci od płaszczyzny
float ballDistance = plane.direction.DotProduct(position) - sphere.radius - plane.offset;
if (ballDistance >= 0)
return 0;
// Utworzenie kontaktu
Contact* contact = data->contacts;
contact->contactNormal = plane.direction;
contact->penetration = -ballDistance;
contact->contactPoint = position - plane.direction * (ballDistance + sphere.radius);
contact->SetBodyData(sphere.body, NULL, data->friction, data->restitution);
data->AddContacts(1);
return 1;
}
unsigned CollisionDetector::SphereAndSphere(const CollisionSphere& one, const CollisionSphere& two, CollisionData* data) {
// Sprawdzenie czy mamy kontakty
if (data->contactsLeft <= 0)
return 0;
// Pozycje kul
Math::vec3f positionOne = one.GetAxis(3);
Math::vec3f positionTwo = two.GetAxis(3);
// Znalezienie wektora pomiędzy obiektami
Math::vec3f midline = positionOne - positionTwo;
float size = midline.Length();
// Czy wektor jest wystarczająco duży
if (size <= 0.0f || size >= one.radius + two.radius)
return 0;
// Ręczne utworzenie normalnej
Math::vec3f normal = midline * (1.0f / size);
Contact* contact = data->contacts;
contact->contactNormal = normal;
contact->contactPoint = positionOne + midline * 0.5f;
contact->penetration = (one.radius + two.radius - size);
contact->SetBodyData(one.body, two.body, data->friction, data->restitution);
data->AddContacts(1);
return 1;
}
unsigned CollisionDetector::BoxAndHalfSpace(const CollisionBox& box, const CollisionPlane& plane, CollisionData* data) {
// Make sure we have contacts
if (data->contactsLeft <= 0) return 0;
// Check for intersection
if (!IntersectionTests::BoxAndHalfSpace(box, plane)) {
return 0;
}
// We have an intersection, so find the intersection points. We can make
// do with only checking vertices. If the box is resting on a plane
// or on an edge, it will be reported as four or two contact points.
// Go through each combination of + and - for each half-size
static float mults[8][3] = {
{1, 1, 1},
{-1, 1, 1},
{1, -1, 1},
{-1, -1, 1},
{1, 1, -1},
{-1, 1, -1},
{1, -1, -1},
{-1, -1, -1}
};
Contact* contact = data->contacts;
unsigned contactsUsed = 0;
for (unsigned i = 0; i < 8; i++) {
// Calculate the position of each vertex
Math::vec3f vertexPos(mults[i][0], mults[i][1], mults[i][2]);
vertexPos.ComponentProductUpdate(box.halfSize);
vertexPos = box.transform * vertexPos;
// Calculate the distance from the plane
float vertexDistance = vertexPos.DotProduct(plane.direction);
// Compare this to the plane's distance
if (vertexDistance <= plane.offset) {
// Create the contact data.
// The contact point is halfway between the vertex and the
// plane - we multiply the direction by half the separation
// distance and add the vertex location.
contact->contactPoint = plane.direction;
contact->contactPoint *= (vertexDistance - plane.offset);
contact->contactPoint = vertexPos;
contact->contactNormal = plane.direction;
contact->penetration = plane.offset - vertexDistance;
// Write the appropriate data
contact->SetBodyData(box.body, NULL,
data->friction, data->restitution);
// Move onto the next contact
contact++;
contactsUsed++;
if (contactsUsed == (unsigned) data->contactsLeft)
return contactsUsed;
}
}
data->AddContacts(contactsUsed);
return contactsUsed;
}
unsigned CollisionDetector::BoxAndBox(const CollisionBox& one, const CollisionBox& two, CollisionData* data) {
//if (!IntersectionTests::BoxAndBox(one, two))
// return 0;
// Znalezienie wektora pomiędzy dwoma środkami
Math::vec3f toCenter = two.GetAxis(3) - one.GetAxis(3);
// Zaczynamy zakładając, że nie ma kontaktu
float pen = FLT_MAX;
unsigned best = 0xffffff;
// Sprawdzamy każdą oś
if (!TryAxis(one, two, one.GetAxis(0), toCenter, 0, pen, best)) return 0;
if (!TryAxis(one, two, one.GetAxis(1), toCenter, 1, pen, best)) return 0;
if (!TryAxis(one, two, one.GetAxis(2), toCenter, 2, pen, best)) return 0;
if (!TryAxis(one, two, two.GetAxis(0), toCenter, 3, pen, best)) return 0;
if (!TryAxis(one, two, two.GetAxis(1), toCenter, 4, pen, best)) return 0;
if (!TryAxis(one, two, two.GetAxis(2), toCenter, 5, pen, best)) return 0;
unsigned bestSingleAxis = best;
if (!TryAxis(one, two, one.GetAxis(0).CrossProduct(two.GetAxis(0)), toCenter, 6, pen, best)) return 0;
if (!TryAxis(one, two, one.GetAxis(0).CrossProduct(two.GetAxis(1)), toCenter, 7, pen, best)) return 0;
if (!TryAxis(one, two, one.GetAxis(0).CrossProduct(two.GetAxis(2)), toCenter, 8, pen, best)) return 0;
if (!TryAxis(one, two, one.GetAxis(1).CrossProduct(two.GetAxis(0)), toCenter, 9, pen, best)) return 0;
if (!TryAxis(one, two, one.GetAxis(1).CrossProduct(two.GetAxis(1)), toCenter, 10, pen, best)) return 0;
if (!TryAxis(one, two, one.GetAxis(1).CrossProduct(two.GetAxis(2)), toCenter, 11, pen, best)) return 0;
if (!TryAxis(one, two, one.GetAxis(2).CrossProduct(two.GetAxis(0)), toCenter, 12, pen, best)) return 0;
if (!TryAxis(one, two, one.GetAxis(2).CrossProduct(two.GetAxis(1)), toCenter, 13, pen, best)) return 0;
if (!TryAxis(one, two, one.GetAxis(2).CrossProduct(two.GetAxis(2)), toCenter, 14, pen, best)) return 0;
// Upewnienie się, że mamy wynik
if (best == 0xffffff)
return -1;
// Wiemy, że istnieje kolizja i wiemy, na której osi występuje najmniejsza penetracja.
if (best < 3) {
// Wierzchołek pudełka dwa na powierzchni pudełka jeden.
FillPointFaceBoxBox(one, two, toCenter, data, best, pen);
data->AddContacts(1);
return 1;
} else if (best < 6) {
// Wierzchołek pudełka jeden na powierzchni pudełka dwa.
// Używamy tego samego algorytmu co powyżej, ale zamieniamy
// pudełka (więc również wektor pomiędzy nimi).
FillPointFaceBoxBox(two, one, toCenter * -1.0f, data, best - 3, pen);
data->AddContacts(1);
return 1;
} else {
// Kontakt krawędziami. Znaleźnienie na których osiach.
best -= 6;
unsigned oneAxisIndex = best / 3;
unsigned twoAxisIndex = best % 3;
Math::vec3f oneAxis = one.GetAxis(oneAxisIndex);
Math::vec3f twoAxis = two.GetAxis(twoAxisIndex);
Math::vec3f axis = oneAxis.CrossProduct(twoAxis);
axis.Normalize();
// Oś powinna wskazywać z pudełka jeden do pudełka dwa.
if (axis.DotProduct(toCenter) > 0)
axis = axis * -1.0f;
// Mamy osie, ale nie krawędzie: każda oś posiada 4 krawędzie równoległe
// do niej. Musimy znaleźć które 4 dla każdego obiektu. Robimy to przez
// znalezienie punktu w środku krawędzi. TODO: Dalszy komentarz
Math::vec3f ptOnOneEdge = one.halfSize;
Math::vec3f ptOnTwoEdge = two.halfSize;
for (unsigned i = 0; i < 3; ++i) {
if (i == oneAxisIndex)
ptOnOneEdge[i] = 0;
else if (one.GetAxis(i).DotProduct(axis) > 0)
ptOnOneEdge[i] = -ptOnOneEdge[i];
if (i == twoAxisIndex)
ptOnTwoEdge[i] = 0;
else if (two.GetAxis(i).DotProduct(axis) < 0)
ptOnTwoEdge[i] = -ptOnTwoEdge[i];
}
// Przeniesienie ich do przestrzeni świata (są w odpowiedniej orientacji
// ponieważ są pochodnymi osi).
ptOnOneEdge = one.transform * ptOnOneEdge;
ptOnTwoEdge = two.transform * ptOnTwoEdge;
// TODO: Komentarz
Math::vec3f vertex = ContactPoint(ptOnOneEdge, oneAxis, one.halfSize[oneAxisIndex],
ptOnTwoEdge, twoAxis, two.halfSize[twoAxisIndex],
bestSingleAxis > 2);
// Wypełnienie struktury kontaktu
Contact* contact = data->contacts;
contact->penetration = pen;
contact->contactNormal = axis;
contact->contactPoint = vertex;
contact->SetBodyData(one.body, two.body, data->friction, data->restitution);
data->AddContacts(1);
return 1;
}
return 0;
}
unsigned CollisionDetector::BoxAndPoint(const CollisionBox& box, const NGE::Math::vec3f& point, CollisionData* data) {
// Transformacja współrzędnych punktu do przestrzeni pudełka
Math::vec3f relPt = box.transform.TransformInverse(point);
Math::vec3f normal;
// Sprawdzenie każdej z osi, szukając tej na której penetracja jest najmniejsza
float min_depth = box.halfSize.x - std::abs(relPt.x);
if (min_depth < 0)
return 0;
normal = box.GetAxis(0) * (relPt.x < 0 ? -1.0f : 1.0f);
float depth = box.halfSize.y - std::abs(relPt.y);
if (depth < 0)
return 0;
else if (depth < min_depth) {
min_depth = depth;
normal = box.GetAxis(1) * (relPt.y < 0 ? -1.0f : 1.0f);
}
depth = box.halfSize.z - std::abs(relPt.z);
if (depth < 0)
return 0;
else if (depth < min_depth) {
min_depth = depth;
normal = box.GetAxis(2) * (relPt.z < 0 ? -1.0f : 1.0f);
}
Contact* contact = data->contacts;
contact->contactNormal = normal;
contact->contactPoint = point;
contact->penetration = min_depth;
// Nie wiemy do jakiego ciała sztywnego należy punkt,
// wiec używamy NULL.
contact->SetBodyData(box.body, NULL, data->friction, data->restitution);
data->AddContacts(1);
return 1;
}
unsigned CollisionDetector::BoxAndSphere(const CollisionBox& box, const CollisionSphere& sphere, CollisionData* data) {
// Transformacja centrum kuli w przestrzeń pudełka
Math::vec3f center = sphere.GetAxis(3);
Math::vec3f relCenter = box.transform.TransformInverse(center);
// Sprawdzenie czy możemy wykluczyć kontakt
if (std::abs(relCenter.x) - sphere.radius > box.halfSize.x ||
std::abs(relCenter.y) - sphere.radius > box.halfSize.y ||
std::abs(relCenter.z) - sphere.radius > box.halfSize.z)
return 0;
Math::vec3f closestPt(0, 0, 0);
float dist;
dist = relCenter.x;
closestPt.x = Math::MathUtils::Clamp(dist, -box.halfSize.x, box.halfSize.x);
dist = relCenter.y;
closestPt.y = Math::MathUtils::Clamp(dist, -box.halfSize.y, box.halfSize.y);
dist = relCenter.z;
closestPt.z = Math::MathUtils::Clamp(dist, -box.halfSize.z, box.halfSize.z);
// Sprawdzenie czy mamy kontakt
dist = (closestPt - relCenter).LengthSquared();
if (dist > sphere.radius * sphere.radius)
return 0;
Math::vec3f closestPtWorld = box.transform * closestPt;
Contact* contact = data->contacts;
contact->contactNormal = (closestPtWorld - center);
contact->contactNormal.Normalize();
contact->contactPoint = closestPtWorld;
contact->penetration = sphere.radius - std::sqrt(dist);
contact->SetBodyData(box.body, sphere.body, data->friction, data->restitution);
data->AddContacts(1);
return 1;
}
float CollisionDetector::PenetrationOnAxis(const CollisionBox& one, const CollisionBox& two, const NGE::Math::vec3f& axis, const NGE::Math::vec3f& toCenter) {
float oneProject = IntersectionTests::TransformToAxis(one, axis);
float twoProject = IntersectionTests::TransformToAxis(two, axis);
float distance = std::abs(toCenter.DotProduct(axis));
return oneProject + twoProject - distance;
}
bool CollisionDetector::TryAxis(const CollisionBox& one, const CollisionBox& two, const NGE::Math::vec3f& axis2, const NGE::Math::vec3f& toCenter,
unsigned index, float& smallestPentration, unsigned &smallestCase) {
Math::vec3f axis = axis2;
// Nie sprawdzamy prawie równoległych osi
if (axis.LengthSquared() < 0.0001)
return true;
axis.Normalize();
float penetration = PenetrationOnAxis(one, two, axis, toCenter);
if (penetration < 0) return false;
if (penetration < smallestPentration) {
smallestPentration = penetration;
smallestCase = index;
}
return true;
}
void CollisionDetector::FillPointFaceBoxBox(const CollisionBox& one, const CollisionBox& two, const NGE::Math::vec3f& toCenter, CollisionData* data, unsigned best, float pen) {
Contact* contact = data->contacts;
Math::vec3f normal = one.GetAxis(best);
if (one.GetAxis(best).DotProduct(toCenter) > 0)
normal = normal * -1.0f;
Math::vec3f vertex = two.halfSize;
if (two.GetAxis(0).DotProduct(normal) < 0)
vertex.x = -vertex.x;
if (two.GetAxis(1).DotProduct(normal) < 0)
vertex.y = -vertex.y;
if (two.GetAxis(2).DotProduct(normal) < 0)
vertex.z = -vertex.z;
contact->contactNormal = normal;
contact->penetration = pen;
contact->contactPoint = two.GetTransform() * vertex;
contact->SetBodyData(one.body, two.body, data->friction, data->restitution);
}
NGE::Math::vec3f CollisionDetector::ContactPoint(const NGE::Math::vec3f& pOne, const NGE::Math::vec3f& dOne, float oneSize, const NGE::Math::vec3f& pTwo, const NGE::Math::vec3f& dTwo,
float twoSize, bool useOne) {
Math::vec3f toSt, cOne, cTwo;
float dpStaOne, dpStaTwo, dpOneTwo, smOne, smTwo;
float denom, mua, mub;
smOne = dOne.LengthSquared();
smTwo = dTwo.LengthSquared();
dpOneTwo = dTwo.DotProduct(dOne);
toSt = pOne - pTwo;
dpStaOne = dOne.DotProduct(toSt);
dpStaTwo = dTwo.DotProduct(toSt);
denom = smOne * smTwo - dpOneTwo * dpOneTwo;
if (std::abs(denom) < 0.0001f)
return useOne ? pOne : pTwo;
mua = (dpOneTwo * dpStaTwo - smTwo * dpStaOne) / denom;
mub = (smOne * dpStaTwo - dpOneTwo * dpStaOne) / denom;
if (mua > oneSize || mua < -oneSize || mub > twoSize || mub < -twoSize)
return useOne ? pOne : pTwo;
else {
cOne = pOne + dOne * mua;
cTwo = pTwo + dTwo * mub;
return cOne * 0.5 + cTwo * 0.5;
}
}
| [
"tymoteusz.kubicz@gmail.com"
] | tymoteusz.kubicz@gmail.com |
49770a3defb1f84ccb78874177c758222babf16e | 36ad63674e2623b9c4fa8b2b4c167557177ac411 | /Headers/GenerateSchedule.h | 1ae2737dc25c9230dcc45faee2c9f1c637d39ef8 | [] | no_license | Gregory06/TimeTableGenerator | 791d01619fd0a852e981f98d15cb9952d52c0e7e | d285a97fae463795509b8669129be1a1ac2f4e8c | refs/heads/master | 2020-05-19T06:57:29.169974 | 2019-05-22T19:41:46 | 2019-05-22T19:41:46 | 184,886,771 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,028 | h | //
// Created by Gregory Postnikov on 2019-04-27.
//
#ifndef TIMETABLE_GENERATESCHEDULE_H
#define TIMETABLE_GENERATESCHEDULE_H
#include "SubjectClass.h"
#include "TeacherClass.h"
#include "GroupClass.h"
#include "EventClass.h"
#include "Constants.h"
Cabinet* GetFeasibleCabinet(std::map<std::string,Cabinet>& cabinets, Time start_time, size_t duration, size_t total_participants) {
Cabinet* fesible_cabinet = nullptr;
for (auto i = cabinets.begin(); i != cabinets.end(); i++) {
if ((*i).second.GetCapacity() < total_participants)
continue;
if (!(*i).second.IsFeasible(start_time, duration))
continue;
fesible_cabinet = &(*i).second;
break;
}
return fesible_cabinet;
}
template <typename T>
void RandomPermutation(std::vector<T> &vector) {
size_t permutations_count = vector.size();
T helper;
for (size_t i = 0; i < permutations_count; i++) {
size_t first_index = random() % permutations_count;
size_t second_index = random() % permutations_count;
helper = vector[first_index];
vector[first_index] = vector[second_index];
vector[second_index] = helper;
}
}
#include "TimeTableClass.h"
void DeleteEvent(TimeTable<Event>& timetable, Time time, std::vector<Group*> &groups) {
Event &event(timetable[(*groups.begin())->GetName()]->GetElem(time));
event.Deactivate();
for (size_t i = 0; i < event.GetDuration(); i++) {
for (auto group = groups.begin(); group != groups.end(); group++)
(*group)->ReleaseTime(event.GetStartTime()+i);
event.GetTeacher()->ReleaseTime(event.GetStartTime()+i);
event.GetCabinet()->ReleaseTime(event.GetStartTime()+i);
}
}
TimeTable<Event>& GenerateRandomSchedule(TimeTable<Event>& timetable, std::map<std::string,Subject>& subjects,
std::map<std::string,Teacher>& teachers, std::map<std::string,Group>& groups,
std::map<std::string,Cabinet>& cabinets) {
SubjectStorage subject_storage;
subject_storage.FillStorage(subjects);
bool prev_place_founded(true);
std::vector<std::vector<Time>> times_stack {};
Subject *current_subject = nullptr;
Time start_time;
while (!subject_storage.QueueEmpty()) {
std::srand(time(NULL));
// std::cout << "_______" << std::endl;
// subject_storage.StorageSize();
if (prev_place_founded) {
current_subject = subject_storage.QueueGetMin();
// std::cout << "OK0" << std::endl;
subject_storage.MoveMinToStack();
int64_t feasible_time = current_subject->GetResultingFeasibleTime();
std::vector<Time> shufled_fesible_time {};
Int2Vector(shufled_fesible_time, feasible_time);
RandomPermutation(shufled_fesible_time);
times_stack.push_back(shufled_fesible_time);
// std::cout << "OK1" << std::endl;
} else {
subject_storage.MoveTopToQueue();
times_stack.pop_back();
current_subject = subject_storage.StackGetTop();
std::vector<Group *> groups(current_subject->GetGroups());
// std::cout << "OK2" << std::endl;
DeleteEvent(timetable, times_stack.back().back(), groups);
// std::cout << "OK3" << std::endl;
times_stack.back().pop_back();
}
while (!times_stack.back().empty()) {
// std::cout << "OK5" << std::endl;
start_time = times_stack.back().back();
Cabinet *feasible_cabinet = GetFeasibleCabinet(cabinets, start_time, current_subject->GetDuration(),
current_subject->GetParticipantsNumber());
if (!feasible_cabinet) {
times_stack.back().pop_back();
continue;
}
std::vector<Group *> groups(current_subject->GetGroups());
// std::cout << "OK6" << std::endl;
// std::cout << current_subject->GetName() << ' ' << current_subject->GetDuration() << ' ' << ' ' \
// << current_subject->GetTeacher()->GetName() << ' ' <<feasible_cabinet->GetName() << std::endl;
// for (auto i = groups.begin(); i != groups.end(); i++)
// std::cout << (*i)->GetName() << std::endl;
// std::cout << "IM OK" << std::endl;
timetable.InsertEvent(current_subject->GetName(), current_subject->GetDuration(),
current_subject->GetType(), current_subject->GetTeacher(),
groups, start_time, feasible_cabinet);
prev_place_founded = true;
break;
}
if (times_stack.back().empty())
prev_place_founded = false;
if (subject_storage.StackEmpty()) {
std::cout << "GENERATION FAIL" << std::endl;
return timetable;
}
}
return timetable;
}
#endif //TIMETABLE_GENERATESCHEDULE_H
| [
"greg@MacBook-Pro-Gregory.local"
] | greg@MacBook-Pro-Gregory.local |
e293f7a488324fcad9d42a58a9ed41559c9ac362 | 9eaf679a99a88ccf42920fe7076856398b095402 | /Server/VerifyServer/src/TaskPoolModule - 副本.cpp | 81b62dd05c34d52c71127681094c84eae3060f44 | [] | no_license | daxingyou/MJ | 1fce631d11c14a2d08928260704a6c359bcca12b | 4fdfc39d710562cf6e493292c5e4afc967866a40 | refs/heads/master | 2021-06-18T19:18:08.864754 | 2017-07-11T10:05:56 | 2017-07-11T10:05:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,266 | cpp | #include "TaskPoolModule.h"
#include "WeChatOrderTask.h"
#include "Timer.h"
#include "ServerMessageDefine.h"
#include "log4z.h"
#include "ISeverApp.h"
#include "VerifyRequest.h"
#include "AppleVerifyTask.h"
#include "WeChatVerifyTask.h"
#include "DBVerifyTask.h"
#include "ApnsTask.h"
#include "AnyLoginTask.h"
void CTaskPoolModule::init( IServerApp* svrApp )
{
IGlobalModule::init(svrApp) ;
m_tTaskPool.init(this,3);
// test code
//static CTimer tTim ;
//tTim.setInterval(2) ;
//tTim.setIsAutoRepeat(false);
//tTim.setCallBack([this](CTimer* p , float f ){ printf("timer invoker\n");testFunc();}) ;
//tTim.start();
// test code
}
void CTaskPoolModule::onExit()
{
getPool().closeAll() ;
}
bool CTaskPoolModule::onMsg(stMsg* pMsg , eMsgPort eSenderPort , uint32_t nSessionID)
{
if ( IGlobalModule::onMsg(pMsg,eSenderPort,nSessionID) )
{
return true;
}
if ( MSG_VERIFY_ITEM_ORDER == pMsg->usMsgType )
{
onWechatOrder(pMsg,eSenderPort,nSessionID) ;
return true ;
}
if ( pMsg->usMsgType == MSG_VERIFY_TANSACTION )
{
onVerifyMsg(pMsg,eSenderPort,nSessionID) ;
return true ;
}
return false ;
}
bool CTaskPoolModule::onMsg(Json::Value& prealMsg ,uint16_t nMsgType, eMsgPort eSenderPort , uint32_t nSessionID)
{
if ( IGlobalModule::onMsg(prealMsg,nMsgType,eSenderPort,nSessionID ) )
{
return true ;
}
return false;
}
void CTaskPoolModule::update(float fDeta )
{
IGlobalModule::update(fDeta) ;
m_tTaskPool.update();
}
bool CTaskPoolModule::onAsyncRequest(uint16_t nRequestType , const Json::Value& jsReqContent, Json::Value& jsResult )
{
if ( eAsync_Apns != nRequestType )
{
return false ;
}
auto p = getPool().getReuseTaskObjByID( eTask_Apns );
CApnsTask* pTest = (CApnsTask*)p.get();
pTest->setRequest(jsReqContent);
getPool().postTask(p);
return true ;
}
void CTaskPoolModule::testFunc()
{
printf("task go \n") ;
uint32_t nCnt = 1 ;
while (nCnt--)
{
auto p = getPool().getReuseTaskObjByID( eTask_Apns );
CApnsTask* pTest = (CApnsTask*)p.get();
Json::Value jsRequest, target ;
target[0u] = 12709990 ;
jsRequest["apnsType"] = 0 ;
jsRequest["targets"] = target;
jsRequest["content"] = "test sfhg" ;
jsRequest["msgID"] = "fs";
jsRequest["msgdesc"] = "fhsg" ;
pTest->setRequest(jsRequest);
getPool().postTask(p);
}
}
ITask::ITaskPrt CTaskPoolModule::createTask( uint32_t nTaskID )
{
switch (nTaskID)
{
case eTask_WechatOrder:
{
std::shared_ptr<CWeChatOrderTask> pTask ( new CWeChatOrderTask(nTaskID)) ;
return pTask ;
}
break;
case eTask_WechatVerify:
{
std::shared_ptr<CWechatVerifyTask> pTask ( new CWechatVerifyTask(nTaskID)) ;
return pTask ;
}
break;
case eTask_AppleVerify:
{
std::shared_ptr<CAppleVerifyTask> pTask ( new CAppleVerifyTask(nTaskID)) ;
return pTask ;
}
break;
case eTask_DBVerify:
{
std::shared_ptr<CDBVerfiyTask> pTask ( new CDBVerfiyTask(nTaskID)) ;
return pTask ;
}
break;
case eTask_Apns:
{
std::shared_ptr<CApnsTask> pTask ( new CApnsTask(nTaskID)) ;
return pTask ;
}
break;
case eTask_AnyLogin:
{
std::shared_ptr<AnyLoginTask> pTask(new AnyLoginTask(nTaskID));
return pTask;
}
break;
default:
break;
}
return nullptr ;
}
// logic
void CTaskPoolModule::onWechatOrder( stMsg* pMsg, eMsgPort eSenderPort , uint32_t nSessionID )
{
stMsgVerifyItemOrder* pOrder = (stMsgVerifyItemOrder*)pMsg ;
auto pTask = getPool().getReuseTaskObjByID(eTask_WechatOrder);
CWeChatOrderTask* pTaskObj = (CWeChatOrderTask*)pTask.get();
// set call back
if ( pTask->getCallBack() == nullptr )
{
pTask->setCallBack([this](ITask::ITaskPrt ptr )
{
CWeChatOrderTask* pTask = (CWeChatOrderTask*)ptr.get();
auto pOrder = pTask->getCurRequest().get();
stMsgVerifyItemOrderRet msgRet ;
memset(msgRet.cPrepayId,0,sizeof(msgRet.cPrepayId));
memset(msgRet.cOutTradeNo,0,sizeof(msgRet.cOutTradeNo));
memcpy(msgRet.cOutTradeNo,pOrder->cOutTradeNo,sizeof(pOrder->cOutTradeNo));
memcpy(msgRet.cPrepayId,pOrder->cPrepayId,sizeof(msgRet.cPrepayId));
msgRet.nChannel = pOrder->nChannel ;
msgRet.nRet = pOrder->nRet ;
getSvrApp()->sendMsg(pOrder->nSessionID,(char*)&msgRet,sizeof(msgRet));
LOGFMTI("finish order for sessionid = %d, ret = %d ",pOrder->nSessionID,pOrder->nRet) ;
}
) ;
}
// set request info
std::shared_ptr<stShopItemOrderRequest> pRe = pTaskObj->getCurRequest() ;
if ( pRe == nullptr )
{
pRe = std::shared_ptr<stShopItemOrderRequest>( new stShopItemOrderRequest );
pTaskObj->setInfo(pRe);
}
memset(pRe.get(),0,sizeof(stShopItemOrderRequest)) ;
sprintf_s(pRe->cShopDesc,50,pOrder->cShopDesc);
sprintf_s(pRe->cOutTradeNo,32,pOrder->cOutTradeNo);
pRe->nPrize = pOrder->nPrize;
sprintf_s(pRe->cTerminalIp,17,pOrder->cTerminalIp);
pRe->nChannel = pOrder->nChannel ;
pRe->nFromPlayerUserUID = 0 ;
pRe->nSessionID = nSessionID ;
// do the request
getPool().postTask(pTask);
return ;
}
static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len)
{
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while (in_len--)
{
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (i = 0; (i <4) ; i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}
if (i)
{
for (j = i; j < 3; j++)
char_array_3[j] = '/0';
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]];
while ((i++ < 3))
ret += '=';
}
return ret;
}
void CTaskPoolModule::onVerifyMsg( stMsg* pMsg, eMsgPort eSenderPort , uint32_t nSessionID )
{
stMsgToVerifyServer* pReal = (stMsgToVerifyServer*)pMsg ;
IVerifyTask::VERIFY_REQUEST_ptr pRequest ( new stVerifyRequest() );
pRequest->nFromPlayerUserUID = pReal->nBuyerPlayerUserUID ;
pRequest->nShopItemID = pReal->nShopItemID;
pRequest->nBuyedForPlayerUserUID = pReal->nBuyForPlayerUserUID ;
pRequest->nChannel = pReal->nChannel ; // now just apple ;
pRequest->nSessionID = nSessionID ;
pRequest->nMiUserUID = pReal->nMiUserUID ;
LOGFMTD("received a transfaction need to verify shop id = %u userUID = %u channel = %d\n",pReal->nShopItemID,pReal->nBuyerPlayerUserUID,pReal->nChannel );
if ( pRequest->nMiUserUID && pRequest->nChannel == ePay_XiaoMi )
{
memcpy(pRequest->pBufferVerifyID,((unsigned char*)pMsg) + sizeof(stMsgToVerifyServer),pReal->nTranscationIDLen);
//m_MiVerifyMgr.AddRequest(pRequest) ;
LOGFMTE("we don't have xiao mi channel") ;
return ;
}
ITask::ITaskPrt pTask = nullptr ;
if ( pRequest->nChannel == ePay_AppStore )
{
std::string str = base64_encode(((unsigned char*)pMsg) + sizeof(stMsgToVerifyServer),pReal->nTranscationIDLen);
//std::string str = base64_encode(((unsigned char*)pMsg) + sizeof(stMsgToVerifyServer),20);
memcpy(pRequest->pBufferVerifyID,str.c_str(),strlen(str.c_str()));
pTask = getPool().getReuseTaskObjByID(eTask_AppleVerify) ;
}
else if ( ePay_WeChat == pRequest->nChannel || ePay_WeChat_365Golden == pRequest->nChannel )
{
memcpy(pRequest->pBufferVerifyID,((unsigned char*)pMsg) + sizeof(stMsgToVerifyServer),pReal->nTranscationIDLen);
std::string strTradeNo(pRequest->pBufferVerifyID);
std::string shopItem = strTradeNo.substr(0,strTradeNo.find_first_of('E')) ;
if ( atoi(shopItem.c_str()) != pRequest->nShopItemID )
{
printf("shop id and verify id not the same \n") ;
pRequest->eResult = eVerify_Apple_Error ;
sendVerifyResult(pRequest) ;
return ;
}
else
{
pTask = getPool().getReuseTaskObjByID(eTask_WechatVerify) ;
}
}
else
{
LOGFMTE("unknown pay channecl = %d, uid = %d",pRequest->nChannel,pReal->nBuyerPlayerUserUID ) ;
return ;
}
if ( !pTask )
{
LOGFMTE("why verify task is null ? ") ;
return ;
}
auto* pVerifyTask = (IVerifyTask*)pTask.get();
pVerifyTask->setVerifyRequest(pRequest) ;
pVerifyTask->setCallBack([this](ITask::ITaskPrt ptr )
{
auto* pAready = (IVerifyTask*)ptr.get();
auto pResult = pAready->getVerifyResult() ;
if ( eVerify_Apple_Error == pResult->eResult )
{
LOGFMTE("apple verify Error uid = %u, channel = %u,shopItem id = %u",pResult->nFromPlayerUserUID,pResult->nChannel,pResult->nShopItemID) ;
// send to client ;
sendVerifyResult(pResult) ;
return ;
}
LOGFMTI("apple verify success uid = %u, channel = %u,shopItem id = %u,go on DB verify",pResult->nFromPlayerUserUID,pResult->nChannel,pResult->nShopItemID) ;
doDBVerify(pResult);
} ) ;
getPool().postTask(pTask);
}
void CTaskPoolModule::sendVerifyResult(std::shared_ptr<stVerifyRequest> & pResult )
{
stMsgFromVerifyServer msg ;
msg.nShopItemID = pResult->nShopItemID ;
msg.nRet = pResult->eResult ;
msg.nBuyerPlayerUserUID = pResult->nFromPlayerUserUID ;
msg.nBuyForPlayerUserUID = pResult->nBuyedForPlayerUserUID ;
getSvrApp()->sendMsg(pResult->nSessionID,(char*)&msg,sizeof(msg));
LOGFMTI( "finish verify transfaction shopid = %u ,uid = %d ret = %d",msg.nShopItemID,msg.nBuyerPlayerUserUID,msg.nRet ) ;
}
void CTaskPoolModule::doDBVerify(uint32_t nUserUID, uint16_t nShopID, uint8_t nChannel,std::string& strTransfcationID)
{
IVerifyTask::VERIFY_REQUEST_ptr pRequest(new stVerifyRequest());
pRequest->nFromPlayerUserUID = nUserUID;
pRequest->nShopItemID = nShopID;
pRequest->nBuyedForPlayerUserUID = nUserUID;
pRequest->nChannel = nChannel;
pRequest->nSessionID = 0;
pRequest->nMiUserUID = 0;
memset(pRequest->pBufferVerifyID,0,sizeof(pRequest->pBufferVerifyID));
memcpy_s(pRequest->pBufferVerifyID, sizeof(pRequest->pBufferVerifyID),strTransfcationID.data(),strTransfcationID.size());
doDBVerify(pRequest);
}
void CTaskPoolModule::doDBVerify(IVerifyTask::VERIFY_REQUEST_ptr ptr)
{
auto pDBTask = getPool().getReuseTaskObjByID(eTask_DBVerify);
auto pDBVerifyTask = (IVerifyTask*)pDBTask.get();
pDBVerifyTask->setVerifyRequest(ptr);
pDBVerifyTask->setCallBack([this](ITask::ITaskPrt ptr){ auto pAready = (IVerifyTask*)ptr.get(); sendVerifyResult(pAready->getVerifyResult()); });
getPool().postTask(pDBTask);
}
ITask::ITaskPrt CTaskPoolModule::getReuseTask(eTask nTask)
{
return getPool().getReuseTaskObjByID(nTask);
}
void CTaskPoolModule::postTask(ITask::ITaskPrt pTask)
{
getPool().postTask(pTask);
} | [
"dengh_dhsea@126.com"
] | dengh_dhsea@126.com |
74f644779755eb88be1b578c3daf404e8abe8b80 | ef672fa41edac5ef96cafa30404d1e396f7536a8 | /src/administator.cpp | 1c53b65b216d3dcef92fbebd75b61949341ff159 | [] | no_license | rafalgrzeda/Multiliga | 2a443febf2e03e2ea30bb7992842a6241782ed7b | 5f76ea1fdd2ab44a836cadcee5ca86056a4c1955 | refs/heads/master | 2022-04-22T06:52:53.790035 | 2020-04-22T12:53:22 | 2020-04-22T12:53:22 | 257,899,361 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,228 | cpp | #include "administator.h"
#include "okno_paneladministratora.h"
#include "listakontuzytkownikow.h"
#include <QDebug>
Permanentny *Administator::getPerm()
{
return perm;
}
void Administator::setPerm(Permanentny *value)
{
perm = value;
}
Administator::Administator(Uzytkownik *uzyt)
:Uzytkownik (uzyt)
{
ID = uzyt->getID();
kod = uzyt->getKod();
typ = uzyt->getTyp();
imie = uzyt->getImie();
email = uzyt->getEmail();
haslo = uzyt->getHaslo();
login = uzyt->getLogin();
nazwisko = uzyt->getNazwisko();
Okno_panelAdministratora *admin_panel = new Okno_panelAdministratora(this);
admin_panel->show();
}
bool Administator::dodajUzytkownika(QString login, QString email, QString imie, QString nazwisko, QString haslo, QString typ)
{
//Sprawdzenie czy uzytkownik o podanym loginie istnieje - jestli nie -> dodanie do bazy
ListaKontUzytkownikow *lista = ListaKontUzytkownikow::getListaKontUzytkownikow();
if(lista->znajdz(login) == nullptr){
perm = new Uzytkownik(NULL,login,email,imie,nazwisko,haslo,typ,"0");
perm->zapisz(NULL);
lista->update();
delete perm;
return true;
}
else{
return false;
}
}
Permanentny* Administator::getUzytkownik(QString login)
{
//Pobranie uzytkownika z listy uzytkownikow
ListaKontUzytkownikow *lista = ListaKontUzytkownikow::getListaKontUzytkownikow();
Uzytkownik* uzyt= lista->znajdz(login);
perm = new Uzytkownik(uzyt);
qDebug() << "Admin - getUzytkownik()";
qDebug() << perm;
qDebug() << getPerm();
return perm;
}
void Administator::edytuj(QString login, QString email, QString imie, QString nazwisko, QString haslo, QString typ)
{
//Ogolnie caly czas perm zmienia swój adres w pamięci więc nic nie działa
qDebug() << "Admnistrator - edytuj";
qDebug() << perm;
//Pobranie ID starego Uzytkownika
//Uzytkownik *u = dynamic_cast<Uzytkownik*>(perm);
//int ID = u->getID();
/*
delete perm;
// Stowrzenie nowego uzytkownika;
perm = new Uzytkownik(ID,login,email,imie,nazwisko,haslo,typ,kod);
perm->zapisz(ID);
*/
}
| [
"noreply@github.com"
] | rafalgrzeda.noreply@github.com |
07188ffc2b4c750e78f28b1a336a131cd3d6736b | 0f10023be72f4ae93e657e715e42e98c3b6cf6dc | /src/qt/walletstack.cpp | e9addfa6224a98b6e4e6266ce2897b9d77870722 | [
"MIT"
] | permissive | kelepirci/bitcoinquality | a653f6ca6224eac40e6e974f6c8875b76c13e6c2 | ecd43ea0680571bf7d9d23fe4627e1f52b204c86 | refs/heads/master | 2021-08-20T05:54:38.919543 | 2017-11-28T10:19:43 | 2017-11-28T10:19:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,210 | cpp | /*
* Qt4 bitcoin GUI.
*
* W.J. van der Laan 2011-2012
* The BitcoinQuality Developers 2011-2013
*/
#include "walletstack.h"
#include "walletview.h"
#include "bitcoingui.h"
#include <QMap>
#include <QMessageBox>
WalletStack::WalletStack(QWidget *parent) :
QStackedWidget(parent),
clientModel(0),
bOutOfSync(true)
{
setContentsMargins(0,0,0,0);
}
WalletStack::~WalletStack()
{
}
bool WalletStack::addWallet(const QString& name, WalletModel *walletModel)
{
if (!gui || !clientModel || mapWalletViews.count(name) > 0)
return false;
WalletView *walletView = new WalletView(this, gui);
walletView->setBitcoinGUI(gui);
walletView->setClientModel(clientModel);
walletView->setWalletModel(walletModel);
walletView->showOutOfSyncWarning(bOutOfSync);
addWidget(walletView);
mapWalletViews[name] = walletView;
return true;
}
bool WalletStack::removeWallet(const QString& name)
{
if (mapWalletViews.count(name) == 0) return false;
WalletView *walletView = mapWalletViews.take(name);
removeWidget(walletView);
return true;
}
void WalletStack::removeAllWallets()
{
QMap<QString, WalletView*>::const_iterator i;
for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i)
removeWidget(i.value());
mapWalletViews.clear();
}
bool WalletStack::handleURI(const QString &uri)
{
WalletView *walletView = (WalletView*)currentWidget();
if (!walletView) return false;
return walletView->handleURI(uri);
}
void WalletStack::showOutOfSyncWarning(bool fShow)
{
bOutOfSync = fShow;
QMap<QString, WalletView*>::const_iterator i;
for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i)
i.value()->showOutOfSyncWarning(fShow);
}
void WalletStack::gotoOverviewPage()
{
QMap<QString, WalletView*>::const_iterator i;
for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i)
i.value()->gotoOverviewPage();
}
void WalletStack::gotoHistoryPage()
{
QMap<QString, WalletView*>::const_iterator i;
for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i)
i.value()->gotoHistoryPage();
}
void WalletStack::gotoAddressBookPage()
{
QMap<QString, WalletView*>::const_iterator i;
for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i)
i.value()->gotoAddressBookPage();
}
void WalletStack::gotoReceiveCoinsPage()
{
QMap<QString, WalletView*>::const_iterator i;
for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i)
i.value()->gotoReceiveCoinsPage();
}
void WalletStack::gotoSendCoinsPage(QString addr)
{
QMap<QString, WalletView*>::const_iterator i;
for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i)
i.value()->gotoSendCoinsPage(addr);
}
void WalletStack::gotoSignMessageTab(QString addr)
{
WalletView *walletView = (WalletView*)currentWidget();
if (walletView) walletView->gotoSignMessageTab(addr);
}
void WalletStack::gotoVerifyMessageTab(QString addr)
{
WalletView *walletView = (WalletView*)currentWidget();
if (walletView) walletView->gotoVerifyMessageTab(addr);
}
void WalletStack::encryptWallet(bool status)
{
WalletView *walletView = (WalletView*)currentWidget();
if (walletView) walletView->encryptWallet(status);
}
void WalletStack::backupWallet()
{
WalletView *walletView = (WalletView*)currentWidget();
if (walletView) walletView->backupWallet();
}
void WalletStack::changePassphrase()
{
WalletView *walletView = (WalletView*)currentWidget();
if (walletView) walletView->changePassphrase();
}
void WalletStack::unlockWallet()
{
WalletView *walletView = (WalletView*)currentWidget();
if (walletView) walletView->unlockWallet();
}
void WalletStack::setEncryptionStatus()
{
WalletView *walletView = (WalletView*)currentWidget();
if (walletView) walletView->setEncryptionStatus();
}
void WalletStack::setCurrentWallet(const QString& name)
{
if (mapWalletViews.count(name) == 0) return;
WalletView *walletView = mapWalletViews.value(name);
setCurrentWidget(walletView);
walletView->setEncryptionStatus();
}
| [
"info@bitcoinquality.org"
] | info@bitcoinquality.org |
4a0925d42c9761426aa1ae650fce0ae83abc90a1 | 13c3630445d73fb2703e5574b70942742f37fb89 | /Stable/Utils/MRSCompilerTool/MRSCompilerToolDlg.h | dd0db98db62131beeebc23398380bc436650cc72 | [] | no_license | NovaDV/Gunz1.5 | 8cb660462c386f4c35d7f5198e614a29d5276547 | 97e7bc51fd082e37f3de0f02c5e2ce6c33530c50 | refs/heads/main | 2023-06-14T15:41:07.759755 | 2021-07-11T18:25:07 | 2021-07-11T18:25:07 | 385,099,338 | 1 | 0 | null | 2021-07-12T02:10:18 | 2021-07-12T02:10:18 | null | UTF-8 | C++ | false | false | 902 | h |
// MRSCompilerToolDlg.h : header file
//
#pragma once
#include "MZip.h"
// CMRSCompilerToolDlg dialog
class CMRSCompilerToolDlg : public CDialogEx
{
// Construction
public:
CMRSCompilerToolDlg(CWnd* pParent = nullptr); // standard constructor
// Dialog Data
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_MRSCOMPILERTOOL_DIALOG };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
void FillListBoxes();
// Implementation
protected:
HICON m_hIcon;
FFileList zipFileList;
FFileList mrsFileList;
// Generated message map functions
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
DECLARE_MESSAGE_MAP()
public:
CListBox m_DecompileList;
CListBox m_CompileList;
CButton m_decompileButton;
afx_msg void OnBnClickedButton1();
afx_msg void OnBnClickedButton2();
};
| [
"jduncan0392@gmail.com"
] | jduncan0392@gmail.com |
a71de3a0662b499b9030ce2f9ca6aeb68f45d72b | 64c8ee39e4c3eb6cc987df675bc5fe88a4eac9cf | /QuanLyQN/QuanLyQN/qlThanhVien.cpp | a0112288999a3849e4cb47b7212f0eebe81fa397 | [] | no_license | aresuit97/oop | 6aee3309a2e0998a0a11d3c3d1d37f6be8803af8 | cc257460760433933998f94070f4fa917172f6c7 | refs/heads/main | 2023-02-18T07:27:51.815733 | 2021-01-13T16:42:06 | 2021-01-13T16:42:06 | 328,200,959 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 892 | cpp | #include "qlThanhVien.h"
qlThanhVien::qlThanhVien()
{
soLuong=0;
tv=nullptr;
}
void qlThanhVien:: display()
{
for(int i=0; i<soLuong; i++)
{
tv[i]->thongTinTaiKhoan();cout<<endl;
}
cout << endl;
}
ThanhVien** qlThanhVien::getds(){
return tv;
}
void qlThanhVien::themTV(ThanhVien* tvien )
{
if(soLuong==0)
{
soLuong=1;
tv=new ThanhVien*[1];
tv[0]=tvien;
}
else
{
ThanhVien** temp=new ThanhVien*[soLuong+1];
for (int i=0; i<soLuong; i++)
{
temp[i]=tv[i];
}
temp[soLuong]=tvien;
delete[] tv;
tv=temp;
soLuong++;
}
}
void qlThanhVien::reset(){
soLuong=0;
if(tv!=nullptr)delete[] tv;
tv=nullptr;
}
void qlThanhVien::setDSTV(ThanhVien** tvi){
tv=tvi;
};
| [
"noreply@github.com"
] | aresuit97.noreply@github.com |
65ac16e39f216db8b51e3cfcb60eddd1514b5275 | 75988ecd13abc28244b4940571dcf0ba6b4e148f | /net/ReNetConfig.cpp | f782bd09813e4eb6550e10883d31543830117d95 | [] | no_license | republib/reqt | 481e2c555a389a6d860992d6c0e8c42dbb937315 | 327e0ddb6bcf8e46b6146ae9aef913e61af94a10 | refs/heads/master | 2021-01-10T05:09:14.143557 | 2015-12-25T08:18:29 | 2015-12-25T08:41:50 | 48,549,961 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 524 | cpp | /*
* ReNetConfig.cpp
*
* (Un)License: Public Domain
* You can use and modify this file without any restriction.
* Do what you want.
* No warranties and disclaimer of any damages.
* More info: http://unlicense.org
* The latest sources: https://github.com/republib
*/
#include "base/rebase.hpp"
#include "math/remath.hpp"
#include "net/renet.hpp"
const char* ReNetConfig::IP = "connection.ip";
const char* ReNetConfig::PORT = "connection.port";
const char* ReNetConfig::SLEEP_MILLISEC = "connection.sleepmillisec";
| [
"republib@gmx.de"
] | republib@gmx.de |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.