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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7346a15238faf3ee9fe014b2790e6792d040a18b | 5,662 | cpp | C++ | src/video/VideoManager.cpp | jaspervdj/JVGS | 59be35ed61b355b445b82bf32796c0f229e21b60 | [
"WTFPL"
] | 31 | 2015-02-02T04:51:10.000Z | 2021-02-20T10:04:41.000Z | src/video/VideoManager.cpp | jaspervdj/JVGS | 59be35ed61b355b445b82bf32796c0f229e21b60 | [
"WTFPL"
] | 2 | 2016-08-30T09:26:31.000Z | 2016-09-14T20:01:20.000Z | src/video/VideoManager.cpp | jaspervdj/JVGS | 59be35ed61b355b445b82bf32796c0f229e21b60 | [
"WTFPL"
] | 7 | 2015-02-02T05:02:09.000Z | 2021-12-24T06:53:01.000Z | #include "VideoManager.h"
#include "Renderer.h"
#include <SDL.h>
#include <SDL_opengl.h>
using namespace jvgs::math;
using namespace std;
namespace jvgs
{
namespace video
{
VideoManager::VideoManager()
{
SDL_InitSubSystem(SDL_INIT_VIDEO);
flags = SDL_DOUBLEBUF | SDL_HWSURFACE | SDL_HWACCEL | SDL_OPENGL;
}
VideoManager::~VideoManager()
{
SDL_QuitSubSystem(SDL_INIT_VIDEO);
}
VideoManager *VideoManager::getInstance()
{
static VideoManager instance;
return &instance;
}
void VideoManager::setVideoMode(std::string title)
{
SDL_Rect **modes = SDL_ListModes(NULL, flags | SDL_FULLSCREEN);
/* Auto-select video mode. */
size = Vector2D(800, 600);
if(modes!=NULL) {
size = Vector2D(modes[0]->w, modes[0]->h);
}
SDL_SetVideoMode((int) size.getX(), (int) size.getY(), 0,
flags | SDL_FULLSCREEN);
SDL_ShowCursor(0);
SDL_WM_SetCaption(title.c_str(), NULL);
setVideoDefaults();
}
void VideoManager::setVideoMode(const Vector2D &size,
std::string title)
{
SDL_WM_SetCaption(title.c_str(), NULL);
setVideoMode(size);
}
void VideoManager::setVideoMode(const Vector2D &size)
{
this->size = Vector2D((float)(int) size.getX(),
(float)(int) size.getY());
SDL_SetVideoMode((int) size.getX(), (int) size.getY(), 0, flags);
SDL_ShowCursor(0);
setVideoDefaults();
}
void VideoManager::setVideoDefaults()
{
glViewport(0, 0, (GLsizei) size.getX(), (GLsizei) size.getY());
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0f, (GLfloat) size.getX(), (GLfloat) size.getY(),
0.0f, -1.0f, 1.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_LINE_SMOOTH);
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
setClearColor(Color(1.0f, 1.0f, 1.0f));
setColor(Color(0.0f, 0.0f, 0.0f));
glLineWidth(1.5f);
}
const Vector2D &VideoManager::getSize() const
{
return size;
}
void VideoManager::clear() const
{
glClear(GL_COLOR_BUFFER_BIT);
}
void VideoManager::flip() const
{
SDL_GL_SwapBuffers();
}
void VideoManager::identity() const
{
glLoadIdentity();
}
void VideoManager::push() const
{
glPushMatrix();
}
void VideoManager::pop() const
{
glPopMatrix();
}
void VideoManager::translate(const Vector2D &vector) const
{
glTranslatef(vector.getX(), vector.getY(), 0.0f);
}
void VideoManager::scale(const Vector2D &scale) const
{
glScalef(scale.getX(), scale.getY(), 1.0f);
}
void VideoManager::rotate(const float °rees) const
{
glRotatef(degrees, 0.0f, 0.0f, 1.0f);
}
void VideoManager::transform(const AffineTransformationMatrix &matrix)
const
{
float *glMatrix = new float[16];
/* Our AffineTransformationMatrix
* / a b c \
* | d e f |
* \ 0 0 1 /
* becomes a matrix we can use with OpenGL:
* / a b 0 c \
* | d e 0 f |
* | 0 0 1 0 |
* \ 0 0 0 1 /
*/
/* Intialize to 0. */
for(int i = 0; i < 16; i++)
glMatrix[i] = 0.0f;
for(int row = 0; row < matrix.getHeight(); row++) {
for(int column = 0; column < matrix.getWidth(); column++) {
if(column < 2 && row < 2) {
glMatrix[column * 4 + row] =
matrix.getValue(row, column);
}
}
}
glMatrix[2 * 4 + 2] = 1.0f;
glMatrix[3 * 4 + 3] = 1.0f;
glMatrix[3 * 4 + 0] = matrix.getValue(0, 2);
glMatrix[3 * 4 + 1] = matrix.getValue(1, 2);
glMultMatrixf(glMatrix);
delete[] glMatrix;
}
void VideoManager::setColor(const Color &color)
{
this->color = color;
glColor4f(color.getRed(), color.getGreen(),
color.getBlue(), color.getAlpha());
}
const Color &VideoManager::getColor() const
{
return color;
}
void VideoManager::setClearColor(const Color &clearColor)
{
this->clearColor = clearColor;
glClearColor(clearColor.getRed(), clearColor.getGreen(),
clearColor.getBlue(), clearColor.getAlpha());
}
const Color &VideoManager::getClearColor() const
{
return clearColor;
}
void VideoManager::invert()
{
Color tmp = color;
setColor(clearColor);
setClearColor(tmp);
}
};
};
| 26.834123 | 78 | 0.481632 | jaspervdj |
73473a583759c7f36c5d220103ac14b0bc68fa93 | 2,409 | cc | C++ | ma/maShapeHandler.cc | cwsmith/core | 840fbf6ec49a63aeaa3945f11ddb224f6055ac9f | [
"BSD-3-Clause"
] | 138 | 2015-01-05T15:50:20.000Z | 2022-02-25T01:09:58.000Z | ma/maShapeHandler.cc | cwsmith/core | 840fbf6ec49a63aeaa3945f11ddb224f6055ac9f | [
"BSD-3-Clause"
] | 337 | 2015-08-07T18:24:58.000Z | 2022-03-31T14:39:03.000Z | ma/maShapeHandler.cc | cwsmith/core | 840fbf6ec49a63aeaa3945f11ddb224f6055ac9f | [
"BSD-3-Clause"
] | 70 | 2015-01-17T00:58:41.000Z | 2022-02-13T04:58:20.000Z | /******************************************************************************
Copyright 2013 Scientific Computation Research Center,
Rensselaer Polytechnic Institute. All rights reserved.
The LICENSE file included with this distribution describes the terms
of the SCOREC Non-Commercial License this program is distributed under.
*******************************************************************************/
#include "maShapeHandler.h"
#include "maShape.h"
#include "maAdapt.h"
#include <apfShape.h>
#include <pcu_util.h>
namespace ma {
class LinearHandler : public ShapeHandler
{
public:
LinearHandler(Adapt* a)
{
mesh = a->mesh;
sizeField = a->sizeField;
}
virtual double getQuality(Entity* e)
{
return measureElementQuality(mesh, sizeField, e);
}
virtual bool hasNodesOn(int dimension)
{
return dimension == 0;
}
virtual void onVertex(
apf::MeshElement* parent,
Vector const& xi,
Entity* vert)
{
Vector point;
apf::mapLocalToGlobal(parent,xi,point);
mesh->setPoint(vert,0,point);
}
private:
Mesh* mesh;
SizeField* sizeField;
};
class QuadraticHandler : public ShapeHandler
{
public:
QuadraticHandler(Adapt* a)
{
mesh = a->mesh;
st = createFieldTransfer(mesh->getCoordinateField());
}
~QuadraticHandler()
{
delete st;
}
virtual double getQuality(Entity* e)
{
PCU_ALWAYS_ASSERT( mesh->getType(e) == apf::Mesh::TET );
return measureQuadraticTetQuality(mesh,e);
}
virtual bool hasNodesOn(int dimension)
{
return st->hasNodesOn(dimension);
}
virtual void onVertex(
apf::MeshElement* parent,
Vector const& xi,
Entity* vert)
{
st->onVertex(parent,xi,vert);
}
virtual void onRefine(
Entity* parent,
EntityArray& newEntities)
{
st->onRefine(parent,newEntities);
}
virtual void onCavity(
EntityArray& oldElements,
EntityArray& newEntities)
{
st->onCavity(oldElements,newEntities);
}
private:
Mesh* mesh;
SolutionTransfer* st;
};
ShapeHandler* getShapeHandler(Adapt* a)
{
apf::FieldShape* s = a->mesh->getShape();
if (s->getOrder() == 1)
return new LinearHandler(a);
if (s->getOrder() == 2)
return new QuadraticHandler(a);
return 0;
}
}
| 22.942857 | 80 | 0.589041 | cwsmith |
7348b47467dcff0080dd4845e078e1e87f18d370 | 1,425 | cpp | C++ | libs/multiprecision/example/mixed_integer_arithmetic.cpp | ballisticwhisper/boost | f72119ab640b564c4b983bd457457046b52af9ee | [
"BSL-1.0"
] | 11 | 2016-04-12T16:29:29.000Z | 2021-06-28T11:01:57.000Z | libs/multiprecision/example/mixed_integer_arithmetic.cpp | ballisticwhisper/boost | f72119ab640b564c4b983bd457457046b52af9ee | [
"BSL-1.0"
] | 3 | 2018-10-31T19:35:14.000Z | 2019-06-04T17:11:27.000Z | libs/multiprecision/example/mixed_integer_arithmetic.cpp | ballisticwhisper/boost | f72119ab640b564c4b983bd457457046b52af9ee | [
"BSL-1.0"
] | 9 | 2015-09-09T02:38:32.000Z | 2021-01-30T00:24:24.000Z | ///////////////////////////////////////////////////////////////
// Copyright 2012 John Maddock. 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_
//
// Compare arithmetic results using fixed_int to GMP results.
//
#ifdef _MSC_VER
# define _SCL_SECURE_NO_WARNINGS
#endif
#include <boost/multiprecision/cpp_int.hpp>
int main()
{
//[mixed_eg
//=#include <boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;
boost::uint64_t i = (std::numeric_limits<boost::uint64_t>::max)();
boost::uint64_t j = 1;
uint128_t ui128;
uint256_t ui256;
//
// Start by performing arithmetic on 64-bit integers to yield 128-bit results:
//
std::cout << std::hex << std::showbase << i << std::endl;
std::cout << std::hex << std::showbase << add(ui128, i, j) << std::endl;
std::cout << std::hex << std::showbase << multiply(ui128, i, i) << std::endl;
//
// The try squaring a 128-bit integer to yield a 256-bit result:
//
ui128 = (std::numeric_limits<uint128_t>::max)();
std::cout << std::hex << std::showbase << multiply(ui256, ui128, ui128) << std::endl;
//]
return 0;
}
/*
Program output:
//[mixed_output
0xffffffffffffffff
0x10000000000000000
0xFFFFFFFFFFFFFFFE0000000000000001
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE00000000000000000000000000000001
//]
*/
| 24.152542 | 88 | 0.653333 | ballisticwhisper |
7348bac9bbc8474ab650d4e0ac07c5408457fb95 | 1,959 | hpp | C++ | breeze/conversion/roman.hpp | gennaroprota/breeze | f1dfd7154222ae358f5ece936c2897a3ae110003 | [
"BSD-3-Clause"
] | 1 | 2021-04-03T22:35:52.000Z | 2021-04-03T22:35:52.000Z | breeze/conversion/roman.hpp | gennaroprota/breeze | f1dfd7154222ae358f5ece936c2897a3ae110003 | [
"BSD-3-Clause"
] | null | null | null | breeze/conversion/roman.hpp | gennaroprota/breeze | f1dfd7154222ae358f5ece936c2897a3ae110003 | [
"BSD-3-Clause"
] | 1 | 2021-10-01T04:26:48.000Z | 2021-10-01T04:26:48.000Z | // ===========================================================================
// Copyright 2016 Gennaro Prota
//
// Licensed under the 3-Clause BSD License.
// (See accompanying file 3_CLAUSE_BSD_LICENSE.txt or
// <https://opensource.org/licenses/BSD-3-Clause>.)
// ___________________________________________________________________________
//
//! \file
//! \brief A Roman numeral.
// ---------------------------------------------------------------------------
#ifndef BREEZE_GUARD_hMt6bmZCT9RIwijJe5QSttMMotHJsr1N
#define BREEZE_GUARD_hMt6bmZCT9RIwijJe5QSttMMotHJsr1N
#include "breeze/top_level_namespace.hpp"
#include <iosfwd>
#include <string>
namespace breeze_ns {
// roman
// =====
//
//! \copybrief roman.hpp
// ---------------------------------------------------------------------------
class roman
{
public:
//! Constructs a Roman numeral corresponding to the number `n`.
//!
//! \pre
//! `1 <= n && n <= 3999`
// -----------------------------------------------------------------------
explicit roman( int n ) ;
//! \return
//! A string containing the Roman numeral. This will always
//! be all-uppercase. To get all-lowercase, use the stream
//! inserter, instead.
//! ----------------------------------------------------------------------
std::string to_string() const ;
private:
//!\cond implementation
int m_value ;
//!endcond
} ;
//!\brief
//! Outputs a Roman numeral to a stream.
//!
//! The uppercase flag (`std::ios_base::uppercase`) is supported, so
//! the user can obtain all-uppercase or all-lowercase.
//!
//! \relatedalso roman.
// ---------------------------------------------------------------------------
std::ostream & operator <<( std::ostream &, roman const & ) ;
}
#endif
| 31.095238 | 78 | 0.453292 | gennaroprota |
734c36b7bf61ac12c065cfe5ad35b0fb84069054 | 453 | cpp | C++ | errlist.cpp | commandus/kv | 49331945c4f6a6608b9545c212d29acf5867ecd3 | [
"MIT"
] | null | null | null | errlist.cpp | commandus/kv | 49331945c4f6a6608b9545c212d29acf5867ecd3 | [
"MIT"
] | null | null | null | errlist.cpp | commandus/kv | 49331945c4f6a6608b9545c212d29acf5867ecd3 | [
"MIT"
] | null | null | null | #include <string.h>
#include "errlist.h"
#define ERR_COUNT 9
static const char* errlist[ERR_COUNT] = {
ERR_COMMAND,
ERR_PARSE_COMMAND,
ERR_LMDB_TXN_BEGIN,
ERR_LMDB_TXN_COMMIT,
ERR_LMDB_OPEN,
ERR_LMDB_CLOSE,
ERR_LMDB_PUT,
ERR_LMDB_GET,
ERR_NO_MEMORY
};
const char *strerror_loracli(
int errcode
)
{
if ((errcode <= -500) && (errcode >= -500 - ERR_COUNT)) {
return errlist[-(errcode + 500)];
}
return strerror(errcode);
}
| 16.777778 | 59 | 0.695364 | commandus |
734d060157db57b523949477841aca66c0c19fbe | 6,663 | cpp | C++ | FEBioXML/FEBioMaterialSection.cpp | Scriptkiddi/FEBioStudio | b4cafde6b2761c9184e7e66451a9555b81a8a3dc | [
"MIT"
] | null | null | null | FEBioXML/FEBioMaterialSection.cpp | Scriptkiddi/FEBioStudio | b4cafde6b2761c9184e7e66451a9555b81a8a3dc | [
"MIT"
] | null | null | null | FEBioXML/FEBioMaterialSection.cpp | Scriptkiddi/FEBioStudio | b4cafde6b2761c9184e7e66451a9555b81a8a3dc | [
"MIT"
] | null | null | null | /*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) 2021 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 "FEBioMaterialSection.h"
#include "FECore/FEModel.h"
#include "FECore/FECoreKernel.h"
#include "FECore/FEMaterial.h"
#include <FEBioMech/FEUncoupledMaterial.h>
#include <FECore/log.h>
#include <sstream>
//-----------------------------------------------------------------------------
//! This function creates a material by checking the type attribute against
//! registered materials. Also, if the tag defines attributes (other than
//! type and name), the material is offered a chance to process the attributes.
FEMaterial* FEBioMaterialSection::CreateMaterial(XMLTag& tag)
{
FEModel& fem = *GetFEModel();
// get the material type
const char* sztype = tag.AttributeValue("type", true);
// in some case, a type is not defined (e.g. for solutes)
// in that case, we use the tag name as the type
if (sztype == 0) sztype = tag.Name();
// create a new material of this type
FEMaterial* pmat = GetBuilder()->CreateMaterial(sztype);
if (pmat == 0) throw XMLReader::InvalidAttributeValue(tag, "type", sztype);
return pmat;
}
//-----------------------------------------------------------------------------
//! Parse the Materials section.
void FEBioMaterialSection::Parse(XMLTag& tag)
{
FEModel& fem = *GetFEModel();
// Make sure no materials are defined
if (fem.Materials() != 0) throw FEBioImport::DuplicateMaterialSection();
// reset material counter
m_nmat = 0;
++tag;
do
{
if (tag == "material")
{
// check that the ID attribute is defined and that it
// equals the number of materials + 1.
int nid = -1;
tag.AttributeValue("id", nid);
int nmat = fem.Materials();
if (nid != nmat+1) throw XMLReader::InvalidAttributeValue(tag, "id");
// make sure that the name is unique
std::string name;
const char* szname = tag.AttributeValue("name", true);
if (szname == nullptr)
{
stringstream ss;
ss << "Material" << nid;
name = ss.str();
feLogWarningEx((&fem), "Material %d has no name.\nIt was given the name %s.", nid, name.c_str());
}
else name = szname;
FEMaterial* mat = fem.FindMaterial(name);
if (mat)
{
throw XMLReader::InvalidAttributeValue(tag, "name");
}
// create a material from this tag
FEMaterial* pmat = CreateMaterial(tag); assert(pmat);
pmat->SetName(name);
// add the material
fem.AddMaterial(pmat);
++m_nmat;
// set the material's ID
pmat->SetID(m_nmat);
// parse the material parameters
ReadParameterList(tag, pmat);
// For uncoupled materials, we collect the bulk moduli of child materials
// and assign it to the top-level material (this one)
FEUncoupledMaterial* pucm = dynamic_cast<FEUncoupledMaterial*>(pmat);
if (pucm) FixUncoupledMaterial(pucm);
}
else throw XMLReader::InvalidTag(tag);
// read next tag
++tag;
}
while (!tag.isend());
}
void FEBioMaterialSection::FixUncoupledMaterial(FEUncoupledMaterial* mat)
{
double K = mat->m_K;
for (int i = 0; i < mat->Properties(); ++i)
{
FEUncoupledMaterial* mati = dynamic_cast<FEUncoupledMaterial*>(mat->GetProperty(i));
if (mati)
{
FixUncoupledMaterial(mati);
K += mati->m_K;
mati->m_K = 0.0;
}
}
mat->m_K = K;
}
//===============================================================================
//-----------------------------------------------------------------------------
//! This function creates a material by checking the type attribute against
//! registered materials. Also, if the tag defines attributes (other than
//! type and name), the material is offered a chance to process the attributes.
FEMaterial* FEBioMaterialSection3::CreateMaterial(XMLTag& tag)
{
FEModel& fem = *GetFEModel();
// get the material type
const char* sztype = tag.AttributeValue("type", true);
// in some case, a type is not defined (e.g. for solutes)
// in that case, we use the tag name as the type
if (sztype == 0) sztype = tag.Name();
// create a new material of this type
FEMaterial* pmat = GetBuilder()->CreateMaterial(sztype);
if (pmat == 0) throw XMLReader::InvalidAttributeValue(tag, "type", sztype);
return pmat;
}
//-----------------------------------------------------------------------------
//! Parse the Materials section.
void FEBioMaterialSection3::Parse(XMLTag& tag)
{
FEModel& fem = *GetFEModel();
// Make sure no materials are defined
if (fem.Materials() != 0) throw FEBioImport::DuplicateMaterialSection();
// reset material counter
m_nmat = 0;
++tag;
do
{
if (tag == "material")
{
// check that the ID attribute is defined and that it
// equals the number of materials + 1.
int nid = -1;
tag.AttributeValue("id", nid);
int nmat = fem.Materials();
if (nid != nmat + 1) throw XMLReader::InvalidAttributeValue(tag, "id");
// make sure that the name is unique
const char* szname = tag.AttributeValue("name");
FEMaterial* mat = fem.FindMaterial(szname);
if (mat)
{
throw XMLReader::InvalidAttributeValue(tag, "name");
}
// create a material from this tag
FEMaterial* pmat = CreateMaterial(tag); assert(pmat);
pmat->SetName(szname);
// add the material
fem.AddMaterial(pmat);
++m_nmat;
// set the material's ID
pmat->SetID(m_nmat);
// parse the material parameters
ReadParameterList(tag, pmat);
}
else throw XMLReader::InvalidTag(tag);
// read next tag
++tag;
} while (!tag.isend());
}
| 29.878924 | 101 | 0.661114 | Scriptkiddi |
7351f5c38092fa0ff8dc1c69abd7da4881961698 | 3,715 | cpp | C++ | USBMissle/servoControl/servoControl.cpp | dennis-tut/thunder-usb-rocketlauncher | d05313382f17ab7a6d4491d3b4439cece13067a9 | [
"MIT"
] | 1 | 2019-12-09T05:50:07.000Z | 2019-12-09T05:50:07.000Z | USBMissle/servoControl/servoControl.cpp | dennis-tut/thunder-usb-rocketlauncher | d05313382f17ab7a6d4491d3b4439cece13067a9 | [
"MIT"
] | null | null | null | USBMissle/servoControl/servoControl.cpp | dennis-tut/thunder-usb-rocketlauncher | d05313382f17ab7a6d4491d3b4439cece13067a9 | [
"MIT"
] | null | null | null | // Uses POSIX functions to send and receive data from a Maestro.
// NOTE: The Maestro's serial mode must be set to "USB Dual Port".
// NOTE: You must change the 'const char * device' line below.
// For further information you can look up the user manual for the Micro Maestro 6-channel at servocity.com
#include "servoControl.h"
servoDevice::servoDevice(void) {
//Open the Maestro's virtual COM port.
const char *device = "/dev/ttyACM0"; //Linux
//if you are a Windows (wo)man you can use "\\\\.\\USBSER000". This solution is not checked though
fd = open(device, O_RDWR | O_NOCTTY);
if (fd == -1) {
perror(device);
}
}
servoDevice::~servoDevice(void) {
resetPosition();
close(fd);
}
//BOTH SPEED FUNCTIONS DO THE SAME
//set Speed from 0 to 255. 0 is no limitation
void servoDevice::setSpeed(std::vector<int> speed) {
if (speed.size() != 2) {
perror("error: speed vector has wrong length\n");
} else {
this->maestroSetSpeed(0, speed[0]);
this->maestroSetSpeed(1, speed[1]);
}
}
//set Speed from 0 to 255. 0 is no limitation
void servoDevice::setSpeed(int speedX, int speedY) {
this->maestroSetSpeed(0, speedX);
this->maestroSetSpeed(1, speedY);
}
//values between 3968 and 8000 are valid
void servoDevice::setPosition(std::vector<int> pos) {
if (pos.size() != 2) {
perror("error: position vector has wrong length\n");
} else {
this->maestroSetTarget(0, pos[0]);
this->maestroSetTarget(1, pos[1]);
}
}
//values between 3968 and 8000 are valid
void servoDevice::setPosition(int posX, int posY) {
this->maestroSetTarget(0, posX);
this->maestroSetTarget(1, posY);
}
// Gets the position of a Maestro channel.
// See the "Serial Servo Commands" section of the user's guide.
int servoDevice::maestroGetPosition(unsigned char channel) {
unsigned char command[] = {0x90, channel};
if (write(fd, command, sizeof(command)) == -1) {
perror("error writing at maestroGetPosition\n");
return -1;
}
unsigned char response[2];
if (read(fd, response, 2) != 2) {
perror("error reading at maestroGetPosition\n");
return -1;
}
return response[0] + 256 * response[1];
}
//Sets the target of a Maestro channel.
//See the "Serial Servo Commands" section of the user's guide
//The units of 'target' are quarter-microseconds.
int servoDevice::maestroSetTarget(unsigned char channel, unsigned short target) {
//user manual pdf page 41 for extensive explanation
unsigned char command[] = {0x84, channel, target & 0x7F, target >> 7 & 0x7F};
if (write(fd, command, sizeof(command)) == -1) {
perror("error writing at maestroSetTarget\n");
return -1;
}
return 0;
}
int servoDevice::maestroSetSpeed(unsigned char channel, unsigned short speed) {
if (speed < 0 || speed > 255) {
perror("error: set a correct speed\n");
return -1;
}
unsigned char command[] = {0x87, channel, speed & 0x7F, speed >> 7 & 0x7F};
if (write(fd, command, sizeof(command)) == -1) {
perror("error writing the speed\n");
return -1;
}
return 0;
}
void servoDevice::resetPosition(void) {
maestroSetTarget(0, 6000);
maestroSetTarget(1, 6000);
}
int main() {
// channel 0 is for vertical rotation, channel 1 for horizontal rotation
// theoretically a 2-axis rotation at the same time should be possible, but currently we'd have to wait for the return of one function
// should be implemented with pthreads or something similar
servoDevice *device = new servoDevice();
device->setSpeed(5,5);
device->setPosition(4000, 4000);
sleep(2);
std::vector<int> *test = new std::vector<int>();
test->push_back(40);
test->push_back(40);
device->setSpeed(*test);
test->at(0) = 8000;
test->at(1) = 8000;
device->setPosition(*test);
delete test;
delete device;
return 1;
}
| 27.518519 | 135 | 0.695828 | dennis-tut |
7356da6131f50831373ca0acf00437d30637b078 | 2,892 | cpp | C++ | main.cpp | kevinyxlu/cs32lab03 | 582c42181d8e7891a6f34a3ef5f524c915e963a1 | [
"MIT"
] | null | null | null | main.cpp | kevinyxlu/cs32lab03 | 582c42181d8e7891a6f34a3ef5f524c915e963a1 | [
"MIT"
] | null | null | null | main.cpp | kevinyxlu/cs32lab03 | 582c42181d8e7891a6f34a3ef5f524c915e963a1 | [
"MIT"
] | null | null | null | // Spring 2021 CS32 lab03
// Created by: Kevin Lu and Kevin Lai
// Created on: 04/25/2021
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include "demogData.h"
#include "parse.h"
#include "dataAQ.h"
using namespace std;
int main() {
dataAQ theAnswers;
//read in a csv file and create a vector of objects representing each counties data
std::vector<shared_ptr<demogData>> theData = read_csv(
"county_demographics.csv", DEMOG);
//debug print out - uncomment if you want to double check your data
/*
for (const auto &obj : theData) {
std::cout << *obj << std::endl;
}
*/
theAnswers.createStateData(theData);
//one example of how to print required - ADD OTHERS
cout << "*** the state that needs the most pre-schools**" << endl;
string needPK = theAnswers.youngestPop();
cout << "Name of state: " << needPK << endl;
if (theAnswers.getStateData(needPK) != nullptr){
cout << *(theAnswers.getStateData(needPK)) << endl;
} else{
cout << "Did you read the lab instructions?" << endl;
}
//NOW fill in these too
cout << "*** the state that needs the most high schools**" << endl;
needPK = theAnswers.teenPop();
cout << "Name of state: " << needPK << endl;
if (theAnswers.getStateData(needPK) != nullptr){
cout << *(theAnswers.getStateData(needPK)) << endl;
} else{
cout << "state ptr getter failed" << endl;
}
cout << "*** the state that needs the most vaccines**" << endl;
needPK = theAnswers.wisePop();
cout << "Name of state: " << needPK << endl;
if (theAnswers.getStateData(needPK) != nullptr){
cout << *(theAnswers.getStateData(needPK)) << endl;
} else{
cout << "state ptr getter failed" << endl;
}
cout << "*** the state that needs the most help with education**" << endl;
needPK = theAnswers.underServeHS();
cout << "Name of state: " << needPK << endl;
if (theAnswers.getStateData(needPK) != nullptr){
cout << *(theAnswers.getStateData(needPK)) << endl;
} else{
cout << "state ptr getter failed" << endl;
}
cout << "*** the state with most college grads**" << endl;
needPK = theAnswers.collegeGrads();
cout << "Name of state: " << needPK << endl;
if (theAnswers.getStateData(needPK) != nullptr){
cout << *(theAnswers.getStateData(needPK)) << endl;
} else{
cout << "state ptr getter failed" << endl;
}
cout << "*** the state with largest percent of the population below the poverty line**" << endl;
needPK = theAnswers.belowPoverty();
cout << "Name of state: " << needPK << endl;
if (theAnswers.getStateData(needPK) != nullptr){
cout << *(theAnswers.getStateData(needPK)) << endl;
} else{
cout << "state ptr getter failed" << endl;
}
return 0;
}
| 31.78022 | 100 | 0.606501 | kevinyxlu |
735adf01eb599dd2d80ebd835b4f0ed3fd7cdd88 | 530 | hpp | C++ | gv_base/src/android/gv_stream_android_asset.hpp | dragonsn/gv_game_engine | dca6c1fb1f8d96e9a244f157a63f8a69da084b0f | [
"MIT"
] | 2 | 2018-12-03T13:17:31.000Z | 2020-04-08T07:00:02.000Z | gv_base/src/android/gv_stream_android_asset.hpp | dragonsn/gv_game_engine | dca6c1fb1f8d96e9a244f157a63f8a69da084b0f | [
"MIT"
] | null | null | null | gv_base/src/android/gv_stream_android_asset.hpp | dragonsn/gv_game_engine | dca6c1fb1f8d96e9a244f157a63f8a69da084b0f | [
"MIT"
] | null | null | null | namespace gv
{
class gv_stream_android_asset : public gvi_stream
{
public:
gv_stream_android_asset();
~gv_stream_android_asset();
virtual bool open(const char* name);
virtual bool close();
virtual gv_int tell();
virtual void flush();
virtual gv_int read(void* pdata, gv_int isize);
virtual gv_int write(const void* pdata, gv_int isize);
virtual bool seek(gv_uint pos, std::ios_base::seekdir dir);
virtual gv_int size();
virtual bool eof();
virtual void set_buf_size(gv_int size);
private:
class AAsset* _asset;
};
}
| 23.043478 | 60 | 0.750943 | dragonsn |
73643306c97d85a7bbcc252b934e5c3b914cf526 | 8,220 | cc | C++ | node_modules/gl/angle/src/tests/perf_tests/third_party/perf/perf_test.cc | aaverty/editly | 71bccaf91f8d68609c80ba59425b79e3f94579ad | [
"MIT"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | node_modules/gl/angle/src/tests/perf_tests/third_party/perf/perf_test.cc | aaverty/editly | 71bccaf91f8d68609c80ba59425b79e3f94579ad | [
"MIT"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | node_modules/gl/angle/src/tests/perf_tests/third_party/perf/perf_test.cc | aaverty/editly | 71bccaf91f8d68609c80ba59425b79e3f94579ad | [
"MIT"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "perf_test.h"
#include <stdio.h>
#include <stdarg.h>
#include <vector>
namespace {
namespace base {
std::string FormatString(const char *fmt, va_list vararg) {
static std::vector<char> buffer(512);
// Attempt to just print to the current buffer
int len = vsnprintf(&buffer[0], buffer.size(), fmt, vararg);
if (len < 0 || static_cast<size_t>(len) >= buffer.size()) {
// Buffer was not large enough, calculate the required size and resize the buffer
len = vsnprintf(NULL, 0, fmt, vararg);
buffer.resize(len + 1);
// Print again
vsnprintf(&buffer[0], buffer.size(), fmt, vararg);
}
return std::string(buffer.data(), len);
}
std::string StringPrintf(const char *fmt, ...) {
va_list vararg;
va_start(vararg, fmt);
std::string result = FormatString(fmt, vararg);
va_end(vararg);
return result;
}
std::string UintToString(unsigned int value) {
return StringPrintf("%u", value);
}
std::string DoubleToString(double value) {
return StringPrintf("%.10lf", value);
}
}
std::string ResultsToString(const std::string& measurement,
const std::string& modifier,
const std::string& trace,
const std::string& values,
const std::string& prefix,
const std::string& suffix,
const std::string& units,
bool important) {
// <*>RESULT <graph_name>: <trace_name>= <value> <units>
// <*>RESULT <graph_name>: <trace_name>= {<mean>, <std deviation>} <units>
// <*>RESULT <graph_name>: <trace_name>= [<value>,value,value,...,] <units>
return base::StringPrintf("%sRESULT %s%s: %s= %s%s%s %s\n",
important ? "*" : "", measurement.c_str(), modifier.c_str(),
trace.c_str(), prefix.c_str(), values.c_str(), suffix.c_str(),
units.c_str());
}
void PrintResultsImpl(const std::string& measurement,
const std::string& modifier,
const std::string& trace,
const std::string& values,
const std::string& prefix,
const std::string& suffix,
const std::string& units,
bool important) {
fflush(stdout);
printf("%s", ResultsToString(measurement, modifier, trace, values,
prefix, suffix, units, important).c_str());
fflush(stdout);
}
} // namespace
namespace perf_test {
void PrintResult(const std::string& measurement,
const std::string& modifier,
const std::string& trace,
size_t value,
const std::string& units,
bool important) {
PrintResultsImpl(measurement,
modifier,
trace,
base::UintToString(static_cast<unsigned int>(value)),
std::string(),
std::string(),
units,
important);
}
void PrintResult(const std::string& measurement,
const std::string& modifier,
const std::string& trace,
double value,
const std::string& units,
bool important) {
PrintResultsImpl(measurement,
modifier,
trace,
base::DoubleToString(value),
std::string(),
std::string(),
units,
important);
}
void AppendResult(std::string& output,
const std::string& measurement,
const std::string& modifier,
const std::string& trace,
size_t value,
const std::string& units,
bool important) {
output += ResultsToString(
measurement,
modifier,
trace,
base::UintToString(static_cast<unsigned int>(value)),
std::string(),
std::string(),
units,
important);
}
void PrintResult(const std::string& measurement,
const std::string& modifier,
const std::string& trace,
const std::string& value,
const std::string& units,
bool important) {
PrintResultsImpl(measurement,
modifier,
trace,
value,
std::string(),
std::string(),
units,
important);
}
void AppendResult(std::string& output,
const std::string& measurement,
const std::string& modifier,
const std::string& trace,
const std::string& value,
const std::string& units,
bool important) {
output += ResultsToString(measurement,
modifier,
trace,
value,
std::string(),
std::string(),
units,
important);
}
void PrintResultMeanAndError(const std::string& measurement,
const std::string& modifier,
const std::string& trace,
const std::string& mean_and_error,
const std::string& units,
bool important) {
PrintResultsImpl(measurement, modifier, trace, mean_and_error,
"{", "}", units, important);
}
void AppendResultMeanAndError(std::string& output,
const std::string& measurement,
const std::string& modifier,
const std::string& trace,
const std::string& mean_and_error,
const std::string& units,
bool important) {
output += ResultsToString(measurement, modifier, trace, mean_and_error,
"{", "}", units, important);
}
void PrintResultList(const std::string& measurement,
const std::string& modifier,
const std::string& trace,
const std::string& values,
const std::string& units,
bool important) {
PrintResultsImpl(measurement, modifier, trace, values,
"[", "]", units, important);
}
void AppendResultList(std::string& output,
const std::string& measurement,
const std::string& modifier,
const std::string& trace,
const std::string& values,
const std::string& units,
bool important) {
output += ResultsToString(measurement, modifier, trace, values,
"[", "]", units, important);
}
void PrintSystemCommitCharge(const std::string& test_name,
size_t charge,
bool important) {
PrintSystemCommitCharge(stdout, test_name, charge, important);
}
void PrintSystemCommitCharge(FILE* target,
const std::string& test_name,
size_t charge,
bool important) {
fprintf(target, "%s", SystemCommitChargeToString(test_name, charge,
important).c_str());
}
std::string SystemCommitChargeToString(const std::string& test_name,
size_t charge,
bool important) {
std::string trace_name(test_name);
std::string output;
AppendResult(output,
"commit_charge",
std::string(),
"cc" + trace_name,
charge,
"kb",
important);
return output;
}
} // namespace perf_test
| 34.25 | 85 | 0.499878 | aaverty |
736818443673654fe8ba564d31d358fbcfd460c2 | 1,360 | cpp | C++ | src/bindings/python/src/compatibility/pyngraph/util.cpp | evgeniya-egupova/openvino | 4b8d6c59e3444ecdc549bfdf357d19d625479b89 | [
"Apache-2.0"
] | null | null | null | src/bindings/python/src/compatibility/pyngraph/util.cpp | evgeniya-egupova/openvino | 4b8d6c59e3444ecdc549bfdf357d19d625479b89 | [
"Apache-2.0"
] | 44 | 2020-12-09T12:38:22.000Z | 2022-03-28T13:18:29.000Z | src/bindings/python/src/compatibility/pyngraph/util.cpp | rkazants/openvino | a9a583eb42d43322b39b95b164b5b22c4f341111 | [
"Apache-2.0"
] | 2 | 2021-11-18T06:09:04.000Z | 2021-11-30T07:39:47.000Z | // Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "pyngraph/util.hpp"
#include <pybind11/numpy.h>
#include "ngraph/validation_util.hpp"
#include "ngraph/version.hpp"
namespace py = pybind11;
void* numpy_to_c(py::array a) {
py::buffer_info info = a.request();
return info.ptr;
}
void regmodule_pyngraph_util(py::module m) {
py::module mod = m.def_submodule("util", "ngraph.impl.util");
mod.def("numpy_to_c", &numpy_to_c);
mod.def("get_constant_from_source",
&ngraph::get_constant_from_source,
py::arg("output"),
R"(
Runs an estimation of source tensor.
Parameters
----------
output : Output
output node
Returns
----------
get_constant_from_source : Constant or None
If it succeeded to calculate both bounds and
they are the same returns Constant operation
from the resulting bound, otherwise Null.
)");
mod.def("get_ngraph_version_string", []() -> std::string {
NGRAPH_SUPPRESS_DEPRECATED_START
return get_ngraph_version_string();
NGRAPH_SUPPRESS_DEPRECATED_END
});
}
| 30.222222 | 68 | 0.5625 | evgeniya-egupova |
73683f437180e5020aa66c1c106252a467b326b3 | 1,437 | hpp | C++ | waveform_system/super_wave_oscillator.hpp | kumataro4160/Sense | ac44d306cc81fb37e017c0dcf12d9f3dd5e9af4b | [
"MIT"
] | null | null | null | waveform_system/super_wave_oscillator.hpp | kumataro4160/Sense | ac44d306cc81fb37e017c0dcf12d9f3dd5e9af4b | [
"MIT"
] | null | null | null | waveform_system/super_wave_oscillator.hpp | kumataro4160/Sense | ac44d306cc81fb37e017c0dcf12d9f3dd5e9af4b | [
"MIT"
] | null | null | null | #pragma once
#include "effector.hpp"
#include "../../random.hpp"
#include "../wave_table_1d.hpp"
namespace sense
{
class SuperWaveOscillator : public Effector
{
const WaveTable1D waveTable;
const std::vector<float64> initialTheta;
const std::vector<float64> omegaRate;
std::vector<float64> theta;
std::vector<float64> getRandomInitialTheta(uint32_t numVoices)
{
std::vector<float64> ret(numVoices);
for(auto &th : ret)
{
th = 2.0 * pi * getRandomNumberZeroToOne();
}
return ret;
}
std::vector<float64> getRandomOmegaRate(uint32_t numVoices, float64 detuneDepth)
{
std::vector<float64> ret(numVoices);
for(auto &om : ret)
{
om = std::pow(2.0, detuneDepth * getRandomNumberNegativeOneToOne() / 12.0);
}
return ret;
}
public:
SuperWaveOscillator(const WaveTable1D &waveTable, uint32_t numVoices, float64 detuneDepth)
: waveTable(waveTable), initialTheta(getRandomInitialTheta(numVoices)), omegaRate(getRandomOmegaRate(numVoices, detuneDepth)), theta(initialTheta)
{
}
void reset()noexcept override
{
theta = initialTheta;
}
__forceinline float64 process(float64 inputSample)noexcept override
{
float64 ret = 0.0;
for(int n = 0; n < theta.size(); ++n)
{
ret += waveTable(theta[n]);
theta[n] += inputSample * omegaRate[n];
if(theta[n] >= 2.0 * pi)
{
theta[n] -= 2.0 * pi;
}
}
return ret / theta.size();
}
};
} | 23.557377 | 149 | 0.66945 | kumataro4160 |
7369778be8ac2e75b45ca12f02b761db0752f7fb | 10,492 | cpp | C++ | test/system/window_focus/main.cpp | alexiynew/nih_framework | a65335586331daa0ece892f98265bd1d2f8f579f | [
"MIT"
] | 1 | 2017-07-14T04:51:54.000Z | 2017-07-14T04:51:54.000Z | test/system/window_focus/main.cpp | alexiynew/nih_framework | a65335586331daa0ece892f98265bd1d2f8f579f | [
"MIT"
] | 32 | 2017-02-02T14:49:41.000Z | 2019-06-25T19:38:27.000Z | test/system/window_focus/main.cpp | alexiynew/nih_framework | a65335586331daa0ece892f98265bd1d2f8f579f | [
"MIT"
] | null | null | null | #include <chrono>
#include <iostream>
#include <thread>
#include <system/window.hpp>
#include <unit_test/suite.hpp>
using namespace framework::system;
class WindowFocusTest : public framework::unit_test::Suite
{
public:
WindowFocusTest()
: Suite("WindowFocusTest")
{
add_test([this]() { focus_one_window(); }, "focus_one_windows");
add_test([this]() { focus_two_windows(); }, "focus_two_windows");
}
private:
void focus_one_window()
{
int on_focus_called = 0;
int on_lost_focus_called = 0;
Window w(name(), {640, 480});
w.on_focus.connect([&on_focus_called](const Window& /*unused*/) { on_focus_called++; });
w.on_lost_focus.connect([&on_lost_focus_called](const Window& /*unused*/) { on_lost_focus_called++; });
w.focus();
TEST_ASSERT(on_focus_called == 0, "Invalid callback call.");
TEST_ASSERT(on_lost_focus_called == 0, "Invalid callback call.");
w.show();
TEST_ASSERT(w.is_visible(), "Window should be visible.");
TEST_ASSERT(w.has_input_focus(), "Window should has focus.");
TEST_ASSERT(on_focus_called == 1, "Invalid callback call.");
TEST_ASSERT(on_lost_focus_called == 0, "Invalid callback call.");
w.focus();
TEST_ASSERT(on_focus_called == 1, "Invalid callback call.");
TEST_ASSERT(on_lost_focus_called == 0, "Invalid callback call.");
w.hide();
TEST_ASSERT(!w.is_visible(), "Window should be visible.");
TEST_ASSERT(!w.has_input_focus(), "Window should has focus.");
TEST_ASSERT(on_focus_called == 1, "Invalid callback call.");
TEST_ASSERT(on_lost_focus_called == 1, "Invalid callback call.");
w.focus();
TEST_ASSERT(on_focus_called == 1, "Invalid callback call.");
TEST_ASSERT(on_lost_focus_called == 1, "Invalid callback call.");
w.show();
TEST_ASSERT(w.is_visible(), "Window should be visible.");
TEST_ASSERT(w.has_input_focus(), "Window should has focus.");
TEST_ASSERT(on_focus_called == 2, "Invalid callback call.");
TEST_ASSERT(on_lost_focus_called == 1, "Invalid callback call.");
w.hide();
TEST_ASSERT(!w.is_visible(), "Window should be visible.");
TEST_ASSERT(!w.has_input_focus(), "Window should has focus.");
TEST_ASSERT(on_focus_called == 2, "Invalid callback call.");
TEST_ASSERT(on_lost_focus_called == 2, "Invalid callback call.");
}
void focus_two_windows()
{
int alpha_focused = 0;
int alpha_lost_focus = 0;
int betta_focused = 0;
int betta_lost_focus = 0;
Window alpha(name() + ":alpha", {640, 480});
Window betta(name() + ":betta", {640, 480});
alpha.on_focus.connect([&alpha_focused](const Window& /*unused*/) { alpha_focused++; });
alpha.on_lost_focus.connect([&alpha_lost_focus](const Window& /*unused*/) { alpha_lost_focus++; });
betta.on_focus.connect([&betta_focused](const Window& /*unused*/) { betta_focused++; });
betta.on_lost_focus.connect([&betta_lost_focus](const Window& /*unused*/) { betta_lost_focus++; });
TEST_ASSERT(!alpha.is_visible(), "Window should not be visible.");
TEST_ASSERT(!betta.is_visible(), "Window should not be visible.");
TEST_ASSERT(!alpha.has_input_focus(), "Window should not has focus.");
TEST_ASSERT(!betta.has_input_focus(), "Window should not has focus.");
// Try to focus hidden windows, should not get focus
alpha.focus();
betta.focus();
TEST_ASSERT(!alpha.has_input_focus(), "Window should not has focus.");
TEST_ASSERT(!betta.has_input_focus(), "Window should not has focus.");
TEST_ASSERT(alpha_focused == 0, "Window should has focus.");
TEST_ASSERT(alpha_lost_focus == 0, "Window should not lost focus.");
TEST_ASSERT(betta_focused == 0, "Window should not has focus.");
TEST_ASSERT(betta_lost_focus == 0, "Window should not lost focus.");
std::this_thread::sleep_for(std::chrono::seconds(1));
// Show the alpha window, should get focus
alpha.show();
TEST_ASSERT(alpha.is_visible(), "Window should be visible.");
TEST_ASSERT(!betta.is_visible(), "Window should not be visible.");
TEST_ASSERT(alpha_focused == 1, "Window should has focus.");
TEST_ASSERT(alpha_lost_focus == 0, "Window should not lost focus.");
TEST_ASSERT(betta_focused == 0, "Window should not has focus.");
TEST_ASSERT(betta_lost_focus == 0, "Window should not lost focus.");
TEST_ASSERT(alpha.has_input_focus(), "Focus function is not working.");
TEST_ASSERT(!betta.has_input_focus(), "Focus function is not working.");
std::this_thread::sleep_for(std::chrono::seconds(1));
// Show the betta window, alpha should lost focus, betta should get focus
betta.show();
alpha.process_events();
TEST_ASSERT(alpha.is_visible(), "Window should be visible.");
TEST_ASSERT(betta.is_visible(), "Window should be visible.");
TEST_ASSERT(alpha_focused == 1, "Window should have had focus previously.");
TEST_ASSERT(alpha_lost_focus == 1, "Window should lost focus.");
TEST_ASSERT(betta_focused == 1, "Window should has focus.");
TEST_ASSERT(betta_lost_focus == 0, "Window should not lost focus.");
TEST_ASSERT(!alpha.has_input_focus(), "Focus function is not working.");
TEST_ASSERT(betta.has_input_focus(), "Focus function is not working.");
std::this_thread::sleep_for(std::chrono::seconds(1));
// Return focus to alpha, betta should lost focus
alpha.focus();
betta.process_events();
TEST_ASSERT(alpha.is_visible(), "Window should be visible.");
TEST_ASSERT(betta.is_visible(), "Window should be visible.");
TEST_ASSERT(alpha_focused == 2, "Window should get focus twice.");
TEST_ASSERT(alpha_lost_focus == 1, "Window should lost focus once.");
TEST_ASSERT(betta_focused == 1, "Window should have had focus previously.");
TEST_ASSERT(betta_lost_focus == 1, "Window should lost focus.");
TEST_ASSERT(alpha.has_input_focus(), "Focus function is not working.");
TEST_ASSERT(!betta.has_input_focus(), "Focus function is not working.");
std::this_thread::sleep_for(std::chrono::seconds(1));
// Return focus to betta, alpha should lost focus
betta.focus();
alpha.process_events();
TEST_ASSERT(alpha.is_visible(), "Window should be visible.");
TEST_ASSERT(betta.is_visible(), "Window should be visible.");
TEST_ASSERT(alpha_focused == 2, "Window should get focus twice.");
TEST_ASSERT(alpha_lost_focus == 2, "Window should lost focus twice.");
TEST_ASSERT(betta_focused == 2, "Window should get focus twice.");
TEST_ASSERT(betta_lost_focus == 1, "Window should lost focus.");
TEST_ASSERT(!alpha.has_input_focus(), "Focus function is not working.");
TEST_ASSERT(betta.has_input_focus(), "Focus function is not working.");
std::this_thread::sleep_for(std::chrono::seconds(1));
// Hide alpha, no on_lost_focus message for alpha
alpha.hide();
betta.process_events();
TEST_ASSERT(!alpha.is_visible(), "Window should not be visible.");
TEST_ASSERT(betta.is_visible(), "Window should be visible.");
TEST_ASSERT(alpha_focused == 2, "Window should get focus twice.");
TEST_ASSERT(alpha_lost_focus == 2, "Window should lost focus twice.");
TEST_ASSERT(betta_focused == 2, "Window should get focus twice.");
TEST_ASSERT(betta_lost_focus == 1, "Window should lost focus.");
TEST_ASSERT(!alpha.has_input_focus(), "Focus function is not working.");
TEST_ASSERT(betta.has_input_focus(), "Focus function is not working.");
std::this_thread::sleep_for(std::chrono::seconds(1));
// Show alpha
alpha.show();
betta.process_events();
TEST_ASSERT(alpha.is_visible(), "Window should be visible.");
TEST_ASSERT(betta.is_visible(), "Window should be visible.");
TEST_ASSERT(alpha_focused == 3, "Window should get focus 3 times.");
TEST_ASSERT(alpha_lost_focus == 2, "Window should lost focus twice.");
TEST_ASSERT(betta_focused == 2, "Window should get focus twice.");
TEST_ASSERT(betta_lost_focus == 2, "Window should lost focus twice.");
TEST_ASSERT(alpha.has_input_focus(), "Focus function is not working.");
TEST_ASSERT(!betta.has_input_focus(), "Focus function is not working.");
std::this_thread::sleep_for(std::chrono::seconds(1));
// Return focus to betta again, alpha should lost focus
betta.focus();
alpha.process_events();
TEST_ASSERT(alpha.is_visible(), "Window should be visible.");
TEST_ASSERT(betta.is_visible(), "Window should be visible.");
TEST_ASSERT(alpha_focused == 3, "Window should get focus 3 times.");
TEST_ASSERT(alpha_lost_focus == 3, "Window should lost focus 3 times.");
TEST_ASSERT(betta_focused == 3, "Window should get focus 3 times.");
TEST_ASSERT(betta_lost_focus == 2, "Window should lost focus twice.");
TEST_ASSERT(!alpha.has_input_focus(), "Focus function is not working.");
TEST_ASSERT(betta.has_input_focus(), "Focus function is not working.");
std::this_thread::sleep_for(std::chrono::seconds(1));
// Hide betta, aplha should get focus
betta.hide();
TEST_ASSERT(!betta.is_visible(), "Window should be visible.");
TEST_ASSERT(!betta.has_input_focus(), "Focus function is not working.");
TEST_ASSERT(betta_focused == 3, "Window should get focus 3 times.");
TEST_ASSERT(betta_lost_focus == 3, "Window should lost focus 3 times.");
std::this_thread::sleep_for(std::chrono::seconds(1));
// Hide alpha, should lost focus
alpha.hide();
TEST_ASSERT(!alpha.is_visible(), "Window should be visible.");
TEST_ASSERT(!alpha.has_input_focus(), "Focus function is not working.");
TEST_ASSERT(alpha_focused == 4, "Window should get focus 4 times.");
TEST_ASSERT(alpha_lost_focus == 4, "Window should lost focus 4 times.");
}
};
int main()
{
return run_tests(WindowFocusTest());
}
| 40.353846 | 111 | 0.648494 | alexiynew |
7369a7603124fc22fb32661e09864c4842d1468a | 267 | cpp | C++ | chapter-04/exercise_4_36.cpp | aufziehvogel/cpp-primer | 1ae8fdcda8580ea5d646a725fbb76110f138dbc8 | [
"MIT"
] | null | null | null | chapter-04/exercise_4_36.cpp | aufziehvogel/cpp-primer | 1ae8fdcda8580ea5d646a725fbb76110f138dbc8 | [
"MIT"
] | null | null | null | chapter-04/exercise_4_36.cpp | aufziehvogel/cpp-primer | 1ae8fdcda8580ea5d646a725fbb76110f138dbc8 | [
"MIT"
] | null | null | null | #include <iostream>
int main()
{
int i = -10;
double d = 3.14;
i *= d;
std::cout << "Without cast to int: " << i << std::endl;
i = -10;
i *= static_cast<int>(d);
std::cout << "With cast to int: " << i << std::endl;
return 0;
}
| 15.705882 | 59 | 0.468165 | aufziehvogel |
736a8131ea3337906e02dfabbc432db6ca002eda | 4,177 | hpp | C++ | interfaces/pixel_buffer.hpp | PiotrBanuba/OEP-module | d60204b8f6c3738e6fb8b5c2ea657460397be774 | [
"MIT"
] | null | null | null | interfaces/pixel_buffer.hpp | PiotrBanuba/OEP-module | d60204b8f6c3738e6fb8b5c2ea657460397be774 | [
"MIT"
] | 2 | 2022-03-16T13:01:29.000Z | 2022-03-16T14:06:16.000Z | interfaces/pixel_buffer.hpp | PiotrBanuba/OEP-module | d60204b8f6c3738e6fb8b5c2ea657460397be774 | [
"MIT"
] | null | null | null | #pragma once
#include <memory>
#include <functional>
#include <interfaces/image_format.hpp>
namespace bnb::oep::interfaces
{
class pixel_buffer;
}
using pixel_buffer_sptr = std::shared_ptr<bnb::oep::interfaces::pixel_buffer>;
namespace bnb::oep::interfaces
{
class pixel_buffer
{
public:
using plane_sptr = std::shared_ptr<uint8_t>;
struct plane_data
{
plane_sptr data{nullptr};
size_t size{0};
int32_t bytes_per_row{0};
}; /* struct plane_data */
public:
/**
* Create the pixel buffer and returns shared pointer.
*
* @param planes with pixel data
* @param fmt input image format
* @param width Inpuut width of the image
* @param width Inpuut height of the image
* @param deleter custom deleter for pixel buffer
*
* @example bnb::oep::interfaces::pixel_buffer::create(planes, image_format::bpc8_rgba, 1280, 720)
*/
static pixel_buffer_sptr create(const std::vector<plane_data>& planes, image_format fmt, int32_t width, int32_t height, std::function<void(pixel_buffer*)> deleter = std::default_delete<pixel_buffer>());
virtual ~pixel_buffer() = default;
/**
* Returns format of the current image
*
* @example get_image_format()
*/
virtual image_format get_image_format() = 0;
/**
* Returns count of the planes
*
* @example get_plane_count()
*/
virtual int32_t get_plane_count() = 0;
/**
* Returns the shared pointer of the first plane
*
* @example get_base_sptr()
*/
virtual plane_sptr get_base_sptr() = 0;
/**
* Returns the shared pointer to pixel data of the specified plane
*
* @param plane_num plane number. Must be 0 for bpc8, [0..1] for nv12 and [0..2] for i420 images
*
* @example get_base_sptr_of_plane(0)
*/
virtual plane_sptr get_base_sptr_of_plane(int32_t plane_num) = 0;
/**
* Returns the pixel size of the first plane
*
* @example get_bytes_per_pixel()
*/
virtual int32_t get_bytes_per_pixel() = 0;
/**
* Returns the pixel size of the specified plane
*
* @param plane_num plane number. Must be 0 for bpc8, [0..1] for nv12 and [0..2] for i420 images
*
* @example get_bytes_per_pixel_of_plane(0)
*/
virtual int32_t get_bytes_per_pixel_of_plane(int32_t plane_num) = 0;
/**
* Returns the stride of the first plane
*
* @example get_bytes_per_row()
*/
virtual int32_t get_bytes_per_row() = 0;
/**
* Returns the stride of the specified plane
*
* @param plane_num plane number. Must be 0 for bpc8, [0..1] for nv12 and [0..2] for i420 images
*
* @example get_bytes_per_row_of_plane(0)
*/
virtual int32_t get_bytes_per_row_of_plane(int32_t plane_num) = 0;
/**
* Returns the width of the first plane
*
* @example get_width()
*/
virtual int32_t get_width() = 0;
/**
* Returns the width of the specified plane
*
* @param plane_num plane number. Must be 0 for bpc8, [0..1] for nv12 and [0..2] for i420 images
*
* @example get_width_of_plane(0)
*/
virtual int32_t get_width_of_plane(int32_t plane_num) = 0;
/**
* Returns the height of the first plane
*
* @example get_height()
*/
virtual int32_t get_height() = 0;
/**
* Returns the height of the specified plane
*
* @param plane_num plane number. Must be 0 for bpc8, [0..1] for nv12 and [0..2] for i420 images
*
* @example get_height_of_plane(0)
*/
virtual int32_t get_height_of_plane(int32_t plane_num) = 0;
}; /* class pixel_buffer INTERFACE */
} /* namespace bnb::oep::interfaces */
| 29.624113 | 210 | 0.570745 | PiotrBanuba |
736ae9a9e9c29141a7e76f871f82c06e8f75c4ae | 7,415 | hpp | C++ | boost/time_series/characteristic_series.hpp | ericniebler/time_series | 4040119366cc21f25c7734bb355e4a647296a96d | [
"BSL-1.0"
] | 11 | 2015-02-21T11:23:44.000Z | 2021-08-15T03:39:29.000Z | boost/time_series/characteristic_series.hpp | ericniebler/time_series | 4040119366cc21f25c7734bb355e4a647296a96d | [
"BSL-1.0"
] | null | null | null | boost/time_series/characteristic_series.hpp | ericniebler/time_series | 4040119366cc21f25c7734bb355e4a647296a96d | [
"BSL-1.0"
] | 3 | 2015-05-09T02:25:42.000Z | 2019-11-02T13:39:29.000Z | ///////////////////////////////////////////////////////////////////////////////
/// \file characteristic_series.hpp
/// A time series that uses characteristic storage
//
// Copyright 2006 Eric Niebler. 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 BOOST_TIME_SERIES_CHARACTERISTIC_SERIES_HPP_EAN_05_29_2006
#define BOOST_TIME_SERIES_CHARACTERISTIC_SERIES_HPP_EAN_05_29_2006
#include <boost/time_series/time_series_facade.hpp>
#include <boost/time_series/storage/characteristic_array.hpp>
namespace boost { namespace time_series
{
/// \brief A \c Mutable_TimeSeries that has the unit value within some <tt>[start,stop)</tt> range,
/// and zero elsewhere.
///
/// A \c Mutable_TimeSeries that has the unit value within some <tt>[start,stop)</tt> range,
/// and zero elsewhere.
///
/// The named parameters for the constructor are, in order:
/// -# \c start, with a default of \c Offset(0)
/// -# \c stop, with a default of \c Offset(0)
/// -# \c value, with a default of \c Value(1)
/// -# \c discretization, with a default of \c Discretization(1)
/// -# \c zero, with a default of \c Value(0)
template<typename Value, typename Discretization, typename Offset>
struct characteristic_unit_series
: time_series_facade<
characteristic_unit_series<Value, Discretization, Offset>
, storage::characteristic_array<Value, Offset>
, Discretization
>
{
typedef time_series_facade<
characteristic_unit_series<Value, Discretization, Offset>
, storage::characteristic_array<Value, Offset>
, Discretization
> base_type;
using base_type::operator=;
BOOST_TIME_SERIES_DEFINE_CTORS(characteristic_unit_series)
};
namespace traits
{
/// INTERNAL ONLY
template<typename Value, typename Discretization, typename Offset>
struct storage_category<characteristic_unit_series<Value, Discretization, Offset> >
: storage_category<storage::characteristic_array<Value, Offset> >
{};
/// INTERNAL ONLY
template<typename Value, typename Discretization, typename Offset>
struct discretization_type<characteristic_unit_series<Value, Discretization, Offset> >
{
typedef Discretization type;
};
/// INTERNAL ONLY
template<typename Value, typename Discretization, typename Offset>
struct offset_type<characteristic_unit_series<Value, Discretization, Offset> >
{
typedef Offset type;
};
/// INTERNAL ONLY
template<typename Value, typename Discretization, typename Offset>
struct generate_series<characteristic_storage_tag, Value, Discretization, Offset>
{
typedef characteristic_unit_series<Value, Discretization, Offset> type;
};
}
}}
namespace boost { namespace sequence { namespace impl
{
/// INTERNAL ONLY
template<typename Value, typename Discretization, typename Offset>
struct tag<time_series::characteristic_unit_series<Value, Discretization, Offset> >
{
typedef time_series_tag type;
};
}}}
namespace boost { namespace time_series
{
/// \brief A \c Mutable_TimeSeries that has a distinct value within some <tt>[start,stop)</tt> range,
/// and zero elsewhere.
///
/// A \c Mutable_TimeSeries that has a distinct value within some <tt>[start,stop)</tt> range,
/// and zero elsewhere.
///
/// The named parameters for the constructor are, in order:
/// -# \c start, with a default of \c Offset(0)
/// -# \c stop, with a default of \c Offset(0)
/// -# \c value, with a default of \c Value(1)
/// -# \c discretization, with a default of \c Discretization(1)
/// -# \c zero, with a default of \c Value(0)
template<typename Value, typename Discretization, typename Offset>
struct characteristic_series
: time_series_facade<
characteristic_series<Value, Discretization, Offset>
, storage::characteristic_array<Value, Offset, storage::constant_elements<Value> >
, Discretization
>
{
typedef time_series_facade<
characteristic_series<Value, Discretization, Offset>
, storage::characteristic_array<Value, Offset, storage::constant_elements<Value> >
, Discretization
> base_type;
using base_type::operator=;
BOOST_TIME_SERIES_DEFINE_CTORS(characteristic_series)
};
namespace traits
{
/// INTERNAL ONLY
template<typename Value, typename Discretization, typename Offset>
struct storage_category<characteristic_series<Value, Discretization, Offset> >
: storage_category<storage::characteristic_array<Value, Offset, storage::constant_elements<Value> > >
{};
/// INTERNAL ONLY
template<typename Value, typename Discretization, typename Offset>
struct discretization_type<characteristic_series<Value, Discretization, Offset> >
{
typedef Discretization type;
};
/// INTERNAL ONLY
template<typename Value, typename Discretization, typename Offset>
struct offset_type<characteristic_series<Value, Discretization, Offset> >
{
typedef Offset type;
};
/// INTERNAL ONLY
template<typename Value, typename Discretization, typename Offset>
struct generate_series<scaled_storage_tag<characteristic_storage_tag>, Value, Discretization, Offset>
{
typedef characteristic_series<Value, Discretization, Offset> type;
};
}
}}
namespace boost { namespace sequence { namespace impl
{
/// INTERNAL ONLY
template<typename Value, typename Discretization, typename Offset>
struct tag<time_series::characteristic_series<Value, Discretization, Offset> >
{
typedef time_series_tag type;
};
}}}
namespace boost { namespace constructors { namespace impl
{
/// INTERNAL ONLY
struct characteristic_series_tag;
/// INTERNAL ONLY
template<typename Value, typename Discretization, typename Offset>
struct tag<time_series::characteristic_series<Value, Discretization, Offset> >
{
typedef characteristic_series_tag type;
};
/// INTERNAL ONLY
template<typename Value, typename Discretization, typename Offset>
struct tag<time_series::characteristic_unit_series<Value, Discretization, Offset> >
{
typedef characteristic_series_tag type;
};
/// INTERNAL ONLY
template<typename T>
struct construct<T, characteristic_series_tag>
: arg_pack_construct
{
typedef parameter::parameters<
parameter::optional<time_series::tag::start>
, parameter::optional<time_series::tag::stop>
, parameter::optional<time_series::tag::value>
, parameter::optional<time_series::tag::discretization>
, parameter::optional<time_series::tag::zero>
> args_type;
};
}}}
#endif
| 36.527094 | 112 | 0.647876 | ericniebler |
736f9ea929f4c7a34fc14ce44795b6f68d63a91b | 2,526 | cc | C++ | quic/test_tools/simulator/alarm_factory.cc | swimfish09/quiche | 2bfc754a599cdbdb2a6875a515713648b92ddb97 | [
"BSD-3-Clause"
] | null | null | null | quic/test_tools/simulator/alarm_factory.cc | swimfish09/quiche | 2bfc754a599cdbdb2a6875a515713648b92ddb97 | [
"BSD-3-Clause"
] | null | null | null | quic/test_tools/simulator/alarm_factory.cc | swimfish09/quiche | 2bfc754a599cdbdb2a6875a515713648b92ddb97 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/third_party/quiche/src/quic/test_tools/simulator/alarm_factory.h"
#include "net/third_party/quiche/src/quic/core/quic_alarm.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_str_cat.h"
namespace quic {
namespace simulator {
// Alarm is an implementation of QuicAlarm which can schedule alarms in the
// simulation timeline.
class Alarm : public QuicAlarm {
public:
Alarm(Simulator* simulator,
QuicString name,
QuicArenaScopedPtr<QuicAlarm::Delegate> delegate)
: QuicAlarm(std::move(delegate)), adapter_(simulator, name, this) {}
~Alarm() override {}
void SetImpl() override {
DCHECK(deadline().IsInitialized());
adapter_.Set(deadline());
}
void CancelImpl() override { adapter_.Cancel(); }
private:
// An adapter class triggering a QuicAlarm using a simulation time system.
// An adapter is required here because neither Actor nor QuicAlarm are pure
// interfaces.
class Adapter : public Actor {
public:
Adapter(Simulator* simulator, QuicString name, Alarm* parent)
: Actor(simulator, name), parent_(parent) {}
~Adapter() override {}
void Set(QuicTime time) { Schedule(std::max(time, clock_->Now())); }
void Cancel() { Unschedule(); }
void Act() override {
DCHECK(clock_->Now() >= parent_->deadline());
parent_->Fire();
}
private:
Alarm* parent_;
};
Adapter adapter_;
};
AlarmFactory::AlarmFactory(Simulator* simulator, QuicString name)
: simulator_(simulator), name_(std::move(name)), counter_(0) {}
AlarmFactory::~AlarmFactory() {}
QuicString AlarmFactory::GetNewAlarmName() {
++counter_;
return QuicStringPrintf("%s (alarm %i)", name_.c_str(), counter_);
}
QuicAlarm* AlarmFactory::CreateAlarm(QuicAlarm::Delegate* delegate) {
return new Alarm(simulator_, GetNewAlarmName(),
QuicArenaScopedPtr<QuicAlarm::Delegate>(delegate));
}
QuicArenaScopedPtr<QuicAlarm> AlarmFactory::CreateAlarm(
QuicArenaScopedPtr<QuicAlarm::Delegate> delegate,
QuicConnectionArena* arena) {
if (arena != nullptr) {
return arena->New<Alarm>(simulator_, GetNewAlarmName(),
std::move(delegate));
}
return QuicArenaScopedPtr<QuicAlarm>(
new Alarm(simulator_, GetNewAlarmName(), std::move(delegate)));
}
} // namespace simulator
} // namespace quic
| 30.804878 | 79 | 0.696754 | swimfish09 |
737adecb189749033e3e3b42bb9a0ae95d706edf | 6,145 | cc | C++ | src/rtcrtpreceiver.cc | D1plo1d/node-webrtc | eb66ddfdcb6dd9c47d94844022a628ebcf3f79c3 | [
"Apache-2.0"
] | null | null | null | src/rtcrtpreceiver.cc | D1plo1d/node-webrtc | eb66ddfdcb6dd9c47d94844022a628ebcf3f79c3 | [
"Apache-2.0"
] | null | null | null | src/rtcrtpreceiver.cc | D1plo1d/node-webrtc | eb66ddfdcb6dd9c47d94844022a628ebcf3f79c3 | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2018 The node-webrtc project authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license that can be found
* in the LICENSE.md file in the root of the source tree. All contributing
* project authors may be found in the AUTHORS file in the root of the source
* tree.
*/
#include "src/rtcrtpreceiver.h"
#include <webrtc/api/rtpreceiverinterface.h> // IWYU pragma: keep
#include <webrtc/rtc_base/scoped_ref_ptr.h>
#include "src/error.h"
#include "src/converters/dictionaries.h" // IWYU pragma: keep
#include "src/mediastreamtrack.h" // IWYU pragma: keep
using node_webrtc::AsyncObjectWrap;
using node_webrtc::RTCRtpReceiver;
using v8::External;
using v8::Function;
using v8::FunctionTemplate;
using v8::Handle;
using v8::Local;
using v8::Object;
using v8::Value;
Nan::Persistent<Function>& RTCRtpReceiver::constructor() {
static Nan::Persistent<Function> constructor;
return constructor;
}
Nan::Persistent<FunctionTemplate>& RTCRtpReceiver::tpl() {
static Nan::Persistent<FunctionTemplate> tpl;
return tpl;
}
RTCRtpReceiver::RTCRtpReceiver(
std::shared_ptr<node_webrtc::PeerConnectionFactory>&& factory,
rtc::scoped_refptr<webrtc::RtpReceiverInterface>&& receiver)
: AsyncObjectWrap("RTCRtpReceiver")
, _factory(std::move(factory))
, _receiver(std::move(receiver)) {
}
RTCRtpReceiver::~RTCRtpReceiver() {
wrap()->Release(this);
}
NAN_METHOD(RTCRtpReceiver::New) {
if (info.Length() != 2 || !info[0]->IsExternal() || !info[1]->IsExternal()) {
return Nan::ThrowTypeError("You cannot construct a RTCRtpReceiver");
}
auto factory = *static_cast<std::shared_ptr<node_webrtc::PeerConnectionFactory>*>(Local<External>::Cast(info[0])->Value());
auto receiver = *static_cast<rtc::scoped_refptr<webrtc::RtpReceiverInterface>*>(Local<External>::Cast(info[1])->Value());
auto obj = new RTCRtpReceiver(std::move(factory), std::move(receiver));
obj->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
NAN_GETTER(RTCRtpReceiver::GetTrack) {
(void) property;
auto self = AsyncObjectWrap::Unwrap<RTCRtpReceiver>(info.Holder());
auto track = MediaStreamTrack::wrap()->GetOrCreate(self->_factory, self->_receiver->track());
info.GetReturnValue().Set(track->ToObject());
}
NAN_GETTER(RTCRtpReceiver::GetTransport) {
(void) property;
info.GetReturnValue().Set(Nan::Null());
}
NAN_GETTER(RTCRtpReceiver::GetRtcpTransport) {
(void) property;
info.GetReturnValue().Set(Nan::Null());
}
NAN_METHOD(RTCRtpReceiver::GetCapabilities) {
(void) info;
Nan::ThrowError("Not yet implemented; file a feature request against node-webrtc");
}
NAN_METHOD(RTCRtpReceiver::GetParameters) {
auto self = AsyncObjectWrap::Unwrap<RTCRtpReceiver>(info.Holder());
auto parameters = self->_receiver->GetParameters();
CONVERT_OR_THROW_AND_RETURN(parameters, result, Local<Value>);
info.GetReturnValue().Set(result);
}
NAN_METHOD(RTCRtpReceiver::GetContributingSources) {
auto self = AsyncObjectWrap::Unwrap<RTCRtpReceiver>(info.Holder());
auto contributingSources = std::vector<webrtc::RtpSource>();
auto sources = self->_receiver->GetSources();
for (auto source : sources) {
if (source.source_type() == webrtc::RtpSourceType::CSRC) {
contributingSources.push_back(source);
}
}
CONVERT_OR_THROW_AND_RETURN(contributingSources, result, Local<Value>);
info.GetReturnValue().Set(result);
}
NAN_METHOD(RTCRtpReceiver::GetSynchronizationSources) {
auto self = AsyncObjectWrap::Unwrap<RTCRtpReceiver>(info.Holder());
auto synchronizationSources = std::vector<webrtc::RtpSource>();
auto sources = self->_receiver->GetSources();
for (auto source : sources) {
if (source.source_type() == webrtc::RtpSourceType::SSRC) {
synchronizationSources.push_back(source);
}
}
CONVERT_OR_THROW_AND_RETURN(synchronizationSources, result, Local<Value>);
info.GetReturnValue().Set(result);
}
NAN_METHOD(RTCRtpReceiver::GetStats) {
auto resolver = v8::Promise::Resolver::New(Nan::GetCurrentContext()).ToLocalChecked();
resolver->Reject(Nan::GetCurrentContext(), Nan::Error("Not yet implemented; file a feature request against node-webrtc")).IsNothing();
info.GetReturnValue().Set(resolver->GetPromise());
}
node_webrtc::Wrap <
RTCRtpReceiver*,
rtc::scoped_refptr<webrtc::RtpReceiverInterface>,
std::shared_ptr<node_webrtc::PeerConnectionFactory>
> * RTCRtpReceiver::wrap() {
static auto wrap = new node_webrtc::Wrap <
RTCRtpReceiver*,
rtc::scoped_refptr<webrtc::RtpReceiverInterface>,
std::shared_ptr<node_webrtc::PeerConnectionFactory>
> (RTCRtpReceiver::Create);
return wrap;
}
RTCRtpReceiver* RTCRtpReceiver::Create(
std::shared_ptr<node_webrtc::PeerConnectionFactory> factory,
rtc::scoped_refptr<webrtc::RtpReceiverInterface> receiver) {
Nan::HandleScope scope;
Local<Value> cargv[2];
cargv[0] = Nan::New<External>(static_cast<void*>(&factory));
cargv[1] = Nan::New<External>(static_cast<void*>(&receiver));
auto value = Nan::NewInstance(Nan::New(RTCRtpReceiver::constructor()), 2, cargv).ToLocalChecked();
return RTCRtpReceiver::Unwrap(value);
}
void RTCRtpReceiver::Init(Handle<Object> exports) {
Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);
RTCRtpReceiver::tpl().Reset(tpl);
tpl->SetClassName(Nan::New("RTCRtpReceiver").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetAccessor(tpl->InstanceTemplate(), Nan::New("track").ToLocalChecked(), GetTrack, nullptr);
Nan::SetAccessor(tpl->InstanceTemplate(), Nan::New("transport").ToLocalChecked(), GetTransport, nullptr);
Nan::SetAccessor(tpl->InstanceTemplate(), Nan::New("rtcpTransport").ToLocalChecked(), GetRtcpTransport, nullptr);
Nan::SetMethod(tpl, "getCapabilities", GetCapabilities);
Nan::SetPrototypeMethod(tpl, "getParameters", GetParameters);
Nan::SetPrototypeMethod(tpl, "getContributingSources", GetContributingSources);
Nan::SetPrototypeMethod(tpl, "getSynchronizationSources", GetSynchronizationSources);
constructor().Reset(tpl->GetFunction());
exports->Set(Nan::New("RTCRtpReceiver").ToLocalChecked(), tpl->GetFunction());
}
| 37.699387 | 136 | 0.74288 | D1plo1d |
737dbd7206a5d23be062bdc8aa58ddef44c6b67d | 1,465 | cpp | C++ | convexHull.cpp | singhkeshav510/DSA-Practice | 3d0eb2137d061c8b4fcba988c46cd7817dfb7fc7 | [
"MIT"
] | null | null | null | convexHull.cpp | singhkeshav510/DSA-Practice | 3d0eb2137d061c8b4fcba988c46cd7817dfb7fc7 | [
"MIT"
] | null | null | null | convexHull.cpp | singhkeshav510/DSA-Practice | 3d0eb2137d061c8b4fcba988c46cd7817dfb7fc7 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
class Point{
public:
int x;
int y;
Point(int x,int y){
this->x=x;
this->y=y;
}
};
Point po;
void swap(Point &p1, Point &p2){
Point temp = p1;
p1 = p2;
p2 = temp;
}
int distSq(Point p1, Point p2){
return (p1.x - p2.x)*(p1.x - p2.x) +
(p1.y - p2.y)*(p1.y - p2.y);
}
int orientation(Point p, Point q, Point r){
int val = (q.y - p.y) * (r.x - q.x) -
(q.x - p.x) * (r.y - q.y);
if (val == 0) return 0;
return (val > 0)? 1: 2;
}
int cmp(const void *vp1, const void *vp2){
Point *p1 = (Point *)vp1;
Point *p2 = (Point *)vp2;
int o = orientation(p0, *p1, *p2);
if (o == 0)
return (distSq(p0, *p2) >= distSq(p0, *p1))? -1 : 1;
return (o == 2)? -1: 1;
}
int main(){
int n,a,b;
cin>>n;
vector<Point> point;
for(int i=0;i<n;i++){
cin>>a>>b;
point.push_back(make_pair(a,b));
}
//minimum y point
Point min(INT_MAX,INT_MAX);
for(int i=0;i<point.size();i++){
if(point[min].y>point[i].y){
if(point[min].x>point[i].x){
min=i;
}
}
}
swap(point[0],point[min]);
po=point[0];
//sorting point on basis of angle
qsort(point[1],n-1,sizeof(Point),cmp);
int m=1;
for(int i=1;i<n-1;i++){
while(i<n-1&&orientation(po,point[i],point[i+1])==0){
i++;
}
point[m]=point[i];
m++;
}
if(m<3) return;
stack<Point> s;
s.push(point[0]);
s.push(point[1]);
s.push(point[2]);
for(int i=3;i<m;i++){
while(orientation(
}
| 19.797297 | 58 | 0.533106 | singhkeshav510 |
737ef3d0d9f0d15a03eb5340d9ff722f30878f93 | 2,481 | hpp | C++ | LED_anima.hpp | sethome2/LED_anima | 3250659ebdbf3be411d6cf63ea2f6c903a500d2d | [
"MIT"
] | 2 | 2021-09-24T17:34:40.000Z | 2021-12-29T23:58:00.000Z | LED_anima.hpp | sethome2/LED_anima | 3250659ebdbf3be411d6cf63ea2f6c903a500d2d | [
"MIT"
] | null | null | null | LED_anima.hpp | sethome2/LED_anima | 3250659ebdbf3be411d6cf63ea2f6c903a500d2d | [
"MIT"
] | null | null | null | /*
* @Author: sethome
* @Description: In User Settings Edit
* @FilePath: \LED_anima\LED_anima.hpp
*/
/*
MIT License
Copyright (c) 2021 sethome
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.
*/
//Data:2020/09/01
//Author:sethome or say sethome2
//Function:Control strip LED color and anima library
//功能:控制条状LED带的色彩以及动画
//PS:It doesn't include code for MCU to directly control LED.
// You need to call a function to read the color data of the current RGB frame
// and send to the LED strip
//PS:不包含MCU直接控制LED的代码
// 您需要调用函数去读出RGB当前帧的颜色数据
// 发送给LED灯带
//C++ library
#include "vector"
#include "map"
//LED_anima Core library
#include "area.hpp"
//Third party library
//#include "bezier.h"
#include "3dr_part./jsonxx/json.hpp"
#ifndef __LED_anima__
#define __LED_anima__
namespace LED_anima
{
template <uint16_t LED_NUM>
class areaManage
{
private:
std::map<std::string, area *> areaList;
public:
RGB_info LEDs[LED_NUM];
public:
areaManage() {} //do not things
~areaManage()
{
}
void bindArgv(std::string argv_json)
{
jsonxx::json areaListData = jsonxx::json::parse(argv_json);
for(auto iter : areaListData)
addArea(iter.key(),iter.value().as_string());
}
void addArea(std::string name, std::string argv)
{
areaList.insert(std::make_pair(name, new area(&LEDs[0], argv)));
}
void update()
{
for (auto iter : areaList)
iter.second->update();
}
};
}
#endif
//end of file
| 25.316327 | 80 | 0.720274 | sethome2 |
73845f1f677dbe869f72cfe74ff10f1d70fa9792 | 651 | cpp | C++ | LeetCode_C++/605_canPlaceFlowers/test.cpp | Yiluhuakai22/algorigthm-study | 084ca94342020e4333045c136886eef0292e4eae | [
"MIT"
] | null | null | null | LeetCode_C++/605_canPlaceFlowers/test.cpp | Yiluhuakai22/algorigthm-study | 084ca94342020e4333045c136886eef0292e4eae | [
"MIT"
] | null | null | null | LeetCode_C++/605_canPlaceFlowers/test.cpp | Yiluhuakai22/algorigthm-study | 084ca94342020e4333045c136886eef0292e4eae | [
"MIT"
] | null | null | null | #include <limits.h>
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include <cstdlib>
#include <iostream>
#include <string>
#include "solution.h"
using ::testing::_;
using ::testing::AtLeast;
using ::testing::Exactly;
using ::testing::Return;
using namespace testing;
using namespace std;
TEST(TEST, TEST)
{
Solution obj;
std::vector<int> flowerbed{0};
EXPECT_EQ(true, obj.canPlaceFlowers(flowerbed,1));
std::vector<int> flowerbed2{0,0};
EXPECT_EQ(true, obj.canPlaceFlowers(flowerbed2,1));
std::vector<int> flowerbed3{0,0,0,1,0,1,0,0,1,0,0,0,0,0,0,0,1,0};
EXPECT_EQ(true, obj.canPlaceFlowers(flowerbed3,4));
}
| 21.7 | 69 | 0.689708 | Yiluhuakai22 |
73849bebaafdbb09f8e340364ca00152cb717840 | 8,009 | hpp | C++ | HotSpot1.7-JVM-Linux-x86/src/share/vm/gc_implementation/parallelScavenge/psCompactionManager.hpp | codefollower/Open-Source-Research | b9f2aed9d0f060b80be45f713c3d48fe91f247b2 | [
"Apache-2.0"
] | 184 | 2015-01-04T03:38:20.000Z | 2022-03-30T05:47:21.000Z | HotSpot1.7/src/share/vm/gc_implementation/parallelScavenge/psCompactionManager.hpp | doczyw/Open-Source-Research | b9f2aed9d0f060b80be45f713c3d48fe91f247b2 | [
"Apache-2.0"
] | 1 | 2016-01-17T09:18:17.000Z | 2016-01-17T09:18:17.000Z | HotSpot1.7/src/share/vm/gc_implementation/parallelScavenge/psCompactionManager.hpp | doczyw/Open-Source-Research | b9f2aed9d0f060b80be45f713c3d48fe91f247b2 | [
"Apache-2.0"
] | 101 | 2015-01-16T23:46:31.000Z | 2022-03-30T05:47:06.000Z | /*
* Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#ifndef SHARE_VM_GC_IMPLEMENTATION_PARALLELSCAVENGE_PSCOMPACTIONMANAGER_HPP
#define SHARE_VM_GC_IMPLEMENTATION_PARALLELSCAVENGE_PSCOMPACTIONMANAGER_HPP
#include "memory/allocation.hpp"
#include "utilities/stack.hpp"
#include "utilities/taskqueue.hpp"
// Move to some global location
#define HAS_BEEN_MOVED 0x1501d01d
// End move to some global location
class MutableSpace;
class PSOldGen;
class ParCompactionManager;
class ObjectStartArray;
class ParallelCompactData;
class ParMarkBitMap;
class ParCompactionManager : public CHeapObj<mtGC> {
friend class ParallelTaskTerminator;
friend class ParMarkBitMap;
friend class PSParallelCompact;
friend class StealRegionCompactionTask;
friend class UpdateAndFillClosure;
friend class RefProcTaskExecutor;
friend class IdleGCTask;
public:
// ------------------------ Don't putback if not needed
// Actions that the compaction manager should take.
enum Action {
Update,
Copy,
UpdateAndCopy,
CopyAndUpdate,
NotValid
};
// ------------------------ End don't putback if not needed
private:
// 32-bit: 4K * 8 = 32KiB; 64-bit: 8K * 16 = 128KiB
#define QUEUE_SIZE (1 << NOT_LP64(12) LP64_ONLY(13))
typedef OverflowTaskQueue<ObjArrayTask, mtGC, QUEUE_SIZE> ObjArrayTaskQueue;
typedef GenericTaskQueueSet<ObjArrayTaskQueue, mtGC> ObjArrayTaskQueueSet;
#undef QUEUE_SIZE
static ParCompactionManager** _manager_array;
static OopTaskQueueSet* _stack_array;
static ObjArrayTaskQueueSet* _objarray_queues;
static ObjectStartArray* _start_array;
static RegionTaskQueueSet* _region_array;
static PSOldGen* _old_gen;
private:
OverflowTaskQueue<oop, mtGC> _marking_stack;
ObjArrayTaskQueue _objarray_stack;
// Is there a way to reuse the _marking_stack for the
// saving empty regions? For now just create a different
// type of TaskQueue.
RegionTaskQueue* _region_stack;
static RegionTaskQueue** _region_list;
// Index in _region_list for current _region_stack.
uint _region_stack_index;
// Indexes of recycled region stacks/overflow stacks
// Stacks of regions to be compacted are embedded in the tasks doing
// the compaction. A thread that executes the task extracts the
// region stack and drains it. These threads keep these region
// stacks for use during compaction task stealing. If a thread
// gets a second draining task, it pushed its current region stack
// index into the array _recycled_stack_index and gets a new
// region stack from the task. A thread that is executing a
// compaction stealing task without ever having executing a
// draining task, will get a region stack from _recycled_stack_index.
//
// Array of indexes into the array of region stacks.
static uint* _recycled_stack_index;
// The index into _recycled_stack_index of the last region stack index
// pushed. If -1, there are no entries into _recycled_stack_index.
static int _recycled_top;
// The index into _recycled_stack_index of the last region stack index
// popped. If -1, there has not been any entry popped.
static int _recycled_bottom;
Stack<Klass*, mtGC> _revisit_klass_stack;
Stack<DataLayout*, mtGC> _revisit_mdo_stack;
static ParMarkBitMap* _mark_bitmap;
Action _action;
static PSOldGen* old_gen() { return _old_gen; }
static ObjectStartArray* start_array() { return _start_array; }
static OopTaskQueueSet* stack_array() { return _stack_array; }
static void initialize(ParMarkBitMap* mbm);
protected:
// Array of tasks. Needed by the ParallelTaskTerminator.
static RegionTaskQueueSet* region_array() { return _region_array; }
OverflowTaskQueue<oop, mtGC>* marking_stack() { return &_marking_stack; }
// Pushes onto the marking stack. If the marking stack is full,
// pushes onto the overflow stack.
void stack_push(oop obj);
// Do not implement an equivalent stack_pop. Deal with the
// marking stack and overflow stack directly.
public:
Action action() { return _action; }
void set_action(Action v) { _action = v; }
RegionTaskQueue* region_stack() { return _region_stack; }
void set_region_stack(RegionTaskQueue* v) { _region_stack = v; }
inline static ParCompactionManager* manager_array(int index);
inline static RegionTaskQueue* region_list(int index) {
return _region_list[index];
}
uint region_stack_index() { return _region_stack_index; }
void set_region_stack_index(uint v) { _region_stack_index = v; }
// Pop and push unique reusable stack index
static int pop_recycled_stack_index();
static void push_recycled_stack_index(uint v);
static void reset_recycled_stack_index() {
_recycled_bottom = _recycled_top = -1;
}
ParCompactionManager();
~ParCompactionManager();
// Pushes onto the region stack at the given index. If the
// region stack is full,
// pushes onto the region overflow stack.
static void region_list_push(uint stack_index, size_t region_index);
static void verify_region_list_empty(uint stack_index);
ParMarkBitMap* mark_bitmap() { return _mark_bitmap; }
// Take actions in preparation for a compaction.
static void reset();
// void drain_stacks();
bool should_update();
bool should_copy();
Stack<Klass*, mtGC>* revisit_klass_stack() { return &_revisit_klass_stack; }
Stack<DataLayout*, mtGC>* revisit_mdo_stack() { return &_revisit_mdo_stack; }
// Save for later processing. Must not fail.
inline void push(oop obj) { _marking_stack.push(obj); }
inline void push_objarray(oop objarray, size_t index);
inline void push_region(size_t index);
// Access function for compaction managers
static ParCompactionManager* gc_thread_compaction_manager(int index);
static bool steal(int queue_num, int* seed, oop& t) {
return stack_array()->steal(queue_num, seed, t);
}
static bool steal_objarray(int queue_num, int* seed, ObjArrayTask& t) {
return _objarray_queues->steal(queue_num, seed, t);
}
static bool steal(int queue_num, int* seed, size_t& region) {
return region_array()->steal(queue_num, seed, region);
}
// Process tasks remaining on any marking stack
void follow_marking_stacks();
inline bool marking_stacks_empty() const;
// Process tasks remaining on any stack
void drain_region_stacks();
};
inline ParCompactionManager* ParCompactionManager::manager_array(int index) {
assert(_manager_array != NULL, "access of NULL manager_array");
assert(index >= 0 && index <= (int)ParallelGCThreads,
"out of range manager_array access");
return _manager_array[index];
}
bool ParCompactionManager::marking_stacks_empty() const {
return _marking_stack.is_empty() && _objarray_stack.is_empty();
}
#endif // SHARE_VM_GC_IMPLEMENTATION_PARALLELSCAVENGE_PSCOMPACTIONMANAGER_HPP
| 36.076577 | 82 | 0.734049 | codefollower |
73863b3f01793831b768e0314b32def426edf6a0 | 161,331 | cpp | C++ | GameServer/Source/ChaosBox.cpp | sp3cialk/MU-S8EP2-Repack | 202856a74c905c203b9b2795fd161f564ca8b257 | [
"MIT"
] | 10 | 2019-04-09T23:36:43.000Z | 2022-02-10T19:20:52.000Z | GameServer/Source/ChaosBox.cpp | microvn/mu-s8ep2-repack | 202856a74c905c203b9b2795fd161f564ca8b257 | [
"MIT"
] | 1 | 2019-09-25T17:12:36.000Z | 2019-09-25T17:12:36.000Z | GameServer/Source/ChaosBox.cpp | microvn/mu-s8ep2-repack | 202856a74c905c203b9b2795fd161f564ca8b257 | [
"MIT"
] | 9 | 2019-09-25T17:12:57.000Z | 2021-08-18T01:21:25.000Z | #include "stdafx.h"
#include "ChaosBox.h"
#include "logproc.h"
#include "GameMain.h"
#include "GameServer.h"
#include "..\common\winutil.h"
#include "DSProtocol.h"
#include "CastleSiegeSync.h"
#include "BloodCastle.h"
#include "..\common\SetItemOption.h"
#include "JewelOfHarmonySystem.h"
#include "giocp.h"
#include "CrywolfSync.h"
#include "CashLotterySystem.h"
#include "CastleSiege.h"
#include "IllusionTempleEvent.h"
#include "Event.h"
#include "ElementalSystem.h"
#include "EventItemBag.h"
#if( __4GAMERS__ == 1 )
#include "Achievements.h"
#endif
CChaosBox g_ChaosBox;
// Constructor / Destructor
CChaosBox::CChaosBox()
{
iChaosJewel = ITEMGET(12,15);
iBlessJewel = ITEMGET(14,13);
iSoulJewel = ITEMGET(14,14);
iCreationJewel = ITEMGET(14,22);
iBlessPack = ITEMGET(12,30);
iSoulPack = ITEMGET(12,31);
iCondorFeather = ITEMGET(13,53);
iCondorStone = ITEMGET(13,52);
iStormWings = ITEMGET(12,36);
iRedemptionWings = ITEMGET(12,37);
iFortitudeWings = ITEMGET(12,38);
iHurricaneWings = ITEMGET(12,39);
iMonarchMantle = ITEMGET(12,40);
iDimensionWings = ITEMGET(12,43);
iRFCape2 = ITEMGET(12,50);
iOptionRate = 50;
}
CChaosBox::~CChaosBox()
{
}
BOOL CChaosBox::ChaosBoxCheck(LPOBJ lpObj)
{
if ( lpObj->pChaosBox == NULL )
{
return false;
}
return true;
}
BOOL CChaosBox::ChaosBoxInit(LPOBJ lpObj)
{
int n;
if ( lpObj->pChaosBox != NULL )
{
for (n=0;n<CHAOS_BOX_SIZE;n++)
{
g_ElementalSystem.ClearErtel(lpObj,&lpObj->pChaosBox[n]);
lpObj->pChaosBox[n].Clear();
}
for (n=0;n<CHAOS_BOX_SIZE;n++)
{
lpObj->pChaosBoxMap[n] = -1;
}
return true;
}
lpObj->pChaosBox = new CItem[CHAOS_BOX_SIZE];
if ( lpObj->pChaosBox == NULL )
{
return false;
}
lpObj->pChaosBoxMap = new unsigned char[CHAOS_BOX_SIZE];
if ( lpObj->pChaosBoxMap == NULL )
{
delete lpObj->pChaosBox;
return false;
}
for (n=0;n<CHAOS_BOX_SIZE;n++)
{
lpObj->pChaosBoxMap[n] = -1;
}
return true;
}
BOOL CChaosBox::ChaosBoxItemDown(LPOBJ lpObj)
{
if ( lpObj->pChaosBox == NULL )
{
return FALSE;
}
for (int n=0;n<CHAOS_BOX_SIZE;n++)
{
if ( lpObj->pChaosBox[n].m_Type == ITEMGET(12,15) ||
lpObj->pChaosBox[n].m_Type == ITEMGET(14,13) ||
lpObj->pChaosBox[n].m_Type == ITEMGET(14,14) ||
lpObj->pChaosBox[n].m_Type == ITEMGET(13,83) ||
lpObj->pChaosBox[n].m_Type == ITEMGET(13,84) ||
lpObj->pChaosBox[n].m_Type == ITEMGET(13,85) ||
lpObj->pChaosBox[n].m_Type == ITEMGET(13,86) ||
lpObj->pChaosBox[n].m_Type == ITEMGET(13,87) ||
lpObj->pChaosBox[n].m_Type == ITEMGET(13,88) ||
lpObj->pChaosBox[n].m_Type == ITEMGET(13,89) ||
lpObj->pChaosBox[n].m_Type == ITEMGET(13,90) ||
lpObj->pChaosBox[n].m_Type == ITEMGET(13,91) ||
lpObj->pChaosBox[n].m_Type == ITEMGET(13,92) ||
lpObj->pChaosBox[n].m_Type == ITEMGET(14,53) )
{
lpObj->pChaosBox[n].Clear();
}
else
{
int op = lpObj->pChaosBox[n].m_Option1;
if ( op > 0 )
{
if ( (rand() % 2) == 0 )
{
op--;
}
}
lpObj->pChaosBox[n].m_Option1 = op;
op = lpObj->pChaosBox[n].m_Option3;
if ( op > 0 )
{
if ( (rand() % 2) == 0 )
{
op--;
}
}
lpObj->pChaosBox[n].m_Option3 = op;
if ( lpObj->pChaosBox[n].m_Level > 0 )
{
lpObj->pChaosBox[n].m_Level = rand() % lpObj->pChaosBox[n].m_Level;
}
float dur = (float)ItemGetDurability(lpObj->pChaosBox[n].m_Type, lpObj->pChaosBox[n].m_Level, lpObj->pChaosBox[n].IsExtItem(), lpObj->pChaosBox[n].IsSetItem() );
lpObj->pChaosBox[n].m_Durability = dur * lpObj->pChaosBox[n].m_Durability / lpObj->pChaosBox[n].m_BaseDurability;
lpObj->pChaosBox[n].Convert(lpObj->pChaosBox[n].m_Type, lpObj->pChaosBox[n].m_Option1,
lpObj->pChaosBox[n].m_Option2, lpObj->pChaosBox[n].m_Option3, lpObj->pChaosBox[n].m_NewOption,
lpObj->pChaosBox[n].m_SetOption, lpObj->pChaosBox[n].m_ItemOptionEx, 0, -1, CURRENT_DB_VERSION);
}
}
return TRUE;
}
int CChaosBox::ChaosBoxMix(LPOBJ lpObj, int & Result2,int & Result3)
{
BYTE ExOption[8];
int ChaosDiamond = 0;
int ChaosItems = 0;
if ( lpObj->pChaosBox == NULL )
{
return 0;
}
int value = 0;
int add = 0;
int nv = 0; // NEW VALUE
Result2 = 0;
Result3 = -1;
int tmpItem = -1;
lpObj->ChaosSuccessRate = 0;
lpObj->ChaosMoney = 0;
int iCharmOfLuckCount = 0;
for ( int n=0;n<CHAOS_BOX_SIZE;n++)
{
if ( lpObj->pChaosBox[n].IsItem() == TRUE )
{
lpObj->pChaosBox[n].OldValue();
add = 0;
nv = 0;
if ( lpObj->pChaosBox[n].m_Level >= MIN_CHAOS_ITEM_LEVEL && (lpObj->pChaosBox[n].m_Option3 *4) >= MIN_CHAOS_ITEM_LEVEL )
{
nv = lpObj->pChaosBox[n].m_OldBuyMoney;
value += lpObj->pChaosBox[n].m_OldBuyMoney;
add = 1;
if ( lpObj->pChaosBox[n].m_Type == ITEMGET(2,6) || lpObj->pChaosBox[n].m_Type == ITEMGET(4,6) || lpObj->pChaosBox[n].m_Type == ITEMGET(5,7) ) // Chaos Items
{
Result2 = 1;
}
}
if ( lpObj->pChaosBox[n].m_Type == ITEMGET(12,15) )
{
value += lpObj->pChaosBox[n].m_OldBuyMoney;
nv = lpObj->pChaosBox[n].m_OldBuyMoney;
ChaosDiamond++;
add = 1;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,13) || lpObj->pChaosBox[n].m_Type == ITEMGET(14,14) ) // Jewel of Bless, Jewel of Soul
{
value += lpObj->pChaosBox[n].m_OldBuyMoney;
nv = lpObj->pChaosBox[n].m_OldBuyMoney;
add = 1;
}
if( lpObj->pChaosBox[n].m_Type == ITEMGET(13,83) ||
lpObj->pChaosBox[n].m_Type == ITEMGET(13,84) ||
lpObj->pChaosBox[n].m_Type == ITEMGET(13,85) ||
lpObj->pChaosBox[n].m_Type == ITEMGET(13,86) ||
lpObj->pChaosBox[n].m_Type == ITEMGET(13,87) )
{
tmpItem = lpObj->pChaosBox[n].m_Type;
}
if( lpObj->pChaosBox[n].m_Type == ITEMGET(13,14) )
{
return false;
}
if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,53) ) // Charm Of Luck
{
iCharmOfLuckCount += (int)lpObj->pChaosBox[n].m_Durability;
}
if ( add != 0 )
{
ChaosItems++;
}
ItemIsBufExOption(ExOption, &lpObj->pChaosBox[n]);
LogAdd("[%s][%s] CBMix [%d,%s,%d,%d,%d,%d]serial:[%u][%d][%d] Ex:[%d,%d,%d,%d,%d,%d,%d]",
lpObj->AccountID, lpObj->Name, n, lpObj->pChaosBox[n].GetName(),
lpObj->pChaosBox[n].m_Level, lpObj->pChaosBox[n].m_Option1,
lpObj->pChaosBox[n].m_Option2, lpObj->pChaosBox[n].m_Option3,
lpObj->pChaosBox[n].m_Number, (int)lpObj->pChaosBox[n].m_Durability,
nv, ExOption[0], ExOption[1], ExOption[2], ExOption[3], ExOption[4], ExOption[5],
ExOption[6], lpObj->pChaosBox[n].m_SetOption);
}
}
if ( ChaosDiamond == 0 )
{
value = 0; // 0% of success
}
if ( ChaosItems < 2 )
{
value = 0;// 0% of success
}
if ( iCharmOfLuckCount > 10 )
return FALSE;
lpObj->ChaosSuccessRate = value / 10000;
lpObj->ChaosSuccessRate += iCharmOfLuckCount;
if ( lpObj->ChaosSuccessRate > 100 )
{
lpObj->ChaosSuccessRate = 100;
}
lpObj->ChaosMoney = lpObj->ChaosSuccessRate * 10000; // Required Money to MIX anc createe a Chaos Item
LogAddTD("[%s][%s] CBMix need Zen : %d SuccessRate : %d, CharmRate : %d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosMoney,
lpObj->ChaosSuccessRate, iCharmOfLuckCount);
if( tmpItem > -1 )
{
int Number = tmpItem^ITEMGET(13,00);
switch( Number )
{
case 83:
Result3 = 2;
break;
case 84:
Result3 = 1;
break;
case 85:
Result3 = 0;
break;
case 86:
Result3 = 41;
break;
case 87:
Result3 = 40;
break;
default:
LogAddTD("[MixSystem] WingCharmItemNum => %d , WingCharmIndex => %d",tmpItem,Number);
break;
}
}
return value;
}
void CChaosBox::DefaultChaosMix(LPOBJ lpObj)
{
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
int aIndex = lpObj->m_Index;
BOOL fail = TRUE;
int MixResult2;
lpObj->ChaosLock = TRUE;
int MixResult3 = -1;
if ( ChaosBoxMix(lpObj, MixResult2, MixResult3) == 0 )
{
pMsg.Result = CB_INCORRECT_MIX_ITEMS;
DataSend(aIndex, (BYTE *)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
int iChaosTaxMoney = (int)((__int64)lpObj->ChaosMoney * (__int64)g_CastleSiegeSync.GetTaxRateChaos(lpObj->m_Index) / (__int64)100);
if ( iChaosTaxMoney < 0 )
{
iChaosTaxMoney = 0;
}
lpObj->ChaosMoney += iChaosTaxMoney;
if ( lpObj->ChaosMoney < 0 )
{
lpObj->ChaosMoney = 0;
}
if ( lpObj->Money < lpObj->ChaosMoney )
{
pMsg.Result = CB_NOT_ENOUGH_ZEN;
DataSend(aIndex, (BYTE *)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
}
else
{
if ( lpObj->ChaosSuccessRate > 0 )
{
if ( lpObj->ChaosSuccessRate >= 100 )
{
lpObj->ChaosSuccessRate = 100;
}
if ( (rand()%100) <= (lpObj->ChaosSuccessRate-1) )
{
fail = FALSE;
pMsg.Result = CB_SUCCESS;
int Level = rand()%5;
int Option1 = 0;
int Option2 = 0;
int Option3 = 0;
if ( (rand()%100)< (lpObj->ChaosSuccessRate/5 + 6) )
{
Option1 = 1;
}
if ( (rand()%100)< (lpObj->ChaosSuccessRate/5 + 4) )
{
Option2 = 1;
}
int OpProb;
int OpType = rand()%3;
OpProb = rand()%100;
switch ( OpType )
{
case 0:
if ( OpProb < (lpObj->ChaosSuccessRate / 5 + 4) )
{
Option3 = 3;
}
break;
case 1:
if ( OpProb < (lpObj->ChaosSuccessRate / 5 + 8) )
{
Option3 = 2;
}
break;
case 2:
if ( OpProb < (lpObj->ChaosSuccessRate / 5 + 12) )
{
Option3 = 1;
}
break;
}
if ( MixResult2 == TRUE )
{
int WingType = rand()%4;
int WingNum = 0;
if ( MixResult3 > -1 )
{
WingNum = ITEMGET(12,00) + MixResult3;
}
else
{
if ( WingType == 0 )
{
WingNum = ITEMGET(12,0);
}
else if ( WingType == 1 )
{
WingNum = ITEMGET(12,1);
}
else if ( WingType == 2 )
{
WingNum = ITEMGET(12,2);
}
else if ( WingType == 3 )
{
WingNum = ITEMGET(12,41);
}
}
::ItemSerialCreateSend(lpObj->m_Index, -1, 0, 0, WingNum, 0, 255, Option1, Option2, Option3, -1, 0, 0);
}
else
{
int ChaosItemType = rand()%3;
int ChaosItemNum = 0;
if ( ChaosItemType == 0 ) // Chaos Dragon Axe
{
ChaosItemNum = ITEMGET(2,6);
}
else if ( ChaosItemType == 1 ) // Chaos Nature Bow
{
ChaosItemNum = ITEMGET(4,6);
}
else if ( ChaosItemType == 2 ) // Chaos Lighting Staff
{
ChaosItemNum = ITEMGET(5,7);
}
::ItemSerialCreateSend(lpObj->m_Index, -1, 0, 0, ChaosItemNum, Level, 255, Option1, Option2, Option3, -1, 0, 0);
}
}
}
lpObj->Money -= lpObj->ChaosMoney;
g_CastleSiegeSync.AddTributeMoney(iChaosTaxMoney);
GCMoneySend(lpObj->m_Index, lpObj->Money);
if ( fail == TRUE )
{
ChaosBoxItemDown(lpObj);
GCUserChaosBoxSend(lpObj, 0);
DataSend(aIndex, (BYTE*)&pMsg, pMsg.h.size);
LogAddTD("[%s][%s] CBMix Fail %d Money : %d-%d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate,
lpObj->Money, lpObj->ChaosMoney);
lpObj->ChaosLock = FALSE;
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, false);
#endif
}
else
{
LogAddTD("[%s][%s] CBMix Success Rate:%d Money : %d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate,
lpObj->ChaosMoney);
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, true);
#endif
}
}
::gObjInventoryCommit(lpObj->m_Index);
}
void CChaosBox::LogDQChaosItem(LPOBJ lpObj)
{
BYTE ExOption[MAX_EXOPTION_SIZE];
for ( int n=0;n<CHAOS_BOX_SIZE;n++)
{
if ( lpObj->pChaosBox[n].IsItem() == TRUE )
{
::ItemIsBufExOption(ExOption, &lpObj->pChaosBox[n] );
LogAddTD("[DevilSquare,%d] [%s][%s] CBMix [%d,%s,%d,%d,%d,%d]serial:[%d][%d] Ex:[%d,%d,%d,%d,%d,%d,%d] Set:[%d] 380Ex[%d] HO:[%d,%d]",
lpObj->pChaosBox[n].m_Level,
lpObj->AccountID, lpObj->Name, n, lpObj->pChaosBox[n].GetName(), lpObj->pChaosBox[n].m_Level,
lpObj->pChaosBox[n].m_Option1, lpObj->pChaosBox[n].m_Option2, lpObj->pChaosBox[n].m_Option3,
lpObj->pChaosBox[n].m_Number, (int)lpObj->pChaosBox[n].m_Durability,
ExOption[0], ExOption[1], ExOption[2], ExOption[3], ExOption[4], ExOption[5], ExOption[6],
lpObj->pChaosBox[n].m_SetOption, lpObj->pChaosBox[n].m_ItemOptionEx >> 7,
g_kJewelOfHarmonySystem.GetItemStrengthenOption(&lpObj->pChaosBox[n]),
g_kJewelOfHarmonySystem.GetItemOptionLevel(&lpObj->pChaosBox[n]));
}
}
}
int CChaosBox::CheckDevilSquareItem(LPOBJ lpObj, int & eventitemcount, int & itemlevel)
{
BOOL bChaoseGem = FALSE;
BOOL bEyeOfDevil = FALSE;
BOOL bKeyOfDevil = FALSE;
eventitemcount = 0;
BOOL FoundOtherItem = FALSE;
int level = -1;
BOOL bLevelCheck = FALSE;
int iCharmOfLuckCount = 0;
BOOL bCharmOfLuckOver = FALSE;
LogAdd("[DevilSquare] Search DevilSquareItem");
for ( int n=0;n<CHAOS_BOX_SIZE;n++)
{
if ( lpObj->pChaosBox[n].IsItem() == TRUE )
{
if ( lpObj->pChaosBox[n].m_Type == ITEMGET(12,15) ) // Chaos
{
bChaoseGem = TRUE;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,17) ) // Eye
{
eventitemcount +=1;
bEyeOfDevil = TRUE;
if ( level != lpObj->pChaosBox[n].m_Level )
{
if ( level == -1 )
{
level = lpObj->pChaosBox[n].m_Level;
}
else
{
bLevelCheck = TRUE;
}
}
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,18) ) // Key
{
eventitemcount +=1;
bKeyOfDevil = TRUE;
if ( level != lpObj->pChaosBox[n].m_Level )
{
if ( level == -1 )
{
level = lpObj->pChaosBox[n].m_Level;
}
else
{
bLevelCheck = TRUE;
}
}
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,53) ) // Charm Of Luck
{
iCharmOfLuckCount += (int)lpObj->pChaosBox[n].m_Durability;
if ( iCharmOfLuckCount > 10 )
{
bCharmOfLuckOver = TRUE;
}
}
else
{
FoundOtherItem = TRUE;
}
}
}
itemlevel = level;
lpObj->ChaosSuccessRate = iCharmOfLuckCount;
if ( FoundOtherItem != FALSE )
{
LogAdd("[DevilSquare] Other DQItems Found");
return 0;
}
if ( bLevelCheck != FALSE )
{
LogAdd("[DevilSquare] DiffLevel DQItems Found");
return 3;
}
if ( bCharmOfLuckOver == TRUE )
{
LogAdd("[DevilSquare] Charm Of Luck Count Over");
return 4;
}
if ( bChaoseGem != FALSE && bEyeOfDevil != FALSE && bKeyOfDevil != FALSE )
{
LogDQChaosItem(lpObj);
return 1;
}
if ( bEyeOfDevil != FALSE && bKeyOfDevil != FALSE )
{
LogDQChaosItem(lpObj);
return 2;
}
LogAdd("[DevilSquare] DQItems Not Found");
return 0;
}
BOOL CChaosBox::DevilSquareEventChaosMix(LPOBJ lpObj, BOOL bCheckType, int iItemLevel)
{
BOOL fail = TRUE;
int aIndex = lpObj->m_Index;
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
lpObj->ChaosLock = TRUE;
LogAddTD("[DevilSquare] Chaos Mix Start");
INT nChaosNeedMoney = 0;
int iCharmOfLuckCount = 0;
iCharmOfLuckCount = lpObj->ChaosSuccessRate;
if ( iCharmOfLuckCount > 10 )
{
pMsg.Result = 0xF0;
lpObj->ChaosLock = FALSE;
DataSend(aIndex, (LPBYTE)&pMsg, pMsg.h.size);
}
switch ( iItemLevel )
{
case 0:
lpObj->ChaosSuccessRate = 60;
nChaosNeedMoney = 100000;
break;
case 1:
lpObj->ChaosSuccessRate = gDQChaosSuccessRateLevel1;
nChaosNeedMoney = 100000;
break;
case 2:
lpObj->ChaosSuccessRate = gDQChaosSuccessRateLevel2;
nChaosNeedMoney = 200000;
break;
case 3:
lpObj->ChaosSuccessRate = gDQChaosSuccessRateLevel3;
nChaosNeedMoney = 400000;
break;
case 4:
lpObj->ChaosSuccessRate = gDQChaosSuccessRateLevel4;
nChaosNeedMoney = 700000;
break;
case 5:
lpObj->ChaosSuccessRate = gDQChaosSuccessRateLevel5;
nChaosNeedMoney = 1100000;
break;
case 6:
lpObj->ChaosSuccessRate = gDQChaosSuccessRateLevel6;
nChaosNeedMoney = 1600000;
break;
case 7:
lpObj->ChaosSuccessRate = gDQChaosSuccessRateLevel7;
nChaosNeedMoney = 2000000;
break;
default:
LogAdd("[DevilSquare] [%s][%s] Invalid DQItem Level [%d]",
lpObj->AccountID, lpObj->Name, iItemLevel);
pMsg.Result = CB_INVALID_ITEM_LEVEL;
DataSend(aIndex, (BYTE *)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return 1;
break;
}
int iChaosTaxMoney = (int)((__int64)nChaosNeedMoney * (__int64)g_CastleSiegeSync.GetTaxRateChaos(lpObj->m_Index) / (__int64)100);
if ( iChaosTaxMoney < 0 )
{
iChaosTaxMoney = 0;
}
nChaosNeedMoney += iChaosTaxMoney;
if ( nChaosNeedMoney < 0 )
{
nChaosNeedMoney = 0;
}
if ( (lpObj->Money - nChaosNeedMoney) < 0 )
{
LogAddTD("[DevilSquare] [%s][%s] CBMix Not Enough Money [%d] need zen [%d]",
lpObj->AccountID, lpObj->Name, lpObj->Money, nChaosNeedMoney);
pMsg.Result = CB_NOT_ENOUGH_ZEN;
DataSend(aIndex, (BYTE *)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return 1;
}
if ( g_CrywolfSync.GetOccupationState() == 0 && g_iCrywolfApplyMvpBenefit )
{
lpObj->ChaosSuccessRate += g_CrywolfSync.GetPlusChaosRate();
}
lpObj->ChaosSuccessRate += iCharmOfLuckCount;
int iRate = rand() % 100;
if ( bCheckType == TRUE )
{
if ( iRate < lpObj->ChaosSuccessRate )
{
int DevilInv = ITEMGET(14,19); // Devil Ticket
ItemSerialCreateSend(lpObj->m_Index, -1, 0, 0, DevilInv, iItemLevel, 0, 0, 0, 0, -1, 0, 0);
fail = FALSE;
}
}
lpObj->Money -= nChaosNeedMoney;
g_CastleSiegeSync.AddTributeMoney(iChaosTaxMoney);
GCMoneySend(lpObj->m_Index, lpObj->Money);
if ( fail == TRUE )
{
ChaosBoxInit(lpObj);
GCUserChaosBoxSend(lpObj, 0);
DataSend(aIndex, (BYTE *)&pMsg, pMsg.h.size);
LogAddTD("[DevilSquare,%d] [%s][%s] CBMix Fail %d Money : %d-%d", iItemLevel,
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate,
lpObj->Money, nChaosNeedMoney);
lpObj->ChaosLock = FALSE;
}
else
{
LogAddTD("[DevilSquare,%d] [%s][%s] CBMix Success Rate:%d Money : %d", iItemLevel,
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate,
nChaosNeedMoney);
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, true);
#endif
}
::gObjInventoryCommit(lpObj->m_Index);
return TRUE;
}
void CChaosBox::DevilSquareItemChaosMix(LPOBJ lpObj)
{
lpObj->ChaosLock = TRUE;
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
int aIndex = lpObj->m_Index;
int eventitemcount;
int itemlevel;
int Ret = CheckDevilSquareItem(lpObj, eventitemcount, itemlevel);
if ( Ret != FALSE )
{
if ( Ret == 3 )
{
pMsg.Result = CB_INCORRECT_MIX_ITEMS;
DataSend(aIndex, (BYTE*)&pMsg, pMsg.h.size);
LogAdd("[DevilSquare] DiffLevel Devil's Key or Eyes [%d]", eventitemcount);
lpObj->ChaosLock = FALSE;
return;
}
if ( Ret == 2 )
{
pMsg.Result = CB_INCORRECT_MIX_ITEMS;
DataSend(aIndex, (BYTE*)&pMsg, pMsg.h.size);
LogAdd("[DevilSquare] Not Found Chaos Gem [%d]", eventitemcount);
lpObj->ChaosLock = FALSE;
return;
}
if ( Ret == 4 )
{
pMsg.Result = 0xF0;
DataSend(aIndex, (BYTE*)&pMsg, pMsg.h.size);
LogAdd("[DevilSquare] Charm Of Luck Over 10% [%d]", eventitemcount);
lpObj->ChaosLock = FALSE;
return;
}
if ( eventitemcount > 2 )
{
pMsg.Result = CB_TOO_MANY_ITEMS;
DataSend(aIndex, (BYTE*)&pMsg, pMsg.h.size);
LogAdd("[DevilSquare] Too many Devil's Key or Eyes [%d]", eventitemcount);
lpObj->ChaosLock = FALSE;
return;
}
if ( lpObj->Level < 10 )
{
pMsg.Result = CB_LOW_LEVEL_USER;
DataSend(aIndex, (BYTE*)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
DevilSquareEventChaosMix(lpObj, Ret, itemlevel);
return;
}
if ( eventitemcount > 1 )
{
pMsg.Result = CB_LACKING_MIX_ITEMS;
DataSend(aIndex, (BYTE*)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
lpObj->ChaosLock = FALSE;
}
void CChaosBox::LogPlusItemLevelChaosItem(LPOBJ lpObj, int iPlusMixLevel)
{
int iMixLevel = 0;
BYTE ExOption[MAX_EXOPTION_SIZE];
if ( iPlusMixLevel == 3 )
iMixLevel = 1;
else if ( iPlusMixLevel == 4 )
iMixLevel = 2;
else if ( iPlusMixLevel == 22 )
iMixLevel = 3;
else if ( iPlusMixLevel == 23 )
iMixLevel = 4;
else if ( iPlusMixLevel == 49 )
iMixLevel = 5;
else if ( iPlusMixLevel == 50 )
iMixLevel = 6;
for ( int n=0;n<CHAOS_BOX_SIZE;n++)
{
if ( lpObj->pChaosBox[n].IsItem() == TRUE )
{
::ItemIsBufExOption(ExOption, &lpObj->pChaosBox[n]);
LogAddTD("[PlusItemLevel,%d] [%s][%s] CBMix [%d,%s,%d,%d,%d,%d]serial:[%d][%d] Ex:[%d,%d,%d,%d,%d,%d,%d] Set:[%d] 380Ex:[%d] HO:[%d,%d]", iMixLevel,
lpObj->AccountID, lpObj->Name, n, lpObj->pChaosBox[n].GetName(), lpObj->pChaosBox[n].m_Level,
lpObj->pChaosBox[n].m_Option1, lpObj->pChaosBox[n].m_Option2, lpObj->pChaosBox[n].m_Option3,
lpObj->pChaosBox[n].m_Number, (int)lpObj->pChaosBox[n].m_Durability,
ExOption[0], ExOption[1], ExOption[2], ExOption[3], ExOption[4], ExOption[5], ExOption[6], lpObj->pChaosBox[n].m_SetOption,
lpObj->pChaosBox[n].m_ItemOptionEx >> 7,
g_kJewelOfHarmonySystem.GetItemOptionLevel(&lpObj->pChaosBox[n]),
g_kJewelOfHarmonySystem.GetItemStrengthenOption(&lpObj->pChaosBox[n]));
}
}
}
void CChaosBox::LogChaosItem(LPOBJ lpObj, LPSTR sLogType)
{
BYTE ExOption[MAX_EXOPTION_SIZE];
for ( int n=0;n<CHAOS_BOX_SIZE;n++)
{
if ( lpObj->pChaosBox[n].IsItem() == TRUE )
{
::ItemIsBufExOption(ExOption, &lpObj->pChaosBox[n]);
LogAddTD("[%s] [%s][%s] CBMix [%d,%s,%d,%d,%d,%d]serial:[%u][%d] Ex:[%d,%d,%d,%d,%d,%d,%d] Set:[%d] 380:[%d] HO:[%d,%d] Socket[%d,%d,%d,%d,%d]",
sLogType, lpObj->AccountID, lpObj->Name, n, lpObj->pChaosBox[n].GetName(), lpObj->pChaosBox[n].m_Level,
lpObj->pChaosBox[n].m_Option1, lpObj->pChaosBox[n].m_Option2, lpObj->pChaosBox[n].m_Option3,
lpObj->pChaosBox[n].m_Number, (int)lpObj->pChaosBox[n].m_Durability,
ExOption[0], ExOption[1], ExOption[2], ExOption[3], ExOption[4], ExOption[5], ExOption[6], lpObj->pChaosBox[n].m_SetOption,
lpObj->pChaosBox[n].m_ItemOptionEx >> 7,
g_kJewelOfHarmonySystem.GetItemStrengthenOption(&lpObj->pChaosBox[n]),
g_kJewelOfHarmonySystem.GetItemOptionLevel(&lpObj->pChaosBox[n]),
lpObj->pChaosBox[n].m_SocketOption[0],lpObj->pChaosBox[n].m_SocketOption[1],lpObj->pChaosBox[n].m_SocketOption[2],lpObj->pChaosBox[n].m_SocketOption[3],lpObj->pChaosBox[n].m_SocketOption[4]);
}
}
}
BOOL CChaosBox::PlusItemLevelChaosMix(LPOBJ lpObj, int mixType)
{
int ChaosGemCount = 0;
int BlessGemCount = 0;
int SoulGemCount = 0;
int Plus9ItemCount = 0;
int Plus10ItemCount = 0;
int PlusItemPos = -1;
int OtherItemFound = 0;
int Plus11ItemCount = 0;
int Plus12ItemCount = 0;
int Plus13ItemCount = 0;
int Plus14ItemCount = 0;
int ExtraBlessGemCount = 0;
int ExtraSoulGemCount = 0;
int iChristmasItem = 0;
int iCharmOfLuckCount = 0;
BYTE btItemLuckValue = 0;
for ( int n=0;n<CHAOS_BOX_SIZE;n++)
{
if ( lpObj->pChaosBox[n].IsItem() == TRUE )
{
if ( lpObj->pChaosBox[n].m_Type == ITEMGET(12,15) )
{
ChaosGemCount++;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,13) )
{
BlessGemCount++;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,14) )
{
SoulGemCount++;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,53) ) // Charm Of Luck
{
iCharmOfLuckCount += (int)lpObj->pChaosBox[n].m_Durability;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,96) )
{
iChristmasItem += 1;
}
else if ( lpObj->pChaosBox[n].m_Level == 9 )
{
Plus9ItemCount++;
PlusItemPos = n;
}
else if ( lpObj->pChaosBox[n].m_Level == 10 )
{
Plus10ItemCount++;
PlusItemPos = n;
}
else if ( lpObj->pChaosBox[n].m_Level == 11 )
{
Plus11ItemCount++;
PlusItemPos = n;
}
else if ( lpObj->pChaosBox[n].m_Level == 12 )
{
Plus12ItemCount++;
PlusItemPos = n;
}
else if ( lpObj->pChaosBox[n].m_Level == 13 )
{
Plus13ItemCount++;
PlusItemPos = n;
}
else if ( lpObj->pChaosBox[n].m_Level == 14 )
{
Plus14ItemCount++;
PlusItemPos = n;
}
else
{
OtherItemFound ++;
}
}
}
if ( iCharmOfLuckCount > 10 )
{
PMSG_CHAOSMIXRESULT pResult;
PHeadSetB((LPBYTE)&pResult, 0x86, sizeof(pResult));
LogAddTD("[PlusItemLevel] [%s][%s] CBMix Charm of luck over 10% (%d)",
lpObj->AccountID, lpObj->Name, iCharmOfLuckCount);
pResult.Result = 0xF0;
DataSend(lpObj->m_Index, (LPBYTE)&pResult, pResult.h.size);
lpObj->ChaosLock = FALSE;
return 0;
}
if ( OtherItemFound != FALSE )
{
return FALSE;
}
if ( iChristmasItem > 1 )
{
PMSG_CHAOSMIXRESULT pResult;
PHeadSetB((LPBYTE)&pResult, 0x86, sizeof(pResult));
pResult.Result = 7;
DataSend(lpObj->m_Index, (LPBYTE)&pResult, pResult.h.size);
lpObj->ChaosLock = FALSE;
return 0;
}
lpObj->ChaosMoney = 0;
int MixType = 0;
if ( Plus9ItemCount == 1 && ChaosGemCount == 1 && BlessGemCount == 1 && SoulGemCount == 1 && Plus10ItemCount == 0 && Plus11ItemCount == 0 && Plus12ItemCount == 0 && Plus13ItemCount == 0 && Plus14ItemCount == 0 )
{
MixType = CHAOS_TYPE_UPGRADE_10;
lpObj->ChaosMoney = 2000000;
ExtraBlessGemCount = BlessGemCount - 1;
ExtraSoulGemCount = SoulGemCount - 1;
}
else if ( Plus10ItemCount == 1 && ChaosGemCount == 1 && BlessGemCount == 2 && SoulGemCount == 2 && Plus9ItemCount == 0 && Plus11ItemCount == 0 && Plus12ItemCount == 0 && Plus13ItemCount == 0 && Plus14ItemCount == 0 )
{
MixType = CHAOS_TYPE_UPGRADE_11;
lpObj->ChaosMoney = 4000000;
ExtraBlessGemCount = BlessGemCount - 2;
ExtraSoulGemCount = SoulGemCount - 2;
}
else if ( Plus11ItemCount == 1 && ChaosGemCount == 1 && BlessGemCount == 3 && SoulGemCount == 3 && Plus9ItemCount == 0 && Plus10ItemCount == 0 && Plus12ItemCount == 0 && Plus13ItemCount == 0 && Plus14ItemCount == 0 )
{
MixType = CHAOS_TYPE_UPGRADE_12;
lpObj->ChaosMoney = 6000000;
ExtraBlessGemCount = BlessGemCount - 3;
ExtraSoulGemCount = SoulGemCount - 3;
}
else if ( Plus12ItemCount == 1 && ChaosGemCount == 1 && BlessGemCount == 4 && SoulGemCount == 4 && Plus9ItemCount == 0 && Plus10ItemCount == 0 && Plus11ItemCount == 0 && Plus13ItemCount == 0 && Plus14ItemCount == 0 )
{
MixType = CHAOS_TYPE_UPGRADE_13;
lpObj->ChaosMoney = 8000000;
ExtraBlessGemCount = BlessGemCount - 4;
ExtraSoulGemCount = SoulGemCount - 4;
}
else if ( Plus13ItemCount == 1 && ChaosGemCount == 1 && BlessGemCount == 5 && SoulGemCount == 5 && Plus9ItemCount == 0 && Plus10ItemCount == 0 && Plus11ItemCount == 0 && Plus12ItemCount == 0 && Plus14ItemCount == 0)
{
MixType = CHAOS_TYPE_UPGRADE_14;
lpObj->ChaosMoney = 10000000;
ExtraBlessGemCount = BlessGemCount - 5;
ExtraSoulGemCount = SoulGemCount - 5;
}
else if ( Plus14ItemCount == 1 && ChaosGemCount == 1 && BlessGemCount == 6 && SoulGemCount == 6 && Plus9ItemCount == 0 && Plus10ItemCount == 0 && Plus11ItemCount == 0 && Plus12ItemCount == 0 && Plus13ItemCount == 0)
{
MixType = CHAOS_TYPE_UPGRADE_15;
lpObj->ChaosMoney = 12000000;
ExtraBlessGemCount = BlessGemCount - 6;
ExtraSoulGemCount = SoulGemCount - 6;
}
if ( MixType != mixType )
{
MixType = 0;
}
if ( MixType == 0 )
{
return FALSE;
}
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
lpObj->ChaosLock = TRUE;
LogPlusItemLevelChaosItem(lpObj, MixType);
LogAddTD("[PlusItemLevel] Chaos Mix Start");
int iChaosTaxMoney = (int)((__int64)lpObj->ChaosMoney * (__int64)g_CastleSiegeSync.GetTaxRateChaos(lpObj->m_Index) / (__int64)100);
if ( iChaosTaxMoney < 0 )
{
iChaosTaxMoney = 0;
}
lpObj->ChaosMoney += iChaosTaxMoney;
if ( lpObj->ChaosMoney < 0 )
{
lpObj->ChaosMoney = 0;
}
if ( lpObj->Money < lpObj->ChaosMoney )
{
LogAddTD("[PlusItemLevel] [%s][%s] CBMix Not Enough Money [%d] need zen [%d]",
lpObj->AccountID, lpObj->Name, lpObj->Money, lpObj->ChaosMoney);
pMsg.Result = CB_NOT_ENOUGH_ZEN;
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return TRUE;
}
lpObj->Money -= lpObj->ChaosMoney;
g_CastleSiegeSync.AddTributeMoney(iChaosTaxMoney);
GCMoneySend(lpObj->m_Index, lpObj->Money);
BYTE btRateType = 0;
if( lpObj->pChaosBox[PlusItemPos].IsExtItem() == TRUE ||
lpObj->pChaosBox[PlusItemPos].IsSetItem() == TRUE ||
g_kItemSystemFor380.Is380Item(&lpObj->pChaosBox[PlusItemPos]) == TRUE )
{
btRateType = 2;
}
else
{
btRateType = 1;
}
if( g_SocketItem.CheckSocketOption(&lpObj->pChaosBox[PlusItemPos]) == TRUE )
{
btRateType = 3;
}
if( ( lpObj->pChaosBox[PlusItemPos].m_Type >= ITEMGET(12,0) && lpObj->pChaosBox[PlusItemPos].m_Type <= ITEMGET(12,6) ) ||
( lpObj->pChaosBox[PlusItemPos].m_Type >= ITEMGET(12,36) && lpObj->pChaosBox[PlusItemPos].m_Type <= ITEMGET(12,43) ) ||
( lpObj->pChaosBox[PlusItemPos].m_Type >= ITEMGET(12,262) && lpObj->pChaosBox[PlusItemPos].m_Type <= ITEMGET(12,267) ) ||
( lpObj->pChaosBox[PlusItemPos].m_Type == ITEMGET(13,30) ||
lpObj->pChaosBox[PlusItemPos].m_Type == ITEMGET(12,49) ||
lpObj->pChaosBox[PlusItemPos].m_Type == ITEMGET(12,50) )
#if (CUSTOM_WINGS == 1)
|| lpObj->pChaosBox[PlusItemPos].m_Type >= ITEMGET(12,440) && lpObj->pChaosBox[PlusItemPos].m_Type <= ITEMGET(12,445)
#endif
)
{
btRateType = 1;
}
#if (__CUSTOM__ == 1)
if( lpObj->pChaosBox[PlusItemPos].m_Level == 9 || lpObj->pChaosBox[PlusItemPos].m_Level == 10 )
{
if( btRateType == 1 )
{
lpObj->ChaosSuccessRate = gc_ChaosMixPlusItemLevel_1_1;
}
else if( btRateType == 2 )
{
lpObj->ChaosSuccessRate = gc_ChaosMixPlusItemLevel_2_1;
}
else if( btRateType == 3 )
{
lpObj->ChaosSuccessRate = gc_ChaosMixPlusItemLevel_3_1;
}
}
else if( lpObj->pChaosBox[PlusItemPos].m_Level == 11 || lpObj->pChaosBox[PlusItemPos].m_Level == 12 )
{
if( btRateType == 1 )
{
lpObj->ChaosSuccessRate = gc_ChaosMixPlusItemLevel_1_2;
}
else if( btRateType == 2 )
{
lpObj->ChaosSuccessRate = gc_ChaosMixPlusItemLevel_2_2;
}
else if( btRateType == 3 )
{
lpObj->ChaosSuccessRate = gc_ChaosMixPlusItemLevel_3_2;
}
}
else if( lpObj->pChaosBox[PlusItemPos].m_Level == 13 || lpObj->pChaosBox[PlusItemPos].m_Level == 14 )
{
if( btRateType == 1 )
{
lpObj->ChaosSuccessRate = gc_ChaosMixPlusItemLevel_1_3;
}
else if( btRateType == 2 )
{
lpObj->ChaosSuccessRate = gc_ChaosMixPlusItemLevel_2_3;
}
else if( btRateType == 3 )
{
lpObj->ChaosSuccessRate = gc_ChaosMixPlusItemLevel_3_3;
}
}
else
{
lpObj->ChaosSuccessRate = 45;
}
if( lpObj->pChaosBox[PlusItemPos].m_Option2 )
{
lpObj->ChaosSuccessRate += gc_ChaosMixPlusItemLevel_Luck;
}
if( lpObj->ChaosSuccessRate > gc_ChaosMixPlusItemLevel_Max )
{
lpObj->ChaosSuccessRate = gc_ChaosMixPlusItemLevel_Max;
}
#else
if( lpObj->pChaosBox[PlusItemPos].m_Level == 9 || lpObj->pChaosBox[PlusItemPos].m_Level == 10 )
{
if( btRateType == 1 )
{
lpObj->ChaosSuccessRate = 60;
}
else if( btRateType == 2 )
{
lpObj->ChaosSuccessRate = 50;
}
else if( btRateType == 3 )
{
lpObj->ChaosSuccessRate = 40;
}
}
else if( lpObj->pChaosBox[PlusItemPos].m_Level == 11 || lpObj->pChaosBox[PlusItemPos].m_Level == 12 )
{
if( btRateType == 1 )
{
lpObj->ChaosSuccessRate = 55;
}
else if( btRateType == 2 )
{
lpObj->ChaosSuccessRate = 45;
}
else if( btRateType == 3 )
{
lpObj->ChaosSuccessRate = 35;
}
}
else if( lpObj->pChaosBox[PlusItemPos].m_Level == 13 || lpObj->pChaosBox[PlusItemPos].m_Level == 14 )
{
if( btRateType == 1 )
{
lpObj->ChaosSuccessRate = 20;
}
else if( btRateType == 2 )
{
lpObj->ChaosSuccessRate = 10;
}
else if( btRateType == 3 )
{
lpObj->ChaosSuccessRate = 5;
}
}
else
{
lpObj->ChaosSuccessRate = 45;
}
if( lpObj->pChaosBox[PlusItemPos].m_Option2 )
{
lpObj->ChaosSuccessRate += 20;
}
if( lpObj->ChaosSuccessRate > 75 )
{
lpObj->ChaosSuccessRate = 75;
}
#endif
lpObj->ChaosSuccessRate += iCharmOfLuckCount;
if ( (rand()%100) < lpObj->ChaosSuccessRate )
{
lpObj->pChaosBox[PlusItemPos].m_Level++;
pMsg.Result = CB_SUCCESS;
CItem Item;
float Dur = (float)ItemGetDurability(lpObj->pChaosBox[PlusItemPos].m_Type, lpObj->pChaosBox[PlusItemPos].m_Level,
lpObj->pChaosBox[PlusItemPos].IsExtItem(), lpObj->pChaosBox[PlusItemPos].IsSetItem());
Item.m_Level = lpObj->pChaosBox[PlusItemPos].m_Level;
Item.m_Durability = Dur * lpObj->pChaosBox[PlusItemPos].m_Durability / lpObj->pChaosBox[PlusItemPos].m_BaseDurability;
Item.m_JewelOfHarmonyOption = lpObj->pChaosBox[PlusItemPos].m_JewelOfHarmonyOption;
Item.m_bLOCKED = lpObj->pChaosBox[PlusItemPos].m_bLOCKED;
BYTE SocketOptions[MAX_SOCKET_COUNT];
BYTE SocketBonus;
if( g_SocketItem.IsSocketItem(lpObj->pChaosBox[PlusItemPos].m_Type) )
{
g_SocketItem.GetItemOptions(&lpObj->pChaosBox[PlusItemPos],&SocketOptions[0],&SocketBonus);
}
else if( g_ElementalSystem.IsPentagram(lpObj->pChaosBox[PlusItemPos].m_Type) )
{
SocketBonus = lpObj->pChaosBox[PlusItemPos].m_SocketBonus;
for(int i = 0; i < 5; i++) {
SocketOptions[i] = lpObj->pChaosBox[PlusItemPos].m_SocketOption[i];
}
}
Item.Convert(lpObj->pChaosBox[PlusItemPos].m_Type, lpObj->pChaosBox[PlusItemPos].m_Option1, lpObj->pChaosBox[PlusItemPos].m_Option2,
lpObj->pChaosBox[PlusItemPos].m_Option3, lpObj->pChaosBox[PlusItemPos].m_NewOption,
lpObj->pChaosBox[PlusItemPos].m_SetOption, lpObj->pChaosBox[PlusItemPos].m_ItemOptionEx, SocketOptions, SocketBonus, CURRENT_DB_VERSION);
Item.m_Number = lpObj->pChaosBox[PlusItemPos].m_Number;
ItemByteConvert(pMsg.ItemInfo, Item);
ChaosBoxInit(lpObj);
::gObjChaosBoxInsertItemPos(lpObj->m_Index, Item, 0, -1);
gObjChaosItemSet(lpObj->m_Index, 0, 1);
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
if ( btItemLuckValue )
{
LogAddTD("[PlusItemLevel] [%s][%s] CBMix Success %d Money : %d-%d [%d], CharmRate : %d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate+5, lpObj->Money,
lpObj->ChaosMoney, Item.m_Level, iCharmOfLuckCount);
}
else
{
LogAddTD("[PlusItemLevel] [%s][%s] CBMix Success %d Money : %d-%d [%d], CharmRate : %d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate, lpObj->Money,
lpObj->ChaosMoney, Item.m_Level, iCharmOfLuckCount);
}
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, true);
#endif
}
else
{
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, false);
#endif
int FailLevel = lpObj->pChaosBox[PlusItemPos].m_Level+1;
if( iChristmasItem != 0 )
{
ChaosBoxSpecialItemDown(lpObj);
GCUserChaosBoxSend(lpObj, 0);
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
}
else
{
ChaosBoxInit(lpObj);
GCUserChaosBoxSend(lpObj, 0);
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
}
if ( btItemLuckValue )
{
LogAddTD("[PlusItemLevel] [%s][%s] CBMix Fail %d Money : %d-%d [%d], CharmRate : %d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate+5, lpObj->Money,
lpObj->ChaosMoney, FailLevel, iCharmOfLuckCount);
}
else
{
LogAddTD("[PlusItemLevel] [%s][%s] CBMix Fail %d Money : %d-%d [%d], CharmRate : %d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate, lpObj->Money,
lpObj->ChaosMoney, FailLevel, iCharmOfLuckCount);
}
}
lpObj->ChaosLock = FALSE;
return true;
}
void CChaosBox::ChaosBoxSpecialItemDown(LPOBJ lpObj)
{
for ( int n=0;n<CHAOS_BOX_SIZE;n++)
{
if( lpObj->pChaosBox[n].IsItem() == TRUE )
{
lpObj->pChaosBox[n].m_Level = 0;
int iType = lpObj->pChaosBox[n].m_Type;
if( IsPlusItemJewel(iType) == TRUE )
{
lpObj->pChaosBox[n].Clear();
lpObj->pChaosBoxMap[n] = 0xFF;
}
}
}
}
int CChaosBox::IsPlusItemJewel(int iType)
{
switch( iType )
{
case ITEMGET(14, 53):
case ITEMGET(12, 15):
case ITEMGET(14, 13):
case ITEMGET(14, 14):
case ITEMGET(14, 96):
case ITEMGET(14, 189):
case ITEMGET(14, 190):
return TRUE;
default:
return FALSE;
}
}
BOOL CChaosBox::PegasiaChaosMix(LPOBJ lpObj)
{
lpObj->ChaosLock = TRUE;
int UniriaCount = 0;
int ChoasGemCount = 0;
int iCharmOfLuckCount = 0;
for (int n = 0; n < CHAOS_BOX_SIZE; n++)
{
if (lpObj->pChaosBox[n].IsItem() == TRUE)
{
if (lpObj->pChaosBox[n].m_Type == ITEMGET(13, 2) && lpObj->pChaosBox[n].m_Durability == 255.0f) // Uniria
{
UniriaCount++;
}
else if (lpObj->pChaosBox[n].m_Type == ITEMGET(12, 15)) // Chaos Gem
{
ChoasGemCount++;
}
else if (lpObj->pChaosBox[n].m_Type == ITEMGET(14, 53)) // Charm Of Luck
{
iCharmOfLuckCount += (int)lpObj->pChaosBox[n].m_Durability;
}
}
}
if (UniriaCount != 10 || ChoasGemCount != 1)
{
lpObj->ChaosLock = FALSE;
return FALSE;
}
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
if ( iCharmOfLuckCount > 10 )
{
lpObj->ChaosLock = FALSE;
pMsg.Result = 0xF0;
DataSend(lpObj->m_Index, (LPBYTE)&pMsg, pMsg.h.size);
return 0;
}
int nChaosNeedMoney = 500000;
int iChaosTaxMoney = (int)((__int64)nChaosNeedMoney * (__int64)g_CastleSiegeSync.GetTaxRateChaos(lpObj->m_Index) / (__int64)100);
if ( iChaosTaxMoney < 0 )
{
iChaosTaxMoney = 0;
}
nChaosNeedMoney += iChaosTaxMoney;
if ( nChaosNeedMoney < 0 )
{
nChaosNeedMoney = 0;
}
if ( lpObj->Money < nChaosNeedMoney )
{
lpObj->ChaosLock = FALSE;
pMsg.Result = CB_NOT_ENOUGH_ZEN;
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return TRUE;
}
LogChaosItem(lpObj, "DinorantMix");
LogAddTD("[DinorantMix] Chaos Mix Start");
lpObj->ChaosSuccessRate = 70; // Succes Rate for Dinorant
lpObj->ChaosSuccessRate += iCharmOfLuckCount;
lpObj->Money -= nChaosNeedMoney;
g_CastleSiegeSync.AddTributeMoney(iChaosTaxMoney);
GCMoneySend(lpObj->m_Index, lpObj->Money);
if ( (rand()%100 ) < lpObj->ChaosSuccessRate )
{
int Dinorant = ITEMGET(13,3);
int Option3 = 0;
if ( (rand()% 100) < 30 )
{
Option3 = 1 << ((rand()%3)) ;
if ( (rand()%5) == 0 )
{
Option3 |= 1 << (rand()%3);
}
}
ItemSerialCreateSend(lpObj->m_Index, -1, 0, 0, Dinorant, 0, 255, 1, 0, Option3, -1, 0, 0);
gObjInventoryCommit(lpObj->m_Index);
LogAddTD("[DinorantMix] [%s][%s] CBMix Success %d Money : %d-%d, CharmRate : %d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate, lpObj->Money, nChaosNeedMoney, iCharmOfLuckCount);
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, true);
#endif
return TRUE;
}
else
{
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, false);
#endif
ChaosBoxInit(lpObj); // Errase Chaos Box
GCUserChaosBoxSend(lpObj, 0);
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
LogAddTD("[DinorantMix] [%s][%s] CBMix Fail %d Money : %d-%d, CharmRate : %d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate, lpObj->Money, nChaosNeedMoney, iCharmOfLuckCount);
lpObj->ChaosLock = FALSE;
return FALSE;
}
}
BOOL CChaosBox::CircleChaosMix(LPOBJ lpObj) // Fruits
{
lpObj->ChaosLock = TRUE;
int CreatureGemCount = 0;
int ChoasGemCount = 0;
int iCharmOfLuckCount = 0;
for ( int n=0;n<CHAOS_BOX_SIZE;n++)
{
if ( lpObj->pChaosBox[n].IsItem() == TRUE )
{
if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,22) ) // Jewel of Creation
{
CreatureGemCount++;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(12,15) ) // Chaos Gem
{
ChoasGemCount++;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,53) ) // Charm Of Luck
{
iCharmOfLuckCount += (int)lpObj->pChaosBox[n].m_Durability;
}
}
}
if ( CreatureGemCount != 1 || ChoasGemCount != 1 )
{
return FALSE;
}
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
if ( iCharmOfLuckCount > 10 )
{
lpObj->ChaosLock = FALSE;
pMsg.Result = 0xF0;
DataSend(lpObj->m_Index, (LPBYTE)&pMsg, pMsg.h.size);
return 1;
}
if ( lpObj->Level < 10 )
{
pMsg.Result = CB_LOW_LEVEL_USER;
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return TRUE;
}
int nChaosNeedMoney = 3000000;
int iChaosTaxMoney = (int)((__int64)nChaosNeedMoney * (__int64)g_CastleSiegeSync.GetTaxRateChaos(lpObj->m_Index) / (__int64)100);
if ( iChaosTaxMoney < 0 )
{
iChaosTaxMoney = 0;
}
nChaosNeedMoney += iChaosTaxMoney;
if ( nChaosNeedMoney < 0 )
{
nChaosNeedMoney = 0;
}
if ( lpObj->Money < nChaosNeedMoney )
{
lpObj->ChaosLock = FALSE;
pMsg.Result = CB_NOT_ENOUGH_ZEN;
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return TRUE;
}
LogChaosItem(lpObj, "CircleMix");
LogAddTD("[CircleMix] Chaos Mix Start");
lpObj->ChaosSuccessRate = 90; // Succes Rate for Fruit
lpObj->ChaosSuccessRate += iCharmOfLuckCount;
lpObj->Money -= nChaosNeedMoney;
g_CastleSiegeSync.AddTributeMoney(iChaosTaxMoney);
GCMoneySend(lpObj->m_Index, lpObj->Money);
if ( (rand()%100 ) < lpObj->ChaosSuccessRate )
{
int Fruit = ITEMGET(13,15); // Fruit
int FruitType;
int RandonValue = rand() % 100;
if ( RandonValue < 30 )
{
FruitType = 0;
}
else if ( RandonValue < 55 )
{
FruitType = 1;
}
else if ( RandonValue < 75 )
{
FruitType = 2;
}
else if ( RandonValue < 95 )
{
FruitType = 3;
}
else
{
FruitType = 4;
}
::ItemSerialCreateSend(lpObj->m_Index, -1, 0, 0, Fruit, FruitType, 255, 1, 0, 0, -1, 0, 0);
::gObjInventoryCommit(lpObj->m_Index);
LogAddTD("[CircleMix] [%s][%s] CBMix Success %d Money : %d-%d, CharmRate : %d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate, lpObj->Money, nChaosNeedMoney, iCharmOfLuckCount);
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, true);
#endif
return TRUE;
}
else
{
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, false);
#endif
ChaosBoxInit(lpObj);
GCUserChaosBoxSend(lpObj, 0);
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
LogAddTD("[CircleMix] [%s][%s] CBMix Fail %d Money : %d-%d, CharmRate : %d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate, lpObj->Money, nChaosNeedMoney, iCharmOfLuckCount);
lpObj->ChaosLock = FALSE;
return FALSE;
}
}
BOOL CChaosBox::WingChaosMix(LPOBJ lpObj)
{
lpObj->ChaosLock = TRUE;
int WingCount = 0;
int ChoasGemCount = 0;
int LokesFeathersCount = 0;
int WingIndex = -1;
int iChaosMoney = 0;
int WingIndex2 = -1;
int iWingChaosMoney = 0;
int iSleeveOfLord = 0;
int iCharmOfLuckCount = 0;
int n;
for ( n=0;n<CHAOS_BOX_SIZE;n++)
{
if ( lpObj->pChaosBox[n].IsItem() == TRUE )
{
if ( (lpObj->pChaosBox[n].m_Type >= ITEMGET(12,3) && lpObj->pChaosBox[n].m_Type <= ITEMGET(12,6)) || lpObj->pChaosBox[n].m_Type == ITEMGET(12,42) || lpObj->pChaosBox[n].m_Type == ITEMGET(14,30) )
{
lpObj->ChaosLock = FALSE;
return FALSE;
}
if ( lpObj->pChaosBox[n].m_Type >= ITEMGET(12,0) && lpObj->pChaosBox[n].m_Type <= ITEMGET(12,2) )
{
WingCount++;
WingIndex = n;
iWingChaosMoney = lpObj->pChaosBox[n].m_BuyMoney;
}
if ( lpObj->pChaosBox[n].m_Type == ITEMGET(12,41) )
{
WingCount++;
WingIndex = n;
iWingChaosMoney = lpObj->pChaosBox[n].m_BuyMoney;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(12,15) ) // Chaos
{
ChoasGemCount++;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(13,14) ) // Feather
{
if ( lpObj->pChaosBox[n].m_Level == 0 ) // Feather
{
LokesFeathersCount++;
}
else // Crst of Monarch
{
iSleeveOfLord ++;
}
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,53) ) // Charm Of Luck
{
iCharmOfLuckCount += (int)lpObj->pChaosBox[n].m_Durability;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(13,88) ||
lpObj->pChaosBox[n].m_Type == ITEMGET(13,89) ||
lpObj->pChaosBox[n].m_Type == ITEMGET(13,90) ||
lpObj->pChaosBox[n].m_Type == ITEMGET(13,91) ||
lpObj->pChaosBox[n].m_Type == ITEMGET(13,92) )
{
WingIndex2 = lpObj->pChaosBox[n].m_Type;
}
else if ( lpObj->pChaosBox[n].IsExtItem() != FALSE )
{
if ( lpObj->pChaosBox[n].m_Level >= 4 )
{
iChaosMoney += lpObj->pChaosBox[n].m_BuyMoney;
}
}
}
}
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
if ( iSleeveOfLord == 1 )
{
if ( WingCount != 1 || ChoasGemCount != 1 || LokesFeathersCount != 0 )
{
lpObj->ChaosLock = FALSE;
pMsg.Result = CB_INCORRECT_MIX_ITEMS;
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
return FALSE;
}
}
else if ( LokesFeathersCount == 1 )
{
if ( WingCount != 1 || ChoasGemCount != 1 || iSleeveOfLord != 0 )
{
pMsg.Result = CB_INCORRECT_MIX_ITEMS;
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return FALSE;
}
}
else
{
lpObj->ChaosLock = FALSE;
pMsg.Result = CB_INCORRECT_MIX_ITEMS;
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
return FALSE;
}
if ( iCharmOfLuckCount > 10 )
{
lpObj->ChaosLock = FALSE;
pMsg.Result = 0xF0;
DataSend(lpObj->m_Index, (LPBYTE)&pMsg, pMsg.h.size);
}
int nChaosNeedMoney = 5000000;
int iChaosTaxMoney = (int)((__int64)nChaosNeedMoney * (__int64)g_CastleSiegeSync.GetTaxRateChaos(lpObj->m_Index) / (__int64)100);
if ( iChaosTaxMoney < 0 )
{
iChaosTaxMoney = 0;
}
nChaosNeedMoney += iChaosTaxMoney;
if ( nChaosNeedMoney < 0 )
{
nChaosNeedMoney = 0;
}
if ( lpObj->Money < nChaosNeedMoney )
{
pMsg.Result = CB_NOT_ENOUGH_ZEN;
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return TRUE;
}
CItem * pWing = &lpObj->pChaosBox[WingIndex];
lpObj->ChaosSuccessRate = (DWORD)((DWORD)iWingChaosMoney / (DWORD)4000000);
lpObj->ChaosSuccessRate += iChaosMoney / 40000;
if ( lpObj->ChaosSuccessRate < 0 )
{
lpObj->ChaosSuccessRate = 100;
}
if ( lpObj->ChaosSuccessRate == 0 )
{
pMsg.Result = CB_INCORRECT_MIX_ITEMS;
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return FALSE;
}
LogChaosItem(lpObj, "WingMix,2");
LogAddTD("[WingMix,2] Chaos Mix Start");
if ( lpObj->ChaosSuccessRate > 90 )
{
lpObj->ChaosSuccessRate = 90;
}
lpObj->ChaosSuccessRate += iCharmOfLuckCount;
lpObj->Money -= nChaosNeedMoney;
g_CastleSiegeSync.AddTributeMoney(iChaosTaxMoney);
GCMoneySend(lpObj->m_Index, lpObj->Money);
if ( (rand()%100) < lpObj->ChaosSuccessRate )
{
int iWingLevel = 0;
int iItemType;
int iItemSubType;
if ( iSleeveOfLord != 0 )
{
if( rand()%2 == TRUE )
{
iItemType = 12;
iItemSubType = 49;
}
else
{
iItemType = 13;
iItemSubType = 30;
}
}
else
{
iItemType = 12;
int iRand = rand()%5;
if( iRand == 4 )
{
iItemSubType = 42;
}
else
{
iItemSubType = iRand + 3;
}
}
if( WingIndex2 > -1 )
{
int WingCharm = WingIndex2^ITEMGET(13,0);
switch( WingCharm )
{
case 88:
iItemSubType = 5;
break;
case 89:
iItemSubType = 4;
break;
case 90:
iItemSubType = 3;
break;
case 91:
iItemSubType = 42;
break;
case 92:
iItemSubType = 6;
break;
default:
LogAddTD("[MixSystem][WingChaosMix] WingCharmItemNum => %d , WingCharmIndex => %d",
WingIndex2,WingCharm);
break;
}
}
int iWingNum = ITEMGET(iItemType, iItemSubType);
int iOption1 = 0;
int iOption2 = 0;
int iOption3 = 0;
if ( (rand()%5) == 0 )
{
iOption1 = 1;
}
int iRandomValue = rand() % 100;
int iRandomValue2 = rand() % 3;
switch ( iRandomValue2 )
{
case 0:
if ( iRandomValue < 4 )
{
iOption2 = 3; // +12
}
break;
case 1:
if ( iRandomValue < 10 )
{
iOption2 = 2; // +8
}
break;
case 2:
if ( iRandomValue < 20 )
{
iOption2 = 1; // +4;
}
}
//int ExOption;
if ( iSleeveOfLord != FALSE )
{
if ( (rand()%5) == 0 )
{
iOption3 = 1 << (rand()%4);
}
iOption3 |= 0x20;
}
else
{
if ( (rand()%5) == 0 )
{
iOption3 = 1 << (rand()%3);
}
if ( (rand()%2) != 0 )
{
iOption3 |= 0x20;
}
}
::ItemSerialCreateSend(lpObj->m_Index, -1, 0, 0, iWingNum, iWingLevel, 0, 0, iOption1, iOption2, -1, iOption3, 0);
::gObjInventoryCommit(lpObj->m_Index);
::LogAddTD("[WingMix,2] [%s][%s] CBMix Success %d Money : %d-%d, CharmRate : %d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate, lpObj->Money, nChaosNeedMoney, iCharmOfLuckCount);
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, true);
#endif
return TRUE;
}
else
{
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, false);
#endif
for ( n=0;n<CHAOS_BOX_SIZE;n++)
{
lpObj->pChaosBox[n].Clear();
}
GCUserChaosBoxSend(lpObj, 0);
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
::LogAddTD("[WingMix,2] [%s][%s] CBMix Fail %d Money : %d-%d, CharmRate : %d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate, lpObj->Money, nChaosNeedMoney, iCharmOfLuckCount);
lpObj->ChaosLock = FALSE;
return FALSE;
}
}
void CChaosBox::BloodCastleItemChaosMix(LPOBJ lpObj)
{
lpObj->ChaosLock = TRUE;
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
int aIndex = lpObj->m_Index;
int iRET_VAL = g_BloodCastle.CheckChoasMixItem(aIndex);
int iMapNumber = g_BloodCastle.GetEventMap(iRET_VAL-1);
if ( BC_MAP_RANGE(iMapNumber) != FALSE )
{
if ( g_BloodCastle.BloodCastleChaosMix(aIndex, iRET_VAL) == false )
{
lpObj->ChaosLock = FALSE;
}
return;
}
switch ( iRET_VAL )
{
case 9:
pMsg.Result = CB_NO_BC_CORRECT_ITEMS ;
DataSend(aIndex, (UCHAR*)&pMsg, pMsg.h.size);
lpObj->m_Index;
lpObj->ChaosLock = FALSE;
break;
case 10:
pMsg.Result = CB_NO_BC_CORRECT_ITEMS ;
DataSend(aIndex, (UCHAR*)&pMsg, pMsg.h.size);
lpObj->m_Index;
lpObj->ChaosLock = FALSE;
break;
case 11:
pMsg.Result = CB_NO_BC_CORRECT_ITEMS ;
DataSend(aIndex, (UCHAR*)&pMsg, pMsg.h.size);
lpObj->m_Index;
lpObj->ChaosLock = FALSE;
break;
case 12:
pMsg.Result = CB_INVALID_ITEM_LEVEL ;
DataSend(aIndex, (UCHAR*)&pMsg, pMsg.h.size);
lpObj->m_Index;
lpObj->ChaosLock = FALSE;
break;
case 13:
pMsg.Result = CB_BC_NOT_ENOUGH_ZEN ;
DataSend(aIndex, (UCHAR*)&pMsg, pMsg.h.size);
lpObj->m_Index;
lpObj->ChaosLock = FALSE;
break;
case 14:
pMsg.Result = CB_USER_CLASS_LOW_LEVEL ;
DataSend(aIndex, (UCHAR*)&pMsg, pMsg.h.size);
lpObj->m_Index;
lpObj->ChaosLock = FALSE;
break;
case 15:
pMsg.Result = 0xF0;
DataSend(aIndex, (BYTE*)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
break;
default:
lpObj->ChaosLock = FALSE;
}
}
void CChaosBox::SetItemChaosMix(LPOBJ lpObj)
{
lpObj->ChaosLock = TRUE;
int ChoasGemCount = 0;
int BlessGemCount = 0;
int SoulGemCount = 0;
int MetalOfAncientCount = 0;
int MixItemCount = 0;
int MixSetItemIndex = 0;
int iMixItemChaosMoney = 0;
int iChaosMoney = 0;
int iMetalOfAncientItemLevel = -1;
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
for ( int n=0;n<CHAOS_BOX_SIZE;n++)
{
if ( lpObj->pChaosBox[n].IsItem() == TRUE )
{
if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,13) )
{
BlessGemCount++;
if ( BlessGemCount > 3 )
{
iChaosMoney += lpObj->pChaosBox[n].m_BuyMoney;
}
}
if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,14) )
{
SoulGemCount++;
if ( SoulGemCount > 3 )
{
iChaosMoney += lpObj->pChaosBox[n].m_BuyMoney;
}
}
if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,16) )
{
iChaosMoney += lpObj->pChaosBox[n].m_BuyMoney;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(12,15) )
{
ChoasGemCount++;
}
else if ( lpObj->pChaosBox[n].m_Level >= 6 && lpObj->pChaosBox[n].IsExtItem() != FALSE)
{
if ( gSetItemOption.IsSetItem(lpObj->pChaosBox[n].m_Type) != FALSE )
{
MixItemCount++;
MixSetItemIndex = n;
iMixItemChaosMoney += lpObj->pChaosBox[n].m_BuyMoney;
}
}
else if ( ((lpObj->pChaosBox[n].m_Type >= ITEMGET(13,8) && lpObj->pChaosBox[n].m_Type < ITEMGET(13,14)) || (lpObj->pChaosBox[n].m_Type >= ITEMGET(13,21) && lpObj->pChaosBox[n].m_Type < ITEMGET(13,28) ) ) && ( lpObj->pChaosBox[n].m_Option3 >= 2 && lpObj->pChaosBox[n].m_Level >= 3 ) )
{
if ( gSetItemOption.IsSetItem(lpObj->pChaosBox[n].m_Type ) != FALSE )
{
MixItemCount++;
MixSetItemIndex = n;
iMixItemChaosMoney += lpObj->pChaosBox[n].m_BuyMoney;
}
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,27) ) // Ancien Metal, Apply Deathway Fix here
{
MetalOfAncientCount++;
iMetalOfAncientItemLevel = lpObj->pChaosBox[n].m_Level;
}
else
{
DataSend(lpObj->m_Index, (BYTE*)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
}
}
}
if ( ChoasGemCount < 1 || BlessGemCount < 3 || SoulGemCount < 3 || MetalOfAncientCount != 1 || MixItemCount != 1 )
{
DataSend(lpObj->m_Index, (BYTE*)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
LogChaosItem(lpObj, "SetItemMix");
LogAddTD("[SetItemMix] Chaos Mix Start");
if ( gSetItemOption.CheckMixContition(lpObj->pChaosBox[MixSetItemIndex].m_Type, iMetalOfAncientItemLevel ) == FALSE )
{
DataSend(lpObj->m_Index, (BYTE*)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
lpObj->ChaosSuccessRate = iMixItemChaosMoney / 40000;
lpObj->ChaosSuccessRate = iChaosMoney / 400000;
if ( lpObj->ChaosSuccessRate > 80 )
{
lpObj->ChaosSuccessRate = 80;
}
int nChaosNeedMoney = (lpObj->ChaosSuccessRate - 50 ) * 1000000;
if ( lpObj->Money < nChaosNeedMoney )
{
pMsg.Result = CB_NOT_ENOUGH_ZEN;
DataSend(lpObj->m_Index, (BYTE*)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
int setoption = gSetItemOption.MakeSetOption(lpObj->pChaosBox[MixSetItemIndex].m_Type, iMetalOfAncientItemLevel);
if ( setoption == 0 )
{
pMsg.Result = CB_ERROR;
DataSend(lpObj->m_Index, (BYTE*)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
lpObj->Money -= nChaosNeedMoney;
GCMoneySend(lpObj->m_Index, lpObj->Money);
if ( (rand()%100) < lpObj->ChaosSuccessRate )
{
lpObj->pChaosBox[MixSetItemIndex].m_SetOption = setoption;
if ( (rand()%100 ) < 80 )
{
lpObj->pChaosBox[MixSetItemIndex].m_SetOption |= 4;
}
else
{
lpObj->pChaosBox[MixSetItemIndex].m_SetOption |= 8;
}
pMsg.Result = CB_SUCCESS;
CItem Item;
float Dur = (float)ItemGetDurability(lpObj->pChaosBox[MixSetItemIndex].m_Type, lpObj->pChaosBox[MixSetItemIndex].m_Level,
lpObj->pChaosBox[MixSetItemIndex].IsExtItem(), lpObj->pChaosBox[MixSetItemIndex].IsSetItem());
Item.m_Level = lpObj->pChaosBox[MixSetItemIndex].m_Level;
Item.m_Durability = Dur * lpObj->pChaosBox[MixSetItemIndex].m_Durability / lpObj->pChaosBox[MixSetItemIndex].m_BaseDurability;
Item.m_JewelOfHarmonyOption = lpObj->pChaosBox[MixSetItemIndex].m_JewelOfHarmonyOption;
Item.m_bLOCKED = lpObj->pChaosBox[MixSetItemIndex].m_bLOCKED;
Item.Convert(lpObj->pChaosBox[MixSetItemIndex].m_Type, lpObj->pChaosBox[MixSetItemIndex].m_Option1, lpObj->pChaosBox[MixSetItemIndex].m_Option2,
lpObj->pChaosBox[MixSetItemIndex].m_Option3, lpObj->pChaosBox[MixSetItemIndex].m_NewOption,
lpObj->pChaosBox[MixSetItemIndex].m_SetOption, lpObj->pChaosBox[MixSetItemIndex].m_ItemOptionEx, 0, -1, CURRENT_DB_VERSION);
Item.m_Number = lpObj->pChaosBox[MixSetItemIndex].m_Number;
ItemByteConvert(pMsg.ItemInfo, Item);
ChaosBoxInit(lpObj);
::gObjChaosBoxInsertItemPos(lpObj->m_Index, Item, 0, -1);
gObjChaosItemSet(lpObj->m_Index, 0, 1);
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, true);
#endif
LogAddTD("[SetItemMix] [%s][%s] CBMix Success %d Money : %d-%d (SetName:%s)", lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate,
lpObj->Money, lpObj->ChaosMoney, gSetItemOption.GetSetOptionName(lpObj->pChaosBox[MixSetItemIndex].m_Type, setoption));
}
else
{
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, false);
#endif
ChaosBoxInit(lpObj);
GCUserChaosBoxSend(lpObj, 0);
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
LogAddTD("[SetItemMix] [%s][%s] CBMix Fail %d Money : %d-%d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate, lpObj->Money,
nChaosNeedMoney);
lpObj->ChaosLock = FALSE;
}
}
void CChaosBox::DarkHorseChaosMix(LPOBJ lpObj)
{
lpObj->ChaosLock = TRUE;
int ChoasGemCount = 0;
int BlessGemCount = 0;
int SoulGemCount = 0;
int CreatureGemCount = 0;
int SoulOfDarkHorse = 0;
int iChaosMoney = 0;
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
int iCharmOfLuckCount = 0;
int iInvalidItemCount = 0;
for ( int n=0;n<CHAOS_BOX_SIZE;n++)
{
if ( lpObj->pChaosBox[n].IsItem() == TRUE )
{
if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,13) )
{
BlessGemCount++;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,14) )
{
SoulGemCount++;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,22) ) // Creation
{
CreatureGemCount++;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(12,15) ) // SUPE CHOAS HAHAHA
{
ChoasGemCount++;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(13,31) && lpObj->pChaosBox[n].m_Level == 0 ) // Spirit
{
SoulOfDarkHorse++;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,53) ) // Charm Of Luck
{
iCharmOfLuckCount += (int)lpObj->pChaosBox[n].m_Durability;
}
else
{
iInvalidItemCount++;
}
}
}
if ( ChoasGemCount != 1 || BlessGemCount != 5 || SoulGemCount != 5 || CreatureGemCount != 1 || SoulOfDarkHorse != 1 || iInvalidItemCount > 0 )
{
DataSend(lpObj->m_Index, (UCHAR*)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
if ( iCharmOfLuckCount > 10 )
{
pMsg.Result = 0xF0;
DataSend(lpObj->m_Index, (LPBYTE)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return ;
}
LogChaosItem(lpObj, "DarkHorseMix");
LogAddTD("[DarkHorseMix] Chaos Mix Start");
lpObj->ChaosSuccessRate = 60;
lpObj->ChaosSuccessRate += iCharmOfLuckCount;
int nChaosNeedMoney = 5000000;
int iChaosTaxMoney = (int)((__int64)nChaosNeedMoney * (__int64)g_CastleSiegeSync.GetTaxRateChaos(lpObj->m_Index) / (__int64)100);
if ( iChaosTaxMoney < 0 )
{
iChaosTaxMoney = 0;
}
nChaosNeedMoney += iChaosTaxMoney;
if ( nChaosNeedMoney < 0 )
{
nChaosNeedMoney = 0;
}
if ( lpObj->Money < nChaosNeedMoney )
{
pMsg.Result = CB_NOT_ENOUGH_ZEN;
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
lpObj->Money -= nChaosNeedMoney;
g_CastleSiegeSync.AddTributeMoney(iChaosTaxMoney);
GCMoneySend(lpObj->m_Index, lpObj->Money);
if ( (rand()%100) < lpObj->ChaosSuccessRate )
{
int Level = 0;
int ItemType = 13;
int ItemSubType = 4;
int ItemNum = ITEMGET(ItemType, ItemSubType);
int Option1 = 0;
int Option2 = 0;
int Option3 = 0;
int Add = 0;
if ( (rand()%100) < (lpObj->ChaosSuccessRate/5+6) )
{
Add = 1;
}
if ( (rand()%5) == 0 )
{
Option1 = 1;
}
int lc22 = rand()%100;
int lc23 = rand()%3;
//int lc24 = lc23;
switch ( lc23 )
{
case 0:
if ( lc22 < 4 )
{
Option2 = 3;
}
break;
case 1:
if ( lc22 < 10 )
{
Option2 = 2;
}
break;
case 2:
if ( lc22 < 20 )
{
Option2 = 1;
}
break;
}
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, true);
#endif
::PetItemSerialCreateSend(lpObj->m_Index, -2, 0, 0, ItemNum, Level, 0,Add, Option1, Option2, -1, 0, 0);
::gObjInventoryCommit(lpObj->m_Index);
LogAddTD("[DarkHorseMix] [%s][%s] CBMix Success %d Money : %d-%d, CharmRate : %d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate,
lpObj->Money, nChaosNeedMoney, iCharmOfLuckCount);
}
else
{
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, false);
#endif
ChaosBoxInit(lpObj);
GCUserChaosBoxSend(lpObj, 1);
DataSend(lpObj->m_Index, (UCHAR*)&pMsg, pMsg.h.size);
LogAddTD("[DarkHorseMix] [%s][%s] CBMix Fail %d Money : %d-%d, CharmRate : %d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate,
lpObj->Money, nChaosNeedMoney, iCharmOfLuckCount);
lpObj->ChaosLock = FALSE;
}
}
void CChaosBox::DarkSpiritChaosMix(LPOBJ lpObj)
{
lpObj->ChaosLock = TRUE;
int ChoasGemCount = 0;
int BlessGemCount = 0;
int SoulGemCount = 0;
int CreatureGemCount = 0;
int SoulOfSpirit = 0;
int iChaosMoney = 0;
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
int iCharmOfLuckCount = 0;
int iInvalidItemCount = 0;
for ( int n=0;n<CHAOS_BOX_SIZE;n++)
{
if ( lpObj->pChaosBox[n].IsItem() == TRUE )
{
if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,13) )
{
BlessGemCount++;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,14) )
{
SoulGemCount++;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,22) ) // Creation
{
CreatureGemCount++;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(12,15) ) // SUPE CHOAS HAHAHA
{
ChoasGemCount++;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(13,31) && lpObj->pChaosBox[n].m_Level == 1 ) // Spirit
{
SoulOfSpirit++;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,53) ) // Charm Of Luck
{
iCharmOfLuckCount += (int)lpObj->pChaosBox[n].m_Durability;
}
else
{
iInvalidItemCount++;
}
}
}
if ( ChoasGemCount != 1 || BlessGemCount != 2 || SoulGemCount != 2 || CreatureGemCount != 1 || SoulOfSpirit != 1 || iInvalidItemCount > 0 )
{
DataSend(lpObj->m_Index, (UCHAR*)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
if ( iCharmOfLuckCount > 10 )
{
pMsg.Result = 0xF0;
DataSend(lpObj->m_Index, (LPBYTE)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return ;
}
LogChaosItem(lpObj, "DarkSpiritMix");
LogAddTD("[DarkSpiritMix] Chaos Mix Start");
lpObj->ChaosSuccessRate = 60;
lpObj->ChaosSuccessRate += iCharmOfLuckCount;
int nChaosNeedMoney = 1000000;
int iChaosTaxMoney = (int)((__int64)nChaosNeedMoney * (__int64)g_CastleSiegeSync.GetTaxRateChaos(lpObj->m_Index) / (__int64)100);
if ( iChaosTaxMoney < 0 )
{
iChaosTaxMoney = 0;
}
nChaosNeedMoney += iChaosTaxMoney;
if ( nChaosNeedMoney < 0 )
{
nChaosNeedMoney = 0;
}
if ( lpObj->Money < nChaosNeedMoney )
{
pMsg.Result = CB_NOT_ENOUGH_ZEN;
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
lpObj->Money -= nChaosNeedMoney;
g_CastleSiegeSync.AddTributeMoney(iChaosTaxMoney);
GCMoneySend(lpObj->m_Index, lpObj->Money);
if ( (rand()%100) < lpObj->ChaosSuccessRate )
{
int Level = 0;
int ItemType = 13;
int ItemSubType = 5;
int ItemNum = ITEMGET(ItemType, ItemSubType);
int Option1 = 0;
int Option2 = 0;
int Option3 = 0;
int Add = 0;
if ( (rand()%100) < (lpObj->ChaosSuccessRate/5+6) )
{
Add = 1;
}
if ( (rand()%5) == 0 )
{
Option1 = 1;
}
int lc22 = rand()%100;
int lc23 = rand()%3;
// int lc24 = lc23;
switch ( lc23 )
{
case 0:
if ( lc22 < 4 )
{
Option2 = 3;
}
break;
case 1:
if ( lc22 < 10 )
{
Option2 = 2;
}
break;
case 2:
if ( lc22 < 20 )
{
Option2 = 1;
}
break;
}
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, true);
#endif
::PetItemSerialCreateSend(lpObj->m_Index, -2, 0, 0, ItemNum, Level, 0, Add, Option1, Option2, -1, 0, 0);
::gObjInventoryCommit(lpObj->m_Index);
LogAddTD("[DarkSpiritMix] [%s][%s] CBMix Success %d Money : %d-%d, CharmRate : %d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate,
lpObj->Money, nChaosNeedMoney, iCharmOfLuckCount);
}
else
{
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, false);
#endif
ChaosBoxInit(lpObj);
GCUserChaosBoxSend(lpObj, 1);
DataSend(lpObj->m_Index, (UCHAR*)&pMsg, pMsg.h.size);
LogAddTD("[DarkSpiritMix] [%s][%s] CBMix Fail %d Money : %d-%d, CharmRate : %d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate,
lpObj->Money, nChaosNeedMoney, iCharmOfLuckCount);
lpObj->ChaosLock = FALSE;
}
}
void CChaosBox::BlessPotionChaosMix(LPOBJ lpObj)
{
lpObj->ChaosLock = TRUE;
int iBlessGemCount = 0;
int iChaosMoney = 0;
int iInvalidItemCount = 0;
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
for ( int n=0;n<CHAOS_BOX_SIZE;n++)
{
if ( lpObj->pChaosBox[n].IsItem() == TRUE )
{
if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,13) )
{
iBlessGemCount++;
}
else
{
iInvalidItemCount++;
}
}
}
if ( iBlessGemCount == 0 )
return;
if ( iInvalidItemCount > 0 )
return;
if ( iBlessGemCount == 0 || iInvalidItemCount > 0 )
{
DataSend(lpObj->m_Index, (LPBYTE)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
if ( iBlessGemCount > 25 )
{
MsgOutput(lpObj->m_Index, lMsg.Get(MSGGET(6,201)));
DataSend(lpObj->m_Index, (LPBYTE)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
LogChaosItem(lpObj, "BlessPotionMix");
LogAddTD("[BlessPotionMix] Chaos Mix Start");
lpObj->ChaosSuccessRate = 100;
int nChaosNeedMoney = 100000;
int iChaosTaxMoney = (int)((__int64)nChaosNeedMoney * (__int64)g_CastleSiegeSync.GetTaxRateChaos(lpObj->m_Index) / (__int64)100);
if ( iChaosTaxMoney < 0 )
{
iChaosTaxMoney = 0;
}
nChaosNeedMoney += iChaosTaxMoney;
if ( nChaosNeedMoney < 0 )
{
nChaosNeedMoney = 0;
}
if ( lpObj->Money < nChaosNeedMoney )
{
pMsg.Result = CB_NOT_ENOUGH_ZEN;
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
lpObj->Money -= nChaosNeedMoney;
g_CastleSiegeSync.AddTributeMoney(iChaosTaxMoney);
GCMoneySend(lpObj->m_Index, lpObj->Money);
if ( (rand()%100) < lpObj->ChaosSuccessRate )
{
int ItemNum = ITEMGET(14,7);
int Level = 0;
int Dur = iBlessGemCount * 10;
ItemSerialCreateSend(lpObj->m_Index, -1, 0, 0, ItemNum, Level, Dur, 0, 0, 0, -1, 0, 0);
::gObjInventoryCommit(lpObj->m_Index);
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, true);
#endif
LogAddTD("[BlessPotionMix] [%s][%s] CBMix Success %d Money : %d-%d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate,
lpObj->Money, nChaosNeedMoney);
}
else
{
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, false);
#endif
ChaosBoxInit(lpObj);
::GCUserChaosBoxSend(lpObj, 1);
DataSend(lpObj->m_Index, (UCHAR*)&pMsg, pMsg.h.size);
LogAddTD("[BlessPotionMix] [%s][%s] CBMix Fail %d Money : %d-%d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate,
lpObj->Money, nChaosNeedMoney);
lpObj->ChaosLock = FALSE;
}
}
void CChaosBox::SoulPotionChaosMix(LPOBJ lpObj)
{
lpObj->ChaosLock = TRUE;
int iSoulGemCount = 0;
int iChaosMoney = 0;
int iInvalidItemCount = 0;
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
for ( int n=0;n<CHAOS_BOX_SIZE;n++)
{
if ( lpObj->pChaosBox[n].IsItem() == TRUE )
{
if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,14) )
{
iSoulGemCount++;
}
else
{
iInvalidItemCount++;
}
}
}
if ( iSoulGemCount == 0 )
return;
if ( iInvalidItemCount > 0 )
return;
if ( iSoulGemCount > 25 )
{
MsgOutput(lpObj->m_Index, lMsg.Get(MSGGET(6,201)));
DataSend(lpObj->m_Index, (LPBYTE)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
LogChaosItem(lpObj, "SoulPotionMix");
LogAddTD("[SoulPotionMix] Chaos Mix Start");
lpObj->ChaosSuccessRate = 100;
int nChaosNeedMoney = 50000;
int iChaosTaxMoney = (int)((__int64)nChaosNeedMoney * (__int64)g_CastleSiegeSync.GetTaxRateChaos(lpObj->m_Index) / (__int64)100);
if ( iChaosTaxMoney < 0 )
{
iChaosTaxMoney = 0;
}
nChaosNeedMoney += iChaosTaxMoney;
if ( nChaosNeedMoney < 0 )
{
nChaosNeedMoney = 0;
}
if ( lpObj->Money < nChaosNeedMoney )
{
pMsg.Result = CB_NOT_ENOUGH_ZEN;
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
lpObj->Money -= nChaosNeedMoney;
g_CastleSiegeSync.AddTributeMoney(iChaosTaxMoney);
GCMoneySend(lpObj->m_Index, lpObj->Money);
if ( (rand()%100) < lpObj->ChaosSuccessRate )
{
int ItemNum = ITEMGET(14,7);
int Level = 1;
int Dur = iSoulGemCount * 10;
ItemSerialCreateSend(lpObj->m_Index, -1, 0, 0, ItemNum, Level, Dur, 0, 0, 0, -1, 0, 0);
::gObjInventoryCommit(lpObj->m_Index);
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, true);
#endif
LogAddTD("[SoulPotionMix] [%s][%s] CBMix Success %d Money : %d-%d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate,
lpObj->Money, nChaosNeedMoney);
}
else
{
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, false);
#endif
ChaosBoxInit(lpObj);
::GCUserChaosBoxSend(lpObj, 1);
DataSend(lpObj->m_Index, (UCHAR*)&pMsg, pMsg.h.size);
LogAddTD("[SoulPotionMix] [%s][%s] CBMix Fail %d Money : %d-%d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate,
lpObj->Money, nChaosNeedMoney);
lpObj->ChaosLock = FALSE;
}
}
void CChaosBox::LifeStoneChaosMix(LPOBJ lpObj)
{
lpObj->ChaosLock = TRUE;
int iChoasGemCount = 0;
int iBlessGemCount = 0;
int iSoulGemCount = 0;
int iProtectionGemCount = 0;
int iInvalidItemCount = 0;
int iChaosMoney = 0;
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
for ( int n=0;n<CHAOS_BOX_SIZE;n++)
{
if ( lpObj->pChaosBox[n].IsItem() == TRUE )
{
if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,13) )
{
iBlessGemCount++;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,14) )
{
iSoulGemCount++;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,31) ) // Guardian Jewel
{
iProtectionGemCount++;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(12,15) ) // Habla pe super CHOAS
{
iChoasGemCount++;
}
else
{
iInvalidItemCount++;
}
}
}
if ( iChoasGemCount != 1 || iBlessGemCount != 5 || iSoulGemCount != 5 || iProtectionGemCount != 1 || iInvalidItemCount > 0 )
{
DataSend(lpObj->m_Index, (UCHAR*)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
LogChaosItem(lpObj, "LifeStoneMix");
LogAddTD("[LifeStoneMix] Chaos Mix Start");
lpObj->ChaosSuccessRate = 100;
int nChaosNeedMoney = 5000000;
int iChaosTaxMoney = (int)((__int64)nChaosNeedMoney * (__int64)g_CastleSiegeSync.GetTaxRateChaos(lpObj->m_Index) / (__int64)100);
if ( iChaosTaxMoney < 0 )
{
iChaosTaxMoney = 0;
}
nChaosNeedMoney += iChaosTaxMoney;
if ( nChaosNeedMoney < 0 )
{
nChaosNeedMoney = 0;
}
if ( lpObj->Money < nChaosNeedMoney )
{
pMsg.Result = CB_NOT_ENOUGH_ZEN;
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
lpObj->Money -= nChaosNeedMoney;
g_CastleSiegeSync.AddTributeMoney(iChaosTaxMoney);
GCMoneySend(lpObj->m_Index, lpObj->Money);
if ( (rand()%100) < lpObj->ChaosSuccessRate )
{
ItemSerialCreateSend(lpObj->m_Index, -1, 0, 0, ITEMGET(13,11) , 1, 0, 0, 0, 0, -1, 0, 0);
::gObjInventoryCommit(lpObj->m_Index);
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, true);
#endif
LogAddTD("[LifeStoneMix] [%s][%s] CBMix Success %d Money : %d-%d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate,
lpObj->Money, nChaosNeedMoney);
}
else
{
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, false);
#endif
ChaosBoxInit(lpObj);
::GCUserChaosBoxSend(lpObj, 1);
DataSend(lpObj->m_Index, (UCHAR*)&pMsg, pMsg.h.size);
LogAddTD("[LifeStoneMix] [%s][%s] CBMix Fail %d Money : %d-%d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate,
lpObj->Money, nChaosNeedMoney);
lpObj->ChaosLock = FALSE;
}
}
void CChaosBox::HiddenTreasureBoxItemMix(LPOBJ lpObj)
{
lpObj->ChaosLock = TRUE;
int iBlueCrystal = 0;
int iRedCrystal = 0;
int iBlackCrystal = 0;
int iInvalidItemCount = 0;
int iChaosMoney = 0;
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
for ( int n=0;n<CHAOS_BOX_SIZE;n++)
{
if ( lpObj->pChaosBox[n].IsItem() == TRUE )
{
if ( lpObj->pChaosBox[n].m_Type == ITEMGET(12,26) )
{
switch ( lpObj->pChaosBox[n].m_Level )
{
case 1:
iRedCrystal++;
break;
case 2:
iBlueCrystal++;
break;
case 3:
iBlackCrystal++;
break;
}
}
else
{
iInvalidItemCount++;
}
}
}
int iCrystalMixType = -1;
if ( iInvalidItemCount == 0 )
{
if ( iBlueCrystal == 7 )
{
if ( iRedCrystal == 0 && iBlackCrystal == 0 )
{
iCrystalMixType = 0;
lpObj->ChaosSuccessRate = 100;
}
}
else if ( iRedCrystal == 5 )
{
if ( iBlueCrystal == 0 && iBlackCrystal == 0 )
{
iCrystalMixType = 1;
lpObj->ChaosSuccessRate = 100;
}
}
else if ( iBlackCrystal == 3 )
{
if ( iRedCrystal == 0 && iBlueCrystal == 0 )
{
iCrystalMixType = 2;
lpObj->ChaosSuccessRate = 100;
}
}
else if ( iBlueCrystal == 1 && iRedCrystal == 1 && iBlackCrystal == 1 )
{
{
iCrystalMixType = 3;
lpObj->ChaosSuccessRate = 100;
}
}
else
{
LogAddTD("[Hidden TreasureBox Event] [%s][%s] Item Mix Failed",
lpObj->AccountID, lpObj->Name);
DataSend(lpObj->m_Index, (UCHAR*)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
}
}
else
{
LogAddTD("[Hidden TreasureBox Event] [%s][%s] Item Mix Failed",
lpObj->AccountID, lpObj->Name);
DataSend(lpObj->m_Index, (UCHAR*)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
LogChaosItem(lpObj, "Hidden TreasureBox Mix");
LogAddTD("[Hidden TreasureBox Event] [%s][%s] Chaos Mix Start",
lpObj->AccountID, lpObj->Name);
if ( (rand()%100) < lpObj->ChaosSuccessRate )
{
switch ( iCrystalMixType )
{
case 0: case 1: case 2:
ItemSerialCreateSend(lpObj->m_Index, -1, 0, 0, ITEMGET(12,26) , 4, 1, 0, 0, 0, -1, 0, 0);
break;
case 3:
ItemSerialCreateSend(lpObj->m_Index, -1, 0, 0, ITEMGET(12,26) , 5, 1, 0, 0, 0, -1, 0, 0);
break;
default:
LogAddTD("[Hidden TreasureBox Event] [%s][%s] CBMix Failed - iCrystalMixType is wrong : %d",
lpObj->AccountID, lpObj->Name, iCrystalMixType);
DataSend(lpObj->m_Index, (UCHAR*)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, true);
#endif
::gObjInventoryCommit(lpObj->m_Index);
LogAddTD("[Hidden TreasureBox Event] [%s][%s] CBMix Success:%d Type:%d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate, iCrystalMixType);
}
else
{
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, false);
#endif
LogAddTD("[Hidden TreasureBox Event] [%s][%s] CBMix Fail Rate:%d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate);
ChaosBoxInit(lpObj);
::GCUserChaosBoxSend(lpObj, 1);
DataSend(lpObj->m_Index, (UCHAR*)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
}
lpObj->ChaosLock = FALSE;
}
void CChaosBox::Fenrir_01Level_Mix(LPOBJ lpObj)
{
lpObj->ChaosLock = TRUE;
int iStuffCount_01 = 0;
int iStuffCount_02 = 0;
int iChaosGemCount = 0;
int iInvalidItemCount = 0;
int iChaosMoney = 0;
int iCharmOfLuckCount = 0;
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
for ( int n=0;n<CHAOS_BOX_SIZE;n++)
{
if ( lpObj->pChaosBox[n].IsItem() == TRUE )
{
if ( lpObj->pChaosBox[n].m_Type == ITEMGET(13,32) )
{
iStuffCount_01 += (int)lpObj->pChaosBox[n].m_Durability;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(13,33) )
{
iStuffCount_02 += (int)lpObj->pChaosBox[n].m_Durability;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(12,15) )
{
iChaosGemCount++;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,53) ) // Charm Of Luck
{
iCharmOfLuckCount += (int)lpObj->pChaosBox[n].m_Durability;
}
else
{
iInvalidItemCount++;
}
}
}
if ( iStuffCount_01 != 20 || iStuffCount_02 != 20 || iChaosGemCount != 1 || iInvalidItemCount > 0 )
{
DataSend(lpObj->m_Index, (UCHAR*)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
if ( iCharmOfLuckCount > 10 )
{
pMsg.Result = 0xF0;
DataSend(lpObj->m_Index, (LPBYTE)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
LogChaosItem(lpObj, "Fenrir_01Level_Mix");
LogAddTD("[Fenrir Mix][Level 01] Chaos Mix Start");
lpObj->ChaosSuccessRate = g_iFenrir_01Level_MixRate;
lpObj->ChaosSuccessRate += iCharmOfLuckCount;
int nChaosNeedMoney = 0;
int iChaosTaxMoney = (int)((__int64)nChaosNeedMoney * (__int64)g_CastleSiegeSync.GetTaxRateChaos(lpObj->m_Index) / (__int64)100);
if ( iChaosTaxMoney < 0 )
{
iChaosTaxMoney = 0;
}
nChaosNeedMoney += iChaosTaxMoney;
if ( nChaosNeedMoney < 0 )
{
nChaosNeedMoney = 0;
}
if ( lpObj->Money < nChaosNeedMoney )
{
pMsg.Result = CB_NOT_ENOUGH_ZEN;
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
lpObj->Money -= nChaosNeedMoney;
g_CastleSiegeSync.AddTributeMoney(iChaosTaxMoney);
GCMoneySend(lpObj->m_Index, lpObj->Money);
if ( (rand()%100) < lpObj->ChaosSuccessRate )
{
int type = ITEMGET(13,35);
int level = 0;
int dur = 1;
ItemSerialCreateSend(lpObj->m_Index, -1, 0, 0, type , level, dur, 0, 0, 0, -1, 0, 0);
::gObjInventoryCommit(lpObj->m_Index);
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, true);
#endif
LogAddTD("[Fenrir Mix][Level 01] [%s][%s] CBMix Success %d Money : %d-%d, CharmRate : %d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate, lpObj->Money, nChaosNeedMoney,
iCharmOfLuckCount);
}
else
{
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, false);
#endif
ChaosBoxInit(lpObj);
::GCUserChaosBoxSend(lpObj, 0);
DataSend(lpObj->m_Index, (UCHAR*)&pMsg, pMsg.h.size);
LogAddTD("[Fenrir Mix][Level 01] [%s][%s] CBMix Fail %d Money : %d-%d, CharmRate : %d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate, lpObj->Money, nChaosNeedMoney,
iCharmOfLuckCount);
lpObj->ChaosLock = FALSE;
}
}
void CChaosBox::Fenrir_02Level_Mix(LPOBJ lpObj)
{
lpObj->ChaosLock = TRUE;
int iStuffCount_01 = 0;
int iStuffCount_02 = 0;
int iChaosGemCount = 0;
int iInvalidItemCount = 0;
int iChaosMoney = 0;
int iCharmOfLuckCount = 0;
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
for ( int n=0;n<CHAOS_BOX_SIZE;n++)
{
if ( lpObj->pChaosBox[n].IsItem() == TRUE )
{
if ( lpObj->pChaosBox[n].m_Type == ITEMGET(13,34) )
{
iStuffCount_01 += (int)lpObj->pChaosBox[n].m_Durability;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(13,35) )
{
iStuffCount_02 ++;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(12,15) )
{
iChaosGemCount++;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,53) ) // Charm Of Luck
{
iCharmOfLuckCount += (int)lpObj->pChaosBox[n].m_Durability;
}
else
{
iInvalidItemCount++;
}
}
}
if ( iStuffCount_01 != 10 || iStuffCount_02 != 5 || iChaosGemCount != 1 || iInvalidItemCount > 0 )
{
DataSend(lpObj->m_Index, (UCHAR*)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
if ( iCharmOfLuckCount > 10 )
{
pMsg.Result = 0xF0;
DataSend(lpObj->m_Index, (LPBYTE)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
LogChaosItem(lpObj, "Fenrir_02Level_Mix");
LogAddTD("[Fenrir Mix][Level 02] Chaos Mix Start");
lpObj->ChaosSuccessRate = g_iFenrir_02Level_MixRate;
lpObj->ChaosSuccessRate += iCharmOfLuckCount;
int nChaosNeedMoney = 0;
int iChaosTaxMoney = (int)((__int64)nChaosNeedMoney * (__int64)g_CastleSiegeSync.GetTaxRateChaos(lpObj->m_Index) / (__int64)100);
if ( iChaosTaxMoney < 0 )
{
iChaosTaxMoney = 0;
}
nChaosNeedMoney += iChaosTaxMoney;
if ( nChaosNeedMoney < 0 )
{
nChaosNeedMoney = 0;
}
if ( lpObj->Money < nChaosNeedMoney )
{
pMsg.Result = CB_NOT_ENOUGH_ZEN;
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
lpObj->Money -= nChaosNeedMoney;
g_CastleSiegeSync.AddTributeMoney(iChaosTaxMoney);
GCMoneySend(lpObj->m_Index, lpObj->Money);
if ( (rand()%100) < lpObj->ChaosSuccessRate )
{
int type = ITEMGET(13,36);
int level = 0;
int dur = 1;
ItemSerialCreateSend(lpObj->m_Index, -1, 0, 0, type , level, dur, 0, 0, 0, -1, 0, 0);
::gObjInventoryCommit(lpObj->m_Index);
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, true);
#endif
LogAddTD("[Fenrir Mix][Level 02] [%s][%s] CBMix Success %d Money : %d-%d, CharmRate : %d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate, lpObj->Money, nChaosNeedMoney,
iCharmOfLuckCount);
}
else
{
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, false);
#endif
ChaosBoxInit(lpObj);
::GCUserChaosBoxSend(lpObj, 0);
DataSend(lpObj->m_Index, (UCHAR*)&pMsg, pMsg.h.size);
LogAddTD("[Fenrir Mix][Level 02] [%s][%s] CBMix Fail %d Money : %d-%d, CharmRate : %d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate, lpObj->Money, nChaosNeedMoney,
iCharmOfLuckCount);
lpObj->ChaosLock = FALSE;
}
}
void CChaosBox::Fenrir_03Level_Mix(LPOBJ lpObj)
{
lpObj->ChaosLock = TRUE;
int iStuffCount_01 = 0;
int iLifeGemCount = 0;
int iChaosGemCount = 0;
int iInvalidItemCount = 0;
int iChaosMoney = 0;
int iCharmOfLuckCount = 0;
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
for ( int n=0;n<CHAOS_BOX_SIZE;n++)
{
if ( lpObj->pChaosBox[n].IsItem() == TRUE )
{
if ( lpObj->pChaosBox[n].m_Type == ITEMGET(13,36) )
{
iStuffCount_01 ++;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,16) )
{
iLifeGemCount ++;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(12,15) )
{
iChaosGemCount++;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,53) ) // Charm Of Luck
{
iCharmOfLuckCount += (int)lpObj->pChaosBox[n].m_Durability;
}
else
{
iInvalidItemCount++;
}
}
}
if ( iStuffCount_01 != 1 || iLifeGemCount != 3 || iChaosGemCount != 1 || iInvalidItemCount > 0 )
{
DataSend(lpObj->m_Index, (UCHAR*)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
if ( iCharmOfLuckCount > 10 )
{
pMsg.Result = 0xF0;
DataSend(lpObj->m_Index, (LPBYTE)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
LogChaosItem(lpObj, "Fenrir_03Level_Mix");
LogAddTD("[Fenrir Mix][Level 03] Chaos Mix Start");
lpObj->ChaosSuccessRate = g_iFenrir_03Level_MixRate;
lpObj->ChaosSuccessRate += iCharmOfLuckCount;
int nChaosNeedMoney = 10000000;
int iChaosTaxMoney = (int)((__int64)nChaosNeedMoney * (__int64)g_CastleSiegeSync.GetTaxRateChaos(lpObj->m_Index) / (__int64)100);
if ( iChaosTaxMoney < 0 )
{
iChaosTaxMoney = 0;
}
nChaosNeedMoney += iChaosTaxMoney;
if ( nChaosNeedMoney < 0 )
{
nChaosNeedMoney = 0;
}
if ( lpObj->Money < nChaosNeedMoney )
{
pMsg.Result = CB_NOT_ENOUGH_ZEN;
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
lpObj->Money -= nChaosNeedMoney;
g_CastleSiegeSync.AddTributeMoney(iChaosTaxMoney);
GCMoneySend(lpObj->m_Index, lpObj->Money);
if ( (rand()%100) < lpObj->ChaosSuccessRate )
{
int type = ITEMGET(13,37);
int level = 0;
int dur = 255;
int op1 = 1;
ItemSerialCreateSend(lpObj->m_Index, -1, 0, 0, type , level, dur, op1, 0, 0, -1, 0, 0);
::gObjInventoryCommit(lpObj->m_Index);
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, true);
#endif
LogAddTD("[Fenrir Mix][Level 03] [%s][%s] CBMix Success %d Money : %d-%d, CharmRate : %d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate, lpObj->Money, nChaosNeedMoney,
iCharmOfLuckCount);
}
else
{
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, false);
#endif
ChaosBoxInit(lpObj);
::GCUserChaosBoxSend(lpObj, 0);
DataSend(lpObj->m_Index, (UCHAR*)&pMsg, pMsg.h.size);
LogAddTD("[Fenrir Mix][Level 03] [%s][%s] CBMix Fail %d Money : %d-%d, CharmRate : %d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate, lpObj->Money, nChaosNeedMoney,
iCharmOfLuckCount);
lpObj->ChaosLock = FALSE;
}
}
void CChaosBox::Fenrir_04Upgrade_Mix(LPOBJ lpObj)
{
lpObj->ChaosLock = TRUE;
int iStuffCount_01 = 0;
int iLifeGemCount = 0;
int iChaosGemCount = 0;
int iAttackStuffCount = 0;
int iDefendStuffCount = 0;
int iAttackStuffPrice = 0;
int iDefendStuffPrice = 0;
int iInvalidItemCount = 0;
int iChaosMoney = 0;
BOOL bFenrirDamageInc = FALSE;
BOOL bFenrirDamageDec = FALSE;
int iCharmOfLuckCount = 0;
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
for ( int n=0;n<CHAOS_BOX_SIZE;n++)
{
if ( lpObj->pChaosBox[n].IsItem() == TRUE )
{
if ( lpObj->pChaosBox[n].m_Type == ITEMGET(13,37) )
{
iStuffCount_01 ++;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,16) )
{
iLifeGemCount ++;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(12,15) )
{
iChaosGemCount++;
}
else if ( lpObj->pChaosBox[n].m_Type >= ITEMGET(0,0) &&
lpObj->pChaosBox[n].m_Type < ITEMGET(6,0) &&
lpObj->pChaosBox[n].m_Level >= 4 &&
lpObj->pChaosBox[n].m_Option3 >= 1)
{
iAttackStuffCount++;
iAttackStuffPrice += lpObj->pChaosBox[n].m_BuyMoney;
}
else if ( lpObj->pChaosBox[n].m_Type >= ITEMGET(6,0) &&
lpObj->pChaosBox[n].m_Type < ITEMGET(12,0) &&
lpObj->pChaosBox[n].m_Level >= 4 &&
lpObj->pChaosBox[n].m_Option3 >= 1)
{
iDefendStuffCount++;
iDefendStuffPrice += lpObj->pChaosBox[n].m_BuyMoney;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,53) ) // Charm Of Luck
{
iCharmOfLuckCount += (int)lpObj->pChaosBox[n].m_Durability;
}
else
{
iInvalidItemCount++;
}
}
}
if ( iStuffCount_01 != 1 || iLifeGemCount != 5 || iChaosGemCount != 1 || ( iAttackStuffCount == 0 && iDefendStuffCount == 0 ) || iInvalidItemCount > 0 )
{
DataSend(lpObj->m_Index, (UCHAR*)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
if ( iCharmOfLuckCount > 10 )
{
pMsg.Result = 0xF0;
DataSend(lpObj->m_Index, (LPBYTE)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
if ( iAttackStuffCount > 0 )
{
bFenrirDamageInc = TRUE;
iChaosMoney = iAttackStuffPrice;
}
if ( iDefendStuffCount > 0 )
{
bFenrirDamageDec = TRUE;
iChaosMoney = iDefendStuffPrice;
}
if ( bFenrirDamageInc && bFenrirDamageDec )
{
DataSend(lpObj->m_Index, (LPBYTE)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
if ( !bFenrirDamageInc && !bFenrirDamageDec )
{
DataSend(lpObj->m_Index, (LPBYTE)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
LogChaosItem(lpObj, "Fenrir_04Level_Mix");
LogAddTD("[Fenrir Mix][Level 04] Chaos Mix Start");
int nChaosNeedMoney = 10000000;
int iChaosTaxMoney = (int)((__int64)nChaosNeedMoney * (__int64)g_CastleSiegeSync.GetTaxRateChaos(lpObj->m_Index) / (__int64)100);
if ( iChaosTaxMoney < 0 )
{
iChaosTaxMoney = 0;
}
nChaosNeedMoney += iChaosTaxMoney;
if ( nChaosNeedMoney < 0 )
{
nChaosNeedMoney = 0;
}
if ( lpObj->Money < nChaosNeedMoney )
{
pMsg.Result = CB_NOT_ENOUGH_ZEN;
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
lpObj->Money -= nChaosNeedMoney;
g_CastleSiegeSync.AddTributeMoney(iChaosTaxMoney);
GCMoneySend(lpObj->m_Index, lpObj->Money);
if ( iChaosMoney > 1000000 )
iChaosMoney = 1000000;
lpObj->ChaosSuccessRate = iChaosMoney * 100 / 1000000;
if ( lpObj->ChaosSuccessRate > 79 )
lpObj->ChaosSuccessRate = 79;
lpObj->ChaosSuccessRate += iCharmOfLuckCount;
if ( (rand()%100) < lpObj->ChaosSuccessRate )
{
int type = ITEMGET(13,37);
int level = 0;
int dur = 255;
int op1 = 1;
int nop = 0;
if ( bFenrirDamageInc )
{
nop |= 1;
}
if ( bFenrirDamageDec )
{
nop |= 2;
}
ItemSerialCreateSend(lpObj->m_Index, -1, 0, 0, type , level, dur, op1, 0, 0, -1, nop, 0);
::gObjInventoryCommit(lpObj->m_Index);
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, true);
#endif
LogAddTD("[Fenrir Mix][Level 04] [%s][%s] CBMix Success %d Money : %d-%d, CharmRate : %d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate, lpObj->Money, nChaosNeedMoney,
iCharmOfLuckCount);
}
else
{
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, false);
#endif
ChaosBoxInit(lpObj);
::GCUserChaosBoxSend(lpObj, 0);
DataSend(lpObj->m_Index, (UCHAR*)&pMsg, pMsg.h.size);
LogAddTD("[Fenrir Mix][Level 04] [%s][%s] CBMix Fail %d Money : %d-%d, CharmRate : %d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate, lpObj->Money, nChaosNeedMoney,
iCharmOfLuckCount);
lpObj->ChaosLock = FALSE;
}
}
void CChaosBox::ShieldPotionLv1_Mix(LPOBJ lpObj)
{
int iHealthPotionCount = 0;
int iInvalidItemCount = 0;
int iChaosMixPrice = 0;
int iCharmOfLuckCount = 0;
if ( g_ShieldSystemOn == FALSE )
return;
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
for ( int n=0;n<CHAOS_BOX_SIZE;n++)
{
if ( lpObj->pChaosBox[n].IsItem() == TRUE )
{
if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,3) )
{
iHealthPotionCount+= (int)lpObj->pChaosBox[n].m_Durability;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,53) ) // Charm Of Luck
{
iCharmOfLuckCount += (int)lpObj->pChaosBox[n].m_Durability;
}
else
{
iInvalidItemCount++;
}
}
}
if ( iInvalidItemCount > 0 || iHealthPotionCount != 3 )
{
DataSend(lpObj->m_Index, (LPBYTE)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
if ( iCharmOfLuckCount > 10 )
{
pMsg.Result = 0xF0;
DataSend(lpObj->m_Index, (LPBYTE)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
iChaosMixPrice = g_iShieldPotionLv1MixMoney;
int iChaosTaxMoney = iChaosMixPrice * g_CastleSiegeSync.GetTaxRateChaos(lpObj->m_Index) / 100;
if ( iChaosTaxMoney < 0 )
{
iChaosTaxMoney = 0;
}
iChaosMixPrice += iChaosTaxMoney;
if ( iChaosMixPrice < 0 )
{
iChaosMixPrice = 0;
}
if ( lpObj->Money < iChaosMixPrice )
{
pMsg.Result = CB_NOT_ENOUGH_ZEN;
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
lpObj->Money -= iChaosMixPrice;
g_CastleSiegeSync.AddTributeMoney(iChaosTaxMoney);
GCMoneySend(lpObj->m_Index, lpObj->Money);
LogChaosItem(lpObj, "PotionMix][ShieldPotion Lv1 Mix");
LogAddTD("[PotionMix][ShieldPotion Lv1 Mix] - Mix Start");
int iRate = rand() % 100;
iRate -= iCharmOfLuckCount;
if ( iRate < g_iShieldPotionLv1MixSuccessRate )
{
int ItemNum = ITEMGET(14,35);
ItemSerialCreateSend(lpObj->m_Index, -1, 0, 0, ItemNum, 0, 1, 0, 0, 0, lpObj->m_Index, 0, 0);
::gObjInventoryCommit(lpObj->m_Index);
LogAddTD("[ChaosMix][Shield Potion] Lv1 Potion Mix Success [%s][%s], Money(%d-%d), CharmRate : %d",
lpObj->AccountID, lpObj->Name, lpObj->Money, iChaosMixPrice, iCharmOfLuckCount);
}
else
{
ChaosBoxInit(lpObj);
::GCUserChaosBoxSend(lpObj, 0);
DataSend(lpObj->m_Index, (UCHAR*)&pMsg, pMsg.h.size);
LogAddTD("[ChaosMix][Shield Potion] Lv1 Potion Mix [%s][%s] CBMix Fail %d Money : %d-%d, CharmRate : %d",
lpObj->AccountID, lpObj->Name, g_iShieldPotionLv1MixSuccessRate,
lpObj->Money, iChaosMixPrice, iCharmOfLuckCount);
}
lpObj->ChaosLock = FALSE;
}
void CChaosBox::ShieldPotionLv2_Mix(LPOBJ lpObj)
{
int iHealthPotionCount = 0;
int iInvalidItemCount = 0;
int iChaosMixPrice = 0;
int iCharmOfLuckCount = 0;
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
for ( int n=0;n<CHAOS_BOX_SIZE;n++)
{
if ( lpObj->pChaosBox[n].IsItem() == TRUE )
{
if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,38) )
{
iHealthPotionCount+= (int)lpObj->pChaosBox[n].m_Durability;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,53) ) // Charm Of Luck
{
iCharmOfLuckCount += (int)lpObj->pChaosBox[n].m_Durability;
}
else
{
iInvalidItemCount++;
}
}
}
if ( iInvalidItemCount > 0 || iHealthPotionCount != 3 )
{
DataSend(lpObj->m_Index, (LPBYTE)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
if ( iCharmOfLuckCount > 10 )
{
pMsg.Result = 0xF0;
DataSend(lpObj->m_Index, (LPBYTE)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
iChaosMixPrice = g_iShieldPotionLv2MixMoney;
int iChaosTaxMoney = iChaosMixPrice * g_CastleSiegeSync.GetTaxRateChaos(lpObj->m_Index) / 100;
if ( iChaosTaxMoney < 0 )
{
iChaosTaxMoney = 0;
}
iChaosMixPrice += iChaosTaxMoney;
if ( iChaosMixPrice < 0 )
{
iChaosMixPrice = 0;
}
if ( lpObj->Money < iChaosMixPrice )
{
pMsg.Result = CB_NOT_ENOUGH_ZEN;
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
lpObj->Money -= iChaosMixPrice;
g_CastleSiegeSync.AddTributeMoney(iChaosTaxMoney);
LogChaosItem(lpObj, "PotionMix][ShieldPotion Lv2 Mix");
LogAddTD("[PotionMix][ShieldPotion Lv2 Mix] - Mix Start");
GCMoneySend(lpObj->m_Index, lpObj->Money);
int iRate = rand() % 100;
iRate -= iCharmOfLuckCount;
if ( iRate < g_iShieldPotionLv2MixSuccessRate )
{
int ItemNum = ITEMGET(14,36);
ItemSerialCreateSend(lpObj->m_Index, -1, 0, 0, ItemNum, 0, 1, 0, 0, 0, lpObj->m_Index, 0, 0);
::gObjInventoryCommit(lpObj->m_Index);
LogAddTD("[ChaosMix][Shield Potion] Lv2 Potion Mix Success [%s][%s], Money(%d-%d), CharmRate : %d",
lpObj->AccountID, lpObj->Name, lpObj->Money, iChaosMixPrice, iCharmOfLuckCount);
}
else
{
ChaosBoxInit(lpObj);
::GCUserChaosBoxSend(lpObj, 0);
DataSend(lpObj->m_Index, (UCHAR*)&pMsg, pMsg.h.size);
LogAddTD("[ChaosMix][Shield Potion] Lv2 Potion Mix [%s][%s] CBMix Fail %d Money : %d-%d, CharmRate : %d",
lpObj->AccountID, lpObj->Name, g_iShieldPotionLv2MixSuccessRate,
lpObj->Money, iChaosMixPrice, iCharmOfLuckCount);
}
lpObj->ChaosLock = FALSE;
}
void CChaosBox::ShieldPotionLv3_Mix(LPOBJ lpObj)
{
int iHealthPotionCount = 0;
int iInvalidItemCount = 0;
int iChaosMixPrice = 0;
int iCharmOfLuckCount = 0;
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
for ( int n=0;n<CHAOS_BOX_SIZE;n++)
{
if ( lpObj->pChaosBox[n].IsItem() == TRUE )
{
if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,39) )
{
iHealthPotionCount+= (int)lpObj->pChaosBox[n].m_Durability;
}
else if ( lpObj->pChaosBox[n].m_Type == ITEMGET(14,53) ) // Charm Of Luck
{
iCharmOfLuckCount += (int)lpObj->pChaosBox[n].m_Durability;
}
else
{
iInvalidItemCount++;
}
}
}
if ( iInvalidItemCount > 0 || iHealthPotionCount != 3 )
{
DataSend(lpObj->m_Index, (LPBYTE)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
if ( iCharmOfLuckCount > 10 )
{
pMsg.Result = 0xF0;
DataSend(lpObj->m_Index, (LPBYTE)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
iChaosMixPrice = g_iShieldPotionLv3MixMoney;
int iChaosTaxMoney = iChaosMixPrice * g_CastleSiegeSync.GetTaxRateChaos(lpObj->m_Index) / 100;
if ( iChaosTaxMoney < 0 )
{
iChaosTaxMoney = 0;
}
iChaosMixPrice += iChaosTaxMoney;
if ( iChaosMixPrice < 0 )
{
iChaosMixPrice = 0;
}
if ( lpObj->Money < iChaosMixPrice )
{
pMsg.Result = CB_NOT_ENOUGH_ZEN;
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
lpObj->Money -= iChaosMixPrice;
g_CastleSiegeSync.AddTributeMoney(iChaosTaxMoney);
GCMoneySend(lpObj->m_Index, lpObj->Money);
LogChaosItem(lpObj, "PotionMix][ShieldPotion Lv3 Mix");
LogAddTD("[PotionMix][ShieldPotion Lv3 Mix] - Mix Start");
int iRate = rand() % 100;
iRate -= iCharmOfLuckCount;
if ( iRate < g_iShieldPotionLv3MixSuccessRate )
{
int ItemNum = ITEMGET(14,37);
ItemSerialCreateSend(lpObj->m_Index, -1, 0, 0, ItemNum, 0, 1, 0, 0, 0, lpObj->m_Index, 0, 0);
::gObjInventoryCommit(lpObj->m_Index);
LogAddTD("[ChaosMix][Shield Potion] Lv3 Potion Mix Success [%s][%s], Money(%d-%d), CharmRate : %d",
lpObj->AccountID, lpObj->Name, lpObj->Money, iChaosMixPrice, iCharmOfLuckCount);
}
else
{
ChaosBoxInit(lpObj);
::GCUserChaosBoxSend(lpObj, 0);
DataSend(lpObj->m_Index, (UCHAR*)&pMsg, pMsg.h.size);
LogAddTD("[ChaosMix][Shield Potion] Lv3 Potion Mix [%s][%s] CBMix Fail %d Money : %d-%d, CharmRate : %d",
lpObj->AccountID, lpObj->Name, g_iShieldPotionLv3MixSuccessRate,
lpObj->Money, iChaosMixPrice, iCharmOfLuckCount);
}
lpObj->ChaosLock = FALSE;
}
int CChaosBox::IsCondorItem(int iType)
{
if( iType == iCondorStone ||
iType == iCondorFeather )
{
return TRUE;
}
return FALSE;
}
int CChaosBox::Is1stLevelWing(int iType)
{
if( iType == ITEMGET(12,0) ||
iType == ITEMGET(12,1) ||
iType == ITEMGET(12,2) ||
iType == ITEMGET(12,41) )
{
return TRUE;
}
return FALSE;
}
int CChaosBox::Is2ndLevelWing(int iType)
{
if( iType == ITEMGET(12,3) ||
iType == ITEMGET(12,4) ||
iType == ITEMGET(12,5) ||
iType == ITEMGET(12,6) ||
iType == ITEMGET(13,30) ||
iType == ITEMGET(12,42) ||
iType == ITEMGET(12,49) )
{
return TRUE;
}
return FALSE;
}
int CChaosBox::CheckItemOptions(CItem* lpItem,short iLevel,BYTE iOption1,BYTE iOption2,BYTE iOption3,BYTE iSetOption,BYTE iExcOption)
{
if( lpItem == FALSE )
{
return false;
}
if( iLevel != FALSE )
{
if( lpItem->m_Level < iLevel )
{
return FALSE;
}
}
if( iOption1 != FALSE )
{
if( lpItem->m_Option1 < iOption1 )
{
return FALSE;
}
}
if( iOption2 != FALSE )
{
if( lpItem->m_Option2 < iOption2 )
{
return FALSE;
}
}
if( iOption3 != FALSE )
{
if( lpItem->m_Option3 < iOption3 )
{
return FALSE;
}
}
if( iSetOption != FALSE )
{
if( lpItem->m_SetOption == FALSE )
{
return FALSE;
}
}
if( iExcOption != FALSE )
{
if( lpItem->m_NewOption == FALSE )
{
return FALSE;
}
}
return TRUE;
}
#if (GS_CASTLE == 1)
void CChaosBox::CastleSpecialItemMix(LPOBJ lpObj)
{
lpObj->ChaosLock = TRUE;
int iDefendGemCount = 0;
int iBlessGemMixCount = 0;
int iSoulGemMixCount = 0;
int iInvalidItemCount =0;
int iChaosMoney = 0;
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((PBYTE)&pMsg,0x86,sizeof(pMsg));
pMsg.Result = CB_ERROR;
if(g_CastleSiege.CheckCastleOwnerMember(lpObj->m_Index) != FALSE )
{
if(lpObj->GuildStatus != G_MASTER)
{
LogAddTD("[CastleSpecialMix] [%s][%s] Item Mix Failed - No Auth",
lpObj->AccountID,lpObj->Name);
DataSend(lpObj->m_Index,(PBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
}
else
{
LogAddTD("[CastleSpecialMix] [%s][%s] Item Mix Failed - No Auth",
lpObj->AccountID,lpObj->Name);
DataSend(lpObj->m_Index,(PBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
if(g_iCastleItemMixLimit <= 0)
{
LogAddTD("[CastleSpecialMix] [%s][%s] Item Mix Failed - Mix Count Limit Over",
lpObj->AccountID,lpObj->Name);
DataSend(lpObj->m_Index,(PBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
for(int n = 0; n < CHAOS_BOX_SIZE; n++)
{
if(lpObj->pChaosBox[n].IsItem() == TRUE)
{
if(lpObj->pChaosBox[n].m_Type == ITEMGET(12,30))
{
iBlessGemMixCount += (lpObj->pChaosBox[n].m_Level + 1);
}
else if(lpObj->pChaosBox[n].m_Type == ITEMGET(12,31))
{
iSoulGemMixCount += (lpObj->pChaosBox[n].m_Level + 1);
}
#ifdef __NOVUS__
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(12, 138) && lpObj->pChaosBox[n].m_Level == 2 )
{
iDefendGemCount++;
}
#else
else if(lpObj->pChaosBox[n].m_Type == ITEMGET(14,31))
{
iDefendGemCount++;
}
#endif
else
{
iInvalidItemCount++;
}
}
}
if(iBlessGemMixCount != 3
|| iSoulGemMixCount != 3
#ifdef __NOVUS__
|| iDefendGemCount != 1
#else
|| iDefendGemCount != 30
#endif
|| iInvalidItemCount > 0)
{
LogAddTD("[CastleSpecialMix] [%s][%s] Item Mix Failed - Item Error (DG:%d, BGx10:%d, SGx10:%d, Other:%d)",
lpObj->AccountID,lpObj->Name,iBlessGemMixCount,iSoulGemMixCount,iDefendGemCount,iInvalidItemCount);
DataSend(lpObj->m_Index,(PBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
LogChaosItem(lpObj,"Castle Special Mix");
LogAddTD("[CastleSpecialMix] [%s][%s] Chaos Mix Start",
lpObj->AccountID,lpObj->Name);
lpObj->ChaosSuccessRate = 100;
int nChaosNeedMoney = 1000000000;
if(lpObj->Money < nChaosNeedMoney)
{
LogAddTD("[CastleSpecialMix] [%s][%s] Item Mix Failed - Lack of Money (%d/%d)",
lpObj->AccountID,lpObj->Name,lpObj->Money,nChaosNeedMoney);
pMsg.Result = 2;
DataSend(lpObj->m_Index,(PBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
lpObj->Money -= nChaosNeedMoney;
GCMoneySend(lpObj->m_Index,lpObj->Money);
if(rand() % 100 < lpObj->ChaosSuccessRate)
{
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, true);
#endif
g_EventItemBagManager.OpenSpecial(EventBagSpecial::CastleMix, lpObj->m_Index, 255, 0, 0);
gObjInventoryCommit(lpObj->m_Index);
LogAddTD("[CastleSpecialMix] [%s][%s] CBMix Success %d Money : %d-%d",
lpObj->AccountID,lpObj->Name,lpObj->ChaosSuccessRate,lpObj->Money,nChaosNeedMoney);
g_iCastleItemMixLimit--;
}
else
{
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, false);
#endif
ChaosBoxInit(lpObj);
GCUserChaosBoxSend(lpObj,1);
DataSend(lpObj->m_Index,(PBYTE)&pMsg,pMsg.h.size);
LogAddTD("[CastleSpecialMix] [%s][%s] CBMix Fail %d Money : %d-%d",
lpObj->AccountID,lpObj->Name,lpObj->ChaosSuccessRate,lpObj->Money,nChaosNeedMoney);
}
lpObj->ChaosLock = FALSE;
}
#endif
void CChaosBox::CondorFeather_Mix(LPOBJ lpObj)
{
lpObj->ChaosLock = TRUE;
int iWingCount = 0;
int iSetItemCount = 0;
int iChaosCount = 0;
int iSoulPackCount = 0;
int iCreationCount = 0;
int iOtherItemCount = 0;
int iItemValue = 0;
int iNeedChaosMoney = 0;
int iCharmOfLuckCount = 0;
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
for(int n = 0; n < CHAOS_BOX_SIZE;n++)
{
if( lpObj->pChaosBox[n].IsItem() == TRUE )
{
//Item* lpItem,short iLevel,BYTE iOption1,BYTE iOption2,BYTE iOption3,BYTE iSetOption,BYTE iExcOption)
if( Is2ndLevelWing(lpObj->pChaosBox[n].m_Type) && CheckItemOptions(&lpObj->pChaosBox[n],9,0,0,1,0,0) )
{
iWingCount++;
}
else if( CheckItemOptions(&lpObj->pChaosBox[n],7,0,0,1,1,0) )
{
iSetItemCount++;
iItemValue += lpObj->pChaosBox[n].m_BuyMoney;
}
else if( lpObj->pChaosBox[n].m_Type == iChaosJewel )
{
iChaosCount++;
}
else if( lpObj->pChaosBox[n].m_Type == iSoulPack )
{
iSoulPackCount++;
}
else if( lpObj->pChaosBox[n].m_Type == iCreationJewel )
{
iCreationCount++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,53) )
{
iCharmOfLuckCount += (int)lpObj->pChaosBox[n].m_Durability;
}
else
{
iOtherItemCount++;
}
}
}
if( iCharmOfLuckCount > 10 )
{
pMsg.Result = 0xF0;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
if( iWingCount != 1 ||
iSetItemCount < 1 ||
iChaosCount != 1 ||
iSoulPackCount != 1 ||
iCreationCount != 1 ||
iOtherItemCount > 0 )
{
pMsg.Result = 7;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
LogChaosItem(lpObj, "ThirdWingLevel1_Mix");
LogAddTD("[ThirdWing Mix][Level 01] Chaos Mix Start");
#if (__CUSTOM__ == 1)
if( iItemValue > 0 )
{
lpObj->ChaosSuccessRate = iItemValue / gc_ChaosMixCondor_Div;
}
if( lpObj->ChaosSuccessRate > gc_ChaosMixCondor_Max )
{
lpObj->ChaosSuccessRate = gc_ChaosMixCondor_Max;
}
else if( lpObj->ChaosSuccessRate < 1 )
{
lpObj->ChaosSuccessRate = 1;
}
#else
if( iItemValue > 0 )
{
lpObj->ChaosSuccessRate = iItemValue / 300000;
}
if( lpObj->ChaosSuccessRate > 60 )
{
lpObj->ChaosSuccessRate = 60;
}
else if( lpObj->ChaosSuccessRate < 1 )
{
lpObj->ChaosSuccessRate = 1;
}
#endif
iNeedChaosMoney = lpObj->ChaosSuccessRate * 200000;
lpObj->ChaosSuccessRate += iCharmOfLuckCount;
iNeedChaosMoney = lpObj->ChaosSuccessRate * 200000;
int iChaosTaxMoney = (int)((__int64)iNeedChaosMoney * (__int64)g_CastleSiegeSync.GetTaxRateChaos(lpObj->m_Index) / (__int64)100);
if ( iChaosTaxMoney < 0 )
{
iChaosTaxMoney = 0;
}
iNeedChaosMoney += iChaosTaxMoney;
if ( iNeedChaosMoney < 0 )
{
iNeedChaosMoney = 0;
}
if(lpObj->Money < iNeedChaosMoney )
{
pMsg.Result = CB_NOT_ENOUGH_ZEN;
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
lpObj->Money -= iNeedChaosMoney;
g_CastleSiegeSync.AddTributeMoney(iChaosTaxMoney);
GCMoneySend(lpObj->m_Index,lpObj->Money);
if( rand() % 100 < lpObj->ChaosSuccessRate )
{
int Item = ITEMGET(13,53);
int Dur = 0;
int Level = 0;
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, true);
#endif
ItemSerialCreateSend(lpObj->m_Index,255,0,0,Item,Level,Dur,0,0,0,-1,0,0);
gObjInventoryCommit(lpObj->m_Index);
LogAddTD("[ThirdWing Mix][Level 01] [%s][%s] CBMix Success %d Money : %d-%d, CharmRate : %d",
lpObj->AccountID,lpObj->Name,lpObj->ChaosSuccessRate,lpObj->Money,iNeedChaosMoney,iCharmOfLuckCount);
}
else
{
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, false);
#endif
ChaosBoxWingMixItemDown(lpObj);
GCUserChaosBoxSend(lpObj, 0);
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
LogAddTD("[ThirdWing Mix][Level 01] [%s][%s] CBMix Fail %d Money : %d-%d, CharmRate : %d",
lpObj->AccountID,lpObj->Name,lpObj->ChaosSuccessRate,lpObj->Money,iNeedChaosMoney,iCharmOfLuckCount);
lpObj->ChaosLock = FALSE;
}
}
void CChaosBox::NewWingChaos_Mix(LPOBJ lpObj)
{
lpObj->ChaosLock = TRUE;
int iExcItemCount = 0;
int iCondorFeatherCount = 0;
int iCondorStoneCount = 0;
int iChaosCount = 0;
int iSoulPackCount = 0;
int iBlessPackCount = 0;
int iCreationCount =0;
int iOtherItemCount = 0;
int iItemValue = 0;
int iNeedChaosMoney = 0;
int iCharmOfLuckCount = 0;
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
for(int n = 0; n < CHAOS_BOX_SIZE; n++)
{
if( lpObj->pChaosBox[n].IsItem() == TRUE )
{
if( CheckItemOptions(&lpObj->pChaosBox[n],7,0,0,1,0,1) != FALSE )
{
iExcItemCount++;
iItemValue += lpObj->pChaosBox[n].m_BuyMoney;
}
else if( lpObj->pChaosBox[n].m_Type == iCondorFeather )
{
iCondorFeatherCount++;
}
else if( lpObj->pChaosBox[n].m_Type == iCondorStone )
{
iCondorStoneCount++;
}
else if( lpObj->pChaosBox[n].m_Type == iChaosJewel )
{
iChaosCount++;
}
else if( lpObj->pChaosBox[n].m_Type == iBlessPack )
{
iBlessPackCount++;
}
else if( lpObj->pChaosBox[n].m_Type == iSoulPack )
{
iSoulPackCount++;
}
else if( lpObj->pChaosBox[n].m_Type == iCreationJewel )
{
iCreationCount++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,53) )
{
iCharmOfLuckCount += (int)lpObj->pChaosBox[n].m_Durability;
}
else
{
iOtherItemCount++;
}
}
}
if( iCharmOfLuckCount > 10 )
{
pMsg.Result = 0xF0;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
if( iExcItemCount < 1 ||
iCondorFeatherCount != 1 ||
iCondorStoneCount != 1 ||
iChaosCount != 1 ||
iSoulPackCount != 1 ||
iBlessPackCount != 1 ||
iCreationCount != 1 ||
iOtherItemCount > 0 )
{
pMsg.Result = 7;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
LogChaosItem(lpObj, "ThirdWingLevel2_Mix");
LogAddTD("[ThirdWing Mix][Level 02] Chaos Mix Start");
#if (__CUSTOM__ == 1)
if( iItemValue > 0 )
{
lpObj->ChaosSuccessRate = iItemValue / gc_ChaosMix3rdWing_Div;
}
if( lpObj->ChaosSuccessRate > gc_ChaosMix3rdWing_Max )
{
lpObj->ChaosSuccessRate = gc_ChaosMix3rdWing_Max;
}
else if( lpObj->ChaosSuccessRate < 1 )
{
lpObj->ChaosSuccessRate = 1;
}
#else
if( iItemValue > 0 )
{
lpObj->ChaosSuccessRate = iItemValue / 3000000;
}
if( lpObj->ChaosSuccessRate > 40 )
{
lpObj->ChaosSuccessRate = 40;
}
else if( lpObj->ChaosSuccessRate < 1 )
{
lpObj->ChaosSuccessRate = 1;
}
#endif
iNeedChaosMoney = lpObj->ChaosSuccessRate * 200000;
lpObj->ChaosSuccessRate += iCharmOfLuckCount;
iNeedChaosMoney = lpObj->ChaosSuccessRate * 200000;
int iChaosTaxMoney = (int)((__int64)iNeedChaosMoney * (__int64)g_CastleSiegeSync.GetTaxRateChaos(lpObj->m_Index) / (__int64)100);
if ( iChaosTaxMoney < 0 )
{
iChaosTaxMoney = 0;
}
iNeedChaosMoney += iChaosTaxMoney;
if ( iNeedChaosMoney < 0 )
{
iNeedChaosMoney = 0;
}
if(lpObj->Money < iNeedChaosMoney)
{
pMsg.Result = CB_NOT_ENOUGH_ZEN;
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
lpObj->Money -= iNeedChaosMoney;
g_CastleSiegeSync.AddTributeMoney(iChaosTaxMoney);
GCMoneySend(lpObj->m_Index,lpObj->Money);
if( rand() % 100 < lpObj->ChaosSuccessRate )
{
int RandWing = rand()%7;
int Item = 0;
if( RandWing == 0 )
{
Item = iStormWings;
}
else if( RandWing == 1 )
{
Item = iRedemptionWings;
}
else if( RandWing == 2 )
{
Item = iFortitudeWings;
}
else if( RandWing == 3 )
{
Item = iHurricaneWings;
}
else if( RandWing == 4 )
{
Item = iMonarchMantle;
}
else if( RandWing == 5 )
{
Item = iDimensionWings;
}
else if( RandWing == 6 )
{
Item = iRFCape2;
}
int Option1 = 0;
int Option2 = 0;
if( rand() % 1000 <= iOptionRate )
{
Option2 = TRUE;
}
int Option3 = 0;
int ExcOption = 0;
int Rand = rand() %2;
int Rand2;
switch( Rand )
{
case 0:
Rand2 = rand() % 1000;
if( Rand2 < 400 )
{
ExcOption |= 0x10;
}
break;
case 1:
Rand2 = rand() % 1000;
if( Rand2 < 300 )
{
ExcOption |= 0x20;
}
break;
}
int Rand3 = rand() % 4;
int Rand4 = rand() % 1000;
Option3 = 0;
switch( Rand3 )
{
case 1:
if( Rand4 < 120 )
{
Option3 = 1;
}
break;
case 2:
if( Rand4 < 60 )
{
Option3 = 2;
}
break;
case 3:
if( Rand4 < 30 )
{
Option3 = 3;
}
break;
}
int Rand5 = rand() % 4;
int Rand6 = rand() % 1000;
switch( Rand5 )
{
case 0:
if( Rand6 < 40 )
{
ExcOption |= 0x01;
}
break;
case 1:
if( Rand6 < 20 )
{
ExcOption |= 0x02;
}
break;
case 2:
if( Rand6 < 70 )
{
ExcOption |= 0x04;
}
break;
case 3:
if( Rand6 < 70 )
{
ExcOption |= 0x08;
}
break;
}
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, true);
#endif
ItemSerialCreateSend(lpObj->m_Index,255,0,0,Item,0,0,Option1,Option2,Option3,-1,ExcOption,0);
gObjInventoryCommit(lpObj->m_Index);
LogAddTD("[ThirdWing Mix][Level 02] [%s][%s] CBMix Success %d Money : %d-%d, CharmRate : %d",
lpObj->AccountID,lpObj->Name,lpObj->ChaosSuccessRate,lpObj->Money,iNeedChaosMoney,iCharmOfLuckCount);
}
else
{
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, false);
#endif
ChaosBoxWingMixItemDown(lpObj);
GCUserChaosBoxSend(lpObj, 0);
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
LogAddTD("[ThirdWing Mix][Level 02] [%s][%s] CBMix Fail %d Money : %d-%d, CharmRate : %d",
lpObj->AccountID,lpObj->Name,lpObj->ChaosSuccessRate,lpObj->Money,iNeedChaosMoney,iCharmOfLuckCount);
lpObj->ChaosLock = FALSE;
}
}
void CChaosBox::ChaosBoxWingMixItemDown(LPOBJ lpObj)
{
if( lpObj->pChaosBox == FALSE )
return;
for(int n = 0; n < CHAOS_BOX_SIZE; n++)
{
if( lpObj->pChaosBox[n].IsItem() == TRUE )
{
if( Is2ndLevelWing(lpObj->pChaosBox[n].m_Type) != FALSE )
{
RandomLevelDown(&lpObj->pChaosBox[n]);
}
else if( CheckItemOptions(&lpObj->pChaosBox[n],0,0,0,0,1,0) != FALSE )
{
RandomLevelDown(&lpObj->pChaosBox[n]);
}
else if( CheckItemOptions(&lpObj->pChaosBox[n],0,0,0,0,0,1) != FALSE )
{
RandomLevelDown(&lpObj->pChaosBox[n]);
}
else
{
lpObj->pChaosBox[n].Clear();
}
}
}
}
void CChaosBox::RandomLevelDown(CItem* lpItem)
{
if( lpItem == FALSE )
return;
if( rand()%2 < 1 )
{
lpItem->m_Level -= 2;
}
else
{
lpItem->m_Level -= 3;
}
lpItem->m_Option3 = 0;
lpItem->Convert(lpItem->m_Type,lpItem->m_Option1,lpItem->m_Option2,lpItem->m_Option3,lpItem->m_NewOption,lpItem->m_SetOption,lpItem->m_ItemOptionEx, lpItem->m_SocketOption, lpItem->m_SocketBonus,3);
}
void CChaosBox::LotteryItemMix(LPOBJ lpObj)
{
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
int iChaosCardCount = 0;
int iOtherItemCount = 0;
int iHeight = 0;
int iWidth = 0;
int iChaosCardType = 0;
for(int n = 0; n < CHAOS_BOX_SIZE; n++)
{
if( lpObj->pChaosBox[n].IsItem() == TRUE )
{
if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,54) )
{
iChaosCardType = 1;
iChaosCardCount++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,92) )
{
iChaosCardType = 2;
iChaosCardCount++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,93) )
{
iChaosCardType = 3;
iChaosCardCount++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,95) )
{
iChaosCardType = 4;
iChaosCardCount++;
}
else
{
iOtherItemCount++;
}
}
}
if( iOtherItemCount > 0 || iChaosCardCount != 1 )
{
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
if( iChaosCardType == 0 )
{
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
LogChaosItem(lpObj, "CashLottery");
iHeight = 4;
iWidth = 2;
if( !CheckInventoryEmptySpace(lpObj,iHeight,iWidth) )
{
pMsg.Result = 0xF1;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
CItem LotteryItem;
if( iChaosCardType == 1 )
{
g_Lottery.GetItem("ChaosCard",&LotteryItem);
}
else if( iChaosCardType == 2 )
{
g_Lottery.GetItem("ChaosCardGold",&LotteryItem);
}
else if( iChaosCardType == 3 )
{
g_Lottery.GetItem("ChaosCardRare",&LotteryItem);
}
else if( iChaosCardType == 4 )
{
g_Lottery.GetItem("ChaosCardMini",&LotteryItem);
}
if( LotteryItem.IsItem() == FALSE )
{
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
LogAddTD("[ChaosMix][LotteryItemMix] Lottery Item Mix Failed. Can't Get Item from List.");
return;
}
ItemSerialCreateSend(lpObj->m_Index,255,0,0,LotteryItem.m_Type,LotteryItem.m_Level,(BYTE)LotteryItem.m_Durability,LotteryItem.m_Option1,
LotteryItem.m_Option2,LotteryItem.m_Option3,lpObj->m_Index,LotteryItem.m_NewOption,0);
gObjInventoryCommit(lpObj->m_Index);
LogAddTD("[ChaosMix][ChaosCardMix] Chaos Card Item Mix Success [%s][%s]",
lpObj->AccountID,lpObj->Name);
BYTE btExOption[MAX_EXOPTION_SIZE];
ItemIsBufExOption(btExOption, &LotteryItem);
LogAddTD("[CashShop][ChaosCardMix] - User(ID:%s,Name:%s) Item(Name:%s,Type:%d,Level:%d,Dur:%d,Skill:%d,Luck:%d,AddOption:%d,Ex:(%d,%d,%d,%d,%d,%d))",
lpObj->AccountID, lpObj->Name, ItemAttribute[LotteryItem.m_Type].Name,
LotteryItem.m_Type, LotteryItem.m_Level, (int)LotteryItem.m_Durability,
LotteryItem.m_Option1, LotteryItem.m_Option2, LotteryItem.m_Option3,
btExOption[0], btExOption[1], btExOption[2], btExOption[3], btExOption[4], btExOption[5]);
}
struct pMixTmp
{
BYTE bOk;
BYTE Dur;
BYTE NeedDur;
int m_Item;
};
void CChaosBox::CherryBlossomMix(LPOBJ lpObj)
{
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
lpObj->ChaosLock = TRUE;
pMixTmp pTmp = {0};
for(int n = 0; n < CHAOS_BOX_SIZE; n++)
{
if( lpObj->pChaosBox[n].IsItem() == FALSE )
continue;
if( pTmp.m_Item == FALSE )
{
pTmp.m_Item = lpObj->pChaosBox[n].m_Type;
if( pTmp.m_Item == ITEMGET(14,88) )
{
pTmp.NeedDur = 10;
}
else if( pTmp.m_Item == ITEMGET(14,89) )
{
pTmp.NeedDur = 30;
}
else if( pTmp.m_Item == ITEMGET(14,90) )
{
pTmp.NeedDur = 255;
}
else
{
pTmp.m_Item = 0;
continue;
}
pTmp.bOk = TRUE;
}
if( pTmp.m_Item == lpObj->pChaosBox[n].m_Type )
{
pTmp.Dur += (int)lpObj->pChaosBox[n].m_Durability;
}
else
{
pTmp.bOk = FALSE;
break;
}
}
if( pTmp.Dur != pTmp.NeedDur )
{
pTmp.bOk = FALSE;
}
if( pTmp.m_Item == FALSE || pTmp.bOk == FALSE )
{
pMsg.Result = 0;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
int iHeight = 4;
int iWidth = 2;
if( !CheckInventoryEmptySpace(lpObj, iHeight, iWidth) )
{
pMsg.Result = 0xF1;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
int bResult = 0;
if( pTmp.m_Item == ITEMGET(14,88) )
{
bResult = g_EventItemBagManager.OpenSpecial(EventBagSpecial::CherryMixWhite, lpObj->m_Index, 0xFF, 0, 0);
}
else if( pTmp.m_Item == ITEMGET(14,89) )
{
bResult = g_EventItemBagManager.OpenSpecial(EventBagSpecial::CherryMixRed, lpObj->m_Index, 0xFF, 0, 0);
}
else if( pTmp.m_Item == ITEMGET(14,90) )
{
bResult = g_EventItemBagManager.OpenSpecial(EventBagSpecial::CherryMixGold, lpObj->m_Index, 0xFF, 0, 0);
}
if( bResult == false )
{
ChaosBoxInit(lpObj);
GCUserChaosBoxSend(lpObj,0);
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
LogAddTD("[%s][%s] CherryBlossomMix Fail %d Money : %d-%d",
lpObj->AccountID,lpObj->Name,lpObj->ChaosSuccessRate,lpObj->Money,lpObj->ChaosMoney);
lpObj->ChaosLock = FALSE;
return;
}
gObjInventoryCommit(lpObj->m_Index);
lpObj->ChaosLock = FALSE;
}
void CChaosBox::IllusionTemple_Mix(LPOBJ lpObj)
{
lpObj->ChaosLock = TRUE;
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
int PaperCount = 0;
int PotionCount = 0;
int ChaosCount = 0;
int PotionLevel = -1;
int PaperLevel = -1;
int OtherItemCount = 0;
int iCharmOfLuckCount = 0;
for(int n = 0; n < CHAOS_BOX_SIZE; n++)
{
if(lpObj->pChaosBox[n].IsItem() == TRUE)
{
if(lpObj->pChaosBox[n].m_Type == ITEMGET(13,49))
{
PaperCount++;
PaperLevel = lpObj->pChaosBox[n].m_Level;
}
else if(lpObj->pChaosBox[n].m_Type == ITEMGET(13,50))
{
PotionCount++;
PotionLevel = lpObj->pChaosBox[n].m_Level;
}
else if(lpObj->pChaosBox[n].m_Type == ITEMGET(12,15))
{
ChaosCount++;
}
else if(lpObj->pChaosBox[n].m_Type == ITEMGET(14,53))
{
iCharmOfLuckCount += (int)lpObj->pChaosBox[n].m_Durability;
}
else
{
OtherItemCount++;
}
}
}
if(PaperCount != 1 || PotionCount != 1 || ChaosCount != 1 || OtherItemCount != 0 || PotionLevel != PaperLevel)
{
DataSend(lpObj->m_Index, (LPBYTE)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
if(PotionLevel < 1 || PotionLevel > IT_MAXTEMPLE)
{
DataSend(lpObj->m_Index, (LPBYTE)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
if(iCharmOfLuckCount > 10)
{
pMsg.Result = 0xF0;
DataSend(lpObj->m_Index, (LPBYTE)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
int nChaosNeedMoney = 300000 + (PotionLevel-1) * 200000;
if(lpObj->Money < nChaosNeedMoney)
{
pMsg.Result = CB_NOT_ENOUGH_ZEN;
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
lpObj->Money -= nChaosNeedMoney;
GCMoneySend(lpObj->m_Index,lpObj->Money);
lpObj->ChaosSuccessRate = 70;
lpObj->ChaosSuccessRate += iCharmOfLuckCount;
if(rand()%100 < lpObj->ChaosSuccessRate)
{
ItemSerialCreateSend(lpObj->m_Index,255,0,0,ITEMGET(13,51),PotionLevel,1,0,0,0,lpObj->m_Index,0,0);
gObjInventoryCommit(lpObj->m_Index);
LogAddTD("[ChaosMix][Illusion Temple] Illusion Ticket Mix Success [%s][%s], Money(%d-%d), CharmRate : %d",
lpObj->AccountID, lpObj->Name, lpObj->Money, nChaosNeedMoney, iCharmOfLuckCount);
}
else
{
for(int n = 0; n < CHAOS_BOX_SIZE; n++)
{
if(lpObj->pChaosBox[n].IsItem() == TRUE)
{
lpObj->pChaosBox[n].Clear();
}
}
GCUserChaosBoxSend(lpObj,0);
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
LogAddTD("[ChaosMix][Illusion Temple] Illusion Ticket [%s][%s] CBMix Fail %d Money : %d-%d, CharmRate : %d",
lpObj->AccountID, lpObj->Name, lpObj->ChaosSuccessRate,lpObj->Money, nChaosNeedMoney, iCharmOfLuckCount);
}
lpObj->ChaosLock = FALSE;
}
void CChaosBox::SeedExtractMix(LPOBJ lpObj)
{
int iExcItemCount = 0;
int iAncItemCount = 0;
int iHarmonyCount = 0;
int iChaosCount = 0;
int iCreationCount = 0;
int iOtherItemCount = 0;
int iChaosMixRate = 0;
DWORD iItemValue = 0;
int iMixNeedMoney = 0;
int iChaosTaxMoney = 0;
int iAncItemPos = 0;
int iExcItemPos = 0;
int iHarmonyPos = 0;
int iChaosPos = 0;
int iCreationPos = 0;
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
lpObj->ChaosLock = TRUE;
for(int n = 0; n < CHAOS_BOX_SIZE; n++)
{
if( lpObj->pChaosBox[n].IsItem() == TRUE )
{
if( lpObj->pChaosBox[n].IsExtItem() == TRUE && lpObj->pChaosBox[n].m_Level >= 4 &&
lpObj->pChaosBox[n].m_bLOCKED == FALSE )
{
iExcItemCount++;
iItemValue += lpObj->pChaosBox[n].m_BuyMoney;
iExcItemPos = n;
}
else if( lpObj->pChaosBox[n].IsSetItem() && lpObj->pChaosBox[n].m_Level >= 4 &&
lpObj->pChaosBox[n].m_bLOCKED == FALSE )
{
iAncItemCount++;
iItemValue += lpObj->pChaosBox[n].m_BuyMoney;
iAncItemPos = n;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,42) )
{
iHarmonyCount++;
iHarmonyPos = n;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(12,15) )
{
iChaosCount++;
iChaosPos = n;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,22) )
{
iCreationCount++;
iCreationPos = n;
}
else
{
iOtherItemCount++;
}
}
}
if( iOtherItemCount > 0 )
{
pMsg.Result = 7;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
if( iExcItemCount != 1 ||
iAncItemCount != 1 ||
iHarmonyCount != 1 ||
iChaosCount != 1 ||
iCreationCount != 1 )
{
pMsg.Result = 7;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
iChaosTaxMoney = (int)((__int64)g_SeedExtractMoney * (__int64)g_CastleSiegeSync.GetTaxRateChaos(lpObj->m_Index) / (__int64)100);
if( iChaosTaxMoney < 0 )
iChaosTaxMoney = 0;
iMixNeedMoney = g_SeedExtractMoney + iChaosTaxMoney;
if( lpObj->Money < iMixNeedMoney )
{
pMsg.Result = 2;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
LogChaosItem(lpObj, "SeedExtract");
lpObj->Money -= iMixNeedMoney;
g_CastleSiegeSync.AddTributeMoney(iChaosTaxMoney);
GCMoneySend(lpObj->m_Index,lpObj->Money);
iChaosMixRate = 80 + (iItemValue / 2000000);
if( iChaosMixRate > 90 )
iChaosMixRate = 90;
if( rand()%100 > iChaosMixRate )
{
lpObj->pChaosBox[iAncItemPos].m_Level -= rand()%3;
lpObj->pChaosBox[iExcItemPos].m_Level -= rand()%3;
lpObj->pChaosBox[iHarmonyPos].Clear();
lpObj->pChaosBox[iChaosPos].Clear();
lpObj->pChaosBox[iCreationPos].Clear();
GCUserChaosBoxSend(lpObj,0);
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
LogAddTD("[%s][%s] Seed Extract Mix Failed.",lpObj->AccountID,lpObj->Name);
}
else
{
BYTE SeedRate = 0;
SeedRate = g_SocketItem.GetOptionRate();
_SOCKET_SEED_DATA* tmpSeed;
tmpSeed = g_SocketItem.GetSeedOption(SeedRate);
if( tmpSeed != NULL )
{
pMsg.Result = TRUE;
ItemSerialCreateSend(lpObj->m_Index,0xFF,0,0,tmpSeed->SeedItem,tmpSeed->btIndex,1,0,0,0,lpObj->m_Index,0,0);
gObjInventoryCommit(lpObj->m_Index);
LogAddTD("[%s][%s] Seed Extract Mix Success - SeedInfo ( Index : %d, Type : %d, Level : %d, ItemCode : %d )",
lpObj->AccountID,lpObj->Name,tmpSeed->btOption,tmpSeed->btGroup,tmpSeed->btIndex,tmpSeed->SeedItem);
}
else
{
lpObj->pChaosBox[iAncItemPos].m_Level -= rand()%3;
lpObj->pChaosBox[iExcItemPos].m_Level -= rand()%3;
lpObj->pChaosBox[iHarmonyPos].Clear();
lpObj->pChaosBox[iChaosPos].Clear();
lpObj->pChaosBox[iCreationPos].Clear();
GCUserChaosBoxSend(lpObj,0);
LogAddTD("[%s][%s] Seed Extract Mix Failed - SeedData is NULL",lpObj->AccountID,lpObj->Name);
lpObj->ChaosLock = FALSE;
}
}
}
void CChaosBox::SeedSphereCompositeMix(LPOBJ lpObj)
{
int iSeedCount = 0;
int iSphereCount = 0;
int iOtherItemCount = 0;
int iChaosCount = 0;
int iCreationCount = 0;
int iChaosTaxMoney = 0;
int iMixNeedMoney = 0;
DWORD iItemValue = 0;
int iChaosMixRate = 0;
CItem* lpSeed = NULL;
CItem* lpSphere = NULL;
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
lpObj->ChaosLock = TRUE;
for(int n = 0; n < CHAOS_BOX_SIZE; n++)
{
if( lpObj->pChaosBox[n].IsItem() == TRUE )
{
if( g_SocketItem.IsSeedItem(lpObj->pChaosBox[n].m_Type) == TRUE )
{
iSeedCount++;
iItemValue += lpObj->pChaosBox[n].m_BuyMoney;
lpSeed = &lpObj->pChaosBox[n];
}
else if( g_SocketItem.IsSphereItem(lpObj->pChaosBox[n].m_Type) == TRUE )
{
iSphereCount++;
iItemValue += lpObj->pChaosBox[n].m_BuyMoney;
lpSphere = &lpObj->pChaosBox[n];
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(12,15) )
{
iChaosCount++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,22) )
{
iCreationCount++;
}
else
{
iOtherItemCount++;
}
}
}
if( iOtherItemCount > 0 )
{
pMsg.Result = 7;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
if( iSeedCount != 1 ||
iSphereCount != 1 ||
iChaosCount != 1 ||
iCreationCount != 1 )
{
pMsg.Result = 7;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
iChaosTaxMoney = (int)((__int64)g_SphereCompositeMoney * (__int64)g_CastleSiegeSync.GetTaxRateChaos(lpObj->m_Index) / (__int64)100);
if( iChaosTaxMoney < 0 )
iChaosTaxMoney = 0;
iMixNeedMoney = g_SphereCompositeMoney + iChaosTaxMoney;
if( lpObj->Money < iMixNeedMoney )
{
pMsg.Result = 2;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
LogChaosItem(lpObj,"SeedSphereComposite");
iChaosMixRate = 80 + (iItemValue / 200000);
if( iChaosMixRate > 90 )
iChaosMixRate = 90;
lpObj->Money -= iMixNeedMoney;
g_CastleSiegeSync.AddTributeMoney(iChaosTaxMoney);
GCMoneySend(lpObj->m_Index,lpObj->Money);
if( rand()%100 > iChaosMixRate )
{
ChaosBoxInit(lpObj);
GCUserChaosBoxSend(lpObj,0);
LogAddTD("[%s][%s] SeedSphere Composite Mix Failed.",lpObj->AccountID,lpObj->Name);
}
else
{
BYTE btOption = 0;
BYTE btLevel = 0;
_SOCKET_SPHERE_OPTION tmpSphere;
btOption = g_SocketItem.GetSeedOption(lpSeed->m_Type,lpSeed->m_Level);
btLevel = g_SocketItem.GetSphereLevel(lpSphere->m_Type);
g_SocketItem.IsOptionSet(&tmpSphere,btOption,btLevel);
if( tmpSphere.SeedItem != 0 )
{
pMsg.Result = TRUE;
ItemSerialCreateSend(lpObj->m_Index,0xFF,0,0,tmpSphere.SeedItem,tmpSphere.btIndex,1,0,0,0,lpObj->m_Index,0,0);
gObjInventoryCommit(lpObj->m_Index);
LogAddTD("[%s][%s] SeedSphere Composite Mix Success - SeedSphere Info ( Index : %d, Type : %d, Level : %d, ItemCode : %d )",
lpObj->AccountID,lpObj->Name,tmpSphere.btOptionId,tmpSphere.btGroup,tmpSphere.btLevel,tmpSphere.SeedItem);
return;
}
else
{
ChaosBoxInit(lpObj);
GCUserChaosBoxSend(lpObj,0);
LogAddTD("[%s][%s] SeedSphere Composite Mix Failed - SeedSphere Data is NULL",
lpObj->AccountID,lpObj->Name);
}
}
lpObj->ChaosLock = FALSE;
}
void CChaosBox::SetSeedSphereMix(LPOBJ lpObj,BYTE Pos)
{
int iItemCount = 0;
int iOtherItemCount = 0;
int iSeedSphereCount = 0;
int iChaosCount = 0;
int iCreationCount = 0;
CItem* lpItem = 0;
CItem* lpSeedSphere = 0;
CItem tmpItem;
int iChaosTaxMoney = 0;
int iMixNeedMoney = 0;
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
if( Pos >= MAX_SOCKET_COUNT )
{
pMsg.Result = 7;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
lpObj->ChaosLock = TRUE;
for(int n = 0; n < CHAOS_BOX_SIZE; n++)
{
if( lpObj->pChaosBox[n].IsItem() == TRUE )
{
if( g_SocketItem.IsSocketItem(lpObj->pChaosBox[n].m_Type) == TRUE &&
lpObj->pChaosBox[n].m_SocketOption[Pos] == (BYTE)-2)
{
iItemCount++;
lpItem = &lpObj->pChaosBox[n];
}
else if( g_SocketItem.IsSeedSphereItem(lpObj->pChaosBox[n].m_Type) == TRUE )
{
iSeedSphereCount++;
lpSeedSphere = &lpObj->pChaosBox[n];
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(12,15) )
{
iChaosCount++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,22) )
{
iCreationCount++;
}
else
{
iOtherItemCount++;
}
}
}
if( iOtherItemCount > 0 )
{
pMsg.Result = 7;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
if( iItemCount != 1 ||
iSeedSphereCount != 1 ||
iChaosCount != 1 ||
iCreationCount != 1 )
{
pMsg.Result = 7;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
if( g_SocketItem.CheckMountItem(lpItem,lpSeedSphere->m_Type,lpSeedSphere->m_Level) == FALSE )
{
pMsg.Result = 7;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
iChaosTaxMoney = (int)((__int64)g_SphereSetMoney * (__int64)g_CastleSiegeSync.GetTaxRateChaos(lpObj->m_Index) / (__int64)100);
if( iChaosTaxMoney < 0 )
iChaosTaxMoney = 0;
iMixNeedMoney = g_SphereSetMoney +iChaosTaxMoney;
if( lpObj->Money < iMixNeedMoney )
{
pMsg.Result = 2;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
LogChaosItem(lpObj,"SetSeedSphere");
BYTE btOption = 0;
btOption = g_SocketItem.GetSphereOption(lpSeedSphere->m_Type,lpSeedSphere->m_Level);
if( btOption == (BYTE)-1 )
{
pMsg.Result = 7;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
LogAddTD("[%s][%s] Set Seed Mix Failed - SeedSphere is NULL",
lpObj->AccountID,lpObj->Name);
return;
}
if( g_SocketItem.IsItemType(lpItem,btOption) == FALSE )
{
pMsg.Result = 7;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
LogAddTD("[%s][%s] Set Seed Mix Failed - Wrong Item Type for Set Socket",
lpObj->AccountID,lpObj->Name);
return;
}
lpObj->Money -= iMixNeedMoney;
g_CastleSiegeSync.AddTributeMoney(iChaosTaxMoney);
GCMoneySend(lpObj->m_Index,lpObj->Money);
g_SocketItem.ItemSetSeedSphere(lpItem,btOption,Pos);
float dur = (float)ItemGetDurability(lpItem->m_Type,lpItem->m_Level,lpItem->IsExtItem(),lpItem->IsSetItem());
tmpItem.m_Number = lpItem->m_Number;
tmpItem.m_Level = lpItem->m_Level;
tmpItem.m_Durability = dur * lpItem->m_Durability / lpItem->m_BaseDurability;
tmpItem.m_JewelOfHarmonyOption = lpItem->m_JewelOfHarmonyOption;
tmpItem.m_bLOCKED = lpItem->m_bLOCKED;
tmpItem.Convert(lpItem->m_Type,lpItem->m_Option1,lpItem->m_Option2,lpItem->m_Option3,lpItem->m_NewOption,lpItem->m_SetOption,lpItem->m_ItemOptionEx,&lpItem->m_SocketOption[0],lpItem->m_SocketBonus,3);
lpObj->ChaosLock = FALSE;
ItemByteConvert(&pMsg.ItemInfo[0],tmpItem);
ChaosBoxInit(lpObj);
gObjChaosBoxInsertItemPos(lpObj->m_Index,tmpItem,0,-1);
gObjChaosItemSet(lpObj->m_Index,0,1);
GCUserChaosBoxSend(lpObj,0);
LogAddTD("[%s][%s] Set SeedSphere Mix Success - ItemInfo ( Name : %s, ItemCode : %d, Level : %d, SocketOption[%d,%d,%d,%d,%d], BonusOption : %d )",
lpObj->AccountID,lpObj->Name,ItemAttribute[tmpItem.m_Type].Name,tmpItem.m_Type,tmpItem.m_Level,
tmpItem.m_SocketOption[0],tmpItem.m_SocketOption[1],tmpItem.m_SocketOption[2],tmpItem.m_SocketOption[3],tmpItem.m_SocketOption[4],
tmpItem.m_SocketBonus);
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
}
void CChaosBox::RemoveSeedSphereMix(LPOBJ lpObj,BYTE Pos)
{
int iItemCount = 0;
int iOtherItemCount = 0;
int tmp = 0;
int iItemPos = 0;
int tmp2 = 0;
int iChaosTaxMoney = 0;
int iMixNeedMoney = 0;
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
if( Pos >= MAX_SOCKET_COUNT )
{
pMsg.Result = 7;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
lpObj->ChaosLock = TRUE;
for(int n = 0; n < CHAOS_BOX_SIZE; n++)
{
if( lpObj->pChaosBox[n].IsItem() == TRUE )
{
if( g_SocketItem.IsSocketItem(lpObj->pChaosBox[n].m_Type) == TRUE &&
lpObj->pChaosBox[n].m_SocketOption[Pos] != 0xFF &&
lpObj->pChaosBox[n].m_SocketOption[Pos] != 0xFE )
{
iItemCount++;
iItemPos = n;
}
else
{
iOtherItemCount++;
}
}
}
if( iOtherItemCount > 0 )
{
pMsg.Result = 7;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
if( iItemCount != 1 )
{
pMsg.Result = 7;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
iChaosTaxMoney = (int)((__int64)g_SphereRemoveMoney * (__int64)g_CastleSiegeSync.GetTaxRateChaos(lpObj->m_Index) / (__int64)100);
if( iChaosTaxMoney < 0 )
iChaosTaxMoney = 0;
iMixNeedMoney = g_SphereRemoveMoney +iChaosTaxMoney;
if( lpObj->Money < iMixNeedMoney )
{
pMsg.Result = 2;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
lpObj->Money -= iMixNeedMoney;
g_CastleSiegeSync.AddTributeMoney(iChaosTaxMoney);
GCMoneySend(lpObj->m_Index,lpObj->Money);
LogChaosItem(lpObj,"SeedSphereRemove");
g_SocketItem.ItemRemoveSeedSphere(&lpObj->pChaosBox[iItemPos],Pos);
lpObj->ChaosLock = FALSE;
gObjInventoryCommit(lpObj->m_Index);
GCUserChaosBoxSend(lpObj,0);
LogAddTD("[%s][%s] SeedSphere Remove Success - ItemInfo ( Name : %s, ItemCode : %d, Level : %d, SocketOption[%d,%d,%d,%d,%d], BonusOption : %d )",
lpObj->AccountID,lpObj->Name,ItemAttribute[lpObj->pChaosBox[iItemPos].m_Type].Name,lpObj->pChaosBox[iItemPos].m_Type,lpObj->pChaosBox[iItemPos].m_Level,
lpObj->pChaosBox[iItemPos].m_SocketOption[0],lpObj->pChaosBox[iItemPos].m_SocketOption[1],lpObj->pChaosBox[iItemPos].m_SocketOption[2],lpObj->pChaosBox[iItemPos].m_SocketOption[3],lpObj->pChaosBox[iItemPos].m_SocketOption[4],
lpObj->pChaosBox[iItemPos].m_SocketBonus);
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
}
void CChaosBox::SecromiconMix(LPOBJ lpObj)
{
lpObj->ChaosLock = TRUE;
int iNeedChaosMoney;
int iSecromiconPart1 = 0;
int iSecromiconPart2 = 0;
int iSecromiconPart3 = 0;
int iSecromiconPart4 = 0;
int iSecromiconPart5 = 0;
int iSecromiconPart6 = 0;
int iOtherItemCount = 0;
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
for(int n = 0; n < CHAOS_BOX_SIZE; n++)
{
if( lpObj->pChaosBox[n].IsItem() == TRUE )
{
if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,103) )
{
iSecromiconPart1++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,104) )
{
iSecromiconPart2++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,105) )
{
iSecromiconPart3++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,106) )
{
iSecromiconPart4++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,107) )
{
iSecromiconPart5++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,108) )
{
iSecromiconPart6++;
}
else
{
iOtherItemCount = 0;
}
}
}
if( iOtherItemCount != 0 ||
iSecromiconPart1 != 1 ||
iSecromiconPart2 != 1 ||
iSecromiconPart3 != 1 ||
iSecromiconPart4 != 1 ||
iSecromiconPart5 != 1 ||
iSecromiconPart6 != 1 )
{
pMsg.Result = 7;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
LogChaosItem(lpObj, "Secromicon");
LogAddTD("[Secromicon] Chaos Mix Start");
lpObj->ChaosSuccessRate = 100;
iNeedChaosMoney = 1000000;
int iChaosTaxMoney = (int)((__int64)iNeedChaosMoney * (__int64)g_CastleSiegeSync.GetTaxRateChaos(lpObj->m_Index) / (__int64)100);
if ( iChaosTaxMoney < 0 )
{
iChaosTaxMoney = 0;
}
iNeedChaosMoney += iChaosTaxMoney;
if ( iNeedChaosMoney < 0 )
{
iNeedChaosMoney = 0;
}
if(lpObj->Money < iNeedChaosMoney)
{
pMsg.Result = CB_NOT_ENOUGH_ZEN;
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
lpObj->Money -= iNeedChaosMoney;
g_CastleSiegeSync.AddTributeMoney(iChaosTaxMoney);
GCMoneySend(lpObj->m_Index,lpObj->Money);
if( rand()%100 < lpObj->ChaosSuccessRate )
{
int Item = ITEMGET(14,109);
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, true);
#endif
ItemSerialCreateSend(lpObj->m_Index,255,0,0,Item,0,0,0,0,0,-1,0,0);
gObjInventoryCommit(lpObj->m_Index);
LogAddTD("[Secromicon Mix][%s][%s] CBMix Success %d Money : %d-%d",
lpObj->AccountID,lpObj->Name,lpObj->ChaosSuccessRate,lpObj->Money,iNeedChaosMoney);
}
else
{
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, false);
#endif
ChaosBoxInit(lpObj);
GCUserChaosBoxSend(lpObj,0);
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
LogAddTD("[Secromicon Mix][%s][%s] CBMix Fail %d Money : %d-%d",
lpObj->AccountID,lpObj->Name,lpObj->ChaosSuccessRate,lpObj->Money,iNeedChaosMoney);
}
lpObj->ChaosLock = FALSE;
}
void CChaosBox::LuckySystemItemCreate(LPOBJ lpObj)
{
lpObj->ChaosLock = TRUE;
CItem* LuckyCard = NULL;
int iLuckyCardCount = 0;
int iOtherItemCount = 0;
BYTE gear_1[MAX_TYPE_PLAYER] = {64,62,63,62,62,65,62};
BYTE gear_2[MAX_TYPE_PLAYER] = {69,67,68,71,66,70,72};
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
for(int n = 0; n < CHAOS_BOX_SIZE; n++)
{
if( lpObj->pChaosBox[n].IsItem() )
{
if( lpObj->pChaosBox[n].m_Type >= ITEMGET(13,135) &&
lpObj->pChaosBox[n].m_Type <= ITEMGET(13,144) )
{
LuckyCard = &lpObj->pChaosBox[n];
iLuckyCardCount++;
}
else
{
iOtherItemCount++;
}
}
}
if( iLuckyCardCount != 1 ||
iOtherItemCount != 0 )
{
pMsg.Result = 0;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
if( lpObj->Class == CLASS_MAGUMSA &&
(LuckyCard->m_Type == ITEMGET(13, 137) || LuckyCard->m_Type == ITEMGET(13, 142) ) )
{
pMsg.Result = 0;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
if( lpObj->Class == CLASS_FIGHTER &&
(LuckyCard->m_Type == ITEMGET(13,138) || LuckyCard->m_Type == ITEMGET(13,143) ) )
{
pMsg.Result = 0;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
LogChaosItem(lpObj, "LuckySystem");
LogAddTD("[LuckySystem] Chaos Mix Start");
int ItemGroup;
int Item;
int Level;
int Option1;
int Option2;
int Option3;
Option1 = TRUE;
Option2 = 0;
Option3 = 0;
Level = rand()%10;
if( rand()%2 ) {
if( rand()%2 ) {
Option2 = TRUE;
}
}
if( rand()%2 ) {
Option3 = 1+rand()%3;
}
if( rand()%2 ) {
Level = rand()%15;
}
switch( LuckyCard->m_Type )
{
case ITEMGET(13,135):
case ITEMGET(13,140):
ItemGroup = 8;
break;
case ITEMGET(13,136):
case ITEMGET(13,141):
ItemGroup = 9;
break;
case ITEMGET(13,137):
case ITEMGET(13,142):
ItemGroup = 7;
break;
case ITEMGET(13,138):
case ITEMGET(13,143):
ItemGroup = 10;
break;
case ITEMGET(13,139):
case ITEMGET(13,144):
ItemGroup = 11;
break;
}
if( LuckyCard->m_Type >= ITEMGET(13,135) && LuckyCard->m_Type <= ITEMGET(13,139) )
{
Item = ITEMGET(ItemGroup,gear_1[lpObj->Class]);
}
else
{
Item = ITEMGET(ItemGroup,gear_2[lpObj->Class]);
}
ItemSerialCreateSend(lpObj->m_Index,255,0,0,Item,Level,0,Option1,Option2,Option3,lpObj->m_Index,0,gSetItemOption.GenSetOption(Item));
gObjInventoryCommit(lpObj->m_Index);
LogAddTD("[LuckySystem][ItemMix] Chaos Card Item Mix Success [%s][%s]",lpObj->AccountID,lpObj->Name);
LogAddTD("[LuckySystem][ItemMix] - User(ID:%s,Name:%s) Item(Name:%s,Type:%d,Level:%d,Dur:%d,Skill:%d,Luck:%d,AddOption:%d)",
lpObj->AccountID, lpObj->Name, ItemAttribute[Item].Name,
Item, Level, (int)255,
Option1, Option2, Option3);
lpObj->ChaosLock = FALSE;
}
void CChaosBox::LuckySystemJewelCreate(LPOBJ lpObj)
{
lpObj->ChaosLock = TRUE;
int iLuckyItemCount = 0;
float iLuckyItemDurability = 0;
int iOtherItemCount = 0;
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
for(int n = 0; n < CHAOS_BOX_SIZE; n++)
{
if( lpObj->pChaosBox[n].IsItem() )
{
if( lpObj->pChaosBox[n].m_bLuckySet )
{
iLuckyItemDurability = lpObj->pChaosBox[n].m_Durability;
iLuckyItemCount++;
}
else
{
iOtherItemCount++;
}
}
}
if( iLuckyItemCount != 1 ||
iOtherItemCount != 0 )
{
pMsg.Result = 7;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
LogChaosItem(lpObj, "LuckySystem");
LogAddTD("[LuckySystem] Chaos Mix Start");
if( iLuckyItemDurability == 255 )
{
lpObj->ChaosSuccessRate = 60;
}
else
{
lpObj->ChaosSuccessRate = 10;
}
if( rand()%100 < lpObj->ChaosSuccessRate )
{
int Item = ITEMGET(14,160);
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, true);
#endif
ItemSerialCreateSend(lpObj->m_Index,255,0,0,Item,0,0,0,0,0,-1,0,0);
gObjInventoryCommit(lpObj->m_Index);
LogAddTD("[LuckySystem][JewelOfExtension][%s][%s] CBMix Success %d",
lpObj->AccountID,lpObj->Name,lpObj->ChaosSuccessRate);
}
else
{
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, false);
#endif
ChaosBoxInit(lpObj);
GCUserChaosBoxSend(lpObj,0);
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
LogAddTD("[LuckySystem][JewelOfExtension][%s][%s] CBMix Fail %d",
lpObj->AccountID,lpObj->Name,lpObj->ChaosSuccessRate);
}
lpObj->ChaosLock = FALSE;
}
void CChaosBox::GoldenNSilverBoxMix(LPOBJ lpObj)
{
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
// ----
pMsg.Result = CB_ERROR; //ebp-11
int nGoldenKey = 0; //ebp-18
int nSilverKey = 0; //ebp-1c
int nGoldenBox = 0; //ebp-20
int nSilverBox = 0; //ebp-24
int nEtcItem = 0; //ebp-28
int nType = 0; //ebp-2c
bool bCheckSourceItem = false; //ebp-30
lpObj->ChaosLock = true;
// ----
for( int i = 0; i < CHAOS_BOX_SIZE; i++ ) //ebp-34
{
if( lpObj->pChaosBox[i].IsItem() )
{
if( lpObj->pChaosBox[i].m_Type == ITEMGET(14, 113) )
{
nGoldenKey++;
}
else if( lpObj->pChaosBox[i].m_Type == ITEMGET(14, 112) )
{
nSilverKey++;
}
else if( lpObj->pChaosBox[i].m_Type == ITEMGET(14, 121) )
{
nGoldenBox++;
}
else if( lpObj->pChaosBox[i].m_Type == ITEMGET(14, 122) )
{
nSilverBox++;
}
else
{
nEtcItem++;
}
}
}
// ----
if( nEtcItem >= 1 || nGoldenKey != 1 && nSilverKey != 1 )
{
bCheckSourceItem = false;
}
else if( nGoldenKey == 1 && nGoldenBox == 1 && !nSilverKey && !nSilverBox )
{
nType = ITEMGET(14, 123);
bCheckSourceItem = true;
}
else if( nSilverKey == 1 && nSilverBox == 1 && !nGoldenKey && !nGoldenBox )
{
nType = ITEMGET(14, 124);
bCheckSourceItem = true;
}
// ----
if( bCheckSourceItem )
{
ItemSerialCreateSend(lpObj->m_Index, 0xFF, 0, 0, nType, 0, 0, 0, 0, 0, -1, 0, 0);
gObjInventoryCommit(lpObj->m_Index);
return;
}
// ----
pMsg.Result = 1;
DataSend(lpObj->m_Index, (LPBYTE)&pMsg, pMsg.h.size);
lpObj->ChaosLock = false;
}
void CChaosBox::SocketItemMix(LPOBJ lpObj,int iMixId)
{
lpObj->ChaosLock = TRUE;
int iSocketItem = -1;
int iNeedChaosMoney;
int iSocketItemCount = 0;
int iRecipeCount = 0;
int iMaterial1Index = -1;
int iMaterial2Index = -1;
int iMaterialCount[9] = {0};
int iCharmOfLuckCount = 0;
int iOtherItemCount = 0;
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
for(int n = 0; n < CHAOS_BOX_SIZE; n++) {
if( !lpObj->pChaosBox[n].IsItem() )
continue;
if( g_SocketItem.IsSocketItem(lpObj->pChaosBox[n].m_Type) &&
lpObj->pChaosBox[n].m_Level >= 7 &&
lpObj->pChaosBox[n].m_Option3 >= 1 )
{
iSocketItemCount++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,191) )
{
iSocketItem = ITEMGET(0,29);
iMaterial1Index = 0;
iMaterial2Index = 8;
iRecipeCount++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,192) )
{
iSocketItem = ITEMGET(0,36);
iMaterial1Index = 1;
iMaterial2Index = 5;
iRecipeCount++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,193) )
{
iSocketItem = ITEMGET(0,37);
iMaterial1Index = 2;
iMaterial2Index = 8;
iRecipeCount++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,194) )
{
iSocketItem = ITEMGET(3,12);
iMaterial1Index = 3;
iMaterial2Index = 5;
iRecipeCount++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,195) )
{
iSocketItem = ITEMGET(2,20);
iMaterial1Index = 2;
iMaterial2Index = 6;
iRecipeCount++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,196) )
{
iSocketItem = ITEMGET(4,25);
iMaterial1Index = 0;
iMaterial2Index = 5;
iRecipeCount++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,197) )
{
iSocketItem = ITEMGET(4,26);
iMaterial1Index = 4;
iMaterial2Index = 7;
iRecipeCount++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,198) )
{
iSocketItem = ITEMGET(5,35);
iMaterial1Index = 2;
iMaterial2Index = 5;
iRecipeCount++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,199) )
{
iSocketItem = ITEMGET(5,37);
iMaterial1Index = 4;
iMaterial2Index = 6;
iRecipeCount++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,200) )
{
iSocketItem = ITEMGET(0,30);
iMaterial1Index = 4;
iMaterial2Index = 8;
iRecipeCount++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,201) )
{
iSocketItem = ITEMGET(2,19);
iMaterial1Index = 1;
iMaterial2Index = 7;
iRecipeCount++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,202) )
{
iSocketItem = ITEMGET(5,32);
iMaterial1Index = 4;
iMaterial2Index = 5;
iRecipeCount++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,180) )
{
iMaterialCount[0]++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,181) )
{
iMaterialCount[1]++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,182) )
{
iMaterialCount[2]++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,183) )
{
iMaterialCount[3]++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,184) )
{
iMaterialCount[4]++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,185) )
{
iMaterialCount[5]++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,186) )
{
iMaterialCount[6]++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,187) )
{
iMaterialCount[7]++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,188) )
{
iMaterialCount[8]++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,53) )
{
iCharmOfLuckCount += (int)lpObj->pChaosBox[n].m_Durability;
}
else
{
iOtherItemCount++;
}
}
if( iCharmOfLuckCount > 10 ) {
pMsg.Result = 0xF0;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
if( iOtherItemCount != 0 ||
iSocketItemCount != 3 ||
iRecipeCount != 1 ||
iMaterial1Index == -1 ||
iMaterial2Index == -1 )
{
pMsg.Result = 7;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
for(int i = 0; i < 9; i++) {
if( i == iMaterial1Index && iMaterialCount[i] == 2 )
continue;
if( i == iMaterial2Index && iMaterialCount[i] == 1 )
continue;
if( iMaterialCount[i] != 0 ) {
pMsg.Result = 7;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
}
LogChaosItem(lpObj, "SocketItemMix");
LogAddTD("[SocketItemMix] Chaos Mix Start");
lpObj->ChaosSuccessRate = 40;
iNeedChaosMoney = 1000000;
lpObj->ChaosSuccessRate += iCharmOfLuckCount;
int iChaosTaxMoney = (int)((__int64)iNeedChaosMoney * (__int64)g_CastleSiegeSync.GetTaxRateChaos(lpObj->m_Index) / (__int64)100);
if ( iChaosTaxMoney < 0 )
{
iChaosTaxMoney = 0;
}
iNeedChaosMoney += iChaosTaxMoney;
if ( iNeedChaosMoney < 0 )
{
iNeedChaosMoney = 0;
}
if(lpObj->Money < iNeedChaosMoney)
{
pMsg.Result = CB_NOT_ENOUGH_ZEN;
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
lpObj->Money -= iNeedChaosMoney;
g_CastleSiegeSync.AddTributeMoney(iChaosTaxMoney);
GCMoneySend(lpObj->m_Index,lpObj->Money);
if( rand() % 100 < lpObj->ChaosSuccessRate )
{
int Option1 = TRUE;
int Option2 = 0;
if( rand() % 1000 <= 50 ) {
Option2 = TRUE;
}
int Rand1 = rand() % 4;
int Rand2 = rand() % 1000;
int Option3 = 0;
switch( Rand1 )
{
case 1:
if( Rand2 < 120 )
{
Option3 = 1;
}
break;
case 2:
if( Rand2 < 60 )
{
Option3 = 2;
}
break;
case 3:
if( Rand2 < 30 )
{
Option3 = 3;
}
break;
}
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, true);
#endif
ItemSerialCreateSend(lpObj->m_Index,255,0,0,iSocketItem,0,0,Option1,Option2,Option3,-1,0,0);
gObjInventoryCommit(lpObj->m_Index);
LogAddTD("[SocketItemMix][Level 02] [%s][%s] CBMix Success %d Money : %d-%d, CharmRate : %d",
lpObj->AccountID,lpObj->Name,lpObj->ChaosSuccessRate,lpObj->Money,iNeedChaosMoney,iCharmOfLuckCount);
}
else
{
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, false);
#endif
ChaosBoxInit(lpObj);
GCUserChaosBoxSend(lpObj,0);
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
LogAddTD("[SocketItemMix] [%s][%s] CBMix Fail %d Money : %d-%d, CharmRate : %d",
lpObj->AccountID,lpObj->Name,lpObj->ChaosSuccessRate,lpObj->Money,iNeedChaosMoney,iCharmOfLuckCount);
lpObj->ChaosLock = FALSE;
}
}
void CChaosBox::Wing25Mix(LPOBJ lpObj)
{
lpObj->ChaosLock = TRUE;
int iNeedChaosMoney;
int iWingID = -1;
int iMaterialID = -1;
int iWingValue = 0;
int iWingCount = 0;
int iChaosCount = 0;
int iCreationCount = 0;
int iMaterialCount = 0;
int iOtherItemCount = 0;
int iCharmOfLuckCount = 0;
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
for(int n = 0; n < CHAOS_BOX_SIZE; n++) {
if( !lpObj->pChaosBox[n].IsItem() )
continue;
if( lpObj->pChaosBox[n].m_Type == ITEMGET(12,15) )
{
iChaosCount++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,22) )
{
iCreationCount++;
}
else if( (lpObj->pChaosBox[n].m_Type >= ITEMGET(12,3) && lpObj->pChaosBox[n].m_Type <= ITEMGET(12,6)) ||
lpObj->pChaosBox[n].m_Type == ITEMGET(12,42) ||
lpObj->pChaosBox[n].m_Type == ITEMGET(12,49) ||
lpObj->pChaosBox[n].m_Type == ITEMGET(13,30) )
{
iWingID = lpObj->pChaosBox[n].m_Type;
iWingValue = lpObj->pChaosBox[n].m_BuyMoney;
iWingCount++;
}
else if( (lpObj->pChaosBox[n].m_Type >= ITEMGET(14,176) && lpObj->pChaosBox[n].m_Type <= ITEMGET(14,179)) )
{
iMaterialID = lpObj->pChaosBox[n].m_Type;
iMaterialCount++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,53) )
{
iCharmOfLuckCount += (int)lpObj->pChaosBox[n].m_Durability;
}
else
{
iOtherItemCount++;
}
}
if( iCharmOfLuckCount > 10 ) {
pMsg.Result = 0xF0;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
if( iOtherItemCount != 0 ||
iMaterialCount != 1 ||
iWingCount != 1 ||
iCreationCount != 1 ||
iChaosCount != 1 )
{
pMsg.Result = 7;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
LogChaosItem(lpObj, "25WingLevel");
LogAddTD("[25Wing Mix] Chaos Mix Start");
int iDivValue = 9000000;
if( iWingID == ITEMGET(13,30) || iWingID == ITEMGET(12,49) )
{
iDivValue = 500000;
}
lpObj->ChaosSuccessRate = iWingValue/iDivValue;
if( lpObj->ChaosSuccessRate < 0 )
lpObj->ChaosSuccessRate = 1;
if( lpObj->ChaosSuccessRate > 60 )
lpObj->ChaosSuccessRate = 60;
iNeedChaosMoney = lpObj->ChaosSuccessRate*100000;
lpObj->ChaosSuccessRate += iCharmOfLuckCount;
int iChaosTaxMoney = (int)((__int64)iNeedChaosMoney * (__int64)g_CastleSiegeSync.GetTaxRateChaos(lpObj->m_Index) / (__int64)100);
if ( iChaosTaxMoney < 0 )
{
iChaosTaxMoney = 0;
}
iNeedChaosMoney += iChaosTaxMoney;
if ( iNeedChaosMoney < 0 )
{
iNeedChaosMoney = 0;
}
if(lpObj->Money < iNeedChaosMoney)
{
pMsg.Result = CB_NOT_ENOUGH_ZEN;
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
lpObj->Money -= iNeedChaosMoney;
g_CastleSiegeSync.AddTributeMoney(iChaosTaxMoney);
GCMoneySend(lpObj->m_Index,lpObj->Money);
if( rand() % 100 < lpObj->ChaosSuccessRate )
{
int Item = ITEMGET(12,262+(iMaterialID-ITEMGET(14,176)));
int Option1 = 0;
int Option2 = 0;
if( rand() % 1000 <= iOptionRate )
{
Option2 = TRUE;
}
int Option3 = 0;
int ExcOption = 0;
int Rand = rand() % 1000;
if( Rand < 400 )
{
ExcOption |= 0x10;
}
int Rand2 = rand() % 4;
int Rand3 = rand() % 1000;
Option3 = 0;
switch( Rand2 )
{
case 1:
if( Rand3 < 120 )
Option3 = 1;
break;
case 2:
if( Rand3 < 60 )
Option3 = 2;
break;
case 3:
if( Rand3 < 30 )
Option3 = 3;
break;
}
int Rand4 = rand() % 2;
int Rand5 = rand() % 1000;
switch( Rand4 )
{
case 0:
if( Rand5 < 40 )
{
ExcOption |= 0x01;
}
break;
case 1:
if( Rand5 < 20 )
{
ExcOption |= 0x02;
}
break;
}
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, true);
#endif
ItemSerialCreateSend(lpObj->m_Index,255,0,0,Item,0,0,Option1,Option2,Option3,-1,ExcOption,0);
gObjInventoryCommit(lpObj->m_Index);
LogAddTD("[25Wing Mix] [%s][%s] CBMix Success %d Money : %d-%d, CharmRate : %d",
lpObj->AccountID,lpObj->Name,lpObj->ChaosSuccessRate,lpObj->Money,iNeedChaosMoney,iCharmOfLuckCount);
}
else
{
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, false);
#endif
ChaosBoxInit(lpObj);
GCUserChaosBoxSend(lpObj,0);
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
LogAddTD("[25Wing Mix] [%s][%s] CBMix Fail %d Money : %d-%d, CharmRate : %d",
lpObj->AccountID,lpObj->Name,lpObj->ChaosSuccessRate,lpObj->Money,iNeedChaosMoney,iCharmOfLuckCount);
lpObj->ChaosLock = FALSE;
}
}
#if (CUSTOM_WINGS == 1)
void CChaosBox::Create4thWings(LPOBJ lpObj)
{
lpObj->ChaosLock = TRUE;
int iSocketItemCount = 0;
int iWingCount = 0;
int iCondorFeatherCount = 0;
int iFeatherCount = 0;
int iChaosCount = 0;
int iCreationCount =0;
int iGuardianCount =0;
int iOtherItemCount = 0;
int iNeedChaosMoney = 0;
int iCharmOfLuckCount = 0;
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
pMsg.Result = CB_ERROR;
for(int n = 0; n < CHAOS_BOX_SIZE; n++)
{
if( lpObj->pChaosBox[n].IsItem() == TRUE )
{
if( g_SocketItem.IsSocketItem(lpObj->pChaosBox[n].m_Type) &&
lpObj->pChaosBox[n].m_Level >= 9 &&
lpObj->pChaosBox[n].m_Option3 >= 1 )
{
iSocketItemCount++;
}
else if( ( (lpObj->pChaosBox[n].m_Type >= ITEMGET(12,36) && lpObj->pChaosBox[n].m_Type <= ITEMGET(12,40)) || lpObj->pChaosBox[n].m_Type == ITEMGET(12,43) || lpObj->pChaosBox[n].m_Type == ITEMGET(12,50) ) &&
lpObj->pChaosBox[n].m_Level >= 9 &&
lpObj->pChaosBox[n].m_Option3 >= 1 )
{
iWingCount++;
}
else if( lpObj->pChaosBox[n].m_Type == iCondorFeather )
{
iCondorFeatherCount++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(13,14) )
{
iFeatherCount++;
}
else if( lpObj->pChaosBox[n].m_Type == iChaosJewel )
{
iChaosCount++;
}
else if( lpObj->pChaosBox[n].m_Type == iCreationJewel )
{
iCreationCount++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,31) )
{
iGuardianCount++;
}
else if( lpObj->pChaosBox[n].m_Type == ITEMGET(14,53) )
{
iCharmOfLuckCount += (int)lpObj->pChaosBox[n].m_Durability;
}
else
{
iOtherItemCount++;
}
}
}
if( iCharmOfLuckCount > 10 )
{
pMsg.Result = 0xF0;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
if( iSocketItemCount != 1 ||
iWingCount != 1 ||
iCondorFeatherCount != 1 ||
iFeatherCount != 1 ||
iChaosCount != 1 ||
iCreationCount != 1 ||
iGuardianCount != 1 ||
iOtherItemCount > 0 )
{
pMsg.Result = 7;
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
LogChaosItem(lpObj, "4thWingLevel");
LogAddTD("[4thWing Mix] Chaos Mix Start");
lpObj->ChaosSuccessRate = 35;
iNeedChaosMoney = 100000000;
lpObj->ChaosSuccessRate += iCharmOfLuckCount;
int iChaosTaxMoney = (int)((__int64)iNeedChaosMoney * (__int64)g_CastleSiegeSync.GetTaxRateChaos(lpObj->m_Index) / (__int64)100);
if ( iChaosTaxMoney < 0 )
{
iChaosTaxMoney = 0;
}
iNeedChaosMoney += iChaosTaxMoney;
if ( iNeedChaosMoney < 0 )
{
iNeedChaosMoney = 0;
}
if(lpObj->Money < iNeedChaosMoney)
{
pMsg.Result = CB_NOT_ENOUGH_ZEN;
DataSend(lpObj->m_Index, (BYTE *)&pMsg, pMsg.h.size);
lpObj->ChaosLock = FALSE;
return;
}
lpObj->Money -= iNeedChaosMoney;
g_CastleSiegeSync.AddTributeMoney(iChaosTaxMoney);
GCMoneySend(lpObj->m_Index,lpObj->Money);
if( rand() % 100 < lpObj->ChaosSuccessRate )
{
int Item = ITEMGET(12,440) + rand()%6;
int Option1 = 0;
int Option2 = 0;
if( rand() % 1000 <= iOptionRate )
{
Option2 = TRUE;
}
int Option3 = 0;
int ExcOption = 0;
int Rand = rand() %2;
int Rand2;
switch( Rand )
{
case 0:
Rand2 = rand() % 1000;
if( Rand2 < 400 )
{
ExcOption |= 0x10;
}
break;
case 1:
Rand2 = rand() % 1000;
if( Rand2 < 300 )
{
ExcOption |= 0x20;
}
break;
}
int Rand3 = rand() % 4;
int Rand4 = rand() % 1000;
Option3 = 0;
switch( Rand3 )
{
case 1:
if( Rand4 < 120 )
{
Option3 = 1;
}
break;
case 2:
if( Rand4 < 60 )
{
Option3 = 2;
}
break;
case 3:
if( Rand4 < 30 )
{
Option3 = 3;
}
break;
}
int Rand5 = rand() % 4;
int Rand6 = rand() % 1000;
switch( Rand5 )
{
case 0:
if( Rand6 < 40 )
{
ExcOption |= 0x01;
}
break;
case 1:
if( Rand6 < 20 )
{
ExcOption |= 0x02;
}
break;
case 2:
if( Rand6 < 70 )
{
ExcOption |= 0x04;
}
break;
case 3:
if( Rand6 < 70 )
{
ExcOption |= 0x08;
}
break;
}
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, true);
#endif
ItemSerialCreateSend(lpObj->m_Index,255,0,0,Item,0,0,Option1,Option2,Option3,-1,ExcOption,0);
gObjInventoryCommit(lpObj->m_Index);
LogAddTD("[4thWing Mix][Level 02] [%s][%s] CBMix Success %d Money : %d-%d, CharmRate : %d",
lpObj->AccountID,lpObj->Name,lpObj->ChaosSuccessRate,lpObj->Money,iNeedChaosMoney,iCharmOfLuckCount);
}
else
{
#if( __4GAMERS__ == 1 )
g_Achievements.GD_UpdateMixData(lpObj, false);
#endif
ChaosBoxInit(lpObj);
GCUserChaosBoxSend(lpObj,0);
DataSend(lpObj->m_Index,(LPBYTE)&pMsg,pMsg.h.size);
LogAddTD("[4thWing Mix] [%s][%s] CBMix Fail %d Money : %d-%d, CharmRate : %d",
lpObj->AccountID,lpObj->Name,lpObj->ChaosSuccessRate,lpObj->Money,iNeedChaosMoney,iCharmOfLuckCount);
lpObj->ChaosLock = FALSE;
}
}
#endif
#ifdef __NOVUS__
void CChaosBox::RareItem(LPOBJ lpUser)
{
PMSG_CHAOSMIXRESULT pMsg;
PHeadSetB((LPBYTE)&pMsg.h, 0x86, sizeof(PMSG_CHAOSMIXRESULT));
// ----
pMsg.Result = CB_ERROR;
int RareItemCount = 0;
int ItemType = 0;
int EtcItem = 0;
bool bCheckSourceItem = false;
lpUser->ChaosLock = true;
// ----
for( int i = 0; i < CHAOS_BOX_SIZE; i++ )
{
if( lpUser->pChaosBox[i].IsItem() )
{
if( lpUser->pChaosBox[i].m_Type >= ITEMGET(14, 58) && lpUser->pChaosBox[i].m_Type <= ITEMGET(14, 62)
|| lpUser->pChaosBox[i].m_Type >= ITEMGET(14, 145) && lpUser->pChaosBox[i].m_Type <= ITEMGET(14, 150) )
{
RareItemCount++;
ItemType = lpUser->pChaosBox[i].m_Type;
}
else
{
EtcItem++;
}
}
}
// ----
if( EtcItem >= 1 || RareItemCount != 1 )
{
bCheckSourceItem = false;
}
// ----
if( bCheckSourceItem )
{
int MixItem = ITEMGET(14, 16);
//switch(ItemType)
// ----
ItemSerialCreateSend(lpUser->m_Index, 0xFF, 0, 0, MixItem, 0, 0, 0, 0, 0, -1, 0, 0);
gObjInventoryCommit(lpUser->m_Index);
return;
}
// ----
pMsg.Result = 1;
DataSend(lpUser->m_Index, (LPBYTE)&pMsg, pMsg.h.size);
lpUser->ChaosLock = false;
}
#endif | 23.179741 | 288 | 0.655026 | sp3cialk |
738f2206ce3e2d2398e3a13b609fd024904466ff | 4,969 | cpp | C++ | SDK/Extras/Quesa Model Viewer/AdvMoof Source/AdvWindow.cpp | h-haris/Quesa | a438ab824291ce6936a88dfae4fd0482dcba1247 | [
"BSD-3-Clause"
] | 24 | 2019-10-28T07:01:48.000Z | 2022-03-04T16:10:39.000Z | SDK/Extras/Quesa Model Viewer/AdvMoof Source/AdvWindow.cpp | h-haris/Quesa | a438ab824291ce6936a88dfae4fd0482dcba1247 | [
"BSD-3-Clause"
] | 8 | 2020-04-22T19:42:45.000Z | 2021-04-30T16:28:32.000Z | SDK/Extras/Quesa Model Viewer/AdvMoof Source/AdvWindow.cpp | h-haris/Quesa | a438ab824291ce6936a88dfae4fd0482dcba1247 | [
"BSD-3-Clause"
] | 6 | 2019-09-22T14:44:15.000Z | 2021-04-01T20:04:29.000Z | #include "AdvWindow.h"
#include "ResourceIDs.h"
AdvWindow::AdvWindow(const Rect &r, const Str255 title,
const short defProc, const Boolean hasCloseBox)
: inherited( r, title, defProc, hasCloseBox ), mDirty(false)
{
mFSSpec.name[0] = 0;
mSaveFileType = kDocFileType;
mSaveFileCreator = kAppCreatorCode;
}
void AdvWindow::InitFromFile( const FSSpec &spec )
{
short fsRefNum;
OSErr err = FSpOpenDF(&spec, fsCurPerm, &fsRefNum);
if (!err) {
SetFSSpec( spec );
SetWTitle( mWindowPtr, spec.name );
err = ReadFromFile( fsRefNum );
FSClose( fsRefNum );
}
else {
HandleError( err );
CloseSelf();
}
}
Boolean AdvWindow::HandleMenuSelection( const short menuNum, const short itemNum )
{
if (menuNum == kFileMenuID) {
switch (itemNum) {
// case kCloseItem: DoClose(); return true;
case kSaveItem: DoSave(); return true;
case kSaveAsItem: DoSaveAs(); return true;
}
}
return inherited::HandleMenuSelection( menuNum, itemNum );
}
Boolean AdvWindow::CanClose(Boolean quitting)
{
// if not saved, ask whether to save first
if (mDirty) {
Str255 name;
GetWTitle( mWindowPtr, name );
#if TARGET_API_MAC_CARBON
/*
// Under Carbon, we're only supposed to ask once if quitting.
// So remember any previous answer.
static Boolean askedAboutQuitting = false;
static Boolean saveBeforeQuit = false;
if (quitting and askedAboutQuitting) {
if (saveBeforeQuit) DoSave();
return true;
}
*/
NavDialogRef dlog = NULL;
NavDialogCreationOptions options;
NavGetDefaultDialogCreationOptions(&options);
options.saveFileName = CFStringCreateWithPascalStringNoCopy(
kCFAllocatorDefault, name, kCFStringEncodingMacRoman, NULL);
OSStatus err = NavCreateAskSaveChangesDialog(&options,
quitting ? kNavSaveChangesQuittingApplication : kNavSaveChangesClosingDocument,
NULL,
NULL,
&dlog);
if (noErr == err) {
err = NavDialogRun(dlog); // doesn't actually run under CarbonLib!!!
}
if (noErr == err) {
NavUserAction answer = NavDialogGetUserAction(dlog);
if (kNavUserActionSaveChanges == answer) DoSave();
NavDialogDispose(dlog);
if (kNavUserActionCancel == answer) return false;
/* if (quitting) {
askedAboutQuitting = true;
saveBeforeQuit = (kNavUserActionSaveChanges == answer);
}
*/
return true;
}
#endif
if (quitting) {
ParamText( name, "\pclosing", NULL, NULL );
}
else {
ParamText( name, "\pquitting", NULL, NULL );
}
short button = Alert(kSaveConfirmID, 0L);
if (button == 1) DoSave();
else if (button == 3) return false; // cancelled
}
// OK, now we can close the window...
return true;
}
void AdvWindow::DoSave()
{
// if we don't already have a filespec name, do "save as" instead
if (!mFSSpec.name[0]) {
DoSaveAs();
}
// We'll let Saver do the hard work for us...
else {
OSErr err = Saver::SaveDoc(mFSSpec, mScript);
if (err == noErr) {
// note that we're now saved...
mDirty = false;
} else HandleError(err);
}
}
OSErr AdvWindow::DoSaveAs(FSSpec *inOutSpec, ScriptCode *outScript, Str255 prompt)
{
// We'll use Saver to display a Nav-savvy dialog box,
// and trigger subsequent saving.
Str255 oldFName;
BlockMoveData( &mFSSpec.name, oldFName, 256 );
GetWTitle( mWindowPtr, mFSSpec.name );
OSErr err = Saver::DoSaveAs(&mFSSpec, &mScript, prompt);
if (err == noErr) {
mDirty = false;
SetWTitle( mWindowPtr, mFSSpec.name );
} else if (err == userCanceledErr) {
// user cancelled -- restore previous FSSpec name, if any
BlockMoveData( oldFName, mFSSpec.name, 256 );
return err;
}
else HandleError(err);
if (inOutSpec) BlockMoveData( &mFSSpec, inOutSpec, sizeof(FSSpec) );
if (outScript) *outScript = mScript;
return err;
}
void AdvWindow::SetFSSpec(const FSSpec& spec)
{
// copy the spec
BlockMoveData( &spec, &mFSSpec, sizeof(FSSpec) );
// set the window title to match
SetWTitle( mWindowPtr, mFSSpec.name );
}
void AdvWindow::DrawGrowBox(const Boolean withScrollBars)
{
// draw grow icon
if (!withScrollBars) {
// get previous clipping region
RgnHandle saveClipRgn = NewRgn();
GetClip( saveClipRgn );
// clip to the area just around the grow box
Rect r = GetPortRect();
r.top = r.bottom - 15;
r.left = r.right - 15;
ClipRect(&r);
// draw the grow icon
DrawGrowIcon(mWindowPtr);
// restore saved clipping region
SetClip( saveClipRgn ); /* restore previous value */
DisposeRgn( saveClipRgn ); /* not needed any more */
}
else DrawGrowIcon(mWindowPtr);
}
void AdvWindow::SaverWindowUpdate(WindowPtr window)
{
// If it's a Moof window, tell it to refresh!
MoofWindow *moofwin = gApplication->RefConToMoofWin( GetWRefCon(window) );
if (moofwin) {
CGrafPtr oldPort;
GDHandle oldDevice;
GetGWorld(&oldPort, &oldDevice);
moofwin->Focus();
BeginUpdate(window);
moofwin->Draw();
EndUpdate(window);
SetGWorld(oldPort, oldDevice);
}
else {
Saver::SaverWindowUpdate(window);
}
}
| 26.152632 | 83 | 0.688267 | h-haris |
739362fc3002d68707c63ffe437b7ea598f24533 | 671 | hpp | C++ | StartScreen.hpp | MineOzelot/Tseitr | f1629f53c08bacba30106026fa53883dcc335006 | [
"MIT"
] | null | null | null | StartScreen.hpp | MineOzelot/Tseitr | f1629f53c08bacba30106026fa53883dcc335006 | [
"MIT"
] | null | null | null | StartScreen.hpp | MineOzelot/Tseitr | f1629f53c08bacba30106026fa53883dcc335006 | [
"MIT"
] | null | null | null | //
// Created by mineozelot on 8/11/18.
//
#ifndef TSEITR_STARTSCREEN_HPP
#define TSEITR_STARTSCREEN_HPP
#include "Screen.hpp"
#include "Game.hpp"
#include "Label.hpp"
class StartScreen: public Screen {
Label *label_startgame = nullptr;
Label *label_leaderboard = nullptr;
Label *label_exit = nullptr;
SDL_Rect selections[3];
int selection = 0;
public:
void init(Game *game) override;
void handle(Game *game, const SDL_Event &event) override;
void update(Game *game) override;
void render(Game *game) override;
void select(Game *game);
void pause() override {}
void resume() override {}
void dispose() override;
};
#endif //TSEITR_STARTSCREEN_HPP
| 18.135135 | 58 | 0.731744 | MineOzelot |
739435c4353a68cdc3bb4d3c252e8f802d7ec302 | 1,543 | cpp | C++ | done/reduce.cpp | birdhumming/usaco | f011e7bd4b71de22736a61004e501af2b273b246 | [
"OLDAP-2.2.1"
] | null | null | null | done/reduce.cpp | birdhumming/usaco | f011e7bd4b71de22736a61004e501af2b273b246 | [
"OLDAP-2.2.1"
] | null | null | null | done/reduce.cpp | birdhumming/usaco | f011e7bd4b71de22736a61004e501af2b273b246 | [
"OLDAP-2.2.1"
] | null | null | null | #include <iostream>
#include <algorithm>
using namespace std;
typedef pair <int, int> ii;
int N;
ii cows[50001];
bool comp1(ii a, ii b) { return a.first < b.first; }
bool comp2(ii a, ii b) { return a.second < b.second; }
bool valid(int sx, int bx, int sy, int by)
{
if (sx > bx || sy > by) return false;
int outside = 0;
for (int i = 0; i < N; i++) {
int x = cows[i].first; int y = cows[i].second;
if (x < sx || x > bx || y < sy || y > by) outside++;
if (outside > 3) return false;
}
return true;
}
int main()
{
freopen("reduce.in", "r", stdin);
freopen("reduce.out", "w", stdout);
cin>>N;
for (int i = 0; i < N; i++) cin>>cows[i].first>>cows[i].second;
int sx[4], bx[4], sy[4], by[4]; //small x, big x, small y, big y
sort(cows, cows+N, comp1);
for (int i = 0; i < 4; i++) {
sx[i] = cows[i].first;
bx[i] = cows[N - i - 1].first;
}
sort(cows, cows+N, comp2);
for (int i = 0; i < 4; i++) {
sy[i] = cows[i].second;
by[i] = cows[N - i - 1].second;
}
long ans = 10000000000000000;
for (int a = 0; a < 4; a++) {
for (int b = 0; b < 4; b++) {
for (int c = 0; c < 4; c++) {
for (int d = 0; d < 4; d++) {
if (valid(sx[a], bx[b], sy[c], by[d])) {
int area = (bx[b] - sx[a]) * (by[d] -s y[c]);
if (area < ans) ans = area;
}
}
}
}
}
cout<<ans<<'\n';
}
| 26.603448 | 69 | 0.436811 | birdhumming |
73949bd7cbc148e499238c30524e692fd54a164a | 600 | cpp | C++ | master/core/third/RCF/src/RCF/Tools.cpp | importlib/klib | a59837857689d0e60d3df6d2ebd12c3160efa794 | [
"MIT"
] | 4 | 2017-12-04T08:22:48.000Z | 2019-10-26T21:44:59.000Z | master/core/third/RCF/src/RCF/Tools.cpp | isuhao/klib | a59837857689d0e60d3df6d2ebd12c3160efa794 | [
"MIT"
] | null | null | null | master/core/third/RCF/src/RCF/Tools.cpp | isuhao/klib | a59837857689d0e60d3df6d2ebd12c3160efa794 | [
"MIT"
] | 4 | 2017-12-04T08:22:49.000Z | 2018-12-27T03:20:31.000Z |
//*****************************************************************************
// RCF - Remote Call Framework
// Copyright (c) 2005. All rights reserved.
// Developed by Jarl Lindrud.
// Contact: jlindrud@hotmail.com .
//*****************************************************************************
#include <RCF/Tools.hpp>
#include <RCF/util/InitDeinit.hpp>
namespace RCF {
util::TraceChannel &getRcfTraceChannel()
{
static util::TraceChannel rcfTraceChannel("RCF");
return rcfTraceChannel;
}
UTIL_ON_INIT( getRcfTraceChannel() )
}
| 23.076923 | 80 | 0.47 | importlib |
7394d738947489a33f1795a8f97fb3a8aa8efc70 | 416 | cpp | C++ | LimeEngine/Engine/IO/EngineIO.cpp | RubyCircle/LimeEngine | 06e3628f2aeb3ce023c1251a6379a26b2df2de4b | [
"MIT"
] | 1 | 2022-01-04T19:25:46.000Z | 2022-01-04T19:25:46.000Z | LimeEngine/Engine/IO/EngineIO.cpp | RubyCircle/LimeEngine | 06e3628f2aeb3ce023c1251a6379a26b2df2de4b | [
"MIT"
] | null | null | null | LimeEngine/Engine/IO/EngineIO.cpp | RubyCircle/LimeEngine | 06e3628f2aeb3ce023c1251a6379a26b2df2de4b | [
"MIT"
] | null | null | null | #include "EngineIO.hpp"
namespace LimeEngine
{
EngineIO::EngineIO(RenderIO&& renderIO, SceneIO&& sceneIO) : renderIO(std::move(renderIO)), sceneIO(std::move(sceneIO)) {}
std::optional<int> EngineIO::Process()
{
return renderIO.Process();
}
void EngineIO::Render()
{
renderIO.Render(sceneIO.camera);
}
InputDevice& EngineIO::GetInput() noexcept
{
return renderIO.renderer->window->inputDevice;
}
} | 19.809524 | 123 | 0.711538 | RubyCircle |
73957798587045c386d9d683a9584bfa06ba8f3a | 34,704 | cpp | C++ | test/ut/gpio/GpioSettingsControllerTests.cpp | bkozdras/picosdkal | 1830a2b0296510a5d40a69d22d9a21618d664528 | [
"MIT"
] | null | null | null | test/ut/gpio/GpioSettingsControllerTests.cpp | bkozdras/picosdkal | 1830a2b0296510a5d40a69d22d9a21618d664528 | [
"MIT"
] | null | null | null | test/ut/gpio/GpioSettingsControllerTests.cpp | bkozdras/picosdkal | 1830a2b0296510a5d40a69d22d9a21618d664528 | [
"MIT"
] | null | null | null | /**********************************************************************************/
/* Copyright by @bkozdras <b.kozdras@gmail.com> */
/* Version: 1.0 */
/* Licence: MIT */
/**********************************************************************************/
#include <algorithm>
#include <cstdint>
#include <utility>
#include <vector>
#include <gmock/gmock.h>
#include <rpipicosdkal/core/Types.hpp>
#include <rpipicosdkal/core/definitions/EOperationResult.hpp>
#include <rpipicosdkal/gpio/fwd.hpp>
#include <rpipicosdkal/gpio/GpioSettingsController.hpp>
#include <rpipicosdkal/gpio/definitions/EGpioDirection.hpp>
#include <rpipicosdkal/gpio/definitions/EGpioDriveStrength.hpp>
#include <rpipicosdkal/gpio/definitions/EGpioFunction.hpp>
#include <rpipicosdkal/gpio/definitions/EGpioPullUp.hpp>
#include <rpipicosdkal/gpio/definitions/EGpioSlewRateLimiting.hpp>
#include <picosdkmock/hardware_gpio/GpioMock.hpp>
#include <testutil/SourceLocationPrinter.hpp>
namespace rpipicosdkal
{
namespace gpio
{
namespace
{
std::vector<std::pair<definitions::EGpioFunction, enum gpio_function>> generateAllGpioFunctions()
{
std::vector<std::pair<definitions::EGpioFunction, enum gpio_function>> gpioFunctions =
{
std::make_pair(definitions::EGpioFunction::NotSet, GPIO_FUNC_NULL),
std::make_pair(definitions::EGpioFunction::XIP, GPIO_FUNC_XIP),
std::make_pair(definitions::EGpioFunction::SPI, GPIO_FUNC_SPI),
std::make_pair(definitions::EGpioFunction::UART, GPIO_FUNC_UART),
std::make_pair(definitions::EGpioFunction::I2C, GPIO_FUNC_I2C),
std::make_pair(definitions::EGpioFunction::PWM, GPIO_FUNC_PWM),
std::make_pair(definitions::EGpioFunction::SIO, GPIO_FUNC_SIO),
std::make_pair(definitions::EGpioFunction::PIO0, GPIO_FUNC_PIO0),
std::make_pair(definitions::EGpioFunction::PIO1, GPIO_FUNC_PIO1),
std::make_pair(definitions::EGpioFunction::GPCK, GPIO_FUNC_GPCK),
std::make_pair(definitions::EGpioFunction::USB, GPIO_FUNC_USB)
};
return gpioFunctions;
}
std::vector<std::pair<definitions::EGpioFunction, enum gpio_function>> generateAllGpioFunctionsExcept(
const std::vector<definitions::EGpioFunction>& excludedGpioFunctions)
{
auto gpioFunctions = generateAllGpioFunctions();
for (const auto excludedGpioFunction : excludedGpioFunctions)
{
gpioFunctions.erase(std::remove_if(std::begin(gpioFunctions),
std::end(gpioFunctions),
[excludedGpioFunction](const auto& gpioFunction)
{
return excludedGpioFunction == gpioFunction.first;
}),
std::end(gpioFunctions));
}
return gpioFunctions;
}
std::vector<std::pair<definitions::EGpioFunction, enum gpio_function>> generateAllGpioFunctionsExcept(
const definitions::EGpioFunction excludedGpioFunction)
{
return generateAllGpioFunctionsExcept(std::vector<definitions::EGpioFunction>{excludedGpioFunction});
}
std::vector<core::TGpioNumber> generateInvalidGpioNumbers()
{
std::vector<core::TGpioNumber> invalidGpioNumbers = {23u, 24u};
for (auto number = 29u; number <= 100u; ++number)
{
invalidGpioNumbers.push_back(number);
}
return invalidGpioNumbers;
}
} // namespace
class GpioSettingsControllerShould : public ::testing::Test
{
protected:
GpioSettingsControllerShould();
IGpioSettingsControllerPtr createSut();
void expectAllGpiosFunctionSetToSioInputOnCreation(
const std::source_location& location = std::source_location::current());
picosdkmock::hardware_gpio::GpioStrictMock picoGpioMock_;
const uint8_t testedCorrectGpioNumber_;
};
GpioSettingsControllerShould::GpioSettingsControllerShould()
: picoGpioMock_()
, testedCorrectGpioNumber_(22u)
{
}
IGpioSettingsControllerPtr GpioSettingsControllerShould::createSut()
{
return GpioSettingsController::create();
}
void GpioSettingsControllerShould::expectAllGpiosFunctionSetToSioInputOnCreation(
const std::source_location& location)
{
std::vector<core::TGpioNumber> allPicoGpioNumbers;
for (auto gpioNumber = 0u; gpioNumber <= 22u; ++gpioNumber)
{
allPicoGpioNumbers.push_back(gpioNumber);
}
for (auto gpioNumber = 25u; gpioNumber <= 28u; ++gpioNumber)
{
allPicoGpioNumbers.push_back(gpioNumber);
}
for (const auto gpioNumber : allPicoGpioNumbers)
{
EXPECT_CALL(picoGpioMock_, gpio_set_function(gpioNumber, GPIO_FUNC_SIO))
.Times(1u);
EXPECT_CALL(picoGpioMock_, gpio_set_dir(gpioNumber, false))
.Times(1u);
}
}
TEST_F(GpioSettingsControllerShould, setAllGpiosToSioAndInput)
{
expectAllGpiosFunctionSetToSioInputOnCreation();
auto sut = createSut();
}
TEST_F(GpioSettingsControllerShould, returnNulloptForGetGpioDirectionAndInvalidGpioNumber)
{
expectAllGpiosFunctionSetToSioInputOnCreation();
auto sut = createSut();
const auto invalidGpioNumbers = generateInvalidGpioNumbers();
for (const auto invalidGpioNumber : invalidGpioNumbers)
{
EXPECT_EQ(sut->getGpioDirection(invalidGpioNumber), std::nullopt)
<< std::endl << testutil::source_location::toString();
}
}
TEST_F(GpioSettingsControllerShould, returnNulloptForGetGpioDirectionAndNotSioGpioFunction)
{
expectAllGpiosFunctionSetToSioInputOnCreation();
auto sut = createSut();
const auto gpioFunctions = generateAllGpioFunctionsExcept(definitions::EGpioFunction::SIO);
for (const auto& gpioFunction : gpioFunctions)
{
EXPECT_CALL(picoGpioMock_, gpio_get_function(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(gpioFunction.second));
EXPECT_EQ(sut->getGpioDirection(testedCorrectGpioNumber_), std::nullopt)
<< std::endl << testutil::source_location::toString();
}
}
TEST_F(GpioSettingsControllerShould, returnCorrectGpioDirectionForSioGpioFunction)
{
expectAllGpiosFunctionSetToSioInputOnCreation();
auto sut = createSut();
{
EXPECT_CALL(picoGpioMock_, gpio_get_function(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_FUNC_SIO));
EXPECT_CALL(picoGpioMock_, gpio_get_dir(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_IN));
const auto returnedGpioDirection = sut->getGpioDirection(testedCorrectGpioNumber_);
ASSERT_NE(returnedGpioDirection, std::nullopt)
<< std::endl << testutil::source_location::toString();
EXPECT_EQ(returnedGpioDirection.value(), definitions::EGpioDirection::Input)
<< std::endl << testutil::source_location::toString();
}
{
EXPECT_CALL(picoGpioMock_, gpio_get_function(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_FUNC_SIO));
EXPECT_CALL(picoGpioMock_, gpio_get_dir(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_OUT));
const auto returnedGpioDirection = sut->getGpioDirection(testedCorrectGpioNumber_);
ASSERT_NE(returnedGpioDirection, std::nullopt)
<< std::endl << testutil::source_location::toString();
EXPECT_EQ(returnedGpioDirection.value(), definitions::EGpioDirection::Output)
<< std::endl << testutil::source_location::toString();
}
}
TEST_F(GpioSettingsControllerShould, returnInvalidArgumentForSetGpioDirectionAndInvalidGpioNumber)
{
expectAllGpiosFunctionSetToSioInputOnCreation();
auto sut = createSut();
const auto invalidGpioNumbers = generateInvalidGpioNumbers();
for (const auto invalidGpioNumber : invalidGpioNumbers)
{
EXPECT_EQ(sut->setGpioDirection(invalidGpioNumber, definitions::EGpioDirection::Output),
core::definitions::EOperationResult::InvalidArgument)
<< std::endl << testutil::source_location::toString();
}
}
TEST_F(GpioSettingsControllerShould, returnNotPossibleForSetGpioDirectionAndNotSioGpioFunction)
{
expectAllGpiosFunctionSetToSioInputOnCreation();
auto sut = createSut();
const auto gpioFunctions = generateAllGpioFunctionsExcept(definitions::EGpioFunction::SIO);
for (const auto& gpioFunction : gpioFunctions)
{
EXPECT_CALL(picoGpioMock_, gpio_get_function(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(gpioFunction.second));
EXPECT_EQ(sut->setGpioDirection(testedCorrectGpioNumber_, definitions::EGpioDirection::Output),
core::definitions::EOperationResult::NotPossible)
<< std::endl << testutil::source_location::toString();
}
}
TEST_F(GpioSettingsControllerShould, returnSuccessOnSetGpioDirectionForSioGpioFunction)
{
expectAllGpiosFunctionSetToSioInputOnCreation();
auto sut = createSut();
{
EXPECT_CALL(picoGpioMock_, gpio_get_function(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_FUNC_SIO));
EXPECT_CALL(picoGpioMock_, gpio_set_dir(testedCorrectGpioNumber_, GPIO_IN))
.Times(1u);
EXPECT_EQ(sut->setGpioDirection(testedCorrectGpioNumber_, definitions::EGpioDirection::Input),
core::definitions::EOperationResult::Success)
<< std::endl << testutil::source_location::toString();
}
{
EXPECT_CALL(picoGpioMock_, gpio_get_function(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_FUNC_SIO));
EXPECT_CALL(picoGpioMock_, gpio_set_dir(testedCorrectGpioNumber_, GPIO_OUT))
.Times(1u);
EXPECT_CALL(picoGpioMock_, gpio_put(testedCorrectGpioNumber_, false))
.Times(1u);
EXPECT_CALL(picoGpioMock_, gpio_set_drive_strength(testedCorrectGpioNumber_, GPIO_DRIVE_STRENGTH_2MA))
.Times(1u);
EXPECT_CALL(picoGpioMock_, gpio_set_slew_rate(testedCorrectGpioNumber_, GPIO_SLEW_RATE_FAST))
.Times(1u);
EXPECT_EQ(sut->setGpioDirection(testedCorrectGpioNumber_, definitions::EGpioDirection::Output),
core::definitions::EOperationResult::Success)
<< std::endl << testutil::source_location::toString();
}
}
TEST_F(GpioSettingsControllerShould, returnNulloptForGetGpioDriveStrengthAndInvalidGpioNumber)
{
expectAllGpiosFunctionSetToSioInputOnCreation();
auto sut = createSut();
const auto invalidGpioNumbers = generateInvalidGpioNumbers();
for (const auto invalidGpioNumber : invalidGpioNumbers)
{
EXPECT_EQ(sut->getGpioDriveStrength(invalidGpioNumber), std::nullopt)
<< std::endl << testutil::source_location::toString();
}
}
TEST_F(GpioSettingsControllerShould, returnNulloptForGetGpioDriveStrengthAndNotSioGpioFunction)
{
expectAllGpiosFunctionSetToSioInputOnCreation();
auto sut = createSut();
const auto gpioFunctions = generateAllGpioFunctionsExcept(definitions::EGpioFunction::SIO);
for (const auto& gpioFunction : gpioFunctions)
{
EXPECT_CALL(picoGpioMock_, gpio_get_function(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(gpioFunction.second));
EXPECT_EQ(sut->getGpioDriveStrength(testedCorrectGpioNumber_), std::nullopt)
<< std::endl << testutil::source_location::toString();
}
}
TEST_F(GpioSettingsControllerShould, returnNulloptForGetGpioDriveStrengthAndInputSioGpioFunction)
{
expectAllGpiosFunctionSetToSioInputOnCreation();
auto sut = createSut();
EXPECT_CALL(picoGpioMock_, gpio_get_function(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_FUNC_SIO));
EXPECT_CALL(picoGpioMock_, gpio_get_dir(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_IN));
EXPECT_EQ(sut->getGpioDriveStrength(testedCorrectGpioNumber_), std::nullopt)
<< std::endl << testutil::source_location::toString();
}
TEST_F(GpioSettingsControllerShould, returnCorrectGpioDriveStrengthForOutputSioGpioFunction)
{
expectAllGpiosFunctionSetToSioInputOnCreation();
auto sut = createSut();
{
EXPECT_CALL(picoGpioMock_, gpio_get_function(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_FUNC_SIO));
EXPECT_CALL(picoGpioMock_, gpio_get_dir(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_OUT));
EXPECT_CALL(picoGpioMock_, gpio_get_drive_strength(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_DRIVE_STRENGTH_2MA));
const auto optionalReturnedValue = sut->getGpioDriveStrength(testedCorrectGpioNumber_);
ASSERT_NE(optionalReturnedValue, std::nullopt)
<< std::endl << testutil::source_location::toString();
EXPECT_EQ(optionalReturnedValue.value(), definitions::EGpioDriveStrength::_2mA)
<< std::endl << testutil::source_location::toString();
}
{
EXPECT_CALL(picoGpioMock_, gpio_get_function(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_FUNC_SIO));
EXPECT_CALL(picoGpioMock_, gpio_get_dir(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_OUT));
EXPECT_CALL(picoGpioMock_, gpio_get_drive_strength(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_DRIVE_STRENGTH_4MA));
const auto optionalReturnedValue = sut->getGpioDriveStrength(testedCorrectGpioNumber_);
ASSERT_NE(optionalReturnedValue, std::nullopt)
<< std::endl << testutil::source_location::toString();
EXPECT_EQ(optionalReturnedValue.value(), definitions::EGpioDriveStrength::_4mA)
<< std::endl << testutil::source_location::toString();
}
{
EXPECT_CALL(picoGpioMock_, gpio_get_function(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_FUNC_SIO));
EXPECT_CALL(picoGpioMock_, gpio_get_dir(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_OUT));
EXPECT_CALL(picoGpioMock_, gpio_get_drive_strength(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_DRIVE_STRENGTH_8MA));
const auto optionalReturnedValue = sut->getGpioDriveStrength(testedCorrectGpioNumber_);
ASSERT_NE(optionalReturnedValue, std::nullopt)
<< std::endl << testutil::source_location::toString();
EXPECT_EQ(optionalReturnedValue.value(), definitions::EGpioDriveStrength::_8mA)
<< std::endl << testutil::source_location::toString();
}
{
EXPECT_CALL(picoGpioMock_, gpio_get_function(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_FUNC_SIO));
EXPECT_CALL(picoGpioMock_, gpio_get_dir(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_OUT));
EXPECT_CALL(picoGpioMock_, gpio_get_drive_strength(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_DRIVE_STRENGTH_12MA));
const auto optionalReturnedValue = sut->getGpioDriveStrength(testedCorrectGpioNumber_);
ASSERT_NE(optionalReturnedValue, std::nullopt)
<< std::endl << testutil::source_location::toString();
EXPECT_EQ(optionalReturnedValue.value(), definitions::EGpioDriveStrength::_12mA)
<< std::endl << testutil::source_location::toString();
}
}
TEST_F(GpioSettingsControllerShould, returnInvalidArgumentForSetGpioDriveStrengthAndInvalidGpioNumber)
{
expectAllGpiosFunctionSetToSioInputOnCreation();
auto sut = createSut();
const auto invalidGpioNumbers = generateInvalidGpioNumbers();
for (const auto invalidGpioNumber : invalidGpioNumbers)
{
EXPECT_EQ(sut->setGpioDriveStrength(invalidGpioNumber, definitions::EGpioDriveStrength::_2mA),
core::definitions::EOperationResult::InvalidArgument)
<< std::endl << testutil::source_location::toString();
}
}
TEST_F(GpioSettingsControllerShould, returnNotPossibleForSetGpioDriveStrengthAndNotSioGpioFunction)
{
expectAllGpiosFunctionSetToSioInputOnCreation();
auto sut = createSut();
const auto gpioFunctions = generateAllGpioFunctionsExcept(definitions::EGpioFunction::SIO);
for (const auto& gpioFunction : gpioFunctions)
{
EXPECT_CALL(picoGpioMock_, gpio_get_function(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(gpioFunction.second));
EXPECT_EQ(sut->setGpioDriveStrength(testedCorrectGpioNumber_, definitions::EGpioDriveStrength::_2mA),
core::definitions::EOperationResult::NotPossible)
<< std::endl << testutil::source_location::toString();
}
}
TEST_F(GpioSettingsControllerShould, returnNotPossibleForSetGpioDriveStrengthAndSioInputGpioFunction)
{
expectAllGpiosFunctionSetToSioInputOnCreation();
auto sut = createSut();
EXPECT_CALL(picoGpioMock_, gpio_get_function(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_FUNC_SIO));
EXPECT_CALL(picoGpioMock_, gpio_get_dir(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_IN));
EXPECT_EQ(sut->setGpioDriveStrength(testedCorrectGpioNumber_, definitions::EGpioDriveStrength::_2mA),
core::definitions::EOperationResult::NotPossible)
<< std::endl << testutil::source_location::toString();
}
TEST_F(GpioSettingsControllerShould, returnSuccessOnSetGpioDriveStrengthForSioGpioOutput)
{
expectAllGpiosFunctionSetToSioInputOnCreation();
auto sut = createSut();
{
EXPECT_CALL(picoGpioMock_, gpio_get_function(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_FUNC_SIO));
EXPECT_CALL(picoGpioMock_, gpio_get_dir(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_OUT));
EXPECT_CALL(picoGpioMock_, gpio_set_drive_strength(testedCorrectGpioNumber_, GPIO_DRIVE_STRENGTH_2MA))
.Times(1u);
EXPECT_EQ(sut->setGpioDriveStrength(testedCorrectGpioNumber_, definitions::EGpioDriveStrength::_2mA),
core::definitions::EOperationResult::Success)
<< std::endl << testutil::source_location::toString();
}
{
EXPECT_CALL(picoGpioMock_, gpio_get_function(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_FUNC_SIO));
EXPECT_CALL(picoGpioMock_, gpio_get_dir(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_OUT));
EXPECT_CALL(picoGpioMock_, gpio_set_drive_strength(testedCorrectGpioNumber_, GPIO_DRIVE_STRENGTH_4MA))
.Times(1u);
EXPECT_EQ(sut->setGpioDriveStrength(testedCorrectGpioNumber_, definitions::EGpioDriveStrength::_4mA),
core::definitions::EOperationResult::Success)
<< std::endl << testutil::source_location::toString();
}
{
EXPECT_CALL(picoGpioMock_, gpio_get_function(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_FUNC_SIO));
EXPECT_CALL(picoGpioMock_, gpio_get_dir(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_OUT));
EXPECT_CALL(picoGpioMock_, gpio_set_drive_strength(testedCorrectGpioNumber_, GPIO_DRIVE_STRENGTH_8MA))
.Times(1u);
EXPECT_EQ(sut->setGpioDriveStrength(testedCorrectGpioNumber_, definitions::EGpioDriveStrength::_8mA),
core::definitions::EOperationResult::Success)
<< std::endl << testutil::source_location::toString();
}
{
EXPECT_CALL(picoGpioMock_, gpio_get_function(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_FUNC_SIO));
EXPECT_CALL(picoGpioMock_, gpio_get_dir(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_OUT));
EXPECT_CALL(picoGpioMock_, gpio_set_drive_strength(testedCorrectGpioNumber_, GPIO_DRIVE_STRENGTH_12MA))
.Times(1u);
EXPECT_EQ(sut->setGpioDriveStrength(testedCorrectGpioNumber_, definitions::EGpioDriveStrength::_12mA),
core::definitions::EOperationResult::Success)
<< std::endl << testutil::source_location::toString();
}
}
TEST_F(GpioSettingsControllerShould, returnNulloptForGetGpioFunctionAndInvalidGpioNumber)
{
expectAllGpiosFunctionSetToSioInputOnCreation();
auto sut = createSut();
const auto invalidGpioNumbers = generateInvalidGpioNumbers();
for (const auto invalidGpioNumber : invalidGpioNumbers)
{
EXPECT_EQ(sut->getGpioFunction(invalidGpioNumber), std::nullopt)
<< std::endl << testutil::source_location::toString();
}
}
TEST_F(GpioSettingsControllerShould, returnCorrectGpioFunction)
{
expectAllGpiosFunctionSetToSioInputOnCreation();
auto sut = createSut();
const auto gpioFunctions = generateAllGpioFunctions();
for (const auto& gpioFunction : gpioFunctions)
{
EXPECT_CALL(picoGpioMock_, gpio_get_function(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(gpioFunction.second));
const auto optionalReturnedValue = sut->getGpioFunction(testedCorrectGpioNumber_);
ASSERT_NE(optionalReturnedValue, std::nullopt)
<< std::endl << testutil::source_location::toString();
EXPECT_EQ(optionalReturnedValue.value(), gpioFunction.first)
<< std::endl << testutil::source_location::toString();
}
}
TEST_F(GpioSettingsControllerShould, returnInvalidArgumentForSetGpioFunctionAndInvalidGpioNumber)
{
expectAllGpiosFunctionSetToSioInputOnCreation();
auto sut = createSut();
const auto invalidGpioNumbers = generateInvalidGpioNumbers();
for (const auto invalidGpioNumber : invalidGpioNumbers)
{
EXPECT_EQ(sut->setGpioFunction(invalidGpioNumber, definitions::EGpioFunction::SIO),
core::definitions::EOperationResult::InvalidArgument)
<< std::endl << testutil::source_location::toString();
}
}
TEST_F(GpioSettingsControllerShould, returnSuccessForSetGpioFunctionAndCorrectGpioNumber)
{
expectAllGpiosFunctionSetToSioInputOnCreation();
auto sut = createSut();
const auto gpioFunctions = generateAllGpioFunctions();
for (const auto& gpioFunction : gpioFunctions)
{
EXPECT_CALL(picoGpioMock_, gpio_set_function(testedCorrectGpioNumber_, gpioFunction.second))
.Times(1u);
EXPECT_EQ(sut->setGpioFunction(testedCorrectGpioNumber_, gpioFunction.first),
core::definitions::EOperationResult::Success)
<< std::endl << testutil::source_location::toString();
}
}
TEST_F(GpioSettingsControllerShould, returnNulloptForGetGpioPullUpAndInvalidGpioNumber)
{
expectAllGpiosFunctionSetToSioInputOnCreation();
auto sut = createSut();
const auto invalidGpioNumbers = generateInvalidGpioNumbers();
for (const auto invalidGpioNumber : invalidGpioNumbers)
{
EXPECT_EQ(sut->getGpioPullUp(invalidGpioNumber), std::nullopt)
<< std::endl << testutil::source_location::toString();
}
}
TEST_F(GpioSettingsControllerShould, returnCorrectGpioPullUpForValidGpioNumber)
{
expectAllGpiosFunctionSetToSioInputOnCreation();
auto sut = createSut();
{
EXPECT_CALL(picoGpioMock_, gpio_is_pulled_down(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(false));
EXPECT_CALL(picoGpioMock_, gpio_is_pulled_up(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(false));
const auto optionalReturnedValue = sut->getGpioPullUp(testedCorrectGpioNumber_);
ASSERT_NE(optionalReturnedValue, std::nullopt)
<< std::endl << testutil::source_location::toString();
EXPECT_EQ(optionalReturnedValue.value(), definitions::EGpioPullUp::NotPulled)
<< std::endl << testutil::source_location::toString();
}
{
EXPECT_CALL(picoGpioMock_, gpio_is_pulled_down(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(true));
EXPECT_CALL(picoGpioMock_, gpio_is_pulled_up(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(false));
const auto optionalReturnedValue = sut->getGpioPullUp(testedCorrectGpioNumber_);
ASSERT_NE(optionalReturnedValue, std::nullopt)
<< std::endl << testutil::source_location::toString();
EXPECT_EQ(optionalReturnedValue.value(), definitions::EGpioPullUp::Down)
<< std::endl << testutil::source_location::toString();
}
{
EXPECT_CALL(picoGpioMock_, gpio_is_pulled_down(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(false));
EXPECT_CALL(picoGpioMock_, gpio_is_pulled_up(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(true));
const auto optionalReturnedValue = sut->getGpioPullUp(testedCorrectGpioNumber_);
ASSERT_NE(optionalReturnedValue, std::nullopt)
<< std::endl << testutil::source_location::toString();
EXPECT_EQ(optionalReturnedValue.value(), definitions::EGpioPullUp::Up)
<< std::endl << testutil::source_location::toString();
}
{
EXPECT_CALL(picoGpioMock_, gpio_is_pulled_down(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(true));
EXPECT_CALL(picoGpioMock_, gpio_is_pulled_up(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(true));
const auto optionalReturnedValue = sut->getGpioPullUp(testedCorrectGpioNumber_);
ASSERT_NE(optionalReturnedValue, std::nullopt)
<< std::endl << testutil::source_location::toString();
EXPECT_EQ(optionalReturnedValue.value(), definitions::EGpioPullUp::BusKeep)
<< std::endl << testutil::source_location::toString();
}
}
TEST_F(GpioSettingsControllerShould, returnInvalidArgumentForSetGpioPullUpAndInvalidGpioNumber)
{
expectAllGpiosFunctionSetToSioInputOnCreation();
auto sut = createSut();
const auto invalidGpioNumbers = generateInvalidGpioNumbers();
for (const auto invalidGpioNumber : invalidGpioNumbers)
{
EXPECT_EQ(sut->setGpioPullUp(invalidGpioNumber, definitions::EGpioPullUp::Up),
core::definitions::EOperationResult::InvalidArgument)
<< std::endl << testutil::source_location::toString();
}
}
TEST_F(GpioSettingsControllerShould, returnSuccessForSetGpioPullUpAndValidGpioNumber)
{
expectAllGpiosFunctionSetToSioInputOnCreation();
auto sut = createSut();
{
EXPECT_CALL(picoGpioMock_, gpio_set_pulls(testedCorrectGpioNumber_, false, false));
EXPECT_EQ(sut->setGpioPullUp(testedCorrectGpioNumber_, definitions::EGpioPullUp::NotPulled),
core::definitions::EOperationResult::Success)
<< std::endl << testutil::source_location::toString();
}
{
EXPECT_CALL(picoGpioMock_, gpio_set_pulls(testedCorrectGpioNumber_, false, true));
EXPECT_EQ(sut->setGpioPullUp(testedCorrectGpioNumber_, definitions::EGpioPullUp::Down),
core::definitions::EOperationResult::Success)
<< std::endl << testutil::source_location::toString();
}
{
EXPECT_CALL(picoGpioMock_, gpio_set_pulls(testedCorrectGpioNumber_, true, false));
EXPECT_EQ(sut->setGpioPullUp(testedCorrectGpioNumber_, definitions::EGpioPullUp::Up),
core::definitions::EOperationResult::Success)
<< std::endl << testutil::source_location::toString();
}
{
EXPECT_CALL(picoGpioMock_, gpio_set_pulls(testedCorrectGpioNumber_, true, true));
EXPECT_EQ(sut->setGpioPullUp(testedCorrectGpioNumber_, definitions::EGpioPullUp::BusKeep),
core::definitions::EOperationResult::Success)
<< std::endl << testutil::source_location::toString();
}
}
TEST_F(GpioSettingsControllerShould, returnNulloptForGetGpioSlewRateLimitingAndInvalidGpioNumber)
{
expectAllGpiosFunctionSetToSioInputOnCreation();
auto sut = createSut();
const auto invalidGpioNumbers = generateInvalidGpioNumbers();
for (const auto invalidGpioNumber : invalidGpioNumbers)
{
EXPECT_EQ(sut->getGpioSlewRateLimiting(invalidGpioNumber), std::nullopt)
<< std::endl << testutil::source_location::toString();
}
}
TEST_F(GpioSettingsControllerShould, returnNulloptForGetGpioSlewRateLimitingAndNotSioGpioFunction)
{
expectAllGpiosFunctionSetToSioInputOnCreation();
auto sut = createSut();
const auto gpioFunctions = generateAllGpioFunctionsExcept(definitions::EGpioFunction::SIO);
for (const auto& gpioFunction : gpioFunctions)
{
EXPECT_CALL(picoGpioMock_, gpio_get_function(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(gpioFunction.second));
EXPECT_EQ(sut->getGpioSlewRateLimiting(testedCorrectGpioNumber_), std::nullopt)
<< std::endl << testutil::source_location::toString();
}
}
TEST_F(GpioSettingsControllerShould, returnNulloptForGetGpioSlewRateLimitingAndInputSioGpioFunction)
{
expectAllGpiosFunctionSetToSioInputOnCreation();
auto sut = createSut();
EXPECT_CALL(picoGpioMock_, gpio_get_function(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_FUNC_SIO));
EXPECT_CALL(picoGpioMock_, gpio_get_dir(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_IN));
EXPECT_EQ(sut->getGpioSlewRateLimiting(testedCorrectGpioNumber_), std::nullopt)
<< std::endl << testutil::source_location::toString();
}
TEST_F(GpioSettingsControllerShould, returnCorrectGpioSlewRateLimitingForOutputSioGpioFunction)
{
expectAllGpiosFunctionSetToSioInputOnCreation();
auto sut = createSut();
{
EXPECT_CALL(picoGpioMock_, gpio_get_function(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_FUNC_SIO));
EXPECT_CALL(picoGpioMock_, gpio_get_dir(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_OUT));
EXPECT_CALL(picoGpioMock_, gpio_get_slew_rate(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_SLEW_RATE_SLOW));
const auto optionalReturnedValue = sut->getGpioSlewRateLimiting(testedCorrectGpioNumber_);
ASSERT_NE(optionalReturnedValue, std::nullopt)
<< std::endl << testutil::source_location::toString();
EXPECT_EQ(optionalReturnedValue.value(), definitions::EGpioSlewRateLimiting::Enabled)
<< std::endl << testutil::source_location::toString();
}
{
EXPECT_CALL(picoGpioMock_, gpio_get_function(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_FUNC_SIO));
EXPECT_CALL(picoGpioMock_, gpio_get_dir(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_OUT));
EXPECT_CALL(picoGpioMock_, gpio_get_slew_rate(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_SLEW_RATE_FAST));
const auto optionalReturnedValue = sut->getGpioSlewRateLimiting(testedCorrectGpioNumber_);
ASSERT_NE(optionalReturnedValue, std::nullopt)
<< std::endl << testutil::source_location::toString();
EXPECT_EQ(optionalReturnedValue.value(), definitions::EGpioSlewRateLimiting::Disabled)
<< std::endl << testutil::source_location::toString();
}
}
TEST_F(GpioSettingsControllerShould, returnInvalidArgumentForSetGpioSlewRateLimitingAndInvalidGpioNumber)
{
expectAllGpiosFunctionSetToSioInputOnCreation();
auto sut = createSut();
const auto invalidGpioNumbers = generateInvalidGpioNumbers();
for (const auto invalidGpioNumber : invalidGpioNumbers)
{
EXPECT_EQ(sut->setGpioSlewRateLimiting(invalidGpioNumber, definitions::EGpioSlewRateLimiting::Enabled),
core::definitions::EOperationResult::InvalidArgument)
<< std::endl << testutil::source_location::toString();
}
}
TEST_F(GpioSettingsControllerShould, returnNotPossibleForSetGpioSlewRateLimitingAndNotSioGpioFunction)
{
expectAllGpiosFunctionSetToSioInputOnCreation();
auto sut = createSut();
const auto gpioFunctions = generateAllGpioFunctionsExcept(definitions::EGpioFunction::SIO);
for (const auto& gpioFunction : gpioFunctions)
{
EXPECT_CALL(picoGpioMock_, gpio_get_function(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(gpioFunction.second));
EXPECT_EQ(sut->setGpioSlewRateLimiting(testedCorrectGpioNumber_, definitions::EGpioSlewRateLimiting::Enabled),
core::definitions::EOperationResult::NotPossible)
<< std::endl << testutil::source_location::toString();
}
}
TEST_F(GpioSettingsControllerShould, returnNotPossibleForSetGpioSlewRateLimitingAndSioInputGpioFunction)
{
expectAllGpiosFunctionSetToSioInputOnCreation();
auto sut = createSut();
EXPECT_CALL(picoGpioMock_, gpio_get_function(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_FUNC_SIO));
EXPECT_CALL(picoGpioMock_, gpio_get_dir(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_IN));
EXPECT_EQ(sut->setGpioSlewRateLimiting(testedCorrectGpioNumber_, definitions::EGpioSlewRateLimiting::Enabled),
core::definitions::EOperationResult::NotPossible)
<< std::endl << testutil::source_location::toString();
}
TEST_F(GpioSettingsControllerShould, returnSuccessOnSetGpioSlewRateLimitingForSioGpioOutput)
{
expectAllGpiosFunctionSetToSioInputOnCreation();
auto sut = createSut();
{
EXPECT_CALL(picoGpioMock_, gpio_get_function(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_FUNC_SIO));
EXPECT_CALL(picoGpioMock_, gpio_get_dir(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_OUT));
EXPECT_CALL(picoGpioMock_, gpio_set_slew_rate(testedCorrectGpioNumber_, GPIO_SLEW_RATE_SLOW))
.Times(1u);
EXPECT_EQ(sut->setGpioSlewRateLimiting(testedCorrectGpioNumber_, definitions::EGpioSlewRateLimiting::Enabled),
core::definitions::EOperationResult::Success)
<< std::endl << testutil::source_location::toString();
}
{
EXPECT_CALL(picoGpioMock_, gpio_get_function(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_FUNC_SIO));
EXPECT_CALL(picoGpioMock_, gpio_get_dir(testedCorrectGpioNumber_))
.WillOnce(::testing::Return(GPIO_OUT));
EXPECT_CALL(picoGpioMock_, gpio_set_slew_rate(testedCorrectGpioNumber_, GPIO_SLEW_RATE_FAST))
.Times(1u);
EXPECT_EQ(sut->setGpioSlewRateLimiting(testedCorrectGpioNumber_, definitions::EGpioSlewRateLimiting::Disabled),
core::definitions::EOperationResult::Success)
<< std::endl << testutil::source_location::toString();
}
}
} // namespace gpio
} // namespace rpipicosdkal
| 44.895213 | 119 | 0.718419 | bkozdras |
739a9cf262fb05a2623562bb4680153985333bcd | 23,720 | cpp | C++ | test/test_block_literal.cpp | fargies/rapidyaml | 6fd373c860b1eef3b190a521acabebc2fd2dcb04 | [
"MIT"
] | null | null | null | test/test_block_literal.cpp | fargies/rapidyaml | 6fd373c860b1eef3b190a521acabebc2fd2dcb04 | [
"MIT"
] | null | null | null | test/test_block_literal.cpp | fargies/rapidyaml | 6fd373c860b1eef3b190a521acabebc2fd2dcb04 | [
"MIT"
] | null | null | null | #include "./test_group.hpp"
namespace c4 {
namespace yml {
TEST(block_literal, empty_block)
{
{
Tree t = parse_in_arena(R"(- |
)");
EXPECT_EQ(t[0].val(), csubstr(""));
}
{
Tree t = parse_in_arena(R"(- |-
)");
EXPECT_EQ(t[0].val(), csubstr(""));
}
{
Tree t = parse_in_arena(R"(- |+
)");
EXPECT_EQ(t[0].val(), csubstr(""));
}
{
Tree t = parse_in_arena(R"(# no indentation: fails!
- |
- |-
- |+
)");
EXPECT_FALSE(t.empty());
EXPECT_EQ(t[0].val(), csubstr(""));
EXPECT_EQ(t[1].val(), csubstr(""));
EXPECT_EQ(t[2].val(), csubstr("\n"));
}
{
Tree t = parse_in_arena(R"(
- |
- |-
- |+
)");
EXPECT_FALSE(t.empty());
EXPECT_EQ(t[0].val(), csubstr(""));
EXPECT_EQ(t[1].val(), csubstr(""));
EXPECT_EQ(t[2].val(), csubstr("\n"));
}
{
Tree t = parse_in_arena(R"(
- |
- |-
- |+
)");
EXPECT_FALSE(t.empty());
EXPECT_EQ(t[0].val(), csubstr(""));
EXPECT_EQ(t[1].val(), csubstr(""));
EXPECT_EQ(t[2].val(), csubstr(""));
}
}
TEST(block_literal, emit_does_not_add_lines_to_multi_at_end_1)
{
Tree t = parse_in_arena("[]");
NodeRef r = t.rootref();
r.append_child() = "\n\n";
r.append_child() = "\n\n";
r.append_child() = "last";
std::string out = emitrs<std::string>(t);
t.clear();
t = parse_in_arena(to_csubstr(out));
EXPECT_EQ(t[0].val(), csubstr("\n\n"));
EXPECT_EQ(t[1].val(), csubstr("\n\n"));
EXPECT_EQ(t[2].val(), csubstr("last"));
out = emitrs<std::string>(t);
t.clear();
t = parse_in_arena(to_csubstr(out));
EXPECT_EQ(t[0].val(), csubstr("\n\n"));
EXPECT_EQ(t[1].val(), csubstr("\n\n"));
EXPECT_EQ(t[2].val(), csubstr("last"));
out = emitrs<std::string>(t);
t.clear();
t = parse_in_arena(to_csubstr(out));
EXPECT_EQ(t[0].val(), csubstr("\n\n"));
EXPECT_EQ(t[1].val(), csubstr("\n\n"));
EXPECT_EQ(t[2].val(), csubstr("last"));
EXPECT_EQ(csubstr("ab\n\n \n").trimr(" \t\n"), csubstr("ab"));
}
TEST(block_literal, emit_does_not_add_lines_to_multi_at_end_2)
{
Tree t = parse_in_arena(R"(--- |+
ab
)");
EXPECT_EQ(t.docref(0).val(), csubstr("ab\n\n \n"));
std::string expected = R"(--- |
ab
)";
std::string out = emitrs<std::string>(t);
EXPECT_EQ(out, expected);
t = parse_in_arena(to_csubstr(out));
EXPECT_EQ(t.docref(0).val(), csubstr("ab\n\n \n"));
out = emitrs<std::string>(t);
EXPECT_EQ(out, expected);
t = parse_in_arena(to_csubstr(out));
EXPECT_EQ(t.docref(0).val(), csubstr("ab\n\n \n"));
out = emitrs<std::string>(t);
EXPECT_EQ(out, expected);
t = parse_in_arena(to_csubstr(out));
EXPECT_EQ(t.docref(0).val(), csubstr("ab\n\n \n"));
}
TEST(block_literal, emit_does_not_add_lines_to_multi_at_end_3)
{
std::string yaml = R"(
- |
Several lines of text,
with some "quotes" of various 'types',
and also a blank line:
plus another line at the end.
- |+
Several lines of text,
with some "quotes" of various 'types',
and also a blank line:
plus another line at the end.
- last
)";
std::string expected = R"(- |
Several lines of text,
with some "quotes" of various 'types',
and also a blank line:
plus another line at the end.
- |+
Several lines of text,
with some "quotes" of various 'types',
and also a blank line:
plus another line at the end.
- last
)";
Tree t = parse_in_arena(to_csubstr(yaml));
EXPECT_EQ(t[0].val(), "Several lines of text,\nwith some \"quotes\" of various 'types',\nand also a blank line:\n\nplus another line at the end.\n");
EXPECT_EQ(t[1].val(), "Several lines of text,\nwith some \"quotes\" of various 'types',\nand also a blank line:\n\nplus another line at the end.\n\n");
std::string out = emitrs<std::string>(t);
EXPECT_EQ(out, expected);
t = parse_in_arena(to_csubstr(out));
EXPECT_EQ(t[0].val(), "Several lines of text,\nwith some \"quotes\" of various 'types',\nand also a blank line:\n\nplus another line at the end.\n");
EXPECT_EQ(t[1].val(), "Several lines of text,\nwith some \"quotes\" of various 'types',\nand also a blank line:\n\nplus another line at the end.\n\n");
out = emitrs<std::string>(t);
EXPECT_EQ(out, expected);
}
TEST(block_literal, carriage_return)
{
std::string yaml = "with: |\r\n"
" text\r\n"
" lines\r\n"
"without: |\n"
" text\n"
" lines\n";
Tree t = parse_in_arena(to_csubstr(yaml));
EXPECT_EQ(t["with"].val(), "text\n \tlines\n");
EXPECT_EQ(t["without"].val(), "text\n \tlines\n");
auto emitted = emitrs<std::string>(t);
#ifdef RYML_DBG
__c4presc(emitted.data(), emitted.size());
#endif
Tree r = parse_in_arena(to_csubstr(emitted));
EXPECT_EQ(t["with"].val(), "text\n \tlines\n");
EXPECT_EQ(t["without"].val(), "text\n \tlines\n");
}
#ifdef JAVAI
TEST(block_literal, errors_on_tab_indents)
{
Tree tree;
ExpectError::do_check(&tree, [&]{
parse_in_arena("foo: |4\n this is foo\n now with tab-\n \t \tmust not work\n", &tree);
});
}
#endif
TEST(block_literal, test_suite_L24T_00)
{
// this is double quoted, but will be emitted as a block literal
csubstr yaml = R"(foo: "x\n \n"
)";
test_check_emit_check(yaml, [](Tree const &t){
EXPECT_EQ(t["foo"].val(), csubstr("x\n \n"));
});
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
CASE_GROUP(BLOCK_LITERAL)
{
//
ADD_CASE_TO_GROUP("indentation requirements",
R"(---
|
hello
there
---
|
hello
there
---
|
hello
there
---
|
ciao
qua
---
|
ciao
qua
---
|
ciao
qua
---
- |
hello
there
- |
ciao
qua
---
foo: |
hello
there
bar: |
ciao
qua
)",
N(STREAM, L{
N(DOCVAL|QV, "hello\nthere\n"),
N(DOCVAL|QV, "hello\nthere\n"),
N(DOCVAL|QV, "hello\nthere\n"),
N(DOCVAL|QV, "ciao\nqua\n"),
N(DOCVAL|QV, "ciao\nqua\n"),
N(DOCVAL|QV, "ciao\nqua\n"),
N(SEQ|DOC, L{N(QV, "hello\nthere\n"), N(QV, "ciao\nqua\n")}),
N(MAP|DOC, L{N(QV, "foo", "hello\nthere\n"), N(QV, "bar", "ciao\nqua\n")}),
}));
ADD_CASE_TO_GROUP("indentation requirements err seq", EXPECT_PARSE_ERROR,
R"(- |
hello
there
- |
ciao
qua
)",
N(L{N(QV, "hello\nthere\n"), N(QV, "ciao\nqua\n")}));
ADD_CASE_TO_GROUP("indentation requirements err map", EXPECT_PARSE_ERROR,
R"(foo: |
hello
there
bar: |
ciao
qua
)",
N(L{N(QV, "foo", "hello\nthere\n"), N(QV, "bar" "ciao\nqua\n")}));
ADD_CASE_TO_GROUP("indentation requirements err level", EXPECT_PARSE_ERROR,
R"(--- |2
hello
there
)",
N(NOTYPE));
ADD_CASE_TO_GROUP("empty, specs only 2G84_02",
"--- |1-",
N(STREAM, L{N(DOCVAL|VALQUO, {})}));
ADD_CASE_TO_GROUP("empty, specs only 2G84_03",
"--- |1+",
N(STREAM, L{N(DOCVAL|VALQUO, {})}));
ADD_CASE_TO_GROUP("empty, specs only 2G84_xx",
"--- |+",
N(STREAM, L{N(DOCVAL|VALQUO, {})}));
ADD_CASE_TO_GROUP("empty, specs only 2G84_02_1",
"|1-",
N(DOCVAL|VALQUO, {}));
ADD_CASE_TO_GROUP("empty, specs only 2G84_03_1",
"|1+",
N(DOCVAL|VALQUO, {}));
ADD_CASE_TO_GROUP("empty, specs only 2G84_xx_1",
"|+",
N(DOCVAL|VALQUO, {}));
ADD_CASE_TO_GROUP("block literal as map entry",
R"(
data: |
There once was a short man from Ealing
Who got on a bus to Darjeeling
It said on the door
"Please don't spit on the floor"
So he carefully spat on the ceiling
)",
N(MAP, {
N(KEYVAL|VALQUO, "data", "There once was a short man from Ealing\nWho got on a bus to Darjeeling\n It said on the door\n \"Please don't spit on the floor\"\nSo he carefully spat on the ceiling\n")
})
);
ADD_CASE_TO_GROUP("block literal and two scalars",
R"(
example: >
HTML goes into YAML without modification
message: |
<blockquote style="font: italic 12pt Times">
<p>"Three is always greater than two,
even for large values of two"</p>
<p>--Author Unknown</p>
</blockquote>
date: 2007-06-01
)",
N(MAP, L{
N(KEYVAL|VALQUO, "example", "HTML goes into YAML without modification\n"),
N(KEYVAL|VALQUO, "message", R"(<blockquote style="font: italic 12pt Times">
<p>"Three is always greater than two,
even for large values of two"</p>
<p>--Author Unknown</p>
</blockquote>
)"),
N("date", "2007-06-01"),
})
);
ADD_CASE_TO_GROUP("block literal no chomp, no indentation",
R"(example: |
Several lines of text,
with some "quotes" of various 'types',
and also a blank line:
plus another line at the end.
another: text
)",
N(MAP, L{
N(KEYVAL|VALQUO, "example", "Several lines of text,\nwith some \"quotes\" of various 'types',\nand also a blank line:\n\nplus another line at the end.\n"),
N("another", "text"),
})
);
ADD_CASE_TO_GROUP("block literal as seq val, implicit indentation 2",
R"(
- |
Several lines of text,
with some "quotes" of various 'types',
and also a blank line:
plus another line at the end.
- another val
)",
L{
N(QV, "Several lines of text,\nwith some \"quotes\" of various 'types',\nand also a blank line:\n\nplus another line at the end.\n"),
N("another val")
}
);
ADD_CASE_TO_GROUP("block literal as seq val, implicit indentation 2, chomp=keep",
R"(
- |+
Several lines of text,
with some "quotes" of various 'types',
and also a blank line:
plus another line at the end.
- another val
)",
L{
N(QV, "Several lines of text,\nwith some \"quotes\" of various 'types',\nand also a blank line:\n\nplus another line at the end.\n\n\n"),
N("another val")
}
);
ADD_CASE_TO_GROUP("block literal as seq val, implicit indentation 2, chomp=strip",
R"(
- |-
Several lines of text,
with some "quotes" of various 'types',
and also a blank line:
plus another line at the end.
- another val
)",
L{
N(QV, "Several lines of text,\nwith some \"quotes\" of various 'types',\nand also a blank line:\n\nplus another line at the end."),
N("another val")
}
);
ADD_CASE_TO_GROUP("block literal as seq val at eof, implicit indentation 2",
R"(
- |
Several lines of text,
with some "quotes" of various 'types',
and also a blank line:
plus another line at the end.
)",
L{
N(QV, "Several lines of text,\nwith some \"quotes\" of various 'types',\nand also a blank line:\n\nplus another line at the end.\n"),
}
);
ADD_CASE_TO_GROUP("block literal as seq val at eof, implicit indentation 4",
R"(
- |
Several lines of text,
with some "quotes" of various 'types',
and also a blank line:
plus another line at the end.
)",
L{
N(QV, "Several lines of text,\nwith some \"quotes\" of various 'types',\nand also a blank line:\n\nplus another line at the end.\n"),
}
);
ADD_CASE_TO_GROUP("block literal as map val, implicit indentation 2",
R"(
example: |
Several lines of text,
with some "quotes" of various 'types',
and also a blank line:
plus another line at the end.
another: val
)",
L{
N(QV, "example", "Several lines of text,\nwith some \"quotes\" of various 'types',\nand also a blank line:\n\nplus another line at the end.\n"),
N("another", "val")
}
);
ADD_CASE_TO_GROUP("block literal as map val, explicit indentation 2",
R"(
example: |2
Several lines of text,
with some "quotes" of various 'types',
and also a blank line:
plus another line at the end.
another: val
)",
L{
N(QV, "example", "Several lines of text,\nwith some \"quotes\" of various 'types',\nand also a blank line:\n\nplus another line at the end.\n"),
N("another", "val")
}
);
ADD_CASE_TO_GROUP("block literal as map val, explicit indentation 2, chomp=keep",
R"(
example: |+2
Several lines of text,
with some "quotes" of various 'types',
and also a blank line:
plus another line at the end.
another: val
)",
L{
N(QV, "example", "Several lines of text,\nwith some \"quotes\" of various 'types',\nand also a blank line:\n\nplus another line at the end.\n\n\n"),
N("another", "val")
}
);
ADD_CASE_TO_GROUP("block literal as map val, explicit indentation 2, chomp=strip",
R"(
example: |-2
Several lines of text,
with some "quotes" of various 'types',
and also a blank line:
plus another line at the end.
another: val
)",
L{
N(QV, "example", "Several lines of text,\nwith some \"quotes\" of various 'types',\nand also a blank line:\n\nplus another line at the end."),
N("another", "val")
}
);
ADD_CASE_TO_GROUP("block literal as map val, implicit indentation 3",
R"(
example: |
Several lines of text,
with some "quotes" of various 'types',
and also a blank line:
plus another line at the end.
another: val
)",
L{
N(QV, "example", "Several lines of text,\nwith some \"quotes\" of various 'types',\nand also a blank line:\n\nplus another line at the end.\n"),
N("another", "val")
}
);
ADD_CASE_TO_GROUP("block literal as map val, explicit indentation 3",
R"(
example: |3
Several lines of text,
with some "quotes" of various 'types',
and also a blank line:
plus another line at the end.
another: val
)",
L{
N(QV, "example", "Several lines of text,\nwith some \"quotes\" of various 'types',\nand also a blank line:\n\nplus another line at the end.\n"),
N("another", "val")
}
);
ADD_CASE_TO_GROUP("block literal as map val, implicit indentation 4",
R"(
example: |
Several lines of text,
with some "quotes" of various 'types',
and also a blank line:
plus another line at the end.
another: val
)",
L{
N(QV, "example", "Several lines of text,\nwith some \"quotes\" of various 'types',\nand also a blank line:\n\nplus another line at the end.\n"),
N("another", "val")
}
);
ADD_CASE_TO_GROUP("block literal as map val, explicit indentation 4",
R"(
example: |4
Several lines of text,
with some "quotes" of various 'types',
and also a blank line:
plus another line at the end.
another: val
)",
L{
N(QV, "example", "Several lines of text,\nwith some \"quotes\" of various 'types',\nand also a blank line:\n\nplus another line at the end.\n"),
N("another", "val")
}
);
ADD_CASE_TO_GROUP("block literal as map val at eof, implicit indentation 2",
R"(
example: |
Several lines of text,
with some "quotes" of various 'types',
and also a blank line:
plus another line at the end.
)",
L{
N(QV, "example", "Several lines of text,\nwith some \"quotes\" of various 'types',\nand also a blank line:\n\nplus another line at the end.\n"),
}
);
ADD_CASE_TO_GROUP("block literal as map val at eof, implicit indentation 4",
R"(
example: |
Several lines of text,
with some "quotes" of various 'types',
and also a blank line:
plus another line at the end.
)",
L{
N(QV, "example", "Several lines of text,\nwith some \"quotes\" of various 'types',\nand also a blank line:\n\nplus another line at the end.\n"),
}
);
ADD_CASE_TO_GROUP("block literal as map val, implicit indentation 9",
R"(
example: |
Several lines of text,
with some "quotes" of various 'types',
and also a blank line:
plus another line at the end.
another: val
)",
L{
N(QV, "example", "Several lines of text,\nwith some \"quotes\" of various 'types',\nand also a blank line:\n\nplus another line at the end.\n"),
N("another", "val")
}
);
ADD_CASE_TO_GROUP("block literal as map val, explicit indentation 9",
R"(
example: |9
Several lines of text,
with some "quotes" of various 'types',
and also a blank line:
plus another line at the end.
another: val
)",
L{
N(QV, "example", "Several lines of text,\nwith some \"quotes\" of various 'types',\nand also a blank line:\n\nplus another line at the end.\n"),
N("another", "val")
}
);
ADD_CASE_TO_GROUP("block literal with empty unindented lines, without quotes",
R"(tpl:
src: |
#include <{{hdr.filename}}>
{{src.gencode}}
)",
L{
N("tpl", L{N(QV, "src", "#include <{{hdr.filename}}>\n\n{{src.gencode}}\n")})
}
);
ADD_CASE_TO_GROUP("block literal with empty unindented lines, with double quotes",
R"(tpl:
src: |
#include "{{hdr.filename}}"
{{src.gencode}}
)",
L{
N("tpl", L{N(QV, "src", "#include \"{{hdr.filename}}\"\n\n{{src.gencode}}\n")})
}
);
ADD_CASE_TO_GROUP("block literal with empty unindented lines, with single quotes",
R"(tpl:
src: |
#include '{{hdr.filename}}'
{{src.gencode}}
)",
L{
N("tpl", L{N(QV, "src", "#include '{{hdr.filename}}'\n\n{{src.gencode}}\n")})
}
);
ADD_CASE_TO_GROUP("block literal with same indentation level 0",
R"(
aaa: |2
xxx
bbb: |
yyy
)",
L{N(QV, "aaa", "xxx\n"), N(QV, "bbb", "yyy\n")}
);
ADD_CASE_TO_GROUP("block literal with same indentation level 1",
R"(
- aaa: |2
xxx
bbb: |
yyy
)",
L{N(L{N(QV, "aaa", "xxx\n"), N(QV, "bbb", "yyy\n")})}
);
ADD_CASE_TO_GROUP("block literal with empty docval 1",
R"(|)",
N(DOCVAL|VALQUO, "")
);
ADD_CASE_TO_GROUP("block literal with empty docval 2",
R"(|
)",
N(DOCVAL|VALQUO, "")
);
ADD_CASE_TO_GROUP("block literal with empty docval 3",
R"(|
)",
N(DOCVAL|VALQUO, "")
);
ADD_CASE_TO_GROUP("block literal with empty docval 4",
R"(|
)",
N(DOCVAL|VALQUO, "")
);
ADD_CASE_TO_GROUP("block literal with empty docval 5",
R"(|
)",
N(DOCVAL|VALQUO, "")
);
ADD_CASE_TO_GROUP("block literal with empty docval 6",
R"(|
)",
N(DOCVAL|VALQUO, "")
);
ADD_CASE_TO_GROUP("block literal with empty docval 7",
R"(|
)",
N(DOCVAL|VALQUO, "")
);
ADD_CASE_TO_GROUP("block literal with empty docval 8",
R"(|
)",
N(DOCVAL|VALQUO, "")
);
ADD_CASE_TO_GROUP("block literal with empty docval 9",
R"(|
)",
N(DOCVAL|VALQUO, "")
);
ADD_CASE_TO_GROUP("block literal with empty docval 10",
R"(|
)",
N(DOCVAL|VALQUO, "")
);
ADD_CASE_TO_GROUP("block literal with empty docval 11",
R"(|
)",
N(DOCVAL|VALQUO, "")
);
ADD_CASE_TO_GROUP("block literal with empty docval 12",
R"(|
)",
N(DOCVAL|VALQUO, "")
);
ADD_CASE_TO_GROUP("block literal with empty docval 13",
R"(|
)",
N(DOCVAL|VALQUO, "")
);
ADD_CASE_TO_GROUP("block literal with empty docval 14.0",
R"(- |+
)",
N(SEQ, L{N(VALQUO, "")})
);
ADD_CASE_TO_GROUP("block literal with empty docval 14.0.1",
R"(- |+
)",
N(SEQ, L{N(VALQUO, "\n")})
);
ADD_CASE_TO_GROUP("block literal with empty docval 14.0.2",
R"(- |+
)",
N(SEQ, L{N(VALQUO, "\n")})
);
ADD_CASE_TO_GROUP("block literal with empty docval 14.1",
R"(foo: |+
)",
N(MAP, L{N(VALQUO, "foo", "")})
);
ADD_CASE_TO_GROUP("block literal with empty docval 14.1.1",
R"(foo: |+
)",
N(MAP, L{N(VALQUO, "foo", "\n")})
);
ADD_CASE_TO_GROUP("block literal with empty docval 14.1.2",
R"(foo: |+
)",
N(MAP, L{N(VALQUO, "foo", "\n")})
);
ADD_CASE_TO_GROUP("block literal with empty docval 14.2",
R"(|+
)",
N(DOCVAL|VALQUO, "")
);
ADD_CASE_TO_GROUP("block literal with empty docval 14.2.1",
R"(|+
)",
N(DOCVAL|VALQUO, "\n")
);
ADD_CASE_TO_GROUP("block literal with empty docval 14.2.2",
R"(|+
)",
N(DOCVAL|VALQUO, "\n")
);
ADD_CASE_TO_GROUP("block literal with empty docval 15.0",
R"(- |+
)",
N(SEQ, L{N(VALQUO, "\n")})
);
ADD_CASE_TO_GROUP("block literal with empty docval 15.0.1",
R"(- |+
)",
N(SEQ, L{N(VALQUO, "\n")})
);
ADD_CASE_TO_GROUP("block literal with empty docval 15.1",
R"(foo: |+
)",
N(MAP, L{N(VALQUO, "foo", "\n")})
);
ADD_CASE_TO_GROUP("block literal with empty docval 15.1.1",
R"(foo: |+
)",
N(MAP, L{N(VALQUO, "foo", "\n")})
);
ADD_CASE_TO_GROUP("block literal with empty docval 15.2",
R"(|+
)",
N(DOCVAL|VALQUO, "\n")
);
ADD_CASE_TO_GROUP("block literal with empty docval 15.2.1",
R"(|+
)",
N(DOCVAL|VALQUO, "\n")
);
ADD_CASE_TO_GROUP("block literal with empty docval 16",
R"(|+
)",
N(DOCVAL|VALQUO, "\n\n")
);
ADD_CASE_TO_GROUP("block literal with empty docval 16.1",
R"(foo: |+
)",
N(MAP, L{N(VALQUO, "foo", "\n\n")})
);
ADD_CASE_TO_GROUP("block literal with empty docval 16.2",
R"(- |+
)",
N(SEQ, L{N(VALQUO, "\n\n")})
);
ADD_CASE_TO_GROUP("block literal with empty docval 17",
R"(|+
)",
N(DOCVAL|VALQUO, "\n\n\n")
);
ADD_CASE_TO_GROUP("block literal with empty docval 17.1",
R"(foo: |+
)",
N(MAP, L{N(VALQUO, "foo", "\n\n\n")})
);
ADD_CASE_TO_GROUP("block literal with empty docval 17.2",
R"(- |+
)",
N(SEQ, L{N(VALQUO, "\n\n\n")})
);
ADD_CASE_TO_GROUP("block literal with docval no newlines at end 0",
R"(|
asd)",
N(DOCVAL|VALQUO, "asd\n")
);
ADD_CASE_TO_GROUP("block literal with docval no newlines at end 1",
R"(|
asd
)",
N(DOCVAL|VALQUO, "asd\n")
);
ADD_CASE_TO_GROUP("block literal with docval no newlines at end 1.1",
R"(|
asd
)",
N(DOCVAL|VALQUO, "asd\n")
);
ADD_CASE_TO_GROUP("block literal with docval no newlines at end 1.2",
R"(|+
asd
)",
N(DOCVAL|VALQUO, "asd\n")
);
ADD_CASE_TO_GROUP("block literal with docval no newlines at end 2",
R"(|
asd
)",
N(DOCVAL|VALQUO, "asd\n")
);
ADD_CASE_TO_GROUP("block literal with docval no newlines at end 3",
R"(|
asd
)",
N(DOCVAL|VALQUO, "asd\n")
);
ADD_CASE_TO_GROUP("block literal with docval no newlines at end 4",
R"(|
asd
)",
N(DOCVAL|VALQUO, "asd\n")
);
ADD_CASE_TO_GROUP("block literal with docval no newlines at end 5",
R"(|
asd
)",
N(DOCVAL|VALQUO, "asd\n")
);
ADD_CASE_TO_GROUP("block literal with docval no newlines at end 5.1",
R"(|
asd
)",
N(DOCVAL|VALQUO, "asd\n")
);
ADD_CASE_TO_GROUP("block literal with docval no newlines at end 5.2",
R"(|
asd
)",
N(DOCVAL|VALQUO, "asd\n")
);
ADD_CASE_TO_GROUP("block literal with docval no newlines at end 5.3",
R"(|
asd
)",
N(DOCVAL|VALQUO, "asd\n\n\n \n")
);
ADD_CASE_TO_GROUP("block literal with docval no newlines at end 6",
R"(|
asd
)",
N(DOCVAL|VALQUO, "asd\n \n")
);
ADD_CASE_TO_GROUP("block literal with docval no newlines at end 7",
R"(|
asd
)",
N(DOCVAL|VALQUO, "asd\n \n")
);
ADD_CASE_TO_GROUP("block literal with docval no newlines at end 8",
R"(|
asd
)",
N(DOCVAL|VALQUO, "asd\n \n")
);
ADD_CASE_TO_GROUP("block literal with docval no newlines at end 9",
R"(|
asd
)",
N(DOCVAL|VALQUO, "asd\n \n")
);
ADD_CASE_TO_GROUP("block literal with docval no newlines at end 10",
R"(|
asd
)",
N(DOCVAL|VALQUO, "asd\n\t \n")
);
ADD_CASE_TO_GROUP("block literal with docval no newlines at end 11",
R"(|
asd
)",
N(DOCVAL|VALQUO, "asd\n \t \n")
);
ADD_CASE_TO_GROUP("block literal with docval no newlines at end 12",
R"(|
asd
)",
N(DOCVAL|VALQUO, "asd\n\t \n")
);
ADD_CASE_TO_GROUP("block literal with docval no newlines at end 13",
R"(|
asd
)",
N(DOCVAL|VALQUO, "asd\n \t \n")
);
ADD_CASE_TO_GROUP("block literal, empty block vals in seq 0",
R"(- |+
- |+
)",
N(L{N(QV, "\n"), N(QV, "\n"),}));
ADD_CASE_TO_GROUP("block literal, empty block vals in seq 1",
R"(- |+
- |+
)",
N(L{N(QV, "\n"), N(QV, "\n"),}));
}
} // namespace yml
} // namespace c4
| 20.483592 | 207 | 0.595573 | fargies |
739f0ebc3ca99219743f4ba3df4d91f5b04bc2d4 | 6,734 | cpp | C++ | be/src/vec/exec/olap_scanner.cpp | acelyc111/doris-vectorized | cb9d1e0128e9f6306dde66265a1f35d15b77e51d | [
"Apache-2.0"
] | null | null | null | be/src/vec/exec/olap_scanner.cpp | acelyc111/doris-vectorized | cb9d1e0128e9f6306dde66265a1f35d15b77e51d | [
"Apache-2.0"
] | null | null | null | be/src/vec/exec/olap_scanner.cpp | acelyc111/doris-vectorized | cb9d1e0128e9f6306dde66265a1f35d15b77e51d | [
"Apache-2.0"
] | null | null | null | // 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.
#include "vec/exec/olap_scanner.h"
#include "vec/columns/column_vector.h"
#include "vec/common/assert_cast.h"
#include "vec/core/block.h"
#include "vec/exec/olap_scan_node.h"
#include "vec/exprs/vexpr_context.h"
namespace doris::vectorized {
VOlapScanner::VOlapScanner(RuntimeState* runtime_state, VOlapScanNode* parent, bool aggregation,
bool need_agg_finalize, const TPaloScanRange& scan_range,
const std::vector<OlapScanRange*>& key_ranges)
: OlapScanner(runtime_state, parent, aggregation, need_agg_finalize, scan_range,
key_ranges),
_runtime_state(runtime_state),
_parent(parent),
_profile(parent->runtime_profile()) {}
VOlapScanner::~VOlapScanner() {}
Status VOlapScanner::get_block(RuntimeState* state, vectorized::Block* block, bool* eof) {
auto tracker = MemTracker::CreateTracker(state->fragment_mem_tracker()->limit(),
"VOlapScanner:" + print_id(state->query_id()),
state->fragment_mem_tracker());
std::unique_ptr<MemPool> mem_pool(new MemPool(tracker.get()));
int64_t raw_rows_threshold = raw_rows_read() + config::doris_scanner_row_num;
auto agg_object_pool = std::make_unique<ObjectPool>();
do {
block->clear();
std::vector<vectorized::MutableColumnPtr> columns;
for (auto slot : get_query_slots()) {
columns.emplace_back(slot->get_empty_mutable_column());
}
while (true) {
// block is full, break
if (state->batch_size() <= columns[0]->size()) {
_update_realtime_counter();
break;
}
// Read one row from reader
auto res = _reader->next_row_with_aggregation(&_read_row_cursor, mem_pool.get(),
agg_object_pool.get(), eof);
if (res != OLAP_SUCCESS) {
std::stringstream ss;
ss << "Internal Error: read storage fail. res=" << res
<< ", tablet=" << _tablet->full_name()
<< ", backend=" << BackendOptions::get_localhost();
return Status::InternalError(ss.str());
}
// If we reach end of this scanner, break
if (UNLIKELY(*eof)) {
break;
}
_num_rows_read++;
_convert_row_to_block(&columns);
VLOG_ROW << "VOlapScanner input row: " << _read_row_cursor.to_string();
if (raw_rows_read() >= raw_rows_threshold) {
break;
}
}
auto n_columns = 0;
for (const auto slot_desc : _tuple_desc->slots()) {
block->insert(ColumnWithTypeAndName(columns[n_columns++]->getPtr(),
slot_desc->get_data_type_ptr(),
slot_desc->col_name()));
}
VLOG_ROW << "VOlapScanner output rows: " << block->rows();
if (_vconjunct_ctx != nullptr) {
int result_column_id = -1;
_vconjunct_ctx->execute(block, &result_column_id);
Block::filter_block(block, result_column_id, _tuple_desc->slots().size());
}
} while (block->rows() == 0 && !(*eof) && raw_rows_read() < raw_rows_threshold);
return Status::OK();
}
void VOlapScanner::_convert_row_to_block(std::vector<vectorized::MutableColumnPtr>* columns) {
size_t slots_size = _query_slots.size();
for (int i = 0; i < slots_size; ++i) {
SlotDescriptor* slot_desc = _query_slots[i];
auto cid = _return_columns[i];
if (_read_row_cursor.is_null(cid)) {
(*columns)[i]->insertData(nullptr, 0);
continue;
}
char* ptr = (char*)_read_row_cursor.cell_ptr(cid);
size_t len = _read_row_cursor.column_size(cid);
switch (slot_desc->type().type) {
case TYPE_CHAR: {
Slice* slice = reinterpret_cast<Slice*>(ptr);
(*columns)[i]->insertData(slice->data, strnlen(slice->data, slice->size));
break;
}
case TYPE_VARCHAR:
case TYPE_OBJECT:
case TYPE_HLL: {
Slice* slice = reinterpret_cast<Slice*>(ptr);
(*columns)[i]->insertData(slice->data, slice->size);
break;
}
case TYPE_DECIMAL: {
int64_t int_value = *(int64_t*)(ptr);
int32_t frac_value = *(int32_t*)(ptr + sizeof(int64_t));
DecimalValue data(int_value, frac_value);
(*columns)[i]->insertData(reinterpret_cast<char*>(&data), slot_desc->slot_size());
break;
}
case TYPE_DECIMALV2: {
int64_t int_value = *(int64_t*)(ptr);
int32_t frac_value = *(int32_t*)(ptr + sizeof(int64_t));
DecimalV2Value data(int_value, frac_value);
(*columns)[i]->insertData(reinterpret_cast<char*>(&data), slot_desc->slot_size());
break;
}
case TYPE_DATETIME: {
uint64_t value = *reinterpret_cast<uint64_t*>(ptr);
DateTimeValue data(value);
(*columns)[i]->insertData(reinterpret_cast<char*>(&data), slot_desc->slot_size());
break;
}
case TYPE_DATE: {
uint64_t value = 0;
value = *(unsigned char*)(ptr + 2);
value <<= 8;
value |= *(unsigned char*)(ptr + 1);
value <<= 8;
value |= *(unsigned char*)(ptr);
DateTimeValue data(value);
(*columns)[i]->insertData(reinterpret_cast<char*>(&data), slot_desc->slot_size());
break;
}
default: {
(*columns)[i]->insertData(ptr, len);
break;
}
}
}
}
} // namespace doris::vectorized
| 40.812121 | 96 | 0.574102 | acelyc111 |
739f4d738dfe9542ea3d7331f5b53807081f709e | 436 | inl | C++ | include/glw/Mesh.inl | jarrettchisholm/glr | 79a57b12e26fe84595e833cace3528cb9c82bc20 | [
"WTFPL"
] | 11 | 2015-08-19T23:15:41.000Z | 2018-05-15T21:53:28.000Z | include/glw/Mesh.inl | jarrettchisholm/glr | 79a57b12e26fe84595e833cace3528cb9c82bc20 | [
"WTFPL"
] | 2 | 2015-05-21T06:37:24.000Z | 2015-05-23T05:37:16.000Z | include/glw/Mesh.inl | jarrettchisholm/glr | 79a57b12e26fe84595e833cace3528cb9c82bc20 | [
"WTFPL"
] | 5 | 2016-10-31T08:02:15.000Z | 2018-08-24T07:40:23.000Z | namespace glr
{
namespace glw
{
template<class Archive> void Mesh::serialize(Archive& ar, const unsigned int version)
{
boost::serialization::void_cast_register<Mesh, IMesh>(
static_cast<Mesh*>(nullptr),
static_cast<IMesh*>(nullptr)
);
//ar & boost::serialization::base_object<IMesh>(*this);
ar & name_;
ar & vertices_;
ar & normals_;
ar & textureCoordinates_;
ar & colors_;
ar & vertexBoneData_;
ar & boneData_;
}
}
}
| 18.166667 | 85 | 0.708716 | jarrettchisholm |
73ab0e23a721296a31385a51f0373b46201ae313 | 1,456 | cpp | C++ | RestfulServer.cpp | Enseed/Restful | 263df222e7bae3678fe32355aab67dc4265b14ca | [
"Apache-2.0"
] | null | null | null | RestfulServer.cpp | Enseed/Restful | 263df222e7bae3678fe32355aab67dc4265b14ca | [
"Apache-2.0"
] | null | null | null | RestfulServer.cpp | Enseed/Restful | 263df222e7bae3678fe32355aab67dc4265b14ca | [
"Apache-2.0"
] | null | null | null | #include "Precompiled.h"
#include "RestfulServer.h"
#include "Domain/DTO/Errors/ErrorDTO.h"
#include "Domain/DTO/Errors/ErrorDTO.reflect.h"
#include "HTTP/HttpDTOResult.h"
#include <boost/uuid/random_generator.hpp>
#include <boost/date_time/microsec_time_clock.hpp>
#include <Restless/HTTP/HttpStatus.h>
#include <Restless/HTTP/HttpResult.h>
#include <Restless/HTTP/HttpMediaType.h>
#include <Restless/HTTP/HttpResponse.h>
#include <Restless/HTTP/HttpExceptions.h>
#include "HTTP/HttpErrors.h"
#include "Log.h"
namespace restful {
RestfulServer::RestfulServer(int port)
: RestlessServer(port)
{}
RestfulServer::~RestfulServer()
{}
sd::AutoPtr<HttpResult> RestfulServer::onException(mg_connection *connection, const std::exception &exception)
{
return HttpErrors::createFromException(exception).givePtr();
}
int RestfulServer::onError(mg_connection * connection, int statusCode)
{
ErrorDTO errorDTO;
errorDTO.id = boost::uuids::random_generator()();
errorDTO.message = HttpStatus::fromInt(statusCode).defaultMessage();
errorDTO.time = boost::posix_time::microsec_clock::universal_time();
HttpResult *result = HttpDTOResult::createFromDTO(errorDTO, HttpMediaType::APPLICATION_JSON);
result->setStatus(HttpStatus::fromInt(statusCode));
HttpResponse response(connection);
response.send(*result);
delete result;
LOG_ERROR << "Error: " << season::RapidSeason::toJSON(errorDTO);
return 0;
}
} // namespace restless
| 28.54902 | 111 | 0.763736 | Enseed |
73af655af51ef49d3c251a5c1e13d63a2e067184 | 1,047 | cpp | C++ | Game/src/main.cpp | DebugScientist78/Encryption-Game | 8044425a11494962d62d162d788e3adac369600f | [
"MIT"
] | null | null | null | Game/src/main.cpp | DebugScientist78/Encryption-Game | 8044425a11494962d62d162d788e3adac369600f | [
"MIT"
] | null | null | null | Game/src/main.cpp | DebugScientist78/Encryption-Game | 8044425a11494962d62d162d788e3adac369600f | [
"MIT"
] | null | null | null | //main.h ties in the project files in a simple include file and can be called easily
#include "../include/main.h"
/*
* Program name: main.cpp
* Date: 10/23/2019
* Purpose: This source file is where the main method is located,
* It runs procedurally with the initilizing and then loads into a loop of screens that are running
* Author: Chency W
*/
int main(int argc, char *args[]) {
//Sets the screen mode to the title screen
scrMode = TITLE;
if (!init()) {
printf("Failed to initlize window \n");
}
else {
//window exit that ends the program
gExit = false;
//the function gives random set of numbers dependent on runtime
srand((int)time(0));
while (!gExit) {
//Check cases for which screen to load
if (scrMode == TITLE) {
loadTitle();
}
else if (scrMode == MAIN) {
loadMain();
}
else if (scrMode == HELP) {
loadHelp();
}
else if (scrMode == LECTURE) {
loadLecture();
}
else {
std::cout << "Transition failed" << std::endl;
}
}
}
//ends the program
clean();
return 0;
} | 22.76087 | 98 | 0.640879 | DebugScientist78 |
73b091bcc2c08ead26f47f76edf5ba13a66d272c | 240 | cc | C++ | Part-I/Ch04/4.2/4.5.cc | RingZEROtlf/Cpp-Primer | bde40534eeca733350825c41f268415fdccb1cc3 | [
"MIT"
] | 1 | 2021-09-23T13:13:12.000Z | 2021-09-23T13:13:12.000Z | Part-I/Ch04/4.2/4.5.cc | RingZEROtlf/Cpp-Primer | bde40534eeca733350825c41f268415fdccb1cc3 | [
"MIT"
] | null | null | null | Part-I/Ch04/4.2/4.5.cc | RingZEROtlf/Cpp-Primer | bde40534eeca733350825c41f268415fdccb1cc3 | [
"MIT"
] | null | null | null | #include <iostream>
int main()
{
std::cout << -30 * 3 + 21 / 5 << std::endl;
std::cout << -30 + 3 * 21 / 5 << std::endl;
std::cout << 30 / 3 * 21 % 5 << std::endl;
std::cout << -30 / 3 * 21 % 4 << std::endl;
return 0;
} | 24 | 47 | 0.454167 | RingZEROtlf |
73b0c3d35f89e2aa26ee925591c7453cea2f5106 | 1,829 | cpp | C++ | Source/SMat3.cpp | JordanEllis6809/UrsineMath | 36f2d82c072af5b209d693b73cd4416a208c0781 | [
"MIT"
] | 1 | 2015-11-02T00:50:04.000Z | 2015-11-02T00:50:04.000Z | Source/SMat3.cpp | JordanEllis6809/UrsineMath | 36f2d82c072af5b209d693b73cd4416a208c0781 | [
"MIT"
] | null | null | null | Source/SMat3.cpp | JordanEllis6809/UrsineMath | 36f2d82c072af5b209d693b73cd4416a208c0781 | [
"MIT"
] | null | null | null | /* ---------------------------------------------------------------------------
** Team Bear King
** DigiPen Institute of Technology 2015
**
** Mat3.cpp
**
** Author:
** - Jordan Ellis - J.Ellis@digipen.edu
**
** Contributors:
** - <list in same format as author if applicable>
** -------------------------------------------------------------------------*/
#include "SMat3.h"
#include "SMat4.h"
#include <sstream>
namespace ursine
{
// Constructors
SMat3::SMat3(const SMat4 &mat)
{
Set(
mat.m[ 0 ][ 0 ], mat.m[ 0 ][ 1 ], mat.m[ 0 ][ 2 ],
mat.m[ 1 ][ 0 ], mat.m[ 1 ][ 1 ], mat.m[ 1 ][ 2 ],
mat.m[ 2 ][ 0 ], mat.m[ 2 ][ 1 ], mat.m[ 2 ][ 2 ]
);
}
SMat3::SMat3(const SQuat &q)
{
auto d = q.LengthSquared( );
// UAssert(d != 0.0f, "This quaternion is of length zero.");
auto s = 2.0f / d;
auto xs = q.X( ) * s, ys = q.Y( ) * s, zs = q.Z( ) * s;
auto wx = q.W( ) * xs, wy = q.W( ) * ys, wz = q.W( ) * zs;
auto xx = q.X( ) * xs, xy = q.X( ) * ys, xz = q.X( ) * zs;
auto yy = q.Y( ) * ys, yz = q.Y( ) * zs, zz = q.Z( ) * zs;
Set(
1.0f - ( yy + zz ), xy - wz, xz + wy,
xy + wz, 1.0f - ( xx + zz ), yz - wx,
xz - wy, yz + wx, 1.0f - ( xx + yy )
);
}
// Public Methods
std::string SMat3::ToString(void) const
{
std::ostringstream M00, M01, M02,
M10, M11, M12,
M20, M21, M22;
M00 << m[ 0 ][ 0 ];
M01 << m[ 0 ][ 1 ];
M02 << m[ 0 ][ 2 ];
M10 << m[ 1 ][ 0 ];
M11 << m[ 1 ][ 1 ];
M12 << m[ 1 ][ 2 ];
M20 << m[ 2 ][ 0 ];
M21 << m[ 2 ][ 1 ];
M22 << m[ 2 ][ 2 ];
return {
"{" +
M00.str( ) + ", " +
M01.str( ) + ", " +
M02.str( ) +
"}\n" +
"{" +
M10.str( ) + ", " +
M11.str( ) + ", " +
M12.str( ) +
"}\n" +
"{" +
M20.str( ) + ", " +
M21.str( ) + ", " +
M22.str( ) +
"}\n"
};
}
}
| 21.517647 | 78 | 0.38491 | JordanEllis6809 |
73b212471bf4609818cf069ca28cfb416e477f2a | 1,164 | cpp | C++ | source/RobotController/Viewer/ViewerPlugin.cpp | xxzl0130/ProgrammingExperience | 4f18ad6eb6bc1e7f0d69b458e0c4efbbf4326cfd | [
"MIT"
] | 1 | 2020-09-08T02:54:11.000Z | 2020-09-08T02:54:11.000Z | source/RobotController/Viewer/ViewerPlugin.cpp | xxzl0130/ProgrammingExperience | 4f18ad6eb6bc1e7f0d69b458e0c4efbbf4326cfd | [
"MIT"
] | 1 | 2020-09-08T02:53:54.000Z | 2020-09-23T00:55:35.000Z | source/RobotController/Viewer/ViewerPlugin.cpp | xxzl0130/ProgrammingExperience | 4f18ad6eb6bc1e7f0d69b458e0c4efbbf4326cfd | [
"MIT"
] | null | null | null | #include "Viewer.h"
#include "ViewerPlugin.h"
#include <QtCore/QtPlugin>
ViewerPlugin::ViewerPlugin(QObject *parent)
: QObject(parent)
{
initialized = false;
}
void ViewerPlugin::initialize(QDesignerFormEditorInterface * /*core*/)
{
if (initialized)
return;
initialized = true;
}
bool ViewerPlugin::isInitialized() const
{
return initialized;
}
QWidget *ViewerPlugin::createWidget(QWidget *parent)
{
return new Viewer(parent);
}
QString ViewerPlugin::name() const
{
return "Viewer";
}
QString ViewerPlugin::group() const
{
return "My Plugins";
}
QIcon ViewerPlugin::icon() const
{
return QIcon();
}
QString ViewerPlugin::toolTip() const
{
return QString();
}
QString ViewerPlugin::whatsThis() const
{
return QString();
}
bool ViewerPlugin::isContainer() const
{
return false;
}
QString ViewerPlugin::domXml() const
{
return "<widget class=\"Viewer\" name=\"viewer\">\n"
" <property name=\"geometry\">\n"
" <rect>\n"
" <x>0</x>\n"
" <y>0</y>\n"
" <width>100</width>\n"
" <height>100</height>\n"
" </rect>\n"
" </property>\n"
"</widget>\n";
}
QString ViewerPlugin::includeFile() const
{
return "Viewer.h";
}
| 14.923077 | 70 | 0.670103 | xxzl0130 |
73b4c3c7ed8df473eca3055c5a94459dd9dc521a | 1,304 | hpp | C++ | include/touca/extra/catch2.hpp | getweasel/weasel-cpp | 871e7790edb791b76a62ef3554b3330f1eb3d1f9 | [
"Apache-2.0"
] | 8 | 2021-01-02T11:41:31.000Z | 2021-04-15T07:05:54.000Z | include/touca/extra/catch2.hpp | getweasel/weasel-cpp | 871e7790edb791b76a62ef3554b3330f1eb3d1f9 | [
"Apache-2.0"
] | 17 | 2021-01-08T06:52:51.000Z | 2021-04-18T20:00:28.000Z | include/touca/extra/catch2.hpp | getweasel/weasel-cpp | 871e7790edb791b76a62ef3554b3330f1eb3d1f9 | [
"Apache-2.0"
] | 1 | 2021-04-16T10:30:23.000Z | 2021-04-16T10:30:23.000Z | // Copyright 2021 Touca, Inc. Subject to Apache-2.0 License.
#pragma once
#ifndef TOUCA_CATCH
#define CATCH_CONFIG_MAIN
#include "catch2/catch.hpp"
#else
#define CATCH_CONFIG_RUNNER
#include "catch2/catch.hpp"
#include "touca/touca.hpp"
int main(int argc, char* argv[]) {
Catch::Session session;
std::array<std::string, 3> touca_configure;
const auto cli =
session.cli() |
Catch::clara::Opt(touca_configure[0],
"api-key")["--api-key"]("Touca API Key") |
Catch::clara::Opt(touca_configure[1],
"api-url")["--api-url"]("Touca API URL") |
Catch::clara::Opt(touca_configure[2], "revision")["--revision"](
"version of the code under test");
session.cli(cli);
const auto returnCode = session.applyCommandLine(argc, argv);
if (returnCode != 0) {
return returnCode;
}
touca::configure({{"api-key", touca_configure[0]},
{"api-url", touca_configure[1]},
{"version", touca_configure[2]}});
if (!touca::is_configured()) {
std::cerr << "failed to configure Touca client:\n - "
<< touca::configuration_error() << std::endl;
return EXIT_FAILURE;
}
const auto exit_status = session.run();
touca::post();
return exit_status;
}
#endif
| 24.603774 | 70 | 0.609663 | getweasel |
73b585fcc67f627ef54a644005bf885e9745b2af | 7,345 | cpp | C++ | test/playback.cpp | hradec/duke | efacf7139cd1d7c2cd2f5127079721bd263dda50 | [
"MIT"
] | 51 | 2015-01-07T18:36:39.000Z | 2021-11-30T15:24:44.000Z | test/playback.cpp | virneo/duke | efacf7139cd1d7c2cd2f5127079721bd263dda50 | [
"MIT"
] | 1 | 2015-01-08T10:48:43.000Z | 2015-02-11T19:32:14.000Z | test/playback.cpp | virneo/duke | efacf7139cd1d7c2cd2f5127079721bd263dda50 | [
"MIT"
] | 18 | 2015-05-11T12:43:37.000Z | 2019-11-29T11:15:41.000Z | #include <gtest/gtest.h>
#include "duke/cmdline/CmdLineParameters.hpp"
#include "duke/engine/Player.hpp"
static const size_t startFrame = 90000;
using namespace duke;
const CmdLineParameters gDefault(0, nullptr);
Timeline getTimeline() {
Track track;
track.add(startFrame, Clip{1});
track.add(startFrame + 1, Clip{1});
track.add(startFrame + 2, Clip{1});
track.add(startFrame + 3, Clip{1});
return {track};
}
TEST(Player, time) {
Player player(gDefault);
EXPECT_EQ(FrameIndex(), player.getCurrentFrame());
player.setPlaybackTime(10); // go to ten seconds
EXPECT_EQ(FrameIndex(25 * 10), player.getCurrentFrame());
player.load(getTimeline(), FrameDuration::PAL);
// should be at the beginning of the timeline
EXPECT_EQ(Time(3600), player.getPlaybackTime());
EXPECT_EQ(FrameIndex(startFrame), player.getCurrentFrame());
player.setPlaybackTime(3610); // go to ten seconds
EXPECT_EQ(FrameIndex(startFrame + 10 * 25), player.getCurrentFrame());
}
TEST(Player, playback) {
Player player(gDefault);
player.load(getTimeline(), FrameDuration::PAL);
player.setPlaybackMode(Player::CONTINUE);
// playing
player.setPlaybackSpeed(1);
player.offsetPlaybackTime(player.getFrameDuration());
const auto currentFrame = player.getCurrentFrame();
EXPECT_EQ(FrameIndex(startFrame + 1), currentFrame);
// pausing
player.setPlaybackSpeed(0);
player.offsetPlaybackTime(player.getFrameDuration());
EXPECT_EQ(currentFrame, player.getCurrentFrame());
// fast forward
player.setPlaybackSpeed(10);
player.offsetPlaybackTime(player.getFrameDuration());
EXPECT_EQ(currentFrame + 10, player.getCurrentFrame());
// fast backward
player.setPlaybackSpeed(-10);
player.offsetPlaybackTime(player.getFrameDuration());
EXPECT_EQ(currentFrame, player.getCurrentFrame());
}
TEST(Player, stopping) {
Player player(gDefault);
player.setPlaybackMode(Player::STOP);
const auto timeline = getTimeline();
const auto range = timeline.getRange();
player.load(timeline, FrameDuration::PAL);
EXPECT_EQ(range.first, player.getCurrentFrame().round());
EXPECT_EQ(Player::STOP, player.getPlaybackMode());
player.setPlaybackSpeed(-1);
player.offsetPlaybackTime(player.getFrameDuration()); // should stop at first frame
EXPECT_EQ(0, player.getPlaybackSpeed());
EXPECT_EQ(range.first, player.getCurrentFrame().round());
player.cue(range.last);
player.setPlaybackSpeed(1);
player.offsetPlaybackTime(player.getFrameDuration()); // should stop at last frame
EXPECT_EQ(0, player.getPlaybackSpeed());
EXPECT_EQ(range.last, player.getCurrentFrame().round());
}
TEST(Player, looping) {
Player player(gDefault);
const auto timeline = getTimeline();
const auto range = timeline.getRange();
player.load(timeline, FrameDuration::PAL);
EXPECT_EQ(range.first, player.getCurrentFrame().round());
EXPECT_EQ(Player::LOOP, player.getPlaybackMode());
// moving one frame
player.setPlaybackSpeed(-1);
player.offsetPlaybackTime(player.getFrameDuration()); // reverse should go last frame
EXPECT_EQ(range.last, player.getCurrentFrame().round());
player.setPlaybackSpeed(1);
player.offsetPlaybackTime(player.getFrameDuration()); // forward should go first frame
EXPECT_EQ(range.first, player.getCurrentFrame().round());
// moving two frames
player.setPlaybackSpeed(-2);
player.offsetPlaybackTime(player.getFrameDuration()); // reverse should go last frame
EXPECT_EQ(range.last - 1, player.getCurrentFrame().round());
player.setPlaybackSpeed(2);
player.offsetPlaybackTime(player.getFrameDuration()); // forward should go first frame
EXPECT_EQ(range.first, player.getCurrentFrame().round());
}
TEST(Player, looping2) {
Player player(gDefault);
Track track;
track.add(0, Clip{1});
track.add(1, Clip{1});
track.add(2, Clip{1});
track.add(3, Clip{1});
const auto timeline = Timeline{track};
const auto range = timeline.getRange();
auto step = [&]() { player.offsetPlaybackTime(player.getFrameDuration()); };
EXPECT_EQ(range, Range(0, 3));
player.load(timeline, FrameDuration::PAL);
EXPECT_EQ(Player::LOOP, player.getPlaybackMode());
// moving one frame
player.setPlaybackSpeed(-1);
step(); // reverse should go last frame
EXPECT_EQ(FrameIndex(3), player.getCurrentFrame());
player.setPlaybackSpeed(1);
step(); // forward should go first frame
EXPECT_EQ(FrameIndex(0), player.getCurrentFrame());
step();
EXPECT_EQ(FrameIndex(1), player.getCurrentFrame());
step();
EXPECT_EQ(FrameIndex(2), player.getCurrentFrame());
step();
EXPECT_EQ(FrameIndex(3), player.getCurrentFrame());
step();
EXPECT_EQ(FrameIndex(0), player.getCurrentFrame());
}
TEST(Player, looping3) {
Player player(gDefault);
Track track;
track.add(0, Clip{2});
const auto timeline = Timeline{track};
const auto range = timeline.getRange();
EXPECT_EQ(range, Range(0, 1));
player.load(timeline, FrameDuration(1));
EXPECT_EQ(Player::LOOP, player.getPlaybackMode());
EXPECT_EQ(FrameIndex(0), player.getCurrentFrame());
player.setPlaybackSpeed(1);
player.offsetPlaybackTime(Time(1)); // 1s
EXPECT_EQ(FrameIndex(1), player.getCurrentFrame().round());
player.offsetPlaybackTime(Time(1, 3)); // 1.333s
EXPECT_EQ(FrameIndex(1), player.getCurrentFrame().round());
player.offsetPlaybackTime(Time(1, 3)); // 1.666s
EXPECT_EQ(FrameIndex(1), player.getCurrentFrame().round());
player.offsetPlaybackTime(Time(1, 3)); // 2s => looping
EXPECT_EQ(FrameIndex(0), player.getCurrentFrame().round());
// backward
player.cue(0);
player.setPlaybackSpeed(1);
EXPECT_EQ(Time(0), player.getPlaybackTime());
player.offsetPlaybackTime(Time(-1, 3)); // looping 1.666s
EXPECT_EQ(Time(5, 3), player.getPlaybackTime());
EXPECT_EQ(FrameIndex(1), player.getCurrentFrame().round());
player.offsetPlaybackTime(Time(-2, 3)); // 1s
EXPECT_EQ(Time(1), player.getPlaybackTime());
EXPECT_EQ(FrameIndex(1), player.getCurrentFrame().round());
player.offsetPlaybackTime(Time(-1, 1000)); // 0.999s
EXPECT_EQ(Time(999, 1000), player.getPlaybackTime());
EXPECT_EQ(FrameIndex(0), player.getCurrentFrame().round());
}
TEST(Player, forwardThenBackToStart) {
Player player(gDefault);
Track track;
track.add(0, Clip{200});
const auto timeline = Timeline{track};
player.load(timeline, FrameDuration::PAL);
player.setPlaybackSpeed(1);
for (size_t i = 0; i < 4; ++i) player.offsetPlaybackTime(FrameDuration::PAL);
EXPECT_EQ(FrameIndex(4), player.getCurrentFrame().round());
player.setPlaybackSpeed(-1);
for (size_t i = 0; i < 3; ++i) player.offsetPlaybackTime(FrameDuration::PAL);
player.offsetPlaybackTime(FrameDuration::PAL);
EXPECT_EQ(FrameIndex(0), player.getCurrentFrame().round());
}
TEST(Player, loopingWithHugeStep) {
// if in looping mode with offset greater than timeline period, just doing nothing
Player player(gDefault);
const auto timeline = getTimeline();
const auto range = timeline.getRange();
player.load(timeline, FrameDuration::PAL);
EXPECT_EQ(range.first, player.getCurrentFrame().round());
EXPECT_EQ(Player::LOOP, player.getPlaybackMode());
player.setPlaybackSpeed(1);
const auto lotsOfFrames = (range.last - range.first + 1) * 5 / 2;
player.offsetPlaybackTime(player.getFrameDuration() * lotsOfFrames);
EXPECT_EQ(range.first, player.getCurrentFrame().round());
}
| 37.860825 | 89 | 0.730565 | hradec |
73b6f8bb711ea1c657973659ab7a0506ab535f7b | 260 | cpp | C++ | 122A.cpp | shaonsani/Codefoce_solving | 80b821267f35bc62cd8016a378e7facc890d6ad0 | [
"MIT"
] | null | null | null | 122A.cpp | shaonsani/Codefoce_solving | 80b821267f35bc62cd8016a378e7facc890d6ad0 | [
"MIT"
] | null | null | null | 122A.cpp | shaonsani/Codefoce_solving | 80b821267f35bc62cd8016a378e7facc890d6ad0 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int main()
{
int s;
cin>>s;
if(s==4||s==47||s==744||s%4==0||s%7==0||s%47==0||s%744==0||s==477)
{
cout<<"YES"<<endl;
}
else
cout<<"NO"<<endl;
return 0;
}
| 15.294118 | 71 | 0.423077 | shaonsani |
73b7dbdadddb23d907f6c381317a32ac4f8bd01d | 1,916 | hh | C++ | common/dstage/dstage.hh | PeterVondras/DAS | 72dd5223280ec121f998b4932cc6bf7e83187d46 | [
"MIT"
] | null | null | null | common/dstage/dstage.hh | PeterVondras/DAS | 72dd5223280ec121f998b4932cc6bf7e83187d46 | [
"MIT"
] | null | null | null | common/dstage/dstage.hh | PeterVondras/DAS | 72dd5223280ec121f998b4932cc6bf7e83187d46 | [
"MIT"
] | null | null | null | // This is an implementation file which is being included as a header so that
// we can have dynamic template specialization at compile time.
#ifndef DANS02_DSTAGE_CC_IMPL__
#define DANS02_DSTAGE_CC_IMPL__
#include "common/dstage/dstage.h"
#include "common/dstage/dstage.h"
#include "common/dstage/job.h"
#include "glog/logging.h"
namespace dans {
template <typename T_INPUT, typename T_INTERNAL>
DStage<T_INPUT, T_INTERNAL>::DStage(
Priority max_priority, std::unique_ptr<BaseMultiQueue<T_INTERNAL>> multi_q,
std::unique_ptr<BaseDispatcher<T_INPUT, T_INTERNAL>> dispatcher,
std::unique_ptr<BaseScheduler<T_INTERNAL>> scheduler)
: _max_priority(max_priority),
_multi_q(std::move(multi_q)),
_dispatcher(std::move(dispatcher)),
_scheduler(std::move(scheduler)) {
VLOG(4) << __PRETTY_FUNCTION__ << " max_priority=" << max_priority;
// Linking scheduler first so that multiqueue has an outlet before a source.
_scheduler->LinkMultiQ(_multi_q.get());
_scheduler->Run();
_dispatcher->LinkMultiQ(_multi_q.get());
}
template <typename T_INPUT, typename T_INTERNAL>
void DStage<T_INPUT, T_INTERNAL>::Dispatch(UniqJobPtr<T_INPUT> job_p,
unsigned requested_duplication) {
VLOG(4) << __PRETTY_FUNCTION__
<< ((job_p == nullptr) ? " job_p=nullptr," : " job_id=")
<< ((job_p == nullptr) ? ' ' : job_p->job_id)
<< ((job_p == nullptr) ? ' ' : ',')
<< " requested_duplication=" << requested_duplication;
_dispatcher->Dispatch(std::move(job_p), requested_duplication);
}
template <typename T_INPUT, typename T_INTERNAL>
unsigned DStage<T_INPUT, T_INTERNAL>::Purge(JobId job_id) {
VLOG(4) << __PRETTY_FUNCTION__ << " job_id=" << job_id;
unsigned purged = _multi_q->Purge(job_id);
purged += _scheduler->Purge(job_id);
return purged;
}
} // namespace dans
#endif // DANS02_DSTAGE_CC_IMPL__ | 37.568627 | 79 | 0.700939 | PeterVondras |
73b8a583b028e60e2e3777dc80654d9a7d06cc73 | 4,916 | cpp | C++ | src/images/SkWebpEncoder.cpp | NearTox/Skia | 8b7e0616161fff86ecbd8938b90600d72b8d5c1d | [
"BSD-3-Clause"
] | null | null | null | src/images/SkWebpEncoder.cpp | NearTox/Skia | 8b7e0616161fff86ecbd8938b90600d72b8d5c1d | [
"BSD-3-Clause"
] | null | null | null | src/images/SkWebpEncoder.cpp | NearTox/Skia | 8b7e0616161fff86ecbd8938b90600d72b8d5c1d | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright 2010 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "src/images/SkImageEncoderPriv.h"
#ifdef SK_ENCODE_WEBP
# include "include/core/SkBitmap.h"
# include "include/core/SkStream.h"
# include "include/core/SkUnPreMultiply.h"
# include "include/encode/SkWebpEncoder.h"
# include "include/private/SkColorData.h"
# include "include/private/SkImageInfoPriv.h"
# include "include/private/SkTemplates.h"
# include "src/images/SkImageEncoderFns.h"
# include "src/utils/SkUTF.h"
// A WebP encoder only, on top of (subset of) libwebp
// For more information on WebP image format, and libwebp library, see:
// http://code.google.com/speed/webp/
// http://www.webmproject.org/code/#libwebp_webp_image_decoder_library
// http://review.webmproject.org/gitweb?p=libwebp.git
# include <stdio.h>
extern "C" {
// If moving libwebp out of skia source tree, path for webp headers must be
// updated accordingly. Here, we enforce using local copy in webp sub-directory.
# include "webp/encode.h"
# include "webp/mux.h"
}
static int stream_writer(const uint8_t* data, size_t data_size, const WebPPicture* const picture) {
SkWStream* const stream = (SkWStream*)picture->custom_ptr;
return stream->write(data, data_size) ? 1 : 0;
}
using WebPPictureImportProc = int (*)(WebPPicture* picture, const uint8_t* pixels, int stride);
bool SkWebpEncoder::Encode(SkWStream* stream, const SkPixmap& pixmap, const Options& opts) {
if (!SkPixmapIsValid(pixmap)) {
return false;
}
if (SkColorTypeIsAlphaOnly(pixmap.colorType())) {
// Maintain the existing behavior of not supporting encoding alpha-only images.
// TODO: Support encoding alpha only to an image with alpha but no color?
return false;
}
if (nullptr == pixmap.addr()) {
return false;
}
WebPConfig webp_config;
if (!WebPConfigPreset(&webp_config, WEBP_PRESET_DEFAULT, opts.fQuality)) {
return false;
}
WebPPicture pic;
WebPPictureInit(&pic);
SkAutoTCallVProc<WebPPicture, WebPPictureFree> autoPic(&pic);
pic.width = pixmap.width();
pic.height = pixmap.height();
pic.writer = stream_writer;
// Set compression, method, and pixel format.
// libwebp recommends using BGRA for lossless and YUV for lossy.
// The choices of |webp_config.method| currently just match Chrome's defaults. We
// could potentially expose this decision to the client.
if (Compression::kLossy == opts.fCompression) {
webp_config.lossless = 0;
# ifndef SK_WEBP_ENCODER_USE_DEFAULT_METHOD
webp_config.method = 3;
# endif
pic.use_argb = 0;
} else {
webp_config.lossless = 1;
webp_config.method = 0;
pic.use_argb = 1;
}
// If there is no need to embed an ICC profile, we write directly to the input stream.
// Otherwise, we will first encode to |tmp| and use a mux to add the ICC chunk. libwebp
// forces us to have an encoded image before we can add a profile.
sk_sp<SkData> icc = icc_from_color_space(pixmap.info());
SkDynamicMemoryWStream tmp;
pic.custom_ptr = icc ? (void*)&tmp : (void*)stream;
{
const SkColorType ct = pixmap.colorType();
const bool premul = pixmap.alphaType() == kPremul_SkAlphaType;
SkBitmap tmpBm;
WebPPictureImportProc importProc = nullptr;
const SkPixmap* src = &pixmap;
if (ct == kRGB_888x_SkColorType) {
importProc = WebPPictureImportRGBX;
} else if (!premul && ct == kRGBA_8888_SkColorType) {
importProc = WebPPictureImportRGBA;
}
# ifdef WebPPictureImportBGRA
else if (!premul && ct == kBGRA_8888_SkColorType) {
importProc = WebPPictureImportBGRA;
}
# endif
else {
importProc = WebPPictureImportRGBA;
auto info =
pixmap.info().makeColorType(kRGBA_8888_SkColorType).makeAlphaType(kUnpremul_SkAlphaType);
if (!tmpBm.tryAllocPixels(info) ||
!pixmap.readPixels(tmpBm.info(), tmpBm.getPixels(), tmpBm.rowBytes())) {
return false;
}
src = &tmpBm.pixmap();
}
if (!importProc(&pic, reinterpret_cast<const uint8_t*>(src->addr()), src->rowBytes())) {
return false;
}
}
if (!WebPEncode(&webp_config, &pic)) {
return false;
}
if (icc) {
sk_sp<SkData> encodedData = tmp.detachAsData();
WebPData encoded = {encodedData->bytes(), encodedData->size()};
WebPData iccChunk = {icc->bytes(), icc->size()};
SkAutoTCallVProc<WebPMux, WebPMuxDelete> mux(WebPMuxNew());
if (WEBP_MUX_OK != WebPMuxSetImage(mux, &encoded, 0)) {
return false;
}
if (WEBP_MUX_OK != WebPMuxSetChunk(mux, "ICCP", &iccChunk, 0)) {
return false;
}
WebPData assembled;
if (WEBP_MUX_OK != WebPMuxAssemble(mux, &assembled)) {
return false;
}
stream->write(assembled.bytes, assembled.size);
WebPDataClear(&assembled);
}
return true;
}
#endif
| 31.312102 | 99 | 0.693043 | NearTox |
73b8e1ff9e9f2d3e3810ccd15e96702288b7047a | 3,341 | inl | C++ | OgreMain/include/Math/Array/SSE2/Single/OgreBooleanMask.inl | FreeNightKnight/ogre-next | f2d1a31887a87c492b4225e063325c48693fec19 | [
"MIT"
] | 701 | 2019-09-08T15:56:41.000Z | 2022-03-31T05:51:26.000Z | OgreMain/include/Math/Array/SSE2/Single/OgreBooleanMask.inl | FreeNightKnight/ogre-next | f2d1a31887a87c492b4225e063325c48693fec19 | [
"MIT"
] | 204 | 2019-09-01T23:02:32.000Z | 2022-03-28T14:58:39.000Z | OgreMain/include/Math/Array/SSE2/Single/OgreBooleanMask.inl | FreeNightKnight/ogre-next | f2d1a31887a87c492b4225e063325c48693fec19 | [
"MIT"
] | 188 | 2019-09-05T05:14:46.000Z | 2022-03-22T21:51:39.000Z | /*
-----------------------------------------------------------------------------
This source file is part of OGRE-Next
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
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.
-----------------------------------------------------------------------------
*/
namespace Ogre
{
inline ArrayReal BooleanMask4::getMask( bool x, bool y, bool z, bool w )
{
size_t idx = (size_t)x | ( (size_t)y << 1 ) | ( (size_t)z << 2 ) | ( (size_t)w << 3 );
return mMasks[idx];
}
//--------------------------------------------------------------------------------------
inline ArrayReal BooleanMask4::getMask( bool b[4] )
{
size_t idx = (size_t)b[0] | ( (size_t)b[1] << 1 ) | ( (size_t)b[2] << 2 ) | ( (size_t)b[3] << 3 );
return mMasks[idx];
}
//--------------------------------------------------------------------------------------
inline ArrayMaskR BooleanMask4::getAllSetMask()
{
return mMasks[MASK_XYZW];
}
//--------------------------------------------------------------------------------------
inline bool BooleanMask4::allBitsSet( bool mask0[4], bool mask1[4] )
{
static_assert( sizeof(bool) == 1 && sizeof(uint32) == 4,
"This code relies on correct casting!" );
return ( *reinterpret_cast<uint32*>(mask0) & *reinterpret_cast<uint32*>(mask1) ) == 0x01010101;
}
//--------------------------------------------------------------------------------------
inline uint32 BooleanMask4::getScalarMask( ArrayReal mask )
{
return static_cast<uint32>( _mm_movemask_ps( mask ) );
}
//--------------------------------------------------------------------------------------
inline uint32 BooleanMask4::getScalarMask( ArrayInt mask )
{
return static_cast<uint32>( _mm_movemask_ps( _mm_castsi128_ps( mask ) ) );
}
#define IS_SET_MASK_X( intMask ) ((intMask & MASK_W) != 0)
#define IS_SET_MASK_Y( intMask ) ((intMask & MASK_Z) != 0)
#define IS_SET_MASK_Z( intMask ) ((intMask & MASK_Y) != 0)
#define IS_SET_MASK_W( intMask ) ((intMask & MASK_X) != 0)
#define MASK_ALL_BITS_SET 4
#define IS_BIT_SET( bit, intMask ) ( (intMask & (1 << bit) ) != 0)
}
| 45.148649 | 106 | 0.55642 | FreeNightKnight |
73b95aae10827f69ac7ebe18a488b36566b0a014 | 4,980 | hpp | C++ | src/projects/dbg/graph_printing.hpp | AntonBankevich/LJA | 979d7929bf0b39fd142ec6465dc0c17814465ef9 | [
"BSD-3-Clause"
] | 53 | 2021-10-10T22:16:27.000Z | 2022-03-23T06:21:06.000Z | src/projects/dbg/graph_printing.hpp | AntonBankevich/LJA | 979d7929bf0b39fd142ec6465dc0c17814465ef9 | [
"BSD-3-Clause"
] | 20 | 2021-05-10T07:44:24.000Z | 2022-03-24T13:23:58.000Z | src/projects/dbg/graph_printing.hpp | AntonBankevich/DR | 73450ad3b25f90a3c7747aaf17fe60d13d9692d3 | [
"BSD-3-Clause"
] | 6 | 2022-01-27T01:45:56.000Z | 2022-03-18T04:23:33.000Z | #pragma once
#include "component.hpp"
#include "sparse_dbg.hpp"
namespace dbg {
inline void printFasta(std::ostream &out, const Component &component, bool mask = false) {
size_t cnt = 0;
size_t masked_cnt = 1;
for (Edge &edge : component.edges()) {
Sequence edge_seq = edge.start()->seq + edge.seq;
Vertex &end = *edge.end();
out << ">" << cnt << "_";
if(mask && !component.contains(*edge.start())) {
out << masked_cnt << "0000";
masked_cnt++;
}
out << edge.start()->hash() << int(edge.start()->isCanonical());
out << "_";
if(mask && !component.contains(*edge.end())) {
out << masked_cnt << "0000";
masked_cnt++;
}
out << end.hash() << int(end.isCanonical());
out << "_" << edge.size() << "_" << edge.getCoverage() << "\n";
out << edge_seq << "\n";
cnt++;
}
}
inline void printAssembly(std::ostream &out, const Component &component) {
size_t cnt = 0;
for (Edge &edge : component.edgesUnique()) {
Sequence edge_seq = edge.start()->seq + edge.seq;
Vertex &end = *edge.end();
out << ">" << cnt << "_" << edge.start()->hash() << int(edge.start()->isCanonical()) <<
"_" << end.hash() << int(end.isCanonical()) << "_" << edge.size()
<< "_" << edge.getCoverage() << "\n";
out << edge_seq << "\n";
cnt++;
}
}
inline Sequence cheatingCutStart(Sequence seq, unsigned char c, size_t min_size, size_t k) {
size_t pos = seq.size() - min_size;
while(pos > 0 && seq[pos + k] != c)
pos--;
return seq.Subseq(pos, seq.size());
}
inline void cheatingFasta(const std::experimental::filesystem::path &outf, const Component &component, size_t cut) {
std::ofstream out;
out.open(outf);
size_t cnt = 0;
size_t k = component.graph().hasher().getK();
for (Edge &edge : component.edges()) {
Sequence edge_seq = edge.start()->seq + edge.seq;
if(edge.size() > cut) {
if(!component.contains(*edge.start())) {
edge_seq = cheatingCutStart(edge_seq, edge.seq[0], cut, k);
} else if(!component.contains(*edge.end())) {
edge_seq = !cheatingCutStart(!edge_seq, edge.rc().seq[0], cut, k);
}
}
Vertex &end = *edge.end();
out << ">" << cnt << "_" << edge.start()->hash() << int(edge.start()->isCanonical()) <<
"_" << end.hash() << int(end.isCanonical()) << "_" << edge_seq.size() - edge.start()->seq.size()
<< "_" << edge.getCoverage() << "\n";
out << edge_seq << "\n";
cnt++;
}
out.close();
}
inline void printFasta(const std::experimental::filesystem::path &outf, const Component &component, bool mask = false) {
std::ofstream out;
out.open(outf);
printFasta(out, component, mask);
out.close();
}
inline void printAssembly(const std::experimental::filesystem::path &outf, const Component &component) {
std::ofstream out;
out.open(outf);
printAssembly(out, component);
out.close();
}
inline void printGFA(std::ostream &out, const Component &component, bool calculate_coverage) {
out << "H\tVN:Z:1.0" << std::endl;
size_t cnt = 0;
for (Edge &edge : component.edges()) {
if (edge.start()->isCanonical(edge)) {
if (calculate_coverage)
out << "S\t" << edge.oldId() << "\t" << edge.start()->seq << edge.seq
<< "\tKC:i:" << edge.intCov() << "\n";
else
out << "S\t" << edge.oldId() << "\t" << edge.start()->seq << edge.seq << "\n";
}
}
for (Vertex &vertex : component.verticesUnique()) {
for (const Edge &out_edge : vertex) {
std::string outid = out_edge.oldId();
bool outsign = vertex.isCanonical(out_edge);
for (const Edge &inc_edge : vertex.rc()) {
std::string incid = inc_edge.oldId();
bool incsign = !vertex.rc().isCanonical(inc_edge);
out << "L\t" << incid << "\t" << (incsign ? "+" : "-") << "\t" << outid << "\t"
<< (outsign ? "+" : "-") << "\t" << component.graph().hasher().getK() << "M" << "\n";
}
}
}
}
inline void printGFA(const std::experimental::filesystem::path &outf, const Component &component, bool calculate_coverage) {
std::ofstream out;
out.open(outf);
printGFA(out, component, calculate_coverage);
out.close();
}
} | 41.5 | 128 | 0.48494 | AntonBankevich |
73b9be014515a643a6e293b7d7f083e336f1f05d | 1,564 | cpp | C++ | source/fixed_pool.cpp | bhlzlx/EASTL | 80eb36c5a6986f814d0983ec26269cbb4ea71ffc | [
"BSD-3-Clause"
] | 6,852 | 2016-02-10T00:42:20.000Z | 2022-03-30T07:33:48.000Z | source/fixed_pool.cpp | bhlzlx/EASTL | 80eb36c5a6986f814d0983ec26269cbb4ea71ffc | [
"BSD-3-Clause"
] | 457 | 2015-05-01T22:07:45.000Z | 2022-03-31T02:19:10.000Z | source/fixed_pool.cpp | bhlzlx/EASTL | 80eb36c5a6986f814d0983ec26269cbb4ea71ffc | [
"BSD-3-Clause"
] | 1,041 | 2016-02-10T02:21:49.000Z | 2022-03-31T14:10:02.000Z | ///////////////////////////////////////////////////////////////////////////////
// Copyright (c) Electronic Arts Inc. All rights reserved.
///////////////////////////////////////////////////////////////////////////////
#include <EASTL/internal/fixed_pool.h>
#include <EASTL/fixed_allocator.h>
namespace eastl
{
EASTL_API void fixed_pool_base::init(void* pMemory, size_t memorySize, size_t nodeSize,
size_t alignment, size_t /*alignmentOffset*/)
{
// To do: Support alignmentOffset.
#if EASTL_FIXED_SIZE_TRACKING_ENABLED
mnCurrentSize = 0;
mnPeakSize = 0;
#endif
if(pMemory)
{
// Assert that alignment is a power of 2 value (e.g. 1, 2, 4, 8, 16, etc.)
EASTL_ASSERT((alignment & (alignment - 1)) == 0);
// Make sure alignment is a valid value.
if(alignment < 1)
alignment = 1;
mpNext = (Link*)(((uintptr_t)pMemory + (alignment - 1)) & ~(alignment - 1));
memorySize -= (uintptr_t)mpNext - (uintptr_t)pMemory;
pMemory = mpNext;
// The node size must be at least as big as a Link, which itself is sizeof(void*).
if(nodeSize < sizeof(Link))
nodeSize = ((sizeof(Link) + (alignment - 1))) & ~(alignment - 1);
// If the user passed in a memory size that wasn't a multiple of the node size,
// we need to chop down the memory size so that the last node is not a whole node.
memorySize = (memorySize / nodeSize) * nodeSize;
mpCapacity = (Link*)((uintptr_t)pMemory + memorySize);
mpHead = NULL;
mnNodeSize = nodeSize;
}
}
} // namespace eastl
| 22.028169 | 88 | 0.582481 | bhlzlx |
73bdcd8657fe494fd4c9ce0a8f63bdac667c3553 | 4,882 | cpp | C++ | gporca/libnaucrates/src/parser/CParseHandlerMetadataColumns.cpp | Tanmoy248/gpdb | 67fa1568b3ef2dc1c7757e3e94705de2f92e124b | [
"PostgreSQL",
"Apache-2.0"
] | null | null | null | gporca/libnaucrates/src/parser/CParseHandlerMetadataColumns.cpp | Tanmoy248/gpdb | 67fa1568b3ef2dc1c7757e3e94705de2f92e124b | [
"PostgreSQL",
"Apache-2.0"
] | null | null | null | gporca/libnaucrates/src/parser/CParseHandlerMetadataColumns.cpp | Tanmoy248/gpdb | 67fa1568b3ef2dc1c7757e3e94705de2f92e124b | [
"PostgreSQL",
"Apache-2.0"
] | 1 | 2022-03-22T18:45:41.000Z | 2022-03-22T18:45:41.000Z | //---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2011 Greenplum, Inc.
//
// @filename:
// CParseHandlerMetadataColumns.cpp
//
// @doc:
// Implementation of the SAX parse handler class for parsing a list of
// columns in a relation's metadata.
//---------------------------------------------------------------------------
#include "naucrates/dxl/parser/CParseHandlerMetadataColumns.h"
#include "naucrates/dxl/parser/CParseHandlerManager.h"
#include "naucrates/dxl/parser/CParseHandlerMetadataColumn.h"
#include "naucrates/dxl/parser/CParseHandlerFactory.h"
#include "naucrates/dxl/operators/CDXLOperatorFactory.h"
using namespace gpdxl;
XERCES_CPP_NAMESPACE_USE
//---------------------------------------------------------------------------
// @function:
// CParseHandlerMetadataColumns::CParseHandlerMetadataColumns
//
// @doc:
// Constructor
//
//---------------------------------------------------------------------------
CParseHandlerMetadataColumns::CParseHandlerMetadataColumns
(
IMemoryPool *mp,
CParseHandlerManager *parse_handler_mgr,
CParseHandlerBase *parse_handler_root
)
:
CParseHandlerBase(mp, parse_handler_mgr, parse_handler_root),
m_md_col_array(NULL)
{
}
//---------------------------------------------------------------------------
// @function:
// CParseHandlerMetadataColumns::~CParseHandlerMetadataColumns
//
// @doc:
// Destructor
//
//---------------------------------------------------------------------------
CParseHandlerMetadataColumns::~CParseHandlerMetadataColumns()
{
CRefCount::SafeRelease(m_md_col_array);
}
//---------------------------------------------------------------------------
// @function:
// CParseHandlerMetadataColumns::StartElement
//
// @doc:
// Invoked by Xerces to process an opening tag
//
//---------------------------------------------------------------------------
void
CParseHandlerMetadataColumns::StartElement
(
const XMLCh* const element_uri,
const XMLCh* const element_local_name,
const XMLCh* const element_qname,
const Attributes& attrs
)
{
if(0 == XMLString::compareString(CDXLTokens::XmlstrToken(EdxltokenColumns), element_local_name))
{
// start of a columns' list
GPOS_ASSERT(NULL == m_md_col_array);
m_md_col_array = GPOS_NEW(m_mp) CMDColumnArray(m_mp);
}
else if (0 == XMLString::compareString(CDXLTokens::XmlstrToken(EdxltokenColumn), element_local_name))
{
// column list must be initialized already
GPOS_ASSERT(NULL != m_md_col_array);
// activate parse handler to parse the column info
CParseHandlerBase *col_parse_handler = CParseHandlerFactory::GetParseHandler(m_mp, CDXLTokens::XmlstrToken(EdxltokenMetadataColumn), m_parse_handler_mgr, this);
m_parse_handler_mgr->ActivateParseHandler(col_parse_handler);
this->Append(col_parse_handler);
col_parse_handler->startElement(element_uri, element_local_name, element_qname, attrs);
}
else
{
CWStringDynamic *str = CDXLUtils::CreateDynamicStringFromXMLChArray(m_parse_handler_mgr->GetDXLMemoryManager(), element_local_name);
GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiDXLUnexpectedTag, str->GetBuffer());
}
}
//---------------------------------------------------------------------------
// @function:
// CParseHandlerMetadataColumns::EndElement
//
// @doc:
// Invoked by Xerces to process a closing tag
//
//---------------------------------------------------------------------------
void
CParseHandlerMetadataColumns::EndElement
(
const XMLCh* const, // element_uri,
const XMLCh* const element_local_name,
const XMLCh* const // element_qname
)
{
if(0 == XMLString::compareString(CDXLTokens::XmlstrToken(EdxltokenColumns), element_local_name))
{
// end of the columns' list
GPOS_ASSERT(NULL != m_md_col_array);
const ULONG size = this->Length();
// add parsed columns to the list
for (ULONG ul = 0; ul < size; ul++)
{
CParseHandlerMetadataColumn *md_col_parse_handler = dynamic_cast<CParseHandlerMetadataColumn *>((*this)[ul]);
GPOS_ASSERT(NULL != md_col_parse_handler->GetMdCol());
CMDColumn *md_col = md_col_parse_handler->GetMdCol();
md_col->AddRef();
m_md_col_array->Append(md_col);
}
// deactivate handler
m_parse_handler_mgr->DeactivateHandler();
}
else
{
CWStringDynamic *str = CDXLUtils::CreateDynamicStringFromXMLChArray(m_parse_handler_mgr->GetDXLMemoryManager(), element_local_name);
GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiDXLUnexpectedTag, str->GetBuffer());
}
}
//---------------------------------------------------------------------------
// @function:
// CParseHandlerMetadataColumns::GetMdColArray
//
// @doc:
// Return the constructed list of metadata columns
//
//---------------------------------------------------------------------------
CMDColumnArray *
CParseHandlerMetadataColumns::GetMdColArray()
{
return m_md_col_array;
}
// EOF
| 30.135802 | 162 | 0.618189 | Tanmoy248 |
73c0f71c280326d953f8257b2bfb28be5e49382d | 86,689 | cpp | C++ | gen/make_mat_h.cpp | HolyBlackCat/LD45 | 0a4211826bae66d0076fe5ffaeefc021e759247c | [
"Zlib"
] | 1 | 2019-10-08T02:49:24.000Z | 2019-10-08T02:49:24.000Z | gen/make_mat_h.cpp | HolyBlackCat/LD45 | 0a4211826bae66d0076fe5ffaeefc021e759247c | [
"Zlib"
] | null | null | null | gen/make_mat_h.cpp | HolyBlackCat/LD45 | 0a4211826bae66d0076fe5ffaeefc021e759247c | [
"Zlib"
] | null | null | null | #include <cstdlib>
#include <cstring>
#include <fstream>
#include <functional>
#include <iostream>
#include <string>
#include <sstream>
#include <type_traits>
#define VERSION "3.1.7"
#pragma GCC diagnostic ignored "-Wpragmas" // Silence GCC warning about the next line disabling a warning that GCC doesn't have.
#pragma GCC diagnostic ignored "-Wstring-plus-int" // Silence clang warning about `1+R"()"` pattern.
namespace data
{
const struct {std::string tag, name;} type_list[]
{
{"b", "bool"},
{"c", "char"},
{"uc", "unsigned char"},
{"sc", "signed char"},
{"s", "short"},
{"us", "unsigned short"},
{"i", "int"},
{"u", "unsigned int"},
{"l", "long"},
{"ul", "unsigned long"},
{"ll", "long long"},
{"ull", "unsigned long long"},
{"f", "float"},
{"d", "double"},
{"ld", "long double"},
{"i8", "int8_t"},
{"u8", "uint8_t"},
{"i16", "int16_t"},
{"u16", "uint16_t"},
{"i32", "int32_t"},
{"u32", "uint32_t"},
{"i64", "int64_t"},
{"u64", "uint64_t"},
};
constexpr int type_list_len = std::extent_v<decltype(type_list)>;
const std::string fields[4] {"x","y","z","w"};
constexpr int fields_alt_count = 2;
const std::string fields_alt[fields_alt_count][4]
{
{fields[0], fields[1], fields[2], fields[3]},
{"r","g","b","a"},
// "s","t","p","q", // Who uses this anyway.
};
const std::string custom_operator_symbol = "/", custom_operator_list[]{"dot","cross"};
}
namespace impl
{
std::ofstream output_file;
std::stringstream ss;
const std::stringstream::fmtflags stdfmt = ss.flags();
bool at_line_start = 1;
int indentation = 0;
int section_depth = 0;
constexpr const char *indentation_string = " ", *indentation_string_labels = " ";
void init(int argc, char **argv)
{
if (argc < 2)
{
std::cout << "Expected output file name.";
std::exit(-1);
}
if (argc > 2)
{
std::cout << "Invalid usage.";
std::exit(-1);
}
output_file.open(argv[1]);
if (!output_file)
{
std::cout << "Unable to open `" << argv[1] << "`.\n";
std::exit(-1);
}
}
}
template <typename ...P> [[nodiscard]] std::string make_str(const P &... params)
{
impl::ss.clear();
impl::ss.str("");
impl::ss.flags(impl::stdfmt);
(impl::ss << ... << params);
return impl::ss.str();
}
void output_str(const std::string &str)
{
for (const char *ptr = str.c_str(); *ptr; ptr++)
{
char ch = *ptr;
if (ch == '}' && impl::indentation > 0)
impl::indentation--;
if (impl::at_line_start)
{
if (std::strchr(" \t\r", ch))
continue;
for (int i = 0; i < impl::indentation; i++)
impl::output_file << (i == impl::indentation-1 && ch == '@' ? impl::indentation_string_labels : impl::indentation_string);
impl::at_line_start = 0;
}
if (ch != '@')
impl::output_file.put(ch == '$' ? ' ' : ch);
if (ch == '{')
impl::indentation++;
if (ch == '\n')
impl::at_line_start = 1;
}
}
template <typename ...P> void output(const P &... params)
{
output_str(make_str(params...));
}
void section(std::string header, std::function<void()> func)
{
output(header, "\n{\n");
func();
output("}\n");
}
void section_sc(std::string header, std::function<void()> func) // 'sc' stands for 'end with semicolon'
{
output(header, "\n{\n");
func();
output("};\n");
}
void decorative_section(std::string name, std::function<void()> func)
{
output("//{", std::string(impl::section_depth+1, ' '), name, "\n");
impl::indentation--;
impl::section_depth++;
func();
impl::section_depth--;
output("//}", std::string(impl::section_depth+1, ' '), name, "\n");
impl::indentation++;
}
void next_line()
{
output("\n");
}
int main(int argc, char **argv)
{
impl::init(argc, argv);
{ // Header
output(1+R"(
// mat.h
// Vector and matrix math
// Version )", VERSION, R"(
// Autogenerated, don't touch.
#pragma once
)");
next_line();
}
{ // Includes
output(1+R"(
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <istream>
#include <ostream>
#include <tuple>
#include <type_traits>
#include <utility>
)");
next_line();
}
section("namespace Math", []
{
section("inline namespace Vector // Declarations", []
{
{ // Main templates
output(1+R"(
template <int D, typename T> struct vec;
template <int W, int H, typename T> struct mat;
)");
}
{ // Type-generic
// Vectors of specific size
for (int i = 2; i <= 4; i++)
output(" template <typename T> using vec", i, " = vec<", i, ",T>;");
next_line();
// Matrices of specific size
for (int h = 2; h <= 4; h++)
{
for (int w = 2; w <= 4; w++)
output(" template <typename T> using mat", w, "x", h, " = mat<", w, ",", h, ",T>;");
next_line();
}
// Square matrices of specific size
for (int i = 2; i <= 4; i++)
output(" template <typename T> using mat", i, " = mat", i, "x", i, "<T>;");
next_line();
}
next_line();
{ // Size-generic
for (int i = 0; i < data::type_list_len; i++)
{
const auto &type = data::type_list[i];
// Any size
output("template <int D> using ", type.tag, "vec = vec<D,", type.name, ">;\n"
"template <int W, int H> using ", type.tag, "mat = mat<W,H,", type.name, ">;\n");
// Fixed size
for (int d = 2; d <= 4; d++)
output(" using ", type.tag, "vec", d, " = vec<", d, ',', type.name, ">;");
next_line();
for (int h = 2; h <= 4; h++)
{
for (int w = 2; w <= 4; w++)
output(" using ", type.tag, "mat", w, "x", h, " = mat<", w, ",", h, ",", type.name, ">;");
next_line();
}
for (int i = 2; i <= 4; i++)
output(" using ", type.tag, "mat", i, " = ", type.tag, "mat", i, "x", i, ";");
next_line();
if (i != data::type_list_len-1)
next_line();
}
}
});
next_line();
section("inline namespace Utility // Templates", []
{
output(1+R"(
template <typename T> struct is_vector_impl : std::false_type {};
template <int D, typename T> struct is_vector_impl< vec<D,T>> : std::true_type {};
template <int D, typename T> struct is_vector_impl<const vec<D,T>> : std::true_type {};
template <typename T> inline constexpr bool is_vector_v = is_vector_impl<T>::value;
template <typename ...P> inline constexpr bool no_vectors_v = !(is_vector_v<P> || ...);
template <typename T> struct is_matrix_impl : std::false_type {};
template <int W, int H, typename T> struct is_matrix_impl<mat<W,H,T>> : std::true_type {};
template <int W, int H, typename T> struct is_matrix_impl<const mat<W,H,T>> : std::true_type {};
template <typename T> inline constexpr bool is_matrix_v = is_matrix_impl<T>::value;
template <typename T, typename = void> struct is_other_impl : std::false_type {};
template <typename T> struct is_other_impl<T, decltype(std::enable_if<1, typename T::disable_vec_mat_operators>{}, void())> : std::true_type {}; // Note the use of `enable_if` without `_t`. We just need an arbitrary template type here.
template <typename T> inline constexpr bool is_other_v = is_other_impl<T>::value;
template <typename T> inline constexpr bool is_scalar_v = !is_vector_v<T> && !is_matrix_v<T> && !is_other_v<T>;
template <typename A, typename B = void> using enable_if_scalar_t = std::enable_if_t<is_scalar_v<A>, B>;
template <typename T> using vec_base_t = typename std::conditional_t<is_vector_v<T>, T, std::enable_if<1,T>>::type;
template <typename T> struct vec_size_impl : std::integral_constant<int, 1> {};
template <int D, typename T> struct vec_size_impl< vec<D,T>> : std::integral_constant<int, D> {};
template <int D, typename T> struct vec_size_impl<const vec<D,T>> : std::integral_constant<int, D> {};
template <typename T> inline constexpr int vec_size_v = vec_size_impl<T>::value;
template <typename A, typename B> using change_vec_base_t = std::conditional_t<is_vector_v<A>, vec<vec_size_v<A>, B>, B>;
template <typename T> using floating_point_t = std::conditional_t<std::is_floating_point_v<vec_base_t<T>>, T, change_vec_base_t<T, double>>;
template <typename A, typename B> inline constexpr int compare_types_v =
$ (!is_scalar_v<A> && !is_vector_v<A>) || (!is_scalar_v<B> && !is_vector_v<B>) ? 0 :
$ std::is_floating_point_v<vec_base_t<A>> < std::is_floating_point_v<vec_base_t<B>> ? -1 :
$ std::is_floating_point_v<vec_base_t<A>> > std::is_floating_point_v<vec_base_t<B>> ? 1 :
$ sizeof(vec_base_t<A>) < sizeof(vec_base_t<B>) ? -1 :
$ sizeof(vec_base_t<A>) > sizeof(vec_base_t<B>) ? 1 : 0;
template <typename ...P> struct larger_impl {using type = void;};
template <typename T> struct larger_impl<T> {using type = T;};
template <typename T, typename ...P> struct larger_impl<T,P...> {using type = typename larger_impl<T, typename larger_impl<P...>::type>::type;};
template <typename A, typename B> struct larger_impl<A,B> {using type = std::conditional_t<compare_types_v<A,B> != 0, std::conditional_t<(compare_types_v<A,B> > 0), A, B>, std::conditional_t<std::is_same_v<A,B>, A, void>>;};
template <int D, typename A, typename B> struct larger_impl<vec<D,A>,B> {using type = std::conditional_t<std::is_void_v<typename larger_impl<A,B>::type>, void, change_vec_base_t<vec<D,A>, typename larger_impl<A,B>::type>>;};
template <int D, typename A, typename B> struct larger_impl<B,vec<D,A>> {using type = std::conditional_t<std::is_void_v<typename larger_impl<A,B>::type>, void, change_vec_base_t<vec<D,A>, typename larger_impl<A,B>::type>>;};
template <int DA, int DB, typename A, typename B> struct larger_impl<vec<DA,A>,vec<DB,B>>
{using type = std::conditional_t<DA != DB || std::is_void_v<typename larger_impl<A,B>::type>, void, change_vec_base_t<vec<DA,A>, typename larger_impl<A,B>::type>>;};
// Void on failure
template <typename ...P> struct opt_larger_impl {using type = typename larger_impl<std::remove_const_t<P>...>::type;};
template <typename ...P> using opt_larger_t = typename opt_larger_impl<P...>::type; // void on failure
template <typename ...P> inline constexpr bool have_larger_type_v = !std::is_void_v<opt_larger_t<P...>>;
// Soft error on failure
template <typename ...P> using soft_larger_t = std::enable_if_t<have_larger_type_v<P...>, opt_larger_t<P...>>;
template <typename ...P> struct hard_larger_impl
{
static_assert(have_larger_type_v<P...>, "Can't determine larger type.");
using type = opt_larger_t<P...>;
};
// Hard error on failure
template <typename ...P> using larger_t = typename hard_larger_impl<P...>::type;
)");
});
next_line();
section("inline namespace Vector // Definitions", []
{
decorative_section("Vectors", [&]
{
for (int w = 2; w <= 4; w++)
{
if (w != 2)
next_line();
section_sc(make_str("template <typename T> struct vec<",w,",T> // vec",w), [&]
{
auto Fields = [&](std::string fold_op, std::string pre = "", std::string post = "") -> std::string
{
std::string ret;
for (int i = 0; i < w; i++)
{
if (i != 0)
ret += fold_op;
ret += pre + data::fields[i] + post;
}
return ret;
};
{ // Static assertions
output("static_assert(!std::is_const_v<T> && !std::is_volatile_v<T>, \"The base type must have no cv-qualifiers.\");\n");
output("static_assert(!std::is_reference_v<T>, \"The base type must not be a reference.\");\n");
}
{ // Aliases
output("using type = T;\n");
}
{ // Properties
output("static constexpr int size = ",w,";\n");
output("static constexpr bool is_floating_point = std::is_floating_point_v<type>;\n");
}
{ // Members
for (int i = 0; i < w; i++)
{
output("union {type ");
for (int j = 0; j < data::fields_alt_count; j++)
{
if (j != 0)
output(", ");
output(data::fields_alt[j][i]);
}
output(";};\n");
}
}
{ // Constructors
// Default
output("constexpr vec() = default;\n");
// Element-wise
output("constexpr vec(",Fields(", ","type "),") : ");
for (int i = 0; i < w; i++)
{
if (i != 0)
output(", ");
output(data::fields[i],"(",data::fields[i],")");
}
output(" {}\n");
// Fill with a single value
output("explicit constexpr vec(type obj) : ",Fields(", ","", "(obj)")," {}\n");
// Converting
output("template <typename TT> constexpr vec(vec",w,"<TT> obj) : ");
for (int i = 0; i < w; i++)
{
if (i != 0)
output(", ");
output(data::fields[i],"(obj.",data::fields[i],")");
}
output(" {}\n");
}
{ // Convert to type
output("template <typename TT> [[nodiscard]] constexpr vec",w,"<TT> to() const {return vec",w,"<TT>(",Fields(", ", "TT(", ")"),");}\n");
}
{ // Member access
// Operator []
output("[[nodiscard]] constexpr type &operator[](int i) {return *(type *)((char *)this + sizeof(type)*i);}\n");
output("[[nodiscard]] constexpr const type &operator[](int i) const {return *(type *)((char *)this + sizeof(type)*i);}\n");
// As array
output("[[nodiscard]] type *as_array() {return &x;};\n");
output("[[nodiscard]] const type *as_array() const {return &x;};\n");
}
{ // Boolean
// Convert to bool
output("[[nodiscard]] explicit constexpr operator bool() const {return any(); static_assert(!std::is_same_v<type, bool>, \"Use .none(), .any(), or .all() for vectors of bool.\");}\n");
// None of
output("[[nodiscard]] constexpr bool none() const {return !any();}\n");
// Any of
output("[[nodiscard]] constexpr bool any() const {return ",Fields(" || "),";}\n");
// All of
output("[[nodiscard]] constexpr bool all() const {return ",Fields(" && "),";}\n");
}
{ // Apply operators
// Sum
output("[[nodiscard]] constexpr auto sum() const {return ", Fields(" + "), ";}\n");
// Product
output("[[nodiscard]] constexpr auto prod() const {return ", Fields(" * "), ";}\n");
// Ratio
if (w == 2)
output("[[nodiscard]] constexpr auto ratio() const {return ", Fields(" / ","floating_point_t<type>(",")"), ";}\n");
// Min
output("[[nodiscard]] constexpr type min() const {return std::min({", Fields(","), "});}\n");
// Max
output("[[nodiscard]] constexpr type max() const {return std::max({", Fields(","), "});}\n");
// Abs
output("[[nodiscard]] constexpr vec abs() const {return vec(", Fields(", ", "std::abs(", ")"), ");}\n");
}
{ // Resize
for (int i = 2; i <= 4; i++)
{
if (i == w)
continue;
output("[[nodiscard]] constexpr vec",i,"<type> to_vec",i,"(");
for (int j = w; j < i; j++)
{
if (j != w)
output(", ");
output("type n",data::fields[j]);
}
output(") const {return {");
for (int j = 0; j < i; j++)
{
if (j != 0)
output(", ");
if (j >= w)
output("n");
output(data::fields[j]);
}
output("};}\n");
}
for (int i = w+1; i <= 4; i++)
{
output("[[nodiscard]] constexpr vec",i,"<type> to_vec",i,"() const {return to_vec",i,"(");
for (int j = w; j < i; j++)
{
if (j != w)
output(", ");
output("01"[j == 3]);
}
output(");}\n");
}
}
{ // Length and normalization
// Squared length
output("[[nodiscard]] constexpr auto len_sqr() const {return ");
for (int i = 0; i < w; i++)
{
if (i != 0)
output(" + ");
output(data::fields[i],"*",data::fields[i]);
}
output(";}\n");
// Length
output("[[nodiscard]] constexpr auto len() const {return std::sqrt(len_sqr());}\n");
// Normalize
output("[[nodiscard]] constexpr auto norm() const -> vec",w,"<decltype(type{}/len())> {if (auto l = len()) return *this / l; else return vec(0);}\n");
}
{ // Angles and directions
if (w == 2)
{
// Construct from angle
output("[[nodiscard]] static constexpr vec dir(type angle, type len = 1) {return vec(std::cos(angle) * len, std::sin(angle) * len); static_assert(is_floating_point, \"The vector must be floating-point.\");}\n");
// Get angle
output("template <typename TT = double> [[nodiscard]] constexpr TT angle() const {return std::atan2(TT(y), TT(x));}\n"); // Note that atan2 is well-defined even when applied to (0,0).
// Rotate by 90 degree increments
output("[[nodiscard]] constexpr vec rot90(int steps = 1) const {switch (steps & 3) {default: return *this; case 1: return {-y,x}; case 2: return -*this; case 3: return {y,-x};}}\n");
}
}
{ // Dot and cross products
// Dot product
output("template <typename TT> [[nodiscard]] constexpr auto dot(const vec",w,"<TT> &o) const {return ");
for (int i = 0; i < w; i++)
{
if (i != 0)
output(" + ");
output(data::fields[i]," * o.",data::fields[i]);
}
output(";}\n");
// Cross product
if (w == 3)
output("template <typename TT> [[nodiscard]] constexpr auto cross(const vec3<TT> &o) const -> vec3<decltype(x * o.x - x * o.x)> {return {y * o.z - z * o.y, z * o.x - x * o.z, x * o.y - y * o.x};}\n");
// Cross product z component
if (w == 2)
output("template <typename TT> [[nodiscard]] constexpr auto cross(const vec2<TT> &o) const {return x * o.y - y * o.x;}\n");
// Delta (aka inverse minus)
output("template <typename TT> [[nodiscard]] constexpr auto delta(vec",w,"<TT> v) const {return v - *this;}\n");
}
{ // Tie
output("[[nodiscard]] constexpr auto tie() {return std::tie(",Fields(","),");}\n");
output("[[nodiscard]] constexpr auto tie() const {return std::tie(",Fields(","),");}\n");
}
{ // Get
output("template <int I> [[nodiscard]] constexpr auto &get() {return std::get<I>(tie());}\n");
output("template <int I> [[nodiscard]] constexpr auto &get() const {return std::get<I>(tie());}\n");
}
});
}
next_line();
// Deduction guides
output("template <typename ...P, typename = std::enable_if_t<sizeof...(P) >= 2 && sizeof...(P) <= 4>> vec(P...) -> vec<sizeof...(P), larger_t<P...>>;\n");
});
next_line();
decorative_section("Matrices", [&]
{
for (int w = 2; w <= 4; w++)
for (int h = 2; h <= 4; h++)
{
if (w != 2 || h != 2)
next_line();
section_sc(make_str("template <typename T> struct mat<",w,",",h,",T> // mat", w, "x", h), [&]
{
auto LargeFields = [&](std::string fold_op, std::string pre = "", std::string post = "") -> std::string
{
std::string ret;
for (int i = 0; i < w; i++)
{
if (i != 0)
ret += fold_op;
ret += pre + data::fields[i] + post;
}
return ret;
};
auto SmallFields = [&](std::string fold_op, std::string pre = "", std::string post = "", std::string mid = ".") -> std::string
{
std::string ret;
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++)
{
if (x != 0 || y != 0)
ret += fold_op;
ret += pre + data::fields[x] + mid + data::fields[y] + post;
}
return ret;
};
{ // Static assertions
output("static_assert(!std::is_const_v<T> && !std::is_volatile_v<T>, \"The base type must have no cv-qualifiers.\");\n");
output("static_assert(!std::is_reference_v<T>, \"The base type must not be a reference.\");\n");
}
{ // Aliases
output("using type = T;\n");
output("using member_type = vec", h,"<T>;\n");
}
{ // Properties
output("static constexpr int width = ",w,", height = ",h,";\n");
if (w == h)
output("static constexpr int size = ",w,";\n");
output("static constexpr bool is_floating_point = std::is_floating_point_v<type>;\n");
}
{ // Members
for (int i = 0; i < w; i++)
{
output("union {member_type ");
for (int j = 0; j < data::fields_alt_count; j++)
{
if (j != 0)
output(", ");
output(data::fields_alt[j][i]);
}
output(";};\n");
}
}
{ // Constructors
// Default
output("constexpr mat() : mat(");
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++)
{
if (x || y)
output(",");
output("01"[x == y]);
}
output(") {}\n");
// Element-wise
output("constexpr mat(",LargeFields(", ","const member_type &"),") : ");
for (int i = 0; i < w; i++)
{
if (i != 0)
output(", ");
output(data::fields[i],"(",data::fields[i],")");
}
output(" {}\n");
// Matrix element-wise
output("constexpr mat(",SmallFields(", ","type ","",""),") : ");
for (int x = 0; x < w; x++)
{
if (x != 0)
output(", ");
output(data::fields[x],"(");
for (int y = 0; y < h; y++)
{
if (y != 0)
output(",");
output(data::fields[x],data::fields[y]);
}
output(")");
}
output(" {}\n");
// Converting
output("template <typename TT> constexpr mat(const mat",w,"x",h,"<TT> &obj) : ");
for (int i = 0; i < w; i++)
{
if (i != 0)
output(", ");
output(data::fields[i],"(obj.",data::fields[i],")");
}
output(" {}\n");
}
{ // Convert to type
output("template <typename TT> [[nodiscard]] constexpr mat",w,"x",h,"<TT> to() const {return mat",w,"x",h,"<TT>(",SmallFields(", ","TT(",")"),");}\n");
}
{ // Member access
// Operator []
output("[[nodiscard]] constexpr member_type &operator[](int i) {return *(member_type *)((char *)this + sizeof(member_type)*i);}\n");
output("[[nodiscard]] constexpr const member_type &operator[](int i) const {return *(member_type *)((char *)this + sizeof(member_type)*i);}\n");
// As array
output("[[nodiscard]] type *as_array() {return &x.x;};\n");
output("[[nodiscard]] const type *as_array() const {return &x.x;};\n");
}
{ // Resize
// One-dimensional
for (int i = 2; i <= 4; i++)
{
if (i == w)
continue;
output("[[nodiscard]] constexpr mat",i,"x",h,"<type> to_vec",i,"(");
for (int j = w; j < i; j++)
{
if (j != w)
output(", ");
output("const member_type &n",data::fields[j]);
}
output(") const {return {");
for (int j = 0; j < i; j++)
{
if (j != 0)
output(", ");
if (j >= w)
output("n");
output(data::fields[j]);
}
output("};}\n");
}
for (int i = w+1; i <= 4; i++)
{
output("[[nodiscard]] constexpr mat",i,"x",h,"<type> to_vec",i,"() const {return to_vec",i,"(");
for (int j = w; j < i; j++)
{
if (j != w)
output(", ");
output("{}");
}
output(");}\n");
}
// Two-dimensional
for (int hhh = 2; hhh <= 4; hhh++)
{
for (int www = 2; www <= 4; www++)
{
if (www == w && hhh == h)
continue;
output("[[nodiscard]] constexpr mat",www,"x",hhh,"<type> to_mat",www,"x",hhh,"() const {return {");
for (int hh = 0; hh < hhh; hh++)
{
for (int ww = 0; ww < www; ww++)
{
if (ww != 0 || hh != 0)
output(",");
if (ww < w && hh < h)
output(data::fields[ww],".",data::fields[hh]);
else
output("01"[ww == hh]);
}
}
output("};}\n");
if (www == hhh)
output("[[nodiscard]] constexpr mat",www,"x",hhh,"<type> to_mat",www,"() const {return to_mat",www,"x",www,"();}\n");
}
}
}
{ // Transpose
output("[[nodiscard]] constexpr mat",h,"x",w,"<T> transpose() const {return {");
for (int x = 0; x < w; x++)
for (int y = 0; y < h; y++)
{
if (x != 0 || y != 0)
output(",");
output(data::fields[x],".",data::fields[y]);
}
output("};}\n");
}
{ // Inverse
if (w == h)
{
// NOTE: `ret{}` is used instead of `ret`, because otherwise those functions wouldn't be constexpr due to an uninitialized variable.
switch (w)
{
case 2:
output(1+R"(
[[nodiscard]] constexpr mat inverse()
{
static_assert(is_floating_point, "This function only makes sense for floating-point matrices.");
mat ret{};
ret.x.x = y.y;
ret.y.x = -y.x;
type d = x.x * ret.x.x + x.y * ret.y.x;
if (d == 0) return {};
d = 1 / d;
ret.x.x *= d;
ret.y.x *= d;
ret.x.y = (-x.y) * d;
ret.y.y = ( x.x) * d;
return ret;
}
)");
break;
case 3:
output(1+R"(
[[nodiscard]] constexpr mat inverse() const
{
static_assert(is_floating_point, "This function only makes sense for floating-point matrices.");
mat ret{};
ret.x.x = y.y * z.z - z.y * y.z;
ret.y.x = -y.x * z.z + z.x * y.z;
ret.z.x = y.x * z.y - z.x * y.y;
type d = x.x * ret.x.x + x.y * ret.y.x + x.z * ret.z.x;
if (d == 0) return {};
d = 1 / d;
ret.x.x *= d;
ret.y.x *= d;
ret.z.x *= d;
ret.x.y = (-x.y * z.z + z.y * x.z) * d;
ret.y.y = ( x.x * z.z - z.x * x.z) * d;
ret.z.y = (-x.x * z.y + z.x * x.y) * d;
ret.x.z = ( x.y * y.z - y.y * x.z) * d;
ret.y.z = (-x.x * y.z + y.x * x.z) * d;
ret.z.z = ( x.x * y.y - y.x * x.y) * d;
return ret;
}
)");
break;
case 4:
output(1+R"(
[[nodiscard]] constexpr mat inverse() const
{
static_assert(is_floating_point, "This function only makes sense for floating-point matrices.");
mat ret;
ret.x.x = y.y * z.z * w.w - y.y * z.w * w.z - z.y * y.z * w.w + z.y * y.w * w.z + w.y * y.z * z.w - w.y * y.w * z.z;
ret.y.x = -y.x * z.z * w.w + y.x * z.w * w.z + z.x * y.z * w.w - z.x * y.w * w.z - w.x * y.z * z.w + w.x * y.w * z.z;
ret.z.x = y.x * z.y * w.w - y.x * z.w * w.y - z.x * y.y * w.w + z.x * y.w * w.y + w.x * y.y * z.w - w.x * y.w * z.y;
ret.w.x = -y.x * z.y * w.z + y.x * z.z * w.y + z.x * y.y * w.z - z.x * y.z * w.y - w.x * y.y * z.z + w.x * y.z * z.y;
type d = x.x * ret.x.x + x.y * ret.y.x + x.z * ret.z.x + x.w * ret.w.x;
if (d == 0) return {};
d = 1 / d;
ret.x.x *= d;
ret.y.x *= d;
ret.z.x *= d;
ret.w.x *= d;
ret.x.y = (-x.y * z.z * w.w + x.y * z.w * w.z + z.y * x.z * w.w - z.y * x.w * w.z - w.y * x.z * z.w + w.y * x.w * z.z) * d;
ret.y.y = ( x.x * z.z * w.w - x.x * z.w * w.z - z.x * x.z * w.w + z.x * x.w * w.z + w.x * x.z * z.w - w.x * x.w * z.z) * d;
ret.z.y = (-x.x * z.y * w.w + x.x * z.w * w.y + z.x * x.y * w.w - z.x * x.w * w.y - w.x * x.y * z.w + w.x * x.w * z.y) * d;
ret.w.y = ( x.x * z.y * w.z - x.x * z.z * w.y - z.x * x.y * w.z + z.x * x.z * w.y + w.x * x.y * z.z - w.x * x.z * z.y) * d;
ret.x.z = ( x.y * y.z * w.w - x.y * y.w * w.z - y.y * x.z * w.w + y.y * x.w * w.z + w.y * x.z * y.w - w.y * x.w * y.z) * d;
ret.y.z = (-x.x * y.z * w.w + x.x * y.w * w.z + y.x * x.z * w.w - y.x * x.w * w.z - w.x * x.z * y.w + w.x * x.w * y.z) * d;
ret.z.z = ( x.x * y.y * w.w - x.x * y.w * w.y - y.x * x.y * w.w + y.x * x.w * w.y + w.x * x.y * y.w - w.x * x.w * y.y) * d;
ret.w.z = (-x.x * y.y * w.z + x.x * y.z * w.y + y.x * x.y * w.z - y.x * x.z * w.y - w.x * x.y * y.z + w.x * x.z * y.y) * d;
ret.x.w = (-x.y * y.z * z.w + x.y * y.w * z.z + y.y * x.z * z.w - y.y * x.w * z.z - z.y * x.z * y.w + z.y * x.w * y.z) * d;
ret.y.w = ( x.x * y.z * z.w - x.x * y.w * z.z - y.x * x.z * z.w + y.x * x.w * z.z + z.x * x.z * y.w - z.x * x.w * y.z) * d;
ret.z.w = (-x.x * y.y * z.w + x.x * y.w * z.y + y.x * x.y * z.w - y.x * x.w * z.y - z.x * x.y * y.w + z.x * x.w * y.y) * d;
ret.w.w = ( x.x * y.y * z.z - x.x * y.z * z.y - y.x * x.y * z.z + y.x * x.z * z.y + z.x * x.y * y.z - z.x * x.z * y.y) * d;
return ret;
}
)");
break;
}
}
}
{ // Matrix presets
auto MakePreset = [&](int min_sz, int max_sz, std::string name, std::string params, std::string param_names, std::string body, bool float_only = 1)
{
if (w != h)
return;
if (w == min_sz)
{
output("[[nodiscard]] static constexpr mat ",name,"(",params,")\n{\n");
if (float_only)
output("static_assert(is_floating_point, \"This function only makes sense for floating-point matrices.\");\n");
output(body,"}\n");
}
else if (w >= min_sz && w <= max_sz)
{
output("[[nodiscard]] static constexpr mat ",name,"(",params,") {return mat",min_sz,"<T>::",name,"(",param_names,").to_mat",w,"();}\n");
}
};
MakePreset(2, 3, "scale", "vec2<type> v", "v", 1+R"(
return { v.x , 0 ,
$ 0 , v.y };
)", 0);
MakePreset(3, 4, "scale", "vec3<type> v", "v", 1+R"(
return { v.x , 0 , 0 ,
$ 0 , v.y , 0 ,
$ 0 , 0 , v.z };
)", 0);
MakePreset(3, 3, "ortho", "vec2<type> min, vec2<type> max", "min, max", 1+R"(
return { 2 / (max.x - min.x) , 0 , (min.x + max.x) / (min.x - max.x) ,
$ 0 , 2 / (max.y - min.y) , (min.y + max.y) / (min.y - max.y) ,
$ 0 , 0 , 1 };
)");
MakePreset(4, 4, "ortho", "vec2<type> min, vec2<type> max, type near, type far", "min, max, near, far", 1+R"(
return { 2 / (max.x - min.x) , 0 , 0 , (min.x + max.x) / (min.x - max.x) ,
$ 0 , 2 / (max.y - min.y) , 0 , (min.y + max.y) / (min.y - max.y) ,
$ 0 , 0 , 2 / (near - far) , (near + far) / (near - far) ,
$ 0 , 0 , 0 , 1 };
)");
MakePreset(4, 4, "look_at", "vec3<type> src, vec3<type> dst, vec3<type> local_up", "src, dst, local_up", 1+R"(
vec3<type> v3 = (src-dst).norm();
vec3<type> v1 = local_up.cross(v3).norm();
vec3<type> v2 = v3.cross(v1);
return { v1.x , v1.y , v1.z , -src.x*v1.x-src.y*v1.y-src.z*v1.z ,
$ v2.x , v2.y , v2.z , -src.x*v2.x-src.y*v2.y-src.z*v2.z ,
$ v3.x , v3.y , v3.z , -src.x*v3.x-src.y*v3.y-src.z*v3.z ,
$ 0 , 0 , 0 , 1 };
)");
MakePreset(3, 3, "translate", "vec2<type> v", "v", 1+R"(
return { 1, 0, v.x ,
$ 0, 1, v.y ,
$ 0, 0, 1 };
)", 0);
MakePreset(4, 4, "translate", "vec3<type> v", "v", 1+R"(
return { 1 , 0 , 0 , v.x ,
$ 0 , 1 , 0 , v.y ,
$ 0 , 0 , 1 , v.z ,
$ 0 , 0 , 0 , 1 };
)", 0);
MakePreset(2, 3, "rotate", "type angle", "angle", 1+R"(
type c = std::cos(angle);
type s = std::sin(angle);
return { c, -s ,
$ s, c };
)");
MakePreset(3, 4, "rotate_with_normalized_axis", "vec3<type> axis, type angle", "axis, angle", 1+R"(
type c = std::cos(angle);
type s = std::sin(angle);
return { axis.x * axis.x * (1 - c) + c , axis.x * axis.y * (1 - c) - axis.z * s , axis.x * axis.z * (1 - c) + axis.y * s,
$ axis.y * axis.x * (1 - c) + axis.z * s , axis.y * axis.y * (1 - c) + c , axis.y * axis.z * (1 - c) - axis.x * s,
$ axis.x * axis.z * (1 - c) - axis.y * s , axis.y * axis.z * (1 - c) + axis.x * s , axis.z * axis.z * (1 - c) + c };
)", 0);
MakePreset(3, 4, "rotate", "vec3<type> axis, type angle", "axis, angle", 1+R"(
return rotate_with_normalized_axis(axis.norm(), angle);
)");
MakePreset(4, 4, "perspective", "type wh_aspect, type y_fov, type near, type far", "wh_aspect, y_fov, near, far", 1+R"(
y_fov = type(1) / std::tan(y_fov / 2);
return { y_fov / wh_aspect , 0 , 0 , 0 ,
$ 0 , y_fov , 0 , 0 ,
$ 0 , 0 , (near + far) / (near - far) , 2 * near * far / (near - far) ,
$ 0 , 0 , -1 , 0 };
)");
}
});
}
next_line();
// Deduction guides
output("template <typename ...P, std::enable_if_t<sizeof...(P) == 4, bool> = true> mat(P...) -> mat<2, 2, larger_t<P...>>;\n");
output("template <typename ...P, std::enable_if_t<sizeof...(P) == 9, bool> = true> mat(P...) -> mat<3, 3, larger_t<P...>>;\n");
output("template <typename ...P, std::enable_if_t<sizeof...(P) == 16, bool> = true> mat(P...) -> mat<4, 4, larger_t<P...>>;\n");
});
next_line();
decorative_section("Operators", []
{
const std::string
ops2[]{"+","-","*","/","%","^","&","|","<<",">>","<",">","<=",">=","==","!="},
ops2bool[]{"&&","||"},
ops1[]{"~","+","-"},
ops1incdec[]{"++","--"},
ops1bool[]{"!"},
ops2as[]{"+=","-=","*=","/=","%=","^=","&=","|=","<<=",">>="};
for (int d = 2; d <= 4; d++)
{
if (d != 2)
next_line();
decorative_section(make_str("vec", d), [&]
{
for (auto op : ops2)
{
bool all_of = (op == std::string("==")),
any_of = (op == std::string("!=")),
boolean = all_of || any_of;
// vec @ vec
output("template <typename A, typename B> [[nodiscard]] constexpr ",(boolean ? "bool" : "auto")," operator",op,"(const vec",d,"<A> &a, const vec",d,"<B> &b)",
(boolean ? "" : make_str(" -> vec",d,"<decltype(a.x ",op," b.x)>"))," {return ",(boolean ? "" : "{"));
for (int i = 0; i < d; i++)
{
if (i != 0)
output(all_of ? " && " :
any_of ? " || " : ", ");
output("a.",data::fields[i]," ",op," b.", data::fields[i]);
}
output((boolean ? "" : "}"),";}\n");
// vec @ scalar
output("template <typename V, typename S, typename = enable_if_scalar_t<S>> [[nodiscard]] constexpr ",(boolean ? "bool" : "auto")," operator",op,"(const vec",d,"<V> &v, const S &s) {return v ",op," vec",d,"<S>(s);}\n");
// scalar @ vec
output("template <typename S, typename V, typename = enable_if_scalar_t<S>> [[nodiscard]] constexpr ",(boolean ? "bool" : "auto")," operator",op,"(const S &s, const vec",d,"<V> &v) {return vec",d,"<S>(s) ",op," v;}\n");
}
for (auto op : ops2bool)
{
// vec @ vec
output("template <typename A, typename B> [[nodiscard]] constexpr bool operator",op,"(const vec",d,"<A> &a, const vec",d,"<B> &b) {return bool(a) ",op," bool(b);}\n");
// vec @ any
output("template <typename A, typename B> [[nodiscard]] constexpr bool operator",op,"(const vec",d,"<A> &a, const B &b) {return bool(a) ",op," bool(b);}\n");
// any @ vec
output("template <typename A, typename B> [[nodiscard]] constexpr bool operator",op,"(const A &a, const vec",d,"<B> &b) {return bool(a) ",op," bool(b);}\n");
}
for (auto op : ops1)
{
// @ vec
output("template <typename T> [[nodiscard]] constexpr auto operator",op,"(const vec",d,"<T> &v) -> vec",d,"<decltype(",op,"v.x)> {return {");
for (int i = 0; i < d; i++)
{
if (i != 0)
output(", ");
output(op, "v.", data::fields[i]);
}
output("};}\n");
}
for (auto op : ops1bool)
{
// @ vec
output("template <typename T> [[nodiscard]] constexpr bool operator",op,"(const vec",d,"<T> &v) {return ",op,"bool(v);}\n");
}
for (auto op : ops1incdec)
{
// @ vec
output("template <typename T> constexpr vec",d,"<T> &operator",op,"(vec",d,"<T> &v) {");
for (int i = 0; i < d; i++)
output(op,"v.",data::fields[i],"; ");
output("return v;}\n");
// vec @
output("template <typename T> constexpr vec",d,"<T> operator",op,"(vec",d,"<T> &v, int) {return {");
for (int i = 0; i < d; i++)
{
if (i != 0)
output(", ");
output("v.",data::fields[i],op);
}
output("};}\n");
}
for (auto op : ops2as)
{
// vec @ vec
output("template <typename A, typename B> constexpr vec",d,"<A> &operator",op,"(vec",d,"<A> &a, const vec",d,"<B> &b) {");
for (int i = 0; i < d; i++)
output("a.",data::fields[i]," ",op," b.",data::fields[i],"; ");
output("return a;}\n");
// vec @ scalar
output("template <typename V, typename S, typename = enable_if_scalar_t<S>> constexpr vec",d,"<V> &operator",op,"(vec",d,"<V> &v, const S &s) {return v ",op," vec",d,"<S>(s);}\n");
}
});
}
next_line();
decorative_section("input/output", [&]
{
output(
R"( template <typename A, typename B, int D, typename T> std::basic_ostream<A,B> &operator<<(std::basic_ostream<A,B> &s, const vec<D,T> &v)
{
s.width(0);
s << '[';
for (int i = 0; i < D; i++)
{
if (i != 0)
$ s << ',';
s << v[i];
}
s << ']';
return s;
}
template <typename A, typename B, int W, int H, typename T> std::basic_ostream<A,B> &operator<<(std::basic_ostream<A,B> &s, const mat<W,H,T> &v)
{
s.width(0);
s << '[';
for (int y = 0; y < H; y++)
{
if (y != 0)
$ s << ';';
for (int x = 0; x < W; x++)
{
if (x != 0)
$ s << ',';
s << v[x][y];
}
}
s << ']';
return s;
}
template <typename A, typename B, int D, typename T> std::basic_istream<A,B> &operator>>(std::basic_istream<A,B> &s, vec<D,T> &v)
{
s.width(0);
for (int i = 0; i < D; i++)
$ s >> v[i];
return s;
}
template <typename A, typename B, int W, int H, typename T> std::basic_istream<A,B> &operator>>(std::basic_istream<A,B> &s, mat<W,H,T> &v)
{
s.width(0);
for (int y = 0; y < H; y++)
for (int x = 0; x < W; x++)
$ s >> v[x][y];
return s;
}
)");
});
next_line();
decorative_section("matrix multiplication", [&]
{
auto Matrix = [&](int x, int y, std::string t) -> std::string
{
if (x == 1 && y == 1)
return t;
if (x == 1)
return make_str("vec",y,"<",t,">");
if (y == 1)
return make_str("vec",x,"<",t,">");
return make_str("mat",x,"x",y,"<",t,">");
};
auto Field = [&](int x, int y, int w, int h) -> std::string
{
if (w == 1 && h == 1)
return "";
if (w == 1)
return data::fields[y];
if (h == 1)
return data::fields[x];
return make_str(data::fields[x], ".", data::fields[y]);
};
for (int w2 = 1; w2 <= 4; w2++)
for (int h1 = 1; h1 <= 4; h1++)
for (int w1h2 = 2; w1h2 <= 4; w1h2++) // Starting from 1 would generate `vec * vec` templates (outer products), which would conflict with member-wise multiplication.
{
if (w2 == 1 && h1 == 1) // This disables generation of `vec * vec` templates (dot products), which would conflict with member-wise multiplication.
continue;
output("template <typename A, typename B> [[nodiscard]] constexpr ",Matrix(w2,h1,"larger_t<A,B>")," operator*(const ",Matrix(w1h2,h1,"A")," &a, const ",Matrix(w2,w1h2,"B")," &b) {return {");
for (int y = 0; y < h1; y++)
for (int x = 0; x < w2; x++)
{
if (y != 0 || x != 0)
output(", ");
for (int j = 0; j < w1h2; j++)
{
if (j != 0)
output(" + ");
output("a.",Field(j,y,w1h2,h1),"*b.",Field(x,j,w2,w1h2));
}
}
output("};}\n");
}
next_line();
// Only in those two cases return type matches the type of the first parameter.
output("template <typename A, typename B, int D> constexpr vec<D,A> &operator*=(vec<D,A> &a, const mat<D,D,B> &b) {a = a * b; return a;}\n");
output("template <typename A, typename B, int W, int H> constexpr mat<W,H,A> &operator*=(mat<W,H,A> &a, const mat<W,W,B> &b) {a = a * b; return a;}\n"); // `mat<W,W,B>` is not a typo!
});
});
});
next_line();
section("inline namespace Utility", []
{
decorative_section("Member access", []
{
output(1+R"(
template <int I, typename T> constexpr auto &get_vec_element(T &&vec)
{
// Returns a non-const reference only if the parameter is a non-const lvalue; otherwise returns a const reference.
static_assert(I >= 0 && I < 4);
constexpr bool not_const = std::is_reference_v<T> && !std::is_const_v<std::remove_reference_t<T>>;
if constexpr (!is_vector_v<std::remove_reference_t<T>>)
$ return std::conditional_t<not_const, T &, const T &>(vec);
else
$ return std::conditional_t<not_const, vec_base_t<std::remove_reference_t<T>> &, const vec_base_t<std::remove_reference_t<T>> &>(vec.template get<I>());
}
template <int D, typename F> constexpr void cexpr_for(F &&func)
{
static_assert(D >= 1 && D <= 4);
)");
for (int i = 0; i < 4; i++)
{
if (i >= 1)
output("if constexpr (D > ",i,") ");
output("func(std::integral_constant<int,",i,">{});\n");
}
output(1+R"(
}
)");
});
next_line();
decorative_section("Custom operators", []
{
for (auto op : data::custom_operator_list)
output("struct op_type_",op," {using disable_vec_mat_operators = void;};\n");
next_line();
for (auto op : data::custom_operator_list)
{
output(1+R"(
template <typename A> struct op_expr_type_)",op,R"(
{
using disable_vec_mat_operators = void;
A &&a;
template <typename B> [[nodiscard]] constexpr decltype(auto) operator)",data::custom_operator_symbol,R"((B &&b) {return std::forward<A>(a).)",op,R"((std::forward<B>(b));}
template <typename B> constexpr decltype(auto) operator)",data::custom_operator_symbol,R"(=(B &&b) {a = std::forward<A>(a).)",op,R"((std::forward<B>(b)); return std::forward<A>(a);}
};
)");
}
next_line();
for (auto op : data::custom_operator_list)
output("template <typename T> inline constexpr op_expr_type_",op,"<T> operator",data::custom_operator_symbol,"(T &¶m, op_type_",op,") {return {std::forward<T>(param)};}\n");
});
next_line();
decorative_section("Ranges", []
{
output(1+R"(
template <typename T> class vector_range
{
static_assert(is_vector_v<T> && !std::is_const_v<T> && std::is_integral_v<vec_base_t<T>>, "The template parameter must be an integral vector.");
T vec_begin = T(0);
T vec_end = T(0);
@public:
using disable_vec_mat_operators = void;
class iterator
{
friend class vector_range<T>;
T vec_begin = T(0);
T vec_end = T(0);
T vec_cur = T(0);
bool finished = 1;
iterator() {}
iterator(T vec_begin, T vec_end) : vec_begin(vec_begin), vec_end(vec_end), vec_cur(vec_begin), finished((vec_begin >= vec_end).any()) {}
@public:
using difference_type = std::ptrdiff_t;
using value_type = T;
using pointer = const T *;
using reference = const T &;
using iterator_category = std::forward_iterator_tag;
iterator &operator++()
{
bool stop = 0;
cexpr_for<vec_size_v<T>>([&](auto index)
{
if (stop)
$ return;
constexpr int i = index.value;
auto &elem = get_vec_element<i>(vec_cur);
elem++;
if (elem >= get_vec_element<i>(vec_end))
{
elem = get_vec_element<i>(vec_begin);
if constexpr (i == vec_size_v<T> - 1)
$ finished = 1;
}
else
{
stop = 1;
}
});
return *this;
}
iterator operator++(int)
{
iterator ret = *this;
++(*this);
return ret;
}
reference operator*() const
{
return vec_cur;
}
pointer operator->() const
{
return &vec_cur;
}
bool operator==(const iterator &other) const
{
if (finished != other.finished)
$ return 0;
if (finished && other.finished)
$ return 1;
return vec_cur == other.vec_cur;
}
bool operator!=(const iterator &other) const
{
return !(*this == other);
}
};
vector_range() {}
vector_range(T vec_begin, T vec_end) : vec_begin(vec_begin), vec_end(vec_end) {}
iterator begin() const
{
return iterator(vec_begin, vec_end);
}
iterator end() const
{
return {};
}
template <int A, typename B> friend vector_range operator+(const vector_range &range, vec<A,B> offset)
{
static_assert(std::is_same_v<T, vec<A,B>>, "The offset must have exactly the same type as the range.");
return vector_range(range.vec_begin + offset, range.vec_end + offset);
}
template <int A, typename B> friend vector_range operator+(vec<A,B> offset, const vector_range &range)
{
return range + offset;
}
};
template <typename T> class vector_range_halfbound
{
static_assert(is_vector_v<T> && !std::is_const_v<T> && std::is_integral_v<vec_base_t<T>>, "The template parameter must be an integral vector.");
T vec_begin = T(0);
@public:
using disable_vec_mat_operators = void;
vector_range_halfbound(T vec_begin) : vec_begin(vec_begin) {}
template <int A, typename B> friend vector_range<T> operator<(const vector_range_halfbound &range, vec<A,B> point)
{
static_assert(std::is_same_v<T, vec<A,B>>, "The upper limit must have exactly the same type as the lower limit.");
return vector_range<T>(range.vec_begin, point);
}
template <int A, typename B> friend vector_range<T> operator<=(const vector_range_halfbound &range, vec<A,B> point)
{
return range < point+1;
}
};
struct vector_range_factory
{
using disable_vec_mat_operators = void;
template <int A, typename B> vector_range<vec<A,B>> operator()(vec<A,B> size) const
{
return vector_range<vec<A,B>>(vec<A,B>(0), size);
}
template <int A, typename B> friend vector_range_halfbound<vec<A,B>> operator<=(vec<A,B> point, vector_range_factory)
{
return {point};
}
template <int A, typename B> friend vector_range_halfbound<vec<A,B>> operator<(vec<A,B> point, vector_range_factory)
{
return point+1 <= vector_range_factory{};
}
};
)");
});
});
next_line();
section("inline namespace Misc", []
{
for (auto op : data::custom_operator_list)
output("inline constexpr op_type_", op, " ", op, ";\n");
next_line();
output("inline constexpr vector_range_factory vector_range;\n");
next_line();
output(1+R"(
template <typename F, typename ...P> constexpr auto apply_elementwise(F &&func, P &&... params)
{
using larger_type = opt_larger_t<change_vec_base_t<std::remove_reference_t<P>, int>...>;
static_assert(!std::is_void_v<larger_type>, "Parameter size mismatch.");
constexpr int size = vec_size_v<larger_type>;
using ret_type = decltype(std::declval<F>()(get_vec_element<0>(std::declval<P>())...));
if constexpr (std::is_void_v<ret_type>)
{
cexpr_for<size>([&](auto index)
{
func(get_vec_element<index.value>(params)...); // No forwarding to prevent moving.
});
return void();
}
else
{
std::conditional_t<size != 1, vec<size, ret_type>, ret_type> ret{};
cexpr_for<size>([&](auto index)
{
get_vec_element<index.value>(ret) = func(get_vec_element<index.value>(params)...); // No forwarding to prevent moving.
});
return ret;
}
}
template <typename T> [[nodiscard]] constexpr T pi() {return T(3.14159265358979323846l);}
constexpr float f_pi = pi<float>();
constexpr double d_pi = pi<double>();
constexpr long double ld_pi = pi<long double>();
template <typename T> [[nodiscard]] constexpr auto to_rad(T in)
{
using fp_t = floating_point_t<T>;
return in * pi<fp_t>() / fp_t(180);
}
template <typename T> [[nodiscard]] constexpr auto to_deg(T in)
{
using fp_t = floating_point_t<T>;
return in * fp_t(180) / pi<fp_t>();
}
template <typename T> [[nodiscard]] constexpr change_vec_base_t<T,int> sign(T val)
{
// Works on scalars and vectors.
return (val > 0) - (val < 0);
}
template <typename A, typename B> constexpr void clamp_var_min(A &var, B min)
{
static_assert(no_vectors_v<B> || is_vector_v<A>, "If `min` is a vector, `var` has to be a vector as well.");
if constexpr (no_vectors_v<A,B>)
{
if (var < min)
$ var = min;
}
else
{
apply_elementwise(clamp_var_min<vec_base_t<A>, vec_base_t<B>>, var, min);
}
}
template <typename A, typename B> constexpr void clamp_var_max(A &var, B max)
{
static_assert(no_vectors_v<B> || is_vector_v<A>, "If `max` is a vector, `var` has to be a vector as well.");
if constexpr (no_vectors_v<A,B>)
{
if (var > max)
$ var = max;
}
else
{
apply_elementwise(clamp_var_max<vec_base_t<A>, vec_base_t<B>>, var, max);
}
}
template <typename A, typename B, typename C> constexpr void clamp_var(A &var, B min, C max)
{
clamp_var_min(var, min);
clamp_var_max(var, max);
}
template <typename A, typename B> [[nodiscard]] constexpr A clamp_min(A val, B min)
{
clamp_var_min(val, min);
return val;
}
template <typename A, typename B> [[nodiscard]] constexpr A clamp_max(A val, B max)
{
clamp_var_max(val, max);
return val;
}
template <typename A, typename B, typename C> [[nodiscard]] constexpr A clamp(A val, B min, C max)
{
clamp_var(val, min, max);
return val;
}
template <typename A> [[nodiscard]] constexpr A clamp(A val) {return clamp(val, 0, 1);}
template <typename A> [[nodiscard]] constexpr A clamp_min(A val) {return clamp_min(val, 0);}
template <typename A> [[nodiscard]] constexpr A clamp_max(A val) {return clamp_max(val, 1);}
template <typename A> constexpr void clamp_var(A &var) {clamp_var(var, 0, 1);}
template <typename A> constexpr void clamp_var_min(A &var) {clamp_var_min(var, 0);}
template <typename A> constexpr void clamp_var_max(A &var) {clamp_var_max(var, 1);}
template <typename I = int, typename F> [[nodiscard]] change_vec_base_t<F,I> iround(F x)
{
static_assert(std::is_floating_point_v<vec_base_t<F>>, "Argument must be floating-point.");
static_assert(std::is_integral_v<I> && std::is_signed_v<I>, "Template argument must be integral and signed.");
if constexpr(no_vectors_v<F>)
{
if constexpr (sizeof (I) <= sizeof (long))
$ return std::lround(x);
else
$ return std::llround(x);
}
else
{
return apply_elementwise(iround<I, vec_base_t<F>>, x);
}
}
template <typename T> [[nodiscard]] T abs(T x)
{
if constexpr (no_vectors_v<T>)
$ return std::abs(x);
else
$ return apply_elementwise(abs<vec_base_t<T>>, x);
}
template <typename T> [[nodiscard]] T round(T x)
{
static_assert(std::is_floating_point_v<vec_base_t<T>>, "Argument must be floating-point.");
if constexpr (no_vectors_v<T>)
$ return std::round(x);
else
$ return apply_elementwise(round<vec_base_t<T>>, x);
}
template <typename T> [[nodiscard]] T floor(T x)
{
static_assert(std::is_floating_point_v<vec_base_t<T>>, "Argument must be floating-point.");
if constexpr (no_vectors_v<T>)
$ return std::floor(x);
else
$ return apply_elementwise(floor<vec_base_t<T>>, x);
}
template <typename T> [[nodiscard]] T ceil(T x)
{
static_assert(std::is_floating_point_v<vec_base_t<T>>, "Argument must be floating-point.");
if constexpr (no_vectors_v<T>)
$ return std::ceil(x);
else
$ return apply_elementwise(ceil<vec_base_t<T>>, x);
}
template <typename T> [[nodiscard]] T trunc(T x)
{
static_assert(std::is_floating_point_v<vec_base_t<T>>, "Argument must be floating-point.");
if constexpr (no_vectors_v<T>)
$ return std::trunc(x);
else
$ return apply_elementwise(trunc<vec_base_t<T>>, x);
}
template <typename T> [[nodiscard]] T frac(T x)
{
static_assert(std::is_floating_point_v<vec_base_t<T>>, "Argument must be floating-point.");
if constexpr (no_vectors_v<T>)
$ return std::modf(x, 0);
else
$ return apply_elementwise(frac<vec_base_t<T>>, x);
}
template <typename A, typename B> [[nodiscard]] constexpr A div_ex(A a, B b)
{
static_assert(no_vectors_v<B> || is_vector_v<A>, "If `b` is a vector, `a` has to be a vector as well.");
static_assert(std::is_integral_v<vec_base_t<A>> && std::is_integral_v<vec_base_t<B>>, "Arguments must be integral.");
if constexpr (no_vectors_v<A,B>)
{
if (a >= 0)
$ return a / b;
else
$ return (a + 1) / b - sign(b);
}
else
{
return apply_elementwise(div_ex<vec_base_t<A>, vec_base_t<B>>, a, b);
}
}
template <typename A, typename B> [[nodiscard]] constexpr A mod_ex(A a, B b)
{
static_assert(no_vectors_v<B> || is_vector_v<A>, "If `b` is a vector, `a` has to be a vector as well.");
static_assert(std::is_integral_v<vec_base_t<A>> && std::is_integral_v<vec_base_t<B>>, "Arguments must be integral.");
if constexpr (no_vectors_v<A,B>)
{
if (a >= 0)
$ return a % b;
else
$ return abs(b) - 1 + (a + 1) % b;
}
else
{
return apply_elementwise(mod_ex<vec_base_t<A>, vec_base_t<B>>, a, b);
}
}
template <typename A, typename B> [[nodiscard]] constexpr A ipow(A a, B b)
{
// `A` can be a scalar or a vector. `B` has to be scalar.
static_assert(std::is_integral_v<B>, "Power must be integral.");
A ret = 1;
while (b-- > 0)
$ ret *= a;
return ret;
}
template <typename A, typename B> [[nodiscard]] constexpr floating_point_t<larger_t<A,B>> pow(A a, B b)
{
if constexpr (no_vectors_v<A,B>)
$ return std::pow(a, b);
else
$ return apply_elementwise(pow<vec_base_t<A>, vec_base_t<B>>, a, b);
}
template <typename T> [[nodiscard]] constexpr T smoothstep(T x)
{
// Works on scalars and vectors.
static_assert(std::is_floating_point_v<vec_base_t<T>>, "Argument must be floating-point.");
return (3 - 2*x) * x*x;
}
template <typename ...P> constexpr larger_t<P...> min(P ... params)
{
if constexpr (no_vectors_v<P...>)
$ return std::min({larger_t<P...>(params)...});
else
$ return apply_elementwise(min<vec_base_t<P>...>, params...);
}
template <typename ...P> constexpr larger_t<P...> max(P ... params)
{
if constexpr (no_vectors_v<P...>)
$ return std::max({larger_t<P...>(params)...});
else
$ return apply_elementwise(max<vec_base_t<P>...>, params...);
}
template <typename T> struct linear_mapping
{
static_assert(std::is_floating_point_v<vec_base_t<T>>, "Template parameter must be floating-point.");
T scale = T(1), offset = T(0);
linear_mapping() = default;
linear_mapping(T src_a, T src_b, T dst_a, T dst_b)
{
T factor = 1 / (src_a - src_b);
scale = (dst_a - dst_b) * factor;
offset = (dst_b * src_a - dst_a * src_b) * factor;
}
T operator()(T x) const
{
return x * scale + offset;
}
using matrix_t = mat<vec_size_v<T>+1, vec_size_v<T>+1, vec_base_t<T>>;
matrix_t matrix() const
{
matrix_t ret{};
for (int i = 0; i < vec_size_v<T>; i++)
{
ret[i][i] = scale[i];
ret[vec_size_v<T>][i] = offset[i];
}
return ret;
}
};
template <typename T> vec2<T> intersection_point(vec2<T> a1, vec2<T> a2, vec2<T> b1, vec2<T> b2)
{
static_assert(std::is_floating_point_v<vec_base_t<T>>, "Arguments must be floating-point.");
auto delta_a = a2 - a1;
auto delta_b = b2 - b1;
return ((a1.y - b1.y) * delta_b.x - (a1.x - b1.x) * delta_b.y) / (delta_a.x * delta_b.y - delta_a.y * delta_b.x) * delta_a + a1;
}
)");
});
next_line();
section("namespace Export", []
{
output(1+R"(
using namespace Vector;
using namespace Misc;
using std::int8_t;
using std::uint8_t;
using std::int16_t;
using std::uint16_t;
using std::int32_t;
using std::uint32_t;
using std::int64_t;
using std::uint64_t;
using std::size_t;
using std::ptrdiff_t;
using std::intptr_t;
using std::uintptr_t;
using std::sqrt;
using std::cos;
using std::sin;
using std::tan;
using std::acos;
using std::asin;
using std::atan;
using std::atan2;
using std::pow;
)");
});
});
next_line();
section("namespace std", []
{
output(1+R"(
template <int D, typename T> struct less<Math::vec<D,T>>
{
using result_type = bool;
using first_argument_type = Math::vec<D,T>;
using second_argument_type = Math::vec<D,T>;
constexpr bool operator()(const Math::vec<D,T> &a, const Math::vec<D,T> &b) const
{
return a.tie() < b.tie();
}
};
template <int D, typename T> struct hash<Math::vec<D,T>>
{
using result_type = std::size_t;
using argument_type = Math::vec<D,T>;
std::size_t operator()(const Math::vec<D,T> &v) const
{
std::size_t ret = std::hash<decltype(v.x)>{}(v.x);
for (int i = 1; i < D; i++)
$ ret ^= std::hash<decltype(v.x)>{}(v[i]) + 0x9e3779b9 + (ret << 6) + (ret >> 2); // From Boost.
return ret;
}
};
)");
});
next_line();
output("using namespace Math::Export;\n");
if (!impl::output_file)
return -1;
}
| 47.920951 | 251 | 0.35377 | HolyBlackCat |
73c161b58274a57a59cce924c645d7a966054c10 | 10,620 | cc | C++ | pagespeed/system/controller_manager.cc | dimitrilongo/mod_pagespeed | d0d3bc51aa4feddf010b7085872c64cc46b5aae0 | [
"Apache-2.0"
] | 2 | 2019-11-02T07:54:17.000Z | 2020-04-16T09:26:51.000Z | pagespeed/system/controller_manager.cc | dimitrilongo/mod_pagespeed | d0d3bc51aa4feddf010b7085872c64cc46b5aae0 | [
"Apache-2.0"
] | 12 | 2017-03-14T18:26:11.000Z | 2021-10-01T15:33:50.000Z | pagespeed/system/controller_manager.cc | dimitrilongo/mod_pagespeed | d0d3bc51aa4feddf010b7085872c64cc46b5aae0 | [
"Apache-2.0"
] | 1 | 2020-04-16T09:28:30.000Z | 2020-04-16T09:28:30.000Z | // Copyright 2016 Google Inc.
//
// 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.
//
// Author: jefftk@google.com (Jeff Kaufman)
#include "pagespeed/system/controller_manager.h"
#include <poll.h>
#include <signal.h>
#include <sys/wait.h>
#include <unistd.h>
#include <cerrno>
#include <cstdlib>
#include "base/logging.h"
#include "pagespeed/kernel/base/string.h"
namespace net_instaweb {
int ControllerManager::controller_write_fd_ = -1;
ControllerManager::ProcessDeathWatcherThread::ProcessDeathWatcherThread(
ThreadSystem* thread_system, int controller_read_fd,
ControllerProcess* process, MessageHandler* handler)
: Thread(thread_system, "process death watcher", ThreadSystem::kJoinable),
handler_(handler),
parent_read_fd_(controller_read_fd),
stop_read_fd_(-1),
stop_write_fd_(-1),
process_(process),
parent_death_detected_(false) {
int fds[2];
if (pipe(fds) < 0) {
LOG(FATAL) << "ProcessDeathWatcherThread: pipe failed: " << strerror(errno);
exit(1); // NOTREACHED
}
stop_read_fd_ = fds[0];
stop_write_fd_ = fds[1];
}
ControllerManager::ProcessDeathWatcherThread::~ProcessDeathWatcherThread() {
close(parent_read_fd_);
close(stop_read_fd_);
close(stop_write_fd_); // May be -1.
}
void ControllerManager::ProcessDeathWatcherThread::Stop() {
if (stop_write_fd_ >= 0) {
close(stop_write_fd_);
stop_write_fd_ = -1;
}
this->Join();
}
void ControllerManager::ProcessDeathWatcherThread::Run() {
CHECK_GE(stop_read_fd_, 0);
CHECK_GE(parent_read_fd_, 0);
// This message is used by system/system_test.sh.
handler_->Message(kInfo, "Watching the root process to exit if it dies.");
struct pollfd fds[2];
memset(&fds, 0, sizeof(fds));
fds[0].fd = parent_read_fd_;
fds[0].events = POLLIN;
fds[1].fd = stop_read_fd_;
fds[1].events = POLLIN;
int nready = 0;
while (nready <= 0) {
nready = poll(fds, arraysize(fds), -1 /* infinite timeout */);
// Activity on parent_read_fd_. That means the Apache/Nginx root either died
// or asked us to quit.
if (fds[0].revents) {
DCHECK_EQ(fds[0].fd, parent_read_fd_);
parent_death_detected_ = true;
char buf[1];
ssize_t status = read(parent_read_fd_, buf, 1);
if (status == -1) {
// It's very unlikely, but it could be that errno is EINTR here.
// Given that these messages are diagnostic only, it's just fine to
// ignore that and just exit the loop anyway.
handler_->Message(
kWarning,
"Controller got error %d reading from pipe, shutting down", errno);
} else if (status == 0 /* EOF */) {
handler_->Message(kInfo,
"Root process exited; controller shutting down.");
} else if (status == 1 /* read a byte */) {
handler_->Message(
kInfo, "Root process is starting a new controller; shutting down.");
} else {
LOG(FATAL) << "Status of " << status << " doesn't make sense";
exit(1); // NOTREACHED
}
// Note that it is possible that ControllerProcess::Run has already exited
// at this point. However, the API requires that calling Stop() is still
// OK.
process_->Stop();
}
// Activity on stop_read_fd_. That means ControllerProcess::Run completed
// and now we are being shutdown.
if (fds[1].revents) {
DCHECK_EQ(fds[1].fd, stop_read_fd_);
handler_->Message(kInfo,
"Child process complete, stopping root watcher.");
}
}
}
void ControllerManager::DetachFromControllerProcess() {
if (controller_write_fd_ != -1) {
close(controller_write_fd_);
controller_write_fd_ = -1;
}
}
void ControllerManager::Daemonize(MessageHandler* handler) {
// Make a new session (process group).
if (setsid() < 0) {
handler->Message(kWarning, "Daemonize: Failed to setsid().");
}
// We need to fork again to make sure there is no session group leader.
pid_t pid = fork();
CHECK(pid != -1) << "Couldn't fork to daemonize.";
if (pid != 0) {
exit(EXIT_SUCCESS);
}
// If we keep the current directory we might keep them from being able to
// unmount their filesystem.
if (chdir("/") < 0) {
handler->Message(kWarning, "Daemonize: Failed to chdir(/).");
}
// If we disconnect file descriptors then logging will break, so don't.
}
int ControllerManager::RunController(int controller_read_fd,
ControllerProcess* process,
ThreadSystem* thread_system,
MessageHandler* handler) {
int exit_status = process->Setup();
if (exit_status == 0) {
// Start a thread to watch to see if the root process dies,
// and quit if it does.
std::unique_ptr<ProcessDeathWatcherThread> process_death_watcher_thread(
new ProcessDeathWatcherThread(thread_system, controller_read_fd,
process, handler));
CHECK(process_death_watcher_thread->Start());
exit_status = process->Run();
process_death_watcher_thread->Stop();
// Run may have returned because the parent died, or because of voluntary
// exit. If the parent died, we need to trap that and force the exit status
// to zero, otherwise the babysitter will unnecessarily respawn us.
if (process_death_watcher_thread->parent_death_detected()) {
exit_status = 0;
}
}
return exit_status;
}
void ControllerManager::ForkControllerProcess(
std::unique_ptr<ControllerProcess>&& process,
SystemRewriteDriverFactory* factory,
ThreadSystem* thread_system,
MessageHandler* handler) {
handler->Message(kInfo, "Forking controller process from PID %d", getpid());
// Whenever we fork off a controller we save the fd for a pipe to it. Then if
// we fork off another controller we can write a byte to the pipe to tell the
// old controller to clean up and exit.
if (controller_write_fd_ != -1) {
// We already forked off a controller earlier. Tell it to quit by writing a
// byte. If there's no one still with the pipe open we'll get SIGPIPE and
// die horribly, but as long as the babysitter hasn't died that won't
// happen.
handler->Message(
kInfo, "Writing a byte to a pipe to tell the old controller to exit.");
ssize_t status;
do {
status = write(controller_write_fd_, "Q", 1);
} while (status == -1 && (errno == EAGAIN ||
errno == EINTR));
if (status == -1) {
handler->Message(kWarning, "killing old controller failed: %s",
strerror(errno));
}
}
int file_descriptors[2];
int pipe_status = pipe(file_descriptors);
CHECK(pipe_status != -1) << "Couldn't create a root-controller pipe.";
pid_t pid = fork();
CHECK(pid != -1) << "Couldn't fork a controller babysitter process";
if (pid != 0) {
// Parent process.
// Close the reading end of the pipe. We'll never write to it, but when we
// (and all our children) die there will be no more processes that could
// potentially write to it, and so the people who do have it open for
// reading can see that death.
close(file_descriptors[0]);
// Save the writing end of the pipe.
controller_write_fd_ = file_descriptors[1];
return;
}
// Now we're in the child process. Set this up as a babysitter process,
// that forks off a controller and restarts it if it dies.
Daemonize(handler);
// We need to clear inherited signal handlers. There's no portable way to get
// a list of all possible signals, and they're not even guaranteed to be in
// order. But NSIG is usually defined these days, and if it is then we just
// want ascending numbers up to to NSIG.
for (int i = 0; i < NSIG; i++) {
signal(i, SIG_DFL);
}
factory->PrepareForkedProcess("babysitter");
// Close the writing end of the pipe. If we read a byte from the pipe it
// means we should quit because a new controller is starting up. If we get
// EOF from the pipe it means we should quit because the master process shut
// down.
close(file_descriptors[1]);
int controller_read_fd = file_descriptors[0];
// This message is used by system/system_test.sh.
handler->Message(kInfo, "Babysitter running with PID %d", getpid());
while (true) {
pid = fork();
CHECK(pid != -1) << "Couldn't fork a controller process";
if (pid == 0) {
factory->PrepareForkedProcess("controller");
factory->PrepareControllerProcess();
// This message is used by get_controller_pid in system/system_test.sh.
handler->Message(kInfo, "Controller running with PID %d", getpid());
int exit_status = RunController(controller_read_fd, process.get(),
thread_system, handler);
handler->Message(kInfo, "Controller %d exiting with status %d",
getpid(), exit_status);
exit(exit_status);
} else {
// Wait for controller process to die, then continue with the loop by
// restarting it.
int status;
pid_t child_pid;
do {
child_pid = waitpid(pid, &status, 0);
} while (child_pid == -1 && errno == EINTR);
CHECK(child_pid != -1) << "Call to waitpid failed with status "
<< child_pid;
if (WIFEXITED(status) && WEXITSTATUS(status) == EXIT_SUCCESS) {
handler->Message(kInfo,
"Controller process %d exited normally, not restarting it. "
"Shutting down babysitter.", child_pid);
exit(EXIT_SUCCESS);
}
// system/system_test.sh and the nginx system test look at these messages.
handler->Message(
kWarning, "Controller process %d exited with wait status %d",
child_pid, status);
// If the controller used an unclean exit, it probably had a problem
// binding to a port or similar. Don't try and restart it immediately.
if (WIFEXITED(status)) {
sleep(1);
}
}
}
}
} // namespace net_instaweb
| 35.518395 | 80 | 0.651789 | dimitrilongo |
73c1797ace43d650ae89e6b1ea877ba8fa310af3 | 28,751 | cpp | C++ | src/LuminoEngine/src/Scene/MeshVoxelmap/MeshVoxelset.cpp | infinnie/Lumino | 921caabdbcb91528a2aac290e31d650628bc3bed | [
"MIT"
] | null | null | null | src/LuminoEngine/src/Scene/MeshVoxelmap/MeshVoxelset.cpp | infinnie/Lumino | 921caabdbcb91528a2aac290e31d650628bc3bed | [
"MIT"
] | null | null | null | src/LuminoEngine/src/Scene/MeshVoxelmap/MeshVoxelset.cpp | infinnie/Lumino | 921caabdbcb91528a2aac290e31d650628bc3bed | [
"MIT"
] | null | null | null |
#include "Internal.hpp"
#include <LuminoEngine/Graphics/Texture.hpp>
#include <LuminoEngine/Rendering/Material.hpp>
#include <LuminoEngine/Rendering/RenderingContext.hpp>
#include <LuminoEngine/Scene/MeshVoxelmap/MeshVoxelset.hpp>
#include <LuminoEngine/Graphics/Texture.hpp>
#include <LuminoEngine/Mesh/MeshModel.hpp>
#include <LuminoEngine/Rendering/RenderingContext.hpp>
#include <LuminoEngine/Rendering/Material.hpp>
//#include <simpleboolean/meshoperator.h>
#include "VoxelmapMesh.hpp"
namespace ln {
//==============================================================================
// MeshAutoVoxelset
MeshAutoVoxelset::MeshAutoVoxelset()
{
}
void MeshAutoVoxelset::init()
{
Object::init();
for (int i = 0; i < 6; i++) beveled[i] = false;
}
void MeshAutoVoxelset::setMaterial(Material* value)
{
m_material = value;
}
void MeshAutoVoxelset::buildQubeFloorAndWall()
{
//auto tex = Texture2D::load(u"autotile1");
//detail::MeshAutoTilesetUVMapper uvMapper(
// Size(tex->width(), tex->height()), Rect(0, 0, tex->width(), tex->height()), detail::MeshAutoTilesetUVMapper::Format::XP);
auto* tex = m_material->mainTexture();
detail::MeshAutoTilesetUVMapper uvMapper(
Size(tex->width(), tex->height()), Rect(0, 0, tex->width(), tex->height()), detail::MeshAutoTilesetUVMapper::Format::MVWithWall);
m_mesh = makeObject<MeshPrimitive>((4 * 4 * 48) * 6, (6 * 4 * 48) * 6);
// ZMinus を、指定方向に向けるための変換行列
const auto finalOffset = Vector3(0.5, 0.5, 0.5);
Matrix faceTransforms[6] = {
Matrix::makeRotationY(Math::PI / 2) * Matrix::makeTranslation(Vector3(-0.5, 0, 0) + finalOffset),
Matrix::makeRotationY(-Math::PI / 2) * Matrix::makeTranslation(Vector3(0.5, 0, 0) + finalOffset),
Matrix::makeRotationZ(Math::PI) * Matrix::makeRotationX(-Math::PI / 2) * Matrix::makeTranslation(Vector3(0, -0.5, 0) + finalOffset),
Matrix::makeRotationX(Math::PI / 2) * Matrix::makeTranslation(Vector3(0, 0.5, 0) + finalOffset),
Matrix::Identity * Matrix::makeTranslation(Vector3(0, 0, -0.5) + finalOffset),
Matrix::makeRotationY(Math::PI) * Matrix::makeTranslation(Vector3(0, 0, 0.5) + finalOffset),
};
int offsetV = 0;
int offsetI = 0;
for (int iFaceDir = 0; iFaceDir < 6; iFaceDir++) {
const Matrix& transform = faceTransforms[iFaceDir];
for (int i = 0; i < 48; i++) {
const auto& info = MeshVoxelset::AutoTileTable[i];
int startIndex = offsetI;
Vector3 pysOffsets[4] = { { -0.5, +0.5, 0.0 }, { 0.0, +0.5, 0.0 }, { -0.5, 0.0, 0.0 }, { 0.0, 0.0, 0.0 } };
// [top-left], [top-right], [bottom-left], [bottom-light]
for (int iCorner = 0; iCorner < 4; iCorner++) {
//int index_tl = g_AutoTileSourcePosTable_TkoolXP[iCorner][info.subtiles[iCorner]];
//auto uv = Vector2(subTileUVSize.x * (index_tl % hc), subTileUVSize.y * (index_tl / hc));
auto uvRect = uvMapper.getUVRectFromLocalId(static_cast<MeshTileFaceDirection>(iFaceDir), i, static_cast<detail::SubtileCorner>(iCorner));
auto p1 = Vector3::transformCoord(pysOffsets[iCorner] + Vector3(0, 0, 0), transform);
auto p2 = Vector3::transformCoord(pysOffsets[iCorner] + Vector3(0.5, 0, 0), transform);
auto p3 = Vector3::transformCoord(pysOffsets[iCorner] + Vector3(0, -0.5, 0), transform);
auto p4 = Vector3::transformCoord(pysOffsets[iCorner] + Vector3(0.5, -0.5, 0), transform);
m_mesh->setVertex(offsetV + 0, Vertex{ p1, Vector3::UnitZ, uvRect.getTopLeft(), Color::White });
m_mesh->setVertex(offsetV + 1, Vertex{ p2, Vector3::UnitZ, uvRect.getTopRight(), Color::White });
m_mesh->setVertex(offsetV + 2, Vertex{ p3, Vector3::UnitZ, uvRect.getBottomLeft(), Color::White });
m_mesh->setVertex(offsetV + 3, Vertex{ p4, Vector3::UnitZ, uvRect.getBottomRight(), Color::White });
m_mesh->setIndex(offsetI + 0, offsetV + 0);
m_mesh->setIndex(offsetI + 1, offsetV + 1);
m_mesh->setIndex(offsetI + 2, offsetV + 2);
m_mesh->setIndex(offsetI + 3, offsetV + 2);
m_mesh->setIndex(offsetI + 4, offsetV + 1);
m_mesh->setIndex(offsetI + 5, offsetV + 3);
offsetV += 4;
offsetI += 6;
}
m_mesh->addSection(startIndex, 8, 0, PrimitiveTopology::TriangleList);
}
}
//m_meshList = makeObject<InstancedMeshList>(m_mesh, 0);
//m_meshList->setTransform(Matrix::makeTranslation(-5, 0, 0));
//m_meshList->drawMesh();
//m_meshList->setTransform(Matrix::makeTranslation(-1, 0, 0));
//m_meshList->drawMesh();
for (int i = 0; i < m_meshList.size(); i++) {
m_meshList[i] = makeObject<InstancedMeshList>(m_mesh, i);
}
}
void MeshAutoVoxelset::buildFloor()
{
auto* tex = m_material->mainTexture();
//detail::MeshAutoTilesetUVMapper uvMapper(
// Size(tex->width(), tex->height()), Rect(0, 0, tex->width(), tex->height()), detail::MeshAutoTilesetUVMapper::Format::MVFloor);
detail::MeshAutoTilesetUVMapper uvMapper(Size(tex->width(), tex->height()), Rect(0, 0, 64, 96), detail::MeshAutoTilesetUVMapper::Format::MVFloor);
m_frameUVOffset.x = 64.0f / tex->width();
m_frameUVOffset.y = 0;
m_animationFrameCount = 3;
m_mesh = makeObject<MeshPrimitive>((4 * 4 * 48) * 1, (6 * 4 * 48) * 1);
int offsetV = 0;
int offsetI = 0;
for (int i = 0; i < 48; i++) {
const auto& info = MeshVoxelset::AutoTileTable[i];
int startIndex = offsetI;
// [top-left], [top-right], [bottom-left], [bottom-light]
Vector3 pysOffsets[4] = { { 0.0, +1.0, +1.0 }, { +0.5, +1.0, +1.0 }, { 0.0, +1.0, +0.5 }, { +0.5, +1.0, +0.5 } };
for (int iCorner = 0; iCorner < 4; iCorner++) {
auto uvRect = uvMapper.getUVRectFromLocalId(MeshTileFaceDirection::YPlus, i, static_cast<detail::SubtileCorner>(iCorner));
auto p1 = pysOffsets[iCorner] + Vector3(0, 0, 0);
auto p2 = pysOffsets[iCorner] + Vector3(0.5, 0, 0);
auto p3 = pysOffsets[iCorner] + Vector3(0, 0, -0.5);
auto p4 = pysOffsets[iCorner] + Vector3(0.5, 0, -0.5);
m_mesh->setVertex(offsetV + 0, Vertex{ p1, Vector3::UnitZ, uvRect.getTopLeft(), Color::White });
m_mesh->setVertex(offsetV + 1, Vertex{ p2, Vector3::UnitZ, uvRect.getTopRight(), Color::White });
m_mesh->setVertex(offsetV + 2, Vertex{ p3, Vector3::UnitZ, uvRect.getBottomLeft(), Color::White });
m_mesh->setVertex(offsetV + 3, Vertex{ p4, Vector3::UnitZ, uvRect.getBottomRight(), Color::White });
m_mesh->setIndex(offsetI + 0, offsetV + 0);
m_mesh->setIndex(offsetI + 1, offsetV + 1);
m_mesh->setIndex(offsetI + 2, offsetV + 2);
m_mesh->setIndex(offsetI + 3, offsetV + 2);
m_mesh->setIndex(offsetI + 4, offsetV + 1);
m_mesh->setIndex(offsetI + 5, offsetV + 3);
offsetV += 4;
offsetI += 6;
}
m_mesh->addSection(startIndex, 8, 0, PrimitiveTopology::TriangleList);
setInstancedMeshList((int)MeshTileFaceDirection::YPlus, i, false, makeObject<InstancedMeshList>(m_mesh, i));
}
}
void MeshAutoVoxelset::buildFloorAndSlopeWall()
{
beveled[(int)MeshTileFaceDirection::XMinus] = true;
beveled[(int)MeshTileFaceDirection::XPlus] = true;
beveled[(int)MeshTileFaceDirection::ZMinus] = true;
beveled[(int)MeshTileFaceDirection::ZPlus] = true;
auto* tex = m_material->mainTexture();
detail::MeshAutoTilesetUVMapper uvMapper(
Size(tex->width(), tex->height()), Rect(0, 0, tex->width(), tex->height()), detail::MeshAutoTilesetUVMapper::Format::MVWithWall);
float m = 0.2;
float mh = m / 2;
//float mag = 0.1;
detail::VoxelmapMeshBuilder builder;
MeshTileFaceDirection sideDirs[4] = {
MeshTileFaceDirection::XMinus,
MeshTileFaceDirection::XPlus,
MeshTileFaceDirection::ZMinus,
MeshTileFaceDirection::ZPlus };
// Convex
for (int iFaceDir = 0; iFaceDir < 4; iFaceDir++) {
MeshTileFaceDirection dir = sideDirs[iFaceDir];
for (int i = 0; i < 48; i++) {
builder.beginSection(dir, i, detail::VoxelMeshFaceKind::Convex);
const auto& info = MeshVoxelset::AutoTileTable[i];
// [top-left]
{
builder.beginSubtile();
int t = info.subtiles[0];
if (t == 1 || t == 2)
builder.putSquare({ -0.5f, 0.5f, mh }, { 0.0f, 0.5f, mh }, { -0.5f, 0.0f, mh }, { 0.0f, 0.0f, mh });
else if (t == 3)
builder.putSquare({ -0.5f, 0.5f, m }, { 0.0f, 0.5f, m }, { -0.5f, 0.0f, mh }, { 0.0f, 0.0f, mh });
else if (t == 4)
builder.putSquare({ -0.5f + mh, 0.5f, mh }, { 0.0f + mh, 0.5f, mh }, { -0.5f + mh, 0.0f, m }, { 0.0f + mh, 0.0f, mh });
else if (t == 5)
builder.putSquare({ -0.5f + m, 0.5f, m }, { 0.0f, 0.5, m }, { -0.5f + mh, 0.0f, mh }, { 0.0f, 0.0f, mh });
builder.projectUV(uvMapper.getUVRectFromLocalId(dir, i, detail::SubtileCorner::SubtileCorner_TopLeft));
builder.endSubtile();
}
// [top-right]
{
builder.beginSubtile();
int t = info.subtiles[1];
if (t == 1 || t == 2)
builder.putSquare({ 0.0f, 0.5f, mh }, { 0.5f, 0.5f, mh }, { 0.0f, 0.0f, mh }, { 0.5f, 0.0f, mh });
else if (t == 3)
builder.putSquare({ 0.0f, 0.5f, m }, { 0.5f, 0.5f, m }, { 0.0f, 0.0f, mh }, { 0.5f, 0.0f, mh });
else if (t == 4)
builder.putSquare({ 0.0f + mh, 0.5f, mh }, { 0.5f + mh, 0.5f, mh }, { 0.0f + mh, 0.0f, mh }, { 0.5f + mh, 0.0f, mh });
else if (t == 5)
builder.putSquare({ 0.0f, 0.5f, m }, { 0.5f - m, 0.5f, m }, { 0.0, 0.0, mh }, { 0.5f - mh, 0.0f, mh });
builder.projectUV(uvMapper.getUVRectFromLocalId(dir, i, detail::SubtileCorner::SubtileCorner_TopRight));
builder.endSubtile();
}
// [bmotto-left]
{
builder.beginSubtile();
int t = info.subtiles[detail::SubtileCorner_BottomLeft];
//if (t == 1 || t == 2)
// builder.putSquare({ -0.5f, 0.0f, mh }, { 0.0f, 0.0f, mh }, { -0.5f, -0.5f, mh }, { 0.0f, -0.5f, mh });
//else
if (t == 3)
builder.putSquare({ -0.5f, 0.0f, mh }, { 0.0f, 0.0f, mh }, { -0.5f, -0.5f, 0.0f }, { 0.0f, -0.5f, 0.0f });
//else if (t == 4)
// builder.putSquare({ -0.5f + mh, 0.0f, mh }, { 0.0f, 0.0f, mh }, { -0.5f + mh, -0.5f, mh }, { 0.0f, -0.5f, mh });
else if (t == 5)
builder.putSquare({ -0.5f + mh, 0.0f, mh }, { 0.0f, 0.0f, mh }, { -0.5f, -0.5f, 0.0f }, { 0.0f, -0.5f, 0.0f });
builder.projectUV(uvMapper.getUVRectFromLocalId(dir, i, detail::SubtileCorner_BottomLeft));
builder.endSubtile();
}
// [bmotto-right]
{
builder.beginSubtile();
int t = info.subtiles[detail::SubtileCorner_BottomRight];
//if (t == 1 || t == 2)
// builder.putSquare({ 0.0f, 0.0f, mh }, { 0.5f, 0.0f, mh }, { 0.0f, -0.5f, mh }, { 0.5f, -0.5f, mh });
//else
if (t == 3)
builder.putSquare({ 0.0f, 0.0f, mh }, { 0.5f, 0.0f, mh }, { 0.0f, -0.5f, 0.0f }, { 0.5f, -0.5f, 0.0f });
//else if (t == 4)
// builder.putSquare({ -0.5f + mh, 0.0f, mh }, { 0.0f, 0.0f, mh }, { -0.5f + mh, -0.5f, mh }, { 0.0f, -0.5f, mh });
else if (t == 5)
builder.putSquare({ 0.0f, 0.0f, mh }, { 0.5f - mh, 0.0f, mh }, { 0.0f, -0.5f, 0.0f }, { 0.5f, -0.5f, 0.0f });
builder.projectUV(uvMapper.getUVRectFromLocalId(dir, i, detail::SubtileCorner_BottomRight));
builder.endSubtile();
}
builder.endSection();
}
}
for (int iFaceDir = 0; iFaceDir < 4; iFaceDir++) {
MeshTileFaceDirection dir = sideDirs[iFaceDir];
for (int i = 0; i < 48; i++) {
builder.beginSection(dir, i, detail::VoxelMeshFaceKind::Concave);
const auto& info = MeshVoxelset::PiledAutoTileTable[i];
// [top-left]
{
builder.beginSubtile();
int t = info.subtiles[0];
if (t == 1) { // No draw.
}
else if (t == 2) {
}
else if (t == 3) {
builder.putSquare(
Vector3(-0.5, 0.5, m), Vector2(0.0, 0.0),
Vector3(-0.5 + m, 0.5, m), Vector2(m, 0.0),
Vector3(-0.5, 0.0, mh), Vector2(0.0, 1.0),
Vector3(-0.5 + mh, 0.0, mh), Vector2(mh, 1.0));
}
else if (t == 4) {
}
else if (t == 5) {
}
builder.projectUV(uvMapper.getUVRectFromLocalId(dir, i, detail::SubtileCorner::SubtileCorner_TopLeft, true));
builder.endSubtile();
}
// [top-right]
{
builder.beginSubtile();
int t = info.subtiles[1];
if (t == 1) { // No draw.
}
else if (t == 2) { // No draw.
}
else if (t == 3) {
builder.putSquare(
Vector3(0.5 - m, 0.5, m), Vector2(0, 0.0),
Vector3(0.5, 0.5, m), Vector2(1.0, 0.0),
Vector3(0.5 - mh, 0.0, mh), Vector2(0, 1.0),
Vector3(0.5, 0.0, mh), Vector2(1.0, 1.0));
}
else if (t == 4) {
}
else if (t == 5) { // No draw.
}
builder.projectUV(uvMapper.getUVRectFromLocalId(dir, i, detail::SubtileCorner::SubtileCorner_TopRight, true));
builder.endSubtile();
}
// [bmotto-left]
{
builder.beginSubtile();
int t = info.subtiles[detail::SubtileCorner_BottomLeft];
if (t == 3)
builder.putSquare(
{ -0.5f, 0.0f, mh }, { 0.0f, 0.0f },
{ -0.5f + mh, 0.0f, mh }, { 0.0f + mh, 0.0f },
{ -0.5f, -0.5f, 0.0f }, { 0.0f, 1.0f },
{ -0.5f, -0.5f, 0.0f }, { 0.0f, 1.0f });
//else if (t == 4)
//else if (t == 5)
builder.projectUV(uvMapper.getUVRectFromLocalId(dir, i, detail::SubtileCorner_BottomLeft, true));
builder.endSubtile();
}
// [bmotto-right]
{
builder.beginSubtile();
int t = info.subtiles[detail::SubtileCorner_BottomRight];
//if (t == 3) {
// builder.putSquare(
// Vector3(0.5 - m, 10.5 -0.5, m), Vector2(0, 0.0),
// Vector3(0.5, 0.5 - 0.5, m), Vector2(1.0, 0.0),
// Vector3(0.5 - mh, 0.0 - 0.5, mh), Vector2(0, 1.0),
// Vector3(0.5, 0.0 - 0.5, mh), Vector2(1.0, 1.0));
//}
//if (t == 1 || t == 2)
//else
if (t == 3)
builder.putSquare(
{ 0.5f - mh, 0.0f, mh }, { 1.0f - mh, 0.0f },
{ 0.5f, 0.0f, mh }, { 1.0f, 0.0f },
{ 0.5f, -0.5f, 0.0f }, { 1.0f, 1.0f },
{ 0.5f, -0.5f, 0.0f }, { 1.0f, 1.0f });
//else if (t == 4)
//else if (t == 5)
builder.projectUV(uvMapper.getUVRectFromLocalId(dir, i, detail::SubtileCorner_BottomRight, true));
builder.endSubtile();
}
builder.endSection();
}
}
//builder.putSquare({ }, { }, { }, { });
// 天板
{
MeshTileFaceDirection dir = MeshTileFaceDirection::YPlus;
for (int i = 0; i < 48; i++) {
builder.beginSection(dir, i, detail::VoxelMeshFaceKind::Convex);
const auto& info = MeshVoxelset::AutoTileTable[i];
// [top-left]
{
builder.beginSubtile();
int t = info.subtiles[0];
if (t == 1) {
builder.putSquare({ -0.5f, 0.5f, 0.0f }, { 0.0f, 0.5f, 0.0f }, { -0.5f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f });
}
else if (t == 2) {
builder.putSquareChamfer(-0.5f, 0.5, 0.0, 0.0, detail::SubtileCorner_TopLeft, m);
}
else if (t == 3) {
builder.putSquare({ -0.5f, 0.5f - m, 0.0f }, { 0.0f, 0.5f - m, 0.0f }, { -0.5f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f });
}
else if (t == 4) {
builder.putSquare({ -0.5f + m, 0.5f, 0.0f }, { 0.0f, 0.5f, 0.0f }, { -0.5f + m, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f });
}
else if (t == 5) {
builder.putSquare({ -0.5f + m, 0.5f - m, 0.0f }, { 0.0f, 0.5f - m, 0.0f }, { -0.5f + m, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f });
}
builder.projectUV(uvMapper.getUVRectFromLocalId(dir, i, detail::SubtileCorner::SubtileCorner_TopLeft));
builder.endSubtile();
}
// [top-right]
{
builder.beginSubtile();
int t = info.subtiles[1];
if (t == 1) {
builder.putSquare({ 0.0f, 0.5f, 0.0f }, { 0.5f, 0.5f, 0.0f }, { 0.0f, 0.0f, 0.0f }, { 0.5f, 0.0f, 0.0f });
}
else if (t == 2) {
builder.putSquareChamfer(0, 0.5, 0.5, 0.0, detail::SubtileCorner_TopRight, m);
}
else if (t == 3) {
builder.putSquare({ 0.0f, 0.5f - m, 0.0f }, { 0.5f, 0.5f - m, 0.0f }, { 0.0f, 0.0f, 0.0f }, { 0.5f, 0.0f, 0.0f });
}
else if (t == 4) {
builder.putSquare({ 0.0f, 0.5f, 0.0f }, { 0.5f - m, 0.5f, 0.0f }, { 0.0f, 0.0f, 0.0f }, { 0.5f - m, 0.0f, 0.0f });
}
else if (t == 5) {
builder.putSquare({ 0.0f, 0.5f - m, 0.0f }, { 0.5f - m, 0.5f - m, 0.0f }, { 0.0f, 0.0f, 0.0f }, { 0.5f - m, 0.0f, 0.0f });
}
builder.projectUV(uvMapper.getUVRectFromLocalId(dir, i, detail::SubtileCorner::SubtileCorner_TopRight));
builder.endSubtile();
}
// [bottom-left]
{
builder.beginSubtile();
int t = info.subtiles[2];
if (t == 1) {
builder.putSquare({ -0.5f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, { -0.5f, -0.5f, 0.0f }, { 0.0f, -0.5f, 0.0f });
}
else if (t == 2) {
builder.putSquareChamfer(-0.5, 0.0, 0.0, -0.5, detail::SubtileCorner_BottomLeft, m);
}
else if (t == 3) {
builder.putSquare({ -0.5f, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, { -0.5f, -0.5f + m, 0.0f }, { 0.0f, -0.5f + m, 0.0f });
}
else if (t == 4) {
builder.putSquare({ -0.5f + m, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, { -0.5f + m, -0.5f, 0.0f }, { 0.0f, -0.5f, 0.0f });
}
else if (t == 5) {
builder.putSquare({ -0.5f + m, 0.0f, 0.0f }, { 0.0f, 0.0f, 0.0f }, { -0.5f + m, -0.5f + m, 0.0f }, { 0.0f, -0.5f + m, 0.0f });
}
builder.projectUV(uvMapper.getUVRectFromLocalId(dir, i, detail::SubtileCorner::SubtileCorner_BottomLeft));
builder.endSubtile();
}
// [bottom-right]
{
builder.beginSubtile();
int t = info.subtiles[3];
if (t == 1) {
builder.putSquare({ 0.0f, 0.0f, 0.0f }, { 0.5f, 0.0f, 0.0f }, { 0.0f, -0.5f, 0.0f }, { 0.5f, -0.5f, 0.0f });
}
else if (t == 2) {
builder.putSquareChamfer(0.0, 0.0, 0.5, -0.5, detail::SubtileCorner_BottomRight, m);
}
else if (t == 3) {
builder.putSquare({ 0.0f, 0.0f, 0.0f }, { 0.5f, 0.0f, 0.0f }, { 0.0f, -0.5f + m, 0.0f }, { 0.5f, -0.5f + m, 0.0f });
}
else if (t == 4) {
builder.putSquare({ 0.0f, 0.0f, 0.0f }, { 0.5f - m, 0.0f, 0.0f }, { 0.0f, -0.5f, 0.0f }, { 0.5f - m, -0.5f, 0.0f });
}
else if (t == 5) {
builder.putSquare({ 0.0f, 0.0f, 0.0f}, { 0.5f - m, 0.0f, 0.0f }, { 0.0f, -0.5f + m, 0.0f }, { 0.5f - m, -0.5f + m, 0.0f });
}
builder.projectUV(uvMapper.getUVRectFromLocalId(dir, i, detail::SubtileCorner::SubtileCorner_BottomRight));
builder.endSubtile();
}
builder.endSection();
}
}
//builder.applyTileCenterMagnitude();
builder.build();
m_mesh = builder.mesh();
m_meshList = builder.convexMeshList();
m_dentMeshList = builder.concaveMeshList();
}
void MeshAutoVoxelset::resetBatch()
{
for (auto& batch : m_meshList) {
if (batch) {
batch->reset();
}
}
for (auto& batch : m_dentMeshList) {
if (batch) {
batch->reset();
}
}
}
void MeshAutoVoxelset::setInstancedMeshList(int d, int autotileId, bool dent, InstancedMeshList* value)
{
int index = (d * 48) + autotileId;
if (dent)
m_dentMeshList[index] = value;
else
m_meshList[index] = value;
}
InstancedMeshList* MeshAutoVoxelset::instancedMeshList(int d, int autotileId, bool dent) const
{
int index = (d * 48) + autotileId;
if (dent)
return m_dentMeshList[index];
else
return m_meshList[index];
}
void MeshAutoVoxelset::drawVoxel(const detail::MeshTile& tile, const detail::MeshTileFaceAdjacency& adjacency, const Matrix& transform, int animationFrame) const
{
Vector4 uvOffset;
if (m_animationFrameCount > 0) {
uvOffset = Vector4(m_frameUVOffset * (animationFrame % m_animationFrameCount), 0, 0);
}
for (int d = 0; d < 6; d++) {
//int t1 = (tile.faceTileId[d] & 0x0F);
//int t2 = (tile.faceTileId[d] & 0xF0) >> 4;
//if (tile.faceTileId[d] >= MeshVoxelset::PiledAutoBlockOffset) {
// int lid = tile.faceTileId[d] - MeshVoxelset::PiledAutoBlockOffset;
//if (t2 > 0) {
// int t = AutBlockPairMap[t1][t2];
// auto* batch = instancedMeshList(d, t, true);
// if (batch) {
// batch->setTransform(transform);
// batch->setUVOffset(uvOffset);
// batch->drawMesh();
// }
//}
//else
if (tile.faceTileId[d] >= MeshVoxelset::PiledAutoBlockOffset) {
int lid = tile.faceTileId[d] - MeshVoxelset::PiledAutoBlockOffset;
if (lid > 0) { // [0] は {1,1,1,1} で一切描画しないので処理不要
auto* batch = instancedMeshList(d, lid, true);
if (batch) {
batch->setTransform(transform);
batch->setUVOffset(uvOffset);
batch->drawMesh();
}
}
}
else
{
auto* batch = instancedMeshList(d, tile.faceTileId[d], false);
if (batch) {
batch->setTransform(transform);
batch->setUVOffset(uvOffset);
batch->drawMesh();
}
}
//if (adjacency.state[d] == detail::MeshTileFaceAdjacency::OPEN) {
//}
//else if (adjacency.state[d] == detail::MeshTileFaceAdjacency::CONNECTED) {
//}
}
}
void MeshAutoVoxelset::flushBatch(RenderingContext* context)
{
context->setMaterial(m_material);
for (auto& batch : m_meshList) {
if (batch) {
context->drawMeshInstanced(batch);
}
}
for (auto& batch : m_dentMeshList) {
if (batch) {
context->drawMeshInstanced(batch);
}
}
}
//==============================================================================
// MeshVoxelset
LN_OBJECT_IMPLEMENT(MeshVoxelset, Object) {}
const MeshVoxelset::AutoTileInfo MeshVoxelset::AutoTileTable[48] =
{
// Block tiles.
/*[0]*/ {1,1,1,1},{2,1,1,1},{3,3,1,1},{1,2,1,1}, {2,2,1,1},{4,1,4,1},{5,3,4,1},{4,2,4,1},
/*[8]*/ {1,4,1,4},{2,4,1,4},{3,5,1,4},{4,4,4,4}, {5,5,4,4},{1,1,2,1},{2,1,2,1},{3,3,2,1},
/*[16]*/ {1,2,2,1},{2,2,2,1},{4,3,4,1},{1,4,2,4}, {2,4,2,4},{3,5,2,4},{1,1,3,3},{2,1,3,3},
/*[24]*/ {3,3,3,3},{1,2,3,3},{2,2,3,3},{4,1,5,3}, {5,3,5,3},{4,2,5,3},{1,4,3,5},{2,4,3,5},
/*[32]*/ {3,5,3,5},{4,4,5,5},{5,5,5,5},{1,1,1,2}, {2,1,1,2},{3,3,1,2},{1,2,1,2},{2,2,1,2},
/*[40]*/ {4,1,4,2},{5,3,4,2},{4,2,4,2},{1,1,2,2}, {2,1,2,2},{3,3,2,2},{1,2,2,2},{2,2,2,2},
};
const MeshVoxelset::AutoTileInfo MeshVoxelset::PiledAutoTileTable[48] =
{
// Block tiles.
{ 1, 1, 1, 1 },{ 4, 4, 1, 1 },{ 3, 1, 3, 1 },{ 5, 4, 3, 1 }, { 2, 1, 1, 1 },{ 1, 3, 1, 3 },{ 4, 5, 1, 3 },{ 1, 2, 1, 1 },
{ 3, 3, 3, 3 },{ 5, 5, 3, 3 },{ 2, 3, 1, 3 },{ 3, 2, 3, 1 }, { 2, 2, 1, 1 },{ 1, 1, 4, 4 },{ 4, 4, 4, 4 },{ 3, 1, 5, 4 },
{ 5, 4, 5, 4 },{ 2, 1, 4, 4 },{ 1, 3, 4, 5 },{ 4, 5, 4, 5 }, { 1, 2, 4, 4 },{ 3, 3, 5, 5 },{ 5, 5, 5, 5 },{ 2, 3, 4, 5 },
{ 3, 2, 5, 4 },{ 2, 2, 4, 4 },{ 1, 1, 2, 1 },{ 4, 4, 2, 1 }, { 2, 1, 2, 1 },{ 1, 3, 2, 3 },{ 4, 5, 2, 3 },{ 2, 3, 2, 3 },
{ 1, 2, 2, 1 },{ 2, 2, 2, 1 },{ 1, 1, 1, 2 },{ 4, 4, 1, 2 }, { 1, 2, 1, 2 },{ 3, 1, 3, 2 },{ 5, 4, 3, 2 },{ 2, 1, 1, 2 },
{ 3, 2, 3, 2 },{ 2, 2, 1, 2 },{ 1, 1, 2, 2 },{ 4, 4, 2, 2 }, { 2, 1, 2, 2 },{ 1, 2, 2, 2 },{ 2, 2, 2, 2 },{ 0, 0, 0, 0 },
///*[0]*/ {1,1,1,1},{2,1,1,1},{3,3,1,1},{1,2,1,1}, {2,2,1,1},{4,1,4,1},{5,3,4,1},{4,2,4,1},
///*[8]*/ {1,4,1,4},{2,4,1,4},{3,5,1,4},{4,4,4,4}, {5,5,4,4},{1,1,2,1},{2,1,2,1},{3,3,2,1},
///*[16]*/ {1,2,2,1},{2,2,2,1},{4,3,4,1},{1,4,2,4}, {2,4,2,4},{3,5,2,4},{1,1,3,3},{2,1,3,3},
///*[24]*/ {3,3,3,3},{1,2,3,3},{2,2,3,3},{4,1,5,3}, {5,3,5,3},{4,2,5,3},{1,4,3,5},{2,4,3,5},
///*[32]*/ {3,5,3,5},{4,4,5,5},{5,5,5,5},{1,1,1,2}, {2,1,1,2},{3,3,1,2},{1,2,1,2},{2,2,1,2},
///*[40]*/ {4,1,4,2},{5,3,4,2},{4,2,4,2},{1,1,2,2}, {2,1,2,2},{3,3,2,2},{1,2,2,2},{2,2,2,2},
};
// SubTileId([0] is invalid) => PhysicalTileIndex
static int g_AutoTileSourcePosTable_TkoolXP[4][6] = // TkoolXP and Wolf
{
// [top-left]
{ -1, 26, 4, 14, 24, 12 },
// [top-right]
{ -1, 27, 5, 15, 29, 17 },
// [bottom-left]
{ -1, 32, 10, 44, 30, 42 },
// [bottom-light]
{ -1, 33, 11, 45, 35, 47 },
};
MeshVoxelset::MeshVoxelset()
{
}
void MeshVoxelset::init()
{
Object::init();
//{
// simpleboolean::Mesh mesh1;
// simpleboolean::Mesh mesh2;
// simpleboolean::loadTriangulatedObj(mesh1, firstObj);
// simpleboolean::loadTriangulatedObj(mesh2, secondObj);
// simpleboolean::MeshOperator combiner;
// combiner.setMeshes(mesh1, mesh2);
// if (!combiner.combine())
// return 1;
// //if (nullptr != outputObj) {
// simpleboolean::Mesh unionMesh;
// combiner.getResult(simpleboolean::Type::Union, &unionMesh);
// //}
//}
auto tex = Texture2D::load(u"autotile4");
m_material = Material::create(tex);
m_material->setShadingModel(ShadingModel::Unlit);
m_material->setShader(Shader::create(u"C:/Proj/LN/Lumino/src/LuminoEngine/src/Rendering/Resource/Sprite.fx"));
//m_autotileSet[0] = makeObject<MeshAutoVoxelset>();
//m_autotileSet[0]->setMaterial(m_material);
//m_autotileSet[0]->buildQubeFloorAndWall();
{
auto tex = Texture2D::load(u"D:/Materials/Tilemap/ねくらファンタジーマップチップ素材集/マップ素材/オートタイル規格2/b_06海岸_at01.png");
auto material = Material::create(tex);
material->setShadingModel(ShadingModel::Unlit);
material->setShader(Shader::create(u"C:/Proj/LN/Lumino/src/LuminoEngine/src/Rendering/Resource/Sprite.fx"));
m_autotileSet[1] = makeObject<MeshAutoVoxelset>();
m_autotileSet[1]->setMaterial(material);
m_autotileSet[1]->buildFloor();
}
//
//{
// auto tex = Texture2D::load(u"D:/Materials/Tilemap/ねくらファンタジーマップチップ素材集/マップ素材/オートタイル規格2/b_06海岸_at02.png");
// auto material = Material::create(tex);
// material->shadingModel = ShadingModel::Unlit;
// material->setShader(Shader::create(u"C:/Proj/LN/Lumino/src/LuminoEngine/src/Rendering/Resource/Sprite.fx"));
// m_autotileSet[2] = makeObject<MeshAutoVoxelset>();
// m_autotileSet[2]->setMaterial(material);
// m_autotileSet[2]->buildFloor();
//}
{
m_autotileSet[3] = makeObject<MeshAutoVoxelset>();
m_autotileSet[3]->setMaterial(m_material);
m_autotileSet[3]->buildFloorAndSlopeWall();
}
}
void MeshVoxelset::beginBatch()
{
for (auto& autotileset : m_autotileSet) {
if (autotileset) {
autotileset->resetBatch();
}
}
}
void MeshVoxelset::drawTile(RenderingContext* context, const detail::MeshTile& tile, const detail::MeshTileFaceAdjacency& adjacency, const Matrix& transform, int animationFrame) const
{
//context->setMaterial(m_material);
int autotileKind = autoTileKindId(tile.tileId);
if (autotileKind >= 0) {
m_autotileSet[autotileKind]->drawVoxel(tile, adjacency, transform, animationFrame);
}
//context->drawMeshInstanced(m_meshList);
}
void MeshVoxelset::drawBatch(RenderingContext* context)
{
for (auto& autotileset : m_autotileSet) {
if (autotileset) {
autotileset->flushBatch(context);
}
}
}
namespace detail {
// SubTileId([0] is invalid) => PhysicalTileIndex
static int g_AutoTileSourcePosTable_MVFloor[4][6] =
{
// [top-left]
{ -1, 13, 2, 10, 16, 8 },
// [top-right]
{ -1, 14, 3, 9, 19, 11 },
// [bottom-left]
{ -1, 17, 6, 22, 12, 20 },
// [bottom-light]
{ -1, 18, 7, 21, 15, 23 },
};
static int g_AutoTileSourcePosTable_MVWall[4][6] =
{
// [top-left]
{ -1, 13 + 16, 24, 9 + 16, 12 + 16, 24 },
// [top-right]
{ -1, 14 + 16, 27 , 10 + 16, 15 + 16, 11 + 16 },
// [bottom-left]
{ -1, 17 + 16, 36, 21 + 16, 16 + 16, 20 + 16 },
// [bottom-light]
{ -1, 18 + 16, 39, 22 + 16, 19 + 16, 23 + 16 },
};
MeshAutoTilesetUVMapper::MeshAutoTilesetUVMapper(const Size& textureSize, const Rect& sourceRect, Format format)
: m_format(format)
{
m_globalUVOffset.x = sourceRect.x / textureSize.width;
m_globalUVOffset.y = sourceRect.y / textureSize.height;
if (m_format == Format::XP) {
m_subtileUVSize.x = (sourceRect.width / 6) / textureSize.width;
m_subtileUVSize.y = (sourceRect.height / 8) / textureSize.height;
}
else if (m_format == Format::MVWithWall) {
m_subtileUVSize.x = (sourceRect.width / 4) / textureSize.width;
m_subtileUVSize.y = (sourceRect.height / 10) / textureSize.height;
}
else if (m_format == Format::MVFloor) {
m_subtileUVSize.x = (sourceRect.width / 4) / textureSize.width;
m_subtileUVSize.y = (sourceRect.height / 6) / textureSize.height;
}
else {
LN_UNREACHABLE();
}
}
Rect MeshAutoTilesetUVMapper::getUVRectFromLocalId(MeshTileFaceDirection direction, int autotileLocalId, SubtileCorner corner, bool beveled) const
{
const MeshVoxelset::AutoTileInfo* info = (beveled) ? &MeshVoxelset::PiledAutoTileTable[autotileLocalId] : &MeshVoxelset::AutoTileTable[autotileLocalId];
if (m_format == Format::XP) {
int index_tl = g_AutoTileSourcePosTable_TkoolXP[corner][info->subtiles[corner]];
auto offset = Vector2(m_subtileUVSize.x * (index_tl % 6), m_subtileUVSize.y * (index_tl / 6));
return Rect(offset.x, offset.y, m_subtileUVSize.x, m_subtileUVSize.y);
}
else if (m_format == Format::MVWithWall) {
if (direction == MeshTileFaceDirection::YPlus || direction == MeshTileFaceDirection::YMinus) {
int index_tl = g_AutoTileSourcePosTable_MVFloor[corner][info->subtiles[corner]];
auto offset = Vector2(m_subtileUVSize.x * (index_tl % 4), m_subtileUVSize.y * (index_tl / 4));
return Rect(offset.x, offset.y, m_subtileUVSize.x, m_subtileUVSize.y);
}
else {
int index_tl = g_AutoTileSourcePosTable_MVWall[corner][info->subtiles[corner]];
auto offset = Vector2(m_subtileUVSize.x * (index_tl % 4), m_subtileUVSize.y * (index_tl / 4));
return Rect(offset.x, offset.y, m_subtileUVSize.x, m_subtileUVSize.y);
}
}
else if (m_format == Format::MVFloor) {
int index_tl = g_AutoTileSourcePosTable_MVFloor[corner][info->subtiles[corner]];
auto offset = Vector2(m_subtileUVSize.x * (index_tl % 4), m_subtileUVSize.y * (index_tl / 4));
return Rect(offset.x, offset.y, m_subtileUVSize.x, m_subtileUVSize.y);
}
else {
LN_UNREACHABLE();
return Rect();
}
}
} // namespace detail
} // namespace ln | 36.25599 | 183 | 0.597127 | infinnie |
73c3942edc74b19f04454276b6220f023326ba9e | 27,417 | cpp | C++ | src/share.cpp | voidluffy/ipmsg342r2src | 2134d79fca21f0d434a8561fed873c9a3753339e | [
"X11",
"Unlicense"
] | 20 | 2017-08-24T01:44:13.000Z | 2022-02-18T16:05:40.000Z | src/share.cpp | voidluffy/ipmsg342r2src | 2134d79fca21f0d434a8561fed873c9a3753339e | [
"X11",
"Unlicense"
] | null | null | null | src/share.cpp | voidluffy/ipmsg342r2src | 2134d79fca21f0d434a8561fed873c9a3753339e | [
"X11",
"Unlicense"
] | 29 | 2017-08-24T01:44:14.000Z | 2022-02-06T11:57:37.000Z | static char *share_id =
"@(#)Copyright (C) H.Shirouzu 2002-2012 share.cpp Ver3.40";
/* ========================================================================
Project Name : IP Messenger for Win32
Module Name : File Share
Create : 2002-04-14(Sun)
Update : 2012-04-02(Mon)
Copyright : H.Shirouzu
Reference :
======================================================================== */
#include "resource.h"
#include "ipmsg.h"
#include <stddef.h>
#define BIG_ALLOC 100
/*
公開ファイル管理
*/
ShareMng::ShareMng(Cfg *_cfg)
{
top = (ShareInfo *)&_top; // 番兵
top->prior = top->next = top;
cfg = _cfg;
statDlg = NULL;
}
ShareInfo *ShareMng::CreateShare(int packetNo)
{
if (Search(packetNo))
return FALSE;
ShareInfo *info = new ShareInfo(packetNo);
info->LinkList(top);
return info;
}
BOOL ShareMng::AddShareCore(ShareInfo *shareInfo, FileInfo *fileInfo)
{
if (!fileInfo) return FALSE;
if ((shareInfo->fileCnt % BIG_ALLOC) == 0)
shareInfo->fileInfo = (FileInfo **)realloc(shareInfo->fileInfo, (shareInfo->fileCnt + BIG_ALLOC) * sizeof(FileInfo *));
shareInfo->fileInfo[shareInfo->fileCnt] = fileInfo;
shareInfo->fileCnt++;
return TRUE;
}
BOOL ShareMng::AddFileShare(ShareInfo *shareInfo, char *fname)
{
for (int i=0; i < shareInfo->fileCnt; i++) {
if (strcmp(fname, shareInfo->fileInfo[i]->Fname()) == 0)
return FALSE;
}
return AddShareCore(shareInfo, SetFileInfo(fname));
}
BOOL ShareMng::AddMemShare(ShareInfo *shareInfo, char *dummy_name, BYTE *data, int size, int pos)
{
FileInfo *info = new FileInfo;
if (!info) return FALSE;
info->SetAttr(IPMSG_FILE_CLIPBOARD);
info->SetFname(dummy_name);
info->SetMemData(data, size);
info->SetMtime(Time());
info->SetPos(pos);
return AddShareCore(shareInfo, info);
}
BOOL ShareMng::DelFileShare(ShareInfo *info, int fileNo)
{
if (fileNo >= info->fileCnt)
return FALSE;
memmove(info->fileInfo + fileNo, info->fileInfo + fileNo +1, (--info->fileCnt - fileNo) * sizeof(FileInfo *));
statDlg->Refresh();
return TRUE;
}
FileInfo *ShareMng::SetFileInfo(char *fname)
{
WIN32_FIND_DATA_U8 fdat;
if (!GetFileInfomationU8(fname, &fdat)) return FALSE;
FileInfo *info = new FileInfo;
UINT attr = (fdat.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? IPMSG_FILE_DIR : IPMSG_FILE_REGULAR;
attr |= (fdat.dwFileAttributes & FILE_ATTRIBUTE_READONLY) ? IPMSG_FILE_RONLYOPT : 0;
attr |= (fdat.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) ? IPMSG_FILE_SYSTEMOPT : 0;
info->SetAttr(attr);
info->SetFname(fname);
if (GET_MODE(info->Attr()) == IPMSG_FILE_DIR)
{
info->SetSize(0);
strncpyz(cfg->lastOpenDir, fname, MAX_PATH_U8);
}
else {
info->SetSize((_int64)fdat.nFileSizeHigh << 32 | fdat.nFileSizeLow);
PathToDir(fname, cfg->lastOpenDir);
}
info->SetMtime(FileTime2UnixTime(&fdat.ftLastWriteTime));
info->SetCrtime(FileTime2UnixTime(&fdat.ftCreationTime));
info->SetAtime(FileTime2UnixTime(&fdat.ftLastAccessTime));
return info;
}
BOOL ShareMng::AddHostShare(ShareInfo *info, SendEntry *entry, int entryNum)
{
info->host = new Host *[info->hostCnt = entryNum];
info->transStat = new char [info->hostCnt * info->fileCnt];
memset(info->transStat, TRANS_INIT, info->hostCnt * info->fileCnt);
for (int i=0; i < entryNum; i++)
{
info->host[i] = (Host *)cfg->fileHosts.GetHostByNameAddr(&entry[i].Host()->hostSub);
if (info->host[i] == NULL)
{
info->host[i] = new Host;
info->host[i]->hostSub = entry[i].Host()->hostSub;
info->host[i]->hostStatus = entry[i].Host()->hostStatus;
info->host[i]->updateTime = entry[i].Host()->updateTime;
info->host[i]->priority = entry[i].Host()->priority;
strncpyz(info->host[i]->nickName, entry[i].Host()->nickName, MAX_NAMEBUF);
cfg->fileHosts.AddHost(info->host[i]);
}
else info->host[i]->RefCnt(1);
}
SYSTEMTIME st;
::GetSystemTime(&st);
::SystemTimeToFileTime(&st, &info->attachTime);
statDlg->Refresh();
return TRUE;
}
int ShareMng::GetFileInfoNo(ShareInfo *info, FileInfo *fileInfo)
{
for (int target=0; info->fileCnt; target++)
if (info->fileInfo[target] == fileInfo)
return target;
return -1;
}
BOOL ShareMng::EndHostShare(int packetNo, HostSub *hostSub, FileInfo *fileInfo, BOOL done)
{
ShareInfo *info = Search(packetNo);
if (info == NULL)
return FALSE;
for (int i=0; i < info->hostCnt; i++)
{
if (IsSameHostEx(&info->host[i]->hostSub, hostSub))
{
if (fileInfo)
{
info->transStat[info->fileCnt * i + GetFileInfoNo(info, fileInfo)] = done ? TRANS_DONE : TRANS_INIT;
if (!done)
return statDlg->Refresh(), TRUE;
for (int j=0; j < info->fileCnt; j++)
if (info->transStat[info->fileCnt * i + j] != TRANS_DONE)
return statDlg->Refresh(), TRUE;
}
if (info->host[i]->RefCnt(-1) == 0)
{
cfg->fileHosts.DelHost(info->host[i]);
delete info->host[i];
}
memmove(info->host + i, info->host + i + 1, (--info->hostCnt - i) * sizeof(Host *));
memmove(info->transStat + info->fileCnt * i, info->transStat + info->fileCnt * (i + 1), (info->hostCnt - i) * info->fileCnt);
if (info->hostCnt == 0)
DestroyShare(info);
return statDlg->Refresh(), TRUE;
}
}
return FALSE;
}
void ShareMng::DestroyShare(ShareInfo *info)
{
info->next->prior = info->prior;
info->prior->next = info->next;
while (info->hostCnt-- > 0)
{
if (info->host[info->hostCnt]->RefCnt(-1) == 0)
{
cfg->fileHosts.DelHost(info->host[info->hostCnt]);
delete info->host[info->hostCnt];
}
}
delete [] info->host;
delete [] info->transStat;
while (info->fileCnt-- > 0)
delete info->fileInfo[info->fileCnt];
free(info->fileInfo);
statDlg->Refresh();
}
ShareInfo *ShareMng::Search(int packetNo)
{
for (ShareInfo *info=Top(); info; info=Next(info))
if (info->packetNo == packetNo)
return info;
return NULL;
}
BOOL ShareMng::GetShareCntInfo(ShareCntInfo *cntInfo, ShareInfo *shareInfo)
{
memset(cntInfo, 0, sizeof(ShareCntInfo));
for (ShareInfo *info = shareInfo ? shareInfo : Top(); info; info=Next(info))
{
if (info->hostCnt)
{
cntInfo->packetCnt++;
cntInfo->hostCnt += info->hostCnt;
int i;
for (i=info->fileCnt * info->hostCnt -1; i >= 0; i--)
{
cntInfo->fileCnt++;
switch (info->transStat[i]) {
case TRANS_INIT: break;
case TRANS_BUSY: cntInfo->transferCnt++; break;
case TRANS_DONE: cntInfo->doneCnt++; break;
}
}
for (i=0; i < info->fileCnt; i++)
{
if (GET_MODE(info->fileInfo[i]->Attr()) == IPMSG_FILE_DIR)
cntInfo->dirCnt++;
cntInfo->totalSize += info->fileInfo[i]->Size();
}
}
if (shareInfo)
return TRUE;
}
return TRUE;
}
BOOL ShareMng::GetAcceptableFileInfo(ConnectInfo *info, char *buf, AcceptFileInfo *fileInfo)
{
// 本当はこんなところでデコードせず、msgmng にやらせるべきだが...
char *tok, *p, *user_name, *host_name;
int targetID;
ShareInfo *shareInfo;
HostSub hostSub = { "", "", info->addr, info->port };
if ((tok = separate_token(buf, ':', &p)) == NULL || atoi(tok) != IPMSG_VERSION)
return FALSE;
if ((tok = separate_token(NULL, ':', &p)) == NULL) // packet no
return FALSE;
if ((user_name = separate_token(NULL, ':', &p)) == NULL)
return FALSE;
if ((host_name = separate_token(NULL, ':', &p)) == NULL)
return FALSE;
if ((tok = separate_token(NULL, ':', &p)) == NULL) // command
return FALSE;
fileInfo->command = atoi(tok);
if (fileInfo->command & IPMSG_UTF8OPT) {
strncpyz(hostSub.userName, user_name, MAX_NAMEBUF);
strncpyz(hostSub.hostName, host_name, MAX_NAMEBUF);
}
else {
strncpyz(hostSub.userName, AtoU8(user_name), MAX_NAMEBUF);
strncpyz(hostSub.hostName, AtoU8(host_name), MAX_NAMEBUF);
}
if ((tok = separate_token(NULL, ':', &p)) == NULL)
return FALSE;
fileInfo->packetNo = strtol(tok, 0, 16);
if ((tok = separate_token(NULL, ':', &p)) == NULL)
return FALSE;
targetID = strtol(tok, 0, 16);
if (GET_MODE(fileInfo->command) == IPMSG_GETFILEDATA)
{
if ((tok = separate_token(NULL, ':', &p)) == NULL)
return FALSE;
fileInfo->offset = hex2ll(tok);
}
else if (GET_MODE(fileInfo->command) == IPMSG_GETDIRFILES)
fileInfo->offset = 0;
else return FALSE;
if ((shareInfo = Search(fileInfo->packetNo)) == NULL)
return FALSE;
int host_cnt, file_cnt;
for (host_cnt=0; host_cnt < shareInfo->hostCnt; host_cnt++)
{
if (IsSameHostEx(&shareInfo->host[host_cnt]->hostSub, &hostSub))
{
fileInfo->host = shareInfo->host[host_cnt];
break;
}
}
if (host_cnt == shareInfo->hostCnt)
return FALSE;
for (file_cnt=0; file_cnt < shareInfo->fileCnt; file_cnt++)
{
if (shareInfo->fileInfo[file_cnt]->Id() == targetID)
{
fileInfo->fileInfo = shareInfo->fileInfo[file_cnt];
if (shareInfo->transStat[shareInfo->fileCnt * host_cnt + file_cnt] != TRANS_INIT)
return FALSE; // download 済み(or 最中)
if (GET_MODE(fileInfo->command) != IPMSG_GETDIRFILES && GET_MODE(fileInfo->fileInfo->Attr()) == IPMSG_FILE_DIR) // dir に対して IPMSG_GETDIRFILES 以外は認めない
return FALSE;
fileInfo->attachTime = shareInfo->attachTime;
shareInfo->transStat[shareInfo->fileCnt * host_cnt + file_cnt] = TRANS_BUSY;
statDlg->Refresh();
return TRUE;
}
}
return FALSE;
}
void ShareMng::Cleanup()
{
int i, j;
Time_t cur_time = Time();
ShareInfo *info, *next;
for (info=Top(); info; info=next) {
next = Next(info);
if (!*(_int64 *)&info->attachTime) continue;
int clip_host = 0;
for (i=0; i < info->fileCnt; i++) {
for (j=0; j < info->hostCnt; j++) {
if (info->transStat[info->fileCnt * j + i] == TRANS_BUSY) break;
if (info->transStat[info->fileCnt * j + i] == TRANS_INIT) {
if (GET_MODE(info->fileInfo[i]->Attr()) != IPMSG_FILE_CLIPBOARD) break;
if (info->host[j]->hostStatus & IPMSG_CLIPBOARDOPT) {
clip_host++;
}
}
}
if (j != info->hostCnt) break;
}
if (i == info->fileCnt && j == info->hostCnt) {
if (clip_host > 0 && FileTime2UnixTime(&info->attachTime) + 1200 > cur_time) continue;
DestroyShare(info);
}
}
}
/* ShareDlg */
TShareDlg::TShareDlg(ShareMng *_shareMng, ShareInfo *_shareInfo, Cfg *_cfg, TWin *_parent) : TDlg(FILE_DIALOG, _parent), shareListView(this)
{
shareMng = _shareMng;
shareInfo = _shareInfo;
cfg = _cfg;
}
TShareDlg::~TShareDlg()
{
shareListView.DeleteAllItems();
}
BOOL TShareDlg::EvCreate(LPARAM lParam)
{
shareListView.AttachWnd(GetDlgItem(FILE_LIST));
char *title[] = { GetLoadStrU8(IDS_FILENAME), GetLoadStrU8(IDS_SIZE), GetLoadStrU8(IDS_LOCATION), NULL };
int size[] = { 120, 70, 180 };
int fmt[] = { LVCFMT_LEFT, LVCFMT_RIGHT, LVCFMT_LEFT, LVCFMT_LEFT };
int i;
for (i=0; title[i]; i++) {
shareListView.InsertColumn(i, title[i], size[i], fmt[i]);
}
for (i=0; i < shareInfo->fileCnt; i++) {
AddList(i);
}
if (rect.left == CW_USEDEFAULT)
{
GetWindowRect(&rect);
int xsize = rect.right - rect.left, ysize = rect.bottom - rect.top;
int cx = ::GetSystemMetrics(SM_CXFULLSCREEN);
int cy = ::GetSystemMetrics(SM_CYFULLSCREEN);
int x = (cx - xsize)/2;
int y = (cy - ysize)/2;
MoveWindow((x < 0) ? 0 : x, (y < 0) ? 0 : y, xsize, ysize, FALSE);
}
else
MoveWindow(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, FALSE);
Show();
::SetFocus(shareListView.hWnd);
return TRUE;
}
BOOL TShareDlg::AddList(int idx)
{
char buf[MAX_BUF_EX];
ForcePathToFname(shareInfo->fileInfo[idx]->Fname(), buf);
shareListView.InsertItem(idx, buf);
if (GET_MODE(shareInfo->fileInfo[idx]->Attr()) == IPMSG_FILE_DIR)
strcpy(buf, "(DIR)");
else
MakeSizeString(buf, shareInfo->fileInfo[idx]->Size(), MSS_SPACE);
shareListView.SetSubItem(idx, 1, buf);
PathToDir(shareInfo->fileInfo[idx]->Fname(), buf);
shareListView.SetSubItem(idx, 2, buf);
return TRUE;
}
BOOL TShareDlg::DelList(int idx)
{
shareListView.DeleteItem(idx);
shareMng->DelFileShare(shareInfo, idx);
return TRUE;
}
BOOL TShareDlg::EvDropFiles(HDROP hDrop)
{
int lastFileCnt = shareInfo->fileCnt;
parent->EvDropFiles(hDrop);
while (lastFileCnt < shareInfo->fileCnt)
AddList(lastFileCnt++);
return TRUE;
}
BOOL TShareDlg::EvCommand(WORD wNotifyCode, WORD wID, LPARAM hWndCtl)
{
switch (wID)
{
case IDOK: EndDialog(TRUE); break;
case IDCANCEL: EndDialog(FALSE); break;
case FILE_BUTTON:
{
int i = shareInfo->fileCnt;
if (FileAddDlg(this, shareMng, shareInfo, cfg))
for (i; i < shareInfo->fileCnt; i++)
AddList(i);
}
break;
case FOLDER_BUTTON:
if (BrowseDirDlg(this, GetLoadStrU8(IDS_FOLDERATTACH), cfg->lastOpenDir, cfg->lastOpenDir))
{
if (shareMng->AddFileShare(shareInfo, cfg->lastOpenDir))
{
AddList(shareInfo->fileCnt -1);
cfg->WriteRegistry(CFG_GENERAL);
}
}
break;
case DEL_BUTTON:
{
for (int i=shareInfo->fileCnt-1; i >= 0; i--)
{
if (!shareListView.IsSelected(i)) continue;
DelList(i);
}
}
break;
default: break;
}
return TRUE;
}
BOOL TShareDlg::FileAddDlg(TDlg *dlg, ShareMng *shareMng, ShareInfo *shareInfo, Cfg *cfg)
{
int bufsize = MAX_MULTI_PATH;
U8str buf(bufsize);
U8str path(bufsize);
OpenFileDlg ofdlg(dlg, OpenFileDlg::MULTI_OPEN);
if (!ofdlg.Exec(buf.Buf(), bufsize, GetLoadStrU8(IDS_ADDFILE),
GetLoadStrAsFilterU8(IDS_OPENFILEALLFLTR), cfg->lastOpenDir)) {
return FALSE;
}
cfg->WriteRegistry(CFG_GENERAL);
int dirlen = (int)strlen(cfg->lastOpenDir);
if (buf[dirlen]) {
return shareMng->AddFileShare(shareInfo, buf.Buf());
}
for (const char *fname=buf+dirlen+1; *fname; fname += strlen(fname) +1)
{
if (MakePath(path.Buf(), buf, fname) >= MAX_PATH_U8)
continue;
shareMng->AddFileShare(shareInfo, path.Buf());
}
return TRUE;
}
/* TShareStatDlg */
TShareStatDlg::TShareStatDlg(ShareMng *_shareMng, Cfg *_cfg, TWin *_parent) : TDlg(SHARE_DIALOG, _parent), shareListView(this)
{
shareMng = _shareMng;
cfg = _cfg;
shareMng->RegisterShareStatDlg(this);
}
TShareStatDlg::~TShareStatDlg()
{
shareListView.DeleteAllItems();
}
BOOL TShareStatDlg::EvCreate(LPARAM lParam)
{
char *title[] = { "No", "Files", "Size", "All/done/trans", "Users", NULL };
int size[] = { 30, 110, 70, 100, 100 };
int fmt[] = { LVCFMT_RIGHT, LVCFMT_LEFT, LVCFMT_RIGHT, LVCFMT_RIGHT, LVCFMT_LEFT };
shareListView.AttachWnd(GetDlgItem(SHARE_LIST));
for (int i=0; title[i]; i++) {
shareListView.InsertColumn(i, title[i], size[i], fmt[i]);
}
SetAllList();
CheckDlgButton(MODIFY_CHECK, (cfg->fileTransOpt & FT_STRICTDATE) ? 1 : 0);
if (rect.left == CW_USEDEFAULT)
{
GetWindowRect(&rect);
int xsize = rect.right - rect.left, ysize = rect.bottom - rect.top;
int cx = ::GetSystemMetrics(SM_CXFULLSCREEN);
int cy = ::GetSystemMetrics(SM_CYFULLSCREEN);
int x = (cx - xsize)/2;
int y = (cy - ysize)/2;
MoveWindow((x < 0) ? 0 : x, (y < 0) ? 0 : y, xsize, ysize, FALSE);
}
else
MoveWindow(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, FALSE);
Show();
::SetFocus(shareListView.hWnd);
return TRUE;
}
BOOL TShareStatDlg::Refresh(void)
{
shareMng->Cleanup();
if (hWnd == NULL)
return FALSE;
SetAllList();
return TRUE;
}
BOOL TShareStatDlg::SetAllList(void)
{
shareListView.DeleteAllItems();
int i=0, j=0, len=0;
char buf[MAX_BUF_EX];
for (ShareInfo *info=shareMng->Top(); info; info=shareMng->Next(info))
{
if (info->hostCnt == 0)
continue;
sprintf(buf, "%d", i);
shareListView.InsertItem(i, buf);
len = 0;
*buf = 0;
for (j=0; j < info->fileCnt && len < sizeof(buf); j++) {
ForcePathToFname(info->fileInfo[j]->Fname(), buf + len);
strcat(buf + len, " ");
len += (int)strlen(buf + len);
if (len + MAX_PATH_U8 >= sizeof(buf)) break;
}
shareListView.SetSubItem(i, 1, buf);
ShareCntInfo cntInfo;
shareMng->GetShareCntInfo(&cntInfo, info);
MakeSizeString(buf, cntInfo.totalSize, MSS_SPACE);
if (cntInfo.dirCnt) wsprintf(buf + strlen(buf), "/%dDIR", cntInfo.dirCnt);
shareListView.SetSubItem(i, 2, buf);
shareMng->GetShareCntInfo(&cntInfo, info);
wsprintf(buf, "%d / %d/ %d", cntInfo.fileCnt, cntInfo.doneCnt, cntInfo.transferCnt);
shareListView.SetSubItem(i, 3, buf);
len = 0;
*buf = 0;
for (j=0; j < info->hostCnt && len + 30 < sizeof(buf); j++) {
Host *host = info->host[j];
len += _snprintf(buf + len, sizeof(buf)-len-1, "%.14s(%.10s) ",
*host->nickName ? host->nickName : host->hostSub.userName,
host->hostSub.hostName);
}
shareListView.SetSubItem(i, 4, buf);
i++;
}
return TRUE;
}
BOOL TShareStatDlg::DelList(int idx)
{
ShareInfo *info = (ShareInfo *)shareListView.GetItemParam(idx);
if (info == NULL)
return FALSE;
for (int i=info->fileCnt * info->hostCnt -1; i >= 0; i--) {
if (info->transStat[i] == ShareMng::TRANS_BUSY)
return FALSE;
}
shareMng->DestroyShare(info);
shareListView.DeleteItem(idx);
return TRUE;
}
BOOL TShareStatDlg::EvCommand(WORD wNotifyCode, WORD wID, LPARAM hWndCtl)
{
switch (wID)
{
case IDOK: EndDialog(TRUE); break;
case IDCANCEL: EndDialog(FALSE); break;
case DEL_BUTTON:
{
for (int i=shareListView.GetItemCount()-1; i >= 0; i--)
{
if (!shareListView.IsSelected(i)) continue;
DelList(i);
}
SetAllList();
}
break;
case MODIFY_CHECK:
cfg->fileTransOpt = SendDlgItemMessage(MODIFY_CHECK, BM_GETCHECK, 0, 0) ? FT_STRICTDATE : 0;
cfg->WriteRegistry(CFG_GENERAL);
break;
default: break;
}
return TRUE;
}
#define PRIOR_BUTTON 2000
#define NEXT_BUTTON 2001
#define LUMP_CHECK 2002
#define RESULT_STATIC 2003
TSaveCommonDlg::TSaveCommonDlg(ShareInfo *_shareInfo, Cfg *_cfg, TWin *_parentWin) : TDlg((UINT)0, _parentWin)
{
parentWin = _parentWin;
shareInfo = _shareInfo;
cfg = _cfg;
offset = 0;
for (int i=0; i < shareInfo->fileCnt; i++)
shareInfo->fileInfo[i]->SetSelected(FALSE);
}
BOOL GetParentDir(const char *srcfile, char *dir)
{
char path[MAX_BUF], *fname=NULL;
if (GetFullPathNameU8(srcfile, sizeof(path), path, &fname) == 0 || fname == NULL)
return strcpy(dir, srcfile), FALSE;
if (fname - path > 3 || path[1] != ':')
*(fname - 1) = 0;
else
*fname = 0; // C:\ の場合
strcpy(dir, path);
return TRUE;
}
int TSaveCommonDlg::Exec(void)
{
modalFlg = TRUE;
char fname[MAX_BUF], last_dir[MAX_BUF], buf[MAX_BUF], *ext;
// 最終保存ディレクトリが無くなっている場合、少しさかのぼる
for (int i=0; i < 5; i++) {
if (*cfg->lastSaveDir && GetFileAttributesU8(cfg->lastSaveDir) == 0xffffffff)
if (!PathToDir(cfg->lastSaveDir, cfg->lastSaveDir))
break;
}
strcpy(last_dir, *cfg->lastSaveDir ? cfg->lastSaveDir : ".");
while (1) {
FileInfo *fileInfo = shareInfo->fileInfo[offset];
MakePath(fname, last_dir, fileInfo->Fname());
// ファイルダイアログ
TApp::GetApp()->AddWin(this);
OpenFileDlg dlg(parentWin, OpenFileDlg::NODEREF_SAVE, (LPOFNHOOKPROC)TApp::WinProc);
BOOL ret = dlg.Exec(fname, sizeof(fname), GetLoadStrU8(IDS_SAVEFILE),
GetLoadStrAsFilterU8(IDS_OPENFILEALLFLTR), last_dir);
TApp::GetApp()->DelWin(this);
hWnd = NULL;
if (!ret)
return FALSE;
// shortcut の場合は、リンク先に飛ぶ
if (!isLinkFile && (ext = strrchr(fname, '.')) && stricmp(ext, ".lnk") == 0) {
char arg[MAX_BUF];
if (ReadLinkU8(fname, last_dir, arg)) {
if ((GetFileAttributesU8(last_dir) & FILE_ATTRIBUTE_DIRECTORY) == 0)
GetParentDir(last_dir, last_dir);
}
continue;
}
fileInfo = shareInfo->fileInfo[offset];
PathToDir(fname, last_dir);
ForcePathToFname(fname, fname);
fileInfo->SetSelected(TRUE);
// 上書き確認
for (int i=0; i < shareInfo->fileCnt; i++)
{
if (!shareInfo->fileInfo[i]->IsSelected())
continue;
MakePath(buf, last_dir, offset == i ? fname : shareInfo->fileInfo[i]->Fname());
if (GetFileAttributesU8(buf) != 0xffffffff)
{
ret = parentWin->MessageBoxU8(GetLoadStrU8(IDS_OVERWRITE), GetLoadStrU8(IDS_ATTENTION), MB_OKCANCEL|MB_ICONEXCLAMATION);
if (ret != IDOK) {
for (int j=0; j < shareInfo->fileCnt; j++)
shareInfo->fileInfo[j]->SetSelected(FALSE);
}
break;
}
}
if (ret) {
fileInfo->SetFname(fname);
strcpy(cfg->lastSaveDir, last_dir);
cfg->WriteRegistry(CFG_GENERAL);
return TRUE;
}
}
// not reach
}
BOOL TSaveCommonDlg::EvCreate(LPARAM lParam)
{
RECT ok_rect = { 0, 0, 50, 20 }, cl_rect;
HWND pWnd = ::GetParent(hWnd);
::ShowWindow(::GetDlgItem(pWnd, 0x441), SW_HIDE);
::ShowWindow(::GetDlgItem(pWnd, 0x470), SW_HIDE);
// if (shareInfo->fileCnt == 1)
// return TRUE;
if (!::GetWindowRect(::GetDlgItem(pWnd, IDOK), &ok_rect))
return TRUE;
int ok_xsize = ok_rect.right - ok_rect.left;
int ok_ysize = ok_rect.bottom - ok_rect.top;
// ボタン高さの2倍分広げる
SetWindowLong(GWL_STYLE, GetWindowLong(GWL_STYLE)|WS_CLIPSIBLINGS);
::GetClientRect(pWnd, &cl_rect);
GetWindowRect(&rect);
MoveWindow(0, 0, cl_rect.right, (rect.bottom - rect.top) + ok_ysize * 5 / 2, FALSE);
GetWindowRect(&rect);
int cx = 20, cy = ok_ysize;
CreateWindowU8(STATIC_CLASS, "", WS_CHILD|WS_VISIBLE|SS_LEFT, cx, 0, rect.right, ok_ysize, hWnd, (HMENU)RESULT_STATIC, TApp::GetInstance(), NULL);
DWORD flg = (shareInfo->fileCnt == 1 ? WS_DISABLED : 0)|WS_CHILD|WS_VISIBLE;
CreateWindowU8(BUTTON_CLASS, GetLoadStrU8(IDS_PREVBUTTON), flg | BS_PUSHBUTTON, cx, cy, ok_xsize, ok_ysize, hWnd, (HMENU)PRIOR_BUTTON, TApp::GetInstance(), NULL);
CreateWindowU8(BUTTON_CLASS, GetLoadStrU8(IDS_NEXTBUTTON), flg | BS_PUSHBUTTON, cx+=ok_xsize+20, cy, ok_xsize, ok_ysize, hWnd, (HMENU)NEXT_BUTTON, TApp::GetInstance(), NULL);
CreateWindowU8(BUTTON_CLASS, "", WS_CHILD|WS_VISIBLE|BS_CHECKBOX, cx+=ok_xsize+20, cy, ok_xsize * 2, ok_ysize, hWnd, (HMENU)LUMP_CHECK, TApp::GetInstance(), NULL);
HFONT hDlgFont = (HFONT)::SendDlgItemMessage(pWnd, IDOK, WM_GETFONT, 0, 0L);
if (hDlgFont)
{
SendDlgItemMessage(RESULT_STATIC, WM_SETFONT, (UINT)hDlgFont, 0L);
SendDlgItemMessage(PRIOR_BUTTON, WM_SETFONT, (UINT)hDlgFont, 0L);
SendDlgItemMessage(NEXT_BUTTON, WM_SETFONT, (UINT)hDlgFont, 0L);
SendDlgItemMessage(LUMP_CHECK, WM_SETFONT, (UINT)hDlgFont, 0L);
}
SetInfo();
if (cfg->LumpCheck)
LumpCheck();
return TRUE;
}
BOOL TSaveCommonDlg::EvCommand(WORD wNotifyCode, WORD wID, LPARAM hwndCtl)
{
switch (wID) {
case PRIOR_BUTTON:
if (offset > 0)
offset--;
SetInfo();
return TRUE;
case NEXT_BUTTON:
if (offset < shareInfo->fileCnt -1)
offset++;
SetInfo();
return TRUE;
case LUMP_CHECK:
LumpCheck();
return TRUE;
}
return FALSE;
}
BOOL TSaveCommonDlg::LumpCheck()
{
cfg->LumpCheck = SendDlgItemMessage(LUMP_CHECK, BM_GETCHECK, 0, 0) == 0;
CheckDlgButton(LUMP_CHECK, cfg->LumpCheck);
for (int i=0; i < shareInfo->fileCnt; i++)
shareInfo->fileInfo[i]->SetSelected(cfg->LumpCheck);
return TRUE;
}
BOOL TSaveCommonDlg::EventApp(UINT uMsg, WPARAM wParam, LPARAM lParam)
{
return FALSE;
}
BOOL TSaveCommonDlg::SetInfo(void)
{
char buf[MAX_BUF], sizestr[MAX_LISTBUF];
Wstr fname_w(shareInfo->fileInfo[offset]->Fname());
::SetDlgItemTextW(::GetParent(hWnd), 0x480, fname_w.Buf());
if (GET_MODE(shareInfo->fileInfo[offset]->Attr()) == IPMSG_FILE_DIR)
strcpy(sizestr, GetLoadStrU8(IDS_DIRSAVE));
else
MakeSizeString(sizestr, shareInfo->fileInfo[offset]->Size());
wsprintf(buf, GetLoadStrU8(IDS_FILEINFO), offset + 1, shareInfo->fileCnt, shareInfo->fileInfo[offset]->Fname(), sizestr);
SetDlgItemTextU8(RESULT_STATIC, buf);
_int64 total_size = 0;
for (int i=0; i < shareInfo->fileCnt; i++)
total_size += shareInfo->fileInfo[i]->Size();
MakeSizeString(sizestr, total_size);
wsprintf(buf, GetLoadStrU8(IDS_LUMPBUTTON), sizestr, shareInfo->fileCnt);
SetDlgItemTextU8(LUMP_CHECK, buf);
const char *ext = strrchr(shareInfo->fileInfo[offset]->Fname(), '.');
isLinkFile = (ext && stricmp(ext, ".lnk") == 0) ? TRUE : FALSE;
return TRUE;
}
/*
ファイル共有(添付)情報をエンコード
*/
BOOL EncodeShareMsg(ShareInfo *info, char *buf, int bufsize, BOOL incMem)
{
int offset=0;
char fname[MAX_PATH_U8];
int id_base = 0;
TGenRandom(&id_base, sizeof(id_base));
id_base &= 0x3fffffff; // 負数になるのを防ぐ
*buf = 0;
for (int i=0; i < info->fileCnt; i++)
{
char addition[100] = "";
if (GET_MODE(info->fileInfo[i]->Attr()) == IPMSG_FILE_CLIPBOARD) {
if (!incMem) continue;
sprintf(addition, ":%x=%x", IPMSG_FILE_CLIPBOARDPOS, info->fileInfo[i]->Pos());
}
ForcePathToFname(info->fileInfo[i]->Fname(), fname);
info->fileInfo[i]->SetId(id_base + i);
offset += sprintf(buf + offset, "%d:%s:%I64x:%x:%x%s:%c",
info->fileInfo[i]->Id(), fname, info->fileInfo[i]->Size(),
info->fileInfo[i]->Mtime(), info->fileInfo[i]->Attr(),
addition, FILELIST_SEPARATOR);
if (offset + MAX_BUF > bufsize)
break;
}
return TRUE;
}
/*
ファイル名に ':' を含む場合、"::" とエスケープされているが、
Windows では使えないので、';' に置き換える
*/
void ConvertShareMsgEscape(char *str)
{
char *ptr;
while ((ptr = strstr(str, "::")))
{
*ptr++ = ';';
memmove(ptr, ptr + 1, strlen(ptr));
}
}
/*
ファイル共有(添付)情報をデコード
注意:破壊読出し。使用が終わり次第 FreeDecodeShareMsg を呼び出すこと。
*/
ShareInfo *DecodeShareMsg(char *buf, BOOL enable_clip)
{
ShareInfo *shareInfo = new ShareInfo;
FileInfo *fileInfo = NULL;
char *tok, *p, *p2, *p3;
char *file = separate_token(buf, FILELIST_SEPARATOR, &p);
for (int i=0; file; i++, file=separate_token(NULL, FILELIST_SEPARATOR, &p))
{
ConvertShareMsgEscape(file); // "::" -> ';'
if ((tok = separate_token(file, ':', &p2)) == NULL)
break;
fileInfo = new FileInfo(atoi(tok));
if ((tok = separate_token(NULL, ':', &p2)) == NULL || strlen(tok) > MAX_FILENAME_U8)
break;
while ((p3 = strchr(tok, '?'))) // UNICODE 対応までの暫定
*p3 = '_';
if (!IsValidFileName(tok))
break;
fileInfo->SetFname(tok);
if ((tok = separate_token(NULL, ':', &p2)) == NULL)
break;
fileInfo->SetSize(hex2ll(tok));
if ((tok = separate_token(NULL, ':', &p2)) == NULL)
break;
fileInfo->SetMtime(strtoul(tok, 0, 16));
if ((tok = separate_token(NULL, ':', &p2)))
{
fileInfo->SetAttr(strtoul(tok, 0, 16));
u_int attr_type = GET_MODE(fileInfo->Attr());
if (attr_type != IPMSG_FILE_DIR &&
attr_type != IPMSG_FILE_REGULAR &&
(!enable_clip || attr_type != IPMSG_FILE_CLIPBOARD))
{
delete fileInfo;
fileInfo = NULL;
continue;
}
if (attr_type == IPMSG_FILE_CLIPBOARD) {
if ((tok = separate_token(NULL, ':', &p2))) {
if (strtoul(tok, 0, 16) == IPMSG_FILE_CLIPBOARDPOS) {
if (separate_token(tok, '=', &p3) &&
(tok = separate_token(NULL, '=', &p3))) {
fileInfo->SetPos(strtoul(tok, 0, 16));
}
}
}
}
}
else fileInfo->SetAttr(IPMSG_FILE_REGULAR);
if ((shareInfo->fileCnt % BIG_ALLOC) == 0)
shareInfo->fileInfo = (FileInfo **)realloc(shareInfo->fileInfo, (shareInfo->fileCnt + BIG_ALLOC) * sizeof(FileInfo *));
shareInfo->fileInfo[shareInfo->fileCnt++] = fileInfo;
fileInfo = NULL;
}
if (fileInfo) // デコード中に抜けた
delete fileInfo;
if (shareInfo->fileCnt <= 0)
{
delete shareInfo;
return NULL;
}
return shareInfo;
}
/*
デコード情報の開放
*/
BOOL FreeDecodeShareMsg(ShareInfo *info)
{
while (info->fileCnt-- > 0)
delete info->fileInfo[info->fileCnt];
free(info->fileInfo);
delete info;
return TRUE;
}
/*
デコード情報内のファイル情報削除
*/
BOOL FreeDecodeShareMsgFile(ShareInfo *info, int index)
{
if (index >= info->fileCnt)
return FALSE;
delete info->fileInfo[index];
memmove(info->fileInfo + index, info->fileInfo + index +1, sizeof(FileInfo *) * (--info->fileCnt - index));
return TRUE;
}
ShareInfo::ShareInfo(int _packetNo)
{
packetNo = _packetNo;
host = NULL;
transStat = NULL;
fileInfo = NULL;
hostCnt = fileCnt = 0;
memset(&attachTime, 0, sizeof(attachTime));
}
void ShareInfo::LinkList(ShareInfo *top)
{
prior = top->prior;
next = top;
top->prior->next = this;
top->prior = this;
}
| 25.889518 | 175 | 0.664186 | voidluffy |
73c84c2fe0155d21d7059938330e44fa3668c6df | 8,887 | cc | C++ | paddle/fluid/operators/detection_map_op.cc | yucheng20170406/Paddle | e91fa1741be58899a58e55f3f1625a51fd95aba0 | [
"Apache-2.0"
] | null | null | null | paddle/fluid/operators/detection_map_op.cc | yucheng20170406/Paddle | e91fa1741be58899a58e55f3f1625a51fd95aba0 | [
"Apache-2.0"
] | 3 | 2018-04-11T10:25:51.000Z | 2018-04-12T01:17:22.000Z | paddle/fluid/operators/detection_map_op.cc | zhaofenqiang/PaddleOnACL | e543af14589e2311ae2f3f6c9887b537d2048666 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include "paddle/fluid/operators/detection_map_op.h"
namespace paddle {
namespace operators {
using Tensor = framework::Tensor;
class DetectionMAPOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext* ctx) const override {
PADDLE_ENFORCE(ctx->HasInput("DetectRes"),
"Input(DetectRes) of DetectionMAPOp should not be null.");
PADDLE_ENFORCE(ctx->HasInput("Label"),
"Input(Label) of DetectionMAPOp should not be null.");
PADDLE_ENFORCE(
ctx->HasOutput("AccumPosCount"),
"Output(AccumPosCount) of DetectionMAPOp should not be null.");
PADDLE_ENFORCE(
ctx->HasOutput("AccumTruePos"),
"Output(AccumTruePos) of DetectionMAPOp should not be null.");
PADDLE_ENFORCE(
ctx->HasOutput("AccumFalsePos"),
"Output(AccumFalsePos) of DetectionMAPOp should not be null.");
PADDLE_ENFORCE(ctx->HasOutput("MAP"),
"Output(MAP) of DetectionMAPOp should not be null.");
auto det_dims = ctx->GetInputDim("DetectRes");
PADDLE_ENFORCE_EQ(det_dims.size(), 2UL,
"The rank of Input(DetectRes) must be 2, "
"the shape is [N, 6].");
PADDLE_ENFORCE_EQ(det_dims[1], 6UL,
"The shape is of Input(DetectRes) [N, 6].");
auto label_dims = ctx->GetInputDim("Label");
PADDLE_ENFORCE_EQ(label_dims.size(), 2,
"The rank of Input(Label) must be 2, "
"the shape is [N, 6].");
PADDLE_ENFORCE_EQ(label_dims[1], 6, "The shape is of Input(Label) [N, 6].");
if (ctx->HasInput("PosCount")) {
PADDLE_ENFORCE(ctx->HasInput("TruePos"),
"Input(TruePos) of DetectionMAPOp should not be null when "
"Input(TruePos) is not null.");
PADDLE_ENFORCE(
ctx->HasInput("FalsePos"),
"Input(FalsePos) of DetectionMAPOp should not be null when "
"Input(FalsePos) is not null.");
}
ctx->SetOutputDim("MAP", framework::make_ddim({1}));
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext& ctx) const override {
return framework::OpKernelType(
framework::ToDataType(
ctx.Input<framework::Tensor>("DetectRes")->type()),
platform::CPUPlace());
}
};
class DetectionMAPOpMaker : public framework::OpProtoAndCheckerMaker {
public:
DetectionMAPOpMaker(OpProto* proto, OpAttrChecker* op_checker)
: OpProtoAndCheckerMaker(proto, op_checker) {
AddInput("DetectRes",
"(LoDTensor) A 2-D LoDTensor with shape [M, 6] represents the "
"detections. Each row has 6 values: "
"[label, confidence, xmin, ymin, xmax, ymax], M is the total "
"number of detect results in this mini-batch. For each instance, "
"the offsets in first dimension are called LoD, the number of "
"offset is N + 1, if LoD[i + 1] - LoD[i] == 0, means there is "
"no detected data.");
AddInput("Label",
"(LoDTensor) A 2-D LoDTensor with shape[N, 6] represents the"
"Labeled ground-truth data. Each row has 6 values: "
"[label, is_difficult, xmin, ymin, xmax, ymax], N is the total "
"number of ground-truth data in this mini-batch. For each "
"instance, the offsets in first dimension are called LoD, "
"the number of offset is N + 1, if LoD[i + 1] - LoD[i] == 0, "
"means there is no ground-truth data.");
AddInput("HasState",
"(Tensor<int>) A tensor with shape [1], 0 means ignoring input "
"states, which including PosCount, TruePos, FalsePos.")
.AsDispensable();
AddInput("PosCount",
"(Tensor) A tensor with shape [Ncls, 1], store the "
"input positive example count of each class, Ncls is the count of "
"input classification. "
"This input is used to pass the AccumPosCount generated by the "
"previous mini-batch when the multi mini-batches cumulative "
"calculation carried out. "
"When the input(PosCount) is empty, the cumulative "
"calculation is not carried out, and only the results of the "
"current mini-batch are calculated.")
.AsDispensable();
AddInput("TruePos",
"(LoDTensor) A 2-D LoDTensor with shape [Ntp, 2], store the "
"input true positive example of each class."
"This input is used to pass the AccumTruePos generated by the "
"previous mini-batch when the multi mini-batches cumulative "
"calculation carried out. ")
.AsDispensable();
AddInput("FalsePos",
"(LoDTensor) A 2-D LoDTensor with shape [Nfp, 2], store the "
"input false positive example of each class."
"This input is used to pass the AccumFalsePos generated by the "
"previous mini-batch when the multi mini-batches cumulative "
"calculation carried out. ")
.AsDispensable();
AddOutput("AccumPosCount",
"(Tensor) A tensor with shape [Ncls, 1], store the "
"positive example count of each class. It combines the input "
"input(PosCount) and the positive example count computed from "
"input(Detection) and input(Label).");
AddOutput("AccumTruePos",
"(LoDTensor) A LoDTensor with shape [Ntp', 2], store the "
"true positive example of each class. It combines the "
"input(TruePos) and the true positive examples computed from "
"input(Detection) and input(Label).");
AddOutput("AccumFalsePos",
"(LoDTensor) A LoDTensor with shape [Nfp', 2], store the "
"false positive example of each class. It combines the "
"input(FalsePos) and the false positive examples computed from "
"input(Detection) and input(Label).");
AddOutput("MAP",
"(Tensor) A tensor with shape [1], store the mAP evaluate "
"result of the detection.");
AddAttr<int>("class_num",
"(int) "
"The class number.");
AddAttr<int>(
"background_label",
"(int, defalut: 0) "
"The index of background label, the background label will be ignored. "
"If set to -1, then all categories will be considered.")
.SetDefault(0);
AddAttr<float>(
"overlap_threshold",
"(float) "
"The lower bound jaccard overlap threshold of detection output and "
"ground-truth data.")
.SetDefault(.5f);
AddAttr<bool>("evaluate_difficult",
"(bool, default true) "
"Switch to control whether the difficult data is evaluated.")
.SetDefault(true);
AddAttr<std::string>("ap_type",
"(string, default 'integral') "
"The AP algorithm type, 'integral' or '11point'.")
.SetDefault("integral")
.InEnum({"integral", "11point"})
.AddCustomChecker([](const std::string& ap_type) {
PADDLE_ENFORCE_NE(GetAPType(ap_type), APType::kNone,
"The ap_type should be 'integral' or '11point.");
});
AddComment(R"DOC(
Detection mAP evaluate operator.
The general steps are as follows. First, calculate the true positive and
false positive according to the input of detection and labels, then
calculate the mAP evaluate value.
Supporting '11 point' and 'integral' mAP algorithm. Please get more information
from the following articles:
https://sanchom.wordpress.com/tag/average-precision/
https://arxiv.org/abs/1512.02325
)DOC");
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OP_WITHOUT_GRADIENT(detection_map, ops::DetectionMAPOp,
ops::DetectionMAPOpMaker);
REGISTER_OP_CPU_KERNEL(
detection_map, ops::DetectionMAPOpKernel<paddle::platform::CPUPlace, float>,
ops::DetectionMAPOpKernel<paddle::platform::CPUPlace, double>);
| 45.341837 | 80 | 0.62507 | yucheng20170406 |
73c86456ccc0491f3519f68c2cb39c89001f7ad1 | 3,021 | cpp | C++ | src/ImathTest/testToFloat.cpp | methodstudios/Imath | 64810ce8ca9d980f1b397d895d20ad8d284f68ad | [
"BSD-3-Clause"
] | 1 | 2021-01-10T16:32:43.000Z | 2021-01-10T16:32:43.000Z | src/ImathTest/testToFloat.cpp | oxt3479/Imath | 39c31ca077ab76a854c70f0d6810fb36eed37d73 | [
"BSD-3-Clause"
] | null | null | null | src/ImathTest/testToFloat.cpp | oxt3479/Imath | 39c31ca077ab76a854c70f0d6810fb36eed37d73 | [
"BSD-3-Clause"
] | null | null | null | //
// SPDX-License-Identifier: BSD-3-Clause
// Copyright Contributors to the OpenEXR Project.
//
#ifdef NDEBUG
# undef NDEBUG
#endif
#include <assert.h>
#include <cmath>
#include <half.h>
#include <iomanip>
#include <iostream>
using namespace std;
//
// This test uses the code that generates the toFLoat.h header to
// validate the the tabel values are correct.
//
//---------------------------------------------------
// Interpret an unsigned short bit pattern as a half,
// and convert that half to the corresponding float's
// bit pattern.
//---------------------------------------------------
unsigned int
halfToFloat (unsigned short y)
{
int s = (y >> 15) & 0x00000001;
int e = (y >> 10) & 0x0000001f;
int m = y & 0x000003ff;
if (e == 0)
{
if (m == 0)
{
//
// Plus or minus zero
//
return s << 31;
}
else
{
//
// Denormalized number -- renormalize it
//
while (!(m & 0x00000400))
{
m <<= 1;
e -= 1;
}
e += 1;
m &= ~0x00000400;
}
}
else if (e == 31)
{
if (m == 0)
{
//
// Positive or negative infinity
//
return (s << 31) | 0x7f800000;
}
else
{
//
// Nan -- preserve sign and significand bits
//
return (s << 31) | 0x7f800000 | (m << 13);
}
}
//
// Normalized number
//
e = e + (127 - 15);
m = m << 13;
//
// Assemble s, e and m.
//
return (s << 31) | (e << 23) | m;
}
union HalfShort
{
half h;
unsigned short s;
};
void
testToFloat()
{
std::cout << "running testToFloat" << std::endl;
constexpr int iMax = (1 << 16);
//
// for each 16-bit bit pattern...
//
for (int s = 0; s < iMax; s++)
{
HalfShort hs;
hs.s = s;
//
// cast these bits to a float, using the cast-to-float
// operator.
//
float f = float (hs.h); // = _toFloat[s]
//
// Cast that float back to a half.
//
half h = half (f);
//
// halfToFloat() above is what generated the _toFloat table.
// The i value return is the integer bit pattern of the corresponding
// float.
//
half::uif uif;
uif.i = halfToFloat (s);
//
// Equality operators fail for inf and nan, so handle them
// specially.
//
if (isnan (f))
{
assert (h.isNan());
assert (isnan (uif.f));
}
else if (isinf (f))
{
assert (h.isInfinity());
assert (isinf (uif.f));
}
else
{
assert (h == hs.h);
assert (f == uif.f);
}
}
std::cout << "ok" << std::endl;
}
| 18.309091 | 77 | 0.42337 | methodstudios |
73c86ddec0d10caf6ddf2f679312fa5aca183b13 | 1,160 | cpp | C++ | Lab10&11/a1.cpp | dipsonu10/OOPsLabClass | 231e608e7301c4802e24de9d5541e435e2f620d3 | [
"MIT"
] | null | null | null | Lab10&11/a1.cpp | dipsonu10/OOPsLabClass | 231e608e7301c4802e24de9d5541e435e2f620d3 | [
"MIT"
] | null | null | null | Lab10&11/a1.cpp | dipsonu10/OOPsLabClass | 231e608e7301c4802e24de9d5541e435e2f620d3 | [
"MIT"
] | null | null | null | /*WAP in C++ which will overload the Binary Operator (+) where the program will add two
Array, store in the resultant array and display the same using member function.*/
#include <iostream>
using namespace std;
class Addition {
public:
int *arr;
int size;
Addition(int S) : size(S) {
arr = new int[size];
}
~Addition() {
delete[] arr;
}
void inputData() {
printf("Enter the elements: ");
for (int i=0; i<size; i++)
cin >> arr[i];
}
Addition operator + (Addition& obj) {
Addition ans(obj.size);
for (int i=0; i<obj.size; i++) {
ans.arr[i] = obj.arr[i] + this->arr[i];
}
return ans;
}
void display() {
printf("[ ");
for(int i=0; i<size; i++) {
cout << arr[i] <<' ';
}
printf("]\n");
}
};
int main(int argc, char** argv) {
Addition arr1(5);
arr1.inputData();
Addition arr2(5);
arr2.inputData();
arr1.display();
arr2.display();
printf("Sum: ");
Addition res = arr1 + arr2;
res.display();
remove(argv[0]);
return EXIT_SUCCESS;
} | 19.333333 | 87 | 0.516379 | dipsonu10 |
73c9da8cae3e8e3e636dcdb0440aaa4b9f0e541b | 11,561 | cpp | C++ | code/Core/MDMA_core/src/UI/zoneeditor.cpp | Amxx/MDMA | 3be4269e252712081c70522f2af56463da5ac868 | [
"CECILL-B"
] | 1 | 2022-01-17T06:39:22.000Z | 2022-01-17T06:39:22.000Z | code/Core/MDMA_core/src/UI/zoneeditor.cpp | Amxx/MDMA | 3be4269e252712081c70522f2af56463da5ac868 | [
"CECILL-B"
] | null | null | null | code/Core/MDMA_core/src/UI/zoneeditor.cpp | Amxx/MDMA | 3be4269e252712081c70522f2af56463da5ac868 | [
"CECILL-B"
] | null | null | null | #include "zoneeditor.h"
#include "ui_zoneeditor.h"
#include <QDebug>
ZoneEditor::ZoneEditor(Zone& zn, QWidget *parent) :
QDialog(parent),
ui(new Ui::ZoneEditor),
_zn(zn)
{
ui->setupUi(this);
ui->lineEdit_name->setText(_zn._name);
ui->comboBox_tab->setCurrentIndex(_zn._tab);
ui->tabWidget_type->setCurrentIndex(_zn._type);
ui->comboBox_axex_0->setCurrentIndex(MDMA::isMidi(_zn[MDMA::EVENT_X].type)?_zn[MDMA::EVENT_X].type:MDMA::GOTO_TAB1);
ui->spinBox_axex_1->setValue(_zn[MDMA::EVENT_X].signal[0]);
ui->spinBox_axex_2->setValue(_zn[MDMA::EVENT_X].signal[1]);
ui->spinBox_axex_3->setValue(_zn[MDMA::EVENT_X].signal[2]);
ui->radioButton_variable_1_1->setChecked(_zn[MDMA::EVENT_X].variable == 1);
ui->radioButton_variable_1_2->setChecked(_zn[MDMA::EVENT_X].variable == 2);
ui->comboBox_axey_0->setCurrentIndex(MDMA::isMidi(_zn[MDMA::EVENT_Y].type)?_zn[MDMA::EVENT_Y].type:MDMA::GOTO_TAB1);
ui->spinBox_axey_1->setValue(_zn[MDMA::EVENT_Y].signal[0]);
ui->spinBox_axey_2->setValue(_zn[MDMA::EVENT_Y].signal[1]);
ui->spinBox_axey_3->setValue(_zn[MDMA::EVENT_Y].signal[2]);
ui->radioButton_variable_2_1->setChecked(_zn[MDMA::EVENT_Y].variable == 1);
ui->radioButton_variable_2_2->setChecked(_zn[MDMA::EVENT_Y].variable == 2);
ui->comboBox_enter->setCurrentIndex(_zn[MDMA::ENTER].type);
ui->spinBox_enter_1->setValue(_zn[MDMA::ENTER].signal[0]);
ui->spinBox_enter_2->setValue(_zn[MDMA::ENTER].signal[1]);
ui->spinBox_enter_3->setValue(_zn[MDMA::ENTER].signal[2]);
ui->comboBox_exit->setCurrentIndex(_zn[MDMA::EXIT].type);
ui->spinBox_exit_1->setValue(_zn[MDMA::EXIT].signal[0]);
ui->spinBox_exit_2->setValue(_zn[MDMA::EXIT].signal[1]);
ui->spinBox_exit_3->setValue(_zn[MDMA::EXIT].signal[2]);
ui->comboBox_open->setCurrentIndex(_zn[MDMA::OPEN].type);
ui->spinBox_open_1->setValue(_zn[MDMA::OPEN].signal[0]);
ui->spinBox_open_2->setValue(_zn[MDMA::OPEN].signal[1]);
ui->spinBox_open_3->setValue(_zn[MDMA::OPEN].signal[2]);
ui->comboBox_close->setCurrentIndex(_zn[MDMA::CLOSE].type);
ui->spinBox_close_1->setValue(_zn[MDMA::CLOSE].signal[0]);
ui->spinBox_close_2->setValue(_zn[MDMA::CLOSE].signal[1]);
ui->spinBox_close_3->setValue(_zn[MDMA::CLOSE].signal[2]);
ui->comboBox_shock->setCurrentIndex(_zn[MDMA::SHOCK].type);
ui->spinBox_shock_1->setValue(_zn[MDMA::SHOCK].signal[0]);
ui->spinBox_shock_2->setValue(_zn[MDMA::SHOCK].signal[1]);
ui->spinBox_shock_3->setValue(_zn[MDMA::SHOCK].signal[2]);
ui->comboBox_in->setCurrentIndex(_zn[MDMA::IN].type);
ui->spinBox_in_1->setValue(_zn[MDMA::IN].signal[0]);
ui->spinBox_in_2->setValue(_zn[MDMA::IN].signal[1]);
ui->spinBox_in_3->setValue(_zn[MDMA::IN].signal[2]);
ui->comboBox_out->setCurrentIndex(_zn[MDMA::OUT].type);
ui->spinBox_out_1->setValue(_zn[MDMA::OUT].signal[0]);
ui->spinBox_out_2->setValue(_zn[MDMA::OUT].signal[1]);
ui->spinBox_out_3->setValue(_zn[MDMA::OUT].signal[2]);
}
ZoneEditor::~ZoneEditor()
{
delete ui;
}
// ========================================================================================
void ZoneEditor::on_pushButton_apply_clicked()
{
_zn._type = (MDMA::type) ui->tabWidget_type->currentIndex();
_zn._name = ui->lineEdit_name->text();
_zn[MDMA::EVENT_X].type = (MDMA::signal) (ui->comboBox_axex_0->currentIndex());
if(!MDMA::isMidi(_zn[MDMA::EVENT_X].type)) _zn[MDMA::EVENT_X].type = MDMA::NOTHING;
_zn[MDMA::EVENT_X].signal[0] = ui->spinBox_axex_1->value();
_zn[MDMA::EVENT_X].signal[1] = ui->spinBox_axex_2->value();
_zn[MDMA::EVENT_X].signal[2] = ui->spinBox_axex_3->value();
_zn[MDMA::EVENT_X].variable = ui->radioButton_variable_1_1->isChecked()?1:2;
_zn[MDMA::EVENT_Y].type = (MDMA::signal) (ui->comboBox_axey_0->currentIndex());
if(!MDMA::isMidi(_zn[MDMA::EVENT_Y].type)) _zn[MDMA::EVENT_Y].type = MDMA::NOTHING;
_zn[MDMA::EVENT_Y].signal[0] = ui->spinBox_axey_1->value();
_zn[MDMA::EVENT_Y].signal[1] = ui->spinBox_axey_2->value();
_zn[MDMA::EVENT_Y].signal[2] = ui->spinBox_axey_3->value();
_zn[MDMA::EVENT_Y].variable = ui->radioButton_variable_2_1->isChecked()?1:2;
// ------------------------------------------------------------------------------------
_zn._tab = ui->comboBox_tab->currentIndex();
// ------------------------------------------------------------------------------------
_zn[MDMA::ENTER].type = (MDMA::signal) ui->comboBox_enter->currentIndex();
_zn[MDMA::ENTER].signal[0] = ui->spinBox_enter_1->value();
_zn[MDMA::ENTER].signal[1] = ui->spinBox_enter_2->value();
_zn[MDMA::ENTER].signal[2] = ui->spinBox_enter_3->value();
_zn[MDMA::EXIT].type = (MDMA::signal) ui->comboBox_exit->currentIndex();
_zn[MDMA::EXIT].signal[0] = ui->spinBox_exit_1->value();
_zn[MDMA::EXIT].signal[1] = ui->spinBox_exit_2->value();
_zn[MDMA::EXIT].signal[2] = ui->spinBox_exit_3->value();
_zn[MDMA::OPEN].type = (MDMA::signal) ui->comboBox_open->currentIndex();
_zn[MDMA::OPEN].signal[0] = ui->spinBox_open_1->value();
_zn[MDMA::OPEN].signal[1] = ui->spinBox_open_2->value();
_zn[MDMA::OPEN].signal[2] = ui->spinBox_open_3->value();
_zn[MDMA::CLOSE].type = (MDMA::signal) ui->comboBox_close->currentIndex();
_zn[MDMA::CLOSE].signal[0] = ui->spinBox_close_1->value();
_zn[MDMA::CLOSE].signal[1] = ui->spinBox_close_2->value();
_zn[MDMA::CLOSE].signal[2] = ui->spinBox_close_3->value();
_zn[MDMA::SHOCK].type = (MDMA::signal) ui->comboBox_shock->currentIndex();
_zn[MDMA::SHOCK].signal[0] = ui->spinBox_shock_1->value();
_zn[MDMA::SHOCK].signal[1] = ui->spinBox_shock_2->value();
_zn[MDMA::SHOCK].signal[2] = ui->spinBox_shock_3->value();
// ------------------------------------------------------------------------------------
_zn[MDMA::IN].type = (MDMA::signal) ui->comboBox_in->currentIndex();
_zn[MDMA::IN].signal[0] = ui->spinBox_in_1->value();
_zn[MDMA::IN].signal[1] = ui->spinBox_in_2->value();
_zn[MDMA::IN].signal[2] = ui->spinBox_in_3->value();
_zn[MDMA::OUT].type = (MDMA::signal) ui->comboBox_out->currentIndex();
_zn[MDMA::OUT].signal[0] = ui->spinBox_out_1->value();
_zn[MDMA::OUT].signal[1] = ui->spinBox_out_2->value();
_zn[MDMA::OUT].signal[2] = ui->spinBox_out_3->value();
// ------------------------------------------------------------------------------------
_zn.update();
accept();
}
void ZoneEditor::on_pushButton_cancel_clicked()
{
reject();
}
void ZoneEditor::on_pushButton_delete_clicked()
{
done(-1);
}
/*
* ==========================================================================================
* = GENERAL =
* ==========================================================================================
*/
void ZoneEditor::on_tabWidget_type_currentChanged(int index)
{
// _zn._type = (MDMA::type) index;
// _zn.update();
}
void ZoneEditor::on_lineEdit_name_textChanged(const QString &arg1)
{
// _zn._name = arg1;
// _zn.update();
}
/*
* ==========================================================================================
* = AXE X =
* ==========================================================================================
*/
void ZoneEditor::on_comboBox_axex_0_currentIndexChanged(int index)
{
// _zn[MDMA::EVENT_X].type = (MDMA::signal) index;
// if(!MDMA::isMidi(_zn[MDMA::EVENT_X].type)) _zn[MDMA::EVENT_X].type = MDMA::NOTHING;
ui->spinBox_axex_1->setDisabled(MDMA::isMidi((MDMA::signal) index) < 1);
ui->spinBox_axex_2->setDisabled((MDMA::isMidi((MDMA::signal) index) < 1)); // || evz.variable[0][0]);
ui->spinBox_axex_3->setDisabled((MDMA::isMidi((MDMA::signal) index) < 2)); // || evz.variable[0][1]);
}
void ZoneEditor::on_spinBox_axex_1_valueChanged(int arg1)
{
// _zn[MDMA::EVENT_X].signal[0] = arg1;
}
void ZoneEditor::on_spinBox_axex_2_valueChanged(int arg1)
{
// _zn[MDMA::EVENT_X].signal[1] = arg1;
}
void ZoneEditor::on_spinBox_axex_3_valueChanged(int arg1)
{
// _zn[MDMA::EVENT_X].signal[2] = arg1;
}
void ZoneEditor::on_radioButton_variable_1_1_toggled(bool checked)
{
// _zn[MDMA::EVENT_X].variable = checked?1:2;
}
/*
* ==========================================================================================
* = AXE Y =
* ==========================================================================================
*/
void ZoneEditor::on_comboBox_axey_0_currentIndexChanged(int index)
{
// _zn[MDMA::EVENT_Y].type = (MDMA::signal) index;
// if(!MDMA::isMidi(_zn[MDMA::EVENT_X].type)) _zn[MDMA::EVENT_X].type = MDMA::NOTHING;
ui->spinBox_axey_1->setDisabled(MDMA::isMidi((MDMA::signal) index) < 1);
ui->spinBox_axey_2->setDisabled((MDMA::isMidi((MDMA::signal) index) < 1)); // || evz.variable[1][0]);
ui->spinBox_axey_3->setDisabled((MDMA::isMidi((MDMA::signal) index) < 2)); // || evz.variable[1][1]);
}
void ZoneEditor::on_spinBox_axey_1_valueChanged(int arg1)
{
// _zn[MDMA::EVENT_Y].signal[0] = arg1;
}
void ZoneEditor::on_spinBox_axey_2_valueChanged(int arg1)
{
// _zn[MDMA::EVENT_Y].signal[1] = arg1;
}
void ZoneEditor::on_spinBox_axey_3_valueChanged(int arg1)
{
// _zn[MDMA::EVENT_Y].signal[2] = arg1;
}
void ZoneEditor::on_radioButton_variable_2_1_toggled(bool checked)
{
// _zn[MDMA::EVENT_Y].variable = checked?1:2;
}
/*
* ==========================================================================================
* = ELSE =
* ==========================================================================================
*/
void ZoneEditor::on_comboBox_enter_currentIndexChanged(int index)
{
ui->spinBox_enter_1->setDisabled(MDMA::isMidi((MDMA::signal) index) < 1);
ui->spinBox_enter_2->setDisabled(MDMA::isMidi((MDMA::signal) index) < 1);
ui->spinBox_enter_3->setDisabled(MDMA::isMidi((MDMA::signal) index) < 2);
}
void ZoneEditor::on_comboBox_exit_currentIndexChanged(int index)
{
ui->spinBox_exit_1->setDisabled(MDMA::isMidi((MDMA::signal) index) < 1);
ui->spinBox_exit_2->setDisabled(MDMA::isMidi((MDMA::signal) index) < 1);
ui->spinBox_exit_3->setDisabled(MDMA::isMidi((MDMA::signal) index) < 2);
}
void ZoneEditor::on_comboBox_open_currentIndexChanged(int index)
{
ui->spinBox_open_1->setDisabled(MDMA::isMidi((MDMA::signal) index) < 1);
ui->spinBox_open_2->setDisabled(MDMA::isMidi((MDMA::signal) index) < 1);
ui->spinBox_open_3->setDisabled(MDMA::isMidi((MDMA::signal) index) < 2);
}
void ZoneEditor::on_comboBox_close_currentIndexChanged(int index)
{
ui->spinBox_close_1->setDisabled(MDMA::isMidi((MDMA::signal) index) < 1);
ui->spinBox_close_2->setDisabled(MDMA::isMidi((MDMA::signal) index) < 1);
ui->spinBox_close_3->setDisabled(MDMA::isMidi((MDMA::signal) index) < 2);
}
void ZoneEditor::on_comboBox_shock_currentIndexChanged(int index)
{
ui->spinBox_shock_1->setDisabled(MDMA::isMidi((MDMA::signal) index) < 1);
ui->spinBox_shock_2->setDisabled(MDMA::isMidi((MDMA::signal) index) < 1);
ui->spinBox_shock_3->setDisabled(MDMA::isMidi((MDMA::signal) index) < 2);
}
void ZoneEditor::on_comboBox_in_currentIndexChanged(int index)
{
ui->spinBox_in_1->setDisabled(MDMA::isMidi((MDMA::signal) index) < 1);
ui->spinBox_in_2->setDisabled(MDMA::isMidi((MDMA::signal) index) < 1);
ui->spinBox_in_3->setDisabled(MDMA::isMidi((MDMA::signal) index) < 2);
}
void ZoneEditor::on_comboBox_out_currentIndexChanged(int index)
{
ui->spinBox_out_1->setDisabled(MDMA::isMidi((MDMA::signal) index) < 1);
ui->spinBox_out_2->setDisabled(MDMA::isMidi((MDMA::signal) index) < 1);
ui->spinBox_out_3->setDisabled(MDMA::isMidi((MDMA::signal) index) < 2);
}
void ZoneEditor::on_noteHelp_clicked()
{
// NoteNumberWindow* noteWindow = new NoteNumberWindow(this);
// noteWindow->show();
}
int EditZone(Zone& zn, QWidget* parent)
{
return ZoneEditor(zn, parent).exec();
}
| 38.795302 | 117 | 0.636969 | Amxx |
73ca5dfab71e0b17d2d290fcc37b81b02ad760ab | 2,786 | cpp | C++ | ontheline.cpp | hiratake26to/tg_ontheline | e471378eff39ea1fd134d0f155a6f159a30462b3 | [
"CECILL-B"
] | null | null | null | ontheline.cpp | hiratake26to/tg_ontheline | e471378eff39ea1fd134d0f155a6f159a30462b3 | [
"CECILL-B"
] | null | null | null | ontheline.cpp | hiratake26to/tg_ontheline | e471378eff39ea1fd134d0f155a6f159a30462b3 | [
"CECILL-B"
] | null | null | null | /**
* license is free
* \file ontheline.cpp
* \author hiratake26to@gmail.com
* \date 2017-10-11 JST
*/
#include <iostream>
#include <boost/numeric/ublas/vector.hpp>
/**
* \brief mouse pointer is on the line
* \param xa x of equipment A
* \param ya y of equipment A
* \param xb x of equipment B
* \param yb y of equipment B
* \param xc x of mouse pointer
* \param yc y of mouse pointer
* \param r line width
*/
bool isOnTheLine(int xa, int ya, int xb, int yb, int xc, int yc, int r);
int main() {
/* 0 1 2 3 4
* 0 _ _ _ _ _
* 1 _ _ _ B _
* 2 _ _ @ _ _
* 3 _ @ _ _ _
* 4 A _ _ _ _
*/
bool result;
result = isOnTheLine(0, 4, 3, 1, 2, 2, 1);
std::cout << "result : " << result << std::endl;
std::cout << "--------------------------" << std::endl;
result = isOnTheLine(0, 4, 3, 1, 3, 2, 1);
std::cout << "result : " << result << std::endl;
std::cout << "--------------------------" << std::endl;
result = isOnTheLine(0, 4, 3, 1, 4, 3, 1);
std::cout << "result : " << result << std::endl;
std::cout << "--------------------------" << std::endl;
result = isOnTheLine(0, 4, 3, 1, 4, 0, 0);
std::cout << "result : " << result << std::endl;
return 0;
}
bool isOnTheLine(int xa, int ya, int xb, int yb, int xc, int yc, int r)
{
namespace ublas = boost::numeric::ublas;
// point C is mouse pointer
// point X is point at the intersection of AB with CX
// vector CX is perpendicular line from C to line AB
ublas::vector<double> v_AB(2);
ublas::vector<double> v_nAB(2); // nAB is unit vector of AB
ublas::vector<double> v_AC(2);
ublas::vector<double> v_AX(2);
ublas::vector<double> v_CX(2);
double len_AB; // length of vector AB
double len_AX; // length of vector AX
double len_CX; // length of vector CX
// vector AB
v_AB[0] = xb - xa; // AB.x
v_AB[1] = yb - ya; // AB.y
// length of AB
len_AB = ublas::norm_2(v_AB);
// unit vector nAB
v_nAB = v_AB / len_AB;
// vector AC
v_AC[0] = xc - xa; // AC.x
v_AC[1] = yc - ya; // AC.y
// length of AX
len_AX = ublas::inner_prod(v_AC, v_nAB); // (AC,nAB)
// vector AX
v_AX = v_nAB * len_AX; // AX = nAB*|AX|
// vector CX
v_CX = v_AX - v_AC;
// length of CX
len_CX = ublas::norm_2(v_CX);
// debug log
std::cout << "length of AB : " << len_AB << std::endl;
std::cout << "length of AX : " << len_AX << std::endl;
std::cout << "dist from C to X: " << len_CX << std::endl;
std::cout << "check length CX : "
<< ((len_CX < r)?"true":"false") << std::endl;
std::cout << "check length AX : "
<< ((len_AX < len_AB)?"true":"false") << std::endl;
bool pointer_isOnLine = (len_CX < r) && (len_AX <= len_AB);
return pointer_isOnLine;
}
| 28.721649 | 72 | 0.548457 | hiratake26to |
73d13975c3f512ef80c422d1ee19e29ff4324e48 | 1,094 | cpp | C++ | solutions/1285/competition.cpp | buptlxb/hihoCoder | 1995bdfda29d4dab98c002870ef0bc138bc37ce7 | [
"Apache-2.0"
] | 44 | 2016-05-11T06:41:14.000Z | 2021-12-20T13:45:41.000Z | solutions/1285/competition.cpp | buptlxb/hihoCoder | 1995bdfda29d4dab98c002870ef0bc138bc37ce7 | [
"Apache-2.0"
] | null | null | null | solutions/1285/competition.cpp | buptlxb/hihoCoder | 1995bdfda29d4dab98c002870ef0bc138bc37ce7 | [
"Apache-2.0"
] | 10 | 2016-06-25T08:55:20.000Z | 2018-07-06T05:52:53.000Z | #include <iostream>
#include <vector>
#include <limits>
#include <algorithm>
using namespace std;
int solve(const vector<int> &levels, int m, int s, int t)
{
vector<vector<int>> dp(levels.size()+1, vector<int>(m+1, m+1));
dp[0].assign(m+1, 0);
for (int i = 1; i < dp.size(); ++i) {
int right = (levels[i-1] + s - 1) / s;
for (int j = 0; j <= right; ++j) {
int remain = levels[i-1] - s * j;
int wrong = remain > 0 ? (remain + t - 1) / t : 0;
for (int k = 0; k+j+wrong <= m; ++k)
dp[i][k+j+wrong] = min(dp[i][k+j+wrong], dp[i-1][k]+j);
}
}
return *min_element(dp.back().begin(), dp.back().end());
}
int main(void)
{
int q;
cin >> q;
while (q--) {
int n, m, s, t;
cin >> n >> m >> s >> t;
vector<int> levels(n);
for (int i = 0; i < n; ++i)
cin >> levels[i];
int res = solve(levels, m, s, t);
if (res > m)
cout << "No" << endl;
else
cout << res << '\n';
}
cout << flush;
return 0;
}
| 25.44186 | 71 | 0.442413 | buptlxb |
73d7da7130321a077a8613b99b8ac3f0bfa48458 | 23,357 | cpp | C++ | components/view/qtcomponentstableview_internal.cpp | jhupo/qt-components | e5797879f63d4fb544695d3abefb2a26767e86c5 | [
"MIT"
] | null | null | null | components/view/qtcomponentstableview_internal.cpp | jhupo/qt-components | e5797879f63d4fb544695d3abefb2a26767e86c5 | [
"MIT"
] | null | null | null | components/view/qtcomponentstableview_internal.cpp | jhupo/qt-components | e5797879f63d4fb544695d3abefb2a26767e86c5 | [
"MIT"
] | null | null | null | #include "qtcomponentstableview.h"
#include "qtcomponentstableview_internal.h"
#include "components/lib/qtcomponentstools.h"
#include "components/button/qtcomponentsbutton.h"
#include <QMouseEvent>
#include <QPainter>
#include <QCheckBox>
#include <QScrollBar>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QBoxLayout>
#include <QMenu>
#include <QAction>
const unsigned int COUSTOM_LINEDIT_LEFT_MARGIN = 0x000F;
QtComponentsHeaderView::QtComponentsHeaderView(QtComponentsTableView* view, Qt::Orientation orientation, QWidget *parent)
: QHeaderView(orientation,parent)
, _state(Qt::Unchecked)
, _view(view)
{
Q_ASSERT(view);
}
QtComponentsHeaderView::~QtComponentsHeaderView()
{
}
void QtComponentsHeaderView::setCheckable(Qt::CheckState state)
{
if (_state == state)
{
return;
}
_state = state;
viewport()->update();
}
Qt::CheckState QtComponentsHeaderView::isChecked() const
{
return _state;
}
void QtComponentsHeaderView::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const
{
if (logicalIndex < 0 || logicalIndex >= _view->modelData()->_labels.size())
{
return;
}
Components::TableHeaderType role = _view->modelData()->_labels[logicalIndex].first;
painter->setRenderHint(QPainter::Antialiasing);
QRect nRect = rect.adjusted(7, 7, -7, -7);
switch (role)
{
case Components::ID:
break;
case Components::hCheckBox:
drawHeaderCheckBox(painter, rect, logicalIndex);
break;
case Components::hText:
drawHeaderText(painter, nRect, logicalIndex);
break;
case Components::hSort:
drawHeaderSort(painter, nRect, logicalIndex);
break;
case Components::hSearch:
drawHeaderSearch(painter, nRect);
break;
default:
QHeaderView::paintSection(painter, rect, logicalIndex);
break;
}
}
void QtComponentsHeaderView::mousePressEvent(QMouseEvent* event)
{
int nColumn = logicalIndexAt(event->pos());
if (nColumn < 0 || nColumn >= _view->modelData()->_labels.size())
{
return;
}
Components::TableHeaderType role = _view->modelData()->_labels[nColumn].first;
if ((event->buttons() & Qt::LeftButton))
{
if (Components::hCheckBox == role)
{
if (Qt::Checked == _state)
{
_state = Qt::Unchecked;
}
else
{
_state = Qt::Checked;
}
emit sectionCheckable(_state);
}
if (Components::hSearch == role)
{
_view->showSearch(mapToGlobal(event->pos() + QPoint(-180, 30)));
}
emit sectionClicked(nColumn);
viewport()->update();
}
QHeaderView::mousePressEvent(event);
}
void QtComponentsHeaderView::drawHeaderCheckBox(QPainter *painter, const QRect &rect, int logicalIndex) const
{
painter->save();
QStyleOptionButton option;
int w = rect.x() + 7;
int h = rect.height() / 2 - 7;
option.rect = QRect(w, h, 14, 14);
if (Qt::Checked == _state && !_view->modelData()->_modelData.isEmpty())
option.state = QStyle::State_On;
else
option.state = QStyle::State_Off;
QCheckBox checkBox;
style()->drawPrimitive(QStyle::PE_IndicatorCheckBox, &option, painter, &checkBox);
painter->restore();
}
void QtComponentsHeaderView::drawHeaderText(QPainter *painter, const QRect &rect, int logicalIndex) const
{
painter->save();
painter->drawText(rect.adjusted(7, 0, 0, 0), Qt::AlignLeft | Qt::AlignVCenter, _view->modelData()->_labels[logicalIndex].second);
painter->restore();
if (logicalIndex != (_view->modelData()->_labels.size() - 1))
{
drawCutLine(painter, rect);
}
}
void QtComponentsHeaderView::drawHeaderSort(QPainter *painter, const QRect &rect, int logicalIndex) const
{
painter->save();
drawHeaderText(painter, rect, logicalIndex);
QRect pixmapRect = QRect(rect.x() + QtComponentsTools::inst().fontMetrics(_view->modelData()->_labels[logicalIndex].second).width() + 9, rect.height() / 2 - 20 / 2 + rect.y(), 20, 20);
painter->drawPixmap(pixmapRect, QtComponentsTools::inst().pixmap(QString("table"), QString("sort"), QSize(20, 20)));
painter->restore();
}
void QtComponentsHeaderView::drawHeaderSearch(QPainter *painter, const QRect &rect) const
{
painter->save();
int w = rect.x() + 7;
int h = rect.height() / 2 - 5;
QRect searchRect = QRect(w, h, 24, 24);
painter->drawPixmap(searchRect, QtComponentsTools::inst().pixmap(QString("table"), QString("search"), searchRect.size()));
painter->restore();
}
void QtComponentsHeaderView::drawCutLine(QPainter *painter, const QRect &rect) const
{
painter->save();
QPen pen(QtComponentsTools::inst().getColor("lineColor"));
painter->setPen(pen);
painter->drawLine(rect.topRight(), rect.bottomRight());
painter->restore();
}
QtComponentsTableDelegate::QtComponentsTableDelegate(QtComponentsTableView* view, QObject* parent)
: QStyledItemDelegate(parent)
, _view(view)
{
Q_ASSERT(view);
}
QtComponentsTableDelegate::~QtComponentsTableDelegate()
{
}
QWidget* QtComponentsTableDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
return QStyledItemDelegate::createEditor(parent, option, index);
}
void QtComponentsTableDelegate::setEditorData(QWidget* editor, const QModelIndex& index) const
{
QStyledItemDelegate::setEditorData(editor, index);
}
void QtComponentsTableDelegate::setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const
{
QStyledItemDelegate::setModelData(editor, model, index);
}
void QtComponentsTableDelegate::updateEditorGeometry(QWidget* editor, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
Q_UNUSED(index);
editor->setGeometry(option.rect);
}
void QtComponentsTableDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
if (!index.isValid())
{
return;
}
if (index.row() > _view->model()->rowCount())
{
return;
}
painter->setRenderHint(QPainter::Antialiasing, true);
if (option.state& QStyle::State_Selected)
{
painter->fillRect(option.rect, QBrush(QColor(240, 240, 240)));
}
Components::TableModelType role = static_cast<Components::TableModelType>(index.data(Qt::UserRole).toInt());
switch (role)
{
case Components::Search:
break;
case Components::ID:
break;
case Components::Text:
drawDefText(painter, option, index);
break;
case Components::PointText:
drawPointText(painter, option, index);
break;
case Components::SuccessPointText:
drawSuccessPointText(painter, option, index);
break;
case Components::ErrorPointText:
drawErrorPointText(painter, option, index);
break;
case Components::ColorText:
drawColorText(painter, option, index);
break;
case Components::InitBtn:
drawInitButton(painter, option, index);
break;
case Components::UpdateBtn:
drawUpdateButton(painter, option, index);
break;
case Components::Warn:
drawDefText(painter, option, index);
break;
case Components::BanRun:
drawDefText(painter, option, index);
break;
default:
QStyledItemDelegate::paint(painter, option, index);
break;
}
}
QSize QtComponentsTableDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const
{
return QStyledItemDelegate::sizeHint(option, index);
}
bool QtComponentsTableDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
{
emit clicked(index);
//TODO: add item clicked event
if (Components::InitBtn == index.data(Qt::UserRole).toInt())
{
emit initClicked(_view->modelData(index.row(),1).second);
}
if (Components::UpdateBtn == index.data(Qt::UserRole).toInt())
{
emit updateClicked(_view->modelData(index.row(), 1).second);
}
return QStyledItemDelegate::editorEvent(event, model, option, index);
}
void QtComponentsTableDelegate::drawDefText(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
painter->save();
painter->setFont(index.data(Qt::FontRole).value<QFont>());
QString text = index.data(Qt::EditRole).toString();
QtComponentsTools::inst().splitText(text, option.rect.width(), painter->font());
painter->setPen(QPen(QtComponentsTools::inst().getColor("defTextColor")));
int h = QtComponentsTools::inst().fontMetrics(text).height() / 2;
QPoint leftPoint = QPoint(option.rect.center() - QPoint((option.rect.width() / 2) - COUSTOM_LINEDIT_LEFT_MARGIN, -h + 4));
painter->drawText(leftPoint, text);
painter->restore();
}
void QtComponentsTableDelegate::drawPointText(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
painter->save();
painter->setPen(QtComponentsTools::inst().getColor("pointTextColor"));
painter->setBrush(QtComponentsTools::inst().getColor("pointTextColor"));
painter->drawEllipse(option.rect.topLeft() + QPoint(COUSTOM_LINEDIT_LEFT_MARGIN, option.rect.height() / 2), 2, 2);
painter->restore();
painter->save();
painter->setFont(index.data(Qt::FontRole).value<QFont>());
painter->setPen(index.data(Qt::TextColorRole).value<QColor>());
QString text = index.data(Qt::EditRole).toString();
QtComponentsTools::inst().splitText(text, option.rect.width(), painter->font());
painter->drawText(option.rect.topLeft() + QPoint(COUSTOM_LINEDIT_LEFT_MARGIN + 7, option.rect.height() / 2 + 5),
text);
painter->restore();
}
void QtComponentsTableDelegate::drawSuccessPointText(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
painter->save();
painter->setPen(QtComponentsTools::inst().getColor("successPointTextColor"));
painter->setBrush(QtComponentsTools::inst().getColor("successPointTextColor"));
painter->drawEllipse(option.rect.topLeft() + QPoint(COUSTOM_LINEDIT_LEFT_MARGIN, option.rect.height() / 2), 2, 2);
painter->restore();
painter->save();
painter->setFont(index.data(Qt::FontRole).value<QFont>());
painter->setPen(QtComponentsTools::inst().getColor("successPointTextColor"));
painter->drawText(option.rect.topLeft() + QPoint(COUSTOM_LINEDIT_LEFT_MARGIN + 7, option.rect.height() / 2 + 5),
index.data(Qt::EditRole).toString());
painter->restore();
}
void QtComponentsTableDelegate::drawErrorPointText(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
painter->save();
painter->setPen(QtComponentsTools::inst().getColor("pointTextColor"));
painter->setBrush(QtComponentsTools::inst().getColor("pointTextColor"));
painter->drawEllipse(option.rect.topLeft() + QPoint(COUSTOM_LINEDIT_LEFT_MARGIN, option.rect.height() / 2), 2, 2);
painter->restore();
painter->save();
painter->setFont(index.data(Qt::FontRole).value<QFont>());
painter->setPen(QtComponentsTools::inst().getColor("pointTextColor"));
painter->drawText(option.rect.topLeft() + QPoint(COUSTOM_LINEDIT_LEFT_MARGIN + 7, option.rect.height() / 2 + 5),
index.data(Qt::EditRole).toString());
painter->restore();
}
void QtComponentsTableDelegate::drawWarnIcon(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
}
void QtComponentsTableDelegate::drawBanRunIcon(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
}
void QtComponentsTableDelegate::drawColorText(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
painter->save();
painter->setFont(index.data(Qt::FontRole).value<QFont>());
painter->setPen(Qt::red);
painter->drawText(option.rect.topLeft() + QPoint(COUSTOM_LINEDIT_LEFT_MARGIN, option.rect.height() / 2 + 5),
index.data(Qt::EditRole).toString());
painter->restore();
}
void QtComponentsTableDelegate::drawInitButton(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
painter->save();
QPixmap initPixMap(QtComponentsTools::inst().pixmap(QString("table"),QString("init"),QSize(17,17)));
QPoint iconPoint = QPoint(option.rect.topLeft() + QPoint(COUSTOM_LINEDIT_LEFT_MARGIN, option.rect.height() / 2 - 6));
painter->drawImage(iconPoint, initPixMap.toImage());
painter->restore();
}
void QtComponentsTableDelegate::drawUpdateButton(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
painter->save();
QPixmap initPixMap(QtComponentsTools::inst().pixmap(QString("table"), QString("update"), QSize(17, 17)));
QPoint iconPoint = QPoint(option.rect.topLeft() + QPoint(COUSTOM_LINEDIT_LEFT_MARGIN, option.rect.height() / 2 - 6));
painter->drawImage(iconPoint, initPixMap.toImage());
painter->restore();
}
QtComponentsTableModel::QtComponentsTableModel(QtComponentsTableView* view, QObject* parent)
: QAbstractTableModel(parent)
, _view(view)
{
Q_ASSERT(view);
}
QtComponentsTableModel::~QtComponentsTableModel()
{
}
void QtComponentsTableModel::resetModel(QList<QVector<Components::_TableModelPair> > datas)
{
if (!datas.isEmpty())
{
beginResetModel();
_datas = datas;
endResetModel();
}
else
{
resetModel();
}
}
void QtComponentsTableModel::resetModel()
{
beginResetModel();
_datas.clear();
endResetModel();
}
void QtComponentsTableModel::insertRow(QVector<Components::_TableModelPair>& rows)
{
beginInsertRows(QModelIndex(), _view->modelData()->_modelData.size(), _view->modelData()->_modelData.size());
_datas.push_back(rows);
endInsertRows();
}
void QtComponentsTableModel::removeRow(int row)
{
beginRemoveRows(QModelIndex(), row, row + 1);
_datas.removeAt(row);
endRemoveRows();
}
void QtComponentsTableModel::delCheckBox()
{
QList<QVector<Components::_TableModelPair> >::iterator rowIter = _datas.begin();
QVector<Components::_TableModelPair>::iterator colIter;
for (; rowIter != _datas.end(); ++rowIter)
{
for (colIter = rowIter->begin(); colIter != rowIter->end(); ++colIter)
{
if (Components::Checked == colIter->first)
{
_datas.erase(rowIter == _datas.begin() ? rowIter : rowIter--);
break;
}
}
}
resetModel();
}
void QtComponentsTableModel::clearModel()
{
qobject_cast<QtComponentsHeaderView*>(_view->horizontalHeader())->setCheckable(Qt::Unchecked);
_datas.clear();
}
QList<QVector<Components::_TableModelPair> >& QtComponentsTableModel::datas()
{
return _datas;
}
QVariant QtComponentsTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role == Qt::DisplayRole && orientation == Qt::Horizontal)
{
return _view->headerLabel(section).second;
}
return QAbstractTableModel::headerData(section, orientation, role);
}
bool QtComponentsTableModel::setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role)
{
return QAbstractTableModel::setHeaderData(section,orientation,value,role);
}
int QtComponentsTableModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return _datas.size();
}
int QtComponentsTableModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return _view->modelData()->_labels.size();
}
QVariant QtComponentsTableModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || _view->modelData()->_modelData.isEmpty())
{
return QVariant();
}
if (index.row() > rowCount(index) || index.column() > columnCount(index))
{
return QVariant();
}
Components::TableModelType type = _datas[index.row()][index.column()].first;
switch (role)
{
case Qt::ToolTipRole:
case Qt::DisplayRole:
case Qt::EditRole:
{
return _datas[index.row()][index.column()].second;
}
case Qt::UserRole:
{
return (int)_datas[index.row()][index.column()].first;
}
case Qt::TextAlignmentRole:
{
return QVariant(Qt::AlignLeft | Qt::AlignVCenter);
}
case Qt::FontRole:
{
QFont textFont;
textFont.setPixelSize(12);
return textFont;
}
case Qt::TextColorRole:
{
if (Components::ColorText == type)
{
return QtComponentsTools::inst().getColor("errorColor");
}
else
{
return QtComponentsTools::inst().getColor("successColor");
}
}
case Qt::CheckStateRole:
{
if (Components::Freeze == type)
{
return Qt::Unchecked;
}
return _datas[index.row()][index.column()].first;
}
default:
break;
}
return QVariant();
}
bool QtComponentsTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (!index.isValid())
{
return false;
}
switch (role)
{
case Qt::DisplayRole:
case Qt::EditRole:
{
//TODO:lock edit WT0026
//_view->modelData()->_modelData[index.row()][index.column()].second = value.toString();
}
break;
case Qt::UserRole:
{
//TODO:Lock key WT0026
//_view->modelData()->_modelData[index.row()][index.column()].first = static_cast<Components::TableModelType>(value.toInt());
}
break;
case Qt::CheckStateRole:
{
//TODO:In order to search for loops, there is no good way to sacrifice efficiency.
//TODO: Each time the checkbox is clicked, the data is traversed
//TODO: Currently when searching is data^2 + _data^col waiting for optimization
for (int row = 0; row < _view->modelData()->_modelData.size(); ++row)
{
bool equal = true;
for (int col = 0; col < columnCount(index); ++col)
{
//TODO:Not done when index is checkbox
if (Components::Checked == _view->modelData()->_modelData[row][col].first ||
Components::UnChecked == _view->modelData()->_modelData[row][col].first ||
Components::Freeze == _view->modelData()->_modelData[row][col].first)
{
continue;
}
if (_view->modelData()->_modelData[row][col].first != _datas[index.row()][col].first ||
_view->modelData()->_modelData[row][col].second != _datas[index.row()][col].second)
{
equal = false;
}
}
if (equal)
{
_view->modelData()->_modelData[row][index.column()].first = static_cast<Components::TableModelType>(value.toInt());
}
}
//TODO: search checkstate not selcect
//_view->modelData()->_modelData[index.row() + _view->entry() * _view->page()][index.column()].first = static_cast<Components::TableModelType>(value.toInt());
_datas[index.row()][index.column()].first = static_cast<Components::TableModelType>(value.toInt());
if (Components::Checked == _datas[index.row()][index.column()].first)
{
_view->modelData()->_checkedCount++;
}
else
{
_view->modelData()->_checkedCount--;
}
//TODO:set for title checkstateRole
if (_view->modelData()->checkedCount() > 0)
{
emit sectionCheckable(Qt::Checked);
}
else
{
emit sectionCheckable(Qt::Unchecked);
}
}
break;
default:
break;
}
return true;
}
bool QtComponentsTableModel::removeRows(int row, int count, const QModelIndex &parent)
{
return QAbstractTableModel::removeRows(row, count, parent);
}
bool QtComponentsTableModel::insertRows(int row, int count, const QModelIndex &parent)
{
return QAbstractTableModel::insertRows(row, count, parent);
}
Qt::ItemFlags QtComponentsTableModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
{
return QAbstractTableModel::flags(index);
}
Components::TableModelType role = static_cast<Components::TableModelType>(index.data(Qt::UserRole).toInt());
Qt::ItemFlags flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable;
if (Components::UnChecked == role ||
Components::Checked == role
)
{
return flags |= Qt::ItemIsUserCheckable;
}
if (Components::Search == role ||
Components::ID == role ||
Components::Freeze == role
)
{
return flags |= Qt::NoItemFlags;
}
return flags |= Qt::ItemIsEditable;
}
QtComponentsTableViewMenu::QtComponentsTableViewMenu(QtComponentsTableView* view, QObject* parent)
: QObject(parent)
, _view(view)
{
Q_ASSERT(view);
setupUI();
}
QtComponentsTableViewMenu::~QtComponentsTableViewMenu()
{
}
void QtComponentsTableViewMenu::onShowMenuPos(QPoint p)
{
_viewMenu->exec(QCursor::pos());
}
void QtComponentsTableViewMenu::timerEvent(QTimerEvent *)
{
if (_view->modelData()->_modelData.isEmpty())
{
_beginAct->setEnabled(false);
_prevAct->setEnabled(false);
_nextAct->setEnabled(false);
_endAct->setEnabled(false);
}
else
{
if (0 != _view->pageCount())
{
_beginAct->setEnabled(true);
_endAct->setEnabled(true);
}
else
{
_beginAct->setEnabled(false);
_endAct->setEnabled(false);
}
if (0 == _view->page())
{
_beginAct->setEnabled(false);
_prevAct->setEnabled(false);
}
else
{
_beginAct->setEnabled(true);
_prevAct->setEnabled(true);
}
if (_view->page() == _view->pageCount())
{
_nextAct->setEnabled(false);
_endAct->setEnabled(false);
}
else
{
_nextAct->setEnabled(true);
_endAct->setEnabled(true);
}
}
}
void QtComponentsTableViewMenu::setupUI()
{
_view->setContextMenuPolicy(Qt::CustomContextMenu);
_viewMenu = new QMenu(_view);
_nextAct = new QAction(tr("next"),_view);
_prevAct = new QAction(tr("prev"),_view);
_beginAct = new QAction(tr("begin"), _view);
_endAct = new QAction(tr("end"), _view);
_viewMenu->addAction(_beginAct);
_viewMenu->addAction(_prevAct);
_viewMenu->addAction(_nextAct);
_viewMenu->addAction(_endAct);
connect(_nextAct, SIGNAL(triggered()), _view, SLOT(next()));
connect(_prevAct, SIGNAL(triggered()), _view, SLOT(prev()));
connect(_beginAct, SIGNAL(triggered()), _view, SLOT(begin()));
connect(_endAct, SIGNAL(triggered()), _view, SLOT(end()));
connect(_view, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(onShowMenuPos(QPoint)));
startTimer(100);
}
| 30.936424 | 188 | 0.653765 | jhupo |
73d8338aff8e61fb924454a249948f1a31453eaf | 2,126 | cpp | C++ | Evil Space/Random.cpp | Cellyceos/Evil-Space | 0c153d07855aa7ae2bd5e47e7ae95d78ba01ee9d | [
"MIT"
] | null | null | null | Evil Space/Random.cpp | Cellyceos/Evil-Space | 0c153d07855aa7ae2bd5e47e7ae95d78ba01ee9d | [
"MIT"
] | null | null | null | Evil Space/Random.cpp | Cellyceos/Evil-Space | 0c153d07855aa7ae2bd5e47e7ae95d78ba01ee9d | [
"MIT"
] | 2 | 2020-03-29T12:32:51.000Z | 2021-03-14T09:18:32.000Z | #include "stdafx.h"
#include "Random.h"
using namespace std;
Random::Random()
{
SeedGeneration(GetTickCount());
}
Random::Random(int seed)
{
SeedGeneration(seed);
}
Random::~Random()
{
delete SeedArray;
}
void Random::SeedGeneration(int seed)
{
SeedArray = new int[56];
int num2 = 161803398 - abs(seed);
SeedArray[55] = num2;
int num3 = 1;
for (int i = 1; i < 55; i++)
{
int index = (21 * i) % 55;
SeedArray[index] = num3;
num3 = num2 - num3;
if (num3 < 0)
{
num3 += 2147483647;
}
num2 = SeedArray[index];
}
for (int j = 1; j < 5; j++)
{
for (int k = 1; k < 56; k++)
{
SeedArray[k] -= SeedArray[1 + ((k + 30) % 55)];
if (SeedArray[k] < 0)
{
SeedArray[k] += 2147483647;
}
}
}
inext = 0;
inextp = 21;
seed = 1;
}
double Random::GetSampleForLargeRange()
{
int num = InternalSample();
if ((((InternalSample() % 2) == 0) ? 1 : 0) != 0)
{
num = -num;
}
double num2 = num;
num2 += 2147483646.0;
return (num2 / 4294967293);
}
int Random::InternalSample()
{
int next = inext;
int nextp = inextp;
if (++next >= 56)
{
next = 1;
}
if (++nextp >= 56)
{
nextp = 1;
}
int num = SeedArray[next] - SeedArray[nextp];
if (num < 0)
{
num += 2147483647;
}
SeedArray[next] = num;
inext = next;
inextp = nextp;
return num;
}
int Random::Next()
{
return InternalSample();
}
int Random::Next(int maxValue)
{
return (int) (Sample() * maxValue);
}
float Random::Next(float maxValue)
{
return (float)(Sample() * maxValue);
}
int Random::Next(int minValue, int maxValue)
{
long num = maxValue - minValue;
if (num <= 2147483647L)
{
return (((int) (Sample() * num)) + minValue);
}
return (((int) ((long) (GetSampleForLargeRange() * num))) + minValue);
}
float Random::Next(float minValue, float maxValue)
{
double num = maxValue - minValue;
if (num <= 2147483647.0)
{
return (((float) (Sample() * num)) + minValue);
}
return (((float) ((double) (GetSampleForLargeRange() * num))) + minValue);
}
double Random::NextDouble()
{
return Sample();
}
double Random::Sample()
{
return (InternalSample() * 4.6566128752457969E-10);
}
| 14.561644 | 75 | 0.596896 | Cellyceos |
73d90fb54691a16837998b12599c69282956f24f | 2,114 | cpp | C++ | src/xray/maya_animation/sources/sisl/s1350.cpp | ixray-team/ixray-2.0 | 85c3a544175842323fc82f42efd96c66f0fc5abb | [
"Linux-OpenIB"
] | 3 | 2021-10-30T09:36:14.000Z | 2022-03-26T17:00:06.000Z | src/xray/maya_animation/sources/sisl/s1350.cpp | acidicMercury8/ixray-2.0 | 85c3a544175842323fc82f42efd96c66f0fc5abb | [
"Linux-OpenIB"
] | null | null | null | src/xray/maya_animation/sources/sisl/s1350.cpp | acidicMercury8/ixray-2.0 | 85c3a544175842323fc82f42efd96c66f0fc5abb | [
"Linux-OpenIB"
] | 1 | 2022-03-26T17:00:08.000Z | 2022-03-26T17:00:08.000Z | #include "pch.h"
#define S1350
#include "sislP.h"
#if defined(SISLNEEDPROTOTYPES)
void s1350(sisl_double ep[],sisl_double epar[],
int im,int idim,int ik,
SISLCurve **rc, int *jstat)
#else
void s1350(ep,epar,im,idim,ik,rc,jstat)
sisl_double ep[];
sisl_double epar[];
int im;
int idim;
int ik;
SISLCurve **rc;
int *jstat;
#endif
{
int i, j, k;
int kic, kit, kw1, kw2;
sisl_double ts = xray::memory::uninitialized_value<sisl_double>(), tw1, tw2;
int kpos = 0;
int in;
int jidim;
int jidimp1;
sisl_double *et = SISL_NULL;
sisl_double *ec = SISL_NULL;
sisl_double ikinv;
int kclosed;
if (im < 2 || idim < 1 || ik < 2) goto err103;
in = (ik-1)*im + 2 - ik;
et = newarray(in+ik, sisl_double);
ec = newarray(in*idim, sisl_double);
if (et==SISL_NULL || ec == SISL_NULL) goto err101;
ikinv = sisl_double(1.)/(ik-1);
for(i=0; i<ik; i++)
et[i] = epar[0];
for(i=0; i<idim; i++)
ec[i] = ep[i];
kic = idim;
kit = ik;
for(j=0, jidim=0, jidimp1=idim; j<im-1; j++, jidim+=idim,
jidimp1+=idim)
{
ts = epar[j+1];
kw1 = ik-1;
kw2 = 0;
for (i=1; i<ik; i++)
{
et[kit] = ts;
kit++;
kw1--;
kw2++;
tw1 = kw1*ikinv;
tw2 = kw2*ikinv;
for (k=0; k<idim; k++)
ec[kic + k] = tw1*ep[jidim + k] +
tw2*ep[jidimp1 + k];
kic += idim;
}
}
et[kit] = ts;
if ((*rc = newCurve(in,ik,et,ec,1,idim,2)) == SISL_NULL)
goto err101;
for (kclosed=1, i=0; i<idim; i++)
if (DNEQUAL(ep[i], ep[(im-1)*idim+i])) kclosed = 0;
if (kclosed) (*rc)->cuopen = SISL_CRV_CLOSED;
*jstat = 0;
goto out;
err101 :
*jstat = -101;
if (et != SISL_NULL) freearray(et);
if (ec != SISL_NULL) freearray(ec);
goto out;
err103:
*jstat = -103;
s6err("s1350",*jstat,kpos);
goto out;
out:
return;
}
| 17.186992 | 89 | 0.486282 | ixray-team |
73da0859e3f717bfd9a9b7d5b02790781db4b14d | 5,013 | cpp | C++ | src/Domain/Creators/Cylinder.cpp | tomwlodarczyk/spectre | 086aaee002f2f07eb812cf17b8e1ba54052feb71 | [
"MIT"
] | null | null | null | src/Domain/Creators/Cylinder.cpp | tomwlodarczyk/spectre | 086aaee002f2f07eb812cf17b8e1ba54052feb71 | [
"MIT"
] | null | null | null | src/Domain/Creators/Cylinder.cpp | tomwlodarczyk/spectre | 086aaee002f2f07eb812cf17b8e1ba54052feb71 | [
"MIT"
] | 1 | 2019-01-03T21:47:04.000Z | 2019-01-03T21:47:04.000Z | // Distributed under the MIT License.
// See LICENSE.txt for details.
#include "Domain/Creators/Cylinder.hpp"
#include <array>
#include <cmath>
#include <memory>
#include <unordered_map>
#include <vector>
#include "Domain/Creators/DomainCreator.hpp" // IWYU pragma: keep
#include "Domain/Domain.hpp"
#include "Domain/DomainHelpers.hpp"
#include "Utilities/MakeArray.hpp"
namespace Frame {
struct Logical;
struct Inertial;
} // namespace Frame
namespace domain::creators {
Cylinder::Cylinder(
typename InnerRadius::type inner_radius,
typename OuterRadius::type outer_radius,
typename LowerBound::type lower_bound,
typename UpperBound::type upper_bound,
typename IsPeriodicInZ::type is_periodic_in_z,
typename InitialRefinement::type initial_refinement,
typename InitialGridPoints::type initial_number_of_grid_points,
typename UseEquiangularMap::type use_equiangular_map,
typename RadialPartitioning::type radial_partitioning,
typename HeightPartitioning::type height_partitioning) noexcept
// clang-tidy: trivially copyable
: inner_radius_(std::move(inner_radius)), // NOLINT
outer_radius_(std::move(outer_radius)), // NOLINT
lower_bound_(std::move(lower_bound)), // NOLINT
upper_bound_(std::move(upper_bound)), // NOLINT
is_periodic_in_z_(std::move(is_periodic_in_z)), // NOLINT
initial_refinement_( // NOLINT
std::move(initial_refinement)), // NOLINT
initial_number_of_grid_points_( // NOLINT
std::move(initial_number_of_grid_points)), // NOLINT
use_equiangular_map_(use_equiangular_map), // NOLINT
radial_partitioning_(std::move(radial_partitioning)), // NOLINT
height_partitioning_(std::move(height_partitioning)) {}
Domain<3> Cylinder::create_domain() const noexcept {
const size_t number_of_shells = 1 + radial_partitioning_.size();
const size_t number_of_discs = 1 + height_partitioning_.size();
std::vector<PairOfFaces> pairs_of_faces{};
if (is_periodic_in_z_) {
// connect faces of end caps in the periodic z-direction
const size_t corners_per_layer = 4 * (number_of_shells + 1);
const size_t num_corners = number_of_discs * corners_per_layer;
PairOfFaces center{
{0, 1, 2, 3},
{num_corners + 0, num_corners + 1, num_corners + 2, num_corners + 3}};
pairs_of_faces.push_back(std::move(center));
for (size_t j = 0; j < number_of_shells; j++) {
PairOfFaces east{{1 + 4 * j, 5 + 4 * j, 3 + 4 * j, 7 + 4 * j},
{num_corners + 4 * j + 1, num_corners + 4 * j + 5,
num_corners + 4 * j + 3, num_corners + 4 * j + 7}};
PairOfFaces north{{3 + 4 * j, 7 + 4 * j, 2 + 4 * j, 6 + 4 * j},
{num_corners + 4 * j + 3, num_corners + 4 * j + 7,
num_corners + 4 * j + 2, num_corners + 4 * j + 6}};
PairOfFaces west{{2 + 4 * j, 6 + 4 * j, 0 + 4 * j, 4 + 4 * j},
{num_corners + 4 * j + 2, num_corners + 4 * j + 6,
num_corners + 4 * j + 0, num_corners + 4 * j + 4}};
PairOfFaces south{{0 + 4 * j, 4 + 4 * j, 1 + 4 * j, 5 + 4 * j},
{num_corners + 4 * j + 0, num_corners + 4 * j + 4,
num_corners + 4 * j + 1, num_corners + 4 * j + 5}};
pairs_of_faces.push_back(std::move(east));
pairs_of_faces.push_back(std::move(north));
pairs_of_faces.push_back(std::move(west));
pairs_of_faces.push_back(std::move(south));
}
}
return Domain<3>{
cyl_wedge_coordinate_maps<Frame::Inertial>(
inner_radius_, outer_radius_, lower_bound_, upper_bound_,
use_equiangular_map_, radial_partitioning_, height_partitioning_),
corners_for_cylindrical_layered_domains(number_of_shells,
number_of_discs),
pairs_of_faces};
}
std::vector<std::array<size_t, 3>> Cylinder::initial_extents() const noexcept {
std::vector<std::array<size_t, 3>> gridpoints_vector;
for (size_t layer = 0; layer < 1 + height_partitioning_.size(); layer++) {
gridpoints_vector.push_back({{initial_number_of_grid_points_.at(1),
initial_number_of_grid_points_.at(1),
initial_number_of_grid_points_.at(2)}});
for (size_t shell = 0; shell < 1 + radial_partitioning_.size(); shell++) {
for (size_t face = 0; face < 4; face++) {
gridpoints_vector.push_back(initial_number_of_grid_points_);
}
}
}
return gridpoints_vector;
}
std::vector<std::array<size_t, 3>> Cylinder::initial_refinement_levels() const
noexcept {
return {(1 + 4 * (1 + radial_partitioning_.size())) *
(1 + height_partitioning_.size()),
make_array<3>(initial_refinement_)};
}
} // namespace domain::creators
| 45.572727 | 79 | 0.620786 | tomwlodarczyk |
73dacf82bad5f57ee466d07246f547adced7b4e2 | 19 | cpp | C++ | Mantle/Source/mtlpch.cpp | AiManti1/Graphics | 050816bf16202b09440412314338373a4d0d6c04 | [
"Apache-2.0"
] | null | null | null | Mantle/Source/mtlpch.cpp | AiManti1/Graphics | 050816bf16202b09440412314338373a4d0d6c04 | [
"Apache-2.0"
] | null | null | null | Mantle/Source/mtlpch.cpp | AiManti1/Graphics | 050816bf16202b09440412314338373a4d0d6c04 | [
"Apache-2.0"
] | null | null | null | #include "mtlpch.h" | 19 | 19 | 0.736842 | AiManti1 |
73de25216439e8b17bb864db8dcabf0326775582 | 6,610 | hpp | C++ | posu/units/system/si/length.hpp | zhu48/posu | 4872bd7572485c1c352aaf5db7a99d578a682113 | [
"MIT"
] | null | null | null | posu/units/system/si/length.hpp | zhu48/posu | 4872bd7572485c1c352aaf5db7a99d578a682113 | [
"MIT"
] | 33 | 2020-12-14T02:50:22.000Z | 2022-03-08T03:20:15.000Z | posu/units/system/si/length.hpp | zhu48/posu | 4872bd7572485c1c352aaf5db7a99d578a682113 | [
"MIT"
] | null | null | null | #ifndef POSU_UNITS_SI_LENGTH_HPP
#define POSU_UNITS_SI_LENGTH_HPP
#include "posu/units/base_unit.hpp"
#include "posu/units/system/length.hpp"
namespace posu::units::si {
struct length : public posu::units::length {
using type = length;
using kind_type = posu::units::length;
using period = std::ratio<1>;
};
} // namespace posu::units::si
namespace posu::units {
template<>
inline constexpr bool enable_as_unit<si::length> = true;
}
namespace posu::units::si {
template<typename Rep, typename Period>
using basic_meter = quantity<Rep, Period, length>;
using attometers = basic_meter<int, std::atto>;
using femtometers = basic_meter<int, std::femto>;
using picometers = basic_meter<int, std::pico>;
using nanometers = basic_meter<int, std::nano>;
using micrometers = basic_meter<int, std::micro>;
using millimeters = basic_meter<int, std::milli>;
using centimeters = basic_meter<int, std::centi>;
using decimeters = basic_meter<int, std::deci>;
using meters = basic_meter<int, std::ratio<1>>;
using decameters = basic_meter<int, std::deca>;
using hectometers = basic_meter<int, std::hecto>;
using kilometers = basic_meter<int, std::kilo>;
using megameters = basic_meter<int, std::mega>;
using gigameters = basic_meter<int, std::giga>;
using terameters = basic_meter<int, std::tera>;
using petameters = basic_meter<int, std::peta>;
using exameters = basic_meter<int, std::exa>;
inline namespace literals {
inline namespace length_literals {
[[nodiscard]] constexpr auto operator""_am(unsigned long long value) -> attometers;
[[nodiscard]] constexpr auto operator""_am(long double value)
-> basic_meter<double, std::atto>;
[[nodiscard]] constexpr auto operator""_fm(unsigned long long value) -> femtometers;
[[nodiscard]] constexpr auto operator""_fm(long double value)
-> basic_meter<double, std::femto>;
[[nodiscard]] constexpr auto operator""_pm(unsigned long long value) -> picometers;
[[nodiscard]] constexpr auto operator""_pm(long double value)
-> basic_meter<double, std::pico>;
[[nodiscard]] constexpr auto operator""_nm(unsigned long long value) -> nanometers;
[[nodiscard]] constexpr auto operator""_nm(long double value)
-> basic_meter<double, std::nano>;
[[nodiscard]] constexpr auto operator""_um(unsigned long long value) -> micrometers;
[[nodiscard]] constexpr auto operator""_um(long double value)
-> basic_meter<double, std::micro>;
[[nodiscard]] constexpr auto operator""_mm(unsigned long long value) -> millimeters;
[[nodiscard]] constexpr auto operator""_mm(long double value)
-> basic_meter<double, std::milli>;
[[nodiscard]] constexpr auto operator""_cm(unsigned long long value) -> centimeters;
[[nodiscard]] constexpr auto operator""_cm(long double value)
-> basic_meter<double, std::centi>;
[[nodiscard]] constexpr auto operator""_dm(unsigned long long value) -> decimeters;
[[nodiscard]] constexpr auto operator""_dm(long double value)
-> basic_meter<double, std::deci>;
[[nodiscard]] constexpr auto operator""_m(unsigned long long value) -> meters;
[[nodiscard]] constexpr auto operator""_m(long double value)
-> basic_meter<double, std::ratio<1>>;
[[nodiscard]] constexpr auto operator""_dam(unsigned long long value) -> decameters;
[[nodiscard]] constexpr auto operator""_dam(long double value)
-> basic_meter<double, std::deca>;
[[nodiscard]] constexpr auto operator""_hm(unsigned long long value) -> hectometers;
[[nodiscard]] constexpr auto operator""_hm(long double value)
-> basic_meter<double, std::hecto>;
[[nodiscard]] constexpr auto operator""_km(unsigned long long value) -> kilometers;
[[nodiscard]] constexpr auto operator""_km(long double value)
-> basic_meter<double, std::kilo>;
[[nodiscard]] constexpr auto operator""_Mm(unsigned long long value) -> megameters;
[[nodiscard]] constexpr auto operator""_Mm(long double value)
-> basic_meter<double, std::mega>;
[[nodiscard]] constexpr auto operator""_Gm(unsigned long long value) -> gigameters;
[[nodiscard]] constexpr auto operator""_Gm(long double value)
-> basic_meter<double, std::giga>;
[[nodiscard]] constexpr auto operator""_Tm(unsigned long long value) -> terameters;
[[nodiscard]] constexpr auto operator""_Tm(long double value)
-> basic_meter<double, std::tera>;
[[nodiscard]] constexpr auto operator""_Pm(unsigned long long value) -> petameters;
[[nodiscard]] constexpr auto operator""_Pm(long double value)
-> basic_meter<double, std::peta>;
[[nodiscard]] constexpr auto operator""_Em(unsigned long long value) -> exameters;
[[nodiscard]] constexpr auto operator""_Em(long double value)
-> basic_meter<double, std::exa>;
} // namespace length_literals
} // namespace literals
using namespace literals::length_literals;
} // namespace posu::units::si
#include "posu/units/system/si/ipp/length.ipp"
namespace posu::units::si {
inline namespace references {
inline namespace length_references {
inline constexpr auto am = 1_am;
inline constexpr auto fm = 1_fm;
inline constexpr auto pm = 1_pm;
inline constexpr auto nm = 1_nm;
inline constexpr auto um = 1_um;
inline constexpr auto mm = 1_mm;
inline constexpr auto cm = 1_cm;
inline constexpr auto dm = 1_dm;
inline constexpr auto m = 1_m;
inline constexpr auto dam = 1_dam;
inline constexpr auto hm = 1_hm;
inline constexpr auto km = 1_km;
inline constexpr auto Mm = 1_Mm;
inline constexpr auto Gm = 1_Gm;
inline constexpr auto Tm = 1_Tm;
inline constexpr auto Pm = 1_Pm;
inline constexpr auto Em = 1_Em;
} // namespace length_references
} // namespace references
} // namespace posu::units::si
#endif // #ifndef POSU_UNITS_SI_LENGTH_HPP
| 45.586207 | 96 | 0.626929 | zhu48 |
73e0230b560b6ddb53e4e17bac6c277a9bb535d4 | 5,264 | cpp | C++ | rpgtools/common/util.cpp | lfairy/rpgtools | ccfa607e93c85db062185d8ca85d0f637f00c2fa | [
"MIT"
] | null | null | null | rpgtools/common/util.cpp | lfairy/rpgtools | ccfa607e93c85db062185d8ca85d0f637f00c2fa | [
"MIT"
] | null | null | null | rpgtools/common/util.cpp | lfairy/rpgtools | ccfa607e93c85db062185d8ca85d0f637f00c2fa | [
"MIT"
] | null | null | null | #include "util.h"
#if defined OS_W32
#include <shellapi.h>
#elif defined OS_UNIX
#include <sys/types.h>
#include <sys/stat.h>
#include <ftw.h>
#include <dirent.h>
#include <unistd.h>
#endif
#include <stdexcept>
#include <algorithm>
#include <cassert>
namespace Util
{
/* PRIVATE FUNCS */
static inline bool isDotOrDotDot(const unichar *str)
{
if (str[0] == '.') {
if (str[1] == 0)
return true;
if (str[1] == '.' && str[2] == 0)
return true;
}
return false;
}
#if defined OS_W32
FILE *fopen(const std::string &str, const unichar *args)
{
return _wfopen(W32::toWide(str).c_str(), const_cast<const WCHAR*>(args));
}
void mkdir(const std::string &dirname)
{
CreateDirectoryW(W32::toWide(dirname).c_str(), NULL);
}
void mkdirsForFile(const std::string &filename)
{
std::wstring tmp = W32::toWide(filename);
for (unsigned int i = 0; i < tmp.size(); ++i) {
if (tmp[i] == '\\' || tmp[i] == '/') {
tmp[i] = 0;
CreateDirectoryW(tmp.c_str(), NULL);
tmp[i] = '\\';
}
}
}
bool dirExists(const std::string &dirname)
{
DWORD attrib = GetFileAttributesW(W32::toWide(dirname).c_str());
return attrib != INVALID_FILE_ATTRIBUTES && (attrib & FILE_ATTRIBUTE_DIRECTORY);
}
std::vector<std::string> listFiles(const std::string &path)
{
assert(*path.rbegin() == PATH_SEPARATOR[0]);
WIN32_FIND_DATAW fd;
HANDLE hFind = NULL;
std::vector<std::string> list;
if ((hFind = FindFirstFileW(W32::toWide(path + "*").c_str(), &fd)) == INVALID_HANDLE_VALUE)
throw std::runtime_error(path + ": could not list files");
do {
if (!isDotOrDotDot(fd.cFileName))
list.push_back(W32::fromWide(fd.cFileName));
} while(FindNextFileW(hFind, &fd));
FindClose(hFind);
return list;
}
size_t getFileSize(const std::string &filename)
{
//TODO getFileSize windows
HANDLE hFile = CreateFileW(W32::toWide(filename).c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
return 0;
LARGE_INTEGER size;
if (!GetFileSizeEx(hFile, &size)) {
CloseHandle(hFile);
return 0;
}
CloseHandle(hFile);
return static_cast<size_t>(size.QuadPart);
}
void deleteFile(const std::string &filename)
{
DeleteFileW(W32::toWide(filename).c_str());
}
void deleteFolder(const std::string &filename)
{
std::wstring wfilename = W32::toWide(filename);
SHFILEOPSTRUCTW ops = {
0,
FO_DELETE,
wfilename.c_str(),
NULL,
FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT,
FALSE,
NULL,
NULL,
};
SHFileOperationW(&ops);
}
#elif defined OS_UNIX
FILE *fopen(const std::string &str, const unichar *ops)
{
return ::fopen(str.c_str(), const_cast<const char*>(ops));
}
void mkdir(const std::string &filename)
{
::mkdir(filename.c_str(), 0777);
}
void mkdirsForFile(const std::string &filename)
{
std::string tmp = filename;
for (unsigned int i = 0; i < tmp.size(); ++i) {
if (tmp[i] == '/') {
tmp[i] = 0;
::mkdir(tmp.c_str(), 0777);
tmp[i] = '/';
}
}
}
bool dirExists(const std::string &dirname)
{
struct stat st;
return stat(dirname.c_str(), &st) == 0 && S_ISDIR(st.st_mode);
}
std::vector<std::string> listFiles(const std::string &path)
{
assert(*path.rbegin() == PATH_SEPARATOR[0]);
std::vector<std::string> list;
DIR *dp = opendir(path.c_str());
if (dp == NULL)
throw std::runtime_error(path + ": could not list files");
//Populate list
dirent *ep;
while ((ep = readdir(dp)) != NULL) {
//TODO OS X UTF-8 conversion!
if (!isDotOrDotDot(ep->d_name))
list.push_back(ep->d_name);
}
closedir(dp);
return list;
}
size_t getFileSize(const std::string &filename)
{
struct stat st;
stat(filename.c_str(), &st);
return st.st_size;
}
void deleteFile(const std::string &filename)
{
unlink(filename.c_str());
}
int deleteFolder_func(const char *filename, const struct stat *st, int flags, struct FTW *fwt)
{
UNUSED(st);
UNUSED(flags);
UNUSED(fwt);
return remove(filename);
}
void deleteFolder(const std::string &filename)
{
nftw(filename.c_str(), deleteFolder_func, 64, FTW_DEPTH | FTW_PHYS);
}
#endif
std::string toLower(std::string str)
{
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
return str;
}
std::string getExtension(const std::string &filename)
{
size_t dot = filename.rfind('.');
if (dot == std::string::npos)
return "";
return Util::toLower(filename.substr(dot + 1));
}
std::string getWithoutExtension(const std::string &filename)
{
size_t dot = filename.rfind('.');
if (dot == std::string::npos)
return filename;
return filename.substr(0, dot);
}
std::string readFileContents(const std::string &filename)
{
size_t size = Util::getFileSize(filename);
ifstream file(filename.c_str());
std::vector<char> data(size);
file.read(data.data(), size);
return std::string(data.begin(), data.end());
}
}
| 23.605381 | 111 | 0.615502 | lfairy |
73e053b5d6f73d41552c65e5a4176f8332d9a4a2 | 6,381 | cc | C++ | Boss2D/addon/_old/webrtc-qt5.11.2_for_boss/modules/audio_processing/transient/file_utils.cc | Yash-Wasalwar-07/Boss2D | 37c5ba0f1c83c89810359a207cabfa0905f803d2 | [
"MIT"
] | null | null | null | Boss2D/addon/_old/webrtc-qt5.11.2_for_boss/modules/audio_processing/transient/file_utils.cc | Yash-Wasalwar-07/Boss2D | 37c5ba0f1c83c89810359a207cabfa0905f803d2 | [
"MIT"
] | null | null | null | Boss2D/addon/_old/webrtc-qt5.11.2_for_boss/modules/audio_processing/transient/file_utils.cc | Yash-Wasalwar-07/Boss2D | 37c5ba0f1c83c89810359a207cabfa0905f803d2 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "modules/audio_processing/transient/file_utils.h"
#include <memory>
#include BOSS_WEBRTC_U_system_wrappers__include__file_wrapper_h //original-code:"system_wrappers/include/file_wrapper.h"
#include BOSS_WEBRTC_U_typedefs_h //original-code:"typedefs.h" // NOLINT(build/include)
namespace webrtc {
int ConvertByteArrayToFloat(const uint8_t bytes[4], float* out) {
if (!bytes || !out) {
return -1;
}
uint32_t binary_value = 0;
for (int i = 3; i >= 0; --i) {
binary_value <<= 8;
binary_value += bytes[i];
}
*out = bit_cast<float>(binary_value);
return 0;
}
int ConvertByteArrayToDouble(const uint8_t bytes[8], double* out) {
if (!bytes || !out) {
return -1;
}
uint64_t binary_value = 0;
for (int i = 7; i >= 0; --i) {
binary_value <<= 8;
binary_value += bytes[i];
}
*out = bit_cast<double>(binary_value);
return 0;
}
int ConvertFloatToByteArray(float value, uint8_t out_bytes[4]) {
if (!out_bytes) {
return -1;
}
uint32_t binary_value = bit_cast<uint32_t>(value);
for (size_t i = 0; i < 4; ++i) {
out_bytes[i] = binary_value;
binary_value >>= 8;
}
return 0;
}
int ConvertDoubleToByteArray(double value, uint8_t out_bytes[8]) {
if (!out_bytes) {
return -1;
}
uint64_t binary_value = bit_cast<uint64_t>(value);
for (size_t i = 0; i < 8; ++i) {
out_bytes[i] = binary_value;
binary_value >>= 8;
}
return 0;
}
size_t ReadInt16BufferFromFile(FileWrapper* file,
size_t length,
int16_t* buffer) {
if (!file || !file->is_open() || !buffer || length <= 0) {
return 0;
}
std::unique_ptr<uint8_t[]> byte_array(new uint8_t[2]);
size_t int16s_read = 0;
while (int16s_read < length) {
size_t bytes_read = file->Read(byte_array.get(), 2);
if (bytes_read < 2) {
break;
}
int16_t value = byte_array[1];
value <<= 8;
value += byte_array[0];
buffer[int16s_read] = value;
++int16s_read;
}
return int16s_read;
}
size_t ReadInt16FromFileToFloatBuffer(FileWrapper* file,
size_t length,
float* buffer) {
if (!file || !file->is_open() || !buffer || length <= 0) {
return 0;
}
std::unique_ptr<int16_t[]> buffer16(new int16_t[length]);
size_t int16s_read = ReadInt16BufferFromFile(file, length, buffer16.get());
for (size_t i = 0; i < int16s_read; ++i) {
buffer[i] = buffer16[i];
}
return int16s_read;
}
size_t ReadInt16FromFileToDoubleBuffer(FileWrapper* file,
size_t length,
double* buffer) {
if (!file || !file->is_open() || !buffer || length <= 0) {
return 0;
}
std::unique_ptr<int16_t[]> buffer16(new int16_t[length]);
size_t int16s_read = ReadInt16BufferFromFile(file, length, buffer16.get());
for (size_t i = 0; i < int16s_read; ++i) {
buffer[i] = buffer16[i];
}
return int16s_read;
}
size_t ReadFloatBufferFromFile(FileWrapper* file,
size_t length,
float* buffer) {
if (!file || !file->is_open() || !buffer || length <= 0) {
return 0;
}
std::unique_ptr<uint8_t[]> byte_array(new uint8_t[4]);
size_t floats_read = 0;
while (floats_read < length) {
size_t bytes_read = file->Read(byte_array.get(), 4);
if (bytes_read < 4) {
break;
}
ConvertByteArrayToFloat(byte_array.get(), &buffer[floats_read]);
++floats_read;
}
return floats_read;
}
size_t ReadDoubleBufferFromFile(FileWrapper* file,
size_t length,
double* buffer) {
if (!file || !file->is_open() || !buffer || length <= 0) {
return 0;
}
std::unique_ptr<uint8_t[]> byte_array(new uint8_t[8]);
size_t doubles_read = 0;
while (doubles_read < length) {
size_t bytes_read = file->Read(byte_array.get(), 8);
if (bytes_read < 8) {
break;
}
ConvertByteArrayToDouble(byte_array.get(), &buffer[doubles_read]);
++doubles_read;
}
return doubles_read;
}
size_t WriteInt16BufferToFile(FileWrapper* file,
size_t length,
const int16_t* buffer) {
if (!file || !file->is_open() || !buffer || length <= 0) {
return 0;
}
std::unique_ptr<uint8_t[]> byte_array(new uint8_t[2]);
size_t int16s_written = 0;
for (int16s_written = 0; int16s_written < length; ++int16s_written) {
// Get byte representation.
byte_array[0] = buffer[int16s_written] & 0xFF;
byte_array[1] = (buffer[int16s_written] >> 8) & 0xFF;
file->Write(byte_array.get(), 2);
}
file->Flush();
return int16s_written;
}
size_t WriteFloatBufferToFile(FileWrapper* file,
size_t length,
const float* buffer) {
if (!file || !file->is_open() || !buffer || length <= 0) {
return 0;
}
std::unique_ptr<uint8_t[]> byte_array(new uint8_t[4]);
size_t floats_written = 0;
for (floats_written = 0; floats_written < length; ++floats_written) {
// Get byte representation.
ConvertFloatToByteArray(buffer[floats_written], byte_array.get());
file->Write(byte_array.get(), 4);
}
file->Flush();
return floats_written;
}
size_t WriteDoubleBufferToFile(FileWrapper* file,
size_t length,
const double* buffer) {
if (!file || !file->is_open() || !buffer || length <= 0) {
return 0;
}
std::unique_ptr<uint8_t[]> byte_array(new uint8_t[8]);
size_t doubles_written = 0;
for (doubles_written = 0; doubles_written < length; ++doubles_written) {
// Get byte representation.
ConvertDoubleToByteArray(buffer[doubles_written], byte_array.get());
file->Write(byte_array.get(), 8);
}
file->Flush();
return doubles_written;
}
} // namespace webrtc
| 24.637066 | 120 | 0.605861 | Yash-Wasalwar-07 |
73e1017d4be186a4865b9335a395010020a78fad | 685 | cpp | C++ | thinking-in-cpp/code/2-6-algorithm2.cpp | liphx/cplusplus | 65df073dc92fa58947e5ff728fc63db839e12760 | [
"MIT"
] | null | null | null | thinking-in-cpp/code/2-6-algorithm2.cpp | liphx/cplusplus | 65df073dc92fa58947e5ff728fc63db839e12760 | [
"MIT"
] | null | null | null | thinking-in-cpp/code/2-6-algorithm2.cpp | liphx/cplusplus | 65df073dc92fa58947e5ff728fc63db839e12760 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
template<typename T>
void print(vector<T>& data){
for(auto x: data){
cout << x << " ";
}
cout << endl;
}
int main()
{
vector<int>data(10);
//填充
fill(data.begin(), data.end(), 7);
print(data);
//=>7 7 7 7 7 7 7 7 7 7
//填充前n个
fill_n(data.begin(), 5, 3);
print(data);
//=>3 3 3 3 3 7 7 7 7 7
//生成
generate(data.begin(), data.end(), [](){ return rand() % 10; } );
print(data);
//=>3 6 7 5 3 5 6 2 9 1
//生成前n个
generate_n(data.begin()+2, 5, [](){ return -1;});
print(data);
//=>3 6 -1 -1 -1 -1 -1 2 9 1
return 0;
} | 19.027778 | 69 | 0.50219 | liphx |
73e2f14b884ec309789055c7348f945d1c8a5466 | 9,390 | cpp | C++ | robot-server/videocontrol.cpp | LejuRobotics/Aelos-Vision-Demo | 0b4ad1338bd018e8107533a7164d00442ff1d394 | [
"Apache-2.0"
] | 6 | 2018-10-23T07:28:35.000Z | 2020-02-06T02:19:40.000Z | robot-server/videocontrol.cpp | LejuRobotics/Aelos-Vision-Demo | 0b4ad1338bd018e8107533a7164d00442ff1d394 | [
"Apache-2.0"
] | null | null | null | robot-server/videocontrol.cpp | LejuRobotics/Aelos-Vision-Demo | 0b4ad1338bd018e8107533a7164d00442ff1d394 | [
"Apache-2.0"
] | 3 | 2018-12-25T08:34:15.000Z | 2020-04-16T07:03:00.000Z | /**
* @file VideoControl.cpp
* @version 1.0
* @date 2017年07月08日
* @author C_Are
* @copyright Leju
*
* @brief 接收摄像头图像,VideoControl类的cpp文件
*/
#include "VideoControl.h"
/**
* @brief VideoControl类的构造函数
* @param parent 父对象
*/
VideoControl::VideoControl(QObject *parent) : QThread(parent)
{
isPause = false;
isSendFrame = true;
alpha = 1.0;
beta = 0;
qRegisterMetaType<QImage>("QImage&");
}
/**
* @brief VideoControl类的析构函数
* @details 关闭并销毁线程,等待1秒,否则强制关闭
*/
VideoControl::~VideoControl()
{
isPause = true;
if (udpSocket != NULL)
{
delete udpSocket;
}
this->quit();
if (!this->wait(1000))
{
this->terminate();
}
}
/**
* @brief 准备向已连接的客户端发送摄像头图像
* @param ip 客户端ip地址
*/
void VideoControl::openUrl(const QString &ip)
{
m_client_ip = ip;
isPause = false;
isSendFrame = true;
if (!this->isRunning())
{
this->start(); //开启线程,进入run()函数
}
}
/**
* @brief 停止向客户端发送摄像头图像
*/
void VideoControl::stop()
{
isSendFrame = false;
}
/**
* @brief 设置亮度
* @param val 亮度
*/
void VideoControl::setBrightness(double val)
{
alpha = val;
}
/**
* @brief 设置对比度
* @param val 对比度
*/
void VideoControl::setContrast(int val)
{
beta = val;
}
/**
* @brief 设置摄像头分辨率
* @param w 宽
* @param h 高
*/
void VideoControl::setCameraResolution(int w, int h)
{
if (w != g_frame_width)
{
isPause = true;
if (w > 320 && g_frame_quality > 90)
{
g_frame_quality = -1;
}
QTimer::singleShot(1500, this, SLOT(restartCamera()));
}
}
/**
* @brief 设置通过hsv识别颜色的参数大小
* @param type 类型
* @param val 大小
*/
void VideoControl::setHsvInRange(const QString &type, int val)
{
// qDebug()<< "setHsvInRange: "<<type<<val;
if (type == "MinH")
{
g_hsv_lower[0] = val;
}
else if (type == "MinS")
{
g_hsv_lower[1] = val;
}
else if (type == "MinV")
{
g_hsv_lower[2] = val;
}
else if (type == "MaxH")
{
g_hsv_upper[0] = val;
}
else if (type == "MaxS")
{
g_hsv_upper[1] = val;
}
else if (type == "MaxV")
{
g_hsv_upper[2] = val;
}
}
/**
* @brief 重新开启摄像头
*/
void VideoControl::restartCamera()
{
isPause = false;
if (!this->isRunning())
{
this->start(); //开启线程,进入run()函数
}
}
/**
* @brief 在该线程中接收摄像头图像并通过UDP发送给客户端,通过信号槽发送每一帧图片给另外一个线程识别颜色
*/
void VideoControl::run()
{
VideoCapture cap;
cap.open(0);
if (!cap.isOpened())
{
qDebug("cannot find camera !");
emit sendInfo("cannot find camera !\r\n");
return;
}
cap.set(CV_CAP_PROP_FRAME_WIDTH, g_frame_width);
cap.set(CV_CAP_PROP_FRAME_HEIGHT, g_frame_height);
// cap.set(CV_CAP_PROP_FPS, 15);
udpSocket = new QUdpSocket;
while(!isPause)
{
cap >> srcFrame;
if (srcFrame.empty())
{
qDebug("frame is empty !");
emit sendInfo("cannot read frame !\r\n");
continue;
}
//[1] 调节亮度和对比度
if (alpha > 1.0 || beta > 0)
{
for( int y = 0; y < srcFrame.rows; y++ )
{
Vec3b *p = srcFrame.ptr<Vec3b>(y); //通过指针遍历每一个像素点
for( int x = 0; x < srcFrame.cols; x++ )
{
for( int c = 0; c < 3; c++ )
{
// frame.at<Vec3b>(y,x)[c] = saturate_cast<uchar>( alpha*( frame.at<Vec3b>(y,x)[c] ) + beta );
p[x][c] = saturate_cast<uchar>( alpha*( srcFrame.at<Vec3b>(y,x)[c] ) + beta );
}
}
}
}
//[1]
//[2] 发送图片给其它线程进行识别颜色
cvtColor(srcFrame,rgb_mat,CV_BGR2RGB);
rgbImg = QImage((uchar*) rgb_mat.data, rgb_mat.cols, rgb_mat.rows,
rgb_mat.cols*rgb_mat.channels(), QImage::Format_RGB888);
emit sendFrame(rgbImg);
//[2]
//[3]将摄像头图像发送给客户端
if (isSendFrame)
{
if (G_Image_Format == "YUV")
{
sendFrameOfYUV();
}
else if (G_Image_Format == "HSV")
{
sendFrameOfHSV();
}
}
//[3]
msleep(1);
}
if (isPause)
{
cap.release();
}
}
void VideoControl::sendFrameOfYUV()
{
QByteArray byteArray;
QBuffer buf(&byteArray);
buf.open(QIODevice::WriteOnly);
if (G_Image_Display == "Original")
{
rgbImg.save(&buf,"JPEG",g_frame_quality);
}
else if (G_Image_Display == "Transform")
{
Mat yuv_mat;
cv::cvtColor(srcFrame, yuv_mat,CV_BGR2YUV);
for(int i = 0; i < g_frame_height; i++)
{
Vec3b *p = yuv_mat.ptr<Vec3b>(i); //通过指针遍历每一个像素点
for(int j = 0; j < g_frame_width; j++)
{
// yuv_mat.at<cv::Vec3b>(i,j)[0] = 128;
p[j][0] = g_color_channel_Y;
}
}
m_displayImage = QImage((uchar*) yuv_mat.data, yuv_mat.cols, yuv_mat.rows,
yuv_mat.cols*yuv_mat.channels(), QImage::Format_RGB888);
m_displayImage.save(&buf,"JPEG",g_frame_quality); //压缩图片大小
}
QByteArray datagram;
QDataStream out(&datagram, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_5_3);
out << QString("IMAGE").toUtf8() << byteArray;
udpSocket->writeDatagram(datagram, QHostAddress(m_client_ip),g_broadcast_port); // 向指定ip地址发送图像
}
void VideoControl::sendFrameOfHSV()
{
QByteArray byteArray;
QBuffer buf(&byteArray);
buf.open(QIODevice::WriteOnly);
//转到HSV空间
Mat hsv_mat;
cvtColor(srcFrame,hsv_mat,COLOR_BGR2HSV);
//根据阈值构建掩膜
inRange(hsv_mat, g_hsv_lower, g_hsv_upper, hsv_mat);
cv::Mat str_el = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(g_nStructElementSize, g_nStructElementSize));
//腐蚀操作
erode(hsv_mat, hsv_mat, str_el);
//膨胀操作,其实先腐蚀再膨胀的效果是开运算,去除噪点
dilate(hsv_mat, hsv_mat, str_el);
//轮廓检测
vector<vector<Point> > contours;
findContours(hsv_mat, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
vector<Moments>mu(contours.size());
vector<Point2f>mc(contours.size());
vector<double> areaVec;
for (size_t i=0; i<contours.size(); ++i)
{
//计算轮廓的面积
double tmparea = fabs(contourArea(contours[i]));
areaVec.push_back(tmparea);
mu[i] = moments(contours[i], false);
mc[i] = Point2f(mu[i].m10 / mu[i].m00, mu[i].m01 / mu[i].m00);
}
//选择最大面积的轮廓
int max_pos = (int)(max_element(areaVec.begin(), areaVec.end()) - areaVec.begin());
if (max_pos < (int)contours.size())
{
Rect findRect = boundingRect(contours[max_pos]);
if (G_Image_Display == "Original")
{
rectangle(rgb_mat, findRect, Scalar(0,255,0),2);
circle(rgb_mat, mc[max_pos], 3, Scalar(0,0,255)); //在重心坐标画圆
m_displayImage = QImage((uchar*) rgb_mat.data, rgb_mat.cols, rgb_mat.rows,
rgb_mat.cols*rgb_mat.channels(), QImage::Format_RGB888);
}
else if (G_Image_Display == "Transform")
{
cvtColor(hsv_mat, hsv_mat, CV_GRAY2RGB);
rectangle(hsv_mat, findRect, Scalar(0,255,0),2);
circle(hsv_mat, mc[max_pos], 3, Scalar(0,0,255)); //在重心坐标画圆
m_displayImage = QImage((uchar*) hsv_mat.data, hsv_mat.cols, hsv_mat.rows,
hsv_mat.cols*hsv_mat.channels(), QImage::Format_RGB888);
}
}
else
{
if (G_Image_Display == "Original")
{
m_displayImage = QImage((uchar*) rgb_mat.data, rgb_mat.cols, rgb_mat.rows,
rgb_mat.cols*rgb_mat.channels(), QImage::Format_RGB888);
}
else if (G_Image_Display == "Transform")
{
m_displayImage = QImage((uchar*) hsv_mat.data, hsv_mat.cols, hsv_mat.rows,
hsv_mat.cols*hsv_mat.channels(), QImage::Format_RGB888);
}
}
m_displayImage.save(&buf,"JPEG",g_frame_quality); //压缩图片大小
QByteArray datagram;
QDataStream out(&datagram, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_5_3);
out << QString("IMAGE").toUtf8() << byteArray;
udpSocket->writeDatagram(datagram, QHostAddress(m_client_ip),g_broadcast_port); // 向指定ip地址发送图像
}
/***************************************************************************************************
* @霍夫圆检测
//转为灰度图,进行图像平滑
Mat football_mat;
cvtColor(frame, football_mat, CV_BGR2GRAY);//转化边缘检测后的图为灰度图
GaussianBlur(football_mat, football_mat, Size(9, 9), 2, 2); //高斯模糊算法
//进行霍夫圆变换
vector<Vec3f> circles;//保存矢量
HoughCircles(football_mat, circles, CV_HOUGH_GRADIENT, 2, football_mat.rows/4, 200, 100, 0, 0);
//依次在图中绘制出圆
for (size_t i = 0; i < circles.size(); i++)
{
Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
int radius = cvRound(circles[i][2]);
//绘制圆心
circle(football_mat, center, 3, Scalar(0, 255, 0), -1, 8, 0);
//绘制圆轮廓
circle(football_mat, center, radius, Scalar(155, 50, 255), 3, 8, 0);
}
****************************************************************************************************/
| 25.106952 | 117 | 0.54164 | LejuRobotics |
73e3e3c88e0da6f8ec8718532acb7b52c587f1ca | 45,577 | hpp | C++ | pgfe/connection.hpp | dmitigr/cefeika | 6189843d4244f7334558708e57e952584561b1e0 | [
"Zlib"
] | 19 | 2019-07-21T15:38:12.000Z | 2022-01-06T05:24:48.000Z | pgfe/connection.hpp | dmitigr/cefeika | 6189843d4244f7334558708e57e952584561b1e0 | [
"Zlib"
] | 6 | 2019-12-07T22:12:37.000Z | 2022-01-10T22:31:48.000Z | pgfe/connection.hpp | dmitigr/cefeika | 6189843d4244f7334558708e57e952584561b1e0 | [
"Zlib"
] | 1 | 2019-08-15T14:49:00.000Z | 2019-08-15T14:49:00.000Z | // -*- C++ -*-
// Copyright (C) 2021 Dmitry Igrishin
//
// 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.
//
// Dmitry Igrishin
// dmitigr@gmail.com
#ifndef DMITIGR_PGFE_CONNECTION_HPP
#define DMITIGR_PGFE_CONNECTION_HPP
#include "basics.hpp"
#include "completion.hpp"
#include "connection_options.hpp"
#include "data.hpp"
#include "dll.hpp"
#include "error.hpp"
#include "notice.hpp"
#include "notification.hpp"
#include "pq.hpp"
#include "prepared_statement.hpp"
#include "sql_string.hpp"
#include "types_fwd.hpp"
#include <cassert>
#include <chrono>
#include <cstdint>
#include <functional>
#include <list>
#include <memory>
#include <optional>
#include <queue>
#include <string>
#include <type_traits>
#include <vector>
namespace dmitigr::pgfe {
/// Convenience function to use as row handler.
inline void ignore_row(Row&&) noexcept {}
/**
* @ingroup main
*
* @brief A connection to a PostgreSQL server.
*/
class Connection final {
public:
/// An alias of Connection_options.
using Options = Connection_options;
/// An alias of Connection_status.
using Status = Connection_status;
/**
* @brief The constructor.
*
* @param options The connection options.
*/
explicit Connection(Options options = {})
: options_{std::move(options)}
{}
/// Non copy-constructible.
Connection(const Connection&) = delete;
/// Non copy-assignable.
Connection& operator=(const Connection&) = delete;
/// Move-constructible.
Connection(Connection&& rhs) noexcept
{
Connection tmp;
tmp.swap(rhs); // reset rhs to the default state
swap(tmp);
}
/// Move-assignable.
Connection& operator=(Connection&& rhs) noexcept
{
if (this != &rhs) {
Connection tmp{std::move(rhs)};
swap(tmp);
}
return *this;
}
/// Swaps this instance with `rhs`.
void swap(Connection& rhs) noexcept
{
using std::swap;
swap(options_, rhs.options_);
swap(error_handler_, rhs.error_handler_);
swap(notice_handler_, rhs.notice_handler_);
swap(notification_handler_, rhs.notification_handler_);
swap(default_result_format_, rhs.default_result_format_);
swap(conn_, rhs.conn_);
swap(polling_status_, rhs.polling_status_);
swap(session_start_time_, rhs.session_start_time_);
swap(response_, rhs.response_);
swap(response_status_, rhs.response_status_);
swap(last_processed_request_id_, rhs.last_processed_request_id_);
swap(last_prepared_statement_, rhs.last_prepared_statement_);
swap(shared_field_names_, rhs.shared_field_names_);
swap(named_prepared_statements_, rhs.named_prepared_statements_);
unnamed_prepared_statement_.swap(rhs.unnamed_prepared_statement_);
swap(requests_, rhs.requests_);
request_prepared_statement_.swap(rhs.request_prepared_statement_);
swap(request_prepared_statement_name_, rhs.request_prepared_statement_name_);
}
/// @name General observers
/// @{
/// @returns The connection options of this instance.
const Connection_options& options() const noexcept
{
return options_;
}
/// @returns `true` if the connection secured by SSL.
bool is_ssl_secured() const noexcept
{
return conn() ? ::PQsslInUse(conn()) : false;
}
/**
* @returns The connection status.
*
* @see is_connected().
*/
DMITIGR_PGFE_API Status status() const noexcept;
/**
* @returns `(status() == Status::connected)`.
*
* @see status().
*/
bool is_connected() const noexcept
{
return status() == Status::connected;
}
/**
* @returns The transaction status.
*
* @see is_transaction_uncommitted().
*/
DMITIGR_PGFE_API std::optional<Transaction_status> transaction_status() const noexcept;
/**
* @returns `(transaction_status() == Transaction_status::uncommitted)`.
*
* @see transaction_status().
*/
bool is_transaction_uncommitted() const noexcept
{
return (transaction_status() == Transaction_status::uncommitted);
}
/**
* @returns The valid PID of server if connected.
*
* @see Notification::server_pid().
*/
std::int_fast32_t server_pid() const noexcept
{
return is_connected() ? ::PQbackendPID(conn()) : 0;
}
/**
* @returns The last registered time point when is_connected() started to
* return `true`, or `std::nullopt` if the session has never started.
*/
std::optional<std::chrono::system_clock::time_point> session_start_time() const noexcept
{
return session_start_time_;
}
///@}
// ---------------------------------------------------------------------------
/// @name Communication
/// @{
/**
* @brief Establishing the connection to a PostgreSQL server without blocking on I/O.
*
* This function should be called repeatedly. Until status() becomes `Status::connected`
* or `Status::failure` loop thus: if status() returned `Status::establishment_reading`,
* wait until the socket is ready to read, then call connect_nio() again; if status()
* returned `Status::establishment_writing`, wait until the socket ready to write, then
* call connect_nio() again. To determine the socket readiness use the socket_readiness()
* function.
*
* @par Effects
* Possible change of the returned value of status().
*
* @par Exception safety guarantee
* Basic.
*
* @remarks If called when `(status() == Status::failure)`, it will discard all
* the unhandled messages!
*
* @see connect(), status(), socket_readiness().
*/
DMITIGR_PGFE_API void connect_nio();
/**
* @brief Attempts to connect to a PostgreSQL server.
*
* @param timeout The value of `-1` means `options()->connect_timeout()`,
* the value of `std::nullopt` means *eternity*.
*
* @par Requires
* `(!timeout || timeout->count() >= -1)`.
*
* @par Effects
* `(status() == Status::failure || status() == Status::connected)`.
*
* @throws An instance of type Timed_out if the expression
* `(status() == Status::connected)` will not evaluates to `true` within the
* specified `timeout`.
*
* @par Exception safety guarantee
* Basic.
*
* @see connect_nio().
*/
DMITIGR_PGFE_API void connect(std::optional<std::chrono::milliseconds> timeout = std::chrono::milliseconds{-1});
/**
* @brief Attempts to disconnect from a server.
*
* @par Effects
* `(status() == Status::disconnected)`.
*
* @par Exception safety guarantee
* Strong.
*/
void disconnect() noexcept
{
reset_session();
conn_.reset(); // discarding unhandled notifications btw.
assert(status() == Status::disconnected);
assert(is_invariant_ok());
}
/**
* @brief Waits for readiness of the connection socket if it's unready.
*
* @returns The bit mask indicating the readiness of the connection socket.
*
* @param mask A bit mask specifying the requested readiness of the
* connection socket.
* @param timeout A maximum amount of time to wait before return. The
* value of `std::nullopt` *eternity*.
*
* @par Requires
* `((!timeout || timeout->count() >= -1) &&
* (status() != Status::failure) && (status() != Status::disconnected))`.
*/
DMITIGR_PGFE_API Socket_readiness wait_socket_readiness(Socket_readiness mask,
std::optional<std::chrono::milliseconds> timeout = std::nullopt) const;
/**
* @brief Polls the readiness of the connection socket.
*
* @returns `wait_socket_readiness(mask, std::chrono::milliseconds{})`.
*
* @param mask Similar to wait_socket_readiness().
*
* @see wait_socket_readiness().
*/
DMITIGR_PGFE_API Socket_readiness socket_readiness(Socket_readiness mask) const;
/**
* @brief If input is available from the server, read it.
*
* This function should be called every time when the value returned by
* handle_input() is Response_status::unready and the socket is in
* read-ready state.
*
* @see handle_input(), socket_readiness().
*/
void read_input()
{
if (!::PQconsumeInput(conn()))
throw std::runtime_error{error_message()};
}
/**
* @brief Attempts to handle the input from the server.
*
* For every parsed notice or notification calls the corresponding handler.
*
* @returns The response status.
*
* @param wait_response Indicates whether to wait for response (which assumes
* possible thread block).
*
* @par Requires
* `is_connected()`.
*
* @par Effects
* *Possible* signals and/or response are available.
*
* @par Exception safety guarantee
* Basic.
*
* @see read_input().
*/
DMITIGR_PGFE_API Response_status handle_input(bool wait_response = false);
/// @}
// -----------------------------------------------------------------------------
/**
* @name Signals
*/
/// @{
/// @returns The valid released instance if available.
DMITIGR_PGFE_API Notification pop_notification();
/// An alias of a notice handler.
using Notice_handler = std::function<void(const Notice&)>;
/**
* @brief Sets the handler for notices.
*
* By default, the notice handler just prints notices to the standard error
* and never throws.
*
* @param handler A handler to set.
*
* @par Exception safety guarantee
* Strong.
*
* @see notice_handler().
*/
void set_notice_handler(Notice_handler handler) noexcept
{
notice_handler_ = std::move(handler);
assert(is_invariant_ok());
}
/// @returns The current notice handler.
const Notice_handler& notice_handler() const noexcept
{
return notice_handler_;
}
/// An alias of a notification handler.
using Notification_handler = std::function<void(Notification&&)>;
/**
* @brief Sets the handler for notifications.
*
* By default, a notification handler isn't set.
*
* @param handler A handler to set.
*
* @par Exception safety guarantee
* Strong.
*/
void set_notification_handler(Notification_handler handler) noexcept
{
notification_handler_ = std::move(handler);
assert(is_invariant_ok());
}
/// @returns The current notification handler.
const Notification_handler& notification_handler() const noexcept
{
return notification_handler_;
}
///@}
// ---------------------------------------------------------------------------
/// @name Responses
/// @{
/// @returns `true` if there is uncompleted request.
bool has_uncompleted_request() const noexcept
{
return !requests_.empty();
}
/// @returns `true` if there is ready response available.
bool has_response() const noexcept
{
return static_cast<bool>(response_) && (response_status_ == Response_status::ready);
}
/**
* @brief Waits the next Response overwriting the current one.
*
* @returns has_response().
*
* @param timeout The value of `-1` means `options().wait_response_timeout()`;
* the value of `std::nullopt` means *eternity*.
*
* @par Requires
* `(!timeout || timeout->count() >= -1)`.
*
* @throws An instance of type Timed_out if the expression `has_response()`
* will not evaluates to `true` within the specified `timeout`.
*
* @par Exception safety guarantee
* Basic.
*
* @remarks All signals retrieved upon waiting the Response will be handled
* by signals handlers being set.
*
* @see wait_response_throw().
*/
DMITIGR_PGFE_API bool wait_response(std::optional<std::chrono::milliseconds> timeout = std::chrono::milliseconds{-1});
/**
* @brief Similar to wait_response(), but throws Server_exception
* if `(error() != std::nullopt)` after awaiting.
*
* @see wait_response().
*/
bool wait_response_throw(std::optional<std::chrono::milliseconds> timeout = std::chrono::milliseconds{-1})
{
const bool result = wait_response(timeout);
throw_if_error();
return result;
}
/**
* @brief An alias of error handler.
*
* Being set, this handler is called when the server responded with an error.
* If calling of this handler doesn't throw an exception and returns `false`
* the instance of type Server_exception will be thrown eventually. If this
* handler returns `true` then the error is considered handled and no further
* action is taken.
*/
using Error_handler = std::function<bool(std::shared_ptr<Error>)>;
/**
* @brief Sets the handler for custom errors.
*
* @param handler A handler to set.
*
* @par Exception safety guarantee
* Strong.
*
* @see Error_handler, error_handler().
*/
void set_error_handler(Error_handler handler) noexcept
{
error_handler_ = std::move(handler);
assert(is_invariant_ok());
}
/// @returns The current error handler.
const Error_handler& error_handler() noexcept
{
return error_handler_;
}
/**
* @returns The released instance if available.
*
* @par Exception safety guarantee
* Strong.
*
* @remarks Useful only if using non-blocking IO API.
*/
Error error() noexcept
{
return (response_.status() == PGRES_FATAL_ERROR) ? Error{std::move(response_)} : Error{};
}
/**
* @returns The released instance if available.
*
* @par Exception safety guarantee
* Strong.
*
* @see wait_response(), completion().
*/
Row row() noexcept
{
return (response_.status() == PGRES_SINGLE_TUPLE) ? Row{std::move(response_), shared_field_names_} : Row{};
}
/**
* @returns The released instance if available.
*
* @par Exception safety guarantee
* Strong.
*
* @see wait_response(), row().
*/
DMITIGR_PGFE_API Completion completion() noexcept;
/**
* @brief Processes the responses.
*
* @returns The released instance if available.
*
* @tparam on_exception What to do when the callback throws an exception.
*
* @param callback A function to be called for each retrieved row. The callback:
* -# can be defined with a parameter of type `Row&&`. An exception will be
* thrown on error in this case.
* -# can be defined with two parameters of type `Row&&` and `Error&&`.
* In case of error an instance of type Error will be passed as the second
* argument of the callback instead of throwing exception and method will
* return an invalid instance of type Completion after the callback returns.
* In case of success, an invalid instance of type Error will be passed as the
* second argument of the callback.
* -# can return a value of type Row_processing to indicate further behavior.
*
* @see execute(), invoke(), call(), Row_processing.
*/
template<Row_processing on_exception = Row_processing::complete, typename F>
std::enable_if_t<detail::Response_callback_traits<F>::is_valid, Completion>
process_responses(F&& callback)
{
using Traits = detail::Response_callback_traits<F>;
const auto with_complete_on_exception = [this](auto&& callback)
{
try {
callback();
} catch (...) {
if constexpr (on_exception == Row_processing::complete) {
Completion comp;
Error err;
std::runtime_error process_responses_error{""};
try {
// std::function is used as the workaround for GCC 7.5
std::function<void(Row&&, Error&&)> f = [&err](auto&&, auto&& e)
{
if (e)
err = std::move(e);
};
comp = process_responses(std::move(f));
assert((comp && !err) || (!comp && err));
} catch (const std::bad_alloc&) {
goto bad_alloc;
} catch (const std::exception& e) {
try {
process_responses_error = std::runtime_error{e.what()};
} catch (...) {
goto bad_alloc;
}
} catch (...) {}
if (comp)
throw;
else if (!err)
std::throw_with_nested(process_responses_error);
else if (std::shared_ptr<Error> e{new (std::nothrow) Error{std::move(err)}})
std::throw_with_nested(Server_exception{std::move(e)});
bad_alloc:
std::throw_with_nested(std::bad_alloc{});
} else if constexpr (on_exception == Row_processing::suspend)
throw;
}
};
Row_processing rowpro{Row_processing::continu};
while (true) {
if constexpr (Traits::has_error_parameter) {
wait_response();
if (auto e = error()) {
callback(Row{}, std::move(e));
return Completion{};
} else if (auto r = row()) {
with_complete_on_exception([this, &callback, &rowpro, &r]
{
if constexpr (!Traits::is_result_void)
rowpro = callback(std::move(r), Error{});
else
callback(std::move(r), Error{});
});
} else
return completion();
} else {
wait_response_throw();
if (auto r = row()) {
with_complete_on_exception([this, &callback, &rowpro, &r]
{
if constexpr (!Traits::is_result_void)
rowpro = callback(std::move(r));
else
callback(std::move(r));
});
} else
return completion();
}
if (rowpro == Row_processing::complete)
return process_responses(ignore_row);
else if (rowpro == Row_processing::suspend)
return Completion{};
}
}
/**
* @returns The pointer to a last prepared statement if the last operation was
* prepare.
*
* @remarks The object pointed by the returned value is owned by this instance.
*
* @see prepare().
*/
Prepared_statement* prepared_statement() noexcept
{
auto* const result = last_prepared_statement_;
last_prepared_statement_ = nullptr;
response_.reset();
return result;
}
/**
* @returns The pointer to a prepared statement by its name if the prepared
* statement with the given name is known by this instance.
*
* @param name A name of prepared statement.
*
* @remarks The object pointed by the returned value is owned by this instance.
* @remarks The statements prepared by using the SQL command `PREPARE` must be
* described first in order to be accessible by this method.
*
* @see describe().
*/
Prepared_statement* prepared_statement(const std::string& name) const noexcept
{
return ps(name);
}
///@}
// ---------------------------------------------------------------------------
/// @name Requests
/// @{
/**
* @returns `true` if the connection is ready for requesting a server in a
* non-blocking manner.
*
* @see is_ready_for_request().
*/
bool is_ready_for_nio_request() const noexcept
{
const auto ts = transaction_status();
return ts && ts != Transaction_status::active;
}
/**
* @returns `true` if the connection is ready for requesting a server.
*
* @see is_ready_for_nio_request().
*/
bool is_ready_for_request() const noexcept
{
// Same as is_ready_for_nio_request() at the moment.
return is_ready_for_nio_request();
}
/**
* @brief Submits a request to a server to prepare the statement.
*
* @par Responses
* Prepared_statement
*
* @param statement A preparsed SQL string.
* @param name A name of statement to be prepared.
*
* @par Effects
* - `has_uncompleted_request()` - just after the successful request submission;
* - `(prepared_statement(name) && prepared_statement(name)->is_preparsed())` -
* just after the successful response.
*
* @par Requires
* `(is_ready_for_nio_request() && !statement.has_missing_parameters())`.
*
* @par Exception safety guarantee
* Strong.
*
* @remarks It's recommended to specify the types of the parameters by using
* explicit type casts to avoid ambiguities or type mismatch mistakes, for
* example:
* @code{sql}
* -- Force to use generate_series(int, int) overload.
* SELECT generate_series($1::int, $2::int);
* @endcode
* This forces parameters `$1` and `$2` to be treated as of type `integer`
* and thus the corresponding overload will be used in this case.
*
* @see unprepare_nio().
*/
void prepare_nio(const Sql_string& statement, const std::string& name = {})
{
assert(!statement.has_missing_parameters());
prepare_nio__(statement.to_query_string().c_str(), name.c_str(), &statement); // can throw
}
/// Same as prepare_nio() except the statement will be send without preparsing.
void prepare_nio_as_is(const std::string& statement, const std::string& name = {})
{
prepare_nio__(statement.c_str(), name.c_str(), nullptr); // can throw
}
/**
* @returns The pointer to the just prepared statement owned by this instance.
*
* @par Requires
* `(is_ready_for_request() && !statement.has_missing_parameters())`.
*
* @par Exception safety guarantee
* Basic.
*
* @remarks See remarks of prepare_nio().
*
* @see unprepare().
*/
Prepared_statement* prepare(const Sql_string& statement, const std::string& name = {})
{
using M = void(Connection::*)(const Sql_string&, const std::string&);
return prepare__(static_cast<M>(&Connection::prepare_nio), statement, name);
}
/// Same as prepare() except the statement will be send without preparsing.
Prepared_statement* prepare_as_is(const std::string& statement, const std::string& name = {})
{
return prepare__(&Connection::prepare_nio_as_is, statement, name);
}
/**
* @brief Requests the server to describe the prepared statement.
*
* @par Responses
* Prepared_statement
*
* @param name A name of prepared statement.
*
* @par Effects
* - `has_uncompleted_request()` - just after the successful request submission;
* - `(prepared_statement(name) && prepared_statement(name)->is_described())` -
* just after the successful response.
*
* @par Requires
* `is_ready_for_nio_request()`.
*
* @par Exception safety guarantee
* Strong.
*
* @see describe().
*/
DMITIGR_PGFE_API void describe_nio(const std::string& name);
/**
* @returns The pointer to the prepared statement owned by this instance.
*
* @par Requires
* `is_ready_for_request()`.
*
* @par Exception safety guarantee
* Basic.
*
* @see describe_nio(), unprepare().
*/
Prepared_statement* describe(const std::string& name)
{
assert(is_ready_for_request());
describe_nio(name);
return wait_prepared_statement__();
}
/**
* @brief Requests the server to deallocate the prepared statement.
*
* @par Responses
* Completion
*
* @param name A name of prepared statement.
*
* @par Effects
* - `has_uncompleted_request()` - just after the successful request;
* - `!prepared_statement(name)` - just after the successful response.
*
* @par Requires
* `(is_ready_for_nio_request() && !name.empty())`.
*
* @par Exception safety guarantee
* Strong.
*
* @remarks The named prepared statements only can be deallocated currently.
*
* @see unprepare().
*/
DMITIGR_PGFE_API void unprepare_nio(const std::string& name);
/**
* @returns The valid released instance if available.
*
* @par Requires
* `is_ready_for_request()`.
*
* @par Exception safety guarantee
* Basic.
*/
Completion unprepare(const std::string& name)
{
assert(is_ready_for_request());
unprepare_nio(name);
wait_response_throw();
return completion();
}
/**
* @brief Requests the server to prepare and execute the unnamed statement
* from the preparsed SQL string without waiting for a response.
*
* @par Responses
* Similar to Prepared_statement::execute().
*
* @param queries A string, containing the SQL query(-es). Adjacent
* queries must be separated by a semicolon.
*
* @par Effects
* `has_uncompleted_request()`.
*
* @par Requires
* `is_ready_for_nio_request()`.
*
* @par Exception safety guarantee
* Strong.
*
* @see execute().
*/
template<typename ... Types>
void execute_nio(const Sql_string& statement, Types&& ... parameters)
{
Prepared_statement ps{"", this, &statement};
ps.bind_many(std::forward<Types>(parameters)...).execute_nio(statement);
}
/**
* @brief Requests the server to prepare and execute the unnamed statement
* from the preparsed SQL string, and waits for a response.
*
* @returns The released instance.
*
* @par Responses
* Similar to Prepared_statement::execute().
*
* @param callback Same as for process_responses().
* @param statement A *preparsed* statement to execute.
* @param parameters Parameters to bind with a parameterized statement.
*
* @par Requires
* `(is_ready_for_request() && !statement.has_missing_parameters())`.
*
* @par Exception safety guarantee
* Basic.
*
* @remarks See remarks of prepare().
*
* @see process_responses().
*/
template<Row_processing on_exception = Row_processing::complete, typename F, typename ... Types>
std::enable_if_t<detail::Response_callback_traits<F>::is_valid, Completion>
execute(F&& callback, const Sql_string& statement, Types&& ... parameters)
{
execute_nio(statement, std::forward<Types>(parameters)...);
return process_responses<on_exception>(std::forward<F>(callback));
}
/// @overload
template<Row_processing on_exception = Row_processing::complete, typename ... Types>
Completion execute(const Sql_string& statement, Types&& ... parameters)
{
return execute<on_exception>([](auto&&){}, statement, std::forward<Types>(parameters)...);
}
/**
* @brief Requests the server to invoke the specified function and waits for
* a response.
*
* If `function` returns table with multiple columns or has multiple output
* parameters they are can be accessed as usual by using Row::data().
*
* If `function` have named parameters it can be called using either
* positional, named or mixed notation.
*
* When using positional notation all arguments specified traditionally in
* order, for example:
* @code
* conn.invoke("generate_series", 1, 3);
* @endcode
*
* When using named notation, each argument is specified using object of type
* Named_argument (or it alias - `a`), for example:
*
* @code
* conn.invoke("person_info", a{"name", "Christopher"}, a{"id", 1});
* @endcode
*
* When using mixed notation which combines positional and named notation,
* named arguments cannot precede positional arguments. The compile time check
* will be performed to enforce that. For example:
*
* @code
* conn.invoke("person_info", 1, a{"name", "Christopher"});
* @endcode
*
* See <a href="https://www.postgresql.org/docs/current/static/sql-syntax-calling-funcs.html">calling functions</a>
* section of the PostgreSQL documentation for the full details on calling
* notations.
*
* @returns The released instance.
*
* @par Responses
* Similar to execute().
*
* @param callback Same as for process_responses().
* @param function A function name to invoke.
* @param arguments Function arguments.
*
* @par Requires
* `(is_ready_for_request() && !function.empty())`.
*
* @par Exception safety guarantee
* Basic.
*
* @remarks It may be problematic to invoke overloaded functions with same
* number of parameters. A SQL query with explicit type casts should be
* executed is such a case. See remarks of prepare_nio().
*
* @see invoke_unexpanded(), call(), execute(), process_responses().
*/
template<Row_processing on_exception = Row_processing::complete, typename F, typename ... Types>
std::enable_if_t<detail::Response_callback_traits<F>::is_valid, Completion>
invoke(F&& callback, std::string_view function, Types&& ... arguments)
{
static_assert(is_routine_arguments_ok__<Types...>(), "named arguments cannot precede positional arguments");
const auto stmt = routine_query__(function, "SELECT * FROM", std::forward<Types>(arguments)...);
return execute<on_exception>(std::forward<F>(callback), stmt, std::forward<Types>(arguments)...);
}
/// @overload
template<Row_processing on_exception = Row_processing::complete, typename ... Types>
Completion invoke(std::string_view function, Types&& ... arguments)
{
return invoke<on_exception>([](auto&&){}, function, std::forward<Types>(arguments)...);
}
/**
* @brief Similar to invoke() but even if `function` returns table with
* multiple columns or has multiple output parameters the result row is
* always consists of exactly one field.
*
* @returns The Completion instance.
*
* @remarks This method is for specific use and in most cases invoke()
* should be used instead.
*
* @see invoke(), call(), execute().
*/
template<Row_processing on_exception = Row_processing::complete, typename F, typename ... Types>
std::enable_if_t<detail::Response_callback_traits<F>::is_valid, Completion>
invoke_unexpanded(F&& callback, std::string_view function, Types&& ... arguments)
{
static_assert(is_routine_arguments_ok__<Types...>(), "named arguments cannot precede positional arguments");
const auto stmt = routine_query__(function, "SELECT", std::forward<Types>(arguments)...);
return execute<on_exception>(std::forward<F>(callback), stmt, std::forward<Types>(arguments)...);
}
/// @overload
template<Row_processing on_exception = Row_processing::complete, typename ... Types>
Completion invoke_unexpanded(std::string_view function, Types&& ... arguments)
{
return invoke_unexpanded<on_exception>([](auto&&){}, function, std::forward<Types>(arguments)...);
}
/**
* @brief Requests the server to invoke the specified procedure and waits for
* a response.
*
* This method is similar to invoke(), but for procedures rather than functions.
*
* @returns The Completion instance.
*
* @remarks PostgreSQL supports procedures since version 11.
*
* @see invoke(), call(), execute().
*/
template<Row_processing on_exception = Row_processing::complete, typename F, typename ... Types>
std::enable_if_t<detail::Response_callback_traits<F>::is_valid, Completion>
call(F&& callback, std::string_view procedure, Types&& ... arguments)
{
static_assert(is_routine_arguments_ok__<Types...>(), "named arguments cannot precede positional arguments");
const auto stmt = routine_query__(procedure, "CALL", std::forward<Types>(arguments)...);
return execute<on_exception>(std::forward<F>(callback), stmt, std::forward<Types>(arguments)...);
}
/// @overload
template<Row_processing on_exception = Row_processing::complete, typename ... Types>
Completion call(std::string_view procedure, Types&& ... arguments)
{
return call<on_exception>([](auto&&){}, procedure, std::forward<Types>(arguments)...);
}
/**
* @brief Sets the default data format of statements execution results.
*
* @par Exception safety guarantee
* Strong.
*/
void set_result_format(const Data_format format) noexcept
{
default_result_format_ = format;
assert(is_invariant_ok());
}
/// @returns The default data format of a statement execution result.
Data_format result_format() const noexcept
{
return default_result_format_;
}
///@}
// ---------------------------------------------------------------------------
/// @name Large objects
/// @{
/**
* @brief Requests the server to create the large object and waits the result.
*
* @param oid A desired OID. `invalid_oid` means *unused oid*.
*
* @returns The valid OID if successful, or `invalid_oid` otherwise.
*
* @par Requires
* `(is_ready_for_request())`.
*
* @par Exception safety guarantee
* Strong.
*/
DMITIGR_PGFE_API Oid create_large_object(Oid oid = invalid_oid) noexcept;
/**
* @brief Requests the server to open the large object and waits the result.
*
* @returns The valid instance if successful.
*
* @par Requires
* `(is_ready_for_request())`.
*
* @par Exception safety guarantee
* Strong.
*/
DMITIGR_PGFE_API Large_object open_large_object(Oid oid, Large_object_open_mode mode) noexcept;
/**
* @brief Requests the server to remove the large object and waits the result.
*
* @returns `true` on success.
*
* @par Requires
* `(is_ready_for_request())`.
*
* @par Exception safety guarantee
* Strong.
*/
bool remove_large_object(Oid oid) noexcept
{
assert(is_ready_for_request());
return ::lo_unlink(conn(), oid);
}
/**
* @brief Requests the server (multiple times) to import the specified file as
* a large object.
*
* @returns The OID of a new large object on success, or `invalid_oid` otherwise.
*
* @par Requires
* `(is_ready_for_request())`.
*
* @par Exception safety guarantee
* Strong.
*/
Oid import_large_object(const std::filesystem::path& filename, Oid oid = invalid_oid) noexcept
{
assert(is_ready_for_request());
return ::lo_import_with_oid(conn(), filename.c_str(), oid);
}
/**
* @brief Requests the server (multiple times) to export the specified large
* object to the specified file.
*
* @returns `true` on success.
*
* @par Requires
* `(is_ready_for_request())`.
*
* @par Exception safety guarantee
* Strong.
*/
bool export_large_object(Oid oid, const std::filesystem::path& filename) noexcept
{
assert(is_ready_for_request());
return ::lo_export(conn(), oid, filename.c_str()) == 1; // lo_export returns -1 on failure
}
/// @}
// ---------------------------------------------------------------------------
/// @name Utilities
/// @{
/**
* @brief Quotes the given string to be used as a literal in a SQL query.
*
* @returns The suitably quoted literal.
*
* @param literal A literal to quote.
*
* @par Requires
* `is_connected()`.
*
* @remarks Using of parameterized prepared statement should be considered as
* the better alternative comparing to including the quoted data into a query.
*
* @remarks Note, the result is depends on session properties (such as a
* character encoding). Therefore using it in queries which are submitted
* by using connections with other session properties is not correct.
*
* @see Prepared_statement.
*/
DMITIGR_PGFE_API std::string to_quoted_literal(const std::string_view literal) const;
/**
* @brief Quotes the given string to be used as an identifier in a SQL query.
*
* @param identifier An identifier to quote.
*
* @returns The suitably quoted identifier.
*
* @par Requires
* `is_connected()`.
*
* @remarks Note, the result is depends on session properties (such as a
* character encoding). Therefore using it in queries which are submitted
* by using connections with other session properties is not correct.
*
* @see Prepared_statement.
*/
DMITIGR_PGFE_API std::string to_quoted_identifier(const std::string_view identifier) const;
/**
* @brief Encodes the binary data into the textual representation to be used
* in a SQL query.
*
* @param binary_data A binary Data to escape.
*
* @returns The encoded data in the hex format.
*
* @par Requires
* `(is_connected() && binary_data && (binary_data->format() == Data_format::binary))`.
*
* @remarks Using of parameterized prepared statement should be considered as
* the better alternative comparing to including the encoded binary data into
* a query.
*
* @remarks Note, the result is depends on session properties (such as a
* character encoding). Therefore using it in queries which are submitted
* by using connections with other session properties is not correct.
*
* @see Prepared_statement.
*/
std::unique_ptr<Data> to_hex_data(const Data* binary_data) const
{
auto [storage, size] = to_hex_storage(binary_data);
return Data::make(std::move(storage), size, Data_format::text);
}
/**
* @brief Similar to to_hex_data(const Data*).
*
* @returns The encoded string in the hex format.
*
* @see to_hex_data().
*/
std::string to_hex_string(const Data* binary_data) const
{
const auto [storage, size] = to_hex_storage(binary_data);
return std::string{static_cast<const char*>(storage.get()), size};
}
///@}
private:
friend Large_object;
friend Prepared_statement;
// ---------------------------------------------------------------------------
// Persistent data
// ---------------------------------------------------------------------------
// Persistent data / constant data
Options options_;
// Persistent data / public-modifiable data
Error_handler error_handler_;
Notice_handler notice_handler_{&default_notice_handler};
Notification_handler notification_handler_;
Data_format default_result_format_{Data_format::text};
// Persistent data / private-modifiable data
std::unique_ptr< ::PGconn> conn_;
std::optional<Status> polling_status_;
::PGconn* conn() const noexcept { return conn_.get(); }
// ---------------------------------------------------------------------------
// Session data / requests data
// ---------------------------------------------------------------------------
enum class Request_id {
execute = 1,
prepare,
describe,
unprepare
};
std::optional<std::chrono::system_clock::time_point> session_start_time_;
detail::pq::Result response_; // allowed to not match to response_status_
Response_status response_status_{}; // status last assigned by handle_input()
Request_id last_processed_request_id_{}; // type last assigned by handle_input()
Prepared_statement* last_prepared_statement_{};
std::shared_ptr<std::vector<std::string>> shared_field_names_;
mutable std::list<Prepared_statement> named_prepared_statements_;
mutable Prepared_statement unnamed_prepared_statement_;
std::queue<Request_id> requests_; // for batch mode
Prepared_statement request_prepared_statement_;
std::optional<std::string> request_prepared_statement_name_;
bool is_invariant_ok() const noexcept;
// ---------------------------------------------------------------------------
// Session data helpers
// ---------------------------------------------------------------------------
void reset_session() noexcept;
// ---------------------------------------------------------------------------
// Handlers
// ---------------------------------------------------------------------------
static void notice_receiver(void* const arg, const ::PGresult* const r) noexcept;
static void default_notice_handler(const Notice& n) noexcept;
// ---------------------------------------------------------------------------
// Prepared statement helpers
// ---------------------------------------------------------------------------
void prepare_nio__(const char* const query, const char* const name, const Sql_string* const preparsed);
template<typename M, typename T>
Prepared_statement* prepare__(M&& prepare, T&& statement, const std::string& name)
{
assert(is_ready_for_request());
(this->*prepare)(std::forward<T>(statement), name);
return wait_prepared_statement__();
}
Prepared_statement* wait_prepared_statement__()
{
wait_response_throw();
auto* const result = prepared_statement();
assert(result);
assert(!completion()); // no completion for prepare/describe
return result;
}
/*
* Attempts to find the prepared statement.
*
* @returns The pointer to a prepared statement, or `nullptr` if no statement
* with the given `name` known by this instance.
*/
Prepared_statement* ps(const std::string& name) const noexcept;
/*
* Registers the prepared statement.
*
* @returns The pointer to the registered prepared statement.
*/
Prepared_statement* register_ps(Prepared_statement&& ps) const noexcept;
// Unregisters the prepared statement.
void unregister_ps(const std::string& name) noexcept;
// ---------------------------------------------------------------------------
// Utilities helpers
// ---------------------------------------------------------------------------
int socket() const noexcept
{
return ::PQsocket(conn());
}
void throw_if_error();
std::string error_message() const;
bool is_out_of_memory() const
{
constexpr char msg[] = "out of memory";
return !std::strncmp(::PQerrorMessage(conn()), msg, sizeof(msg) - 1);
}
std::pair<std::unique_ptr<void, void(*)(void*)>, std::size_t> to_hex_storage(const pgfe::Data* const binary_data) const;
// ---------------------------------------------------------------------------
// Large Object private API
// ---------------------------------------------------------------------------
DMITIGR_PGFE_API bool close(Large_object& lo) noexcept;
DMITIGR_PGFE_API std::int_fast64_t seek(Large_object& lo, std::int_fast64_t offset, Large_object_seek_whence whence) noexcept;
DMITIGR_PGFE_API std::int_fast64_t tell(Large_object& lo) noexcept;
DMITIGR_PGFE_API bool truncate(Large_object& lo, const std::int_fast64_t new_size) noexcept;
DMITIGR_PGFE_API int read(Large_object& lo, char* const buf, const std::size_t size) noexcept;
DMITIGR_PGFE_API int write(Large_object& lo, const char* const buf, const std::size_t size) noexcept;
// ---------------------------------------------------------------------------
// call/invoke helpers
// ---------------------------------------------------------------------------
template<typename ... Types>
std::string routine_query__(std::string_view function, std::string_view invocation, Types&& ... arguments)
{
assert(!function.empty());
assert(invocation == "SELECT * FROM" || invocation == "SELECT" || invocation == "CALL");
std::string result;
if constexpr (sizeof...(arguments) > 0) {
result.reserve(64);
result.append(invocation).append(" ");
result.append(function).append("(");
result.append(routine_arguments__(std::make_index_sequence<sizeof ... (Types)>{}, std::forward<Types>(arguments)...));
result.append(")");
} else {
result.reserve(14 + function.size() + 2);
result.append(invocation).append(" ").append(function).append("()");
}
return result;
}
template<std::size_t ... I, typename ... Types>
std::string routine_arguments__(std::index_sequence<I...>, Types&& ... arguments)
{
static_assert(sizeof...(arguments) > 0);
static_assert(sizeof...(arguments) == sizeof...(I));
std::string result;
(result.append(routine_argument__(arguments, I)).append(","), ...);
result.pop_back();
return result;
}
template<typename T>
std::string routine_argument__(const T&, const std::size_t i)
{
return std::string{"$"}.append(std::to_string(i + 1));
}
std::string routine_argument__(const Named_argument& na, const std::size_t)
{
return std::string{na.name()}.append("=>:").append(na.name());
}
template<typename T = void>
static constexpr bool is_routine_arguments_ok__()
{
return true;
}
template<typename T1, typename T2, typename ... Types>
static constexpr bool is_routine_arguments_ok__()
{
using U1 = std::decay_t<T1>;
using U2 = std::decay_t<T2>;
constexpr bool is_named_1 = std::is_same_v<U1, Named_argument>;
constexpr bool is_named_2 = std::is_same_v<U2, Named_argument>;
constexpr bool is_both_positionals = !is_named_1 && !is_named_2;
constexpr bool is_both_named = is_named_1 && is_named_2;
constexpr bool is_named_follows_positional = !is_named_1 && is_named_2;
constexpr bool is_ok = (is_both_positionals || is_both_named || is_named_follows_positional);
return is_ok && is_routine_arguments_ok__<T2, Types...>();
}
};
template<Row_processing on_exception = Row_processing::complete, typename F, typename ... Types>
std::enable_if_t<detail::Response_callback_traits<F>::is_valid, Completion>
Prepared_statement::execute(F&& callback, Types&& ... parameters)
{
assert(connection_);
assert(connection_->is_ready_for_request());
bind_many(std::forward<Types>(parameters)...).execute_nio();
assert(is_invariant_ok());
return connection_->process_responses<on_exception>(std::forward<F>(callback));
}
/// Connection is swappable.
inline void swap(Connection& lhs, Connection& rhs) noexcept
{
lhs.swap(rhs);
}
} // namespace dmitigr::pgfe
#ifdef DMITIGR_PGFE_HEADER_ONLY
#include "connection.cpp"
#include "prepared_statement.cpp"
#endif
#endif // DMITIGR_PGFE_CONNECTION_HPP
| 31.345942 | 128 | 0.647542 | dmitigr |
73e4e515deb920262768a606cf5fb5ae3e23cfd2 | 4,518 | hpp | C++ | crogine/include/crogine/graphics/DepthTexture.hpp | fallahn/crogine | f6cf3ade1f4e5de610d52e562bf43e852344bca0 | [
"FTL",
"Zlib"
] | 41 | 2017-08-29T12:14:36.000Z | 2022-02-04T23:49:48.000Z | crogine/include/crogine/graphics/DepthTexture.hpp | fallahn/crogine | f6cf3ade1f4e5de610d52e562bf43e852344bca0 | [
"FTL",
"Zlib"
] | 11 | 2017-09-02T15:32:45.000Z | 2021-12-27T13:34:56.000Z | crogine/include/crogine/graphics/DepthTexture.hpp | fallahn/crogine | f6cf3ade1f4e5de610d52e562bf43e852344bca0 | [
"FTL",
"Zlib"
] | 5 | 2020-01-25T17:51:45.000Z | 2022-03-01T05:20:30.000Z | /*-----------------------------------------------------------------------
Matt Marchant 2017 - 2020
http://trederia.blogspot.com
crogine - Zlib license.
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.
-----------------------------------------------------------------------*/
#pragma once
#include <crogine/detail/SDLResource.hpp>
#include <crogine/graphics/RenderTarget.hpp>
#include <crogine/graphics/MaterialData.hpp>
#include <array>
namespace cro
{
/*!
\brief A render buffer with only a depth component attached.
DepthTextures are non-copyable objects but *can* be moved.
*/
class CRO_EXPORT_API DepthTexture final : public RenderTarget, public Detail::SDLResource
{
public:
/*!
\brief Constructor.
By default DepthTextures are in an invalid state until create() has been called
at least once.
To draw to a depth texture first call its clear() function, which then activates
it as the current target. All drawing operations will then be performed on it
until display() is called. Both clear AND display() *must* be called either side of
drawing to prevent undefined results.
*/
DepthTexture();
~DepthTexture();
DepthTexture(const DepthTexture&) = delete;
DepthTexture(DepthTexture&&) noexcept;
const DepthTexture& operator = (const DepthTexture&) = delete;
DepthTexture& operator = (DepthTexture&&) noexcept;
/*!
\brief Creates (or recreates) the depth texture
\param width Width of the texture to create. This should be
power of 2 on mobile platforms
\param height Height of the texture.
\returns true on success, else returns false
*/
bool create(std::uint32_t width, std::uint32_t height);
/*!
\brief Returns the current size in pixels of the depth texture (zero if not yet created)
*/
glm::uvec2 getSize() const override;
/*!
\brief Clears the texture ready for drawing
This should be called to activate the depth texture as the current draw target.
From then on all drawing operations will be applied to the DepthTexture until display()
is called. For every clear() call there must be exactly one display() call. This
also attempts to save and restore any existing viewport, while also applying its
own during rendering.
*/
void clear();
/*!
\brief This must be called once for each call to clear to properly validate
the final state of the depth texture. Failing to do this will result in undefined
behaviour.
*/
void display();
/*!
\brief Defines the area of the DepthTexture on to which to draw.
*/
void setViewport(URect);
/*!
\brief Returns the active viewport for this texture
*/
URect getViewport() const;
/*!
\brief Returns the default viewport of the DepthTexture
*/
URect getDefaultViewport() const;
/*!
\brief Returns true if the render texture is available for drawing.
If create() has not yet been called, or previously failed then this
will return false
*/
bool available() const { return m_fboID != 0; }
/*!
\brief Returns the texture ID wrappped in a handle which can be bound to
material uniforms.
*/
TextureID getTexture() const;
private:
std::uint32_t m_fboID;
std::uint32_t m_textureID;
glm::uvec2 m_size;
URect m_viewport;
std::array<std::int32_t, 4u> m_lastViewport = {};
std::int32_t m_lastBuffer;
};
} | 34.48855 | 96 | 0.644754 | fallahn |
73e6085209d8051c08f3c08df5a994e9e1d7d8af | 2,901 | cpp | C++ | parse_stdin.cpp | Payshare/cpptoml | 5361e1c2eb2e00ac6566cfc973a1f9508f447b85 | [
"MIT"
] | 1 | 2015-07-01T19:19:51.000Z | 2015-07-01T19:19:51.000Z | parse_stdin.cpp | Payshare/cpptoml | 5361e1c2eb2e00ac6566cfc973a1f9508f447b85 | [
"MIT"
] | null | null | null | parse_stdin.cpp | Payshare/cpptoml | 5361e1c2eb2e00ac6566cfc973a1f9508f447b85 | [
"MIT"
] | null | null | null | #include "cpptoml.h"
#include <iostream>
#include <limits>
std::string escape_string(const std::string& str)
{
std::string res;
for (auto it = str.begin(); it != str.end(); ++it)
{
if (*it == '\\')
res += "\\\\";
else if (*it == '"')
res += "\\\"";
else if (*it == '\n')
res += "\\n";
else
res += *it;
}
return res;
}
void print_value(std::ostream& o, const std::shared_ptr<cpptoml::base>& base)
{
if (auto v = base->as<std::string>())
{
o << "{\"type\":\"string\",\"value\":\"" << escape_string(v->get())
<< "\"}";
}
else if (auto v = base->as<int64_t>())
{
o << "{\"type\":\"integer\",\"value\":\"" << v->get() << "\"}";
}
else if (auto v = base->as<double>())
{
o << "{\"type\":\"float\",\"value\":\"" << v->get() << "\"}";
}
else if (auto v = base->as<cpptoml::datetime>())
{
o << "{\"type\":\"datetime\",\"value\":\"" << v->get() << "\"}";
}
else if (auto v = base->as<bool>())
{
o << "{\"type\":\"bool\",\"value\":\"";
v->print(o);
o << "\"}";
}
}
void print_array(std::ostream& o, cpptoml::array& arr)
{
o << "{\"type\":\"array\",\"value\":[";
auto it = arr.get().begin();
while (it != arr.get().end())
{
if ((*it)->is_array())
print_array(o, *(*it)->as_array());
else
print_value(o, *it);
if (++it != arr.get().end())
o << ", ";
}
o << "]}";
}
void print_table(std::ostream& o, cpptoml::table& g)
{
o << "{";
auto it = g.begin();
while (it != g.end())
{
o << '"' << escape_string(it->first) << "\":";
if (it->second->is_array())
{
print_array(o, *it->second->as_array());
}
else if (it->second->is_table())
{
print_table(o, *g.get_table(it->first));
}
else if (it->second->is_table_array())
{
o << "[";
auto arr = g.get_table_array(it->first)->get();
auto ait = arr.begin();
while (ait != arr.end())
{
print_table(o, **ait);
if (++ait != arr.end())
o << ", ";
}
o << "]";
}
else
{
print_value(o, it->second);
}
if (++it != g.end())
o << ", ";
}
o << "}";
}
int main()
{
std::cout.precision(std::numeric_limits<double>::max_digits10);
cpptoml::parser p{std::cin};
try
{
cpptoml::table g = p.parse();
print_table(std::cout, g);
std::cout << std::endl;
}
catch (const cpptoml::parse_exception& ex)
{
std::cerr << "Parsing failed: " << ex.what() << std::endl;
return 1;
}
return 0;
}
| 23.778689 | 77 | 0.403999 | Payshare |
73eabcb4063b9c47087a31a241b3dcca5309cafb | 2,331 | cpp | C++ | tinydui/base/kpopuptipwnd.cpp | haomiao/tinydui | e425d930a1045f99d9e407844a448c4a5c8c104d | [
"MIT"
] | null | null | null | tinydui/base/kpopuptipwnd.cpp | haomiao/tinydui | e425d930a1045f99d9e407844a448c4a5c8c104d | [
"MIT"
] | null | null | null | tinydui/base/kpopuptipwnd.cpp | haomiao/tinydui | e425d930a1045f99d9e407844a448c4a5c8c104d | [
"MIT"
] | null | null | null | #include "kpch.h"
#include "kpopuptipwnd.h"
namespace TinyDui
{
KPopupTipWnd::KPopupTipWnd()
{
}
KPopupTipWnd::~KPopupTipWnd()
{
ReleaseResources();
}
LRESULT KPopupTipWnd::OnPaint(WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
if (!(m_hWnd && ::IsWindow(m_hWnd)))
{
return 0;
}
RECT rcWnd = {};
::GetClientRect(m_hWnd, &rcWnd);
if (::IsRectEmpty(&rcWnd))
{
return 0;
}
int nWidth = rcWnd.right - rcWnd.left;
int nHeight = rcWnd.bottom - rcWnd.top;
PAINTSTRUCT ps;
HDC hDC = ::BeginPaint(m_hWnd, &ps);
HDC hMemDC = ::CreateCompatibleDC(hDC);
HBITMAP hBmpMem = ::CreateCompatibleBitmap(hDC, nWidth, nHeight);
HBITMAP hOldBmpMem = (HBITMAP)::SelectObject(hMemDC, hBmpMem);
::SetBkMode(hMemDC, TRANSPARENT);
DrawBackground(hMemDC);
DrawOthers(hMemDC);
DrawControls(hMemDC);
::BitBlt(hDC, 0, 0, nWidth, nHeight, hMemDC, 0, 0, SRCCOPY);
::SelectObject(hMemDC, hOldBmpMem);
SAFE_DELETE_OBJECT(hBmpMem);
SAFE_DELETE_DC(hMemDC);
::EndPaint(m_hWnd, &ps);
bHandled = TRUE;
return 0;
}
BOOL KPopupTipWnd::OnCommand(WPARAM wParam, LPARAM lParam)
{
return FALSE;
}
LRESULT KPopupTipWnd::OnCommand(WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
bHandled = TRUE;
return (LRESULT)OnCommand(wParam, lParam);
}
LRESULT KPopupTipWnd::OnSize(WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
bHandled = TRUE;
return (LRESULT)OnSize(wParam, lParam);
}
BOOL KPopupTipWnd::OnSize(WPARAM wParam, LPARAM lParam)
{
return FALSE;
}
LRESULT KPopupTipWnd::OnKeyUp(WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
bHandled = TRUE;
return (LRESULT)OnKeyUp(wParam, lParam);
}
BOOL KPopupTipWnd::OnKeyUp(WPARAM wParam, LPARAM lParam)
{
return FALSE;
}
LRESULT KPopupTipWnd::OnEraseBkgnd(WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
bHandled = TRUE;
return TRUE;
}
void KPopupTipWnd::InitializeWnd()
{
if (!(m_hWnd && ::IsWindow(m_hWnd)))
{
return;
}
InitResources();
InitControls();
}
void KPopupTipWnd::DrawBackground(HDC hDC)
{
}
void KPopupTipWnd::DrawOthers(HDC hDC)
{
}
void KPopupTipWnd::DrawControls(HDC hDC)
{
}
void KPopupTipWnd::InitControls()
{
}
void KPopupTipWnd::InitResources()
{
}
void KPopupTipWnd::ReleaseResources()
{
}
}
| 17.139706 | 81 | 0.673531 | haomiao |
73ee26f17719fc968feaee5afd906e1b63fe2489 | 46,486 | cc | C++ | facerecognitionlibrary/jni-build/jni/genfiles/tensorflow/core/framework/device_attributes.pb.cc | ikaee/bfr-attendant | 15e5a00d0dcb39b2903988658e3424b19bbc5a9f | [
"Apache-2.0"
] | 5 | 2018-03-22T06:56:15.000Z | 2018-09-04T02:41:35.000Z | facerecognitionlibrary/jni-build/jni/genfiles/tensorflow/core/framework/device_attributes.pb.cc | ikaee/bfr-attendant | 15e5a00d0dcb39b2903988658e3424b19bbc5a9f | [
"Apache-2.0"
] | null | null | null | facerecognitionlibrary/jni-build/jni/genfiles/tensorflow/core/framework/device_attributes.pb.cc | ikaee/bfr-attendant | 15e5a00d0dcb39b2903988658e3424b19bbc5a9f | [
"Apache-2.0"
] | 2 | 2018-05-16T10:40:26.000Z | 2020-08-25T09:05:23.000Z | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: tensorflow/core/framework/device_attributes.proto
#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include "tensorflow/core/framework/device_attributes.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
namespace tensorflow {
class DeviceLocalityDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<DeviceLocality> {
} _DeviceLocality_default_instance_;
class DeviceAttributesDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<DeviceAttributes> {
} _DeviceAttributes_default_instance_;
namespace protobuf_tensorflow_2fcore_2fframework_2fdevice_5fattributes_2eproto {
namespace {
::google::protobuf::Metadata file_level_metadata[2];
} // namespace
const ::google::protobuf::uint32 TableStruct::offsets[] = {
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DeviceLocality, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DeviceLocality, bus_id_),
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DeviceAttributes, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DeviceAttributes, name_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DeviceAttributes, device_type_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DeviceAttributes, memory_limit_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DeviceAttributes, locality_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DeviceAttributes, incarnation_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DeviceAttributes, physical_device_desc_),
};
static const ::google::protobuf::internal::MigrationSchema schemas[] = {
{ 0, -1, sizeof(DeviceLocality)},
{ 5, -1, sizeof(DeviceAttributes)},
};
static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&_DeviceLocality_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&_DeviceAttributes_default_instance_),
};
namespace {
void protobuf_AssignDescriptors() {
AddDescriptors();
::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
"tensorflow/core/framework/device_attributes.proto", schemas, file_default_instances, TableStruct::offsets, factory,
file_level_metadata, NULL, NULL);
}
void protobuf_AssignDescriptorsOnce() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 2);
}
} // namespace
void TableStruct::Shutdown() {
_DeviceLocality_default_instance_.Shutdown();
delete file_level_metadata[0].reflection;
_DeviceAttributes_default_instance_.Shutdown();
delete file_level_metadata[1].reflection;
}
void TableStruct::InitDefaultsImpl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
::google::protobuf::internal::InitProtobufDefaults();
_DeviceLocality_default_instance_.DefaultConstruct();
_DeviceAttributes_default_instance_.DefaultConstruct();
_DeviceAttributes_default_instance_.get_mutable()->locality_ = const_cast< ::tensorflow::DeviceLocality*>(
::tensorflow::DeviceLocality::internal_default_instance());
}
void InitDefaults() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &TableStruct::InitDefaultsImpl);
}
void AddDescriptorsImpl() {
InitDefaults();
static const char descriptor[] = {
"\n1tensorflow/core/framework/device_attri"
"butes.proto\022\ntensorflow\" \n\016DeviceLocalit"
"y\022\016\n\006bus_id\030\001 \001(\005\"\254\001\n\020DeviceAttributes\022\014"
"\n\004name\030\001 \001(\t\022\023\n\013device_type\030\002 \001(\t\022\024\n\014mem"
"ory_limit\030\004 \001(\003\022,\n\010locality\030\005 \001(\0132\032.tens"
"orflow.DeviceLocality\022\023\n\013incarnation\030\006 \001"
"(\006\022\034\n\024physical_device_desc\030\007 \001(\tB7\n\030org."
"tensorflow.frameworkB\026DeviceAttributesPr"
"otosP\001\370\001\001b\006proto3"
};
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
descriptor, 337);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"tensorflow/core/framework/device_attributes.proto", &protobuf_RegisterTypes);
::google::protobuf::internal::OnShutdown(&TableStruct::Shutdown);
}
void AddDescriptors() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer {
StaticDescriptorInitializer() {
AddDescriptors();
}
} static_descriptor_initializer;
} // namespace protobuf_tensorflow_2fcore_2fframework_2fdevice_5fattributes_2eproto
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int DeviceLocality::kBusIdFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
DeviceLocality::DeviceLocality()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
protobuf_tensorflow_2fcore_2fframework_2fdevice_5fattributes_2eproto::InitDefaults();
}
SharedCtor();
// @@protoc_insertion_point(constructor:tensorflow.DeviceLocality)
}
DeviceLocality::DeviceLocality(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
protobuf_tensorflow_2fcore_2fframework_2fdevice_5fattributes_2eproto::InitDefaults();
#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:tensorflow.DeviceLocality)
}
DeviceLocality::DeviceLocality(const DeviceLocality& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
bus_id_ = from.bus_id_;
// @@protoc_insertion_point(copy_constructor:tensorflow.DeviceLocality)
}
void DeviceLocality::SharedCtor() {
bus_id_ = 0;
_cached_size_ = 0;
}
DeviceLocality::~DeviceLocality() {
// @@protoc_insertion_point(destructor:tensorflow.DeviceLocality)
SharedDtor();
}
void DeviceLocality::SharedDtor() {
::google::protobuf::Arena* arena = GetArenaNoVirtual();
if (arena != NULL) {
return;
}
}
void DeviceLocality::ArenaDtor(void* object) {
DeviceLocality* _this = reinterpret_cast< DeviceLocality* >(object);
(void)_this;
}
void DeviceLocality::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void DeviceLocality::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* DeviceLocality::descriptor() {
protobuf_tensorflow_2fcore_2fframework_2fdevice_5fattributes_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_tensorflow_2fcore_2fframework_2fdevice_5fattributes_2eproto::file_level_metadata[0].descriptor;
}
const DeviceLocality& DeviceLocality::default_instance() {
protobuf_tensorflow_2fcore_2fframework_2fdevice_5fattributes_2eproto::InitDefaults();
return *internal_default_instance();
}
DeviceLocality* DeviceLocality::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<DeviceLocality>(arena);
}
void DeviceLocality::Clear() {
// @@protoc_insertion_point(message_clear_start:tensorflow.DeviceLocality)
bus_id_ = 0;
}
bool DeviceLocality::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:tensorflow.DeviceLocality)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// int32 bus_id = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(8u)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &bus_id_)));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:tensorflow.DeviceLocality)
return true;
failure:
// @@protoc_insertion_point(parse_failure:tensorflow.DeviceLocality)
return false;
#undef DO_
}
void DeviceLocality::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:tensorflow.DeviceLocality)
// int32 bus_id = 1;
if (this->bus_id() != 0) {
::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->bus_id(), output);
}
// @@protoc_insertion_point(serialize_end:tensorflow.DeviceLocality)
}
::google::protobuf::uint8* DeviceLocality::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:tensorflow.DeviceLocality)
// int32 bus_id = 1;
if (this->bus_id() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->bus_id(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:tensorflow.DeviceLocality)
return target;
}
size_t DeviceLocality::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:tensorflow.DeviceLocality)
size_t total_size = 0;
// int32 bus_id = 1;
if (this->bus_id() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->bus_id());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void DeviceLocality::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:tensorflow.DeviceLocality)
GOOGLE_DCHECK_NE(&from, this);
const DeviceLocality* source =
::google::protobuf::internal::DynamicCastToGenerated<const DeviceLocality>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:tensorflow.DeviceLocality)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:tensorflow.DeviceLocality)
MergeFrom(*source);
}
}
void DeviceLocality::MergeFrom(const DeviceLocality& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:tensorflow.DeviceLocality)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
if (from.bus_id() != 0) {
set_bus_id(from.bus_id());
}
}
void DeviceLocality::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:tensorflow.DeviceLocality)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void DeviceLocality::CopyFrom(const DeviceLocality& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:tensorflow.DeviceLocality)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool DeviceLocality::IsInitialized() const {
return true;
}
void DeviceLocality::Swap(DeviceLocality* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
DeviceLocality* temp = New(GetArenaNoVirtual());
temp->MergeFrom(*other);
other->CopyFrom(*this);
InternalSwap(temp);
if (GetArenaNoVirtual() == NULL) {
delete temp;
}
}
}
void DeviceLocality::UnsafeArenaSwap(DeviceLocality* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void DeviceLocality::InternalSwap(DeviceLocality* other) {
std::swap(bus_id_, other->bus_id_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata DeviceLocality::GetMetadata() const {
protobuf_tensorflow_2fcore_2fframework_2fdevice_5fattributes_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_tensorflow_2fcore_2fframework_2fdevice_5fattributes_2eproto::file_level_metadata[0];
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// DeviceLocality
// int32 bus_id = 1;
void DeviceLocality::clear_bus_id() {
bus_id_ = 0;
}
::google::protobuf::int32 DeviceLocality::bus_id() const {
// @@protoc_insertion_point(field_get:tensorflow.DeviceLocality.bus_id)
return bus_id_;
}
void DeviceLocality::set_bus_id(::google::protobuf::int32 value) {
bus_id_ = value;
// @@protoc_insertion_point(field_set:tensorflow.DeviceLocality.bus_id)
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
void DeviceAttributes::_slow_mutable_locality() {
locality_ = ::google::protobuf::Arena::CreateMessage< ::tensorflow::DeviceLocality >(
GetArenaNoVirtual());
}
::tensorflow::DeviceLocality* DeviceAttributes::_slow_release_locality() {
if (locality_ == NULL) {
return NULL;
} else {
::tensorflow::DeviceLocality* temp = new ::tensorflow::DeviceLocality(*locality_);
locality_ = NULL;
return temp;
}
}
::tensorflow::DeviceLocality* DeviceAttributes::unsafe_arena_release_locality() {
// @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.DeviceAttributes.locality)
::tensorflow::DeviceLocality* temp = locality_;
locality_ = NULL;
return temp;
}
void DeviceAttributes::_slow_set_allocated_locality(
::google::protobuf::Arena* message_arena, ::tensorflow::DeviceLocality** locality) {
if (message_arena != NULL &&
::google::protobuf::Arena::GetArena(*locality) == NULL) {
message_arena->Own(*locality);
} else if (message_arena !=
::google::protobuf::Arena::GetArena(*locality)) {
::tensorflow::DeviceLocality* new_locality =
::google::protobuf::Arena::CreateMessage< ::tensorflow::DeviceLocality >(
message_arena);
new_locality->CopyFrom(**locality);
*locality = new_locality;
}
}
void DeviceAttributes::unsafe_arena_set_allocated_locality(
::tensorflow::DeviceLocality* locality) {
if (GetArenaNoVirtual() == NULL) {
delete locality_;
}
locality_ = locality;
if (locality) {
} else {
}
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.DeviceAttributes.locality)
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int DeviceAttributes::kNameFieldNumber;
const int DeviceAttributes::kDeviceTypeFieldNumber;
const int DeviceAttributes::kMemoryLimitFieldNumber;
const int DeviceAttributes::kLocalityFieldNumber;
const int DeviceAttributes::kIncarnationFieldNumber;
const int DeviceAttributes::kPhysicalDeviceDescFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
DeviceAttributes::DeviceAttributes()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
protobuf_tensorflow_2fcore_2fframework_2fdevice_5fattributes_2eproto::InitDefaults();
}
SharedCtor();
// @@protoc_insertion_point(constructor:tensorflow.DeviceAttributes)
}
DeviceAttributes::DeviceAttributes(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
protobuf_tensorflow_2fcore_2fframework_2fdevice_5fattributes_2eproto::InitDefaults();
#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:tensorflow.DeviceAttributes)
}
DeviceAttributes::DeviceAttributes(const DeviceAttributes& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL),
_cached_size_(0) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.name().size() > 0) {
name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name(),
GetArenaNoVirtual());
}
device_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.device_type().size() > 0) {
device_type_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.device_type(),
GetArenaNoVirtual());
}
physical_device_desc_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.physical_device_desc().size() > 0) {
physical_device_desc_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.physical_device_desc(),
GetArenaNoVirtual());
}
if (from.has_locality()) {
locality_ = new ::tensorflow::DeviceLocality(*from.locality_);
} else {
locality_ = NULL;
}
::memcpy(&memory_limit_, &from.memory_limit_,
reinterpret_cast<char*>(&incarnation_) -
reinterpret_cast<char*>(&memory_limit_) + sizeof(incarnation_));
// @@protoc_insertion_point(copy_constructor:tensorflow.DeviceAttributes)
}
void DeviceAttributes::SharedCtor() {
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
device_type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
physical_device_desc_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
::memset(&locality_, 0, reinterpret_cast<char*>(&incarnation_) -
reinterpret_cast<char*>(&locality_) + sizeof(incarnation_));
_cached_size_ = 0;
}
DeviceAttributes::~DeviceAttributes() {
// @@protoc_insertion_point(destructor:tensorflow.DeviceAttributes)
SharedDtor();
}
void DeviceAttributes::SharedDtor() {
::google::protobuf::Arena* arena = GetArenaNoVirtual();
if (arena != NULL) {
return;
}
name_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
device_type_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
physical_device_desc_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena);
if (this != internal_default_instance()) {
delete locality_;
}
}
void DeviceAttributes::ArenaDtor(void* object) {
DeviceAttributes* _this = reinterpret_cast< DeviceAttributes* >(object);
(void)_this;
}
void DeviceAttributes::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void DeviceAttributes::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* DeviceAttributes::descriptor() {
protobuf_tensorflow_2fcore_2fframework_2fdevice_5fattributes_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_tensorflow_2fcore_2fframework_2fdevice_5fattributes_2eproto::file_level_metadata[1].descriptor;
}
const DeviceAttributes& DeviceAttributes::default_instance() {
protobuf_tensorflow_2fcore_2fframework_2fdevice_5fattributes_2eproto::InitDefaults();
return *internal_default_instance();
}
DeviceAttributes* DeviceAttributes::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<DeviceAttributes>(arena);
}
void DeviceAttributes::Clear() {
// @@protoc_insertion_point(message_clear_start:tensorflow.DeviceAttributes)
name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
device_type_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
physical_device_desc_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
if (GetArenaNoVirtual() == NULL && locality_ != NULL) {
delete locality_;
}
locality_ = NULL;
::memset(&memory_limit_, 0, reinterpret_cast<char*>(&incarnation_) -
reinterpret_cast<char*>(&memory_limit_) + sizeof(incarnation_));
}
bool DeviceAttributes::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:tensorflow.DeviceAttributes)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// string name = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->name().data(), this->name().length(),
::google::protobuf::internal::WireFormatLite::PARSE,
"tensorflow.DeviceAttributes.name"));
} else {
goto handle_unusual;
}
break;
}
// string device_type = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(18u)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_device_type()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->device_type().data(), this->device_type().length(),
::google::protobuf::internal::WireFormatLite::PARSE,
"tensorflow.DeviceAttributes.device_type"));
} else {
goto handle_unusual;
}
break;
}
// int64 memory_limit = 4;
case 4: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(32u)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>(
input, &memory_limit_)));
} else {
goto handle_unusual;
}
break;
}
// .tensorflow.DeviceLocality locality = 5;
case 5: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(42u)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_locality()));
} else {
goto handle_unusual;
}
break;
}
// fixed64 incarnation = 6;
case 6: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(49u)) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_FIXED64>(
input, &incarnation_)));
} else {
goto handle_unusual;
}
break;
}
// string physical_device_desc = 7;
case 7: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(58u)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_physical_device_desc()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->physical_device_desc().data(), this->physical_device_desc().length(),
::google::protobuf::internal::WireFormatLite::PARSE,
"tensorflow.DeviceAttributes.physical_device_desc"));
} else {
goto handle_unusual;
}
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:tensorflow.DeviceAttributes)
return true;
failure:
// @@protoc_insertion_point(parse_failure:tensorflow.DeviceAttributes)
return false;
#undef DO_
}
void DeviceAttributes::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:tensorflow.DeviceAttributes)
// string name = 1;
if (this->name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->name().data(), this->name().length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.DeviceAttributes.name");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
1, this->name(), output);
}
// string device_type = 2;
if (this->device_type().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->device_type().data(), this->device_type().length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.DeviceAttributes.device_type");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
2, this->device_type(), output);
}
// int64 memory_limit = 4;
if (this->memory_limit() != 0) {
::google::protobuf::internal::WireFormatLite::WriteInt64(4, this->memory_limit(), output);
}
// .tensorflow.DeviceLocality locality = 5;
if (this->has_locality()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
5, *this->locality_, output);
}
// fixed64 incarnation = 6;
if (this->incarnation() != 0) {
::google::protobuf::internal::WireFormatLite::WriteFixed64(6, this->incarnation(), output);
}
// string physical_device_desc = 7;
if (this->physical_device_desc().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->physical_device_desc().data(), this->physical_device_desc().length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.DeviceAttributes.physical_device_desc");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
7, this->physical_device_desc(), output);
}
// @@protoc_insertion_point(serialize_end:tensorflow.DeviceAttributes)
}
::google::protobuf::uint8* DeviceAttributes::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:tensorflow.DeviceAttributes)
// string name = 1;
if (this->name().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->name().data(), this->name().length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.DeviceAttributes.name");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
1, this->name(), target);
}
// string device_type = 2;
if (this->device_type().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->device_type().data(), this->device_type().length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.DeviceAttributes.device_type");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
2, this->device_type(), target);
}
// int64 memory_limit = 4;
if (this->memory_limit() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(4, this->memory_limit(), target);
}
// .tensorflow.DeviceLocality locality = 5;
if (this->has_locality()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
5, *this->locality_, false, target);
}
// fixed64 incarnation = 6;
if (this->incarnation() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteFixed64ToArray(6, this->incarnation(), target);
}
// string physical_device_desc = 7;
if (this->physical_device_desc().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->physical_device_desc().data(), this->physical_device_desc().length(),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"tensorflow.DeviceAttributes.physical_device_desc");
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
7, this->physical_device_desc(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:tensorflow.DeviceAttributes)
return target;
}
size_t DeviceAttributes::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:tensorflow.DeviceAttributes)
size_t total_size = 0;
// string name = 1;
if (this->name().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->name());
}
// string device_type = 2;
if (this->device_type().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->device_type());
}
// string physical_device_desc = 7;
if (this->physical_device_desc().size() > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->physical_device_desc());
}
// .tensorflow.DeviceLocality locality = 5;
if (this->has_locality()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*this->locality_);
}
// int64 memory_limit = 4;
if (this->memory_limit() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int64Size(
this->memory_limit());
}
// fixed64 incarnation = 6;
if (this->incarnation() != 0) {
total_size += 1 + 8;
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void DeviceAttributes::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:tensorflow.DeviceAttributes)
GOOGLE_DCHECK_NE(&from, this);
const DeviceAttributes* source =
::google::protobuf::internal::DynamicCastToGenerated<const DeviceAttributes>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:tensorflow.DeviceAttributes)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:tensorflow.DeviceAttributes)
MergeFrom(*source);
}
}
void DeviceAttributes::MergeFrom(const DeviceAttributes& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:tensorflow.DeviceAttributes)
GOOGLE_DCHECK_NE(&from, this);
_internal_metadata_.MergeFrom(from._internal_metadata_);
if (from.name().size() > 0) {
set_name(from.name());
}
if (from.device_type().size() > 0) {
set_device_type(from.device_type());
}
if (from.physical_device_desc().size() > 0) {
set_physical_device_desc(from.physical_device_desc());
}
if (from.has_locality()) {
mutable_locality()->::tensorflow::DeviceLocality::MergeFrom(from.locality());
}
if (from.memory_limit() != 0) {
set_memory_limit(from.memory_limit());
}
if (from.incarnation() != 0) {
set_incarnation(from.incarnation());
}
}
void DeviceAttributes::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:tensorflow.DeviceAttributes)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void DeviceAttributes::CopyFrom(const DeviceAttributes& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:tensorflow.DeviceAttributes)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool DeviceAttributes::IsInitialized() const {
return true;
}
void DeviceAttributes::Swap(DeviceAttributes* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
DeviceAttributes* temp = New(GetArenaNoVirtual());
temp->MergeFrom(*other);
other->CopyFrom(*this);
InternalSwap(temp);
if (GetArenaNoVirtual() == NULL) {
delete temp;
}
}
}
void DeviceAttributes::UnsafeArenaSwap(DeviceAttributes* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void DeviceAttributes::InternalSwap(DeviceAttributes* other) {
name_.Swap(&other->name_);
device_type_.Swap(&other->device_type_);
physical_device_desc_.Swap(&other->physical_device_desc_);
std::swap(locality_, other->locality_);
std::swap(memory_limit_, other->memory_limit_);
std::swap(incarnation_, other->incarnation_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata DeviceAttributes::GetMetadata() const {
protobuf_tensorflow_2fcore_2fframework_2fdevice_5fattributes_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_tensorflow_2fcore_2fframework_2fdevice_5fattributes_2eproto::file_level_metadata[1];
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// DeviceAttributes
// string name = 1;
void DeviceAttributes::clear_name() {
name_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
const ::std::string& DeviceAttributes::name() const {
// @@protoc_insertion_point(field_get:tensorflow.DeviceAttributes.name)
return name_.Get();
}
void DeviceAttributes::set_name(const ::std::string& value) {
name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:tensorflow.DeviceAttributes.name)
}
void DeviceAttributes::set_name(const char* value) {
name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:tensorflow.DeviceAttributes.name)
}
void DeviceAttributes::set_name(const char* value,
size_t size) {
name_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:tensorflow.DeviceAttributes.name)
}
::std::string* DeviceAttributes::mutable_name() {
// @@protoc_insertion_point(field_mutable:tensorflow.DeviceAttributes.name)
return name_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
::std::string* DeviceAttributes::release_name() {
// @@protoc_insertion_point(field_release:tensorflow.DeviceAttributes.name)
return name_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
::std::string* DeviceAttributes::unsafe_arena_release_name() {
// @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.DeviceAttributes.name)
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
return name_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
void DeviceAttributes::set_allocated_name(::std::string* name) {
if (name != NULL) {
} else {
}
name_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name,
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:tensorflow.DeviceAttributes.name)
}
void DeviceAttributes::unsafe_arena_set_allocated_name(
::std::string* name) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
if (name != NULL) {
} else {
}
name_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
name, GetArenaNoVirtual());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.DeviceAttributes.name)
}
// string device_type = 2;
void DeviceAttributes::clear_device_type() {
device_type_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
const ::std::string& DeviceAttributes::device_type() const {
// @@protoc_insertion_point(field_get:tensorflow.DeviceAttributes.device_type)
return device_type_.Get();
}
void DeviceAttributes::set_device_type(const ::std::string& value) {
device_type_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:tensorflow.DeviceAttributes.device_type)
}
void DeviceAttributes::set_device_type(const char* value) {
device_type_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:tensorflow.DeviceAttributes.device_type)
}
void DeviceAttributes::set_device_type(const char* value,
size_t size) {
device_type_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:tensorflow.DeviceAttributes.device_type)
}
::std::string* DeviceAttributes::mutable_device_type() {
// @@protoc_insertion_point(field_mutable:tensorflow.DeviceAttributes.device_type)
return device_type_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
::std::string* DeviceAttributes::release_device_type() {
// @@protoc_insertion_point(field_release:tensorflow.DeviceAttributes.device_type)
return device_type_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
::std::string* DeviceAttributes::unsafe_arena_release_device_type() {
// @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.DeviceAttributes.device_type)
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
return device_type_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
void DeviceAttributes::set_allocated_device_type(::std::string* device_type) {
if (device_type != NULL) {
} else {
}
device_type_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), device_type,
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:tensorflow.DeviceAttributes.device_type)
}
void DeviceAttributes::unsafe_arena_set_allocated_device_type(
::std::string* device_type) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
if (device_type != NULL) {
} else {
}
device_type_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
device_type, GetArenaNoVirtual());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.DeviceAttributes.device_type)
}
// int64 memory_limit = 4;
void DeviceAttributes::clear_memory_limit() {
memory_limit_ = GOOGLE_LONGLONG(0);
}
::google::protobuf::int64 DeviceAttributes::memory_limit() const {
// @@protoc_insertion_point(field_get:tensorflow.DeviceAttributes.memory_limit)
return memory_limit_;
}
void DeviceAttributes::set_memory_limit(::google::protobuf::int64 value) {
memory_limit_ = value;
// @@protoc_insertion_point(field_set:tensorflow.DeviceAttributes.memory_limit)
}
// .tensorflow.DeviceLocality locality = 5;
bool DeviceAttributes::has_locality() const {
return this != internal_default_instance() && locality_ != NULL;
}
void DeviceAttributes::clear_locality() {
if (GetArenaNoVirtual() == NULL && locality_ != NULL) delete locality_;
locality_ = NULL;
}
const ::tensorflow::DeviceLocality& DeviceAttributes::locality() const {
// @@protoc_insertion_point(field_get:tensorflow.DeviceAttributes.locality)
return locality_ != NULL ? *locality_
: *::tensorflow::DeviceLocality::internal_default_instance();
}
::tensorflow::DeviceLocality* DeviceAttributes::mutable_locality() {
if (locality_ == NULL) {
_slow_mutable_locality();
}
// @@protoc_insertion_point(field_mutable:tensorflow.DeviceAttributes.locality)
return locality_;
}
::tensorflow::DeviceLocality* DeviceAttributes::release_locality() {
// @@protoc_insertion_point(field_release:tensorflow.DeviceAttributes.locality)
if (GetArenaNoVirtual() != NULL) {
return _slow_release_locality();
} else {
::tensorflow::DeviceLocality* temp = locality_;
locality_ = NULL;
return temp;
}
}
void DeviceAttributes::set_allocated_locality(::tensorflow::DeviceLocality* locality) {
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
if (message_arena == NULL) {
delete locality_;
}
if (locality != NULL) {
_slow_set_allocated_locality(message_arena, &locality);
}
locality_ = locality;
if (locality) {
} else {
}
// @@protoc_insertion_point(field_set_allocated:tensorflow.DeviceAttributes.locality)
}
// fixed64 incarnation = 6;
void DeviceAttributes::clear_incarnation() {
incarnation_ = GOOGLE_ULONGLONG(0);
}
::google::protobuf::uint64 DeviceAttributes::incarnation() const {
// @@protoc_insertion_point(field_get:tensorflow.DeviceAttributes.incarnation)
return incarnation_;
}
void DeviceAttributes::set_incarnation(::google::protobuf::uint64 value) {
incarnation_ = value;
// @@protoc_insertion_point(field_set:tensorflow.DeviceAttributes.incarnation)
}
// string physical_device_desc = 7;
void DeviceAttributes::clear_physical_device_desc() {
physical_device_desc_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
const ::std::string& DeviceAttributes::physical_device_desc() const {
// @@protoc_insertion_point(field_get:tensorflow.DeviceAttributes.physical_device_desc)
return physical_device_desc_.Get();
}
void DeviceAttributes::set_physical_device_desc(const ::std::string& value) {
physical_device_desc_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual());
// @@protoc_insertion_point(field_set:tensorflow.DeviceAttributes.physical_device_desc)
}
void DeviceAttributes::set_physical_device_desc(const char* value) {
physical_device_desc_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value),
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_char:tensorflow.DeviceAttributes.physical_device_desc)
}
void DeviceAttributes::set_physical_device_desc(const char* value,
size_t size) {
physical_device_desc_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(
reinterpret_cast<const char*>(value), size), GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_pointer:tensorflow.DeviceAttributes.physical_device_desc)
}
::std::string* DeviceAttributes::mutable_physical_device_desc() {
// @@protoc_insertion_point(field_mutable:tensorflow.DeviceAttributes.physical_device_desc)
return physical_device_desc_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
::std::string* DeviceAttributes::release_physical_device_desc() {
// @@protoc_insertion_point(field_release:tensorflow.DeviceAttributes.physical_device_desc)
return physical_device_desc_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual());
}
::std::string* DeviceAttributes::unsafe_arena_release_physical_device_desc() {
// @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.DeviceAttributes.physical_device_desc)
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
return physical_device_desc_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
}
void DeviceAttributes::set_allocated_physical_device_desc(::std::string* physical_device_desc) {
if (physical_device_desc != NULL) {
} else {
}
physical_device_desc_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), physical_device_desc,
GetArenaNoVirtual());
// @@protoc_insertion_point(field_set_allocated:tensorflow.DeviceAttributes.physical_device_desc)
}
void DeviceAttributes::unsafe_arena_set_allocated_physical_device_desc(
::std::string* physical_device_desc) {
GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);
if (physical_device_desc != NULL) {
} else {
}
physical_device_desc_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
physical_device_desc, GetArenaNoVirtual());
// @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.DeviceAttributes.physical_device_desc)
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
} // namespace tensorflow
// @@protoc_insertion_point(global_scope)
| 37.855049 | 122 | 0.730456 | ikaee |
73f03a35bda1f124aacf91743b48f77502f19440 | 1,147 | cpp | C++ | leetcode/30days-challenge/202004/day4.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | 18 | 2020-08-27T05:27:50.000Z | 2022-03-08T02:56:48.000Z | leetcode/30days-challenge/202004/day4.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | null | null | null | leetcode/30days-challenge/202004/day4.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | 1 | 2020-10-13T05:23:58.000Z | 2020-10-13T05:23:58.000Z | /*
Move Zeroes
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
*/
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int k=0;
int sz=nums.size();
// loop thru the array and check if it is non-zero
// if so, move it to position k and increase k by 1
// 0 1 0 3 12 // k = 0
// ^
// 1 1 0 3 12 // k = 1
// ^
// 1 3 0 3 12 // k = 2
// ^
// 1 3 12 3 12 // k = 3
for(int i=0;i<sz;i++) if(nums[i]!=0) nums[k++]=nums[i];
// Starting from position k, replace all the number with 0 till nums.size()-1
// 1 3 12 3 12 // k = 3
// ^
// 1 3 12 0 0
for(int i=k;i<sz;i++) nums[i]=0;
}
};
static const auto io_sync_off = []() {std::ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);return 0;}();
| 29.410256 | 133 | 0.530078 | wingkwong |
73f978f5dfe772de0c40a955b1b0e7a17bfee469 | 26,817 | hpp | C++ | hpx/runtime/threads/threadmanager_impl.hpp | andreasbuhr/hpx | 4366a90aacbd3e95428a94ab24a1646a67459cc2 | [
"BSL-1.0"
] | null | null | null | hpx/runtime/threads/threadmanager_impl.hpp | andreasbuhr/hpx | 4366a90aacbd3e95428a94ab24a1646a67459cc2 | [
"BSL-1.0"
] | null | null | null | hpx/runtime/threads/threadmanager_impl.hpp | andreasbuhr/hpx | 4366a90aacbd3e95428a94ab24a1646a67459cc2 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2007-2013 Hartmut Kaiser
// Copyright (c) 2007-2009 Chirag Dekate, Anshul Tandon
// Copyright (c) 2011 Bryce Lelbach, Katelyn Kufahl
//
// 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)
#if !defined(HPX_THREADMANAGER_IMPL_HPP)
#define HPX_THREADMANAGER_IMPL_HPP
#include <hpx/config.hpp>
#include <boost/atomic.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/thread.hpp>
#include <boost/thread/condition.hpp>
#include <hpx/exception.hpp>
#include <hpx/state.hpp>
#include <hpx/runtime/naming/name.hpp>
#include <hpx/runtime/threads/thread_init_data.hpp>
#include <hpx/runtime/threads/threadmanager.hpp>
#include <hpx/performance_counters/counters.hpp>
#include <hpx/util/io_service_pool.hpp>
#include <hpx/util/block_profiler.hpp>
#include <hpx/util/spinlock.hpp>
#include <hpx/util/lockfree/fifo.hpp>
#include <hpx/config/warnings_prefix.hpp>
#include <vector>
#include <memory>
#include <numeric>
// TODO: add branch prediction and function heat
namespace hpx { namespace threads
{
///////////////////////////////////////////////////////////////////////////
/// The \a threadmanager class is the central instance of management for
/// all (non-depleted) threads
template <typename SchedulingPolicy, typename NotificationPolicy>
class HPX_EXPORT threadmanager_impl : public threadmanager_base
{
private:
// we use a simple mutex to protect the data members of the
// threadmanager for now
typedef boost::mutex mutex_type;
// we use the boost::posix_time::ptime type for time representation
typedef typename threadmanager_base::time_type time_type;
// we use the boost::posix_time::time_duration type as the duration
// representation
typedef typename threadmanager_base::duration_type duration_type;
public:
typedef SchedulingPolicy scheduling_policy_type;
typedef NotificationPolicy notification_policy_type;
///
threadmanager_impl(util::io_service_pool& timer_pool,
scheduling_policy_type& scheduler,
notification_policy_type& notifier,
std::size_t num_threads);
~threadmanager_impl();
/// The function \a register_work adds a new work item to the thread
/// manager. It doesn't immediately create a new \a thread, it just adds
/// the task parameters (function, initial state and description) to
/// the internal management data structures. The thread itself will be
/// created when the number of existing threads drops below the number
/// of threads specified by the constructors max_count parameter.
///
/// \param func [in] The function or function object to execute as
/// the thread's function. This must have a signature as
/// defined by \a thread_function_type.
/// \param description [in] The value of this parameter allows to
/// specify a description of the thread to create. This
/// information is used for logging purposes mainly, but
/// might be useful for debugging as well. This parameter
/// is optional and defaults to an empty string.
/// \param initial_state
/// [in] The value of this parameter defines the initial
/// state of the newly created \a thread. This must be
/// one of the values as defined by the \a thread_state
/// enumeration (thread_state#pending, or \a
/// thread_state#suspended, any other value will throw a
/// hpx#bad_parameter exception).
void register_work(thread_init_data& data,
thread_state_enum initial_state = pending,
error_code& ec = throws);
/// The function \a register_thread adds a new work item to the thread
/// manager. It creates a new \a thread, adds it to the internal
/// management data structures, and schedules the new thread, if
/// appropriate.
///
/// \param func [in] The function or function object to execute as
/// the thread's function. This must have a signature as
/// defined by \a thread_function_type.
/// \param description [in] The value of this parameter allows to
/// specify a description of the thread to create. This
/// information is used for logging purposes mainly, but
/// might be useful for debugging as well. This parameter
/// is optional and defaults to an empty string.
/// \param initial_state
/// [in] The value of this parameter defines the initial
/// state of the newly created \a thread. This must be
/// one of the values as defined by the \a thread_state
/// enumeration (thread_state#pending, or \a
/// thread_state#suspended, any other value will throw a
/// hpx#bad_parameter exception).
/// \param run_now [in] If this parameter is \a true and the initial
/// state is given as \a thread_state#pending the thread
/// will be run immediately, otherwise it will be
/// scheduled to run later (either this function is
/// called for another thread using \a true for the
/// parameter \a run_now or the function \a
/// threadmanager#do_some_work is called). This parameter
/// is optional and defaults to \a true.
///
/// \returns The function returns the thread id of the newly
/// created thread.
thread_id_type register_thread(thread_init_data& data,
thread_state_enum initial_state = pending,
bool run_now = true, error_code& ec = throws);
/// \brief Run the thread manager's work queue. This function
/// instantiates the specified number of OS threads. All OS
/// threads are started to execute the function \a tfunc.
///
/// \param num_threads
/// [in] The initial number of threads to be started by
/// this thread manager instance. This parameter is
/// optional and defaults to 1 (one).
///
/// \returns The function returns \a true if the thread manager
/// has been started successfully, otherwise it returns
/// \a false.
bool run(std::size_t num_threads = 1);
/// The get_interruption_enabled function is part of the thread related
/// API. It queries whether of one of the threads known can be
/// interrupted.
///
/// \param id [in] The thread id of the thread to query.
///
/// \returns This function returns whether the thread referenced
/// by the \a id parameter can be interrupted. If the
/// thread is not known to the thread-manager the return
/// value will be false.
bool get_interruption_enabled(thread_id_type id,
error_code& ec = throws);
/// The set_interruption_enabled function is part of the thread related
/// API. It sets whether of one of the threads known can be
/// interrupted.
///
/// \param id [in] The thread id of the thread to query.
bool set_interruption_enabled(thread_id_type id, bool enable,
error_code& ec = throws);
/// The get_interruption_requested function is part of the thread related
/// API. It queries whether of one of the threads known has been
/// interrupted.
///
/// \param id [in] The thread id of the thread to query.
///
/// \returns This function returns whether the thread referenced
/// by the \a id parameter has been interrupted. If the
/// thread is not known to the thread-manager the return
/// value will be false.
bool get_interruption_requested(thread_id_type id,
error_code& ec = throws);
/// The interrupt function is part of the thread related API. It
/// queries notifies one of the threads to abort at the next
/// interruption point.
///
/// \param id [in] The thread id of the thread to interrupt.
/// \param flag [in] The flag encodes whether the thread should be
/// interrupted (if it is \a true), or 'uninterrupted'
/// (if it is \a false).
/// \param ec [in,out] this represents the error status on exit,
/// if this is pre-initialized to \a hpx#throws
/// the function will throw on error instead.
void interrupt(thread_id_type id, bool flag, error_code& ec = throws);
/// Interrupt the current thread at this point if it was canceled. This
/// will throw a thread_interrupted exception, which will cancel the thread.
///
/// \param id [in] The thread id of the thread which should be
/// interrupted.
/// \param ec [in,out] this represents the error status on exit,
/// if this is pre-initialized to \a hpx#throws
/// the function will throw on error instead.
void interruption_point(thread_id_type id, error_code& ec = throws);
/// The run_thread_exit_callbacks function is part of the thread related
/// API. It runs all exit functions for one of the threads.
///
/// \param id [in] The thread id of the thread to interrupt.
void run_thread_exit_callbacks(thread_id_type id,
error_code& ec = throws);
/// The add_thread_exit_callback function is part of the thread related
/// API. It adds a callback function to be executed at thread exit.
///
/// \param id [in] The thread id of the thread to interrupt.
///
/// \returns This function returns whether the function has been
/// added to the referenced thread
/// by the \a id parameter has been interrupted. If the
/// thread is not known to the thread-manager the return
/// value will be false.
bool add_thread_exit_callback(thread_id_type id,
HPX_STD_FUNCTION<void()> const& f, error_code& ec = throws);
///
void free_thread_exit_callbacks(thread_id_type id,
error_code& ec = throws);
/// \brief Forcefully stop the thread-manager
///
/// \param blocking
///
void stop (bool blocking = true);
/// \brief Return whether the thread manager is still running
state status() const
{
return state_.load();
}
/// \brief return the number of HPX-threads with the given state
///
/// \note This function lock the internal OS lock in the thread manager
boost::int64_t get_thread_count(thread_state_enum state = unknown,
thread_priority priority = thread_priority_default) const;
// \brief Abort all threads which are in suspended state. This will set
// the state of all suspended threads to \a pending while
// supplying the wait_abort extended state flag
void abort_all_suspended_threads();
// \brief Clean up terminated threads. This deletes all threads which
// have been terminated but which are still held in the queue
// of terminated threads. Some schedulers might not do anything
// here.
bool cleanup_terminated(bool delete_all = false);
/// \brief Return the number of OS threads running in this thread-manager
///
/// This function will return correct results only if the thread-manager
/// is running.
std::size_t get_os_thread_count() const
{
mutex_type::scoped_lock lk(mtx_);
return threads_.size();
}
/// The set_state function is part of the thread related API and allows
/// to change the state of one of the threads managed by this
/// threadmanager.
///
/// \param id [in] The thread id of the thread the state should
/// be modified for.
/// \param newstate [in] The new state to be set for the thread
/// referenced by the \a id parameter.
/// \param newstate_ex [in] The new extended state to be set for the
/// thread referenced by the \a id parameter.
/// \param priority [in] The priority with which the thread will be
/// executed if the parameter \a newstate is pending.
///
/// \returns This function returns the previous state of the
/// thread referenced by the \a id parameter. It will
/// return one of the values as defined by the
/// \a thread_state enumeration. If the
/// thread is not known to the threadmanager the return
/// value will be \a thread_state#unknown.
///
/// \note If the thread referenced by the parameter \a id
/// is in \a thread_state#active state this function
/// schedules a new thread which will set the state of
/// the thread as soon as its not active anymore. The
/// function returns \a thread_state#active in this case.
thread_state set_state(thread_id_type id, thread_state_enum newstate,
thread_state_ex_enum newstate_ex = wait_signaled,
thread_priority priority = thread_priority_default,
error_code& ec = throws);
/// The get_state function is part of the thread related API. It
/// queries the state of one of the threads known to the thread manager
///
/// \param id [in] The thread id of the thread the state should
/// be returned for.
///
/// \returns This function returns the current state of the
/// thread referenced by the \a id parameter. It will
/// return one of the values as defined by the
/// \a thread_state enumeration. If the
/// thread is not known to the thread manager the return
/// value will be \a thread_state#unknown.
thread_state get_state(thread_id_type id);
/// The get_phase function is part of the thread related API. It
/// queries the phase of one of the threads known to the thread manager
///
/// \param id [in] The thread id of the thread the phase should
/// be returned for.
///
/// \returns This function returns the current phase of the
/// thread referenced by the \a id parameter. If the
/// thread is not known to the thread manager the return
/// value will be ~0.
std::size_t get_phase(thread_id_type id);
/// The get_priority function is part of the thread related API. It
/// queries the priority of one of the threads known to the thread manager
///
/// \param id [in] The thread id of the thread the phase should
/// be returned for.
///
/// \returns This function returns the current priority of the
/// thread referenced by the \a id parameter. If the
/// thread is not known to the thread manager the return
/// value will be ~0.
thread_priority get_priority(thread_id_type id);
/// Set a timer to set the state of the given \a thread to the given
/// new value after it expired (at the given time)
/// \brief Set the thread state of the \a thread referenced by the
/// thread_id \a id.
///
/// Set a timer to set the state of the given \a thread to the given
/// new value after it expired (at the given time)
///
/// \param id [in] The thread id of the thread the state should
/// be modified for.
/// \param at_time
/// \param state [in] The new state to be set for the thread
/// referenced by the \a id parameter.
/// \param newstate_ex [in] The new extended state to be set for the
/// thread referenced by the \a id parameter.
/// \param priority [in] The priority with which the thread will be
/// executed if the parameter \a new_state is pending.
///
/// \returns
thread_id_type set_state (time_type const& expire_at,
thread_id_type id, thread_state_enum newstate = pending,
thread_state_ex_enum newstate_ex = wait_timeout,
thread_priority priority = thread_priority_default,
error_code& ec = throws);
/// \brief Set the thread state of the \a thread referenced by the
/// thread_id \a id.
///
/// Set a timer to set the state of the given \a thread to the given
/// new value after it expired (after the given duration)
///
/// \param id [in] The thread id of the thread the state should
/// be modified for.
/// \param after_duration
/// \param state [in] The new state to be set for the thread
/// referenced by the \a id parameter.
/// \param newstate_ex [in] The new extended state to be set for the
/// thread referenced by the \a id parameter.
/// \param priority [in] The priority with which the thread will be
/// executed if the parameter \a new_state is pending.
///
/// \returns
thread_id_type set_state (duration_type const& expire_from_now,
thread_id_type id, thread_state_enum newstate = pending,
thread_state_ex_enum newstate_ex = wait_timeout,
thread_priority priority = thread_priority_default,
error_code& ec = throws);
/// The get_description function is part of the thread related API and
/// allows to query the description of one of the threads known to the
/// threadmanager
///
/// \param id [in] The thread id of the thread the description
/// should be returned for.
///
/// \returns This function returns the description of the
/// thread referenced by the \a id parameter. If the
/// thread is not known to the thread-manager the return
/// value will be the string "<unknown>".
char const* get_description(thread_id_type id) const;
char const* set_description(thread_id_type id, char const* desc = 0);
char const* get_lco_description(thread_id_type id) const;
char const* set_lco_description(thread_id_type id, char const* desc = 0);
/// The function get_thread_backtrace is part of the thread related API
/// allows to query the currently stored thread back trace (which is
/// captured during thread suspension).
///
/// \param id [in] The thread id of the thread being queried.
/// \param ec [in,out] this represents the error status on exit,
/// if this is pre-initialized to \a hpx#throws
/// the function will throw on error instead.
///
/// \returns This function returns the currently captured stack
/// back trace of the thread referenced by the \a id
/// parameter. If the thread is not known to the
/// thread-manager the return value will be the zero.
util::backtrace const* get_backtrace(thread_id_type id) const;
util::backtrace const* set_backtrace(thread_id_type id, util::backtrace const* bt = 0);
#if HPX_THREAD_MAINTAIN_THREAD_DATA
/// The get_thread_data function is part of the thread related
/// API. It queries the currently stored thread specific data pointer.
///
/// \param id [in] The thread id of the thread to query.
///
/// \returns This function returns the thread specific data
/// pointer or zero if none is set.
std::size_t get_thread_data(thread_id_type id,
error_code& ec = throws) const;
/// The set_thread_data function is part of the thread related
/// API. It sets the currently stored thread specific data pointer.
///
/// \param id [in] The thread id of the thread to query.
/// \param data [in] The thread specific data pointer to set for
/// the given thread.
///
/// \returns This function returns the previously set thread
/// specific data pointer or zero if none was set.
std::size_t set_thread_data(thread_id_type id,
std::size_t data, error_code& ec = throws);
#endif
/// Get percent maintenance time in main thread-manager loop.
boost::int64_t avg_idle_rate(bool reset);
boost::int64_t avg_idle_rate(std::size_t num_thread, bool reset);
protected:
// this is the thread function executing the work items in the queue
void tfunc(std::size_t num_thread, topology const& topology_);
void tfunc_impl(std::size_t num_thread);
public:
/// this notifies the thread manager that there is some more work
/// available
void do_some_work(std::size_t num_thread = std::size_t(-1))
{
scheduler_.do_some_work(num_thread);
}
/// API functions forwarding to notification policy
void report_error(std::size_t num_thread, boost::exception_ptr const& e)
{
notifier_.on_error(num_thread, e);
scheduler_.on_error(num_thread, e);
}
boost::int64_t get_executed_threads(std::size_t num = std::size_t(-1),
bool reset = false);
protected:
///
template <typename C>
void start_periodic_maintenance(boost::mpl::true_);
template <typename C>
void start_periodic_maintenance(boost::mpl::false_) {}
template <typename C>
void periodic_maintenance_handler(boost::mpl::true_);
template <typename C>
void periodic_maintenance_handler(boost::mpl::false_) {}
public:
/// The function register_counter_types() is called during startup to
/// allow the registration of all performance counter types for this
/// thread-manager instance.
void register_counter_types();
/// Returns of the number of the processing units the given thread
/// is allowed to run on
std::size_t get_pu_num(std::size_t num_thread) const
{
return scheduler_.get_pu_num(num_thread);
}
/// Return the mask for processing units the given thread is allowed
/// to run on.
mask_cref_type get_pu_mask(topology const& topology, std::size_t num_thread) const
{
return scheduler_.get_pu_mask(topology, num_thread);
}
// Returns the mask identifying all processing units used by this
// thread manager.
mask_cref_type get_used_processing_units() const
{
return used_processing_units_;
}
// Return the executor associated with th egiven thread
executor get_executor(thread_id_type id, error_code& ec) const;
private:
// counter creator functions
naming::gid_type queue_length_counter_creator(
performance_counters::counter_info const& info, error_code& ec);
naming::gid_type thread_counts_counter_creator(
performance_counters::counter_info const& info, error_code& ec);
naming::gid_type idle_rate_counter_creator(
performance_counters::counter_info const& info, error_code& ec);
#if HPX_THREAD_MAINTAIN_QUEUE_WAITTIME
naming::gid_type thread_wait_time_counter_creator(
performance_counters::counter_info const& info, error_code& ec);
naming::gid_type task_wait_time_counter_creator(
performance_counters::counter_info const& info, error_code& ec);
#endif
private:
/// this thread manager has exactly as much threads as requested
mutable mutex_type mtx_; ///< mutex protecting the members
boost::barrier* startup_; ///< startup synchronization
boost::ptr_vector<boost::thread> threads_;
// count number of executed HPX-threads (invocations)
std::vector<boost::int64_t> executed_threads_;
boost::atomic<long> thread_count_;
boost::atomic<hpx::state> state_; ///< thread manager state
util::io_service_pool& timer_pool_; ///< used for timed set_state
util::block_profiler<register_thread_tag> thread_logger_;
util::block_profiler<register_work_tag> work_logger_;
util::block_profiler<set_state_tag> set_state_logger_;
scheduling_policy_type& scheduler_;
notification_policy_type& notifier_;
// tfunc_impl timers
std::vector<boost::uint64_t> exec_times, tfunc_times;
// Stores the mask identifying all processing units used by this
// thread manager.
threads::mask_type used_processing_units_;
};
}}
#include <hpx/config/warnings_suffix.hpp>
#endif
| 48.318919 | 95 | 0.594175 | andreasbuhr |
73fac5c56124e8d75dc9e1a5febabce4a7852710 | 334 | cpp | C++ | region/region.cpp | lhb8125/unstructured_frame | 3f28879cd7eb69e5fd9d5e812b6b36b6186125fe | [
"Apache-2.0"
] | null | null | null | region/region.cpp | lhb8125/unstructured_frame | 3f28879cd7eb69e5fd9d5e812b6b36b6186125fe | [
"Apache-2.0"
] | null | null | null | region/region.cpp | lhb8125/unstructured_frame | 3f28879cd7eb69e5fd9d5e812b6b36b6186125fe | [
"Apache-2.0"
] | null | null | null | /**
* @file:
* @author: Liu Hongbin
* @brief:
* @date: 2019-10-14 09:17:17
* @last Modified by: lenovo
* @last Modified time: 2019-10-14 09:18:49
*/
// #include "mesh.hpp"
// class Region
// {
// private:
// Mesh mesh;
// public:
// Region();
// ~Region();
// Mesh& getMesh(){return this->mesh;};
// }; | 16.7 | 43 | 0.526946 | lhb8125 |
73fcf2f85d42915ba9de15163c6b23342d346fad | 4,576 | hxx | C++ | include/graphics/nxglyphs.hxx | normanr/incubator-nuttx-apps | b5128c401f5c65f44298f46c3887d6bb57bfb90b | [
"Apache-2.0"
] | 132 | 2019-12-17T23:45:42.000Z | 2022-03-30T11:58:30.000Z | include/graphics/nxglyphs.hxx | normanr/incubator-nuttx-apps | b5128c401f5c65f44298f46c3887d6bb57bfb90b | [
"Apache-2.0"
] | 443 | 2020-01-01T03:06:24.000Z | 2022-03-31T08:57:35.000Z | include/graphics/nxglyphs.hxx | normanr/incubator-nuttx-apps | b5128c401f5c65f44298f46c3887d6bb57bfb90b | [
"Apache-2.0"
] | 232 | 2019-12-21T10:18:12.000Z | 2022-03-30T07:42:13.000Z | /****************************************************************************
* apps/include/graphics/nxwidgets/nxglyphs.hxx
*
* 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 __APPS_INCLUDE_GRAPHICS_NXGLYPHS_HXX
#define __APPS_INCLUDE_GRAPHICS_NXGLYPHS_HXX
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <stdint.h>
#include <stdbool.h>
#include <nuttx/nx/nxglib.h>
#include "graphics/nxwidgets/nxconfig.hxx"
/****************************************************************************
* Pre-Processor Definitions
****************************************************************************/
/* Default background color */
#ifndef CONFIG_NXGLYPHS_BACKGROUNDCOLOR
# define CONFIG_NXGLYPHS_BACKGROUNDCOLOR MKRGB(148,189,215)
#endif
/****************************************************************************
* Bitmap Glyph References
****************************************************************************/
#if defined(__cplusplus)
namespace NXWidgets
{
struct SBitmap;
// Bitmaps used by NxWidgets
// Global RLE Paletted Bitmaps
extern const struct SRlePaletteBitmap g_nuttxBitmap160x160;
extern const struct SRlePaletteBitmap g_nuttxBitmap320x320;
// Global Simple Bitmaps
extern const struct SBitmap g_screenDepthUp;
extern const struct SBitmap g_screenDepthDown;
extern const struct SBitmap g_windowClose;
extern const struct SBitmap g_windowDepthUp;
extern const struct SBitmap g_windowDepthDown;
extern const struct SBitmap g_radioButtonOn;
extern const struct SBitmap g_radioButtonOff;
extern const struct SBitmap g_radioButtonMu;
extern const struct SBitmap g_checkBoxOff;
extern const struct SBitmap g_checkBoxOn;
extern const struct SBitmap g_checkBoxMu;
extern const struct SBitmap g_screenFlipUp;
extern const struct SBitmap g_screenFlipDown;
extern const struct SBitmap g_arrowUp;
extern const struct SBitmap g_arrowDown;
extern const struct SBitmap g_arrowLeft;
extern const struct SBitmap g_arrowRight;
extern const struct SBitmap g_cycle;
extern const struct SBitmap g_backspace;
extern const struct SBitmap g_return;
extern const struct SBitmap g_shift;
extern const struct SBitmap g_capslock;
extern const struct SBitmap g_control;
// Bitmaps used by NxWM, Twm4Nx, and SLcd
// Global RLE Paletted Bitmaps
extern const struct SRlePaletteBitmap g_calculatorBitmap;
extern const struct SRlePaletteBitmap g_calibrationBitmap;
extern const struct SRlePaletteBitmap g_cmdBitmap;
extern const struct SRlePaletteBitmap g_menuBitmap;
extern const struct SRlePaletteBitmap g_menu2Bitmap;
extern const struct SRlePaletteBitmap g_resizeBitmap;
extern const struct SRlePaletteBitmap g_resize2Bitmap;
extern const struct SRlePaletteBitmap g_nxiconBitmap;
extern const struct SRlePaletteBitmap g_lcdClockBitmap;
// Used by NxWM media player
extern const struct SRlePaletteBitmap g_mediaplayerBitmap;
extern const struct SRlePaletteBitmap g_mplayerFwdBitmap;
extern const struct SRlePaletteBitmap g_mplayerPlayBitmap;
extern const struct SRlePaletteBitmap g_mplayerPauseBitmap;
extern const struct SRlePaletteBitmap g_mplayerRewBitmap;
extern const struct SRlePaletteBitmap g_mplayerVolBitmap;
extern const struct SRlePaletteBitmap g_minimizeBitmap;
extern const struct SRlePaletteBitmap g_minimize2Bitmap;
extern const struct SRlePaletteBitmap g_playBitmap;
extern const struct SRlePaletteBitmap g_stopBitmap;
extern const struct SRlePaletteBitmap g_stop2Bitmap;
}
#endif // __cplusplus
#endif // __APPS_INCLUDE_GRAPHICS_NXGLYPHS_HXX
| 38.133333 | 78 | 0.697771 | normanr |
bab69cdfaa6c8515085cc9906a64d42e9ea76d0b | 3,131 | hpp | C++ | or-tools_Ubuntu-18.04-64bit_v7.4.7247/include/coin/CbcPartialNodeInfo.hpp | rajiff/docker-google-or-tools | b7a6c730639c5b47857925de9cf673b456cb4390 | [
"Apache-2.0"
] | 7 | 2020-07-04T01:50:12.000Z | 2021-06-03T21:54:52.000Z | PO_class/assignment_2/or-tools/include/coin/CbcPartialNodeInfo.hpp | ItamarRocha/Operations-Research | 55c4d54959555c3b9d54641e76eb6cfb2c011a2c | [
"MIT"
] | null | null | null | PO_class/assignment_2/or-tools/include/coin/CbcPartialNodeInfo.hpp | ItamarRocha/Operations-Research | 55c4d54959555c3b9d54641e76eb6cfb2c011a2c | [
"MIT"
] | null | null | null | // $Id$
// Copyright (C) 2002, International Business Machines
// Corporation and others. All Rights Reserved.
// This code is licensed under the terms of the Eclipse Public License (EPL).
// Edwin 11/24/09 carved from CbcNode
#ifndef CbcPartialNodeInfo_H
#define CbcPartialNodeInfo_H
#include <string>
#include <vector>
#include "CoinWarmStartBasis.hpp"
#include "CoinSearchTree.hpp"
#include "CbcBranchBase.hpp"
#include "CbcNodeInfo.hpp"
class OsiSolverInterface;
class OsiSolverBranch;
class OsiCuts;
class OsiRowCut;
class OsiRowCutDebugger;
class CoinWarmStartBasis;
class CbcCountRowCut;
class CbcModel;
class CbcNode;
class CbcSubProblem;
class CbcGeneralBranchingObject;
/** \brief Holds information for recreating a subproblem by incremental change
from the parent.
A CbcPartialNodeInfo object contains changes to the bounds and basis, and
additional cuts, required to recreate a subproblem by modifying and
augmenting the parent subproblem.
*/
class CbcPartialNodeInfo : public CbcNodeInfo {
public:
/** \brief Modify model according to information at node
The routine modifies the model according to bound and basis change
information at node and adds any cuts to the addCuts array.
*/
virtual void applyToModel(CbcModel *model, CoinWarmStartBasis *&basis,
CbcCountRowCut **addCuts,
int ¤tNumberCuts) const;
/// Just apply bounds to one variable - force means overwrite by lower,upper (1=>infeasible)
virtual int applyBounds(int iColumn, double &lower, double &upper, int force);
/** Builds up row basis backwards (until original model).
Returns NULL or previous one to apply .
Depends on Free being 0 and impossible for cuts
*/
virtual CbcNodeInfo *buildRowBasis(CoinWarmStartBasis &basis) const;
// Default Constructor
CbcPartialNodeInfo();
// Constructor from current state
CbcPartialNodeInfo(CbcNodeInfo *parent, CbcNode *owner,
int numberChangedBounds, const int *variables,
const double *boundChanges,
const CoinWarmStartDiff *basisDiff);
// Copy constructor
CbcPartialNodeInfo(const CbcPartialNodeInfo &);
// Destructor
~CbcPartialNodeInfo();
/// Clone
virtual CbcNodeInfo *clone() const;
/// Basis diff information
inline const CoinWarmStartDiff *basisDiff() const
{
return basisDiff_;
}
/// Which variable (top bit if upper bound changing)
inline const int *variables() const
{
return variables_;
}
// New bound
inline const double *newBounds() const
{
return newBounds_;
}
/// Number of bound changes
inline int numberChangedBounds() const
{
return numberChangedBounds_;
}
protected:
/* Data values */
/// Basis diff information
CoinWarmStartDiff *basisDiff_;
/// Which variable (top bit if upper bound changing)
int *variables_;
// New bound
double *newBounds_;
/// Number of bound changes
int numberChangedBounds_;
private:
/// Illegal Assignment operator
CbcPartialNodeInfo &operator=(const CbcPartialNodeInfo &rhs);
};
#endif //CbcPartialNodeInfo_H
/* vi: softtabstop=2 shiftwidth=2 expandtab tabstop=2
*/
| 26.760684 | 94 | 0.743213 | rajiff |
babbdc2315384ab392cf45f677c3cb02996c91c1 | 1,747 | cpp | C++ | 8. Backtracking/SubsetSUM.cpp | Vipulhere/DAA_CodingNinjas | 526ff9e5fa87cbc24666c1fb39d4861306d51ab6 | [
"MIT"
] | 2 | 2022-02-06T16:48:37.000Z | 2022-02-17T12:20:09.000Z | 8. Backtracking/SubsetSUM.cpp | Vipulhere/DAA_CodingNinjas | 526ff9e5fa87cbc24666c1fb39d4861306d51ab6 | [
"MIT"
] | null | null | null | 8. Backtracking/SubsetSUM.cpp | Vipulhere/DAA_CodingNinjas | 526ff9e5fa87cbc24666c1fb39d4861306d51ab6 | [
"MIT"
] | null | null | null | // #include <bits/stdc++.h>
// using namespace std;
// int subsetSum(int a[], int n, int sum)
// {
// // Initializing the matrix
// int tab[n + 1][sum + 1];
// // Initializing the first value of matrix
// tab[0][0] = 1;
// for (int i = 1; i <= sum; i++)
// tab[0][i] = 0;
// for (int i = 1; i <= n; i++)
// tab[i][0] = 1;
// for (int i = 1; i <= n; i++)
// {
// for (int j = 1; j <= sum; j++)
// {
// // if the value is greater than the sum
// if (a[i - 1] > j)
// tab[i][j] = tab[i - 1][j];
// else
// {
// tab[i][j] = tab[i - 1][j] + tab[i - 1][j - a[i - 1]];
// }
// }
// }
// return tab[n][sum];
// }
// int main(){
// int t; cin >> t;
// while(t--){
// int n,sum; cin >> n >> sum;
// int a[n];
// for(int i=0;i<n;i++){
// cin >> a[i];
// }
// cout << (subsetSum(a, n, sum)) << endl;
// }
// }
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define double long double
int countWays(const vector<int>& a, int k, int index) {
if(index == a.size()) {
return k == 0;
}
int count = 0;
if(k - a[index] >= 0) {
count += countWays(a, k - a[index], index+1);
}
count += countWays(a, k, index+1);
return count;
}
int32_t main()
{
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
string s = "abs";
int t; cin >> t;
while(t--)
{
int n, k;
cin >> n >> k;
vector<int> a(n);
for(int i = 0 ; i < n ; ++i) {
cin >> a[i];
}
cout << countWays(a, k, 0) << '\n';
}
return 0;
}
| 20.797619 | 73 | 0.39668 | Vipulhere |
bac2b0e7804bb879c61a4aac7ced3a9f390c5c29 | 1,793 | cpp | C++ | lib/chainInsert.cpp | deltaclock/Trip_chooser | d663cfaf04fc126e6b24c2fa9cbf9cfed4d2c19a | [
"MIT"
] | null | null | null | lib/chainInsert.cpp | deltaclock/Trip_chooser | d663cfaf04fc126e6b24c2fa9cbf9cfed4d2c19a | [
"MIT"
] | null | null | null | lib/chainInsert.cpp | deltaclock/Trip_chooser | d663cfaf04fc126e6b24c2fa9cbf9cfed4d2c19a | [
"MIT"
] | null | null | null | #include "chain.hpp"
template <class T> Chain<T> &Chain<T>::Insert(int k, const T &x) {
// Insert x after the k'th element.
// Throw OutOfBounds exception if no k'th element.
// Pass NoMem exception if inadequate space.
if (k < 0)
throw std::out_of_range("Negative value..!!");
// p will eventually point to k'th node
ChainNode<T> *p = first;
for (int index = 1; index < k && p; index++)
p = p->link; // move p to k'th
if (k > 0 && !p)
throw std::out_of_range("No " + std::to_string(k) +
"th element"); // no k'th
// insert
ChainNode<T> *y = new ChainNode<T>;
y->data = x;
if (k) { // insert after p
y->link = p->link;
p->link = y;
} else { // insert as first element
y->link = first;
first = y;
}
if (!y->link)
last = y;
return *this;
}
template <class T> Chain<T> &Chain<T>::Delete(int k, T &x) {
// Set x to the k'th element and delete it.
// Throw OutOfBounds exception if no k'th element.
if (k < 1 || !first)
throw std::out_of_range("No " + std::to_string(k) +
"th element"); // no k'th
// p will eventually point to k'th node
ChainNode<T> *p = first;
// move p to k'th & remove from chain
if (k == 1) // p already at k'th
first = first->link; // remove
else { // use q to get to k-1'st
ChainNode<T> *q = first;
for (int index = 1; index < k - 1 && q; index++)
q = q->link;
if (!q || !q->link)
throw std::out_of_range("No " + std::to_string(k) +
"th element"); // no k'th
p = q->link;
if (p == last)
last = q;
q->link = p->link;
}
// remove k'th
// save k'th element and free node p
x = p->data;
delete p;
return *this;
}
| 26.367647 | 66 | 0.525934 | deltaclock |
bac5b7ab0c99d8806c7684fbe8b7b930fa3904eb | 13,580 | cpp | C++ | src/cpp/rtps/builtin/discovery/endpoint/EDPStatic.cpp | Jerry-2005/Fast-DDS | 60aa927778fc028c60970a08309dc3510455a166 | [
"Apache-2.0"
] | null | null | null | src/cpp/rtps/builtin/discovery/endpoint/EDPStatic.cpp | Jerry-2005/Fast-DDS | 60aa927778fc028c60970a08309dc3510455a166 | [
"Apache-2.0"
] | null | null | null | src/cpp/rtps/builtin/discovery/endpoint/EDPStatic.cpp | Jerry-2005/Fast-DDS | 60aa927778fc028c60970a08309dc3510455a166 | [
"Apache-2.0"
] | 1 | 2021-06-02T11:16:56.000Z | 2021-06-02T11:16:56.000Z | // Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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.
/**
* @file EDPStatic.cpp
*
*/
#include <fastdds/rtps/builtin/discovery/endpoint/EDPStatic.h>
#include <fastdds/rtps/builtin/discovery/participant/PDPSimple.h>
#include <fastrtps/xmlparser/XMLEndpointParser.h>
#include <fastdds/rtps/builtin/data/WriterProxyData.h>
#include <fastdds/rtps/builtin/data/ReaderProxyData.h>
#include <fastdds/rtps/builtin/data/ParticipantProxyData.h>
#include <fastdds/rtps/reader/RTPSReader.h>
#include <fastdds/rtps/writer/RTPSWriter.h>
#include <fastdds/dds/log/Log.hpp>
#include <rtps/participant/RTPSParticipantImpl.h>
#include <mutex>
#include <sstream>
namespace eprosima {
namespace fastrtps {
namespace rtps {
EDPStatic::EDPStatic(
PDP* p,
RTPSParticipantImpl* part)
: EDP(p, part)
, mp_edpXML(nullptr)
{
}
EDPStatic::~EDPStatic()
{
if (mp_edpXML != nullptr)
{
delete(mp_edpXML);
}
}
bool EDPStatic::initEDP(
BuiltinAttributes& attributes)
{
logInfo(RTPS_EDP, "Beginning STATIC EndpointDiscoveryProtocol");
m_attributes = attributes;
mp_edpXML = new xmlparser::XMLEndpointParser();
std::string filename(m_attributes.discovery_config.getStaticEndpointXMLFilename());
return (this->mp_edpXML->loadXMLFile(filename) == xmlparser::XMLP_ret::XML_OK);
}
std::pair<std::string, std::string> EDPStaticProperty::toProperty(
std::string type,
std::string status,
uint16_t id,
const EntityId_t& ent)
{
std::pair<std::string, std::string> prop;
std::stringstream ss;
ss << "eProsimaEDPStatic_" << type << "_" << status << "_ID_" << id;
prop.first = ss.str();
ss.clear();
ss.str(std::string());
ss << (int)ent.value[0] << ".";
ss << (int)ent.value[1] << ".";
ss << (int)ent.value[2] << ".";
ss << (int)ent.value[3];
prop.second = ss.str();
return prop;
}
bool EDPStaticProperty::fromProperty(
std::pair<std::string, std::string> prop)
{
if (prop.first.substr(0, 17) == "eProsimaEDPStatic" && prop.first.substr(31, 2) == "ID")
{
this->m_endpointType = prop.first.substr(18, 6);
this->m_status = prop.first.substr(25, 5);
this->m_userIdStr = prop.first.substr(34, 100);
std::stringstream ss;
ss << m_userIdStr;
ss >> m_userId;
ss.clear();
ss.str(std::string());
ss << prop.second;
int a, b, c, d;
char ch;
ss >> a >> ch >> b >> ch >> c >> ch >> d;
m_entityId.value[0] = (octet)a; m_entityId.value[1] = (octet)b;
m_entityId.value[2] = (octet)c; m_entityId.value[3] = (octet)d;
return true;
}
return false;
}
bool EDPStatic::processLocalReaderProxyData(
RTPSReader*,
ReaderProxyData* rdata)
{
logInfo(RTPS_EDP, rdata->guid().entityId << " in topic: " << rdata->topicName());
mp_PDP->getMutex()->lock();
//Add the property list entry to our local pdp
ParticipantProxyData* localpdata = this->mp_PDP->getLocalParticipantProxyData();
localpdata->m_properties.push_back(EDPStaticProperty::toProperty("Reader", "ALIVE", rdata->userDefinedId(),
rdata->guid().entityId));
mp_PDP->getMutex()->unlock();
this->mp_PDP->announceParticipantState(true);
return true;
}
bool EDPStatic::processLocalWriterProxyData(
RTPSWriter*,
WriterProxyData* wdata)
{
logInfo(RTPS_EDP, wdata->guid().entityId << " in topic: " << wdata->topicName());
mp_PDP->getMutex()->lock();
//Add the property list entry to our local pdp
ParticipantProxyData* localpdata = this->mp_PDP->getLocalParticipantProxyData();
localpdata->m_properties.push_back(EDPStaticProperty::toProperty("Writer", "ALIVE",
wdata->userDefinedId(), wdata->guid().entityId));
mp_PDP->getMutex()->unlock();
this->mp_PDP->announceParticipantState(true);
return true;
}
bool EDPStatic::removeLocalReader(
RTPSReader* R)
{
std::lock_guard<std::recursive_mutex> guard(*mp_PDP->getMutex());
ParticipantProxyData* localpdata = this->mp_PDP->getLocalParticipantProxyData();
for (ParameterPropertyList_t::iterator pit = localpdata->m_properties.begin();
pit != localpdata->m_properties.end(); ++pit)
{
EDPStaticProperty staticproperty;
if (staticproperty.fromProperty((*pit).pair()))
{
if (staticproperty.m_entityId == R->getGuid().entityId)
{
auto new_property = EDPStaticProperty::toProperty("Reader", "ENDED",
R->getAttributes().getUserDefinedID(), R->getGuid().entityId);
if (!pit->modify(new_property))
{
logError(RTPS_EDP, "Failed to change property <"
<< pit->first() << " | " << pit->second() << "> to <"
<< new_property.first << " | " << new_property.second << ">");
}
}
}
}
return false;
}
bool EDPStatic::removeLocalWriter(
RTPSWriter* W)
{
std::lock_guard<std::recursive_mutex> guard(*mp_PDP->getMutex());
ParticipantProxyData* localpdata = this->mp_PDP->getLocalParticipantProxyData();
for (ParameterPropertyList_t::iterator pit = localpdata->m_properties.begin();
pit != localpdata->m_properties.end(); ++pit)
{
EDPStaticProperty staticproperty;
if (staticproperty.fromProperty((*pit).pair()))
{
if (staticproperty.m_entityId == W->getGuid().entityId)
{
auto new_property = EDPStaticProperty::toProperty("Writer", "ENDED",
W->getAttributes().getUserDefinedID(), W->getGuid().entityId);
if (!pit->modify(new_property))
{
logError(RTPS_EDP, "Failed to change property <"
<< pit->first() << " | " << pit->second() << "> to <"
<< new_property.first << " | " << new_property.second << ">");
}
}
}
}
return false;
}
void EDPStatic::assignRemoteEndpoints(
const ParticipantProxyData& pdata)
{
for (ParameterPropertyList_t::const_iterator pit = pdata.m_properties.begin();
pit != pdata.m_properties.end(); ++pit)
{
//cout << "STATIC EDP READING PROPERTY " << pit->first << "// " << pit->second << endl;
EDPStaticProperty staticproperty;
if (staticproperty.fromProperty((*pit).pair()))
{
if (staticproperty.m_endpointType == "Reader" && staticproperty.m_status == "ALIVE")
{
GUID_t guid(pdata.m_guid.guidPrefix, staticproperty.m_entityId);
if (!this->mp_PDP->has_reader_proxy_data(guid))//IF NOT FOUND, we CREATE AND PAIR IT
{
newRemoteReader(pdata.m_guid, pdata.m_participantName,
staticproperty.m_userId, staticproperty.m_entityId);
}
}
else if (staticproperty.m_endpointType == "Writer" && staticproperty.m_status == "ALIVE")
{
GUID_t guid(pdata.m_guid.guidPrefix, staticproperty.m_entityId);
if (!this->mp_PDP->has_writer_proxy_data(guid))//IF NOT FOUND, we CREATE AND PAIR IT
{
newRemoteWriter(pdata.m_guid, pdata.m_participantName,
staticproperty.m_userId, staticproperty.m_entityId);
}
}
else if (staticproperty.m_endpointType == "Reader" && staticproperty.m_status == "ENDED")
{
GUID_t guid(pdata.m_guid.guidPrefix, staticproperty.m_entityId);
this->mp_PDP->removeReaderProxyData(guid);
}
else if (staticproperty.m_endpointType == "Writer" && staticproperty.m_status == "ENDED")
{
GUID_t guid(pdata.m_guid.guidPrefix, staticproperty.m_entityId);
this->mp_PDP->removeWriterProxyData(guid);
}
else
{
logWarning(RTPS_EDP, "Property with type: " << staticproperty.m_endpointType
<< " and status " << staticproperty.m_status <<
" not recognized");
}
}
else
{
}
}
}
bool EDPStatic::newRemoteReader(
const GUID_t& participant_guid,
const string_255& participant_name,
uint16_t user_id,
EntityId_t ent_id)
{
ReaderProxyData* rpd = NULL;
if (mp_edpXML->lookforReader(participant_name, user_id, &rpd) == xmlparser::XMLP_ret::XML_OK)
{
logInfo(RTPS_EDP, "Activating: " << rpd->guid().entityId << " in topic " << rpd->topicName());
GUID_t reader_guid(participant_guid.guidPrefix, ent_id != c_EntityId_Unknown ? ent_id : rpd->guid().entityId);
auto init_fun = [this, participant_guid, reader_guid, rpd](
ReaderProxyData* newRPD,
bool updating,
const ParticipantProxyData& participant_data)
{
// Should be a new reader
(void)updating;
assert(!updating);
*newRPD = *rpd;
newRPD->guid(reader_guid);
if (!checkEntityId(newRPD))
{
logError(RTPS_EDP, "The provided entityId for Reader with ID: "
<< newRPD->userDefinedId() << " does not match the topic Kind");
return false;
}
newRPD->key() = newRPD->guid();
newRPD->RTPSParticipantKey() = participant_guid;
if (!newRPD->has_locators())
{
const NetworkFactory& network = mp_RTPSParticipant->network_factory();
newRPD->set_remote_locators(participant_data.default_locators, network, true);
}
return true;
};
GUID_t temp_participant_guid;
ReaderProxyData* reader_data = this->mp_PDP->addReaderProxyData(reader_guid, temp_participant_guid, init_fun);
if (reader_data != nullptr)
{
this->pairing_reader_proxy_with_any_local_writer(participant_guid, reader_data);
return true;
}
}
return false;
}
bool EDPStatic::newRemoteWriter(
const GUID_t& participant_guid,
const string_255& participant_name,
uint16_t user_id,
EntityId_t ent_id)
{
WriterProxyData* wpd = NULL;
if (mp_edpXML->lookforWriter(participant_name, user_id, &wpd) == xmlparser::XMLP_ret::XML_OK)
{
logInfo(RTPS_EDP, "Activating: " << wpd->guid().entityId << " in topic " << wpd->topicName());
GUID_t writer_guid(participant_guid.guidPrefix, ent_id != c_EntityId_Unknown ? ent_id : wpd->guid().entityId);
auto init_fun = [this, participant_guid, writer_guid, wpd](
WriterProxyData* newWPD,
bool updating,
const ParticipantProxyData& participant_data)
{
// Should be a new reader
(void)updating;
assert(!updating);
*newWPD = *wpd;
newWPD->guid(writer_guid);
if (!checkEntityId(newWPD))
{
logError(RTPS_EDP, "The provided entityId for Writer with User ID: "
<< newWPD->userDefinedId() << " does not match the topic Kind");
return false;
}
newWPD->key() = newWPD->guid();
newWPD->RTPSParticipantKey() = participant_guid;
if (!newWPD->has_locators())
{
const NetworkFactory& network = mp_RTPSParticipant->network_factory();
newWPD->set_remote_locators(participant_data.default_locators, network, true);
}
return true;
};
GUID_t temp_participant_guid;
WriterProxyData* writer_data = this->mp_PDP->addWriterProxyData(writer_guid, temp_participant_guid, init_fun);
if (writer_data != nullptr)
{
this->pairing_writer_proxy_with_any_local_reader(participant_guid, writer_data);
return true;
}
}
return false;
}
bool EDPStatic::checkEntityId(
ReaderProxyData* rdata)
{
if (rdata->topicKind() == WITH_KEY && rdata->guid().entityId.value[3] == 0x07)
{
return true;
}
if (rdata->topicKind() == NO_KEY && rdata->guid().entityId.value[3] == 0x04)
{
return true;
}
return false;
}
bool EDPStatic::checkEntityId(
WriterProxyData* wdata)
{
if (wdata->topicKind() == WITH_KEY && wdata->guid().entityId.value[3] == 0x02)
{
return true;
}
if (wdata->topicKind() == NO_KEY && wdata->guid().entityId.value[3] == 0x03)
{
return true;
}
return false;
}
} /* namespace rtps */
} /* namespace fastrtps */
} /* namespace eprosima */
| 35.549738 | 118 | 0.593888 | Jerry-2005 |
bac68912a6bea7516b356b3c7833ca646a3046a1 | 2,605 | cpp | C++ | src/Applications/Application_Enable_Light_Mode/Application_Enable_Light_Mode.cpp | gammasoft71/Examples_FLTK | 7d8f11d5da25f7279834d3730732d07e91591f7c | [
"MIT"
] | 21 | 2020-03-04T17:38:14.000Z | 2022-03-07T02:46:39.000Z | src/Applications/Application_Enable_Light_Mode/Application_Enable_Light_Mode.cpp | gammasoft71/Examples_FLTK | 7d8f11d5da25f7279834d3730732d07e91591f7c | [
"MIT"
] | null | null | null | src/Applications/Application_Enable_Light_Mode/Application_Enable_Light_Mode.cpp | gammasoft71/Examples_FLTK | 7d8f11d5da25f7279834d3730732d07e91591f7c | [
"MIT"
] | 6 | 2021-03-12T20:57:00.000Z | 2022-03-31T23:19:03.000Z | #include <initializer_list>
#include <map>
#include <string>
#include <FL/Fl.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Browser.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Choice.H>
#include <FL/Fl_Check_Button.H>
#include <FL/fl_draw.H>
#include <FL/fl_message.H>
#include <FL/Fl_Radio_Round_Button.H>
#include <FL/Fl_Window.H>
using namespace std;
namespace Examples {
class Main_Window : public Fl_Window {
public:
Main_Window() : Fl_Window(200, 100, 330, 300, "") {
box1.align(FL_ALIGN_LEFT | FL_ALIGN_TOP | FL_ALIGN_CLIP | FL_ALIGN_INSIDE);
button1.callback([](Fl_Widget* sender, void* window) {
fl_message_icon()->box(FL_ROUND_UP_BOX);
fl_message_icon()->color(fl_rgb_color(0, 0, 255));
fl_message_icon()->label("i");
fl_message_icon()->labelcolor(fl_rgb_color(255, 255, 255));
fl_message_title("Message");
fl_choice("This is an example of message...", nullptr, fl_ok, nullptr);
}, this);
browser1.type(FL_HOLD_BROWSER);
for (auto item : {"item 1", "item 2", "item 3", "item 4", "item 5", "item 6", "item 7", "item 8", "item 9", "item 10"})
browser1.add(item);
browser1.select(1);
radio1.value(true);
check_button1.value(true);
}
private:
Fl_Box box1 {10, 10, 90, 25, "Dark mode"};
Fl_Button button1 {110, 10, 75, 25, "Click me"};
Fl_Browser browser1 {10, 50, 120, 100};
Fl_Radio_Round_Button radio1 {10, 170, 90, 25, "Raddio 1"};
Fl_Radio_Round_Button radio2 {110, 170, 90, 25, "Raddio 2"};
Fl_Check_Button check_button1 {10, 200, 90, 25, "Check 1"};
Fl_Check_Button check_button2 {110, 200, 90, 25, "Check 2"};
};
}
int main(int argc, char *argv[]) {
fl_message_hotspot(false);
fl_message_icon()->labelfont(FL_HELVETICA_BOLD);
Examples::Main_Window window;
window.show(argc, argv);
struct Fl_Enable_Light_Mode {
Fl_Enable_Light_Mode() {
#if _WIN32
Fl::background(240, 240, 240);
Fl::background2(255, 255, 255);
Fl::foreground(0, 0, 0);
Fl::set_color(FL_SELECTION_COLOR, 0, 120, 215);
#elif __APPLE__
Fl::background(236, 236, 236);
Fl::background2(255, 255, 255);
Fl::foreground(0 ,0, 0);
Fl::set_color(FL_SELECTION_COLOR, 0, 98, 225);
#else
Fl::background(241, 240, 238);
Fl::background2(255, 255, 255);
Fl::foreground(0, 0, 0);
Fl::set_color(FL_SELECTION_COLOR, 53, 100, 228);
#endif
}
} enable_light_mode; // Must be call after window.show, because show(...) method init system colors and reset selection color to 0xf.
return Fl::run();
}
| 32.5625 | 135 | 0.647985 | gammasoft71 |
bac6fdf60707dbf2946f98bf073414e3912b685a | 8,709 | cc | C++ | tonic-suite/asr/src/gmmbin/gmm-latgen-map.cc | csb1024/djinn_csb | de50d6b6bc9c137e9f4b881de9048eba9e83142d | [
"BSD-3-Clause"
] | 59 | 2015-07-01T21:41:47.000Z | 2021-07-28T07:07:42.000Z | tonic-suite/asr/src/gmmbin/gmm-latgen-map.cc | csb1024/djinn_csb | de50d6b6bc9c137e9f4b881de9048eba9e83142d | [
"BSD-3-Clause"
] | 4 | 2016-01-24T13:25:03.000Z | 2021-07-06T09:10:23.000Z | tonic-suite/asr/src/gmmbin/gmm-latgen-map.cc | csb1024/djinn_csb | de50d6b6bc9c137e9f4b881de9048eba9e83142d | [
"BSD-3-Clause"
] | 54 | 2015-06-13T15:31:20.000Z | 2021-07-28T07:07:43.000Z | // gmmbin/gmm-latgen-map.cc
// Copyright 2012 Neha Agrawal, Cisco Systems;
// Johns Hopkins University (author: Daniel Povey)
// 2014 Guoguo Chen
// See ../../COPYING for clarification regarding multiple authors
//
// 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
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#include <string>
#include <vector>
#include "base/kaldi-common.h"
#include "util/common-utils.h"
#include "gmm/am-diag-gmm.h"
#include "gmm/mle-am-diag-gmm.h"
#include "hmm/transition-model.h"
#include "transform/fmllr-diag-gmm.h"
#include "fstext/fstext-lib.h"
#include "decoder/lattice-faster-decoder.h"
#include "gmm/decodable-am-diag-gmm.h"
#include "base/timer.h"
#include "lat/kaldi-lattice.h" // for {Compact}LatticeArc
int main(int argc, char *argv[]) {
try {
using namespace kaldi;
typedef kaldi::int32 int32;
using fst::SymbolTable;
using fst::VectorFst;
using fst::StdArc;
const char *usage =
"Decode features using GMM-based model. Note: the input\n"
"<gmms-rspecifier> will typically be piped in from gmm-est-map.\n"
"Note: <model-in> is only needed for the transition-model, which "
"isn't\n"
"included in <gmms-rspecifier>.\n"
"\n"
"Usage: gmm-latgen-map [options] <model-in> "
"<gmms-rspecifier> <fsts-rxfilename|fsts-rspecifier> "
"<features-rspecifier> "
"<lattice-wspecifier> [ <words-wspecifier> [ <alignments-wspecifier> ] "
"]\n";
ParseOptions po(usage);
bool binary = true;
bool allow_partial = true;
BaseFloat acoustic_scale = 0.1;
std::string word_syms_filename, utt2spk_rspecifier;
LatticeFasterDecoderConfig decoder_opts;
decoder_opts.Register(&po);
po.Register("utt2spk", &utt2spk_rspecifier,
"rspecifier for utterance to "
"speaker map");
po.Register("binary", &binary, "Write output in binary mode");
po.Register("acoustic-scale", &acoustic_scale,
"Scaling factor for acoustic likelihoods");
po.Register("word-symbol-table", &word_syms_filename,
"Symbol table for words [for debug output]");
po.Register("allow-partial", &allow_partial,
"Produce output even when final state was not reached");
po.Read(argc, argv);
if (po.NumArgs() < 5 || po.NumArgs() > 7) {
po.PrintUsage();
exit(1);
}
std::string model_in_filename = po.GetArg(1),
gmms_rspecifier = po.GetArg(2), fst_in_filename = po.GetArg(3),
feature_rspecifier = po.GetArg(4),
lattice_wspecifier = po.GetArg(5),
words_wspecifier = po.GetOptArg(6),
alignment_wspecifier = po.GetOptArg(7);
TransitionModel trans_model;
{
bool binary_read;
Input is(model_in_filename, &binary_read);
trans_model.Read(is.Stream(), binary_read);
}
RandomAccessMapAmDiagGmmReaderMapped gmms_reader(gmms_rspecifier,
utt2spk_rspecifier);
Int32VectorWriter words_writer(words_wspecifier);
Int32VectorWriter alignment_writer(alignment_wspecifier);
bool determinize = decoder_opts.determinize_lattice;
if (!determinize) KALDI_WARN << "determinize is set to FASLE ...";
CompactLatticeWriter compact_lattice_writer;
LatticeWriter lattice_writer;
if (lattice_wspecifier != "") {
if (!(determinize ? compact_lattice_writer.Open(lattice_wspecifier)
: lattice_writer.Open(lattice_wspecifier)))
KALDI_ERR << "Could not open table for writing lattices: "
<< lattice_wspecifier;
}
fst::SymbolTable *word_syms = NULL;
if (word_syms_filename != "") {
word_syms = fst::SymbolTable::ReadText(word_syms_filename);
if (!word_syms) {
KALDI_ERR << "Could not read symbol table from file "
<< word_syms_filename;
}
}
BaseFloat tot_like = 0.0;
kaldi::int64 frame_count = 0;
int num_success = 0, num_fail = 0;
Timer timer;
if (ClassifyRspecifier(fst_in_filename, NULL, NULL) == kNoRspecifier) {
// Input FST is just one FST, not a table of FSTs.
VectorFst<StdArc> *decode_fst = fst::ReadFstKaldi(fst_in_filename);
SequentialBaseFloatMatrixReader feature_reader(feature_rspecifier);
for (; !feature_reader.Done(); feature_reader.Next()) {
string utt = feature_reader.Key();
if (!gmms_reader.HasKey(utt)) {
KALDI_WARN
<< "Utterance " << utt
<< " has no corresponding MAP model skipping this utterance.";
num_fail++;
continue;
}
AmDiagGmm am_gmm;
am_gmm.CopyFromAmDiagGmm(gmms_reader.Value(utt));
Matrix<BaseFloat> features(feature_reader.Value());
feature_reader.FreeCurrent();
if (features.NumRows() == 0) {
KALDI_WARN << "Zero-length utterance: " << utt;
num_fail++;
continue;
}
LatticeFasterDecoder decoder(*decode_fst, decoder_opts);
kaldi::DecodableAmDiagGmmScaled gmm_decodable(am_gmm, trans_model,
features, acoustic_scale);
double like;
if (DecodeUtteranceLatticeFaster(
decoder, gmm_decodable, trans_model, word_syms, utt,
acoustic_scale, determinize, allow_partial, &alignment_writer,
&words_writer, &compact_lattice_writer, &lattice_writer,
&like)) {
tot_like += like;
frame_count += features.NumRows();
num_success++;
} else
num_fail++;
} // end looping over all utterances
} else {
RandomAccessTableReader<fst::VectorFstHolder> fst_reader(fst_in_filename);
SequentialBaseFloatMatrixReader feature_reader(feature_rspecifier);
for (; !feature_reader.Done(); feature_reader.Next()) {
string utt = feature_reader.Key();
if (!fst_reader.HasKey(utt)) {
KALDI_WARN << "Utterance " << utt << " has no corresponding FST"
<< "skipping this utterance.";
num_fail++;
continue;
}
if (!gmms_reader.HasKey(utt)) {
KALDI_WARN
<< "Utterance " << utt
<< " has no corresponding MAP model skipping this utterance.";
num_fail++;
continue;
}
AmDiagGmm am_gmm;
am_gmm.CopyFromAmDiagGmm(gmms_reader.Value(utt));
Matrix<BaseFloat> features(feature_reader.Value());
feature_reader.FreeCurrent();
if (features.NumRows() == 0) {
KALDI_WARN << "Zero-length utterance: " << utt;
num_fail++;
continue;
}
LatticeFasterDecoder decoder(fst_reader.Value(utt), decoder_opts);
kaldi::DecodableAmDiagGmmScaled gmm_decodable(am_gmm, trans_model,
features, acoustic_scale);
double like;
if (DecodeUtteranceLatticeFaster(
decoder, gmm_decodable, trans_model, word_syms, utt,
acoustic_scale, determinize, allow_partial, &alignment_writer,
&words_writer, &compact_lattice_writer, &lattice_writer,
&like)) {
tot_like += like;
frame_count += features.NumRows();
num_success++;
} else
num_fail++;
} // end looping over all utterances
}
KALDI_LOG << "Average log-likelihood per frame is "
<< (tot_like / frame_count) << " over " << frame_count
<< " frames.";
double elapsed = timer.Elapsed();
KALDI_LOG << "Time taken [excluding initialization] " << elapsed
<< "s: real-time factor assuming 100 frames/sec is "
<< (elapsed * 100.0 / frame_count);
KALDI_LOG << "Done " << num_success << " utterances, failed for "
<< num_fail;
if (word_syms) delete word_syms;
return (num_success != 0 ? 0 : 1);
} catch (const std::exception &e) {
std::cerr << e.what();
return -1;
}
}
| 37.217949 | 80 | 0.616489 | csb1024 |
bac88505a3020f47c8babc96ea0ca71095a3b909 | 3,073 | cc | C++ | src/Dataflow/Network/PortInterface.cc | Haydelj/SCIRun | f7ee04d85349b946224dbff183438663e54b9413 | [
"MIT"
] | 92 | 2015-02-09T22:42:11.000Z | 2022-03-25T09:14:50.000Z | src/Dataflow/Network/PortInterface.cc | Haydelj/SCIRun | f7ee04d85349b946224dbff183438663e54b9413 | [
"MIT"
] | 1,618 | 2015-01-05T19:39:13.000Z | 2022-03-27T20:28:45.000Z | src/Dataflow/Network/PortInterface.cc | Haydelj/SCIRun | f7ee04d85349b946224dbff183438663e54b9413 | [
"MIT"
] | 64 | 2015-02-20T17:51:23.000Z | 2021-11-19T07:08:08.000Z | /*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 Scientific Computing and Imaging Institute,
University of Utah.
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.
*/
/// @todo Documentation Dataflow/Network/PortInterface.cc
#include <Dataflow/Network/PortInterface.h>
#include <Dataflow/Network/ModuleDescription.h>
#include <Dataflow/Network/DataflowInterfaces.h>
#include <Core/Logging/Log.h>
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Logging;
PortDescriptionInterface::~PortDescriptionInterface()
{
}
PortInterface::~PortInterface()
{
}
InputPortInterface::~InputPortInterface()
{
}
OutputPortInterface::~OutputPortInterface()
{
}
namespace
{
bool isFullInputPort(const PortDescriptionInterface& port)
{
return port.isInput() && port.nconnections() == 1;
}
bool sharesParentModule(const PortDescriptionInterface& port1, const PortDescriptionInterface& port2)
{
return port1.getUnderlyingModuleId() == port2.getUnderlyingModuleId();
}
bool isWildPort(const PortDescriptionInterface& port)
{
return port.get_typename() == "Datatype";
}
}
/// @todo: unit test
bool PortConnectionDeterminer::canBeConnected(const PortDescriptionInterface& port1, const PortDescriptionInterface& port2) const
{
if (isFullInputPort(port1) || isFullInputPort(port2))
{
LOG_TRACE("can't connect since input ports can only take one connection");
return false;
}
if (port1.isInput() == port2.isInput())
{
LOG_TRACE("can't connect since input/output not compatible");
return false;
}
if (sharesParentModule(port1, port2))
{
LOG_TRACE("can't connect since it's the same module");
return false;
}
if (isWildPort(port1) || isWildPort(port2))
{
LOG_TRACE("found wild port");
/// @todo: trying out "wildcard" ports
return true;
}
if (port1.get_typename() != port2.get_typename())
{
LOG_TRACE("can't connect since colors don't match");
return false;
}
return true;
}
| 28.990566 | 129 | 0.739017 | Haydelj |
bac98996ba05d5e8c6736ff31706070d537a5b95 | 548 | cc | C++ | ch03/sigmoid/main/main.cc | research-note/deep-learning-from-scratch-using-cpp | 5e11be85fa9c4c7672ce9c3ea2c5ffa8f27defd1 | [
"MIT"
] | 2 | 2021-08-15T12:38:41.000Z | 2021-08-15T12:38:51.000Z | ch03/sigmoid/main/main.cc | research-note/deep-learning-from-scratch-using-modern-cpp | 5e11be85fa9c4c7672ce9c3ea2c5ffa8f27defd1 | [
"MIT"
] | null | null | null | ch03/sigmoid/main/main.cc | research-note/deep-learning-from-scratch-using-modern-cpp | 5e11be85fa9c4c7672ce9c3ea2c5ffa8f27defd1 | [
"MIT"
] | null | null | null | /c *
* Build executable object file liking with cc_library lib file example.
*
* Copyright Bazel organization
*
*/
#include "lib/hello-time.h"
#include "main/sigmoid.hpp"
#include <iostream>
#include <string>
int main(int argc, char** argv) {
double x = -5.5, y = 4.3;
if (argc > 2) {
x = *argv[1], y = *argv[2];
}
print_localtime();
std::cout << "sigmoid(" << x << "): " << sigmoid(x) << std::endl;
print_localtime();
std::cout << "sigmoid(" << y << "): " << sigmoid(y) << std::endl;
return 0;
}
| 21.076923 | 72 | 0.556569 | research-note |
bacd541c66319b366a947154f517e59a28aaa11e | 1,667 | cpp | C++ | source/engine/input/service/input_service.cpp | Coeurou/kairos_engine | b02eb302d7470d5f29b6ae342b2236dddaae91ea | [
"CC0-1.0"
] | null | null | null | source/engine/input/service/input_service.cpp | Coeurou/kairos_engine | b02eb302d7470d5f29b6ae342b2236dddaae91ea | [
"CC0-1.0"
] | null | null | null | source/engine/input/service/input_service.cpp | Coeurou/kairos_engine | b02eb302d7470d5f29b6ae342b2236dddaae91ea | [
"CC0-1.0"
] | null | null | null | #include <input/service/input_service.h>
#include <input/service/detail/input_service_helpers.h>
namespace kairos {
/** Member functions */
result<uint32> input_service::enable(input_device device) {
if (detail::enable(device)) {
return result<uint32>(EXIT_SUCCESS);
}
else {
return result<uint32>(error_type::runtime_error);
}
}
void input_service::process_events(const array<system_event>& events) {
for (const auto& e : events) {
switch (type(e)) {
case event_type::key_press:
case event_type::key_release: {
const auto& k = cast<keyboard_event>(e);
my_keyboard.my_keys_status[to_index(k.my_key)] = k.my_action;
break;
}
case event_type::controller_button_press:
case event_type::controller_button_release: {
const auto& c = cast<controller_event>(e);
my_controller.my_buttons_status[to_index(c.my_button)] = c.my_action;
break;
}
case event_type::controller_axis_move: {
const auto& c = cast<controller_event>(e);
my_controller.my_axis_status[to_index(c.my_axis)] = c.my_axis_value;
break;
}
case event_type::controller_device: {
reset(my_controller);
const auto& c = cast<controller_event>(e);
if (c.my_device_state != controller_device_state::removed) {
my_controller.is_connected = true;
my_controller.my_id = c.my_controller_id;
}
break;
}
}
}
}
} // namespace kairos | 32.686275 | 82 | 0.590282 | Coeurou |
bacde35bc59c9f200dcb533630ded58054f0548e | 1,373 | hpp | C++ | syswatcher/util/traverse.hpp | Jim-CodeHub/syswatcher | 57aa62c54fc1e5ab7b158e205ad0026631dc845a | [
"Apache-2.0"
] | null | null | null | syswatcher/util/traverse.hpp | Jim-CodeHub/syswatcher | 57aa62c54fc1e5ab7b158e205ad0026631dc845a | [
"Apache-2.0"
] | null | null | null | syswatcher/util/traverse.hpp | Jim-CodeHub/syswatcher | 57aa62c54fc1e5ab7b158e205ad0026631dc845a | [
"Apache-2.0"
] | null | null | null |
/**-----------------------------------------------------------------------------------------------------------------
* @file traverse.hpp
*
* Copyright (c) 2020-2020 Jim Zhang 303683086@qq.com
*------------------------------------------------------------------------------------------------------------------
*/
#ifndef __TRAVERSE_H__
#define __TRAVERSE_H__
/*------------------------------------------------------------------------------------------------------------------
*
* FolderBox INCLUDES
*
*------------------------------------------------------------------------------------------------------------------
*/
#include <fstream>
namespace NS_FOLDERBOX{
/*------------------------------------------------------------------------------------------------------------------
*
* FolderBox SHORTALIAS
*
*------------------------------------------------------------------------------------------------------------------
*/
/*------------------------------------------------------------------------------------------------------------------
*
* FolderBox DATABLOCK
*
*------------------------------------------------------------------------------------------------------------------
*/
class traverse{
public:
traverse();
~traverse();
private:
};
} /**< NS_FOLDERBOX */
#endif /*__TRAVERSE_H__*/
| 25.425926 | 116 | 0.187181 | Jim-CodeHub |
bad735d6bf40a4c3a5a6d13a499703070d4316ff | 23 | cpp | C++ | clWrapper/clWrapper/clContext.cpp | JJPPeters/clWrapper | c8528d0c264bb4faf17b678f299dd3aa0e194141 | [
"MIT"
] | 1 | 2017-08-24T21:55:31.000Z | 2017-08-24T21:55:31.000Z | clWrapper/clWrapper/clContext.cpp | JJPPeters/clWrapper | c8528d0c264bb4faf17b678f299dd3aa0e194141 | [
"MIT"
] | null | null | null | clWrapper/clWrapper/clContext.cpp | JJPPeters/clWrapper | c8528d0c264bb4faf17b678f299dd3aa0e194141 | [
"MIT"
] | 1 | 2019-03-03T10:12:55.000Z | 2019-03-03T10:12:55.000Z | #include "clContext.h"
| 11.5 | 22 | 0.73913 | JJPPeters |
bad94f77d7514bc071b05cce93095a29327f2b82 | 6,677 | hpp | C++ | cpp/include/communication/ControlSettings.hpp | skydiveuas/skydive | 6a3ddb20210c7feec93c2124c99a764e91f13701 | [
"MIT"
] | 2 | 2017-12-09T22:44:35.000Z | 2018-04-08T11:51:53.000Z | cpp/include/communication/ControlSettings.hpp | skydiveuas/skydive | 6a3ddb20210c7feec93c2124c99a764e91f13701 | [
"MIT"
] | 1 | 2018-04-08T12:15:23.000Z | 2018-04-08T12:15:23.000Z | cpp/include/communication/ControlSettings.hpp | skydiveuas/skydive | 6a3ddb20210c7feec93c2124c99a764e91f13701 | [
"MIT"
] | 1 | 2018-04-08T11:50:43.000Z | 2018-04-08T11:50:43.000Z | // =========== roboLib ============
// === *** BARTOSZ NAWROT *** ===
// ================================
#ifndef __CONTROL_SETTINGS__
#define __CONTROL_SETTINGS__
#ifdef __SKYDIVE_USE_STL__
#include <string>
#include <vector>
#endif // __SKYDIVE_USE_STL__
#include "common/MathCore.hpp"
#include "ISignalPayloadMessage.hpp"
#include "SignalData.hpp"
#include "ControlData.hpp"
#include "common/Flags.hpp"
/**
* =============================================================================================
* ControlSettings
* =============================================================================================
*/
class ControlSettings : public ISignalPayloadMessage
{
public:
enum UavType
{
TRICOPTER_REAR = 1000,
TRICOPTER_FRONT = 1500,
QUADROCOPTER_X = 2000,
QUADROCOPTER_PLUS = 2500,
HEXACOPTER_X = 3000,
HEXACOPTER_PLUS = 3500,
OCTOCOPTER_X = 4000,
OCTOCOPTER_PLUS = 4500
};
enum ThrottleMode // unsigned char
{
STATIC = 10,
DYNAMIC = 20,
RATE = 30,
ALTITUDE = 40
};
enum StickMovementMode
{
COPTER,
GEOGRAPHIC,
BASE_POINT
};
enum BatteryType
{
UNDEFINED = 0,
BATTERY_2S = 2,
BATTERY_3S,
BATTERY_4S,
BATTERY_5S,
BATTERY_6S
};
enum EscPwmFreq
{
SLOW = 100,
MEDIUM = 200,
FAST = 300,
VERY_FAST = 400,
ONESHOT_125 = 3200
};
enum FlagId
{
ENABLE_FLIGHT_LOGGER,
ALLOW_DYNAMIC_AUTOPILOT,
EMPTY, // to be used by new flag
ANGLES_TUNED,
AUTOPILOT_TUNED
};
// base control settings
int uavType;
int initialSolverMode;
int manualThrottleMode;
// auto landing settings
float autoLandingDescedRate;
float maxAutoLandingTime;
// control values
float maxRollPitchControlValue;
float maxYawControlValue;
// regulator control settings
// stabilization
Vect3Df pidRollRate, pidPitchRate, pidYawRate;
// angle
float rollProp, pitchProp, yawProp;
// throttle controller settings
float maxVerticalAutoVelocity;
float altPositionProp;
float altVelocityProp;
Vect3Df pidThrottleAccel;
// throttle controller stick settings
float throttleAltRateProp;
// autopilot settings
float maxAutoAngle;
float maxAutoVelocity;
float autoPositionProp;
float autoVelocityProp;
Vect3Df pidAutoAccel;
// autopilot stick settings
float stickPositionRateProp;
int stickMovementMode;
// battery type
int batteryType;
// error handling type
int errorHandlingAction;
// esc controller PWM frequency
int escPwmFreq;
// gps sensors position in rigid body coordinate system
Vect3Df gpsSensorPosition;
// flags for any boolean settings
Flags<unsigned> flags;
ControlSettings(void);
ControlSettings(const unsigned char* src);
void serialize(unsigned char* dst) const;
unsigned getDataSize() const;
SignalData::Command getSignalDataType(void) const;
SignalData::Command getSignalDataCommand(void) const;
SignalData::Command getUploadAction(void) const;
MessageType getMessageType(void) const;
bool isValid(void) const;
unsigned getCrc(void) const;
void setCrc(void);
ISignalPayloadMessage* clone(void) const;
UavType getUavType() const;
ControlData::SolverMode getSolverMode() const;
ThrottleMode getManualThrottleMode() const;
StickMovementMode getStickMovementMode() const;
BatteryType getBatteryType() const;
ControlData::ControllerCommand getErrorHandlingAction() const;
EscPwmFreq getEscPwmFreq() const;
float getBatteryErrorLevel(void) const;
float getBatteryWarningLevel(void) const;
float getBatteryMaxLevel(void) const;
float getBatteryPercentage(const float voltage) const;
bool isBatteryError(const float voltage) const;
bool isBatteryWarning(const float voltage) const;
ControlData::SolverMode getInitialSolverMode(void) const;
ControlData formatEulers(const ControlData& controlData) const;
static ControlSettings createDefault(void);
bool isUavBisymetricalFromData(void) const;
ControlData getControlDataForLogs(const ControlData& controlData) const;
float retriveAngleTuner(void);
float retriveRateTuner(void);
static float getTunerRpProp(const float tuner);
static Vect3Df getTunerRpRate(const float tuner);
static float getTunerYawProp(const float tuner);
static Vect3Df getTunerYawRate(const float tuner);
Vect2Df retriveAutopilotTuners(void);
static Vect2Df getTunerVerticalPropSpeed(const float speed, const float force);
static Vect3Df getTunerVerticalAccel(const float speed, const float force);
static Vect2Df getTunerHorizontalPropSpeed(const float speed, const float force);
static Vect3Df getTunerHorizontalAccel(const float speed, const float force);
#ifdef __SKYDIVE_USE_STL__
static std::string getUavTypeString(UavType type);
std::string getUavTypeString(void) const;
std::string getInitialSolverString(void) const;
std::string getManualThrottleString(void) const;
std::string getStickModeString(void) const;
std::string getBatteryTypeString(void) const;
std::string getErrorHandlingActionString(void) const;
std::string getEscPwmFreqString(void) const;
static UavType uavTypeFromString(const std::string& uavTypeString);
static ControlData::SolverMode solverModeFromString(const std::string& solverMode);
static ThrottleMode manualThrottleModeFromString(const std::string& throttleMode);
static StickMovementMode stickModeFromString(const std::string& stickMode);
static BatteryType batteryTypeFromString(const std::string& batteryType);
static ControlData::ControllerCommand errorHandlingActionFromString(const std::string& errorHandlingAction);
static EscPwmFreq escPwmFreqFromString(const std::string& escPwmFreq);
static std::vector<std::string> getUavTypes(void);
static std::vector<std::string> getSolvers(void);
static std::vector<std::string> getThrottleModes(void);
static std::vector<std::string> getStickModes(void);
static std::vector<std::string> getBatteryTypes(void);
static std::vector<std::string> getErrorHandlingActions(void);
static std::vector<std::string> getEscPwmFreqs(void);
friend std::ostream& operator << (std::ostream& stream, const ControlSettings& cS);
#endif // __SKYDIVE_USE_STL__
private:
unsigned crcValue;
};
#endif // __CONTROL_SETTINGS__
| 28.054622 | 112 | 0.687584 | skydiveuas |
badb85fe1210ee5f1d614cd0b64b68f433c0a827 | 1,618 | cpp | C++ | Electronics/Firmware/src/Program/Lib_Chicago/Debug/cmd.cpp | magicmellon/ProjectNorthStar | a7ab09aac9810055639f099f5a53bb1cb5496fb8 | [
"Apache-2.0"
] | 2 | 2018-08-18T20:27:29.000Z | 2018-11-19T20:21:26.000Z | Electronics/Firmware/src/Program/Lib_Chicago/Debug/cmd.cpp | magicmellon/ProjectNorthStar | a7ab09aac9810055639f099f5a53bb1cb5496fb8 | [
"Apache-2.0"
] | null | null | null | Electronics/Firmware/src/Program/Lib_Chicago/Debug/cmd.cpp | magicmellon/ProjectNorthStar | a7ab09aac9810055639f099f5a53bb1cb5496fb8 | [
"Apache-2.0"
] | null | null | null | /**
* @file cmd.cpp
*
* @brief Chicago UART command line interpreter
*
* @copyright
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 3.0 of the License, or (at your option) any later version.
*
* @copyright
* 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.
*
* @author Analogix, Inc
* @author Adam Munich
*/
//#############################################################################
// Includes
//-----------------------------------------------------------------------------
#include <string.h>
#include <stdint.h>
#include "./cmd.h"
#include "./debug.h"
#include "./serial.h"
#include "./cmdHandler.h"
#include "../Chicago/chicago_config.h"
//#############################################################################
// Variable Declarations
//-----------------------------------------------------------------------------
extern uint8_t g_CmdLineBuf[CMD_LINE_SIZE];
extern const uint8_t g_bPutcharEnable;
//#############################################################################
// Function Definitions
//-----------------------------------------------------------------------------
void cmd(void){
volatile uint8_t ser = SerialRecv();
if(ser != 0){
CmdHandler();
}
}
| 29.418182 | 79 | 0.513597 | magicmellon |
badc323034d5416a16415f766707873a1302ff53 | 2,604 | cc | C++ | bench/SpMMFP32Benchmark.cc | menchunlei/FBGEMM | 588ecfcca3d83186461554cd28dedc41532d75b4 | [
"BSD-3-Clause"
] | null | null | null | bench/SpMMFP32Benchmark.cc | menchunlei/FBGEMM | 588ecfcca3d83186461554cd28dedc41532d75b4 | [
"BSD-3-Clause"
] | null | null | null | bench/SpMMFP32Benchmark.cc | menchunlei/FBGEMM | 588ecfcca3d83186461554cd28dedc41532d75b4 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "bench/BenchUtils.h"
#include "fbgemm/FbgemmSpMM.h"
#include <iostream>
using namespace std;
using namespace fbgemm;
int main(int, char**) {
vector<vector<int>> shapes = {{128, 1024, 1024}};
// C is MxN -> CT is NxM
// A is MxK -> AT is KxM
// B is KxN -> BT is NxK
// for (int s = 64; s <= 128; s *= 2)
for (auto const& s : shapes) {
int m = s[0];
int n = s[1];
int k = s[2];
for (float fnz = 0.99; fnz >= 0.009999; fnz -= 0.01) {
auto aData = getRandomSparseVector(m * k);
auto bData = getRandomSparseVector(k * n, fnz);
auto cData = getRandomSparseVector(m * n);
aligned_vector<float> atData(k * m);
aligned_vector<float> btData(n * k);
aligned_vector<float> ctData(n * m);
transpose_matrix(m, k, aData.data(), k, atData.data(), m);
transpose_matrix(k, n, bData.data(), n, btData.data(), k);
// We calculate C^T = B^T x A^T
// B matrix is sparse and passed in as first matrix to generateSpMM
int ldat = m;
int ldbt = k;
int ldct = m;
auto fn = generateSpMM<float>(n, m, k, btData.data(), ldbt, ldat, ldct);
auto fn_varying_n = generateSpMM<float>(n, k, btData.data(), ldbt);
double effective_flop = m * n * k * 2;
constexpr int NWARMUP = 5;
constexpr int NITER = 32;
auto secs = measureWithWarmup(
[&]() { fn(atData.data(), ctData.data(), 0); },
NWARMUP,
NITER,
[&]() {
cache_evict(atData);
cache_evict(btData);
cache_evict(ctData);
});
auto secs_varying_n = measureWithWarmup(
[&]() {
fn_varying_n(
atData.data(),
ctData.data(),
m,
ldat, /* ldat */
ldct, /* ldct */
0 /* accum_flag */);
},
NWARMUP,
NITER,
[&]() {
cache_evict(atData);
cache_evict(btData);
cache_evict(ctData);
});
double effective_gflops = effective_flop / secs / 1e9;
double effective_gflops_varying_n = effective_flop / secs_varying_n / 1e9;
cout << fnz << "," << effective_gflops << "," << fnz * effective_gflops
<< "," << effective_gflops_varying_n << ","
<< fnz * effective_gflops_varying_n << endl;
}
}
}
| 29.258427 | 80 | 0.541859 | menchunlei |
bae057a39f0c8f59cb74cc9176e0361d754d51a0 | 251 | cpp | C++ | apps/bjt/main.cpp | Brillist/libutl | e55c2af091ba1101a1d0608db2830e279ec95d16 | [
"MIT"
] | 1 | 2021-09-14T06:12:58.000Z | 2021-09-14T06:12:58.000Z | apps/bjt/main.cpp | Brillist/libutl | e55c2af091ba1101a1d0608db2830e279ec95d16 | [
"MIT"
] | null | null | null | apps/bjt/main.cpp | Brillist/libutl | e55c2af091ba1101a1d0608db2830e279ec95d16 | [
"MIT"
] | 2 | 2019-05-13T23:04:31.000Z | 2021-09-14T06:12:59.000Z | #include "common.h"
#include <libutl/BufferedFDstream.h>
#include "BlackjackTrainer.h"
#include <libutl/Exception.h>
////////////////////////////////////////////////////////////////////////////////////////////////////
UTL_MAIN_RL(BlackjackTrainer);
| 27.888889 | 100 | 0.47012 | Brillist |
bae1d9d124b9b6db2cf54232dc5c732fc63e2a39 | 4,880 | hpp | C++ | include/nix/Feature.hpp | cgars/nix | 0bc4c32f173d2d34e19d1a02ee1e0183551bf160 | [
"BSD-3-Clause"
] | null | null | null | include/nix/Feature.hpp | cgars/nix | 0bc4c32f173d2d34e19d1a02ee1e0183551bf160 | [
"BSD-3-Clause"
] | null | null | null | include/nix/Feature.hpp | cgars/nix | 0bc4c32f173d2d34e19d1a02ee1e0183551bf160 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#ifndef NIX_FEATURE_H
#define NIX_FEATURE_H
#include <nix/base/Entity.hpp>
#include <nix/base/IFeature.hpp>
#include <nix/DataArray.hpp>
#include <nix/Platform.hpp>
namespace nix {
/**
* @brief {@link Feature} entities are used to attach further data to a {@link nix::Tag} or
* {@link nix::MultiTag}
*
* A {@link Feature} entity contains a link to an existing {@link nix::DataArray} containing additional
* data that belongs to the respective tag. The way how data and feature are connected is specified by the
* link type.
*
* ### Tagged
*
* This link type indicates, that only a certain subset of the linked {@link nix::DataArray}
* belongs to the {@link Feature}. This subset is defined by the position and extent of the
* respective tag.
*
* ### Untagged
*
* This implies that the whole data stored in the linked {@link nix::DataArray} belongs to
* the {@link Feature}.
*
* ### Indexed
*
* This value is only valid for multi tags where it indicates that
* the data linked via this {@link Feature} has to be accessed according
* to the index in the respective position entry.
*/
class NIXAPI Feature : public base::Entity<base::IFeature> {
public:
/**
* @brief Constructor that creates an uninitialized Feature.
*
* Calling any method on an uninitialized feature will throw a {@link nix::UninitializedEntity}
* exception. The following code illustrates how to check if a feature is initialized:
*
* ~~~
* Feature e = ...;
* if (e) {
* // e is initialised
* } else {
* // e is uninitialized
* }
* ~~~
*/
Feature()
: Entity()
{
}
/**
* @brief Copy constructor.
*
* Copying of all NIX front facing objects like Feature is a rather cheap operation.
* Semantically this is equivalent to the creation of another reference to the original
* object.
*
* @param other The feature to copy.
*/
Feature(const Feature &other)
: Entity(other.impl())
{
}
/**
* @brief Constructor that creates a new entity from a shared pointer to
* an implementation instance.
*
* This constructor should only be used in the back-end.
*/
Feature(const std::shared_ptr<base::IFeature> &p_impl)
: Entity(p_impl)
{
}
/**
* @brief Constructor with move semantics that creates a new entity from a shared pointer to
* an implementation instance.
*
* This constructor should only be used in the back-end.
*/
Feature(std::shared_ptr<base::IFeature> &&ptr)
: Entity(std::move(ptr))
{
}
/**
* @brief Setter for the link type.
*
* @param type The link type to set.
*/
void linkType(LinkType type) {
backend()->linkType(type);
}
/**
* @brief Getter for the link type.
*
* @return The current link type of the feature.
*/
LinkType linkType() const {
return backend()->linkType();
}
/**
* @brief Sets the data array associated with this feature.
*
* @param name_or_id Name or id of the data array to set.
*/
void data(const std::string &name_or_id);
/**
* @brief Sets the data array associated with this feature.
*
* @param data The data array to set.
*/
void data(const DataArray &data);
/**
* @brief Gets the data array associated with this feature.
*
* @return The associated data array.
*/
DataArray data() const {
return backend()->data();
}
/**
* @brief Destructor.
*/
virtual ~Feature() {}
//--------------------------------------------------
// Other methods and functions
//--------------------------------------------------
/**
* @brief Assignment operator for none.
*/
Feature &operator=(const none_t &t) {
ImplContainer::operator=(t);
return *this;
}
};
/**
* @brief Convert a link type into string representation.
*
* @param ltype The link type.
*
* @return A human readable name for the given type.
*/
NIXAPI std::string link_type_to_string(LinkType ltype);
/**
* @brief Output operator for link type.
*
* Prints a human readable string representation of the
* link type to an output stream.
*
* @param out The output stream.
* @param ltype The link type to print.
*
* @return The output stream.
*/
NIXAPI std::ostream& operator<<(std::ostream &out, const LinkType ltype);
} // namespace nix
#endif // NIX_FEATURE_H
| 25.549738 | 106 | 0.609631 | cgars |
bae701112f00025e9cb3484bdc0a4517e95331d3 | 6,621 | cc | C++ | xapian/xapian-core-1.2.13/expand/ortermlist.cc | NeoYY/tailbench-v0.9 | cf9849c3e8c407199f25b4710c06fb8c4e2ff025 | [
"MIT"
] | 2 | 2021-01-13T21:17:42.000Z | 2021-01-13T21:17:42.000Z | xapian/xapian-core-1.2.13/expand/ortermlist.cc | Loslove55/tailbench | fbbf3f31e3f0af1bb7db7f07c2e7193b84abb1eb | [
"MIT"
] | null | null | null | xapian/xapian-core-1.2.13/expand/ortermlist.cc | Loslove55/tailbench | fbbf3f31e3f0af1bb7db7f07c2e7193b84abb1eb | [
"MIT"
] | null | null | null | /** @file ortermlist.cc
* @brief Merge two TermList objects using an OR operation.
*/
/* Copyright (C) 2007,2010 Olly Betts
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <config.h>
#include "ortermlist.h"
#include "debuglog.h"
#include "omassert.h"
#include <xapian/positioniterator.h>
using namespace std;
void
OrTermList::check_started() const
{
Assert(!left_current.empty());
Assert(!right_current.empty());
}
OrTermList::~OrTermList()
{
delete left;
delete right;
}
Xapian::termcount
OrTermList::get_approx_size() const
{
LOGCALL(EXPAND, Xapian::termcount, "OrTermList::get_approx_size", NO_ARGS);
// This is actually the upper bound, but we only use this to order the
// binary tree of OrTermList objects so it's probably not worth trying
// to be more sophisticated.
RETURN(left->get_approx_size() + right->get_approx_size());
}
void
OrTermList::accumulate_stats(Xapian::Internal::ExpandStats & stats) const
{
LOGCALL_VOID(EXPAND, "OrTermList::accumulate_stats", stats);
check_started();
if (left_current <= right_current) left->accumulate_stats(stats);
if (left_current >= right_current) right->accumulate_stats(stats);
}
string
OrTermList::get_termname() const
{
LOGCALL(EXPAND, string, "OrTermList::get_termname", NO_ARGS);
check_started();
if (left_current < right_current) RETURN(left_current);
RETURN(right_current);
}
Xapian::termcount
OrTermList::get_wdf() const
{
LOGCALL(EXPAND, Xapian::termcount, "OrTermList::get_wdf", NO_ARGS);
check_started();
if (left_current < right_current) RETURN(left->get_wdf());
if (left_current > right_current) RETURN(right->get_wdf());
RETURN(left->get_wdf() + right->get_wdf());
}
Xapian::doccount
OrTermList::get_termfreq() const
{
LOGCALL(EXPAND, Xapian::doccount, "OrTermList::get_termfreq", NO_ARGS);
check_started();
if (left_current < right_current) RETURN(left->get_termfreq());
Assert(left_current > right_current || left->get_termfreq() == right->get_termfreq());
RETURN(right->get_termfreq());
}
#if 0 // This method isn't actually used anywhere currently.
Xapian::termcount
OrTermList::get_collection_freq() const
{
LOGCALL(EXPAND, Xapian::termcount, "OrTermList::get_collection_freq", NO_ARGS);
check_started();
if (left_current < right_current) RETURN(left->get_collection_freq());
Assert(left_current > right_current || left->get_collection_freq() == right->get_collection_freq());
RETURN(right->get_collection_freq());
}
#endif
// Helper function.
inline void
handle_prune(TermList *& old, TermList * result)
{
if (result) {
delete old;
old = result;
}
}
TermList *
OrTermList::next()
{
LOGCALL(EXPAND, TermList *, "OrTermList::next", NO_ARGS);
// If we've not started yet, both left_current and right_current will be
// empty, so we'll take the third case below which is what we want to do to
// get started.
if (left_current < right_current) {
handle_prune(left, left->next());
if (left->at_end()) {
TermList *ret = right;
right = NULL;
RETURN(ret);
}
left_current = left->get_termname();
} else if (left_current > right_current) {
handle_prune(right, right->next());
if (right->at_end()) {
TermList *ret = left;
left = NULL;
RETURN(ret);
}
right_current = right->get_termname();
} else {
AssertEq(left_current, right_current);
handle_prune(left, left->next());
handle_prune(right, right->next());
if (left->at_end()) {
// right->at_end() may also be true, but our parent will deal with
// that.
TermList *ret = right;
right = NULL;
RETURN(ret);
}
if (right->at_end()) {
TermList *ret = left;
left = NULL;
RETURN(ret);
}
left_current = left->get_termname();
right_current = right->get_termname();
}
RETURN(NULL);
}
TermList *
OrTermList::skip_to(const string & term)
{
LOGCALL(EXPAND, TermList *, "OrTermList::skip_to", term);
// If we've not started yet, both left_current and right_current will be
// empty, so we'll take the third case below which is what we want to do to
// get started.
if (left_current < right_current) {
handle_prune(left, left->skip_to(term));
if (left->at_end()) {
TermList *ret = right;
right = NULL;
RETURN(ret);
}
left_current = left->get_termname();
} else if (left_current > right_current) {
handle_prune(right, right->skip_to(term));
if (right->at_end()) {
TermList *ret = left;
left = NULL;
RETURN(ret);
}
right_current = right->get_termname();
} else {
AssertEq(left_current, right_current);
handle_prune(left, left->skip_to(term));
handle_prune(right, right->skip_to(term));
if (left->at_end()) {
// right->at_end() may also be true, but our parent will deal with
// that.
TermList *ret = right;
right = NULL;
RETURN(ret);
}
if (right->at_end()) {
TermList *ret = left;
left = NULL;
RETURN(ret);
}
left_current = left->get_termname();
right_current = right->get_termname();
}
RETURN(NULL);
}
bool
OrTermList::at_end() const
{
LOGCALL(EXPAND, bool, "OrTermList::at_end", NO_ARGS);
check_started();
// next() should have pruned if either child is at_end().
Assert(!left->at_end());
Assert(!right->at_end());
RETURN(false);
}
Xapian::termcount
OrTermList::positionlist_count() const
{
Assert(false);
return 0;
}
Xapian::PositionIterator
OrTermList::positionlist_begin() const
{
Assert(false);
return Xapian::PositionIterator();
}
Xapian::doccount
FreqAdderOrTermList::get_termfreq() const
{
LOGCALL(EXPAND, Xapian::doccount, "FreqAdderOrTermList::get_termfreq", NO_ARGS);
check_started();
if (left_current < right_current) RETURN(left->get_termfreq());
if (left_current > right_current) RETURN(right->get_termfreq());
RETURN(left->get_termfreq() + right->get_termfreq());
}
| 27.5875 | 104 | 0.685697 | NeoYY |
bae81855c27b08a3e568512e0c2600a9c5c5e0bb | 1,130 | cpp | C++ | license-server/serverapp/appconfig_reader.cpp | stallion5632/license-services | e46be0a89fdee4037aa8804411b6ec135ce25887 | [
"MIT"
] | 1 | 2022-01-02T13:14:05.000Z | 2022-01-02T13:14:05.000Z | license-server/serverapp/appconfig_reader.cpp | stallion5632/license-services | e46be0a89fdee4037aa8804411b6ec135ce25887 | [
"MIT"
] | null | null | null | license-server/serverapp/appconfig_reader.cpp | stallion5632/license-services | e46be0a89fdee4037aa8804411b6ec135ce25887 | [
"MIT"
] | 1 | 2021-06-16T10:09:09.000Z | 2021-06-16T10:09:09.000Z | #include "appconfig_reader.h"
#include "common.h"
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/algorithm/string.hpp>
#include <iostream>
using namespace boost;
static const char *kAppConfigRoot = "server";
static const char *kDogCheckInterval = "DogCheckInterval";
static const char *kHeartbeatInterval = "HeartbeatInterval";
static const char *kMaxSupportClientNum = "MaxSupportClientNum";
static const char *kServerPort = "ServerPort";
// load app configure
ServerConfig loadAppConfig(const std::string &filepath)
{
property_tree::ptree pt;
property_tree::ini_parser::read_ini(filepath, pt);
property_tree::ptree client;
client = pt.get_child(kAppConfigRoot);
ServerConfig cfg;
auto a = client.get_optional<int>(kHeartbeatInterval);
if (a)
cfg.heartbeatInterval = *a;
auto b = client.get_optional<int>(kDogCheckInterval);
if (b)
cfg.dogCheckInterval = *b;
auto c = client.get_optional<int>(kMaxSupportClientNum);
if (c)
cfg.maxSupportClientNum = *c;
auto d = client.get_optional<int>(kServerPort);
if (d)
cfg.serverPort = *d;
return cfg;
}
| 26.27907 | 64 | 0.760177 | stallion5632 |
baf5502ce60aae2b30afe33b1ecdf1a75ae7ea7f | 1,403 | hpp | C++ | src/integrator/direct.hpp | jkrueger/phosphorus | e36d3c4b81b4327a983469116f066fdeefc9104e | [
"MIT"
] | null | null | null | src/integrator/direct.hpp | jkrueger/phosphorus | e36d3c4b81b4327a983469116f066fdeefc9104e | [
"MIT"
] | null | null | null | src/integrator/direct.hpp | jkrueger/phosphorus | e36d3c4b81b4327a983469116f066fdeefc9104e | [
"MIT"
] | null | null | null | #pragma once
#include "math/ray.hpp"
#include "math/sampling.hpp"
#include "shading.hpp"
#include "thing.hpp"
#include "things/scene.hpp"
#include "util/color.hpp"
struct direct_t {
const uint32_t spd;
const uint32_t samples;
sample_t uv[9];
direct_t(uint32_t spd)
: spd(spd)
, samples(spd*spd) {
sampling::strategies::stratified_2d(uv, spd);
}
template<typename Scene>
inline color_t li(
const Scene& scene
, const vector_t& wo
, const shading_info_t& info) const {
color_t r;
const auto bxdf = info.bxdf();
if (scene.lights.size() > 0 && bxdf->has_distribution()) {
sampled_vector_t light_samples[samples];
// TODO: importance sampling on light sources
for (const auto& emitter : scene.lights) {
// TODO: replace with precomputed samples
emitter->sample(info.p, uv, light_samples, samples);
color_t light;
for (const auto& sample : light_samples) {
auto wi = sample.sampled - info.p;
const auto d = wi.length();
wi.normalize();
if (in_same_hemisphere(wi, info.n) &&
!scene.occluded(info.ray(wi), d)) {
const auto il = info.b.to_local(wi);
const auto ol = info.b.to_local(wo);
const auto s = il.y/(sample.pdf*d*d);
light += (emitter->emit() * bxdf->f(il, ol)).scale(s);
}
}
r += light.scale(1.0/samples);
}
}
return r * (1.0f/scene.lights.size());
}
};
| 23 | 62 | 0.634355 | jkrueger |
bafa42994ecccd1cd33714577c2ff9cf04bd19b3 | 5,558 | cpp | C++ | CENTRAL 3D/Source/Quadtree.cpp | AitorSimona/3DEngines | 01700230b4733e6976fb14971dcc835374f8db12 | [
"MIT"
] | 2 | 2020-01-20T12:28:42.000Z | 2020-05-10T23:06:58.000Z | CENTRAL 3D/Source/Quadtree.cpp | AitorSimona/3DEngines | 01700230b4733e6976fb14971dcc835374f8db12 | [
"MIT"
] | 3 | 2020-01-20T13:15:28.000Z | 2020-04-07T10:53:53.000Z | CENTRAL 3D/Source/Quadtree.cpp | AitorSimona/3DEngines | 01700230b4733e6976fb14971dcc835374f8db12 | [
"MIT"
] | 4 | 2019-10-22T20:56:48.000Z | 2021-01-10T14:24:43.000Z | #include "Globals.h"
#include "GameObject.h"
#include "ComponentTransform.h"
#include "QuadTree.h"
#include "mmgr/mmgr.h"
// --- All child indexes ---
#define NET 0
#define SET 1
#define SWT 2
#define NWT 3
#define NEB 4
#define SEB 5
#define SWB 6
#define NWB 7
// --- Max items before subdividing ---
#define QUADTREE_MAX_ITEMS 10
#define QUADTREE_MIN_SIZE 10.0f
QuadtreeNode::QuadtreeNode(const AABB& box) : box(box)
{
parent = childs[NET] = childs[SET] = childs[SWT] = childs[NWT] = childs[NEB] = childs[SEB] = childs[SWB] = childs[NWB] = nullptr;
}
QuadtreeNode::~QuadtreeNode()
{
for (int i = 0; i < 8; ++i)
{
if (childs[i] != nullptr)
delete(childs[i]);
}
}
bool QuadtreeNode::IsLeaf() const
{
return childs[0] == nullptr;
}
void QuadtreeNode::Insert(GameObject* go)
{
if (IsLeaf() == true &&
(objects.size() < QUADTREE_MAX_ITEMS ||
(box.HalfSize().LengthSq() <= QUADTREE_MIN_SIZE * QUADTREE_MIN_SIZE)))
objects.push_back(go);
else
{
if (IsLeaf() == true)
CreateChilds();
objects.push_back(go);
RedistributeChilds();
}
}
void QuadtreeNode::Erase(GameObject * go)
{
std::list<GameObject*>::iterator it = std::find(objects.begin(), objects.end(), go);
if (it != objects.end())
objects.erase(it);
if (IsLeaf() == false)
{
for (int i = 0; i < 8; ++i)
childs[i]->Erase(go);
}
}
/*
----------- MaxPoint
| NW | NE |
|---------|
| SW | SE |
-----------
MinPoint
*/
void QuadtreeNode::CreateChilds()
{
// NorthEast - TOP
childs[NET] = new QuadtreeNode(box);
childs[NET]->CreateNode(NET);
// SouthEast - TOP
childs[SET] = new QuadtreeNode(box);
childs[SET]->CreateNode(SET);
// SouthWest - TOP
childs[SWT] = new QuadtreeNode(box);
childs[SWT]->CreateNode(SWT);
// NorthWest - TOP
childs[NWT] = new QuadtreeNode(box);
childs[NWT]->CreateNode(NWT);
// NorthEast - BOT
childs[NEB] = new QuadtreeNode(box);
childs[NEB]->CreateNode(NEB);
// SouthEast - BOT
childs[SEB] = new QuadtreeNode(box);
childs[SEB]->CreateNode(SEB);
// SouthWest - BOT
childs[SWB] = new QuadtreeNode(box);
childs[SWB]->CreateNode(SWB);
// NorthWest - BOT
childs[NWB] = new QuadtreeNode(box);
childs[NWB]->CreateNode(NWB);
}
void QuadtreeNode::CreateNode(uint index)
{
//Index positions from top view
//0 1
//2 3
float3 minPoint, maxPoint;
minPoint.y = this->box.minPoint.y;
maxPoint.y = this->box.maxPoint.y;
minPoint.x = (index / 2) == 1 ? this->box.minPoint.x : (this->box.maxPoint.x + this->box.minPoint.x) / 2;
maxPoint.x = (index / 2) == 1 ? (this->box.maxPoint.x + this->box.minPoint.x) / 2 : this->box.maxPoint.x;
minPoint.z = index % 2 == 0 ? this->box.minPoint.z : (this->box.maxPoint.z + this->box.minPoint.z) / 2;
maxPoint.z = index % 2 == 0 ? (this->box.maxPoint.z + this->box.minPoint.z) / 2 : this->box.maxPoint.z;
box = AABB(minPoint, maxPoint);
}
void QuadtreeNode::RedistributeChilds()
{
// --- Redistribute all objects ---
for (std::list<GameObject*>::iterator it = objects.begin(); it != objects.end();)
{
GameObject* go = *it;
AABB new_box(go->GetOBB().MinimalEnclosingAABB());
// --- Distribute this new gameobject onto the childs ---
bool intersects[8];
for (int i = 0; i < 8; ++i)
intersects[i] = childs[i]->box.Intersects(new_box);
if (intersects[0] && intersects[1] && intersects[2] && intersects[3]
&& intersects[4] && intersects[5] && intersects[6] && intersects[7])
++it; // if it hits all childs, better to just keep it here
else
{
it = objects.erase(it);
for (int i = 0; i < 8; ++i)
{
if (intersects[i])
{
childs[i]->Insert(go);
break;
}
}
}
}
}
void QuadtreeNode::CollectObjects(std::vector<GameObject*>& objects) const
{
for (std::list<GameObject*>::const_iterator it = this->objects.begin(); it != this->objects.end(); ++it)
objects.push_back(*it);
for (int i = 0; i < 8; ++i)
if (childs[i] != nullptr) childs[i]->CollectObjects(objects);
}
void QuadtreeNode::CollectObjects(std::map<float, GameObject*>& objects, const float3& origin) const
{
for (std::list<GameObject*>::const_iterator it = this->objects.begin(); it != this->objects.end(); ++it)
{
ComponentTransform* transform = (*it)->GetComponent<ComponentTransform>();
float dist = origin.DistanceSq(transform->GetGlobalPosition());
objects[dist] = *it;
}
for (int i = 0; i < 8; ++i)
if (childs[i] != nullptr) childs[i]->CollectObjects(objects, origin);
}
void QuadtreeNode::CollectBoxes(std::vector<const QuadtreeNode*>& nodes) const
{
nodes.push_back(this);
for (int i = 0; i < 8; ++i)
if (childs[i] != nullptr) childs[i]->CollectBoxes(nodes);
}
// ---------------------------------------------------------------------
Quadtree::Quadtree()
{}
Quadtree::~Quadtree()
{
Clear();
}
void Quadtree::SetBoundaries(const AABB& box)
{
Clear();
root = new QuadtreeNode(box);
}
void Quadtree::Insert(GameObject* go)
{
if (root != nullptr)
{
if (go->GetOBB().MinimalEnclosingAABB().Intersects(root->box))
root->Insert(go);
}
}
void Quadtree::Erase(GameObject * go)
{
if (root != nullptr)
root->Erase(go);
}
void Quadtree::Clear()
{
delete root;
}
void Quadtree::CollectBoxes(std::vector<const QuadtreeNode*>& nodes) const
{
if (root != nullptr)
root->CollectBoxes(nodes);
}
void Quadtree::CollectObjects(std::vector<GameObject*>& objects) const
{
if (root != nullptr)
root->CollectObjects(objects);
}
void Quadtree::CollectObjects(std::map<float, GameObject*>& objects, const float3& origin) const
{
if (root != nullptr)
root->CollectObjects(objects, origin);
}
| 21.796078 | 130 | 0.639259 | AitorSimona |
bafd0582987553bc920b0542043507875d9298a5 | 8,623 | cpp | C++ | testbed/tests/maxwell.cpp | Hexlord/box2d | 57722e8c0aee124545b6fe67f82f8d64e2117d2b | [
"MIT"
] | 1 | 2020-09-19T08:19:28.000Z | 2020-09-19T08:19:28.000Z | testbed/tests/maxwell.cpp | Hexlord/box2d | 57722e8c0aee124545b6fe67f82f8d64e2117d2b | [
"MIT"
] | null | null | null | testbed/tests/maxwell.cpp | Hexlord/box2d | 57722e8c0aee124545b6fe67f82f8d64e2117d2b | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2014 Google, Inc.
*
* 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 "test.h"
// Game which adds some fun to Maxwell's demon.
// http://en.wikipedia.org/wiki/Maxwell's_demon
// The user's goal is to try to catch as many particles as possible in the
// bottom half of the container by splitting the container using a barrier
// with the 'a' key. See Maxwell::Keyboard() for other controls.
class Maxwell : public Test
{
public:
Maxwell()
{
m_density = k_densityDefault;
m_position = k_containerHalfHeight;
m_particleGroup = NULL;
m_temperature = k_temperatureDefault;
m_barrierBody = NULL;
m_world->SetGravity(b2Vec2(0, 0));
// Create the container.
{
b2BodyDef bd;
b2Body* ground = m_world->CreateBody(&bd);
b2ChainShape shape;
const b2Vec2 vertices[4] = {
b2Vec2(-k_containerHalfWidth, 0),
b2Vec2(k_containerHalfWidth, 0),
b2Vec2(k_containerHalfWidth, k_containerHeight),
b2Vec2(-k_containerHalfWidth, k_containerHeight)};
shape.CreateLoop(vertices, 4);
b2FixtureDef def;
def.shape = &shape;
def.density = 0;
def.restitution = 1.0;
ground->CreateFixture(&def);
}
// Enable the barrier.
EnableBarrier();
// Create the particles.
ResetParticles();
}
// Disable the barrier.
void DisableBarrier()
{
if (m_barrierBody)
{
m_world->DestroyBody(m_barrierBody);
m_barrierBody = NULL;
}
}
// Enable the barrier.
void EnableBarrier()
{
if (!m_barrierBody)
{
b2BodyDef bd;
m_barrierBody = m_world->CreateBody(&bd);
b2PolygonShape barrierShape;
barrierShape.SetAsBox(k_containerHalfWidth, k_barrierHeight,
b2Vec2(0, m_position), 0);
b2FixtureDef def;
def.shape = &barrierShape;
def.density = 0;
def.restitution = 1.0;
m_barrierBody->CreateFixture(&def);
}
}
// Enable / disable the barrier.
void ToggleBarrier()
{
if (m_barrierBody)
{
DisableBarrier();
}
else
{
EnableBarrier();
}
}
// Destroy and recreate all particles.
void ResetParticles()
{
if (m_particleGroup != NULL)
{
m_particleGroup->DestroyParticles();
m_particleGroup = NULL;
}
m_particleSystem->SetRadius(k_containerHalfWidth / 20.0f);
{
b2PolygonShape shape;
shape.SetAsBox(m_density * k_containerHalfWidth,
m_density * k_containerHalfHeight,
b2Vec2(0, k_containerHalfHeight), 0);
b2ParticleGroupDef pd;
pd.flags = b2_powderParticle;
pd.shape = &shape;
m_particleGroup = m_particleSystem->CreateParticleGroup(pd);
b2Vec2* velocities =
m_particleSystem->GetVelocityBuffer() +
m_particleGroup->GetBufferIndex();
for (int i = 0; i < m_particleGroup->GetParticleCount(); ++i)
{
b2Vec2& v = *(velocities + i);
v.Set(RandomFloat() + 1.0f, RandomFloat() + 1.0f);
v.Normalize();
v *= m_temperature;
}
}
}
virtual void Step(Settings& settings)
{
Test::Step(settings);
// Number of particles above (top) and below (bottom) the barrier.
int32 top = 0;
int32 bottom = 0;
const int32 index = m_particleGroup->GetBufferIndex();
b2Vec2* const velocities =
m_particleSystem->GetVelocityBuffer() + index;
b2Vec2* const positions =
m_particleSystem->GetPositionBuffer() + index;
for (int32 i = 0; i < m_particleGroup->GetParticleCount(); i++)
{
// Add energy to particles based upon the temperature.
b2Vec2& v = velocities[i];
v.Normalize();
v *= m_temperature;
// Keep track of the number of particles above / below the
// divider / barrier position.
b2Vec2& p = positions[i];
if (p.y > m_position)
top++;
else
bottom++;
}
// Calculate a score based upon the difference in pressure between the
// upper and lower divisions of the container.
const float topPressure = top / (k_containerHeight - m_position);
const float botPressure = bottom / m_position;
g_debugDraw.DrawString(
10, 75, "A to toggle barrier\n= to increase density\n- to decrease density\n; to increase temperature\n\\ to decrease temperature\nScore: %f",
topPressure > 0.0f ? botPressure / topPressure - 1.0f : 0.0f);
}
// Reset the particles and the barrier.
void Reset()
{
DisableBarrier();
ResetParticles();
EnableBarrier();
}
// Move the divider / barrier.
void MoveDivider(const float newPosition)
{
m_position = b2Clamp(newPosition, k_barrierMovementIncrement,
k_containerHeight - k_barrierMovementIncrement);
Reset();
}
virtual void Keyboard(int key)
{
switch(key)
{
case GLFW_KEY_A:
// Enable / disable the barrier.
ToggleBarrier();
break;
case GLFW_KEY_EQUAL:
// Increase the particle density.
m_density = b2Min(m_density * k_densityStep, k_densityMax);
Reset();
break;
case GLFW_KEY_MINUS:
// Reduce the particle density.
m_density = b2Max(m_density / k_densityStep, k_densityMin);
Reset();
break;
case GLFW_KEY_PERIOD:
// Move the location of the divider up.
MoveDivider(m_position + k_barrierMovementIncrement);
break;
case GLFW_KEY_COMMA:
// Move the location of the divider down.
MoveDivider(m_position - k_barrierMovementIncrement);
break;
case GLFW_KEY_SEMICOLON:
// Reduce the temperature (velocity of particles).
m_temperature = b2Max(m_temperature - k_temperatureStep,
k_temperatureMin);
Reset();
break;
case GLFW_KEY_BACKSLASH:
// Increase the temperature (velocity of particles).
m_temperature = b2Min(m_temperature + k_temperatureStep,
k_temperatureMax);
Reset();
break;
default:
Test::Keyboard(key);
break;
}
}
// Determine whether a point is in the container.
bool InContainer(const b2Vec2& p) const
{
return p.x >= -k_containerHalfWidth && p.x <= k_containerHalfWidth &&
p.y >= 0.0f && p.y <= k_containerHalfHeight * 2.0f;
}
virtual void MouseDown(const b2Vec2& p)
{
if (!InContainer(p))
{
Test::MouseDown(p);
}
}
virtual void MouseUp(const b2Vec2& p)
{
// If the pointer is in the container.
if (InContainer(p))
{
// Enable / disable the barrier.
ToggleBarrier();
}
else
{
// Move the barrier to the touch position.
MoveDivider(p.y);
Test::MouseUp(p);
}
}
float GetDefaultViewZoom() const
{
return 0.1f;
}
static Test* Create()
{
return new Maxwell;
}
private:
float m_density;
float m_position;
float m_temperature;
b2Body* m_barrierBody;
b2ParticleGroup* m_particleGroup;
private:
static const float k_containerWidth;
static const float k_containerHeight;
static const float k_containerHalfWidth;
static const float k_containerHalfHeight;
static const float k_barrierHeight;
static const float k_barrierMovementIncrement;
static const float k_densityStep;
static const float k_densityMin;
static const float k_densityMax;
static const float k_densityDefault;
static const float k_temperatureStep;
static const float k_temperatureMin;
static const float k_temperatureMax;
static const float k_temperatureDefault;
};
const float Maxwell::k_containerWidth = 2.0f;
const float Maxwell::k_containerHeight = 4.0f;
const float Maxwell::k_containerHalfWidth =
Maxwell::k_containerWidth / 2.0f;
const float Maxwell::k_containerHalfHeight =
Maxwell::k_containerHeight / 2.0f;
const float Maxwell::k_barrierHeight =
Maxwell::k_containerHalfHeight / 100.0f;
const float Maxwell::k_barrierMovementIncrement =
Maxwell::k_containerHalfHeight * 0.1f;
const float Maxwell::k_densityStep = 1.25;
const float Maxwell::k_densityMin = 0.01f;
const float Maxwell::k_densityMax = 0.8f;
const float Maxwell::k_densityDefault = 0.25f;
const float Maxwell::k_temperatureStep = 0.2f;
const float Maxwell::k_temperatureMin = 0.4f;
const float Maxwell::k_temperatureMax = 10.0f;
const float Maxwell::k_temperatureDefault = 5.0f;
static int testIndex = RegisterTest("Particles", "Maxwell", Maxwell::Create);
| 26.946875 | 145 | 0.714137 | Hexlord |
bafd6e1299e4cb0aa407b83651decc6163ec81e2 | 7,341 | hpp | C++ | types/IntervalParser.hpp | Hacker0912/quickstep-datalog | 1de22e7ab787b5efa619861a167a097ff6a4f549 | [
"Apache-2.0"
] | 82 | 2016-04-18T03:59:06.000Z | 2019-02-04T11:46:08.000Z | types/IntervalParser.hpp | Hacker0912/quickstep-datalog | 1de22e7ab787b5efa619861a167a097ff6a4f549 | [
"Apache-2.0"
] | 265 | 2016-04-19T17:52:43.000Z | 2018-10-11T17:55:08.000Z | types/IntervalParser.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_TYPES_INTERVAL_PARSER_HPP_
#define QUICKSTEP_TYPES_INTERVAL_PARSER_HPP_
#include <cstdint>
#include <string>
#include "utility/Macros.hpp"
namespace quickstep {
struct DatetimeIntervalLit;
struct YearMonthIntervalLit;
/**
* @brief All-static utility class with methods for parsing INTERVAL values
* from string representations.
*
* INTERVAL literals can have two formats. The "simple" format is an integer
* followed by a string indicating units (e.g. "1 second", "2 days",
* "3 years"). The "complex" format is the same as that printed by
* DatetimeIntervalType::printValueToString() or
* YearMonthIntervalType::printValueToString() (e.g. "1 day 00:39:35.244090"
* for DatetimeInterval, or "2 years 1 mon" for YearMonthInterval).
**/
class IntervalParser {
public:
/**
* @brief Finish parsing a DatetimeIntervalLit from a simple format
* representation.
*
* @param count The numeric portion of the interval specification, already
* parsed as int64_t.
* @param units_lowercase A lowercase string representing the units that
* count should be interpreted as. Valid options are "microsecond",
* "millisecond", "second", "minute", "hour", "day", and "week", as
* well as plural forms and SI abbreviations.
* @param interval A pointer to a DatetimeIntervalLit which will be
* overwritten with the parsed DatetimeInterval value on success.
* @return true on success, false if units_lowercase was not valid.
**/
static bool ParseDatetimeIntervalSimpleFormat(const std::int64_t count,
const std::string &units_lowercase,
DatetimeIntervalLit *interval);
/**
* @brief Parse a DatetimeIntervalLit from a complex format representation.
*
* @param interval_string A description of a DatetimeInterval in complex
* format.
* @param interval A pointer to a DatetimeIntervalLit which will be
* overwritten with the parsed DatetimeInterval value on success.
* @return true on success, false if interval_string was not in valid format.
**/
static bool ParseDatetimeIntervalComplexFormat(const std::string &interval_string,
DatetimeIntervalLit *interval);
/**
* @brief Finish parsing a YearMonthIntervalLit from a simple format
* representation.
*
* @param count The numeric portion of the interval specification, already
* parsed as int64_t.
* @param units_lowercase A lowercase string representing the units that
* count should be interpreted as. Valid options are "month", "year",
* "decade", "century", and "millenium", as well as plural forms and
* SI abbreviations.
* @param interval A pointer to a YearMonthIntervalLit which will be
* overwritten with the parsed YearMonthInterval value on success.
* @return true on success, false if units_lowercase was not valid.
**/
static bool ParseYearMonthIntervalSimpleFormat(const std::int64_t count,
const std::string &units_lowercase,
YearMonthIntervalLit *interval);
/**
* @brief Parse a YearMonthIntervalLit from a complex format representation.
*
* @param interval_string A description of a YearMonthInterval in complex
* format.
* @param interval A pointer to a YearMonthIntervalLit which will be
* overwritten with the parsed YearMonthInterval value on success.
* @return true on success, false if interval_string was not in valid format.
**/
static bool ParseYearMonthIntervalComplexFormat(const std::string &interval_string,
YearMonthIntervalLit *interval);
/**
* @brief Extract the count and units fields from a combined string
* describing an interval.
*
* @param interval_string A single combined string describing an interval.
* Valid formats are all of the form "count units", and single quotes
* may appear around the entire string, just the count portion, or be
* omitted entirely. Note that quotes around the units only are NOT a
* valid format.
* @param count A pointer to an int64_t that will be overwritten with the
* parsed count portion of interval_string on success.
* @param units_lowercase A pointer to a string that will be overwritten with
* the units portion of interval_string, converted to lowercase, on
* success. Note that this method does not check that units_lowercase
* specifies a known unit.
* @return true on successful parse, false if interval_string was not in the
* expected format.
**/
static bool ParseSimpleFormatFieldsFromCombinedString(
const std::string &interval_string,
std::int64_t *count,
std::string *units_lowercase);
/**
* @brief A stricter version of ParseSimpleFormatFieldsFromCombinedString()
* that does not allow extra trailing whitespace, nor extra whitespace
* inside quotes.
*
* @param interval_string A single combined string describing an interval.
* Valid formats are all of the form "count units", and single quotes
* may appear around the entire string, just the count portion, or be
* omitted entirely. Note that quotes around the units only are NOT a
* valid format.
* @param count A pointer to an int64_t that will be overwritten with the
* parsed count portion of interval_string on success.
* @param units_lowercase A pointer to a string that will be overwritten with
* the units portion of interval_string, converted to lowercase, on
* success. Note that this method does not check that units_lowercase
* specifies a known unit.
* @return true on successful parse, false if interval_string was not in the
* expected format.
**/
static bool ParseSimpleFormatFieldsFromCombinedStringNoExtraWhitespace(
const std::string &interval_string,
std::int64_t *count,
std::string *units_lowercase);
private:
// Undefined default constructor. Class is all-static and should not be
// instantiated.
IntervalParser();
DISALLOW_COPY_AND_ASSIGN(IntervalParser);
};
} // namespace quickstep
#endif // QUICKSTEP_TYPES_INTERVAL_PARSER_HPP_
| 44.762195 | 85 | 0.690505 | Hacker0912 |
24001aec762f9bde541ba37c76e5da251fa3df71 | 2,196 | cpp | C++ | Wonderland/Wonderland/Editor/Modules/VulkanWrapper/Renderable/VWRenderable.cpp | RodrigoHolztrattner/Wonderland | ffb71d47c1725e7cd537e2d1380962b5dfdc3d75 | [
"MIT"
] | 3 | 2018-04-09T13:01:07.000Z | 2021-03-18T12:28:48.000Z | Wonderland/Wonderland/Editor/Modules/VulkanWrapper/Renderable/VWRenderable.cpp | RodrigoHolztrattner/Wonderland | ffb71d47c1725e7cd537e2d1380962b5dfdc3d75 | [
"MIT"
] | null | null | null | Wonderland/Wonderland/Editor/Modules/VulkanWrapper/Renderable/VWRenderable.cpp | RodrigoHolztrattner/Wonderland | ffb71d47c1725e7cd537e2d1380962b5dfdc3d75 | [
"MIT"
] | 1 | 2021-03-18T12:28:50.000Z | 2021-03-18T12:28:50.000Z | ////////////////////////////////////////////////////////////////////////////////
// Filename: FluxMyWrapper.cpp
////////////////////////////////////////////////////////////////////////////////
#include "VWRenderable.h"
#include "..\Context\VWContext.h"
#define GLM_FORCE_RADIANS
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <chrono>
VulkanWrapper::VWRenderable::VWRenderable()
{
// Set the initial data
m_UpdateTime = 0;
m_Position = glm::vec3(0, 0, 0);
m_Rotation = glm::vec3(0, 0, 0);
m_Scale = glm::vec3(1, 1, 1);
m_Alpha = 1.0f;
m_IsValid = false;
}
VulkanWrapper::VWRenderable::~VWRenderable()
{
}
bool VulkanWrapper::VWRenderable::Initialize(VWContext* _context)
{
// Get the model manager
VWModelManager* modelManager = _context->GetModelManager();
// Get the texture group manager
VWTextureGroupManager* textureGroupManager = _context->GetTextureGroupManager();
//
// Request our model object
modelManager->RequestObject(&GetModelReference(), "square");
// Get the texture group
textureGroupManager->RequestObject(&GetTextureGroupReference(), "textureGroupSky");
//
// Get our texture
m_DiffuseTexture.CreateWithTextureGroup(&GetTextureGroupReference(), "Ground");
// Set the texture parameter
SetTextureParameter("diffuseTexture", &m_DiffuseTexture);
return true;
}
bool VulkanWrapper::VWRenderable::IsValid()
{
// Fast check if we are valid
if (m_IsValid)
{
return true;
}
// Check if the texture group reference is valid
if (!IsResourceReferenceValid(GetTextureGroupReference()))
{
return false;
}
// Check if the model reference is valid
if (!IsResourceReferenceValid(GetModelReference()))
{
return false;
}
// Set that we are valid to be used
m_IsValid = true;
return true;
}
void VulkanWrapper::VWRenderable::Update(float _timeElapsed, bool _horizontal, bool _vertical, bool _depth)
{
// Increment the time elapsed
m_UpdateTime += _timeElapsed;
// Set the amount
float amount = 3;
// Set the position
m_Position = glm::vec3(std::cos(m_UpdateTime) * _horizontal * amount, std::sin(m_UpdateTime) * _vertical * amount, std::cos(m_UpdateTime) * std::sin(m_UpdateTime) * _depth * amount);
} | 24.131868 | 183 | 0.679872 | RodrigoHolztrattner |
2409a5957203e4bb6d2e3f1aaa021a5812b3b38f | 17,038 | cxx | C++ | Modules/Filtering/LabelMap/test/itkShapeLabelMapFilterGTest.cxx | Kronephon/itktest | a34e46226638c08bba315a257e33550a68203d97 | [
"Apache-2.0"
] | null | null | null | Modules/Filtering/LabelMap/test/itkShapeLabelMapFilterGTest.cxx | Kronephon/itktest | a34e46226638c08bba315a257e33550a68203d97 | [
"Apache-2.0"
] | null | null | null | Modules/Filtering/LabelMap/test/itkShapeLabelMapFilterGTest.cxx | Kronephon/itktest | a34e46226638c08bba315a257e33550a68203d97 | [
"Apache-2.0"
] | null | null | null | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 "itkGTest.h"
#include "itkImage.h"
#include "itkLabelImageToShapeLabelMapFilter.h"
namespace Math = itk::Math;
namespace
{
class ShapeLabelMapFixture
: public ::testing::Test
{
public:
ShapeLabelMapFixture() {}
~ShapeLabelMapFixture() override {}
protected:
void SetUp() override {}
void TearDown() override {}
template<unsigned int D, typename TPixelType = unsigned short>
struct FixtureUtilities
{
static const unsigned int Dimension = D;
using PixelType = TPixelType;
using ImageType = itk::Image<PixelType, Dimension>;
using LabelObjectType = itk::ShapeLabelObject<PixelType, Dimension>;
using ShapeLabelMapType = itk::LabelMap<LabelObjectType>;
static typename ImageType::Pointer CreateImage(void)
{
typename ImageType::Pointer image = ImageType::New();
typename ImageType::SizeType imageSize;
imageSize.Fill(25);
image->SetRegions(typename ImageType::RegionType(imageSize));
image->Allocate();
image->FillBuffer(0);
return image;
}
static typename LabelObjectType::ConstPointer ComputeLabelObject(const ImageType* image,
PixelType label = 1)
{
using L2SType = itk::LabelImageToShapeLabelMapFilter<ImageType>;
typename L2SType::Pointer l2s = L2SType::New();
l2s->SetInput( image );
l2s->ComputeFeretDiameterOn();
l2s->ComputePerimeterOn();
l2s->ComputeOrientedBoundingBoxOn();
l2s->Update();
return l2s->GetOutput()->GetLabelObject(label);
}
};
};
}
// The expected results were verified for these tests cases, unless
// the test is marked with the "resulting value" comment. In which
// case the baseline value was just what was computed by the method.
TEST_F(ShapeLabelMapFixture,3D_T1x1x1)
{
using namespace itk::GTest::TypedefsAndConstructors::Dimension3;
using Utils = FixtureUtilities<3>;
Utils::ImageType::Pointer image( Utils::CreateImage() );
image->SetPixel(MakeIndex(5,7,9), 1);
Utils::LabelObjectType::ConstPointer labelObject = Utils::ComputeLabelObject(image);
EXPECT_VECTOR_NEAR(MakeIndex(5,7,9), labelObject->GetBoundingBox().GetIndex(), 1e-99);
EXPECT_VECTOR_NEAR(MakeSize(1,1,1), labelObject->GetBoundingBox().GetSize(), 1e-99);
EXPECT_VECTOR_NEAR(MakePoint(5.0,7.0,9.0), labelObject->GetCentroid(), 1e-10);
EXPECT_EQ(0.0, labelObject->GetElongation());
EXPECT_VECTOR_NEAR(MakePoint(0.0,0.0,0.0), labelObject->GetEquivalentEllipsoidDiameter(), 1e-10);
EXPECT_NEAR(4.83598, labelObject->GetEquivalentSphericalPerimeter(), 1e-4); // resulting value
EXPECT_NEAR(0.62035, labelObject->GetEquivalentSphericalRadius(), 1e-4); // resulting value
EXPECT_EQ(0.0, labelObject->GetFeretDiameter());
EXPECT_EQ(0.0, labelObject->GetFlatness());
EXPECT_EQ(1u, labelObject->GetNumberOfPixels());
EXPECT_EQ(0u, labelObject->GetNumberOfPixelsOnBorder());
EXPECT_VECTOR_NEAR(MakeVector(1u,1u,1u), labelObject->GetOrientedBoundingBoxSize(), 1e-10);
EXPECT_VECTOR_NEAR(MakePoint(4.5,6.5,8.5), labelObject->GetOrientedBoundingBoxOrigin(), 1e-10);
EXPECT_NEAR(3.004, labelObject->GetPerimeter(), 1e-4); // resulting value
EXPECT_EQ(0.0, labelObject->GetPerimeterOnBorder());
EXPECT_EQ(0.0, labelObject->GetPerimeterOnBorderRatio());
EXPECT_EQ(1.0, labelObject->GetPhysicalSize());
// labelObject->GetPrincipalAxes(); degenerate case
EXPECT_EQ(MakeVector(0.0,0.0,0.0), labelObject->GetPrincipalMoments());
EXPECT_NEAR(1.6098, labelObject->GetRoundness(), 0.0001); // resulting value
EXPECT_EQ(labelObject->GetBoundingBox(), labelObject->GetRegion());
if (::testing::Test::HasFailure())
{
labelObject->Print(std::cout);
}
}
TEST_F(ShapeLabelMapFixture,3D_T3x2x1)
{
using namespace itk::GTest::TypedefsAndConstructors::Dimension3;
using Utils = FixtureUtilities<3>;
Utils::ImageType::Pointer image( Utils::CreateImage() );
for (unsigned int i = 5; i < 8; ++i)
{
image->SetPixel(MakeIndex(i,9,11), 1);
image->SetPixel(MakeIndex(i,10,11), 1);
}
Utils::LabelObjectType::ConstPointer labelObject = Utils::ComputeLabelObject(image);
EXPECT_VECTOR_NEAR(MakeIndex(5,9,11), labelObject->GetBoundingBox().GetIndex(), 1e-99);
EXPECT_VECTOR_NEAR(MakeSize(3,2,1), labelObject->GetBoundingBox().GetSize(), 1e-99);
EXPECT_EQ(MakePoint(6,9.5,11.0), labelObject->GetCentroid());
EXPECT_NEAR(1.63299, labelObject->GetElongation(), 1e-4);
EXPECT_VECTOR_NEAR(MakePoint(0.0,0.0,0.0), labelObject->GetEquivalentEllipsoidDiameter(), 1e-10);
EXPECT_NEAR(15.96804, labelObject->GetEquivalentSphericalPerimeter(), 1e-4); // resulting value
EXPECT_NEAR(1.12725, labelObject->GetEquivalentSphericalRadius(), 1e-4); // resulting value
EXPECT_NEAR(2.23606, labelObject->GetFeretDiameter(), 1e-4);
EXPECT_EQ(0.0, labelObject->GetFlatness());
EXPECT_EQ(6u, labelObject->GetNumberOfPixels());
EXPECT_EQ(0u, labelObject->GetNumberOfPixelsOnBorder());
EXPECT_VECTOR_NEAR(MakeVector(1u,2u,3u), labelObject->GetOrientedBoundingBoxSize(),1e-10);
EXPECT_VECTOR_NEAR(MakePoint(7.5, 8.5, 10.5), labelObject->GetOrientedBoundingBoxOrigin(), 1e-10);
EXPECT_NEAR(14.62414, labelObject->GetPerimeter(), 1e-4); // resulting value
EXPECT_EQ(0.0, labelObject->GetPerimeterOnBorder());
EXPECT_EQ(0.0, labelObject->GetPerimeterOnBorderRatio());
EXPECT_EQ(6.0, labelObject->GetPhysicalSize());
// labelObject->GetPrincipalAxes(); omitted
EXPECT_VECTOR_NEAR(MakeVector(0, 0.25, 0.666667), labelObject->GetPrincipalMoments(),1e-4);
EXPECT_NEAR(1.09189, labelObject->GetRoundness(), 1e-4); // resulting value
EXPECT_EQ(labelObject->GetBoundingBox(), labelObject->GetRegion());
if (::testing::Test::HasFailure())
{
labelObject->Print(std::cout);
}
}
TEST_F(ShapeLabelMapFixture,3D_T3x2x1_Direction)
{
using namespace itk::GTest::TypedefsAndConstructors::Dimension3;
using Utils = FixtureUtilities<3>;
Utils::ImageType::Pointer image( Utils::CreateImage() );
for (unsigned int i = 5; i < 8; ++i)
{
image->SetPixel(MakeIndex(i,9,11), 1);
image->SetPixel(MakeIndex(i,10,11), 1);
}
DirectionType direction;
const double d[9] = {0.7950707161543119, -0.44533237368675166, 0.41175433605536305,
-0.6065167008084678, -0.5840224148057925, 0.5394954222649374,
0.00021898465942798317, -0.6786728931900383, -0.7344406416415056};
direction = DirectionType::InternalMatrixType(d);
image->SetDirection(direction);
Utils::LabelObjectType::ConstPointer labelObject = Utils::ComputeLabelObject(image);
EXPECT_VECTOR_NEAR(MakeIndex(5,9,11), labelObject->GetBoundingBox().GetIndex(), 1e-99);
EXPECT_VECTOR_NEAR(MakeSize(3,2,1), labelObject->GetBoundingBox().GetSize(), 1e-99);
EXPECT_VECTOR_NEAR(MakePoint(5.06906, -3.25286, -14.5249), labelObject->GetCentroid(), 1e-4);
EXPECT_NEAR(1.63299, labelObject->GetElongation(), 1e-4);
//EXPECT_VECTOR_NEAR(MakePoint(0.0,0.0,0.0), labelObject->GetEquivalentEllipsoidDiameter(), 1e-10);
EXPECT_NEAR(15.96804, labelObject->GetEquivalentSphericalPerimeter(), 1e-4); // resulting value
EXPECT_NEAR(1.12725, labelObject->GetEquivalentSphericalRadius(), 1e-4); // resulting value
EXPECT_NEAR(2.23606, labelObject->GetFeretDiameter(), 1e-4);
//EXPECT_EQ(0.0, labelObject->GetFlatness()); unstable due to division near zero
EXPECT_EQ(6u, labelObject->GetNumberOfPixels());
EXPECT_EQ(0u, labelObject->GetNumberOfPixelsOnBorder());
EXPECT_VECTOR_NEAR(MakeVector(1u,2u,3u), labelObject->GetOrientedBoundingBoxSize(),1e-10);
EXPECT_VECTOR_NEAR(MakePoint(3.22524, -3.19685, -14.83670), labelObject->GetOrientedBoundingBoxOrigin(), 1e-4);
EXPECT_NEAR(14.62414, labelObject->GetPerimeter(), 1e-4); // resulting value
EXPECT_EQ(0.0, labelObject->GetPerimeterOnBorder());
EXPECT_EQ(0.0, labelObject->GetPerimeterOnBorderRatio());
EXPECT_EQ(6.0, labelObject->GetPhysicalSize());
//labelObject->GetPrincipalAxes(); omitted
EXPECT_VECTOR_NEAR(MakeVector(0, 0.25, 0.666667), labelObject->GetPrincipalMoments(),1e-4);
EXPECT_NEAR(1.09189, labelObject->GetRoundness(), 1e-4); // resulting value
if (::testing::Test::HasFailure())
{
labelObject->Print(std::cout);
}
}
TEST_F(ShapeLabelMapFixture,3D_T2x2x2_Spacing)
{
using namespace itk::GTest::TypedefsAndConstructors::Dimension3;
using Utils = FixtureUtilities<3>;
Utils::ImageType::Pointer image( Utils::CreateImage() );
for (unsigned int i = 0; i < 2; ++i)
{
for (unsigned int j = 0; j < 2; ++j)
{
image->SetPixel(MakeIndex(5+j,9+i,11), 1);
image->SetPixel(MakeIndex(5+j,9+i,12), 1);
}
}
image->SetSpacing(MakeVector(1.0,1.1,2.2));
Utils::LabelObjectType::ConstPointer labelObject = Utils::ComputeLabelObject(image);
EXPECT_VECTOR_NEAR(MakeIndex(5,9,11), labelObject->GetBoundingBox().GetIndex(), 1e-99);
EXPECT_VECTOR_NEAR(MakeSize(2,2,2), labelObject->GetBoundingBox().GetSize(), 1e-99);
EXPECT_VECTOR_NEAR(MakePoint(5.5, 10.45, 25.3), labelObject->GetCentroid(), 1e-4);
EXPECT_NEAR(2.0, labelObject->GetElongation(), 1e-4);
EXPECT_VECTOR_NEAR(MakePoint(2.4814, 2.72954, 5.45908), labelObject->GetEquivalentEllipsoidDiameter(), 1e-4); // resulting value
EXPECT_NEAR(34.86751, labelObject->GetEquivalentSphericalPerimeter(), 1e-4); // resulting value
EXPECT_NEAR(1.66573, labelObject->GetEquivalentSphericalRadius(), 1e-4); // resulting value
EXPECT_NEAR(2.65518, labelObject->GetFeretDiameter(), 1e-4);
EXPECT_NEAR(1.1, labelObject->GetFlatness(), 1e-4);
EXPECT_EQ(8u, labelObject->GetNumberOfPixels());
EXPECT_EQ(0u, labelObject->GetNumberOfPixelsOnBorder());
EXPECT_VECTOR_NEAR(MakeVector(2, 2.2, 4.4), labelObject->GetOrientedBoundingBoxSize(),1e-10);
EXPECT_NEAR(28.3919, labelObject->GetPerimeter(), 1e-4); // resulting value
EXPECT_EQ(0.0, labelObject->GetPerimeterOnBorder());
EXPECT_EQ(0.0, labelObject->GetPerimeterOnBorderRatio());
EXPECT_NEAR(19.36, labelObject->GetPhysicalSize(), 1e-10);
// We are omitted these because the sign of the eigen vectors is not
//unique, therefore the axes may not always point in the same
//direction and the origin may not be the same corner
//EXPECT_VECTOR_NEAR(MakePoint(4.5, 9.35, 23.1), labelObject->GetOrientedBoundingBoxOrigin(), 1e-4);
//labelObject->GetPrincipalAxes(); omitted
EXPECT_VECTOR_NEAR(MakeVector(0.25, 0.3025, 1.21), labelObject->GetPrincipalMoments(),1e-4);
EXPECT_NEAR( 1.22808, labelObject->GetRoundness(), 1e-4); // resulting value
if (::testing::Test::HasFailure())
{
labelObject->Print(std::cout);
}
}
TEST_F(ShapeLabelMapFixture,3D_T2x2x2_Spacing_Direction)
{
using namespace itk::GTest::TypedefsAndConstructors::Dimension3;
using Utils = FixtureUtilities<3>;
Utils::ImageType::Pointer image( Utils::CreateImage() );
DirectionType direction;
const double d[9] = {0.7950707161543119, -0.44533237368675166, 0.41175433605536305,
-0.6065167008084678, -0.5840224148057925, 0.5394954222649374,
0.00021898465942798317, -0.6786728931900383, -0.7344406416415056};
direction = DirectionType::InternalMatrixType(d);
image->SetDirection(direction);
for (unsigned int i = 0; i < 2; ++i)
{
for (unsigned int j = 0; j < 2; ++j)
{
image->SetPixel(MakeIndex(5+j,9+i,11), 1);
image->SetPixel(MakeIndex(5+j,9+i,12), 1);
}
}
image->SetSpacing(MakeVector(1.0,1.1,2.2));
Utils::LabelObjectType::ConstPointer labelObject = Utils::ComputeLabelObject(image);
EXPECT_VECTOR_NEAR(MakeIndex(5,9,11), labelObject->GetBoundingBox().GetIndex(), 1e-99);
EXPECT_VECTOR_NEAR(MakeSize(2,2,2), labelObject->GetBoundingBox().GetSize(), 1e-99);
EXPECT_VECTOR_NEAR(MakePoint(10.13655, 4.21035, -25.67227), labelObject->GetCentroid(), 1e-4); // resulting value
EXPECT_NEAR(2.0, labelObject->GetElongation(), 1e-4);
EXPECT_VECTOR_NEAR(MakePoint(2.4814, 2.72954, 5.45908), labelObject->GetEquivalentEllipsoidDiameter(), 1e-4); // resulting value
EXPECT_NEAR(34.86751, labelObject->GetEquivalentSphericalPerimeter(), 1e-4); // resulting value
EXPECT_NEAR(1.66573, labelObject->GetEquivalentSphericalRadius(), 1e-4); // resulting value
EXPECT_NEAR(2.65518, labelObject->GetFeretDiameter(), 1e-4);
EXPECT_NEAR(1.1, labelObject->GetFlatness(), 1e-4);
EXPECT_EQ(8u, labelObject->GetNumberOfPixels());
EXPECT_EQ(0u, labelObject->GetNumberOfPixelsOnBorder());
EXPECT_VECTOR_NEAR(MakeVector(2, 2.2, 4.4), labelObject->GetOrientedBoundingBoxSize(),1e-10);
EXPECT_VECTOR_NEAR(MakePoint(8.92548, 4.27240, -23.31018), labelObject->GetOrientedBoundingBoxOrigin(), 1e-4); // resulting value
EXPECT_NEAR(28.3919, labelObject->GetPerimeter(), 1e-4); // resulting value
EXPECT_EQ(0.0, labelObject->GetPerimeterOnBorder());
EXPECT_EQ(0.0, labelObject->GetPerimeterOnBorderRatio());
EXPECT_NEAR(19.36, labelObject->GetPhysicalSize(), 1e-10);
//labelObject->GetPrincipalAxes(); omitted
EXPECT_VECTOR_NEAR(MakeVector(0.25, 0.3025, 1.21), labelObject->GetPrincipalMoments(),1e-4);
EXPECT_NEAR( 1.22808, labelObject->GetRoundness(), 1e-4); // resulting value
if (::testing::Test::HasFailure())
{
labelObject->Print(std::cout);
}
}
TEST_F(ShapeLabelMapFixture,2D_T1x1)
{
using namespace itk::GTest::TypedefsAndConstructors::Dimension2;
using Utils = FixtureUtilities<2>;
Utils::ImageType::Pointer image( Utils::CreateImage() );
image->SetPixel(MakeIndex(5,7), 1);
Utils::LabelObjectType::ConstPointer labelObject = Utils::ComputeLabelObject(image);
EXPECT_VECTOR_NEAR(MakeVector(1.0,1.0), labelObject->GetOrientedBoundingBoxSize(),1e-10);
EXPECT_VECTOR_NEAR(MakePoint(4.5, 6.5), labelObject->GetOrientedBoundingBoxOrigin(), 1e-4);
if (::testing::Test::HasFailure())
{
labelObject->Print(std::cout);
}
}
TEST_F(ShapeLabelMapFixture,2D_T1_1)
{
using namespace itk::GTest::TypedefsAndConstructors::Dimension2;
using Utils = FixtureUtilities<2>;
Utils::ImageType::Pointer image( Utils::CreateImage() );
image->SetPixel(MakeIndex(5,7), 1);
image->SetPixel(MakeIndex(6,8), 1);
Utils::LabelObjectType::ConstPointer labelObject = Utils::ComputeLabelObject(image);
EXPECT_VECTOR_NEAR(MakeSize(2,2), labelObject->GetBoundingBox().GetSize(), 1e-99);
EXPECT_VECTOR_NEAR(MakeVector(Math::sqrt2, 2.0*Math::sqrt2), labelObject->GetOrientedBoundingBoxSize(),1e-4);
EXPECT_VECTOR_NEAR(MakePoint(4.0, 7.0), labelObject->GetOrientedBoundingBoxOrigin(), 1e-4);
if (::testing::Test::HasFailure())
{
labelObject->Print(std::cout);
}
}
TEST_F(ShapeLabelMapFixture,2D_T1_1_FlipDirection)
{
using namespace itk::GTest::TypedefsAndConstructors::Dimension2;
using Utils = FixtureUtilities<2>;
Utils::ImageType::Pointer image( Utils::CreateImage() );
image->SetPixel(MakeIndex(5,7), 1);
image->SetPixel(MakeIndex(6,8), 1);
DirectionType direction;
const double d[4] = {0,1.0,
1.0, 0};
direction = DirectionType::InternalMatrixType(d);
image->SetDirection(direction);
Utils::LabelObjectType::ConstPointer labelObject = Utils::ComputeLabelObject(image);
EXPECT_VECTOR_NEAR(MakeVector(Math::sqrt2, 2.0*Math::sqrt2), labelObject->GetOrientedBoundingBoxSize(),1e-4);
EXPECT_VECTOR_NEAR(MakePoint(6.0, 5.0), labelObject->GetOrientedBoundingBoxOrigin(), 1e-4);
if (::testing::Test::HasFailure())
{
labelObject->Print(std::cout);
}
}
TEST_F(ShapeLabelMapFixture,2D_T2x4)
{
using namespace itk::GTest::TypedefsAndConstructors::Dimension2;
using Utils = FixtureUtilities<2>;
Utils::ImageType::Pointer image( Utils::CreateImage() );
for (unsigned int i = 4; i < 6; ++i)
{
for (unsigned int j = 3; j < 7; ++j)
{
image->SetPixel(MakeIndex(i,j), 1);
}
}
Utils::LabelObjectType::ConstPointer labelObject = Utils::ComputeLabelObject(image);
EXPECT_VECTOR_NEAR(MakeVector(2.0,4.0), labelObject->GetOrientedBoundingBoxSize(),1e-10);
EXPECT_VECTOR_NEAR(MakePoint(3.5, 2.5), labelObject->GetOrientedBoundingBoxOrigin(), 1e-4);
if (::testing::Test::HasFailure())
{
labelObject->Print(std::cout);
}
}
| 37.528634 | 131 | 0.71276 | Kronephon |
240b8e6fcc249e9d7c79b9ebc01e0dcef1f26730 | 2,135 | cpp | C++ | source/aufgabe2bis4.cpp | philbranding/programmiersprachen-aufgabenblatt-3 | d8b8426fa290ab5ae048749ca11982454e031a2b | [
"MIT"
] | null | null | null | source/aufgabe2bis4.cpp | philbranding/programmiersprachen-aufgabenblatt-3 | d8b8426fa290ab5ae048749ca11982454e031a2b | [
"MIT"
] | null | null | null | source/aufgabe2bis4.cpp | philbranding/programmiersprachen-aufgabenblatt-3 | d8b8426fa290ab5ae048749ca11982454e031a2b | [
"MIT"
] | null | null | null | # include <cstdlib> //std::rand()
# include <vector> //std::vector<>
# include <list> //std::list<>
# include <iostream> //std::cout
# include <iterator> //std::ostream_iterator<>
# include <algorithm> //std::reverse, std::generate
# include <set>
# include <map>
int main(){
std::list<unsigned int> mylist(100); // creating a new list called l1 with the same size as the v0
for (auto& i : mylist){ // an iteration that starts refering to the beginning of the v0 Vector
i = std::rand() % 101; // placing random numbers into the 10 places that we have created v0-v9
}
std::vector<unsigned int> myVector(mylist.size());
std::copy(std::begin(mylist),
std::end(mylist),
std::begin(myVector));
//using set to get the different numbers from 1 to 100
std::cout <<" " <<std::endl;
std::cout <<" -------------------------------------Aufgabe 3.3 Set-----------------------------------------" <<std::endl;
std::set<unsigned int> setlist(std::begin(mylist), std::end(mylist));
for (auto& i : setlist){
setlist.insert(i);
std::cout<< i <<" ";
}
std::cout <<" " <<std::endl;
std::cout <<"There are : " << setlist.size() << " different numbers in the List" <<std::endl;
std::cout <<" " <<std::endl;
//using set to get the missing number by checking with a counter
std::cout <<" ----------------------3.3 Zahlen von 0 bis 100 die nicht in der Liste sind--------------------" <<std::endl;
for(unsigned int missingNumber = 0; missingNumber <= setlist.size(); missingNumber++){
if(setlist.find(missingNumber) == setlist.end()){
std::cout<< missingNumber <<" ";
}
}
std::cout <<" " <<std::endl;
std::cout <<" " <<std::endl;
//using map to count the number of repeated Number from 1 to 100 in our List using an iterator counter
std::cout <<" ----------------------3.4 Häufigkeit jeder Zahl nicht in der Liste--------------------" <<std::endl;
std::map<unsigned int, unsigned int>listMap;
for (auto& i : mylist){
listMap[i]++;
}
for (auto& i : listMap){
std::cout<< i.first<<" => : "<< i.second <<std::endl;
}
return 0;
} | 28.851351 | 122 | 0.573302 | philbranding |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.