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
108
| 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
67k
⌀ | 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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7fe64908148936a470b6d209a967c22820589f1d
| 295
|
cpp
|
C++
|
Week 1 May 1st to May 7th/numberComplement.cpp
|
huynhtruc0309/May-LeetCoding-Challenge
|
958de292527ff15502af495c695d17f10eedd697
|
[
"MIT"
] | 16
|
2020-05-06T14:56:33.000Z
|
2020-05-10T17:32:16.000Z
|
Week 1 May 1st to May 7th/numberComplement.cpp
|
huynhtruc0309/May-LeetCoding-Challenge
|
958de292527ff15502af495c695d17f10eedd697
|
[
"MIT"
] | null | null | null |
Week 1 May 1st to May 7th/numberComplement.cpp
|
huynhtruc0309/May-LeetCoding-Challenge
|
958de292527ff15502af495c695d17f10eedd697
|
[
"MIT"
] | 1
|
2020-05-17T09:31:30.000Z
|
2020-05-17T09:31:30.000Z
|
class Solution {
public:
int findComplement(int num) {
int result = 0;
int i = 0;
while(num) {
if ((num & 1) == 0)
result += 1 << i;
i += 1;
num >>= 1;
}
return result;
}
};
| 18.4375
| 33
| 0.332203
|
huynhtruc0309
|
7fe83cf4a5a5e11cc25f6f00a35ed1ff91d73d6f
| 2,680
|
cpp
|
C++
|
TestFramework/RIMStageWebViewTestSuite.cpp
|
blackberry/Ripple-Framework
|
c3126aa0669068f5ee102b65231fdaebdcdfa9ff
|
[
"Apache-2.0"
] | 1
|
2015-04-17T04:48:56.000Z
|
2015-04-17T04:48:56.000Z
|
TestFramework/RIMStageWebViewTestSuite.cpp
|
blackberry-webworks/Ripple-Framework
|
c3126aa0669068f5ee102b65231fdaebdcdfa9ff
|
[
"Apache-2.0"
] | 4
|
2016-04-22T13:37:33.000Z
|
2016-04-22T13:37:56.000Z
|
TestFramework/RIMStageWebViewTestSuite.cpp
|
blackberry-webworks/Ripple-Framework
|
c3126aa0669068f5ee102b65231fdaebdcdfa9ff
|
[
"Apache-2.0"
] | 2
|
2019-02-15T19:14:52.000Z
|
2020-08-06T01:42:03.000Z
|
/*
* Copyright 2010-2011 Research In Motion Limited.
*
* 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 "RIMStageWebViewTestSuite.h"
RIMStageWebViewTestSuite::RIMStageWebViewTestSuite(QObject *parent) {
}
RIMStageWebViewTestSuite::~RIMStageWebViewTestSuite(void) {
}
void RIMStageWebViewTestSuite::initTestCase() {
qDebug("RIMStageWebViewTestSuite Init Test Case");
}
void RIMStageWebViewTestSuite::cleanupTestCase() {
qDebug("RIMStageWebViewTestSuite Cleanup Test Case");
}
void RIMStageWebViewTestSuite::init() {
_pageLoaded = false;
_pageLoadedSignal = false;
QSize size(360,480);
_webView = new RIMStageWebView(size);
}
void RIMStageWebViewTestSuite::cleanup() {
delete _webView;
}
void RIMStageWebViewTestSuite::loadURLTest() {
//_webView needs a QT container to show, so this test case did not go through <stu:06/03/2011>
//TODO: create a QMainWindow ...
QString site = "http://www.google.com";
qDebug("loading http://www.google.com");
connect(_webView, SIGNAL(loadFinished()), this, SLOT(loadedWebView()));
_webView->loadURL(site);
int i = 0;
// Wait for the signal or 10s
while (!_pageLoadedSignal && i++ < 50) {
QTest::qWait(200);
};
if (!_pageLoaded)
QFAIL("No Page was loaded");
}
void RIMStageWebViewTestSuite::crossOriginTest() {
if ( _pageLoaded )
{
qDebug("enabling crossSiteXHR");
_webView->enableCrossSiteXHR(true);
qDebug("disabling crossSiteXHR");
_webView->enableCrossSiteXHR(false);
}
}
void RIMStageWebViewTestSuite::executeJavaScriptTest() {
qDebug("Attempting to execute javascript");
int result = _webView->executeJavaScript("a=3+4").toInt();
QVERIFY(result == 7);
}
void RIMStageWebViewTestSuite::setGeometryTest()
{
QRect original = _webView->geometry();
int x = 100, y = 100, w = original.width(), h = original.height();
_webView->setGeometry(x,y,w,h);
QRect newpos = _webView->geometry();
QVERIFY( x == newpos.x());
QVERIFY( y == newpos.y());
}
void RIMStageWebViewTestSuite::loadedWebView() {
_pageLoadedSignal = true;
_pageLoaded = true;
}
| 27.346939
| 97
| 0.698507
|
blackberry
|
7fe9238a5801d5137269ec4ac4116aadd933975b
| 2,708
|
hxx
|
C++
|
opencascade/BRepGProp_Sinert.hxx
|
valgur/OCP
|
2f7d9da73a08e4ffe80883614aedacb27351134f
|
[
"Apache-2.0"
] | 117
|
2020-03-07T12:07:05.000Z
|
2022-03-27T07:35:22.000Z
|
opencascade/BRepGProp_Sinert.hxx
|
CadQuery/cpp-py-bindgen
|
66e7376d3a27444393fc99acbdbef40bbc7031ae
|
[
"Apache-2.0"
] | 66
|
2019-12-20T16:07:36.000Z
|
2022-03-15T21:56:10.000Z
|
opencascade/BRepGProp_Sinert.hxx
|
CadQuery/cpp-py-bindgen
|
66e7376d3a27444393fc99acbdbef40bbc7031ae
|
[
"Apache-2.0"
] | 76
|
2020-03-16T01:47:46.000Z
|
2022-03-21T16:37:07.000Z
|
// Created on: 1991-04-12
// Created by: Michel CHAUVAT
// Copyright (c) 1991-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _BRepGProp_Sinert_HeaderFile
#define _BRepGProp_Sinert_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Standard_Real.hxx>
#include <GProp_GProps.hxx>
class BRepGProp_Face;
class gp_Pnt;
class BRepGProp_Domain;
//! Computes the global properties of a face in 3D space.
//! The face 's requirements to evaluate the global properties
//! are defined in the template FaceTool from package GProp.
class BRepGProp_Sinert : public GProp_GProps
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT BRepGProp_Sinert();
Standard_EXPORT BRepGProp_Sinert(const BRepGProp_Face& S, const gp_Pnt& SLocation);
//! Builds a Sinert to evaluate the global properties of
//! the face <S>. If isNaturalRestriction is true the domain of S is defined
//! with the natural bounds, else it defined with an iterator
//! of Edge from TopoDS (see DomainTool from GProp)
Standard_EXPORT BRepGProp_Sinert(BRepGProp_Face& S, BRepGProp_Domain& D, const gp_Pnt& SLocation);
Standard_EXPORT BRepGProp_Sinert(BRepGProp_Face& S, const gp_Pnt& SLocation, const Standard_Real Eps);
Standard_EXPORT BRepGProp_Sinert(BRepGProp_Face& S, BRepGProp_Domain& D, const gp_Pnt& SLocation, const Standard_Real Eps);
Standard_EXPORT void SetLocation (const gp_Pnt& SLocation);
Standard_EXPORT void Perform (const BRepGProp_Face& S);
Standard_EXPORT void Perform (BRepGProp_Face& S, BRepGProp_Domain& D);
Standard_EXPORT Standard_Real Perform (BRepGProp_Face& S, const Standard_Real Eps);
Standard_EXPORT Standard_Real Perform (BRepGProp_Face& S, BRepGProp_Domain& D, const Standard_Real Eps);
//! If previously used method contained Eps parameter
//! get actual relative error of the computation, else return 1.0.
Standard_EXPORT Standard_Real GetEpsilon();
protected:
private:
Standard_Real myEpsilon;
};
#endif // _BRepGProp_Sinert_HeaderFile
| 27.917526
| 125
| 0.772157
|
valgur
|
7fea0a7772e523c1b08eb7d4330533cfc1d042f6
| 3,563
|
cpp
|
C++
|
PJDL/SimpleToken.cpp
|
szopeno/skeleton-parser-civetweb
|
440d684675e4446d8e4fea5e333452b36f33614c
|
[
"MIT"
] | null | null | null |
PJDL/SimpleToken.cpp
|
szopeno/skeleton-parser-civetweb
|
440d684675e4446d8e4fea5e333452b36f33614c
|
[
"MIT"
] | null | null | null |
PJDL/SimpleToken.cpp
|
szopeno/skeleton-parser-civetweb
|
440d684675e4446d8e4fea5e333452b36f33614c
|
[
"MIT"
] | null | null | null |
#include "SimpleToken.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
SimpleToken::SimpleToken() : indent(-1), _level(0), isInt(false)
{
value[0] = 0;
numValue = 0;
}
//const char *const str ?
SimpleToken::SimpleToken(const char str[])
{
int i;
//long *dst = (long *)value,*src = (long *) str;
for (i=0;str[i];i++)
value[i]=str[i];
value[i]=0;
/*
for (i=0;i<(MAX_LITERAL_SIZE/(sizeof(long)));i++)
{
dst[i]=src[i];
}
dst[i]=0;
*/
numValue = 0;
}
SimpleToken *SimpleToken::createKey(char const val[])
{
SimpleToken *t = new SimpleToken(val);
t->basicTokenType = T_KEY;
return t;
}
SimpleToken *SimpleToken::createString(char const val[])
{
SimpleToken *t = new SimpleToken(val);
t->basicTokenType = T_STRING;
return t;
}
SimpleToken *SimpleToken::createAttrib(char const val[])
{
SimpleToken *t = new SimpleToken(val);
t->basicTokenType = T_ATTRIB;
return t;
}
SimpleToken *SimpleToken::createVar(char const val[])
{
SimpleToken *t = new SimpleToken(val);
t->basicTokenType = T_VAR;
return t;
}
SimpleToken *SimpleToken::createNumber(char const val[], bool isInt)
{
SimpleToken *t = new SimpleToken();
t->basicTokenType = T_NUMBER;
t->numValue = strtold(val,0);
t->isInt = isInt;
snprintf(t->value, MAX_LITERAL_SIZE-1, "%.8lf", t->numValue);
return t;
}
SimpleToken *SimpleToken::createOper(const char val)
{
SimpleToken *t = new SimpleToken();
t->value[0] = val;
t->value[1] = 0;
t->basicTokenType = T_OPER;
return t;
}
SimpleToken *SimpleToken::createEOF()
{
SimpleToken *t = new SimpleToken();
t->value[0] = 4;
t->value[1] = 0;
t->basicTokenType = T_EOF;
return t;
}
std::string SimpleToken::toString() const
{
switch ( basicTokenType ) {
case T_OPER:
return std::string("operator<")+std::string(value)+std::string(">");
case T_KEY:
return std::string("keyword<")+std::string(value)+std::string(">");
case T_STRING:
return std::string("string<")+std::string(value)+std::string(">");
case T_NUMBER:
return std::string("number<")+std::string(value)+std::string(">");
case T_ATTRIB:
return std::string("attrib<")+std::string(value)+std::string(">");
case T_VAR:
return std::string("var<")+std::string(value)+std::string(">");
case T_EOF:
return std::string("eof<")+std::string(value)+std::string(">");
}
return std::string("unknown<")+std::string(value)+std::string(">");
}
std::string SimpleToken::stringValue() const
{
return std::string(value);
}
void SimpleToken::setString( std::string val)
{
strncpy( value, val.c_str(), MAX_LITERAL_SIZE);
}
void SimpleToken::setNumber(double n)
{
numValue = n;
snprintf(value, MAX_LITERAL_SIZE-1, "%.8lf", numValue);
}
std::string SimpleToken::fieldsStr() const
{
char tmpi[32], tmpl[32], tmpf[32],tmpp[32];
snprintf(tmpi,32,"%d", indent);
snprintf(tmpl,32,"%d", _level);
snprintf(tmpf,32,"%d", fileLine);
snprintf(tmpp,32,"%d", filePos);
return std::string("[ ") + std::string(source) + std::string(" ") + \
std::string( tmpf) + std::string( ":" ) + std::string( tmpi ) + \
std::string( " (") + std::string( tmpp ) + std::string(") ") + \
std::string( "" ) + std::string( first?"true ":"false ") + \
std::string( "L: ") + std::string( tmpl ) + std::string(" ]");
}
| 25.633094
| 80
| 0.588549
|
szopeno
|
7ff3641a9471cf5c90711469cde3e63d53daed85
| 11,978
|
hpp
|
C++
|
src/protocol.hpp
|
Fingercomp/oc-vremote
|
db93fd9c246e52b9a7fbcac41ef703135f3d4b10
|
[
"Apache-2.0"
] | null | null | null |
src/protocol.hpp
|
Fingercomp/oc-vremote
|
db93fd9c246e52b9a7fbcac41ef703135f3d4b10
|
[
"Apache-2.0"
] | null | null | null |
src/protocol.hpp
|
Fingercomp/oc-vremote
|
db93fd9c246e52b9a7fbcac41ef703135f3d4b10
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include <sstream>
#include <string>
#include <vector>
#include "util.hpp"
// We're using uint32_t as uint24_t:
// 32-bit integers has the long type
using uint24_t = uint32_t;
enum NetMessageCode {
MSG_ERROR, // = 0
MSG_AUTH_CLIENT, // = 1
MSG_AUTH_SERVER, // = 2
MSG_INITIAL_DATA, // = 3
MSG_SET_BG, // = 4
MSG_SET_FG, // = 5
MSG_SET_PALETTE, // = 6
MSG_SET_RESOLUTION, // = 7
MSG_SET_CHARS, // = 8
MSG_COPY, // = 9
MSG_FILL, // = 10
MSG_TURN_ON_OFF, // = 11
MSG_SET_PRECISE, // = 12
MSG_FETCH, // = 13
MSG_EVENT_TOUCH, // = 14
MSG_EVENT_DRAG, // = 15
MSG_EVENT_DROP, // = 16
MSG_EVENT_SCROLL, // = 17
MSG_EVENT_KEY_DOWN, // = 18
MSG_EVENT_KEY_UP, // = 19
MSG_EVENT_CLIPBOARD, // = 20
MSG_PING, // = 21
MSG_PONG // = 22
};
enum class ConnectionMode {
GpuKbd, // = 0
Gpu, // = 1
Kbd, // = 2
Custom // = 3
};
enum class AuthResult {
Authenticated, // = 0
WrongCredentials, // = 1
UnsupportedMode // = 2
};
struct Resolution {
uint8_t w;
uint8_t h;
};
struct Char {
long c;
uint8_t fg;
uint8_t bg;
};
struct NetMessage {
virtual NetMessageCode code() const = 0;
};
namespace nmsg {
struct NetMessageError: public NetMessage {
virtual NetMessageCode code() const {
return MSG_ERROR;
}
std::string description;
};
struct NetMessageAuthClient: public NetMessage {
virtual NetMessageCode code() const {
return MSG_AUTH_CLIENT;
}
std::string user;
std::string password;
ConnectionMode connectionMode;
uint16_t pingInterval;
};
struct NetMessageAuthServer: public NetMessage {
virtual NetMessageCode code() const {
return MSG_AUTH_SERVER;
}
AuthResult result;
std::string displayString;
};
struct NetMessageInitialData: public NetMessage {
virtual NetMessageCode code() const {
return MSG_INITIAL_DATA;
}
Palette palette;
uint8_t fg;
uint8_t bg;
Resolution resolution;
bool screenState;
bool preciseMode;
std::vector<Char> chars;
};
struct NetMessageSetBG: public NetMessage {
virtual NetMessageCode code() const {
return MSG_SET_BG;
}
uint8_t index;
};
struct NetMessageSetFG: public NetMessage {
virtual NetMessageCode code() const {
return MSG_SET_FG;
}
uint8_t index;
};
struct NetMessageSetPalette: public NetMessage {
virtual NetMessageCode code() const {
return MSG_SET_PALETTE;
}
Color color;
uint8_t index;
};
struct NetMessageSetResolution: public NetMessage {
virtual NetMessageCode code() const {
return MSG_SET_RESOLUTION;
}
uint8_t w;
uint8_t h;
};
struct NetMessageSetChars: public NetMessage {
virtual NetMessageCode code() const {
return MSG_SET_CHARS;
}
uint8_t x;
uint8_t y;
std::string chars;
bool vertical;
};
struct NetMessageCopy: public NetMessage {
virtual NetMessageCode code() const {
return MSG_COPY;
}
uint8_t x;
uint8_t y;
uint8_t w;
uint8_t h;
uint8_t tx;
uint8_t ty;
};
struct NetMessageFill: public NetMessage {
virtual NetMessageCode code() const {
return MSG_FILL;
}
uint8_t x;
uint8_t y;
uint8_t w;
uint8_t h;
long c;
};
struct NetMessageTurnOnOff: public NetMessage {
virtual NetMessageCode code() const {
return MSG_TURN_ON_OFF;
}
bool on;
};
struct NetMessageSetPrecise: public NetMessage {
virtual NetMessageCode code() const {
return MSG_SET_PRECISE;
}
bool precise;
};
struct NetMessageFetch: public NetMessage {
virtual NetMessageCode code() const {
return MSG_FETCH;
}
};
struct NetMessageEventTouch: public NetMessage {
virtual NetMessageCode code() const {
return MSG_EVENT_TOUCH;
}
uint8_t x;
uint8_t y;
uint8_t button;
};
struct NetMessageEventDrag: public NetMessage {
virtual NetMessageCode code() const {
return MSG_EVENT_DRAG;
}
uint8_t x;
uint8_t y;
uint8_t button;
};
struct NetMessageEventDrop: public NetMessage {
virtual NetMessageCode code() const {
return MSG_EVENT_DROP;
}
uint8_t x;
uint8_t y;
uint8_t button;
};
struct NetMessageEventScroll: public NetMessage {
virtual NetMessageCode code() const {
return MSG_EVENT_SCROLL;
}
uint8_t x;
uint8_t y;
bool direction;
uint8_t delta;
};
struct NetMessageEventKeyDown: public NetMessage {
virtual NetMessageCode code() const {
return MSG_EVENT_KEY_DOWN;
}
long chr;
long cod;
};
struct NetMessageEventKeyUp: public NetMessage {
virtual NetMessageCode code() const {
return MSG_EVENT_KEY_UP;
}
long chr;
long cod;
};
struct NetMessageEventClipboard: public NetMessage {
virtual NetMessageCode code() const {
return MSG_EVENT_CLIPBOARD;
}
std::string data;
};
struct NetMessagePing: public NetMessage {
virtual NetMessageCode code() const {
return MSG_PING;
}
uint64_t ping;
};
struct NetMessagePong: public NetMessage {
virtual NetMessageCode code() const {
return MSG_PONG;
}
uint64_t pong;
};
}
std::stringstream& pack(std::stringstream &result, const long data);
std::stringstream& pack(std::stringstream &result, const uint24_t data);
std::stringstream& pack(std::stringstream &result, const uint16_t data);
std::stringstream& pack(std::stringstream &result, const uint8_t data);
std::stringstream& pack(std::stringstream &result, const std::string &data);
std::stringstream& pack(std::stringstream &result, const NetMessageCode data);
std::stringstream& pack(std::stringstream &result, const ConnectionMode data);
std::stringstream& pack(std::stringstream &result, const AuthResult data);
std::stringstream& pack(std::stringstream &result, const Resolution &data);
std::stringstream& pack(std::stringstream &result, const bool data);
std::stringstream& pack(std::stringstream &result, const Char &data);
std::stringstream& pack(std::stringstream &result, const Color &color);
template <typename T>
std::stringstream& pack(std::stringstream &result, const std::vector<T> &data) {
pack(result, static_cast<uint24_t>(data.size()));
for (auto i: data) {
pack(result, i);
}
return result;
}
std::stringstream& pack(std::stringstream &result, const Palette &data);
std::stringstream& pack(std::stringstream &result, const uint64_t data);
std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageError &data);
std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageAuthClient &data);
std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageAuthServer &data);
std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageInitialData &data);
std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageSetBG &data);
std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageSetFG &data);
std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageSetPalette &data);
std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageSetResolution &data);
std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageSetChars &data);
std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageCopy &data);
std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageFill &data);
std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageTurnOnOff &data);
std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageSetPrecise &data);
std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageFetch &);
std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageEventTouch &data);
std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageEventDrag &data);
std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageEventDrop &data);
std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageEventScroll &data);
std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageEventKeyDown &data);
std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageEventKeyUp &data);
std::stringstream& pack(std::stringstream &result, const nmsg::NetMessageEventClipboard &data);
std::stringstream& pack(std::stringstream &result, const nmsg::NetMessagePing &data);
std::stringstream& pack(std::stringstream &result, const nmsg::NetMessagePong &data);
void unpack(std::stringstream &str, long &result);
void unpack(std::stringstream &str, uint24_t &result);
void unpack(std::stringstream &str, uint16_t &result);
void unpack(std::stringstream &str, uint8_t &result);
void unpack(std::stringstream &str, std::string &result);
void unpack(std::stringstream &str, NetMessageCode &result);
void unpack(std::stringstream &str, ConnectionMode &result);
void unpack(std::stringstream &str, AuthResult &result);
void unpack(std::stringstream &str, Resolution &result);
void unpack(std::stringstream &str, bool &result);
void unpack(std::stringstream &str, Char &result);
void unpack(std::stringstream &str, Color &result);
void unpack(std::stringstream &str, Palette &result);
void unpack(std::stringstream &str, uint64_t &result);
template <typename T>
void unpack(std::stringstream &str, std::vector<T> &result) {
uint24_t len;
unpack(str, len);
for (uint24_t i = 0; i < len; ++i) {
T element;
unpack(str, element);
result.push_back(element);
}
}
void unpack(std::stringstream &str, nmsg::NetMessageError &result);
void unpack(std::stringstream &str, nmsg::NetMessageAuthClient &result);
void unpack(std::stringstream &str, nmsg::NetMessageAuthServer &result);
void unpack(std::stringstream &str, nmsg::NetMessageInitialData &result);
void unpack(std::stringstream &str, nmsg::NetMessageSetBG &result);
void unpack(std::stringstream &str, nmsg::NetMessageSetFG &result);
void unpack(std::stringstream &str, nmsg::NetMessageSetPalette &result);
void unpack(std::stringstream &str, nmsg::NetMessageSetResolution &result);
void unpack(std::stringstream &str, nmsg::NetMessageSetChars &result);
void unpack(std::stringstream &str, nmsg::NetMessageCopy &result);
void unpack(std::stringstream &str, nmsg::NetMessageFill &result);
void unpack(std::stringstream &str, nmsg::NetMessageTurnOnOff &result);
void unpack(std::stringstream &str, nmsg::NetMessageSetPrecise &result);
void unpack(std::stringstream &, nmsg::NetMessageFetch &);
void unpack(std::stringstream &str, nmsg::NetMessageEventTouch &result);
void unpack(std::stringstream &str, nmsg::NetMessageEventDrag &result);
void unpack(std::stringstream &str, nmsg::NetMessageEventDrop &result);
void unpack(std::stringstream &str, nmsg::NetMessageEventScroll &result);
void unpack(std::stringstream &str, nmsg::NetMessageEventKeyDown &result);
void unpack(std::stringstream &str, nmsg::NetMessageEventKeyUp &result);
void unpack(std::stringstream &str, nmsg::NetMessageEventClipboard &result);
void unpack(std::stringstream &str, nmsg::NetMessagePing &result);
void unpack(std::stringstream &str, nmsg::NetMessagePong &result);
| 32.726776
| 95
| 0.67098
|
Fingercomp
|
7ff807a70c731bdc96b684e849b319e0ea9db4fb
| 30,019
|
cc
|
C++
|
docker/water/sph/tags/gpusph/src/writers/VTKWriter.cc
|
liujiamingustc/phd
|
4f815a738abad43531d02ac66f5bd0d9a1def52a
|
[
"Apache-2.0"
] | 3
|
2021-01-06T03:01:18.000Z
|
2022-03-21T03:02:55.000Z
|
docker/water/sph/tags/gpusph/src/writers/VTKWriter.cc
|
liujiamingustc/phd
|
4f815a738abad43531d02ac66f5bd0d9a1def52a
|
[
"Apache-2.0"
] | null | null | null |
docker/water/sph/tags/gpusph/src/writers/VTKWriter.cc
|
liujiamingustc/phd
|
4f815a738abad43531d02ac66f5bd0d9a1def52a
|
[
"Apache-2.0"
] | null | null | null |
/* Copyright 2011-2013 Alexis Herault, Giuseppe Bilotta, Robert A. Dalrymple, Eugenio Rustico, Ciro Del Negro
Istituto Nazionale di Geofisica e Vulcanologia
Sezione di Catania, Catania, Italy
Università di Catania, Catania, Italy
Johns Hopkins University, Baltimore, MD
This file is part of GPUSPH.
GPUSPH is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
GPUSPH 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 GPUSPH. If not, see <http://www.gnu.org/licenses/>.
*/
#include <sstream>
#include <fstream>
#include <stdexcept>
#include "VTKWriter.h"
// GlobalData is required for writing the device index. With some order
// of inclusions, a forward declaration might be required
#include "GlobalData.h"
#include "vector_print.h"
// for FLT_EPSILON
#include <cfloat>
using namespace std;
// TODO for the time being, we assume no more than 256 devices
// upgrade to UInt16 / ushort if it's ever needed
typedef unsigned char dev_idx_t;
static const char dev_idx_str[] = "UInt8";
VTKWriter::VTKWriter(const GlobalData *_gdata)
: Writer(_gdata),
m_planes_fname(),
m_blockidx(-1)
{
m_fname_sfx = ".vtu";
string time_fname = open_data_file(m_timefile, "VTUinp", "", ".pvd");
// Writing header of VTUinp.pvd file
if (m_timefile) {
m_timefile << "<?xml version='1.0'?>\n";
m_timefile << "<VTKFile type='Collection' version='0.1'>\n";
m_timefile << " <Collection>\n";
}
}
VTKWriter::~VTKWriter()
{
mark_timefile();
m_timefile.close();
}
void VTKWriter::add_block(string const& blockname, string const& fname)
{
++m_blockidx;
m_timefile << " <DataSet timestep='" << m_current_time << "' group='" << m_blockidx <<
"' name='" << blockname << "' file='" << fname << "'/>" << endl;
}
void VTKWriter::start_writing(double t, flag_t write_flags)
{
Writer::start_writing(t, write_flags);
ostringstream time_repr;
time_repr << t;
m_current_time = time_repr.str();
// we append the current integrator step to the timestring,
// but we need to add a dot if there isn't one already
string dot = m_current_time.find('.') != string::npos ? "" : ".";
if (write_flags == INTEGRATOR_STEP_1)
m_current_time += dot + "00000001";
else if (write_flags == INTEGRATOR_STEP_2)
m_current_time += dot + "00000002";
m_blockidx = -1;
const bool has_planes = gdata->s_hPlanes.size() > 0;
if (has_planes) {
if (m_planes_fname.size() == 0) {
save_planes();
}
add_block("Planes", m_planes_fname);
}
}
void VTKWriter::mark_written(double t)
{
mark_timefile();
Writer::mark_written(t);
}
/* Endianness check: (char*)&endian_int reads the first byte of the int,
* which is 0 on big-endian machines, and 1 in little-endian machines */
static int endian_int=1;
static const char* endianness[2] = { "BigEndian", "LittleEndian" };
static float zeroes[4];
/* auxiliary functions to write data array entrypoints */
inline void
scalar_array(ofstream &out, const char *type, const char *name, size_t offset)
{
out << " <DataArray type='" << type << "' Name='" << name
<< "' format='appended' offset='" << offset << "'/>" << endl;
}
inline void
vector_array(ofstream &out, const char *type, const char *name, uint dim, size_t offset)
{
out << " <DataArray type='" << type << "' Name='" << name
<< "' NumberOfComponents='" << dim
<< "' format='appended' offset='" << offset << "'/>" << endl;
}
inline void
vector_array(ofstream &out, const char *type, uint dim, size_t offset)
{
out << " <DataArray type='" << type
<< "' NumberOfComponents='" << dim
<< "' format='appended' offset='" << offset << "'/>" << endl;
}
// Binary dump a single variable of a given type
template<typename T>
inline void
write_var(ofstream &out, T const& var)
{
out.write(reinterpret_cast<const char *>(&var), sizeof(T));
}
// Binary dump an array of variables of given type and size
template<typename T>
inline void
write_arr(ofstream &out, T const *var, size_t len)
{
out.write(reinterpret_cast<const char *>(var), sizeof(T)*len);
}
void
VTKWriter::write(uint numParts, BufferList const& buffers, uint node_offset, double t, const bool testpoints)
{
const double4 *pos = buffers.getData<BUFFER_POS_GLOBAL>();
const hashKey *particleHash = buffers.getData<BUFFER_HASH>();
const float4 *vel = buffers.getData<BUFFER_VEL>();
const float4 *vol = buffers.getData<BUFFER_VOLUME>();
const float *sigma = buffers.getData<BUFFER_SIGMA>();
const particleinfo *info = buffers.getData<BUFFER_INFO>();
const float3 *vort = buffers.getData<BUFFER_VORTICITY>();
const float4 *normals = buffers.getData<BUFFER_NORMALS>();
const float4 *gradGamma = buffers.getData<BUFFER_GRADGAMMA>();
const float *tke = buffers.getData<BUFFER_TKE>();
const float *eps = buffers.getData<BUFFER_EPSILON>();
const float *turbvisc = buffers.getData<BUFFER_TURBVISC>();
const float *spsturbvisc = buffers.getData<BUFFER_SPS_TURBVISC>();
const float4 *eulervel = buffers.getData<BUFFER_EULERVEL>();
const float *priv = buffers.getData<BUFFER_PRIVATE>();
const vertexinfo *vertices = buffers.getData<BUFFER_VERTICES>();
const float *intEnergy = buffers.getData<BUFFER_INTERNAL_ENERGY>();
const float4 *forces = buffers.getData<BUFFER_FORCES>();
const neibdata *neibslist = buffers.getData<BUFFER_NEIBSLIST>();
ushort *neibsnum = new ushort[numParts];
if (neibslist) {
ofstream neibs;
open_data_file(neibs, "neibs", current_filenum(), ".txt");
const idx_t stride = numParts;
const idx_t maxneibsnum = gdata->problem->simparams()->maxneibsnum;
const id_t listend = maxneibsnum*stride;
for (int i = 0; i < numParts; ++i) {
neibsnum[i] = maxneibsnum;
neibs << i << "\t" << id(info[i]) << "\t";
for (int index = i; index < listend; index += stride) {
neibdata neib = neibslist[index];
neibs << neib << "\t";
if (neib == USHRT_MAX) {
neibsnum[i] = (index - i)/stride;
break;
}
if (neib >= CELLNUM_ENCODED) {
int neib_cellnum = DECODE_CELL(neib);
neibdata ndata = neib & NEIBINDEX_MASK;
neibs << "(" << neib_cellnum << ": " << ndata << ")\t";
}
}
neibs << "[" << neibsnum[i] << "]" << endl;
}
neibs.close();
}
string filename;
ofstream fid;
filename = open_data_file(fid, "PART", current_filenum());
// Header
//====================================================================================
fid << "<?xml version='1.0'?>" << endl;
fid << "<VTKFile type='UnstructuredGrid' version='0.1' byte_order='" <<
endianness[*(char*)&endian_int & 1] << "'>" << endl;
fid << " <UnstructuredGrid>" << endl;
fid << " <Piece NumberOfPoints='" << numParts << "' NumberOfCells='" << numParts << "'>" << endl;
fid << " <PointData Scalars='" << (neibslist ? "Neibs" : "Pressure") << "' Vectors='Velocity'>" << endl;
size_t offset = 0;
// neibs
if (neibslist) {
scalar_array(fid, "UInt16", "Neibs", offset);
offset += sizeof(ushort)*numParts+sizeof(int);
}
if (intEnergy) {
scalar_array(fid, "Float32", "Internal Energy", offset);
offset += sizeof(float)*numParts+sizeof(int);
}
if (forces) {
vector_array(fid, "Float32", "Spatial acceleration", 3, offset);
offset += sizeof(float)*3*numParts+sizeof(int);
scalar_array(fid, "Float32", "Continuity derivative", offset);
offset += sizeof(float)*numParts+sizeof(int);
}
// pressure
scalar_array(fid, "Float32", "Pressure", offset);
offset += sizeof(float)*numParts+sizeof(int);
// density
scalar_array(fid, "Float32", "Density", offset);
offset += sizeof(float)*numParts+sizeof(int);
// mass
scalar_array(fid, "Float32", "Mass", offset);
offset += sizeof(float)*numParts+sizeof(int);
// gamma
if (gradGamma) {
scalar_array(fid, "Float32", "Gamma", offset);
offset += sizeof(float)*numParts+sizeof(int);
}
// turbulent kinetic energy
if (tke) {
scalar_array(fid, "Float32", "TKE", offset);
offset += sizeof(float)*numParts+sizeof(int);
}
// turbulent epsilon
if (eps) {
scalar_array(fid, "Float32", "Epsilon", offset);
offset += sizeof(float)*numParts+sizeof(int);
}
// eddy viscosity
if (turbvisc) {
scalar_array(fid, "Float32", "Eddy viscosity", offset);
offset += sizeof(float)*numParts+sizeof(int);
}
// SPS eddy viscosity
if (spsturbvisc) {
scalar_array(fid, "Float32", "SPS turbulent viscosity", offset);
offset += sizeof(float)*numParts+sizeof(int);
}
/* Fluid number is only included if there are more than 1 */
const bool write_fluid_num = (gdata->problem->physparams()->numFluids() > 1);
/* Object number is only included if there are any */
// TODO a better way would be for GPUSPH to expose the highest
// object number ever associated with any particle, so that we
// could check that
const bool write_part_obj = (gdata->problem->simparams()->numbodies > 0);
// particle info
if (info) {
scalar_array(fid, "UInt8", "Part type", offset);
offset += sizeof(uchar)*numParts+sizeof(int);
scalar_array(fid, "UInt8", "Part flags", offset);
offset += sizeof(uchar)*numParts+sizeof(int);
// fluid number
if (write_fluid_num) {
// Limit to 256 fluids
scalar_array(fid, "UInt8", "Fluid number", offset);
offset += sizeof(uchar)*numParts+sizeof(int);
}
// object number
if (write_part_obj) {
// TODO UInt16 or UInt8 based on number of objects
scalar_array(fid, "UInt16", "Part object", offset);
offset += sizeof(ushort)*numParts+sizeof(int);
}
scalar_array(fid, "UInt32", "Part id", offset);
offset += sizeof(uint)*numParts+sizeof(int);
}
if (vertices) {
vector_array(fid, "UInt32", "Vertices", 4, offset);
offset += sizeof(uint)*4*numParts+sizeof(int);
}
// device index
if (MULTI_DEVICE) {
scalar_array(fid, dev_idx_str, "DeviceIndex", offset);
offset += sizeof(dev_idx_t)*numParts+sizeof(int);
}
// cell index
scalar_array(fid, "UInt32", "CellIndex", offset);
offset += sizeof(uint)*numParts+sizeof(int);
// velocity
vector_array(fid, "Float32", "Velocity", 3, offset);
offset += sizeof(float)*3*numParts+sizeof(int);
if (eulervel) {
// Eulerian velocity
vector_array(fid, "Float32", "Eulerian velocity", 3, offset);
offset += sizeof(float)*3*numParts+sizeof(int);
// Eulerian density
scalar_array(fid, "Float32", "Eulerian density", offset);
offset += sizeof(float)*numParts+sizeof(int);
}
// gradient gamma
if (gradGamma) {
vector_array(fid, "Float32", "Gradient Gamma", 3, offset);
offset += sizeof(float)*3*numParts+sizeof(int);
}
// vorticity
if (vort) {
vector_array(fid, "Float32", "Vorticity", 3, offset);
offset += sizeof(float)*3*numParts+sizeof(int);
}
// normals
if (normals) {
vector_array(fid, "Float32", "Normals", 3, offset);
offset += sizeof(float)*3*numParts+sizeof(int);
scalar_array(fid, "Float32", "Criteria", offset);
offset += sizeof(float)*numParts+sizeof(int);
}
// private
if (priv) {
scalar_array(fid, "Float32", "Private", offset);
offset += sizeof(float)*numParts+sizeof(int);
}
// volume
if (vol) {
vector_array(fid, "Float32", "Volume", 4, offset);
offset += sizeof(float)*4*numParts+sizeof(int);
}
// sigma
if (sigma) {
scalar_array(fid, "Float32", "Sigma", offset);
offset += sizeof(float)*numParts+sizeof(int);
}
fid << " </PointData>" << endl;
// position
fid << " <Points>" << endl;
vector_array(fid, "Float64", 3, offset);
offset += sizeof(double)*3*numParts+sizeof(int);
fid << " </Points>" << endl;
// Cells data
fid << " <Cells>" << endl;
scalar_array(fid, "Int32", "connectivity", offset);
offset += sizeof(uint)*numParts+sizeof(int);
scalar_array(fid, "Int32", "offsets", offset);
offset += sizeof(uint)*numParts+sizeof(int);
scalar_array(fid, "UInt8", "types", offset);
offset += sizeof(uchar)*numParts+sizeof(int);
fid << " </Cells>" << endl;
fid << " </Piece>" << endl;
fid << " </UnstructuredGrid>" << endl;
fid << " <AppendedData encoding='raw'>\n_";
//====================================================================================
int numbytes;
// neibs
if (neibslist) {
numbytes = sizeof(ushort)*numParts;
write_var(fid, numbytes);
write_arr(fid, neibsnum, numParts);
}
if (intEnergy) {
numbytes = sizeof(float)*numParts;
write_var(fid, numbytes);
write_arr(fid, intEnergy, numParts);
}
if (forces) {
numbytes=sizeof(float)*numParts*3;
// write spatial acceleration
write_var(fid, numbytes);
for (uint i=node_offset; i < node_offset + numParts; i++) {
const float *value = (float*)(forces + i);
write_arr(fid, value, 3);
}
numbytes=sizeof(float)*numParts;
write_var(fid, numbytes);
for (uint i=node_offset; i < node_offset + numParts; i++) {
const float value = forces[i].w;
write_var(fid, value);
}
}
numbytes=sizeof(float)*numParts;
// pressure
write_var(fid, numbytes);
for (uint i=node_offset; i < node_offset + numParts; i++) {
float value = 0.0;
if (TESTPOINT(info[i]))
value = vel[i].w;
else
value = m_problem->pressure(vel[i].w, fluid_num(info[i]));
write_var(fid, value);
}
// density
write_var(fid, numbytes);
for (uint i=node_offset; i < node_offset + numParts; i++) {
float value = 0.0;
if (TESTPOINT(info[i]))
// TODO FIXME: Testpoints compute pressure only
// In the future we would like to have a density here
// but this needs to be done correctly for multifluids
value = NAN;
else
value = vel[i].w;
write_var(fid, value);
}
// mass
write_var(fid, numbytes);
for (uint i=node_offset; i < node_offset + numParts; i++) {
float value = pos[i].w;
write_var(fid, value);
}
// gamma
if (gradGamma) {
write_var(fid, numbytes);
for (uint i=node_offset; i < node_offset + numParts; i++) {
float value = gradGamma[i].w;
write_var(fid, value);
}
}
// turbulent kinetic energy
if (tke) {
write_var(fid, numbytes);
for (uint i=node_offset; i < node_offset + numParts; i++) {
float value = tke[i];
write_var(fid, value);
}
}
// turbulent epsilon
if (eps) {
write_var(fid, numbytes);
for (uint i=0; i < numParts; i++) {
float value = eps[i];
write_var(fid, value);
}
}
// eddy viscosity
if (turbvisc) {
write_var(fid, numbytes);
for (uint i=node_offset; i < node_offset + numParts; i++) {
float value = turbvisc[i];
write_var(fid, value);
}
}
// SPS turbulent viscosity
if (spsturbvisc) {
write_var(fid, numbytes);
for (uint i=node_offset; i < node_offset + numParts; i++) {
float value = spsturbvisc[i];
write_var(fid, value);
}
}
// particle info
if (info) {
// type
numbytes=sizeof(uchar)*numParts;
write_var(fid, numbytes);
for (uint i=node_offset; i < node_offset + numParts; i++) {
uchar value = PART_TYPE(info[i]);
write_var(fid, value);
}
// flag
write_var(fid, numbytes);
for (uint i=node_offset; i < node_offset + numParts; i++) {
uchar value = (PART_FLAGS(info[i]) >> PART_FLAG_SHIFT);
write_var(fid, value);
}
// fluid number
if (write_fluid_num) {
write_var(fid, numbytes);
for (uint i=node_offset; i < node_offset + numParts; i++) {
uchar value = fluid_num(info[i]);
write_var(fid, value);
}
}
if (write_part_obj) {
numbytes=sizeof(ushort)*numParts;
write_var(fid, numbytes);
for (uint i=node_offset; i < node_offset + numParts; i++) {
ushort value = object(info[i]);
write_var(fid, value);
}
}
// id
numbytes=sizeof(uint)*numParts;
write_var(fid, numbytes);
for (uint i=node_offset; i < node_offset + numParts; i++) {
uint value = id(info[i]);
write_var(fid, value);
}
}
// vertices
if (vertices) {
numbytes = sizeof(uint)*4*numParts;
write_var(fid, numbytes);
for (uint i=node_offset; i < node_offset + numParts; i++) {
uint *value = (uint*)(vertices + i);
write_arr(fid, value, 4);
}
}
// device index
if (MULTI_DEVICE) {
numbytes = sizeof(dev_idx_t)*numParts;
write_var(fid, numbytes);
// The previous way was to compute the theoretical containing cell solely according on the particle position. This, however,
// was inconsistent with the actual particle distribution among the devices, since one particle can be physically out of the
// containing cell until next calchash/reorder.
// The current policy is: just list the particles according to how the global array is partitioned. In other words, we rely
// on the particle index to understad which device downloaded the particle data.
for (uint d = 0; d < gdata->devices; d++) {
// compute the global device ID for each device
dev_idx_t value = gdata->GLOBAL_DEVICE_ID(gdata->mpi_rank, d);
// write one for each particle (no need for the "absolute" particle index)
for (uint p = 0; p < gdata->s_hPartsPerDevice[d]; p++)
write_var(fid, value);
}
// There two alternate policies: 1. use particle hash or 2. compute belonging device.
// To use the particle hash, instead of just relying on the particle index, use the following code:
/*
for (uint i=node_offset; i < node_offset + numParts; i++) {
uint value = gdata->s_hDeviceMap[ cellHashFromParticleHash(particleHash[i]) ];
write_var(fid, value);
}
*/
// This should be equivalent to the current "listing" approach. If for any reason (e.g. debug) one needs to write the
// device index according to the current spatial position, it is enough to compute the particle hash from its position
// instead of reading it from the particlehash array. Please note that this would reflect the spatial split but not the
// actual assignments: until the next calchash is performed, one particle remains in the containing device even if it
// it is slightly outside the domain.
}
// linearized cell index (NOTE: particles might be slightly off the belonging cell)
numbytes = sizeof(uint)*numParts;
write_var(fid, numbytes);
for (uint i=node_offset; i < node_offset + numParts; i++) {
uint value = cellHashFromParticleHash( particleHash[i] );
write_var(fid, value);
}
numbytes=sizeof(float)*3*numParts;
// velocity
write_var(fid, numbytes);
for (uint i=node_offset; i < node_offset + numParts; i++) {
float *value = zeroes;
//if (FLUID(info[i]) || TESTPOINTS(info[i]))
value = (float*)(vel + i);
write_arr(fid, value, 3);
}
if (eulervel) {
write_var(fid, numbytes);
for (uint i=node_offset; i < node_offset + numParts; i++) {
float *value = zeroes;
value = (float*)(eulervel + i);
write_arr(fid, value, 3);
}
numbytes=sizeof(float)*numParts;
write_var(fid, numbytes);
for (uint i=node_offset; i < node_offset + numParts; i++) {
float value = eulervel[i].w;
write_var(fid, value);
}
numbytes=sizeof(float)*3*numParts;
}
// gradient gamma
if (gradGamma) {
write_var(fid, numbytes);
for (uint i=node_offset; i < node_offset + numParts; i++) {
float *value = zeroes;
value = (float*)(gradGamma + i);
write_arr(fid, value, 3);
}
}
// vorticity
if (vort) {
write_var(fid, numbytes);
for (uint i=node_offset; i < node_offset + numParts; i++) {
float *value = zeroes;
if (FLUID(info[i])) {
value = (float*)(vort + i);
}
write_arr(fid, value, 3);
}
}
// normals
if (normals) {
write_var(fid, numbytes);
for (uint i=node_offset; i < node_offset + numParts; i++) {
float *value = zeroes;
if (FLUID(info[i])) {
value = (float*)(normals + i);
}
write_arr(fid, value, 3);
}
numbytes=sizeof(float)*numParts;
// criteria
write_var(fid, numbytes);
for (uint i=node_offset; i < node_offset + numParts; i++) {
float value = 0;
if (FLUID(info[i]))
value = normals[i].w;
write_var(fid, value);
}
}
numbytes=sizeof(float)*numParts;
// private
if (priv) {
write_var(fid, numbytes);
for (uint i=node_offset; i < node_offset + numParts; i++) {
float value = priv[i];
write_var(fid, value);
}
}
numbytes=sizeof(float)*numParts*4;
// volume
if (vol) {
write_var(fid, numbytes);
for (uint i=node_offset; i < node_offset + numParts; i++) {
float *value = (float*)(vol + i);
write_arr(fid, value, 4);
}
}
numbytes=sizeof(float)*numParts;
// sigma
if (sigma) {
write_var(fid, numbytes);
for (uint i=node_offset; i < node_offset + numParts; i++) {
float value = sigma[i];
write_var(fid, value);
}
}
numbytes=sizeof(double)*3*numParts;
// position
write_var(fid, numbytes);
for (uint i=node_offset; i < node_offset + numParts; i++) {
double *value = (double*)(pos + i);
write_arr(fid, value, 3);
}
numbytes=sizeof(int)*numParts;
// connectivity
write_var(fid, numbytes);
for (uint i=0; i < numParts; i++) {
uint value = i;
write_var(fid, value);
}
// offsets
write_var(fid, numbytes);
for (uint i=0; i < numParts; i++) {
uint value = i+1;
write_var(fid, value);
}
// types (currently all cells type=1, single vertex, the particle)
numbytes=sizeof(uchar)*numParts;
write_var(fid, numbytes);
for (uint i=0; i < numParts; i++) {
uchar value = 1;
write_var(fid, value);
}
fid << " </AppendedData>" << endl;
fid << "</VTKFile>" << endl;
fid.close();
add_block("Particles", filename);
delete[] neibsnum;
}
void
VTKWriter::write_WaveGage(double t, GageList const& gage)
{
ofstream fp;
string filename = open_data_file(fp, "WaveGage", current_filenum());
size_t num = gage.size();
// For gages without points, z will be NaN, and we'll set
// it to match the lowest world coordinate
const double worldBottom = gdata->worldOrigin.z;
// Header
fp << "<?xml version='1.0'?>" << endl;
fp << "<VTKFile type='UnstructuredGrid' version='0.1' byte_order='" <<
endianness[*(char*)&endian_int & 1] << "'>" << endl;
fp << " <UnstructuredGrid>" << endl;
fp << " <Piece NumberOfPoints='" << num << "' NumberOfCells='" << num << "'>" << endl;
//Writing Position
fp << " <Points>" << endl;
fp << " <DataArray type='Float32' NumberOfComponents='3' format='ascii'>" << endl;
for (size_t i=0; i < num; i++)
fp << gage[i].x << "\t" << gage[i].y << "\t" <<
(isfinite(gage[i].z) ? gage[i].z : worldBottom) << "\t";
fp << endl;
fp << " </DataArray>" << endl;
fp << " </Points>" << endl;
// Cells data
fp << " <Cells>" << endl;
fp << " <DataArray type='Int32' Name='connectivity' format='ascii'>" << endl;
for (size_t i = 0; i < num; i++)
fp << i << "\t" ;
fp << endl;
fp << " </DataArray>" << endl;
fp << "" << endl;
fp << " <DataArray type='Int32' Name='offsets' format='ascii'>" << endl;
for (size_t i = 0; i < num; i++)
fp << (i+1) << "\t" ;
fp << endl;
fp << " </DataArray>" << endl;
fp << "" << endl;
fp << " <DataArray type='Int32' Name='types' format='ascii'>" << endl;
for (size_t i = 0; i < num; i++)
fp << 1 << "\t" ;
fp << endl;
fp << " </DataArray>" << endl;
fp << " </Cells>" << endl;
fp << " </Piece>" << endl;
fp << " </UnstructuredGrid>" << endl;
fp << "</VTKFile>" <<endl;
fp.close();
add_block("WaveGages", filename);
}
static inline void chomp(double3 &pt, double eps=FLT_EPSILON)
{
if (fabs(pt.x) < eps)
pt.x = 0;
if (fabs(pt.y) < eps)
pt.y = 0;
if (fabs(pt.z) < eps)
pt.z = 0;
}
// check that pt is between inf and sup, with FLT_EPSILON relative tolerange
static inline bool bound(float pt, float inf, float sup)
{
// when inf or sup is zero, the tolerance must be absolute, not relative
// Also note the use of absolue value to ensure the limits are expanded
// in the right direction
const float lower = inf ? inf - FLT_EPSILON*fabs(inf) : -FLT_EPSILON;
const float upper = sup ? sup + FLT_EPSILON*fabs(sup) : FLT_EPSILON;
return (pt > lower) && (pt < upper);
}
void
VTKWriter::save_planes()
{
ofstream fp;
m_planes_fname = open_data_file(fp, "PLANES");
fp << set_vector_fmt(" ");
PlaneList const& planes = gdata->s_hPlanes;
const double3 wo = gdata->problem->get_worldorigin();
const double3 ow = wo + gdata->problem->get_worldsize();
typedef vector<pair<double4, int> > CheckList;
typedef vector<double3> CoordList;
// We want to find the intersection of the planes defined in the boundary
// with the bounding box of the plane (wo to ow). We do this by finding the intersection
// with each pair of planes of the bounding box. The CheckList is composed of such pairs,
// ordered such that the intersections are returned in sequence (otherwise the resulting
// planes in the VTK would come out butterfly-shaped.
// The number associated with each pair of planes is the index of the coordinate that must
// be found by the intersection.
CheckList checks;
checks.push_back(make_pair(
make_double4(wo.x, wo.y, 0, 1), 2));
checks.push_back(make_pair(
make_double4(wo.x, 0, wo.z, 1), 1));
checks.push_back(make_pair(
make_double4(wo.x, ow.y, 0, 1), 2));
checks.push_back(make_pair(
make_double4(wo.x, 0, ow.z, 1), 1));
checks.push_back(make_pair(
make_double4(ow.x, ow.y, 0, 1), 2));
checks.push_back(make_pair(
make_double4(ow.x, 0, ow.z, 1), 1));
checks.push_back(make_pair(
make_double4(ow.x, wo.y, 0, 1), 2));
checks.push_back(make_pair(
make_double4(0, wo.y, wo.z, 1), 0));
checks.push_back(make_pair(
make_double4(0, wo.y, ow.z, 1), 0));
checks.push_back(make_pair(
make_double4(0, ow.y, ow.z, 1), 0));
checks.push_back(make_pair(
make_double4(ow.x, 0, wo.z, 1), 1));
checks.push_back(make_pair(
make_double4(0, ow.y, wo.z, 1), 0));
CoordList centers;
CoordList normals;
vector< CoordList > all_intersections;
// we will store one point per plane (center)
// followed by the intersections for each plane with the domain bounding box
size_t npoints = planes.size();
// find the intersection of each plane with the domain bounding box
PlaneList::const_iterator plane(planes.begin());
for (; plane != planes.end(); ++plane) {
centers.push_back(gdata->calcGlobalPosOffset(plane->gridPos, plane->pos) + wo);
double3 &cpos = centers.back();
chomp(cpos);
normals.push_back(make_double3(plane->normal));
chomp(normals.back());
double3 const& normal = normals.back();
double4 implicit = make_double4(normal, -dot(cpos, normal));
#if DEBUG_VTK_PLANES
cout << "plane through " << cpos << " normal " << normal << endl;
cout << "\timplicit " << implicit << endl;
#endif
all_intersections.push_back( vector<double3>() );
vector<double3> & intersections = all_intersections.back();
CheckList::const_iterator check(checks.begin());
for (; check != checks.end(); ++check) {
const double4 &ref = check->first;
const int coord = check->second;
double3 pt = make_double3(ref);
switch (coord) {
case 0:
if (!normal.x) continue;
pt.x = -dot(implicit, ref)/normal.x;
if (!bound(pt.x, wo.x, ow.x)) continue;
break;
case 1:
if (!normal.y) continue;
pt.y = -dot(implicit, ref)/normal.y;
if (!bound(pt.y, wo.y, ow.y)) continue;
break;
case 2:
if (!normal.z) continue;
pt.z = -dot(implicit, ref)/normal.z;
if (!bound(pt.z, wo.z, ow.z)) continue;
break;
}
chomp(pt);
intersections.push_back(pt);
#if DEBUG_VTK_PLANES
cout << "\t(" << (check-checks.begin()) << ")" << endl;
cout << "\tcheck " << ref << " from " << coord << endl;
cout << "\t\tpoint " << intersections.back() << endl;
#endif
}
npoints += intersections.size();
}
size_t offset = 0;
fp << "<?xml version='1.0'?>" << endl;
fp << "<VTKFile type='UnstructuredGrid' version='0.1' byte_order='" <<
endianness[*(char*)&endian_int & 1] << "'>" << endl;
fp << " <UnstructuredGrid>" << endl;
fp << " <Piece NumberOfPoints='" << npoints
<< "' NumberOfCells='" << planes.size() << " '>" << endl;
fp << " <Points>" << endl;
fp << "<DataArray type='Float64' NumberOfComponents='3'>" << endl;
// intersection points
for (vector<CoordList>::const_iterator pl(all_intersections.begin());
pl < all_intersections.end(); ++pl) {
CoordList const& pts = *pl;
for (CoordList::const_iterator pt(pts.begin()); pt != pts.end(); ++pt)
fp << *pt << endl;
}
// center points
for (CoordList::const_iterator pt(centers.begin()); pt != centers.end(); ++pt)
fp << *pt << endl;
fp << "</DataArray>" << endl;
fp << " </Points>" << endl;
fp << " <Cells>" << endl;
fp << "<DataArray type='Int32' Name='connectivity'>" << endl;
// intersection points
offset = 0;
for (vector<CoordList>::const_iterator pl(all_intersections.begin());
pl < all_intersections.end(); ++pl) {
CoordList const& pts = *pl;
for (int i = 0; i < pts.size(); ++i) {
fp << " " << offset + i;
}
offset += pts.size();
fp << endl;
}
fp << "</DataArray>" << endl;
fp << "<DataArray type='Int32' Name='offsets'>" << endl;
offset = 0;
for (int i = 0; i < planes.size(); ++i) {
offset += all_intersections[i].size();
fp << offset << endl;
}
fp << "</DataArray>" << endl;
fp << "<DataArray type='Int32' Name='types'>" << endl;
for (int i = 0; i < planes.size(); ++i) {
fp << 7 << " "; // POLYGON
}
fp << endl;
fp << "</DataArray>" << endl;
fp << " </Cells>" << endl;
fp << " <PointData />" << endl;
fp << " <CellData Normals='Normals'>" << endl;
fp << "<DataArray type='Float64' Name='Normals' NumberOfComponents='3'>" << endl;
for (CoordList::const_iterator pt(normals.begin()); pt != normals.end(); ++pt)
fp << *pt << endl;
fp << "</DataArray>" << endl;
fp << " </CellData>" << endl;
fp << " </Piece>" << endl;
fp << " </UnstructuredGrid>" << endl;
fp << "</VTKFile>" <<endl;
fp.close();
}
void
VTKWriter::mark_timefile()
{
if (!m_timefile)
return;
// Mark the current position, close the XML, go back
// to the marked position
ofstream::pos_type mark = m_timefile.tellp();
m_timefile << " </Collection>\n";
m_timefile << "</VTKFile>" << endl;
m_timefile.seekp(mark);
}
| 28.616778
| 126
| 0.64779
|
liujiamingustc
|
7ff9bb86d836248aba8bbdfc0129cbcba4e251a2
| 518
|
hpp
|
C++
|
protean/detail/sequence.hpp
|
proteanic/protean
|
dcbb0d0d2da708dd7f524124e64a8085ccb8b9e5
|
[
"BSL-1.0"
] | 2
|
2017-11-08T19:40:50.000Z
|
2017-11-24T18:43:09.000Z
|
protean/detail/sequence.hpp
|
roederja/protean
|
502cccd10b5721bd74385959362890ec6b5e5d29
|
[
"BSL-1.0"
] | 3
|
2017-12-20T13:37:00.000Z
|
2018-12-04T11:31:14.000Z
|
protean/detail/sequence.hpp
|
roederja/protean
|
502cccd10b5721bd74385959362890ec6b5e5d29
|
[
"BSL-1.0"
] | 7
|
2015-02-11T14:43:16.000Z
|
2020-06-20T21:06:38.000Z
|
#ifndef PROTEAN_DETAIL_SEQUENCE_HPP
#define PROTEAN_DETAIL_SEQUENCE_HPP
#include <protean/config.hpp>
#include <protean/detail/collection.hpp>
namespace protean {
class variant;
namespace detail {
class PROTEAN_DECL sequence : public collection
{
public:
virtual const variant& at(size_t index) const = 0;
virtual variant& at(size_t index) = 0;
};
} // namespace protean::detail
} // namespace protean
#endif // PROTEAN_DETAIL_SEQUENCE_HPP
| 19.185185
| 62
| 0.671815
|
proteanic
|
7ffc2ff07c26e8a54e280caa0d73deff81c874f7
| 804
|
cpp
|
C++
|
src/1000/1012.cpp14.cpp
|
upple/BOJ
|
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
|
[
"MIT"
] | 8
|
2018-04-12T15:54:09.000Z
|
2020-06-05T07:41:15.000Z
|
src/1000/1012.cpp14.cpp
|
upple/BOJ
|
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
|
[
"MIT"
] | null | null | null |
src/1000/1012.cpp14.cpp
|
upple/BOJ
|
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
|
[
"MIT"
] | null | null | null |
#include <cstdio>
using namespace std;
const int move_x[4]={1, -1, 0, 0};
const int move_y[4]={ 0, 0, 1, -1};
bool map[51][52]={}, visit[52][52]={};
int count;
int dfs(int x, int y)
{
for(int i=0; i<4; i++)
{
int nx=x+move_x[i], ny=y+move_y[i];
if(map[nx][ny] && !visit[nx][ny])
visit[nx][ny]=true, dfs(nx, ny);
}
}
int main()
{
int t, row, col, n;
scanf("%d", &t);
while(t--)
{
scanf("%d %d %d", &row, &col, &n);
for(int i=1; i<=row; i++)
for(int j=1; j<=col; j++)
map[i][j]=visit[i][j]=false;
while(n--)
{
int x, y;
scanf("%d %d", &x, &y);
map[x+1][y+1]=true;
}
for(int i=1; i<=row; i++)
for(int j=1; j<=col; j++)
{
if(map[i][j] && !visit[i][j])
visit[i][j]=true, count++, dfs(i, j);
}
printf("%d\n", count);
count=0;
}
return 0;
}
| 17.106383
| 42
| 0.483831
|
upple
|
7fff156a502f4205f09f91f15687ebf7d3debff8
| 7,055
|
cpp
|
C++
|
calculation/BigInt/SignedBigInt.cpp
|
searchstar2017/acmtool
|
03392b8909a3d45f10c2711ca4ad9ba69f64a481
|
[
"MIT"
] | null | null | null |
calculation/BigInt/SignedBigInt.cpp
|
searchstar2017/acmtool
|
03392b8909a3d45f10c2711ca4ad9ba69f64a481
|
[
"MIT"
] | null | null | null |
calculation/BigInt/SignedBigInt.cpp
|
searchstar2017/acmtool
|
03392b8909a3d45f10c2711ca4ad9ba69f64a481
|
[
"MIT"
] | null | null | null |
struct SignedBigInt {
bool is_minus;
UnsignedBigInt absVal;
SignedBigInt() : is_minus(false) {}
explicit SignedBigInt(int num) : absVal(std::abs(num)), is_minus(num < 0) {}
explicit SignedBigInt(LL num) : absVal(std::abs(num)), is_minus(num < 0) {}
explicit SignedBigInt(const string& num) {
if(!isdigit(num[0])) {
is_minus = (num[0] == '-');
absVal = num.c_str() + 1;
} else {
is_minus = false;
absVal = num;
}
}
explicit SignedBigInt(const UnsignedBigInt& val) : absVal(val), is_minus(false) {}
explicit operator int() {
return is_minus ? -(int)absVal : (int)absVal;
}
explicit operator double() const {
return is_minus ? -(double)absVal : (double)absVal;
}
explicit operator string() const {
string ans;
if (absVal.s.empty()) {
ans = '0';
} else {
if (is_minus)
ans += '-';
ans += (string)absVal;
}
return ans;
}
explicit operator bool() const {
return !absVal.s.empty();
}
explicit operator int() const {
return absVal.s.empty() ? 0 : (is_minus ? -absVal.s[0] : absVal.s[0]);
}
SignedBigInt& operator = (const int num) {
return (*this = SignedBigInt(num));
}
SignedBigInt& operator = (const string& num) {
return (*this = SignedBigInt(num));
}
bool operator == (const SignedBigInt& b) const
{
return absVal.s.empty() && b.absVal.s.empty() ? 1 : (is_minus != b.is_minus ? 0 : absVal == b.absVal);
}
bool operator < (const SignedBigInt& b) const
{
return absVal.s.empty() && b.absVal.s.empty() ? 0 : (is_minus != b.is_minus ? is_minus : (is_minus ? b.absVal < absVal : absVal < b.absVal));
}
bool operator <= (const SignedBigInt& b) const {
return *this < b || *this == b;
}
bool operator > (const SignedBigInt& b) const {
return b < *this;
}
bool operator >= (const SignedBigInt& b) const {
return b <= *this;
}
bool operator != (const SignedBigInt& b) const {
return !(*this == b);
}
bool operator == (int b) const {
return (b < 0) ^ is_minus ? (absVal.s.empty() && b == 0) : absVal == UnsignedBigInt(std::abs(b));
}
bool operator < (int b) const
{
return absVal.s.empty() ? b > 0 : ((b < 0) ^ is_minus ? is_minus : (is_minus ? -b < absVal : absVal < b));
}
bool operator <= (int rhs) const {
return *this < rhs || *this == rhs;
}
bool operator > (int rhs) const {
return !(*this <= rhs);
}
bool operator >= (int rhs) const {
return !(*this < rhs);
}
bool operator != (int rhs) const {
return !(*this == rhs);
}
SignedBigInt& AddEq(bool b_is_minus, const UnsignedBigInt& b_absVal)
{
if(is_minus ^ b_is_minus)//different sign
{
if(absVal < b_absVal)
{
absVal = b_absVal - absVal;
is_minus = b_is_minus;
}
else
absVal -= b_absVal;
}
else
absVal += b_absVal;
return *this;
}
SignedBigInt& operator += (const SignedBigInt& b)
{
return AddEq(b.is_minus, b.absVal);
}
SignedBigInt operator + (const SignedBigInt& b) const
{
SignedBigInt ans = *this;
return ans += b;
}
//SignedBigInt& AddEq(bool b_is_minus, const UnsignedBigInt& b_absVal)
SignedBigInt& operator -= (const SignedBigInt& b)
{
return AddEq(!b.is_minus, b.absVal);
}
SignedBigInt operator - (const SignedBigInt& b) const {
return SignedBigInt(*this) -= b;
}
SignedBigInt operator - () const
{
SignedBigInt ans;
ans.is_minus = !is_minus;
ans.absVal = absVal;
return ans;
}
SignedBigInt operator * (const SignedBigInt& b) const
{
SignedBigInt ans;
ans.is_minus = is_minus ^ b.is_minus;
ans.absVal = absVal * b.absVal;
return ans;
}
SignedBigInt& operator *= (const SignedBigInt& b)
{
return *this = *this * b;
}
SignedBigInt operator / (const SignedBigInt& b) const
{
SignedBigInt ans;
ans.is_minus = is_minus ^ b.is_minus;
ans.absVal = absVal / b.absVal;
return ans;
}
SignedBigInt& operator /= (const SignedBigInt& b)
{
return *this = *this / b;
}
SignedBigInt operator % (const SignedBigInt& b) const
{
SignedBigInt ans;
ans.is_minus = is_minus;
ans.absVal = absVal % b.absVal;
return ans;
}
SignedBigInt& operator %= (const SignedBigInt& b)
{
return *this = *this % b;
}
SignedBigInt abs() const {
return SignedBigInt(absVal);
}
SignedBigInt& operator += (int rhs) {
if (is_minus ^ (rhs<0)) {
if (absVal >= rhs) {
absVal -= rhs;
} else {
absVal = UnsignedBigInt(rhs - absVal);
is_minus = !is_minus;
}
} else {
absVal += rhs;
}
return *this;
}
SignedBigInt& operator ++ () {
return *this += 1;
}
SignedBigInt operator + (int rhs) {
SignedBigInt ans = *this;
return ans += rhs;
}
SignedBigInt& operator -= (int rhs) {
if (rhs >= 0) {
if (is_minus) {
absVal += rhs;
} else {
absVal -= rhs;
}
} else {
absVal += -rhs;
}
return *this;
}
SignedBigInt& operator -- () {
return *this -= 1;
}
SignedBigInt operator - (int rhs) {
SignedBigInt ans = *this;
return ans -= rhs;
}
SignedBigInt& operator *= (int rhs) {
if (rhs < 0) {
is_minus = !is_minus;
rhs = -rhs;
}
absVal *= rhs;
return *this;
}
SignedBigInt operator * (int rhs) {
SignedBigInt ans = *this;
return ans *= rhs;
}
SignedBigInt& operator /= (int rhs) {
assert(rhs);
if (rhs < 0) {
is_minus = !is_minus;
rhs = -rhs;
}
absVal /= rhs;
return *this;
}
SignedBigInt operator / (int rhs) {
SignedBigInt ans = *this;
return ans /= rhs;
}
int operator % (int rhs) {
int ans = absVal % std::abs(rhs);
return is_minus ? -ans : ans;
}
SignedBigInt& operator %= (int rhs) {
absVal %= std::abs(rhs);
return *this;
}
};
ostream& operator << (ostream& out, const SignedBigInt& a)
{
return out << string(a);
}
istream& operator >> (istream& in, SignedBigInt& a)
{
string str;
if (in >> str)
a = str;
return in;
}
SignedBigInt sqrt(const SignedBigInt& x, int m) {
assert(!x.is_minus);
return SignedBigInt(sqrt(x.absVal, m));
}
| 26.03321
| 149
| 0.514245
|
searchstar2017
|
7ffff0fffabaf2f0077794c791cf69d75490d39e
| 1,036
|
cpp
|
C++
|
src/sequencial.cpp
|
lucasnr/so-atividade-1
|
556d1cf710217d81d47cc74a1494049f883ff6aa
|
[
"MIT"
] | null | null | null |
src/sequencial.cpp
|
lucasnr/so-atividade-1
|
556d1cf710217d81d47cc74a1494049f883ff6aa
|
[
"MIT"
] | null | null | null |
src/sequencial.cpp
|
lucasnr/so-atividade-1
|
556d1cf710217d81d47cc74a1494049f883ff6aa
|
[
"MIT"
] | null | null | null |
#include <chrono>
#include <iostream>
#include <vector>
#include "./util.h"
using namespace std;
using matrix = vector<vector<int>>;
int main(int argc, char **argv) {
if (argc < 3) {
cout << "Not enough arguments" << endl;
exit(1);
}
auto filename1 = argv[1];
auto filename2 = argv[2];
matrix array1 = matrix();
matrix array2 = matrix();
read_array_from_file(&array1, filename1);
read_array_from_file(&array2, filename2);
matrix product = matrix();
int rows = array1.size(), cols = array2[0].size();
initialize_array(&product, rows, cols);
chrono::steady_clock::time_point begin = chrono::steady_clock::now();
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < cols; j++) {
calculate_at_position(&product, i, j, &array1, &array2);
}
}
chrono::steady_clock::time_point end = chrono::steady_clock::now();
auto duration =
chrono::duration_cast<chrono::milliseconds>(end - begin).count();
write_array_to_file(&product, "sequencial.txt", duration);
return 0;
}
| 24.093023
| 71
| 0.65444
|
lucasnr
|
3d013b42ee6c78efc856be9afffc62665f89f08d
| 15,394
|
cpp
|
C++
|
src/Core/DS_Config.cpp
|
WinT-3794/libDS
|
87ae5b3018e968bfb932d6cb8929e9ffefb273ab
|
[
"MIT"
] | 12
|
2015-09-21T03:05:57.000Z
|
2016-04-27T17:46:41.000Z
|
src/Core/DS_Config.cpp
|
WinT-3794/LibDS
|
87ae5b3018e968bfb932d6cb8929e9ffefb273ab
|
[
"MIT"
] | null | null | null |
src/Core/DS_Config.cpp
|
WinT-3794/LibDS
|
87ae5b3018e968bfb932d6cb8929e9ffefb273ab
|
[
"MIT"
] | null | null | null |
/*
* Copyright (c) 2016 Alex Spataru <alex_spataru@outlook.com>
*
* This file is part of the LibDS, which is released under the MIT license.
* For more information, please read the LICENSE file in the root directory
* of this project.
*/
#include "DS_Config.h"
#include "DriverStation.h"
#include <QThread>
#include <QElapsedTimer>
#include <Core/Logger.h>
DS_Config::DS_Config() {
m_timer = new QElapsedTimer;
m_logger = new Logger;
m_team = 0;
m_voltage = 0;
m_cpuUsage = 0;
m_ramUsage = 0;
m_diskUsage = 0;
m_libVersion = "";
m_pcmVersion = "";
m_pdpVersion = "";
m_simulated = false;
m_timerEnabled = false;
m_position = kPosition1;
m_alliance = kAllianceRed;
m_codeStatus = kCodeFailing;
m_operationStatus = kNormal;
m_fmsCommStatus = kCommsFailing;
m_enableStatus = kDisabled;
m_voltageStatus = kVoltageNormal;
m_radioCommStatus = kCommsFailing;
m_robotCommStatus = kCommsFailing;
m_controlMode = kControlTeleoperated;
/* Move the robot logger to another thread */
QThread* thread = new QThread (this);
m_logger->moveToThread (thread);
thread->start (QThread::NormalPriority);
/* Begin elapsed time loop */
updateElapsedTime();
}
/**
* Returns the instance of the robot logger object
*/
Logger* DS_Config::logger() {
return m_logger;
}
/**
* Returns the one and only instance of
*/
DS_Config* DS_Config::getInstance() {
static DS_Config instance;
return &instance;
}
/**
* Returns the current team number
*/
int DS_Config::team() const {
return m_team;
}
/**
* Returns the current CPU usage of the robot (0 - 100)
*/
int DS_Config::cpuUsage() const {
return m_cpuUsage;
}
/**
* Returns the current RAM usage of the robot
*/
int DS_Config::ramUsage() const {
return m_ramUsage;
}
/**
* Returns the current disk usage of the robot
*/
int DS_Config::diskUsage() const {
return m_diskUsage;
}
/**
* Returns the current voltage of the robot
*/
qreal DS_Config::voltage() const {
if (isConnectedToRobot())
return m_voltage;
return 0;
}
/**
* Returns \c true if the robot is enabled. Otherwise, it returns \c false
*/
bool DS_Config::isEnabled() const {
return enableStatus() == DS::kEnabled;
}
/**
* Returns \c true if the robot is simulated. Otherwise, it returns \c false
*/
bool DS_Config::isSimulated() const {
return m_simulated;
}
/**
* Returns the current alliance of the robot (be it user-set or FMS-set)
*/
DS::Alliance DS_Config::alliance() const {
return m_alliance;
}
/**
* Returns the current position of the robot (be it user-set or FMS-set)
*/
DS::Position DS_Config::position() const {
return m_position;
}
/**
* Returns \c true if the Driver Station is connected to the Field Management
* System (FMS).
*/
bool DS_Config::isFMSAttached() const {
return fmsCommStatus() == DS::kCommsWorking;
}
/**
* Returns the library version of the robot
*/
QString DS_Config::libVersion() const {
return m_libVersion;
}
/**
* Returns the PCM version of the robot
*/
QString DS_Config::pcmVersion() const {
return m_pcmVersion;
}
/**
* Returns the PDP version of the robot
*/
QString DS_Config::pdpVersion() const {
return m_pdpVersion;
}
/**
* Returns \c true if the robot is emergency stopped. Otherwise, it returns
* \c false.
*/
bool DS_Config::isEmergencyStopped() const {
return operationStatus() == DS::kEmergencyStop;
}
/**
* Returns \c true if the robot code is running. Otherwise, it returns \c false
*/
bool DS_Config::isRobotCodeRunning() const {
return robotCodeStatus() == DS::kCodeRunning;
}
/**
* Returns \c true if the Driver Station is connected to the radio. Otherwise,
* it returns \c false
*/
bool DS_Config::isConnectedToRadio() const {
return radioCommStatus() == DS::kCommsWorking;
}
/**
* Returns \c true if the Driver Station is connected to the robot. Otherwise,
* it returns \c false
*/
bool DS_Config::isConnectedToRobot() const {
return robotCommStatus() == DS::kCommsWorking;
}
/**
* Returns the current control mode of the robot
*/
DS::ControlMode DS_Config::controlMode() const {
return m_controlMode;
}
/**
* Returns the current status of the FMS communications.
* \note You can also use the \c isConnectedToFMS() function
*/
DS::CommStatus DS_Config::fmsCommStatus() const {
return m_fmsCommStatus;
}
/**
* Returns the current enabled status of the robot
* \note You can also use the \c isEnabled() function
*/
DS::EnableStatus DS_Config::enableStatus() const {
return m_enableStatus;
}
/**
* Returns the current status of the radio communications
* \note You can also use the \c isConnectedToRadio() function
*/
DS::CommStatus DS_Config::radioCommStatus() const {
return m_radioCommStatus;
}
/**
* Returns the current status of the robot communications
* \note You can also use the \c isConnectedToRobot() function
*/
DS::CommStatus DS_Config::robotCommStatus() const {
return m_robotCommStatus;
}
/**
* Returns the current status of the robot code
* \note You can also use the \c isRobotCodeRunning() function
*/
DS::CodeStatus DS_Config::robotCodeStatus() const {
return m_codeStatus;
}
/**
* Returns the current voltage brownout status of the robot.
*/
DS::VoltageStatus DS_Config::voltageStatus() const {
return m_voltageStatus;
}
/**
* Returns the current operation status of the robot.
* \note You can also use the \c isEmergencyStopped() function
*/
DS::OperationStatus DS_Config::operationStatus() const {
return m_operationStatus;
}
/**
* Changes the \a team number and fires the appropriate signals if required
*/
void DS_Config::updateTeam (int team) {
if (m_team != team) {
m_team = team;
emit teamChanged (m_team);
qDebug() << "Team number set to" << team;
}
}
/**
* Changes the robot \a code status and fires the appropriate signals if
* required
*/
void DS_Config::setRobotCode (bool code) {
DS::CodeStatus status = DS::kCodeFailing;
if (code) status = DS::kCodeRunning;
updateRobotCodeStatus (status);
}
/**
* Changes the \a enabled status and fires the appropriate signals if required
*/
void DS_Config::setEnabled (bool enabled) {
DS::EnableStatus status = DS::kDisabled;
if (enabled) status = DS::kEnabled;
updateEnabled (status);
}
/**
* Changes the CPU \a usage and fires the appropriate signals if required
*/
void DS_Config::updateCpuUsage (int usage) {
m_cpuUsage = 0;
emit cpuUsageChanged (usage);
}
/**
* Changes the RAM \a usage and fires the appropriate signals if required
*/
void DS_Config::updateRamUsage (int usage) {
m_ramUsage = 0;
emit ramUsageChanged (usage);
}
/**
* Changes the disk \a usage and fires the appropriate signals if required
*/
void DS_Config::updateDiskUsage (int usage) {
m_diskUsage = 0;
emit diskUsageChanged (usage);
}
/**
* Changes the voltage \a brownout status and fires the appropriate signals
* if required.
*/
void DS_Config::setBrownout (bool brownout) {
DS::VoltageStatus status = DS::kVoltageNormal;
if (brownout) status = DS::kVoltageBrownout;
updateVoltageStatus (status);
}
/**
* Changes the \a estop status and fires the appropriate signals if required
*/
void DS_Config::setEmergencyStop (bool estop) {
DS::OperationStatus status = DS::kNormal;
if (estop) status = DS::kEmergencyStop;
updateOperationStatus (status);
}
/**
* Changes the robot \a voltage and fires the appropriate signals if required
*/
void DS_Config::updateVoltage (qreal voltage) {
/* Round voltage to two decimal places */
m_voltage = roundf (voltage * 100) / 100;
/* Avoid this: http://i.imgur.com/iAAi1bX.png */
if (m_voltage > DriverStation::getInstance()->maxBatteryVoltage())
m_voltage = DriverStation::getInstance()->maxBatteryVoltage();
/* Separate voltage into natural and decimal numbers */
int integer = static_cast<int> (m_voltage);
int decimal = static_cast<qreal> (m_voltage - integer) * 100;
/* Convert the obtained numbers into strings */
QString integer_str = QString::number (integer);
QString decimal_str = QString::number (decimal);
/* Prepend a 0 to the decimal numbers if required */
if (decimal < 10)
decimal_str.prepend ("0");
/* Emit signals */
emit voltageChanged (m_voltage);
emit voltageChanged (integer_str + "." + decimal_str + " V");
/* Log robot voltage */
m_logger->registerVoltage (m_voltage);
}
/**
* Changes the \a simulated status and fires the appropriate signals if
* required
*/
void DS_Config::updateSimulated (bool simulated) {
m_simulated = simulated;
emit simulatedChanged (simulated);
}
/**
* Changes the \a alliance and fires the appropriate signals if required
*/
void DS_Config::updateAlliance (Alliance alliance) {
if (m_alliance != alliance) {
m_alliance = alliance;
m_logger->registerAlliance (alliance);
}
emit allianceChanged (m_alliance);
}
/**
* Changes the \a position and fires the appropriate signals if required
*/
void DS_Config::updatePosition (Position position) {
if (m_position != position) {
m_position = position;
m_logger->registerPosition (position);
}
emit positionChanged (m_position);
}
/**
* Changes the robot code \a status and fires the appropriate signals if
* required
*/
void DS_Config::updateRobotCodeStatus (CodeStatus status) {
if (m_codeStatus != status) {
m_codeStatus = status;
m_logger->registerCodeStatus (status);
}
emit codeStatusChanged (m_codeStatus);
emit statusChanged (DriverStation::getInstance()->generalStatus());
}
/**
* Changes the robot control \a mode and fires the appropriate signals if
* required
*/
void DS_Config::updateControlMode (ControlMode mode) {
if (m_controlMode != mode) {
m_controlMode = mode;
m_logger->registerControlMode (mode);
}
emit controlModeChanged (m_controlMode);
emit statusChanged (DriverStation::getInstance()->generalStatus());
}
/**
* Changes the robot library \a version and fires the appropriate signals if
* required
*/
void DS_Config::updateLibVersion (const QString& version) {
if (m_libVersion != version) {
m_libVersion = version;
qDebug() << "LIB version set to" << version;
}
emit libVersionChanged (m_libVersion);
}
/**
* Changes the PCM \a version and fires the appropriate signals if required
*/
void DS_Config::updatePcmVersion (const QString& version) {
if (m_pcmVersion != version) {
m_pcmVersion = version;
qDebug() << "PCM version set to" << version;
}
emit pcmVersionChanged (m_pcmVersion);
}
/**
* Changes the PDP/PDB \a version and fires the appropriate signals if required
*/
void DS_Config::updatePdpVersion (const QString& version) {
if (m_pdpVersion != version) {
m_pdpVersion = version;
qDebug() << "PDP version set to" << version;
}
emit pdpVersionChanged (m_pdpVersion);
}
/**
* Changes the enabled \a status and fires the appropriate signals if required
*/
void DS_Config::updateEnabled (EnableStatus status) {
if (m_enableStatus != status) {
m_enableStatus = status;
if (status == DS::kEnabled) {
m_timer->restart();
m_timerEnabled = true;
}
else
m_timerEnabled = false;
m_logger->registerEnableStatus (status);
}
emit enabledChanged (m_enableStatus);
emit statusChanged (DriverStation::getInstance()->generalStatus());
}
/**
* Changes the FMS communication \a status and fires the appropriate signals
* if required
*/
void DS_Config::updateFMSCommStatus (CommStatus status) {
if (m_fmsCommStatus != status) {
m_fmsCommStatus = status;
qDebug() << "FMS comm. status set to" << status;
}
emit fmsCommStatusChanged (m_fmsCommStatus);
emit statusChanged (DriverStation::getInstance()->generalStatus());
}
/**
* Changes the radio communication \a status and fires the appropriate signals
* if required
*/
void DS_Config::updateRadioCommStatus (CommStatus status) {
if (m_radioCommStatus != status) {
m_radioCommStatus = status;
m_logger->registerRadioCommStatus (status);
}
emit radioCommStatusChanged (m_radioCommStatus);
}
/**
* Changes the robot communication \a status and fires the appropriate signals
* if required
*/
void DS_Config::updateRobotCommStatus (CommStatus status) {
if (m_robotCommStatus != status) {
m_robotCommStatus = status;
m_logger->registerRobotCommStatus (status);
}
emit robotCommStatusChanged (m_robotCommStatus);
emit statusChanged (DriverStation::getInstance()->generalStatus());
}
/**
* Changes the voltage brownout \a status and fires the appropriate signals
* if required
*/
void DS_Config::updateVoltageStatus (VoltageStatus status) {
if (m_voltageStatus != status) {
m_voltageStatus = status;
m_logger->registerVoltageStatus (status);
}
emit voltageStatusChanged (m_voltageStatus);
emit statusChanged (DriverStation::getInstance()->generalStatus());
}
/**
* Changes the robot operation \a status and fires the appropriate signals
* if required
*/
void DS_Config::updateOperationStatus (OperationStatus status) {
if (m_operationStatus != status) {
m_operationStatus = status;
updateEnabled (DS::kDisabled);
m_logger->registerOperationStatus (status);
}
emit operationStatusChanged (m_operationStatus);
emit statusChanged (DriverStation::getInstance()->generalStatus());
}
/**
* Calculates the elapsed time since the robot has been enabled (regardless of
* the operation mode).
*
* This function is called every 100 milliseconds.
*
* \note This function will not run if there is no communication status with
* the robot or if the robot is emergency stopped
* \note The elapsed time will be resetted when the user changes the control
* mode of the robot
*/
void DS_Config::updateElapsedTime() {
if (m_timerEnabled && isConnectedToRobot() && !isEmergencyStopped()) {
quint32 msec = m_timer->elapsed();
quint32 secs = (msec / 1000);
quint32 mins = (secs / 60) % 60;
secs = secs % 60;
msec = msec % 1000;
emit elapsedTimeChanged (msec);
emit elapsedTimeChanged (QString ("%1:%2.%3")
.arg (mins, 2, 10, QLatin1Char ('0'))
.arg (secs, 2, 10, QLatin1Char ('0'))
.arg (QString::number (msec).at (0)));
}
DS_Schedule (100, this, SLOT (updateElapsedTime()));
}
| 26.450172
| 80
| 0.654476
|
WinT-3794
|
3d03852efc50f17976123526503114185e2edf71
| 19,901
|
cpp
|
C++
|
scanmatcher/src/image_projection.cpp
|
rsasaki0109/li_slam_ros2
|
09e8cd3df514c10cbc1058896828dd1eb8e900be
|
[
"BSD-2-Clause"
] | 113
|
2020-07-09T01:08:53.000Z
|
2022-03-25T07:52:05.000Z
|
scanmatcher/src/image_projection.cpp
|
rsasaki0109/li_slam_ros2
|
09e8cd3df514c10cbc1058896828dd1eb8e900be
|
[
"BSD-2-Clause"
] | 5
|
2020-10-07T14:31:34.000Z
|
2021-08-01T13:01:03.000Z
|
scanmatcher/src/image_projection.cpp
|
rsasaki0109/li_slam_ros2
|
09e8cd3df514c10cbc1058896828dd1eb8e900be
|
[
"BSD-2-Clause"
] | 15
|
2020-07-11T13:50:01.000Z
|
2022-03-17T03:11:36.000Z
|
// BSD 3-Clause License
//
// Copyright (c) 2020, Tixiao Shan
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "scanmatcher/utility.h"
#include <pcl/console/print.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/conversions.h>
#include <pcl/impl/pcl_base.hpp>
typedef pcl::PointXYZI PointType;
struct PointXYZIRT
{
PCL_ADD_POINT4D
PCL_ADD_INTENSITY
uint16_t ring;
float time;
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
} EIGEN_ALIGN16;
POINT_CLOUD_REGISTER_POINT_STRUCT(
PointXYZIRT,
(float, x, x)(float, y, y)(float, z, z) (float, intensity, intensity)(
uint16_t, ring,
ring) (float, time, time)
)
const int queueLength = 500;
class ImageProjection : public ParamServer
{
private:
std::mutex imuLock;
std::mutex odoLock;
rclcpp::Subscription<sensor_msgs::msg::PointCloud2>::SharedPtr subLaserCloud;
rclcpp::Publisher<sensor_msgs::msg::PointCloud2>::SharedPtr pubLaserCloud;
rclcpp::Publisher<sensor_msgs::msg::PointCloud2>::SharedPtr pubExtractedCloud;
rclcpp::Subscription<sensor_msgs::msg::Imu>::SharedPtr subImu;
std::deque<sensor_msgs::msg::Imu> imuQueue;
rclcpp::Subscription<nav_msgs::msg::Odometry>::SharedPtr subOdom;
std::deque<nav_msgs::msg::Odometry> odomQueue;
std::deque<sensor_msgs::msg::PointCloud2> cloudQueue;
sensor_msgs::msg::PointCloud2 currentCloudMsg;
double * imuTime = new double[queueLength];
double * imuRotX = new double[queueLength];
double * imuRotY = new double[queueLength];
double * imuRotZ = new double[queueLength];
int imuPointerCur;
bool firstPointFlag;
Eigen::Affine3f transStartInverse;
pcl::PointCloud<PointXYZIRT>::Ptr laserCloudIn;
pcl::PointCloud<PointType>::Ptr fullCloud;
pcl::PointCloud<PointType>::Ptr extractedCloud;
int deskewFlag;
cv::Mat rangeMat;
bool odomDeskewFlag;
float odomIncreX;
float odomIncreY;
float odomIncreZ;
double timeScanCur;
double timeScanNext;
std_msgs::msg::Header cloudHeader;
public:
ImageProjection(const rclcpp::NodeOptions & options)
: ParamServer("image_projection", options),
deskewFlag(0)
{
auto imu_callback =
[this](const sensor_msgs::msg::Imu::ConstPtr msg) -> void
{
imuHandler(msg);
};
subImu = create_subscription<sensor_msgs::msg::Imu>(
imuTopic, rclcpp::SensorDataQoS(), imu_callback);
auto odom_callback =
[this](const nav_msgs::msg::Odometry::ConstPtr msg) -> void
{
odometryHandler(msg);
};
subOdom = create_subscription<nav_msgs::msg::Odometry>(
odomTopic, rclcpp::SensorDataQoS(), odom_callback);
auto lc_callback =
[this](const sensor_msgs::msg::PointCloud2::ConstPtr msg) -> void
{
cloudHandler(msg);
};
subLaserCloud = create_subscription<sensor_msgs::msg::PointCloud2>(
pointCloudTopic, 5, lc_callback);
pubExtractedCloud = create_publisher<sensor_msgs::msg::PointCloud2>("cloud_deskewed", 2000);
allocateMemory();
resetParameters();
}
void allocateMemory()
{
laserCloudIn.reset(new pcl::PointCloud<PointXYZIRT>());
fullCloud.reset(new pcl::PointCloud<PointType>());
extractedCloud.reset(new pcl::PointCloud<PointType>());
fullCloud->points.resize(N_SCAN * Horizon_SCAN);
resetParameters();
}
void resetParameters()
{
laserCloudIn->clear();
extractedCloud->clear();
// reset range matrix for range image projection
rangeMat = cv::Mat(N_SCAN, Horizon_SCAN, CV_32F, cv::Scalar::all(FLT_MAX));
imuPointerCur = 0;
firstPointFlag = true;
odomDeskewFlag = false;
for (int i = 0; i < queueLength; ++i) {
imuTime[i] = 0;
imuRotX[i] = 0;
imuRotY[i] = 0;
imuRotZ[i] = 0;
}
}
~ImageProjection() {}
void imuHandler(const sensor_msgs::msg::Imu::ConstPtr & imuMsg)
{
sensor_msgs::msg::Imu thisImu = imuConverter(*imuMsg);
std::lock_guard<std::mutex> lock1(imuLock);
imuQueue.push_back(thisImu);
// debug IMU data
// cout << std::setprecision(6);
// cout << "IMU acc: " << endl;
// cout << "x: " << thisImu.linear_acceleration.x <<
// ", y: " << thisImu.linear_acceleration.y <<
// ", z: " << thisImu.linear_acceleration.z << endl;
// cout << "IMU gyro: " << endl;
// cout << "x: " << thisImu.angular_velocity.x <<
// ", y: " << thisImu.angular_velocity.y <<
// ", z: " << thisImu.angular_velocity.z << endl;
// double imuRoll, imuPitch, imuYaw;
// tf::Quaternion orientation;
// tf::quaternionMsgToTF(thisImu.orientation, orientation);
// tf::Matrix3x3(orientation).getRPY(imuRoll, imuPitch, imuYaw);
// cout << "IMU roll pitch yaw: " << endl;
// cout << "roll: " << imuRoll << ", pitch: " << imuPitch << ", yaw: " << imuYaw << endl << endl;
}
void odometryHandler(const nav_msgs::msg::Odometry::ConstPtr & odometryMsg)
{
std::lock_guard<std::mutex> lock2(odoLock);
odomQueue.push_back(*odometryMsg);
}
void cloudHandler(const sensor_msgs::msg::PointCloud2::ConstPtr & laserCloudMsg)
{
if (!cachePointCloud(laserCloudMsg)) {
return;
}
if (!deskewInfo()) {
return;
}
projectPointCloud();
cloudExtraction();
publishCloud();
resetParameters();
}
bool cachePointCloud(const sensor_msgs::msg::PointCloud2::ConstPtr & laserCloudMsg)
{
// cache point cloud
cloudQueue.push_back(*laserCloudMsg);
if (cloudQueue.size() <= 2) {
return false;
} else {
currentCloudMsg = cloudQueue.front();
cloudQueue.pop_front();
cloudHeader = currentCloudMsg.header;
// timeScanCur = cloudHeader.stamp.toSec();
timeScanCur = cloudHeader.stamp.sec + cloudHeader.stamp.nanosec * 1e-9;
// timeScanNext = cloudQueue.front().header.stamp.toSec();
timeScanNext = cloudQueue.front().header.stamp.sec + cloudQueue.front().header.stamp.nanosec *
1e-9;
}
// convert cloud
pcl::fromROSMsg(currentCloudMsg, *laserCloudIn);
// check dense flag
if (laserCloudIn->is_dense == false) {
RCLCPP_ERROR(
get_logger(), "Point cloud is not in dense format, please remove NaN points first!");
rclcpp::shutdown();
}
// check ring channel
static int ringFlag = 0;
if (ringFlag == 0) {
ringFlag = -1;
for (int i = 0; i < currentCloudMsg.fields.size(); ++i) {
if (currentCloudMsg.fields[i].name == "ring") {
ringFlag = 1;
break;
}
}
if (ringFlag == -1) {
RCLCPP_ERROR(
get_logger(),
"Point cloud ring channel not available, please configure your point cloud data!");
rclcpp::shutdown();
}
}
// check point time
if (deskewFlag == 0) {
deskewFlag = -1;
for (int i = 0; i < currentCloudMsg.fields.size(); ++i) {
if (currentCloudMsg.fields[i].name == "time") {
deskewFlag = 1;
break;
}
}
if (deskewFlag == -1) {
RCLCPP_WARN(
get_logger(),
"Point cloud timestamp not available, deskew function disabled, system will drift significantly!");
}
}
return true;
}
bool deskewInfo()
{
std::lock_guard<std::mutex> lock1(imuLock);
std::lock_guard<std::mutex> lock2(odoLock);
// make sure IMU data available for the scan
auto t_f = imuQueue.front().header.stamp.sec +
imuQueue.front().header.stamp.nanosec * 1e-9;
auto t_b = imuQueue.back().header.stamp.sec +
imuQueue.back().header.stamp.nanosec * 1e-9;
// if (imuQueue.empty() || imuQueue.front().header.stamp.toSec() > timeScanCur || imuQueue.back().header.stamp.toSec() < timeScanNext)
if (imuQueue.empty() || t_f > timeScanCur || t_b < timeScanNext) {
RCLCPP_DEBUG(get_logger(), "Waiting for IMU data ...");
return false;
}
imuDeskewInfo();
odomDeskewInfo();
return true;
}
void imuDeskewInfo()
{
while (!imuQueue.empty()) {
auto t_f = imuQueue.front().header.stamp.sec +
imuQueue.front().header.stamp.nanosec * 1e-9;
if (t_f < timeScanCur - 0.01) {
imuQueue.pop_front();
} else {
break;
}
}
if (imuQueue.empty()) {
return;
}
imuPointerCur = 0;
for (int i = 0; i < imuQueue.size(); ++i) {
sensor_msgs::msg::Imu thisImuMsg = imuQueue[i];
//double currentImuTime = thisImuMsg.header.stamp.toSec();
double currentImuTime = thisImuMsg.header.stamp.sec +
thisImuMsg.header.stamp.nanosec * 1e-9;
if (currentImuTime > timeScanNext + 0.01) {
break;
}
if (imuPointerCur == 0) {
imuRotX[0] = 0;
imuRotY[0] = 0;
imuRotZ[0] = 0;
imuTime[0] = currentImuTime;
++imuPointerCur;
continue;
}
// get angular velocity
double angular_x, angular_y, angular_z;
imuAngular2rosAngular(&thisImuMsg, &angular_x, &angular_y, &angular_z);
// integrate rotation
double timeDiff = currentImuTime - imuTime[imuPointerCur - 1];
imuRotX[imuPointerCur] = imuRotX[imuPointerCur - 1] + angular_x * timeDiff;
imuRotY[imuPointerCur] = imuRotY[imuPointerCur - 1] + angular_y * timeDiff;
imuRotZ[imuPointerCur] = imuRotZ[imuPointerCur - 1] + angular_z * timeDiff;
imuTime[imuPointerCur] = currentImuTime;
++imuPointerCur;
}
--imuPointerCur;
if (imuPointerCur <= 0) {
return;
}
}
void odomDeskewInfo()
{
while (!odomQueue.empty()) {
auto time = odomQueue.front().header.stamp.sec +
odomQueue.front().header.stamp.nanosec * 1e-9;
//if (odomQueue.front().header.stamp.toSec() < timeScanCur - 0.01)
if (time < timeScanCur - 0.01) {
odomQueue.pop_front();
} else {
break;
}
}
if (odomQueue.empty()) {
return;
}
auto t_f = odomQueue.front().header.stamp.sec +
odomQueue.front().header.stamp.nanosec * 1e-9;
// if (odomQueue.front().header.stamp.toSec() > timeScanCur)
if (t_f > timeScanCur) {
return;
}
// get start odometry at the beinning of the scan
nav_msgs::msg::Odometry startOdomMsg;
for (int i = 0; i < odomQueue.size(); ++i) {
startOdomMsg = odomQueue[i];
if (ROS_TIME(&startOdomMsg) < timeScanCur) {
continue;
} else {
break;
}
}
tf2::Quaternion orientation;
// tf2::quaternionMsgToTF(startOdomMsg.pose.pose.orientation, orientation);
tf2::fromMsg(startOdomMsg.pose.pose.orientation, orientation);
double roll, pitch, yaw;
tf2::Matrix3x3(orientation).getRPY(roll, pitch, yaw);
// get end odometry at the end of the scan
odomDeskewFlag = false;
auto t_b = odomQueue.back().header.stamp.sec +
odomQueue.back().header.stamp.nanosec * 1e-9;
if (t_b < timeScanNext) {
return;
}
nav_msgs::msg::Odometry endOdomMsg;
for (int i = 0; i < odomQueue.size(); ++i) {
endOdomMsg = odomQueue[i];
if (ROS_TIME(&endOdomMsg) < timeScanNext) {
continue;
} else {
break;
}
}
if (int(round(startOdomMsg.pose.covariance[0])) != int(round(endOdomMsg.pose.covariance[0]))) {
return;
}
Eigen::Affine3f transBegin = pcl::getTransformation(
startOdomMsg.pose.pose.position.x,
startOdomMsg.pose.pose.position.y,
startOdomMsg.pose.pose.position.z, roll,
pitch, yaw);
tf2::fromMsg(endOdomMsg.pose.pose.orientation, orientation);
tf2::Matrix3x3(orientation).getRPY(roll, pitch, yaw);
Eigen::Affine3f transEnd = pcl::getTransformation(
endOdomMsg.pose.pose.position.x,
endOdomMsg.pose.pose.position.y,
endOdomMsg.pose.pose.position.z, roll, pitch,
yaw);
Eigen::Affine3f transBt = transBegin.inverse() * transEnd;
float rollIncre, pitchIncre, yawIncre;
pcl::getTranslationAndEulerAngles(
transBt, odomIncreX, odomIncreY, odomIncreZ, rollIncre,
pitchIncre, yawIncre);
odomDeskewFlag = true;
}
void findRotation(double pointTime, float * rotXCur, float * rotYCur, float * rotZCur)
{
*rotXCur = 0; *rotYCur = 0; *rotZCur = 0;
int imuPointerFront = 0;
while (imuPointerFront < imuPointerCur) {
if (pointTime < imuTime[imuPointerFront]) {
break;
}
++imuPointerFront;
}
if (pointTime > imuTime[imuPointerFront] || imuPointerFront == 0) {
*rotXCur = imuRotX[imuPointerFront];
*rotYCur = imuRotY[imuPointerFront];
*rotZCur = imuRotZ[imuPointerFront];
} else {
int imuPointerBack = imuPointerFront - 1;
double ratioFront = (pointTime - imuTime[imuPointerBack]) /
(imuTime[imuPointerFront] - imuTime[imuPointerBack]);
double ratioBack = (imuTime[imuPointerFront] - pointTime) /
(imuTime[imuPointerFront] - imuTime[imuPointerBack]);
*rotXCur = imuRotX[imuPointerFront] * ratioFront + imuRotX[imuPointerBack] * ratioBack;
*rotYCur = imuRotY[imuPointerFront] * ratioFront + imuRotY[imuPointerBack] * ratioBack;
*rotZCur = imuRotZ[imuPointerFront] * ratioFront + imuRotZ[imuPointerBack] * ratioBack;
}
}
void findPosition(double relTime, float * posXCur, float * posYCur, float * posZCur)
{
*posXCur = 0; *posYCur = 0; *posZCur = 0;
// If the sensor moves relatively slow, like walking speed, positional deskew seems to have little benefits. Thus code below is commented.
// if (odomDeskewFlag == false)
// return;
// float ratio = relTime / (timeScanNext - timeScanCur);
// *posXCur = ratio * odomIncreX;
// *posYCur = ratio * odomIncreY;
// *posZCur = ratio * odomIncreZ;
}
PointType deskewPoint(PointType * point, double relTime)
{
if (deskewFlag == -1) {
return *point;
}
double pointTime = timeScanCur + relTime;
float rotXCur, rotYCur, rotZCur;
findRotation(pointTime, &rotXCur, &rotYCur, &rotZCur);
float posXCur, posYCur, posZCur;
findPosition(relTime, &posXCur, &posYCur, &posZCur);
if (firstPointFlag == true) {
transStartInverse =
(pcl::getTransformation(posXCur, posYCur, posZCur, rotXCur, rotYCur, rotZCur)).inverse();
firstPointFlag = false;
}
// transform points to start
Eigen::Affine3f transFinal = pcl::getTransformation(
posXCur, posYCur, posZCur, rotXCur, rotYCur,
rotZCur);
Eigen::Affine3f transBt = transStartInverse * transFinal;
PointType newPoint;
newPoint.x =
transBt(
0,
0) * point->x + transBt(0, 1) * point->y + transBt(0, 2) * point->z + transBt(0, 3);
newPoint.y =
transBt(
1,
0) * point->x + transBt(1, 1) * point->y + transBt(1, 2) * point->z + transBt(1, 3);
newPoint.z =
transBt(
2,
0) * point->x + transBt(2, 1) * point->y + transBt(2, 2) * point->z + transBt(2, 3);
newPoint.intensity = point->intensity;
return newPoint;
}
void projectPointCloud()
{
int cloudSize = laserCloudIn->points.size();
// range image projection
for (int i = 0; i < cloudSize; ++i) {
PointType thisPoint;
thisPoint.x = laserCloudIn->points[i].x;
thisPoint.y = laserCloudIn->points[i].y;
thisPoint.z = laserCloudIn->points[i].z;
thisPoint.intensity = laserCloudIn->points[i].intensity;
int rowIdn = laserCloudIn->points[i].ring;
if (rowIdn < 0 || rowIdn >= N_SCAN) {
continue;
}
float horizonAngle = atan2(thisPoint.x, thisPoint.y) * 180 / M_PI;
float ang_res_x = 360.0 / float(Horizon_SCAN);
int columnIdn = -round((horizonAngle - 90.0) / ang_res_x) + Horizon_SCAN / 2;
if (columnIdn >= Horizon_SCAN) {
columnIdn -= Horizon_SCAN;
}
if (columnIdn < 0 || columnIdn >= Horizon_SCAN) {
continue;
}
float range = pointDistance(thisPoint);
if (range < 1.0) {
continue;
}
if (rangeMat.at<float>(rowIdn, columnIdn) != FLT_MAX) {continue;}
// for the amsterdam dataset
// if (range < 6.0 && rowIdn <= 7 && (columnIdn >= 1600 || columnIdn <= 200))
// continue;
// if (thisPoint.z < -2.0)
// continue;
rangeMat.at<float>(rowIdn, columnIdn) = range;
thisPoint = deskewPoint(&thisPoint, laserCloudIn->points[i].time);
int index = columnIdn + rowIdn * Horizon_SCAN;
fullCloud->points[index] = thisPoint;
}
}
void cloudExtraction()
{
int count = 0;
// extract segmented cloud for lidar odometry
for (int i = 0; i < N_SCAN; ++i) {
for (int j = 0; j < Horizon_SCAN; ++j) {
if (rangeMat.at<float>(i, j) != FLT_MAX) {
// save extracted cloud
extractedCloud->push_back(fullCloud->points[j + i * Horizon_SCAN]);
// size of extracted cloud
++count;
}
}
}
}
void publishCloud()
{
sensor_msgs::msg::PointCloud2 tempCloud;
pcl::toROSMsg(*extractedCloud, tempCloud);
tempCloud.header.stamp = cloudHeader.stamp;
tempCloud.header.frame_id = "base_link";
pubExtractedCloud->publish(tempCloud);
}
template<typename T>
void imuAngular2rosAngular(
sensor_msgs::msg::Imu * thisImuMsg, T * angular_x, T * angular_y,
T * angular_z)
{
*angular_x = thisImuMsg->angular_velocity.x;
*angular_y = thisImuMsg->angular_velocity.y;
*angular_z = thisImuMsg->angular_velocity.z;
}
template<typename T>
void imuAccel2rosAccel(sensor_msgs::msg::Imu * thisImuMsg, T * acc_x, T * acc_y, T * acc_z)
{
*acc_x = thisImuMsg->linear_acceleration.x;
*acc_y = thisImuMsg->linear_acceleration.y;
*acc_z = thisImuMsg->linear_acceleration.z;
}
float pointDistance(PointType p)
{
return sqrt(p.x * p.x + p.y * p.y + p.z * p.z);
}
float pointDistance(PointType p1, PointType p2)
{
return sqrt(
(p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y) + (p1.z - p2.z) *
(p1.z - p2.z));
}
};
int main(int argc, char ** argv)
{
rclcpp::init(argc, argv);
rclcpp::NodeOptions options;
options.use_intra_process_comms(true);
rclcpp::executors::SingleThreadedExecutor exec;
auto ip = std::make_shared<ImageProjection>(options);
exec.add_node(ip);
std::cout << "\033[1;32m----> ImageProjection Started.\033[0m" << std::endl;
exec.spin();
rclcpp::shutdown();
return 0;
return 0;
}
| 29.309278
| 142
| 0.64042
|
rsasaki0109
|
3d0436217b956386d9d0ab1cb2236b094b880d8f
| 1,531
|
hpp
|
C++
|
include/Aheuiplusplus/command_line.hpp
|
JellyBrick/Aheuiplusplus
|
e4303582517d6893850d120c772244486017f873
|
[
"MIT"
] | null | null | null |
include/Aheuiplusplus/command_line.hpp
|
JellyBrick/Aheuiplusplus
|
e4303582517d6893850d120c772244486017f873
|
[
"MIT"
] | null | null | null |
include/Aheuiplusplus/command_line.hpp
|
JellyBrick/Aheuiplusplus
|
e4303582517d6893850d120c772244486017f873
|
[
"MIT"
] | null | null | null |
#ifndef AHEUIPLUSPLUS_HEADER_PROGRAM_OPTIONS_HPP
#define AHEUIPLUSPLUS_HEADER_PROGRAM_OPTIONS_HPP
#include <Aheuiplusplus/version.hpp>
#include <cstdio>
#include <string>
namespace app
{
class command_line final
{
public:
command_line() = default;
command_line(const command_line& data);
~command_line() = default;
public:
command_line& operator=(const command_line& data);
bool operator==(const command_line& data) const = delete;
bool operator!=(const command_line& data) const = delete;
public:
bool parse(int argc, char** argv);
bool parse(std::FILE* output_stream, int argc, char** argv);
public:
bool option_aheui() const noexcept;
void option_aheui(bool new_option_aheui) noexcept;
bool option_interpreting_mode() const noexcept;
void option_interpreting_mode(bool new_option_interpreting_mode) noexcept;
version option_version() const noexcept;
void option_version(version new_option_version) noexcept;
bool option_loud_mode() const noexcept;
void option_loud_mode(bool new_option_loud_mode) noexcept;
bool option_input_end_mode() const noexcept;
void option_input_end_mode(bool new_option_input_end_mode) noexcept;
std::string option_code_path() const;
void option_code_path(const std::string& new_option_code_path);
private:
bool option_aheui_ = false;
bool option_interpreting_mode_ = false;
version option_version_ = version::none;
bool option_loud_mode_ = false;
bool option_input_end_mode_ = false;
std::string option_code_path_;
};
}
#endif
| 27.836364
| 76
| 0.779882
|
JellyBrick
|
3d0bc70aa4b41d04e032cace0dc9d1ef09d4c7c6
| 60,197
|
cpp
|
C++
|
src/viewer/Scene.cpp
|
VladSerhiienko/Viewer
|
b0ea7f299e234a677ea15e82c35b713e59aeb236
|
[
"MIT"
] | 10
|
2017-12-29T09:35:44.000Z
|
2019-10-03T17:20:00.000Z
|
src/viewer/Scene.cpp
|
VladSerhiienko/Viewer
|
b0ea7f299e234a677ea15e82c35b713e59aeb236
|
[
"MIT"
] | null | null | null |
src/viewer/Scene.cpp
|
VladSerhiienko/Viewer
|
b0ea7f299e234a677ea15e82c35b713e59aeb236
|
[
"MIT"
] | 1
|
2019-03-18T06:03:40.000Z
|
2019-03-18T06:03:40.000Z
|
#include "Scene.h"
#include <apemode/platform/AppState.h>
#include <apemode/platform/memory/MemoryManager.h>
//#define APEMODEVK_NO_GOOGLE_DRACO
#ifndef APEMODEVK_NO_GOOGLE_DRACO
#ifdef ERROR
#undef ERROR
#endif
#include <draco/compression/decode.h>
#include <draco/animation/keyframe_animation_decoder.h>
#endif
#ifndef PI
#define PI 3.14159265358979323846264338327950288
#endif
constexpr float toRadsFactor = float( PI ) / 180.0f;
namespace {
template < typename T >
inline bool IsNotNullAndNotEmpty( const flatbuffers::Vector< T > *pVector ) {
return pVector && pVector->size( );
}
bool IsValid( const float a ) {
return !isnan( a ) && !isinf( a );
}
//bool IsIdentity( const apemode::XMFLOAT4X4 m ) {
// using namespace apemodexm;
// return IsNearlyEqual( m._11, 1 ) && IsNearlyEqual( m._12, 0 ) && IsNearlyEqual( m._13, 0 ) && IsNearlyEqual( m._14, 0 ) &&
// IsNearlyEqual( m._21, 0 ) && IsNearlyEqual( m._22, 1 ) && IsNearlyEqual( m._23, 0 ) && IsNearlyEqual( m._24, 0 ) &&
// IsNearlyEqual( m._31, 0 ) && IsNearlyEqual( m._32, 0 ) && IsNearlyEqual( m._33, 1 ) && IsNearlyEqual( m._34, 0 ) &&
// IsNearlyEqual( m._41, 0 ) && IsNearlyEqual( m._42, 0 ) && IsNearlyEqual( m._43, 0 ) && IsNearlyEqual( m._44, 1 );
//}
bool IsValid( const apemode::XMFLOAT4X4 m ) {
using namespace apemodexm;
return /*!IsNearlyEqual( m._11, 0 ) && */ IsValid( m._12 ) && IsValid( m._13 ) && IsValid( m._14 ) && IsValid( m._21 ) &&
/*!IsNearlyEqual( m._22, 0 ) && */ IsValid( m._23 ) && IsValid( m._24 ) && IsValid( m._31 ) && IsValid( m._32 ) &&
/*!IsNearlyEqual( m._33, 0 ) && */ IsValid( m._34 ) && IsValid( m._41 ) && IsValid( m._42 ) && IsValid( m._43 ) &&
/*!IsNearlyEqual( m._44, 0 ) && */ IsValid( m._11 ) && IsValid( m._22 ) && IsValid( m._33 ) && IsValid( m._44 ) &&
false == ( IsNearlyZero( m._12 ) && IsNearlyZero( m._13 ) && IsNearlyZero( m._14 ) && IsNearlyZero( m._21 ) &&
IsNearlyZero( m._23 ) && IsNearlyZero( m._24 ) && IsNearlyZero( m._31 ) && IsNearlyZero( m._32 ) &&
IsNearlyZero( m._34 ) && IsNearlyZero( m._41 ) && IsNearlyZero( m._42 ) && IsNearlyZero( m._43 ) &&
IsNearlyZero( m._11 ) && IsNearlyZero( m._22 ) && IsNearlyZero( m._33 ) && IsNearlyZero( m._44 ) );
}
bool IsValid( const apemode::XMMATRIX m ) {
apemode::XMFLOAT4X4 storedMatrix;
XMStoreFloat4x4( &storedMatrix, m );
return IsValid( storedMatrix );
}
} // namespace
using namespace apemode;
struct SceneAnimLayerId {
union {
struct {
uint16_t AnimStackIndex;
uint16_t AnimLayerIndex;
};
uint32_t AnimLayerCompositeId;
};
};
struct SceneAnimNodeId {
union {
struct {
uint32_t NodeId;
SceneAnimLayerId AnimLayerId;
};
uint64_t AnimNodeCompositeId;
};
};
inline XMFLOAT4 ToVec4( apemodefb::Vec4Fb const v ) {
return XMFLOAT4{v.x( ), v.y( ), v.z( ), v.w( )};
}
inline XMFLOAT3 ToVec3( apemodefb::Vec3Fb const v ) {
return XMFLOAT3{v.x( ), v.y( ), v.z( )};
}
inline XMFLOAT2 ToVec2( apemodefb::Vec2Fb const v ) {
return XMFLOAT2{v.x( ), v.y( )};
}
bool apemode::SceneNodeTransform::Validate( ) const {
return IsValid( Translation.x ) && IsValid( Translation.y ) && IsValid( Translation.z ) && IsValid( RotationOffset.x ) &&
IsValid( RotationOffset.y ) && IsValid( RotationOffset.z ) && IsValid( RotationPivot.x ) &&
IsValid( RotationPivot.y ) && IsValid( RotationPivot.z ) && IsValid( PreRotation.x ) && IsValid( PreRotation.y ) &&
IsValid( PreRotation.z ) && IsValid( PostRotation.x ) && IsValid( PostRotation.y ) && IsValid( PostRotation.z ) &&
IsValid( Rotation.x ) && IsValid( Rotation.y ) && IsValid( Rotation.z ) && IsValid( ScalingOffset.x ) &&
IsValid( ScalingOffset.y ) && IsValid( ScalingOffset.z ) && IsValid( ScalingPivot.x ) && IsValid( ScalingPivot.y ) &&
IsValid( ScalingPivot.z ) && IsValid( Scaling.x ) && IsValid( Scaling.y ) && IsValid( Scaling.z ) &&
IsValid( GeometricTranslation.x ) && IsValid( GeometricTranslation.y ) && IsValid( GeometricTranslation.z ) &&
IsValid( GeometricRotation.x ) && IsValid( GeometricRotation.y ) && IsValid( GeometricRotation.z ) &&
IsValid( GeometricScaling.x ) && IsValid( GeometricScaling.y ) && IsValid( GeometricScaling.z ) &&
!IsNearlyZero( Scaling.x ) && !IsNearlyZero( Scaling.y ) && !IsNearlyZero( Scaling.z ) &&
!IsNearlyZero( GeometricScaling.x ) && !IsNearlyZero( GeometricScaling.y ) && !IsNearlyZero( GeometricScaling.z );
}
XMMATRIX XMMatrixRotationOrdered( const XMFLOAT3 v, detail::ERotationOrder eRotOrder ) {
// return XMMatrixRotationZ( v.z ) * XMMatrixRotationY( v.y ) * XMMatrixRotationX( v.x );
switch ( eRotOrder ) {
case detail::eRotationOrder_EulerXYZ:
return XMMatrixRotationX( v.x ) * XMMatrixRotationY( v.y ) * XMMatrixRotationZ( v.z ); //
case detail::eRotationOrder_EulerXZY:
return XMMatrixRotationX( v.x ) * XMMatrixRotationZ( v.z ) * XMMatrixRotationY( v.y ); //
case detail::eRotationOrder_EulerYZX:
return XMMatrixRotationY( v.y ) * XMMatrixRotationZ( v.z ) * XMMatrixRotationX( v.x ); //
case detail::eRotationOrder_EulerYXZ:
return XMMatrixRotationY( v.y ) * XMMatrixRotationX( v.x ) * XMMatrixRotationZ( v.z ); //
case detail::eRotationOrder_EulerZXY:
return XMMatrixRotationZ( v.z ) * XMMatrixRotationX( v.x ) * XMMatrixRotationY( v.y ); //
case detail::eRotationOrder_EulerZYX:
return XMMatrixRotationZ( v.z ) * XMMatrixRotationY( v.y ) * XMMatrixRotationX( v.x );
case detail::eRotationOrder_EulerSphericXYZ:
return XMMatrixRotationX( v.x ) * XMMatrixRotationY( v.y ) * XMMatrixRotationZ( v.z );
}
assert( false && "Unhandled rotation orders." );
return XMMatrixRotationX( v.x ) * XMMatrixRotationY( v.y ) * XMMatrixRotationZ( v.z );
}
XMMATRIX XMMatrixRotationOrderedInversed( XMFLOAT3 v, const detail::ERotationOrder eRotOrder ) {
v.x = -v.x;
v.y = -v.y;
v.z = -v.z;
return XMMatrixRotationOrdered( v, eRotOrder );
}
XMMATRIX XMMatrixRotationZYX( const XMFLOAT3 *v ) {
return XMMatrixRotationX( v->x ) *
XMMatrixRotationY( v->y ) *
XMMatrixRotationZ( v->z );
}
void apemode::SceneNodeTransform::ApplyLimits( const SceneNodeTransformLimits &limits ) {
#define CLAMP_PROPERTY_COMPONENT( P ) \
if ( limits.Is##P##MaxActive.x ) { \
P.x = std::min( P.x, limits.P##Max.x ); \
} \
if ( limits.Is##P##MinActive.x ) { \
P.x = std::max( P.x, limits.P##Min.x ); \
} \
if ( limits.Is##P##MaxActive.x ) { \
P.y = std::min( P.y, limits.P##Max.y ); \
} \
if ( limits.Is##P##MinActive.x ) { \
P.y = std::max( P.y, limits.P##Min.y ); \
} \
if ( limits.Is##P##MaxActive.x ) { \
P.z = std::min( P.z, limits.P##Max.z ); \
} \
if ( limits.Is##P##MinActive.x ) { \
P.z = std::max( P.z, limits.P##Min.z ); \
}
CLAMP_PROPERTY_COMPONENT( Translation );
CLAMP_PROPERTY_COMPONENT( Rotation );
CLAMP_PROPERTY_COMPONENT( Scaling );
#undef CLAMP_PROPERTY_COMPONENT
}
XMMATRIX apemode::SceneNodeTransform::CalculateLocalMatrix( const detail::ERotationOrder eOrder ) const {
// return XMMatrixTranslationFromVector( XMLoadFloat3( &Translation ) ) *
// XMMatrixRotationOrdered( Rotation, eOrder ) *
// XMMatrixScalingFromVector( XMLoadFloat3( &Scaling ) );
// return XMMatrixScalingFromVector( XMLoadFloat3( &Scaling ) ) *
// XMMatrixRotationOrdered( Rotation, eOrder ) *
// XMMatrixTranslationFromVector( XMLoadFloat3( &Translation ) );
//
// return XMMatrixTranslationFromVector( XMLoadFloat3( &Translation ) ) *
// XMMatrixTranslationFromVector( XMLoadFloat3( &RotationOffset ) ) *
// XMMatrixTranslationFromVector( XMLoadFloat3( &RotationPivot ) ) *
// XMMatrixRotationOrdered( PreRotation, eOrder ) *
// XMMatrixRotationOrdered( Rotation, eOrder ) *
// XMMatrixRotationOrderedInversed( PostRotation, eOrder ) *
// XMMatrixTranslationFromVector( XMVectorNegate( XMLoadFloat3( &RotationPivot ) ) ) *
// XMMatrixTranslationFromVector( XMLoadFloat3( &ScalingOffset ) ) *
// XMMatrixTranslationFromVector( XMLoadFloat3( &ScalingPivot ) ) *
// XMMatrixScalingFromVector( XMLoadFloat3( &Scaling ) ) *
// XMMatrixTranslationFromVector( XMVectorNegate( XMLoadFloat3( &ScalingPivot ) ) );
return XMMatrixTranslationFromVector( XMVectorNegate( XMLoadFloat3( &ScalingPivot ) ) ) *
XMMatrixScalingFromVector( XMLoadFloat3( &Scaling ) ) *
XMMatrixTranslationFromVector( XMLoadFloat3( &ScalingPivot ) ) *
XMMatrixTranslationFromVector( XMLoadFloat3( &ScalingOffset ) ) *
XMMatrixTranslationFromVector( XMVectorNegate( XMLoadFloat3( &RotationPivot ) ) ) *
XMMatrixRotationOrderedInversed( PostRotation, eOrder ) *
XMMatrixRotationOrdered( Rotation, eOrder ) *
XMMatrixRotationOrdered( PreRotation, eOrder ) *
XMMatrixTranslationFromVector( XMLoadFloat3( &RotationPivot ) ) *
XMMatrixTranslationFromVector( XMLoadFloat3( &RotationOffset ) ) *
XMMatrixTranslationFromVector( XMLoadFloat3( &Translation ) );
}
XMMATRIX apemode::SceneNodeTransform::CalculateGeometricMatrix( const detail::ERotationOrder eOrder ) const {
return XMMatrixScalingFromVector( XMLoadFloat3( &GeometricScaling ) ) *
XMMatrixRotationOrdered( GeometricRotation, eOrder ) *
XMMatrixTranslationFromVector( XMLoadFloat3( &GeometricTranslation ) );
}
void apemode::Scene::InitializeTransformFrame( SceneNodeTransformFrame &t ) const {
t.Transforms.resize( Nodes.size( ) );
}
const apemode::SceneNodeAnimCurveIds *apemode::Scene::GetAnimCurveIds( const uint32_t nodeId,
const uint16_t animStackId,
const uint16_t animLayerId ) const {
if ( ! AnimNodeIdToAnimCurveIds.empty( ) ) {
SceneAnimNodeId animNodeCompositeId;
animNodeCompositeId.NodeId = nodeId;
animNodeCompositeId.AnimLayerId.AnimStackIndex = animStackId;
animNodeCompositeId.AnimLayerId.AnimLayerIndex = animLayerId;
const auto animCurveIdsIt = AnimNodeIdToAnimCurveIds.find( animNodeCompositeId.AnimNodeCompositeId );
if ( animCurveIdsIt != AnimNodeIdToAnimCurveIds.end( ) ) {
assert( AnimNodeIdToAnimCurveIds.end( ) != animCurveIdsIt );
return &animCurveIdsIt->second;
}
}
return nullptr;
}
inline XMMATRIX CalculateOffsetMatrix( const XMMATRIX invBindPoseMatrix, const XMMATRIX currentAnimatedMatrix ) {
return invBindPoseMatrix * currentAnimatedMatrix;
}
void apemode::Scene::UpdateSkinMatrices( const SceneSkin & skin,
const SceneNodeTransformFrame *pSceneAnimatedFrame,
const XMMATRIX nodeWorldTransform,
XMFLOAT4X4 * pOffsetMatrices,
XMFLOAT4X4 * pNormalMatrices,
size_t matrixCount ) const {
assert( matrixCount >= skin.LinkIds.size( ) );
for ( size_t i = 0; i < skin.LinkIds.size( ); ++i ) {
uint32_t nodeId = skin.LinkIds[ i ];
XMMATRIX currentWorldMatrix = pSceneAnimatedFrame->Transforms[ nodeId ].WorldMatrix;
// currentWorldMatrix = XMMatrixInverse(0, nodeWorldTransform) * currentWorldMatrix;
// const SceneSkeleton &skeleton = Skeletons[ skin.SkeletonId ];
// const uint32_t nodeIndex = skin.SkeletonNodeIndices[ i ];
// assert( nodeIndex < skeleton.NodeIds.size( ) );
// const XMMATRIX currentWorldMatrix = pSkeletonAnimatedFrame->Transforms[ nodeIndex ].WorldMatrix;
// const XMMATRIX currentWorldMatrix = pSkeletonAnimatedFrame->Transforms[ nodeIndex ].HierarchicalMatrix;
const XMMATRIX invBindPoseMatrix = skin.InvBindPoseMatrices[ i ];
const XMMATRIX offsetMatrix = CalculateOffsetMatrix( invBindPoseMatrix , currentWorldMatrix );
assert( IsValid( currentWorldMatrix ) );
assert( IsValid( invBindPoseMatrix ) );
assert( IsValid( offsetMatrix ) );
XMStoreFloat4x4( &pOffsetMatrices[ i ], offsetMatrix );
// assert( IsIdentity( pOffsetMatrices[ i ] ) );
if ( pNormalMatrices ) {
XMStoreFloat4x4( &pNormalMatrices[ i ], XMMatrixTranspose( XMMatrixInverse( 0, offsetMatrix ) ) );
}
}
}
bool IsRotationProperty( const apemode::SceneAnimCurve::EProperty eProperty ) {
switch ( eProperty ) {
case apemode::SceneAnimCurve::eProperty_LclRotation:
case apemode::SceneAnimCurve::eProperty_PreRotation:
case apemode::SceneAnimCurve::eProperty_PostRotation:
case apemode::SceneAnimCurve::eProperty_GeometricRotation:
return true;
default:
return false;
}
}
XMFLOAT3 *MapProperty( apemode::SceneAnimCurve::EProperty eProperty, apemode::SceneNodeTransform *pProperties ) {
static_assert( sizeof( SceneNodeTransform ) == ( sizeof( XMFLOAT3 ) * SceneAnimCurve::ePropertyCount / 3 ), "Re-implement mapping with switch cases." );
assert( ( ( eProperty % 3 ) == 0 ) && ( eProperty < SceneAnimCurve::ePropertyCount ) );
return reinterpret_cast< XMFLOAT3 * >( pProperties ) + ( eProperty / 3 );
}
void apemode::Scene::UpdateTransformProperties( float time,
const bool bLoop,
const uint16_t animStackId,
const uint16_t animLayerId,
SceneNodeTransformFrame *pAnimTransformFrame ) {
const float debugTimeSpan = 20;
XMFLOAT3 TimeMinMaxTotal;
TimeMinMaxTotal.x = 0;
TimeMinMaxTotal.y = debugTimeSpan;
TimeMinMaxTotal.z = debugTimeSpan;
if ( bLoop ) {
// Loop the given time value.
#define SCENEANIMCURVE_USE_MODF
#ifdef SCENEANIMCURVE_USE_MODF
float relativeTime, fractionalPart, integerPart;
relativeTime = ( time - TimeMinMaxTotal.x ) / TimeMinMaxTotal.z;
fractionalPart = modf( relativeTime, &integerPart );
time = TimeMinMaxTotal.x + TimeMinMaxTotal.z * fractionalPart;
(void) integerPart;
#else
float relativeTime, fractionalPart;
relativeTime = ( time - TimeMinMaxTotal.x ) / TimeMinMaxTotal.z;
fractionalPart = relativeTime - (float) (long) relativeTime;
time = TimeMinMaxTotal.x + TimeMinMaxTotal.z * fractionalPart;
#endif
}
if ( pAnimTransformFrame ) { //SceneNodeTransformFrame *pAnimTransformFrame = GetAnimatedTransformFrame( animStackId, animLayerId ) ) {
*pAnimTransformFrame = BindPoseFrame;
// assert( pAnimTransformFrame->Transforms.size( ) == BindPoseFrame.Transforms.size( ) );
// const size_t transformFrameByteSize = sizeof( SceneNodeTransformComposite ) * pAnimTransformFrame->Transforms.size( );
// memcpy( pAnimTransformFrame->Transforms.data( ), BindPoseFrame.Transforms.data( ), transformFrameByteSize );
for ( const SceneNode &node : Nodes ) {
if ( const SceneNodeAnimCurveIds *animCurveIds = GetAnimCurveIds( node.Id, animStackId, animLayerId ) ) {
auto &animTransformComposite = pAnimTransformFrame->Transforms[ node.Id ];
for ( uint32_t propertyIndex = 0; propertyIndex < SceneAnimCurve::ePropertyCount; propertyIndex += SceneAnimCurve::eChannelCount ) {
const SceneAnimCurve::EProperty eProperty = SceneAnimCurve::EProperty( propertyIndex );
const float convertionFactor = IsRotationProperty( eProperty ) ? toRadsFactor : 1.0f;
XMFLOAT3 *pProperty = MapProperty( eProperty, &animTransformComposite.Properties );
const uint32_t animCurveIdX = animCurveIds->AnimCurveIds[ propertyIndex + SceneAnimCurve::eChannel_X ];
const uint32_t animCurveIdY = animCurveIds->AnimCurveIds[ propertyIndex + SceneAnimCurve::eChannel_Y ];
const uint32_t animCurveIdZ = animCurveIds->AnimCurveIds[ propertyIndex + SceneAnimCurve::eChannel_Z ];
const SceneAnimCurve *pAnimCurveX = ( animCurveIdX != detail::kInvalidId ) ? ( &AnimCurves[ animCurveIdX ] ) : nullptr;
const SceneAnimCurve *pAnimCurveY = ( animCurveIdY != detail::kInvalidId ) ? ( &AnimCurves[ animCurveIdY ] ) : nullptr;
const SceneAnimCurve *pAnimCurveZ = ( animCurveIdZ != detail::kInvalidId ) ? ( &AnimCurves[ animCurveIdZ ] ) : nullptr;
if ( pAnimCurveX || pAnimCurveY || pAnimCurveZ ) {
switch ( eProperty ) {
case SceneAnimCurve::eProperty_PreRotation:
case SceneAnimCurve::eProperty_PostRotation:
case SceneAnimCurve::eProperty_ScalingPivot:
case SceneAnimCurve::eProperty_ScalingOffset:
case SceneAnimCurve::eProperty_RotationPivot:
case SceneAnimCurve::eProperty_RotationOffset:
case SceneAnimCurve::eProperty_GeometricScaling:
case SceneAnimCurve::eProperty_GeometricRotation:
case SceneAnimCurve::eProperty_GeometricTranslation: {
LogWarn("Animating an object-offset property: {}",
apemodefb::EnumNameEAnimCurvePropertyFb(
apemodefb::EAnimCurvePropertyFb(eProperty)));
} break;
default:
break;
}
}
assert( !pAnimCurveX || pAnimCurveX->eProperty == eProperty && pAnimCurveX->eChannel == SceneAnimCurve::eChannel_X );
assert( !pAnimCurveY || pAnimCurveY->eProperty == eProperty && pAnimCurveY->eChannel == SceneAnimCurve::eChannel_Y );
assert( !pAnimCurveZ || pAnimCurveZ->eProperty == eProperty && pAnimCurveZ->eChannel == SceneAnimCurve::eChannel_Z );
pProperty->x = pAnimCurveX ? ( pAnimCurveX->Calculate( time ) * convertionFactor ) : pProperty->x;
pProperty->y = pAnimCurveY ? ( pAnimCurveY->Calculate( time ) * convertionFactor ) : pProperty->y;
pProperty->z = pAnimCurveZ ? ( pAnimCurveZ->Calculate( time ) * convertionFactor ) : pProperty->z;
assert( animTransformComposite.Properties.Validate( ) );
}
}
}
// return pAnimTransformFrame;
}
// return false;
// return nullptr;
}
SceneNodeTransformFrame &apemode::Scene::GetBindPoseTransformFrame( ) {
return BindPoseFrame;
}
const SceneNodeTransformFrame &apemode::Scene::GetBindPoseTransformFrame( ) const {
return BindPoseFrame;
}
bool apemode::Scene::HasAnimStackLayer( uint16_t animStackId, uint16_t animLayerId ) const {
if ( animStackId < AnimStacks.size() ) {
return animLayerId < AnimStacks[animStackId].LayerCount;
}
return false;
}
void apemode::Scene::UpdateTransformMatrices( const uint32_t parentNodeId, SceneNodeTransformFrame &t ) const {
assert( parentNodeId == Nodes[ parentNodeId ].Id );
const SceneNodeTransformComposite &transformComposite = t.Transforms[ parentNodeId ];
const auto childIdRange = NodeToChildIds.equal_range( parentNodeId );
for ( auto childIdIt = childIdRange.first; childIdIt != childIdRange.second; ++childIdIt ) {
const uint32_t childId = childIdIt->second;
const SceneNode & childNode = Nodes[ childId ];
SceneNodeTransformComposite &childTransformComposite = t.Transforms[ childId ];
assert( parentNodeId == childNode.ParentId );
if (childNode.LimitsId != uint32_t(-1)) {
childTransformComposite.Properties.ApplyLimits(Limits[childNode.LimitsId]);
}
childTransformComposite.LocalMatrix = childTransformComposite.Properties.CalculateLocalMatrix( childNode.eOrder );
childTransformComposite.GeometricalMatrix = childTransformComposite.Properties.CalculateGeometricMatrix( childNode.eOrder );
childTransformComposite.HierarchicalMatrix = childTransformComposite.LocalMatrix * transformComposite.HierarchicalMatrix;
childTransformComposite.WorldMatrix = childTransformComposite.GeometricalMatrix * childTransformComposite.HierarchicalMatrix;
assert( childTransformComposite.Properties.Validate() );
assert( IsValid( transformComposite.HierarchicalMatrix ) );
assert( IsValid( childTransformComposite.LocalMatrix ) );
assert( IsValid( childTransformComposite.HierarchicalMatrix ) );
assert( IsValid( childTransformComposite.GeometricalMatrix ) );
assert( IsValid( childTransformComposite.WorldMatrix ) );
UpdateTransformMatrices( childId, t );
}
}
void apemode::Scene::UpdateTransformMatrices( SceneNodeTransformFrame &t ) const {
if ( t.Transforms.empty( ) || Nodes.empty( ) )
return;
//
// Implicit world calculations for the root node.
// Start recursive updates from the root node.
//
SceneNodeTransformComposite &rootTransformComposite = t.Transforms[ 0 ];
const detail::ERotationOrder eRootOrder = Nodes.front( ).eOrder;
rootTransformComposite.LocalMatrix = rootTransformComposite.Properties.CalculateLocalMatrix( eRootOrder );
rootTransformComposite.GeometricalMatrix = rootTransformComposite.Properties.CalculateGeometricMatrix( eRootOrder );
rootTransformComposite.HierarchicalMatrix = rootTransformComposite.LocalMatrix;
rootTransformComposite.WorldMatrix = rootTransformComposite.GeometricalMatrix * rootTransformComposite.LocalMatrix;
UpdateTransformMatrices( 0, t );
}
apemode::LoadedScene apemode::LoadSceneFromBin( apemode::vector< uint8_t > && fileContents ) {
using namespace utils;
const apemodefb::SceneFb *pSrcScene = !fileContents.empty( )
? apemodefb::GetSceneFb( fileContents.data( ) )
: nullptr;
if ( nullptr == pSrcScene ) {
LogError( "Failed to reinterpret the buffer to scene." );
return apemode::LoadedScene{};
}
if ( apemodefb::EVersionFb_Value != pSrcScene->version( ) ) {
LogError( "Library version \"{}\" does not match to file version \"{}\"",
apemodefb::EVersionFb_Value,
pSrcScene->version( ) );
return apemode::LoadedScene{};
}
auto pNodesFb = pSrcScene->nodes( );
auto pMeshesFb = pSrcScene->meshes( );
auto pMaterialsFb = pSrcScene->materials( );
auto pAnimCurvesFb = pSrcScene->anim_curves( );
auto pAnimStacksFb = pSrcScene->anim_stacks( );
auto pAnimLayersFb = pSrcScene->anim_layers( );
auto pSkinsFb = pSrcScene->skins( );
apemode::unique_ptr< Scene > pScene( apemode_new Scene( ) );
if ( IsNotNullAndNotEmpty( pAnimStacksFb ) ) {
pScene->AnimStacks.resize( pAnimStacksFb->size( ) );
for ( uint32_t i = 0; i < pAnimStacksFb->size( ); ++i ) {
pScene->AnimStacks[ i ].pszName = GetCStringProperty( pSrcScene, pAnimStacksFb->Get( i )->name_id( ) );
pScene->AnimStacks[ i ].LayerCount = 0;
LogInfo( "Adding animation stack: \"{}\"", pScene->AnimStacks[ i ].pszName );
}
}
pScene->BindPoseBoundingBox.Extents.x = ( pSrcScene->bbox_max( )->x( ) - pSrcScene->bbox_min( )->x( ) ) * 0.5f;
pScene->BindPoseBoundingBox.Extents.y = ( pSrcScene->bbox_max( )->y( ) - pSrcScene->bbox_min( )->y( ) ) * 0.5f;
pScene->BindPoseBoundingBox.Extents.z = ( pSrcScene->bbox_max( )->z( ) - pSrcScene->bbox_min( )->z( ) ) * 0.5f;
pScene->BindPoseBoundingBox.Center.x = pScene->BindPoseBoundingBox.Extents.x + pSrcScene->bbox_min( )->x( );
pScene->BindPoseBoundingBox.Center.y = pScene->BindPoseBoundingBox.Extents.y + pSrcScene->bbox_min( )->y( );
pScene->BindPoseBoundingBox.Center.z = pScene->BindPoseBoundingBox.Extents.z + pSrcScene->bbox_min( )->z( );
if ( IsNotNullAndNotEmpty( pNodesFb ) ) {
size_t nodeIdCount = 0;
size_t animCurveIdCount = 0;
for ( auto pNodeFb : *pNodesFb ) {
nodeIdCount += IsNotNullAndNotEmpty( pNodeFb->child_ids( ) ) ? pNodeFb->child_ids( )->size( ) : 0;
animCurveIdCount += IsNotNullAndNotEmpty( pNodeFb->anim_curve_ids( ) ) ? pNodeFb->anim_curve_ids( )->size( ) : 0;
}
pScene->NodeToChildIds.reserve( nodeIdCount );
pScene->NodeIdToAnimCurveIds.reserve( animCurveIdCount );
LogInfo( "Node IDs: {}", nodeIdCount );
LogInfo( "Curve IDs: {}", animCurveIdCount );
}
if ( IsNotNullAndNotEmpty( pNodesFb ) ) {
pScene->Nodes.resize( pNodesFb->size( ) );
SceneNodeTransformFrame &bindPoseFrame = pScene->BindPoseFrame;
pScene->InitializeTransformFrame( bindPoseFrame );
apemode::vector<uint32_t> rootIds;
apemode::vector<uint32_t> limbIds;
for ( auto pNodeFb : *pNodesFb ) {
assert( pNodeFb );
auto &node = pScene->Nodes[ pNodeFb->id( ) ];
node.Id = pNodeFb->id( );
node.eOrder = detail::ERotationOrder( pNodeFb->rotation_order( ) );
node.eInheritType = detail::EInheritType( pNodeFb->inherit_type( ) );
node.eSkeletonType = detail::ESkeletonType( pNodeFb->skeleton_type( ) );
node.pszName = GetCStringProperty( pSrcScene, pNodeFb->name_id( ) );
switch (node.eSkeletonType) {
case detail::eSkeletonType_Root:
rootIds.push_back( node.Id );
limbIds.push_back( node.Id );
break;
case detail::eSkeletonType_Limb:
case detail::eSkeletonType_LimbNode:
limbIds.push_back( node.Id );
break;
default:
break;
}
if ( pNodeFb->mesh_id( ) != detail::kInvalidId ) {
node.MeshId = pNodeFb->mesh_id( );
}
LogInfo( "Processing node: {}{}"
, GetCStringProperty( pSrcScene, pNodeFb->name_id( ) )
, pNodeFb->mesh_id() != detail::kInvalidId ? " (has mesh)" : "" );
auto pChildIdsFb = pNodeFb->child_ids( );
if ( IsNotNullAndNotEmpty( pChildIdsFb ) ) {
for ( const uint32_t childNodeId : *pChildIdsFb ) {
pScene->NodeToChildIds.insert( eastl::make_pair( node.Id, childNodeId ) );
pScene->Nodes[ childNodeId ].ParentId = node.Id;
}
}
auto &transformComposite = bindPoseFrame.Transforms[ pNodeFb->id( ) ];
auto transformFb = pSrcScene->transforms( )->Get( pNodeFb->id( ) );
#define MATCH_VECTOR_TYPE( v, V ) \
{ \
v.x = V.x( ); \
v.y = V.y( ); \
v.z = V.z( ); \
}
MATCH_VECTOR_TYPE( transformComposite.Properties.Translation, transformFb->translation( ) );
MATCH_VECTOR_TYPE( transformComposite.Properties.RotationOffset, transformFb->rotation_offset( ) );
MATCH_VECTOR_TYPE( transformComposite.Properties.RotationPivot, transformFb->rotation_pivot( ) );
MATCH_VECTOR_TYPE( transformComposite.Properties.PreRotation, transformFb->pre_rotation( ) );
MATCH_VECTOR_TYPE( transformComposite.Properties.Rotation, transformFb->rotation( ) );
MATCH_VECTOR_TYPE( transformComposite.Properties.PostRotation, transformFb->post_rotation( ) );
MATCH_VECTOR_TYPE( transformComposite.Properties.ScalingOffset, transformFb->scaling_offset( ) );
MATCH_VECTOR_TYPE( transformComposite.Properties.ScalingPivot, transformFb->scaling_pivot( ) );
MATCH_VECTOR_TYPE( transformComposite.Properties.Scaling, transformFb->scaling( ) );
MATCH_VECTOR_TYPE( transformComposite.Properties.GeometricTranslation, transformFb->geometric_translation( ) );
MATCH_VECTOR_TYPE( transformComposite.Properties.GeometricRotation, transformFb->geometric_rotation( ) );
MATCH_VECTOR_TYPE( transformComposite.Properties.GeometricScaling, transformFb->geometric_scaling( ) );
transformComposite.Properties.PreRotation.x *= toRadsFactor;
transformComposite.Properties.PreRotation.y *= toRadsFactor;
transformComposite.Properties.PreRotation.z *= toRadsFactor;
transformComposite.Properties.Rotation.x *= toRadsFactor;
transformComposite.Properties.Rotation.y *= toRadsFactor;
transformComposite.Properties.Rotation.z *= toRadsFactor;
transformComposite.Properties.PostRotation.x *= toRadsFactor;
transformComposite.Properties.PostRotation.y *= toRadsFactor;
transformComposite.Properties.PostRotation.z *= toRadsFactor;
transformComposite.Properties.GeometricRotation.x *= toRadsFactor;
transformComposite.Properties.GeometricRotation.y *= toRadsFactor;
transformComposite.Properties.GeometricRotation.z *= toRadsFactor;
#define REPORT_USED_PROPERTY( P, d ) \
if ( !IsNearlyEqual( P.x, d ) || !IsNearlyEqual( P.y, d ) || !IsNearlyEqual( P.z, d ) ) { \
LogWarn( "Node \"{}\" uses property \"{}\".", GetCStringProperty( pSrcScene, pNodeFb->name_id( ) ), #P ); \
}
REPORT_USED_PROPERTY( transformComposite.Properties.Translation, 0 );
REPORT_USED_PROPERTY( transformComposite.Properties.Rotation, 0 );
REPORT_USED_PROPERTY( transformComposite.Properties.Scaling, 1 );
REPORT_USED_PROPERTY( transformComposite.Properties.ScalingOffset, 0 );
REPORT_USED_PROPERTY( transformComposite.Properties.ScalingPivot, 0 );
REPORT_USED_PROPERTY( transformComposite.Properties.RotationOffset, 0 );
REPORT_USED_PROPERTY( transformComposite.Properties.RotationPivot, 0 );
REPORT_USED_PROPERTY( transformComposite.Properties.PreRotation, 0 );
REPORT_USED_PROPERTY( transformComposite.Properties.PostRotation, 0 );
REPORT_USED_PROPERTY( transformComposite.Properties.GeometricRotation, 0 );
REPORT_USED_PROPERTY( transformComposite.Properties.GeometricTranslation, 0 );
REPORT_USED_PROPERTY( transformComposite.Properties.GeometricScaling, 1 );
#undef REPORT_USED_PROPERTY
if ( !transformComposite.Properties.Validate( ) ) {
LogError( "Found invalid transform, node id {}", pNodeFb->id( ) );
assert( false );
}
if ( pNodeFb->transform_limits_id( ) != uint32_t( -1 ) ) {
auto pTransformLimitsFb = pSrcScene->transform_limits( )->Get( pNodeFb->transform_limits_id( ) );
node.LimitsId = uint32_t(pScene->Limits.size());
auto &limits = pScene->Limits.emplace_back( );
MATCH_VECTOR_TYPE( limits.IsTranslationMaxActive, pTransformLimitsFb->translation_max_active( ) );
MATCH_VECTOR_TYPE( limits.IsTranslationMinActive, pTransformLimitsFb->translation_min_active( ) );
MATCH_VECTOR_TYPE( limits.IsRotationMaxActive, pTransformLimitsFb->rotation_max_active( ) );
MATCH_VECTOR_TYPE( limits.IsRotationMinActive, pTransformLimitsFb->rotation_min_active( ) );
MATCH_VECTOR_TYPE( limits.IsScalingMaxActive, pTransformLimitsFb->scaling_max_active( ) );
MATCH_VECTOR_TYPE( limits.IsScalingMinActive, pTransformLimitsFb->scaling_min_active( ) );
MATCH_VECTOR_TYPE( limits.TranslationMax, pTransformLimitsFb->translation_max( ) );
MATCH_VECTOR_TYPE( limits.TranslationMin, pTransformLimitsFb->translation_min( ) );
MATCH_VECTOR_TYPE( limits.RotationMax, pTransformLimitsFb->rotation_max( ) );
MATCH_VECTOR_TYPE( limits.RotationMin, pTransformLimitsFb->rotation_min( ) );
MATCH_VECTOR_TYPE( limits.ScalingMax, pTransformLimitsFb->scaling_max( ) );
MATCH_VECTOR_TYPE( limits.ScalingMin, pTransformLimitsFb->scaling_min( ) );
limits.RotationMax.x *= toRadsFactor;
limits.RotationMax.y *= toRadsFactor;
limits.RotationMax.z *= toRadsFactor;
limits.RotationMin.x *= toRadsFactor;
limits.RotationMin.y *= toRadsFactor;
limits.RotationMin.z *= toRadsFactor;
}
#undef MATCH_VECTOR_TYPE
auto pAnimCurveIdsFb = pNodeFb->anim_curve_ids( );
if ( IsNotNullAndNotEmpty( pAnimCurveIdsFb ) ) {
for ( const uint32_t animCurveId : *pAnimCurveIdsFb ) {
assert( animCurveId < pAnimCurvesFb->size( ) );
pScene->NodeIdToAnimCurveIds.insert( eastl::make_pair( node.Id, animCurveId ) );
}
}
}
pScene->UpdateTransformMatrices( bindPoseFrame );
//BuildSkeletons( pScene.get(), eastl::move( rootIds ), eastl::move( limbIds ) );
#if 0
LogInfo( "----------------------------------" );
for ( auto &node : pScene->Nodes ) {
XMFLOAT4X4 WM;
XMFLOAT4X4 HM;
XMStoreFloat4x4( &WM, bindPoseFrame.Transforms[ node.Id ].WorldMatrix );
XMStoreFloat4x4( &HM, bindPoseFrame.Transforms[ node.Id ].HierarchicalMatrix );
LogInfo( "Node \"{}\"", node.pszName );
LogInfo( "----------------------------------" );
LogInfo( "\t{} {} {} {}", WM._11, WM._12, WM._13, WM._14 );
LogInfo( "\t{} {} {} {}", WM._21, WM._22, WM._23, WM._24 );
LogInfo( "\t{} {} {} {}", WM._31, WM._32, WM._33, WM._34 );
LogInfo( "\t{} {} {} {}", WM._41, WM._42, WM._43, WM._44 );
LogInfo( "----------------------------------" );
LogInfo( "\t{} {} {} {}", HM._11, HM._12, HM._13, HM._14 );
LogInfo( "\t{} {} {} {}", HM._21, HM._22, HM._23, HM._24 );
LogInfo( "\t{} {} {} {}", HM._31, HM._32, HM._33, HM._34 );
LogInfo( "\t{} {} {} {}", HM._41, HM._42, HM._43, HM._44 );
LogInfo( "----------------------------------" );
}
#endif
}
if ( IsNotNullAndNotEmpty( pAnimCurvesFb ) ) {
assert( IsNotNullAndNotEmpty( pAnimLayersFb ) );
assert( IsNotNullAndNotEmpty( pAnimStacksFb ) );
pScene->AnimCurves.reserve( pAnimCurvesFb->size( ) );
for ( auto pAnimCurveFb : *pAnimCurvesFb ) {
assert( pAnimCurveFb );
LogInfo( "Processing curve: #{} -> \"{}\", keys={}",
pAnimCurveFb->id( ),
GetCStringProperty( pSrcScene, pAnimCurveFb->name_id( ) ),
pAnimCurveFb->keys( )->size( ) );
pScene->AnimCurves.emplace_back( );
auto &animCurve = pScene->AnimCurves.back( );
assert( pAnimCurveFb->anim_layer_id( ) < pAnimLayersFb->size( ) );
assert( pAnimCurveFb->anim_stack_id( ) < pAnimStacksFb->size( ) );
assert( pAnimCurveFb->anim_layer_id( ) < 0xFFFFU );
assert( pAnimCurveFb->anim_stack_id( ) < 0xFFFFU );
auto pAnimLayerFbIt = eastl::find_if(pAnimLayersFb->begin(), pAnimLayersFb->end(), [pAnimCurveFb](const apemodefb::AnimLayerFb * pAnimLayerFb) {
return pAnimLayerFb->id() == pAnimCurveFb->anim_layer_id();
});
pScene->AnimStacks[pAnimCurveFb->anim_stack_id( )].LayerCount =
eastl::max(pScene->AnimStacks[pAnimCurveFb->anim_stack_id( )].LayerCount, pAnimLayerFbIt->anim_stack_idx( ) + 1);
animCurve.AnimLayerIndex = static_cast< uint16_t >( pAnimLayerFbIt->anim_stack_idx( ) );
animCurve.AnimStackIndex = static_cast< uint16_t >( pAnimCurveFb->anim_stack_id( ) );
animCurve.eChannel = SceneAnimCurve::EChannel( pAnimCurveFb->channel( ) );
animCurve.eProperty = SceneAnimCurve::EProperty( pAnimCurveFb->property( ) * SceneAnimCurve::eChannelCount );
assert( IsNotNullAndNotEmpty( pAnimCurveFb->keys( ) ) );
animCurve.Keys.reserve( pAnimCurveFb->keys( )->size( ) );
if ( pAnimCurveFb->compression_type() == apemodefb::ECompressionTypeFb_None ) {
auto keys = (const apemodefb::AnimCurveCubicKeyFb*) pAnimCurveFb->keys( )->data( );
auto keysEnd = keys + pAnimCurveFb->keys( )->size( ) / sizeof( apemodefb::AnimCurveCubicKeyFb );
eastl::transform( keys,
keysEnd,
eastl::inserter( animCurve.Keys, animCurve.Keys.begin( ) ),
[]( const apemodefb::AnimCurveCubicKeyFb &keyFb ) {
auto pKeyFb = &keyFb;
return eastl::make_pair< float, SceneAnimCurveKey >( pKeyFb->time( ),
SceneAnimCurveKey{
SceneAnimCurveKey::EInterpolationMode(pKeyFb->interpolation_mode()),
pKeyFb->time( ),
pKeyFb->value_bez0_bez3( ),
pKeyFb->bez1( ),
pKeyFb->bez2( ),
} );
} );
} else {
draco::DecoderBuffer decoderBuffer;
decoderBuffer.Init( (const char *)pAnimCurveFb->keys( )->data( ), pAnimCurveFb->keys( )->size( ) );
draco::DecoderOptions options;
draco::Decoder decoder;
draco::PointCloud animPointCloud;
draco::Status status = decoder.DecodeBufferToGeometry( &decoderBuffer, &animPointCloud );
if (status.code() == draco::Status::OK) {
constexpr int keyValuesAttributeIndex = 0;
constexpr int keyTimeAttributeIndex = 1;
constexpr int keyTypeAttributeIndex = 2;
const draco::PointAttribute* keyValuesAttribute = animPointCloud.attribute( keyValuesAttributeIndex );
const draco::PointAttribute* keyTimeAttribute = animPointCloud.attribute( keyTimeAttributeIndex );
const draco::PointAttribute* keyTypeAttribute = animPointCloud.attribute( keyTypeAttributeIndex );
animCurve.Keys.reserve( animPointCloud.num_points( ) );
for (uint32_t i = 0; i < animPointCloud.num_points( ); ++i) {
const draco::PointIndex pointIndex {i};
float mappedTime = 0;
keyTimeAttribute->GetMappedValue( pointIndex, &mappedTime );
auto &key = animCurve.Keys[mappedTime];
key.Time = mappedTime;
keyValuesAttribute->GetMappedValue( pointIndex, &key.Value );
keyTypeAttribute->GetMappedValue( pointIndex, &key.eInterpMode );
}
}
#if 0
draco::KeyframeAnimationDecoder keyframeAnimationDecoder;
draco::DecoderOptions options;
draco::KeyframeAnimation keyframeAnimation;
keyframeAnimationDecoder.Decode(options, &decoderBuffer, &keyframeAnimation);
const size_t numFrames = keyframeAnimation.num_frames();
const auto timestamps = keyframeAnimation.timestamps();
const auto * values = keyframeAnimation.keyframes(1);
const auto * interpolationTypes = keyframeAnimation.keyframes(2);
animCurve.Keys.reserve(numFrames);
for (uint32_t i = 0; i < numFrames; ++i) {
float mappedTimestamp {};
XMFLOAT3 mappedValues {};
uint8_t mappedInterpolationType {};
timestamps->GetMappedValue(draco::PointIndex(i), &mappedTimestamp);
values->GetMappedValue(draco::PointIndex(i), &mappedValues);
interpolationTypes->GetMappedValue(draco::PointIndex(i), &mappedInterpolationType);
auto &key = animCurve.Keys[mappedTimestamp];
key.Time = mappedTimestamp;
key.Value = mappedValues.x;
key.Bez1 = mappedValues.y;
key.Bez2 = mappedValues.z;
key.eInterpMode = SceneAnimCurveKey::EInterpolationMode(mappedInterpolationType);
}
#endif
}
animCurve.TimeMinMaxTotal.x = animCurve.Keys.cbegin( )->second.Time;
animCurve.TimeMinMaxTotal.y = animCurve.Keys.crbegin( )->second.Time;
animCurve.TimeMinMaxTotal.z = animCurve.TimeMinMaxTotal.y - animCurve.TimeMinMaxTotal.x;
LogInfo( "\tStart: {} -> End: {} (Duration: {})",
animCurve.TimeMinMaxTotal.x,
animCurve.TimeMinMaxTotal.y,
animCurve.TimeMinMaxTotal.z );
}
pScene->AnimNodeIdToAnimCurveIds.reserve( pAnimCurvesFb->size( ) );
for ( auto &node : pScene->Nodes ) {
const auto animCurveIdRange = pScene->NodeIdToAnimCurveIds.equal_range( node.Id );
for ( auto animCurveIdIt = animCurveIdRange.first; animCurveIdIt != animCurveIdRange.second; ++animCurveIdIt ) {
const uint32_t animCurveId = animCurveIdIt->second;
auto pAnimCurve = &pScene->AnimCurves[ animCurveId ];
SceneAnimNodeId animNodeId;
animNodeId.NodeId = node.Id;
animNodeId.AnimLayerId.AnimLayerIndex = pAnimCurve->AnimLayerIndex;
animNodeId.AnimLayerId.AnimStackIndex = pAnimCurve->AnimStackIndex;
SceneNodeAnimCurveIds &animCurves = pScene->AnimNodeIdToAnimCurveIds[ animNodeId.AnimNodeCompositeId ];
const uint32_t animCurveIndex = uint32_t( pAnimCurve->eProperty ) + uint32_t( pAnimCurve->eChannel );
animCurves.AnimCurveIds[ animCurveIndex ] = animCurveIdIt->second;
}
}
for ( auto pAnimLayerFb : *pAnimLayersFb ) {
auto pAnimStackFb = pAnimStacksFb->Get( pAnimLayerFb->anim_stack_id( ) );
LogInfo( "Processing anim set: stack=#{} \"{}\", layer=#{} \"{}\"",
pAnimStackFb->id( ),
GetCStringProperty( pSrcScene, pAnimStackFb->name_id( ) ),
pAnimLayerFb->anim_stack_idx( ),
GetCStringProperty( pSrcScene, pAnimLayerFb->name_id( ) ) );
SceneAnimLayerId animLayerId;
animLayerId.AnimLayerIndex = pAnimLayerFb->anim_stack_idx( );
animLayerId.AnimStackIndex = pAnimLayerFb->anim_stack_id( );
}
}
if ( IsNotNullAndNotEmpty( pMeshesFb ) ) {
{ /* All the subsets are stored in Scene instance, and can be referenced
* by the BaseSubset and SubsetCount values in SceneMeshSubset struct.
*/
size_t totalSubsetCount = 0;
for ( uint32_t meshId = 0; meshId < pMeshesFb->size( ); ++meshId ) {
auto pMeshFb = pMeshesFb->Get( meshId );
totalSubsetCount += pMeshFb->subsets( ) ? pMeshFb->subsets( )->size( ) : 0;
}
pScene->Subsets.reserve( totalSubsetCount );
}
pScene->Meshes.reserve( pMeshesFb->size( ) );
for ( uint32_t meshId = 0; meshId < pMeshesFb->size( ); ++meshId ) {
auto pMeshFb = pMeshesFb->Get( meshId );
assert( pMeshFb );
assert( IsNotNullAndNotEmpty( pMeshFb->vertices( ) ) );
// assert( IsNotNullAndNotEmpty( pMeshFb->indices( ) ) );
assert( IsNotNullAndNotEmpty( pMeshFb->subsets( ) ) );
assert( IsNotNullAndNotEmpty( pMeshFb->submeshes( ) ) );
// std::array<apemode::detail::SkinnedVertex, 128> sv;
// memcpy(sv.data(), pMeshFb->vertices(), std::min<size_t>(sizeof(sv), pMeshFb->vertices()->size()));
pScene->Meshes.emplace_back( );
auto &mesh = pScene->Meshes.back( );
mesh.SubsetCount = static_cast< uint32_t >( pMeshFb->subsets( )->size( ) );
mesh.BaseSubset = static_cast< uint32_t >( pScene->Subsets.size( ) );
mesh.eVertexType = detail::eVertexType_Custom;
// auto pSubmeshesFb = pMeshFb->submeshes( );
// auto pSubmeshFb = pSubmeshesFb->Get( 0 );
// switch ( pSubmeshFb->vertex_format( ) ) {
// case apemodefb::EVertexFormatFb_Default:
// mesh.eVertexType = detail::eVertexType_Default;
// break;
// case apemodefb::EVertexFormatFb_Skinned:
// mesh.eVertexType = detail::eVertexType_Skinned;
// break;
// case apemodefb::EVertexFormatFb_FatSkinned:
// mesh.eVertexType = detail::eVertexType_FatSkinned;
// break;
// default:
// break;
// }
std::transform( pMeshFb->subsets( )->begin( ),
pMeshFb->subsets( )->end( ),
std::back_inserter( pScene->Subsets ),
[&]( const apemodefb::SubsetFb *pSubsetFb ) {
SceneMeshSubset subset;
subset.MeshId = mesh.Id;
subset.MaterialId = pSubsetFb->material_id( );
subset.BaseIndex = pSubsetFb->base_index( );
subset.IndexCount = pSubsetFb->index_count( );
return subset;
} );
mesh.Id = meshId;
mesh.SkinId = pMeshFb->skin_id( );
}
}
if ( IsNotNullAndNotEmpty( pSkinsFb ) ) {
pScene->Skins.resize( pSkinsFb->size() );
for ( auto &mesh : pScene->Meshes ) {
if ( mesh.SkinId != detail::kInvalidId ) {
auto &skin = pScene->Skins[ mesh.SkinId ];
skin.Id = mesh.SkinId;
auto pSkinFb = pSkinsFb->Get( mesh.SkinId );
auto pInvBindMatrices = pSkinFb->inv_bind_pose_matrices( );
if ( skin.LinkIds.empty( ) && pSkinFb ) {
auto pLinkIdsFb = pSkinFb->links_ids( );
if ( IsNotNullAndNotEmpty( pLinkIdsFb ) ) {
LogInfo( "Processing skin: \"{}\", links {}",
GetCStringProperty( pSrcScene, pSkinFb->name_id( ) ),
pLinkIdsFb->size( ) );
skin.LinkIds.reserve( pLinkIdsFb->size( ) );
skin.InvBindPoseMatrices.reserve( pLinkIdsFb->size( ) );
for ( uint32_t linkIndex = 0; linkIndex < pLinkIdsFb->size( ); ++linkIndex ) {
auto linkNodeId = pLinkIdsFb->Get( linkIndex );
LogInfo( "\t+ link {} \"{}\"", linkNodeId, pScene->Nodes[ linkNodeId ].pszName );
const XMFLOAT4X4 *invBindPoseMatrixFb = (const XMFLOAT4X4 *) pInvBindMatrices->Get( linkIndex );
XMMATRIX invBindPoseMatrix = XMLoadFloat4x4( invBindPoseMatrixFb );
skin.LinkIds.push_back( linkNodeId );
skin.InvBindPoseMatrices.push_back( invBindPoseMatrix );
}
}
}
}
}
}
auto pTexturesFb = pSrcScene->textures( );
auto pFilesFb = pSrcScene->files( );
if ( IsNotNullAndNotEmpty( pMaterialsFb ) ) {
pScene->Materials.reserve( pMaterialsFb->size( ) );
for ( uint32_t materialId = 0; materialId < pMaterialsFb->size( ); ++materialId ) {
auto pMaterialFb = pMaterialsFb->Get( materialId );
assert( pMaterialFb );
LogInfo( "Processing material \"{}\": properties: {}, textures: {}",
GetCStringProperty( pSrcScene, pMaterialFb->name_id( ) ),
pMaterialFb->properties( ) ? pMaterialFb->properties( )->size( ) : 0,
pMaterialFb->texture_properties( ) ? pMaterialFb->texture_properties( )->size( ) : 0 );
pScene->Materials.emplace_back( );
auto &material = pScene->Materials.back( );
material.Id = materialId;
for ( auto pTexturePropFb : *pMaterialFb->texture_properties( ) ) {
auto pszTexturePropName = GetCStringProperty( pSrcScene, pTexturePropFb->name_id( ) );
auto pTextureFb = pTexturesFb->Get( pTexturePropFb->value_id( ) );
assert( pTextureFb );
if ( pTextureFb->file_id( ) != -1 ) {
auto pFileFb = pFilesFb->Get( pTextureFb->file_id( ) );
assert( pFileFb );
auto pszFileName = GetCStringProperty( pSrcScene, pFileFb->name_id( ) );
assert( pszFileName );
LogInfo( "\tTexture: \"{}\" -> {}", pszTexturePropName, pszFileName );
}
}
if ( auto pPropertiesFb = pMaterialFb->properties( ) ) {
for ( auto pMaterialPropFb : *pPropertiesFb ) {
auto pszMaterialPropName = GetCStringProperty( pSrcScene, pMaterialPropFb->name_id( ) );
LogInfo( "\tProperty: \"{}\"", pszMaterialPropName );
if ( strcmp( "diffuseFactor", pszMaterialPropName ) == 0 ) {
material.BaseColorFactor = ToVec4( GetVec4Property( pSrcScene, pMaterialPropFb->value_id( ) ) );
} else if ( strcmp( "baseColorFactor", pszMaterialPropName ) == 0 ) {
material.BaseColorFactor = ToVec4( GetVec4Property( pSrcScene, pMaterialPropFb->value_id( ) ) );
} else if ( strcmp( "metallicFactor", pszMaterialPropName ) == 0 ) {
material.MetallicFactor = GetScalarProperty( pSrcScene, pMaterialPropFb->value_id( ) );
} else if ( strcmp( "emissiveFactor", pszMaterialPropName ) == 0 ) {
material.EmissiveFactor = ToVec3( GetVec3Property( pSrcScene, pMaterialPropFb->value_id( ) ) );
} else if ( strcmp( "specularFactor", pszMaterialPropName ) == 0 ) {
material.MetallicFactor = GetVec3Property( pSrcScene, pMaterialPropFb->value_id( ) ).x();
} else if ( strcmp( "glossinessFactor", pszMaterialPropName ) == 0 ) {
material.RoughnessFactor = 1.0f - GetScalarProperty( pSrcScene, pMaterialPropFb->value_id( ) );
} else if ( strcmp( "roughnessFactor", pszMaterialPropName ) == 0 ) {
material.RoughnessFactor = GetScalarProperty( pSrcScene, pMaterialPropFb->value_id( ) );
} else if ( strcmp( "doubleSided", pszMaterialPropName ) == 0 ) {
material.bDoubleSided = GetBoolProperty( pSrcScene, pMaterialPropFb->value_id( ) );
} else if ( strcmp( "alphaCutoff", pszMaterialPropName ) == 0 ) {
material.AlphaCutoff = GetScalarProperty( pSrcScene, pMaterialPropFb->value_id( ) );
} else if ( strcmp( "alphaMode", pszMaterialPropName ) == 0 ) {
if ( strcmp( "BLEND", GetCStringProperty( pSrcScene, pMaterialPropFb->value_id( ) ) ) == 0 )
material.eAlphaMode = SceneMaterial::eAlphaMode_Blend;
} else {
LogError( "Failed to map the property to the available slot" );
}
} /* pMaterialPropFb */
} /* pPropertiesFb */
} /* pMaterialFb */
} /* pMaterialsFb */
detail::ScenePrintPretty prettyPrint;
prettyPrint.PrintPretty( pScene.get( ) );
return LoadedScene{std::move( fileContents ), pSrcScene, std::move( pScene )};
}
void apemode::SceneAnimCurve::GetKeyIndices( float & time, uint32_t &i, uint32_t &j ) const {
if ( apemode::IsNearlyEqualOrLess( time, TimeMinMaxTotal.x ) ) {
// Case: before the curve's first key, or on it.
i = 0;
j = 0;
} else if ( apemode::IsNearlyEqualOrGreater( time, TimeMinMaxTotal.y ) ) {
// Case: after the curve's last key, or on it.
i = static_cast< uint32_t >( Keys.size( ) ) - 1;
j = i;
} else {
// Case: inside the curve's timeline.
auto matchOrUpperBoundIt = Keys.lower_bound( time );
assert( matchOrUpperBoundIt != Keys.end( ) );
if ( apemode::IsNearlyEqual( matchOrUpperBoundIt->second.Time, time ) ) {
// Case: exactly on curve's key.
i = static_cast< uint32_t >( eastl::distance( Keys.cbegin( ), matchOrUpperBoundIt ) );
j = i;
} else {
const auto lowerBoundIt = eastl::prev( matchOrUpperBoundIt );
const auto upperBoundIt = matchOrUpperBoundIt;
assert( lowerBoundIt != Keys.end( ) );
// Case: inside the curve's segment.
i = static_cast< uint32_t >( eastl::distance( Keys.cbegin( ), lowerBoundIt ) );
j = static_cast< uint32_t >( eastl::distance( Keys.cbegin( ), upperBoundIt ) );
}
}
}
float CubicInterp( const float P0, const float P1, const float P2, const float P3, const float t ) {
#define SQUARED( x ) ( ( x ) * ( x ) )
#define CUBED( x ) ( ( x ) * ( x ) * ( x ) )
return CUBED( 1 - t ) * P0 + 3 * SQUARED( 1 - t ) * t * P1 + 3 * ( 1 - t ) * SQUARED( t ) * P2 + CUBED( t ) * P3;
#undef SQUARED
#undef CUBED
}
float InterpolateValue( const float time, const SceneAnimCurveKey& a, const SceneAnimCurveKey& b ) {
switch ( a.eInterpMode ) {
case apemode::SceneAnimCurveKey::eInterpolationMode_Const:
return a.Value;
case apemode::SceneAnimCurveKey::eInterpolationMode_Linear: {
const float l = ( time - a.Time ) / ( b.Time - a.Time );
const float t = ( b.Value - a.Value ) * l + a.Value;
return t;
}
default: {
const float l = ( time - a.Time ) / ( b.Time - a.Time );
const float t = CubicInterp( a.Bez0( ), a.Bez1, a.Bez2, b.PrevBez3( ), l );
return t;
}
}
}
float apemode::SceneAnimCurve::Calculate( float time ) const {
uint32_t i, j;
GetKeyIndices( time, i, j );
if ( i == j ) {
const SceneAnimCurveKey a = Keys.at( i ).second;
return a.Value;
} else {
const SceneAnimCurveKey a = Keys.at( i ).second;
const SceneAnimCurveKey b = Keys.at( j ).second;
const float interpolatedValue = InterpolateValue( time, a, b );
assert( !isnan( interpolatedValue) );
return interpolatedValue;
}
}
uint32_t apemode::utils::MaterialPropertyGetIndex( const uint32_t packed ) {
const uint32_t valueIndex = ( packed >> 8 ) & 0x0fff;
return valueIndex;
}
apemodefb::EValueTypeFb apemode::utils::MaterialPropertyGetType( const uint32_t packed ) {
const uint32_t valueType = packed & 0x000f;
return apemodefb::EValueTypeFb( valueType );
}
const char *apemode::utils::GetCStringProperty( const apemodefb::SceneFb *pScene, const uint32_t valueId ) {
assert( pScene && apemodefb::EValueTypeFb_String == MaterialPropertyGetType( valueId ) );
const uint32_t valueIndex = MaterialPropertyGetIndex( valueId );
return pScene->string_values( )->Get( valueIndex )->c_str( );
}
bool apemode::utils::GetBoolProperty( const apemodefb::SceneFb *pScene, const uint32_t valueId ) {
assert( pScene && apemodefb::EValueTypeFb_Bool == MaterialPropertyGetType( valueId ) );
const uint32_t valueIndex = MaterialPropertyGetIndex( valueId );
return pScene->bool_values( )->Get( valueIndex );
}
float apemode::utils::GetScalarProperty( const apemodefb::SceneFb *pScene, const uint32_t valueId ) {
assert( pScene && apemodefb::EValueTypeFb_Float == MaterialPropertyGetType( valueId ) );
const uint32_t valueIndex = MaterialPropertyGetIndex( valueId );
return pScene->float_values( )->Get( valueIndex );
}
apemodefb::Vec2Fb apemode::utils::GetVec2Property( const apemodefb::SceneFb *pScene, const uint32_t valueId ) {
assert( pScene && apemodefb::EValueTypeFb_Float2 == MaterialPropertyGetType( valueId ) );
const uint32_t valueIndex = MaterialPropertyGetIndex( valueId );
return apemodefb::Vec2Fb( pScene->float_values( )->Get( valueIndex ), pScene->float_values( )->Get( valueIndex + 1 ) );
}
apemodefb::Vec3Fb apemode::utils::GetVec3Property( const apemodefb::SceneFb *pScene, const uint32_t valueId ) {
assert( pScene && apemodefb::EValueTypeFb_Float3 == MaterialPropertyGetType( valueId ) );
const uint32_t valueIndex = MaterialPropertyGetIndex( valueId );
return apemodefb::Vec3Fb( pScene->float_values( )->Get( valueIndex ),
pScene->float_values( )->Get( valueIndex + 1 ),
pScene->float_values( )->Get( valueIndex + 2 ) );
}
apemodefb::Vec4Fb apemode::utils::GetVec4Property( const apemodefb::SceneFb *pScene,
const uint32_t valueId,
const float defaultW ) {
assert( pScene && ( apemodefb::EValueTypeFb_Float3 == MaterialPropertyGetType( valueId ) ||
apemodefb::EValueTypeFb_Float4 == MaterialPropertyGetType( valueId ) ) );
const uint32_t valueIndex = MaterialPropertyGetIndex( valueId );
return apemodefb::Vec4Fb( pScene->float_values( )->Get( valueIndex ),
pScene->float_values( )->Get( valueIndex + 1 ),
pScene->float_values( )->Get( valueIndex + 2 ),
apemodefb::EValueTypeFb_Float4 == MaterialPropertyGetType( valueId )
? pScene->float_values( )->Get( valueIndex + 3 )
: defaultW );
}
| 51.318841
| 163
| 0.593352
|
VladSerhiienko
|
3d11ac454b8035716481d5f83f7cd6e6372b955b
| 22,688
|
cpp
|
C++
|
Source/Homework 10 Includes/MyFloatD.cpp
|
rux616/c201
|
d8509e8d49e52e7326486249ad8d567560bf4ad4
|
[
"MIT"
] | null | null | null |
Source/Homework 10 Includes/MyFloatD.cpp
|
rux616/c201
|
d8509e8d49e52e7326486249ad8d567560bf4ad4
|
[
"MIT"
] | null | null | null |
Source/Homework 10 Includes/MyFloatD.cpp
|
rux616/c201
|
d8509e8d49e52e7326486249ad8d567560bf4ad4
|
[
"MIT"
] | null | null | null |
/*
Name: Dan Cassidy
Date: 2014-04-26
Homework #: 10
Source File: MyFloatD.cpp
Class: C-201 MW 1000
Action: This file represents the detailed abstraction and implementation of the Abstract Data Type
"MyFloat", which is a dynamically-precise decimal (up to 65535 places) between 0 and 1.
In this implementation of the class, trailing zeroes are deemed insignificant. This means
that when comparing two MyFloats, precision does not matter, e.g. 0.10 is considered equal
to 0.1000 but 0.10 is still considered smaller than 0.1001.
When adding two MyFloats, any portion of the result that is larger than 1 is automatically
ignored, e.g. 0.52 + 0.61 = 0.13.
Class Data Members:
unsigned char *Float
A char array that represents the main data structure and has its data in subscripts
0 through a dynamic number. Digits read in are stored, in order, starting at
subscript 0. For example, if the value 0.987 was read in, 9 would be
stored in subscript 0, 8 would be stored in subscript 1, and 7 would be stored in
subscript 2. The rest of the array is zeroed out.
unsigned short NumDigits
An unsigned short that represents the current number of significant digits stored
in Float. If NumDigits is zero then either the MyFloat object has not been
initialized yet, an illegally formatted float was encountered while reading, or
there was an error while allocating dynamic memory for the Float array.
unsigned short MaxLength
An unsigned short that represents the maximum possible number of digits that can
be stored in Float. If MaxLength is zero then there was an error while attempting
to dynamically allocate memory for the Float array.
Class Member Functions:
Digits
Returns the current number of significant digits in a MyFloat object.
MaxDigits
Returns the maximum possible number of digits in a MyFloat object.
Class Operator Overloads:
+
Adds two MyFloat objects together.
<<
Writes a leading zero, a decimal point, and then the contents of the MyFloat
object.
>>
Reads standard input and puts a valid float into a MyFloat object.
>
Compares two MyFloat objects and determines if the left hand side is greater than
the right hand side.
==
Compares two MyFloat objects and determines if they are equal.
= (String)
Converts a string representating a float between 0 and 1 (for example: "0.14159")
to a MyFloat object.
= (MyFloat)
Sets the calling MyFloat object equal to the source MyFloat object.
Class Destructor:
~MyFloat
Frees the dynamically allocated memory once the variable goes out of scope.
Class Constructors:
MyFloat (Default)
Initializes a MyFloat object with a max length of DEFAULT_MAX_LENGTH.
MyFloat (Short Int)
Initializes a MyFloat object with a custom length.
MyFloat (Copy)
Copies the source MyFloat object to the calling MyFloat object.
Detailed descriptions of the member functions' actions including input and output
parameters, return value data types, and preconditions can be found further down in the
file just ahead of their respective functions.
*/
//MYFLOAT ABSTRACTION
#include <iostream>
#include <cstdlib>
using namespace std;
class MyFloat
{
private:
enum { DEFAULT_MAX_LENGTH = 10 };
//Data Members
unsigned char *Float;
unsigned short NumDigits;
unsigned short MaxLength;
public:
//Member Functions
unsigned short Digits();
unsigned short MaxDigits();
//Operator Overloads
const MyFloat operator+(const MyFloat &Other) const;
friend ostream& operator<<(ostream &MFout, const MyFloat &Source);
friend istream& operator>>(istream &MFin, MyFloat &Target);
const bool operator>(const MyFloat &Other) const;
const bool operator==(const MyFloat &Other) const;
const MyFloat& operator=(const char String[]);
const MyFloat& operator=(const MyFloat &Source);
//Destructor
~MyFloat();
//Constructors
MyFloat();
MyFloat(const unsigned short RequestedMaxLength);
MyFloat(const MyFloat &Source);
};
//MYFLOAT IMPLEMENTATION
//Class Member Functions
/****************************** Digits ********************************************************************
Action: Returns the current number of significant digits in a MyFloat. If 0 is returned, then an
illegally formatted float has been detected or the MyFloat has not been initialized yet.
Parameters:
IN: None
OUT: None
Returns: unsigned short representing the number of digits in a MyFloat.
Precondition: None
**********************************************************************************************************/
unsigned short MyFloat::Digits()
{
return NumDigits;
}
/****************************** MaxDigits *****************************************************************
Action: Returns the maximum possible number of digits in a MyFloat.
Parameters:
IN: None
OUT: None
Returns: unsigned short representing the maximum possible number of digits in a MyFloat.
Precondition: None
**********************************************************************************************************/
unsigned short MyFloat::MaxDigits()
{
return MaxLength;
}
//Class Operator Overloads
/****************************** operator+ *****************************************************************
Action: Operator overload for + for the MyFloat class. Adds two MyFloat objects together. If
either MyFloat object is in an error state or is uninitialized, this operation will return
an uninitialized MyFloat object.
Parameters:
IN: const MyFloat &Other, holds the reference to the MyFloat object that will be added to the
calling MyFloat object.
OUT: None
Returns: const MyFloat containing either the sum of the two MyFloats, or an uninitialized MyFloat if
one or both of the MyFloats were in an error state or uninitialized themselves.
Precondition: None
**********************************************************************************************************/
const MyFloat MyFloat::operator+(const MyFloat &Other) const
{
MyFloat Result;
unsigned char CarryBit = 0;
//Verify that both operands are initialized MyFloats. If not, skip the addition and return the still-
//uninitialized MyFloat object Result.
if (NumDigits && Other.NumDigits)
{
//Set Result.NumDigits to whichever NumDigits is greater. This ensures that no precision is lost.
Result.NumDigits = (NumDigits >= Other.NumDigits ? NumDigits : Other.NumDigits);
//Check to make sure the Result MyFloat object is large enough to receive the data from the
//addition operation and if it is not, deallocate the current memory and allocate more.
if (Result.MaxLength < Result.NumDigits)
{
delete[] Result.Float; Result.Float = nullptr;
Result.Float = new (nothrow) unsigned char[Result.NumDigits];
if (Float == nullptr)
{
Result.NumDigits = 0;
Result.MaxLength = 0;
return Result;
}
Result.MaxLength = Result.NumDigits;
}
for (long i = Result.NumDigits - 1; i >= 0; --i)
{
unsigned char Sum = (NumDigits < i + 1 ? 0 : Float[i])
+ (Other.NumDigits < i + 1 ? 0 : Other.Float[i]) + CarryBit;
CarryBit = Sum / 10;
Sum -= CarryBit * 10;
Result.Float[i] = Sum;
}
}
return Result;
}
/****************************** operator<< ****************************************************************
Action: Writes a leading zero, a decimal point, and then the contents of the calling MyFloat
object. If there has been an error in reading, or if the MyFloat object has not been
initialized yet, it will output a question mark instead of the contents of the MyFloat
object after the leading zero and decimal point.
Parameters:
IN: ostream &MFout, holds the reference to the ostream object that will be used to output the
MyFloat object referenced by &Source.
IN: const MyFloat &Source, holds the reference to the MyFloat object that will be output.
OUT: None
Returns: ostream& referencing &MFout in order to facilitate ostream cascading.
Precondition: None
**********************************************************************************************************/
ostream& operator<<(ostream &MFout, const MyFloat &Source)
{
MFout << "0.";
if (Source.NumDigits)
for (unsigned short i = 0; i < Source.NumDigits; ++i)
MFout << int(Source.Float[i]);
else
MFout << "?";
return MFout;
}
/****************************** operator>> ****************************************************************
Action: Reads a MyFloat from standard input. If an error is detected, NumDigits is set to 0. Also
puts the last character read from the input buffer back into it, and zeroes out the rest of
the array.
Parameters:
IN: istream &MFin, holds the reference to the istream object that will be used to input the
MyFloat referenced by &Target.
OUT: MyFloat &Target, holds the reference to the target MyFloat which will receive the input.
Returns: istream& referencing &MFin in order to facilitate istream cascading.
Precondition: None
**********************************************************************************************************/
istream& operator>>(istream &MFin, MyFloat &Target)
{
//Clears anything and everything remaining in the input buffer and then triggers the now empty input
//buffer to ask for input.
cin.ignore(MFin.rdbuf()->in_avail());
MFin.peek();
//Get length of input buffer
unsigned short Length = MFin.rdbuf()->in_avail();
//Dynamically create a char array to hold the user input and if it is created successfully, read in a
//line of user input as a string, and then set Target equal to that utilizing the overloaded =
//operator.
char *Buffer = new (nothrow) char[Length];
if (Buffer != nullptr)
{
MFin.getline(Buffer, Length);
//Put back the last character read from the input buffer because the test program expects at least
//one character in the input buffer.
MFin.unget();
Target = Buffer;
delete[] Buffer; Buffer = nullptr;
}
return MFin;
}
/****************************** operator> *****************************************************************
Action: Operator overload for > for the MyFloat class. Compares two MyFloat objects and determines
if the left hand side is greater than the right hand side. Will compare MyFloat objects
that are in an error status or are uninitalized as well (these are both considered to be
the smallest possible value for a MyFloat object.)
Parameters:
IN: const MyFloat &Other, holds the reference to the MyFloat object that will be compared to
the calling MyFloat object.
OUT: None
Returns: const bool representing whether the left hand side MyFloat object is greater than the right
hand side MyFloat object or not.
Precondition: None
**********************************************************************************************************/
const bool MyFloat::operator>(const MyFloat &Other) const
{
bool IsLessThan = false, IsGreaterThan = false;
//Uninitialized MyFloats are considered to be the smallest possible value, so if the calling MyFloat is
//uninitialized, it is automatically either less than or equal to Other. Conversely, if *this is
//initialized and Other is not, *this is automatically greater than Other.
if (!NumDigits)
IsGreaterThan = false;
else if (!Other.NumDigits)
IsGreaterThan = true;
else
{
//Compare up to the lesser length of the two MyFloat objects.
unsigned short LesserDigits = (NumDigits < Other.NumDigits ? NumDigits : Other.NumDigits);
for (unsigned short i = 0; i < LesserDigits && !IsLessThan && !IsGreaterThan; ++i)
if (Float[i] < Other.Float[i])
IsLessThan = true;
else if (Float[i] > Other.Float[i])
IsGreaterThan = true;
//If the two MyFloat objects are still equal after comparing the smallest number of digits, check
//to make sure they are not equal in length, then test the longer MyFloat object to see if any of
//the remaining digits are not zero. If they are, the longer MyFloat object is automatically
//larger.
if (!IsLessThan && !IsGreaterThan && NumDigits != Other.NumDigits)
{
if (NumDigits < Other.NumDigits)
{
for (unsigned short i = LesserDigits; i < Other.NumDigits && !IsLessThan; ++i)
if (Other.Float[i])
IsLessThan = true;
}
else
for (unsigned short i = LesserDigits; i < NumDigits && !IsGreaterThan; ++i)
if (Float[i])
IsGreaterThan = true;
}
}
return IsGreaterThan;
}
/****************************** operator== ****************************************************************
Action: Operator overload for == for the MyFloat class. Compares two MyFloat objects and
determines if they are equal. Will compare MyFloat objects that are in an error status or
are uninitialized as well. Note that trailing zeroes are deemed insignificant, so 0.1 is
equal to 0.10.
Parameters:
IN: const MyFloat &Other, holds the reference to the MyFloat object that will be compared to
the calling MyFloat object.
OUT: None
Returns: const bool representing whether the two MyFloat objects are equal.
Precondition: None
**********************************************************************************************************/
const bool MyFloat::operator==(const MyFloat &Other) const
{
bool IsEqual = true;
//Compare up to the lesser length of the two MyFloat objects.
unsigned short LesserDigits = (NumDigits < Other.NumDigits ? NumDigits : Other.NumDigits);
for (unsigned short i = 0; i < LesserDigits && IsEqual; ++i)
if (Float[i] != Other.Float[i])
IsEqual = false;
//If the two MyFloat objects are still equal after comparing the smallest number of digits, check to
//make sure they are not equal in length, then test the longer MyFloat object to see if any of the
//remaining digits are not zero. If they are, the longer MyFloat object is automatically larger and
//therefore not equal to the other MyFloat object.
if (IsEqual && NumDigits != Other.NumDigits)
{
if (NumDigits < Other.NumDigits)
{
for (unsigned short i = LesserDigits; i < Other.NumDigits && IsEqual; ++i)
if (Other.Float[i])
IsEqual = false;
}
else
for (unsigned short i = LesserDigits; i < NumDigits && IsEqual; ++i)
if (Float[i])
IsEqual = false;
}
return IsEqual;
}
/****************************** operator= *****************************************************************
Action: Operator overload for = for the MyFloat class. Converts a string representating a float
between 0 and 1 (for example: "0.14159") to a MyFloat. Also zeroes out the unused portion
of the MyFloat.
Parameters:
IN: const char String[], holds the pointer to the null-terminating character array that will be
read in to a MyFloat object.
OUT: None
Returns: const MyFloat& referencing the calling MyFloat object now holding the contents of String[].
Precondition: String must be a null-terminating character array.
**********************************************************************************************************/
const MyFloat& MyFloat::operator=(const char String[])
{
bool Error = false, Finished = false;
unsigned short i = 0, Length = 0;
//Go through the first part of the string until a period is found
for (bool ZeroEncountered = false; String[i] && !Error && !Finished; ++i)
{
if (String[i] == '0')
ZeroEncountered = true;
else if (String[i] == '.')
Finished = true;
else if (isspace(String[i]) && !ZeroEncountered)
;//Do nothing, ignore the whitespace
else
Error = true;
}
if (!Error && !Finished)
//Null encountered before period found.
Error = true;
//Reset the Finished flag for the next loop.
Finished = false;
//Run through the rest of String to get the length of the valid data.
for (unsigned short k = i; String[k] && !Error && !Finished; ++k)
{
if (isdigit(String[k]))
++Length;
else if (!Length)
Error = true;
else
Finished = true;
}
//Check to make sure the calling MyFloat object is large enough to receive the data from String and
//if it is not, deallocate the current memory and allocate more.
if (!Error && MaxLength < Length)
{
delete[] Float; Float = nullptr;
Float = new (nothrow) unsigned char[Length];
if (Float == nullptr)
{
NumDigits = 0;
MaxLength = 0;
return *this;
}
MaxLength = Length;
}
//Reset the Finished flag for the next loop.
Finished = false;
//Run through the rest of String for real to get the data.
for (Length = 0; String[i] && !Error && !Finished; ++i)
{
if (isdigit(String[i]))
Float[Length++] = String[i] - '0';
else
Finished = true;
}
//Determine what NumDigits gets set to.
// 0 if there was an error
// Length if the previous loop encountered a non-numeric (null included)
if (Error)
NumDigits = 0;
else
NumDigits = Length;
//Zero out the remainder of the array.
for (i = NumDigits; i < MaxLength; ++i)
Float[i] = 0;
return *this;
}
/****************************** operator= *****************************************************************
Action: Operator overload for = for the MyFloat class. Performs a deep copy of the source MyFloat
object into the calling MyFloat object and will expand the calling MyFloat object as
necessary. Also zeroes out the unused portion of the Float array in the calling MyFloat
object.
Parameters:
IN: const MyFloat &Source, holds the reference to the MyFloat object that will be deep copied
into the calling MyFloat object.
OUT: None
Returns: const MyFloat& referencing the calling MyFloat object now holding the contents of Source.
Precondition: None
**********************************************************************************************************/
const MyFloat& MyFloat::operator=(const MyFloat &Source)
{
//Don't copy self
if (this == &Source)
return *this;
//Check if the length of calling MyFloat object is sufficient to handle the incoming data from Source
//and if not, deallocate the current memory and allocate more.
if (MaxLength < Source.NumDigits)
{
delete[] Float; Float = nullptr;
Float = new (nothrow) unsigned char[Source.NumDigits];
if (Float == nullptr)
{
NumDigits = 0;
MaxLength = 0;
return *this;
}
MaxLength = Source.NumDigits;
}
NumDigits = Source.NumDigits;
//Deep copy the contents of Source.Float into the calling object's Float.
for (unsigned short i = 0; i < NumDigits; ++i)
Float[i] = Source.Float[i];
//Zero out the unused portion of the array.
for (unsigned short i = NumDigits; i < MaxLength; ++i)
Float[i] = 0;
return *this;
}
//Class Destructor
/****************************** ~MyFloat ******************************************************************
Action: Destructor for the MyFloat class. Deallocates dynamic memory that was allocated to Float
and then sets Float to nullptr for safety.
Parameters:
IN: None
OUT: None
Returns: Nothing
Precondition: Must not be called explicitly.
**********************************************************************************************************/
MyFloat::~MyFloat()
{
//Only need to free the dynamic memory; compiler handles the statics automagically.
delete[] Float;
//Set Float to nullptr just in case someone gets stupid and calls the destructor manually.
Float = nullptr;
}
//Class Constructors
/****************************** MyFloat (Default Constructor) *********************************************
Action: Default constructor for the MyFloat class. Sets NumDigits to 0, MaxLength to
DEFAULT_MAX_LENGTH, attempts to dynamically allocate enough memory for the Float array,
then zeroes it out. If there is an error allocating the required memory to Float,
MaxLength is set to 0.
Parameters:
IN: None
OUT: None
Returns: Nothing
Precondition: None
**********************************************************************************************************/
MyFloat::MyFloat()
{
NumDigits = 0;
MaxLength = DEFAULT_MAX_LENGTH;
//Safe initialization of Float, just in case
Float = nullptr;
Float = new (nothrow) unsigned char[MaxLength];
if (Float != nullptr)
for (unsigned short i = 0; i < MaxLength; ++i)
Float[i] = 0;
else
MaxLength = 0;
}
/****************************** MyFloat (Constructor) *****************************************************
Action: Constructor for the MyFloat class. Sets NumDigits to 0, MaxLength to RequestedMaxLength,
attempts to dynamically allocate enough memory for the Float array, then zeroes it out. If
there is an error allocating the required memory to Float, MaxLength is set to 0.
Parameters:
IN: const unsigned short RequestedMaxLength, holds the requested number of max digits
OUT: None
Returns: Nothing
Precondition: None
**********************************************************************************************************/
MyFloat::MyFloat(const unsigned short RequestedMaxLength)
{
NumDigits = 0;
MaxLength = RequestedMaxLength;
//Safe initialization of Float, just in case
Float = nullptr;
//Added safety measure, just in case 0 gets passed in as the RequestedMaxLength
if (MaxLength)
Float = new (nothrow) unsigned char[MaxLength];
if (Float != nullptr)
for (unsigned short i = 0; i < MaxLength; ++i)
Float[i] = 0;
else
MaxLength = 0;
}
/****************************** MyFloat (Copy Constructor) ************************************************
Action: Copy constructor for the MyFloat class. Sets up a new MyFloat using the MaxLength from
Source as its own MaxLength, then performs a deep copy of Source to the calling MyFloat
object. If there is an error allocating the required memory to Float, NumDigits and
MaxLength are both set to 0.
Parameters:
IN: None
OUT: None
Returns: Nothing
Precondition: None
**********************************************************************************************************/
MyFloat::MyFloat(const MyFloat &Source)
{
NumDigits = Source.NumDigits;
MaxLength = Source.MaxLength;
//Safe initialization of Float, just in case
Float = nullptr;
//Added safety measure in case the copy constructor is called to copy a MyFloat object that failed to
//have dynamic memory allocated to it.
if (MaxLength)
Float = new (nothrow) unsigned char[MaxLength];
if (Float != nullptr)
{
for (unsigned short i = 0; i < MaxLength; ++i)
Float[i] = Source.Float[i];
}
else
{
NumDigits = 0;
MaxLength = 0;
}
}
| 33.266862
| 107
| 0.634124
|
rux616
|
3d11ba5288ab036fa926e5afdacfb198b0b5d5ab
| 595
|
hh
|
C++
|
src/parser/transform.hh
|
jcbaillie/urbi
|
fb17359b2838cdf8d3c0858abb141e167a9d4bdb
|
[
"BSD-3-Clause"
] | 16
|
2016-05-10T05:50:58.000Z
|
2021-10-05T22:16:13.000Z
|
src/parser/transform.hh
|
jcbaillie/urbi
|
fb17359b2838cdf8d3c0858abb141e167a9d4bdb
|
[
"BSD-3-Clause"
] | 7
|
2016-09-05T10:08:33.000Z
|
2019-02-13T10:51:07.000Z
|
src/parser/transform.hh
|
jcbaillie/urbi
|
fb17359b2838cdf8d3c0858abb141e167a9d4bdb
|
[
"BSD-3-Clause"
] | 15
|
2015-01-28T20:27:02.000Z
|
2021-09-28T19:26:08.000Z
|
/*
* Copyright (C) 2008-2010, 2012, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#ifndef PARSER_TRANSFORM_HH
# define PARSER_TRANSFORM_HH
# include <ast/fwd.hh>
# include <urbi/export.hh>
namespace parser
{
template <typename T>
URBI_SDK_API libport::intrusive_ptr<T>
transform(libport::intrusive_ptr<const T> ast);
} // namespace parser
#endif // PARSER_TRANSFORM_HH
| 23.8
| 66
| 0.739496
|
jcbaillie
|
3d1351b6ef7af2fd5e3f7c34d1e7488e77921c28
| 1,536
|
cpp
|
C++
|
c++/solution2055.cpp
|
imafish/leetcodetests
|
abee2c2d6c0b25a21ef4294bceb7e069b6547b85
|
[
"MIT"
] | null | null | null |
c++/solution2055.cpp
|
imafish/leetcodetests
|
abee2c2d6c0b25a21ef4294bceb7e069b6547b85
|
[
"MIT"
] | null | null | null |
c++/solution2055.cpp
|
imafish/leetcodetests
|
abee2c2d6c0b25a21ef4294bceb7e069b6547b85
|
[
"MIT"
] | null | null | null |
#include "afx.h"
using namespace std;
class Solution
{
public:
vector<int> platesBetweenCandles(string s, vector<vector<int>> &queries)
{
std::vector<int> result(queries.size());
prepare(s);
for (int i = 0; i < queries.size(); i++)
{
result[i] = findOne(queries[i]);
}
return result;
}
private:
int findOne(vector<int> &query)
{
int left = _data[query[0]][2];
int right = _data[query[1]][1];
if (left == -1 || right == -1 || left >= right)
{
return 0;
}
int total = _data[right][0] - _data[left][0];
return total;
}
void prepare(const string &s)
{
_data.resize(s.length());
int lastCandle = -1;
int plateIndex = 0;
int i = 0;
for (; i < s.length(); i++)
{
if (s[i] == '|')
{
lastCandle = i;
_data[i][0] = plateIndex;
_data[i][1] = i;
}
else
{
_data[i][0] = plateIndex++;
_data[i][1] = lastCandle;
}
}
lastCandle = -1;
for (i = s.length() - 1; i >= 0; i--)
{
if (s[i] == '|')
{
lastCandle = i;
_data[i][2] = i;
}
else
{
_data[i][2] = lastCandle;
}
}
}
private:
std::vector<std::array<int, 3>> _data;
};
| 21.633803
| 76
| 0.392578
|
imafish
|
3d1664daf4eea73225e3392fbd51715403cca37d
| 85
|
hpp
|
C++
|
shared/logging.hpp
|
cvrebeatsaber/QuestQualifications
|
4be76c3e8da9ead1727e2320fd12c083aabdacad
|
[
"MIT"
] | 1
|
2020-10-07T06:39:16.000Z
|
2020-10-07T06:39:16.000Z
|
shared/logging.hpp
|
cvrebeatsaber/QuestQualifications
|
4be76c3e8da9ead1727e2320fd12c083aabdacad
|
[
"MIT"
] | null | null | null |
shared/logging.hpp
|
cvrebeatsaber/QuestQualifications
|
4be76c3e8da9ead1727e2320fd12c083aabdacad
|
[
"MIT"
] | 1
|
2021-06-02T23:13:46.000Z
|
2021-06-02T23:13:46.000Z
|
#pragma once
#include "beatsaber-hook/shared/utils/logging.hpp"
Logger& getLogger();
| 21.25
| 50
| 0.776471
|
cvrebeatsaber
|
3d168d4f61ba906957acecbee97cc126344c1c1e
| 936
|
cpp
|
C++
|
1000/90/1091b.cpp
|
actium/cf
|
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
|
[
"Unlicense"
] | 1
|
2020-07-03T15:55:52.000Z
|
2020-07-03T15:55:52.000Z
|
1000/90/1091b.cpp
|
actium/cf
|
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
|
[
"Unlicense"
] | null | null | null |
1000/90/1091b.cpp
|
actium/cf
|
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
|
[
"Unlicense"
] | 3
|
2020-10-01T14:55:28.000Z
|
2021-07-11T11:33:58.000Z
|
#include <iostream>
#include <vector>
using distance_t = std::pair<int, int>;
template <typename T, typename U>
std::istream& operator >>(std::istream& input, std::pair<T, U>& v)
{
return input >> v.first >> v.second;
}
template <typename T>
std::istream& operator >>(std::istream& input, std::vector<T>& v)
{
for (T& a : v)
input >> a;
return input;
}
void answer(int x, int y)
{
std::cout << x << ' ' << y << '\n';
}
void solve(const std::vector<distance_t>& p, const std::vector<distance_t>& d)
{
const size_t n = p.size();
long long sx = 0, sy = 0;
for (size_t i = 0; i < n; ++i) {
sx+= p[i].first + d[i].first;
sy += p[i].second + d[i].second;
}
answer(sx / n, sy / n);
}
int main()
{
size_t n;
std::cin >> n;
std::vector<distance_t> p(n);
std::cin >> p;
std::vector<distance_t> d(n);
std::cin >> d;
solve(p, d);
return 0;
}
| 17.018182
| 78
| 0.536325
|
actium
|
3d1917251618d0eaf76c8f81b742f05eeb14d345
| 1,502
|
hpp
|
C++
|
src/storage/tree/Units.hpp
|
nopdotcom/opentxs
|
140428ba8f1bd4c09654ebf0a1c1725f396efa8b
|
[
"MIT"
] | null | null | null |
src/storage/tree/Units.hpp
|
nopdotcom/opentxs
|
140428ba8f1bd4c09654ebf0a1c1725f396efa8b
|
[
"MIT"
] | null | null | null |
src/storage/tree/Units.hpp
|
nopdotcom/opentxs
|
140428ba8f1bd4c09654ebf0a1c1725f396efa8b
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2018 The Open-Transactions developers
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#pragma once
#include "Internal.hpp"
#include "opentxs/api/storage/Storage.hpp"
#include "opentxs/api/Editor.hpp"
#include "Node.hpp"
namespace opentxs
{
namespace storage
{
class Tree;
class Units : public Node
{
private:
friend class Tree;
void init(const std::string& hash) override;
bool save(const std::unique_lock<std::mutex>& lock) const override;
proto::StorageUnits serialize() const;
Units(const opentxs::api::storage::Driver& storage, const std::string& key);
Units() = delete;
Units(const Units&) = delete;
Units(Units&&) = delete;
Units operator=(const Units&) = delete;
Units operator=(Units&&) = delete;
public:
std::string Alias(const std::string& id) const;
bool Load(
const std::string& id,
std::shared_ptr<proto::UnitDefinition>& output,
std::string& alias,
const bool checking) const;
void Map(UnitLambda lambda) const;
bool Delete(const std::string& id);
bool SetAlias(const std::string& id, const std::string& alias);
bool Store(
const proto::UnitDefinition& data,
const std::string& alias,
std::string& plaintext);
~Units() = default;
};
} // namespace storage
} // namespace opentxs
| 25.896552
| 80
| 0.669774
|
nopdotcom
|
3d1ab9f4ddd01a8fbb879a714ab87f1c44a5daaa
| 37,750
|
cpp
|
C++
|
Fuji/Source/MFString.cpp
|
TurkeyMan/fuji
|
afd6a26c710ce23965b088ad158fe916d6a1a091
|
[
"BSD-2-Clause"
] | 35
|
2015-01-19T22:07:48.000Z
|
2022-02-21T22:17:53.000Z
|
Fuji/Source/MFString.cpp
|
TurkeyMan/fuji
|
afd6a26c710ce23965b088ad158fe916d6a1a091
|
[
"BSD-2-Clause"
] | 1
|
2022-02-23T09:34:15.000Z
|
2022-02-23T09:34:15.000Z
|
Fuji/Source/MFString.cpp
|
TurkeyMan/fuji
|
afd6a26c710ce23965b088ad158fe916d6a1a091
|
[
"BSD-2-Clause"
] | 4
|
2015-05-11T03:31:35.000Z
|
2018-09-27T04:55:57.000Z
|
#include "Fuji_Internal.h"
#include "MFString.h"
#include "MFHeap_Internal.h"
#include "MFObjectPool.h"
#include <stdio.h>
#include <stdarg.h>
#define stricmp strcasecmp
#include <string.h>
MFObjectPool stringPool;
MFObjectPoolGroup stringHeap;
int gModuleInitCount = 0;
// this is okay as global; it can be shared or duplicated freely
MFALIGN_BEGIN(16)
static char gStringBuffer[1024*128]
MFALIGN_END(16);
static size_t gStringOffset = 0;
static const MFObjectPoolGroupConfig gStringGroups[] =
{
{ 5, 256, 128 },
{ 16, 512, 128 },
{ 128, 32, 16 },
{ 1024, 4, 4 }
};
MFInitStatus MFString_InitModule(int moduleId, bool bPerformInitialisation)
{
if(!bPerformInitialisation)
return MFIS_Succeeded;
if(gModuleInitCount == 0)
{
++gModuleInitCount;
stringHeap.Init(gStringGroups, sizeof(gStringGroups) / sizeof(gStringGroups[0]));
stringPool.Init(sizeof(MFStringData), 128, 128);
}
return MFIS_Succeeded;
}
void MFString_DeinitModule()
{
if(--gModuleInitCount == 0)
{
stringPool.Deinit();
stringHeap.Deinit();
}
}
MF_API MFString MFString_GetStats()
{
size_t overhead = stringPool.GetTotalMemory() + stringPool.GetOverheadMemory() + stringHeap.GetOverheadMemory();
size_t waste = 0, averageSize = 0;
// calculate waste
int numStrings = stringPool.GetNumAllocated();
for(int a=0; a<numStrings; ++a)
{
MFStringData *pString = (MFStringData*)stringPool.GetItem(a);
size_t allocated = pString->allocated;
if(allocated)
{
size_t bytes = pString->bytes+1;
averageSize += bytes;
waste += allocated - bytes;
}
}
if(numStrings)
averageSize /= numStrings;
MFString desc;
desc.Reserve(1024);
desc = MFStr("String heap memory: " MFFMT_SIZE_T " allocated/" MFFMT_SIZE_T " reserved + " MFFMT_SIZE_T " overhead Waste: " MFFMT_SIZE_T " Average length: " MFFMT_SIZE_T "\n\tPool: %d/%d", stringHeap.GetAllocatedMemory(), stringHeap.GetTotalMemory(), overhead, waste, averageSize, stringPool.GetNumAllocated(), stringPool.GetNumReserved());
int numGroups = stringHeap.GetNumPools();
for(int a=0; a<numGroups; ++a)
{
MFObjectPool *pPool = stringHeap.GetPool(a);
desc += MFStr("\n\t\t" MFFMT_SIZE_T " byte: %d/%d", pPool->GetObjectSize(), pPool->GetNumAllocated(), pPool->GetNumReserved());
}
return desc;
}
MF_API void MFString_Dump()
{
MFString temp = MFString_GetStats();
MFDebug_Log(1, "\n-------------------------------------------------------------------------------------------------------");
MFDebug_Log(1, temp.CStr());
// dump all strings...
MFDebug_Log(1, "");
int numStrings = stringPool.GetNumAllocated();
for(int a=0; a<numStrings; ++a)
{
MFStringData *pString = (MFStringData*)stringPool.GetItem(a);
MFDebug_Log(1, MFStr("%d refs, " MFFMT_SIZE_T "b: \"%s\"", pString->refCount, pString->allocated, pString->pMemory));
}
}
MF_API void *MFCopyMemory(void *pDest, const void *pSrc, size_t size)
{
return memcpy(pDest, pSrc, size);
}
MF_API void *MFMemSet(void *pDest, int value, size_t size)
{
return memset(pDest, value, size);
}
MF_API void *MFZeroMemory(void *pDest, size_t size)
{
return memset(pDest, 0, size);
}
MF_API int MFMemCompare(const void *pBuf1, const void *pBuf2, size_t size)
{
return memcmp(pBuf1, pBuf2, size);
}
MF_API char* MFString_Dup(const char *pString)
{
size_t len = MFString_Length(pString);
char *pNew = (char*)MFHeap_Alloc(len + 1);
MFString_Copy(pNew, pString);
return pNew;
}
MF_API const char * MFString_ToLower(const char *pString)
{
char *pBuffer = &gStringBuffer[gStringOffset];
size_t len = MFString_Length(pString);
gStringOffset += len+1;
char *pT = pBuffer;
while(*pString)
{
*pT = (char)MFToLower(*pString);
++pT;
++pString;
}
if(gStringOffset >= sizeof(gStringBuffer) - 1024) gStringOffset = 0;
return pBuffer;
}
MF_API const char * MFString_ToUpper(const char *pString)
{
char *pBuffer = &gStringBuffer[gStringOffset];
size_t len = MFString_Length(pString);
gStringOffset += len+1;
char *pT = pBuffer;
while(*pString)
{
*pT = (char)MFToUpper(*pString);
++pT;
++pString;
}
if(gStringOffset >= sizeof(gStringBuffer) - 1024) gStringOffset = 0;
return pBuffer;
}
MF_API const char * MFStr(const char *format, ...)
{
va_list arglist;
char *pBuffer = &gStringBuffer[gStringOffset];
int nRes = 0;
va_start(arglist, format);
nRes = vsprintf(pBuffer, format, arglist);
gStringOffset += nRes+1;
if(gStringOffset >= sizeof(gStringBuffer) - 1024) gStringOffset = 0;
va_end(arglist);
return pBuffer;
}
MF_API const char * MFStrN(const char *pSource, size_t n)
{
char *pBuffer = &gStringBuffer[gStringOffset];
MFString_CopyN(pBuffer, pSource, (int)n);
pBuffer[n] = 0;
gStringOffset += (uint32)n+1;
if(gStringOffset >= sizeof(gStringBuffer) - 1024) gStringOffset = 0;
return pBuffer;
}
MF_API int MFString_Compare(const char *pString1, const char *pString2)
{
while(*pString1 == *pString2++)
{
if(*pString1++ == 0)
return 0;
}
return (*(const unsigned char *)pString1 - *(const unsigned char *)(pString2 - 1));
}
MF_API int MFString_CompareN(const char *pString1, const char *pString2, size_t n)
{
if(n == 0)
return 0;
do
{
if(*pString1 != *pString2++)
return (*(const unsigned char *)pString1 - *(const unsigned char *)(pString2 - 1));
if(*pString1++ == 0)
break;
}
while(--n != 0);
return 0;
}
MF_API int MFString_CaseCmp(const char *pSource1, const char *pSource2)
{
register unsigned int c1, c2;
do
{
c1 = MFToUpper(*pSource1++);
c2 = MFToUpper(*pSource2++);
}
while(c1 && (c1 == c2));
return c1 - c2;
}
MF_API int MFString_CaseCmpN(const char *pSource1, const char *pSource2, size_t n)
{
register int c = 0;
while(n)
{
if((c = MFToUpper(*pSource1) - MFToUpper(*pSource2++) ) != 0 || !*pSource1++)
break;
n--;
}
return c;
}
MF_API bool MFString_PatternMatch(const char *pPattern, const char *pFilename, const char **ppMatchDirectory, bool bCaseSensitive)
{
if(!pPattern || !pFilename)
return false;
while(*pPattern && *pFilename)
{
if(*pPattern == '?')
{
if(*pFilename == '/' || *pFilename == '\\')
break;
}
else if(*pPattern == '*')
{
++pPattern;
// if an asterisk is the last character in the pattern, it's a match!
if(*pPattern == 0)
return true;
bool match = false;
while(*pFilename)
{
match = MFString_PatternMatch(pPattern, pFilename, ppMatchDirectory);
if(match)
break;
if(*pFilename == '/' || *pFilename == '\\')
break;
++pFilename;
}
return match;
}
else if((bCaseSensitive && *pPattern != *pFilename) || (!bCaseSensitive && MFToLower(*pPattern) != MFToLower(*pFilename)))
break;
++pPattern;
++pFilename;
}
if(*pPattern == 0)
{
if((*pFilename == '/' || *pFilename == '\\') && ppMatchDirectory)
*ppMatchDirectory = pFilename + 1;
if((ppMatchDirectory && *ppMatchDirectory) || *pFilename == 0)
return true;
}
return false;
}
MF_API const char* MFStr_URLEncodeString(const char *pString, const char *pExcludeChars)
{
char *pBuffer = &gStringBuffer[gStringOffset];
size_t sourceLen = MFString_Length(pString);
size_t destLen = 0;
for(size_t a=0; a<sourceLen; ++a)
{
int c = (uint8)pString[a];
if(MFIsAlphaNumeric(c) || MFString_Chr("-_.!~*'()", c) || (pExcludeChars && MFString_Chr(pExcludeChars, c)))
pBuffer[destLen++] = (char)c;
else if(c == ' ')
pBuffer[destLen++] = '+';
else
destLen += sprintf(pBuffer + destLen, "%%%02X", c);
}
pBuffer[destLen] = 0;
gStringOffset += destLen+1;
if(gStringOffset >= sizeof(gStringBuffer) - 1024)
gStringOffset = 0;
return pBuffer;
}
MF_API size_t MFString_URLEncode(char *pDest, const char *pString, const char *pExcludeChars)
{
size_t sourceLen = MFString_Length(pString);
size_t destLen = 0;
for(size_t a=0; a<sourceLen; ++a)
{
int c = (uint8)pString[a];
if(MFIsAlphaNumeric(c) || MFString_Chr("-_.!~*'()", c) || (pExcludeChars && MFString_Chr(pExcludeChars, c)))
{
if(pDest)
pDest[destLen] = (char)c;
destLen++;
}
else if(c == ' ')
{
if(pDest)
pDest[destLen] = '+';
destLen++;
}
else
{
if(pDest)
destLen += sprintf(pDest + destLen, "%%%02X", c);
else
destLen += 3; // *** surely this can't write more than 3 chars? '%xx'
}
}
if(pDest)
pDest[destLen] = 0;
return destLen;
}
MF_API bool MFString_IsNumber(const char *pString, bool bAllowHex)
{
pString = MFSkipWhite(pString);
int numDigits = 0;
if(bAllowHex && pString[0] == '0' && pString[1] == 'x')
{
// hex number
pString += 2;
while(*pString)
{
if(!MFIsHex(*pString++))
return false;
++numDigits;
}
}
else
{
// decimal number
if(*pString == '-' || *pString == '+')
++pString;
bool bHasDot = false;
while(*pString)
{
if(!MFIsNumeric(*pString) && (bHasDot || *pString != '.'))
return false;
if(*pString++ == '.')
{
bHasDot = true;
numDigits = 0;
}
else
++numDigits;
}
}
return numDigits > 0 ? true : false;
}
MF_API int MFString_AsciiToInteger(const char *pString, bool bDetectBase, int base, const char **ppNextChar)
{
pString = MFSkipWhite(pString);
int number = 0;
if(base == 16 || (bDetectBase && ((pString[0] == '0' && pString[1] == 'x') || pString[0] == '$')))
{
// hex number
if(pString[0] == '0' && pString[1] == 'x')
pString += 2;
else if(pString[0] == '$')
pString += 1;
while(*pString)
{
int digit = *pString++;
if(!MFIsHex(digit))
return number;
number <<= 4;
number += MFIsNumeric(digit) ? digit - '0' : MFToLower(digit) - 'a' + 10;
}
}
else if(base == 2 || (bDetectBase && pString[0] == 'b'))
{
if(pString[0] == 'b')
++pString;
while(*pString == '0' || *pString == '1')
{
number <<= 1;
number |= *pString - '0';
}
}
else if(base == 10)
{
// decimal number
bool neg = false;
if(*pString == '-' || *pString == '+')
{
neg = *pString == '-';
++pString;
}
while(*pString)
{
if(!MFIsNumeric(*pString))
return neg ? -number : number;
number = number*10 + (*pString++) - '0';
}
if(neg)
number = -number;
}
if(ppNextChar)
*ppNextChar = pString;
return number;
}
MF_API float MFString_AsciiToFloat(const char *pString, const char **ppNextChar)
{
pString = MFSkipWhite(pString);
int64 number = 0;
float frac = 1;
// floating poiont number
bool neg = false;
if(*pString == '-' || *pString == '+')
{
neg = *pString == '-';
++pString;
}
bool bHasDot = false;
while(*pString)
{
int digit = *pString++;
if(!MFIsNumeric(digit) && (bHasDot || digit != '.'))
return (float)(neg ? -number : number) * frac;
if(digit == '.')
bHasDot = true;
else
{
number = number*10 + digit - '0';
if(bHasDot)
frac *= 0.1f;
}
}
if(neg)
number = -number;
if(ppNextChar)
*ppNextChar = pString;
return (float)number * frac;
}
MF_API int MFString_Enumerate(const char *pString, const char **ppKeys, size_t numKeys, bool bCaseSensitive)
{
for(size_t i=0; i<numKeys && ppKeys[i]; ++i)
{
if(bCaseSensitive ? !MFString_Compare(pString, ppKeys[i]) : !MFString_CaseCmp(pString, ppKeys[i]))
return (int)i;
}
return -1;
}
#if 0
char* MFString_Copy(char *pDest, const char *pSrc)
{
#if !defined(PREFER_SPEED_OVER_SIZE)
char *s = pDest;
while(*pDest++ = *pSrc++) { }
return s;
#else
char *dst = dst0;
_CONST char *src = src0;
long *aligned_dst;
_CONST long *aligned_src;
/* If SRC or DEST is unaligned, then copy bytes. */
if (!UNALIGNED (src, dst))
{
aligned_dst = (long*)dst;
aligned_src = (long*)src;
/* SRC and DEST are both "long int" aligned, try to do "long int"
sized copies. */
while (!DETECTNULL(*aligned_src))
{
*aligned_dst++ = *aligned_src++;
}
dst = (char*)aligned_dst;
src = (char*)aligned_src;
}
while (*dst++ = *src++)
;
return dst0;
#endif
}
char* MFString_CopyN(char *pDest, const char *pSrc, int n)
{
#if !defined(PREFER_SPEED_OVER_SIZE)
char *dscan;
const char *sscan;
dscan = pDest;
sscan = pSrc;
while(n > 0)
{
--n;
if((*dscan++ = *sscan++) == '\0')
break;
}
while(n-- > 0)
*dscan++ = '\0';
return pDest;
#else
char *dst = dst0;
_CONST char *src = src0;
long *aligned_dst;
_CONST long *aligned_src;
/* If SRC and DEST is aligned and count large enough, then copy words. */
if(!UNALIGNED (src, dst) && !TOO_SMALL (count))
{
aligned_dst = (long*)dst;
aligned_src = (long*)src;
/* SRC and DEST are both "long int" aligned, try to do "long int"
sized copies. */
while(count >= sizeof (long int) && !DETECTNULL(*aligned_src))
{
count -= sizeof (long int);
*aligned_dst++ = *aligned_src++;
}
dst = (char*)aligned_dst;
src = (char*)aligned_src;
}
while(count > 0)
{
--count;
if((*dst++ = *src++) == '\0')
break;
}
while(count-- > 0)
*dst++ = '\0';
return dst0;
#endif
}
char* MFString_Cat(char *pDest, const char *pSrc)
{
#if !defined(PREFER_SPEED_OVER_SIZE)
char *s = pDest;
while(*pDest) pDest++;
while(*pDest++ = *pSrc++) { }
return s;
#else
char *s = s1;
/* Skip over the data in s1 as quickly as possible. */
if (ALIGNED (s1))
{
unsigned long *aligned_s1 = (unsigned long *)s1;
while (!DETECTNULL (*aligned_s1))
aligned_s1++;
s1 = (char *)aligned_s1;
}
while (*s1)
s1++;
/* s1 now points to the its trailing null character, we can
just use strcpy to do the work for us now.
?!? We might want to just include strcpy here.
Also, this will cause many more unaligned string copies because
s1 is much less likely to be aligned. I don't know if its worth
tweaking strcpy to handle this better. */
MFString_Copy(s1, s2);
return s;
#endif
}
char* MFString_CopyCat(char *pDest, const char *pSrc, const char *pSrc2)
{
#if !defined(PREFER_SPEED_OVER_SIZE)
char *s = pDest;
while(*pDest = *pSrc++) { ++pDest; }
while(*pDest++ = *pSrc2++) { }
return s;
#else
char *dst = dst0;
_CONST char *src = src0;
long *aligned_dst;
_CONST long *aligned_src;
/* If SRC or DEST is unaligned, then copy bytes. */
if (!UNALIGNED (src, dst))
{
aligned_dst = (long*)dst;
aligned_src = (long*)src;
/* SRC and DEST are both "long int" aligned, try to do "long int"
sized copies. */
while (!DETECTNULL(*aligned_src))
{
*aligned_dst++ = *aligned_src++;
}
dst = (char*)aligned_dst;
src = (char*)aligned_src;
}
while (*dst++ = *src++)
;
return dst0;
#endif /* not PREFER_SIZE_OVER_SPEED */
}
#endif
//
// UTF8 support
//
MF_API size_t MFWString_CopyUTF8ToUTF16(wchar_t *pBuffer, const char *pString)
{
const wchar_t *pStart = pBuffer;
while(*pString)
{
int c;
pString += MFString_DecodeUTF8(pString, &c);
*pBuffer++ = (wchar_t)c;
}
*pBuffer = 0;
return pBuffer - pStart;
}
MF_API size_t MFString_CopyUTF16ToUTF8(char *pBuffer, const wchar_t *pString)
{
const char *pStart = pBuffer;
while(*pString)
pBuffer += MFString_EncodeUTF8(*pString++, pBuffer);
*pBuffer = 0;
return pBuffer - pStart;
}
MF_API wchar_t* MFString_UFT8AsWChar(const char *pUTF8String, size_t *pNumChars)
{
// count number of actual characters in the string
size_t numChars = MFString_GetNumChars(pUTF8String);
// get some space in the MFStr buffer
if(gStringOffset & 1)
++gStringOffset;
wchar_t *pBuffer = (wchar_t*)&gStringBuffer[gStringOffset];
gStringOffset += numChars*2 + 2;
// if we wrapped the string buffer
if(gStringOffset >= sizeof(gStringBuffer) - 1024)
{
gStringOffset = numChars*2 + 2;
pBuffer = (wchar_t*)gStringBuffer;
}
// copy the string
MFWString_CopyUTF8ToUTF16(pBuffer, pUTF8String);
if(pNumChars)
*pNumChars = numChars;
return pBuffer;
}
MF_API char* MFString_WCharAsUTF8(const wchar_t *pWString, size_t *pNumBytes)
{
// count number of actual characters in the string
size_t numBytes = 0;
const wchar_t *pCount = pWString;
while (*pCount)
numBytes += MFString_EncodeUTF8(*pCount++, NULL);
// get some space in the MFStr buffer
char *pBuffer = &gStringBuffer[gStringOffset];
gStringOffset += numBytes + 1;
// if we wrapped the string buffer
if (gStringOffset >= sizeof(gStringBuffer) - 1024)
{
gStringOffset = numBytes + 1;
pBuffer = gStringBuffer;
}
// copy the string
MFString_CopyUTF16ToUTF8(pBuffer, pWString);
if (pNumBytes)
*pNumBytes = numBytes;
return pBuffer;
}
//
// unicode support
//
MF_API wchar_t* MFWString_Dup(const wchar_t *pString)
{
size_t len = MFWString_Length(pString);
wchar_t *pNew = (wchar_t*)MFHeap_Alloc((len + 1)*sizeof(wchar_t));
MFWString_Copy(pNew, pString);
return pNew;
}
MF_API const wchar_t * MFWStr(const wchar_t *format, ...)
{
va_list arglist;
gStringOffset += gStringOffset & 1;
wchar_t *pBuffer = (wchar_t*)&gStringBuffer[gStringOffset];
int nRes = 0;
va_start(arglist, format);
nRes = vswprintf(pBuffer, format, arglist);
gStringOffset += (nRes + 1)*sizeof(wchar_t);
if (gStringOffset >= sizeof(gStringBuffer) - 1024) gStringOffset = 0;
va_end(arglist);
return pBuffer;
}
MF_API const wchar_t * MFWStrN(const wchar_t *pSource, size_t n)
{
gStringOffset += gStringOffset & 1;
wchar_t *pBuffer = (wchar_t*)&gStringBuffer[gStringOffset];
MFWString_CopyN(pBuffer, pSource, n);
pBuffer[n] = 0;
gStringOffset += (n + 1)*sizeof(wchar_t);
if (gStringOffset >= sizeof(gStringBuffer) - 1024) gStringOffset = 0;
return pBuffer;
}
MF_API int MFWString_Compare(const wchar_t *pString1, const wchar_t *pString2)
{
while(*pString1 == *pString2++)
{
if(*pString1++ == 0)
return 0;
}
return (*(const uint16 *)pString1 - *(const uint16 *)(pString2 - 1));
}
MF_API int MFWString_CaseCmp(const wchar_t *pSource1, const wchar_t *pSource2)
{
register unsigned int c1, c2;
do
{
c1 = MFToUpper(*pSource1++);
c2 = MFToUpper(*pSource2++);
}
while(c1 && (c1 == c2));
return c1 - c2;
}
MF_API int MFWString_CompareUTF8(const wchar_t *pString1, const char *pString2)
{
int c;
int len = MFString_DecodeUTF8(pString2, &c);
pString2 += len;
while(*pString1 == c)
{
if(*pString1++ == 0)
return 0;
len = MFString_DecodeUTF8(pString2, &c);
pString2 += len;
}
return *(const uint16 *)pString1 - c;
}
/**** MFString Functions ****/
MF_API MFStringData *MFStringData_Alloc()
{
MFStringData *pData = (MFStringData*)stringPool.Alloc();
pData->refCount = 1;
pData->pMemory = NULL;
pData->allocated = pData->bytes = 0;
return pData;
}
MF_API void MFStringData_Destroy(MFStringData *pStringData)
{
if(pStringData->allocated)
stringHeap.Free(pStringData->pMemory);
stringPool.Free(pStringData);
}
MF_API char *MFStringHeap_Alloc(size_t bytes, size_t *pAllocated)
{
return (char*)stringHeap.Alloc(bytes, pAllocated);
}
MF_API void MFStringHeap_Free(char *pString)
{
stringHeap.Free(pString);
}
__forceinline void MFStringData_Release(MFStringData *pStringData)
{
if(--pStringData->refCount == 0)
MFStringData_Destroy(pStringData);
}
MFString::MFString(const char *pString, bool bHoldStaticPointer)
{
if(!pString)
{
pData = NULL;
}
else
{
pData = MFStringData_Alloc();
pData->bytes = MFString_Length(pString);
if(bHoldStaticPointer)
{
pData->pMemory = (char*)pString;
}
else
{
pData->pMemory = (char*)stringHeap.Alloc(pData->bytes + 1, &pData->allocated);
MFString_Copy(pData->pMemory, pString);
}
}
}
MFString::MFString(const char *pString, size_t maxChars)
{
if(!pString)
{
pData = NULL;
}
else
{
pData = MFStringData_Alloc();
pData->bytes = MFString_LengthN(pString, (int)maxChars);
pData->pMemory = (char*)stringHeap.Alloc(pData->bytes + 1, &pData->allocated);
MFString_CopyN(pData->pMemory, pString, (int)pData->bytes);
pData->pMemory[pData->bytes] = 0;
}
}
MFString& MFString::operator=(const char *pString)
{
if(pString)
{
size_t bytes = MFString_Length(pString);
Reserve(bytes + 1, true);
MFString_Copy(pData->pMemory, pString);
pData->bytes = bytes;
}
else if(pData)
{
MFStringData_Release(pData);
pData = NULL;
}
return *this;
}
MFString& MFString::operator=(const MFString &string)
{
if(pData)
MFStringData_Release(pData);
pData = string.pData;
if(pData)
++pData->refCount;
return *this;
}
MFString& MFString::operator+=(char c)
{
Reserve(NumBytes() + 2);
pData->pMemory[pData->bytes++] = c;
pData->pMemory[pData->bytes] = 0;
return *this;
}
MFString& MFString::operator+=(const char *pString)
{
if(!pString || *pString == 0)
return *this;
if(IsEmpty())
{
*this = pString;
}
else
{
size_t sumBytes = pData->bytes + MFString_Length(pString);
Reserve(sumBytes + 1);
MFString_Copy(pData->pMemory + pData->bytes, pString);
pData->bytes = sumBytes;
}
return *this;
}
MFString& MFString::operator+=(const MFString &string)
{
if(string.IsEmpty())
return *this;
if(IsEmpty())
{
*this = string;
}
else
{
size_t sumBytes = pData->bytes + string.pData->bytes;
Reserve(sumBytes + 1);
MFString_Copy(pData->pMemory + pData->bytes, string.pData->pMemory);
pData->bytes = sumBytes;
}
return *this;
}
MFString MFString::operator+(char c) const
{
MFString s = *this;
s += c;
return s;
}
MFString MFString::operator+(const char *pString) const
{
if(!pString || *pString == 0)
return *this;
if(IsEmpty())
return MFString(pString);
size_t bytes = pData->bytes + MFString_Length(pString);
MFString t;
t.Reserve(bytes + 1);
MFString_CopyCat(t.pData->pMemory, pData->pMemory, pString);
t.pData->bytes = bytes;
return t;
}
MFString MFString::operator+(const MFString &string) const
{
if(string.IsEmpty())
return *this;
if(IsEmpty())
return string;
size_t bytes = pData->bytes + string.pData->bytes;
MFString t;
t.Reserve(bytes + 1);
MFString_CopyCat(t.pData->pMemory, pData->pMemory, string.pData->pMemory);
t.pData->bytes = bytes;
return t;
}
MFString operator+(const char *pString, const MFString &string)
{
if(string.IsEmpty())
return MFString(pString);
if(!pString || *pString == 0)
return string;
return MFString::Static(pString) + string;
}
MFString& MFString::SetStaticString(const char *pStaticString)
{
if(pData)
{
MFStringData_Release(pData);
pData = NULL;
}
if(pStaticString)
{
pData = MFStringData_Alloc();
pData->bytes = MFString_Length(pStaticString);
pData->pMemory = (char*)pStaticString;
}
return *this;
}
MFString& MFString::FromUTF16(const wchar_t *pString)
{
if(pData)
{
MFStringData_Release(pData);
pData = NULL;
}
if(pString)
{
pData = MFStringData_Alloc();
size_t len = 0;
const wchar_t *pS = pString;
while(*pS)
len += MFString_EncodeUTF8(*pS++, NULL);
pData->bytes = len;
pData->pMemory = (char*)stringHeap.Alloc(pData->bytes + 1, &pData->allocated);
MFString_CopyUTF16ToUTF8(pData->pMemory, (const wchar_t*)pString);
}
return *this;
}
MFString& MFString::Detach(size_t reserveBytes)
{
if(pData && (pData->refCount > 1 || pData->allocated == 0))
{
MFStringData *pNew = MFStringData_Alloc();
pNew->bytes = pData->bytes;
pNew->pMemory = (char*)stringHeap.Alloc(MFMax(pNew->bytes + 1, reserveBytes), &pNew->allocated);
MFString_Copy(pNew->pMemory, pData->pMemory);
MFStringData_Release(pData);
pData = pNew;
}
return *this;
}
MFString& MFString::Reserve(size_t bytes, bool bClearString)
{
// detach instance
Detach(bytes);
// allocate memory
if(!pData)
{
pData = MFStringData_Alloc();
pData->pMemory = (char*)stringHeap.Alloc(bytes, &pData->allocated);
pData->pMemory[0] = 0;
pData->bytes = 0;
}
else
{
if(bytes > pData->allocated)
{
bool bNeedFree = pData->allocated != 0;
char *pNew = (char*)stringHeap.Alloc(bytes, &pData->allocated);
if(!bClearString)
MFString_Copy(pNew, pData->pMemory);
if(bNeedFree)
stringHeap.Free(pData->pMemory);
pData->pMemory = pNew;
}
if(bClearString)
{
pData->bytes = 0;
pData->pMemory[0] = 0;
}
}
return *this;
}
MFString& MFString::Sprintf(const char *pFormat, ...)
{
if(pData)
{
MFStringData_Release(pData);
pData = NULL;
}
va_list arglist;
va_start(arglist, pFormat);
int nRes = vsnprintf(NULL, 0, pFormat, arglist);
va_start(arglist, pFormat);
if(nRes >= 0)
{
pData = MFStringData_Alloc();
pData->bytes = nRes;
pData->pMemory = (char*)stringHeap.Alloc(pData->bytes + 1, &pData->allocated);
vsprintf(pData->pMemory, pFormat, arglist);
}
va_end(arglist);
return *this;
}
MFString MFString::Format(const char *pFormat, ...)
{
MFString t;
va_list arglist;
va_start(arglist, pFormat);
int nRes = vsnprintf(NULL, 0, pFormat, arglist);
va_start(arglist, pFormat);
if(nRes >= 0)
{
t.pData = MFStringData_Alloc();
t.pData->bytes = nRes;
t.pData->pMemory = (char*)stringHeap.Alloc(t.pData->bytes + 1, &t.pData->allocated);
vsprintf(t.pData->pMemory, pFormat, arglist);
}
va_end(arglist);
return t;
}
MFString& MFString::FromInt(int number)
{
Sprintf("%d", number);
return *this;
}
MFString& MFString::FromFloat(float number)
{
Sprintf("%g", number);
return *this;
}
MFString MFString::Upper() const
{
if(!pData)
return *this;
// allocate a new string
MFString t;
t.Reserve(pData->bytes + 1);
t.pData->bytes = pData->bytes;
// copy upper case
for(size_t a=0; a<pData->bytes + 1; ++a)
t.pData->pMemory[a] = (char)MFToUpper(pData->pMemory[a]);
return t;
}
MFString MFString::Lower() const
{
if(!pData)
return *this;
// allocate a new string
MFString t;
t.Reserve(pData->bytes + 1);
t.pData->bytes = pData->bytes;
// copy lower case string
for(size_t a=0; a<pData->bytes + 1; ++a)
t.pData->pMemory[a] = (char)MFToLower(pData->pMemory[a]);
return t;
}
MFString& MFString::Trim(bool bFront, bool bEnd, const char *pCharacters)
{
if(pData)
{
const char *pSrc = pData->pMemory;
size_t offset = 0;
// trim start
if(bFront)
{
while(pSrc[offset] && MFString_Chr(pCharacters, pSrc[offset]))
++offset;
}
size_t count = pData->bytes - offset;
// trim end
if(bEnd)
{
const char *pEnd = pSrc + offset + count - 1;
while(count && MFString_Chr(pCharacters, *pEnd))
{
--count;
--pEnd;
}
}
*this = SubStr((int)offset, (int)count);
}
return *this;
}
MFString& MFString::PadLeft(int minLength, const char *pPadding)
{
// check if the string is already long enough
int len = NumBytes();
if(len >= minLength)
return *this;
// reserve enough memory
Reserve(minLength + 1);
pData->bytes = minLength;
// move string
size_t preBytes = minLength - len;
for(int a=len; a>=0; --a)
pData->pMemory[a + preBytes] = pData->pMemory[a];
// pre-pad the string
size_t padLen = MFString_Length(pPadding);
for(size_t a=0, b=0; a<preBytes; ++a, ++b)
{
if(b >= padLen)
b = 0;
pData->pMemory[a] = pPadding[b];
}
return *this;
}
MFString& MFString::PadRight(int minLength, const char *pPadding, bool bAlignPadding)
{
// check if the string is already long enough
int len = NumBytes();
if(len >= minLength)
return *this;
// reserve enough memory
Reserve(minLength + 1);
pData->bytes = minLength;
pData->pMemory[minLength] = 0;
// pad the string
size_t padLen = MFString_Length(pPadding);
size_t b = bAlignPadding ? len%padLen : 0;
for(int a=len; a<minLength; ++a, ++b)
{
if(b >= padLen)
b = 0;
pData->pMemory[a] = pPadding[b];
}
return *this;
}
MFString MFString::SubStr(int offset, int count) const
{
if(!pData)
return *this;
// limit within the strings range
int maxChars = (int)pData->bytes - offset;
if(count < 0 || count > maxChars)
count = maxChars;
// bail if we don't need to do anything
if(count == (int)pData->bytes)
return *this;
// allocate a new string
MFString t;
t.Reserve(count + 1);
t.pData->bytes = count;
// copy sub string
MFString_CopyN(t.pData->pMemory, pData->pMemory + offset, count);
t.pData->pMemory[count] = 0;
return t;
}
MFString& MFString::Truncate(int length)
{
if(pData && (size_t)length < pData->bytes)
{
Detach();
pData->bytes = length;
pData->pMemory[length] = 0;
}
return *this;
}
MFString MFString::GetExtension() const
{
int dot = FindCharReverse('.');
if(dot > FindCharReverse('/') && dot > FindCharReverse('\\'))
return SubStr(dot);
return MFString();
}
MFString& MFString::TruncateExtension()
{
int dot = FindCharReverse('.');
if(dot >= 0)
{
pData->pMemory[dot] = 0;
pData->bytes = dot;
}
return *this;
}
MFString& MFString::ClearRange(int offset, int length)
{
if(!pData)
return *this;
// limit within the strings range
int maxChars = (int)pData->bytes - offset;
if(length > maxChars)
length = maxChars;
// bail if we don't need to do anything
if(length <= 0)
return *this;
// clear the range
Detach();
int postBytes = (int)pData->bytes - (offset + length);
pData->bytes -= length;
char *pReplace = pData->pMemory + offset;
const char *pTail = pReplace + length;
for(int a=0; a <= postBytes; ++a)
pReplace[a] = pTail[a];
return *this;
}
MFString& MFString::Replace(int offset, int range, MFString string)
{
if(!pData)
{
pData = string.pData;
if(pData)
++pData->refCount;
return *this;
}
// limit within the strings range
offset = MFMin(offset, (int)pData->bytes);
int maxChars = (int)pData->bytes - offset;
if(range > maxChars)
range = maxChars;
// bail if we don't need to do anything
int strLen = string.NumBytes();
if(range == 0 && strLen == 0)
return *this;
int reposition = strLen - range;
int newSize = (int)pData->bytes + reposition;
// reserve memory for the new string
Reserve(newSize);
// move tail into place
if(reposition)
{
int tailOffset = offset + range;
char *pSrc = pData->pMemory + tailOffset;
char *pDest = pSrc + reposition;
if(pDest < pSrc)
{
while(*pSrc)
*pDest++ = *pSrc++;
*pDest = 0;
}
else
{
int len = (int)pData->bytes - tailOffset;
while(len >= 0)
{
pDest[len] = pSrc[len];
--len;
}
}
}
// insert string
if(strLen)
MFString_CopyN(pData->pMemory + offset, string.pData->pMemory, strLen);
pData->bytes = newSize;
return *this;
}
int MFString::FindChar(int c, int startOffset) const
{
if(pData)
{
const char *pStart = pData->pMemory + startOffset;
const char *pT = pStart;
while(*pT)
{
// decode utf8
int t;
int bytes = MFString_DecodeUTF8(pT, &t);
// check if the characters match
if(t == c)
return (int)(pT - pStart);
// progress to next char
pT += bytes;
}
}
return -1;
}
int MFString::FindCharReverse(int c) const
{
if(pData)
{
const char *pT = pData->pMemory + pData->bytes;
while(pT >= pData->pMemory)
{
// decode utf8
int t;
MFString_DecodeUTF8(pT, &t);
// check if the characters match
if(t == c)
return (int)(pT - pData->pMemory);
// progress to prev char
pT = MFString_PrevChar(pT);
}
}
return -1;
}
MFString& MFString::Join(const MFArray<MFString> &strings, const char *pSeparator, const char *pTokenPrefix, const char *pTokenSuffix, const char *pBefore, const char *pAfter)
{
MFString result;
size_t numTokens = strings.size();
// TODO: we should resize the string in advance...
if(pBefore)
result += pBefore;
// TODO: alternate loops with different availability of parameters?
for(size_t i=0; i<numTokens; ++i)
{
if(pSeparator && i>0)
result += pSeparator;
if(pTokenPrefix)
result += pTokenPrefix;
result += strings[i];
if(pTokenSuffix)
result += pTokenSuffix;
}
if(pAfter)
result += pAfter;
*this = result;
return *this;
}
MFArray<MFString>& MFString::Split(MFArray<MFString> &output, const char *pDelimiters)
{
output.clear();
if(!pData)
return output;
const char *pText = pData->pMemory;
while(*pText)
{
const char *pEnd = MFSeekDelimiter(pText, pDelimiters);
output.push(MFString(pText, (size_t)(pEnd - pText)));
pText = MFSkipDelimiters(pEnd, pDelimiters);
}
return output;
}
int MFString::Enumerate(const MFArray<MFString> keys, bool bCaseSensitive)
{
if(IsEmpty())
return -1;
for(size_t i=0; i<keys.size(); ++i)
{
if(bCaseSensitive ? Equals(keys[i]) : EqualsInsensitive(keys[i]))
return (int)i;
}
return -1;
}
MFString MFString::StripToken(const char *pDelimiters)
{
if(!pData)
return NULL;
// find token
const char *pText = CStr();
const char *pToken = MFSkipDelimiters(pText, pDelimiters);
const char *pEnd = MFSeekDelimiter(pToken, pDelimiters);
const char *pTrim = MFSkipDelimiters(pEnd, pDelimiters);
// capture the token
MFString token(pToken, (size_t)(pEnd - pToken));
// strip from source string
size_t offset = pTrim - pText;
if(offset > 0)
{
Detach();
for(size_t i = offset; i <= pData->bytes; ++i)
pData->pMemory[i - offset] = pData->pMemory[i];
pData->bytes -= offset;
}
return token;
}
static MFString GetNextBit(const char *&pFormat)
{
MFString format;
while(*pFormat)
{
if(*pFormat == '%')
{
if(pFormat[1] == '%')
++pFormat;
else
break;
}
else if(*pFormat == '\\')
{
if(pFormat[1] == 't')
{
format += '\t';
pFormat += 2;
continue;
}
else if(pFormat[1] == 'n')
{
format += '\n';
pFormat += 2;
continue;
}
else if(pFormat[1] == 'r')
{
format += '\r';
pFormat += 2;
continue;
}
else
++pFormat;
}
format += *pFormat++;
}
return format;
}
static int Match(const char *pString, const char *pFormat)
{
if(!pFormat)
return 0;
const char *pStart = pString;
while(*pFormat)
{
if(*pFormat == '?')
{
if(*pString == 0)
return -1;
}
/*
elseif(*pFormat == '*')
{
pString = MFString_Chr(pString, pFormat[1]);
++pFormat;
continue;
}
*/
else if(*pString != *pFormat)
return -1;
++pString;
++pFormat;
}
return (int)(pString - pStart);
}
int MFString::Parse(const char *pFormat, ...)
{
if(!pData || !pFormat)
return 0;
va_list arglist;
va_start(arglist, pFormat);
const char *pS = pData->pMemory;
int numArgs = 0;
MFString format = GetNextBit(pFormat);
int numChars = Match(pS, format.CStr());
while(*pFormat && numChars >= 0)
{
pS += numChars;
++pFormat;
int length = -1;
// gather format options...
while(*pFormat)
{
int c = MFToLower(*pFormat++);
if(c == 's')
{
MFString *pStr = va_arg(arglist, MFString*);
++numArgs;
format = GetNextBit(pFormat);
if(length >= 0)
{
MFString s(pS, (size_t)length);
*pStr = s;
numChars = Match(pS, format.CStr());
}
else if(format.NumBytes() == 0)
{
*pStr = pS;
}
else
{
const char *pEnd = pS;
while(*pEnd && (numChars = Match(pEnd, format.CStr())) < 0)
++pEnd;
MFString s(pS, (size_t)(pEnd - pS));
*pStr = s;
}
pS += pStr->NumBytes();
break;
}
else if(c == 'd' || c == 'i')
{
int *pInt = va_arg(arglist, int*);
++numArgs;
bool bNeg = *pS == '-';
if(*pS == '-' || *pS == '+')
++pS;
*pInt = 0;
while(MFIsNumeric(*pS) && ((uint32&)length)-- > 0)
*pInt = *pInt*10 + *pS++ - '0';
if(bNeg)
*pInt = -*pInt;
format = GetNextBit(pFormat);
numChars = Match(pS, format.CStr());
break;
}
else if(c == 'x')
{
int *pInt = va_arg(arglist, int*);
++numArgs;
*pInt = 0;
while(MFIsHex(*pS) && ((uint32&)length)-- > 0)
{
int digit = *pS++;
*pInt = (*pInt << 4) + (MFIsNumeric(digit) ? digit - '0' : MFToLower(digit) - 'a' + 10);
}
format = GetNextBit(pFormat);
numChars = Match(pS, format.CStr());
break;
}
else if(c == 'f')
{
float *pFloat = va_arg(arglist, float*);
++numArgs;
*pFloat = MFString_AsciiToFloat(pS, &pS);
format = GetNextBit(pFormat);
numChars = Match(pS, format.CStr());
break;
}
else if(MFIsNumeric(c))
{
// read numeric length
length = 0;
while(true)
{
length = length*10 + c - '0';
c = *pFormat;
if(!MFIsNumeric(c))
break;
++pFormat;
}
}
else if(c == '*')
{
// read length from varargs
length = va_arg(arglist, int);
++numArgs;
}
}
}
va_end(arglist);
return numArgs;
}
| 20.372369
| 344
| 0.611762
|
TurkeyMan
|
3d1b5edde4b64236474afa8d96c498cece3ce679
| 715
|
cc
|
C++
|
benchmarks/0000.10m_size_t/raw/charconv_vs_ospan.cc
|
EwoutH/fast_io
|
1393ef01b82dffa87f3008ec0898431865870a1f
|
[
"MIT"
] | 2
|
2020-07-20T06:07:20.000Z
|
2020-10-21T08:53:49.000Z
|
benchmarks/0000.10m_size_t/raw/charconv_vs_ospan.cc
|
EwoutH/fast_io
|
1393ef01b82dffa87f3008ec0898431865870a1f
|
[
"MIT"
] | null | null | null |
benchmarks/0000.10m_size_t/raw/charconv_vs_ospan.cc
|
EwoutH/fast_io
|
1393ef01b82dffa87f3008ec0898431865870a1f
|
[
"MIT"
] | null | null | null |
#include"../timer.h"
#include"../../include/fast_io.h"
#include"../../include/fast_io_device.h"
#include<charconv>
int main()
{
constexpr std::size_t N(10000000);
std::size_t osp_total{};
{
fast_io::timer t("ospan");
std::array<char,50> array;
for(std::size_t i{};i!=100000000;++i)
{
fast_io::ospan osp(array);
println(osp,i);
osp_total+=osize(osp);
}
}
std::size_t charconv_total{};
{
fast_io::timer t("array");
std::array<char,50> array;
for(std::size_t i{};i!=100000000;++i)
{
auto [p,ec]=std::to_chars(array.data(),array.data()+array.size(),i);
*p=u8'\n';
charconv_total+=++p-array.data();
}
}
println("charconv_total:",charconv_total," osp_total:",osp_total);
}
| 21.029412
| 71
| 0.630769
|
EwoutH
|
3d1e09b984b148667bf8be54c46da1f5b62268c3
| 1,164
|
cpp
|
C++
|
cpp/other-concepts/attending-workshops.cpp
|
feliposz/hackerrank-solutions
|
fb1d63ca12a0d289362c9b3fb4cb0b79ef73f72f
|
[
"MIT"
] | null | null | null |
cpp/other-concepts/attending-workshops.cpp
|
feliposz/hackerrank-solutions
|
fb1d63ca12a0d289362c9b3fb4cb0b79ef73f72f
|
[
"MIT"
] | null | null | null |
cpp/other-concepts/attending-workshops.cpp
|
feliposz/hackerrank-solutions
|
fb1d63ca12a0d289362c9b3fb4cb0b79ef73f72f
|
[
"MIT"
] | null | null | null |
//Define the structs Workshops and Available_Workshops.
//Implement the functions initialize and CalculateMaxWorkshops
struct Workshop {
int start_time;
int duration;
int end_time;
};
struct Available_Workshops {
int n;
Workshop *ws;
};
Available_Workshops* initialize (int start_time[], int duration[], int n)
{
Available_Workshops *result = new Available_Workshops();
result->n = n;
result->ws = new Workshop[n];
for (int i = 0; i < n; i++) {
result->ws[i].start_time = start_time[i];
result->ws[i].duration = duration[i];
result->ws[i].end_time = start_time[i] + duration[i];
}
return result;
}
int cmp(const void *a, const void *b) {
Workshop *pa = (Workshop *)a;
Workshop *pb = (Workshop *)b;
return pa->end_time - pb->end_time;
}
int CalculateMaxWorkshops(Available_Workshops* ptr)
{
qsort(ptr->ws, ptr->n, sizeof(Workshop), cmp);
int count = 0;
int end_time = 0;
for (int i = 0; i < ptr->n; i++) {
if (ptr->ws[i].start_time >= end_time) {
end_time = ptr->ws[i].end_time;
count++;
}
}
return count;
}
| 22.823529
| 73
| 0.604811
|
feliposz
|
3d1e3180cadbf87e7b353f14b832e1d99e1c2308
| 3,005
|
cpp
|
C++
|
MT Game Engine/Source/Interaction/Input.cpp
|
MatthewATaylor/MT-Game-Engine
|
bad800163a2ae5476fbe7d08a8c245e6a563c4fb
|
[
"MIT"
] | 3
|
2019-10-08T20:58:43.000Z
|
2020-10-17T15:59:01.000Z
|
MT Game Engine/Source/Interaction/Input.cpp
|
MatthewATaylor/MT-Game-Engine
|
bad800163a2ae5476fbe7d08a8c245e6a563c4fb
|
[
"MIT"
] | null | null | null |
MT Game Engine/Source/Interaction/Input.cpp
|
MatthewATaylor/MT-Game-Engine
|
bad800163a2ae5476fbe7d08a8c245e6a563c4fb
|
[
"MIT"
] | null | null | null |
#include "Interaction/Input.h"
namespace mtge {
const int Input::GLFW_KEY_LIST[Input::NUM_KEYS] = {
GLFW_KEY_UNKNOWN,
GLFW_KEY_CAPS_LOCK, GLFW_KEY_NUM_LOCK, GLFW_KEY_SCROLL_LOCK,
GLFW_KEY_PAGE_UP, GLFW_KEY_PAGE_DOWN, GLFW_KEY_HOME, GLFW_KEY_END, GLFW_KEY_PRINT_SCREEN, GLFW_KEY_PAUSE,
GLFW_KEY_LEFT_CONTROL, GLFW_KEY_RIGHT_CONTROL, GLFW_KEY_LEFT_ALT, GLFW_KEY_RIGHT_ALT,
GLFW_KEY_SPACE, GLFW_KEY_TAB, GLFW_KEY_ENTER, GLFW_KEY_BACKSPACE, GLFW_KEY_DELETE, GLFW_KEY_INSERT, GLFW_KEY_ESCAPE,
GLFW_KEY_UP, GLFW_KEY_DOWN, GLFW_KEY_LEFT, GLFW_KEY_RIGHT,
GLFW_KEY_A, GLFW_KEY_B, GLFW_KEY_C, GLFW_KEY_D, GLFW_KEY_E, GLFW_KEY_F, GLFW_KEY_G, GLFW_KEY_H, GLFW_KEY_I, GLFW_KEY_J, GLFW_KEY_K, GLFW_KEY_L, GLFW_KEY_M,
GLFW_KEY_N, GLFW_KEY_O, GLFW_KEY_P, GLFW_KEY_Q, GLFW_KEY_R, GLFW_KEY_S, GLFW_KEY_T, GLFW_KEY_U, GLFW_KEY_V, GLFW_KEY_W, GLFW_KEY_X, GLFW_KEY_Y, GLFW_KEY_Z,
GLFW_KEY_0, GLFW_KEY_1, GLFW_KEY_2, GLFW_KEY_3, GLFW_KEY_4, GLFW_KEY_5, GLFW_KEY_6, GLFW_KEY_7, GLFW_KEY_8, GLFW_KEY_9,
GLFW_KEY_COMMA, GLFW_KEY_PERIOD, GLFW_KEY_SLASH, GLFW_KEY_BACKSLASH, GLFW_KEY_SEMICOLON, GLFW_KEY_APOSTROPHE, GLFW_KEY_LEFT_BRACKET, GLFW_KEY_RIGHT_BRACKET, GLFW_KEY_MINUS, GLFW_KEY_EQUAL, GLFW_KEY_GRAVE_ACCENT,
GLFW_KEY_KP_0, GLFW_KEY_KP_1, GLFW_KEY_KP_2, GLFW_KEY_KP_3, GLFW_KEY_KP_4, GLFW_KEY_KP_5, GLFW_KEY_KP_6, GLFW_KEY_KP_7, GLFW_KEY_KP_8, GLFW_KEY_KP_9,
GLFW_KEY_KP_ADD, GLFW_KEY_KP_SUBTRACT, GLFW_KEY_KP_MULTIPLY, GLFW_KEY_KP_DIVIDE, GLFW_KEY_KP_DECIMAL,
GLFW_KEY_F1, GLFW_KEY_F2, GLFW_KEY_F3, GLFW_KEY_F4, GLFW_KEY_F5, GLFW_KEY_F6, GLFW_KEY_F7, GLFW_KEY_F8, GLFW_KEY_F9, GLFW_KEY_F10, GLFW_KEY_F11, GLFW_KEY_F12, GLFW_KEY_F13,
GLFW_KEY_F14, GLFW_KEY_F15, GLFW_KEY_F16, GLFW_KEY_F17, GLFW_KEY_F18, GLFW_KEY_F19, GLFW_KEY_F20, GLFW_KEY_F21, GLFW_KEY_F22, GLFW_KEY_F23, GLFW_KEY_F24, GLFW_KEY_F25
};
CursorType Input::cursorType = CursorType::UNDEFINED;
double Input::mouseX = 0.0;
double Input::mouseY = 0.0;
//Private
void Input::mouseCursorCallback(GLFWwindow *window, double xPos, double yPos) {
mouseX = xPos;
mouseY = yPos;
}
//Public
void Input::initCursorInput(Window *window) {
glfwSetCursorPosCallback(window->getPtr_GLFW(), mouseCursorCallback);
}
bool Input::keyPressed(Window *window, Key key) {
return (glfwGetKey(window->getPtr_GLFW(), GLFW_KEY_LIST[(int)key]) == GLFW_PRESS);
}
void Input::pollInput() {
glfwPollEvents();
}
void Input::setCursorType(Window *window, CursorType cursorType) {
int cursorType_GLFW = 0;
switch (cursorType) {
case CursorType::NORMAL:
cursorType_GLFW = GLFW_CURSOR_NORMAL;
break;
case CursorType::HIDDEN:
cursorType_GLFW = GLFW_CURSOR_HIDDEN;
break;
case CursorType::DISABLED:
cursorType_GLFW = GLFW_CURSOR_DISABLED;
}
glfwSetInputMode(window->getPtr_GLFW(), GLFW_CURSOR, cursorType_GLFW);
Input::cursorType = cursorType;
}
CursorType Input::getCursorType() {
return cursorType;
}
double Input::getMouseX() {
return mouseX;
}
double Input::getMouseY() {
return mouseY;
}
}
| 46.230769
| 213
| 0.797338
|
MatthewATaylor
|
3d1f3dd38753110136a4eb68769d5107bb53d903
| 8,847
|
hpp
|
C++
|
src/AnimationData.hpp
|
AnimatedLEDStrip/client-cpp
|
b16ec6b638659d4af0c31c3767590dcfee0290b4
|
[
"MIT"
] | null | null | null |
src/AnimationData.hpp
|
AnimatedLEDStrip/client-cpp
|
b16ec6b638659d4af0c31c3767590dcfee0290b4
|
[
"MIT"
] | null | null | null |
src/AnimationData.hpp
|
AnimatedLEDStrip/client-cpp
|
b16ec6b638659d4af0c31c3767590dcfee0290b4
|
[
"MIT"
] | null | null | null |
/*
* Copyright (c) 2019-2020 AnimatedLEDStrip
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef ANIMATEDLEDSTRIP_ANIMATIONDATA_HPP
#define ANIMATEDLEDSTRIP_ANIMATIONDATA_HPP
#include <iostream>
#include <string>
#include <nlohmann/json.hpp>
#include "ColorContainer.hpp"
#define MAX_LEN 10000
enum Continuous {
CONTINUOUS,
NONCONTINUOUS,
DEFAULT
};
enum Direction {
FORWARD,
BACKWARD
};
class AnimationData {
public:
std::string animation = "Color";
std::vector<ColorContainer> colors;
int center = -1;
Continuous continuous = DEFAULT;
long delay = -1;
double delay_mod = 1.0;
Direction direction = FORWARD;
int distance = -1;
std::string id = "";
std::string section = "";
int spacing = -1;
AnimationData & setAnimation(const std::string & a) {
animation.assign(a);
return *this;
}
AnimationData & setAnimation(const char * a) {
animation.assign(a);
return *this;
}
AnimationData & addColor(ColorContainer & c) {
colors.push_back(c);
return *this;
}
AnimationData & setCenter(int c) {
center = c;
return *this;
}
AnimationData & setContinuous(enum Continuous c) {
continuous = c;
return *this;
}
AnimationData & setDelay(long d) {
delay = d;
return *this;
}
AnimationData & setDelayMod(double d) {
delay_mod = d;
return *this;
}
AnimationData & setDirection(enum Direction d) {
direction = d;
return *this;
}
AnimationData & setDistance(int d) {
distance = d;
return *this;
}
AnimationData & setId(const std::string & i) {
id.assign(i);
return *this;
}
AnimationData & setId(const char * i) {
id.assign(i);
return *this;
}
AnimationData & setSection(const std::string & s) {
section.assign(s);
return *this;
}
AnimationData & setSection(const char * s) {
section.assign(s);
return *this;
}
AnimationData & setSpacing(int s) {
spacing = s;
return *this;
}
static std::string continuousToString(enum Continuous c) {
switch (c) {
case CONTINUOUS:
return "true";
case NONCONTINUOUS:
return "false";
case DEFAULT:
return "null";
}
}
static enum Direction directionFromString(const std::string & d) {
if (std::strcmp(d.c_str(), "BACKWARD") == 0) return BACKWARD;
else if (std::strcmp(d.c_str(), "FORWARD") == 0) return FORWARD;
else {
std::cerr << "Bad direction string " << d << std::endl;
return FORWARD;
}
}
static std::string directionToString(enum Direction d) {
switch (d) {
case FORWARD:
return "FORWARD";
case BACKWARD:
return "BACKWARD";
}
}
AnimationData() = default;
explicit AnimationData(nlohmann::json data) {
if (data["animation"].is_string())
setAnimation(data["animation"].get<std::string>());
else if (!data["animation"].is_null())
std::cerr << "Bad type for animation" << data["animation"].type_name() << std::endl;
if (data["colors"].is_array())
for (auto & c : data["colors"].items()) {
if (c.value().is_object()) {
ColorContainer cc = ColorContainer(c.value());
addColor(cc);
}
}
else if (!data["colors"].is_null())
std::cerr << "Bad type for colors" << data["colors"].type_name() << std::endl;
if (data["center"].is_number_integer())
setCenter(data["center"].get<int>());
else if (!data["center"].is_null())
std::cerr << "Bad type for center" << data["center"].type_name() << std::endl;
if (data["continuous"].is_null())
setContinuous(DEFAULT);
else if (data["continuous"].is_boolean() && data["continuous"].get<bool>())
setContinuous(CONTINUOUS);
else if (data["continuous"].is_boolean() && !data["continuous"].get<bool>())
setContinuous(NONCONTINUOUS);
else
std::cerr << "Bad type for continuous" << data["continuous"].type_name() << std::endl;
if (data["delay"].is_number_integer())
setDelay(data["delay"].get<int>());
else if (!data["delay"].is_null())
std::cerr << "Bad type for delay" << data["delay"].type_name() << std::endl;
if (data["delayMod"].is_number_float())
setDelayMod(data["delayMod"].get<double>());
else if (!data["delayMod"].is_null())
std::cerr << "Bad type for delayMod" << data["delayMod"].type_name() << std::endl;
if (data["direction"].is_string())
setDirection(directionFromString(data["direction"].get<std::string>()));
else if (!data["direction"].is_null())
std::cerr << "Bad type for direction" << data["direction"].type_name() << std::endl;
if (data["distance"].is_number_integer())
setDistance(data["distance"].get<int>());
else if (!data["distance"].is_null())
std::cerr << "Bad type for distance" << data["distance"].type_name() << std::endl;
if (data["id"].is_string())
setId(data["id"].get<std::string>());
else if (!data["id"].is_null())
std::cerr << "Bad type for id" << data["id"].type_name() << std::endl;
if (data["section"].is_string())
setSection(data["section"].get<std::string>());
else if (!data["section"].is_null())
std::cerr << "Bad type for section" << data["section"].type_name() << std::endl;
if (data["spacing"].is_number_integer())
setSpacing(data["spacing"].get<int>());
else if (!data["spacing"].is_null())
std::cerr << "Bad type for spacing" << data["spacing"].type_name() << std::endl;
}
std::string colorsString() {
std::string cols = "[";
for (auto c : colors) {
cols.append(c.colorsString(true));
cols.append(",");
}
if (!colors.empty())
cols.pop_back();
cols.append("]");
return cols;
}
int json(char ** buff) const {
std::string data = "DATA:{";
data.append(R"("animation":")");
data.append(animation);
data.append(R"(","colors":[)");
char * cBuff = new char[MAX_LEN];
for (ColorContainer c : colors) {
cBuff[0] = 0;
c.json(&cBuff);
data.append(cBuff);
data.append(",");
}
if (!colors.empty())
data.pop_back();
data.append(R"(],"center":)");
data.append(std::to_string(center));
data.append(R"(,"continuous":)");
data.append(continuousToString(continuous));
data.append(R"(,"delay":)");
data.append(std::to_string(delay));
data.append(R"(,"delayMod":)");
data.append(std::to_string(delay_mod));
data.append(R"(,"direction":")");
data.append(directionToString(direction));
data.append(R"(","distance":)");
data.append(std::to_string(distance));
data.append(R"(,"id":")");
data.append(id);
data.append(R"(","section":")");
data.append(section);
data.append(R"(","spacing":)");
data.append(std::to_string(spacing));
data.append("}");
std::strcpy(*buff, data.c_str());
return data.size();
}
};
#endif // ANIMATEDLEDSTRIP_ANIMATIONDATA_HPP
| 30.091837
| 98
| 0.565163
|
AnimatedLEDStrip
|
3d27dda5a7ee08d9aaaca11d0164c87d9e2c07a7
| 451
|
cpp
|
C++
|
sdk/poeng/stdafx.cpp
|
hadrien-psydk/pngoptimizer
|
d92946e63a57a4562af0feaa9e4cfd8628373777
|
[
"Zlib"
] | 90
|
2016-08-23T00:13:04.000Z
|
2022-02-22T09:40:46.000Z
|
sdk/poeng/stdafx.cpp
|
hadrien-psydk/pngoptimizer
|
d92946e63a57a4562af0feaa9e4cfd8628373777
|
[
"Zlib"
] | 25
|
2016-09-01T07:09:03.000Z
|
2022-01-31T16:18:57.000Z
|
sdk/poeng/stdafx.cpp
|
hadrien-psydk/pngoptimizer
|
d92946e63a57a4562af0feaa9e4cfd8628373777
|
[
"Zlib"
] | 17
|
2017-05-03T17:49:25.000Z
|
2021-12-28T06:47:56.000Z
|
/////////////////////////////////////////////////////////////////////////////////////
// This file is part of the POEngine library, part of the PngOptimizer application
// Copyright (C) Hadrien Nilsson - psydk.org
// This library is distributed under the terms of the GNU LESSER GENERAL PUBLIC LICENSE
// See License.txt for the full license.
/////////////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
| 45.1
| 87
| 0.472284
|
hadrien-psydk
|
3d2909b6846d368db5ff17528e646e1ca115d9ad
| 2,994
|
cpp
|
C++
|
Siv3D/src/Siv3D/Bezier3/SivBezier3.cpp
|
yumetodo/OpenSiv3D
|
ea191438ecbc64185f5df3d9f79dffc6757e4192
|
[
"MIT"
] | 7
|
2020-04-26T11:06:02.000Z
|
2021-09-05T16:42:31.000Z
|
Siv3D/src/Siv3D/Bezier3/SivBezier3.cpp
|
yumetodo/OpenSiv3D
|
ea191438ecbc64185f5df3d9f79dffc6757e4192
|
[
"MIT"
] | 10
|
2020-04-26T13:25:36.000Z
|
2022-03-01T12:34:44.000Z
|
Siv3D/src/Siv3D/Bezier3/SivBezier3.cpp
|
yumetodo/OpenSiv3D
|
ea191438ecbc64185f5df3d9f79dffc6757e4192
|
[
"MIT"
] | 2
|
2020-05-11T08:23:23.000Z
|
2020-08-08T12:33:30.000Z
|
//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2019 Ryo Suzuki
// Copyright (c) 2016-2019 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# include <Siv3D/Bezier3.hpp>
namespace s3d
{
Vec2 Bezier3::getPos(const double t) const noexcept
{
return (1 - t) * (1 - t) * (1 - t) * p0 + 3 * (1 - t) * (1 - t) * t * p1 + 3 * (1 - t) * t * t * p2 + t * t * t * p3;
}
Vec2 Bezier3::getTangent(const double t) const noexcept
{
return (-3 * p0 * (1 - t) * (1 - t) +
p1 * (3 * (1 - t) * (1 - t) - 6 * (1 - t) * t) +
p2 * (6 * (1 - t) * t - 3 * t * t) + 3 * p3 * t * t).normalized();
}
LineString Bezier3::getLineString(const uint32 quality) const
{
return getLineString(0.0, 1.0, quality);
}
LineString Bezier3::getLineString(const double start, const double end, const uint32 quality) const
{
const double length = end - start;
const double d = length / (quality + 1);
LineString pts(quality + 2);
Vec2* pDst = pts.data();
for (uint32 i = 0; i <= (quality + 1); ++i)
{
*pDst++ = getPos(start + d * i);
}
return pts;
}
const Bezier3& Bezier3::paint(Image& dst, const Color& color) const
{
return paint(dst, 1, color);
}
const Bezier3& Bezier3::paint(Image& dst, const int32 thickness, const Color& color) const
{
getLineString().paint(dst, thickness, color);
return *this;
}
const Bezier3& Bezier3::overwrite(Image& dst, const Color& color, const bool antialiased) const
{
return overwrite(dst, 1, color, antialiased);
}
const Bezier3& Bezier3::overwrite(Image& dst, const int32 thickness, const Color& color, const bool antialiased) const
{
getLineString().overwrite(dst, thickness, color, antialiased);
return *this;
}
const Bezier3& Bezier3::draw(const ColorF& color, const uint32 quality) const
{
return draw(1.0, color, quality);
}
const Bezier3& Bezier3::draw(const double thickness, const ColorF& color, const uint32 quality) const
{
getLineString(quality).draw(thickness, color);
return *this;
}
void Formatter(FormatData& formatData, const Bezier3& value)
{
formatData.string.push_back(U'(');
Formatter(formatData, value.p0);
formatData.string.append(U", "_sv);
Formatter(formatData, value.p1);
formatData.string.append(U", "_sv);
Formatter(formatData, value.p2);
formatData.string.append(U", "_sv);
Formatter(formatData, value.p3);
formatData.string.push_back(U')');
}
Bezier3Path::Bezier3Path(const Bezier3& bezier) noexcept
: m_v0(-3 * bezier.p0 + 9 * bezier.p1 - 9 * bezier.p2 + 3 * bezier.p3)
, m_v1(6 * bezier.p0 - 12 * bezier.p1 + 6 * bezier.p2)
, m_v2(-3 * bezier.p0 + 3 * bezier.p1)
{
}
double Bezier3Path::advance(const double distance, const int32 quality) noexcept
{
for (int i = 0; i < quality; ++i)
{
m_t = m_t + (distance / quality) / (m_t * m_t * m_v0 + m_t * m_v1 + m_v2).length();
}
return m_t;
}
}
| 25.810345
| 119
| 0.620908
|
yumetodo
|
3d2b6dc38f2a02d4f3257892844ba2bb2e70543b
| 947
|
cpp
|
C++
|
robowflex_library/scripts/plugin_io.cpp
|
servetb/robowflex
|
4444fd75e0c6d32a3b9b8e8da6ee69869e56fd3e
|
[
"BSD-3-Clause"
] | 58
|
2018-08-17T14:26:02.000Z
|
2022-03-28T05:42:03.000Z
|
robowflex_library/scripts/plugin_io.cpp
|
servetb/robowflex
|
4444fd75e0c6d32a3b9b8e8da6ee69869e56fd3e
|
[
"BSD-3-Clause"
] | 52
|
2018-08-23T01:33:04.000Z
|
2022-03-28T15:54:13.000Z
|
robowflex_library/scripts/plugin_io.cpp
|
servetb/robowflex
|
4444fd75e0c6d32a3b9b8e8da6ee69869e56fd3e
|
[
"BSD-3-Clause"
] | 14
|
2021-04-05T23:49:55.000Z
|
2022-03-21T00:18:16.000Z
|
/* Author: Zachary Kingston */
#include <moveit/planning_request_adapter/planning_request_adapter.h>
#include <robowflex_library/io/plugin.h>
#include <robowflex_library/util.h>
using namespace robowflex;
/* \file plugin_io.cpp
* Demonstrates how to use the plugin loader helper class to load some MoveIt
* plugins.
*/
int main(int argc, char **argv)
{
ROS ros(argc, argv);
auto plugin1 = IO::PluginManager::load<planning_request_adapter::PlanningRequestAdapter>( //
"moveit_core", "default_planner_request_adapters/AddTimeParameterization");
auto plugin2 = IO::PluginManager::load<planning_request_adapter::PlanningRequestAdapter>( //
"moveit_core", "default_planner_request_adapters/FixStartStateBounds");
auto plugin3 = IO::PluginManager::load<planning_request_adapter::PlanningRequestAdapter>( //
"moveit_core", "default_planner_request_adapters/FixStartStateCollision");
return 0;
}
| 31.566667
| 97
| 0.757128
|
servetb
|
3d2cdd91f776ec8572b6092cb48e06b0890bf686
| 23
|
cpp
|
C++
|
src/Core_ally.cpp
|
Riateche/ridual
|
d91ca5326438e15fccd38a4e4263aeb291d64539
|
[
"MIT"
] | 3
|
2015-07-08T07:41:36.000Z
|
2017-11-08T15:01:26.000Z
|
src/Core_ally.cpp
|
Riateche/ridual
|
d91ca5326438e15fccd38a4e4263aeb291d64539
|
[
"MIT"
] | null | null | null |
src/Core_ally.cpp
|
Riateche/ridual
|
d91ca5326438e15fccd38a4e4263aeb291d64539
|
[
"MIT"
] | null | null | null |
#include "Core_ally.h"
| 11.5
| 22
| 0.73913
|
Riateche
|
3d2de11dd2467a80e4300f297a62b03f5d8620cb
| 49
|
hpp
|
C++
|
addons/main/script_version.hpp
|
YonVclaw/6sfdgdemo
|
f09b4ed8569cd0fcbca4c634aa79289f1ca84014
|
[
"MIT"
] | null | null | null |
addons/main/script_version.hpp
|
YonVclaw/6sfdgdemo
|
f09b4ed8569cd0fcbca4c634aa79289f1ca84014
|
[
"MIT"
] | null | null | null |
addons/main/script_version.hpp
|
YonVclaw/6sfdgdemo
|
f09b4ed8569cd0fcbca4c634aa79289f1ca84014
|
[
"MIT"
] | null | null | null |
#define MAJOR 1
#define MINOR 14
#define PATCH 2
| 12.25
| 16
| 0.755102
|
YonVclaw
|
3d323d783baec2c138768d7e519d4e7556b8201c
| 5,302
|
cc
|
C++
|
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_aguila/ag_AguilaGuiTest.cc
|
quanpands/wflow
|
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
|
[
"MIT"
] | null | null | null |
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_aguila/ag_AguilaGuiTest.cc
|
quanpands/wflow
|
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
|
[
"MIT"
] | null | null | null |
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_aguila/ag_AguilaGuiTest.cc
|
quanpands/wflow
|
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
|
[
"MIT"
] | null | null | null |
#include "ag_AguilaGuiTest.h"
// External headers.
#include <boost/filesystem.hpp>
// Project headers.
#include "dal_Exception.h"
// Module headers.
#include "ag_Aguila.h"
#include "ag_Viewer.h"
/*!
\file
This file contains the implementation of the AguilaGuiTest class.
*/
namespace ag {
//------------------------------------------------------------------------------
// DEFINITION OF STATIC AGUILAGUITEST MEMBERS
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// DEFINITION OF AGUILAGUITEST MEMBERS
//------------------------------------------------------------------------------
//! ctor
AguilaGuiTest::AguilaGuiTest()
:
// Cursor Window
// CursorView
// Data source table
d_nrVisualisationsPerCursorDialog(3),
// Map window
// Map
// Legend view
// Map view
d_nrVisualisationsPerMapWindow(4),
// Plot window
// Plot
// Legend view
// Plot view
d_nrVisualisationsPerTimePlotWindow(4),
d_nrVisualisationsPerAnimationDialog(1)
{
}
void AguilaGuiTest::initTestCase()
{
}
void AguilaGuiTest::cleanupTestCase()
{
}
void AguilaGuiTest::init()
{
}
void AguilaGuiTest::cleanup()
{
// Viewer::resetInstance();
}
void AguilaGuiTest::testNotExisting(
std::string const& name)
{
int argc = 2;
char const* argv[2] = { "aguila", name.c_str() };
QVERIFY(!boost::filesystem::exists(name));
Aguila aguila(argc, const_cast<char**>(argv));
bool rightExceptionCaught;
try {
rightExceptionCaught = false;
aguila.setup();
}
catch(dal::Exception const& exception) {
rightExceptionCaught = true;
QCOMPARE(exception.message(),
std::string("Data source " + name + ":\ncannot be opened"));
}
catch(...) {
}
QVERIFY(rightExceptionCaught);
Viewer const& viewer(aguila.viewer());
QCOMPARE(viewer.nrVisualisations(), static_cast<size_t>(0));
QVERIFY(!boost::filesystem::exists(name));
/// Viewer::resetInstance();
}
void AguilaGuiTest::testNotExisting()
{
testNotExisting("DoesNotExist.map");
testNotExisting("DoesNotExist");
}
void AguilaGuiTest::testRasterMinMaxEqual()
{
int argc = 2;
char const* argv[2] = { "aguila",
"MinMaxEqual.map" };
Aguila aguila(argc, const_cast<char**>(argv));
aguila.setup();
Viewer const& viewer(aguila.viewer());
QCOMPARE(viewer.nrVisualisations(), static_cast<size_t>(
/* d_nrVisualisationsPerCursorDialog + */
d_nrVisualisationsPerMapWindow));
}
void AguilaGuiTest::testDataset1()
{
{
int argc = 2;
char const* argv[2] = { "aguila",
"dataset1/aap/scalar_10" };
Aguila aguila(argc, const_cast<char**>(argv));
aguila.setup();
Viewer const& viewer(aguila.viewer());
QCOMPARE(viewer.nrVisualisations(), size_t(
/* d_nrVisualisationsPerCursorDialog + */
d_nrVisualisationsPerMapWindow));
}
{
int argc = 4;
char const* argv[4] = { "aguila",
"--scenarios", "{dataset1/aap, dataset1/noot, dataset1/mies}",
"scalar_10" };
Aguila aguila(argc, const_cast<char**>(argv));
aguila.setup();
Viewer const& viewer(aguila.viewer());
QCOMPARE(viewer.nrVisualisations(), size_t(
/* d_nrVisualisationsPerCursorDialog + */
3 * d_nrVisualisationsPerMapWindow));
}
{
int argc = 6;
char const* argv[6] = { "aguila",
"--scenarios", "{dataset1/aap, dataset1/noot, dataset1/mies}",
"--timesteps", "[1, 30]",
"scalar" };
Aguila aguila(argc, const_cast<char**>(argv));
aguila.setup();
Viewer const& viewer(aguila.viewer());
QCOMPARE(viewer.nrVisualisations(), size_t(
/* d_nrVisualisationsPerCursorDialog + */
3 * d_nrVisualisationsPerMapWindow // +
/* d_nrVisualisationsPerAnimationDialog */));
}
{
int argc = 8;
char const* argv[8] = { "aguila",
"--multi", "2x2",
"--scenarios", "{dataset1/aap, dataset1/noot, dataset1/mies}",
"--timesteps", "[1, 30]",
"scalar" };
Aguila aguila(argc, const_cast<char**>(argv));
aguila.setup();
Viewer const& viewer(aguila.viewer());
// MultiMap window
// MultiMap
// Legend view
// MultiMap view
// 4 * Map view
QCOMPARE(viewer.nrVisualisations(), size_t(
/* d_nrVisualisationsPerCursorDialog + */ 8 // +
/* d_nrVisualisationsPerAnimationDialog */));
}
}
void AguilaGuiTest::testMultipleViews()
{
// {
// int argc = 7;
// char const* argv[7] = { "aguila",
// "--timesteps", "[1, 250]",
// "--timeGraph", "dem",
// "--mapView", "dem"};
// Aguila aguila(argc, const_cast<char**>(argv));
// aguila.setup();
// Viewer const& viewer(aguila.viewer());
// // MultiMap window
// // MultiMap
// // Legend view
// // MultiMap view
// // 4 * Map view
// QCOMPARE(viewer.nrVisualisations(), size_t(
// d_nrVisualisationsPerCursorDialog +
// d_nrVisualisationsPerAnimationDialog +
// d_nrVisualisationsPerTimePlotWindow +
// d_nrVisualisationsPerMapWindow));
// }
}
} // namespace ag
| 22.277311
| 80
| 0.577707
|
quanpands
|
3d35c3c9a7b42ea5e888bed29e718ccd70f36423
| 7,306
|
hpp
|
C++
|
include/argot/prov/switch_/detail/generate_switch_provision.hpp
|
mattcalabrese/argot
|
97349baaf27659c9dc4d67cf8963b2e871eaedae
|
[
"BSL-1.0"
] | 49
|
2018-05-09T23:17:45.000Z
|
2021-07-21T10:05:19.000Z
|
include/argot/prov/switch_/detail/generate_switch_provision.hpp
|
mattcalabrese/argot
|
97349baaf27659c9dc4d67cf8963b2e871eaedae
|
[
"BSL-1.0"
] | null | null | null |
include/argot/prov/switch_/detail/generate_switch_provision.hpp
|
mattcalabrese/argot
|
97349baaf27659c9dc4d67cf8963b2e871eaedae
|
[
"BSL-1.0"
] | 2
|
2019-08-04T03:51:36.000Z
|
2020-12-28T06:53:29.000Z
|
/*==============================================================================
Copyright (c) 2017, 2018 Matt Calabrese
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 ARGOT_PROV_SWITCH_DETAIL_GENERATE_SWITCH_PROVISION_HPP_
#define ARGOT_PROV_SWITCH_DETAIL_GENERATE_SWITCH_PROVISION_HPP_
#ifndef ARGOT_PREPROCESSING_MODE
#include <argot/concepts/switch_body_default.hpp>
#include <argot/detail/unreachable.hpp>
#include <argot/detail/forward.hpp>
#include <argot/gen/is_modeled.hpp>
#include <argot/prov/switch_/detail/config.hpp>
#include <argot/prov/switch_/detail/switch_impl_fwd.hpp>
#include <argot/prov/switch_/detail/switch_provision_base.hpp>
#include <argot/prov/switch_/detail/switch_provision_fwd.hpp>
#include <argot/switch_traits/argument_list_kinds_of_body_destructive.hpp>
#include <argot/switch_traits/argument_list_kinds_of_body_persistent.hpp>
#include <argot/switch_traits/case_value_for_type_at.hpp>
#include <argot/switch_traits/destructive_provide_case.hpp>
#include <argot/switch_traits/destructive_provide_default.hpp>
#include <argot/switch_traits/num_cases.hpp>
#include <argot/switch_traits/persistent_provide_case.hpp>
#include <argot/switch_traits/persistent_provide_default.hpp>
#include <argot/unreachable_function.hpp>
#include <boost/preprocessor/arithmetic/dec.hpp>
#include <boost/preprocessor/iteration/iterate.hpp>
#include <cstddef>
namespace argot::prov::switch_detail {
#if ARGOT_MAX_PREPROCESSED_SWITCH_CASES_IS_VALID
////////////////////////////////////////////////////////////////////////////////
// Begin generation of switch_provision specializations... //
////////////////////////////////////////////////////////////////////////////////
#define BOOST_PP_ITERATION_PARAMS_1 \
( 3, ( 1, ARGOT_MAX_PREPROCESSED_SWITCH_CASES \
, <argot/prov/switch_/detail/generation/switch_generation.hpp> \
) \
)
#include BOOST_PP_ITERATE()
////////////////////////////////////////////////////////////////////////////////
// End generation of switch_provision specializations. //
////////////////////////////////////////////////////////////////////////////////
// This default definition handles situations where there are more cases than
// can fit in a single, preprocessed switch-statement. An instantation
// represents either the first or an intermediate link in a chain of
// switch-statements whose maximum number of cases is
// ARGOT_MAX_PREPROCESSED_SWITCH_CASES.
template< std::size_t NumRemainingCases, provision_kind Kind >
struct switch_provision
: switch_provision_base< Kind >
{
using base_t = switch_provision_base< Kind >;
template< class T >
using with_qualifiers_t = typename base_t::template with_qualifiers_t< T >;
template< auto V >
using provide_case_t = typename base_t::template provide_case_t< V >;
using provide_default_t = typename base_t::provide_default_t;
template< class Body, class ValueType >
using argument_list_kinds_of_body_t
= typename base_t
::template argument_list_kinds_of_body_t< Body, ValueType >;
/* TODO(mattcalabrese) Constrain*/
template< class ValueType, class... Bodies, class Receiver >
static constexpr decltype( auto ) run
( with_qualifiers_t
< prov::switch_detail::switch_impl< ValueType, Bodies... > > self
, Receiver&& receiver
)
{
using body_t
= typename prov::switch_detail::switch_impl< ValueType, Bodies... >
::body_t;
using qualified_body_t = with_qualifiers_t< body_t >;
std::size_t constexpr index_offset
= switch_traits::num_cases_v< body_t > - NumRemainingCases;
switch( self.value )
{
////////////////////////////////////////////////////////////////////////////////
// Begin generation of cases... //
////////////////////////////////////////////////////////////////////////////////
#define BOOST_PP_ITERATION_PARAMS_1 \
( 3, ( 0, ARGOT_MAX_PREPROCESSED_SWITCH_CASES - 1 \
, <argot/prov/switch_/detail/generation/case_generation.hpp> \
) \
)
#include BOOST_PP_ITERATE()
////////////////////////////////////////////////////////////////////////////////
// End generation of cases. //
////////////////////////////////////////////////////////////////////////////////
default:
return switch_provision
< NumRemainingCases - ARGOT_MAX_PREPROCESSED_SWITCH_CASES, Kind >::run
( static_cast
< with_qualifiers_t
< prov::switch_detail::switch_impl< ValueType, Bodies... > >
>( self )
, static_cast< Receiver&& >( receiver )
);
}
}
};
#endif // ARGOT_MAX_PREPROCESSED_SWITCH_CASES_IS_VALID
} // namespace (argot::prov::switch_detail)
#else // Otherwise, we are generating the preprocessed forms as files...
#define ARGOT_PROV_SWITCH_DETAIL_PREPROCESSING_PROVISION_RANGE ( 1, 2 )
#include <argot/prov/switch_/detail/generate_switch_provision_default_definition.hpp>
#include <argot/prov/switch_/detail/generate_switch_provision_range.hpp>
#if ARGOT_MAX_PREPROCESSED_SWITCH_CASES >= 3
#define ARGOT_PROV_SWITCH_DETAIL_PREPROCESSING_PROVISION_RANGE ( 3, 4 )
#include <argot/prov/switch_/detail/generate_switch_provision_default_definition.hpp>
#include <argot/prov/switch_/detail/generate_switch_provision_range.hpp>
#endif
#if ARGOT_MAX_PREPROCESSED_SWITCH_CASES >= 5
#define ARGOT_PROV_SWITCH_DETAIL_PREPROCESSING_PROVISION_RANGE ( 5, 8 )
#include <argot/prov/switch_/detail/generate_switch_provision_default_definition.hpp>
#include <argot/prov/switch_/detail/generate_switch_provision_range.hpp>
#endif
#if ARGOT_MAX_PREPROCESSED_SWITCH_CASES >= 9
#define ARGOT_PROV_SWITCH_DETAIL_PREPROCESSING_PROVISION_RANGE ( 9, 16 )
#include <argot/prov/switch_/detail/generate_switch_provision_default_definition.hpp>
#include <argot/prov/switch_/detail/generate_switch_provision_range.hpp>
#endif
#if ARGOT_MAX_PREPROCESSED_SWITCH_CASES >= 17
#define ARGOT_PROV_SWITCH_DETAIL_PREPROCESSING_PROVISION_RANGE ( 17, 32 )
#include <argot/prov/switch_/detail/generate_switch_provision_default_definition.hpp>
#include <argot/prov/switch_/detail/generate_switch_provision_range.hpp>
#endif
#if ARGOT_MAX_PREPROCESSED_SWITCH_CASES >= 33
#define ARGOT_PROV_SWITCH_DETAIL_PREPROCESSING_PROVISION_RANGE ( 33, 64 )
#include <argot/prov/switch_/detail/generate_switch_provision_default_definition.hpp>
#include <argot/prov/switch_/detail/generate_switch_provision_range.hpp>
#endif
#if ARGOT_MAX_PREPROCESSED_SWITCH_CASES >= 65
#error User requested preprocessing for switches with more than 64 cases.
#endif
#undef ARGOT_PROV_SWITCH_DETAIL_PREPROCESSING_PROVISION_RANGE
#endif // End of preprocessing mode checks
#endif // ARGOT_PROV_SWITCH_DETAIL_GENERATE_SWITCH_PROVISION_HPP_
| 40.142857
| 85
| 0.656584
|
mattcalabrese
|
3d36745f5a28918e6248895cf2c1fea18e67768a
| 3,807
|
hpp
|
C++
|
ext/lexertl/lexertl/partition/equivset.hpp
|
thangduong/tokenex
|
fbc124caf248aaf83b8fb5e293b38398da7b1d6a
|
[
"MIT"
] | null | null | null |
ext/lexertl/lexertl/partition/equivset.hpp
|
thangduong/tokenex
|
fbc124caf248aaf83b8fb5e293b38398da7b1d6a
|
[
"MIT"
] | null | null | null |
ext/lexertl/lexertl/partition/equivset.hpp
|
thangduong/tokenex
|
fbc124caf248aaf83b8fb5e293b38398da7b1d6a
|
[
"MIT"
] | null | null | null |
// equivset.hpp
// Copyright (c) 2005-2017 Ben Hanson (http://www.benhanson.net/)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file licence_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef LEXERTL_EQUIVSET_HPP
#define LEXERTL_EQUIVSET_HPP
#include <algorithm>
#include "../parser/tree/node.hpp"
#include <set>
namespace lexertl
{
namespace detail
{
template<typename id_type>
struct basic_equivset
{
typedef std::set<id_type> index_set;
typedef std::vector<id_type> index_vector;
// Not owner of nodes:
typedef basic_node<id_type> node;
typedef std::vector<node *> node_vector;
index_vector _index_vector;
id_type _id;
bool _greedy;
node_vector _followpos;
basic_equivset() :
_index_vector(),
_id(0),
_greedy(true),
_followpos()
{
}
basic_equivset(const index_set &index_set_, const id_type id_,
const bool greedy_, const node_vector &followpos_) :
_index_vector(index_set_.begin(), index_set_.end()),
_id(id_),
_greedy(greedy_),
_followpos(followpos_)
{
}
bool empty() const
{
return _index_vector.empty() && _followpos.empty();
}
void intersect(basic_equivset &rhs_, basic_equivset &overlap_)
{
intersect_indexes(rhs_._index_vector, overlap_._index_vector);
if (!overlap_._index_vector.empty())
{
// Note that the LHS takes priority in order to
// respect rule ordering priority in the lex spec.
overlap_._id = _id;
overlap_._greedy = _greedy;
overlap_._followpos = _followpos;
typename node_vector::const_iterator overlap_begin_ =
overlap_._followpos.begin();
typename node_vector::const_iterator overlap_end_ =
overlap_._followpos.end();
typename node_vector::const_iterator rhs_iter_ =
rhs_._followpos.begin();
typename node_vector::const_iterator rhs_end_ =
rhs_._followpos.end();
for (; rhs_iter_ != rhs_end_; ++rhs_iter_)
{
node *node_ = *rhs_iter_;
if (std::find(overlap_begin_, overlap_end_, node_) ==
overlap_end_)
{
overlap_._followpos.push_back(node_);
overlap_begin_ = overlap_._followpos.begin();
overlap_end_ = overlap_._followpos.end();
}
}
if (_index_vector.empty())
{
_followpos.clear();
}
if (rhs_._index_vector.empty())
{
rhs_._followpos.clear();
}
}
}
private:
void intersect_indexes(index_vector &rhs_, index_vector &overlap_)
{
typename index_vector::iterator iter_ = _index_vector.begin();
typename index_vector::iterator end_ = _index_vector.end();
typename index_vector::iterator rhs_iter_ = rhs_.begin();
typename index_vector::iterator rhs_end_ = rhs_.end();
while (iter_ != end_ && rhs_iter_ != rhs_end_)
{
const id_type index_ = *iter_;
const id_type rhs_index_ = *rhs_iter_;
if (index_ < rhs_index_)
{
++iter_;
}
else if (index_ > rhs_index_)
{
++rhs_iter_;
}
else
{
overlap_.push_back(index_);
iter_ = _index_vector.erase(iter_);
end_ = _index_vector.end();
rhs_iter_ = rhs_.erase(rhs_iter_);
rhs_end_ = rhs_.end();
}
}
}
};
}
}
#endif
| 28.2
| 79
| 0.567113
|
thangduong
|
3d39874c86d5a8d0607dff20b27d0641b0a681ce
| 1,847
|
cpp
|
C++
|
mapping/src/mapperLazyTimesteps.cpp
|
xaedes/GNSS-Shadowing
|
a748e3063fb76272005b6430a844a53644cca9b0
|
[
"MIT"
] | 29
|
2017-10-13T12:14:13.000Z
|
2022-02-25T16:39:05.000Z
|
mapping/src/mapperLazyTimesteps.cpp
|
xaedes/GNSS-Shadowing
|
a748e3063fb76272005b6430a844a53644cca9b0
|
[
"MIT"
] | null | null | null |
mapping/src/mapperLazyTimesteps.cpp
|
xaedes/GNSS-Shadowing
|
a748e3063fb76272005b6430a844a53644cca9b0
|
[
"MIT"
] | 8
|
2018-04-21T14:52:26.000Z
|
2022-02-14T13:51:10.000Z
|
#include "mapping/mapperLazyTimesteps.h"
#include <iostream>
namespace gnssShadowing {
namespace mapping {
MapperLazyTimesteps::MapperLazyTimesteps(world::World& world, MapProperties mapProperties, double startTimeUnixTimeSeconds, double timePerStep, double minimumSatelliteElevation)
: m_world(world)
, m_mapProperties(mapProperties)
, m_minimumSatelliteElevation(minimumSatelliteElevation)
, m_startTimeUnixTimeSeconds(startTimeUnixTimeSeconds)
, m_timePerStep(timePerStep)
{}
double MapperLazyTimesteps::getTime(int timeStep)
{
return m_startTimeUnixTimeSeconds + m_timePerStep*timeStep;
}
DOPMap& MapperLazyTimesteps::getDOPMap(int timeStep)
{
if (m_mappers.count(timeStep) && m_mappers[timeStep].get())
{
return m_mappers[timeStep]->m_dopMap;
}
else
{
return computeDOPMap(timeStep);
}
}
OccupancyMap& MapperLazyTimesteps::getOccupancyMap(int timeStep)
{
if (m_mappers.count(timeStep) && m_mappers[timeStep].get())
{
return m_mappers[timeStep]->m_occupancyMap;
}
else
{
computeDOPMap(timeStep);
return m_mappers[timeStep]->m_occupancyMap;
}
}
void MapperLazyTimesteps::clear()
{
m_mappers.clear();
}
DOPMap& MapperLazyTimesteps::computeDOPMap(int timeStep)
{
// std::cout << __PRETTY_FUNCTION__ << " timeStep " << timeStep << std::endl;
double now = getTime(timeStep);
m_mappers[timeStep].reset(new Mapper(m_world, m_mapProperties, m_minimumSatelliteElevation));
m_mappers[timeStep]->computeDOPMap(now);
return m_mappers[timeStep]->m_dopMap;
}
} // namespace mapping
} // namespace gnssShadowing
| 27.567164
| 181
| 0.651326
|
xaedes
|
3d3bb9d6ec3066e7ae8aa645808da6c09ff82951
| 678
|
cpp
|
C++
|
simple_model_loader/src/main.cpp
|
JacobNeal/gl-projects
|
4ea40797fde28602b9f787f0ec8005dcd164e054
|
[
"MIT"
] | null | null | null |
simple_model_loader/src/main.cpp
|
JacobNeal/gl-projects
|
4ea40797fde28602b9f787f0ec8005dcd164e054
|
[
"MIT"
] | null | null | null |
simple_model_loader/src/main.cpp
|
JacobNeal/gl-projects
|
4ea40797fde28602b9f787f0ec8005dcd164e054
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <fstream>
#include "ModelLoader.hpp"
#include "Model.hpp"
#include "Window.hpp"
#include "Logger.hpp"
LOGGER_DECL
int main()
{
Window window("Simple Model Loader", 800, 640);
ModelLoader modelLoader;
Model * model = modelLoader.load("cube.MODEL");
while (!window.isDone())
{
window.beginDraw();
window.update();
window.draw(model);
window.endDraw();
}
// Clean up after the ModelLoader
delete model;
std::cout << LOGGER;
std::ofstream logFile("log.txt");
if (logFile.is_open())
{
logFile << LOGGER;
logFile.close();
}
return 0;
}
| 14.73913
| 51
| 0.589971
|
JacobNeal
|
3d3ee1870119b322c1714c4886457ca06e699be7
| 1,010
|
cpp
|
C++
|
src/random/NormalDistribution.cpp
|
cuhkshenzhen/CUHKSZLib
|
4ad122d7e736cda3e768c8ae8dcad1f9fb195a1f
|
[
"MIT"
] | null | null | null |
src/random/NormalDistribution.cpp
|
cuhkshenzhen/CUHKSZLib
|
4ad122d7e736cda3e768c8ae8dcad1f9fb195a1f
|
[
"MIT"
] | 29
|
2017-04-26T09:15:28.000Z
|
2017-05-21T15:50:37.000Z
|
src/random/NormalDistribution.cpp
|
cuhkshenzhen/CUHKSZLib
|
4ad122d7e736cda3e768c8ae8dcad1f9fb195a1f
|
[
"MIT"
] | 7
|
2017-04-26T09:32:39.000Z
|
2021-11-03T02:00:07.000Z
|
#include "random/NormalDistribution.h"
#include <cmath>
#include "utils/error.h"
namespace cuhksz {
void NormalDistribution::init(double mean, double stddev) {
if (stddev <= 0) {
error("Invalid parameter `stddev` for NormalDistribution");
}
mean_ = mean;
stddev_ = stddev;
}
double NormalDistribution::next() {
// Marsaglia polar method
// (https://en.wikipedia.org/wiki/Marsaglia_polar_method)
if (hasSpare) {
hasSpare = false;
return spareResult * stddev_ + mean_;
}
double u;
double v;
double sum;
do {
u = randomGenerator->nextDouble(-1, 1);
v = randomGenerator->nextDouble(-1, 1);
sum = u * u + v * v;
// disable gcc's warning for comparing with 0.0
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wfloat-equal"
} while (sum == 0.0 || sum > 1);
#pragma GCC diagnostic pop
double result = std::sqrt(-2 * std::log(sum) / sum);
spareResult = v * result;
hasSpare = true;
return u * result * stddev_ + mean_;
}
} // namespace cuhksz
| 24.634146
| 63
| 0.664356
|
cuhkshenzhen
|
3d3ff38fa83b28d3310c62eecfd311f8e5a1c197
| 8,097
|
cc
|
C++
|
tests/types/traits/logical.cc
|
evanacox/freestanding-rt
|
44cb68d86654f07fe82c0a44a139f90ed5730ac3
|
[
"BSD-3-Clause"
] | null | null | null |
tests/types/traits/logical.cc
|
evanacox/freestanding-rt
|
44cb68d86654f07fe82c0a44a139f90ed5730ac3
|
[
"BSD-3-Clause"
] | null | null | null |
tests/types/traits/logical.cc
|
evanacox/freestanding-rt
|
44cb68d86654f07fe82c0a44a139f90ed5730ac3
|
[
"BSD-3-Clause"
] | null | null | null |
//======---------------------------------------------------------------======//
// //
// Copyright 2021-2022 Evan Cox <evanacox00@gmail.com>. All rights reserved. //
// //
// Use of this source code is governed by a BSD-style license that can be //
// found in the LICENSE.txt file at the root of this project, or at the //
// following link: https://opensource.org/licenses/BSD-3-Clause //
// //
//======---------------------------------------------------------------======//
#include "frt/types/concepts.h"
#include "frt/types/traits.h"
#include "gtest/gtest.h"
/*
* Note: Most of this test is adapted from the libc++ test suite, therefore it is
* also under the LLVM copyright. See the license header below for details:
*/
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
namespace {
struct True {
static constexpr bool value = true;
};
struct False {
static constexpr bool value = false;
};
TEST(FrtTypesTraits, Conjunction) {
static_assert(frt::traits::ConjunctionTrait<>::value);
static_assert(frt::traits::ConjunctionTrait<std::true_type>::value);
static_assert(!frt::traits::ConjunctionTrait<std::false_type>::value);
static_assert(frt::traits::conjunction<>);
static_assert(frt::traits::conjunction<std::true_type>);
static_assert(!frt::traits::conjunction<std::false_type>);
static_assert(frt::traits::ConjunctionTrait<std::true_type, std::true_type>::value);
static_assert(!frt::traits::ConjunctionTrait<std::true_type, std::false_type>::value);
static_assert(!frt::traits::ConjunctionTrait<std::false_type, std::true_type>::value);
static_assert(!frt::traits::ConjunctionTrait<std::false_type, std::false_type>::value);
static_assert(frt::traits::conjunction<std::true_type, std::true_type>);
static_assert(!frt::traits::conjunction<std::true_type, std::false_type>);
static_assert(!frt::traits::conjunction<std::false_type, std::true_type>);
static_assert(!frt::traits::conjunction<std::false_type, std::false_type>);
static_assert(frt::traits::ConjunctionTrait<std::true_type, std::true_type, std::true_type>::value);
static_assert(!frt::traits::ConjunctionTrait<std::true_type, std::false_type, std::true_type>::value);
static_assert(!frt::traits::ConjunctionTrait<std::false_type, std::true_type, std::true_type>::value);
static_assert(!frt::traits::ConjunctionTrait<std::false_type, std::false_type, std::true_type>::value);
static_assert(!frt::traits::ConjunctionTrait<std::true_type, std::true_type, std::false_type>::value);
static_assert(!frt::traits::ConjunctionTrait<std::true_type, std::false_type, std::false_type>::value);
static_assert(!frt::traits::ConjunctionTrait<std::false_type, std::true_type, std::false_type>::value);
static_assert(!frt::traits::ConjunctionTrait<std::false_type, std::false_type, std::false_type>::value);
static_assert(frt::traits::conjunction<std::true_type, std::true_type, std::true_type>);
static_assert(!frt::traits::conjunction<std::true_type, std::false_type, std::true_type>);
static_assert(!frt::traits::conjunction<std::false_type, std::true_type, std::true_type>);
static_assert(!frt::traits::conjunction<std::false_type, std::false_type, std::true_type>);
static_assert(!frt::traits::conjunction<std::true_type, std::true_type, std::false_type>);
static_assert(!frt::traits::conjunction<std::true_type, std::false_type, std::false_type>);
static_assert(!frt::traits::conjunction<std::false_type, std::true_type, std::false_type>);
static_assert(!frt::traits::conjunction<std::false_type, std::false_type, std::false_type>);
static_assert(frt::traits::ConjunctionTrait<True>::value);
static_assert(!frt::traits::ConjunctionTrait<False>::value);
static_assert(frt::traits::conjunction<True>);
static_assert(!frt::traits::conjunction<False>);
}
TEST(FrtTypesTraits, Disjunction) {
static_assert(!frt::traits::DisjunctionTrait<>::value);
static_assert(frt::traits::DisjunctionTrait<std::true_type>::value);
static_assert(!frt::traits::DisjunctionTrait<std::false_type>::value);
static_assert(!frt::traits::disjunction<>);
static_assert(frt::traits::disjunction<std::true_type>);
static_assert(!frt::traits::disjunction<std::false_type>);
static_assert(frt::traits::DisjunctionTrait<std::true_type, std::true_type>::value);
static_assert(frt::traits::DisjunctionTrait<std::true_type, std::false_type>::value);
static_assert(frt::traits::DisjunctionTrait<std::false_type, std::true_type>::value);
static_assert(!frt::traits::DisjunctionTrait<std::false_type, std::false_type>::value);
static_assert(frt::traits::disjunction<std::true_type, std::true_type>);
static_assert(frt::traits::disjunction<std::true_type, std::false_type>);
static_assert(frt::traits::disjunction<std::false_type, std::true_type>);
static_assert(!frt::traits::disjunction<std::false_type, std::false_type>);
static_assert(frt::traits::DisjunctionTrait<std::true_type, std::true_type, std::true_type>::value);
static_assert(frt::traits::DisjunctionTrait<std::true_type, std::false_type, std::true_type>::value);
static_assert(frt::traits::DisjunctionTrait<std::false_type, std::true_type, std::true_type>::value);
static_assert(frt::traits::DisjunctionTrait<std::false_type, std::false_type, std::true_type>::value);
static_assert(frt::traits::DisjunctionTrait<std::true_type, std::true_type, std::false_type>::value);
static_assert(frt::traits::DisjunctionTrait<std::true_type, std::false_type, std::false_type>::value);
static_assert(frt::traits::DisjunctionTrait<std::false_type, std::true_type, std::false_type>::value);
static_assert(!frt::traits::DisjunctionTrait<std::false_type, std::false_type, std::false_type>::value);
static_assert(frt::traits::disjunction<std::true_type, std::true_type, std::true_type>);
static_assert(frt::traits::disjunction<std::true_type, std::false_type, std::true_type>);
static_assert(frt::traits::disjunction<std::false_type, std::true_type, std::true_type>);
static_assert(frt::traits::disjunction<std::false_type, std::false_type, std::true_type>);
static_assert(frt::traits::disjunction<std::true_type, std::true_type, std::false_type>);
static_assert(frt::traits::disjunction<std::true_type, std::false_type, std::false_type>);
static_assert(frt::traits::disjunction<std::false_type, std::true_type, std::false_type>);
static_assert(!frt::traits::disjunction<std::false_type, std::false_type, std::false_type>);
static_assert(frt::traits::DisjunctionTrait<True>::value);
static_assert(!frt::traits::DisjunctionTrait<False>::value);
static_assert(frt::traits::disjunction<True>);
static_assert(!frt::traits::disjunction<False>);
}
TEST(FrtTypesTraits, Negation) {
static_assert(!frt::traits::NegationTrait<std::true_type>::value);
static_assert(frt::traits::NegationTrait<std::false_type>::value);
static_assert(!frt::traits::negation<std::true_type>);
static_assert(frt::traits::negation<std::false_type>);
static_assert(!frt::traits::NegationTrait<True>::value);
static_assert(frt::traits::NegationTrait<False>::value);
static_assert(!frt::traits::negation<True>);
static_assert(frt::traits::negation<False>);
static_assert(frt::traits::NegationTrait<std::negation<std::true_type>>::value);
static_assert(!frt::traits::NegationTrait<std::negation<std::false_type>>::value);
}
} // namespace
| 57.835714
| 108
| 0.682845
|
evanacox
|
3d406ccf27012fa7f5b609ec3291bada72ac6268
| 140
|
hpp
|
C++
|
template-bot/src/utils.hpp
|
bmstu-iu8-cpp-sem-1/homework-telegram-bot
|
138f6611e4ca08b9a5c4dde76c54af1cefe6504c
|
[
"MIT"
] | 2
|
2021-03-09T08:12:28.000Z
|
2022-02-21T18:10:36.000Z
|
template-bot/src/utils.hpp
|
sjuda/telegram-bot
|
11f7bb7f24044bdd4e0d30b7a65757e5a4d1be8d
|
[
"MIT"
] | null | null | null |
template-bot/src/utils.hpp
|
sjuda/telegram-bot
|
11f7bb7f24044bdd4e0d30b7a65757e5a4d1be8d
|
[
"MIT"
] | null | null | null |
#pragma once
#include <string>
#include <boost/locale.hpp>
namespace Utils
{
std::string fromLocale(const std::string& localeStr);
}
| 12.727273
| 57
| 0.714286
|
bmstu-iu8-cpp-sem-1
|
3d420cd5393eba0250fc200d6e0304cc05ed703d
| 3,343
|
cpp
|
C++
|
Code/System/Resource/ResourceLoader.cpp
|
JuanluMorales/KRG
|
f3a11de469586a4ef0db835af4bc4589e6b70779
|
[
"MIT"
] | 419
|
2022-01-27T19:37:43.000Z
|
2022-03-31T06:14:22.000Z
|
Code/System/Resource/ResourceLoader.cpp
|
jagt/KRG
|
ba20cd8798997b0450491b0cc04dc817c4a4bc76
|
[
"MIT"
] | 2
|
2022-01-28T20:35:33.000Z
|
2022-03-13T17:42:52.000Z
|
Code/System/Resource/ResourceLoader.cpp
|
jagt/KRG
|
ba20cd8798997b0450491b0cc04dc817c4a4bc76
|
[
"MIT"
] | 20
|
2022-01-27T20:41:02.000Z
|
2022-03-26T16:16:57.000Z
|
#include "ResourceLoader.h"
#include "ResourceHeader.h"
#include "System/Core/Serialization/BinaryArchive.h"
#include "System/Core/Logging/Log.h"
//-------------------------------------------------------------------------
namespace KRG::Resource
{
bool ResourceLoader::Load( ResourceID const& resourceID, TVector<Byte>& rawData, ResourceRecord* pResourceRecord ) const
{
Serialization::BinaryMemoryArchive archive( Serialization::Mode::Read, rawData );
if ( archive.IsValid() )
{
// Read resource header
Resource::ResourceHeader header;
archive >> header;
// Set all install dependencies
pResourceRecord->m_installDependencyResourceIDs.reserve( header.m_installDependencies.size() );
for ( auto const& depResourceID : header.m_installDependencies )
{
pResourceRecord->m_installDependencyResourceIDs.push_back( depResourceID );
}
// Perform resource load
if ( !LoadInternal( resourceID, pResourceRecord, archive ) )
{
KRG_LOG_ERROR( "Resource", "Resource loader failed to load resource: %s", resourceID.c_str() );
return false;
}
// Loaders must always set a valid resource data ptr, even if the resource internally is invalid
// This is enforced to prevent leaks from occurring when a loader allocates a resource, then tries to
// load it unsuccessfully and then forgets to release the allocated data.
KRG_ASSERT( pResourceRecord->GetResourceData() != nullptr );
return true;
}
else
{
KRG_LOG_ERROR( "Resource", "Failed to read binary resource data (%s)", resourceID.c_str() );
return false;
}
}
InstallResult ResourceLoader::Install( ResourceID const& resourceID, ResourceRecord* pResourceRecord, InstallDependencyList const& installDependencies ) const
{
KRG_ASSERT( pResourceRecord != nullptr );
pResourceRecord->m_pResource->m_resourceID = resourceID;
return InstallResult::Succeeded;
}
InstallResult ResourceLoader::UpdateInstall( ResourceID const& resourceID, ResourceRecord* pResourceRecord ) const
{
// This function should never be called directly!!
// If your resource requires multi-frame installation, you need to override this function in your loader and return InstallResult::InProgress from the install function!
KRG_UNREACHABLE_CODE();
return InstallResult::Succeeded;
}
void ResourceLoader::Unload( ResourceID const& resourceID, ResourceRecord* pResourceRecord ) const
{
KRG_ASSERT( pResourceRecord != nullptr );
KRG_ASSERT( pResourceRecord->IsUnloading() || pResourceRecord->HasLoadingFailed() );
UnloadInternal( resourceID, pResourceRecord );
pResourceRecord->m_installDependencyResourceIDs.clear();
}
void ResourceLoader::UnloadInternal( ResourceID const& resourceID, ResourceRecord* pResourceRecord ) const
{
IResource* pData = pResourceRecord->GetResourceData();
KRG::Delete( pData );
pResourceRecord->SetResourceData( nullptr );
}
}
| 44.573333
| 177
| 0.638648
|
JuanluMorales
|
3d447cbeece9cbf1aa1dc04cf5ba3f18bd7e77fd
| 2,937
|
cc
|
C++
|
moe/moe-core/moe.apple/moe.core.native/android.art.compiler/src/main/native/compiler_common_gen/image_writer_operator_out.cc
|
ark100/multi-os-engine
|
f71d66a58b3d7e5eb2a68541480b7a0d88c7b908
|
[
"Apache-2.0"
] | 1
|
2020-05-11T18:36:25.000Z
|
2020-05-11T18:36:25.000Z
|
moe/moe-core/moe.apple/moe.core.native/android.art.compiler/src/main/native/compiler_common_gen/image_writer_operator_out.cc
|
ark100/multi-os-engine
|
f71d66a58b3d7e5eb2a68541480b7a0d88c7b908
|
[
"Apache-2.0"
] | null | null | null |
moe/moe-core/moe.apple/moe.core.native/android.art.compiler/src/main/native/compiler_common_gen/image_writer_operator_out.cc
|
ark100/multi-os-engine
|
f71d66a58b3d7e5eb2a68541480b7a0d88c7b908
|
[
"Apache-2.0"
] | null | null | null |
/*
Copyright 2014-2016 Intel Corporation
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 <iostream>
#include "image_writer.h"
// This was automatically generated by /Volumes/Android/inde-dev//art/tools/generate-operator-out.py --- do not edit!
namespace art {
std::ostream& operator<<(std::ostream& os, const ImageWriter::Bin& rhs) {
switch (rhs) {
case ImageWriter::kBinString: os << "BinString"; break;
case ImageWriter::kBinRegular: os << "BinRegular"; break;
case ImageWriter::kBinClassInitializedFinalStatics: os << "BinClassInitializedFinalStatics"; break;
case ImageWriter::kBinClassInitialized: os << "BinClassInitialized"; break;
case ImageWriter::kBinClassVerified: os << "BinClassVerified"; break;
case ImageWriter::kBinArtField: os << "BinArtField"; break;
case ImageWriter::kBinArtMethodClean: os << "BinArtMethodClean"; break;
case ImageWriter::kBinArtMethodDirty: os << "BinArtMethodDirty"; break;
case ImageWriter::kBinDexCacheArray: os << "BinDexCacheArray"; break;
case ImageWriter::kBinSize: os << "BinSize"; break;
default: os << "ImageWriter::Bin[" << static_cast<int>(rhs) << "]"; break;
}
return os;
}
} // namespace art
// This was automatically generated by /Volumes/Android/inde-dev//art/tools/generate-operator-out.py --- do not edit!
namespace art {
std::ostream& operator<<(std::ostream& os, const ImageWriter::NativeObjectRelocationType& rhs) {
switch (rhs) {
case ImageWriter::kNativeObjectRelocationTypeArtField: os << "NativeObjectRelocationTypeArtField"; break;
case ImageWriter::kNativeObjectRelocationTypeArtFieldArray: os << "NativeObjectRelocationTypeArtFieldArray"; break;
case ImageWriter::kNativeObjectRelocationTypeArtMethodClean: os << "NativeObjectRelocationTypeArtMethodClean"; break;
case ImageWriter::kNativeObjectRelocationTypeArtMethodArrayClean: os << "NativeObjectRelocationTypeArtMethodArrayClean"; break;
case ImageWriter::kNativeObjectRelocationTypeArtMethodDirty: os << "NativeObjectRelocationTypeArtMethodDirty"; break;
case ImageWriter::kNativeObjectRelocationTypeArtMethodArrayDirty: os << "NativeObjectRelocationTypeArtMethodArrayDirty"; break;
case ImageWriter::kNativeObjectRelocationTypeDexCacheArray: os << "NativeObjectRelocationTypeDexCacheArray"; break;
default: os << "ImageWriter::NativeObjectRelocationType[" << static_cast<int>(rhs) << "]"; break;
}
return os;
}
} // namespace art
| 49.779661
| 131
| 0.765066
|
ark100
|
3d4aedc2125a1985f141e06caed48c4ba3c24f50
| 1,991
|
hpp
|
C++
|
aslam_optimizer/sparse_block_matrix/test/sbm_gtest.hpp
|
PushyamiKaveti/kalibr
|
d8bdfc59ee666ef854012becc93571f96fe5d80c
|
[
"BSD-4-Clause"
] | 2,690
|
2015-01-07T03:50:23.000Z
|
2022-03-31T20:27:01.000Z
|
aslam_optimizer/sparse_block_matrix/test/sbm_gtest.hpp
|
PushyamiKaveti/kalibr
|
d8bdfc59ee666ef854012becc93571f96fe5d80c
|
[
"BSD-4-Clause"
] | 481
|
2015-01-27T10:21:00.000Z
|
2022-03-31T14:02:41.000Z
|
aslam_optimizer/sparse_block_matrix/test/sbm_gtest.hpp
|
PushyamiKaveti/kalibr
|
d8bdfc59ee666ef854012becc93571f96fe5d80c
|
[
"BSD-4-Clause"
] | 1,091
|
2015-01-26T21:21:13.000Z
|
2022-03-30T01:55:33.000Z
|
/**
* @file sbm_gtest.hpp
* @author Paul Furgale <paul.furgale@gmail.com>
* @date Wed Jan 11 09:29:57 2012
*
* @brief Helper functions for unit testing SBM
*
*
*/
#ifndef _SBM_GTEST_H_
#define _SBM_GTEST_H_
namespace sparse_block_matrix {
template<typename MATRIX1_TYPE, typename MATRIX2_TYPE, typename T>
void expectNear(const MATRIX1_TYPE & A, const MATRIX2_TYPE & B, T tolerance, std::string const & message = "")
{
// These assert statements will return from this function but not from the base unit test.
ASSERT_EQ(A.rows(),B.rows()) << message << "\nMatrix A:\n" << A << "\nand matrix B\n" << B << "\nare not the same size";
ASSERT_EQ(A.cols(),B.cols()) << message << "\nMatrix A:\n" << A << "\nand matrix B\n" << B << "\nare not the same size";
for(int r = 0; r < A.rows(); r++)
{
for(int c = 0; c < A.cols(); c++)
{
ASSERT_NEAR(A(r,c),B(r,c),tolerance) << message << "\nTolerance comparison failed at (" << r << "," << c << ")"
<< "\nMatrix A:\n" << A << "\nand matrix B\n" << B;
}
}
}
template<typename MATRIX1_TYPE, typename MATRIX2_TYPE>
void expectEqual(const MATRIX1_TYPE & A, const MATRIX2_TYPE & B, std::string const & message = "")
{
// These assert statements will return from this function but not from the base unit test.
ASSERT_EQ(B.rows(),A.rows()) << message << "\nMatrix A:\n" << A << "\nand matrix B\n" << B << "\nare not the same size";
ASSERT_EQ(B.cols(),A.cols()) << message << "\nMatrix A:\n" << A << "\nand matrix B\n" << B << "\nare not the same size";
for(int r = 0; r < A.rows(); r++)
{
for(int c = 0; c < A.cols(); c++)
{
ASSERT_EQ(B(r,c),A(r,c)) << message << "\nEquality comparison failed at (" << r << "," << c << ")"
<< "\nMatrix A:\n" << A << "\nand matrix B\n" << B;
}
}
}
} // namespace sbm
#endif /* _SBM_GTEST_H_ */
| 36.87037
| 126
| 0.550979
|
PushyamiKaveti
|
3d4c6a768bef0b77475e30aa4f9b42aff74bbba1
| 444
|
cpp
|
C++
|
codeforces/1108B.cpp
|
cosmicray001/Online_judge_Solutions-
|
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
|
[
"MIT"
] | 3
|
2018-01-08T02:52:51.000Z
|
2021-03-03T01:08:44.000Z
|
codeforces/1108B.cpp
|
cosmicray001/Online_judge_Solutions-
|
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
|
[
"MIT"
] | null | null | null |
codeforces/1108B.cpp
|
cosmicray001/Online_judge_Solutions-
|
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
|
[
"MIT"
] | 1
|
2020-08-13T18:07:35.000Z
|
2020-08-13T18:07:35.000Z
|
#include <bits/stdc++.h>
#define le 130
using namespace std;
int n[le];
map<int, int> mp;
int main(){
//freopen("input.txt", "r", stdin);
int len, mx = -INT_MAX, mx1 = -INT_MAX;
scanf("%d", &len);
for(int i = 0; i < len; i++){
scanf("%d", &n[i]);
mx = max(mx, n[i]);
}
for(int i = 0; i < len; i++){
mp[n[i]]++;
if(mx % n[i] != 0 || mp[n[i]] > 1) mx1 = max(mx1, n[i]);
}
printf("%d %d\n", mx, mx1);
return 0;
}
| 21.142857
| 60
| 0.481982
|
cosmicray001
|
3d4cbc776bb8b6c4f70872c069f5e89785342846
| 620
|
cpp
|
C++
|
c++11/understanding-cpp11/chapter7/7-3-13.cpp
|
cuiwm/choe_lib
|
6992c7bf551e7d6d633399b21b028e6873d5e6e8
|
[
"MIT"
] | null | null | null |
c++11/understanding-cpp11/chapter7/7-3-13.cpp
|
cuiwm/choe_lib
|
6992c7bf551e7d6d633399b21b028e6873d5e6e8
|
[
"MIT"
] | null | null | null |
c++11/understanding-cpp11/chapter7/7-3-13.cpp
|
cuiwm/choe_lib
|
6992c7bf551e7d6d633399b21b028e6873d5e6e8
|
[
"MIT"
] | null | null | null |
#include <vector>
#include <algorithm>
using namespace std;
vector<int> nums;
vector<int> largeNums;
const int ubound = 10;
inline void LargeNumsFunc(int i){
if (i > ubound)
largeNums.push_back(i);
}
void Above() {
// 传统的for循环
for (auto itr = nums.begin(); itr != nums.end(); ++itr) {
if (*itr >= ubound)
largeNums.push_back(*itr);
}
// 使用函数指针
for_each(nums.begin(), nums.end(), LargeNumsFunc);
// 使用lambda函数和算法for_each
for_each(nums.begin(), nums.end(), [=](int i){
if (i > ubound)
largeNums.push_back(i);
});
}
| 19.375
| 61
| 0.562903
|
cuiwm
|
3d4cc3e641a6d66de21abeea0c2035956e900a7d
| 5,612
|
cpp
|
C++
|
FBConsole.cpp
|
StereoRocker/fbconsole
|
a0ad55525f1c6a0a048147f8d5317a081fe372f0
|
[
"BSD-3-Clause"
] | null | null | null |
FBConsole.cpp
|
StereoRocker/fbconsole
|
a0ad55525f1c6a0a048147f8d5317a081fe372f0
|
[
"BSD-3-Clause"
] | null | null | null |
FBConsole.cpp
|
StereoRocker/fbconsole
|
a0ad55525f1c6a0a048147f8d5317a081fe372f0
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright 2021 Dominic Houghton. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Framebuffer console driver, using the I_Framebuffer interface
#include "FBConsole.hpp"
template <class T>
FBConsole<T>::FBConsole(I_Framebuffer<T>* framebuffer, uint8_t* font, uint8_t scale)
{
// These will hold the display's actual dimensions while initialising
uint16_t display_width, display_height;
// Set the constants within the class
_FRAMEBUFFER = framebuffer;
_FONT = font;
_SCALE = scale;
// Calculate the console width and height, store them within the class
_FRAMEBUFFER->get_dimensions(&display_width, &display_height);
_WIDTH = display_width / (8 * _SCALE);
_HEIGHT = display_height / (8 * _SCALE);
/* Create a buffer of pixels, large enough to hold a single character.
* The put_char function will use this array, so as to maintain a consistent
* memory footprint.
*
* Scaling the font to be larger will increase the memory footprint
* exponentially.
*/
_CHARBUF = new T[(8 * _SCALE) * (8 * _SCALE)];
// Set sane defaults for the runtime variables
console_background = _FRAMEBUFFER->get_color(0x00,0x00,0x00); // Black
console_foreground = _FRAMEBUFFER->get_color(0xFF,0xFF,0xFF); // White
console_x = 0;
console_y = 0;
}
template <class T>
void FBConsole<T>::put_char(char c)
{
// Determine the character to draw
uint16_t charindex = 0;
bool drawchar = true;
int count;
// Handle special-case characters, or calculate the font index
switch (c)
{
case '\n': // Line feed, handled unix-style
drawchar = false;
console_x = 0;
console_y++;
break;
case '\r': // Carriage return
drawchar = false;
console_x = 0;
break;
case '\t': // Tab
count = _TABSTOP - ((console_x) % _TABSTOP);
for (int i = 0; i < count; i++)
put_char(' ');
drawchar = false;
break;
case '\b': // Backspace
if (console_x > 0)
console_x--;
drawchar = false;
break;
// If character is none of the special cases above
default:
// Test if the character is mapped in the font
if (c >= 0x20 || c <= 0x7E)
charindex = (c - 0x20);
else
charindex = 95; // font[95] contains the "invalid" glyph
break;
}
// Fill the character buffer
// Iterate through the character data
if (drawchar) {
T* color;
for (int cy = 0; cy < 8; cy++)
{
for (int cx = 0; cx < 8; cx++)
{
// Test the bit
if ( ((_FONT[(charindex * 8) + cy] << cx) & 0x80) == 0x80 )
color = &console_foreground;
else
color = &console_background;
// Plot the color in the character buffer
for (int by = 0; by < _SCALE; by++)
{
for (int bx = 0; bx < _SCALE; bx++)
{
//_CHARBUF[((cy + by) * 8 * _SCALE) + (cx * _SCALE) + bx] = *color;
//_CHARBUF[(cy * 8 * _SCALE) + (cx * _SCALE) + bx] = *color;
_CHARBUF[ (((cy * _SCALE) + by) * (8 * _SCALE)) + (cx * _SCALE) + bx] = *color;
}
}
}
}
// Plot the character buffer
uint16_t dx, dy;
dx = (console_x * 8 * _SCALE);
dy = (console_y * 8 * _SCALE);
_FRAMEBUFFER->plot_block(dx, dy,
dx + (8 * _SCALE) - 1, dy + (8 * _SCALE) - 1,
_CHARBUF, (8 * _SCALE) * (8 * _SCALE));
// Increase console_x
console_x++;
}
// Test console_x, increment console_y if necessary
if (console_x >= _WIDTH)
{
console_x = 0;
console_y++;
}
// Test console_y, call scroll_vertical if necessary
if (console_y >= _HEIGHT)
{
_FRAMEBUFFER->scroll_vertical(8 * _SCALE);
// If scroll_vertical was called, decrement console_y and clear the row
console_y--;
// Set character with only background
for (int cy = 0; cy < 8; cy++)
{
for (int cx = 0; cx < 8; cx++)
{
// Plot the color in the character buffer
for (int by = 0; by < _SCALE; by++)
{
for (int bx = 0; bx < _SCALE; bx++)
{
_CHARBUF[ (((cy * _SCALE) + by) * (8 * _SCALE)) + (cx * _SCALE) + bx] = console_background;
}
}
}
}
// Clear the row with the background color
int dy = (console_y * 8 * _SCALE);
int dx;
for (int x = 0; x < _WIDTH; x++)
{
dx = (x * 8 * _SCALE);
_FRAMEBUFFER->plot_block(dx, dy,
dx + (8 * _SCALE) - 1, dy + (8 * _SCALE) - 1,
_CHARBUF, (8 * _SCALE) * (8 * _SCALE));
}
}
}
template <class T>
void FBConsole<T>::put_string(const char* str)
{
int i = 0;
for (i = 0; str[i] != 0; i++)
put_char(str[i]);
}
template class FBConsole<uint8_t>;
template class FBConsole<uint16_t>;
template class FBConsole<uint32_t>;
| 30.335135
| 115
| 0.50392
|
StereoRocker
|
3d4ce5463fc1e90aa8c6ff5511f4d0f941e7304c
| 4,819
|
cpp
|
C++
|
librtt/Display/Rtt_ClosedPath.cpp
|
pouwelsjochem/corona
|
86ffe9002e42721b4bb2c386024111d995e7b27c
|
[
"MIT"
] | null | null | null |
librtt/Display/Rtt_ClosedPath.cpp
|
pouwelsjochem/corona
|
86ffe9002e42721b4bb2c386024111d995e7b27c
|
[
"MIT"
] | null | null | null |
librtt/Display/Rtt_ClosedPath.cpp
|
pouwelsjochem/corona
|
86ffe9002e42721b4bb2c386024111d995e7b27c
|
[
"MIT"
] | null | null | null |
//////////////////////////////////////////////////////////////////////////////
//
// This file is part of the Corona game engine.
// For overview and more information on licensing please refer to README.md
// Home page: https://github.com/coronalabs/corona
// Contact: support@coronalabs.com
//
//////////////////////////////////////////////////////////////////////////////
#include "Core/Rtt_Build.h"
#include "Display/Rtt_ClosedPath.h"
#include "Display/Rtt_DisplayTypes.h"
#include "Rtt_Matrix.h"
#include "Rtt_LuaUserdataProxy.h"
#include "Display/Rtt_VertexCache.h"
#include "Display/Rtt_DisplayObject.h"
#include "Display/Rtt_Paint.h"
#include "Display/Rtt_Shader.h"
#include "Renderer/Rtt_Program.h"
#include "Renderer/Rtt_Geometry_Renderer.h"
// ----------------------------------------------------------------------------
namespace Rtt
{
// ----------------------------------------------------------------------------
ClosedPath::ClosedPath( Rtt_Allocator* pAllocator )
: fObserver( NULL ),
fAdapter( NULL ),
fProxy( NULL ),
fFill( NULL ),
fProperties( 0 ),
fDirtyFlags( kDefault )
{
}
ClosedPath::~ClosedPath()
{
if ( fProxy )
{
GetObserver()->QueueRelease( fProxy ); // Release native ref to Lua-side proxy
fProxy->DetachUserdata(); // Notify proxy that object is invalid
}
Rtt_DELETE( fFill );
}
void
ClosedPath::Update( RenderData& data, const Matrix& srcToDstSpace )
{
if ( HasFill() && ! fFill->IsValid(Paint::kTextureTransformFlag) )
{
Invalidate( kFillSourceTexture );
}
}
void
ClosedPath::UpdateGeometry( Geometry& dst, const VertexCache& src, const Matrix& srcToDstSpace, U32 flags, Array<U16> *indices )
{
if ( 0 == flags ) { return; }
const ArrayVertex2& vertices = src.Vertices();
const ArrayVertex2& texVertices = src.TexVertices();
U32 numVertices = vertices.Length();
U32 numIndices = indices==NULL?0:indices->Length();
if ( dst.GetVerticesAllocated() < numVertices || dst.GetIndicesAllocated() < numIndices)
{
dst.Resize( numVertices, numIndices, false );
}
Geometry::Vertex *dstVertices = dst.GetVertexData();
bool updateVertices = ( flags & kVerticesMask );
bool updateTexture = ( flags & kTexVerticesMask );
Rtt_ASSERT( ! updateTexture || ( vertices.Length() == texVertices.Length() ) );
for ( U32 i = 0, iMax = vertices.Length(); i < iMax; i++ )
{
Rtt_ASSERT( i < dst.GetVerticesAllocated() );
Geometry::Vertex& dst = dstVertices[i];
if ( updateVertices )
{
Vertex2 v = vertices[i];
srcToDstSpace.Apply( v );
dst.x = v.x;
dst.y = v.y;
dst.z = 0.f;
}
if ( updateTexture )
{
dst.u = texVertices[i].x;
dst.v = texVertices[i].y;
dst.q = 1.f;
}
}
dst.SetVerticesUsed( numVertices );
if(flags & kIndicesMask)
{
if(indices)
{
const U16* indicesData = indices->ReadAccess();
U16* dstData = dst.GetIndexData();
numIndices = indices->Length();
for (U32 i=0; i<numIndices; i++)
{
dstData[i] = indicesData[i];
}
dst.Invalidate();
}
dst.SetIndicesUsed(numIndices);
}
}
void
ClosedPath::Translate( Real dx, Real dy )
{
if ( HasFill() )
{
fFill->Translate( dx, dy );
}
}
bool
ClosedPath::SetSelfBounds( Real width, Real height )
{
return false;
}
void
ClosedPath::UpdatePaint( RenderData& data )
{
if ( HasFill() )
{
fFill->UpdatePaint( data );
}
}
void
ClosedPath::UpdateColor( RenderData& data, U8 objectAlpha )
{
if ( HasFill() )
{
fFill->UpdateColor( data, objectAlpha );
}
}
void
ClosedPath::SetFill( Paint* newValue )
{
if ( IsProperty( kIsFillLocked ) )
{
// Caller expects receiver to own this, so we delete it
// b/c the fill is locked. Otherwise it will leak.
Rtt_DELETE( newValue );
return;
}
if ( fFill != newValue )
{
if ( ! fFill )
{
// If fill was NULL, then we need to ensure
// source vertices are generated
Invalidate( kFillSource | kFillSourceTexture );
}
Rtt_DELETE( fFill );
fFill = newValue;
if ( newValue )
{
newValue->SetObserver( GetObserver() );
}
}
}
void
ClosedPath::SwapFill( ClosedPath& rhs )
{
Paint* paint = rhs.fFill;
rhs.fFill = fFill;
fFill = paint;
if ( fFill )
{
fFill->SetObserver( GetObserver() );
}
if ( rhs.fFill )
{
rhs.fFill->SetObserver( rhs.GetObserver() );
}
Invalidate( kFillSource );
}
bool
ClosedPath::IsFillVisible() const
{
bool result = false;
if ( HasFill() )
{
result = ( fFill->GetRGBA().a > Rtt_REAL_0 );
}
return result;
}
void
ClosedPath::PushProxy( lua_State *L ) const
{
if ( ! fProxy )
{
fProxy = LuaUserdataProxy::New( L, const_cast< Self * >( this ) );
fProxy->SetAdapter( GetAdapter() );
}
fProxy->Push( L );
}
// ----------------------------------------------------------------------------
} // namespace Rtt
// ----------------------------------------------------------------------------
| 19.913223
| 128
| 0.599709
|
pouwelsjochem
|
3d4d428b5518f3ebfb7a75e47af0c31a1f7b8b90
| 271
|
cpp
|
C++
|
tester-webserv/CppTester/src/Utility/close_pipe.cpp
|
aprilmayjune135/42_web_server
|
46bc46dd6a0008119842e3848d4fe57fcd84526b
|
[
"MIT"
] | 2
|
2022-01-04T13:07:46.000Z
|
2022-01-04T13:08:50.000Z
|
tester-webserv/CppTester/src/Utility/close_pipe.cpp
|
aprilmayjune135/web-server
|
46bc46dd6a0008119842e3848d4fe57fcd84526b
|
[
"MIT"
] | 3
|
2021-09-27T08:35:34.000Z
|
2021-11-25T09:49:52.000Z
|
tester-webserv/CppTester/src/Utility/close_pipe.cpp
|
aprilmayjune135/web-server
|
46bc46dd6a0008119842e3848d4fe57fcd84526b
|
[
"MIT"
] | 2
|
2021-11-17T20:26:55.000Z
|
2021-12-22T21:54:24.000Z
|
#include "utility.hpp"
#include "macros.hpp"
#include <unistd.h>
#include <stdio.h>
namespace util
{
void closeFd(int fd)
{
if (close(fd) == -1)
{
syscallError(_FUNC_ERR("close"));
}
}
void closePipe(int* fds)
{
closeFd(fds[0]);
closeFd(fds[1]);
}
}
| 12.318182
| 36
| 0.612546
|
aprilmayjune135
|
3d5811c0d2006ec2c33ae0fdf33af47b00862d3d
| 752
|
cpp
|
C++
|
halfacookie.cpp
|
nemo201/Kattis
|
887711eece263965a4529048011847f7a2749fec
|
[
"MIT"
] | null | null | null |
halfacookie.cpp
|
nemo201/Kattis
|
887711eece263965a4529048011847f7a2749fec
|
[
"MIT"
] | null | null | null |
halfacookie.cpp
|
nemo201/Kattis
|
887711eece263965a4529048011847f7a2749fec
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
#define rep(i, a, b) for(int i = a; i < (b); ++i)
#define trav(a, x) for(auto& a : x)
#define all(x) x.begin(), x.end()
#define sz(x) (int)(x).size()
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
int main() {
cout << fixed << setprecision(4);
double r, x, y;
while(cin >> r >> x >> y){
if(sqrt(x * x + y * y) >= r){
cout << "miss" << endl;
} else {
double h = r - sqrt(x * x + y * y);
double area = r * r * 3.141592653589793238462643383;
double seg_area = r * r * acos((r - h) / r) - (r - h) * sqrt((2 * r * h - h * h));
cout << area - seg_area << " " << seg_area << endl;
}
}
}
| 30.08
| 94
| 0.482713
|
nemo201
|
3d59a072f742b1c1ae7225767f5ef46ae0edec0c
| 1,088
|
cpp
|
C++
|
Tree Algorithms/Distance Queries.cpp
|
DecSP/cses-downloader
|
12a8f37665a33f6f790bd2c355f84dea8a0e332c
|
[
"MIT"
] | 2
|
2022-02-12T12:30:13.000Z
|
2022-02-12T13:59:20.000Z
|
Tree Algorithms/Distance Queries.cpp
|
DecSP/cses-downloader
|
12a8f37665a33f6f790bd2c355f84dea8a0e332c
|
[
"MIT"
] | 2
|
2022-02-12T11:09:41.000Z
|
2022-02-12T11:55:49.000Z
|
Tree Algorithms/Distance Queries.cpp
|
DecSP/cses-downloader
|
12a8f37665a33f6f790bd2c355f84dea8a0e332c
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
vector<vector<int>> adjList;
int up[(int)(2e5+1.5)][20] {};
vector<int>tin,tout,d;
int n,q,timer;
void dfs(int curr,int pre){
tin[curr]=timer++;
up[curr][0]=pre;
for (int i=1;i<20;++i){
up[curr][i]=up[up[curr][i-1]][i-1];
}
for (int &v:adjList[curr]){
if (v==pre) continue;
d[v]=d[curr]+1;
dfs(v,curr);
}
tout[curr]=timer++;
}
bool is_ancestor(int par,int child){
return tin[par]<=tin[child]&&tout[par]>=tout[child];
}
int lca(int n1,int n2){
if (is_ancestor(n1,n2)) return n1;
if (is_ancestor(n2,n1)) return n2;
for (int i=19;i>=0;--i){
if (!is_ancestor(up[n1][i],n2)) n1=up[n1][i];
}
return up[n1][0];
}
int main(){
ios::sync_with_stdio(false);cin.tie(NULL);
cin>>n>>q;
adjList.assign(n,vector<int>());
tin.assign(n,-1);
tout.assign(n,-1);
d.assign(n,-1);
d[0]=0;
timer=0;
for (int i=1;i<n;++i){
int a,b;cin>>a>>b;--a;--b;
adjList[a].push_back(b);
adjList[b].push_back(a);
}
dfs(0,0);
for (int i=0;i<q;++i){
int a,b;
cin>>a>>b;--a;--b;
cout<<d[a]+d[b]-2*d[lca(a,b)]<<'\n';
}
return 0;
}
| 19.087719
| 53
| 0.579963
|
DecSP
|
3d5b8c15d444b1fe8d4086f4a81a95f4f38fec7f
| 1,718
|
cpp
|
C++
|
plugins/robots/common/kitBase/src/blocksBase/common/getButtonCodeBlock.cpp
|
anastasia143/qreal
|
9bd224b41e569c9c50ab88848a5746a010c65ad7
|
[
"Apache-2.0"
] | 39
|
2015-01-26T16:18:43.000Z
|
2021-12-20T23:36:41.000Z
|
plugins/robots/common/kitBase/src/blocksBase/common/getButtonCodeBlock.cpp
|
anastasia143/qreal
|
9bd224b41e569c9c50ab88848a5746a010c65ad7
|
[
"Apache-2.0"
] | 1,248
|
2019-02-21T19:32:09.000Z
|
2022-03-29T16:50:04.000Z
|
plugins/robots/common/kitBase/src/blocksBase/common/getButtonCodeBlock.cpp
|
anastasia143/qreal
|
9bd224b41e569c9c50ab88848a5746a010c65ad7
|
[
"Apache-2.0"
] | 58
|
2015-03-03T12:57:28.000Z
|
2020-05-09T15:54:42.000Z
|
/* Copyright 2007-2015 QReal Research Group
*
* 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 "kitBase/blocksBase/common/getButtonCodeBlock.h"
#include <utils/abstractTimer.h>
#include <kitBase/robotModel/robotParts/button.h>
#include <kitBase/robotModel/robotModelUtils.h>
using namespace kitBase::blocksBase::common;
using namespace kitBase::robotModel;
GetButtonCodeBlock::GetButtonCodeBlock(RobotModelInterface &robotModel)
: WaitBlock(robotModel)
{
}
void GetButtonCodeBlock::run()
{
mButtons.clear();
for (const PortInfo &port : mRobotModel.availablePorts()) {
const robotParts::Button *button = RobotModelUtils::findDevice<robotParts::Button>(mRobotModel, port.name());
if (button) {
mButtons << button;
}
}
mActiveWaitingTimer->start();
}
void GetButtonCodeBlock::timerTimeout()
{
for (const robotParts::Button *button : mButtons) {
if (button->lastData()) {
returnCode(button->code());
return;
}
}
if (!boolProperty("Wait")) {
returnCode(-1);
}
}
DeviceInfo GetButtonCodeBlock::device() const
{
return DeviceInfo();
}
void GetButtonCodeBlock::returnCode(int code)
{
evalCode(stringProperty("Variable") + " = " + QString::number(code));
stop();
}
| 26.030303
| 111
| 0.735157
|
anastasia143
|
3d5e27cb374a8905ccf9b4d80607ae7935995314
| 2,235
|
cpp
|
C++
|
sdlpaint/rcolor.cpp
|
cbries/utilities
|
86ce97d2c3e0d13b9beb0fc6ec79d31945c14461
|
[
"MIT"
] | 1
|
2015-02-22T17:40:23.000Z
|
2015-02-22T17:40:23.000Z
|
sdlpaint/rcolor.cpp
|
cbries/utilities
|
86ce97d2c3e0d13b9beb0fc6ec79d31945c14461
|
[
"MIT"
] | null | null | null |
sdlpaint/rcolor.cpp
|
cbries/utilities
|
86ce97d2c3e0d13b9beb0fc6ec79d31945c14461
|
[
"MIT"
] | null | null | null |
/**
* Copyright (C) 2007 Christian B. Ries
* License: MIT
* Website: https://github.com/cbries/utilities
*/
#include "rcolor.h"
RColor::RColor()
{
setType( COLOR );
}
RColor::RColor( const SDL_Surface * surface,
int xpos, int ypos,
int width, int height )
: RButton( surface, xpos, ypos, width, height )
{
setType( COLOR );
}
RColor::~RColor()
{
}
void RColor::draw()
{
SDL_Rect clip;
clip.x = x();
clip.y = y();
clip.w = width();
clip.h = height();
SDL_SetClipRect((SDL_Surface*)surface(), &clip);
if( _state == NOTACTIVE )
{
boxRGBA( (SDL_Surface*)surface(), x(), y(), x_end()-2, y_end()-2, _r, _g, _b, 255 );
rectangleRGBA( (SDL_Surface*)surface(), x(), y(), x_end()-2, y_end()-2, 0, 0, 0, 255 );
aalineRGBA( (SDL_Surface*)surface(), x() + 2, y_end() - 2, x_end(), y_end() - 2, 0, 0, 0, 255 );
aalineRGBA( (SDL_Surface*)surface(), x() + 2, y_end() - 1, x_end(), y_end() - 1, 0, 0, 0, 255 );
aalineRGBA( (SDL_Surface*)surface(), x() + 2, y_end() - 0, x_end(), y_end() - 0, 0, 0, 0, 255 );
aalineRGBA( (SDL_Surface*)surface(), x_end() - 2, y() + 2, x_end() - 2, y_end() - 2, 0, 0, 0, 255 );
aalineRGBA( (SDL_Surface*)surface(), x_end() - 1, y() + 2, x_end() - 1, y_end() - 2, 0, 0, 0, 255 );
aalineRGBA( (SDL_Surface*)surface(), x_end() - 0, y() + 2, x_end() - 0, y_end() - 2, 0, 0, 0, 255 );
}
if( _state == ACTIVE )
{
boxRGBA( (SDL_Surface*)surface(), x() + 2, y() + 2, x_end() - 2, y_end() - 2, _r, _g, _b, 255 );
rectangleRGBA( (SDL_Surface*)surface(), x() + 2, y() + 2, x_end() - 2, y_end() - 2, 0, 0, 0, 255 );
aalineRGBA( (SDL_Surface*)surface(), x(), y() + 0, x_end() - 3, y() + 0, 0, 0, 0, 255 );
aalineRGBA( (SDL_Surface*)surface(), x(), y() + 1, x_end() - 3, y() + 1, 0, 0, 0, 255 );
aalineRGBA( (SDL_Surface*)surface(), x(), y() + 2, x_end() - 3, y() + 2, 0, 0, 0, 255 );
aalineRGBA( (SDL_Surface*)surface(), x() + 0, y(), x() + 0, y_end() - 3, 0, 0, 0, 255 );
aalineRGBA( (SDL_Surface*)surface(), x() + 1, y(), x() + 1, y_end() - 3, 0, 0, 0, 255 );
aalineRGBA( (SDL_Surface*)surface(), x() + 2, y(), x() + 2, y_end() - 3, 0, 0, 0, 255 );
}
SDL_UpdateRect((SDL_Surface*)surface(), x(), y(), width(), height() );
}
| 33.358209
| 102
| 0.536913
|
cbries
|
3d5fbc8152f3d044e3385f2629cd0cc7640b2fc8
| 110
|
hpp
|
C++
|
include/lib_B/lib_B.hpp
|
dep-heaven/lib_B
|
c7b119372bfe85b8bff8a6dc42c5955a5e2b03fd
|
[
"MIT"
] | null | null | null |
include/lib_B/lib_B.hpp
|
dep-heaven/lib_B
|
c7b119372bfe85b8bff8a6dc42c5955a5e2b03fd
|
[
"MIT"
] | null | null | null |
include/lib_B/lib_B.hpp
|
dep-heaven/lib_B
|
c7b119372bfe85b8bff8a6dc42c5955a5e2b03fd
|
[
"MIT"
] | null | null | null |
#ifndef LIB_B_HPP
#define LIB_B_HPP
namespace lib_B {
int fn_b();
} // namespace lib_B
#endif // LIB_B_HPP
| 11
| 20
| 0.718182
|
dep-heaven
|
87d1f145000427ebc429b437c62dd6992a6a9d1e
| 2,299
|
cpp
|
C++
|
src/_cxx11/_semaphore.cpp
|
ombre5733/weos
|
2c3edef042fa80baa7c8fb968ba3104b7119cf2d
|
[
"BSD-2-Clause"
] | 11
|
2015-10-06T21:00:30.000Z
|
2021-07-27T05:54:44.000Z
|
src/_cxx11/_semaphore.cpp
|
ombre5733/weos
|
2c3edef042fa80baa7c8fb968ba3104b7119cf2d
|
[
"BSD-2-Clause"
] | null | null | null |
src/_cxx11/_semaphore.cpp
|
ombre5733/weos
|
2c3edef042fa80baa7c8fb968ba3104b7119cf2d
|
[
"BSD-2-Clause"
] | 1
|
2015-10-03T03:51:28.000Z
|
2015-10-03T03:51:28.000Z
|
/*******************************************************************************
WEOS - Wrapper for embedded operating systems
Copyright (c) 2013-2016, Manuel Freiberger
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
#include "_semaphore.hpp"
WEOS_BEGIN_NAMESPACE
semaphore::~semaphore()
{
}
void semaphore::post()
{
std::lock_guard<std::mutex> lock(m_mutex);
m_mutex.lock();
++m_value;
m_mutex.unlock();
m_conditionVariable.notify_one();
}
void semaphore::wait()
{
std::unique_lock<std::mutex> lock(m_mutex);
m_conditionVariable.wait(lock, [this] { return m_value != 0; });
--m_value;
}
bool semaphore::try_wait()
{
std::unique_lock<std::mutex> lock(m_mutex);
if (m_value > 0)
{
--m_value;
return true;
}
else
{
return false;
}
}
semaphore::value_type semaphore::value() const
{
std::lock_guard<std::mutex> lock(m_mutex);
return m_value;
}
WEOS_END_NAMESPACE
| 30.653333
| 80
| 0.680731
|
ombre5733
|
87d364317e653c45917da8b33c7adfcf1e21c6ab
| 10,868
|
cpp
|
C++
|
cobs/construction/compact_index.cpp
|
karasikov/cobs
|
63ba36f042c59e14f721018e68e36e20a8bf4936
|
[
"MIT"
] | null | null | null |
cobs/construction/compact_index.cpp
|
karasikov/cobs
|
63ba36f042c59e14f721018e68e36e20a8bf4936
|
[
"MIT"
] | null | null | null |
cobs/construction/compact_index.cpp
|
karasikov/cobs
|
63ba36f042c59e14f721018e68e36e20a8bf4936
|
[
"MIT"
] | null | null | null |
/*******************************************************************************
* cobs/construction/compact_index.cpp
*
* Copyright (c) 2018 Florian Gauger
*
* All rights reserved. Published under the MIT License in the LICENSE file.
******************************************************************************/
#include <cobs/construction/classic_index.hpp>
#include <cobs/construction/compact_index.hpp>
#include <cobs/file/classic_index_header.hpp>
#include <cobs/file/compact_index_header.hpp>
#include <cobs/file/kmer_buffer_header.hpp>
#include <cobs/util/calc_signature_size.hpp>
#include <cobs/util/file.hpp>
#include <iomanip>
#include <tlx/die.hpp>
#include <tlx/math/div_ceil.hpp>
#include <tlx/math/round_to_power_of_two.hpp>
#include <tlx/math/round_up.hpp>
#include <tlx/string/format_iec_units.hpp>
namespace cobs {
bool combine_classic_index(const fs::path& in_dir, const fs::path& out_dir,
size_t mem_bytes, size_t num_threads) {
bool all_combined = true;
fs::path result_file;
for (fs::directory_iterator it(in_dir), end; it != end; it++) {
if (fs::is_directory(it->path())) {
bool this_combined = classic_combine(
in_dir / it->path().filename(),
out_dir / it->path().filename(),
result_file,
mem_bytes, num_threads);
if (!this_combined)
all_combined = false;
}
}
if (!gopt_keep_temporary) {
fs::remove(in_dir);
}
return all_combined;
}
void compact_combine_into_compact(
const fs::path& in_dir, const fs::path& out_file,
uint64_t page_size, uint64_t memory)
{
std::vector<fs::path> paths;
fs::recursive_directory_iterator it(in_dir), end;
std::copy_if(it, end, std::back_inserter(paths), [](const auto& p) {
return file_has_header<ClassicIndexHeader>(p);
});
std::sort(paths.begin(), paths.end());
unsigned term_size = 0;
uint8_t canonicalize = 0;
std::vector<CompactIndexHeader::parameter> parameters;
std::vector<std::string> file_names;
LOG1 << "Combine Compact Index from " << paths.size() << " Classic Indices";
for (size_t i = 0; i < paths.size(); i++) {
auto h = deserialize_header<ClassicIndexHeader>(paths[i]);
parameters.push_back({ h.signature_size(), h.num_hashes() });
file_names.insert(file_names.end(),
h.file_names().begin(), h.file_names().end());
if (term_size == 0) {
term_size = h.term_size();
canonicalize = h.canonicalize();
}
die_unequal(term_size, h.term_size());
die_unequal(canonicalize, h.canonicalize());
LOG1 << i << ": " << h.row_bits() << " documents "
<< tlx::format_iec_units(fs::file_size(paths[i])) << 'B'
<< " row_size " << h.row_size()
<< " : " << paths[i].string();
if (i < paths.size() - 1) {
die_unless(h.row_size() == page_size);
}
else {
die_unless(h.row_size() <= page_size);
}
}
Timer t;
CompactIndexHeader h(term_size, canonicalize, parameters,
file_names, page_size);
std::ofstream ofs;
serialize_header(ofs, out_file, h);
for (const auto& p : paths) {
std::ifstream ifs;
uint64_t row_size =
deserialize_header<ClassicIndexHeader>(ifs, p).row_size();
if (row_size == page_size) {
// row_size is page_size -> direct copy
t.active("copy");
ofs << ifs.rdbuf();
t.stop();
}
else {
// row_size needs to be padded to page_size
size_t batch_size = memory / 2 / page_size;
uint64_t data_size = get_stream_size(ifs);
batch_size = std::min(
batch_size, tlx::div_ceil(data_size, page_size));
sLOG0 << "batch_size" << batch_size;
std::vector<char> buffer(batch_size* page_size);
die_unless(data_size % row_size == 0);
while (data_size > 0) {
t.active("read");
size_t this_batch = std::min(batch_size, data_size / row_size);
ifs.read(buffer.data(), this_batch * row_size);
die_unequal(this_batch * row_size,
static_cast<size_t>(ifs.gcount()));
data_size -= this_batch * row_size;
t.active("expand");
// expand each row_size to page_size, start at the back
for (size_t b = this_batch; b != 0; ) {
--b;
std::copy_backward(
buffer.begin() + b * row_size,
buffer.begin() + (b + 1) * row_size,
buffer.begin() + b * page_size + row_size);
std::fill(
buffer.begin() + b * page_size + row_size,
buffer.begin() + (b + 1) * page_size,
0);
}
t.active("write");
ofs.write(buffer.data(), this_batch * page_size);
t.stop();
}
}
ifs.close();
if (!gopt_keep_temporary) {
fs::remove(p);
fs::remove(p.parent_path());
}
}
if (!gopt_keep_temporary) {
fs::remove(in_dir);
}
t.print("compact_combine_into_compact()");
}
void compact_construct(const fs::path& in_dir, const fs::path& index_file,
const fs::path& tmp_path,
CompactIndexParameters params) {
size_t iteration = 1;
// read file list, sort by size
DocumentList doc_list(in_dir);
doc_list.sort_by_size();
if (params.page_size == 0) {
params.page_size = tlx::round_up_to_power_of_two(
static_cast<size_t>(std::sqrt(doc_list.size() / 8)));
params.page_size = std::max<uint64_t>(params.page_size, 8);
params.page_size = std::min<uint64_t>(params.page_size, 4096);
}
size_t num_pages = tlx::div_ceil(doc_list.size(), 8 * params.page_size);
size_t num_threads = params.num_threads;
if (num_threads > num_pages) {
// use div_floor() instead
num_threads = doc_list.size() / (8 * params.page_size);
}
if (num_threads == 0) num_threads = 1;
LOG1 << "Compact Index Parameters:\n"
<< " term_size: " << params.term_size << '\n'
<< " number of documents: " << doc_list.size() << '\n'
<< " num_hashes: " << params.num_hashes << '\n'
<< " false_positive_rate: " << params.false_positive_rate << '\n'
<< " page_size: " << params.page_size << " bytes"
<< " = " << params.page_size * 8 << " documents" << '\n'
<< " num_pages: " << num_pages << '\n'
<< " mem_bytes: " << params.mem_bytes
<< " = " << tlx::format_iec_units(params.mem_bytes) << 'B' << '\n'
<< " num_threads: " << num_threads;
size_t total_size = 0;
doc_list.process_batches(
8 * params.page_size,
[&](size_t /* batch_num */, const std::vector<DocumentEntry>& files,
fs::path /* out_file */) {
size_t max_doc_size = 0;
for (const DocumentEntry& de : files) {
max_doc_size = std::max(
max_doc_size, de.num_terms(params.term_size));
}
size_t signature_size = calc_signature_size(
max_doc_size, params.num_hashes, params.false_positive_rate);
total_size += params.page_size * signature_size;
});
LOG1 << " total_size: " << tlx::format_iec_units(total_size) << 'B';
// process batches and create classic indexes for each batch
doc_list.process_batches_parallel(
8 * params.page_size, num_threads,
[&](size_t batch_num, const std::vector<DocumentEntry>& files,
fs::path /* out_file */) {
size_t max_doc_size = 0;
for (const DocumentEntry& de : files) {
max_doc_size = std::max(
max_doc_size, de.num_terms(params.term_size));
}
size_t signature_size = calc_signature_size(
max_doc_size, params.num_hashes, params.false_positive_rate);
size_t docsize_roundup = tlx::round_up(files.size(), 8);
if (max_doc_size == 0)
return;
ClassicIndexParameters classic_params;
classic_params.term_size = params.term_size;
classic_params.canonicalize = params.canonicalize;
classic_params.num_hashes = params.num_hashes;
classic_params.false_positive_rate = params.false_positive_rate;
classic_params.signature_size = signature_size;
classic_params.mem_bytes = params.mem_bytes / num_threads;
classic_params.num_threads =
tlx::div_ceil(params.num_threads, num_threads);
classic_params.log_prefix
= "[" + pad_index(batch_num, 2)
+ "/" + pad_index(num_pages, 2) + "] ";
LOG1 << "Classic Sub-Index Parameters: "
<< classic_params.log_prefix << '\n'
<< " number of documents: " << files.size() << '\n'
<< " maximum document size: " << max_doc_size << '\n'
<< " signature_size: " << signature_size << '\n'
<< " sub-index size: "
<< (docsize_roundup / 8 * signature_size) << " = "
<< tlx::format_iec_units(docsize_roundup / 8 * signature_size)
<< '\n'
<< " mem_bytes: " << classic_params.mem_bytes << '\n'
<< " num_threads: " << classic_params.num_threads;
DocumentList batch_list(files);
fs::path classic_dir = tmp_path / pad_index(iteration);
classic_construct_from_documents(
batch_list, classic_dir / pad_index(batch_num), classic_params);
});
// combine classic indexes
while (!combine_classic_index(tmp_path / pad_index(iteration),
tmp_path / pad_index(iteration + 1),
params.mem_bytes, params.num_threads)) {
iteration++;
}
// combine classic indexes into one compact index
compact_combine_into_compact(
tmp_path / pad_index(iteration + 1),
index_file,
params.page_size, params.mem_bytes);
// cleanup: this will fail if not _all_ temporary files are removed
if (!gopt_keep_temporary) {
fs::remove(tmp_path);
}
}
} // namespace cobs
/******************************************************************************/
| 36.592593
| 80
| 0.544442
|
karasikov
|
87dd82ed0539a26de1a25c25eeb2fc8dda035205
| 892
|
hh
|
C++
|
dune/xt/common/python.hh
|
dune-community/dune-xt
|
da921524c6fff8d60c715cb4849a0bdd5f020d2b
|
[
"BSD-2-Clause"
] | 2
|
2020-02-08T04:08:52.000Z
|
2020-08-01T18:54:14.000Z
|
dune/xt/common/python.hh
|
dune-community/dune-xt
|
da921524c6fff8d60c715cb4849a0bdd5f020d2b
|
[
"BSD-2-Clause"
] | 35
|
2019-08-19T12:06:35.000Z
|
2020-03-27T08:20:39.000Z
|
dune/xt/common/python.hh
|
dune-community/dune-xt
|
da921524c6fff8d60c715cb4849a0bdd5f020d2b
|
[
"BSD-2-Clause"
] | 1
|
2020-02-08T04:09:34.000Z
|
2020-02-08T04:09:34.000Z
|
// This file is part of the dune-xt project:
// https://zivgitlab.uni-muenster.de/ag-ohlberger/dune-community/dune-xt
// Copyright 2009-2021 dune-xt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2019)
// René Fritze (2018 - 2020)
// Tobias Leibner (2020)
//
// Created by r_milk01 on 4/25/18.
#ifndef DUNE_XT_COMMON_PYTHON_HH
#define DUNE_XT_COMMON_PYTHON_HH
#include <functional>
#include <dune/pybindxi/pybind11.h>
namespace Dune::XT::Common::bindings {
void guarded_bind(const std::function<void()>& registrar);
} // namespace Dune::XT::Common::bindings
#endif // DUNE_XT_COMMON_PYTHON_HH
| 29.733333
| 95
| 0.719731
|
dune-community
|
87dda1ed26f9e38adf47580171f95e67e0d5d7d0
| 24,417
|
cpp
|
C++
|
src/dialman.cpp
|
taviso/mpgravity
|
f6a2a7a02014b19047e44db76ae551bd689c16ac
|
[
"BSD-3-Clause"
] | 9
|
2020-04-01T04:15:22.000Z
|
2021-09-26T21:03:47.000Z
|
src/dialman.cpp
|
taviso/mpgravity
|
f6a2a7a02014b19047e44db76ae551bd689c16ac
|
[
"BSD-3-Clause"
] | 17
|
2020-04-02T19:38:40.000Z
|
2020-04-12T05:47:08.000Z
|
src/dialman.cpp
|
taviso/mpgravity
|
f6a2a7a02014b19047e44db76ae551bd689c16ac
|
[
"BSD-3-Clause"
] | null | null | null |
/*****************************************************************************/
/* SOURCE CONTROL VERSIONS */
/*---------------------------------------------------------------------------*/
/* */
/* Version Date Time Author / Comment (optional) */
/* */
/* $Log: dialman.cpp,v $
/* Revision 1.1 2010/07/21 17:14:56 richard_wood
/* Initial checkin of V3.0.0 source code and other resources.
/* Initial code builds V3.0.0 RC1
/*
/* Revision 1.2 2009/08/25 20:04:25 richard_wood
/* Updates for 2.9.9
/*
/* Revision 1.1 2009/06/09 13:21:28 richard_wood
/* *** empty log message ***
/*
/* Revision 1.2 2008/09/19 14:51:21 richard_wood
/* Updated for VS 2005
/*
/* */
/*****************************************************************************/
/**********************************************************************************
Copyright (c) 2003, Albert M. Choy
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Microplanet, Inc. nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
**********************************************************************************/
// TDialupManager - class for managing a dialup connection for Gravity
#include "stdafx.h"
#include "mplib.h"
#include "globals.h"
#include "server.h"
#include "dialman.h"
#include "critsect.h"
#include "fileutil.h"
#include "resource.h"
#include "genutil.h" // GetOS
#include "timemb.h" // TimeMsgBox_MessageBox
#include "servcp.h" // TServerCountedPtr
#include "raserror.h" // ERROR_NO_CONNECTION
#include "rasdlg.h" // TRasDialDlg our timer redial dlg
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif
TDialupManager dialMgr; // a global
P_RASSTATUSFUNC gpfnStatus = 0;
// prototypes;
static UINT GetRasConnStateStringID( RASCONNSTATE rasconn );
static HWND hWaitDlg;
static HWND ghWndOutput = 0; // set within Connect
static UINT gmsgOutput = 0; // set within Connect
BOOL postSuccess ()
{
PostMessage (ghWndOutput, gmsgOutput, 0, 0);
return TRUE;
}
BOOL postFailure (DWORD dwError)
{
// stuff error code into wParam
PostMessage (ghWndOutput, gmsgOutput, (WPARAM) dwError, 0);
return TRUE;
}
// prototype
void WINAPI ras_process_event (UINT uMsg,
RASCONNSTATE rasconnstate,
DWORD dwError);
/////////////////////////////////////////////////////////////////////////////
// TDialupManager ctor - Construct a dialup manager for Gravity
/////////////////////////////////////////////////////////////////////////////
TDialupManager::TDialupManager()
{
m_fRasInstalled = FALSE;
m_hConnection = 0;
m_fWeCreated = FALSE;
m_fCancelled = FALSE;
m_ePseudoState = kNotConnected;
m_byRedials = 0;
m_hCriticalSection = &m_CriticalSection;
m_fAskedQuestionAlready = false;
InitializeCriticalSection (m_hCriticalSection);
}
/////////////////////////////////////////////////////////////////////////////
// loads RAS dll
/////////////////////////////////////////////////////////////////////////////
BOOL TDialupManager::Initialize ()
{
m_fRasInstalled = m_rasLib.Initialize ();
return m_fRasInstalled;
}
/////////////////////////////////////////////////////////////////////////////
// TDialupManager dtor
/////////////////////////////////////////////////////////////////////////////
TDialupManager::~TDialupManager ()
{
DeleteCriticalSection (m_hCriticalSection);
}
/////////////////////////////////////////////////////////////////////////////
// ShowRasError - Show a RAS error to the user.
/////////////////////////////////////////////////////////////////////////////
void TDialupManager::ShowRasError (bool fDuringInit, DWORD errorNum)
{
CString strIntro;
if (fDuringInit)
strIntro.LoadString (IDS_ERR_DIALUP_EST);
else
strIntro.LoadString (IDS_ERR_DIALUP_TERM);
TCHAR errorBuff[512];
CString errorString;
if (0 != m_rasLib.RasGetErrorString (errorNum,
errorBuff, sizeof (errorBuff)))
errorBuff[0] = 0;
errorString.Format ("%s - %s.", (LPCTSTR)strIntro, errorBuff);
NewsMessageBox (TGlobalDef::kMainWnd, errorString, MB_OK | MB_ICONEXCLAMATION);
}
/////////////////////////////////////////////////////////////////////////////
// Connect - Take the steps to create a dialup networking connection.
//
// Notes: 1) If ForceConnect is FALSE, then we just return true,
// since we assume that the connection has been established.
// 2) If PromptBeforeConnecting is set, we prompt before
// attempting to make the dialup connection.
// 3) If UseExistingConnection, we check to see if the
// DUN connection exists by enumerating over the current
// connections, and if found, using it. Otherwise
// we proceed to build a connection.
/////////////////////////////////////////////////////////////////////////////
BOOL TDialupManager::Connect (P_RASSTATUSFUNC pStatusFunc, HWND hWnd, UINT msg)
{
ghWndOutput = hWnd;
gmsgOutput = msg;
m_fAskedQuestionAlready = false;
TServerCountedPtr cpNewsServer; // smart pointer
// act dumb
if (!m_fRasInstalled)
{
return postSuccess ();
}
if (!IsActiveServer())
throw(new TException (IDS_ERR_NO_SERVER_SET_UP, kError));
// don't let more than one person Try to connect at once...
if (TDialupManager::kConnecting == m_ePseudoState)
{
//TRACE0("we are connecting already...\n");
return FALSE;
}
// if we're already connected, just return TRUE
const CString & strDialupName = cpNewsServer->GetConnectionName();
HRASCONN hFound = 0;
if (FindConnectionByName (kFindOurs, strDialupName, hFound))
{
//TRACE0("we are Already connected...\n");
TEnterCSection cs(m_hCriticalSection);
m_hConnection = hFound;
m_ePseudoState = kConnected;
return postSuccess ();
}
if (!cpNewsServer->GetForceConnection() && !cpNewsServer->GetForceDisconnect ())
{
// we're not responsible for any RAS work. or this is a LAN connection
return postSuccess ();
}
BOOL fRet;
// if we're not told to force a connection, then we just
// tell whoever is calling us the connection has been
// established
if (!cpNewsServer->GetForceConnection())
{
TEnterCSection ds(m_hCriticalSection);
FindConnectionByName(kFindAny, "", m_hConnection);
return postSuccess ();
}
if (strDialupName.IsEmpty())
{
// "You have not selected a dialup connection to use."
NewsMessageBox (TGlobalDef::kMainWnd, IDS_DIALUP_NOCONNECTION, MB_OK | MB_ICONSTOP);
return TRUE;
}
if (cpNewsServer->GetUseExistingConnection())
{
// iterate over the existing connections and use
// the existing one if one is there...
HRASCONN hRasConn;
if (FindConnectionByName (kFindOurs, strDialupName, hRasConn))
{
//TRACE0("Found an existing connection\n");
// we found the connection that the user specified, so
// we set that we connected and return TRUE to the user...
{
TEnterCSection cs(m_hCriticalSection);
m_hConnection = hRasConn;
}
return postSuccess ();
}
}
LPCTSTR pszConnectionName = strDialupName;
if (cpNewsServer->GetPromptBeforeConnecting())
{
CString connectionPrompt;
AfxFormatString1 (connectionPrompt, IDS_DIALUP_CONNECT1, pszConnectionName);
// "Connect to %s now?"
if (IDNO == NewsMessageBox(TGlobalDef::kMainWnd,
connectionPrompt,
MB_YESNO | MB_ICONQUESTION))
{
return FALSE;
}
}
// get to the nitty gritty
gpfnStatus = pStatusFunc;
fRet = MakeConnection (pszConnectionName);
return fRet;
}
/////////////////////////////////////////////////////////////////////////////
// Disconnect - Handle disconnecting from the dialup connection we may
// or may not have started. This is controlled by two variables
// that can be set in the server - ForceDisconnect and
// DisconnectIfWeOpened. The method will also show a prompt
// if PromptBeforeDisconnecting is set at the server.
//
// fAutoDisconnect - indicates that Gravity is disconnecting automatically.
// Don't let the MessageBoxes halt the shutdown
/////////////////////////////////////////////////////////////////////////////
BOOL TDialupManager::Disconnect(BOOL fAutoDisconnect)
{
DWORD dwRC;
TServerCountedPtr cpNewsServer; // smart pointer
//TRACE ("%s : %d, thread ID : %d\n", __FILE__, __LINE__, AfxGetThread ());
if (FALSE == m_fRasInstalled)
return TRUE;
if (!IsActiveServer ())
throw(new TException (IDS_ERR_NO_SERVER_SET_UP, kError));
if (!cpNewsServer->GetForceDisconnect())
{
// reset to clean state
set_vars_init ();
return TRUE;
}
// if they only want us to disconnect sessions we created, then return
if (cpNewsServer->GetDisconnectIfWeOpened ())
{
if (!m_fWeCreated)
{
// reset to clean state
set_vars_init ();
return TRUE;
}
}
if (kConnecting == m_ePseudoState)
{
// amc - it's valid to Try to abort a RAS session that is
// connecting. Proceed
}
else if (0 == m_hConnection)
{
set_vars_init ();
return TRUE;
}
try
{
// keep from asking the disconnect Question more than once.
// this is weird since you might get asked 3 times:
// 1) disconnect
// 2) mainfrm OnClose
// 3) ExitInstance
if (m_fAskedQuestionAlready)
{
set_vars_init ();
return FALSE;
}
if (cpNewsServer->GetPromptBeforeDisconnecting() && !m_fAskedQuestionAlready)
{
int nMsgRet;
CString promptString;
AfxFormatString1(promptString, IDS_DIALUP_ASKDISCONNECT1,
cpNewsServer->GetConnectionName ());
UINT uBoxFlags = MB_YESNO | MB_ICONQUESTION;
if (fAutoDisconnect)
{
// Timeout after 60 seconds - return IDTIMEOUT
nMsgRet = NewsMessageBoxTimeout (60, NULL, promptString, uBoxFlags);
}
else
nMsgRet = NewsMessageBox(TGlobalDef::kMainWnd, promptString, uBoxFlags);
m_fAskedQuestionAlready = true;
if (IDNO == nMsgRet)
{
set_vars_init ();
return FALSE;
}
}
}
catch(...)
{
LINE_TRACE();
throw;
}
// go ahead and close the connection....
try
{
// 2-26-98. Even if the server has dropped us,
// (FindConnectionByName==FALSE)
// call ras hangup on the m_hConnection handle. It seems to
// help ras come back to a clean initial state.
if (kConnecting == m_ePseudoState)
m_fCancelled = TRUE;
{
TEnterCSection cs(m_hCriticalSection);
dwRC = 0;
ASSERT(m_hConnection);
//TRACE0("In Disconnect() - call RasHangUp\n");
if (m_hConnection)
{
dwRC = m_rasLib.RasHangUp (m_hConnection);
}
if (0 == dwRC)
{
// wait for handle to become invalid
wait_after_hangup (m_hConnection);
// set vars to indicate cancelled
set_vars_init ();
return TRUE;
}
}
// deal with error
set_vars_init ();
// it's silly to say "Can't hang up - connection was dropped"
if (ERROR_NO_CONNECTION != dwRC)
{
ShowRasError (false, dwRC);
}
return FALSE;
}
catch(...)
{
LINE_TRACE();
throw;
}
}
// -------------------------------------------------------------------------
// set_vars_init -- reset variables to a clean state
void TDialupManager::set_vars_init()
{
TEnterCSection cs(m_hCriticalSection);
m_fWeCreated = FALSE;
m_fCancelled = FALSE;
m_hConnection = NULL;
m_ePseudoState = kNotConnected;
}
//-------------------------------------------------------------------------
// called from the dialog box
void WINAPI ras_process_event (UINT uMsg,
RASCONNSTATE rasconnstate,
DWORD dwError)
{
// wait for 1 of three cases
// dwError is not zero - An Error occurred
// RASCS_Connected -
// someone called RasHangup
if (dwError)
{
//TRACE("callback - (error) %d, %u\n", (int)rasconnstate, dwError);
// clear status line
if (gpfnStatus)
gpfnStatus ( -1 );
// both cases need to set flags to failure values
dialMgr.processEventsResult (false);
dialMgr.hangup_nowait ();
// special handling for ERROR_LINE_BUSY, pass error up, so upper layer can redial
if (ERROR_LINE_BUSY == dwError ||
ERROR_VOICE_ANSWER == dwError)
{
postFailure (dwError);
return ;
}
if (ERROR_USER_DISCONNECTION == dwError)
{
// user interrupted dialing themselves, so they don't need to see the error msg.
}
else
dialMgr.ShowRasError (true, dwError);
return;
}
if (gpfnStatus)
gpfnStatus ( GetRasConnStateStringID(rasconnstate) );
if (RASCS_DONE & rasconnstate)
{
dialMgr.processEventsResult (true); // success
postSuccess ();
}
}
/////////////////////////////////////////////////////////////////////////////
// TDialupManager::GetDialupState
//
// Returns: ECheckConnect[kNotConnected, kConnected,
// kConnecting, kNotInstalled]
//
/////////////////////////////////////////////////////////////////////////////
TDialupManager::ECheckConnect TDialupManager::GetDialupState ()
{
if (FALSE == m_fRasInstalled)
return kNotInstalled;
// don't use FindConnectionByName, use the pseudo var
return m_ePseudoState;
}
/////////////////////////////////////////////////////////////////////////////
BOOL TDialupManager::MakeConnection (LPCTSTR pConnName)
{
if (RUNNING_ON_WINNT == GetOS())
{
m_ePseudoState = kConnecting;
RASDIALDLG DlgInfo;
ZeroMemory (&DlgInfo, sizeof(DlgInfo));
DlgInfo.dwSize = sizeof(DlgInfo);
DlgInfo.hwndOwner = ghWndOutput;
// returns 0 for ERROR or if the user Canceled
BOOL fRet = m_rasLib.RasNTDialDlg (NULL, // phonebook
pConnName, // phbook entry
NULL, // override phone number
&DlgInfo);
if (fRet)
{
TEnterCSection cs(m_hCriticalSection);
FindConnectionByName (kFindOurs, pConnName, m_hConnection);
m_ePseudoState = kConnected;
m_fWeCreated = TRUE;
return postSuccess ();
}
else
{
m_ePseudoState = kNotConnected;
if (ERROR_LINE_BUSY == DlgInfo.dwError)
postFailure (DlgInfo.dwError);
return FALSE;
}
}
RASDIALPARAMS rasParms;
DWORD dwRC;
m_fCancelled = FALSE;
// get the dial parameters from the registry...
if (FALSE == get_dial_parms ( pConnName, &rasParms ))
return FALSE;
HRASCONN hConnection = NULL;
m_ePseudoState = kConnecting;
m_fWeCreated = TRUE;
RASDIALEXTENSIONS extensions;
ZeroMemory (&extensions, sizeof (extensions));
extensions.dwSize = sizeof (extensions);
extensions.dwfOptions |= RDEOPT_PausedStates;
// dialog processes events via ras_process_event (in this module)
dwRC = m_rasLib.RasDial (
&extensions, // RASDIALEXTENSIONS - we don't use them
NULL, // use the default phonebook
&rasParms, // parameters for RAS dialer
(DWORD) 0 , // treat next param as type RasDialFunc
ras_process_event, // pass in our function ptr
&hConnection);
if (dwRC)
{
if (true)
{
TEnterCSection cs(m_hCriticalSection);
hangup_and_wait ( hConnection );
m_hConnection = NULL;
}
if (m_fCancelled)
{
m_fCancelled = FALSE; // reset to clean state
}
else
ShowRasError (true, dwRC);
m_ePseudoState = kNotConnected;
m_fWeCreated = FALSE;
return FALSE;
}
else
{
TEnterCSection cs(m_hCriticalSection);
m_hConnection = hConnection;
}
return TRUE;
}
DWORD TDialupManager::RasCreatePhonebookEntry(HWND hwnd, LPTSTR pPhoneBook)
{
return m_rasLib.RasCreatePhonebookEntry(hwnd, pPhoneBook);
}
DWORD TDialupManager::RasEditPhonebookEntry(HWND hwnd, LPTSTR pPhoneBook, LPTSTR entry)
{
return m_rasLib.RasEditPhonebookEntry(hwnd, pPhoneBook, entry);
}
DWORD TDialupManager::RasEnumEntries(LPTSTR r1, LPTSTR pPhoneBook, LPRASENTRYNAME pEntry,
LPDWORD lpcb, LPDWORD lpcEntries)
{
return m_rasLib.RasEnumEntries(r1, pPhoneBook, pEntry, lpcb, lpcEntries);
}
DWORD
TDialupManager::RasGetEntryDialParams(LPTSTR pPhoneBook,
LPRASDIALPARAMS pDialParams,
LPBOOL pfPassword)
{
return m_rasLib.RasGetEntryDialParams(pPhoneBook, pDialParams, pfPassword);
}
DWORD
TDialupManager::RasSetEntryDialParams(LPTSTR pBook,
LPRASDIALPARAMS pDP,
BOOL fRemovePwd)
{
return m_rasLib.RasSetEntryDialParams(pBook, pDP, fRemovePwd);
}
//-------------------------------------------------------------------------
void TDialupManager::wait_after_hangup (HRASCONN hConnection)
{
RASCONNSTATUS rasStatus;
DWORD dwRC;
CTime start = CTime::GetCurrentTime();
do
{
ZeroMemory (&rasStatus, sizeof(rasStatus));
rasStatus.dwSize = sizeof(rasStatus);
dwRC = m_rasLib.RasGetConnectStatus (hConnection, &rasStatus);
if (ERROR_INVALID_HANDLE == dwRC)
break;
Sleep (0);
} while ((CTime::GetCurrentTime() - start).GetSeconds() < 15);
}
//-------------------------------------------------------------------------
BOOL TDialupManager::get_dial_parms (LPCTSTR pConnName,
RASDIALPARAMS* prasParms)
{
BOOL fPassword = FALSE;
DWORD dwRC;
ZeroMemory (prasParms, sizeof(RASDIALPARAMS));
prasParms->dwSize = sizeof(RASDIALPARAMS);
if (sizeof(*prasParms) != sizeof(RASDIALPARAMS))
AfxThrowMemoryException();
_tcscpy(prasParms->szEntryName, pConnName);
dwRC = m_rasLib.RasGetEntryDialParams(
NULL, // use default phonebook
prasParms, // pointer to parameters
&fPassword); // was password returned?
if (0 != dwRC)
{
// "Error retrieving dialup networking parameters."
NewsMessageBox (TGlobalDef::kMainWnd, IDS_DIALUP_ERRGETDIALPARAMS, MB_OK | MB_ICONSTOP);
return FALSE;
}
return TRUE;
}
// ------------------------------------------------------------------------
// PURPOSE: get the index to the corresponding string
//
// PARAMETERS:
// rasconn - ras connection state
//
// RETURNS:
// index into stringtable.
static UINT GetRasConnStateStringID( RASCONNSTATE rasconn )
{
switch( rasconn )
{
case RASCS_OpenPort:
return IDS_OPENPORT;
case RASCS_PortOpened:
return IDS_PORTOPENED;
case RASCS_ConnectDevice:
return IDS_CONNECTDEVICE;
case RASCS_DeviceConnected:
return IDS_DEVICECONNECTED;
case RASCS_AllDevicesConnected:
return IDS_ALLDEVICESCONNECTED;
case RASCS_Authenticate:
return IDS_AUTHENTICATE;
case RASCS_AuthNotify:
return IDS_AUTHNOTIFY;
case RASCS_AuthRetry:
return IDS_AUTHRETRY;
case RASCS_AuthCallback:
return IDS_AUTHCALLBACK;
case RASCS_AuthChangePassword:
return IDS_AUTHCHANGEPASSWORD;
case RASCS_AuthProject:
return IDS_AUTHPROJECT;
case RASCS_AuthLinkSpeed:
return IDS_AUTHLINKSPEED;
case RASCS_AuthAck:
return IDS_AUTHACK;
case RASCS_ReAuthenticate:
return IDS_REAUTHENTICATE;
case RASCS_Authenticated:
return IDS_AUTHENTICATED;
case RASCS_PrepareForCallback:
return IDS_PREPAREFORCALLBACK;
case RASCS_WaitForModemReset:
return IDS_WAITFORMODEMRESET;
case RASCS_WaitForCallback:
return IDS_WAITFORCALLBACK;
case RASCS_StartAuthentication:
return IDS_STARTAUTH;
case RASCS_CallbackComplete:
return IDS_CALLBACK_COMPLETE;
case RASCS_LogonNetwork:
return IDS_LOGON_NETWORK;
case RASCS_SubEntryConnected:
return IDS_SUBENTRYCONNECTED;
case RASCS_Interactive:
return IDS_INTERACTIVE;
case RASCS_RetryAuthentication:
return IDS_RETRYAUTHENTICATION;
case RASCS_CallbackSetByCaller:
return IDS_CALLBACKSETBYCALLER;
case RASCS_PasswordExpired:
return IDS_PASSWORDEXPIRED;
case RASCS_Connected:
return IDS_CONNECTED;
case RASCS_Disconnected:
return IDS_DISCONNECTED;
default:
return IDS_RAS_UNDEFINED_ERROR;
}
}
//-------------------------------------------------------------------------
void TDialupManager::hangup_and_wait (HRASCONN hConnection)
{
if (hConnection)
{
m_rasLib.RasHangUp ( hConnection );
wait_after_hangup ( hConnection );
}
}
/////////////////////////////////////////////////////////////////////////////
// FindConnectionByName - Locate a connection (in the set of current
// connections) by name
/////////////////////////////////////////////////////////////////////////////
BOOL TDialupManager::FindConnectionByName(
EFindConn eFind,
const CString & dialupName,
HRASCONN & hConnection)
{
RASCONN connections[10]; // assume there are not more than 10 ras conns
DWORD cbSize;
DWORD numConnections;
DWORD dwRC;
cbSize = sizeof (connections);
connections[0].dwSize = sizeof (RASCONN);
dwRC = m_rasLib.RasEnumConnections (connections,
&cbSize,
&numConnections);
if (0 == dwRC)
{
for (int i = 0; i < int(numConnections); i++)
{
if (eFind == kFindOurs)
{
if (dialupName.CompareNoCase(connections[i].szEntryName) == 0)
{
hConnection = connections[i].hrasconn;
return TRUE;
}
}
else // kFindAny
{
hConnection = connections[i].hrasconn;
return TRUE;
}
}
}
hConnection = NULL;
return FALSE;
}
/////////////////////////////////////////////////////////////////////////////
void TDialupManager::processEventsResult (bool fSuccess)
{
if (fSuccess)
{
m_ePseudoState = kConnected ;
m_byRedials = 0;
}
else
{
m_ePseudoState = kNotConnected;
}
}
/////////////////////////////////////////////////////////////////////////////
void TDialupManager::hangup_nowait ()
{
TEnterCSection cs(m_hCriticalSection);
if (m_hConnection)
{
// we are not hanging up a Valid connection, more like freeing the
// memory for this handle
// come here if we get a busy signal
m_rasLib.RasHangUp (m_hConnection);
m_hConnection = 0;
}
}
// returns true to redial
bool TDialupManager::incrementRedialCount (bool fResetToZero)
{
BYTE n = m_byRedials + 1;
if (n > 4 || fResetToZero)
{
// over the limit
m_byRedials = 0;
return false;
}
else
{
m_byRedials = n;
return true;
}
}
// ------------------------------------------------------------------------
// Returns true for "ok to redial"
bool TDialupManager::ShowRedialDlg (CWnd * pAnchor)
{
TRasDialDlg sDlg(pAnchor);
sDlg.DoModal();
return sDlg.getAnswer();
}
| 27.009956
| 91
| 0.60507
|
taviso
|
87ddf5a2e5a3747713708066b0d4f8f8c710746c
| 3,835
|
cpp
|
C++
|
VGP242/06_HelloTexturing/GameState.cpp
|
TheJimmyGod/JimmyGod_Engine
|
b9752c6fbd9db17dc23f03330b5e4537bdcadf8e
|
[
"MIT"
] | null | null | null |
VGP242/06_HelloTexturing/GameState.cpp
|
TheJimmyGod/JimmyGod_Engine
|
b9752c6fbd9db17dc23f03330b5e4537bdcadf8e
|
[
"MIT"
] | null | null | null |
VGP242/06_HelloTexturing/GameState.cpp
|
TheJimmyGod/JimmyGod_Engine
|
b9752c6fbd9db17dc23f03330b5e4537bdcadf8e
|
[
"MIT"
] | null | null | null |
#include "GameState.h"
using namespace JimmyGod::Input;
using namespace JimmyGod::Graphics;
using namespace JimmyGod::Math;
void GameState::Initialize()
{
GraphicsSystem::Get()->SetClearColor(Colors::Black);
mCamera.SetPosition({ 0.0f,0.0f,-5.0f });
mCamera.SetDirection({ 0.0f,0.0f,1.0f });
/* Homework
Update helloTexturing to use a MeshPX data to draw a texture mapped cubes
You will need to add Sampler and Texture classes provided
You will need to use DoTexturing fx shaders
Add a new class called Graphics::MeshBuilder with the following functions
namespace JimmyGod::Graphics
{
class MeshBuilder
{
static MeshPX CreatePlanePX();
static MeshPX CreateCylinderPX();
static MeshPX CreateSpherePX(float radius, int ringhs = 16, int slices = 16);
}
This will allow you to create a mesh easily by doing:
auto mesh = MeshBuilder::CreateSpherePX(...);
Add HelloEarth to test a texture mapped sphere using Earth texture
a plane:
for(int y=0; y< height; ++y)
for(int x=0; x<width; ++x)
mMesh.push_back({x,y,0.0f}...);
a cylinder:
for(int y=0; y< height; ++y)
for(int theta=0; theta<TwoPi; theta += ...)
mMesh.push_back({sin(theta),y,cos(theta)}...);
a sphere:
for(int phi=0; phi< Pi; phi += ...)
for(int theta=0; theta<TwoPi; theta += ...)
mMesh.push_back({sin(theta) * r,phi,cos(theta) *r}...);
}*/
auto Mesh = MeshBuilder::CreateCubePX();
auto Plane = MeshBuilder::CreatePlanePX(2,2);
auto Cylinder = MeshBuilder::CreateCylinderPX(36, 36);
auto Sphere = MeshBuilder::CreateSpherePX(10);
mMeshBuffer.Initialize(Plane);
mConstantBuffer.Initialize(sizeof(Matrix4));
mSampler.Initialize(Sampler::Filter::Point, Sampler::AddressMode::Clamp);
mTexture.Initialize("../../Assets/Textures/SimYoung.jpg");
// Compile and create vertex shader
mVertexShader.Initialize("../../Assets/Shaders/DoTexturing.fx",VertexPX::Format);
// Compile and create pixel shader
mPixelShader.Initialize("../../Assets/Shaders/DoTexturing.fx");
}
void GameState::Terminate()
{
mVertexShader.Terminate();
mPixelShader.Terminate();
mMeshBuffer.Terminate();
mConstantBuffer.Terminate();
mTexture.Terminate();
mSampler.Terminate();
}
void GameState::Update(float deltaTime)
{
const float kMoveSpeed = 7.5f;
const float kTurnSpeed = 0.5f;
auto inputSystem = InputSystem::Get();
if (inputSystem->IsKeyDown(KeyCode::W))
{
mCamera.Walk(kMoveSpeed*deltaTime);
}
if (inputSystem->IsKeyDown(KeyCode::S))
{
mCamera.Walk(-kMoveSpeed * deltaTime);
}
mCamera.Yaw(inputSystem->GetMouseMoveX() * kTurnSpeed * deltaTime);
mCamera.Pitch(inputSystem->GetMouseMoveY() * kTurnSpeed * deltaTime);
if (inputSystem->IsKeyDown(KeyCode::A))
{
mRotation += deltaTime;
}
if (inputSystem->IsKeyDown(KeyCode::D))
{
mRotation -= deltaTime;
}
}
void GameState::Render()
{
auto matView = mCamera.GetViewMatrix();
auto matProj = mCamera.GetPerspectiveMatrix();
mVertexShader.Bind();
mPixelShader.Bind();
mConstantBuffer.BindVS(0);
mSampler.BindPS();
mTexture.BindPS();
for (int i = 0; i < 2; i++)
{
auto matWorld1 = Matrix4::RotationY(mRotation.y);
//auto matWorld2 = Matrix4::RotationX(mRotation.x- static_cast<float>(i));
//auto matWorld3 = Matrix4::RotationZ(mRotation.z+ static_cast<float>(i));
auto matTranslation = Matrix4::Identity;// Matrix4::Translation(Vector3(static_cast<float>(i), static_cast<float>(i), static_cast<float>(0)));
auto matScl = Matrix4::Scaling(static_cast<float>(i) * 0.25f);
auto matWVP = Transpose(matScl*matTranslation*matWorld1 * matView * matProj);
mConstantBuffer.Update(&matWVP);
mMeshBuffer.Draw();
}
/*context->Draw(mVertices.size(), 0);*/ // This is for when we don't have an index buffer
}
| 30.19685
| 145
| 0.690743
|
TheJimmyGod
|
87e0ec19e6f60dc42bcc6fa3a417c0796aee134d
| 1,187
|
hpp
|
C++
|
include/codegen/include/GlobalNamespace/BeatmapEventData.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 1
|
2021-11-12T09:29:31.000Z
|
2021-11-12T09:29:31.000Z
|
include/codegen/include/GlobalNamespace/BeatmapEventData.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | null | null | null |
include/codegen/include/GlobalNamespace/BeatmapEventData.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 2
|
2021-10-03T02:14:20.000Z
|
2021-11-12T09:29:36.000Z
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: BeatmapEventType
#include "GlobalNamespace/BeatmapEventType.hpp"
// Completed includes
// Type namespace:
namespace GlobalNamespace {
// Autogenerated type: BeatmapEventData
class BeatmapEventData : public ::Il2CppObject {
public:
// public readonly BeatmapEventType type
// Offset: 0x10
GlobalNamespace::BeatmapEventType type;
// public readonly System.Single time
// Offset: 0x14
float time;
// public readonly System.Int32 value
// Offset: 0x18
int value;
// public System.Void .ctor(System.Single time, BeatmapEventType type, System.Int32 value)
// Offset: 0xB8D16C
static BeatmapEventData* New_ctor(float time, GlobalNamespace::BeatmapEventType type, int value);
}; // BeatmapEventData
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::BeatmapEventData*, "", "BeatmapEventData");
#pragma pack(pop)
| 35.969697
| 101
| 0.699242
|
Futuremappermydud
|
87e24f9b179db7cf817f62262a028bed3a77134d
| 3,987
|
hpp
|
C++
|
src/main/cpp/USSL/BasicArithmatic.hpp
|
Crtl-F5/F5RC-Kernel
|
145cf9f7a34463226e68112033f56e0d121425e3
|
[
"MIT"
] | 1
|
2018-08-12T03:50:19.000Z
|
2018-08-12T03:50:19.000Z
|
src/main/cpp/USSL/BasicArithmatic.hpp
|
Crtl-F5/F5RC-Kernel
|
145cf9f7a34463226e68112033f56e0d121425e3
|
[
"MIT"
] | null | null | null |
src/main/cpp/USSL/BasicArithmatic.hpp
|
Crtl-F5/F5RC-Kernel
|
145cf9f7a34463226e68112033f56e0d121425e3
|
[
"MIT"
] | null | null | null |
#pragma once
#include <ProgramType.hpp>
namespace USSL
{
inline void ADD(ProgramType* args, unsigned char* programMemory)
{
switch (args[0].type)
{
case b: *((signed char*)programMemory + args[0].data.i) = args[1].data.b + args[2].data.b; break;
case s: *((signed short*)programMemory + args[0].data.i) = args[1].data.s + args[2].data.s; break;
case i: *((signed long*)programMemory + args[0].data.i) = args[1].data.i + args[2].data.i; break;
case l: *((signed long long*)programMemory + args[0].data.i) = args[1].data.l + args[2].data.l; break;
case f: *((float*)programMemory + args[0].data.i) = args[1].data.f + args[2].data.f; break;
case d: *((double*)programMemory + args[0].data.i) = args[1].data.d + args[2].data.d; break;
}
}
inline void SUB((ProgramType* args, unsigned char* programMemory)
{
switch (args[0].type)
{
case b: *((signed char*)programMemory + args[0].data.i) = args[1].data.b - args[2].data.b; break;
case s: *((signed short*)programMemory + args[0].data.i) = args[1].data.s - args[2].data.s; break;
case i: *((signed long*)programMemory + args[0].data.i) = args[1].data.i - args[2].data.i; break;
case l: *((signed long long*)programMemory + args[0].data.i) = args[1].data.l - args[2].data.l; break;
case f: *((float*)programMemory + args[0].data.i) = args[1].data.f - args[2].data.f; break;
case d: *((double*)programMemory + args[0].data.i) = args[1].data.d - args[2].data.d; break;
}
}
inline void MUL(ProgramType* args, unsigned char* programMemory)
{
switch (args[0].type)
{
case b: *((signed char*)programMemory + args[0].data.i) = args[1].data.b * args[2].data.b; break;
case s: *((signed short*)programMemory + args[0].data.i) = args[1].data.s * args[2].data.s; break;
case i: *((signed long*)programMemory + args[0].data.i) = args[1].data.i * args[2].data.i; break;
case l: *((signed long long*)programMemory + args[0].data.i) = args[1].data.l * args[2].data.l; break;
case f: *((float*)programMemory + args[0].data.i) = args[1].data.f * args[2].data.f; break;
case d: *((double*)programMemory + args[0].data.i) = args[1].data.d * args[2].data.d; break;
}
}
inline void DIV(ProgramType* args, unsigned char* programMemory)
{
switch (args[0].type)
{
case b: *((signed char*)programMemory + args[0].data.i) = args[1].data.b / args[2].data.b; break;
case s: *((signed short*)programMemory + args[0].data.i) = args[1].data.s / args[2].data.s; break;
case i: *((signed long*)programMemory + args[0].data.i) = args[1].data.i / args[2].data.i; break;
case l: *((signed long long*)programMemory + args[0].data.i) = args[1].data.l / args[2].data.l; break;
case f: *((float*)programMemory + args[0].data.i) = args[1].data.f / args[2].data.f; break;
case d: *((double*)programMemory + args[0].data.i) = args[1].data.d / args[2].data.d; break;
}
}
inline void MOD(ProgramType* args, unsigned char* memory)
{
switch (args[0].type)
{
case b: *((signed char*)programMemory + args[0].data.i) = args[1].data.b % args[2].data.b; break;
case s: *((signed short*)programMemory + args[0].data.i) = args[1].data.s % args[2].data.s; break;
case i: *((signed long*)programMemory + args[0].data.i) = args[1].data.i % args[2].data.i; break;
case l: *((signed long long*)programMemory + args[0].data.i) = args[1].data.l % args[2].data.l; break;
case f: *((float*)programMemory + args[0].data.i) = args[1].data.f % args[2].data.f; break;
case d: *((double*)programMemory + args[0].data.i) = args[1].data.d % args[2].data.d; break;
}
}
}
| 56.957143
| 114
| 0.563582
|
Crtl-F5
|
87e7683708abea0b9a5cf4c0ecbae75ffdf6184e
| 1,582
|
cpp
|
C++
|
acmicpc/16235.cpp
|
juseongkr/BOJ
|
8f10a2bf9a7d695455493fbe7423347a8b648416
|
[
"Apache-2.0"
] | 7
|
2020-02-03T10:00:19.000Z
|
2021-11-16T11:03:57.000Z
|
acmicpc/16235.cpp
|
juseongkr/Algorithm-training
|
8f10a2bf9a7d695455493fbe7423347a8b648416
|
[
"Apache-2.0"
] | 1
|
2021-01-03T06:58:24.000Z
|
2021-01-03T06:58:24.000Z
|
acmicpc/16235.cpp
|
juseongkr/Algorithm-training
|
8f10a2bf9a7d695455493fbe7423347a8b648416
|
[
"Apache-2.0"
] | 1
|
2020-01-22T14:34:03.000Z
|
2020-01-22T14:34:03.000Z
|
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
using namespace std;
#define MAX 11
const int dx[8] = {-1, -1, -1, 0, 0, 1, 1, 1};
const int dy[8] = {-1, 0, 1, -1, 1, -1, 0, 1};
int n, m, k, x, y, z;
int map[MAX][MAX], nou[MAX][MAX], new_tree[MAX][MAX];
bool visit[MAX][MAX];
vector<int> tree[MAX][MAX];
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n >> m >> k;
for (int i=0; i<n; ++i) {
for (int j=0; j<n; ++j) {
cin >> map[i][j];
nou[i][j] = 5;
}
}
for (int i=0; i<m; ++i) {
cin >> x >> y >> z;
tree[x-1][y-1].push_back(z);
}
while (k--) {
memset(new_tree, 0, sizeof(new_tree));
for (int i=0; i<n; ++i) {
for (int j=0; j<n; ++j) {
sort(tree[i][j].begin(), tree[i][j].end());
vector<int> t;
int dead = 0;
for (int s=0; s<tree[i][j].size(); ++s) {
int cur = tree[i][j][s];
if (cur <= nou[i][j]) {
t.push_back(cur+1);
nou[i][j] -= cur;
if ((cur+1) % 5 != 0)
continue;
for (int p=0; p<8; ++p) {
int nx = i + dx[p];
int ny = j + dy[p];
if (nx < 0 || ny < 0 || nx >= n || ny >= n)
continue;
new_tree[nx][ny] += 1;
}
} else {
dead += cur/2;
}
}
nou[i][j] += (dead + map[i][j]);
tree[i][j] = t;
}
}
for (int i=0; i<n; ++i)
for (int j=0; j<n; ++j)
for (int k=0; k<new_tree[i][j]; ++k)
tree[i][j].push_back(1);
}
int ans = 0;
for (int i=0; i<n; ++i)
for (int j=0; j<n; ++j)
ans += tree[i][j].size();
cout << ans << '\n';
return 0;
}
| 19.530864
| 53
| 0.453224
|
juseongkr
|
87e9cd99ee6892015e96a6141a5649aad854bde2
| 1,580
|
cpp
|
C++
|
libnativeipc/src/ConnectionFactory.cpp
|
stream-labs/twitch-native-ipc
|
81154497fcf55288c51cb5c93e95014ec4f0644d
|
[
"MIT"
] | 8
|
2020-10-12T21:44:47.000Z
|
2021-07-29T16:58:41.000Z
|
libnativeipc/src/ConnectionFactory.cpp
|
ConnectionMaster/twitch-native-ipc
|
81154497fcf55288c51cb5c93e95014ec4f0644d
|
[
"MIT"
] | 1
|
2021-08-28T03:11:34.000Z
|
2021-08-28T03:11:34.000Z
|
libnativeipc/src/ConnectionFactory.cpp
|
ConnectionMaster/twitch-native-ipc
|
81154497fcf55288c51cb5c93e95014ec4f0644d
|
[
"MIT"
] | 3
|
2020-10-02T17:34:57.000Z
|
2021-08-28T03:11:23.000Z
|
// Copyright Twitch Interactive, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT
#include "ClientConnection.h"
#include "ConnectionFactoryPrivate.h"
#include "Pipe-ClientTransport.h"
#include "Pipe-ServerTransport.h"
#include "TCP-ClientTransport.h"
#include "TCP-ServerTransport.h"
#include "ServerConnection.h"
#include "ServerConnectionSingle.h"
using namespace Twitch::IPC;
namespace {
std::string pipeNameForEndpoint(const std::string &endpoint)
{
#ifdef _WIN32
return R"(\\.\pipe\)" + endpoint;
#else
return "/tmp/" + endpoint;
#endif
}
} // namespace
namespace Twitch::IPC::ConnectionFactory {
NATIVEIPC_LIBSPEC std::unique_ptr<IConnection> newServerConnection(const std::string &endpoint, bool allowMultiuserAccess)
{
return std::unique_ptr<IConnection>(std::make_unique<ServerConnectionSingle>(
MakeFactory<Transport::Pipe>(), pipeNameForEndpoint(endpoint), allowMultiuserAccess));
}
NATIVEIPC_LIBSPEC std::unique_ptr<IConnection> newClientConnection(
const std::string &endpoint)
{
return std::unique_ptr<IConnection>(std::make_unique<ClientConnection>(
MakeFactory<Transport::Pipe>(), pipeNameForEndpoint(endpoint)));
}
NATIVEIPC_LIBSPEC std::unique_ptr<IServerConnection> newMulticonnectServerConnection(const std::string &endpoint, bool allowMultiuserAccess)
{
return std::unique_ptr<IServerConnection>(std::make_unique<ServerConnection>(
MakeFactory<Transport::Pipe>(), pipeNameForEndpoint(endpoint), false, allowMultiuserAccess));
}
} // namespace Twitch::IPC::ConnectionFactory
| 32.244898
| 140
| 0.772152
|
stream-labs
|
87eeb246a6f0325edcc78761210938ddb9930ff2
| 516
|
cc
|
C++
|
ChiTech/ChiMesh/Region/chi_region.cc
|
Jrgriss2/chi-tech
|
db75df761d5f25ca4b79ee19d36f886ef240c2b5
|
[
"MIT"
] | 7
|
2019-09-10T12:16:08.000Z
|
2021-05-06T16:01:59.000Z
|
ChiTech/ChiMesh/Region/chi_region.cc
|
Jrgriss2/chi-tech
|
db75df761d5f25ca4b79ee19d36f886ef240c2b5
|
[
"MIT"
] | 72
|
2019-09-04T15:00:25.000Z
|
2021-12-02T20:47:29.000Z
|
ChiTech/ChiMesh/Region/chi_region.cc
|
Jrgriss2/chi-tech
|
db75df761d5f25ca4b79ee19d36f886ef240c2b5
|
[
"MIT"
] | 41
|
2019-09-02T15:33:31.000Z
|
2022-02-10T13:26:49.000Z
|
#include "chi_region.h"
#include "chi_log.h"
extern ChiLog& chi_log;
//###################################################################
/** Obtains the latest created grid from the region.*/
chi_mesh::MeshContinuumPtr chi_mesh::Region::GetGrid()
{
if (this->volume_mesh_continua.empty())
{
chi_log.Log(LOG_ALLERROR)
<< "Region: Grid retrieval failed. Verify that volume mesher"
" has executed for this region.";
exit(EXIT_FAILURE);
} else
return volume_mesh_continua.back();
}
| 25.8
| 69
| 0.602713
|
Jrgriss2
|
87efcf503e4fdf4c4251b35612961e906b8b0b90
| 1,361
|
cpp
|
C++
|
TP/starters 12/maxpoint.cpp
|
ShyrenMore/DSA_Docs
|
7d489326799886afd8d5f7ec7f4b88311e86e582
|
[
"Unlicense"
] | null | null | null |
TP/starters 12/maxpoint.cpp
|
ShyrenMore/DSA_Docs
|
7d489326799886afd8d5f7ec7f4b88311e86e582
|
[
"Unlicense"
] | null | null | null |
TP/starters 12/maxpoint.cpp
|
ShyrenMore/DSA_Docs
|
7d489326799886afd8d5f7ec7f4b88311e86e582
|
[
"Unlicense"
] | null | null | null |
#include <bits/stdc++.h>
#define deb(x) cout << #x << ": " << x << endl;
#define deb2(x, y) cout << #x << ": " << x << " ~ " << #y << ": " << y << endl;
#define in(n, arr) \
for (int i = 0; i < n; i++) \
cin >> arr[i]
#define out(n, arr) \
for (int i = 0; i < n; i++) \
cout << arr[i]
#define lli long long int
#define here cout << "\nHERE\n"
#pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
using namespace std;
int main()
{
// /*
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
// */
ios_base::sync_with_stdio(false);
cin.tie(0);
int t;
cin >> t;
while (t--)
{
int A, B, C, X, Y, Z;
cin >> A >> B >> C >> X >> Y >> Z;
int ans = 0;
for (int take_a = 0; take_a <= 20; take_a++)
{
for (int take_b = 0; take_b <= 20; take_b++)
{
for (int take_c = 0; take_c <= 20; take_c++)
{
int time = take_a * A + take_b * B + take_c * C;
if (time <= 240)
{
ans = max(ans, take_a * X + take_b * Y + take_c * Z);
}
}
}
}
cout << ans << "\n";
}
return 0;
}
| 24.745455
| 79
| 0.404849
|
ShyrenMore
|
87f3b27586d6ffea1b2d3b216f9bea13a9ef1fad
| 12,602
|
cpp
|
C++
|
game_server/test/misc_test.cpp
|
CellWarsOfficial/CellWars
|
40b1e956c871ee686062eba1251a9f9a43d86c2c
|
[
"Apache-2.0"
] | 5
|
2017-07-20T10:36:23.000Z
|
2018-01-30T16:18:31.000Z
|
game_server/test/misc_test.cpp
|
CellWarsOfficial/CellWars
|
40b1e956c871ee686062eba1251a9f9a43d86c2c
|
[
"Apache-2.0"
] | null | null | null |
game_server/test/misc_test.cpp
|
CellWarsOfficial/CellWars
|
40b1e956c871ee686062eba1251a9f9a43d86c2c
|
[
"Apache-2.0"
] | null | null | null |
#include "misc_test.hpp"
#include <cstring>
#include <cstdio>
#include <cinttypes>
#include <constants.hpp>
using namespace std;
int fails = 0;
int tests = 0;
int math_tests()
{
fails = 0;
tests = 0;
// TODO tests go here
//test binary_to_num
string test1 = "1101";
string test2 = "00001101";
string test3 = "11000011010011111";
string test4 = "0000100110011010";
string test5 = "100110011010";
unsigned long test6 = 70;
unsigned long test7 = 63;
unsigned long test8 = 0;
unsigned long test9 = 7;
unsigned long test10 = 8;
string test11 = "000000111";
string test12 = "000000111111";
string test13 = "0010000";
string test14 = "000100000";
string test15 = "000100001";
string test16 = "Mihai";
string test17 = "journey";
string test18 = "persona";
string test19 = "car";
string test20 = "cat";
string test21 = "";
tests++;
if(13 != binary_to_num(test1)){
fprintf(stderr, "TEST FAIL: binary_to_num.\n");
fails++;
}
tests++;
if(13 != binary_to_num(test2)){
fprintf(stderr, "TEST FAIL: binary_to_num.\n");
fails++;
}
tests++;
if(99999 != binary_to_num(test3)){
fprintf(stderr, "TEST FAIL: binary_to_num.\n");
fails++;
}
tests++;
if(2458 != binary_to_num(test4)){
fprintf(stderr, "TEST FAIL: binary_to_num.\n");
fails++;
}
tests++;
if(2458 != binary_to_num(test5)){
fprintf(stderr, "TEST FAIL: binary_to_num.\n");
fails++;
}
//test num_to_binary
tests++;
if(!str_eq("01000110", num_to_binary(test6))){
fprintf(stderr, "TEST FAIL: num_to_binary.\n");
string s = num_to_binary(test6);
printf("HERE:%s\n", s.c_str());
fails++;
}
tests++;
if(!str_eq("00111111", num_to_binary(test7))){
fprintf(stderr, "TEST FAIL: num_to_binary.\n");
fails++;
}
tests++;
if(!str_eq("00000000", num_to_binary(test8))){
fprintf(stderr, "TEST FAIL: num_to_binary.\n");
fails++;
}
tests++;
if(!str_eq("00000111", num_to_binary(test9))){
fprintf(stderr, "TEST FAIL: num_to_binary.\n");
fails++;
}
tests++;
if(!str_eq("00001000", num_to_binary(test10))){
fprintf(stderr, "TEST FAIL: num_to_binary.\n");
fails++;
}
//test encode_six_bits
tests++;
if(7 != encode_six_bits(test11, 3)){
fprintf(stderr, "TEST FAIL: encode_six_bits.\n");
fails++;
}
tests++;
if(7 != encode_six_bits(test12, 3)){
fprintf(stderr, "TEST FAIL: encode_six_bits.\n");
fails++;
}
tests++;
if(16 != encode_six_bits(test13, 1)){
fprintf(stderr, "TEST FAIL: encode_six_bits.\n");
fails++;
}
tests++;
if(32 != encode_six_bits(test14, 3)){
fprintf(stderr, "TEST FAIL: encode_six_bits.\n");
fails++;
}
tests++;
if(33 != encode_six_bits(test15, 3)){
fprintf(stderr, "TEST FAIL: encode_six_bits.\n");
fails++;
}
tests++;
if(!str_eq("TWloYWk=", encode_base64((unsigned char *) test16.c_str(), test16.length()))){
printf("OUT: %s\n", (encode_base64((unsigned char *) test16.c_str(), test16.length()).c_str()));
fprintf(stderr, "TEST FAIL: encode_base64.\n");
fails++;
}
tests++;
if(!str_eq("am91cm5leQ==", encode_base64((unsigned char *) test17.c_str(), test17.length()))){
printf("OUT: %s\n", (encode_base64((unsigned char *) test17.c_str(), test17.length()).c_str()));
fprintf(stderr, "TEST FAIL: encode_base64.\n");
fails++;
}
tests++;
if(!str_eq("cGVyc29uYQ==", encode_base64((unsigned char *) test18.c_str(), test18.length()))){
printf("OUT: %s\n", (encode_base64((unsigned char *) test18.c_str(), test18.length()).c_str()));
fprintf(stderr, "TEST FAIL: encode_base64.\n");
fails++;
}
tests++;
if(!str_eq("Y2Fy", encode_base64((unsigned char *) test19.c_str(), test19.length()))){
printf("OUT: %s\n", (encode_base64((unsigned char *) test19.c_str(), test19.length()).c_str()));
fprintf(stderr, "TEST FAIL: encode_base64.\n");
fails++;
}
tests++;
if(!str_eq("Y2F0", encode_base64((unsigned char *) test20.c_str(), test20.length()))){
printf("OUT: %s\n", (encode_base64((unsigned char *) test20.c_str(), test20.length()).c_str()));
fprintf(stderr, "TEST FAIL: encode_base64.\n");
fails++;
}
tests++;
if(!str_eq("", encode_base64((unsigned char *) test21.c_str(), test21.length()))){
printf("OUT: %s\n", (encode_base64((unsigned char *) test21.c_str(), test21.length()).c_str()));
fprintf(stderr, "TEST FAIL: encode_base64.\n");
fails++;
}
//test encode_base64.
fprintf(stderr, "%d/%d tests passed - math\n", tests - fails, tests);
return fails;
}
int strings_tests()
{
fails = 0;
tests = 0;
// in tests
tests++;
if(!in(' ', STR_WHITE)){fails++; fprintf(stderr, "In failing long\n");}
tests++;
if(!in('\f', STR_WHITE)){fails++; fprintf(stderr, "In failing long\n");}
tests++;
if(!in('\n', STR_WHITE)){fails++; fprintf(stderr, "In failing long\n");}
tests++;
if(!in('\r', STR_WHITE)){fails++; fprintf(stderr, "In failing long\n");}
tests++;
if(!in('\t', STR_WHITE)){fails++; fprintf(stderr, "In failing long\n");}
tests++;
if(!in('\v', STR_WHITE)){fails++; fprintf(stderr, "In failing\n");}
tests++;
if(in(' ', "")){fails++; fprintf(stderr, "In failing empty\n");}
tests++;
if(in(' ', "asdefaersdvkdjlvc")){fails++; fprintf(stderr, "In failing not\n");}
tests++;
if(!in('A', "AAAAAAAAAAAAAAAAAAAAA")){fails++; fprintf(stderr, "In failing many\n");}
tests++;
if(!in('A', "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWA")){fails++; fprintf(stderr, "In failing long\n");}
// skip_ws tests
tests++;
if(*(skip_ws(" qwe")) != 'q'){fails++; fprintf(stderr, "skipped ws failing\n");}
tests++;
if(*(skip_ws(" \n\n\n")) != (char)0){fails++; fprintf(stderr, "skipped ws failing around sentinel\n");}
tests++;
if(*(skip_ws("")) != (char)0){fails++; fprintf(stderr, "skipped ws failing for empty\n");}
tests++;
if(*(skip_ws("asd")) != 'a'){fails++; fprintf(stderr, "skipped ws when not required\n");}
// string_seek tests
tests++;
if(*(string_seek("asdqwerty", "asd")) != 'q'){fails++; fprintf(stderr, "mismatch at asd\n");}
tests++;
if(*(string_seek("key: MAGIC_KEY", "key:")) != 'M'){fails++; fprintf(stderr, "mismatch at MAGIC\n");}
tests++;
if(*(string_seek("kkey: MAGICKA_KEY", "key:")) != 'M'){fails++; fprintf(stderr, "mismatch at MAGICKA\n");}
tests++;
if(*(string_seek("kkkkkkkkkkkkkey: MAGICA_KEY", "key:")) != 'M'){fails++; fprintf(stderr, "mismatch at MAGICA\n");}
tests++;
if(*(string_seek("key: MADOKA_KEY", "key:")) != 'M'){fails++; fprintf(stderr, "mismatch at MADOKA\n");}
tests++;
if(*(string_seek("kkey: MAGIKA_KEY", "key:")) != 'M'){fails++; fprintf(stderr, "mismatch at kkey\n");}
tests++;
if(*(string_seek("kkkkkkkkkkkkkey: AGICKA_KEY", "key:")) != 'A'){fails++; fprintf(stderr, "mismatch at AGICKA\n");}
tests++;
if(string_seek("qwertyuiop", "key") != NULL){fails++; fprintf(stderr, "mismatch at never\n");}
tests++;
if(string_seek("kekeroni macaroni.", "key") != NULL){fails++; fprintf(stderr, "mismatch at kek\n");}
tests++;
if(*(string_seek(" lorem ipsum", "lorem")) != 'i'){fails++; fprintf(stderr, "mismatch at lorem\n");}
tests++;
if(*(string_seek(" lorem ipsum", "lore")) != 'm'){fails++; fprintf(stderr, "mismatch at lore\n");}
tests++;
if(string_seek("", "key") != NULL){fails++; fprintf(stderr, "mismatch at null\n");}
// string_get_next_token tests
string tok;
tests++;
if((tok = string_get_next_token("qwert", "ert")).compare("qw")){fails++; fprintf(stderr, "mismatch token qwe1\n got \"%s\" expected qw\n", tok.c_str());}
tests++;
if((tok = string_get_next_token("qwert", "tr")).compare("qwe")){fails++; fprintf(stderr, "mismatch token qwe2\n got \"%s\" expected qwe\n", tok.c_str());}
tests++;
if((tok = string_get_next_token(" ", STR_WHITE)).compare("")){fails++; fprintf(stderr, "mismatch token empty ws\n got \"%s\" expected nothing\n", tok.c_str());}
tests++;
if((tok = string_get_next_token("asdqwe ", STR_WHITE)).compare("asdqwe")){fails++; fprintf(stderr, "mismatch token full ws\n got \"%s\" expected asdqwe\n", tok.c_str());}
tests++;
if((tok = string_get_next_token("asdqwetyi", STR_WHITE)).compare("asdqwetyi")){fails++; fprintf(stderr, "mismatch token no separator\n got \"%s\" expected asdqwetyi\n", tok.c_str());}
tests++;
if((tok = string_get_next_token(STR_WHITE, "")).compare(STR_WHITE)){fails++; fprintf(stderr, "mismatch token null separator\n got \"%s\" expected whitespace\n", tok.c_str());}
tests++;
if((tok = string_get_next_token("", "")).compare("")){fails++; fprintf(stderr, "mismatch token empty insanity\n got \"%s\" expected nothing\n", tok.c_str());}
// is_num tests
tests++;
if(!is_num("0")){fails++; fprintf(stderr, "0 not detected as numeric\n");}
tests++;
if(!is_num("-0")){fails++; fprintf(stderr, "-0 not detected as numeric\n");}
tests++;
if(!is_num("-12312312312312321321321321312")){fails++; fprintf(stderr, "-long not detected as numeric\n");}
tests++;
if(is_num("-----123")){fails++; fprintf(stderr, "multiple negation detected as numeric\n");}
tests++;
if(is_num(" ")){fails++; fprintf(stderr, "space detected as numeric\n");}
tests++;
if(is_num("-")){fails++; fprintf(stderr, "Just minus detected as numeric\n");}
tests++;
if(is_num("-asd123")){fails++; fprintf(stderr, "minus string detected as numeric\n");}
tests++;
if(is_num("asdqwe")){fails++; fprintf(stderr, "text detected as numeric\n");}
tests++;
if(!is_num("1asdqwe")){fails++; fprintf(stderr, "number prefix not detected as numeric\n");}
tests++;
if(!is_num("-4asdqwe")){fails++; fprintf(stderr, "negative number prefix not detected as numeric\n");}
// combination tests
tests++;
if((tok = string_get_next_token(string_seek("HTTP1/1 GET /\nws_key: asdqwemihai", "ws_key:"), STR_WHITE)).compare("asdqwemihai")){fails++; fprintf(stderr, "failed key detection\n");}
tests++;
if(string_get_next_token
(string_seek
(string_seek
("HTTP1/1 GET /index.html?x=1&y=2&t=3\nws_key: ????????"
, "?")
, "x=")
, " \n\t\f\r\v&")
.compare("1"))
{fails++; fprintf(stderr, "failed argument parsing for x(first)\n");}
tests++;
if(string_get_next_token
(string_seek
(string_seek
("HTTP1/1 GET /index.html?x=1&y=2&t=3\nws_key: ????????"
, "?")
, "y=")
, " \n\t\f\r\v&")
.compare("2"))
{fails++; fprintf(stderr, "failed argument parsing for y(second)\n");}
tests++;
if(string_get_next_token
(string_seek
(string_seek
("HTTP1/1 GET /index.html?x=1&y=2&t=3\nws_key: ????????"
, "?")
, "t=")
, " \n\t\f\r\v&")
.compare("3"))
{fails++; fprintf(stderr, "failed argument parsing for t(third)\n");}
tests++;
if(string_get_next_token
(string_seek
(string_seek
("HTTP1/1 GET /index.html?x=1&y=2&t=3\nws_key: ????????"
, "?")
, "k=")
, " \n\t\f\r\v&")
.compare(""))
{fails++; fprintf(stderr, "failed argument parsing for t(third)\n");}
// null propagation testing
tests++;
if(in('U', NULL)){fails++; fprintf(stderr, "Null propagation failing for in\n");}
tests++;
if(skip_ws(NULL)){fails++; fprintf(stderr, "Null propagation failing for skip_ws\n");}
tests++;
if(string_seek(NULL, "qwe")){fails++; fprintf(stderr, "Null propagation failing for seek(origin)\n");}
tests++;
if(string_seek("qwe", NULL)){fails++; fprintf(stderr, "Null propagation failing for seek(target)\n");}
tests++;
if(string_seek(NULL, NULL)){fails++; fprintf(stderr, "Null propagation failing for seek(both)\n");}
tests++;
if(string_get_next_token(FIXED_STRING, NULL).compare(FIXED_STRING)){fails++; fprintf(stderr, "Null propagation failing for tokenizer when it should work\n");}
tests++;
if(string_get_next_token(NULL, FIXED_STRING).compare("")){fails++; fprintf(stderr, "Null propagation failing for tokenizer when it should fail\n");}
tests++;
if(is_num("")){fails++; fprintf(stderr, "empty detected as numeric\n");}
tests++;
if(is_num(NULL)){fails++; fprintf(stderr, "null detected as numeric\n");}
// results and finish
fprintf(stderr, "%d/%d tests passed - strings\n", tests - fails, tests);
return fails;
}
int main()
{
return math_tests() + strings_tests();
}
| 38.656442
| 187
| 0.610062
|
CellWarsOfficial
|
87f60818cf08ceae83d9cce078c75e5de85c125d
| 33,887
|
cpp
|
C++
|
Blizzlike/ArcEmu/C++/World/ScriptMgr.cpp
|
499453466/Lua-Other
|
43fd2b72405faf3f2074fd2a2706ef115d16faa6
|
[
"Unlicense"
] | 2
|
2015-06-23T16:26:32.000Z
|
2019-06-27T07:45:59.000Z
|
Blizzlike/ArcEmu/C++/World/ScriptMgr.cpp
|
Eduardo-Silla/Lua-Other
|
db610f946dbcaf81b3de9801f758e11a7bf2753f
|
[
"Unlicense"
] | null | null | null |
Blizzlike/ArcEmu/C++/World/ScriptMgr.cpp
|
Eduardo-Silla/Lua-Other
|
db610f946dbcaf81b3de9801f758e11a7bf2753f
|
[
"Unlicense"
] | 3
|
2015-01-10T18:22:59.000Z
|
2021-04-27T21:28:28.000Z
|
/*
* ArcEmu MMORPG Server
* Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2008-2011 <http://www.ArcEmu.org/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/*
English Worldstrings as of 08.16.2009
entry text
1 I would like to browse your goods.
2 I seek
3 mage
4 shaman
5 warrior
6 paladin
7 warlock
8 hunter
9 rogue
10 druid
11 priest
12 training
13 Train me in the ways of the beast.
14 Give me a ride.
15 I would like to make a bid.
16 Make this inn your home.
17 I would like to check my deposit box.
18 Bring me back to life.
19 How do I create a guild/arena team?
20 I want to create a guild crest.
21 I would like to go to the battleground.
22 I would like to reset my talents.
23 I wish to untrain my pet.
24 I understand, continue.
25 Yes, please do.
26 This instance is unavailable.
27 You must have The Burning Crusade Expansion to access this content.
28 Heroic mode unavailable for this instance.
29 You must be in a raid group to pass through here.
30 You do not have the required attunement to pass through here.
31 You must be at least level %u to pass through here.
32 You must be in a party to pass through here.
33 You must be level 70 to enter heroic mode.
34 -
35 You must have the item, `%s` to pass through here.
36 You must have the item, UNKNOWN to pass through here.
37 What can I teach you, $N?
38 Alterac Valley
39 Warsong Gulch
40 Arathi Basin
41 Arena 2v2
42 Arena 3v3
43 Arena 5v5
44 Eye of the Storm
45 Unknown Battleground
46 One minute until the battle for %s begins!
47 Thirty seconds until the battle for %s begins!
48 Fifteen seconds until the battle for %s begins!
49 The battle for %s has begun!
50 Arena
51 You have tried to join an invalid instance id.
52 Your queue on battleground instance id %u is no longer valid. Reason: Instance Deleted.
53 You cannot join this battleground as it has already ended.
54 Your queue on battleground instance %u is no longer valid, the instance no longer exists.
55 Sorry, raid groups joining battlegrounds are currently unsupported.
56 You must be the party leader to add a group to an arena.
57 You must be in a team to join rated arena.
58 You have too many players in your party to join this type of arena.
59 Sorry, some of your party members are not level 70.
60 One or more of your party members are already queued or inside a battleground.
61 One or more of your party members are not members of your team.
62 Welcome to
63 Horde
64 Alliance
65 [ |cff00ccffAttention|r ] Welcome! A new challenger (|cff00ff00{%d}|r - |cffff0000%s|r) has arrived and joined into |cffff0000%s|r,their force has already been increased.
66 This instance is scheduled to reset on
67 Auto loot passing is now %s
68 On
69 Off
70 Hey there, $N. How can I help you?
71 You are already in an arena team.
72 That name is already in use.
73 You already have an arena charter.
74 A guild with that name already exists.
75 You already have a guild charter.
76 Item not found.
77 Target is of the wrong faction.
78 Target player cannot sign your charter for one or more reasons.
79 You have already signed that charter.
80 You don't have the required amount of signatures to turn in this petition.
81 You must have Wrath of the Lich King Expansion to access this content.
82 Deathknight
*/
#include "StdAfx.h"
#include <git_version.h>
namespace worldstring
{
}
initialiseSingleton(ScriptMgr);
initialiseSingleton(HookInterface);
ScriptMgr::ScriptMgr()
{
}
ScriptMgr::~ScriptMgr()
{
}
struct ScriptingEngine_dl
{
Arcemu::DynLib* dl;
exp_script_register InitializeCall;
uint32 Type;
ScriptingEngine_dl()
{
dl = NULL;
InitializeCall = NULL;
Type = 0;
}
};
void ScriptMgr::LoadScripts()
{
if(HookInterface::getSingletonPtr() == NULL)
new HookInterface;
Log.Success("Server", "Loading External Script Libraries...");
std::string Path;
std::string FileMask;
Path = PREFIX;
Path += '/';
#ifdef WIN32
/*Path = Config.MainConfig.GetStringDefault( "Script", "BinaryLocation", "script_bin" );
Path += "\\";*/
FileMask = ".dll";
#else
#ifndef __APPLE__
FileMask = ".so";
#else
FileMask = ".dylib";
#endif
#endif
Arcemu::FindFilesResult findres;
std::vector< ScriptingEngine_dl > Engines;
Arcemu::FindFiles(Path.c_str(), FileMask.c_str(), findres);
uint32 count = 0;
while(findres.HasNext())
{
std::stringstream loadmessage;
std::string fname = Path + findres.GetNext();
Arcemu::DynLib* dl = new Arcemu::DynLib(fname.c_str());
loadmessage << " " << dl->GetName() << " : ";
if(!dl->Load())
{
loadmessage << "ERROR: Cannot open library.";
LOG_ERROR(loadmessage.str().c_str());
delete dl;
continue;
}
else
{
exp_get_version vcall = reinterpret_cast< exp_get_version >(dl->GetAddressForSymbol("_exp_get_version"));
exp_script_register rcall = reinterpret_cast< exp_script_register >(dl->GetAddressForSymbol("_exp_script_register"));
exp_get_script_type scall = reinterpret_cast< exp_get_script_type >(dl->GetAddressForSymbol("_exp_get_script_type"));
if((vcall == NULL) || (rcall == NULL) || (scall == NULL))
{
loadmessage << "ERROR: Cannot find version functions.";
LOG_ERROR(loadmessage.str().c_str());
delete dl;
continue;
}
else
{
const char *version = vcall();
uint32 stype = scall();
if( strcmp( version, BUILD_HASH_STR ) != 0 )
{
loadmessage << "ERROR: Version mismatch.";
LOG_ERROR(loadmessage.str().c_str());
delete dl;
continue;
}
else
{
loadmessage << ' ' << std::string( BUILD_HASH_STR ) << " : ";
if((stype & SCRIPT_TYPE_SCRIPT_ENGINE) != 0)
{
ScriptingEngine_dl se;
se.dl = dl;
se.InitializeCall = rcall;
se.Type = stype;
Engines.push_back(se);
loadmessage << "delayed load";
}
else
{
rcall(this);
dynamiclibs.push_back(dl);
loadmessage << "loaded";
}
LOG_BASIC(loadmessage.str().c_str());
count++;
}
}
}
}
if(count == 0)
{
LOG_ERROR(" No external scripts found! Server will continue to function with limited functionality.");
}
else
{
Log.Success("Server", "Loaded %u external libraries.", count);
Log.Success("Server", "Loading optional scripting engine(s)...");
for(std::vector< ScriptingEngine_dl >::iterator itr = Engines.begin(); itr != Engines.end(); ++itr)
{
itr->InitializeCall(this);
dynamiclibs.push_back(itr->dl);
}
Log.Success("Server", "Done loading scripting engine(s)...");
}
}
void ScriptMgr::UnloadScripts()
{
if(HookInterface::getSingletonPtr())
delete HookInterface::getSingletonPtr();
for(CustomGossipScripts::iterator itr = _customgossipscripts.begin(); itr != _customgossipscripts.end(); ++itr)
(*itr)->Destroy();
_customgossipscripts.clear();
for(QuestScripts::iterator itr = _questscripts.begin(); itr != _questscripts.end(); ++itr)
delete *itr;
_questscripts.clear();
UnloadScriptEngines();
for(DynamicLibraryMap::iterator itr = dynamiclibs.begin(); itr != dynamiclibs.end(); ++itr)
delete *itr;
dynamiclibs.clear();
}
void ScriptMgr::DumpUnimplementedSpells()
{
std::ofstream of;
LOG_BASIC("Dumping IDs for spells with unimplemented dummy/script effect(s)");
uint32 count = 0;
of.open("unimplemented1.txt");
for(DBCStorage< SpellEntry >::iterator itr = dbcSpell.begin(); itr != dbcSpell.end(); ++itr)
{
SpellEntry* sp = *itr;
if(!sp->HasEffect(SPELL_EFFECT_DUMMY) && !sp->HasEffect(SPELL_EFFECT_SCRIPT_EFFECT) && !sp->HasEffect(SPELL_EFFECT_SEND_EVENT))
continue;
HandleDummySpellMap::iterator sitr = _spells.find(sp->Id);
if(sitr != _spells.end())
continue;
HandleScriptEffectMap::iterator seitr = SpellScriptEffects.find(sp->Id);
if(seitr != SpellScriptEffects.end())
continue;
std::stringstream ss;
ss << sp->Id;
ss << std::endl;
of.write(ss.str().c_str(), ss.str().length());
count++;
}
of.close();
LOG_BASIC("Dumped %u IDs.", count);
LOG_BASIC("Dumping IDs for spells with unimplemented dummy aura effect.");
std::ofstream of2;
of2.open("unimplemented2.txt");
count = 0;
for(DBCStorage< SpellEntry >::iterator itr = dbcSpell.begin(); itr != dbcSpell.end(); ++itr)
{
SpellEntry* sp = *itr;
if(!sp->AppliesAura(SPELL_AURA_DUMMY))
continue;
HandleDummyAuraMap::iterator ditr = _auras.find(sp->Id);
if(ditr != _auras.end())
continue;
std::stringstream ss;
ss << sp->Id;
ss << std::endl;
of2.write(ss.str().c_str(), ss.str().length());
count++;
}
of2.close();
LOG_BASIC("Dumped %u IDs.", count);
}
void ScriptMgr::register_creature_script(uint32 entry, exp_create_creature_ai callback)
{
if(_creatures.find(entry) != _creatures.end())
LOG_ERROR("ScriptMgr is trying to register a script for Creature ID: %u even if there's already one for that Creature. Remove one of those scripts.", entry);
_creatures.insert(CreatureCreateMap::value_type(entry, callback));
}
void ScriptMgr::register_gameobject_script(uint32 entry, exp_create_gameobject_ai callback)
{
if(_gameobjects.find(entry) != _gameobjects.end())
LOG_ERROR("ScriptMgr is trying to register a script for GameObject ID: %u even if there's already one for that GameObject. Remove one of those scripts.", entry);
_gameobjects.insert(GameObjectCreateMap::value_type(entry, callback));
}
void ScriptMgr::register_dummy_aura(uint32 entry, exp_handle_dummy_aura callback)
{
if(_auras.find(entry) != _auras.end())
{
LOG_ERROR("ScriptMgr is trying to register a script for Aura ID: %u even if there's already one for that Aura. Remove one of those scripts.", entry);
}
SpellEntry* sp = dbcSpell.LookupEntryForced(entry);
if(sp == NULL)
{
LOG_ERROR("ScriptMgr is trying to register a dummy aura handler for Spell ID: %u which is invalid.", entry);
return;
}
if(!sp->AppliesAura(SPELL_AURA_DUMMY) && !sp->AppliesAura(SPELL_AURA_PERIODIC_TRIGGER_DUMMY))
LOG_ERROR("ScriptMgr has registered a dummy aura handler for Spell ID: %u ( %s ), but spell has no dummy aura!", entry, sp->Name);
_auras.insert(HandleDummyAuraMap::value_type(entry, callback));
}
void ScriptMgr::register_dummy_spell(uint32 entry, exp_handle_dummy_spell callback)
{
if(_spells.find(entry) != _spells.end())
{
LOG_ERROR("ScriptMgr is trying to register a script for Spell ID: %u even if there's already one for that Spell. Remove one of those scripts.", entry);
return;
}
SpellEntry* sp = dbcSpell.LookupEntryForced(entry);
if(sp == NULL)
{
LOG_ERROR("ScriptMgr is trying to register a dummy handler for Spell ID: %u which is invalid.", entry);
return;
}
if(!sp->HasEffect(SPELL_EFFECT_DUMMY) && !sp->HasEffect(SPELL_EFFECT_SCRIPT_EFFECT) && !sp->HasEffect(SPELL_EFFECT_SEND_EVENT))
LOG_ERROR("ScriptMgr has registered a dummy handler for Spell ID: %u ( %s ), but spell has no dummy/script/send event effect!", entry, sp->Name);
_spells.insert(HandleDummySpellMap::value_type(entry, callback));
}
void ScriptMgr::register_gossip_script(uint32 entry, GossipScript* gs)
{
register_creature_gossip(entry, gs);
}
void ScriptMgr::register_go_gossip_script(uint32 entry, GossipScript* gs)
{
register_go_gossip(entry, gs);
}
void ScriptMgr::register_quest_script(uint32 entry, QuestScript* qs)
{
Quest* q = QuestStorage.LookupEntry(entry);
if(q != NULL)
{
if(q->pQuestScript != NULL)
LOG_ERROR("ScriptMgr is trying to register a script for Quest ID: %u even if there's already one for that Quest. Remove one of those scripts.", entry);
q->pQuestScript = qs;
}
_questscripts.insert(qs);
}
void ScriptMgr::register_instance_script(uint32 pMapId, exp_create_instance_ai pCallback)
{
if(mInstances.find(pMapId) != mInstances.end())
LOG_ERROR("ScriptMgr is trying to register a script for Instance ID: %u even if there's already one for that Instance. Remove one of those scripts.", pMapId);
mInstances.insert(InstanceCreateMap::value_type(pMapId, pCallback));
};
void ScriptMgr::register_creature_script(uint32* entries, exp_create_creature_ai callback)
{
for(uint32 y = 0; entries[y] != 0; y++)
{
register_creature_script(entries[y], callback);
}
};
void ScriptMgr::register_gameobject_script(uint32* entries, exp_create_gameobject_ai callback)
{
for(uint32 y = 0; entries[y] != 0; y++)
{
register_gameobject_script(entries[y], callback);
}
};
void ScriptMgr::register_dummy_aura(uint32* entries, exp_handle_dummy_aura callback)
{
for(uint32 y = 0; entries[y] != 0; y++)
{
register_dummy_aura(entries[y], callback);
}
};
void ScriptMgr::register_dummy_spell(uint32* entries, exp_handle_dummy_spell callback)
{
for(uint32 y = 0; entries[y] != 0; y++)
{
register_dummy_spell(entries[y], callback);
}
};
void ScriptMgr::register_script_effect(uint32* entries, exp_handle_script_effect callback)
{
for(uint32 y = 0; entries[y] != 0; y++)
{
register_script_effect(entries[y], callback);
}
};
void ScriptMgr::register_script_effect(uint32 entry, exp_handle_script_effect callback)
{
HandleScriptEffectMap::iterator itr = SpellScriptEffects.find(entry);
if(itr != SpellScriptEffects.end())
{
LOG_ERROR("ScriptMgr tried to register more than 1 script effect handlers for Spell %u", entry);
return;
}
SpellEntry* sp = dbcSpell.LookupEntryForced(entry);
if(sp == NULL)
{
LOG_ERROR("ScriptMgr tried to register a script effect handler for Spell %u, which is invalid.", entry);
return;
}
if(!sp->HasEffect(SPELL_EFFECT_SCRIPT_EFFECT) && !sp->HasEffect(SPELL_EFFECT_SEND_EVENT))
LOG_ERROR("ScriptMgr has registered a script effect handler for Spell ID: %u ( %s ), but spell has no scripted effect!", entry, sp->Name);
SpellScriptEffects.insert(std::pair< uint32, exp_handle_script_effect >(entry, callback));
}
CreatureAIScript* ScriptMgr::CreateAIScriptClassForEntry(Creature* pCreature)
{
CreatureCreateMap::iterator itr = _creatures.find(pCreature->GetEntry());
if(itr == _creatures.end())
return NULL;
exp_create_creature_ai function_ptr = itr->second;
return (function_ptr)(pCreature);
}
GameObjectAIScript* ScriptMgr::CreateAIScriptClassForGameObject(uint32 uEntryId, GameObject* pGameObject)
{
GameObjectCreateMap::iterator itr = _gameobjects.find(pGameObject->GetEntry());
if(itr == _gameobjects.end())
return NULL;
exp_create_gameobject_ai function_ptr = itr->second;
return (function_ptr)(pGameObject);
}
InstanceScript* ScriptMgr::CreateScriptClassForInstance(uint32 pMapId, MapMgr* pMapMgr)
{
InstanceCreateMap::iterator Iter = mInstances.find(pMapMgr->GetMapId());
if(Iter == mInstances.end())
return NULL;
exp_create_instance_ai function_ptr = Iter->second;
return (function_ptr)(pMapMgr);
};
bool ScriptMgr::CallScriptedDummySpell(uint32 uSpellId, uint32 i, Spell* pSpell)
{
HandleDummySpellMap::iterator itr = _spells.find(uSpellId);
if(itr == _spells.end())
return false;
exp_handle_dummy_spell function_ptr = itr->second;
return (function_ptr)(i, pSpell);
}
bool ScriptMgr::HandleScriptedSpellEffect(uint32 SpellId, uint32 i, Spell* s)
{
HandleScriptEffectMap::iterator itr = SpellScriptEffects.find(SpellId);
if(itr == SpellScriptEffects.end())
return false;
exp_handle_script_effect ptr = itr->second;
return (ptr)(i, s);
}
bool ScriptMgr::CallScriptedDummyAura(uint32 uSpellId, uint32 i, Aura* pAura, bool apply)
{
HandleDummyAuraMap::iterator itr = _auras.find(uSpellId);
if(itr == _auras.end())
return false;
exp_handle_dummy_aura function_ptr = itr->second;
return (function_ptr)(i, pAura, apply);
}
bool ScriptMgr::CallScriptedItem(Item* pItem, Player* pPlayer)
{
Arcemu::Gossip::Script* script = this->get_item_gossip(pItem->GetEntry());
if(script != NULL)
{
script->OnHello(pItem, pPlayer);
return true;
}
return false;
}
void ScriptMgr::register_item_gossip_script(uint32 entry, GossipScript* gs)
{
register_item_gossip(entry, gs);
}
/* CreatureAI Stuff */
CreatureAIScript::CreatureAIScript(Creature* creature) : _unit(creature), linkedCreatureAI(NULL)
{
}
CreatureAIScript::~CreatureAIScript()
{
//notify our linked creature that we are being deleted.
if(linkedCreatureAI != NULL)
linkedCreatureAI->LinkedCreatureDeleted();
}
void CreatureAIScript::RegisterAIUpdateEvent(uint32 frequency)
{
//sEventMgr.AddEvent(_unit, &Creature::CallScriptUpdate, EVENT_SCRIPT_UPDATE_EVENT, frequency, 0,0);
sEventMgr.AddEvent(_unit, &Creature::CallScriptUpdate, EVENT_SCRIPT_UPDATE_EVENT, frequency, 0, EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT);
}
void CreatureAIScript::ModifyAIUpdateEvent(uint32 newfrequency)
{
sEventMgr.ModifyEventTimeAndTimeLeft(_unit, EVENT_SCRIPT_UPDATE_EVENT, newfrequency);
}
void CreatureAIScript::RemoveAIUpdateEvent()
{
sEventMgr.RemoveEvents(_unit, EVENT_SCRIPT_UPDATE_EVENT);
}
void CreatureAIScript::LinkedCreatureDeleted()
{
linkedCreatureAI = NULL;
}
void CreatureAIScript::SetLinkedCreature(CreatureAIScript* creatureAI)
{
//notify our linked creature that we are not more linked
if(linkedCreatureAI != NULL)
linkedCreatureAI->LinkedCreatureDeleted();
//link to the new creature
linkedCreatureAI = creatureAI;
}
bool CreatureAIScript::IsAlive()
{
return _unit->isAlive();
}
/* GameObjectAI Stuff */
GameObjectAIScript::GameObjectAIScript(GameObject* goinstance) : _gameobject(goinstance)
{
}
void GameObjectAIScript::ModifyAIUpdateEvent(uint32 newfrequency)
{
sEventMgr.ModifyEventTimeAndTimeLeft(_gameobject, EVENT_SCRIPT_UPDATE_EVENT, newfrequency);
}
void GameObjectAIScript::RemoveAIUpdateEvent()
{
sEventMgr.RemoveEvents(_gameobject, EVENT_SCRIPT_UPDATE_EVENT);
}
void GameObjectAIScript::RegisterAIUpdateEvent(uint32 frequency)
{
sEventMgr.AddEvent(_gameobject, &GameObject::CallScriptUpdate, EVENT_SCRIPT_UPDATE_EVENT, frequency, 0, EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT);
}
/* InstanceAI Stuff */
InstanceScript::InstanceScript(MapMgr* pMapMgr) : mInstance(pMapMgr)
{
};
void InstanceScript::RegisterUpdateEvent(uint32 pFrequency)
{
sEventMgr.AddEvent(mInstance, &MapMgr::CallScriptUpdate, EVENT_SCRIPT_UPDATE_EVENT, pFrequency, 0, EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT);
};
void InstanceScript::ModifyUpdateEvent(uint32 pNewFrequency)
{
sEventMgr.ModifyEventTimeAndTimeLeft(mInstance, EVENT_SCRIPT_UPDATE_EVENT, pNewFrequency);
};
void InstanceScript::RemoveUpdateEvent()
{
sEventMgr.RemoveEvents(mInstance, EVENT_SCRIPT_UPDATE_EVENT);
};
/* Hook Stuff */
void ScriptMgr::register_hook(ServerHookEvents event, void* function_pointer)
{
ARCEMU_ASSERT(event < NUM_SERVER_HOOKS);
_hooks[event].insert(function_pointer);
}
bool ScriptMgr::has_creature_script(uint32 entry) const
{
return (_creatures.find(entry) != _creatures.end());
}
bool ScriptMgr::has_gameobject_script(uint32 entry) const
{
return (_gameobjects.find(entry) != _gameobjects.end());
}
bool ScriptMgr::has_dummy_aura_script(uint32 entry) const
{
return (_auras.find(entry) != _auras.end());
}
bool ScriptMgr::has_dummy_spell_script(uint32 entry) const
{
return (_spells.find(entry) != _spells.end());
}
bool ScriptMgr::has_script_effect(uint32 entry) const
{
return (SpellScriptEffects.find(entry) != SpellScriptEffects.end());
}
bool ScriptMgr::has_instance_script(uint32 id) const
{
return (mInstances.find(id) != mInstances.end());
}
bool ScriptMgr::has_hook(ServerHookEvents evt, void* ptr) const
{
return (_hooks[evt].size() != 0 && _hooks[evt].find(ptr) != _hooks[evt].end());
}
bool ScriptMgr::has_quest_script(uint32 entry) const
{
Quest* q = QuestStorage.LookupEntry(entry);
return (q == NULL || q->pQuestScript != NULL);
}
void ScriptMgr::register_creature_gossip(uint32 entry, Arcemu::Gossip::Script* script)
{
GossipMap::iterator itr = creaturegossip_.find(entry);
if(itr == creaturegossip_.end())
creaturegossip_.insert(make_pair(entry, script));
//keeping track of all created gossips to delete them all on shutdown
_customgossipscripts.insert(script);
}
bool ScriptMgr::has_creature_gossip(uint32 entry) const
{
return creaturegossip_.find(entry) != creaturegossip_.end();
}
Arcemu::Gossip::Script* ScriptMgr::get_creature_gossip(uint32 entry) const
{
GossipMap::const_iterator itr = creaturegossip_.find(entry);
if(itr != creaturegossip_.end())
return itr->second;
return NULL;
}
void ScriptMgr::register_item_gossip(uint32 entry, Arcemu::Gossip::Script* script)
{
GossipMap::iterator itr = itemgossip_.find(entry);
if(itr == itemgossip_.end())
itemgossip_.insert(make_pair(entry, script));
//keeping track of all created gossips to delete them all on shutdown
_customgossipscripts.insert(script);
}
void ScriptMgr::register_go_gossip(uint32 entry, Arcemu::Gossip::Script* script)
{
GossipMap::iterator itr = gogossip_.find(entry);
if(itr == gogossip_.end())
gogossip_.insert(make_pair(entry, script));
//keeping track of all created gossips to delete them all on shutdown
_customgossipscripts.insert(script);
}
bool ScriptMgr::has_item_gossip(uint32 entry) const
{
return itemgossip_.find(entry) != itemgossip_.end();
}
bool ScriptMgr::has_go_gossip(uint32 entry) const
{
return gogossip_.find(entry) != gogossip_.end();
}
Arcemu::Gossip::Script* ScriptMgr::get_go_gossip(uint32 entry) const
{
GossipMap::const_iterator itr = gogossip_.find(entry);
if(itr != gogossip_.end())
return itr->second;
return NULL;
}
Arcemu::Gossip::Script* ScriptMgr::get_item_gossip(uint32 entry) const
{
GossipMap::const_iterator itr = itemgossip_.find(entry);
if(itr != itemgossip_.end())
return itr->second;
return NULL;
}
void ScriptMgr::ReloadScriptEngines()
{
//for all scripting engines that allow reloading, assuming there will be new scripting engines.
exp_get_script_type version_function;
exp_engine_reload engine_reloadfunc;
for(DynamicLibraryMap::iterator itr = dynamiclibs.begin(); itr != dynamiclibs.end(); ++itr)
{
Arcemu::DynLib* dl = *itr;
version_function = reinterpret_cast< exp_get_script_type >(dl->GetAddressForSymbol("_exp_get_script_type"));
if(version_function == NULL)
continue;
if((version_function() & SCRIPT_TYPE_SCRIPT_ENGINE) != 0)
{
engine_reloadfunc = reinterpret_cast< exp_engine_reload >(dl->GetAddressForSymbol("_export_engine_reload"));
if(engine_reloadfunc != NULL)
engine_reloadfunc();
}
}
}
void ScriptMgr::UnloadScriptEngines()
{
//for all scripting engines that allow unloading, assuming there will be new scripting engines.
exp_get_script_type version_function;
exp_engine_unload engine_unloadfunc;
for(DynamicLibraryMap::iterator itr = dynamiclibs.begin(); itr != dynamiclibs.end(); ++itr)
{
Arcemu::DynLib* dl = *itr;
version_function = reinterpret_cast< exp_get_script_type >(dl->GetAddressForSymbol("_exp_get_script_type"));
if(version_function == NULL)
continue;
if((version_function() & SCRIPT_TYPE_SCRIPT_ENGINE) != 0)
{
engine_unloadfunc = reinterpret_cast< exp_engine_unload >(dl->GetAddressForSymbol("_exp_engine_unload"));
if(engine_unloadfunc != NULL)
engine_unloadfunc();
}
}
}
//support for Gossip scripts added before r4106 changes
void GossipScript::OnHello(Object* pObject, Player* Plr)
{
GossipHello(pObject, Plr);
}
void GossipScript::OnSelectOption(Object* pObject, Player* Plr, uint32 Id, const char* EnteredCode)
{
uint32 IntId = Id;
if(Plr->CurrentGossipMenu != NULL)
{
GossipMenuItem item = Plr->CurrentGossipMenu->GetItem(Id);
IntId = item.IntId;
}
GossipSelectOption(pObject, Plr, Id , IntId, EnteredCode);
}
void GossipScript::OnEnd(Object* pObject, Player* Plr)
{
GossipEnd(pObject, Plr);
}
/* Hook Implementations */
bool HookInterface::OnNewCharacter(uint32 Race, uint32 Class, WorldSession* Session, const char* Name)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_NEW_CHARACTER];
bool ret_val = true;
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
{
bool rv = ((tOnNewCharacter) * itr)(Race, Class, Session, Name);
if(rv == false) // never set ret_val back to true, once it's false
ret_val = false;
}
return ret_val;
}
void HookInterface::OnKillPlayer(Player* pPlayer, Player* pVictim)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_KILL_PLAYER];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnKillPlayer)*itr)(pPlayer, pVictim);
}
void HookInterface::OnFirstEnterWorld(Player* pPlayer)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_FIRST_ENTER_WORLD];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnFirstEnterWorld)*itr)(pPlayer);
}
void HookInterface::OnCharacterCreate(Player* pPlayer)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_CHARACTER_CREATE];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOCharacterCreate)*itr)(pPlayer);
}
void HookInterface::OnEnterWorld(Player* pPlayer)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_ENTER_WORLD];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnEnterWorld)*itr)(pPlayer);
}
void HookInterface::OnGuildCreate(Player* pLeader, Guild* pGuild)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_GUILD_CREATE];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnGuildCreate)*itr)(pLeader, pGuild);
}
void HookInterface::OnGuildJoin(Player* pPlayer, Guild* pGuild)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_GUILD_JOIN];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnGuildJoin)*itr)(pPlayer, pGuild);
}
void HookInterface::OnDeath(Player* pPlayer)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_DEATH];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnDeath)*itr)(pPlayer);
}
bool HookInterface::OnRepop(Player* pPlayer)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_REPOP];
bool ret_val = true;
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
{
bool rv = ((tOnRepop) * itr)(pPlayer);
if(rv == false) // never set ret_val back to true, once it's false
ret_val = false;
}
return ret_val;
}
void HookInterface::OnEmote(Player* pPlayer, uint32 Emote, Unit* pUnit)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_EMOTE];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnEmote)*itr)(pPlayer, Emote, pUnit);
}
void HookInterface::OnEnterCombat(Player* pPlayer, Unit* pTarget)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_ENTER_COMBAT];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnEnterCombat)*itr)(pPlayer, pTarget);
}
bool HookInterface::OnCastSpell(Player* pPlayer, SpellEntry* pSpell, Spell* spell)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_CAST_SPELL];
bool ret_val = true;
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
{
bool rv = ((tOnCastSpell) * itr)(pPlayer, pSpell, spell);
if(rv == false) // never set ret_val back to true, once it's false
ret_val = false;
}
return ret_val;
}
bool HookInterface::OnLogoutRequest(Player* pPlayer)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_LOGOUT_REQUEST];
bool ret_val = true;
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
{
bool rv = ((tOnLogoutRequest) * itr)(pPlayer);
if(rv == false) // never set ret_val back to true, once it's false
ret_val = false;
}
return ret_val;
}
void HookInterface::OnLogout(Player* pPlayer)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_LOGOUT];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnLogout)*itr)(pPlayer);
}
void HookInterface::OnQuestAccept(Player* pPlayer, Quest* pQuest, Object* pQuestGiver)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_QUEST_ACCEPT];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnQuestAccept)*itr)(pPlayer, pQuest, pQuestGiver);
}
void HookInterface::OnZone(Player* pPlayer, uint32 zone, uint32 oldZone)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_ZONE];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnZone)*itr)(pPlayer, zone, oldZone);
}
bool HookInterface::OnChat(Player* pPlayer, uint32 type, uint32 lang, const char* message, const char* misc)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_CHAT];
bool ret_val = true;
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
{
bool rv = ((tOnChat) * itr)(pPlayer, type, lang, message, misc);
if(rv == false) // never set ret_val back to true, once it's false
ret_val = false;
}
return ret_val;
}
void HookInterface::OnLoot(Player* pPlayer, Unit* pTarget, uint32 money, uint32 itemId)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_LOOT];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnLoot)*itr)(pPlayer, pTarget, money, itemId);
}
void HookInterface::OnObjectLoot(Player* pPlayer, Object* pTarget, uint32 money, uint32 itemId)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_OBJECTLOOT];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnObjectLoot)*itr)(pPlayer, pTarget, money, itemId);
}
void HookInterface::OnFullLogin(Player* pPlayer)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_FULL_LOGIN];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnEnterWorld)*itr)(pPlayer);
}
void HookInterface::OnQuestCancelled(Player* pPlayer, Quest* pQuest)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_QUEST_CANCELLED];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnQuestCancel)*itr)(pPlayer, pQuest);
}
void HookInterface::OnQuestFinished(Player* pPlayer, Quest* pQuest, Object* pQuestGiver)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_QUEST_FINISHED];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnQuestFinished)*itr)(pPlayer, pQuest, pQuestGiver);
}
void HookInterface::OnHonorableKill(Player* pPlayer, Player* pKilled)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_HONORABLE_KILL];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnHonorableKill)*itr)(pPlayer, pKilled);
}
void HookInterface::OnArenaFinish(Player* pPlayer, ArenaTeam* pTeam, bool victory, bool rated)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_ARENA_FINISH];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnArenaFinish)*itr)(pPlayer, pTeam, victory, rated);
}
void HookInterface::OnAreaTrigger(Player* pPlayer, uint32 areaTrigger)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_AREATRIGGER];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnAreaTrigger)*itr)(pPlayer, areaTrigger);
}
void HookInterface::OnPostLevelUp(Player* pPlayer)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_POST_LEVELUP];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnPostLevelUp)*itr)(pPlayer);
}
bool HookInterface::OnPreUnitDie(Unit* killer, Unit* victim)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_PRE_DIE];
bool ret_val = true;
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
{
bool rv = ((tOnPreUnitDie) * itr)(killer, victim);
if(rv == false) // never set ret_val back to true, once it's false
ret_val = false;
}
return ret_val;
}
void HookInterface::OnAdvanceSkillLine(Player* pPlayer, uint32 skillLine, uint32 current)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_ADVANCE_SKILLLINE];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnAdvanceSkillLine)*itr)(pPlayer, skillLine, current);
}
void HookInterface::OnDuelFinished(Player* Winner, Player* Looser)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_DUEL_FINISHED];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnDuelFinished)*itr)(Winner, Looser);
}
void HookInterface::OnAuraRemove(Aura* aura)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_AURA_REMOVE];
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
((tOnAuraRemove)*itr)(aura);
}
bool HookInterface::OnResurrect(Player* pPlayer)
{
ServerHookList hookList = sScriptMgr._hooks[SERVER_HOOK_EVENT_ON_RESURRECT];
bool ret_val = true;
for(ServerHookList::iterator itr = hookList.begin(); itr != hookList.end(); ++itr)
{
bool rv = ((tOnResurrect) * itr)(pPlayer);
if(rv == false) // never set ret_val back to true, once it's false
ret_val = false;
}
return ret_val;
}
| 30.25625
| 174
| 0.741051
|
499453466
|
87ff0fe2e6931d5ab67336efe927a2c045ad694d
| 1,584
|
cpp
|
C++
|
Cpp-Projects/Part_02_Foundation/L4_writing_multiple_programs/13_Classes_and_OOP/1_Code_without_Objects/main.cpp
|
selfbeing/selfdriving
|
8a40db76e5aa4ac3b0f83a855e4ca29b99b90dd9
|
[
"MIT"
] | null | null | null |
Cpp-Projects/Part_02_Foundation/L4_writing_multiple_programs/13_Classes_and_OOP/1_Code_without_Objects/main.cpp
|
selfbeing/selfdriving
|
8a40db76e5aa4ac3b0f83a855e4ca29b99b90dd9
|
[
"MIT"
] | null | null | null |
Cpp-Projects/Part_02_Foundation/L4_writing_multiple_programs/13_Classes_and_OOP/1_Code_without_Objects/main.cpp
|
selfbeing/selfdriving
|
8a40db76e5aa4ac3b0f83a855e4ca29b99b90dd9
|
[
"MIT"
] | null | null | null |
/*
Code without Objects
Suppose you were writing a program to model several cars.
In your program, you want to keep track of each car's color and the distance the car has traveled,
and you want to be able to increment this distance and print out the car's properties.
You could write something like the code below to accomplish this:
*/
#include <iostream>
#include <string>
using std::string;
using std::cout;
int main()
{
// Variables to hold each car's color.
string car_1_color = "green";
string car_2_color = "red";
string car_3_color = "blue";
// Variables to hold each car's initial position.
int car_1_distance = 0;
int car_2_distance = 0;
int car_3_distance = 0;
// Increment car_1's position by 1.
car_1_distance++;
// Print out the position and color of each car.
cout << "The distance that the " << car_1_color << " car 1 has traveled is: " << car_1_distance << "\n";
cout << "The distance that the " << car_2_color << " car 2 has traveled is: " << car_2_distance << "\n";
cout << "The distance that the " << car_3_color << " car 3 has traveled is: " << car_3_distance << "\n";
}
/*
This works for the few cars that are defined in the program,
but if you wanted the program to keep track of many cars this would be cumbersome.
You would need to create a new variables for every car, and the code would quickly become cluttered.
One way to fix this would be to define a Car class with those variables as attributes,
along with a few class methods to increment the distance traveled and print out car data.
*/
| 36
| 108
| 0.705177
|
selfbeing
|
e2008f873e49dc817c7bbea2579cd98fb7e09b25
| 4,792
|
cpp
|
C++
|
sdh/crc.cpp
|
ipab-slmc/SDHLibrary-CPP
|
0217d4edf82f34292750240bd7a3d9c63feb7e33
|
[
"Apache-2.0"
] | 2
|
2021-11-12T09:28:45.000Z
|
2021-12-22T09:09:31.000Z
|
sdh/crc.cpp
|
ipab-slmc/SDHLibrary-CPP
|
0217d4edf82f34292750240bd7a3d9c63feb7e33
|
[
"Apache-2.0"
] | null | null | null |
sdh/crc.cpp
|
ipab-slmc/SDHLibrary-CPP
|
0217d4edf82f34292750240bd7a3d9c63feb7e33
|
[
"Apache-2.0"
] | 2
|
2019-05-02T20:03:29.000Z
|
2019-06-24T14:50:42.000Z
|
//======================================================================
/*!
\file
\section sdhlibrary_cpp_crc_cpp_general General file information
\author Dirk Osswald
\date 2007-02-19
\brief
Implementation of class #SDH::cCRC_DSACON32m (actually only the static members all other is derived).
\section sdhlibrary_cpp_crc_cpp_copyright Copyright
- Copyright (c) 2008 SCHUNK GmbH & Co. KG
<HR>
\internal
\subsection sdhlibrary_cpp_crc_cpp_details SVN related, detailed file specific information:
$LastChangedBy: Osswald2 $
$LastChangedDate: 2008-10-08 10:48:38 +0200 (Mi, 08 Okt 2008) $
\par SVN file revision:
$Id: crc.cpp 3659 2008-10-08 08:48:38Z Osswald2 $
\subsection sdhlibrary_cpp_crc_cpp_changelog Changelog of this file:
\include crc.cpp.log
*/
//======================================================================
#include "sdhlibrary_settings.h"
//----------------------------------------------------------------------
// System Includes - include with <>
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// Project Includes - include with ""
//----------------------------------------------------------------------
#include "crc.h"
USING_NAMESPACE_SDH
//----------------------------------------------------------------------
// Defines, enums, unions, structs,
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// Global variables
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// Function implementation (function definitions)
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// Class member definitions
//----------------------------------------------------------------------
tCRCValue const cCRC_DSACON32m::crc_table_dsacon32m[256] =
{
0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,
0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6,
0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,
0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485,
0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d,
0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4,
0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc,
0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823,
0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b,
0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12,
0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,
0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41,
0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49,
0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70,
0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78,
0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f,
0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,
0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e,
0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256,
0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,
0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c,
0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634,
0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab,
0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3,
0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a,
0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92,
0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9,
0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1,
0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8,
0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0
};
//======================================================================
/*
Here are some settings for the emacs/xemacs editor (and can be safely ignored):
(e.g. to explicitely set C++ mode for *.h header files)
Local Variables:
mode:C++
mode:ELSE
End:
*/
//======================================================================
| 42.785714
| 105
| 0.515442
|
ipab-slmc
|
e207034aa51177b9803721c97bffdf7abe9ae688
| 279
|
hpp
|
C++
|
include/RED4ext/Scripting/Natives/Generated/rend/WindShapeAnchorPointVert.hpp
|
jackhumbert/RED4ext.SDK
|
2c55eccb83beabbbe02abae7945af8efce638fca
|
[
"MIT"
] | 42
|
2020-12-25T08:33:00.000Z
|
2022-03-22T14:47:07.000Z
|
include/RED4ext/Scripting/Natives/Generated/rend/WindShapeAnchorPointVert.hpp
|
jackhumbert/RED4ext.SDK
|
2c55eccb83beabbbe02abae7945af8efce638fca
|
[
"MIT"
] | 38
|
2020-12-28T22:36:06.000Z
|
2022-02-16T11:25:47.000Z
|
include/RED4ext/Scripting/Natives/Generated/rend/WindShapeAnchorPointVert.hpp
|
jackhumbert/RED4ext.SDK
|
2c55eccb83beabbbe02abae7945af8efce638fca
|
[
"MIT"
] | 20
|
2020-12-28T22:17:38.000Z
|
2022-03-22T17:19:01.000Z
|
#pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
namespace RED4ext
{
namespace rend {
enum class WindShapeAnchorPointVert : uint32_t
{
AP_CENTER = 0,
AP_TOP = 1,
AP_BOTTOM = 2,
};
} // namespace rend
} // namespace RED4ext
| 16.411765
| 57
| 0.698925
|
jackhumbert
|
e20737d3135a49e21df6882d87d3d9136988046b
| 786
|
hpp
|
C++
|
source/gui/LogEntry.hpp
|
RobertDamerius/GroundControlStation
|
7f0d896bd56e5ea0ee02d5738c2b497dc2956c2f
|
[
"MIT"
] | 1
|
2021-12-26T12:48:18.000Z
|
2021-12-26T12:48:18.000Z
|
source/gui/LogEntry.hpp
|
RobertDamerius/GroundControlStation
|
7f0d896bd56e5ea0ee02d5738c2b497dc2956c2f
|
[
"MIT"
] | null | null | null |
source/gui/LogEntry.hpp
|
RobertDamerius/GroundControlStation
|
7f0d896bd56e5ea0ee02d5738c2b497dc2956c2f
|
[
"MIT"
] | 1
|
2021-12-26T12:48:25.000Z
|
2021-12-26T12:48:25.000Z
|
#pragma once
#include <VehicleID.hpp>
class LogEntry {
public:
std::string timestamp;
std::string source;
std::string text;
uint8_t color[3];
/**
* @brief Create a log entry.
* @param [in] timestamp The UTC second of the day.
* @param [in] source Source of the log message.
* @param [in] text Text of the log message.
* @param [in] r Red component for text color.
* @param [in] g Green component for text color.
* @param [in] b Blue component for text color.
*/
LogEntry(double timestamp, const VehicleID& source, std::string& text, uint8_t r, uint8_t g, uint8_t b);
/**
* @brief Delete the log entry.
*/
~LogEntry();
};
| 25.354839
| 112
| 0.554707
|
RobertDamerius
|
e208cd81c87125355ee128e641604a7199345678
| 1,545
|
cpp
|
C++
|
libpigpiodpp/test/pihardwaremanagerfactorytests.cpp
|
freesurfer-rge/linesidecabinet
|
8944c67fa7d340aa792e3a6e681113a4676bfbad
|
[
"MIT"
] | null | null | null |
libpigpiodpp/test/pihardwaremanagerfactorytests.cpp
|
freesurfer-rge/linesidecabinet
|
8944c67fa7d340aa792e3a6e681113a4676bfbad
|
[
"MIT"
] | 14
|
2019-11-17T14:46:25.000Z
|
2021-03-10T02:48:40.000Z
|
libpigpiodpp/test/pihardwaremanagerfactorytests.cpp
|
freesurfer-rge/linesidecabinet
|
8944c67fa7d340aa792e3a6e681113a4676bfbad
|
[
"MIT"
] | null | null | null |
#include <boost/test/unit_test.hpp>
#include "tendril/devices/i2cdevicedata.hpp"
#include "tendril/devices/pca9685.hpp"
#include "pigpiodpp/pihardwaremanagerfactory.hpp"
BOOST_AUTO_TEST_SUITE( PiHardwareManagerFactory )
BOOST_AUTO_TEST_CASE( Smoke )
{
Tendril::HardwareManagerData config;
auto hwm = PiGPIOdpp::GetHardwareManager(config);
BOOST_REQUIRE( hwm );
BOOST_CHECK( hwm->bipProviderRegistrar.Retrieve("GPIO") );
BOOST_CHECK( hwm->bopProviderRegistrar.Retrieve("GPIO") );
BOOST_CHECK( hwm->bopArrayProviderRegistrar.Retrieve("GPIO") );
BOOST_CHECK( hwm->i2cCommProviderRegistrar.Retrieve("0") );
BOOST_CHECK( hwm->i2cCommProviderRegistrar.Retrieve("1") );
}
BOOST_AUTO_TEST_CASE( WithPCA9685 )
{
const std::string devName = "MyServoProvider";
auto some9685 = std::make_shared<
Tendril::Devices::I2CDeviceData<Tendril::Devices::PCA9685>>();
some9685->i2cCommsRequest.providerName = "1";
some9685->i2cCommsRequest.idOnProvider = "0x10";
some9685->name = devName;
some9685->settings["referenceClock"] = "25e6";
some9685->settings["pwmFrequency"] = "60";
Tendril::HardwareManagerData config;
config.devices.push_back(some9685);
auto hwm = PiGPIOdpp::GetHardwareManager(config);
BOOST_REQUIRE( hwm );
BOOST_CHECK( hwm->bipProviderRegistrar.Retrieve("GPIO") );
BOOST_CHECK( hwm->bopProviderRegistrar.Retrieve("GPIO") );
BOOST_CHECK( hwm->bopArrayProviderRegistrar.Retrieve("GPIO") );
BOOST_CHECK( hwm->pwmcProviderRegistrar.Retrieve( devName ) );
}
BOOST_AUTO_TEST_SUITE_END()
| 32.1875
| 66
| 0.756634
|
freesurfer-rge
|
e20a1779c288f36bf771964a87d0f79255b286bb
| 10,634
|
cpp
|
C++
|
Quickhaptics/examples/ShapeDepthFeedback/ShapeDepthFeedbackGLUT/src/main.cpp
|
Stalpaard/SensoHapt
|
74c90f1f4b1a17bd94109bc6543a864006849c75
|
[
"MIT"
] | null | null | null |
Quickhaptics/examples/ShapeDepthFeedback/ShapeDepthFeedbackGLUT/src/main.cpp
|
Stalpaard/SensoHapt
|
74c90f1f4b1a17bd94109bc6543a864006849c75
|
[
"MIT"
] | null | null | null |
Quickhaptics/examples/ShapeDepthFeedback/ShapeDepthFeedbackGLUT/src/main.cpp
|
Stalpaard/SensoHapt
|
74c90f1f4b1a17bd94109bc6543a864006849c75
|
[
"MIT"
] | null | null | null |
/////////////////////////////////////////////////////////////////////////////
//OpenHaptics QuickHaptics - Depth and Feedback Buffer Example
//SensAble Technologies, Woburn, MA
//September 03, 2008
//Programmer: Hari Vasudevan
//////////////////////////////////////////////////////////////////////////////
#include <QHHeadersGLUT.h>//Include all necessary headers
void glutMenuFunction(int MenuID);
int main(int argc, char *argv[])
{
QHGLUT* DisplayObject = new QHGLUT(argc,argv);//create a display window
DeviceSpace* OmniSpace = new DeviceSpace;//get the default device
DisplayObject->tell(OmniSpace);//Tell QuickHaptics about it
TriMesh* Bunny = new TriMesh("Models/BunnyRep.ply");//Load the Bunny Models
Bunny->setName("Bunny");//give it a name
Bunny->setTranslation(0.25,-1.0,0.0);//Position the model
Bunny->setScale(10.0);//make the model 2 times as large
Bunny->setStiffness(0.5);
Bunny->setDamping(0.3);
Bunny->setFriction(0.3, 0.5);//Give the Bunny some friction on the surface
Bunny->setShapeColor(205.0/255.0,133.0/255.0,63.0/255.0);//Set a brown color for the bunny
DisplayObject->tell(Bunny);//Tell Quickhaptics about the bunny
TriMesh* WheelLowRes = new TriMesh("Models/wheel-lo.obj");//Load the low resolution Wheel model
WheelLowRes->setName("WheelLowRes");//give it a name
WheelLowRes->setScale(1/12.0);//This model is too big compared to the bunnt model.. So we have to scale it down
WheelLowRes->setStiffness(1.0);
WheelLowRes->setFriction(0.5,0.3);//Give the Wheel some friction on the surface
WheelLowRes->setShapeColor(0.65,0.65,0.65);//Give the Wheel a green color
DisplayObject->tell(WheelLowRes);//Tell Quickhaptics about the low resolution Wheel
TriMesh* WheelHighRes = new TriMesh("Models/wheel-hi.obj");//Load the High resolution Wheel model
WheelHighRes->setName("WheelHighRes");//give it a name
WheelHighRes->setScale(1/12.0);//Scale the Wheel model
WheelHighRes->setStiffness(1.0);
WheelHighRes->setFriction(0.5,0.3);//Give the Wheel some friction on the surface
WheelHighRes->setRenderModeDepth();//Set the rendering mode to Depth Buffer. This is because the High resolution mode contains more than 65536 vertices
WheelHighRes->setShapeColor(0.65,0.65,0.65);//Set the color of the shape to green
DisplayObject->tell(WheelHighRes);//Tell Quickhaptics about the WheelHighRes
Text* RenderModeMsg = new Text(30, "Render Mode: Feedback Buffer", 0.0, 0.95);//Set the message to be displayed on screen, with it's position in
//normalised coordinates. (0,0) is the lower left corner of the screen and (1,1) is the upper right corner.
RenderModeMsg->setShapeColor(0.0,0.0,0.0);//Set the color as black.
RenderModeMsg->setName("RenderModemessage");//Give the message a name
DisplayObject->tell(RenderModeMsg);//Tell QuickHaptics about the text message
Text* ModelStatMsg = new Text(24, "Stanford Bunny: 35,947 vertices",0.0, 0.875);//Create a text message and position it.
ModelStatMsg->setShapeColor(0.0,0.0,0.0);//Set the color as black.
ModelStatMsg->setName("ModelStatMessage");//Give the message a name
DisplayObject->tell(ModelStatMsg);//Tell QuickHaptics about the text message
Text* InstMsg = new Text(24, "Right click on screen to bring up the menu",0.0, 0.05);
InstMsg->setShapeColor(0.0,0.0,0.0);//Set the color as black.
InstMsg->setName("ModelStatMessage");//Tell QuickHaptics about the text message
DisplayObject->tell(InstMsg);//Tell QuickHaptics about the text message
Cursor* OmniCursor = new Cursor("Models/pencil.3DS");//Declare a new cursor
OmniCursor->scaleCursor(0.002);//Scale the cursor because it is too large
TriMesh* ModelTriMeshPointer = OmniCursor->getTriMeshPointer();
ModelTriMeshPointer->setTexture("Models/pencil.JPG");
DisplayObject->tell(OmniCursor);//tell QuickHaptics about the cursor
//Make the The Hight and Low Res Wheels both haptically and graphically invisible
/////////////////////////////////////////////////////////////////////////////////
WheelLowRes->setHapticVisibility(false);
WheelLowRes->setGraphicVisibility(false);
WheelHighRes->setHapticVisibility(false);
WheelHighRes->setGraphicVisibility(false);
/////////////////////////////////////////////////////////////////////////////////
//Create the GLUT menu
glutCreateMenu(glutMenuFunction);
//Add entries
glutAddMenuEntry("Stanford Bunny - Feedback Buffer", 0);
glutAddMenuEntry("Stanford Bunny - Depth Buffer", 1);
glutAddMenuEntry("Wheel Low Resolution - Feedback Buffer", 2);
glutAddMenuEntry("Wheel Low Resolution - Depth Buffer", 3);
glutAddMenuEntry("Wheel High Resolution - Depth Buffer", 4);
//Attach the menu to the right mouse button
glutAttachMenu(GLUT_RIGHT_BUTTON);
qhStart();//Set everything in motion
return 0;
}
void glutMenuFunction(int MenuID)
{
static TriMesh* BunnyPointer = TriMesh::searchTriMesh("Bunny");//Search for a Pointer to the model
static TriMesh* WheelLowRes = TriMesh::searchTriMesh("WheelLowRes");//Search for a Pointer to the model
static TriMesh* WheelHighRes = TriMesh::searchTriMesh("WheelHighRes");//Search for a Pointer to the model
static Text* RenderModeMsgPointer = Text::searchText("RenderModemessage");//Search for a Pointer to the Text
static Text* ModelStatMsgPointer = Text::searchText("ModelStatMessage");//Search for a Pointer to the Text
if(!(BunnyPointer && WheelLowRes && WheelHighRes && RenderModeMsgPointer && ModelStatMsgPointer))//If any of the models cannot be found then return
return;
//////////////////////////
//////////////////////////
if(MenuID == 0)//If the Bunny is clicked on
{
BunnyPointer->setHapticVisibility(true);//Make the Bunny Haptically visible
BunnyPointer->setGraphicVisibility(true);//Make the Bunny Graphically visible
////////////////////////////////////////////////////////////
//Make the other models graphically and haptically invisible
////////////////////////////////////////////////////////////
WheelLowRes->setHapticVisibility(false);
WheelLowRes->setGraphicVisibility(false);
WheelHighRes->setHapticVisibility(false);
WheelHighRes->setGraphicVisibility(false);
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
BunnyPointer->setRenderModeFeedback();
WheelLowRes->setRenderModeFeedback();
WheelHighRes->setRenderModeDepth();
RenderModeMsgPointer->setText("Render Mode: Feedback Buffer");//For any other model change the message to feedback buffer
ModelStatMsgPointer->setText("Stanford Bunny: 35,947 vertices");//Display message
///////////////////////
///////////////////////
}
else if(MenuID == 1)//If the low resolution Wheel is clicked on
{
BunnyPointer->setHapticVisibility(true);//Make the Bunny Haptically visible
BunnyPointer->setGraphicVisibility(true);//Make the Bunny Graphically visible
////////////////////////////////////////////////////////////
//Make the other models graphically and haptically invisible
////////////////////////////////////////////////////////////
WheelLowRes->setHapticVisibility(false);
WheelLowRes->setGraphicVisibility(false);
WheelHighRes->setHapticVisibility(false);
WheelHighRes->setGraphicVisibility(false);
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
BunnyPointer->setRenderModeDepth();
WheelLowRes->setRenderModeDepth();
WheelHighRes->setRenderModeDepth();
RenderModeMsgPointer->setText("Render Mode: Depth Buffer");
ModelStatMsgPointer->setText("Stanford Bunny: 35,947 vertices");//Display message
///////////////////////
///////////////////////
}
else if(MenuID == 2)//If the high resolution Wheel is clicked on
{
WheelLowRes->setHapticVisibility(true);//Make the Low Res Wheel Haptically visible
WheelLowRes->setGraphicVisibility(true);//Make the Low Res Wheel Graphically visible
////////////////////////////////////////////////////////////
//Make the other models graphically and haptically invisible
////////////////////////////////////////////////////////////
BunnyPointer->setHapticVisibility(false);
BunnyPointer->setGraphicVisibility(false);
WheelHighRes->setHapticVisibility(false);
WheelHighRes->setGraphicVisibility(false);
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
BunnyPointer->setRenderModeFeedback();
WheelLowRes->setRenderModeFeedback();
WheelHighRes->setRenderModeDepth();
RenderModeMsgPointer->setText("Render Mode: Feedback Buffer");
ModelStatMsgPointer->setText("Wheel - Low Resolution: 49,989 vertices");
}
else if(MenuID == 3)
{
WheelLowRes->setHapticVisibility(true);//Make the Low Res Wheel Haptically visible;
WheelLowRes->setGraphicVisibility(true);//Make the Low Res Wheel Graphically visible
////////////////////////////////////////////////////////////
//Make the other models graphically and haptically invisible
////////////////////////////////////////////////////////////
BunnyPointer->setHapticVisibility(false);
BunnyPointer->setGraphicVisibility(false);
WheelHighRes->setHapticVisibility(false);
WheelHighRes->setGraphicVisibility(false);
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
BunnyPointer->setRenderModeDepth();
WheelLowRes->setRenderModeDepth();
WheelHighRes->setRenderModeDepth();
RenderModeMsgPointer->setText("Render Mode: Depth Buffer");
ModelStatMsgPointer->setText("Wheel - Low Resolution: 49,989 vertices");
}
else if(MenuID == 4)
{
WheelHighRes->setHapticVisibility(true);//Make the High Res Wheel Haptically visible;
WheelHighRes->setGraphicVisibility(true);//Make the High Res Wheel Graphically visible;
////////////////////////////////////////////////////////////
//Make the other models graphically and haptically invisible
////////////////////////////////////////////////////////////
BunnyPointer->setHapticVisibility(false);
BunnyPointer->setGraphicVisibility(false);
WheelLowRes->setHapticVisibility(false);
WheelLowRes->setGraphicVisibility(false);
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
BunnyPointer->setRenderModeDepth();
WheelLowRes->setRenderModeDepth();
WheelHighRes->setRenderModeDepth();
RenderModeMsgPointer->setText("Render Mode: Depth Buffer");
ModelStatMsgPointer->setText("Wheel - High Resolution: 147,489 vertices");
}
}
| 43.227642
| 152
| 0.639552
|
Stalpaard
|
e20eea4aa0e49a939e83748eb6704d8bf33e8e06
| 545
|
cpp
|
C++
|
440. K-th Smallest in Lexicographical Order/solution.cpp
|
zlsun/leetcode
|
438d0020a701d7aa6a82eee0e46e5b11305abfda
|
[
"MIT"
] | null | null | null |
440. K-th Smallest in Lexicographical Order/solution.cpp
|
zlsun/leetcode
|
438d0020a701d7aa6a82eee0e46e5b11305abfda
|
[
"MIT"
] | null | null | null |
440. K-th Smallest in Lexicographical Order/solution.cpp
|
zlsun/leetcode
|
438d0020a701d7aa6a82eee0e46e5b11305abfda
|
[
"MIT"
] | null | null | null |
/** 440. K-th Smallest in Lexicographical Order
Given integers n and k, find the lexicographically k-th smallest integer in the range from 1 to n.
Note: 1 ≤ k ≤ n ≤ 109.
Example:
Input:
n: 13 k: 2
Output:
10
Explanation:
The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10.
**/
#include <iostream>
#include "../utils.h"
using namespace std;
class Solution {
public:
int findKthNumber(int n, int k) {
}
};
int main() {
Solution s;
return 0;
}
| 16.029412
| 110
| 0.638532
|
zlsun
|
e2149b5c91c3ba0cb374d5e5506b3b243b969ff1
| 1,709
|
hpp
|
C++
|
src/core/Math.hpp
|
bferan/lucent
|
b19163df12739ffc513110d927e92f98c0b54321
|
[
"MIT"
] | 1
|
2021-11-12T08:42:43.000Z
|
2021-11-12T08:42:43.000Z
|
src/core/Math.hpp
|
bferan/lucent
|
b19163df12739ffc513110d927e92f98c0b54321
|
[
"MIT"
] | null | null | null |
src/core/Math.hpp
|
bferan/lucent
|
b19163df12739ffc513110d927e92f98c0b54321
|
[
"MIT"
] | null | null | null |
#pragma once
#include <cmath>
#include "math.h"
namespace lucent
{
constexpr float kPi = 3.14159265358979323846;
constexpr float k2Pi = kPi * 2.0f;
constexpr float kHalfPi = kPi / 2.0f;
// Math wrapper functions:
inline float Sqrt(float x)
{
return std::sqrt(x);
}
inline float Sin(float radians)
{
return std::sin(radians);
}
inline float Asin(float x)
{
return std::asin(x);
}
inline float Cos(float radians)
{
return std::cos(radians);
}
inline float Acos(float x)
{
return std::acos(x);
}
inline float Tan(float radians)
{
return std::tan(radians);
}
inline float Atan(float x)
{
return std::atan(x);
}
inline float Atan2(float x, float y)
{
return std::atan2(x, y);
}
inline float Clamp(float value, float min, float max)
{
return value > min ? (value < max ? value : max) : min;
}
inline float Ceil(float value)
{
return std::ceil(value);
}
inline float Floor(float value)
{
return std::floor(value);
}
inline float Round(float value)
{
return Floor(value + 0.5f);
}
inline float Mod(float value, float by)
{
return std::fmod(value, by);
}
inline float Exp(float value)
{
return std::exp(value);
}
inline float Pow(float base, float exp)
{
return std::powf(base, exp);
}
inline float Abs(float x)
{
return std::abs(x);
}
inline float CopySign(float value, float sign)
{
return std::copysign(value, sign);
}
inline bool Approximately(float x, float y, float epsilon = FLT_EPSILON)
{
return Abs(x - y) <= epsilon;
}
inline float Log2(float x)
{
return std::log2(x);
}
template<typename T>
T Min(T a, T b)
{
return a < b ? a : b;
}
template<typename T>
T Max(T a, T b)
{
return a < b ? b : a;
}
}
| 14.008197
| 72
| 0.647162
|
bferan
|
e216b026375f1dfdaeeb490f3eeb344d5e13abb4
| 1,052
|
cpp
|
C++
|
control/examples/pegel/main.cpp
|
devfix/b15f
|
5a49a37e69cca99359a98e1ef29a83043afed5e5
|
[
"MIT"
] | 1
|
2019-10-26T18:37:49.000Z
|
2019-10-26T18:37:49.000Z
|
control/examples/pegel/main.cpp
|
devfix/b15f
|
5a49a37e69cca99359a98e1ef29a83043afed5e5
|
[
"MIT"
] | null | null | null |
control/examples/pegel/main.cpp
|
devfix/b15f
|
5a49a37e69cca99359a98e1ef29a83043afed5e5
|
[
"MIT"
] | 1
|
2022-03-26T16:06:23.000Z
|
2022-03-26T16:06:23.000Z
|
#include <iostream>
#include <cmath>
#include <b15f/b15f.h>
#include <b15f/plottyfile.h>
/*
* Inkrementiert DAC 0 von 0 bis 1023 und speichert zu jeder Ausgabe den Wert von ADC 0 in einem Puffer.
* Die Funktion ADC 0 abhängig von DAC 0 wird als Graph geplottet.
*/
const char PLOT_FILE[] = "plot.bin";
int main()
{
B15F& drv = B15F::getInstance();
PlottyFile pf;
uint16_t buf[1024];
const uint16_t count = 1024;
const uint16_t delta = 1;
const uint16_t start = 0;
pf.setUnitX("V");
pf.setUnitY("V");
pf.setUnitPara("V");
pf.setDescX("U_{OUT}");
pf.setDescY("U_{IN}");
pf.setDescPara("");
pf.setRefX(5);
pf.setRefY(5);
pf.setParaFirstCurve(0);
pf.setParaStepWidth(0);
const uint8_t curve = 0;
drv.analogSequence(0, &buf[0], 0, 1, nullptr, 0, start, delta, count);
for(uint16_t x = 0; x < count; x++)
{
std::cout << x << " - " << buf[x] << std::endl;
pf.addDot(Dot(x, buf[x], curve));
}
// speichern und plotty starten
pf.writeToFile(PLOT_FILE);
pf.startPlotty(PLOT_FILE);
}
| 21.04
| 104
| 0.635932
|
devfix
|
e21babaa579368d6960e67e4357583b0514be73d
| 17,289
|
cpp
|
C++
|
engine/hltvclient.cpp
|
DannyParker0001/Kisak-Strike
|
99ed85927336fe3aff2efd9b9382b2b32eb1d05d
|
[
"Unlicense"
] | 252
|
2020-12-16T15:34:43.000Z
|
2022-03-31T23:21:37.000Z
|
cstrike15_src/engine/hltvclient.cpp
|
bahadiraraz/Counter-Strike-Global-Offensive
|
9a0534100cb98ffa1cf0c32e138f0e7971e910d3
|
[
"MIT"
] | 23
|
2020-12-20T18:02:54.000Z
|
2022-03-28T16:58:32.000Z
|
cstrike15_src/engine/hltvclient.cpp
|
bahadiraraz/Counter-Strike-Global-Offensive
|
9a0534100cb98ffa1cf0c32e138f0e7971e910d3
|
[
"MIT"
] | 42
|
2020-12-19T04:32:33.000Z
|
2022-03-30T06:00:28.000Z
|
//===== Copyright (c) Valve Corporation, All rights reserved. ======//
//
// hltvclient.cpp: implementation of the CHLTVClient class.
//
// $NoKeywords: $
//
//==================================================================//
#include <tier0/vprof.h>
#include "hltvclient.h"
#include "netmessages.h"
#include "hltvserver.h"
#include "framesnapshot.h"
#include "networkstringtable.h"
#include "dt_send_eng.h"
#include "GameEventManager.h"
#include "cmd.h"
#include "ihltvdirector.h"
#include "host.h"
#include "sv_steamauth.h"
#include "fmtstr.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
static ConVar tv_maxrate( "tv_maxrate", STRINGIFY( DEFAULT_RATE ), FCVAR_RELEASE, "Max GOTV spectator bandwidth rate allowed, 0 == unlimited" );
static ConVar tv_relaypassword( "tv_relaypassword", "", FCVAR_NOTIFY | FCVAR_PROTECTED | FCVAR_DONTRECORD | FCVAR_RELEASE, "GOTV password for relay proxies" );
static ConVar tv_chattimelimit( "tv_chattimelimit", "8", FCVAR_RELEASE, "Limits spectators to chat only every n seconds" );
static ConVar tv_chatgroupsize( "tv_chatgroupsize", "0", FCVAR_RELEASE, "Set the default chat group size" );
extern ConVar replay_debug;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CHLTVClient::CHLTVClient(int slot, CBaseServer *pServer)
{
Clear();
m_nClientSlot = slot;
m_Server = pServer;
m_pHLTV = dynamic_cast<CHLTVServer*>(pServer);
Assert( g_pHltvServer[ m_pHLTV->GetInstanceIndex() ] == pServer );
m_nEntityIndex = slot < 0 ? slot : m_pHLTV->GetHLTVSlot() + 1;
m_nLastSendTick = 0;
m_fLastSendTime = 0.0f;
m_flLastChatTime = 0.0f;
m_bNoChat = false;
if ( tv_chatgroupsize.GetInt() > 0 )
{
Q_snprintf( m_szChatGroup, sizeof(m_szChatGroup), "group%d", slot%tv_chatgroupsize.GetInt() );
}
else
{
Q_strncpy( m_szChatGroup, "all", sizeof(m_szChatGroup) );
}
}
CHLTVClient::~CHLTVClient()
{
}
bool CHLTVClient::SendSignonData( void )
{
// check class table CRCs
if ( m_nSendtableCRC != SendTable_GetCRC() )
{
Disconnect( "Server uses different class tables" );
return false;
}
else
{
// use your class infos, CRC is correct
CSVCMsg_ClassInfo_t classmsg;
classmsg.set_create_on_client( true );
m_NetChannel->SendNetMsg( classmsg );
}
return CBaseClient::SendSignonData();
}
bool CHLTVClient::ProcessSignonStateMsg(int state, int spawncount)
{
if ( !CBaseClient::ProcessSignonStateMsg( state, spawncount ) )
return false;
if ( state == SIGNONSTATE_FULL )
{
// Send all the delayed avatar data to the fully connected client
if ( INetChannel *pMyNetChannel = GetNetChannel() )
{
FOR_EACH_MAP_FAST( m_pHLTV->m_mapPlayerAvatarData, iData )
{
pMyNetChannel->EnqueueVeryLargeAsyncTransfer( *m_pHLTV->m_mapPlayerAvatarData.Element( iData ) );
}
}
}
return true;
}
bool CHLTVClient::CLCMsg_ClientInfo( const CCLCMsg_ClientInfo& msg )
{
if ( !CBaseClient::CLCMsg_ClientInfo( msg ) )
return false;
return true;
}
bool CHLTVClient::CLCMsg_Move( const CCLCMsg_Move& msg )
{
// HLTV clients can't move
return true;
}
bool CHLTVClient::CLCMsg_ListenEvents( const CCLCMsg_ListenEvents& msg )
{
// HLTV clients can't subscribe to events, we just send them
return true;
}
bool CHLTVClient::CLCMsg_RespondCvarValue( const CCLCMsg_RespondCvarValue& msg )
{
return true;
}
bool CHLTVClient::CLCMsg_FileCRCCheck( const CCLCMsg_FileCRCCheck& msg )
{
return true;
}
bool CHLTVClient::CLCMsg_VoiceData(const CCLCMsg_VoiceData& msg)
{
// HLTV clients can't speak
return true;
}
void CHLTVClient::ConnectionClosing(const char *reason)
{
Disconnect ( (reason!=NULL)?reason:"Connection closing" );
}
void CHLTVClient::ConnectionCrashed(const char *reason)
{
Disconnect ( (reason!=NULL)?reason:"Connection lost" );
}
void CHLTVClient::PacketStart(int incoming_sequence, int outgoing_acknowledged)
{
// During connection, only respond if client sends a packet
m_bReceivedPacket = true;
}
void CHLTVClient::PacketEnd()
{
}
void CHLTVClient::FileRequested(const char *fileName, unsigned int transferID, bool bIsReplayDemoFile /* = false */ )
{
DevMsg( "CHLTVClient::FileRequested: %s.\n", fileName );
m_NetChannel->DenyFile( fileName, transferID, bIsReplayDemoFile );
}
void CHLTVClient::FileDenied(const char *fileName, unsigned int transferID, bool bIsReplayDemoFile /* = false */ )
{
DevMsg( "CHLTVClient::FileDenied: %s.\n", fileName );
}
void CHLTVClient::FileReceived( const char *fileName, unsigned int transferID, bool bIsReplayDemoFile /* = false */ )
{
DevMsg( "CHLTVClient::FileReceived: %s.\n", fileName );
}
void CHLTVClient::FileSent( const char *fileName, unsigned int transferID, bool bIsReplayDemoFile /* = false */ )
{
DevMsg( "CHLTVClient::FileSent: %s.\n", fileName );
}
CClientFrame *CHLTVClient::GetDeltaFrame( int nTick )
{
return m_pHLTV->GetDeltaFrame( nTick );
}
bool CHLTVClient::ExecuteStringCommand( const char *pCommandString )
{
// first let the baseclass handle it
if ( CBaseClient::ExecuteStringCommand( pCommandString ) )
return true;
if ( !pCommandString || !pCommandString[0] )
return true;
CCommand args;
if ( !args.Tokenize( pCommandString, kCommandSrcNetServer ) )
return true;
const char *cmd = args[ 0 ];
if ( !Q_stricmp( cmd, "spec_next" ) ||
!Q_stricmp( cmd, "spec_prev" ) ||
!Q_stricmp( cmd, "spec_mode" ) ||
!Q_stricmp( cmd, "spec_goto" ) ||
!Q_stricmp( cmd, "spec_lerpto" ) )
{
ClientPrintf("Camera settings can't be changed during a live broadcast.\n");
return true;
}
if ( !Q_stricmp( cmd, "say" ) && args.ArgC() > 1 )
{
// if tv_chattimelimit = 0, chat is turned off
if ( tv_chattimelimit.GetFloat() <= 0 )
return true;
if ( (m_flLastChatTime + tv_chattimelimit.GetFloat()) > net_time )
return true;
m_flLastChatTime = net_time;
// Check if chat is non-empty string
bool bValidText = false;
for ( char const *szChatMsg = args[1]; szChatMsg && *szChatMsg; ++ szChatMsg )
{
if ( !V_isspace( *szChatMsg ) )
{
bValidText = true;
break;
}
}
if ( !bValidText )
return true;
char chattext[128];
V_sprintf_safe( chattext, "%s : %s", GetClientName(), args[1] );
m_pHLTV->BroadcastLocalChat( chattext, m_szChatGroup );
return true;
}
else if ( !Q_strcmp( cmd, "tv_chatgroup" ) )
{
if ( args.ArgC() > 1 )
{
Q_strncpy( m_szChatGroup, args[1], sizeof(m_szChatGroup) );
}
else
{
ClientPrintf("Your current chat group is \"%s\"\n", m_szChatGroup );
}
return true;
}
else if ( !Q_strcmp( cmd, "status" ) )
{
int slots, proxies, clients;
char gd[MAX_OSPATH];
Q_FileBase( com_gamedir, gd, sizeof( gd ) );
if ( m_pHLTV->IsMasterProxy() )
{
ClientPrintf("GOTV Master \"%s\", delay %.0f\n",
m_pHLTV->GetName(), m_pHLTV->GetDirector()->GetDelay() );
}
else // if ( m_Server->IsRelayProxy() )
{
if ( m_pHLTV->GetRelayAddress() )
{
ClientPrintf("GOTV Relay \"%s\", connected.\n",
m_pHLTV->GetName() );
}
else
{
ClientPrintf("GOTV Relay \"%s\", not connect.\n", m_pHLTV->GetName() );
}
}
ClientPrintf("IP %s:%i, Online %s, Version %i (%s)\n",
net_local_adr.ToString( true ), m_pHLTV->GetUDPPort(),
COM_FormatSeconds( m_pHLTV->GetOnlineTime() ), build_number(),
#ifdef _WIN32
"Win32" );
#else
"Linux" );
#endif
ClientPrintf("Game Time %s, Mod \"%s\", Map \"%s\", Players %i\n", COM_FormatSeconds( m_pHLTV->GetTime() ),
gd, m_pHLTV->GetMapName(), m_pHLTV->GetNumPlayers() );
m_pHLTV->GetLocalStats( proxies, slots, clients );
ClientPrintf("Local Slots %i, Spectators %i, Proxies %i\n",
slots, clients-proxies, proxies );
m_pHLTV->GetGlobalStats( proxies, slots, clients);
ClientPrintf("Total Slots %i, Spectators %i, Proxies %i\n",
slots, clients-proxies, proxies);
m_pHLTV->GetExternalStats( slots, clients );
if ( slots > 0 )
{
if ( clients > 0 )
ClientPrintf( "Streaming spectators %i, linked to Steam %i\n", slots, clients );
else
ClientPrintf( "Streaming spectators %i\n", slots );
}
}
else
{
DevMsg( "CHLTVClient::ExecuteStringCommand: Unknown command %s.\n", pCommandString );
}
return true;
}
bool CHLTVClient::ShouldSendMessages( void )
{
if ( !IsActive() )
{
// during signon behave like normal client
return CBaseClient::ShouldSendMessages();
}
// HLTV clients use snapshot rate used by HLTV server, not given by HLTV client
// if the reliable message overflowed, drop the client
if ( m_NetChannel->IsOverflowed() )
{
m_NetChannel->Reset();
Disconnect( CFmtStr( "%s overflowed reliable buffer", m_Name ) );
return false;
}
// send a packet if server has a new tick we didn't already send
bool bSendMessage = ( m_nLastSendTick != m_Server->m_nTickCount );
// send a packet at least every 2 seconds
if ( !bSendMessage && (m_fLastSendTime + 2.0f) < net_time )
{
bSendMessage = true; // force sending a message even if server didn't update
}
if ( bSendMessage && !m_NetChannel->CanPacket() )
{
// we would like to send a message, but bandwidth isn't available yet
// in HLTV we don't send choke information, doesn't matter
bSendMessage = false;
}
return bSendMessage;
}
void CHLTVClient::SpawnPlayer( void )
{
// set view entity
CSVCMsg_SetView_t setView;
setView.set_entity_index( m_pHLTV->m_nViewEntity );
SendNetMsg( setView );
m_pHLTV->BroadcastLocalTitle( this );
m_flLastChatTime = net_time;
CBaseClient::SpawnPlayer();
}
void CHLTVClient::SetRate(int nRate, bool bForce )
{
if ( !bForce )
{
if ( m_bIsHLTV )
{
// allow higher bandwidth rates for HLTV proxies
nRate = clamp( nRate, MIN_RATE, MAX_RATE );
}
else if ( tv_maxrate.GetInt() > 0 )
{
// restrict rate for normal clients to hltv_maxrate
nRate = clamp( nRate, MIN_RATE, tv_maxrate.GetInt() );
}
}
CBaseClient::SetRate( nRate, bForce );
}
void CHLTVClient::SetUpdateRate( float fUpdateRate, bool bForce)
{
// for HLTV clients ignore update rate settings, speed is tv_snapshotrate
m_fSnapshotInterval = 1.0f / m_pHLTV->GetSnapshotRate();
}
bool CHLTVClient::NETMsg_SetConVar(const CNETMsg_SetConVar& msg)
{
if ( !CBaseClient::NETMsg_SetConVar( msg ) )
return false;
// if this is the first time we get user settings, check password etc
if ( GetSignonState() == SIGNONSTATE_CONNECTED )
{
// Note: the master client of HLTV server will replace the rate ConVars for us. It's necessary so that demo recorder can take those frames from the master client and write them with values already modified
m_bIsHLTV = m_ConVars->GetInt( "tv_relay", 0 ) != 0;
if ( m_bIsHLTV )
{
// The connecting client is a TV relay
// Check if this relay address is whitelisted by IP range mask and bypasses all checks
extern bool IsHltvRelayProxyWhitelisted( ns_address const &adr );
if ( IsHltvRelayProxyWhitelisted( m_NetChannel->GetRemoteAddress() ) )
{
Msg( "Accepted GOTV relay proxy from whitelisted IP address: %s\n", m_NetChannel->GetAddress() );
}
// if the connecting client is a TV relay, check the password
else if ( !m_pHLTV->CheckHltvPasswordMatch( m_szPassword, m_pHLTV->GetHltvRelayPassword(), CSteamID() ) )
{
Disconnect("Bad relay password");
return false;
}
}
else
{
// if client is a normal spectator, check if we can to forward him to other relays
if ( m_pHLTV->DispatchToRelay( this ) )
{
return false;
}
// if we are not dispatching the client to other relay and we are the master server then validate
// the number of non-proxy clients
extern ConVar tv_maxclients_relayreserved;
if ( tv_maxclients_relayreserved.GetInt() )
{
int numActualNonProxyAccounts = 0;
for (int i=0; i < m_pHLTV->GetClientCount(); i++ )
{
CBaseClient *pProxy = static_cast< CBaseClient * >( m_pHLTV->GetClient( i ) );
// check if this is a proxy
if ( !pProxy->IsConnected() || pProxy->IsHLTV() || (this == pProxy) )
continue;
++ numActualNonProxyAccounts;
}
if ( numActualNonProxyAccounts > m_pHLTV->GetMaxClients() - tv_maxclients_relayreserved.GetInt() )
{
this->Disconnect( "No GOTV relays available" );
return false;
}
}
// if client stays here, check the normal password
// additionally if the first variable is client accountid then use that to validate personalized password
CSteamID steamUserAccountID;
if ( Steam3Server().SteamGameServerUtils() &&
( msg.convars().cvars_size() > 1 ) &&
!Q_strcmp( NetMsgGetCVarUsingDictionary( msg.convars().cvars( 0 ) ), "accountid" ) )
steamUserAccountID = CSteamID( Q_atoi( msg.convars().cvars( 0 ).value().c_str() ), Steam3Server().SteamGameServerUtils()->GetConnectedUniverse(), k_EAccountTypeIndividual );
if ( !m_pHLTV->CheckHltvPasswordMatch( m_szPassword, m_pHLTV->GetPassword(), steamUserAccountID ) )
{
Disconnect("Bad spectator password");
return false;
}
// check if server is LAN only
if ( !m_pHLTV->CheckIPRestrictions( m_NetChannel->GetRemoteAddress(), PROTOCOL_HASHEDCDKEY ) )
{
Disconnect( "GOTV server is restricted to local spectators (class C).\n" );
return false;
}
}
}
return true;
}
void CHLTVClient::UpdateUserSettings()
{
// set voice loopback
m_bNoChat = m_ConVars->GetInt( "tv_nochat", 0 ) != 0;
CBaseClient::UpdateUserSettings();
}
bool CHLTVClient::SendSnapshot( CClientFrame * pFrame )
{
VPROF_BUDGET( "CHLTVClient::SendSnapshot", "HLTV" );
byte buf[NET_MAX_PAYLOAD];
bf_write msg( "CHLTVClient::SendSnapshot", buf, sizeof(buf) );
// if we send a full snapshot (no delta-compression) before, wait until client
// received and acknowledge that update. don't spam client with full updates
if ( m_pLastSnapshot == pFrame->GetSnapshot() )
{
// never send the same snapshot twice
m_NetChannel->Transmit();
return false;
}
if ( m_nForceWaitForTick > 0 )
{
// just continue transmitting reliable data
Assert( !m_bFakePlayer ); // Should never happen
m_NetChannel->Transmit();
return false;
}
CClientFrame *pDeltaFrame = GetDeltaFrame( m_nDeltaTick ); // NULL if delta_tick is not found
CHLTVFrame *pLastFrame = (CHLTVFrame*) GetDeltaFrame( m_nLastSendTick );
if ( pLastFrame )
{
// start first frame after last send
pLastFrame = (CHLTVFrame*) pLastFrame->m_pNext;
}
// add all reliable messages between ]lastframe,currentframe]
// add all tempent & sound messages between ]lastframe,currentframe]
while ( pLastFrame && pLastFrame->tick_count <= pFrame->tick_count )
{
m_NetChannel->SendData( pLastFrame->m_Messages[HLTV_BUFFER_RELIABLE], true );
if ( pDeltaFrame )
{
// if we send entities delta compressed, also send unreliable data
m_NetChannel->SendData( pLastFrame->m_Messages[HLTV_BUFFER_UNRELIABLE], false );
m_NetChannel->SendData( pLastFrame->m_Messages[ HLTV_BUFFER_VOICE ], false ); // we separate voice, even though it's simply more unreliable data, because we don't send it in replay
}
pLastFrame = (CHLTVFrame*) pLastFrame->m_pNext;
}
// now create client snapshot packet
// send tick time
CNETMsg_Tick_t tickmsg( pFrame->tick_count, host_frameendtime_computationduration, host_frametime_stddeviation, host_framestarttime_stddeviation );
tickmsg.WriteToBuffer( msg );
// Update shared client/server string tables. Must be done before sending entities
m_Server->m_StringTables->WriteUpdateMessage( NULL, GetMaxAckTickCount(), msg );
// TODO delta cache whole snapshots, not just packet entities. then use net_Align
// send entity update, delta compressed if deltaFrame != NULL
{
CSVCMsg_PacketEntities_t packetmsg;
m_Server->WriteDeltaEntities( this, pFrame, pDeltaFrame, packetmsg );
packetmsg.WriteToBuffer( msg );
}
// write message to packet and check for overflow
if ( msg.IsOverflowed() )
{
if ( !pDeltaFrame )
{
// if this is a reliable snapshot, drop the client
Disconnect( "ERROR! Reliable snapshot overflow." );
return false;
}
else
{
// unreliable snapshots may be dropped
ConMsg ("WARNING: msg overflowed for %s\n", m_Name);
msg.Reset();
}
}
// remember this snapshot
m_pLastSnapshot = pFrame->GetSnapshot();
m_nLastSendTick = pFrame->tick_count;
// Don't send the datagram to fakeplayers
if ( m_bFakePlayer )
{
m_nDeltaTick = pFrame->tick_count;
return true;
}
bool bSendOK;
// is this is a full entity update (no delta) ?
if ( !pDeltaFrame )
{
if ( replay_debug.GetInt() >= 10 )
Msg( "HLTV send full frame %d bytes\n", ( msg.m_iCurBit + 7 ) / 8 );
// transmit snapshot as reliable data chunk
bSendOK = m_NetChannel->SendData( msg );
bSendOK = bSendOK && m_NetChannel->Transmit();
// remember this tickcount we send the reliable snapshot
// so we can continue sending other updates if this has been acknowledged
m_nForceWaitForTick = pFrame->tick_count;
}
else
{
if ( replay_debug.GetInt() >= 10 )
Msg( "HLTV send datagram %d bytes\n", ( msg.m_iCurBit + 7 ) / 8 );
// just send it as unreliable snapshot
bSendOK = m_NetChannel->SendDatagram( &msg ) > 0;
}
if ( !bSendOK )
{
Disconnect( "ERROR! Couldn't send snapshot." );
return false;
}
return true;
}
| 28.066558
| 208
| 0.692116
|
DannyParker0001
|
e21c6fa48127900170983abd4d0f273513c10bf7
| 44,201
|
cpp
|
C++
|
deprecated-code/Ajisai/Integrators/BidirectionalPath.cpp
|
siyuanpan/ajisai_render
|
203d79235bf698c1a4a747be291c0f3050b213da
|
[
"MIT"
] | null | null | null |
deprecated-code/Ajisai/Integrators/BidirectionalPath.cpp
|
siyuanpan/ajisai_render
|
203d79235bf698c1a4a747be291c0f3050b213da
|
[
"MIT"
] | null | null | null |
deprecated-code/Ajisai/Integrators/BidirectionalPath.cpp
|
siyuanpan/ajisai_render
|
203d79235bf698c1a4a747be291c0f3050b213da
|
[
"MIT"
] | null | null | null |
/*
Copyright 2021 Siyuan Pan <pansiyuan.cs@gmail.com>
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 <Ajisai/Core/BSDF.h>
#include <Ajisai/Core/Geometry.h>
#include <Ajisai/Integrators/Integrator.h>
#include <Ajisai/Integrators/BidirectionalPath.h>
#include <cstring>
// using Ajisai::Core::CameraSamplingRecord;
// using Ajisai::Core::Intersect;
// using Ajisai::Core::LightSamplingRecord;
// using Ajisai::Core::SurfaceInteraction;
// using Ajisai::Core::VisibilityTester;
using namespace Ajisai::Math;
using namespace Ajisai::Core;
namespace Ajisai::Integrators {
// template <typename T>
// class ScopedAssignment {
// T* target = nullptr;
// T backup;
// public:
// ScopedAssignment() : target(nullptr), backup(T()) {}
// ScopedAssignment(T* target, T value) : target(target) {
// if (target) {
// backup = *target;
// *target = value;
// }
// }
// ~ScopedAssignment() {
// if (target) *target = backup;
// }
// ScopedAssignment(ScopedAssignment&&) = delete;
// ScopedAssignment(const ScopedAssignment&) = delete;
// ScopedAssignment& operator=(const ScopedAssignment&) = delete;
// ScopedAssignment& operator=(ScopedAssignment&& other) noexcept {
// if (target) *target = backup;
// target = other.target;
// backup = other.backup;
// other.target = nullptr;
// return *this;
// }
// };
// struct EndpointInteraction : Intersect {
// using Intersect::Intersect;
// // Math::Vector3f p;
// union {
// const Core::Camera* camera;
// const Core::AreaLight* light;
// };
// EndpointInteraction() : light{nullptr} {}
// EndpointInteraction(const Core::Ray& ray)
// : Intersect(ray.Point(1)), light(nullptr) {}
// EndpointInteraction(const Core::Camera* camera, const Core::Ray& ray)
// : Intersect(ray.o), camera(camera) {}
// EndpointInteraction(const Core::AreaLight* light, const Core::Ray& ray)
// : Intersect(ray.o), light(light) {}
// // EndpointInteraction(const Core::Camera* camera, const Math::Vector3f& p)
// // : Intersect(p), camera(camera) {}
// EndpointInteraction(const Core::AreaLight* light, const Core::Ray& r,
// const Math::Vector3f& nl)
// : Intersect(r.o), light(light) {
// Ng = nl;
// }
// };
// enum class VertexType { Camera, Light, Surface };
// enum class TransportMode { Radiance, Importance };
// struct PathVertex {
// VertexType type;
// Math::Spectrum beta;
// union {
// EndpointInteraction ei;
// SurfaceInteraction si;
// };
// bool delta = false;
// float pdfFwd = 0, pdfRev = 0;
// PathVertex() : ei() {}
// PathVertex(VertexType type, const EndpointInteraction& ei,
// const Math::Spectrum& beta)
// : type(type), beta(beta), ei(ei) {}
// PathVertex(const SurfaceInteraction& si, const Math::Spectrum& beta)
// : type(VertexType::Surface), beta(beta), si(si) {}
// ~PathVertex() {}
// PathVertex(const PathVertex& v) { memcpy(this, &v, sizeof(PathVertex)); }
// PathVertex& operator=(const PathVertex& v) {
// memcpy(this, &v, sizeof(PathVertex));
// return *this;
// }
// const Intersect& GetInteraction() const {
// switch (type) {
// case VertexType::Surface:
// return si;
// default:
// return ei;
// }
// }
// const auto& p() const { return GetInteraction().p; }
// const auto& ng() const { return GetInteraction().Ng; }
// [[nodiscard]] Math::Vector3f Ns() const {
// if (type == VertexType::Surface) {
// return si.Ns;
// } else if (type == VertexType::Light || type == VertexType::Camera) {
// return ei.Ng;
// } else {
// return {};
// }
// }
// bool IsOnSurface() const { return ng() != Math::Vector3f{0.f}; }
// bool IsConnectible() const {
// switch (type) {
// case VertexType::Light:
// return true;
// case VertexType::Camera:
// return true;
// case VertexType::Surface:
// return !delta;
// }
// return false; // NOTREACHED
// }
// float PdfLightOrigin(const Core::Scene& scene, const PathVertex& next) {
// const Core::AreaLight* light = ei.light;
// if (!light) {
// return 0.0f;
// }
// auto w = next.p() - p();
// w = w.normalized();
// float pdfPos = 0, pdfDir = 0;
// light->Pdf_Le(Core::Ray(p(), w), &pdfPos, &pdfDir);
// return scene.PdfLight(light) * pdfPos;
// }
// Math::Spectrum Le(const PathVertex& next) const {
// switch (type) {
// case VertexType::Surface: {
// auto wo = (next.p() - p()).normalized();
// return si.Le(wo);
// }
// case VertexType::Light: {
// auto* light = ei.light;
// auto wo = (next.p() - p()).normalized();
// return light->Li(wo);
// }
// case VertexType::Camera:
// default:
// return Math::Spectrum{0.f};
// }
// }
// float Pdf(const Core::Scene& scene, const PathVertex* prev,
// const PathVertex& next) {
// if (type == VertexType::Light) {
// return PdfLight(scene, next);
// }
// auto wn = next.p() - p();
// if (Math::dot(wn, wn) == 0) return 0;
// wn = wn.normalized();
// Math::Vector3f wp;
// if (prev) {
// wp = prev->p() - p();
// if (Math::dot(wp, wp) == 0) return 0;
// wp = wp.normalized();
// } else {
// assert(type == VertexType::Camera);
// }
// float pdf = 0;
// if (type == VertexType::Surface) {
// auto wo = si.bsdf->toLocal(-wp);
// auto wi = si.bsdf->toLocal(wn);
// pdf = si.bsdf->EvaluatePdf(wo, wi);
// } else if (type == VertexType::Camera) {
// auto* camera = ei.camera;
// float _;
// camera->Pdf_We(ei.SpawnRay(wn), &_, &pdf);
// } else {
// std::exit(1);
// }
// return ConvertDensity(pdf, next);
// }
// float PdfLight(const Core::Scene& scene, const PathVertex& next) {
// const Core::AreaLight* light = ei.light;
// if (!light) {
// return 0;
// }
// auto w = next.p() - p();
// float invDist2 = 1 / Math::dot(w, w);
// w = w.normalized();
// float pdf;
// float pdfPos = 0, pdfDir = 0;
// light->Pdf_Le(Core::Ray(p(), w), &pdfPos, &pdfDir);
// pdf = pdfDir * invDist2;
// if (next.IsOnSurface()) {
// pdf *= std::abs(Math::dot(next.ng(), w));
// }
// return pdf;
// }
// Math::Spectrum f(const PathVertex& next) const {
// auto wi = (next.p() - p()).normalized();
// switch (type) {
// case VertexType::Surface: {
// return si.bsdf->Evaluate(si.wo, wi);
// }
// default:
// return {};
// }
// }
// float ConvertDensity(float pdf, const PathVertex& next) const {
// // Return solid angle density if _next_ is an infinite area light
// // if (next.IsInfiniteLight()) return pdf;
// auto w = next.p() - p();
// if (Math::dot(w, w) == 0) return 0;
// float invDist2 = 1 / Math::dot(w, w);
// w = w.normalized();
// if (next.IsOnSurface()) pdf *= std::abs(Math::dot(next.ng(), w));
// // pdf *= std::abs(Math::dot(next.ng(), w * std::sqrt(invDist2)));
// return pdf * invDist2;
// }
// static inline PathVertex CreateCamera(const Core::Camera* camera,
// const Core::Ray& ray,
// const Math::Spectrum& beta);
// static inline PathVertex CreateLight(const EndpointInteraction& ei,
// const Math::Spectrum& beta, float
// pdf);
// static inline PathVertex CreateSurface(const SurfaceInteraction& si,
// const Math::Spectrum& beta, float
// pdf, const PathVertex& prev);
// static inline PathVertex CreateLight(const Core::AreaLight* light,
// const Core::Ray& ray,
// const Math::Vector3f& N,
// const Math::Spectrum& Le, float pdf);
// static inline PathVertex CreateCamera(const Core::Camera* camera,
// const Math::Vector3f& p,
// const Math::Spectrum& beta);
// static Math::Spectrum G(const Core::Scene& scene, const PathVertex& v0,
// const PathVertex& v1) {
// auto d = v0.p() - v1.p();
// float g = 1 / Math::dot(d, d);
// // d *= std::sqrt(g);
// d = d.normalized();
// if (v0.IsOnSurface()) g *= std::abs(Math::dot(v0.Ns(), d));
// if (v1.IsOnSurface()) g *= std::abs(Math::dot(v1.Ns(), d));
// VisibilityTester vis(v0.GetInteraction(), v1.GetInteraction());
// return g * vis.Tr(scene);
// }
// };
// inline PathVertex PathVertex::CreateCamera(const Core::Camera* camera,
// const Core::Ray& ray,
// const Math::Spectrum& beta) {
// return PathVertex(VertexType::Camera, EndpointInteraction(camera, ray),
// beta);
// }
// inline PathVertex PathVertex::CreateLight(const EndpointInteraction& ei,
// const Math::Spectrum& beta,
// float pdf) {
// PathVertex v(VertexType::Light, ei, beta);
// v.pdfFwd = pdf;
// return v;
// }
// inline PathVertex PathVertex::CreateSurface(const SurfaceInteraction& si,
// const Math::Spectrum& beta,
// float pdf, const PathVertex&
// prev) {
// PathVertex v(si, beta);
// v.pdfFwd = prev.ConvertDensity(pdf, v);
// return v;
// }
// inline PathVertex PathVertex::CreateLight(const Core::AreaLight* light,
// const Core::Ray& ray,
// const Math::Vector3f& N,
// const Math::Spectrum& Le, float
// pdf) {
// PathVertex v(VertexType::Light, EndpointInteraction(light, ray, N), Le);
// v.pdfFwd = pdf;
// return v;
// }
// inline PathVertex PathVertex::CreateCamera(const Core::Camera* camera,
// const Math::Vector3f& p,
// const Math::Spectrum& beta) {
// return PathVertex(VertexType::Camera, EndpointInteraction(camera, p),
// beta);
// }
// class BDPTIntegrator : public Integrator {
// public:
// explicit BDPTIntegrator(PluginManager::AbstractManager& manager,
// const std::string plugin)
// : Integrator{manager, plugin} {}
// struct Vertex {
// Spectrum throughput;
// uint32_t length;
// SurfaceInteraction si;
// Vector3f inDir;
// float DVCM;
// float DVC;
// };
// struct PathState {
// Vector3f origin;
// Vector3f direction;
// Spectrum throughput;
// uint PathLength : 30;
// bool isFiniteLight : 1;
// bool SpecularPath : 1;
// float DVCM;
// float DVC;
// };
// size_t RandomWalk(const Core::Scene& scene, Core::Sampler& sampler,
// Core::Ray& ray, Math::Spectrum& beta, float pdf,
// size_t depth, TransportMode mode, PathVertex* path) const
// {
// using Core::BSDFSamplingRecord;
// using Core::BSDFType;
// if (depth == 0) return 0;
// int bounces = 0;
// float pdfFwd = pdf, pdfRev = 0.f;
// while (true) {
// Core::Intersection isect;
// bool foundIntersection = scene.Intersect(ray, &isect);
// if (beta.isBlack()) break;
// auto& vertex = path[bounces];
// auto& prev = path[bounces - 1];
// if (!foundIntersection) {
// // if (mode == TransportMode::Radiance) {
// // vertex =
// // PathVertex::CreateLight(EndpointInteraction(ray), beta,
// // pdfFwd);
// // ++bounces;
// // }
// break;
// }
// Core::Triangle triangle{};
// isect.mesh->GetTriangle(isect.triId, &triangle);
// auto p = ray.Point(isect.t);
// SurfaceInteraction si(-ray.d, p, triangle, isect);
// isect.mesh->GetMaterial()->ComputeScatteringFunction(&si);
// vertex = PathVertex::CreateSurface(si, beta, pdfFwd, prev);
// if (++bounces >= depth) break;
// Math::Vector3f wi, wo = si.wo;
// BSDFSamplingRecord bRec(si, sampler.Next2D());
// si.bsdf->Sample(bRec);
// if (bRec.pdf <= 0.f) break;
// pdfFwd = bRec.pdf;
// wi = si.bsdf->toWorld(bRec.wi);
// beta *= bRec.f * std::abs(Math::dot(wi, si.Ns)) / bRec.pdf;
// pdfRev = si.bsdf->EvaluatePdf(bRec.wi, bRec.wo);
// if (bRec.type & BSDFType::BSDF_SPECULAR) {
// vertex.delta = true;
// pdfFwd = pdfRev = 0.f;
// }
// ray = si.SpawnRay(wi);
// prev.pdfRev = vertex.ConvertDensity(pdfRev, prev);
// }
// return bounces;
// }
// size_t GenerateCameraSubpath(const Core::Scene& scene,
// const Core::Camera& camera,
// const Math::Vector2i& raster,
// Core::Sampler& sampler, size_t depth,
// PathVertex* path) const {
// if (depth == 0) return 0;
// // const float u =
// // (raster.x() + sampler.Next1D()) /
// camera.GetFilm()->Dimension().x();
// // const float v =
// // (raster.y() + sampler.Next1D()) /
// camera.GetFilm()->Dimension().y();
// // auto ray = camera.GenerateRay(u, v);
// auto ray = camera.GenerateRay(sampler.Next2D(), sampler.Next2D(),
// raster); auto beta = Math::Spectrum(1);
// float pdfPos, pdfDir;
// path[0] = PathVertex::CreateCamera(&camera, ray, beta);
// camera.Pdf_We(ray, &pdfPos, &pdfDir);
// if (pdfDir <= 0 || pdfPos <= 0) {
// return 0;
// }
// return RandomWalk(scene, sampler, ray, beta, pdfDir, depth - 1,
// TransportMode::Importance, path + 1) +
// 1;
// }
// size_t GenerateLightSubpath(const Core::Scene& scene, Core::Sampler&
// sampler,
// size_t depth, PathVertex* path) const {
// if (depth == 0) return 0;
// float lightPdf = 0.f;
// auto sampleLight = scene.SampleOneLight(sampler.Next1D(), &lightPdf);
// Core::Ray ray;
// Math::Vector3f nLight;
// float pdfPos, pdfDir;
// Math::Spectrum Le;
// sampleLight->Sample_Le(sampler.Next2D(), sampler.Next2D(), &ray, nLight,
// &pdfPos, &pdfDir, Le);
// if (lightPdf <= 0 || pdfPos <= 0 || pdfDir <= 0 || Le.isBlack()) {
// return 0;
// }
// path[0] = PathVertex::CreateLight(sampleLight, ray, nLight, Le,
// pdfPos * lightPdf);
// Math::Spectrum beta =
// Le * std::abs(Math::dot(nLight, ray.d)) / (lightPdf * pdfPos *
// pdfDir);
// return 1 + RandomWalk(scene, sampler, ray, beta, pdfDir, depth - 1,
// TransportMode::Radiance, path + 1);
// }
// template <int Power>
// float MisWeight(const Core::Scene& scene, Core::Sampler& sampler,
// PathVertex* cameraVertices, size_t t,
// PathVertex* lightVertices, size_t s,
// PathVertex& sampled) const {
// if (s + t == 2) return 1;
// auto remap0 = [](float x) -> float {
// return x != 0 ? std::pow(x, Power) : 1.0f;
// };
// (void)remap0;
// float sumRi = 0;
// // p_0 ... pt qs ... q_0
// auto* pt = t > 0 ? &cameraVertices[t - 1] : nullptr;
// auto* qs = s > 0 ? &lightVertices[s - 1] : nullptr;
// auto* ptMinus = t > 1 ? &cameraVertices[t - 2] : nullptr;
// auto* qsMinus = s > 1 ? &lightVertices[s - 2] : nullptr;
// ScopedAssignment<PathVertex> _a1;
// if (s == 1)
// _a1 = {qs, sampled};
// else if (t == 1)
// _a1 = {pt, sampled};
// // if (s == 1) {
// // printf("b %f\n", lightVertices[s - 1].pdfFwd);
// // }
// ScopedAssignment<bool> _a2, _a3;
// if (pt) _a2 = {&pt->delta, false};
// if (qs) _a3 = {&qs->delta, false};
// // now connect pt to qs
// // we need to compute pt->pdfRev
// // segfault ?
// ScopedAssignment<float> _a4;
// if (pt) {
// float pdfRev;
// if (s > 0) {
// pdfRev = qs->Pdf(scene, qsMinus, *pt);
// } else {
// pdfRev = pt->PdfLightOrigin(scene, *ptMinus);
// }
// // if (s != 0)
// // printf("before rev %f s %d pdfRev %f\n", pt->pdfRev, (int)s,
// pdfRev); _a4 = {&pt->pdfRev, pdfRev};
// }
// // if (pt) printf("after rev %f\n", pt->pdfRev);
// // now ptMinus->pdfRev
// ScopedAssignment<float> _a5;
// // if (ptMinus) printf("before rev %f\n", ptMinus->pdfRev);
// if (ptMinus) {
// float pdfRev;
// if (s > 0) {
// pdfRev = pt->Pdf(scene, qs, *ptMinus);
// } else {
// pdfRev = pt->PdfLight(scene, *ptMinus);
// }
// _a5 = {&ptMinus->pdfRev, pdfRev};
// }
// // if (ptMinus) printf("after rev %f\n", ptMinus->pdfRev);
// // now qs
// ScopedAssignment<float> _a6;
// if (qs) {
// _a6 = {&qs->pdfRev, pt->Pdf(scene, ptMinus, *qs)};
// }
// // printf("%f\n", sampled.pdfFwd);
// // now qsMinus
// ScopedAssignment<float> _a7;
// if (qsMinus) {
// _a7 = {&qsMinus->pdfRev, qs->Pdf(scene, pt, *qsMinus)};
// }
// float ri = 1;
// for (int i = (int)t - 1; i > 0; i--) {
// ri *= remap0(cameraVertices[i].pdfRev) /
// remap0(cameraVertices[i].pdfFwd); if (!cameraVertices[i].delta &&
// !cameraVertices[i - 1].delta) {
// sumRi += ri;
// }
// }
// ri = 1;
// for (int i = (int)s - 1; i >= 0; i--) {
// ri *= remap0(lightVertices[i].pdfRev) /
// remap0(lightVertices[i].pdfFwd); bool delta = i > 0 ? lightVertices[i -
// 1].delta
// : false /*lightVertices[i].IsDeltaLight()*/;
// if (!lightVertices[i].delta && !delta) {
// sumRi += ri;
// }
// }
// return 1.0 / (1.0 + sumRi);
// }
// Math::Spectrum ConnectPath(const Core::Scene& scene, Core::Sampler&
// sampler,
// PathVertex* cameraVertices, size_t t,
// PathVertex* lightVertices, size_t s,
// Math::Vector2f* pRaster) const {
// if (t > 1 && s != 0 && cameraVertices[t - 1].type == VertexType::Light)
// return Math::Spectrum(0.f);
// Math::Spectrum L(0.f);
// PathVertex sampled{};
// if (s == 0) {
// const PathVertex& pt = cameraVertices[t - 1];
// L = pt.Le(cameraVertices[t - 2]) * pt.beta;
// } else if (t == 1) {
// const PathVertex& qs = lightVertices[s - 1];
// auto camera = cameraVertices[0].ei.camera;
// if (qs.IsConnectible()) {
// VisibilityTester vis;
// CameraSamplingRecord cRec;
// camera->Sample_Wi(sampler.Next2D(), qs.GetInteraction(), &cRec,
// &vis); *pRaster = cRec.pos; if (cRec.pdf > 0 && !cRec.I.isBlack()) {
// // Initialize dynamically sampled vertex and _L_ for $t=1$ case
// sampled = PathVertex::CreateCamera(camera, vis.shadowRay,
// cRec.I / cRec.pdf);
// L = qs.beta * qs.f(sampled) * sampled.beta;
// if (qs.IsOnSurface()) L *= std::abs(Math::dot(cRec.wi, qs.Ns()));
// // Only check visibility after we know that the path would
// // make a non-zero contribution.
// if (!L.isBlack()) L *= vis.Tr(scene);
// }
// }
// } else if (s == 1) {
// // Sample a point on a light and connect it to the camera subpath
// const PathVertex& pt = cameraVertices[t - 1];
// auto& lightVertex = lightVertices[0];
// if (pt.IsConnectible()) {
// float lightPdf;
// VisibilityTester vis;
// LightSamplingRecord lRec;
// lightVertex.ei.light->Sample_Li(sampler.Next2D(),
// pt.GetInteraction(),
// lRec, vis);
// const Core::AreaLight* light = lightVertex.ei.light;
// if (lRec.pdf > 0 && !lRec.Li.isBlack()) {
// EndpointInteraction ei(light, vis.shadowRay);
// sampled = PathVertex::CreateLight(
// ei, lRec.Li / (scene.PdfLight(light) * lRec.pdf), 0);
// sampled.pdfFwd = sampled.PdfLightOrigin(scene, pt);
// L = pt.beta * pt.f(sampled) * sampled.beta;
// if (pt.IsOnSurface()) L *= std::abs(Math::dot(lRec.wi, pt.Ns()));
// // Only check visibility if the path would carry radiance.
// if (!L.isBlack()) L *= vis.Tr(scene);
// }
// }
// } else {
// // Handle all other bidirectional connection cases
// const PathVertex &qs = lightVertices[s - 1], &pt = cameraVertices[t -
// 1]; if (qs.IsConnectible() && pt.IsConnectible()) {
// L = qs.beta * qs.f(pt) * pt.f(qs) * pt.beta;
// // VLOG(2) << "General connect s: " << s << ", t: " << t << " qs: "
// <<
// // qs
// // << ", pt: " << pt
// // << ", qs.f(pt): " << qs.f(pt, TransportMode::Importance)
// // << ", pt.f(qs): " << pt.f(qs, TransportMode::Radiance)
// // << ", G: " << G(scene, sampler, qs, pt)
// // << ", dist^2: " << DistanceSquared(qs.p(), pt.p());
// if (!L.isBlack()) L *= PathVertex::G(scene, qs, pt);
// }
// }
// if (L.isBlack()) return {};
// float misWeight = 1.0f / (s + t);
// // if (s == 1) printf("t %d s %d\n", (int)t, (int)s);
// misWeight = MisWeight<1>(scene, sampler, cameraVertices, t,
// lightVertices,
// s, sampled);
// assert(misWeight >= 0);
// L *= misWeight;
// return L.removeNaN();
// }
template <int pow>
float MIS(float fVal) {
// Use power heuristic
return std::pow(fVal, pow);
}
BDPTIntegrator::PathState BDPTIntegrator::SampleLightSource(Scene* scene,
Sampler* sampler) {
PathState ret;
float lightPdf = 0.f;
auto sampleLight = scene->SampleOneLight(sampler->Next1D(), &lightPdf);
// printf("lightPdf %f\n", lightPdf);
Ray lightRay;
Vector3f nLight;
float posPdf, dirPdf;
sampleLight->Sample_Le(sampler->Next2D(), sampler->Next2D(), &lightRay,
nLight, &posPdf, &dirPdf, ret.throughput);
// printf(
// "ray.o (%f %f %f) ray.d (%f %f %f) nLight (%f %f %f) posPdf (%f) "
// "dirPdf(%f) E (%f %f %f)\n",
// lightRay.o[0], lightRay.o[1], lightRay.o[2], lightRay.d[0],
// lightRay.d[1], lightRay.d[2], nLight.x(), nLight.y(), nLight.z(),
// posPdf, dirPdf, ret.throughput[0], ret.throughput[1],
// ret.throughput[2]);
if ((posPdf * dirPdf) == 0.0f) return ret;
// dirPdf *= lightPdf;
// posPdf *= lightPdf;
// printf("dirPdf %f, posPdf %f, lightPdf %f emitPdf %f\n", dirPdf, posPdf,
// lightPdf, dirPdf * posPdf * lightPdf);
float emitPdf = dirPdf * posPdf * lightPdf;
ret.throughput /= emitPdf;
ret.isFiniteLight = sampleLight->isFinite();
ret.SpecularPath = true;
ret.PathLength = 1;
ret.direction = lightRay.d.normalized();
ret.origin = lightRay.o;
float emitCos = dot(nLight, lightRay.d);
ret.DVCM = MIS<pow>((posPdf * lightPdf) / emitPdf);
ret.DVC = sampleLight->isDelta()
? 0.f
: (sampleLight->isFinite()
? MIS<pow>(emitCos / (dirPdf * posPdf * lightPdf))
: MIS<pow>(1.f / (dirPdf * posPdf * lightPdf)));
// printf("dirPdf %f, posPdf %f, lightPdf %f emitPdf %f\n", dirPdf, posPdf,
// lightPdf, emitPdf);
// printf("E (%f %f %f), emitCos %f, DVCM %f DVC %f\n", ret.throughput[0],
// ret.throughput[1], ret.throughput[2], emitCos, ret.DVCM, ret.DVC);
return ret;
}
Spectrum BDPTIntegrator::ConnectToCamera(Scene* scene, Camera* camera,
Sampler* sampler,
SurfaceInteraction& si,
Vertex& lightVertex,
Vector2f& pRaster) {
Vector3f dirToCamera;
// Vector2f pRaster;
if (!camera->ToRaster(sampler->Next2D(), si, dirToCamera, pRaster)) return {};
float distToCamera = dirToCamera.length();
dirToCamera = dirToCamera.normalized();
// printf("(%f %f %f) (%f %f)\n", lightVertex.throughput[0],
// lightVertex.throughput[1], lightVertex.throughput[2], pRaster[0],
// pRaster[1]);
Spectrum f = si.bsdf->Evaluate(dirToCamera, lightVertex.inDir) *
std::abs(dot(lightVertex.inDir, si.Ns)) /
std::abs(dot(lightVertex.inDir, si.Ng));
// printf("(%f %f %f) (%f %f %f) %f %f (%f %f %f)\n", dirToCamera[0],
// dirToCamera[1], dirToCamera[2],
// si.bsdf->Evaluate(dirToCamera, lightVertex.inDir)[0],
// si.bsdf->Evaluate(dirToCamera, lightVertex.inDir)[1],
// si.bsdf->Evaluate(dirToCamera, lightVertex.inDir)[2],
// std::abs(dot(lightVertex.inDir, si.Ns)),
// std::abs(dot(lightVertex.inDir, si.Ng)), f[0], f[1], f[2]);
if (f.isBlack()) return {};
// printf("(%f %f %f)\n", f[0], f[1], f[2]);
float pdf = si.bsdf->EvaluatePdf(si.bsdf->toLocal(lightVertex.inDir),
si.bsdf->toLocal(dirToCamera));
float revPdf = si.bsdf->EvaluatePdf(si.bsdf->toLocal(dirToCamera),
si.bsdf->toLocal(lightVertex.inDir));
// printf("%f %f\n", pdf, revPdf);
if (pdf == 0.f || revPdf == 0.f) return {};
float cosToCam = dot(si.Ng, dirToCamera);
CameraSamplingRecord cRec;
VisibilityTester tester;
camera->Sample_Wi(sampler->Next2D(), si, &cRec, &tester);
(void)tester;
// printf("%f\n", cRec.pdf);
float cameraPdfA =
cRec.pdf * std::abs(cosToCam) / (distToCamera * distToCamera);
// printf("%d\n", camera->GetPixelCount());
float WLight =
MIS<pow>(
cameraPdfA / camera->GetPixelCount() //(float)camera->GetPixelCount()
) *
(lightVertex.DVCM + lightVertex.DVC * MIS<pow>(revPdf));
float MISWeight = 1.f / (WLight + 1.f);
// printf("%f\n", MISWeight);
Spectrum contrib = MISWeight * lightVertex.throughput * f * cameraPdfA /
camera->GetPixelCount();
// (float)camera->GetPixelCount();
// printf("%f %f %f\n", contrib[0], contrib[1], contrib[2]);
// printf("(%f %f %f) MISWeight %f f (%f %f %f) cameraPdfA %f A %f\n",
// lightVertex.throughput[0], lightVertex.throughput[1],
// lightVertex.throughput[2], MISWeight, f[0], f[1], f[2],
// cameraPdfA, camera->A());
Ray rayToCam =
Ray(si.p, dirToCamera, Ray::Eps(), distToCamera * (1.f - Ray::Eps()));
if (!contrib.isBlack() && !scene->Occlude(rayToCam)) {
// printf("%f %f %f\n", contrib[0], contrib[1], contrib[2]);
return contrib;
}
return {};
}
int BDPTIntegrator::GenerateLightPath(Scene* scene, Sampler* sampler,
const int maxDepth, Vertex* lightVertices,
Camera* camera, int* vertexCount,
const int rrDepth,
const bool connectToCamera) {
if (maxDepth == 0) {
*vertexCount = 0;
return 0;
}
PathState lightPathState = SampleLightSource(scene, sampler);
if (lightPathState.throughput.isBlack()) return 0;
// printf("(%f %f %f) \n", lightPathState.throughput[0],
// lightPathState.throughput[1], lightPathState.throughput[2]);
if (lightPathState.PathLength >= maxDepth) {
*vertexCount = 0;
return lightPathState.PathLength;
}
*vertexCount = 0;
while (true) {
Ray pathRay(lightPathState.origin, lightPathState.direction);
// printf("(%f %f %f) (%f %f %f)\n", pathRay.o[0], pathRay.o[1],
// pathRay.o[2], pathRay.d[0], pathRay.d[1], pathRay.d[2]);
Intersection isect;
if (!scene->Intersect(pathRay, &isect)) {
return lightPathState.PathLength;
}
if (lightPathState.PathLength > 1 || lightPathState.isFiniteLight) {
// printf("1 %f %f\n", lightPathState.DVCM, isect.t);
lightPathState.DVCM *= MIS<pow>(isect.t * isect.t);
// printf("(%f) (%f)\n", (pathRay.Point(isect.t) - pathRay.o).length(),
// isect.t);
// printf("2 %f\n", lightPathState.DVCM);
}
float cosIn = std::abs(dot(isect.Ng, -pathRay.d));
lightPathState.DVCM /= MIS<pow>(cosIn);
lightPathState.DVC /= MIS<pow>(cosIn);
// printf("cosIn %f DVCM %f DVC %f\n", cosIn, lightPathState.DVCM,
// lightPathState.DVC);
Triangle triangle{};
isect.mesh->GetTriangle(isect.triId, &triangle);
auto p = pathRay.Point(isect.t);
SurfaceInteraction si(-pathRay.d, p, triangle, isect);
isect.mesh->GetMaterial()->ComputeScatteringFunction(
&si, Core::TransportMode::eRadiance);
BSDFSamplingRecord bRec(si, sampler->Next2D());
si.bsdf->Sample(bRec);
// if (bRec.pdf <= 0.f) break;
auto specular = bRec.type & BxDFType::BSDF_SPECULAR;
if (!specular) {
Vertex& lightVertex = lightVertices[(*vertexCount)++];
lightVertex.throughput = lightPathState.throughput;
lightVertex.length = lightPathState.PathLength + 1;
lightVertex.si = si;
lightVertex.inDir = -lightPathState.direction;
lightVertex.DVCM = lightPathState.DVCM;
lightVertex.DVC = lightPathState.DVC;
// printf("(%f %f %f) \n", lightVertex.throughput[0],
// lightVertex.throughput[1], lightVertex.throughput[2]);
// connect to camera
if (connectToCamera) {
Vector2f ptRaster;
Spectrum connectRadiance =
ConnectToCamera(scene, camera, sampler, si, lightVertex, ptRaster);
// if (connectRadiance.isBlack()) break;
// printf("(%f %f %f) (%f %f)\n", connectRadiance[0],
// connectRadiance[1],
// connectRadiance[2], ptRaster[0], ptRaster[1]);
camera->GetFilm()->AddSplat(connectRadiance, ptRaster);
}
}
if (++lightPathState.PathLength >= maxDepth) break;
// if (!SampleScattering()) break;
Spectrum f = bRec.f;
Vector3f wi = bRec.wi;
float scatteredPdf = bRec.pdf;
float revPdf = si.bsdf->EvaluatePdf(wi, si.bsdf->toLocal(-pathRay.d));
if (f.isBlack() || scatteredPdf == 0.f) break;
// printf("(%f %f %f) %f\n", f[0], f[1], f[2], scatteredPdf);
if (!specular && rrDepth != -1 && lightPathState.PathLength > rrDepth) {
float q = std::min(0.95f, lightPathState.throughput.max());
if (sampler->Next1D() >= q) break;
lightPathState.throughput /= q;
}
lightPathState.origin = si.p;
lightPathState.direction = si.bsdf->toWorld(bRec.wi);
float cosOut = std::abs(dot(si.Ns, si.bsdf->toWorld(bRec.wi)));
if (!specular) {
lightPathState.SpecularPath &= 0;
lightPathState.DVCM =
MIS<pow>(cosOut / scatteredPdf) *
(lightPathState.DVC * MIS<pow>(revPdf) + lightPathState.DVCM);
lightPathState.DVC = MIS<pow>(1.0f / scatteredPdf);
// printf("%f %f\n", lightPathState.DVCM, lightPathState.DVC);
} else {
lightPathState.SpecularPath &= 1;
lightPathState.DVCM = 0.f;
lightPathState.DVC *= MIS<pow>(cosOut);
// printf("%f %f\n", lightPathState.DVCM, lightPathState.DVC);
}
lightPathState.throughput *= f * cosOut / scatteredPdf;
// printf("(%f %f %f) \n", lightPathState.throughput[0],
// lightPathState.throughput[1], lightPathState.throughput[2]);
}
return lightPathState.PathLength;
}
// bool SampleScattering() const {}
void BDPTIntegrator::SampleCamera(Camera* camera, Ray& ray, Sampler* sampler,
PathState& initPathState) {
// CameraSamplingRecord cRec;
// VisibilityTester tester;
// SurfaceInteraction si;
// ray.d = ray.d.normalized();
// si.p = ray.Point(camera->GetFocusDistance());
// camera->Sample_Wi(sampler->Next2D(), si, &cRec, &tester);
// (void)tester;
// float cosAtCam = Math::Dot(pCamera->mDir, primRay.mDir);
// float rasterToCamDist = pCamera->GetImagePlaneDistance() / cosAtCam;
// float cameraPdfW = rasterToCamDist * rasterToCamDist / cosAtCam;
float virtualImagePlaneDistance = camera->GetImagePlaneDist();
float cosThetaCamera = dot(camera->GetDir(), ray.d.normalized());
float imagePointToCameraDistance = virtualImagePlaneDistance / cosThetaCamera;
float invSolidAngleMeasure =
imagePointToCameraDistance * imagePointToCameraDistance / cosThetaCamera;
float revCameraPdfW = (1.0f / invSolidAngleMeasure);
// printf("%f %f %f %f %f\n", virtualImagePlaneDistance, cosThetaCamera,
// imagePointToCameraDistance, invSolidAngleMeasure, revCameraPdfW);
initPathState.origin = ray.o;
initPathState.direction = ray.d.normalized();
initPathState.throughput = Spectrum{1.f};
initPathState.PathLength = 1;
initPathState.SpecularPath = true;
initPathState.DVC = 0.f;
initPathState.DVCM = MIS<pow>(revCameraPdfW * camera->GetPixelCount());
// initPathState.DVCM = MIS<pow>( // camera->GetPixelCount()
// camera->A() / cRec.pdf);
// printf("%d %f %f\n", camera->GetPixelCount(), cRec.pdf,
// initPathState.DVCM);
}
Spectrum BDPTIntegrator::HittingLightSource(Scene* scene, Ray& ray,
Intersection& isect,
AreaLight* light,
PathState& cameraPathState) {
float pickPdf = scene->PdfLight(light);
float emitPdfW, directPdfA;
Spectrum emittedRadiance =
light->Emit(-ray.d, isect.Ng, &emitPdfW, &directPdfA);
// printf("(%f %f %f) %f %f\n", emittedRadiance[0], emittedRadiance[1],
// emittedRadiance[2], emitPdfW, directPdfA);
if (emittedRadiance.isBlack()) return {};
// printf("%d\n", cameraPathState.PathLength);
if (cameraPathState.PathLength == 2) {
return emittedRadiance;
}
directPdfA *= pickPdf;
emitPdfW *= pickPdf;
float WCamera = MIS<pow>(directPdfA) * cameraPathState.DVCM +
MIS<pow>(emitPdfW) * cameraPathState.DVC;
float MISWeight = 1.0f / (1.0f + WCamera);
// printf("%f %f %f %f %f\n", directPdfA, emitPdfW, cameraPathState.DVCM,
// cameraPathState.DVC, WCamera);
return MISWeight * emittedRadiance;
}
Spectrum BDPTIntegrator::ConnectToLight(const Scene* scene, Ray& pathRay,
const SurfaceInteraction& si,
Sampler* sampler,
PathState& cameraPathState) {
// Sample light source and get radiance
float lightPdf = 0.f;
auto sampleLight = scene->SampleOneLight(sampler->Next1D(), &lightPdf);
const Vector3f& pos = si.p;
Vector3f vIn;
VisibilityTester visibility;
float lightPdfW;
float cosAtLight;
float emitPdfW;
Spectrum radiance =
sampleLight->Illuminate(si, sampler->Next2D(), vIn, visibility,
&lightPdfW, &cosAtLight, &emitPdfW);
// printf("(%f %f %f) %f %f %f\n", radiance[0], radiance[1], radiance[2],
// lightPdfW, cosAtLight, emitPdfW);
if (radiance.isBlack() || lightPdfW == 0.0f) {
return {};
}
Vector3f vOut = -pathRay.d;
Spectrum bsdfFac = si.bsdf->Evaluate(vOut, vIn);
if (bsdfFac.isBlack()) {
return {};
}
float bsdfPdfW = si.bsdf->EvaluatePdf(vOut, vIn);
if (bsdfPdfW == 0.f) return {};
if (sampleLight->isDelta()) bsdfPdfW = 0.f;
float bsdfRevPdfW = si.bsdf->EvaluatePdf(vIn, vOut);
float WLight = MIS<pow>(bsdfPdfW / (lightPdfW * lightPdf));
// printf("%f\n", WLight);
float cosToLight = std::abs(Math::dot(si.Ns, vIn));
float WCamera =
MIS<pow>(emitPdfW * cosToLight / (lightPdfW * cosAtLight)) *
(cameraPathState.DVCM + cameraPathState.DVC * MIS<pow>(bsdfRevPdfW));
// printf("%f\n", WCamera);
float fMISWeight = 1.0f / (WLight + 1.0f + WCamera);
Spectrum contribution =
(fMISWeight * cosToLight / (lightPdfW * lightPdf)) * bsdfFac * radiance;
if (contribution.isBlack() || !visibility.visible(*scene)) {
return {};
}
// printf("%f %f %f\n", contribution[0], contribution[1], contribution[2]);
return contribution;
}
Spectrum BDPTIntegrator::ConnectVertex(Scene* scene, SurfaceInteraction& si,
const Vertex& lightVertex,
PathState& cameraState) {
const Vector3f& cameraPos = si.p;
auto dirToLight = lightVertex.si.p - cameraPos;
float distToLightSqr = dot(dirToLight, dirToLight);
float distToLight = dirToLight.length();
auto vOutCam = -cameraState.direction;
Spectrum cameraBsdfFac = si.bsdf->Evaluate(vOutCam, dirToLight);
float cosAtCam = dot(si.Ns, dirToLight);
auto cameraDirPdfW = si.bsdf->EvaluatePdf(vOutCam, dirToLight);
float cameraReversePdfW = si.bsdf->EvaluatePdf(dirToLight, vOutCam);
if (cameraBsdfFac.isBlack() || cameraDirPdfW == 0.0f ||
cameraReversePdfW == 0.0f)
return {};
Vector3f dirToCamera = -dirToLight;
Spectrum lightBsdfFac =
lightVertex.si.bsdf->Evaluate(lightVertex.inDir, dirToCamera);
float cosAtLight = Math::dot(lightVertex.si.Ns, dirToCamera);
float lightDirPdfW =
lightVertex.si.bsdf->EvaluatePdf(lightVertex.inDir, dirToCamera);
float lightRevPdfW =
lightVertex.si.bsdf->EvaluatePdf(dirToCamera, lightVertex.inDir);
if (lightBsdfFac.isBlack() || lightDirPdfW == 0.0f || lightRevPdfW == 0.0f)
return {};
// printf("%f %f %f %f\n", cameraDirPdfW, cameraReversePdfW, lightDirPdfW,
// lightRevPdfW);
float geometryTerm = cosAtLight * cosAtCam / distToLightSqr;
if (geometryTerm < 0.0f) {
return {};
}
// printf("%f\n", geometryTerm);
float cameraDirPdfA =
cameraDirPdfW * std::abs(cosAtLight) / (distToLight * distToLight);
float lightDirPdfA =
lightDirPdfW * std::abs(cosAtCam) / (distToLight * distToLight);
float WLight = MIS<pow>(cameraDirPdfA) *
(lightVertex.DVCM + lightVertex.DVC * MIS<pow>(lightRevPdfW));
float WCamera =
MIS<pow>(lightDirPdfA) *
(cameraState.DVCM + cameraState.DVC * MIS<pow>(cameraReversePdfW));
float fMISWeight = 1.0f / (WLight + 1.0f + WCamera);
// printf("%f %f %f\n", fMISWeight, WLight, WCamera);
Spectrum contribution =
(fMISWeight * geometryTerm) * lightBsdfFac * cameraBsdfFac;
Ray rayToLight =
Ray(cameraPos, dirToLight, Ray::Eps(), distToLight * (1.f - Ray::Eps()));
if (contribution.isBlack() || scene->Occlude(rayToLight)) {
// printf("%f %f %f\n", contribution[0], contribution[1],
// contribution[2]);
return {};
}
// printf("%f %f %f\n", contribution[0], contribution[1], contribution[2]);
return contribution;
}
Math::Spectrum BDPTIntegrator::Li(Core::Scene* scene, Core::Camera* camera,
const Math::Vector2i& raster,
Core::Sampler* sampler) const {
Vertex* lightVertices = (Vertex*)calloc(maxDepth, sizeof(Vertex));
int numLightVertex;
int lightPathLen = GenerateLightPath(scene, sampler, maxDepth + 1,
lightVertices, camera, &numLightVertex);
const float u =
(raster.x() + sampler->Next1D()) / camera->GetFilm()->Dimension().x();
const float v =
(raster.y() + sampler->Next1D()) / camera->GetFilm()->Dimension().y();
// auto ray = camera->GenerateRay(u, v);
auto ray = camera->GenerateRay(sampler->Next2D(), sampler->Next2D(), raster);
PathState cameraPathState;
SampleCamera(camera, ray, sampler, cameraPathState);
Math::Spectrum L(0.f);
while (true) {
Ray pathRay(cameraPathState.origin, cameraPathState.direction);
Intersection isect;
if (!scene->Intersect(pathRay, &isect)) {
break;
}
float cosIn = std::abs(dot(isect.Ng, -pathRay.d));
cameraPathState.DVCM *= MIS<pow>(isect.t * isect.t);
cameraPathState.DVCM /= MIS<pow>(cosIn);
cameraPathState.DVC /= MIS<pow>(cosIn);
// printf("%f %f\n", cameraPathState.DVCM, cameraPathState.DVC);
if (isect.mesh->IsEmitter()) {
cameraPathState.PathLength++;
L += cameraPathState.throughput *
HittingLightSource(scene, pathRay, isect,
isect.mesh->GetLight(isect.triId).get(),
cameraPathState);
break;
}
if (++cameraPathState.PathLength >= maxDepth + 2) {
break;
}
Triangle triangle{};
isect.mesh->GetTriangle(isect.triId, &triangle);
auto p = pathRay.Point(isect.t);
SurfaceInteraction si(-pathRay.d, p, triangle, isect);
isect.mesh->GetMaterial()->ComputeScatteringFunction(
&si, Core::TransportMode::eImportance);
BSDFSamplingRecord bRec(si, sampler->Next2D());
si.bsdf->Sample(bRec);
if (bRec.pdf <= 0.f) break;
auto specular = bRec.type & BxDFType::BSDF_SPECULAR;
if (!specular) {
L += cameraPathState.throughput *
ConnectToLight(scene, pathRay, si, sampler, cameraPathState);
for (int i = 0; i < numLightVertex; i++) {
const Vertex& lightVertex = lightVertices[i];
if (lightVertex.length + cameraPathState.PathLength - 2 > maxDepth) {
break;
}
L += lightVertex.throughput * cameraPathState.throughput *
ConnectVertex(scene, si, lightVertex, cameraPathState);
}
}
Spectrum f = bRec.f;
Vector3f wi = bRec.wi;
float scatteredPdf = bRec.pdf;
float revPdf = si.bsdf->EvaluatePdf(wi, si.bsdf->toLocal(-pathRay.d));
if (f.isBlack() || scatteredPdf == 0.f) break;
// printf("(%f %f %f) %f\n", f[0], f[1], f[2], scatteredPdf);
if (!specular && rrDepth != -1 && cameraPathState.PathLength > rrDepth) {
float q = std::min(0.95f, cameraPathState.throughput.max());
if (sampler->Next1D() >= q) break;
cameraPathState.throughput /= q;
}
cameraPathState.origin = si.p;
cameraPathState.direction = si.bsdf->toWorld(bRec.wi);
float cosOut = std::abs(dot(si.Ns, si.bsdf->toWorld(bRec.wi)));
if (!specular) {
cameraPathState.SpecularPath &= 0;
cameraPathState.DVCM =
MIS<pow>(cosOut / scatteredPdf) *
(cameraPathState.DVC * MIS<pow>(revPdf) + cameraPathState.DVCM);
cameraPathState.DVC = MIS<pow>(1.0f / scatteredPdf);
} else {
cameraPathState.SpecularPath &= 1;
cameraPathState.DVCM = 0.f;
cameraPathState.DVC *= MIS<pow>(cosOut);
}
cameraPathState.throughput *= f * cosOut / scatteredPdf;
}
free((void*)lightVertices);
return L;
}
void BDPTIntegrator::Render(Core::Scene* scene, Core::Camera* camera,
Core::Sampler* sampler) const {}
// private:
// // int rrDepth = 5, maxDepth = 16;
// int rrDepth = 5, maxDepth = 16;
// // heuristic
// static constexpr int pow = 1;
// };
} // namespace Ajisai::Integrators
AJISAI_PLUGIN_REGISTER(BDPTIntegrator, Ajisai::Integrators::BDPTIntegrator,
"ajisai.integrators.Integrator/0.0.1")
| 36.111928
| 80
| 0.573878
|
siyuanpan
|
e2228f6754b8bbf31357a6f7086c29b17ac48b84
| 6,380
|
hpp
|
C++
|
libctrpf/include/CTRPluginFrameworkImpl/Menu/KeyboardImpl.hpp
|
MirayXS/Vapecord-ACNL-Plugin
|
247eb270dfe849eda325cc0c6adc5498d51de3ef
|
[
"MIT"
] | null | null | null |
libctrpf/include/CTRPluginFrameworkImpl/Menu/KeyboardImpl.hpp
|
MirayXS/Vapecord-ACNL-Plugin
|
247eb270dfe849eda325cc0c6adc5498d51de3ef
|
[
"MIT"
] | null | null | null |
libctrpf/include/CTRPluginFrameworkImpl/Menu/KeyboardImpl.hpp
|
MirayXS/Vapecord-ACNL-Plugin
|
247eb270dfe849eda325cc0c6adc5498d51de3ef
|
[
"MIT"
] | null | null | null |
#ifndef CTRPLUGINFRAMEWORKIMPL_KEYBOARD_HPP
#define CTRPLUGINFRAMEWORKIMPL_KEYBOARD_HPP
#include "CTRPluginFrameworkImpl/Graphics.hpp"
#include "CTRPluginFramework/Graphics/CustomIcon.hpp"
#include "CTRPluginFrameworkImpl/Graphics/TouchKey.hpp"
#include "CTRPluginFrameworkImpl/Graphics/TouchKeyString.hpp"
#include "CTRPluginFramework/Menu/Keyboard.hpp"
#include "CTRPluginFrameworkImpl/System.hpp"
#include "CTRPluginFramework/Sound.hpp"
#include <vector>
#include <string>
namespace CTRPluginFramework
{
enum Layout
{
QWERTY,
DECIMAL,
HEXADECIMAL
};
class Keyboard;
class KeyboardImpl
{
using CompareCallback = bool (*)(const void *, std::string&);
using ConvertCallback = void *(*)(std::string&, bool);
using OnEventCallback = void(*)(Keyboard&, KeyboardEvent&);
using FrameCallback = void (*)(Time);
using KeyIter = std::vector<TouchKey>::iterator;
using KeyStringIter = std::vector<TouchKeyString>::iterator;
public:
KeyboardImpl(const std::string &text = "");
explicit KeyboardImpl(Keyboard *kb, const std::string &text = "");
~KeyboardImpl(void);
void SetLayout(Layout layout);
void SetHexadecimal(bool isHex);
bool IsHexadecimal(void) const;
void SetMaxInput(u32 max);
void CanAbort(bool canAbort);
void CanChangeLayout(bool canChange);
std::string &GetInput(void);
std::string &GetMessage(void);
std::string &GetTitle(void);
void SetError(std::string &error);
void SetConvertCallback(ConvertCallback callback);
void SetCompareCallback(CompareCallback callback);
void OnKeyboardEvent(OnEventCallback callback);
static void OnNewFrame(FrameCallback callback);
void ChangeSelectedEntry(int entry);
int GetSelectedEntry() {return _manualKey;}
void ChangeEntrySound(int entry, SoundEngine::Event soundEvent);
void Populate(const std::vector<std::string>& input, bool resetScroll);
void Populate(const std::vector<CustomIcon>& input, bool resetScroll);
void Clear(void);
int Run(void);
void Close(void);
bool operator()(int &out);
bool DisplayTopScreen;
private:
friend class HexEditor;
friend class ARCodeEditor;
void _RenderTop(void);
void _RenderBottom(void);
void _ProcessEvent(Event &event);
void _UpdateScroll(float delta, bool ignoreTouch);
void _Update(float delta);
// Keyboard layout constructor
void _Qwerty(void);
void _QwertyLowCase(void);
void _QwertyUpCase(void);
void _QwertySymbols(void);
void _QwertyNintendo(void);
static void _DigitKeyboard(std::vector<TouchKey> &keys);
void _Decimal(void);
void _Hexadecimal(void);
void _ScrollUp(void);
void _ScrollDown(void);
void _UpdateScrollInfos(void);
bool _CheckKeys(void); //<- Return if input have changed
bool _CheckInput(void); //<- Call compare callback, return true if the input is valid
bool _CheckButtons(int &ret); //<- for string button
void _HandleManualKeyPress(Key key);
void _ClearKeyboardEvent();
void _ChangeManualKey(int newVal, bool playSound = true);
Keyboard *_owner{nullptr};
std::string _title;
std::string _text;
std::string _error;
std::string _userInput;
bool _canChangeLayout{false};
bool _canAbort{true};
bool _isOpen{false};
bool _askForExit{false};
bool _errorMessage{false};
bool _userAbort{false};
bool _isHex{true};
bool _mustRelease{false};
bool _useCaps{false};
bool _useSymbols{false};
bool _useNintendo{false};
float _offset{0.f};
u32 _max{0};
u8 _symbolsPage{0};
u8 _nintendoPage{0};
Layout _layout{HEXADECIMAL};
Clock _blinkingClock;
int _cursorPositionInString{0};
int _cursorPositionOnScreen{0};
bool _showCursor{true};
CompareCallback _compare{nullptr};
ConvertCallback _convert{nullptr};
OnEventCallback _onKeyboardEvent{nullptr};
static FrameCallback _onNewFrame;
KeyboardEvent _KeyboardEvent{};
std::vector<TouchKey> *_keys{nullptr};
static std::vector<TouchKey> _DecimalKeys;
static std::vector<TouchKey> _HexaDecimalKeys;
static std::vector<TouchKey> _QwertyKeys;
// Custom keyboard stuff
int _manualKey{0};
int _prevManualKey{-2};
bool _manualScrollUpdate{false};
bool _userSelectedKey{false};
bool _customKeyboard{false};
bool _displayScrollbar{false};
bool _isIconKeyboard{false};
int _currentPosition{0};
u32 _scrollbarSize{0};
u32 _scrollCursorSize{0};
float _scrollSize{0.f};
float _scrollPosition{0.f};
float _scrollPadding{0.f};
float _scrollJump{0.f};
float _inertialVelocity{0.f};
float _scrollStart{0.f};
float _scrollEnd{0.f};
IntVector _lastTouch;
Clock _touchTimer;
std::vector<TouchKeyString *> _strKeys;
};
}
#endif
| 38.902439
| 96
| 0.54185
|
MirayXS
|
e224e709d74a393c04acd3371847fe9ca1d0b0e3
| 704
|
cpp
|
C++
|
152-maxProductSubarray.cpp
|
riasood02/leetcoding-problems
|
568bb4e323acb57e274b87c07969a772f011259e
|
[
"Unlicense"
] | 5
|
2020-10-06T13:10:04.000Z
|
2021-06-07T02:07:59.000Z
|
152-maxProductSubarray.cpp
|
riasood02/leetcoding-problems
|
568bb4e323acb57e274b87c07969a772f011259e
|
[
"Unlicense"
] | 5
|
2020-10-05T17:23:57.000Z
|
2020-10-10T12:56:15.000Z
|
152-maxProductSubarray.cpp
|
riasood02/leetcoding-problems
|
568bb4e323acb57e274b87c07969a772f011259e
|
[
"Unlicense"
] | 43
|
2020-10-05T17:31:56.000Z
|
2020-10-29T23:47:53.000Z
|
// https://leetcode.com/problems/maximum-product-subarray/
class Solution {
public:
int maxProduct(vector<int>& nums) {
int cur = INT_MIN;
vector<int> a(nums.size(),0);
vector<int> b(nums.size(),0);
a[0] = nums[0];
b[0] = nums[0];
int ma = a[0];
for(int i = 1 ;i<nums.size();i++){
if(nums[i]<0){
a[i] = max(nums[i],b[i-1]*nums[i]);
b[i] = min(nums[i],a[i-1]*nums[i]);
}
else{
a[i] = max(nums[i],a[i-1]*nums[i]);
b[i] = min(nums[i],b[i-1]*nums[i]);
}
ma = max(a[i],ma);
}
return ma;
}
};
| 27.076923
| 58
| 0.400568
|
riasood02
|
e226f459cd362e116b198f580aba183789202887
| 653
|
cc
|
C++
|
autofuzz/lcms_fuzz.cc
|
Munyola/security-research-pocs
|
bbbd8ccf20999800a736070b379d5116731aa1f5
|
[
"Apache-2.0"
] | 2
|
2020-09-18T04:59:08.000Z
|
2020-12-28T18:59:36.000Z
|
autofuzz/lcms_fuzz.cc
|
Sicks3c/security-research-pocs
|
bbbd8ccf20999800a736070b379d5116731aa1f5
|
[
"Apache-2.0"
] | null | null | null |
autofuzz/lcms_fuzz.cc
|
Sicks3c/security-research-pocs
|
bbbd8ccf20999800a736070b379d5116731aa1f5
|
[
"Apache-2.0"
] | 1
|
2021-06-08T17:12:24.000Z
|
2021-06-08T17:12:24.000Z
|
#include <stdint.h>
#include <string>
#include "lcms2.h"
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
if (size < 2) {
return 0;
}
size_t mid = size / 2;
cmsHPROFILE hInProfile, hOutProfile;
cmsHTRANSFORM hTransform;
hInProfile = cmsOpenProfileFromMem(data, mid);
hOutProfile = cmsOpenProfileFromMem(data + mid, size - mid);
hTransform = cmsCreateTransform(hInProfile, TYPE_BGR_8, hOutProfile,
TYPE_BGR_8, INTENT_PERCEPTUAL, 0);
cmsCloseProfile(hInProfile);
cmsCloseProfile(hOutProfile);
if (hTransform) {
cmsDeleteTransform(hTransform);
}
return 0;
}
| 24.185185
| 73
| 0.689127
|
Munyola
|
e22cbd6c605e06532af43dbbde37760a540e4ad3
| 2,773
|
hpp
|
C++
|
src/cpp/basic_lot.hpp
|
plewis/phycas
|
9f5a4d9b2342dab907d14a46eb91f92ad80a5605
|
[
"MIT"
] | 3
|
2015-09-24T23:12:57.000Z
|
2021-04-12T07:07:01.000Z
|
src/cpp/basic_lot.hpp
|
plewis/phycas
|
9f5a4d9b2342dab907d14a46eb91f92ad80a5605
|
[
"MIT"
] | null | null | null |
src/cpp/basic_lot.hpp
|
plewis/phycas
|
9f5a4d9b2342dab907d14a46eb91f92ad80a5605
|
[
"MIT"
] | 1
|
2015-11-23T10:35:43.000Z
|
2015-11-23T10:35:43.000Z
|
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\
| Phycas: Python software for phylogenetic analysis |
| Copyright (C) 2006 Mark T. Holder, Paul O. Lewis and David L. Swofford |
| |
| 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 Street, Fifth Floor, Boston, MA 02110-1301 USA. |
\~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
#if ! defined(BASIC_LOT_HPP)
#define BASIC_LOT_HPP
#include <cmath>
#include <ctime>
#include <boost/shared_ptr.hpp>
namespace phycas
{
/*----------------------------------------------------------------------------------------------------------------------
| This class was called Lot because the noun lot is defined as "an object used in deciding something by chance"
| according to The New Merriam-Webster Dictionary.
*/
class Lot
{
public:
Lot();
Lot(unsigned);
~Lot();
// Accessors
unsigned GetSeed() const;
unsigned GetInitSeed() const;
// Modifiers
void UseClockToSeed();
void SetSeed(unsigned s);
// Utilities
unsigned MultinomialDraw(const double * probs, unsigned n, double totalProb=1.0);
unsigned SampleUInt(unsigned);
unsigned GetRandBits(unsigned nbits);
double Uniform();
double Normal();
bool Boolean();
private:
unsigned last_seed_setting;
unsigned curr_seed;
};
typedef boost::shared_ptr<Lot> LotShPtr;
inline bool Lot::Boolean()
{
return (Uniform() < 0.5);
}
inline double Lot::Normal()
{
double u = Uniform();
double x = sqrt(-2.0*log(u));
double v = Uniform();
double y = cos(2.0*3.141592653589793238846*v);
return x*y;
}
} // namespace phycas
#endif
| 33.011905
| 120
| 0.510999
|
plewis
|
e2338d870195e71b2e20868ca3757af7d5680636
| 5,493
|
cpp
|
C++
|
src/uavpc/Pose/PoseService.cpp
|
filipdutescu/uavpc
|
050bd19b103f2cf7cdac9fd167d8965d0032c5ec
|
[
"Apache-2.0"
] | 2
|
2021-10-11T02:54:08.000Z
|
2021-10-11T09:29:59.000Z
|
src/uavpc/Pose/PoseService.cpp
|
filipdutescu/uavpc
|
050bd19b103f2cf7cdac9fd167d8965d0032c5ec
|
[
"Apache-2.0"
] | null | null | null |
src/uavpc/Pose/PoseService.cpp
|
filipdutescu/uavpc
|
050bd19b103f2cf7cdac9fd167d8965d0032c5ec
|
[
"Apache-2.0"
] | null | null | null |
#include "uavpc/Pose/PoseService.hpp"
#include <ctime>
#include <iostream>
#include <stdexcept>
#include <string>
#include <opencv2/core/types.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/videoio.hpp>
#include <openpose/core/matrix.hpp>
#include <openpose/core/point.hpp>
#include <openpose/thread/enumClasses.hpp>
namespace uavpc::Pose
{
PoseService::PoseService() noexcept
: m_OpenPoseWrapper(op::ThreadManagerMode::Asynchronous),
m_ShouldRun(false),
m_WithRecognition(false),
m_SaveVideoStream(false)
{
}
PoseService::~PoseService()
{
if (m_ShouldRun)
{
while (!m_RecognitionMutex.try_lock())
{
std::this_thread::sleep_for(s_MutexTryLockWaitTime);
}
m_ShouldRun = false;
m_RecognitionMutex.unlock();
while (!m_RecognitionThread.joinable())
{
std::this_thread::sleep_for(s_MutexTryLockWaitTime);
}
if (m_RecognitionThread.joinable())
{
m_RecognitionThread.join();
}
m_RecognitionMutex.unlock();
if (m_SaveVideoStream)
{
ToggleSaveVideoStream();
}
}
}
TDatumsSP PoseService::DetectPoseFromFrame(const cv::Mat &frame) noexcept
{
const auto rawImage = OP_CV2OPCONSTMAT(frame);
return m_OpenPoseWrapper.emplaceAndPop(rawImage);
}
void PoseService::DisplayFrameWithPose(const TDatumsSP &frame) noexcept
{
try
{
if (frame != nullptr && !frame->empty())
{
const auto image = OP_OP2CVCONSTMAT(frame->at(0U)->cvOutputData);
if (!image.empty())
{
cv::imshow("UAVPC", image);
}
}
}
catch (const std::exception &e)
{
std::cerr << "Could not display frame with pose: " << e.what();
}
}
void PoseService::ToggleRecognition() noexcept
{
m_WithRecognition = !m_WithRecognition;
}
void PoseService::ToggleSaveVideoStream() noexcept
{
m_SaveVideoStream = !m_SaveVideoStream;
if (m_ShouldRun)
{
if (m_SaveVideoStream)
{
while (m_RecognitionMutex.try_lock())
{
std::this_thread::sleep_for(s_MutexTryLockWaitTime);
}
constexpr auto format = "uavpc_%Y%m%d_%H%M%S.mp4";
constexpr auto bufferSize = 30U;
char buffer[bufferSize]{ '\0' };
std::strftime(buffer, bufferSize, format, std::localtime(nullptr));
m_PersistentVideoStream.open(
std::string(buffer), cv::VideoWriter::fourcc('M', 'P', '4', 'V'), -1, m_VideoStreamSize);
m_RecognitionMutex.unlock();
}
else
{
while (m_RecognitionMutex.try_lock())
{
std::this_thread::sleep_for(s_MutexTryLockWaitTime);
}
m_PersistentVideoStream.release();
m_RecognitionMutex.unlock();
}
}
}
void PoseService::StartDisplay(cv::VideoCapture &videoStream)
{
m_ShouldRun = true;
if (!videoStream.isOpened())
{
throw std::runtime_error("Video stream closed.");
}
m_RecognitionThread = std::thread(
[&]
{
auto width = static_cast<int>(videoStream.get(cv::CAP_PROP_FRAME_WIDTH) / 2);
auto height = static_cast<int>(videoStream.get(cv::CAP_PROP_FRAME_HEIGHT) / 2);
auto opWidth = (width / (16 * 3) + 1) * 16;
auto opHeight = (width / (16 * 3) + 1) * 16;
cv::Mat frame;
op::WrapperStructPose poseConfig{};
poseConfig.netInputSize = op::Point<int>(opWidth, opHeight);
poseConfig.poseModel = op::PoseModel::MPI_15_4;
m_OpenPoseWrapper.configure(poseConfig);
m_OpenPoseWrapper.start();
while (m_ShouldRun)
{
if (videoStream.read(frame))
{
if (!frame.empty())
{
cv::Mat resizedFrame;
cv::resize(frame, resizedFrame, cv::Size(width, height));
cv::Mat persistentFrame = resizedFrame;
if (m_WithRecognition)
{
auto processedFrame = DetectPoseFromFrame(resizedFrame);
DisplayFrameWithPose(processedFrame);
persistentFrame = OP_OP2CVCONSTMAT(processedFrame->at(0U)->cvOutputData);
}
else
{
cv::imshow("UAVPC", resizedFrame);
}
if (m_SaveVideoStream)
{
while (m_RecognitionMutex.try_lock())
{
std::this_thread::sleep_for(s_MutexTryLockWaitTime);
}
m_PersistentVideoStream.write(persistentFrame);
m_RecognitionMutex.unlock();
}
}
}
else
{
std::cout << "could not read frame" << std::endl;
}
cv::waitKey(1);
}
});
}
void PoseService::StopDisplay() noexcept
{
while (!m_RecognitionMutex.try_lock())
{
std::this_thread::sleep_for(s_MutexTryLockWaitTime);
}
m_ShouldRun = false;
m_RecognitionMutex.unlock();
while (!m_RecognitionThread.joinable())
{
std::this_thread::sleep_for(s_MutexTryLockWaitTime);
}
if (m_RecognitionThread.joinable())
{
m_RecognitionThread.join();
}
m_RecognitionMutex.unlock();
m_OpenPoseWrapper.stop();
}
} // namespace uavpc::Pose
| 25.910377
| 101
| 0.57728
|
filipdutescu
|
e23ab9f821e9f74c8baa4061e876516778c0842a
| 422
|
cpp
|
C++
|
CanadianExperience/CanadianExperience/Testing/CAnimChannelAngleTest.cpp
|
NicholsTyler/cse_335
|
b8a46522c15a9881cb681ae94b4a5f737817b05e
|
[
"MIT"
] | null | null | null |
CanadianExperience/CanadianExperience/Testing/CAnimChannelAngleTest.cpp
|
NicholsTyler/cse_335
|
b8a46522c15a9881cb681ae94b4a5f737817b05e
|
[
"MIT"
] | null | null | null |
CanadianExperience/CanadianExperience/Testing/CAnimChannelAngleTest.cpp
|
NicholsTyler/cse_335
|
b8a46522c15a9881cb681ae94b4a5f737817b05e
|
[
"MIT"
] | null | null | null |
#include "pch.h"
#include "CppUnitTest.h"
#include "AnimChannelAngle.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace Testing
{
TEST_CLASS(CAnimChannelAngleTest)
{
public:
TEST_METHOD(TestCAnimChannelAngleName)
{
CAnimChannelAngle channel;
channel.SetName(L"abcdexx");
Assert::AreEqual(std::wstring(L"abcdexx"), channel.GetName());
}
};
}
| 16.230769
| 74
| 0.687204
|
NicholsTyler
|
e24129d77e249d87a686a143648196a9981f0b01
| 788
|
cpp
|
C++
|
SumNumber/SumNumber.cpp
|
Tupiet/Learncpp-tutorial
|
d9c382687d0f7f6dca4bd18c1c78d11368047726
|
[
"MIT"
] | null | null | null |
SumNumber/SumNumber.cpp
|
Tupiet/Learncpp-tutorial
|
d9c382687d0f7f6dca4bd18c1c78d11368047726
|
[
"MIT"
] | null | null | null |
SumNumber/SumNumber.cpp
|
Tupiet/Learncpp-tutorial
|
d9c382687d0f7f6dca4bd18c1c78d11368047726
|
[
"MIT"
] | null | null | null |
// This app will, simply, sum two numbers that we'll input from the console. It's an easy program.
#include "sum.h" // Including the header with the math logic
#include "getInput.h" // Including the header with all the inputs
#include "utilities.h" // This includes some utilities that will made this easy to understarnd
#include <iostream> // For having std::cout and std::cin
#include <limits> // We need them for allowing the app to only close if the user press any key.
int main()
{
std::cout << "Bienvenido a SumNumber!\n" << "Somos la aplicacion perfecta si no sabes sumar.\n";
int x = intInput();
int y = intInput();
std::cout << "La suma de " << x << " y " << y << " es igual a " << sum(x, y);
askBeforeExiting();
return 0;
}
| 31.52
| 101
| 0.643401
|
Tupiet
|
e249cc60aa888d14c8688687992cf22d8f83ba50
| 1,069
|
hpp
|
C++
|
include/gclib/gc_delete.hpp
|
axilmar/gclib
|
1d2707238b549d889a7c9b097d599a36e3841da4
|
[
"Apache-2.0"
] | 2
|
2021-11-24T18:49:09.000Z
|
2022-01-11T04:30:43.000Z
|
include/gclib/gc_delete.hpp
|
axilmar/gclib
|
1d2707238b549d889a7c9b097d599a36e3841da4
|
[
"Apache-2.0"
] | null | null | null |
include/gclib/gc_delete.hpp
|
axilmar/gclib
|
1d2707238b549d889a7c9b097d599a36e3841da4
|
[
"Apache-2.0"
] | 1
|
2020-10-27T09:51:06.000Z
|
2020-10-27T09:51:06.000Z
|
#ifndef GCLIB_GC_DELETE_HPP
#define GCLIB_GC_DELETE_HPP
#include "gc_new_array.hpp"
namespace gclib {
/**
* Deletes an object pointed to by the given pointer.
* @param p pointer to object to delete; can be null; if not null, then it should have a value returned by gc_new,
* otherwise the operation will have undefined results.
*/
template <class T> void gc_delete(const gc_ptr<T>& p) {
if (!p) {
return;
}
class delete_object {
public:
delete_object(void* obj)
: m_block(gc::object_to_block(obj))
{
gc::begin_remove(m_block);
m_block->vtable->finalize(m_block + 1, m_block->end());
}
~delete_object() {
gc::end_remove(m_block);
m_block->vtable->deallocate(m_block);
}
private:
gc::block* m_block;
};
const delete_object delete_object_var(p.get());
}
} //namespace gclib
#endif //GCLIB_GC_DELETE_HPP
| 22.270833
| 118
| 0.558466
|
axilmar
|
e249ede58f2470a9c1f7e80dc03b41cb69fcfeb0
| 6,519
|
cpp
|
C++
|
src/VDBMapping.cpp
|
fzi-forschungszentrum-informatik/vdb_mapping
|
b15e5349309f82fc05d39152865d6eb43fe75215
|
[
"Apache-2.0"
] | 12
|
2021-04-15T10:22:41.000Z
|
2022-03-16T16:35:13.000Z
|
src/VDBMapping.cpp
|
fzi-forschungszentrum-informatik/vdb_mapping
|
b15e5349309f82fc05d39152865d6eb43fe75215
|
[
"Apache-2.0"
] | 2
|
2021-12-06T18:13:43.000Z
|
2022-03-25T11:05:07.000Z
|
src/VDBMapping.cpp
|
fzi-forschungszentrum-informatik/vdb_mapping
|
b15e5349309f82fc05d39152865d6eb43fe75215
|
[
"Apache-2.0"
] | 2
|
2021-06-30T10:28:44.000Z
|
2022-03-17T10:39:12.000Z
|
// this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*-
// -- BEGIN LICENSE BLOCK ----------------------------------------------
// Copyright 2021 FZI Forschungszentrum Informatik
//
// 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.
// -- END LICENSE BLOCK ------------------------------------------------
//----------------------------------------------------------------------
/*!\file
*
* \author Marvin Große Besselmann grosse@fzi.de
* \date 2020-12-23
*
*/
//----------------------------------------------------------------------
#include <vdb_mapping/VDBMapping.h>
#include <iostream>
VDBMapping::VDBMapping(const double resolution)
: m_resolution(resolution)
, m_config_set(false)
{
// Initialize Grid
m_vdb_grid = createVDBMap(m_resolution);
}
void VDBMapping::resetMap()
{
m_vdb_grid->clear();
m_vdb_grid = createVDBMap(m_resolution);
}
VDBMapping::GridT::Ptr VDBMapping::createVDBMap(double resolution)
{
GridT::Ptr new_map = GridT::create(0.0);
new_map->setTransform(openvdb::math::Transform::createLinearTransform(m_resolution));
new_map->setGridClass(openvdb::GRID_LEVEL_SET);
return new_map;
}
bool VDBMapping::insertPointCloud(const PointCloudT::ConstPtr& cloud,
const Eigen::Matrix<double, 3, 1>& origin)
{
// Check if a valid configuration was loaded
if (!m_config_set)
{
std::cerr << "Map not properly configured. Did you call setConfig method?" << std::endl;
return false;
}
RayT ray;
DDAT dda;
// Ray origin in world coordinates
openvdb::Vec3d ray_origin_world(origin.x(), origin.y(), origin.z());
// Ray origin in index coordinates
const Vec3T ray_origin_index(m_vdb_grid->worldToIndex(ray_origin_world));
// Ray end point in world coordinates
openvdb::Vec3d ray_end_world;
// Direction the ray is point towards
openvdb::Vec3d ray_direction;
bool max_range_ray;
GridT::Accessor acc = m_vdb_grid->getAccessor();
// Creating a temporary grid in which the new data is casted. This way we prevent the computation
// of redundant probability updates in the actual map
GridT::Ptr temp_grid = GridT::create(0.0);
GridT::Accessor temp_acc = temp_grid->getAccessor();
openvdb::Vec3d x;
double ray_length;
// Raycasting of every point in the input cloud
for (const PointT& pt : *cloud)
{
max_range_ray = false;
ray_end_world = openvdb::Vec3d(pt.x, pt.y, pt.z);
if (m_max_range > 0.0 && (ray_end_world - ray_origin_world).length() > m_max_range)
{
ray_end_world = ray_origin_world + (ray_end_world - ray_origin_world).unit() * m_max_range;
max_range_ray = true;
}
ray_direction = m_vdb_grid->worldToIndex(ray_end_world - ray_origin_world);
ray.setEye(ray_origin_index);
ray.setDir(ray_direction);
dda.init(ray);
ray_length = ray_direction.length();
ray_direction.normalize();
// The signed distance is calculated for each DDA step to determine, when the endpoint is
// reached.
double signed_distance = 1;
while (signed_distance >= 0)
{
x = openvdb::Vec3d(dda.voxel().x(), dda.voxel().y(), dda.voxel().z()) - ray_origin_index;
// Signed distance in grid coordinates for faster processing(not scaled with the grid
// resolution!!!)
// The main idea of the dot product is to first get the center of the current voxel and then
// add half the ray direction to gain the outer boundary of this voxel
signed_distance =
ray_length - ray_direction.dot(x + 0.5 + ray_direction / 2.0);
if (signed_distance >= 0)
{
temp_acc.setActiveState(dda.voxel(), true);
dda.step();
}
else
{
// Set the last passed voxel as occupied if the ray wasn't longer than the maximum raycast
// range
if (!max_range_ray)
{
temp_acc.setValueOn(dda.voxel(), -1);
}
}
}
}
// Probability update lambda for free space grid elements
auto miss = [&prob_miss = m_logodds_miss,
&prob_thres_min = m_logodds_thres_min](float& voxel_value, bool& active) {
voxel_value += prob_miss;
if (voxel_value < prob_thres_min)
{
active = false;
}
};
// Probability update lambda for occupied grid elements
auto hit = [&prob_hit = m_logodds_hit, &prob_thres_max = m_logodds_thres_max](float& voxel_value,
bool& active) {
voxel_value += prob_hit;
if (voxel_value > prob_thres_max)
{
active = true;
}
};
// Integrating the data of the temporary grid into the map using the probability update functions
for (GridT::ValueOnCIter iter = temp_grid->cbeginValueOn(); iter; ++iter)
{
if (*iter == -1)
{
acc.modifyValueAndActiveState(iter.getCoord(), hit);
}
else
{
acc.modifyValueAndActiveState(iter.getCoord(), miss);
}
}
return true;
}
void VDBMapping::setConfig(const Config config)
{
// Sanity Check for input config
if (config.prob_miss > 0.5)
{
std::cerr << "Probability for a miss should be below 0.5 but is " << config.prob_miss
<< std::endl;
return;
}
if (config.prob_hit < 0.5)
{
std::cerr << "Probability for a hit should be above 0.5 but is " << config.prob_miss
<< std::endl;
return;
}
if (config.max_range < 0.0)
{
std::cerr << "Max range of " << config.max_range << " invalid. Range cannot be negative."
<< config.prob_miss << std::endl;
return;
}
m_max_range = config.max_range;
// Store probabilities as log odds
m_logodds_miss = log(config.prob_miss) - log(1 - config.prob_miss);
m_logodds_hit = log(config.prob_hit) - log(1 - config.prob_hit);
m_logodds_thres_min = log(config.prob_thres_min) - log(1 - config.prob_thres_min);
m_logodds_thres_max = log(config.prob_thres_max) - log(1 - config.prob_thres_max);
m_config_set = true;
}
| 32.432836
| 99
| 0.637828
|
fzi-forschungszentrum-informatik
|
f46d513866d62800e662f5381531cf2cd4b82e88
| 2,430
|
cpp
|
C++
|
control/groupsform.cpp
|
TheMrButcher/offline-mentor
|
15c362710fc993b21ed2d23adfc98e797e2380db
|
[
"MIT"
] | null | null | null |
control/groupsform.cpp
|
TheMrButcher/offline-mentor
|
15c362710fc993b21ed2d23adfc98e797e2380db
|
[
"MIT"
] | 101
|
2017-03-11T19:09:46.000Z
|
2017-09-04T17:37:55.000Z
|
control/groupsform.cpp
|
TheMrButcher/offline-mentor
|
15c362710fc993b21ed2d23adfc98e797e2380db
|
[
"MIT"
] | 1
|
2018-03-13T03:47:15.000Z
|
2018-03-13T03:47:15.000Z
|
#include "groupsform.h"
#include "ui_groupsform.h"
#include "group_utils.h"
#include "groupdialog.h"
GroupsForm::GroupsForm(QWidget *parent) :
QWidget(parent),
ui(new Ui::GroupsForm)
{
ui->setupUi(this);
}
GroupsForm::~GroupsForm()
{
delete ui;
}
void GroupsForm::load()
{
ui->listWidget->clear();
ui->listWidget->selectionModel()->clear();
for (const auto& group : getGroups()) {
QListWidgetItem* item = new QListWidgetItem(group.name, ui->listWidget);
item->setData(Qt::UserRole, group.id);
}
}
void GroupsForm::onGroupsPathChanged()
{
loadGroups();
load();
emit groupCollectionChanged();
}
void GroupsForm::createGroup()
{
if (!groupDialog)
groupDialog = new GroupDialog(this);
groupDialog->init(Group::createGroup());
if (groupDialog->exec() == QDialog::Accepted) {
auto newGroup = groupDialog->result();
QListWidgetItem* item = new QListWidgetItem(newGroup.name, ui->listWidget);
item->setData(Qt::UserRole, newGroup.id);
addGroup(newGroup);
emit groupAdded(newGroup.id);
}
}
void GroupsForm::editGroupInRow(int row)
{
if (!groupDialog)
groupDialog = new GroupDialog(this);
auto item = ui->listWidget->item(row);
const auto& group = getGroup(item->data(Qt::UserRole).toUuid());
groupDialog->init(group);
if (groupDialog->exec() == QDialog::Accepted) {
auto newGroup = groupDialog->result();
item->setText(newGroup.name);
addGroup(newGroup);
emit groupCollectionChanged();
}
}
void GroupsForm::on_addButton_clicked()
{
createGroup();
}
void GroupsForm::on_editButton_clicked()
{
editGroupInRow(ui->listWidget->selectionModel()->selectedRows()[0].row());
}
void GroupsForm::on_removeButton_clicked()
{
int row = ui->listWidget->selectionModel()->selectedRows()[0].row();
auto item = ui->listWidget->item(row);
removeGroup(item->data(Qt::UserRole).toUuid());
delete item;
ui->listWidget->selectionModel()->clear();
emit groupCollectionChanged();
}
void GroupsForm::on_listWidget_doubleClicked(const QModelIndex &index)
{
editGroupInRow(index.row());
}
void GroupsForm::on_listWidget_itemSelectionChanged()
{
bool isRowSelected = ui->listWidget->selectionModel()->selectedRows().size() == 1;
ui->editButton->setEnabled(isRowSelected);
ui->removeButton->setEnabled(isRowSelected);
}
| 25.578947
| 86
| 0.671605
|
TheMrButcher
|
f46e2fffcd01d3db771283a05a6a14e9cb327b97
| 432
|
cpp
|
C++
|
ArkEngineTest/ArkEngineTest.cpp
|
gamedevboy/ArkEngine
|
1fb1fb153ac73fcbfa75f8e02eb5a26e8993ff01
|
[
"MIT"
] | null | null | null |
ArkEngineTest/ArkEngineTest.cpp
|
gamedevboy/ArkEngine
|
1fb1fb153ac73fcbfa75f8e02eb5a26e8993ff01
|
[
"MIT"
] | null | null | null |
ArkEngineTest/ArkEngineTest.cpp
|
gamedevboy/ArkEngine
|
1fb1fb153ac73fcbfa75f8e02eb5a26e8993ff01
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "CppUnitTest.h"
#include "../ArkEngine/include/ArkEngine/AEModuleManager.h"
#include "../ArkEngine/include/ArkEngine/gfx/AEGFXDevice.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace ArkEngineTest
{
TEST_CLASS(ArkEngineTest)
{
public:
TEST_METHOD(ModuleTest)
{
ArkEngine::GFX::AEGFXDevice device;
ArkEngine::AEModuleManager::Get()->Initialize();
}
};
}
| 19.636364
| 62
| 0.743056
|
gamedevboy
|
f472b7a520d86afbd6c1e38b9fa9230bfe2880da
| 3,156
|
cpp
|
C++
|
day11/day11.cpp
|
throx/advent2020
|
071dee09e6bb2596c3f78c19f9c97d076798c8b3
|
[
"Unlicense"
] | null | null | null |
day11/day11.cpp
|
throx/advent2020
|
071dee09e6bb2596c3f78c19f9c97d076798c8b3
|
[
"Unlicense"
] | null | null | null |
day11/day11.cpp
|
throx/advent2020
|
071dee09e6bb2596c3f78c19f9c97d076798c8b3
|
[
"Unlicense"
] | null | null | null |
#include <iostream>
#include <vector>
#include <string>
#include <numeric>
using namespace std;
int NumOcc(const vector<string>& seats, int x, int y)
{
int maxx = seats[0].length();
int maxy = seats.size();
int numocc = 0;
for (int x1 = max(0, x - 1); x1 < min(maxx, x + 2); ++x1) {
for (int y1 = max(0, y - 1); y1 < min(maxy, y + 2); ++y1) {
if (x != x1 || y != y1) {
if (seats[y1][x1] == '#') {
++numocc;
}
}
}
}
return numocc;
}
int NumOccSeen(const vector<string>& seats, int x, int y)
{
int maxx = seats[0].length();
int maxy = seats.size();
int numocc = 0;
for (int dx = -1; dx <= 1; ++dx) {
for (int dy = -1; dy <= 1; ++dy) {
if (dx != 0 || dy != 0) {
int x1 = x + dx;
int y1 = y + dy;
while (x1 >= 0 && x1 < maxx && y1 >= 0 && y1 < maxy) {
if (seats[y1][x1] == '#') {
++numocc;
break;
}
else if (seats[y1][x1] == 'L') {
break;
}
x1 += dx;
y1 += dy;
}
}
}
}
return numocc;
}
void DoRound(vector<string>& seats, int maxocc = 4, int occfn(const vector<string>&, int, int) = NumOcc)
{
int maxx = seats[0].length();
int maxy = seats.size();
vector<string> newseats;
for (int y = 0; y < maxy; ++y) {
string s;
for (int x = 0; x < maxx; ++x) {
if (seats[y][x] != '.') {
int n = occfn(seats, x, y);
if (n == 0) {
s.push_back('#');
}
else if (n >= maxocc) {
s.push_back('L');
}
else {
s.push_back(seats[y][x]);
}
}
else {
s.push_back('.');
}
}
newseats.push_back(s);
}
seats = newseats;
}
void Dump(const vector<string>& seats)
{
for (auto v : seats) {
cout << v << endl;
}
cout << endl;
}
int Occupancy(const vector<string>& seats)
{
int occ = 0;
for (auto s : seats) {
for (auto c : s) {
if (c == '#') ++occ;
}
}
return occ;
}
int main()
{
vector<string> seats;
string s;
while (getline(cin, s)) {
seats.push_back(s);
}
auto base = seats;
vector<string> prev;
int rounds = 0;
while (prev != seats) {
prev = seats;
DoRound(seats);
++rounds;
//Dump(seats);
}
cout << "Rounds to stable = " << rounds - 1 << endl;
cout << "Occupancy = " << Occupancy(seats) << endl << endl;
seats = base;
rounds = 0;
while (prev != seats) {
prev = seats;
DoRound(seats, 5, NumOccSeen);
++rounds;
//Dump(seats);
}
cout << "Rounds to stable = " << rounds - 1 << endl;
cout << "Occupancy = " << Occupancy(seats) << endl;
}
| 21.616438
| 104
| 0.398289
|
throx
|
f474d24b5559b63aa17cce38e93e1ffaff1cee97
| 2,098
|
cpp
|
C++
|
cpp/leetcode/RemoveComments.cpp
|
danyfang/SourceCode
|
8168f6058648f2a330a7354daf3a73a4d8a4e730
|
[
"MIT"
] | null | null | null |
cpp/leetcode/RemoveComments.cpp
|
danyfang/SourceCode
|
8168f6058648f2a330a7354daf3a73a4d8a4e730
|
[
"MIT"
] | null | null | null |
cpp/leetcode/RemoveComments.cpp
|
danyfang/SourceCode
|
8168f6058648f2a330a7354daf3a73a4d8a4e730
|
[
"MIT"
] | null | null | null |
//Leetcode Problem No 722 Remove Comments
//Solution written by Xuqiang Fang on 30 May, 2018
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <stack>
#include <queue>
#include <regex>
using namespace std;
class Solution{
public:
vector<string> removeComments(vector<string>& source) {
/*
* only a few cases, double slash, block
*/
vector<string> ans;
bool in = false;
string b;
for(auto&s : source){
for(int j=0; j<s.length(); ++j){
if(in){
if(s[j] == '*' && j < s.length() - 1 && s[j+1] == '/'){
in = false;
j++;
}
}
else{
if(s[j] == '/' && j < s.length() - 1 && s[j+1] == '*'){
in = true;
j++;
}
else if(s[j] == '/' && j < s.length() - 1 && s[j+1] == '/'){
break;
}
else{
b.push_back(s[j]);
}
}
}
if(!in && b.length() > 0){
ans.push_back(b);
b = "";
}
}
return ans;
}
};
int main(){
Solution s;
vector<string> s1{"/*Test program */", "int main()", "{ ", " // variable declaration ", "aaa//a"};
vector<string> s2{"a/*comment", "line", "more_comment*/b"};
vector<string> s3{"/*Test program */", "int main()", "{ ", " // variable declaration ", "int a, b, c;", "/* This is a test", " multiline ", " comment for ", " testing */", "a = b + c;", "}"};
vector<string> ans = s.removeComments(s1);
for(auto& a : ans){
cout << a << endl;
}
ans = s.removeComments(s2);
for(auto& a : ans){
cout << a << endl;
}
ans = s.removeComments(s3);
for(auto& a : ans){
cout << a << endl;
}
return 0;
}
| 28.739726
| 203
| 0.408008
|
danyfang
|
f4758d1ca2a898ed6dab41ffc92a79c178fe68b9
| 993
|
hpp
|
C++
|
Converter/include/converter.hpp
|
ref-humbold/CPlusPlus-Gtk
|
acd78ea9ec0fe94c5847b532a05a33b4ca23d898
|
[
"MIT"
] | 1
|
2020-08-06T08:06:43.000Z
|
2020-08-06T08:06:43.000Z
|
Converter/include/converter.hpp
|
ref-humbold/CPlusPlus-Gtk
|
acd78ea9ec0fe94c5847b532a05a33b4ca23d898
|
[
"MIT"
] | null | null | null |
Converter/include/converter.hpp
|
ref-humbold/CPlusPlus-Gtk
|
acd78ea9ec0fe94c5847b532a05a33b4ca23d898
|
[
"MIT"
] | null | null | null |
#ifndef CONVERTER_HPP_
#define CONVERTER_HPP_
#include <cstdlib>
#include <cmath>
#include <exception>
#include <iostream>
#include <stdexcept>
#include <algorithm>
#include <string>
#include <vector>
#include <numeric>
class converter_exception : public std::logic_error
{
public:
explicit converter_exception(const std::string & s) : std::logic_error(s)
{
}
};
class converter
{
private:
enum sign
{
minus,
plus,
nosign
};
public:
converter(int base_in, int base_out);
~converter() = default;
std::string convert(const std::string & number) const;
private:
sign get_sign(const std::string & number) const;
void validate_digits(sign sgn, const std::string & number) const;
long long int to_decimal(const std::string & number) const;
std::vector<int> to_base_out(long long int decimal) const;
std::string build_number(sign sgn, const std::vector<int> & number) const;
int base_in, base_out;
};
#endif
| 20.265306
| 78
| 0.683787
|
ref-humbold
|
f47cb5a5ca81f778eccc1c89e0c3879162d31a72
| 1,921
|
cpp
|
C++
|
mp3encoder/jni/mp3_encoder/libmp3_encoder/mp3_encoder.cpp
|
belieflong/media-dev-android
|
6103cdce4725bc9ab1a8d5d085abbdab26a164dc
|
[
"Apache-2.0"
] | null | null | null |
mp3encoder/jni/mp3_encoder/libmp3_encoder/mp3_encoder.cpp
|
belieflong/media-dev-android
|
6103cdce4725bc9ab1a8d5d085abbdab26a164dc
|
[
"Apache-2.0"
] | null | null | null |
mp3encoder/jni/mp3_encoder/libmp3_encoder/mp3_encoder.cpp
|
belieflong/media-dev-android
|
6103cdce4725bc9ab1a8d5d085abbdab26a164dc
|
[
"Apache-2.0"
] | null | null | null |
#include "mp3_encoder.h"
#define LOG_TAG "Mp3Encoder"
Mp3Encoder::Mp3Encoder() {
}
Mp3Encoder::~Mp3Encoder() {
}
int Mp3Encoder::Init(const char* pcmFilePath, const char *mp3FilePath, int sampleRate, int channels, int bitRate) {
int ret = -1;
pcmFile = fopen(pcmFilePath, "rb");
if(pcmFile) {
mp3File = fopen(mp3FilePath, "wb");
if(mp3File) {
lameClient = lame_init();
lame_set_in_samplerate(lameClient, sampleRate);
lame_set_out_samplerate(lameClient, sampleRate);
lame_set_num_channels(lameClient, channels);
lame_set_brate(lameClient, bitRate / 1000);
lame_init_params(lameClient);
ret = 0;
}
}
return ret;
}
void Mp3Encoder::Encode() {
int bufferSize = 1024 * 512; // 缓冲区的数据量大小 (512KB)
short* buffer = new short[bufferSize / 2]; //262144[bit] -> 256[Byte] (262144B -> 256KB)
short* leftBuffer = new short[bufferSize / 4];
short* rightBuffer = new short[bufferSize / 4];
uint8_t* mp3_buffer = new uint8_t[bufferSize];
int readBufferSize = 0;
LOGD("sizeof(short) = %zd", sizeof(short));
//将PCM数据读取到 buffer 中,一次性读 2*(bufferSize / 2)的数据量
while ((readBufferSize = fread(buffer, 2, bufferSize / 2, pcmFile)) > 0) {
for (int i = 0; i < readBufferSize; i++) {
// 读取到的长度 分割为两半:一半左声道、一半右声道,分别填充数据
if (i % 2 == 0) {
leftBuffer[i / 2] = buffer[i];
} else {
rightBuffer[i / 2] = buffer[i];
}
}
LOGD("readBufferSize = %d", readBufferSize); // 成功读取的元素总数 * size(short) = pcm的总字节数
//左声道数据、右声道数据、每个通道的样本数量、MP3buffer、buffer大小 ->返回每段数据 编码后的长度,写入文件
int wroteSize = lame_encode_buffer(lameClient, (short int *) leftBuffer, (short int *) rightBuffer, readBufferSize / 2, mp3_buffer, bufferSize);
fwrite(mp3_buffer, 1, wroteSize, mp3File);
}
delete[] buffer;
delete[] leftBuffer;
delete[] rightBuffer;
delete[] mp3_buffer;
}
void Mp3Encoder::Destory() {
if(pcmFile) {
fclose(pcmFile);
}
if(mp3File) {
fclose(mp3File);
lame_close(lameClient);
}
}
| 28.671642
| 146
| 0.68506
|
belieflong
|
f47e2107c702f649175447aec68f6acf7eaff645
| 254
|
hpp
|
C++
|
pythran/pythonic/include/operator_/__itruediv__.hpp
|
xmar/pythran
|
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
|
[
"BSD-3-Clause"
] | null | null | null |
pythran/pythonic/include/operator_/__itruediv__.hpp
|
xmar/pythran
|
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
|
[
"BSD-3-Clause"
] | null | null | null |
pythran/pythonic/include/operator_/__itruediv__.hpp
|
xmar/pythran
|
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef PYTHONIC_INCLUDE_OPERATOR_ITRUEDIV__HPP
#define PYTHONIC_INCLUDE_OPERATOR_ITRUEDIV__HPP
#include "pythonic/include/operator_/itruediv.hpp"
namespace pythonic
{
namespace operator_
{
USING_FUNCTOR(__itruediv__, itruediv);
}
}
#endif
| 15.875
| 50
| 0.807087
|
xmar
|
f47e9665cb2ddbe80c4ea6ef19e806cc109ec4d8
| 5,435
|
cpp
|
C++
|
LexRisLogic/src/MathStructures/Polygon.cpp
|
chanochambure/LexRisLogicHeaders
|
00a07ac1aa3f5122dcbe7a38c2e3e7dc740ed2f6
|
[
"MIT"
] | 2
|
2016-01-31T03:32:25.000Z
|
2020-12-07T02:59:35.000Z
|
LexRisLogic/src/MathStructures/Polygon.cpp
|
chanochambure/LexRisLogicHeaders
|
00a07ac1aa3f5122dcbe7a38c2e3e7dc740ed2f6
|
[
"MIT"
] | null | null | null |
LexRisLogic/src/MathStructures/Polygon.cpp
|
chanochambure/LexRisLogicHeaders
|
00a07ac1aa3f5122dcbe7a38c2e3e7dc740ed2f6
|
[
"MIT"
] | null | null | null |
/* Polygon.cpp -- Polygon Math Structure Source - LexRis Logic Headers
Copyright (c) 2017-2018 LexRisLogic
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.
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 "../../include/LexRisLogic/MathStructures/Polygon.h"
namespace LL_MathStructure
{
bool Polygon::add_point(Point point)
{
if(point.get_dimension()==2)
{
_V_points.push_back(point);
return true;
}
return false;
}
bool Polygon::remove_point(unsigned int index)
{
if(index>=_V_points.size())
return false;
_V_points.erase(_V_points.begin()+index);
return true;
}
unsigned int Polygon::size()
{
return _V_points.size();
}
void Polygon::clear()
{
_V_points.clear();
}
bool Polygon::set_point(unsigned int index,Point new_point)
{
if(new_point.get_dimension()==2 and index<_V_points.size())
{
_V_points[index]=new_point;
return true;
}
return false;
}
const Point Polygon::operator [] (unsigned int index)
{
return _V_points[index];
}
bool LL_SHARED point_into_polygon(Polygon polygon,Point point)
{
if(point.get_dimension()==2 and polygon.size()>2)
{
float max_pos_x=polygon[0][0];
for(unsigned int i=1;i<polygon.size();++i)
{
if(polygon[i][0]>max_pos_x)
max_pos_x=polygon[i][0];
}
unsigned int count_intersection=0;
for(unsigned int i=0;i<polygon.size();++i)
{
unsigned int j=(i+1)%polygon.size();
LineSegment first_segment(2);
first_segment.set_ini_point(point);
first_segment.set_end_point(create_point(max_pos_x+1,point[1]));
LineSegment second_segment(2);
second_segment.set_ini_point(polygon[i]);
second_segment.set_end_point(polygon[j]);
count_intersection+=intersection_of_line_segments_in_two_dimensions(first_segment,second_segment);
}
return count_intersection%2;
}
return false;
}
bool LL_SHARED collision_of_polygons(Polygon first_polygon,Polygon second_polygon,std::list<Point>* points)
{
if(first_polygon.size()>2 and second_polygon.size()>2)
{
for(unsigned int i=0;i<first_polygon.size();++i)
{
unsigned int j=(i+1)%first_polygon.size();
for(unsigned int k=0;k<second_polygon.size();++k)
{
unsigned int l=(k+1)%second_polygon.size();
float intersection_x;
float intersection_y;
LineSegment first_segment(2);
first_segment.set_ini_point(first_polygon[i]);
first_segment.set_end_point(first_polygon[j]);
LineSegment second_segment(2);
second_segment.set_ini_point(second_polygon[k]);
second_segment.set_end_point(second_polygon[l]);
if(intersection_of_line_segments_in_two_dimensions(first_segment,second_segment,
&intersection_x,&intersection_y))
{
if(points)
{
bool insertion=true;
for(std::list<Point>::iterator m=points->begin();m!=points->end();++m)
{
if((*m)[0]==intersection_x and (*m)[1]==intersection_y)
{
insertion=false;
break;
}
}
if(insertion)
points->push_back(create_point(intersection_x,intersection_y));
}
else
return true;
}
}
}
if(points and points->size())
return true;
return (point_into_polygon(first_polygon,second_polygon[0]) or
point_into_polygon(second_polygon,first_polygon[0]));
}
return false;
}
}
| 39.384058
| 119
| 0.552714
|
chanochambure
|
f4858b21356f076b7544d53c05055b358c718911
| 3,229
|
hpp
|
C++
|
src/Zv8/V8Engine.hpp
|
indie-zen/zen-server
|
deb4485fe462d6c88eeeadb09c62e6024e06ff67
|
[
"MIT"
] | null | null | null |
src/Zv8/V8Engine.hpp
|
indie-zen/zen-server
|
deb4485fe462d6c88eeeadb09c62e6024e06ff67
|
[
"MIT"
] | 8
|
2016-12-06T15:55:28.000Z
|
2016-12-18T17:31:36.000Z
|
src/Zv8/V8Engine.hpp
|
indie-zen/zen-server
|
deb4485fe462d6c88eeeadb09c62e6024e06ff67
|
[
"MIT"
] | null | null | null |
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
// V8 plugin for Zen Scripting
//
// Copyright (C) 2001 - 2016 Raymond A. Richards
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
#pragma once
#include <Zen/Scripting/I_ScriptEngine.hpp>
#include <memory>
#include <v8.h>
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
namespace Zen {
namespace Zv8 {
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
class V8Engine
: public Zen::Scripting::I_ScriptEngine
, public std::enable_shared_from_this<V8Engine>
{
/// @name I_ScriptEngine implementation
/// @{
public:
virtual void initialize(pConfiguration_type _pConfiguration = nullptr);
virtual Scripting::I_ObjectHeap& heap();
virtual bool executeScript(const std::string& _fileName);
virtual void executeMethod(boost::any& _object, boost::any& _method, std::vector<boost::any>& _parms);
virtual pScriptModule_type createScriptModule(const std::string& _moduleName, const std::string& _docString);
/// @}
/// @name V8Engine implementation
/// @{
public:
/// Implementation of managed_self_ref from Zen 1.x
std::shared_ptr<V8Engine> getSelfReference();
/// Execute a script that is embedded in a string
/// @param _source - String to execute
/// @param _name - Name of the string (usually the URI where the string
/// was loaded from)
/// @param _printResult - output the results of the script to std::cout
/// @param _reportExceptions - output an exception report if the script throws
/// an uncaught exception.
bool executeString(v8::Local<v8::String> _source, v8::Local<v8::Value> _name,
bool _printResult, bool _reportExecptions);
/// Read a file into a (maybe local) string
/// @todo Zen Server should not support direct file access; instead, all
/// source must be loaded from a container local segment of Zen Spaces.
/// This is only being supported as a temporary measure until Zen Spaces
/// integration is complete.
v8::MaybeLocal<v8::String> readFile(const std::string& _scriptName);
/// Report an exception
/// Output an exception to std::cout (maybe it should be std::cerr?)
void reportException(v8::TryCatch* _pTryCatch);
/// Convert a v8 string to a C string
const char* toCString(const v8::String::Utf8Value& value);
v8::Isolate* getIsolate();
/// @}
/// @name 'Structors
/// @{
public:
V8Engine();
virtual ~V8Engine();
/// @}
/// @name Member variables
/// @{
private:
v8::Platform* m_pPlatform;
v8::Isolate* m_pIsolate;
v8::Isolate::Scope* m_pGlobalScope;
v8::HandleScope* m_pHandleScope;
// v8::Global<v8::ObjectTemplate> m_global;
v8::Global<v8::Context> m_context;
/// @}
}; // class V8Engine
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
} // namespace Zv8
} // namespace Zen
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
| 35.483516
| 113
| 0.549396
|
indie-zen
|
f498dc62d5bebae3e8bd7c1efbc82658400f67d4
| 2,051
|
cpp
|
C++
|
Semester1/Homeworks/HW7.Lists/7.3/7.3/list.cpp
|
PavelSaltykov/Course1
|
68920c4a4679b6dd0e0b83cb8109d3c52d2cf076
|
[
"Apache-2.0"
] | null | null | null |
Semester1/Homeworks/HW7.Lists/7.3/7.3/list.cpp
|
PavelSaltykov/Course1
|
68920c4a4679b6dd0e0b83cb8109d3c52d2cf076
|
[
"Apache-2.0"
] | 2
|
2019-12-17T11:58:46.000Z
|
2019-12-21T20:08:01.000Z
|
Semester1/Homeworks/HW7.Lists/7.3/7.3/list.cpp
|
PavelSaltykov/Course1
|
68920c4a4679b6dd0e0b83cb8109d3c52d2cf076
|
[
"Apache-2.0"
] | 1
|
2020-02-24T18:28:00.000Z
|
2020-02-24T18:28:00.000Z
|
#include <stdio.h>
#include <string.h>
#include "list.h"
struct Entry
{
char *name = nullptr;
char *phone = nullptr;
Entry *next = nullptr;
};
struct List
{
int length = 0;
Entry *head = nullptr;
Entry *tail = nullptr;
};
List *createList()
{
return new List;
}
bool isEmpty(List *list)
{
return list->head == nullptr;
}
void addEntry(List *list, char *name, char *phone)
{
list->length++;
char *newName = new char[strlen(name) + 1];
char *newPhone = new char[strlen(phone) + 1];
strcpy(newName, name);
strcpy(newPhone, phone);
Entry *newEntry = new Entry {newName, newPhone, nullptr};
if (isEmpty(list))
{
list->head = newEntry;
list->tail = list->head;
return;
}
list->tail->next = newEntry;
list->tail = list->tail->next;
}
char *returnNameFromHead(List *list)
{
return list->head->name;
}
char *returnPhoneFromHead(List *list)
{
return list->head->phone;
}
int listLength(List *list)
{
return list->length;
}
void deleteHead(List *list)
{
if (isEmpty(list))
{
return;
}
list->length--;
Entry *temp = list->head->next;
delete list->head->name;
delete list->head->phone;
delete list->head;
list->head = temp;
}
bool checkSort(List *list, bool byName)
{
if (isEmpty(list))
{
return true;
}
Entry *current = list->head->next;
Entry *previous = list->head;
while (current != nullptr)
{
int comparison = 0;
if (byName)
{
comparison = strcmp(current->name, previous->name);
}
else
{
comparison = strcmp(current->phone, previous->phone);
}
if (comparison < 0)
{
return false;
}
previous = current;
current = current->next;
}
return true;
}
void printList(List *list)
{
if (isEmpty(list))
{
return;
}
Entry *current = list->head;
while (current != nullptr)
{
printf("%s - %s\n", current->name, current->phone);
current = current->next;
}
}
void deleteList(List *list)
{
while (!isEmpty(list))
{
Entry *temp = list->head->next;
delete list->head->name;
delete list->head->phone;
delete list->head;
list->head = temp;
}
delete list;
}
| 15.537879
| 58
| 0.641151
|
PavelSaltykov
|
f49da775121857bfc051cb595e70bbd9923d03ea
| 3,588
|
cpp
|
C++
|
main.cpp
|
DennisZZH/CS263_Project_Garbage_Collector
|
07e81c0eb532792cb3d1fd504b501bca67b5365d
|
[
"MIT"
] | null | null | null |
main.cpp
|
DennisZZH/CS263_Project_Garbage_Collector
|
07e81c0eb532792cb3d1fd504b501bca67b5365d
|
[
"MIT"
] | null | null | null |
main.cpp
|
DennisZZH/CS263_Project_Garbage_Collector
|
07e81c0eb532792cb3d1fd504b501bca67b5365d
|
[
"MIT"
] | null | null | null |
#include <fstream>
#include <iostream>
#include <sstream>
#include "frontend/lexer.h"
#include "frontend/parser.h"
#include "backend/codegen.h"
using namespace cs160::frontend;
using namespace cs160::backend;
void usage(char const* programName) {
std::cerr << "Usage: " << programName << " program.l2 [--gen-asm-only] output-file\n\n"
<< "This program compiles given L2 program. If the `--gen-asm-only` option is given, it will only generate the assembly code, otherwise it will also link the assembly code with the bootstrap code and GC code to produce an executable.";
}
// Option for generating assembly only
const std::string OnlyGenAsm{"--gen-asm-only"};
// C++ compiler. We use it as linker. GCC's C++ compier is usually named `g++` on most systems.
const std::string CPPCompiler{"g++"};
// Name of the assembler program. GNU assembler is usually named `as` on most systems.
const std::string Assembler{"as"};
int main(int argc, char* argv[]) {
std::string outputFileName;
bool link = true;
if (argc == 3) {
outputFileName = argv[2];
} else if (argc == 4 && OnlyGenAsm == argv[2]) {
outputFileName = argv[3];
link = false;
} else{
usage(argv[0]);
return 1;
}
std::ifstream programFile{argv[1]};
if (!programFile.is_open()) {
std::cerr << "'" << argv[1]
<< "' does not exist or is not a regular file.\n\n";
usage(argv[0]);
} // Read the file
std::string programText{std::istreambuf_iterator<char>(programFile),
std::istreambuf_iterator<char>()};
// Run the lexer
std::cout << "Lexing the input program '" << argv[1] << "'" << std::endl;
Lexer lexer;
auto tokens = lexer.tokenize(programText);
// Run the parser
std::cout << "Parsing the token stream" << std::endl;
Parser parser(tokens);
auto ast = parser.parse();
if (! ast) {
std::cerr << "Parse error: the parser produced an empty unique_ptr" << std::endl;
return 1;
}
// Run the code generator
std::cout << "Generating code" << std::endl;
CodeGen codeGen;
auto insns = codeGen.generateCode(*ast);
// Write out the assembly file
std::string asmFileName = link ? (outputFileName + ".asm") : outputFileName;
std::ofstream asmFile{asmFileName};
if (!asmFile.is_open()) {
std::cerr << "Failed to open the assembly file '" << asmFileName << "'" << std::endl;
return 1;
}
for (auto & line : insns) {
asmFile << line << "\n";
}
asmFile.close();
// Assemble and link to build an executable
if (link) {
// Assemble the object file
std::cout << "Calling the assembler on the assembly code to build\n";
std::ostringstream cmdLine;
cmdLine << Assembler << " --32 -g " << asmFileName << " -o " << outputFileName << ".o";
auto cmd = cmdLine.str();
std::cout << "Running assembler command: " << cmd << std::endl;
if (auto err = std::system(cmd.c_str())) {
std::cerr << "Assembler command exited with error code " << err << std::endl;
return 1;
}
// Link the object files
std::cout << "Linking the bootstrap code with L2 program object code\n";
// reset the command line
cmdLine = std::ostringstream{};
cmdLine << CPPCompiler << " -m32 build/bootstrap.o build/gc.o " << outputFileName << ".o -o " << outputFileName;
cmd = cmdLine.str();
std::cout << "Running linker command: " << cmd << std::endl;
// Run the linker
if (auto err = std::system(cmd.c_str())) {
std::cerr << "Linker exited with error code " << err << std::endl;
return 1;
}
}
return 0;
}
| 31.752212
| 247
| 0.625139
|
DennisZZH
|
f4a5bfba34e14bc084fff11d5e9053a3bf5831ca
| 3,815
|
cpp
|
C++
|
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgWrappers/osgParticle/Emitter.cpp
|
UM-ARM-Lab/mab_ms
|
f199f05b88060182cfbb47706bd1ff3479032c43
|
[
"BSD-2-Clause"
] | 3
|
2018-08-20T12:12:43.000Z
|
2021-06-06T09:43:27.000Z
|
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgWrappers/osgParticle/Emitter.cpp
|
UM-ARM-Lab/mab_ms
|
f199f05b88060182cfbb47706bd1ff3479032c43
|
[
"BSD-2-Clause"
] | null | null | null |
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgWrappers/osgParticle/Emitter.cpp
|
UM-ARM-Lab/mab_ms
|
f199f05b88060182cfbb47706bd1ff3479032c43
|
[
"BSD-2-Clause"
] | 1
|
2022-03-31T03:12:23.000Z
|
2022-03-31T03:12:23.000Z
|
// ***************************************************************************
//
// Generated automatically by genwrapper.
// Please DO NOT EDIT this file!
//
// ***************************************************************************
#include <osgIntrospection/ReflectionMacros>
#include <osgIntrospection/TypedMethodInfo>
#include <osgIntrospection/StaticMethodInfo>
#include <osgIntrospection/Attributes>
#include <osg/CopyOp>
#include <osg/NodeVisitor>
#include <osg/Object>
#include <osgParticle/Emitter>
#include <osgParticle/Particle>
// Must undefine IN and OUT macros defined in Windows headers
#ifdef IN
#undef IN
#endif
#ifdef OUT
#undef OUT
#endif
BEGIN_ABSTRACT_OBJECT_REFLECTOR(osgParticle::Emitter)
I_DeclaringFile("osgParticle/Emitter");
I_BaseType(osgParticle::ParticleProcessor);
I_Constructor0(____Emitter,
"",
"");
I_ConstructorWithDefaults2(IN, const osgParticle::Emitter &, copy, , IN, const osg::CopyOp &, copyop, osg::CopyOp::SHALLOW_COPY,
____Emitter__C5_Emitter_R1__C5_osg_CopyOp_R1,
"",
"");
I_Method0(const char *, libraryName,
Properties::VIRTUAL,
__C5_char_P1__libraryName,
"return the name of the node's library. ",
"");
I_Method0(const char *, className,
Properties::VIRTUAL,
__C5_char_P1__className,
"return the name of the node's class type. ",
"");
I_Method1(bool, isSameKindAs, IN, const osg::Object *, obj,
Properties::VIRTUAL,
__bool__isSameKindAs__C5_osg_Object_P1,
"return true if this and obj are of the same kind of object. ",
"");
I_Method1(void, accept, IN, osg::NodeVisitor &, nv,
Properties::VIRTUAL,
__void__accept__osg_NodeVisitor_R1,
"Visitor Pattern : calls the apply method of a NodeVisitor with this node's type. ",
"");
I_Method0(const osgParticle::Particle &, getParticleTemplate,
Properties::NON_VIRTUAL,
__C5_Particle_R1__getParticleTemplate,
"Get the particle template. ",
"");
I_Method1(void, setParticleTemplate, IN, const osgParticle::Particle &, p,
Properties::NON_VIRTUAL,
__void__setParticleTemplate__C5_Particle_R1,
"Set the particle template (particle is copied). ",
"");
I_Method0(bool, getUseDefaultTemplate,
Properties::NON_VIRTUAL,
__bool__getUseDefaultTemplate,
"Return whether the particle system's default template should be used. ",
"");
I_Method1(void, setUseDefaultTemplate, IN, bool, v,
Properties::NON_VIRTUAL,
__void__setUseDefaultTemplate__bool,
"Set whether the default particle template should be used. ",
"When this flag is true, the particle template is ignored, and the particle system's default template is used instead. ");
I_ProtectedMethod1(void, process, IN, double, dt,
Properties::VIRTUAL,
Properties::NON_CONST,
__void__process__double,
"",
"");
I_ProtectedMethod1(void, emit, IN, double, dt,
Properties::PURE_VIRTUAL,
Properties::NON_CONST,
__void__emit__double,
"",
"");
I_SimpleProperty(const osgParticle::Particle &, ParticleTemplate,
__C5_Particle_R1__getParticleTemplate,
__void__setParticleTemplate__C5_Particle_R1);
I_SimpleProperty(bool, UseDefaultTemplate,
__bool__getUseDefaultTemplate,
__void__setUseDefaultTemplate__bool);
END_REFLECTOR
| 39.329897
| 133
| 0.603932
|
UM-ARM-Lab
|
f4ab84cd87a1853294e48fc98a7110a2fd1a11f9
| 6,507
|
hpp
|
C++
|
Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_StdClass.hpp
|
MarkStega/CIDLib
|
82014e064eef51cad998bf2c694ed9c1c8cceac6
|
[
"MIT"
] | 216
|
2019-03-09T06:41:28.000Z
|
2022-02-25T16:27:19.000Z
|
Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_StdClass.hpp
|
MarkStega/CIDLib
|
82014e064eef51cad998bf2c694ed9c1c8cceac6
|
[
"MIT"
] | 9
|
2020-09-27T08:00:52.000Z
|
2021-07-02T14:27:31.000Z
|
Source/AllProjects/LangUtils/CIDMacroEng/CIDMacroEng_StdClass.hpp
|
MarkStega/CIDLib
|
82014e064eef51cad998bf2c694ed9c1c8cceac6
|
[
"MIT"
] | 29
|
2019-03-09T10:12:24.000Z
|
2021-03-03T22:25:29.000Z
|
//
// FILE NAME: CIDMacroEng_StdClass.hpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 01/24/2003
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2019
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This is the header file for the CIDMacroEng_StdClass.cpp file, which
// implements derivates of the class info and class value classes that are
// used by the compiler for compiled macros from user code. These classes
// are all the same except for the classpath of the class. The members of
// such a class are all dynamically controlled and added as method, var,
// import, and so forth objects. The invocation is just a passthrough to
// the targeted method object.
//
// The value class is just a dummy, since we don't need any actual C++
// level data members, but we must have an instance data class. At some
// point, it might be used to keep some housekeeping, instrumentation, or
// debugging info. The macro level member objects are handled by the common
// base value class. Any classes which only need macro level members objects
// can use this class for their value object, which is all macro level
// defined classes, but also any wrapped C++ classes which store their
// data as standard macro level value objects (and they all should if they
// can.)
//
// Copying to and from involves copying the contents of each defined
// variable for that class. We initially set the class as copyable, but
// if any non-coypable member is added, it becomes non-copyable.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $_CIDLib_Log_$
//
#pragma once
#pragma CIDLIB_PACK(CIDLIBPACK)
class TMEngStdClassInfo;
// ---------------------------------------------------------------------------
// CLASS: TMEngStdClassVal
// PREFIX: mecv
// ---------------------------------------------------------------------------
class CIDMACROENGEXP TMEngStdClassVal : public TMEngClassVal
{
public :
// -------------------------------------------------------------------
// Constructors and Destructor
// -------------------------------------------------------------------
TMEngStdClassVal
(
const TString& strName
, const tCIDLib::TCard2 c2ClassId
, const tCIDMacroEng::EConstTypes eConst
);
TMEngStdClassVal(const TMEngStdClassVal&) = delete;
~TMEngStdClassVal();
// -------------------------------------------------------------------
// Public operators
// -------------------------------------------------------------------
TMEngStdClassVal& operator=(const TMEngStdClassVal&) = delete;
// -------------------------------------------------------------------
// Public, inherited methods
// -------------------------------------------------------------------
tCIDLib::TBoolean bDbgFormat
(
TTextOutStream& strmTarget
, const TMEngClassInfo& meciThis
, const tCIDMacroEng::EDbgFmts eFormat
, const tCIDLib::ERadices eRadix
, const TCIDMacroEngine& meOwner
) const override;
tCIDLib::TVoid CopyFrom
(
const TMEngClassVal& mecvToCopy
, TCIDMacroEngine& meOwner
) override;
protected :
// -------------------------------------------------------------------
// Declare our friends. We want our info class to be our friend so
// that, when he creates a new instance, he can load us up with
// value objects for our members.
// -------------------------------------------------------------------
friend class TMEngStdClassInfo;
private :
// -------------------------------------------------------------------
// Do any needed magic macros
// -------------------------------------------------------------------
RTTIDefs(TMEngStdClassVal,TMEngClassVal)
};
// ---------------------------------------------------------------------------
// CLASS: TMEngStdClassInfo
// PREFIX: meci
// ---------------------------------------------------------------------------
class CIDMACROENGEXP TMEngStdClassInfo : public TMEngClassInfo
{
public :
// -------------------------------------------------------------------
// Constructors and Destructor
// -------------------------------------------------------------------
TMEngStdClassInfo
(
const TString& strName
, const TString& strBasePath
, TCIDMacroEngine& meOwner
, const TString& strParentClassPath
);
TMEngStdClassInfo(const TMEngStdClassInfo&) = delete;
~TMEngStdClassInfo();
// -------------------------------------------------------------------
// Public operators
// -------------------------------------------------------------------
TMEngStdClassInfo& operator=(const TMEngStdClassInfo&) = delete;
// -------------------------------------------------------------------
// Public, inherited methods
// -------------------------------------------------------------------
TMEngClassVal* pmecvMakeStorage
(
const TString& strName
, TCIDMacroEngine& meOwner
, const tCIDMacroEng::EConstTypes eConst
) const override;
protected :
// -------------------------------------------------------------------
// Protected, inherited methods
// -------------------------------------------------------------------
tCIDLib::TBoolean bInvokeMethod
(
TCIDMacroEngine& meOwner
, const TMEngMethodInfo& methiTarget
, TMEngClassVal& mecvInstance
) override;
private :
// -------------------------------------------------------------------
// Do any needed magic macros
// -------------------------------------------------------------------
RTTIDefs(TMEngStdClassInfo,TMEngClassInfo)
};
#pragma CIDLIB_POPPACK
| 35.950276
| 78
| 0.442908
|
MarkStega
|
f4ac64b514f7a6a1259d2da3562e3034220407b8
| 16,221
|
cc
|
C++
|
swap-ssdb-1.9.2/tests/qa/integration/hash_test.cc
|
TimothyZhang023/swapdb
|
e40c1ddf46892e698acf54f26b02927f0505ea84
|
[
"BSD-2-Clause"
] | 242
|
2017-12-14T00:31:28.000Z
|
2022-02-16T02:00:15.000Z
|
swap-ssdb-1.9.2/tests/qa/integration/hash_test.cc
|
javaperson/swapdb
|
66efd9f919dfaa56dcefd9b39a8bdabe57624546
|
[
"BSD-2-Clause"
] | 7
|
2017-12-14T08:34:43.000Z
|
2020-12-19T02:53:03.000Z
|
swap-ssdb-1.9.2/tests/qa/integration/hash_test.cc
|
javaperson/swapdb
|
66efd9f919dfaa56dcefd9b39a8bdabe57624546
|
[
"BSD-2-Clause"
] | 47
|
2017-12-26T03:11:26.000Z
|
2022-01-26T07:46:45.000Z
|
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <sstream>
#include "SSDB_client.h"
#include "gtest/gtest.h"
#include "ssdb_test.h"
using namespace std;
class HashTest : public SSDBTest
{
public:
ssdb::Status s;
std::vector<std::string> list, keys, kvs2;
std::map<std::string, std::string> kvs;
string key, val, getVal, field;
uint16_t keysNum;
int64_t ret;
};
TEST_F(HashTest, Test_hash_hset) {
#define OKHset s = client->hset(key, field, val);\
ASSERT_TRUE(s.ok())<<"fail to hset key!"<<endl;\
s = client->hget(key, field, &getVal);\
ASSERT_TRUE(s.ok()&&(val == getVal))<<"fail to hget key val!"<<s.code()<<key<<endl;
#define FalseHset s = client->hset(key, field, val);\
ASSERT_TRUE(s.error())<<"this key should set fail!"<<s.code()<<endl;
// Some special keys
for(vector<string>::iterator it = Keys.begin(); it != Keys.end(); it++)
{
key = *it;
field = GetRandomField_();
val = GetRandomVal_();
s = client->multi_del(key);
OKHset
// set exsit key
field = GetRandomField_();
val = GetRandomVal_();
OKHset
s = client->multi_del(key);
}
// Some random keys
keysNum = 100;
val = "";
key = GetRandomKey_();
field = GetRandomField_();
s = client->multi_del(key);
for(int n = 0; n < keysNum; n++)
{
field = field+itoa(n);
OKHset
}
s = client->hsize(key, &ret);
ASSERT_EQ(keysNum, ret);
s = client->multi_del(key);
//other types key
field = GetRandomField_();
val = GetRandomVal_();
client->multi_del(key);
s = client->set(key, val);
FalseHset
client->multi_del(key);
client->sadd(key, val);
FalseHset
client->multi_del(key);
client->qpush_front(key, val);
FalseHset
client->multi_del(key);
client->zset(key, field, 1.0);
FalseHset
client->multi_del(key);
}
TEST_F(HashTest, Test_hash_hget) {
#define NotFoundHget s = client->hget(key, field, &getVal);\
ASSERT_TRUE(s.not_found())<<"this key should be not found!"<<endl;
// Some random keys
for(int n = 0; n < 5; n++)
{
key = GetRandomKey_();
val = GetRandomVal_();
field = GetRandomField_();
s = client->multi_del(key);
NotFoundHget
}
keysNum = 100;
for(int n = 0; n < keysNum; n++)
{
field = field+itoa(n);
s = client->hset(key, field, val);
}
field = field+itoa(keysNum);
NotFoundHget
s = client->multi_del(key);
}
TEST_F(HashTest, Test_hash_hdel) {
#define OKHdel s = client->multi_hdel(key, field);\
ASSERT_TRUE(s.ok())<<"fail to delete key!"<<key<<endl;\
s = client->hget(key, field, &getVal);\
ASSERT_TRUE(s.not_found())<<"this key should be deleted!"<<key<<endl;
#define NotFoundHdel s = client->multi_hdel(key, field);\
ASSERT_TRUE(s.not_found())<<"this key should be not found!"<<endl;
//Some special keys
for(vector<string>::iterator it = Keys.begin(); it != Keys.end(); it++)
{
key = *it;
client->multi_del(key);
val = GetRandomVal_();
field = GetRandomField_();
s = client->hset(key, field, val);
OKHdel
// NotFoundHdel
}
keysNum = 100;
val = "";
for(int n = 0; n < keysNum; n++)
{
field = field+itoa(n);
s = client->hset(key, field, val);
OKHdel
// NotFoundHdel
}
}
TEST_F(HashTest, Test_hash_hincrby) {
#define OKHincr incr = GetRandomInt64_();\
s = client->multi_del(key);\
s = client->hincr(key, field, incr, &ret);\
ASSERT_TRUE(s.ok());\
s = client->hget(key, field, &getVal);\
ASSERT_EQ(to_string(incr), getVal);\
\
s = client->hincr(key, field, n, &ret);\
ASSERT_TRUE(s.ok());\
s = client->hget(key, field, &getVal);\
ASSERT_EQ(to_string(incr+n), getVal);\
s = client->multi_hdel(key, field);
#define FalseHincr s = client->hincr(key, field, 1, &ret);\
ASSERT_TRUE(s.error())<<"this key should hincr fail!"<<endl;
int64_t incr, ret, n = 0;
//Some special keys
for(vector<string>::iterator it = Keys.begin(); it != Keys.end(); it++)
{
n++;
key = *it;
field = GetRandomField_();
OKHincr
client->multi_del(key);
}
//Some random keys
keysNum = 10;
val = "";
for(n = 0; n < keysNum; n++)
{
key = GetRandomKey_();
field = GetRandomField_();
OKHincr
client->multi_del(key);
}
s = client->multi_del(key);
s = client->hincr(key, field, MAX_INT64, &ret);
s = client->hget(key, field, &getVal);
ASSERT_EQ(i64toa(MAX_INT64), getVal);
s = client->hincr(key, field, 1, &ret);
ASSERT_TRUE(s.error());
s = client->hget(key, field, &getVal);
ASSERT_EQ(i64toa(MAX_INT64), getVal);
s = client->multi_del(key);
s = client->hincr(key, field, MIN_INT64, &ret);
ASSERT_EQ((MIN_INT64), ret);
s = client->hget(key, field, &getVal);
ASSERT_EQ(i64toa(MIN_INT64), getVal);
s = client->hincr(key, field, -1, &ret);
ASSERT_TRUE(s.error());
s = client->hget(key, field, &getVal);
ASSERT_EQ(i64toa(MIN_INT64), getVal);
s = client->multi_hdel(key, field);
//other types key
field = GetRandomField_();
val = GetRandomVal_();
client->multi_del(key);
s = client->set(key, val);
FalseHincr
client->multi_del(key);
client->sadd(key, val);
FalseHincr
client->multi_del(key);
client->qpush_front(key, val);
FalseHincr
client->multi_del(key);
client->zset(key, field, 1.0);
FalseHincr
client->multi_del(key);
}
//hdecr removed
//TEST_F(HashTest, Test_hash_hdecrby) {
//#define OKHdecr decr = GetRandomInt64_();\
// s = client->multi_del(key);\
// s = client->hdecr(key, field, decr, &ret);\
// ASSERT_TRUE(s.ok());\
// s = client->hget(key, field, &getVal);\
// ASSERT_EQ(to_string(-1*decr), getVal);\
// \
// s = client->hdecr(key, field, n, &ret);\
// ASSERT_TRUE(s.ok());\
// s = client->hget(key, field, &getVal);\
// ASSERT_EQ(to_string(-1*(decr+n)), getVal);\
// s = client->multi_hdel(key, field);
//
// int64_t decr, ret, n = 0;
// //Some special keys
// for(vector<string>::iterator it = Keys.begin(); it != Keys.end(); it++)
// {
// n++;
// key = *it;
// field = GetRandomField_();
// OKHdecr
// client->multi_del(key);
// }
//}
TEST_F(HashTest, Test_hash_hgetall) {
#define NotExsitHgetall s = client->hgetall(key, &list);\
ASSERT_TRUE(s.ok());\
ASSERT_EQ(0, list.size())<<"get list should be empty!"<<endl;
// EXPECT_TRUE(s.not_found())<<"this key should be not found!"<<endl;
key = GetRandomKey_();
val = GetRandomVal_();
field = GetRandomField_();
s = client->multi_del(key);
NotExsitHgetall
keysNum = 10;
for(int n = 0; n < keysNum; n++)
{
field = field+itoa(n);
val = val+itoa(n);
kvs.insert(std::make_pair(field, val));
s = client->hset(key, field, val);
}
s = client->hgetall(key, &list);
for(int n = 0; n < keysNum; n += 2)
{
EXPECT_EQ(kvs[list[n]], list[n+1]);
}
s = client->multi_del(key);
}
TEST_F(HashTest, Test_hash_hsize) {
#define OKHsize(num) s = client->hsize(key, &ret);\
ASSERT_EQ(ret, num)<<"fail to hsize key!"<<key<<endl;\
ASSERT_TRUE(s.ok())<<"hsize key not ok!"<<endl;
// Some special keys
for(vector<string>::iterator it = Keys.begin(); it != Keys.end(); it++)
{
key = *it;
field = GetRandomField_();
val = GetRandomVal_();
s = client->multi_del(key);
OKHsize(0)
s = client->hset(key, field, val);
OKHsize(1)
s = client->multi_hdel(key, field);
}
key = GetRandomKey_();
field = GetRandomField_();
val = GetRandomVal_();
s = client->multi_del(key);
for(int n = 0; n < 10; n++)
{
field = field+itoa(n);
val = val+itoa(n);
client->hset(key, field, val);
OKHsize(n+1)
}
s = client->multi_del(key);
}
//use del instead of hclear,and hclear cannot clear 100 elements hash key now.
/*
TEST_F(HashTest, Test_hash_hclear) {
#define OKHclear(num) s = client->hclear(key, &ret);\
ASSERT_EQ(ret , num)<<"fail to hclear key!"<<key<<endl;\
s = client->hsize(key, &ret);\
ASSERT_EQ(ret, 0)<<"key is not null!"<<key<<endl;
// Some special keys
for(vector<string>::iterator it = Keys.begin(); it != Keys.end(); it++)
{
key = *it;
field = GetRandomField_();
val = GetRandomVal_();
s = client->multi_del(key);
OKHclear(0)
s = client->hset(key, field, val);
OKHclear(1)
}
key = GetRandomKey_();
field = GetRandomField_();
val = GetRandomVal_();
s = client->multi_del(key);
for(int n = 0; n < 100; n++)
{
field = field+itoa(n);
val = val+itoa(n);
client->hset(key, field, val);
}
OKHclear(100)
} */
TEST_F(HashTest, Test_hash_hkeys) {
key = GetRandomKey_();
s = client->hkeys(key, "", "", 5, &list);
ASSERT_TRUE(s.ok() && list.size() == 0);
list.clear();
client->hset(key, "000000001","");
client->hset(key, "000000002","");
client->hset(key, "000000003","");
//TODO HKEYS command changed
s = client->hkeys(key, "000000000", "000000002", 5, &list);
ASSERT_TRUE(s.ok() && list.size() == 3);
ASSERT_EQ("000000001", list[0]);
ASSERT_EQ("000000002", list[1]);
list.clear();
s = client->hkeys(key, "000000000", "000000003", 5, &list);
ASSERT_TRUE(s.ok() && list.size() == 3);
ASSERT_EQ("000000003", list[2]);
list.clear();
s = client->hkeys(key, "000000000", "000000003", 2, &list);
ASSERT_TRUE(s.ok() && list.size() == 3);
s = client->multi_del(key);
}
TEST_F(HashTest, DISABLED_Test_hash_hscan) {
key = GetRandomKey_();
s = client->hscan(key, "", "", 2, &list);
ASSERT_TRUE(s.ok() && list.size() <= 4);
list.clear();
client->multi_del("key");
client->hset("key", "00000000f1","v1");
client->hset("key", "00000000f2","v2");
s = client->hscan("key", "00000000f0", "00000000f2", 2, &list);
ASSERT_TRUE(s.ok() && list.size() == 4);
ASSERT_EQ("00000000f1", list[0]);
ASSERT_EQ("v1", list[1]);
ASSERT_EQ("00000000f2", list[2]);
ASSERT_EQ("v2", list[3]);
list.clear();
s = client->hscan("key", "00000000f2", "00000000f0", 2, &list);
ASSERT_EQ(0, list.size());
s = client->multi_del("key");
s = client->hscan("key", "00000000f0", "00000000f2", 2, &list);
ASSERT_EQ(0, list.size());
}
//remove hrscan
/* TEST_F(HashTest, Test_hash_hrscan) {
key = GetRandomKey_();
s = client->hrscan(key, "", "", 2, &list);
ASSERT_TRUE(s.ok() && list.size() <= 4);
list.clear();
client->multi_del("key");
client->hset("key", "00000000f1","v1");
client->hset("key", "00000000f2","v2");
s = client->hrscan("key", "00000000f3", "00000000f1", 2, &list);
ASSERT_TRUE(s.ok() && list.size() == 4);
ASSERT_EQ("00000000f2", list[0]);
ASSERT_EQ("v2", list[1]);
ASSERT_EQ("00000000f1", list[2]);
ASSERT_EQ("v1", list[3]);
list.clear();
s = client->hrscan("key", "00000000f1", "00000000f3", 2, &list);
ASSERT_EQ(0, list.size());
s = client->multi_del("key");
s = client->hrscan("key", "00000000f3", "00000000f1", 2, &list);
ASSERT_EQ(0, list.size());
} */
TEST_F(HashTest, Test_hash_hmset_hmget_hdel) {
//Redis hmset/hmget/hdel
string key, field1, field2, field3, val1, val2, val3;
key = GetRandomKey_();
field1 = GetRandomField_();
field2 = field1+'2';
field3 = field1+'3';
val1 = GetRandomVal_();
val2 = val1+'2';
val3 = val1+'3';
kvs.clear();
keys.clear();
list.clear();
kvs.insert(std::make_pair(field1, val1));
kvs.insert(std::make_pair(field2, val2));
keys.push_back(field1);
keys.push_back(field2);
keys.push_back(field3);
//all keys not exist
s = client->multi_hdel(key, keys, &ret);
ASSERT_TRUE(s.ok());
ASSERT_EQ(0, ret);
s = client->multi_hget(key, keys, &list);
ASSERT_EQ(0, list.size());
s = client->multi_hset(key, kvs);
ASSERT_TRUE(s.ok());
s = client->multi_hget(key, keys, &list);
ASSERT_EQ(4, list.size());
ASSERT_EQ(field1, list[0]);
ASSERT_EQ(val1, list[1]);
ASSERT_EQ(field2, list[2]);
ASSERT_EQ(val2, list[3]);
kvs.insert(std::make_pair(field3, val3));
//one key not exist, two keys exist
s = client->multi_hset(key, kvs);
ASSERT_TRUE(s.ok());
list.clear();
s = client->multi_hget(key, keys, &list);
ASSERT_EQ(6, list.size());
kvs.clear();
val1 = val1+'1';
val2 = val2+'2';
val3 = val3+'3';
kvs.insert(std::make_pair(field1, val1));
kvs.insert(std::make_pair(field2, val2));
kvs.insert(std::make_pair(field3, val3));
//all keys exist, update their vals
s = client->multi_hset(key, kvs);
ASSERT_TRUE(s.ok());
list.clear();
s = client->multi_hget(key, keys, &list);
ASSERT_EQ(6, list.size());
ASSERT_EQ(field1, list[0]);
ASSERT_EQ(val1, list[1]);
ASSERT_EQ(field2, list[2]);
ASSERT_EQ(val2, list[3]);
ASSERT_EQ(field3, list[4]);
ASSERT_EQ(val3, list[5]);
s = client->multi_hdel(key, keys, &ret);
ASSERT_TRUE(s.ok());
ASSERT_EQ(3, ret);
list.clear();
s = client->multi_hget(key, keys, &list);
ASSERT_EQ(0, list.size());
kvs.clear();
list.clear();
keys.clear();
int fieldNum = 10;
for(int n = 0; n < fieldNum; n++)
{
kvs.insert(std::make_pair(field1 + itoa(n), val1 + itoa(n)));
keys.push_back(field1 + itoa(n));
}
s = client->multi_hset(key, kvs);
ASSERT_TRUE(s.ok());
s = client->multi_hget(key, keys, &list);
ASSERT_EQ(fieldNum*2, list.size());
for(int n = 0; n < fieldNum; n++)
{
ASSERT_EQ(field1 + itoa(n), list[n*2]);
ASSERT_EQ(val1 + itoa(n), list[n*2+1]);
}
s = client->multi_hdel(key, keys, &ret);
ASSERT_TRUE(s.ok());
ASSERT_EQ(fieldNum, ret);
list.clear();
s = client->multi_hget(key, keys, &list);
ASSERT_EQ(0, list.size());
client->sadd(key, "val");
s = client->multi_hdel(key, keys, &ret);
ASSERT_TRUE(s.error());
s = client->multi_hget(key, keys, &list);
ASSERT_TRUE(s.error());
s = client->multi_hset(key, kvs);
ASSERT_TRUE(s.error());
client->multi_del(key);
}
TEST_F(HashTest, Test_hash_samefields_hmset_hmget_hdel) {
//simulate process same fields at one time.
key = "hkey";
field = "hfield_";
val = "hval_";
keysNum = 1;
kvs2.clear();
keys.clear();
for(int m = 0;m < 2;m++){
for(int n = 0;n < keysNum;n++) {
keys.push_back(field+itoa(n));
kvs2.push_back(field+itoa(n));
kvs2.push_back(val+itoa(n));
}
}
//all keys not exist
client->multi_del(key);
s = client->multi_hdel(key, keys, &ret);
ASSERT_TRUE(s.ok());
ASSERT_EQ(0, ret);
list.clear();
s = client->multi_hget(key, keys, &list);
ASSERT_EQ(0, list.size());
//same field same value hmset
s = client->multi_hset(key, kvs2);
ASSERT_TRUE(s.ok());
s = client->multi_hget(key, keys, &list);
ASSERT_EQ(keys.size()*2, list.size());
for(int n = 0;n < 2*keysNum;n++) {
ASSERT_EQ(field+itoa(n%keysNum), list[2*n]);
ASSERT_EQ(val+itoa(n%keysNum), list[2*n+1]);
}
//same key diff value mset
for(int n = 0;n < keysNum;n++) {
keys.push_back(field+itoa(n));
kvs2.push_back(field+itoa(n));
kvs2.push_back(val+itoa(n*2));
}
s = client->multi_hset(key, kvs2);
ASSERT_TRUE(s.ok());
list.clear();
s = client->multi_hget(key, keys, &list);
ASSERT_EQ(keys.size()*2, list.size());
for(int n = 0;n < 3*keysNum;n++) {
ASSERT_EQ(field+itoa(n%keysNum), list[2*n]);
ASSERT_EQ(val+itoa(n%keysNum*2), list[2*n+1]);
}
client->multi_hdel(key, keys, &ret);
ASSERT_EQ(keysNum, ret);
}
| 28.308901
| 87
| 0.573208
|
TimothyZhang023
|
f4acf5c25709d692fda58cf417492ad69f05621d
| 3,227
|
cpp
|
C++
|
src/HandGunC.cpp
|
pablojor/mood
|
779af33ae3fc596c1749901917f67c0d8a14d63f
|
[
"MIT"
] | null | null | null |
src/HandGunC.cpp
|
pablojor/mood
|
779af33ae3fc596c1749901917f67c0d8a14d63f
|
[
"MIT"
] | 2
|
2020-04-12T14:01:00.000Z
|
2020-05-20T12:53:11.000Z
|
src/HandGunC.cpp
|
NoVariableGlobal/mood
|
e3446857a1d309dfac71beaf6407bb905f02a912
|
[
"MIT"
] | 1
|
2020-10-07T15:09:45.000Z
|
2020-10-07T15:09:45.000Z
|
#include "HandGunC.h"
#include "BulletC.h"
#include "ComponentsManager.h"
#include "Entity.h"
#include "FactoriesFactory.h"
#include "Ogre.h"
#include "OgreQuaternion.h"
#include "RigidbodyPC.h"
#include "Scene.h"
#include "TransformComponent.h"
#include <json.h>
void HandGunC::onShoot(TransformComponent* transform, RigidbodyPC* rigidBody) {
Ogre::Quaternion quat = getOrientation();
transform->setPosition(myTransform_->getPosition() +
(quat * Ogre::Vector3::UNIT_Y) * 25 +
(quat * Ogre::Vector3::UNIT_Z) * 10);
transform->setOrientation(myTransform_->getOrientation());
rigidBody->setLinearVelocity((quat * Ogre::Vector3::UNIT_Z) * bulletSpeed_);
GunC::onShoot(transform, rigidBody);
}
// FACTORY INFRASTRUCTURE
HandGunCFactory::HandGunCFactory() = default;
Component* HandGunCFactory::create(Entity* _father, Json::Value& _data,
Scene* _scene) {
HandGunC* hg = new HandGunC();
_scene->getComponentsManager()->addDC(hg);
hg->setFather(_father);
hg->setScene(_scene);
hg->setSoundManager();
if (!_data["bulletTag"].isString())
throw std::exception("HandGunC: bulletTag is not a string");
hg->setBulletTag(_data["bulletTag"].asString());
if (!_data["bulletchamberMax"].isInt())
throw std::exception("HandGunC: bulletchamberMax is not an int");
hg->setbulletchamber(_data["bulletchamberMax"].asInt());
if (!_data["munition"].isInt())
throw std::exception("HandGunC: munition is not an int");
hg->setmunition(_data["munition"].asInt());
if (!_data["bulletDamage"].isDouble())
throw std::exception("HandGunC: bulletDamage is not a double");
hg->setbulletdamage(_data["bulletDamage"].asDouble());
if (!_data["bulletSpeed"].isDouble())
throw std::exception("HandGunC: bulletSpeed is not a double");
hg->setbulletspeed(_data["bulletSpeed"].asDouble());
if (!_data["cadence"].isDouble())
throw std::exception("HandGunC: cadence is not an int");
hg->setcadence(_data["cadence"].asFloat());
if (!_data["automatic"].isBool())
throw std::exception("HandGunC: semiautomatic is not an bool");
hg->setautomatic(_data["automatic"].asBool());
if (!_data["instakill"].isBool())
throw std::exception("HandGunC: instakill is not an bool");
hg->setInstakill(_data["instakill"].asBool());
if (_data["infiniteAmmo"].isBool())
hg->setInfiniteAmmo(_data["infiniteAmmo"].asBool());
if (!_data["bulletType"].isString())
throw std::exception("HandGunC: bulletType is not a string");
hg->setBulletType(_data["bulletType"].asString());
if (!_data["shotSound"].isString())
throw std::exception("HandGunC: shotSound is not a string");
hg->setShotSound(_data["shotSound"].asString());
if (!_data["bulletComponent"].isString())
throw std::exception("HandGunC: bulletComponent is not a string");
hg->setBulletComponentName(_data["bulletComponent"].asString());
hg->setTransform(reinterpret_cast<TransformComponent*>(
_father->getComponent("TransformComponent")));
return hg;
};
DEFINE_FACTORY(HandGunC);
| 35.076087
| 80
| 0.662845
|
pablojor
|
f4ad65e4c0e2b702c324528a34702eec26bceafb
| 6,137
|
cpp
|
C++
|
opt_kappa.cpp
|
dokyum/tiLDA
|
7dc3a2c8023bfc92b777fa9a2f50ace65209fccc
|
[
"Apache-2.0"
] | 2
|
2016-01-21T02:40:42.000Z
|
2018-12-22T18:07:02.000Z
|
opt_kappa.cpp
|
vineelpratap/tiLDA
|
7dc3a2c8023bfc92b777fa9a2f50ace65209fccc
|
[
"Apache-2.0"
] | null | null | null |
opt_kappa.cpp
|
vineelpratap/tiLDA
|
7dc3a2c8023bfc92b777fa9a2f50ace65209fccc
|
[
"Apache-2.0"
] | 2
|
2015-02-13T20:53:34.000Z
|
2021-01-30T17:11:51.000Z
|
#include "opt_kappa.h"
#define KAPPA_NEWTON_THRESH 1e-6
#define KAPPA_MAX_ITER 5000
#define LIKELIHOOD_DECREASE_ALLOWANCE 1e-5
extern double oneoverk;
double opt_kappa(double* kappa, int ntopics, int nchildren,
double* dirichlet_prior,
double alpha, double tau,
double* digamma_sum_over_children,
int node_index)
{
double* g = NULL;
double* h = NULL;
double* delta_kappa = NULL;
double* new_kappa = NULL;
g = zero_init_double_array(ntopics);
h = zero_init_double_array(ntopics);
delta_kappa = zero_init_double_array(ntopics);
new_kappa = zero_init_double_array(ntopics);
for (int i = 0; i < ntopics; ++i) {
kappa[i] = oneoverk;
}
#ifdef _DEBUG
// printf("kappa opt start %d : nchildren %d \t alpha %5.15f \t tau %5.15f \n",
// node_index, nchildren, alpha, tau);
// for (int i = 0; i < ntopics; ++i) {
// printf("kappa opt start %d %d : dirichlet_prior %5.15f \t kappa %5.15f \n",
// node_index, i, dirichlet_prior[i], kappa[i]);
// }
#endif
double invhsum = 0;
double goverhsum = 0;
double coefficient = 0;
double old_likelihood = 0;
// double likelihood = 0;
double sqr_newton_decrement = 0;
double step_size;
double indep_new_likelihood = 0;
double dep_new_likelihood = 0;
double new_likelihood;
double expected_increase;
#ifdef _DEBUG
double initial_likelihood;
#endif
int iter = 0;
for (int i = 0; i < ntopics; ++i) {
double const taukappai = tau * kappa[i];
double const alphakappai = alpha * kappa[i];
double const common = dirichlet_prior[i] + nchildren * (1 - alphakappai) - taukappai;
double const digammataukappai = digamma(taukappai);
double const logkappai = log(kappa[i]);
dep_new_likelihood += digammataukappai * common;
indep_new_likelihood -= nchildren * (lgamma(alphakappai) + (1 - alphakappai) * logkappai);
indep_new_likelihood += alphakappai * digamma_sum_over_children[i];
dep_new_likelihood += lgamma(taukappai);
}
new_likelihood = indep_new_likelihood + dep_new_likelihood;
#ifdef _DEBUG
initial_likelihood = new_likelihood;
#endif
do {
iter++;
invhsum = 0;
goverhsum = 0;
coefficient = 0;
for (int i = 0; i < ntopics; ++i) {
double const taukappai = tau * kappa[i];
double const alphakappai = alpha * kappa[i];
double const common = dirichlet_prior[i] + nchildren * (1 - alphakappai) - taukappai;
double const digammataukappai = digamma(taukappai);
double const trigammataukappai = trigamma(taukappai);
double const logkappai = log(kappa[i]);
g[i] = tau * trigammataukappai * common
- nchildren * alpha * (digamma(alphakappai) - logkappai + digammataukappai - 1)
- nchildren / kappa[i]
+ alpha * digamma_sum_over_children[i];
h[i] = tau * tau * tetragamma(taukappai) * common
- tau * trigammataukappai * (tau + 2 * alpha * nchildren)
- alpha * alpha * trigamma(alphakappai) * nchildren
+ alpha * nchildren / kappa[i]
+ nchildren / (kappa[i] * kappa[i]);
invhsum += 1 / h[i];
goverhsum += g[i] / h[i];
}
old_likelihood = new_likelihood;
coefficient = goverhsum / invhsum;
sqr_newton_decrement = 0;
expected_increase = 0;
step_size = 1;
for (int i = 0; i < ntopics; ++i) {
delta_kappa[i] = (coefficient - g[i]) / h[i];
sqr_newton_decrement -= h[i] * delta_kappa[i] * delta_kappa[i]; // this one is maximization
expected_increase += g[i] * delta_kappa[i];
//sqr_newton_decrement += g[i] * delta_kappa[i];
if (delta_kappa[i] < 0) {
double limit = (kappa[i] - 1e-10) / -(delta_kappa[i]);
if (step_size > limit) {
step_size = limit;
}
}
}
#ifdef _DEBUG
printf("kappa maximization %d : L %5.15f \t dL %5.15f \t indL %5.15f \t newton %5.15f \t %5.15f\n",
node_index, old_likelihood, dep_new_likelihood, indep_new_likelihood, sqr_newton_decrement / 2, step_size);
// for (int i = 0; i < ntopics; ++i) {
// printf("kappa maximization %d %d: delta_kappa %5.15f \n",
// node_index, i, delta_kappa[i]);
// }
#endif
if (sqr_newton_decrement < KAPPA_NEWTON_THRESH * 2 || step_size < 1e-8 ) {
break;
}
// backtracking line search
while(1) {
// double sum_new_kappa = 0.0;
indep_new_likelihood = 0.0;
dep_new_likelihood = 0.0;
for (int i = 0; i < ntopics; ++i) {
new_kappa[i] = kappa[i] + step_size * delta_kappa[i];
double const taukappai = tau * new_kappa[i];
double const alphakappai = alpha * new_kappa[i];
double const common = dirichlet_prior[i] + nchildren * (1 - alphakappai) - taukappai;
double const logkappai = log(new_kappa[i]);
dep_new_likelihood += digamma(taukappai) * common;
indep_new_likelihood -= nchildren * (lgamma(alphakappai) + (1 - alphakappai) * logkappai);
indep_new_likelihood += alphakappai * digamma_sum_over_children[i];
dep_new_likelihood += lgamma(taukappai);
}
new_likelihood = indep_new_likelihood + dep_new_likelihood;
#ifdef _DEBUG
printf("line search %d : nL: %5.15f \t bound: %5.15f \t step_size: %5.15f \n",
node_index, new_likelihood, old_likelihood + 0.4 * step_size * expected_increase, step_size);
#endif
if (new_likelihood > old_likelihood + 0.4 * step_size * expected_increase) {
// if (new_likelihood > old_likelihood + 0.4 * step_size * sqr_newton_decrement) {
break;
}
step_size *= 0.9;
if (step_size < 1e-8) break;
}
if (step_size < 1e-8) break;
for (int i = 0; i < ntopics; ++i) {
kappa[i] = new_kappa[i];
assert(!std::isnan(kappa[i]));
assert(kappa[i] > 0);
}
} while (iter < KAPPA_MAX_ITER);
if (iter >= KAPPA_MAX_ITER) {
printf("KAPPA_MAX_ITER reached\n");
exit(-1);
}
#ifdef _DEBUG
printf("%d TL %5.15f \t IL %5.15f \n", node_index, new_likelihood, initial_likelihood);
assert(new_likelihood >= initial_likelihood ||
( ((initial_likelihood - new_likelihood) / fabs(initial_likelihood) < LIKELIHOOD_DECREASE_ALLOWANCE)
&& (iter >= 3) )
);
#endif
free(new_kappa);
free(delta_kappa);
free(g);
free(h);
return new_likelihood;
}
| 31.311224
| 112
| 0.653577
|
dokyum
|