hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
358329894e63b1079bd7ce71c2f7061fafab24dc | 50,114 | cpp | C++ | PiTool/src/ResourceModel.cpp | nlyan/PiTool | bd50739de4a9f6e2a294351d0cd96c9efb1ec817 | [
"BSD-3-Clause"
] | 46 | 2019-09-24T19:30:06.000Z | 2022-02-05T12:51:52.000Z | PiTool/src/ResourceModel.cpp | nlyan/PiTool | bd50739de4a9f6e2a294351d0cd96c9efb1ec817 | [
"BSD-3-Clause"
] | 6 | 2019-09-24T20:10:35.000Z | 2019-12-29T22:55:12.000Z | PiTool/src/ResourceModel.cpp | nlyan/PiTool | bd50739de4a9f6e2a294351d0cd96c9efb1ec817 | [
"BSD-3-Clause"
] | 18 | 2019-09-24T19:36:39.000Z | 2022-02-05T12:51:55.000Z | #include "ResourceModel.h"
#include <QDir>
#include <QFile>
#include <QStandardPaths>
#include <QProcess>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QSettings>
#include <QDesktopServices>
#include "quazip/JlCompress.h"
#include <QDebug>
#include "piservice.h"
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QPixmap>
#include "OnlineModel.h"
#include "PiLog/WinCommon.h"
#include "diagnoseHandler.h"
#define RESOURCE_FILE "resource.json"
ResourceModel *resourceModel=nullptr;
#define RESOURCE_TYPE_GAME "game"
#define RESOURCE_TYPE_VIDEO "video"
#define RESOURCE_TYPE_PICTURE "picture"
QString gLaunchedApp="";
ResourceModel::ResourceModel(QObject *parent) : QObject(parent){
qInfo()<<"ResourceModel";
mRpcServer = nullptr;
if(resourceModel){
return;
}
initResource();
mRpcServer = new RpcServer(parent);
mRpcServer->setCallback(&ResourceModel::rpcServer_CallbackSt);
resourceModel = this;
}
ResourceModel::~ResourceModel(){
qInfo()<<"~ResourceModel";
if(mRpcServer){
delete mRpcServer;
mRpcServer = nullptr;
}
mResourceList.clear();
mSearchResultList.clear();
}
bool __stdcall ResourceModel::rpcServer_CallbackSt(QWebSocket *pSocket,QString process,QJsonObject param){
if(resourceModel){
return resourceModel->rpcServer_Callback(pSocket,process,param);
}
return false;
}
void ResourceModel::sendMessage_addResource(QString resId){
qInfo()<<"sendMessage_addResource "<<resId;
if(resourceModel){
QString param = QString("{\"id\":\"%1\"}").arg(resId);
resourceModel->mRpcServer->sendMessage("addResource",param);
}else{
qInfo()<<"sendMessage_addResource resourceModel is null";
}
}
void ResourceModel::sendMessage_deleteResource(QString resId){
qInfo()<<"sendMessage_deleteResource "<<resId;
if(resourceModel){
QString param = QString("{\"id\":\"%1\"}").arg(resId);
resourceModel->mRpcServer->sendMessage("deleteResource",param);
}else{
qInfo()<<"sendMessage_deleteResource resourceModel is null";
}
}
void ResourceModel::sendMessage_statusChanged(QString resId,int status){
if(resourceModel){
QString param = QString("{\"id\":\"%1\",\"status\":%2}").arg(resId).arg(status);
resourceModel->mRpcServer->sendMessage("statusChanged",param);
}else{
qInfo()<<"sendMessage_statusChanged resourceModel is null";
}
}
void ResourceModel::sendMessage_progressChanged(QString resId,int status,qint64 total_bytes,qint64 downloaded_bytes){
// qInfo()<<"sendMessage_progressChanged "<<resId<<status;
if(resourceModel){
QString param = QString("{\"id\":\"%1\",\"status\":%2,\"total_bytes\":%3,\"downloaded\":%4}")
.arg(resId).arg(status).arg(total_bytes).arg(downloaded_bytes);
resourceModel->mRpcServer->sendMessage("progressChanged",param);
}else{
qInfo()<<"sendMessage_progressChanged resourceModel is null";
}
}
bool ResourceModel::rpcServer_Callback(QWebSocket *pSocket,QString process,QJsonObject param){
qDebug()<<"rpcServer_Callback"<<process<<param;
if(process=="downloadResource"){
QString resId = JsonHandler::getJsonValue(param,"id","");
QString third_id = JsonHandler::getJsonValue(param,"third_id","");
QString type = JsonHandler::getJsonValue(param,"type","");
QString sub_type = JsonHandler::getJsonValue(param,"sub_type","");
QString download_url = JsonHandler::getJsonValue(param,"download_url","");
QString image_url = JsonHandler::getJsonValue(param,"image_url","");
QString title = JsonHandler::getJsonValue(param,"title","");
QString desc = JsonHandler::getJsonValue(param,"desc","");
if(downloadResouce(resId,third_id,type,sub_type,download_url,image_url,title,desc)){
mRpcServer->sendCallback(pSocket,process,true);
}else{
mRpcServer->sendCallback(pSocket,process,false,mError);
}
return true;
}
if(process=="deleteResource"){
QString resId = JsonHandler::getJsonValue(param,"id","");
bool deleteFile = JsonHandler::getJsonValue(param,"delete_file",false);
if(deleteResource(resId,deleteFile)){
mRpcServer->sendCallback(pSocket,process,true);
}else{
mRpcServer->sendCallback(pSocket,process,false,mError);
}
return true;
}
if(process=="startDownload"){
QString resId = JsonHandler::getJsonValue(param,"id","");
startDownload(resId);
mRpcServer->sendCallback(pSocket,process,true);
return true;
}
if(process=="stopDownload"){
QString resId = JsonHandler::getJsonValue(param,"id","");
stopDownload(resId);
mRpcServer->sendCallback(pSocket,process,true);
return true;
}
if(process=="playGame"){
QString resId = JsonHandler::getJsonValue(param,"id","");
if(playGame(resId)){
mRpcServer->sendCallback(pSocket,process,true);
}else{
mRpcServer->sendCallback(pSocket,process,false,mError);
}
return true;
}
if(process=="playVideo"){
QString resId = JsonHandler::getJsonValue(param,"id","");
if(playVideoEx(resId)){
mRpcServer->sendCallback(pSocket,process,true);
}else{
mRpcServer->sendCallback(pSocket,process,false,mError);
}
return true;
}
if(process=="getStatus"){
QString resId = JsonHandler::getJsonValue(param,"id","");
QObject *object = getItem(resId,"");
QJsonObject json;
if(object==nullptr){
json.insert("status",-1);
}else{
ResourceItem *item = (ResourceItem*)object;
json.insert("status",item->status());
json.insert("total_bytes",item->totalBytes());
json.insert("downloaded",item->readBytes());
}
QJsonDocument document;
document.setObject(json);
QByteArray byteArray = document.toJson(QJsonDocument::Compact);
QString values = QString(byteArray);
mRpcServer->sendCallback(pSocket,process,QString("true"),values);
return true;
}
if(process=="openUrl"){
QString url = JsonHandler::getJsonValue(param,"url","");
if(url!=""){
QDesktopServices::openUrl(QUrl(url));
mRpcServer->sendCallback(pSocket,process,true);
}
return true;
}
if(process=="openSteam"){
if(!steamVrIsInstalled()){
Setting::callQmlFunc("showInstallSteamVr");
return true;
}
launchSteamVr();
}
return false;
}
void ResourceModel::initResource(){
QString roamingPiToolDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
QString manifestDir = roamingPiToolDir+"\\manifest";
QDir dir(manifestDir);
if(!dir.exists()){
QDir().mkpath(manifestDir);
}
QStringList nameFilters;
nameFilters.append("*.json");
for(QString fileName:dir.entryList(nameFilters)){
if(fileName.contains("steam.") || fileName.contains("ocs_")){
continue;
}
ResourceItem *item = new ResourceItem();
if(item->loadFromFile(manifestDir+"\\"+fileName)){
mResourceList.append(item);
}else{
QFile(manifestDir+"\\"+fileName).remove();
delete item;
}
}
qInfo()<<"initResource tool size"<<mResourceList.size();
QString piplayManifestDir = roamingPiToolDir.remove("PiTool") + "PiPlay\\manifest";
QDir oldDir(piplayManifestDir);
if(oldDir.exists()){
QStringList nameFilters;
nameFilters.append("*.json");
for(QString fileName:oldDir.entryList(nameFilters)){
if(fileName.contains("steam.") || fileName.contains("ocs_")){
continue;
}
ResourceItem *item = new ResourceItem();
if(item->loadFromFile(piplayManifestDir+"\\"+fileName)){
mResourceList.append(item);
}else{
QFile(piplayManifestDir+"\\"+fileName).remove();
delete item;
}
}
}
qInfo()<<"initResource piplay size:"<<mResourceList.size();
checkSteamGame();
checkOculusGame();
loadPiplay1Data();
}
void ResourceModel::sortList(QList<QObject*> *list,int sortType){
if(sortType==SORT_BY_DATE){
qSort(list->begin(),list->end(),compareResourceItem);
}else if(sortType==SORT_BY_NAME){
qSort(list->begin(),list->end(),compareResourceItemByName);
}else if(sortType==SORT_BY_PLAYTIME){
qSort(list->begin(),list->end(),[](QObject *itemA,QObject *itemB){
ResourceItem *item1 = (ResourceItem*)itemA;
ResourceItem *item2 = (ResourceItem*)itemB;
qInfo()<<"item1 paly time:"<<item1->play_time()<<" ;name:"<<item1->title();
qInfo()<<"item2 paly time:"<<item2->play_time()<<" ;name:"<<item2->title();
return (item1->play_time() - item2->play_time() >0);
});
// qSort(list->begin(),list->end(),compareResourceItemByPlayTime);
}else if(sortType==SORT_BY_BOUGHT_TIME){
qSort(list->begin(),list->end(),[](QObject *itemA,QObject *itemB){
ResourceItem *item1 = (ResourceItem*)itemA;
ResourceItem *item2 = (ResourceItem*)itemB;
return (item1->bought_time()- item2->bought_time()>0);
});
}else if(sortType==SORT_BY_RELEASE_DATE){
qSort(list->begin(),list->end(),[](QObject *itemA,QObject *itemB){
ResourceItem *item1 = (ResourceItem*)itemA;
ResourceItem *item2 = (ResourceItem*)itemB;
QByteArray temp1 = item1->releaseDate().toLocal8Bit();
const char *date1 = temp1.constData();
QByteArray temp2 = item2->releaseDate().toLocal8Bit();
const char *date2 = temp2.constData();
return (strcmp(date1,date2)>0);
});
}
}
void ResourceModel::searchResource(QString keyword,int resType,int sortType,bool downloading,bool upgrading){
mSearchResultList.clear();
keyword = keyword.toLower();
QString types[]={"game","video","picture"};
for(int i=0;i<mResourceList.size();i++){
ResourceItem *item = (ResourceItem*)mResourceList.at(i);
if(item->status()==ResourceItem::STATUS_DELETED){
continue;
}
if(downloading&&item->status()==0){
continue;
}
if(!downloading&&item->status()>0){
continue;
}
if(upgrading&&item->upgradeFlag()==0){
continue;
}
if(resType>0&&resType<4&&types[resType-1]!=item->type()){
continue;
}
if(!keyword.isEmpty()
&&item->title().toLower().indexOf(keyword)==-1
&&item->subType()!=keyword
){
continue;
}
mSearchResultList.append(mResourceList.at(i));
}
sortList(&mSearchResultList,sortType);
emit searchResultListChanged(mSearchResultList);
}
void ResourceModel::searchResource(QString keyword,int resType,int sortType,int searchType, int gameType){
mSearchResultList.clear();
keyword = keyword.toLower();
QString types[]={"game","video","picture"};
for(int i=0;i<mResourceList.size();i++){
ResourceItem *item = (ResourceItem*)mResourceList.at(i);
if(item->status()==ResourceItem::STATUS_DELETED){
continue;
}
if(searchType==0&&item->status()>0){
continue;
}
if(searchType==1&&(item->status()==ResourceItem::STATUS_LOCAL||item->status()==ResourceItem::STATUS_ONLINE)){
continue;
}
if(searchType==2&&item->upgradeFlag()==0){
continue;
}
if(searchType==3&&!item->bought()){
continue;
}
if(resType>0&&resType<4&&types[resType-1]!=item->type()){
continue;
}
if(!keyword.isEmpty()
&&item->title().toLower().indexOf(keyword)==-1
&&item->subType()!=keyword
){
continue;
}
if(((SORT_BY_GAME_STEAMVR == gameType) && (item->subType() != "steam")) ||
((SORT_BY_GAME_OCULUS == gameType) && (item->subType() != "oculus")) ||
((SORT_BY_GAME_LOCAL == gameType) && (item->subType() != "pimax"))){
continue;
}
mSearchResultList.append(mResourceList.at(i));
}
sortList(&mSearchResultList,sortType);
emit searchResultListChanged(mSearchResultList);
}
bool ResourceModel::compareResourceItem(QObject *itemA,QObject *itemB){
ResourceItem *item1 = (ResourceItem*)itemA;
ResourceItem *item2 = (ResourceItem*)itemB;
qint64 create_date1 = item1->create_time();
qint64 create_date2 = item2->create_time();
if(create_date1>create_date2){
return true;
}else if(create_date1<create_date2){
return false;
}else{
return item1->id().compare(item2->id())>0;
}
}
bool ResourceModel::compareResourceItemByName( QObject *itemA,QObject *itemB){
ResourceItem *item1 = (ResourceItem*)itemA;
ResourceItem *item2 = (ResourceItem*)itemB;
QByteArray temp1 = item1->title().toLower().toLocal8Bit();
const char *title1 = temp1.constData();
QByteArray temp2 = item2->title().toLower().toLocal8Bit();
const char *title2 = temp2.constData();
qInfo()<<"item1 paly name:"<<title1;
qInfo()<<"item2 paly name:"<<title2;
if(strcmp(title1,title2)>0){
return false;
}else{
return true;
}
}
bool ResourceModel::compareResourceItemByPlayTime( QObject *itemA,QObject *itemB){
ResourceItem *item1 = (ResourceItem*)itemA;
ResourceItem *item2 = (ResourceItem*)itemB;
qint64 time1 = item1->play_time();
qint64 time2 = item2->play_time();
if(time1>time2){
return true;
}else if(time1<time2){
return false;
}else{
return item1->id().compare(item2->id())>0;
}
}
QString supportFilePosfixs=",exe,mp4,mkv,rm,rmvb,wmv,avi,3gp,flv,mpeg,vod,mov,jpg,png,jpeg,bmp,svg,swf";
ResourceItem* ResourceModel::loadLocalResouce(QString resourceType, QString fileName,QString name,bool showError,QString resId){
if(fileName.indexOf("file:///")==0){
fileName = fileName.right(fileName.length()-QString("file:///").length());
}
QString filePosfix = fileName.mid(fileName.lastIndexOf(".")+1).toLower();
qDebug()<<"loadLocalResouce "<<fileName<<filePosfix;
if(supportFilePosfixs.indexOf(","+filePosfix+",")==-1){
if(showError){
Setting::showAlertEx("import.invalid");
}
return nullptr;
}
QList<QObject*> list = mResourceList;
for(int i=0;i<list.length();i++){
ResourceItem *item = (ResourceItem *)list.at(i);
if(item->status()==ResourceItem::STATUS_DELETED){
continue;
}
if(item->file()==fileName){
qDebug()<<"loadLocalResouce exist: "<<i;
if(showError){
Setting::showAlertEx("import.exist");
}
return nullptr;
}
}
QString title="Local";
if(name!=""){
title = name;
}else{
int pos1 = fileName.lastIndexOf('/');
int pos2 = fileName.lastIndexOf('.');
title = fileName.mid(pos1+1,pos2-pos1-1);
}
QDateTime now = QDateTime::currentDateTime();
static int seq_id = 100;
QString id = QString::number(now.toSecsSinceEpoch())+QString::number(seq_id++);
if(!resId.isEmpty()){
id = resId;
}
ResourceItem *resource = new ResourceItem();
resource->setId(id);
resource->setTitle(title);
resource->setFile(fileName);
resource->setType(resourceType);
resource->setSubType(resourceType==RESOURCE_TYPE_GAME?"pimax":"2d");
resource->setStatus(ResourceItem::STATUS_LOCAL);
if(resourceType==RESOURCE_TYPE_PICTURE){
QPixmap pixmap(fileName);
pixmap = pixmap.scaled(200,135);
QString imageFile = fileName.replace("."+filePosfix,"_thumbnail."+filePosfix);
if(pixmap.save(imageFile)){
resource->setImageUrl("file:///"+imageFile);
}else{
resource->setImageUrl("qrc:/resource/video_default.png");
}
}else{
resource->setImageUrl(resourceType==RESOURCE_TYPE_GAME?"qrc:/resource/game_default.png":"qrc:/resource/video_default.png");
}
resource->setCreateTime();
resource->saveToFile();
mResourceList.insert(0,resource);
emit resCountChanged(getResCount());
sendMessage_addResource(id);
return resource;
}
bool ResourceModel::loadLocalResouce(QString resourceType, QString fileName){
if(loadLocalResouce(resourceType,fileName,"",false,"")){
return true;
}else{
return false;
}
}
int ResourceModel::getDlingCount(){
int count = 0;
for(int i=0;i<mResourceList.length();i++){
ResourceItem *item = (ResourceItem*)mResourceList.at(i);
if(item->status()>0
&&item->status()!=ResourceItem::STATUS_DELETED
&&item->status()!=ResourceItem::STATUS_ONLINE){
count++;
}
}
return count;
}
int ResourceModel::getResCount(){
int count = 0;
for(int i=0;i<mResourceList.length();i++){
ResourceItem *item = (ResourceItem*)mResourceList.at(i);
if(item->status()!=ResourceItem::STATUS_DELETED){
count++;
}
}
return count;
}
QList<QObject*> ResourceModel::searchResultList(){
return mSearchResultList;
}
QObject* ResourceModel::getItem(QString id,QString third_id) const{
for(int i=0;i<mResourceList.length();i++){
ResourceItem *item = (ResourceItem*)mResourceList.at(i);
if(item->id()==id ||
(!third_id.isEmpty()&&item->thirdId()==third_id)){
return (QObject*)item->getObject();
}
}
return nullptr;
}
bool ResourceModel::isSteamApp(QString appFile){
qInfo()<<"isSteamApp"<<appFile;
QString appDir = appFile.left(appFile.toLower().lastIndexOf(".exe"))+"_Data";
for(int index = 0; index < m_oculusAppPathList.size(); index++){
m_oculusAppPath = m_oculusAppPathList.at(index);
if(appDir.contains(m_oculusAppPath)){
qInfo()<<"is oculus home app";
return false;
}
}
if(QDir(appDir).exists()&&QFile(appDir+"\\Plugins\\openvr_api.dll").exists()){
return true;
}
return false;
}
bool ResourceModel::launchApp(QString id,QString app,QString param,bool bChecked){
if(!PiService::getInstance()->connect()){
Setting::callQmlFunc("showDisconnectMessage");
return true;
}
if(bChecked&&!QFile(app).exists()){
m_nError = ERROR_FILE_NOT_EXIST;
return false;
}
app = app.replace("/","\\");
QString appName = app.mid(app.lastIndexOf("\\")+1);
QString playUrl = "";
QString workingDirectory="";
if(!isSteamApp(app)&&PiService::getInstance()->modeType()==0&&app.indexOf("UnityPVRPlayer")==-1){
playUrl = Setting::getOvrLauncher()+" "+app.replace("/","\\")+"";
if(!param.isEmpty()){
playUrl = playUrl+" \""+param.replace("/","\\")+"\"";
}
}else{
playUrl = "\""+app.replace("/","\\")+"\"";
if(!param.isEmpty()){
playUrl = playUrl+" \""+param.replace("/","\\")+"\"";
}else{
workingDirectory = app.left(app.lastIndexOf("\\"));
qInfo()<<"workingDirectory "<<workingDirectory;
}
}
killSteamVr();
killAllProcess();
gLaunchedApp = appName;
QProcess *process = new QProcess();
process->setWorkingDirectory(workingDirectory);
process->start(playUrl,QStringList());
qInfo()<<"launchApp"<<appName<<playUrl;
addProcess(id,process);
return true;
}
void ResourceModel::processFinished(int exitCode, QProcess::ExitStatus exitStatus){
QProcess *process = qobject_cast<QProcess*>(sender());
qInfo()<<"processFinished,exitCode="<<exitCode<<"exitStatus="<<exitStatus;
qInfo()<<"program"<<process->program();
for(int i=0;i<mProcessList.size();i++){
MyProcess *myProcess = mProcessList.at(i);
if(myProcess->process==process){
mProcessList.removeAt(i);
delete myProcess;
}
}
delete process;
}
void ResourceModel::killSteamVr(){
mSteamModel.killSteamVr();
}
bool ResourceModel::playGame(QString id){
for(int i=0;i<mResourceList.length();i++){
ResourceItem *item = (ResourceItem *)mResourceList.at(i);
if(item->id()==id){
if(item->subType()=="steam"&&!QFile(item->file()).exists()){
qInfo()<<"openItem "<<item->download_url();
killAllProcess();
gLaunchedApp = "";
item->setPlayTime();
QDesktopServices::openUrl(QUrl(item->download_url()));
return true;
}
if(item->subType()=="oculus"){
qInfo()<<"oculus game"<<item->file();
item->setPlayTime();
return launchApp(id,item->file(),"",false);
}
if(!QFile(item->file()).exists()){
m_nError = ERROR_FILE_NOT_EXIST;
mError = tr("game file not exist!");
return false;
}
item->setPlayTime();
return launchApp(id,item->file(),"");
}
}
return true;
}
bool ResourceModel::playVideoEx(QString resId){
ResourceItem *foundItem = nullptr;
for(int i=0;i<mResourceList.length();i++){
ResourceItem *item = (ResourceItem *)mResourceList.at(i);
if(item->id()==resId){
foundItem = item;
break;
}
}
if(foundItem){
if(foundItem->subType()=="2D"||foundItem->subType()=="3D"){
return play2DVideo(resId);
}else{
return playVideo(resId);
}
}
return true;
}
bool ResourceModel::playVideo(QString id){
return true;
}
bool ResourceModel::play2DVideo(QString id){
return true;
}
void ResourceModel::playOnlineVideo(QString url){
qInfo()<<"playOnlineVideo"<<url;
if(PiService::getInstance()->modeType()==1){
//launchApp("",Setting::getVideoPlayer2D(),url);
return;
}
QString videoPlayer = "";//Setting::getVideoPlayer();
if(!videoPlayer.contains("UnityPVRPlayer",Qt::CaseInsensitive)){
videoPlayer = "";//Setting::getInstallPath()+"\\UnityPVRPlayer\\UnityPVRPlayer.exe";
}
QString playUrl = "\""+videoPlayer+"\" "+url;
qInfo()<<"playOnlineVideo"<<playUrl;
QProcess().start(playUrl);
}
void ResourceModel::playResource(QString fileName){
if(fileName.indexOf("file:///")==0){
fileName = fileName.right(fileName.length()-QString("file:///").length());
}
QString filePosfix = fileName.mid(fileName.lastIndexOf(".")+1).toLower();
qInfo()<<"playResource "<<fileName<<filePosfix;
if(supportFilePosfixs.indexOf(","+filePosfix+",")==-1){
Setting::showAlertEx("import.invalid");
return;
}
if(filePosfix=="exe"){//game
launchApp("",fileName,"");
}else if(PiService::getInstance()->modeType()==1){
//launchApp("",Setting::getVideoPlayer2D(),fileName);
}else{
//launchApp("",Setting::getVideoPlayer(),fileName);
}
}
bool ResourceModel::deleteResource(QString resId,bool deleteFile){
qInfo()<<"deleteResource"<<resId<<deleteFile<<mResourceList.length();
ResourceItem *item = getResourceItem(resId);
if(item!=nullptr){
item->deleteItem(deleteFile);
if(item->bought()){
item->setStatus(ResourceItem::STATUS_ONLINE);
}else{
mResourceList.removeOne(item);
}
emit resCountChanged(getResCount());
emit dlingCountChanged(getDlingCount());
return true;
}
mError = tr("Resource is not exist");
return false;
}
bool ResourceModel::downloadResouce(QString id, QString thirdId,QString type,QString subType,QString download_url,QString image_url,QString title,QString desc){
if(!QDir(Setting::getDownloadDir()).exists()){
Setting::showAlertEx("download.path.removed");
mError = tr("download path removed");
return false;
}
qInfo()<<"downloadResource"<<id<<thirdId<<type<<subType<<download_url<<image_url<<title<<desc;
ResourceItem *resource = getResourceItem(id);
if(resource!=nullptr){
if(resource->status()!=ResourceItem::STATUS_ONLINE){
return false;
}
resource->setId(id);
resource->setDownloadUrl(download_url);
resource->setFile(getFileName(id,download_url,type));
resource->setCreateTime();
resource->setStatus(ResourceItem::STATUS_READY_DOWNLOAD);
}else{
resource = new ResourceItem(id, thirdId, type, subType, download_url, image_url, title, desc);
mResourceList.append(resource);
resource->setFile(getFileName(id,download_url,type));
resource->setStatus(ResourceItem::STATUS_READY_DOWNLOAD);
sendMessage_addResource(id);
}
emit dlingCountChanged(getDlingCount());
emit resCountChanged(getResCount());
connect(resource,SIGNAL(downloadFinished(ResourceItem*)),this,SLOT(downloadFinished(ResourceItem*)));
resource->startDownload();
return true;
}
QString ResourceModel::getFileName(QString id,QString url,QString type){
QFileInfo info(url);
QString fileName(info.fileName());
QString filePath = Setting::getDownloadDir();
if(type=="game"){
filePath+="\\games";
}else if(type=="video"){
filePath+="\\videos";
}else{
filePath+="\\apps";
}
QDir().mkdir(filePath);
if(fileName.isEmpty()){
if(type=="video"){
fileName = id+".mp4.tmp";
}else{
fileName = id+".zip.tmp";
}
}else{
fileName = fileName+".tmp";
}
return filePath + "\\" + fileName;
}
void ResourceModel::startDownload(QString id){
qInfo()<<"startDownload "<<id;
for(int i=0;i<mResourceList.length();i++){
ResourceItem *item = (ResourceItem *)mResourceList.at(i);
if(item->id().compare(id)==0){
connect(item,SIGNAL(downloadFinished(ResourceItem*)),this,SLOT(downloadFinished(ResourceItem*)));
item->startDownload();
}
}
}
void ResourceModel::stopDownload(QString id){
qInfo()<<"stopDownload "<<id;
for(int i=0;i<mResourceList.length();i++){
ResourceItem *item = (ResourceItem *)mResourceList.at(i);
if(item->id().compare(id)==0){
item->stopDownload();
}
}
}
void ResourceModel::downloadFinished(ResourceItem *item){
qInfo()<<"downloadFinished "<<item->id()<<item->status();
Setting::showMessage("\""+item->title()+"\""+tr("Download Finished"));
emit dlingCountChanged(getDlingCount());
emit resCountChanged(getResCount());
}
QString ResourceModel::formatBytes(quint64 bytes){
if(bytes<100*1024){
return QString::number((double)bytes/1024,'f',2)+"KB";
}else if(bytes<1024*1024*1024){
return QString::number((double)bytes/1024/1024,'f',2)+"MB";
}
return QString::number((double)bytes/1024/1024/1024,'f',2)+"GB";
}
bool ResourceModel::steamVrIsInstalled(){
return mSteamModel.steamVrIsInstalled();
}
void ResourceModel::loadSteamVrGame(){
m_steamGames.clear();
if(!steamVrIsInstalled()){
qInfo()<<"steamvr is not installed";
return;
}
int oldSize = mResourceList.size();
QJsonObject obj = JsonHandler::loadJsonObject(mSteamModel.m_steamManifestPath);
QJsonArray defaultArray;
QJsonArray jsonApps =JsonHandler::getJsonValue(obj,"applications",defaultArray);
qInfo()<<"steamvr app:"<<mSteamModel.m_steamManifestPath<<" size:"<<jsonApps.size();
for(int i=0;i<jsonApps.size();i++){
QJsonObject jsonObject = jsonApps.at(i).toObject();
ResourceItem *resource = new ResourceItem();
if(resource->loadSteamVr(jsonObject)){//&&!mSteamModel.steamGameIsDownloding(resource->id())){
resource->setFile(mSteamModel.getExeFile(resource->id()));
m_steamGames.append(resource->id());
if(!appendLocalResource(resource)){
qInfo()<<"append local resource failed.";
delete resource;
}else{
resource->downloadImage();
emit resCountChanged(getResCount());
sendMessage_addResource(resource->id());
}
}else{
delete resource;
qInfo()<<"delete steamvr resource";
}
}
if(oldSize!=mResourceList.size()){
emit resCountChanged(getResCount());
}
}
void ResourceModel::launchSteamVr(){
if(steamVrIsInstalled()){
killSteamVr();
QString exe = "\""+mSteamModel.m_steamVRFile+"\"";
QProcess().startDetached(exe);
qInfo()<<"launchSteamVr()"<<exe;
}
// QDesktopServices::openUrl(QUrl("steam://rungameid/250820"));
}
void ResourceModel::reService()
{
DiagnoseHandler handle;
handle.stopServiceByName("PiServiceLauncher");
handle.startService();
if (WinCommon::processAlived("vrserver.exe") ||
WinCommon::processAlived("vrmonitor.exe") ||
WinCommon::processAlived("vrcompositor.exe") ||
WinCommon::processAlived("vrdashboard.exe"))
{
launchSteamVr();
}
}
void ResourceModel::launchPihome(bool bStart){
if(!pihomeIsExist()){
return;
}
QString appName = "pihome.exe";
QString exeFile = "";//"\""+Setting::getInstallPath()+"\\Pihome\\"+appName+"\"";
if(bStart){
if(WinCommon::processAlived(appName.toStdString())){
WinCommon::killProcessByName(appName.toStdString());
}
qInfo()<<"launchPihome"<<exeFile;
QProcess().startDetached(exeFile);
}else{
if(WinCommon::processAlived(appName.toStdString())){
qInfo()<<"launchPihome"<<bStart;
WinCommon::killProcessByName(appName.toStdString());
}
}
}
bool ResourceModel::pihomeIsExist(){
//QString exeFile = Setting::getInstallPath()+"\\Pihome\\pihome.exe";
//return QFile(exeFile).exists();
return false;
}
bool ResourceModel::appendLocalResource(ResourceItem *resource){
qInfo()<<"appendLocalResource "<<mResourceList.length();
for(int i=0;i<mResourceList.length();i++){
if(((ResourceItem*)mResourceList.at(i))->id()==resource->id()){
//return false;
}
}
qInfo()<<"append new Local resource "<<resource->id()<<mResourceList.length();
mResourceList.append(resource);
resource->saveToFile();
return true;
}
void ResourceModel::checkSteamGameIsDeleted(){
int size = mResourceList.size();
for(int i=size-1;i>=0;i--){
ResourceItem *item = (ResourceItem *)mResourceList.at(i);
if(item->subType()=="steam"&&!m_steamGames.contains(item->id())){
qInfo() << "delete steam game "<<m_steamGames.size()<<" "<<item->id();
item->deleteItem();
mResourceList.removeOne(item);
delete item;
}
}
if(size!=mResourceList.size()){
emit resCountChanged(getResCount());
}
}
void ResourceModel::checkSteamGame(){
loadSteamVrGame();
checkSteamGameIsDeleted();
}
#define REG_PATH_OCULUS_HOME "HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\Oculus VR, LLC\\Oculus"
#define REG_PATH_OCULUS_APPS "HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\Oculus VR, LLC\\Oculus\\Config"
#define REG_ITEM_INSTALL_PATH "InstallPath"
bool ResourceModel::oculusHomeIsInstalled(){
if(m_oculusPath!=""&&m_oculusAppPath!=""){
if(QDir(m_oculusPath).exists()&&QDir(m_oculusAppPath).exists()
&&QFile(m_oculusPath + "\\Support\\oculus-client\\OculusClient.exe").exists()){
return true;
}
}
m_oculusPath = "";
m_oculusAppPath = "";
QSettings reg(REG_PATH_OCULUS_HOME,QSettings::NativeFormat);
QStringList keyList=reg.childKeys();
foreach(QString key,keyList){
if(key=="Base"){
m_oculusPath = reg.value(key).toString().trimmed();
qInfo() << "oculusHomeIsInstalled m_oculusPath " << m_oculusPath;
break;
}
}
if(m_oculusPath==""||!QDir(m_oculusPath).exists()){
// qInfo() << "oculusHomeIsInstalled " << m_oculusPath << " is not exist";
return false;
}
QString oculusClient = m_oculusPath + "\\Support\\oculus-client\\OculusClient.exe";
if(!QFile(oculusClient).exists()){
// qInfo() << "oculusHomeIsInstalled " << oculusClient << " is not exist";
return false;
}
QSettings reg2(REG_PATH_OCULUS_APPS,QSettings::NativeFormat);
QStringList keyList2=reg2.childKeys();
foreach(QString key,keyList2){
if(key=="InitialAppLibrary"){
m_oculusAppPath = reg2.value(key).toString().trimmed()+"\\Software";
break;
}
}
if(m_oculusAppPath==""){
m_oculusAppPath = m_oculusPath+"\\Software";
}
qInfo() << "oculusHome Is Installed " << m_oculusAppPath;
return true;
}
std::wstring ResourceModel::getHLKMRegStringVal(std::wstring path, std::wstring key)
{
HKEY hKEY;
if (ERROR_SUCCESS == ::RegOpenKeyEx(HKEY_LOCAL_MACHINE, path.c_str(), 0, KEY_READ, &hKEY))
{
TCHAR dwValue[MAX_PATH + 1] = { 0 };
DWORD dwSzType = REG_SZ;
DWORD dwSize = sizeof(dwValue);
if (::RegQueryValueEx(hKEY, key.c_str(), 0, &dwSzType, (LPBYTE)&dwValue, &dwSize) == ERROR_SUCCESS)
{
return dwValue;
}
::RegCloseKey(hKEY);
}
return{};
}
QStringList ResourceModel::getOCHomeDefaultLibraryPath()
{
LONG error = ERROR_SUCCESS;
WCHAR keyPath[MAX_PATH] = { L"Software\\Oculus VR, LLC\\Oculus\\Libraries\\" };
HKEY oculusKey;
error = RegOpenKeyExW(HKEY_CURRENT_USER, keyPath, 0, KEY_READ, &oculusKey);
if (error != ERROR_SUCCESS)
{
qCritical() << "Unable to open Libraries key.";
return{};
}
DWORD dwIndex = 0, NameSize, NameCnt, NameMaxLen, Type;
DWORD KeySize, KeyCnt, KeyMaxLen, DateSize, MaxDateLen;
if (RegQueryInfoKeyW(oculusKey, NULL, NULL, NULL, &KeyCnt, &KeyMaxLen, NULL, &NameCnt, &NameMaxLen, &MaxDateLen, NULL, NULL) != ERROR_SUCCESS)
{
qCritical() << "failed to get sub info.";
return{};
}
std::vector<std::wstring> guids;
for (dwIndex = 0; dwIndex < KeyCnt; dwIndex++)
{
KeySize = KeyMaxLen + 1;
wchar_t* szKeyName = new wchar_t[KeySize];
RegEnumKeyExW(oculusKey, dwIndex, szKeyName, &KeySize, NULL, NULL, NULL, NULL);
guids.push_back(szKeyName);
delete szKeyName;
}
WCHAR guid[40] = { L'\0' };
DWORD guidSize = sizeof(guid);
error = RegQueryValueExW(oculusKey, L"DefaultLibrary", NULL, NULL, (PBYTE)guid, &guidSize);
RegCloseKey(oculusKey);
if (error == ERROR_SUCCESS)
{
for (auto it = guids.begin(); it != guids.end(); it++)
{
if (*it == guid) {
guids.erase(it);
break;
}
}
guids.insert(guids.begin(), guid);
}
QStringList paths;
for (auto guid:guids)
{
std::wstring subKeyPath = keyPath + guid;
error = RegOpenKeyExW(HKEY_CURRENT_USER, subKeyPath.c_str(), 0, KEY_READ, &oculusKey);
if (error != ERROR_SUCCESS)
{
qCritical() << "Unable to open Library path key.";
return{};
}
DWORD pathSize;
error = RegQueryValueExW(oculusKey, L"Path", NULL, NULL, NULL, &pathSize);
PWCHAR volumePath = (PWCHAR)malloc(pathSize);
error = RegQueryValueExW(oculusKey, L"Path", NULL, NULL, (PBYTE)volumePath, &pathSize);
RegCloseKey(oculusKey);
if (error != ERROR_SUCCESS)
{
free(volumePath);
qCritical() << "Unable to read Library path.";
continue;
}
DWORD total;
WCHAR volume[50] = { L'\0' };
wcsncpy_s(volume, volumePath, 49);
WCHAR path[MAX_PATH + 1] = { L'\0' };
GetVolumePathNamesForVolumeNameW(volume, path, MAX_PATH, &total);
wcsncat_s(path, MAX_PATH, volumePath + 49, MAX_PATH);
free(volumePath);
paths.append(QString::fromStdWString(path));
}
return paths;
}
bool ResourceModel::getOculusGamePathList()
{
m_oculusAppPathList = getOCHomeDefaultLibraryPath();
if (!m_oculusAppPathList.isEmpty()) {
return true;
}
std::wstring appPath;
appPath = getHLKMRegStringVal(TEXT("SOFTWARE\\Wow6432Node\\Oculus VR, LLC\\Oculus\\Config"), TEXT("InitialAppLibrary"));
if (!appPath.empty()) {
m_oculusAppPathList.append(QString::fromStdWString(appPath));
return true;
}
appPath = getHLKMRegStringVal(TEXT("SOFTWARE\\Oculus VR, LLC\\Oculus\\Config"), TEXT("InitialAppLibrary"));
if (!appPath.empty()) {
m_oculusAppPathList.append(QString::fromStdWString(appPath));
return true;
}
appPath = getHLKMRegStringVal(TEXT("SOFTWARE\\Wow6432Node\\Oculus VR, LLC\\Oculus"), TEXT("Base"));
if (!appPath.empty()) {
appPath += L"\\Software";
m_oculusAppPathList.append(QString::fromStdWString(appPath));
return true;
}
appPath = getHLKMRegStringVal(TEXT("SOFTWARE\\Oculus VR, LLC\\Oculus"), TEXT("Base"));
if (!appPath.empty()) {
appPath += L"\\Software";
m_oculusAppPathList.append(QString::fromStdWString(appPath));
return true;
}
return m_oculusAppPathList.isEmpty();
}
void ResourceModel::loadOculusGame(){
m_oculusGames.clear();
QSettings reg(REG_PATH_OCULUS_HOME,QSettings::NativeFormat);
QStringList keyList=reg.childKeys();
foreach(QString key,keyList){
if(key=="Base"){
m_oculusPath = reg.value(key).toString().trimmed();
qInfo() << "oculusHomeIsInstalled m_oculusPath " << m_oculusPath;
break;
}
}
if(!getOculusGamePathList()){//(!oculusHomeIsInstalled()){
return;
}
int oldSize = mResourceList.size();
for(int index = 0; index < m_oculusAppPathList.size(); index++){
m_oculusAppPath = m_oculusAppPathList.at(index);
qInfo()<<"m_oculusAppPath "<<m_oculusAppPath;
QDir dir(m_oculusAppPath+"\\Manifests");
QFileInfoList list = dir.entryInfoList();
for (int i = 0; i < list.size(); ++i) {
QFileInfo fileInfo = list.at(i);
QString fileName = fileInfo.fileName();
QString posfix = fileName.right(fileName.length()-fileName.lastIndexOf(".")-1);
if(posfix=="json"&&fileName.indexOf("_assets")==-1){
QJsonObject root = JsonHandler::loadJsonObject(m_oculusAppPath+"\\Manifests\\"+fileName);
QString appId = JsonHandler::getJsonValue(root,"appId","");
QString path = JsonHandler::getJsonValue(root,"canonicalName","");
QString launchFile = JsonHandler::getJsonValue(root,"launchFile","");
QString launchParameters = JsonHandler::getJsonValue(root,"launchParameters","");
QString launchPathFile = m_oculusAppPath+"\\Software\\"+path+"\\"+launchFile;
if(appId==""||path==""||launchFile==""||!QFile(launchPathFile).exists()){
qInfo()<<"loadOculusGame "<<appId<<path<<launchFile<<launchPathFile;
continue;
}
if(launchParameters!=""&&launchParameters!="null"){
launchPathFile = launchPathFile+" "+launchParameters;
}
ResourceItem *resource = new ResourceItem();
resource->setId("ocs_"+appId);
resource->setThirdId(appId);
resource->setTitle(path.replace("-"," "));
resource->setType("game");
resource->setSubType("oculus");
resource->setFile(launchPathFile);
resource->setStatus(ResourceItem::STATUS_LOCAL);
resource->setCreateTime();
QString pathForImage = path.replace(" ","-");
QString imageUrl =m_oculusAppPath+"\\Software\\StoreAssets\\"+pathForImage+"_assets\\cover_landscape_image.jpg";
if(QFile(imageUrl).exists()){
resource->setImageUrl("file:///"+imageUrl.replace("\\","/"));//.replace(" ","%20"));
}else{
imageUrl = imageUrl.replace("SoftWare","Software\\Software");
if(QFile(imageUrl).exists()){
resource->setImageUrl("file:///"+imageUrl.replace("\\","/"));//.replace(" ","%20"));
}else if(m_oculusPath != "" && QDir(m_oculusPath).exists()){
imageUrl = m_oculusPath + "\\CoreData\\Software\\StoreAssets\\" + pathForImage+"_assets\\cover_landscape_image.jpg";
if(QFile(imageUrl).exists()){
resource->setImageUrl("file:///"+imageUrl.replace("\\","/"));
}else{
resource->setImageUrl("qrc:/resource/game_default.png");
}
}else{
resource->setImageUrl("qrc:/resource/game_default.png");
}
qInfo()<<"loadOculusGame "<<imageUrl;
}
m_oculusGames.append(resource->id());
if(!appendLocalResource(resource)){
delete resource;
}else{
sendMessage_addResource(resource->id());
}
}
}
}
if(oldSize!=mResourceList.size()){
emit resCountChanged(getResCount());
}
}
void ResourceModel::checkOculusGameIsDeleted(){
int size = mResourceList.size();
for(int i=size-1;i>=0;i--){
ResourceItem *item = (ResourceItem *)mResourceList.at(i);
if(item->subType()=="oculus"&&!m_oculusGames.contains(item->id())){
qInfo() << "delete oculus game "<<mResourceList.size()<<" "<<item->id();
item->deleteItem();
mResourceList.removeOne(item);
delete item;
}
}
if(size!=mResourceList.size()){
emit resCountChanged(getResCount());
}
}
void ResourceModel::checkOculusGame(){
loadOculusGame();
checkOculusGameIsDeleted();
}
void ResourceModel::loadPiplay1Data(){
QStringList dirList = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation);
QString programDataDir;
for(QString dir:dirList){
programDataDir = dir.remove("PiTool");
if(programDataDir.indexOf("ProgramData",Qt::CaseInsensitive)>0){
break;
}
}
QString dbDir = programDataDir+"pimax\\pidb";
dbDir.replace("/","\\");
qInfo()<<"loadPiplay1Data"<<programDataDir<<dbDir;
QString dbFile = dbDir+"\\pi.db";
if(!QDir(dbDir).exists()){
qInfo()<<dbDir<<"is not exist";
return;
}
if(!QFile(dbFile).exists()){
qInfo()<<dbFile<<"is not exist";
return;
}
if(QFile(dbDir+"\\imported.txt").exists()){
qInfo()<<"Piplay1 data has been imported before";
return;
}
QSqlDatabase database = QSqlDatabase::addDatabase("QSQLITE");
database.setDatabaseName(dbFile);
if(!database.open()){
qInfo()<<"loadPiplay1Data"<<database.lastError();
qInfo()<<"loadPiplay1Data open database failed";
return;
}
qInfo()<<"loadPiplay1Data open database success";
//load local database
QString sqlString = "select id,type,name,localpath,image,info,info_us from pilocal where state=1";
QSqlQuery sql_query;
sql_query.prepare(sqlString);
if(!sql_query.exec()){
qInfo()<<"loadPiplay1Data query sql error"<<sqlString<<sql_query.lastError();
database.close();
return;
}
while(sql_query.next()){
QString id = sql_query.value("id").toString();
QString type = sql_query.value("type").toString();
QString name = sql_query.value("name").toString();
QString localPath = sql_query.value("localpath").toString();
QString info = sql_query.value("info").toString();
QStringList infoList = info.split("\r\n");
if(infoList.size()>=3){
name = infoList.at(0);
name = name.mid(4,name.length()-5);
info = infoList.at(2);
info = info.mid(3);
}
qInfo()<<"piplay1 data record:"<<type<<name<<info<<localPath<<infoList;
if(!QFile(localPath).exists()){
continue;
}
QString resourceType=RESOURCE_TYPE_GAME;
if(type=="vrVideo"){
resourceType = RESOURCE_TYPE_VIDEO;
}
ResourceItem* resource = loadLocalResouce(resourceType,localPath,name,false,"piplay1."+id);
if(resource){
QByteArray imageData = sql_query.value("image").toByteArray();
QString posfix = ".jpg";
if(imageData.at(0)=='B'&&imageData.at(1)=='M'){
posfix = ".bmp";
}
QString imageFile = dbDir+"\\"+resource->id()+posfix;
QFile file(imageFile);
if(imageData.length()>0&&file.open(QIODevice::WriteOnly|QIODevice::Truncate)){
file.write(imageData);
file.close();
resource->setImageUrl("file:///"+imageFile.replace("\\\\","\\"));
resource->saveToFile();
}
}
}
//load import database
sqlString = "select id,type,name,localpath from piImport";
sql_query;
sql_query.prepare(sqlString);
if(!sql_query.exec()){
qInfo()<<"loadPiplay1Data query sql error"<<sqlString<<sql_query.lastError();
database.close();
return;
}
while(sql_query.next()){
QString id = sql_query.value("id").toString();
QString type = sql_query.value("type").toString();
QString name = sql_query.value("name").toString();
QString localPath = sql_query.value("localpath").toString();
qInfo()<<"piplay1 data record:"<<type<<name<<localPath;
if(!QFile(localPath).exists()){
continue;
}
QString resourceType=RESOURCE_TYPE_GAME;
if(type=="vrVideo"){
resourceType = RESOURCE_TYPE_VIDEO;
}
loadLocalResouce(resourceType,localPath,name,false,"piplay1.import."+id);
}
database.close();
QFile(dbDir+"\\imported.txt").open(QIODevice::ReadWrite);
}
QString ResourceModel::getError(){
switch (m_nError) {
case ERROR_FILE_NOT_EXIST:
return tr("file not exists");
break;
default:
break;
}
if(m_nError){
}
return mError;
}
int ResourceModel::getErrorCode(){
return m_nError;
}
ResourceItem *ResourceModel::getResourceItem(QString id){
for(int i=0;i<mResourceList.size();i++){
ResourceItem *item = (ResourceItem*)mResourceList.at(i);
if(item->id()==id){
return item;
}
}
return nullptr;
}
void ResourceModel::parseOnlineBoughtData(OnlineRequest* request,int code,QString type,QString message,QJsonObject dataObject){
delete request;
if(code!=8888){
return;
}
QJsonArray defValue;
QJsonArray jsonArray = JsonHandler::getJsonValue(dataObject,"items",defValue);
for(int i=0;i<jsonArray.size();i++){
QJsonObject json = jsonArray.at(i).toObject();
QString id = JsonHandler::getJsonValue(json,"id","");
if(id == ""){
continue;
}
ResourceItem *item = getResourceItem(id);
if(item==nullptr){
item = new ResourceItem();
item->setId(id);
item->setStatus(ResourceItem::STATUS_ONLINE);
item->setTitle(JsonHandler::getJsonValue(json,"title", ""));
item->setThirdId(JsonHandler::getJsonValue(json,"third_id",""));
item->setDownloadUrl(JsonHandler::getJsonValue(json,"url", ""));
item->setType(JsonHandler::getJsonValue(json,"type", ""));
item->setSubType(JsonHandler::getJsonValue(json,"subtype", ""));
item->setImageUrl(JsonHandler::getJsonValue(json,"image_url", ""));
mResourceList.append(item);
}
item->setBought(true);
item->setBoughtTime(JsonHandler::getJsonValue(json,"bought_time", double(0)));
item->setReleaseDate(JsonHandler::getJsonValue(json,"release", ""));
}
}
void ResourceModel::searchBoughtResource(QString access_token){
clearBoughtResource();
OnlineRequest *request = new OnlineRequest();
connect(request,SIGNAL(parseOnlineData(OnlineRequest *,int,QString,QString,QJsonObject)),
this,SLOT(parseOnlineBoughtData(OnlineRequest *,int,QString,QString,QJsonObject)));
request->getHttpRequest("/userProduct/search",QString("access_token=%1&pageSize=200&pageIndex=1").arg(access_token));
}
void ResourceModel::clearBoughtResource(){
for(int i=0;i<mResourceList.size();i++){
ResourceItem *item = (ResourceItem*)mResourceList.at(i);
if(item->status()==ResourceItem::STATUS_ONLINE){
item->setStatus(ResourceItem::STATUS_DELETED);
mResourceList.removeOne(item);
}else if(item->bought()){
item->setBought(false);
}
}
}
void ResourceModel::killAllProcess(){
if(!gLaunchedApp.isEmpty()){
WinCommon::killProcessByName(gLaunchedApp.toStdString());
}
for(int i=0;i<mProcessList.size();i++){
MyProcess *myProcess = mProcessList.at(i);
myProcess->process->kill();
qInfo()<<"kill process"<<myProcess->process->program();
}
}
void ResourceModel::addProcess(QString id,QProcess *process){
connect(process,SIGNAL(finished(int, QProcess::ExitStatus)),this,SLOT(processFinished(int, QProcess::ExitStatus)));
MyProcess *myProcess = new MyProcess(id,process);
mProcessList.append(myProcess);
}
| 35.693732 | 160 | 0.612364 | nlyan |
358368f4431def18aa43e295ea8d992298a3ce75 | 7,752 | cc | C++ | policy-decision-point/ast_2_policy_stack.cc | SSICLOPS/cppl | 265514bc461352b7b5bc58fd7482328601029e4a | [
"Apache-2.0"
] | 1 | 2018-06-02T11:50:06.000Z | 2018-06-02T11:50:06.000Z | policy-decision-point/ast_2_policy_stack.cc | SSICLOPS/cppl | 265514bc461352b7b5bc58fd7482328601029e4a | [
"Apache-2.0"
] | 1 | 2018-01-17T04:16:29.000Z | 2018-01-30T09:01:44.000Z | policy-decision-point/ast_2_policy_stack.cc | SSICLOPS/cppl | 265514bc461352b7b5bc58fd7482328601029e4a | [
"Apache-2.0"
] | 1 | 2018-11-18T20:31:54.000Z | 2018-11-18T20:31:54.000Z | // Copyright 2015-2018 RWTH Aachen University
//
// 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 "ast_2_policy_stack.hh"
#include "equal.hh"
#include "not_equal.hh"
#include "less.hh"
#include "less_equal.hh"
#include "greater.hh"
#include "greater_equal.hh"
#include "is_true.hh"
#include "is_false.hh"
#include "basic_type.hh"
#include "function.hh"
#include "ID.hh"
void Ast2PolicyStack::visit(AstOperation &op){
if (op.type == AstOperationType::NOT)
throw "The not operation should have been eliminated, since we here only support & and |";
if (op.type == AstOperationType::OR || op.type == AstOperationType::AND){
for (uint8_t i = 0; i < op.getNumberOfChildren(); ++i)
op.getChild(i)->accept(*this);
StackOperation stackOp;
if (op.type == AstOperationType::OR){
stackOp.type = PolicyStackOperationType::OR;
}
else{
stackOp.type = PolicyStackOperationType::AND;
}
policyStack.push(std::move(stackOp));
}
else if (op.type == AstOperationType::ELIMINATED_NOT){
assert(op.getNumberOfChildren() == 1);
op.getChild(0)->accept(*this);
}
else{
op.getChild(0)->accept(*this);
if (op.type != AstOperationType::IS_TRUE && op.type != AstOperationType::IS_FALSE){
assert(op.getNumberOfChildren() == 2);
op.getChild(1)->accept(*this);
}
Relation * relation = NULL;
if (op.type == AstOperationType::EQUAL){
#ifdef __DEBUG__
std::cout<<_left<<" = "<<_right<<std::endl;
#endif
relation = new Equal(_left, _right);
}
else if (op.type == AstOperationType::NEQ){
#ifdef __DEBUG__
std::cout<<_left<<" != "<<_right<<std::endl;
#endif
relation = new NotEqual(_left, _right);
}
else if (op.type == AstOperationType::LESS){
#ifdef __DEBUG__
std::cout<<_left<<" < "<<_right<<std::endl;
#endif
relation = new Less(_left, _right);
}
else if (op.type == AstOperationType::LEQ){
#ifdef __DEBUG__
std::cout<<_left<<" <= "<<_right<<std::endl;
#endif
relation = new LessEqual(_left, _right);
}
else if (op.type == AstOperationType::GREATER){
#ifdef __DEBUG__
std::cout<<_left<<" > "<<_right<<std::endl;
#endif
relation = new Greater(_left, _right);
}
else if (op.type == AstOperationType::GEQ){
#ifdef __DEBUG__
std::cout<<_left<<" >= "<<_right<<std::endl;
#endif
relation = new GreaterEqual(_left, _right);
}
else if (op.type == AstOperationType::IS_TRUE){
#ifdef __DEBUG__
std::cout<<_left<<" = true"<<std::endl;
#endif
relation = new IsTrue(_left);
}
else if (op.type == AstOperationType::IS_FALSE){
#ifdef __DEBUG__
std::cout<<_left<<" = false"<<std::endl;
#endif
relation = new IsFalse(_left);
}
else
throw "Convert for this RelationSetType is not implemented";
StackOperation stackOp;
id_type relationId = relationSet.getRelationID(*relation);
if (relationId == std::numeric_limits<id_type>::max()){//a normal, new relation
relationSet.addRelation(relation);
stackOp.type = PolicyStackOperationType::NEXT_RELATION;
}
else{
delete relation;
stackOp.type = PolicyStackOperationType::SPECIFIC_RELATION;
stackOp.relationId = relationId;
}
policyStack.push(std::move(stackOp));
_left = _right = std::numeric_limits<id_type>::max();
}
}
Variable * AstConstant2Variable(const AstConstant & astConst){
Variable * var = NULL;
if (astConst.type == AstValueType::UINT8){
#ifdef __DEBUG__
std::cout<<"AstConstant: UINT8"<<std::endl;
#endif
var = new Uint8(boost::get<int64_t>(astConst.value));
}
else if (astConst.type == AstValueType::UINT16){
#ifdef __DEBUG__
std::cout<<"AstConstant: UINT16"<<std::endl;
#endif
var = new Uint16(boost::get<int64_t>(astConst.value));
}
else if (astConst.type == AstValueType::UINT32){
#ifdef __DEBUG__
std::cout<<"AstConstant: UINT32"<<std::endl;
#endif
var = new Uint32(boost::get<int64_t>(astConst.value));
}
else if (astConst.type == AstValueType::INT8){
#ifdef __DEBUG__
std::cout<<"AstConstant: INT8"<<std::endl;
#endif
var = new Int8(boost::get<int64_t>(astConst.value));
}
else if (astConst.type == AstValueType::INT16){
#ifdef __DEBUG__
std::cout<<"AstConstant: INT16"<<std::endl;
#endif
var = new Int16(boost::get<int64_t>(astConst.value));
}
else if (astConst.type == AstValueType::INT32){
#ifdef __DEBUG__
std::cout<<"AstConstant: INT32"<<std::endl;
#endif
var = new Int32(boost::get<int64_t>(astConst.value));
}
else if (astConst.type == AstValueType::INT64){
#ifdef __DEBUG__
std::cout<<"AstConstant: INT64"<<std::endl;
#endif
var = new Int64(boost::get<int64_t>(astConst.value));
}
else if (astConst.type == AstValueType::Float){
#ifdef __DEBUG__
std::cout<<"AstConstant: Float"<<std::endl;
#endif
var = new Double(boost::get<double>(astConst.value));
}
else if (astConst.type == AstValueType::Boolean){
#ifdef __DEBUG__
std::cout<<"AstConstant: Boolean"<<std::endl;
#endif
var = new Boolean(boost::get<bool>(astConst.value));
}
else if (astConst.type == AstValueType::String){
#ifdef __DEBUG__
std::cout<<"AstConstant: String"<<std::endl;
#endif
var = new String(boost::get<string>(astConst.value));
}
else if (astConst.type == AstValueType::EnumValue){
#ifdef __DEBUG__
std::cout<<"AstConstant: EnumValue"<<std::endl;
#endif
var = new Enum(boost::get<int64_t>(astConst.value), astConst.enumValuePosition);
}
return var;
}
void Ast2PolicyStack::visit(AstConstant & astConstant){
id_type * pOpID = &_left;
if (_left != std::numeric_limits<id_type>::max())
pOpID = &_right;
if (_right != std::numeric_limits<id_type>::max())
throw "astConstant: only relations with less than two variables are supported";
Variable * var = AstConstant2Variable(astConstant);
if (var->get_type() != Variable::Types::BOOLEAN){
*pOpID = relationSet.getVariableID(*var);
}
if (*pOpID == std::numeric_limits<id_type>::max()){
*pOpID = relationSet.addVariable(var);
}
else
delete var;
}
void Ast2PolicyStack::visit(AstId & astId){
#ifdef __DEBUG__
std::cout<<astId.name<<std::endl;
#endif
id_type * pOpID = &_left;
if (_left != std::numeric_limits<id_type>::max())
pOpID = &_right;
if (_right != std::numeric_limits<id_type>::max())
throw "AstId: only relations with less than two variables are supported";
ID * id = new ID(NULL, astId.position);
//*pOpID = relationSet.getVariableID(*id);
//if (*pOpID == std::numeric_limits<id_type>::max()){
*pOpID = relationSet.addVariable(id);
//}
//else
// delete id;
}
void Ast2PolicyStack::visit(AstFunction & astFunction){
id_type * pOpID = &_left;
if (_left != std::numeric_limits<id_type>::max())
pOpID = &_right;
if (_right != std::numeric_limits<id_type>::max())
throw "AstFunction: only relations with less than two variables are supported";
Function * function = new Function(astFunction.position, NULL, NULL);
for (auto it = astFunction.parameters.begin(); it != astFunction.parameters.end();++it){
function->addParam(AstConstant2Variable(**it));
}
*pOpID = relationSet.getVariableID(*function);
if (*pOpID == std::numeric_limits<id_type>::max()){
*pOpID = relationSet.addVariable(function);
}
else
delete function;
}
void Ast2PolicyStack::visit(Ast & ast){
policyStack.push({PolicyStackOperationType::SPECIFIC_RELATION, std::numeric_limits<id_type>::max()});
ast.root->accept(*this);
}
| 29.587786 | 102 | 0.696078 | SSICLOPS |
35893ebafdb3649fc28fc4ec5cc11e89793103f3 | 4,028 | cxx | C++ | src/TStoreGEMEvent.cxx | a-capra/feGEM | 0ae28e1d2aae609f6f8f5000bad30d8dcc41626c | [
"MIT"
] | null | null | null | src/TStoreGEMEvent.cxx | a-capra/feGEM | 0ae28e1d2aae609f6f8f5000bad30d8dcc41626c | [
"MIT"
] | null | null | null | src/TStoreGEMEvent.cxx | a-capra/feGEM | 0ae28e1d2aae609f6f8f5000bad30d8dcc41626c | [
"MIT"
] | 1 | 2021-02-26T20:59:50.000Z | 2021-02-26T20:59:50.000Z | #include "TStoreGEMEvent.h"
TStoreGEMEventHeader::TStoreGEMEventHeader()
{
//ctor
}
TStoreGEMEventHeader::TStoreGEMEventHeader(GEMBANK<void*> *bank)
{
BANK = bank->GetBANK();
DATATYPE = bank->GetType();
VARCATEGORY = bank->GetCategoryName();
VARNAME = bank->GetVariableName();
EquipmentType = bank->GetEquipmentType();
HistorySettings = bank->HistorySettings;
HistoryPeriod = bank->HistoryPeriod;
TimestampEndianness = bank->TimestampEndianness;
DataEndianness = bank->DataEndianness;
}
TStoreGEMEventHeader::~TStoreGEMEventHeader()
{
//dtor
}
ClassImp(TStoreGEMEventHeader)
TLVTimestamp::TLVTimestamp(bool Now)
{
if (!Now)
return;
using namespace std::chrono;
system_clock::time_point tp = system_clock::now();
system_clock::duration dtn = tp.time_since_epoch();
Seconds=dtn.count() * system_clock::period::num / system_clock::period::den;//+2082844800;
double fraction=(double)(dtn.count() - Seconds*system_clock::period::den / system_clock::period::num)/system_clock::period::den;
SubSecondFraction=fraction*(double)((uint64_t)-1);
//Convert from UNIX time (seconds since 1970) to LabVIEW time (seconds since 01/01/1904 )
Seconds+=2082844800;
//LabVIEW timestamp is big endian... conform...
Seconds=change_endian(Seconds);
SubSecondFraction=change_endian(SubSecondFraction);
//print();
}
TLVTimestamp::~TLVTimestamp()
{
}
TLVTimestamp::TLVTimestamp(const TLVTimestamp& ts)
{
Seconds = ts.Seconds;
SubSecondFraction = ts.SubSecondFraction;
}
TLVTimestamp& TLVTimestamp::operator=(const TLVTimestamp& ts)
{
Seconds = ts.Seconds;
SubSecondFraction = ts.SubSecondFraction;
return *this;
}
TLVTimestamp& TLVTimestamp::operator=(const LVTimestamp& ts)
{
Seconds = ts.Seconds;
SubSecondFraction = ts.SubSecondFraction;
return *this;
}
ClassImp(TLVTimestamp);
template <class T>
TStoreGEMData<T>::TStoreGEMData()
{
}
template <class T>
void TStoreGEMData<T>::Set(const GEMDATA<T>* gemdata,const int BlockSize,
const uint16_t _TimestampEndianness, const uint16_t _DataEndianness,
const uint32_t _MIDASTime, const double RunTimeOffset, const int _runNumber)
{
RawLabVIEWtimestamp = gemdata->timestamp;
//Please check this calculation
RawLabVIEWAsUNIXTime = gemdata->GetUnixTimestamp(_TimestampEndianness);
//Really, check this fraction calculation
double fraction = (double) gemdata->GetLabVIEWFineTime(_TimestampEndianness)/(double)((uint64_t)-1);
assert(fraction<1);
RawLabVIEWAsUNIXTime += fraction;
TimestampEndianness = _TimestampEndianness;
DataEndianness = _DataEndianness;
MIDASTime = _MIDASTime;
//std::cout<<"MIDAS:"<< MIDASTime;
runNumber = _runNumber;
RunTime = RawLabVIEWAsUNIXTime - RunTimeOffset;
//std::cout<<"RunTime"<<RunTime<<std::endl;
data.clear();
int entries=gemdata->GetEntries(BlockSize);
data.reserve(entries);
for (size_t i=0; i<entries; i++)
{
//std::cout<<"DATA: "<<gemdata->DATA[i];
data.push_back(gemdata->DATA[i]);
//std::cout<<"\t"<<data.back()<<std::endl;
}
}
template <class T>
TStoreGEMData<T>::~TStoreGEMData()
{
data.clear();
}
ClassImp(TStoreGEMData<double>)
ClassImp(TStoreGEMData<float>)
ClassImp(TStoreGEMData<bool>)
ClassImp(TStoreGEMData<int32_t>)
ClassImp(TStoreGEMData<uint32_t>)
ClassImp(TStoreGEMData<uint16_t>)
ClassImp(TStoreGEMData<char>)
TStoreGEMFile::TStoreGEMFile(): TStoreGEMData<char>()
{
}
TStoreGEMFile::~TStoreGEMFile()
{
}
ClassImp(TStoreGEMFile);
//Define all valid data types for TStoreGEMData
template class TStoreGEMData<double>;
template class TStoreGEMData<float>;
template class TStoreGEMData<bool>;
template class TStoreGEMData<int32_t>;
template class TStoreGEMData<uint32_t>;
template class TStoreGEMData<uint16_t>;
template class TStoreGEMData<char>;
| 26.326797 | 132 | 0.701837 | a-capra |
3592b5dc4608a697fa7c2a49cc8e082c4d5d8752 | 244 | cpp | C++ | project5-multi_exe_dep_on_common_lib/src/the_main1.cpp | adamcavendish/ReasonableCMakeForCXX | c49d94106f25fa6e25bdfd2389d68b5fb7fb80b3 | [
"Unlicense"
] | 3 | 2017-04-05T16:03:31.000Z | 2017-05-18T13:58:52.000Z | project5-multi_exe_dep_on_common_lib/src/the_main1.cpp | adamcavendish/ReasonableCMakeForCXX | c49d94106f25fa6e25bdfd2389d68b5fb7fb80b3 | [
"Unlicense"
] | null | null | null | project5-multi_exe_dep_on_common_lib/src/the_main1.cpp | adamcavendish/ReasonableCMakeForCXX | c49d94106f25fa6e25bdfd2389d68b5fb7fb80b3 | [
"Unlicense"
] | null | null | null | #include <main1/the_main1.hpp>
#include <common1/c1.hpp>
#include <common2/c2.hpp>
#include <module3/m3.hpp>
#include <string>
std::string the_main1() {
return std::string() + "c1=" + c1() + ",c2=" + c2() + ",m3=" + m3() + ",the_main1!";
}
| 22.181818 | 86 | 0.606557 | adamcavendish |
359916fc528122d2d1b1e2472f66c5c59d087043 | 21,405 | cpp | C++ | src/ankicar.cpp | ThomasHeinrichSchmidt/anki-overdrive-goes-iot | d28f728694ff7aabe65ccb77da5c3d41c70b3dc3 | [
"MIT"
] | 1 | 2021-04-13T18:20:56.000Z | 2021-04-13T18:20:56.000Z | src/ankicar.cpp | ThomasHeinrichSchmidt/anki-overdrive-goes-iot | d28f728694ff7aabe65ccb77da5c3d41c70b3dc3 | [
"MIT"
] | null | null | null | src/ankicar.cpp | ThomasHeinrichSchmidt/anki-overdrive-goes-iot | d28f728694ff7aabe65ccb77da5c3d41c70b3dc3 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 9.11.2016 com2m GmbH.
* All rights reserved.
*/
#include "headers/ankicar.h"
#include <QDebug>
#include <QLowEnergyController>
#include <QLowEnergyCharacteristic>
#include <iostream>
#include "headers/ankimessage.h"
#include "headers/trackpiece.h"
#include <QLowEnergyConnectionParameters>
#include "headers/tragediyimplementation.h"
#include <QThread>
const QBluetoothUuid AnkiCar::SERVICE_UUID = QBluetoothUuid(QString("BE15BEEF-6186-407E-8381-0BD89C4D8DF4"));
const QBluetoothUuid AnkiCar::CHR_READ_UUID = QBluetoothUuid(QString("BE15BEE0-6186-407E-8381-0BD89C4D8DF4"));
const QBluetoothUuid AnkiCar::CHR_WRITE_UUID = QBluetoothUuid(QString("BE15BEE1-6186-407E-8381-0BD89C4D8DF4"));
AnkiCar::AnkiCar(QObject *parent) : QObject(parent) {
name = "<unknown>";
}
AnkiCar::~AnkiCar() {
if (lowEnergyController != 0) {
lowEnergyController->disconnectFromDevice();
}
}
void AnkiCar::init(const QBluetoothDeviceInfo& device) {
this->address = device.address();
// https://en.wikipedia.org/wiki/ANSI_escape_code
QString Blue = "\e[34m";
QString BrightBlue = "\e[94m";
QString Red = "\e[31m";
QString BrightRed = "\e[91m";
QString White = "\e[37m";
QString Black = "\e[40m";
if (this->address.toString() == "D8:91:3E:EE:01:6F") name = BrightBlue + Black + "Ground Shock" + White + Black;
else if (this->address.toString() == "E6:45:5A:32:6E:4A") name = BrightRed + Black + "Skull" + White + Black;
else name = this->address.toString();
// QString QBluetoothDeviceInfo::name() returns the name assigned to the device - but is nothing really readable, at least not speific for a car
// qDebug().noquote().nospace() << "[" + this->getAddress().toString() + "]" << " name is: " << device.name();
/*
* QVector<quint16> QBluetoothDeviceInfo::manufacturerIds() const
* Returns all manufacturer ids attached to this device information.
* This function was introduced in Qt 5.12.
*
* pi@raspberrypi:~ $ qmake --version
* QMake version 3.0
* Using Qt version 5.7.1 in /usr/lib/arm-linux-gnueabihf
*
* see http://www.tal.org/tutorials/building-qt-512-raspberry-pi
*
const QVector<quint16> manufacturerIds = device.manufacturerIds(); // Returns all manufacturer ids attached to this device information.
for (int i = 0; i < manufacturerIds.size(); ++i) {
qDebug().noquote().nospace() << "[" + this->getAddress().toString() + "]" << " manufacturerData is: " << device.manufacturerData(manufacturerIds.at(i)).toString();
} // Returns the data associated with the given manufacturerId.
*/
lowEnergyController = new QLowEnergyController(device, this);
lowEnergyController->setRemoteAddressType(QLowEnergyController::RandomAddress);
connect(lowEnergyController, SIGNAL(serviceDiscovered(QBluetoothUuid)), this, SLOT(serviceDiscovered(QBluetoothUuid)));
connect(lowEnergyController, SIGNAL(discoveryFinished()), this, SLOT(serviceDiscoveryFinished()));
connect(lowEnergyController, SIGNAL(error(QLowEnergyController::Error)), this, SLOT(controllerError(QLowEnergyController::Error)));
connect(lowEnergyController, SIGNAL(connected()), this, SLOT(deviceConnected()));
connect(lowEnergyController, SIGNAL(disconnected()), this, SLOT(deviceDisconnected()));
lowEnergyController->connectToDevice();
}
void AnkiCar::serviceDiscovered(const QBluetoothUuid &uuid) {
uuidList.append(uuid);
}
void AnkiCar::serviceDiscoveryFinished() {
emit sendMessage("[" + getAddress().toString() + "]>> SERVICE DISCOVERY FINISHED.");
qDebug().noquote().nospace() << "[" + this->getAddress().toString() + "]" << ">> SERVICE DISCOVERY FINISHED.";
foreach (QBluetoothUuid uuid, uuidList) {
if (uuid == SERVICE_UUID) {
emit sendMessage("[" + getAddress().toString() + "]>> FOUND ANKI SERVICE.");
qDebug().noquote().nospace() << "[" + this->getAddress().toString() + "]" << ">> FOUND ANKI SERVICE.";
lowEnergyService = lowEnergyController->createServiceObject(uuid);
connect(lowEnergyService, SIGNAL(stateChanged(QLowEnergyService::ServiceState)), this, SLOT(serviceStateChanged(QLowEnergyService::ServiceState)));
connect(lowEnergyService, SIGNAL(characteristicWritten(QLowEnergyCharacteristic,QByteArray)), this, SLOT(characteristicWritten(QLowEnergyCharacteristic,QByteArray)));
connect(lowEnergyService, SIGNAL(characteristicRead(QLowEnergyCharacteristic,QByteArray)), this, SLOT(characteristicRead(QLowEnergyCharacteristic,QByteArray)));
connect(lowEnergyService, SIGNAL(descriptorWritten(QLowEnergyDescriptor,QByteArray)), this, SLOT(descriptorWritten(QLowEnergyDescriptor,QByteArray)));
lowEnergyService->discoverDetails();
}
}
}
void AnkiCar::descriptorWritten(const QLowEnergyDescriptor &descriptor, const QByteArray &newValue) {
(void)descriptor;
(void)newValue;
emit sendMessage("[" + getAddress().toString() + "]>> DESCRIPTOR SUCCESSFULLY WRITTEN.");
qDebug().noquote().nospace() << "[" + this->getAddress().toString() + "]" << ">> DESCRIPTOR SUCCESSFULLY WRITTEN.";
}
// This function is called as soon as there are incoming messages from the vehicle
void AnkiCar::characteristicChanged(const QLowEnergyCharacteristic &characteristic, const QByteArray &value) {
(void)characteristic;
AnkiMessage response(value);
processIncomingMessage(response);
}
// Get characteristics and enable notifications
void AnkiCar::serviceStateChanged(const QLowEnergyService::ServiceState &state) {
if (state == QLowEnergyService::ServiceDiscovered) {
foreach (QLowEnergyCharacteristic characteristic, lowEnergyService->characteristics()) {
if (characteristic.uuid() == CHR_READ_UUID) {
readCharacteristic = characteristic;
if (characteristic.isValid()) {
QLowEnergyDescriptor notification = characteristic.descriptor(QBluetoothUuid::ClientCharacteristicConfiguration);
if (notification.isValid()) {
connect(lowEnergyService, &QLowEnergyService::characteristicChanged, this, &AnkiCar::characteristicChanged);
lowEnergyService->writeDescriptor(notification, QByteArray::fromHex("0100"));
}
}
}
else if (characteristic.uuid() == CHR_WRITE_UUID) {
writeCharacteristic = characteristic;
}
}
emit sendMessage("[" + getAddress().toString() + "]>> SERVICE CHARACTERISTICS DISCOVERED.");
qDebug().noquote().nospace() << "[" + this->getAddress().toString() + "]" << ">> SERVICE CHARACTERISTICS DISCOVERED.";
sdkModeOn();
}
}
void AnkiCar::characteristicRead(const QLowEnergyCharacteristic &characteristic, const QByteArray &value) {
(void)characteristic;
(void)value;
emit sendMessage("[" + getAddress().toString() + "]>> READ ANKI CHARACTERISTIC.");
qDebug() << "CHARACTERISTIC READ.";
}
void AnkiCar::sdkModeOn() {
AnkiMessage sdkMessage(AnkiMessage::SDK_MODE);
sendMessage(sdkMessage);
emit sendMessage("[" + getAddress().toString() + "]>> SDK MODE ON.");
qDebug().noquote().nospace() << "[" + this->getAddress().toString() + "]" << ">> SDK ON.";
}
void AnkiCar::setVelocity(uint16_t velocity, uint16_t acceleration) {
AnkiMessage sdkMessage(AnkiMessage::SET_VELOCITY, velocity, acceleration);
this->velocity = velocity;
sendMessage(sdkMessage);
}
void AnkiCar::setLights(uint8_t lightValue) {
AnkiMessage sdkMessage(AnkiMessage::SET_LIGHTS, lightValue);
this->lightValue = lightValue;
sendMessage(sdkMessage);
}
void AnkiCar::setEngineLight(uint8_t red, uint8_t green, uint8_t blue) {
qDebug().noquote().nospace() << "AnkiCar::setEngineLight(" << red << ", " << green << ", " << blue << ")";
AnkiMessage sdkMessage(AnkiMessage::LIGHTS_PATTERN, red, green, blue);
sendMessage(sdkMessage);
}
uint16_t AnkiCar::getVelocity() {
return this->velocity;
}
int AnkiCar::getLane() {
if (this->currentLane < 1) {
this->currentLane = (this->getOffset() + 72.5)/9.06;
if (this->currentLane < 2) this->currentLane = 2;
if (this->currentLane > 17) this->currentLane = 17;
qDebug().noquote().nospace() << "[" << getAddress().toString() << "]" << ">> getLane() = " << this->currentLane << " (offset = " << this->getOffset() << ")";
}
if (this->currentLane < 2) {
return 2;
}
else if (this->currentLane > 17) {
return 17;
}
return this->currentLane;
}
uint16_t AnkiCar::getBatteryLevel() {
return this->batteryLevel;
}
float AnkiCar::getOffset() {
return this->offset;
}
void AnkiCar::doUturn() {
AnkiMessage sdkMessage(AnkiMessage::UTURN);
sendMessage(sdkMessage);
}
void AnkiCar::setVehicleOffset(float offset, uint16_t velocity, uint16_t acceleration) {
AnkiMessage sdkMessage(AnkiMessage::CHANGE_LANE, offset, velocity, acceleration);
sendMessage(sdkMessage);
}
void AnkiCar::setOffsetFromRoadCenter(float offset) {
AnkiMessage sdkMessage(AnkiMessage::SET_OFFSET_FROM_ROADCENTER, offset);
sendMessage(sdkMessage);
}
void AnkiCar::requestBatteryLevel() {
AnkiMessage sdkMessage(AnkiMessage::BATTERY_REQUEST);
sendMessage(sdkMessage);
}
void AnkiCar::changeLane(float offset, uint16_t velocity, uint16_t acceleration) {
setVehicleOffset(offset, velocity, acceleration);
}
// This function is called after a message has been sent to the vehicle
void AnkiCar::characteristicWritten(const QLowEnergyCharacteristic &characteristic, const QByteArray &newValue) {
(void)characteristic;
AnkiMessage message(newValue);
if (!initialized) {
initialized = true;
available = true;
emit ready();
}
}
void AnkiCar::controllerError(const QLowEnergyController::Error &error) {
switch (error) {
case QLowEnergyController::NoError:
qDebug("AnkiCar::controllerError() >>> No Error");
break;
case QLowEnergyController::UnknownError:
qDebug("AnkiCar::controllerError() >>> Unknown Error");
initialized = false;
break;
case QLowEnergyController::UnknownRemoteDeviceError:
qDebug("AnkiCar::controllerError() >>> The remote Bluetooth LE device with the address pass to the constructor of this class cannot be found.");
break;
case QLowEnergyController::NetworkError:
qDebug("AnkiCar::controllerError() >>> Read/Write failed");
break;
case QLowEnergyController::InvalidBluetoothAdapterError:
qDebug("AnkiCar::controllerError() >>> Bluetooth adaptor not found");
break;
case QLowEnergyController::ConnectionError:
qDebug("AnkiCar::controllerError() >>> Connection attempt failed");
break;
case QLowEnergyController::AdvertisingError:
qDebug("AnkiCar::controllerError() >>> Advertising failed");
break;
}
}
void AnkiCar::deviceConnected() {
emit sendMessage("[" + getAddress().toString() + "]>> CONNECTED.");
qDebug().noquote().nospace() << "[" << getAddress().toString() << "]" << ">> CONNECTED.";
QThread::msleep(500); // After you connect put a sleep delay of a few hundred ms and always request a single services and characteristic at a time.
lowEnergyController->discoverServices();
QThread::msleep(500);
}
void AnkiCar::deviceDisconnected() {
emit sendMessage("[" + getAddress().toString() + "]>> DISCONNECTED.");
qDebug().noquote().nospace() << "[" + getAddress().toString() + "]" << ">> DISCONNECTED.";
if (lowEnergyService !=0) lowEnergyService->disconnect();
uuidList.clear();
velocity = 0;
batteryLevel = 0;
offset = 0.0f;
scanMode = false;
initialized = false;
currentSegment = TrackPiece::SEGMENT_NOT_DEFINED;
lastSegmentBeforeFinishLine = false;
stopAtStart = false;
destinationLane = 0;
currentLane = 0;
charging = false;
onTrack = true;
available = false;
slowedDown = false;
currentPieceId = 0;
changingLane = false;
reverseDriving = false;
emit disconnected();
}
void AnkiCar::scanTrack() {
track.clear();
scanMode = true;
setVelocity(450); // 300 is slow
}
void AnkiCar::cancelLaneChange() {
AnkiMessage sdkMessage(AnkiMessage::CANCEL_LANE_CHANGE);
changingLane = false;
sendMessage(sdkMessage);
}
QBluetoothAddress AnkiCar::getAddress() {
return this->address;
}
QString AnkiCar::getName() {
return this->name;
}
void AnkiCar::processIncomingMessage(AnkiMessage message) {
if (message.getType() == AnkiMessage::POSITION_UPDATE){
// qDebug() << message.getPieceId();
}
// qDebug() << message.getReadableMessage();
if (scanMode && (message.getType() == AnkiMessage::POSITION_UPDATE || message.getType() == AnkiMessage::TRANSITION_UPDATE)) {
if (message.getType() == AnkiMessage::POSITION_UPDATE) {
track.printTrack();
if (track.isComplete(message.getPieceId())) {
stop();
scanMode = false;
emit trackScanCompleted(track);
}
else {
if (track.getTrackPieceString( message.getPieceId() ) != "C"){
qDebug() << ("Trackpiece:" + track.getTrackPieceString( message.getPieceId())) << message.getPieceId();
}
else if (message.reverseParsing()) {
qDebug() << "Trackpiece: R " << message.getPieceId() ;
}
else {
qDebug() << "Trackpiece: L " << message.getPieceId() ;
}
if (message.reverseParsing()) {
track.append(message.getPieceId(), TrackPiece::DIRECTION_RIGHT);
}
else {
track.append(message.getPieceId(), TrackPiece::DIRECTION_LEFT);
}
// if (message.reverseParsing()) {
// track.setLastDirection(TrackPiece::DIRECTION_RIGHT);
// }
// else {
// track.setLastDirection(TrackPiece::DIRECTION_LEFT);
// }
}
}
else if (message.getType() == AnkiMessage::TRANSITION_UPDATE) {
//Alternative solution based on wheel displacement
// if (message.getLeftWheelDisplacement() +4 < message.getRightWheelDisplacement()) {
// qDebug() << "T_Left";
// }
// else if (message.getLeftWheelDisplacement() > message.getRightWheelDisplacement() + 4){
// qDebug() << "T_Right";
// }
// else {
// qDebug() << "T_Straight";
// }
//
// if (message.getLeftWheelDisplacement() +4 < message.getRightWheelDisplacement()) {
// track.setLastDirection(TrackPiece::DIRECTION_LEFT);
// }
// else if (message.getLeftWheelDisplacement() > message.getRightWheelDisplacement() + 4){
// track.setLastDirection(TrackPiece::DIRECTION_RIGHT);
// }
}
// track.printTrack();
}
if (message.getType() == AnkiMessage::BATTERY_RESPONSE) {
batteryLevel = message.getBattery();
emit batteryLevelUpdate(batteryLevel);
}
if (message.getType() == AnkiMessage::TRANSITION_UPDATE) {
bool emitTransition = true;
// qDebug().noquote().nospace() << "[" << getAddress().toString() << "]" << ">> TRANSITION_UPDATE (left wheel = " << message.getLeftWheelDisplacement() << ", right wheel = " << message.getRightWheelDisplacement() << " ,,, inside [32,39]?) - message = " << message.toString();
if ((message.getLeftWheelDisplacement() < 0x27) && (message.getLeftWheelDisplacement() > 0x20) && (message.getRightWheelDisplacement() < 0x27) && (message.getRightWheelDisplacement() > 0x20)) {
emit finishLine();
if (slowedDown) {
currentPieceId = 34;
stop();
destinationLane = 0;
stopAtStart = false;
slowedDown = false;
emit stoppedAtStart();
emitTransition = false;
}
}
if (emitTransition) {
emit transition();
}
if (track.getTrackList().length() > 0) {
if (!scanMode && this->currentPieceId == track.getTrackList().last().getPieceId()) {
lastSegmentBeforeFinishLine = true;
}
}
}
if (message.getType() == AnkiMessage::POSITION_UPDATE) {
if (stopAtStart && TragediyImplementation::getAnkiLocationTableEntry(message).getDistance() < 200 && !slowedDown) {
setVelocity(100, 800);
slowedDown = true;
}
this->reverseDriving = message.reverseDriving() ? true : false;
this->offset = message.getOffset();
this->currentSegment = (TrackPiece::Type)(message.getPieceId());
this->currentPieceId = message.getPieceId();
emit positionUpdate(message);
if (changingLane) {
currentLane = TragediyImplementation::getAnkiLocationTableEntry(message).getLane();
// if (currentLane < 1) currentLane = this->getLane(); // added this line - maybe wrong
int reverseDriving = message.reverseDriving() ? (-1) : (1);
if (currentLane < destinationLane) {
setOffsetFromRoadCenter(0.0f);
changeLane((reverseDriving) * (destinationLane - currentLane) * 9.06, velocity);
}
else if (currentLane > destinationLane) {
setOffsetFromRoadCenter(0.0f);
changeLane((reverseDriving) * (-1)*(currentLane - destinationLane) * 9.06, velocity);
}
else {
changingLane = false;
}
qDebug().noquote().nospace() << "[" << getAddress().toString() << "]" << ">> changingLane: current = " << currentLane << ", dest =" << destinationLane;
}
}
if (message.getType() == AnkiMessage::VEHICLE_INFO) {
onTrack = message.onTrack();
charging = message.charging();
if (message.charging() && !message.onTrack()) {
emit sendMessage("[" + getAddress().toString() + "]>> CHARGING, NOT ON TRACK.");
qDebug().noquote().nospace() << "[" << getAddress().toString() << "]" << ">> CHARGING, NOT ON TRACK.";
}
else if (!message.charging() && !message.onTrack()){
emit sendMessage("[" + getAddress().toString() + "]>> NOT CHARGING, NOT ON TRACK.");
qDebug().noquote().nospace() << "[" << getAddress().toString() << "]" << ">> NOT CHARGING, NOT ON TRACK.";
}
else if (!message.charging() && message.onTrack()) {
emit sendMessage("[" + getAddress().toString() + "]>> NOT CHARGING, ON TRACK.");
qDebug().noquote().nospace() << "[" << getAddress().toString() << "]" << ">> NOT CHARGING, ON TRACK.";
}
emit vehicleInfoUpdate(message.onTrack(), message.charging());
}
}
void AnkiCar::changeLane(int lane) {
if (lane > 17) {
destinationLane = 17;
}
else if (lane < 2) {
destinationLane = 2;
}
else {
destinationLane = lane;
}
changingLane = true;
}
void AnkiCar::sendMessage(AnkiMessage message) {
if (lowEnergyService !=0) lowEnergyService->writeCharacteristic(lowEnergyService->characteristic(CHR_WRITE_UUID), message.getMessage());
}
void AnkiCar::stop() {
setVelocity(0);
emit velocityUpdate();
}
TrackPiece::Type AnkiCar::getCurrentSegment() {
return this->currentSegment;
}
bool AnkiCar::stoppingAtStart() {
return stopAtStart;
}
bool AnkiCar::isCharging() {
return charging;
}
bool AnkiCar::isOnTrack() {
return onTrack;
}
void AnkiCar::driveToStart(int lane) {
setVelocity(500, (uint16_t)12500); // min 300, typ 500, max 700
changingLane = true;
stopAtStart = true;
this->destinationLane = lane;
qDebug().noquote().nospace() << "[" << getAddress().toString() << "]" << ">> driveToStart: current lane = " << this->getLane();
}
bool AnkiCar::isAvailable() {
return available;
}
void AnkiCar::reconnect() {
if (lowEnergyController != 0) {
// if (lowEnergyController->state() == QLowEnergyController::UnconnectedState)
lowEnergyController->connectToDevice();
}
}
void AnkiCar::setReverseDriving(bool value) {
reverseDriving = value;
}
| 38.429084 | 284 | 0.61252 | ThomasHeinrichSchmidt |
359daed756953a06ec7e66f9f817cbd0ff5f97f0 | 524 | cpp | C++ | unit_tests/test_ftoa_rev.cpp | shreyasbharath/nanoprintf | 7dc843a6201df5c2daabf675224183d3cc1a3264 | [
"Unlicense"
] | 1 | 2020-06-29T13:30:04.000Z | 2020-06-29T13:30:04.000Z | unit_tests/test_ftoa_rev.cpp | shreyasbharath/nanoprintf | 7dc843a6201df5c2daabf675224183d3cc1a3264 | [
"Unlicense"
] | null | null | null | unit_tests/test_ftoa_rev.cpp | shreyasbharath/nanoprintf | 7dc843a6201df5c2daabf675224183d3cc1a3264 | [
"Unlicense"
] | null | null | null | #include "nanoprintf_in_unit_tests.h"
#include "CppUTest/TestHarness.h"
#include <cstring>
TEST_GROUP(ftoa_rev) {
void setup() override { memset(buf, 0, sizeof(buf)); }
char buf[64];
int frac_bytes;
npf__format_spec_conversion_case_t const lower =
NPF_FMT_SPEC_CONV_CASE_LOWER;
npf__format_spec_conversion_case_t const upper =
NPF_FMT_SPEC_CONV_CASE_UPPER;
};
TEST(ftoa_rev, Zero) {
CHECK_EQUAL(2, npf__ftoa_rev(buf, 0.f, 10, lower, &frac_bytes));
STRCMP_EQUAL(".0", buf);
}
| 23.818182 | 68 | 0.709924 | shreyasbharath |
359e392ba31ff6313bede241351a2de52e092074 | 8,734 | cpp | C++ | GPUPerfStudio/Server/DX12Server/Objects/DX12WrappedObjectDatabase.cpp | davidlee80/amd-gpuperfstudio-dx12 | 4ce82d2eb0c9b8a8fc2889372b370ab23383a0fe | [
"MIT"
] | 1 | 2017-03-25T02:09:15.000Z | 2017-03-25T02:09:15.000Z | GPUPerfStudio/Server/DX12Server/Objects/DX12WrappedObjectDatabase.cpp | davidlee80/amd-gpuperfstudio-dx12 | 4ce82d2eb0c9b8a8fc2889372b370ab23383a0fe | [
"MIT"
] | null | null | null | GPUPerfStudio/Server/DX12Server/Objects/DX12WrappedObjectDatabase.cpp | davidlee80/amd-gpuperfstudio-dx12 | 4ce82d2eb0c9b8a8fc2889372b370ab23383a0fe | [
"MIT"
] | 3 | 2017-03-15T03:35:13.000Z | 2022-02-23T06:29:02.000Z | //==============================================================================
// Copyright (c) 2015 Advanced Micro Devices, Inc. All rights reserved.
/// \author AMD Developer Tools Team
/// \file
/// \brief The DX12WrappedObjectDatabase is responsible for tracking
/// wrapped and destroyed objects.
//==============================================================================
#include "DX12WrappedObjectDatabase.h"
#include "../../Common/IInstanceBase.h"
#include "IDX12InstanceBase.h"
#include "DX12ObjectDatabaseProcessor.h"
#include "Autogenerated/DX12CoreWrappers.h"
//--------------------------------------------------------------------------
/// Default constructor initializes a new instance of the DX12WrappedObjectDatabase class.
//--------------------------------------------------------------------------
DX12WrappedObjectDatabase::DX12WrappedObjectDatabase()
{
}
//--------------------------------------------------------------------------
/// Destructor destroys the DX12WrappedObjectDatabase instance.
//--------------------------------------------------------------------------
DX12WrappedObjectDatabase::~DX12WrappedObjectDatabase()
{
}
//--------------------------------------------------------------------------
/// Retrieve a list of stored database objects with the same given type.
/// \param inObjectType The type of object to search the database for.
/// \param outObjectInstancesOfGivenType A list containing same-typed object instances.
//--------------------------------------------------------------------------
void DX12WrappedObjectDatabase::GetObjectsByType(eObjectType inObjectType, WrappedInstanceVector& outObjectInstancesOfGivenType, bool inbOnlyCurrentObjects) const
{
// Loop through everything in the object database and look for specific types of objects.
DXInterfaceToWrapperMetadata::const_iterator wrapperIter;
DXInterfaceToWrapperMetadata::const_iterator endIter = mWrapperInstanceToWrapperMetadata.end();
for (wrapperIter = mWrapperInstanceToWrapperMetadata.begin(); wrapperIter != endIter; ++wrapperIter)
{
IDX12InstanceBase* wrapperMetadata = wrapperIter->second;
if (wrapperMetadata->GetObjectType() == inObjectType)
{
// If we only care about currently-active objects, don't include it if it has already been destroyed.
if (inbOnlyCurrentObjects && wrapperMetadata->IsDestroyed())
{
continue;
}
outObjectInstancesOfGivenType.push_back(wrapperMetadata);
}
}
}
//--------------------------------------------------------------------------
/// Retrieve a pointer to the wrapper instance of the given ID3D12 object.
/// \param inInstanceHandle A handle to the ID3D12 interface instance.
/// \returns A IInstanceBase pointer, which is the wrapper for the given input instance.
//--------------------------------------------------------------------------
IInstanceBase* DX12WrappedObjectDatabase::GetWrappedInstance(void* inInstanceHandle) const
{
// Look in the wrapped object database for the incoming pointer.
IUnknown* wrappedInstance = (IUnknown*)inInstanceHandle;
DXInterfaceToWrapperMetadata::const_iterator interfaceIter = mRealInstanceToWrapperMetadata.find(wrappedInstance);
DXInterfaceToWrapperMetadata::const_iterator endIter = mRealInstanceToWrapperMetadata.end();
if (interfaceIter != endIter)
{
return interfaceIter->second;
}
else
{
// Is the incoming pointer already a wrapped pointer? If so, just return the metadata object.
DXInterfaceToWrapperMetadata::const_iterator wrapperInterfaceIter = mWrapperInstanceToWrapperMetadata.find(wrappedInstance);
DXInterfaceToWrapperMetadata::const_iterator wrappersEnditer = mWrapperInstanceToWrapperMetadata.end();
if (wrapperInterfaceIter != wrappersEnditer)
{
return wrapperInterfaceIter->second;
}
}
return NULL;
}
//--------------------------------------------------------------------------
/// A handler that's invoked when a device is destroyed. Responsible for cleaning up wrappers.
/// \param inDeviceInstance A wrapper instance for the device being destroyed.
//--------------------------------------------------------------------------
void DX12WrappedObjectDatabase::OnDeviceDestroyed(IInstanceBase* inDeviceInstance)
{
// @DX12TODO: Clean up wrappers related to the destroyed object.
(void)inDeviceInstance;
}
//--------------------------------------------------------------------------
/// Attempt to unwrap the given pointer so that it points to the real ID3D12 runtime interface instance.
/// \param inPossiblyWrapperInstance A pointer to either a D3D12 interface instance, or a IDX12InstanceBase wrapper.
/// \returns True if the pointer was already unwrapped, or has been successfully unwrapped. False if the pointer is not in the database.
//--------------------------------------------------------------------------
bool DX12WrappedObjectDatabase::AttemptUnwrap(IUnknown** ioPossiblyWrapperInstance)
{
bool bUnwrappedInstance = false;
IUnknown* possibleReal = *ioPossiblyWrapperInstance;
// Is the incoming pointer a wrapped DX12 interface? Check the wrapper map to find out.
DXInterfaceToWrapperMetadata::const_iterator wrapperIter = mWrapperInstanceToWrapperMetadata.find(possibleReal);
if (wrapperIter != mWrapperInstanceToWrapperMetadata.end())
{
// The incoming pointer was a GPS_ID3D12 wrapped interface. Unwrap it here and send it back out.
IDX12InstanceBase* wrapperMetadata = wrapperIter->second;
*ioPossiblyWrapperInstance = static_cast<IUnknown*>(wrapperMetadata->GetRuntimeInstance());
bUnwrappedInstance = true;
}
else
{
Log(logWARNING, "Failed to unwrap instance '0x%p'. Likely wasn't a wrapped interface.\n", possibleReal);
}
return bUnwrappedInstance;
}
//--------------------------------------------------------------------------
/// Add a wrapper metadata object to the object database.
/// \param inWrapperMetadata A pointer to the IDX12InstanceBase wrapper metadata instance.
//--------------------------------------------------------------------------
void DX12WrappedObjectDatabase::Add(IDX12InstanceBase* inWrapperMetadata)
{
ScopeLock mutex(&mCurrentObjectsMapLock);
IUnknown* wrapperHandle = static_cast<IUnknown*>(inWrapperMetadata->GetApplicationHandle());
IUnknown* runtimeInstance = inWrapperMetadata->GetRuntimeInstance();
mWrapperInstanceToWrapperMetadata[wrapperHandle] = inWrapperMetadata;
mRealInstanceToWrapperMetadata[runtimeInstance] = inWrapperMetadata;
}
//--------------------------------------------------------------------------
/// Retrieve the IDX12InstanceBase metadata object corresponding to the given input wrapper.
/// \param An GPS_ID3D12[Something] interface wrapper.
/// \returns The IDX12InstanceBase metadata object associated with the given wrapper, or NULL if it doesn't exist.
//--------------------------------------------------------------------------
IDX12InstanceBase* DX12WrappedObjectDatabase::GetMetadataObject(IUnknown* inWrapperInstance)
{
IDX12InstanceBase* resultInstance = NULL;
DXInterfaceToWrapperMetadata::const_iterator objectIter = mWrapperInstanceToWrapperMetadata.find(inWrapperInstance);
if (objectIter != mWrapperInstanceToWrapperMetadata.end())
{
resultInstance = objectIter->second;
}
return resultInstance;
}
//--------------------------------------------------------------------------
/// Retrieve a pointer to the wrapper instance when given a pointer to the real instance.
/// \param ioInstance A pointer to the real ID3D12 interface instance.
/// \returns True if the object is already in the DB, false if it's not.
/// Note: When true, ioInstance is reassigned to the wrapper instance.
//--------------------------------------------------------------------------
bool DX12WrappedObjectDatabase::WrappedObject(IUnknown** ioInstance) const
{
ScopeLock dbLock(&mCurrentObjectsMapLock);
IUnknown* pReal = *ioInstance;
// Check if object has been wrapped
DXInterfaceToWrapperMetadata::const_iterator objectIter = mRealInstanceToWrapperMetadata.find(pReal);
if (objectIter == mRealInstanceToWrapperMetadata.end())
{
return false;
}
else
{
// The object already has a wrapper instance in the database. Return the GPS_ID3D12[Something] wrapper instance.
IDX12InstanceBase* wrapperMetaData = static_cast<IDX12InstanceBase*>(objectIter->second);
*ioInstance = (IUnknown*)wrapperMetaData->GetApplicationHandle();
return true;
}
} | 46.705882 | 162 | 0.6248 | davidlee80 |
35a06a63f02917d0b697f2d18e1da85af01b9726 | 4,275 | cpp | C++ | CaWE/MapEditor/wxExt/valTextNumber.cpp | dns/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | 3 | 2020-04-11T13:00:31.000Z | 2020-12-07T03:19:10.000Z | CaWE/MapEditor/wxExt/valTextNumber.cpp | DNS/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | null | null | null | CaWE/MapEditor/wxExt/valTextNumber.cpp | DNS/Cafu | 77b34014cc7493d6015db7d674439fe8c23f6493 | [
"MIT"
] | 1 | 2020-04-11T13:00:04.000Z | 2020-04-11T13:00:04.000Z | /*
Cafu Engine, http://www.cafu.de/
Copyright (c) Carsten Fuchs and other contributors.
This project is licensed under the terms of the MIT license.
*/
#ifndef WX_PRECOMP
#include <stdio.h>
#include "wx/textctrl.h"
#include "wx/utils.h"
#include "wx/msgdlg.h"
#include "wx/intl.h"
#endif
#include "valTextNumber.hpp"
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
IMPLEMENT_CLASS(textNumberValidator, wxValidator)
BEGIN_EVENT_TABLE(textNumberValidator, wxValidator)
EVT_CHAR(textNumberValidator::OnChar)
END_EVENT_TABLE()
textNumberValidator::textNumberValidator(double* val, double minvalue, double maxvalue)
{
m_doubleValue = val;
if ( minvalue < maxvalue )
{
m_doubleMin = minvalue;
m_doubleMax = maxvalue;
}
else
{
m_doubleMin = maxvalue;
m_doubleMax = minvalue;
}
m_isDouble = true;
}
textNumberValidator::textNumberValidator(int* val, int minvalue, int maxvalue)
{
m_intValue = val;
if ( minvalue < maxvalue )
{
m_intMin = minvalue;
m_intMax = maxvalue;
}
else
{
m_intMin = maxvalue;
m_intMax = minvalue;
}
m_isDouble = false;
}
textNumberValidator::textNumberValidator(const textNumberValidator& val)
: wxValidator()
{
Copy(val);
}
wxObject* textNumberValidator::Clone() const
{
return new textNumberValidator(*this);
}
bool textNumberValidator::Copy(const textNumberValidator& val)
{
wxValidator::Copy(val);
m_doubleValue = val.m_doubleValue;
m_doubleMin = val.m_doubleMin;
m_doubleMax = val.m_doubleMax;
m_intValue = val.m_intValue;
m_intMin = val.m_intMin;
m_intMax = val.m_intMax;
m_isDouble = val.m_isDouble;
return true;
}
textNumberValidator::~textNumberValidator()
{
}
bool textNumberValidator::Validate(wxWindow* parent)
{
if ( !CheckValidator() )
return false;
wxTextCtrl* control = (wxTextCtrl*)m_validatorWindow;
if ( !control->IsEnabled() )
return true;
wxString errormsg;
wxString stringValue = control->GetValue();
bool ok = true;
if (m_isDouble)
{
double tmpVal;
if (!stringValue.ToDouble(&tmpVal))
{
ok = false;
errormsg = "Please enter a valid number.";
}
else if (m_doubleMin != m_doubleMax)
{
if ( (tmpVal < m_doubleMin) || (tmpVal > m_doubleMax) )
{
ok = false;
errormsg = wxString::Format("Please enter a number between %.2f and %.2f", m_doubleMin, m_doubleMax);
}
}
}
else
{
long tmpVal;
if (!stringValue.ToLong(&tmpVal))
{
ok = false;
errormsg = "Please enter a valid number.";
}
else if (m_intMin != m_intMax)
{
if ( (tmpVal < m_intMin) || (tmpVal > m_intMax) )
{
ok = false;
errormsg = wxString::Format("Please enter a number between %d and %d", m_intMin, m_intMax);
}
}
}
if ( !ok )
{
wxASSERT_MSG( !errormsg.empty(), _T("you forgot to set errormsg") );
m_validatorWindow->SetFocus();
// wxString buf;
// buf.Printf(errormsg, val.c_str());
// wxMessageBox(buf, _("Invalid Number"), wxOK | wxICON_EXCLAMATION, parent);
wxMessageBox(errormsg, wxT("Invalid Number"), wxOK | wxICON_EXCLAMATION, parent);
}
return ok;
}
// Called to transfer data to the window
bool textNumberValidator::TransferToWindow(void)
{
if( !CheckValidator() )
return false;
wxTextCtrl *control = (wxTextCtrl *)m_validatorWindow ;
if (m_isDouble)
{
control->SetValue(wxString::Format("%.2f", *m_doubleValue));
}
else
{
control->SetValue(wxString::Format("%d", *m_intValue));
}
return true;
}
// Called to transfer data to the window
bool textNumberValidator::TransferFromWindow(void)
{
if( !CheckValidator() )
return false;
wxTextCtrl *control = (wxTextCtrl *) m_validatorWindow ;
wxString stringValue = control->GetValue();
if ( m_isDouble)
{
stringValue.ToDouble(m_doubleValue);
}
else
{
long tmpVal;
stringValue.ToLong(&tmpVal);
*m_intValue = (int)tmpVal;
}
return true;
}
void textNumberValidator::OnChar(wxKeyEvent& event)
{
if (m_validatorWindow)
{
int keycode = (int)event.GetKeyCode();
if (!(keycode < WXK_SPACE || keycode == WXK_DELETE || keycode > WXK_START) &&
!wxIsdigit(keycode) && (keycode != '.') && (keycode != '-'))
{
if (!wxValidator::IsSilent())
wxBell();
return;
}
}
event.Skip();
}
| 18.832599 | 105 | 0.673684 | dns |
35ac952e9eb904c05e9753e378d32f76d65155af | 1,610 | cpp | C++ | PriorityQueues/RunningMedian.cpp | tanmayagarwal06/CompetitiveProgramming | ce1df2dbe829a0babfb18e65beee8604eb80915c | [
"MIT"
] | null | null | null | PriorityQueues/RunningMedian.cpp | tanmayagarwal06/CompetitiveProgramming | ce1df2dbe829a0babfb18e65beee8604eb80915c | [
"MIT"
] | null | null | null | PriorityQueues/RunningMedian.cpp | tanmayagarwal06/CompetitiveProgramming | ce1df2dbe829a0babfb18e65beee8604eb80915c | [
"MIT"
] | 3 | 2020-10-06T02:57:41.000Z | 2020-10-20T06:54:04.000Z | #include <iostream>
#include<queue>
#include<bits/stdc++.h>
#include<math.h>
using namespace std;
void findMedian(int arr[], int n){
priority_queue<int, vector<int>, greater<int>> minHeap;
priority_queue<int> maxHeap;
for(int i = 0; i<n; i++){
if(maxHeap.size() != 0 && arr[i] > maxHeap.top()){
minHeap.push(arr[i]);
} else {
maxHeap.push(arr[i]);
}
if(abs((int)maxHeap.size() - (int)minHeap.size()) > 1){
if(maxHeap.size() > minHeap.size()){
int temp = maxHeap.top();
maxHeap.pop();
minHeap.push(temp);
} else {
int temp = minHeap.top();
minHeap.pop();
maxHeap.push(temp);
}
}
int totalSize = maxHeap.size() + minHeap.size();
int median;
if(totalSize % 2 == 1){
if(maxHeap.size() > minHeap.size()){
median = maxHeap.top();
} else {
median = minHeap.top();
}
} else{
median = 0;
if(maxHeap.size() != 0){
median += maxHeap.top();
}
if(minHeap.size() != 0){
median += minHeap.top();
}
median /= 2;
}
cout << median << endl;
}
}
int main() {
int n;
cin >> n;
int arr[n], i;
for(i=0;i<n;i++) cin >> arr[i];
findMedian(arr, n);
}
| 24.393939 | 64 | 0.398758 | tanmayagarwal06 |
35ae4b9cc45ef13cef10a51b450bff522a99faba | 718 | hpp | C++ | ultra/not_released/dark/sapi.hpp | badryasuo/UltraDark | c9f60e3a754b051db33c29129f943807c6010b9e | [
"MIT"
] | null | null | null | ultra/not_released/dark/sapi.hpp | badryasuo/UltraDark | c9f60e3a754b051db33c29129f943807c6010b9e | [
"MIT"
] | null | null | null | ultra/not_released/dark/sapi.hpp | badryasuo/UltraDark | c9f60e3a754b051db33c29129f943807c6010b9e | [
"MIT"
] | null | null | null | // Speech API from Microsoft is required.
#include <sapi.h>
#include "std.hpp"
namespace dark
{
class Voice
{
protected:
HRESULT hr = S_OK;
ISpVoice * me = NULL;
// child/teen/etc
dark::char_ptr voice;
// 'F' for Female, 'M' for Male
dark::uchar gender;
// -10 to +10
dark::ushort pitch;
// 0 to 100
dark::ushort volume;
public:
static bool Init()
{
return ::CoInitialize(NULL);
}
static void Uninit()
{
CoUninitialize();
}
Voice(dark::char_ptr voice, dark::uchar gender, dark::ushort pitch)
{
this->voice =voice;
this->gender = gender;
this->pitch = pitch;
hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void**)&me);
}
};
} | 17.95 | 85 | 0.629526 | badryasuo |
35af3e44df6420ffba7ad8544cef62d0a6e0f812 | 251 | cpp | C++ | src/cubo.cpp | Italo1994/Laboratorio2-IMD0030 | ebe3df127ec78914d2feca77f92bf398e61c023c | [
"MIT"
] | null | null | null | src/cubo.cpp | Italo1994/Laboratorio2-IMD0030 | ebe3df127ec78914d2feca77f92bf398e61c023c | [
"MIT"
] | null | null | null | src/cubo.cpp | Italo1994/Laboratorio2-IMD0030 | ebe3df127ec78914d2feca77f92bf398e61c023c | [
"MIT"
] | null | null | null | #include "cubo.h"
Cubo::Cubo(int m_aresta): aresta(m_aresta) {
area = 6 * pow(aresta, 2);
volume = aresta * aresta * aresta;
}
Cubo::~Cubo() {
}
int Cubo::getAreaCubo() {
return area;
}
int Cubo::getVolumeCubo() {
return volume;
} | 13.944444 | 45 | 0.605578 | Italo1994 |
35b2407029bfd5c4d96d001938c60ab06ef28a22 | 1,746 | cpp | C++ | src/Board.cpp | jsgaonac/towdef-ai | 5973a736d02b7e3420d2367ffd81b564519c65c9 | [
"MIT"
] | null | null | null | src/Board.cpp | jsgaonac/towdef-ai | 5973a736d02b7e3420d2367ffd81b564519c65c9 | [
"MIT"
] | null | null | null | src/Board.cpp | jsgaonac/towdef-ai | 5973a736d02b7e3420d2367ffd81b564519c65c9 | [
"MIT"
] | null | null | null | #include "Board.hpp"
logic::Board::Board()
{
}
void logic::Board::reset()
{
for (std::size_t i = 0; i < BOARD_W; i++)
{
for (std::size_t j = 0; j < BOARD_H; j++)
{
board[i][j].clear();
}
}
}
bool logic::Board::isCoordValid(int x, int y) const
{
if (x >= BOARD_W || y >= BOARD_H) return false;
if (x < 0 || y < 0) return false;
return true;
}
bool logic::Board::setPlayerAt(logic::Entity* player, int x, int y)
{
if (!isCoordValid(x, y)) return false;
board[x][y].push_back(player);
return true;
}
bool logic::Board::moveEntityTo(Entity* ent, int dstX, int dstY)
{
int srcX = ent->getPosition().x;
int srcY = ent->getPosition().y;
removeEntityAt(ent, srcX, srcY);
// The coordinate must be a valid one.
if (!isCoordValid(dstX, dstY)) return false;
// In case the coordinate is occupied, check the type of the Entity occupying that place.
if (!board[dstX][dstY].empty())
{
logic::EntityType type = board[dstX][dstY][0]->getType();
// Only attacking entities can be in a same position.
if (type != logic::EntityType::ATTACK)
{
return false;
}
}
// The entity is added if the tile is empty or if the entities in the tile are attackers.
board[dstX][dstY].push_back(ent);
// Update the new position of the entity.
ent->setPosition(dstX, dstY);
return true;
}
void logic::Board::removeEntityAt(logic::Entity* ent, int x, int y)
{
std::size_t size = board[x][y].size();
for (std::size_t i = 0; i < size; ++i)
{
if (board[x][y][i] == ent)
{
board[x][y][i] = board[x][y][size - 1];
board[x][y].pop_back();
break;
}
}
}
const std::vector<logic::Entity*>* logic::Board::getEntitiesAt(int x, int y) const
{
if (!isCoordValid(x, y)) return nullptr;
return &board[x][y];
} | 19.840909 | 90 | 0.632875 | jsgaonac |
35c0d6191a09a3afe5c6a97b52c10e99b6c4b85f | 2,303 | cpp | C++ | 1343C.cpp | JiangWeibeta/Answers-to-Codeforces-Problems | f258ed0d441f587551ae0fc55215dca189a9dcef | [
"Apache-2.0"
] | 1 | 2021-10-30T02:17:29.000Z | 2021-10-30T02:17:29.000Z | 1343C.cpp | JiangWeibeta/Answers-to-codeforces-problemset | f258ed0d441f587551ae0fc55215dca189a9dcef | [
"Apache-2.0"
] | null | null | null | 1343C.cpp | JiangWeibeta/Answers-to-codeforces-problemset | f258ed0d441f587551ae0fc55215dca189a9dcef | [
"Apache-2.0"
] | null | null | null | #include <algorithm>
#include <iostream>
#include <map>
#include <stdlib.h>
#include <vector>
using namespace std;
typedef long long ll;
struct ans
{
ll len = 0;
ll sum = 0;
ll last_element = 0;
};
void solve()
{
int size = 0;
cin >> size;
ans p_start, n_start;
vector<ll> vc(size + 1);
for (int i = 1; i < size + 1; i++)
{
cin >> vc[i];
}
int p = 0, n = 0;
for (int i = 1; i < size + 1; i++)
{
if (vc[i] > 0)
{
p_start.len = 1;
p_start.sum = vc[i];
p_start.last_element = vc[i];
p = i;
break;
}
}
for (int i = 1; i < size + 1; i++)
{
if (vc[i] < 0)
{
n_start.len = 1;
n_start.sum = vc[i];
n_start.last_element = vc[i];
n = i;
break;
}
}
for (int j = p + 1; j < size + 1; j++)
{
if (vc[j] * p_start.last_element < 0)
{
p_start.len++;
p_start.sum += vc[j];
p_start.last_element = vc[j];
}
else
{
if (vc[j] > p_start.last_element)
{
p_start.sum = p_start.sum - p_start.last_element + vc[j];
p_start.last_element = vc[j];
}
}
}
for (int j = n + 1; j < size + 1; j++)
{
if (vc[j] * n_start.last_element < 0)
{
n_start.len++;
n_start.sum += vc[j];
n_start.last_element = vc[j];
}
else
{
if (vc[j] > n_start.last_element)
{
n_start.sum = n_start.sum - n_start.last_element + vc[j];
n_start.last_element = vc[j];
}
}
}
if (p_start.len > n_start.len)
{
cout << p_start.sum << endl;
}
else
{
cout << n_start.sum << endl;
}
}
int main()
{
int cnt = 0;
cin >> cnt;
for (int i = 0; i < cnt; i++)
{
solve();
}
system("pause");
return 0;
}
| 21.726415 | 83 | 0.366479 | JiangWeibeta |
35c5d14a654a57e23c92e5c0ab6aa86496d3ea2b | 13,208 | cpp | C++ | Iron/territory/vmap.cpp | biug/titan | aacb4e2dc4d55601abd45cb8321d8e5160851eec | [
"MIT"
] | null | null | null | Iron/territory/vmap.cpp | biug/titan | aacb4e2dc4d55601abd45cb8321d8e5160851eec | [
"MIT"
] | null | null | null | Iron/territory/vmap.cpp | biug/titan | aacb4e2dc4d55601abd45cb8321d8e5160851eec | [
"MIT"
] | null | null | null | //////////////////////////////////////////////////////////////////////////
//
// This file is part of Iron's source files.
// Iron is free software, licensed under the MIT/X11 License.
// A copy of the license is provided with the library in the LICENSE file.
// Copyright (c) 2016, 2017, Igor Dimitrijevic
//
//////////////////////////////////////////////////////////////////////////
#include "vmap.h"
#include "../Iron.h"
namespace { auto & bw = Broodwar; }
namespace iron
{
int pathExists(const Position & a, const Position & b)
{
int length;
ai()->GetMap().GetPath(a, b, &length);
return (length >= 0);
}
//////////////////////////////////////////////////////////////////////////////////////////////
// //
// class VMap
// //
//////////////////////////////////////////////////////////////////////////////////////////////
VMap::VMap(BWEM::Map * pMap)
: m_pMap(pMap)
{
m_Bases.reserve(pMap->BaseCount());
m_Areas.reserve(pMap->Areas().size());
m_ChokePoints.reserve(pMap->ChokePointCount());
ChokePoint::UnmarkAll();
for (const Area & area : pMap->Areas())
{
m_Areas.emplace_back(&area);
for (const Base & base : area.Bases())
m_Bases.emplace_back(&base);
for (const ChokePoint * cp : area.ChokePoints())
if (!cp->Marked())
{
cp->SetMarked();
m_ChokePoints.emplace_back(cp);
}
}
vector<const Neutral *> Neutrals;
for (const auto & m : pMap->Minerals()) Neutrals.push_back(m.get());
for (const auto & g : pMap->Geysers()) Neutrals.push_back(g.get());
for (const auto & sb : pMap->StaticBuildings()) Neutrals.push_back(sb.get());
for (const Neutral * n : Neutrals)
{
vector<TilePosition> Border = outerBorder(n->TopLeft(), n->Size(), bool("noCorner"));
for (auto t : Border)
if (pMap->Valid(t))
ai()->GetVMap().SetNearNeutral(pMap->GetTile(t, check_t::no_check));
if (n->IsRessource())
for (int dy = -3 ; dy < n->Size().y + 3 ; ++dy)
for (int dx = -3 ; dx < n->Size().x + 3 ; ++dx)
{
TilePosition t = n->TopLeft() + TilePosition(dx, dy);
if (pMap->Valid(t))
ai()->GetVMap().SetCommandCenterImpossible(pMap->GetTile(t, check_t::no_check));
}
}
for (const VBase & base : m_Bases)
for (int dy = 0 ; dy < UnitType(Terran_Command_Center).tileSize().y ; ++dy)
for (int dx = 0 ; dx < UnitType(Terran_Command_Center).tileSize().x + 2 ; ++dx)
{
TilePosition t = base.BWEMPart()->Location() + TilePosition(dx, dy);
if (pMap->Valid(t))
ai()->GetVMap().SetCommandCenterWithAddonRoom(pMap->GetTile(t, check_t::no_check));
}
Initialize();
}
void VMap::Initialize()
{
for (VBase & base : m_Bases)
base.Initialize();
for (VArea & area : Areas())
area.Initialize();
for (VChokePoint & cp : ChokePoints())
cp.Initialize();
ComputeImpasses(1);
ComputeImpasses(2);
for (VBase & base : m_Bases)
if (base.BWEMPart()->Starting())
base.AssignWall();
}
void VMap::Update()
{
for (VChokePoint & cp : ChokePoints())
cp.Update();
if (m_MainPath.empty())
if (him().StartingBase())
m_MainPath = ai()->GetMap().GetPath(me().StartingBase()->Center(), him().StartingBase()->Center(), &m_MainPathLength);
}
VBase * VMap::GetBaseAt(TilePosition location)
{
auto it = find_if(m_Bases.begin(), m_Bases.end(), [location](const VBase & base){ return base.BWEMPart()->Location() == location; });
return it == m_Bases.end() ? nullptr : &*it;
}
WalkPosition VMap::GetIncreasingAltitudeDirection(WalkPosition pos) const
{
assert_throw(GetMap()->Valid(pos));
altitude_t maxAltitude = -1;
WalkPosition bestDir;
for (WalkPosition delta : { WalkPosition(-1, -1), WalkPosition(0, -1), WalkPosition(+1, -1),
WalkPosition(-1, 0), WalkPosition(+1, 0),
WalkPosition(-1, +1), WalkPosition(0, +1), WalkPosition(+1, +1)})
{
WalkPosition w = pos + delta;
if (GetMap()->Valid(w))
{
altitude_t altitude = GetMap()->GetMiniTile(w, check_t::no_check).Altitude();
if (altitude > maxAltitude)
{
maxAltitude = altitude;
bestDir = delta;
}
}
}
return bestDir;
}
Position VMap::RandomPosition(Position center, int radius) const
{
return GetMap()->Crop(center + Position(radius - rand()%(2*radius), radius - rand()%(2*radius)));
}
Position VMap::RandomSeaPosition() const
{
for (int tries = 0 ; tries < 1000 ; ++tries)
{
Position p = GetMap()->RandomPosition();
if (GetMap()->GetMiniTile(WalkPosition(p), check_t::no_check).Sea())
return p;
}
return GetMap()->RandomPosition();
}
bool VMap::Impasse(int i, const Tile & tile) const
{
switch(i)
{
case 1: return Impasse<4>(tile);
case 2: return Impasse<8>(tile);
}
assert_throw(false);
}
void VMap::SetImpasse(int i, const Tile & tile)
{
switch(i)
{
case 1: return SetImpasse<4>(tile);
case 2: return SetImpasse<8>(tile);
}
assert_throw(false);
}
void VMap::UnsetImpasse(int i, const Tile & tile)
{
switch(i)
{
case 1: return UnsetImpasse<4>(tile);
case 2: return UnsetImpasse<8>(tile);
}
assert_throw(false);
}
void VMap::ComputeImpasses_MarkRessources()
{
vector<const Ressource *> Ressources;
for (const auto & m : ai()->GetMap().Minerals())
Ressources.push_back(m.get());
for (const auto & g : ai()->GetMap().Geysers())
Ressources.push_back(g.get());
for (const Ressource * r : Ressources)
{
bool edgeRessource = false;
for (int ndy = 0 ; ndy < r->Size().y ; ++ndy) if (!edgeRessource)
for (int ndx = 0 ; ndx < r->Size().x ; ++ndx) if (!edgeRessource)
{
TilePosition t = r->TopLeft() + TilePosition(ndx, ndy);
if (GetMap()->GetTile(t).MinAltitude() <= 3*32)
edgeRessource = true;
}
if (!edgeRessource) continue;
for (int ndy = 0 ; ndy < r->Size().y ; ++ndy)
for (int ndx = 0 ; ndx < r->Size().x ; ++ndx)
{
TilePosition t = r->TopLeft() + TilePosition(ndx, ndy);
for (int dy = -4 ; dy <= +4 ; ++dy)
for (int dx = -4 ; dx <= +4 ; ++dx)
{
TilePosition t2 = t + TilePosition(dx, dy);
if (!GetMap()->Valid(t2)) continue;
const Tile & tile2 = GetMap()->GetTile(t2);
if (!tile2.Marked())
if (dist(t, t2) <= 4)
{
tile2.SetMarked();
}
}
}
}
}
void VMap::ComputeImpasses(int kind)
{
Tile::UnmarkAll();
if (kind == 2) ComputeImpasses_MarkRessources();
for (const Area & area : GetMap()->Areas())
{
int k = 4*32;
altitude_t maxAltitude = area.MaxAltitude();
// MapPrinter::Get().Circle(WalkPosition(area.Top()), maxAltitude/8, MapPrinter::Color(255, 0, 255));
int impasseCount = 0;
for (int tryNum = 1 ; tryNum <= 2 ; ++tryNum)
{
if ((maxAltitude < k+2*32) || (tryNum == 2)) k = (maxAltitude/2 + 16)/32*32;
for (int y = area.TopLeft().y ; y <= area.BottomRight().y ; ++y)
for (int x = area.TopLeft().x ; x <= area.BottomRight().x ; ++x)
{
TilePosition t(x, y);
const Tile & tile = GetMap()->GetTile(t);
if (tile.AreaId() == area.Id())
{
if (k <= tile.MinAltitude())
{
if (!Impasse(kind, GetMap()->GetTile(t)))
{
SetImpasse(kind, GetMap()->GetTile(t));
++impasseCount;
}
if (tile.MinAltitude() <= k+1*32 && !tile.Marked())
for (int dy = -k/32 ; dy <= +k/32 ; ++dy)
for (int dx = -k/32 ; dx <= +k/32 ; ++dx)
{
TilePosition t2(x + dx, y + dy);
if (!GetMap()->Valid(t2)) continue;
const Tile & tile2 = GetMap()->GetTile(t2);
if (tile2.AreaId() == area.Id())
{
if (dist(t, t2) <= (k/32))
if (!Impasse(kind, GetMap()->GetTile(t2)))
{
SetImpasse(kind, GetMap()->GetTile(t2));
++impasseCount;
}
}
}
}
}
}
if (tryNum == 1)
{
/// Log << impasseCount << " / " << area.MiniTiles()/16 << " " << double(impasseCount)/(area.MiniTiles()/16) << endl;
if (double(impasseCount)/max(1, (area.MiniTiles()/16)) >= 0.65) break;
}
}
}
for (const Area & area : GetMap()->Areas())
{
for (const ChokePoint * cp : area.ChokePoints())
if (!cp->Blocked())
{
ComputeImpasses_FillFromChokePoint(kind, area, cp);
for (WalkPosition w : cp->Geometry())
SetImpasse(kind, GetMap()->GetTile(TilePosition(w)));
}
}
for (int y = 0 ; y < GetMap()->Size().y ; ++y)
for (int x = 0 ; x < GetMap()->Size().x ; ++x)
{
const Tile & tile = GetMap()->GetTile(TilePosition(x, y), check_t::no_check);
if (Impasse(kind, tile)) UnsetImpasse(kind, tile);
else SetImpasse(kind, tile);
}
}
void VMap::ComputeImpasses_FillFromChokePoint(int kind, const Area & area, const ChokePoint * cp)
{
Tile::UnmarkAll();
TilePosition start = TilePosition(cp->PosInArea(ChokePoint::middle, &area));
queue<TilePosition> ToVisit;
ToVisit.push(start);
const Tile & Start = GetMap()->GetTile(start, check_t::no_check);
Start.SetMarked();
int matchesCount = 0;
altitude_t cpAltitude = ext(cp)->MaxAltitude();
int dd = Start.MinAltitude() + 0;
TilePosition maxAltitudeTile = TilePosition(cp->Center());
while (!ToVisit.empty())
{
TilePosition current = ToVisit.front();
ToVisit.pop();
for (TilePosition delta : { TilePosition(-1, -1), TilePosition(0, -1), TilePosition(+1, -1),
TilePosition(-1, 0), TilePosition(+1, 0),
TilePosition(-1, +1), TilePosition(0, +1), TilePosition(+1, +1)})
{
TilePosition next = current + delta;
if (GetMap()->Valid(next))
{
const Tile & Next = GetMap()->GetTile(next, check_t::no_check);
if (!Next.Marked())
if (Next.AreaId() == area.Id())
{
int d = Next.MinAltitude() + int(dist(next, start)*32/2);
if (d >= dd) { dd = d; maxAltitudeTile = next; }
Next.SetMarked();
ToVisit.push(next);
if (!Impasse(kind, Next))
{
if (dist(next, maxAltitudeTile)*32 <= cpAltitude+3*32)
SetImpasse(kind, Next);
}
else
{
if (++matchesCount == (2*cpAltitude/32 + 2)*(2*cpAltitude/32 + 2)) return;
}
}
}
}
}
}
void VMap::PrintImpasses() const
{
#if BWEM_USE_MAP_PRINTER
for (int y = 0 ; y < GetMap()->Size().y ; ++y)
for (int x = 0 ; x < GetMap()->Size().x ; ++x)
{
const Tile & tile = GetMap()->GetTile(TilePosition(x, y));
if (tile.Walkable())
if (tile.AreaId() > 0 || tile.AreaId() == -1)
{
WalkPosition origin(TilePosition(x, y));
MapPrinter::Color col = MapPrinter::Color(255, 255, 255);
if (Impasse(1, tile))
MapPrinter::Get().Rectangle(origin + 0, origin + 3, col);
if (Impasse(2, tile))
MapPrinter::Get().Rectangle(origin + 1, origin + 2, col);
}
}
#endif
}
int VMap::BuildingsAndNeutralsAround(TilePosition center, int radius) const
{
vector<void *> DistinctBuildingsAndNeutrals;
for (int dy = -radius ; dy <= +radius ; ++dy)
for (int dx = -radius ; dx <= +radius ; ++dx)
{
TilePosition t = center + TilePosition(dx, dy);
if (GetMap()->Valid(t))
{
const Tile & tile = GetMap()->GetTile(t, check_t::no_check);
if (BWAPIUnit * b = GetBuildingOn(tile)) push_back_if_not_found(DistinctBuildingsAndNeutrals, b);
else if (Neutral * n = tile.GetNeutral()) push_back_if_not_found(DistinctBuildingsAndNeutrals, n);
}
}
return DistinctBuildingsAndNeutrals.size();
}
HisBuilding * VMap::EnemyBuildingsAround(TilePosition center, int radius) const
{
for (int dy = -radius ; dy <= +radius ; dy += 2)
for (int dx = -radius ; dx <= +radius ; dx += 2)
{
TilePosition t = center + TilePosition(dx, dy);
if (GetMap()->Valid(t))
{
const Tile & tile = GetMap()->GetTile(t, check_t::no_check);
if (BWAPIUnit * b = GetBuildingOn(tile))
if (HisBuilding * pHisBuilding = b->IsHisBuilding())
return pHisBuilding;
}
}
return nullptr;
}
void VMap::PrintAreaChains() const
{
#if BWEM_USE_MAP_PRINTER
MapPrinter::Color col = MapPrinter::Color(255, 255, 0);
set<const AreaChain *> AreaChains;
for (const VArea & area : Areas())
if (const AreaChain * pChain = area.IsInChain())
AreaChains.insert(pChain);
for (const AreaChain * pChain : AreaChains)
{
if (pChain->GetAreas().size() == 1)
MapPrinter::Get().Circle(pChain->GetAreas().front()->BWEMPart()->Top(), 5, col);
else
for (int i = 1 ; i < (int)pChain->GetAreas().size() ; ++i)
MapPrinter::Get().Line(pChain->GetAreas()[i-1]->BWEMPart()->Top(), pChain->GetAreas()[i]->BWEMPart()->Top(), col);
if (pChain->IsLeaf())
for (VArea * area : {pChain->GetAreas().front(), pChain->GetAreas().back()})
if (area->BWEMPart()->AccessibleNeighbours().size() == 1)
{
MapPrinter::Get().Circle(area->BWEMPart()->Top(), 4, MapPrinter::Color(0, 0, 0), MapPrinter::fill);
MapPrinter::Get().Circle(area->BWEMPart()->Top(), 2, col, MapPrinter::fill);
}
}
#endif
}
void VMap::PrintEnlargedAreas() const
{
#if BWEM_USE_MAP_PRINTER
for (const VArea & area : Areas())
for (const Area * ext : area.EnlargedArea())
if (ext != area.BWEMPart())
{
MapPrinter::Color col = MapPrinter::Color(0, 0, 255);
MapPrinter::Get().Line(area.BWEMPart()->Top(), ext->Top(), col, MapPrinter::dashed);
}
#endif
}
} // namespace iron
| 26.310757 | 134 | 0.58457 | biug |
35c6d8e728175661d80749ca30c0cfdf97d38ab0 | 6,123 | cpp | C++ | tests/unit_tests/common.shared/message_processing/test_message_tokenizer.cpp | Vavilon3000/icq | 9fe7a3c42c07eb665d2e3b0ec50052de382fd89c | [
"Apache-2.0"
] | 1 | 2019-12-02T08:37:10.000Z | 2019-12-02T08:37:10.000Z | tests/unit_tests/common.shared/message_processing/test_message_tokenizer.cpp | Vavilon3000/icq | 9fe7a3c42c07eb665d2e3b0ec50052de382fd89c | [
"Apache-2.0"
] | null | null | null | tests/unit_tests/common.shared/message_processing/test_message_tokenizer.cpp | Vavilon3000/icq | 9fe7a3c42c07eb665d2e3b0ec50052de382fd89c | [
"Apache-2.0"
] | null | null | null | #include <boost/test/unit_test.hpp>
#include <common.shared/message_processing/message_tokenizer.h>
#ifdef CHECK_TOKEN_START
#error Rename the macros
#endif
#define CHECK_TOKEN_START common::tools::message_tokenizer tokenizer(_message);
#ifdef CHECK_TOKEN_N
#error Rename the macros
#endif
#define CHECK_TOKEN_N(N) \
if (!tokenizer.has_token()) { std::cerr << "no token\n"; return false; } \
if (tokenizer.current().type_ != get_type<T##N>()) { std::cerr << tokenizer.current().type_ << " != " << get_type<T##N>() << '\n'; return false; } \
if (!equal<T##N>(tokenizer.current().data_, _v##N)) { std::cerr << to_string<T##N>(tokenizer.current().data_) << " != " << _v##N << '\n'; return false; } \
tokenizer.next();
#ifdef CHECK_TOKEN_FINISH
#error Rename the macros
#endif
#define CHECK_TOKEN_FINISH \
if (tokenizer.has_token()) { std::cerr << "too many tokens\n"; return false; } \
return true;
namespace
{
template <class T>
common::tools::message_token::type get_type(typename std::enable_if<std::is_convertible<T, std::string>::value>::type* _dummy = nullptr)
{
return common::tools::message_token::type::text;
}
template <class T>
common::tools::message_token::type get_type(typename std::enable_if<std::is_same<T, common::tools::url>::value>::type* _dummy = nullptr)
{
return common::tools::message_token::type::url;
}
template <class T>
bool equal(const common::tools::message_token::data_t& x, const T& y, typename std::enable_if<std::is_convertible<T, std::string>::value>::type* _dummy = nullptr)
{
return boost::get<std::string>(x) == y;
}
template <class T>
bool equal(const common::tools::message_token::data_t& x, const T& y, typename std::enable_if<std::is_same<T, common::tools::url>::value>::type* _dummy = nullptr)
{
return boost::get<T>(x) == y;
}
template <class T>
std::string to_string(const common::tools::message_token::data_t& x, typename std::enable_if<std::is_convertible<T, std::string>::value>::type* _dummy = nullptr)
{
return boost::get<std::string>(x);
}
template <class T>
std::string to_string(const common::tools::message_token::data_t& x, typename std::enable_if<std::is_same<T, common::tools::url>::value>::type* _dummy = nullptr)
{
std::stringstream buf;
buf << boost::get<T>(x);
return buf.str();
}
template <class T1>
bool check(const char* _message, const T1& _v1)
{
CHECK_TOKEN_START
CHECK_TOKEN_N(1)
CHECK_TOKEN_FINISH
}
template <class T1, class T2>
bool check(const char* _message, const T1& _v1, const T2& _v2)
{
CHECK_TOKEN_START
CHECK_TOKEN_N(1)
CHECK_TOKEN_N(2)
CHECK_TOKEN_FINISH
}
template <class T1, class T2, class T3>
bool check(const char* _message, const T1& _v1, const T2& _v2, const T3& _v3)
{
CHECK_TOKEN_START
CHECK_TOKEN_N(1)
CHECK_TOKEN_N(2)
CHECK_TOKEN_N(3)
CHECK_TOKEN_FINISH
}
template <class T1, class T2, class T3, class T4>
bool check(const char* _message, const T1& _v1, const T2& _v2, const T3& _v3, const T4& _v4)
{
CHECK_TOKEN_START
CHECK_TOKEN_N(1)
CHECK_TOKEN_N(2)
CHECK_TOKEN_N(3)
CHECK_TOKEN_N(4)
CHECK_TOKEN_FINISH
}
template <class T1, class T2, class T3, class T4, class T5>
bool check(const char* _message, const T1& _v1, const T2& _v2, const T3& _v3, const T4& _v4, const T5& _v5)
{
CHECK_TOKEN_START
CHECK_TOKEN_N(1)
CHECK_TOKEN_N(2)
CHECK_TOKEN_N(3)
CHECK_TOKEN_N(4)
CHECK_TOKEN_N(5)
CHECK_TOKEN_FINISH
}
template <class T1, class T2, class T3, class T4, class T5, class T6>
bool check(const char* _message, const T1& _v1, const T2& _v2, const T3& _v3, const T4& _v4, const T5& _v5, const T6& _v6)
{
CHECK_TOKEN_START
CHECK_TOKEN_N(1)
CHECK_TOKEN_N(2)
CHECK_TOKEN_N(3)
CHECK_TOKEN_N(4)
CHECK_TOKEN_N(5)
CHECK_TOKEN_N(6)
CHECK_TOKEN_FINISH
}
}
#undef CHECK_TOKEN_START
#undef CHECK_TOKEN_N
#undef CHECK_TOKEN_FINISH
BOOST_AUTO_TEST_SUITE(common)
BOOST_AUTO_TEST_SUITE(tools)
BOOST_AUTO_TEST_SUITE(message_processing)
BOOST_AUTO_TEST_CASE(test_message_tokenizer)
{
using namespace common::tools;
BOOST_CHECK(check("текст 8.8.8@ya.ru.", "текст ", url("8.8.8@ya.ru", url::type::email, url::protocol::undefined, url::extension::undefined), "."));
BOOST_CHECK(check("http://mail.ru? текст", url("http://mail.ru", url::type::site, url::protocol::http, url::extension::undefined), "? текст"));
BOOST_CHECK(check("O.life", url("http://O.life", url::type::site, url::protocol::http, url::extension::undefined)));
BOOST_CHECK(check("O.life!", url("http://O.life", url::type::site, url::protocol::http, url::extension::undefined), "!"));
BOOST_CHECK(check("O.life 18", url("http://O.life", url::type::site, url::protocol::http, url::extension::undefined), " 18"));
BOOST_CHECK(check("https://ya.ru, Ok!", url("https://ya.ru", url::type::site, url::protocol::https, url::extension::undefined), ", Ok!"));
BOOST_CHECK(check("test1@mail.ru\ntest2@mail.ru\ntest3@mail.ru", url("test1@mail.ru", url::type::email, url::protocol::undefined, url::extension::undefined), "\n",
url("test2@mail.ru", url::type::email, url::protocol::undefined, url::extension::undefined), "\n",
url("test3@mail.ru", url::type::email, url::protocol::undefined, url::extension::undefined)));
BOOST_CHECK(check("получить https://files.icq.net/get/ ->> первая часть", "получить ",
url("https://files.icq.net/get/", url::type::site, url::protocol::https, url::extension::undefined), " ->> первая часть"));
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()
| 37.564417 | 168 | 0.633186 | Vavilon3000 |
35d0da7eebdf514a79697e044e0d5fdf794b0240 | 3,363 | cpp | C++ | Codeforces/1000~1999/1252/L.cpp | tiger0132/code-backup | 9cb4ee5e99bf3c274e34f1e59d398ab52e51ecf7 | [
"MIT"
] | 6 | 2018-12-30T06:16:54.000Z | 2022-03-23T08:03:33.000Z | Codeforces/1000~1999/1252/L.cpp | tiger0132/code-backup | 9cb4ee5e99bf3c274e34f1e59d398ab52e51ecf7 | [
"MIT"
] | null | null | null | Codeforces/1000~1999/1252/L.cpp | tiger0132/code-backup | 9cb4ee5e99bf3c274e34f1e59d398ab52e51ecf7 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <cstdio>
#include <cstring>
#include <map>
#include <queue>
#include <stack>
#include <vector>
#define int ll
void fuck(bool exp) {
while (!exp) exp = 0;
}
typedef long long ll;
const int N = 3e4 + 43, M = 2e6 + 62, K = 2e3 + 32;
struct {
struct edge {
int to, next, w;
} e[M << 1];
int head[N], cnt = 1;
void operator()(int x, int y, int z) {
fuck(cnt <= 3e6);
e[++cnt] = {y, x[head], 0}, x[head] = cnt;
e[++cnt] = {x, y[head], z}, y[head] = cnt;
}
int lv[N];
bool bfs(int s, int t) {
memset(lv, 0, sizeof lv), s[lv] = 1;
std::queue<int> q;
for (q.push(s); !q.empty(); q.pop())
for (int x = q.front(), i = x[head], nx; i; i = e[i].next)
if (!(nx = e[i].to)[lv] && e[i ^ 1].w) q.push(nx), nx[lv] = x[lv] + 1;
return t[lv];
}
int dfs(int s, int t, int f) {
if (s == t || !f) return f;
int r = 0;
for (int i = s[head], nx, w; f && i; i = e[i].next)
if ((nx = e[i].to)[lv] == s[lv] + 1 && e[i ^ 1].w)
w = dfs(nx, t, std::min(f, e[i ^ 1].w)), e[i].w += w, e[i ^ 1].w -= w,
r += w, f -= w;
return (f && (s[lv] = 0)), r;
}
ll dinic(int s, int t) {
ll r = 0;
while (bfs(s, t)) r += dfs(s, t, 1e9);
return r;
}
} f;
struct {
struct edge {
int to, next;
} e[M << 1];
int head[N], cnt = 1;
void operator()(int x, int y) {
fuck(cnt <= 3e6);
e[++cnt] = {y, x[head]}, x[head] = cnt;
e[++cnt] = {x, y[head]}, y[head] = cnt;
}
} g;
std::stack<int> st;
bool v[N], R[N];
bool dfs(int x, int p) {
if (x[v]) {
for (int y = 0; y != x; st.pop()) (y = st.top())[R] = true;
return true;
}
st.push(x), x[v] = true;
for (int i = x[g.head]; i; i = g.e[i].next)
if (i != (p ^ 1) && dfs(g.e[i].to, i)) return true;
return st.pop(), false;
}
std::map<int, int> mp;
int id(int x) {
if (!mp.count(x)) return mp[x] = (int)mp.size() + 1;
return mp[x];
}
int n, k, x, y, z, c[N], l[K], ans[K][2], cntR;
std::vector<int> a[K], worker[N], idx[K];
int S, S0, T, edge[N], material[N], nc;
// bool vis[K][K];
int aaaa[K];
signed main() {
// freopen("1.in", "r", stdin);
scanf("%lld%lld", &n, &k);
S = 1, S0 = 2, T = 3, nc = 3;
for (int i = 1; i <= n; edge[i] = ++nc, g(i++, x))
for (scanf("%lld%lld", &x, &y), l[i] = x; y--;) {
scanf("%lld", &z), z = id(z);
// vis[i][z] = 1;
a[i].push_back(z);
}
for (int i = 1; i <= k; i++)
scanf("%lld", &x), x = id(x), /*aaaa[i] = x, */ worker[x].push_back(i), c[x]++;
for (int i = 1; i <= (int)mp.size(); i++) material[i] = ++nc;
fuck(nc <= 2e4);
dfs(1, 0);
for (int i = 1; i <= n; i++)
if (!i[R]) {
f(S, edge[i], 1);
for (int j : a[i]) f(edge[i], material[j], 1), idx[i].push_back(f.cnt - 1);
} else {
cntR++;
f(S0, edge[i], 1);
for (int j : a[i]) f(edge[i], material[j], 1), idx[i].push_back(f.cnt - 1);
}
for (int i = 1; i <= (int)mp.size(); i++) f(material[i], T, c[i]);
f(S, S0, cntR - 1);
if (f.dinic(S, T) < n - 1) return puts("-1"), 0;
for (int i = 1; i <= n; i++)
for (int jj = 0; jj < a[i].size(); jj++) {
x = idx[i][jj];
int j = a[i][jj];
if (f.e[x].w) {
z = worker[j].back(), worker[j].pop_back();
z[ans][0] = i, z[ans][1] = l[i];
}
}
// bool f1 = 1;
// int count = 0;
for (int i = 1; i <= k; i++) {
printf("%lld %lld\n", ans[i][0], ans[i][1]);
// if (ans[i][0]) f1 &= vis[ans[i][0]][aaaa[i]], count++;
}
// while (!f1 || count != n - 1)
// ;
} | 25.477273 | 81 | 0.470116 | tiger0132 |
35d4620b8e7dfdbb17232f69f6cfde5933e06ceb | 441 | hpp | C++ | GazeTracker/GazeTracker_Qt/ProcessingUI.hpp | bernhardrieder/GazeTracker | b468a03cb986a4950ee1d2a49df759e17a80c5cc | [
"MIT"
] | null | null | null | GazeTracker/GazeTracker_Qt/ProcessingUI.hpp | bernhardrieder/GazeTracker | b468a03cb986a4950ee1d2a49df759e17a80c5cc | [
"MIT"
] | null | null | null | GazeTracker/GazeTracker_Qt/ProcessingUI.hpp | bernhardrieder/GazeTracker | b468a03cb986a4950ee1d2a49df759e17a80c5cc | [
"MIT"
] | null | null | null | #pragma once
#include <QWidget>
#include "ui_processingui.h"
namespace gt
{
class ProcessingUI : public QWidget
{
Q_OBJECT
public:
ProcessingUI(QWidget* parent = Q_NULLPTR);
~ProcessingUI();
signals:
void closing();
public slots:
void show();
void close();
void stateChanged(int);
void changeProgess(double) const;
protected:
void closeEvent(QCloseEvent* event) override;
private:
Ui::ProcessingUI ui;
};
}
| 15.206897 | 47 | 0.705215 | bernhardrieder |
35dfe14a1f1fecf3af4fd987e3be6b9840c7da8a | 2,466 | cpp | C++ | qws/src/gui/QStyleOptionTitleBar.cpp | keera-studios/hsQt | 8aa71a585cbec40005354d0ee43bce9794a55a9a | [
"BSD-2-Clause"
] | 42 | 2015-02-16T19:29:16.000Z | 2021-07-25T11:09:03.000Z | qws/src/gui/QStyleOptionTitleBar.cpp | keera-studios/hsQt | 8aa71a585cbec40005354d0ee43bce9794a55a9a | [
"BSD-2-Clause"
] | 1 | 2017-11-23T12:49:25.000Z | 2017-11-23T12:49:25.000Z | qws/src/gui/QStyleOptionTitleBar.cpp | keera-studios/hsQt | 8aa71a585cbec40005354d0ee43bce9794a55a9a | [
"BSD-2-Clause"
] | 5 | 2015-10-15T21:25:30.000Z | 2017-11-22T13:18:24.000Z | /////////////////////////////////////////////////////////////////////////////
//
// File : QStyleOptionTitleBar.cpp
// Copyright : (c) David Harley 2010
// Project : qtHaskell
// Version : 1.1.4
// Modified : 2010-09-02 17:02:05
//
// Warning : this file is machine generated - do not modify.
//
/////////////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <wchar.h>
#include <qtc_wrp_core.h>
#include <qtc_wrp_gui.h>
#include <qtc_subclass.h>
#ifndef dhclassheader
#define dhclassheader
#include <qpointer.h>
#include <dynamicqhandler.h>
#include <DhOther_gui.h>
#include <DhAutohead_gui.h>
#endif
extern "C"
{
QTCEXPORT(void*,qtc_QStyleOptionTitleBar)() {
QStyleOptionTitleBar*tr = new QStyleOptionTitleBar();
return (void*) tr;
}
QTCEXPORT(void*,qtc_QStyleOptionTitleBar1)(void* x1) {
QStyleOptionTitleBar*tr = new QStyleOptionTitleBar((const QStyleOptionTitleBar&)(*(QStyleOptionTitleBar*)x1));
return (void*) tr;
}
QTCEXPORT(void*,qtc_QStyleOptionTitleBar_icon)(void* x0) {
QIcon * tc = new QIcon(((QStyleOptionTitleBar*)x0)->icon);
return (void*)(tc);
}
QTCEXPORT(void,qtc_QStyleOptionTitleBar_setIcon)(void* x0, void* x1) {
((QStyleOptionTitleBar*)x0)->icon = (QIcon)(*(QIcon*)x1);
}
QTCEXPORT(void,qtc_QStyleOptionTitleBar_setText)(void* x0, wchar_t* x1) {
((QStyleOptionTitleBar*)x0)->text = from_method(x1);
}
QTCEXPORT(void,qtc_QStyleOptionTitleBar_setTitleBarFlags)(void* x0, long x1) {
((QStyleOptionTitleBar*)x0)->titleBarFlags = (Qt::WindowFlags)x1;
}
QTCEXPORT(void,qtc_QStyleOptionTitleBar_setTitleBarState)(void* x0, int x1) {
((QStyleOptionTitleBar*)x0)->titleBarState = (int)x1;
}
QTCEXPORT(void*,qtc_QStyleOptionTitleBar_text)(void* x0) {
QString * tq = new QString(((QStyleOptionTitleBar*)x0)->text);
return (void*)(tq);
}
QTCEXPORT(long,qtc_QStyleOptionTitleBar_titleBarFlags)(void* x0) {
return (long) ((QStyleOptionTitleBar*)x0)->titleBarFlags;
}
QTCEXPORT(int,qtc_QStyleOptionTitleBar_titleBarState)(void* x0) {
return (int) ((QStyleOptionTitleBar*)x0)->titleBarState;
}
QTCEXPORT(void,qtc_QStyleOptionTitleBar_finalizer)(void* x0) {
delete ((QStyleOptionTitleBar*)x0);
}
QTCEXPORT(void*,qtc_QStyleOptionTitleBar_getFinalizer)() {
return (void*)(&qtc_QStyleOptionTitleBar_finalizer);
}
QTCEXPORT(void,qtc_QStyleOptionTitleBar_delete)(void* x0) {
delete((QStyleOptionTitleBar*)x0);
}
}
| 28.674419 | 112 | 0.680049 | keera-studios |
35e1cf174455cf1dad50e68bb6bb2817733691dd | 3,320 | cpp | C++ | docalculation.cpp | jlee975/qfractal | 76fd98b1775c20495c46de0a8a0280151a47ef8a | [
"MIT"
] | 1 | 2021-05-18T02:43:43.000Z | 2021-05-18T02:43:43.000Z | docalculation.cpp | jlee975/qfractal | 76fd98b1775c20495c46de0a8a0280151a47ef8a | [
"MIT"
] | null | null | null | docalculation.cpp | jlee975/qfractal | 76fd98b1775c20495c46de0a8a0280151a47ef8a | [
"MIT"
] | null | null | null | #include "docalculation.h"
#include <iostream>
#include "mandelbrot.h"
namespace
{
int msb(int x)
{
if (x == 0) return 0;
int m = 1;
while (x / m > 1)
m += m;
return m;
}
color_t color_index(int i)
{
#if 0
color_t c = { (i % 512 >= 256 ? 255 - i % 256 : i % 256), 0, 0 };
return c;
#else
std::size_t ncolors = sizeof(chromamap) / sizeof(chromamap[0]);
return chromamap[static_cast<unsigned>(i) % ncolors];
#endif
}
}
// im must be a pointer to an array of size >= 4wh bytes
DoCalculation::DoCalculation(QObject *parent)
: QThread(parent), image(0), w(0), h(0), f(0), centerx(0), centery(0),
scale(), status(0), black(), red()
{
color_t b = { 0, 0, 0 };
black = b;
color_t r = { 255, 0, 0 };
red = r;
}
void DoCalculation::setRange(
unsigned char* im,
int w_,
int h_,
Mandelbrot* f_,
double centerx_,
double centery_,
double scale_
)
{
image = im;
w = w_;
h = h_;
f = f_;
centerx = centerx_;
centery = centery_;
scale = scale_;
status_t* t = status;
status = new status_t[w_ * h_];
delete[] t;
for (std::size_t i = 0; i < static_cast<unsigned>(w * h); ++i)
status[i] = Untested;
}
DoCalculation::~DoCalculation() {
delete[] status;
}
DoCalculation::status_t DoCalculation::updatePoint(int x, int y)
{
status_t s = status[y * w + x];
if (s == Untested)
{
// initial point
double cx = ((x + x - w) * scale) / w + centerx;
double cy = ((y + y - h) * scale) / h + centery;
int e = (*f)(cx, cy);
s = (e < 0 ? InSet : NotInSet);
status[y * w + x] = s;
color_t c = (e != -1 ? color_index(e) : black);
unsigned char* p = image + (4 * (y * w + x));
p[0] = c.blue;
p[1] = c.green;
p[2] = c.red;
p[3] = 0;
}
return s;
}
// Check if the boundary of a square is in set => interior in set (for
// simple connected sets like Mandelbrot)
void DoCalculation::fillSquare(int x0, int y0, int x1, int y1)
{
// do the square
for (int i = x0 + 1; i < x1; ++i)
{
if (updatePoint(i, y0) != InSet) return;
}
for (int i = x0 + 1; i < x1; ++i)
{
if (updatePoint(i, y1) != InSet) return;
}
for (int i = y0 + 1; i < y1; ++i)
{
if (updatePoint(x0, i) != InSet) return;
}
for (int i = y0 + 1; i < y1; ++i)
{
if (updatePoint(x1, i) != InSet) return;
}
for (int i = y0 + 1; i < y1; ++i)
{
for (int j = x0 + 1; j < x1; ++j)
{
/** @todo Wrong once
if (updatePoint(j,i) != InSet)
std::cout << "ZOMG WRONG" << std::endl;
*/
status[i * w + j] = InSet;
unsigned char* p = image + (4 * (i * w + j));
p[0] = black.blue;
p[1] = black.green;
p[2] = black.red;
p[3] = 0;
}
}
}
void DoCalculation::run()
{
if (!f || !image) return;
/// @todo Refactor into "progressive"
for (int step = std::max(msb(w), msb(h)); step > 0; step /= 2)
{
for (int y = 0; y < h; y += step)
{
for (int x = 0; x < w; x += step)
{
if (updatePoint(x, y) == InSet)
{
// only take this step if f->simplyConnected
if (step > 2 && x > 0 && y > 0 && status[(y-1) * w + (x - 1)] == Untested && status[(y-step)*w+x] == InSet && status[(y-step)*w+(x-step)] == InSet && status[y * w + (x - step)] == InSet)
{
fillSquare(x - step, y - step, x, y);
}
}
}
}
emit ready();
}
}
#if 0
int lsb(int x)
{
if (x == 0) return 0;
int m = 1;
while ((x & m) == 0)
m += m;
return m;
}
#endif
| 18.444444 | 191 | 0.540663 | jlee975 |
35e7eaa22dba72458669bbba5439256339b86e87 | 486 | hpp | C++ | dm-heom/include/heom/git_version.hpp | noma/dm-heom | 85c94f947190064d21bd38544094731113c15412 | [
"BSD-3-Clause"
] | 7 | 2019-07-28T01:02:52.000Z | 2021-11-09T04:01:36.000Z | dm-heom/include/heom/git_version.hpp | noma/dm-heom | 85c94f947190064d21bd38544094731113c15412 | [
"BSD-3-Clause"
] | null | null | null | dm-heom/include/heom/git_version.hpp | noma/dm-heom | 85c94f947190064d21bd38544094731113c15412 | [
"BSD-3-Clause"
] | 2 | 2020-04-04T15:20:30.000Z | 2021-08-24T15:16:40.000Z | // This file is part of DM-HEOM (https://github.com/noma/dm-heom)
//
// Copyright (c) 2015-2019 Matthias Noack, Zuse Institute Berlin
//
// Licensed under the 3-clause BSD License, see accompanying LICENSE,
// CONTRIBUTORS.md, and README.md for further information.
#ifndef git_version_hpp
#define git_version_hpp
#include <ostream>
extern const char GIT_VERSION_STR[];
extern const char GIT_LOCAL_CHANGES_STR[];
void write_git_version(std::ostream& out);
#endif // git_version_hpp | 27 | 69 | 0.76749 | noma |
35e7ed7927b6c3e310ef9e7946d0b4d0f3164841 | 10,599 | hpp | C++ | Source/VkToolbox/InPlaceFunction.hpp | glampert/VulkanDemo | cd9cae2dcbc790bbe6c42f811cb3aee792242ae0 | [
"MIT"
] | null | null | null | Source/VkToolbox/InPlaceFunction.hpp | glampert/VulkanDemo | cd9cae2dcbc790bbe6c42f811cb3aee792242ae0 | [
"MIT"
] | null | null | null | Source/VkToolbox/InPlaceFunction.hpp | glampert/VulkanDemo | cd9cae2dcbc790bbe6c42f811cb3aee792242ae0 | [
"MIT"
] | null | null | null | #pragma once
// ================================================================================================
// File: VkToolbox/InPlaceFunction.hpp
// Author: Guilherme R. Lampert
// Created on: 14/05/17
// Brief: std::function-like functor that has an inline buffer to store the
// callable object. It is guaranteed to never allocate. If the callable is
// too big, a static_assert is triggered. The size of the functor is defined
// as a template argument, so it can be of any size. Doesn't use exceptions.
// ================================================================================================
#include <cstddef>
#include <cstdint>
#include <memory>
#include <utility>
// Configurable, but should be a power of two.
#ifndef INPLACE_FUNCTION_ALIGN
#define INPLACE_FUNCTION_ALIGN 16
#endif // INPLACE_FUNCTION_ALIGN
// Used to trap null function calls. Exceptions are not used.
#ifndef INPLACE_FUNCTION_ASSERT
#include <cassert>
#define INPLACE_FUNCTION_ASSERT(expr, message) assert(expr && message)
#endif // INPLACE_FUNCTION_ASSERT
namespace VkToolbox
{
// ========================================================
// class InPlaceFunctionBase:
// ========================================================
template<int, typename>
class InPlaceFunctionBase; // Unimplemented
template<int SizeInBytes, typename ReturnType, typename... ArgTypes>
class InPlaceFunctionBase<SizeInBytes, ReturnType(ArgTypes...)>
{
private:
struct BaseCallableObject
{
virtual ReturnType invoke(ArgTypes... args) const = 0;
virtual BaseCallableObject * copyConstruct(void * where) const = 0;
virtual BaseCallableObject * moveConstruct(void * where) = 0;
virtual ~BaseCallableObject() = default;
};
template<typename F>
struct CallableObjectImpl final
: public BaseCallableObject
{
F m_fn;
CallableObjectImpl(const F & fn)
: m_fn{ fn }
{ }
CallableObjectImpl(F && fn)
: m_fn{ std::move(fn) }
{ }
ReturnType invoke(ArgTypes... args) const override
{
return m_fn(std::forward<ArgTypes>(args)...);
}
BaseCallableObject * copyConstruct(void * where) const override
{
return ::new(where) CallableObjectImpl<F>{ m_fn };
}
BaseCallableObject * moveConstruct(void * where) override
{
return ::new(where) CallableObjectImpl<F>{ std::move(m_fn) };
}
};
enum Constants
{
kUserAlign = INPLACE_FUNCTION_ALIGN,
kMinAlign = (kUserAlign > alignof(std::max_align_t)) ? kUserAlign : alignof(std::max_align_t),
kMinSize = (sizeof(BaseCallableObject *) + (kMinAlign - 1)) & ~(kMinAlign - 1),
kMaxSize = SizeInBytes - sizeof(BaseCallableObject *),
};
static_assert(SizeInBytes >= kMinSize, "Requested InPlaceFunction size is too small.");
union Storage
{
struct FunctionObject
{
// Space for a lambda capture, etc, minus the reserved callable pointer.
alignas(kMinAlign) std::uint8_t buffer[kMaxSize];
// One pointer worth of memory is taken from the end for the functor pointer.
BaseCallableObject * callablePtr;
} funcObj;
// In case INPLACE_FUNCTION_ALIGN is less than the minimum, don't rely solely on alignas().
std::max_align_t maxAlign;
} m_storage;
protected:
void * placementBuffer()
{
return m_storage.funcObj.buffer;
}
BaseCallableObject * callablePtr() const
{
return m_storage.funcObj.callablePtr;
}
void setCallablePtr(BaseCallableObject * callable)
{
m_storage.funcObj.callablePtr = callable;
}
template<typename F> void placeFunctionObject(F && fn)
{
static_assert(sizeof(CallableObjectImpl<F>) <= kMaxSize, "Function object too big to fit in InPlaceFunction! Use a bigger size.");
CallableObjectImpl<F> temp{ std::move(fn) };
setCallablePtr(temp.moveConstruct(placementBuffer()));
}
void placeMove(InPlaceFunctionBase * other)
{
BaseCallableObject * otherCallable = other->callablePtr();
if (otherCallable != nullptr)
{
setCallablePtr(otherCallable->moveConstruct(placementBuffer()));
other->setCallablePtr(nullptr);
}
}
void placeCopy(const InPlaceFunctionBase & other)
{
const BaseCallableObject * otherCallable = other.callablePtr();
if (otherCallable != nullptr)
{
setCallablePtr(otherCallable->copyConstruct(placementBuffer()));
}
}
void destroy()
{
BaseCallableObject * myCallable = callablePtr();
if (myCallable != nullptr)
{
myCallable->~BaseCallableObject();
setCallablePtr(nullptr);
}
}
public:
InPlaceFunctionBase()
{
setCallablePtr(nullptr);
}
~InPlaceFunctionBase()
{
destroy();
}
bool isNull() const
{
return callablePtr() == nullptr;
}
ReturnType operator()(ArgTypes... args) const
{
INPLACE_FUNCTION_ASSERT(!isNull(), "Invalid InPlaceFunction call!");
return callablePtr()->invoke(std::forward<ArgTypes>(args)...);
}
};
// ========================================================
// class InPlaceFunction:
// ========================================================
template<int SizeInBytes, typename FuncType>
class InPlaceFunction final
: public InPlaceFunctionBase<SizeInBytes, FuncType>
{
public:
//
// Constructors:
//
InPlaceFunction() = default;
InPlaceFunction(std::nullptr_t) { } // Implicitly null.
InPlaceFunction(InPlaceFunction && other)
{
placeMove(&other);
}
InPlaceFunction(const InPlaceFunction & other)
{
placeCopy(other);
}
template<typename F> InPlaceFunction(F fn)
{
placeFunctionObject(std::move(fn));
}
//
// Assignment:
//
InPlaceFunction & operator = (std::nullptr_t)
{
destroy();
return *this;
}
InPlaceFunction & operator = (InPlaceFunction && other)
{
destroy();
placeMove(&other);
return *this;
}
InPlaceFunction & operator = (const InPlaceFunction & other)
{
destroy();
placeCopy(other);
return *this;
}
template<typename F> InPlaceFunction & operator = (F fn)
{
destroy();
placeFunctionObject(std::move(fn));
return *this;
}
//
// Null pointer comparison:
//
explicit operator bool() const
{
return !isNull();
}
bool operator == (std::nullptr_t) const
{
return isNull();
}
bool operator != (std::nullptr_t) const
{
return !isNull();
}
// Disallow copying or assigning from a function of different size.
template<int OtherSize> InPlaceFunction(const InPlaceFunction<OtherSize, FuncType> &) = delete;
template<int OtherSize> InPlaceFunction & operator = (const InPlaceFunction<OtherSize, FuncType> &) = delete;
};
// ========================================================
// Aliases for common sizes:
// ========================================================
template<typename F> using InPlaceFunction32 = InPlaceFunction< 32, F>;
template<typename F> using InPlaceFunction64 = InPlaceFunction< 64, F>;
template<typename F> using InPlaceFunction128 = InPlaceFunction<128, F>;
template<typename F> using InPlaceFunction256 = InPlaceFunction<256, F>;
template<typename F> using InPlaceFunction512 = InPlaceFunction<512, F>;
static_assert(sizeof(InPlaceFunction32<void()>) == 32, "Wrong size for InPlaceFunction32");
static_assert(sizeof(InPlaceFunction64<void()>) == 64, "Wrong size for InPlaceFunction64");
static_assert(sizeof(InPlaceFunction128<void()>) == 128, "Wrong size for InPlaceFunction128");
static_assert(sizeof(InPlaceFunction256<void()>) == 256, "Wrong size for InPlaceFunction256");
static_assert(sizeof(InPlaceFunction512<void()>) == 512, "Wrong size for InPlaceFunction512");
// ========================================================
// class MemberFunctionHolder:
// ========================================================
//
// Allows easily creating an InPlaceFunction from a
// pointer to an object and class member function.
// Use the provided makeInPlaceFunctionFromMember()
// functions to create the wrappers. The function
// type returned will be an InPlaceFunction32. No
// additional memory allocated. Example:
//
// MyClass obj{};
// auto memFun = makeInPlaceFunctionFromMember(&obj, &MyClass::someMethod);
// memFun(); // calls obj->someMethod();
//
template<typename ClassType, typename ReturnType, typename... ArgTypes>
class MemberFunctionHolder final
{
public:
// This selector will use the const-qualified method if
// ClassType is const, the non-const one otherwise.
using MMemFunc = ReturnType (ClassType::*)(ArgTypes...);
using CMemFunc = ReturnType (ClassType::*)(ArgTypes...) const;
using MemFuncType = typename std::conditional<std::is_const<ClassType>::value, CMemFunc, MMemFunc>::type;
MemberFunctionHolder(ClassType * obj, MemFuncType pmf)
: m_pObject(obj), m_pMemFun(pmf)
{
INPLACE_FUNCTION_ASSERT(m_pObject != nullptr, "Null this pointer!");
INPLACE_FUNCTION_ASSERT(m_pMemFun != nullptr, "Null member pointer!");
}
ReturnType operator()(ArgTypes... args) const
{
return (m_pObject->*m_pMemFun)(std::forward<ArgTypes>(args)...);
}
private:
ClassType * m_pObject;
MemFuncType m_pMemFun;
};
// ========================================================
template<typename ClassType, typename ReturnType, typename... ArgTypes>
inline InPlaceFunction32<ReturnType(ArgTypes...)>
makeInPlaceFunctionFromMember(ClassType * obj, ReturnType (ClassType::*pmf)(ArgTypes...))
{
return InPlaceFunction32<ReturnType(ArgTypes...)>(
MemberFunctionHolder<ClassType, ReturnType, ArgTypes...>(obj, pmf));
}
template<typename ClassType, typename ReturnType, typename... ArgTypes>
inline InPlaceFunction32<ReturnType(ArgTypes...)>
makeInPlaceFunctionFromMember(const ClassType * obj, ReturnType (ClassType::*pmf)(ArgTypes...) const)
{
return InPlaceFunction32<ReturnType(ArgTypes...)>(
MemberFunctionHolder<const ClassType, ReturnType, ArgTypes...>(obj, pmf));
}
// ========================================================
} // namespace VkToolbox
| 31.544643 | 138 | 0.613171 | glampert |
e302f7119a7ac9cd4ba9831fbed09bf23cb41dd3 | 1,237 | cpp | C++ | includes/graph.cpp | AnthonyN1/Advent-of-Code | 28782b219a50d92b2621dc88ecf00ae2e3b45b0a | [
"MIT"
] | null | null | null | includes/graph.cpp | AnthonyN1/Advent-of-Code | 28782b219a50d92b2621dc88ecf00ae2e3b45b0a | [
"MIT"
] | null | null | null | includes/graph.cpp | AnthonyN1/Advent-of-Code | 28782b219a50d92b2621dc88ecf00ae2e3b45b0a | [
"MIT"
] | null | null | null | /*
Advent of Code - Graph Implementation
Author: Anthony Nool (AnthonyN1)
*/
#include <map>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "graph.h"
//==================================================//
// Observer //
//==================================================//
/*
Returns a vector of all the vertices in the graph.
*/
std::vector<std::string> Graph::getVertices() const {
std::vector<std::string> verts;
std::map<std::string, std::set<std::string>>::const_iterator itr;
for(itr = adjList_.cbegin(); itr != adjList_.cend(); ++itr)
verts.push_back(itr->first);
return verts;
}
//==================================================//
// Mutators //
//==================================================//
/*
Adds an edge between v1 and v2 with weight weight to the graph.
*/
void Graph::addEdge(const std::string &v1, const std::string &v2, long long weight){
adjList_[v1].insert(v2);
weights_[std::make_pair(v1, v2)] = weight;
}
/*
Adds a vertex v to the graph.
*/
void Graph::addVertex(const std::string &v){
if(adjList_.find(v) == adjList_.end())
adjList_[v] = std::set<std::string>();
}
| 24.74 | 84 | 0.510105 | AnthonyN1 |
e31480b7cabea3e7798bf1bdc6fa7e89f116e6dc | 1,736 | cpp | C++ | src/MCP23S17.cpp | tobiasjaster/MCP23X17 | 853fb9ff73e0d9d484c8eb67829802e1505f2fcc | [
"BSD-3-Clause"
] | null | null | null | src/MCP23S17.cpp | tobiasjaster/MCP23X17 | 853fb9ff73e0d9d484c8eb67829802e1505f2fcc | [
"BSD-3-Clause"
] | null | null | null | src/MCP23S17.cpp | tobiasjaster/MCP23X17 | 853fb9ff73e0d9d484c8eb67829802e1505f2fcc | [
"BSD-3-Clause"
] | null | null | null | #include "MCP23S17.h"
MCP23S17::MCP23S17(uint8_t address, uint8_t chipSelect) : MCP23X17() {
_deviceAddr = address;
_cs = chipSelect;
pinMode(_cs, OUTPUT);
digitalWrite(_cs, HIGH);
_bus = &SPI;
}
MCP23S17::MCP23S17(uint8_t address, uint8_t chipSelect, SPIClass *bus) : MCP23X17() {
_deviceAddr = address;
_cs = chipSelect;
pinMode(_cs, OUTPUT);
digitalWrite(_cs, HIGH);
_bus = bus;
}
MCP23S17::~MCP23S17() {}
void MCP23S17::writeRegister(MCP23X17Register reg, uint8_t value)
{
uint8_t cmd = 0x40 | ((_deviceAddr & 0b111) << 1);
digitalWrite(_cs, LOW);
_bus->transfer(cmd);
_bus->transfer(static_cast<uint8_t>(reg));
_bus->transfer(value);
digitalWrite(_cs, HIGH);
}
void MCP23S17::writeRegister(MCP23X17Register reg, uint8_t portA, uint8_t portB)
{
uint8_t cmd = 0x40 | ((_deviceAddr & 0b111) << 1);
digitalWrite(_cs, LOW);
_bus->transfer(cmd);
_bus->transfer(static_cast<uint8_t>(reg));
_bus->transfer(portA);
_bus->transfer(portB);
digitalWrite(_cs, HIGH);
}
uint8_t MCP23S17::readRegister(MCP23X17Register reg)
{
uint8_t cmd = 0x41 | ((_deviceAddr & 0b111) << 1);
digitalWrite(_cs, LOW);
_bus->transfer(cmd);
_bus->transfer(static_cast<uint8_t>(reg));
uint8_t value = _bus->transfer(0xFF);
digitalWrite(_cs, HIGH);
return value;
}
void MCP23S17::readRegister(MCP23X17Register reg, uint8_t& portA, uint8_t& portB)
{
uint8_t cmd = 0x41 | ((_deviceAddr & 0b111) << 1);
digitalWrite(_cs, LOW);
_bus->transfer(cmd);
_bus->transfer(static_cast<uint8_t>(reg));
portA = _bus->transfer(0xFF);
portB = _bus->transfer(0xFF);
digitalWrite(_cs, HIGH);
} | 27.555556 | 86 | 0.652074 | tobiasjaster |
e3190cc1c3666f4e7dc0a6cba874f20501fbc199 | 832 | hh | C++ | src/Utilities/planarReflectingOperator.hh | jmikeowen/Spheral | 3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 22 | 2018-07-31T21:38:22.000Z | 2020-06-29T08:58:33.000Z | src/Utilities/planarReflectingOperator.hh | markguozhiming/spheral | bbb982102e61edb8a1d00cf780bfa571835e1b61 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 41 | 2020-09-28T23:14:27.000Z | 2022-03-28T17:01:33.000Z | src/Utilities/planarReflectingOperator.hh | markguozhiming/spheral | bbb982102e61edb8a1d00cf780bfa571835e1b61 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 7 | 2019-12-01T07:00:06.000Z | 2020-09-15T21:12:39.000Z | //---------------------------------Spheral++----------------------------------//
// planarReflectingOperator
// Generate the reflection operator for the given plane.
//
// Created by JMO, Wed Feb 16 21:01:02 PST 2000
//----------------------------------------------------------------------------//
#ifndef __Spheral_planarReflectingOperator__
#define __Spheral_planarReflectingOperator__
#include "Geometry/GeomPlane.hh"
namespace Spheral {
template<typename Dimension>
inline
typename Dimension::Tensor
planarReflectingOperator(const typename Dimension::Vector& nhat) {
return Dimension::Tensor::one - 2.0*nhat.selfdyad();
}
template<typename Dimension>
inline
typename Dimension::Tensor
planarReflectingOperator(const GeomPlane<Dimension>& plane) {
return planarReflectingOperator<Dimension>(plane.normal());
}
}
#endif
| 26.83871 | 80 | 0.653846 | jmikeowen |
e31f630b614766efb76a14c72746594f0b6be709 | 1,463 | cpp | C++ | cpp/leetcode/13.roman-to-integer.cpp | Gerrard-YNWA/piece_of_code | ea8c9f05a453c893cc1f10e9b91d4393838670c1 | [
"MIT"
] | 1 | 2021-11-02T05:17:24.000Z | 2021-11-02T05:17:24.000Z | cpp/leetcode/13.roman-to-integer.cpp | Gerrard-YNWA/code | 546230593c33ff322d3205499fe17cd6a9a437c1 | [
"MIT"
] | null | null | null | cpp/leetcode/13.roman-to-integer.cpp | Gerrard-YNWA/code | 546230593c33ff322d3205499fe17cd6a9a437c1 | [
"MIT"
] | null | null | null | /*
* @lc app=leetcode id=13 lang=cpp
*
* [13] Roman to Integer
*/
#include<iostream>
#include<string>
using namespace std;
// @lc code=start
class Solution {
public:
int romanToInt(string s) {
auto len = s.length();
if (len == 1) {
return charToNumber(s[0]);
}
int sum = 0;
int cur, next;
for (auto i = 0; i < len - 1; i++){
cur = charToNumber(s[i]);
next = charToNumber(s[i+1]);
if (cur < next) {
sum = sum - cur;
} else {
sum = sum + cur;
}
}
sum = sum + next;
return sum;
}
private:
int charToNumber(char c) {
switch(c) {
case 'I': return 1;
break;
case 'V': return 5;
break;
case 'X': return 10;
break;
case 'L': return 50;
break;
case 'C': return 100;
break;
case 'D': return 500;
break;
case 'M': return 1000;
break;
default: return 0;
}
}
};
// @lc code=end
int main() {
Solution s;
cout<<s.romanToInt("III")<<endl;
cout<<s.romanToInt("IV")<<endl;
cout<<s.romanToInt("IX")<<endl;
cout<<s.romanToInt("LVIII")<<endl;
cout<<s.romanToInt("MCMXCIV")<<endl;
return 0;
}
| 22.859375 | 43 | 0.420369 | Gerrard-YNWA |
e32128124cae61f0afd671e4df899c964284ba42 | 1,423 | cpp | C++ | libRay/Shaders/NormalVizBump.cpp | RA-Kooi/Ray-Tracer | 8a4f133c1a7cc479f9f33819eb200d5a3ffa48d0 | [
"MIT"
] | 3 | 2019-03-22T02:15:18.000Z | 2019-11-12T08:12:57.000Z | libRay/Shaders/NormalVizBump.cpp | RA-Kooi/Ray-Tracer | 8a4f133c1a7cc479f9f33819eb200d5a3ffa48d0 | [
"MIT"
] | null | null | null | libRay/Shaders/NormalVizBump.cpp | RA-Kooi/Ray-Tracer | 8a4f133c1a7cc479f9f33819eb200d5a3ffa48d0 | [
"MIT"
] | null | null | null | #include "NormalVizBump.hpp"
#include <algorithm>
#include "../Material/Color.hpp"
#include "../Math/MathUtils.hpp"
#include "../Shapes/Shape.hpp"
#include "../Intersection.hpp"
#include "../Light.hpp"
namespace LibRay
{
using namespace Materials;
using namespace Math;
using namespace Shapes;
Color NormalVizShaderBump::Run(
Intersection const &intersection,
Vector3 const &,
Ray const &,
std::vector<Observer<Light const>> const &,
Color const &,
float) const
{
Shape const &shape = *intersection.shape;
Material const &material = shape.Material();
// N'u,v = N + (Bu,v - Bu-1,v)t + (Bu,v - Bu,v-1)b;
Vector3 const &baseNormal = intersection.surfaceNormal;
Vector3 const &tangent = intersection.surfaceTangent;
Vector3 const biTangent = glm::cross(baseNormal, tangent);
Vector2 const &uv = intersection.uv;
Texture const &bumpMap = material.TexturePropertyByName("bump map");
Vector3 const bumpUV = bumpMap.Sample(uv.x, uv.y);
Vector3 const bumpUMinusOne = bumpMap.Sample(uv.x - 1.f, uv.y);
Vector3 const bumpVMinusOne = bumpMap.Sample(uv.x, uv.y - 1.f);
float const bumpStrength = material.FloatPropertyByName("bump strength");
Vector3 const normal = glm::normalize(
baseNormal * bumpStrength
+ (bumpUV - bumpUMinusOne) * tangent
+ (bumpUV - bumpVMinusOne) * biTangent);
Vector3 const col = (0.5f * normal) + Vector3(0.5f);
return Color(col.x, col.y, col.z);
}
} // namespace LibRay
| 27.901961 | 74 | 0.718201 | RA-Kooi |
e32949fc823f62dba3a8aed367af9ed8924dbd1a | 461 | hpp | C++ | num_t.hpp | kensmith/mancalc | db0c2d15811f0da76689ec3c3cc94d9d56d1612d | [
"BSL-1.0"
] | 1 | 2020-03-24T22:51:38.000Z | 2020-03-24T22:51:38.000Z | num_t.hpp | kensmith/mancalc | db0c2d15811f0da76689ec3c3cc94d9d56d1612d | [
"BSL-1.0"
] | null | null | null | num_t.hpp | kensmith/mancalc | db0c2d15811f0da76689ec3c3cc94d9d56d1612d | [
"BSL-1.0"
] | null | null | null | #ifndef __num_t_hpp__
#define __num_t_hpp__
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/multiprecision/cpp_int.hpp>
using int_t = boost::multiprecision::number
<
boost::multiprecision::cpp_int_backend<>,
boost::multiprecision::expression_template_option::et_off
>;
using num_t = boost::multiprecision::number
<
boost::multiprecision::cpp_dec_float<1024>,
boost::multiprecision::expression_template_option::et_off
>;
#endif
| 23.05 | 60 | 0.787419 | kensmith |
e32b5a14be51c0f0a0e105c03ef1f5137163d550 | 2,516 | hpp | C++ | include/omw/array.hpp | vtavernier/omw | 3f598496c8564ea7ad1878f29c48f0e949ef0dd9 | [
"Unlicense",
"MIT"
] | null | null | null | include/omw/array.hpp | vtavernier/omw | 3f598496c8564ea7ad1878f29c48f0e949ef0dd9 | [
"Unlicense",
"MIT"
] | null | null | null | include/omw/array.hpp | vtavernier/omw | 3f598496c8564ea7ad1878f29c48f0e949ef0dd9 | [
"Unlicense",
"MIT"
] | null | null | null | /**
* @file omw/array.hpp
* @brief Definition of omw::array
* @author Vincent TAVERNIER <vincent.tavernier@inria.fr>
* @date 2018
*/
#ifndef _OMW_ARRAY_HPP_
#define _OMW_ARRAY_HPP_
#include <memory>
#include <vector>
#include "omw/pre.hpp"
namespace omw
{
/**
* @brief Represents a 1D array without managing its memory, to be used with Octave
* and Mathematica APIs.
*/
template <typename T> class basic_array
{
public:
/**
* @brief Base class destructor
*/
virtual ~basic_array()
{}
/**
* @brief Pointer to the array data.
*
* @return Pointer to the underlying memory block
*/
virtual const T *data() const = 0;
/**
* @brief Accesses an element by index.
*
* @param idx 0-based index of the element in the array
* @return Reference to the element at the given index
*/
virtual const T &operator[](std::size_t idx) const = 0;
/**
* @brief Obtains the size of the array.
*
* @return Number of elements in the array
*/
virtual std::size_t size() const = 0;
};
/**
* @brief Represents a 1D array backed by a vector.
*/
template <typename T> class vector_array : public basic_array<T>
{
std::vector<T> m_container;
public:
/**
* @brief Pointer to the array data.
*
* @return Pointer to the underlying memory block
*/
const T *data() const override { return m_container.data(); }
/**
* @brief Accesses an element by index.
*
* @param idx 0-based index of the element in the array
* @return Reference to the element at the given index
*/
const T &operator[](std::size_t idx) const override { return m_container[idx]; }
/**
* @brief Obtains the size of the array.
*
* @return Number of elements in the array
*/
std::size_t size() const override { return m_container.size(); }
/**
* @brief Initializes a new instance of the omw::vector_array class.
*
* @param v Vector that holds the contents of the array
*/
vector_array(const std::vector<T> &v) : m_container(v) {}
/**
* @brief Builds an omw::vector_array <T> from a std::vector <T>.
*
* @tparam Args Type of the arguments to forward to the std::vector<T> constructor
* @param args Arguments to forward to the std::vector<T> constructor
* @return Shared pointer to the newly allocated omw::array
*/
template <typename... Args> static std::shared_ptr<basic_array<T>> make(Args&&... args)
{
return std::make_shared<vector_array<T>>(std::vector<T>(std::forward<Args>(args)...));
}
};
}
#endif /* _OMW_ARRAY_HPP_ */
| 23.735849 | 89 | 0.669714 | vtavernier |
e32d2f9a73b14d38860897ed8c8ce95550f0fbb0 | 373 | hpp | C++ | wield/tests/acceptance_test/queue_stress/queue_stress/ProcessingFunctorBase.hpp | paxos1977/wield | a4e4c2df28763d2a720e14b3d6e903b083eb3a7d | [
"BSD-4-Clause"
] | null | null | null | wield/tests/acceptance_test/queue_stress/queue_stress/ProcessingFunctorBase.hpp | paxos1977/wield | a4e4c2df28763d2a720e14b3d6e903b083eb3a7d | [
"BSD-4-Clause"
] | null | null | null | wield/tests/acceptance_test/queue_stress/queue_stress/ProcessingFunctorBase.hpp | paxos1977/wield | a4e4c2df28763d2a720e14b3d6e903b083eb3a7d | [
"BSD-4-Clause"
] | null | null | null | #pragma once
#include <queue_stress/Message.hpp>
namespace queue_stress { namespace message {
class TestMessage;
}}
namespace queue_stress {
class ProcessingFunctorBase
{
public:
virtual ~ProcessingFunctorBase(){}
virtual void operator()(Message&){}
virtual void operator()(message::TestMessage&){}
};
}
| 18.65 | 57 | 0.632708 | paxos1977 |
e32eaab1db8757d11e8c2ba915e8eda90c3ea6a4 | 11,698 | cc | C++ | dcmdata/apps/dcm2json.cc | palmerc/dcmtk | 716832be091d138f3e119c47a4e1e243f5b261d3 | [
"Apache-2.0"
] | null | null | null | dcmdata/apps/dcm2json.cc | palmerc/dcmtk | 716832be091d138f3e119c47a4e1e243f5b261d3 | [
"Apache-2.0"
] | null | null | null | dcmdata/apps/dcm2json.cc | palmerc/dcmtk | 716832be091d138f3e119c47a4e1e243f5b261d3 | [
"Apache-2.0"
] | null | null | null | /*
*
* Copyright (C) 2016, OFFIS e.V.
* All rights reserved. See COPYRIGHT file for details.
*
* This software and supporting documentation were developed by
*
* OFFIS e.V.
* R&D Division Health
* Escherweg 2
* D-26121 Oldenburg, Germany
*
*
* Module: dcmdata
*
* Author: Sebastian Grallert
*
* Purpose: Convert the contents of a DICOM file to JSON format
*
*/
#include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */
#include "dcmtk/dcmdata/dctk.h"
#include "dcmtk/dcmdata/cmdlnarg.h"
#include "dcmtk/dcmdata/dcjson.h"
#include "dcmtk/ofstd/ofstream.h"
#include "dcmtk/ofstd/ofconapp.h"
#ifdef WITH_ZLIB
#include <zlib.h> /* for zlibVersion() */
#endif
#ifdef DCMTK_ENABLE_CHARSET_CONVERSION
#include "dcmtk/ofstd/ofchrenc.h" /* for OFCharacterEncoding */
#endif
#define OFFIS_CONSOLE_APPLICATION "dcm2json"
#define OFFIS_CONSOLE_DESCRIPTION "Convert DICOM file and data set to JSON"
static OFLogger dcm2jsonLogger = OFLog::getLogger("dcmtk.apps." OFFIS_CONSOLE_APPLICATION);
static char rcsid[] = "$dcmtk: " OFFIS_CONSOLE_APPLICATION " v"
OFFIS_DCMTK_VERSION " " OFFIS_DCMTK_RELEASEDATE " $";
// ********************************************
/* Function to call all writeJson() functions in DCMTK */
static OFCondition writeFile(STD_NAMESPACE ostream &out,
const char *ifname,
DcmFileFormat *dfile,
const E_FileReadMode readMode,
const OFBool loadIntoMemory,
const OFBool format,
const OFBool printMetaheaderInformation,
const OFBool checkAllStrings)
{
OFCondition result = EC_IllegalParameter;
if ((ifname != NULL) && (dfile != NULL))
{
DcmDataset *dset = dfile->getDataset();
if (loadIntoMemory)
dset->loadAllDataIntoMemory();
/* write JSON document content */
if (readMode == ERM_dataset)
{
result = format
?
dset->writeJson(out, DcmJsonFormatPretty(printMetaheaderInformation))
:
dset->writeJson(out, DcmJsonFormatCompact(printMetaheaderInformation))
;
}
else
{
result = format
?
dfile->writeJson(out, DcmJsonFormatPretty(printMetaheaderInformation))
:
dfile->writeJson(out, DcmJsonFormatCompact(printMetaheaderInformation))
;
}
}
return result;
}
#define SHORTCOL 3
#define LONGCOL 20
int main(int argc, char *argv[])
{
OFBool opt_loadIntoMemory = OFFalse;
OFBool opt_checkAllStrings = OFFalse;
OFBool opt_format = OFTrue;
OFBool opt_addMetaInformation = OFFalse;
E_FileReadMode opt_readMode = ERM_autoDetect;
E_TransferSyntax opt_ixfer = EXS_Unknown;
OFCmdUnsignedInt opt_maxReadLength = 4096; // default is 4 KB
OFString optStr;
OFConsoleApplication app(OFFIS_CONSOLE_APPLICATION, OFFIS_CONSOLE_DESCRIPTION, rcsid);
OFCommandLine cmd;
cmd.setOptionColumns(LONGCOL, SHORTCOL);
cmd.setParamColumn(LONGCOL + SHORTCOL + 4);
cmd.addParam("dcmfile-in", "DICOM input filename to be converted", OFCmdParam::PM_Mandatory);
cmd.addParam("jsonfile-out", "JSON output filename (default: stdout)", OFCmdParam::PM_Optional);
cmd.addGroup("general options:", LONGCOL, SHORTCOL + 2);
cmd.addOption("--help", "-h", "print this help text and exit", OFCommandLine::AF_Exclusive);
cmd.addOption("--version", "print version information and exit", OFCommandLine::AF_Exclusive);
OFLog::addOptions(cmd);
cmd.addGroup("input options:");
cmd.addSubGroup("input file format:");
cmd.addOption("--read-file", "+f", "read file format or data set (default)");
cmd.addOption("--read-file-only", "+fo", "read file format only");
cmd.addOption("--read-dataset", "-f", "read data set without file meta information");
cmd.addSubGroup("input transfer syntax:");
cmd.addOption("--read-xfer-auto", "-t=", "use TS recognition (default)");
cmd.addOption("--read-xfer-detect", "-td", "ignore TS specified in the file meta header");
cmd.addOption("--read-xfer-little", "-te", "read with explicit VR little endian TS");
cmd.addOption("--read-xfer-big", "-tb", "read with explicit VR big endian TS");
cmd.addOption("--read-xfer-implicit", "-ti", "read with implicit VR little endian TS");
cmd.addSubGroup("long tag values:") ;
cmd.addOption("--load-all", "+M", "load very long tag values (e.g. pixel data)");
cmd.addOption("--load-short", "-M", "do not load very long values (default)");
cmd.addOption("--max-read-length", "+R", 1, "[k]bytes: integer (4..4194302, default: 4)",
"set threshold for long values to k kbytes");
cmd.addGroup("output options:");
cmd.addSubGroup("output format:");
cmd.addOption("--formatted-code", "+fc", "output file with human readable formatting (def.)");
cmd.addOption("--compact-code", "-fc", "output without formatting (single line of code)");
cmd.addOption("--write-meta", "+m", "write data set with meta information");
/* evaluate command line */
prepareCmdLineArgs(argc, argv, OFFIS_CONSOLE_APPLICATION);
if (app.parseCommandLine(cmd, argc, argv))
{
/* check exclusive options first */
if (cmd.hasExclusiveOption())
{
if (cmd.findOption("--version"))
{
app.printHeader(OFTrue /*print host identifier*/);
COUT << OFendl << "External libraries used:";
#if !defined(WITH_ZLIB) && !defined(DCMTK_ENABLE_CHARSET_CONVERSION)
COUT << " none" << OFendl;
#else
COUT << OFendl;
#endif
#ifdef WITH_ZLIB
COUT << "- ZLIB, Version " << zlibVersion() << OFendl;
#endif
#ifdef DCMTK_ENABLE_CHARSET_CONVERSION
COUT << "- " << OFCharacterEncoding::getLibraryVersionString() << OFendl;
#endif
return 0;
}
}
/* general options */
OFLog::configureFromCommandLine(cmd, app);
/* input options */
cmd.beginOptionBlock();
if (cmd.findOption("--read-file")) opt_readMode = ERM_autoDetect;
if (cmd.findOption("--read-file-only")) opt_readMode = ERM_fileOnly;
if (cmd.findOption("--read-dataset")) opt_readMode = ERM_dataset;
cmd.endOptionBlock();
cmd.beginOptionBlock();
if (cmd.findOption("--read-xfer-auto"))
opt_ixfer = EXS_Unknown;
if (cmd.findOption("--read-xfer-detect"))
dcmAutoDetectDatasetXfer.set(OFTrue);
if (cmd.findOption("--read-xfer-little"))
{
app.checkDependence("--read-xfer-little", "--read-dataset", opt_readMode == ERM_dataset);
opt_ixfer = EXS_LittleEndianExplicit;
}
if (cmd.findOption("--read-xfer-big"))
{
app.checkDependence("--read-xfer-big", "--read-dataset", opt_readMode == ERM_dataset);
opt_ixfer = EXS_BigEndianExplicit;
}
if (cmd.findOption("--read-xfer-implicit"))
{
app.checkDependence("--read-xfer-implicit", "--read-dataset", opt_readMode == ERM_dataset);
opt_ixfer = EXS_LittleEndianImplicit;
}
cmd.endOptionBlock();
if (cmd.findOption("--max-read-length"))
{
app.checkValue(cmd.getValueAndCheckMinMax(opt_maxReadLength, 4, 4194302));
opt_maxReadLength *= 1024; // convert kbytes to bytes
}
cmd.beginOptionBlock();
if (cmd.findOption("--load-all"))
opt_loadIntoMemory = OFTrue;
if (cmd.findOption("--load-short"))
opt_loadIntoMemory = OFFalse;
cmd.endOptionBlock();
/* format options */
cmd.beginOptionBlock();
if (cmd.findOption("--formatted-code"))
opt_format = OFTrue;
if (cmd.findOption("--compact-code"))
opt_format = OFFalse;
cmd.endOptionBlock();
/* meta option */
cmd.beginOptionBlock();
if (cmd.findOption("--write-meta"))
opt_addMetaInformation = OFTrue;
cmd.endOptionBlock();
}
/* print resource identifier */
OFLOG_DEBUG(dcm2jsonLogger, rcsid << OFendl);
/* make sure data dictionary is loaded */
if (!dcmDataDict.isDictionaryLoaded())
{
OFLOG_WARN(dcm2jsonLogger, "no data dictionary loaded, check environment variable: "
<< DCM_DICT_ENVIRONMENT_VARIABLE);
}
int result = 0;
/* first parameter is treated as the input filename */
const char *ifname = NULL;
cmd.getParam(1, ifname);
/* check input file */
if ((ifname != NULL) && (strlen(ifname) > 0))
{
/* read DICOM file or data set */
DcmFileFormat dfile;
OFCondition status = dfile.loadFile(ifname, opt_ixfer, EGL_noChange, OFstatic_cast(Uint32, opt_maxReadLength), opt_readMode);
if (status.good())
{
DcmDataset *dset = dfile.getDataset();
OFString csetString;
if (dset->findAndGetOFStringArray(DCM_SpecificCharacterSet, csetString).good())
{
if (csetString.compare("ISO_IR 192") != 0 && csetString.compare("ISO_IR 6") != 0)
{
#ifdef DCMTK_ENABLE_CHARSET_CONVERSION
/* convert all DICOM strings to UTF-8 */
OFLOG_INFO(dcm2jsonLogger, "converting all element values that are affected by SpecificCharacterSet (0008,0005) to UTF-8");
status = dset->convertToUTF8();
if (status.bad())
{
OFLOG_FATAL(dcm2jsonLogger, status.text() << ": converting file to UTF-8: " << ifname);
result = 4;
}
#else
OFLOG_FATAL(dcm2jsonLogger, "character set conversion not available");
return 4;
#endif
}
}
if (result == 0)
{
/* if second parameter is present, it is treated as the output filename ("stdout" otherwise) */
if (cmd.getParamCount() == 2)
{
const char *ofname = NULL;
cmd.getParam(2, ofname);
STD_NAMESPACE ofstream stream(ofname);
if (stream.good())
{
/* write content in JSON format to file */
if (writeFile(stream, ifname, &dfile, opt_readMode, opt_loadIntoMemory,
opt_format, opt_addMetaInformation, opt_checkAllStrings).bad())
result = 2;
}
else
result = 1;
}
else
{
/* write content in JSON format to standard output */
if (writeFile(COUT, ifname, &dfile, opt_readMode, opt_loadIntoMemory,
opt_format, opt_addMetaInformation, opt_checkAllStrings).bad())
result = 3;
}
}
}
else
OFLOG_ERROR(dcm2jsonLogger, OFFIS_CONSOLE_APPLICATION << ": error (" << status.text() << ") reading file: " << ifname);
}
else
OFLOG_ERROR(dcm2jsonLogger, OFFIS_CONSOLE_APPLICATION << ": invalid filename: <empty string>");
return result;
}
| 38.735099 | 143 | 0.583091 | palmerc |
e32eaf89bb21afb619ffde0fd81dd73a7ce17673 | 14,894 | cpp | C++ | src/acFindWidget.cpp | nfogh/common-src-AMDTApplicationComponents | 9fc0fa073b8af5d8552eb331fc47ede8becca642 | [
"MIT"
] | 1 | 2017-01-28T14:14:18.000Z | 2017-01-28T14:14:18.000Z | src/acFindWidget.cpp | nfogh/common-src-AMDTApplicationComponents | 9fc0fa073b8af5d8552eb331fc47ede8becca642 | [
"MIT"
] | null | null | null | src/acFindWidget.cpp | nfogh/common-src-AMDTApplicationComponents | 9fc0fa073b8af5d8552eb331fc47ede8becca642 | [
"MIT"
] | 2 | 2018-10-26T09:34:00.000Z | 2019-11-01T23:05:53.000Z | //==================================================================================
// Copyright (c) 2016 , Advanced Micro Devices, Inc. All rights reserved.
//
/// \author AMD Developer Tools Team
/// \file acFindWidget.cpp
///
//==================================================================================
// Infra:
#include <AMDTBaseTools/Include/gtAssert.h>
// Local:
#include <AMDTApplicationComponents/Include/acFindWidget.h>
#include <AMDTApplicationComponents/Include/acFunctions.h>
#include <AMDTApplicationComponents/inc/acStringConstants.h>
#define AC_FIND_PUSH_BUTTON_WIDTH 24
#define AC_STR_FindWidgetPushButtonStyle "QPushButton:hover {border: 1px solid gray; } QPushButton{border: 1px solid #B4B4B4; }"
#define AC_STR_FindWidgetPrevNextButtonsStyle "QPushButton:hover { "\
"border: 1px solid gray;"\
"border-style: inset;" \
"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 white, stop: 1 rgba(255,255,207,255));margin-top: 2px;" \
"}"\
"QPushButton { "\
"border: 1px solid gray;"\
"background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 white, stop: 1 rgba(255,255,207,255));" \
"background-color:rgba(255,255,207,255);margin-top: 2px;"\
"}"
#define AC_STR_FindWidgetPushButtonRadiusRight "QPushButton:hover { border-bottom-right-radius:2px; border-top-right-radius:2px; }" \
"QPushButton{ border-bottom-right-radius:2px; border-top-right-radius:2px; }"
#define AC_STR_FindWidgetPushButtonStyleNoBorder "QPushButton:hover {border: 1px solid gray; border-radius:2px;margin-top: 2px;} QPushButton{border: none;margin-top: 2px;}"
#define AC_STR_FindWidgetToolBarStyle "QToolBar { border-top: 2px solid #B9B9B9; border-bottom: 1px solid #B9B9B9; border-style: outset;}"
#define AC_STR_FindWidgetTextWidgetStyle "QWidget { background-color:rgba(255,255,207,255); border: 1px solid gray; border-right:none; border-top-left-radius:2px;border-bottom-left-radius:2px; border-style: inset; margin-top: 2px;}"
#define AC_STR_FindWidgetTextWidgetStyleNoResults "QWidget { background-color:rgba(255,255,207,255); border: 1px solid red; border-right:none; border-top-left-radius:2px;border-bottom-left-radius:2px; border-style: inset; margin-top: 2px;}"
#define AC_STR_FindWidgetLineEditStyle "QLineEdit {border-style: none;}"
#define AC_STR_FindWidgetMatchCaseStyle "QPushButton { padding-right: 8px; padding-left: 8px;} QPushButton:checked { border: 1px solid gray; border-radius:2px; padding-right: 10px; padding-left: 10px; padding: 2px;margin-top: 2px;border-radius:4px; border-style:inset; } QPushButton:hover { border: 1px solid gray; border-radius:2px; border-style:outset; padding-right: 10px; padding-left: 10px; padding: 2px;margin-top: 2px;}"
acFindWidget* acFindWidget::m_spMySingleInstance = nullptr;
// ---------------------------------------------------------------------------
acFindWidget::acFindWidget()
: QWidget(nullptr),
m_pDockWidget(nullptr), m_pEditToolbar(nullptr), m_pFindTextWidget(nullptr),
m_pFindTextLayout(nullptr), m_pFindLineEdit(nullptr), m_pFindCloseLineButton(nullptr),
m_pNextButton(nullptr), m_pPrevButton(nullptr), m_pCaseSensitiveButton(nullptr),
m_pCloseButton(nullptr), m_pLastWidgetWithFocus(nullptr),
m_pFindNextAction(nullptr), m_pFindPrevAction(nullptr),
m_pCloseAction(nullptr)
{
setContentsMargins(0, 0, 0, 0);
// init the dock widget
m_pDockWidget = new QDockWidget(nullptr);
m_pDockWidget->setObjectName("FindDockWidget");
m_pDockWidget->setAllowedAreas(Qt::TopDockWidgetArea);
m_pDockWidget->setFloating(false);
m_pDockWidget->setTitleBarWidget(new QWidget());
m_pDockWidget->setContentsMargins(0, 0, 0, 0);
// init the toolbar, sits on the dock widget
m_pEditToolbar = new acToolBar(m_pDockWidget);
m_pEditToolbar->setContentsMargins(0, 2, 0, 2);
m_pEditToolbar->setStyleSheet(AC_STR_FindWidgetToolBarStyle);
m_pEditToolbar->setObjectName("FindToolBar");
// widget that contains the text ctrl combined with an icon,
// m_pFindTextWidget is used as a wrapper to make the text box and icon look like one unit
m_pFindTextWidget = new QWidget();
m_pFindTextWidget->setContentsMargins(0, 2, 0, 2);
m_pFindTextWidget->setFixedWidth(196);
m_pFindTextWidget->setStyleSheet(AC_STR_FindWidgetTextWidgetStyle);
// m_pFindTextWidget 's layout
m_pFindTextLayout = new QHBoxLayout();
m_pFindTextLayout->setContentsMargins(1, 0, 1, 0);
m_pFindTextWidget->setLayout(m_pFindTextLayout);
// m_pFindLineEdit - holds the searched text
m_pFindLineEdit = new acLineEdit(nullptr);
m_pFindLineEdit->setStyleSheet(AC_STR_FindWidgetLineEditStyle);
// button holds 2 icons, allows to clear the searched text
// the image displayed is modified according to the icon enable state
InitPushButton(m_pFindCloseLineButton, AC_STR_FindWidgetPushButtonStyleNoBorder);
m_pFindCloseLineButton->setEnabled(false);
m_pFindCloseLineButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
QPixmap searchPixmap;
acSetIconInPixmap(searchPixmap, AC_ICON_FIND_FIND);
QPixmap closePixmap;
acSetIconInPixmap(closePixmap, AC_ICON_FIND_CLOSE_CLEAR);
QIcon searchIcon;
searchIcon.addPixmap(searchPixmap, QIcon::Disabled);
searchIcon.addPixmap(closePixmap, QIcon::Normal);
m_pFindCloseLineButton->setIcon(searchIcon);
// add to the custom text widget layout
m_pFindTextLayout->addWidget(m_pFindLineEdit, 1, 0);
m_pFindTextLayout->addWidget(m_pFindCloseLineButton, 0, 0);
// init search up and search down buttons
InitPushButton(m_pNextButton, AC_STR_FindWidgetPrevNextButtonsStyle, AC_ICON_FIND_DOWN);
QString style2 = AC_STR_FindWidgetPrevNextButtonsStyle;
style2.append(AC_STR_FindWidgetPushButtonRadiusRight);
InitPushButton(m_pPrevButton, style2, AC_ICON_FIND_UP);
m_pPrevButton->setEnabled(false);
m_pNextButton->setEnabled(false);
m_pPrevButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
m_pNextButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
// init case sensitive check box
m_pCaseSensitiveButton = new QPushButton(tr(AC_STR_matchCase));
m_pCaseSensitiveButton->setFlat(true);
m_pCaseSensitiveButton->setCheckable(true);
m_pCaseSensitiveButton->setStyleSheet(AC_STR_FindWidgetMatchCaseStyle);
m_pCaseSensitiveButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
// init toolbar close button
InitPushButton(m_pCloseButton, AC_STR_FindWidgetPushButtonStyleNoBorder, AC_ICON_FIND_CLOSE_CLEAR);
m_pCloseButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
// add an empty expanding widget(to make the close button align to right) :
QWidget* pSpacer = new QWidget;
pSpacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
QWidget* pSpacer2 = new QWidget;
pSpacer2->setFixedWidth(5);
// adding all widgets to toolbar
m_pEditToolbar->addWidget(pSpacer);
m_pEditToolbar->addWidget(m_pFindTextWidget);
m_pFindNextAction = m_pEditToolbar->addWidget(m_pNextButton);
m_pFindPrevAction = m_pEditToolbar->addWidget(m_pPrevButton);
m_pEditToolbar->addWidget(pSpacer2);
m_pEditToolbar->addWidget(m_pCaseSensitiveButton);
m_pCloseAction = m_pEditToolbar->addWidget(m_pCloseButton);
// Set the shortcuts for the items which their shortcuts do not change:
m_pFindPrevAction->setShortcut(QKeySequence::FindPrevious);
m_pCloseAction->setShortcut(QKeySequence(Qt::Key_Escape));
m_pDockWidget->setWidget(m_pEditToolbar);
// connect signals
bool rc = connect(m_pCloseButton, SIGNAL(clicked()), this, SLOT(OnClose()));
GT_ASSERT(rc == true);
rc = connect(m_pNextButton, SIGNAL(clicked()), this, SLOT(OnFindNext()));
GT_ASSERT(rc == true);
rc = connect(m_pPrevButton, SIGNAL(clicked()), this, SLOT(OnFindPrevious()));
GT_ASSERT(rc == true);
rc = connect(m_pCloseAction, SIGNAL(triggered()), this, SLOT(OnClose()));
GT_ASSERT(rc);
rc = connect(m_pFindNextAction, SIGNAL(triggered()), this, SLOT(OnFindNext()));
GT_ASSERT(rc);
rc = connect(m_pFindPrevAction, SIGNAL(triggered()), this, SLOT(OnFindPrevious()));
GT_ASSERT(rc);
rc = connect(m_pFindCloseLineButton, SIGNAL(clicked()), this, SLOT(OnClearFindText()));
GT_ASSERT(rc);
rc = connect(m_pFindLineEdit, SIGNAL(textChanged(const QString&)), this, SLOT(OnFindTextChange(const QString&)));
GT_ASSERT(rc);
rc = connect(m_pCaseSensitiveButton, SIGNAL(clicked()), this, SLOT(OnFindParamChanged()));
GT_ASSERT(rc);
m_pDockWidget->setHidden(true);
}
// ---------------------------------------------------------------------------
acFindWidget::~acFindWidget()
{
}
acFindWidget& acFindWidget::Instance()
{
if (nullptr == m_spMySingleInstance)
{
m_spMySingleInstance = new acFindWidget;
}
return *m_spMySingleInstance;
}
// ---------------------------------------------------------------------------
void acFindWidget::OnFindPrevious()
{
acFindParameters::Instance().m_isSearchUp = true;
emit OnFind();
}
// ---------------------------------------------------------------------------
void acFindWidget::OnFindNext()
{
acFindParameters::Instance().m_isSearchUp = false;
emit OnFind();
}
// ---------------------------------------------------------------------------
void acFindWidget::SetFindFocusedWidget(QWidget* pFocusedWidget)
{
bool rc;
if (nullptr != m_pLastWidgetWithFocus)
{
rc = m_pLastWidgetWithFocus->disconnect(SIGNAL(destroyed()));
GT_ASSERT(rc);
}
m_pLastWidgetWithFocus = pFocusedWidget;
rc = connect(pFocusedWidget, SIGNAL(destroyed()), this, SLOT(OnDeleteLastWidgetWithFocus()));
GT_ASSERT(rc);
}
// ---------------------------------------------------------------------------
void acFindWidget::OnClose()
{
GT_IF_WITH_ASSERT(nullptr != m_pDockWidget)
{
m_pDockWidget->setHidden(true);
}
// setting focus to last widget who had it, only if still visible to user
if (nullptr != m_pLastWidgetWithFocus && m_pLastWidgetWithFocus->isTopLevel())
{
m_pLastWidgetWithFocus->setFocus();
}
m_pLastWidgetWithFocus = nullptr;
}
// ---------------------------------------------------------------------------
void acFindWidget::OnDeleteLastWidgetWithFocus()
{
m_pLastWidgetWithFocus = nullptr;
}
void acFindWidget::SetFocusOnFindText()
{
// Sanity check
GT_IF_WITH_ASSERT(m_pFindLineEdit != nullptr)
{
m_pFindLineEdit->setFocus();
m_pFindLineEdit->selectAll();
}
}
void acFindWidget::SetSearchUpParam(bool searchUp)
{
m_searchUp = searchUp;
}
void acFindWidget::SetTextToFind(QString text)
{
// Sanity check
GT_IF_WITH_ASSERT(m_pFindLineEdit != nullptr)
{
m_pFindLineEdit->setText(text);
m_pNextButton->setEnabled(!text.isEmpty());
m_pPrevButton->setEnabled(!text.isEmpty());
AdjustWidgetsToCurrentText(text);
}
}
// ---------------------------------------------------------------------------
void acFindWidget::OnClearFindText()
{
GT_IF_WITH_ASSERT(m_pFindLineEdit != nullptr)
{
m_pFindLineEdit->clear();
AdjustWidgetsToCurrentText("");
UpdateUI();
m_pFindLineEdit->setFocus();
}
}
// ---------------------------------------------------------------------------
void acFindWidget::OnFindTextChange(const QString& text)
{
// Adjust the widgets look to the current text:
AdjustWidgetsToCurrentText(text);
acFindParameters::Instance().m_findExpr = m_pFindLineEdit->text();
if (acFindParameters::Instance().m_shouldRespondToTextChange)
{
// Emit a find signal:
emit OnFind();
}
}
bool acFindWidget::IsFindWidgetHidden()
{
bool isHidden = false;
GT_IF_WITH_ASSERT(m_pDockWidget != nullptr)
{
isHidden = m_pDockWidget->isHidden();
}
return isHidden;
}
// ---------------------------------------------------------------------------
void acFindWidget::ShowFindWidget(bool show)
{
GT_IF_WITH_ASSERT(m_pDockWidget != nullptr)
{
m_pDockWidget->setHidden(!show);
// Notice: find next action is supposed to use F3 shortcut. The shortcut should both be available
// when the toolbar is opened, and when it is closed (through the main menu).
// To avoid shortcuts ambiguity, we set the shortcut on show, and un-set on hide:
QList<QKeySequence> findNextShortcuts;
if (show)
{
findNextShortcuts.append(QKeySequence::FindNext);
findNextShortcuts.append(QKeySequence(Qt::Key_Return));
}
// On hide the list will be empty:
m_pFindNextAction->setShortcuts(findNextShortcuts);
}
}
// ---------------------------------------------------------------------------
void acFindWidget::InitPushButton(QPushButton*& pButton, QString styleSheet, acIconId iconId)
{
pButton = new QPushButton();
pButton->setStyleSheet(styleSheet);
pButton->setFlat(true);
pButton->setFixedWidth(AC_FIND_PUSH_BUTTON_WIDTH);
if (iconId != AC_ICON_EMPTY)
{
QPixmap pixMap;
acSetIconInPixmap(pixMap, iconId);
pButton->setIcon(QIcon(pixMap));
}
}
void acFindWidget::UpdateUI()
{
// Sanity check:
GT_IF_WITH_ASSERT((m_pFindTextWidget != nullptr) && (m_pFindLineEdit != nullptr))
{
bool wasFound = acFindParameters::Instance().m_lastResult || acFindParameters::Instance().m_findExpr.isEmpty();
// Set the style according to the results:
QString style = wasFound ? AC_STR_FindWidgetTextWidgetStyle : AC_STR_FindWidgetTextWidgetStyleNoResults;
m_pFindTextWidget->setStyleSheet(style);
// Give the focus back to the text:
m_pFindLineEdit->setFocus();
}
}
void acFindWidget::AdjustWidgetsToCurrentText(const QString& text)
{
// m_pFindLineButton change displayed image according to text
// text is not empty - image is delete and pressing button will clear the text
GT_IF_WITH_ASSERT((m_pFindCloseLineButton != nullptr) && (m_pNextButton != nullptr) && (m_pPrevButton != nullptr))
{
bool hasText = !text.isEmpty();
m_pFindCloseLineButton->setEnabled(hasText);
m_pNextButton->setEnabled(hasText);
m_pPrevButton->setEnabled(hasText);
}
}
void acFindWidget::OnFindParamChanged()
{
// Sanity check:
GT_IF_WITH_ASSERT((m_pFindLineEdit != nullptr) && (m_pCaseSensitiveButton != nullptr))
{
acFindParameters::Instance().m_findExpr = m_pFindLineEdit->text();
acFindParameters::Instance().m_isCaseSensitive = m_pCaseSensitiveButton->isChecked();
acFindParameters::Instance().m_isSearchUp = m_searchUp;
}
}
| 38.585492 | 429 | 0.675574 | nfogh |
e3336236ba0da367b30e6f765895e8f9b625a9b3 | 1,233 | hpp | C++ | audio/XaSystem.hpp | quyse/inanity | a39225c5a41f879abe5aa492bb22b500dbe77433 | [
"MIT"
] | 26 | 2015-04-22T05:25:25.000Z | 2020-11-15T11:07:56.000Z | audio/XaSystem.hpp | quyse/inanity | a39225c5a41f879abe5aa492bb22b500dbe77433 | [
"MIT"
] | 2 | 2015-01-05T10:41:27.000Z | 2015-01-06T20:46:11.000Z | audio/XaSystem.hpp | quyse/inanity | a39225c5a41f879abe5aa492bb22b500dbe77433 | [
"MIT"
] | 5 | 2016-08-02T11:13:57.000Z | 2018-10-26T11:19:27.000Z | #ifndef ___INANITY_AUDIO_XA_SYSTEM_HPP___
#define ___INANITY_AUDIO_XA_SYSTEM_HPP___
#include "System.hpp"
#include "Format.hpp"
#include "xaudio2.hpp"
#include "../CriticalSection.hpp"
#include "../ComPointer.hpp"
#include <unordered_set>
BEGIN_INANITY_AUDIO
class Device;
struct Format;
class XaPlayer;
/// Класс звуковой подсистемы для XAudio.
class XaSystem : public System
{
private:
ComPointer<IXAudio2> xAudio2;
std::unordered_set<XaPlayer*> players;
CriticalSection csPlayers;
std::vector<ptr<XaPlayer> > tempPlayers;
uint32_t operationSet;
bool hadOperations;
public:
XaSystem();
/// Получить voice нужного формата.
IXAudio2SourceVoice* AllocateSourceVoice(const Format& format, IXAudio2VoiceCallback* callback);
/// Получить текущий номер operation set.
//** Предполагается, что операция будет произведена.
uint32_t GetOperationSet();
/// Зарегистрировать плеер, чтобы вызывать у него тик. Потоковобезопасно.
void RegisterPlayer(XaPlayer* player);
/// Разрегистрировать плеер. Потоковобезопасно.
void UnregisterPlayer(XaPlayer* player);
static WAVEFORMATEX ConvertFormat(const Format& format);
//** System's methods.
ptr<Device> CreateDefaultDevice();
void Tick();
};
END_INANITY_AUDIO
#endif
| 23.711538 | 97 | 0.781833 | quyse |
e3412ca26c6407d00a49c620aa74dd803e496285 | 687 | cpp | C++ | credit.cpp | TomGlint/ANSim | f02edc65a80fbbcf3bc812f4f6841658571c2024 | [
"MIT"
] | null | null | null | credit.cpp | TomGlint/ANSim | f02edc65a80fbbcf3bc812f4f6841658571c2024 | [
"MIT"
] | null | null | null | credit.cpp | TomGlint/ANSim | f02edc65a80fbbcf3bc812f4f6841658571c2024 | [
"MIT"
] | null | null | null | // $Id$
/*credit.cpp
*
*A class for credits
*/
#include "booksim.hpp"
#include "credit.hpp"
stack<Credit *> Credit::_all;
stack<Credit *> Credit::_free;
Credit::Credit()
{
Reset();
}
void Credit::Reset()
{
vc.clear();
head = false;
tail = false;
id = -1;
}
Credit *Credit::New()
{
Credit *c;
if (_free.empty())
{
c = new Credit();
_all.push(c);
}
else
{
c = _free.top();
c->Reset();
_free.pop();
}
return c;
}
void Credit::Free()
{
_free.push(this);
}
void Credit::FreeAll()
{
while (!_all.empty())
{
delete _all.top();
_all.pop();
}
}
long long int Credit::OutStanding()
{
return _all.size() - _free.size();
}
| 11.080645 | 36 | 0.551674 | TomGlint |
e34776e65acd191846eca1b767bc7d1d29f8790c | 1,307 | cpp | C++ | android-31/java/util/concurrent/CyclicBarrier.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/java/util/concurrent/CyclicBarrier.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-29/java/util/concurrent/CyclicBarrier.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "./TimeUnit.hpp"
#include "./locks/ReentrantLock.hpp"
#include "./CyclicBarrier.hpp"
namespace java::util::concurrent
{
// Fields
// QJniObject forward
CyclicBarrier::CyclicBarrier(QJniObject obj) : JObject(obj) {}
// Constructors
CyclicBarrier::CyclicBarrier(jint arg0)
: JObject(
"java.util.concurrent.CyclicBarrier",
"(I)V",
arg0
) {}
CyclicBarrier::CyclicBarrier(jint arg0, JObject arg1)
: JObject(
"java.util.concurrent.CyclicBarrier",
"(ILjava/lang/Runnable;)V",
arg0,
arg1.object()
) {}
// Methods
jint CyclicBarrier::await() const
{
return callMethod<jint>(
"await",
"()I"
);
}
jint CyclicBarrier::await(jlong arg0, java::util::concurrent::TimeUnit arg1) const
{
return callMethod<jint>(
"await",
"(JLjava/util/concurrent/TimeUnit;)I",
arg0,
arg1.object()
);
}
jint CyclicBarrier::getNumberWaiting() const
{
return callMethod<jint>(
"getNumberWaiting",
"()I"
);
}
jint CyclicBarrier::getParties() const
{
return callMethod<jint>(
"getParties",
"()I"
);
}
jboolean CyclicBarrier::isBroken() const
{
return callMethod<jboolean>(
"isBroken",
"()Z"
);
}
void CyclicBarrier::reset() const
{
callMethod<void>(
"reset",
"()V"
);
}
} // namespace java::util::concurrent
| 17.662162 | 83 | 0.648049 | YJBeetle |
e348827d92e0bc791efe14e521f4f459c9173efc | 1,810 | hpp | C++ | src/thunder/include/thunder/spdlog/sinks/file_hourly_sink.hpp | Lyrex/thunder | f664aca2d74e6edbdd4188989feade38345a3f6f | [
"MIT"
] | null | null | null | src/thunder/include/thunder/spdlog/sinks/file_hourly_sink.hpp | Lyrex/thunder | f664aca2d74e6edbdd4188989feade38345a3f6f | [
"MIT"
] | null | null | null | src/thunder/include/thunder/spdlog/sinks/file_hourly_sink.hpp | Lyrex/thunder | f664aca2d74e6edbdd4188989feade38345a3f6f | [
"MIT"
] | null | null | null | #include <mutex>
#include <spdlog/spdlog.h>
#include <spdlog/sinks/sink.h>
#include <spdlog/sinks/base_sink.h>
#include <spdlog/sinks/file_sinks.h>
#include <spdlog/details/null_mutex.h>
namespace thunder {
namespace sinks {
/*
* Rotating file sink based on hour. rotates every hour
*/
template<class Mutex, class FileNameCalc = spdlog::sinks::default_daily_file_name_calculator>
class hourly_file_sink : public spdlog::sinks::base_sink<Mutex>
{
public:
//create hourly file sink which rotates on given time
hourly_file_sink(const spdlog::filename_t& base_filename)
: _base_filename(base_filename), _file_helper()
{
_rotation_tp = _next_rotation_tp();
_file_helper.open(FileNameCalc::calc_filename(_base_filename));
}
protected:
void _sink_it(const spdlog::details::log_msg& msg) override final
{
if (std::chrono::system_clock::now() >= _rotation_tp)
{
_file_helper.open(FileNameCalc::calc_filename(_base_filename));
_rotation_tp = _next_rotation_tp();
}
_file_helper.write(msg);
}
void _flush() override final
{
_file_helper.flush();
}
private:
std::chrono::system_clock::time_point _next_rotation_tp()
{
using namespace std::chrono;
auto now = system_clock::now();
now += hours(1);
time_t tnow = std::chrono::system_clock::to_time_t(now);
tm date = spdlog::details::os::localtime(tnow);
date.tm_min = 0;
date.tm_sec = 0;
auto rotation_time = std::chrono::system_clock::from_time_t(std::mktime(&date));
return rotation_time;
}
spdlog::filename_t _base_filename;
std::chrono::system_clock::time_point _rotation_tp;
spdlog::details::file_helper _file_helper;
};
typedef hourly_file_sink<std::mutex> hourly_file_sink_mt;
typedef hourly_file_sink<spdlog::details::null_mutex> hourly_file_sink_st;
};
};
| 27.846154 | 94 | 0.733149 | Lyrex |
e34a61c1604eb2a07f69e91380832ca39d4805d0 | 5,732 | cpp | C++ | ExLemmings/Lemmings/02-Lemming/MenuScene.cpp | GuillemCastro/LemmingsVJ | 03cfc73d198213b1629ab36d61c85d2fbae603b9 | [
"MIT"
] | null | null | null | ExLemmings/Lemmings/02-Lemming/MenuScene.cpp | GuillemCastro/LemmingsVJ | 03cfc73d198213b1629ab36d61c85d2fbae603b9 | [
"MIT"
] | null | null | null | ExLemmings/Lemmings/02-Lemming/MenuScene.cpp | GuillemCastro/LemmingsVJ | 03cfc73d198213b1629ab36d61c85d2fbae603b9 | [
"MIT"
] | null | null | null | #include "MenuScene.h"
#include <glm/gtc/matrix_transform.hpp>
#include <iostream>
#include "Game.h"
MenuScene::MenuScene()
{
}
MenuScene::~MenuScene()
{
menuScreen->free();
levelButton->free();
delete menuScreen;
delete levelButton;
}
void MenuScene::init() {
glm::vec2 geom[2] = { glm::vec2(0.f, 0.f), glm::vec2(float(CAMERA_WIDTH), float(CAMERA_HEIGHT) - 60) };
glm::vec2 geomButtons[2] = {glm::vec2(0.f, 0.f), glm::vec2(50.0f, 25.0f)};
glm::vec2 texCoords[2] = { glm::vec2(0.0f, 0.f), glm::vec2(1.0f, 1.0f) };
initShaders();
menuScreen = TexturedQuad::createTexturedQuad(geom, texCoords, simpleTexProgram);
levelButton = TexturedQuad::createTexturedQuad(geomButtons, texCoords, simpleTexProgram);
colorTexture.loadFromFile("images/title.png", TEXTURE_PIXEL_FORMAT_RGBA);
colorTexture.setMinFilter(GL_NEAREST);
colorTexture.setMagFilter(GL_NEAREST);
level1Tex.loadFromFile("images/level1.png", TEXTURE_PIXEL_FORMAT_RGBA);
level1Tex.setMinFilter(GL_NEAREST);
level1Tex.setMagFilter(GL_NEAREST);
level2Tex.loadFromFile("images/level2.png", TEXTURE_PIXEL_FORMAT_RGBA);
level2Tex.setMinFilter(GL_NEAREST);
level2Tex.setMagFilter(GL_NEAREST);
level3Tex.loadFromFile("images/level3.png", TEXTURE_PIXEL_FORMAT_RGBA);
level3Tex.setMinFilter(GL_NEAREST);
level3Tex.setMagFilter(GL_NEAREST);
creditsTex.loadFromFile("images/credits.png", TEXTURE_PIXEL_FORMAT_RGBA);
creditsTex.setMagFilter(GL_NEAREST);
creditsTex.setMinFilter(GL_NEAREST);
projection = glm::ortho(0.f, float(CAMERA_WIDTH - 1), float(CAMERA_HEIGHT - 1), 0.f);
currentTime = 0.0f;
}
void MenuScene::update(int deltaTime) {
currentTime += deltaTime;
}
void MenuScene::render() {
glm::mat4 modelview;
simpleTexProgram.use();
simpleTexProgram.setUniformMatrix4f("projection", projection);
simpleTexProgram.setUniform4f("color", 1.0f, 1.0f, 1.0f, 1.0f);
modelview = glm::mat4(1.0f);
modelview = glm::translate(modelview, glm::vec3(0.f, 30.f, 0.f));
simpleTexProgram.setUniformMatrix4f("modelview", modelview);
menuScreen->render(colorTexture);
simpleTexProgram.use();
simpleTexProgram.setUniformMatrix4f("projection", projection);
simpleTexProgram.setUniform4f("color", .0f, 1.0f, .0f, 1.0f);
modelview = glm::mat4(1.0f);
modelview = glm::translate(modelview, glm::vec3(55.f, 130.0f, 0.0f));
simpleTexProgram.setUniformMatrix4f("modelview", modelview);
levelButton->render(level1Tex);
simpleTexProgram.use();
simpleTexProgram.setUniformMatrix4f("projection", projection);
simpleTexProgram.setUniform4f("color", .0f, .0f, 1.0f, 1.0f);
modelview = glm::mat4(1.0f);
modelview = glm::translate(modelview, glm::vec3(135.f, 130.0f, 0.0f));
simpleTexProgram.setUniformMatrix4f("modelview", modelview);
levelButton->render(level2Tex);
simpleTexProgram.use();
simpleTexProgram.setUniformMatrix4f("projection", projection);
simpleTexProgram.setUniform4f("color", 1.0f, 0.f, .0f, 1.0f);
modelview = glm::mat4(1.0f);
modelview = glm::translate(modelview, glm::vec3(225.f, 130.0f, 0.0f));
simpleTexProgram.setUniformMatrix4f("modelview", modelview);
levelButton->render(level3Tex);
simpleTexProgram.use();
simpleTexProgram.setUniformMatrix4f("projection", projection);
simpleTexProgram.setUniform4f("color", .5f, .5f, .5f, 1.0f);
modelview = glm::mat4(1.0f);
modelview = glm::translate(modelview, glm::vec3(135.f, 160.0f, 0.0f));
simpleTexProgram.setUniformMatrix4f("modelview", modelview);
levelButton->render(creditsTex);
}
void MenuScene::mouseMoved(int mouseX, int mouseY, bool bLeftButton, bool bRightButton) {
int x = mouseX / 3;
int y = mouseY / 3;
if (bLeftButton) {
if (x >= 55 && x <= 105 && y >= 130 && y <= 155) {
Game::instance().changeScene(SCENE1);
}
else if (x >= 135 && x <= 185 && y >= 130 && y <= 155) {
Game::instance().changeScene(SCENE2);
}
else if (x >= 225 && x <= 275 && y >= 130 && y <= 155) {
Game::instance().changeScene(SCENE3);
}
else if (x >= 135 && x <= 185 && y >= 160 && y <= 185) {
Game::instance().changeScene(CREDITS);
}
}
}
void MenuScene::initShaders() {
Shader vShader, fShader;
vShader.initFromFile(VERTEX_SHADER, "shaders/texture.vert");
if (!vShader.isCompiled())
{
cout << "Vertex Shader Error" << endl;
cout << "" << vShader.log() << endl << endl;
}
fShader.initFromFile(FRAGMENT_SHADER, "shaders/texture.frag");
if (!fShader.isCompiled())
{
cout << "Fragment Shader Error" << endl;
cout << "" << fShader.log() << endl << endl;
}
simpleTexProgram.init();
simpleTexProgram.addShader(vShader);
simpleTexProgram.addShader(fShader);
simpleTexProgram.link();
if (!simpleTexProgram.isLinked())
{
cout << "Shader Linking Error" << endl;
cout << "" << simpleTexProgram.log() << endl << endl;
}
simpleTexProgram.bindFragmentOutput("outColor");
vShader.free();
fShader.free();
vShader.initFromFile(VERTEX_SHADER, "shaders/maskedTexture.vert");
if (!vShader.isCompiled())
{
cout << "Vertex Shader Error" << endl;
cout << "" << vShader.log() << endl << endl;
}
fShader.initFromFile(FRAGMENT_SHADER, "shaders/maskedTexture.frag");
if (!fShader.isCompiled())
{
cout << "Fragment Shader Error" << endl;
cout << "" << fShader.log() << endl << endl;
}
maskedTexProgram.init();
maskedTexProgram.addShader(vShader);
maskedTexProgram.addShader(fShader);
maskedTexProgram.link();
if (!maskedTexProgram.isLinked())
{
cout << "Shader Linking Error" << endl;
cout << "" << maskedTexProgram.log() << endl << endl;
}
maskedTexProgram.bindFragmentOutput("outColor");
vShader.free();
fShader.free();
}
| 31.322404 | 105 | 0.686148 | GuillemCastro |
e34ce03f8cfdd46fc6dfbc08b94a4a48305d7b13 | 2,348 | cpp | C++ | pointers_references_sau.cpp | saurabhkakade21/Cpp-Practice-Code | ac5e77f1a53bb164f7b265e9291b3ca63a2a2f60 | [
"MIT"
] | null | null | null | pointers_references_sau.cpp | saurabhkakade21/Cpp-Practice-Code | ac5e77f1a53bb164f7b265e9291b3ca63a2a2f60 | [
"MIT"
] | null | null | null | pointers_references_sau.cpp | saurabhkakade21/Cpp-Practice-Code | ac5e77f1a53bb164f7b265e9291b3ca63a2a2f60 | [
"MIT"
] | null | null | null | // Section 12
// Challenge
/* Write a C++ function named apply_all that expects two arrays of integers and their sizes and
dynamically allocates a new array of integers whose size is the product of the 2 array sizes
The function should loop through the second array and multiplies each element across each element of array 1 and store the
product in the newly created array.
The function should return a pointer to the newly allocated array.
You can also write a print function that expects a pointer to an array of integers and its size and display the
elements in the array.
For example,
Below is the output from the following code which would be in main:
int array1[] {1,2,3,4,5};
int array2[] {10,20,30};
cout << "Array 1: " ;
print(array1,5);
cout << "Array 2: " ;
print(array2,3);
int *results = apply_all(array1, 5, array2, 3);
cout << "Result: " ;
print(results,15);
Output
---------------------
Array 1: [ 1 2 3 4 5 ]
Array 2: [ 10 20 30 ]
Result: [ 10 20 30 40 50 20 40 60 80 100 30 60 90 120 150 ]
*/
#include <iostream>
using namespace std;
int print(int * const array1, size_t arr1_size)
{
std::cout << "[ ";
for (size_t i = 0; i < arr1_size; i++)
{
/* code */
std::cout << array1[i] << " ";
}
std::cout << "]" << std::endl;
return 0;
}
int *apply_all(int * const array1, size_t arr1_size, int * const array2, size_t arr2_size)
{
int * total {nullptr};
total = new int[arr1_size + arr2_size];
size_t index{0};
for (size_t i = 0; i < arr2_size; i++)
{
for (size_t j = 0; j < arr1_size; j++)
{
total[index] = array1[j] * array2[i];
index++;
}
}
return total;
}
int main() {
system("clear");
const size_t array1_size {5};
const size_t array2_size {3};
int array1[] {1,2,3,4,5};
int array2[] {10,20,30};
cout << "Array 1: " ;
print(array1,array1_size);
cout << "Array 2: " ;
print(array2,array2_size);
int *results = apply_all(array1, array1_size, array2, array2_size);
constexpr size_t results_size {array1_size * array2_size};
cout << "Result: " ;
print(results, results_size);
cout << endl;
return 0;
}
| 23.48 | 124 | 0.587734 | saurabhkakade21 |
e34d58650f4126fb33ca0f368b011f51bf4790ee | 7,729 | cpp | C++ | OpenCP/libGaussian/gaussian_conv_sii.cpp | norishigefukushima/OpenCP | 63090131ec975e834f85b04e84ec29b2893845b2 | [
"BSD-3-Clause"
] | 137 | 2015-03-27T07:11:19.000Z | 2022-03-30T05:58:22.000Z | OpenCP/libGaussian/gaussian_conv_sii.cpp | Pandinosaurus/OpenCP | a5234ed531c610d7944fa14d42f7320442ea34a1 | [
"BSD-3-Clause"
] | 2 | 2016-05-18T06:33:16.000Z | 2016-07-11T17:39:17.000Z | OpenCP/libGaussian/gaussian_conv_sii.cpp | Pandinosaurus/OpenCP | a5234ed531c610d7944fa14d42f7320442ea34a1 | [
"BSD-3-Clause"
] | 43 | 2015-02-20T15:34:25.000Z | 2022-01-27T14:59:37.000Z | /**
* \file gaussian_conv_sii.c
* \brief Gaussian convolution using stacked integral images
* \author Pascal Getreuer <getreuer@cmla.ens-cachan.fr>
*
* Copyright (c) 2012-2013, Pascal Getreuer
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify it
* under, at your option, the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version, or the terms of the
* simplified BSD license.
*
* You should have received a copy of these licenses along with this program.
* If not, see <http://www.gnu.org/licenses/> and
* <http://www.opensource.org/licenses/bsd-license.html>.
*/
#include "gaussian_conv.h"
#include <assert.h>
#include <stdio.h>
#ifndef M_PI
/** \brief The constant pi */
#define M_PI 3.14159265358979323846264338327950288
#endif
/**
* \brief Precompute filter coefficients for SII Gaussian convolution
* \param c sii_coeffs pointer to hold precomputed coefficients
* \param sigma Gaussian standard deviation
* \param K number of boxes = 3, 4, or 5
* \return 1 on success, 0 on failure
*
* This routine reads Elboher and Werman's optimal SII radii and weights for
* reference standard deviation \f$ \sigma_0 = 100/\pi \f$ from a table and
* scales them to the specified value of sigma.
*/
template<typename srcType>
void sii_precomp_(sii_coeffs<srcType> &c, const srcType sigma, const int K)
{
/* Elboher and Werman's optimal radii and weights. */
const double sigma0 = 100.0 / M_PI;
static const short radii0[SII_MAX_K - SII_MIN_K + 1][SII_MAX_K] =
{ { 76, 46, 23, 0, 0 },
{ 82, 56, 37, 19, 0 },
{ 85, 61, 44, 30, 16 } };
static const float weights0[SII_MAX_K - SII_MIN_K + 1][SII_MAX_K] =
{ { 0.1618f, 0.5502f, 0.9495f, 0, 0 },
{ 0.0976f, 0.3376f, 0.6700f, 0.9649f, 0 },
{ 0.0739f, 0.2534f, 0.5031f, 0.7596f, 0.9738f } };
const int i = K - SII_MIN_K;
double sum;
int k;
assert(sigma > 0 && SII_VALID_K(K));
c.K = K;
for (k = 0, sum = 0; k < K; ++k)
{
c.radii[k] = (long)(radii0[i][k] * (sigma / sigma0) + 0.5);
sum += weights0[i][k] * (2 * c.radii[k] + 1);
}
for (k = 0; k < K; ++k)
c.weights[k] = (srcType)(weights0[i][k] / sum);
return;
}
void sii_precomp(sii_coeffs<float> &c, const float sigma, const int K)
{
sii_precomp_<float>(c, sigma, K);
}
void sii_precomp(sii_coeffs<double> &c, const double sigma, const int K)
{
sii_precomp_<double>(c, sigma, K);
}
/**
* \brief Determines the buffer size needed for SII Gaussian convolution
* \param c sii_coeffs created by sii_precomp()
* \param N number of samples
* \return required buffer size in units of num samples
*
* This routine determines the minimum size of the buffer needed for use in
* sii_gaussian_conv() or sii_gaussian_conv_image(). This size is the length
* of the signal (or in 2D, max(width, height)) plus the twice largest box
* radius, for padding.
*/
template<typename srcType>
long sii_buffer_size_(sii_coeffs<srcType> c, long N)
{
long pad = c.radii[0] + 1;
return N + 2 * pad;
}
long sii_buffer_size(sii_coeffs<float> c, long N)
{
return sii_buffer_size_<float>(c, N);
}
long sii_buffer_size(sii_coeffs<double> c, long N)
{
return sii_buffer_size_<double>(c, N);
}
/**
* \brief Gaussian convolution SII approximation
* \param c sii_coeffs created by sii_precomp()
* \param dest output convolved data
* \param buffer array with space for sii_buffer_size() samples
* \param src input, modified in-place if src = dest
* \param N number of samples
* \param stride stride between successive samples
*
* This routine performs stacked integral images approximation of Gaussian
* convolution with half-sample symmetric boundary handling. The buffer array
* is used to store the cumulative sum of the input, and must have space for
* at least sii_buffer_size(c,N) samples.
*
* The convolution can be performed in-place by setting `src` = `dest` (the
* source array is overwritten with the result). However, the buffer array
* must be distinct from `src` and `dest`.
*/
template<typename srcType>
void sii_gaussian_conv_(sii_coeffs<srcType> c, srcType *dest, srcType *buffer, const srcType *src, long N, long stride)
{
srcType accum;
int pad, n;
int k;
//assert(dest && buffer && src && dest != buffer && src != buffer && N > 0 && stride != 0)
pad = c.radii[0] + 1;
buffer += pad;
/* Compute cumulative sum of src over n = -pad,..., N + pad - 1. */
for (n = -pad, accum = 0; n < N + pad; ++n)
{
accum += src[stride * extension(N, n)];
buffer[n] = accum;
}
/* Compute stacked box filters. */
for (n = 0; n < N; ++n, dest += stride)
{
accum = c.weights[0] * (buffer[n + c.radii[0]]
- buffer[n - c.radii[0] - 1]);
for (k = 1; k < c.K; ++k)
accum += c.weights[k] * (buffer[n + c.radii[k]]
- buffer[n - c.radii[k] - 1]);
*dest = accum;
}
return;
}
void sii_gaussian_conv(sii_coeffs<float> c, float *dest, float *buffer, const float *src, long N, long stride)
{
sii_gaussian_conv_<float>(c, dest, buffer, src, N, stride);
}
void sii_gaussian_conv(sii_coeffs<double> c, double *dest, double *buffer, const double *src, long N, long stride)
{
sii_gaussian_conv_<double>(c, dest, buffer, src, N, stride);
}
/**
* \brief 2D Gaussian convolution SII approximation
* \param c sii_coeffs created by sii_precomp()
* \param dest output convolved data
* \param buffer array with space for sii_buffer_size() samples
* \param src image to be convolved, overwritten if src = dest
* \param width image width
* \param height image height
* \param num_channels number of image channels
*
* Similar to sii_gaussian_conv(), this routine approximates 2D Gaussian
* convolution with stacked integral images. The buffer array must have space
* for at least sii_buffer_size(c,max(width,height)) samples.
*
* The convolution can be performed in-place by setting `src` = `dest` (the
* source array is overwritten with the result). However, the buffer array
* must be distinct from `src` and `dest`.
*/
template<typename srcType>
void sii_gaussian_conv_image_(sii_coeffs<srcType> c, srcType *dest, srcType *buffer, const srcType *src, int width, int height, int num_channels)
{
long num_pixels = ((long)width) * ((long)height);
int x, y, channel;
assert(dest && buffer && src && num_pixels > 0);
/* Loop over the image channels. */
for (channel = 0; channel < num_channels; ++channel)
{
srcType *dest_y = dest;
const srcType *src_y = src;
/* Filter each row of the channel. */
for (y = 0; y < height; ++y)
{
sii_gaussian_conv(c, dest_y, buffer, src_y, width, 1);
dest_y += width;
src_y += width;
}
/* Filter each column of the channel. */
for (x = 0; x < width; ++x)
sii_gaussian_conv(c, dest + x, buffer, dest + x, height, width);
dest += num_pixels;
src += num_pixels;
}
return;
}
void sii_gaussian_conv_image(sii_coeffs<float> c, float *dest, float *buffer, const float *src, int width, int height, int num_channels)
{
sii_gaussian_conv_image_<float>(c, dest, buffer, src, width, height, num_channels);
}
void sii_gaussian_conv_image(sii_coeffs<double> c, double *dest, double *buffer, const double *src, int width, int height, int num_channels)
{
sii_gaussian_conv_image_<double>(c, dest, buffer, src, width, height, num_channels);
} | 33.899123 | 145 | 0.6561 | norishigefukushima |
e34e4fcab1e2253f7da8483740c4d57d6b9d93b8 | 3,356 | cpp | C++ | monitor/src/v20180724/model/DescribeServiceDiscoveryRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | monitor/src/v20180724/model/DescribeServiceDiscoveryRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | monitor/src/v20180724/model/DescribeServiceDiscoveryRequest.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 28 | 2019-07-12T09:06:22.000Z | 2022-03-30T08:04:18.000Z | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/monitor/v20180724/model/DescribeServiceDiscoveryRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Monitor::V20180724::Model;
using namespace std;
DescribeServiceDiscoveryRequest::DescribeServiceDiscoveryRequest() :
m_instanceIdHasBeenSet(false),
m_kubeClusterIdHasBeenSet(false),
m_kubeTypeHasBeenSet(false)
{
}
string DescribeServiceDiscoveryRequest::ToJsonString() const
{
rapidjson::Document d;
d.SetObject();
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
if (m_instanceIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "InstanceId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_instanceId.c_str(), allocator).Move(), allocator);
}
if (m_kubeClusterIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "KubeClusterId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_kubeClusterId.c_str(), allocator).Move(), allocator);
}
if (m_kubeTypeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "KubeType";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_kubeType, allocator);
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
string DescribeServiceDiscoveryRequest::GetInstanceId() const
{
return m_instanceId;
}
void DescribeServiceDiscoveryRequest::SetInstanceId(const string& _instanceId)
{
m_instanceId = _instanceId;
m_instanceIdHasBeenSet = true;
}
bool DescribeServiceDiscoveryRequest::InstanceIdHasBeenSet() const
{
return m_instanceIdHasBeenSet;
}
string DescribeServiceDiscoveryRequest::GetKubeClusterId() const
{
return m_kubeClusterId;
}
void DescribeServiceDiscoveryRequest::SetKubeClusterId(const string& _kubeClusterId)
{
m_kubeClusterId = _kubeClusterId;
m_kubeClusterIdHasBeenSet = true;
}
bool DescribeServiceDiscoveryRequest::KubeClusterIdHasBeenSet() const
{
return m_kubeClusterIdHasBeenSet;
}
int64_t DescribeServiceDiscoveryRequest::GetKubeType() const
{
return m_kubeType;
}
void DescribeServiceDiscoveryRequest::SetKubeType(const int64_t& _kubeType)
{
m_kubeType = _kubeType;
m_kubeTypeHasBeenSet = true;
}
bool DescribeServiceDiscoveryRequest::KubeTypeHasBeenSet() const
{
return m_kubeTypeHasBeenSet;
}
| 27.966667 | 98 | 0.744338 | suluner |
e35bfe487c5aff4fc46f3240c454844e689acb0a | 849 | hpp | C++ | android-31/android/os/storage/OnObbStateChangeListener.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/android/os/storage/OnObbStateChangeListener.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-29/android/os/storage/OnObbStateChangeListener.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #pragma once
#include "../../../JObject.hpp"
class JString;
namespace android::os::storage
{
class OnObbStateChangeListener : public JObject
{
public:
// Fields
static jint ERROR_ALREADY_MOUNTED();
static jint ERROR_COULD_NOT_MOUNT();
static jint ERROR_COULD_NOT_UNMOUNT();
static jint ERROR_INTERNAL();
static jint ERROR_NOT_MOUNTED();
static jint ERROR_PERMISSION_DENIED();
static jint MOUNTED();
static jint UNMOUNTED();
// QJniObject forward
template<typename ...Ts> explicit OnObbStateChangeListener(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {}
OnObbStateChangeListener(QJniObject obj);
// Constructors
OnObbStateChangeListener();
// Methods
void onObbStateChange(JString arg0, jint arg1) const;
};
} // namespace android::os::storage
| 24.970588 | 165 | 0.727915 | YJBeetle |
e35c46fee5e0447817270af245fdb67e45fd9bb5 | 4,696 | cpp | C++ | src/via/http/request.cpp | aestuarium/via-httplib | 8906ad438e4126aaac17633eded467cc8eac55bb | [
"BSL-1.0"
] | null | null | null | src/via/http/request.cpp | aestuarium/via-httplib | 8906ad438e4126aaac17633eded467cc8eac55bb | [
"BSL-1.0"
] | null | null | null | src/via/http/request.cpp | aestuarium/via-httplib | 8906ad438e4126aaac17633eded467cc8eac55bb | [
"BSL-1.0"
] | null | null | null | //////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2013-2015 Ken Barker
// (ken dot barker at via-technology dot co dot uk)
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//////////////////////////////////////////////////////////////////////////////
#include "via/http/request.hpp"
#include "via/http/character.hpp"
#include <limits>
namespace via
{
namespace http
{
//////////////////////////////////////////////////////////////////////////
bool request_line::parse_char(char c)
{
switch (state_)
{
case REQ_METHOD:
// Valid HTTP methods must be uppercase chars
if (std::isupper(c))
{
method_.push_back(c);
if (method_.size() > max_method_length_)
{
state_ = REQ_ERROR_METHOD_LENGTH;
return false;
}
}
// If this char is whitespace and method has been read
else if (is_space_or_tab(c) && !method_.empty())
{
ws_count_ = 1;
state_ = REQ_URI;
}
else
return false;
break;
case REQ_URI:
if (is_end_of_line(c))
return false;
else if (is_space_or_tab(c))
{
// Ignore leading whitespace
// but only upto to a limit!
if (++ws_count_ > max_whitespace_)
{
state_ = REQ_ERROR_WS;
return false;
}
if (!uri_.empty())
{
ws_count_ = 1;
state_ = REQ_HTTP_H;
}
}
else
{
uri_.push_back(c);
if (uri_.size() > max_uri_length_)
{
state_ = REQ_ERROR_URI_LENGTH;
return false;
}
}
break;
case REQ_HTTP_H:
// Ignore leading whitespace
if (is_space_or_tab(c))
{
// but only upto to a limit!
if (++ws_count_ > max_whitespace_)
{
state_ = REQ_ERROR_WS;
return false;
}
}
else
{
if ('H' == c)
state_ = REQ_HTTP_T1;
else
return false;
}
break;
case REQ_HTTP_T1:
if ('T' == c)
state_ = REQ_HTTP_T2;
else
return false;
break;
case REQ_HTTP_T2:
if ('T' == c)
state_ = REQ_HTTP_P;
else
return false;
break;
case REQ_HTTP_P:
if ('P' == c)
state_ = REQ_HTTP_SLASH;
else
return false;
break;
case REQ_HTTP_SLASH:
if ('/' == c)
state_ = REQ_HTTP_MAJOR;
else
return false;
break;
case REQ_HTTP_MAJOR:
if (std::isdigit(c))
{
major_version_ = c;
state_ = REQ_HTTP_DOT;
}
else
return false;
break;
case REQ_HTTP_DOT:
if ('.' == c)
state_ = REQ_HTTP_MINOR;
else
return false;
break;
case REQ_HTTP_MINOR:
if (std::isdigit(c))
{
minor_version_ = c;
state_ = REQ_CR;
}
else
return false;
break;
case REQ_CR:
// The HTTP line should end with a \r\n...
if ('\r' == c)
state_ = REQ_LF;
else
{
// but (if not being strict) permit just \n
if (!strict_crlf_ && ('\n' == c))
state_ = REQ_VALID;
else
{
state_ = REQ_ERROR_CRLF;
return false;
}
}
break;
case REQ_LF:
if ('\n' == c)
{
state_ = REQ_VALID;
break;
}
// intentional fall-through (for code coverage)
default:
return false;
}
return true;
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
std::string request_line::to_string() const
{
std::string output(method_);
output += ' ' + uri_ + ' '
+ http_version(major_version_, minor_version_)
+ CRLF;
return output;
}
//////////////////////////////////////////////////////////////////////////
}
}
| 24.082051 | 79 | 0.397785 | aestuarium |
e35dab2baee8b47dde1349a488114b424175c848 | 336 | cpp | C++ | src/module.cpp | dylangentile/DFK | a627073f0d54bedec10e7b344b86912669d2e070 | [
"MIT"
] | 1 | 2020-06-26T06:31:33.000Z | 2020-06-26T06:31:33.000Z | src/module.cpp | dylangentile/DFK | a627073f0d54bedec10e7b344b86912669d2e070 | [
"MIT"
] | null | null | null | src/module.cpp | dylangentile/DFK | a627073f0d54bedec10e7b344b86912669d2e070 | [
"MIT"
] | null | null | null | #include <kernel/module.h>
Module::Module(ModuleType type) : mType(type)
{
}
Module::~Module()
{
}
#include <module/fs_module.h>
FileSystem::FileSystem() : Module(kModuleType_FileSystem)
{
}
FileSystem::~FileSystem()
{
}
FileSystem::FileDescriptor::FileDescriptor()
{
}
FileSystem::FileDescriptor::~FileDescriptor()
{
} | 9.6 | 57 | 0.696429 | dylangentile |
e362284ca189ac75567d9a77252bd666f0df1147 | 7,251 | hxx | C++ | tools/VisualizeECC/draw_epipolar_lines.hxx | mareikethies/EpipolarConsistency | 63d7ca2fd705911a6c93ca4247486fc66a9d31c7 | [
"Apache-2.0"
] | 2 | 2020-03-21T16:33:51.000Z | 2021-09-12T03:03:00.000Z | tools/VisualizeECC/draw_epipolar_lines.hxx | mareikethies/EpipolarConsistency | 63d7ca2fd705911a6c93ca4247486fc66a9d31c7 | [
"Apache-2.0"
] | 1 | 2018-06-14T07:48:55.000Z | 2018-06-14T07:48:55.000Z | tools/VisualizeECC/draw_epipolar_lines.hxx | mareikethies/EpipolarConsistency | 63d7ca2fd705911a6c93ca4247486fc66a9d31c7 | [
"Apache-2.0"
] | 6 | 2018-05-15T21:38:35.000Z | 2022-01-06T07:20:47.000Z | // Utilities for Displaying Images and Plots
#include <LibUtilsQt/Figure.hxx>
#include <LibUtilsQt/Plot.hxx>
using UtilsQt::Figure;
using UtilsQt::Plot;
#include <LibEpipolarConsistency/EpipolarConsistencyCommon.hxx>
/// Function called when user clicks into projection images. Epipolar lines are drawn in 2 and 3 dimensions.
void updateEpipolarLines(const std::string& figure_name, bool is_blue, std::vector<Eigen::Vector4d>& selections)
{
// Number of selections
int n=(int)selections.size();
if (is_blue || n==0 || n>10) {
selections.clear();
return;
}
// Do not allow ractangular selections
if (!selections.back().tail(2).isConstant(1)) {
selections.pop_back();
return;
}
// Figure out which image has been clicked on with what mouse button
Figure figure0(figure_name);
Figure figure1((figure_name=="Image 0")?"Image 1":"Image 0");
figure1.clearSelection(is_blue);
// Figure out epipolar geometry
using namespace Geometry;
ProjectionMatrix P0=figure0.getProjectionMatrix();
ProjectionMatrix P1=figure1.getProjectionMatrix();
// Figure out projection to epipolar line 1 and plane
auto F=computeFundamentalMatrix(P0,P1);
auto P0invT=pseudoInverse(P0).transpose().eval();
RP3Line B=join_pluecker(getCameraCenter(P0),getCameraCenter(P1));
// Figure out epipolar planes at 0 and 90 degrees w.r.t. the origin.
RP3Plane E0=join_pluecker(B,origin3);
RP3Plane E90=join_pluecker(B,E0);
// Convert to Hessian normal form
E0/=E0.head(3).norm();
E90/=E90.head(3).norm();
// Figure out image planes
double spacing=GetSet<double>("Epipolar Consistency/Images/Pixel Spacing");
auto I0=getCameraImagePlane(P0,spacing);
auto I1=getCameraImagePlane(P1,spacing);
// Epipoles in 3D
auto Ep1=meet_pluecker(B,I0);
auto Ep0=meet_pluecker(B,I1);
// Intersection line of image planes
auto I=meet_pluecker(I0,I1);
// Remove all overlays from figures, except for 3D geometry
GraphicsItems::Group geom3d=figure0.overlay().group("3D");
figure0.overlay().clear().set("3D",geom3d);
figure1.overlay().clear().set("3D",geom3d);
// Prepare 2D plot
Plot plot("Epipolar Consistency");
plot.clearItems();
// Prepare info for 3D plot
auto& line3d=Figure("Geometry").overlay().group("3D Lines");
line3d.clear();
line3d.add(GraphicsItems::PlueckerLine3D(B,2,QColor(0,0,0)));
line3d.add(GraphicsItems::PlueckerLine3D(I,-1 ,QColor(0,0,0,128)));
double w2=figure0.getImage().size(0)*0.5;
double h2=figure0.getImage().size(1)*0.5;
// Should samples in Radon intermediate functions be displayed?
Figure fig0("Radon Intermediate Function 0");
Figure fig1("Radon Intermediate Function 1");
bool show_dtr=fig0.exists(true) & fig0.exists(true);
double range_t=0;
if (show_dtr)
{
fig0.overlay().group("Highlighted Lines").clear();
fig1.overlay().group("Highlighted Lines").clear();
// Compute range of t-value in Radon transform this dtr corresponds to
double bin_size_distance=stringTo<double>(fig0.getImage().meta_info["Bin Size/Distance"]);
range_t=bin_size_distance*fig0.getImage().size(1);
}
Geometry::RP2Homography line_origin_to_center=
Geometry::Translation(-0.5*figure0.getImage().size(0),-0.5*figure0.getImage().size(1)) // shift by half image size
.inverse().transpose(); // inverse transpose because we are transforming lines (covariantly)
//std::cout << "Current line pairs:\n";
for (int i=0;i<n;i++)
{
RP2Point x0(selections[i][0],selections[i][1],1);
RP2Line l1=F*x0;
RP3Plane E=P1.transpose()*l1;
RP2Line l0=P0invT*E;
l0/=l0.head(2).norm();
l1/=l1.head(2).norm();
//std::cout << toString(i,3,' ') << ": l0 = " << l0[0] << " " << l0[1] << " " << l0[2] << " (alpha=" << std::atan2(-l0[0], -l0[1])+Pi*0.5 << "t=" << -l0[2]-w2*l0[0]-h2*l0[1]<< ")" << std::endl;
//std::cout << toString(i,3,' ') << ": l1 = " << l1[0] << " " << l1[1] << " " << l1[2] << " (alpha=" << std::atan2(-l1[0], -l1[1])+Pi*0.5 << "t=" << -l1[2]-w2*l1[0]-h2*l1[1]<< ")" << std::endl;
E/=E.head(3).norm();
double kappa=plane_angle_in_pencil(E,E0,E90);
if (kappa>+Pi/2) kappa-=Pi;
if (kappa<-Pi/2) kappa+=Pi;
auto color=GraphicsItems::colorByIndex(i+2);
plot.drawVerticalLine(kappa,color,1);
figure0.overlay().add(GraphicsItems::PlueckerLine2D(l0,1,color));
figure1.overlay().add(GraphicsItems::PlueckerLine2D(l1,1,color));
auto corner=meet_pluecker(I,E);
line3d.add(GraphicsItems::Line3D(Ep0,corner,1,color));
line3d.add(GraphicsItems::Line3D(Ep1,corner,1,color));
if (show_dtr)
{
// Move origin of line to image center
l0=line_origin_to_center*l0;
l1=line_origin_to_center*l1;
// Convert line to angle distance and compute texture coordinates to be sampled.
lineToSampleDtr(l0,range_t);
lineToSampleDtr(l1,range_t);
fig0.overlay().group("Highlighted Lines").add(GraphicsItems::Point2D(
l0[0]*fig0.getImage().size(0),
l0[1]*fig0.getImage().size(1),
5,color,GraphicsItems::Dot));
fig1.overlay().group("Highlighted Lines").add(GraphicsItems::Point2D(
l1[0]*fig1.getImage().size(0),
l1[1]*fig1.getImage().size(1),
5,color,GraphicsItems::Dot));
}
}
}
void showImages(const NRRD::Image<float>& I0, const NRRD::Image<float>& I1, Geometry::ProjectionMatrix P0, Geometry::ProjectionMatrix P1, double spacing)
{
// Visualize Projection Matrices
Eigen::Vector4d image_rect(0,0,I0.size(0),I0.size(1));
GraphicsItems::Group static_3d_geometry;
auto cube=GraphicsItems::ConvexMesh::Cube();
static_3d_geometry
.add(GraphicsItems::CoordinateAxes())
.add(cube);
cube.q_color.front()=QColor(0,0,0,64);
cube.l_color=QColor(0,0,0,255);
// Project geometry to 3D image planes
auto C0=Geometry::getCameraCenter(P0);
auto C1=Geometry::getCameraCenter(P1);
auto proj_to_plane0=Geometry::centralProjectionToPlane(C0,Geometry::SourceDetectorGeometry(P0,spacing).image_plane);
auto proj_to_plane1=Geometry::centralProjectionToPlane(C1,Geometry::SourceDetectorGeometry(P1,spacing).image_plane);
GraphicsItems::Group image_plane_0(proj_to_plane0);
GraphicsItems::Group image_plane_1(proj_to_plane1);
image_plane_0.add(cube);
image_plane_1.add(cube);
Figure("Geometry",800,600).overlay()
.add(static_3d_geometry)
.add(image_plane_0)
.add(image_plane_1)
.add(GraphicsItems::ConvexMesh::Camera(P0,image_rect,spacing,true,QColor(255,0,0,32)))
.add(GraphicsItems::ConvexMesh::Camera(P1,image_rect,spacing,true,QColor(0,255,0,32)));
// Visualize Images
Figure figure0("Image 0",I0);
Figure figure1("Image 1",I1);
figure0.setCallback(updateEpipolarLines);
figure1.setCallback(updateEpipolarLines);
figure0.showTiled(0,800,600,false).setProjectionMatrix(P0).overlay().group("3D").add(static_3d_geometry);
figure1.showTiled(1,800,600,false).setProjectionMatrix(P1).overlay().group("3D").add(static_3d_geometry);
// Show some standard lines
std::vector<Eigen::Vector4d> selections;
selections.push_back(Eigen::Vector4d(I0.size(0)*0.5,I0.size(1)*0.1,1,1));
selections.push_back(Eigen::Vector4d(I0.size(0)*0.5,I0.size(1)*0.3,1,1));
selections.push_back(Eigen::Vector4d(I0.size(0)*0.5,I0.size(1)*0.5,1,1));
selections.push_back(Eigen::Vector4d(I0.size(0)*0.5,I0.size(1)*0.7,1,1));
selections.push_back(Eigen::Vector4d(I0.size(0)*0.5,I0.size(1)*0.9,1,1));
updateEpipolarLines("Image 0", false, selections);
}
| 42.156977 | 196 | 0.71728 | mareikethies |
e362ec8e242c5c7af2c450760bbe89bf28e38b44 | 2,500 | cpp | C++ | Demos/VerveTutorialBase/source/Verve/Extension/LightObject/VLightObjectAnimationEvent.cpp | AnteSim/Verve | 22a55d182f86e3d7684fdc52f628ca57837cac8a | [
"MIT"
] | 1 | 2021-01-02T09:17:18.000Z | 2021-01-02T09:17:18.000Z | Templates/Verve/source/Verve/Extension/LightObject/VLightObjectAnimationEvent.cpp | AnteSim/Verve | 22a55d182f86e3d7684fdc52f628ca57837cac8a | [
"MIT"
] | null | null | null | Templates/Verve/source/Verve/Extension/LightObject/VLightObjectAnimationEvent.cpp | AnteSim/Verve | 22a55d182f86e3d7684fdc52f628ca57837cac8a | [
"MIT"
] | 4 | 2015-05-16T17:35:07.000Z | 2021-01-02T09:17:26.000Z | //-----------------------------------------------------------------------------
// Verve
// Copyright (C) - Violent Tulip
//-----------------------------------------------------------------------------
#include "Verve/Extension/LightObject/VLightObjectAnimationEvent.h"
#include "console/consoleTypes.h"
//-----------------------------------------------------------------------------
IMPLEMENT_CONOBJECT( VLightObjectAnimationEvent );
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
VLightObjectAnimationEvent::VLightObjectAnimationEvent( void ) :
mAnimationData( NULL )
{
setLabel( "AnimationEvent" );
}
void VLightObjectAnimationEvent::initPersistFields( void )
{
Parent::initPersistFields();
addField( "AnimationData", TYPEID<VTorque::LightAnimationDataType>(), Offset( mAnimationData, VLightObjectAnimationEvent ) );
}
//-----------------------------------------------------------------------------
//
// Callback Methods.
//
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//
// VLightObjectAnimationEvent::onTrigger( pTime, pDelta );
//
// When this Event is triggered the light object will begin to play the target
// animation.
//
//-----------------------------------------------------------------------------
void VLightObjectAnimationEvent::onTrigger( const S32 &pTime, const S32 &pDelta )
{
Parent::onTrigger( pTime, pDelta );
// Fetch the Light Object.
VTorque::LightObjectType *lightObject;
if ( getSceneObject( lightObject ) )
{
// Play the Animation.
VTorque::playAnimation( lightObject, mAnimationData );
}
}
//-----------------------------------------------------------------------------
//
// VLightObjectAnimationEvent::onComplete( pTime, pDelta );
//
// The current animation played by the light object will be paused when this
// Event completes its updates.
//
//-----------------------------------------------------------------------------
void VLightObjectAnimationEvent::onComplete( const S32 &pTime, const S32 &pDelta )
{
Parent::onTrigger( pTime, pDelta );
// Fetch the Light Object.
VTorque::LightObjectType *lightObject;
if ( getSceneObject( lightObject ) )
{
// Pause the Animation.
VTorque::pauseAnimation( lightObject );
}
} | 33.333333 | 129 | 0.4588 | AnteSim |
e373e7fa9e5e49fc4f231e274be782d5e644845f | 707 | cpp | C++ | luogu_U68608/luogu_U68608.cpp | skyfackr/luogu_personal_cppcode | b59af9839745d65091e6c01cddf53e5bb6fb274a | [
"BSD-3-Clause"
] | null | null | null | luogu_U68608/luogu_U68608.cpp | skyfackr/luogu_personal_cppcode | b59af9839745d65091e6c01cddf53e5bb6fb274a | [
"BSD-3-Clause"
] | null | null | null | luogu_U68608/luogu_U68608.cpp | skyfackr/luogu_personal_cppcode | b59af9839745d65091e6c01cddf53e5bb6fb274a | [
"BSD-3-Clause"
] | null | null | null | /*头像上传*/
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define gou1 "Too Young"
#define gou2 "Too Simple"
#define gou3 "Sometimes Naive"
int n,l,g;
void preanalyse(int &w,int &h)
{
//int maxbian=max(w,h);
while (max(w,h)>g)
{
w/=2;
h/=2;
}
return;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cin>>n>>l>>g;
while (n)
{
n--;
int w,h;
cin>>w>>h;
preanalyse(w,h);
if (w<l||h<l)
{
cout<<gou1<<endl;
continue;
}
if (w!=h)
{
cout<<gou2<<endl;
continue;
}
cout<<gou3<<endl;
}
return 0;
} | 16.44186 | 30 | 0.445545 | skyfackr |
e375b0f0afc248bce5e837b9b49405634083b8f2 | 1,684 | cpp | C++ | Days 201 - 210/Day 207/IsGraphBipartite.cpp | LucidSigma/Daily-Coding-Problems | 21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a | [
"MIT"
] | null | null | null | Days 201 - 210/Day 207/IsGraphBipartite.cpp | LucidSigma/Daily-Coding-Problems | 21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a | [
"MIT"
] | null | null | null | Days 201 - 210/Day 207/IsGraphBipartite.cpp | LucidSigma/Daily-Coding-Problems | 21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a | [
"MIT"
] | null | null | null | #include <algorithm>
#include <array>
#include <cstddef>
#include <iostream>
#include <iterator>
template <std::size_t Size>
using Graph = std::array<std::array<unsigned int, Size>, Size>;
static constexpr int NullColour = -1;
template <std::size_t Size>
bool IsBipartiteGraphHelper(const Graph<Size>& graph, std::array<int, Size>& graphColouring, const std::size_t currentPosition, const int colour) noexcept
{
if (graphColouring[currentPosition] != NullColour && graphColouring[currentPosition != colour])
{
return false;
}
graphColouring[currentPosition] = colour;
bool isBipartite = true;
for (std::size_t i = 0; i < Size; ++i)
{
if (graph[currentPosition][i] != 0)
{
if (graphColouring[i] == NullColour)
{
isBipartite &= IsBipartiteGraphHelper(graph, graphColouring, i, 1 - colour);
}
if (graphColouring[i] != NullColour && graphColouring[i] != 1 - colour)
{
return false;
}
}
if (!isBipartite)
{
return false;
}
}
return true;
}
template <std::size_t Size>
inline bool IsBipartiteGraph(const Graph<Size>& graph) noexcept
{
std::array<int, Size> graphColouring;
std::fill(std::begin(graphColouring), std::end(graphColouring), NullColour);
return IsBipartiteGraphHelper(graph, graphColouring, 0, 1);
}
int main(int argc, char* argv[])
{
const Graph<5> graph
{
std::array<unsigned int, 5>{ 0, 1, 0, 1, 0 },
std::array<unsigned int, 5>{ 1, 0, 1, 0, 1 },
std::array<unsigned int, 5>{ 0, 1, 0, 1, 0 },
std::array<unsigned int, 5>{ 1, 0, 1, 0, 1 },
std::array<unsigned int, 5>{ 0, 1, 0, 1, 0 }
};
std::cout << std::boolalpha;
std::cout << IsBipartiteGraph(graph) << "\n";
std::cin.get();
return 0;
} | 23.068493 | 154 | 0.663302 | LucidSigma |
e37d30affcccc7498f6b18a6e9df66dc6f01adbf | 896 | hpp | C++ | C++/Examples/AHRS/AHRS.hpp | PhiliLegault/Navio2 | b3ed81b9e50838cb21677ba4dfd79d811ed8737a | [
"BSD-3-Clause"
] | 150 | 2016-03-21T00:41:14.000Z | 2022-03-16T22:40:43.000Z | docExamples/RPI+Navio/AHRS/AHRS.hpp | torressantiago/PINISAT | 21809d7a96ffd44d48d43b5ed1cfb866dcc97be5 | [
"MIT"
] | 34 | 2016-05-09T14:25:21.000Z | 2021-08-03T13:10:55.000Z | docExamples/RPI+Navio/AHRS/AHRS.hpp | torressantiago/PINISAT | 21809d7a96ffd44d48d43b5ed1cfb866dcc97be5 | [
"MIT"
] | 132 | 2016-02-25T01:52:01.000Z | 2022-02-25T13:29:27.000Z | /*
Mahony AHRS algorithm implemented by Madgwick
See: http://x-io.co.uk/open-source-imu-and-ahrs-algorithms/
Adapted by Igor Vereninov (igor.vereninov@emlid.com)
Provided to you by Emlid Ltd (c) 2014.
twitter.com/emlidtech || www.emlid.com || info@emlid.com
*/
#ifndef AHRS_HPP
#define AHRS_HPP
#include <cmath>
#include <stdio.h>
#include <memory>
#include <Common/InertialSensor.h>
class AHRS{
private:
float q0, q1, q2, q3;
float gyroOffset[3];
float twoKi;
float twoKp;
float integralFBx, integralFBy, integralFBz;
std::unique_ptr <InertialSensor> sensor;
public:
AHRS( std::unique_ptr <InertialSensor> imu);
void update(float dt);
void updateIMU(float dt);
void setGyroOffset();
void getEuler(float* roll, float* pitch, float* yaw);
float invSqrt(float x);
float getW();
float getX();
float getY();
float getZ();
};
#endif // AHRS_hpp
| 21.333333 | 59 | 0.699777 | PhiliLegault |
e3824cbbd5f0531bfd7c351555618baba005d1eb | 5,064 | cpp | C++ | source/libgui/MYGUI/mygui_button.cpp | Lauvak/ray | 906d3991ddd232a7f78f0e51f29aeead008a139a | [
"BSD-3-Clause"
] | 113 | 2015-06-25T06:24:59.000Z | 2021-09-26T02:46:02.000Z | source/libgui/MYGUI/mygui_button.cpp | Lauvak/ray | 906d3991ddd232a7f78f0e51f29aeead008a139a | [
"BSD-3-Clause"
] | 2 | 2015-05-03T07:22:49.000Z | 2017-12-11T09:17:20.000Z | source/libgui/MYGUI/mygui_button.cpp | Lauvak/ray | 906d3991ddd232a7f78f0e51f29aeead008a139a | [
"BSD-3-Clause"
] | 17 | 2015-11-10T15:07:15.000Z | 2021-01-19T15:28:16.000Z | // +----------------------------------------------------------------------
// | Project : ray.
// | All rights reserved.
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2015.
// +----------------------------------------------------------------------
// | * Redistribution and use of this software 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 ray team, nor the names of its
// | contributors may be used to endorse or promote products
// | derived from this software without specific prior
// | written permission of the ray team.
// |
// | 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.
// +----------------------------------------------------------------------
#if defined(_BUILD_MYGUI)
#include "mygui_button.h"
#include "mygui_textbox.h"
_NAME_BEGIN
__ImplementSubClass(MyGuiButtonImpl, MyGuiWidget, "MyGuiButtonImpl")
__ImplementSubClass(MyGuiButton, GuiButton, "MyGuiButton")
MyGuiButtonImpl::MyGuiButtonImpl() noexcept
: _destroy(true)
, _parent(nullptr)
, _button(nullptr)
{
}
MyGuiButtonImpl::MyGuiButtonImpl(MyGUI::Button* self, bool destroy) noexcept
: _destroy(destroy)
, _parent(nullptr)
, _button(self)
{
_textbox = std::make_shared<MyGuiTextBox>(_button, false);
}
MyGuiButtonImpl::~MyGuiButtonImpl() noexcept
{
this->destroy();
}
bool
MyGuiButtonImpl::create() except
{
assert(!_button);
if (_parent)
_button = _parent->createWidget<MyGUI::Button>("", 0, 0, 0, 0, MyGUI::Align::Default, "");
else
_button = MyGUI::Gui::getInstance().createWidget<MyGUI::Button>("", 0, 0, 0, 0, MyGUI::Align::Default, "Main", "");
_textbox = std::make_shared<MyGuiTextBox>(_button, false);
this->setWidget(_button);
return _button ? true : false;
}
void
MyGuiButtonImpl::destroy() noexcept
{
if (_destroy)
{
if (_button)
{
MyGUI::Gui::getInstance().destroyWidget(_button);
_button = nullptr;
}
}
}
GuiTextBoxPtr
MyGuiButtonImpl::getGuiTextBox() const noexcept
{
return _textbox;
}
void
MyGuiButtonImpl::setStateSelected(bool value) noexcept
{
assert(_button);
_button->setStateSelected(value);
}
bool
MyGuiButtonImpl::getStateSelected() const noexcept
{
assert(_button);
return _button->getStateSelected();
}
void
MyGuiButtonImpl::setModeImage(bool value) noexcept
{
assert(_button);
_button->setModeImage(value);
}
bool
MyGuiButtonImpl::getModeImage() const noexcept
{
assert(_button);
return _button->getModeImage();
}
void
MyGuiButtonImpl::setImageResource(const std::string& name) noexcept
{
assert(_button);
_button->setImageResource(name);
}
void
MyGuiButtonImpl::setImageGroup(const std::string& name) noexcept
{
assert(_button);
_button->setImageGroup(name);
}
void
MyGuiButtonImpl::setImageName(const std::string& name) noexcept
{
assert(_button);
_button->setImageName(name);
}
MyGuiButton::MyGuiButton() noexcept
: GuiButton(_impl)
{
}
MyGuiButton::MyGuiButton(MyGUI::Button* self, bool destroy) noexcept
: GuiButton(_impl)
, _impl(self, destroy)
{
}
MyGuiButton::~MyGuiButton() noexcept
{
}
GuiTextBoxPtr
MyGuiButton::getGuiTextBox() const noexcept
{
return _impl.getGuiTextBox();
}
void
MyGuiButton::setStateSelected(bool value) noexcept
{
_impl.setStateSelected(value);
}
bool
MyGuiButton::getStateSelected() const noexcept
{
return _impl.getStateSelected();
}
void
MyGuiButton::setModeImage(bool value) noexcept
{
_impl.setModeImage(value);
}
bool
MyGuiButton::getModeImage() const noexcept
{
return _impl.getModeImage();
}
void
MyGuiButton::setImageResource(const std::string& name) noexcept
{
_impl.setImageResource(name);
}
void
MyGuiButton::setImageGroup(const std::string& name) noexcept
{
_impl.setImageGroup(name);
}
void
MyGuiButton::setImageName(const std::string& name) noexcept
{
_impl.setImageName(name);
}
_NAME_END
#endif | 23.553488 | 117 | 0.69767 | Lauvak |
be644f093ff3a05f9b6e2f3753151570be13e866 | 16,689 | cpp | C++ | dfgTestQt/dfgTestCsvItemModel.cpp | tc3t/dfglib | 7157973e952234a010da8e9fbd551a912c146368 | [
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 1 | 2017-08-01T04:42:29.000Z | 2017-08-01T04:42:29.000Z | dfgTestQt/dfgTestCsvItemModel.cpp | tc3t/dfglib | 7157973e952234a010da8e9fbd551a912c146368 | [
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 128 | 2018-04-06T23:01:51.000Z | 2022-03-31T20:19:38.000Z | dfgTestQt/dfgTestCsvItemModel.cpp | tc3t/dfglib | 7157973e952234a010da8e9fbd551a912c146368 | [
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | 3 | 2018-03-21T01:11:05.000Z | 2021-04-05T19:20:31.000Z | #include <dfg/qt/CsvItemModel.hpp>
#include <dfg/io.hpp>
#include <dfg/io/OmcByteStream.hpp>
#include <dfg/qt/containerUtils.hpp>
#include <dfg/qt/connectHelper.hpp>
#include <dfg/math.hpp>
#include <dfg/qt/sqlTools.hpp>
#include <dfg/qt/PatternMatcher.hpp>
#include <dfg/iter/FunctionValueIterator.hpp>
#include <dfg/os/TemporaryFileStream.hpp>
#include "../dfgTest/dfgTest.hpp"
DFG_BEGIN_INCLUDE_WITH_DISABLED_WARNINGS
#include <gtest/gtest.h>
#include <QAction>
#include <QCoreApplication>
#include <QDateTime>
#include <QFile>
#include <QFileInfo>
#include <QDialog>
#include <QThread>
DFG_END_INCLUDE_WITH_DISABLED_WARNINGS
TEST(dfgQt, CsvItemModel)
{
for (size_t i = 0;; ++i)
{
const QString sInputPath = QString("testfiles/example%1.csv").arg(i);
const QString sOutputPath = QString("testfiles/generated/example%1.testOutput.csv").arg(i);
if (!QFileInfo(sInputPath).exists())
{
const bool bAtLeastOneFileFound = (i != 0);
EXPECT_TRUE(bAtLeastOneFileFound);
break;
}
DFG_MODULE_NS(qt)::DFG_CLASS_NAME(CsvItemModel) model;
DFG_MODULE_NS(qt)::DFG_CLASS_NAME(CsvItemModel)::LoadOptions loadOptions;
if (i == 3) // Example 3 needs non-native eol-settings.
loadOptions.separatorChar('\t');
if (i == 4)
loadOptions.textEncoding(DFG_MODULE_NS(io)::encodingLatin1);
const auto bOpenSuccess = model.openFile(sInputPath, loadOptions);
EXPECT_EQ(true, bOpenSuccess);
DFG_MODULE_NS(qt)::DFG_CLASS_NAME(CsvItemModel)::SaveOptions saveOptions(&model);
if (i == 3)
saveOptions = loadOptions;
if (i == 4)
saveOptions.textEncoding(loadOptions.textEncoding());
saveOptions.eolType((i == 1 || i == 4) ? DFG_MODULE_NS(io)::EndOfLineTypeN : DFG_MODULE_NS(io)::EndOfLineTypeRN);
// Note: EOL-setting does not affect in-cell EOL-items, i.e. saving of eol-chars inside cell content
// is not affected by eol-setting.
const auto bSaveSuccess = model.saveToFile(sOutputPath, saveOptions);
EXPECT_EQ(true, bSaveSuccess);
auto inputBytesWithAddedEol = DFG_MODULE_NS(io)::fileToVector(sInputPath.toLatin1().data());
const auto sEol = ::DFG_MODULE_NS(io)::eolStrFromEndOfLineType(saveOptions.eolType());
inputBytesWithAddedEol.insert(inputBytesWithAddedEol.end(), sEol.cbegin(), sEol.cend());
const auto outputBytes = DFG_MODULE_NS(io)::fileToVector(sOutputPath.toLatin1().data());
EXPECT_EQ(inputBytesWithAddedEol, outputBytes);
// Test in-memory saving
{
DFG_MODULE_NS(io)::DFG_CLASS_NAME(OmcByteStream)<std::vector<char>> strm;
model.save(strm, saveOptions);
const auto& outputBytesMc = strm.container();
EXPECT_EQ(inputBytesWithAddedEol, outputBytesMc);
}
}
// Testing insertRows/Columns
{
using namespace DFG_MODULE_NS(qt);
CsvItemModel model;
// Making sure that bad insert counts are handled correctly.
EXPECT_FALSE(model.insertRows(0, 0));
EXPECT_FALSE(model.insertColumns(0, 0));
EXPECT_FALSE(model.insertRows(0, -5));
EXPECT_FALSE(model.insertColumns(0, -5));
EXPECT_EQ(0, model.rowCount());
EXPECT_EQ(0, model.columnCount());
}
}
TEST(dfgQt, CsvItemModel_removeRows)
{
DFG_MODULE_NS(qt)::DFG_CLASS_NAME(CsvItemModel) model;
model.insertColumns(0, 1);
model.insertRows(0, 10);
EXPECT_EQ(10, model.rowCount());
EXPECT_EQ(1, model.columnCount());
for (int r = 0, nRowCount = model.rowCount(); r < nRowCount; ++r)
{
char c[2] = { static_cast<char>('a' + r), '\0' };
model.setDataNoUndo(r, 0, DFG_ROOT_NS::SzPtrAscii(c));
}
model.removeRows(0, 2);
EXPECT_EQ(8, model.rowCount());
EXPECT_EQ(QString("c"), model.data(model.index(0, 0)).toString());
model.removeRows(0, 1);
EXPECT_EQ(7, model.rowCount());
EXPECT_EQ(QString("d"), model.data(model.index(0, 0)).toString());
const int removeRows0[] = { -1 };
model.removeRows(removeRows0);
EXPECT_EQ(7, model.rowCount()); // Passing bogus row index shouldn't do anything.
const int removeRows1[] = { 1, 5, 6 };
model.removeRows(removeRows1);
EXPECT_EQ(4, model.rowCount());
EXPECT_EQ(QString("d"), model.data(model.index(0, 0)).toString());
EXPECT_EQ(QString("f"), model.data(model.index(1, 0)).toString());
const int removeRows2[] = { 1, 2 };
model.removeRows(removeRows2);
EXPECT_EQ(2, model.rowCount());
EXPECT_EQ(QString("d"), model.data(model.index(0, 0)).toString());
EXPECT_EQ(QString("h"), model.data(model.index(1, 0)).toString());
// Removing remaining rows and testing that bogus entries in the input list gets handled correctly also in this case.
const int removeRows3[] = { -5, -2, -1, 0, 1, 2, 3, 50 };
model.removeRows(removeRows3);
EXPECT_EQ(0, model.rowCount());
}
TEST(dfgQt, CsvItemModel_filteredRead)
{
using namespace DFG_MODULE_NS(qt);
const char szFilePath5x5[] = "testfiles/test_5x5_sep1F_content_row_comma_column.csv";
const char szFilePathAb[] = "testfiles/example_forFilterRead.csv";
CsvItemModel model;
// Row and column filter.
{
auto options = model.getLoadOptionsForFile(szFilePath5x5);
options.setProperty(CsvOptionProperty_includeRows, "0;2;4");
options.setProperty(CsvOptionProperty_includeColumns, "2;3;5");
model.openFile(szFilePath5x5, options);
ASSERT_EQ(2, model.rowCount());
ASSERT_EQ(3, model.columnCount());
EXPECT_EQ(QString("Col1"), model.getHeaderName(0));
EXPECT_EQ(QString("Col2"), model.getHeaderName(1));
EXPECT_EQ(QString("Col4"), model.getHeaderName(2));
EXPECT_EQ(QString("2,1"), QString::fromUtf8(model.RawStringPtrAt(0, 0).c_str()));
EXPECT_EQ(QString("2,2"), QString::fromUtf8(model.RawStringPtrAt(0, 1).c_str()));
EXPECT_EQ(QString("2,4"), QString::fromUtf8(model.RawStringPtrAt(0, 2).c_str()));
EXPECT_EQ(QString("4,1"), QString::fromUtf8(model.RawStringPtrAt(1, 0).c_str()));
EXPECT_EQ(QString("4,2"), QString::fromUtf8(model.RawStringPtrAt(1, 1).c_str()));
EXPECT_EQ(QString("4,4"), QString::fromUtf8(model.RawStringPtrAt(1, 2).c_str()));
}
// Content filter, basic test
{
auto options = model.getLoadOptionsForFile(szFilePath5x5);
const char szFilters[] = R"({ "text": "1,4" })";
options.setProperty(CsvOptionProperty_readFilters, szFilters);
model.openFile(szFilePath5x5, options);
ASSERT_EQ(1, model.rowCount());
ASSERT_EQ(5, model.columnCount());
EXPECT_EQ(QString("Col4"), model.getHeaderName(4));
EXPECT_EQ(QString("1,4"), QString::fromUtf8(model.RawStringPtrAt(0, 4).c_str()));
EXPECT_EQ(5, model.m_table.cellCountNonEmpty());
}
// Content filter, both OR and AND filters
{
auto options = model.getLoadOptionsForFile(szFilePath5x5);
const char szFilters[] = R"({ "text": "3,*", "and_group": "a" }
{ "text": "*,0", "and_group": "a" }
{"text": "1,4", "and_group": "b"} )";
options.setProperty(CsvOptionProperty_readFilters, szFilters);
model.openFile(szFilePath5x5, options);
ASSERT_EQ(2, model.rowCount());
ASSERT_EQ(5, model.columnCount());
EXPECT_EQ(QString("Col0"), model.getHeaderName(0));
EXPECT_EQ(QString("Col4"), model.getHeaderName(4));
EXPECT_EQ(QString("1,4"), QString::fromUtf8(model.RawStringPtrAt(0, 4).c_str()));
EXPECT_EQ(QString("3,0"), QString::fromUtf8(model.RawStringPtrAt(1, 0).c_str()));
EXPECT_EQ(10, model.m_table.cellCountNonEmpty());
}
// Row, column and content filters
{
auto options = model.getLoadOptionsForFile(szFilePath5x5);
const char szFilters[] = R"({ "text": "3,*", "and_group": "a" }
{ "text": "*,1", "and_group": "a" }
{ "text": "4,1", "and_group": "b"} )";
options.setProperty(CsvOptionProperty_includeRows, "0;3;5");
options.setProperty(CsvOptionProperty_includeColumns, "2");
options.setProperty(CsvOptionProperty_readFilters, szFilters);
model.openFile(szFilePath5x5, options);
ASSERT_EQ(1, model.rowCount());
ASSERT_EQ(1, model.columnCount());
EXPECT_EQ(QString("Col1"), model.getHeaderName(0));
EXPECT_EQ(QString("3,1"), QString::fromUtf8(model.RawStringPtrAt(0, 0).c_str()));
EXPECT_EQ(1, model.m_table.cellCountNonEmpty());
}
// Case sensitivity in content filter
{
{
auto options = model.getLoadOptionsForFile(szFilePathAb);
const char szFilters[] = R"({ "text": "A", "case_sensitive": true } )";
options.setProperty(CsvOptionProperty_readFilters, szFilters);
model.openFile(szFilePathAb, options);
EXPECT_EQ(0, model.m_table.cellCountNonEmpty());
}
{
auto options = model.getLoadOptionsForFile(szFilePathAb);
const char szFilters[] = R"({ "text": "A", "case_sensitive": false } )";
options.setProperty(CsvOptionProperty_readFilters, szFilters);
model.openFile(szFilePathAb, options);
EXPECT_EQ(6, model.m_table.cellCountNonEmpty());
}
}
// Column apply-filters in content filter
{
auto options = model.getLoadOptionsForFile(szFilePathAb);
const char szFilters[] = R"({ "text": "a", "apply_columns": "2" } )";
options.setProperty(CsvOptionProperty_readFilters, szFilters);
model.openFile(szFilePathAb, options);
ASSERT_EQ(1, model.rowCount());
ASSERT_EQ(2, model.columnCount());
EXPECT_EQ(QString("Col0"), model.getHeaderName(0));
EXPECT_EQ(QString("Col1"), model.getHeaderName(1));
EXPECT_EQ(QString("b"), QString::fromUtf8(model.RawStringPtrAt(0, 0).c_str()));
EXPECT_EQ(QString("ab"), QString::fromUtf8(model.RawStringPtrAt(0, 1).c_str()));
EXPECT_EQ(2, model.m_table.cellCountNonEmpty());
}
// Row apply-filters in content filter
{
auto options = model.getLoadOptionsForFile(szFilePathAb);
const char szFilters[] = R"({ "text": "c", "apply_rows": "1;3" } )";
options.setProperty(CsvOptionProperty_readFilters, szFilters);
model.openFile(szFilePathAb, options);
ASSERT_EQ(2, model.rowCount());
ASSERT_EQ(2, model.columnCount());
EXPECT_EQ(QString("Col0"), model.getHeaderName(0));
EXPECT_EQ(QString("Col1"), model.getHeaderName(1));
EXPECT_EQ(QString("b"), QString::fromUtf8(model.RawStringPtrAt(0, 0).c_str()));
EXPECT_EQ(QString("ab"), QString::fromUtf8(model.RawStringPtrAt(0, 1).c_str()));
EXPECT_EQ(QString("ab"), QString::fromUtf8(model.RawStringPtrAt(1, 0).c_str()));
EXPECT_EQ(QString("c"), QString::fromUtf8(model.RawStringPtrAt(1, 1).c_str()));
EXPECT_EQ(4, model.m_table.cellCountNonEmpty());
}
}
namespace
{
struct CsvItemModelReadFormatTestCase
{
const char* m_pszInput;
DFG_MODULE_NS(qt)::DFG_CLASS_NAME(CsvItemModel)::LoadOptions m_loadOptions;
};
}
// Test that saving uses the same settings as loading
TEST(dfgQt, CsvItemModel_readFormatUsageOnWrite)
{
typedef DFG_MODULE_NS(qt)::DFG_CLASS_NAME(CsvItemModel) ModelT;
typedef DFG_MODULE_NS(io)::DFG_CLASS_NAME(OmcByteStream)<std::string> StrmT;
typedef DFG_MODULE_NS(qt)::DFG_CLASS_NAME(CsvItemModel)::LoadOptions LoadOptionsT;
typedef DFG_ROOT_NS::DFG_CLASS_NAME(CsvFormatDefinition) CsvFormatDef;
#define DFG_TEMP_BOM DFG_UTF_BOM_STR_UTF8
CsvItemModelReadFormatTestCase testCases[] =
{
// Auto-detected separators with default enclosing char.
{ DFG_TEMP_BOM "a,b,\",c\"\n", LoadOptionsT() },
{ DFG_TEMP_BOM "a;b;\";c\"\n", LoadOptionsT() },
{ DFG_TEMP_BOM "a\tb\t\"\tc\"\n", LoadOptionsT() },
{ DFG_TEMP_BOM "a\x1f" "b\x1f" "\"\x1f" "c\"\n", LoadOptionsT() },
// Custom formats
{ DFG_TEMP_BOM "a2b2\"2c\"\n", CsvFormatDef('2', '"', DFG_MODULE_NS(io)::EndOfLineTypeN, DFG_MODULE_NS(io)::encodingUTF8) }, // Separator '2', enc '"', eol n
{ DFG_TEMP_BOM "a|b|^|c^\n", CsvFormatDef('|', '^', DFG_MODULE_NS(io)::EndOfLineTypeN, DFG_MODULE_NS(io)::encodingUTF8) }, // Separator '|', enc '^', eol n
{ DFG_TEMP_BOM "a|b|^|c^\r\n", CsvFormatDef('|', '^', DFG_MODULE_NS(io)::EndOfLineTypeRN, DFG_MODULE_NS(io)::encodingUTF8) }, // Separator '|', enc '^', eol rn
{ "\xE4" "|\xF6" "|^|c^\n", CsvFormatDef('|', '^', DFG_MODULE_NS(io)::EndOfLineTypeN, DFG_MODULE_NS(io)::encodingLatin1) }, // Separator '|', enc '^', eol n, encoding Latin1
// Note: EOL-handling is not tested thoroughly as parsing does not detect EOL (e.g. reading with \n will read \r\n fine, but does not automatically set read EOL as \r\n).
};
for (auto iter = std::begin(testCases); iter != std::end(testCases); ++iter)
{
ModelT model;
model.openFromMemory(iter->m_pszInput, DFG_MODULE_NS(str)::strLen(iter->m_pszInput), iter->m_loadOptions);
EXPECT_EQ(3, model.columnCount());
StrmT ostrm;
model.save(ostrm);
EXPECT_EQ(iter->m_pszInput, ostrm.container());
}
#undef DFG_TEMP_BOM
}
// Tests for SQLite handling (open, save)
TEST(dfgQt, CsvItemModel_SQLite)
{
// Testing that csv -> SQLite -> csv roundtrip is non-modifying given that sqlite -> csv is done with correct save options.
using namespace DFG_MODULE_NS(qt);
const char szFilePath[] = "testfiles/example3.csv";
const QString sSqlitePath = QString("testfiles/generated/csvItemModel_sqliteTest.sqlite3");
const QString sCsvFromSqlitePath = QString("testfiles/generated/csvItemModel_sqliteTest.csv");
const auto initialBytes = ::DFG_MODULE_NS(io)::fileToByteContainer<std::string>(szFilePath) + "\r\n";
QStringList columnNamesInCsv;
auto originalSaveOptions = CsvItemModel().getSaveOptions();
// Removing existing temp files
{
QFile::remove(sSqlitePath);
QFile::remove(sCsvFromSqlitePath);
}
// Reading from csv and exporting as SQLite
{
CsvItemModel model;
EXPECT_TRUE(model.openFile(szFilePath));
columnNamesInCsv = model.getColumnNames();
originalSaveOptions = model.getSaveOptions();
EXPECT_TRUE(model.exportAsSQLiteFile(sSqlitePath));
}
// Reading from SQLite and writing as csv
{
CsvItemModel model;
const auto tableNames = ::DFG_MODULE_NS(sql)::SQLiteDatabase::getSQLiteFileTableNames(sSqlitePath);
ASSERT_EQ(1, tableNames.size());
const auto columnNames = ::DFG_MODULE_NS(sql)::SQLiteDatabase::getSQLiteFileTableColumnNames(sSqlitePath, tableNames.front());
EXPECT_EQ(columnNamesInCsv, columnNames);
EXPECT_TRUE(model.openFromSqlite(sSqlitePath, QString("SELECT * FROM '%1';").arg(tableNames.front())));
EXPECT_TRUE(model.saveToFile(sCsvFromSqlitePath, originalSaveOptions));
}
const auto finalBytes = ::DFG_MODULE_NS(io)::fileToByteContainer<std::string>(qStringToFileApi8Bit(sCsvFromSqlitePath));
EXPECT_EQ(initialBytes, finalBytes);
EXPECT_TRUE(QFile::remove(sSqlitePath));
EXPECT_TRUE(QFile::remove(sCsvFromSqlitePath));
}
TEST(dfgQt, CsvItemModel_setSize)
{
using namespace DFG_MODULE_NS(qt);
CsvItemModel model;
EXPECT_FALSE(model.setSize(-1, -1));
EXPECT_TRUE(model.setSize(1, -1));
EXPECT_EQ(1, model.rowCount());
EXPECT_EQ(0, model.columnCount());
EXPECT_TRUE(model.setSize(-1, 1));
EXPECT_EQ(1, model.rowCount());
EXPECT_EQ(1, model.columnCount());
model.setDataNoUndo(0, 0, DFG_UTF8("abc"));
EXPECT_TRUE(model.setSize(10, 500));
EXPECT_EQ(10, model.rowCount());
EXPECT_EQ(500, model.columnCount());
EXPECT_TRUE(model.setSize(200, 30));
EXPECT_EQ(200, model.rowCount());
EXPECT_EQ(30, model.columnCount());
EXPECT_TRUE(model.setSize(1, 1));
EXPECT_FALSE(model.setSize(1, 1));
EXPECT_EQ("abc", model.rawStringViewAt(0, 0).asUntypedView());
EXPECT_TRUE(model.setSize(0, 0));
EXPECT_EQ(0, model.rowCount());
EXPECT_EQ(0, model.columnCount());
}
| 44.504 | 213 | 0.646773 | tc3t |
be71bf464a61cf0eb1e1cf0498d59102e0e8fbb0 | 2,100 | cpp | C++ | sword_Offer/15_MergeList/15_MergeList.cpp | bastamon/CodingInterviewChinese2 | 625c3907c6c5fe36d5cc1f2f91d8e062c90c932e | [
"BSD-3-Clause"
] | null | null | null | sword_Offer/15_MergeList/15_MergeList.cpp | bastamon/CodingInterviewChinese2 | 625c3907c6c5fe36d5cc1f2f91d8e062c90c932e | [
"BSD-3-Clause"
] | null | null | null | sword_Offer/15_MergeList/15_MergeList.cpp | bastamon/CodingInterviewChinese2 | 625c3907c6c5fe36d5cc1f2f91d8e062c90c932e | [
"BSD-3-Clause"
] | 1 | 2021-04-12T03:06:44.000Z | 2021-04-12T03:06:44.000Z | #include<iostream>
#include<cstdio>
#include<cstdlib>
#include<vector>
using namespace std;
typedef unsigned int uint32_t;
struct ListNode
{
int val;
struct ListNode *next;
ListNode(int x):val(x), next(nullptr)
{
}
};
class Solution
{
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if (pHead1 == nullptr && pHead2 == nullptr)
return nullptr;
else if (pHead1 == nullptr)
return pHead2;
else if (pHead2 == nullptr)
return pHead1;
ListNode* pHead = new ListNode(0);
ListNode* cur = pHead;
while (true)
{
if (pHead1 == nullptr)
{
cur->next = pHead2;
break;
}
else if (pHead2 == nullptr)
{
cur->next = pHead1;
break;
}
if (pHead1->val > pHead2->val)
swap(pHead1, pHead2);
cur->next = pHead1;
cur = cur->next;
pHead1 = pHead1->next;
}
return pHead->next;
}
//ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
//{
//
// if (pHead1 == nullptr &&pHead2 == nullptr)
// return nullptr;
// if (pHead1 == nullptr)
// return pHead2;
// if (pHead2 == nullptr)
// return pHead1;
// else
// {
// ListNode *p = pHead1;
// ListNode *q = (ListNode *)malloc(sizeof(ListNode));
// for (q = pHead1; q->next != nullptr;)
// q = q->next;
// q->next = pHead2;
// free(q);
// return insertionSortList(p);
// }
//}
//ListNode *insertionSortList(ListNode *head)
//{
// // IMPORTANT: Please reset any member data you declared, as
// // the same Solution instance will be reused for each test case.
// if (head == NULL || head->next == NULL)return head;
// ListNode *p = head->next, *pstart = new ListNode(0), *pend = head;
// pstart->next = head; //为了操作方便,添加一个头结点
// while (p != NULL)
// {
// ListNode *tmp = pstart->next, *pre = pstart;
// while (tmp != p && p->val >= tmp->val) //找到插入位置
// {
// tmp = tmp->next; pre = pre->next;
// }
// if (tmp == p)pend = p;
// else
// {
// pend->next = p->next;
// p->next = tmp;
// pre->next = p;
// }
// p = pend->next;
// }
// head = pstart->next;
// delete pstart;
// return head;
//}
}; | 19.626168 | 70 | 0.57381 | bastamon |
be7549bb9547b3ee1500cee7415bc14096aaa0f9 | 245 | cpp | C++ | engine/src/wolf.render/vulkan/w_queue.cpp | SiminBadri/Wolf.Engine | 3da04471ec26e162e1cbb7cc88c7ce37ee32c954 | [
"BSL-1.0",
"Apache-2.0",
"libpng-2.0"
] | 1 | 2020-07-15T13:14:26.000Z | 2020-07-15T13:14:26.000Z | engine/src/wolf.render/vulkan/w_queue.cpp | foroughmajidi/Wolf.Engine | f08a8cbd519ca2c70b1c8325250dc9af7ac4c498 | [
"BSL-1.0",
"Apache-2.0",
"libpng-2.0"
] | null | null | null | engine/src/wolf.render/vulkan/w_queue.cpp | foroughmajidi/Wolf.Engine | f08a8cbd519ca2c70b1c8325250dc9af7ac4c498 | [
"BSL-1.0",
"Apache-2.0",
"libpng-2.0"
] | null | null | null | #include "w_render_pch.h"
#include "w_graphics_device_manager.h"
#include "w_queue.h"
using namespace wolf::render::vulkan;
ULONG w_queue::release()
{
#ifdef __VULKAN__
this->queue = 0;
#endif
this->index = UINT32_MAX;
return 0;
}
| 16.333333 | 38 | 0.706122 | SiminBadri |
be7848a05dfa45d2f9b923655cfa196b96cf4459 | 2,542 | cpp | C++ | xs/src/Geometry.cpp | Lenbok/Slic3r | bc44611f241a5f1d7ab66f14ffc0b1f3d563fc59 | [
"CC-BY-3.0"
] | null | null | null | xs/src/Geometry.cpp | Lenbok/Slic3r | bc44611f241a5f1d7ab66f14ffc0b1f3d563fc59 | [
"CC-BY-3.0"
] | null | null | null | xs/src/Geometry.cpp | Lenbok/Slic3r | bc44611f241a5f1d7ab66f14ffc0b1f3d563fc59 | [
"CC-BY-3.0"
] | null | null | null | #include "Geometry.hpp"
#include "clipper.hpp"
#include <algorithm>
#include <map>
#include <vector>
namespace Slic3r { namespace Geometry {
static bool
sort_points (Point a, Point b)
{
return (a.x < b.x) || (a.x == b.x && a.y < b.y);
}
/* This implementation is based on Andrew's monotone chain 2D convex hull algorithm */
void
convex_hull(Points &points, Polygon* hull)
{
assert(points.size() >= 3);
// sort input points
std::sort(points.begin(), points.end(), sort_points);
int n = points.size(), k = 0;
hull->points.resize(2*n);
// Build lower hull
for (int i = 0; i < n; i++) {
while (k >= 2 && points[i].ccw(hull->points[k-2], hull->points[k-1]) <= 0) k--;
hull->points[k++] = points[i];
}
// Build upper hull
for (int i = n-2, t = k+1; i >= 0; i--) {
while (k >= t && points[i].ccw(hull->points[k-2], hull->points[k-1]) <= 0) k--;
hull->points[k++] = points[i];
}
hull->points.resize(k);
assert( hull->points.front().coincides_with(hull->points.back()) );
hull->points.pop_back();
}
/* accepts an arrayref of points and returns a list of indices
according to a nearest-neighbor walk */
void
chained_path(Points &points, std::vector<Points::size_type> &retval, Point start_near)
{
PointPtrs my_points;
std::map<Point*,Points::size_type> indices;
my_points.reserve(points.size());
for (Points::iterator it = points.begin(); it != points.end(); ++it) {
my_points.push_back(&*it);
indices[&*it] = it - points.begin();
}
retval.reserve(points.size());
while (!my_points.empty()) {
Points::size_type idx = start_near.nearest_point_index(my_points);
start_near = *my_points[idx];
retval.push_back(indices[ my_points[idx] ]);
my_points.erase(my_points.begin() + idx);
}
}
void
chained_path(Points &points, std::vector<Points::size_type> &retval)
{
if (points.empty()) return; // can't call front() on empty vector
chained_path(points, retval, points.front());
}
/* retval and items must be different containers */
template<class T>
void
chained_path_items(Points &points, T &items, T &retval)
{
std::vector<Points::size_type> indices;
chained_path(points, indices);
for (std::vector<Points::size_type>::const_iterator it = indices.begin(); it != indices.end(); ++it)
retval.push_back(items[*it]);
}
template void chained_path_items(Points &points, ClipperLib::PolyNodes &items, ClipperLib::PolyNodes &retval);
} }
| 29.55814 | 110 | 0.630606 | Lenbok |
be78a1bc0d677423a54f3642c06c75d64788e75f | 5,753 | cpp | C++ | examples/shape_visitor/shape_visitor.cpp | cesiumsolutions/dynamic_generic_visitor | da8fe928bf77270e1a64beae0051bfadba7ea256 | [
"MIT"
] | null | null | null | examples/shape_visitor/shape_visitor.cpp | cesiumsolutions/dynamic_generic_visitor | da8fe928bf77270e1a64beae0051bfadba7ea256 | [
"MIT"
] | null | null | null | examples/shape_visitor/shape_visitor.cpp | cesiumsolutions/dynamic_generic_visitor | da8fe928bf77270e1a64beae0051bfadba7ea256 | [
"MIT"
] | null | null | null | #include <shapes/Area.hpp>
#include <shapes/Circumference.hpp>
#include <visitor/DynamicVisitor.hpp>
#include <visitor/Visitable.hpp>
#include <boost/dll.hpp>
#include <boost/function.hpp>
#include <functional>
#include <iostream>
#include <vector>
struct NonShape
{
};
using ShapeVisitor = DynamicVisitor<float( float )>;
using VisitableShapePtr = VisitableUPtr<ShapeVisitor>;
using VisitableShapePtrVec = std::vector<VisitableShapePtr>;
ShapeVisitor makeAreaVisitor();
ShapeVisitor makeCircumferenceVisitor();
void loadPlugin( char const * const pluginFilename,
VisitableShapePtrVec & shapes,
ShapeVisitor & areaVisitor,
ShapeVisitor & circumferenceVisitor );
boost::dll::shared_library sharedLib;
int
main( int argc, char ** argv )
{
std::cout << "Running Generic DynamicVisitor with Plugin Example\n\n";
Rectangle rectangle { 2.0f, 3.0f };
Circle circle { 2.0f };
NonShape nonShape;
float scale = 2.0f;
// Populate heterogeneous list of concrete Shape objects
VisitableShapePtrVec shapes;
shapes.push_back( makeUniqueVisitable<ShapeVisitor>( rectangle ) );
shapes.push_back( makeUniqueVisitable<ShapeVisitor>( circle ) );
// Note: Now we CAN insert a NonShape into the list of shapes. But if no
// handler is registered for it, it will result in a runtime error/warning.
shapes.push_back( makeUniqueVisitable<ShapeVisitor>( nonShape ) );
ShapeVisitor areaVisitor = makeAreaVisitor();
ShapeVisitor circumferenceVisitor = makeCircumferenceVisitor();
if ( argc >= 2 ) {
loadPlugin( argv[1], shapes, areaVisitor, circumferenceVisitor );
}
// ==========================================================================
std::cout << "Area Visitor:\n";
// Visit the Shapes with the Area Visitor - checking valid accept result
float totalArea = 0.0f;
for ( auto const & shape : shapes ) {
auto result = shape->accept( areaVisitor, scale );
if ( result ) {
std::cout << " - Area for shape [" << shape->typeInfo().name()
<< "]: " << *result << '\n';
totalArea += *result;
}
else {
std::cerr << "WARNING: Unrecognized type: " << shape->typeInfo().name()
<< '\n';
}
}
float expectedArea =
scale * area( rectangle ) + scale * area( circle ) +
scale * ( ( 3.0f * 4.0f ) / 2.0f ); // right triangle 3,4,5
std::cout << " Visited Area: " << totalArea << '\n'
<< " Expected Area: " << expectedArea << '\n';
// ==========================================================================
std::cout << "\nCircumference Visitor:\n";
// Visit the Shapes with the Circumference Visitor - checking valid result
float totalCircumference = 0.0f;
for ( auto const & shape : shapes ) {
auto result = shape->accept( circumferenceVisitor, scale );
if ( result ) {
std::cout << " - Circumference for shape [" << shape->typeInfo().name()
<< "]: " << *result << '\n';
totalCircumference += *result;
}
else {
std::cerr << "WARNING: Unrecognized type: " << shape->typeInfo().name()
<< '\n';
}
}
float expectedCircumference =
scale * circumference( rectangle ) + scale * circumference( circle ) +
scale * ( 3.0f + 4.0f + 5.0f ); // Triangle{3,4,5}
std::cout << " Visited Circumference: " << totalCircumference << '\n'
<< " Expected Circumference: " << expectedCircumference << '\n';
}
ShapeVisitor
makeAreaVisitor()
{
// Add the area functions as handlers to the DynamicVisitor
ShapeVisitor areaVisitor;
areaVisitor.addHandler<Rectangle>(
[]( Rectangle const & r, float s ) -> float { return s * area( r ); } );
areaVisitor.addHandler<Circle>(
[]( Circle const & c, float s ) -> float { return s * area( c ); } );
return areaVisitor;
} // makeAreaVisitor
ShapeVisitor
makeCircumferenceVisitor()
{
// Add the circumference functions as handlers to the DynamicVisitor
ShapeVisitor circumferenceVisitor;
circumferenceVisitor.addHandler<Rectangle>(
[]( Rectangle const & r, float s ) -> float {
return s * circumference( r );
} );
circumferenceVisitor.addHandler<Circle>(
[]( Circle const & c, float s ) -> float {
return s * circumference( c );
} );
return circumferenceVisitor;
} // makeCircumferenceVisitor
void
loadPlugin( char const * const pluginFilename,
VisitableShapePtrVec & shapes,
ShapeVisitor & areaVisitor,
ShapeVisitor & circumferenceVisitor )
{
try {
std::cout << "Attempting to load Shape plugin from: " << pluginFilename
<< '\n';
sharedLib.load( pluginFilename );
using ShapeSig = void( VisitableShapePtrVec * );
using VisitorSig = void( ShapeVisitor * );
// Request plugin to fill the Shapes vector
boost::function<ShapeSig> fillShapes =
sharedLib.get<ShapeSig>( "fillShapes" );
if ( fillShapes ) {
fillShapes( &shapes );
}
// Request plugin to add handlers to the Area Visitor
boost::function<VisitorSig> fillAreaVisitor =
sharedLib.get<VisitorSig>( "fillAreaVisitor" );
if ( fillAreaVisitor ) {
fillAreaVisitor( &areaVisitor );
}
// Request plugin to add handlers to the Circumference Visitor
boost::function<VisitorSig> fillCircumferenceVisitor =
sharedLib.get<VisitorSig>( "fillCircumferenceVisitor" );
if ( fillCircumferenceVisitor ) {
fillCircumferenceVisitor( &circumferenceVisitor );
}
}
catch ( std::exception & e ) {
std::cerr << "EXCEPTION: " << e.what() << '\n';
}
} // loadPlugin
| 33.447674 | 79 | 0.615505 | cesiumsolutions |
be798bd7d9254706e90695873217fa9b42c15cad | 4,052 | cpp | C++ | ophidian/parser/Guide.cpp | sheiny/ophidian | 037ae44357e0093d60b379513615b467c1f841cf | [
"Apache-2.0"
] | 40 | 2016-04-22T14:42:42.000Z | 2021-05-25T23:14:23.000Z | ophidian/parser/Guide.cpp | sheiny/ophidian | 037ae44357e0093d60b379513615b467c1f841cf | [
"Apache-2.0"
] | 64 | 2016-04-28T21:10:47.000Z | 2017-11-07T11:33:17.000Z | ophidian/parser/Guide.cpp | eclufsc/openeda | 037ae44357e0093d60b379513615b467c1f841cf | [
"Apache-2.0"
] | 25 | 2016-04-18T19:31:48.000Z | 2021-05-05T15:50:41.000Z | #include <fstream>
#include <regex>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include "Guide.h"
#include "ParserException.h"
namespace ophidian::parser
{
Guide::Guide(const std::string &guide_file):
m_nets{}
{
read_file(guide_file);
}
void Guide::read_file(const std::string &guide_file)
{
auto line = std::string{};
auto file = std::ifstream{guide_file};
if (!file.is_open()){
throw exceptions::InexistentFile{};
}
auto integer = std::regex{"(\\+|-)?[[:digit:]]+"};
auto net = std::regex{"net[[:digit:]]+"};
auto metal = std::regex{"Metal[[:digit:]]+"};
auto words = std::vector<std::string>{};
while (getline(file, line))
{
boost::split(words, line, [](char c){return c == ' ';});
if(regex_match(words[0],net))
{
auto net_name = Guide::net_type::name_type{words[0]};
getline(file, line); //get "("
if(line.compare("(") != 0){
throw exceptions::GuideFileSyntaxError{};
}
words.clear();
auto regions = Guide::net_type::region_container_type{};
while (getline(file, line) && line.compare(")") != 0)
{
//get the regions belonging to NET
boost::split(words, line, [](char c){return c == ' ';});
if(words.size() != 5){
throw exceptions::GuideFileSyntaxError{};
}
if(!(regex_match(words[0], integer) && regex_match(words[1], integer) &&
regex_match(words[2], integer) && regex_match(words[3], integer) &&
regex_match(words[4], metal)) )
{
throw exceptions::GuideFileSyntaxError{};
}
auto x1 = static_cast<double>(boost::lexical_cast<int>(words[0]));
auto y1 = static_cast<double>(boost::lexical_cast<int>(words[1]));
auto x2 = static_cast<double>(boost::lexical_cast<int>(words[2]));
auto y2 = static_cast<double>(boost::lexical_cast<int>(words[3]));
auto origin = Guide::database_unit_point_type{
database_unit_type{x1},
database_unit_type{y1}
};
auto upperRight = Guide::database_unit_point_type{
database_unit_type{x2},
database_unit_type{y2}
};
regions.emplace_back(
Guide::net_type::region_type::layer_name_type{words[4]},
Guide::net_type::region_type::geometry_type{origin, upperRight}
);
}
if(line.compare(")") != 0){ //get ")"
throw exceptions::GuideFileSyntaxError();
}
m_nets.emplace_back(
std::move(net_name),
std::move(regions)
);
}
}
file.close();
}
Guide::net_container_type& Guide::nets() noexcept
{
return m_nets;
}
const Guide::net_container_type& Guide::nets() const noexcept
{
return m_nets;
}
const Guide::Net::name_type& Guide::Net::name() const noexcept
{
return m_name;
}
Guide::Net::region_container_type& Guide::Net::regions() noexcept
{
return m_regions;
}
const Guide::Net::region_container_type& Guide::Net::regions() const noexcept
{
return m_regions;
}
const Guide::Region::layer_name_type& Guide::Region::metal_layer_name() const noexcept
{
return m_metal;
}
const Guide::Region::geometry_type& Guide::Region::geometry() const noexcept
{
return m_region;
}
}
| 29.794118 | 92 | 0.498026 | sheiny |
be7db08de46a532fd979f06ed37d77136e1adf13 | 3,906 | cpp | C++ | Fractal/Fractal/src/core/systems/Engine.cpp | talislincoln/fractals | a9ed52e99b9737ce0a6bba715f61e4d122e37dd5 | [
"MIT"
] | 2 | 2016-09-22T16:11:17.000Z | 2016-09-22T16:11:55.000Z | Fractal/Fractal/src/core/systems/Engine.cpp | talislincoln/FractalGameEngine | a9ed52e99b9737ce0a6bba715f61e4d122e37dd5 | [
"MIT"
] | null | null | null | Fractal/Fractal/src/core/systems/Engine.cpp | talislincoln/FractalGameEngine | a9ed52e99b9737ce0a6bba715f61e4d122e37dd5 | [
"MIT"
] | null | null | null | #include "core\systems\Engine.h"
#include <iostream>
namespace fractal {
namespace fcore {
Engine::Engine(AbstractGame* game) :
m_game(game), m_isRunning(false),
m_maxFPS(60.0f)
{
}
Engine::~Engine()
{
}
int Engine::run()
{
if (!initialize())
{
printf("Engine failed to init.");
//Singleton<Logger>::getInstance().log(_T("Initialization of the engine failed."), LOGTYPE_ERROR);
//return INITIALIZATION_FAILED;
return -1;
}
// Seed the random number generator
// this will set the the random numbers to be always random (in theory?)
srand(SDL_GetTicks());
m_isRunning = true;
while (m_isRunning)
{
TIMER_SYSTEM->startFPS();
update();
draw();
printf("fps: %f\n", TIMER_SYSTEM->endFPS());
//create the fixed timestep
}
if (!shutDown())
{
//Singleton<Logger>::getInstance().log(_T("Shutdown of the engine failed."), LOGTYPE_ERROR);
//return SHUTDOWN_FAILED;
printf("failed to shutdown");
return -2;
}
return 0;
}
int Engine::initialize()
{
//Init the managers (Scene and System manager)
if (!createManagers())
return -1;
//Create instances for the different types of system
//and check if the system is null after creation
Logic* logic = LOGIC_SYSTEM;
if (logic == nullptr)
return 0;
Window* window = WINDOW_SYSTEM;
if (window == nullptr)
return 0; //error
Input* input = INPUT_SYSTEM;
if (input == nullptr)
return 0;
Graphics* graphics = GRAPHICS_SYSTEM;
if (graphics == nullptr)
return 0;
Timer* timer = TIMER_SYSTEM;
if (timer == nullptr)
return 0;
fphysics::PhysicsWorld* physics = PHYSICS_SYSTEM;
if (physics == nullptr)
return 0;
//HUDs system need to be after Graphics system
HUD* HUDs = HUD_SYSTEM;
if (HUDs == nullptr)
return 0;
if (!physics->initialize())
return 0;
if (!window->initialize())
return 0;
if (!graphics->initialize())
return 0;
if (!HUDs->initialize())
return 0;
input->bindInput(InputBinding(SDL_QUIT * 2, std::bind(&Engine::closeRequested, this), InputStateType::PRESSED));
if (!timer->initialize())
return 0;
logic->setGame(this->m_game);
if (!logic->initialize())
return 0;
if (!input->initialize())
return 0;
printf("input succeeded initializing");
return 1; //true
}
void Engine::draw()
{
Graphics* graphics = GRAPHICS_SYSTEM;
graphics->beginDraw();
for (IDrawable* system : fhelpers::Singleton<SystemManager>::getInstance().getDrawableSystems())
{
if (system->getCanDraw())
system->draw();
}
graphics->endDraw();
}
void Engine::update()
{
for (System* system : fhelpers::Singleton<SystemManager>::getInstance().getSystems())
system->update();
}
int Engine::shutDown()
{
if (!destroyManagers())
return -1;
return 1;
}
bool Engine::createManagers()
{
using namespace fhelpers;
//Singleton<WorldSettings>::createInstance(); //this holds the informations to configure the engine/game
Singleton<SystemManager>::createInstance();
Singleton<fscene::SceneManager>::createInstance();
//if (!Singleton<WorldSettings>::getInstance().initialize())
// return false;
if (!Singleton<SystemManager>::getInstance().initialize())
return false;
//scene manager is initialized in the Logic class
return true;
}
bool Engine::destroyManagers()
{
using namespace fhelpers;
using namespace fscene;
if (!Singleton<SystemManager>::getInstance().shutdown())
return false;
// scene manager is shut down in the Logic class
//if (!Singleton<WorldSettings>::getInstance().shutdown())
// return false;
Singleton<SystemManager>::destroyInstance();
Singleton<SceneManager>::destroyInstance();
//Singleton<WorldSettings>::destroyInstance();
return true;
}
}
}
| 21.94382 | 115 | 0.649002 | talislincoln |
be7faef478ae77d4ae662b434c89274f29ade1ad | 246 | cpp | C++ | main.cpp | marcomalabag/GDGRAPX-Assignment---Simple-Portrait | b51ce5634eb433de06e0f660f6d29e3728f1cca8 | [
"Unlicense"
] | null | null | null | main.cpp | marcomalabag/GDGRAPX-Assignment---Simple-Portrait | b51ce5634eb433de06e0f660f6d29e3728f1cca8 | [
"Unlicense"
] | null | null | null | main.cpp | marcomalabag/GDGRAPX-Assignment---Simple-Portrait | b51ce5634eb433de06e0f660f6d29e3728f1cca8 | [
"Unlicense"
] | null | null | null | #include <stdio.h>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include "AppWindow.h"
int main() {
AppWindow app; // AppWindow extends the Window class. The Window class is responsible for initializing the window
while (app.isRunning());
}
| 22.363636 | 115 | 0.723577 | marcomalabag |
be8d8a710e6fe5f151e7a82eec8095b71ae69f76 | 246 | hpp | C++ | include/RED4ext/Scripting/Natives/Generated/ent/RepellingShape.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 42 | 2020-12-25T08:33:00.000Z | 2022-03-22T14:47:07.000Z | include/RED4ext/Scripting/Natives/Generated/ent/RepellingShape.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 38 | 2020-12-28T22:36:06.000Z | 2022-02-16T11:25:47.000Z | include/RED4ext/Scripting/Natives/Generated/ent/RepellingShape.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 20 | 2020-12-28T22:17:38.000Z | 2022-03-22T17:19:01.000Z | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
namespace RED4ext
{
namespace ent {
enum class RepellingShape : uint32_t
{
Sphere = 0,
Capsule = 1,
};
} // namespace ent
} // namespace RED4ext
| 15.375 | 57 | 0.695122 | jackhumbert |
be90c7f5e6941c8162d45435f42eb60efb0282b1 | 16,436 | cc | C++ | Coordinator.cc | cafaro/DUDDSketch | 75660f3c689e1761ccf0f5a97accf82dc45cda57 | [
"MIT"
] | null | null | null | Coordinator.cc | cafaro/DUDDSketch | 75660f3c689e1761ccf0f5a97accf82dc45cda57 | [
"MIT"
] | null | null | null | Coordinator.cc | cafaro/DUDDSketch | 75660f3c689e1761ccf0f5a97accf82dc45cda57 | [
"MIT"
] | null | null | null | /********************************************************/
/* Distributed UDDSketch */
/* */
/* Coded by Catiuscia Melle */
/* */
/* April 8, 2021 */
/* */
/* */
/********************************************************/
#include "Coordinator.h"
FILE *logStartupConfiguration(PeersT *p, GraphT *g, InputT *data, double gamma, double NBOUND, unsigned long timestamp) {
if (!p || !g || !data) {
std::cout << "Failed to pass Params"<<std::endl;
return NULL;
}
FILE *fp = NULL;
char fname[FLEN];
snprintf(fname, FLEN, "Logs/%.3s-%d-%d-%.3s-%ld.log", g->gname, p->num_peers, p->rounds, data->dname, timestamp);
fp = fopen(fname, "w");
if (!fp){
std::cout << "Error on opening "<<fname<<std::endl;
return fp;
}
printGraphT(g, fp);
fprintf(fp, "----------\n");
printPeersT(p, fp);
fprintf(fp, "----------\n");
printInputT(data, fp, gamma, NBOUND);
fprintf(fp, "----------\n");
return fp;
}
void onClose(PeersT *p, GraphT *g, InputT *data) {
if (g){
freeGraphT(g);
}
}
int validityOfData(InputT *data, bool fdist, int dtype, bool fitems) {
int res = 0;
if (fdist)
{
switch (dtype){
case UNIFORM:
{
data->dtype = UNIFORM;
if (data->y <= data->x) {
std::cout<<"Error on setting the range [a,b) for Uniform distribution\n" << std::endl;
return EPARAMS;
}
#ifdef POSI
if (data->x < 0.0) {
std::cout<<"POSITIVE MODE: we only want to deal with positive numbers, set [a,b) in the positive range \n" << std::endl;
return EPARAMS;
}
#endif
}
break;
case EXPONENTIAL:
{
data->dtype = EXPONENTIAL;
if (data->x <= 0.0){
std::cout<<"Error on setting the lambda (λ) for Exponential distribution (it has to be (λ>0)\n" << std::endl;
return EPARAMS;
}
}
break;
case NORMAL:
{
data->dtype = NORMAL;
if (data->y==0.0) {
std::cout<<"Error on setting stddev (σ) for Normal distribution\n" <<std::endl;
return EPARAMS;
}
#ifdef POSI
if (data->x <= 0) {
std::cout<<"POSITIVE MODE: we only want to deal with positive numbers, set mean (μ) in the positive range \n" << std::endl;
return EPARAMS;
}
#endif
}
break;
case LOGN:
{
data->dtype = LOGN;
#ifdef POSI
if (data->x < 0) {
std::cout<<"POSITIVE MODE: we only want to deal with positive numbers, set mean (μ) in the positive range \n" << std::endl;
return EPARAMS;
}
#endif
}
break;
case CHIS:
{
data->dtype = CHIS;
if (data->x==0.0){
std::cout<<"Error on setting the degree of freedom for Chi-Squared distribution\n" <<std::endl;
return EPARAMS;
}
#ifdef POSI
if (data->x < 0) {
std::cout<<"POSITIVE MODE: we only want to deal with positive numbers, set degree of freedom in the positive range \n" << std::endl;
return EPARAMS;
}
#endif
}
break;
default:
data->dtype = UNKNOWN;
fdist = false;
std::cout<<"Error on setting input distribution type\n" <<std::endl;
break;
}//switch
getDistName(data->dtype, data->dname, NLEN);
}//fi fdist
if (!fdist && !data->fileflag) {
std::cout << "You must specify either the input binary file (-i) or the distribution to process (-d)!\n"<<std::endl;
return EPARAMS;
}
if (fdist && !fitems) {
data->inputLen = INPUTLEN;
std::cout << "\tNumber of items to process invalid or not configured ... Setting to default " << data->inputLen << std::endl;
}
if (data->fileflag) {
std::string name = data->filename;
std::size_t from_p = name.find_last_of("/");
std::size_t to_p = name.find_last_of(".");
memcpy(data->dname, name.substr(from_p+1, to_p-from_p-1).c_str(), sizeof(char)*NLEN);
}//fi
return res;
}
int getUserParams(int argc, char *argv[], PeersT *p, GraphT *g, InputT *data) {
int res = 0;
if (!p || !g || !data) {
std::cout << "Failed to pass Params"<<std::endl;
exit(EPARAMS);
}
initGraphT(g);
bool fgraph = false;
int gtype = -1;
initPeersT(p);
bool fpeers = false;
bool frounds = false;
int churnmodel = 0;
initInputData(data);
bool falpha = false;
bool fbound = false;
bool fdist = false;
int dtype = UNKNOWN;
bool fitems = false;
int c=0;
while ( (c = getopt(argc, argv, "G:S:R:P:O:M:C:F:a:b:i:d:x:y:n:h:")) != -1)
{
switch (c) {
case 'G':
{
gtype = atoi(optarg);
if (gtype < 1 || gtype > 4) {
std::cout << "Invalid graph type specification\n";
return EPARAMS;
}//fi gtype
fgraph = true;
switch (gtype) {
case BARABASI:
g->graph_type = BARABASI;
break;
case ERDOS:
g->graph_type = ERDOS;
break;
case GEOMETRIC:
g->graph_type = GEOMETRIC;
break;
case REGULAR:
g->graph_type = REGULAR;
break;
default:
g->graph_type = UNRECOGNIZED;
break;
}//switch
getGraphName(g->graph_type, g->gname, NLEN);
}
break;
case 'S':
g->initial_seed = strtoul(optarg, NULL, 10);
break;
case 'P':
p->num_peers = atoi(optarg);
if (p->num_peers <= 1) {
std::cout << "Invalid number of peers specification (at least 2)\n";
return EPARAMS;
}//fi
fpeers = true;
break;
case 'O':
p->fan_out = atoi(optarg);
if (p->fan_out < 1) {
std::cout << "Invalid fan-out number \n";
return EPARAMS;
}
break;
case 'R':
p->rounds = atoi(optarg);
if (p->rounds < 1) {
std::cout << "Invalid number of rounds specification\n";
return EPARAMS;
}
frounds = true;
break;
case 'C':
churnmodel = atoi(optarg);
if (churnmodel < 0 || churnmodel > 3) {
std::cout << "Churning model specification invalid, disable churning\n";
churnmodel = 0;
}//fi
break;
case 'F':
p->peer_failure_p = strtod(optarg,NULL);
break;
case 'a':
data->initial_alpha = strtod(optarg, NULL);
falpha = true;
break;
case 'b':
data->sketch_bound = atoi(optarg);
fbound = true;
break;
case 'i':
if (strlen(optarg) <= FLEN) {
snprintf(data->filename, FLEN-1,"%s", optarg);
data->fileflag = true;
}
break;
case 'd':
dtype = atoi(optarg);
if (dtype < 1 || dtype > 5) {
std::cout << "Invalid distribution model specification\n";
return EPARAMS;
}//fi
fdist = true;
break;
case 'x':
data->x = strtod(optarg, NULL);
break;
case 'y':
data->y = strtod(optarg, NULL);
break;
case 'n':
data->inputLen = strtoul(optarg, NULL, 10);
fitems = true;
break;
case 'h':
data->process_seed = strtoul(optarg, NULL, 10);
break;
default:
fprintf(stdout, "Incorrect parameter specification for: '%c'\n", optopt);
break;
}// switch
}//wend
if (!fgraph) {
std::cout << " You must provide the kind of graph to use, -G option\n" <<std::endl;
exit(EPARAMS);
}
if (!fpeers) {
p->num_peers = DEFAULT_PEERS;
std::cout << "\tNumber of peers in the network, -P option invalid or not configured ... Setting to default " << p->num_peers << std::endl;
}
if (p->fan_out < 1 || p->fan_out >= p->num_peers) {
p->fan_out = DEFAULT_FAN_OUT;
}
if (!frounds){
std::cout << " You must provide the number of gossip rounds, -R option\n" <<std::endl;
exit(EPARAMS);
}//fi rounds
switch (churnmodel)
{
case NOCHURN:
p->churntype = NOCHURN;
snprintf(p->churnname, FLEN-1, "No churning");
break;
case FAILSTOP:
p->churntype = FAILSTOP;
snprintf(p->churnname, FLEN-1, "Fail-and-Stop churning");
break;
case YAO:
p->churntype = YAO;
snprintf(p->churnname, FLEN-1, "Churning with Yao model");
break;
case YAOEXP:
p->churntype = YAOEXP;
snprintf(p->churnname, FLEN-1, "Churning with Yao model and Exponential rejoin");
break;
default:
p->churntype = NOCHURN;
snprintf(p->churnname, FLEN-1, "No churning");
break;
}//switch
if (validityOfData(data, fdist, dtype, fitems)){// == EPARAMS) {
std::cout << "Incorrect input data arguments!\n"<<std::endl;
return EPARAMS;
}
if (!falpha){
data->initial_alpha = ALPHA;
}
if (!fbound){
data->sketch_bound = DEFAULT_BOUND;
}
return res;
}
double GossipSketches(char *prefixName, int *executedRounds, PState *peers, GraphT *g, PeersT *p, ChurnEvent *churnEv, double *Qs, int Ns, InputT *data, unsigned long tSum, PVariate *dparams) {
Timer gossipTime;
igraph_vector_t neighbours[p->num_peers];
long neighboursCount[p->num_peers];
int failedPeersAtRound = 0;
int aliveP = 0;
int currentRound = 0;
int STEP = 5;
sampleConvergenceAtRound(currentRound, prefixName, Qs, Ns, p, tSum, peers, data, dparams);
startTimer(&gossipTime);
while(currentRound < p->rounds) {
failedPeersAtRound = updateNetAtRound(churnEv, currentRound, p->peer_failure_p);
aliveP = p->num_peers - churnEv->failedPeersCount;
fprintf(stderr, "Round %d, Failed at round: %d, Total Failed peers %d/%d, Joined %d\n", currentRound, failedPeersAtRound, churnEv->failedPeersCount, p->num_peers, aliveP);
for(int i = 0; i < p->num_peers; ++i) {
peers[i].prev_q = peers[i].q;
}
for (int peerI = 0; peerI < p->num_peers; ++peerI){
if (!churnEv->PeersFailed[peerI]) {
bool isChurnOn = churnEv->churnmode;
neighboursCount[peerI] = getPeerNeighbours(peerI, g, &neighbours[peerI], p->fan_out, churnEv->PeersFailed, p->num_peers, isChurnOn);
assert(neighboursCount[peerI] <= p->fan_out);
for(int j=0; j < neighboursCount[peerI]; ++j)
{
int peerJ = (int) igraph_vector_e(&neighbours[peerI], j);
int epoch = (peers[peerI].epoch < peers[peerJ].epoch)?peers[peerJ].epoch:peers[peerI].epoch;
peers[peerI].epoch = peers[peerJ].epoch = epoch+1;
double mean = (peers[peerI].q + peers[peerJ].q)/2.0;
peers[peerI].q = peers[peerJ].q = mean;
double mergeTime = 0;
mergeSketches(peerI, &(peers[peerI].L), peerJ, &(peers[peerJ].L), &mergeTime, peers[peerJ].hasConverged );
}//for push-pull with j
igraph_vector_destroy(&neighbours[peerI]);
}//fi
}//for peerI
++currentRound;
if (currentRound%STEP == 0){
sampleConvergenceAtRound(currentRound, prefixName, Qs, Ns, p, tSum, peers, data, dparams);
}
}//wend currentRound
stopTimer(&gossipTime);
//*** n. End gossiping
double seconds = getElapsedSeconds(&gossipTime);
if (executedRounds) {
*executedRounds = currentRound;
}
return seconds;
}
void sampleConvergenceAtRound(int sampledRound, char *PrefixName, double *Qs, int Ns, PeersT *peers, unsigned long tSum, PState *pstates, InputT *data, PVariate *dparams) {
char outname[FLEN];
snprintf(outname, FLEN, "CSV/Round-%d-%s.csv", sampledRound, PrefixName);
FILE *out = fopen(outname, "w");
if (!out) {
std::cout << "Error opening "<<outname<<std::endl;
} else {
double npeers = (double) peers->num_peers;
fprintf(out, "ID,EstPeers,relErrP,Dtype,ParamX,ParamY,PLen,Bound,Collps,IAlpha,FAlpha,EstCount,ExactCount,errCount,");
logHeader(out, Qs, Ns);
fprintf(out, "\n");
for(int id = 0; id < peers->num_peers; ++id) {
double estP = 0, errP = 0;
if (pstates[id].q > 0){
estP = 1.0/pstates[id].q;
} else {
estP = 1;
}
errP = std::abs(estP - npeers)/npeers;
double estItems = (pstates[id].L.negapop+pstates[id].L.posipop)*estP;
double CountErr = std::abs(estItems - tSum)/(double)tSum;
fprintf(out, "%d,%.2f,%.6f,", pstates[id].peerId, estP, errP);
fprintf(out, "%s,%.6f,%.6f,%ld,", data->dname, dparams[id].x, dparams[id].y, dparams[id].len);
fprintf(out, "%d,%d,%.6f,%.6f,", pstates[id].L.bound, pstates[id].L.collapses, data->initial_alpha, pstates[id].L.alpha);
fprintf(out, "%.3f,%lu,%.3f,", estItems, tSum, CountErr);
logAvgQuantiles(Qs, Ns, &pstates[id].L, out);
fprintf(out,"\n");
}
fclose(out);
out = NULL;
}//fi
}
| 30.047532 | 193 | 0.435994 | cafaro |
be94b3e1328e0f7937890e5f6240c560ece3c0c1 | 1,006 | cpp | C++ | ACM/2018-2019 Summer UESTC ACM Training/UESTC 2019 Summer Training #7/G.cpp | lyh543/Some-Codes | 2b295338f802e71c6b613350f1b6e8299856780f | [
"MIT"
] | 3 | 2020-06-05T08:29:16.000Z | 2021-12-09T05:44:54.000Z | ACM/2018-2019 Summer UESTC ACM Training/UESTC 2019 Summer Training #7/G.cpp | lyh543/Some-Codes | 6648d57be5cc9642d623563b35780446ed986edc | [
"MIT"
] | null | null | null | ACM/2018-2019 Summer UESTC ACM Training/UESTC 2019 Summer Training #7/G.cpp | lyh543/Some-Codes | 6648d57be5cc9642d623563b35780446ed986edc | [
"MIT"
] | 1 | 2020-09-15T14:50:31.000Z | 2020-09-15T14:50:31.000Z | #include<bits/stdc++.h>
#define ld long double
#define ll long long
#define infty 0x3fffffffll
#define fastio ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
using namespace std;
typedef pair<ll, ll> P;
const int maxn = 1e5+5;
P operator + (P a, P b)
{
return make_pair(a.first + b.first, a.second + b.second);
}
P operator * (ll t, P a)
{
return make_pair(t*a.first, t*a.second);
}
ll abs(P a)
{
return abs(a.first) + abs(a.second);
}
P seq[maxn];
map<char, P> m;
signed main()
{
fastio;
m['U'] = make_pair(0, 1);
m['D'] = make_pair(0, -1);
m['L'] = make_pair(-1, 0);
m['R'] = make_pair(1, 0);
int T;
cin >> T;
while (T--)
{
ll n, k, ans = 0;
string s;
cin >> n >> k >> s;
seq[0] = make_pair(0,0);
for (int i = 1; i <= n; i++)
{
seq[i] = m[s[i-1]] + seq[i - 1];
ans = max(ans, abs(seq[i]));
}
for (int i = 1; i <= n; i++)
{
ans = max(ans, abs((k -1)* seq[n] + seq[i]));
}
cout << ans << endl;
}
}
| 17.649123 | 63 | 0.513917 | lyh543 |
be98c0be0a4ec14805f6a73fa59a7d234602899a | 3,086 | cpp | C++ | src/fps_map/local_map.cpp | Lab-RoCoCo/fps_mapper | 376e557c8f5012e05187fe85ee3f4044f99f944a | [
"BSD-3-Clause"
] | 1 | 2017-12-01T14:57:16.000Z | 2017-12-01T14:57:16.000Z | src/fps_map/local_map.cpp | Lab-RoCoCo/fps_mapper | 376e557c8f5012e05187fe85ee3f4044f99f944a | [
"BSD-3-Clause"
] | null | null | null | src/fps_map/local_map.cpp | Lab-RoCoCo/fps_mapper | 376e557c8f5012e05187fe85ee3f4044f99f944a | [
"BSD-3-Clause"
] | null | null | null | #include "local_map.h"
#include "GL/gl.h"
#include "gl_helpers/opengl_primitives.h"
#include <iostream>
namespace fps_mapper {
using namespace std;
LocalMap::LocalMap(const Eigen::Isometry3f& transform,
int id,
boss::IdContext* context) : MapNode(transform, id, context){
}
LocalMap::~LocalMap(){
_cloud_ref.set(0);
}
void LocalMap::serialize(boss::ObjectData& data, boss::IdContext& context) {
MapNode::serialize(data,context);
boss::ObjectData * blobData=new boss::ObjectData();
data.setField("cloud", blobData);
_cloud_ref.serialize(*blobData,context);
boss::ArrayData* nodesArray = new boss::ArrayData;
for (MapNodeList::iterator it = _nodes.begin(); it!=_nodes.end(); it++){
MapNode* node=it->get();
nodesArray->add(new boss::PointerData(node));
}
data.setField("nodes", nodesArray);
boss::ArrayData* relationsArray = new boss::ArrayData;
for (BinaryNodeRelationSet::iterator it = _relations.begin(); it!=_relations.end(); it++){
BinaryNodeRelation* rel=it->get();
relationsArray->add(new boss::PointerData(rel));
}
data.setField("relations", relationsArray);
}
void LocalMap::deserialize(boss::ObjectData& data, boss::IdContext& context) {
MapNode::deserialize(data,context);
// deserialize the cloud
boss::ObjectData * blobData = static_cast<boss::ObjectData *>(data.getField("cloud"));
_cloud_ref.deserialize(*blobData,context);
boss::ArrayData& nodesArray=data.getField("nodes")->getArray();
for (size_t i =0; i< nodesArray.size(); i++){
boss::ValueData& v = nodesArray[i];
boss::Identifiable* id = v.getPointer();
MapNode* n = dynamic_cast<MapNode*>(id);
_nodes.addElement(n);
}
boss::ArrayData& relationsArray=data.getField("relations")->getArray();
for (size_t i =0; i< relationsArray.size(); i++){
boss::ValueData& v = relationsArray[i];
boss::Identifiable* id = v.getPointer();
BinaryNodeRelation* r = dynamic_cast<BinaryNodeRelation*>(id);
}
}
void LocalMap::draw(DrawAttributesType attributes, int name){
if (! (attributes&ATTRIBUTE_SHOW))
return;
if (name>-1)
glPushName(name);
glPushMatrix();
GLHelpers::glMultMatrix(_transform);
// draw the cloud, if the local map is selected
if (attributes&ATTRIBUTE_SELECTED) {
cloud()->draw(attributes);
if( ! (attributes&ATTRIBUTE_HIDE_REF) ) {
_nodes.draw(attributes);
for (BinaryNodeRelationSet::iterator it = _relations.begin(); it!=_relations.end(); it++) {
(*it)->draw();
}
}
}
// draw the reference system coordinates, unless explicitly hidden
if( ! (attributes&ATTRIBUTE_HIDE_REF) ) {
glPushMatrix();
glScalef(0.2, 0.2, 0.2);
glPushAttrib(GL_COLOR);
GLHelpers::drawReferenceSystem();
glPopAttrib(); // GL_COLOR
glPopMatrix();
}
glPopMatrix();
if (name>-1)
glPopName();
}
BOSS_REGISTER_CLASS(LocalMap);
}
| 28.841121 | 99 | 0.639339 | Lab-RoCoCo |
be9e13daa6e50c1daf8efc41ba5a4ea0c671e43a | 13,998 | cpp | C++ | imagecore/image/colorpalette.cpp | shahzadlone/vireo | 73e7176d0255a9506b009c9ab8cc532ecd86e98c | [
"MIT"
] | 890 | 2017-12-15T17:55:42.000Z | 2022-03-27T07:46:49.000Z | imagecore/image/colorpalette.cpp | shahzadlone/vireo | 73e7176d0255a9506b009c9ab8cc532ecd86e98c | [
"MIT"
] | 29 | 2017-12-16T21:49:08.000Z | 2021-09-08T23:04:10.000Z | imagecore/image/colorpalette.cpp | shahzadlone/vireo | 73e7176d0255a9506b009c9ab8cc532ecd86e98c | [
"MIT"
] | 88 | 2017-12-15T19:29:49.000Z | 2022-03-21T00:59:29.000Z | /*
* MIT License
*
* Copyright (c) 2017 Twitter
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "colorpalette.h"
#include "imagecore/utils/mathutils.h"
#include "imagecore/utils/securemath.h"
#include "imagecore/formats/format.h"
#include "imagecore/image/image.h"
#include "imagecore/image/rgba.h"
#include "imagecore/image/resizecrop.h"
#include "imagecore/image/colorspace.h"
#include <algorithm>
#include <cstdlib>
namespace imagecore {
using namespace std;
// Histogram based algorithm
#define INDEX_HIST(x,y,z) ((z) + (y) * kHistTotalSize + (x) * kHistTotalSize * kHistTotalSize)
int wrappedDist(int ha, int hb, int dist) {
return abs(ha - hb) % dist;
}
struct WeightedColor {
RGBA color;
float pct;
bool operator<(const WeightedColor& color) const {
return pct < color.pct;
}
};
static int computeHistogram(ImageRGBA* frameImage, RGBA* ccolors, double* colorPct, int numColors)
{
unsigned int width = frameImage->getWidth();
unsigned int height = frameImage->getHeight();
bool useHsv = numColors == 1;
int kHistSize = useHsv ? 16 : 24;
const int searchSizeX = useHsv ? 1 : 4;
const int searchSizeY = useHsv ? 2 : 1;
const int searchSizeZ = useHsv ? 4 : 1;
const int kHistPadding = max(searchSizeX, max(searchSizeY, searchSizeZ));
const int kHistTotalSize = kHistSize + kHistPadding * 2;
float* histogramAlloc = (float*)calloc(kHistTotalSize * kHistTotalSize * kHistTotalSize, sizeof(float));
float* histogram = histogramAlloc + (kHistPadding + kHistPadding * kHistTotalSize + kHistPadding * kHistTotalSize * kHistTotalSize);
float3* floatImage = (float3*)malloc(width * height * sizeof(float3));
unsigned int framePitch;
uint8_t* buffer = frameImage->lockRect(width, height, framePitch);
START_CLOCK(ColorConversionHistogram);
for( unsigned int y = 0; y < height; y++ ) {
for( unsigned int x = 0; x < width; x++ ) {
const RGBA* rgba = (RGBA*)(&buffer[y * framePitch + x * 4]);
if (useHsv) {
floatImage[y * width + x] = ColorSpace::srgbToHsv(ColorSpace::byteToFloat(*rgba));
} else {
floatImage[y * width + x] = ColorSpace::srgbToLab(ColorSpace::byteToFloat(*rgba));
}
if( rgba->a > 128 ) {
const float3& c = floatImage[y * width + x];
unsigned int hx = clamp(0, kHistSize - 1, (int)(c.x * (float)kHistSize));
unsigned int hy = clamp(0, kHistSize - 1, (int)(c.y * (float)kHistSize));
unsigned int hz = clamp(0, kHistSize - 1, (int)(c.z * (float)kHistSize));
int idx = INDEX_HIST(hx, hy, hz);
float saturation = sqrtf(((c.y - 0.5f) * (c.y - 0.5f) + (c.z - 0.5f) * (c.z - 0.5f)));
float luminance = fabs(c.x - 0.5f);
histogram[idx] += useHsv ? 1.0f : fmaxf(luminance, saturation);
}
}
}
END_CLOCK(ColorConversionHistogram);
START_CLOCK(Search);
std::vector<int> vAreaMaxX;
std::vector<int> vAreaMaxY;
std::vector<int> vAreaMaxZ;
for( int i = 0; i < numColors; i++ ) {
int areaMaxX = 0;
int areaMaxY = 0;
int areaMaxZ = 0;
float maxAreaSum = 0.0f;
for( int x = 0; x < kHistSize; x++ ) {
for( int y = 0; y < kHistSize; y++ ) {
for( int z = 0; z < kHistSize; z++ ) {
float sum = 0;
for( int sx = -searchSizeX; sx <= searchSizeX; sx++ ) {
int wrappedX = x + sx;
if (useHsv) {
// Hue in HSV is circular, so we wrap instead of clamp.
if( wrappedX >= kHistSize ) {
wrappedX = wrappedX - kHistSize;
} else if( wrappedX < 0 ) {
wrappedX = kHistSize + wrappedX - 1;
}
}
for( int sy = -searchSizeY; sy <= searchSizeY; sy++ ) {
int index = INDEX_HIST(wrappedX, y + sy, z);
for( int sz = -searchSizeZ; sz <= searchSizeZ; sz++ ) {
sum += histogram[index + sz];
}
}
}
if( sum > maxAreaSum ) {
areaMaxX = x;
areaMaxY = y;
areaMaxZ = z;
maxAreaSum = sum;
}
}
}
}
if( maxAreaSum > 0.0f ) {
vAreaMaxX.push_back(areaMaxX);
vAreaMaxY.push_back(areaMaxY);
vAreaMaxZ.push_back(areaMaxZ);
if( numColors > 1 ) {
for( int sx = -searchSizeX; sx <= searchSizeX; sx++ ) {
int wrappedX = areaMaxX + sx;
if( useHsv ) {
// Hue in HSV is circular, so we wrap instead of clamp.
if( wrappedX >= kHistSize ) {
wrappedX = wrappedX - kHistSize;
} else if( wrappedX < 0 ) {
wrappedX = kHistSize + wrappedX - 1;
}
}
for( int sy = -searchSizeY; sy <= searchSizeY; sy++ ) {
int index = INDEX_HIST(wrappedX, areaMaxY + sy, areaMaxZ);
for( int sz = -searchSizeZ; sz <= searchSizeZ; sz++ ) {
histogram[index + sz] = -fabs(histogram[index + sz]);
}
}
}
}
}
}
END_CLOCK(Search);
START_CLOCK(Sort);
int numOutColors = 0;
WeightedColor* weightedColors = (WeightedColor*)malloc(numColors * sizeof(WeightedColor));
SECURE_ASSERT(vAreaMaxX.size() == vAreaMaxY.size() && vAreaMaxX.size() == vAreaMaxZ.size());
for( int m = 0; m < min((int)vAreaMaxX.size(), numColors); m++ ) {
int areaMaxX = vAreaMaxX[m];
int areaMaxY = vAreaMaxY[m];
int areaMaxZ = vAreaMaxZ[m];
std::vector<unsigned char> rDim;
std::vector<unsigned char> gDim;
std::vector<unsigned char> bDim;
std::vector<RGBA> colors;
int rAvg = 0;
int gAvg = 0;
int bAvg = 0;
int mmax = 0;
for( unsigned int y = 0; y < height; y++ ) {
for( unsigned int x = 0; x < width; x++ ) {
const RGBA* rgba = (RGBA*)(&buffer[y * framePitch + x * 4]);
const float3& c = floatImage[y * width + x];
int hx = clamp(0, kHistSize - 1, (int)(c.x * (float)kHistSize));
int hy = clamp(0, kHistSize - 1, (int)(c.y * (float)kHistSize));
int hz = clamp(0, kHistSize - 1, (int)(c.z * (float)kHistSize));
if( (useHsv && rgba->a > 128 && (wrappedDist(hx, areaMaxX, kHistSize) <= searchSizeX && abs(hy - areaMaxY) <= searchSizeY && abs(hz - areaMaxZ) <= searchSizeZ))
|| (!useHsv && rgba->a > 128 && (abs(hx - areaMaxX) <= searchSizeX && abs(hy - areaMaxY) <= searchSizeY && abs(hz - areaMaxZ) <= searchSizeZ))) {
rAvg += rgba->r;
gAvg += rgba->g;
bAvg += rgba->b;
rDim.push_back(rgba->r);
gDim.push_back(rgba->g);
bDim.push_back(rgba->b);
colors.push_back(*rgba);
mmax++;
}
}
}
double pct = (double)colors.size() / (double)(width * height);
if( pct > 0.001f) {
std::sort(rDim.begin(), rDim.end());
std::sort(gDim.begin(), gDim.end());
std::sort(bDim.begin(), bDim.end());
int medianR = rDim.size() > 0 ? rDim.at(rDim.size() / 2) : 0;
int medianG = gDim.size() > 0 ? gDim.at(gDim.size() / 2) : 0;
int medianB = bDim.size() > 0 ? bDim.at(bDim.size() / 2) : 0;
RGBA outColor(0, 0, 0, 255);
int closestColorDist = 10000000;
for( unsigned i = 0; i < colors.size(); i++ ) {
const RGBA& c = colors.at(i);
float dr = c.r - medianR;
float dg = c.g - medianG;
float db = c.b - medianB;
float dist = (dr * dr) + (dg * dg) + (db * db);
if( dist < closestColorDist ) {
weightedColors[numOutColors].color = c;
weightedColors[numOutColors].pct = pct;
closestColorDist = dist;
if( dist == 0 ) {
break;
}
}
}
numOutColors++;
}
}
std::sort(weightedColors, weightedColors + numOutColors);
for( int i = 0; i < numOutColors; i++ ) {
ccolors[i] = weightedColors[numOutColors - i - 1].color;
colorPct[i] = weightedColors[numOutColors - i - 1].pct;
}
END_CLOCK(Sort);
free(weightedColors);
weightedColors = NULL;
free(floatImage);
floatImage = NULL;
free(histogramAlloc);
histogramAlloc = NULL;
return numOutColors;
}
// Kmeans based algorithm
#define MAX_ITERATIONS 100
#define DELTA_LIMIT 0.00000001
struct colorSample {
RGBA rgba;
float3 lab;
int label = -1;
uint64_t clusterSize = 0;
colorSample() {}
colorSample(RGBA rgba, float3 lab, int label, int size) : rgba(rgba), lab(lab), label(label), clusterSize(size) {}
colorSample& operator=(const colorSample& s)
{
rgba = s.rgba;
lab = s.lab;
label = s.label;
clusterSize = s.clusterSize;
return *this;
}
bool operator<(const colorSample& color) const {
return clusterSize < color.clusterSize;
}
};
static vector<colorSample> initializeCentroids(unsigned int numCluster, vector<colorSample>& samples) {
vector<colorSample> centroids;
uint64_t size = samples.size();
// initialize using random samples in the image
srand(817504253); // feed a fixed prime seed for deterministic results and easy testing
for( unsigned int k = 0; k < numCluster; k++ ) {
uint64_t randomIdx = rand() % size;
unsigned int count = 0;
for( unsigned int i = 0; i < k; i++ ) {
while( samples[randomIdx].rgba == centroids[i].rgba && count < 10 ) { // get rid of same colors as initial centroids, but do not try too hard
randomIdx = rand() % size;
count++;
}
}
samples[randomIdx].label = k;
samples[randomIdx].clusterSize++;
centroids.push_back(samples[randomIdx]);
}
return centroids;
}
static float squaredDist(const colorSample& color1, const colorSample& color2) {
float dx = color1.lab.x - color2.lab.x;
float dy = color1.lab.y - color2.lab.y;
float dz = color1.lab.z - color2.lab.z;
return dx * dx + dy * dy + dz * dz;
}
static void sampleLabeling(vector<colorSample> &samples, vector<colorSample> ¢roids) {
for( colorSample& sample : samples ) {
float currMinDist = std::numeric_limits<float>::max();
for( colorSample& centroid : centroids ) {
float currDist = squaredDist(sample, centroid);
if( currDist < currMinDist ) {
currMinDist = currDist;
sample.label = centroid.label;
}
}
centroids[sample.label].clusterSize++;
}
for( colorSample& sample : samples ) {
sample.clusterSize = centroids[sample.label].clusterSize;
}
}
static vector<colorSample> getCentroids(vector<colorSample> samples, unsigned int numCluster) {
vector<float3> sums(numCluster, 0);
vector<uint64_t> clusterSize(numCluster, 0);
for( colorSample& sample : samples ){
sums[sample.label].x += sample.lab.x;
sums[sample.label].y += sample.lab.y;
sums[sample.label].z += sample.lab.z;
clusterSize[sample.label] = sample.clusterSize;
}
vector<colorSample> centroids;
for( unsigned int k = 0; k < numCluster; k++ ) {
float3 lab(sums[k].x / clusterSize[k], sums[k].y / clusterSize[k], sums[k].z / clusterSize[k]);
RGBA rgba = ColorSpace::floatToByte(ColorSpace::labToSrgb(lab));
centroids.push_back(colorSample(rgba, lab, k, 0));
}
return centroids;
}
static int computeKmeans(imagecore::ImageRGBA *frameImage, unsigned int numCluster, RGBA* colorPalette, double* colorPct) {
SECURE_ASSERT(frameImage != NULL);
SECURE_ASSERT(numCluster >= 2 && numCluster <= 10); // don't want large numbers for k
unsigned int width = frameImage->getWidth();
unsigned int height = frameImage->getHeight();
vector<colorSample> samples;
unsigned int framePitch;
uint8_t* buffer = frameImage->lockRect(width, height, framePitch);
// get all the samples (whose alpha value is > 128)
for( unsigned int y = 0; y < height; y++ ) {
for( unsigned int x = 0; x < width; x++ ) {
const RGBA rgba = *(RGBA*)(&buffer[y * framePitch + x * 4]);
if( rgba.a > 128 ) {
float3 lab = ColorSpace::srgbToLab(ColorSpace::byteToFloat(rgba));
colorSample sample(rgba, lab, -1, 0);
samples.push_back(sample);
}
}
}
SECURE_ASSERT(samples.size() > 0 && samples.size() <= width * height);
vector<colorSample> centroids = initializeCentroids(numCluster, samples);
// main loop for k-means clustering
for( unsigned int iteration = 0; iteration < MAX_ITERATIONS; iteration++ ) {
sampleLabeling(samples, centroids);
vector<colorSample> newCentroids = getCentroids(samples, numCluster);
//if newCentroids are closed enough to old centroids, stop iteration
bool closeEnough = true;
for( unsigned int k = 0; k < numCluster; k++ ) {
if( squaredDist(centroids[k], newCentroids[k]) > DELTA_LIMIT ) {
closeEnough = false;
}
}
if( closeEnough ) {
break;
}
centroids = newCentroids;
}
sort(centroids.begin(), centroids.end());
unsigned int totalSize = width * height;
unsigned int numOutColors = 0;
colorPalette[numOutColors] = centroids[numCluster-1].rgba;
colorPct[numOutColors] = (double)centroids[numCluster - 1].clusterSize / totalSize;
for( int k = numCluster - 2; k >= 0; k-- ) {
double pct = (double)centroids[k].clusterSize / totalSize;
if( pct < 0.001f) {
continue;
}
if( centroids[k].rgba == colorPalette[numOutColors] ) {
colorPct[numOutColors] += pct;
} else {
numOutColors++;
colorPalette[numOutColors] = centroids[k].rgba;
colorPct[numOutColors] = pct;
}
}
return numOutColors + 1;
}
int ColorPalette::compute(ImageRGBA* image, RGBA* outColors, double* colorPct, int maxColors, EColorsAlgorithm algorithm) {
if( algorithm == kColorAlgorithm_Histogram ) {
return computeHistogram(image, outColors, colorPct, maxColors);
} else if( algorithm == kColorAlgorithm_KMeans ) {
return computeKmeans(image, maxColors, outColors, colorPct);
}
return 0;
}
}
| 32.553488 | 164 | 0.65788 | shahzadlone |
bea9c06deb3dd0d25c237efb67d158d958cb257a | 2,065 | cpp | C++ | Advent of Code/2021/09_1_smoke_basin.cpp | aleksi-kangas/competitive-programming | 149c38158c889b3417034b5d9d6cd4517f937447 | [
"MIT"
] | null | null | null | Advent of Code/2021/09_1_smoke_basin.cpp | aleksi-kangas/competitive-programming | 149c38158c889b3417034b5d9d6cd4517f937447 | [
"MIT"
] | null | null | null | Advent of Code/2021/09_1_smoke_basin.cpp | aleksi-kangas/competitive-programming | 149c38158c889b3417034b5d9d6cd4517f937447 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <bitset>
#include <climits>
#include <cmath>
#include <deque>
#include <functional>
#include <iostream>
#include <iterator>
#include <map>
#include <memory>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
using ll = long long;
vector<vector<int>> ParseInput() {
vector<vector<int>> m;
string s;
while (getline(cin, s) && !s.empty()) {
vector<int> row;
row.reserve(s.size());
for (char c : s) {
row.push_back(c - '0');
}
m.push_back(move(row));
}
return m;
}
int Solve() {
vector<vector<int>> heights = ParseInput();
int n = static_cast<int>(heights.size());
int m = static_cast<int>(heights[0].size());
vector<vector<int>> down(n, vector<int>(m, 0));
for (int i = n - 2; i >= 0; --i) {
for (int j = 0; j < m; ++j) {
if (heights[i][j] >= heights[i + 1][j]) {
down[i][j] = down[i + 1][j] + 1;
}
}
}
vector<vector<int>> up(n, vector<int>(m, 0));
for (int i = 1; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (heights[i][j] >= heights[i - 1][j]) {
up[i][j] = up[i - 1][j] + 1;
}
}
}
vector<vector<int>> left(n, vector<int>(m, 0));
for (int i = 0; i < n; ++i) {
for (int j = 1; j < m; ++j) {
if (heights[i][j] >= heights[i][j - 1]) {
left[i][j] = left[i][j - 1] + 1;
}
}
}
vector<vector<int>> right(n, vector<int>(m, 0));
for (int i = 0; i < n; ++i) {
for (int j = m - 2; j >= 0; --j) {
if (heights[i][j] >= heights[i][j + 1]) {
right[i][j] = right[i][j + 1] + 1;
}
}
}
int risk_sum = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (down[i][j] == 0 && up[i][j] == 0 && left[i][j] == 0 && right[i][j] == 0) {
risk_sum += heights[i][j] + 1;
}
}
}
return risk_sum;
}
int main() {
int risk_sum = Solve();
cout << risk_sum << endl;
}
| 21.510417 | 84 | 0.502179 | aleksi-kangas |
beb157cd2d9ef531f5d298b710051a788c7e8fac | 6,010 | cpp | C++ | src/pam/pam.cpp | merelabs/mere-auth-lib | f4b09375563094af74ba937b4c2dca440c0d4431 | [
"BSD-2-Clause"
] | 2 | 2021-12-09T22:44:39.000Z | 2022-03-26T16:29:50.000Z | src/pam/pam.cpp | merelabs/mere-auth | f4b09375563094af74ba937b4c2dca440c0d4431 | [
"BSD-2-Clause"
] | null | null | null | src/pam/pam.cpp | merelabs/mere-auth | f4b09375563094af74ba937b4c2dca440c0d4431 | [
"BSD-2-Clause"
] | null | null | null | #include "pam.h"
#include <iostream>
Mere::Auth::PAM::~PAM()
{
}
Mere::Auth::PAM::PAM(const std::string &service, int flags)
: m_flags(flags),
m_service(service),
handler(NULL)
{
}
int Mere::Auth::PAM::login(const Applicant &applicant)
{
const struct pam_conv converse = { handshake, (void *) &applicant };
// why target user = NULL?
const char *service = m_service.c_str();
int result = pam_start(service, applicant.username().c_str(), &converse, &handler);
if( result != PAM_SUCCESS)
{
std::cout << pam_strerror(handler, result) << std::endl;
return result;
}
if ((result = pam_set_item(handler, PAM_TTY, getenv("DISPLAY"))) != PAM_SUCCESS)
{
std::cout << "PAM: %s" << pam_strerror(handler, result) << std::endl;
return result;
}
// Set information to PAM Server
// Username
const std::string strUsername = applicant.username();
if (strUsername.length() == 0) return 1;
const char *username = strUsername.c_str();
result = pam_set_item(handler, PAM_RUSER, username);
if( result != PAM_SUCCESS)
{
std::cout << pam_strerror(handler, result) << std::endl;
pam_end(handler, result);
return result;
}
// result = pam_set_item(handler, PAM_AUTHTOK, applicant.password().c_str());
// if (result != PAM_SUCCESS)
// {
// pam_end(handler, result);
// return result;
// }
// Hostname
char hostname[MAXHOSTNAMELEN];
gethostname(hostname, MAXHOSTNAMELEN);
result = pam_set_item(handler, PAM_RHOST, hostname);
if( result != PAM_SUCCESS)
{
std::cout << pam_strerror(handler, result) << std::endl;
pam_end(handler, result);
return result;
}
// Authenticate the applicant
result = pam_authenticate(handler, m_flags);
if (result != PAM_SUCCESS)
{
std::cout << pam_strerror(handler, result) << std::endl;
pam_end(handler, result);
return result;
}
result = pam_acct_mgmt(handler, 0);
if (result != PAM_SUCCESS)
{
std::cout << pam_strerror(handler, result) << std::endl;
pam_end(handler, result);
return result;
}
result = pam_setcred(handler, PAM_ESTABLISH_CRED);
if (result != PAM_SUCCESS)
{
std::cout << pam_strerror(handler, result) << std::endl;
pam_end(handler, result);
return result;
}
result = pam_open_session(handler, PAM_SILENT);
if (result != PAM_SUCCESS)
{
std::cout << pam_strerror(handler, result) << std::endl;
pam_setcred(handler, PAM_DELETE_CRED);
pam_end(handler, result);
return result;
}
/* get mapped user name; PAM may have changed it */
struct passwd *pwd;
result = pam_get_item(handler, PAM_USER, (const void **)&username);
if (result != PAM_SUCCESS || (pwd = getpwnam(username)) == nullptr)
{
std::cout << pam_strerror(handler, result) << std::endl;
pam_end(handler, result);
return result;
}
/* export PAM environment */
char **pam_envlist, **pam_env;
if ((pam_envlist = pam_getenvlist(handler)) != NULL)
{
for (pam_env = pam_envlist; *pam_env != NULL; ++pam_env)
{
putenv(*pam_env);
free(*pam_env);
}
free(pam_envlist);
}
return result;
}
int Mere::Auth::PAM::logout()
{
int result = pam_close_session(handler, 0);
if (result != PAM_SUCCESS)
{
std::cerr << pam_strerror(handler, result) << std::endl;
return result;
}
result = pam_setcred(handler, PAM_DELETE_CRED);
if (result != PAM_SUCCESS)
{
std::cerr << pam_strerror(handler, result) << std::endl;
}
pam_end(handler, result);
return result;
}
//static
int Mere::Auth::PAM::handshake(int num_msg, const struct pam_message **message, struct pam_response **response, void *data)
{
if (num_msg <= 0 || num_msg > PAM_MAX_NUM_MSG)
return PAM_CONV_ERR;
*response = (struct pam_response *) calloc(num_msg, sizeof(struct pam_response));
if (*response == NULL) return PAM_BUF_ERR;
Applicant *applicant = static_cast<Applicant *>(data);
for (int i = 0; i < num_msg; i++)
{
(*response)[i].resp = nullptr;
(*response)[i].resp_retcode = 0;
switch (message[i]->msg_style)
{
// PAM asking for passsowd
case PAM_PROMPT_ECHO_OFF:
{
const std::string strPassword = applicant->password();
const char *passowrd = strPassword.c_str();
(*response)[i].resp = strdup(passowrd);
if ((*response)[i].resp == nullptr)
return fail(num_msg, response);
}
break;
// PAM asking for username
case PAM_PROMPT_ECHO_ON:
{
const std::string strUsername = applicant->username();
const char *username = strUsername.c_str();
(*response)[i].resp = strdup(username);
if ((*response)[i].resp == NULL)
return fail(num_msg, response);
}
break;
case PAM_ERROR_MSG:
std::cerr << message[i]->msg << std::endl;
break;
case PAM_TEXT_INFO:
std::cout << message[i]->msg << std::endl;
break;
default:
return fail(num_msg, response);
}
}
return PAM_SUCCESS;
}
//static
int Mere::Auth::PAM::fail(int num_msg, struct pam_response **response)
{
for (int i = 0; i < num_msg; i++)
{
if ((*response)[i].resp != nullptr)
{
free((*response)[i].resp);
(*response)[i].resp = nullptr;
}
}
*response = nullptr;
return PAM_CONV_ERR;
}
| 27.072072 | 123 | 0.557903 | merelabs |
beb9b9965cd0926b49da1c96fa5918c8ae5c5dcb | 3,935 | cpp | C++ | UnderstandingCpp11/src/compatibility.cpp | elloop/algorithm | 5485be0aedbc18968f775cff9533a2d444dbdcb5 | [
"MIT"
] | 15 | 2015-11-04T12:53:23.000Z | 2021-08-10T09:53:12.000Z | UnderstandingCpp11/src/compatibility.cpp | elloop/algorithm | 5485be0aedbc18968f775cff9533a2d444dbdcb5 | [
"MIT"
] | null | null | null | UnderstandingCpp11/src/compatibility.cpp | elloop/algorithm | 5485be0aedbc18968f775cff9533a2d444dbdcb5 | [
"MIT"
] | 6 | 2015-11-13T10:17:01.000Z | 2020-05-14T07:25:48.000Z | #include "compatibility.h"
#include "inc.h"
#include <climits>
#include <iostream>
USING_NS_STD;
NS_ELLOOP_BEGIN
//---------------------------------- test in this cpp ------------------------------------
void testC99Macro();
void testLongLong();
void testNoexcept() { }
Compatibility * Compatibility::run() {
#ifdef _MSC_VER
LOGD("in function : %s\n", __FUNCTION__);
#else
LOGD("in function : %s\n", __func__);
#endif
LOGD("__cplusplus : %ld\n", __cplusplus);
// testC99Macro();
Printer<Compatibility> p;
Compatibility c;
p.p(c);
// testLongLong();
return this;
}
//----------------------------------------------------------------------
// test C99 macro
//----------------------------------------------------------------------
void testC99Macro() {
#ifdef __STDC_HOSTED__
LOGD("Standard Clib: %d\n", __STDC_HOSTED__);
#endif
// psln(__STDC_HOSTED__);
#ifndef _MSC_VER
LOGD("Standard C: %d\n", __STDC__);
#endif
// psln(__STDC__);
// psln(__STDC_VERSION__);
// LOGD("C Standard Version: %d\n", __STDC_VERSION__);
// in gcc 4.8.2 __STDC_ISO_10646__ not defined....
// LOGD("ISO/IEC: %ld\n", __STDC_ISO_10646__);
// psln(__STDC_ISO_10646__);
}
//----------------------------------------------------------------------
// long long keyword.
//----------------------------------------------------------------------
void testLongLong() {
long long ll_min = LLONG_MIN;
LOGD("long long min: %lld\n", ll_min);
long long ll_max = LLONG_MAX;
LOGD("long long max: %lld\n", ll_max);
unsigned long long ull_max = ULLONG_MAX;
LOGD("unsigned long long max: %llu\n", ull_max);
}
//----------------------------------------------------------------------
// noexcept used as:
// 1. specifier. used in plain function definittion.
// void f() noexcept { }
// void g() noexcept(false) { }
//
// 2. operator. used in template function :
// template <typename T>
// void func() noexcept(noexcept(T())) { }
//
// In default, destructor is noexcept(true).
//
// if a noexcept(true) function throws a exception(s), std::terminate() will be called.
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// friend extend.
// 1. friend class A --> friend A;
// 2. typedef A AA;
// friend AA; // ok.
// 3. friend of template class is ok.
// template <typename T>
// class B {
// friend T;
// };
// // T is friend class of B<T>.
// // if T is not user type, such as int, float ..., friend is ignore.
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// quick init member variables.
// class A {
// public:
//
// A(int i) : i_(1000), f_(100) // init list come second.
// {
// i_ = i; // come last.
// }
//
// int i_ = 0; // come first.
//
// float f_ {1.11};
//
// };
// A a(-1);
//
// finally, a.i_ will be -1; a.f_ will be 100.
//
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// extern template declaration.
//
// avoid compiler generate duplicate copies of the same function of a template.
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// template actual parameters extend.
// template <typename T> class X {};
// template <typename T> f(T t) {};
//
// use:
// 1. local struct. { struct A {} a; X<A>; f(a); }
// 2. anonymous struct. typedef struct { int i;} B; X<B>;
// 3. struct { int i;} b; f(b);
//----------------------------------------------------------------------
NS_ELLOOP_END | 27.517483 | 91 | 0.424142 | elloop |
bebe08d2719a0053d3194552cc53713e8e81b408 | 1,969 | cpp | C++ | compiler/llvmArrayLoadInsn.cpp | Kishanthan/nballerina | baa4fc70ee140ceb5f57ce40905b233fffcb602f | [
"Apache-2.0"
] | null | null | null | compiler/llvmArrayLoadInsn.cpp | Kishanthan/nballerina | baa4fc70ee140ceb5f57ce40905b233fffcb602f | [
"Apache-2.0"
] | null | null | null | compiler/llvmArrayLoadInsn.cpp | Kishanthan/nballerina | baa4fc70ee140ceb5f57ce40905b233fffcb602f | [
"Apache-2.0"
] | null | null | null | #include "BIR.h"
ArrayLoadInsn::ArrayLoadInsn() { }
ArrayLoadInsn::ArrayLoadInsn(Location *pos, InstructionKind kind, Operand *lOp,
bool opFA, bool fR, Operand* KOp, Operand* ROp)
: NonTerminatorInsn(pos, kind, lOp), optionalFieldAccess(opFA),
fillingRead(fR), keyOp(KOp), rhsOp(ROp) {}
LLVMValueRef ArrayLoadInsn::getArrayLoadDeclaration (LLVMModuleRef &modRef,
BIRPackage *pkg) {
LLVMTypeRef *paramTypes = new LLVMTypeRef[2];
LLVMTypeRef int32PtrType = LLVMPointerType(LLVMInt32Type(),0);
paramTypes[0] = int32PtrType;
paramTypes[1] = LLVMInt32Type();
LLVMTypeRef funcType = LLVMFunctionType(int32PtrType, paramTypes, 2, 0);
LLVMValueRef addedFuncRef = LLVMAddFunction(modRef, "int_array_load", funcType);
pkg->addArrayFunctionRef("int_array_load", addedFuncRef);
return addedFuncRef;
}
void ArrayLoadInsn::translate(LLVMModuleRef &modRef) {
BIRFunction *funcObj = getFunction();
BIRPackage *pkgObj = getPkgAddress();
string lhsName = getLhsOperand()->name();
string rhsName = rhsOp->name();
LLVMBuilderRef builder = funcObj->getLLVMBuilder();
LLVMValueRef ArrayLoadFunc = pkgObj->getFunctionRefBasedOnName ("int_array_load");
if (!ArrayLoadFunc)
ArrayLoadFunc = getArrayLoadDeclaration(modRef, pkgObj);
LLVMValueRef lhsOpRef = funcObj->getLocalVarRefUsingId(lhsName);
if (!lhsOpRef)
lhsOpRef = pkgObj->getGlobalVarRefUsingId(lhsName);
LLVMValueRef rhsOpRef = funcObj->getLocalVarRefUsingId(rhsName);
LLVMValueRef keyRef = funcObj->getLocalToTempVar(keyOp);
assert(ArrayLoadFunc && rhsOpRef && keyRef);
LLVMValueRef *sizeOpValueRef = new LLVMValueRef[2];
sizeOpValueRef[0] = rhsOpRef;
sizeOpValueRef[1] = keyRef;
LLVMValueRef valueInArrayPointer = LLVMBuildCall(builder, ArrayLoadFunc, sizeOpValueRef, 2, "");
LLVMValueRef ArrayTempVal = LLVMBuildLoad(builder, valueInArrayPointer, "");
LLVMBuildStore(builder, ArrayTempVal, lhsOpRef);
}
ArrayLoadInsn::~ArrayLoadInsn() { }
| 41.893617 | 98 | 0.757237 | Kishanthan |
bec3c4047906c0673ac770fc4d7f0b997e7fadaf | 550 | cpp | C++ | src/5000/5789.cpp14.cpp | upple/BOJ | e6dbf9fd17fa2b458c6a781d803123b14c18e6f1 | [
"MIT"
] | 8 | 2018-04-12T15:54:09.000Z | 2020-06-05T07:41:15.000Z | src/5000/5789.cpp14.cpp | upple/BOJ | e6dbf9fd17fa2b458c6a781d803123b14c18e6f1 | [
"MIT"
] | null | null | null | src/5000/5789.cpp14.cpp | upple/BOJ | e6dbf9fd17fa2b458c6a781d803123b14c18e6f1 | [
"MIT"
] | null | null | null | #include<iostream>
#include<string>
using namespace std;
int main()
{
int no_case;
cin>>no_case;
while(no_case--)
{
string num;
cin>>num;
int k=num.size()/2;
int n1, n2;
switch(num.size()%2)
{
case 0:
n1=num.at(k-1), n2=num.at(k);
break;
case 1:
n1=num.at(k-2), n2=num.at(k);
}
if(n1==n2)
cout<<"Do-it";
else
cout<<"Do-it-Not";
cout<<endl;
}
return 0;
} | 14.473684 | 41 | 0.409091 | upple |
bed182e25bf0c180072642de20bd37e82b49fa61 | 10,785 | tcc | C++ | include/lvr2/algorithm/CleanupAlgorithms.tcc | uos/lvr | 9bb03a30441b027c39db967318877e03725112d5 | [
"BSD-3-Clause"
] | 38 | 2019-06-19T15:10:35.000Z | 2022-02-16T03:08:24.000Z | include/lvr2/algorithm/CleanupAlgorithms.tcc | uos/lvr | 9bb03a30441b027c39db967318877e03725112d5 | [
"BSD-3-Clause"
] | 9 | 2019-06-19T16:19:51.000Z | 2021-09-17T08:31:25.000Z | include/lvr2/algorithm/CleanupAlgorithms.tcc | uos/lvr | 9bb03a30441b027c39db967318877e03725112d5 | [
"BSD-3-Clause"
] | 13 | 2019-04-16T11:50:32.000Z | 2020-11-26T07:47:44.000Z | /**
* Copyright (c) 2018, University Osnabrück
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the University Osnabrück 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 University Osnabrück 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.
*/
/*
* CleanupAlgorithms.tcc
*/
#include "lvr2/io/Progress.hpp"
#include "lvr2/algorithm/ContourAlgorithms.hpp"
#include "lvr2/attrmaps/AttrMaps.hpp"
#include "lvr2/io/Timestamp.hpp"
namespace lvr2
{
template<typename BaseVecT>
void cleanContours(BaseMesh<BaseVecT>& mesh, int iterations, float areaThreshold)
{
for (int i = 0; i < iterations; i++)
{
for (const auto fH: mesh.faces())
{
// For each face, we want to count the number of boundary edges
// adjacent to that face. This can be a number between 0 and 3.
int boundaryEdgeCount = 0;
for (const auto eH: mesh.getEdgesOfFace(fH))
{
// For both (optional) faces of the edge...
for (const auto neighborFaceH: mesh.getFacesOfEdge(eH))
{
// ... we will count one up if there is no face on that
// side. Note that this correctly ignores our own face.
if (!neighborFaceH)
{
boundaryEdgeCount += 1;
}
}
}
// Now, given the number of boundary edges, we decide what to do
// with the face.
if (boundaryEdgeCount >= 2)
{
mesh.removeFace(fH);
}
else if (boundaryEdgeCount == 1 && mesh.calcFaceArea(fH) < areaThreshold)
{
mesh.removeFace(fH);
}
}
}
}
template<typename BaseVecT>
size_t naiveFillSmallHoles(BaseMesh<BaseVecT>& mesh, size_t maxSize, bool collapseOnly)
{
// There are no holes with less than three edges.
if (maxSize < 3)
{
return 0;
}
cout << timestamp << "Trying to remove all holes with size ≤ " << maxSize << endl;
// First, we need to have a ClusterBiMap where each cluster describes one
// connected part of the mesh.
auto subMeshes = clusterGrowing(mesh, [](FaceHandle referenceFaceH, FaceHandle currentFaceH)
{
return true;
});
DenseEdgeMap<bool> visitedEdges(mesh.numEdges(), false);
// We count how many holes we were unable to fill. This happens when a hole
// has many non-collapsable edges.
size_t failedToFillCount = 0;
// This is only used later but created here to avoid useless heap
// allocations.
vector<vector<EdgeHandle>> contours;
// We execute the algorithm for each connected part of the mesh
string comment = timestamp.getElapsedTime() + "Trying to remove all holes ";
ProgressBar progress(subMeshes.numCluster(), comment);
for (auto clusterH: subMeshes)
{
if(!timestamp.isQuiet())
++progress;
contours.clear();
// We only use this within the loop, but create it here to avoid
// useless heap allocations.
vector<EdgeHandle> contourEdges;
for (auto faceH: subMeshes[clusterH])
{
for (auto eH: mesh.getEdgesOfFace(faceH))
{
// Skip already visited edges and mark edge as visited
if (visitedEdges[eH])
{
continue;
}
visitedEdges[eH] = true;
// We are only interested in boundary edges
if (mesh.numAdjacentFaces(eH) != 1)
{
continue;
}
// Get full contour and store it in our list
contourEdges.clear();
calcContourEdges(mesh, eH, contourEdges);
contours.emplace_back(contourEdges);
// Mark all edges in the contour we just added as visited
for (auto edgeH: contours.back())
{
visitedEdges[edgeH] = true;
}
}
}
// It can actually happen that a cluster doesn't contain any contour
// edges that we haven't visited before. In that case, just ignore it.
if (contours.size() == 0)
{
continue;
}
// Now we have a list of all contours of the current part of the mesh.
// Next, we need to find the contour with most vertices and delete it
// from the list. This is a very naive assumption: we say that the
// contour containing most edges is the "outer" contour which we don't
// treat as a hole. This is far from being universally correct, but
// works OK for small holes.
size_t maxIdx = 0;
for (size_t i = 1; i < contours.size(); i++)
{
if (contours[i].size() > contours[maxIdx].size())
{
maxIdx = i;
}
}
contours.erase(contours.begin() + maxIdx);
// We assume that all remaining contours are holes we could fill. (And
// yes, we need the index later and can't use a range based for loop).
for (size_t contourIdx = 0; contourIdx < contours.size(); contourIdx++)
{
auto& contour = contours[contourIdx];
// We only try to fill the hole if it is smaller than the threshold
if (contour.size() > maxSize)
{
continue;
}
// Collapse as many edges as possible, but already stop when we
// have less than 4 edges left.
while (contour.size() > 3)
{
auto collapsableEdge = std::find_if(contour.begin(), contour.end(), [&](auto edgeH)
{
return mesh.isCollapsable(edgeH);
});
// In case there is no collapsable edge anymore
if (collapsableEdge == contour.end())
{
break;
}
// Collapse edge and remove it from the list of contours
auto collapseResult = mesh.collapseEdge(*collapsableEdge);
contour.erase(collapsableEdge);
// It may happen that the edge collapse invalidated an edge
// from our list. We need to fix that.
//
// First, we know that only one face will be collapsed, so we
// can just deal with that one.
auto removedNeighbor = collapseResult.neighbors[0]
? *(collapseResult.neighbors[0])
: *(collapseResult.neighbors[1]);
// We have to check if the removed edges are referenced
// anywhere. If yes, we have to fix those occurrences to avoid
// referencing invalid edges later. But we only store boundary
// edges, so we only need to fix anything if the new edge is
// still a boundary edge. That means that it is referred to
// somewhere.
if (mesh.numAdjacentFaces(removedNeighbor.newEdge) < 2)
{
for (auto removedEdgeH: removedNeighbor.removedEdges)
{
for (size_t i = contourIdx; i < contours.size(); i++)
{
auto& contourToFix = contours[i];
auto it = std::find(contourToFix.begin(), contourToFix.end(), removedEdgeH);
if (it != contourToFix.end())
{
// We replace the handle with the new one
*it = removedNeighbor.newEdge;
// We can stop here, because each edge is only
// part of one contour.
break;
}
}
}
}
// If the removed face belongs to a cluster different from the
// current one, we also have to remove the face there.
auto clusterH = subMeshes.getClusterOf(removedNeighbor.removedFace);
if (clusterH)
{
subMeshes.removeFromCluster(clusterH.unwrap(), removedNeighbor.removedFace);
}
}
if (collapseOnly)
{
continue;
}
// We collapsed as many edges as we could. In most cases, there is
// only one or two triangles left which we can close right ahead.
// Otherwise, we just leave the hole.
if (contour.size() == 3)
{
// The edges in `contour` are already in the correct order.
auto v0 = mesh.getVertexBetween(contour[0], contour[1]).unwrap();
auto v1 = mesh.getVertexBetween(contour[1], contour[2]).unwrap();
auto v2 = mesh.getVertexBetween(contour[2], contour[0]).unwrap();
mesh.addFace(v0, v1, v2);
}
else
{
failedToFillCount += 1;
}
}
}
if(!timestamp.isQuiet())
cout << endl;
return failedToFillCount;
}
} // namespace lvr2
| 38.244681 | 104 | 0.553732 | uos |
bed9204c7dbcd2ce89c8e7eb8ce54be93218f452 | 5,314 | hpp | C++ | include/c9/value.hpp | stormbrew/channel9 | 626b42c208ce1eb54fff09ebd9f9e9fd0311935d | [
"MIT"
] | 1 | 2015-02-13T02:03:29.000Z | 2015-02-13T02:03:29.000Z | include/c9/value.hpp | stormbrew/channel9 | 626b42c208ce1eb54fff09ebd9f9e9fd0311935d | [
"MIT"
] | null | null | null | include/c9/value.hpp | stormbrew/channel9 | 626b42c208ce1eb54fff09ebd9f9e9fd0311935d | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include "json/json.h"
#include "c9/channel9.hpp"
#include "c9/gc.hpp"
#include "c9/string.hpp"
namespace Channel9
{
union Value
{
enum {
TYPE_SHIFT = 56,
TYPE_MASK = 0xf000000000000000ULL,
HEAP_TYPE_MASK = 0xff00000000000000ULL,
VALUE_MASK = 0x0fffffffffffffffULL,
POINTER_MASK = 0x00007fffffffffffULL,
};
uint64_t raw;
int64_t machine_num;
double float_num;
const String *str_p;
const Tuple *tuple_p;
const Message *msg_p;
CallableContext *call_ctx_p;
RunnableContext *ret_ctx_p;
};
extern Value Nil;
extern Value True;
extern Value False;
extern Value Undef;
inline uint64_t type_mask(ValueType type)
{
return (uint64_t)(type) << Value::TYPE_SHIFT;
}
inline ValueType basic_type(const Value &val)
{
return ValueType((val.raw & Value::TYPE_MASK) >> Value::TYPE_SHIFT);
}
inline ValueType type(const Value &val)
{
ValueType t = basic_type(val);
if (t != HEAP_TYPE)
return t;
else
return ValueType((val.raw & Value::HEAP_TYPE_MASK) >> Value::TYPE_SHIFT);
}
inline bool is(const Value &val, ValueType t)
{
return type(val) == t;
}
inline bool is_truthy(const Value &val) { return !((basic_type(val) & FALSY_MASK) == FALSY_PATTERN); }
inline bool is_number(const Value &val) { ValueType t = basic_type(val); return t == POSITIVE_NUMBER || t == NEGATIVE_NUMBER; }
inline bool same_type(const Value &l, const Value &r)
{
return type(l) == type(r);
}
bool complex_compare(const Value &l, const Value &r);
inline bool operator==(const Value &l, const Value &r)
{
if (memcmp(&l, &r, sizeof(Value)) == 0)
return true;
else if (same_type(l, r)) {
return complex_compare(l, r);
} else {
return false;
}
}
inline bool operator!=(const Value &l, const Value &r)
{
return !(l == r);
}
inline const Value &bvalue(bool truthy) { return truthy ? True : False; }
template <typename tPtr>
tPtr *ptr(const Value &val)
{
DO_DEBUG if (!is(val, CALLABLE_CONTEXT)) assert(nursery_pool.validate((tPtr*)(val.raw & Value::POINTER_MASK)));
return (tPtr*)(val.raw & Value::POINTER_MASK);
}
template <typename tPtr>
inline Value make_value_ptr(ValueType type, tPtr value)
{
Value val = {type_mask(type) | ((uint64_t)value & Value::POINTER_MASK)};
return val;
}
inline Value value(long long machine_num)
{//cut off the top 4 bits, maintaining the sign
uint64_t type = (uint64_t)(machine_num >> 4) & Value::TYPE_MASK;
uint64_t num = type | ((uint64_t)(machine_num) & Value::VALUE_MASK);
Value val = {((uint64_t)(num))};
return val;
}
inline Value value(long machine_num) { return value((long long)machine_num); }
inline Value value(double float_num)
{//cut off the bottom 4 bits of precision
Value val;
val.float_num = float_num;
val.raw = type_mask(FLOAT_NUM) | (val.raw >> 4);
return val;
}
inline double float_num(Value val)
{
Value nval = val;
nval.raw = (nval.raw & Value::VALUE_MASK) << 4;
return nval.float_num;
}
inline Value value(const std::string &str) { return make_value_ptr(STRING, new_string(str)); }
inline Value value(const String *str) { return make_value_ptr(STRING, str); }
inline Value value(CallableContext *call_ctx) { return make_value_ptr(CALLABLE_CONTEXT, call_ctx); }
inline Value value(RunnableContext *ret_ctx) { return make_value_ptr(RUNNABLE_CONTEXT, ret_ctx); }
inline Value value(RunningContext *ret_ctx) { return make_value_ptr(RUNNING_CONTEXT, ret_ctx); }
void gc_scan(void *obj, CallableContext *ctx);
inline void gc_scan(void *obj, Value &from)
{
ValueType t = basic_type(from);
if (unlikely(t == HEAP_TYPE))
{
gc_mark(obj, (void**)&from);
} else if (unlikely(t == CALLABLE_CONTEXT)) {
gc_scan(obj, ptr<CallableContext>(from));
}
}
inline bool is_nursery(const Value &val)
{
return basic_type(val) == HEAP_TYPE && is_nursery(raw_tagged_ptr(val));
}
inline bool is_tenure(const Value &val)
{
return basic_type(val) == HEAP_TYPE && is_tenure(raw_tagged_ptr(val));
}
inline bool is_generation(const Value &val, uint8_t generation)
{
return basic_type(val) == HEAP_TYPE && is_generation(raw_tagged_ptr(val), generation);
}
// use this instead of write_ptr if you're writing a reference,
// it checks if the value is a heap pointer before writing.
template <typename tRef>
inline void gc_write_value(void *obj, tRef &ref, const Value &val)
{
if (basic_type(val) == HEAP_TYPE)
gc_write_ptr(obj, ref, val);
else
ref = val;
}
std::string inspect(const Value &val);
Json::Value to_json(const Value &val);
template <typename tVal>
class GCRef : private GCRoot
{
private:
tVal m_val;
public:
GCRef(const tVal &val)
: m_val(val)
{}
GCRef(const GCRef<tVal> &ref)
: m_val(ref.m_val)
{}
void scan()
{
gc_mark(NULL, &m_val);
}
const tVal &operator*() const { return m_val; }
tVal &operator*() { return m_val; }
const tVal &operator->() const { return m_val; }
tVal &operator->() { return m_val; }
};
// Specialize GCRef::scan for Values as we only scan them.
// They take care of marking themselves.
template <>
inline void GCRef<Value>::scan()
{
gc_scan(NULL, m_val);
}
template <typename tVal>
inline GCRef<tVal> gc_ref(const tVal &val)
{
return GCRef<tVal>(val);
}
}
#include "c9/tuple.hpp"
| 25.548077 | 128 | 0.690817 | stormbrew |
bed9631b262608c09677527bf691f8c469c5b6ba | 519 | cpp | C++ | Games/Inheritance/Point.cpp | PowerUser64/dP-2 | 98e5edc2dca4ed629e2bbf222c5b764e166e7193 | [
"MIT"
] | null | null | null | Games/Inheritance/Point.cpp | PowerUser64/dP-2 | 98e5edc2dca4ed629e2bbf222c5b764e166e7193 | [
"MIT"
] | null | null | null | Games/Inheritance/Point.cpp | PowerUser64/dP-2 | 98e5edc2dca4ed629e2bbf222c5b764e166e7193 | [
"MIT"
] | null | null | null | //------------------------------------------------------------------------------
//
// File Name: FileName.h
// Author(s): Blakely North (blakely.north@digipen.edu)
// Project: CS170 Project 4: Inheritance
// Course: WANIC VGP2
//
// Copyright © 2019 DigiPen (USA) Corporation.
//
//------------------------------------------------------------------------------
#include "Point.h"
Point::Point()
{
x = 0;
y = 0;
}
Point::Point(float x_, float y_)
{
x = x_;
y = y_;
} | 22.565217 | 81 | 0.375723 | PowerUser64 |
bedf2c17e71d62feeb1c01c0c80e52bf0ea1e921 | 3,614 | hpp | C++ | Include/libShapeDB.hpp | ldgcomputing/libShape | 89505afac7ee10903538604b5476b8b8fd6368c2 | [
"MIT"
] | null | null | null | Include/libShapeDB.hpp | ldgcomputing/libShape | 89505afac7ee10903538604b5476b8b8fd6368c2 | [
"MIT"
] | null | null | null | Include/libShapeDB.hpp | ldgcomputing/libShape | 89505afac7ee10903538604b5476b8b8fd6368c2 | [
"MIT"
] | null | null | null | //
// libShapeDB.hpp
// libShape
//
// Created by Louis Gehrig on 4/13/19.
// Copyright © 2019 Louis Gehrig. All rights reserved.
//
/***
MIT License
Copyright (c) 2019 Louis Gehrig
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
***/
#ifndef INCLUDE_LIBSHAPEDB_HPP
#define INCLUDE_LIBSHAPEDB_HPP
// STL includes
#include <list>
#include <string>
#include <vector>
// Project includes
#include <libShape.hpp>
namespace libShape {
// A DB exception
class dbException {
public:
dbException(std::string msg);
virtual ~dbException();
const std::string excpMsg;
};
// The DB field information
class dbField {
public:
// The possible field types
enum e_field_types {
FT_TEXT = 'T',
FT_NUMBER = 'N',
FT_LOGICAL = 'L',
FT_INVALID = 'X'
};
typedef enum e_field_types E_FIELD_TYPE;
// Construction from byte buffer
dbField( const BYTE *pBuffer, const size_t bufSize);
// Destruction
virtual ~dbField();
// Get the name of the field
const char * getName() const { return fieldName; }
// Get the field type
E_FIELD_TYPE getType() const { return eFieldType; }
// Get the field length
size_t getLength() const { return fieldLength; }
// Get the decimal count (if any)
size_t getDecimalCount() const { return decimalCount; }
protected:
// The name of the field
char fieldName [10 + 1];
// The field type
E_FIELD_TYPE eFieldType;
// The field length
size_t fieldLength;
// The decimal count
size_t decimalCount;
};
typedef std::vector<dbField> CNT_FIELDS;
typedef CNT_FIELDS::const_iterator CITR_FIELDS;
typedef CNT_FIELDS::iterator ITR_FIELDS;
class dbTable {
public:
// Construction
dbTable( FILE *dbFile);
// Destruction
virtual ~dbTable();
// Get the table version
int getVersion() const { return version; }
// Get the fields
const CNT_FIELDS & getFields() const { return cntFields; }
// Get the number of records
size_t getRecordCount() const { return numRecords; }
// Get the last update
const BYTE * getLastUpdate() const { return lastUpdate; }
// Get the size of each record
size_t getRecordSize() const { return recSize; }
// Get the raw bytes for a record
const BYTE * getRecordBytes(const size_t recNum);
protected:
// The DB file
FILE *fileDB;
// The DB version
int version;
// The number of records
size_t numRecords;
// The list of fields
CNT_FIELDS cntFields;
// The last update
BYTE lastUpdate[3];
// The header size
size_t hdrSize;
// The record size
size_t recSize;
// The record buffer
BYTE *pRecordBuffer;
};
};
#endif
| 21.511905 | 79 | 0.714721 | ldgcomputing |
bee42a0ec43b9e8666c2912841ecf863fd0069da | 17 | hpp | C++ | src/color/LuvCH/trait/index/index.hpp | 3l0w/color | e42d0933b6b88564807bcd5f49e9c7f66e24990a | [
"Apache-2.0"
] | 120 | 2015-12-31T22:30:14.000Z | 2022-03-29T15:08:01.000Z | src/color/LuvCH/trait/index/index.hpp | 3l0w/color | e42d0933b6b88564807bcd5f49e9c7f66e24990a | [
"Apache-2.0"
] | 6 | 2016-08-22T02:14:56.000Z | 2021-11-06T22:39:52.000Z | src/color/LuvCH/trait/index/index.hpp | 3l0w/color | e42d0933b6b88564807bcd5f49e9c7f66e24990a | [
"Apache-2.0"
] | 23 | 2016-02-03T01:56:26.000Z | 2021-09-28T16:36:27.000Z | // USE Default!!! | 17 | 17 | 0.588235 | 3l0w |
bee4753e8fa7dcaec3bad5e8092772a81d215591 | 384 | cpp | C++ | check/src/hello_hipfft.cpp | powderluv/rocm-build | db8b6f4cde075344aec91d7bf5b521905b42fb50 | [
"Apache-2.0"
] | 59 | 2020-10-30T12:28:30.000Z | 2022-03-31T05:29:24.000Z | check/src/hello_hipfft.cpp | powderluv/rocm-build | db8b6f4cde075344aec91d7bf5b521905b42fb50 | [
"Apache-2.0"
] | 26 | 2020-09-28T03:53:26.000Z | 2022-03-14T03:12:42.000Z | check/src/hello_hipfft.cpp | powderluv/rocm-build | db8b6f4cde075344aec91d7bf5b521905b42fb50 | [
"Apache-2.0"
] | 7 | 2020-09-28T03:43:21.000Z | 2022-03-20T16:17:10.000Z |
#include "hipfft.h"
char status_text[10] = "failure";
char* hipfft_status_to_string(hipfftResult status)
{
return status_text;
}
int main()
{
int v;
hipfftResult ret = hipfftGetVersion(&v);
if (ret != HIPFFT_SUCCESS) {
printf("[hipFFT] %s\n", hipfft_status_to_string(ret));
return 0;
}
printf("[hipFFT] %d\n", v);
return 0;
}
| 16 | 66 | 0.601563 | powderluv |
bee484b2f47911447f4b18cc3969f814711f38f1 | 2,411 | cpp | C++ | CSES/Range Queries/RangeMinimumQueriesOne.cpp | Anni1123/competitive-programming | bfcc72ff3379d09dee22f30f71751a32c0cc511b | [
"MIT"
] | 1 | 2021-04-03T13:33:00.000Z | 2021-04-03T13:33:00.000Z | CSES/Range Queries/RangeMinimumQueriesOne.cpp | iamsuryakant/competitive-programming | 413000f5bc4a627407e1335c35dcdbee516e8cc1 | [
"MIT"
] | null | null | null | CSES/Range Queries/RangeMinimumQueriesOne.cpp | iamsuryakant/competitive-programming | 413000f5bc4a627407e1335c35dcdbee516e8cc1 | [
"MIT"
] | 2 | 2021-01-23T14:35:48.000Z | 2021-03-15T05:04:24.000Z | #pragma GCC optimize("O3")
#pragma GCC target("sse4")
#include <bits/stdc++.h>
using namespace std;
#define deb(x) cout << #x << " is " << x << "\n"
#define int long long
#define mod 1000000007
#define PI acos(-1)
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
template <typename T>
using max_heap = priority_queue<T>;
template <typename... T>
void read(T &... args) {
((cin >> args), ...);
}
template <typename... T>
void write(T &&... args) {
((cout << args), ...);
}
template <typename T>
void readContainer(T &t) {
for (auto &e : t) read(e);
}
template <typename T>
void writeContainer(T &t) {
for (const auto &e : t) write(e, " ");
write("\n");
}
// size of tree = 4 * N + 1, where N = size of input array
vector<int> tree;
vector<int> arr;
// index: initial index of tree = 1
// [start, end]: range of size of input array
void buildTree(int index, int start, int end) {
if (start > end) {
return;
}
if (start == end) {
tree[index] = arr[start];
return;
}
int mid = start + (end - start) / 2;
buildTree(2 * index, start, mid);
buildTree(2 * index + 1, mid + 1, end);
tree[index] = min(tree[2 * index], tree[2 * index + 1]);
}
// find the answer for [left, right] query
// tree[index] contains the answer for [start, end]
int queryTree(int index, int start, int end, int left, int right) {
if (left > end || right < start) {
return LLONG_MAX;
}
if (left <= start && end <= right) {
return tree[index];
}
int mid = start + (end - start) / 2;
return min(queryTree(2 * index, start, mid, left, right), queryTree(2 * index + 1, mid + 1, end, left, right));
}
void solve(int tc) {
int N, Q, L, R;
read(N, Q);
arr.resize(N);
tree.resize(4 * N + 1);
readContainer(arr);
buildTree(1, 0, N - 1);
while (Q--) {
read(L, R);
L--;
R--;
write(queryTree(1, 0, N - 1, L, R), "\n");
}
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
// #ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
// #endif
int tc = 1;
// read(tc);
for (int curr = 1; curr <= tc; curr++) solve(curr);
return 0;
} | 24.353535 | 116 | 0.533389 | Anni1123 |
beef195f4976c9a5579a491c3e81570e2b5ca0fd | 490 | cpp | C++ | source/quantum-script-extension-url.amalgam.cpp | g-stefan/quantum-script-extension-url | 4226f12bb962bc04f91204c15b9ed19fb3e06f06 | [
"MIT",
"Unlicense"
] | null | null | null | source/quantum-script-extension-url.amalgam.cpp | g-stefan/quantum-script-extension-url | 4226f12bb962bc04f91204c15b9ed19fb3e06f06 | [
"MIT",
"Unlicense"
] | null | null | null | source/quantum-script-extension-url.amalgam.cpp | g-stefan/quantum-script-extension-url | 4226f12bb962bc04f91204c15b9ed19fb3e06f06 | [
"MIT",
"Unlicense"
] | null | null | null | //
// Quantum Script Extension URL
//
// Copyright (c) 2020-2021 Grigore Stefan <g_stefan@yahoo.com>
// Created by Grigore Stefan <g_stefan@yahoo.com>
//
// MIT License (MIT) <http://opensource.org/licenses/MIT>
//
#include "quantum-script-extension-url.cpp"
#include "quantum-script-extension-url-copyright.cpp"
#include "quantum-script-extension-url-license.cpp"
#ifndef QUANTUM_SCRIPT_EXTENSION_URL_NO_VERSION
#include "quantum-script-extension-url-version.cpp"
#endif
| 28.823529 | 63 | 0.742857 | g-stefan |
beef410381b4d935cf10debc3666b7e1cada5d0f | 1,314 | cpp | C++ | lightoj/1263.cpp | cosmicray001/Online_judge_Solutions- | 5dc6f90d3848eb192e6edea8e8c731f41a1761dd | [
"MIT"
] | 3 | 2018-01-08T02:52:51.000Z | 2021-03-03T01:08:44.000Z | lightoj/1263.cpp | cosmicray001/Online_judge_Solutions- | 5dc6f90d3848eb192e6edea8e8c731f41a1761dd | [
"MIT"
] | null | null | null | lightoj/1263.cpp | cosmicray001/Online_judge_Solutions- | 5dc6f90d3848eb192e6edea8e8c731f41a1761dd | [
"MIT"
] | 4 | 2020-08-11T14:23:34.000Z | 2020-11-17T10:52:31.000Z | #include <bits/stdc++.h>
#define le 1003
using namespace std;
bool vis[le], ck[le];
int mo[le];
set<int> st;
vector<int> v[le];
bool bfs(int a){
memset(vis, 0, sizeof(vis));
vis[a] = true;
ck[a] = true;
int n = 1, sum = mo[a];
queue<int> q;
q.push(a);
while(!q.empty()){
int p = q.front();
q.pop();
for(int i = 0; i < v[p].size(); i++){
int e = v[p][i];
if(!vis[e]){
vis[e] = true;
ck[e] = true;
sum += mo[e];
n++;
q.push(e);
}
}
}
if(sum % n == 0){
st.insert(sum / n);
return true;
}
return false;
}
int main(){
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
int t, co = 0, n, m, a, b;
for(scanf("%d", &t); t--; ){
memset(ck, 0, sizeof(ck));
scanf("%d %d", &n, &m);
for(int i = 0; i < n; scanf("%d", &mo[i + 1]), i++);
for(int i = 0; i < m; i++){
scanf("%d %d", &a, &b);
v[a].push_back(b);
v[b].push_back(a);
}
bool f = true;
for(int i = 1; i < n + 1; i++){
if(!ck[i]){
if(!bfs(i)){
f = false;
break;
}
}
}
if(f && st.size() == 1) printf("Case %d: Yes\n", ++co);
else printf("Case %d: No\n", ++co);
for(int i = 0; i < le; v[i].clear(), i++);
st.clear();
}
}
| 20.857143 | 59 | 0.424658 | cosmicray001 |
bef18a09af66acdd54a0ce56fbf0cc22d89b1c8d | 6,820 | hpp | C++ | pwiz/utility/bindings/CLI/common/Unimod.hpp | edyp-lab/pwiz-mzdb | d13ce17f4061596c7e3daf9cf5671167b5996831 | [
"Apache-2.0"
] | 11 | 2015-01-08T08:33:44.000Z | 2019-07-12T06:14:54.000Z | pwiz/utility/bindings/CLI/common/Unimod.hpp | shze/pwizard-deb | 4822829196e915525029a808470f02d24b8b8043 | [
"Apache-2.0"
] | 61 | 2015-05-27T11:20:11.000Z | 2019-12-20T15:06:21.000Z | pwiz/utility/bindings/CLI/common/Unimod.hpp | shze/pwizard-deb | 4822829196e915525029a808470f02d24b8b8043 | [
"Apache-2.0"
] | 4 | 2016-02-03T09:41:16.000Z | 2021-08-01T18:42:36.000Z | //
// $Id: Unimod.hpp 4922 2013-09-05 22:33:08Z pcbrefugee $
//
//
// Original author: Matt Chambers <matt.chambers .@. vanderbilt.edu>
//
// Copyright 2011 Vanderbilt University - Nashville, TN 37232
//
// 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 _UNIMOD_HPP_CLI_
#define _UNIMOD_HPP_CLI_
#pragma warning( push )
#pragma warning( disable : 4634 4635 )
#pragma unmanaged
#include "pwiz/data/common/Unimod.hpp"
#pragma managed
#include "SharedCLI.hpp"
#include "cv.hpp"
#include "../chemistry/chemistry.hpp"
#pragma warning( pop )
namespace pwiz {
namespace CLI {
namespace data {
using System::String;
using System::Nullable;
using System::Collections::Generic::IList;
using namespace CLI::cv;
using namespace CLI::chemistry;
// acts like a namespace
public ref struct unimod abstract sealed {
[System::FlagsAttribute]
enum class Site
{
Any = 1<<0,
NTerminus = 1<<1,
CTerminus = 1<<2,
Alanine = 1<<3,
Cysteine = 1<<4,
AsparticAcid = 1<<5,
GlutamicAcid = 1<<6,
Phenylalanine = 1<<7,
Glycine = 1<<8,
Histidine = 1<<9,
Isoleucine = 1<<10,
Lysine = 1<<11,
Leucine = 1<<12,
Methionine = 1<<13,
Asparagine = 1<<14,
Proline = 1<<15,
Glutamine = 1<<16,
Arginine = 1<<17,
Serine = 1<<18,
Threonine = 1<<19,
Selenocysteine = 1<<20,
Valine = 1<<21,
Tryptophan = 1<<22,
Tyrosine = 1<<23
};
enum class Position
{
Anywhere = 0,
AnyNTerminus,
AnyCTerminus,
ProteinNTerminus,
ProteinCTerminus
};
[System::FlagsAttribute]
enum class Classification
{
Any = 1<<0,
Artifact = 1<<1,
ChemicalDerivative = 1<<2,
CoTranslational = 1<<3,
IsotopicLabel = 1<<4,
Multiple = 1<<5,
NLinkedGlycosylation = 1<<6,
NonStandardResidue = 1<<7,
OLinkedGlycosylation = 1<<8,
OtherGlycosylation = 1<<9,
Other = 1<<10,
PostTranslational = 1<<11,
PreTranslational = 1<<12,
Substitution = 1<<13
};
/// <summary>a modification from Unimod</summary>
ref class Modification
{
DEFINE_INTERNAL_BASE_CODE(Modification, pwiz::data::unimod::Modification);
public:
ref class Specificity
{
DEFINE_INTERNAL_BASE_CODE(Specificity, pwiz::data::unimod::Modification::Specificity);
public:
property Site site { Site get(); }
property Position position { Position get(); }
property bool hidden { bool get(); }
property Classification classification { Classification get(); }
};
property CVID cvid { CVID get(); }
property String^ name { String^ get(); }
property Formula^ deltaComposition { Formula^ get(); }
property double deltaMonoisotopicMass { double get(); }
property double deltaAverageMass { double get(); }
property bool approved { bool get(); }
property IList<Specificity^>^ specificities { IList<Specificity^>^ get(); }
};
/// <summary>
/// returns the Site given a one-letter residue code, or:
/// 'x' for Site.Any, 'n' for Site.NTerminus, 'c' for Site.CTerminus
/// </summary>
static Site site(System::Char symbol);
/// <summary>
/// returns a Position corresponding to one of the following CVIDs:
/// CVID.CVID_Unknown: Position.Anywhere
/// MS_modification_specificity_peptide_N_term: Position.AnyNTerminus
/// MS_modification_specificity_peptide_C_term: Position.AnyCTerminus
/// Else: InvalidArgumentException
/// </summary>
static Position position(CVID cvid);
/// <summary>the entire list of Unimod modifications</summary>
static IList<Modification^>^ modifications();
/// <summary>filters the list of Unimod modifications according to specified parameters</summary>
ref struct Filter
{
/// <summary>
/// the default filter gets a list of modifications by mass and tolerance;
/// - mass is treated as monoisotopic
/// - only approved modifications
/// - any site, position, classification, and hidden state is allowed
/// </summary>
Filter(double mass, double tolerance);
/// <summary>mass is treated as monoisotopic if monoisotopic=true; if null, both average and monoisotopic lookups are done</summary>
property double mass;
/// <summary>the filter accepts mods within the range [mass-tolerance, mass+tolerance]</summary>
property double tolerance;
/// <summary>mass is treated as monoisotopic if monoisotopic=true; if null, both average and monoisotopic lookups are done</summary>
property System::Nullable<bool> monoisotopic;
/// <summary>if approved is not null, only approved/unapproved modifications are considered</summary>
property System::Nullable<bool> approved;
/// <summary>
/// - the site, position, and classification parameters filter the resulting modifications such that
/// every modification must have at least one specificity matching all three criteria;
/// </summary>
property Site site;
/// <summary>
/// - the site, position, and classification parameters filter the resulting modifications such that
/// every modification must have at least one specificity matching all three criteria;
/// </summary>
property Position position;
/// <summary>
/// - the site, position, and classification parameters filter the resulting modifications such that
/// every modification must have at least one specificity matching all three criteria;
/// </summary>
property Classification classification;
/// <summary>if hidden is not null, matching site/position/classification specificities must be hidden (or not)</summary>
property System::Nullable<bool> hidden;
};
/// <summary>get a list of modifications filtered by the specified filter</summary>
static IList<Modification^>^ modifications(Filter^ filter);
/// <summary>find a modification by CVID</summary>
static Modification^ modification(CVID cvid);
/// <summary>find a modification by title, e.g. "Phospho" not "Phosphorylation"</summary>
static Modification^ modification(String^ title);
}; // namespace unimod
} // namespace data
} // namespace CLI
} // namespace pwiz
#endif // _UNIMOD_HPP_CLI_
| 30.176991 | 137 | 0.673607 | edyp-lab |
befbe4b417cd1677d3df8fe69e74edda1dbe8cd2 | 362 | cpp | C++ | test/test.main.cpp | spjuanjoc/template_project_cpp | c52c1b9223bf7a8a8ef66f8bb278c91b5487f189 | [
"MIT"
] | 1 | 2021-12-29T10:11:53.000Z | 2021-12-29T10:11:53.000Z | test/test.main.cpp | spjuanjoc/template_project_cpp | c52c1b9223bf7a8a8ef66f8bb278c91b5487f189 | [
"MIT"
] | null | null | null | test/test.main.cpp | spjuanjoc/template_project_cpp | c52c1b9223bf7a8a8ef66f8bb278c91b5487f189 | [
"MIT"
] | null | null | null | /**
* @brief Defines the entry point for the tests.
*
* @author juan.castellanos
* @date 2021-06-28
*/
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "catch2/catch.hpp"
#include "fmt/core.h"
TEST_CASE("test the main", "[foo]")
{
fmt::print("Test the framework\n");
REQUIRE(1 == 1);
}
| 20.111111 | 97 | 0.649171 | spjuanjoc |
befff457b2857aef240df5b23d325b57640c0c0e | 919 | cpp | C++ | tests/sslstreaming.cpp | doa379/libsockpp | f45b3335fbbd53edc6ee6f8b110fc9f9cba2b38c | [
"MIT"
] | null | null | null | tests/sslstreaming.cpp | doa379/libsockpp | f45b3335fbbd53edc6ee6f8b110fc9f9cba2b38c | [
"MIT"
] | null | null | null | tests/sslstreaming.cpp | doa379/libsockpp | f45b3335fbbd53edc6ee6f8b110fc9f9cba2b38c | [
"MIT"
] | null | null | null | #include <iostream>
#include <libsockpp/sock.h>
static const char HOST[] { "localhost" };
static const char PORT[] { "4433" };
// Remember to generate a set of pems
// $ openssl req -x509 -nodes -days 365 -newkey rsa:1024 -keyout /tmp/key.pem -out /tmp/cert.pem
int main(int ARGC, char *ARGV[])
{
sockpp::Cb cb { [](const std::string &buffer) { std::cout << buffer; } };
// Data sent as POST request
// Header validates request is OK
// Chunked transfer calls cb()
sockpp::XHandle h { cb, POST, { "OK" }, "Some Data", "/" };
try {
sockpp::Client<sockpp::Https> client { 1.1, HOST, PORT };
if (!client.performreq(h))
throw "Unable to sendreq()";
std::cout << "Stream disconnected\n";
std::cout << "The response header:\n===================\n";
std::cout << h.header << std::endl;
}
catch (const char e[]) {
std::cout << std::string(e) << std::endl;
}
return 0;
}
| 27.029412 | 96 | 0.594124 | doa379 |
8305f9fa1120af9344ce35e471f2ccd35e2aa9ca | 974 | cpp | C++ | examples/multithreading/game/triggers.cpp | mamontov-cpp/saddy | f20a0030e18af9e0714fe56c19407fbeacc529a7 | [
"BSD-2-Clause"
] | 58 | 2015-08-09T14:56:35.000Z | 2022-01-15T22:06:58.000Z | examples/multithreading/game/triggers.cpp | mamontov-cpp/saddy-graphics-engine-2d | e25a6637fcc49cb26614bf03b70e5d03a3a436c7 | [
"BSD-2-Clause"
] | 245 | 2015-08-08T08:44:22.000Z | 2022-01-04T09:18:08.000Z | examples/multithreading/game/triggers.cpp | mamontov-cpp/saddy | f20a0030e18af9e0714fe56c19407fbeacc529a7 | [
"BSD-2-Clause"
] | 23 | 2015-12-06T03:57:49.000Z | 2020-10-12T14:15:50.000Z | #include "triggers.h"
#include "player.h"
#include "../game.h"
#include <log/log.h>
void game::Triggers::add(double x, const sad::dukpp03::CompiledFunction& func, bool once)
{
m_triggers << game::Triggers::Data(x, func, once);
}
void game::Triggers::clear()
{
m_triggers.clear();
}
void game::Triggers::tryRun(game::Player* p, sad::dukpp03::Context *ctx)
{
double localx = p->area()[0].x();
for(size_t i = 0; i < m_triggers.size(); i++)
{
if (localx > m_triggers[i]._1())
{
m_triggers[i]._2().call(ctx);
dukpp03::Maybe<std::string> data = ctx->errorOnStack(-1);
if (data.exists())
{
sad::String log_entry = data.value() + "\n";
SL_LOCAL_CRITICAL(log_entry, *(p->game()->rendererForMainThread()));
}
if (m_triggers[i]._3())
{
m_triggers.removeAt(i);
--i;
}
}
}
}
| 24.974359 | 89 | 0.517454 | mamontov-cpp |
8306951b2205f038a53bb813f4f6b4bc5acd27a0 | 9,672 | hpp | C++ | external/include/mapnik/enumeration.hpp | Wujingli/OpenWebGlobeDataProcessing | 932eaa00c81fc0571122bc618ade010fa255735e | [
"MIT"
] | null | null | null | external/include/mapnik/enumeration.hpp | Wujingli/OpenWebGlobeDataProcessing | 932eaa00c81fc0571122bc618ade010fa255735e | [
"MIT"
] | null | null | null | external/include/mapnik/enumeration.hpp | Wujingli/OpenWebGlobeDataProcessing | 932eaa00c81fc0571122bc618ade010fa255735e | [
"MIT"
] | 2 | 2019-06-08T15:59:26.000Z | 2021-02-06T08:13:01.000Z | /*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_ENUMERATION_HPP
#define MAPNIK_ENUMERATION_HPP
// mapnik
#include <mapnik/config.hpp>
// stl
#include <vector>
#include <bitset>
#include <iostream>
#include <cstdlib>
namespace mapnik {
class illegal_enum_value : public std::exception
{
public:
illegal_enum_value():
what_() {}
illegal_enum_value( std::string const& what ) :
what_( what )
{
}
virtual ~illegal_enum_value() throw() {}
virtual const char * what() const throw()
{
return what_.c_str();
}
protected:
std::string what_;
};
/** Slim wrapper for enumerations. It creates a new type from a native enum and
* a char pointer array. It almost exactly behaves like a native enumeration
* type. It supports string conversion through stream operators. This is usefull
* for debugging, serialization/deserialization and also helps with implementing
* language bindings. The two convinient macros DEFINE_ENUM() and IMPLEMENT_ENUM()
* are provided to help with instanciation.
*
* @par Limitations:
* - The enum must start at zero.
* - The enum must be consecutive.
* - The enum must be terminated with a special token consisting of the enum's
* name plus "_MAX".
* - The corresponding char pointer array must be terminated with an empty string.
* - The names must only consist of characters and digits (<i>a-z, A-Z, 0-9</i>),
* underscores (<i>_</i>) and dashes (<i>-</i>).
*
*
* @warning At the moment the verify_mapnik_enum() method is called during static initialization.
* It quits the application with exit code 1 if any error is detected. The other solution
* i thought of is to do the checks at compile time (using boost::mpl).
*
* @par Example:
* The following code goes into the header file:
* @code
* enum fruit_enum {
* APPLE,
* CHERRY,
* BANANA,
* PASSION_FRUIT,
* fruit_enum_MAX
* };
*
* static const char * fruit_strings[] = {
* "apple",
* "cherry",
* "banana",
* "passion_fruit",
* ""
* };
*
* DEFINE_ENUM( fruit, fruit_enum);
* @endcode
* In the corresponding cpp file do:
* @code
* IMPLEMENT_ENUM( fruit, fruit_strings );
* @endcode
* And here is how to use the resulting type Fruit
* @code
*
* int
* main(int argc, char * argv[]) {
* fruit f(APPLE);
* switch ( f ) {
* case BANANA:
* case APPLE:
* cerr << "No thanks. I hate " << f << "s" << endl;
* break;
* default:
* cerr << "Hmmm ... yummy " << f << endl;
* break;
* }
*
* f = CHERRY;
*
* fruit_enum native_enum = f;
*
* f.from_string("passion_fruit");
*
* for (unsigned i = 0; i < fruit::MAX; ++i) {
* cerr << i << " = " << fruit::get_string(i) << endl;
* }
*
* f.from_string("elephant"); // throws illegal_enum_value
*
* return 0;
* }
* @endcode
*/
template <typename ENUM, int THE_MAX>
class MAPNIK_DECL enumeration {
public:
typedef ENUM native_type;
enumeration()
: value_() {}
enumeration( ENUM v )
: value_(v) {}
enumeration( enumeration const& other )
: value_(other.value_) {}
/** Assignment operator for native enum values. */
void operator=(ENUM v)
{
value_ = v;
}
/** Assignment operator. */
void operator=(enumeration const& other)
{
value_ = other.value_;
}
/** Conversion operator for native enum values. */
operator ENUM() const
{
return value_;
}
enum Max
{
MAX = THE_MAX
};
/** Converts @p str to an enum.
* @throw illegal_enum_value @p str is not a legal identifier.
* */
void from_string(std::string const& str)
{
for (unsigned i = 0; i < THE_MAX; ++i)
{
if (str == our_strings_[i])
{
value_ = static_cast<ENUM>(i);
return;
}
}
throw illegal_enum_value(std::string("Illegal enumeration value '") +
str + "' for enum " + our_name_);
}
/** Parses the input stream @p is for a word consisting of characters and
* digits (<i>a-z, A-Z, 0-9</i>) and underscores (<i>_</i>).
* The failbit of the stream is set if the word is not a valid identifier.
*/
std::istream & parse(std::istream & is)
{
std::string word;
char c;
while ( is.peek() != std::char_traits< char >::eof())
{
is >> c;
if ( isspace(c) && word.empty() )
{
continue;
}
if ( isalnum(c) || (c == '_') || c == '-' )
{
word += c;
}
else
{
is.unget();
break;
}
}
try
{
from_string( word );
}
catch (illegal_enum_value const&)
{
is.setstate(std::ios::failbit);
}
return is;
}
/** Returns the current value as a string identifier. */
std::string as_string() const
{
return our_strings_[value_];
}
/** Prints the string identifier to the output stream @p os. */
std::ostream & print(std::ostream & os = std::cerr) const
{
return os << our_strings_[value_];
}
/** Static helper function to iterate over valid identifiers. */
static const char * get_string(unsigned i)
{
return our_strings_[i];
}
/** Performs some simple checks and quits the application if
* any error is detected. Tries to print helpful error messages.
*/
static bool verify_mapnik_enum(const char * filename, unsigned line_no)
{
for (unsigned i = 0; i < THE_MAX; ++i)
{
if (our_strings_[i] == 0 )
{
std::cerr << "### FATAL: Not enough strings for enum "
<< our_name_ << " defined in file '" << filename
<< "' at line " << line_no;
}
}
if ( std::string("") != our_strings_[THE_MAX])
{
std::cerr << "### FATAL: The string array for enum " << our_name_
<< " defined in file '" << filename << "' at line " << line_no
<< " has too many items or is not terminated with an "
<< "empty string";
}
return true;
}
static std::string const& get_full_qualified_name()
{
return our_name_;
}
static std::string get_name()
{
std::string::size_type idx = our_name_.find_last_of(":");
if ( idx == std::string::npos )
{
return our_name_;
} else {
return our_name_.substr( idx + 1 );
}
}
private:
ENUM value_;
static const char ** our_strings_ ;
static std::string our_name_ ;
static bool our_verified_flag_;
};
/** ostream operator for enumeration
* @relates mapnik::enumeration
*/
template <class ENUM, int THE_MAX>
std::ostream &
operator<<(std::ostream & os, const mapnik::enumeration<ENUM, THE_MAX> & e)
{
e.print( os );
return os;
}
/** istream operator for enumeration
* @relates mapnik::enumeration
*/
template <class ENUM, int THE_MAX>
std::istream &
operator>>(std::istream & is, mapnik::enumeration<ENUM, THE_MAX> & e)
{
e.parse( is );
return is;
}
} // end of namespace
/** Helper macro. Creates a typedef.
* @relates mapnik::enumeration
*/
#ifdef _MSC_VER
#define DEFINE_ENUM( name, e) \
template enumeration<e, e ## _MAX>; \
typedef enumeration<e, e ## _MAX> name
#else
#define DEFINE_ENUM( name, e) \
typedef enumeration<e, e ## _MAX> name
#endif
/** Helper macro. Runs the verify_mapnik_enum() method during static initialization.
* @relates mapnik::enumeration
*/
#define IMPLEMENT_ENUM( name, strings ) \
template <> const char ** name ::our_strings_ = strings; \
template <> std::string name ::our_name_ = #name; \
template <> bool name ::our_verified_flag_( name ::verify_mapnik_enum(__FILE__, __LINE__));
#endif // MAPNIK_ENUMERATION_HPP
| 28.280702 | 98 | 0.541977 | Wujingli |
8306aebebd21dce0d5dad909167f917f0bc6e680 | 1,074 | hpp | C++ | smart_tales_ii/game/obstacle/base/gestureobstacle.hpp | TijmenUU/smarttalesii | c3a9c90bc2385e21e6fe4aa1cfda550edf6e20ba | [
"CC-BY-3.0",
"CC-BY-4.0"
] | null | null | null | smart_tales_ii/game/obstacle/base/gestureobstacle.hpp | TijmenUU/smarttalesii | c3a9c90bc2385e21e6fe4aa1cfda550edf6e20ba | [
"CC-BY-3.0",
"CC-BY-4.0"
] | 11 | 2018-02-08T14:50:16.000Z | 2022-01-21T19:54:24.000Z | smart_tales_ii/game/obstacle/base/gestureobstacle.hpp | TijmenUU/smarttalesii | c3a9c90bc2385e21e6fe4aa1cfda550edf6e20ba | [
"CC-BY-3.0",
"CC-BY-4.0"
] | null | null | null | /*
gestureobstacle.hpp
Expanded base obstacle with support for gestures
Defines the logic for how the gesture obstacle
is neutralized by user input.
This class is virtual.
*/
#pragma once
#include "baseobstacle.hpp"
namespace Obstacle
{
enum class GestureType : uint8_t
{
None = 0,
InProgress = 1,
Tap = 2,
Vertical_Upwards = 4,
Vertical_Downwards = 8,
Horizontal_LeftToRight = 16,
Horizontal_RightToLeft = 32
};
class GestureBase : public Base
{
protected:
bool gestureInProgress = false;
sf::Vector2f gestureStart = sf::Vector2f(0.f, 0.f);
float gestureMinDistance;
uint8_t gestureFlag;
virtual bool IsInteractionInBounds(const Inputhandler & input) const = 0;
virtual GestureType TrackGestures(const Inputhandler & input);
// Returns whether user input neutralized this obstacle
virtual bool HandleInput(const Inputhandler & input);
public:
GestureBase(const uint8_t _gestureFlag,
const float gestureMinWorldTravel,
const Type t,
const Animation::Sheet & obstacleSheet,
const bool playerHasSensor);
};
}
| 21.48 | 75 | 0.744879 | TijmenUU |
8306e55296b6898502854fbbb8b28de2107b1618 | 579 | cpp | C++ | 3_memory_mgmt/3_smart_pointers/05_scopes.cpp | aalfianrachmat/CppND-practice | 6c35141c106b9fa867392a846b35c482ded74e62 | [
"MIT"
] | 27 | 2019-10-08T13:43:32.000Z | 2021-08-30T08:00:28.000Z | 3_memory_mgmt/3_smart_pointers/05_scopes.cpp | aalfianrachmat/CppND-practice | 6c35141c106b9fa867392a846b35c482ded74e62 | [
"MIT"
] | 1 | 2020-10-11T23:20:15.000Z | 2020-10-11T23:20:15.000Z | 3_memory_mgmt/3_smart_pointers/05_scopes.cpp | aalfianrachmat/CppND-practice | 6c35141c106b9fa867392a846b35c482ded74e62 | [
"MIT"
] | 14 | 2019-09-22T15:17:59.000Z | 2021-07-13T06:06:37.000Z | #include <iostream>
int var = 5; // global varible
namespace test
{
int var = 3; // namespace variable
}
void func() {
int var = 7; // function variable
std::cout << "Function variable : " << var << std::endl;
}
int main() {
int var = 10; // local variable
std::cout << "Global variable : " << ::var << std::endl;
std::cout << "Namesapce variable : " << test::var << std::endl;
func(); // function call, which uses variable from within function scope
std::cout << "Local variable : " << var << std::endl;
return 0;
}
| 22.269231 | 80 | 0.56304 | aalfianrachmat |
83072cb43898916d3743e26aa338b26eb36506f2 | 1,967 | hpp | C++ | KFContrib/KFGlobal/KFUuidData.hpp | 282951387/KFrame | 5d6e953f7cc312321c36632715259394ca67144c | [
"Apache-2.0"
] | 1 | 2021-04-26T09:31:32.000Z | 2021-04-26T09:31:32.000Z | KFContrib/KFGlobal/KFUuidData.hpp | 282951387/KFrame | 5d6e953f7cc312321c36632715259394ca67144c | [
"Apache-2.0"
] | null | null | null | KFContrib/KFGlobal/KFUuidData.hpp | 282951387/KFrame | 5d6e953f7cc312321c36632715259394ca67144c | [
"Apache-2.0"
] | null | null | null | #ifndef __KF_UUID_DATA_H__
#define __KF_UUID_DATA_H__
#include "KFInclude.h"
namespace KFrame
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
+------+---------------+----------+----------------+----------+
| sign | delta seconds | zone id | worker node id | sequence |
+------+---------------+----------+----------------+----------+
| 1bit | 29bits | 10bits | 10bits | 14bits |
+------+---------------+----------+----------------+----------+
*/
// 默认
// 1 符号位
// 29 时间( 大概可以支持17年, 可以修改项目开始时间 )
// 10 zoneid 可以支持1023个小区不会重复
// 10 workerid 1023个工作者进程不会重复
// 14 序列号 同一进程1秒钟内超过16383个就会重复 -- 应该不可能, 除非你要疯
// 可以保证同一模块生成的guid不相同, 不同模块可能会一样
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class KFUuidSetting;
class KFUuidData
{
public:
KFUuidData( const KFUuidSetting* kfsetting );
~KFUuidData() = default;
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
// 生产guid
uint64 Make( uint32 zoneid, uint32 workerid, uint64 nowtime );
// 获得zoneid
uint32 ZoneId( uint64 uuid );
// 解析guid( time, zone, worker, seq )
std::tuple<uint64, uint32, uint32, uint32> Parse( uint64 uuid );
private:
// uuid 配置
const KFUuidSetting* _kf_setting = nullptr;
// 上一次时间
uint64 _last_time = 0u;
// 序列号
uint32 _sequence = 0u;
};
}
#endif
| 34.508772 | 116 | 0.32181 | 282951387 |
8312977ba244abcaeccdadeb0aca150f683e8e8e | 796 | cpp | C++ | src/reguladorwatt.cpp | pirobtumen/UGR_IG | 8492d6c8a68e2151cc18103f0168a078afb46c3b | [
"MIT"
] | null | null | null | src/reguladorwatt.cpp | pirobtumen/UGR_IG | 8492d6c8a68e2151cc18103f0168a078afb46c3b | [
"MIT"
] | null | null | null | src/reguladorwatt.cpp | pirobtumen/UGR_IG | 8492d6c8a68e2151cc18103f0168a078afb46c3b | [
"MIT"
] | null | null | null | // Informática Gráfica
//
// Alberto Sola - 2016
// -----------------------------------------------------------------------------
#include "reguladorwatt.hpp"
// -----------------------------------------------------------------------------
Base Watt::base;
Body Watt::body;
// -----------------------------------------------------------------------------
Watt::Watt(){
draw(DrawMode::ALL);
}
// -----------------------------------------------------------------------------
void Watt::draw(DrawMode mode) const{
glPushMatrix();
glTranslated(0,1,0);
base.draw(mode);
glPushMatrix();
glTranslated(0,0.75,0);
glRotated(rotate_angle,0,1,0);
body.draw(mode);
glPopMatrix();
glPopMatrix();
}
// -----------------------------------------------------------------------------
| 22.111111 | 80 | 0.324121 | pirobtumen |
8312c46e4175afa3e3b22592a960ab7a184e6957 | 173,512 | cpp | C++ | src/examRoutines.cpp | tmilev/calculator | e39280f23975241985393651fe7a52db5c7fd1d5 | [
"Apache-2.0"
] | 7 | 2017-07-12T11:15:54.000Z | 2021-10-29T18:33:33.000Z | src/examRoutines.cpp | tmilev/calculator | e39280f23975241985393651fe7a52db5c7fd1d5 | [
"Apache-2.0"
] | 18 | 2017-05-16T03:48:45.000Z | 2022-03-16T19:51:26.000Z | src/examRoutines.cpp | tmilev/calculator | e39280f23975241985393651fe7a52db5c7fd1d5 | [
"Apache-2.0"
] | 1 | 2018-08-02T09:05:08.000Z | 2018-08-02T09:05:08.000Z | // The current file is licensed under the license terms found in the main header file "calculator.h".
// For additional information refer to the file "calculator.h".
#include "calculator_inner_functions.h"
#include "calculator_html_functions.h"
#include "database.h"
#include "general_time_date.h"
#include "calculator_html_interpretation.h"
#include "web_api.h"
#include "math_extra_latex_routines.h"
#include <iomanip>
#include "database.h"
#include "string_constants.h"
std::string CalculatorHTML::stringScoredQuizzes = "Quiz";
std::string CalculatorHTML::stringPracticE = "Practice";
std::string CalculatorHTML::stringProblemLink = "Problem";
std::string SyntacticElementHTML::Tags::filler = "filler";
std::string SyntacticElementHTML::Tags::command = "command";
std::string SyntacticElementHTML::Tags::calculator = "calculator";
std::string SyntacticElementHTML::Tags::calculatorHidden = "calculatorHidden";
std::string SyntacticElementHTML::Tags::calculatorSolution = "calculatorSolution";
std::string SyntacticElementHTML::Tags::calculatorShowToUserOnly = "calculatorShowToUserOnly";
std::string SyntacticElementHTML::Tags::calculatorSolutionStart = "calculatorSolutionStart";
std::string SyntacticElementHTML::Tags::calculatorSolutionEnd = "calculatorSolutionEnd";
std::string SyntacticElementHTML::Tags::calculatorExamProblem = "calculatorExamProblem";
std::string SyntacticElementHTML::Tags::calculatorAnswer = "calculatorAnswer";
std::string SyntacticElementHTML::Tags::hardCodedAnswer = "answer";
std::string SyntacticElementHTML::Tags::answerCalculatorHighlight = "answerCalculatorHighlight";
std::string SyntacticElementHTML::Tags::answerCalculatorHighlightStart = "answerCalculatorHighlightStart";
std::string SyntacticElementHTML::Tags::answerCalculatorHighlightEnd = "answerCalculatorHighlightEnd";
HashedList<std::string, HashFunctions::hashFunction> CalculatorHTML::Parser::calculatorClasses;
HashedList<std::string, HashFunctions::hashFunction> CalculatorHTML::Parser::calculatorClassesAnswerFields;
int SyntacticElementHTML::parsingDummyElements = 8;
CalculatorHTML::CalculatorHTML() {
this->numberOfInterpretationAttempts = 0;
this->numberOfAnswerIdsMathquilled = 0;
this->maxInterpretationAttempts = 25;
this->flagLoadedSuccessfully = false;
this->flagParentInvestigated = false;
this->numberOfProblemsFound = 0;
this->numberOfVideosFound = 0;
this->numberOfHandwrittenSolutionsFound = 0;
this->numberOfVideosHandwrittenFound = 0;
this->numberOfVideosWithSlidesFound = 0;
this->numberOfSlidesFound = 0;
this->flagIsForReal = false;
this->flagLoadedFromDB = false;
this->flagLoadedClassDataSuccessfully = false;
this->flagDoPrependEditPagePanel = true;
this->flagTopicTableStarted = false;
this->flagTopicSectionStarted = false;
this->flagTopicSubSectionStarted = false;
this->flagTopicChapterStarted = false;
this->timeToParseHtml = 0;
this->flagSectionsPrepared = false;
this->topicLectureCounter = 0;
this->topics.owner = this;
this->parser.owner = this;
}
bool CalculatorHTML::mergeProblemWeight(
const JSData& inputJSON,
MapList<std::string, ProblemData, MathRoutines::hashString>& outputAppendProblemInfo,
bool checkFileExistence,
std::stringstream* commentsOnFailure
) {
MacroRegisterFunctionWithName("DatabaseRoutines::LoadProblemWeightsAppend");
(void) commentsOnFailure;
if (inputJSON.elementType != JSData::token::tokenObject) {
return true;
}
ProblemData emptyData;
std::string currentCourse = global.userDefault.courseComputed;
for (int i = 0; i < inputJSON.objects.size(); i ++) {
std::string currentProblemName = inputJSON.objects.keys[i];
if (checkFileExistence) {
if (!FileOperations::fileExistsVirtualCustomizedReadOnly(
currentProblemName, commentsOnFailure
)) {
if (commentsOnFailure != nullptr) {
*commentsOnFailure << "Problem "
<< currentProblemName << " <b>does not appear to exist</b>. ";
}
return false;
}
}
JSData currentProblem = inputJSON.objects.values[i];
if (!outputAppendProblemInfo.contains(currentProblemName)) {
outputAppendProblemInfo.setKeyValue(currentProblemName, emptyData);
}
ProblemData& currentProblemValue = outputAppendProblemInfo.getValueCreateEmpty(currentProblemName);
JSData& currentWeight = currentProblem[DatabaseStrings::labelProblemWeight];
if (currentWeight.elementType == JSData::token::tokenString) {
currentProblemValue.adminData.problemWeightsPerCourse.setKeyValue(currentCourse, currentWeight.stringValue);
} else if (currentWeight.elementType == JSData::token::tokenObject) {
for (int i = 0; i < currentWeight.objects.size(); i ++) {
if (currentWeight.objects.values[i].elementType != JSData::token::tokenString) {
if (commentsOnFailure != nullptr) {
*commentsOnFailure << "Failed to extract weight from: "
<< currentWeight.objects.values[i]
<< " in weight: " << currentWeight.toString();
}
return false;
}
currentProblemValue.adminData.problemWeightsPerCourse.setKeyValue(
currentWeight.objects.keys[i],
currentWeight.objects.values[i].stringValue
);
}
} else {
if (commentsOnFailure != nullptr) {
*commentsOnFailure << "Could extract weight from "
<< currentWeight.toString(nullptr) << ". Your input was: "
<< inputJSON.toString(nullptr);
}
return false;
}
}
return true;
}
bool CalculatorHTML::mergeProblemDeadline(
const JSData& inputJSON,
MapList<std::string, ProblemData, MathRoutines::hashString>& outputAppendProblemInfo,
std::stringstream *commentsOnFailure
) {
MacroRegisterFunctionWithName("DatabaseRoutines::LoadProblemWeightsAppend");
(void) commentsOnFailure;
if (inputJSON.elementType != JSData::token::tokenObject) {
return true;
}
ProblemData emptyData;
for (int i = 0; i < inputJSON.objects.size(); i ++) {
std::string currentProbName = inputJSON.objects.keys[i];
JSData currentProblem = inputJSON.objects.values[i];
if (currentProbName == "") {
continue;
}
if (!outputAppendProblemInfo.contains(currentProbName)) {
outputAppendProblemInfo.setKeyValue(currentProbName, emptyData);
}
ProblemData& currentProblemValue = outputAppendProblemInfo.getValueCreateEmpty(currentProbName);
JSData& currentDeadlines = currentProblem[DatabaseStrings::labelDeadlines];
if (currentDeadlines.elementType == JSData::token::tokenObject) {
for (int j = 0; j < currentDeadlines.objects.size(); j ++) {
currentProblemValue.adminData.deadlinesPerSection.setKeyValue(
currentDeadlines.objects.keys[j],
currentDeadlines.objects.values[j].stringValue
);
}
} else {
if (commentsOnFailure != nullptr) {
*commentsOnFailure << "Unexpected deadline format. ";
}
return false;
}
}
return true;
}
JSData CalculatorHTML::toJSONDeadlines(
MapList<std::string, ProblemData, MathRoutines::hashString>& inputProblemInfo
) {
MacroRegisterFunctionWithName("CalculatorHTML::toJSONDeadlines");
JSData output;
output.elementType = JSData::token::tokenObject;
for (int i = 0; i < inputProblemInfo.size(); i ++) {
ProblemDataAdministrative& currentProblem = inputProblemInfo.values[i].adminData;
if (currentProblem.deadlinesPerSection.size() == 0) {
continue;
}
std::string currentProblemName = inputProblemInfo.keys[i];
JSData currentProblemJSON;
for (int j = 0; j < currentProblem.deadlinesPerSection.size(); j ++) {
std::string currentDeadline = StringRoutines::stringTrimWhiteSpace(
currentProblem.deadlinesPerSection.values[j]
);
if (currentDeadline == "") {
continue;
}
std::string currentSection = StringRoutines::stringTrimWhiteSpace(
currentProblem.deadlinesPerSection.keys[j]
);
currentProblemJSON[DatabaseStrings::labelDeadlines][currentSection] = currentDeadline;
}
output[currentProblemName] = currentProblemJSON;
}
return output;
}
QuerySet CalculatorHTML::toQuerySetProblemWeights(
MapList<std::string, ProblemData, MathRoutines::hashString>& inputProblemInfo
) {
MacroRegisterFunctionWithName("CalculatorHTML::toQuerySetProblemWeights");
QuerySet output;
output.nestedLabels.addOnTop(DatabaseStrings::labelProblemWeight);
for (int i = 0; i < inputProblemInfo.size(); i ++) {
ProblemDataAdministrative& currentProblem = inputProblemInfo.values[i].adminData;
if (currentProblem.problemWeightsPerCourse.size() == 0) {
continue;
}
std::string currentProblemName = inputProblemInfo.keys[i];
JSData currentProblemJSON;
for (int j = 0; j < currentProblem.problemWeightsPerCourse.size(); j ++) {
std::string currentWeight = StringRoutines::stringTrimWhiteSpace(
currentProblem.problemWeightsPerCourse.values[j]
);
if (currentWeight == "") {
continue;
}
std::string currentCourse = StringRoutines::stringTrimWhiteSpace(
currentProblem.problemWeightsPerCourse.keys[j]
);
currentProblemJSON[currentCourse] = currentWeight;
}
JSData currentWeight;
currentWeight[DatabaseStrings::labelProblemWeight] = currentProblemJSON;
output.value[currentProblemName] = currentWeight;
}
return output;
}
bool CalculatorHTML::mergeOneProblemAdminData(
const std::string& inputProblemName,
ProblemData& inputProblemInfo,
std::stringstream& commentsOnFailure
) {
MacroRegisterFunctionWithName("CalculatorHTML::mergeOneProblemAdminData");
if (!this->topics.topics.contains(inputProblemName)) {
commentsOnFailure << "Did not find " << inputProblemName
<< " among the list of topics/problems. ";
if (global.userDefaultHasAdminRights() && global.userDebugFlagOn()) {
commentsOnFailure << "The topics are: " << this->topics.topics.toStringHtml();
}
return false;
}
if (!this->currentUser.problemData.contains(inputProblemName)) {
this->currentUser.problemData.setKeyValue(inputProblemName, inputProblemInfo);
}
ProblemDataAdministrative& currentProblem =
this->currentUser.problemData.getValueCreateEmpty(inputProblemName).adminData;
MapList<std::string, std::string, MathRoutines::hashString>&
currentDeadlines = currentProblem.deadlinesPerSection;
MapList<std::string, std::string, MathRoutines::hashString>&
incomingDeadlines = inputProblemInfo.adminData.deadlinesPerSection;
MapList<std::string, std::string, MathRoutines::hashString>&
currentWeightS = currentProblem.problemWeightsPerCourse;
MapList<std::string, std::string, MathRoutines::hashString>&
incomingWeightS = inputProblemInfo.adminData.problemWeightsPerCourse;
for (int i = 0; i < incomingDeadlines.size(); i ++) {
if (this->databaseStudentSections.size >= 1000) {
commentsOnFailure << "Failed to account deadlines: max 999 sections allowed. ";
return false;
}
this->databaseStudentSections.addOnTopNoRepetition(incomingDeadlines.keys[i]);
}
////////////////////////////////////////////
for (int i = 0; i < incomingDeadlines.size(); i ++) {
currentDeadlines.setKeyValue(incomingDeadlines.keys[i], incomingDeadlines.values[i]);
}
for (int i = 0; i < incomingWeightS.size(); i ++) {
currentWeightS.setKeyValue(incomingWeightS.keys[i], incomingWeightS.values[i]);
}
return true;
}
bool CalculatorHTML::mergeProblemWeightAndStore(
std::string& incomingProblemInfo, std::stringstream* commentsOnFailure
) {
MacroRegisterFunctionWithName("DatabaseRoutines::MergeProblemInfoInDatabase");
JSData problemJSON;
if (!problemJSON.parse(incomingProblemInfo, commentsOnFailure)) {
if (commentsOnFailure != nullptr) {
*commentsOnFailure << "Failed to parse your input. ";
}
return false;
}
MapList<std::string, ProblemData, MathRoutines::hashString> incomingProblems;
if (!this->mergeProblemWeight(problemJSON, incomingProblems, true, commentsOnFailure)) {
if (commentsOnFailure != nullptr) {
*commentsOnFailure << "Failed to parse your request";
}
return false;
}
return this->storeProblemWeights(incomingProblems, commentsOnFailure);
}
bool CalculatorHTML::mergeProblemDeadlineAndStore(
std::string& incomingProblemInfo, std::stringstream* commentsOnFailure
) {
MacroRegisterFunctionWithName("DatabaseRoutines::mergeProblemDeadlineAndStore");
JSData problemJSON;
if (!problemJSON.parse(incomingProblemInfo, commentsOnFailure)) {
if (commentsOnFailure != nullptr) {
*commentsOnFailure << "Failed to parse your input. ";
}
return false;
}
MapList<std::string, ProblemData, MathRoutines::hashString> incomingProblems;
if (!this->mergeProblemDeadline(problemJSON, incomingProblems, commentsOnFailure)) {
if (commentsOnFailure != nullptr) {
*commentsOnFailure << "Failed to parse your request";
}
return false;
}
return this->storeProblemDeadlines(incomingProblems, commentsOnFailure);
}
bool CalculatorHTML::storeProblemWeights(
MapList<std::string, ProblemData, MathRoutines::hashString>& toStore,
std::stringstream *commentsOnFailure
) {
MacroRegisterFunctionWithName("DatabaseRoutines::StoreProblemDatabaseInfo");
QueryExact weightFinder;
weightFinder.collection = DatabaseStrings::tableProblemWeights;
weightFinder.setLabelValue(
DatabaseStrings::labelProblemWeightsSchema,
global.userDefault.problemWeightSchema
);
QuerySet updateQuery = this->toQuerySetProblemWeights(toStore);
if (!Database::get().updateOne(weightFinder, updateQuery, commentsOnFailure)) {
if (commentsOnFailure != nullptr) {
*commentsOnFailure << "Failed to update weight schema. ";
global << Logger::red
<< "Failed to update weight schema with update query: "
<< updateQuery.toStringDebug() << Logger::endL;
}
return false;
}
return true;
}
bool CalculatorHTML::storeProblemDeadlines(
MapList<std::string, ProblemData, MathRoutines::hashString>& toStore,
std::stringstream* commentsOnFailure
) {
MacroRegisterFunctionWithName("DatabaseRoutines::StoreProblemDatabaseInfo");
QueryExact deadlineSchema;
deadlineSchema.collection = DatabaseStrings::tableDeadlines;
deadlineSchema.setLabelValue(DatabaseStrings::labelDeadlinesSchema, global.userDefault.deadlineSchema);
QuerySet updateQuery = this->toJSONDeadlines(toStore);
if (!Database::get().updateOne(deadlineSchema, updateQuery, commentsOnFailure)) {
if (commentsOnFailure != nullptr) {
*commentsOnFailure << "Failed to update deadline schema. ";
}
return false;
}
return true;
}
bool CalculatorHTML::loadDatabaseInfo(std::stringstream& comments) {
MacroRegisterFunctionWithName("CalculatorHTML::loadDatabaseInfo");
this->currentUser.::UserCalculatorData::operator=(global.userDefault);
if (!this->prepareSectionList(comments)) {
return false;
}
if (this->currentUser.problemDataJSON.objects.size() != 0 || this->currentUser.problemDataStrinG == "") {
if (!this->currentUser.interpretDatabaseProblemDataJSON(this->currentUser.problemDataJSON, comments)) {
comments << "Failed to interpret user's problem saved data. ";
return false;
}
} else {
if (!this->currentUser.interpretDatabaseProblemData(this->currentUser.problemDataStrinG, comments)) {
comments << "Failed to interpret user's problem saved data. ";
return false;
}
}
if (!this->mergeProblemWeight(
this->currentUser.problemWeights,
this->currentUser.problemData,
false,
&comments
)) {
comments << "Failed to load problem weights. ";
return false;
}
if (!this->mergeProblemDeadline(
this->currentUser.deadlines, this->currentUser.problemData, &comments
)) {
comments << "Failed to load problem deadlines. ";
return false;
}
if (this->currentUser.problemData.contains(this->fileName)) {
this->problemData = this->currentUser.problemData.getValueCreateEmpty(this->fileName);
}
global.userDefault = this->currentUser;
return true;
}
bool CalculatorHTML::loadMe(
bool doLoadDatabase,
const std::string& inputRandomSeed,
std::stringstream* commentsOnFailure
) {
MacroRegisterFunctionWithName("CalculatorHTML::loadMe");
if (!FileOperations::getPhysicalFileNameFromVirtualCustomizedReadOnly(
this->fileName, this->relativePhysicalFileNameWithFolder, commentsOnFailure
)) {
if (commentsOnFailure != nullptr) {
*commentsOnFailure << "Failed to get physical file name from "
<< this->fileName << ". ";
}
return false;
}
(void) doLoadDatabase;
if (!FileOperations::loadFiletoStringVirtualCustomizedReadOnly(
this->fileName, this->parser.inputHtml, commentsOnFailure
)) {
if (commentsOnFailure != nullptr) {
*commentsOnFailure << "<br>User-input file name: [<b>" << this->fileName
<< "</b>]. ";
}
return false;
}
this->flagIsForReal = global.userRequestRequiresLoadingRealExamData();
this->topicListFileName = HtmlRoutines::convertURLStringToNormal(
global.getWebInput(WebAPI::problem::topicList), false
);
if (doLoadDatabase) {
std::stringstream errorStream;
if (!this->loadDatabaseInfo(errorStream)) {
global.comments << "Error loading your problem from the database. " << errorStream.str();
}
for (int i = 0; i < this->topics.topics.size(); i ++) {
this->computeDeadlinesAllSectionsNoInheritance(
this->topics.topics.values[i]
);
}
}
this->problemData.checkConsistency();
if (!this->flagIsForReal && inputRandomSeed != "") {
std::stringstream randSeedStream(inputRandomSeed);
randSeedStream >> this->problemData.randomSeed;
this->problemData.flagRandomSeedGiven = true;
}
return true;
}
std::string CalculatorHTML::loadAndInterpretCurrentProblemItemJSON(
bool needToLoadDatabaseMayIgnore, const std::string& desiredRandomSeed, std::stringstream* commentsOnFailure
) {
MacroRegisterFunctionWithName("CalculatorHTML::LoadAndInterpretCurrentProblemItemJSON");
double startTime = global.getElapsedSeconds();
this->loadCurrentProblemItem(needToLoadDatabaseMayIgnore, desiredRandomSeed, commentsOnFailure);
if (!this->flagLoadedSuccessfully) {
return WebAPI::problem::failedToLoadProblem;
}
std::stringstream out;
if (!this->interpretHtml(commentsOnFailure)) {
out << "<b>Failed to interpret file: " << this->fileName << "</b>. ";
out << "<br>We limit the number of generation attemps to "
<< this->maxInterpretationAttempts << " for performance reasons; "
<< "with bad luck, some finicky problems require more. "
<< "Random seeds tried: "
<< this->randomSeedPerAttempt.toStringCommaDelimited()
<< "<br> <b>Please refresh the page.</b><br>";
if (!this->flagIsForReal) {
out
<< "If you specified the problem through the 'problem link' link, "
<< "please go back to the course page. ";
} else {
out << "<b>Your random seed must have been reset. </b>";
}
out << "<br><b style ='color:red'>If the problem persists "
<< "after a couple of page refreshes, "
<< "it's a bug. Please take a screenshot and email "
<< "the site administrator/your instructor. </b>";
out
<< "Generated in "
<< MathRoutines::reducePrecision(global.getElapsedSeconds() - startTime)
<< " second(s). ";
return out.str();
}
out << this->outputHtmlBodyNoTag;
return out.str();
}
void CalculatorHTML::loadFileNames() {
this->fileName = HtmlRoutines::convertURLStringToNormal(global.getWebInput(WebAPI::problem::fileName), false);
this->courseHome = HtmlRoutines::convertURLStringToNormal(global.getWebInput(WebAPI::problem::courseHome), false);
this->topicListFileName = HtmlRoutines::convertURLStringToNormal(global.getWebInput(WebAPI::problem::topicList), false);
}
void CalculatorHTML::loadCurrentProblemItem(
bool needToLoadDatabaseMayIgnore, const std::string& inputRandomSeed, std::stringstream* commentsOnFailure
) {
MacroRegisterFunctionWithName("CalculatorHTML::loadCurrentProblemItem");
this->loadFileNames();
this->flagLoadedSuccessfully = false;
if (global.userGuestMode()) {
needToLoadDatabaseMayIgnore = false;
}
this->flagLoadedSuccessfully = true;
if (this->fileName == "") {
this->flagLoadedSuccessfully = false;
if (commentsOnFailure != nullptr) {
*commentsOnFailure << "<b>No problem file name found. </b>";
}
}
if (!this->loadMe(needToLoadDatabaseMayIgnore, inputRandomSeed, commentsOnFailure)) {
this->flagLoadedSuccessfully = false;
}
this->problemData.checkConsistency();
}
bool CalculatorHTML::Parser::isStateModifierApplyIfYes(SyntacticElementHTML& inputElt) {
MacroRegisterFunctionWithName("CalculatorHTML::Parser::isStateModifierApplyIfYes");
if (inputElt.syntacticRole != "command") {
return false;
}
std::string tagClass = inputElt.getTagClass();
return false;
}
bool Answer::hasSolution() const {
return this->solutionElements.size > 0;
}
std::string Answer::toString() {
MacroRegisterFunctionWithName("Answer::toString");
std::stringstream out;
out << "Answer id: " << this->answerId;
out << "<br>Answer commands on give-up: " << this->commandAnswerOnGiveUp;
return out.str();
}
std::string Answer::toStringSolutionElements() {
MacroRegisterFunctionWithName("Answer::toStringSolutionElements");
std::stringstream out;
out << this->solutionElements.size << " total solution elements. ";
for (int i = 0; i < this->solutionElements.size; i ++) {
out << this->solutionElements[i].toStringTagAndContent();
if (i != this->solutionElements.size - 1) {
out << ", ";
}
}
return out.str();
}
std::string CalculatorHTML::toStringCalculatorProblemSourceFromFileName(const std::string& fileName) {
MacroRegisterFunctionWithName("CalculatorHTML::toStringCalculatorProblemSourceFromFileName");
std::stringstream out;
out //<< "<span class =\"calculatorExamProblem\">\n"
<< "Title: " << fileName << "\n"
<< "Problem: " << fileName << "\n"
//<< "\n</span>"
;
return out.str();
}
void CalculatorHTML::interpretGenerateLink(SyntacticElementHTML& inputOutput) {
MacroRegisterFunctionWithName("CalculatorHTML::interpretGenerateLink");
inputOutput.interpretedCommand = this->toStringProblemInfo(this->cleanUpFileName(inputOutput.content));
}
std::string CalculatorHTML::toStringLinkCurrentAdmin(
const std::string& displayString, bool setDebugFlag, bool includeRandomSeed
) {
MacroRegisterFunctionWithName("CalculatorHTML::toStringLinkCurrentAdmin");
if (!global.userDefaultHasAdminRights()) {
return "";
}
std::stringstream out;
out << "<a class =\"linkStandardButtonLike\" href=\"" << global.displayNameExecutable << "?request="
<< global.requestType << "&";
std::string urledProblem = HtmlRoutines::convertStringToURLString(this->fileName, false);
List<std::string> randomSeedContainer;
randomSeedContainer.addOnTop(WebAPI::problem::randomSeed);
out << "fileName=" << urledProblem << "&"
<< global.toStringCalculatorArgumentsNoNavigation(&randomSeedContainer);
if (includeRandomSeed) {
out << "randomSeed=" << this->problemData.randomSeed << "&";
}
if (setDebugFlag) {
out << "debugFlag=true&";
} else {
out << "debugFlag=false&";
}
if (this->topicListFileName != "") {
out << "topicList=" << this->topicListFileName << "&";
}
if (this->courseHome != "") {
out << "courseHome=" << this->courseHome << "&";
}
if (global.userStudentVieWOn()) {
out << "studentView=true&";
if (global.getWebInput("studentSection") != "") {
out << "studentSection=" << global.getWebInput("studentSection") << "&";
}
}
out << "\">" << displayString << "</a>";
return out.str();
}
std::string CalculatorHTML::toStringLinkFromFileName(const std::string& fileName) {
MacroRegisterFunctionWithName("CalculatorHTML::toStringLinkFromFileName");
std::stringstream out, refStreamNoRequest, refStreamExercise, refStreamForReal;
std::string urledProblem = HtmlRoutines::convertStringToURLString(fileName, false);
refStreamNoRequest << global.toStringCalculatorArgumentsNoNavigation(nullptr)
<< "fileName=" << urledProblem << "&";
if (global.userStudentVieWOn()) {
refStreamNoRequest << "studentView=true&";
if (global.getWebInput("studentSection") != "") {
refStreamNoRequest << "studentSection="
<< global.getWebInput("studentSection") << "&";
}
}
if (this->topicListFileName != "") {
refStreamNoRequest << "topicList=" << this->topicListFileName << "&";
}
if (this->courseHome != "") {
refStreamNoRequest << "courseHome=" << this->courseHome << "&";
}
if (
fileName == this->topicListFileName ||
fileName == this->courseHome ||
StringRoutines::stringEndsWith(fileName, ".txt")
) {
out << "<a href=\"" << global.displayNameExecutable
<< "?request=template&" << refStreamNoRequest.str() << "\">" << "Home" << "</a> ";
return out.str();
}
if (!global.userGuestMode()) {
refStreamExercise << global.displayNameExecutable
<< "?request=exercise&" << refStreamNoRequest.str();
refStreamForReal << global.displayNameExecutable
<< "?request=scoredQuiz&" << refStreamNoRequest.str();
} else {
refStreamExercise << "?request=exerciseNoLogin&" << refStreamNoRequest.str();
}
if (!global.userGuestMode()) {
out << "<b><a class =\"problemLinkQuiz\" href=\"" << refStreamForReal.str() << "\">"
<< CalculatorHTML::stringScoredQuizzes << "</a></b>";
}
out << "<a class =\"problemLinkPractice\" href=\"" << refStreamExercise.str() << "\">"
<< CalculatorHTML::stringPracticE << "</a>";
return out.str();
}
std::string CalculatorHTML::toStringProblemInfo(const std::string& fileName, const std::string& stringToDisplay) {
MacroRegisterFunctionWithName("CalculatorHTML::toStringLinksFromFileName");
std::stringstream out;
out << this->toStringLinkFromFileName(fileName);
out << this->toStringProblemScoreFull(fileName);
if (global.flagDatabaseCompiled) {
bool problemAlreadySolved = false;
if (this->currentUser.problemData.contains(fileName)) {
ProblemData& problemData = this->currentUser.problemData.getValueCreateEmpty(fileName);
if (problemData.numCorrectlyAnswered >= problemData.answers.size()) {
problemAlreadySolved = true;
}
}
out << this->toStringDeadline(fileName, problemAlreadySolved, false, false);
}
std::string finalStringToDisplay = stringToDisplay;
if (finalStringToDisplay == "") {
finalStringToDisplay = FileOperations::getFileNameFromFileNameWithPath(fileName);
}
out << finalStringToDisplay;
return out.str();
}
bool CalculatorHtmlFunctions::interpretProblemGiveUp(
Calculator& calculator, const Expression& input, Expression& output
) {
MacroRegisterFunctionWithName("CalculatorFunctions::interpretProblemGiveUp");
if (input.size() != 4) {
return calculator << "Expected 3 arguments: problem filename, answer id and randomSeed string. ";
}
std::string oldProblem = global.getWebInput(WebAPI::problem::fileName);
std::string testedProblem = input[1].toString();
global.setWebInput(WebAPI::problem::fileName, testedProblem);
std::string randomSeed = input[3].toString();
std::string answerId = input[2].toString();
global.setWebInput(WebAPI::problem::calculatorAnswerPrefix + answerId, "not used");
JSData result = WebAPIResponse::getAnswerOnGiveUp(randomSeed, nullptr, nullptr, false);
global.webArguments.removeKey(WebAPI::problem::calculatorAnswerPrefix + answerId);
global.setWebInput(WebAPI::problem::fileName, oldProblem);
std::stringstream out;
out << WebAPI::problem::answerGenerationSuccess
<< ":" << result[WebAPI::problem::answerGenerationSuccess] << "<br>";
out << "<br>resultHTML:<br>" << result[WebAPI::result::resultHtml].stringValue;
return output.assignValue(calculator, out.str());
}
bool CalculatorHtmlFunctions::interpretProblem(
Calculator& calculator, const Expression& input, Expression& output
) {
MacroRegisterFunctionWithName("CalculatorFunctions::interpretProblem");
CalculatorHTML problem;
if (!input.isOfType<std::string>(&problem.parser.inputHtml)) {
return calculator << "Extracting calculator expressions from html takes as input strings. ";
}
problem.problemData.flagRandomSeedGiven = true;
problem.problemData.randomSeed = calculator.objectContainer.pseudoRandom.getRandomSeed();
problem.interpretHtml(&calculator.comments);
std::stringstream out;
out << problem.outputHtmlBodyNoTag;
out << "<hr>Time to parse html: " << std::fixed << problem.timeToParseHtml << " second(s). ";
out << "<br>Intermediate interpretation times (per attempt): ";
for (int i = 0; i < problem.timeIntermediatePerAttempt.size; i ++) {
for (int j = 0; j < problem.timeIntermediateComments[i].size; j ++) {
out << "<br>" << problem.timeIntermediateComments[i][j]
<< ": " << problem.timeIntermediatePerAttempt[i][j] << " second(s)";
}
}
out << "<br>Interpretation times (per attempt): "
<< problem.timePerAttempt.toStringCommaDelimited();
return output.assignValue(calculator, out.str());
}
std::string CalculatorHTML::toStringExtractedCommands() {
MacroRegisterFunctionWithName("CalculatorHTML::toStringExtractedCommands");
std::stringstream out;
out << "<hr><b>The commands extracted from the HTML follow.</b><br>";
out << "<table>";
for (int i = 0; i < this->content.size; i ++) {
if (this->content[i].syntacticRole != "") {
out << "<tr>" << "<td>"
<< this->content[i].toStringDebug() << "</td>"
<< "</tr>";
} else {
out << "<tr><td></td></tr>";
}
}
out << "</table>";
out << "<hr><b>The HTML from which the commands were extracted follows.</b><br>" << this->parser.inputHtml
<< "<hr><b>The parsing stack follows.</b>" << this->parser.toStringParsingStack(this->parser.elementStack) << "<hr>";
return out.str();
}
std::string CalculatorHTML::toStringContent() {
MacroRegisterFunctionWithName("CalculatorHTML::toStringContent");
std::stringstream out;
out << "<hr><b>The extracted commands follow.</b><br>";
for (int i = 0; i < this->content.size; i ++) {
out << this->content[i].toStringTagAndContent();
}
out << "<hr><b>The html read follows.</b><br>" << this->parser.inputHtml << "<hr>";
return out.str();
}
void SyntacticElementHTML::resetAllExceptContent() {
this->tag = "";
this->properties.clear();
this->propertiesWithoutValue.clear();
this->syntacticRole = "";
this->flagUseDisplaystyleInMathMode = false;
this->errorComment = "";
}
std::string SyntacticElementHTML::toStringOpenTag(
const std::string& overrideTagIfNonEmpty, bool immediatelyClose
) const {
if (this->tag == "" || this->flagUseMathSpan == false) {
return "";
}
std::stringstream out;
if (overrideTagIfNonEmpty == "") {
out << "<" << this->tag;
} else {
out << "<" << overrideTagIfNonEmpty;
}
for (int i = 0; i < this->properties.size(); i ++) {
out << " " << this->properties.keys[i] << "=\""
<< this->properties.values[i] << "\"";
}
for (int i = 0; i < this->defaultKeysIfMissing.size; i ++) {
if (!this->properties.contains(this->defaultKeysIfMissing[i])) {
out << " " << this->defaultKeysIfMissing[i] << "=\"" << this->defaultValuesIfMissing[i] << "\"";
}
}
if (this->propertiesWithoutValue.size > 0) {
for (int i = 0; i < this->propertiesWithoutValue.size; i ++) {
out << " " << this->propertiesWithoutValue[i];
}
}
if (immediatelyClose) {
out << "/";
}
out << ">";
return out.str();
}
std::string SyntacticElementHTML::toStringCloseTag(
const std::string& overrideTagIfNonEmpty
) const {
if (this->tag == "" || this->flagUseMathSpan == false) {
return "";
}
if (overrideTagIfNonEmpty == "") {
return "</" + this->tag + ">";
} else {
return "</" + overrideTagIfNonEmpty + ">";
}
}
std::string SyntacticElementHTML::toStringTagAndContent() const {
MacroRegisterFunctionWithName("SyntacticElementHTML::toStringTagAndContent");
if (this->syntacticRole == "") {
return this->content;
}
std::stringstream out;
out << this->toStringOpenTag("") + this->content + this->toStringCloseTag("");
return out.str();
}
std::string SyntacticElementHTML::toStringDebug() const {
MacroRegisterFunctionWithName("SyntacticElementHTML::toStringDebug");
if (this->syntacticRole == "") {
return HtmlRoutines::convertStringToHtmlString(this->toStringTagAndContent(), false);
}
std::stringstream out;
out << "<span style='color:green'>";
out << HtmlRoutines::convertStringToHtmlString(this->syntacticRole, false);
out << "</span>";
out << "[" << HtmlRoutines::convertStringToHtmlString(this->toStringTagAndContent(), false) << "]";
if (this->errorComment != "") {
out << "[[<span style='color:red'>" << this->errorComment << "</span>]]";
}
return out.str();
}
std::string SyntacticElementHTML::getKeyValue(const std::string& key) const {
MacroRegisterFunctionWithName("SyntacticElementHTML::getKeyValue");
if (!this->properties.contains(key)) {
return "";
}
return this->properties.getValueNoFail(key);
}
void SyntacticElementHTML::setKeyValue(const std::string& key, const std::string& value) {
MacroRegisterFunctionWithName("SyntacticElementHTML::setKeyValue");
this->properties.setKeyValue(key, value);
}
std::string SyntacticElementHTML::toStringInterpretedBody() {
if (this->syntacticRole == "") {
return this->content;
}
if (this->isInterpretedNotByCalculator()) {
return this->interpretedCommand;
}
std::stringstream out;
out << this->toStringOpenTag("");
if (this->interpretedCommand != "") {
if (this->flagUseMathMode) {
out << "\\( ";
if (this->flagUseDisplaystyleInMathMode) {
out << "\\displaystyle ";
}
}
out << this->interpretedCommand;
if (this->flagUseMathMode) {
out << " \\)";
}
}
out << this->toStringCloseTag("");
return out.str();
}
bool SyntacticElementHTML::isInterpretedNotByCalculator() {
MacroRegisterFunctionWithName("SyntacticElementHTML::isInterpretedNotByCalculator");
if (this->syntacticRole != "command") {
return false;
}
if (
this->tag == "answerCalculatorHighlightStart" ||
this->tag == "answerCalculatorHighlightFinish"
) {
return true;
}
std::string tagClass = this->getTagClass();
return
tagClass == SyntacticElementHTML::Tags::calculatorExamProblem ||
tagClass == "calculatorExamIntermediate" ||
tagClass == SyntacticElementHTML::Tags::calculatorAnswer ||
tagClass == SyntacticElementHTML::Tags::hardCodedAnswer ||
tagClass == "calculatorManageClass" ||
tagClass == "calculatorJavascript" ||
tagClass == "accountInformationLinks" ||
tagClass == "calculatorNavigationHere" ||
tagClass == "calculatorEditPageHere" ||
this->isAnswerElement(nullptr);
}
bool SyntacticElementHTML::isInterpretedByCalculatorOnGeneration() const {
if (this->syntacticRole != SyntacticElementHTML::Tags::command) {
return false;
}
std::string tagClass = this->getTagClass();
return tagClass == SyntacticElementHTML::Tags::calculator ||
tagClass == SyntacticElementHTML::Tags::calculatorHidden ||
tagClass == SyntacticElementHTML::Tags::calculatorShowToUserOnly ;
}
bool SyntacticElementHTML::isInterpretedByCalculatorOnSubmission() {
if (this->syntacticRole != SyntacticElementHTML::Tags::command) {
return false;
}
std::string tagClass = this->getTagClass();
return tagClass == SyntacticElementHTML::Tags::calculator ||
tagClass == SyntacticElementHTML::Tags::calculatorHidden;
}
bool SyntacticElementHTML::isAnswerStandard() const {
if (this->syntacticRole != SyntacticElementHTML::Tags::command) {
return false;
}
return this->getTagClass() == SyntacticElementHTML::Tags::calculatorAnswer;
}
bool SyntacticElementHTML::isAnswer() const {
return this->isAnswerStandard() || this->isAnswerHardCoded();
}
bool SyntacticElementHTML::isAnswerHardCoded() const {
if (this->syntacticRole != SyntacticElementHTML::Tags::command) {
return false;
}
return this->getTagClass() == SyntacticElementHTML::Tags::hardCodedAnswer;
}
bool SyntacticElementHTML::isCalculatorCommand() const {
if (this->syntacticRole != SyntacticElementHTML::Tags::command) {
return false;
}
return this->getTagClass() == SyntacticElementHTML::Tags::calculator;
}
bool SyntacticElementHTML::isCalculatorCommandGenerationOnly() const {
if (this->syntacticRole != SyntacticElementHTML::Tags::command) {
return false;
}
return this->getTagClass() == SyntacticElementHTML::Tags::calculatorShowToUserOnly;
}
bool SyntacticElementHTML::isCalculatorHidden() {
if (this->syntacticRole != SyntacticElementHTML::Tags::command) {
return false;
}
return this->getTagClass() == SyntacticElementHTML::Tags::calculatorHidden;
}
bool SyntacticElementHTML::shouldShow() const {
if (this->syntacticRole != "command") {
return true;
}
std::string tagClass = this->getTagClass();
return
tagClass == SyntacticElementHTML::Tags::calculator ||
tagClass == SyntacticElementHTML::Tags::calculatorShowToUserOnly ||
tagClass == SyntacticElementHTML::Tags::calculatorAnswer ||
tagClass == SyntacticElementHTML::Tags::hardCodedAnswer;
}
bool SyntacticElementHTML::isSolution() {
if (this->syntacticRole != "command") {
return false;
}
std::string tagClass = this->getTagClass();
return tagClass == SyntacticElementHTML::Tags::calculatorSolution;
}
std::string SyntacticElementHTML::getAnswerIdOfOwner() const {
if (this->syntacticRole != "command") {
return "";
}
return StringRoutines::stringTrimWhiteSpace(this->getKeyValue("name"));
}
std::string SyntacticElementHTML::answerIdCorrectIfEmpty() {
std::string result = this->answerIdIfAnswer();
if (this->getKeyValue("id") == "") {
this->properties.setKeyValue("id", result);
}
return result;
}
std::string SyntacticElementHTML::answerIdIfAnswer() const {
if (!this->isAnswer()) {
return "";
}
std::string result = this->getKeyValue("id");
if (result == "") {
result = "answerIdAutogenerated";
}
return StringRoutines::stringTrimWhiteSpace(result);
}
bool SyntacticElementHTML::isAnswerOnGiveUp() {
if (this->syntacticRole != "command") {
return false;
}
std::string tagClass = this->getTagClass();
return tagClass == "calculatorAnswerOnGiveUp";
}
bool SyntacticElementHTML::isCommentBeforeSubmission() {
if (this->syntacticRole != "command") {
return false;
}
std::string tagClass = this->getTagClass();
return tagClass == "calculatorCommentsBeforeSubmission";
}
bool SyntacticElementHTML::isCommentBeforeInterpretation() {
if (this->syntacticRole != "command") {
return false;
}
std::string tagClass = this->getTagClass();
return tagClass == "calculatorCommentsBeforeInterpretation";
}
bool SyntacticElementHTML::isAnswerElement(std::string* desiredAnswerId) {
if (this->syntacticRole != "command") {
return false;
}
std::string tagClass = this->getTagClass();
bool result = tagClass == "calculatorButtonSubmit" ||
tagClass == "calculatorButtonInterpret" ||
tagClass == "calculatorButtonGiveUp" ||
tagClass == "calculatorButtonSolution" ||
tagClass == "calculatorMQField" ||
tagClass == "calculatorMQButtonPanel" ||
tagClass == "calculatorAnswerVerification" ||
tagClass == SyntacticElementHTML::Tags::calculatorSolution;
if (result && desiredAnswerId != nullptr) {
*desiredAnswerId = this->getKeyValue("name");
}
return result;
}
std::string CalculatorHTML::prepareUserInputBoxes() {
MacroRegisterFunctionWithName("CalculatorHTML::PrepareInterpreter");
if (this->flagIsForReal) {
return "";
}
std::stringstream out;
MapList<std::string, std::string, MathRoutines::hashString>& arguments = global.webArguments;
std::string inputNonAnswerReader;
for (int i = 0; i < arguments.size(); i ++) {
if (StringRoutines::stringBeginsWith(arguments.keys[i], "userInputBox", &inputNonAnswerReader)) {
if (inputNonAnswerReader != "" && arguments.values[i] != "") {
out << Calculator::Atoms::setInputBox << "(name = "
<< inputNonAnswerReader
<< ", value = " << HtmlRoutines::convertURLStringToNormal(arguments.values[i], false)
<< "); ";
}
}
}
return out.str();
}
std::string CalculatorHTML::getProblemHeaderEnclosure() {
std::stringstream out;
out << Calculator::Atoms::commandEnclosure << "{}(";
out << Calculator::Atoms::setRandomSeed
<< "{}(" << this->problemData.randomSeed << "); ";
out << this->prepareUserInputBoxes();
out << "); ";
return out.str();
}
std::string CalculatorHTML::getProblemHeaderWithoutEnclosure() {
std::stringstream out;
out << Calculator::Atoms::setRandomSeed
<< " {}(" << this->problemData.randomSeed << "); ";
out << this->prepareUserInputBoxes();
return out.str();
}
bool CalculatorHTML::prepareCommandsGenerateProblem(std::stringstream* comments) {
MacroRegisterFunctionWithName("CalculatorHTML::prepareCommandsGenerateProblem");
(void) comments;
std::stringstream streamCommands, streamCommandsNoEnclosures;
streamCommandsNoEnclosures << this->getProblemHeaderWithoutEnclosure();
streamCommands << this->getProblemHeaderEnclosure();
// <-The first calculator enclosure contains the header.
int commandCount = 2;
// <- Two commands at the start: the opCommandSequence command and
// the first enclosure.
for (int i = 0; i < this->content.size; i ++) {
SyntacticElementHTML& current = this->content[i];
if (!current.isInterpretedByCalculatorOnGeneration()) {
continue;
}
streamCommands << current.commandEnclosed();
streamCommandsNoEnclosures << current.commandCleaned();
current.commandIndex = commandCount;
commandCount ++;
}
this->problemData.commandsGenerateProblem = streamCommands.str();
this->problemData.commandsGenerateProblemNoEnclosures = streamCommandsNoEnclosures.str();
std::stringstream debugStream;
debugStream << "<a href='"
<< HtmlRoutines::getCalculatorComputationURL(
this->problemData.commandsGenerateProblemNoEnclosures
) << "' target='_blank'>"
<< "Input link </a>";
this->problemData.commandsGenerateProblemLink = debugStream.str();
return true;
}
bool CalculatorHTML::parseHTMLPrepareCommands(std::stringstream* comments) {
MacroRegisterFunctionWithName("CalculatorHTML::parseHTMLPrepareCommands");
if (!this->parser.parseHTML(comments)) {
return false;
}
return this->prepareCommands(comments);
}
bool CalculatorHTML::prepareCommands(std::stringstream* comments) {
MacroRegisterFunctionWithName("CalculatorHTML::prepareCommands");
if (!this->prepareCommandsGenerateProblem(comments)) {
return false;
}
for (int i = 0; i < this->problemData.answers.size(); i ++) {
Answer& answer = this->problemData.answers.values[i];
if (!this->prepareCommandsAnswer(answer, comments)) {
return false;
}
if (!this->prepareCommandsAnswerOnGiveUp(answer, comments)) {
return false;
}
if (!this->exrtactSolutionCommands(answer, comments)) {
return false;
}
if (!this->prepareCommentsBeforeSubmission(answer, comments)) {
return false;
}
if (!this->prepareCommentsBeforeInterpretation(answer, comments)) {
return false;
}
}
return true;
}
bool CalculatorHTML::prepareCommandsAnswerOnGiveUp(
Answer& answer, std::stringstream* comments
) {
MacroRegisterFunctionWithName("CalculatorHTML::prepareCommandsAnswerOnGiveUp");
if (answer.flagAnswerHardcoded) {
return true;
}
(void) comments;
std::stringstream streamCommands;
for (int i = 0; i < this->content.size; i ++) {
SyntacticElementHTML& current = this->content[i];
if (!current.isAnswerOnGiveUp()) {
continue;
}
if (current.getKeyValue("name") == answer.answerId) {
streamCommands << current.commandCleaned();
}
}
answer.commandAnswerOnGiveUp = streamCommands.str();
return true;
}
bool CalculatorHTML::prepareCommentsBeforeSubmission(
Answer& answer, std::stringstream* comments
) {
MacroRegisterFunctionWithName("CalculatorHTML::prepareCommentsBeforeSubmission");
(void) comments;
std::stringstream streamCommands;
for (int i = 0; i < this->content.size; i ++) {
SyntacticElementHTML& current = this->content[i];
if (!current.isCommentBeforeSubmission()) {
continue;
}
if (current.getKeyValue("name") != answer.answerId) {
continue;
}
streamCommands << current.commandCleaned();
}
answer.commandsCommentsBeforeSubmission = streamCommands.str();
return true;
}
bool CalculatorHTML::prepareCommentsBeforeInterpretation(
Answer& answer, std::stringstream* comments
) {
MacroRegisterFunctionWithName("CalculatorHTML::prepareCommentsBeforeInterpretation");
(void) comments;
std::stringstream streamCommands;
for (int i = 0; i < this->content.size; i ++) {
SyntacticElementHTML& current = this->content[i];
if (!current.isCommentBeforeInterpretation()) {
continue;
}
if (current.getKeyValue("name") != answer.answerId) {
continue;
}
streamCommands << current.commandCleaned();
}
answer.commandsCommentsBeforeInterpretation = streamCommands.str();
return true;
}
bool CalculatorHTML::exrtactSolutionCommands(
Answer& answer,
std::stringstream* comments
) {
(void) comments;
std::stringstream streamCommands;
int numCommandsSoFar = 2;
for (int j = 0; j < answer.solutionElements.size; j ++) {
SyntacticElementHTML& current = answer.solutionElements[j];
if (
!current.isInterpretedByCalculatorOnGeneration()
) {
continue;
}
current.commandIndex = numCommandsSoFar;
numCommandsSoFar ++;
streamCommands << Calculator::Atoms::commandEnclosure << "{}("
<< current.commandCleaned() << "); ";
}
answer.commandsSolutionOnly = streamCommands.str();
return true;
}
Answer::Answer() {
this->numSubmissions = 0;
this->numCorrectSubmissions = 0;
this->flagAutoGenerateSubmitButtons = true;
this->flagAutoGenerateMQButtonPanel = true;
this->flagAutoGenerateMQfield = true;
this->flagAutoGenerateVerificationField = true;
this->flagAutoGenerateButtonSolution = true;
this->flagAnswerVerificationFound = false;
this->flagAnswerHardcoded = false;
}
bool Answer::prepareAnswer(
const SyntacticElementHTML& input,
std::stringstream& commands,
std::stringstream& commandsBody,
std::stringstream& commandsNoEnclosures,
std::stringstream& commandsBodyNoEnclosures
) {
if (
!input.isAnswer() ||
input.answerIdIfAnswer() != this->answerId
) {
return false;
}
if (input.isAnswerStandard()) {
return this->prepareAnswerStandard(
input,
commands,
commandsBody,
commandsNoEnclosures,
commandsBodyNoEnclosures
);
}
return this->prepareAnswerHardCoded(
input,
commands,
commandsBody,
commandsNoEnclosures,
commandsBodyNoEnclosures
);
}
bool Answer::prepareAnswerStandard(
const SyntacticElementHTML &input,
std::stringstream& commands,
std::stringstream& commandsBody,
std::stringstream& commandsNoEnclosures,
std::stringstream& commandsBodyNoEnclosures
) {
std::string stringCommandsBody = commandsBody.str();
if (stringCommandsBody != "") {
commands << Calculator::Atoms::commandEnclosure << "{}(" << stringCommandsBody << ");\n";
commandsNoEnclosures << commandsBodyNoEnclosures.str();
}
this->commandsBeforeAnswer = commands.str();
this->commandsBeforeAnswerNoEnclosuresForDEBUGGING = commandsNoEnclosures.str();
this->commandVerificationOnly = input.commandCleaned();
this->flagAnswerHardcoded = false;
return true;
}
bool Answer::prepareAnswerHardCoded(
const SyntacticElementHTML& input,
std::stringstream& commands,
std::stringstream& commandsBody,
std::stringstream& commandsNoEnclosures,
std::stringstream& commandsBodyNoEnclosures
) {
std::string stringCommandsBody = commandsBody.str();
if (stringCommandsBody != "") {
commands << SyntacticElementHTML::cleanUpEncloseCommand(stringCommandsBody);
commandsNoEnclosures << commandsBodyNoEnclosures.str();
}
this->commandsBeforeAnswer = commands.str();
this->commandsBeforeAnswerNoEnclosuresForDEBUGGING = commandsNoEnclosures.str();
this->commandAnswerOnGiveUp = input.content;
this->flagAnswerHardcoded = true;
return true;
}
bool CalculatorHTML::prepareCommandsAnswer(Answer& answer, std::stringstream* comments) {
MacroRegisterFunctionWithName("CalculatorHTML::prepareCommandsAnswer");
std::stringstream commands;
std::stringstream commandsNoEnclosures;
commands << this->getProblemHeaderEnclosure(); // first calculator enclosure contains the header
commandsNoEnclosures << this->getProblemHeaderWithoutEnclosure();
std::stringstream commandsBody;
std::stringstream commandsBodyNoEnclosures;
for (int i = 0; i < this->content.size; i ++) {
SyntacticElementHTML& current = this->content[i];
if (
!current.isCalculatorHidden() &&
!current.isCalculatorCommand() &&
!current.isAnswer()
) {
continue;
}
if (answer.prepareAnswer(
current,
commands,
commandsBody,
commandsNoEnclosures,
commandsBodyNoEnclosures
)) {
return true;
}
if (this->content[i].isCalculatorHidden() || this->content[i].isCalculatorCommand()) {
commandsBody << current.commandEnclosed();
commandsBodyNoEnclosures << current.commandCleaned();
}
}
if (comments != nullptr) {
*comments << "<b>Something is wrong: did not find answer for answer tag: "
<< answer.answerId << ". </b>";
}
return false;
}
bool CalculatorHTML::prepareAndExecuteCommands(Calculator& interpreter, std::stringstream* comments) {
MacroRegisterFunctionWithName("Problem::prepareAndExecuteCommands");
double startTime = global.getElapsedSeconds();
this->prepareCommands(comments);
interpreter.initialize(Calculator::Mode::educational);
interpreter.flagWriteLatexPlots = false;
interpreter.flagPlotNoControls = true;
this->timeIntermediatePerAttempt.lastObject()->addOnTop(global.getElapsedSeconds()-startTime);
this->timeIntermediateComments.lastObject()->addOnTop("calculator initialize time");
if (global.userDebugFlagOn() && global.userDefaultHasProblemComposingRights()) {
this->logCommandsProblemGeneratioN << "<b>Input commands:</b> "
<< this->problemData.commandsGenerateProblemLink
<< "<br>\n"
<< this->problemData.commandsGenerateProblem << "<br>";
}
interpreter.evaluate(this->problemData.commandsGenerateProblem);
this->timeIntermediatePerAttempt.lastObject()->addOnTop(global.getElapsedSeconds() - startTime);
this->timeIntermediateComments.lastObject()->addOnTop("calculator evaluation time");
bool result = !interpreter.flagAbortComputationASAP && interpreter.parser.syntaxErrors == "";
if (!result && comments != nullptr) {
*comments << "<br>Failed to interpret your file. "
<< HtmlRoutines::getCalculatorComputationAnchorSameURL(
this->problemData.commandsGenerateProblemNoEnclosures, "Failed commands:"
) << "<br>"
<< this->problemData.commandsGenerateProblem
<< "<br>";
if (global.userDefaultHasAdminRights()) {
*comments << "The result of the interpretation attempt is:<br>"
<< interpreter.outputString << "<br><b>Comments</b><br>"
<< interpreter.outputCommentsString;
} else {
*comments << "This may be a bug with the problem. "
<< "Feel free to take a screenshot of the issue and "
<< "email it to the site admin(s). ";
}
}
for (int i = 0; i < interpreter.objectContainer.userInputTextBoxesWithValues.size(); i ++) {
this->problemData.inputNonAnswerIds.addOnTop(
interpreter.objectContainer.userInputTextBoxesWithValues.keys[i]
);
}
return result;
}
std::string SyntacticElementHTML::getTagClass() const {
std::string className = this->getKeyValue("class");
if (this->tag != "") {
if (
!CalculatorHTML::Parser::calculatorClasses.contains(this->tag) &&
CalculatorHTML::Parser::calculatorClasses.contains(className)
) {
return className;
}
return this->tag;
}
return className;
}
bool CalculatorHTML::prepareSectionList(std::stringstream& commentsOnFailure) {
MacroRegisterFunctionWithName("CalculatorHTML::prepareSectionList");
(void) commentsOnFailure;
if (this->flagSectionsPrepared) {
return true;
}
this->flagSectionsPrepared = true;
if (
this->currentUser.sectionsTaught.size == 0 || (
this->currentUser.userRole != UserCalculator::Roles::administator &&
this->currentUser.userRole != UserCalculator::Roles::teacher
)
) {
if (this->currentUser.sectionComputed != "") {
this->databaseStudentSections.addOnTop(this->currentUser.sectionComputed);
return true;
}
}
this->databaseStudentSections.addListOnTop(this->currentUser.sectionsTaught);
return true;
}
void CalculatorHTML::interpretManageClass(SyntacticElementHTML& inputOutput) {
MacroRegisterFunctionWithName("CalculatorHTML::interpretManageClass");
if (!global.userDefaultHasAdminRights() || global.userStudentVieWOn()) {
return;
}
if (!global.flagDatabaseCompiled) {
inputOutput.interpretedCommand = "<b>Managing class not available (no database).</b>";
return;
}
std::stringstream out;
out << "<a href=\"" << global.displayNameExecutable << "?request=accounts\"> Manage accounts</a>";
inputOutput.interpretedCommand = out.str();
}
bool CalculatorHTML::computeAnswerRelatedStrings(SyntacticElementHTML& inputOutput) {
MacroRegisterFunctionWithName("CalculatorHTML::computeAnswerRelatedStrings");
std::string desiredAnswerId = inputOutput.answerIdIfAnswer();
if (desiredAnswerId == "") {
inputOutput.interpretedCommand = "<b>Error: could not generate submit button: "
"the answer tag does not have a valid id. Please fix the problem template.</b>";
return false;
}
int index = this->getAnswerIndex(desiredAnswerId);
if (index == - 1) {
global.fatal << "This is not supposed to happen: problem has syntactic element with answerId: "
<< desiredAnswerId << " but the answerId is missing from the list of known answer ids. "
<< this->problemData.toStringAvailableAnswerIds() << global.fatal;
}
Answer& currentA = this->problemData.answers.values[index];
if (index < this->answerHighlights.size) {
currentA.htmlAnswerHighlight = this->answerHighlights[index];
} else {
currentA.htmlAnswerHighlight = "";
}
std::string& answerId = currentA.answerId;
currentA.idAnswerPanel = "spanAnswerPanel" + answerId;
this->numberOfAnswerIdsMathquilled ++;
currentA.idVerificationSpan = "verification" + answerId;
currentA.idSpanSolution = "solution" + answerId;
currentA.idMathEquationField = answerId + "MQSpanId";
currentA.idMQFieldLocation = answerId + "MQSpanIdLocation";
if (currentA.idMQButtonPanelLocation == "") {
currentA.idMQButtonPanelLocation = answerId + "MQbuttonPanel";
}
std::stringstream previewAnswerStream;
previewAnswerStream << "previewAnswers('" << answerId << "', '"
<< currentA.idVerificationSpan << "');";
currentA.properties.clear();
for (int i = 0; i < inputOutput.properties.size(); i ++) {
if (inputOutput.properties.keys[i] == "id") {
continue;
}
currentA.properties.setKeyValue(inputOutput.properties.keys[i], inputOutput.properties.values[i]);
}
currentA.javascriptPreviewAnswer = previewAnswerStream.str();
currentA.idButtonSubmit = "buttonSubmit" + answerId;
currentA.idButtonInterpret = "buttonInterpret" + answerId;
currentA.idButtonAnswer = "buttonAnswer" + answerId;
currentA.idButtonSolution = "buttonSolution" + answerId;
std::stringstream verifyStream;
int numCorrectSubmissions = currentA.numCorrectSubmissions;
int numSubmissions = currentA.numSubmissions;
if (
global.requestType == "scoredQuiz" ||
global.requestType == "scoredQuizJSON"
) {
if (numCorrectSubmissions > 0) {
verifyStream << "<b style =\"color:green\">Correctly answered: \\("
<< currentA.firstCorrectAnswerClean << "\\) </b> ";
if (numSubmissions > 0) {
verifyStream << "<br>Used: " << numSubmissions << " attempt(s) (" << numCorrectSubmissions << " correct).";
}
} else if (numSubmissions > 0) {
verifyStream << numSubmissions << " attempt(s) so far. ";
}
}
currentA.htmlSpanVerifyAnswer = verifyStream.str();
return true;
}
void CalculatorHTML::interpretGenerateStudentAnswerButton(SyntacticElementHTML& inputOutput) {
MacroRegisterFunctionWithName("CalculatorHTML::interpretGenerateStudentAnswerButton");
if (!this->computeAnswerRelatedStrings(inputOutput)) {
return;
}
std::string answerId = inputOutput.answerIdIfAnswer();
Answer& answer = this->problemData.answers.values[this->getAnswerIndex(answerId)];
std::stringstream out;
out << "<span class='panelAnswer' id='" << answer.idAnswerPanel << "'></span>";
inputOutput.interpretedCommand = out.str();
}
void CalculatorHTML::interpretIfAnswer(SyntacticElementHTML& inputOutput) {
MacroRegisterFunctionWithName("CalculatorHTML::interpretIfAnswer");
if (!inputOutput.isAnswer()) {
return;
}
this->interpretGenerateStudentAnswerButton(inputOutput);
}
void CalculatorHTML::interpretNotByCalculatorNotAnswer(SyntacticElementHTML& inputOutput) {
MacroRegisterFunctionWithName("CalculatorHTML::interpretNotByCalculatorNotAnswer");
std::string tagClass = inputOutput.getTagClass();
if (tagClass == SyntacticElementHTML::Tags::calculatorExamProblem || tagClass == "calculatorExamIntermediate") {
this->interpretGenerateLink(inputOutput);
} else if (tagClass == "calculatorManageClass") {
this->interpretManageClass(inputOutput);
} else if (tagClass == "accountInformationLinks") {
this->interpretAccountInformationLinks(inputOutput);
} else if (tagClass == "calculatorJavascript") {
this->interpretJavascripts(inputOutput);
}
}
std::string CalculatorHTML::cleanUpFileName(const std::string& inputLink) {
MacroRegisterFunctionWithName("CalculatorHTML::cleanUpFileName");
if (inputLink.size() == 0) {
return inputLink;
}
unsigned firstMeaningfulChar = 0;
for (; firstMeaningfulChar < inputLink.size(); firstMeaningfulChar ++) {
if (
inputLink[firstMeaningfulChar] != '\n' &&
inputLink[firstMeaningfulChar] != '\r' &&
inputLink[firstMeaningfulChar] != '\t' &&
inputLink[firstMeaningfulChar] != ' '
) {
break;
}
}
unsigned lastMeaningfulChar = static_cast<unsigned>(inputLink.size()) - 1;
for (; lastMeaningfulChar > firstMeaningfulChar; lastMeaningfulChar --) {
if (
inputLink[lastMeaningfulChar] != '\n' &&
inputLink[lastMeaningfulChar] != '\r' &&
inputLink[lastMeaningfulChar] != '\t' &&
inputLink[lastMeaningfulChar] != ' '
) {
break;
}
}
if (firstMeaningfulChar >= inputLink.size()) {
return "";
}
return inputLink.substr(firstMeaningfulChar, lastMeaningfulChar - firstMeaningfulChar + 1);
}
#include "crypto.h"
std::string CalculatorHTML::getDeadlineNoInheritance(const std::string& id) {
MacroRegisterFunctionWithName("CalculatorHTML::getDeadlineNoInheritance");
(void) id;
if (!global.flagDatabaseCompiled) {
// deadline not present.
return "";
}
if (!this->currentUser.problemData.contains(id)) {
return "";
}
ProblemDataAdministrative& currentProb = this->currentUser.problemData.getValueCreateNoInitialization((id)).adminData;
if (!currentProb.deadlinesPerSection.contains(this->currentUser.sectionComputed)) {
return "";
}
return currentProb.deadlinesPerSection.getValueCreateEmpty(this->currentUser.sectionComputed);
}
std::string CalculatorHTML::getDeadline(
const std::string& problemName, const std::string& sectionNumber, bool& outputIsInherited
) {
MacroRegisterFunctionWithName("CalculatorHTML::getDeadline");
(void) problemName;
(void) sectionNumber;
(void) outputIsInherited;
outputIsInherited = true;
std::string result;
if (!global.flagDatabaseCompiled) {
return "While getting deadline: database not compiled";
}
int topicIndex = this->topics.topics.getIndex(problemName);
if (topicIndex == - 1) {
return problemName + " not found in topic list. ";
}
TopicElement& currentTopic = this->topics.topics.getValueCreateEmpty(problemName);
for (int i = currentTopic.parentTopics.size - 1; i >= 0; i --) {
const std::string& containerName = this->topics.topics.keys[currentTopic.parentTopics[i]];
if (this->currentUser.problemData.contains(containerName)) {
ProblemDataAdministrative& currentProblem =
this->currentUser.problemData.getValueCreateNoInitialization(containerName).adminData;
result = currentProblem.deadlinesPerSection.getValueCreateEmpty(sectionNumber);
if (StringRoutines::stringTrimWhiteSpace(result) != "") {
outputIsInherited = (containerName != problemName);
return result;
}
}
}
return result;
}
std::string CalculatorHTML::toStringOneDeadlineFormatted(
const std::string& topicID,
const std::string& sectionNumber,
bool problemAlreadySolved,
bool returnEmptyStringIfNoDeadline,
bool isSection
) {
std::stringstream out;
(void) problemAlreadySolved;
(void) isSection;
bool deadlineIsInherited = false;
std::string currentDeadline = this->getDeadline(topicID, sectionNumber, deadlineIsInherited);
if (currentDeadline == "") {
if (returnEmptyStringIfNoDeadline) {
return "";
}
out << "<span style =\"color:orange\">No deadline yet</span>";
return out.str();
}
if (!global.flagDatabaseCompiled) {
out << "Database not running: no deadlines";
return out.str();
}
TimeWrapper now, deadline; //<-needs a fix for different time formats.
//<-For the time being, we hard-code it to month/day/year format (no time to program it better).
std::stringstream badDateStream;
if (!deadline.assignMonthDayYear(currentDeadline, badDateStream)) {
out << "<span style =\"color:red\">" << badDateStream.str() << "</span>";
}
// out << "deadline.date: " << deadline.time.tm_mday;
now.assignLocalTime();
// out << "Now: " << asctime (&now.time) << " mktime: " << mktime(&now.time)
// << " deadline: " << asctime(&deadline.time) << " mktime: " << mktime(&deadline.time);
double secondsTillDeadline = deadline.subtractAnotherTimeFromMeInSeconds(now) + 7 * 3600;
std::stringstream hoursTillDeadlineStream;
bool deadlineIsNear = secondsTillDeadline < 24 * 3600 && !problemAlreadySolved && !isSection;
bool deadlineHasPassed = (secondsTillDeadline < 0);
if (deadlineIsInherited && !global.userStudentVieWOn()) {
out << "Inherited: ";
} else if (deadlineIsInherited && isSection && returnEmptyStringIfNoDeadline) {
return "";
} else {
out << "Deadline: ";
}
if (!deadlineHasPassed) {
if (deadlineIsNear) {
hoursTillDeadlineStream << "<span style =\"color:red\">"
<< TimeWrapper::toStringSecondsToDaysHoursSecondsString(secondsTillDeadline, false, true) << "</span>";
} else {
hoursTillDeadlineStream << TimeWrapper::toStringSecondsToDaysHoursSecondsString(secondsTillDeadline, false, true)
<< " left. ";
}
} else {
hoursTillDeadlineStream << "[passed].";
}
if (deadlineHasPassed && !problemAlreadySolved) {
out << "<span style =\"color:blue\">" << currentDeadline << "</span> ";
out << "<b style =\"red\">[passed].</b>";
} else {
if (problemAlreadySolved && !isSection) {
out << "<span style =\"color:green\">" << currentDeadline << "</span> ";
} else if (deadlineIsNear && !isSection) {
out << "<span style =\"color:red\">" << currentDeadline << "</span> ";
} else {
out << "<span style =\"color:brown\">" << currentDeadline << "</span> ";
}
out << hoursTillDeadlineStream.str();
}
return
//"[<span style =\"color:green\"><b>disabled</b> </span>] "+
out.str();
}
std::string CalculatorHTML::toStringAllSectionDeadlines(const std::string& topicID, bool isSection) {
MacroRegisterFunctionWithName("CalculatorHTML::toStringAllSectionDeadlines");
if (!global.userDefaultHasAdminRights())
return "";
std::stringstream out;
out << "<table>";
for (int i = 0; i < this->databaseStudentSections.size; i ++) {
if (this->databaseStudentSections[i] == "") {
continue;
}
out << "<tr><td>Section " << this->databaseStudentSections[i] << ":</td>";
out << "<td>"
<< this->toStringOneDeadlineFormatted(topicID, this->databaseStudentSections[i], false, false, isSection)
<< "</td>";
out << "</tr>";
}
out << "</table>";
return out.str();
}
std::string CalculatorHTML::toStringDeadline(
const std::string& topicID, bool problemAlreadySolved, bool returnEmptyStringIfNoDeadline, bool isSection
) {
MacroRegisterFunctionWithName("CalculatorHTML::ToStringDeadlineWithModifyButton");
(void) topicID;
(void) problemAlreadySolved;
(void) returnEmptyStringIfNoDeadline;
(void) isSection;
if (!global.flagDatabaseCompiled) {
return "Database not available";
}
if (global.userGuestMode()) {
return "deadlines require login";
} else if (
global.userDefaultHasAdminRights() &&
global.userStudentVieWOn()
) {
std::string sectionNum = HtmlRoutines::convertURLStringToNormal(
global.getWebInput("studentSection"), false
);
return this->toStringOneDeadlineFormatted(
topicID, sectionNum, problemAlreadySolved, returnEmptyStringIfNoDeadline, isSection
);
} else {
return this->toStringOneDeadlineFormatted(
topicID,
this->currentUser.sectionComputed,
problemAlreadySolved,
returnEmptyStringIfNoDeadline,
isSection
);
}
// return "";
}
void CalculatorHTML::computeDeadlinesAllSections(TopicElement& inputOutput) {
MacroRegisterFunctionWithName("CalculatorHTML::computeDeadlinesAllSections");
inputOutput.deadlinesPerSectioN.initializeFillInObject(this->databaseStudentSections.size, "");
inputOutput.deadlinesAreInherited.initializeFillInObject(this->databaseStudentSections.size, false);
for (int i = 0; i < this->databaseStudentSections.size; i ++) {
inputOutput.deadlinesPerSectioN[i] = this->getDeadline(
inputOutput.id, this->databaseStudentSections[i], inputOutput.deadlinesAreInherited[i]
);
if (inputOutput.deadlinesAreInherited[i]) {
inputOutput.deadlinesPerSectioN[i] = "";
}
}
}
void CalculatorHTML::computeDeadlinesAllSectionsNoInheritance(TopicElement& inputOutput) {
MacroRegisterFunctionWithName("CalculatorHTML::computeDeadlinesAllSectionsNoInheritance");
inputOutput.deadlinesPerSectioN.initializeFillInObject(this->databaseStudentSections.size, "");
for (int i = 0; i < this->databaseStudentSections.size; i ++) {
ProblemDataAdministrative& currentProb =
this->currentUser.problemData.getValueCreateNoInitialization(inputOutput.id).adminData;
inputOutput.deadlinesPerSectioN[i] =
currentProb.deadlinesPerSection.getValueCreateEmpty(this->databaseStudentSections[i]);
}
}
std::string CalculatorHTML::toStringInterprettedCommands(Calculator &calculator, List<SyntacticElementHTML>& elements) {
MacroRegisterFunctionWithName("CalculatorHTML::toStringInterprettedCommands");
std::stringstream out;
out << "<table>";
int commandCounter = calculator.programExpression.size() - 1;
for (int eltCounter = elements.size - 1; eltCounter > 0; eltCounter --) {
SyntacticElementHTML& currentElt = elements[eltCounter];
std::string currentEltString = currentElt.getTagClass() + "[" + currentElt.content.substr(0, 10) + "...]";
if (!currentElt.isInterpretedByCalculatorOnGeneration()) {
out << "<tr><td>" << currentEltString << "</td>"
<< "<td>"
<< calculator.programExpression[commandCounter].toString()
<< "</td></tr>";
commandCounter --;
continue;
}
for (; commandCounter > 1; commandCounter --) {
std::string currentString= calculator.programExpression[commandCounter].toString();
out << "<tr><td>" << currentEltString << "</td><td>"
<< currentString << "</td></tr>";
if (currentString == "SeparatorBetweenSpans") {
break;
}
}
}
out << "</table>";
return out.str();
}
bool CalculatorHTML::processOneExecutedCommand(
Calculator& interpreter,
SyntacticElementHTML& element,
std::stringstream& comments
) {
(void) comments;
MacroRegisterFunctionWithName("CalculatorHTML::processOneExecutedCommand");
if (!element.isInterpretedByCalculatorOnGeneration()) {
element.interpretedCommand = "";
return true;
}
if (
element.commandIndex >= interpreter.programExpression.size() ||
element.commandIndex < 0
) {
std::stringstream errorStream;
errorStream << "<b>Syntactic element "
<< element.toStringDebug() << " has wrongly computed commandIndex: "
<< element.commandIndex << ". "
<< "Please report this error to the website admins. </b>";
element.interpretedCommand = errorStream.str();
return false;
}
if (!interpreter.programExpression[element.commandIndex].startsWith(interpreter.opCommandEnclosure())) {
global.fatal << "Element: "
<< interpreter.programExpression[element.commandIndex].toString()
<< " in " << interpreter.programExpression.toString()
<< " is supposed to be a command enclosure but apparently isn't. " << global.fatal;
}
Expression interpretedExpression = interpreter.programExpression[element.commandIndex][1];
if (interpretedExpression.startsWith(interpreter.opCommandSequence()) && interpretedExpression.size() == 2) {
interpretedExpression = interpretedExpression[1];
}
if (interpretedExpression.startsWith(interpreter.opCommandSequence())) {
element.flagUseMathMode = false;
}
FormatExpressions format;
format.flagExpressionIsFinal = true;
format.flagMakingExpressionTableWithLatex = true;
format.flagIncludeExtraHtmlDescriptionsInPlots = false;
format.flagUseQuotes = false;
format.flagUseLatex = true;
format.flagUseQuotes = false;
format.flagMakingExpressionTableWithLatex = true;
element.interpretedCommand = "";
element.interpretedCommand += interpretedExpression.toString(&format);
element.flagUseDisplaystyleInMathMode = (element.content.find("\\displaystyle") != std::string::npos);
element.flagUseMathMode = true;
element.flagUseMathSpan = false;
if (
interpretedExpression.isOfType<std::string> () ||
interpretedExpression.isOfType<Plot>() ||
element.getKeyValue("noTags") == "true"
) {
element.flagUseMathMode = false;
}
return true;
}
bool CalculatorHTML::processExecutedCommands(
Calculator& interpreter,
List<SyntacticElementHTML>& elements,
std::stringstream& comments
) {
MacroRegisterFunctionWithName("CalculatorHTML::processExecutedCommands");
(void) comments;
bool result = true;
interpreter.objectContainer.resetPlots();
for (int i = 0; i < elements.size; i ++) {
if (!this->processOneExecutedCommand(interpreter, elements[i], comments)) {
result = true;
}
}
return result;
}
void CalculatorHTML::logProblemGenerationObsolete(Calculator& interpreter) {
if (!global.userDebugFlagOn() || !global.userDefaultHasProblemComposingRights()) {
return;
}
std::stringstream streamLog;
streamLog << "<table border ='1'>";
for (int i = 0; i < interpreter.programExpression.size(); i ++) {
streamLog << "<tr>";
for (int j = 0; j < this->content.size; j ++) {
if (this->content[j].commandIndex == i) {
streamLog << "<td>" << this->content[j].toStringDebug() << "</td>";
}
}
streamLog << "<td>" << interpreter.programExpression[i].toString()
<< "</td></tr>";
}
streamLog << "</table>";
this->logCommandsProblemGeneratioN << streamLog.str();
}
void CalculatorHTML::figureOutCurrentProblemList(std::stringstream& comments) {
MacroRegisterFunctionWithName("CalculatorHTML::figureOutCurrentProblemList");
if (this->flagParentInvestigated) {
return;
}
this->flagParentInvestigated = true;
this->topicListFileName = HtmlRoutines::convertURLStringToNormal(global.getWebInput(WebAPI::problem::topicList), false);
this->loadAndParseTopicList(comments);
}
bool CalculatorHTML::interpretHtml(std::stringstream* comments) {
MacroRegisterFunctionWithName("CalculatorHTML::interpretHtml");
double startTime = global.getElapsedSeconds();
if (!this->parser.parseHTML(comments)) {
this->outputHtmlBodyNoTag = "<b>Failed to interpret html input. </b><br>" + this->toStringContent();
this->timeToParseHtml = global.getElapsedSeconds() - startTime;
return false;
}
this->timeToParseHtml = global.getElapsedSeconds() - startTime;
this->maxInterpretationAttempts = 25;
this->randomSeedPerAttempt.setSize(this->maxInterpretationAttempts);
UnsecurePseudoRandomGenerator generator;
if (!this->problemData.flagRandomSeedGiven) {
generator.setRandomSeedSmall(static_cast<uint32_t>(time(nullptr)));
} else {
generator.setRandomSeedSmall(this->problemData.randomSeed);
}
this->randomSeedPerAttempt[0] = generator.getRandomSeed();
for (int i = 1; i < this->randomSeedPerAttempt.size; i ++) {
this->randomSeedPerAttempt[i] = generator.getRandomNonNegativeLessThanMaximumSeed();
}
this->timePerAttempt.setSize(0);
this->timeIntermediatePerAttempt.setSize(0);
this->timeIntermediateComments.setSize(0);
this->numberOfInterpretationAttempts = 0;
for (int i = 0; i < this->maxInterpretationAttempts; i ++) {
this->problemData.randomSeed = this->randomSeedPerAttempt[i];
this->numberOfInterpretationAttempts = i + 1;
startTime = global.getElapsedSeconds();
this->timeIntermediatePerAttempt.setSize(this->timeIntermediatePerAttempt.size + 1);
this->timeIntermediatePerAttempt.lastObject()->setSize(0);
this->timeIntermediateComments.setSize(this->timeIntermediateComments.size + 1);
this->timeIntermediateComments.lastObject()->setSize(0);
Calculator interpreter;
std::stringstream commentsOnLastFailure;
if (this->interpretHtmlOneAttempt(interpreter, commentsOnLastFailure)) {
this->timePerAttempt.addOnTop(global.getElapsedSeconds() - startTime);
this->problemData.checkConsistency();
return true;
}
this->timePerAttempt.addOnTop(global.getElapsedSeconds() - startTime);
if (this->numberOfInterpretationAttempts >= this->maxInterpretationAttempts && comments != nullptr) {
*comments << "Failed attempt " << this->numberOfInterpretationAttempts
<< " to interpret your file. Attempted random seeds: "
<< this->randomSeedPerAttempt.toStringCommaDelimited()
<< "Last interpretation failure follows. <br>"
<< commentsOnLastFailure.str();
}
}
if (comments != nullptr) {
*comments << "<hr>Failed to evaluate the commands: " << this->numberOfInterpretationAttempts
<< " attempts made. ";
}
if (this->flagIsForReal) {
this->storeRandomSeedCurrent(comments);
if (comments != nullptr) {
*comments << "<b>Your random seed has been reset due to a finicky problem generation. </b>";
}
}
this->problemData.checkConsistency();
return false;
}
bool CalculatorHTML::Parser::isWhiteSpace(const std::string& input) {
if (input.size() != 1) {
return false;
}
return input == " " || input == "\n" || input == "\t";
}
bool CalculatorHTML::Parser::isSplittingChar(const std::string& input) {
if (input.size() != 1) {
return false;
}
return this->splittingChars.contains(input[0]);
}
std::string CalculatorHTML::Parser::toStringParsingStack(
List<SyntacticElementHTML>& stack
) {
MacroRegisterFunctionWithName("CalculatorHTML::toStringParsingStack");
std::stringstream out;
out << "#Non-dummy elts: " << stack.size - SyntacticElementHTML::parsingDummyElements << ". ";
for (int i = SyntacticElementHTML::parsingDummyElements; i < stack.size; i ++) {
out << "<span style ='color:" << ((i % 2 == 0) ? "orange" : "blue") << "'>";
std::string content = stack[i].toStringDebug();
if (content.size() == 0) {
content = "<b>empty</b>";
} else if (content == " ") {
content = "_";
}
out << content << "</span>";
}
return out.str();
}
int CalculatorHTML::getAnswerIndex(const std::string& desiredAnswerId) {
return this->problemData.answers.getIndex(desiredAnswerId);
}
bool CalculatorHTML::Parser::canBeMerged(
const SyntacticElementHTML& left, const SyntacticElementHTML& right
) {
MacroRegisterFunctionWithName("SyntacticElementHTML::canBeMerged");
if (left.syntacticRole != "" || right.syntacticRole != "") {
return false;
}
if (this->isSplittingChar(left.content) && left.content != " ") {
return false;
}
if (this->isSplittingChar(right.content) && right.content != " ") {
return false;
}
return true;
}
void TopicElementParser::initializeElementTypes() {
MacroRegisterFunctionWithName("CalculatorHTML::initializeElementTypes");
// Please note: the static_cast<int> below is needed with the present gcc compiler version.
// Without it, you should get linker errors.
// See: https://stackoverflow.com/questions/5391973/undefined-reference-to-static-const-int
if (this->elementTypes.size() == 0) {
this->elementTypes.setKeyValue("Undefined" , static_cast<int>(TopicElement::types::chapter ));
this->elementTypes.setKeyValue("Chapter" , static_cast<int>(TopicElement::types::chapter ));
this->elementTypes.setKeyValue("Section" , static_cast<int>(TopicElement::types::section ));
this->elementTypes.setKeyValue("Topic" , static_cast<int>(TopicElement::types::topic ));
this->elementTypes.setKeyValue("Problem" , static_cast<int>(TopicElement::types::problem ));
this->elementTypes.setKeyValue("Error" , static_cast<int>(TopicElement::types::error ));
this->elementTypes.setKeyValue("TexHeader" , static_cast<int>(TopicElement::types::error ));
this->elementTypes.setKeyValue("Title" , static_cast<int>(TopicElement::types::title ));
this->elementTypes.setKeyValue("Video" , static_cast<int>(TopicElement::types::video ));
this->elementTypes.setKeyValue("VideoHandwritten" , static_cast<int>(TopicElement::types::videoHandwritten ));
this->elementTypes.setKeyValue("SlidesLatex" , static_cast<int>(TopicElement::types::slidesLatex ));
this->elementTypes.setKeyValue("SlidesSource" , static_cast<int>(TopicElement::types::slidesSource ));
this->elementTypes.setKeyValue("HomeworkLatex" , static_cast<int>(TopicElement::types::homeworkLatex ));
this->elementTypes.setKeyValue("HomeworkSource" , static_cast<int>(TopicElement::types::homeworkSource ));
this->elementTypes.setKeyValue("HomeworkSolutionSource" , static_cast<int>(TopicElement::types::homeworkSolutionSource));
this->elementTypes.setKeyValue("SlidesSourceHeader" , static_cast<int>(TopicElement::types::slidesSourceHeader ));
this->elementTypes.setKeyValue("HomeworkSourceHeader" , static_cast<int>(TopicElement::types::homeworkSourceHeader ));
this->elementTypes.setKeyValue("LoadTopicBundles" , static_cast<int>(TopicElement::types::loadTopicBundles ));
this->elementTypes.setKeyValue("TopicBundle" , static_cast<int>(TopicElement::types::topicBundle ));
this->elementTypes.setKeyValue("BundleBegin" , static_cast<int>(TopicElement::types::bundleBegin ));
this->elementTypes.setKeyValue("BundleEnd" , static_cast<int>(TopicElement::types::bundleEnd ));
for (int i = 0; i < this->elementTypes.size(); i ++) {
this->elementNames.setKeyValue(this->elementTypes.values[i], this->elementTypes.keys[i]);
}
}
}
void CalculatorHTML::initAutocompleteExtras() {
MacroRegisterFunctionWithName("CalculatorHTML::initAutocompleteExtras");
if (this->autoCompleteExtras.size > 0) {
return;
}
this->autoCompleteExtras.addOnTop("answerCalculatorHighlight");
this->autoCompleteExtras.addOnTop("algebra");
this->autoCompleteExtras.addOnTop("logarithms");
this->autoCompleteExtras.addOnTop("buttons");
this->autoCompleteExtras.addOnTop("displaystyle");
}
void CalculatorHTML::initBuiltInSpanClasses() {
this->parser.initBuiltInSpanClasses();
}
void CalculatorHTML::Parser::initBuiltInSpanClasses() {
MacroRegisterFunctionWithName("CalculatorHTML::Parser::initBuiltInSpanClasses");
if (this->calculatorClassesAnswerFields.size == 0) {
this->calculatorClassesAnswerFields.addOnTop("calculatorButtonSubmit");
this->calculatorClassesAnswerFields.addOnTop("calculatorButtonInterpret");
this->calculatorClassesAnswerFields.addOnTop("calculatorButtonGiveUp");
this->calculatorClassesAnswerFields.addOnTop("calculatorButtonSolution");
this->calculatorClassesAnswerFields.addOnTop("calculatorMQField");
this->calculatorClassesAnswerFields.addOnTop("calculatorMQButtonPanel");
this->calculatorClassesAnswerFields.addOnTop("calculatorAnswerVerification");
}
if (this->calculatorClasses.size == 0) {
this->calculatorClasses.addOnTop("calculator");
this->calculatorClasses.addOnTop(SyntacticElementHTML::Tags::calculatorSolution);
this->calculatorClasses.addOnTop(SyntacticElementHTML::Tags::calculatorShowToUserOnly);
this->calculatorClasses.addOnTop("calculatorHidden");
this->calculatorClasses.addOnTop("calculatorCommentsBeforeInterpretation");
this->calculatorClasses.addOnTop("calculatorCommentsBeforeSubmission");
this->calculatorClasses.addOnTop(SyntacticElementHTML::Tags::calculatorAnswer);
this->calculatorClasses.addOnTop(SyntacticElementHTML::Tags::hardCodedAnswer);
this->calculatorClasses.addOnTop("calculatorAnswerOnGiveUp");
this->calculatorClasses.addOnTop("calculatorExamIntermediate");
this->calculatorClasses.addOnTop(SyntacticElementHTML::Tags::calculatorExamProblem);
this->calculatorClasses.addOnTop("calculatorNavigationHere");
this->calculatorClasses.addOnTop("calculatorProblemNavigationHere");
this->calculatorClasses.addOnTop("calculatorManageClass");
this->calculatorClasses.addOnTop("setCalculatorExamHome");
this->calculatorClasses.addOnTop("accountInformationLinks");
this->calculatorClasses.addOnTop("calculatorJavascript");
this->calculatorClasses.addOnTop("answerCalculatorHighlight");
this->calculatorClasses.addListOnTop(this->calculatorClassesAnswerFields);
}
}
CalculatorHTML::Parser::Parser(){
this->owner = nullptr;
this->reset();
}
void CalculatorHTML::Parser::reset() {
this->phase = CalculatorHTML::Parser::Phase::none;
}
bool CalculatorHTML::Parser::parseHTML(std::stringstream* comments) {
MacroRegisterFunctionWithName("CalculatorHTML::Parser::parseHTML");
this->reset();
std::stringstream reader(this->inputHtml);
reader.seekg(0);
std::string word;
char currentChar;
List<SyntacticElementHTML> elements;
elements.setSize(0);
elements.setExpectedSize(static_cast<int>(reader.str().size()) / 4);
this->splittingChars.addOnTop('<');
this->splittingChars.addOnTop('\"');
this->splittingChars.addOnTop('>');
this->splittingChars.addOnTop('=');
this->splittingChars.addOnTop('/');
this->splittingChars.addOnTop(' ');
this->splittingChars.addOnTop('\'');
this->splittingChars.addOnTop('\'');
this->splittingChars.addOnTop('\t');
this->splittingChars.addOnTop('\n');
while (reader.get(currentChar)) {
if (splittingChars.contains(currentChar)) {
if (word != "") {
elements.addOnTop(word);
}
std::string charToString;
charToString.push_back(currentChar);
SyntacticElementHTML element(charToString);
element.syntacticRole = charToString;
elements.addOnTop(element);
word = "";
} else {
word.push_back(currentChar);
}
}
if (word != "") {
elements.addOnTop(word);
}
this->initBuiltInSpanClasses();
this->elementStack.setSize(0);
SyntacticElementHTML dummy, element;
dummy.content = "";
dummy.syntacticRole = SyntacticElementHTML::Tags::filler;
element.syntacticRole = "command";
element.tag = "";
element.content = "";
this->elementStack.setExpectedSize(elements.size + SyntacticElementHTML::parsingDummyElements);
for (int i = 0; i < SyntacticElementHTML::parsingDummyElements; i ++) {
this->elementStack.addOnTop(dummy);
}
for (int i = 0; i < elements.size; i ++) {
this->elementStack.addOnTop(elements[i]);
while (this->reduceMore()) {
}
if (this->elementStack.lastObject()->syntacticRole == "error") {
break;
}
}
return this->owner->processParsedElements(comments);
}
bool CalculatorHTML::extractContent(std::stringstream* comments) {
MacroRegisterFunctionWithName("CalculatorHTML::extractContent");
bool result = true;
for (int i = SyntacticElementHTML::parsingDummyElements; i < this->parser.elementStack.size; i ++) {
const SyntacticElementHTML& current = this->parser.elementStack[i];
bool needNewTag = false;
if (i == SyntacticElementHTML::parsingDummyElements) {
needNewTag = true;
} else if (this->content.lastObject()->syntacticRole != "") {
needNewTag = true;
}
if (current.syntacticRole != "") {
needNewTag = true;
}
if (current.syntacticRole != "command" && current.syntacticRole != "") {
result = false;
if (comments != nullptr) {
*comments << "<br>Syntactic element: " << current.toStringDebug()
<< " is not a command but has non-empty syntactic role.";
}
}
if (!needNewTag) {
this->content.lastObject()->content += current.content;
} else {
if (this->content.size > 0) {
if (
this->content.lastObject()->isInterpretedByCalculatorOnGeneration() &&
current.isInterpretedByCalculatorOnGeneration()
) {
SyntacticElementHTML empty;
this->content.addOnTop(empty);
}
}
this->content.addOnTop(current);
}
}
return result;
}
bool CalculatorHTML::processParsedElements(std::stringstream* comments) {
this->content.setSize(0);
bool result = true;
if (!this->extractContent(comments)) {
result = false;
}
if (!result && comments != nullptr) {
*comments << "<hr>Parsing stack.<hr>"
<< this->parser.toStringParsingStack(this->parser.elementStack);
}
if (result) {
result = this->extractAnswerIds(comments);
}
if (result) {
result = this->processSolutions(comments);
}
for (int i = 0; i < this->content.size; i ++) {
this->content[i].indexInOwner = i;
}
if (result) {
result = this->checkContent(comments);
}
this->problemData.checkConsistency();
return result;
}
bool CalculatorHTML::Parser::consumeContentStandard() {
SyntacticElementHTML& last = this->elementStack[this->elementStack.size - 1];
if (last.syntacticRole == "<") {
this->phase = CalculatorHTML::Parser::Phase::leftAngleBracketEncountered;
return false;
}
if (
last.syntacticRole != SyntacticElementHTML::Tags::command &&
last.syntacticRole != SyntacticElementHTML::Tags::filler
) {
last.syntacticRole = "";
}
SyntacticElementHTML& secondToLast = this->elementStack[this->elementStack.size - 2];
if (
secondToLast.syntacticRole == SyntacticElementHTML::Tags::filler ||
secondToLast.syntacticRole == SyntacticElementHTML::Tags::command
) {
return false;
}
return this->reduceStackMergeContents(1);
}
bool CalculatorHTML::Parser::setLastToError(const std::string &errorMessage) {
SyntacticElementHTML& last = this->elementStack[this->elementStack.size - 1];
last.syntacticRole = "error";
last.errorComment = errorMessage;
this->phase = CalculatorHTML::Parser::Phase::error;
return false;
}
bool CalculatorHTML::Parser::consumeErrorOrMergeInCalculatorTag(
int calculatorTagNegativeOffset, const std::string& errorMessage
) {
int startIndex = this->elementStack.size + calculatorTagNegativeOffset;
SyntacticElementHTML& calculatorTag = this->elementStack[startIndex];
if (calculatorTag.syntacticRole != "<calculatorTag>") {
return this->setLastToError(errorMessage);
}
this->reduceStackMergeContents(- calculatorTagNegativeOffset - 1);
this->phase = CalculatorHTML::Parser::Phase::none;
return false;
}
bool CalculatorHTML::Parser::consumeErrorOrMergeInCalculatorTagRetainLast(
int calculatorTagNegativeOffset, const std::string& errorMessage
) {
int startIndex = this->elementStack.size + calculatorTagNegativeOffset;
SyntacticElementHTML& calculatorTag = this->elementStack[startIndex];
if (calculatorTag.syntacticRole != "<calculatorTag>") {
return this->setLastToError(errorMessage);
}
this->reduceStackMergeContentsRetainLast(- calculatorTagNegativeOffset - 2);
this->phase = CalculatorHTML::Parser::Phase::none;
return false;
}
bool CalculatorHTML::Parser::reduceStackMergeContents(
int numberOfElementsToRemove
) {
SyntacticElementHTML& calculatorTag = this->elementStack[this->elementStack.size - numberOfElementsToRemove - 1];
for (int i = this->elementStack.size - numberOfElementsToRemove; i < this->elementStack.size; i ++) {
calculatorTag.content.append(this->elementStack[i].content);
}
this->elementStack.setSize(this->elementStack.size - numberOfElementsToRemove);
return false;
}
bool CalculatorHTML::Parser::reduceStackMergeContentsRetainLast(
int numberOfElementsToRemove
) {
SyntacticElementHTML& calculatorTag = this->elementStack[this->elementStack.size - numberOfElementsToRemove - 2];
for (int i = this->elementStack.size - numberOfElementsToRemove - 1; i < this->elementStack.size - 1; i ++) {
calculatorTag.content.append(this->elementStack[i].content);
}
this->elementStack[this->elementStack.size - numberOfElementsToRemove - 1] = *this->elementStack.lastObject();
this->elementStack.setSize(this->elementStack.size - numberOfElementsToRemove);
return false;
}
bool CalculatorHTML::Parser::consumeAfterLeftAngleBracket() {
SyntacticElementHTML& last = this->elementStack[this->elementStack.size - 1];
SyntacticElementHTML& secondToLast = this->elementStack[this->elementStack.size - 2];
if (secondToLast.syntacticRole != "<") {
return this->setLastToError("Unexpected stack state after left angle bracket.");
}
if (last.syntacticRole == " ") {
return this->reduceStackMergeContents(1);
}
if (last.syntacticRole == "/") {
secondToLast.syntacticRole = "</";
this->phase = CalculatorHTML::Parser::Phase::startedCloseTag;
return this->reduceStackMergeContents(1);
}
if (last.syntacticRole == "") {
secondToLast.tag = last.content;
secondToLast.syntacticRole = "<openTag";
this->phase = CalculatorHTML::Parser::Phase::startedOpenTag;
return this->reduceStackMergeContents(1);
}
return this->consumeErrorOrMergeInCalculatorTag(- 3, "Left angle bracket not followed by word forward slash or empty space. ");
}
bool CalculatorHTML::Parser::isCalculatorTag(
const SyntacticElementHTML& input
) {
std::string tagName = input.getTagClass();
return this->calculatorClasses.contains(input.getTagClass());
}
bool CalculatorHTML::Parser::closeOpenTag(int tagOffsetNegative) {
SyntacticElementHTML& toBeConverted = this->elementStack[this->elementStack.size + tagOffsetNegative];
this->phase = CalculatorHTML::Parser::Phase::none;
if (this->isCalculatorTag(toBeConverted)) {
toBeConverted.content = "";
std::string tagName = toBeConverted.getTagClass();
if (tagName == SyntacticElementHTML::Tags::calculatorSolution) {
toBeConverted.tag = SyntacticElementHTML::Tags::calculatorSolutionStart;
toBeConverted.syntacticRole = "command";
} else if (tagName == SyntacticElementHTML::Tags::answerCalculatorHighlight){
toBeConverted.tag = SyntacticElementHTML::Tags::answerCalculatorHighlightStart;
toBeConverted.syntacticRole = "command";
} else {
toBeConverted.syntacticRole = "<calculatorTag>";
}
this->elementStack.setSize(this->elementStack.size + tagOffsetNegative + 1);
return false;
}
toBeConverted.syntacticRole = "";
this->reduceStackMergeContents(- tagOffsetNegative - 1);
return this->consumeContentStandard();
}
bool CalculatorHTML::Parser::consumeTagOpened() {
SyntacticElementHTML& secondToLast = this->elementStack[this->elementStack.size - 2];
if (secondToLast.syntacticRole != "<openTag") {
return this->setLastToError("Unexpected stack state after left angle bracket tag.");
}
SyntacticElementHTML& last = this->elementStack[this->elementStack.size - 1];
if (this->isWhiteSpace(last.syntacticRole)) {
return this->reduceStackMergeContents(1);
}
if (last.syntacticRole == "") {
last.syntacticRole = "property";
this->phase = CalculatorHTML::Parser::Phase::propertyEncountered;
return false;
}
if (last.syntacticRole == ">") {
return this->closeOpenTag(- 2);
}
if (last.syntacticRole == "/") {
secondToLast.syntacticRole = "<openTag/";
this->phase = CalculatorHTML::Parser::Phase::startedOpenTagGotBackslash;
return this->reduceStackMergeContents(1);
}
if (last.syntacticRole == "<") {
this->consumeErrorOrMergeInCalculatorTagRetainLast(
- 3, "While constructing your tag, failed to interpret " + last.syntacticRole
);
// Don't push new elements to be parsed on the stack.
return true;
}
return this->consumeErrorOrMergeInCalculatorTag(
- 3, "While constructing your tag, failed to interpret " + last.syntacticRole
);
}
bool CalculatorHTML::Parser::consumeTagOpenedGotBackSlash() {
SyntacticElementHTML& secondToLast = this->elementStack[this->elementStack.size - 2];
if (secondToLast.syntacticRole != "<openTag/") {
return this->setLastToError("Unexpected stack state after left angle bracket tag backslash.");
}
SyntacticElementHTML& last = this->elementStack[this->elementStack.size - 1];
if (last.syntacticRole == " ") {
return this->reduceStackMergeContents(1);
}
if (last.syntacticRole == ">") {
this->phase = CalculatorHTML::Parser::Phase::none;
this->reduceStackMergeContents(1);
last.syntacticRole = "";
return this->consumeContentStandard();
}
return this->consumeErrorOrMergeInCalculatorTag(
- 3, "While processing state <openTag/, failed to interpret " + last.syntacticRole
);
}
bool CalculatorHTML::Parser::consumeAfterProperty() {
SyntacticElementHTML& secondToLast = this->elementStack[this->elementStack.size - 2];
SyntacticElementHTML& thirdToLast = this->elementStack[this->elementStack.size - 3];
if (secondToLast.syntacticRole != "property" || thirdToLast.syntacticRole != "<openTag") {
return this->setLastToError("Unexpected stack state after property was encountered. ");
}
SyntacticElementHTML& last = this->elementStack[this->elementStack.size - 1];
if (this->isWhiteSpace(last.syntacticRole)) {
return this->reduceStackMergeContents(1);
}
if (last.syntacticRole == "") {
thirdToLast.propertiesWithoutValue.addOnTop(StringRoutines::stringTrimWhiteSpace(secondToLast.content));
thirdToLast.content.append(secondToLast.content);
last.syntacticRole = "property";
this->elementStack[this->elementStack.size - 2] = last;
this->elementStack.removeLastObject();
return false;
}
if (last.syntacticRole == ">") {
thirdToLast.propertiesWithoutValue.addOnTop(StringRoutines::stringTrimWhiteSpace(secondToLast.content));
return this->closeOpenTag(- 3);
}
if (last.syntacticRole == "<") {
this->consumeErrorOrMergeInCalculatorTagRetainLast(- 4, "Couldn't continue tag construction after property " + secondToLast.content);
return true;
}
if (last.syntacticRole == "/") {
thirdToLast.propertiesWithoutValue.addOnTop(StringRoutines::stringTrimWhiteSpace(secondToLast.content));
thirdToLast.syntacticRole = "<openTag/";
this->phase = CalculatorHTML::Parser::Phase::startedOpenTagGotBackslash;
return this->reduceStackMergeContents(2);
}
if (last.syntacticRole == "=") {
this->phase = CalculatorHTML::Parser::Phase::equalityEncountered;
return false;
}
return this->consumeErrorOrMergeInCalculatorTag(- 4, "Couldn't continue tag construction after property " + secondToLast.content);
}
bool CalculatorHTML::Parser::consumeAfterEquality() {
SyntacticElementHTML& secondToLast = this->elementStack[this->elementStack.size - 2];
SyntacticElementHTML& thirdToLast = this->elementStack[this->elementStack.size - 3];
SyntacticElementHTML& fourthToLast = this->elementStack[this->elementStack.size - 4];
if (
secondToLast.syntacticRole != "=" ||
thirdToLast.syntacticRole != "property" ||
fourthToLast.syntacticRole != "<openTag"
) {
return this->setLastToError("Unexpected stack state after equality. ");
}
SyntacticElementHTML& last = this->elementStack[this->elementStack.size - 1];
if (this->isWhiteSpace(last.syntacticRole)) {
return this->reduceStackMergeContents(1);
}
if (last.syntacticRole == "\"") {
this->phase = CalculatorHTML::Parser::Phase::doubleQuoteOpened;
return false;
}
if (last.syntacticRole == "'") {
this->phase = CalculatorHTML::Parser::Phase::singleQuoteOpened;
return false;
}
return this->consumeErrorOrMergeInCalculatorTag(- 5, "Expected quote after equality. ");
}
bool CalculatorHTML::Parser::consumeAfterQuote(const std::string& quoteSymbol) {
SyntacticElementHTML& secondToLast = this->elementStack[this->elementStack.size - 2];
if (secondToLast.syntacticRole != quoteSymbol) {
return this->setLastToError("Unexpected stack state after quote. ");
}
SyntacticElementHTML& last = this->elementStack[this->elementStack.size - 1];
if (last.syntacticRole == quoteSymbol) {
SyntacticElementHTML& thirdToLast = this->elementStack[this->elementStack.size - 3];
SyntacticElementHTML& fourthToLast = this->elementStack[this->elementStack.size - 4];
SyntacticElementHTML& fifthToLast = this->elementStack[this->elementStack.size - 5];
if (thirdToLast.syntacticRole != "=" || fourthToLast.syntacticRole != "property" || fifthToLast.syntacticRole != "<openTag") {
return this->setLastToError("Unexpected stack state after closing single quote. ");
}
std::string quoteContent = secondToLast.content.substr(1);
std::string property = StringRoutines::stringTrimWhiteSpace(fourthToLast.content);
fifthToLast.properties.setKeyValue(property, quoteContent);
this->phase = CalculatorHTML::Parser::Phase::startedOpenTag;
return this->reduceStackMergeContents(4);
}
return this->reduceStackMergeContents(1);
}
bool CalculatorHTML::Parser::consumeCloseTagOpened() {
SyntacticElementHTML& secondToLast = this->elementStack[this->elementStack.size - 2];
if (secondToLast.syntacticRole != "</") {
return this->setLastToError("Unexpected stack state after langle forward slash.");
}
SyntacticElementHTML& last = this->elementStack[this->elementStack.size - 1];
if (this->isWhiteSpace(last.syntacticRole)) {
return this->reduceStackMergeContents(1);
}
if (last.syntacticRole == "") {
this->phase = CalculatorHTML::Parser::Phase::closeTagWaitingForRightAngleBracket;
secondToLast.tag = last.content;
secondToLast.syntacticRole = "</closeTag";
return this->reduceStackMergeContents(1);
}
return this->consumeErrorOrMergeInCalculatorTag(- 3, "Bad close tag. ");
}
bool CalculatorHTML::Parser::consumeCloseTagWaitingForRightAngleBracket() {
SyntacticElementHTML& secondToLast = this->elementStack[this->elementStack.size - 2];
if (secondToLast.syntacticRole != "</closeTag") {
return this->setLastToError("Unexpected stack state after langle forward slash closeTag.");
}
SyntacticElementHTML& last = this->elementStack[this->elementStack.size - 1];
if (this->isWhiteSpace(last.syntacticRole)) {
return this->reduceStackMergeContents(1);
}
if (last.syntacticRole == ">") {
SyntacticElementHTML& thirdToLast = this->elementStack[this->elementStack.size - 3];
this->phase = CalculatorHTML::Parser::none;
if (secondToLast.tag == SyntacticElementHTML::Tags::calculatorSolution) {
secondToLast.tag = SyntacticElementHTML::Tags::calculatorSolutionEnd;
secondToLast.syntacticRole = "command";
return this->reduceStackMergeContents(1);
}
if (secondToLast.tag == SyntacticElementHTML::Tags::answerCalculatorHighlight) {
secondToLast.tag = SyntacticElementHTML::Tags::answerCalculatorHighlightEnd;
secondToLast.syntacticRole = "command";
return this->reduceStackMergeContents(1);
}
if (thirdToLast.syntacticRole == "<calculatorTag>" && secondToLast.tag == thirdToLast.tag) {
thirdToLast.syntacticRole = "command";
this->elementStack.setSize(this->elementStack.size - 2);
return false;
}
secondToLast.syntacticRole = "";
this->reduceStackMergeContents(1);
return true;
}
return this->consumeErrorOrMergeInCalculatorTag(- 3, "Unexpected character after langle forward slash closeTag");
}
std::string CalculatorHTML::Parser::toStringPhaseInfo() {
std::stringstream stackTop;
int stepsToShow = 5;
for (int i = this->elementStack.size - stepsToShow - 1; i < this->elementStack.size; i ++) {
SyntacticElementHTML& current = this->elementStack[i];
if (
current.syntacticRole == SyntacticElementHTML::Tags::filler &&
current.content == ""
) {
continue;
}
stackTop << this->elementStack[i].toStringDebug() << " ";
}
// stackTop << stackContent.str();
switch (this->phase) {
case CalculatorHTML::Parser::Phase::none:
return "Phase::none: " + stackTop.str();
case CalculatorHTML::Parser::Phase::leftAngleBracketEncountered:
return "Phase::leftAngleBracketEncountered: " + stackTop.str();
case CalculatorHTML::Parser::Phase::startedOpenTag:
return "Phase::startedOpenTag: " + stackTop.str();
case CalculatorHTML::Parser::Phase::startedOpenTagGotBackslash:
return "Phase::startedOpenTagGotBackslash: " + stackTop.str();
case CalculatorHTML::Parser::Phase::propertyEncountered:
return "Phase::propertyEncountered: " + stackTop.str();
case CalculatorHTML::Parser::Phase::equalityEncountered:
return "Phase::equalityEncountered: " + stackTop.str();
case CalculatorHTML::Parser::Phase::singleQuoteOpened:
return "Phase::singleQuoteOpened: " + stackTop.str();
case CalculatorHTML::Parser::Phase::doubleQuoteOpened:
return "Phase::doubleQuoteOpened: " + stackTop.str();
case CalculatorHTML::Parser::Phase::startedCloseTag:
return "Phase::startedCloseTag: " + stackTop.str();
case CalculatorHTML::Parser::Phase::closeTagWaitingForRightAngleBracket:
return "Phase::closeTagWaitingForRightAngleBracket: " + stackTop.str();
case CalculatorHTML::Parser::Phase::error:
return "Phase::error: " + stackTop.str();
}
return "";
}
bool CalculatorHTML::Parser::reduceMore() {
switch (this->phase) {
case CalculatorHTML::Parser::Phase::none:
return this->consumeContentStandard();
case CalculatorHTML::Parser::Phase::leftAngleBracketEncountered:
return this->consumeAfterLeftAngleBracket();
case CalculatorHTML::Parser::Phase::startedOpenTag:
return this->consumeTagOpened();
case CalculatorHTML::Parser::Phase::startedOpenTagGotBackslash:
return this->consumeTagOpenedGotBackSlash();
case CalculatorHTML::Parser::Phase::propertyEncountered:
return this->consumeAfterProperty();
case CalculatorHTML::Parser::Phase::equalityEncountered:
return this->consumeAfterEquality();
case CalculatorHTML::Parser::Phase::singleQuoteOpened:
return this->consumeAfterQuote("'");
case CalculatorHTML::Parser::Phase::doubleQuoteOpened:
return this->consumeAfterQuote("\"");
case CalculatorHTML::Parser::Phase::startedCloseTag:
return this->consumeCloseTagOpened();
case CalculatorHTML::Parser::Phase::closeTagWaitingForRightAngleBracket:
return this->consumeCloseTagWaitingForRightAngleBracket();
case CalculatorHTML::Parser::Phase::error:
return false;
}
return false;
}
bool CalculatorHTML::interpretOneAnswerElement(SyntacticElementHTML& inputOutput) {
MacroRegisterFunctionWithName("CalculatorHTML::interpretOneAnswerElement");
std::string answerId;
if (!inputOutput.isAnswerElement(&answerId)) {
return true;
}
int index = this->getAnswerIndex(answerId);
std::string tagClass = inputOutput.getTagClass();
if (index == - 1) {
std::stringstream out;
out << "<b>Element of class " << tagClass << " has name: "
<< answerId << " but that does not match any answerId value. "
<< this->problemData.toStringAvailableAnswerIds() << ". </b>";
inputOutput.interpretedCommand = out.str();
return true;
}
Answer& answer = this->problemData.answers.values[index];
if (tagClass == "calculatorAnswerVerification") {
inputOutput.interpretedCommand = answer.htmlSpanVerifyAnswer;
}
return true;
}
bool CalculatorHTML::interpretAnswerHighlights(std::stringstream& comments) {
MacroRegisterFunctionWithName("CalculatorHTML::interpretAnswerHighlights");
(void) comments;
this->answerHighlights.setSize(0);
bool answerHighlightStarted = false;
for (int i = 0; i < this->content.size; i ++) {
if (this->content[i].tag == SyntacticElementHTML::Tags::answerCalculatorHighlightStart) {
answerHighlightStarted = true;
this->answerHighlights.addOnTop("");
this->content[i].content = "";
continue;
}
if (!answerHighlightStarted) {
continue;
}
if (this->content[i].isAnswerElement(nullptr)) {
continue;
}
if (this->content[i].tag == SyntacticElementHTML::Tags::answerCalculatorHighlightEnd) {
answerHighlightStarted = false;
this->content[i].content = "";
continue;
}
*this->answerHighlights.lastObject() += this->content[i].toStringInterpretedBody();
this->content[i].content = "";
this->content[i].interpretedCommand = "";
}
return true;
}
bool CalculatorHTML::interpretAnswerElements(std::stringstream& comments) {
MacroRegisterFunctionWithName("CalculatorHTML::interpretAnswerElements");
(void) comments;
for (int i = 0; i < this->content.size; i ++) {
this->interpretOneAnswerElement(this->content[i]);
}
return true;
}
bool CalculatorHTML::prepareAnswerElements(std::stringstream &comments) {
MacroRegisterFunctionWithName("CalculatorHTML::prepareAnswerElements");
(void) comments;
std::string currentId;
for (int i = 0; i < this->content.size; i ++) {
if (this->content[i].isAnswerElement(¤tId)) {
int index = this->getAnswerIndex(currentId);
if (index == - 1) {
continue;
}
Answer& currentA = this->problemData.answers.values[index];
std::string tagClass = this->content[i].getTagClass();
if (
tagClass == "calculatorButtonSubmit" ||
tagClass == "calculatorButtonInterpret" ||
tagClass == "calculatorButtonGiveUp"
) {
currentA.flagAutoGenerateSubmitButtons = false;
}
if (tagClass == "calculatorButtonSolution") {
currentA.flagAutoGenerateButtonSolution = false;
}
if (tagClass == "calculatorMQField") {
currentA.flagAutoGenerateMQfield = false;
}
if (tagClass == "calculatorMQButtonPanel") {
currentA.flagAutoGenerateMQButtonPanel = false;
}
if (tagClass == "calculatorAnswerVerification") {
currentA.flagAutoGenerateVerificationField = false;
}
}
}
return true;
}
bool CalculatorHTML::extractOneAnswerId(
SyntacticElementHTML& input, std::stringstream* comments
) {
MacroRegisterFunctionWithName("CalculatorHTML::extractOneAnswerId");
if (!input.isAnswer()) {
return true;
}
std::string currentId = input.answerIdCorrectIfEmpty();
for (unsigned i = 0; i < currentId.size(); i ++) {
if (!MathRoutines::isALatinLetter(currentId[i])) {
if (comments != nullptr) {
*comments << "Answer id must contain latin letters only, but was: " << currentId;
}
return false;
}
}
if (!this->problemData.answers.contains(currentId)) {
Answer newAnswer;
newAnswer.answerId = currentId;
this->problemData.answers.setKeyValue(currentId, newAnswer);
}
Answer& current = this->problemData.answers.getValueCreateEmpty(currentId);
if (current.flagAnswerVerificationFound) {
if (comments != nullptr) {
*comments << "<b>Answer with id: "
<< currentId << " has more than one answer/verification commands. </b>";
}
return false;
}
current.flagAnswerVerificationFound = true;
current.mathQuillPanelOptions = input.getKeyValue("buttons");
return true;
}
CalculatorHTML::SolutionProcessor::SolutionProcessor() {
this->currentAnswer = nullptr;
}
bool CalculatorHTML::processOneSolution(
SyntacticElementHTML& input,
CalculatorHTML::SolutionProcessor& processor,
std::stringstream* comments
) {
MacroRegisterFunctionWithName("CalculatorHTML::processOneSolution");
std::string tagName = input.getTagClass();
if (processor.currentAnswer != nullptr) {
if (tagName == SyntacticElementHTML::Tags::calculatorSolutionEnd) {
processor.currentAnswer = nullptr;
return true;
}
processor.currentAnswer->solutionElements.addOnTop(input);
return true;
}
if (tagName == SyntacticElementHTML::Tags::calculatorSolutionStart) {
std::string answerId = input.getAnswerIdOfOwner();
if (answerId == "") {
if (this->problemData.answers.size() > 0) {
answerId = *this->problemData.answers.keys.lastObject();
}
}
if (answerId == "") {
if (comments != nullptr) {
*comments << "Solution tag with tag name: " << tagName << " has empty id. ";
}
return false;
}
processor.currentAnswer = &this->problemData.answers.getValueCreateEmpty(answerId);
return true;
}
processor.contentWithoutSolutionElements.addOnTop(input);
return true;
}
bool CalculatorHTML::processSolutions(std::stringstream* comments) {
MacroRegisterFunctionWithName("CalculatorHTML::processSolutions");
CalculatorHTML::SolutionProcessor processor;
for (int i = 0; i < this->content.size; i ++) {
if (!this->processOneSolution(this->content[i], processor, comments)) {
return false;
}
}
this->content = processor.contentWithoutSolutionElements;
return true;
}
bool CalculatorHTML::extractAnswerIdsOnce(
SyntacticElementHTML& element, std::stringstream* comments
) {
MacroRegisterFunctionWithName("CalculatorHTML::extractAnswerIdsOnce");
if (!this->extractOneAnswerId(element, comments)) {
return false;
}
if (element.isAnswer()) {
return true;
}
if (
!element.isCommentBeforeSubmission() &&
!element.isCommentBeforeInterpretation() &&
!element.isAnswerOnGiveUp() &&
!element.isSolution()
) {
return true;
}
std::string nameOfTag = element.getAnswerIdOfOwner();
if (nameOfTag == "") {
int numberOfIdsSoFar = this->problemData.answers.size();
if (numberOfIdsSoFar == 0) {
if (comments != nullptr) {
*comments << "Auxilary answer element: " << element.toStringDebug()
<< " has no name and appears before the first answer tag. "
<< "Auxilary answers apply the answer tag whose id is specified in the name "
<< "tag of the auxilary answer. If the auxilary answer has no "
<< "name tag, it is assumed to apply to the (nearest) answer tag above it. "
<< "To fix the issue either place the auxilary element after the answer or "
<< "specify the answer's id in the name tag of the auxilary element. ";
}
return false;
}
element.setKeyValue("name", *this->problemData.answers.keys.lastObject());
nameOfTag = element.getAnswerIdOfOwner();
}
if (nameOfTag == "") {
global.fatal << "Unexpected empty answer name." << global.fatal;
}
if (!this->problemData.answers.contains(nameOfTag)) {
Answer newAnswer;
newAnswer.answerId = nameOfTag;
this->problemData.answers.setKeyValue(newAnswer.answerId, newAnswer);
}
return true;
}
bool CalculatorHTML::extractAnswerIds(std::stringstream* comments) {
MacroRegisterFunctionWithName("CalculatorHTML::extractAnswerIds");
// we shouldn't clear this->problemData.answers: it may contain
// outdated information loaded from the database. We don't want to loose that info
// (say we renamed an answerId but students have already stored answers using the old answerId...).
for (int i = 0; i < this->content.size; i ++) {
if (!this->extractAnswerIdsOnce(this->content[i], comments)) {
return false;
}
}
this->problemData.checkConsistency();
return true;
}
bool CalculatorHTML::checkContent(std::stringstream* comments) {
MacroRegisterFunctionWithName("CalculatorHTML::checkContent");
bool result = true;
for (int i = 0; i < this->content.size; i ++) {
SyntacticElementHTML& current = this->content[i];
if (
current.syntacticRole == "command" &&
current.isAnswer() &&
current.getKeyValue("id").find('=') != std::string::npos
) {
result = false;
if (comments != nullptr) {
*comments << "Error: the id of tag "
<< current.toStringDebug()
<< " contains the equality sign which is not allowed. ";
}
}
}
return result;
}
std::string SyntacticElementHTML::commandCleaned() const {
return SyntacticElementHTML::cleanUpCommandString(this->content);
}
std::string SyntacticElementHTML::commandEnclosed() const {
return SyntacticElementHTML::cleanUpEncloseCommand(this->content);
}
std::string SyntacticElementHTML::cleanUpEncloseCommand(const std::string& inputCommand) {
return Calculator::Atoms::commandEnclosure + "{}( " +
SyntacticElementHTML::cleanUpCommandString(inputCommand)
+ " );";
}
std::string SyntacticElementHTML::cleanUpCommandString(const std::string& inputCommand) {
MacroRegisterFunctionWithName("CalculatorHTML::cleanUpCommandString");
if (inputCommand == "") {
return "";
}
int realStart = 0;
int realEnd = static_cast<signed>(inputCommand.size()) - 1;
for (; realStart < static_cast<signed>(inputCommand.size()); realStart ++) {
if (
inputCommand[static_cast<unsigned>(realStart)] == ' ' ||
inputCommand[static_cast<unsigned>(realStart)] == '\n'
) {
continue;
}
if (inputCommand[static_cast<unsigned>(realStart)] == '\\') {
if (realStart + 1 < static_cast<signed>(inputCommand.size())) {
if (inputCommand[static_cast<unsigned>(realStart) + 1] == '(') {
realStart ++;
continue;
}
}
}
break;
}
for (; realEnd >= 0; realEnd --) {
if (
inputCommand[static_cast<unsigned>(realEnd)] == ' ' ||
inputCommand[static_cast<unsigned>(realEnd)] == '\n'
) {
continue;
}
if (inputCommand[static_cast<unsigned>(realEnd)] == ')') {
if (realEnd > 0) {
if (inputCommand[static_cast<unsigned>(realEnd) - 1] == '\\') {
realEnd --;
continue;
}
}
}
break;
}
if (realEnd < realStart) {
realEnd = realStart - 1;
}
std::string result = inputCommand.substr(static_cast<unsigned>(realStart), static_cast<unsigned>(realEnd - realStart + 1));
for (int i = static_cast<signed>(result.size()) - 1; i >= 0; i --) {
if (result[static_cast<unsigned>(i)] == ' ' || result[static_cast<unsigned>(i)] == '\n') {
continue;
}
if (result[static_cast<unsigned>(i)] == ';') {
return result;
}
break;
}
if (result == "") {
return "";
}
result.push_back(';');
return result;
}
bool CalculatorHtmlFunctions::extractCalculatorExpressionFromHtml(
Calculator& calculator, const Expression& input, Expression& output
) {
MacroRegisterFunctionWithName("CalculatorFunctions::extractCalculatorExpressionFromHtml");
if (input.size() != 2) {
return false;
}
CalculatorHTML interpreter;
if (!input[1].isOfType<std::string>(&interpreter.parser.inputHtml)) {
return calculator << "Extracting calculator expressions from html takes as input strings. ";
}
if (!interpreter.parseHTML(&calculator.comments)) {
return false;
}
return output.assignValue(calculator, interpreter.toStringExtractedCommands());
}
std::string CalculatorHTML::answerLabels::properties = "properties";
std::string CalculatorHTML::answerLabels::idPanel = "answerPanelId";
std::string CalculatorHTML::answerLabels::answerHighlight = "answerHighlight";
std::string CalculatorHTML::answerLabels::idEquationEditorElement = "idEquationEditorElement";
std::string CalculatorHTML::answerLabels::idButtonContainer = "idButtonContainer";
std::string CalculatorHTML::answerLabels::mathQuillPanelOptions = "mathQuillPanelOptions";
std::string CalculatorHTML::answerLabels::idPureLatex = "idPureLatex";
std::string CalculatorHTML::answerLabels::idButtonSubmit = "idButtonSubmit";
std::string CalculatorHTML::answerLabels::idButtonInterpret = "idButtonInterpret";
std::string CalculatorHTML::answerLabels::idButtonAnswer = "idButtonAnswer";
std::string CalculatorHTML::answerLabels::idButtonSolution = "idButtonSolution";
std::string CalculatorHTML::answerLabels::idVerificationSpan = "idVerificationSpan";
std::string CalculatorHTML::answerLabels::previousAnswers = "previousAnswers";
JSData CalculatorHTML::getEditorBoxesHTML() {
MacroRegisterFunctionWithName("CalculatorHTML::getEditorBoxesHTML");
////////////////////////////////////////////////////////////////////
JSData output;
output.elementType = JSData::token::tokenArray;
for (int i = 0; i < this->problemData.answers.size(); i ++) {
JSData currentAnswerJS;
Answer& currentAnswer = this->problemData.answers.values[i];
///////////////
JSData properties;
for (int j = 0; j < currentAnswer.properties.size(); j ++) {
properties[currentAnswer.properties.keys[j]] = currentAnswer.properties.values[j];
}
if (currentAnswer.properties.size() > 0) {
currentAnswerJS[answerLabels::properties] = properties;
}
currentAnswerJS[answerLabels::idPanel] = currentAnswer.idAnswerPanel;
currentAnswerJS[answerLabels::answerHighlight] = currentAnswer.htmlAnswerHighlight;
currentAnswerJS[answerLabels::idEquationEditorElement] = currentAnswer.idMathEquationField;
currentAnswerJS[answerLabels::idButtonContainer] = currentAnswer.idMQButtonPanelLocation;
currentAnswerJS[answerLabels::mathQuillPanelOptions] = currentAnswer.mathQuillPanelOptions;
currentAnswerJS[answerLabels::idPureLatex] = currentAnswer.answerId;
currentAnswerJS[answerLabels::idButtonSubmit] = currentAnswer.idButtonSubmit;
currentAnswerJS[answerLabels::idButtonInterpret] = currentAnswer.idButtonInterpret;
if (currentAnswer.commandAnswerOnGiveUp != "") {
currentAnswerJS[answerLabels::idButtonAnswer] = currentAnswer.idButtonAnswer;
}
if (currentAnswer.hasSolution()) {
currentAnswerJS[answerLabels::idButtonSolution] = currentAnswer.idButtonSolution;
}
currentAnswerJS[answerLabels::idVerificationSpan] = currentAnswer.idVerificationSpan;
currentAnswerJS[answerLabels::previousAnswers] = currentAnswer.htmlSpanVerifyAnswer;
///////////////
output[i] = currentAnswerJS;
}
return output;
}
bool CalculatorHTML::storeRandomSeedCurrent(std::stringstream* commentsOnFailure) {
MacroRegisterFunctionWithName("CalculatorHTML::storeRandomSeedCurrent");
this->problemData.flagRandomSeedGiven = true;
this->currentUser.setProblemData(this->fileName, this->problemData);
if (!this->currentUser.storeProblemData(this->fileName, commentsOnFailure)) {
if (commentsOnFailure != nullptr) {
*commentsOnFailure << "<b style = 'color:red'>"
<< "Error: failed to store problem in database. "
<< "If you see this message, please take a screenshot and post a bug report in "
<< HtmlRoutines::getHtmlLinkToGithubRepository("our source code repository")
<< ".</b>";
}
return false;
}
return true;
}
void CalculatorHTML::computeProblemLabel() {
if (this->outputProblemLabel != "") {
return;
}
if (
global.requestType == "template" ||
global.requestType == "templateNoLogin"
) {
return;
}
if (!this->topics.topics.contains(this->fileName)) {
return;
}
TopicElement& current = this->topics.topics.getValueCreateEmpty(this->fileName);
current.computeLinks(*this, true);
this->outputProblemLabel = current.problemNumberString;
this->outputProblemTitle = current.title;
}
std::string SyntacticElementHTML::toHTMLElements(
const List<SyntacticElementHTML>& input
) {
std::stringstream out;
out << input.size << " elements. ";
for (int i = 0; i < input.size; i ++) {
out << "<br>" << "<span style='color:" << ((i % 2 == 0) ? "orange" : "blue") << "'>";
std::string content = input[i].toStringDebug();
if (content.size() == 0) {
content = "<b>empty</b>";
} else if (content == " ") {
content = "<b>space</b>";
}
out << content << "</span>";
}
return out.str();
}
std::string CalculatorHTML::toStringParsedElements() const {
MacroRegisterFunctionWithName("CalculatorHTML::toStringParsedElements");
return SyntacticElementHTML::toHTMLElements(this->content);
}
void CalculatorHTML::computeBodyDebugString() {
MacroRegisterFunctionWithName("CalculatorHTML::computeBodyDebugString");
this->outputDebugInformationBody = "";
if (!global.userDebugFlagOn() || !global.userDefaultHasAdminRights()) {
return;
}
std::stringstream out;
out << "<hr><hr><b style='color:blue'>Problem body debug information.</b> ";
if (this->logCommandsProblemGeneratioN.str() != "") {
out << "<br>" << this->logCommandsProblemGeneratioN.str() << "<hr>";
}
out << "<br>Random seed: "
<< this->problemData.randomSeed
<< "<br>ForReal: " << this->flagIsForReal << "<br>seed given: "
<< this->problemData.flagRandomSeedGiven
<< "<br>flagRandomSeedGiven: "
<< this->problemData.flagRandomSeedGiven
<< "\n<hr><hr>\n"
<< "<b style='color:orange'>Parsing information.</b> "
<< this->toStringParsedElements()
<< "<hr>"
<< "<hr>"
<< HtmlRoutines::convertStringToHtmlString(this->toStringCalculatorArgumentsForProblem("exercise", "false"), true);
this->outputDebugInformationBody = out.str();
}
bool CalculatorHTML::interpretHtmlOneAttempt(Calculator& interpreter, std::stringstream& comments) {
MacroRegisterFunctionWithName("CalculatorHTML::interpretHtmlOneAttempt");
double startTime = global.getElapsedSeconds();
std::stringstream outBody;
std::stringstream outHeadPt2;
this->figureOutCurrentProblemList(comments);
this->timeIntermediatePerAttempt.lastObject()->addOnTop(global.getElapsedSeconds() - startTime);
this->timeIntermediateComments.lastObject()->addOnTop("Time before after loading problem list");
this->timeIntermediatePerAttempt.lastObject()->addOnTop(global.getElapsedSeconds() - startTime);
this->timeIntermediateComments.lastObject()->addOnTop("Time before execution");
if (!this->prepareAndExecuteCommands(interpreter, &comments)) {
return false;
}
//////////////////////////////interpretation takes place before javascript generation as the latter depends on the former.
this->computeProblemLabel();
std::string problemLabel = "";
if (
global.requestType != "template" &&
global.requestType != "templateNoLogin"
) {
if (this->topics.topics.contains(this->fileName)) {
TopicElement& current = this->topics.topics.getValueCreateEmpty(this->fileName);
current.computeLinks(*this, true);
problemLabel = current.displayTitle + " ";
}
}
if (
this->flagIsForReal &&
global.requestType == WebAPI::frontend::scoredQuiz
) {
if (global.flagDatabaseCompiled) {
bool problemAlreadySolved = false;
if (this->currentUser.problemData.contains(this->fileName)) {
ProblemData& problemData = this->currentUser.problemData.getValueCreateEmpty(this->fileName);
if (problemData.numCorrectlyAnswered >= problemData.answers.size()) {
problemAlreadySolved = true;
}
}
this->outputDeadlineString = this->toStringDeadline(this->fileName, problemAlreadySolved, true, true);
}
}
return this->interpretHtmlOneAttemptPartTwo(
interpreter,
comments,
startTime,
outBody,
outHeadPt2
);
}
bool CalculatorHTML::interpretHtmlOneAttemptPartTwo(
Calculator& interpreter,
std::stringstream& comments,
double startTime,
std::stringstream& outBody,
std::stringstream& outHeadPt2
) {
MacroRegisterFunctionWithName("CalculatorHTML::interpretHtmlOneAttemptPartTwo");
//////////////////////////////
this->timeIntermediatePerAttempt.lastObject()->addOnTop(global.getElapsedSeconds() - startTime);
this->timeIntermediateComments.lastObject()->addOnTop("Time after execution");
//first command and first syntactic element are the random seed and are ignored.
interpreter.objectContainer.resetSliders();
if (!this->processExecutedCommands(interpreter, this->content, comments)) {
outBody << comments.str();
this->outputHtmlBodyNoTag = outBody.str();
return false;
}
this->timeIntermediatePerAttempt.lastObject()->addOnTop(global.getElapsedSeconds() - startTime);
this->timeIntermediateComments.lastObject()->addOnTop("Time before class management routines");
this->prepareAnswerElements(comments);
this->numberOfAnswerIdsMathquilled = 0;
for (int i = 0; i < this->content.size; i ++) {
if (this->content[i].isInterpretedNotByCalculator()) {
this->interpretNotByCalculatorNotAnswer(this->content[i]);
}
}
this->interpretAnswerHighlights(comments);
for (int i = 0; i < this->content.size; i ++) {
this->interpretIfAnswer(this->content[i]);
}
outHeadPt2 << this->topicListJavascriptWithTag;
this->interpretAnswerElements(comments);
this->problemData.checkConsistency();
this->problemData.checkConsistencyMathQuillIds();
std::string tagClass;
for (int i = 0; i < this->content.size; i ++) {
if (this->content[i].shouldShow()) {
tagClass = this->content[i].getTagClass();
outBody << this->content[i].toStringInterpretedBody();
}
}
if (interpreter.flagHasGraphics) {
MapReferences<std::string, std::string, MathRoutines::hashString>& interpreterScripts =
interpreter.objectContainer.graphicsScripts;
for (int i = 0; i < interpreterScripts.size(); i ++) {
this->scripts.setKeyValue(interpreterScripts.keys[i], interpreterScripts.values[i]);
}
}
this->timeIntermediatePerAttempt.lastObject()->addOnTop(global.getElapsedSeconds() - startTime);
this->timeIntermediateComments.lastObject()->addOnTop("Time before database storage");
bool shouldResetTheRandomSeed = false;
if (this->flagIsForReal && !this->problemData.flagRandomSeedGiven) {
shouldResetTheRandomSeed = true;
}
if (this->flagIsForReal && this->numberOfInterpretationAttempts > 1) {
shouldResetTheRandomSeed = true;
outBody
<< "<hr><b style='color:red'>"
<< "Your problem's random seed was just reset. </b> "
<< "You should be seeing this message very rarely, "
<< "<b>ONLY IF</b> your problem was changed by your instructor "
<< "<b>AFTER</b> you started solving it. "
<< "You should not be seeing this message a second time. "
<< "<b style='color:red'>If you see this message every "
<< "time you reload the problem "
<< "this is a bug. "
<< "Please take a screenshot and send it to your instructor. </b>";
}
if (shouldResetTheRandomSeed) {
bool successStoringSeed = this->storeRandomSeedCurrent(&comments);
if (!successStoringSeed) {
global << Logger::red
<< "This should not happen: failed to store random seed." << Logger::endL
<< Logger::yellow << comments.str() << Logger::endL;
global.comments << "<b style='color:red'>Failed to store your problem data.</b> " << comments.str();
}
}
this->computeBodyDebugString();
std::stringstream navigationAndEditTagStream;
this->outputProblemNavigatioN = navigationAndEditTagStream.str();
this->outputHtmlBodyNoTag = outBody.str();
this->outputHtmlHeadNoTag = outHeadPt2.str();
return true;
}
std::string CalculatorHTML::toStringCalculatorArgumentsForProblem(
const std::string& requestType,
const std::string& studentView,
const std::string& studentSection,
bool includeRandomSeedIfAppropriate
) const {
MacroRegisterFunctionWithName("CalculatorHTML::toStringCalculatorArgumentsForProblem");
if (!global.flagLoggedIn && !global.userGuestMode()) {
return "";
}
std::stringstream out;
out << "request=" << requestType << "&";
List<std::string> excludedTags;
excludedTags.addOnTop(WebAPI::problem::randomSeed);
out << global.toStringCalculatorArgumentsNoNavigation(&excludedTags)
<< "courseHome=" << global.getWebInput(WebAPI::problem::courseHome) << "&";
if (this->fileName != "") {
out << WebAPI::problem::fileName << "="
<< HtmlRoutines::convertStringToURLString(this->fileName, false) << "&";
} else {
out << WebAPI::problem::fileName << "="
<< HtmlRoutines::convertStringToURLString(global.getWebInput(WebAPI::problem::fileName), false)
<< "&";
}
out << "topicList=" << global.getWebInput(WebAPI::problem::topicList) << "&";
out << "studentView=" << studentView << "&";
if (studentSection != "") {
out << "studentSection=" << HtmlRoutines::convertStringToURLString(studentSection, false) << "&";
}
if (includeRandomSeedIfAppropriate) {
out << "randomSeed=" << this->problemData.randomSeed << "&";
}
return out.str();
}
std::string CalculatorHTML::toStringProblemScoreFull(const std::string& fileName) {
MacroRegisterFunctionWithName("CalculatorHTML::toStringProblemScoreFull");
(void) fileName;
std::stringstream out;
if (global.userGuestMode()) {
out << "scores require login";
return out.str();
}
if (!global.flagDatabaseCompiled) {
out << "scores not available: no database. ";
return out.str();
}
Rational currentWeight;
if (this->currentUser.problemData.contains(fileName)) {
ProblemData& problemData = this->currentUser.problemData.getValueCreateEmpty(fileName);
if (!problemData.flagProblemWeightIsOK) {
out << "<span style =\"color:orange\">No point weight assigned yet. </span>";
if (!problemData.adminData.getWeightFromCourse(this->currentUser.courseComputed, currentWeight)) {
currentWeight = 0;
}
if (problemData.answers.size() == 1) {
if (problemData.numCorrectlyAnswered == 1) {
out << problemData.totalNumSubmissions << " submission(s), problem correctly answered. ";
} else {
out << problemData.totalNumSubmissions << " submission(s), problem not correctly answered yet. ";
}
} else if (problemData.answers.size() > 1) {
out << problemData.totalNumSubmissions << " submission(s), " << problemData.numCorrectlyAnswered
<< " out of " << problemData.answers.size() << " subproblems correctly answered. ";
}
} else if (problemData.totalNumSubmissions != 0) {
if (problemData.numCorrectlyAnswered < problemData.answers.size()) {
out << "<b style =\"color:red\">"
<< problemData.points << " out of "
<< currentWeight << " point(s). </b>";
} else if (problemData.numCorrectlyAnswered == problemData.answers.size()) {
out << "<b style =\"color:green\">"
<< problemData.points << " out of "
<< currentWeight << " point(s). </b> ";
}
}
} else {
out << "<b style =\"color:brown\">No submissions.</b>" ;
}
return out.str();
}
std::string CalculatorHTML::toStringProblemScoreShort(const std::string& fileName, bool& outputAlreadySolved) {
MacroRegisterFunctionWithName("CalculatorHTML::toStringProblemScoreShort");
(void) fileName;
(void) outputAlreadySolved;
if (!global.flagDatabaseCompiled) {
return "Error: database not running. ";
}
std::stringstream out;
if (global.userGuestMode()) {
out << "scores require login";
return out.str();
}
std::stringstream problemWeight;
ProblemData problemData;
bool showModifyButton = global.userDefaultHasAdminRights() && !global.userStudentVieWOn();
outputAlreadySolved = false;
Rational currentWeight;
std::string currentWeightAsGivenByInstructor;
if (this->currentUser.problemData.contains(fileName)) {
problemData = this->currentUser.problemData.getValueCreateEmpty(fileName);
Rational percentSolved = 0, totalPoints = 0;
percentSolved.assignNumeratorAndDenominator(problemData.numCorrectlyAnswered, problemData.answers.size());
problemData.flagProblemWeightIsOK = problemData.adminData.getWeightFromCourse(
this->currentUser.courseComputed, currentWeight, ¤tWeightAsGivenByInstructor
);
if (!problemData.flagProblemWeightIsOK) {
problemWeight << "?";
if (currentWeightAsGivenByInstructor != "") {
problemWeight << "<span style =\"color:red\">"
<< currentWeightAsGivenByInstructor << "(Error)</span>";
}
} else {
problemWeight << currentWeight;
totalPoints = percentSolved * currentWeight;
}
outputAlreadySolved = (percentSolved == 1);
if (!outputAlreadySolved) {
if (!problemData.flagProblemWeightIsOK) {
out << "<b style =\"color:brown\">" << percentSolved
<< " out of " << problemWeight.str() << "</b>";
} else {
out << "<b style =\"color:red\">" << totalPoints
<< " out of " << problemWeight.str() << "</b>";
}
} else {
if (!problemData.flagProblemWeightIsOK) {
out << "<b style =\"color:green\">solved</b>";
} else {
out << "<b style =\"color:green\">" << totalPoints << " out of " << problemWeight.str() << "</b>";
}
}
} else {
out << "<b style =\"color:brown\">need to solve</b>";
}
if (!showModifyButton) {
return out.str();
}
std::stringstream finalOut;
finalOut << "<button class =\"accordionLike\" onclick=\"toggleProblemWeights();\">"
<< out.str()
<< "</button>";
return finalOut.str();
}
void TopicElement::computeID(int elementIndex, TopicElementParser& owner) {
MacroRegisterFunctionWithName("TopicElement::computeID");
if (this->problemFileName != "") {
this->id = this->problemFileName;
if (this->type != TopicElement::types::problem) {
global.fatal
<< "Type problem is the only type allowed to have non-empty file name. "
<< global.fatal;
}
} else {
std::stringstream out;
out << elementIndex << ". ";
out << "[" << owner.elementNames.getValueNoFail(this->type) << "] ";
out << this->title;
this->id = out.str();
}
this->idBase64 = Crypto::computeSha3_256OutputBase64URL(this->id);
}
TopicElementParser::TopicElementParser() {
this->owner = nullptr;
this->maximumTopics = 10000;
}
void TopicElementParser::addTopic(TopicElement& inputElt, int index) {
MacroRegisterFunctionWithName("TopicElement::addTopic");
if (this->topics.contains(inputElt.id)) {
std::stringstream out;
out << index << ". [Error] Element id: " << inputElt.id << " already present. ";
inputElt.id = out.str();
inputElt.title = out.str();
}
this->topics.setKeyValue(inputElt.id, inputElt);
}
void TopicElement::makeError(const std::string& message) {
this->type = TopicElement::types::error;
this->error = message;
this->immediateChildren.setSize(0);
}
TopicElement::TopicElement() {
this->reset();
}
void TopicElement::reset() {
this->type = TopicElement::types::unknown;
this->indexInParent = - 1;
this->flagSubproblemHasNoWeight = false;
this->title = "empty";
this->id = "";
this->video = "";
this->videoHandwritten = "";
this->querySlides = "";
this->queryHomework = "";
this->handwrittenSolution = "";
this->sourceSlides.setSize(0);
this->sourceHomework.setSize(0);
this->sourceHomeworkIsSolution.setSize(0);
this->problemFileName = "";
this->error = "";
this->immediateChildren.setSize(0);
this->totalSubSectionsUnderME = 0;
this->totalSubSectionsUnderMeIncludingEmptySubsections = 0;
this->flagContainsProblemsNotInSubsection = false;
this->flagHasLectureTag = true;
this->pointsEarnedInProblemsThatAreImmediateChildren = 0;
this->totalPointsEarned = 0;
this->maxPointsInAllChildren = 0;
this->type = TopicElement::types::unknown;
}
bool TopicElementParser::checkConsistencyParsed() {
MacroRegisterFunctionWithName("TopicElementParser::checkConsistencyParsed");
for (int i = 0; i < this->topics.size(); i ++) {
if (this->topics.values[i].type == TopicElement::types::problem) {
if (this->topics.values[i].immediateChildren.size > 0) {
global.fatal << "Topic element: "
<< this->topics.values[i].toString()
<< " has non-zero immediate children. " << global.fatal;
return false;
}
}
}
return true;
}
bool TopicElementParser::checkNoErrors(std::stringstream* commentsOnFailure) {
MacroRegisterFunctionWithName("TopicElementParser::checkNoErrors");
for (int i = 0; i < this->topics.size(); i ++) {
TopicElement& current = this->topics.values[i];
if (current.isError()) {
if (commentsOnFailure != nullptr) {
*commentsOnFailure << "Element index "
<< i << " has an error. " << current.toString();
}
return false;
}
}
return true;
}
bool TopicElement::isError() {
return this->type == TopicElement::types::error;
}
bool TopicElement::pdfSlidesOpenIfAvailable(
CalculatorHTML& owner, std::stringstream* commentsOnFailure
) {
if (
this->type != TopicElement::types::chapter &&
this->type != TopicElement::types::section &&
this->type != TopicElement::types::topic &&
this->type != TopicElement::types::title &&
this->type != TopicElement::types::problem
) {
return true;
}
if (this->sourceSlides.size == 0) {
return true;
}
LaTeXCrawler latexCrawler;
latexCrawler.desiredPresentationTitle = this->title;
latexCrawler.addSlidesOnTop(owner.slidesSourcesHeaders);
latexCrawler.addSlidesOnTop(this->sourceSlides);
latexCrawler.flagProjectorMode = true;
latexCrawler.flagHomeworkRatherThanSlides = false;
if (!latexCrawler.extractFileNamesPdfExists(commentsOnFailure, commentsOnFailure)) {
return false;
}
std::string actualOutput;
FileOperations::getPhysicalFileNameFromVirtual(
latexCrawler.targetPDFFileNameWithPathVirtual, actualOutput, false, false, nullptr
);
global << "Physical filename: " << actualOutput << Logger::endL;
if (!latexCrawler.flagPDFExists && commentsOnFailure != nullptr) {
*commentsOnFailure << "Could not find file: "
<< latexCrawler.targetPDFFileNameWithPathVirtual << ". ";
}
return latexCrawler.flagPDFExists;
}
bool TopicElement::pdfHomeworkOpensIfAvailable(CalculatorHTML& owner, std::stringstream* commentsOnFailure) {
if (
this->type != TopicElement::types::chapter &&
this->type != TopicElement::types::section &&
this->type != TopicElement::types::topic &&
this->type != TopicElement::types::title &&
this->type != TopicElement::types::problem
) {
return true;
}
if (this->sourceHomework.size == 0) {
return true;
}
LaTeXCrawler latexCrawler;
latexCrawler.desiredPresentationTitle = this->title;
latexCrawler.addSlidesOnTop(owner.sourcesHomeworkHeaders);
latexCrawler.addSlidesOnTop(this->sourceHomework);
latexCrawler.flagHomeworkRatherThanSlides = true;
if (!latexCrawler.extractFileNamesPdfExists(commentsOnFailure, commentsOnFailure)) {
return false;
}
std::string actualOutput;
FileOperations::getPhysicalFileNameFromVirtual(
latexCrawler.targetPDFFileNameWithPathVirtual, actualOutput, false, false, nullptr
);
global << "Physical filename: " << actualOutput << Logger::endL;
if (!latexCrawler.flagPDFExists && commentsOnFailure != nullptr) {
*commentsOnFailure << "Could not find file: "
<< latexCrawler.targetPDFFileNameWithPathVirtual << ". ";
}
return latexCrawler.flagPDFExists;
}
bool TopicElement::pdfsOpenIfAvailable(CalculatorHTML& owner, std::stringstream* commentsOnFailure) {
return
this->pdfSlidesOpenIfAvailable(owner, commentsOnFailure) &&
this->pdfHomeworkOpensIfAvailable(owner, commentsOnFailure);
}
bool TopicElement::problemOpensIfAvailable(std::stringstream* commentsOnFailure) {
if (this->problemFileName == "") {
return true;
}
bool result = FileOperations::fileExistsVirtualCustomizedReadOnly(
this->problemFileName, commentsOnFailure
);
if (!result && commentsOnFailure != nullptr) {
*commentsOnFailure << "File "
<< CalculatorHTML::toStringLinkFromProblem(this->problemFileName)
<< " does not appear to exist. ";
}
return result;
}
bool TopicElementParser::checkProblemsOpen(
std::stringstream* commentsOnFailure
) {
MacroRegisterFunctionWithName("TopicElementParser::checkProblemsOpen");
for (int i = 0; i < this->topics.size(); i ++) {
TopicElement& current = this->topics.values[i];
if (!current.problemOpensIfAvailable(commentsOnFailure)) {
return false;
}
}
return true;
}
bool TopicElementParser::checkTopicPdfs(
std::stringstream* commentsOnFailure
) {
MacroRegisterFunctionWithName("TopicElementParser::checkTopicPdfs");
this->checkInitialization();
for (int i = 0; i < this->topics.size(); i ++) {
TopicElement& current = this->topics.values[i];
if (!current.pdfsOpenIfAvailable(*this->owner, commentsOnFailure)) {
return false;
}
}
return true;
}
bool TopicElementParser::checkInitialization() {
if (this->owner == nullptr) {
global.fatal << "TopicElementParser not initialized when it should be. " << global.fatal;
}
return true;
}
void TopicElementParser::TopicLine::makeError(const std::string& message) {
this->contentTrimmedWhiteSpace = StringRoutines::stringTrimWhiteSpace(message);
this->tag = "Error";
this->topicType = TopicElement::types::error;
}
void TopicElementParser::TopicLine::MakeEmpty() {
this->contentTrimmedWhiteSpace = "";
this->tag = "";
this->topicType = TopicElement::types::empty;
}
void TopicElementParser::insertTopicBundle(TopicElementParser::TopicLine& input) {
MacroRegisterFunctionWithName("TopicElementParser::insertTopicBundle");
std::string bundleId = input.contentTrimmedWhiteSpace;
if (!this->knownTopicBundles.contains(bundleId)) {
std::stringstream out;
out << "Failed to find bundle: " << bundleId << ". ";
input.makeError(out.str());
this->bundleStack.addOnTop(input);
return;
}
List<TopicElementParser::TopicLine>& currentBundle = this->knownTopicBundles.getValueCreateEmpty(bundleId);
for (int i = currentBundle.size - 1; i >= 0; i --) {
this->bundleStack.addOnTop(currentBundle[i]);
}
}
void TopicElementParser::loadTopicBundleFile(
TopicElementParser::TopicLine& input
) {
MacroRegisterFunctionWithName("TopicElement::loadTopicBundleFile");
std::string fileName = input.contentTrimmedWhiteSpace;
if (this->loadedTopicBundleFiles.contains(fileName)) {
return;
}
std::string newTopicBundles;
std::stringstream errorStream;
if (!FileOperations::isOKFileNameVirtual(fileName, false, &errorStream)) {
errorStream << "The file name " << fileName << " is not a valid topic bundle file name. ";
input.makeError(errorStream.str());
this->bundleStack.addOnTop(input);
return;
}
if (!FileOperations::loadFiletoStringVirtualCustomizedReadOnly(fileName, newTopicBundles, &errorStream)) {
errorStream << "Could not open topic bundle file. ";
input.makeError(errorStream.str());
this->bundleStack.addOnTop(input);
return;
}
this->loadedTopicBundleFiles.addOnTop(fileName);
std::string currentLineString;
List<std::string> bundleNameStack;
std::stringstream bundleReader(newTopicBundles);
while (std::getline(bundleReader, currentLineString, '\n')) {
TopicElementParser::TopicLine currentLine = this->extractLine(currentLineString);
if (currentLine.topicType == TopicElement::types::bundleBegin) {
bundleNameStack.addOnTop(currentLine.contentTrimmedWhiteSpace);
} else if (currentLine.topicType == TopicElement::types::bundleEnd) {
if (bundleNameStack.size > 0) {
bundleNameStack.removeLastObject();
} else {
errorStream << "BundleEnd command without BungleBegin.";
input.makeError(errorStream.str());
this->bundleStack.addOnTop(input);
return;
}
} else {
for (int i = 0; i < bundleNameStack.size; i ++) {
this->knownTopicBundles.getValueCreateEmpty(bundleNameStack[i]).addOnTop(currentLine);
}
}
}
}
TopicElementParser::TopicLine TopicElementParser::extractLine(const std::string& inputNonTrimmed) {
TopicElementParser::TopicLine result;
std::string input = StringRoutines::stringTrimWhiteSpace(inputNonTrimmed);
if (input.size() == 0) {
result.MakeEmpty();
return result;
}
if (input[0] == '%') {
result.MakeEmpty();
return result;
}
result.topicType = TopicElement::types::unknown;
for (unsigned i = 0; i < input.size(); i ++) {
char current = input[i];
if (current == ':') {
result.contentTrimmedWhiteSpace = StringRoutines::stringTrimWhiteSpace(input.substr(i + 1));
break;
}
result.tag.push_back(current);
}
result.tag = StringRoutines::stringTrimWhiteSpace(result.tag);
if (result.contentTrimmedWhiteSpace.size() == 0) {
result.contentTrimmedWhiteSpace = result.tag;
result.tag = "";
}
int indexElement = this->elementTypes.getIndex(result.tag);
if (indexElement >= 0) {
result.topicType = this->elementTypes.values[indexElement];
}
return result;
}
void TopicElementParser::exhaustCrawlStack() {
while (this->bundleStack.size > 0) {
if (this->crawled.size > this->maximumTopics) {
TopicElementParser::TopicLine errorLine;
std::stringstream errorStream;
errorStream << "Too many topics (" << this->crawled.size << ") while crawling bundles. ";
errorLine.makeError(errorStream.str());
this->crawled.addOnTop(errorLine);
return;
}
TopicElementParser::TopicLine nextLine = bundleStack.popLastObject();
if (nextLine.topicType == TopicElement::types::loadTopicBundles) {
this->loadTopicBundleFile(nextLine);
continue;
}
if (nextLine.topicType == TopicElement::types::topicBundle) {
this->insertTopicBundle(nextLine);
continue;
}
this->crawled.addOnTop(nextLine);
}
}
void TopicElementParser::crawl(const std::string& inputString) {
this->initializeElementTypes();
std::string currentLine, currentArgument;
std::stringstream tableReader(inputString);
this->crawled.setSize(0);
while (true) {
if (this->crawled.size > this->maximumTopics) {
TopicElementParser::TopicLine errorLine;
std::stringstream errorStream;
errorStream << "Too many topics (" << this->crawled.size << "). ";
errorLine.makeError(errorStream.str());
this->crawled.addOnTop(errorLine);
return;
}
this->exhaustCrawlStack();
if (!std::getline(tableReader, currentLine, '\n')) {
break;
}
this->bundleStack.addOnTop(this->extractLine(currentLine));
}
}
bool TopicElementParser::TopicLine::accountIfStateChanger(CalculatorHTML& owner) const {
if (this->topicType == TopicElement::types::slidesSourceHeader) {
owner.slidesSourcesHeaders.addOnTop(this->contentTrimmedWhiteSpace);
return true;
}
if (this->topicType == TopicElement::types::homeworkSourceHeader){
owner.sourcesHomeworkHeaders.addOnTop(this->contentTrimmedWhiteSpace);
return true;
}
return false;
}
void TopicElementParser::addNewTopicElementFromLine(const TopicElementParser::TopicLine& input) {
TopicElement incoming = input.toTopicElement();
if (incoming.type == TopicElement::types::empty) {
return;
}
this->elements.addOnTop(incoming);
}
bool TopicElement::mergeTopicLine(
const TopicElementParser::TopicLine& input
) {
if (this->type != TopicElement::types::problem) {
return false;
}
if (input.topicType == TopicElement::types::problem) {
if (this->problemFileName == "") {
this->problemFileName = input.contentTrimmedWhiteSpace;
return true;
} else {
return false;
}
}
switch (input.topicType) {
case TopicElement::types::video:
this->video = input.contentTrimmedWhiteSpace;
return true;
case TopicElement::types::videoHandwritten:
this->videoHandwritten = input.contentTrimmedWhiteSpace;
return true;
case TopicElement::types::slidesSource:
this->sourceSlides.addOnTop(input.contentTrimmedWhiteSpace);
return true;
case TopicElement::types::homeworkSource:
this->sourceHomework.addOnTop(input.contentTrimmedWhiteSpace);
this->sourceHomeworkIsSolution.addOnTop(false);
return true;
case TopicElement::types::homeworkSolutionSource:
this->sourceHomework.addOnTop(input.contentTrimmedWhiteSpace);
this->sourceHomeworkIsSolution.addOnTop(true);
return true;
case TopicElement::types::slidesLatex:
this->sourceSlides.addOnTop("LaTeX: " + input.contentTrimmedWhiteSpace);
return true;
case TopicElement::types::homeworkLatex:
this->sourceHomework.addOnTop("LaTeX: " + input.contentTrimmedWhiteSpace);
this->sourceHomeworkIsSolution.addOnTop(false);
return true;
case TopicElement::types::handwrittenSolutions:
this->handwrittenSolution = input.contentTrimmedWhiteSpace;
return true;
}
return false;
}
std::string TopicElementParser::TopicLine::toString() const {
std::stringstream out;
out << this->tag << ": " << this->contentTrimmedWhiteSpace;
return out.str();
}
TopicElement TopicElementParser::TopicLine::toTopicElement() const {
TopicElement result;
result.type = TopicElement::types::empty;
if (this->topicType == TopicElement::types::problem) {
result.problemFileName = this->contentTrimmedWhiteSpace;
result.type = TopicElement::types::problem;
}
if (this->topicType == TopicElement::types::title) {
result.type = TopicElement::types::problem;
result.title = this->contentTrimmedWhiteSpace;
}
if (
this->topicType == TopicElement::types::chapter ||
this->topicType == TopicElement::types::section ||
this->topicType == TopicElement::types::topic
) {
result.type = this->topicType;
result.title = this->contentTrimmedWhiteSpace;
}
return result;
}
void TopicElementParser::compressOneTopicLine(
const TopicElementParser::TopicLine& input, CalculatorHTML& owner
) {
if (input.accountIfStateChanger(owner)) {
return;
}
if (this->elements.size == 0) {
this->addNewTopicElementFromLine(input);
return;
}
TopicElement& last = *this->elements.lastObject();
if (last.mergeTopicLine(input)) {
return;
}
this->addNewTopicElementFromLine(input);
}
void TopicElementParser::compressTopicLines() {
MacroRegisterFunctionWithName("TopicElementParser::compressTopicLines");
this->checkInitialization();
this->elements.setSize(0);
for (int i = 0; i < this->crawled.size; i ++) {
this->compressOneTopicLine(this->crawled[i], *this->owner);
}
}
void TopicElementParser::computeIds() {
for (int i = 0; i < this->elements.size; i ++) {
this->elements[i].computeID(i, *this);
}
}
std::string TopicElementParser::toString() const {
std::stringstream out;
out << "Loaded bundle files: " << this->loadedTopicBundleFiles;
out << "<hr>";
out << "Known bundles: " << this->knownTopicBundles.toStringHtml();
return out.str();
}
void TopicElementParser::parseTopicList(
const std::string& inputString
) {
MacroRegisterFunctionWithName("TopicElementParser::parseTopicList");
this->crawl(inputString);
this->compressTopicLines();
this->computeIds();
for (int i = 0; i < this->elements.size; i ++) {
this->addTopic(this->elements[i], i);
}
this->computeTopicHierarchy();
this->computeTopicNumbers();
}
void TopicElementParser::computeTopicNumbers() {
List<int> currentProblemNumber;
for (int i = 0; i < this->topics.size(); i ++) {
TopicElement& current = this->topics.values[i];
int labelsNeeded = current.type - TopicElement::types::chapter + 1;
if (labelsNeeded > 4 || labelsNeeded < 0) {
labelsNeeded = 4;
}
for (int j = currentProblemNumber.size; j < labelsNeeded; j ++) {
currentProblemNumber.addOnTop(0);
}
currentProblemNumber.setSize(labelsNeeded);
(*currentProblemNumber.lastObject()) ++;
current.problemNumber = currentProblemNumber;
}
}
void TopicElementParser::computeTopicHierarchy() {
this->computeTopicHierarchyPartOne();
this->computeTopicHierarchyPartTwo();
}
void TopicElementParser::computeTopicHierarchyPartOne() {
MacroRegisterFunctionWithName("computeTopicHierarchyPartOne");
List<int> parentChain;
List<int> parentTypes;
for (int i = 0; i < this->topics.size(); i ++) {
int currentAdjustedtype = this->topics.values[i].type;
if (
currentAdjustedtype != TopicElement::types::chapter &&
currentAdjustedtype != TopicElement::types::section &&
currentAdjustedtype != TopicElement::types::topic
) {
currentAdjustedtype = TopicElement::types::problem;
}
for (int j = parentChain.size - 1; j >= 0; j --) {
if (parentTypes[j] >= currentAdjustedtype) {
parentTypes.removeLastObject();
parentChain.removeLastObject();
}
}
if (parentChain.size > 0) {
TopicElement& parent = this->topics.values[*parentChain.lastObject()];
parent.immediateChildren.addOnTop(i);
}
this->topics.values[i].parentTopics.setSize(0);
for (int j = 0; j < parentChain.size; j ++) {
this->topics.values[i].parentTopics.addOnTop(parentChain[j]);
}
parentChain.addOnTop(i);
parentTypes.addOnTop(currentAdjustedtype);
}
}
void TopicElementParser::computeTopicHierarchyPartTwo() {
MacroRegisterFunctionWithName("TopicElementParser::computeTopicHierarchyPartTwo");
for (int i = this->topics.size() - 1; i >= 0; i --) {
TopicElement& currentElt = this->topics.values[i];
if (currentElt.problemFileName != "") {
continue;
}
if (currentElt.type == TopicElement::types::topic) {
currentElt.totalSubSectionsUnderME = 0;
currentElt.totalSubSectionsUnderMeIncludingEmptySubsections = 0;
currentElt.flagContainsProblemsNotInSubsection = false;
continue;
}
currentElt.flagContainsProblemsNotInSubsection = false;
currentElt.totalSubSectionsUnderME = 0;
for (int j = 0; j < currentElt.immediateChildren.size; j ++) {
TopicElement& currentChild = this->topics.values[currentElt.immediateChildren[j]];
if (currentChild.type == TopicElement::types::topic) {
currentElt.totalSubSectionsUnderME ++;
currentElt.totalSubSectionsUnderMeIncludingEmptySubsections ++;
} else if (currentChild.problemFileName != "") {
currentElt.flagContainsProblemsNotInSubsection = true;
} else {
currentElt.totalSubSectionsUnderME += currentChild.totalSubSectionsUnderME;
currentElt.totalSubSectionsUnderMeIncludingEmptySubsections += currentChild.totalSubSectionsUnderMeIncludingEmptySubsections;
}
}
if (currentElt.flagContainsProblemsNotInSubsection) {
currentElt.totalSubSectionsUnderMeIncludingEmptySubsections ++;
}
}
this->checkConsistencyParsed();
}
void CalculatorHTML::interpretAccountInformationLinks(SyntacticElementHTML& inputOutput) {
MacroRegisterFunctionWithName("CalculatorHTML::interpretAccountInformationLinks");
std::stringstream out;
if (!global.flagLoggedIn) {
out << "<b>User not logged-in.</b>";
inputOutput.interpretedCommand = out.str();
return;
}
if (!global.flagUsingSSLinCurrentConnection) {
out << "<b>Account management requires https.</b>";
inputOutput.interpretedCommand = out.str();
return;
}
out << "<a href=\"" << global.displayNameExecutable << "?request=changePasswordPage\">Change password</a>";
if (global.userDefaultHasAdminRights()) {
out << "<br>\n<a href=\"" << global.displayNameExecutable << "?request=accounts\">Manage accounts</a>";
}
inputOutput.interpretedCommand = out.str();
return;
}
bool CalculatorHTML::loadAndParseTopicIndex(int index, std::stringstream& comments) {
MacroRegisterFunctionWithName("CalculatorHTML::loadAndParseTopicIndex");
if (index == 0) {
return CalculatorHTML::loadAndParseTopicList(comments);
}
index --;
CourseList courseList;
if (!courseList.load()) {
comments << "Failed to log course list. ";
return false;
}
if (index < 0 || index >= courseList.allCourses.size) {
comments << "Index out of range. ";
return false;
}
Course course = courseList.allCourses[index];
this->topicListFileName = course.courseTopicsWithFolder();
this->courseHome = course.title;
return CalculatorHTML::loadAndParseTopicList(comments);
}
bool CalculatorHTML::loadAndParseTopicList(std::stringstream& comments) {
MacroRegisterFunctionWithName("CalculatorHTML::loadAndParseTopicList");
if (this->topics.topics.size() != 0) {
return true;
}
if (this->topicListContent == "") {
if (!FileOperations::loadFiletoStringVirtualCustomizedReadOnly(
this->topicListFileName, this->topicListContent, &comments
)) {
comments
<< "Failed to load the topic list associated with this course. "
<< "Go to ``select course'' from the menu "
<< "to see a list of available courses. ";
return false;
}
}
if (this->topicListContent == "") {
comments << "Topic list empty. Topic list file name: "
<< this->topicListFileName << ". ";
return false;
}
this->topics.parseTopicList(this->topicListContent);
this->problemNamesNoTopics.clear();
for (int i = 0; i < this->topics.topics.size(); i ++) {
if (this->topics.topics.values[i].problemFileName != "") {
this->problemNamesNoTopics.addOnTop(
this->topics.topics.values[i].problemFileName
);
}
}
return true;
}
JSData CalculatorHTML::toStringTopicListJSON(std::stringstream* comments) {
MacroRegisterFunctionWithName("CalculatorHTML::toStringTopicListJSON");
std::stringstream out;
JSData output, topicBundleFiles;
if (!this->loadAndParseTopicList(out)) {
output[WebAPI::result::error] = out.str();
return output;
}
topicBundleFiles.elementType = JSData::token::tokenArray;
for (int i = 0; i < this->topics.loadedTopicBundleFiles.size; i ++) {
topicBundleFiles[i] = this->topics.loadedTopicBundleFiles[i];
}
output["topicBundleFile"] = topicBundleFiles;
output["children"].elementType = JSData::token::tokenArray;
for (int i = 0; i < this->topics.topics.size(); i ++) {
TopicElement& currentElt = this->topics.topics.values[i];
if (currentElt.type == TopicElement::types::chapter) {
output["children"].listObjects.addOnTop(currentElt.toJSON(*this));
}
}
if (global.userDefaultIsDebuggingAdmin()) {
if (comments != nullptr) {
output[WebAPI::result::comments] = comments->str();
}
output[WebAPI::result::commentsGlobal] = global.comments.getCurrentReset();
}
return output;
}
void CalculatorHTML::interpretJavascripts(SyntacticElementHTML& inputOutput) {
MacroRegisterFunctionWithName("CalculatorHTML::interpretJavascripts");
std::string javascriptName = StringRoutines::stringTrimWhiteSpace(inputOutput.content);
}
int TopicElement::scoreButtonCounter = 0;
bool CalculatorHTML::computeTopicListAndPointsEarned(std::stringstream& commentsOnFailure) {
MacroRegisterFunctionWithName("CalculatorHTML::computeTopicListAndPointsEarned");
if (!this->loadAndParseTopicList(commentsOnFailure)) {
return false;
}
if (!this->loadDatabaseInfo(commentsOnFailure)) {
commentsOnFailure << "Error loading problem history. ";
}
if (!this->prepareSectionList(commentsOnFailure)) {
commentsOnFailure << "Error preparing section list. ";
}
if (global.flagDatabaseCompiled) {
this->flagIncludeStudentScores =
global.userDefaultHasAdminRights() &&
!global.userStudentVieWOn() &&
global.requestType != "templateNoLogin";
HashedList<std::string, MathRoutines::hashString> gradableProblems;
for (int i = 0; i < this->topics.topics.size(); i ++) {
if (this->topics.topics.values[i].type == TopicElement::types::problem) {
gradableProblems.addOnTopNoRepetition(this->topics.topics.values[i].id);
if (this->topics.topics.values[i].immediateChildren.size > 0) {
global.fatal << "Error: problem " << this->topics.topics.values[i].toString()
<< " has children topics which is not allowed. "
<< global.fatal;
}
}
}
this->currentUser.computePointsEarned(gradableProblems, &this->topics.topics, commentsOnFailure);
}
this->topics.initializeElementTypes();
return true;
}
JSData LaTeXCrawler::FileWithOption::toJSON() {
JSData result;
result[WebAPI::request::slides::slideFilename] = this->fileName;
if (this->isSolution) {
result[WebAPI::request::slides::isSolution] = "true";
}
return result;
}
bool LaTeXCrawler::FileWithOption::fromJSON(JSData& input, std::stringstream* commentsOnFailure) {
JSData& file = input[WebAPI::request::slides::slideFilename];
if (file.elementType != JSData::token::tokenString) {
if (commentsOnFailure != nullptr) {
*commentsOnFailure << "While parsing file, failed to find key: " << WebAPI::request::slides::slideFilename << ". ";
}
return false;
}
this->fileName = file.stringValue;
this->isSolution = false;
if (input[WebAPI::request::slides::isSolution].stringValue == "true") {
this->isSolution = true;
}
return true;
}
void LaTeXCrawler::Slides::addSlidesOnTop(const List<std::string>& input) {
for (int i = 0; i < input.size; i ++) {
this->filesToCrawl.addOnTop(LaTeXCrawler::FileWithOption(input[i]));
}
}
JSData LaTeXCrawler::Slides::toJSON() {
JSData result;
result[WebAPI::request::slides::title] = this->title;
JSData fileNames;
fileNames.elementType = JSData::token::tokenArray;
for (int i = 0; i < this->filesToCrawl.size; i ++) {
fileNames.listObjects.addOnTop(this->filesToCrawl[i].toJSON());
}
result[WebAPI::request::slides::files] = fileNames;
return result;
}
bool LaTeXCrawler::Slides::fromJSON(
JSData& input, std::stringstream* commentsOnFailure
) {
if (!input[WebAPI::request::slides::title].isString(&this->title)) {
if (commentsOnFailure != nullptr) {
*commentsOnFailure << "slideTitle entry missing or not a string. ";
}
return false;
}
JSData& files = input[WebAPI::request::slides::files];
if (files.elementType != JSData::token::tokenArray) {
if (commentsOnFailure != nullptr) {
*commentsOnFailure << "files entry missing or not a list. ";
}
return false;
}
this->filesToCrawl.setSize(files.listObjects.size);
for (int i = 0; i < files.listObjects.size; i ++) {
if (!this->filesToCrawl[i].fromJSON(files.listObjects[i], commentsOnFailure)) {
if (commentsOnFailure != nullptr) {
*commentsOnFailure << "Failed to extract file from entry index " << i << ". ";
}
return false;
}
}
return true;
}
bool LaTeXCrawler::Slides::fromString(
const std::string& input, std::stringstream* commentsOnFailure
) {
if (input == "") {
if (commentsOnFailure != nullptr) {
*commentsOnFailure << "Slide specification string is empty. ";
}
return false;
}
std::string decoded;
HtmlRoutines::convertURLStringToNormal(input, decoded, false);
JSData parsed;
if (!parsed.parse(decoded, commentsOnFailure)) {
if (commentsOnFailure != nullptr) {
*commentsOnFailure << "Failed to parse your input in "
<< "LaTeXCrawler::Slides::fromString. ";
}
return false;
}
return this->fromJSON(parsed, commentsOnFailure);
}
JSData TopicElement::computeSlidesJSON(CalculatorHTML& owner) {
LaTeXCrawler::Slides slides;
slides.addSlidesOnTop(owner.slidesSourcesHeaders);
slides.addSlidesOnTop(this->sourceSlides);
slides.title = this->title;
return slides.toJSON();
}
JSData TopicElement::computeHomeworkJSON(CalculatorHTML& owner) {
LaTeXCrawler::Slides slides;
slides.addSlidesOnTop(owner.sourcesHomeworkHeaders);
for (int i = 0; i < this->sourceHomework.size; i ++) {
LaTeXCrawler::FileWithOption file;
file.fileName = this->sourceHomework[i];
if (i < this->sourceHomeworkIsSolution.size) {
file.isSolution = this->sourceHomeworkIsSolution[i];
}
slides.filesToCrawl.addOnTop(file);
}
slides.title = this->title;
return slides.toJSON();
}
void TopicElement::computeHomework(CalculatorHTML& owner) {
MacroRegisterFunctionWithName("TopicElement::computeHomework");
if (this->sourceHomework.size == 0) {
return;
}
JSData resultJSON = this->computeHomeworkJSON(owner);
this->queryHomework = WebAPI::request::slides::content + "=" + HtmlRoutines::convertStringToURLString(resultJSON.toString(), false);
}
void TopicElement::computeSlides(CalculatorHTML& owner) {
MacroRegisterFunctionWithName("TopicElement::computeSlides");
if (this->sourceSlides.size == 0) {
return;
}
JSData resultJSON = this->computeSlidesJSON(owner);
this->querySlides = WebAPI::request::slides::content + "=" + HtmlRoutines::convertStringToURLString(resultJSON.toString(), false);
}
void TopicElement::computeLinks(CalculatorHTML& owner, bool plainStyle) {
MacroRegisterFunctionWithName("TopicElement::computeLinks");
(void) plainStyle;
if (this->displayProblemLink != "") {
return;
}
int depth = 3;
if (this->type == TopicElement::types::chapter) {
depth = 0;
}
if (this->type == TopicElement::types::section) {
depth = 1;
}
if (this->type == TopicElement::types::topic) {
depth = 2;
}
std::stringstream problemLabel;
for (int i = 0; i < depth + 1; i ++) {
problemLabel << this->problemNumber[i];
problemLabel << ".";
}
problemLabel << " ";
this->problemNumberString = problemLabel.str();
std::string titleWithLectureNumber = this->title;
this->flagHasLectureTag = false;
int lectureTagStart = static_cast<int>(titleWithLectureNumber.find("<lectureTag>"));
if (lectureTagStart >= 0) {
int lectureTagFinish = static_cast<int>(titleWithLectureNumber.find("</lectureTag>"));
if (lectureTagFinish >= 0) {
owner.topicLectureCounter ++;
lectureTagFinish += 13;
std::stringstream newTitle;
newTitle
<< titleWithLectureNumber.substr(0, static_cast<unsigned>(lectureTagStart))
<< "<lectureTag>ℒ"
<< "</lectureTag>"
<< "Lecture "
<< owner.topicLectureCounter
<< "."
<< titleWithLectureNumber.substr(static_cast<unsigned>(lectureTagFinish));
this->flagHasLectureTag = true;
titleWithLectureNumber = newTitle.str();
}
}
if (this->title == "") {
this->displayTitle = this->problemNumberString + "-" ;
} else {
this->displayTitle = this->problemNumberString + titleWithLectureNumber;
}
if (this->video == "" || this->video == "-" || this->video == "--") {
this->displayVideoLink = "";
} else {
this->displayVideoLink = "<a href=\"" + this->video +
"\" class ='videoLink' class = 'videoLink' target = '_blank'>Video</a>";
}
if (this->videoHandwritten == "" || this->videoHandwritten == "-" || this->videoHandwritten == "--") {
this->displayVideoHandwrittenLink = "";
} else {
this->displayVideoHandwrittenLink = "<a href=\"" +
this->videoHandwritten + "\" class =\"videoLink\" class =\"videoLink\" target =\"_blank\">Video <b>(H)</b></a>";
}
if (this->handwrittenSolution != "") {
this->displayHandwrittenSolution = "<a href=\"" +
this->handwrittenSolution + "\" class =\"slidesLink\">Handwritten solutions</a>";
}
this->computeSlides(owner);
this->computeHomework(owner);
bool problemSolved = false;
bool returnEmptyStringIfNoDeadline = false;
if (this->problemFileName == "") {
if (this->type == TopicElement::types::problem) {
this->displayProblemLink = "(theory)";
} else {
this->displayProblemLink = "";
}
this->displayScore = "";
this->displayModifyWeight = "";
problemSolved = false;
returnEmptyStringIfNoDeadline = true;
} else {
//std::string rawSQLink = global.displayNameExecutable +
//"?request=scoredQuiz&fileName=" + this->problem;
std::string rawExerciseLink;
rawExerciseLink = global.displayNameExecutable + "?request=exercise&fileName=" + this->problemFileName;
this->displayProblemLink = owner.toStringLinkFromFileName(this->problemFileName);
this->displayScore = owner.toStringProblemScoreShort(this->problemFileName, problemSolved);
}
if (this->problemFileName == "" && this->type == TopicElement::types::problem) {
this->displayDeadlinE = "";
} else {
this->displayDeadlinE = owner.toStringDeadline(
this->id, problemSolved, returnEmptyStringIfNoDeadline, (this->type != TopicElement::types::problem)
);
}
std::stringstream displayResourcesLinksStream;
displayResourcesLinksStream
<< this->displayVideoLink << this->displayVideoHandwrittenLink
<< this->displayHandwrittenSolution;
this->displayResourcesLinks = displayResourcesLinksStream.str();
if (this->problemFileName != "") {
owner.numberOfProblemsFound ++;
}
if (this->video != "") {
owner.numberOfVideosWithSlidesFound ++;
}
if (this->videoHandwritten != "") {
owner.numberOfVideosHandwrittenFound ++;
}
}
JSData TopicElement::toJSON(CalculatorHTML& owner) {
MacroRegisterFunctionWithName("TopicElement::toJSON");
JSData output;
output["title"] = this->title;
std::string elementType = owner.topics.elementNames.getValueCreateEmpty(this->type);
if (elementType == "") {
elementType = "not documented";
}
output["type"] = elementType;
output["children"].elementType = JSData::token::tokenArray;
this->computeLinks(owner, true);
if (this->type == TopicElement::types::problem && this->immediateChildren.size > 0) {
global.fatal << "Error: Problem " << this->toString() << " reported to have children topic elements: "
<< this->immediateChildren.toStringCommaDelimited() << global.fatal;
}
for (int i = 0; i < this->immediateChildren.size; i ++) {
TopicElement& currentChild = owner.topics.topics.values[this->immediateChildren[i]];
output["children"].listObjects.addOnTop(currentChild.toJSON(owner));
}
output["problemNumberString"] = this->problemNumberString;
output["video"] = this->video;
output["videoHandwritten"] = this->videoHandwritten;
if (this->querySlides != "") {
output["querySlides"] = this->querySlides;
}
if (this->queryHomework != "") {
output[WebAPI::request::slides::queryHomework] = this->queryHomework;
}
output[DatabaseStrings::labelDeadlines] = this->deadlinesPerSectioN;
if (!global.userDefaultHasProblemComposingRights()) {
std::string deadline = owner.getDeadlineNoInheritance(this->id);
output[WebAPI::problem::deadlineSingle] = deadline;
}
output["handwrittenSolution"] = this->handwrittenSolution;
output[WebAPI::problem::fileName] = this->problemFileName;
output[WebAPI::problem::idProblem] = this->id;
if (global.flagDatabaseCompiled) {
if (owner.currentUser.problemData.contains(this->problemFileName)) {
ProblemData& currentData = owner.currentUser.problemData.getValueCreateEmpty(this->problemFileName);
output["correctlyAnswered"] = currentData.numCorrectlyAnswered;
output["totalQuestions"] = currentData.answers.size();
Rational currentWeight;
std::string currentWeightAsGivenByInstructor;
currentData.flagProblemWeightIsOK = currentData.adminData.getWeightFromCourse(
owner.currentUser.courseComputed, currentWeight, ¤tWeightAsGivenByInstructor
);
if (currentData.flagProblemWeightIsOK) {
output["weight"] = currentWeightAsGivenByInstructor;
}
}
}
return output;
}
std::string TopicElement::toString() const {
std::stringstream out;
out << this->title << ", id: " << this->id << " ";
if (this->title == "") {
out << "-";
}
if (this->type == TopicElement::types::problem) {
out << "(problem)";
}
if (this->type == TopicElement::types::chapter) {
out << "(chapter)";
}
if (this->type == TopicElement::types::section) {
out << "(section)";
}
if (this->type == TopicElement::types::topic) {
out << "(subsection)";
}
out << ". Index in parent: " << this->indexInParent;
out << ". Parents: " << this->parentTopics.toStringCommaDelimited()
<< ". Immediate children: " << this->immediateChildren.toStringCommaDelimited() << ". ";
return out.str();
}
| 38.387611 | 137 | 0.704314 | tmilev |
23fedab0e03fc589615f011678fb317abafd7eb0 | 840 | cpp | C++ | src/glfw-cxx/GammaRamp.cpp | Mischa-Alff/glfw-cxx | bd335a7c5ac959da0ea1ac009a66b75ada21efb6 | [
"MIT"
] | 12 | 2015-07-05T15:07:26.000Z | 2020-07-10T03:15:56.000Z | src/glfw-cxx/GammaRamp.cpp | TheRealJoe24/glfw-cxx | bd335a7c5ac959da0ea1ac009a66b75ada21efb6 | [
"MIT"
] | 1 | 2016-08-10T16:49:13.000Z | 2016-08-19T18:23:04.000Z | src/glfw-cxx/GammaRamp.cpp | TheRealJoe24/glfw-cxx | bd335a7c5ac959da0ea1ac009a66b75ada21efb6 | [
"MIT"
] | 3 | 2017-04-24T14:33:46.000Z | 2019-06-15T22:15:22.000Z | #include <glfw-cxx/GammaRamp.hpp>
namespace glfw
{
unsigned short* GammaRamp::GetRed()
{
return m_gammaramp.red;
}
void GammaRamp::SetRed(unsigned short* red)
{
m_gammaramp.red = red;
}
unsigned short* GammaRamp::GetGreen()
{
return m_gammaramp.green;
}
void GammaRamp::SetGreen(unsigned short* green)
{
m_gammaramp.green = green;
}
unsigned short* GammaRamp::GetBlue()
{
return m_gammaramp.blue;
}
void GammaRamp::SetBlue(unsigned short* blue)
{
m_gammaramp.blue = blue;
}
unsigned int GammaRamp::GetSize()
{
return m_gammaramp.size;
}
void GammaRamp::SetSize(unsigned int size)
{
m_gammaramp.size = size;
}
GLFWgammaramp* GammaRamp::GetRawPointerData()
{
return &m_gammaramp;
}
GammaRamp::GammaRamp(GLFWgammaramp gammaramp) : m_gammaramp(gammaramp) {}
GammaRamp::GammaRamp() {}
}
| 15.555556 | 74 | 0.705952 | Mischa-Alff |
9b00611b2ea7c84a162cb3dc1282a41c055ad8df | 1,501 | hpp | C++ | Raylib/include/Gamepad.hpp | MitchellRB/Pathfinding | 65be4ab55489fb79c98fdbd86e88c2e2e70d7105 | [
"MIT"
] | null | null | null | Raylib/include/Gamepad.hpp | MitchellRB/Pathfinding | 65be4ab55489fb79c98fdbd86e88c2e2e70d7105 | [
"MIT"
] | null | null | null | Raylib/include/Gamepad.hpp | MitchellRB/Pathfinding | 65be4ab55489fb79c98fdbd86e88c2e2e70d7105 | [
"MIT"
] | null | null | null | #ifndef RAYLIB_CPP_GAMEPAD_HPP_
#define RAYLIB_CPP_GAMEPAD_HPP_
#include <string>
#ifdef __cplusplus
extern "C"{
#endif
#include "raylib.h"
#ifdef __cplusplus
}
#endif
#include "./raylib-cpp-utils.hpp"
namespace raylib {
class Gamepad {
public:
Gamepad(int gamepadNumber = 0) {
set(gamepadNumber);
}
int number;
inline void set(int gamepadNumber) {
number = gamepadNumber;
}
GETTERSETTER(int,Number,number)
Gamepad& operator=(const Gamepad& gamepad) {
set(gamepad);
return *this;
}
operator int() const { return number; }
inline bool IsAvailable() {
return ::IsGamepadAvailable(number);
}
inline bool IsName(const std::string& name) {
return ::IsGamepadName(number, name.c_str());
}
std::string GetName() {
return std::string(::GetGamepadName(number));
}
inline bool IsButtonPressed(int button) {
return ::IsGamepadButtonPressed(number, button);
}
inline bool IsButtonDown(int button) {
return ::IsGamepadButtonDown(number, button);
}
inline bool IsButtonReleased(int button) {
return ::IsGamepadButtonReleased(number, button);
}
inline bool IsButtonUp(int button) {
return ::IsGamepadButtonUp(number, button);
}
inline int GetButtonPressed() {
return ::GetGamepadButtonPressed();
}
inline int GetAxisCount() {
return ::GetGamepadAxisCount(number);
}
inline float GetAxisMovement(int axis) {
return ::GetGamepadAxisMovement(number, axis);
}
};
}
#endif
| 19.75 | 52 | 0.686875 | MitchellRB |
9b02408d2961dc099ebe068a3b2a2a77d67fc4bc | 4,297 | cpp | C++ | cplusplus/TDD/src/tdd-QbLzwDictionary.cpp | abaquesoftware/QbGifBuilder | 2fae881308beb60def50e494feaa119e417fadfe | [
"MIT"
] | null | null | null | cplusplus/TDD/src/tdd-QbLzwDictionary.cpp | abaquesoftware/QbGifBuilder | 2fae881308beb60def50e494feaa119e417fadfe | [
"MIT"
] | null | null | null | cplusplus/TDD/src/tdd-QbLzwDictionary.cpp | abaquesoftware/QbGifBuilder | 2fae881308beb60def50e494feaa119e417fadfe | [
"MIT"
] | null | null | null | #include <catch/catch.hpp>
#include "QbGifBuilder/include/QbLzwDecoder.h"
using namespace std;
using namespace Catch::Matchers;
TEST_CASE( "Constructor and getters", "[QbLzwDictionary]" ) {
QbLzwDictionary test1(8);
QbLzwDictionary test2(7);
CHECK(test1.getInitialCodeWidth() == 8);
CHECK(test1.getEntryMapSize() == (1 << 8) + 2);
CHECK(test1.getMaxEntrySize() == 1);
CHECK(test1.getCodeWidthChangeEntry()->toString() == "---- code width change");
// KO !!!
// CHECK( test1.getEntryByData (NULL, 0, 1) == NULL );
__u_char bytes[] = {0x00, 0x01, 0xcd, 0xff};
CHECK(test1.getEntryByCode(0x01)->toString() == "[0x0001]->(1):0x01");
CHECK(test1.getEntryByCode(0xab)->toString() == "[0x00ab]->(1):0xab");
CHECK(test1.getEntryByCode(0xff)->toString() == "[0x00ff]->(1):0xff");
CHECK(test1.getEntryByCode(0x100)->toString() == "[0x0100]->(1):0x00");
CHECK(test1.getEntryByCode(0x101)->toString() == "[0x0101]->(1):0x00");
CHECK( test1.getEntryByData(bytes, 0, 1)->toString() == "[0x0000]->(1):0x00");
CHECK( test1.getEntryByData(bytes, 1, 1)->toString() == "[0x0001]->(1):0x01");
CHECK( test1.getEntryByData(bytes, 2, 1)->toString() == "[0x00cd]->(1):0xcd");
CHECK( test1.getEntryByData(bytes, 3, 1)->toString() == "[0x00ff]->(1):0xff");
CHECK( test1.getEntryByData(bytes, 0, 2) == NULL );
CHECK( test2.getInitialCodeWidth() == 7 );
CHECK( test2.getEntryMapSize() == (1 << 7) + 2 );
CHECK( test2.getEntryByCode(1)->toString() == "[0x0001]->(1):0x01");
}
TEST_CASE( "Add entry from byte array", "[QbLzwDictionary]" ) {
QbLzwDictionary test(8);
__u_char bytes[] = {0x00, 0x01, 0x02};
u_short newCode = test.addEntry(bytes, 2);
CHECK( newCode == ((1 << 8) + 2 ) );
CHECK( test.getEntryByCode(0x0102)->toString() == "[0x0102]->(2):0x00.0x01");
CHECK( test.getEntryByData(bytes, 0, 2)->toString() == "[0x0102]->(2):0x00.0x01");
CHECK( test.getEntryMapSize() == (1 << 8) + 2 + 1 );
CHECK( test.getMaxEntrySize() == 2 );
newCode = test.addEntry(bytes, 3);
CHECK( newCode == ((1 << 8) + 2 + 1 ) );
CHECK( test.getEntryByCode(0x0103)->toString() == "[0x0103]->(3):0x00.0x01.0x02");
CHECK( test.getEntryByData(bytes, 0, 3)->toString() == "[0x0103]->(3):0x00.0x01.0x02");
CHECK( test.getEntryMapSize() == (1 << 8) + 2 + 2 );
CHECK( test.getMaxEntrySize() == 3 );
}
TEST_CASE( "Add entry from QbLzwDictionaryEntry", "[QbLzwDictionary]" ) {
QbLzwDictionary test(8);
__u_char bytes[] = {0x00, 0x01, 0x7F};
QbLzwDictionaryEntry entry(bytes, 2, 8);
u_short newCode = test.addEntry(&entry, 0x7F);
CHECK( newCode == ((1 << 8) + 2 ) );
CHECK( test.getEntryByCode(0x0102)->toString() == "[0x0102]->(3):0x00.0x01.0x7f");
CHECK( test.getEntryByData(bytes, 0, 3)->toString() == "[0x0102]->(3):0x00.0x01.0x7f");
CHECK( test.getEntryMapSize() == (1 << 8) + 2 + 1 );
CHECK( test.getMaxEntrySize() == 3 );
}
TEST_CASE( "clearAll", "[QbLzwDictionary]" ) {
QbLzwDictionary test(8);
__u_char *bytes = (__u_char *)malloc(sizeof(__u_char) * 256);
for (int i = 0; i < 256; i++) {
bytes[i] = i;
}
u_short newCode = test.addEntry(bytes, 2);
CHECK( test.getInitialCodeWidth() == 8 );
CHECK( test.getEntryMapSize() == (1 << 8) + 2 + 1 );
CHECK( test.getMaxEntrySize() == 2 );
CHECK( newCode == ((1 << 8) + 2 ) );
test.clearAll();
CHECK( test.getInitialCodeWidth() == 8 );
CHECK( test.getEntryMapSize() == (1 << 8) + 2 );
CHECK( test.getMaxEntrySize() == 1 );
}
TEST_CASE( "Test entry stack overflow", "[QbLzwDictionary]" ) {
int max_entries = 4094;
QbLzwDictionary test(8);
u_short newCode;
// Add 4093 - 259 entries
__u_char *bytes = (__u_char *)malloc(sizeof(__u_char) * 256);
int nb_new_entries = 0;
int nb_created_entries = 0;
int nb_error_entries = 0;
for (int i = 0; i < 230; i++) {
for (int j = 2; j < 20; j++) {
if (nb_new_entries < (max_entries - 256 - 2)) {
newCode = test.addEntry(&(bytes[i]), j);
if (newCode == 0xFFFF ) {
nb_error_entries++;
} else {
nb_created_entries++;
}
nb_new_entries++;
}
}
}
CHECK( nb_created_entries == (max_entries - 256 - 2) );
CHECK( nb_error_entries == 0 );
// Add 1 more entries
newCode = test.addEntry(&(bytes[254]), 2);
CHECK( newCode == 0xFFFF );
}
| 37.692982 | 89 | 0.616011 | abaquesoftware |
9b02f7607108666b76bb6a08bdd681959fe7deab | 3,624 | cpp | C++ | Program2/src/App.cpp | PawelWieczorek/MuditaTask | dd4786beee6853205df067709c5f73e32c6ca89a | [
"Unlicense"
] | null | null | null | Program2/src/App.cpp | PawelWieczorek/MuditaTask | dd4786beee6853205df067709c5f73e32c6ca89a | [
"Unlicense"
] | null | null | null | Program2/src/App.cpp | PawelWieczorek/MuditaTask | dd4786beee6853205df067709c5f73e32c6ca89a | [
"Unlicense"
] | null | null | null | //
// Created by pawel on 04.05.20.
//
#include "../include/App.h"
App::App(const std::string fifo_1to2, const std::string fifo_2to1) : fifo_1to2_name(fifo_1to2), fifo_2to1_name(fifo_2to1)
{
fifo_2to1_write = nullptr;
fifo_1to2_read = nullptr;
App::isOpen = true;
App::readingFromFifo = true;
App::writingToFifo = true;
writeQueue = std::queue<std::string>();
commandQueue = std::queue<ICommand*>();
}
void App::open_fifo_to_read(std::string fifo_to_read)
{
this->fifo_1to2_read = new FifoReader(fifo_to_read);
}
void App::open_fifo_to_write(std::string fifo_to_write)
{
this->fifo_2to1_write = new FifoWriter(fifo_to_write);
}
App::~App()
{
delete fifo_1to2_read;
delete fifo_2to1_write;
isOpen = false;
while (readingFromFifo || writingToFifo) {}
}
void App::create()
{
std::thread open_fifo_rd(&App::open_fifo_to_read, this, fifo_1to2_name);
std::thread open_fifo_wr(&App::open_fifo_to_write, this, fifo_2to1_name);
open_fifo_rd.detach();
open_fifo_wr.detach();
while (fifo_2to1_write == nullptr || fifo_1to2_read == nullptr) {}
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = (void (*)(int)) &App::finish_program;
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
sigaction(SIGINT, &sigIntHandler, NULL);
this->create_bitmap();
}
void App::execute()
{
std::thread read_fifo(&App::read_from_fifo, this);
std::thread write_fifo(&App::write_to_fifo, this);
std::thread execution(&App::execute_commands, this);
read_fifo.detach();
write_fifo.detach();
execution.detach();
while (readingFromFifo || writingToFifo) {}
}
void App::write_to_fifo()
{
do {
std::string write_buff = "";
this->writeMutex.lock();
if (!this->writeQueue.empty())
{
write_buff = writeQueue.front();
writeQueue.pop();
}
this->writeMutex.unlock();
if (!write_buff.empty())
{
this->fifo_2to1_write->write(write_buff);
}
usleep(100);
} while(App::isOpen);
App::writingToFifo = false;
}
void App::read_from_fifo()
{
std::string read_buff = "";
do {
read_buff = this->fifo_1to2_read->read();
if (!read_buff.empty())
{
ICommand* command = parser.parse(read_buff);
if (command != nullptr)
{
this->commandMutex.lock();
this->commandQueue.push(command);
this->commandMutex.unlock();
}
else
{
this->writeMutex.lock();
this->writeQueue.push("Bad_command: " + read_buff);
this->writeMutex.unlock();
}
}
usleep(100);
} while(App::isOpen);
App::readingFromFifo = false;
}
void App::finish_program()
{
App::isOpen = false;
}
void App::execute_commands()
{
do
{
ICommand* command = nullptr;
this->commandMutex.lock();
if (!this->commandQueue.empty())
{
command = commandQueue.front();
commandQueue.pop();
}
this->commandMutex.unlock();
if (command != nullptr)
{
command->execute(this->image);
delete command;
}
usleep(100);
} while (App::isOpen);
}
void App::create_bitmap()
{
this->image = bitmap_image(200, 200);
this->image.set_all_channels(255,255,255);
}
volatile bool App::isOpen;
volatile bool App::readingFromFifo;
volatile bool App::writingToFifo; | 20.590909 | 121 | 0.594647 | PawelWieczorek |
9b04af6a7f544db35456ffaccc7877b12112175b | 1,976 | hpp | C++ | src/Calendar/MonthlyCalendar.hpp | pokorj54/Command-line-calendar | de2c8a89917bd4cb69547427a6ec1bced218c5ad | [
"MIT"
] | null | null | null | src/Calendar/MonthlyCalendar.hpp | pokorj54/Command-line-calendar | de2c8a89917bd4cb69547427a6ec1bced218c5ad | [
"MIT"
] | null | null | null | src/Calendar/MonthlyCalendar.hpp | pokorj54/Command-line-calendar | de2c8a89917bd4cb69547427a6ec1bced218c5ad | [
"MIT"
] | null | null | null | #ifndef MonthlyCalendar_3837d1b6871845d09187dff8161117e6
#define MonthlyCalendar_3837d1b6871845d09187dff8161117e6
#include "Calendar.hpp"
#include "../Event/Event.hpp"
#include "../Event/EventContainer.hpp"
#include <iostream>
/**
* @brief Represents Calendar that can show events in selected month
*
*/
class MonthlyCalendar : public Calendar
{
private:
/**
* @brief Prints Block view of a calnendar for selected month with marking of given days
*
* @param[out] os Here it will be printed
* @param days Days which will be marked with color
*/
void PrintBlockCalendar(std::ostream & os, const std::vector<int> & days) const;
public:
/**
* @brief Construct a new MonthlyCalendar object, selects first day of month as start
*
* @param ec From this container it will gather Event objects
* @param dt Selects month
*/
MonthlyCalendar(const std::shared_ptr<EventContainer> & ec, DateTime dt);
/**
* @brief Fills instances with all Event objects that are happening selected month
*
*/
void FillWithVirtualEvents() override;
/**
* @brief Prints all VirtualEvents objects in instances, spilts them by start day
*
* @param[out] os here it will be printed
*/
void Print(std::ostream & os) const override;
/**
* @brief Prints that it is MonthlyCalendar and first day of selected month
*
* @param[out] os here it will be printed
*/
void PrintPrefix(std::ostream & os) const override;
/**
* @brief Changes Calendar view to next month
*
*/
void Next() override;
/**
* @brief Changes Calendar view to previous month
*
*/
void Prev() override;
};
#endif //MonthlyCalendar_3837d1b6871845d09187dff8161117e6 | 31.365079 | 96 | 0.607287 | pokorj54 |
9b066ece3e949e7a90bee638f6c594ffc3e0d5f9 | 1,343 | cpp | C++ | examples/google-code-jam/slowpoke/GCJ2017Q-C.cpp | rbenic-fer/progauthfp | d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675 | [
"MIT"
] | null | null | null | examples/google-code-jam/slowpoke/GCJ2017Q-C.cpp | rbenic-fer/progauthfp | d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675 | [
"MIT"
] | null | null | null | examples/google-code-jam/slowpoke/GCJ2017Q-C.cpp | rbenic-fer/progauthfp | d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <iostream>
using namespace std;
void comp(int tc){
unsigned long long n, k;
cin >> n >> k;
unsigned long long lowC = 0, hiC = 1, nlowC = 0, nhiC = 0, lowV = n-1, hiV = n, count = 0;
unsigned long long ans;
while(true){
if(count + hiC + lowC >= k){
if(count + hiC >= k){
ans = hiV;
}else{
ans = lowV;
}
break;
}
count += lowC + hiC;
if(lowV & 1){
if(lowV >= 3)
nlowC += lowC * 2;
} else {
if(lowV >= 4){
nlowC += lowC;
}
if(lowV >= 2){
nhiC += lowC;
}
}
if(hiV & 1){
if(hiV >= 3)
nhiC += hiC * 2;
} else {
if(hiV >= 4){
nlowC += hiC;
}
if(hiV >= 2){
nhiC += hiC;
}
}
lowC = nlowC;
hiC = nhiC;
nlowC = nhiC = 0;
lowV = (lowV-1)/2;
hiV = hiV/2;
}
cout << "Case #" << tc << ": " << (ans/2) << " " << ((ans-1)/2) << endl;
}
int main(){
int T;
cin >> T;
for(int tc=1; tc<=T; ++tc){
comp(tc);
}
}
| 20.044776 | 94 | 0.323902 | rbenic-fer |
9b0b8ddbd44045d563b7134ff7b3edbb095c0433 | 457 | inl | C++ | node_modules/lzz-gyp/lzz-source/util_Table.inl | SuperDizor/dizornator | 9f57dbb3f6af80283b4d977612c95190a3d47900 | [
"ISC"
] | 3 | 2019-09-18T16:44:33.000Z | 2021-03-29T13:45:27.000Z | node_modules/lzz-gyp/lzz-source/util_Table.inl | SuperDizor/dizornator | 9f57dbb3f6af80283b4d977612c95190a3d47900 | [
"ISC"
] | null | null | null | node_modules/lzz-gyp/lzz-source/util_Table.inl | SuperDizor/dizornator | 9f57dbb3f6af80283b4d977612c95190a3d47900 | [
"ISC"
] | 2 | 2019-03-29T01:06:38.000Z | 2019-09-18T16:44:34.000Z | // util_Table.inl
//
#ifdef LZZ_ENABLE_INLINE
#define LZZ_INLINE inline
#else
#define LZZ_INLINE
#endif
namespace util
{
LZZ_INLINE TableNode::TableNode (size_t handle, size_t bit_mask)
: handle (handle), bit_mask (bit_mask)
{}
}
namespace util
{
LZZ_INLINE size_t Table::get_fdb_mask (size_t handle1, size_t handle2)
{
int i, k;
for (i = 1, k = handle1 ^ handle2; ! (k & i); i <<= 1);
return i;
}
}
#undef LZZ_INLINE
| 18.28 | 72 | 0.656455 | SuperDizor |
9b0ebe0eaf89da27820516ce270161f4d3a6a648 | 1,922 | cpp | C++ | archive/3/januszex.cpp | Aleshkev/algoritmika | fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189 | [
"MIT"
] | 2 | 2019-05-04T09:37:09.000Z | 2019-05-22T18:07:28.000Z | archive/3/januszex.cpp | Aleshkev/algoritmika | fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189 | [
"MIT"
] | null | null | null | archive/3/januszex.cpp | Aleshkev/algoritmika | fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef int I;
struct Span {
I a, b;
Span(I a, I b) : a(a), b(b) {};
bool operator<(const Span &other) {
return a < other.a;
};
};
int main()
{
char JANUSZEX[] = "januszex";
I EIGHT = sizeof(JANUSZEX) - 1;
I n, m;
scanf("%i %i", &n, &m);
//cout << n << m;
static I t[200000];
for(I i = 0; i < n; ++i) {
char c;
scanf(" %c", &c);
char *j = strchr(JANUSZEX, c);
t[i] = j != NULL ? j - JANUSZEX : EIGHT;
}
/*for(I i = 0; i < n; ++i) {
cout << setw(2) << t[i] << ' ';
} cout << '\n';*/
vector<Span> spans;
for(I i = 0; i < n; ++i) {
if(t[i] != 0) {
continue;
}
I current = 0;
I b = i + 1;
while(b < n) {
if(t[b] == current + 1) {
++current;
if(current == EIGHT - 1) {
break;
}
}
++b;
}
if(b < n) {
spans.push_back(Span(i, b + 1));
}
}
/*for(I i = 0; i < spans.size(); ++i) {
cout << spans[i].a << ":" << spans[i].b << ' ';
for(I j = spans[i].a; j < spans[i].b; ++j) {
cout << t[j] << ' ';
} cout << '\n';
}*/
/*for(I i = 0; i < n; ++i) {
cout << setw(2) << u[i] << ' ';
} cout << '\n';*/
for(I i = 0; i < m; ++i) {
I a, b;
scanf("%i %i", &a, &b);
--a;
I score = 0;
I taken_to = 0;
for(vector<Span>::iterator it = lower_bound(spans.begin(), spans.end(), Span(a, -1)); it != spans.end() && it->b <= b; ++it) {
if(it->a < taken_to) {
continue;
}
++score;
taken_to = it->b;
}
//cout << ": " << score << endl;
printf("%i\n", score);
}
return 0;
}
| 19.814433 | 134 | 0.349636 | Aleshkev |
9b13709bccd72d1e0d9c82e2c7f4aa19c1939a81 | 6,580 | cpp | C++ | src/Misc/MatchHistoryEntry.cpp | BigETI/WhackAStoodentServer | 05c670a9b745262ae926aebcb1fce0f1ecc5f4d2 | [
"MIT"
] | 1 | 2021-04-28T20:32:57.000Z | 2021-04-28T20:32:57.000Z | src/Misc/MatchHistoryEntry.cpp | BigETI/WhackAStoodentServer | 05c670a9b745262ae926aebcb1fce0f1ecc5f4d2 | [
"MIT"
] | 7 | 2021-08-24T14:09:33.000Z | 2021-08-30T12:47:40.000Z | src/Misc/MatchHistoryEntry.cpp | BigETI/WhackAStoodentServer | 05c670a9b745262ae926aebcb1fce0f1ecc5f4d2 | [
"MIT"
] | null | null | null | #include <Misc/MatchHistoryEntry.hpp>
#include <Static/NumericSerializer.hpp>
#include <Static/StringSerializer.hpp>
/// <summary>
/// Constructs a match history entry
/// </summary>
WhackAStoodentServer::MatchHistoryEntry::MatchHistoryEntry() :
yourScore(static_cast<std::int64_t>(0)),
yourRole(WhackAStoodentServer::EPlayerRole::Hitter),
opponentScore(static_cast<std::int64_t>(0)),
opponentRole(WhackAStoodentServer::EPlayerRole::Mole)
{
// ...
}
/// <summary>
/// Constructs a match history entry
/// </summary>
/// <param name="matchHistoryEntry">Match history entry</param>
WhackAStoodentServer::MatchHistoryEntry::MatchHistoryEntry(const WhackAStoodentServer::MatchHistoryEntry& matchHistoryEntry) :
yourScore(matchHistoryEntry.yourScore),
yourRole(matchHistoryEntry.yourRole),
yourName(matchHistoryEntry.yourName),
opponentScore(matchHistoryEntry.opponentScore),
opponentRole(matchHistoryEntry.opponentRole),
opponentName(matchHistoryEntry.opponentName)
{
// ...
}
/// <summary>
/// Constructs a match history entry
/// </summary>
/// <param name="matchHistoryEntry">Match history entry</param>
WhackAStoodentServer::MatchHistoryEntry::MatchHistoryEntry(WhackAStoodentServer::MatchHistoryEntry&& matchHistoryEntry) :
yourScore(matchHistoryEntry.yourScore),
yourRole(matchHistoryEntry.yourRole),
yourName(matchHistoryEntry.yourName),
opponentScore(matchHistoryEntry.opponentScore),
opponentRole(matchHistoryEntry.opponentRole),
opponentName(matchHistoryEntry.opponentName)
{
// ...
}
/// <summary>
/// Constructs a match history entry
/// </summary>
/// <param name="yourScore">Your score</param>
/// <param name="yourRole">Your role</param>
/// <param name="yourName">Your name</param>
/// <param name="opponentScore">Opponent's score</param>
/// <param name="opponentRole">Opponent's role</param>
/// <param name="opponentName">Opponent's name</param>
WhackAStoodentServer::MatchHistoryEntry::MatchHistoryEntry(std::int64_t yourScore, WhackAStoodentServer::EPlayerRole yourRole, std::wstring_view yourName, std::int64_t opponentScore, WhackAStoodentServer::EPlayerRole opponentRole, std::wstring_view opponentName) :
yourScore(yourScore),
yourRole(yourRole),
yourName(yourName),
opponentScore(opponentScore),
opponentRole(opponentRole),
opponentName(opponentName)
{
// ...
}
/// <summary>
/// Destroys match history entry
/// </summary>
WhackAStoodentServer::MatchHistoryEntry::~MatchHistoryEntry()
{
// ...
}
/// <summary>
/// Gets your score
/// </summary>
/// <returns>Your score</returns>
std::int64_t WhackAStoodentServer::MatchHistoryEntry::GetYourScore() const
{
return yourScore;
}
/// <summary>
/// Gets your role
/// </summary>
/// <returns>Your role</returns>
WhackAStoodentServer::EPlayerRole WhackAStoodentServer::MatchHistoryEntry::GetYourRole() const
{
return yourRole;
}
/// <summary>
/// Gets your name
/// </summary>
/// <returns>Your name</returns>
std::wstring_view WhackAStoodentServer::MatchHistoryEntry::GetYourName() const
{
return yourName;
}
/// <summary>
/// Gets the opponent's score
/// </summary>
/// <returns>Opponent's score</returns>
std::int64_t WhackAStoodentServer::MatchHistoryEntry::GetOpponentScore() const
{
return opponentScore;
}
/// <summary>
/// Gets opponent's role
/// </summary>
/// <returns>Opponent's role</returns>
WhackAStoodentServer::EPlayerRole WhackAStoodentServer::MatchHistoryEntry::GetOpponentRole() const
{
return opponentRole;
}
/// <summary>
/// Gets the opponent's name
/// </summary>
/// <returns>Opponent's name</returns>
std::wstring_view WhackAStoodentServer::MatchHistoryEntry::GetOpponentName() const
{
return opponentName;
}
/// <summary>
/// Serializes contents
/// </summary>
/// <param name="result">Result</param>
/// <returns>Serialized contents</returns>
std::vector<std::uint8_t>& WhackAStoodentServer::MatchHistoryEntry::Serialize(std::vector<std::uint8_t>& result) const
{
WhackAStoodentServer::NumericSerializer::SerializeLong(yourScore, result);
WhackAStoodentServer::NumericSerializer::SerializeByte(static_cast<std::uint8_t>(yourRole), result);
WhackAStoodentServer::StringSerializer::SerializeByteSizedString(yourName, result);
WhackAStoodentServer::NumericSerializer::SerializeLong(opponentScore, result);
WhackAStoodentServer::NumericSerializer::SerializeByte(static_cast<std::uint8_t>(opponentRole), result);
return WhackAStoodentServer::StringSerializer::SerializeByteSizedString(opponentName, result);
}
/// <summary>
/// Deserializes given input
/// </summary>
/// <param name="data">Data to deserialize</param>
/// <returns>Remaining data to deserialize</returns>
nonstd::span<const std::uint8_t> WhackAStoodentServer::MatchHistoryEntry::Deserialize(nonstd::span<const std::uint8_t> data)
{
std::uint8_t role;
nonstd::span<const std::uint8_t> next_bytes(WhackAStoodentServer::NumericSerializer::DeserializeLong(data, yourScore));
next_bytes = WhackAStoodentServer::NumericSerializer::DeserializeByte(next_bytes, role);
yourRole = static_cast<WhackAStoodentServer::EPlayerRole>(role);
next_bytes = WhackAStoodentServer::StringSerializer::DeserializeByteSizedString(next_bytes, yourName);
next_bytes = WhackAStoodentServer::NumericSerializer::DeserializeLong(next_bytes, opponentScore);
next_bytes = WhackAStoodentServer::NumericSerializer::DeserializeByte(next_bytes, role);
opponentRole = static_cast<WhackAStoodentServer::EPlayerRole>(role);
return WhackAStoodentServer::StringSerializer::DeserializeByteSizedString(next_bytes, opponentName);
}
/// <summary>
/// Assigns a match history entry to this object
/// </summary>
/// <param name="matchHistoryEntry">Match history entry</param>
/// <returns>This object</returns>
WhackAStoodentServer::MatchHistoryEntry& WhackAStoodentServer::MatchHistoryEntry::operator=(const WhackAStoodentServer::MatchHistoryEntry& matchHistoryEntry)
{
yourScore = matchHistoryEntry.yourScore;
yourName = matchHistoryEntry.yourName;
opponentScore = matchHistoryEntry.opponentScore;
opponentName = matchHistoryEntry.opponentName;
return *this;
}
/// <summary>
/// Assigns a match history entry to this object
/// </summary>
/// <param name="matchHistoryEntry">Match history entry</param>
/// <returns>This object</returns>
WhackAStoodentServer::MatchHistoryEntry& WhackAStoodentServer::MatchHistoryEntry::operator=(WhackAStoodentServer::MatchHistoryEntry&& matchHistoryEntry) noexcept
{
yourScore = matchHistoryEntry.yourScore;
yourName = matchHistoryEntry.yourName;
opponentScore = matchHistoryEntry.opponentScore;
opponentName = matchHistoryEntry.opponentName;
return *this;
}
| 34.814815 | 264 | 0.780091 | BigETI |
9b14e3bf90159387c623741a8c0fd72741057162 | 15,646 | cpp | C++ | HomeController/RGB3ChController.cpp | Yurik72/ESPHomeController | 89561ee27c4e8d847dc1c3d6505dfc6436514a91 | [
"MIT"
] | 24 | 2019-03-02T20:21:15.000Z | 2022-01-04T18:34:05.000Z | HomeController/RGB3ChController.cpp | Yurik72/ESPHomeController | 89561ee27c4e8d847dc1c3d6505dfc6436514a91 | [
"MIT"
] | null | null | null | HomeController/RGB3ChController.cpp | Yurik72/ESPHomeController | 89561ee27c4e8d847dc1c3d6505dfc6436514a91 | [
"MIT"
] | 5 | 2019-09-20T10:11:22.000Z | 2021-12-10T05:12:31.000Z | #include <Arduino.h>
#include <ArduinoJson.h>
#include "config.h"
#include "Utilities.h"
#include "BaseController.h"
#include "RGB3ChController.h"
#include <Ticker.h>
#ifndef DISABLE_RGB
REGISTER_CONTROLLER_FACTORY(RGB3ChController)
#endif
const size_t bufferSize = JSON_OBJECT_SIZE(40);
static String rgbModes;
/// Matrix
///// Controller
RGB3ChController::RGB3ChController() {
this->mqtt_hue = 0.0;
this->mqtt_saturation = 0.0;
this->pSmooth = new CSmoothVal();
this->isEnableSmooth = true;
//rgbModes = "";
//this->coreMode = Both;
//this->core = 1;
//this->priority = 100;
this->malimit = 2000; //mamper limit
this->rpin=0;
this->gpin=0;
this->bpin=0;
#ifdef ESP32
//.this->channel= get_next_available_channel ();
this->rchannel = get_next_espchannel();
this->gchannel = get_next_espchannel();
this->bchannel = get_next_espchannel();
#endif
#ifdef ENABLE_NATIVE_HAP
this->ishap=true;
this->hapservice=NULL;
this->hap_on=NULL;
this->hap_br=NULL;
this->hap_hue=NULL;
this->hap_saturation=NULL;
#endif
}
RGB3ChController::~RGB3ChController() {
if (this->pSmooth)
delete this->pSmooth;
}
String RGB3ChController::serializestate() {
DynamicJsonDocument jsonBuffer(bufferSize);
JsonObject root = jsonBuffer.to<JsonObject>();
root[FPSTR(szisOnText)] = this->get_state().isOn;
root[FPSTR(szbrightnessText)] = this->get_state().brightness;
root["color"] = this->get_state().color;
String json;
json.reserve(256);
serializeJson(root, json);
return json;
}
bool RGB3ChController::deserializestate(String jsonstate, CmdSource src) {
//DBG_OUTPUT_PORT.println("RGBStripController::deserializestate");
if (jsonstate.length() == 0) {
DBG_OUTPUT_PORT.println("State is empty");
return false;
}
DynamicJsonDocument jsonBuffer(bufferSize);
DeserializationError error = deserializeJson(jsonBuffer, jsonstate);
if (error) {
DBG_OUTPUT_PORT.print(FPSTR(szParseJsonFailText));
DBG_OUTPUT_PORT.println(this->get_name());
DBG_OUTPUT_PORT.println(error.c_str());
return false;
}
JsonObject root = jsonBuffer.as<JsonObject>();
RGB3ChState newState = this->get_state();
newState.isOn = get_json_bool(root, FPSTR(szisOnText));// root[FPSTR(szisOnText)];
newState.brightness = root[FPSTR(szbrightnessText)];
newState.color = root["color"];
this->AddCommand(newState, SetRGB, src);
return true;
}
void RGB3ChController::loadconfig(JsonObject& json) {
RGB3ChStrip::loadconfig(json);
pin = json[FPSTR(szPinText)];
numleds = json[FPSTR(sznumleds)];
//isEnableSmooth = json[FPSTR(szissmooth)];
// if(json.containsKey("rgb_startled"))
// rgb_startled= json["rgb_startled"];
loadif(isEnableSmooth, json, FPSTR(szissmooth));
loadif(malimit, json,"malimit");
loadif(temperature, json, "temperature");
loadif(correction, json, "correction");
loadif(rpin, json, "rpin");
loadif(gpin, json, "gpin");
loadif(bpin, json, "bpin");
}
void RGB3ChController::getdefaultconfig(JsonObject& json) {
json[FPSTR(szPinText)]= pin;
json[FPSTR(sznumleds)]= numleds;
json[FPSTR(szservice)] = "RGB3ChController";
json[FPSTR(szname)] = "RGB3Ch";
json[FPSTR(szissmooth)] = false;
json[FPSTR(szrgb_startled)] = -1;
json[FPSTR(szismatrix)] = false;
json[FPSTR(szmatrixwidth)] = 0;
json["temperature"] = 0;
json["correction"] = 0;
json["rpin"] = 1;
json["gpin"] = 2;
json["bpin"] = 3;
RGB3ChStrip::getdefaultconfig(json);
}
void RGB3ChController::setup() {
RGB3ChStrip::setup();
#ifdef ESP8266
if(rpin>0)
pinMode(rpin, OUTPUT);
if (gpin > 0)
pinMode(gpin, OUTPUT);
if (bpin > 0)
pinMode(bpin, OUTPUT);
//digitalWrite(pin, this->isinvert ? HIGH : LOW);
#endif
#ifdef ESP32
// if (gpio_hold_en((gpio_num_t)pin) != ESP_OK) {
// DBG_OUTPUT_PORT.println("rtc_gpio_hold_en error");
// }
if (rpin > 0) {
ledcSetup(rchannel, DIM_FREQ, DIM_RESOLUTION);
ledcAttachPin(rpin, rchannel);
pinMode(rpin, OUTPUT);
}
if (gpin > 0) {
ledcSetup(gchannel, DIM_FREQ, DIM_RESOLUTION);
ledcAttachPin(gpin, gchannel);
pinMode(gpin, OUTPUT);
}
if (bpin > 0) {
ledcSetup(bchannel, DIM_FREQ, DIM_RESOLUTION);
ledcAttachPin(bpin, bchannel);
pinMode(bpin, OUTPUT);
}
setBrightness(100);
// if (gpio_hold_en((gpio_num_t)pin) != ESP_OK) {
// DBG_OUTPUT_PORT.println("rtc_gpio_hold_en error");
// }
#endif
}
void RGB3ChController::runcore() {
}
void RGB3ChController::setColor(uint8_t r, uint8_t g, uint8_t b) {
RGB3ChState state = this->get_state();
if (rpin > 0) {
#ifdef ESP8266
analogWrite(rpin, DIMCALC_VAL(CALC_COLOR(r, state.get_br_100()), false));
#endif
#ifdef ESP32
ledcWrite(rchannel, DIMCALC_VAL(CALC_COLOR(r, state.get_br_100()), false));
#endif
}
if (gpin > 0) {
#ifdef ESP8266
analogWrite(gpin, DIMCALC_VAL(CALC_COLOR(r, state.get_br_100()), false));
#endif
#ifdef ESP32
ledcWrite(gchannel, DIMCALC_VAL(CALC_COLOR(g, state.get_br_100()), false));
#endif
}
if (bpin > 0) {
#ifdef ESP8266
analogWrite(bpin, DIMCALC_VAL(CALC_COLOR(r, state.get_br_100()), false));
#endif
#ifdef ESP32
ledcWrite(bchannel, DIMCALC_VAL(CALC_COLOR(b, state.get_br_100()), false));
#endif
}
/*
DBG_OUTPUT_PORT.print("RED::");
DBG_OUTPUT_PORT.println(CALC_COLOR(r, state.get_br_100()));
DBG_OUTPUT_PORT.print("GREEN::");
DBG_OUTPUT_PORT.println(CALC_COLOR(g, state.get_br_100()));
DBG_OUTPUT_PORT.print("BLUE::");
DBG_OUTPUT_PORT.println(CALC_COLOR(b, state.get_br_100()));
*/
}
void RGB3ChController::setBrightness(uint8_t br) {
RGB3ChState state = this->get_state();
this->setColor(REDVALUE(state.color), GREENVALUE(state.color), BLUEVALUE(state.color));
}
void RGB3ChController::run() {
command cmd;
bool isSet = true;
if (this->isEnableSmooth && pSmooth->isActive())
return; ///ignore
while (commands.Dequeue(&cmd)) {
//DBG_OUTPUT_PORT.println("RGBStripController::process command");
//DBG_OUTPUT_PORT.println(cmd.mode);
if (this->baseprocesscommands(cmd))
continue;
RGB3ChState newState = this->get_state();
switch (cmd.mode) {
case On:
newState.isOn = true;
newState.fadetm = cmd.state.fadetm;
break;
case Off:
newState.isOn = false;
newState.fadetm = cmd.state.fadetm;
break;
case SetBrigthness:
newState.brightness = cmd.state.brightness;
break;
case SetColor:
newState.color = cmd.state.color;
newState.isHsv = cmd.state.isHsv;
break;
case SetRGB:
case SetRestore:
newState = cmd.state;
break;
default:
isSet = false;
break;
}
if(isSet)
this->set_state(newState);
}
RGB3ChStrip::run();
}
void RGB3ChController::set_power_on() {
RGB3ChStrip::set_power_on();
this->run();
}
void RGB3ChController::set_state(RGB3ChState state) {
//DBG_OUTPUT_PORT.println("RGBStripController::set_state");
RGB3ChState oldState = this->get_state();
RGB3ChController* self = this;
bool ignore_br = false;
if (oldState.isOn != state.isOn) { // on/off
if (state.isOn) {
if (this->isEnableSmooth && !pSmooth->isActive()) {
// DBG_OUTPUT_PORT.println("CMD On Smooth");
pSmooth->stop();
int brval = state.brightness;
pSmooth->start(0, brval,
[self](int val) {
self->setBrightness(val);
}, //self->setbrightness(val, srcSmooth);},
[self, state]() {self->AddCommand(state, SetRGB, srcSmooth);});
ignore_br = true;
//return;
}
else {
this->setBrightness(state.brightness);
}
}
else {
//DBG_OUTPUT_PORT.println("Switching OFF");
if (this->isEnableSmooth && !pSmooth->isActive()) {
pSmooth->stop();
uint32_t duration = 1000;
if (state.fadetm > 1) {
duration = state.fadetm * 1000;
}
uint32_t count = duration / 50;
//DBG_OUTPUT_PORT.println(duration);
//DBG_OUTPUT_PORT.println(count);
pSmooth->start(oldState.brightness,0,
[self](int val) {
self->setBrightness(val);
//self->pStripWrapper->trigger();
},//self->setbrightness(val, srcSmooth);},
[self, state]() {
//if (self->pStripWrapper->isRunning())
// self->pStripWrapper->stop();
self->AddCommand(state, SetRGB, srcSmooth);
},duration,count);
//return;
}else{
this->setBrightness(0);
}
}
}
if (state.isOn) {
if (oldState.color != state.color)
this->setColor(REDVALUE(state.color), GREENVALUE(state.color), BLUEVALUE(state.color));
if (!state.isHsv && ((oldState.color != state.color) || (oldState.brightness != state.brightness))) {
double intensity = 0.0;
double hue = 0.0;
double saturation = 0.0;
ColorToHSI(state.color, state.brightness, hue, saturation, intensity);
this->mqtt_hue = hue;
this->mqtt_saturation = saturation*100.0/255.0;
}
if (oldState.brightness != state.brightness && !ignore_br) {
this->setBrightness(state.brightness);
}
}
RGB3ChStrip::set_state(state);
}
bool RGB3ChController::onpublishmqtt(String& endkey, String& payload) {
endkey = szStatusText;
payload = String(this->get_state().isOn ? 1 : 0);
return true;
}
bool RGB3ChController::onpublishmqttex(String& endkey, String& payload, int topicnr){
switch (topicnr) {
case 0:
endkey = szStatusText;
payload = String(this->get_state().isOn ? 1 : 0);
return true;
case 1:
if (!this->get_state().isOn) return false;
endkey = "Brightness";
payload = String(this->get_state().brightness);
return true;
case 2:
if (!this->get_state().isOn) return false;
endkey = "Hue";
payload = String(this->mqtt_hue);
return true;
case 3:
if (!this->get_state().isOn) return false;
endkey = "Saturation";
payload = String(this->mqtt_saturation);
return true;
default:
return false;
}
}
void RGB3ChController::onmqqtmessage(String topic, String payload) {
//RGBState oldState = this->get_state();
command setcmd;
setcmd.state= this->get_state();
if (topic.endsWith("Set")) {
if (payload.toInt() > 0) {
setcmd.mode = On;
setcmd.state.isOn = true;
}
else {
setcmd.mode = Off;
setcmd.state.isOn = false;
}
}
if (topic.endsWith("Brightness")) {
setcmd.mode = SetBrigthness;
setcmd.state.brightness = payload.toInt();
}else if(topic.endsWith("Hue")) {
this->mqtt_hue= payload.toFloat();
setcmd.state.color = HSVColor(this->mqtt_hue, this->mqtt_saturation, setcmd.state.brightness);
setcmd.mode = SetColor;
#ifdef MQTT_DEBUG
DBG_OUTPUT_PORT.print("Mqtt: Hue,hue = color = ");
DBG_OUTPUT_PORT.println(this->mqtt_hue);
DBG_OUTPUT_PORT.println(setcmd.state.color);
#endif
}
else if (topic.endsWith("Saturation")) {
this->mqtt_saturation = payload.toFloat();
setcmd.state.color = HSVColor(this->mqtt_hue, this->mqtt_saturation, setcmd.state.brightness);
setcmd.mode = SetColor;
#ifdef MQTT_DEBUG
DBG_OUTPUT_PORT.print("Mqtt: Saturation,sat- color = ");
DBG_OUTPUT_PORT.println(this->mqtt_saturation);
DBG_OUTPUT_PORT.println(setcmd.state.color);
#endif
}
this->AddCommand(setcmd.state, setcmd.mode, srcMQTT);
}
#if !defined ASYNC_WEBSERVER
#if defined(ESP8266)
void RGBStripController::setuphandlers(ESP8266WebServer& server) {
ESP8266WebServer* _server = &server;
#else
void RGBStripController::setuphandlers(WebServer& server) {
WebServer* _server = &server;
#endif
String path = "/";
path += this->get_name();
path+= String("/get_modes");
RGBStripController* self=this;
_server->on(path, HTTP_GET, [=]() {
DBG_OUTPUT_PORT.println("get modes request");
_server->sendHeader("Access-Control-Allow-Origin", "*");
_server->sendHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");
_server->send_P(200, PSTR("text/html"), self->string_modes().c_str());
DBG_OUTPUT_PORT.println("Processed");
});
}
#endif
#if defined ASYNC_WEBSERVER
void RGB3ChController::setuphandlers(AsyncWebServer& server) {
}
#endif
void RGB3ChController::setbrightness(int br, CmdSource src) {
RGB3ChState st = this->get_state();
if (st.brightness == 0 && br!=0)
this->AddCommand(st, On, src);
st.brightness = br;
this->AddCommand(st, SetBrigthness, src);
if (br == 0)
this->AddCommand(st, Off, src);
}
#ifdef ENABLE_NATIVE_HAP
void RGB3ChController::setup_hap_service(){
DBG_OUTPUT_PORT.println("RGB3ChController::setup_hap_service()");
if(!ishap)
return;
if (this->accessory_type > 1) {
this->hapservice = hap_add_rgbstrip_service_as_accessory(this->accessory_type, this->get_name(), RGB3ChController::hap_callback, this);
}
else
{
this->hapservice = hap_add_rgbstrip_service(this->get_name(), RGB3ChController::hap_callback, this);
}
//homekit_service_t* x= HOMEKIT_SERVICE(LIGHTBULB, .primary = true);
//homekit_characteristic_t * ch= NEW_HOMEKIT_CHARACTERISTIC(NAME, "x");
//this->hapservice=hap_add_rgbstrip_service(this->get_name(), RGB3ChController::hap_callback,this);
this->hap_on=homekit_service_characteristic_by_type(this->hapservice, HOMEKIT_CHARACTERISTIC_ON);;
this->hap_br=homekit_service_characteristic_by_type(this->hapservice, HOMEKIT_CHARACTERISTIC_BRIGHTNESS);;
this->hap_hue=homekit_service_characteristic_by_type(this->hapservice, HOMEKIT_CHARACTERISTIC_HUE);;
this->hap_saturation=homekit_service_characteristic_by_type(this->hapservice, HOMEKIT_CHARACTERISTIC_SATURATION);;
}
void RGB3ChController::notify_hap(){
if(this->ishap && this->hapservice){
//DBG_OUTPUT_PORT.println("RGBStripController::notify_hap");
RGB3ChState newState=this->get_state();
if(this->hap_on && this->hap_on->value.bool_value!=newState.isOn){
this->hap_on->value.bool_value=newState.isOn;
homekit_characteristic_notify(this->hap_on,this->hap_on->value);
}
if(this->hap_br && this->hap_br->value.int_value !=newState.get_br_100()){
this->hap_br->value.int_value=newState.get_br_100();
homekit_characteristic_notify(this->hap_br,this->hap_br->value);
}
if(this->hap_hue && this->hap_hue->value.float_value !=this->mqtt_hue){
this->hap_hue->value.float_value=this->mqtt_hue;
homekit_characteristic_notify(this->hap_hue,this->hap_hue->value);
}
if(this->hap_saturation && this->hap_saturation->value.float_value !=this->mqtt_saturation){
this->hap_saturation->value.float_value=this->mqtt_saturation;
homekit_characteristic_notify(this->hap_saturation,this->hap_saturation->value);
}
}
}
void RGB3ChController::hap_callback(homekit_characteristic_t *ch, homekit_value_t value, void *context){
//DBG_OUTPUT_PORT.println("RGBStripController::hap_callback");
if(!context){
return;
};
RGB3ChController* ctl= (RGB3ChController*)context;
RGB3ChState newState=ctl->get_state();
RGB3ChCMD cmd = On;
bool isSet=false;
if(ch==ctl->hap_on && ch->value.bool_value!=newState.isOn){
newState.isOn=ch->value.bool_value;
cmd =newState.isOn?On:Off;
isSet=true;
}
if(ch==ctl->hap_br && ch->value.int_value!=newState.get_br_100()){
newState.set_br_100(ch->value.int_value);
cmd=SetBrigthness;
isSet=true;
}
if(ch==ctl->hap_hue && ch->value.float_value!=ctl->mqtt_hue){
ctl->mqtt_hue=ch->value.float_value;
newState.isHsv = true;
newState.color = HSVColor(ctl->mqtt_hue, ctl->mqtt_saturation/100.0, newState.brightness / 255.0);
cmd=SetColor;
//isSet=true;
//DBG_OUTPUT_PORT.println("HUE");
//DBG_OUTPUT_PORT.println(ch->value.float_value);
}
if(ch==ctl->hap_saturation && ch->value.float_value!=ctl->mqtt_saturation){
ctl->mqtt_saturation=ch->value.float_value;
newState.color = HSVColor(ctl->mqtt_hue, ctl->mqtt_saturation/100.0, newState.brightness/255.0);
cmd=SetColor;
newState.isHsv = true;
isSet=true;
//DBG_OUTPUT_PORT.println("Saturation");
//DBG_OUTPUT_PORT.println(ch->value.float_value);
}
// newState.isOn=value.bool_value;
if(isSet)
ctl->AddCommand(newState, cmd, srcHAP);
}
#endif
| 27.790409 | 137 | 0.707337 | Yurik72 |
9b1bedc066b51ce44fa2e69d9905e7db808aa3dc | 1,879 | hpp | C++ | src/rstd/iter/iter_decl.hpp | agerasev/cpp-rstd | cb4dcb510c4b3d562f7fed0d9eaa3eca94c9db36 | [
"MIT"
] | null | null | null | src/rstd/iter/iter_decl.hpp | agerasev/cpp-rstd | cb4dcb510c4b3d562f7fed0d9eaa3eca94c9db36 | [
"MIT"
] | null | null | null | src/rstd/iter/iter_decl.hpp | agerasev/cpp-rstd | cb4dcb510c4b3d562f7fed0d9eaa3eca94c9db36 | [
"MIT"
] | null | null | null | #pragma once
#include <type_traits>
#include <rstd/prelude.hpp>
namespace rstd {
namespace iter {
template <
typename T, typename I, typename F,
typename R=std::invoke_result_t<F, T &&>
>
class Map;
template <
typename T, typename I, typename F,
typename R=option_some_type<std::invoke_result_t<F, T &&>>
>
class MapWhile;
template <typename T, typename I, typename F>
class Filter;
template <
typename T, typename I, typename F,
typename R=option_some_type<std::invoke_result_t<F, T &&>>
>
class FilterMap;
template <typename T, typename I>
class Cycle;
template <typename T, typename I, typename J>
class Chain;
template <
typename T, typename I, typename S, typename F,
typename R=option_some_type<std::invoke_result_t<F, S *, T &&>>
>
class Scan;
template <typename T, typename I>
class Fuse;
template <typename T, typename U, typename I, typename J>
class Zip;
template <typename T, typename I>
class StepBy;
template <typename T>
class Empty;
template <typename T>
Empty<T> empty();
template <typename T>
class Once;
template <typename T>
Once<T> once(T &&t);
template <typename F, typename R=std::invoke_result_t<F>>
class OnceWith;
template <typename F>
decltype(auto) once_with(F &&f);
template <typename T>
class Repeat;
template <typename T>
Repeat<T> repeat(T &&t);
template <typename T>
Repeat<T> repeat(const T &t);
template <typename F, typename R=std::invoke_result_t<F>>
class RepeatWith;
template <typename F>
decltype(auto) repeat_with(F &&f);
template <typename T, typename F>
class Successors;
template <typename T, typename F>
Successors<T, F> successors(Option<T> &&init, F &&f);
} // namespace iter
template <typename I>
struct IteratorItem {
typedef decltype(((I*)nullptr)->next().unwrap()) type;
};
template <typename I>
using iterator_item = typename IteratorItem<I>::type;
} // namespace rstd
| 19.989362 | 67 | 0.718467 | agerasev |
9b2084954c4b4577cd80c2acc313d0b747ab1f93 | 6,190 | cpp | C++ | src/libtego/source/core/ContactsManager.cpp | blueprint-freespeech/r2-rebound | 65efe5bcea7c1222d0eef4ce447d3bebfee37779 | [
"BSD-3-Clause"
] | 1 | 2019-06-10T11:05:15.000Z | 2019-06-10T11:05:15.000Z | src/libtego/source/core/ContactsManager.cpp | blueprint-freespeech/r2-rebound | 65efe5bcea7c1222d0eef4ce447d3bebfee37779 | [
"BSD-3-Clause"
] | null | null | null | src/libtego/source/core/ContactsManager.cpp | blueprint-freespeech/r2-rebound | 65efe5bcea7c1222d0eef4ce447d3bebfee37779 | [
"BSD-3-Clause"
] | null | null | null | /* Ricochet - https://ricochet.im/
* Copyright (C) 2014, John Brooks <john.brooks@dereferenced.net>
*
* 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 names of the copyright owners 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.
*/
#include "ContactsManager.h"
#include "IncomingRequestManager.h"
#include "OutgoingContactRequest.h"
#include "ContactIDValidator.h"
#include "ConversationModel.h"
#include "protocol/ChatChannel.h"
ContactsManager *contactsManager = 0;
ContactsManager::ContactsManager(UserIdentity *id)
: identity(id), incomingRequests(this)
{
contactsManager = this;
}
// tego_user_type_allowed
void ContactsManager::addAllowedContacts(const QList<QString>& userHostnames)
{
for(const auto& hostname : userHostnames)
{
ContactUser *user = new ContactUser(identity, hostname, ContactUser::Offline, this);
connectSignals(user);
pContacts.append(user);
emit contactAdded(user);
}
}
// tego_user_type_requesting
void ContactsManager::addIncomingRequests(const QList<QString>& userHostnames)
{
this->incomingRequests.loadRequests(userHostnames);
}
// tego_user_type_blocked
void ContactsManager::addRejectedIncomingRequests(const QList<QString>& userHostnames)
{
for(const auto& hostname : userHostnames)
{
this->incomingRequests.addRejectedHost(hostname.toUtf8());
}
}
// tego_user_type_pending
void ContactsManager::addOutgoingRequests(const QList<QString>& userHostnames)
{
for(const auto& hostname : userHostnames)
{
this->createContactRequest(QString("ricochet:%1").arg(hostname), QString());
}
}
// tego_user_type_rejected
void ContactsManager::addRejectedOutgoingRequests(const QList<QString>& userHostnames)
{
for(const auto& hostname : userHostnames)
{
ContactUser *user = new ContactUser(identity, hostname, ContactUser::RequestRejected, this);
connect(user, SIGNAL(contactDeleted(ContactUser*)), SLOT(contactDeleted(ContactUser*)));
pContacts.append(user);
// emit contactAdded(user);
}
}
ContactUser *ContactsManager::addContact(const QString& hostname)
{
ContactUser *user = new ContactUser(identity, hostname);
user->setParent(this);
connectSignals(user);
qDebug() << "Added new contact" << hostname;
pContacts.append(user);
emit contactAdded(user);
return user;
}
void ContactsManager::connectSignals(ContactUser *user)
{
connect(user, SIGNAL(contactDeleted(ContactUser*)), SLOT(contactDeleted(ContactUser*)));
connect(user->conversation(), &ConversationModel::unreadCountChanged, this, &ContactsManager::onUnreadCountChanged);
connect(user, &ContactUser::statusChanged, [this,user]() { emit contactStatusChanged(user, user->status()); });
}
ContactUser *ContactsManager::createContactRequest(const QString &contactid, const QString &message)
{
logger::println("contactId : {}", contactid);
logger::println("message : {}", message);
QString hostname = ContactIDValidator::hostnameFromID(contactid);
if (hostname.isEmpty() || lookupHostname(contactid))
{
return 0;
}
bool b = blockSignals(true);
const auto contactHostname = ContactIDValidator::hostnameFromID(contactid);
ContactUser *user = addContact(contactHostname);
blockSignals(b);
if (!user)
return user;
user->setHostname(ContactIDValidator::hostnameFromID(contactid));
OutgoingContactRequest::createNewRequest(user, message);
/* Signal deferred from addContact to avoid changing the status immediately */
Q_ASSERT(user->status() == ContactUser::RequestPending);
emit contactAdded(user);
return user;
}
void ContactsManager::contactDeleted(ContactUser *user)
{
pContacts.removeOne(user);
}
ContactUser *ContactsManager::lookupHostname(const QString &hostname) const
{
QString ohost = ContactIDValidator::hostnameFromID(hostname);
if (ohost.isNull())
ohost = hostname;
if (!ohost.endsWith(QLatin1String(".onion")))
ohost.append(QLatin1String(".onion"));
for (QList<ContactUser*>::ConstIterator it = pContacts.begin(); it != pContacts.end(); ++it)
{
if (ohost.compare((*it)->hostname(), Qt::CaseInsensitive) == 0)
return *it;
}
return 0;
}
void ContactsManager::onUnreadCountChanged()
{
ConversationModel *model = qobject_cast<ConversationModel*>(sender());
Q_ASSERT(model);
if (!model)
return;
ContactUser *user = model->contact();
emit unreadCountChanged(user, model->unreadCount());
}
int ContactsManager::globalUnreadCount() const
{
int re = 0;
foreach (ContactUser *u, pContacts) {
if (u->conversation())
re += u->conversation()->unreadCount();
}
return re;
}
| 32.408377 | 120 | 0.718901 | blueprint-freespeech |
9b29736710c795d6ff7427b3acbe40f5573b344e | 180,019 | cpp | C++ | yocto/yocto_shape.cpp | erez-o/yocto-gl | b722ae746433369ec891a5cd5b1975953951c491 | [
"MIT"
] | 2 | 2020-10-16T06:05:27.000Z | 2021-03-31T03:58:56.000Z | yocto/yocto_shape.cpp | erez-o/yocto-gl | b722ae746433369ec891a5cd5b1975953951c491 | [
"MIT"
] | null | null | null | yocto/yocto_shape.cpp | erez-o/yocto-gl | b722ae746433369ec891a5cd5b1975953951c491 | [
"MIT"
] | null | null | null | //
// Implementation for Yocto/Shape
//
// -----------------------------------------------------------------------------
// INCLUDES
// -----------------------------------------------------------------------------
#include "yocto_shape.h"
#include "ext/happly.h"
#include "yocto_obj.h"
#include "yocto_random.h"
#include <deque>
#include "ext/filesystem.hpp"
namespace fs = ghc::filesystem;
// -----------------------------------------------------------------------------
// IMPLEMENTATION OF COMPUTATION OF PER_VERTEX PROPETIES
// -----------------------------------------------------------------------------
namespace yocto {
// Compute per-vertex tangents for lines.
void compute_tangents(vector<vec3f>& tangents, const vector<vec2i>& lines,
const vector<vec3f>& positions) {
if (tangents.size() != positions.size()) {
throw std::out_of_range("array should be the same length");
}
for (auto& tangent : tangents) tangent = zero3f;
for (auto& l : lines) {
auto tangent = line_tangent(positions[l.x], positions[l.y]);
auto length = line_length(positions[l.x], positions[l.y]);
tangents[l.x] += tangent * length;
tangents[l.y] += tangent * length;
}
for (auto& tangent : tangents) tangent = normalize(tangent);
}
// Compute per-vertex normals for triangles.
void compute_normals(vector<vec3f>& normals, const vector<vec3i>& triangles,
const vector<vec3f>& positions) {
if (normals.size() != positions.size()) {
throw std::out_of_range("array should be the same length");
}
for (auto& normal : normals) normal = zero3f;
for (auto& t : triangles) {
auto normal = triangle_normal(
positions[t.x], positions[t.y], positions[t.z]);
auto area = triangle_area(positions[t.x], positions[t.y], positions[t.z]);
normals[t.x] += normal * area;
normals[t.y] += normal * area;
normals[t.z] += normal * area;
}
for (auto& normal : normals) normal = normalize(normal);
}
// Compute per-vertex normals for quads.
void compute_normals(vector<vec3f>& normals, const vector<vec4i>& quads,
const vector<vec3f>& positions) {
if (normals.size() != positions.size()) {
throw std::out_of_range("array should be the same length");
}
for (auto& normal : normals) normal = zero3f;
for (auto& q : quads) {
auto normal = quad_normal(
positions[q.x], positions[q.y], positions[q.z], positions[q.w]);
auto area = quad_area(
positions[q.x], positions[q.y], positions[q.z], positions[q.w]);
normals[q.x] += normal * area;
normals[q.y] += normal * area;
normals[q.z] += normal * area;
if (q.z != q.w) normals[q.w] += normal * area;
}
for (auto& normal : normals) normal = normalize(normal);
}
// Shortcuts
vector<vec3f> compute_tangents(
const vector<vec2i>& lines, const vector<vec3f>& positions) {
auto tangents = vector<vec3f>{positions.size()};
compute_tangents(tangents, lines, positions);
return tangents;
}
vector<vec3f> compute_normals(
const vector<vec3i>& triangles, const vector<vec3f>& positions) {
auto normals = vector<vec3f>{positions.size()};
compute_normals(normals, triangles, positions);
return normals;
}
vector<vec3f> compute_normals(
const vector<vec4i>& quads, const vector<vec3f>& positions) {
auto normals = vector<vec3f>{positions.size()};
compute_normals(normals, quads, positions);
return normals;
}
// Compute per-vertex tangent frame for triangle meshes.
// Tangent space is defined by a four component vector.
// The first three components are the tangent with respect to the U texcoord.
// The fourth component is the sign of the tangent wrt the V texcoord.
// Tangent frame is useful in normal mapping.
void compute_tangent_spaces(vector<vec4f>& tangent_spaces,
const vector<vec3i>& triangles, const vector<vec3f>& positions,
const vector<vec3f>& normals, const vector<vec2f>& texcoords) {
auto tangu = vector<vec3f>(positions.size(), zero3f);
auto tangv = vector<vec3f>(positions.size(), zero3f);
for (auto t : triangles) {
auto tutv = triangle_tangents_fromuv(positions[t.x], positions[t.y],
positions[t.z], texcoords[t.x], texcoords[t.y], texcoords[t.z]);
for (auto vid : {t.x, t.y, t.z}) tangu[vid] += normalize(tutv.first);
for (auto vid : {t.x, t.y, t.z}) tangv[vid] += normalize(tutv.second);
}
for (auto& t : tangu) t = normalize(t);
for (auto& t : tangv) t = normalize(t);
for (auto& tangent : tangent_spaces) tangent = zero4f;
for (auto i = 0; i < positions.size(); i++) {
tangu[i] = orthonormalize(tangu[i], normals[i]);
auto s = (dot(cross(normals[i], tangu[i]), tangv[i]) < 0) ? -1.0f : 1.0f;
tangent_spaces[i] = {tangu[i].x, tangu[i].y, tangu[i].z, s};
}
}
vector<vec4f> compute_tangent_spaces(const vector<vec3i>& triangles,
const vector<vec3f>& positions, const vector<vec3f>& normals,
const vector<vec2f>& texcoords) {
auto tangent_spaces = vector<vec4f>(positions.size());
compute_tangent_spaces(
tangent_spaces, triangles, positions, normals, texcoords);
return tangent_spaces;
}
// Apply skinning
void compute_skinning(vector<vec3f>& skinned_positions,
vector<vec3f>& skinned_normals, const vector<vec3f>& positions,
const vector<vec3f>& normals, const vector<vec4f>& weights,
const vector<vec4i>& joints, const vector<frame3f>& xforms) {
if (skinned_positions.size() != positions.size() ||
skinned_normals.size() != normals.size()) {
throw std::out_of_range("arrays should be the same size");
}
for (auto i = 0; i < positions.size(); i++) {
skinned_positions[i] =
transform_point(xforms[joints[i].x], positions[i]) * weights[i].x +
transform_point(xforms[joints[i].y], positions[i]) * weights[i].y +
transform_point(xforms[joints[i].z], positions[i]) * weights[i].z +
transform_point(xforms[joints[i].w], positions[i]) * weights[i].w;
}
for (auto i = 0; i < normals.size(); i++) {
skinned_normals[i] = normalize(
transform_direction(xforms[joints[i].x], normals[i]) * weights[i].x +
transform_direction(xforms[joints[i].y], normals[i]) * weights[i].y +
transform_direction(xforms[joints[i].z], normals[i]) * weights[i].z +
transform_direction(xforms[joints[i].w], normals[i]) * weights[i].w);
}
}
pair<vector<vec3f>, vector<vec3f>> compute_skinning(
const vector<vec3f>& positions, const vector<vec3f>& normals,
const vector<vec4f>& weights, const vector<vec4i>& joints,
const vector<frame3f>& xforms) {
auto skinned = pair<vector<vec3f>, vector<vec3f>>{
vector<vec3f>{positions.size()}, vector<vec3f>{normals.size()}};
compute_skinning(skinned.first, skinned.second, positions, normals, weights,
joints, xforms);
return skinned;
}
// Apply skinning as specified in Khronos glTF
void compute_matrix_skinning(vector<vec3f>& skinned_positions,
vector<vec3f>& skinned_normals, const vector<vec3f>& positions,
const vector<vec3f>& normals, const vector<vec4f>& weights,
const vector<vec4i>& joints, const vector<mat4f>& xforms) {
if (skinned_positions.size() != positions.size() ||
skinned_normals.size() != normals.size()) {
throw std::out_of_range("arrays should be the same size");
}
for (auto i = 0; i < positions.size(); i++) {
auto xform = xforms[joints[i].x] * weights[i].x +
xforms[joints[i].y] * weights[i].y +
xforms[joints[i].z] * weights[i].z +
xforms[joints[i].w] * weights[i].w;
skinned_positions[i] = transform_point(xform, positions[i]);
skinned_normals[i] = normalize(transform_direction(xform, normals[i]));
}
}
pair<vector<vec3f>, vector<vec3f>> compute_matrix_skinning(
const vector<vec3f>& positions, const vector<vec3f>& normals,
const vector<vec4f>& weights, const vector<vec4i>& joints,
const vector<mat4f>& xforms) {
auto skinned = pair<vector<vec3f>, vector<vec3f>>{
vector<vec3f>{positions.size()}, vector<vec3f>{normals.size()}};
compute_matrix_skinning(skinned.first, skinned.second, positions, normals,
weights, joints, xforms);
return skinned;
}
} // namespace yocto
// -----------------------------------------------------------------------------
// COMPUTATION OF PER_VERTEX PROPETIES
// -----------------------------------------------------------------------------
namespace yocto {
// Flip vertex normals
void flip_normals(vector<vec3f>& flipped, const vector<vec3f>& normals) {
flipped = normals;
for (auto& n : flipped) n = -n;
}
vector<vec3f> flip_normals(const vector<vec3f>& normals) {
auto flipped = normals;
for (auto& n : flipped) n = -n;
return flipped;
}
// Flip face orientation
void flip_triangles(vector<vec3i>& flipped, const vector<vec3i>& triangles) {
flipped = triangles;
for (auto& t : flipped) swap(t.y, t.z);
}
vector<vec3i> flip_triangles(const vector<vec3i>& triangles) {
auto flipped = triangles;
for (auto& t : flipped) swap(t.y, t.z);
return flipped;
}
void flip_quads(vector<vec4i>& flipped, const vector<vec4i>& quads) {
flipped = quads;
for (auto& q : flipped) {
if (q.z != q.w) {
swap(q.y, q.w);
} else {
swap(q.y, q.z);
q.w = q.z;
}
}
}
vector<vec4i> flip_quads(const vector<vec4i>& quads) {
auto flipped = quads;
for (auto& q : flipped) {
if (q.z != q.w) {
swap(q.y, q.w);
} else {
swap(q.y, q.z);
q.w = q.z;
}
}
return flipped;
}
// Align vertex positions. Alignment is 0: none, 1: min, 2: max, 3: center.
void align_vertices(vector<vec3f>& aligned, const vector<vec3f>& positions,
const vec3i& alignment) {
auto bounds = invalidb3f;
for (auto& p : positions) bounds = merge(bounds, p);
auto offset = vec3f{0, 0, 0};
switch (alignment.x) {
case 1: offset.x = bounds.min.x; break;
case 2: offset.x = (bounds.min.x + bounds.max.x) / 2; break;
case 3: offset.x = bounds.max.x; break;
}
switch (alignment.y) {
case 1: offset.y = bounds.min.y; break;
case 2: offset.y = (bounds.min.y + bounds.max.y) / 2; break;
case 3: offset.y = bounds.max.y; break;
}
switch (alignment.z) {
case 1: offset.z = bounds.min.z; break;
case 2: offset.z = (bounds.min.z + bounds.max.z) / 2; break;
case 3: offset.z = bounds.max.z; break;
}
aligned = positions;
for (auto& p : aligned) p -= offset;
}
vector<vec3f> align_vertices(
const vector<vec3f>& positions, const vec3i& alignment) {
auto aligned = vector<vec3f>(positions.size());
align_vertices(aligned, positions, alignment);
return aligned;
}
} // namespace yocto
// -----------------------------------------------------------------------------
// IMPLEMENTATION OF EDGE AND GRID DATA STRUCTURES
// -----------------------------------------------------------------------------
namespace yocto {
// Initialize an edge map with elements.
edge_map make_edge_map(const vector<vec3i>& triangles) {
auto emap = edge_map{};
for (auto& t : triangles) {
insert_edge(emap, {t.x, t.y});
insert_edge(emap, {t.y, t.z});
insert_edge(emap, {t.z, t.x});
}
return emap;
}
edge_map make_edge_map(const vector<vec4i>& quads) {
auto emap = edge_map{};
for (auto& q : quads) {
insert_edge(emap, {q.x, q.y});
insert_edge(emap, {q.y, q.z});
if (q.z != q.w) insert_edge(emap, {q.z, q.w});
insert_edge(emap, {q.w, q.x});
}
return emap;
}
void insert_edges(edge_map& emap, const vector<vec3i>& triangles) {
for (auto& t : triangles) {
insert_edge(emap, {t.x, t.y});
insert_edge(emap, {t.y, t.z});
insert_edge(emap, {t.z, t.x});
}
}
void insert_edges(edge_map& emap, const vector<vec4i>& quads) {
for (auto& q : quads) {
insert_edge(emap, {q.x, q.y});
insert_edge(emap, {q.y, q.z});
if (q.z != q.w) insert_edge(emap, {q.z, q.w});
insert_edge(emap, {q.w, q.x});
}
}
// Insert an edge and return its index
int insert_edge(edge_map& emap, const vec2i& edge) {
auto es = edge.x < edge.y ? edge : vec2i{edge.y, edge.x};
auto it = emap.index.find(es);
if (it == emap.index.end()) {
auto idx = (int)emap.edges.size();
emap.index.insert(it, {es, idx});
emap.edges.push_back(es);
emap.nfaces.push_back(1);
return idx;
} else {
auto idx = it->second;
emap.nfaces[idx] += 1;
return idx;
}
}
// Get number of edges
int num_edges(const edge_map& emap) { return emap.edges.size(); }
// Get the edge index
int edge_index(const edge_map& emap, const vec2i& edge) {
auto es = edge.x < edge.y ? edge : vec2i{edge.y, edge.x};
auto iterator = emap.index.find(es);
if (iterator == emap.index.end()) return -1;
return iterator->second;
}
// Get a list of edges, boundary edges, boundary vertices
vector<vec2i> get_edges(const edge_map& emap) { return emap.edges; }
vector<vec2i> get_boundary(const edge_map& emap) {
auto boundary = vector<vec2i>{};
for (auto idx = 0; idx < emap.edges.size(); idx++) {
if (emap.nfaces[idx] < 2) boundary.push_back(emap.edges[idx]);
}
return boundary;
}
void get_edges(const edge_map& emap, vector<vec2i>& edges) {
edges = emap.edges;
}
void get_boundary(const edge_map& emap, vector<vec2i>& boundary) {
boundary.clear();
for (auto idx = 0; idx < emap.edges.size(); idx++) {
if (emap.nfaces[idx] < 2) boundary.push_back(emap.edges[idx]);
}
}
vector<vec2i> get_edges(const vector<vec3i>& triangles) {
return get_edges(make_edge_map(triangles));
}
vector<vec2i> get_edges(const vector<vec4i>& quads) {
return get_edges(make_edge_map(quads));
}
// Gets the cell index
vec3i get_cell_index(const hash_grid& grid, const vec3f& position) {
auto scaledpos = position * grid.cell_inv_size;
return vec3i{(int)scaledpos.x, (int)scaledpos.y, (int)scaledpos.z};
}
// Create a hash_grid
hash_grid make_hash_grid(float cell_size) {
auto grid = hash_grid{};
grid.cell_size = cell_size;
grid.cell_inv_size = 1 / cell_size;
return grid;
}
hash_grid make_hash_grid(const vector<vec3f>& positions, float cell_size) {
auto grid = hash_grid{};
grid.cell_size = cell_size;
grid.cell_inv_size = 1 / cell_size;
for (auto& position : positions) insert_vertex(grid, position);
return grid;
}
// Inserts a point into the grid
int insert_vertex(hash_grid& grid, const vec3f& position) {
auto vertex_id = (int)grid.positions.size();
auto cell = get_cell_index(grid, position);
grid.cells[cell].push_back(vertex_id);
grid.positions.push_back(position);
return vertex_id;
}
// Finds the nearest neighboors within a given radius
void find_neightbors(const hash_grid& grid, vector<int>& neighboors,
const vec3f& position, float max_radius, int skip_id) {
auto cell = get_cell_index(grid, position);
auto cell_radius = (int)(max_radius * grid.cell_inv_size) + 1;
neighboors.clear();
auto max_radius_squared = max_radius * max_radius;
for (auto k = -cell_radius; k <= cell_radius; k++) {
for (auto j = -cell_radius; j <= cell_radius; j++) {
for (auto i = -cell_radius; i <= cell_radius; i++) {
auto ncell = cell + vec3i{i, j, k};
auto cell_iterator = grid.cells.find(ncell);
if (cell_iterator == grid.cells.end()) continue;
auto& ncell_vertices = cell_iterator->second;
for (auto vertex_id : ncell_vertices) {
if (distance_squared(grid.positions[vertex_id], position) >
max_radius_squared)
continue;
if (vertex_id == skip_id) continue;
neighboors.push_back(vertex_id);
}
}
}
}
}
void find_neightbors(const hash_grid& grid, vector<int>& neighboors,
const vec3f& position, float max_radius) {
find_neightbors(grid, neighboors, position, max_radius, -1);
}
void find_neightbors(const hash_grid& grid, vector<int>& neighboors, int vertex,
float max_radius) {
find_neightbors(grid, neighboors, grid.positions[vertex], max_radius, vertex);
}
} // namespace yocto
// -----------------------------------------------------------------------------
// IMPLEMENTATION OF SHAPE ELEMENT CONVERSION AND GROUPING
// -----------------------------------------------------------------------------
namespace yocto {
// Convert quads to triangles
vector<vec3i> quads_to_triangles(const vector<vec4i>& quads) {
auto triangles = vector<vec3i>{};
triangles.reserve(quads.size() * 2);
for (auto& q : quads) {
triangles.push_back({q.x, q.y, q.w});
if (q.z != q.w) triangles.push_back({q.z, q.w, q.y});
}
return triangles;
}
void quads_to_triangles(vector<vec3i>& triangles, const vector<vec4i>& quads) {
triangles.clear();
triangles.reserve(quads.size() * 2);
for (auto& q : quads) {
triangles.push_back({q.x, q.y, q.w});
if (q.z != q.w) triangles.push_back({q.z, q.w, q.y});
}
}
// Convert triangles to quads by creating degenerate quads
vector<vec4i> triangles_to_quads(const vector<vec3i>& triangles) {
auto quads = vector<vec4i>{};
quads.reserve(triangles.size());
for (auto& t : triangles) quads.push_back({t.x, t.y, t.z, t.z});
return quads;
}
void triangles_to_quads(vector<vec4i>& quads, const vector<vec3i>& triangles) {
quads.clear();
quads.reserve(triangles.size());
for (auto& t : triangles) quads.push_back({t.x, t.y, t.z, t.z});
}
// Convert beziers to lines using 3 lines for each bezier.
vector<vec2i> bezier_to_lines(const vector<vec4i>& beziers) {
auto lines = vector<vec2i>{};
lines.reserve(beziers.size() * 3);
for (auto b : beziers) {
lines.push_back({b.x, b.y});
lines.push_back({b.y, b.z});
lines.push_back({b.z, b.w});
}
return lines;
}
void bezier_to_lines(vector<vec2i>& lines, const vector<vec4i>& beziers) {
lines.clear();
lines.reserve(beziers.size() * 3);
for (auto b : beziers) {
lines.push_back({b.x, b.y});
lines.push_back({b.y, b.z});
lines.push_back({b.z, b.w});
}
}
// Convert face varying data to single primitives. Returns the quads indices
// and filled vectors for pos, norm and texcoord.
void split_facevarying(vector<vec4i>& split_quads,
vector<vec3f>& split_positions, vector<vec3f>& split_normals,
vector<vec2f>& split_texcoords, const vector<vec4i>& quadspos,
const vector<vec4i>& quadsnorm, const vector<vec4i>& quadstexcoord,
const vector<vec3f>& positions, const vector<vec3f>& normals,
const vector<vec2f>& texcoords) {
// make faces unique
unordered_map<vec3i, int> vert_map;
split_quads.resize(quadspos.size());
for (auto fid = 0; fid < quadspos.size(); fid++) {
for (auto c = 0; c < 4; c++) {
auto v = vec3i{
(&quadspos[fid].x)[c],
(!quadsnorm.empty()) ? (&quadsnorm[fid].x)[c] : -1,
(!quadstexcoord.empty()) ? (&quadstexcoord[fid].x)[c] : -1,
};
auto it = vert_map.find(v);
if (it == vert_map.end()) {
auto s = (int)vert_map.size();
vert_map.insert(it, {v, s});
(&split_quads[fid].x)[c] = s;
} else {
(&split_quads[fid].x)[c] = it->second;
}
}
}
// fill vert data
split_positions.clear();
if (!positions.empty()) {
split_positions.resize(vert_map.size());
for (auto& [vert, index] : vert_map) {
split_positions[index] = positions[vert.x];
}
}
split_normals.clear();
if (!normals.empty()) {
split_normals.resize(vert_map.size());
for (auto& [vert, index] : vert_map) {
split_normals[index] = normals[vert.y];
}
}
split_texcoords.clear();
if (!texcoords.empty()) {
split_texcoords.resize(vert_map.size());
for (auto& [vert, index] : vert_map) {
split_texcoords[index] = texcoords[vert.z];
}
}
}
// Split primitives per id
template <typename T>
vector<vector<T>> ungroup_elems_impl(
const vector<T>& elems, const vector<int>& ids) {
auto max_id = *max_element(ids.begin(), ids.end());
auto split_elems = vector<vector<T>>(max_id + 1);
for (auto elem_id = 0; elem_id < elems.size(); elem_id++) {
split_elems[ids[elem_id]].push_back(elems[elem_id]);
}
return split_elems;
}
vector<vector<vec2i>> ungroup_lines(
const vector<vec2i>& lines, const vector<int>& ids) {
return ungroup_elems_impl(lines, ids);
}
vector<vector<vec3i>> ungroup_triangles(
const vector<vec3i>& triangles, const vector<int>& ids) {
return ungroup_elems_impl(triangles, ids);
}
vector<vector<vec4i>> ungroup_quads(
const vector<vec4i>& quads, const vector<int>& ids) {
return ungroup_elems_impl(quads, ids);
}
template <typename T>
void ungroup_elems_impl(vector<vector<T>>& split_elems, const vector<T>& elems,
const vector<int>& ids) {
auto max_id = *max_element(ids.begin(), ids.end());
split_elems.resize(max_id + 1);
for (auto elem_id = 0; elem_id < elems.size(); elem_id++) {
split_elems[ids[elem_id]].push_back(elems[elem_id]);
}
}
void ungroup_lines(vector<vector<vec2i>>& split_lines,
const vector<vec2i>& lines, const vector<int>& ids) {
ungroup_elems_impl(split_lines, lines, ids);
}
void ungroup_triangles(vector<vector<vec3i>>& split_triangles,
const vector<vec3i>& triangles, const vector<int>& ids) {
ungroup_elems_impl(split_triangles, triangles, ids);
}
void ungroup_quads(vector<vector<vec4i>>& split_quads,
const vector<vec4i>& quads, const vector<int>& ids) {
ungroup_elems_impl(split_quads, quads, ids);
}
// Weld vertices within a threshold.
pair<vector<vec3f>, vector<int>> weld_vertices(
const vector<vec3f>& positions, float threshold) {
auto indices = vector<int>(positions.size());
auto welded = vector<vec3f>{};
auto grid = make_hash_grid(threshold);
auto neighboors = vector<int>{};
for (auto vertex = 0; vertex < positions.size(); vertex++) {
auto& position = positions[vertex];
find_neightbors(grid, neighboors, position, threshold);
if (neighboors.empty()) {
welded.push_back(position);
indices[vertex] = (int)welded.size() - 1;
insert_vertex(grid, position);
} else {
indices[vertex] = neighboors.front();
}
}
return {welded, indices};
}
pair<vector<vec3i>, vector<vec3f>> weld_triangles(
const vector<vec3i>& triangles, const vector<vec3f>& positions,
float threshold) {
auto [wpositions, indices] = weld_vertices(positions, threshold);
auto wtriangles = triangles;
for (auto& t : wtriangles) t = {indices[t.x], indices[t.y], indices[t.z]};
return {wtriangles, wpositions};
}
pair<vector<vec4i>, vector<vec3f>> weld_quads(const vector<vec4i>& quads,
const vector<vec3f>& positions, float threshold) {
auto [wpositions, indices] = weld_vertices(positions, threshold);
auto wquads = quads;
for (auto& q : wquads)
q = {
indices[q.x],
indices[q.y],
indices[q.z],
indices[q.w],
};
return {wquads, wpositions};
}
void weld_vertices(vector<vec3f>& wpositions, vector<int>& indices,
const vector<vec3f>& positions, float threshold) {
indices.resize(positions.size());
wpositions.clear();
auto grid = make_hash_grid(threshold);
auto neighboors = vector<int>{};
for (auto vertex = 0; vertex < positions.size(); vertex++) {
auto& position = positions[vertex];
find_neightbors(grid, neighboors, position, threshold);
if (neighboors.empty()) {
wpositions.push_back(position);
indices[vertex] = (int)wpositions.size() - 1;
insert_vertex(grid, position);
} else {
indices[vertex] = neighboors.front();
}
}
}
void weld_triangles_inplace(vector<vec3i>& wtriangles,
vector<vec3f>& wpositions, const vector<vec3i>& triangles,
const vector<vec3f>& positions, float threshold) {
auto indices = vector<int>{};
weld_vertices(wpositions, indices, positions, threshold);
wtriangles = triangles;
for (auto& t : wtriangles) t = {indices[t.x], indices[t.y], indices[t.z]};
}
void weld_quads_inplace(vector<vec4i>& wquads, vector<vec3f>& wpositions,
const vector<vec4i>& quads, const vector<vec3f>& positions,
float threshold) {
auto indices = vector<int>{};
weld_vertices(wpositions, indices, positions, threshold);
wquads = quads;
for (auto& q : wquads)
q = {
indices[q.x],
indices[q.y],
indices[q.z],
indices[q.w],
};
}
// Merge shape elements
void merge_lines(
vector<vec2i>& lines, const vector<vec2i>& merge_lines, int num_verts) {
for (auto& l : merge_lines)
lines.push_back({l.x + num_verts, l.y + num_verts});
}
void merge_triangles(vector<vec3i>& triangles,
const vector<vec3i>& merge_triangles, int num_verts) {
for (auto& t : merge_triangles)
triangles.push_back({t.x + num_verts, t.y + num_verts, t.z + num_verts});
}
void merge_quads(
vector<vec4i>& quads, const vector<vec4i>& merge_quads, int num_verts) {
for (auto& q : merge_quads)
quads.push_back(
{q.x + num_verts, q.y + num_verts, q.z + num_verts, q.w + num_verts});
}
void merge_lines(vector<vec2i>& lines, vector<vec3f>& positions,
vector<vec3f>& tangents, vector<vec2f>& texcoords, vector<float>& radius,
const vector<vec2i>& merge_lines, const vector<vec3f>& merge_positions,
const vector<vec3f>& merge_tangents,
const vector<vec2f>& merge_texturecoords,
const vector<float>& merge_radius) {
auto merge_verts = (int)positions.size();
for (auto& l : merge_lines)
lines.push_back({l.x + merge_verts, l.y + merge_verts});
positions.insert(
positions.end(), merge_positions.begin(), merge_positions.end());
tangents.insert(tangents.end(), merge_tangents.begin(), merge_tangents.end());
texcoords.insert(
texcoords.end(), merge_texturecoords.begin(), merge_texturecoords.end());
radius.insert(radius.end(), merge_radius.begin(), merge_radius.end());
}
void merge_triangles(vector<vec3i>& triangles, vector<vec3f>& positions,
vector<vec3f>& normals, vector<vec2f>& texcoords,
const vector<vec3i>& merge_triangles, const vector<vec3f>& merge_positions,
const vector<vec3f>& merge_normals,
const vector<vec2f>& merge_texturecoords) {
auto merge_verts = (int)positions.size();
for (auto& t : merge_triangles)
triangles.push_back(
{t.x + merge_verts, t.y + merge_verts, t.z + merge_verts});
positions.insert(
positions.end(), merge_positions.begin(), merge_positions.end());
normals.insert(normals.end(), merge_normals.begin(), merge_normals.end());
texcoords.insert(
texcoords.end(), merge_texturecoords.begin(), merge_texturecoords.end());
}
void merge_quads(vector<vec4i>& quads, vector<vec3f>& positions,
vector<vec3f>& normals, vector<vec2f>& texcoords,
const vector<vec4i>& merge_quads, const vector<vec3f>& merge_positions,
const vector<vec3f>& merge_normals,
const vector<vec2f>& merge_texturecoords) {
auto merge_verts = (int)positions.size();
for (auto& q : merge_quads)
quads.push_back({q.x + merge_verts, q.y + merge_verts, q.z + merge_verts,
q.w + merge_verts});
positions.insert(
positions.end(), merge_positions.begin(), merge_positions.end());
normals.insert(normals.end(), merge_normals.begin(), merge_normals.end());
texcoords.insert(
texcoords.end(), merge_texturecoords.begin(), merge_texturecoords.end());
}
void merge_triangles_and_quads(
vector<vec3i>& triangles, vector<vec4i>& quads, bool force_triangles) {
if (quads.empty()) return;
if (force_triangles) {
auto qtriangles = quads_to_triangles(quads);
triangles.insert(triangles.end(), qtriangles.begin(), qtriangles.end());
quads = {};
} else {
auto tquads = triangles_to_quads(triangles);
quads.insert(quads.end(), tquads.begin(), tquads.end());
triangles = {};
}
}
} // namespace yocto
// -----------------------------------------------------------------------------
// IMPLEMENTATION OF SHAPE SUBDIVISION
// -----------------------------------------------------------------------------
namespace yocto {
// Subdivide lines.
template <typename T>
void subdivide_lines_impl(vector<vec2i>& lines, vector<T>& vert,
const vector<vec2i>& lines_, const vector<T>& vert_, int level) {
// initialization
lines = lines_;
vert = vert_;
// early exit
if (lines.empty() || vert.empty()) return;
// loop over levels
for (auto l = 0; l < level; l++) {
// sizes
auto nverts = (int)vert.size();
auto nlines = (int)lines.size();
// create vertices
auto tvert = vector<T>(nverts + nlines);
for (auto i = 0; i < nverts; i++) tvert[i] = vert[i];
for (auto i = 0; i < nlines; i++) {
auto l = lines[i];
tvert[nverts + i] = (vert[l.x] + vert[l.y]) / 2;
}
// create lines
auto tlines = vector<vec2i>(nlines * 2);
for (auto i = 0; i < nlines; i++) {
auto l = lines[i];
tlines[i * 2 + 0] = {l.x, nverts + i};
tlines[i * 2 + 0] = {nverts + i, l.y};
}
swap(tlines, lines);
swap(tvert, vert);
}
}
template <typename T>
pair<vector<vec2i>, vector<T>> subdivide_lines_impl(
const vector<vec2i>& lines, const vector<T>& vert, int level) {
auto tess = pair<vector<vec2i>, vector<T>>{};
subdivide_lines_impl(tess.first, tess.second, lines, vert, level);
return tess;
}
// Subdivide triangle.
template <typename T>
void subdivide_triangles_impl(vector<vec3i>& triangles, vector<T>& vert,
const vector<vec3i>& triangles_, const vector<T>& vert_, int level) {
// initialization
triangles = triangles_;
vert = vert_;
// early exit
if (triangles.empty() || vert.empty()) return;
// loop over levels
for (auto l = 0; l < level; l++) {
// get edges
auto emap = make_edge_map(triangles);
auto edges = get_edges(emap);
// number of elements
auto nverts = (int)vert.size();
auto nedges = (int)edges.size();
auto nfaces = (int)triangles.size();
// create vertices
auto tvert = vector<T>(nverts + nedges);
for (auto i = 0; i < nverts; i++) tvert[i] = vert[i];
for (auto i = 0; i < nedges; i++) {
auto e = edges[i];
tvert[nverts + i] = (vert[e.x] + vert[e.y]) / 2;
}
// create triangles
auto ttriangles = vector<vec3i>(nfaces * 4);
for (auto i = 0; i < nfaces; i++) {
auto t = triangles[i];
ttriangles[i * 4 + 0] = {t.x, nverts + edge_index(emap, {t.x, t.y}),
nverts + edge_index(emap, {t.z, t.x})};
ttriangles[i * 4 + 1] = {t.y, nverts + edge_index(emap, {t.y, t.z}),
nverts + edge_index(emap, {t.x, t.y})};
ttriangles[i * 4 + 2] = {t.z, nverts + edge_index(emap, {t.z, t.x}),
nverts + edge_index(emap, {t.y, t.z})};
ttriangles[i * 4 + 3] = {nverts + edge_index(emap, {t.x, t.y}),
nverts + edge_index(emap, {t.y, t.z}),
nverts + edge_index(emap, {t.z, t.x})};
}
swap(ttriangles, triangles);
swap(tvert, vert);
}
}
template <typename T>
pair<vector<vec3i>, vector<T>> subdivide_triangles_impl(
const vector<vec3i>& triangles, const vector<T>& vert, int level) {
auto tess = pair<vector<vec3i>, vector<T>>{};
subdivide_triangles_impl(tess.first, tess.second, triangles, vert, level);
return tess;
}
// Subdivide quads.
template <typename T>
void subdivide_quads_impl(vector<vec4i>& quads, vector<T>& vert,
const vector<vec4i>& quads_, const vector<T>& vert_, int level) {
// initialization
quads = quads_;
vert = vert_;
// early exit
if (quads.empty() || vert.empty()) return;
// loop over levels
for (auto l = 0; l < level; l++) {
// get edges
auto emap = make_edge_map(quads);
auto edges = get_edges(emap);
// number of elements
auto nverts = (int)vert.size();
auto nedges = (int)edges.size();
auto nfaces = (int)quads.size();
// create vertices
auto tvert = vector<T>(nverts + nedges + nfaces);
for (auto i = 0; i < nverts; i++) tvert[i] = vert[i];
for (auto i = 0; i < nedges; i++) {
auto e = edges[i];
tvert[nverts + i] = (vert[e.x] + vert[e.y]) / 2;
}
for (auto i = 0; i < nfaces; i++) {
auto q = quads[i];
if (q.z != q.w) {
tvert[nverts + nedges + i] =
(vert[q.x] + vert[q.y] + vert[q.z] + vert[q.w]) / 4;
} else {
tvert[nverts + nedges + i] = (vert[q.x] + vert[q.y] + vert[q.y]) / 3;
}
}
// create quads
auto tquads = vector<vec4i>(nfaces * 4); // conservative allocation
auto qi = 0;
for (auto i = 0; i < nfaces; i++) {
auto q = quads[i];
if (q.z != q.w) {
tquads[qi++] = {q.x, nverts + edge_index(emap, {q.x, q.y}),
nverts + nedges + i, nverts + edge_index(emap, {q.w, q.x})};
tquads[qi++] = {q.y, nverts + edge_index(emap, {q.y, q.z}),
nverts + nedges + i, nverts + edge_index(emap, {q.x, q.y})};
tquads[qi++] = {q.z, nverts + edge_index(emap, {q.z, q.w}),
nverts + nedges + i, nverts + edge_index(emap, {q.y, q.z})};
tquads[qi++] = {q.w, nverts + edge_index(emap, {q.w, q.x}),
nverts + nedges + i, nverts + edge_index(emap, {q.z, q.w})};
} else {
tquads[qi++] = {q.x, nverts + edge_index(emap, {q.x, q.y}),
nverts + nedges + i, nverts + edge_index(emap, {q.z, q.x})};
tquads[qi++] = {q.y, nverts + edge_index(emap, {q.y, q.z}),
nverts + nedges + i, nverts + edge_index(emap, {q.x, q.y})};
tquads[qi++] = {q.z, nverts + edge_index(emap, {q.z, q.x}),
nverts + nedges + i, nverts + edge_index(emap, {q.y, q.z})};
}
}
tquads.resize(qi);
// done
swap(tquads, quads);
swap(tvert, vert);
}
}
template <typename T>
pair<vector<vec4i>, vector<T>> subdivide_quads_impl(
const vector<vec4i>& quads, const vector<T>& vert, int level) {
auto tess = pair<vector<vec4i>, vector<T>>{};
subdivide_quads_impl(tess.first, tess.second, quads, vert, level);
return tess;
}
// Subdivide beziers.
template <typename T>
void subdivide_beziers_impl(vector<vec4i>& beziers, vector<T>& vert,
const vector<vec4i>& beziers_, const vector<T>& vert_, int level) {
// initialization
beziers = beziers_;
vert = vert_;
// early exit
if (beziers.empty() || vert.empty()) return;
// loop over levels
for (auto l = 0; l < level; l++) {
// get edges
auto vmap = unordered_map<int, int>();
auto tvert = vector<T>();
auto tbeziers = vector<vec4i>();
for (auto b : beziers) {
if (vmap.find(b.x) == vmap.end()) {
vmap[b.x] = (int)tvert.size();
tvert.push_back(vert[b.x]);
}
if (vmap.find(b.w) == vmap.end()) {
vmap[b.w] = (int)tvert.size();
tvert.push_back(vert[b.w]);
}
auto bo = (int)tvert.size();
tbeziers.push_back({vmap.at(b.x), bo + 0, bo + 1, bo + 2});
tbeziers.push_back({bo + 2, bo + 3, bo + 4, vmap.at(b.w)});
tvert.push_back(vert[b.x] / 2 + vert[b.y] / 2);
tvert.push_back(vert[b.x] / 4 + vert[b.y] / 2 + vert[b.z] / 4);
tvert.push_back(vert[b.x] / 8 + vert[b.y] * ((float)3 / (float)8) +
vert[b.z] * ((float)3 / (float)8) + vert[b.w] / 8);
tvert.push_back(vert[b.y] / 4 + vert[b.z] / 2 + vert[b.w] / 4);
tvert.push_back(vert[b.z] / 2 + vert[b.w] / 2);
}
// done
swap(tbeziers, beziers);
swap(tvert, vert);
}
}
template <typename T>
pair<vector<vec4i>, vector<T>> subdivide_beziers_impl(
const vector<vec4i>& beziers, const vector<T>& vert, int level) {
auto tess = pair<vector<vec4i>, vector<T>>{};
subdivide_beziers_impl(tess.first, tess.second, beziers, vert, level);
return tess;
}
// Subdivide catmullclark.
template <typename T>
void subdivide_catmullclark_impl(vector<vec4i>& quads, vector<T>& vert,
const vector<vec4i>& quads_, const vector<T>& vert_, int level,
bool lock_boundary) {
// initialization
quads = quads_;
vert = vert_;
// early exit
if (quads.empty() || vert.empty()) return;
// loop over levels
for (auto l = 0; l < level; l++) {
// get edges
auto emap = make_edge_map(quads);
auto edges = get_edges(emap);
auto boundary = get_boundary(emap);
// number of elements
auto nverts = (int)vert.size();
auto nedges = (int)edges.size();
auto nboundary = (int)boundary.size();
auto nfaces = (int)quads.size();
// split elements ------------------------------------
// create vertices
auto tvert = vector<T>(nverts + nedges + nfaces);
for (auto i = 0; i < nverts; i++) tvert[i] = vert[i];
for (auto i = 0; i < nedges; i++) {
auto e = edges[i];
tvert[nverts + i] = (vert[e.x] + vert[e.y]) / 2;
}
for (auto i = 0; i < nfaces; i++) {
auto q = quads[i];
if (q.z != q.w) {
tvert[nverts + nedges + i] =
(vert[q.x] + vert[q.y] + vert[q.z] + vert[q.w]) / 4;
} else {
tvert[nverts + nedges + i] = (vert[q.x] + vert[q.y] + vert[q.y]) / 3;
}
}
// create quads
auto tquads = vector<vec4i>(nfaces * 4); // conservative allocation
auto qi = 0;
for (auto i = 0; i < nfaces; i++) {
auto q = quads[i];
if (q.z != q.w) {
tquads[qi++] = {q.x, nverts + edge_index(emap, {q.x, q.y}),
nverts + nedges + i, nverts + edge_index(emap, {q.w, q.x})};
tquads[qi++] = {q.y, nverts + edge_index(emap, {q.y, q.z}),
nverts + nedges + i, nverts + edge_index(emap, {q.x, q.y})};
tquads[qi++] = {q.z, nverts + edge_index(emap, {q.z, q.w}),
nverts + nedges + i, nverts + edge_index(emap, {q.y, q.z})};
tquads[qi++] = {q.w, nverts + edge_index(emap, {q.w, q.x}),
nverts + nedges + i, nverts + edge_index(emap, {q.z, q.w})};
} else {
tquads[qi++] = {q.x, nverts + edge_index(emap, {q.x, q.y}),
nverts + nedges + i, nverts + edge_index(emap, {q.z, q.x})};
tquads[qi++] = {q.y, nverts + edge_index(emap, {q.y, q.z}),
nverts + nedges + i, nverts + edge_index(emap, {q.x, q.y})};
tquads[qi++] = {q.z, nverts + edge_index(emap, {q.z, q.x}),
nverts + nedges + i, nverts + edge_index(emap, {q.y, q.z})};
}
}
tquads.resize(qi);
// split boundary
auto tboundary = vector<vec2i>(nboundary * 2);
for (auto i = 0; i < nboundary; i++) {
auto e = boundary[i];
tboundary.push_back({e.x, nverts + edge_index(emap, e)});
tboundary.push_back({nverts + edge_index(emap, e), e.y});
}
// setup creases -----------------------------------
auto tcrease_edges = vector<vec2i>();
auto tcrease_verts = vector<int>();
if (lock_boundary) {
for (auto& b : tboundary) {
tcrease_verts.push_back(b.x);
tcrease_verts.push_back(b.y);
}
} else {
for (auto& b : tboundary) tcrease_edges.push_back(b);
}
// define vertex valence ---------------------------
auto tvert_val = vector<int>(tvert.size(), 2);
for (auto& e : tboundary) {
tvert_val[e.x] = (lock_boundary) ? 0 : 1;
tvert_val[e.y] = (lock_boundary) ? 0 : 1;
}
// averaging pass ----------------------------------
auto avert = vector<T>(tvert.size(), T());
auto acount = vector<int>(tvert.size(), 0);
for (auto p : tcrease_verts) {
if (tvert_val[p] != 0) continue;
avert[p] += tvert[p];
acount[p] += 1;
}
for (auto& e : tcrease_edges) {
auto c = (tvert[e.x] + tvert[e.y]) / 2;
for (auto vid : {e.x, e.y}) {
if (tvert_val[vid] != 1) continue;
avert[vid] += c;
acount[vid] += 1;
}
}
for (auto& q : tquads) {
auto c = (tvert[q.x] + tvert[q.y] + tvert[q.z] + tvert[q.w]) / 4;
for (auto vid : {q.x, q.y, q.z, q.w}) {
if (tvert_val[vid] != 2) continue;
avert[vid] += c;
acount[vid] += 1;
}
}
for (auto i = 0; i < tvert.size(); i++) avert[i] /= (float)acount[i];
// correction pass ----------------------------------
// p = p + (avg_p - p) * (4/avg_count)
for (auto i = 0; i < tvert.size(); i++) {
if (tvert_val[i] != 2) continue;
avert[i] = tvert[i] + (avert[i] - tvert[i]) * (4 / (float)acount[i]);
}
tvert = avert;
// done
swap(tquads, quads);
swap(tvert, vert);
}
}
template <typename T>
pair<vector<vec4i>, vector<T>> subdivide_catmullclark_impl(
const vector<vec4i>& quads, const vector<T>& vert, int level,
bool lock_boundary) {
auto tess = pair<vector<vec4i>, vector<T>>{};
subdivide_catmullclark_impl(
tess.first, tess.second, quads, vert, level, lock_boundary);
return tess;
}
template <typename T, typename SubdivideFunc>
void subdivide_elems_impl(vector<T>& selems, vector<vec3f>& spositions,
vector<vec3f>& snormals, vector<vec2f>& stexcoords, vector<vec4f>& scolors,
vector<float>& sradius, const vector<T>& elems,
const vector<vec3f>& positions, const vector<vec3f>& normals,
const vector<vec2f>& texcoords, const vector<vec4f>& colors,
const vector<float>& radius, int level,
const SubdivideFunc&& subdivide_func) {
struct vertex {
vec3f position = zero3f;
vec3f normal = zero3f;
vec2f texcoord = zero2f;
vec4f color = zero4f;
float radius = 0;
vertex& operator+=(const vertex& a) { return *this = *this + a; };
vertex& operator/=(float s) { return *this = *this / s; };
vertex operator+(const vertex& a) const {
return {position + a.position, normal + a.normal, texcoord + a.texcoord,
color + a.color, radius + a.radius};
};
vertex operator-(const vertex& a) const {
return {position - a.position, normal - a.normal, texcoord - a.texcoord,
color - a.color, radius - a.radius};
};
vertex operator*(float s) const {
return {position * s, normal * s, texcoord * s, color * s, radius * s};
};
vertex operator/(float s) const { return operator*(1 / s); };
};
auto vertices = vector<vertex>(positions.size());
if (!positions.empty()) {
for (auto i = 0; i < vertices.size(); i++)
vertices[i].position = positions[i];
}
if (!normals.empty()) {
for (auto i = 0; i < vertices.size(); i++) vertices[i].normal = normals[i];
}
if (!texcoords.empty()) {
for (auto i = 0; i < vertices.size(); i++)
vertices[i].texcoord = texcoords[i];
}
if (!colors.empty()) {
for (auto i = 0; i < vertices.size(); i++) vertices[i].color = colors[i];
}
if (!radius.empty()) {
for (auto i = 0; i < vertices.size(); i++) vertices[i].radius = radius[i];
}
subdivide_func(selems, vertices, elems, vertices, level);
if (!positions.empty()) {
spositions.resize(vertices.size());
for (auto i = 0; i < vertices.size(); i++)
spositions[i] = vertices[i].position;
}
if (!normals.empty()) {
snormals.resize(vertices.size());
for (auto i = 0; i < vertices.size(); i++) snormals[i] = vertices[i].normal;
}
if (!texcoords.empty()) {
stexcoords.resize(vertices.size());
for (auto i = 0; i < vertices.size(); i++)
stexcoords[i] = vertices[i].texcoord;
}
if (!colors.empty()) {
scolors.resize(vertices.size());
for (auto i = 0; i < vertices.size(); i++) scolors[i] = vertices[i].color;
}
if (!radius.empty()) {
sradius.resize(vertices.size());
for (auto i = 0; i < vertices.size(); i++) sradius[i] = vertices[i].radius;
}
}
pair<vector<vec2i>, vector<float>> subdivide_lines(
const vector<vec2i>& lines, const vector<float>& vert, int level) {
return subdivide_lines_impl(lines, vert, level);
}
pair<vector<vec2i>, vector<vec2f>> subdivide_lines(
const vector<vec2i>& lines, const vector<vec2f>& vert, int level) {
return subdivide_lines_impl(lines, vert, level);
}
pair<vector<vec2i>, vector<vec3f>> subdivide_lines(
const vector<vec2i>& lines, const vector<vec3f>& vert, int level) {
return subdivide_lines_impl(lines, vert, level);
}
pair<vector<vec2i>, vector<vec4f>> subdivide_lines(
const vector<vec2i>& lines, const vector<vec4f>& vert, int level) {
return subdivide_lines_impl(lines, vert, level);
}
void subdivide_lines(vector<vec2i>& slines, vector<float>& svert,
const vector<vec2i>& lines, const vector<float>& vert, int level) {
subdivide_lines_impl(slines, svert, lines, vert, level);
}
void subdivide_lines(vector<vec2i>& slines, vector<vec2f>& svert,
const vector<vec2i>& lines, const vector<vec2f>& vert, int level) {
subdivide_lines_impl(slines, svert, lines, vert, level);
}
void subdivide_lines(vector<vec2i>& slines, vector<vec3f>& svert,
const vector<vec2i>& lines, const vector<vec3f>& vert, int level) {
subdivide_lines_impl(slines, svert, lines, vert, level);
}
void subdivide_lines(vector<vec2i>& slines, vector<vec4f>& svert,
const vector<vec2i>& lines, const vector<vec4f>& vert, int level) {
subdivide_lines_impl(slines, svert, lines, vert, level);
}
void subdivide_lines(vector<vec2i>& slines, vector<vec3f>& spositions,
vector<vec3f>& snormals, vector<vec2f>& stexcoords, vector<vec4f>& scolors,
vector<float>& sradius, const vector<vec2i>& lines,
const vector<vec3f>& positions, const vector<vec3f>& normals,
const vector<vec2f>& texcoords, const vector<vec4f>& colors,
const vector<float>& radius, int level) {
subdivide_elems_impl(slines, spositions, snormals, stexcoords, scolors,
sradius, lines, positions, normals, texcoords, colors, radius, level,
[](auto& slines, auto& svert, auto& lines, auto& vert, int level) {
subdivide_lines_impl(slines, svert, lines, vert, level);
});
}
pair<vector<vec3i>, vector<float>> subdivide_triangles(
const vector<vec3i>& triangles, const vector<float>& vert, int level) {
return subdivide_triangles_impl(triangles, vert, level);
}
pair<vector<vec3i>, vector<vec2f>> subdivide_triangles(
const vector<vec3i>& triangles, const vector<vec2f>& vert, int level) {
return subdivide_triangles_impl(triangles, vert, level);
}
pair<vector<vec3i>, vector<vec3f>> subdivide_triangles(
const vector<vec3i>& triangles, const vector<vec3f>& vert, int level) {
return subdivide_triangles_impl(triangles, vert, level);
}
pair<vector<vec3i>, vector<vec4f>> subdivide_triangles(
const vector<vec3i>& triangles, const vector<vec4f>& vert, int level) {
return subdivide_triangles_impl(triangles, vert, level);
}
void subdivide_triangles(vector<vec3i>& striangles, vector<float>& svert,
const vector<vec3i>& triangles, const vector<float>& vert, int level) {
subdivide_triangles_impl(striangles, svert, triangles, vert, level);
}
void subdivide_triangles(vector<vec3i>& striangles, vector<vec2f>& svert,
const vector<vec3i>& triangles, const vector<vec2f>& vert, int level) {
subdivide_triangles_impl(striangles, svert, triangles, vert, level);
}
void subdivide_triangles(vector<vec3i>& striangles, vector<vec3f>& svert,
const vector<vec3i>& triangles, const vector<vec3f>& vert, int level) {
subdivide_triangles_impl(striangles, svert, triangles, vert, level);
}
void subdivide_triangles(vector<vec3i>& striangles, vector<vec4f>& svert,
const vector<vec3i>& triangles, const vector<vec4f>& vert, int level) {
subdivide_triangles_impl(striangles, svert, triangles, vert, level);
}
void subdivide_triangles(vector<vec3i>& striangles, vector<vec3f>& spositions,
vector<vec3f>& snormals, vector<vec2f>& stexcoords, vector<vec4f>& scolors,
vector<float>& sradius, const vector<vec3i>& triangles,
const vector<vec3f>& positions, const vector<vec3f>& normals,
const vector<vec2f>& texcoords, const vector<vec4f>& colors,
const vector<float>& radius, int level) {
subdivide_elems_impl(striangles, spositions, snormals, stexcoords, scolors,
sradius, triangles, positions, normals, texcoords, colors, radius, level,
[](auto& striangles, auto& svert, auto& triangles, auto& vert,
int level) {
subdivide_triangles_impl(striangles, svert, triangles, vert, level);
});
}
pair<vector<vec4i>, vector<float>> subdivide_quads(
const vector<vec4i>& quads, const vector<float>& vert, int level) {
return subdivide_quads_impl(quads, vert, level);
}
pair<vector<vec4i>, vector<vec2f>> subdivide_quads(
const vector<vec4i>& quads, const vector<vec2f>& vert, int level) {
return subdivide_quads_impl(quads, vert, level);
}
pair<vector<vec4i>, vector<vec3f>> subdivide_quads(
const vector<vec4i>& quads, const vector<vec3f>& vert, int level) {
return subdivide_quads_impl(quads, vert, level);
}
pair<vector<vec4i>, vector<vec4f>> subdivide_quads(
const vector<vec4i>& quads, const vector<vec4f>& vert, int level) {
return subdivide_quads_impl(quads, vert, level);
}
void subdivide_quads(vector<vec4i>& squads, vector<float>& svert,
const vector<vec4i>& quads, const vector<float>& vert, int level) {
subdivide_quads_impl(squads, svert, quads, vert, level);
}
void subdivide_quads(vector<vec4i>& squads, vector<vec2f>& svert,
const vector<vec4i>& quads, const vector<vec2f>& vert, int level) {
subdivide_quads_impl(squads, svert, quads, vert, level);
}
void subdivide_quads(vector<vec4i>& squads, vector<vec3f>& svert,
const vector<vec4i>& quads, const vector<vec3f>& vert, int level) {
subdivide_quads_impl(squads, svert, quads, vert, level);
}
void subdivide_quads(vector<vec4i>& squads, vector<vec4f>& svert,
const vector<vec4i>& quads, const vector<vec4f>& vert, int level) {
subdivide_quads_impl(squads, svert, quads, vert, level);
}
void subdivide_quads(vector<vec4i>& squads, vector<vec3f>& spositions,
vector<vec3f>& snormals, vector<vec2f>& stexcoords, vector<vec4f>& scolors,
vector<float>& sradius, const vector<vec4i>& quads,
const vector<vec3f>& positions, const vector<vec3f>& normals,
const vector<vec2f>& texcoords, const vector<vec4f>& colors,
const vector<float>& radius, int level) {
subdivide_elems_impl(squads, spositions, snormals, stexcoords, scolors,
sradius, quads, positions, normals, texcoords, colors, radius, level,
[](auto& squads, auto& svert, auto& quads, auto& vert, int level) {
subdivide_quads_impl(squads, svert, quads, vert, level);
});
}
pair<vector<vec4i>, vector<float>> subdivide_beziers(
const vector<vec4i>& beziers, const vector<float>& vert, int level) {
return subdivide_beziers_impl(beziers, vert, level);
}
pair<vector<vec4i>, vector<vec2f>> subdivide_beziers(
const vector<vec4i>& beziers, const vector<vec2f>& vert, int level) {
return subdivide_beziers_impl(beziers, vert, level);
}
pair<vector<vec4i>, vector<vec3f>> subdivide_beziers(
const vector<vec4i>& beziers, const vector<vec3f>& vert, int level) {
return subdivide_beziers_impl(beziers, vert, level);
}
pair<vector<vec4i>, vector<vec4f>> subdivide_beziers(
const vector<vec4i>& beziers, const vector<vec4f>& vert, int level) {
return subdivide_beziers_impl(beziers, vert, level);
}
void subdivide_beziers(vector<vec4i>& sbeziers, vector<float>& svert,
const vector<vec4i>& beziers, const vector<float>& vert, int level) {
subdivide_beziers_impl(sbeziers, svert, beziers, vert, level);
}
void subdivide_beziers(vector<vec4i>& sbeziers, vector<vec2f>& svert,
const vector<vec4i>& beziers, const vector<vec2f>& vert, int level) {
subdivide_beziers_impl(sbeziers, svert, beziers, vert, level);
}
void subdivide_beziers(vector<vec4i>& sbeziers, vector<vec3f>& svert,
const vector<vec4i>& beziers, const vector<vec3f>& vert, int level) {
subdivide_beziers_impl(sbeziers, svert, beziers, vert, level);
}
void subdivide_beziers(vector<vec4i>& sbeziers, vector<vec4f>& svert,
const vector<vec4i>& beziers, const vector<vec4f>& vert, int level) {
subdivide_beziers_impl(sbeziers, svert, beziers, vert, level);
}
void subdivide_beziers(vector<vec4i>& sbeziers, vector<vec3f>& spositions,
vector<vec3f>& snormals, vector<vec2f>& stexcoords, vector<vec4f>& scolors,
vector<float>& sradius, const vector<vec4i>& beziers,
const vector<vec3f>& positions, const vector<vec3f>& normals,
const vector<vec2f>& texcoords, const vector<vec4f>& colors,
const vector<float>& radius, int level) {
subdivide_elems_impl(sbeziers, spositions, snormals, stexcoords, scolors,
sradius, beziers, positions, normals, texcoords, colors, radius, level,
[](auto& sbeziers, auto& svert, auto& beziers, auto& vert, int level) {
subdivide_beziers_impl(sbeziers, svert, beziers, vert, level);
});
}
pair<vector<vec4i>, vector<float>> subdivide_catmullclark(
const vector<vec4i>& quads, const vector<float>& vert, int level,
bool lock_boundary) {
return subdivide_catmullclark_impl(quads, vert, level, lock_boundary);
}
pair<vector<vec4i>, vector<vec2f>> subdivide_catmullclark(
const vector<vec4i>& quads, const vector<vec2f>& vert, int level,
bool lock_boundary) {
return subdivide_catmullclark_impl(quads, vert, level, lock_boundary);
}
pair<vector<vec4i>, vector<vec3f>> subdivide_catmullclark(
const vector<vec4i>& quads, const vector<vec3f>& vert, int level,
bool lock_boundary) {
return subdivide_catmullclark_impl(quads, vert, level, lock_boundary);
}
pair<vector<vec4i>, vector<vec4f>> subdivide_catmullclark(
const vector<vec4i>& quads, const vector<vec4f>& vert, int level,
bool lock_boundary) {
return subdivide_catmullclark_impl(quads, vert, level, lock_boundary);
}
void subdivide_catmullclark(vector<vec4i>& squads, vector<float>& svert,
const vector<vec4i>& quads, const vector<float>& vert, int level,
bool lock_boundary) {
subdivide_catmullclark_impl(squads, svert, quads, vert, level, lock_boundary);
}
void subdivide_catmullclark(vector<vec4i>& squads, vector<vec2f>& svert,
const vector<vec4i>& quads, const vector<vec2f>& vert, int level,
bool lock_boundary) {
subdivide_catmullclark_impl(squads, svert, quads, vert, level, lock_boundary);
}
void subdivide_catmullclark(vector<vec4i>& squads, vector<vec3f>& svert,
const vector<vec4i>& quads, const vector<vec3f>& vert, int level,
bool lock_boundary) {
subdivide_catmullclark_impl(squads, svert, quads, vert, level, lock_boundary);
}
void subdivide_catmullclark(vector<vec4i>& squads, vector<vec4f>& svert,
const vector<vec4i>& quads, const vector<vec4f>& vert, int level,
bool lock_boundary) {
subdivide_catmullclark_impl(squads, svert, quads, vert, level, lock_boundary);
}
void subdivide_catmullclark(vector<vec4i>& squads, vector<vec3f>& spositions,
vector<vec3f>& snormals, vector<vec2f>& stexcoords, vector<vec4f>& scolors,
vector<float>& sradius, const vector<vec4i>& quads,
const vector<vec3f>& positions, const vector<vec3f>& normals,
const vector<vec2f>& texcoords, const vector<vec4f>& colors,
const vector<float>& radius, int level) {
subdivide_elems_impl(squads, spositions, snormals, stexcoords, scolors,
sradius, quads, positions, normals, texcoords, colors, radius, level,
[](auto& squads, auto& svert, auto& quads, auto& vert, int level) {
subdivide_catmullclark_impl(squads, svert, quads, vert, level, true);
});
}
} // namespace yocto
// -----------------------------------------------------------------------------
// IMPLEMENTATION OF SHAPE SAMPLING
// -----------------------------------------------------------------------------
namespace yocto {
// Pick a point in a point set uniformly.
int sample_points(int npoints, float re) { return sample_uniform(npoints, re); }
int sample_points(const vector<float>& cdf, float re) {
return sample_discrete(cdf, re);
}
vector<float> sample_points_cdf(int npoints) {
auto cdf = vector<float>(npoints);
for (auto i = 0; i < cdf.size(); i++) cdf[i] = 1 + (i ? cdf[i - 1] : 0);
return cdf;
}
void sample_points_cdf(vector<float>& cdf, int npoints) {
cdf.resize(npoints);
for (auto i = 0; i < cdf.size(); i++) cdf[i] = 1 + (i ? cdf[i - 1] : 0);
}
// Pick a point on lines uniformly.
pair<int, float> sample_lines(const vector<float>& cdf, float re, float ru) {
return {sample_discrete(cdf, re), ru};
}
vector<float> sample_lines_cdf(
const vector<vec2i>& lines, const vector<vec3f>& positions) {
auto cdf = vector<float>(lines.size());
for (auto i = 0; i < cdf.size(); i++) {
auto l = lines[i];
auto w = line_length(positions[l.x], positions[l.y]);
cdf[i] = w + (i ? cdf[i - 1] : 0);
}
return cdf;
}
void sample_lines_cdf(vector<float>& cdf, const vector<vec2i>& lines,
const vector<vec3f>& positions) {
cdf.resize(lines.size());
for (auto i = 0; i < cdf.size(); i++) {
auto l = lines[i];
auto w = line_length(positions[l.x], positions[l.y]);
cdf[i] = w + (i ? cdf[i - 1] : 0);
}
}
// Pick a point on a triangle mesh uniformly.
pair<int, vec2f> sample_triangles(
const vector<float>& cdf, float re, const vec2f& ruv) {
return {sample_discrete(cdf, re), sample_triangle(ruv)};
}
vector<float> sample_triangles_cdf(
const vector<vec3i>& triangles, const vector<vec3f>& positions) {
auto cdf = vector<float>(triangles.size());
for (auto i = 0; i < cdf.size(); i++) {
auto t = triangles[i];
auto w = triangle_area(positions[t.x], positions[t.y], positions[t.z]);
cdf[i] = w + (i ? cdf[i - 1] : 0);
}
return cdf;
}
void sample_triangles_cdf(vector<float>& cdf, const vector<vec3i>& triangles,
const vector<vec3f>& positions) {
cdf.resize(triangles.size());
for (auto i = 0; i < cdf.size(); i++) {
auto t = triangles[i];
auto w = triangle_area(positions[t.x], positions[t.y], positions[t.z]);
cdf[i] = w + (i ? cdf[i - 1] : 0);
}
}
// Pick a point on a quad mesh uniformly.
pair<int, vec2f> sample_quads(
const vector<float>& cdf, float re, const vec2f& ruv) {
return {sample_discrete(cdf, re), ruv};
}
pair<int, vec2f> sample_quads(const vector<vec4i>& quads,
const vector<float>& cdf, float re, const vec2f& ruv) {
auto element = sample_discrete(cdf, re);
if (quads[element].z == quads[element].w) {
return {element, sample_triangle(ruv)};
} else {
return {element, ruv};
}
}
vector<float> sample_quads_cdf(
const vector<vec4i>& quads, const vector<vec3f>& positions) {
auto cdf = vector<float>(quads.size());
for (auto i = 0; i < cdf.size(); i++) {
auto q = quads[i];
auto w = quad_area(
positions[q.x], positions[q.y], positions[q.z], positions[q.w]);
cdf[i] = w + (i ? cdf[i - 1] : 0);
}
return cdf;
}
void sample_quads_cdf(vector<float>& cdf, const vector<vec4i>& quads,
const vector<vec3f>& positions) {
cdf.resize(quads.size());
for (auto i = 0; i < cdf.size(); i++) {
auto q = quads[i];
auto w = quad_area(
positions[q.x], positions[q.y], positions[q.z], positions[q.w]);
cdf[i] = w + (i ? cdf[i - 1] : 0);
}
}
// Samples a set of points over a triangle mesh uniformly. The rng function
// takes the point index and returns vec3f numbers uniform directibuted in
// [0,1]^3. unorm and texcoord are optional.
void sample_triangles(vector<vec3f>& sampled_positions,
vector<vec3f>& sampled_normals, vector<vec2f>& sampled_texturecoords,
const vector<vec3i>& triangles, const vector<vec3f>& positions,
const vector<vec3f>& normals, const vector<vec2f>& texcoords, int npoints,
int seed) {
sampled_positions.resize(npoints);
sampled_normals.resize(npoints);
sampled_texturecoords.resize(npoints);
auto cdf = vector<float>{};
sample_triangles_cdf(cdf, triangles, positions);
auto rng = make_rng(seed);
for (auto i = 0; i < npoints; i++) {
auto sample = sample_triangles(cdf, rand1f(rng), rand2f(rng));
auto& t = triangles[sample.first];
auto uv = sample.second;
sampled_positions[i] = interpolate_triangle(
positions[t.x], positions[t.y], positions[t.z], uv);
if (!sampled_normals.empty()) {
sampled_normals[i] = normalize(
interpolate_triangle(normals[t.x], normals[t.y], normals[t.z], uv));
} else {
sampled_normals[i] = triangle_normal(
positions[t.x], positions[t.y], positions[t.z]);
}
if (!sampled_texturecoords.empty()) {
sampled_texturecoords[i] = interpolate_triangle(
texcoords[t.x], texcoords[t.y], texcoords[t.z], uv);
} else {
sampled_texturecoords[i] = zero2f;
}
}
}
// Samples a set of points over a triangle mesh uniformly. The rng function
// takes the point index and returns vec3f numbers uniform directibuted in
// [0,1]^3. unorm and texcoord are optional.
void sample_quads(vector<vec3f>& sampled_positions,
vector<vec3f>& sampled_normals, vector<vec2f>& sampled_texturecoords,
const vector<vec4i>& quads, const vector<vec3f>& positions,
const vector<vec3f>& normals, const vector<vec2f>& texcoords, int npoints,
int seed) {
sampled_positions.resize(npoints);
sampled_normals.resize(npoints);
sampled_texturecoords.resize(npoints);
auto cdf = vector<float>{};
sample_quads_cdf(cdf, quads, positions);
auto rng = make_rng(seed);
for (auto i = 0; i < npoints; i++) {
auto sample = sample_quads(cdf, rand1f(rng), rand2f(rng));
auto& q = quads[sample.first];
auto uv = sample.second;
sampled_positions[i] = interpolate_quad(
positions[q.x], positions[q.y], positions[q.z], positions[q.w], uv);
if (!sampled_normals.empty()) {
sampled_normals[i] = normalize(interpolate_quad(
normals[q.x], normals[q.y], normals[q.z], normals[q.w], uv));
} else {
sampled_normals[i] = quad_normal(
positions[q.x], positions[q.y], positions[q.z], positions[q.w]);
}
if (!sampled_texturecoords.empty()) {
sampled_texturecoords[i] = interpolate_quad(
texcoords[q.x], texcoords[q.y], texcoords[q.z], texcoords[q.w], uv);
} else {
sampled_texturecoords[i] = zero2f;
}
}
}
} // namespace yocto
// -----------------------------------------------------------------------------
// SHAPE GEODESICS
// -----------------------------------------------------------------------------
namespace yocto {
void add_node(geodesic_solver& solver, const vec3f& position) {
solver.positions.push_back(position);
solver.graph.push_back({});
solver.graph.back().reserve(8);
}
void add_directed_arc(geodesic_solver& solver, int from, int to) {
// assert(from >= 0 && from < solver.graph.size());
// assert(to >= 0 && to < solver.graph.size());
auto len = length(solver.positions[from] - solver.positions[to]);
solver.graph[from].push_back({to, len});
}
void add_undirected_arc(geodesic_solver& solver, int na, int nb) {
add_directed_arc(solver, na, nb);
add_directed_arc(solver, nb, na);
}
void make_edge_solver_slow(geodesic_solver& solver,
const vector<vec3i>& triangles, const vector<vec3f>& positions,
bool use_steiner_points) {
solver.graph.reserve(positions.size());
for (int i = 0; i < positions.size(); i++) add_node(solver, positions[i]);
auto emap = make_edge_map(triangles);
auto edges = get_edges(emap);
for (auto& edge : edges) {
add_undirected_arc(solver, edge.x, edge.y);
}
if (!use_steiner_points) return;
solver.graph.reserve(size(positions) + size(edges));
auto steiner_per_edge = vector<int>(num_edges(emap));
// On each edge, connect the mid vertex with the vertices on th same edge.
for (auto edge_index = 0; edge_index < size(edges); edge_index++) {
auto& edge = edges[edge_index];
auto steiner_idx = solver.graph.size();
steiner_per_edge[edge_index] = steiner_idx;
add_node(solver, (positions[edge.x] + positions[edge.y]) * 0.5f);
add_directed_arc(solver, steiner_idx, edge.x);
add_directed_arc(solver, steiner_idx, edge.y);
}
// Make connection for each face
for (int face = 0; face < triangles.size(); ++face) {
int steiner_idx[3];
for (int k : {0, 1, 2}) {
int a = triangles[face][k];
int b = triangles[face][(k + 1) % 3];
steiner_idx[k] = steiner_per_edge[edge_index(emap, {a, b})];
}
// Connect each mid-vertex to the opposite mesh vertex in the triangle
int opp[3] = {triangles[face].z, triangles[face].x, triangles[face].y};
add_undirected_arc(solver, steiner_idx[0], opp[0]);
add_undirected_arc(solver, steiner_idx[1], opp[1]);
add_undirected_arc(solver, steiner_idx[2], opp[2]);
// Connect mid-verts of the face between them
add_undirected_arc(solver, steiner_idx[0], steiner_idx[1]);
add_undirected_arc(solver, steiner_idx[0], steiner_idx[2]);
add_undirected_arc(solver, steiner_idx[1], steiner_idx[2]);
}
}
void add_half_edge(geodesic_solver& solver, const vec2i& edge) {
// check if edge exists already
for (auto [vert, _] : solver.graph[edge.x]) {
if (vert == edge.y) return;
}
auto len = length(solver.positions[edge.x] - solver.positions[edge.y]);
auto edge_index = (int)solver.edges.size();
solver.graph[edge.x].push_back({edge.y, len});
solver.edge_index[edge.x].push_back({edge.y, edge_index});
solver.edges.push_back(edge);
}
void add_edge(geodesic_solver& solver, const vec2i& edge) {
// check if edge exists already
for (auto [vert, _] : solver.graph[edge.x]) {
if (vert == edge.y) return;
}
auto len = length(solver.positions[edge.x] - solver.positions[edge.y]);
solver.graph[edge.x].push_back({edge.y, len});
solver.graph[edge.y].push_back({edge.x, len});
auto edge_index = (int)solver.edges.size();
solver.edge_index[edge.x].push_back({edge.y, edge_index});
solver.edge_index[edge.y].push_back({edge.x, edge_index});
solver.edges.push_back(edge);
}
int edge_index(const geodesic_solver& solver, const vec2i& edge) {
for (auto [node, index] : solver.edge_index[edge.x])
if (edge.y == node) return index;
return -1;
}
void make_edge_solver_fast(geodesic_solver& solver,
const vector<vec3i>& triangles, const vector<vec3f>& positions,
bool use_steiner_points) {
solver.positions = positions;
solver.graph.resize(size(positions));
solver.edge_index.resize(size(positions));
// fast construction assuming edges are not repeated
for (auto t : triangles) {
add_edge(solver, {t.x, t.y});
add_edge(solver, {t.y, t.z});
add_edge(solver, {t.z, t.x});
}
if (!use_steiner_points) return;
auto edges = solver.edges;
solver.graph.resize(size(positions) + size(edges));
solver.edge_index.resize(size(positions) + size(edges));
solver.positions.resize(size(positions) + size(edges));
auto steiner_per_edge = vector<int>(size(edges));
// On each edge, connect the mid vertex with the vertices on th same edge.
auto edge_offset = (int)positions.size();
for (auto edge_index = 0; edge_index < size(edges); edge_index++) {
auto& edge = edges[edge_index];
auto steiner_idx = edge_offset + edge_index;
steiner_per_edge[edge_index] = steiner_idx;
solver.positions[steiner_idx] = (positions[edge.x] + positions[edge.y]) *
0.5f;
add_half_edge(solver, {steiner_idx, edge.x});
add_half_edge(solver, {steiner_idx, edge.y});
}
// Make connection for each face
for (int face = 0; face < triangles.size(); ++face) {
int steiner_idx[3];
for (int k : {0, 1, 2}) {
int a = triangles[face][k];
int b = triangles[face][(k + 1) % 3];
steiner_idx[k] = steiner_per_edge[edge_index(solver, {a, b})];
}
// Connect each mid-vertex to the opposite mesh vertex in the triangle
int opp[3] = {triangles[face].z, triangles[face].x, triangles[face].y};
add_edge(solver, {steiner_idx[0], opp[0]});
add_edge(solver, {steiner_idx[1], opp[1]});
add_edge(solver, {steiner_idx[2], opp[2]});
// Connect mid-verts of the face between them
add_edge(solver, {steiner_idx[0], steiner_idx[1]});
add_edge(solver, {steiner_idx[1], steiner_idx[2]});
add_edge(solver, {steiner_idx[2], steiner_idx[0]});
}
}
void log_geodesic_solver_stats(const geodesic_solver& solver) {
// stats
auto num_edges = 0;
auto min_adjacents = int_max, max_adjacents = int_min;
auto min_length = flt_max, max_length = flt_min;
auto avg_adjacents = 0.0, avg_length = 0.0;
for (auto& adj : solver.graph) {
num_edges += (int)adj.size();
min_adjacents = min(min_adjacents, (int)adj.size());
max_adjacents = max(max_adjacents, (int)adj.size());
avg_adjacents += adj.size() / (double)solver.graph.size();
for (auto& edge : adj) {
min_length = min(min_length, edge.length);
max_length = max(max_length, edge.length);
avg_length += edge.length;
}
}
avg_length /= num_edges;
}
void update_edge_distances(geodesic_solver& solver) {
for (auto node = 0; node < solver.graph.size(); node++) {
for (auto& edge : solver.graph[node])
edge.length = length(
solver.positions[node] - solver.positions[edge.node]);
}
}
void init_geodesic_solver(geodesic_solver& solver,
const vector<vec3i>& triangles, const vector<vec3f>& positions) {
make_edge_solver_fast(solver, triangles, positions, true);
// auto solver = make_edge_solver_slow(triangles, positions, true);
log_geodesic_solver_stats(solver);
}
void compute_geodesic_distances(geodesic_solver& graph,
vector<float>& distances, const vector<int>& sources) {
// preallocated
distances.resize(graph.positions.size());
for (auto& d : distances) d = flt_max;
// Small Label Fisrt + Large Label Last
// https://en.wikipedia.org/wiki/Shortest_Path_Faster_Algorithm
auto num_nodes = (int)graph.graph.size();
// assert(distances.size() == num_nodes);
auto visited = vector<bool>(num_nodes, false);
// setup queue
auto queue = std::deque<int>{};
for (auto source : sources) {
distances[source] = 0.0f;
visited[source] = true;
queue.push_back(source);
}
// Cumulative weights of elements in queue.
auto cumulative_weight = 0.0f;
while (!queue.empty()) {
auto node = queue.front();
auto average_weight = (double)cumulative_weight / queue.size();
// Large Label Last: until front node weights more than the average, put
// it on back. Sometimes average_weight is less than envery value due to
// Ting point errors (doesn't happen with double precision).
for (auto tries = 0; tries < queue.size() + 1; tries++) {
if (distances[node] <= average_weight) break;
queue.pop_front();
queue.push_back(node);
node = queue.front();
}
queue.pop_front();
visited[node] = false; // out of queue
cumulative_weight -= distances[node]; // update average
const auto offset_distance = distances[node];
const auto num_neighbors = (int)graph.graph[node].size();
for (int neighbor_idx = 0; neighbor_idx < num_neighbors; neighbor_idx++) {
// distance and id to neightbor through this node
auto new_distance = offset_distance +
graph.graph[node][neighbor_idx].length;
auto neighbor = graph.graph[node][neighbor_idx].node;
auto old_distance = distances[neighbor];
if (new_distance >= old_distance) continue;
if (visited[neighbor]) {
// if neighbor already in queue, update cumulative weights.
cumulative_weight = cumulative_weight - old_distance + new_distance;
} else {
// if neighbor not in queue, Small Label first.
if (queue.empty() || (new_distance < distances[queue.front()]))
queue.push_front(neighbor);
else
queue.push_back(neighbor);
visited[neighbor] = true;
cumulative_weight = cumulative_weight + new_distance;
}
distances[neighbor] = new_distance;
}
}
}
void convert_distance_to_color(
vector<vec4f>& colors, const vector<float>& distances) {
colors.resize(distances.size());
for (auto idx = 0; idx < distances.size(); idx++) {
auto distance = fmod(distances[idx] * 10, 1.0f);
colors[idx] = {distance, distance, distance, 1};
}
}
} // namespace yocto
// -----------------------------------------------------------------------------
// IMPLEMENTATION OF SHAPE EXAMPLES
// -----------------------------------------------------------------------------
namespace yocto {
// Make a quad.
static void make_rect(vector<vec4i>& quads, vector<vec3f>& positions,
vector<vec3f>& normals, vector<vec2f>& texcoords, const vec2i& steps,
const vec2f& size, const vec2f& uvsize) {
positions.resize((steps.x + 1) * (steps.y + 1));
normals.resize((steps.x + 1) * (steps.y + 1));
texcoords.resize((steps.x + 1) * (steps.y + 1));
for (auto j = 0; j <= steps.y; j++) {
for (auto i = 0; i <= steps.x; i++) {
auto uv = vec2f{i / (float)steps.x, j / (float)steps.y};
positions[j * (steps.x + 1) + i] = {
(uv.x - 0.5f) * size.x, (uv.y - 0.5f) * size.y, 0};
normals[j * (steps.x + 1) + i] = {0, 0, 1};
texcoords[j * (steps.x + 1) + i] = 1 - uv * uvsize;
}
}
quads.resize(steps.x * steps.y);
for (auto j = 0; j < steps.y; j++) {
for (auto i = 0; i < steps.x; i++) {
quads[j * steps.x + i] = {j * (steps.x + 1) + i,
j * (steps.x + 1) + i + 1, (j + 1) * (steps.x + 1) + i + 1,
(j + 1) * (steps.x + 1) + i};
}
}
}
// Make a cube.
void make_box(vector<vec4i>& quads, vector<vec3f>& positions,
vector<vec3f>& normals, vector<vec2f>& texcoords, const vec3i& steps,
const vec3f& size, const vec3f& uvsize) {
quads.clear();
positions.clear();
normals.clear();
texcoords.clear();
auto qquads = vector<vec4i>{};
auto qpositions = vector<vec3f>{};
auto qnormals = vector<vec3f>{};
auto qtexturecoords = vector<vec2f>{};
// + z
make_rect(qquads, qpositions, qnormals, qtexturecoords, {steps.x, steps.y},
{size.x, size.y}, {uvsize.x, uvsize.y});
for (auto& p : qpositions) p = {p.x, p.y, size.z / 2};
for (auto& n : qnormals) n = {0, 0, 1};
merge_quads(quads, positions, normals, texcoords, qquads, qpositions,
qnormals, qtexturecoords);
// - z
make_rect(qquads, qpositions, qnormals, qtexturecoords, {steps.x, steps.y},
{size.x, size.y}, {uvsize.x, uvsize.y});
for (auto& p : qpositions) p = {-p.x, p.y, -size.z / 2};
for (auto& n : qnormals) n = {0, 0, -1};
merge_quads(quads, positions, normals, texcoords, qquads, qpositions,
qnormals, qtexturecoords);
// + x
make_rect(qquads, qpositions, qnormals, qtexturecoords, {steps.z, steps.y},
{size.z, size.y}, {uvsize.z, uvsize.y});
for (auto& p : qpositions) p = {size.x / 2, p.y, -p.x};
for (auto& n : qnormals) n = {1, 0, 0};
merge_quads(quads, positions, normals, texcoords, qquads, qpositions,
qnormals, qtexturecoords);
// - x
make_rect(qquads, qpositions, qnormals, qtexturecoords, {steps.z, steps.y},
{size.z, size.y}, {uvsize.z, uvsize.y});
for (auto& p : qpositions) p = {-size.x / 2, p.y, p.x};
for (auto& n : qnormals) n = {-1, 0, 0};
merge_quads(quads, positions, normals, texcoords, qquads, qpositions,
qnormals, qtexturecoords);
// + y
make_rect(qquads, qpositions, qnormals, qtexturecoords, {steps.x, steps.z},
{size.x, size.z}, {uvsize.x, uvsize.z});
for (auto i = 0; i < qpositions.size(); i++) {
qpositions[i] = {qpositions[i].x, size.y / 2, -qpositions[i].y};
qnormals[i] = {0, 1, 0};
}
merge_quads(quads, positions, normals, texcoords, qquads, qpositions,
qnormals, qtexturecoords);
// - y
make_rect(qquads, qpositions, qnormals, qtexturecoords, {steps.x, steps.z},
{size.x, size.z}, {uvsize.x, uvsize.z});
for (auto i = 0; i < qpositions.size(); i++) {
qpositions[i] = {qpositions[i].x, -size.y / 2, qpositions[i].y};
qnormals[i] = {0, -1, 0};
}
merge_quads(quads, positions, normals, texcoords, qquads, qpositions,
qnormals, qtexturecoords);
}
// Generate lines set along a quad.
void make_lines(vector<vec2i>& lines, vector<vec3f>& positions,
vector<vec3f>& normals, vector<vec2f>& texcoords, vector<float>& radius,
int num, int subdivisions, const vec2f& size, const vec2f& uvsize,
const vec2f& line_radius) {
auto steps = vec2i{pow2(subdivisions), num};
auto nverts = (steps.x + 1) * steps.y;
auto nlines = steps.x * steps.y;
auto vid = [steps](int i, int j) { return j * (steps.x + 1) + i; };
auto fid = [steps](int i, int j) { return j * steps.x + i; };
positions.resize(nverts);
normals.resize(nverts);
texcoords.resize(nverts);
radius.resize(nverts);
if (steps.y > 1) {
for (auto j = 0; j < steps.y; j++) {
for (auto i = 0; i <= steps.x; i++) {
auto uv = vec2f{
i / (float)steps.x, j / (float)(steps.y > 1 ? steps.y - 1 : 1)};
positions[vid(i, j)] = {
(uv.x - 0.5f) * size.x, (uv.y - 0.5f) * size.y, 0};
normals[vid(i, j)] = {1, 0, 0};
texcoords[vid(i, j)] = uv * uvsize;
}
}
} else {
for (auto i = 0; i <= steps.x; i++) {
auto uv = vec2f{i / (float)steps.x, 0};
positions[vid(i, 0)] = {(uv.x - 0.5f) * size.x, 0, 0};
normals[vid(i, 0)] = {1, 0, 0};
texcoords[vid(i, 0)] = uv * uvsize;
}
}
lines.resize(nlines);
for (int j = 0; j < steps.y; j++) {
for (int i = 0; i < steps.x; i++) {
lines[fid(i, j)] = {vid(i, j), vid(i + 1, j)};
}
}
}
// Generate a point set with points placed at the origin with texcoords
// varying along u.
void make_points(vector<int>& points, vector<vec3f>& positions,
vector<vec3f>& normals, vector<vec2f>& texcoords, vector<float>& radius,
int num, float uvsize, float point_radius) {
points.resize(num);
for (auto i = 0; i < num; i++) points[i] = i;
positions.assign(num, {0, 0, 0});
normals.assign(num, {0, 0, 1});
texcoords.assign(num, {0, 0});
radius.assign(num, point_radius);
for (auto i = 0; i < texcoords.size(); i++)
texcoords[i] = {(float)i / (float)num, 0};
}
// Generate a point set.
void make_random_points(vector<int>& points, vector<vec3f>& positions,
vector<vec3f>& normals, vector<vec2f>& texcoords, vector<float>& radius,
int num, const vec3f& size, float uvsize, float point_radius,
uint64_t seed) {
make_points(
points, positions, normals, texcoords, radius, num, uvsize, point_radius);
auto rng = make_rng(seed);
for (auto i = 0; i < positions.size(); i++) {
positions[i] = (rand3f(rng) - vec3f{0.5f, 0.5f, 0.5f}) * size;
}
}
// Make a point.
void make_point(vector<int>& points, vector<vec3f>& positions,
vector<vec3f>& normals, vector<vec2f>& texcoords, vector<float>& radius,
float point_radius) {
points = {0};
positions = {{0, 0, 0}};
normals = {{0, 0, 1}};
texcoords = {{0, 0}};
radius = {point_radius};
}
// Make a bezier circle. Returns bezier, pos.
void make_bezier_circle(
vector<vec4i>& beziers, vector<vec3f>& positions, float size) {
// constant from http://spencermortensen.com/articles/bezier-circle/
const auto c = 0.551915024494f;
static auto circle_pos = vector<vec3f>{{1, 0, 0}, {1, c, 0}, {c, 1, 0},
{0, 1, 0}, {-c, 1, 0}, {-1, c, 0}, {-1, 0, 0}, {-1, -c, 0}, {-c, -1, 0},
{0, -1, 0}, {c, -1, 0}, {1, -c, 0}};
static auto circle_beziers = vector<vec4i>{
{0, 1, 2, 3}, {3, 4, 5, 6}, {6, 7, 8, 9}, {9, 10, 11, 0}};
positions = circle_pos;
beziers = circle_beziers;
for (auto& p : positions) p *= size;
}
// Make a procedural shape
extern const vector<vec3f> quad_positions;
extern const vector<vec3f> quad_normals;
extern const vector<vec2f> quad_texcoords;
extern const vector<vec4i> quad_quads;
extern const vector<vec3f> quady_positions;
extern const vector<vec3f> quady_normals;
extern const vector<vec2f> quady_texcoords;
extern const vector<vec4i> quady_quads;
extern const vector<vec3f> cube_positions;
extern const vector<vec3f> cube_normals;
extern const vector<vec2f> cube_texcoords;
extern const vector<vec4i> cube_quads;
extern const vector<vec3f> fvcube_positions;
extern const vector<vec4i> fvcube_quads;
extern const vector<vec3f> suzanne_positions;
extern const vector<vec4i> suzanne_quads;
// Make a procedural shape
void make_proc_shape(vector<vec3i>& triangles, vector<vec4i>& quads,
vector<vec3f>& positions, vector<vec3f>& normals, vector<vec2f>& texcoords,
const proc_shape_params& params) {
auto subdivide_quads_pnt = [&](auto& qquads, auto& qpositions, auto& qnormals,
auto& qtexcoords) {
struct vertex {
vec3f position = zero3f;
vec3f normal = zero3f;
vec2f texcoord = zero2f;
vertex& operator+=(const vertex& a) { return *this = *this + a; };
vertex& operator/=(float s) { return *this = *this / s; };
vertex operator+(const vertex& a) const {
return {
position + a.position, normal + a.normal, texcoord + a.texcoord};
};
vertex operator-(const vertex& a) const {
return {
position - a.position, normal - a.normal, texcoord - a.texcoord};
};
vertex operator*(float s) const {
return {position * s, normal * s, texcoord * s};
};
vertex operator/(float s) const { return operator*(1 / s); };
};
auto vertices = vector<vertex>(qpositions.size());
for (auto i = 0; i < vertices.size(); i++) {
vertices[i].position = qpositions[i];
vertices[i].normal = qnormals[i];
vertices[i].texcoord = qtexcoords[i];
}
subdivide_quads_impl(
quads, vertices, qquads, vertices, params.subdivisions);
positions.resize(vertices.size());
normals.resize(vertices.size());
texcoords.resize(vertices.size());
for (auto i = 0; i < vertices.size(); i++) {
positions[i] = vertices[i].position;
normals[i] = vertices[i].normal;
texcoords[i] = vertices[i].texcoord;
}
};
auto subdivide_quads_p = [&](auto& qquads, auto& qpositions) {
subdivide_quads_impl(
quads, positions, qquads, qpositions, params.subdivisions);
};
triangles.clear();
quads.clear();
positions.clear();
normals.clear();
texcoords.clear();
switch (params.type) {
case proc_shape_params::type_t::quad: {
subdivide_quads_pnt(
quad_quads, quad_positions, quad_normals, quad_texcoords);
if (params.rounded) {
auto height = params.rounded;
auto radius = (1 + height * height) / (2 * height);
auto center = vec3f{0, 0, -radius + height};
for (auto i = 0; i < positions.size(); i++) {
auto pn = normalize(positions[i] - center);
positions[i] = center + pn * radius;
normals[i] = pn;
}
}
} break;
case proc_shape_params::type_t::floor: {
subdivide_quads_pnt(
quady_quads, quady_positions, quady_normals, quady_texcoords);
if (params.rounded) {
auto radius = params.rounded;
auto start = (1 - radius) / 2;
auto end = start + radius;
for (auto i = 0; i < positions.size(); i++) {
if (positions[i].z < -end) {
positions[i] = {
positions[i].x, -positions[i].z - end + radius, -end};
normals[i] = {0, 0, 1};
} else if (positions[i].z < -start && positions[i].z >= -end) {
auto phi = (pif / 2) * (-positions[i].z - start) / radius;
positions[i] = {positions[i].x, -cos(phi) * radius + radius,
-sin(phi) * radius - start};
normals[i] = {0, cos(phi), sin(phi)};
} else {
}
}
}
} break;
case proc_shape_params::type_t::cube: {
subdivide_quads_pnt(
cube_quads, cube_positions, cube_normals, cube_texcoords);
auto steps = vec3i{pow2(params.subdivisions)};
auto uvsize = vec3f{1};
auto size = vec3f{2};
make_box(quads, positions, normals, texcoords, steps, size, uvsize);
if (params.rounded) {
auto radius = params.rounded;
auto c = vec3f{1 - radius};
for (auto i = 0; i < positions.size(); i++) {
auto pc = vec3f{
abs(positions[i].x), abs(positions[i].y), abs(positions[i].z)};
auto ps = vec3f{positions[i].x < 0 ? -1.0f : 1.0f,
positions[i].y < 0 ? -1.0f : 1.0f,
positions[i].z < 0 ? -1.0f : 1.0f};
if (pc.x >= c.x && pc.y >= c.y && pc.z >= c.z) {
auto pn = normalize(pc - c);
positions[i] = c + radius * pn;
normals[i] = pn;
} else if (pc.x >= c.x && pc.y >= c.y) {
auto pn = normalize((pc - c) * vec3f{1, 1, 0});
positions[i] = {c.x + radius * pn.x, c.y + radius * pn.y, pc.z};
normals[i] = pn;
} else if (pc.x >= c.x && pc.z >= c.z) {
auto pn = normalize((pc - c) * vec3f{1, 0, 1});
positions[i] = {c.x + radius * pn.x, pc.y, c.z + radius * pn.z};
normals[i] = pn;
} else if (pc.y >= c.y && pc.z >= c.z) {
auto pn = normalize((pc - c) * vec3f{0, 1, 1});
positions[i] = {pc.x, c.y + radius * pn.y, c.z + radius * pn.z};
normals[i] = pn;
} else {
continue;
}
positions[i] *= ps;
normals[i] *= ps;
}
}
} break;
case proc_shape_params::type_t::sphere: {
subdivide_quads_pnt(
cube_quads, cube_positions, cube_normals, cube_texcoords);
for (auto& p : positions) p = normalize(p);
normals = positions;
} break;
case proc_shape_params::type_t::uvsphere: {
subdivide_quads_pnt(
quad_quads, quad_positions, quad_normals, quad_texcoords);
for (auto i = 0; i < positions.size(); i++) {
auto uv = texcoords[i];
auto a = vec2f{2 * pif * uv.x, pif * (1 - uv.y)};
auto p = vec3f{cos(a.x) * sin(a.y), sin(a.x) * sin(a.y), cos(a.y)};
positions[i] = p;
normals[i] = normalize(p);
texcoords[i] = uv;
}
if (params.rounded) {
auto zflip = (1 - params.rounded);
for (auto i = 0; i < positions.size(); i++) {
if (positions[i].z > zflip) {
positions[i].z = 2 * zflip - positions[i].z;
normals[i].x = -normals[i].x;
normals[i].y = -normals[i].y;
} else if (positions[i].z < -zflip) {
positions[i].z = 2 * (-zflip) - positions[i].z;
normals[i].x = -normals[i].x;
normals[i].y = -normals[i].y;
}
}
}
} break;
case proc_shape_params::type_t::disk: {
subdivide_quads_pnt(
quad_quads, quad_positions, quad_normals, quad_texcoords);
for (auto i = 0; i < positions.size(); i++) {
// Analytical Methods for Squaring the Disc, by C. Fong
// https://arxiv.org/abs/1509.06344
auto xy = vec2f{positions[i].x, positions[i].y};
auto uv = vec2f{
xy.x * sqrt(1 - xy.y * xy.y / 2), xy.y * sqrt(1 - xy.x * xy.x / 2)};
positions[i] = {uv.x, uv.y, 0};
}
if (params.rounded) {
auto height = params.rounded;
auto radius = (1 + height * height) / (2 * height);
auto center = vec3f{0, 0, -radius + height};
for (auto i = 0; i < positions.size(); i++) {
auto pn = normalize(positions[i] - center);
positions[i] = center + pn * radius;
normals[i] = pn;
}
}
} break;
case proc_shape_params::type_t::matball: {
subdivide_quads_pnt(
cube_quads, cube_positions, cube_normals, cube_texcoords);
for (auto i = 0; i < positions.size(); i++) {
auto p = positions[i];
positions[i] = normalize(p);
normals[i] = normalize(p);
}
} break;
case proc_shape_params::type_t::suzanne: {
subdivide_quads_p(suzanne_quads, suzanne_positions);
} break;
case proc_shape_params::type_t::box: {
auto steps = vec3i{
(int)round(pow2(params.subdivisions) * params.aspect.x),
(int)round(pow2(params.subdivisions) * params.aspect.y),
(int)round(pow2(params.subdivisions) * params.aspect.z)};
auto uvsize = params.aspect;
auto size = 2 * params.aspect;
make_box(quads, positions, normals, texcoords, steps, size, uvsize);
if (params.rounded) {
auto radius = params.rounded * min(size) / 2;
auto c = size / 2 - radius;
for (auto i = 0; i < positions.size(); i++) {
auto pc = vec3f{
abs(positions[i].x), abs(positions[i].y), abs(positions[i].z)};
auto ps = vec3f{positions[i].x < 0 ? -1.0f : 1.0f,
positions[i].y < 0 ? -1.0f : 1.0f,
positions[i].z < 0 ? -1.0f : 1.0f};
if (pc.x >= c.x && pc.y >= c.y && pc.z >= c.z) {
auto pn = normalize(pc - c);
positions[i] = c + radius * pn;
normals[i] = pn;
} else if (pc.x >= c.x && pc.y >= c.y) {
auto pn = normalize((pc - c) * vec3f{1, 1, 0});
positions[i] = {c.x + radius * pn.x, c.y + radius * pn.y, pc.z};
normals[i] = pn;
} else if (pc.x >= c.x && pc.z >= c.z) {
auto pn = normalize((pc - c) * vec3f{1, 0, 1});
positions[i] = {c.x + radius * pn.x, pc.y, c.z + radius * pn.z};
normals[i] = pn;
} else if (pc.y >= c.y && pc.z >= c.z) {
auto pn = normalize((pc - c) * vec3f{0, 1, 1});
positions[i] = {pc.x, c.y + radius * pn.y, c.z + radius * pn.z};
normals[i] = pn;
} else {
continue;
}
positions[i] *= ps;
normals[i] *= ps;
}
}
} break;
case proc_shape_params::type_t::rect: {
auto steps = vec2i{
(int)round(pow2(params.subdivisions) * params.aspect.x),
(int)round(pow2(params.subdivisions) * params.aspect.y)};
auto uvsize = vec2f{params.aspect.x, params.aspect.y};
auto size = 2 * vec2f{params.aspect.x, params.aspect.y};
make_rect(quads, positions, normals, texcoords, steps, size, uvsize);
} break;
case proc_shape_params::type_t::rect_stack: {
auto steps = vec3i{
(int)round(pow2(params.subdivisions) * params.aspect.x),
(int)round(pow2(params.subdivisions) * params.aspect.y),
(int)round(pow2(params.subdivisions) * params.aspect.z)};
auto uvsize = vec2f{params.aspect.x, params.aspect.y};
auto size = params.aspect;
auto qquads = vector<vec4i>{};
auto qpositions = vector<vec3f>{};
auto qnormals = vector<vec3f>{};
auto qtexturecoords = vector<vec2f>{};
for (auto i = 0; i <= steps.z; i++) {
make_rect(qquads, qpositions, qnormals, qtexturecoords,
{steps.x, steps.y}, {size.x, size.y}, uvsize);
for (auto& p : qpositions) p.z = (-0.5f + (float)i / steps.z) * size.z;
merge_quads(quads, positions, normals, texcoords, qquads, qpositions,
qnormals, qtexturecoords);
}
} break;
case proc_shape_params::type_t::uvdisk: {
subdivide_quads_pnt(
quad_quads, quad_positions, quad_normals, quad_texcoords);
for (auto i = 0; i < positions.size(); i++) {
auto uv = texcoords[i];
auto phi = 2 * pif * uv.x;
positions[i] = {cos(phi) * uv.y, sin(phi) * uv.y, 0};
normals[i] = {0, 0, 1};
}
} break;
case proc_shape_params::type_t::uvcylinder: {
auto steps = vec3i{
(int)round(pow2(params.subdivisions + 1) * params.aspect.x),
(int)round(pow2(params.subdivisions + 0) * params.aspect.y),
(int)round(pow2(params.subdivisions - 1) * params.aspect.z)};
auto uvsize = params.aspect;
auto size = 2 * vec2f{params.aspect.x, params.aspect.y};
auto qquads = vector<vec4i>{};
auto qpositions = vector<vec3f>{};
auto qnormals = vector<vec3f>{};
auto qtexcoords = vector<vec2f>{};
// side
make_rect(qquads, qpositions, qnormals, qtexcoords, {steps.x, steps.y},
{1, 1}, {1, 1});
for (auto i = 0; i < qpositions.size(); i++) {
auto uv = qtexcoords[i];
auto phi = 2 * pif * uv.x;
qpositions[i] = {cos(phi) * size.x / 2, sin(phi) * size.x / 2,
(uv.y - 0.5f) * size.y};
qnormals[i] = {cos(phi), sin(phi), 0};
qtexcoords[i] = uv * vec2f{uvsize.x, uvsize.y};
}
merge_quads(quads, positions, normals, texcoords, qquads, qpositions,
qnormals, qtexcoords);
// top
make_rect(qquads, qpositions, qnormals, qtexcoords, {steps.x, steps.z},
{1, 1}, {1, 1});
for (auto i = 0; i < qpositions.size(); i++) {
auto uv = qtexcoords[i];
auto phi = 2 * pif * uv.x;
qpositions[i] = {
cos(phi) * uv.y * size.x / 2, sin(phi) * uv.y * size.x / 2, 0};
qnormals[i] = {0, 0, 1};
qtexcoords[i] = uv * vec2f{uvsize.x, uvsize.z};
qpositions[i].z = size.y / 2;
}
merge_quads(quads, positions, normals, texcoords, qquads, qpositions,
qnormals, qtexcoords);
// bottom
make_rect(qquads, qpositions, qnormals, qtexcoords, {steps.x, steps.z},
{1, 1}, {1, 1});
for (auto i = 0; i < qpositions.size(); i++) {
auto uv = qtexcoords[i];
auto phi = 2 * pif * uv.x;
qpositions[i] = {
cos(phi) * uv.y * size.x / 2, sin(phi) * uv.y * size.x / 2, 0};
qnormals[i] = {0, 0, 1};
qtexcoords[i] = uv * vec2f{uvsize.x, uvsize.z};
qpositions[i].z = -size.y / 2;
qnormals[i] = -qnormals[i];
}
for (auto i = 0; i < qquads.size(); i++) swap(qquads[i].x, qquads[i].z);
merge_quads(quads, positions, normals, texcoords, qquads, qpositions,
qnormals, qtexcoords);
if (params.rounded) {
auto radius = params.rounded * min(size) / 2;
auto c = size / 2 - vec2f{radius, radius};
for (auto i = 0; i < positions.size(); i++) {
auto phi = atan2(positions[i].y, positions[i].x);
auto r = length(vec2f{positions[i].x, positions[i].y});
auto z = positions[i].z;
auto pc = vec2f{r, fabs(z)};
auto ps = (z < 0) ? -1.0f : 1.0f;
if (pc.x >= c.x && pc.y >= c.y) {
auto pn = normalize(pc - c);
positions[i] = {cos(phi) * (c.x + radius * pn.x),
sin(phi) * (c.x + radius * pn.x), ps * (c.y + radius * pn.y)};
normals[i] = {cos(phi) * pn.x, sin(phi) * pn.x, ps * pn.y};
} else {
continue;
}
}
}
} break;
case proc_shape_params::type_t::geosphere: {
// https://stackoverflow.com/questions/17705621/algorithm-for-a-geodesic-sphere
const float X = 0.525731112119133606f;
const float Z = 0.850650808352039932f;
static auto sphere_positions = vector<vec3f>{{-X, 0.0, Z}, {X, 0.0, Z},
{-X, 0.0, -Z}, {X, 0.0, -Z}, {0.0, Z, X}, {0.0, Z, -X}, {0.0, -Z, X},
{0.0, -Z, -X}, {Z, X, 0.0}, {-Z, X, 0.0}, {Z, -X, 0.0},
{-Z, -X, 0.0}};
static auto sphere_triangles = vector<vec3i>{{0, 1, 4}, {0, 4, 9},
{9, 4, 5}, {4, 8, 5}, {4, 1, 8}, {8, 1, 10}, {8, 10, 3}, {5, 8, 3},
{5, 3, 2}, {2, 3, 7}, {7, 3, 10}, {7, 10, 6}, {7, 6, 11}, {11, 6, 0},
{0, 6, 1}, {6, 10, 1}, {9, 11, 0}, {9, 2, 11}, {9, 5, 2}, {7, 11, 2}};
subdivide_triangles(triangles, positions, sphere_triangles,
sphere_positions, params.subdivisions);
for (auto& p : positions) p = normalize(p);
normals = positions;
} break;
}
if (params.scale != 1) {
for (auto& p : positions) p *= params.scale;
}
if (params.uvscale != 1) {
for (auto& uv : texcoords) uv *= params.uvscale;
}
if (params.frame != identity3x4f) {
for (auto& p : positions) p = transform_point(params.frame, p);
}
}
// Make face-varying quads
void make_proc_fvshape(vector<vec4i>& quadspos, vector<vec4i>& quadsnorm,
vector<vec4i>& quadstexcoord, vector<vec3f>& positions,
vector<vec3f>& normals, vector<vec2f>& texcoords,
const proc_shape_params& params) {
switch (params.type) {
case proc_shape_params::type_t::quad: {
subdivide_quads(
quadspos, positions, quad_quads, quad_positions, params.subdivisions);
subdivide_quads(
quadsnorm, normals, quad_quads, quad_normals, params.subdivisions);
subdivide_quads(quadstexcoord, texcoords, quad_quads, quad_texcoords,
params.subdivisions);
} break;
case proc_shape_params::type_t::cube: {
subdivide_quads(quadspos, positions, fvcube_quads, fvcube_positions,
params.subdivisions);
subdivide_quads(
quadsnorm, normals, cube_quads, cube_normals, params.subdivisions);
subdivide_quads(quadstexcoord, texcoords, cube_quads, cube_texcoords,
params.subdivisions);
} break;
case proc_shape_params::type_t::sphere: {
subdivide_quads(quadspos, positions, fvcube_quads, fvcube_positions,
params.subdivisions);
subdivide_quads(quadstexcoord, texcoords, cube_quads, cube_texcoords,
params.subdivisions);
for (auto& p : positions) p = normalize(p);
normals = positions;
quadsnorm = quadspos;
} break;
case proc_shape_params::type_t::suzanne: {
subdivide_quads(quadspos, positions, suzanne_quads, suzanne_positions,
params.subdivisions);
} break;
default: {
throw std::runtime_error(
"shape type not supported " + std::to_string((int)params.type));
} break;
}
if (params.scale != 1) {
for (auto& p : positions) p *= params.scale;
}
if (params.uvscale != 1) {
for (auto& uv : texcoords) uv *= params.uvscale;
}
if (params.frame != identity3x4f) {
for (auto& p : positions) p = transform_point(params.frame, p);
}
}
// Make a hair ball around a shape
void make_hair(vector<vec2i>& lines, vector<vec3f>& positions,
vector<vec3f>& normals, vector<vec2f>& texcoords, vector<float>& radius,
const vector<vec3i>& striangles, const vector<vec4i>& squads,
const vector<vec3f>& spos, const vector<vec3f>& snorm,
const vector<vec2f>& stexcoord, const hair_params& params) {
auto alltriangles = striangles;
auto quads_triangles = vector<vec3i>{};
quads_to_triangles(quads_triangles, squads);
alltriangles.insert(
alltriangles.end(), quads_triangles.begin(), quads_triangles.end());
auto bpos = vector<vec3f>{};
auto bnorm = vector<vec3f>{};
auto btexcoord = vector<vec2f>{};
sample_triangles(bpos, bnorm, btexcoord, alltriangles, spos, snorm, stexcoord,
params.num, params.seed);
auto rng = make_rng(params.seed, 3);
auto blen = vector<float>(bpos.size());
for (auto& l : blen) {
l = lerp(params.length_min, params.length_max, rand1f(rng));
}
auto cidx = vector<int>();
if (params.clump_strength > 0) {
for (auto bidx = 0; bidx < bpos.size(); bidx++) {
cidx.push_back(0);
auto cdist = flt_max;
for (auto c = 0; c < params.clump_num; c++) {
auto d = length(bpos[bidx] - bpos[c]);
if (d < cdist) {
cdist = d;
cidx.back() = c;
}
}
}
}
auto steps = pow2(params.subdivisions);
make_lines(lines, positions, normals, texcoords, radius, params.num,
params.subdivisions, {1, 1}, {1, 1}, {1, 1});
for (auto i = 0; i < positions.size(); i++) {
auto u = texcoords[i].x;
auto bidx = i / (steps + 1);
positions[i] = bpos[bidx] + bnorm[bidx] * u * blen[bidx];
normals[i] = bnorm[bidx];
radius[i] = lerp(params.radius_base, params.radius_tip, u);
if (params.clump_strength > 0) {
positions[i] =
positions[i] +
(positions[i + (cidx[bidx] - bidx) * (steps + 1)] - positions[i]) *
u * params.clump_strength;
}
if (params.noise_strength > 0) {
auto nx = perlin_noise(
positions[i] * params.noise_scale + vec3f{0, 0, 0}) *
params.noise_strength;
auto ny = perlin_noise(
positions[i] * params.noise_scale + vec3f{3, 7, 11}) *
params.noise_strength;
auto nz = perlin_noise(
positions[i] * params.noise_scale + vec3f{13, 17, 19}) *
params.noise_strength;
positions[i] += {nx, ny, nz};
}
}
if (params.clump_strength > 0 || params.noise_strength > 0 ||
params.rotation_strength > 0) {
compute_tangents(normals, lines, positions);
}
}
// Thickens a shape by copy9ing the shape content, rescaling it and flipping
// its normals. Note that this is very much not robust and only useful for
// trivial cases.
void make_shell(vector<vec4i>& quads, vector<vec3f>& positions,
vector<vec3f>& normals, vector<vec2f>& texcoords, float thickness) {
auto bbox = invalidb3f;
for (auto p : positions) bbox = merge(bbox, p);
auto center = yocto::center(bbox);
auto inner_quads = quads;
auto inner_positions = positions;
auto inner_normals = normals;
auto inner_texturecoords = texcoords;
for (auto& p : inner_positions) p = (1 - thickness) * (p - center) + center;
for (auto& n : inner_normals) n = -n;
merge_quads(quads, positions, normals, texcoords, inner_quads,
inner_positions, inner_normals, inner_texturecoords);
}
// Shape presets used ofr testing.
void make_shape_preset(vector<int>& points, vector<vec2i>& lines,
vector<vec3i>& triangles, vector<vec4i>& quads, vector<vec4i>& quadspos,
vector<vec4i>& quadsnorm, vector<vec4i>& quadstexcoord,
vector<vec3f>& positions, vector<vec3f>& normals, vector<vec2f>& texcoords,
vector<vec4f>& colors, vector<float>& radius, const string& type) {
if (type == "default-quad") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::quad;
make_proc_shape(triangles, quads, positions, normals, texcoords, params);
} else if (type == "default-quady") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::quad;
make_proc_shape(triangles, quads, positions, normals, texcoords, params);
} else if (type == "default-cube") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::cube;
make_proc_shape(triangles, quads, positions, normals, texcoords, params);
} else if (type == "default-cube-rounded") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::cube;
params.rounded = 0.15;
make_proc_shape(triangles, quads, positions, normals, texcoords, params);
} else if (type == "default-sphere") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::sphere;
params.subdivisions = 5;
make_proc_shape(triangles, quads, positions, normals, texcoords, params);
} else if (type == "default-disk") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::disk;
params.subdivisions = 5;
make_proc_shape(triangles, quads, positions, normals, texcoords, params);
} else if (type == "default-disk-bulged") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::disk;
params.subdivisions = 5;
params.rounded = 0.25;
make_proc_shape(triangles, quads, positions, normals, texcoords, params);
} else if (type == "default-quad-bulged") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::quad;
params.subdivisions = 5;
params.rounded = 0.25;
make_proc_shape(triangles, quads, positions, normals, texcoords, params);
} else if (type == "default-uvsphere") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::uvsphere;
params.subdivisions = 5;
make_proc_shape(triangles, quads, positions, normals, texcoords, params);
} else if (type == "default-uvsphere-flipcap") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::uvsphere;
params.subdivisions = 5;
params.rounded = 0.75;
make_proc_shape(triangles, quads, positions, normals, texcoords, params);
} else if (type == "default-uvdisk") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::uvdisk;
params.subdivisions = 4;
make_proc_shape(triangles, quads, positions, normals, texcoords, params);
} else if (type == "default-uvcylinder") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::uvcylinder;
params.subdivisions = 5;
make_proc_shape(triangles, quads, positions, normals, texcoords, params);
} else if (type == "default-uvcylinder-rounded") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::uvcylinder;
params.subdivisions = 5;
params.rounded = 0.075;
make_proc_shape(triangles, quads, positions, normals, texcoords, params);
} else if (type == "default-geosphere") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::geosphere;
params.subdivisions = 5;
make_proc_shape(triangles, quads, positions, normals, texcoords, params);
} else if (type == "default-floor") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::floor;
params.scale = 20;
params.uvscale = 20;
params.subdivisions = 1;
make_proc_shape(triangles, quads, positions, normals, texcoords, params);
} else if (type == "default-floor-bent") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::floor;
params.scale = 20;
params.uvscale = 20;
params.subdivisions = 5;
params.rounded = 0.5;
make_proc_shape(triangles, quads, positions, normals, texcoords, params);
} else if (type == "default-matball") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::matball;
params.subdivisions = 5;
make_proc_shape(triangles, quads, positions, normals, texcoords, params);
} else if (type == "default-hairball") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::sphere;
params.subdivisions = 5;
params.scale = 0.8f;
auto base_triangles = vector<vec3i>{};
auto base_quads = vector<vec4i>{};
auto base_positions = vector<vec3f>{};
auto base_normals = vector<vec3f>{};
auto base_texcoords = vector<vec2f>{};
make_proc_shape(base_triangles, base_quads, base_positions, base_normals,
base_texcoords, params);
auto hparams = hair_params{};
hparams.subdivisions = 2;
hparams.num = 65536;
hparams.length_min = 0.2;
hparams.length_max = 0.2;
hparams.radius_base = 0.002;
hparams.radius_tip = 0.001;
make_hair(lines, positions, normals, texcoords, radius, base_triangles,
base_quads, base_positions, base_normals, base_texcoords, hparams);
} else if (type == "default-hairball-interior") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::sphere;
params.subdivisions = 5;
params.scale = 0.8f;
make_proc_shape(triangles, quads, positions, normals, texcoords, params);
} else if (type == "default-suzanne") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::suzanne;
make_proc_shape(triangles, quads, positions, normals, texcoords, params);
} else if (type == "default-cube-facevarying") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::cube;
make_proc_fvshape(quadspos, quadsnorm, quadstexcoord, positions, normals,
texcoords, params);
} else if (type == "default-sphere-facevarying") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::sphere;
params.subdivisions = 5;
make_proc_fvshape(quadspos, quadsnorm, quadstexcoord, positions, normals,
texcoords, params);
} else if (type == "test-cube") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::cube;
params.subdivisions = 5;
params.scale = 0.075;
params.rounded = 0.3;
params.frame = frame3f{{0, 0.075, 0}};
make_proc_shape(triangles, quads, positions, normals, texcoords, params);
} else if (type == "test-uvsphere") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::uvsphere;
params.subdivisions = 5;
params.scale = 0.075;
params.frame = frame3f{{0, 0.075, 0}};
make_proc_shape(triangles, quads, positions, normals, texcoords, params);
} else if (type == "test-uvsphere-flipcap") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::uvsphere;
params.subdivisions = 5;
params.scale = 0.075;
params.rounded = 0.3;
params.frame = frame3f{{0, 0.075, 0}};
make_proc_shape(triangles, quads, positions, normals, texcoords, params);
} else if (type == "test-sphere") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::sphere;
params.subdivisions = 5;
params.scale = 0.075;
params.frame = frame3f{{0, 0.075, 0}};
make_proc_shape(triangles, quads, positions, normals, texcoords, params);
} else if (type == "test-sphere-displaced") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::sphere;
params.subdivisions = 7;
params.scale = 0.075;
params.frame = frame3f{{0, 0.075, 0}};
make_proc_shape(triangles, quads, positions, normals, texcoords, params);
} else if (type == "test-disk") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::disk;
params.subdivisions = 5;
params.scale = 0.075;
params.frame = frame3f{{0, 0.075, 0}};
make_proc_shape(triangles, quads, positions, normals, texcoords, params);
} else if (type == "test-uvcylinder") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::uvcylinder;
params.subdivisions = 5;
params.scale = 0.075;
params.rounded = 0.3;
params.frame = frame3f{{0, 0.075, 0}};
make_proc_shape(triangles, quads, positions, normals, texcoords, params);
} else if (type == "test-floor") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::floor;
params.subdivisions = 0;
params.scale = 2;
params.uvscale = 20;
params.frame = identity3x4f;
make_proc_shape(triangles, quads, positions, normals, texcoords, params);
} else if (type == "test-matball") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::matball;
params.subdivisions = 5;
params.scale = 0.075;
params.frame = frame3f{{0, 0.075, 0}};
make_proc_shape(triangles, quads, positions, normals, texcoords, params);
} else if (type == "test-hairball1") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::sphere;
params.subdivisions = 5;
params.scale = 0.075f * 0.8f;
params.frame = frame3f{{0, 0.075, 0}};
auto base_triangles = vector<vec3i>{};
auto base_quads = vector<vec4i>{};
auto base_positions = vector<vec3f>{};
auto base_normals = vector<vec3f>{};
auto base_texcoords = vector<vec2f>{};
make_proc_shape(base_triangles, base_quads, base_positions, base_normals,
base_texcoords, params);
auto hparams = hair_params{};
hparams.num = 65536;
hparams.subdivisions = 2;
hparams.length_min = 0.1f * 0.15f;
hparams.length_max = 0.1f * 0.15f;
hparams.radius_base = 0.001f * 0.15f;
hparams.radius_tip = 0.0005f * 0.15f;
hparams.noise_strength = 0.03f;
hparams.noise_scale = 100;
make_hair(lines, positions, normals, texcoords, radius, base_triangles,
base_quads, base_positions, base_normals, base_texcoords, hparams);
} else if (type == "test-hairball2") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::sphere;
params.subdivisions = 5;
params.scale = 0.075f * 0.8f;
params.frame = frame3f{{0, 0.075, 0}};
auto base_triangles = vector<vec3i>{};
auto base_quads = vector<vec4i>{};
auto base_positions = vector<vec3f>{};
auto base_normals = vector<vec3f>{};
auto base_texcoords = vector<vec2f>{};
make_proc_shape(base_triangles, base_quads, base_positions, base_normals,
base_texcoords, params);
auto hparams = hair_params{};
hparams.num = 65536;
hparams.subdivisions = 2;
hparams.length_min = 0.1f * 0.15f;
hparams.length_max = 0.1f * 0.15f;
hparams.radius_base = 0.001f * 0.15f;
hparams.radius_tip = 0.0005f * 0.15f;
make_hair(lines, positions, normals, texcoords, radius, base_triangles,
base_quads, base_positions, base_normals, base_texcoords, hparams);
} else if (type == "test-hairball3") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::sphere;
params.subdivisions = 5;
params.scale = 0.075f * 0.8f;
params.frame = frame3f{{0, 0.075, 0}};
auto base_triangles = vector<vec3i>{};
auto base_quads = vector<vec4i>{};
auto base_positions = vector<vec3f>{};
auto base_normals = vector<vec3f>{};
auto base_texcoords = vector<vec2f>{};
make_proc_shape(base_triangles, base_quads, base_positions, base_normals,
base_texcoords, params);
auto hparams = hair_params{};
hparams.num = 65536;
hparams.subdivisions = 2;
hparams.length_min = 0.1f * 0.15f;
hparams.length_max = 0.1f * 0.15f;
hparams.radius_base = 0.001f * 0.15f;
hparams.radius_tip = 0.0005f * 0.15f;
hparams.clump_strength = 0.5f;
hparams.clump_num = 128;
make_hair(lines, positions, normals, texcoords, radius, base_triangles,
base_quads, base_positions, base_normals, base_texcoords, hparams);
} else if (type == "test-hairball-interior") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::sphere;
params.subdivisions = 5;
params.scale = 0.075f * 0.8f;
params.frame = frame3f{{0, 0.075, 0}};
make_proc_shape(triangles, quads, positions, normals, texcoords, params);
} else if (type == "test-suzanne-subdiv") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::suzanne;
params.scale = 0.075f * 0.8f;
params.frame = frame3f{{0, 0.075, 0}};
make_proc_shape(triangles, quads, positions, normals, texcoords, params);
} else if (type == "test-cube-subdiv") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::cube;
params.scale = 0.075;
params.frame = frame3f{{0, 0.075, 0}};
make_proc_fvshape(quadspos, quadsnorm, quadstexcoord, positions, normals,
texcoords, params);
} else if (type == "test-arealight1") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::quad;
params.scale = 0.2;
make_proc_shape(triangles, quads, positions, normals, texcoords, params);
} else if (type == "test-arealight2") {
auto params = proc_shape_params{};
params.type = proc_shape_params::type_t::quad;
params.scale = 0.2;
make_proc_shape(triangles, quads, positions, normals, texcoords, params);
} else {
throw std::invalid_argument("unknown shape preset " + type);
}
}
} // namespace yocto
// -----------------------------------------------------------------------------
// IMPLEMENTATION OF SHAPE IO
// -----------------------------------------------------------------------------
namespace yocto {
// hack for CyHair data
static void load_cyhair_shape(const string& filename, vector<vec2i>& lines,
vector<vec3f>& positions, vector<vec3f>& normals, vector<vec2f>& texcoords,
vector<vec4f>& color, vector<float>& radius, bool flip_texcoord = true);
// Load/Save a ply mesh
static void load_ply_shape(const string& filename, vector<int>& points,
vector<vec2i>& lines, vector<vec3i>& triangles, vector<vec4i>& quads,
vector<vec4i>& quadspos, vector<vec4i>& quadsnorm,
vector<vec4i>& quadstexcoord, vector<vec3f>& positions,
vector<vec3f>& normals, vector<vec2f>& texcoords, vector<vec4f>& color,
vector<float>& radius, bool flip_texcoord = true);
static void save_ply_shape(const string& filename, const vector<int>& points,
const vector<vec2i>& lines, const vector<vec3i>& triangles,
const vector<vec4i>& quads, const vector<vec4i>& quadspos,
const vector<vec4i>& quadsnorm, const vector<vec4i>& quadstexcoord,
const vector<vec3f>& positions, const vector<vec3f>& normals,
const vector<vec2f>& texcoords, const vector<vec4f>& colors,
const vector<float>& radius, bool ascii = false, bool flip_texcoord = true);
// Load/Save an OBJ mesh
static void load_obj_shape(const string& filename, vector<int>& points,
vector<vec2i>& lines, vector<vec3i>& triangles, vector<vec4i>& quads,
vector<vec4i>& quadspos, vector<vec4i>& quadsnorm,
vector<vec4i>& quadstexcoord, vector<vec3f>& positions,
vector<vec3f>& normals, vector<vec2f>& texcoords, bool facevarying,
bool flip_texcoord = true);
static void save_obj_shape(const string& filename, const vector<int>& points,
const vector<vec2i>& lines, const vector<vec3i>& triangles,
const vector<vec4i>& quads, const vector<vec4i>& quadspos,
const vector<vec4i>& quadsnorm, const vector<vec4i>& quadstexcoord,
const vector<vec3f>& positions, const vector<vec3f>& normals,
const vector<vec2f>& texcoords, bool flip_texcoord = true);
// Load ply mesh
void load_shape(const string& filename, vector<int>& points,
vector<vec2i>& lines, vector<vec3i>& triangles, vector<vec4i>& quads,
vector<vec4i>& quadspos, vector<vec4i>& quadsnorm,
vector<vec4i>& quadstexcoord, vector<vec3f>& positions,
vector<vec3f>& normals, vector<vec2f>& texcoords, vector<vec4f>& colors,
vector<float>& radius, bool preserve_facevarrying) {
points = {};
lines = {};
triangles = {};
quads = {};
quadspos = {};
quadsnorm = {};
quadstexcoord = {};
positions = {};
normals = {};
texcoords = {};
colors = {};
radius = {};
auto ext = fs::path(filename).extension().string();
if (ext == ".ply" || ext == ".PLY") {
load_ply_shape(filename, points, lines, triangles, quads, quadspos,
quadsnorm, quadstexcoord, positions, normals, texcoords, colors,
radius);
} else if (ext == ".obj" || ext == ".OBJ") {
load_obj_shape(filename, points, lines, triangles, quads, quadspos,
quadsnorm, quadstexcoord, positions, normals, texcoords,
preserve_facevarrying);
} else if (ext == ".hair" || ext == ".HAIR") {
load_cyhair_shape(
filename, lines, positions, normals, texcoords, colors, radius);
} else {
throw std::runtime_error("unsupported mesh type " + ext);
}
}
// Save ply mesh
void save_shape(const string& filename, const vector<int>& points,
const vector<vec2i>& lines, const vector<vec3i>& triangles,
const vector<vec4i>& quads, const vector<vec4i>& quadspos,
const vector<vec4i>& quadsnorm, const vector<vec4i>& quadstexcoord,
const vector<vec3f>& positions, const vector<vec3f>& normals,
const vector<vec2f>& texcoords, const vector<vec4f>& colors,
const vector<float>& radius, bool ascii) {
auto ext = fs::path(filename).extension().string();
if (ext == ".ply" || ext == ".PLY") {
return save_ply_shape(filename, points, lines, triangles, quads, quadspos,
quadsnorm, quadstexcoord, positions, normals, texcoords, colors, radius,
ascii);
} else if (ext == ".obj" || ext == ".OBJ") {
return save_obj_shape(filename, points, lines, triangles, quads, quadspos,
quadsnorm, quadstexcoord, positions, normals, texcoords);
} else {
throw std::runtime_error("unsupported mesh type " + ext);
}
}
static void load_ply_shape(const string& filename, vector<int>& points,
vector<vec2i>& lines, vector<vec3i>& triangles, vector<vec4i>& quads,
vector<vec4i>& quadspos, vector<vec4i>& quadsnorm,
vector<vec4i>& quadstexcoord, vector<vec3f>& positions,
vector<vec3f>& normals, vector<vec2f>& texcoords, vector<vec4f>& colors,
vector<float>& radius, bool flip_texcoord) {
try {
// load ply
happly::PLYData ply(filename);
// copy vertex data
if (ply.hasElement("vertex")) {
auto& vertex = ply.getElement("vertex");
if (vertex.hasProperty("x") && vertex.hasProperty("y") &&
vertex.hasProperty("z")) {
auto x = vertex.getProperty<float>("x");
auto y = vertex.getProperty<float>("y");
auto z = vertex.getProperty<float>("z");
positions.resize(x.size());
for (auto i = 0; i < positions.size(); i++) {
positions[i] = {x[i], y[i], z[i]};
}
} else {
throw std::runtime_error("vertex positions not present");
}
if (vertex.hasProperty("nx") && vertex.hasProperty("ny") &&
vertex.hasProperty("nz")) {
auto x = vertex.getProperty<float>("nx");
auto y = vertex.getProperty<float>("ny");
auto z = vertex.getProperty<float>("nz");
normals.resize(x.size());
for (auto i = 0; i < normals.size(); i++) {
normals[i] = {x[i], y[i], z[i]};
}
}
if (vertex.hasProperty("u") && vertex.hasProperty("v")) {
auto x = vertex.getProperty<float>("u");
auto y = vertex.getProperty<float>("v");
texcoords.resize(x.size());
for (auto i = 0; i < texcoords.size(); i++) {
texcoords[i] = {x[i], y[i]};
}
}
if (vertex.hasProperty("s") && vertex.hasProperty("t")) {
auto x = vertex.getProperty<float>("s");
auto y = vertex.getProperty<float>("t");
texcoords.resize(x.size());
for (auto i = 0; i < texcoords.size(); i++) {
texcoords[i] = {x[i], y[i]};
}
}
if (vertex.hasProperty("red") && vertex.hasProperty("green") &&
vertex.hasProperty("blue")) {
auto x = vertex.getProperty<float>("red");
auto y = vertex.getProperty<float>("green");
auto z = vertex.getProperty<float>("blue");
colors.resize(x.size());
for (auto i = 0; i < colors.size(); i++) {
colors[i] = {x[i], y[i], z[i], 1};
}
if (vertex.hasProperty("alpha")) {
auto w = vertex.getProperty<float>("alpha");
for (auto i = 0; i < colors.size(); i++) {
colors[i].w = w[i];
}
}
}
if (vertex.hasProperty("radius")) {
radius = vertex.getProperty<float>("radius");
}
}
// fix texture coordinated
if (flip_texcoord && !texcoords.empty()) {
for (auto& uv : texcoords) uv.y = 1 - uv.y;
}
// copy face data
if (ply.hasElement("face")) {
auto& elements = ply.getElement("face");
if (!elements.hasProperty("vertex_indices"))
throw std::runtime_error("bad ply faces");
auto indices = vector<vector<int>>{};
try {
indices = elements.getListProperty<int>("vertex_indices");
} catch (...) {
(vector<vector<unsigned int>>&)indices =
elements.getListProperty<unsigned int>("vertex_indices");
}
for (auto& face : indices) {
if (face.size() == 4) {
quads.push_back({face[0], face[1], face[2], face[3]});
} else {
for (auto i = 2; i < face.size(); i++)
triangles.push_back({face[0], face[i - 1], face[i]});
}
}
}
// copy face data
if (ply.hasElement("line")) {
auto& elements = ply.getElement("line");
if (!elements.hasProperty("vertex_indices"))
throw std::runtime_error("bad ply lines");
auto indices = vector<vector<int>>{};
try {
indices = elements.getListProperty<int>("vertex_indices");
} catch (...) {
(vector<vector<unsigned int>>&)indices =
elements.getListProperty<unsigned int>("vertex_indices");
}
for (auto& line : indices) {
for (auto i = 1; i < line.size(); i++)
lines.push_back({line[i], line[i - 1]});
}
}
merge_triangles_and_quads(triangles, quads, false);
} catch (const std::exception& e) {
throw std::runtime_error("cannot load mesh " + filename + "\n" + e.what());
}
}
// Save ply mesh
static void save_ply_shape(const string& filename, const vector<int>& points,
const vector<vec2i>& lines, const vector<vec3i>& triangles,
const vector<vec4i>& quads, const vector<vec4i>& quadspos,
const vector<vec4i>& quadsnorm, const vector<vec4i>& quadstexcoord,
const vector<vec3f>& positions, const vector<vec3f>& normals,
const vector<vec2f>& texcoords, const vector<vec4f>& colors,
const vector<float>& radius, bool ascii, bool flip_texcoord) {
if (!quadspos.empty()) {
auto split_quads = vector<vec4i>{};
auto split_positions = vector<vec3f>{};
auto split_normals = vector<vec3f>{};
auto split_texturecoords = vector<vec2f>{};
split_facevarying(split_quads, split_positions, split_normals,
split_texturecoords, quadspos, quadsnorm, quadstexcoord, positions,
normals, texcoords);
return save_ply_shape(filename, {}, {}, {}, split_quads, {}, {}, {},
split_positions, split_normals, split_texturecoords, {}, {}, ascii,
flip_texcoord);
}
// empty data
happly::PLYData ply;
ply.comments.push_back("Written by Yocto/GL");
ply.comments.push_back("https://github.com/xelatihy/yocto-gl");
// add elements
ply.addElement("vertex", positions.size());
if (!positions.empty()) {
auto& vertex = ply.getElement("vertex");
auto x = vector<float>{};
auto y = vector<float>{};
auto z = vector<float>{};
for (auto& p : positions) {
x.push_back(p.x);
y.push_back(p.y);
z.push_back(p.z);
}
vertex.addProperty("x", x);
vertex.addProperty("y", y);
vertex.addProperty("z", z);
}
if (!normals.empty()) {
auto& vertex = ply.getElement("vertex");
auto x = vector<float>{};
auto y = vector<float>{};
auto z = vector<float>{};
for (auto& n : normals) {
x.push_back(n.x);
y.push_back(n.y);
z.push_back(n.z);
}
vertex.addProperty("nx", x);
vertex.addProperty("ny", y);
vertex.addProperty("nz", z);
}
if (!texcoords.empty()) {
auto& vertex = ply.getElement("vertex");
auto x = vector<float>{};
auto y = vector<float>{};
for (auto& t : texcoords) {
x.push_back(t.x);
y.push_back(flip_texcoord ? 1 - t.y : t.y);
}
vertex.addProperty("u", x);
vertex.addProperty("v", y);
}
if (!colors.empty()) {
auto& vertex = ply.getElement("vertex");
auto x = vector<float>{};
auto y = vector<float>{};
auto z = vector<float>{};
auto w = vector<float>{};
for (auto& c : colors) {
x.push_back(c.x);
y.push_back(c.y);
z.push_back(c.z);
w.push_back(c.w);
}
vertex.addProperty("red", x);
vertex.addProperty("green", y);
vertex.addProperty("blue", z);
vertex.addProperty("alpha", w);
}
if (!radius.empty()) {
auto& vertex = ply.getElement("vertex");
vertex.addProperty("radius", radius);
}
// face date
if (!triangles.empty() || !quads.empty()) {
ply.addElement("face", triangles.size() + quads.size());
auto elements = vector<vector<int>>{};
for (auto& t : triangles) {
elements.push_back({t.x, t.y, t.z});
}
for (auto& q : quads) {
if (q.z == q.w) {
elements.push_back({q.x, q.y, q.z});
} else {
elements.push_back({q.x, q.y, q.z, q.w});
}
}
ply.getElement("face").addListProperty("vertex_indices", elements);
}
if (!lines.empty()) {
ply.addElement("line", lines.size());
auto elements = vector<vector<int>>{};
for (auto& l : lines) {
elements.push_back({l.x, l.y});
}
ply.getElement("line").addListProperty("vertex_indices", elements);
}
if (!points.empty() || !quads.empty()) {
ply.addElement("point", points.size());
auto elements = vector<vector<int>>{};
for (auto& p : points) {
elements.push_back({p});
}
ply.getElement("point").addListProperty("vertex_indices", elements);
}
// Write our data
try {
ply.write(filename,
ascii ? happly::DataFormat::ASCII : happly::DataFormat::Binary);
} catch (const std::exception& e) {
throw std::runtime_error("cannot save mesh " + filename + "\n" + e.what());
}
}
struct load_obj_shape_cb : obj_callbacks {
vector<int>& points;
vector<vec2i>& lines;
vector<vec3i>& triangles;
vector<vec4i>& quads;
vector<vec4i>& quadspos;
vector<vec4i>& quadsnorm;
vector<vec4i>& quadstexcoord;
vector<vec3f>& positions;
vector<vec3f>& normals;
vector<vec2f>& texcoords;
bool facevarying = false;
// TODO: implement me
// obj vertices
std::deque<vec3f> opos = std::deque<vec3f>();
std::deque<vec3f> onorm = std::deque<vec3f>();
std::deque<vec2f> otexcoord = std::deque<vec2f>();
// vertex maps
unordered_map<obj_vertex, int> vertex_map = unordered_map<obj_vertex, int>();
// vertex maps
unordered_map<int, int> pos_map = unordered_map<int, int>();
unordered_map<int, int> texcoord_map = unordered_map<int, int>();
unordered_map<int, int> norm_map = unordered_map<int, int>();
load_obj_shape_cb(vector<int>& points, vector<vec2i>& lines,
vector<vec3i>& triangles, vector<vec4i>& quads, vector<vec4i>& quadspos,
vector<vec4i>& quadsnorm, vector<vec4i>& quadstexcoord,
vector<vec3f>& positions, vector<vec3f>& normals,
vector<vec2f>& texcoords, bool facevarying)
: points{points}
, lines{lines}
, triangles{triangles}
, quads{quads}
, quadspos{quadspos}
, quadsnorm{quadsnorm}
, quadstexcoord{quadstexcoord}
, positions{positions}
, normals{normals}
, texcoords{texcoords}
, facevarying{facevarying} {}
// Add vertices to the current shape
void add_verts(const vector<obj_vertex>& verts) {
for (auto& vert : verts) {
auto it = vertex_map.find(vert);
if (it != vertex_map.end()) continue;
auto nverts = (int)positions.size();
vertex_map.insert(it, {vert, nverts});
if (vert.position) positions.push_back(opos.at(vert.position - 1));
if (vert.texcoord) texcoords.push_back(otexcoord.at(vert.texcoord - 1));
if (vert.normal) normals.push_back(onorm.at(vert.normal - 1));
}
}
// add vertex
void add_fvverts(const vector<obj_vertex>& verts) {
for (auto& vert : verts) {
if (!vert.position) continue;
auto pos_it = pos_map.find(vert.position);
if (pos_it != pos_map.end()) continue;
auto nverts = (int)positions.size();
pos_map.insert(pos_it, {vert.position, nverts});
positions.push_back(opos.at(vert.position - 1));
}
for (auto& vert : verts) {
if (!vert.texcoord) continue;
auto texcoord_it = texcoord_map.find(vert.texcoord);
if (texcoord_it != texcoord_map.end()) continue;
auto nverts = (int)texcoords.size();
texcoord_map.insert(texcoord_it, {vert.texcoord, nverts});
texcoords.push_back(otexcoord.at(vert.texcoord - 1));
}
for (auto& vert : verts) {
if (!vert.normal) continue;
auto norm_it = norm_map.find(vert.normal);
if (norm_it != norm_map.end()) continue;
auto nverts = (int)normals.size();
norm_map.insert(norm_it, {vert.normal, nverts});
normals.push_back(onorm.at(vert.normal - 1));
}
}
void vert(const vec3f& v) override { opos.push_back(v); }
void norm(const vec3f& v) override { onorm.push_back(v); }
void texcoord(const vec2f& v) override { otexcoord.push_back(v); }
void face(const vector<obj_vertex>& verts) override {
if (!facevarying) {
add_verts(verts);
if (verts.size() == 4) {
quads.push_back({vertex_map.at(verts[0]), vertex_map.at(verts[1]),
vertex_map.at(verts[2]), vertex_map.at(verts[3])});
} else {
for (auto i = 2; i < verts.size(); i++)
triangles.push_back({vertex_map.at(verts[0]),
vertex_map.at(verts[i - 1]), vertex_map.at(verts[i])});
}
} else {
add_fvverts(verts);
if (verts.size() == 4) {
if (verts[0].position) {
quadspos.push_back({pos_map.at(verts[0].position),
pos_map.at(verts[1].position), pos_map.at(verts[2].position),
pos_map.at(verts[3].position)});
}
if (verts[0].texcoord) {
quadstexcoord.push_back({texcoord_map.at(verts[0].texcoord),
texcoord_map.at(verts[1].texcoord),
texcoord_map.at(verts[2].texcoord),
texcoord_map.at(verts[3].texcoord)});
}
if (verts[0].normal) {
quadsnorm.push_back(
{norm_map.at(verts[0].normal), norm_map.at(verts[1].normal),
norm_map.at(verts[2].normal), norm_map.at(verts[3].normal)});
}
// quads_materials.push_back(current_material_id);
} else {
if (verts[0].position) {
for (auto i = 2; i < verts.size(); i++)
quadspos.push_back({pos_map.at(verts[0].position),
pos_map.at(verts[1].position), pos_map.at(verts[i].position),
pos_map.at(verts[i].position)});
}
if (verts[0].texcoord) {
for (auto i = 2; i < verts.size(); i++)
quadstexcoord.push_back({texcoord_map.at(verts[0].texcoord),
texcoord_map.at(verts[1].texcoord),
texcoord_map.at(verts[i].texcoord),
texcoord_map.at(verts[i].texcoord)});
}
if (verts[0].normal) {
for (auto i = 2; i < verts.size(); i++)
quadsnorm.push_back({norm_map.at(verts[0].normal),
norm_map.at(verts[1].normal), norm_map.at(verts[i].normal),
norm_map.at(verts[i].normal)});
}
// for (auto i = 2; i < verts.size();
// i++)
// quads_materials.push_back(current_material_id);
}
}
}
void line(const vector<obj_vertex>& verts) override {
add_verts(verts);
for (auto i = 1; i < verts.size(); i++)
lines.push_back({vertex_map.at(verts[i - 1]), vertex_map.at(verts[i])});
}
void point(const vector<obj_vertex>& verts) override {
add_verts(verts);
for (auto i = 0; i < verts.size(); i++)
points.push_back(vertex_map.at(verts[i]));
}
// void usemtl(const string& name) {
// auto pos = std::find(
// material_group.begin(),
// material_group.end(), name);
// if (pos == material_group.end()) {
// material_group.push_back(name);
// current_material_id = (int)material_group.size() - 1;
// } else {
// current_material_id = (int)(pos -
// material_group.begin());
// }
// }
};
// Load ply mesh
static void load_obj_shape(const string& filename, vector<int>& points,
vector<vec2i>& lines, vector<vec3i>& triangles, vector<vec4i>& quads,
vector<vec4i>& quadspos, vector<vec4i>& quadsnorm,
vector<vec4i>& quadstexcoord, vector<vec3f>& positions,
vector<vec3f>& normals, vector<vec2f>& texcoords, bool facevarying,
bool flip_texcoord) {
try {
// load obj
auto cb = load_obj_shape_cb{points, lines, triangles, quads, quadspos,
quadsnorm, quadstexcoord, positions, normals, texcoords, facevarying};
load_obj(filename, cb, true, flip_texcoord);
// merging quads and triangles
if (!facevarying) {
merge_triangles_and_quads(triangles, quads, false);
}
} catch (const std::exception& e) {
throw std::runtime_error("cannot load mesh " + filename + "\n" + e.what());
}
}
// A file holder that closes a file when destructed. Useful for RIIA
struct file_holder {
FILE* fs = nullptr;
string filename = "";
file_holder(const file_holder&) = delete;
file_holder& operator=(const file_holder&) = delete;
~file_holder() {
if (fs) fclose(fs);
}
};
// Opens a file returing a handle with RIIA
static inline file_holder open_input_file(
const string& filename, bool binary = false) {
auto fs = fopen(filename.c_str(), !binary ? "rt" : "rb");
if (!fs) throw std::runtime_error("could not open file " + filename);
return {fs, filename};
}
static inline file_holder open_output_file(
const string& filename, bool binary = false) {
auto fs = fopen(filename.c_str(), !binary ? "wt" : "wb");
if (!fs) throw std::runtime_error("could not open file " + filename);
return {fs, filename};
}
// Write text to file
static inline void write_obj_value(FILE* fs, float value) {
if (fprintf(fs, "%g", value) < 0)
throw std::runtime_error("cannot print value");
}
static inline void write_obj_text(FILE* fs, const char* value) {
if (fprintf(fs, "%s", value) < 0)
throw std::runtime_error("cannot print value");
}
static inline void write_obj_value(FILE* fs, const char* value) {
if (fprintf(fs, "%s", value) < 0)
throw std::runtime_error("cannot print value");
}
static void write_obj_value(FILE* fs, const obj_vertex& value) {
if (fprintf(fs, "%d", value.position) < 0)
throw std::runtime_error("cannot write value");
if (value.texcoord) {
if (fprintf(fs, "/%d", value.texcoord) < 0)
throw std::runtime_error("cannot write value");
if (value.normal) {
if (fprintf(fs, "/%d", value.normal) < 0)
throw std::runtime_error("cannot write value");
}
} else if (value.normal) {
if (fprintf(fs, "//%d", value.normal) < 0)
throw std::runtime_error("cannot write value");
}
}
template <typename T, typename... Ts>
static inline void write_obj_line(
FILE* fs, const T& value, const Ts... values) {
write_obj_value(fs, value);
if constexpr (sizeof...(values) == 0) {
write_obj_text(fs, "\n");
} else {
write_obj_text(fs, " ");
write_obj_line(fs, values...);
}
}
// Load ply mesh
static void save_obj_shape(const string& filename, const vector<int>& points,
const vector<vec2i>& lines, const vector<vec3i>& triangles,
const vector<vec4i>& quads, const vector<vec4i>& quadspos,
const vector<vec4i>& quadsnorm, const vector<vec4i>& quadstexcoord,
const vector<vec3f>& positions, const vector<vec3f>& normals,
const vector<vec2f>& texcoords, bool flip_texcoord) {
// open file
auto fs_ = open_output_file(filename);
auto fs = fs_.fs;
write_obj_text(fs, "#\n");
write_obj_text(fs, "# Written by Yocto/GL\n");
write_obj_text(fs, "# https://github.com/xelatihy/yocto-gl\n");
write_obj_text(fs, "#\n");
for (auto& p : positions) write_obj_line(fs, "v", p.x, p.y, p.z);
for (auto& n : normals) write_obj_line(fs, "vn", n.x, n.y, n.z);
for (auto& t : texcoords)
write_obj_line(fs, "vt", t.x, (flip_texcoord) ? 1 - t.y : t.y);
auto mask = obj_vertex{1, texcoords.empty() ? 0 : 1, normals.empty() ? 0 : 1};
auto vert = [mask](int i) {
return obj_vertex{(i + 1) * mask.position, (i + 1) * mask.texcoord,
(i + 1) * mask.normal};
};
for (auto& p : points) {
write_obj_line(fs, "p", vert(p));
}
for (auto& l : lines) {
write_obj_line(fs, "l", vert(l.x), vert(l.y));
}
for (auto& t : triangles) {
write_obj_line(fs, "f", vert(t.x), vert(t.y), vert(t.z));
}
for (auto& q : quads) {
if (q.z == q.w) {
write_obj_line(fs, "f", vert(q.x), vert(q.y), vert(q.z));
} else {
write_obj_line(fs, "f", vert(q.x), vert(q.y), vert(q.z), vert(q.w));
}
}
auto fvmask = obj_vertex{
1, texcoords.empty() ? 0 : 1, normals.empty() ? 0 : 1};
auto fvvert = [fvmask](int pi, int ti, int ni) {
return obj_vertex{(pi + 1) * fvmask.position, (ti + 1) * fvmask.texcoord,
(ni + 1) * fvmask.normal};
};
// auto last_material_id = -1;
for (auto i = 0; i < quadspos.size(); i++) {
// if (!quads_materials.empty() &&
// quads_materials[i] != last_material_id) {
// last_material_id = quads_materials[i];
// println_values(fs, "usemtl material_{}\n",
// last_material_id);
// }
auto qp = quadspos.at(i);
auto qt = !quadstexcoord.empty() ? quadstexcoord.at(i)
: vec4i{-1, -1, -1, -1};
auto qn = !quadsnorm.empty() ? quadsnorm.at(i) : vec4i{-1, -1, -1, -1};
if (qp.z != qp.w) {
write_obj_line(fs, "f", fvvert(qp.x, qt.x, qn.x),
fvvert(qp.y, qt.y, qn.y), fvvert(qp.z, qt.z, qn.z),
fvvert(qp.w, qt.w, qn.w));
} else {
write_obj_line(fs, "f", fvvert(qp.x, qt.x, qn.x),
fvvert(qp.y, qt.y, qn.y), fvvert(qp.z, qt.z, qn.z));
}
}
}
} // namespace yocto
// -----------------------------------------------------------------------------
// IMPLEMENTATION OF CYHAIR
// -----------------------------------------------------------------------------
namespace yocto {
struct cyhair_strand {
vector<vec3f> positions;
vector<float> radius;
vector<float> transparency;
vector<vec3f> color;
};
struct cyhair_data {
vector<cyhair_strand> strands = {};
float default_thickness = 0;
float default_transparency = 0;
vec3f default_color = zero3f;
};
static void load_cyhair(const string& filename, cyhair_data& hair) {
// open file
hair = {};
auto fs_ = open_input_file(filename, true);
auto fs = fs_.fs;
// Bytes 0-3 Must be "HAIR" in ascii code (48 41 49 52)
// Bytes 4-7 Number of hair strands as unsigned int
// Bytes 8-11 Total number of points of all strands as unsigned int
// Bytes 12-15 Bit array of data in the file
// Bit-0 is 1 if the file has segments array.
// Bit-1 is 1 if the file has points array (this bit must be 1).
// Bit-2 is 1 if the file has radius array.
// Bit-3 is 1 if the file has transparency array.
// Bit-4 is 1 if the file has color array.
// Bit-5 to Bit-31 are reserved for future extension (must be 0).
// Bytes 16-19 Default number of segments of hair strands as unsigned int
// If the file does not have a segments array, this default value is used.
// Bytes 20-23 Default radius hair strands as float
// If the file does not have a radius array, this default value is used.
// Bytes 24-27 Default transparency hair strands as float
// If the file does not have a transparency array, this default value is
// used. Bytes 28-39 Default color hair strands as float array of size 3
// If the file does not have a radius array, this default value is used.
// Bytes 40-127 File information as char array of size 88 in ascii
auto read_value = [](FILE* fs, auto& value) {
if (fread(&value, sizeof(value), 1, fs) != 1) {
throw std::runtime_error("cannot read from file");
}
};
auto read_values = [](FILE* fs, auto& values) {
if (values.empty()) return;
if (fread(values.data(), sizeof(values[0]), values.size(), fs) !=
values.size()) {
throw std::runtime_error("cannot read from file");
}
};
// parse header
hair = cyhair_data{};
struct cyhair_header {
char magic[4] = {0};
unsigned int num_strands = 0;
unsigned int num_points = 0;
unsigned int flags = 0;
unsigned int default_segments = 0;
float default_thickness = 0;
float default_transparency = 0;
vec3f default_color = zero3f;
char info[88] = {0};
};
static_assert(sizeof(cyhair_header) == 128);
auto header = cyhair_header{};
read_value(fs, header);
if (header.magic[0] != 'H' || header.magic[1] != 'A' ||
header.magic[2] != 'I' || header.magic[3] != 'R')
throw std::runtime_error("bad cyhair header");
// set up data
hair.default_thickness = header.default_thickness;
hair.default_transparency = header.default_transparency;
hair.default_color = header.default_color;
hair.strands.resize(header.num_strands);
// get segments length
auto segments = vector<unsigned short>();
if (header.flags & 1) {
segments.resize(header.num_strands);
read_values(fs, segments);
} else {
segments.assign(header.num_strands, header.default_segments);
}
// check segment length
auto total_length = 0;
for (auto segment : segments) total_length += segment + 1;
if (total_length != header.num_points) {
throw std::runtime_error("bad cyhair file");
}
// read positions data
if (header.flags & 2) {
for (auto strand_id = 0; strand_id < header.num_strands; strand_id++) {
auto strand_size = (int)segments[strand_id] + 1;
hair.strands[strand_id].positions.resize(strand_size);
read_values(fs, hair.strands[strand_id].positions);
}
}
// read radius data
if (header.flags & 4) {
for (auto strand_id = 0; strand_id < header.num_strands; strand_id++) {
auto strand_size = (int)segments[strand_id] + 1;
hair.strands[strand_id].radius.resize(strand_size);
read_values(fs, hair.strands[strand_id].radius);
}
}
// read transparency data
if (header.flags & 8) {
for (auto strand_id = 0; strand_id < header.num_strands; strand_id++) {
auto strand_size = (int)segments[strand_id] + 1;
hair.strands[strand_id].transparency.resize(strand_size);
read_values(fs, hair.strands[strand_id].transparency);
}
}
// read color data
if (header.flags & 16) {
for (auto strand_id = 0; strand_id < header.num_strands; strand_id++) {
auto strand_size = (int)segments[strand_id] + 1;
hair.strands[strand_id].color.resize(strand_size);
read_values(fs, hair.strands[strand_id].color);
}
}
}
static void load_cyhair_shape(const string& filename, vector<vec2i>& lines,
vector<vec3f>& positions, vector<vec3f>& normals, vector<vec2f>& texcoords,
vector<vec4f>& color, vector<float>& radius, bool flip_texcoord) {
// load hair file
auto hair = cyhair_data();
load_cyhair(filename, hair);
// generate curve data
for (auto& strand : hair.strands) {
auto offset = (int)positions.size();
for (auto segment = 0; segment < (int)strand.positions.size() - 1;
segment++) {
lines.push_back({offset + segment, offset + segment + 1});
}
positions.insert(
positions.end(), strand.positions.begin(), strand.positions.end());
if (strand.radius.empty()) {
radius.insert(
radius.end(), strand.positions.size(), hair.default_thickness);
} else {
radius.insert(radius.end(), strand.radius.begin(), strand.radius.end());
}
if (strand.color.empty()) {
color.insert(color.end(), strand.positions.size(),
{hair.default_color.x, hair.default_color.y, hair.default_color.z,
1});
} else {
for (auto i = 0; i < strand.color.size(); i++) {
auto scolor = strand.color[i];
color.push_back({scolor.x, scolor.y, scolor.z, 1});
}
}
}
// flip yz
for (auto& p : positions) std::swap(p.y, p.z);
// compute tangents
normals.resize(positions.size());
compute_tangents(normals, lines, positions);
// fix colors
for (auto& c : color) c = {pow(xyz(c), 2.2f), c.w};
}
} // namespace yocto
// -----------------------------------------------------------------------------
// EMBEDDED SHAPE DATA
// -----------------------------------------------------------------------------
namespace yocto {
const vector<vec3f> quad_positions = vector<vec3f>{
{-1, -1, 0}, {+1, -1, 0}, {+1, +1, 0}, {-1, +1, 0}};
const vector<vec3f> quad_normals = vector<vec3f>{
{0, 0, 1}, {0, 0, 1}, {0, 0, 1}, {0, 0, 1}};
const vector<vec2f> quad_texcoords = vector<vec2f>{
{0, 1}, {1, 1}, {1, 0}, {0, 0}};
const vector<vec4i> quad_quads = vector<vec4i>{{0, 1, 2, 3}};
const vector<vec3f> quady_positions = vector<vec3f>{
{-1, 0, -1}, {-1, 0, +1}, {+1, 0, +1}, {+1, 0, -1}};
const vector<vec3f> quady_normals = vector<vec3f>{
{0, 1, 0}, {0, 1, 0}, {0, 1, 0}, {0, 1, 0}};
const vector<vec2f> quady_texcoords = vector<vec2f>{
{0, 0}, {1, 0}, {1, 1}, {0, 1}};
const vector<vec4i> quady_quads = vector<vec4i>{{0, 1, 2, 3}};
const vector<vec3f> cube_positions = vector<vec3f>{{-1, -1, +1}, {+1, -1, +1},
{+1, +1, +1}, {-1, +1, +1}, {+1, -1, -1}, {-1, -1, -1}, {-1, +1, -1},
{+1, +1, -1}, {+1, -1, +1}, {+1, -1, -1}, {+1, +1, -1}, {+1, +1, +1},
{-1, -1, -1}, {-1, -1, +1}, {-1, +1, +1}, {-1, +1, -1}, {-1, +1, +1},
{+1, +1, +1}, {+1, +1, -1}, {-1, +1, -1}, {+1, -1, +1}, {-1, -1, +1},
{-1, -1, -1}, {+1, -1, -1}};
const vector<vec3f> cube_normals = vector<vec3f>{{0, 0, +1}, {0, 0, +1},
{0, 0, +1}, {0, 0, +1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1},
{+1, 0, 0}, {+1, 0, 0}, {+1, 0, 0}, {+1, 0, 0}, {-1, 0, 0}, {-1, 0, 0},
{-1, 0, 0}, {-1, 0, 0}, {0, +1, 0}, {0, +1, 0}, {0, +1, 0}, {0, +1, 0},
{0, -1, 0}, {0, -1, 0}, {0, -1, 0}, {0, -1, 0}};
const vector<vec2f> cube_texcoords = vector<vec2f>{{0, 1}, {1, 1}, {1, 0},
{0, 0}, {0, 1}, {1, 1}, {1, 0}, {0, 0}, {0, 1}, {1, 1}, {1, 0}, {0, 0},
{0, 1}, {1, 1}, {1, 0}, {0, 0}, {0, 1}, {1, 1}, {1, 0}, {0, 0}, {0, 1},
{1, 1}, {1, 0}, {0, 0}};
const vector<vec4i> cube_quads = vector<vec4i>{{0, 1, 2, 3}, {4, 5, 6, 7},
{8, 9, 10, 11}, {12, 13, 14, 15}, {16, 17, 18, 19}, {20, 21, 22, 23}};
const vector<vec3f> fvcube_positions = vector<vec3f>{{-1, -1, +1}, {+1, -1, +1},
{+1, +1, +1}, {-1, +1, +1}, {+1, -1, -1}, {-1, -1, -1}, {-1, +1, -1},
{+1, +1, -1}};
const vector<vec4i> fvcube_quads = vector<vec4i>{{0, 1, 2, 3}, {4, 5, 6, 7},
{1, 4, 7, 2}, {5, 0, 3, 6}, {3, 2, 7, 6}, {1, 0, 5, 4}};
const vector<vec3f> suzanne_positions = vector<vec3f>{
{0.4375, 0.1640625, 0.765625}, {-0.4375, 0.1640625, 0.765625},
{0.5, 0.09375, 0.6875}, {-0.5, 0.09375, 0.6875},
{0.546875, 0.0546875, 0.578125}, {-0.546875, 0.0546875, 0.578125},
{0.3515625, -0.0234375, 0.6171875}, {-0.3515625, -0.0234375, 0.6171875},
{0.3515625, 0.03125, 0.71875}, {-0.3515625, 0.03125, 0.71875},
{0.3515625, 0.1328125, 0.78125}, {-0.3515625, 0.1328125, 0.78125},
{0.2734375, 0.1640625, 0.796875}, {-0.2734375, 0.1640625, 0.796875},
{0.203125, 0.09375, 0.7421875}, {-0.203125, 0.09375, 0.7421875},
{0.15625, 0.0546875, 0.6484375}, {-0.15625, 0.0546875, 0.6484375},
{0.078125, 0.2421875, 0.65625}, {-0.078125, 0.2421875, 0.65625},
{0.140625, 0.2421875, 0.7421875}, {-0.140625, 0.2421875, 0.7421875},
{0.2421875, 0.2421875, 0.796875}, {-0.2421875, 0.2421875, 0.796875},
{0.2734375, 0.328125, 0.796875}, {-0.2734375, 0.328125, 0.796875},
{0.203125, 0.390625, 0.7421875}, {-0.203125, 0.390625, 0.7421875},
{0.15625, 0.4375, 0.6484375}, {-0.15625, 0.4375, 0.6484375},
{0.3515625, 0.515625, 0.6171875}, {-0.3515625, 0.515625, 0.6171875},
{0.3515625, 0.453125, 0.71875}, {-0.3515625, 0.453125, 0.71875},
{0.3515625, 0.359375, 0.78125}, {-0.3515625, 0.359375, 0.78125},
{0.4375, 0.328125, 0.765625}, {-0.4375, 0.328125, 0.765625},
{0.5, 0.390625, 0.6875}, {-0.5, 0.390625, 0.6875},
{0.546875, 0.4375, 0.578125}, {-0.546875, 0.4375, 0.578125},
{0.625, 0.2421875, 0.5625}, {-0.625, 0.2421875, 0.5625},
{0.5625, 0.2421875, 0.671875}, {-0.5625, 0.2421875, 0.671875},
{0.46875, 0.2421875, 0.7578125}, {-0.46875, 0.2421875, 0.7578125},
{0.4765625, 0.2421875, 0.7734375}, {-0.4765625, 0.2421875, 0.7734375},
{0.4453125, 0.3359375, 0.78125}, {-0.4453125, 0.3359375, 0.78125},
{0.3515625, 0.375, 0.8046875}, {-0.3515625, 0.375, 0.8046875},
{0.265625, 0.3359375, 0.8203125}, {-0.265625, 0.3359375, 0.8203125},
{0.2265625, 0.2421875, 0.8203125}, {-0.2265625, 0.2421875, 0.8203125},
{0.265625, 0.15625, 0.8203125}, {-0.265625, 0.15625, 0.8203125},
{0.3515625, 0.2421875, 0.828125}, {-0.3515625, 0.2421875, 0.828125},
{0.3515625, 0.1171875, 0.8046875}, {-0.3515625, 0.1171875, 0.8046875},
{0.4453125, 0.15625, 0.78125}, {-0.4453125, 0.15625, 0.78125},
{0.0, 0.4296875, 0.7421875}, {0.0, 0.3515625, 0.8203125},
{0.0, -0.6796875, 0.734375}, {0.0, -0.3203125, 0.78125},
{0.0, -0.1875, 0.796875}, {0.0, -0.7734375, 0.71875},
{0.0, 0.40625, 0.6015625}, {0.0, 0.5703125, 0.5703125},
{0.0, 0.8984375, -0.546875}, {0.0, 0.5625, -0.8515625},
{0.0, 0.0703125, -0.828125}, {0.0, -0.3828125, -0.3515625},
{0.203125, -0.1875, 0.5625}, {-0.203125, -0.1875, 0.5625},
{0.3125, -0.4375, 0.5703125}, {-0.3125, -0.4375, 0.5703125},
{0.3515625, -0.6953125, 0.5703125}, {-0.3515625, -0.6953125, 0.5703125},
{0.3671875, -0.890625, 0.53125}, {-0.3671875, -0.890625, 0.53125},
{0.328125, -0.9453125, 0.5234375}, {-0.328125, -0.9453125, 0.5234375},
{0.1796875, -0.96875, 0.5546875}, {-0.1796875, -0.96875, 0.5546875},
{0.0, -0.984375, 0.578125}, {0.4375, -0.140625, 0.53125},
{-0.4375, -0.140625, 0.53125}, {0.6328125, -0.0390625, 0.5390625},
{-0.6328125, -0.0390625, 0.5390625}, {0.828125, 0.1484375, 0.4453125},
{-0.828125, 0.1484375, 0.4453125}, {0.859375, 0.4296875, 0.59375},
{-0.859375, 0.4296875, 0.59375}, {0.7109375, 0.484375, 0.625},
{-0.7109375, 0.484375, 0.625}, {0.4921875, 0.6015625, 0.6875},
{-0.4921875, 0.6015625, 0.6875}, {0.3203125, 0.7578125, 0.734375},
{-0.3203125, 0.7578125, 0.734375}, {0.15625, 0.71875, 0.7578125},
{-0.15625, 0.71875, 0.7578125}, {0.0625, 0.4921875, 0.75},
{-0.0625, 0.4921875, 0.75}, {0.1640625, 0.4140625, 0.7734375},
{-0.1640625, 0.4140625, 0.7734375}, {0.125, 0.3046875, 0.765625},
{-0.125, 0.3046875, 0.765625}, {0.203125, 0.09375, 0.7421875},
{-0.203125, 0.09375, 0.7421875}, {0.375, 0.015625, 0.703125},
{-0.375, 0.015625, 0.703125}, {0.4921875, 0.0625, 0.671875},
{-0.4921875, 0.0625, 0.671875}, {0.625, 0.1875, 0.6484375},
{-0.625, 0.1875, 0.6484375}, {0.640625, 0.296875, 0.6484375},
{-0.640625, 0.296875, 0.6484375}, {0.6015625, 0.375, 0.6640625},
{-0.6015625, 0.375, 0.6640625}, {0.4296875, 0.4375, 0.71875},
{-0.4296875, 0.4375, 0.71875}, {0.25, 0.46875, 0.7578125},
{-0.25, 0.46875, 0.7578125}, {0.0, -0.765625, 0.734375},
{0.109375, -0.71875, 0.734375}, {-0.109375, -0.71875, 0.734375},
{0.1171875, -0.8359375, 0.7109375}, {-0.1171875, -0.8359375, 0.7109375},
{0.0625, -0.8828125, 0.6953125}, {-0.0625, -0.8828125, 0.6953125},
{0.0, -0.890625, 0.6875}, {0.0, -0.1953125, 0.75},
{0.0, -0.140625, 0.7421875}, {0.1015625, -0.1484375, 0.7421875},
{-0.1015625, -0.1484375, 0.7421875}, {0.125, -0.2265625, 0.75},
{-0.125, -0.2265625, 0.75}, {0.0859375, -0.2890625, 0.7421875},
{-0.0859375, -0.2890625, 0.7421875}, {0.3984375, -0.046875, 0.671875},
{-0.3984375, -0.046875, 0.671875}, {0.6171875, 0.0546875, 0.625},
{-0.6171875, 0.0546875, 0.625}, {0.7265625, 0.203125, 0.6015625},
{-0.7265625, 0.203125, 0.6015625}, {0.7421875, 0.375, 0.65625},
{-0.7421875, 0.375, 0.65625}, {0.6875, 0.4140625, 0.7265625},
{-0.6875, 0.4140625, 0.7265625}, {0.4375, 0.546875, 0.796875},
{-0.4375, 0.546875, 0.796875}, {0.3125, 0.640625, 0.8359375},
{-0.3125, 0.640625, 0.8359375}, {0.203125, 0.6171875, 0.8515625},
{-0.203125, 0.6171875, 0.8515625}, {0.1015625, 0.4296875, 0.84375},
{-0.1015625, 0.4296875, 0.84375}, {0.125, -0.1015625, 0.8125},
{-0.125, -0.1015625, 0.8125}, {0.2109375, -0.4453125, 0.7109375},
{-0.2109375, -0.4453125, 0.7109375}, {0.25, -0.703125, 0.6875},
{-0.25, -0.703125, 0.6875}, {0.265625, -0.8203125, 0.6640625},
{-0.265625, -0.8203125, 0.6640625}, {0.234375, -0.9140625, 0.6328125},
{-0.234375, -0.9140625, 0.6328125}, {0.1640625, -0.9296875, 0.6328125},
{-0.1640625, -0.9296875, 0.6328125}, {0.0, -0.9453125, 0.640625},
{0.0, 0.046875, 0.7265625}, {0.0, 0.2109375, 0.765625},
{0.328125, 0.4765625, 0.7421875}, {-0.328125, 0.4765625, 0.7421875},
{0.1640625, 0.140625, 0.75}, {-0.1640625, 0.140625, 0.75},
{0.1328125, 0.2109375, 0.7578125}, {-0.1328125, 0.2109375, 0.7578125},
{0.1171875, -0.6875, 0.734375}, {-0.1171875, -0.6875, 0.734375},
{0.078125, -0.4453125, 0.75}, {-0.078125, -0.4453125, 0.75},
{0.0, -0.4453125, 0.75}, {0.0, -0.328125, 0.7421875},
{0.09375, -0.2734375, 0.78125}, {-0.09375, -0.2734375, 0.78125},
{0.1328125, -0.2265625, 0.796875}, {-0.1328125, -0.2265625, 0.796875},
{0.109375, -0.1328125, 0.78125}, {-0.109375, -0.1328125, 0.78125},
{0.0390625, -0.125, 0.78125}, {-0.0390625, -0.125, 0.78125},
{0.0, -0.203125, 0.828125}, {0.046875, -0.1484375, 0.8125},
{-0.046875, -0.1484375, 0.8125}, {0.09375, -0.15625, 0.8125},
{-0.09375, -0.15625, 0.8125}, {0.109375, -0.2265625, 0.828125},
{-0.109375, -0.2265625, 0.828125}, {0.078125, -0.25, 0.8046875},
{-0.078125, -0.25, 0.8046875}, {0.0, -0.2890625, 0.8046875},
{0.2578125, -0.3125, 0.5546875}, {-0.2578125, -0.3125, 0.5546875},
{0.1640625, -0.2421875, 0.7109375}, {-0.1640625, -0.2421875, 0.7109375},
{0.1796875, -0.3125, 0.7109375}, {-0.1796875, -0.3125, 0.7109375},
{0.234375, -0.25, 0.5546875}, {-0.234375, -0.25, 0.5546875},
{0.0, -0.875, 0.6875}, {0.046875, -0.8671875, 0.6875},
{-0.046875, -0.8671875, 0.6875}, {0.09375, -0.8203125, 0.7109375},
{-0.09375, -0.8203125, 0.7109375}, {0.09375, -0.7421875, 0.7265625},
{-0.09375, -0.7421875, 0.7265625}, {0.0, -0.78125, 0.65625},
{0.09375, -0.75, 0.6640625}, {-0.09375, -0.75, 0.6640625},
{0.09375, -0.8125, 0.640625}, {-0.09375, -0.8125, 0.640625},
{0.046875, -0.8515625, 0.6328125}, {-0.046875, -0.8515625, 0.6328125},
{0.0, -0.859375, 0.6328125}, {0.171875, 0.21875, 0.78125},
{-0.171875, 0.21875, 0.78125}, {0.1875, 0.15625, 0.7734375},
{-0.1875, 0.15625, 0.7734375}, {0.3359375, 0.4296875, 0.7578125},
{-0.3359375, 0.4296875, 0.7578125}, {0.2734375, 0.421875, 0.7734375},
{-0.2734375, 0.421875, 0.7734375}, {0.421875, 0.3984375, 0.7734375},
{-0.421875, 0.3984375, 0.7734375}, {0.5625, 0.3515625, 0.6953125},
{-0.5625, 0.3515625, 0.6953125}, {0.5859375, 0.2890625, 0.6875},
{-0.5859375, 0.2890625, 0.6875}, {0.578125, 0.1953125, 0.6796875},
{-0.578125, 0.1953125, 0.6796875}, {0.4765625, 0.1015625, 0.71875},
{-0.4765625, 0.1015625, 0.71875}, {0.375, 0.0625, 0.7421875},
{-0.375, 0.0625, 0.7421875}, {0.2265625, 0.109375, 0.78125},
{-0.2265625, 0.109375, 0.78125}, {0.1796875, 0.296875, 0.78125},
{-0.1796875, 0.296875, 0.78125}, {0.2109375, 0.375, 0.78125},
{-0.2109375, 0.375, 0.78125}, {0.234375, 0.359375, 0.7578125},
{-0.234375, 0.359375, 0.7578125}, {0.1953125, 0.296875, 0.7578125},
{-0.1953125, 0.296875, 0.7578125}, {0.2421875, 0.125, 0.7578125},
{-0.2421875, 0.125, 0.7578125}, {0.375, 0.0859375, 0.7265625},
{-0.375, 0.0859375, 0.7265625}, {0.4609375, 0.1171875, 0.703125},
{-0.4609375, 0.1171875, 0.703125}, {0.546875, 0.2109375, 0.671875},
{-0.546875, 0.2109375, 0.671875}, {0.5546875, 0.28125, 0.671875},
{-0.5546875, 0.28125, 0.671875}, {0.53125, 0.3359375, 0.6796875},
{-0.53125, 0.3359375, 0.6796875}, {0.4140625, 0.390625, 0.75},
{-0.4140625, 0.390625, 0.75}, {0.28125, 0.3984375, 0.765625},
{-0.28125, 0.3984375, 0.765625}, {0.3359375, 0.40625, 0.75},
{-0.3359375, 0.40625, 0.75}, {0.203125, 0.171875, 0.75},
{-0.203125, 0.171875, 0.75}, {0.1953125, 0.2265625, 0.75},
{-0.1953125, 0.2265625, 0.75}, {0.109375, 0.4609375, 0.609375},
{-0.109375, 0.4609375, 0.609375}, {0.1953125, 0.6640625, 0.6171875},
{-0.1953125, 0.6640625, 0.6171875}, {0.3359375, 0.6875, 0.59375},
{-0.3359375, 0.6875, 0.59375}, {0.484375, 0.5546875, 0.5546875},
{-0.484375, 0.5546875, 0.5546875}, {0.6796875, 0.453125, 0.4921875},
{-0.6796875, 0.453125, 0.4921875}, {0.796875, 0.40625, 0.4609375},
{-0.796875, 0.40625, 0.4609375}, {0.7734375, 0.1640625, 0.375},
{-0.7734375, 0.1640625, 0.375}, {0.6015625, 0.0, 0.4140625},
{-0.6015625, 0.0, 0.4140625}, {0.4375, -0.09375, 0.46875},
{-0.4375, -0.09375, 0.46875}, {0.0, 0.8984375, 0.2890625},
{0.0, 0.984375, -0.078125}, {0.0, -0.1953125, -0.671875},
{0.0, -0.4609375, 0.1875}, {0.0, -0.9765625, 0.4609375},
{0.0, -0.8046875, 0.34375}, {0.0, -0.5703125, 0.3203125},
{0.0, -0.484375, 0.28125}, {0.8515625, 0.234375, 0.0546875},
{-0.8515625, 0.234375, 0.0546875}, {0.859375, 0.3203125, -0.046875},
{-0.859375, 0.3203125, -0.046875}, {0.7734375, 0.265625, -0.4375},
{-0.7734375, 0.265625, -0.4375}, {0.4609375, 0.4375, -0.703125},
{-0.4609375, 0.4375, -0.703125}, {0.734375, -0.046875, 0.0703125},
{-0.734375, -0.046875, 0.0703125}, {0.59375, -0.125, -0.1640625},
{-0.59375, -0.125, -0.1640625}, {0.640625, -0.0078125, -0.4296875},
{-0.640625, -0.0078125, -0.4296875}, {0.3359375, 0.0546875, -0.6640625},
{-0.3359375, 0.0546875, -0.6640625}, {0.234375, -0.3515625, 0.40625},
{-0.234375, -0.3515625, 0.40625}, {0.1796875, -0.4140625, 0.2578125},
{-0.1796875, -0.4140625, 0.2578125}, {0.2890625, -0.7109375, 0.3828125},
{-0.2890625, -0.7109375, 0.3828125}, {0.25, -0.5, 0.390625},
{-0.25, -0.5, 0.390625}, {0.328125, -0.9140625, 0.3984375},
{-0.328125, -0.9140625, 0.3984375}, {0.140625, -0.7578125, 0.3671875},
{-0.140625, -0.7578125, 0.3671875}, {0.125, -0.5390625, 0.359375},
{-0.125, -0.5390625, 0.359375}, {0.1640625, -0.9453125, 0.4375},
{-0.1640625, -0.9453125, 0.4375}, {0.21875, -0.28125, 0.4296875},
{-0.21875, -0.28125, 0.4296875}, {0.2109375, -0.2265625, 0.46875},
{-0.2109375, -0.2265625, 0.46875}, {0.203125, -0.171875, 0.5},
{-0.203125, -0.171875, 0.5}, {0.2109375, -0.390625, 0.1640625},
{-0.2109375, -0.390625, 0.1640625}, {0.296875, -0.3125, -0.265625},
{-0.296875, -0.3125, -0.265625}, {0.34375, -0.1484375, -0.5390625},
{-0.34375, -0.1484375, -0.5390625}, {0.453125, 0.8671875, -0.3828125},
{-0.453125, 0.8671875, -0.3828125}, {0.453125, 0.9296875, -0.0703125},
{-0.453125, 0.9296875, -0.0703125}, {0.453125, 0.8515625, 0.234375},
{-0.453125, 0.8515625, 0.234375}, {0.4609375, 0.5234375, 0.4296875},
{-0.4609375, 0.5234375, 0.4296875}, {0.7265625, 0.40625, 0.3359375},
{-0.7265625, 0.40625, 0.3359375}, {0.6328125, 0.453125, 0.28125},
{-0.6328125, 0.453125, 0.28125}, {0.640625, 0.703125, 0.0546875},
{-0.640625, 0.703125, 0.0546875}, {0.796875, 0.5625, 0.125},
{-0.796875, 0.5625, 0.125}, {0.796875, 0.6171875, -0.1171875},
{-0.796875, 0.6171875, -0.1171875}, {0.640625, 0.75, -0.1953125},
{-0.640625, 0.75, -0.1953125}, {0.640625, 0.6796875, -0.4453125},
{-0.640625, 0.6796875, -0.4453125}, {0.796875, 0.5390625, -0.359375},
{-0.796875, 0.5390625, -0.359375}, {0.6171875, 0.328125, -0.5859375},
{-0.6171875, 0.328125, -0.5859375}, {0.484375, 0.0234375, -0.546875},
{-0.484375, 0.0234375, -0.546875}, {0.8203125, 0.328125, -0.203125},
{-0.8203125, 0.328125, -0.203125}, {0.40625, -0.171875, 0.1484375},
{-0.40625, -0.171875, 0.1484375}, {0.4296875, -0.1953125, -0.2109375},
{-0.4296875, -0.1953125, -0.2109375}, {0.890625, 0.40625, -0.234375},
{-0.890625, 0.40625, -0.234375}, {0.7734375, -0.140625, -0.125},
{-0.7734375, -0.140625, -0.125}, {1.0390625, -0.1015625, -0.328125},
{-1.0390625, -0.1015625, -0.328125}, {1.28125, 0.0546875, -0.4296875},
{-1.28125, 0.0546875, -0.4296875}, {1.3515625, 0.3203125, -0.421875},
{-1.3515625, 0.3203125, -0.421875}, {1.234375, 0.5078125, -0.421875},
{-1.234375, 0.5078125, -0.421875}, {1.0234375, 0.4765625, -0.3125},
{-1.0234375, 0.4765625, -0.3125}, {1.015625, 0.4140625, -0.2890625},
{-1.015625, 0.4140625, -0.2890625}, {1.1875, 0.4375, -0.390625},
{-1.1875, 0.4375, -0.390625}, {1.265625, 0.2890625, -0.40625},
{-1.265625, 0.2890625, -0.40625}, {1.2109375, 0.078125, -0.40625},
{-1.2109375, 0.078125, -0.40625}, {1.03125, -0.0390625, -0.3046875},
{-1.03125, -0.0390625, -0.3046875}, {0.828125, -0.0703125, -0.1328125},
{-0.828125, -0.0703125, -0.1328125}, {0.921875, 0.359375, -0.21875},
{-0.921875, 0.359375, -0.21875}, {0.9453125, 0.3046875, -0.2890625},
{-0.9453125, 0.3046875, -0.2890625}, {0.8828125, -0.0234375, -0.2109375},
{-0.8828125, -0.0234375, -0.2109375}, {1.0390625, 0.0, -0.3671875},
{-1.0390625, 0.0, -0.3671875}, {1.1875, 0.09375, -0.4453125},
{-1.1875, 0.09375, -0.4453125}, {1.234375, 0.25, -0.4453125},
{-1.234375, 0.25, -0.4453125}, {1.171875, 0.359375, -0.4375},
{-1.171875, 0.359375, -0.4375}, {1.0234375, 0.34375, -0.359375},
{-1.0234375, 0.34375, -0.359375}, {0.84375, 0.2890625, -0.2109375},
{-0.84375, 0.2890625, -0.2109375}, {0.8359375, 0.171875, -0.2734375},
{-0.8359375, 0.171875, -0.2734375}, {0.7578125, 0.09375, -0.2734375},
{-0.7578125, 0.09375, -0.2734375}, {0.8203125, 0.0859375, -0.2734375},
{-0.8203125, 0.0859375, -0.2734375}, {0.84375, 0.015625, -0.2734375},
{-0.84375, 0.015625, -0.2734375}, {0.8125, -0.015625, -0.2734375},
{-0.8125, -0.015625, -0.2734375}, {0.7265625, 0.0, -0.0703125},
{-0.7265625, 0.0, -0.0703125}, {0.71875, -0.0234375, -0.171875},
{-0.71875, -0.0234375, -0.171875}, {0.71875, 0.0390625, -0.1875},
{-0.71875, 0.0390625, -0.1875}, {0.796875, 0.203125, -0.2109375},
{-0.796875, 0.203125, -0.2109375}, {0.890625, 0.2421875, -0.265625},
{-0.890625, 0.2421875, -0.265625}, {0.890625, 0.234375, -0.3203125},
{-0.890625, 0.234375, -0.3203125}, {0.8125, -0.015625, -0.3203125},
{-0.8125, -0.015625, -0.3203125}, {0.8515625, 0.015625, -0.3203125},
{-0.8515625, 0.015625, -0.3203125}, {0.828125, 0.078125, -0.3203125},
{-0.828125, 0.078125, -0.3203125}, {0.765625, 0.09375, -0.3203125},
{-0.765625, 0.09375, -0.3203125}, {0.84375, 0.171875, -0.3203125},
{-0.84375, 0.171875, -0.3203125}, {1.0390625, 0.328125, -0.4140625},
{-1.0390625, 0.328125, -0.4140625}, {1.1875, 0.34375, -0.484375},
{-1.1875, 0.34375, -0.484375}, {1.2578125, 0.2421875, -0.4921875},
{-1.2578125, 0.2421875, -0.4921875}, {1.2109375, 0.0859375, -0.484375},
{-1.2109375, 0.0859375, -0.484375}, {1.046875, 0.0, -0.421875},
{-1.046875, 0.0, -0.421875}, {0.8828125, -0.015625, -0.265625},
{-0.8828125, -0.015625, -0.265625}, {0.953125, 0.2890625, -0.34375},
{-0.953125, 0.2890625, -0.34375}, {0.890625, 0.109375, -0.328125},
{-0.890625, 0.109375, -0.328125}, {0.9375, 0.0625, -0.3359375},
{-0.9375, 0.0625, -0.3359375}, {1.0, 0.125, -0.3671875},
{-1.0, 0.125, -0.3671875}, {0.9609375, 0.171875, -0.3515625},
{-0.9609375, 0.171875, -0.3515625}, {1.015625, 0.234375, -0.375},
{-1.015625, 0.234375, -0.375}, {1.0546875, 0.1875, -0.3828125},
{-1.0546875, 0.1875, -0.3828125}, {1.109375, 0.2109375, -0.390625},
{-1.109375, 0.2109375, -0.390625}, {1.0859375, 0.2734375, -0.390625},
{-1.0859375, 0.2734375, -0.390625}, {1.0234375, 0.4375, -0.484375},
{-1.0234375, 0.4375, -0.484375}, {1.25, 0.46875, -0.546875},
{-1.25, 0.46875, -0.546875}, {1.3671875, 0.296875, -0.5},
{-1.3671875, 0.296875, -0.5}, {1.3125, 0.0546875, -0.53125},
{-1.3125, 0.0546875, -0.53125}, {1.0390625, -0.0859375, -0.4921875},
{-1.0390625, -0.0859375, -0.4921875}, {0.7890625, -0.125, -0.328125},
{-0.7890625, -0.125, -0.328125}, {0.859375, 0.3828125, -0.3828125},
{-0.859375, 0.3828125, -0.3828125}};
const vector<vec4i> suzanne_quads = vector<vec4i>{{46, 0, 2, 44},
{3, 1, 47, 45}, {44, 2, 4, 42}, {5, 3, 45, 43}, {2, 8, 6, 4}, {7, 9, 3, 5},
{0, 10, 8, 2}, {9, 11, 1, 3}, {10, 12, 14, 8}, {15, 13, 11, 9},
{8, 14, 16, 6}, {17, 15, 9, 7}, {14, 20, 18, 16}, {19, 21, 15, 17},
{12, 22, 20, 14}, {21, 23, 13, 15}, {22, 24, 26, 20}, {27, 25, 23, 21},
{20, 26, 28, 18}, {29, 27, 21, 19}, {26, 32, 30, 28}, {31, 33, 27, 29},
{24, 34, 32, 26}, {33, 35, 25, 27}, {34, 36, 38, 32}, {39, 37, 35, 33},
{32, 38, 40, 30}, {41, 39, 33, 31}, {38, 44, 42, 40}, {43, 45, 39, 41},
{36, 46, 44, 38}, {45, 47, 37, 39}, {46, 36, 50, 48}, {51, 37, 47, 49},
{36, 34, 52, 50}, {53, 35, 37, 51}, {34, 24, 54, 52}, {55, 25, 35, 53},
{24, 22, 56, 54}, {57, 23, 25, 55}, {22, 12, 58, 56}, {59, 13, 23, 57},
{12, 10, 62, 58}, {63, 11, 13, 59}, {10, 0, 64, 62}, {65, 1, 11, 63},
{0, 46, 48, 64}, {49, 47, 1, 65}, {88, 173, 175, 90}, {175, 174, 89, 90},
{86, 171, 173, 88}, {174, 172, 87, 89}, {84, 169, 171, 86},
{172, 170, 85, 87}, {82, 167, 169, 84}, {170, 168, 83, 85},
{80, 165, 167, 82}, {168, 166, 81, 83}, {78, 91, 145, 163},
{146, 92, 79, 164}, {91, 93, 147, 145}, {148, 94, 92, 146},
{93, 95, 149, 147}, {150, 96, 94, 148}, {95, 97, 151, 149},
{152, 98, 96, 150}, {97, 99, 153, 151}, {154, 100, 98, 152},
{99, 101, 155, 153}, {156, 102, 100, 154}, {101, 103, 157, 155},
{158, 104, 102, 156}, {103, 105, 159, 157}, {160, 106, 104, 158},
{105, 107, 161, 159}, {162, 108, 106, 160}, {107, 66, 67, 161},
{67, 66, 108, 162}, {109, 127, 159, 161}, {160, 128, 110, 162},
{127, 178, 157, 159}, {158, 179, 128, 160}, {125, 155, 157, 178},
{158, 156, 126, 179}, {123, 153, 155, 125}, {156, 154, 124, 126},
{121, 151, 153, 123}, {154, 152, 122, 124}, {119, 149, 151, 121},
{152, 150, 120, 122}, {117, 147, 149, 119}, {150, 148, 118, 120},
{115, 145, 147, 117}, {148, 146, 116, 118}, {113, 163, 145, 115},
{146, 164, 114, 116}, {113, 180, 176, 163}, {176, 181, 114, 164},
{109, 161, 67, 111}, {67, 162, 110, 112}, {111, 67, 177, 182},
{177, 67, 112, 183}, {176, 180, 182, 177}, {183, 181, 176, 177},
{134, 136, 175, 173}, {175, 136, 135, 174}, {132, 134, 173, 171},
{174, 135, 133, 172}, {130, 132, 171, 169}, {172, 133, 131, 170},
{165, 186, 184, 167}, {185, 187, 166, 168}, {130, 169, 167, 184},
{168, 170, 131, 185}, {143, 189, 188, 186}, {188, 189, 144, 187},
{184, 186, 188, 68}, {188, 187, 185, 68}, {129, 130, 184, 68},
{185, 131, 129, 68}, {141, 192, 190, 143}, {191, 193, 142, 144},
{139, 194, 192, 141}, {193, 195, 140, 142}, {138, 196, 194, 139},
{195, 197, 138, 140}, {137, 70, 196, 138}, {197, 70, 137, 138},
{189, 143, 190, 69}, {191, 144, 189, 69}, {69, 190, 205, 207},
{206, 191, 69, 207}, {70, 198, 199, 196}, {200, 198, 70, 197},
{196, 199, 201, 194}, {202, 200, 197, 195}, {194, 201, 203, 192},
{204, 202, 195, 193}, {192, 203, 205, 190}, {206, 204, 193, 191},
{198, 203, 201, 199}, {202, 204, 198, 200}, {198, 207, 205, 203},
{206, 207, 198, 204}, {138, 139, 163, 176}, {164, 140, 138, 176},
{139, 141, 210, 163}, {211, 142, 140, 164}, {141, 143, 212, 210},
{213, 144, 142, 211}, {143, 186, 165, 212}, {166, 187, 144, 213},
{80, 208, 212, 165}, {213, 209, 81, 166}, {208, 214, 210, 212},
{211, 215, 209, 213}, {78, 163, 210, 214}, {211, 164, 79, 215},
{130, 129, 71, 221}, {71, 129, 131, 222}, {132, 130, 221, 219},
{222, 131, 133, 220}, {134, 132, 219, 217}, {220, 133, 135, 218},
{136, 134, 217, 216}, {218, 135, 136, 216}, {216, 217, 228, 230},
{229, 218, 216, 230}, {217, 219, 226, 228}, {227, 220, 218, 229},
{219, 221, 224, 226}, {225, 222, 220, 227}, {221, 71, 223, 224},
{223, 71, 222, 225}, {223, 230, 228, 224}, {229, 230, 223, 225},
{182, 180, 233, 231}, {234, 181, 183, 232}, {111, 182, 231, 253},
{232, 183, 112, 254}, {109, 111, 253, 255}, {254, 112, 110, 256},
{180, 113, 251, 233}, {252, 114, 181, 234}, {113, 115, 249, 251},
{250, 116, 114, 252}, {115, 117, 247, 249}, {248, 118, 116, 250},
{117, 119, 245, 247}, {246, 120, 118, 248}, {119, 121, 243, 245},
{244, 122, 120, 246}, {121, 123, 241, 243}, {242, 124, 122, 244},
{123, 125, 239, 241}, {240, 126, 124, 242}, {125, 178, 235, 239},
{236, 179, 126, 240}, {178, 127, 237, 235}, {238, 128, 179, 236},
{127, 109, 255, 237}, {256, 110, 128, 238}, {237, 255, 257, 275},
{258, 256, 238, 276}, {235, 237, 275, 277}, {276, 238, 236, 278},
{239, 235, 277, 273}, {278, 236, 240, 274}, {241, 239, 273, 271},
{274, 240, 242, 272}, {243, 241, 271, 269}, {272, 242, 244, 270},
{245, 243, 269, 267}, {270, 244, 246, 268}, {247, 245, 267, 265},
{268, 246, 248, 266}, {249, 247, 265, 263}, {266, 248, 250, 264},
{251, 249, 263, 261}, {264, 250, 252, 262}, {233, 251, 261, 279},
{262, 252, 234, 280}, {255, 253, 259, 257}, {260, 254, 256, 258},
{253, 231, 281, 259}, {282, 232, 254, 260}, {231, 233, 279, 281},
{280, 234, 232, 282}, {66, 107, 283, 72}, {284, 108, 66, 72},
{107, 105, 285, 283}, {286, 106, 108, 284}, {105, 103, 287, 285},
{288, 104, 106, 286}, {103, 101, 289, 287}, {290, 102, 104, 288},
{101, 99, 291, 289}, {292, 100, 102, 290}, {99, 97, 293, 291},
{294, 98, 100, 292}, {97, 95, 295, 293}, {296, 96, 98, 294},
{95, 93, 297, 295}, {298, 94, 96, 296}, {93, 91, 299, 297},
{300, 92, 94, 298}, {307, 308, 327, 337}, {328, 308, 307, 338},
{306, 307, 337, 335}, {338, 307, 306, 336}, {305, 306, 335, 339},
{336, 306, 305, 340}, {88, 90, 305, 339}, {305, 90, 89, 340},
{86, 88, 339, 333}, {340, 89, 87, 334}, {84, 86, 333, 329},
{334, 87, 85, 330}, {82, 84, 329, 331}, {330, 85, 83, 332},
{329, 335, 337, 331}, {338, 336, 330, 332}, {329, 333, 339, 335},
{340, 334, 330, 336}, {325, 331, 337, 327}, {338, 332, 326, 328},
{80, 82, 331, 325}, {332, 83, 81, 326}, {208, 341, 343, 214},
{344, 342, 209, 215}, {80, 325, 341, 208}, {342, 326, 81, 209},
{78, 214, 343, 345}, {344, 215, 79, 346}, {78, 345, 299, 91},
{300, 346, 79, 92}, {76, 323, 351, 303}, {352, 324, 76, 303},
{303, 351, 349, 77}, {350, 352, 303, 77}, {77, 349, 347, 304},
{348, 350, 77, 304}, {304, 347, 327, 308}, {328, 348, 304, 308},
{325, 327, 347, 341}, {348, 328, 326, 342}, {295, 297, 317, 309},
{318, 298, 296, 310}, {75, 315, 323, 76}, {324, 316, 75, 76},
{301, 357, 355, 302}, {356, 358, 301, 302}, {302, 355, 353, 74},
{354, 356, 302, 74}, {74, 353, 315, 75}, {316, 354, 74, 75},
{291, 293, 361, 363}, {362, 294, 292, 364}, {363, 361, 367, 365},
{368, 362, 364, 366}, {365, 367, 369, 371}, {370, 368, 366, 372},
{371, 369, 375, 373}, {376, 370, 372, 374}, {313, 377, 373, 375},
{374, 378, 314, 376}, {315, 353, 373, 377}, {374, 354, 316, 378},
{353, 355, 371, 373}, {372, 356, 354, 374}, {355, 357, 365, 371},
{366, 358, 356, 372}, {357, 359, 363, 365}, {364, 360, 358, 366},
{289, 291, 363, 359}, {364, 292, 290, 360}, {73, 359, 357, 301},
{358, 360, 73, 301}, {283, 285, 287, 289}, {288, 286, 284, 290},
{283, 289, 359, 73}, {360, 290, 284, 73}, {293, 295, 309, 361},
{310, 296, 294, 362}, {309, 311, 367, 361}, {368, 312, 310, 362},
{311, 381, 369, 367}, {370, 382, 312, 368}, {313, 375, 369, 381},
{370, 376, 314, 382}, {347, 349, 385, 383}, {386, 350, 348, 384},
{317, 383, 385, 319}, {386, 384, 318, 320}, {297, 299, 383, 317},
{384, 300, 298, 318}, {299, 343, 341, 383}, {342, 344, 300, 384},
{313, 321, 379, 377}, {380, 322, 314, 378}, {315, 377, 379, 323},
{380, 378, 316, 324}, {319, 385, 379, 321}, {380, 386, 320, 322},
{349, 351, 379, 385}, {380, 352, 350, 386}, {399, 387, 413, 401},
{414, 388, 400, 402}, {399, 401, 403, 397}, {404, 402, 400, 398},
{397, 403, 405, 395}, {406, 404, 398, 396}, {395, 405, 407, 393},
{408, 406, 396, 394}, {393, 407, 409, 391}, {410, 408, 394, 392},
{391, 409, 411, 389}, {412, 410, 392, 390}, {409, 419, 417, 411},
{418, 420, 410, 412}, {407, 421, 419, 409}, {420, 422, 408, 410},
{405, 423, 421, 407}, {422, 424, 406, 408}, {403, 425, 423, 405},
{424, 426, 404, 406}, {401, 427, 425, 403}, {426, 428, 402, 404},
{401, 413, 415, 427}, {416, 414, 402, 428}, {317, 319, 443, 441},
{444, 320, 318, 442}, {319, 389, 411, 443}, {412, 390, 320, 444},
{309, 317, 441, 311}, {442, 318, 310, 312}, {381, 429, 413, 387},
{414, 430, 382, 388}, {411, 417, 439, 443}, {440, 418, 412, 444},
{437, 445, 443, 439}, {444, 446, 438, 440}, {433, 445, 437, 435},
{438, 446, 434, 436}, {431, 447, 445, 433}, {446, 448, 432, 434},
{429, 447, 431, 449}, {432, 448, 430, 450}, {413, 429, 449, 415},
{450, 430, 414, 416}, {311, 447, 429, 381}, {430, 448, 312, 382},
{311, 441, 445, 447}, {446, 442, 312, 448}, {415, 449, 451, 475},
{452, 450, 416, 476}, {449, 431, 461, 451}, {462, 432, 450, 452},
{431, 433, 459, 461}, {460, 434, 432, 462}, {433, 435, 457, 459},
{458, 436, 434, 460}, {435, 437, 455, 457}, {456, 438, 436, 458},
{437, 439, 453, 455}, {454, 440, 438, 456}, {439, 417, 473, 453},
{474, 418, 440, 454}, {427, 415, 475, 463}, {476, 416, 428, 464},
{425, 427, 463, 465}, {464, 428, 426, 466}, {423, 425, 465, 467},
{466, 426, 424, 468}, {421, 423, 467, 469}, {468, 424, 422, 470},
{419, 421, 469, 471}, {470, 422, 420, 472}, {417, 419, 471, 473},
{472, 420, 418, 474}, {457, 455, 479, 477}, {480, 456, 458, 478},
{477, 479, 481, 483}, {482, 480, 478, 484}, {483, 481, 487, 485},
{488, 482, 484, 486}, {485, 487, 489, 491}, {490, 488, 486, 492},
{463, 475, 485, 491}, {486, 476, 464, 492}, {451, 483, 485, 475},
{486, 484, 452, 476}, {451, 461, 477, 483}, {478, 462, 452, 484},
{457, 477, 461, 459}, {462, 478, 458, 460}, {453, 473, 479, 455},
{480, 474, 454, 456}, {471, 481, 479, 473}, {480, 482, 472, 474},
{469, 487, 481, 471}, {482, 488, 470, 472}, {467, 489, 487, 469},
{488, 490, 468, 470}, {465, 491, 489, 467}, {490, 492, 466, 468},
{391, 389, 503, 501}, {504, 390, 392, 502}, {393, 391, 501, 499},
{502, 392, 394, 500}, {395, 393, 499, 497}, {500, 394, 396, 498},
{397, 395, 497, 495}, {498, 396, 398, 496}, {399, 397, 495, 493},
{496, 398, 400, 494}, {387, 399, 493, 505}, {494, 400, 388, 506},
{493, 501, 503, 505}, {504, 502, 494, 506}, {493, 495, 499, 501},
{500, 496, 494, 502}, {313, 381, 387, 505}, {388, 382, 314, 506},
{313, 505, 503, 321}, {504, 506, 314, 322}, {319, 321, 503, 389},
{504, 322, 320, 390},
// ttriangles
{60, 64, 48, 48}, {49, 65, 61, 61}, {62, 64, 60, 60}, {61, 65, 63, 63},
{60, 58, 62, 62}, {63, 59, 61, 61}, {60, 56, 58, 58}, {59, 57, 61, 61},
{60, 54, 56, 56}, {57, 55, 61, 61}, {60, 52, 54, 54}, {55, 53, 61, 61},
{60, 50, 52, 52}, {53, 51, 61, 61}, {60, 48, 50, 50}, {51, 49, 61, 61},
{224, 228, 226, 226}, {227, 229, 225, 255}, {72, 283, 73, 73},
{73, 284, 72, 72}, {341, 347, 383, 383}, {384, 348, 342, 342},
{299, 345, 343, 343}, {344, 346, 300, 300}, {323, 379, 351, 351},
{352, 380, 324, 324}, {441, 443, 445, 445}, {446, 444, 442, 442},
{463, 491, 465, 465}, {466, 492, 464, 464}, {495, 497, 499, 499},
{500, 498, 496, 496}};
} // namespace yocto
| 42.437294 | 85 | 0.602442 | erez-o |
9b2dc2f67702a3457ff509829249237ce4e09333 | 15,601 | cpp | C++ | vwgen.cpp | RDamman/SpeakerWorkshop | 87a38d04197a07a9a7878b3f60d5e0706782163c | [
"OML"
] | 12 | 2019-06-07T10:06:41.000Z | 2021-03-22T22:13:59.000Z | vwgen.cpp | RDamman/SpeakerWorkshop | 87a38d04197a07a9a7878b3f60d5e0706782163c | [
"OML"
] | 1 | 2019-05-09T07:38:12.000Z | 2019-07-10T04:20:55.000Z | vwgen.cpp | RDamman/SpeakerWorkshop | 87a38d04197a07a9a7878b3f60d5e0706782163c | [
"OML"
] | 3 | 2020-09-08T08:27:33.000Z | 2021-05-13T09:25:43.000Z | // audtevw.cpp : implementation of the CAudGenView class
//
#include "stdafx.h"
#include "Audtest.h"
#include "audtedoc.h"
#include "vwGen.h"
#include "Chart.h"
#include "xform.h"
#include "xformall.h"
#include "generat.h"
#include "dataset.h"
#include "zFormEdt.h"
#include "dlgRenam.h"
#include "dlgRecor.h"
#include "dlgPlayS.h"
#include "dlgMsrDistort.h"
#include "dlgMsrIn.h"
#include "opItem.h"
#include "opRecord.h"
#ifdef _DEBUG
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CAudGenView
IMPLEMENT_DYNCREATE(CAudGenView, CAudchView)
BEGIN_MESSAGE_MAP(CAudGenView, CAudchView)
//{{AFX_MSG_MAP(CAudGenView)
ON_COMMAND(ID_CANCEL_EDIT_SRVR, OnCancelEditSrvr)
ON_COMMAND(ID_SOUND_RECORD, OnSoundRecord)
ON_COMMAND(ID_SOUND_LOOP, OnSoundLoop)
ON_COMMAND(ID_SOUND_LOOPRECORD, OnSoundLooprecord)
ON_COMMAND(ID_SOUND_PLAY, OnSoundPlay)
ON_COMMAND(ID_SOUND_PLAYAGAIN, OnSoundPlayagain)
ON_COMMAND(ID_SOUND_RECORDAGAIN, OnSoundRecordagain)
ON_COMMAND(ID_SOUND_STOP, OnSoundStop)
ON_COMMAND(ID_SOUND_CONVERTTODATA, OnSoundConverttodata)
ON_COMMAND(ID_MEASURE_DISTORTION, OnMeasureDistortion)
ON_COMMAND(ID_MEASURE_FREQUENCYRESPONSE, OnMeasureFrequencyresponse)
ON_COMMAND(ID_MEASURE_IMPEDANCE, OnMeasureImpedance)
ON_COMMAND(ID_MEASURE_INTERMODULATIONDISTORTION, OnMeasureIntermodulationdistortion)
ON_COMMAND(ID_MEASURE_MICROPHONERESPONSE, OnMeasureMicrophoneresponse)
ON_COMMAND(ID_MEASURE_PASSIVECOMPONENT, OnMeasurePassivecomponent)
ON_COMMAND(ID_MEASURE_TIMERESPONSE, OnMeasureTimeresponse)
ON_COMMAND(ID_MEASURE_GATED, OnMeasureGated)
ON_UPDATE_COMMAND_UI(ID_SHOW_LEFTINPUT, OnUpdateShowLeftinput)
ON_UPDATE_COMMAND_UI(ID_SHOW_OUTPUT, OnUpdateShowOutput)
ON_UPDATE_COMMAND_UI(ID_SHOW_RIGHTINPUT, OnUpdateShowRightinput)
ON_COMMAND(ID_SHOW_LEFTINPUT, OnShowLeftinput)
ON_COMMAND(ID_SHOW_OUTPUT, OnShowOutput)
ON_COMMAND(ID_SHOW_RIGHTINPUT, OnShowRightinput)
ON_COMMAND(ID_SHOW_BOTHINPUT, OnShowBothinput)
ON_UPDATE_COMMAND_UI(ID_SHOW_BOTHINPUT, OnUpdateShowBothinput)
ON_COMMAND(ID_GEN_MEASURE_IMPEDANCE, OnMeasureImpedance)
//}}AFX_MSG_MAP
// Standard printing commands
ON_COMMAND(ID_FILE_PRINT, CAudchView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, CAudchView::OnFilePrintPreview)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CAudGenView construction/destruction
CAudGenView::CAudGenView()
{
// TODO: add construction code here
}
CAudGenView::~CAudGenView()
{
}
/////////////////////////////////////////////////////////////////////////////
// OLE Server support
// The following command handler provides the standard keyboard
// user interface to cancel an in-place editing session. Here,
// the server (not the container) causes the deactivation.
void CAudGenView::OnCancelEditSrvr()
{
GetDocument()->OnDeactivateUI(FALSE);
}
/////////////////////////////////////////////////////////////////////////////
// CAudGenView diagnostics
#ifdef _DEBUG
void CAudGenView::AssertValid() const
{
CAudchView::AssertValid();
}
void CAudGenView::Dump(CDumpContext& dc) const
{
CAudchView::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CAudGenView message handlers
// -----------------------------------------------------------------
// ------------- the local functions to play and record
// -----------------------------------------------------------------
void CAudGenView::execute_Play( RECORDINGINFO *pRec)
{
COpPlayStd *cop = new COpPlayStd( GetTargetObject(), this);
cop->SetRecordInfo( pRec);
if ( ! cop->QueueAndDo())
SetCurrentOperation( cop);
}
void CAudGenView::execute_Record( RECORDINGINFO *pRec)
{
COpRecordStd *cop = new COpRecordStd( GetTargetObject(), this);
cop->SetRecordInfo( pRec);
if ( ! cop->QueueAndDo())
SetCurrentOperation( cop);
}
// -----------------------------------------------------------------
// ------------- OnSoundRecord
// -----------------------------------------------------------------
void CAudGenView::OnSoundRecord()
{
CNamed *cname;
CAudtestDoc* pDoc = GetDocument();
int nout;
CDlgRecord dlgrecord;
cname = pDoc->GetByID( GetTarget());
if ( ! cname)
return;
dlgrecord.UseDocument( pDoc); // use the document settings
nout = dlgrecord.DoModal();
if ( IDOK == nout)
{
dlgrecord.SetDocument( pDoc);
OnSoundRecordagain();
}
}
// -----------------------------------------------------------------
// ------------- OnSoundLoop
// -----------------------------------------------------------------
void CAudGenView::OnSoundLoop()
{
RECORDINGINFO rec;
CAudtestApp::GetRecordingInfo( &rec);
rec.m_bLoopPlay = TRUE;
execute_Play( &rec);
}
// -----------------------------------------------------------------
// ------------- OnSoundLooprecord
// -----------------------------------------------------------------
void CAudGenView::OnSoundLooprecord()
{
RECORDINGINFO rec;
CAudtestApp::GetRecordingInfo( &rec);
rec.m_bLoopRecord = TRUE;
rec.m_bLoopPlay = TRUE;
execute_Record( &rec);
}
// -----------------------------------------------------------------
// ------------- OnSoundPlay
// -----------------------------------------------------------------
void CAudGenView::OnSoundPlay()
{
CAudtestDoc* pDoc = GetDocument();
CDlgPlaySound dlgplay;
int nout;
CGenerator *pcgen = (CGenerator *)GetTargetObject();
if ( ! pcgen)
return;
dlgplay.UseDocument( pDoc); // use the document settings
nout = dlgplay.DoModal();
if ( IDOK == nout)
{
dlgplay.SetDocument( pDoc);
OnSoundPlayagain();
}
}
// -----------------------------------------------------------------
// ------------- OnSoundPlayagain
// -----------------------------------------------------------------
void CAudGenView::OnSoundPlayagain()
{
RECORDINGINFO rec;
CAudtestApp::GetRecordingInfo( &rec);
rec.m_bLoopPlay = FALSE;
execute_Play( &rec);
}
// -----------------------------------------------------------------
// ------------- OnSoundRecordagain
// -----------------------------------------------------------------
void CAudGenView::OnSoundRecordagain()
{
RECORDINGINFO rec;
CAudtestApp::GetRecordingInfo( &rec);
rec.m_bLoopRecord = FALSE;
rec.m_bLoopPlay = FALSE;
execute_Record( &rec);
}
// =================================================================
// ------------- Measure and Play functions
// =================================================================
// -----------------------------------------------------------------
// ------------- On Sound Convert To Data - convert play data to a dataset
// -----------------------------------------------------------------
void CAudGenView::OnSoundConverttodata()
{
CNamed *cname;
CAudtestDoc* pDoc = GetDocument();
cname = pDoc->GetByID( GetTarget());
if ( ! cname)
return;
CGenerator *pcgen = (CGenerator *)cname;
pcgen->CreateWave(4096000 / 44142);
CDataSet *pcdata;
{
CString csname = cname->GetName() + ".out";
CNamed *cnam = pDoc->GetRoot()->GetItemByName( csname);
if ( cnam && ntDataSet == cnam->GetType())
pcdata = (CDataSet *)cnam;
else
{
pcdata = new CDataSet();
pcdata->SetName( csname);
pDoc->GetRoot()->AddItem( pcdata);
}
}
pcgen->MakeDatasets( FALSE, pcdata, NULL);
pDoc->UpdateAll(this, pcdata->GetID());
}
// -----------------------------------------------------------------
// ------------- OnMeasureDistortion
// -----------------------------------------------------------------
void CAudGenView::OnMeasureDistortion()
{
CDlgMsrDistort cdlg;
COpMsrDistortion *cop = new COpMsrDistortion( GetTargetObject(), this);
CAudtestApp *capp = (CAudtestApp *)AfxGetApp();
MSRDISTORTINFO cinfo;
// is there a registry entry???
if ( capp->ReadRegistry( IDS_KEYDISTINFO, &cinfo, sizeof( cinfo)))
{ // failed, set default values
cinfo.fFreq = 100.0f;
cinfo.fFreq1 = 20.0f;
cinfo.fFreq2 = 1000.0f;
cinfo.fPower = 1.0f;
cinfo.fPower1 = 1.0f;
cinfo.fPower2 = 10.0f;
cinfo.bLogRange = TRUE;
cinfo.fWatt = 50;
cinfo.nStyle = 0;
cinfo.nPoints = 5;
}
cdlg.m_fFreq = cinfo.fFreq;
cdlg.m_fFreqStart = cinfo.fFreq1;
cdlg.m_fFreqEnd = cinfo.fFreq2;
cdlg.m_fPower = cinfo.fPower;
cdlg.m_fPowerStart = cinfo.fPower1;
cdlg.m_fPowerEnd = cinfo.fPower2;
cdlg.m_bLogRange = cinfo.bLogRange;
cdlg.m_fEquate = cinfo.fWatt;
cdlg.m_nStyle = cinfo.nStyle;
cdlg.m_nPoints = cinfo.nPoints;
if ( IDOK == cdlg.DoModal())
{
cinfo.fFreq = cdlg.m_fFreq;
cinfo.fFreq1 = cdlg.m_fFreqStart;
cinfo.fFreq2 = cdlg.m_fFreqEnd;
cinfo.fPower = cdlg.m_fPower;
cinfo.fPower1 = cdlg.m_fPowerStart;
cinfo.fPower2 = cdlg.m_fPowerEnd;
cinfo.bLogRange = cdlg.m_bLogRange;
cinfo.fWatt = cdlg.m_fEquate;
cinfo.nStyle = cdlg.m_nStyle;
cinfo.nPoints = cdlg.m_nPoints;
capp->WriteRegistry( IDS_KEYDISTINFO, &cinfo, sizeof( cinfo));
cop->SetParms( &cinfo);
StdOperation( cop );
}
}
// -----------------------------------------------------------------
// ------------- OnMeasureFrequencyresponse
// -----------------------------------------------------------------
void CAudGenView::OnMeasureFrequencyresponse()
{
StdOperation( new COpMsrFrequency( GetTargetObject(), this) );
}
// -----------------------------------------------------------------
// ------------- OnMeasureImpedance
// -----------------------------------------------------------------
void CAudGenView::OnMeasureImpedance()
{
StdOperation( new COpMsrImpedance( GetTargetObject(), this) );
}
// -----------------------------------------------------------------
// ------------- OnMeasureIntermodulationdistortion
// -----------------------------------------------------------------
void CAudGenView::OnMeasureIntermodulationdistortion()
{
CDlgMsrIntermod cdlg;
COpMsrIntermod *cop = new COpMsrIntermod( GetTargetObject(), this);
CAudtestApp *capp = (CAudtestApp *)AfxGetApp();
MSRINTERMODINFO cinfo;
// is there a registry entry???
if ( capp->ReadRegistry( IDS_KEYINTERINFO, &cinfo, sizeof( cinfo)))
{ // failed, set default values
cinfo.fFreq1 = 19000.0f;
cinfo.fFreq2 = 20000.0f;
cinfo.fPower = 50.0f;
}
cdlg.m_fFreqStart = cinfo.fFreq1;
cdlg.m_fFreqEnd = cinfo.fFreq2;
cdlg.m_fPower = cinfo.fPower;
if ( IDOK == cdlg.DoModal())
{
cinfo.fFreq1 = cdlg.m_fFreqStart;
cinfo.fFreq2 = cdlg.m_fFreqEnd;
cinfo.fPower = cdlg.m_fPower;
capp->WriteRegistry( IDS_KEYINTERINFO, &cinfo, sizeof( cinfo));
cop->SetParms( &cinfo);
StdOperation( cop );
}
}
// -----------------------------------------------------------------
// ------------- OnMeasureMicrophoneresponse
// -----------------------------------------------------------------
void CAudGenView::OnMeasureMicrophoneresponse()
{
StdOperation( new COpMsrMicTotal( GetTargetObject(), this) );
}
// -----------------------------------------------------------------
// ------------- OnMeasureMicGated
// -----------------------------------------------------------------
void CAudGenView::OnMeasureGated()
{
StdOperation( new COpMsrMicAnechoic( GetTargetObject(), this) );
}
// -----------------------------------------------------------------
// ------------- OnMeasurePassivecomponent
// -----------------------------------------------------------------
void CAudGenView::OnMeasurePassivecomponent()
{
StdOperation( new COpMsrPassive( GetTargetObject(), this) );
}
// -----------------------------------------------------------------
// ------------- OnMeasureTimeresponse
// -----------------------------------------------------------------
void CAudGenView::OnMeasureTimeresponse()
{
StdOperation( new COpMsrTime( GetTargetObject(), this) );
}
// -----------------------------------------------------------------
// ------------- OnMeasureTransferfunction
// -----------------------------------------------------------------
//void CAudGenView::OnMeasureTransferfunction()
//{
// StdOperation( new COpMsrTransfer( GetTargetObject(), this) );
//}
// -----------------------------------------------------------------
// ------------- On Sound Stop
// -----------------------------------------------------------------
void CAudGenView::OnSoundStop()
{
CAudtestView::OnSoundStop();
}
void CAudGenView::OnUpdateShowLeftinput(CCmdUI* pCmdUI)
{
enChannel enshow = CAudtestApp::GetShowChannels();
pCmdUI->SetRadio ( chLeft == enshow);
}
void CAudGenView::OnUpdateShowOutput(CCmdUI* pCmdUI)
{
enChannel enshow = CAudtestApp::GetShowChannels();
pCmdUI->SetRadio ( chMono == enshow);
}
void CAudGenView::OnUpdateShowRightinput(CCmdUI* pCmdUI)
{
enChannel enshow = CAudtestApp::GetShowChannels();
pCmdUI->SetRadio ( chRight == enshow);
}
void CAudGenView::OnUpdateShowBothinput(CCmdUI* pCmdUI)
{
enChannel enshow = CAudtestApp::GetShowChannels();
pCmdUI->SetRadio ( chBoth == enshow);
}
void CAudGenView::OnShowLeftinput()
{
enChannel enshow = chLeft;
CAudtestApp::SetShowChannels( enshow);
CAudtestDoc* pDoc = GetDocument();
pDoc->UpdateAllViews( NULL);
}
void CAudGenView::OnShowOutput()
{
enChannel enshow = chMono;
CAudtestApp::SetShowChannels( enshow);
CAudtestDoc* pDoc = GetDocument();
pDoc->UpdateAllViews( NULL);
}
void CAudGenView::OnShowRightinput()
{
enChannel enshow = chRight;
CAudtestApp::SetShowChannels( enshow);
CAudtestDoc* pDoc = GetDocument();
pDoc->UpdateAllViews( NULL);
}
void CAudGenView::OnShowBothinput()
{
enChannel enshow = chBoth;
CAudtestApp::SetShowChannels( enshow);
CAudtestDoc* pDoc = GetDocument();
pDoc->UpdateAllViews( NULL);
}
void CAudGenView::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint)
{
CGenerator *pcgen = (CGenerator *)GetTargetObject();
DWORD dwl, dwr, dwo; // left, right, out
DWORD dwme;
if ( ! pcgen)
return;
// here's where we determine who is in the chart for this guy
if ( (!lHint) || (DWORD )lHint == GetTarget())
{
CSubChart *cchart = (CSubChart *)GetViewChart();
CNamed *cdata;
CString csn;
if ( cchart) // we have a chart, do it
{
CString csr = ".in.r";
CString csl = ".in.l";
RECORDINGINFO rec;
CAudtestApp::GetRecordingInfo( &rec);
csn = pcgen->GetName();
if ( rtTime != rec.m_nDataType) // measuring frequency
{
csr += ".Fft";
csl += ".Fft";
}
if ( rtImpedance == rec.m_nDataType) // measuring frequency
{
csr += ".Z";
csl += ".Z";
}
cdata = pcgen->FindByName( csn + csr);
dwl = (cdata ? cdata->GetID() : 0);
cdata = pcgen->FindByName( csn + csl);
dwr = (cdata ? cdata->GetID() : 0);
cdata = pcgen->FindByName( csn + ".Output");
dwo = (cdata ? cdata->GetID() : 0);
// remove all the datalines
CDataLine *cp = cchart->GetDataAt(0);
if ( cp)
dwme = cp->GetDataID();
else
dwme = 0;
switch( CAudtestApp::GetShowChannels())
{
case chLeft: // left
if ( dwl && dwl != dwme)
{
cchart->DetachAll();
cchart->Attach( dwl);
}
break;
case chRight: // right
if ( dwr && dwr != dwme)
{
cchart->DetachAll();
cchart->Attach( dwr);
}
break;
case chBoth: // both
if ( dwl && dwl != dwme)
{
cchart->DetachAll();
cchart->Attach( dwl);
}
if ( dwr)
cchart->Attach( dwr);
break;
default: // ?????
case chMono: // output
if ( dwo && dwo != dwme)
{
cchart->DetachAll();
cchart->Attach( dwo);
}
break;
}
}
}
CAudchView::OnUpdate( pSender, lHint, pHint);
}
| 24.881978 | 85 | 0.561887 | RDamman |
9b2e3e86a6d2f613704c96e935e7e067bc145360 | 170 | cpp | C++ | toggleConsoleVisibility/toggleConsoleVisibility.cpp | FreeSoftwareDevlopment/play-something-with-windows-api | f5a4341a7cafd8a36430127d913bafe1eb21bc68 | [
"MIT"
] | null | null | null | toggleConsoleVisibility/toggleConsoleVisibility.cpp | FreeSoftwareDevlopment/play-something-with-windows-api | f5a4341a7cafd8a36430127d913bafe1eb21bc68 | [
"MIT"
] | null | null | null | toggleConsoleVisibility/toggleConsoleVisibility.cpp | FreeSoftwareDevlopment/play-something-with-windows-api | f5a4341a7cafd8a36430127d913bafe1eb21bc68 | [
"MIT"
] | null | null | null | #include <Windows.h>
int main()
{
HWND ConsoleWindow{ GetConsoleWindow() };
ShowWindow(ConsoleWindow, (IsWindowVisible(ConsoleWindow) == TRUE) ? SW_HIDE : SW_SHOW);
}
| 21.25 | 89 | 0.729412 | FreeSoftwareDevlopment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.