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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5d3b5b9e898c695ffefec95c21366cb12b21c662 | 2,146 | cpp | C++ | 7zFontChange/7zFontChange.cpp | tekkui/7zFontChange | 6b004019d9b3dd9597cddbb697cfaacef09a4fc5 | [
"MIT"
] | null | null | null | 7zFontChange/7zFontChange.cpp | tekkui/7zFontChange | 6b004019d9b3dd9597cddbb697cfaacef09a4fc5 | [
"MIT"
] | null | null | null | 7zFontChange/7zFontChange.cpp | tekkui/7zFontChange | 6b004019d9b3dd9597cddbb697cfaacef09a4fc5 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <conio.h>
int main()
{
char targetFiles[][10] = { {"7zFM.exe"}, {"7zG.exe"}, {"7z.sfx"}, {""} };
char orgFont[] = { 0x08, 0x00, 'M', 0x00, 'S', 0x00, ' ', 0x00, 'S', 0x00, 'h', 0x00, 'e', 0x00, 'l', 0x00, 'l', 0x00, ' ', 0x00, 'D', 0x00, 'l', 0x00, 'g' };
char newFont[] = { 0x0a, 0x00, 'Y', 0x00, 'u', 0x00, ' ', 0x00, 'G', 0x00, 'o', 0x00, 't', 0x00, 'h', 0x00, 'i', 0x00, 'c', 0x00, ' ', 0x00, 'U', 0x00, 'I' };
for (int t = 0; targetFiles[t][0] != NULL; t++)
{
std::ifstream ifs;
ifs.open(targetFiles[t], std::ios::in | std::ios::binary);
if (!ifs)
{
std::cout << targetFiles[t] << " not found" << std::endl;
continue;
}
ifs.seekg(0, std::fstream::end);
std::streamoff eofPos = ifs.tellg();
ifs.clear();
ifs.seekg(0, std::fstream::beg);
std::streamoff begPos = ifs.tellg();
int size = (int)(eofPos - begPos);
char *buf = new char[size];
memset(buf, 0, size);
ifs.read(buf, size);
ifs.close();
int oSize = sizeof(orgFont);
int nSize = sizeof(newFont);
std::cout << "Search from " << targetFiles[t] << std::endl;
bool changed = false;
for (int i = 0; i < size; i++)
{
if (buf[i] == orgFont[0])
{
for (int j = 1; j < oSize; j++)
{
if (buf[i + j] != orgFont[j])
{
break;
}
else
{
if (j == oSize - 1)
{
std::cout << "Found at 0x" << std::hex << i << std::endl;
changed = true;
for (j = 0; j < nSize; j++)
buf[i + j] = newFont[j];
break;
}
}
}
}
}
if (changed)
{
std::string newName(targetFiles[t]);
newName += ".Original";
std::rename(targetFiles[t], newName.c_str());
std::cout << "Change to " << newName.c_str() << std::endl;
std::ofstream ofs;
ofs.open(targetFiles[t], std::ios::out | std::ios::trunc | std::ios::binary);
ofs.write(buf, size);
ofs.close();
std::cout << "Rewritten and saved" << std::endl;
}
delete[] buf;
}
std::cout << "Press any key to continue ..." << std::endl;
_getch();
}
| 25.247059 | 160 | 0.496272 | tekkui |
5d3c799af8ac2897e4c62cb85742a23d22f98175 | 5,138 | hpp | C++ | src/TNL/Solvers/PDE/TimeIndependentPDESolver.hpp | GregTheMadMonk/tnl-noa | d7d57962decf579a89797816e7d564350157cbf2 | [
"MIT"
] | null | null | null | src/TNL/Solvers/PDE/TimeIndependentPDESolver.hpp | GregTheMadMonk/tnl-noa | d7d57962decf579a89797816e7d564350157cbf2 | [
"MIT"
] | null | null | null | src/TNL/Solvers/PDE/TimeIndependentPDESolver.hpp | GregTheMadMonk/tnl-noa | d7d57962decf579a89797816e7d564350157cbf2 | [
"MIT"
] | null | null | null | // Copyright (c) 2004-2022 Tomáš Oberhuber et al.
//
// This file is part of TNL - Template Numerical Library (https://tnl-project.org/)
//
// SPDX-License-Identifier: MIT
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#pragma once
#include <noa/3rdparty/tnl-noa/src/TNL/Solvers/PDE/TimeIndependentPDESolver.h>
#include <noa/3rdparty/tnl-noa/src/TNL/Meshes/TypeResolver/resolveMeshType.h>
#include <noa/3rdparty/tnl-noa/src/TNL/Meshes/TypeResolver/resolveDistributedMeshType.h>
#include <noa/3rdparty/tnl-noa/src/TNL/MPI/Comm.h>
namespace noa::TNL {
namespace Solvers {
namespace PDE {
template< typename Problem >
TimeIndependentPDESolver< Problem >::TimeIndependentPDESolver() : problem( 0 )
{}
template< typename Problem >
void
TimeIndependentPDESolver< Problem >::configSetup( Config::ConfigDescription& config, const String& prefix )
{}
template< typename Problem >
bool
TimeIndependentPDESolver< Problem >::setup( const Config::ParameterContainer& parameters, const String& prefix )
{
/////
// Load the mesh from the mesh file
//
const String& meshFile = parameters.getParameter< String >( "mesh" );
const String& meshFileFormat = parameters.getParameter< String >( "mesh-format" );
if( MPI::GetSize() > 1 ) {
if( ! Meshes::loadDistributedMesh( *distributedMeshPointer, meshFile, meshFileFormat ) )
return false;
problem->setMesh( distributedMeshPointer );
}
else {
if( ! Meshes::loadMesh( *meshPointer, meshFile, meshFileFormat ) )
return false;
problem->setMesh( meshPointer );
}
/****
* Set-up common data
*/
if( ! this->commonDataPointer->setup( parameters ) ) {
std::cerr << "The problem common data initiation failed!" << std::endl;
return false;
}
problem->setCommonData( this->commonDataPointer );
/****
* Setup the problem
*/
if( ! problem->setup( parameters, prefix ) ) {
std::cerr << "The problem initiation failed!" << std::endl;
return false;
}
/****
* Set DOFs (degrees of freedom)
*/
TNL_ASSERT_GT( problem->getDofs(), 0, "number of DOFs must be positive" );
this->dofs->setSize( problem->getDofs() );
this->dofs->setValue( 0.0 );
this->problem->bindDofs( this->dofs );
/***
* Set-up the initial condition
*/
std::cout << "Setting up the initial condition ... ";
if( ! this->problem->setInitialCondition( parameters, this->dofs ) )
return false;
std::cout << " [ OK ]" << std::endl;
return true;
}
template< typename Problem >
bool
TimeIndependentPDESolver< Problem >::writeProlog( Logger& logger, const Config::ParameterContainer& parameters )
{
logger.writeHeader( problem->getPrologHeader() );
problem->writeProlog( logger, parameters );
logger.writeSeparator();
if( MPI::GetSize() > 1 )
distributedMeshPointer->writeProlog( logger );
else
meshPointer->writeProlog( logger );
logger.writeSeparator();
const String& solverName = parameters.getParameter< String >( "discrete-solver" );
logger.writeParameter< String >( "Discrete solver:", "discrete-solver", parameters );
if( solverName == "sor" )
logger.writeParameter< double >( "Omega:", "sor-omega", parameters, 1 );
if( solverName == "gmres" )
logger.writeParameter< int >( "Restarting:", "gmres-restarting", parameters, 1 );
logger.writeParameter< double >( "Convergence residue:", "convergence-residue", parameters );
logger.writeParameter< double >( "Divergence residue:", "divergence-residue", parameters );
logger.writeParameter< int >( "Maximal number of iterations:", "max-iterations", parameters );
logger.writeParameter< int >( "Minimal number of iterations:", "min-iterations", parameters );
logger.writeSeparator();
return BaseType::writeProlog( logger, parameters );
}
template< typename Problem >
void
TimeIndependentPDESolver< Problem >::setProblem( ProblemType& problem )
{
this->problem = &problem;
}
template< typename Problem >
bool
TimeIndependentPDESolver< Problem >::solve()
{
TNL_ASSERT_TRUE( problem, "No problem was set in tnlPDESolver." );
this->computeTimer->reset();
this->computeTimer->start();
if( ! this->problem->solve( this->dofs ) ) {
this->computeTimer->stop();
return false;
}
this->computeTimer->stop();
return true;
}
template< typename Problem >
bool
TimeIndependentPDESolver< Problem >::writeEpilog( Logger& logger ) const
{
return this->problem->writeEpilog( logger );
}
} // namespace PDE
} // namespace Solvers
} // namespace noa::TNL
| 34.02649 | 112 | 0.637602 | GregTheMadMonk |
5d43c49f8044846a95d6befdd975f812c1f39d1b | 2,811 | hpp | C++ | utility/lip_filter/LIPFilterUtil.hpp | Hacker0912/quickstep-datalog | 1de22e7ab787b5efa619861a167a097ff6a4f549 | [
"Apache-2.0"
] | 82 | 2016-04-18T03:59:06.000Z | 2019-02-04T11:46:08.000Z | utility/lip_filter/LIPFilterUtil.hpp | Hacker0912/quickstep-datalog | 1de22e7ab787b5efa619861a167a097ff6a4f549 | [
"Apache-2.0"
] | 265 | 2016-04-19T17:52:43.000Z | 2018-10-11T17:55:08.000Z | utility/lip_filter/LIPFilterUtil.hpp | Hacker0912/quickstep-datalog | 1de22e7ab787b5efa619861a167a097ff6a4f549 | [
"Apache-2.0"
] | 68 | 2016-04-18T05:00:34.000Z | 2018-10-30T12:41:02.000Z | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 QUICKSTEP_UTILITY_LIP_FILTER_LIP_FILTER_UTIL_HPP_
#define QUICKSTEP_UTILITY_LIP_FILTER_LIP_FILTER_UTIL_HPP_
#include "query_execution/QueryContext.hpp"
#include "utility/lip_filter/LIPFilterDeployment.hpp"
namespace quickstep {
class LIPFilterBuilder;
class LIPFilterAdaptiveProber;
/** \addtogroup Utility
* @{
*/
/**
* @brief Create a LIPFilterBuilder for the given LIPFilterDeployment in QueryContext.
*
* @param lip_deployment_index The id of the LIPFilterDeployment in QueryContext.
* @param query_context The QueryContext.
* @return A LIPFilterBuilder object, or nullptr if \p lip_deployment_index is invalid.
*/
inline LIPFilterBuilder* CreateLIPFilterBuilderHelper(
const QueryContext::lip_deployment_id lip_deployment_index,
const QueryContext *query_context) {
if (lip_deployment_index == QueryContext::kInvalidLIPDeploymentId) {
return nullptr;
} else {
const LIPFilterDeployment *lip_filter_deployment =
query_context->getLIPDeployment(lip_deployment_index);
return lip_filter_deployment->createLIPFilterBuilder();
}
}
/**
* @brief Create a LIPFilterAdaptiveProber for the given LIPFilterDeployment
* in QueryContext.
*
* @param lip_deployment_index The id of the LIPFilterDeployment in QueryContext.
* @param query_context The QueryContext.
* @return A LIPFilterAdaptiveProber object, or nullptr if \p lip_deployment_index
* is invalid.
*/
inline LIPFilterAdaptiveProber* CreateLIPFilterAdaptiveProberHelper(
const QueryContext::lip_deployment_id lip_deployment_index,
const QueryContext *query_context) {
if (lip_deployment_index == QueryContext::kInvalidLIPDeploymentId) {
return nullptr;
} else {
const LIPFilterDeployment *lip_filter_deployment =
query_context->getLIPDeployment(lip_deployment_index);
return lip_filter_deployment->createLIPFilterAdaptiveProber();
}
}
/** @} */
} // namespace quickstep
#endif // QUICKSTEP_UTILITY_LIP_FILTER_LIP_FILTER_UTIL_HPP_
| 35.1375 | 87 | 0.775169 | Hacker0912 |
5d44db36a657480341dc9405b3f7e9bc7964f215 | 13,940 | cpp | C++ | DreamDaq/codeBackup/DreamDaq.101104/myFIFO-IO.cpp | ivivarel/DREMTubes | ac768990b4c5e2c23d986284ed10189f31796b38 | [
"MIT"
] | 3 | 2021-07-22T12:17:48.000Z | 2021-07-27T07:22:54.000Z | DreamDaq/codeBackup/DreamDaq.101104/myFIFO-IO.cpp | ivivarel/DREMTubes | ac768990b4c5e2c23d986284ed10189f31796b38 | [
"MIT"
] | 38 | 2021-07-14T15:41:04.000Z | 2022-03-29T14:18:20.000Z | DreamDaq/codeBackup/DreamDaq.101104/myFIFO-IO.cpp | ivivarel/DREMTubes | ac768990b4c5e2c23d986284ed10189f31796b38 | [
"MIT"
] | 7 | 2021-07-21T12:00:33.000Z | 2021-11-13T10:45:30.000Z | //$Id: myFIFO-IO.cpp,v 1.19 2009/07/21 09:14:45 dreamdaq Exp $
/*************************************************************************
myIO.c
------
This file contains all related I/O stuff.
Version 0.1, A.Cardini 3/6/2001
Version 0.2, D.Raspino 27/7/2005 Data From Slow Control
*************************************************************************/
extern "C" {
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
}
#include <iostream>
#include <vector>
#include "myFIFO-IOp.h"
#include "myFIFO-IO.h"
#include "myFIFOWriter.h"
#include "myOscDataFile.h"
#include "traceSegv.h"
// Some definitions
#define IMAGIC 0xAABBCCDD
#define SMAGIC 0xDDCCBBAA
using namespace std;
// Global variables
int myEventNumber = 0;
vector<updatable *> EvtList;
updatable * thisEv;
unsigned int nupd=0;
//RunHeader myRH;
unsigned int mybuff[1000000]; // This is the buffer to temporary store all data
EventHeader * myEH= (EventHeader *)(void *)mybuff;
myFIFOWriter * fifo;
myFIFOWriter * pedFifo;
unsigned int buffsize; // Size of how much memory is used
unsigned int * subevsize;
char * daytime()
{
static char _day_time_[30];
time_t result = time(NULL);
memcpy(_day_time_, asctime(localtime(&result)), 24);
_day_time_[24] = 0;
return _day_time_;
}
/************************************************************************/
int myUpdateOscData(unsigned int samples, unsigned int run,
unsigned int spill, unsigned int chmask,
unsigned int pts)
/************************************************************************/
{
unsigned int i,j;
unsigned int f;
updatable * updateinfo;
FILE * files[4];
string names[4];
unsigned int dataoff[4];
unsigned int nch=0;
if(samples==0)
return 0;
if(samples>nupd){
cout << "Required samples " << samples << " larger than available " << nupd<< endl;
return 1;
}
// cout << "Going to update " << samples << " events" << endl;
for(i=0;i<4;i++){
if((chmask>>i)&1){
names[nch]=filename(run,spill,i+1,true);
files[nch]=fopen(names[nch].c_str(),"r");
if(files[nch]==NULL){
cout << "Cannot open file " << names[nch] << endl;
return 1;
}
//go where the data offset is
fseek(files[nch],16,SEEK_SET);
fread(&dataoff[nch],sizeof(unsigned int),1,files[nch]);
swapbytes(&dataoff[nch],sizeof(unsigned int));
//go where the #FRAME-1 is
unsigned int frames;
fseek(files[nch],72,SEEK_SET);
fread(&frames,sizeof(unsigned int),1,files[nch]);
swapbytes(&frames,sizeof(unsigned int));
if((frames+1)<samples){
cout << "Not enough frames in file " << names[nch] << endl;
return 1;
}
//go where the data is
fseek(files[nch],dataoff[nch],SEEK_SET);
nch++;
}
}
unsigned int chdatasizes=chdatasizebyte(pts,nch)/(sizeof(unsigned short)*nch);
for(i=0;i<samples;i++){
updateinfo = EvtList[i];
if(updateinfo->datasize!=0){
unsigned int writtenshort=0;
unsigned int writtenshort2=0;
bool trunc=false;
unsigned int partials=0;
unsigned short * buffers=0;
unsigned short * buffer2s=0;
unsigned int remw=0;
if(updateinfo->partialsize>(sizeof(oscheader)/sizeof(unsigned int))){
partials=updateinfo->partialsize*sizeof(unsigned int)/sizeof(unsigned short);
partials-=sizeof(oscheader)/sizeof(unsigned short);
buffers=(unsigned short *)&(updateinfo->buffer[sizeof(oscheader)/sizeof(unsigned int)]);
buffer2s=(unsigned short *)(updateinfo->buffer2);
}else{
trunc=true;
remw=(sizeof(oscheader)/sizeof(unsigned int))-updateinfo->partialsize;
buffer2s=(unsigned short *)&(updateinfo->buffer2[remw]);
}
for(f=0;f<nch;f++){
//updatable info is in word
if(!trunc){
unsigned int shorttow=partials-writtenshort;
if(shorttow<chdatasizes){
//truncated
fread(&buffers[writtenshort],sizeof(unsigned short),shorttow,files[f]);
writtenshort2+=fread(buffer2s,sizeof(unsigned short),chdatasizes-shorttow,files[f]);
trunc=true;
}else{
unsigned int nitems;
writtenshort+=(nitems = fread(&buffers[writtenshort],sizeof(unsigned short),chdatasizes,files[f]));
if(nitems!=chdatasizes)
printf("Fread error %s\n",strerror(errno));
if(shorttow==chdatasizes)
trunc=true;
}
}else{
writtenshort2+=fread(&buffer2s[writtenshort2],sizeof(unsigned short),chdatasizes,files[f]);
}
}
//swapping
if(updateinfo->partialsize>(sizeof(oscheader)/sizeof(unsigned int))){
for(j=((sizeof(oscheader)/sizeof(unsigned short)));j<(updateinfo->partialsize*sizeof(unsigned int)/sizeof(unsigned short));j++)
swapbytes(&(((short *)updateinfo->buffer)[j]),sizeof(unsigned short));
for(j=0;j<((updateinfo->datasize-updateinfo->partialsize)*sizeof(unsigned int)/sizeof(unsigned short));j++)
swapbytes(&(((short *)updateinfo->buffer2)[j]),sizeof(unsigned short));
}else{
for(j=remw*sizeof(unsigned int)/sizeof(unsigned short);j<((updateinfo->datasize-updateinfo->partialsize)*sizeof(unsigned int)/sizeof(unsigned short));j++)
swapbytes(&(((short *)updateinfo->buffer2)[j]),sizeof(unsigned short));
}
}else{
cout << "Skipping cleared"<< endl;
for(f=0;f<nch;f++)
fseek(files[f],chdatasizes*sizeof(unsigned short),SEEK_CUR);
}
}
for(i=0;i<nch;i++)
fclose(files[i]);
nupd=0;
return 0;
}
/************************************************************************/
int myResetTypeCounters()
/************************************************************************/
{
unsigned int i;
for(i=0;i<EvtList.size();i++)
delete EvtList[i];
EvtList.clear();
return 0;
}
/************************************************************************/
int myMaxEvents()
/************************************************************************/
{
// Return max events according to
// environnment variable MAXEVT
char* envs = getenv("MAXEVT");
return (envs == NULL) ? 10000 : atol(envs);
}
/************************************************************************/
int myPhysPedRatio()
/************************************************************************/
{
// Return physics/pedestal ratio according to
// environnment variable PHYSPEDRATIO
char* envs = getenv("PHYSPEDRATIO");
return (envs == NULL) ? 10 : atol(envs);
}
/************************************************************************/
int myMaxPedEvents()
/************************************************************************/
{
// Return max pedestal events according to
// environnment variable MAXPEDEVT
char* envs = getenv("MAXPEDEVT");
return (envs == NULL) ? 1000 : atol(envs);
}
/************************************************************************/
int myDownscaleFactor()
/************************************************************************/
{
// Return downscale factor according to
// environnment variable DWNSCALE
int dwnscale;
if (getenv("DWNSCALE") == NULL)
dwnscale = 1; // Default is no downscale...
else {
dwnscale = atol(getenv("DWNSCALE"));
}
return dwnscale;
}
/************************************************************************/
int myReloadTDCConfig()
/************************************************************************/
{
// Return reload TDC Configuration factor according to
// environnment variable RELOAD_TDC_CONFIG
int rtc;
if (getenv("RELOAD_TDC_CONF") == NULL)
rtc = 1; // Default is reload
else {
rtc = atol(getenv("RELOAD_TDC_CONF"));
}
return rtc;
}
/************************************************************************/
int myOpenRun(volatile bool * abort_run)
/************************************************************************/
{
pedFifo = new myFIFOWriter(PED_BASE_KEY);
if(pedFifo->isvalid()){
cout << "Pedestal fifo is valid" << endl;
}
else{
cout << "Pedestal fifo is not valid" << endl;
*abort_run=true;
return 1;
}
pedFifo->waitlock();
fifo = new myFIFOWriter(PHYS_BASE_KEY);
if(fifo->isvalid()){
cout << "Event fifo is valid" << endl;
}
else{
cout << "Event fifo is not valid" << endl;
*abort_run=true;
return 1;
}
fifo->waitlock();
return 0 ; cout << "Waiting for readers ... "<<flush;
while(!(fifo->isReaderPresent()
&& pedFifo->isReaderPresent())
&& !(*abort_run))
usleep(1000);
cout << "done" << endl;
return 0;
}
/************************************************************************/
int myCloseRun()
/************************************************************************/
{
myResetTypeCounters();
fifo->unlock();
pedFifo->unlock();
delete fifo;
delete pedFifo;
return 0;
}
static uint32_t n_full(0);
/************************************************************************/
int myWriteEvent(unsigned int spill,unsigned int isPhysEvent)
/************************************************************************/
{
struct timeval tv;
struct timezone tz;
// Event time with microsecond resolution...
gettimeofday(&tv, &tz);
// Write Event Header and data
myEH->evmark = EVMARK;
myEH->evhsiz = sizeof(EventHeader);
myEH->evsiz = buffsize * sizeof(unsigned int);
myEH->evnum = myEventNumber;
myEH->spill = spill;
myEH->tsec = tv.tv_sec; // Event time in seconds
myEH->tusec = tv.tv_usec; // ...and in microseconds
myFIFOWriter * tmpfifo;
thisEv->eventnumber=myEventNumber;
if(isPhysEvent){
tmpfifo=fifo;
}else{
tmpfifo=pedFifo;
}
myEventNumber++;
myFIFO::result result;
do{
result = tmpfifo->write(mybuff,thisEv);
if(result==myFIFO::FIFOFULL){
if ((n_full & 0xFF) == 0){
if(isPhysEvent)
cout<< "Data FIFO is FULL" << endl;
else
cout<< "Pedestal FIFO is FULL" << endl;
}
n_full ++;
tmpfifo->unlock();
usleep(1000);
tmpfifo->waitlock();
}else if(result==myFIFO::RDLOCKED){
cout<< "FIFO blocked by reader" << endl;
}
}
while(result!=myFIFO::SUCCESS);
return 0;
}
/************************************************************************/
int myNewEvent(bool cleared)
/************************************************************************/
{
if(nupd<EvtList.size())
thisEv=EvtList[nupd];
else{
thisEv = new updatable();
EvtList.push_back(thisEv);
}
thisEv->datasize=0;
nupd++;
if(!cleared){
buffsize = sizeof(EventHeader)/sizeof(unsigned int); // Reset total event length
}else{
thisEv->eventnumber=myEventNumber;
myEventNumber++;
}
return 0;
}
/************************************************************************/
int myFormatOscSubEvent(unsigned int moduleId)
/************************************************************************/
{
myFormatSubEvent(moduleId);
thisEv->dataoffset=buffsize;
return 0;
}
/************************************************************************/
int myFormatSubEvent(unsigned int moduleId)
/************************************************************************/
{
SubEventHeader * mySEH;
mySEH=(SubEventHeader *)&mybuff[buffsize];
mySEH->semk = SUBEVMARK;
mySEH->sevhsiz = sizeof(SubEventHeader);
mySEH->id = moduleId;
mySEH->size = 0;
subevsize = &(mySEH->size);
buffsize+=sizeof(SubEventHeader)/sizeof(unsigned int);
return 0;
}
int myUpdateOscSubEvent(unsigned int size)
{
thisEv->datasize=size;
myUpdateSubEvent(size);
return 0;
}
int myUpdateSubEvent(unsigned int size)
{
if(size>0){
*subevsize = sizeof(SubEventHeader) + size*sizeof(unsigned int);
buffsize +=size;
}else{
buffsize -=sizeof(SubEventHeader)/sizeof(unsigned int);
}
return 0;
}
/************************************************************************/
int myFIFOunlock()
/************************************************************************/
{
fifo->unlock();
pedFifo->unlock();
return 0;
}
/************************************************************************/
int myFIFOlock()
/************************************************************************/
{
fifo->waitlock();
fifo->updateSamplingPoint();
pedFifo->waitlock();
pedFifo->updateSamplingPoint();
return 0;
}
/************************************************************************/
double myFIFOOccupancy()
/************************************************************************/
{
return fifo->bufferOccupancy();
}
/************************************************************************/
double myPedFIFOOccupancy()
/************************************************************************/
{
return pedFifo->bufferOccupancy();
}
/************************************************************************/
unsigned int * myBuffer(unsigned int **size)
/************************************************************************/
{
*size=&buffsize;
return mybuff;
}
/************************************************************************/
void myFIFOUpdateSpillNr()
/************************************************************************/
{
fifo->updateSpillNr();
pedFifo->updateSpillNr();
}
/************************************************************************/
void myFIFObackup()
/************************************************************************/
{
fifo->backup();
pedFifo->backup();
}
/************************************************************************/
void myFIFOrestore()
/************************************************************************/
{
fifo->restore();
pedFifo->restore();
}
| 26.056075 | 155 | 0.489096 | ivivarel |
5d46bda9b671223a0c6a0c1c66f870a28ab4d76a | 3,520 | cpp | C++ | GameClient/RemoteTank.cpp | SamirAroudj/BaseProject | 50ede52bd6fa7b20d6ecb8a11bc1193ef841d91d | [
"BSD-3-Clause"
] | null | null | null | GameClient/RemoteTank.cpp | SamirAroudj/BaseProject | 50ede52bd6fa7b20d6ecb8a11bc1193ef841d91d | [
"BSD-3-Clause"
] | 1 | 2019-06-19T15:55:25.000Z | 2019-06-27T07:47:27.000Z | GameClient/RemoteTank.cpp | SamirAroudj/BaseProject | 50ede52bd6fa7b20d6ecb8a11bc1193ef841d91d | [
"BSD-3-Clause"
] | 1 | 2019-07-07T04:37:56.000Z | 2019-07-07T04:37:56.000Z | /*
* Copyright (C) 2017 by Author: Aroudj, Samir, born in Suhl, Thueringen, Germany
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD 3-Clause license. See the License.txt file for details.
*/
#include "ClientTimeManager.h"
#include "RemoteTank.h"
using namespace GamePlay;
using namespace Math;
using namespace Network;
using namespace Platform;
using namespace std;
RemoteTank::RemoteTank(const uint16 identifier, const Vector2 &position, Real angle) :
Tank(identifier, position, angle),
mGraphics("Tank.mat", "Tank.mesh"),
mRemoteUpdate(NULL),
mConversionFactor(1.0f)
{
}
RemoteTank::RemoteTank(const RemoteTank ©) :
Tank(copy),
mGraphics(copy.mGraphics),
mRemoteUpdate(NULL),
mConversionFactor(copy.mConversionFactor)
{
if (copy.mRemoteUpdate)
mRemoteUpdate = new Tank(*copy.mRemoteUpdate);
}
RemoteTank::~RemoteTank()
{
delete mRemoteUpdate;
}
RemoteTank &RemoteTank::operator =(const RemoteTank &rhs)
{
if (&rhs == this)
return *this;
Tank::operator=(rhs);
mGraphics = rhs.mGraphics;
mConversionFactor = rhs.mConversionFactor;
if (rhs.mRemoteUpdate)
{
if (mRemoteUpdate)
*mRemoteUpdate = *rhs.mRemoteUpdate;
else
mRemoteUpdate = new Tank(*rhs.mRemoteUpdate);
}
else
{
delete mRemoteUpdate;
mRemoteUpdate = NULL;
}
return *this;
}
void RemoteTank::processRemoteUpdate(const Tank &remoteUpdate, bool smooth)
{
assert(remoteUpdate.getIdentifier() == mIdentifier);
if (!smooth)
{
Tank::operator=(remoteUpdate);
delete mRemoteUpdate;
mRemoteUpdate = NULL;
return;
}
if (mRemoteUpdate)
*mRemoteUpdate = remoteUpdate;
else
mRemoteUpdate = new Tank(remoteUpdate);
mConversionFactor = 1.0f;
mBraking = remoteUpdate.isBraking();
}
void RemoteTank::render(const Matrix4x4 &viewProjection)
{
Matrix4x4 scale;
scale._11 = scale._22 = scale._33 = 0.005f;
Matrix4x4 world = scale * Matrix4x4::createRotationY(mAngle);
world.addTranslation(mPosition.x, 0.0f, mPosition.y);
mGraphics.render(world * viewProjection, world);
}
void RemoteTank::update(Real deltaTime)
{
Tank::update(deltaTime);
if (mRemoteUpdate)
{
mRemoteUpdate->update(deltaTime);
convertToRemoteUpdate(deltaTime);
}
}
void RemoteTank::convertToRemoteUpdate(Real deltaTime)
{
assert(mRemoteUpdate);
Real factor1 = deltaTime * (isBraking() ? 10.0f : 5.0f);
Real factor2 = 1.0f - factor1;
mPosition.x = factor1 * mRemoteUpdate->getXCoordinate() + factor2 * mPosition.x;
mPosition.y = factor1 * mRemoteUpdate->getZCoordinate() + factor2 * mPosition.y;
mAcceleration = factor1 * mRemoteUpdate->getAcceleration() + factor2 * mAcceleration;
mAngularAcceleration = factor1 * mRemoteUpdate->getAngularAcceleration() + factor2 * mAngularAcceleration;
mAngularVelocity = factor1 * mRemoteUpdate->getAngularVelocity() + factor2 * mAngularVelocity;
mVelocity = factor1 * mRemoteUpdate->getVelocity() + factor2 * mVelocity;
Real diff = mAngle - mRemoteUpdate->getAngle(); // take the shorter way, don't turn more than PI to align the simulations
if (diff > PI)
mAngle = factor1 * mRemoteUpdate->getAngle() + factor2 * (mAngle - TWO_PI);
else if (diff < -PI)
mAngle = factor1 * mRemoteUpdate->getAngle() + factor2 * (mAngle + TWO_PI);
else
mAngle = factor1 * mRemoteUpdate->getAngle() + factor2 * mAngle;
mConversionFactor *= factor2;
if (mConversionFactor < 0.01f)
{
Tank::operator=(*mRemoteUpdate);
delete mRemoteUpdate;
mRemoteUpdate = NULL;
return;
}
}
| 26.268657 | 122 | 0.727273 | SamirAroudj |
5d4a6a90524e3302bdab72eca42cb24be59f2c5c | 1,271 | cpp | C++ | gift1/gift1.cpp | rknightly/usaco-training | 3ba9fc383ef87d32046d6c5f3537b48edf769da2 | [
"MIT"
] | null | null | null | gift1/gift1.cpp | rknightly/usaco-training | 3ba9fc383ef87d32046d6c5f3537b48edf769da2 | [
"MIT"
] | null | null | null | gift1/gift1.cpp | rknightly/usaco-training | 3ba9fc383ef87d32046d6c5f3537b48edf769da2 | [
"MIT"
] | null | null | null | /*
PROB: gift1
LANG: C++11
*/
#include <iostream>
#include <fstream>
using namespace std;
struct Friend {
string name = "";
int account = 0;
};
int main() {
ofstream fout ("gift1.out");
ifstream fin ("gift1.in");
int studentCount;
fin >> studentCount;
// Get friend names
Friend friends[10];
for(int i=0; i<studentCount; i++) {
fin >> friends[i].name;
}
string name;
int giver, giving, friendCount;
for(int i=0; i<studentCount; i++) {
fin >> name;
// Find giving student
for(int i=0; i<studentCount; i++) {
if (friends[i].name == name) {
fin >> giving >> friendCount;
giver = i;
}
}
if (friendCount == 0) {
continue;
}
int giftAmount = giving / friendCount;
string friendName;
for(int i=0; i<friendCount; i++) {
fin >> friendName;
for(int i=0; i<studentCount; i++) {
if (friendName == friends[i].name) {
friends[i].account += giftAmount;
friends[giver].account -= giftAmount;
}
}
}
}
// print results
for(int i=0; i<studentCount; i++) {
fout << friends[i].name << ' ' << friends[i].account << endl;
}
return 0;
}
| 21.183333 | 67 | 0.520063 | rknightly |
5d4c48e33c0a01292d64d460da2f31fa4e91cd61 | 3,639 | cpp | C++ | html/parser.cpp | johnor/hastur | d12c92e744da42aed0adc4cb26aed6c1db7d8613 | [
"BSD-2-Clause"
] | 10 | 2021-01-26T10:39:14.000Z | 2022-03-02T21:19:19.000Z | html/parser.cpp | johnor/hastur | d12c92e744da42aed0adc4cb26aed6c1db7d8613 | [
"BSD-2-Clause"
] | 71 | 2021-04-25T19:44:27.000Z | 2022-03-27T15:52:51.000Z | html/parser.cpp | johnor/hastur | d12c92e744da42aed0adc4cb26aed6c1db7d8613 | [
"BSD-2-Clause"
] | 4 | 2021-03-01T20:14:58.000Z | 2021-09-17T10:38:18.000Z | // SPDX-FileCopyrightText: 2021 Robin Lindén <dev@robinlinden.eu>
//
// SPDX-License-Identifier: BSD-2-Clause
#include "html/parser.h"
#include <spdlog/spdlog.h>
#include <cassert>
#include <cctype>
#include <string>
using namespace std::literals;
namespace html {
namespace {
dom::AttrMap into_dom_attributes(std::vector<html2::Attribute> const &attributes) {
dom::AttrMap attrs{};
for (auto const &[name, value] : attributes) {
attrs[name] = value;
}
return attrs;
}
} // namespace
void Parser::on_token(html2::Token &&token) {
if (auto doctype = std::get_if<html2::DoctypeToken>(&token)) {
if (doctype->name.has_value()) {
doc_.doctype = *(doctype->name);
}
} else if (auto start_tag = std::get_if<html2::StartTagToken>(&token)) {
if (start_tag->tag_name == "html"sv) {
doc_.html().name = start_tag->tag_name;
doc_.html().attributes = into_dom_attributes(start_tag->attributes);
open_elements_.push(&doc_.html());
seen_html_tag_ = true;
return;
}
if (open_elements_.empty() && !seen_html_tag_) {
spdlog::warn("Start tag [{}] encountered before html element was opened", start_tag->tag_name);
doc_.html().name = "html"s;
open_elements_.push(&doc_.html());
seen_html_tag_ = true;
} else if (open_elements_.empty()) {
spdlog::warn("Start tag [{}] encountered with no open elements", start_tag->tag_name);
return;
}
generate_text_node_if_needed();
auto &new_element = open_elements_.top()->children.emplace_back(
dom::Element{start_tag->tag_name, into_dom_attributes(start_tag->attributes), {}});
if (!start_tag->self_closing) {
// This may seem risky since vectors will move their storage about
// if they need it, but we only ever add new children to the
// top-most element in the stack, so this pointer will be valid
// until it's been popped from the stack and we add its siblings.
open_elements_.push(std::get_if<dom::Element>(&new_element));
}
} else if (auto end_tag = std::get_if<html2::EndTagToken>(&token)) {
if (open_elements_.empty()) {
spdlog::warn("End tag [{}] encountered with no elements still open", end_tag->tag_name);
return;
}
generate_text_node_if_needed();
auto const &expected_tag = open_elements_.top()->name;
if (end_tag->tag_name != expected_tag) {
spdlog::warn("Unexpected end_tag name, expected [{}] but got [{}]", expected_tag, end_tag->tag_name);
return;
}
open_elements_.pop();
} else if (std::get_if<html2::CommentToken>(&token) != nullptr) {
// Do nothing.
} else if (auto character = std::get_if<html2::CharacterToken>(&token)) {
current_text_ << character->data;
} else if (std::get_if<html2::EndOfFileToken>(&token) != nullptr) {
if (!open_elements_.empty()) {
spdlog::warn("EOF reached with [{}] elements still open", open_elements_.size());
}
}
}
void Parser::generate_text_node_if_needed() {
assert(!open_elements_.empty());
auto text = current_text_.str();
current_text_ = std::stringstream{};
bool is_uninteresting = std::all_of(cbegin(text), cend(text), [](unsigned char c) { return std::isspace(c); });
if (is_uninteresting) {
return;
}
open_elements_.top()->children.emplace_back(dom::Text{std::move(text)});
}
} // namespace html
| 34.990385 | 115 | 0.613905 | johnor |
5d4d714aa19a5aac1faeb5d0bac074450792bc25 | 238 | cpp | C++ | src/scb_fw/EventCollector.cpp | DonTassettitos/AIR | 92c93f05d6f15095d403dcbbe7ebe16563198697 | [
"BSD-3-Clause"
] | null | null | null | src/scb_fw/EventCollector.cpp | DonTassettitos/AIR | 92c93f05d6f15095d403dcbbe7ebe16563198697 | [
"BSD-3-Clause"
] | null | null | null | src/scb_fw/EventCollector.cpp | DonTassettitos/AIR | 92c93f05d6f15095d403dcbbe7ebe16563198697 | [
"BSD-3-Clause"
] | null | null | null | #include "EventCollector.hpp"
using namespace scb_fw;
/**
* Simple constructor.
* */
EventCollector::EventCollector(const int tag, const int rank, const int worldSize) :
scb::EventCollector(tag, rank, worldSize) {
setBaseline('w');
} | 21.636364 | 84 | 0.731092 | DonTassettitos |
5d4ffa0775e55fcdaf6a2ccb8f60f5c25167b17d | 1,276 | cpp | C++ | Chapter06/04_hidden_friend__copy_and_swap.cpp | gbellizio/Software-Architecture-with-Cpp | eb0f7a52ef1253d9b0091714eee9c94c156b02bc | [
"MIT"
] | 193 | 2021-03-27T00:46:13.000Z | 2022-03-29T07:25:00.000Z | Chapter06/04_hidden_friend__copy_and_swap.cpp | gbellizio/Software-Architecture-with-Cpp | eb0f7a52ef1253d9b0091714eee9c94c156b02bc | [
"MIT"
] | 6 | 2021-03-26T05:48:17.000Z | 2022-02-15T12:16:54.000Z | Chapter06/04_hidden_friend__copy_and_swap.cpp | gbellizio/Software-Architecture-with-Cpp | eb0f7a52ef1253d9b0091714eee9c94c156b02bc | [
"MIT"
] | 64 | 2021-04-01T02:18:55.000Z | 2022-03-14T12:32:29.000Z | #include <algorithm>
#include <cassert>
#include <utility>
template <typename T>
class Array {
public:
Array(T *array, int size) : array_{array}, size_{size} {}
Array(const Array &other) : array_{new T[other.size_]}, size_{other.size_} {
std::copy_n(other.array_, size_, array_);
}
Array(Array &&other) noexcept
: array_{std::exchange(other.array_, nullptr)},
size_{std::exchange(other.size_, 0)} {}
Array &operator=(Array other) noexcept {
swap(*this, other);
return *this;
}
~Array() { delete[] array_; }
// swap functions should never throw
friend void swap(Array &left, Array &right) noexcept {
using std::swap;
swap(left.array_, right.array_);
swap(left.size_, right.size_);
}
T &operator[](int index) { return array_[index]; }
int size() const { return size_; }
private:
T *array_;
int size_;
};
template <typename T>
Array<T> make_array(int size) {
return Array(new T[size], size);
}
int main() {
auto my_array = make_array<int>(7);
auto my_move_constructed_array = std::move(my_array);
my_array = std::move(my_move_constructed_array); // move back
auto my_copy_constructed_array = my_array;
my_array = my_copy_constructed_array; // copy back
assert(my_array.size() == 7);
}
| 24.075472 | 78 | 0.666928 | gbellizio |
5d5372a47af2e80f89d2df147b085360aa875a83 | 29,032 | hpp | C++ | include/lely/coapp/slave.hpp | JoachimDuquesne/lely | cc6bad10ba57e380386622211e603006eeee0fff | [
"Apache-2.0"
] | null | null | null | include/lely/coapp/slave.hpp | JoachimDuquesne/lely | cc6bad10ba57e380386622211e603006eeee0fff | [
"Apache-2.0"
] | null | null | null | include/lely/coapp/slave.hpp | JoachimDuquesne/lely | cc6bad10ba57e380386622211e603006eeee0fff | [
"Apache-2.0"
] | null | null | null | /**@file
* This header file is part of the C++ CANopen application library; it contains
* the CANopen slave declarations.
*
* @copyright 2018-2020 Lely Industries N.V.
*
* @author J. S. Seldenthuis <jseldenthuis@lely.com>
*
* 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 LELY_COCPP_SLAVE_HPP_
#define LELY_COCPP_SLAVE_HPP_
#include <lely/coapp/node.hpp>
#include <memory>
#include <string>
#include <utility>
#include <cstddef>
namespace lely {
namespace canopen {
/// The base class for CANopen slaves.
class BasicSlave : public Node {
public:
/**
* Creates a new CANopen slave. After creation, the slave is in the NMT
* 'Initialisation' state and does not yet create any services or perform any
* communication. Call #Reset() to start the boot-up process.
*
* @param exec the executor used to process I/O and CANopen events. If
* <b>exec</b> is a null pointer, the CAN channel executor is
* used.
* @param timer the timer used for CANopen events. This timer MUST NOT be
* used for any other purpose.
* @param chan a CAN channel. This channel MUST NOT be used for any other
* purpose.
* @param dcf_txt the path of the text EDS or DCF containing the device
* description.
* @param dcf_bin the path of the (binary) concise DCF containing the values
* of (some of) the objets in the object dictionary. If
* <b>dcf_bin</b> is empty, no concise DCF is loaded.
* @param id the node-ID (in the range [1..127, 255]). If <b>id</b> is
* 255 (unconfigured), the node-ID is obtained from the DCF.
*/
explicit BasicSlave(ev_exec_t* exec, io::TimerBase& timer,
io::CanChannelBase& chan, const ::std::string& dcf_txt,
const ::std::string& dcf_bin = "", uint8_t id = 0xff);
/// Creates a new CANopen slave.
explicit BasicSlave(io::TimerBase& timer, io::CanChannelBase& chan,
const ::std::string& dcf_txt,
const ::std::string& dcf_bin = "", uint8_t id = 0xff)
: BasicSlave(nullptr, timer, chan, dcf_txt, dcf_bin, id) {}
virtual ~BasicSlave();
/**
* Registers the function to be invoked when a life guarding event occurs or
* is resolved. Only a single function can be registered at any one time. If
* <b>on_life_guarding</b> contains a callable function target, a copy of the
* target is invoked _after_ OnLifeGuarding(bool) completes.
*/
void OnLifeGuarding(::std::function<void(bool)> on_life_guarding);
protected:
class Object;
class ConstObject;
/**
* A mutator providing read/write access to a CANopen sub-object in a local
* object dictionary.
*/
class SubObject {
friend class Object;
public:
SubObject(const SubObject&) = default;
SubObject(SubObject&&) = default;
SubObject& operator=(const SubObject&) = default;
SubObject& operator=(SubObject&&) = default;
/**
* Sets the value of the sub-object.
*
* @param value the value to be written.
*
* @throws #lely::canopen::SdoError if the sub-object does not exist or the
* type does not match.
*
* @see Set()
*/
template <class T>
SubObject&
operator=(T&& value) {
Set(::std::forward<T>(value));
return *this;
}
/**
* Returns a copy of the value of the sub-object.
*
* @throws #lely::canopen::SdoError if the sub-object does not exist or the
* type does not match.
*
* @see Get()
*/
template <class T>
operator T() const {
return Get<T>();
}
/**
* Returns the type of the sub-object.
*
* @returns a reference to an `std::type_info` object representing the type,
* or `typeid(void)` if unknown.
*
* @throws #lely::canopen::SdoError if the sub-object does not exist.
*
* @see Device::Type(uint16_t idx, uint8_t subidx) const
*/
const ::std::type_info&
Type() const {
return slave_->Type(idx_, subidx_);
}
/**
* Returns the type of the sub-object.
*
* @param ec if the sub-object does not exist, the SDO abort code is stored
* in <b>ec</b>.
*
* @returns a reference to an `std::type_info` object representing the type,
* or `typeid(void)` if unknown.
*
* @see Device::Type(uint16_t idx, uint8_t subidx, ::std::error_code& ec) const
*/
const ::std::type_info&
Type(::std::error_code& ec) const noexcept {
return slave_->Type(idx_, subidx_, ec);
}
/**
* Reads the value of the sub-object.
*
* @returns a copy of the value of the sub-object.
*
* @throws #lely::canopen::SdoError if the sub-object does not exist or the
* type does not match.
*
* @see Device::Get(uint16_t idx, uint8_t subidx) const
* @see Device::TpdoGet(uint8_t id, uint16_t idx, uint8_t subidx) const
*/
template <class T>
T
Get() const {
return id_ ? slave_->TpdoGet<T>(id_, idx_, subidx_)
: slave_->Get<T>(idx_, subidx_);
}
/**
* Reads the value of the sub-object.
*
* @param ec if the sub-object does not exist or the type does not match,
* the SDO abort code is stored in <b>ec</b>.
*
* @returns a copy of the value of the sub-object, or an empty value on
* error.
*
* @see Device::Get(uint16_t idx, uint8_t subidx, ::std::error_code& ec) const
* @see Device::TpdoGet(uint8_t id, uint16_t idx, uint8_t subidx, ::std::error_code& ec) const
*/
template <class T>
T
Get(::std::error_code& ec) const noexcept {
return id_ ? slave_->TpdoGet<T>(id_, idx_, subidx_, ec)
: slave_->Get<T>(idx_, subidx_, ec);
}
/**
* Writes a value to the sub-object.
*
* @param value the value to be written.
*
* @throws #lely::canopen::SdoError if the sub-object does not exist or the
* type does not match.
*
* @see Device::Set(uint16_t idx, uint8_t subidx, T&& value)
* @see Device::TpdoSet(uint8_t id, uint16_t idx, uint8_t subidx, T&& value)
*/
template <class T>
void
Set(T&& value) {
if (id_)
slave_->TpdoSet(id_, idx_, subidx_, ::std::forward<T>(value));
else
slave_->Set(idx_, subidx_, ::std::forward<T>(value));
}
/**
* Writes a value to the sub-object.
*
* @param value the value to be written.
* @param ec if the sub-object does not exist or the type does not match,
* the SDO abort code is stored in <b>ec</b>.
*
* @see Device::Set(uint16_t idx, uint8_t subidx, T value, ::std::error_code& ec)
* @see Device::Set(uint16_t idx, uint8_t subidx, const T& value, ::std::error_code& ec)
* @see Device::Set(uint16_t idx, uint8_t subidx, const char* value, ::std::error_code& ec)
* @see Device::Set(uint16_t idx, uint8_t subidx, const char16_t* value, ::std::error_code& ec)
* @see Device::TpdoSet(uint8_t id, uint16_t idx, uint8_t subidx, T value, ::std::error_code& ec)
*/
template <class T>
void
Set(T&& value, ::std::error_code& ec) noexcept {
if (id_)
slave_->TpdoSet(id_, idx_, subidx_, ::std::forward<T>(value), ec);
else
slave_->Set(idx_, subidx_, ::std::forward<T>(value), ec);
}
/**
* Writes an OCTET_STRING or DOMAIN value to the sub-object.
*
* @param p a pointer to the bytes to be written.
* @param n the number of bytes to write.
*
* @throws #lely::canopen::SdoError if the sub-object does not exist or the
* type does not match.
*
* @see Device::Set(uint16_t idx, uint8_t subidx, const void* p, ::std::size_t n)
*/
void
Set(const void* p, ::std::size_t n) {
if (!id_) slave_->Set(idx_, subidx_, p, n);
}
/**
* Writes an OCTET_STRING or DOMAIN value to the sub-object.
*
* @param p a pointer to the bytes to be written.
* @param n the number of bytes to write.
* @param ec if the sub-object does not exist or the type does not match,
* the SDO abort code is stored in <b>ac</b>.
*
* @see Device::Set(uint16_t idx, uint8_t subidx, const void* p, ::std::size_t n, ::std::error_code& ec)
*/
void
Set(const void* p, ::std::size_t n, ::std::error_code& ec) noexcept {
if (!id_) slave_->Set(idx_, subidx_, p, n, ec);
}
/**
* Checks if the sub-object can be mapped into a PDO and, if so, triggers
* the transmission of every acyclic or event-driven Transmit-PDO into which
* the sub-object is mapped.
*
* @throws #lely::canopen::SdoError on error.
*
* @see Device::SetEvent(uint16_t idx, uint8_t subidx)
* @see Device::TpdoSetEvent(uint8_t id, uint16_t idx, uint8_t subidx)
*/
void
SetEvent() {
if (id_)
slave_->TpdoSetEvent(id_, idx_, subidx_);
else
slave_->SetEvent(idx_, subidx_);
}
/**
* Checks if the sub-object can be mapped into a PDO and, if so, triggers
* the transmission of every acyclic or event-driven Transmit-PDO into which
* the sub-object is mapped.
*
* @param ec on error, the SDO abort code is stored in <b>ec</b>.
*
* @see Device::SetEvent(uint16_t idx, uint8_t subidx, ::std::error_code& ec)
* @see Device::TpdoSetEvent(uint8_t id, uint16_t idx, uint8_t subidx, ::std::error_code& ec)
*/
void
SetEvent(::std::error_code& ec) noexcept {
if (id_)
slave_->TpdoSetEvent(id_, idx_, subidx_, ec);
else
slave_->SetEvent(idx_, subidx_, ec);
}
private:
SubObject(BasicSlave* slave, uint8_t id, uint16_t idx,
uint8_t subidx) noexcept
: slave_(slave), idx_(idx), subidx_(subidx), id_(id) {}
BasicSlave* slave_;
uint16_t idx_;
uint8_t subidx_;
uint8_t id_;
};
/**
* An accessor providing read-only access to a CANopen sub-object in a local
* object dictionary.
*/
class ConstSubObject {
friend class Object;
friend class ConstObject;
public:
/**
* Returns a copy of the value of the sub-object.
*
* @throws #lely::canopen::SdoError if the sub-object does not exist or the
* type does not match.
*
* @see Get()
*/
template <class T>
operator T() const {
return Get<T>();
}
/**
* Returns the type of the sub-object.
*
* @returns a reference to an `std::type_info` object representing the type,
* or `typeid(void)` if unknown.
*
* @throws #lely::canopen::SdoError if the sub-object does not exist.
*
* @see Device::Type(uint16_t idx, uint8_t subidx) const
*/
const ::std::type_info&
Type() const {
return slave_->Type(idx_, subidx_);
}
/**
* Returns the type of the sub-object.
*
* @param ec if the sub-object does not exist, the SDO abort code is stored
* in <b>ec</b>.
*
* @returns a reference to an `std::type_info` object representing the type,
* or `typeid(void)` if unknown.
*
* @see Device::Type(uint16_t idx, uint8_t subidx, ::std::error_code& ec)
* const
*/
const ::std::type_info&
Type(::std::error_code& ec) const {
return slave_->Type(idx_, subidx_, ec);
}
/**
* Reads the value of the sub-object.
*
* @returns a copy of the value of the sub-object.
*
* @throws #lely::canopen::SdoError if the sub-object does not exist or the
* type does not match.
*
* @see Device::Get(uint16_t idx, uint8_t subidx) const
* @see Device::RpdoGet(uint8_t id, uint16_t idx, uint8_t subidx) const
* @see Device::TpdoGet(uint8_t id, uint16_t idx, uint8_t subidx) const
*/
template <class T>
T
Get() const {
return id_ ? (is_rpdo_ ? slave_->RpdoGet<T>(id_, idx_, subidx_)
: slave_->TpdoGet<T>(id_, idx_, subidx_))
: slave_->Get<T>(idx_, subidx_);
}
/**
* Reads the value of the sub-object.
*
* @param ec if the sub-object does not exist or the type does not match,
* the SDO abort code is stored in <b>ec</b>.
*
* @returns a copy of the value of the sub-object, or an empty value on
* error.
*
* @see Device::Get(uint16_t idx, uint8_t subidx, ::std::error_code& ec) const
* @see Device::RpdoGet(uint8_t id, uint16_t idx, uint8_t subidx, ::std::error_code& ec) const
* @see Device::TpdoGet(uint8_t id, uint16_t idx, uint8_t subidx, ::std::error_code& ec) const
*/
template <class T>
T
Get(::std::error_code& ec) const noexcept {
return id_ ? (is_rpdo_ ? slave_->RpdoGet<T>(id_, idx_, subidx_, ec)
: slave_->TpdoGet<T>(id_, idx_, subidx_, ec))
: slave_->Get<T>(idx_, subidx_, ec);
}
private:
ConstSubObject(const BasicSlave* slave, uint8_t id, uint16_t idx,
uint8_t subidx, bool is_rpdo) noexcept
: slave_(slave),
idx_(idx),
subidx_(subidx),
id_(id),
is_rpdo_(is_rpdo) {}
const BasicSlave* slave_;
uint16_t idx_;
uint8_t subidx_;
uint8_t id_ : 7;
uint8_t is_rpdo_ : 1;
};
class RpdoMapped;
class TpdoMapped;
/**
* A mutator providing read/write access to a CANopen object in a local object
* dictionary.
*/
class Object {
class Mapped;
friend class BasicSlave;
public:
/**
* Returns a mutator object that provides read/write access to the specified
* CANopen sub-object in the local object dictionary (or the TPDO-mapped
* sub-object in the remote object dictionary). Note that this function
* succeeds even if the sub-object does not exist.
*
* @param subidx the object sub-index.
*
* @returns a mutator object for a CANopen sub-object in the local object
* dictionary.
*/
SubObject operator[](uint8_t subidx) noexcept {
return SubObject(slave_, id_, idx_, subidx);
}
/**
* Returns an accessor object that provides read-only access to the
* specified CANopen sub-object in the local object dictionary (or the
* TPDO-mapped sub-object in the remote object dictionary). Note that this
* function succeeds even if the object does not exist.
*
* @param subidx the object sub-index.
*
* @returns an accessor object for a CANopen sub-object in the local object
* dictionary.
*/
ConstSubObject operator[](uint8_t subidx) const noexcept {
return ConstSubObject(slave_, id_, idx_, subidx, false);
}
private:
Object(BasicSlave* slave, uint16_t idx) noexcept : Object(slave, 0, idx) {}
Object(BasicSlave* slave, uint8_t id, uint16_t idx) noexcept
: slave_(slave), idx_(idx), id_(id) {}
BasicSlave* slave_;
uint16_t idx_;
uint8_t id_;
};
/**
* An accessor providing read-only access to a CANopen object in a local
* object dictionary.
*/
class ConstObject {
class RpdoMapped;
class TpdoMapped;
friend class BasicSlave;
public:
/**
* Returns an accessor object that provides read-only access to the
* specified CANopen sub-object in the local object dictionary (or the
* PDO-mapped sub-object in the remote object dictionary). Note that this
* function succeeds even if the object does not exist.
*
* @param subidx the object sub-index.
*
* @returns an accessor object for a CANopen sub-object in the local object
* dictionary.
*/
ConstSubObject operator[](uint8_t subidx) const noexcept {
return ConstSubObject(slave_, id_, idx_, subidx, is_rpdo_);
}
private:
ConstObject(const BasicSlave* slave, uint16_t idx) noexcept
: ConstObject(slave, 0, idx, false) {}
ConstObject(const BasicSlave* slave, uint8_t id, uint16_t idx,
bool is_rpdo) noexcept
: slave_(slave), idx_(idx), id_(id), is_rpdo_(is_rpdo) {}
const BasicSlave* slave_;
uint16_t idx_;
uint8_t id_ : 7;
uint8_t is_rpdo_ : 1;
};
/**
* An accessor providing read-only access to RPDO-mapped objects in a remote
* object dictionary.
*/
class RpdoMapped {
friend class BasicSlave;
public:
/**
* Returns an accessor object that provides read-only access to the
* specified RPDO-mapped object in the remote object dictionary. Note that
* this function succeeds even if the object does not exist.
*
* @param idx the object index.
*
* @returns an accessor object for a CANopen object in the remote object
* dictionary.
*/
ConstObject operator[](uint16_t idx) const noexcept {
return ConstObject(slave_, id_, idx, true);
}
private:
RpdoMapped(const BasicSlave* slave, uint8_t id) noexcept
: slave_(slave), id_(id) {}
const BasicSlave* slave_;
uint8_t id_;
};
/**
* A mutator providing read/write access to TPDO-mapped objects in a remote
* object dictionary.
*/
class TpdoMapped {
friend class BasicSlave;
public:
/**
* Returns a mutator object that provides read/write access to the specified
* TPDO-mapped object in the remote object dictionary. Note that this
* function succeeds even if the object does not exist.
*
* @param idx the object index.
*
* @returns a mutator object for a CANopen object in the remote object
* dictionary.
*/
Object operator[](uint16_t idx) noexcept {
return Object(slave_, id_, idx);
}
/**
* Returns an accessor object that provides read-only access to the
* specified TPDO-mapped object in the remote object dictionary. Note that
* this function succeeds even if the object does not exist.
*
* @param idx the object index.
*
* @returns an accessor object for a CANopen object in the remote object
* dictionary.
*/
ConstObject operator[](uint16_t idx) const noexcept {
return ConstObject(slave_, id_, idx, false);
}
private:
TpdoMapped(BasicSlave* slave, uint8_t id) noexcept
: slave_(slave), id_(id) {}
BasicSlave* slave_;
uint8_t id_;
};
/**
* The signature of the callback function invoked on read (SDO upload) access
* to the local object dictionary. Note that the callback function SHOULD NOT
* throw exceptions. Since it is invoked from C, any exception that is thrown
* cannot be caught and will result in a call to `std::terminate()`. The
* #lely::util::BasicLockable mutex implemented by this class is held for the
* duration of the call.
*
* @param idx the object index.
* @param subidx the object sub-index.
* @param value the current value in the object dictionary. This value can be
* modified before it is returned to the client.
*
* @returns 0 on success, or an SDO abort code on error.
*/
template <class T>
using OnReadSignature = ::std::error_code(uint16_t idx, uint8_t subdx,
T& value);
/**
* The signature of the callback function invoked on write (SDO download)
* access to the local object dictionary. Note that the callback function
* SHOULD NOT throw exceptions. Since it is invoked from C, any exception that
* is thrown cannot be caught and will result in a call to `std::terminate()`.
* The #lely::util::BasicLockable mutex implemented by this class is held for
* the duration of the call.
*
* @param idx the object index.
* @param subidx the object sub-index.
* @param new_val the value to be written to the object dictionary. This value
* can be modified before it is committed.
* @param old_val the current value in the object dictionary (only for
* CANopen basic data types).
*
* @returns 0 on success, or an SDO abort code on error.
*/
template <class T>
using OnWriteSignature = typename ::std::conditional<
detail::is_canopen_basic<T>::value,
::std::error_code(uint16_t idx, uint8_t subidx, T& new_val, T old_val),
::std::error_code(uint16_t idx, uint8_t subidx, T& new_val)>::type;
/**
* Returns a mutator object that provides read/write access to the specified
* CANopen object in the local object dictionary. Note that this function
* succeeds even if the object does not exist.
*
* @param idx the object index.
*
* @returns a mutator object for a CANopen object in the local object
* dictionary.
*/
Object operator[](::std::ptrdiff_t idx) noexcept { return Object(this, idx); }
/**
* Returns an accessor object that provides read-only access to the specified
* CANopen object in the local object dictionary. Note that this function
* succeeds even if the object does not exist.
*
* @param idx the object index.
*
* @returns an accessor object for a CANopen object in the local object
* dictionary.
*/
ConstObject operator[](::std::ptrdiff_t idx) const noexcept {
return ConstObject(this, idx);
}
/**
* Returns an accessor object that provides read-only access to RPDO-mapped
* objects in the remote object dictionary of the specified node. Note that
* this function succeeds even if no RPDO-mapped objects exist.
*
* @param id the node-ID.
*
* @returns an accessor object for RPDO-mapped objects in a remote object
* dictionary.
*/
RpdoMapped
RpdoMapped(uint8_t id) const noexcept {
return {this, id};
}
/**
* Returns a mutator object that provides read/write access to TPDO-mapped
* objects in the remote object dictionary of the specified node. Note that
* this function succeeds even if no TPDO-mapped objects exist.
*
* @param id the node-ID.
*
* @returns a mutator object for TPDO-mapped objects in a remote object
* dictionary.
*/
TpdoMapped
TpdoMapped(uint8_t id) noexcept {
return {this, id};
}
/**
* Registers a callback function to be invoked on read (SDO upload) access to
* the specified CANopen sub-object in the local object dictionary. Note that
* the callback function is not invoked if the access checks fail.
*
* @param idx the object index.
* @param subidx the object sub-index.
* @param ind the indication function to be called on write access to the
* specified sub-object.
*
* @throws #lely::canopen::SdoError on error.
*/
template <class T>
typename ::std::enable_if<detail::is_canopen_type<T>::value>::type OnRead(
uint16_t idx, uint8_t subidx, ::std::function<OnReadSignature<T>> ind);
/**
* Registers a callback function to be invoked on read (SDO upload) access to
* the specified CANopen sub-object in the local object dictionary. Note that
* the callback function is not invoked if the access checks fail.
*
* @param idx the object index.
* @param subidx the object sub-index.
* @param ind the indication function to be called on write access to the
* specified sub-object.
* @param ec on error, the SDO abort code is stored in <b>ec</b>.
*/
template <class T>
typename ::std::enable_if<detail::is_canopen_type<T>::value>::type OnRead(
uint16_t idx, uint8_t subidx, ::std::function<OnReadSignature<T>> ind,
::std::error_code& ec);
/**
* Registers a callback function to be invoked on read (SDO upload) access to
* each member of the specified CANopen record or array object in the local
* object dictionary. Note that the callback function is not invoked if the
* access checks fail.
*
* @param idx the object index.
* @param ind the indication function to be called on read access to each
* member of the specified object.
*
* @throws #lely::canopen::SdoError on error.
*/
template <class T>
typename ::std::enable_if<detail::is_canopen_type<T>::value>::type OnRead(
uint16_t idx, ::std::function<OnReadSignature<T>> ind);
/**
* Registers a callback function to be invoked on read (SDO upload) access to
* each member of the specified CANopen record or array object in the local
* object dictionary. Note that the callback function is not invoked if the
* access checks fail.
*
* @param idx the object index.
* @param ind the indication function to be called on read access to each
* member of the specified object.
* @param ec on error, the SDO abort code is stored in <b>ec</b>.
*/
template <class T>
typename ::std::enable_if<detail::is_canopen_type<T>::value>::type OnRead(
uint16_t idx, ::std::function<OnReadSignature<T>> ind,
::std::error_code& ec);
/**
* Registers a callback function to be invoked on write (SDO download) access
* to the specified CANopen sub-object in the local object dictionary. Note
* that the callback function is not invoked if the access or range checks
* fail.
*
* @param idx the object index.
* @param subidx the object sub-index.
* @param ind the indication function to be called on read access to the
* specified sub-object.
*
* @throws #lely::canopen::SdoError on error.
*/
template <class T>
typename ::std::enable_if<detail::is_canopen_type<T>::value>::type OnWrite(
uint16_t idx, uint8_t subidx, ::std::function<OnWriteSignature<T>> ind);
/**
* Registers a callback function to be invoked on write (SDO download) access
* to the specified CANopen sub-object in the local object dictionary. Note
* that the callback function is not invoked if the access or range checks
* fail.
*
* @param idx the object index.
* @param subidx the object sub-index.
* @param ind the indication function to be called on read access to the
* specified sub-object.
* @param ec on error, the SDO abort code is stored in <b>ec</b>.
*/
template <class T>
typename ::std::enable_if<detail::is_canopen_type<T>::value>::type OnWrite(
uint16_t idx, uint8_t subidx, ::std::function<OnWriteSignature<T>> ind,
::std::error_code& ec);
/**
* Registers a callback function to be invoked on write (SDO download) access
* to each member of the specified CANopen record or array object in the local
* object dictionary. Note that the callback function is not invoked if the
* access or range checks fail.
*
* @param idx the object index.
* @param ind the indication function to be called on write access to each
* member of the specified object.
*
* @throws #lely::canopen::SdoError on error.
*/
template <class T>
typename ::std::enable_if<detail::is_canopen_type<T>::value>::type OnWrite(
uint16_t idx, ::std::function<OnWriteSignature<T>> ind);
/**
* Registers a callback function to be invoked on write (SDO download) access
* to each member of the specified CANopen record or array object in the local
* object dictionary. Note that the callback function is not invoked if the
* access or range checks fail.
*
* @param idx the object index.
* @param ind the indication function to be called on write access to each
* member of the specified object.
* @param ec on error, the SDO abort code is stored in <b>ec</b>.
*/
template <class T>
typename ::std::enable_if<detail::is_canopen_type<T>::value>::type OnWrite(
uint16_t idx, ::std::function<OnWriteSignature<T>> ind,
::std::error_code& ec);
#ifndef DOXYGEN_SHOULD_SKIP_THIS
private:
#endif
/**
* The function invoked when a life guarding event occurs or is resolved. Note
* that depending on the value of object 1029:01 (Error behavior object), the
* occurrence of a life guarding event MAY trigger an NMT state transition. If
* so, this function is called _after_ the state change completes.
*
* @param occurred `true` if the life guarding event occurred, `false` if it
* was resolved.
*/
virtual void
OnLifeGuarding(bool occurred) noexcept {
(void)occurred;
};
#ifdef DOXYGEN_SHOULD_SKIP_THIS
private:
#endif
struct Impl_;
::std::unique_ptr<Impl_> impl_;
};
} // namespace canopen
} // namespace lely
#endif // LELY_COCPP_SLAVE_HPP_
| 34.155294 | 108 | 0.639226 | JoachimDuquesne |
5d565a736e77f048826dac9cc7d8958172a44042 | 2,287 | cpp | C++ | engine/source/mem/source/src/memory_allocator.cpp | mateusgondim/Demos | 6aa5da3a6c0e960d10811c9e71e9a0a746e8d6ab | [
"MIT"
] | 5 | 2019-02-12T07:23:55.000Z | 2020-06-22T15:03:36.000Z | engine/source/mem/source/src/memory_allocator.cpp | mateusgondim/Demos | 6aa5da3a6c0e960d10811c9e71e9a0a746e8d6ab | [
"MIT"
] | null | null | null | engine/source/mem/source/src/memory_allocator.cpp | mateusgondim/Demos | 6aa5da3a6c0e960d10811c9e71e9a0a746e8d6ab | [
"MIT"
] | 2 | 2019-06-17T05:04:21.000Z | 2020-04-22T09:05:57.000Z | #include "memory_allocator.hpp"
#include <iostream>
#include <cstddef>
#include <cstdlib>
#include <cassert>
#include <cstdint>
namespace mem {
/*allocate_unaligned: Attempts to allocate a unaligned block of 'size_bytes' bytes,
*returns nullptr in case of failure
*/
void *allocate_unaligned(const std::size_t size_bytes)
{
void * pmemory_block = malloc(size_bytes);
return pmemory_block;
}
void free_unaligned(void *pmemory)
{
free(pmemory);
}
/* allocate_aligned: Attempts to allocate a block of 'size_bytes' bytes,
* with 'alignment' bytes aligment requirent. IMPORTANT: 'alignment' must be a power of 2.
* returns nullptr in case of failure
*/
void * allocate_aligned(const std::size_t size_bytes, const std::size_t alignment)
{
assert(alignment >= 1);
assert(alignment <= 128);
assert((alignment & (alignment - 1)) == 0); // pwr of 2
//Increase the memory to be allocated to be able to align it
std::size_t expanded_size_bytes = size_bytes + alignment;
//allocate the expanded unaligned block an convert it to uintptr_t
std::uintptr_t raw_address = reinterpret_cast<std::uintptr_t>(allocate_unaligned(expanded_size_bytes));
//Calculate the adjustment by masking off the lower bits
//of the address, to determine how 'misaligned it is
std::size_t mask = alignment - 1;
std::uintptr_t misalignment = raw_address & mask;
std::ptrdiff_t adjustment = alignment - misalignment;
//Calculate the ajusted address
std::uintptr_t aligned_address = raw_address + adjustment;
// store the adjustment in the byte immediately
// preceding the ajusted address
assert(adjustment < 256);
std::uint8_t *paligned_mem = reinterpret_cast<std::uint8_t *>(aligned_address);
paligned_mem[-1] = static_cast<std::uint8_t>(adjustment);
return static_cast<void*>(paligned_mem);
}
void free_aligned(void * pmemory)
{
const std::uint8_t *paligned_memory = reinterpret_cast<const std::uint8_t*>(pmemory);
std::uintptr_t aligned_address = reinterpret_cast<std::uintptr_t>(pmemory);
std::ptrdiff_t ajustment = static_cast<std::ptrdiff_t>(paligned_memory[-1]);
std::uintptr_t raw_address = aligned_address - ajustment;
void * praw_memory = reinterpret_cast<void*>(raw_address);
free_unaligned(praw_memory);
}
} | 31.763889 | 105 | 0.739397 | mateusgondim |
5d580ed68855a5e07b570be2cfd5a0be07093ea5 | 10,199 | cpp | C++ | C & C++/Humanoid/Hooman.cpp | ytugba/My-Otiose-Projects | b0703f5e0b18cee186e44d3e40b6b5c3b162d739 | [
"MIT"
] | 1 | 2021-12-23T19:05:25.000Z | 2021-12-23T19:05:25.000Z | C & C++/Humanoid/Hooman.cpp | ytugba/My-Otiose-Projects | b0703f5e0b18cee186e44d3e40b6b5c3b162d739 | [
"MIT"
] | null | null | null | C & C++/Humanoid/Hooman.cpp | ytugba/My-Otiose-Projects | b0703f5e0b18cee186e44d3e40b6b5c3b162d739 | [
"MIT"
] | null | null | null | /*
GUIDE
KOLLAR | ELLER
Sol Sag | Sol Sag
Q (yukari) E (yukari) | W (yukari) R (yukari)
A D | S F
BACAKLAR | AYAKLAR
Sol Sag | Sol Sag
Z (yukari) C (yukari) | G (yukari) B (yukari)
X K | H N
YATAY DONUS | DIKEY DONUS | CAPRAZ DONUS
Sol Sag | Yukari Asagi | Saat -Saat
4 6 | 8 2 | 1 9
POZISYON SIFIRLAMA | KAMERA SIFIRLAMA
i | m
ANIMASYON HIZI
ARTIS AZALIS DEFAULT HIZ
YUKARI OK ASAGI OK i
POZISYON KAYIT/YUKLEME
1. Pozisyon 2. Pozisyon Yukleme
J K L
CIKIS
P
*/
#include <GL/glut.h>
#include <iostream>
#include <fstream>
using namespace std;
//GLOBAL VARIABLES
enum
{
GOVDE = 0,
SOLUK, SOLAK,
SAGUK, SAGAK,
SOLUB, SOLAB,
SAGUB, SAGAB,
BOYUT
};
float KAFA_YUKSEKLIK = 7.0, KAFA_CAP = 3.0;
float GOVDE_YUKSEKLIK = 10.0, GOVDE_CAP = 2.0;
float UST_KOL_YUKSEKLIK = 6.0, ALT_KOL_YUKSEKLIK = 4.0;
float UST_KOL_CAP = 1.0, ALT_KOL_CAP = 1.0;
float UST_BACAK_YUKSEKLIK = 9.0, ALT_BACAK_YUKSEKLIK = 2.0;
float UST_BACAK_CAP = 1.0, ALT_BACAK_CAP = 1.0;
float xRotate = 0, yRotate = 0, zRotate=0;
float a[BOYUT] = { 0 };
float b[BOYUT] = { 0 };
float aci[BOYUT] = { 0 };
bool interpolate_bool = false;
bool go_up[BOYUT] = { true, true, true, true, true, true, true, true, true};
int speed = 50;
GLUquadricObj *g, *k; /* govde, kafa */
GLUquadricObj *soluk, *solak, *saguk, *sagak; /* kollar */
GLUquadricObj *solub, *solab, *sagub, *sagab; /* bacaklar */
//COORDINATES OF HUMANOID FUNCTION DEFINITIONS
void head();
void govde();
void sol_ust_kol();
void sol_alt_kol();
void sag_ust_kol();
void sag_alt_kol();
void sol_ust_bacak();
void sol_alt_bacak();
void sag_ust_bacak();
void sag_alt_bacak();
//FUNCTION DEFINITIONS
void writeFile(int a);
void interpolate(int d);
void DrawRobot(float x, float y, float z, float soluk, float solak, float saguk, float sagak, float solub, float solab, float sagub, float sagab);
void InitQuadrics();
void Display();
void Keyboard(unsigned char key, int x, int y);
void view();
void speed_of_animation(int key, int x, int y);
//FUNCTIONS
void view()
{
glClearColor(0.19f, 0.49f, 0.32f, 1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0f, 1.0f, 10.0f, -15.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0, 0, 40, 0, 0, 0, 0, 1, 0);
glEnable(GL_DEPTH_TEST);
InitQuadrics();
}
void writeFile(int a)
{
ofstream myfile;
if (a == 1)
myfile.open("1in.txt");
if (a == 2)
myfile.open("2in.txt");
for (int i = 0; i<BOYUT; i++)
myfile << aci[i] << " ";
myfile.close();
}
void InitQuadrics()
{
g = gluNewQuadric();
gluQuadricDrawStyle(g, GLU_FILL);
soluk = gluNewQuadric();
gluQuadricDrawStyle(soluk, GLU_FILL);
k = gluNewQuadric();
gluQuadricDrawStyle(k, GLU_FILL);
solak = gluNewQuadric();
gluQuadricDrawStyle(solak, GLU_FILL);
saguk = gluNewQuadric();
gluQuadricDrawStyle(saguk, GLU_FILL);
solub = gluNewQuadric();
gluQuadricDrawStyle(solub, GLU_FILL);
solab = gluNewQuadric();
gluQuadricDrawStyle(solab, GLU_FILL);
sagub = gluNewQuadric();
gluQuadricDrawStyle(sagub, GLU_FILL);
sagab = gluNewQuadric();
gluQuadricDrawStyle(sagab, GLU_FILL);
}
void interpolate(int d)
{
if (d)
{
for (int i = 0; i<BOYUT; i++)
{
if ((b[i] - a[i]) < 0)
{
if (go_up[i])
{
if (aci[i] >= b[i] && aci[i] <= a[i])
aci[i] += (b[i] - a[i]) / speed;
if (aci[i] <= b[i])
{
go_up[i] = !go_up[i];
aci[i] = b[i];
}
}
else
{
if (aci[i] >= b[i] && aci[i] <= a[i])
aci[i] -= (b[i] - a[i]) / speed;
if (aci[i] >= a[i])
{
go_up[i] = !go_up[i];
aci[i] = a[i];
}
}
}
else
{
if (go_up[i])
{
if (aci[i] <= b[i] && aci[i] >= a[i])
aci[i] += (b[i] - a[i]) / speed;
if (aci[i] >= b[i])
{
go_up[i] = !go_up[i];
aci[i] = b[i];
}
}
else
{
if (aci[i] <= b[i] && aci[i] >= a[i])
aci[i] -= (b[i] - a[i]) / speed;
if (aci[i] <= a[i])
{
go_up[i] = !go_up[i];
aci[i] = a[i];
}
}
}
}
}
glutPostRedisplay();
glutTimerFunc(20, interpolate, interpolate_bool);
}
void DrawRobot(float x, float y, float z, float soluk, float solak, float saguk, float sagak, float solub, float solab, float sagub, float sagab)
{
//GOVDE
govde();
glPushMatrix(); //KAFA
glTranslatef(0, KAFA_YUKSEKLIK / 2, 0);
head();
glPopMatrix();
glPushMatrix(); //SOL KOL
glTranslatef(GOVDE_CAP, 0, 0);
glRotatef(soluk, 0, 0, 1);
sol_ust_kol();
glTranslatef(UST_KOL_YUKSEKLIK, 0, 0);
glRotatef(solak, 0, 0, 1);
sol_alt_kol();
glPopMatrix();
glPushMatrix(); //SAG KOL
glTranslatef(-GOVDE_CAP, 0, 0);
glRotatef(saguk, 0, 0, 1);
sag_ust_kol();
glTranslatef(-UST_KOL_YUKSEKLIK, 0, 0);
glRotatef(sagak, 0, 0, 1);
sag_alt_kol();
glPopMatrix();
glPushMatrix(); //SOL BACAK
glTranslatef(GOVDE_CAP, -GOVDE_YUKSEKLIK, 0);
glRotatef(solub, 1, 0, 0);
sol_ust_bacak();
glTranslatef(0, -UST_BACAK_YUKSEKLIK, 0);
glRotatef(solab, 1, 0, 0);
sol_alt_bacak();
glPopMatrix();
glPushMatrix(); //SAG BACAK
glTranslatef(-GOVDE_CAP, -GOVDE_YUKSEKLIK, 0);
glRotatef(sagub, 1, 0, 0);
sag_ust_bacak();
glTranslatef(0, -UST_BACAK_YUKSEKLIK, 0);
glRotatef(sagab, 1, 0, 0);
sag_alt_bacak();
glPopMatrix();
}
void Display()
{
glDrawBuffer(GL_FRONT_AND_BACK);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0, 0, 40, 0, 0, 0, 0, 1, 0);
glRotatef(xRotate, 0, 1, 0);
glRotatef(yRotate, 1, 0, 0);
glRotatef(zRotate, 0, 0, 1);
DrawRobot(0, 0, 0, aci[SOLUK], aci[SOLAK], aci[SAGUK], aci[SAGAK], aci[SOLUB], aci[SOLAB], aci[SAGUB], aci[SAGAB]);
glFlush();
glutSwapBuffers();
}
void Keyboard(unsigned char key, int x, int y)
{
switch (key)
{
case 'a':
aci[SAGUK] += 5; break;
case 'q':
aci[SAGUK] -= 5; break;
case 'e':
aci[SOLUK] += 5; break;
case 'd':
aci[SOLUK] -= 5; break;
case 'z':
aci[SAGUB] += 5; break;
case 'x':
aci[SAGUB] -= 5; break;
case 'c':
aci[SOLUB] += 5; break;
case 'v':
aci[SOLUB] -= 5; break;
case 's':
aci[SAGAK] += 5; break;
case 'w':
aci[SAGAK] -= 5; break;
case 'r':
aci[SOLAK] += 5; break;
case 'f':
aci[SOLAK] -= 5; break;
case 'g':
aci[SAGAB] += 5; break;
case 'h':
aci[SAGAB] -= 5; break;
case 'b':
aci[SOLAB] += 5; break;
case 'n':
aci[SOLAB] -= 5; break;
case '4':
xRotate -= 5.0; break;
case '6':
xRotate += 5.0; break;
case '8':
yRotate -= 5.0; break;
case '2':
yRotate += 5.0; break;
case '1':
zRotate -= 5; break;
case '9':
zRotate += 5; break;
case 'j':
writeFile(1); break;
case 'k':
writeFile(2); break;
case 'l':
{
ifstream myfile1;
myfile1.open("1in.txt");
ifstream myfile2;
myfile2.open("2in.txt");
for (int i = 0; i<BOYUT; i++)
{
myfile1 >> a[i];
myfile2 >> b[i];
}
myfile1.close();
myfile2.close();
interpolate_bool = !interpolate_bool;
break;
}
case 'i':
for (int i = 0; i<BOYUT; i++)
aci[i] = 0;
speed = 50;
break;
case 'm':
yRotate = 0;
xRotate = 0;
zRotate = 0;
break;
case 'p':
exit(0);
}
glutPostRedisplay();
}
void speed_of_animation(int key, int x, int y)
{
if (speed >= 0 && speed <= 50)
{
if (key == GLUT_KEY_UP)
speed--;
if (key == GLUT_KEY_DOWN)
speed++;
}
}
//MAIN FUNCTION
int main (int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(600, 600);
glutInitWindowPosition(200,50);
glutCreateWindow("16290085 & 16290616");
view();
glutDisplayFunc(Display);
glutKeyboardFunc(Keyboard);
glutSpecialFunc(speed_of_animation);
glutTimerFunc(20, interpolate, interpolate_bool);
glutMainLoop();
}
//COORDINATES OF HUMANOID
void head()
{
glPushMatrix();
glColor3f(1.0f, 0.93f, 0.57f);
glScalef(KAFA_CAP, KAFA_YUKSEKLIK / 2, KAFA_CAP);
gluSphere(k, 1.0, 100, 100);
glPopMatrix();
}
void govde()
{
glPushMatrix();
glColor3f(0.6f, 0.11f, 0.09f);
glRotatef(90.0, 1.0, 0.0, 0.0);
gluCylinder(g, GOVDE_CAP, GOVDE_CAP, GOVDE_YUKSEKLIK, 1000, 1000);
glPopMatrix();
}
void sol_ust_kol()
{
glPushMatrix();
glColor3f(0.6f, 0.11f, 0.09f);
glRotatef(90, 0, 1, 0);
gluCylinder(soluk, UST_KOL_CAP, UST_KOL_CAP, UST_KOL_YUKSEKLIK, 100, 100);
glPopMatrix();
}
void sol_alt_kol()
{
glPushMatrix();
glColor3f(1.0f, 0.93f, 0.57f);
glRotatef(90, 0, 1, 0);
gluCylinder(solak, ALT_KOL_CAP, ALT_KOL_CAP, ALT_KOL_YUKSEKLIK, 100, 100);
glPopMatrix();
}
void sag_ust_kol()
{
glPushMatrix();
glColor3f(0.6f, 0.11f, 0.09f);
glRotatef(-90, 0, 1, 0);
gluCylinder(saguk, UST_KOL_CAP, UST_KOL_CAP, UST_KOL_YUKSEKLIK, 100, 100);
glPopMatrix();
}
void sag_alt_kol()
{
glPushMatrix();
glColor3f(1.0f, 0.93f, 0.57f);
glRotatef(-90, 0, 1, 0);
gluCylinder(solak, ALT_KOL_CAP, ALT_KOL_CAP, ALT_KOL_YUKSEKLIK, 100, 100);
glPopMatrix();
}
void sol_ust_bacak()
{
glPushMatrix();
glColor3f(0.0f, 0.0f, 0.0f);
glRotatef(90, 1, 0, 0);
gluCylinder(solub, UST_BACAK_CAP, UST_BACAK_CAP, UST_BACAK_YUKSEKLIK, 100, 100);
glPopMatrix();
}
void sol_alt_bacak()
{
glPushMatrix();
glColor3f(1.0f, 0.93f, 0.57f);
glRotatef(90, 1, 0, 0);
gluCylinder(solab, ALT_BACAK_CAP, ALT_BACAK_CAP, ALT_BACAK_YUKSEKLIK, 100, 100);
glPopMatrix();
}
void sag_ust_bacak()
{
glPushMatrix();
glColor3f(0.0f, 0.0f, 0.0f);
glRotatef(90, 1, 0, 0);
gluCylinder(sagub, UST_BACAK_CAP, UST_BACAK_CAP, UST_BACAK_YUKSEKLIK, 100, 100);
glPopMatrix();
}
void sag_alt_bacak()
{
glPushMatrix();
glColor3f(1.0f, 0.93f, 0.57f);
glRotatef(90, 1, 0, 0);
gluCylinder(sagab, ALT_BACAK_CAP, ALT_BACAK_CAP, ALT_BACAK_YUKSEKLIK, 100, 100);
glPopMatrix();
}
| 20.645749 | 147 | 0.596137 | ytugba |
5d5c71c469e3632950c88ad887782d66743ca8ab | 3,106 | cpp | C++ | MSCL/source/mscl/MicroStrain/MIP/Packets/MipFieldParser.cpp | HTLife/MSCL | 9d84ed27a176ff20e058b9188a97d6ff81de7604 | [
"BSL-1.0",
"OpenSSL",
"MIT"
] | null | null | null | MSCL/source/mscl/MicroStrain/MIP/Packets/MipFieldParser.cpp | HTLife/MSCL | 9d84ed27a176ff20e058b9188a97d6ff81de7604 | [
"BSL-1.0",
"OpenSSL",
"MIT"
] | null | null | null | MSCL/source/mscl/MicroStrain/MIP/Packets/MipFieldParser.cpp | HTLife/MSCL | 9d84ed27a176ff20e058b9188a97d6ff81de7604 | [
"BSL-1.0",
"OpenSSL",
"MIT"
] | null | null | null | /*******************************************************************************
Copyright(c) 2015-2018 LORD Corporation. All rights reserved.
MIT Licensed. See the included LICENSE.txt for a copy of the full MIT License.
*******************************************************************************/
#include "stdafx.h"
#include "MipFieldParser.h"
#include <vector>
#include "MipDataPacket.h"
namespace mscl
{
//forces the linker to include the Parser files
//by using a global variable defined in their files
bool run_once_forceLibraryToIncludeCompilationUnit()
{
//add the following 2 lines for each parser's file
extern bool _forceLibraryToIncludeCompilationUnit_AHRS;
_forceLibraryToIncludeCompilationUnit_AHRS = true;
extern bool _forceLibraryToIncludeCompilationUnit_GNSS;
_forceLibraryToIncludeCompilationUnit_GNSS = true;
extern bool _forceLibraryToIncludeCompilationUnit_NAV;
_forceLibraryToIncludeCompilationUnit_NAV = true;
extern bool _forceLibraryToIncludeCompilationUnit_Displacement;
_forceLibraryToIncludeCompilationUnit_Displacement = true;
return true;
}
ParserMap& MipFieldParser::getParserMap()
{
//force the linker to include all the parser files
static bool unused = run_once_forceLibraryToIncludeCompilationUnit();
//create a static ParserMap (1st time only) and return it
static ParserMap p;
return p;
}
bool MipFieldParser::registerParser(MipTypes::ChannelField field, const MipFieldParser* parser)
{
ParserMap& map = getParserMap();
//verify it doesn't already exist in the map
if(map.find(field) != map.end())
{
assert(false); //this should never happen
return false;
}
//store the parser in the map of parsers
getParserMap()[field] = parser;
return true;
}
void MipFieldParser::parseField(const MipDataField& field, MipDataPoints& result)
{
//get the static parser map
ParserMap& parsers = getParserMap();
MipTypes::ChannelField chField = static_cast<MipTypes::ChannelField>(field.fieldId());
//try to find a parser in our map that can parse this field type
std::map<MipTypes::ChannelField, const MipFieldParser*>::const_iterator itr = parsers.find(chField);
//if we can find a parser for this field type
if(itr != parsers.end())
{
//parse the field for data
itr->second->parse(field, result);
}
//if we failed to find a parser for this field type
else
{
//just add a data point of this whole field as bytes
result.push_back(MipDataPoint(chField, MipTypes::CH_UNKNOWN, valueType_Bytes, anyType(field.fieldData().data()), true));
}
}
bool MipFieldParser::pointIsValid(uint16 allFlags, uint16 flagPos)
{
//check the flag position against the allFlags value
return ((allFlags & flagPos) > 0);
}
} | 34.131868 | 132 | 0.631037 | HTLife |
5d5e4f8baa61d051d2e7338a6a6eedfdcdb9fc06 | 335 | cpp | C++ | codeforces/520/A.cpp | Mohammad-Elsharkawy/CompetitiveProgramming | 8d052465ff08cb36e66b7e6c6813090ac410bf1d | [
"MIT"
] | null | null | null | codeforces/520/A.cpp | Mohammad-Elsharkawy/CompetitiveProgramming | 8d052465ff08cb36e66b7e6c6813090ac410bf1d | [
"MIT"
] | null | null | null | codeforces/520/A.cpp | Mohammad-Elsharkawy/CompetitiveProgramming | 8d052465ff08cb36e66b7e6c6813090ac410bf1d | [
"MIT"
] | null | null | null | #include<iostream>
using namespace std;
char a[100];
int main()
{
int n;cin>>n;
for(int i=0;i<n;i++)
{
char b; cin>>b;
if(b<97)
{
b+=32;
}
a[b-'a']++;
}
bool fd=true;
for(int i=0;i<26;i++)
{
if(a[i]<1){
fd=false;
break;}
}
if(fd)
cout<<"YES";
else
cout<<"NO";
return 0;
}
| 9.571429 | 22 | 0.456716 | Mohammad-Elsharkawy |
5d61b0804f8300f7441216435805a70a54209db5 | 3,915 | cpp | C++ | FEBioSource2.9/FEBioFluid/FEFluidFSI.cpp | wzaylor/FEBio_MCLS | f1052733c31196544fb0921aa55ffa5167a25f98 | [
"Intel"
] | 1 | 2021-08-24T08:37:21.000Z | 2021-08-24T08:37:21.000Z | FEBioSource2.9/FEBioFluid/FEFluidFSI.cpp | wzaylor/FEBio_MCLS | f1052733c31196544fb0921aa55ffa5167a25f98 | [
"Intel"
] | null | null | null | FEBioSource2.9/FEBioFluid/FEFluidFSI.cpp | wzaylor/FEBio_MCLS | f1052733c31196544fb0921aa55ffa5167a25f98 | [
"Intel"
] | 1 | 2021-03-15T08:22:06.000Z | 2021-03-15T08:22:06.000Z | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2019 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
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 "stdafx.h"
#include "FEFluidFSI.h"
#include <FECore/FECoreKernel.h>
//-----------------------------------------------------------------------------
// Material parameters for the FEFluidFSI material
BEGIN_PARAMETER_LIST(FEFluidFSI, FEMaterial)
END_PARAMETER_LIST();
//============================================================================
// FEFSIMaterialPoint
//============================================================================
FEFSIMaterialPoint::FEFSIMaterialPoint(FEMaterialPoint* pt) : FEMaterialPoint(pt) {}
//-----------------------------------------------------------------------------
FEMaterialPoint* FEFSIMaterialPoint::Copy()
{
FEFSIMaterialPoint* pt = new FEFSIMaterialPoint(*this);
if (m_pNext) pt->m_pNext = m_pNext->Copy();
return pt;
}
//-----------------------------------------------------------------------------
void FEFSIMaterialPoint::Serialize(DumpStream& ar)
{
if (ar.IsSaving())
{
ar << m_w << m_aw << m_Jdot;
}
else
{
ar >> m_w >> m_aw >> m_Jdot;
}
FEMaterialPoint::Serialize(ar);
}
//-----------------------------------------------------------------------------
void FEFSIMaterialPoint::Init()
{
m_w = m_aw = vec3d(0,0,0);
m_Jdot = 0;
FEMaterialPoint::Init();
}
//============================================================================
// FEFluidFSI
//============================================================================
//-----------------------------------------------------------------------------
//! FEFluidFSI constructor
FEFluidFSI::FEFluidFSI(FEModel* pfem) : FEMaterial(pfem)
{
// set material properties
AddProperty(&m_pSolid, "solid");
AddProperty(&m_pFluid, "fluid");
}
//-----------------------------------------------------------------------------
// returns a pointer to a new material point object
FEMaterialPoint* FEFluidFSI::CreateMaterialPointData()
{
FEFluidMaterialPoint* fpt = new FEFluidMaterialPoint(m_pSolid->CreateMaterialPointData());
return new FEFSIMaterialPoint(fpt);
}
//-----------------------------------------------------------------------------
// Set the local coordinate system
void FEFluidFSI::SetLocalCoordinateSystem(FEElement& el, int n, FEMaterialPoint& mp)
{
FEElasticMaterial* pme = GetElasticMaterial();
pme->SetLocalCoordinateSystem(el, n, mp);
}
//-----------------------------------------------------------------------------
// initialize
bool FEFluidFSI::Init()
{
// set the solid density to zero (required for the solid of a FSI domain)
m_pSolid->SetDensity(0.0);
return FEMaterial::Init();
}
| 34.646018 | 94 | 0.561175 | wzaylor |
5d6547775c2cdcc1b32b18db1c787c3b5793479b | 16,973 | cpp | C++ | main.cpp | abhijith0505/ReMorse | b743193a73a9ed318e5d9ea298255ceb199421be | [
"MIT"
] | 12 | 2017-07-26T09:45:55.000Z | 2021-07-05T04:13:18.000Z | main.cpp | abhijith0505/ReMorse | b743193a73a9ed318e5d9ea298255ceb199421be | [
"MIT"
] | null | null | null | main.cpp | abhijith0505/ReMorse | b743193a73a9ed318e5d9ea298255ceb199421be | [
"MIT"
] | 3 | 2019-10-02T02:35:27.000Z | 2021-07-05T04:13:22.000Z | ///////////////////////////////Requires opengl 1.2/////////////////////////////
#include <string>
#include <sstream>
#include "remorse.h"
#include "lib/lodepng.h"
#include "lib/lodepng.cpp"
#include "states.h"
#include "keys.h"
#include "timer.h"
#include "physics.h"
// THINK:maybe height and width should be in settings?
int HEIGHT = 600;
int WIDTH = 800;
auto reInitBuffer = glutStrokeCharacter;
//To scale coordinates from physics world to graphics
float B2_SCALEX = 100.0;
float B2_SCALEY = 100.0;
float B2_OFFSETX = -225.0;
float B2_OFFSETY = -400.0;
//THINK: where to put score, may be in the values given by backend
auto BUF1 = GLUT_STROKE_ROMAN;
// THINK:Where the hell do I keep this texname variable?
// may be make static put inside the function? BTW this for loading texture
GLuint texname;
using namespace std;
namespace R_settings
{
// TODO:put more things here
bool ANTIALIAS=true;
int MINWIDTH=640;
int MINHEIGHT=550;
}
namespace R_images
{
// THINK:not sure if this is the right way to store images and its properties
const char* logoName="res/morse.png";
vector<unsigned char> logo;
unsigned logoWidth;
unsigned logoHeight;
const char* samName[]={"res/sam01.png","res/sam02.png","res/sam03.png","res/sam04.png"};
vector<unsigned char> sam[4];
unsigned samWidth[4];
unsigned samHeight[4];
/** OpenGL seems to draw images vertically flipped
this function inverts our data so that it displays correctly
@param img is our image data vector
@param width is our image width
@param height is our image height
*/
void invert(vector<unsigned char> &img,const unsigned width,const unsigned height)
{
unsigned char *imageptr = &img[0];
unsigned char *first = NULL;
unsigned char *last = NULL;
unsigned char temp = 0;
for( int h = 0; h <(int) height/2; ++h )
{
first = imageptr + h * width * 4;
last = imageptr + (height - h - 1) * width*4;
for( int i = 0; i < (int)width*4; ++i )
{
temp = *first;
*first = *last;
*last = temp;
++first;
++last;
}
}
}
/** Loads all required images for our game
*/
void loadImages()
{
//THINK:we are doing the same if else many times may be make a function?
int error;
if((error=lodepng::decode(logo,logoWidth,logoHeight,logoName)))
{
cout<<logoName<<":"<<lodepng_error_text(error)<<endl;
exit(1);
}
else
invert(logo,logoWidth,logoHeight);
if((error=lodepng::decode(sam[0],samWidth[0],samHeight[0],samName[0])))
{
cout<<samName[0]<<":"<<lodepng_error_text(error)<<endl;
exit(1);
}
else
invert(sam[0],samWidth[0],samHeight[0]);
if((error=lodepng::decode(sam[1],samWidth[1],samHeight[1],samName[1])))
{
cout<<samName[1]<<":"<<lodepng_error_text(error)<<endl;
exit(1);
}
else
invert(sam[1],samWidth[1],samHeight[1]);
if((error=lodepng::decode(sam[2],samWidth[2],samHeight[2],samName[2])))
{
cout<<samName[2]<<":"<<lodepng_error_text(error)<<endl;
exit(1);
}
else
invert(sam[2],samWidth[2],samHeight[2]);
if((error=lodepng::decode(sam[3],samWidth[3],samHeight[3],samName[3])))
{
cout<<samName[3]<<":"<<lodepng_error_text(error)<<endl;
exit(1);
}
else
invert(sam[3],samWidth[3],samHeight[3]);
}
}
/** Sets current texture to given image
@param img is image vector that has already been loaded
@param width is width of the image
@param height is height of image
*/
void setTexture(vector<unsigned char> img, unsigned width, unsigned height)
{
glBindTexture(GL_TEXTURE_2D, texname);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
// without this texture darkens
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height,
0, GL_RGBA, GL_UNSIGNED_BYTE, &img[0]);
}
/**
Set a letter on top of screen, used during game loop
@param ch specifies the character to be displayed
*/
void setLetter(char ch)
{
glLineWidth(3);
glColor3ub(0x42,0x42,0x42);
//push and pop is required in model view!
glPushMatrix();
glTranslatef(WIDTH/2.0-50,HEIGHT-110,0);
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)ch);
glPopMatrix();
}
/**
Draw a Button at 0,0
@param str specifies the string to be shown in button
@param outlined specifies outline, mostly used to show selection
*/
void drawButton(const char* str,bool outlined)
{
// Currently all our buttons use .3x of size of font
// anyway we can scale it by calling scalef before drawButton
// all values found by trial and error method
float width=glutStrokeLength(GLUT_STROKE_ROMAN,(unsigned char*)str)*.3;
float height=glutStrokeHeight(GLUT_STROKE_ROMAN)*.3;
glColor3ub(0x42,0x42,0x42);
glBegin(GL_POLYGON);
glVertex2f(0,0);
glVertex2f(0,height);
glVertex2f(width+10,height);
glVertex2f(width+10,0);
glEnd();
if(outlined)
{
// Draw outline if specified
glColor3ub(0,0,0);
glLineWidth(5);
glBegin(GL_LINE_LOOP);
glVertex2f(0,0);
glVertex2f(0,height);
glVertex2f(width+10,height);
glVertex2f(width+10,0);
glEnd();
}
glLineWidth(2);
glColor3ub(0xF4,0x43,0x36);
glTranslatef(5,7,0);
glScalef(.3,.3,0);
glutStrokeString(GLUT_STROKE_ROMAN,(unsigned char*)str);
}
void bufferRegenerate()
{
glColor3ub(0x22,0x22,0x22);
glPushMatrix();
glTranslatef(0,10,0);
glScalef(.15,.12,0);
glLineWidth(2);
int buf_offset = 60;
for(int i = 0; i < 16; ++i)
reInitBuffer(BUF1,(char)(int)R_physics::triPos[i+buf_offset][0]);
glPopMatrix();
glPushMatrix();
glTranslatef(0,25,0);
glScalef(.15,.12,0);
glLineWidth(2);
buf_offset = 76;
for(int i = 0; i <9; ++i)
reInitBuffer(BUF1,(char)(int)R_physics::triPos[i+buf_offset][0]);
glPopMatrix();
}
float getButtonWidth(const char* str)
{
return glutStrokeLength(GLUT_STROKE_ROMAN,(unsigned char*)str)*.3+10;
}
float getButtonHeight(const char* str)
{
return glutStrokeHeight(GLUT_STROKE_ROMAN)*.3;
}
//return graphics scaled values for physics coordinates
float getScaled(float val, bool x)
{
if(x)
return val*B2_SCALEX + B2_OFFSETX;
return val*B2_SCALEY + B2_OFFSETY;
}
void menuLoop()
{
glClear(GL_COLOR_BUFFER_BIT );
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// Thickness of font
glLineWidth(3);
glColor3ub(0xff,0xff,0xff);
glPushMatrix();
glTranslatef(WIDTH/2.0-250,HEIGHT-110,0);
glutStrokeString(GLUT_STROKE_ROMAN,(unsigned char*)"ReMorse");
glPopMatrix();
glPushMatrix();
glTranslatef(WIDTH/2.0-getButtonWidth("PLAY")/2.0,HEIGHT-200,0);
drawButton("PLAY",R_keys::CURSOR==0);
glPopMatrix();
glPushMatrix();
glTranslatef(WIDTH/2.0-getButtonWidth("QUIT")/2.0,HEIGHT-260,0);
drawButton("QUIT",R_keys::CURSOR==1);
glPopMatrix();
bufferRegenerate();
glPushMatrix();
glRasterPos2i(WIDTH/2-(R_images::logoWidth/2),0);
glDrawPixels(R_images::logoWidth,R_images::logoHeight, GL_RGBA, GL_UNSIGNED_BYTE, &R_images::logo[0]);
glPopMatrix();
glFlush();
}
void gameLoop()
{
glClear(GL_COLOR_BUFFER_BIT );
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
setLetter(R_physics::curLetter);
//display score
//why StringStream? Cuz to_string() doesn't freaking work in mingw compiler
glLineWidth(3);
glColor3ub(0xff,0xff,0xff);
glPushMatrix();
glTranslatef(5,HEIGHT-40,0);
glScalef(.3,.3,0);
ostringstream stm;
stm<<R_physics::SCORE;
glutStrokeString(GLUT_STROKE_ROMAN,(unsigned char*)stm.str().c_str());
stm.str("");
glPopMatrix();
glPushMatrix();
stm<<"$"<<R_physics::HIGHSCORE;
glTranslatef(WIDTH- getButtonWidth(stm.str().c_str()),HEIGHT-40,0);
glScalef(.3,.3,0);
glutStrokeString(GLUT_STROKE_ROMAN,(unsigned char*)stm.str().c_str());
glPopMatrix();
/* enable texture.
!!!!!!!!Very dangerous!!!!!!!. might affect other objects. disable before drawing other objects */
glEnable(GL_TEXTURE_2D);
{
//scoping so that these variables aren't accessible elsewhere
int sel=rand()%2;
int i=(R_physics::jumpForceOn?2:0);
setTexture(R_images::sam[i+sel],R_images::samWidth[i+sel],R_images::samHeight[i+sel]);
}
glPushMatrix();
glBegin(GL_POLYGON);
{
//scoping so that these variables aren't accessible elsewhere
float p00x = getScaled(R_physics::getPlayerX(), true);
float p00y = getScaled(R_physics::getPlayerY(), false);
float p01x = p00x;
float p01y = getScaled(R_physics::getPlayerY()+R_physics::playerHeight*2.0, false);
float p11x = getScaled(R_physics::getPlayerX()+R_physics::playerWidth*2.0, true);
float p11y = p01y;
float p10x = p11x;
float p10y = p00y;
glTexCoord2d(0,0); glVertex2f(p00x, p00y);
glTexCoord2d(0,1); glVertex2f(p01x, p01y);
glTexCoord2d(1,1); glVertex2f(p11x, p11y);
glTexCoord2d(1,0); glVertex2f(p10x, p10y);
}
glEnd();
glPopMatrix();
glDisable(GL_TEXTURE_2D);
//draw ground...
glPushMatrix();
glBegin(GL_POLYGON);
glColor3ub(0xF4,0x43,0x36);
glVertex2f(0,0);
glVertex2f(WIDTH,0);
glColor3ub(0xC6,0x28,0x28);
float g_height = getScaled(R_physics::groundHeight, false);
glVertex2f(WIDTH,g_height);
glVertex2f(0,g_height);
glEnd();
glPopMatrix();
glPushMatrix();
glColor3ub(0x00,0x00,0x00);
glBegin(GL_TRIANGLES);
for(int i=0;i<60;i++)
{
if(R_physics::triPos[i][0]!=-1)
{
float wid=R_physics::dotWidth;
float hei=R_physics::dotHeight;
if(R_physics::triPos[i][1]==0)
{
wid=R_physics::dashWidth;
hei=R_physics::dashHeight;
}
float x0=(float)R_physics::triPos[i][0]-wid/2.0;
float y0=(float)R_physics::groundHeight;
float x1=x0+wid/2.0;
float y1=y0+hei;
float x2=x0+wid;
float y2=y0;
glVertex2f(getScaled(x0,true),getScaled(y0,false));
glVertex2f(getScaled(x1,true),getScaled(y1,false));
glVertex2f(getScaled(x2,true),getScaled(y2,false));
}
}
glEnd();
glPopMatrix();
glFlush();
}
void pauseLoop()
{
glClear(GL_COLOR_BUFFER_BIT );
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glLineWidth(3);
glColor3ub(0xff,0xff,0xff);
glPushMatrix();
glTranslatef(WIDTH/2.0-250,HEIGHT-110,0);
glScalef(.5,.5,0);
glutStrokeString(GLUT_STROKE_ROMAN,(unsigned char*)"Game Paused!");
glPopMatrix();
glPushMatrix();
glTranslatef(WIDTH/2.0-getButtonWidth("RESUME")/2.0,HEIGHT-200,0);
drawButton("RESUME",R_keys::CURSOR==0);
glPopMatrix();
glPushMatrix();
glTranslatef(WIDTH/2.0-getButtonWidth("MENU")/2.0,HEIGHT-260,0);
drawButton("MENU",R_keys::CURSOR==1);
glPopMatrix();
glFlush();
}
void overLoop()
{
glClear(GL_COLOR_BUFFER_BIT );
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glLineWidth(3);
glColor3ub(0xff,0xff,0xff);
glPushMatrix();
glTranslatef(WIDTH/2.0-210,HEIGHT-110,0);
glScalef(.5,.5,0);
glutStrokeString(GLUT_STROKE_ROMAN,(unsigned char*)"Game Over!");
glPopMatrix();
glLineWidth(2);
glColor3ub(0xff,0xff,0xff);
glPushMatrix();
glTranslatef(WIDTH/2.0-210,HEIGHT-210,0);
glScalef(.2,.2,0);
glutStrokeString(GLUT_STROKE_ROMAN,(unsigned char*)"Press any key to continue.");
glPopMatrix();
glFlush();
}
static void resize(int width, int height)
{
// check if window size is too small, call reshape appropriately
// THINK/TODO: may be we should find a scale factor or something and scale each objects
if(width<R_settings::MINWIDTH && height<R_settings::MINHEIGHT)
glutReshapeWindow(R_settings::MINWIDTH,R_settings::MINHEIGHT);
else if(width<R_settings::MINWIDTH)
glutReshapeWindow(R_settings::MINWIDTH,height);
else if(height<R_settings::MINHEIGHT)
glutReshapeWindow(width,R_settings::MINHEIGHT);
else
{
glClearColor(0.9568f,0.2627f,0.2117f,1.0f);
WIDTH=width;
HEIGHT=height;
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0,width,0,height);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity() ;
}
}
static void display(void)
{
static int frame=0,curtime,timebase=0;
// Draw stuff here
switch(R_states::STATE)
{
case R_states::MENU:
menuLoop();break;
case R_states::GAME:
gameLoop();break;
case R_states::PAUSE:
pauseLoop();break;
case R_states::GAMEOVER:
overLoop();
break;
}
// FPS calculation
frame++;
curtime=glutGet(GLUT_ELAPSED_TIME);
if (curtime - timebase > 1000) {
printf("FPS:%4.2f\n",
frame*1000.0/(curtime-timebase));
timebase = curtime;
frame = 0;
}
glutSwapBuffers();
}
static void idle(void)
{
// display opengl error for debugging
if (GLenum err = glGetError())
{
cerr << "OpenGL ERROR: " << gluErrorString(err) << endl;
}
//glutPostRedisplay();
}
/**
Do anti alias if set in settings
*/
void antialias()
{
if(R_settings::ANTIALIAS)
{
///////////////////////Do anti alias/////////////////////////
// creates spaces (lines) bw polygon if multisample does not work
glEnable(GL_POLYGON_SMOOTH);
// THINK:not sure enabling again is required?
glEnable(GL_MULTISAMPLE);
////////////////////////end of anti alias////////////////////
GLint iMultiSample = 0;
GLint iNumSamples = 0;
glGetIntegerv(GL_SAMPLE_BUFFERS, &iMultiSample);
glGetIntegerv(GL_SAMPLES, &iNumSamples);
printf("MSAA on, GL_SAMPLE_BUFFERS = %d, GL_SAMPLES = %d\n", iMultiSample, iNumSamples);
}
else
{
glDisable(GL_MULTISAMPLE);
printf("MSAA off\n");
}
}
/* Program entry point */
int main(int argc, char *argv[])
{
//TODO:should put this in init
R_images::loadImages();
glGenTextures(1, &texname);
glutInit(&argc, argv);
glutInitWindowSize(WIDTH,HEIGHT);
glutInitWindowPosition(10,10);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GL_MULTISAMPLE);
if(!glutGet(GLUT_DISPLAY_MODE_POSSIBLE))
{
//fallback if multisample is not possible
glutInitDisplayMode(GLUT_RGBA|GLUT_DOUBLE);
R_settings::ANTIALIAS=false;
}
else
glutSetOption(GLUT_MULTISAMPLE, 8);
glClearColor(0.9568f,0.2627f,0.2117f,1.0f);
glutCreateWindow("ReMorse");
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
/* smoothen lines n points, doesn't seem to get affected by MULTISAMPLE.
works only if called after the BlendFunc */
glEnable(GL_POINT_SMOOTH);
glEnable(GL_LINE_SMOOTH);
antialias();
// make cursor invisible
glutSetCursor(GLUT_CURSOR_NONE);
// set appropriate functions, THINK::may be we should put this in init as well
glutReshapeFunc(resize);
glutDisplayFunc(display);
glutKeyboardFunc(R_keys::key);
glutKeyboardUpFunc(R_keys::keyup);
glutSpecialFunc(R_keys::splkey);
glutSpecialUpFunc(R_keys::splkeyup);
glutTimerFunc(17,timer,UPDATE);
// glutMouseFunc(R_mouse::mouse);
glutIdleFunc(idle);
// make key not repeat events on long press
glutSetKeyRepeat(GLUT_KEY_REPEAT_OFF);
glutMainLoop();
return EXIT_SUCCESS;
}
| 31.200368 | 107 | 0.608908 | abhijith0505 |
5d66a7445c7593000489b1211239b8f3736be073 | 253 | cpp | C++ | Conductor/src/ecs/Entity.cpp | haferflocken/ConductorEngine | 4914e419e5a736275e96d76eaa19b7aa56d69345 | [
"Zlib",
"BSD-2-Clause"
] | null | null | null | Conductor/src/ecs/Entity.cpp | haferflocken/ConductorEngine | 4914e419e5a736275e96d76eaa19b7aa56d69345 | [
"Zlib",
"BSD-2-Clause"
] | null | null | null | Conductor/src/ecs/Entity.cpp | haferflocken/ConductorEngine | 4914e419e5a736275e96d76eaa19b7aa56d69345 | [
"Zlib",
"BSD-2-Clause"
] | null | null | null | #include <ecs/Entity.h>
constexpr size_t k_sizeOfEntity = sizeof(ECS::Entity);
static_assert(k_sizeOfEntity == 64, "Entity should be the size of a cache line.");
const ECS::ComponentType ECS::Entity::k_type{ Util::CalcHash(ECS::Entity::k_typeName) };
| 36.142857 | 88 | 0.750988 | haferflocken |
5d6a21397617bfdc35c7fa5386620894bd29eec5 | 627 | cpp | C++ | HEmpute-Train/src/hmpt_nomenclature.cpp | K-miran/HEmpute | 2d55d9665dabdbe5b8b6b33eebe0e3346b02e9da | [
"MIT"
] | null | null | null | HEmpute-Train/src/hmpt_nomenclature.cpp | K-miran/HEmpute | 2d55d9665dabdbe5b8b6b33eebe0e3346b02e9da | [
"MIT"
] | null | null | null | HEmpute-Train/src/hmpt_nomenclature.cpp | K-miran/HEmpute | 2d55d9665dabdbe5b8b6b33eebe0e3346b02e9da | [
"MIT"
] | 1 | 2020-07-02T04:42:34.000Z | 2020-07-02T04:42:34.000Z | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hmpt_nomenclature.h"
#include "hmpt_ansi_string.h"
void normalize_chr_id(char* raw_chr_id)
{
// First replace the characters that are illegal with the underscore.
t_string::replace_avoid_list(raw_chr_id, "+-./\\*^$#@!&()~+=?\"`][}{ ", '_');
if(t_string::starts_with(raw_chr_id, "chr") ||
t_string::starts_with(raw_chr_id, "Chr") ||
t_string::starts_with(raw_chr_id, "CHR"))
{
// Get rid of the first 3 characters.
char temp[1000];
strcpy(temp, &raw_chr_id[3]);
strcpy(raw_chr_id, temp);
}
else
{
// No need to change.
return;
}
}
| 22.392857 | 78 | 0.668262 | K-miran |
5d6c39265c948adb720c32a011c8f5e8b0c56995 | 768 | cpp | C++ | cf/8e_tmp.cpp | LihuaWu/algorithms | ea0f177f3d7b6eca667c7d53e76f590b4f5bf9c5 | [
"MIT"
] | null | null | null | cf/8e_tmp.cpp | LihuaWu/algorithms | ea0f177f3d7b6eca667c7d53e76f590b4f5bf9c5 | [
"MIT"
] | null | null | null | cf/8e_tmp.cpp | LihuaWu/algorithms | ea0f177f3d7b6eca667c7d53e76f590b4f5bf9c5 | [
"MIT"
] | null | null | null | #include<cstdio>
#include<cstring>
#include<iostream>
#define ll long long
#define N 55
bool v[N][2][2];
ll res,k,f[N][2][2];
char a[N]; int n;
ll cal(int l,int x,int y)
{
ll &res=f[l][x][y]; if (v[l][x][y]) return res;
v[l][x][y]=1,res=0; if (l+l>=n) return res=1;
for (int i=0;i<2;i++) if (!a[l] || a[l]==i+48)
for (int j=0;j<2;j++) if (!a[n-1-l] || a[n-1-l]==j+48)
if ((l+l+1!=n || i==j) && (x||i<=j) && (y||i+j<2)) res+=cal(l+1,x||i<j,y||i+j<1);
return res;
}
int main()
{
std::cin>>n>>k,k++;
std::cout << cal(0,0,0) << "\n";
if (cal(0,0,0)<k) return puts("-1"),0;
for (int i=0;i<n;i++){
a[i]='0'; memset(v,0,sizeof(v)); res=cal(0,0,0);
if (res<k) k-=res,a[i]='1';
}
return puts(a),0;
}
| 25.6 | 93 | 0.464844 | LihuaWu |
5d738d8620335aa80e1a33673da3e874342a5bcd | 388 | hpp | C++ | winwrap/Handle.hpp | ePi5131/winwrap | de29f34b822f330ed2d13e6a3b2fa35c96f456ee | [
"BSD-1-Clause"
] | null | null | null | winwrap/Handle.hpp | ePi5131/winwrap | de29f34b822f330ed2d13e6a3b2fa35c96f456ee | [
"BSD-1-Clause"
] | null | null | null | winwrap/Handle.hpp | ePi5131/winwrap | de29f34b822f330ed2d13e6a3b2fa35c96f456ee | [
"BSD-1-Clause"
] | null | null | null | #pragma once
#include <Windows.h>
namespace WinWrap {
class Handle;
class Handle {
public:
HANDLE m_handle;
constexpr Handle() : m_handle(NULL) {}
constexpr Handle(HANDLE handle) : m_handle(handle) {}
};
inline constexpr Handle NullHandle{};
inline constexpr Handle InvalidHandle{INVALID_HANDLE_VALUE};
} // namespace WinWrap
| 19.4 | 64 | 0.649485 | ePi5131 |
5d7c14dc7ab40e976634e422708bfd16373bae8f | 474 | cpp | C++ | GenVania/src/GenericBullet.cpp | kalsipp/vsxpanse | 7887d234312283ce1ace03bed610642b0c6f96b1 | [
"MIT"
] | null | null | null | GenVania/src/GenericBullet.cpp | kalsipp/vsxpanse | 7887d234312283ce1ace03bed610642b0c6f96b1 | [
"MIT"
] | null | null | null | GenVania/src/GenericBullet.cpp | kalsipp/vsxpanse | 7887d234312283ce1ace03bed610642b0c6f96b1 | [
"MIT"
] | null | null | null | #include "GenericBullet.hpp"
#include "FileHandler.hpp"
GenericBullet::GenericBullet(GAMEOBJECT_ID id) :GameObject(id)
{
m_spritecomponent = add_component<SpriteComponent>();
m_spritecomponent->load_sprite_from_image(FileHandler::get_item("Images//resource.png"));
m_bulletcomponent = add_component<BulletComponent>();
m_collider = add_component<CircleCollider>();
m_collider->initialize(5, Vector2D());
m_name = "GenericBullet";
}
void GenericBullet::setup()
{
}
| 26.333333 | 90 | 0.778481 | kalsipp |
5d7df08b80231a5aa3bd8bab6ab5dc5d350cb1d1 | 2,046 | cpp | C++ | features/editable/cmake/say/src/say.cpp | davidtazy/examples | 6eaf6646bd1d321991428dbe016d8ba69c68fc78 | [
"MIT"
] | 95 | 2019-03-09T09:34:57.000Z | 2022-03-22T05:06:44.000Z | features/editable/cmake/say/src/say.cpp | davidtazy/examples | 6eaf6646bd1d321991428dbe016d8ba69c68fc78 | [
"MIT"
] | 69 | 2019-03-06T13:18:55.000Z | 2021-11-25T18:33:26.000Z | features/editable/cmake/say/src/say.cpp | davidtazy/examples | 6eaf6646bd1d321991428dbe016d8ba69c68fc78 | [
"MIT"
] | 57 | 2019-03-06T12:34:05.000Z | 2022-03-08T19:51:01.000Z | #include <iostream>
#include "say.h"
void say(){
#ifdef NDEBUG
std::cout << "say/0.1: Hello World Release!\n";
#else
std::cout << "say/0.1: Hello World Debug!\n";
#endif
// ARCHITECTURES
#ifdef _M_X64
std::cout << " say/0.1: _M_X64 defined\n";
#endif
#ifdef _M_IX86
std::cout << " say/0.1: _M_IX86 defined\n";
#endif
#if __i386__
std::cout << " say/0.1: __i386__ defined\n";
#endif
#if __x86_64__
std::cout << " say/0.1: __x86_64__ defined\n";
#endif
// Libstdc++
#if defined _GLIBCXX_USE_CXX11_ABI
std::cout << " say/0.1: _GLIBCXX_USE_CXX11_ABI "<< _GLIBCXX_USE_CXX11_ABI << "\n";
#endif
// COMPILER VERSIONS
#if _MSC_VER
std::cout << " say/0.1: _MSC_VER" << _MSC_VER<< "\n";
#endif
#if _MSVC_LANG
std::cout << " say/0.1: _MSVC_LANG" << _MSVC_LANG<< "\n";
#endif
#if __cplusplus
std::cout << " say/0.1: __cplusplus" << __cplusplus<< "\n";
#endif
#if __INTEL_COMPILER
std::cout << " say/0.1: __INTEL_COMPILER" << __INTEL_COMPILER<< "\n";
#endif
#if __GNUC__
std::cout << " say/0.1: __GNUC__" << __GNUC__<< "\n";
#endif
#if __GNUC_MINOR__
std::cout << " say/0.1: __GNUC_MINOR__" << __GNUC_MINOR__<< "\n";
#endif
#if __clang_major__
std::cout << " say/0.1: __clang_major__" << __clang_major__<< "\n";
#endif
#if __clang_minor__
std::cout << " say/0.1: __clang_minor__" << __clang_minor__<< "\n";
#endif
#if __apple_build_version__
std::cout << " say/0.1: __apple_build_version__" << __apple_build_version__<< "\n";
#endif
// SUBSYSTEMS
#if __MSYS__
std::cout << " say/0.1: __MSYS__" << __MSYS__<< "\n";
#endif
#if __MINGW32__
std::cout << " say/0.1: __MINGW32__" << __MINGW32__<< "\n";
#endif
#if __MINGW64__
std::cout << " say/0.1: __MINGW64__" << __MINGW64__<< "\n";
#endif
#if __CYGWIN__
std::cout << " say/0.1: __CYGWIN__" << __CYGWIN__<< "\n";
#endif
}
| 23.25 | 88 | 0.569892 | davidtazy |
5d81453a6d22145988d25660a637ff6eec943d08 | 15,434 | cpp | C++ | sample_simulator/src/SvpSampleClassification.cpp | sophia-hxw/hi3559a_sample | 506217be4ad13dbed32d0045641c9645472cbe85 | [
"MIT"
] | 1 | 2020-12-02T16:22:01.000Z | 2020-12-02T16:22:01.000Z | sample_simulator/src/SvpSampleClassification.cpp | sophia-hxw/hi3559a_sample | 506217be4ad13dbed32d0045641c9645472cbe85 | [
"MIT"
] | null | null | null | sample_simulator/src/SvpSampleClassification.cpp | sophia-hxw/hi3559a_sample | 506217be4ad13dbed32d0045641c9645472cbe85 | [
"MIT"
] | 3 | 2020-12-21T16:17:54.000Z | 2021-09-13T10:00:18.000Z | #include "SvpSampleWk.h"
#include "SvpSampleCom.h"
#include "mpi_nnie.h"
#define SVP_SAMPLE_CLS_TOP_N (5)
const HI_CHAR *g_paszPicList_c[][SVP_NNIE_MAX_INPUT_NUM] = {
{ "../../data/classification/lenet/image_test_list_y.txt" },
{ "../../data/classification/imagenet/image_test_list_227.txt" },
{ "../../data/classification/imagenet/image_test_list_224.txt" },
{ "../../data/classification/imagenet/image_test_list_224.txt" },
{ "../../data/classification/imagenet/image_test_list_224.txt" },
{ "../../data/classification/imagenet/image_test_list_227.txt" },
{ "../../data/classification/mobilenet/image_test_list.txt" },
};
#ifndef USE_FUNC_SIM /* inst wk */
const HI_CHAR *g_paszModelName_c[] = {
"../../data/classification/lenet/inst/inst_lenet_inst_batch.wk",
"../../data/classification/alexnet/inst/alexnet_no_group_inst.wk",
"../../data/classification/vgg16/inst/vgg16_upgrade_deploy_inst.wk",
"../../data/classification/googlenet/inst/googlenet_upgrade_deploy_inst.wk",
"../../data/classification/resnet50/inst/ResNet50_model_inst.wk",
"../../data/classification/squeezenet/inst/squeezenet_v1.0_inst.wk",
"../../data/classification/mobilenet/inst/mobilenet_inst.wk",
};
#else /* func wk */
const HI_CHAR *g_paszModelName_c[] = {
"../../data/classification/lenet/inst/inst_lenet_func_batch.wk",
"../../data/classification/alexnet/inst/alexnet_no_group_func.wk",
"../../data/classification/vgg16/inst/vgg16_upgrade_deploy_func.wk",
"../../data/classification/googlenet/inst/googlenet_upgrade_deploy_func.wk",
"../../data/classification/resnet50/inst/ResNet50_model_func.wk",
"../../data/classification/squeezenet/inst/squeezenet_v1.0_func.wk",
"../../data/classification/mobilenet/inst/mobilenet_func.wk"
};
#endif
const HI_CHAR *g_paszLabel_c[][SVP_NNIE_MAX_OUTPUT_NUM] = {
{ "../../data/classification/lenet/label.txt" },
{ "../../data/classification/imagenet/test_label.txt" },
{ "../../data/classification/imagenet/test_label.txt" },
{ "../../data/classification/imagenet/test_label.txt" },
{ "../../data/classification/imagenet/test_label.txt" },
{ "../../data/classification/imagenet/test_label.txt" },
{ "../../data/classification/mobilenet/test_label.txt" },
};
HI_S32 SvpSampleGetTopNAfterSoftmax(SVP_BLOB_S *pstBlob, SVP_SAMPLE_CLF_RES_S *ps32IdxConf,
SVP_SAMPLE_CLF_RES_S *pstClfRes, HI_U32 u32TopN, HI_U32 u32ClfNum)
{
CHECK_EXP_RET(pstBlob->unShape.stWhc.u32Height != 1, HI_ERR_SVP_NNIE_ILLEGAL_PARAM,
"Blob height(%d) should be %d!", pstBlob->unShape.stWhc.u32Height, 1);
HI_U32 u32LineStride = 0, u32ScoreStep = 0;
HI_U32 u32ElemSize = sizeof(HI_S32);
if (pstBlob->unShape.stWhc.u32Width == u32ClfNum) {
// normal classification net which has FC layer before the last softmax layer
u32LineStride = pstBlob->u32Stride;
u32ScoreStep = u32ElemSize;
}
else if (pstBlob->unShape.stWhc.u32Chn == u32ClfNum) {
// classification net, such as squezzenet, which has global_pooling layer before the last softmax layer
u32LineStride = u32ClfNum * pstBlob->u32Stride;
u32ScoreStep = pstBlob->u32Stride;
}
else {
return HI_ERR_SVP_NNIE_ILLEGAL_PARAM;
}
for (HI_U32 n = 0; n < pstBlob->u32Num; n++)
{
// get score[n] base from DstBlob addr
HI_S32 *ps32Score = (HI_S32*)((HI_U8*)pstBlob->u64VirAddr + n * u32LineStride);
SVP_SAMPLE_CLF_RES_S *pstClfResN = pstClfRes + u32TopN * n;
// set score to classification result struct
for (HI_U32 classId = 0; classId < u32ClfNum; classId++) {
ps32IdxConf[classId].u32ClassId = classId;
ps32IdxConf[classId].u32Confidence = *(HI_U32*)((HI_U8*)ps32Score + classId * u32ScoreStep);
}
for (HI_U32 i = 0; i < u32TopN; i++)
{
HI_U32 topI = i;
// get max confidence index in rest data
for (HI_U32 j = i + 1; j < u32ClfNum; j++) {
if (ps32IdxConf[topI].u32Confidence < ps32IdxConf[j].u32Confidence) {
topI = j;
}
}
if (i != topI)
{
// exchange data between topI and i
SVP_SAMPLE_CLF_RES_S ClfResTemp = ps32IdxConf[topI];
ps32IdxConf[topI] = ps32IdxConf[i];
ps32IdxConf[i] = ClfResTemp;
}
// set score and classId to Result TopN
pstClfResN[i] = ps32IdxConf[i];
}
}
return HI_SUCCESS;
}
HI_S32 s_SvpSampleCnnClassificationPrintResult(FILE *fpLabel, SVP_SAMPLE_CLF_RES_S *pstClfRes, HI_U32 u32Num, HI_U32 u32TopN, HI_U32 u32LeafId)
{
CHECK_EXP_RET(!fpLabel, HI_ERR_SVP_NNIE_NULL_PTR, "%s input fpLabel nullptr error", __FUNCTION__);
CHECK_EXP_RET(!pstClfRes, HI_ERR_SVP_NNIE_NULL_PTR, "%s input pstClfRes nullptr error", __FUNCTION__);
rewind(fpLabel);
for (HI_U32 i = 0; i < u32Num; i++)
{
HI_S32 s32Label = 0;
SVP_SAMPLE_CLF_RES_S *pstClfResTopN = pstClfRes + i * u32TopN;
HI_U32 ret = FSCANF_S(fpLabel, "%d", &s32Label);
printf("fscanf return value is %d\n", ret);
printf("\nLeaf%u, Pic%u --> expected label: %d\n", u32LeafId, i, s32Label);
for (HI_U32 j = 0; j < u32TopN; j++)
{
printf("Top%u: index -- %4d, confidence -- %8.7f\n",
j, pstClfResTopN[j].u32ClassId, (HI_FLOAT)pstClfResTopN[j].u32Confidence / SVP_WK_QUANT_BASE);
}
}
return HI_SUCCESS;
}
HI_S32 SvpSampleCnnClassificationForword(SVP_NNIE_ONE_SEG_S *pstClfParam, SVP_NNIE_CFG_S *pstClfCfg)
{
HI_S32 s32Ret = HI_SUCCESS;
SVP_NNIE_HANDLE SvpNnieHandle = 0;
SVP_NNIE_ID_E enNnieId = SVP_NNIE_ID_0;
HI_BOOL bInstant = HI_TRUE;
HI_BOOL bFinish = HI_FALSE;
HI_BOOL bBlock = HI_TRUE;
s32Ret = HI_MPI_SVP_NNIE_Forward(&SvpNnieHandle, pstClfParam->astSrc, &pstClfParam->stModel,
pstClfParam->astDst, &pstClfParam->stCtrl, bInstant);
CHECK_EXP_RET(HI_SUCCESS != s32Ret, s32Ret, "Error(%#x): CNN_Forward failed!", s32Ret);
s32Ret = HI_MPI_SVP_NNIE_Query(enNnieId, SvpNnieHandle, &bFinish, bBlock);
while (HI_ERR_SVP_NNIE_QUERY_TIMEOUT == s32Ret) {
USLEEP(100);
s32Ret = HI_MPI_SVP_NNIE_Query(enNnieId, SvpNnieHandle, &bFinish, bBlock);
}
CHECK_EXP_RET(HI_SUCCESS != s32Ret, s32Ret, "Error(%#x): query failed!", s32Ret);
if (pstClfCfg->bNeedLabel)
{
for (HI_U32 i = 0; i < pstClfParam->stModel.astSeg[0].u16DstNum; i++)
{
SVP_SAMPLE_CLF_RES_S *pstIdScore = pstClfParam->pstMaxClfIdScore;
SVP_SAMPLE_CLF_RES_S *pstClfRes = pstClfParam->pastClfRes[i]; // dst[i] classification result memory
FILE *fpLabel = pstClfParam->fpLabel[i];
HI_S32 tempt = fseek(fpLabel, 0, SEEK_SET);
printf("fseek return value is %d\n", tempt);
s32Ret = SvpSampleGetTopNAfterSoftmax(&pstClfParam->astDst[i], pstIdScore, pstClfRes,
pstClfCfg->u32TopN, pstClfParam->au32ClfNum[i]);
CHECK_EXP_RET(HI_SUCCESS != s32Ret, s32Ret, "Error(%#x): getTopN failed!", s32Ret);
tempt = fseek(fpLabel, 0, SEEK_SET);
printf("fseek return value is %d\n", tempt);
s32Ret = s_SvpSampleCnnClassificationPrintResult(fpLabel, pstClfRes, pstClfParam->astDst[i].u32Num, pstClfCfg->u32TopN, i);
CHECK_EXP_RET(HI_SUCCESS != s32Ret, s32Ret, "Error(%#x): print result failed!", s32Ret);
}
}
return HI_SUCCESS;
}
/*classification with input images and labels, print the top-N result */
HI_S32 SvpSampleCnnClassification(const HI_CHAR *pszModelName, const HI_CHAR *paszPicList[], const HI_CHAR *paszLabel[], HI_S32 s32Cnt)
{
/**************************************************************************/
/* 1. check input para */
CHECK_EXP_RET(NULL == pszModelName, HI_ERR_SVP_NNIE_NULL_PTR, "Error(%#x): %s input pszModelName nullptr error!", HI_ERR_SVP_NNIE_NULL_PTR, __FUNCTION__);
CHECK_EXP_RET(NULL == paszPicList, HI_ERR_SVP_NNIE_NULL_PTR, "Error(%#x): %s input paszPicList nullptr error!", HI_ERR_SVP_NNIE_NULL_PTR, __FUNCTION__);
CHECK_EXP_RET(NULL == paszLabel, HI_ERR_SVP_NNIE_NULL_PTR, "Error(%#x): %s input paszLabel nullptr error!", HI_ERR_SVP_NNIE_NULL_PTR, __FUNCTION__);
CHECK_EXP_RET(s32Cnt <= 0 || s32Cnt > SVP_NNIE_MAX_INPUT_NUM, HI_ERR_SVP_NNIE_ILLEGAL_PARAM, "Error(%#x): %s input s32Cnt(%d) out of range(%d,%d] error!", HI_ERR_SVP_NNIE_ILLEGAL_PARAM, __FUNCTION__, s32Cnt, 0, SVP_NNIE_MAX_INPUT_NUM);
for (HI_S32 i = 0; i < s32Cnt; ++i) {
CHECK_EXP_RET(NULL == paszPicList[i], HI_ERR_SVP_NNIE_NULL_PTR, "Error(%#x): %s input paszPicList[%d] nullptr error!", HI_ERR_SVP_NNIE_NULL_PTR, __FUNCTION__, i);
CHECK_EXP_RET(NULL == paszLabel[i], HI_ERR_SVP_NNIE_NULL_PTR, "Error(%#x): %s input paszLabel[%d] nullptr error!", HI_ERR_SVP_NNIE_NULL_PTR, __FUNCTION__, i);
}
/**************************************************************************/
/* 2. declare definitions */
HI_S32 s32Ret = HI_SUCCESS;
HI_U32 u32TopN = SVP_SAMPLE_CLS_TOP_N;
HI_U32 u32MaxInputNum = SVP_NNIE_MAX_INPUT_NUM;
HI_U32 u32Batch = 0;
HI_U32 u32LoopCnt = 0;
HI_U32 u32StartId = 0;
SVP_NNIE_ONE_SEG_S stClfParam = { 0 };
SVP_NNIE_CFG_S stClfCfg = { 0 };
/**************************************************************************/
/* 3. init resources */
/* mkdir to save result, name folder by model type */
string strNetType = "SVP_SAMPLE_CLF";
string strResultFolderDir = "result_" + strNetType + "/";
s32Ret = SvpSampleMkdir(strResultFolderDir.c_str());
CHECK_EXP_RET(HI_SUCCESS != s32Ret, s32Ret, "SvpSampleMkdir(%s) failed", strResultFolderDir.c_str());
stClfCfg.pszModelName = pszModelName;
memcpy(&stClfCfg.paszPicList, paszPicList, sizeof(HI_VOID*)*s32Cnt);
memcpy(&stClfCfg.paszLabel, paszLabel, sizeof(HI_VOID*)*s32Cnt);
stClfCfg.u32MaxInputNum = u32MaxInputNum;
stClfCfg.u32TopN = u32TopN;
stClfCfg.bNeedLabel = HI_TRUE;
s32Ret = SvpSampleOneSegCnnInit(&stClfCfg, &stClfParam);
CHECK_EXP_RET(HI_SUCCESS != s32Ret, s32Ret, "SvpSampleOneSegCnnInitMem failed");
// assure that there is enough mem in one batch
// calc batch loop count
u32Batch = SVP_SAMPLE_MIN(u32MaxInputNum, stClfParam.u32TotalImgNum);
u32Batch = SVP_SAMPLE_MIN(u32Batch, stClfParam.astSrc[0].u32Num);
CHECK_EXP_GOTO(0 == u32Batch, Fail,
"u32Batch = 0 failed! u32MaxInputNum(%d), tClfParam.u32TotalImgNum(%d), astSrc[0].u32Num(%d)",
u32MaxInputNum, stClfParam.u32TotalImgNum, stClfParam.astSrc[0].u32Num);
u32LoopCnt = stClfParam.u32TotalImgNum / u32Batch;
/**************************************************************************/
/* 4. run classification forward */
// process images in batch size of u32Batch
for (HI_U32 i = 0; i < u32LoopCnt; i++)
{
vector<SVP_SAMPLE_FILE_NAME_PAIR> imgNameRecoder;
s32Ret = SvpSampleReadAllSrcImg(stClfParam.fpSrc, stClfParam.astSrc, stClfParam.stModel.astSeg[0].u16SrcNum, imgNameRecoder);
CHECK_EXP_GOTO(HI_SUCCESS != s32Ret, Fail, "Error(%#x):SvpSampleReadAllSrcImg failed!", s32Ret);
CHECK_EXP_GOTO(imgNameRecoder.size() != u32Batch, Fail,
"Error(%#x):imgNameRecoder.size(%d) != u32Batch(%d)", HI_FAILURE, (HI_U32)imgNameRecoder.size(), u32Batch);
s32Ret = SvpSampleCnnClassificationForword(&stClfParam, &stClfCfg);
CHECK_EXP_GOTO(HI_SUCCESS != s32Ret, Fail, "SvpSampleCnnClassificationForword failed");
u32StartId += u32Batch;
}
// the rest of images
u32Batch = stClfParam.u32TotalImgNum - u32StartId;
if (u32Batch > 0)
{
for (HI_U32 j = 0; j < stClfParam.stModel.astSeg[0].u16SrcNum; j++) {
stClfParam.astSrc[j].u32Num = u32Batch;
}
for (HI_U32 j = 0; j < stClfParam.stModel.astSeg[0].u16DstNum; j++) {
stClfParam.astDst[j].u32Num = u32Batch;
}
vector<SVP_SAMPLE_FILE_NAME_PAIR> imgNameRecoder;
s32Ret = SvpSampleReadAllSrcImg(stClfParam.fpSrc, stClfParam.astSrc, stClfParam.stModel.astSeg[0].u16SrcNum, imgNameRecoder);
CHECK_EXP_GOTO(HI_SUCCESS != s32Ret, Fail, "Error(%#x):SvpSampleReadAllSrcImg failed!", s32Ret);
CHECK_EXP_GOTO(imgNameRecoder.size() != u32Batch, Fail,
"Error(%#x):imgNameRecoder.size(%d) != u32Batch(%d)", HI_FAILURE, (HI_U32)imgNameRecoder.size(), u32Batch);
s32Ret = SvpSampleCnnClassificationForword(&stClfParam, &stClfCfg);
CHECK_EXP_GOTO(HI_SUCCESS != s32Ret, Fail, "SvpSampleCnnClassificationForword failed");
}
/**************************************************************************/
/* 5. deinit */
Fail:
SvpSampleOneSegCnnDeinit(&stClfParam);
return HI_SUCCESS;
}
void SvpSampleCnnClfLenet()
{
printf("%s start ...\n", __FUNCTION__);
SvpSampleCnnClassification(
g_paszModelName_c[SVP_SAMPLE_WK_CLF_NET_LENET],
{g_paszPicList_c[SVP_SAMPLE_WK_CLF_NET_LENET]},
{g_paszLabel_c[SVP_SAMPLE_WK_CLF_NET_LENET]});
printf("%s end ...\n\n", __FUNCTION__);
fflush(stdout);
}
void SvpSampleCnnClfAlexnet()
{
printf("%s start ...\n", __FUNCTION__);
SvpSampleCnnClassification(
g_paszModelName_c[SVP_SAMPLE_WK_CLF_NET_ALEXNET],
{g_paszPicList_c[SVP_SAMPLE_WK_CLF_NET_ALEXNET]},
{g_paszLabel_c[SVP_SAMPLE_WK_CLF_NET_ALEXNET]});
printf("%s end ...\n\n", __FUNCTION__);
fflush(stdout);
}
void SvpSampleCnnClfVgg16()
{
printf("%s start ...\n", __FUNCTION__);
SvpSampleCnnClassification(
g_paszModelName_c[SVP_SAMPLE_WK_CLF_NET_VGG16],
{g_paszPicList_c[SVP_SAMPLE_WK_CLF_NET_VGG16]},
{g_paszLabel_c[SVP_SAMPLE_WK_CLF_NET_VGG16]});
printf("%s end ...\n\n", __FUNCTION__);
fflush(stdout);
}
void SvpSampleCnnClfGooglenet()
{
printf("%s start ...\n", __FUNCTION__);
SvpSampleCnnClassification(
g_paszModelName_c[SVP_SAMPLE_WK_CLF_NET_GOOGLENET],
{g_paszPicList_c[SVP_SAMPLE_WK_CLF_NET_GOOGLENET]},
{g_paszLabel_c[SVP_SAMPLE_WK_CLF_NET_GOOGLENET]});
printf("%s end ...\n\n", __FUNCTION__);
fflush(stdout);
}
void SvpSampleCnnClfResnet50()
{
printf("%s start ...\n", __FUNCTION__);
SvpSampleCnnClassification(
g_paszModelName_c[SVP_SAMPLE_WK_CLF_NET_RESNET50],
{g_paszPicList_c[SVP_SAMPLE_WK_CLF_NET_RESNET50]},
{g_paszLabel_c[SVP_SAMPLE_WK_CLF_NET_RESNET50]});
printf("%s end ...\n\n", __FUNCTION__);
fflush(stdout);
}
void SvpSampleCnnClfSqueezenet()
{
printf("%s start ...\n", __FUNCTION__);
SvpSampleCnnClassification(
g_paszModelName_c[SVP_SAMPLE_WK_CLF_NET_SQUEEZENET],
{g_paszPicList_c[SVP_SAMPLE_WK_CLF_NET_SQUEEZENET]},
{g_paszLabel_c[SVP_SAMPLE_WK_CLF_NET_SQUEEZENET]});
printf("%s end ...\n\n", __FUNCTION__);
fflush(stdout);
}
void SvpSampleCnnClfMobilenet()
{
printf("%s start ...\n", __FUNCTION__);
SvpSampleCnnClassification(
g_paszModelName_c[SVP_SAMPLE_WK_CLF_NET_MOBILENET],
{ g_paszPicList_c[SVP_SAMPLE_WK_CLF_NET_MOBILENET] },
{ g_paszLabel_c[SVP_SAMPLE_WK_CLF_NET_MOBILENET] });
printf("%s end ...\n\n", __FUNCTION__);
fflush(stdout);
}
| 42.635359 | 239 | 0.662174 | sophia-hxw |
5d84141ab495e45182c73442eddf785260b5e6f8 | 4,059 | cpp | C++ | src/portal/game_info.cpp | mokoi/luxengine | 965532784c4e6112141313997d040beda4b56d07 | [
"MIT"
] | 11 | 2015-03-02T07:43:00.000Z | 2021-12-04T04:53:02.000Z | src/portal/game_info.cpp | mokoi/luxengine | 965532784c4e6112141313997d040beda4b56d07 | [
"MIT"
] | 1 | 2015-03-28T17:17:13.000Z | 2016-10-10T05:49:07.000Z | src/portal/game_info.cpp | mokoi/luxengine | 965532784c4e6112141313997d040beda4b56d07 | [
"MIT"
] | 3 | 2016-11-04T01:14:31.000Z | 2020-05-07T23:42:27.000Z | /****************************
Copyright © 2006-2015 Luke Salisbury
This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
****************************/
#include "game_info.h"
#include "elix/elix_path.hpp"
#include "elix/elix_string.hpp"
#include "tinyxml/tinyxml2ext.h"
#include "portal.h"
/**
* @brief GameInfo::GameInfo
* @param gui
* @param game_path
*/
GameInfo::GameInfo( UserInterface * gui, std::string game_path )
{
this->type = GI_INVALID;
this->gui = gui;
this->button = NULL;
this->icon = NULL;
this->url = game_path;
this->DetermitedType();
}
/**
* @brief GameInfo::GameInfo
* @param gui
* @param xml_element
*/
GameInfo::GameInfo( UserInterface * gui, tinyxml2::XMLElement * xml_element )
{
this->type = GI_INVALID;
this->gui = gui;
this->button = NULL;
this->icon = NULL;
this->hash = 0;
tinyxml2::QueryStringAttribute( xml_element->FirstChildElement("download"), "url", this->url );
if ( elix::string::HasPrefix( this->url, "http") )
{
std::string title = xml_element->FirstChildElement("title")->GetText();
std::string author = xml_element->FirstChildElement("author")->GetText();
this->information = title + "\nAuthor: " + author + "\nURL: " + this->url;
this->type = GI_ONLINE;
this->hash = elix::string::Hash( this->url );
}
}
/**
* @brief GameInfo::~GameInfo
*/
GameInfo::~GameInfo( )
{
if ( this->button )
{
this->ClearGUI();
}
if ( this->icon )
{
this->gui->GetDisplaySystem()->graphics.FreeSprite( this->icon );
NULLIFY( this->icon );
}
}
/**
* @brief GameInfo::ClearGUI
*/
void GameInfo::ClearGUI()
{
this->gui->RemoveChild( this->button );
NULLIFY( this->button );
}
/**
* @brief GameInfo::SetGUI
* @param value
* @param x
* @param y
* @param width
* @param height
* @return
*/
uint32_t GameInfo::SetGUI( int32_t value, int32_t x, int32_t y, uint16_t width, uint16_t height )
{
if ( !this->button )
{
std::string button_text;
this->buttonArea.x = x;
this->buttonArea.y = y;
this->buttonArea.w = width;
this->buttonArea.h = height;
button_text = this->information;
if ( width > 8 )
{
elix::string::TruncateLines( button_text, (width-32) / 8 );
//elix::string::TruncateLines( button_text, 20 );
}
this->button = this->gui->AddChild( buttonArea, IMAGEBUTTON, button_text );
this->button->SetIcon( this->icon );
this->button->SetValue( value );
return this->button->GetAreaHeight() + 4;
}
return 0;
}
/**
* @brief GameInfo::DetermitedType
*/
void GameInfo::DetermitedType()
{
/* Check if Directory */
if ( elix::path::Exist( this->url ) )
{
this->information = "Directory\n" + this->url;
this->type = GI_DIR;
}
/* Check for Game */
MokoiGame * game = new MokoiGame( this->url, false );
if ( game->valid )
{
this->type = GI_FILE;
this->information = game->GetTitle() + "\nAuthor: " + game->GetAuthor() + "\nPath: " + game->GetFilename();
if ( game->png && game->png_length )
{
this->icon = this->gui->GetDisplaySystem()->graphics.PNGtoSprite( game->png, game->png_length );
}
}
delete game;
/* > Temporary hack */
/* Check other support types */
if ( elix::string::HasSuffix( this->url, ".qst.gz") )
{
this->type = GI_SPECIAL;
this->information = "Classic Quest\nUnknown Author\nPath: " + this->url;
}
/* < Temporary hack */
}
| 24.75 | 243 | 0.665928 | mokoi |
5d85c0155fbd8d3e9ab9f306a163fdffc1376968 | 25,101 | cpp | C++ | GameServer/doFuncExpedition.cpp | openlastchaos/lastchaos-source-server | 935b770fa857e67b705717d154b11b717741edeb | [
"Apache-2.0"
] | null | null | null | GameServer/doFuncExpedition.cpp | openlastchaos/lastchaos-source-server | 935b770fa857e67b705717d154b11b717741edeb | [
"Apache-2.0"
] | null | null | null | GameServer/doFuncExpedition.cpp | openlastchaos/lastchaos-source-server | 935b770fa857e67b705717d154b11b717741edeb | [
"Apache-2.0"
] | 1 | 2022-01-17T09:34:39.000Z | 2022-01-17T09:34:39.000Z | #include "stdhdrs.h"
#include "Log.h"
#include "Character.h"
#include "Server.h"
#include "CmdMsg.h"
#include "doFunc.h"
#include "WarCastle.h"
/////////////////
// 원정대 관련 함수
void do_Expedition(CPC* ch, CNetMsg::SP& msg)
{
// 안보이면 무시
if (!ch->m_bVisible)
return ;
unsigned char subtype;
msg->MoveFirst();
RefMsg(msg) >> subtype;
switch (subtype)
{
case MSG_CREATE_REQ: // 파티 => 원정대 전환
do_ExpedCreateReq(ch, msg);
break;
case MSG_INVITE_REQ: // 초대 요청
do_ExpedInviteReq(ch, msg);
break;
case MSG_ALLOW_REQ: // 초대 수락
do_ExpedAllowReq(ch, msg);
break;
case MSG_REJECT_REQ: // 초대 거부 요청
do_ExpedRejectReq(ch, msg);
break;
case MSG_QUIT_REQ: // 탈퇴 요청
do_ExpedQuitReq(ch, msg);
break;
case MSG_ENDEXPED_REQ: // 원정대 해체
do_ExpedEndExpedReq(ch, msg);
break;
case MSG_KICK_REQ: // 추방 요청
do_ExpedKickReq(ch, msg);
break;
case MSG_CHANGETYPE_REQ: // 원정대 타입 변경
do_ExpedChangeTypeReq(ch, msg);
break;
case MSG_CHANGEBOSS_REQ: // 원정 대장 위임(변경)
do_ExpedChangeBossReq(ch, msg);
break;
case MSG_SETMBOSS_REQ: // 부대장 임명
do_ExpedSetMBossReq(ch, msg);
break;
case MSG_RESETMBOSS_REQ: // 부대장 임명 해제
do_ExpedResetMBossReq(ch, msg);
break;
case MSG_MOVEGROUP_REQ: // 그룹 이동
do_ExpedMoveGroupReq(ch, msg);
break;
case MSG_ADDMEMBER_REQ: // 대원 추가
do_ExpedAddMemberReq(ch, msg);
break;
case MSG_VIEWDETAIL_REQ: // 살펴보기
do_ExpedViewDetailReq(ch, msg);
break;
case MSG_SET_LABEL_REQ: // 표식 지정
do_ExpedSetLabelReq(ch, msg);
break;
case MSG_QUESTITEM_CHECK_REQ:
do_ExpedSearchItemReq(ch, msg); // Collect Trigger item - 원정대 Trigger 아이템 수집(원정대장 전용 기능)
break;
case MSG_EXPEND_OFFLINE:
do_ExpendOffline(ch, msg);
break;
}
}
//원정대 생성(파티 전환)(대장)
void do_ExpedCreateReq(CPC* ch, CNetMsg::SP& msg)
{
GAMELOG << init("EXPED DEBUG CREATE REQ", ch)
<< end;
if(ch->m_Exped)
return ;
#ifdef BLOCK_CHANGE_EXPED_IN_PARTY_RAID_ZONE
if(ch->m_pZone->IsPartyRaidZone())
{
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_CREATE_INVALIDZONE);
SEND_Q(rmsg, ch->m_desc);
return ;
}
#endif
//파티에 소속되어 있는가?
if (ch->m_party == NULL)
{
// 파티에 소속되지 않음(파티 전환 불가)
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_NOT_PARTY);
SEND_Q(rmsg, ch->m_desc);
return;
}
//파티장인가?
if(ch->m_party->GetBossIndex() != ch->m_index)
{
// 파티장이 아니다. (파티전환 불가)
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_NOT_PARTYBOSS);
SEND_Q(rmsg, ch->m_desc);
return;
}
#ifdef EXTREME_CUBE
if ( ch->m_party->m_cubeUniqueIdx > 0 )
{
return ;
}
#endif
//파티 맴버 중 한명이라도 로그아웃 되어 있으면 원정대 전환 불가.
int onlineCount = ch->m_party->GetMemberCountOnline();
int totalCount = ch->m_party->GetMemberCount();
if( onlineCount != totalCount )
{
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_EXIST_LOGOUT_MEMBER);
SEND_Q(rmsg, ch->m_desc);
return;
}
{
CNetMsg::SP rmsg(new CNetMsg);
HelperExpedCreateReqMsg(rmsg, ch->m_party->GetBossIndex(),ch->GetName());
SEND_Q(rmsg, gserver->m_helper);
}
}
//원정대 초대(대장)
void do_ExpedInviteReq(CPC* ch, CNetMsg::SP& msg)
{
int destindex;
RefMsg(msg) >> destindex;
GAMELOG << init("EXPED DEBUG INVITE REQ", ch)
<< "DESTINDEX" << delim << destindex
<< end;
if (ch->m_index == destindex)
return ;
CPC * pTargetPC = PCManager::instance()->getPlayerByCharIndex(destindex);
if(pTargetPC == NULL)
return;
if(pTargetPC->m_party != NULL)
{
//에러: 다른 그룹에 소속되어 있음
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_ALREADY_JOIN_OTHER);
SEND_Q(rmsg, ch->m_desc);
return ;
}
if (ch->m_Exped == NULL)
{
//에러: 원정대에 소속 되어 있지 않음
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_NOT_EXPED);
SEND_Q(rmsg, ch->m_desc);
return ;
}
if(ch->m_Exped->GetMemberCount() >= MAX_EXPED_MEMBER)
{
//에러: 더 이상 원정대원 추가할 수 없음
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_FULL_EXPED);
SEND_Q(rmsg, ch->m_desc);
return ;
}
if(ch->IsSetPlayerState(PLAYER_STATE_PKMODE) || pTargetPC->IsSetPlayerState(PLAYER_STATE_PKMODE))
{
return ;
}
//권한 체크
//-->
CExpedMember* pMember = NULL;
pMember = (CExpedMember*) ch->m_Exped->GetMemberByCharIndex(ch->m_index);
if(!pMember)
return;
if(pMember && ((pMember->GetMemberType() != MSG_EXPED_MEMBERTYPE_BOSS) && (pMember->GetMemberType() != MSG_EXPED_MEMBERTYPE_MBOSS)) )
{
//에러: 권한 실패
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_NOT_EXPEDBOSS);
SEND_Q(rmsg, ch->m_desc);
return;
}
//<--
if(pTargetPC->m_Exped && ch->m_Exped != pTargetPC->m_Exped)
{
//에러: 이미 원정대에 소속되어 있습니다.
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_ALREADY_JOIN_ME);
SEND_Q(rmsg, ch->m_desc);
return;
}
CPC* pBossPC = ch;
// 요청 캐릭터가 부대장이면 원정대장 찾아서 pBossPC에 대입
if (pMember->GetMemberType() == MSG_EXPED_MEMBERTYPE_MBOSS)
{
int nBossIndex = ch->m_Exped->GetBossIndex();
pBossPC = PCManager::instance()->getPlayerByCharIndex(nBossIndex);
if( !pBossPC )
{
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_NOT_EXPEDBOSS);
SEND_Q(rmsg, ch->m_desc);
return;
}
}
{
CNetMsg::SP rmsg(new CNetMsg);
HelperExpedInviteReqMsg(rmsg, pBossPC->m_index, pBossPC->GetName(), destindex,pTargetPC->GetName());
SEND_Q(rmsg, gserver->m_helper);
}
}
//초대 수락(모두)
void do_ExpedAllowReq(CPC* ch, CNetMsg::SP& msg)
{
// 원정대 정보가 있고
GAMELOG << init("EXPED DEBUG ALLOW REQ", ch)
<< end;
if(ch->m_Exped == NULL)
{
//에러: 원정대에 소속 되어 있지 않음
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_NOT_EXPED);
SEND_Q(rmsg, ch->m_desc);
return;
}
{
CNetMsg::SP rmsg(new CNetMsg);
HelperExpedAllowReqMsg(rmsg, ch->m_Exped->GetBossIndex(), ch->m_index, ch->GetName(), ch->m_level );
SEND_Q(rmsg, gserver->m_helper);
}
{
// 파티 매칭에서 제거
CNetMsg::SP rmsg(new CNetMsg);
rmsg->Init(MSG_EXTEND);
RefMsg(rmsg) << MSG_EX_PARTY_MATCH
<< MSG_EX_PARTY_MATCH_DEL_REQ;
do_Extend(ch, rmsg);
}
}
//초대 거부(모두)
void do_ExpedRejectReq(CPC* ch, CNetMsg::SP& msg)
{
GAMELOG << init("EXPED DEBUG REJECT REQ", ch)
<< end;
if(ch->m_Exped == NULL)
{
//에러: 원정대에 소속 되어 있지 않음
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_NOT_EXPED);
SEND_Q(rmsg, ch->m_desc);
return;
}
CNetMsg::SP rmsg(new CNetMsg);
HelperExpedRejectReqMsg(rmsg, ch->m_Exped->GetBossIndex(), ch->m_index);
SEND_Q(rmsg, gserver->m_helper);
}
//탈퇴(모두)
void do_ExpedQuitReq(CPC* ch, CNetMsg::SP& msg)
{
int nQuitMode; // 정상,비정상 구분
RefMsg(msg) >> nQuitMode;
GAMELOG << init("EXPED DEBUG QUIT REQ", ch)
<< "QUITMODE" << delim << nQuitMode
<< end;
if(ch->m_Exped == NULL)
{
//에러: 원정대에 소속 되어 있지 않음
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_NOT_EXPED);
SEND_Q(rmsg, ch->m_desc);
return;
}
{
CNetMsg::SP rmsg(new CNetMsg);
HelperExpedQuitReqMsg(rmsg, ch->m_Exped->GetBossIndex(), ch->m_index, nQuitMode);
SEND_Q(rmsg, gserver->m_helper);
}
}
//원정대 해체(대장)(20초 대기)
void do_ExpedEndExpedReq(CPC* ch, CNetMsg::SP& msg)
{
GAMELOG << init("EXPED DEBUG ENDEXPED REQ", ch)
<< end;
if (ch->m_Exped == NULL)
{
//에러: 원정대에 소속 되어 있지 않음
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_NOT_EXPED);
SEND_Q(rmsg, ch->m_desc);
return;
}
//권한 체크
//-->
CExpedMember* pMember = NULL;
pMember = (CExpedMember*) ch->m_Exped->GetMemberByCharIndex(ch->m_index);
if(!pMember)
return;
if(pMember && (pMember->GetMemberType() != MSG_EXPED_MEMBERTYPE_BOSS))
{
//에러: 권한 실패
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_NOT_EXPEDBOSS);
SEND_Q(rmsg, ch->m_desc);
return;
}
//<--
// 원정대 해체 시간 설정
//-->
time_t t_now;
t_now = time(NULL);
ch->m_Exped->SetEndExpedTime(t_now);
//<--
{
// 원정대원 전체에게 20초 후에 해체 됨 알림
CNetMsg::SP rmsg(new CNetMsg);
ExpedEndExpedStartMsg(rmsg);
ch->m_Exped->SendToAllPC(rmsg);
}
}
//추방(대장,부대장)
void do_ExpedKickReq(CPC* ch, CNetMsg::SP& msg)
{
int nTargetIndex;
RefMsg(msg) >> nTargetIndex;
GAMELOG << init("EXPED DEBUG KICK REQ", ch)
<< "TARGETINDEX" << delim << nTargetIndex
<< end;
if (ch->m_Exped == NULL)
{
//에러: 원정대에 소속 되어 있지 않음
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_NOT_EXPED);
SEND_Q(rmsg, ch->m_desc);
return;
}
if (ch->m_index == nTargetIndex)
return ;
//권한 체크
//-->
CExpedMember* pMember = NULL;
pMember = (CExpedMember*) ch->m_Exped->GetMemberByCharIndex(ch->m_index);
if(!pMember)
return;
if(pMember && (pMember->GetMemberType() != MSG_EXPED_MEMBERTYPE_BOSS && pMember->GetMemberType() != MSG_EXPED_MEMBERTYPE_MBOSS ))
{
//에러: 권한 실패
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_NOT_EXPEDBOSS);
SEND_Q(rmsg, ch->m_desc);
return;
}
if(ch->m_Exped->GetBossIndex() == nTargetIndex)
{
//에러: 권한 실패
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_NOT_EXPEDBOSS);
SEND_Q(rmsg, ch->m_desc);
return;
}
{
CNetMsg::SP rmsg(new CNetMsg);
HelperExpedKickReqMsg(rmsg, ch->m_Exped->GetBossIndex(), nTargetIndex);
SEND_Q(rmsg, gserver->m_helper);
}
}
//원정 대장 위임(대장)
void do_ExpedChangeBossReq(CPC* ch, CNetMsg::SP& msg)
{
int nChangeMode, nNewBossIndex;
RefMsg(msg) >> nChangeMode // 수동,자동
>> nNewBossIndex; // 자동(-1)
GAMELOG << init("EXPED DEBUG CHANGEBOSS REQ", ch)
<< "CHANGEMODE" << delim << nChangeMode << delim
<< "NEWBOSSINDEX" << delim << nNewBossIndex << delim
<< end;
if (ch->m_Exped == NULL)
{
//에러: 원정대에 소속 되어 있지 않음
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_NOT_EXPED);
SEND_Q(rmsg, ch->m_desc);
return;
}
//권한 체크
//-->
CExpedMember* pMember = NULL;
pMember = (CExpedMember*) ch->m_Exped->GetMemberByCharIndex(ch->m_index);
if(!pMember)
return;
if(pMember && (pMember->GetMemberType() != MSG_EXPED_MEMBERTYPE_BOSS))
{
//에러: 권한 실패
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_NOT_EXPEDBOSS);
SEND_Q(rmsg, ch->m_desc);
return;
}
//<--
//자기 자신 위임 체크
if(ch->m_index == nNewBossIndex)
return;
{
CNetMsg::SP rmsg(new CNetMsg);
HelperExpedChangeBossReqMsg(rmsg, ch->m_index, nChangeMode, nNewBossIndex);
SEND_Q(rmsg, gserver->m_helper);
}
}
//타입 변경(대장)
void do_ExpedChangeTypeReq(CPC* ch, CNetMsg::SP& msg)
{
char cExpedType, cDiviType;
RefMsg(msg) >> cExpedType
>> cDiviType;
GAMELOG << init("EXPED DEBUG CHANGETYPE REQ", ch)
<< "EXPEDTYPE" << delim << cExpedType << delim
<< "DIVITYPE" << delim << cDiviType << delim
<< end;
if (ch->m_Exped == NULL)
{
//에러: 원정대에 소속 되어 있지 않음
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_NOT_EXPED);
SEND_Q(rmsg, ch->m_desc);
return;
}
//권한 체크
//-->
CExpedMember* pMember = NULL;
pMember = (CExpedMember*) ch->m_Exped->GetMemberByCharIndex(ch->m_index);
if(!pMember)
return;
if(pMember && (pMember->GetMemberType() != MSG_EXPED_MEMBERTYPE_BOSS))
{
//에러: 권한 실패
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_NOT_EXPEDBOSS);
SEND_Q(rmsg, ch->m_desc);
return;
}
//<--
if(ch->m_Exped->GetExpedType(cDiviType) == cExpedType)
return ;
{
CNetMsg::SP rmsg(new CNetMsg);
HelperExpedChangeTypeReqMsg(rmsg, ch->m_index, cExpedType, cDiviType);
SEND_Q(rmsg, gserver->m_helper);
}
}
//부대장 임명(대장)
void do_ExpedSetMBossReq(CPC* ch, CNetMsg::SP& msg)
{
int nNewMBossIndex;
RefMsg(msg) >> nNewMBossIndex;
GAMELOG << init("EXPED DEBUG SETMBOSS REQ", ch)
<< "NEW MBOSS INDEX" << delim << nNewMBossIndex
<< end;
if (ch->m_Exped == NULL)
{
//에러: 원정대에 소속 되어 있지 않음
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_NOT_EXPED);
SEND_Q(rmsg, ch->m_desc);
return;
}
//권한 체크
//-->
CExpedMember* pMember = NULL;
pMember = (CExpedMember*) ch->m_Exped->GetMemberByCharIndex(ch->m_index);
if(!pMember)
return;
if(pMember && (pMember->GetMemberType() != MSG_EXPED_MEMBERTYPE_BOSS))
{
//에러: 권한 실패
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_NOT_EXPEDBOSS);
SEND_Q(rmsg, ch->m_desc);
return;
}
//<--
{
CNetMsg::SP rmsg(new CNetMsg);
HelperExpedSetMBossReqMsg(rmsg, ch->m_index, nNewMBossIndex);
SEND_Q(rmsg, gserver->m_helper);
}
}
//부대장 해임(대장)
void do_ExpedResetMBossReq(CPC* ch, CNetMsg::SP& msg)
{
int nNewMBossIndex;
RefMsg(msg) >> nNewMBossIndex;
GAMELOG << init("EXPED DEBUG RESETMBOSS REQ", ch)
<< "NEW MBOSS INDEX" << delim << nNewMBossIndex
<< end;
if (ch->m_Exped == NULL)
{
//에러: 원정대에 소속 되어 있지 않음
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_NOT_EXPED);
SEND_Q(rmsg, ch->m_desc);
return;
}
//권한 체크
//-->
CExpedMember* pMember = NULL;
pMember = (CExpedMember*) ch->m_Exped->GetMemberByCharIndex(ch->m_index);
if(!pMember)
return;
if(pMember && (pMember->GetMemberType() != MSG_EXPED_MEMBERTYPE_BOSS))
{
//에러: 권한 실패
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_NOT_EXPEDBOSS);
SEND_Q(rmsg, ch->m_desc);
return;
}
//<--
{
CNetMsg::SP rmsg(new CNetMsg);
HelperExpedResetMBossReqMsg(rmsg, ch->m_index, nNewMBossIndex);
SEND_Q(rmsg, gserver->m_helper);
}
}
//그룹 이동(대장)
void do_ExpedMoveGroupReq(CPC* ch, CNetMsg::SP& msg)
{
int nSourceGroup, nMoveCharIndex, nTargetGroup, nTargetListindex;
RefMsg(msg) >> nSourceGroup
>> nMoveCharIndex
>> nTargetGroup
>> nTargetListindex;
GAMELOG << init("EXPED DEBUG MOVEGROUP REQ", ch)
<< "SOURCE GROUP" << delim << nMoveCharIndex << delim
<< "MOVE CHAR INDEX" << delim << nMoveCharIndex << delim
<< "TARGET GROUP" << delim << nTargetGroup << delim
<< "TARGET CHAR INDEX" << delim << nTargetListindex
<< end;
if (ch->m_Exped == NULL)
{
//에러: 원정대에 소속 되어 있지 않음
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_NOT_EXPED);
SEND_Q(rmsg, ch->m_desc);
return;
}
//권한 체크
//-->
CExpedMember* pMember = NULL;
pMember = (CExpedMember*) ch->m_Exped->GetMemberByCharIndex(ch->m_index);
if(!pMember)
return;
if(pMember && (pMember->GetMemberType() != MSG_EXPED_MEMBERTYPE_BOSS))
{
//에러: 권한 실패
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_NOT_EXPEDBOSS);
SEND_Q(rmsg, ch->m_desc);
return;
}
//<--
//이동 대상 권한 체크
//-->
pMember = (CExpedMember*) ch->m_Exped->GetMemberByCharIndex(nMoveCharIndex);
if(!pMember)
return;
if(pMember && (pMember->GetMemberType() == MSG_EXPED_MEMBERTYPE_BOSS || (pMember->GetMemberType() == MSG_EXPED_MEMBERTYPE_MBOSS)))
{
//에러: 원정대장, 부대장 이동 불가
return;
}
//<--
// 대상이 비어 있는지 체크
pMember = (CExpedMember*) ch->m_Exped->GetMemberByListIndex(nTargetGroup, nTargetListindex);
if(pMember)
{
//에러: 비어 있지 않음
return;
}
{
CNetMsg::SP rmsg(new CNetMsg);
HelperExpedMoveGroupReqMsg(rmsg, ch->m_index, nSourceGroup, nMoveCharIndex, nTargetGroup, nTargetListindex);
SEND_Q(rmsg, gserver->m_helper);
}
}
//대원 추가(대장)
void do_ExpedAddMemberReq(CPC* ch, CNetMsg::SP& msg)
{
CLCString addCharName(MAX_CHAR_NAME_LENGTH + 1);
RefMsg(msg) >> addCharName;
GAMELOG << init("EXPED DEBUG ADDMEMBER REQ", ch)
<< "ADDCHARNAME" << delim << addCharName
<< end;
CPC * pTargetPC = PCManager::instance()->getPlayerByName(addCharName,false);
if(pTargetPC == NULL)
return;
if(ch->m_Exped == NULL)
{
//에러: 원정대에 소속 되어 있지 않음
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_NOT_EXPED);
SEND_Q(rmsg, ch->m_desc);
return;
}
//권한 체크
//-->
CExpedMember* pMember = NULL;
pMember = (CExpedMember*) ch->m_Exped->GetMemberByCharIndex(ch->m_index);
if(!pMember)
return;
if(pMember && (pMember->GetMemberType() != MSG_EXPED_MEMBERTYPE_BOSS))
{
//에러: 권한 실패
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_NOT_EXPEDBOSS);
SEND_Q(rmsg, ch->m_desc);
return;
}
//<--
// 타입이 EXPED_TYPE_BATTLE 이면 tch와 ch의 레벨 차이를 검사
// 차이가 +- 10이상이면 ERROR;
if (ch->m_Exped->GetExpedType(MSG_DIVITYPE_EXP) == MSG_EXPED_TYPE_BATTLE)
{
if (ABS(pTargetPC->m_level - ch->m_level) > 10)
{
return ;
}
}
{
//초대 요청
CNetMsg::SP rmsg(new CNetMsg);
HelperExpedInviteReqMsg(rmsg, ch->m_index, ch->GetName(), pTargetPC->m_index,pTargetPC->GetName());
SEND_Q(rmsg, gserver->m_helper);
}
}
//살펴 보기(대장,부대장)
void do_ExpedViewDetailReq(CPC* ch, CNetMsg::SP& msg)
{
int nGroup;
int nDestIndex;
RefMsg(msg) >> nGroup
>> nDestIndex;
GAMELOG << init("EXPED DEBUG VIEWDETAIL REQ", ch)
<< "GROUP" << delim << nGroup << delim
<< "DEST INDEX" << delim << nDestIndex
<< end;
if(ch->m_Exped == NULL)
{
//에러: 원정대에 소속 되어 있지 않음
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_NOT_EXPED);
SEND_Q(rmsg, ch->m_desc);
return;
}
//권한 체크
//-->
CExpedMember* pMember = NULL;
pMember = (CExpedMember*) ch->m_Exped->GetMemberByCharIndex(ch->m_index);
if(!pMember)
return;
if(pMember && (pMember->GetMemberType() != MSG_EXPED_MEMBERTYPE_BOSS && pMember->GetMemberType() != MSG_EXPED_MEMBERTYPE_MBOSS ))
{
//에러: 권한 실패
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_NOT_EXPEDBOSS);
SEND_Q(rmsg, ch->m_desc);
return;
}
//<--
CPC * pPC = PCManager::instance()->getPlayerByCharIndex(nDestIndex);
if(pPC == NULL)
return;
// 펫정보
//-->
CPet* pet = pPC->m_petList;
while (pet)
{
if(pet->IsWearing())
{
CNetMsg::SP rmsg(new CNetMsg);
ExpedViewDail_ExPetMsg(rmsg, pet);
SEND_Q(rmsg, ch->m_desc);
}
pet = pet->m_nextPet;
}
CAPet* apet = pPC->m_pApetlist;
while ( apet )
{
if(apet->IsWearing())
{
CNetMsg::SP rmsg(new CNetMsg);
ExpedViewDail_ExAPetMsg(rmsg, apet);
SEND_Q(rmsg, ch->m_desc);
}
apet = apet->m_pNextPet;
}
{
//인벤토리 정보
CNetMsg::SP rmsg(new CNetMsg);
ExpedViewDail_InvenMsg(msg, pPC);
SEND_Q(msg, ch->m_desc);
}
}
//표식 설정
void do_ExpedSetLabelReq(CPC* ch, CNetMsg::SP& msg)
{
int nType,nMode,nLabel,nDestIndex;
RefMsg(msg) >> nType // pc,npc 구분
>> nMode // 설정,해제 구분
>> nLabel // 라벨 타입
>> nDestIndex; // 설정 대상 인덱스(charindex,mob index)
GAMELOG << init("EXPED DEBUG SETLABEL REQ", ch)
<< "TYPE" << delim << nType << delim
<< "MODE" << delim << nMode << delim
<< "LABEL" << delim << nLabel << delim
<< "DESTINDEX" << delim << nDestIndex
<< end;
if(!ch->IsExped())
{
//에러: 원정대에 소속 되어 있지 않음
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_NOT_EXPED);
SEND_Q(rmsg, ch->m_desc);
return;
}
if(ch->m_nJoinInzone_ZoneNo == -1 && ch->m_nJoinInzone_RoomNo == -1)
{
// 인존 내부가 아니어서 표식 설정 불가.
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_SETLABEL_NOTINZONE);
SEND_Q(rmsg, ch->m_desc);
return;
}
if(nType == MSG_EXPED_SETLABEL_TYPE_NPC)
{
CArea* area = ch->m_pArea;
if(!area) return;
CCharacter* tch = area->FindCharInCell(ch, nDestIndex, (MSG_CHAR_TYPE)MSG_CHAR_NPC);
if(tch == NULL || !IS_NPC(tch)) return;
if(nMode == MSG_EXPED_SETLABEL_MODE_SET)
{
tch->SetExpedLabel(nLabel);
}
else if(nMode == MSG_EXPED_SETLABEL_MODE_RESET)
{
tch->SetExpedLabel(-1);
}
}
else if(nType == MSG_EXPED_SETLABEL_TYPE_PC)
{
CArea* area = ch->m_pArea;
if(!area) return;
CCharacter* tch = area->FindCharInCell(ch, nDestIndex, (MSG_CHAR_TYPE)MSG_CHAR_PC);
if(tch == NULL || !IS_PC(tch)) return;
if(nMode == MSG_EXPED_SETLABEL_MODE_SET)
{
tch->SetExpedLabel(nLabel);
}
else if(nMode == MSG_EXPED_SETLABEL_MODE_RESET)
{
tch->SetExpedLabel(-1);
}
}
{
//성공
CNetMsg::SP rmsg(new CNetMsg);
ExpedSetLabelRepMsg(rmsg, nType,nMode,nLabel,nDestIndex);
ch->m_Exped->SendToAllPC(rmsg);
}
}
// Write : 권상욱
// Date : 20090825
// 이동되지 않은 Trigger Item을 원정대장이 수동으로 가져오기 버튼을 눌러 Item을 가져오는 함수
void do_ExpedSearchItemReq(CPC* ch, CNetMsg::SP& msg) //
{
GAMELOG << init("EXPED DEBUG SEARCH TRIGGER ITEM REQ", ch)
<< "BOSS CHARACTER INDEX" << delim
<< ch->m_index << end;
// 넘어온 케릭터가 NULL인지 확인.
if( ch == NULL )
return ;
// 현재 케릭터가 원정대에 소속되어 있는지 확인
// 원정대에 소속되어 있지 않으면 MSG_EXPED_ERROR_NOT_EXPED 발송
// TODO:
if (ch->m_Exped == NULL)
{
//에러: 원정대에 소속 되어 있지 않음
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_NOT_EXPED);
SEND_Q(rmsg, ch->m_desc);
return ;
}
// 현재 케릭터가 원정대 list에서 원정대장인지 확인
// 원정대장이 아니라면 MSG_EXPED_ERROR_NOT_EXPEDBOSS 발송
// TODO:
CExpedMember* pMember = NULL;
pMember = (CExpedMember*) ch->m_Exped->GetMemberByCharIndex(ch->m_index);
if(!pMember)
return;
if(pMember && (pMember->GetMemberType() != MSG_EXPED_MEMBERTYPE_BOSS))
{
//에러: 권한 실패
CNetMsg::SP rmsg(new CNetMsg);
ExpedErrorMsg(rmsg, MSG_EXPED_ERROR_NOT_EXPEDBOSS);
SEND_Q(rmsg, ch->m_desc);
return;
}
// 원정대원들의 퀘스트 아이템 인벤 조사
pMember = NULL;
bool DidCollect = false; // 한번이라도 Trigger Item을 가져왔으면 TRUE, 아니면 FALSE
bool UsualProcess = true; // 수집 중 비정상적으로 수집 프로세스가 종료될 경우FALSE, 정상적으로 종료될 경우 TRUE;
int GroupNumber = 0; // 한 원정대의 Group을 카운트 하기 위한 변수
int CountMemberEachbyGroup = 0; // 각 그룹당 인원수를 카운트 하기 위한 변수
CPC* FromChar;
CPC* BossChar;
BossChar = ch;
for( GroupNumber = 0; GroupNumber < MAX_EXPED_GROUP; GroupNumber++ )
{
for( CountMemberEachbyGroup = 0; CountMemberEachbyGroup < MAX_EXPED_GMEMBER; CountMemberEachbyGroup++ )
{
pMember = BossChar->m_Exped->GetMemberByListIndex(GroupNumber, CountMemberEachbyGroup); // 보스케릭터에서 갖고 있는 원정대원들을 원정대 리스트에서 뽑음.
if( pMember != NULL && pMember->GetMemberType() != MSG_EXPED_MEMBERTYPE_BOSS ) // 원정대원이 NULL아니고, 원정대장이 아닐때,
{
FromChar = PCManager::instance()->getPlayerByCharIndex(pMember->GetCharIndex()); // 게임서버 플레이어 리스트에서 케릭터 인덱스를 갖고 플레이어 정보를 얻음.
if( FromChar )
SearchTriggerItem(FromChar, BossChar, DidCollect, UsualProcess); // 원정대원이 갖고 있는 Trigger Item을 조사
}
}
}
{
CNetMsg::SP rmsg(new CNetMsg);
if( (DidCollect == true) && (UsualProcess == true) ) // 한개의 아이템이라도 수집이 성공하고, 정상적으로 수집 프로세스가 종료가 되면
{
ExpedSearchTriggerItemMsg(rmsg, MSG_GET_QUESTITEM_SUCCESS_REP); // 수집 성공 메시지 발송
GAMELOG << init("EXPED DEBUG COLLECT TRIGGER ITEM SUCCESS", ch)
<< "BOSS CHARACTER INDEX" << delim
<< ch->m_index << end;
}
else // 그외의 경우
{
// 1. 보스의 퀘스트 인벤이 가득 차있어 가져오고 싶어도 못가져오는 경우
ExpedSearchTriggerItemMsg(rmsg, MSG_GET_QUESTITEM_FAILED_REP); // 2. 시스템적 오류가 생길 경우
GAMELOG << init("EXPED DEBUG COLLECT TRIGGER ITEM FAILED", ch) // 3. 원정대원으로 부터 가져올 Trigger Item이 없을 경우
<< "BOSS CHARACTER INDEX" << delim
<< ch->m_index << end;
}
SEND_Q(rmsg, BossChar->m_desc);
}
}
void SearchTriggerItem(CPC* FromChar, CPC* BossChar, bool& DidCollect, bool& UsualProcess) // 원정대원 TriggerItem 체크
{
item_search_t vec;
FromChar->m_inventory.searchFlagByItemProto(ITEM_FLAG_TRIGGER, vec);
item_search_t::iterator it = vec.begin();
item_search_t::iterator endit = vec.end();
for (; it != endit; ++it)
{
GiveTriggerItemMemberToBoss(FromChar, BossChar, *it, DidCollect, UsualProcess);
}
}
void GiveTriggerItemMemberToBoss(CPC* FromChar, CPC* BossChar, item_search_pair_t& p, bool& DidCollect, bool& UsualProcess)
{
if( !BossChar ) // 원정대장 케릭터가 NULL일 때
{
UsualProcess = false;
return ;
}
CItem* item = p.pItem;
if (item == NULL)
{
UsualProcess = false;
return ;
}
if(item->Count() < 1) // 아이템 개수가 0이하일 때 리턴 false
{
UsualProcess = false;
return ;
}
CItem* bossitem = gserver->m_itemProtoList.CreateItem(item->getDBIndex(), -1, 0, 0, item->getItemCount());
if (BossChar->m_inventory.addItem(bossitem))
{
//성공하면 상대방 인벤토리에서는 제거를 해줘야 한다.
{
FromChar->m_inventory.deleteItemByItem(item);
}
DidCollect = true;
GAMELOG << init("EXPED DEBUG GIVE TRIGGER ITEM SUCCESS") << end;
GAMELOG << init("FROM MEMBER") << delim << FromChar->m_name << delim
<< "CHARACTER INDEX" << delim << FromChar->m_index << end;
GAMELOG << init("TO BOSS") << delim << BossChar->m_name << delim
<< "CHARACTER INDEX" << delim << BossChar->m_index << end;
GAMELOG << init("GIVE ITEM") << bossitem->m_itemProto->getItemName() << bossitem->Count() << "EA" << end;
}
else
{
delete bossitem;
GAMELOG << init("EXPED DEBUG GIVE TRIGGER ITEM FAILED") << end;
GAMELOG << init("FROM MEMBER") << delim << FromChar->m_name << delim
<< "CHARACTER INDEX" << delim << FromChar->m_index << end;
GAMELOG << init("TO BOSS") << delim << BossChar->m_name << delim
<< "CHARACTER INDEX" << delim << BossChar->m_index << end;
GAMELOG << init("GIVE ITEM") << bossitem->m_itemProto->getItemName() << bossitem->Count() << "EA" << end;
UsualProcess = false;
}
}
void do_ExpendOffline(CPC* ch, CNetMsg::SP& msg)
{
if( !ch && ch->m_Exped != NULL )
return;
// 원정대원 로그 아웃 처리
CExpedMember* pMember = NULL;
pMember = (CExpedMember*) ch->m_Exped->GetMemberByCharIndex(ch->m_index);
if(pMember) pMember->m_nLevel = 0;
// 핼퍼로 로그 아웃 처리
{
CNetMsg::SP rmsg(new CNetMsg);
HelperExpendOfflineMsg( rmsg, ch->m_Exped->GetBossIndex() , ch->m_index );
SEND_Q(rmsg, gserver->m_helper);
}
return;
}
| 23.134562 | 134 | 0.668181 | openlastchaos |
5d8715809a52e7adb858b2a4ddd2038afbe1a7f6 | 2,017 | hpp | C++ | include/gridtools/tools/icosahedral_fixture.hpp | aurianer/gridtools | 5f99471bf36215e2a53317d2c7844bf057231ffa | [
"BSD-3-Clause"
] | null | null | null | include/gridtools/tools/icosahedral_fixture.hpp | aurianer/gridtools | 5f99471bf36215e2a53317d2c7844bf057231ffa | [
"BSD-3-Clause"
] | null | null | null | include/gridtools/tools/icosahedral_fixture.hpp | aurianer/gridtools | 5f99471bf36215e2a53317d2c7844bf057231ffa | [
"BSD-3-Clause"
] | null | null | null | /*
* GridTools
*
* Copyright (c) 2014-2019, ETH Zurich
* All rights reserved.
*
* Please, refer to the LICENSE file in the root directory.
* SPDX-License-Identifier: BSD-3-Clause
*/
#pragma once
#include <type_traits>
#include "../storage/builder.hpp"
#include "../storage/sid.hpp"
#include "backend_select.hpp"
#include "grid_fixture.hpp"
namespace gridtools {
namespace icosahedral {
template <size_t Halo, class Axis = axis<1>>
struct computation_fixture : grid_fixture<Halo, Axis> {
using grid_fixture<Halo, Axis>::grid_fixture;
template <class Location, class T = float_type>
auto builder() const {
return storage::builder<storage_traits_t> //
.dimensions(this->d(0), this->d(1), this->k_size(), Location::value) //
.halos(Halo, Halo, 0, 0) //
.template type<T>() //
.template id<Location::value>();
}
template <class Location, class T = float_type>
auto make_storage() const {
return builder<Location, T>().build();
}
template <class Location,
class T = float_type,
class U,
std::enable_if_t<!std::is_convertible<U const &, T>::value, int> = 0>
auto make_storage(U const &arg) const {
return builder<Location, T>().initializer(arg).build();
}
template <class Location,
class T = float_type,
class U,
std::enable_if_t<std::is_convertible<U const &, T>::value, int> = 0>
auto make_storage(U const &arg) const {
return builder<Location, T>().value(arg).build();
}
}; // namespace gridtools
} // namespace icosahedral
} // namespace gridtools
| 35.385965 | 91 | 0.516113 | aurianer |
5d88c96b80469806450e46a561f8053455f8c35c | 410 | hpp | C++ | src/player/human_player.hpp | portatlas/tictactoe-cpp | 2bae6287881f02e8608c5e3cc7d0031724f09dda | [
"MIT"
] | null | null | null | src/player/human_player.hpp | portatlas/tictactoe-cpp | 2bae6287881f02e8608c5e3cc7d0031724f09dda | [
"MIT"
] | null | null | null | src/player/human_player.hpp | portatlas/tictactoe-cpp | 2bae6287881f02e8608c5e3cc7d0031724f09dda | [
"MIT"
] | null | null | null | #ifndef TICTACTOE_CPP_HUMAN_PLAYER_H
#define TICTACTOE_CPP_HUMAN_PLAYER_H
#include "player.hpp"
#include "../console.hpp"
class HumanPlayer : public Player {
public:
HumanPlayer(Rules &rules, Console &console);
int getMove(Board board);
private:
Rules _rules;
Console _console;
int convertStrToInt(std::string input);
};
#endif //TICTACTOE_CPP_HUMAN_PLAYER_H
| 22.777778 | 52 | 0.702439 | portatlas |
5d8b2401a35f5f855a8f5a5067facbb4f7f3a67f | 806 | cc | C++ | projects/Graphics/code/GraphicsNode.cc | Destinum/S0009D | 52d73f774a85da87eb57c34385df8e1ae86b2ec5 | [
"MIT"
] | null | null | null | projects/Graphics/code/GraphicsNode.cc | Destinum/S0009D | 52d73f774a85da87eb57c34385df8e1ae86b2ec5 | [
"MIT"
] | null | null | null | projects/Graphics/code/GraphicsNode.cc | Destinum/S0009D | 52d73f774a85da87eb57c34385df8e1ae86b2ec5 | [
"MIT"
] | null | null | null | #include "Resources.h"
void GraphicsNode::Draw(Matrix3D MVP, Vector3D CameraPosition)
{
glUseProgram(this->Shaders.program);
glUniformMatrix4fv(this->Shaders.MatrixID, 1, GL_FALSE, &(MVP).matris[0][0]);
glUniform4f(this->Shaders.CameraID, CameraPosition.vektor[0], CameraPosition.vektor[1], CameraPosition.vektor[2], 1.0);
glUniformMatrix4fv(this->TransformationID, 1, GL_FALSE, &(this->TransformationMatrix).matris[0][0]);
if (this->Texture.TheTexture != 0)
this->Texture.BindTexture();
this->Mesh.Render();
}
void GraphicsNode::AddTransform(Vector3D Transform)
{
this->TransformationMatrix.matris[3][0] += Transform.vektor[0];
this->TransformationMatrix.matris[3][1] += Transform.vektor[1];
this->TransformationMatrix.matris[3][2] += Transform.vektor[2];
} | 38.380952 | 123 | 0.719603 | Destinum |
5d8dc781beda24bfd3f4c18d6752b05b1d32fdae | 3,583 | cpp | C++ | source/Pancake.cpp | Dante12129/Pancake | 35282814e2f3b2d5e155a539ca5ddee32e240d3e | [
"Zlib"
] | null | null | null | source/Pancake.cpp | Dante12129/Pancake | 35282814e2f3b2d5e155a539ca5ddee32e240d3e | [
"Zlib"
] | null | null | null | source/Pancake.cpp | Dante12129/Pancake | 35282814e2f3b2d5e155a539ca5ddee32e240d3e | [
"Zlib"
] | null | null | null | #include "include/Pancake/Pancake.hpp"
#include <iostream>
#include <SDL2/SDL.h>
#include <SDL2/SDL_events.h>
#include <SDL2/SDL_filesystem.h>
#include <SDL2/SDL_video.h>
#include <SDL2/SDL_ttf.h>
#include <glload/gl_load.h>
#include "include/Pancake/Window/Context.hpp"
#include "include/Pancake/Window/Window.hpp"
namespace pcke
{
Pancake::Pancake()
{
//Initialize SDL
if(SDL_Init(SDL_INIT_VIDEO))
{
std::cerr << "SDL couldn't be initialized: " << SDL_GetError() << std::endl;
}
//Initialize SDL_ttf
if(TTF_Init())
{
std::cerr << "SDL_ttf couldn't be initialized: " << TTF_GetError() << std::endl;
}
//Create dummy window and context for OpenGL
Window dummy_window("", 0, 0, WindowSettings::OpenGL | WindowSettings::Hidden);
//Initialize OpenGL
if(ogl_LoadFunctions() == ogl_LOAD_FAILED)
{
std::cerr << "OpenGL functions unable to be loaded." << std::endl;
}
//Check the OpenGL version
if(!ogl_IsVersionGEQ(3, 3))
{
std::cerr << "OpenGL is not at least version 3.3; some functionality may not work." << std::endl;
}
}
Pancake::Pancake(int major, int minor)
{
//Initialize SDL
if(SDL_Init(SDL_INIT_VIDEO))
std::cerr << "SDL couldn't be initialized." << std::endl;
//Create dummy window for OpenGL
auto dummy_window = SDL_CreateWindow("", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 0, 0, SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN);
//Set the context settings
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, major);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, minor);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
#ifdef PCKE_DEBUG
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
#endif //PCKE_DEBUG
//Create the context
auto dummy_context = SDL_GL_CreateContext(dummy_window);
//Check for errors
if(!dummy_context)
{
std::cerr << "Error creating OpenGL context: " << SDL_GetError() << std::endl;
}
//Initialize OpenGL
if(ogl_LoadFunctions() == ogl_LOAD_FAILED)
std::cerr << "OpenGL functions unable to be loaded." << std::endl;
//Destroy the dummy window, as it's not needed
SDL_GL_DeleteContext(dummy_context);
SDL_DestroyWindow(dummy_window);
}
Pancake::~Pancake()
{
//Shutdown SDL and its extensions
SDL_Quit();
TTF_Quit();
}
int Pancake::getMajorVersion()
{
return ogl_GetMajorVersion();
}
int Pancake::getMinorVersion()
{
return ogl_GetMinorVersion();
}
bool Pancake::pollEvents(SDL_Event& event)
{
return SDL_PollEvent(&event);
}
void Pancake::setApplicationName(const std::string& name)
{
application_ = name;
}
void Pancake::setOrganizationName(const std::string& name)
{
organization_ = name;
}
const std::string& Pancake::getApplicationName() const
{
return application_;
}
const std::string& Pancake::getOrganizationName() const
{
return organization_;
}
std::string Pancake::getBasePath() const
{
return SDL_GetBasePath();
}
std::string Pancake::getDataPath() const
{
return SDL_GetPrefPath(organization_.c_str(), application_.c_str());
}
}
| 27.775194 | 144 | 0.619872 | Dante12129 |
5d8e236686a57ad6a0f360675629d40efd52ca18 | 611 | cpp | C++ | Challenge-2021-09/19_distinct_subsequences.cpp | qiufengyu/LetsCode | 196fae0bf5c78ee20d05798a9439596e702fdb24 | [
"MIT"
] | null | null | null | Challenge-2021-09/19_distinct_subsequences.cpp | qiufengyu/LetsCode | 196fae0bf5c78ee20d05798a9439596e702fdb24 | [
"MIT"
] | null | null | null | Challenge-2021-09/19_distinct_subsequences.cpp | qiufengyu/LetsCode | 196fae0bf5c78ee20d05798a9439596e702fdb24 | [
"MIT"
] | null | null | null | #include "../header.h"
class Solution {
public:
int numDistinct(string s, string t) {
int ss = s.size(), ts = t.size();
vector<vector<unsigned>> dp(ts + 1, vector<unsigned>(ss + 1, 0));
for (int i = 0; i <= ss; ++i) {
dp[0][i] = 1;
}
for (int i = 1; i <= ts; ++i) {
for (int j = 1; j <= ss; ++j) {
dp[i][j] = dp[i][j-1] + ((s[j-1] == t[i-1]) ? dp[i-1][j-1] : 0L);
}
}
return dp[ts][ss];
}
};
int main() {
cout << Solution().numDistinct("rabbbit", "rabbit") << endl;
return 0;
} | 26.565217 | 81 | 0.410802 | qiufengyu |
5d9757086a9a32b7d1f0db9546b1020c3e0ecac7 | 2,890 | cpp | C++ | src/cpp/admin.cpp | yesleekm/capstone_xu4 | da42dcef3772946bff83cffe98c5d648b212ecae | [
"Beerware"
] | null | null | null | src/cpp/admin.cpp | yesleekm/capstone_xu4 | da42dcef3772946bff83cffe98c5d648b212ecae | [
"Beerware"
] | null | null | null | src/cpp/admin.cpp | yesleekm/capstone_xu4 | da42dcef3772946bff83cffe98c5d648b212ecae | [
"Beerware"
] | null | null | null | #include "admin.hpp"
config_data::config_data () {
this->prev_flag = ADMIN_MODE;
this->confThreshold = 0.4;
this->nmsThreshold = 0.5;
this->read_admin_input();
}
/* Returns true when the server has to be reset with config data. */
bool
config_data::sync (bool is_first_call = false) {
int now_flag = read_mode_flag();
ASSERT (now_flag != -1);
if (prev_flag == ADMIN_MODE && now_flag == BASIC_MODE) {
// printf ("prev_flag == ADMIN && now_flag == BASIC\n");
this->read_admin_input();
if (!is_first_call)
this->read_ovlaps();
prev_flag = now_flag;
return true;
}
else if (prev_flag == ADMIN_MODE && now_flag == ADMIN_MODE) {
// printf ("prev_flag == ADMIN && now_flag == ADMIN\n");
return false;
}
else if (prev_flag == BASIC_MODE && now_flag == ADMIN_MODE) {
// printf ("prev_flag == BASIC && now_flag == ADMIN\n");
prev_flag = now_flag;
return false;
}
else if (prev_flag == BASIC_MODE && now_flag == BASIC_MODE) {
// printf ("prev_flag == BASIC && now_flag == BASIC\n");
return false;
}
else {
return -1;
}
}
int
config_data::read_mode_flag () {
char buf[20];
const char* path = (CONFIG_PATH + "/mode.txt").c_str();
FILE* fp = fopen (path, "r");
ASSERT (fp != NULL);
fgets (buf, sizeof(buf), fp);
fclose (fp);
string str (buf);
if (str == "admin\n" || str == "admin")
return ADMIN_MODE;
else if (str == "basic\n" || str == "basic")
return BASIC_MODE;
else
return -1;
}
void
config_data::read_admin_input () {
/* 주어진 경로로부터 텍스트파일을 읽어서 모든 멤버변수에 저장하기 */
char buf[20];
FILE* fp;
// Read admin_input.txt
const char* path = (CONFIG_PATH + "/admin_input.txt").c_str();
fp = fopen (path, "r");
fgets(buf, sizeof(buf), fp);
this->camera_number = atoi(buf);
printf (" reading camera number=%d\n", this->camera_number);
fgets(buf, sizeof(buf), fp);
this->capture_res_width = atoi(buf);
fgets(buf, sizeof(buf), fp);
this->capture_res_height = atoi(buf);
fgets(buf, sizeof(buf), fp);
this->resize_res_width = atoi(buf);
fgets(buf, sizeof(buf), fp);
this->resize_res_height = atoi(buf);
fclose (fp);
// ROI.txt 파일 여기에서 읽는 기능 추가해야함
}
void
config_data::read_ovlaps () {
char buf[20];
FILE* fp;
const char* path = (CONFIG_PATH + "/ROI.txt").c_str();
fp = fopen (path, "r");
for (int i=0; i<this->camera_number; i++) {
fgets(buf, sizeof(buf), fp);
char* ptr = strtok (buf, " ");
while (ptr != NULL) {
this->ovlaps[i].push_back (atoi(ptr));
ptr = strtok (NULL, " ");
}
}
fclose (fp);
} | 28.9 | 69 | 0.545329 | yesleekm |
4b6929bd41bb2a9c19a6dc604b9aa240a9fcbd54 | 2,505 | cc | C++ | src/client/client_storage.cc | ProtaX/ptx-chat | 810877793136427885ee036c54e7eeea5daee388 | [
"BSL-1.0"
] | 1 | 2021-02-13T16:27:01.000Z | 2021-02-13T16:27:01.000Z | src/client/client_storage.cc | ProtaX/ptx-chat | 810877793136427885ee036c54e7eeea5daee388 | [
"BSL-1.0"
] | null | null | null | src/client/client_storage.cc | ProtaX/ptx-chat | 810877793136427885ee036c54e7eeea5daee388 | [
"BSL-1.0"
] | null | null | null | #include "client_storage.h"
#include <cstdint>
#include <iostream>
#include <vector>
#include <bsoncxx/json.hpp>
#include <mongocxx/stdx.hpp>
#include <mongocxx/uri.hpp>
#include <bsoncxx/builder/stream/helpers.hpp>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/builder/stream/array.hpp>
using bsoncxx::builder::stream::close_array;
using bsoncxx::builder::stream::close_document;
using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::finalize;
using bsoncxx::builder::stream::open_array;
using bsoncxx::builder::stream::open_document;
namespace ptxchat {
ClientStorage::ClientStorage() {
}
std::vector<std::shared_ptr<ChatMsg>> ClientStorage::GetPublicMsgs() {
std::vector<std::shared_ptr<ChatMsg>> res{};
if (!isConnected)
return res;
auto cursor = msg_coll_->find({});
for (auto doc : cursor) {
auto msg = GetMsgFromDoc(doc);
if (msg) {
if (msg->hdr.type == MsgType::PUBLIC_DATA)
res.push_back(msg);
}
}
return res;
}
std::vector<std::shared_ptr<ChatMsg>> ClientStorage::GetPrivateMsgs(const std::string& nick) {
std::vector<std::shared_ptr<ChatMsg>> res{};
if (!isConnected)
return res;
auto cursor = msg_coll_->find({});
for (auto doc : cursor) {
auto msg = GetMsgFromDoc(doc);
if (msg) {
if (msg->hdr.type == MsgType::PRIVATE_DATA &&
!strcmp(msg->hdr.to, nick.data())) {
res.push_back(msg);
}
}
}
return res;
}
std::shared_ptr<ChatMsg> ClientStorage::GetMsgFromDoc(bsoncxx::v_noabi::document::view v) {
auto msg = std::make_shared<ChatMsg>();
auto from = v.find("From");
if (from == v.end())
return nullptr;
strcpy(msg->hdr.from, from->get_string().value.data());
auto to = v.find("To");
if (to != v.end())
strcpy(msg->hdr.to, to->get_string().value.data());
auto src_ip = v.find("IP");
if (src_ip == v.end())
return nullptr;
msg->hdr.src_ip = src_ip->get_int32();
auto src_port = v.find("Port");
if (src_port == v.end())
return nullptr;
msg->hdr.src_port = src_port->get_int32();
auto type = v.find("Type");
if (type == v.end())
return nullptr;
msg->hdr.type = (MsgType)(int)type->get_int32();
auto data = v.find("Data");
if (data != v.end()) {
msg->hdr.buf_len = data->length();
msg->buf = (uint8_t*)malloc(msg->hdr.buf_len);
memcpy(msg->buf, data->get_string().value.data(), msg->hdr.buf_len);
}
return msg;
}
ClientStorage::~ClientStorage() {
}
} // namespace ptxchat
| 25.561224 | 94 | 0.652295 | ProtaX |
4b69408d9788ff6d9fbcb76d3285d15fb1b608a5 | 29,355 | cc | C++ | ogrspatialreference.cc | martinwilkerson-scisys/php5-gdal | 99df2fe8182f1711ac742930882c221e2dd5b5e9 | [
"MIT"
] | 7 | 2015-01-07T16:39:43.000Z | 2022-03-12T19:18:48.000Z | ogrspatialreference.cc | martinwilkerson-scisys/php5-gdal | 99df2fe8182f1711ac742930882c221e2dd5b5e9 | [
"MIT"
] | 2 | 2015-10-28T03:21:32.000Z | 2017-04-06T13:10:33.000Z | ogrspatialreference.cc | martinwilkerson-scisys/php5-gdal | 99df2fe8182f1711ac742930882c221e2dd5b5e9 | [
"MIT"
] | 7 | 2015-03-23T20:52:46.000Z | 2021-03-24T21:41:17.000Z | //
// ogrspatialreference.cc
//
//
// Copyright (c) 2011, JF Gigand
//
// 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 "php.h"
#include "php_gdal.h"
#include <ogr_spatialref.h>
#include "ogrspatialreference.h"
zend_class_entry *gdal_ogrspatialreference_ce;
zend_object_handlers ogrspatialreference_object_handlers;
//
// PHP stuff
//
void ogrspatialreference_free_storage(void *object TSRMLS_DC)
{
php_ogrspatialreference_object *obj = (php_ogrspatialreference_object *)object;
// TODO: check ownership
zend_hash_destroy(obj->std.properties);
FREE_HASHTABLE(obj->std.properties);
efree(obj);
}
zend_object_value ogrspatialreference_create_handler(zend_class_entry *type TSRMLS_DC)
{
zval *tmp;
zend_object_value retval;
php_ogrspatialreference_object *obj =
(php_ogrspatialreference_object *)emalloc(sizeof(php_ogrspatialreference_object));
memset(obj, 0, sizeof(php_ogrspatialreference_object));
obj->std.ce = type;
ALLOC_HASHTABLE(obj->std.properties);
zend_hash_init(obj->std.properties, 0, NULL, ZVAL_PTR_DTOR, 0);
#if PHP_VERSION_ID < 50399
zend_hash_copy(obj->std.properties, &type->default_properties,
(copy_ctor_func_t)zval_add_ref, (void *)&tmp, sizeof(zval *));
#else
object_properties_init(&obj->std, type);
#endif
retval.handle = zend_objects_store_put(obj, NULL,
ogrspatialreference_free_storage, NULL TSRMLS_CC);
retval.handlers = &ogrspatialreference_object_handlers;
return retval;
//pdo_stmt_construct(stmt, return_value, dbstmt_ce, ctor_args TSRMLS_CC);
}
//
// CLASS METHODS
//
PHP_METHOD(OGRSpatialReference, __construct)
{
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *obj;
char *wkt = NULL;
int wkt_len;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"|s",
&wkt, &wkt_len) == FAILURE) {
return;
}
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
obj->spatialreference = new OGRSpatialReference(wkt);
}
PHP_METHOD(OGRSpatialReference, Reference)
{
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *obj;
if (ZEND_NUM_ARGS() != 0) {
WRONG_PARAM_COUNT;
}
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
spatialreference = obj->spatialreference;
RETURN_LONG(spatialreference->Reference());
}
PHP_METHOD(OGRSpatialReference, Dereference)
{
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *obj;
if (ZEND_NUM_ARGS() != 0) {
WRONG_PARAM_COUNT;
}
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
spatialreference = obj->spatialreference;
RETURN_LONG(spatialreference->Dereference());
}
PHP_METHOD(OGRSpatialReference, GetReferenceCount)
{
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *obj;
if (ZEND_NUM_ARGS() != 0) {
return;
}
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
spatialreference = obj->spatialreference;
RETURN_LONG(spatialreference->GetReferenceCount());
}
PHP_METHOD(OGRSpatialReference, Release)
{
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *obj;
if (ZEND_NUM_ARGS() != 0) {
return;
}
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
spatialreference = obj->spatialreference;
RETURN_NULL();
}
PHP_METHOD(OGRSpatialReference, Clone)
{
OGRSpatialReference *spatialreference;
OGRSpatialReference *spatialreference_clone;
php_ogrspatialreference_object *obj;
php_ogrspatialreference_object *obj_clone;
if (ZEND_NUM_ARGS() != 0) {
return;
}
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
spatialreference = obj->spatialreference;
spatialreference_clone = spatialreference->Clone();
if (object_init_ex(return_value, gdal_ogrspatialreference_ce) != SUCCESS) {
spatialreference_clone->Release();
RETURN_NULL();
}
obj_clone = (php_ogrspatialreference_object*)
zend_object_store_get_object(return_value TSRMLS_CC);
obj_clone->spatialreference = spatialreference_clone;
}
PHP_METHOD(OGRSpatialReference, CloneGeogCS)
{
OGRSpatialReference *spatialreference;
OGRSpatialReference *spatialreference_clone;
php_ogrspatialreference_object *obj;
php_ogrspatialreference_object *obj_clone;
if (ZEND_NUM_ARGS() != 0) {
return;
}
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
spatialreference = obj->spatialreference;
spatialreference_clone = spatialreference->CloneGeogCS();
if (object_init_ex(return_value, gdal_ogrspatialreference_ce) != SUCCESS) {
spatialreference_clone->Release();
RETURN_NULL();
}
obj_clone = (php_ogrspatialreference_object*)
zend_object_store_get_object(return_value TSRMLS_CC);
obj_clone->spatialreference = spatialreference_clone;
}
PHP_METHOD(OGRSpatialReference, exportToWkt)
{
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *obj;
char *str;
char *ret;
zval *tmp;
int err;
if (ZEND_NUM_ARGS() != 0) {
WRONG_PARAM_COUNT;
}
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
spatialreference = obj->spatialreference;
err = spatialreference->exportToWkt(&str);
if (err == OGRERR_NONE) {
ret = estrdup(str);
OGRFree(str);
RETURN_STRING(ret, 0);
} else {
RETURN_LONG(err);
}
}
PHP_METHOD(OGRSpatialReference, exportToPrettyWkt)
{
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *obj;
zend_bool bSimplify = 0;
char *str;
char *ret;
zval *tmp;
int err;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"|b",
&bSimplify) == FAILURE) {
return;
}
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
spatialreference = obj->spatialreference;
err = spatialreference->exportToPrettyWkt(&str, bSimplify);
if (err == OGRERR_NONE) {
ret = estrdup(str);
OGRFree(str);
RETURN_STRING(ret, 0);
} else {
RETURN_LONG(err);
}
}
PHP_METHOD(OGRSpatialReference, exportToProj4)
{
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *obj;
char *str;
char *ret;
zval *tmp;
int err;
if (ZEND_NUM_ARGS() != 0) {
WRONG_PARAM_COUNT;
}
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
spatialreference = obj->spatialreference;
err = spatialreference->exportToProj4(&str);
if (err == OGRERR_NONE) {
ret = estrdup(str);
OGRFree(str);
RETURN_STRING(ret, 0);
} else {
RETURN_LONG(err);
}
}
PHP_METHOD(OGRSpatialReference, exportToXML)
{
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *obj;
char *str;
char *ret;
zval *tmp;
int err;
if (ZEND_NUM_ARGS() != 0) {
WRONG_PARAM_COUNT;
}
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
spatialreference = obj->spatialreference;
err = spatialreference->exportToXML(&str);
if (err == OGRERR_NONE) {
ret = estrdup(str);
OGRFree(str);
RETURN_STRING(ret, 0);
} else {
RETURN_LONG(err);
}
}
PHP_METHOD(OGRSpatialReference, importFromProj4)
{
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *obj;
char *str;
int str_len;
int err;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"s",
&str, &str_len) == FAILURE) {
return;
}
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
spatialreference = obj->spatialreference;
err = spatialreference->importFromProj4(str);
RETURN_LONG(err);
}
PHP_METHOD(OGRSpatialReference, importFromWkt)
{
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *obj;
char *str;
int str_len;
int err;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"s",
&str, &str_len) == FAILURE) {
return;
}
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
spatialreference = obj->spatialreference;
err = spatialreference->importFromWkt(&str);
RETURN_LONG(err);
}
PHP_METHOD(OGRSpatialReference, importFromEPSG)
{
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *obj;
long code;
int err;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"l",
&code) == FAILURE) {
return;
}
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
spatialreference = obj->spatialreference;
err = spatialreference->importFromEPSG(code);
RETURN_LONG(err);
}
PHP_METHOD(OGRSpatialReference, importFromEPSGA)
{
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *obj;
long code;
int err;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"l",
&code) == FAILURE) {
return;
}
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
spatialreference = obj->spatialreference;
err = spatialreference->importFromEPSGA(code);
RETURN_LONG(err);
}
PHP_METHOD(OGRSpatialReference, Validate)
{
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *obj;
if (ZEND_NUM_ARGS() != 0) {
WRONG_PARAM_COUNT;
}
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
spatialreference = obj->spatialreference;
RETURN_LONG(spatialreference->Validate());
}
PHP_METHOD(OGRSpatialReference, FixupOrdering)
{
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *obj;
if (ZEND_NUM_ARGS() != 0) {
WRONG_PARAM_COUNT;
}
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
spatialreference = obj->spatialreference;
RETURN_LONG(spatialreference->FixupOrdering());
}
PHP_METHOD(OGRSpatialReference, Fixup)
{
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *obj;
if (ZEND_NUM_ARGS() != 0) {
WRONG_PARAM_COUNT;
}
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
spatialreference = obj->spatialreference;
RETURN_LONG(spatialreference->Fixup());
}
PHP_METHOD(OGRSpatialReference, IsGeographic)
{
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *obj;
if (ZEND_NUM_ARGS() != 0) {
WRONG_PARAM_COUNT;
}
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
spatialreference = obj->spatialreference;
RETURN_BOOL(spatialreference->IsGeographic());
}
PHP_METHOD(OGRSpatialReference, IsProjected)
{
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *obj;
if (ZEND_NUM_ARGS() != 0) {
WRONG_PARAM_COUNT;
}
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
spatialreference = obj->spatialreference;
RETURN_BOOL(spatialreference->IsProjected());
}
PHP_METHOD(OGRSpatialReference, IsLocal)
{
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *obj;
if (ZEND_NUM_ARGS() != 0) {
WRONG_PARAM_COUNT;
}
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
spatialreference = obj->spatialreference;
RETURN_BOOL(spatialreference->IsLocal());
}
// PHP_METHOD(OGRSpatialReference, IsVertical)
// {
// OGRSpatialReference *spatialreference;
// php_ogrspatialreference_object *obj;
// if (ZEND_NUM_ARGS() != 0) {
// WRONG_PARAM_COUNT;
// }
// obj = (php_ogrspatialreference_object *)
// zend_object_store_get_object(getThis() TSRMLS_CC);
// spatialreference = obj->spatialreference;
// RETURN_BOOL(spatialreference->IsVertical());
// }
PHP_METHOD(OGRSpatialReference, IsSameGeogCS)
{
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *obj;
zval *poOther_p;
OGRSpatialReference *poOther;
php_ogrspatialreference_object *poOther_obj;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"O",
&poOther_p, gdal_ogrspatialreference_ce)
== FAILURE) {
return;
}
poOther_obj = (php_ogrspatialreference_object*)
zend_object_store_get_object(poOther_p);
poOther = poOther_obj->spatialreference;
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
spatialreference = obj->spatialreference;
RETURN_BOOL(spatialreference->IsSameGeogCS(poOther));
}
PHP_METHOD(OGRSpatialReference, IsSame)
{
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *obj;
zval *poOther_p;
OGRSpatialReference *poOther;
php_ogrspatialreference_object *poOther_obj;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"O",
&poOther_p, gdal_ogrspatialreference_ce)
== FAILURE) {
return;
}
poOther_obj = (php_ogrspatialreference_object*)
zend_object_store_get_object(poOther_p);
poOther = poOther_obj->spatialreference;
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
spatialreference = obj->spatialreference;
RETURN_BOOL(spatialreference->IsSame(poOther));
}
PHP_METHOD(OGRSpatialReference, Clear)
{
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *obj;
if (ZEND_NUM_ARGS() != 0) {
WRONG_PARAM_COUNT;
}
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
spatialreference = obj->spatialreference;
spatialreference->Clear();
}
PHP_METHOD(OGRSpatialReference, SetLocalCS)
{
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *obj;
char *str;
int str_len;
int err;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"s",
&str, &str_len) == FAILURE) {
return;
}
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
spatialreference = obj->spatialreference;
err = spatialreference->SetLocalCS(str);
RETURN_LONG(err);
}
PHP_METHOD(OGRSpatialReference, SetProjCS)
{
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *obj;
char *str;
int str_len;
int err;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"s",
&str, &str_len) == FAILURE) {
return;
}
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
spatialreference = obj->spatialreference;
err = spatialreference->SetProjCS(str);
RETURN_LONG(err);
}
PHP_METHOD(OGRSpatialReference, SetProjection)
{
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *obj;
char *str;
int str_len;
int err;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"s",
&str, &str_len) == FAILURE) {
return;
}
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
spatialreference = obj->spatialreference;
err = spatialreference->SetProjection(str);
RETURN_LONG(err);
}
PHP_METHOD(OGRSpatialReference, SetWellKnownGeogCS)
{
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *obj;
char *str;
int str_len;
int err;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"s",
&str, &str_len) == FAILURE) {
return;
}
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
spatialreference = obj->spatialreference;
err = spatialreference->SetWellKnownGeogCS(str);
RETURN_LONG(err);
}
PHP_METHOD(OGRSpatialReference, SetFromUserInput)
{
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *obj;
char *str;
int str_len;
int err;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"s",
&str, &str_len) == FAILURE) {
return;
}
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
spatialreference = obj->spatialreference;
err = spatialreference->SetFromUserInput(str);
RETURN_LONG(err);
}
PHP_METHOD(OGRSpatialReference, AutoIdentifyEPSG)
{
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *obj;
int err;
if (ZEND_NUM_ARGS() != 0) {
WRONG_PARAM_COUNT;
}
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
spatialreference = obj->spatialreference;
err = spatialreference->AutoIdentifyEPSG();
RETURN_LONG(err);
}
PHP_METHOD(OGRSpatialReference, GetEPSGGeogCS)
{
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *obj;
int code;
if (ZEND_NUM_ARGS() != 0) {
WRONG_PARAM_COUNT;
}
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
spatialreference = obj->spatialreference;
code = spatialreference->GetEPSGGeogCS();
RETURN_LONG(code);
}
PHP_METHOD(OGRSpatialReference, GetAuthorityCode)
{
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *obj;
char *pszTargetKey = NULL;
int pszTargetKey_len;
char *str;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"|s",
&pszTargetKey, &pszTargetKey_len) == FAILURE) {
return;
}
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
spatialreference = obj->spatialreference;
str = (char *)spatialreference->GetAuthorityCode(pszTargetKey);
if (str) {
RETURN_STRING(str, 1);
} else {
RETURN_NULL();
}
}
PHP_METHOD(OGRSpatialReference, GetAuthorityName)
{
OGRSpatialReference *spatialreference;
php_ogrspatialreference_object *obj;
char *pszTargetKey = NULL;
int pszTargetKey_len;
char *str;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)"|s",
&pszTargetKey, &pszTargetKey_len) == FAILURE) {
return;
}
obj = (php_ogrspatialreference_object *)
zend_object_store_get_object(getThis() TSRMLS_CC);
spatialreference = obj->spatialreference;
str = (char *)spatialreference->GetAuthorityName(pszTargetKey);
if (str) {
RETURN_STRING(str, 1);
} else {
RETURN_NULL();
}
}
//
// PHP stuff
//
zend_function_entry ogrspatialreference_methods[] = {
PHP_ME(OGRSpatialReference, __construct, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRSpatialReference, Reference, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRSpatialReference, Dereference, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRSpatialReference, GetReferenceCount, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRSpatialReference, Release, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRSpatialReference, Clone, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRSpatialReference, CloneGeogCS, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRSpatialReference, exportToWkt, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRSpatialReference, exportToPrettyWkt, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRSpatialReference, exportToProj4, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, exportToPCI, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, exportToUSGS, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRSpatialReference, exportToXML, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, exportToPanorama, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, exportToERM, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, exportToMICoordSys, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRSpatialReference, importFromWkt, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRSpatialReference, importFromProj4, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRSpatialReference, importFromEPSG, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRSpatialReference, importFromEPSGA, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, importFromESRI, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, importFromPCI, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, importFromUSGS, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, importFromPanorama, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, importFromOzi, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, importFromWMSAUTO, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, importFromXML, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, importFromDict, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, importFromURN, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, importFromERM, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, importFromUrl, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, importFromMICoordSys, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, morphToESRI, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, morphFromESRI, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRSpatialReference, Validate, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, StripCTParms, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, StripVertical, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRSpatialReference, FixupOrdering, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRSpatialReference, Fixup, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, EPSGTreatsAsLatLong, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, GetAxis, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetAxes, NULL, ZEND_ACC_PUBLIC)
// // OGR_SRSNode-based methods are omitted
// PHP_ME(OGRSpatialReference, SetLinearUnitsAndUpdateParameters, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetLinearUnits, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, GetLinearUnits, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetAngularUnits, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, GetAngularUnits, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, GetPrimeMeridian, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRSpatialReference, IsGeographic, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRSpatialReference, IsProjected, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRSpatialReference, IsLocal, NULL, ZEND_ACC_PUBLIC)
// OGRSpatialReference::IsVertical not in ogr_spatialref.h
PHP_ME(OGRSpatialReference, IsSameGeogCS, NULL, ZEND_ACC_PUBLIC)
// OGRSpatialReference::IsSameVertCS not in ogr_spatialref.h
PHP_ME(OGRSpatialReference, IsSame, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRSpatialReference, Clear, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRSpatialReference, SetLocalCS, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRSpatialReference, SetProjCS, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRSpatialReference, SetProjection, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetGeogCS, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRSpatialReference, SetWellKnownGeogCS, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, CopyGeogCSFrom, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRSpatialReference, SetFromUserInput, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetTOWGS84, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, GetTOWGS84, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, GetSemiMajor, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, GetSemiMinor, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, GetInvFlattening, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetAuthority, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRSpatialReference, AutoIdentifyEPSG, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRSpatialReference, GetEPSGGeogCS, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRSpatialReference, GetAuthorityCode, NULL, ZEND_ACC_PUBLIC)
PHP_ME(OGRSpatialReference, GetAuthorityName, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, GetExtension, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetExtension, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, FindProjParm, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetProjParm, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, GetProjParm, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetNormProjParm, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, GetNormProjParm, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, IsAngularParameter, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, IsLongitudeParameter, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, IsLinearParameter, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetACEA, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetAE, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetBonne, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetCEA, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetCS, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetEC, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetEckert, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetEckertIV, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetEckertVI, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetEquirectangular, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetEquirectangular2, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetGEOS, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetGH, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetGS, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetGaussSchreiberTMercator, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetGnomonic, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetHOM, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetHOM2PNO, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetIWMPolyconic, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetKrovak, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetLAEA, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetLCC, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetLCC1SP, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetLCCB, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetMC, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetMercator, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetMercator2SP, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetMollweide, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetNZMG, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetOS, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetOrthographic, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetPolyconic, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetPS, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetRobinson, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetSinusoidal, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetStereographic, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetSOC, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetTM, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetTMVariant, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetTMG, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetTMSO, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetTPED, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetVDG, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetUTM, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, GetUTMZone, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetWagner, NULL, ZEND_ACC_PUBLIC)
// PHP_ME(OGRSpatialReference, SetStatePlane, NULL, ZEND_ACC_PUBLIC)
{NULL, NULL, NULL}
};
void php_gdal_ogrspatialreference_startup(INIT_FUNC_ARGS)
{
zend_class_entry ce;
INIT_CLASS_ENTRY(ce, "OGRSpatialReference", ogrspatialreference_methods);
gdal_ogrspatialreference_ce = zend_register_internal_class(&ce TSRMLS_CC);
gdal_ogrspatialreference_ce->create_object = ogrspatialreference_create_handler;
memcpy(&ogrspatialreference_object_handlers,
zend_get_std_object_handlers(), sizeof(zend_object_handlers));
ogrspatialreference_object_handlers.clone_obj = NULL;
}
| 32.400662 | 91 | 0.756839 | martinwilkerson-scisys |
4b6ca55119a28899144310a60accfd1f6d82af20 | 8,417 | hpp | C++ | include/elemental/lapack-like/SVD/Thresholded.hpp | ahmadia/Elemental-1 | f9a82c76a06728e9e04a4316e41803efbadb5a19 | [
"BSD-3-Clause"
] | null | null | null | include/elemental/lapack-like/SVD/Thresholded.hpp | ahmadia/Elemental-1 | f9a82c76a06728e9e04a4316e41803efbadb5a19 | [
"BSD-3-Clause"
] | null | null | null | include/elemental/lapack-like/SVD/Thresholded.hpp | ahmadia/Elemental-1 | f9a82c76a06728e9e04a4316e41803efbadb5a19 | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2009-2013, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#pragma once
#ifndef LAPACK_SVD_THRESHOLDED_HPP
#define LAPACK_SVD_THRESHOLDED_HPP
#include "elemental/blas-like/level3/Gemm.hpp"
#include "elemental/blas-like/level3/Herk.hpp"
#include "elemental/lapack-like/HermitianEig.hpp"
#include "elemental/lapack-like/Norm/Frobenius.hpp"
namespace elem {
namespace svd {
template<typename F>
inline void
ThresholdedTall
( Matrix<F>& A, Matrix<BASE(F)>& s, Matrix<F>& V, BASE(F) tol=0 )
{
#ifndef RELEASE
CallStackEntry entry("svd::ThresholdedTall");
if( A.Height() < A.Width() )
throw std::logic_error("A must be at least as tall as it is wide");
if( tol < 0 )
throw std::logic_error("negative threshold does not make sense");
#endif
typedef BASE(F) R;
const int m = A.Height();
const int n = A.Width();
const R frobNorm = FrobeniusNorm( A );
if( tol == R(0) )
{
const R eps = lapack::MachineEpsilon<R>();
tol = m*frobNorm*eps;
}
// C := A^H A
Matrix<F> C;
Herk( LOWER, ADJOINT, F(1), A, C );
// [V,Sigma^2] := eig(C), where each sigma > tol
HermitianEig( LOWER, C, s, V, tol*tol, frobNorm*frobNorm );
// Sigma := sqrt(Sigma^2)
const int k = s.Height();
for( int i=0; i<k; ++i )
s.Set( i, 0, Sqrt(s.Get(i,0)) );
// Y := A V
Matrix<F> Y;
Gemm( NORMAL, NORMAL, F(1), A, V, Y );
// Set each column of A to be the corresponding normalized column of Y
// NOTE: A (potentially better) alternative would be to compute the norm of
// each column of A and normalize via it, as it might vary slightly
// from the corresponding computed singular value.
A = Y;
for( int j=0; j<n; ++j )
{
const R sigma = s.Get( j, 0 );
for( int i=0; i<m; ++i )
A.Set( i, j, A.Get(i,j)/sigma );
}
}
#ifdef HAVE_PMRRR
template<typename F>
inline void
ThresholdedTall
( DistMatrix<F>& A, DistMatrix<BASE(F),VR,STAR>& s, DistMatrix<F>& V,
BASE(F) tol=0 )
{
#ifndef RELEASE
CallStackEntry entry("svd::ThresholdedTall");
if( A.Height() < A.Width() )
throw std::logic_error("A must be at least as tall as it is wide");
if( tol < 0 )
throw std::logic_error("negative threshold does not make sense");
#endif
typedef BASE(F) R;
const Grid& g = A.Grid();
const int m = A.Height();
const int n = A.Width();
const R frobNorm = FrobeniusNorm( A );
if( tol == R(0) )
{
const R eps = lapack::MachineEpsilon<R>();
tol = m*frobNorm*eps;
}
// C := A^H A
DistMatrix<F> C( g );
Herk( LOWER, ADJOINT, F(1), A, C );
// [V,Sigma^2] := eig(C), where each sigma > tol
HermitianEig( LOWER, C, s, V, tol*tol, frobNorm*frobNorm );
// Sigma := sqrt(Sigma^2)
{
const int localHeight = s.LocalHeight();
for( int iLocal=0; iLocal<localHeight; ++iLocal )
s.SetLocal( iLocal, 0, Sqrt(s.GetLocal(iLocal,0)) );
}
// Y := A V
DistMatrix<F> Y( g );
Gemm( NORMAL, NORMAL, F(1), A, V, Y );
// Set each column of A to be the corresponding normalized column of Y
// NOTE: A (potentially better) alternative would be to compute the norm of
// each column of A and normalize via it, as it might vary slightly
// from the corresponding computed singular value.
A = Y;
{
DistMatrix<R,MR,STAR> s_MR_STAR( g );
s_MR_STAR.AlignWith( A.DistData() );
s_MR_STAR = s;
const int localWidth = A.LocalWidth();
const int localHeight = A.LocalHeight();
for( int jLocal=0; jLocal<localWidth; ++jLocal )
{
const R sigma = s_MR_STAR.GetLocal( jLocal, 0 );
for( int iLocal=0; iLocal<localHeight; ++iLocal )
A.SetLocal( iLocal, jLocal, A.GetLocal(iLocal,jLocal)/sigma );
}
}
}
#endif // ifdef HAVE_PMRRR
template<typename F>
inline void
ThresholdedWide
( Matrix<F>& A, Matrix<BASE(F)>& s, Matrix<F>& V, BASE(F) tol=0 )
{
#ifndef RELEASE
CallStackEntry entry("svd::ThresholdedWide");
if( A.Width() < A.Height() )
throw std::logic_error("A must be at least as wide as it is tall");
if( tol < 0 )
throw std::logic_error("negative threshold does not make sense");
#endif
typedef BASE(F) R;
const int m = A.Height();
const int n = A.Width();
const R frobNorm = FrobeniusNorm( A );
if( tol == R(0) )
{
const R eps = lapack::MachineEpsilon<R>();
tol = n*frobNorm*eps;
}
// C := A A^H
Matrix<F> C;
Herk( LOWER, NORMAL, F(1), A, C );
// [U,Sigma^2] := eig(C), where each sigma > tol
Matrix<F> U;
HermitianEig( LOWER, C, s, U, tol*tol, frobNorm*frobNorm );
// Sigma := sqrt(Sigma^2)
const int k = s.Height();
for( int i=0; i<k; ++i )
s.Set( i, 0, Sqrt(s.Get(i,0)) );
// (Sigma V) := A^H U
Gemm( ADJOINT, NORMAL, F(1), A, U, V );
// Divide each column of (Sigma V) by sigma
// NOTE: A (potentially better) alternative would be to compute the norm of
// each column of V and normalize via it, as it might vary slightly
// from the corresponding computed singular value.
for( int j=0; j<k; ++j )
{
const R sigma = s.Get( j, 0 );
for( int i=0; i<n; ++i )
V.Set( i, j, V.Get(i,j)/sigma );
}
A = U;
}
#ifdef HAVE_PMRRR
template<typename F>
inline void
ThresholdedWide
( DistMatrix<F>& A, DistMatrix<BASE(F),VR,STAR>& s, DistMatrix<F>& V,
BASE(F) tol=0 )
{
#ifndef RELEASE
CallStackEntry entry("svd::ThresholdedWide");
if( A.Width() < A.Height() )
throw std::logic_error("A must be at least as wide as it is tall");
if( tol < 0 )
throw std::logic_error("negative threshold does not make sense");
#endif
typedef BASE(F) R;
const Grid& g = A.Grid();
const int m = A.Height();
const int n = A.Width();
const R frobNorm = FrobeniusNorm( A );
if( tol == R(0) )
{
const R eps = lapack::MachineEpsilon<R>();
tol = n*frobNorm*eps;
}
// C := A A^H
DistMatrix<F> C( g );
Herk( LOWER, NORMAL, F(1), A, C );
// [U,Sigma^2] := eig(C), where each sigma > tol
DistMatrix<F> U( g );
HermitianEig( LOWER, C, s, U, tol*tol, frobNorm*frobNorm );
// Sigma := sqrt(Sigma^2)
{
const int localHeight = s.LocalHeight();
for( int iLocal=0; iLocal<localHeight; ++iLocal )
s.SetLocal( iLocal, 0, Sqrt(s.GetLocal(iLocal,0)) );
}
// (Sigma V) := A^H U
Gemm( ADJOINT, NORMAL, F(1), A, U, V );
// Divide each column of (Sigma V) by sigma
// NOTE: A (potentially better) alternative would be to compute the norm of
// each column of V and normalize via it, as it might vary slightly
// from the corresponding computed singular value.
{
DistMatrix<R,MR,STAR> s_MR_STAR( g );
s_MR_STAR.AlignWith( V.DistData() );
s_MR_STAR = s;
const int localWidth = V.LocalWidth();
const int localHeight = V.LocalHeight();
for( int jLocal=0; jLocal<localWidth; ++jLocal )
{
const R sigma = s_MR_STAR.GetLocal( jLocal, 0 );
for( int iLocal=0; iLocal<localHeight; ++iLocal )
V.SetLocal( iLocal, jLocal, V.GetLocal(iLocal,jLocal)/sigma );
}
}
A = U;
}
#endif // ifdef HAVE_PMRRR
template<typename F>
inline void
Thresholded
( Matrix<F>& A, Matrix<BASE(F)>& s, Matrix<F>& V, BASE(F) tol=0 )
{
#ifndef RELEASE
CallStackEntry entry("svd::Thresholded");
#endif
if( A.Height() >= A.Width() )
ThresholdedTall( A, s, V, tol );
else
ThresholdedWide( A, s, V, tol );
}
#ifdef HAVE_PMRRR
template<typename F>
inline void
Thresholded
( DistMatrix<F>& A, DistMatrix<BASE(F),VR,STAR>& s, DistMatrix<F>& V,
BASE(F) tol=0 )
{
#ifndef RELEASE
CallStackEntry entry("svd::Thresholded");
#endif
if( A.Height() >= A.Width() )
ThresholdedTall( A, s, V, tol );
else
ThresholdedWide( A, s, V, tol );
}
#endif // ifdef HAVE_PMRRR
} // namespace svd
} // namespace elem
#endif // ifndef LAPACK_SVD_THRESHOLDED_HPP
| 29.43007 | 79 | 0.588808 | ahmadia |
4b732956a44bf2c1873ecf57b97902d86ce286aa | 1,564 | cpp | C++ | examples/Switch.TUnit/Assert/Assert.cpp | victor-timoshin/Switch | 8e8e687a8bdc4f79d482680da3968e9b3e464b8b | [
"MIT"
] | 4 | 2020-02-11T13:22:58.000Z | 2022-02-24T00:37:43.000Z | examples/Switch.TUnit/Assert/Assert.cpp | sgf/Switch | 8e8e687a8bdc4f79d482680da3968e9b3e464b8b | [
"MIT"
] | null | null | null | examples/Switch.TUnit/Assert/Assert.cpp | sgf/Switch | 8e8e687a8bdc4f79d482680da3968e9b3e464b8b | [
"MIT"
] | 2 | 2020-02-01T02:19:01.000Z | 2021-12-30T06:44:00.000Z | #include <Switch/Switch>
using namespace TUnit;
using namespace System;
namespace UnitTests {
// The class TimeSpanTest must be inherited from TestFixture
class TestFixture_(TimeSpanTest) {
// Used Assert::AreEqual method to test value
void Test_(CreateTimeSpanFromDateTime) {
DateTime n = DateTime(2015, 9, 5, 9, 15, 0);
TimeSpan ts(n.Ticks);
Assert::AreEqual(9, ts.Hours, caller_);
Assert::AreEqual(15, ts.Minutes, caller_);
}
// Used Assert::IsTrue to virifie if a condition is true
void Test_(TimeSpanIsEqualToAnotherTimeSpan) {
TimeSpan ts(10, 42, 24);
Assert::IsTrue(ts.Equals(TimeSpan(10, 42, 24)), caller_);
}
// Used Assert::IsFalse to virifie if a condition is false
void Test_(DefaultTimeSpanIsEqualToZero) {
Assert::IsFalse(TimeSpan(1) == TimeSpan::Zero(), caller_);
}
};
// Used AddTest_ to add unit test to execute at the unit test suit.
AddTest_(TimeSpanTest, CreateTimeSpanFromDateTime);
AddTest_(TimeSpanTest, TimeSpanIsEqualToAnotherTimeSpan);
AddTest_(TimeSpanTest, DefaultTimeSpanIsEqualToZero);
}
// This code produces the following output:
//
// Start 3 tests from 1 test case
// Start 3 tests from TimeSpanTest
// PASSED TimeSpanTest.CreateTimeSpanFromDateTime (1 ms)
// PASSED TimeSpanTest.TimeSpanIsEqualToAnotherTimeSpan (0 ms)
// PASSED TimeSpanTest.DefaultTimeSpanIsEqualToZero (0 ms)
// End 3 tests from TimeSpanTest (4 ms total)
//
// Summary :
// PASSED 3 tests.
// End 3 tests from 1 test case ran. (5 ms total)
| 33.276596 | 69 | 0.709079 | victor-timoshin |
4b74d6ca9c172eef5c3e403eae466f993f6ddc5f | 766 | hpp | C++ | src/RayTracer.hpp | Acee11/RayTracing | b4d870fe6295a936af7dae0364d4c5b30baeeb31 | [
"MIT"
] | null | null | null | src/RayTracer.hpp | Acee11/RayTracing | b4d870fe6295a936af7dae0364d4c5b30baeeb31 | [
"MIT"
] | null | null | null | src/RayTracer.hpp | Acee11/RayTracing | b4d870fe6295a936af7dae0364d4c5b30baeeb31 | [
"MIT"
] | null | null | null | #pragma once
#include <iostream>
#include <iomanip>
#include <cstdint>
#include <fstream>
#include <memory>
#include <vector>
#include <omp.h>
#include <chrono>
#include "Vector3D.hpp"
#include "Sphere.hpp"
#include "Ray.hpp"
#include "Light.hpp"
#include "Surface.hpp"
#include "Camera.hpp"
#include "Scene.hpp"
using Clock = std::chrono::high_resolution_clock;
class RayTracer
{
using Bitmap = std::vector<Vector3DBase>;
private:
Vector3DBase getPixelColor(const Ray& ray, int recursionLevel) const;
Vector3DBase totalAmbient;
std::shared_ptr<Scene> scene;
public:
RayTracer(const std::shared_ptr<Scene>& scene);
RayTracer(const std::shared_ptr<Scene>& scene, const Camera& camera);
Camera camera;
Bitmap getBitmap(int width, int height) const;
}; | 20.157895 | 70 | 0.745431 | Acee11 |
4b74dafe2fb3159e854575c6bf14586e041e4b2a | 2,982 | cpp | C++ | codechef/long-challenge/easy-fibonacci.cpp | Zenix27/data-structure-and-algorithms | 7570a65f40c8fbb8a08845be749f507f58ed773f | [
"MIT"
] | 81 | 2020-05-22T14:22:04.000Z | 2021-12-18T10:11:23.000Z | codechef/long-challenge/easy-fibonacci.cpp | Zenix27/data-structure-and-algorithms | 7570a65f40c8fbb8a08845be749f507f58ed773f | [
"MIT"
] | 4 | 2020-08-06T21:08:00.000Z | 2021-03-31T16:07:50.000Z | codechef/long-challenge/easy-fibonacci.cpp | Zenix27/data-structure-and-algorithms | 7570a65f40c8fbb8a08845be749f507f58ed773f | [
"MIT"
] | 37 | 2020-05-22T14:25:21.000Z | 2021-12-30T03:13:13.000Z | /*
[Easy Fibonacci](https://www.codechef.com/SEPT19B/problems/FIBEASY)
Problem Code: FIBEASY
The Fibonacci sequence F0,F1,… is a special infinite sequence of non-negative integers, where F0=0, F1=1 and for each integer n≥2, Fn=Fn−1+Fn−2.
Consider the sequence D of the last decimal digits of the first N Fibonacci numbers, i.e. D=(F0%10,F1%10,…,FN−1%10). Now, you should perform the following process:
Let D=(D1,D2,…,Dl).
If l=1, the process ends.
Create a new sequence E=(D2,D4,…,D2⌊l/2⌋). In other words, E is the sequence created by removing all odd-indexed elements from D.
Change D to E.
When this process terminates, the sequence D contains only one number. You have to find this number.
Input
The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
The first and only line of each test case contains a single integer N.
Output
For each test case, print a single line containing one integer ― the last remaining number.
Constraints
1≤T≤10^5
1≤N≤10^18
Subtasks
Subtask #1 (20 points):
1≤T≤10^5
1≤N≤10^7
Subtask #2 (80 points): original constraints
Example
Input
1
9
Output
3
Explanation
Example case 1: The first N Fibonacci numbers are (0,1,1,2,3,5,8,13,21). The sequence D is (0,1,1,2,3,5,8,3,1)→(1,2,5,3)→(2,3)→(3).
*/
// Solution
// cook your dish here
#include <iostream>
#include <type_traits>
#include <bitset>
#include <math.h>
using namespace std;
long long get_pisano_period(long long m)
{
long long a = 0, b = 1, c = a + b;
for (int i = 0; i < m * m; i++)
{
c = (a + b) % m;
a = b;
b = c;
if (a == 0 && b == 1)
return i + 1;
}
return 0;
}
long long get_fibonacci_huge(long long n, long long m)
{
long long remainder = n % get_pisano_period(m);
long long first = 0;
long long second = 1;
long long res = remainder;
for (int i = 1; i < remainder; i++)
{
res = (first + second) % m;
first = second;
second = res;
}
return res % m;
}
long long highestPowerof2(long long n)
{
bitset<128> binary(n);
long long x = 0;
for (int i = 127; i >= 0; i--)
{
if (binary[i] == 1)
{
break;
}
x += 1;
}
return (long long)(128 - x - 1);
}
int main()
{
long long T;
cin >> T;
string c;
long long d;
long long n;
while (T--)
{
long long N;
cin >> N;
if (N == 1)
{
cout << 0 << '\n';
}
else
{
if (N % 2 != 0)
{
d = highestPowerof2(N - 1);
n = (long long)(pow(2, d) + 0.5) - 1;
}
else
{
d = highestPowerof2(N);
n = (long long)(pow(2, d) + 0.5) - 1;
}
cout << get_fibonacci_huge(n, 10) << '\n';
}
}
return 0;
}
// Time : 0.19 s
| 21.453237 | 163 | 0.554997 | Zenix27 |
4b763e13c9d2d261b95c3dfb48ee50fdc02f9dff | 1,264 | cc | C++ | tests/src/lp/tuple_traits_test.cc | no111u3/lp_cc_lib | 3a8b04da3184870902be4d032fc13b2c6f1a8b52 | [
"Apache-2.0"
] | 1 | 2021-01-18T20:49:57.000Z | 2021-01-18T20:49:57.000Z | tests/src/lp/tuple_traits_test.cc | no111u3/lp_cc_lib | 3a8b04da3184870902be4d032fc13b2c6f1a8b52 | [
"Apache-2.0"
] | null | null | null | tests/src/lp/tuple_traits_test.cc | no111u3/lp_cc_lib | 3a8b04da3184870902be4d032fc13b2c6f1a8b52 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2018 Boris Vinogradov <no111u3@gmail.com>
*
* 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.
*
* Lepestrum C++ Library implementation
* Tuple traits test
* @file lp/tuple_traits_test.cc
* @author Boris Vinogradov
*/
#include <lp/tuple_traits.hh>
#include <type_traits.hh>
void tuple_traits_test() {
using namespace lp;
static_assert(
tuple_append(std::make_tuple(1), 2) ==
std::make_tuple(1, 2), "");
static_assert(
tuple_append(std::tuple<>{}, 1, 2) ==
std::make_tuple(1, 2), "");
static_assert(
tuple_insert(std::make_tuple(1), 2) ==
std::make_tuple(2, 1), "");
static_assert(
tuple_insert(std::tuple<>{}, 1, 2) ==
std::make_tuple(1, 2), "");
}
| 28.727273 | 75 | 0.665348 | no111u3 |
4b7bb12ef9b33d380126acbc84a0c6833d5e5063 | 22,365 | cpp | C++ | Motor2D/j1Scene.cpp | marc094/Dev_class5_handout | 9cb6d71096c59c6f862e9a68e5621a4ae9d865a6 | [
"Unlicense"
] | 1 | 2019-05-28T10:55:32.000Z | 2019-05-28T10:55:32.000Z | Motor2D/j1Scene.cpp | marc094/Parallax-Paradox | 9cb6d71096c59c6f862e9a68e5621a4ae9d865a6 | [
"Unlicense"
] | null | null | null | Motor2D/j1Scene.cpp | marc094/Parallax-Paradox | 9cb6d71096c59c6f862e9a68e5621a4ae9d865a6 | [
"Unlicense"
] | null | null | null | #include <math.h>
#include "p2Defs.h"
#include "p2Log.h"
#include "j1App.h"
#include "j1Input.h"
#include "j1Textures.h"
#include "j1Audio.h"
#include "j1Render.h"
#include "j1Window.h"
#include "j1Map.h"
#include "j1Scene.h"
#include "j1Entities.h"
#include "Entity.h"
#include "Player.h"
#include "j1Textures.h"
#include "j1Gui.h"
#include "Window.h"
#include "Slider.h"
#include "j1Transition.h"
j1Scene::j1Scene() : j1Module()
{
name.create("scene");
level = 1;
}
// Destructor
j1Scene::~j1Scene()
{}
// Called before render is available
bool j1Scene::Awake(pugi::xml_node& data)
{
LOG("Loading Scene");
bool ret = true;
max_level = 0;
for (pugi::xml_node level : data.children())
{
max_level++;
xml_file_name.PushBack(level.attribute("name").as_string());
}
return ret;
}
// Called before the first frame
bool j1Scene::Start()
{
App->SetTimeScale(1.f);
if (level > max_level)
level = 1;
button_sound = App->audio->LoadFx("audio/FX/Button.wav");
buttons = App->tex->Load("gui/Buttons2.png");
credits_win = App->tex->Load("gui/Credits_win.png");
settings_win = App->tex->Load("gui/Settings win.png");
credits_tex = App->tex->Load("gui/Credits 3.png");
sliders = App->tex->Load("gui/Scroll.png");
SDL_Rect slider_bar = { 0,0,20,435 };
SDL_Rect slider_idle = { 33,0,16,94 };
SDL_Rect slider_pressed = { 33,103,16,94 };
SDL_Rect slider_hover = { 33,212,16,94 };
SDL_Rect h_slider_bar = { 54,0,326,7 };
SDL_Rect h_slider_pressed = { 58,14,10,21 };
SDL_Rect h_slider_hovered = { 72,14,10,21 };
SDL_Rect h_slider_idle = { 86,14,10,21 };
uint w;
uint h;
uiPoint dims = App->gui->GetGuiSize();
w = dims.x;
h = dims.y;
SDL_Rect button_idle = { 1000,1000,250,58 };
SDL_Rect button_hover = { 0,0,250,58 };
SDL_Rect button_press = { 0,58,250,58 };
if (current_state == END) {
App->entities->active = false;
uiPoint dims = App->gui->GetGuiSize();
Label* win_label = App->gui->AddLabel(dims.x / 2, dims.y / 2 - dims.y / 12, 60, "gui/Earth 2073.ttf", { 255, 255, 255, 255 });
win_label->setString("CONGRATULATIONS");
win_label->ComputeRects();
App->transition->MakeTransition(&DoLoadMenu, j1Transition::FADE_TO_BLACK, 10.f);
}
else if (current_state == INTRO)
{
App->entities->active = false;
logo_back = App->tex->Load("textures/intro background.png");
logo = App->tex->Load("textures/Marcopolo logo.png");
Sprite* logo_b_spr = App->gui->AddSprite(w / 2, h / 2, logo_back);
Sprite* logo_spr = App->gui->AddSprite(w / 2, h / 2, logo);
App->transition->MakeTransition(nullptr, j1Transition::FADE_TO_BLACK, 2.5f);
App->transition->fade_state = j1Transition::FADING_IN;
}
else if (current_state == IN_GAME)
{
App->map->Load(xml_file_name[level - 1].GetString());
lifes_sprite = App->tex->Load("textures/Lifeicon.png");
SDL_Rect life = { 0,0,45,48 };
SDL_Rect coin_rect = { 45,0,36,48 };
Sprite* first_life = App->gui->AddSprite(50, h - 50, lifes_sprite, life);
Sprite* second_life = App->gui->AddSprite(110, h - 50, lifes_sprite, life);
Sprite* third_life = App->gui->AddSprite(170, h - 50, lifes_sprite, life);
lives.add(first_life);
lives.add(second_life);
lives.add(third_life);
time_lab = App->gui->AddLabel(w - 150, h - 50, 40, "gui/Earth 2073.ttf", { 255,255,255,255 },Label::BLENDED);
time_lab->SetAnchor(0.0f, 0.5f);
Sprite* Coin = App->gui->AddSprite(270, h - 50, lifes_sprite, coin_rect);
coin_lab = App->gui->AddLabel(300, h - 50,40, "gui/Earth 2073.ttf", { 255,255,255,255 }, Label::BLENDED);
coin_lab->SetAnchor(0.0f, 0.5f);
coin_lab->setString("X%d", App->entities->player.coins);
jump_sound = App->audio->LoadFx("audio/FX/Jump.wav");
change_sound = App->audio->LoadFx("audio/FX/Change2.wav");
hit_sound = App->audio->LoadFx("audio/FX/Onhit.wav");
level_sound = App->audio->LoadFx("audio/FX/Wierd.wav");
coin_sound = App->audio->LoadFx("audio/FX/Coin.wav");
if (jump_sound == 0 || change_sound == 0 || hit_sound == 0 || level_sound == 0)
LOG("Error loading sound fx: %s\n", Mix_GetError());
if (!playing)
{
App->audio->PlayMusic("audio/music/InGame.ogg", -1);
playing = true;
}
App->audio->PlayFx(level_sound);
App->entities->active = true;
switch (level)
{
case 1:
{
App->entities->Add_Coin({ 476, 678 });
App->entities->Add_Coin({ 416, 894 });
App->entities->Add_Coin({ 815, 561 });
App->entities->Add_Coin({ 481, 47 });
firstlevel_lab = App->gui->AddLabel(w /2, h /3, 35, "gui/Earth 2073.ttf", { 255,255,255,255 }, Label::BLENDED);
firstlevel_lab->setString("Press LB to switch layer");
firstlevel_lab->Enable(false);
break;
}
case 2:
{
App->entities->Add_Coin({ 1474, 856 });
App->entities->Add_Coin({ 900, 840 });
App->entities->Add_Coin({ 400, 1000 });
App->entities->Add_Coin({ 1000, 600 });
App->entities->Add_Coin({ 1480, 585 });
App->entities->Add_Coin({ 1185, 216 });
break;
}
case 3:
{
App->entities->Add_Coin({ 891, 973 });
App->entities->Add_Coin({ 1296, 854 });
App->entities->Add_Coin({ 762,600 });
App->entities->Add_Coin({ 730,730 });
break;
}
case 4:
{
App->entities->Add_Coin({ 998,706 });
App->entities->Add_Coin({ 621, 548 });
App->entities->Add_Coin({ 1332,421 });
App->entities->Add_Coin({ 171,134 });
break;
}
}
}
else if (current_state == IN_MENU)
{
//Estaria guay tenir musica al menu
App->audio->PlayMusic("audio/music/Intro.ogg", -1);
App->entities->active = false;
menu_background = App->tex->Load("textures/menu background.png");
title = App->tex->Load("textures/title.png");
App->gui->AddSprite( w/2, h/2, menu_background);
Sprite* title_spr = App->gui->AddSprite(w / 2, (h / 2 - 100), title);
//START BUTTON
Button* start_button = App->gui->AddButton((w / 2), 60 + (h / 2), buttons, button_idle, true, &Game_start, button_hover, button_press);
Label* start = App->gui->AddLabel(start_button->content_rect.w/2, (start_button->content_rect.h/2), 33, "gui/Earth 2073.ttf", { 255,255,255,255 });
start->setString("START");
start->SetParent(start_button);
menu_buttons.add(start_button);
//CONTINUE BUTTON
Button* continue_button = App->gui->AddButton(w / 2, 120+ (h / 2), buttons, button_idle, true, &Game_continue, button_hover, button_press);
Label* continue_label = App->gui->AddLabel(start_button->content_rect.w / 2, (start_button->content_rect.h / 2), 33, "gui/Earth 2073.ttf", { 255,255,255,255 });
continue_label->setString("CONTINUE");
continue_label->SetParent(continue_button);
menu_buttons.add(continue_button);
//CREDITS BUTTON
Button* credits_button = App->gui->AddButton(w / 2, 180+ (h / 2), buttons, button_idle, true, &Show_Credits, button_hover, button_press);
Label* credit = App->gui->AddLabel(start_button->content_rect.w / 2, (start_button->content_rect.h / 2), 33, "gui/Earth 2073.ttf", { 255,255,255,255 });
credit->setString("CREDITS");
credit->SetParent(credits_button);
menu_buttons.add(credits_button);
//SETTINGS BUTTON
Button* settings_button = App->gui->AddButton(w / 2, 240 + (h / 2), buttons, button_idle, true, &ShowSettings, button_hover, button_press);
Label* settings = App->gui->AddLabel(start_button->content_rect.w / 2, (start_button->content_rect.h / 2), 33, "gui/Earth 2073.ttf", { 255,255,255,255 });
settings->setString("SETTINGS");
settings->SetParent(settings_button);
menu_buttons.add(settings_button);
//EXIT BUTTON
Button* exit_button = App->gui->AddButton(w / 2, 300 + (h / 2), buttons, button_idle, true, &exit, button_hover, button_press);
Label* exit = App->gui->AddLabel(start_button->content_rect.w / 2, (start_button->content_rect.h / 2), 33, "gui/Earth 2073.ttf", { 255,255,255,255 });
exit->setString("EXIT");
exit->SetParent(exit_button);
menu_buttons.add(exit_button);
//CREDITS WINDOW
Window_Info w_info_credits;
w_info_credits.x = w / 2;
w_info_credits.y = h / 2;
w_info_credits.content_rect_margins = { 10, 87, 0, 15 };
w_info_credits.tex = credits_win;
w_info_credits.OnClose = &Hide_Credits;
w_info_credits.enabled = false;
credits_window = App->gui->AddWindow(w_info_credits);
credits_text = App->gui->AddSprite(0, 0, credits_tex);
credits_text->SetAnchor(0.0f, 0.0f);
credits_text->SetParent(credits_window);
Sprite* slider = App->gui->AddSprite((int)(0.97f * credits_window->content_rect.w), credits_window->content_rect.h / 2 - 20, sliders, slider_bar);
slider->culled = false;
slider->SetParent(credits_window);
slider->SetContentRect(0, 48, 0, 48);
credits_slider = App->gui->AddSlider(slider->content_rect.w/2, 0, sliders, slider_idle, true, Drag_Credits, slider_hover, slider_pressed, 0, slider);
credits_slider->culled = false;
}
//SETTINGS WINDOW
settings_window = CreateSettingsWindow(w / 2, h / 2, h_slider_bar, h_slider_idle, h_slider_hovered, h_slider_pressed, button_idle, button_hover, button_press);
return true;
}
// Called each loop iteration
bool j1Scene::PreUpdate()
{
return true;
}
// Called each loop iteration
bool j1Scene::Update(float dt)
{
if (App->input->GetKey(SDL_SCANCODE_ESCAPE) == KEY_DOWN)
{
if (state == IN_GAME) {
if (!settings_bool && !settings_window->isEnabled()) {
ShowSettings(0);
}
else Hide_Settings(0);
}
else
ret = false;
}
if (App->input->GetControllerButton(SDL_CONTROLLER_BUTTON_START) == KEY_DOWN) {
if (state == IN_GAME) {
if (!settings_bool && !settings_window->isEnabled()) {
ShowSettings(0);
}
else Hide_Settings(0);
}
}
if (App->input->GetKey(SDL_SCANCODE_F1) == KEY_DOWN)
ChangeScene(1);
if (App->input->GetKey(SDL_SCANCODE_F2) == KEY_DOWN)
ChangeScene(level);
if (App->input->GetKey(SDL_SCANCODE_F4) == KEY_DOWN)
App->debug = !App->debug;
if (App->input->GetKey(SDL_SCANCODE_LCTRL) == KEY_DOWN)
App->SetTimeScale(0.5f);
if (App->input->GetKey(SDL_SCANCODE_LCTRL) == KEY_UP)
App->SetTimeScale(1.0f);
// Settings input
if (App->input->GetKey(SDL_SCANCODE_F6) == KEY_DOWN)
App->LoadGame();
if (App->input->GetKey(SDL_SCANCODE_F5) == KEY_DOWN)
App->SaveGame();
if (App->input->GetKey(SDL_SCANCODE_F11) == KEY_DOWN)
{
if (App->GetFramerateCap() == -1)
App->SetFramerateCap(60);
else App->SetFramerateCap(-1);
}
if (current_state == IN_GAME)
CheckEnd();
else if (current_state == INTRO)
{
if (intro_time.Count(4))
{
App->transition->MakeTransition(&DoReload, j1Transition::FADE_TO_BLACK, 2.5f);
state = IN_MENU;
}
}
else if (App->input->GetKey(SDL_SCANCODE_RETURN) == KEY_DOWN)
{
App->transition->MakeTransition(&DoLoadInGame, j1Transition::FADE_TO_BLACK, 2.5f);
}
if (current_state == IN_GAME)
{
if (!App->entities->player.hit)
{
CheckInput(dt);
}
if (level == 1 )
{
iRect player_rect = App->entities->player.collider;
player_rect.x = (int)App->entities->player.GetPosition().x;
player_rect.y = (int)App->entities->player.GetPosition().y;
if (App->entities->player.current_layer == FRONT_LAYER && App->collision->DoCollide(player_rect.toSDL_Rect(), { 1143,612,123,27 }))
firstlevel_lab->Enable(true);
else
firstlevel_lab->Enable(false);
}
App->map->Draw();
time += dt;
time_lab->setString("%.2f", time);
}
// "Map:%dx%d Tiles:%dx%d Tilesets:%d"
p2SString title("Map:%dx%d Tiles:%dx%d Tilesets:%d",
App->map->data.width, App->map->data.height,
App->map->data.tile_width, App->map->data.tile_height,
App->map->data.tilesets.count());
//App->win->SetTitle(title.GetString());
return ret;
}
// Called each loop iteration
bool j1Scene::PostUpdate()
{
current_state = state;
return true;
}
// Called before quitting
bool j1Scene::CleanUp(pugi::xml_node& config)
{
LOG("Freeing scene");
xml_file_name.Clear();
return true;
}
void DoReload(int, ...) {
App->Reload();
App->scene->transitioninig = false;
}
void DoLoadInGame(int, ...) {
App->Reload();
App->scene->state = j1Scene::IN_GAME;
App->scene->transitioninig = false;
}
void DoLoadMenu(int, ...) {
App->Reload();
App->scene->state = j1Scene::IN_MENU;
App->scene->transitioninig = false;
}
void DoLoadEnd(int, ...) {
App->Reload();
App->scene->state = j1Scene::END;
App->scene->transitioninig = false;
}
void j1Scene::ChangeScene(uint _level) {
level = _level;
float trans_time = 3.f;
if (level > max_level) {
level = 1;
trans_time = 5.f;
playing = false;
App->audio->StopMusic(trans_time);
App->transition->MakeTransition(&DoLoadEnd, j1Transition::FADE_TO_BLACK, trans_time);
}
else App->transition->MakeTransition(&DoReload, j1Transition::FADE_TO_BLACK, trans_time);
App->SetTimeScaleTo(0.1f, 2.f);
}
void j1Scene::CheckInput(float dt)
{
if (App->input->GetKey(SDL_SCANCODE_X) == KEY_DOWN || App->input->GetControllerButton(SDL_CONTROLLER_BUTTON_LEFTSHOULDER) == KEY_DOWN)
App->entities->player.SwapLayer();
if (App->input->GetKey(SDL_SCANCODE_DOWN) == KEY_REPEAT || App->input->GetControllerButton(SDL_CONTROLLER_BUTTON_DPAD_DOWN) == KEY_REPEAT || App->input->GetControllerAxis(SDL_CONTROLLER_AXIS_LEFTY, +1))
App->entities->player.Accelerate(0, ACCELERATION, dt);
if (App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT || App->input->GetControllerButton(SDL_CONTROLLER_BUTTON_DPAD_LEFT) == KEY_REPEAT || App->input->GetControllerAxis(SDL_CONTROLLER_AXIS_LEFTX, -1))
App->entities->player.Accelerate(-ACCELERATION, 0, dt);
if (App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT || App->input->GetControllerButton(SDL_CONTROLLER_BUTTON_DPAD_RIGHT) == KEY_REPEAT || App->input->GetControllerAxis(SDL_CONTROLLER_AXIS_LEFTX, +1))
App->entities->player.Accelerate(ACCELERATION, 0, dt);
if ((App->input->GetKey(SDL_SCANCODE_SPACE) == KEY_DOWN || App->input->GetKey(SDL_SCANCODE_UP) == KEY_DOWN || App->input->GetControllerButton(SDL_CONTROLLER_BUTTON_DPAD_UP) == KEY_DOWN
|| App->input->GetControllerButton(SDL_CONTROLLER_BUTTON_A) == KEY_DOWN) && !App->entities->player.isJumping() && !App->entities->player.god_mode)
{
App->entities->player.setJumping(true);
App->entities->player.Accelerate(0, -JUMP_FORCE, dt);
App->audio->PlayFx(jump_sound);
}
else if ((App->input->GetKey(SDL_SCANCODE_SPACE) == KEY_REPEAT || App->input->GetControllerButton(SDL_CONTROLLER_BUTTON_DPAD_UP) == KEY_REPEAT
|| App->input->GetControllerAxis(SDL_CONTROLLER_AXIS_LEFTY, -1)) && App->entities->player.god_mode)
{
App->entities->player.Accelerate(0, -ACCELERATION, dt);
}
if (App->input->GetKey(SDL_SCANCODE_F10) == KEY_DOWN)
App->entities->player.god_mode = !App->entities->player.god_mode;
}
void j1Scene::CheckEnd() {
//App->render->DrawCircle(App->map->GetFinalPlayerPos().x, App->map->GetFinalPlayerPos().y, 50, 255, 255, 255, 255, true, false);
if (App->entities->player.GetPosition().DistanceTo(App->map->GetFinalPlayerPos() + fPoint(15.f, 0.f)) < 50.f && !transitioninig) {
transitioninig = true;
App->scene->ChangeScene(level + 1);
}
}
bool j1Scene::Load(pugi::xml_node& data)
{
level = data.child("level").attribute("current_level").as_int();
time = data.child("time").attribute("sec").as_float();
return true;
}
bool j1Scene::Save(pugi::xml_node& data) const
{
pugi::xml_node pos = data.append_child("level");
pos.append_attribute("current_level") = level;
pugi::xml_node time_node = data.append_child("time");
time_node.append_attribute("sec") = time;
return true;
}
void j1Scene::ChangeLifes()
{
p2List_item<Sprite*>* curr = lives.end;
while (curr->prev != NULL)
{
if (curr->data->isEnabled())
{
curr->data->Enable(false);
break;
}
curr = curr->prev;
}
}
void j1Scene::SumCoin()
{
coin_lab->setString("X%d", App->entities->player.coins);
}
Window* j1Scene::CreateSettingsWindow(int x, int y, SDL_Rect h_slider_bar, SDL_Rect h_slider_idle, SDL_Rect h_slider_hovered, SDL_Rect h_slider_pressed, SDL_Rect button_idle, SDL_Rect button_hover, SDL_Rect button_press)
{
Window_Info w_info;
w_info.x = x;
w_info.y = y;
w_info.content_rect_margins = { 10, 40, 10, 60 };
w_info.tex = settings_win;
w_info.enabled = false;
w_info.OnClose = &Hide_Settings;
Window* settings_window = App->gui->AddWindow(w_info);
Label* music_set_lab = App->gui->AddLabel(15, 80, 30, "gui/Earth 2073.ttf", { 255,255,255,255 });
music_set_lab->SetParent(settings_window);
music_set_lab->SetAnchor(0, 0.5f);
music_set_lab->setString("Music:");
Sprite* music_set_slid = App->gui->AddSprite(settings_window->content_rect.w / 2, 80, sliders, h_slider_bar);
music_set_slid->SetParent(settings_window);
music_set_slid->SetAnchor(0.5f, 0.0f);
music_set_slid->SetContentRect(5, 0, 5, 0);
music_set_slid->culled = false;
Slider* set_mus_slider = App->gui->AddSlider(music_set_slid->content_rect.w / 2, 0, sliders, h_slider_idle, true, &SetVolumeMusic, h_slider_hovered, h_slider_pressed, 1, music_set_slid);
set_mus_slider->culled = false;
set_mus_slider->rel_pos.x = (App->audio->GetVolumeMusic() * music_set_slid->content_rect.w) + set_mus_slider->initial_pos.x - music_set_slid->content_rect.w * music_set_slid->GetAnchorX();
Label* fx_set_lab = App->gui->AddLabel(15, 160, 30, "gui/Earth 2073.ttf", { 255,255,255,255 });
fx_set_lab->SetParent(settings_window);
fx_set_lab->SetAnchor(0, 0.5f);
fx_set_lab->setString("SFX:");
Sprite* fx_set_slid = App->gui->AddSprite(0.5f * settings_window->content_rect.w, 160, sliders, h_slider_bar);
fx_set_slid->SetParent(settings_window);
fx_set_slid->SetAnchor(0.5f, 0.0f);
fx_set_slid->SetContentRect(5, 0, 5, 0);
fx_set_slid->culled = false;
Slider* set_fx_slider = App->gui->AddSlider(fx_set_slid->content_rect.w / 2, 0, sliders, h_slider_idle, true, &SetVolumeFX, h_slider_hovered, h_slider_pressed, 1, fx_set_slid);
set_fx_slider->culled = false;
set_fx_slider->rel_pos.x = (App->audio->GetVolumeFX() * fx_set_slid->content_rect.w) + set_fx_slider->initial_pos.x - fx_set_slid->content_rect.w * fx_set_slid->GetAnchorX();
Label* fps_set_lab = App->gui->AddLabel(15, 240, 30, "gui/Earth 2073.ttf", { 255,255,255,255 });
fps_set_lab->SetParent(settings_window);
fps_set_lab->SetAnchor(0, 0.5f);
fps_set_lab->setString("Framerate:");
Button* fps_button_30 = App->gui->AddButton(0.2f * settings_window->content_rect.w, 290, buttons, button_idle, true, &Fps_30, button_hover, button_press);
fps_button_30->SetParent(settings_window);
Label* fps_label_30 = App->gui->AddLabel(0.5f * fps_button_30->content_rect.w, 0.5f * fps_button_30->content_rect.h, 33, "gui/Earth 2073.ttf", { 255, 255, 255, 255 });
fps_label_30->setString("30 fps");
fps_label_30->SetParent(fps_button_30);
Button* fps_button_60 = App->gui->AddButton(0.5f * settings_window->content_rect.w, 290, buttons, button_idle, true, &Fps_60, button_hover, button_press);
fps_button_60->SetParent(settings_window);
Label* fps_label_60 = App->gui->AddLabel(0.5f * fps_button_60->content_rect.w, 0.5f * fps_button_60->content_rect.h, 33, "gui/Earth 2073.ttf", { 255, 255, 255, 255 });
fps_label_60->setString("60 fps");
fps_label_60->SetParent(fps_button_60);
Button* fps_button_Uncapped = App->gui->AddButton(0.8f * settings_window->content_rect.w, 290, buttons, button_idle, true, &Fps_Uncapped, button_hover, button_press);
fps_button_Uncapped->SetParent(settings_window);
Label* fps_label_Uncapped = App->gui->AddLabel(0.5f * fps_button_Uncapped->content_rect.w, 0.5f * fps_button_Uncapped->content_rect.h, 33, "gui/Earth 2073.ttf", { 255, 255, 255, 255 });
fps_label_Uncapped->setString("Uncapped");
fps_label_Uncapped->SetParent(fps_button_Uncapped);
if (state == IN_GAME) {
Button* exit_button = App->gui->AddButton(0.75f * settings_window->content_rect.w, 360, buttons, button_idle, true, &exit, button_hover, button_press);
Label* exit_label = App->gui->AddLabel(exit_button->content_rect.w / 2, (exit_button->content_rect.h / 2), 33, "gui/Earth 2073.ttf", { 255,255,255,255 });
exit_label->setString("EXIT");
exit_label->SetParent(exit_button);
exit_button->SetParent(settings_window);
Button* menu_button = App->gui->AddButton(0.25f * settings_window->content_rect.w, 360, buttons, button_idle, true, &toMenu, button_hover, button_press);
Label* menu_label = App->gui->AddLabel(menu_button->content_rect.w / 2, (menu_button->content_rect.h / 2), 33, "gui/Earth 2073.ttf", { 255,255,255,255 });
menu_label->setString("To Menu");
menu_label->SetParent(menu_button);
menu_button->SetParent(settings_window);
}
return settings_window;
}
void button_callback(const char* text) {
LOG("%s", text);
}
void StartAlready(int, ...) {
App->Reload();
App->scene->time = 0.f;
App->scene->state = App->scene->IN_GAME;
}
void Game_start(int, ...)
{
App->transition->MakeTransition(&StartAlready, j1Transition::FADE_TO_BLACK);
}
void ContinueAlready(int, ...) {
App->LoadGame();
App->Reload();
App->scene->time = 0.f;
App->scene->state = App->scene->IN_GAME;
}
void Game_continue(int, ...)
{
App->transition->MakeTransition(&ContinueAlready, j1Transition::FADE_TO_BLACK);
}
void Show_Credits(int, ...)
{
App->scene->credits_window->Enable(true);
App->gui->setFocus(App->scene->credits_window);
App->scene->credits_bool = true;
}
void Hide_Credits(int, ...)
{
App->scene->credits_window->Enable(false);
App->scene->credits_bool = false;
}
void Hide_Settings(int, ...)
{
App->scene->settings_window->Enable(false);
App->scene->settings_bool = false;
App->SetTimeScale(1.0f);
}
void Drag_Credits(int, ...)
{
App->scene->credits_text->rel_pos.y = App->scene->credits_text->initial_pos.y + (int)((App->scene->credits_slider->initial_pos.y - App->scene->credits_slider->rel_pos.y) * 2.3f);
}
void exit(int, ...)
{
App->scene->ret = false;
}
void toMenu(int, ...)
{
App->transition->MakeTransition(&DoLoadMenu, j1Transition::FADE_TO_BLACK);
}
void ShowSettings(int, ...) {
App->scene->settings_window->Enable(true);
App->scene->settings_bool = true;
App->SetTimeScale(0.0f);
}
void SetVolumeFX(int n, ...) {
va_list ap;
va_start(ap, n);
double percent = va_arg(ap, double);
va_end(ap);
App->audio->SetVolumeFX((float)percent);
}
void SetVolumeMusic(int n, ...) {
va_list ap;
va_start(ap, n);
double percent = va_arg(ap, double);
va_end(ap);
App->audio->SetVolumeMusic((float)percent);
}
void Fps_30(int, ...)
{
App->SetFramerateCap(30);
}
void Fps_60(int, ...)
{
App->SetFramerateCap(60);
}
void Fps_Uncapped(int, ...)
{
App->SetFramerateCap(-1);
} | 31.588983 | 220 | 0.696624 | marc094 |
4b7c2cf7aa529fad0dd18b5bd2e45c389fc14653 | 2,246 | cpp | C++ | FRAME/MainGUI.cpp | Mr-Devin/GraphicAlgorithm | 58877e6a8dba75ab171b0d89260defaffa22d047 | [
"MIT"
] | 1 | 2021-11-16T11:40:04.000Z | 2021-11-16T11:40:04.000Z | FRAME/MainGUI.cpp | younha169/GraphicAlgorithm | 93287ae4d4171764e788371887c4fd1549304552 | [
"MIT"
] | null | null | null | FRAME/MainGUI.cpp | younha169/GraphicAlgorithm | 93287ae4d4171764e788371887c4fd1549304552 | [
"MIT"
] | null | null | null | //--------------------------------------------------------------------------------------
// Copyright (c) Elay Pu. All rights reserved.
//--------------------------------------------------------------------------------------
#include "MainGUI.h"
#include <vector>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <imgui.h>
#include <examples/imgui_impl_glfw.h>
#include <examples/imgui_impl_opengl3.h>
#include "GLFWWindow.h"
#include "App.h"
#include "ResourceManager.h"
//using namespace ElayGraphics;
//************************************************************************************
//Function:
void CMainGUI::init()
{
ImGui::CreateContext();
m_pIO = &ImGui::GetIO();
ImGui_ImplGlfw_InitForOpenGL(CResourceManager::getOrCreateInstance()->fetchOrCreateGLFWWindow()->fetchWindow(), true);
ImGui_ImplOpenGL3_Init("#version 430");
ImGui::StyleColorsDark();
ImFontConfig IconsConfig;
IconsConfig.MergeMode = true;
m_pDefaultFont.reset(m_pIO->Fonts->AddFontFromFileTTF("../Fonts/roboto-regular.ttf", 18.0));
_ASSERT(m_pDefaultFont);
m_pIO->Fonts->AddFontFromFileTTF("../Fonts/fontawesome-webfont.ttf", 16.0f, &IconsConfig, m_IconRanges.data());
}
//************************************************************************************
//Function:
void CMainGUI::update()
{
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
ImGui::SetColorEditOptions(ImGuiColorEditFlags_PickerHueWheel);
if (m_IsShowDefaultWindow)
{
ImGuiWindowFlags WindowFlag = 0;
WindowFlag |= ImGuiWindowFlags_MenuBar;
ImGui::Begin("Demo Information", &m_IsShowDefaultWindow, WindowFlag);
ImGui::Text("Frame rate: %f, FPS: %d", CApp::getOrCreateInstance()->getFrameRateInMilliSecond(), CApp::getOrCreateInstance()->getFramesPerSecond());
m_IsEndDefaultWindowInCurrentFrame = false;
}
}
//************************************************************************************
//Function:
void CMainGUI::lateUpdate()
{
if (m_IsShowDefaultWindow || !m_IsEndDefaultWindowInCurrentFrame)
{
ImGui::End();
m_IsEndDefaultWindowInCurrentFrame = true;
}
ImGui::Render();
auto p = ImGui::GetDrawData();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
} | 33.522388 | 150 | 0.614426 | Mr-Devin |
4b7d1435e8747147772c0d225d1b5f49f26946eb | 430 | hpp | C++ | include/FileUtil.hpp | Frostie314159/FrostEngine | bb7781c5c90baf77ca836d69d6c38a4a5381e27f | [
"MIT"
] | null | null | null | include/FileUtil.hpp | Frostie314159/FrostEngine | bb7781c5c90baf77ca836d69d6c38a4a5381e27f | [
"MIT"
] | null | null | null | include/FileUtil.hpp | Frostie314159/FrostEngine | bb7781c5c90baf77ca836d69d6c38a4a5381e27f | [
"MIT"
] | null | null | null | #pragma once
#ifndef FILE_UTIL_HPP_
#define FILE_UTIL_HPP_
#include <iostream>
#include <fstream>
#include <regex>
#include <filesystem>
class FileUtil {
public:
static const bool validateFilePath(std::filesystem::path t_filePath);
static void correctInvalidFilePath(std::filesystem::path t_filePath);
static const bool checkFileFlags(std::fstream::openmode t_fileFlags, std::fstream::openmode t_requiredFileFlag);
};
#endif | 25.294118 | 113 | 0.797674 | Frostie314159 |
4b7df69700f9980d1d57f6d4603cdeac7ca4b9fe | 5,197 | cpp | C++ | src/kalman_filter/ukf.cpp | pcdangio/ros-kalman_filter | 0b5653f0ab88931523f5014940228b62f114790b | [
"MIT"
] | 2 | 2021-01-26T15:48:13.000Z | 2021-12-09T13:49:25.000Z | src/kalman_filter/ukf.cpp | pcdangio/ros-kalman_filter | 0b5653f0ab88931523f5014940228b62f114790b | [
"MIT"
] | null | null | null | src/kalman_filter/ukf.cpp | pcdangio/ros-kalman_filter | 0b5653f0ab88931523f5014940228b62f114790b | [
"MIT"
] | 1 | 2021-03-05T16:44:29.000Z | 2021-03-05T16:44:29.000Z | #include <kalman_filter/ukf.hpp>
using namespace kalman_filter;
// CONSTRUCTORS
ukf_t::ukf_t(uint32_t n_variables, uint32_t n_observers)
: base_t(n_variables, n_observers)
{
// Calculate number of sigma points.
ukf_t::n_s = 1 + 2*ukf_t::n_x;
// Allocate weight vector.
ukf_t::wj.setZero(ukf_t::n_s);
// Allocate sigma matrices
ukf_t::X.setZero(ukf_t::n_x, ukf_t::n_s);
ukf_t::Z.setZero(ukf_t::n_z, ukf_t::n_s);
// Allocate interface components.
ukf_t::i_xp.setZero(ukf_t::n_x);
ukf_t::i_x.setZero(ukf_t::n_x);
ukf_t::i_z.setZero(ukf_t::n_z);
// Allocate temporaries.
ukf_t::t_xs.setZero(ukf_t::n_x, ukf_t::n_s);
ukf_t::t_zs.setZero(ukf_t::n_z, ukf_t::n_s);
// Set default parameters.
ukf_t::wo = 0.1;
}
// FILTER METHODS
void ukf_t::iterate()
{
// ---------- STEP 1: PREPARATION ----------
// Calculate weight vector for mean and covariance averaging.
ukf_t::wj.fill((1.0 - ukf_t::wo)/(2.0 * static_cast<double>(ukf_t::n_x)));
ukf_t::wj[0] = ukf_t::wo;
// ---------- STEP 2: PREDICT ----------
// Populate previous state sigma matrix
// Calculate square root of P using Cholseky Decomposition
ukf_t::llt.compute(ukf_t::P);
// Check if calculation succeeded (positive semi definite)
if(ukf_t::llt.info() != Eigen::ComputationInfo::Success)
{
throw std::runtime_error("covariance matrix P is not positive semi definite (predict)");
}
// Reset first column of X.
ukf_t::X.col(0).setZero();
// Fill X with +sqrt(P)
ukf_t::X.block(0,1,ukf_t::n_x,ukf_t::n_x) = ukf_t::llt.matrixL();
// Fill X with -sqrt(P)
ukf_t::X.block(0,1+ukf_t::n_x,ukf_t::n_x,ukf_t::n_x) = -1.0 * ukf_t::X.block(0,1,ukf_t::n_x,ukf_t::n_x);
// Apply sqrt(n+lambda) to entire matrix.
ukf_t::X *= std::sqrt(static_cast<double>(ukf_t::n_x) / (1.0 - ukf_t::wo));
// Add mean to entire matrix.
ukf_t::X += ukf_t::x.replicate(1,ukf_t::n_s);
// Pass previous X through state transition function.
for(uint32_t s = 0; s < ukf_t::n_s; ++s)
{
// Populate interface vector.
ukf_t::i_xp = ukf_t::X.col(s);
ukf_t::i_x.setZero();
// Evaluate state transition.
state_transition(ukf_t::i_xp, ukf_t::i_x);
// Store result back in X.
ukf_t::X.col(s) = ukf_t::i_x;
}
// Calculate predicted state mean.
ukf_t::x.noalias() = ukf_t::X * ukf_t::wj;
// Calculate predicted state covariance.
ukf_t::X -= ukf_t::x.replicate(1, ukf_t::n_s);
ukf_t::t_xs.noalias() = ukf_t::X * ukf_t::wj.asDiagonal();
ukf_t::P.noalias() = ukf_t::t_xs * ukf_t::X.transpose();
ukf_t::P += ukf_t::Q;
// Log predicted state.
ukf_t::log_predicted_state();
// ---------- STEP 3: UPDATE ----------
// Check if update is necessary.
if(ukf_t::has_observations())
{
// Populate predicted state sigma matrix.
// Calculate square root of P using Cholseky Decomposition
ukf_t::llt.compute(ukf_t::P);
// Check if calculation succeeded (positive semi definite)
if(ukf_t::llt.info() != Eigen::ComputationInfo::Success)
{
throw std::runtime_error("covariance matrix P is not positive semi definite (update)");
}
// Reset first column of X.
ukf_t::X.col(0).setZero();
// Fill X with +sqrt(P)
ukf_t::X.block(0,1,ukf_t::n_x,ukf_t::n_x) = ukf_t::llt.matrixL();
// Fill X with -sqrt(P)
ukf_t::X.block(0,1+ukf_t::n_x,ukf_t::n_x,ukf_t::n_x) = -1.0 * ukf_t::X.block(0,1,ukf_t::n_x,ukf_t::n_x);
// Apply sqrt(n+lambda) to entire matrix.
ukf_t::X *= std::sqrt(static_cast<double>(ukf_t::n_x) / (1.0 - ukf_t::wo));
// Add mean to entire matrix.
ukf_t::X += ukf_t::x.replicate(1,ukf_t::n_s);
// Pass predicted X through state transition function.
for(uint32_t s = 0; s < ukf_t::n_s; ++s)
{
// Populate interface vector.
ukf_t::i_x = ukf_t::X.col(s);
ukf_t::i_z.setZero();
// Evaluate state transition.
observation(ukf_t::i_x, ukf_t::i_z);
// Store result back in X.
ukf_t::Z.col(s) = ukf_t::i_z;
}
// Calculate predicted observation mean.
ukf_t::z.noalias() = ukf_t::Z * ukf_t::wj;
// Log predicted observation.
ukf_t::log_observations();
// Calculate predicted observation covariance.
ukf_t::Z -= ukf_t::z.replicate(1, ukf_t::n_s);
ukf_t::t_zs.noalias() = ukf_t::Z * ukf_t::wj.asDiagonal();
ukf_t::S.noalias() = ukf_t::t_zs * ukf_t::Z.transpose();
ukf_t::S += ukf_t::R;
// Calculate predicted state/observation covariance.
ukf_t::X -= ukf_t::x.replicate(1, ukf_t::n_s);
ukf_t::t_xs.noalias() = ukf_t::X * ukf_t::wj.asDiagonal();
ukf_t::C.noalias() = ukf_t::t_xs * ukf_t::Z.transpose();
// Run masked Kalman update.
ukf_t::masked_kalman_update();
}
else
{
// Log empty observations.
ukf_t::log_observations(true);
}
// Log estimated state.
ukf_t::log_estimated_state();
} | 34.646667 | 112 | 0.593612 | pcdangio |
4b7e9f40a8790c25b4b9f92894c350de7c51c8a6 | 2,296 | cpp | C++ | src/exit.cpp | tsung-wei-huang/DtCraft | 80cc9e1195adc0026107814243401a1fc47b5be2 | [
"MIT"
] | 69 | 2019-03-16T20:13:26.000Z | 2022-03-24T14:12:19.000Z | src/exit.cpp | Tsung-Wei/DtCraft | 80cc9e1195adc0026107814243401a1fc47b5be2 | [
"MIT"
] | 12 | 2017-12-02T05:38:30.000Z | 2019-02-08T11:16:12.000Z | src/exit.cpp | Tsung-Wei/DtCraft | 80cc9e1195adc0026107814243401a1fc47b5be2 | [
"MIT"
] | 12 | 2019-04-13T16:27:29.000Z | 2022-01-07T14:42:46.000Z | /******************************************************************************
* *
* Copyright (c) 2018, Tsung-Wei Huang, Chun-Xun Lin, and Martin D. F. Wong, *
* University of Illinois at Urbana-Champaign (UIUC), IL, USA. *
* *
* All Rights Reserved. *
* *
* This program is free software. You can redistribute and/or modify *
* it in accordance with the terms of the accompanying license agreement. *
* See LICENSE in the top-level directory for details. *
* *
******************************************************************************/
#include <dtc/exit.hpp>
namespace dtc {
std::string status_to_string(int status) {
using namespace std::literals::string_literals;
if(WIFEXITED(status)) {
switch(auto code = WEXITSTATUS(status); code) {
case EXIT_SUCCESS:
return "exited ok";
break;
case EXIT_MASTER_FAILED:
return "failed to launch the master";
break;
case EXIT_AGENT_FAILED:
return "failed to launch the agent";
break;
case EXIT_EXECUTOR_FAILED:
return "failed to launch the executor";
break;
case EXIT_BROKEN_CONNECTION:
return "borken connection";
break;
case EXIT_CRITICAL_STREAM:
return "critical stream reached";
break;
case EXIT_CONTAINER_SPAWN_FAILED:
return "container failed";
break;
case EXIT_VERTEX_PROGRAM_FAILED:
return "vertex program failed";
break;
case EXIT_FAILURE:
return "exited with failure";
break;
default:
return "exited with unknown code: "s + std::to_string(code);
break;
};
}
else if(WIFSIGNALED(status)) {
return ::strsignal(WTERMSIG(status));
}
else {
return "error";
}
}
}; // End of namespace dtc. ----------------------------------------------------------------------
| 29.818182 | 99 | 0.452962 | tsung-wei-huang |
4b7fcb485b06402bb384473213e125ab9a1598b9 | 6,255 | cpp | C++ | renderdoc/driver/metal/metal_device.cpp | yanjifa/renderdoc | 308456535f067df15be78de145440c170c2d8c00 | [
"MIT"
] | null | null | null | renderdoc/driver/metal/metal_device.cpp | yanjifa/renderdoc | 308456535f067df15be78de145440c170c2d8c00 | [
"MIT"
] | null | null | null | renderdoc/driver/metal/metal_device.cpp | yanjifa/renderdoc | 308456535f067df15be78de145440c170c2d8c00 | [
"MIT"
] | null | null | null | /******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2022 Baldur Karlsson
*
* 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 "metal_device.h"
#include "metal_helpers_bridge.h"
#include "metal_library.h"
#include "metal_manager.h"
WrappedMTLDevice::WrappedMTLDevice(MTL::Device *realMTLDevice, ResourceId objId)
: WrappedMTLObject(realMTLDevice, objId, this, GetStateRef())
{
objcBridge = AllocateObjCBridge(this);
m_WrappedMTLDevice = this;
threadSerialiserTLSSlot = Threading::AllocateTLSSlot();
m_ResourceManager = new MetalResourceManager(m_State, this);
RDCASSERT(m_WrappedMTLDevice == this);
GetResourceManager()->AddCurrentResource(objId, this);
}
WrappedMTLDevice *WrappedMTLDevice::MTLCreateSystemDefaultDevice(MTL::Device *realMTLDevice)
{
ResourceId objId = ResourceIDGen::GetNewUniqueID();
WrappedMTLDevice *wrappedMTLDevice = new WrappedMTLDevice(realMTLDevice, objId);
return wrappedMTLDevice;
}
template <typename SerialiserType>
bool WrappedMTLDevice::Serialise_newDefaultLibrary(SerialiserType &ser, WrappedMTLLibrary *library)
{
bytebuf buffer;
if(ser.IsWriting())
{
ObjC::Get_defaultLibraryData(buffer);
}
SERIALISE_ELEMENT_LOCAL(Library, GetResID(library)).TypedAs("MTLLibrary"_lit);
SERIALISE_ELEMENT(buffer);
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
// TODO: implement RD MTL replay
}
return true;
}
WrappedMTLLibrary *WrappedMTLDevice::newDefaultLibrary()
{
MTL::Library *realMTLLibrary;
SERIALISE_TIME_CALL(realMTLLibrary = GetReal()->newDefaultLibrary());
WrappedMTLLibrary *wrappedMTLLibrary;
ResourceId id = GetResourceManager()->WrapResource(realMTLLibrary, wrappedMTLLibrary);
if(IsCaptureMode(m_State))
{
Chunk *chunk = NULL;
{
CACHE_THREAD_SERIALISER();
SCOPED_SERIALISE_CHUNK(MetalChunk::MTLDevice_newDefaultLibrary);
Serialise_newDefaultLibrary(ser, wrappedMTLLibrary);
chunk = scope.Get();
}
MetalResourceRecord *record = GetResourceManager()->AddResourceRecord(wrappedMTLLibrary);
record->AddChunk(chunk);
GetResourceManager()->MarkResourceFrameReferenced(id, eFrameRef_Read);
}
else
{
// TODO: implement RD MTL replay
// GetResourceManager()->AddLiveResource(id, wrappedMTLLibrary);
}
return wrappedMTLLibrary;
}
template <typename SerialiserType>
bool WrappedMTLDevice::Serialise_newLibraryWithSource(SerialiserType &ser,
WrappedMTLLibrary *library, NS::String *source,
MTL::CompileOptions *options)
{
SERIALISE_ELEMENT_LOCAL(Library, GetResID(library)).TypedAs("MTLLibrary"_lit);
SERIALISE_ELEMENT(source);
// TODO:SERIALISE_ELEMENT(options);
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
// TODO: implement RD MTL replay
}
return true;
}
WrappedMTLLibrary *WrappedMTLDevice::newLibraryWithSource(NS::String *source,
MTL::CompileOptions *options,
NS::Error **error)
{
MTL::Library *realMTLLibrary;
SERIALISE_TIME_CALL(realMTLLibrary = GetReal()->newLibrary(source, options, error));
WrappedMTLLibrary *wrappedMTLLibrary;
ResourceId id = GetResourceManager()->WrapResource(realMTLLibrary, wrappedMTLLibrary);
if(IsCaptureMode(m_State))
{
Chunk *chunk = NULL;
{
CACHE_THREAD_SERIALISER();
SCOPED_SERIALISE_CHUNK(MetalChunk::MTLDevice_newLibraryWithSource);
Serialise_newLibraryWithSource(ser, wrappedMTLLibrary, source, options);
chunk = scope.Get();
}
MetalResourceRecord *record = GetResourceManager()->AddResourceRecord(wrappedMTLLibrary);
record->AddChunk(chunk);
GetResourceManager()->MarkResourceFrameReferenced(id, eFrameRef_Read);
}
else
{
// TODO: implement RD MTL replay
// GetResourceManager()->AddLiveResource(id, wrappedMTLLibrary);
}
return wrappedMTLLibrary;
}
template bool WrappedMTLDevice::Serialise_newDefaultLibrary(ReadSerialiser &ser,
WrappedMTLLibrary *library);
template bool WrappedMTLDevice::Serialise_newDefaultLibrary(WriteSerialiser &ser,
WrappedMTLLibrary *library);
template bool WrappedMTLDevice::Serialise_newLibraryWithSource(ReadSerialiser &ser,
WrappedMTLLibrary *library,
NS::String *source,
MTL::CompileOptions *options);
template bool WrappedMTLDevice::Serialise_newLibraryWithSource(WriteSerialiser &ser,
WrappedMTLLibrary *library,
NS::String *source,
MTL::CompileOptions *options);
| 39.339623 | 101 | 0.660911 | yanjifa |
4b88766cc5439cafcd78649e59ef0777d9e17ce9 | 514 | cpp | C++ | tests/activation/hard_sigmoid.cpp | Catminusminus/scenn | 69f09449768deec811acea453f9e081c7c170a56 | [
"MIT"
] | 4 | 2019-08-18T10:54:22.000Z | 2021-05-08T17:44:52.000Z | tests/activation/hard_sigmoid.cpp | Catminusminus/scenn | 69f09449768deec811acea453f9e081c7c170a56 | [
"MIT"
] | null | null | null | tests/activation/hard_sigmoid.cpp | Catminusminus/scenn | 69f09449768deec811acea453f9e081c7c170a56 | [
"MIT"
] | null | null | null | #include <scenn/activation/hard_sigmoid.hpp>
#include <scenn/matrix.hpp>
int main() {
using namespace scenn;
constexpr HardSigmoid h;
constexpr float arr[3] = {1.0, 2.0, 3.0};
constexpr auto mat1 = make_vector_from_array(arr);
constexpr auto mat2 = mat1.fmap([](auto&& x) { return hard_sigmoid(x); });
static_assert(h.activate(mat1) == mat2);
constexpr auto mat3 =
mat1.fmap([](auto&& x) { return hard_sigmoid_prime(x); }) * mat1;
static_assert(h.calc_backward_pass(mat1, mat1) == mat3);
}
| 32.125 | 76 | 0.68677 | Catminusminus |
4b959102038536543457c8a4257dbd8ab66815bc | 5,426 | cpp | C++ | windows/commng/vsthost/vsteffect.cpp | whitehara/NP2kai | 72117d7a5def7e6c735f6780d53322c044e2b1d3 | [
"MIT"
] | 170 | 2017-08-15T17:02:36.000Z | 2022-03-30T20:02:26.000Z | windows/commng/vsthost/vsteffect.cpp | whitehara/NP2kai | 72117d7a5def7e6c735f6780d53322c044e2b1d3 | [
"MIT"
] | 138 | 2017-07-09T13:18:51.000Z | 2022-03-20T17:53:43.000Z | windows/commng/vsthost/vsteffect.cpp | whitehara/NP2kai | 72117d7a5def7e6c735f6780d53322c044e2b1d3 | [
"MIT"
] | 53 | 2017-07-17T10:27:42.000Z | 2022-03-15T01:09:05.000Z | /**
* @file vsteffect.cpp
* @brief VST effect クラスの動作の定義を行います
*/
#include <compiler.h>
#include "vsteffect.h"
#include "vsteditwndbase.h"
#ifdef _WIN32
#include <shlwapi.h>
#include <atlbase.h>
#pragma comment(lib, "shlwapi.lib")
#else // _WIN32
#include <dlfcn.h>
#endif // _WIN32
/*! エフェクト ハンドラー */
std::map<AEffect*, CVstEffect*> CVstEffect::sm_effects;
/**
* コンストラクタ
*/
CVstEffect::CVstEffect()
: m_effect(NULL)
, m_hModule(NULL)
, m_lpDir(NULL)
, m_pWnd(NULL)
{
}
/**
* デストラクタ
*/
CVstEffect::~CVstEffect()
{
Unload();
}
/**
* ロードする
* @param[in] lpVst プラグイン
* @retval true 成功
* @retval false 失敗
*/
bool CVstEffect::Load(LPCTSTR lpVst)
{
Unload();
#ifdef _WIN32
/* VSTi読み込み */
HMODULE hModule = ::LoadLibrary(lpVst);
if (hModule == NULL)
{
return false;
}
typedef AEffect* (*FnMain)(::audioMasterCallback audioMaster);
FnMain fnMain = reinterpret_cast<FnMain>(::GetProcAddress(hModule, "VSTPluginMain"));
if (fnMain == NULL)
{
fnMain = reinterpret_cast<FnMain>(::GetProcAddress(hModule, "main"));
}
if (fnMain == NULL)
{
::FreeLibrary(hModule);
return false;
}
// 初期化
AEffect* effect = (*fnMain)(cAudioMasterCallback);
if (effect == NULL)
{
::FreeLibrary(hModule);
return false;
}
if (effect->magic != kEffectMagic)
{
::FreeLibrary(hModule);
return false;
}
TCHAR szDir[MAX_PATH];
::lstrcpyn(szDir, lpVst, _countof(szDir));
::PathRemoveFileSpec(szDir);
USES_CONVERSION;
m_lpDir = ::strdup(T2A(szDir));
#else // _WIN32
/* VSTi読み込み */
void* hModule = ::dlopen(lpVst, 262);
if (hModule == NULL)
{
return false;
}
typedef AEffect* (*FnMain)(::audioMasterCallback audioMaster);
FnMain fnMain = reinterpret_cast<FnMain>(::dlsym(hModule, "VSTPluginMain"));
if (fnMain == NULL)
{
fnMain = reinterpret_cast<FnMain>(::dlsym(hModule, "main"));
}
if (fnMain == NULL)
{
::dlclose(hModule);
return false;
}
// 初期化
AEffect* effect = (*fnMain)(cAudioMasterCallback);
if (effect == NULL)
{
::dlclose(hModule);
return false;
}
if (effect->magic != kEffectMagic)
{
::dlclose(hModule);
return false;
}
m_lpDir = ::strdup(lpVst);
char* pSlash = strrchr(m_lpDir, '/');
if (pSlash)
{
*(pSlash + 1) = 0;
}
else
{
free(m_lpDir);
m_lpDir = NULL;
}
#endif
printf("%d input(s), %d output(s)\n", effect->numInputs, effect->numOutputs);
sm_effects[effect] = this;
m_effect = effect;
m_hModule = hModule;
return true;
}
/**
* アンロードする
*/
void CVstEffect::Unload()
{
if (m_effect)
{
sm_effects.erase(m_effect);
m_effect = NULL;
}
if (m_hModule)
{
#ifdef _WIN32
::FreeLibrary(m_hModule);
#else // _WIN32
::dlclose(m_hModule);
#endif // _WIN32
m_hModule = NULL;
}
if (m_lpDir)
{
free(m_lpDir);
m_lpDir = NULL;
}
}
/**
* ウィンドウ アタッチ
* @param[in] pWnd ハンドル
* @return 以前のハンドル
*/
IVstEditWnd* CVstEffect::Attach(IVstEditWnd* pWnd)
{
IVstEditWnd* pRet = m_pWnd;
m_pWnd = pWnd;
return pRet;
}
/**
* ディスパッチ
* @param[in] opcode The operation code
* @param[in] index The index
* @param[in] value The value
* @param[in] ptr The pointer
* @param[in] opt The option
* @return The result
*/
VstIntPtr CVstEffect::dispatcher(VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
{
if (m_effect)
{
return (*m_effect->dispatcher)(m_effect, opcode, index, value, ptr, opt);
}
return 0;
}
/**
* プロセス
* @param[in] inputs 入力
* @param[in] outputs 出力
* @param[in] sampleFrames サンプル数
*/
void CVstEffect::processReplacing(float** inputs, float** outputs, VstInt32 sampleFrames)
{
if (m_effect)
{
(*m_effect->processReplacing)(m_effect, inputs, outputs, sampleFrames);
}
}
/**
* コールバック
* @param[in] effect The instance of effect
* @param[in] opcode The operation code
* @param[in] index The index
* @param[in] value The value
* @param[in] ptr The pointer
* @param[in] opt The option
* @return The result
*/
VstIntPtr CVstEffect::cAudioMasterCallback(AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
{
switch (opcode)
{
case audioMasterVersion:
return 2400;
default:
break;
}
std::map<AEffect*, CVstEffect*>::iterator it = sm_effects.find(effect);
if (it != sm_effects.end())
{
return it->second->audioMasterCallback(opcode, index, value, ptr, opt);
}
return 0;
}
/**
* コールバック
* @param[in] opcode The operation code
* @param[in] index The index
* @param[in] value The value
* @param[in] ptr The pointer
* @param[in] opt The option
* @return The result
*/
VstIntPtr CVstEffect::audioMasterCallback(VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
{
VstIntPtr ret = 0;
switch (opcode)
{
case audioMasterGetDirectory:
ret = reinterpret_cast<VstIntPtr>(m_lpDir);
break;
case DECLARE_VST_DEPRECATED(audioMasterWantMidi):
break;
case audioMasterSizeWindow:
if (m_pWnd)
{
ret = m_pWnd->OnResize(index, static_cast<VstInt32>(value));
}
break;
case audioMasterUpdateDisplay:
if (m_pWnd)
{
ret = m_pWnd->OnUpdateDisplay();
}
break;
default:
printf("callback: AudioMasterCallback %d %d\n", opcode, index);
break;
}
return ret;
}
| 18.972028 | 132 | 0.630483 | whitehara |
4b97fc074121f45a5bfd6e76fff22b6824ac9477 | 253 | cpp | C++ | Engineers.cpp | Mbedzi346/GeekHubProject | 613fdf9d181fa9c5fa0f8a95d4a94c5faed61255 | [
"MIT"
] | null | null | null | Engineers.cpp | Mbedzi346/GeekHubProject | 613fdf9d181fa9c5fa0f8a95d4a94c5faed61255 | [
"MIT"
] | null | null | null | Engineers.cpp | Mbedzi346/GeekHubProject | 613fdf9d181fa9c5fa0f8a95d4a94c5faed61255 | [
"MIT"
] | null | null | null | //
// Created by Orifha Mbedzi on 2019-10-27.
//
#include "Engineers.h"
Engineers::Engineers(int r) : CrewMember(r) {
}
void Engineers::sendReport(string s) {
auto mediator = getMediator();
this->setReport(s);
mediator->notify(this);
}
| 14.882353 | 45 | 0.656126 | Mbedzi346 |
4b99ae6b65691df5447a53a2aacef224a85b37d5 | 1,817 | cpp | C++ | External/FEXCore/Source/Interface/Core/JIT/Arm64/MoveOps.cpp | duck-37/FEX | fbda0e7ba521d151d3448f5d664da6879686cff8 | [
"MIT"
] | null | null | null | External/FEXCore/Source/Interface/Core/JIT/Arm64/MoveOps.cpp | duck-37/FEX | fbda0e7ba521d151d3448f5d664da6879686cff8 | [
"MIT"
] | null | null | null | External/FEXCore/Source/Interface/Core/JIT/Arm64/MoveOps.cpp | duck-37/FEX | fbda0e7ba521d151d3448f5d664da6879686cff8 | [
"MIT"
] | null | null | null | #include "Interface/Core/JIT/Arm64/JITClass.h"
namespace FEXCore::CPU {
using namespace vixl;
using namespace vixl::aarch64;
#define DEF_OP(x) void JITCore::Op_##x(FEXCore::IR::IROp_Header *IROp, uint32_t Node)
DEF_OP(ExtractElementPair) {
auto Op = IROp->C<IR::IROp_ExtractElementPair>();
switch (Op->Header.Size) {
case 4: {
auto Src = GetSrcPair<RA_32>(Op->Header.Args[0].ID());
std::array<aarch64::Register, 2> Regs = {Src.first, Src.second};
mov (GetReg<RA_32>(Node), Regs[Op->Element]);
break;
}
case 8: {
auto Src = GetSrcPair<RA_64>(Op->Header.Args[0].ID());
std::array<aarch64::Register, 2> Regs = {Src.first, Src.second};
mov (GetReg<RA_64>(Node), Regs[Op->Element]);
break;
}
default: LogMan::Msg::A("Unknown Size"); break;
}
}
DEF_OP(CreateElementPair) {
auto Op = IROp->C<IR::IROp_CreateElementPair>();
switch (Op->Header.Size) {
case 4: {
auto Dst = GetSrcPair<RA_32>(Node);
mov(Dst.first, GetReg<RA_32>(Op->Header.Args[0].ID()));
mov(Dst.second, GetReg<RA_32>(Op->Header.Args[1].ID()));
break;
}
case 8: {
auto Dst = GetSrcPair<RA_64>(Node);
mov(Dst.first, GetReg<RA_64>(Op->Header.Args[0].ID()));
mov(Dst.second, GetReg<RA_64>(Op->Header.Args[1].ID()));
break;
}
default: LogMan::Msg::A("Unknown Size"); break;
}
}
DEF_OP(Mov) {
auto Op = IROp->C<IR::IROp_Mov>();
mov(GetReg<RA_64>(Node), GetReg<RA_64>(Op->Header.Args[0].ID()));
}
#undef DEF_OP
void JITCore::RegisterMoveHandlers() {
#define REGISTER_OP(op, x) OpHandlers[FEXCore::IR::IROps::OP_##op] = &JITCore::Op_##x
REGISTER_OP(EXTRACTELEMENTPAIR, ExtractElementPair);
REGISTER_OP(CREATEELEMENTPAIR, CreateElementPair);
REGISTER_OP(MOV, Mov);
#undef REGISTER_OP
}
}
| 29.786885 | 85 | 0.634012 | duck-37 |
4b9c32f7dd8e1427ed5421190152cd5a1bea3627 | 294 | cpp | C++ | program3/src/main.cpp | CharlesBarone/datastructures-unh-spring2020 | 0d3365ede7d4ecd0ea9d76f41966e72d75e1cf48 | [
"MIT"
] | null | null | null | program3/src/main.cpp | CharlesBarone/datastructures-unh-spring2020 | 0d3365ede7d4ecd0ea9d76f41966e72d75e1cf48 | [
"MIT"
] | null | null | null | program3/src/main.cpp | CharlesBarone/datastructures-unh-spring2020 | 0d3365ede7d4ecd0ea9d76f41966e72d75e1cf48 | [
"MIT"
] | null | null | null | //
// main.cpp
// program3
//
// Created by Charles Barone on 4/22/20.
// Copyright © 2020 Charles Barone. All rights reserved.
//
#include <iostream>
#include "Runner.hpp"
int main(int argc, const char * argv[]) {
Runner* run = new Runner;
run->Begin();
delete run;
return 0;
}
| 14 | 57 | 0.636054 | CharlesBarone |
4ba50879ac6a649e43be1f876d555a2f941f6f51 | 736 | hpp | C++ | include/gpcxx/util.hpp | Rahul-Nirola/gpcxx | 365182b66994f69e8cad6214d4cfa543183d4724 | [
"BSL-1.0"
] | 21 | 2015-05-15T08:01:37.000Z | 2020-11-12T07:28:54.000Z | include/gpcxx/util.hpp | Rahul-Nirola/gpcxx | 365182b66994f69e8cad6214d4cfa543183d4724 | [
"BSL-1.0"
] | 2 | 2015-03-26T23:48:04.000Z | 2016-02-29T14:16:37.000Z | include/gpcxx/util.hpp | Rahul-Nirola/gpcxx | 365182b66994f69e8cad6214d4cfa543183d4724 | [
"BSL-1.0"
] | 9 | 2015-02-12T21:39:01.000Z | 2020-10-01T05:14:08.000Z | /*
* gpcxx/util.hpp
*
* Author: Karsten Ahnert (karsten.ahnert@gmx.de)
* Copyright: Karsten Ahnert
*
* 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)
*/
#ifndef GPCXX_UTIL_HPP_DEFINED
#define GPCXX_UTIL_HPP_DEFINED
#include <gpcxx/util/array_unpack.hpp>
#include <gpcxx/util/assert.hpp>
#include <gpcxx/util/create_random_indices.hpp>
#include <gpcxx/util/exception.hpp>
#include <gpcxx/util/identity.hpp>
#include <gpcxx/util/indent.hpp>
#include <gpcxx/util/iterate_until.hpp>
#include <gpcxx/util/macros.hpp>
#include <gpcxx/util/sort_indices.hpp>
#include <gpcxx/util/version.hpp>
#endif // GPCXX_UTIL_HPP_DEFINED
| 25.37931 | 61 | 0.763587 | Rahul-Nirola |
4ba595a87be9a7038ebef767da16a557aab69522 | 20,506 | cpp | C++ | src/modules/mavlink/mavlink_ftp.cpp | aresmiao/firmware | 6457a9cc60828d8781bed32ae08f4c992ae6e265 | [
"BSD-3-Clause"
] | 18 | 2015-06-11T15:39:39.000Z | 2022-01-13T03:58:19.000Z | src/modules/mavlink/mavlink_ftp.cpp | aresmiao/firmware | 6457a9cc60828d8781bed32ae08f4c992ae6e265 | [
"BSD-3-Clause"
] | 6 | 2015-08-20T22:34:34.000Z | 2020-04-17T03:21:46.000Z | src/modules/mavlink/mavlink_ftp.cpp | Falcon-in-KAU/PX4-Falcon | a82bcbf1d70c71f0e2b282a86029ad614a02ba6d | [
"BSD-3-Clause"
] | 34 | 2015-06-11T15:39:23.000Z | 2021-03-06T09:25:12.000Z | /****************************************************************************
*
* Copyright (c) 2014 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/// @file mavlink_ftp.cpp
/// @author px4dev, Don Gagne <don@thegagnes.com>
#include <crc32.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>
#include "mavlink_ftp.h"
#include "mavlink_tests/mavlink_ftp_test.h"
// Uncomment the line below to get better debug output. Never commit with this left on.
//#define MAVLINK_FTP_DEBUG
MavlinkFTP *
MavlinkFTP::get_server(void)
{
static MavlinkFTP server;
return &server;
}
MavlinkFTP::MavlinkFTP() :
_request_bufs{},
_request_queue{},
_request_queue_sem{},
_utRcvMsgFunc{},
_ftp_test{}
{
// initialise the request freelist
dq_init(&_request_queue);
sem_init(&_request_queue_sem, 0, 1);
// initialize session list
for (size_t i=0; i<kMaxSession; i++) {
_session_fds[i] = -1;
}
// drop work entries onto the free list
for (unsigned i = 0; i < kRequestQueueSize; i++) {
_return_request(&_request_bufs[i]);
}
}
#ifdef MAVLINK_FTP_UNIT_TEST
void
MavlinkFTP::set_unittest_worker(ReceiveMessageFunc_t rcvMsgFunc, MavlinkFtpTest *ftp_test)
{
_utRcvMsgFunc = rcvMsgFunc;
_ftp_test = ftp_test;
}
#endif
void
MavlinkFTP::handle_message(Mavlink* mavlink, mavlink_message_t *msg)
{
// get a free request
struct Request* req = _get_request();
// if we couldn't get a request slot, just drop it
if (req == nullptr) {
warnx("Dropping FTP request: queue full\n");
return;
}
if (msg->msgid == MAVLINK_MSG_ID_FILE_TRANSFER_PROTOCOL) {
mavlink_msg_file_transfer_protocol_decode(msg, &req->message);
#ifdef MAVLINK_FTP_UNIT_TEST
if (!_utRcvMsgFunc) {
warnx("Incorrectly written unit test\n");
return;
}
// We use fake ids when unit testing
req->serverSystemId = MavlinkFtpTest::serverSystemId;
req->serverComponentId = MavlinkFtpTest::serverComponentId;
req->serverChannel = MavlinkFtpTest::serverChannel;
#else
// Not unit testing, use the real thing
req->serverSystemId = mavlink->get_system_id();
req->serverComponentId = mavlink->get_component_id();
req->serverChannel = mavlink->get_channel();
#endif
// This is the system id we want to target when sending
req->targetSystemId = msg->sysid;
if (req->message.target_system == req->serverSystemId) {
req->mavlink = mavlink;
#ifdef MAVLINK_FTP_UNIT_TEST
// We are running in Unit Test mode. Don't queue, just call _worket directly.
_process_request(req);
#else
// We are running in normal mode. Queue the request to the worker
work_queue(LPWORK, &req->work, &MavlinkFTP::_worker_trampoline, req, 0);
#endif
return;
}
}
_return_request(req);
}
/// @brief Queued static work queue routine to handle mavlink messages
void
MavlinkFTP::_worker_trampoline(void *arg)
{
Request* req = reinterpret_cast<Request *>(arg);
MavlinkFTP* server = MavlinkFTP::get_server();
// call the server worker with the work item
server->_process_request(req);
}
/// @brief Processes an FTP message
void
MavlinkFTP::_process_request(Request *req)
{
PayloadHeader *payload = reinterpret_cast<PayloadHeader *>(&req->message.payload[0]);
ErrorCode errorCode = kErrNone;
// basic sanity checks; must validate length before use
if (payload->size > kMaxDataLength) {
errorCode = kErrInvalidDataSize;
goto out;
}
#ifdef MAVLINK_FTP_DEBUG
printf("ftp: channel %u opc %u size %u offset %u\n", req->serverChannel, payload->opcode, payload->size, payload->offset);
#endif
switch (payload->opcode) {
case kCmdNone:
break;
case kCmdTerminateSession:
errorCode = _workTerminate(payload);
break;
case kCmdResetSessions:
errorCode = _workReset(payload);
break;
case kCmdListDirectory:
errorCode = _workList(payload);
break;
case kCmdOpenFileRO:
errorCode = _workOpen(payload, O_RDONLY);
break;
case kCmdCreateFile:
errorCode = _workOpen(payload, O_CREAT | O_EXCL | O_WRONLY);
break;
case kCmdOpenFileWO:
errorCode = _workOpen(payload, O_CREAT | O_WRONLY);
break;
case kCmdReadFile:
errorCode = _workRead(payload);
break;
case kCmdWriteFile:
errorCode = _workWrite(payload);
break;
case kCmdRemoveFile:
errorCode = _workRemoveFile(payload);
break;
case kCmdRename:
errorCode = _workRename(payload);
break;
case kCmdTruncateFile:
errorCode = _workTruncateFile(payload);
break;
case kCmdCreateDirectory:
errorCode = _workCreateDirectory(payload);
break;
case kCmdRemoveDirectory:
errorCode = _workRemoveDirectory(payload);
break;
case kCmdCalcFileCRC32:
errorCode = _workCalcFileCRC32(payload);
break;
default:
errorCode = kErrUnknownCommand;
break;
}
out:
// handle success vs. error
if (errorCode == kErrNone) {
payload->req_opcode = payload->opcode;
payload->opcode = kRspAck;
#ifdef MAVLINK_FTP_DEBUG
warnx("FTP: ack\n");
#endif
} else {
int r_errno = errno;
warnx("FTP: nak %u", errorCode);
payload->req_opcode = payload->opcode;
payload->opcode = kRspNak;
payload->size = 1;
payload->data[0] = errorCode;
if (errorCode == kErrFailErrno) {
payload->size = 2;
payload->data[1] = r_errno;
}
}
// respond to the request
_reply(req);
_return_request(req);
}
/// @brief Sends the specified FTP reponse message out through mavlink
void
MavlinkFTP::_reply(Request *req)
{
PayloadHeader *payload = reinterpret_cast<PayloadHeader *>(&req->message.payload[0]);
payload->seqNumber = payload->seqNumber + 1;
mavlink_message_t msg;
msg.checksum = 0;
#ifndef MAVLINK_FTP_UNIT_TEST
uint16_t len =
#endif
mavlink_msg_file_transfer_protocol_pack_chan(req->serverSystemId, // Sender system id
req->serverComponentId, // Sender component id
req->serverChannel, // Channel to send on
&msg, // Message to pack payload into
0, // Target network
req->targetSystemId, // Target system id
0, // Target component id
(const uint8_t*)payload); // Payload to pack into message
bool success = true;
#ifdef MAVLINK_FTP_UNIT_TEST
// Unit test hook is set, call that instead
_utRcvMsgFunc(&msg, _ftp_test);
#else
Mavlink *mavlink = req->mavlink;
mavlink->lockMessageBufferMutex();
success = mavlink->message_buffer_write(&msg, len);
mavlink->unlockMessageBufferMutex();
#endif
if (!success) {
warnx("FTP TX ERR");
}
#ifdef MAVLINK_FTP_DEBUG
else {
warnx("wrote: sys: %d, comp: %d, chan: %d, checksum: %d",
req->serverSystemId,
req->serverComponentId,
req->serverChannel,
msg.checksum);
}
#endif
}
/// @brief Responds to a List command
MavlinkFTP::ErrorCode
MavlinkFTP::_workList(PayloadHeader* payload)
{
char dirPath[kMaxDataLength];
strncpy(dirPath, _data_as_cstring(payload), kMaxDataLength);
DIR *dp = opendir(dirPath);
if (dp == nullptr) {
warnx("FTP: can't open path '%s'", dirPath);
return kErrFailErrno;
}
#ifdef MAVLINK_FTP_DEBUG
warnx("FTP: list %s offset %d", dirPath, payload->offset);
#endif
ErrorCode errorCode = kErrNone;
struct dirent entry, *result = nullptr;
unsigned offset = 0;
// move to the requested offset
seekdir(dp, payload->offset);
for (;;) {
// read the directory entry
if (readdir_r(dp, &entry, &result)) {
warnx("FTP: list %s readdir_r failure\n", dirPath);
errorCode = kErrFailErrno;
break;
}
// no more entries?
if (result == nullptr) {
if (payload->offset != 0 && offset == 0) {
// User is requesting subsequent dir entries but there were none. This means the user asked
// to seek past EOF.
errorCode = kErrEOF;
}
// Otherwise we are just at the last directory entry, so we leave the errorCode at kErrorNone to signal that
break;
}
uint32_t fileSize = 0;
char buf[256];
char direntType;
// Determine the directory entry type
switch (entry.d_type) {
case DTYPE_FILE:
// For files we get the file size as well
direntType = kDirentFile;
snprintf(buf, sizeof(buf), "%s/%s", dirPath, entry.d_name);
struct stat st;
if (stat(buf, &st) == 0) {
fileSize = st.st_size;
}
break;
case DTYPE_DIRECTORY:
if (strcmp(entry.d_name, ".") == 0 || strcmp(entry.d_name, "..") == 0) {
// Don't bother sending these back
direntType = kDirentSkip;
} else {
direntType = kDirentDir;
}
break;
default:
// We only send back file and diretory entries, skip everything else
direntType = kDirentSkip;
}
if (direntType == kDirentSkip) {
// Skip send only dirent identifier
buf[0] = '\0';
} else if (direntType == kDirentFile) {
// Files send filename and file length
snprintf(buf, sizeof(buf), "%s\t%d", entry.d_name, fileSize);
} else {
// Everything else just sends name
strncpy(buf, entry.d_name, sizeof(buf));
buf[sizeof(buf)-1] = 0;
}
size_t nameLen = strlen(buf);
// Do we have room for the name, the one char directory identifier and the null terminator?
if ((offset + nameLen + 2) > kMaxDataLength) {
break;
}
// Move the data into the buffer
payload->data[offset++] = direntType;
strcpy((char *)&payload->data[offset], buf);
#ifdef MAVLINK_FTP_DEBUG
printf("FTP: list %s %s\n", dirPath, (char *)&payload->data[offset-1]);
#endif
offset += nameLen + 1;
}
closedir(dp);
payload->size = offset;
return errorCode;
}
/// @brief Responds to an Open command
MavlinkFTP::ErrorCode
MavlinkFTP::_workOpen(PayloadHeader* payload, int oflag)
{
int session_index = _find_unused_session();
if (session_index < 0) {
warnx("FTP: Open failed - out of sessions\n");
return kErrNoSessionsAvailable;
}
char *filename = _data_as_cstring(payload);
uint32_t fileSize = 0;
struct stat st;
if (stat(filename, &st) != 0) {
// fail only if requested open for read
if (oflag & O_RDONLY)
return kErrFailErrno;
else
st.st_size = 0;
}
fileSize = st.st_size;
int fd = ::open(filename, oflag);
if (fd < 0) {
return kErrFailErrno;
}
_session_fds[session_index] = fd;
payload->session = session_index;
payload->size = sizeof(uint32_t);
*((uint32_t*)payload->data) = fileSize;
return kErrNone;
}
/// @brief Responds to a Read command
MavlinkFTP::ErrorCode
MavlinkFTP::_workRead(PayloadHeader* payload)
{
int session_index = payload->session;
if (!_valid_session(session_index)) {
return kErrInvalidSession;
}
// Seek to the specified position
#ifdef MAVLINK_FTP_DEBUG
warnx("seek %d", payload->offset);
#endif
if (lseek(_session_fds[session_index], payload->offset, SEEK_SET) < 0) {
// Unable to see to the specified location
warnx("seek fail");
return kErrEOF;
}
int bytes_read = ::read(_session_fds[session_index], &payload->data[0], kMaxDataLength);
if (bytes_read < 0) {
// Negative return indicates error other than eof
warnx("read fail %d", bytes_read);
return kErrFailErrno;
}
payload->size = bytes_read;
return kErrNone;
}
/// @brief Responds to a Write command
MavlinkFTP::ErrorCode
MavlinkFTP::_workWrite(PayloadHeader* payload)
{
int session_index = payload->session;
if (!_valid_session(session_index)) {
return kErrInvalidSession;
}
// Seek to the specified position
#ifdef MAVLINK_FTP_DEBUG
warnx("seek %d", payload->offset);
#endif
if (lseek(_session_fds[session_index], payload->offset, SEEK_SET) < 0) {
// Unable to see to the specified location
warnx("seek fail");
return kErrFailErrno;
}
int bytes_written = ::write(_session_fds[session_index], &payload->data[0], payload->size);
if (bytes_written < 0) {
// Negative return indicates error other than eof
warnx("write fail %d", bytes_written);
return kErrFailErrno;
}
payload->size = sizeof(uint32_t);
*((uint32_t*)payload->data) = bytes_written;
return kErrNone;
}
/// @brief Responds to a RemoveFile command
MavlinkFTP::ErrorCode
MavlinkFTP::_workRemoveFile(PayloadHeader* payload)
{
char file[kMaxDataLength];
strncpy(file, _data_as_cstring(payload), kMaxDataLength);
if (unlink(file) == 0) {
payload->size = 0;
return kErrNone;
} else {
return kErrFailErrno;
}
}
/// @brief Responds to a TruncateFile command
MavlinkFTP::ErrorCode
MavlinkFTP::_workTruncateFile(PayloadHeader* payload)
{
char file[kMaxDataLength];
const char temp_file[] = "/fs/microsd/.trunc.tmp";
strncpy(file, _data_as_cstring(payload), kMaxDataLength);
payload->size = 0;
// emulate truncate(file, payload->offset) by
// copying to temp and overwrite with O_TRUNC flag.
struct stat st;
if (stat(file, &st) != 0) {
return kErrFailErrno;
}
if (!S_ISREG(st.st_mode)) {
errno = EISDIR;
return kErrFailErrno;
}
// check perms allow us to write (not romfs)
if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH))) {
errno = EROFS;
return kErrFailErrno;
}
if (payload->offset == (unsigned)st.st_size) {
// nothing to do
return kErrNone;
}
else if (payload->offset == 0) {
// 1: truncate all data
int fd = ::open(file, O_TRUNC | O_WRONLY);
if (fd < 0) {
return kErrFailErrno;
}
::close(fd);
return kErrNone;
}
else if (payload->offset > (unsigned)st.st_size) {
// 2: extend file
int fd = ::open(file, O_WRONLY);
if (fd < 0) {
return kErrFailErrno;
}
if (lseek(fd, payload->offset - 1, SEEK_SET) < 0) {
::close(fd);
return kErrFailErrno;
}
bool ok = 1 == ::write(fd, "", 1);
::close(fd);
return (ok)? kErrNone : kErrFailErrno;
}
else {
// 3: truncate
if (_copy_file(file, temp_file, payload->offset) != 0) {
return kErrFailErrno;
}
if (_copy_file(temp_file, file, payload->offset) != 0) {
return kErrFailErrno;
}
if (::unlink(temp_file) != 0) {
return kErrFailErrno;
}
return kErrNone;
}
}
/// @brief Responds to a Terminate command
MavlinkFTP::ErrorCode
MavlinkFTP::_workTerminate(PayloadHeader* payload)
{
if (!_valid_session(payload->session)) {
return kErrInvalidSession;
}
::close(_session_fds[payload->session]);
_session_fds[payload->session] = -1;
payload->size = 0;
return kErrNone;
}
/// @brief Responds to a Reset command
MavlinkFTP::ErrorCode
MavlinkFTP::_workReset(PayloadHeader* payload)
{
for (size_t i=0; i<kMaxSession; i++) {
if (_session_fds[i] != -1) {
::close(_session_fds[i]);
_session_fds[i] = -1;
}
}
payload->size = 0;
return kErrNone;
}
/// @brief Responds to a Rename command
MavlinkFTP::ErrorCode
MavlinkFTP::_workRename(PayloadHeader* payload)
{
char oldpath[kMaxDataLength];
char newpath[kMaxDataLength];
char *ptr = _data_as_cstring(payload);
size_t oldpath_sz = strlen(ptr);
if (oldpath_sz == payload->size) {
// no newpath
errno = EINVAL;
return kErrFailErrno;
}
strncpy(oldpath, ptr, kMaxDataLength);
strncpy(newpath, ptr + oldpath_sz + 1, kMaxDataLength);
if (rename(oldpath, newpath) == 0) {
payload->size = 0;
return kErrNone;
} else {
return kErrFailErrno;
}
}
/// @brief Responds to a RemoveDirectory command
MavlinkFTP::ErrorCode
MavlinkFTP::_workRemoveDirectory(PayloadHeader* payload)
{
char dir[kMaxDataLength];
strncpy(dir, _data_as_cstring(payload), kMaxDataLength);
if (rmdir(dir) == 0) {
payload->size = 0;
return kErrNone;
} else {
return kErrFailErrno;
}
}
/// @brief Responds to a CreateDirectory command
MavlinkFTP::ErrorCode
MavlinkFTP::_workCreateDirectory(PayloadHeader* payload)
{
char dir[kMaxDataLength];
strncpy(dir, _data_as_cstring(payload), kMaxDataLength);
if (mkdir(dir, S_IRWXU | S_IRWXG | S_IRWXO) == 0) {
payload->size = 0;
return kErrNone;
} else {
return kErrFailErrno;
}
}
/// @brief Responds to a CalcFileCRC32 command
MavlinkFTP::ErrorCode
MavlinkFTP::_workCalcFileCRC32(PayloadHeader* payload)
{
char file_buf[256];
uint32_t checksum = 0;
ssize_t bytes_read;
strncpy(file_buf, _data_as_cstring(payload), kMaxDataLength);
int fd = ::open(file_buf, O_RDONLY);
if (fd < 0) {
return kErrFailErrno;
}
do {
bytes_read = ::read(fd, file_buf, sizeof(file_buf));
if (bytes_read < 0) {
int r_errno = errno;
::close(fd);
errno = r_errno;
return kErrFailErrno;
}
checksum = crc32part((uint8_t*)file_buf, bytes_read, checksum);
} while (bytes_read == sizeof(file_buf));
::close(fd);
payload->size = sizeof(uint32_t);
*((uint32_t*)payload->data) = checksum;
return kErrNone;
}
/// @brief Returns true if the specified session is a valid open session
bool
MavlinkFTP::_valid_session(unsigned index)
{
if ((index >= kMaxSession) || (_session_fds[index] < 0)) {
return false;
}
return true;
}
/// @brief Returns an unused session index
int
MavlinkFTP::_find_unused_session(void)
{
for (size_t i=0; i<kMaxSession; i++) {
if (_session_fds[i] == -1) {
return i;
}
}
return -1;
}
/// @brief Guarantees that the payload data is null terminated.
/// @return Returns a pointer to the payload data as a char *
char *
MavlinkFTP::_data_as_cstring(PayloadHeader* payload)
{
// guarantee nul termination
if (payload->size < kMaxDataLength) {
payload->data[payload->size] = '\0';
} else {
payload->data[kMaxDataLength - 1] = '\0';
}
// and return data
return (char *)&(payload->data[0]);
}
/// @brief Returns a unused Request entry. NULL if none available.
MavlinkFTP::Request *
MavlinkFTP::_get_request(void)
{
_lock_request_queue();
Request* req = reinterpret_cast<Request *>(dq_remfirst(&_request_queue));
_unlock_request_queue();
return req;
}
/// @brief Locks a semaphore to provide exclusive access to the request queue
void
MavlinkFTP::_lock_request_queue(void)
{
do {}
while (sem_wait(&_request_queue_sem) != 0);
}
/// @brief Unlocks the semaphore providing exclusive access to the request queue
void
MavlinkFTP::_unlock_request_queue(void)
{
sem_post(&_request_queue_sem);
}
/// @brief Returns a no longer needed request to the queue
void
MavlinkFTP::_return_request(Request *req)
{
_lock_request_queue();
dq_addlast(&req->work.dq, &_request_queue);
_unlock_request_queue();
}
/// @brief Copy file (with limited space)
int
MavlinkFTP::_copy_file(const char *src_path, const char *dst_path, size_t length)
{
char buff[512];
int src_fd = -1, dst_fd = -1;
int op_errno = 0;
src_fd = ::open(src_path, O_RDONLY);
if (src_fd < 0) {
return -1;
}
dst_fd = ::open(dst_path, O_CREAT | O_TRUNC | O_WRONLY);
if (dst_fd < 0) {
op_errno = errno;
::close(src_fd);
errno = op_errno;
return -1;
}
while (length > 0) {
ssize_t bytes_read, bytes_written;
size_t blen = (length > sizeof(buff))? sizeof(buff) : length;
bytes_read = ::read(src_fd, buff, blen);
if (bytes_read == 0) {
// EOF
break;
}
else if (bytes_read < 0) {
warnx("cp: read");
op_errno = errno;
break;
}
bytes_written = ::write(dst_fd, buff, bytes_read);
if (bytes_written != bytes_read) {
warnx("cp: short write");
op_errno = errno;
break;
}
length -= bytes_written;
}
::close(src_fd);
::close(dst_fd);
errno = op_errno;
return (length > 0)? -1 : 0;
}
| 24.01171 | 123 | 0.692578 | aresmiao |
4ba835e8ff8db46a9a034f8a7a875d813f6291f2 | 1,497 | cpp | C++ | 数据结构/22.博弈树.cpp | xiabee/BIT-CS | 5d8d8331e6b9588773991a872c259e430ef1eae1 | [
"Apache-2.0"
] | 63 | 2021-01-10T02:32:17.000Z | 2022-03-30T04:08:38.000Z | 数据结构/22.博弈树.cpp | xiabee/BIT-CS | 5d8d8331e6b9588773991a872c259e430ef1eae1 | [
"Apache-2.0"
] | 2 | 2021-06-09T05:38:58.000Z | 2021-12-14T13:53:54.000Z | 数据结构/22.博弈树.cpp | xiabee/BIT-CS | 5d8d8331e6b9588773991a872c259e430ef1eae1 | [
"Apache-2.0"
] | 20 | 2021-01-12T11:49:36.000Z | 2022-03-26T11:04:58.000Z | #define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
const char str1[36] = "(a,(b,(x)),(c,(d),(e,(g),(h)),(f)))";
const char str2[76] = "(a,(b,(c,(d),(e)),(f)),(g,(h),(i)),(j,(k,(m),(n),(o),(p,(r))),(x,(y,(z)))))";
const char str3[76] = "(a,(b,(c,(d),(e)),(f)),(g,(h),(i)),(q,(k,(m),(n),(o),(p,(r))),(x,(y,(z)))))";
int main() {
char str[100] = {'\0'};
int v = scanf("%s", str);
if (strcmp(str, str1) == 0)
printf("a\nb\nx\nc\nd\ne\ng\nh\nf\nWho play first(0: computer; 1: player )?\nplayer:\ncomputer: d\nSorry, you lost.\nContinue(y/n)?\nWho play first(0: computer; 1: player )?\nplayer:\nillegal move.\nplayer:\ncomputer: x\nSorry, you lost.\nContinue(y/n)?\nWho play first(0: computer; 1: player )?\ncomputer: c\nplayer:\nCongratulate, you win.\nContinue(y/n)?\n");
if (strcmp(str, str2) == 0)
printf("a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\nm\nn\no\np\nr\nx\ny\nz\nWho play first(0: computer; 1: player )?\nplayer:\ncomputer: x\nplayer:\ncomputer: z\nSorry, you lost.\nContinue(y/n)?\nWho play first(0: computer; 1: player )?\nplayer:\ncomputer: f\nSorry, you lost.\nContinue(y/n)?\nWho play first(0: computer; 1: player )?\ncomputer: j\nplayer:\ncomputer: m\nSorry, you lost.\nContinue(y/n)?\n");
if (strcmp(str, str3) == 0)
printf("a\nb\nc\nd\ne\nf\ng\nh\ni\nq\nk\nm\nn\no\np\nr\nx\ny\nz\nWho play first(0: computer; 1: player )?\nplayer:\ncomputer: x\nplayer:\nillegal move.\nplayer:\ncomputer: z\nSorry, you lost.\nContinue(y/n)?\n");
return 0;
}
| 78.789474 | 399 | 0.626587 | xiabee |
4bb294c94d7a5f0920171583c13340fce82be993 | 565 | cpp | C++ | 14-virtualFunc/14-virtualFunc/Student.cpp | jianlong108/grammar-of-C-plus-plus | 8eda24baf6bb7c1df9af63287b6c45debf54bc6e | [
"Apache-2.0"
] | null | null | null | 14-virtualFunc/14-virtualFunc/Student.cpp | jianlong108/grammar-of-C-plus-plus | 8eda24baf6bb7c1df9af63287b6c45debf54bc6e | [
"Apache-2.0"
] | null | null | null | 14-virtualFunc/14-virtualFunc/Student.cpp | jianlong108/grammar-of-C-plus-plus | 8eda24baf6bb7c1df9af63287b6c45debf54bc6e | [
"Apache-2.0"
] | null | null | null | //
// Student.cpp
// 12-initializationList
//
// Created by Wangjianlong on 2018/12/23.
// Copyright © 2018 wangjianlong. All rights reserved.
//
#include "Student.hpp"
Student::Student(float score,int age,float height):m_score(score),Person(age,height)
{
cout << "Student(float score,int age,float height)" << endl;
}
Student::Student(float score):m_score(score),Person(0,0)
{
cout << "Student(float score)" << endl;
}
Student::~Student()
{
cout << "~Student()" << endl;
}
void Student::running()
{
cout << "Student::running()" << endl;
}
| 18.833333 | 84 | 0.651327 | jianlong108 |
4bb333abd567c73fd738b998f27c099cebdf11b8 | 5,001 | cpp | C++ | software/firmware/src/badge/GameOfLife.cpp | mwales/defcon25-badge | 40707149a825fe5d7a36ad24db9c9c838f3f9cd0 | [
"MIT"
] | 19 | 2017-07-30T23:21:12.000Z | 2022-03-10T06:16:41.000Z | software/firmware/src/badge/GameOfLife.cpp | mwales/defcon25-badge | 40707149a825fe5d7a36ad24db9c9c838f3f9cd0 | [
"MIT"
] | null | null | null | software/firmware/src/badge/GameOfLife.cpp | mwales/defcon25-badge | 40707149a825fe5d7a36ad24db9c9c838f3f9cd0 | [
"MIT"
] | 8 | 2017-08-07T03:49:00.000Z | 2022-03-10T03:09:34.000Z | #include "GameOfLife.h"
#include "leddc25.h"
#include <stdlib.h>
GameOfLife::GameOfLife() :
Generations(0), CurrentGeneration(0), Neighborhood(0), InternalState(GameOfLife::GAME), DisplayMessageUntil(0) {
}
GameOfLife::~GameOfLife() {
}
//static uint8_t TIMES_SCREEN_SAVER=3; //due to lack of code space to put in configurable sleep time
ErrorType GameOfLife::onInit(RunContext &rc) {
UNUSED(rc);
InternalState = INIT;
return ErrorType();
}
bool GameOfLife::shouldDisplayMessage() {
return HAL_GetTick() < DisplayMessageUntil;
}
static uint8_t noChange = 0;
ReturnStateContext GameOfLife::onRun(RunContext &rc) {
switch (InternalState) {
case INIT: {
rc.getDisplay().fillScreen(RGBColor::BLACK);
DisplayMessageUntil = HAL_GetTick() + 3000;
initGame();
int danceType = rand()%LedDC25::TOTAL_DANCE_TYPES;
rc.getLedControl().setDanceType(LedDC25::LED_DANCE_TYPE(danceType));
noChange = 0;
}
break;
case MESSAGE:
rc.getDisplay().drawString(0, 10, &UtilityBuf[0], RGBColor::BLACK, RGBColor::WHITE, 1, true);
InternalState = TIME_WAIT;
break;
case TIME_WAIT:
if (!shouldDisplayMessage()) {
InternalState = GAME;
rc.getDisplay().fillScreen(RGBColor::BLACK);
}
break;
case GAME: {
if (CurrentGeneration >= Generations) {
InternalState = INIT;
} else {
uint16_t count = 0;
//uint8_t bitToCheck = CurrentGeneration % 32;
for (uint16_t j = 0; j < height; j++) {
for (uint16_t k = 0; k < width; k++) {
if ((gol[j] & (1 << k)) != 0) {
rc.getDisplay().drawPixel(k * 4, j * 2 + 10, RGBColor::WHITE);
count++;
} else {
rc.getDisplay().drawPixel(k * 4, j * 2 + 10, RGBColor::BLACK);
}
}
}
if (0 == count) {
sprintf(&UtilityBuf[0], " ALL DEAD\n After %d\n generations", CurrentGeneration);
CurrentGeneration = Generations + 1;
InternalState = MESSAGE;
DisplayMessageUntil = HAL_GetTick() + 3000;
rc.getDisplay().fillScreen(RGBColor::BLACK);
} else {
uint32_t tmp[sizeof(gol)];
if (!life(&gol[0], Neighborhood, width, height, &tmp[0])) {
noChange++;
if (noChange > 6) {
CurrentGeneration = Generations + 1;
}
}
}
CurrentGeneration++;
}
}
break;
case SLEEP:
break;
}
if (rc.getKB().getLastKeyReleased() == QKeyboard::NO_PIN_SELECTED) {
return ReturnStateContext(this);
} else {
rc.getLedControl().setDanceType(LedDC25::NONE);
return ReturnStateContext(StateFactory::getMenuState());
}
}
ErrorType GameOfLife::onShutdown() {
return ErrorType();
}
void GameOfLife::initGame() {
uint32_t start = HAL_GetTick();
CurrentGeneration = 0;
Neighborhood = (start & 1) == 0 ? 'm' : 'v';
srand(start);
short chanceToBeAlive = rand() % 50;
memset(&gol[0], 0, sizeof(gol));
for (int j = 0; j < height ; j++) {
for (int i = 0; i < width; i++) {
if ((rand() % 100) < chanceToBeAlive) {
gol[j] |= (1 << i);
}
}
}
Generations = 100 + (rand() % 75);
InternalState = MESSAGE;
DisplayMessageUntil = start + 3000;
sprintf(&UtilityBuf[0], " Max\n Generations: %d", Generations);
}
//The life function is the most important function in the program.
//It counts the number of cells surrounding the center cell, and
//determines whether it lives, dies, or stays the same.
bool GameOfLife::life(uint32_t *array, char choice, short width, short height, uint32_t *temp) {
//Copies the main array to a temp array so changes can be entered into a grid
//without effecting the other cells and the calculations being performed on them.
memcpy(&temp[0], &array[0], sizeof(gol));
for (int j = 1; j < height - 1; ++j) {
for (int i = 0; i < width; ++i) {
if (choice == 'm') {
//The Moore neighborhood checks all 8 cells surrounding the current cell in the array.
int count = 0;
count = ((array[j - 1] & (1 << i)) > 0 ? 1 : 0) + ((array[j - 1] & (1 << (i - 1))) > 0 ? 1 : 0)
+ ((array[j] & (1 << (i - 1))) > 0 ? 1 : 0) + ((array[j + 1] & (1 << (i - 1))) > 0 ? 1 : 0)
+ ((array[j + 1] & (1 << i)) > 0 ? 1 : 0) + ((array[j + 1] & (1 << (i + 1))) > 0 ? 1 : 0)
+ ((array[j] & (1 << (i + 1))) > 0 ? 1 : 0) + ((array[j - 1] & (1 << (i + 1))) > 0 ? 1 : 0);
if (count < 2 || count > 3)
temp[j] &= ~(1 << i);
if (count == 3)
temp[j] |= (1 << i);
} else if (choice == 'v') {
//The Von Neumann neighborhood checks only the 4 surrounding cells in the array, (N, S, E, and W).
int count = 0;
count = ((array[j - 1] & (1 << i)) > 0 ? 1 : 0) + ((array[j] & (1 << (i - 1))) > 0 ? 1 : 0)
+ ((array[j + 1] & (1 << i)) > 0 ? 1 : 0) + ((array[j] & (1 << (i + 1))) > 0 ? 1 : 0);
//The cell dies.
if (count < 2 || count > 3)
temp[j] &= ~(1 << i);
//The cell either stays alive, or is "born".
if (count == 3)
temp[j] |= (1 << i);
}
}
}
if (memcmp(&array[0], &temp[0], sizeof(gol)) == 0) {
return false;
} else {
//Copies the completed temp array back to the main array.
memcpy(&array[0], &temp[0], sizeof(gol));
return true;
}
}
| 31.45283 | 114 | 0.594881 | mwales |
4bb7f119c11c8b7c81583da0f525d7381754b600 | 3,657 | hpp | C++ | Engine/EntitySystem/Systems/System.hpp | xubury/FoggyEngine | 1af5b814e9c3946da678be3acf93cd4d89f01c80 | [
"BSD-3-Clause"
] | null | null | null | Engine/EntitySystem/Systems/System.hpp | xubury/FoggyEngine | 1af5b814e9c3946da678be3acf93cd4d89f01c80 | [
"BSD-3-Clause"
] | null | null | null | Engine/EntitySystem/Systems/System.hpp | xubury/FoggyEngine | 1af5b814e9c3946da678be3acf93cd4d89f01c80 | [
"BSD-3-Clause"
] | null | null | null | #ifndef SYSTEM_HPP
#define SYSTEM_HPP
#include <SFML/System.hpp>
#include <cassert>
#include <memory>
#include <unordered_map>
#include "EntitySystem/Defines.hpp"
namespace foggy {
namespace es {
template <typename ENTITY>
class EntityManager;
template <typename ENTITY>
class Entity;
template <typename ENTITY>
class VSystem {
public:
VSystem(const VSystem&) = delete;
VSystem& operator=(const VSystem&) = delete;
virtual ~VSystem() = default;
virtual void update(EntityManager<ENTITY>& entity_manager,
const sf::Time& deltaTime) = 0;
protected:
VSystem() = default;
static uint32_t s_family_counter;
};
template <typename COMPONENT, typename ENTITY>
class System : public VSystem<ENTITY> {
public:
System(const System&) = delete;
System& operator=(const System&) = delete;
System() = default;
virtual ~System() = default;
static uint32_t family();
};
#define ES_INIT_VSYSTEM(ENTITY) \
template <> \
uint32_t foggy::es::VSystem<ENTITY>::s_family_counter = 0;
template <typename ENTITY>
class SystemManager {
public:
SystemManager(const SystemManager&) = delete;
SystemManager& operator=(const SystemManager&) = delete;
SystemManager(EntityManager<ENTITY>& manager);
~SystemManager() = default;
template <typename SYSTEM>
bool add(std::shared_ptr<SYSTEM> ptr);
template <typename SYSTEM, typename... Args>
bool add(Args&&... args);
template <typename SYSTEM>
bool Remove();
template <typename SYSTEM>
SYSTEM* system();
template <typename SYSTEM>
void update(const sf::Time& deltaTime);
void updateAll(const sf::Time& deltaTime);
private:
EntityManager<ENTITY>& m_manager;
std::unordered_map<uint32_t, std::shared_ptr<VSystem<ENTITY>>> m_systems;
};
template <typename COMPONENT, typename ENTITY>
uint32_t System<COMPONENT, ENTITY>::family() {
static uint32_t family = VSystem<ENTITY>::s_family_counter++;
assert(family < MAX_COMPONENTS);
return family;
}
template <typename ENTITY>
SystemManager<ENTITY>::SystemManager(EntityManager<ENTITY>& manager)
: m_manager(manager) {}
template <typename ENTITY>
void SystemManager<ENTITY>::updateAll(const sf::Time& deltaTime) {
for (auto& pair : m_systems) pair.second->update(m_manager, deltaTime);
}
template <typename ENTITY>
template <typename SYSTEM>
bool SystemManager<ENTITY>::add(std::shared_ptr<SYSTEM> ptr) {
if (m_systems.count(SYSTEM::family()) == 0) {
m_systems.insert(std::make_pair(SYSTEM::family(), ptr));
return true;
}
return false;
}
template <typename ENTITY>
template <typename SYSTEM, typename... Args>
bool SystemManager<ENTITY>::add(Args&&... args) {
if (m_systems.count(SYSTEM::family()) == 0) {
m_systems.emplace(
SYSTEM::family(),
std::shared_ptr<SYSTEM>(new SYSTEM(std::forward<Args>(args)...)));
return true;
}
return false;
}
template <typename ENTITY>
template <typename SYSTEM>
bool SystemManager<ENTITY>::Remove() {
if (m_systems.count(SYSTEM::family()) == 0) return false;
m_systems.erase(SYSTEM::family());
return true;
}
template <typename ENTITY>
template <typename SYSTEM>
inline SYSTEM* SystemManager<ENTITY>::system() {
return std::static_pointer_cast<SYSTEM>(m_systems.at(SYSTEM::family()))
.get();
}
template <typename ENTITY>
template <typename SYSTEM>
inline void SystemManager<ENTITY>::update(const sf::Time& deltaTime) {
system<SYSTEM>()->update(m_manager, deltaTime);
}
} // namespace es
} // namespace foggy
#endif /* SYSTEM_HPP */
| 25.22069 | 78 | 0.686628 | xubury |
4bb858310866db8399724a61603954155e422c5e | 12,347 | cpp | C++ | src/HashTable/HashTable.cpp | DDreher/OpenCL-Sandbox | 6baa42a013e2f6de92161f240e97f1ce25d89daa | [
"BSL-1.0"
] | null | null | null | src/HashTable/HashTable.cpp | DDreher/OpenCL-Sandbox | 6baa42a013e2f6de92161f240e97f1ce25d89daa | [
"BSL-1.0"
] | null | null | null | src/HashTable/HashTable.cpp | DDreher/OpenCL-Sandbox | 6baa42a013e2f6de92161f240e97f1ce25d89daa | [
"BSL-1.0"
] | null | null | null | #include "HashTable/HashTable.h"
#include <Base\OpenCLManager.h>
#include "assert.h"
#include "Base\Definitions.h"
#include "Base\Utilities.h"
HashTable::HashTable()
{
// Init random seed
srand(random_seed_);
}
HashTable::~HashTable()
{
// Release buffers
cl_int status = 0;
if(table_buffer_ != 0)
{
status = clReleaseMemObject(table_buffer_);
assert(status == mpp::ReturnCode::CODE_SUCCESS);
}
if (params_buffer_ != 0)
{
status = clReleaseMemObject(params_buffer_);
assert(status == mpp::ReturnCode::CODE_SUCCESS);
}
}
bool HashTable::Init(uint32_t table_size)
{
size_ = static_cast<uint32_t>(ceil(table_size * table_size_factor));
GenerateParams();
OpenCLManager* mgr = OpenCLManager::GetInstance();
assert(mgr != nullptr);
cl_int status = 0;
// 1. Allocate enough memory on GPU to fit hash table
if(table_buffer_ == 0)
{
table_buffer_ = clCreateBuffer(mgr->context, CL_MEM_READ_WRITE, size_ * sizeof(uint64_t), NULL, NULL);
}
// 2. Initialize all the memory with empty elements
std::vector<uint64_t> empty_elements(size_, mpp::constants::EMPTY);
status = clEnqueueWriteBuffer(mgr->command_queue, table_buffer_, CL_TRUE, 0, size_ * sizeof(uint64_t), empty_elements.data(), 0, NULL, NULL);
assert(status == mpp::ReturnCode::CODE_SUCCESS);
return status == mpp::ReturnCode::CODE_SUCCESS;
}
bool HashTable::Init(uint32_t table_size, const std::vector<uint32_t>& keys, const std::vector<uint32_t>& values)
{
bool success = true;
for(current_iteration_ = 0; current_iteration_ < max_reconstructions; ++current_iteration_)
{
Init(table_size);
if(keys.size() > 0)
{
success = Insert(keys, values);
if(success)
{
break;
}
}
}
return success;
}
bool HashTable::Insert(const std::vector<uint32_t>& keys, const std::vector<uint32_t>& values)
{
assert(keys.size() == values.size());
OpenCLManager* mgr = OpenCLManager::GetInstance();
assert(mgr != nullptr);
cl_int status = 0;
// 1. Allocate GPU memory for key-val-pairs to insert, padded to size of wavefront
cl_int next_multiple = static_cast<cl_int>(
Utility::GetNextMultipleOf(static_cast<uint32_t>(keys.size()), static_cast<uint32_t>(mpp::constants::WAVEFRONT_SIZE)));
cl_mem keys_buffer = clCreateBuffer(mgr->context, CL_MEM_READ_WRITE, next_multiple * sizeof(uint32_t), NULL, NULL);
cl_mem values_buffer = clCreateBuffer(mgr->context, CL_MEM_READ_ONLY, next_multiple * sizeof(uint32_t), NULL, NULL);
// 2. Fill buffers
status = clEnqueueWriteBuffer(mgr->command_queue, keys_buffer, CL_TRUE, 0, keys.size() * sizeof(uint32_t), keys.data(), 0, NULL, NULL);
assert(status == mpp::ReturnCode::CODE_SUCCESS);
status = clEnqueueWriteBuffer(mgr->command_queue, values_buffer, CL_TRUE, 0, values.size() * sizeof(uint32_t), values.data(), 0, NULL, NULL);
assert(status == mpp::ReturnCode::CODE_SUCCESS);
// If necessary write padding
if (keys.size() < next_multiple)
{
uint32_t num_padded_elements = next_multiple - static_cast<uint32_t>(keys.size());
std::vector<uint32_t> empty_elements(num_padded_elements, mpp::constants::EMPTY_32);
size_t offset = keys.size() * sizeof(uint32_t);
size_t num_bytes_written = num_padded_elements * sizeof(uint32_t);
status = clEnqueueWriteBuffer(mgr->command_queue, keys_buffer, CL_TRUE, offset, num_bytes_written, empty_elements.data(), 0, NULL, NULL);
assert(status == mpp::ReturnCode::CODE_SUCCESS);
status = clEnqueueWriteBuffer(mgr->command_queue, values_buffer, CL_TRUE, offset, num_bytes_written, empty_elements.data(), 0, NULL, NULL);
assert(status == mpp::ReturnCode::CODE_SUCCESS);
}
// 3. Construct status buffer
cl_mem status_buffer = clCreateBuffer(mgr->context, CL_MEM_READ_WRITE, sizeof(uint32_t), NULL, NULL);
int intital_status = 0;
status = clEnqueueWriteBuffer(mgr->command_queue, status_buffer, CL_TRUE, 0, sizeof(uint32_t), &intital_status, 0, NULL, NULL);
assert(status == mpp::ReturnCode::CODE_SUCCESS);
// 4. Run kernel
const cl_kernel kernel_hashtable_insert = mgr->kernel_map[mpp::kernels::HASHTABLE_INSERT];
// args: __global uint32_t* keys, __global uint32_t* values, __global uint64_t* table, __constant uint32_t* params, __global uint32_t* out_status
status = clSetKernelArg(kernel_hashtable_insert, 0, sizeof(cl_mem), (void*)&keys_buffer);
assert(status == mpp::ReturnCode::CODE_SUCCESS);
status = clSetKernelArg(kernel_hashtable_insert, 1, sizeof(cl_mem), (void*)&values_buffer);
assert(status == mpp::ReturnCode::CODE_SUCCESS);
status = clSetKernelArg(kernel_hashtable_insert, 2, sizeof(cl_mem), (void*)&table_buffer_);
assert(status == mpp::ReturnCode::CODE_SUCCESS);
status = clSetKernelArg(kernel_hashtable_insert, 3, sizeof(cl_mem), (void*)¶ms_buffer_);
assert(status == mpp::ReturnCode::CODE_SUCCESS);
status = clSetKernelArg(kernel_hashtable_insert, 4, sizeof(cl_mem), (void*)&status_buffer);
assert(status == mpp::ReturnCode::CODE_SUCCESS);
size_t global_work_size[1] = { static_cast<size_t>(next_multiple) };
size_t local_work_size[1] = { std::min(static_cast<size_t>(THREAD_BLOCK_SIZE), static_cast<size_t>(next_multiple)) };
status = clEnqueueNDRangeKernel(mgr->command_queue, kernel_hashtable_insert, 1, NULL, global_work_size, local_work_size, 0, NULL, NULL);
assert(status == mpp::ReturnCode::CODE_SUCCESS);
// 5. Error checking - Check if max iterations have been exceeded
// In theory we could check which elements failed to be inserted, then take the original state of the hashtable, generate new hash parameters and then reconstruct the hashtable
// from scratch. There probably are elements left which could not be inserted due to collision though...
// For now it's assumed that insert is only called once.
uint32_t kernel_status = mpp::ReturnCode::CODE_SUCCESS;
status = clEnqueueReadBuffer(mgr->command_queue, status_buffer, CL_TRUE, 0, sizeof(uint32_t), &kernel_status, 0, NULL, NULL);
assert(status == mpp::ReturnCode::CODE_SUCCESS);
// DEBUG - Check which/how many elements failed to be inserted
//if(kernel_status != mpp::ReturnCode::CODE_SUCCESS)
//{
// std::vector<uint32_t> status_per_element(next_multiple);
// status = clEnqueueReadBuffer(mgr->command_queue, keys_buffer, CL_TRUE, 0, next_multiple * sizeof(uint32_t), status_per_element.data(), 0, NULL, NULL);
// assert(status == mpp::ReturnCode::CODE_SUCCESS);
// // Assume that 0 and 1 are never used as keys for debug purposes
// uint32_t num_unresolved_collisions = static_cast<uint32_t>(std::count(status_per_element.begin(), status_per_element.end(), mpp::ReturnCode::CODE_ERROR));
// std::cout << "Host Table construction iteration: " << current_iteration_ << " Num unresolved collisions: " << num_unresolved_collisions << std::endl;
//}
// 6. Cleanup -> Release buffers
status = clReleaseMemObject(keys_buffer);
assert(status == mpp::ReturnCode::CODE_SUCCESS);
status = clReleaseMemObject(values_buffer);
assert(status == mpp::ReturnCode::CODE_SUCCESS);
status = clReleaseMemObject(status_buffer);
assert(status == mpp::ReturnCode::CODE_SUCCESS);
return kernel_status == mpp::ReturnCode::CODE_SUCCESS;
}
std::vector<uint32_t> HashTable::Retrieve(const std::vector<uint32_t>& keys)
{
OpenCLManager* mgr = OpenCLManager::GetInstance();
assert(mgr != nullptr);
cl_int status = 0;
// 1. Allocate GPU memory
cl_int next_multiple = static_cast<cl_int>(
Utility::GetNextMultipleOf(static_cast<uint32_t>(keys.size()), static_cast<uint32_t>(mpp::constants::WAVEFRONT_SIZE)));
cl_mem keys_buffer = clCreateBuffer(mgr->context, CL_MEM_READ_ONLY, next_multiple * sizeof(uint32_t), NULL, NULL);
cl_mem vals_buffer = clCreateBuffer(mgr->context, CL_MEM_READ_WRITE, next_multiple * sizeof(uint32_t), NULL, NULL);
// 2. Fill buffer
status = clEnqueueWriteBuffer(mgr->command_queue, keys_buffer, CL_TRUE, 0, keys.size() * sizeof(uint32_t), keys.data(), 0, NULL, NULL);
assert(status == mpp::ReturnCode::CODE_SUCCESS);
// If necessary write padding
if (keys.size() < next_multiple)
{
uint32_t num_padded_elements = next_multiple - static_cast<uint32_t>(keys.size());
std::vector<uint32_t> empty_elements(num_padded_elements, mpp::constants::EMPTY_32);
size_t offset = keys.size() * sizeof(uint32_t);
size_t num_bytes_written = num_padded_elements * sizeof(uint32_t);
status = clEnqueueWriteBuffer(mgr->command_queue, keys_buffer, CL_TRUE, offset, num_bytes_written, empty_elements.data(), 0, NULL, NULL);
assert(status == mpp::ReturnCode::CODE_SUCCESS);
}
// 3. Construct parameters buffer
cl_mem params_buffer = clCreateBuffer(mgr->context, CL_MEM_READ_WRITE, params_.size() * sizeof(uint32_t), NULL, NULL);
status = clEnqueueWriteBuffer(mgr->command_queue, params_buffer, CL_TRUE, 0, params_.size() * sizeof(uint32_t), params_.data(), 0, NULL, NULL);
assert(status == mpp::ReturnCode::CODE_SUCCESS);
// 4. invoke retrieve kernel
const cl_kernel kernel_hashtable_retrieve = mgr->kernel_map[mpp::kernels::HASHTABLE_RETRIEVE];
// params: __global int32_t* keys, __global int64_t* table, __constant uint32_t* params
status = clSetKernelArg(kernel_hashtable_retrieve, 0, sizeof(cl_mem), (void*)&keys_buffer);
assert(status == mpp::ReturnCode::CODE_SUCCESS);
status = clSetKernelArg(kernel_hashtable_retrieve, 1, sizeof(cl_mem), (void*)&vals_buffer);
assert(status == mpp::ReturnCode::CODE_SUCCESS);
status = clSetKernelArg(kernel_hashtable_retrieve, 2, sizeof(cl_mem), (void*)&table_buffer_);
assert(status == mpp::ReturnCode::CODE_SUCCESS);
status = clSetKernelArg(kernel_hashtable_retrieve, 3, sizeof(cl_mem), (void*)¶ms_buffer);
assert(status == mpp::ReturnCode::CODE_SUCCESS);
size_t global_work_size[1] = { static_cast<size_t>(next_multiple) };
size_t local_work_size[1] = { std::min(static_cast<size_t>(THREAD_BLOCK_SIZE), static_cast<size_t>(next_multiple)) };
status = clEnqueueNDRangeKernel(mgr->command_queue, kernel_hashtable_retrieve, 1, NULL, global_work_size, local_work_size, 0, NULL, NULL);
assert(status == mpp::ReturnCode::CODE_SUCCESS);
// 5. Read back results
std::vector<uint32_t> retrieved_entries(next_multiple);
status = clEnqueueReadBuffer(mgr->command_queue, vals_buffer, CL_TRUE, 0, next_multiple * sizeof(uint32_t), retrieved_entries.data(), 0, NULL, NULL);
assert(status == mpp::ReturnCode::CODE_SUCCESS);
// 6. Release buffers
status = clReleaseMemObject(keys_buffer);
assert(status == mpp::ReturnCode::CODE_SUCCESS);
status = clReleaseMemObject(vals_buffer);
assert(status == mpp::ReturnCode::CODE_SUCCESS);
status = clReleaseMemObject(params_buffer);
assert(status == mpp::ReturnCode::CODE_SUCCESS);
retrieved_entries.resize(keys.size());
return retrieved_entries;
}
void HashTable::GenerateParams()
{
params_[PARAM_IDX_HASHFUNC_A_0] = rand();
params_[PARAM_IDX_HASHFUNC_B_0] = rand();
params_[PARAM_IDX_HASHFUNC_A_1] = rand();
params_[PARAM_IDX_HASHFUNC_B_1] = rand();
params_[PARAM_IDX_HASHFUNC_A_2] = rand();
params_[PARAM_IDX_HASHFUNC_B_2] = rand();
params_[PARAM_IDX_HASHFUNC_A_3] = rand();
params_[PARAM_IDX_HASHFUNC_B_3] = rand();
params_[PARAM_IDX_MAX_ITERATIONS] = max_iterations;
params_[PARAM_IDX_TABLESIZE] = size_;
OpenCLManager* mgr = OpenCLManager::GetInstance();
assert(mgr != nullptr);
cl_int status = 0;
if (params_buffer_ != 0)
{
status = clReleaseMemObject(params_buffer_);
assert(status == mpp::ReturnCode::CODE_SUCCESS);
}
params_buffer_ = clCreateBuffer(mgr->context, CL_MEM_READ_ONLY, params_.size() * sizeof(uint32_t), NULL, NULL);
status = clEnqueueWriteBuffer(mgr->command_queue, params_buffer_, CL_TRUE, 0, params_.size() * sizeof(uint32_t), params_.data(), 0, NULL, NULL);
assert(status == mpp::ReturnCode::CODE_SUCCESS);
}
| 47.856589 | 180 | 0.710618 | DDreher |
4bb88d7ee18dfb726c52c636d826b100787fa7bd | 2,614 | hh | C++ | StoppingTargetGeom/inc/TargetFoilSupportStructure.hh | bonventre/Offline | 77db9d6368f27ab9401c690c2c2a4257ade6c231 | [
"Apache-2.0"
] | 1 | 2021-06-25T00:00:12.000Z | 2021-06-25T00:00:12.000Z | StoppingTargetGeom/inc/TargetFoilSupportStructure.hh | bonventre/Offline | 77db9d6368f27ab9401c690c2c2a4257ade6c231 | [
"Apache-2.0"
] | 1 | 2019-11-22T14:45:51.000Z | 2019-11-22T14:50:03.000Z | StoppingTargetGeom/inc/TargetFoilSupportStructure.hh | bonventre/Offline | 77db9d6368f27ab9401c690c2c2a4257ade6c231 | [
"Apache-2.0"
] | 2 | 2019-10-14T17:46:58.000Z | 2020-03-30T21:05:15.000Z | #ifndef StoppingTargetGeom_TargetFoilSupportStructure_hh
#define StoppingTargetGeom_TargetFoilSupportStructure_hh
//
// Class to represent one support structure of one target foil.
//
// $Id: TargetFoilSupportStructure.hh,v 1.1 2013/10/14 23:57:32 roehrken Exp $
// $Author: roehrken $
// $Date: 2013/10/14 23:57:32 $
//
// Original author Rob Kutschke
//
// Coordinates are given in the detector coordinate
// system in mm.
//
#include <string>
// Includes from CLHEP
#include "CLHEP/Vector/ThreeVector.h"
namespace mu2e {
class TargetFoilSupportStructure {
public:
TargetFoilSupportStructure( int support_id, int foil_id,
CLHEP::Hep3Vector const& foilCenterInMu2e,
CLHEP::Hep3Vector const& n,
double radius,
double length,
double angleOffset,
double foil_outer_radius,
std::string m,
const CLHEP::Hep3Vector& detSysOrigin
):
_support_id(support_id),
_foil_id(foil_id),
_centerInMu2e(foilCenterInMu2e),
_centerInDetectorSystem(foilCenterInMu2e - detSysOrigin),
_norm(n),
_radius(radius),
_length(length),
_angleOffset(angleOffset),
_foil_outer_radius(foil_outer_radius),
_material(m){
}
// Use compiler-generated copy c'tor, copy assignment, and d'tor
int support_id() const { return _support_id; }
int foil_id() const { return _foil_id; }
CLHEP::Hep3Vector const& centerInMu2e() const { return _centerInMu2e;}
CLHEP::Hep3Vector const& centerInDetectorSystem() const { return _centerInDetectorSystem;}
CLHEP::Hep3Vector const& normal() const { return _norm;}
double radius() const { return _radius;}
double length() const { return _length;}
double angleOffset() const { return _angleOffset;}
double foil_outer_radius() const { return _foil_outer_radius;}
std::string material() const { return _material;}
private:
int _support_id;
int _foil_id;
// Center of the foil.
CLHEP::Hep3Vector _centerInMu2e;
CLHEP::Hep3Vector _centerInDetectorSystem;
// "+z" normal vector
CLHEP::Hep3Vector _norm;
double _radius; // radius of the supporting structure wire
double _length; // length of the supporting structure wire
double _angleOffset; // angle of first support wire wrt vertical
double _foil_outer_radius; // outer radius of the foil the wire connects to
std::string _material;
};
}
#endif /* StoppingTargetGeom_TargetFoilSupportStructure_hh */
| 29.044444 | 95 | 0.674445 | bonventre |
4bb92c8639aa50eda352757ba82670bb823ff970 | 2,235 | cpp | C++ | examples/0120-template-classes/exp/example.cpp | satya-das/cib | 369333ea58b0530b8789a340e21096ba7d159d0e | [
"MIT"
] | 30 | 2018-03-05T17:35:29.000Z | 2022-03-17T18:59:34.000Z | examples/0120-template-classes/exp/example.cpp | satya-das/cib | 369333ea58b0530b8789a340e21096ba7d159d0e | [
"MIT"
] | 2 | 2016-05-26T04:47:13.000Z | 2019-02-15T05:17:43.000Z | examples/0120-template-classes/exp/example.cpp | satya-das/cib | 369333ea58b0530b8789a340e21096ba7d159d0e | [
"MIT"
] | 5 | 2019-02-15T05:09:22.000Z | 2021-04-14T12:10:16.000Z | #include "example.h"
#include "value.h"
namespace Example {
Example::A::A(__zz_cib_AbiType h)
: __zz_cib_h_(h)
{}
Example::A::A(A&& rhs)
: __zz_cib_h_(rhs.__zz_cib_h_)
{
rhs.__zz_cib_h_ = nullptr;
}
Example::A::A()
: Example::A(__zz_cib_MyHelper::__zz_cib_New_0())
{}
Example::A::A(const ::Example::A& __zz_cib_param0)
: Example::A(__zz_cib_MyHelper::__zz_cib_Copy_1(
__zz_cib_::__zz_cib_ToAbiType<decltype(__zz_cib_param0)>(__zz_cib_param0)))
{}
Example::A::~A() {
auto h = __zz_cib_MyHelper::__zz_cib_ReleaseHandle(this);
__zz_cib_MyHelper::__zz_cib_Delete_2(
h
);
}
void Example::A::Set(const ::Example::Value<int>& x) {
__zz_cib_MyHelper::Set_3<__zz_cib_::__zz_cib_AbiType_t<void>>(
__zz_cib_::__zz_cib_ToAbiType<decltype(this)>(this),
__zz_cib_::__zz_cib_ToAbiType<decltype(x)>(x)
);
}
::Example::Value<int> Example::A::Get() const {
return __zz_cib_::__zz_cib_FromAbiType<::Example::Value<int>>(
__zz_cib_MyHelper::Get_4<__zz_cib_::__zz_cib_AbiType_t<::Example::Value<int>>>(
__zz_cib_::__zz_cib_ToAbiType<decltype(this)>(this)
)
);
}
void Example::A::SetInt(const ::Example::Value<::Example::Int>& y) {
__zz_cib_MyHelper::SetInt_5<__zz_cib_::__zz_cib_AbiType_t<void>>(
__zz_cib_::__zz_cib_ToAbiType<decltype(this)>(this),
__zz_cib_::__zz_cib_ToAbiType<decltype(y)>(y)
);
}
::Example::Value<::Example::Int> Example::A::GetInt() const {
return __zz_cib_::__zz_cib_FromAbiType<::Example::Value<::Example::Int>>(
__zz_cib_MyHelper::GetInt_6<__zz_cib_::__zz_cib_AbiType_t<::Example::Value<::Example::Int>>>(
__zz_cib_::__zz_cib_ToAbiType<decltype(this)>(this)
)
);
}
void Example::A::SetFloat(::Example::Value<float> f) {
__zz_cib_MyHelper::SetFloat_7<__zz_cib_::__zz_cib_AbiType_t<void>>(
__zz_cib_::__zz_cib_ToAbiType<decltype(this)>(this),
__zz_cib_::__zz_cib_ToAbiType<decltype(f)>(std::move(f))
);
}
::Example::Value<float> Example::A::GetFloat() const {
return __zz_cib_::__zz_cib_FromAbiType<::Example::Value<float>>(
__zz_cib_MyHelper::GetFloat_8<__zz_cib_::__zz_cib_AbiType_t<::Example::Value<float>>>(
__zz_cib_::__zz_cib_ToAbiType<decltype(this)>(this)
)
);
}
}
| 29.025974 | 97 | 0.699776 | satya-das |
4bc1d5e4fa3415db6afe1c4c008ff2dc86b5ca41 | 1,429 | cc | C++ | systemc-utils/bca-subset/src/sysc/kernel/sc_module.cc | hhonda68/handy-eda-utils | 1ff761d2a30d76681d0047e62663cb42f6622d69 | [
"MIT"
] | null | null | null | systemc-utils/bca-subset/src/sysc/kernel/sc_module.cc | hhonda68/handy-eda-utils | 1ff761d2a30d76681d0047e62663cb42f6622d69 | [
"MIT"
] | null | null | null | systemc-utils/bca-subset/src/sysc/kernel/sc_module.cc | hhonda68/handy-eda-utils | 1ff761d2a30d76681d0047e62663cb42f6622d69 | [
"MIT"
] | null | null | null | //
// Minimal synthesizable BCA subset of SystemC.
//
// Copyright (c) 2008 the handy-eda-utils developer(s).
// Distributed under the MIT License.
// (See accompanying file COPYING or copy at
// http://www.opensource.org/licenses/mit-license.php.)
#include "sc_module.h"
#include <string>
namespace sc_core {
sc_sensitive sc_module::sensitive;
struct sc_module::impl_t {
const ::std::string basename;
const sc_module* parent;
mutable ::std::string name;
impl_t() : basename(the_simcontext->scmodule_basename()), parent(the_simcontext->scmodule_parent()) {}
};
const char* sc_module::basename() const { return m.basename.c_str(); }
const char* sc_module::name() const
{
if (m.name.empty()) {
if (m.parent == 0) {
m.name = m.basename;
} else {
m.parent->name(); // initialize m.parent->m.name if necessary
m.name = m.parent->m.name + "." + m.basename;
}
}
return m.name.c_str();
}
sc_module::sc_module() : m(*(new impl_t))
{
the_simcontext->construct_scmodule(this);
}
void sc_module::reset_signal_is(sc_in<bool>& port, bool polarity)
{
the_simcontext->register_reset_port(port);
the_simcontext->mark_cthread_as_resettable();
}
void sc_module::reset_signal_is(sc_signal<bool>& sig, bool polarity)
{
the_simcontext->mark_cthread_as_resettable();
}
void sc_module::set_stack_size(int size)
{
the_simcontext->set_cthread_stack_size(size);
}
} // namespace sc_core
| 23.048387 | 104 | 0.703289 | hhonda68 |
4bc4102582cb459cb8c2e7f212d90938a196d612 | 943 | cpp | C++ | wfc/winterface.cpp | mambaru/wfc | 170bf87302487c0cedc40b47c84447a765894774 | [
"MIT"
] | 1 | 2018-10-18T10:15:53.000Z | 2018-10-18T10:15:53.000Z | wfc/winterface.cpp | mambaru/wfc | 170bf87302487c0cedc40b47c84447a765894774 | [
"MIT"
] | 7 | 2019-12-04T23:36:03.000Z | 2021-04-21T12:37:07.000Z | wfc/winterface.cpp | mambaru/wfc | 170bf87302487c0cedc40b47c84447a765894774 | [
"MIT"
] | null | null | null | #include <wfc/winterface.hpp>
namespace wfc{
winterface::winterface(std::weak_ptr<iinterface> target, bool suspend)
: _target(target)
, _suspend(suspend)
{}
void winterface::unreg_io(io_id_t id)
{
auto target = _target.lock();
if ( !_suspend && target!=nullptr )
{
target->unreg_io(id);
}
}
void winterface::reg_io(io_id_t id, std::weak_ptr<iinterface> itf)
{
auto target = _target.lock();
if ( !_suspend && target!=nullptr )
{
target->reg_io(id, itf);
}
}
void winterface::perform_io(data_ptr d, io_id_t id, output_handler_t cb)
{
auto target = _target.lock();
if ( !_suspend && target!=nullptr )
{
target->perform_io(std::move(d), id, cb);
}
else if (_suspend)
{
cb(std::move(d));
}
else
{
cb(nullptr);
}
}
void winterface::set_target(std::weak_ptr<iinterface> target)
{
_target = target;
}
void winterface::set_suspend( bool suspend)
{
_suspend = suspend;
}
}
| 16.54386 | 72 | 0.646872 | mambaru |
4bcd317bc8d66f535e10ccaf61d9f5ae14b1b533 | 1,679 | cpp | C++ | Game/Game/src/Game.cpp | ParachanActionGame-Project/KurachanActionGame | af85abcf3c9554f04cacd8686140eb59242463ae | [
"BSD-2-Clause"
] | null | null | null | Game/Game/src/Game.cpp | ParachanActionGame-Project/KurachanActionGame | af85abcf3c9554f04cacd8686140eb59242463ae | [
"BSD-2-Clause"
] | 10 | 2021-09-24T11:40:45.000Z | 2021-10-30T04:59:13.000Z | Game/Game/src/Game.cpp | ParachanActionGame-Project/KurachanActionGame | af85abcf3c9554f04cacd8686140eb59242463ae | [
"BSD-2-Clause"
] | null | null | null |
# include "Game.hpp"
Game::Game(const InitData& init)
: IScene(init)
{
// 横 (Scene::Width() / blockSize.x) 個、縦 5 個のブロックを配列に追加する
for (auto p : step(Size((Scene::Width() / blockSize.x), 5)))
{
m_blocks << Rect(p.x * blockSize.x, 60 + p.y * blockSize.y, blockSize);
}
}
void Game::update()
{
// パドルを操作
m_paddle = Rect(Arg::center(Cursor::Pos().x, 500), 60, 10);
// ボールを移動
m_ball.moveBy(m_ballVelocity * Scene::DeltaTime());
// ブロックを順にチェック
for (auto it = m_blocks.begin(); it != m_blocks.end(); ++it)
{
// ボールとブロックが交差していたら
if (it->intersects(m_ball))
{
// ボールの向きを反転する
(it->bottom().intersects(m_ball) || it->top().intersects(m_ball) ? m_ballVelocity.y : m_ballVelocity.x) *= -1;
// ブロックを配列から削除(イテレータが無効になるので注意)
m_blocks.erase(it);
// スコアを加算
++m_score;
// これ以上チェックしない
break;
}
}
// 天井にぶつかったらはね返る
if (m_ball.y < 0 && m_ballVelocity.y < 0)
{
m_ballVelocity.y *= -1;
}
if (m_ball.y > Scene::Height())
{
changeScene(State::Title);
getData().highScore = Max(getData().highScore, m_score);
}
// 左右の壁にぶつかったらはね返る
if ((m_ball.x < 0 && m_ballVelocity.x < 0) || (Scene::Width() < m_ball.x && m_ballVelocity.x > 0))
{
m_ballVelocity.x *= -1;
}
// パドルにあたったらはね返る
if (m_ballVelocity.y > 0 && m_paddle.intersects(m_ball))
{
// パドルの中心からの距離に応じてはね返る向きを変える
m_ballVelocity = Vec2((m_ball.x - m_paddle.center().x) * 10, -m_ballVelocity.y).setLength(speed);
}
}
void Game::draw() const
{
FontAsset(U"Score")(m_score).drawAt(Scene::Center().x, 30);
// すべてのブロックを描画する
for (const auto& block : m_blocks)
{
block.stretched(-1).draw(HSV(block.y - 40));
}
// ボールを描く
m_ball.draw();
// パドルを描く
m_paddle.draw();
}
| 19.988095 | 113 | 0.628946 | ParachanActionGame-Project |
4bcf10bc4af2432076c85c4568fb4308e0287f58 | 628 | cpp | C++ | AtiRoNya/Bridge/Array/Array.cpp | AtiLion/AtiRoNya | e20e4a8fc47b37834c8284f9e6e937f04a84c510 | [
"MIT"
] | 25 | 2019-10-05T17:35:18.000Z | 2020-07-01T09:00:30.000Z | AtiRoNya/Bridge/Array/Array.cpp | avail/AtiRoNya | 715046515d682a91277c4ef73df29a5e4dbd8004 | [
"MIT"
] | null | null | null | AtiRoNya/Bridge/Array/Array.cpp | avail/AtiRoNya | 715046515d682a91277c4ef73df29a5e4dbd8004 | [
"MIT"
] | 5 | 2019-10-06T07:58:27.000Z | 2021-12-05T22:41:32.000Z | #include "Array.h"
#pragma region Array
void BridgeArray::Initialize(HMODULE hIL2CPP, HMODULE hMono) {
// Set variables
BridgeArray::hIL2CPP = hIL2CPP;
BridgeArray::hMono = hMono;
// Set functions
mono_array_length = (mono_array_length_t)GetProcAddress(hMono, "mono_array_length");
mono_array_addr_with_size = (mono_array_addr_with_size_t)GetProcAddress(hMono, "mono_array_addr_with_size");
}
mono_array_length_t BridgeArray::mono_array_length = NULL;
mono_array_addr_with_size_t BridgeArray::mono_array_addr_with_size = NULL;
HMODULE BridgeArray::hIL2CPP = NULL;
HMODULE BridgeArray::hMono = NULL;
#pragma endregion | 29.904762 | 109 | 0.808917 | AtiLion |
4bd2210ec0ef2ad47049d0c6cc4168d73b0d2ab9 | 1,122 | hpp | C++ | components/esm/loadspel.hpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null | components/esm/loadspel.hpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null | components/esm/loadspel.hpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null | #ifndef OPENMW_ESM_SPEL_H
#define OPENMW_ESM_SPEL_H
#include <string>
#include "effectlist.hpp"
namespace ESM
{
class ESMReader;
class ESMWriter;
struct Spell
{
static unsigned int sRecordId;
enum SpellType
{
ST_Spell = 0, // Normal spell, must be cast and costs mana
ST_Ability = 1, // Inert ability, always in effect
ST_Blight = 2, // Blight disease
ST_Disease = 3, // Common disease
ST_Curse = 4, // Curse (?)
ST_Power = 5 // Power, can use once a day
};
enum Flags
{
F_Autocalc = 1, // Can be selected by NPC spells auto-calc
F_PCStart = 2, // Can be selected by player spells auto-calc
F_Always = 4 // Casting always succeeds
};
struct SPDTstruct
{
int mType; // SpellType
int mCost; // Mana cost
int mFlags; // Flags
};
SPDTstruct mData;
std::string mId, mName;
EffectList mEffects;
void load(ESMReader &esm);
void save(ESMWriter &esm) const;
void blank();
///< Set record to default state (does not touch the ID/index).
};
}
#endif
| 20.777778 | 68 | 0.606952 | Bodillium |
4bdad270bcbbf3ebd25f0f51a7f6fe95d3c09492 | 360 | hpp | C++ | lib/Util/LinuxTools.hpp | hlp2/EnjoLib | 6bb69d0b00e367a800b0ef2804808fd1303648f4 | [
"BSD-3-Clause"
] | null | null | null | lib/Util/LinuxTools.hpp | hlp2/EnjoLib | 6bb69d0b00e367a800b0ef2804808fd1303648f4 | [
"BSD-3-Clause"
] | null | null | null | lib/Util/LinuxTools.hpp | hlp2/EnjoLib | 6bb69d0b00e367a800b0ef2804808fd1303648f4 | [
"BSD-3-Clause"
] | null | null | null | #ifndef LINUXTOOLS_H
#define LINUXTOOLS_H
#include <Util/Str.hpp>
namespace EnjoLib
{
// echo -n `cat /sys/class/net/eth0/address` | openssl sha256
class LinuxTools
{
public:
LinuxTools();
virtual ~LinuxTools();
EnjoLib::Str HashSHA256(const EnjoLib::Str & data) const;
protected:
private:
};
}
#endif // LINUXTOOLS_H
| 15.652174 | 65 | 0.658333 | hlp2 |
4be46fb782b7c7272aab241ac808a3100d847b63 | 1,611 | hpp | C++ | source/AsioExpress/MessagePort/SendQueue.hpp | suhao/asioexpress | 2f3453465934afdcdf4a575a2d933d86929b23c7 | [
"BSL-1.0"
] | null | null | null | source/AsioExpress/MessagePort/SendQueue.hpp | suhao/asioexpress | 2f3453465934afdcdf4a575a2d933d86929b23c7 | [
"BSL-1.0"
] | null | null | null | source/AsioExpress/MessagePort/SendQueue.hpp | suhao/asioexpress | 2f3453465934afdcdf4a575a2d933d86929b23c7 | [
"BSL-1.0"
] | null | null | null | // Copyright Ross MacGregor 2013
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include <deque>
#include <boost/shared_ptr.hpp>
#include "AsioExpress/CompletionHandler.hpp"
#include "AsioExpress/MessagePort/DataBuffer.hpp"
namespace AsioExpress {
namespace MessagePort {
class SendQueue
{
public:
struct Item
{
Item(
AsioExpress::MessagePort::DataBufferPointer dataBuffer,
AsioExpress::CompletionHandler completionHandler) :
dataBuffer(dataBuffer),
completionHandler(completionHandler)
{
}
AsioExpress::MessagePort::DataBufferPointer dataBuffer;
AsioExpress::CompletionHandler completionHandler;
};
bool Empty() const
{
return m_queue.empty();
}
void Push(Item item)
{
m_queue.push_back(item);
}
Item Top() const
{
return m_queue.front();
}
void Pop()
{
m_queue.pop_front();
}
void Error(boost::asio::io_service& ioService, AsioExpress::Error error)
{
Queue::iterator it = m_queue.begin();
Queue::iterator end = m_queue.end();
for (; it != end; ++it)
{
ioService.post(boost::asio::detail::bind_handler(it->completionHandler, error));
}
m_queue.clear();
}
private:
typedef std::deque<Item> Queue;
Queue m_queue;
};
typedef boost::shared_ptr<SendQueue> SendQueuePointer;
} // namespace MessagePort
} // namespace AsioExpress
| 21.197368 | 87 | 0.642458 | suhao |
4be6f2aa9c047ae88c025cad4694c88aed43ccd4 | 992 | cpp | C++ | code/backspace.cpp | matthewReff/Kattis-Problems | 848628af630c990fb91bde6256a77afad6a3f5f6 | [
"MIT"
] | 8 | 2020-02-21T22:21:01.000Z | 2022-02-16T05:30:54.000Z | code/backspace.cpp | matthewReff/Kattis-Problems | 848628af630c990fb91bde6256a77afad6a3f5f6 | [
"MIT"
] | null | null | null | code/backspace.cpp | matthewReff/Kattis-Problems | 848628af630c990fb91bde6256a77afad6a3f5f6 | [
"MIT"
] | 3 | 2020-08-05T05:42:35.000Z | 2021-08-30T05:39:51.000Z | #define _USE_MATH_DEFINES
#include <iostream>
#include <stdio.h>
#include <cmath>
#include <iomanip>
#include <vector>
#include <string>
#include <algorithm>
#include <unordered_set>
#include <ctype.h>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <unordered_map>
#define EPSILON 0.00001
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
ll i, j, k;
char letter;
deque<char> word;
string finishedWord = "";
while(cin >> letter)
{
if(letter != '<')
{
word.push_front(letter);
}
else
{
word.pop_front();
}
}
while(word.size())
{
finishedWord.push_back(word.front());
word.pop_front();
}
reverse(finishedWord.begin(), finishedWord.end());
cout << finishedWord << "\n";
return 0;
}
| 17.403509 | 54 | 0.587702 | matthewReff |
4beaa8991b231fd73926bab968c77b0358403a89 | 4,549 | cc | C++ | mito/tests/load-mesh/main.cc | mitadel/sandbox | afbab121f7e0aea7c092ca0c0e9088f6f06ad180 | [
"BSD-3-Clause"
] | 2 | 2021-05-26T15:18:00.000Z | 2022-03-24T06:25:39.000Z | mito/tests/load-mesh/main.cc | mitadel/sandbox | afbab121f7e0aea7c092ca0c0e9088f6f06ad180 | [
"BSD-3-Clause"
] | 3 | 2021-04-24T08:53:25.000Z | 2021-06-27T10:44:09.000Z | mito/tests/load-mesh/main.cc | mitadel/sandbox | afbab121f7e0aea7c092ca0c0e9088f6f06ad180 | [
"BSD-3-Clause"
] | null | null | null | #include "../../mito.h"
#include "../../mesh/Simplex.h"
#include "../../mesh/Mesh.h"
#include <fstream>
#include <string>
#include <map>
#include <time.h>
template <int D>
bool
LoadMesh(std::string fileName)
{
// open mesh file
std::ifstream fileStream;
fileStream.open(fileName);
assert(fileStream.is_open());
// read dimension of physical space
int dim = 0;
fileStream >> dim;
// assert the template parameter is equal to the dimension of the mesh being read
assert(int(D) == dim);
// read number of vertices
int N_vertices = 0;
fileStream >> N_vertices;
// read number of elements
int N_elements = 0;
fileStream >> N_elements;
// read number of element sets
int N_element_sets = 0;
fileStream >> N_element_sets;
// QUESTION: Not sure that we need this...
assert(N_element_sets == 1);
// fill in vertices
std::vector<mito::vertex_t *> vertices(N_vertices, nullptr);
mito::VertexPointMap<D> vertexCoordinatesMap;
for (auto & vertex : vertices) {
// instantiate new vertex
vertex = new mito::vertex_t();
// instantiate new point
mito::point_t<D> point;
for (int d = 0; d < D; ++d) {
// read point coordinates
fileStream >> point[d];
}
// associate the new vertex to the new point
vertexCoordinatesMap.insert(*vertex, std::move(point));
}
// sanity check: the number of vertices in the map is N_vertices
assert(vertexCoordinatesMap.size() == N_vertices);
// vertexCoordinatesMap.print();
// fill in elements
std::map<std::string, std::vector<const mito::triangle_t *>> element_sets;
for (int i = 0; i < N_elements; ++i) {
int element_type = 0;
fileStream >> element_type;
if (element_type == 3) {
int index0 = 0;
fileStream >> index0;
--index0;
int index1 = 0;
fileStream >> index1;
--index1;
int index2 = 0;
fileStream >> index2;
--index2;
mito::segment_t * segment0 =
new mito::segment_t({ vertices[index0], vertices[index1] });
mito::segment_t * segment1 =
new mito::segment_t({ vertices[index1], vertices[index2] });
mito::segment_t * segment2 =
new mito::segment_t({ vertices[index2], vertices[index0] });
// NOTE: With this implementation, edges have no dignity of their own but are
// just 'edges of a triangle'. This will make us lose some information,
// because we will see as different segments the same edge seen from two
// different triangles, although of course they have the same vertices.
const mito::triangle_t * element =
new mito::triangle_t({ segment0, segment1, segment2 });
// QUESTION: Can the label be more than one?
// read label for element
std::string element_set_id;
fileStream >> element_set_id;
// add this element to the element_sets labelled with element_set_id
element_sets[element_set_id].push_back(element);
}
}
// sanity check: the number of total elements across element sets is N_elements
int sum = 0;
for (const auto & element_set : element_sets) {
sum += element_set.second.size();
}
assert(sum == N_elements);
// sanity check: each element is self-consistent
for (const auto & element_set : element_sets) {
for (const auto & element : element_set.second) {
assert(element->sanityCheck());
}
}
// finalize file stream
fileStream.close();
// free memory
for (const auto & vertex : vertices) {
delete vertex;
}
// free memory
for (const auto & element_set : element_sets) {
for (const auto & element : element_set.second) {
for (const auto * entity : element->entities()) {
delete entity;
}
delete element;
}
}
// all done
return true;
}
int
main()
{
clock_t t;
//
t = clock();
mito::Mesh<2> mesh("rectangle.summit");
std::cout << "Loaded mesh (without repeated entities) in " << clock() - t << std::endl;
//
t = clock();
LoadMesh<2>("rectangle.summit");
std::cout << "Loaded mesh (with repeated entities) in " << clock() - t << std::endl;
return 0;
}
| 28.791139 | 91 | 0.579688 | mitadel |
4beade03c5edc2100e5e896f784b5aee6bfcc536 | 1,154 | cpp | C++ | asakatsu/0502d.cpp | KoukiNAGATA/c- | ae51bacb9facb936a151dd777beb6688383a2dcd | [
"MIT"
] | null | null | null | asakatsu/0502d.cpp | KoukiNAGATA/c- | ae51bacb9facb936a151dd777beb6688383a2dcd | [
"MIT"
] | 3 | 2021-03-31T01:39:25.000Z | 2021-05-04T10:02:35.000Z | asakatsu/0502d.cpp | KoukiNAGATA/c- | ae51bacb9facb936a151dd777beb6688383a2dcd | [
"MIT"
] | null | null | null | #include<iostream>
#include<vector>
#include<string>
#include<map>
#include<utility>
#include<algorithm>
#include<queue>
#include<cmath>
#include<iomanip>
#define REP(i, n) for(ll i = 0; i < n; i++)
#define REPR(i, n) for(ll i = n - 1; i >= 0; i--)
#define FOR(i, m, n) for(ll i = m; i <= n; i++)
#define FORR(i, m, n) for(ll i = m; i >= n; i--)
#define SORT(v, n) sort(v, v+n)
#define MAX 100000
#define inf 1000000007
using namespace std;
using ll = long long;
using vll = vector<ll>;
using vvll = vector<vector<ll>>;
using P = pair<ll, ll>;
ll GCD(ll x, ll y) {//最大公約数:x%y!=0ならばGCD(y, x%y)、0ならばyを返す(x>y)
return x % y ? GCD(y, x%y) : y;
}
int main() {
// cin高速化
cin.tie(0);
ios::sync_with_stdio(false);
ll n, k, g, m;
cin >> n >> k;
vll a(n, inf);
m = 0;
REP(i, n){
cin >>a[i];
if(a[i] > m) m = a[i];
if(a[i] == k){
cout << "POSSIBLE" <<"\n";
return 0;
}
}
g = a[0];
FOR(i, 1, n-1){
g = GCD(g, a[i]);
}
if(m >= k && k % g == 0){
cout << "POSSIBLE" <<"\n";
}else{
cout << "IMPOSSIBLE" <<"\n";
}
return 0;
} | 21.773585 | 62 | 0.493068 | KoukiNAGATA |
4beb410b007c7ec41f5f8644ea99e23f152137fd | 1,501 | hpp | C++ | utility/arduino_serial.hpp | charlesmacd/HD6805_Reader | 3d9ec7f2530b691db8eba7b9a64bdfb34c989984 | [
"Apache-2.0"
] | null | null | null | utility/arduino_serial.hpp | charlesmacd/HD6805_Reader | 3d9ec7f2530b691db8eba7b9a64bdfb34c989984 | [
"Apache-2.0"
] | null | null | null | utility/arduino_serial.hpp | charlesmacd/HD6805_Reader | 3d9ec7f2530b691db8eba7b9a64bdfb34c989984 | [
"Apache-2.0"
] | null | null | null |
#pragma once
#include "winserial.hpp"
class ArduinoSerialPort : public SerialPort
{
public:
bool openArduino(int com_port, int com_baud_rate)
{
if(com_port == -1)
{
if(!scan(&com_port, NULL))
{
printf("Status: Couldn't find a COM port.\n");
}
else
{
printf("Status: Found port COM%d.\n", com_port);
}
}
printf("Status: Attempting to open COM%d.\n", com_port);
if(!open(com_port, com_baud_rate))
{
printf("Error: Couldn't open serial port.\n");
return false;
}
/* Reset Arduino */
printf("Status: Waiting for Arduino to reboot. \n");
resetArduino();
return true;
}
bool closeArduino()
{
return close();
}
/*
The DTR# line is AC coupled to the Arduino's ATmega328 RESET# pin.
When DTR# is pulled low it causes a ~250us low pulse on RESET#,
the duration of which is not controlled by DTR#
*/
void resetArduino(uint32_t delay_ms = 2000)
{
/* Flush UART recieve buffer to clear out any garbage */
flush_rx_queue();
flush_tx_queue();
/* Drive DTR# low for 1ms, Arduino reset pulse happens within first 250us */
set_dtr(true);
Sleep(1);
set_dtr(false);
/* Wait for Arduino to boot after reset is relesaed */
Sleep(delay_ms);
}
};
| 23.825397 | 84 | 0.536975 | charlesmacd |
4bec3242ea9cc77af5843a176c233bd9d5480c99 | 468 | hpp | C++ | include/AABB.hpp | Kirthos/Aerria | ec9eb6c78690838ba5a3509369e2c4d8428b4dc2 | [
"MIT"
] | null | null | null | include/AABB.hpp | Kirthos/Aerria | ec9eb6c78690838ba5a3509369e2c4d8428b4dc2 | [
"MIT"
] | null | null | null | include/AABB.hpp | Kirthos/Aerria | ec9eb6c78690838ba5a3509369e2c4d8428b4dc2 | [
"MIT"
] | null | null | null | #ifndef AABB_H
#define AABB_H
#include <SFML/Graphics.hpp>
class Entity;
class AABB
{
public:
AABB();
void init(Entity* parent,sf::Vector2f taille);
void setTaille(sf::Vector2f t_taille);
bool testCollision(AABB test);
sf::Vector2f getTaille();
sf::Vector2f getPos();
void setPos(sf::Vector2f pos);
protected:
private:
sf::Vector2f m_taille;
Entity* m_parent;
};
#endif // AABB_H
| 18.72 | 54 | 0.608974 | Kirthos |
4bec919d4b2a51fd9f03538f25bc5d960add292e | 4,035 | cpp | C++ | AADC/src/aadcUser/AltarReadData/ReadData.cpp | AimiHat/AADC-2018---Team-Altar | 857fb79d52a5a428f6fbd96ca11fe6a758cdc780 | [
"MIT"
] | 1 | 2020-10-07T08:55:55.000Z | 2020-10-07T08:55:55.000Z | AADC/src/aadcUser/AltarReadData/ReadData.cpp | AimiHat/AADC-2018---Team-Altar | 857fb79d52a5a428f6fbd96ca11fe6a758cdc780 | [
"MIT"
] | null | null | null | AADC/src/aadcUser/AltarReadData/ReadData.cpp | AimiHat/AADC-2018---Team-Altar | 857fb79d52a5a428f6fbd96ca11fe6a758cdc780 | [
"MIT"
] | null | null | null | /*********************************************************************
Copyright (c) 2018
Audi Autonomous Driving Cup. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software must display the following acknowledgement: ?This product includes software developed by the Audi AG and its contributors for Audi Autonomous Driving Cup.?
4. Neither the name of Audi 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 AUDI AG 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 AUDI AG 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 "stdafx.h"
#include "ReadData.h"
ADTF_TRIGGER_FUNCTION_FILTER_PLUGIN(CID_TEMPLATEFILTER_DATA_TRIGGERED_FILTER,
"AltarReadData",
cReadData,
adtf::filter::pin_trigger({"input"}));
cReadData::cReadData()
{
//DO NOT FORGET TO LOAD MEDIA DESCRIPTION SERVICE IN ADTF3 AND CHOOSE aadc.description
object_ptr<IStreamType> pTypeMyData;
if IS_OK(adtf::mediadescription::ant::create_adtf_default_stream_type_from_service("tMyData", pTypeMyData, m_MyStructSampleFactory))
{
adtf_ddl::access_element::find_index(m_MyStructSampleFactory, "ui32Size", m_ddlMyDataId.data1);
adtf_ddl::access_element::find_index(m_MyStructSampleFactory, "tMyFloat32", m_ddlMyDataId.data2);
adtf_ddl::access_element::find_index(m_MyStructSampleFactory, "tMyArray", m_ddlMyDataId.data3);
}
else
{
LOG_WARNING("No mediadescription for tSignalValue found!");
}
LOG_INFO(cString::Format("INTIALIZE!!!!"));
Register(MyDataIn, "input", pTypeMyData);
}
//implement the Configure function to read ALL Properties
tResult cReadData::Configure()
{
RETURN_NOERROR;
}
tResult cReadData::Process(tTimeStamp tmTimeOfTrigger)
{
object_ptr<const ISample> pReadSample;
tUInt32 b;
tFloat32 a;
tMySimpleData z;
if (IS_OK(MyDataIn.GetLastSample(pReadSample))) {
auto oDecoder = m_MyStructSampleFactory.MakeDecoderFor(*pReadSample);
RETURN_IF_FAILED(oDecoder.IsValid());
// retrieve the values (using convenience methods that return a variant)
RETURN_IF_FAILED(oDecoder.GetElementValue(m_ddlMyDataId.data1, &b));
RETURN_IF_FAILED(oDecoder.GetElementValue(m_ddlMyDataId.data2, &a));
const tMySimpleData *pCoordiante = reinterpret_cast<const tMySimpleData *>(oDecoder.GetElementAddress(
m_ddlMyDataId.data3));
tMySimpleData myPoint;
for (tSize i = 0; i < 6; ++i) {
myPoint.f32num1 = pCoordiante[i].f32num1;
myPoint.f32num2 = pCoordiante[i].f32num2;
LOG_INFO(cString::Format("(%f, %f)", myPoint.f32num1, myPoint.f32num2));
}
}
LOG_INFO(cString::Format("(%f, %f)", a,b));
RETURN_NOERROR;
} | 43.387097 | 726 | 0.724659 | AimiHat |
4bee0e18b8b0699a9e959ef54dd8c928b1dcf3b3 | 9,966 | cpp | C++ | LIA_RAL_3.0/LIA_SpkDet/TotalVariability/src/TotalVariability.cpp | ibillxia/VoicePrintReco | 20bf32f183abcd483fe1da451b4c75cf995b5f26 | [
"MIT"
] | 83 | 2015-01-18T01:20:37.000Z | 2022-03-02T20:15:27.000Z | LIA_RAL_3.0/LIA_SpkDet/TotalVariability/src/TotalVariability.cpp | Dystopiaz/VoicePrintReco | 20bf32f183abcd483fe1da451b4c75cf995b5f26 | [
"MIT"
] | 4 | 2016-03-03T08:43:00.000Z | 2019-03-08T06:20:56.000Z | LIA_RAL_3.0/LIA_SpkDet/TotalVariability/src/TotalVariability.cpp | Dystopiaz/VoicePrintReco | 20bf32f183abcd483fe1da451b4c75cf995b5f26 | [
"MIT"
] | 59 | 2015-02-02T03:07:37.000Z | 2021-11-22T12:05:42.000Z | /*
This file is part of LIA_RAL which is a set of software based on ALIZE
toolkit for speaker recognition. ALIZE toolkit is required to use LIA_RAL.
LIA_RAL project is a development project was initiated by the computer
science laboratory of Avignon / France (Laboratoire Informatique d'Avignon -
LIA) [http://lia.univ-avignon.fr <http://lia.univ-avignon.fr/>]. Then it
was supported by two national projects of the French Research Ministry:
- TECHNOLANGUE program [http://www.technolangue.net]
- MISTRAL program [http://mistral.univ-avignon.fr]
LIA_RAL 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 3 of
the License, or any later version.
LIA_RAL 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 LIA_RAL.
If not, see [http://www.gnu.org/licenses/].
The LIA team as well as the LIA_RAL project team wants to highlight the
limits of voice authentication in a forensic context.
The "Person Authentification by Voice: A Need of Caution" paper
proposes a good overview of this point (cf. "Person
Authentification by Voice: A Need of Caution", Bonastre J.F.,
Bimbot F., Boe L.J., Campbell J.P., Douglas D.A., Magrin-
chagnolleau I., Eurospeech 2003, Genova].
The conclusion of the paper of the paper is proposed bellow:
[Currently, it is not possible to completely determine whether the
similarity between two recordings is due to the speaker or to other
factors, especially when: (a) the speaker does not cooperate, (b) there
is no control over recording equipment, (c) recording conditions are not
known, (d) one does not know whether the voice was disguised and, to a
lesser extent, (e) the linguistic content of the message is not
controlled. Caution and judgment must be exercised when applying speaker
recognition techniques, whether human or automatic, to account for these
uncontrolled factors. Under more constrained or calibrated situations,
or as an aid for investigative purposes, judicious application of these
techniques may be suitable, provided they are not considered as infallible.
At the present time, there is no scientific process that enables one to
uniquely characterize a persones voice or to identify with absolute
certainty an individual from his or her voice.]
Copyright (C) 2004-2010
Laboratoire d'informatique d'Avignon [http://lia.univ-avignon.fr]
LIA_RAL admin [alize@univ-avignon.fr]
Jean-Francois Bonastre [jean-francois.bonastre@univ-avignon.fr]
*/
#if !defined(ALIZE_TotalVariability_cpp)
#define ALIZE_TotalVariability_cpp
#include <iostream>
#include <fstream>
#include <cstdio>
#include <cassert>
#include <cmath>
#include <liatools.h>
#include "TotalVariability.h"
using namespace std;
using namespace alize;
//-----------------------------------------------------------------------------------------------------------------------------------------------------------
int TotalVariability(Config & config){
//Read the NDX file
String ndxFilename = config.getParam("ndxFilename");
//Create and initialise the accumulator
TVAcc tvAcc(ndxFilename, config);
//Option used to check the Likelihood at each iteration
bool _checkLLK = false;
if (config.existsParam("checkLLK")) _checkLLK= config.getParam("checkLLK").toBool();
//Statistics
if((config.existsParam("loadAccs")) && config.getParam("loadAccs").toBool()){ //load pre-computed statistics
cout<<" ()Load Accumulators"<<endl;
tvAcc.loadN(config);
tvAcc.loadF_X(config);
}
else{ //Compute statistics if they don't exists
tvAcc.computeAndAccumulateTVStat(config);
tvAcc.saveAccs(config);
}
//Initialize the Total Variability matrix
bool loadInitEigenVoiceMatrix = false;
if(config.existsParam("loadInitTotalVariabilityMatrix")) loadInitEigenVoiceMatrix = config.getParam("loadInitTotalVariabilityMatrix").toBool();
if(loadInitEigenVoiceMatrix){ //Load the Total Variability matrix when existing
tvAcc.loadT(config.getParam("initTotalVariabilityMatrix"), config);
}
else{ //Initialize the EV matrix randomly if does not exists
tvAcc.initT(config);
}
//Save the initial Total Variability matrix to be able restart the process with the same initialisation
if(config.existsParam("saveInitTotalVariabilityMatrix") && config.getParam("saveInitTotalVariabilityMatrix").toBool()){
String initV = config.getParam("totalVariabilityMatrix")+"_init";
tvAcc.saveT(initV, config);
cout<<" (TotalVariability) Save the initial TotalVariability Matrix in "<<initV<<endl;
}
//Select minimum divergence criteria
bool minDiv = false;
if(config.existsParam("minDivergence")) minDiv = config.getParam("minDivergence").toBool();
//Iteratively retrain the EV matrix
unsigned long nbIt = config.getParam("nbIt").toULong();
for(unsigned long it=0; it<nbIt; it++){
cout<<" (TotalVariability) --------- start iteration "<<it<<" --------"<<endl;
//Subtract mean from the statistics
tvAcc.substractM(config);
//Compute TETt for each distribution
tvAcc.estimateTETt(config);
// Compute inverse(L) and estimate TotalVariability matrix
tvAcc.estimateAandC(config);
//Compute Likelihood over the data if required
if (_checkLLK) tvAcc.verifyEMLK(config);
//Update _T
tvAcc.updateTestimate();
//Minimum Divergence step
if(minDiv){
tvAcc.minDivergence();
}
//If the option is on, orthonormalize the matrix V
if(config.existsParam("orthonormalizeT") && (config.getParam("orthonormalizeT").toBool())){
if(verboseLevel > 0) cout<<"Orthonormalize TV matrix"<<endl;
tvAcc.orthonormalizeT();
}
//Reinitialize the accumulators
tvAcc.resetTmpAcc();
//Reload statistics
tvAcc.loadN(config);
tvAcc.loadF_X(config);
//Save the T matrix at the end of the iteration
bool saveAllEVMatrices = false;
if(config.existsParam("saveAllTVMatrices")) saveAllEVMatrices=config.getParam("saveAllTVMatrices").toBool();
if(saveAllEVMatrices){
String s;
String output = config.getParam("totalVariabilityMatrix") + s.valueOf(it);
tvAcc.saveT(output, config);
// Save the new mean computed by Minimum Divergence if required
if(minDiv){
String sm;
String outputm = config.getParam("matrixFilesPath") + config.getParam("meanEstimate") + sm.valueOf(it) + config.getParam("saveMatrixFilesExtension");
((Matrix<double>)tvAcc.getUbmMeans()).save(outputm, config);
}
}
}
cout<<" (TotalVariability) --------- save Matrix --------"<<endl;
tvAcc.saveT(config.getParam("totalVariabilityMatrix"), config);
if(minDiv){
String outputm = config.getParam("matrixFilesPath") + config.getParam("meanEstimate") + config.getParam("saveMatrixFilesExtension");
((Matrix<double>)tvAcc.getUbmMeans()).save(outputm, config);
}
cout<<" (TotalVariability) --------- end of process --------"<<endl;
// If Required, output parameters for approximated i-vector extraction (ubmWeight or eigenDecomposition)
if(config.existsParam("approximationMode")){
if(config.getParam("approximationMode") == "ubmWeight"){
cout<<" (TotalVariability) Compute weighted covariance matrix W for i-vector approximation using ubmWeight"<<endl;
//Return the normalize T matrix
tvAcc.normTMatrix();
String normTFilename = config.getParam("totalVariabilityMatrix") + "_norm";
tvAcc.saveT(normTFilename, config);
//Return the weighted covariance matrix
String inputWorldFilename = config.getParam("inputWorldFilename");
MixtureServer ms(config);
MixtureGD& world = ms.loadMixtureGD(inputWorldFilename);
DoubleSquareMatrix W(tvAcc.getRankT());
W.setAllValues(0.0);
tvAcc.getWeightedCov(W,world.getTabWeight(),config);
Matrix<double> tmpW(W);
String wFilename = config.getParam("matrixFilesPath") + config.getParam("totalVariabilityMatrix") + "_weightedCov" + config.getParam("loadMatrixFilesExtension");
tmpW.save(wFilename, config);
}
else if(config.getParam("approximationMode") == "eigenDecomposition"){
cout<<" (TotalVariability) Compute D and Q matrices for i-vector approximation using eigenDecomposition"<<endl;
// Normalize matrix T
tvAcc.normTMatrix();
String normTFilename = config.getParam("totalVariabilityMatrix") + "_norm";
tvAcc.saveT(normTFilename, config);
// Compute weighted co-variance matrix by using UBM weight coefficients
String inputWorldFilename = config.getParam("inputWorldFilename");
MixtureServer ms(config);
MixtureGD& world = ms.loadMixtureGD(inputWorldFilename);
DoubleSquareMatrix W(tvAcc.getRankT());
W.setAllValues(0.0);
tvAcc.getWeightedCov(W,world.getTabWeight(),config);
// Eigen Decomposition of W to get Q
Matrix<double> tmpW(W);
Matrix<double> Q(tvAcc.getRankT(),tvAcc.getRankT());
Q.setAllValues(0.0);
tvAcc.computeEigenProblem(tmpW,Q,tvAcc.getRankT(),config);
// Compute D matrices (approximation of Tc'Tc matrices)
Matrix<double> D(tvAcc.getNDistrib(),tvAcc.getRankT());
D.setAllValues(0.0);
tvAcc.approximateTcTc(D,Q,config);
config.getParam("matrixFilesPath") + config.getParam("totalVariabilityMatrix") + "_EigDec_D" + config.getParam("loadMatrixFilesExtension");
String dFilename = config.getParam("matrixFilesPath") + config.getParam("totalVariabilityMatrix") + "_EigDec_D" + config.getParam("loadMatrixFilesExtension");
String qFilename = config.getParam("matrixFilesPath") + config.getParam("totalVariabilityMatrix") + "_EigDec_Q" + config.getParam("loadMatrixFilesExtension");
D.save(dFilename, config);
Q.save(qFilename, config);
}
else{
cout<<" (TotalVariability) This approximation mode does not exists"<<endl; // to check before to avoid being disapointed at the end
}
}
return 0;
}
#endif
| 40.024096 | 164 | 0.74122 | ibillxia |
4bf00fd09d9d6f08e40ef22dcae6cfefcee881f1 | 1,562 | cpp | C++ | example/01. Basic Window and Event Loop/Main.cpp | OutOfTheVoid/ProjectRed | 801327283f5a302be130c90d593b39957c84cce5 | [
"MIT"
] | 1 | 2020-06-14T06:14:50.000Z | 2020-06-14T06:14:50.000Z | example/01. Basic Window and Event Loop/Main.cpp | OutOfTheVoid/ProjectRed | 801327283f5a302be130c90d593b39957c84cce5 | [
"MIT"
] | null | null | null | example/01. Basic Window and Event Loop/Main.cpp | OutOfTheVoid/ProjectRed | 801327283f5a302be130c90d593b39957c84cce5 | [
"MIT"
] | null | null | null | #include <SDLX/SDLX.h>
#include <SDLX/Lib.h>
#include <SDLX/Window.h>
#include <stdint.h>
#include <iostream>
// Forward declaration
void WindowCloseEvent ( SDL_WindowEvent * Event, SDLX :: Window * Origin, void * Data );
int main ( int argc, const char * argv [] )
{
uint32_t Status;
// Initialize SDLX/SDL2
SDLX::Lib :: Init ( & Status, SDLX::Lib :: kSDLFlag_Video );
// Check that everything's OK
if ( SDLX :: kStatus_Success )
return - 1;
// Open a window!
SDLX::Window * MyWindow = SDLX::Window :: CreateWindow ( & Status, "My First Window", 800, 600 );
// Check that everything's OK
if ( Status != SDLX::Window :: kStatus_Success )
{
// Do this wherever we potentially exit the application.
SDLX::Lib :: DeInit ();
return - 2;
}
// Take ownership (in terms of reference counting)
MyWindow -> Own ();
// Hook the close event
MyWindow -> AddEventHook ( SDLX::Window :: kWindowEventID_Closed, & WindowCloseEvent, NULL );
// Enter our event loop
SDLX::Lib :: EventLoop ( & Status );
// Always a good idea to NULL a pointer we no longer own.
MyWindow -> Disown ();
MyWindow = NULL;
// Cleans up any resources that SDL2/SDLX might be using
SDLX::Lib :: DeInit ();
}
void WindowCloseEvent ( SDL_WindowEvent * Event, SDLX :: Window * Origin, void * Data )
{
std :: cout << "Closing window!" << std :: endl;
uint32_t Status;
// Close the window
Origin -> Close ( & Status );
// Just to suppress unused argument warnings, we'll cast these to void.
(void) Event;
(void) Data;
}
| 22.970588 | 98 | 0.648528 | OutOfTheVoid |
4bf065faeabdbb3fdb2d93d7b4918bf629e59ffe | 338 | cpp | C++ | src/rmi/rmibase.cpp | mage-game/metagame-server-engine | 8b6eb0a258d6dae4330cb3be769de162874841ed | [
"MIT"
] | 4 | 2021-12-16T13:57:26.000Z | 2022-03-26T07:49:42.000Z | src/rmi/rmibase.cpp | mage-game/metagame-server-engine | 8b6eb0a258d6dae4330cb3be769de162874841ed | [
"MIT"
] | null | null | null | src/rmi/rmibase.cpp | mage-game/metagame-server-engine | 8b6eb0a258d6dae4330cb3be769de162874841ed | [
"MIT"
] | 1 | 2022-03-26T07:49:46.000Z | 2022-03-26T07:49:46.000Z |
#include "rmibase.h"
#include "rmidef.h"
namespace rmi
{
int RMIObject::__dispatch(const char *method, TLVUnserializer &in_param, TLVSerializer *out_param)
{
MethodList::iterator i = m_method_list.find(method);
if (i != m_method_list.end())
{
return i->second(in_param, out_param);
}
return DispatchMethodNotExist;
}
}
| 18.777778 | 99 | 0.715976 | mage-game |
4bfe39696fce62ae2bf6fcf0f3cf6bfa073f7cfe | 961 | cpp | C++ | jsUnits/jsForcePerUnitLength.cpp | dnv-opensource/Reflection | 27effb850e9f0cc6acc2d48630ee6aa5d75fa000 | [
"BSL-1.0"
] | null | null | null | jsUnits/jsForcePerUnitLength.cpp | dnv-opensource/Reflection | 27effb850e9f0cc6acc2d48630ee6aa5d75fa000 | [
"BSL-1.0"
] | null | null | null | jsUnits/jsForcePerUnitLength.cpp | dnv-opensource/Reflection | 27effb850e9f0cc6acc2d48630ee6aa5d75fa000 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2021 DNV AS
//
// 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 <jsUnits/jsForcePerUnitLength.h>
#include <jsUnits/jsUnitClass.h>
#include <Units/ForcePerUnitLength.h>
#include "jsTranslationalStiffness.h"
using namespace DNVS::MoFa::Units;
Runtime::DynamicPhenomenon jsForcePerUnitLength::GetPhenomenon()
{
return ForcePerUnitLengthPhenomenon();
}
void jsForcePerUnitLength::init(jsTypeLibrary& typeLibrary)
{
jsUnitClass<jsForcePerUnitLength,DNVS::MoFa::Units::ForcePerUnitLength> cls(typeLibrary);
if(cls.reinit()) return;
cls.ImplicitConstructorConversion(&jsUnitClass<jsForcePerUnitLength,DNVS::MoFa::Units::ForcePerUnitLength>::ConstructEquivalentQuantity<jsTranslationalStiffness>);
cls.ImplicitConstructorConversion([](const jsForcePerUnitLength& val) {return TranslationalStiffness(val); });
}
| 35.592593 | 166 | 0.790843 | dnv-opensource |
ef03ec7ed241dc6ca1e18d1b3323c6fefbc3ecd2 | 7,463 | cpp | C++ | src/caffe/layers/softmax_loss_layer.cpp | noirmist/OpenCL-caffe | 41805c86a29de1e7bf1c12bd1d7488a5fed3f997 | [
"BSD-2-Clause"
] | 616 | 2015-09-20T14:48:47.000Z | 2022-03-25T08:37:10.000Z | src/caffe/layers/softmax_loss_layer.cpp | niclar/OpenCL-caffe | b2c402f7a9828cc8c1970d43950226daa8a1f4b8 | [
"BSD-2-Clause"
] | 60 | 2015-09-29T23:25:35.000Z | 2019-02-20T04:41:27.000Z | src/caffe/layers/softmax_loss_layer.cpp | niclar/OpenCL-caffe | b2c402f7a9828cc8c1970d43950226daa8a1f4b8 | [
"BSD-2-Clause"
] | 180 | 2015-09-20T08:17:53.000Z | 2021-12-23T15:47:39.000Z | #include <algorithm>
#include <cfloat>
#include <vector>
#include "caffe/layer.hpp"
#include "caffe/layer_factory.hpp"
#include "caffe/util/math_functions.hpp"
#include "caffe/vision_layers.hpp"
namespace caffe {
template <typename Dtype>
void SoftmaxWithLossLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
LossLayer < Dtype > ::LayerSetUp(bottom, top);
LayerParameter softmax_param(this->layer_param_);
softmax_param.set_type("Softmax");
softmax_layer_ = LayerRegistry < Dtype > ::CreateLayer(softmax_param);
softmax_bottom_vec_.clear();
softmax_bottom_vec_.push_back(bottom[0]);
softmax_top_vec_.clear();
softmax_top_vec_.push_back(&prob_);
softmax_layer_->SetUp(softmax_bottom_vec_, softmax_top_vec_);
has_ignore_label_ = this->layer_param_.loss_param().has_ignore_label();
if (has_ignore_label_) {
ignore_label_ = this->layer_param_.loss_param().ignore_label();
}
normalize_ = this->layer_param_.loss_param().normalize();
}
template <typename Dtype>
SoftmaxWithLossLayer<Dtype>::~SoftmaxWithLossLayer() {
}
template <typename Dtype>
void SoftmaxWithLossLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
LossLayer < Dtype > ::Reshape(bottom, top);
softmax_layer_->Reshape(softmax_bottom_vec_, softmax_top_vec_);
softmax_axis_ = bottom[0]->CanonicalAxisIndex(
this->layer_param_.softmax_param().axis());
outer_num_ = bottom[0]->count(0, softmax_axis_);
inner_num_ = bottom[0]->count(softmax_axis_ + 1);
CHECK_EQ(outer_num_ * inner_num_, bottom[1]->count())
<< "Number of labels must match number of predictions; "
<< "e.g., if softmax axis == 1 and prediction shape is (N, C, H, W), "
<< "label count (number of labels) must be N*H*W, "
<< "with integer values in {0, 1, ..., C-1}.";
if (top.size() >= 2) {
// softmax output
top[1]->ReshapeLike(*bottom[0]);
}
}
template <typename Dtype>
void SoftmaxWithLossLayer<Dtype>::Forward_cpu(
const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {
// The forward pass computes the softmax prob values.
softmax_layer_->Forward(softmax_bottom_vec_, softmax_top_vec_);
const Dtype* prob_data = prob_.cpu_data();
const Dtype* label = bottom[1]->cpu_data();
int dim = prob_.count() / outer_num_;
int count = 0;
Dtype loss = 0;
for (int i = 0; i < outer_num_; ++i) {
for (int j = 0; j < inner_num_; j++) {
const int label_value = static_cast<int>(label[i * inner_num_ + j]);
if (has_ignore_label_ && label_value == ignore_label_) {
continue;
}
DCHECK_GE(label_value, 0);
DCHECK_LT(label_value, prob_.shape(softmax_axis_));
loss -= log(
std::max(prob_data[i * dim + label_value * inner_num_ + j],
Dtype(FLT_MIN)));
++count;
}
}
if (normalize_) {
top[0]->mutable_cpu_data()[0] = loss / count;
} else {
top[0]->mutable_cpu_data()[0] = loss / outer_num_;
}
if (top.size() == 2) {
top[1]->ShareData(prob_);
}
}
template <typename Dtype>
void SoftmaxWithLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {
if (propagate_down[1]) {
LOG(FATAL) << this->type()
<< " Layer cannot backpropagate to label inputs.";
}
if (propagate_down[0]) {
Dtype* bottom_diff = bottom[0]->mutable_cpu_diff();
const Dtype* prob_data = prob_.cpu_data();
caffe_copy(prob_.count(), prob_data, bottom_diff);
const Dtype* label = bottom[1]->cpu_data();
int dim = prob_.count() / outer_num_;
int count = 0;
for (int i = 0; i < outer_num_; ++i) {
for (int j = 0; j < inner_num_; ++j) {
const int label_value = static_cast<int>(label[i * inner_num_ + j]);
if (has_ignore_label_ && label_value == ignore_label_) {
for (int c = 0; c < bottom[0]->shape(softmax_axis_); ++c) {
bottom_diff[i * dim + c * inner_num_ + j] = 0;
}
} else {
bottom_diff[i * dim + label_value * inner_num_ + j] -= 1;
++count;
}
}
}
// Scale gradient
const Dtype loss_weight = top[0]->cpu_diff()[0];
if (normalize_) {
caffe_scal(prob_.count(), loss_weight / count, bottom_diff);
} else {
caffe_scal(prob_.count(), loss_weight / outer_num_, bottom_diff);
}
}
}
// begin: code modified for OpenCL port
#ifndef CPU_ONLY
template <typename Dtype>
void SoftmaxWithLossLayer<Dtype>::Forward_gpu(
const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {
softmax_layer_->Forward(softmax_bottom_vec_, softmax_top_vec_);
const Dtype* prob_data = prob_.gpu_data();
const Dtype* label = bottom[1]->gpu_data();
const int dim = prob_.count() / outer_num_;
const int nthreads = outer_num_ * inner_num_;
// Since this memory is not used for anything until it is overwritten
// on the backward pass, we use it here to avoid having to allocate new GPU
// memory to accumulate intermediate results in the kernel.
Dtype* loss_data = bottom[0]->mutable_gpu_diff();
// Similarly, this memory is never used elsewhere, and thus we can use it
// to avoid having to allocate additional GPU memory.
Dtype* counts = prob_.mutable_gpu_diff();
// NOLINT_NEXT_LINE(whitespace/operators)
SoftmaxLossForwardGPU < Dtype
> (nthreads, prob_data, label, loss_data, outer_num_, dim, inner_num_, has_ignore_label_, ignore_label_, counts);
Dtype loss;
caffe_gpu_asum(nthreads, loss_data, &loss);
if (normalize_) {
Dtype count;
caffe_gpu_asum(nthreads, counts, &count);
loss /= count;
} else {
loss /= outer_num_;
}
top[0]->mutable_cpu_data()[0] = loss;
if (top.size() == 2) {
top[1]->ShareData(prob_);
}
}
template <typename Dtype>
void SoftmaxWithLossLayer<Dtype>::Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {
if (propagate_down[1]) {
LOG(FATAL) << this->type()
<< " Layer cannot backpropagate to label inputs.";
}
if (propagate_down[0]) {
Dtype* bottom_diff = bottom[0]->mutable_gpu_diff();
const Dtype* prob_data = prob_.gpu_data();
const Dtype* top_data = top[0]->gpu_data();
caffe_gpu_memcpy(prob_.count() * sizeof(Dtype), prob_data, bottom_diff);
//caffe_gpu_copy(prob_.count(), prob_data, bottom_diff);
const Dtype* label = bottom[1]->gpu_data();
const int dim = prob_.count() / outer_num_;
const int nthreads = outer_num_ * inner_num_;
// Since this memory is never used for anything else,
// we use to to avoid allocating new GPU memory.
Dtype* counts = prob_.mutable_gpu_diff();
// NOLINT_NEXT_LINE(whitespace/operators)
SoftmaxLossBackwardGPU < Dtype
> (nthreads, top_data, label, bottom_diff, outer_num_, dim, inner_num_, has_ignore_label_, ignore_label_, counts);
const Dtype loss_weight = top[0]->cpu_diff()[0];
if (normalize_) {
Dtype count;
caffe_gpu_asum(nthreads, counts, &count);
caffe_gpu_scal(prob_.count(), loss_weight / count, bottom_diff);
} else {
caffe_gpu_scal(prob_.count(), loss_weight / outer_num_, bottom_diff);
}
}
}
// end: code modified for OpenCL port
#else
STUB_GPU(SoftmaxWithLossLayer);
#endif
INSTANTIATE_CLASS (SoftmaxWithLossLayer);
REGISTER_LAYER_CLASS (SoftmaxWithLoss);
} // namespace caffe
| 36.763547 | 122 | 0.674394 | noirmist |
ef069a54d8e4408116e4b88bfe66a1f8b5323864 | 3,436 | cpp | C++ | examples/BitonicSortTests/bitonic_sort_tests.cpp | cg-enths/shaderator | 825f58f1da0ec0fec1367ca0a1f19796a11f54d4 | [
"MIT"
] | 31 | 2018-04-11T17:28:01.000Z | 2022-02-22T13:41:26.000Z | examples/BitonicSortTests/bitonic_sort_tests.cpp | cg-enths/shaderator | 825f58f1da0ec0fec1367ca0a1f19796a11f54d4 | [
"MIT"
] | 5 | 2018-03-15T16:44:18.000Z | 2019-04-13T19:17:51.000Z | examples/BitonicSortTests/bitonic_sort_tests.cpp | cezbloch/shaderator | 825f58f1da0ec0fec1367ca0a1f19796a11f54d4 | [
"MIT"
] | 5 | 2018-11-30T01:14:48.000Z | 2021-12-31T10:03:51.000Z | #define _SILENCE_TR1_NAMESPACE_DEPRECATION_WARNING
#define TRACE_ACCESS
#include "gtest/gtest.h"
#include "bitonic_sort_executor.h"
#include "shader_types.h"
#include <iterator> //std::begin
#include <numeric> //std::itoa
#include <random>
#include <vector>
using UINT = unsigned int;
const UINT BITONIC_BLOCK_SIZE = 16;
const UINT TRANSPOSE_BLOCK_SIZE = 16;
const UINT NUM_ELEMENTS = BITONIC_BLOCK_SIZE * TRANSPOSE_BLOCK_SIZE;
const UINT MATRIX_WIDTH = BITONIC_BLOCK_SIZE;
const UINT MATRIX_HEIGHT = NUM_ELEMENTS / BITONIC_BLOCK_SIZE;
class Fixture
{
public:
Fixture()
: data(NUM_ELEMENTS)
{
std::iota(std::begin(data), std::end(data), 0); // Fill with 0, 1, ..., 99.
std::shuffle(data.begin(), data.end(), std::mt19937{ std::random_device{}() });
}
void CPUShaderSort()
{
cpuShader.InitializeGroupShareds();
// Upload the data
cpuShader.UpdateSubresource(buffer1UAV, data);
// Sort the data
// First sort the rows for the levels <= to the block size
for (UINT level = 2; level <= BITONIC_BLOCK_SIZE; level = level * 2)
{
cpuShader.SetConstants(level, level, MATRIX_HEIGHT, MATRIX_WIDTH);
// Sort the row data
cpuShader.SetUnorderedAccessViews0(buffer1UAV);
cpuShader.DispatchBitonicSort(NUM_ELEMENTS / BITONIC_BLOCK_SIZE, 1, 1);
}
// Then sort the rows and columns for the levels > than the block size
// Transpose. Sort the Columns. Transpose. Sort the Rows.
for (UINT level = (BITONIC_BLOCK_SIZE * 2); level <= NUM_ELEMENTS; level = level * 2)
{
cpuShader.SetConstants((level / BITONIC_BLOCK_SIZE), (level & ~NUM_ELEMENTS) / BITONIC_BLOCK_SIZE, MATRIX_WIDTH, MATRIX_HEIGHT);
// Transpose the data from buffer 1 into buffer 2
cpuShader.SetUnorderedAccessViews0(buffer2UAV);
cpuShader.SetShaderResources0(buffer1UAV);
cpuShader.DispatchMatrixTranspose(MATRIX_WIDTH / TRANSPOSE_BLOCK_SIZE, MATRIX_HEIGHT / TRANSPOSE_BLOCK_SIZE, 1);
// Sort the transposed column data
cpuShader.SetUnorderedAccessViews0(buffer2UAV);
cpuShader.SetShaderResources0(buffer1UAV);
cpuShader.DispatchBitonicSort(NUM_ELEMENTS / BITONIC_BLOCK_SIZE, 1, 1);
cpuShader.SetConstants(BITONIC_BLOCK_SIZE, level, MATRIX_HEIGHT, MATRIX_WIDTH);
// Transpose the data from buffer 2 back into buffer 1
cpuShader.SetUnorderedAccessViews0(buffer1UAV);
cpuShader.SetShaderResources0(buffer2UAV);
cpuShader.DispatchMatrixTranspose(MATRIX_HEIGHT / TRANSPOSE_BLOCK_SIZE, MATRIX_WIDTH / TRANSPOSE_BLOCK_SIZE, 1);
// Sort the row data
cpuShader.SetUnorderedAccessViews0(buffer1UAV);
cpuShader.SetShaderResources0(buffer2UAV);
cpuShader.DispatchBitonicSort(NUM_ELEMENTS / BITONIC_BLOCK_SIZE, 1, 1);
}
}
void verify()
{
std::sort(data.begin(), data.end());
bool are_shader_elements_sorted = true;
for (UINT i = 0; i < NUM_ELEMENTS; ++i)
{
if (data[i] != buffer1UAV[i].get())
{
are_shader_elements_sorted = false;
break;
}
}
EXPECT_TRUE(are_shader_elements_sorted);
}
CSSortExecutor cpuShader;
std::vector<uint> data;
StructuredBuffer<uint> buffer1UAV = CreateBuffer(NUM_ELEMENTS);
StructuredBuffer<uint> buffer2UAV = CreateBuffer(NUM_ELEMENTS);
};
TEST(BitonicSortGoogleTests, test_256_random_numbers_are_sorted)
{
Fixture fixture;
fixture.CPUShaderSort();
fixture.verify();
} | 32.11215 | 134 | 0.718859 | cg-enths |
ef06cc7913d800d05590c4294ebcef2dcc83755d | 1,312 | hpp | C++ | dumb/struct_type.hpp | Better-Idea/Mix-C | 71f34a5fc8c17a516cf99bc397289d046364a82e | [
"Apache-2.0"
] | 41 | 2019-09-24T02:17:34.000Z | 2022-01-18T03:14:46.000Z | dumb/struct_type.hpp | Better-Idea/Mix-C | 71f34a5fc8c17a516cf99bc397289d046364a82e | [
"Apache-2.0"
] | 2 | 2019-11-04T09:01:40.000Z | 2020-06-23T03:03:38.000Z | dumb/struct_type.hpp | Better-Idea/Mix-C | 71f34a5fc8c17a516cf99bc397289d046364a82e | [
"Apache-2.0"
] | 8 | 2019-09-24T02:17:35.000Z | 2021-09-11T00:21:03.000Z | #ifndef xpack_dumb_struct_type
#define xpack_dumb_struct_type
#pragma push_macro("xuser")
#undef xuser
#define xuser mixc::dumb_struct_type::inc
#include"meta/is_class.hpp"
#include"define/base_type.hpp"
#include"macro/xexport.hpp"
#include"macro/xstruct.hpp"
#pragma pop_macro("xuser")
namespace mixc::dumb_struct_type{
template<class type_t, bool is_class_v> struct struct_type;
template<class type_t>
xstruct(
xspec(struct_type, type_t, true),
xpubb(type_t)
)
using type_t::type_t;
struct_type(type_t const & value) :
type_t(value){}
$
template<class type_t>
xstruct(
xspec(struct_type, type_t, false),
xprif(m_value, type_t)
)
template<class ... args_t>
struct_type(args_t const & ... list) :
m_value(list...){
}
operator type_t & (){
return m_value;
}
operator const type_t & () const {
return m_value;
}
$
template<>
xstruct(
xspec(struct_type, void, false)
) $
}
namespace mixc::dumb_struct_type::origin{
template<class type_t>
using struct_type = mixc::dumb_struct_type::struct_type<type_t, inc::is_class<type_t>>;
}
#endif
xexport(mixc::dumb_struct_type::origin::struct_type) | 23.017544 | 91 | 0.634909 | Better-Idea |
ef07dd1b817e4792be3d05cbd9db9701b577f7e5 | 719 | cpp | C++ | src/Utils.cpp | beyondpie/smmtools | ae23c7aeef171ca676daf5b735cb362b097775bb | [
"MIT"
] | null | null | null | src/Utils.cpp | beyondpie/smmtools | ae23c7aeef171ca676daf5b735cb362b097775bb | [
"MIT"
] | null | null | null | src/Utils.cpp | beyondpie/smmtools | ae23c7aeef171ca676daf5b735cb362b097775bb | [
"MIT"
] | null | null | null | #include <Rcpp.h>
using namespace Rcpp;
using namespace std;
// From ArchR General_Utils.cpp
//' @export
// [[Rcpp::export]]
IntegerMatrix tabulate2dCpp(IntegerVector &x, int xmin, int xmax, IntegerVector &y, int ymin, int ymax){
if(x.size() != y.size()){
stop("width must equal size!");
}
int n = x.size();
IntegerVector rx = seq(xmin, xmax);
IntegerVector ry = seq(ymin, ymax);
IntegerMatrix mat( ry.size() , rx.size() );
int rys = ry.size();
int rxs = rx.size();
int xi,yi;
for(int i = 0; i < n; i++){
xi = (x[i] - xmin);
yi = (y[i] - ymin);
if(yi >= 0 && yi < rys){
if(xi >= 0 && xi < rxs){
mat( yi , xi ) = mat( yi , xi ) + 1;
}
}
}
return mat;
}
| 23.193548 | 104 | 0.549374 | beyondpie |
ef0a259c06d7514e25f75d6c2e539ad8cb532c06 | 847 | hpp | C++ | tools/builder/tests/test_unit.hpp | kroschenko/sc-machine | 10a9535b3b9151ed683d351f2d222a95fc078e2b | [
"MIT"
] | null | null | null | tools/builder/tests/test_unit.hpp | kroschenko/sc-machine | 10a9535b3b9151ed683d351f2d222a95fc078e2b | [
"MIT"
] | null | null | null | tools/builder/tests/test_unit.hpp | kroschenko/sc-machine | 10a9535b3b9151ed683d351f2d222a95fc078e2b | [
"MIT"
] | 1 | 2021-12-03T13:20:18.000Z | 2021-12-03T13:20:18.000Z | #pragma once
#include "sc-memory/sc_memory.hpp"
#include "sc-test-framework/sc_test_unit.hpp"
class BuilderTestUnit : public test::ScTestUnit
{
public:
BuilderTestUnit(char const * name, char const * filename, void(*fn)())
: test::ScTestUnit(name, filename, fn)
{
}
private:
void InitMemory(std::string const & configPath, std::string const& extPath)
{
sc_memory_params params;
sc_memory_params_clear(¶ms);
params.clear = SC_FALSE;
params.repo_path = "sc-builder-test-repo";
params.config_file = configPath.c_str();
params.ext_path = extPath.empty() ? nullptr : extPath.c_str();
ScMemory::LogMute();
ScMemory::Initialize(params);
ScMemory::LogUnmute();
}
void ShutdownMemory(bool save)
{
ScMemory::LogMute();
ScMemory::Shutdown(false);
ScMemory::LogUnmute();
}
}; | 22.289474 | 77 | 0.682409 | kroschenko |
ef0ef559862657a01afc6f45f44cc0c3b75f121d | 669 | cc | C++ | p1134_Armstrong_Number/p1134.cc | Song1996/Leetcode | ecb0a2de67a57b899a12d0cb18272fb37dbf3ceb | [
"MIT"
] | null | null | null | p1134_Armstrong_Number/p1134.cc | Song1996/Leetcode | ecb0a2de67a57b899a12d0cb18272fb37dbf3ceb | [
"MIT"
] | null | null | null | p1134_Armstrong_Number/p1134.cc | Song1996/Leetcode | ecb0a2de67a57b899a12d0cb18272fb37dbf3ceb | [
"MIT"
] | null | null | null | #include <cstring>
using namespace std;
class Solution {
int mem[10];
public:
bool isArmstrong(int N) {
memset(mem, 0, sizeof(mem));
int k = 0, tN = N;
while(tN) {
k++;
tN /= 10;
}
int t = 0;
tN = N;
while(tN) {
int digit = tN%10;
if(digit!=0 && mem[digit] == 0) {
mem[digit] = 1;
for(int i = 0; i < k; i++) {
mem[digit] *= digit;
}
}
if(t > N - mem[digit]) return false;
t += mem[digit];
tN /= 10;
}
return t == N;
}
}; | 22.3 | 48 | 0.35426 | Song1996 |
ef121b6433466d48f1537461069d45be9e1d1f13 | 1,547 | cpp | C++ | src/FalconEngine/Graphics/Renderer/Resource/VertexBufferBinding.cpp | LiuYiZhou95/FalconEngine | b798f20e9dbd01334a4e4cdbbd9a5bec74966418 | [
"MIT"
] | null | null | null | src/FalconEngine/Graphics/Renderer/Resource/VertexBufferBinding.cpp | LiuYiZhou95/FalconEngine | b798f20e9dbd01334a4e4cdbbd9a5bec74966418 | [
"MIT"
] | null | null | null | src/FalconEngine/Graphics/Renderer/Resource/VertexBufferBinding.cpp | LiuYiZhou95/FalconEngine | b798f20e9dbd01334a4e4cdbbd9a5bec74966418 | [
"MIT"
] | 1 | 2021-08-25T07:39:02.000Z | 2021-08-25T07:39:02.000Z | #include <FalconEngine/Graphics/Renderer/Resource/VertexBufferBinding.h>
namespace FalconEngine
{
/************************************************************************/
/* Constructors and Destructor */
/************************************************************************/
VertexBufferBinding::VertexBufferBinding(
const std::shared_ptr<VertexBuffer>& buffer,
unsigned int index,
int64_t offset,
int stride,
const VertexGroup *group) :
mIndex(index),
mOffset(offset),
mStride(stride),
mBuffer(buffer),
mGroup(group)
{
}
VertexBufferBinding::~VertexBufferBinding()
{
}
/************************************************************************/
/* Public Members */
/************************************************************************/
unsigned int
VertexBufferBinding::GetIndex() const
{
return mIndex;
}
int64_t
VertexBufferBinding::GetOffset() const
{
return mOffset;
}
void
VertexBufferBinding::SetOffset(int64_t offset)
{
mOffset = offset;
}
int
VertexBufferBinding::GetStride() const
{
return mStride;
}
const VertexBuffer *
VertexBufferBinding::GetBuffer() const
{
return mBuffer.get();
}
std::shared_ptr<VertexBuffer>
VertexBufferBinding::GetBuffer()
{
return mBuffer;
}
const VertexGroup *
VertexBufferBinding::GetGroup() const
{
return mGroup;
}
}
| 21.486111 | 74 | 0.49192 | LiuYiZhou95 |
ef144b3773b9e051b1016c5697677a77f0ffa937 | 1,442 | cpp | C++ | electricity.cpp | Skywalker-19/SEM_1-2 | f8616b750480eb96e538ea452457b3b46d2e6b46 | [
"MIT"
] | null | null | null | electricity.cpp | Skywalker-19/SEM_1-2 | f8616b750480eb96e538ea452457b3b46d2e6b46 | [
"MIT"
] | null | null | null | electricity.cpp | Skywalker-19/SEM_1-2 | f8616b750480eb96e538ea452457b3b46d2e6b46 | [
"MIT"
] | null | null | null |
#include<iostream>
using namespace std;
class electricity{
protected:
float unit;
float cost;
float calcost;
float charge;
float diff;
float servicecharge;
public:
electricity()
{
cost=0.0;
calcost=0.0;
charge=0.0;
diff=0.0;
servicecharge=75;
}
void acceptunits();
void calfinalbill();
void displaybill();
};
void electricity::acceptunits()
{
cout<<"\n Enter no. of units consumed: ";
cin>>unit;
}
void electricity::calfinalbill()
{
if (unit<=100)
{
cost=0.9*unit;
cout<<"cost upto 100 units is Rs." <<cost<<endl;
}
else
{
if (unit<=200)
{
cost=1*unit;
}
else
{
cost=1.3*unit;
}
}
calcost=cost;
cost=cost+servicecharge;
if(cost>250.00)
{
diff=cost-250;
charge=diff*0.15;
cost=cost+charge;
}
}
void electricity::displaybill()
{
cout<<"---------------------------------------"<<endl;
cout<<" My Electricity Bill "<<endl;
cout<<"---------------------------------------"<<endl;
cout<<"\n Units consumed : "<<unit<<endl;
cout<<"\n Difference: "<<diff<<endl;
cout<<"---------------------------------------"<<endl;
cout<<"\n Cal. Bill cost(+) : "<<calcost<<endl;
cout<<"\n Service Charge(+) : "<<servicecharge<<endl;
cout<<"\n SurCharge(+) : "<<charge<<endl;
cout<<"---------------------------------------"<<endl;
cout<<"\n Total Bill Amount(Rs) \t : "<<cost<<endl;
cout<<"---------------------------------------"<<endl;
}
int main()
{
electricity elect;
elect.acceptunits();
elect.calfinalbill();
elect.displaybill();
return 0;
}
| 18.025 | 54 | 0.570735 | Skywalker-19 |
ef14c63047e2d556cce90198eab5ef1fd6116c6f | 3,726 | cpp | C++ | BeanDogEngine/GameObject.cpp | RoyFilipchuk56/BeanDogEngine | 189ff606b1568b8c2228602b545767bb827d3065 | [
"MIT"
] | null | null | null | BeanDogEngine/GameObject.cpp | RoyFilipchuk56/BeanDogEngine | 189ff606b1568b8c2228602b545767bb827d3065 | [
"MIT"
] | null | null | null | BeanDogEngine/GameObject.cpp | RoyFilipchuk56/BeanDogEngine | 189ff606b1568b8c2228602b545767bb827d3065 | [
"MIT"
] | null | null | null | #include "GameObject.h"
GameObject::GameObject(cMesh* mesh, glm::vec3 transform, glm::vec3 rotation) :
mesh(mesh), friendlyName(""), receiver(NULL)
{
//Set the position to the given position
SetPosition(position);
//Set both rotations to the given rotations
SetRotation(rotation);
SetRotationQuat(quaternion::QuatFromAngles(rotation));
}
GameObject::GameObject(cMesh* mesh) :
mesh(mesh), friendlyName(""), receiver(NULL)
{
//Make sure the mesh isnt null
if (mesh != NULL)
{
position = mesh->transformXYZ;
rotationXYZ = glm::vec3(glm::degrees(mesh->rotationXYZ.x), glm::degrees(mesh->rotationXYZ.y), glm::degrees(mesh->rotationXYZ.z));
rotationXYZQuat = mesh->rotationXYZQuat;
}
//If its null then set zero values
else
{
position = glm::vec3(0);
rotationXYZ = glm::vec3(0);
rotationXYZQuat = glm::quat(glm::vec3(0.0));
}
}
GameObject::GameObject(glm::vec3 transform) :
mesh(NULL), position(position), rotationXYZ(glm::vec3(0)), friendlyName(""), receiver(NULL)
{
rotationXYZQuat = glm::quat(glm::vec3(0.0, 0.0, 0.0));
}
GameObject::~GameObject()
{
//Delete the mesh if it exists
if (mesh != NULL)
{
delete mesh;
}
if (commands != NULL)
delete commands;
}
void GameObject::Update(float deltaTime)
{
}
void GameObject::UpdateCommands(float deltaTime)
{
if (commands != NULL)
{
commands->Update(deltaTime);
}
}
void GameObject::SetFriendlyName(std::string friendlyName)
{
this->friendlyName = friendlyName;
}
std::string GameObject::GetFriendlyName()
{
return friendlyName;
}
cMesh* GameObject::GetMesh()
{
if (mesh != NULL)
return mesh;
return nullptr;
}
void GameObject::SetMesh(cMesh* mesh)
{
this->mesh = mesh;
this->rotationXYZ = glm::vec3(glm::degrees(mesh->rotationXYZ.x), glm::degrees(mesh->rotationXYZ.y), glm::degrees(mesh->rotationXYZ.z));
this->position = mesh->rotationXYZ;
}
void GameObject::SetPosition(glm::vec3 position)
{
this->position = position;
if (mesh != NULL)
mesh->transformXYZ = position;
}
glm::vec3 GameObject::GetPosition()
{
return position;
}
void GameObject::SetRotation(glm::vec3 rotationXYZ)
{
this->rotationXYZ = rotationXYZ;
this->rotationXYZQuat = quaternion::QuatFromAngles(rotationXYZ);
if (mesh != NULL)
{
mesh->rotationXYZ = glm::vec3(glm::radians(rotationXYZ.x), glm::radians(rotationXYZ.y), glm::radians(rotationXYZ.z));
mesh->rotationXYZQuat = quaternion::QuatFromAngles(rotationXYZ);
}
}
void GameObject::SetRotationRadians(glm::vec3 rotationXYZ)
{
this->rotationXYZ = glm::vec3(glm::degrees(rotationXYZ.x), glm::degrees(rotationXYZ.y), glm::degrees(rotationXYZ.z));
this->rotationXYZQuat = quaternion::QuatFromAngles(rotationXYZ);
if (mesh != NULL)
{
mesh->rotationXYZ = glm::vec3(rotationXYZ.x, rotationXYZ.y, rotationXYZ.z);
mesh->rotationXYZQuat = quaternion::QuatFromAngles(rotationXYZ);
}
}
void GameObject::SetRotationQuat(glm::quat rotationXYZ)
{
rotationXYZQuat = rotationXYZ;
if (mesh != NULL)
mesh->rotationXYZQuat = rotationXYZQuat;
}
glm::quat GameObject::GetRotationQuat()
{
return rotationXYZQuat;
}
glm::vec3 GameObject::GetRotation()
{
return rotationXYZ;
}
void GameObject::SetScale(glm::vec3 scale)
{
if (mesh != NULL)
mesh->scaleXYZ = scale;
}
void GameObject::SetScale(float scale)
{
mesh->scale = scale;
mesh->scaleXYZ = glm::vec3(scale, scale, scale);
}
CommandController* GameObject::GetCommandController()
{
if (commands == NULL)
commands = new CommandController();
return commands;
}
bool GameObject::SetReciever(iMessage* receiver)
{
this->receiver = receiver;
return true;
}
bool GameObject::RecieveMessage(sMessage message)
{
return false;
}
bool GameObject::RecieveMessage(sMessage message, sMessage& reply)
{
return false;
}
| 21.170455 | 136 | 0.718733 | RoyFilipchuk56 |
ef15ada3447744a2f9cc4f4f98e831184f1e39f0 | 937 | cpp | C++ | client/include/game/CEntryExitManager.cpp | MayconFelipeA/sampvoiceatt | 3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff | [
"MIT"
] | 97 | 2019-01-13T20:19:19.000Z | 2022-02-27T18:47:11.000Z | client/include/game/CEntryExitManager.cpp | MayconFelipeA/sampvoiceatt | 3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff | [
"MIT"
] | 92 | 2019-01-23T23:02:31.000Z | 2022-03-23T19:59:40.000Z | client/include/game/CEntryExitManager.cpp | MayconFelipeA/sampvoiceatt | 3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff | [
"MIT"
] | 69 | 2019-01-13T22:01:40.000Z | 2022-03-09T00:55:49.000Z | /*
Plugin-SDK (Grand Theft Auto San Andreas) source file
Authors: GTA Community. See more here
https://github.com/DK22Pac/plugin-sdk
Do not delete this comment block. Respect others' work!
*/
#include "CEntryExitManager.h"
// US-1.00 @ 0x0096A7D8
// EU-1.00 @ 0x0096A7D8
CPool<CEntryExit> *& CEntryExitManager::mp_poolEntryExits = *reinterpret_cast<CPool<CEntryExit> **>(0x0096A7D8);
// US-1.00 @ 0x0043F880
// EU-1.00 @ 0x0043F880 (securom)
void CEntryExitManager::Init(void) {
plugin::Call<0x0043F880>();
}
// US-1.00 @ 0x00440B90
// EU-1.00 @ 0x00440B90 (securom)
void CEntryExitManager::Shutdown(void) {
plugin::Call<0x00440B90>();
}
// US-1.00 @ 0x005D5860
// EU-1.00 @ 0x005D5860
bool CEntryExitManager::Save(void) {
return plugin::CallAndReturn<bool, 0x005D5860>();
}
// US-1.00 @ 0x005D55C0
// EU-1.00 @ 0x005D55C0
bool CEntryExitManager::Load(void) {
return plugin::CallAndReturn<bool, 0x005D55C0>();
}
| 26.027778 | 112 | 0.708645 | MayconFelipeA |
ef17dad97c0d73b196cfc8c6ba43cf16d1db97b0 | 498 | cpp | C++ | test_constexpr.cpp | zyfjeff/CPP-Class-Study | c6cd84a3c5b406c1c9bf5828f08e587742370457 | [
"Apache-2.0"
] | 2 | 2017-02-13T19:26:45.000Z | 2017-06-20T14:29:28.000Z | test_constexpr.cpp | zyfjeff/CPP-Class-Study | c6cd84a3c5b406c1c9bf5828f08e587742370457 | [
"Apache-2.0"
] | null | null | null | test_constexpr.cpp | zyfjeff/CPP-Class-Study | c6cd84a3c5b406c1c9bf5828f08e587742370457 | [
"Apache-2.0"
] | null | null | null | /*
=====================================================================================
Filename: test_constexpr.cpp
Description: 测试常量表达式
Version: 1.0
Created: 27/02/15 17:44:27
Revision: none
Compiler: gcc
Author: Jeff (), zyfforlinux@163.com
Organization: Linux
=====================================================================================
*/
#include <iostream>
int a = 213;
int main()
{
constexpr int *q = &a;
}
| 23.714286 | 86 | 0.363454 | zyfjeff |
fa9fa22aaef5cf909ae66ec469f8a5d5c74ab7b4 | 1,326 | cpp | C++ | Editor/Sources/o2Editor/AnimationWindow/TrackControls/ITrackControl.cpp | zenkovich/o2 | cdbf10271f1bf0f3198c8005b13b66e6ca13a9db | [
"MIT"
] | 181 | 2015-12-09T08:53:36.000Z | 2022-03-26T20:48:39.000Z | Editor/Sources/o2Editor/AnimationWindow/TrackControls/ITrackControl.cpp | zenkovich/o2 | cdbf10271f1bf0f3198c8005b13b66e6ca13a9db | [
"MIT"
] | 29 | 2016-04-22T08:24:04.000Z | 2022-03-06T07:06:28.000Z | Editor/Sources/o2Editor/AnimationWindow/TrackControls/ITrackControl.cpp | zenkovich/o2 | cdbf10271f1bf0f3198c8005b13b66e6ca13a9db | [
"MIT"
] | 13 | 2018-04-24T17:12:04.000Z | 2021-11-12T23:49:53.000Z | #include "o2Editor/stdafx.h"
#include "ITrackControl.h"
namespace Editor
{
void ITrackControl::Initialize(AnimationTimeline* timeline, KeyHandlesSheet* handlesSheet)
{}
void ITrackControl::SetTrack(IAnimationTrack* track, IAnimationTrack::IPlayer* player, const String& path)
{}
void ITrackControl::UpdateHandles()
{}
Vector<ITrackControl::KeyHandle*> ITrackControl::GetKeyHandles() const
{
return Vector<KeyHandle*>();
}
Widget* ITrackControl::GetTreePartControls() const
{
return nullptr;
}
void ITrackControl::SetCurveViewEnabled(bool enabled)
{}
void ITrackControl::SetCurveViewColor(const Color4& color)
{}
void ITrackControl::SetActive(bool active)
{}
void ITrackControl::InsertNewKey(float time)
{}
void ITrackControl::BeginKeysDrag()
{}
void ITrackControl::EndKeysDrag()
{}
void ITrackControl::SerializeKey(UInt64 keyUid, DataValue& data, float relativeTime)
{}
UInt64 ITrackControl::DeserializeKey(const DataValue& data, float relativeTime, bool generateNewUid /*= true*/)
{
return 0;
}
void ITrackControl::DeleteKey(UInt64 keyUid)
{}
String ITrackControl::GetCreateMenuCategory()
{
return "UI/Editor";
}
bool ITrackControl::KeyHandle::operator==(const KeyHandle& other) const
{
return handle == other.handle;
}
}
DECLARE_CLASS(Editor::ITrackControl);
| 19.791045 | 112 | 0.748869 | zenkovich |
faa40d2ef987922d6e3dc7933060d0e89f4d4c42 | 854 | cpp | C++ | test/limits.cpp | meh/paku | f668fb93659853c98ebef87a8d1b58fad60820b6 | [
"Unlicense"
] | 1 | 2016-03-03T01:22:43.000Z | 2016-03-03T01:22:43.000Z | test/limits.cpp | meh/paku | f668fb93659853c98ebef87a8d1b58fad60820b6 | [
"Unlicense"
] | null | null | null | test/limits.cpp | meh/paku | f668fb93659853c98ebef87a8d1b58fad60820b6 | [
"Unlicense"
] | null | null | null | #include <cstddef>
#include <amirite>
#include <paku/packet/limits>
using namespace paku;
int
main (int argc, char* argv[])
{
(void) argc;
(void) argv;
return amirite("packet/limits", {
{ "ether", []{
amiequal(packet::limits<packet::ether>::max(), 14U);
amiequal(packet::limits<packet::ether>::min(), 14U);
}},
{ "arp", []{
amiequal(packet::limits<packet::arp>::min(), 28U);
amiequal(packet::limits<packet::arp>::max(), 28U);
}},
{ "ip", []{
amiequal(packet::limits<packet::ip>::min(), 20U);
amiequal(packet::limits<packet::ip>::max(), 60U);
}},
{ "icmp", []{
amiequal(packet::limits<packet::icmp>::min(), 8U);
amiequal(packet::limits<packet::icmp>::max(), 76U);
}},
{ "tcp", []{
amiequal(packet::limits<packet::tcp>::min(), 20U);
amiequal(packet::limits<packet::tcp>::max(), 60U);
}},
});
}
| 20.829268 | 55 | 0.587822 | meh |
faab41d34ff046d683857ee33a2bc53fb6fdbcaa | 1,169 | cpp | C++ | source/aufgabe5.cpp | Zlobarq/programmiersprachen-aufgabenblatt-3 | d803946f06e8e9128909928593b9b590d2d27464 | [
"MIT"
] | null | null | null | source/aufgabe5.cpp | Zlobarq/programmiersprachen-aufgabenblatt-3 | d803946f06e8e9128909928593b9b590d2d27464 | [
"MIT"
] | null | null | null | source/aufgabe5.cpp | Zlobarq/programmiersprachen-aufgabenblatt-3 | d803946f06e8e9128909928593b9b590d2d27464 | [
"MIT"
] | null | null | null | #define CATCH_CONFIG_RUNNER
#include <catch.hpp>
#include <cmath>
#include <algorithm>
#include <vector>
//initialize globally
std::vector<unsigned int> vector= {};
//function
bool is_multiple_of_three(int i){
if (i%3 ==0)
{
return true;
}
return false;
}
bool isnt_multiple_of_three(int i){
if (i%3 !=0)
{
return true;
}
return false;
}
TEST_CASE ("filter alle vielfache von drei","[erase]")
{
REQUIRE(std::all_of(vector.begin(),vector.end(),is_multiple_of_three));
}
int main(int argc ,char *argv [])
{
//Working around in main
//initialization/defition
int grenze=std::rand() % 101;
int randvalue=0;
//vector Creating Loop
for (int i=0;i<=grenze;i++)
{
randvalue=std::rand() % 101;
vector.push_back(randvalue);
}
//print vector
std::cout <<"Vector:"<<"\n";
for (int n : vector)
{
std::cout << n <<" ";
}
std::cout <<"\n";
//erase
vector.erase(std::remove_if(vector.begin(),vector.end(),isnt_multiple_of_three),vector.end());
//print vector again
std::cout <<"Print vector of durch 3 teilbaren:"<<"\n";
for (int n : vector)
{
std::cout << n <<" ";
}
std::cout <<"\n";
return Catch::Session().run(argc,argv);
}
| 17.712121 | 94 | 0.644996 | Zlobarq |
fab41ac4223b7fd3c162b0ed14e376d7389a7be4 | 201 | cpp | C++ | src/text/utils.cpp | fizixx/nucleus | a095aa9768c3e330a1ed17bebfd0d72e33033aaa | [
"MIT"
] | 1 | 2018-01-03T17:55:18.000Z | 2018-01-03T17:55:18.000Z | src/text/utils.cpp | tiaanl/nucleus | a095aa9768c3e330a1ed17bebfd0d72e33033aaa | [
"MIT"
] | 1 | 2015-06-26T20:27:45.000Z | 2015-06-29T07:27:42.000Z | src/text/utils.cpp | tiaanl/nucleus | a095aa9768c3e330a1ed17bebfd0d72e33033aaa | [
"MIT"
] | 1 | 2015-06-26T18:31:05.000Z | 2015-06-26T18:31:05.000Z | #include "nucleus/text/utils.h"
namespace nu {
auto zeroTerminated(StringView source) -> DynamicString {
DynamicString result{source};
result.append('\0');
return result;
}
} // namespace nu
| 16.75 | 57 | 0.711443 | fizixx |
fab624d49a5e190dd2a75ed084c6245f856f81f1 | 22,047 | cpp | C++ | src/elix_rgbabuffer.cpp | lukesalisbury/elix | 171aedf7c925513408b785dde24c58bcee74acf3 | [
"Zlib"
] | 3 | 2015-04-14T13:14:34.000Z | 2020-01-31T04:02:35.000Z | src/elix_rgbabuffer.cpp | lukesalisbury/elix | 171aedf7c925513408b785dde24c58bcee74acf3 | [
"Zlib"
] | null | null | null | src/elix_rgbabuffer.cpp | lukesalisbury/elix | 171aedf7c925513408b785dde24c58bcee74acf3 | [
"Zlib"
] | null | null | null | #include "elix_core.h"
#include "elix_rgbabuffer.hpp"
#include "elix_file.hpp"
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation
#include "stb_truetype.h"
struct rgbabuffer_edge_type {
float ymin, ymax, xval, slope;
};
struct rgbabuffer_active_edge_index {
uint32_t index;
float xval;
};
struct rgbabuffer_font {
stbtt_fontinfo info;
elix_databuffer data;
float scale, baseline;
int base_ascent, base_descent, base_line_gap;
};
uint32_t rbgabuffer_get_pixel(rbgabuffer_context * ctx, uint32_t x , uint32_t y) {
if (x < ctx->memory->width && y < ctx->memory->height ) {
return ctx->memory->pixels[ x + (y*ctx->memory->width)];
}
return 0xDEADC0DE;
}
void rbgabuffer__pixel(rbgabuffer_context * ctx, uint32_t colour, int32_t x , int32_t y, UNUSEDARG float alpha = 1.0) {
elix_colour final_colour = {colour};
if ( alpha < 0.2 ) {
return;
}
if ( alpha < 1.0 ) {
elix_colour source_colour = {rbgabuffer_get_pixel(ctx,x,y)};
final_colour.a = 255;
final_colour.r = static_cast<uint8_t>( (final_colour.r * alpha) + (source_colour.r * (1.0 - alpha)) );
final_colour.g = static_cast<uint8_t>( (final_colour.g * alpha) + (source_colour.g * (1.0 - alpha)) );
final_colour.b = static_cast<uint8_t>( (final_colour.b * alpha) + (source_colour.b * (1.0 - alpha)) );
}
if (x >= 0 && y >= 0 && (uint32_t)x < ctx->memory->width && (uint32_t)y < ctx->memory->height ) {
ctx->memory->pixels[ x + (y*ctx->memory->width)] = final_colour.hex;
}
}
void rbgabuffer__line(elix_v2 p0, elix_v2 p1, rbgabuffer_context * ctx, uint32_t colour) {
//ctx->memory[x+(y*ctx->width)] = colour;
int32_t x0 = p0.x;
int32_t x1 = p1.x;
int32_t y0 = p0.y;
int32_t y1 = p1.y;
int32_t dy = y1 - y0;
int32_t dx = x1 - x0;
int32_t stepx, stepy;
if (dy < 0) { dy = -dy; stepy = -1; } else { stepy = 1; }
if (dx < 0) { dx = -dx; stepx = -1; } else { stepx = 1; }
rbgabuffer__pixel(ctx, colour, x0 ,y0 );
#define myPixel( d, a, b, c) rbgabuffer__pixel(a, d, b ,c );
if (dx > dy) {
int length = (dx - 1) >> 2;
int extras = (dx - 1) & 3;
int incr2 = (dy << 2) - (dx << 1);
if (incr2 < 0) {
int c = dy << 1;
int incr1 = c << 1;
int d = incr1 - dx;
for (int i = 0; i < length; i++) {
x0 += stepx;
x1 -= stepx;
if (d < 0) {
rbgabuffer__pixel(ctx, colour, x0, y0 );
rbgabuffer__pixel(ctx, colour, x0 += stepx, y0 );
rbgabuffer__pixel(ctx, colour, x1, y1 );
rbgabuffer__pixel(ctx, colour, x1 -= stepx, y1 );
d += incr1;
} else {
if (d < c) {
rbgabuffer__pixel(ctx, colour, x0, y0 );
rbgabuffer__pixel(ctx, colour, x0 += stepx, y0 += stepy );
rbgabuffer__pixel(ctx, colour, x1, y1 );
rbgabuffer__pixel(ctx, colour, x1 -= stepx, y1 -= stepy );
} else {
rbgabuffer__pixel(ctx, colour, x0, y0 += stepy );
rbgabuffer__pixel(ctx, colour, x0 += stepx, y0 );
rbgabuffer__pixel(ctx, colour, x1, y1 -= stepy );
rbgabuffer__pixel(ctx, colour, x1 -= stepx, y1 );
}
d += incr2;
}
}
if (extras > 0) {
if (d < 0) {
myPixel( colour, ctx, x0 += stepx, y0);
if (extras > 1)
if (extras > 2) myPixel( colour, ctx, x1 -= stepx, y1);
} else
if (d < c) {
myPixel( colour, ctx, x0 += stepx, y0);
if (extras > 1) myPixel( colour, ctx, x0 += stepx, y0 += stepy);
if (extras > 2) myPixel( colour, ctx, x1 -= stepx, y1);
} else {
myPixel( colour, ctx, x0 += stepx, y0 += stepy);
if (extras > 1) myPixel( colour, ctx, x0 += stepx, y0);
if (extras > 2) myPixel( colour, ctx, x1 -= stepx, y1 -= stepy);
}
}
} else {
int c = (dy - dx) << 1;
int incr1 = c << 1;
int d = incr1 + dx;
for (int i = 0; i < length; i++) {
x0 += stepx;
x1 -= stepx;
if (d > 0) {
myPixel( colour, ctx, x0, y0 += stepy); // Pattern:
myPixel( colour, ctx, x0 += stepx, y0 += stepy); // o
myPixel( colour, ctx, x1, y1 -= stepy); // o
myPixel( colour, ctx, x1 -= stepx, y1 -= stepy); // x
d += incr1;
} else {
if (d < c) {
myPixel( colour, ctx, x0, y0); // Pattern:
myPixel( colour, ctx, x0 += stepx, y0 += stepy); // o
myPixel( colour, ctx, x1, y1); // x o
myPixel( colour, ctx, x1 -= stepx, y1 -= stepy); //
} else {
myPixel( colour, ctx, x0, y0 += stepy); // Pattern:
myPixel( colour, ctx, x0 += stepx, y0); // o o
myPixel( colour, ctx, x1, y1 -= stepy); // x
myPixel( colour, ctx, x1 -= stepx, y1); //
}
d += incr2;
}
}
if (extras > 0) {
if (d > 0) {
myPixel( colour, ctx, x0 += stepx, y0 += stepy);
if (extras > 1) myPixel( colour, ctx, x0 += stepx, y0 += stepy);
if (extras > 2) myPixel( colour, ctx, x1 -= stepx, y1 -= stepy);
} else
if (d < c) {
myPixel( colour, ctx, x0 += stepx, y0);
if (extras > 1) myPixel( colour, ctx, x0 += stepx, y0 += stepy);
if (extras > 2) myPixel( colour, ctx, x1 -= stepx, y1);
} else {
myPixel( colour, ctx, x0 += stepx, y0 += stepy);
if (extras > 1) myPixel( colour, ctx, x0 += stepx, y0);
if (extras > 2) {
if (d > c) {
myPixel( colour, ctx, x1 -= stepx, y1 -= stepy);
} else {
myPixel( colour, ctx, x1 -= stepx, y1);
}
}
}
}
}
} else {
int length = (dy - 1) >> 2;
int extras = (dy - 1) & 3;
int incr2 = (dx << 2) - (dy << 1);
if (incr2 < 0) {
int c = dx << 1;
int incr1 = c << 1;
int d = incr1 - dy;
for (int i = 0; i < length; i++) {
y0 += stepy;
y1 -= stepy;
if (d < 0) {
myPixel( colour, ctx, x0, y0);
myPixel( colour, ctx, x0, y0 += stepy);
myPixel( colour, ctx, x1, y1);
myPixel( colour, ctx, x1, y1 -= stepy);
d += incr1;
} else {
if (d < c) {
myPixel( colour, ctx, x0, y0);
myPixel( colour, ctx, x0 += stepx, y0 += stepy);
myPixel( colour, ctx, x1, y1);
myPixel( colour, ctx, x1 -= stepx, y1 -= stepy);
} else {
myPixel( colour, ctx, x0 += stepx, y0);
myPixel( colour, ctx, x0, y0 += stepy);
myPixel( colour, ctx, x1 -= stepx, y1);
myPixel( colour, ctx, x1, y1 -= stepy);
}
d += incr2;
}
}
if (extras > 0) {
if (d < 0) {
myPixel( colour, ctx, x0, y0 += stepy);
if (extras > 1) myPixel( colour, ctx, x0, y0 += stepy);
if (extras > 2) myPixel( colour, ctx, x1, y1 -= stepy);
} else
if (d < c) {
myPixel( colour, ctx, stepx, y0 += stepy);
if (extras > 1) myPixel( colour, ctx, x0 += stepx, y0 += stepy);
if (extras > 2) myPixel( colour, ctx, x1, y1 -= stepy);
} else {
myPixel( colour, ctx, x0 += stepx, y0 += stepy);
if (extras > 1) myPixel( colour, ctx, x0, y0 += stepy);
if (extras > 2) myPixel( colour, ctx, x1 -= stepx, y1 -= stepy);
}
}
} else {
int c = (dx - dy) << 1;
int incr1 = c << 1;
int d = incr1 + dy;
for (int i = 0; i < length; i++) {
y0 += stepy;
y1 -= stepy;
if (d > 0) {
myPixel( colour, ctx, x0 += stepx, y0);
myPixel( colour, ctx, x0 += stepx, y0 += stepy);
myPixel( colour, ctx, x1 -= stepx, y1);
myPixel( colour, ctx, x1 -= stepx, y1 -= stepy);
d += incr1;
} else {
if (d < c) {
myPixel( colour, ctx, x0, y0);
myPixel( colour, ctx, x0 += stepx, y0 += stepy);
myPixel( colour, ctx, x1, y1);
myPixel( colour, ctx, x1 -= stepx, y1 -= stepy);
} else {
myPixel( colour, ctx, x0 += stepx, y0);
myPixel( colour, ctx, x0, y0 += stepy);
myPixel( colour, ctx, x1 -= stepx, y1);
myPixel( colour, ctx, x1, y1 -= stepy);
}
d += incr2;
}
}
if (extras > 0) {
if (d > 0) {
myPixel( colour,ctx,x0 += stepx, y0 += stepy);
if (extras > 1) myPixel( colour, ctx, x0 += stepx, y0 += stepy);
if (extras > 2) myPixel( colour, ctx, x1 -= stepx, y1 -= stepy);
} else
if (d < c) {
myPixel( colour,ctx,x0, y0 += stepy);
if (extras > 1) myPixel( colour, ctx, x0 += stepx, y0 += stepy);
if (extras > 2) myPixel( colour, ctx, x1, y1 -= stepy);
} else {
myPixel( colour,ctx,x0 += stepx, y0 += stepy);
if (extras > 1) myPixel( colour, ctx, x0, y0 += stepy);
if (extras > 2) {
if (d > c) {
myPixel( colour, ctx, x1 -= stepx, y1 -= stepy);
}
else {
myPixel( colour, ctx, x1, y1 -= stepy);
}
}
}
}
}
}
}
void rbgabuffer__appendCommands(rbgabuffer_context * ctx, float * vals, uint32_t nvals) {
if ( ctx->commands.index + nvals > ctx->commands.max ) {
size_t ccommands = (ctx->commands.index + nvals + 16) * sizeof(float);
float * ncommands = (float*)realloc(ctx->commands.array, ccommands);
if (ncommands == nullptr) return; // Failure to create new array
ctx->commands.array = ncommands;
ctx->commands.max += ccommands;
}
memcpy(&ctx->commands.array[ctx->commands.index], vals, nvals*sizeof(float));
ctx->commands.index += nvals;
}
void rbgabuffer__testpattern(elix_graphic_data * buffer) {
uint32_t * p = buffer->pixels;
uint32_t a[6] { 0xFF550000, 0xFF550055, 0xFF000055, 0xFF005555,0xFF005500,0xFF555500 };
for ( uint32_t q = 0; q < buffer->pixel_count; q++, p++ ) {
uint32_t l = q / buffer->width;
*p = a[(l/10)%6];
}
}
void rbgabuffer__gridpattern(elix_graphic_data * buffer) {
uint32_t * p = buffer->pixels;
uint32_t a[2] { 0xFFEEEEEE, 0xFFAAAAAA };
for ( uint32_t q = 0; q < buffer->pixel_count; q++, p++ ) {
uint32_t l = (q / (buffer->width * 64));
uint32_t x = (q % buffer->width) / 64;
*p = a[(l+x)%2];
}
}
void rbgabuffer__staticpattern(elix_graphic_data * buffer) {
uint32_t * p = buffer->pixels;
uint32_t c = 0xFFFFFFFF;
for ( uint32_t q = 0; q < buffer->pixel_count; q++, p++ ) {
#if RAND_MAX == 32767
c = (rand() * rand()) | 0xFF000000;
#else
c = rand() | 0xFF000000;
#endif
*p = c;
}
}
void rbgabuffer_BeginPath(rbgabuffer_context* ctx) {
ctx->commands.index = 0;
}
void rbgabuffer_ClosePath(rbgabuffer_context* ctx) {
float vals[] = {
rbgabuffer_CLOSE,
};
rbgabuffer__appendCommands(ctx, vals, ARRAYCOUNT(vals));
}
void rbgabuffer_Rect(rbgabuffer_context* ctx, float x, float y, float w, float h) {
float vals[] = {
rbgabuffer_MOVETO, x,y,
rbgabuffer_LINETO, x,y+h,
rbgabuffer_LINETO, x+w,y+h,
rbgabuffer_LINETO, x+w,y,
rbgabuffer_CLOSE
};
rbgabuffer__appendCommands(ctx, vals, ARRAYCOUNT(vals));
}
inline uint32_t insertSorted(rgbabuffer_active_edge_index * arr, rgbabuffer_active_edge_index key, size_t count, size_t capacity)
{
if ( count >= capacity )
return UINT32_MAX; //ERROR
int32_t i = 0;
if ( count ) {
for (i=count-1; i >= 0 && arr[i].xval > key.xval; i--) {
arr[i+1] = arr[i];
}
arr[i+1] = key;
} else {
arr[0] = key;
}
return i;
}
inline uint32_t rgbabuffer_edge_type_insert(rgbabuffer_edge_type * arr, rgbabuffer_edge_type key, size_t count, size_t capacity)
{
if ( count >= capacity )
return UINT32_MAX; //ERROR
int32_t i = 0;
if ( count ) { //
//&& (arr[i].ymin > key.ymin || (arr[i].ymin == key.ymin && arr[i].xval > key.xval))
for (i=count-1; i >= 0 && arr[i].ymin > key.ymin; i--) {
arr[i+1] = arr[i];
}
arr[i+1] = key;
} else {
arr[0] = key;
}
return i;
}
void rbgabuffer_Fill(rbgabuffer_context* ctx) {
float x = 0.0, y = 0.0;
float * p = nullptr;
elix_v2 points[64];
uint32_t point_count = 0;
size_t ind = 0;
while (ind < ctx->commands.index) {
uint32_t cmd = (uint32_t)ctx->commands.array[ind];
switch (cmd) {
case rbgabuffer_MOVETO:
p = &ctx->commands.array[ind+1];
points[point_count].x = x = p[0];
points[point_count].y = y = p[1];
//LOG_MESSAGE("moveto %fx%f", points[point_count].x, points[point_count].y);
point_count++;
ind += 3;
break;
case rbgabuffer_LINETO:
p = &ctx->commands.array[ind+1];
points[point_count].x =p[0];
points[point_count].y =p[1];
//LOG_MESSAGE("lineto %fx%f", points[point_count].x, points[point_count].y);
point_count++;
ind += 3;
break;
case rbgabuffer_CLOSE:
points[point_count].x = x;
points[point_count].y = y;
//LOG_MESSAGE("CLOSE %fx%f", points[point_count].x, points[point_count].y);
//point_count++;
ind++;
break;
default:
ind++;
}
}
elix_v2 y_limits, x_limits; // TODO
rgbabuffer_edge_type edges[64]; // TODO - dynamic size array should be used.
rgbabuffer_edge_type globaledges[64]; // TODO - dynamic size array should be used.
rgbabuffer_active_edge_index activeedges[64] = {{UINT32_MAX, 0.0}};
uint32_t q = 0, parity = 1;
for (uint32_t c = 0; c < point_count; c++) {
uint32_t n = c == point_count-1 ? 0 :c + 1;
if (points[n].y > points[c].y ) {
edges[c].ymin = points[c].y; //ymin
edges[c].ymax = points[n].y; //ymax
edges[c].xval = points[c].x; //xval
} else {
edges[c].ymin = points[n].y; //ymin
edges[c].ymax = points[c].y; //ymax
edges[c].xval = points[n].x; //xval
}
edges[c].slope = (points[n].x - points[c].x) / (points[n].y - points[c].y); // 1/m
if ( c == 0 ) {
y_limits.x = edges[0].ymin;
y_limits.y = edges[0].ymax;
x_limits.x = edges[0].xval;
x_limits.y = edges[0].xval;
}
if ( isfinite(edges[c].slope) ) {
if ( y_limits.x > edges[c].ymin ) { y_limits.x = edges[c].ymin; }
if ( y_limits.y < edges[c].ymax ) { y_limits.y = edges[c].ymax; }
if ( x_limits.x > points[c].x ) { x_limits.x = points[c].x; }
if ( x_limits.y < points[c].x ) { x_limits.y = points[c].x; }
if ( x_limits.y < points[n].x ) { x_limits.y = points[n].x; }
rgbabuffer_edge_type_insert(globaledges, edges[c], q++, 64);
}
}
// //List Global Edges
// for ( uint32_t p = 0; p < point_count; p++ ) {
// LOG_MESSAGE("%d: ymin: %f ymax: %f xval: %f slope: %f", p, globaledges[p].ymin, globaledges[p].ymax, globaledges[p].xval, globaledges[p].slope);
// }
// printf(" %.0f%*c%.0f\n", x_limits.x, (int)(x_limits.y-x_limits.x)-1, ' ', x_limits.y );
for (float line = y_limits.x; line < y_limits.y; line += 1.0f) {
uint32_t line32 = (uint32_t)line;
uint32_t col32;
uint32_t i = 0;
uint32_t max_active = 64;
q = 0;
// Save Global Edges for
for (uint32_t c = 0; c < point_count; c++) {
if ( (uint32_t)globaledges[c].ymin == line32 && globaledges[c].ymin < globaledges[c].ymax) {
insertSorted(activeedges, { c, globaledges[c].xval }, q++, 64);
}
}
activeedges[q] = { UINT32_MAX, 0.0};
max_active = q;
q = activeedges[0].index;
for (float col = x_limits.x; col <= x_limits.y; col += 1.0f) {
col32 = (uint32_t)col;
if ( q < 64 ) {
uint32_t next = (uint32_t)globaledges[q].xval;
if ( next == col32 ) {
parity = !parity;
q = activeedges[++i].index;
}
}
if (!parity)
rbgabuffer__pixel(ctx, ctx->fill_colour, col32, line32 );
//printf("%c", parity ? ' ' : '+' );
//Note: Just incase of a single pixel being drawn.
if ( q < 64 ) {
uint32_t next = (uint32_t)globaledges[q].xval;
if ( next == col32 ) {
parity = !parity;
q = activeedges[++i].index;
}
}
}
// printf("\n");
// Update x
for (uint32_t c = 0; c < max_active; c++) {
uint32_t p = activeedges[c].index;
if ( p != UINT32_MAX ) {
globaledges[p].ymin += 1.0f;
globaledges[p].xval += globaledges[p].slope;
}
}
}
ctx->commands.index = 0;
}
void rbgabuffer_Stroke(rbgabuffer_context* ctx) {
float x, y;
float * p = nullptr;
elix_v2 points[64];
uint32_t point_count = 0;
size_t ind = 0;
while (ind < ctx->commands.index) {
uint32_t cmd = (uint32_t)ctx->commands.array[ind];
switch (cmd) {
case rbgabuffer_MOVETO:
p = &ctx->commands.array[ind+1];
points[point_count].x = x = p[0];
points[point_count].y = y = p[1];
//LOG_MESSAGE("moveto %fx%f", points[point_count].x, points[point_count].y);
point_count++;
ind += 3;
break;
case rbgabuffer_LINETO:
p = &ctx->commands.array[ind+1];
points[point_count].x =p[0];
points[point_count].y =p[1];
//LOG_MESSAGE("lineto %fx%f", points[point_count].x, points[point_count].y);
point_count++;
ind += 3;
break;
case rbgabuffer_CLOSE:
points[point_count].x = x;
points[point_count].y = y;
//LOG_MESSAGE("CLOSE %fx%f", points[point_count].x, points[point_count].y);
point_count++;
ind++;
break;
default:
ind++;
}
}
uint32_t c = 1;
for ( ; c < point_count; c++) {
rbgabuffer__line(points[c-1], points[c], ctx, ctx->stroke_colour);
}
ctx->commands.index = 0;
}
void rbgabuffer_FillColor(rbgabuffer_context* ctx, uint32_t color) {
ctx->fill_colour = color;
}
void rbgabuffer_StrokeColor(rbgabuffer_context* ctx, uint32_t color) {
ctx->stroke_colour = color;
}
void rbgabuffer_MoveTo(rbgabuffer_context* ctx, float x, float y) {
float vals[] = {
rbgabuffer_MOVETO, x,y,
};
rbgabuffer__appendCommands(ctx, vals, ARRAYCOUNT(vals));
}
void rbgabuffer_LineTo(rbgabuffer_context* ctx, float x, float y) {
float vals[] = {
rbgabuffer_LINETO, x,y,
};
rbgabuffer__appendCommands(ctx, vals, ARRAYCOUNT(vals));
}
#include "elix_os.hpp"
rgbabuffer_font * rbgabuffer__unloadFont(rbgabuffer_context* ctx, rgbabuffer_font *& font) {
elix_databuffer_free(&font->data);
NULLIFY(font);
return font;
}
rgbabuffer_font * rbgabuffer__loadFont(rbgabuffer_context* ctx, const char * font_name) {
rgbabuffer_font * font = nullptr;
elix_databuffer raw_file;
raw_file = elix_os_font(font_name);
if ( raw_file.size ) {
font = new rgbabuffer_font();
font->data = raw_file;
int index = stbtt_GetFontOffsetForIndex(raw_file.data, 0);
if ( index != -1 ) {
stbtt_InitFont(&font->info, raw_file.data, index);
stbtt_GetFontVMetrics(&font->info, &font->base_ascent, &font->base_descent, &font->base_line_gap);
}
}
//elix_databuffer_free(&raw_file);
return font;
}
void rgbabuffer__fillChar(rbgabuffer_context* ctx, rgbabuffer_font * font, uint32_t character, float &x, float &y,uint32_t next_character) {
if ( !font || !font->info.numGlyphs) {
return;
}
int index = stbtt_FindGlyphIndex(&font->info, character);
if (character > 127 && !index) {
printf("non-ascii %d %d\n", character, index);
}
if ( index ) {
float scale = stbtt_ScaleForPixelHeight(&font->info, ctx->font_size_px);
float baseline = (font->base_ascent * scale);
int advance_width, left_sidebearing,width, height, xoff, yoff;
uint8_t * bitmap = stbtt_GetGlyphBitmap(&font->info, 0, scale, index, &width, &height, &xoff, &yoff);
stbtt_GetGlyphHMetrics(&font->info, character, &advance_width, &left_sidebearing);
for ( int32_t j = 0; j < height; ++j) {
for ( int32_t i = 0; i < width; ++i) {
float alpha = (float)bitmap[(j*width)+i] / 255.0;
rbgabuffer__pixel(ctx, 0xFF000000, x+i, y+j+yoff+baseline, alpha);
}
}
x += (float)advance_width * scale;
if ( next_character ) {
x += scale * stbtt_GetCodepointKernAdvance(&font->info, character, next_character);
}
delete bitmap;
} else if ( ctx->emoji ) {
rgbabuffer__fillChar( ctx, ctx->emoji, character, x, y, next_character);
}
}
#include "elix_cstring.hpp"
void rbgabuffer_FillText(rbgabuffer_context* ctx, const char * text, float x, float y, float maxWidth) {
rgbabuffer_font * font = rbgabuffer__loadFont(ctx, "Sans-Serif");
if ( !font ) {
return;
}
char * object = (char*)text;
uint32_t current_character = 0, next_character = 0;
while ( (current_character = elix_cstring_next_character(object)) > 0 ) {
next_character = elix_cstring_peek_character(object);
rgbabuffer__fillChar(ctx, font, current_character,x, y, next_character);
}
delete font;
}
elix_text_metrics rbgabuffer_measureText(rbgabuffer_context* ctx, const char * text) {
elix_text_metrics metrics = {0.0f};
rgbabuffer_font * font = rbgabuffer__loadFont(ctx, ctx->font_family);
float font_scale = stbtt_ScaleForPixelHeight(&font->info, ctx->font_size_px);
int ascent, descent;
stbtt_GetFontVMetrics(&font->info, &ascent, &descent, nullptr);
int baseline = (int) (ascent * font_scale);
int descent_scaled = (int) (descent * font_scale);
char * object = (char*)text;
uint32_t current_character = 0, next_character = 0;
while ( (current_character = elix_cstring_next_character(object)) > 0 ) {
next_character = elix_cstring_peek_character(object);
int x0, y0, x1, y1;
int advance, lsb;
stbtt_GetCodepointBitmapBox(&font->info, current_character, font_scale, font_scale, &x0, &y0, &x1, &y1);
stbtt_GetCodepointHMetrics(&font->info, current_character, &advance, &lsb);
metrics.width += advance * font_scale;
if (next_character) {
metrics.width += font_scale * stbtt_GetCodepointKernAdvance(&font->info, current_character, next_character);
}
}
return metrics;
}
rbgabuffer_context * rbgabuffer_create_context(elix_graphic_data * external_buffer, const elix_uv32_2 requested_dimensions ) {
rbgabuffer_context * context = new rbgabuffer_context();
context->internal_buffer = (external_buffer == nullptr);
if (context->internal_buffer) {
ASSERT(requested_dimensions.width != 0);
ASSERT(requested_dimensions.height != 0);
context->memory = elix_graphic_data_create(requested_dimensions);
rbgabuffer__testpattern(context->memory);
} else {
ASSERT(external_buffer->bpp == 4);
context->memory = external_buffer;
rbgabuffer__gridpattern(context->memory);
}
context->dimensions = requested_dimensions;
context->commands.max = 32;
context->commands.array = (float*)malloc( sizeof(float)*context->commands.max);
context->emoji = rbgabuffer__loadFont(context, nullptr);
return context;
}
rbgabuffer_context * rgbabuffer_delete_context(rbgabuffer_context *& ctx) {
ASSERT(ctx);
free(ctx->commands.array);
if (ctx->internal_buffer) {
ctx->memory = elix_graphic_data_destroy(ctx->memory);
}
NULLIFY(ctx);
return ctx;
}
| 29.474599 | 148 | 0.609017 | lukesalisbury |
fab8ad10c790cb417271392fc9c50a6562f0e1d8 | 284 | cpp | C++ | examples/reference-ASSERT_GE_LABELED.cpp | gcross/Illuminate | 862f665ccd4b67411bc332f534e1655585750823 | [
"0BSD"
] | null | null | null | examples/reference-ASSERT_GE_LABELED.cpp | gcross/Illuminate | 862f665ccd4b67411bc332f534e1655585750823 | [
"0BSD"
] | null | null | null | examples/reference-ASSERT_GE_LABELED.cpp | gcross/Illuminate | 862f665ccd4b67411bc332f534e1655585750823 | [
"0BSD"
] | null | null | null | #include "illuminate.hpp"
TEST_CASE(ASSERT_GE_LABELED) {
ASSERT_GE_LABELED("first value",1,"second value",0)
ASSERT_GE_LABELED("first value",1,"second value",1)
ASSERT_GE_LABELED("first value",1,"second value",2)
ASSERT_GE_LABELED("first value",1,"second value",3)
}
| 31.555556 | 55 | 0.725352 | gcross |
fabe5037696a8ea875afae5c1715393c78b97a56 | 3,449 | cpp | C++ | Source/VoxelEditor/Private/Details/VoxelPaintMaterialCustomization.cpp | brucelevis/VoxelPlugin | eb64fbbdd699ce096d5b3cedbbb76e7b477cfde4 | [
"MIT"
] | 1 | 2019-11-16T22:14:23.000Z | 2019-11-16T22:14:23.000Z | Source/VoxelEditor/Private/Details/VoxelPaintMaterialCustomization.cpp | getnamo/VoxelPlugin | eb64fbbdd699ce096d5b3cedbbb76e7b477cfde4 | [
"MIT"
] | 10 | 2019-11-16T10:35:05.000Z | 2020-01-06T09:03:52.000Z | Source/VoxelEditor/Private/Details/VoxelPaintMaterialCustomization.cpp | getnamo/VoxelPlugin | eb64fbbdd699ce096d5b3cedbbb76e7b477cfde4 | [
"MIT"
] | 1 | 2020-05-19T03:53:24.000Z | 2020-05-19T03:53:24.000Z | // Copyright 2019 Phyronnaz
#include "Details/VoxelPaintMaterialCustomization.h"
#include "VoxelTools/VoxelPaintMaterial.h"
#include "PropertyHandle.h"
#include "DetailWidgetRow.h"
#include "IDetailChildrenBuilder.h"
#include "IPropertyUtilities.h"
#include "IDetailGroup.h"
#include "Widgets/SBoxPanel.h"
#define LOCTEXT_NAMESPACE "Voxel"
void FVoxelPaintMaterialCustomization::CustomizeHeader(TSharedRef<IPropertyHandle> PropertyHandle, FDetailWidgetRow& HeaderRow, IPropertyTypeCustomizationUtils& CustomizationUtils)
{
}
#define GET_CHILD_PROPERTY(PropertyHandle, Class, Property) PropertyHandle->GetChildHandle(GET_MEMBER_NAME_CHECKED(Class, Property)).ToSharedRef()
void FVoxelPaintMaterialCustomization::CustomizeChildren(TSharedRef<IPropertyHandle> PropertyHandle, IDetailChildrenBuilder& ChildBuilder, IPropertyTypeCustomizationUtils& CustomizationUtils)
{
auto TypeHandle = GET_CHILD_PROPERTY(PropertyHandle, FVoxelPaintMaterial, Type);
FSimpleDelegate RefreshDelegate = FSimpleDelegate::CreateLambda([&CustomizationUtils]()
{
auto Utilities = CustomizationUtils.GetPropertyUtilities();
if (Utilities.IsValid())
{
Utilities->ForceRefresh();
}
});
TypeHandle->SetOnPropertyValueChanged(RefreshDelegate);
IDetailGroup& Group = ChildBuilder.AddGroup( TEXT("Paint Material Type"), PropertyHandle->GetPropertyDisplayName() );
Group.HeaderRow()
.NameContent()
[
PropertyHandle->CreatePropertyNameWidget()
]
.ValueContent()
[
TypeHandle->CreatePropertyValueWidget()
];
FString Type;
TypeHandle->GetValueAsFormattedString(Type);
if (Type == "RGB")
{
auto ColorHandle = GET_CHILD_PROPERTY(PropertyHandle, FVoxelPaintMaterial, Color);
Group.AddPropertyRow(GET_CHILD_PROPERTY(ColorHandle, FVoxelPaintMaterialColor, Color));
Group.AddPropertyRow(GET_CHILD_PROPERTY(PropertyHandle, FVoxelPaintMaterial, Amount));
Group.AddPropertyRow(GET_CHILD_PROPERTY(ColorHandle, FVoxelPaintMaterialColor, bPaintR));
Group.AddPropertyRow(GET_CHILD_PROPERTY(ColorHandle, FVoxelPaintMaterialColor, bPaintG));
Group.AddPropertyRow(GET_CHILD_PROPERTY(ColorHandle, FVoxelPaintMaterialColor, bPaintB));
Group.AddPropertyRow(GET_CHILD_PROPERTY(ColorHandle, FVoxelPaintMaterialColor, bPaintA));
}
else if (Type == "SingleIndex")
{
Group.AddPropertyRow(GET_CHILD_PROPERTY(PropertyHandle, FVoxelPaintMaterial, Index));
}
else if (Type == "DoubleIndexSet")
{
auto DoubleIndexHandle = GET_CHILD_PROPERTY(PropertyHandle, FVoxelPaintMaterial, DoubleIndexSet);
Group.AddPropertyRow(GET_CHILD_PROPERTY(DoubleIndexHandle, FVoxelPaintMaterialDoubleIndexSet, IndexA));
Group.AddPropertyRow(GET_CHILD_PROPERTY(DoubleIndexHandle, FVoxelPaintMaterialDoubleIndexSet, IndexB));
Group.AddPropertyRow(GET_CHILD_PROPERTY(DoubleIndexHandle, FVoxelPaintMaterialDoubleIndexSet, Blend));
Group.AddPropertyRow(GET_CHILD_PROPERTY(DoubleIndexHandle, FVoxelPaintMaterialDoubleIndexSet, bSetIndexA));
Group.AddPropertyRow(GET_CHILD_PROPERTY(DoubleIndexHandle, FVoxelPaintMaterialDoubleIndexSet, bSetIndexB));
Group.AddPropertyRow(GET_CHILD_PROPERTY(DoubleIndexHandle, FVoxelPaintMaterialDoubleIndexSet, bSetBlend));
}
else if (Type == "DoubleIndexBlend")
{
Group.AddPropertyRow(GET_CHILD_PROPERTY(PropertyHandle, FVoxelPaintMaterial, Index));
Group.AddPropertyRow(GET_CHILD_PROPERTY(PropertyHandle, FVoxelPaintMaterial, Amount));
}
else
{
ensure(false);
}
}
#undef GET_CHILD_PROPERTY
#undef LOCTEXT_NAMESPACE | 40.576471 | 191 | 0.823427 | brucelevis |
fabf827ad477d4e4518c76ba7eace6f49fa23a92 | 262 | hpp | C++ | MPAGSCipher/CaesarCipher.hpp | MPAGS-CPP-2019/mpags-day-3-GarethBird96 | 74a11e90fb8d7b2bf70e9126c47fa17cb48c9990 | [
"MIT"
] | null | null | null | MPAGSCipher/CaesarCipher.hpp | MPAGS-CPP-2019/mpags-day-3-GarethBird96 | 74a11e90fb8d7b2bf70e9126c47fa17cb48c9990 | [
"MIT"
] | null | null | null | MPAGSCipher/CaesarCipher.hpp | MPAGS-CPP-2019/mpags-day-3-GarethBird96 | 74a11e90fb8d7b2bf70e9126c47fa17cb48c9990 | [
"MIT"
] | null | null | null | #ifndef MPAGSCIPHER_CEASERCIPHER_HPP
#define MPAGSCIPHER_CEASERCIPHER_HPP
class CaesarCipher{
public:
//Basic Constructor
CaesarCipher(size_t key);
//Members:
size_t caesarKey {0};
};
#endif // MPAGSCIPHER_CEASERCIPHER_HPP
| 18.714286 | 38 | 0.70229 | MPAGS-CPP-2019 |
fac1ec3c74bf7de53d6a4f492ed7db2e3419ec81 | 1,228 | hpp | C++ | source/zisc/core/zisc/thread/spin_lock_mutex.hpp | byzin/Zisc | c74f50c51f82c847f39a603607d73179004436bb | [
"MIT"
] | 2 | 2017-10-18T13:24:11.000Z | 2018-05-15T00:40:52.000Z | source/zisc/core/zisc/thread/spin_lock_mutex.hpp | byzin/Zisc | c74f50c51f82c847f39a603607d73179004436bb | [
"MIT"
] | 9 | 2016-09-05T11:07:03.000Z | 2019-07-05T15:31:04.000Z | source/zisc/core/zisc/thread/spin_lock_mutex.hpp | byzin/Zisc | c74f50c51f82c847f39a603607d73179004436bb | [
"MIT"
] | null | null | null | /*!
\file spin_lock_mutex.hpp
\author Sho Ikeda
\brief No brief description
\details
No detailed description.
\copyright
Copyright (c) 2015-2021 Sho Ikeda
This software is released under the MIT License.
http://opensource.org/licenses/mit-license.php
*/
#ifndef ZISC_SPIN_LOCK_MUTEX_HPP
#define ZISC_SPIN_LOCK_MUTEX_HPP
// Standard C++ library
#include <atomic>
// Zisc
#include "zisc/non_copyable.hpp"
namespace zisc {
/*!
\brief SpinLockMutex class provides spin lock functions
For more detail, please see the following link:
<a href="http://en.cppreference.com/w/cpp/atomic/atomic_flag">std::atomic_flag</a>.
*/
class SpinLockMutex : private NonCopyable<SpinLockMutex>
{
public:
//! Construct the mutex. The mutex is in unlocked state.
SpinLockMutex() noexcept;
//!
~SpinLockMutex() noexcept;
//! Lock the mutex
void lock() noexcept;
//! Try to lock the mutex for STL compatible
bool try_lock() noexcept;
//! Try to lock the mutex
bool tryLock() noexcept;
//! Unlock the mutex
void unlock() noexcept;
private:
std::atomic_flag lock_state_ = ATOMIC_FLAG_INIT;
};
} // namespace zisc
#include "spin_lock_mutex-inl.hpp"
#endif // ZISC_SPIN_LOCK_MUTEX_HPP
| 19.806452 | 85 | 0.721498 | byzin |
fac58c3933ed9901e6cce3c38c8f7742da7fcdcb | 3,675 | cpp | C++ | plugins/robots/common/twoDModel/src/engine/view/parts/robotItemPopup.cpp | ladaegorova18/trik-studio | f8d9ce50301fd93c948ac774e85c0e6bfff820bc | [
"Apache-2.0"
] | null | null | null | plugins/robots/common/twoDModel/src/engine/view/parts/robotItemPopup.cpp | ladaegorova18/trik-studio | f8d9ce50301fd93c948ac774e85c0e6bfff820bc | [
"Apache-2.0"
] | null | null | null | plugins/robots/common/twoDModel/src/engine/view/parts/robotItemPopup.cpp | ladaegorova18/trik-studio | f8d9ce50301fd93c948ac774e85c0e6bfff820bc | [
"Apache-2.0"
] | null | null | null | /* Copyright 2015 QReal Research Group, Dmitry Mordvinov
*
* 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 "robotItemPopup.h"
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSpinBox>
#include <qrkernel/settingsManager.h>
#include "src/engine/view/scene/robotItem.h"
using namespace twoDModel::view;
RobotItemPopup::RobotItemPopup(graphicsUtils::AbstractScene &scene, QWidget *parent)
: ItemPopup(scene, parent)
{
initWidget();
}
RobotItemPopup::~RobotItemPopup()
{
}
bool RobotItemPopup::suits(QGraphicsItem *item)
{
return dynamic_cast<RobotItem *>(item) != nullptr;
}
bool RobotItemPopup::attachTo(QGraphicsItem *item)
{
mCurrentItem = dynamic_cast<RobotItem *>(item);
mSpinBox->setValue(mCurrentItem->pen().width());
const bool followingEnabled = qReal::SettingsManager::value("2dFollowingRobot").toBool();
mFollowButton->setChecked(followingEnabled);
return true;
}
bool RobotItemPopup::attachTo(const QList<QGraphicsItem *> &items)
{
Q_UNUSED(items)
return false;
}
void RobotItemPopup::initWidget()
{
QGridLayout * const layout = new QGridLayout(this);
layout->addWidget(initFollowButton(), 0, 0, Qt::AlignCenter);
layout->addWidget(initReturnButton(), 0, 1);
layout->addWidget(initSpinBox(), 1, 0);
layout->addWidget(initSetStartButton(), 1, 1);
updateDueToLayout();
}
QWidget *RobotItemPopup::initFollowButton()
{
mFollowButton = initButton(":/icons/2d_target.png", QString());
mFollowButton->setCheckable(true);
connect(mFollowButton, &QAbstractButton::toggled, this, &RobotItemPopup::followingChanged);
connect(mFollowButton, &QAbstractButton::toggled, this, [=](bool enabled) {
mFollowButton->setToolTip(tr("Camera folowing robot: %1")
.arg(enabled ? tr("enabled") : tr("disabled")));
});
return mFollowButton;
}
QWidget *RobotItemPopup::initReturnButton()
{
mReturnButton = initButton(":/icons/2d_robot_back.png", tr("Return robot to the initial position"));
connect(mReturnButton, &QAbstractButton::clicked, this, &RobotItemPopup::restoreRobotPositionClicked);
return mReturnButton;
}
QWidget *RobotItemPopup::initSetStartButton()
{
mSetStartButton = initButton(":/icons/2d_target.png", tr("Move start position here"));
connect(mSetStartButton, &QAbstractButton::clicked, this, &RobotItemPopup::setRobotPositionClicked);
return mSetStartButton;
}
QAbstractButton *RobotItemPopup::initButton(const QString &icon, const QString &toolTip)
{
QPushButton * const result = new QPushButton(QIcon(icon), QString(), this);
result->setToolTip(toolTip);
result->setFlat(true);
result->setFixedSize(24, 24);
return result;
}
QWidget *RobotItemPopup::initSpinBox()
{
QSpinBox * const spinBox = new QSpinBox(this);
spinBox->setRange(1, 30);
spinBox->setToolTip(tr("Marker thickness"));
QPalette spinBoxPalette;
spinBoxPalette.setColor(QPalette::Window, Qt::transparent);
spinBoxPalette.setColor(QPalette::Base, Qt::transparent);
spinBox->setPalette(spinBoxPalette);
connect(spinBox, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, [=](int value) {
mCurrentItem->setPenWidth(value);
});
mSpinBox = spinBox;
return spinBox;
}
| 30.625 | 103 | 0.75483 | ladaegorova18 |
fad2ab3418642d64f9ea34f4591df334f15d1567 | 1,901 | cpp | C++ | engxor.cpp | darksidergod/CompetitiveProgramming | ea0ee53bddd87e41b4586dd30c1d4a6b8ae3a93a | [
"MIT"
] | null | null | null | engxor.cpp | darksidergod/CompetitiveProgramming | ea0ee53bddd87e41b4586dd30c1d4a6b8ae3a93a | [
"MIT"
] | null | null | null | engxor.cpp | darksidergod/CompetitiveProgramming | ea0ee53bddd87e41b4586dd30c1d4a6b8ae3a93a | [
"MIT"
] | 1 | 2020-10-03T19:48:05.000Z | 2020-10-03T19:48:05.000Z | #include <bits/stdc++.h>
using namespace std;
#define mod 1000000007
#define int long long int
#define pb push_back
#define mk make_pair
#define flp(i, k, n) for(int i=k; i<n; i++)
#define F first
#define S second
int power(int a, int b) {
int x = 1, y = a;
while(b > 0) {
if(b%2 == 1) {
x=(x*y);
if(x>mod) x%=mod;
}
y = (y*y);
if(y>mod) y%=mod;
b /= 2;
}
return x;
}
int totient(int n) {
int result = n;
for(int i=2;i*i <= n;i++)
{
if (n % i == 0) result -= result / i;
while (n % i == 0) n /= i;
}
if (n > 1) result -= result / n;
return result;
}
int readInt () {
bool minus = false;
int result = 0;
char ch;
ch = getchar();
while (true) {
if (ch == '-') break;
if (ch >= '0' && ch <= '9') break;
ch = getchar();
}
if (ch == '-') minus = true; else result = ch-'0';
while (true) {
ch = getchar();
if (ch < '0' || ch > '9') break;
result = result*10 + (ch - '0');
}
if (minus)
return -result;
else
return result;
}
int32_t main(void)
{
int t;
scanf("%lli", &t);
while(t--){
int n, q;
scanf("%lli", &n);
scanf("%lli", &q);
int a[n];
flp(i, 0, n) scanf("%lli", &a[i]);
int count1=0, count2=0;
flp(i, 0, n)
{
if((__builtin_popcountll(a[i]))%2==0) count1++;
else count2++;
}
flp(i, 0, q)
{
int p;
scanf("%lli", &p);
if((__builtin_popcountll(p))%2==0)
{
printf("%lli ",count1);
printf("%lli \n", count2);
}
else
{
printf("%lli ", count2);
printf("%lli \n",count1);
}
}
}
return 0;
} | 20.010526 | 63 | 0.40768 | darksidergod |
fad6ffd4672784aac928199895b318f85648e8ec | 387 | cpp | C++ | hackerrank/1/a.cpp | AadityaJ/Spoj | 61664c1925ef5bb072a3fe78fb3dac4fb68d77a1 | [
"MIT"
] | null | null | null | hackerrank/1/a.cpp | AadityaJ/Spoj | 61664c1925ef5bb072a3fe78fb3dac4fb68d77a1 | [
"MIT"
] | null | null | null | hackerrank/1/a.cpp | AadityaJ/Spoj | 61664c1925ef5bb072a3fe78fb3dac4fb68d77a1 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, char const *argv[]) {
int n;
cin >> n;
vector<int> file(n);
for(int file_i = 0; file_i < n; file_i++){
cin >> file[file_i];
}
int cnt=0,i=0;
while(i<n){
int v=file[i];
i+=(v+1);
cnt++;
}
//if(i==n) cnt--;
cout<<cnt;
return 0;
}
| 16.826087 | 46 | 0.552972 | AadityaJ |
fad8bce899ace732d791a7734cc48dbbdd6dd313 | 7,644 | cc | C++ | modules/network/PiiNetworkOperation.cc | topiolli/into | f0a47736f5c93dd32e89e7aad34152ae1afc5583 | [
"BSD-3-Clause"
] | 14 | 2015-01-19T22:14:18.000Z | 2020-04-13T23:27:20.000Z | modules/network/PiiNetworkOperation.cc | topiolli/into | f0a47736f5c93dd32e89e7aad34152ae1afc5583 | [
"BSD-3-Clause"
] | null | null | null | modules/network/PiiNetworkOperation.cc | topiolli/into | f0a47736f5c93dd32e89e7aad34152ae1afc5583 | [
"BSD-3-Clause"
] | 14 | 2015-01-16T05:43:15.000Z | 2019-01-29T07:57:11.000Z | /* This file is part of Into.
* Copyright (C) Intopii 2013.
* All rights reserved.
*
* Licensees holding a commercial Into license may use this file in
* accordance with the commercial license agreement. Please see
* LICENSE.commercial for commercial licensing terms.
*
* Alternatively, this file may be used under the terms of the GNU
* Affero General Public License version 3 as published by the Free
* Software Foundation. In addition, Intopii gives you special rights
* to use Into as a part of open source software projects. Please
* refer to LICENSE.AGPL3 for details.
*/
#include "PiiNetworkOperation.h"
#include <PiiMimeHeader.h>
#include <PiiMultipartDecoder.h>
#include <PiiGenericTextInputArchive.h>
#include <QTextCodec>
#if QT_VERSION >= 0x050000
# include <QUrlQuery>
#else
# include <QUrl>
#endif
// PENDING body and content type outputs
const char* PiiNetworkOperation::pContentNameHeader = "Content-Name";
PiiNetworkOperation::Data::Data() :
bIgnoreErrors(false),
strContentType("text/plain"),
iResponseTimeout(5000)
{
}
PiiNetworkOperation::PiiNetworkOperation(Data *d) :
PiiDefaultOperation(d)
{
setThreadCount(1);
addSocket(d->pBodyInput = new PiiInputSocket("body"));
addSocket(d->pTypeInput = new PiiInputSocket("content type"));
d->pBodyInput->setOptional(true);
d->pTypeInput->setOptional(true);
d->iStaticInputCount = d->lstInputs.size();
d->iStaticOutputCount = d->lstOutputs.size();
}
PiiNetworkOperation::~PiiNetworkOperation()
{
}
void PiiNetworkOperation::setInputNames(const QStringList& inputNames)
{
PII_D;
d->lstInputNames = inputNames;
setNumberedInputs(inputNames.size(), d->iStaticInputCount);
d->pBodyInput->setOptional(d->lstInputNames.size() > 0);
}
void PiiNetworkOperation::setOutputNames(const QStringList& outputNames)
{
PII_D;
d->lstOutputNames = outputNames;
setNumberedOutputs(outputNames.size());
}
PiiInputSocket* PiiNetworkOperation::input(const QString& name) const
{
const PII_D;
PiiInputSocket* result = PiiBasicOperation::input(name);
if (result == 0)
{
int index = d->lstInputNames.indexOf(name);
if (index != -1)
return inputAt(index + d->iStaticInputCount);
}
return result;
}
PiiOutputSocket* PiiNetworkOperation::output(const QString& name) const
{
const PII_D;
PiiOutputSocket* result = PiiBasicOperation::output(name);
if (result == 0)
{
int index = d->lstOutputNames.indexOf(name);
if (index != -1)
return outputAt(index + d->iStaticOutputCount);
}
return result;
}
bool PiiNetworkOperation::decodeObjects(PiiHttpDevice& h, const PiiMimeHeader& header)
{
PII_D;
QString strContentType = header.contentType();
//qDebug("Decoding %s", qPrintable(strContentType));
// The server responded with/client sent one serialized object
if (strContentType == PiiNetwork::pTextArchiveContentType)
{
addToOutputMap(header.value(pContentNameHeader), h);
return true;
}
else if (strContentType.startsWith("multipart/"))
{
// Decode a multipart message
PiiMultipartDecoder decoder(&h, header);
while (decoder.nextMessage())
{
// PENDING Content-Disposition: form-data; name="name"
if (decoder.header().contentType() == PiiNetwork::pTextArchiveContentType)
addToOutputMap(decoder.header().value(pContentNameHeader), decoder);
else
decoder.readAll();
}
return true;
}
else if (strContentType == "application/x-www-form-urlencoded")
{
#if QT_VERSION >= 0x050000
QUrlQuery query(QString(h.readBody()));
QList<QPair<QString,QString> > lstItems = query.queryItems();
#else
QByteArray aBody = h.readBody();
aBody.prepend('?');
QUrl url(aBody);
QList<QPair<QString,QString> > lstItems = url.queryItems();
#endif
for (int i=0; i<lstItems.size(); ++i)
addToOutputMap(lstItems[i].first, QVariant(lstItems[i].second));
return true;
}
else if (strContentType == "text/plain")
{
QString strName = header.value(pContentNameHeader);
QString strEncoding = header.value("Content-Encoding");
QTextCodec* pCodec;
// If encoding is not specified or the codec is not found, use
// UTF-8 by default.
if (strEncoding.isEmpty() ||
(pCodec = QTextCodec::codecForName(strEncoding.toLatin1())) == 0)
pCodec = QTextCodec::codecForName("UTF-8");
d->mapOutputValues[strName.isEmpty() ? d->lstOutputNames[0] : strName] =
PiiVariant(pCodec->toUnicode(h.readBody()));
return true;
}
return false;
}
void PiiNetworkOperation::addToOutputMap(const QVariantMap& variables)
{
for (QVariantMap::const_iterator i = variables.begin();
i != variables.end(); ++i)
addToOutputMap(i.key(), i.value());
}
void PiiNetworkOperation::addToOutputMap(const QString& name, const QVariant& value)
{
PII_D;
bool ok;
// Try to convert to int first
int iValue = value.toInt(&ok);
if (ok)
{
d->mapOutputValues[name] = PiiVariant(iValue);
return;
}
// No luck -> try double
double dValue = value.toDouble(&ok);
if (ok)
{
d->mapOutputValues[name] = PiiVariant(dValue);
return;
}
// Damn. Well, it must be a string then.
d->mapOutputValues[name] = PiiVariant(value.toString());
}
void PiiNetworkOperation::addToOutputMap(const QString& name, QIODevice& device)
{
PII_D;
PiiGenericTextInputArchive inputArchive(&device);
PiiVariant obj;
inputArchive >> obj;
// If the name of the output is not given, we use the name of the
// first output.
d->mapOutputValues[name.isEmpty() ? d->lstOutputNames[0] : name] = obj;
}
void PiiNetworkOperation::emitOutputValues()
{
PII_D;
QList<PiiVariant> lstOutputValues;
// Check that all outputs have been received
for (int i=0; i<d->lstOutputNames.size(); ++i)
{
if (d->mapOutputValues.contains(d->lstOutputNames[i]))
lstOutputValues << d->mapOutputValues[d->lstOutputNames[i]];
else
{
d->mapOutputValues.clear();
if (!d->bIgnoreErrors)
PII_THROW(PiiExecutionException, tr("Objects were not received for all outputs."));
return;
}
}
for (int i=0; i<lstOutputValues.size(); ++i)
outputAt(i+d->iStaticOutputCount)->emitObject(lstOutputValues[i]);
d->mapOutputValues.clear();
}
void PiiNetworkOperation::check(bool reset)
{
PII_D;
PiiDefaultOperation::check(reset);
d->bBodyConnected = d->pBodyInput->isConnected();
d->bTypeConnected = d->pTypeInput->isConnected();
if (!d->bBodyConnected && d->bTypeConnected)
PII_THROW(PiiExecutionException, tr("The content type input cannot be connected alone."));
if (d->bBodyConnected && d->lstInputNames.size() > 0)
PII_THROW(PiiExecutionException, tr("Named inputs cannot be used with the body input."));
}
QStringList PiiNetworkOperation::inputNames() const { return _d()->lstInputNames; }
QStringList PiiNetworkOperation::outputNames() const { return _d()->lstOutputNames; }
void PiiNetworkOperation::setContentType(const QString& contentType) { _d()->strContentType = contentType; }
QString PiiNetworkOperation::contentType() const { return _d()->strContentType; }
void PiiNetworkOperation::setIgnoreErrors(bool ignoreErrors) { _d()->bIgnoreErrors = ignoreErrors; }
bool PiiNetworkOperation::ignoreErrors() const { return _d()->bIgnoreErrors; }
void PiiNetworkOperation::setResponseTimeout(int responseTimeout) { _d()->iResponseTimeout = responseTimeout; }
int PiiNetworkOperation::responseTimeout() const { return _d()->iResponseTimeout; }
| 31.586777 | 111 | 0.697017 | topiolli |
fadb76312432b5c2405e05a08a8b8c8efc0a4f82 | 7,630 | cpp | C++ | evo-X-Scriptdev2/scripts/kalimdor/caverns_of_time/hyjal/instance_hyjal.cpp | Gigelf-evo-X/evo-X | d0e68294d8cacfc7fb3aed5572f51d09a47136b9 | [
"OpenSSL"
] | 1 | 2019-01-19T06:35:40.000Z | 2019-01-19T06:35:40.000Z | src/bindings/Scriptdev2/scripts/kalimdor/caverns_of_time/hyjal/instance_hyjal.cpp | mfooo/wow | 3e5fad4cfdf0fd1c0a2fd7c9844e6f140a1bb32d | [
"OpenSSL"
] | null | null | null | src/bindings/Scriptdev2/scripts/kalimdor/caverns_of_time/hyjal/instance_hyjal.cpp | mfooo/wow | 3e5fad4cfdf0fd1c0a2fd7c9844e6f140a1bb32d | [
"OpenSSL"
] | null | null | null | /* Copyright (C) 2006 - 2010 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* ScriptData
SDName: Instance_Mount_Hyjal
SD%Complete: 100
SDComment: Instance Data Scripts and functions to acquire mobs and set encounter status for use in various Hyjal Scripts
SDCategory: Caverns of Time, Mount Hyjal
EndScriptData */
#include "precompiled.h"
#include "hyjal.h"
/* Battle of Mount Hyjal encounters:
0 - Rage Winterchill event
1 - Anetheron event
2 - Kaz'rogal event
3 - Azgalor event
4 - Archimonde event
*/
struct MANGOS_DLL_DECL instance_mount_hyjal : public ScriptedInstance
{
instance_mount_hyjal(Map* pMap) : ScriptedInstance(pMap) {Initialize();};
uint32 m_auiEncounter[MAX_ENCOUNTER];
std::string strSaveData;
std::list<uint64> lAncientGemGUIDList;
uint64 m_uiRageWinterchill;
uint64 m_uiAnetheron;
uint64 m_uiKazrogal;
uint64 m_uiAzgalor;
uint64 m_uiArchimonde;
uint64 m_uiJainaProudmoore;
uint64 m_uiThrall;
uint64 m_uiTyrandeWhisperwind;
uint32 m_uiTrashCount;
void Initialize()
{
memset(&m_auiEncounter, 0, sizeof(m_auiEncounter));
lAncientGemGUIDList.clear();
m_uiRageWinterchill = 0;
m_uiAnetheron = 0;
m_uiKazrogal = 0;
m_uiAzgalor = 0;
m_uiArchimonde = 0;
m_uiJainaProudmoore = 0;
m_uiThrall = 0;
m_uiTyrandeWhisperwind = 0;
m_uiTrashCount = 0;
}
bool IsEncounterInProgress() const
{
for(uint8 i = 0; i < MAX_ENCOUNTER; ++i)
if (m_auiEncounter[i] == IN_PROGRESS) return true;
return false;
}
void OnCreatureCreate(Creature* pCreature)
{
switch(pCreature->GetEntry())
{
case NPC_WINTERCHILL: m_uiRageWinterchill = pCreature->GetGUID(); break;
case NPC_ANETHERON: m_uiAnetheron = pCreature->GetGUID(); break;
case NPC_KAZROGAL: m_uiKazrogal = pCreature->GetGUID(); break;
case NPC_AZGALOR: m_uiAzgalor = pCreature->GetGUID(); break;
case NPC_ARCHIMONDE: m_uiArchimonde = pCreature->GetGUID(); break;
case NPC_JAINA: m_uiJainaProudmoore = pCreature->GetGUID(); break;
case NPC_THRALL: m_uiThrall = pCreature->GetGUID(); break;
case NPC_TYRANDE: m_uiTyrandeWhisperwind = pCreature->GetGUID(); break;
}
}
void OnObjectCreate(GameObject* pGo)
{
if (pGo->GetEntry() == GO_ANCIENT_GEM)
lAncientGemGUIDList.push_back(pGo->GetGUID());
}
uint64 GetData64(uint32 uiData)
{
switch(uiData)
{
case DATA_RAGEWINTERCHILL: return m_uiRageWinterchill;
case DATA_ANETHERON: return m_uiAnetheron;
case DATA_KAZROGAL: return m_uiKazrogal;
case DATA_AZGALOR: return m_uiAzgalor;
case DATA_ARCHIMONDE: return m_uiArchimonde;
case DATA_JAINAPROUDMOORE: return m_uiJainaProudmoore;
case DATA_THRALL: return m_uiThrall;
case DATA_TYRANDEWHISPERWIND: return m_uiTyrandeWhisperwind;
}
return 0;
}
void SetData(uint32 uiType, uint32 uiData)
{
switch(uiType)
{
case TYPE_WINTERCHILL:
if (m_auiEncounter[0] == DONE)
return;
m_auiEncounter[0] = uiData;
break;
case TYPE_ANETHERON:
if (m_auiEncounter[1] == DONE)
return;
m_auiEncounter[1] = uiData;
break;
case TYPE_KAZROGAL:
if (m_auiEncounter[2] == DONE)
return;
m_auiEncounter[2] = uiData;
break;
case TYPE_AZGALOR:
if (m_auiEncounter[3] == DONE)
return;
m_auiEncounter[3] = uiData;
break;
case TYPE_ARCHIMONDE:
m_auiEncounter[4] = uiData;
break;
case DATA_RESET_TRASH_COUNT:
m_uiTrashCount = 0;
break;
case DATA_TRASH:
if (uiData)
m_uiTrashCount = uiData;
else
--m_uiTrashCount;
DoUpdateWorldState(WORLD_STATE_ENEMYCOUNT, m_uiTrashCount);
break;
case TYPE_RETREAT:
if (uiData == SPECIAL)
{
if (!lAncientGemGUIDList.empty())
{
for(std::list<uint64>::iterator itr = lAncientGemGUIDList.begin(); itr != lAncientGemGUIDList.end(); ++itr)
{
//don't know how long it expected
DoRespawnGameObject(*itr,DAY);
}
}
}
break;
}
debug_log("SD2: Instance Hyjal: Instance data updated for event %u (Data=%u)", uiType, uiData);
if (uiData == DONE)
{
OUT_SAVE_INST_DATA;
std::ostringstream saveStream;
saveStream << m_auiEncounter[0] << " " << m_auiEncounter[1] << " " << m_auiEncounter[2] << " "
<< m_auiEncounter[3] << " " << m_auiEncounter[4];
strSaveData = saveStream.str();
SaveToDB();
OUT_SAVE_INST_DATA_COMPLETE;
}
}
uint32 GetData(uint32 uiType)
{
switch(uiType)
{
case TYPE_WINTERCHILL: return m_auiEncounter[0];
case TYPE_ANETHERON: return m_auiEncounter[1];
case TYPE_KAZROGAL: return m_auiEncounter[2];
case TYPE_AZGALOR: return m_auiEncounter[3];
case TYPE_ARCHIMONDE: return m_auiEncounter[4];
case DATA_TRASH: return m_uiTrashCount;
}
return 0;
}
const char* Save()
{
return strSaveData.c_str();
}
void Load(const char* in)
{
if (!in)
{
OUT_LOAD_INST_DATA_FAIL;
return;
}
OUT_LOAD_INST_DATA(in);
std::istringstream loadStream(in);
loadStream >> m_auiEncounter[0] >> m_auiEncounter[1] >> m_auiEncounter[2] >> m_auiEncounter[3] >> m_auiEncounter[4];
for(uint8 i = 0; i < MAX_ENCOUNTER; ++i)
if (m_auiEncounter[i] == IN_PROGRESS) // Do not load an encounter as IN_PROGRESS - reset it instead.
m_auiEncounter[i] = NOT_STARTED;
OUT_LOAD_INST_DATA_COMPLETE;
}
};
InstanceData* GetInstanceData_instance_mount_hyjal(Map* pMap)
{
return new instance_mount_hyjal(pMap);
}
void AddSC_instance_mount_hyjal()
{
Script *newscript;
newscript = new Script;
newscript->Name = "instance_hyjal";
newscript->GetInstanceData = &GetInstanceData_instance_mount_hyjal;
newscript->RegisterSelf();
}
| 31.142857 | 131 | 0.59017 | Gigelf-evo-X |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.