blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 115
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
644a9aadfdaa900e9328d51c1f3c14c55eef1f33 | c1d39d3b0bcafbb48ba2514afbbbd6d94cb7ffe1 | /source/deps/illa/webp_imagecomposer.cpp | 1fbc0969a7b7e9e0b2d6ea8846c2781603c65018 | [
"IJG",
"MIT"
] | permissive | P4ll/Pictus | c6bb6fbc8014c7de5116380f48f8c1c4016a2c43 | 0e58285b89292d0b221ab4d09911ef439711cc59 | refs/heads/master | 2023-03-16T06:42:12.293939 | 2018-09-13T18:19:30 | 2018-09-13T18:19:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,060 | cpp | #include "webp_imagecomposer.h"
#include "surfacemgr.h"
namespace Img {
void WebpImageComposer::SetCanvasSize(Geom::SizeInt newSize)
{
std::lock_guard<std::mutex> l(m_mutFrames);
m_dims = newSize;
}
void WebpImageComposer::SetBackgroundColor(Img::Color backgroundColor)
{
std::lock_guard<std::mutex> l(m_mutFrames);
m_backgroundColor = backgroundColor;
}
void WebpImageComposer::SetFrameCount(size_t numFrames)
{
std::lock_guard<std::mutex> l(m_mutFrames);
m_numFrames = numFrames;
}
void WebpImageComposer::SendFrame(WebpFrame frame)
{
std::lock_guard<std::mutex> l(m_mutFrames);
m_frames.push_back(frame);
}
WebpImageComposer::WebpImageComposer():
m_currFrame(0),
m_numFrames(0)
{
}
WebpImageComposer::~WebpImageComposer()
{}
Surface::Ptr WebpImageComposer::ComposeCurrentSurface() {
std::lock_guard<std::mutex> l(m_mutFrames);
if (m_frames.empty())
{
return nullptr;
}
if (m_currentSurface == nullptr)
{
m_currentSurface = CreateNewSurface(m_dims, Img::Format::ARGB8888);
}
if (m_frames[m_currFrame].DisposeMethod == WebpDispose::BackgroundColor)
{
m_currentSurface->ClearSurface(m_backgroundColor);
}
if (m_frames[m_currFrame].BlendMethod == WebpBlendMethod::Alpha && m_currFrame > 0)
{
m_currentSurface->BlitSurfaceAlpha(m_frames[m_currFrame].Surface, m_frames[m_currFrame].Offset);
}
else
{
m_currentSurface->CopySurface(m_frames[m_currFrame].Surface, m_frames[m_currFrame].Offset);
}
return m_currentSurface;
}
void WebpImageComposer::OnAdvance() {
std::lock_guard<std::mutex> l(m_mutFrames);
if (m_currFrame + 1 < m_frames.size() && m_currentSurface != nullptr) {
m_currFrame++;
}
else if (m_currFrame + 1 == m_numFrames) {
m_currFrame = 0;
}
}
int WebpImageComposer::OnDelay() {
std::lock_guard<std::mutex> l(m_mutFrames);
if (m_currFrame >= m_frames.size()) {
return 10;
}
return m_frames[m_currFrame].Delay;
}
void WebpImageComposer::OnRestart() {
std::lock_guard<std::mutex> l(m_mutFrames);
m_currFrame = 0;
}
}
| [
"[email protected]"
] | |
57d0b081f9845d474554012875fcf47c73a36b88 | c57819bebe1a3e1d305ae0cb869cdcc48c7181d1 | /src/qt/src/3rdparty/webkit/Source/WebCore/bridge/jni/JavaMethodJobject.cpp | 2f2802ca0c244f09954338c20610d51125216e65 | [
"BSD-2-Clause",
"LGPL-2.1-only",
"LGPL-2.0-only",
"Qt-LGPL-exception-1.1",
"LicenseRef-scancode-generic-exception",
"GPL-3.0-only",
"GPL-1.0-or-later",
"GFDL-1.3-only",
"BSD-3-Clause"
] | permissive | blowery/phantomjs | 255829570e90a28d1cd597192e20314578ef0276 | f929d2b04a29ff6c3c5b47cd08a8f741b1335c72 | refs/heads/master | 2023-04-08T01:22:35.426692 | 2012-10-11T17:43:24 | 2012-10-11T17:43:24 | 6,177,895 | 1 | 0 | BSD-3-Clause | 2023-04-03T23:09:40 | 2012-10-11T17:39:25 | C++ | UTF-8 | C++ | false | false | 5,893 | cpp | /*
* Copyright (C) 2003, 2004, 2005, 2007, 2009 Apple Inc. All rights reserved.
* Copyright 2010, The Android Open Source Project
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h"
#include "JavaMethodJobject.h"
#if ENABLE(JAVA_BRIDGE)
#include "JavaString.h"
#if USE(JSC)
#include <runtime/JSObject.h>
#include <runtime/ScopeChain.h>
#endif
#include <wtf/text/StringBuilder.h>
using namespace JSC;
using namespace JSC::Bindings;
JavaMethodJobject::JavaMethodJobject(JNIEnv* env, jobject aMethod)
{
// Get return type name
jstring returnTypeName = 0;
if (jobject returnType = callJNIMethod<jobject>(aMethod, "getReturnType", "()Ljava/lang/Class;")) {
returnTypeName = static_cast<jstring>(callJNIMethod<jobject>(returnType, "getName", "()Ljava/lang/String;"));
if (!returnTypeName)
returnTypeName = env->NewStringUTF("<Unknown>");
env->DeleteLocalRef(returnType);
}
m_returnTypeClassName = JavaString(env, returnTypeName);
m_returnType = javaTypeFromClassName(m_returnTypeClassName.utf8());
env->DeleteLocalRef(returnTypeName);
// Get method name
jstring methodName = static_cast<jstring>(callJNIMethod<jobject>(aMethod, "getName", "()Ljava/lang/String;"));
if (!methodName)
methodName = env->NewStringUTF("<Unknown>");
m_name = JavaString(env, methodName);
env->DeleteLocalRef(methodName);
// Get parameters
if (jarray jparameters = static_cast<jarray>(callJNIMethod<jobject>(aMethod, "getParameterTypes", "()[Ljava/lang/Class;"))) {
unsigned int numParams = env->GetArrayLength(jparameters);
for (unsigned int i = 0; i < numParams; i++) {
jobject aParameter = env->GetObjectArrayElement(static_cast<jobjectArray>(jparameters), i);
jstring parameterName = static_cast<jstring>(callJNIMethod<jobject>(aParameter, "getName", "()Ljava/lang/String;"));
if (!parameterName)
parameterName = env->NewStringUTF("<Unknown>");
m_parameters.append(JavaString(env, parameterName).impl());
env->DeleteLocalRef(aParameter);
env->DeleteLocalRef(parameterName);
}
env->DeleteLocalRef(jparameters);
}
// Created lazily.
m_signature = 0;
jclass modifierClass = env->FindClass("java/lang/reflect/Modifier");
int modifiers = callJNIMethod<jint>(aMethod, "getModifiers", "()I");
m_isStatic = static_cast<bool>(callJNIStaticMethod<jboolean>(modifierClass, "isStatic", "(I)Z", modifiers));
env->DeleteLocalRef(modifierClass);
}
JavaMethodJobject::~JavaMethodJobject()
{
if (m_signature)
fastFree(m_signature);
}
// JNI method signatures use '/' between components of a class name, but
// we get '.' between components from the reflection API.
static void appendClassName(StringBuilder& builder, const char* className)
{
#if USE(JSC)
ASSERT(JSLock::lockCount() > 0);
#endif
char* c = fastStrDup(className);
char* result = c;
while (*c) {
if (*c == '.')
*c = '/';
c++;
}
builder.append(result);
fastFree(result);
}
const char* JavaMethodJobject::signature() const
{
if (!m_signature) {
#if USE(JSC)
JSLock lock(SilenceAssertionsOnly);
#endif
StringBuilder signatureBuilder;
signatureBuilder.append('(');
for (unsigned int i = 0; i < m_parameters.size(); i++) {
CString javaClassName = parameterAt(i).utf8();
JavaType type = javaTypeFromClassName(javaClassName.data());
if (type == JavaTypeArray)
appendClassName(signatureBuilder, javaClassName.data());
else {
signatureBuilder.append(signatureFromJavaType(type));
if (type == JavaTypeObject) {
appendClassName(signatureBuilder, javaClassName.data());
signatureBuilder.append(';');
}
}
}
signatureBuilder.append(')');
const char* returnType = m_returnTypeClassName.utf8();
if (m_returnType == JavaTypeArray)
appendClassName(signatureBuilder, returnType);
else {
signatureBuilder.append(signatureFromJavaType(m_returnType));
if (m_returnType == JavaTypeObject) {
appendClassName(signatureBuilder, returnType);
signatureBuilder.append(';');
}
}
String signatureString = signatureBuilder.toString();
m_signature = fastStrDup(signatureString.utf8().data());
}
return m_signature;
}
#endif // ENABLE(JAVA_BRIDGE)
| [
"[email protected]"
] | |
9a8661d74c8781d15c69970f3a18e7de6e558e33 | 0f732387ddd27d25996bf092e1368c3bad1da62e | /Stack/main.cpp | 0697afdfda8ae33e337cea6291b9a7a36b7c401a | [] | no_license | abdelrahmaneltohamy/data-structure | f462a0d815c8af34af4c6f0b7097aa5c9e9cc084 | e0da5fcfd078f0e39560e655aab5ef3cb781d45d | refs/heads/master | 2022-05-28T13:10:57.053175 | 2020-04-27T12:15:50 | 2020-04-27T12:15:50 | 259,306,010 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,224 | cpp | #include <iostream>
using namespace std;
template <class StackElemType>
class Stack {
public:
Stack(int Size)
{
if(Size<1)
throw"cannot construct an empty stack";
stackArray = new StackElemType[Size];
arraySize = Size;
topIndex = -1; // Point at no where in the array
}
Stack(StackElemType value, int intial_size)
{
if(intial_size<1)
throw"cannot construct an empty stack";
stackArray = new StackElemType[intial_size];
arraySize = intial_size;
topIndex = -1;
for(int i=0;i<arraySize;i++)
{
push(value);
}
}
void push(StackElemType value)
{
if (topIndex >= arraySize - 1)
{
throw"reached max of array";
}
else
{
topIndex++;
stackArray[topIndex] = value;
}
}
StackElemType& pop()
{
if (topIndex < 0)
throw"stack is empty";
else
{
return stackArray[topIndex--];
}
}
StackElemType& top()
{
if (topIndex < 0)
throw"stack is empty";
else
{
return stackArray[topIndex];
}
}
bool isEmpty()
{
if(topIndex==-1)
return true;
else
return false;
}
bool isFull()
{
if(topIndex==arraySize-1)
return true;
else
return false;
}
~Stack()
{
delete[] stackArray;
}
int Size()
{
return topIndex+1;
}
private:
StackElemType* stackArray;
int arraySize;
int topIndex;
};
int main()
{
Stack<int> mystack(20,30);
int mm=mystack.top();
cout<<mm<<endl<<mystack.Size()<<endl;
while(!mystack.isEmpty())
{
mm=mystack.pop();
cout<<mm<<" ";
}
cout<<endl;
Stack<int> mystack2(10);
mystack2.push(3);
mystack2.push(4);
mystack2.push(5);
try
{
while(!mystack2.isEmpty())
{
mm=mystack2.pop();
cout<<endl<<mm<<" ";
}
}
catch (char const* hh)
{
cout<<endl<<hh;
}
return 0;
}
| [
"[email protected]"
] | |
3db51f7dc82ccb43de5e403556b26ac23bd1fc91 | 18c5b07a6d4f430eefa1fd12376d66050c22df74 | /moc_filelineedit.cpp | e3ced78e57932e47fa0d5bf6caed44552f30a645 | [] | no_license | KingSann/Project_lemon | 921f13fead3b9f810643dd292b2c1eeeae04a483 | 21b7b8353d24cd431524d849c71f1c29bc595918 | refs/heads/master | 2020-03-20T19:55:42.187457 | 2018-07-10T00:59:14 | 2018-07-10T00:59:14 | 137,661,349 | 0 | 0 | null | 2018-06-17T14:32:08 | 2018-06-17T14:32:08 | null | UTF-8 | C++ | false | false | 3,416 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'filelineedit.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.11.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "filelineedit.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'filelineedit.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.11.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_FileLineEdit_t {
QByteArrayData data[3];
char stringdata0[30];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_FileLineEdit_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_FileLineEdit_t qt_meta_stringdata_FileLineEdit = {
{
QT_MOC_LITERAL(0, 0, 12), // "FileLineEdit"
QT_MOC_LITERAL(1, 13, 15), // "refreshFileList"
QT_MOC_LITERAL(2, 29, 0) // ""
},
"FileLineEdit\0refreshFileList\0"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_FileLineEdit[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
1, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 19, 2, 0x0a /* Public */,
// slots: parameters
QMetaType::Void,
0 // eod
};
void FileLineEdit::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
FileLineEdit *_t = static_cast<FileLineEdit *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->refreshFileList(); break;
default: ;
}
}
Q_UNUSED(_a);
}
QT_INIT_METAOBJECT const QMetaObject FileLineEdit::staticMetaObject = {
{ &QLineEdit::staticMetaObject, qt_meta_stringdata_FileLineEdit.data,
qt_meta_data_FileLineEdit, qt_static_metacall, nullptr, nullptr}
};
const QMetaObject *FileLineEdit::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *FileLineEdit::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_FileLineEdit.stringdata0))
return static_cast<void*>(this);
return QLineEdit::qt_metacast(_clname);
}
int FileLineEdit::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QLineEdit::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 1)
qt_static_metacall(this, _c, _id, _a);
_id -= 1;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 1)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 1;
}
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| [
"[email protected]"
] | |
c09abbc2c7a46b9d24896ebfb4546ddc7c96226d | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/cd/7bc6734eb84d8d/main.cpp | 4bc743e7378c7b07aca9eda535c1146d56cf22e5 | [] | no_license | WhiZTiM/coliru | 3a6c4c0bdac566d1aa1c21818118ba70479b0f40 | 2c72c048846c082f943e6c7f9fa8d94aee76979f | refs/heads/master | 2021-01-01T05:10:33.812560 | 2015-08-24T19:09:22 | 2015-08-24T19:09:22 | 56,789,706 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,107 | cpp |
#include <type_traits>
#include <utility>
#include <iomanip>
#include <iostream>
namespace {
template<class U, class T>
static auto
has_member_f_impl(signed)
-> decltype(
std::declval<T&>().f(std::declval<U&>()),
std::true_type{}
)
;
template<class, class>
static std::false_type
has_member_f_impl(...);
template<class U, class T>
static auto
has_non_member_f_impl(signed)
-> decltype(
f(std::declval<U&>(), std::declval<T&>()),
std::true_type{}
)
;
template<class, class>
static std::false_type
has_non_member_f_impl(...);
} // anonymous namespace
template<class U, class T>
struct has_member_f
: public decltype(has_member_f_impl<U, T>(0))
{};
template<class U, class T>
struct has_non_member_f
: public decltype(has_non_member_f_impl<U, T>(0))
{};
// test
struct B {
template<class T>
void f(T&) {}
};
struct D : public B {};
template<class U, class T>
void f(U&, T&) {}
signed main() {
std::cout
<< std::boolalpha
<< has_member_f<int, D>::value << '\n'
<< has_non_member_f<int, D>::value << '\n'
;
return 0;
}
| [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
6c3e29c9a5be97924506f16a3dcc1d228768ebc4 | 1d26a2a5761a36279c293403a839536b6de911b7 | /Crow/src/Platform/PlatformAPI.cpp | dd2f01a27c83360e6fe68be0d5cd915b262f82de | [
"Apache-2.0"
] | permissive | quesswho/Crow | 919f97a1ff6a2d5da1d27c774c7a50672ad9ba01 | c57df8fe6dc323acd2c5e7b14b0b65d34b4a6e94 | refs/heads/master | 2020-07-09T17:23:37.081282 | 2020-05-02T22:22:23 | 2020-05-02T22:22:23 | 204,032,891 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,254 | cpp | #include "PlatformAPI.h"
#include "Crow/Application.h"
namespace Crow {
namespace Platform {
ApplicationAPI PlatformAPI::s_ApplicationAPI;
void PlatformAPI::ApplicationAPIInit(ApplicationAPI appApi)
{
switch(appApi)
{
case ApplicationAPI::GLFW:
s_ApplicationAPI = ApplicationAPI::GLFW;
GLFWInit();
MathInit();
break;
case ApplicationAPI::WINDOWS:
CR_WINDOWSERROR();
s_ApplicationAPI = ApplicationAPI::WINDOWS;
WindowsInit();
MathInit();
break;
}
}
void PlatformAPI::GLFWInit()
{
CreateWindowAPI = &GLFWAPIWindow::CreateGLFWWindow;
}
void PlatformAPI::WindowsInit()
{
CreateWindowAPI = &WindowsAPIWindow::CreateWindowsWindow;
}
void PlatformAPI::MathInit()
{
#ifdef CROW_OGL
Math::MATH_COORDINATE::s_MathCoordinateType = Math::MATH_COORDINATE::MATH_COORDINATE_RIGHTHAND;
#elif defined(CROW_DX11)
Math::MATH_COORDINATE::s_MathCoordinateType = Math::MATH_COORDINATE::MATH_COORDINATE_LEFTHAND;
#endif
}
bool PlatformAPI::CheckWindowsError()
{
if (s_ApplicationAPI != ApplicationAPI::WINDOWS)
{
CR_CORE_WARNING("Cannot use a non Windows application for DirectX! Using OpenGL instead.");
return false;
}
return true;
}
}
} | [
"[email protected]"
] | |
0e4179c98bf628a506bad7106e61ea646b598f32 | d90566c011088f1815e70d58445a52d8479135b5 | /udpserver/udpserver/main.cpp | 0f46857017d53c7f6c07f2a9ee9b961f279f9421 | [] | no_license | lordstone/Trial_TCPIP_server_client | 91b3063adef0e3791ab9ee59f8c75d0ad633556a | 0af420d0b29067472ef10cf99400e22664a4db8f | refs/heads/master | 2021-01-10T07:35:12.561790 | 2016-03-27T04:35:42 | 2016-03-27T04:35:42 | 54,806,887 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,492 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <iostream>
#include <netdb.h>
#define BUFSIZE 2048
#define CUSTOM_SERVER_PORT 9292
#define CUSTOM_CLIENT_PORT 2929
using namespace std;
void error(const char * msg){
perror(msg);
exit(1);
}
int startUdpServer(){
// this is the main func for udp server
// start creating socket obj
int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
if(socket_fd < 0){
error("Cannot create socket");
}
// define sockaddr_in struct
struct sockaddr_in socket_addr;
// set the mem to be all 0
memset((char *)&socket_addr, 0, sizeof(socket_addr));
socket_addr.sin_family = AF_INET;
socket_addr.sin_port = htons(CUSTOM_SERVER_PORT); // 9292 picked at random
socket_addr.sin_addr.s_addr = htonl(INADDR_ANY);
cout << "Now we are to bind ... " << endl;
//now we try to bind it
if(bind(socket_fd, (struct sockaddr *) &socket_addr, sizeof(socket_addr)) < 0){
error("Cannot bind");
}
//time to process incoming msg
// never exits, keep recving
int recvlen; /* # bytes received */
unsigned char buf[BUFSIZE]; /* receive buffer */
struct sockaddr_in remaddr; /* remote address */
socklen_t addrlen = sizeof(remaddr); /* length of addresses */
for (;;) {
recvlen = recvfrom(socket_fd, buf, BUFSIZE, 0, (struct sockaddr *)&remaddr, &addrlen);
if(recvlen < 0){
error("recvfrom error. Exiting...");
}
printf("received %d bytes\n", recvlen);
if (recvlen > 0) {
buf[recvlen] = 0;
printf("received message: \"%s\"\n", buf);
}
}
/* never exits */
return 0;
}
int startUdpClient(){
// define necessary vars to get host
struct hostent * myhost;
char * host = "127.0.0.1";
int n;
cout << "Getting host..." << endl;
// get the host
myhost = gethostbyname(host);
if(!myhost){
error("Cannot obtain the address;");
}
// define sockaddr
struct sockaddr_in servaddr;
// reset the whole servaddr obj
memset((char*)&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(0);
// now copy the addr to it
memcpy((void*)&servaddr.sin_addr, myhost->h_addr_list[0], myhost->h_length);
cout << "Now type in the message:";
char msg[256];
fgets(msg,255,stdin);
if(msg[0] == 'e'){
cout << "Exiting on demand..." << endl;
exit(0);
}
cout << "Now try to send" << endl;
//defined socket fd
int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
//now we try to bind it
if(bind(socket_fd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0){
error("Cannot bind");
}
// set up serv port no
servaddr.sin_port = htons(CUSTOM_SERVER_PORT);
cout << "Just before sendto" << endl;
// now send the message through UDP
if(sendto(socket_fd, msg, strlen(msg), 0, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0){
error("Send failed");
}
cout << "Seems sendto succeeded... Exiting" << endl;
return 0;
}
int main(int argc, char * argv[])
{
cout << "Parsing args module" << endl;
if(argc != 2){
error("Wrong arg count, Exiting");
}
// cout << "argv1:" << argv[1] << endl;
if(argv[1][0] == 's'){
cout << "Entering Server Mode..." << endl;
int statusCode = startUdpServer();
}else if(argv[1][0] == 'c'){
cout << "Entering Client Mode..." << endl;
int statusCode = startUdpClient();
}else{
error("Error in argument. Exiting");
}
return 0;
}
| [
"[email protected]"
] | |
e3f73241cfde8e26693c8e85ac7617aa900280b9 | 9dc7f37e290c03d27172ef211fac548d08ec83c6 | /Testing/testReceiveVideo.cxx | ce326cad6022eaba256b11f445d8eeefe6000c3a | [
"Apache-2.0"
] | permissive | Sunderlandkyl/OpenIGTLinkIO | cd8414ae08add54372e0c6e0facba5984ca3ec48 | 4b792865f07e0dbc812c328176d74c94a5e5983c | refs/heads/master | 2022-11-01T01:09:22.149398 | 2018-01-12T04:03:04 | 2018-01-24T03:08:33 | 120,339,747 | 0 | 0 | null | 2018-02-05T17:45:29 | 2018-02-05T17:45:28 | null | UTF-8 | C++ | false | false | 3,601 | cxx | #include <string>
#include "igtlioLogic.h"
#include "igtlioConnector.h"
#include "vtkTimerLog.h"
#include "vtkImageData.h"
#include "igtlioVideoConverter.h"
#include "vtkMatrix4x4.h"
#include <vtksys/SystemTools.hxx>
#include "igtlioVideoConverter.h"
#include <vtkImageDifference.h>
#include "IGTLIOFixture.h"
#include "igtlioVideoDevice.h"
#include "igtlioSession.h"
#include "igtlMessageDebugFunction.h"
bool compare(vtkSmartPointer<vtkImageData> a, vtkSmartPointer<vtkImageData> b)
{
#if defined(OpenIGTLink_ENABLE_VIDEOSTREAMING)
GenericEncoder * encoder = new VP9Encoder();
GenericDecoder * decoder = new VP9Decoder();
igtlUint8* yuv_a = new igtlUint8[a->GetDimensions()[0]*a->GetDimensions()[1]*3/2];
igtlUint8* rgb_a = new igtlUint8[a->GetDimensions()[0]*a->GetDimensions()[1]*3];
encoder->ConvertRGBToYUV((igtlUint8*)a->GetScalarPointer(), yuv_a, a->GetDimensions()[0], a->GetDimensions()[1]);
decoder->ConvertYUVToRGB(yuv_a, rgb_a, b->GetDimensions()[0], b->GetDimensions()[1]);
int iReturn = memcmp(rgb_a, a->GetScalarPointer(),a->GetDimensions()[0]*a->GetDimensions()[1]*3);// The conversion is not valid. Image is not the same after conversion.
//TestDebugCharArrayCmp(b->GetScalarPointer(),rgb_a,a->GetDimensions()[0]*a->GetDimensions()[1]*3);
int sumError = 0;
for (int i = 0 ; i< a->GetDimensions()[0]*a->GetDimensions()[1];i++)
{
sumError += abs(*((igtlUint8*)rgb_a+i)-*((igtlUint8*)b->GetScalarPointer()+i));
}
delete encoder;
delete decoder;
if (sumError<a->GetDimensions()[0]*a->GetDimensions()[1]) // To do, check the lossless encoding problem. most likely from the RGB and YUV conversion
return true;
#endif
return false;
}
bool compare(igtlio::VideoDevicePointer a, igtlio::VideoDevicePointer b)
{
if (a->GetDeviceName() != b->GetDeviceName())
return false;
if (a->GetDeviceType() != b->GetDeviceType())
return false;
if (!compare(a->GetContent().image, b->GetContent().image))
return false;
return true;
}
int main(int argc, char **argv)
{
ClientServerFixture fixture;
if (!fixture.ConnectClientToServer())
return 1;
if (fixture.Client.Logic->GetNumberOfDevices() != 0)
{
std::cout << "ERROR: Client has devices before they have been added or fundamental error!" << std::endl;
return 1;
}
std::cout << "*** Connection done" << std::endl;
//---------------------------------------------------------------------------
igtlio::VideoDevicePointer videoDevice;
videoDevice = fixture.Server.Session->SendFrame("TestDevice_Image",
fixture.CreateTestImage());
std::cout << "*** Sent message from Server to Client" << std::endl;
//---------------------------------------------------------------------------
if (!fixture.LoopUntilEventDetected(&fixture.Client, igtlio::Logic::NewDeviceEvent))
{
return 1;
}
if (fixture.Client.Logic->GetNumberOfDevices() == 0)
{
std::cout << "FAILURE: No devices received." << std::endl;
return 1;
}
igtlio::VideoDevicePointer receivedDevice;
receivedDevice = igtlio::VideoDevice::SafeDownCast(fixture.Client.Logic->GetDevice(0));
if (!receivedDevice)
{
std::cout << "FAILURE: Non-video device received." << std::endl;
return 1;
}
std::cout << "*** Client received video device." << std::endl;
//---------------------------------------------------------------------------
if (!compare(videoDevice, receivedDevice))
{
std::cout << "FAILURE: frame differs from the one sent from server." << std::endl;
return 1;
}
}
| [
"[email protected]"
] | |
fedb8c9cb5b71e578ad0fd5a381aac47835c6202 | 238edf5919d6653e0c63552229ac9f48e33ba274 | /AccountData v2/testUserClass.cpp | 6d295fc767dee813f4150dbe38a2abe337a5e6d2 | [] | no_license | elnasty/222_A1 | 9a5b22cb282df9e5185c47250362b8a0fc0247de | 99b9fbd29da3888ed83389045bab122aa3e38d92 | refs/heads/master | 2021-05-05T00:32:17.041262 | 2018-02-21T02:47:01 | 2018-02-21T02:47:01 | 119,502,345 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,294 | cpp | #include "User.cpp"
int main ()
{
//Testing constructors
User user;
User user1 ("S12345", "abc123", "abc.gmail.com");
User user2 ("54321", "12345", "maybenot.gmail.com");
//Test mutators
user2.setStaffID ("setala");
user2.setPwd("setpw");
user2.setEmail("set.gmail.com");
user2.setAccLock (true);
//Test Accessors
cout<< user2.getStaffID() << '\t'
<< user2.getPwd() << '\t'
<< user2.getEmail() << '\t';
if (user2.getAccLock () == true)
cout << "Locked";
else
cout << "Unlocked";
cout << endl;
cout<< user1.getStaffID() << '\t'
<< user1.getPwd() << '\t'
<< user1.getEmail() << '\t';
if (user1.getAccLock () == true)
cout << "Locked";
else
cout << "Unlocked";
cout << endl;
cout<< user.getStaffID() << '\t'
<< user.getPwd() << '\t'
<< user.getEmail() << '\t';
if (user.getAccLock () == true)
cout << "Locked";
else
cout << "Unlocked";
cout << endl;
//Testing if user is empty
if (strcmp (user.getStaffID(), "") == 0)
cout << "Empty" << '\t';
if (strcmp (user.getPwd(), "") == 0)
cout << "Empty" << '\t';
if (strcmp (user.getEmail(), "") == 0)
cout << "Empty" << endl;
if (user.isEmpty())
cout << "This user is not allocated!" << endl;
}
| [
"Dell@Dell-PC"
] | Dell@Dell-PC |
c905e9da6f2c33553dbd6bed45248bdb887e2a74 | d7bd0cd8e016fc213ac3e0149487c77e8ef523ba | /Algorithmic_Problem_Solving/rec6_5.cpp | f7db1a222f7a37cbe53e9875d7049d8c2c418bb4 | [] | no_license | Michael98Liu/Competitive-Programming | eafa6fa063efedeec8da10a85ad7a9b8900728b3 | dc5752a1e90bcd3a908e7f307776baf0d349af34 | refs/heads/master | 2021-01-01T20:03:04.073372 | 2019-02-14T15:31:39 | 2019-02-14T15:31:39 | 98,750,625 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 453 | cpp | #include <iostream>
#include <vector>
#include <math.h>
using namespace std;
int main(){
int t;
int n;
int num;
scanf("%d\n", &t);
for( int i =0; i< t; i++ ){
vector<int> canvas;
scanf("%d\n", &n);
for( int j= 0; j < n; j++ ){
scanf("%d\n", &num);
canvas.push_back(num);
}
int layer = (int)log2(n) -1;
int paint =
printf("%d\n", paint);
}
}
| [
"[email protected]"
] | |
82465516e53ab94951fdf7eb231788aaaf6bdb5d | 8ce8354aaf1e39e278ffc0bab22e57675d3c4a90 | /libbsn/test/test_configuration.h | 3076de0c253052fe00be9e3c45e4302ce902fb35 | [] | no_license | rdinizcal/bsn | b82dc2926178320f488b8798e9be3ae0449c0f21 | f51d7e6d30e04847b3d0b3223a63ed723858339e | refs/heads/master | 2022-01-13T00:48:04.861834 | 2019-01-28T18:09:53 | 2019-01-28T18:09:53 | 104,138,457 | 2 | 0 | null | 2019-01-09T20:34:24 | 2017-09-19T23:03:27 | C++ | UTF-8 | C++ | false | false | 5,195 | h | #include <cxxtest/TestSuite.h>
#include <iostream>
#include "bsn/configuration/SensorConfiguration.hpp"
using namespace std;
using namespace bsn::range;
using namespace bsn::configuration;
class SensoConfigurationTestSuite: public CxxTest::TestSuite{
Range l;
Range m1;
Range m2;
Range h1;
Range h2;
array<Range,2> a1;
array<Range,2> a2;
array<Range,3> percentages;
SensorConfiguration s;
public:
void setUp(){
l.setLowerBound(36.5);
l.setUpperBound(37.5);
m1.setLowerBound(33);
m1.setUpperBound(35);
h1.setLowerBound(20);
h1.setUpperBound(32);
m2.setLowerBound(37.6);
m2.setUpperBound(39.0);
h2.setLowerBound(39.1);
h2.setUpperBound(43.0);
percentages = {Range(0,0.2), Range(0.21,0.65), Range(0.66,1.0)};
a1 = {m1, m2};
a2 = {h1, h2};
}
void test_constructor() {
cout << "Testando configurações do sensor" << endl;
cout << "\tTestando construtor:\n";
SensorConfiguration s(1,l,a1,a2,percentages);
TS_ASSERT_EQUALS(1, s.getId());
}
void test_unknow_value() {
cout << "\tTestando avaliação sinal unknow\n";
TS_ASSERT_EQUALS(s.evaluateNumber(44), -1);
TS_ASSERT_EQUALS(s.evaluateNumber(10), -1);
}
void test_getDisplacement_normal() {
cout << "\tTestando metodo getDisplacement em ordem\n";
SensorConfiguration s(1,l,a1,a2,percentages);
TS_ASSERT_EQUALS(s.getDisplacement( Range(0,10), 5, "crescent"), 0.5 );
TS_ASSERT_EQUALS(s.getDisplacement( Range(0,10), 10, "crescent"), 1 );
TS_ASSERT_EQUALS(s.getDisplacement( Range(0,10), 0, "crescent"), 0 );
TS_ASSERT_EQUALS(s.getDisplacement( Range(0,10), 7.5, "crescent"), 0.75 );
TS_ASSERT_EQUALS(s.getDisplacement( Range(0,10), 2.5, "crescent"), 0.25 );
}
void test_getDisplacement_inverse() {
cout << "\tTestando metodo getDisplacement com logica decrescente\n";
SensorConfiguration s(1,l,a1,a2,percentages);
TS_ASSERT_EQUALS(s.getDisplacement( Range(0,10), 5, "decrescent"), 0.5 );
TS_ASSERT_EQUALS(s.getDisplacement( Range(0,10), 10, "decrescent"), 0 );
TS_ASSERT_EQUALS(s.getDisplacement( Range(0,10), 0, "decrescent"), 1 );
TS_ASSERT_EQUALS(s.getDisplacement( Range(0,10), 7.5, "decrescent"), 0.25 );
TS_ASSERT_EQUALS(s.getDisplacement( Range(0,10), 2.5, "decrescent"), 0.75 );
}
void test_getDisplacement_medium() {
cout << "\tTestando metodo getDisplacement com logica mediana\n";
SensorConfiguration s(1,l,a1,a2,percentages);
TS_ASSERT_EQUALS(s.getDisplacement( Range(0,10), 5, "medium"), 0.0 );
TS_ASSERT_EQUALS(s.getDisplacement( Range(0,10), 10, "medium"), 1 );
TS_ASSERT_EQUALS(s.getDisplacement( Range(0,10), 0, "medium"), 1 );
TS_ASSERT_EQUALS(s.getDisplacement( Range(0,10), 7.5, "medium"), 0.50 );
TS_ASSERT_EQUALS(s.getDisplacement( Range(0,10), 2.5, "medium"), 0.50 );
TS_ASSERT_EQUALS(s.getDisplacement( Range(36.5,37.5), 37.0, "medium"), 0 );
TS_ASSERT_EQUALS(s.getDisplacement( Range(36.5,37.5), 36.5, "medium"), 1 );
TS_ASSERT_EQUALS(s.getDisplacement( Range(36.5,37.5), 37.5, "medium"), 1 );
}
void test_getDisplacement_invalid_argument() {
cout << "\tTestando metodo getDisplacement com argumentos inválidos\n";
SensorConfiguration s(1,l,a1,a2,percentages);
TS_ASSERT_THROWS(s.getDisplacement( Range(0,10), 5, "kjflakj"), std::invalid_argument);
}
void test_low() {
cout << "\tTestando avaliação sinal low\n";
SensorConfiguration s(1,l,a1,a2,percentages);
TS_ASSERT_EQUALS(s.evaluateNumber(37),0);
TS_ASSERT_EQUALS(s.evaluateNumber(37.5), 0.2);
TS_ASSERT_EQUALS(s.evaluateNumber(36.5), 0.2);
TS_ASSERT_EQUALS(s.evaluateNumber(36.75), 0.1);
}
void test_medium0() {
cout << "\tTestando avaliação sinal medium0\n";
SensorConfiguration s(1,l,a1,a2,percentages);
TS_ASSERT_EQUALS(s.evaluateNumber(33), 0.65);
TS_ASSERT_EQUALS(s.evaluateNumber(35), 0.21);
}
void test_medium1() {
cout << "\tTestando avaliação sinal medium1\n";
SensorConfiguration s(1,l,a1,a2,percentages);
TS_ASSERT_EQUALS(s.evaluateNumber(37.6), 0.21);
TS_ASSERT_EQUALS(s.evaluateNumber(39), 0.65);
}
void test_high0() {
cout << "\tTestando avaliação sinal high0\n";
SensorConfiguration s(1,l,a1,a2,percentages);
TS_ASSERT_EQUALS(s.evaluateNumber(20), 1);
TS_ASSERT_EQUALS(s.evaluateNumber(32), 0.66);
}
void test_high1() {
cout << "\tTestando avaliação sinal high1\n";
SensorConfiguration s(1,l,a1,a2,percentages);
TS_ASSERT_EQUALS(s.evaluateNumber(39.1), 0.66);
TS_ASSERT_EQUALS(s.evaluateNumber(43), 1.0);
}
};
| [
"[email protected]"
] | |
1150764899bd035a85eb0f69741020b8950a6389 | 9ecbc437bd1db137d8f6e83b7b4173eb328f60a9 | /gcc-build/i686-pc-linux-gnu/libjava/java/sql/Time.h | 5070468f21da1ac2ff15882032e1c9acbd38e760 | [] | no_license | giraffe/jrate | 7eabe07e79e7633caae6522e9b78c975e7515fe9 | 764bbf973d1de4e38f93ba9b9c7be566f1541e16 | refs/heads/master | 2021-01-10T18:25:37.819466 | 2013-07-20T12:28:23 | 2013-07-20T12:28:23 | 11,545,290 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 766 | h | // DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*-
#ifndef __java_sql_Time__
#define __java_sql_Time__
#pragma interface
#include <java/util/Date.h>
extern "Java"
{
namespace java
{
namespace sql
{
class Time;
}
namespace text
{
class SimpleDateFormat;
}
}
};
class ::java::sql::Time : public ::java::util::Date
{
public:
static ::java::sql::Time *valueOf (::java::lang::String *);
Time (jint, jint, jint);
Time (jlong);
virtual ::java::lang::String *toString ();
public: // actually package-private
static const jlong serialVersionUID = 8397324403548013681LL;
private:
static ::java::text::SimpleDateFormat *sdf;
public:
static ::java::lang::Class class$;
};
#endif /* __java_sql_Time__ */
| [
"[email protected]"
] | |
3f4ac0c200521f5b1e24aa445c87209ac1240086 | de362ea0a23543fb0a39a9732be3f91958c9e4f9 | /UnderGraduate/bin/debug/moc_DioPortUI.cpp | 8b697a8e6517374fb9346061470116c9c644cff9 | [] | no_license | looklucas/Control | 341aa15d369928a68be932700a781e8cc8c85a37 | 751657b23d4f4ae73ddc8276070ba33bd9724db2 | refs/heads/master | 2022-12-09T21:04:24.786472 | 2019-06-19T06:43:58 | 2019-06-19T06:43:58 | 166,159,719 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,350 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'DioPortUI.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.11.2)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../common/DioPortUI.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'DioPortUI.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.11.2. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_DioPortUI_t {
QByteArrayData data[6];
char stringdata0[48];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_DioPortUI_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_DioPortUI_t qt_meta_stringdata_DioPortUI = {
{
QT_MOC_LITERAL(0, 0, 9), // "DioPortUI"
QT_MOC_LITERAL(1, 10, 12), // "stateChanged"
QT_MOC_LITERAL(2, 23, 0), // ""
QT_MOC_LITERAL(3, 24, 6), // "sender"
QT_MOC_LITERAL(4, 31, 13), // "ButtonClicked"
QT_MOC_LITERAL(5, 45, 2) // "id"
},
"DioPortUI\0stateChanged\0\0sender\0"
"ButtonClicked\0id"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_DioPortUI[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
2, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
1, // signalCount
// signals: name, argc, parameters, tag, flags
1, 1, 24, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
4, 1, 27, 2, 0x08 /* Private */,
// signals: parameters
QMetaType::Void, QMetaType::QObjectStar, 3,
// slots: parameters
QMetaType::Void, QMetaType::Int, 5,
0 // eod
};
void DioPortUI::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
DioPortUI *_t = static_cast<DioPortUI *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->stateChanged((*reinterpret_cast< QObject*(*)>(_a[1]))); break;
case 1: _t->ButtonClicked((*reinterpret_cast< int(*)>(_a[1]))); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
{
using _t = void (DioPortUI::*)(QObject * );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&DioPortUI::stateChanged)) {
*result = 0;
return;
}
}
}
}
QT_INIT_METAOBJECT const QMetaObject DioPortUI::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_DioPortUI.data,
qt_meta_data_DioPortUI, qt_static_metacall, nullptr, nullptr}
};
const QMetaObject *DioPortUI::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *DioPortUI::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_DioPortUI.stringdata0))
return static_cast<void*>(this);
return QWidget::qt_metacast(_clname);
}
int DioPortUI::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 2)
qt_static_metacall(this, _c, _id, _a);
_id -= 2;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 2)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 2;
}
return _id;
}
// SIGNAL 0
void DioPortUI::stateChanged(QObject * _t1)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| [
"[email protected]"
] | |
d3152d4f72dd7ba8eaaf88c015b2ef115c6d804c | 51efb0b6dac397477499eed32b4b92dbe1ce18da | /src/p4_main.cpp | c9ad46f6528c163e1b4ee261b1d80d2d6336a427 | [
"MIT"
] | permissive | fneiva2006/supervisory-simulator | eec883e4bbe6f5e7f05d5f0f3757dd3f6f7455d4 | 0e451f35afd111496cf8a25c6a9402a6f95860ea | refs/heads/master | 2022-08-30T04:40:09.294686 | 2020-05-31T15:32:54 | 2020-05-31T15:32:54 | 268,308,425 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 10,006 | cpp | #include "p4_ops.h"
/* Control HANDLES */
HANDLE ghExitEvent = NULL; // Evento encerramento do programa
HANDLE ghExibeOpSem = NULL; // Semáforo liga/desliga módulo
/* OP List HANDLES */
HANDLE ghListaOPMappedFile = NULL; //
HANDLE ghPermissaoLeituraOPSem = NULL;
HANDLE ghPermissaoEscritaOPSem = NULL;
HANDLE ghListaOPMutex = NULL;
/* OP Disk List Handles */
HANDLE ghOPDiskList = NULL;
int main(int argc, char* argv[])
{
setlocale(LC_ALL,"");
/* Adquire Handle de janela de console */
HWND ptr = GetConsoleWindow();
/* Posiciona janela do console em local inicial */
MoveWindow(ptr,670,0,720,400, true);
/* Desativa Botão de Fechar da Janela do Console */
EnableMenuItem(GetSystemMenu(ptr, FALSE), SC_CLOSE,
MF_BYCOMMAND | MF_DISABLED | MF_GRAYED);
inicializaObjetosP4();
DWORD indice_leitura = 0; // Posição da lista de Status a ser lida
char *sm_ptr; // Ponteiro auxiliar para captura de mensagens da lista
/* Buffer auxiliar para armazenar as mensagens lidas da lista */
char buffer[TAMANHO_MSG_ORDEM_PRODUCAO+1];
/* Endereço base relativo ao início da lista de status compartilhada em memória */
const char* base_sm_addr = (char*) MapViewOfFile(ghListaOPMappedFile,
FILE_MAP_READ | FILE_MAP_WRITE,
0,
0,
(TAMANHO_LISTA_OP*TAMANHO_MSG_ORDEM_PRODUCAO) + sizeof(DWORD) );
DWORD* n_entradas_lista = (DWORD*) &base_sm_addr[TAMANHO_LISTA_OP*TAMANHO_MSG_ORDEM_PRODUCAO];
/* Array auxiliar de handles */
HANDLE hSinc[] = { ghExitEvent, ghExibeOpSem };
while(1)
{
/* Aguarda Evento de Encerramento Global ou Estado de Exibição Ligado
(Semaforo de Controle on/off do módulo) */
if(WaitForMultipleObjects(2,hSinc,FALSE,INFINITE) == WAIT_OBJECT_0) break;
/* Aguarda Permissão de Leitura da Lista (Semáforo de Recurso Compartilhado
da lista). Operação com timeout */
if( WaitForSingleObject(ghPermissaoLeituraOPSem,TIMEOUT_MS) == WAIT_TIMEOUT)
{
/* Libera Semaforo de Controle on/off do módulo de Exibição de Mensagens de Status*/
ReleaseSemaphore(ghExibeOpSem,1,NULL); continue;
}
/* Aguarda Condição de exclusão mútua para Leitura da Lista
(Mutex de Recurso Compartilhado da lista). Operação com timeout */
if( WaitForSingleObject(ghListaOPMutex,TIMEOUT_MS) == WAIT_TIMEOUT)
{
/* Libera Semaforo de Controle on/off do módulo de Exibição de Mensagens de Status*/
ReleaseSemaphore(ghExibeOpSem,1,NULL); continue;
}
/* Adquire posição da memória da próxima mensagem da lista ser lida */
sm_ptr = (char*) &base_sm_addr[indice_leitura*TAMANHO_MSG_ORDEM_PRODUCAO];
/* Extrai e salva no buffer mensagem de status localizada no endereço
de memoria obtido anteriormente*/
strncpy(buffer,sm_ptr,TAMANHO_MSG_ORDEM_PRODUCAO);
buffer[TAMANHO_MSG_ORDEM_PRODUCAO] = '\0';
/* Exibe Mensagem Extraída da Lista e a salva em Disco */
salvaOPEmDisco(buffer);
exibeMensagemOP(buffer);
/* Decrementa número de entradas da lista que ainda não foram lidas */
*n_entradas_lista = *n_entradas_lista - 1;
/* Atualiza índice para a leitura da próxima mensagem da lista*/
indice_leitura = (indice_leitura+1)%TAMANHO_LISTA_OP;
/* Libera 1 permissão de escrita na lista */
ReleaseSemaphore(ghPermissaoEscritaOPSem,1,NULL);
/* Libera Mutex de controle do acesso a lista */
ReleaseMutex(ghListaOPMutex);
/* Libera Semaforo de Controle on/off do módulo de Exibição de Mensagens de Status */
ReleaseSemaphore(ghExibeOpSem,1,NULL);
}
FlushFileBuffers(ghOPDiskList);
UnmapViewOfFile(sm_ptr); /* Fecha visão da lista compartilhada em memória */
fechaHandlesP4();
/* Salva copia da lista de OP's em disco */
CopyFile(OP_DISK_LIST,COPIA_OP_DISK_LIST,FALSE);
SetFileAttributes(COPIA_OP_DISK_LIST,FILE_ATTRIBUTE_NORMAL);
return 0;
}
void inicializaObjetosP4(void)
{
/* Control HANDLES */
/* Abre o evento de encerramento global da aplicação */
ghExitEvent = (HANDLE) OpenEvent(EVENT_ALL_ACCESS,FALSE,GLOBAL_EXIT_EVENT);
CheckForError(ghExitEvent);
/* Abre o semaforo de controle on/off do modulo de exibição das mensagens de status*/
ghExibeOpSem = (HANDLE) OpenSemaphore(SEMAPHORE_ALL_ACCESS,FALSE,EXIBE_OP_SEM);
CheckForError(ghExibeOpSem);
/* ----------------------------------------------------------------------- */
/* OP List HANDLES */
/* Abre o handle para a lista de status mapeada em memoria*/
do
{
ghListaOPMappedFile = (HANDLE) OpenFileMapping(FILE_MAP_ALL_ACCESS,FALSE,OP_LIST_MAPPED_FILE);
} while ( ghListaOPMappedFile == INVALID_HANDLE_VALUE);
/* Abre os semaforos de permissao de leitura/escrita da lista de OP's compartilhada em memoria */
do
{
ghPermissaoLeituraOPSem = (HANDLE) OpenSemaphore(SEMAPHORE_ALL_ACCESS,
FALSE,
PERMISSAO_LEITURA_OP_SEM);
ghPermissaoEscritaOPSem = (HANDLE) OpenSemaphore(SEMAPHORE_ALL_ACCESS,
FALSE,
PERMISSAO_ESCRITA_OP_SEM);
} while( ( ghPermissaoLeituraOPSem == INVALID_HANDLE_VALUE) || ( ghPermissaoEscritaOPSem == INVALID_HANDLE_VALUE ));
/* Abre Mutex da Lista em de OP's em Memoria Compartilhada */
do
{
ghListaOPMutex= (HANDLE) OpenMutex(MUTEX_ALL_ACCESS,FALSE, LISTA_OP_MUTEX);
} while(ghListaOPMutex == INVALID_HANDLE_VALUE);
/* OP Disk List Handles */
ghOPDiskList = (HANDLE) CreateFile(OP_DISK_LIST,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ,
NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_HIDDEN,
NULL);
if(GetLastError() != 0 && GetLastError() != ERROR_ALREADY_EXISTS )
printf("Erro ao abrir lista em disco. Error ID %d\n", GetLastError());
inicializaListaOPEmDisco();
exibeListaOPEmDisco();
}
void fechaHandlesP4(void)
{
/* Fechamento de todos os handles utilizados no código */
/* Control HANDLES */
CloseHandle(ghExitEvent);
CloseHandle(ghExibeOpSem);
/* Status List HANDLES */
CloseHandle(ghListaOPMappedFile);
CloseHandle(ghPermissaoLeituraOPSem);
CloseHandle(ghPermissaoEscritaOPSem);
CloseHandle(ghListaOPMutex);
/* OP Disk List Handles */
CloseHandle(ghOPDiskList);
}
void exibeMensagemOP(const char* msg)
{
MensagemOP_t Mensagem;
static char copia[32];
strcpy(copia,msg);
strcpy(Mensagem.nseq, strtok(copia,"/"));
strcpy(Mensagem.op, strtok(NULL,"/"));
strcpy(Mensagem.tbat, strtok(NULL,"/"));
strcpy(Mensagem.linha, strtok(NULL,"/"));
strcpy(Mensagem.tipo, strtok(NULL,"/"));
strcpy(Mensagem.receita, strtok(NULL,"/"));
printf("NSEQ: %s OP: %s TBAT: %s LINHA: %s TIPO: %s RECEITA: %s\n",
Mensagem.nseq, Mensagem.op, Mensagem.tbat, Mensagem.linha, Mensagem.tipo,
Mensagem.receita);
}
void salvaOPEmDisco(const char* msg)
{
static char buffer[256] = {0};
DWORD bytes_escritos;
DWORD pointer = 0;
DWORD idx_proxima_entrada = 0;
BOOL lista_completa = true;
LockFile(ghOPDiskList,0,0, ( (TAMANHO_LISTA_OP*TAMANHO_MSG_ORDEM_PRODUCAO) + OVERHEAD_CONTROLE),0);
SetFilePointer(ghOPDiskList,-(LONG) OVERHEAD_CONTROLE,0,FILE_END);
ReadFile(ghOPDiskList,&idx_proxima_entrada,sizeof(DWORD),&bytes_escritos,NULL);
SetFilePointer(ghOPDiskList,idx_proxima_entrada*TAMANHO_MSG_ORDEM_PRODUCAO,0,FILE_BEGIN);
WriteFile(ghOPDiskList,msg,TAMANHO_MSG_ORDEM_PRODUCAO,&bytes_escritos,NULL);
printf("Atribuindo à Entrada %d -> \n\t",idx_proxima_entrada+1);
idx_proxima_entrada = (idx_proxima_entrada+1)%TAMANHO_LISTA_OP;
SetFilePointer(ghOPDiskList,-(LONG) OVERHEAD_CONTROLE,0,FILE_END);
WriteFile(ghOPDiskList,&idx_proxima_entrada,sizeof(DWORD),&bytes_escritos,NULL);
if(idx_proxima_entrada == 0)
WriteFile(ghOPDiskList,&lista_completa,sizeof(BOOL),&bytes_escritos,NULL);
UnlockFile(ghOPDiskList,0,0, ( (TAMANHO_LISTA_OP*TAMANHO_MSG_ORDEM_PRODUCAO) + OVERHEAD_CONTROLE),0);
}
void inicializaListaOPEmDisco()
{
/* Inicialização do tamanho da lista em disco */
_LARGE_INTEGER liTamanhoListaDisco = {0}, pointer = {0};
liTamanhoListaDisco.LowPart = ( (TAMANHO_LISTA_OP*TAMANHO_MSG_ORDEM_PRODUCAO) + OVERHEAD_CONTROLE);
/* Valores de campos de controle a serem inicializados */
DWORD init_idx = 0;
BOOL init_lista_completa = 0;
DWORD bytes_escritos = 0;
/* Sob regime de exclusão mútua, escreve valores de incialização nos campos de controle da lista */
LockFile(ghOPDiskList,0,0, ( (TAMANHO_LISTA_OP*TAMANHO_MSG_ORDEM_PRODUCAO) + OVERHEAD_CONTROLE),0);
if(SetFilePointer(ghOPDiskList,0,0,FILE_END) != liTamanhoListaDisco.LowPart)
{
puts("Lista de OP's em Disco Inexistente. Criando Lista Agora ...");
SetFilePointerEx(ghOPDiskList,liTamanhoListaDisco, &pointer, FILE_BEGIN );
SetEndOfFile(ghOPDiskList);
SetFilePointer(ghOPDiskList,-(LONG) OVERHEAD_CONTROLE,0,FILE_END);
WriteFile(ghOPDiskList,&init_idx,sizeof(DWORD),&bytes_escritos,NULL);
WriteFile(ghOPDiskList,&init_lista_completa,sizeof(BOOL),&bytes_escritos,NULL);
}
UnlockFile(ghOPDiskList,0,0, ( (TAMANHO_LISTA_OP*TAMANHO_MSG_ORDEM_PRODUCAO) + OVERHEAD_CONTROLE),0);
}
void exibeListaOPEmDisco()
{
char buffer[256];
DWORD bytes_lidos;
DWORD idx_proxima_entrada = 0;
BOOL lista_completa = FALSE;
DWORD i;
LockFile(ghOPDiskList,0,0, ( (TAMANHO_LISTA_OP*TAMANHO_MSG_ORDEM_PRODUCAO) + OVERHEAD_CONTROLE),0);
SetFilePointer(ghOPDiskList,-(LONG)OVERHEAD_CONTROLE,0,FILE_END);
ReadFile(ghOPDiskList,&idx_proxima_entrada,sizeof(DWORD),&bytes_lidos,NULL);
ReadFile(ghOPDiskList,&lista_completa,sizeof(BOOL),&bytes_lidos,NULL);
if(lista_completa)
{
idx_proxima_entrada = TAMANHO_LISTA_OP;
printf("Lista está completa (%3d Registros)\n\n",idx_proxima_entrada);
}
else
printf("Lista não está completa e contém %3d Registros \n\n",idx_proxima_entrada);
SetFilePointer(ghOPDiskList,0,0,FILE_BEGIN);
for(i = 0; i < idx_proxima_entrada; i++)
{
ReadFile(ghOPDiskList,buffer,TAMANHO_MSG_ORDEM_PRODUCAO,&bytes_lidos,NULL);
buffer[bytes_lidos] = '\0';
if(bytes_lidos == TAMANHO_MSG_ORDEM_PRODUCAO)
{
printf("%3d) ",i+1);
exibeMensagemOP(buffer);
}
}
UnlockFile(ghOPDiskList,0,0, ( (TAMANHO_LISTA_OP*TAMANHO_MSG_ORDEM_PRODUCAO) + OVERHEAD_CONTROLE),0);
puts("");
} | [
"[email protected]"
] | |
9b5cacbb9deb8b39c364b4d2e95b8bb92e6887e9 | cbbca5fba9870b62c2546642c6bf38d02a19b374 | /Headers/Graphics/ITransform.h | ef5f55ebe0374c5d23099f9ed839cb3c65f5c845 | [] | no_license | jul1278/SimpleComponents | 4383f35d6e7399a22ce540e57870dfb97150d59c | 6e98c96092bb44a83b14435fc9f32a5b1c074c8a | refs/heads/ComponentCollections | 2020-12-11T04:13:28.425645 | 2016-12-13T00:12:12 | 2016-12-13T00:12:12 | 46,651,081 | 0 | 1 | null | 2016-05-08T15:45:26 | 2015-11-22T07:38:29 | C++ | UTF-8 | C++ | false | false | 197 | h | #ifndef ITRANSFORM_H
#define ITRANSFORM_H
struct TransformComponent;
class ITransform
{
public:
virtual ~ITransform() {}
virtual TransformComponent* operator()() = 0;
};
#endif // ITRANSFORM_H | [
"[email protected]"
] | |
f1a7872e43e2438d2ad79693c93b529da2ad43ff | 85cc3a99d62ab295e1015b9d91c70cf3ef5adf72 | /Sparky-core/src/graphics/shaders/Shader.cpp | ef37fc4e9c05384591e34932a2c3fbf247c86274 | [
"Apache-2.0"
] | permissive | JarofJava/Sparky | 9f7376159bab8f19efa52c4d80df094e158a7900 | 78509ab53588368c6182edf43542f05dcdc80293 | refs/heads/master | 2021-01-15T03:43:17.074542 | 2015-11-25T05:50:15 | 2015-11-25T05:50:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,013 | cpp | #include "Shader.h"
#include <GL/glew.h>
namespace sparky { namespace graphics {
Shader::Shader(const char* name, const char* vertSrc, const char* fragSrc)
: m_Name(name), m_VertSrc(vertSrc), m_FragSrc(fragSrc)
{
m_ShaderID = Load(m_VertSrc, m_FragSrc);
}
Shader::Shader(const char* vertPath, const char* fragPath)
: m_Name(vertPath), m_VertPath(vertPath), m_FragPath(fragPath)
{
std::string vertSourceString = read_file(m_VertPath);
std::string fragSourceString = read_file(m_FragPath);
m_VertSrc = vertSourceString.c_str();
m_FragSrc = fragSourceString.c_str();
m_ShaderID = Load(m_VertSrc, m_FragSrc);
}
Shader* Shader::FromFile(const char* vertPath, const char* fragPath)
{
return new Shader(vertPath, fragPath);
}
Shader* Shader::FromSource(const char* vertSrc, const char* fragSrc)
{
return new Shader(vertSrc, vertSrc, fragSrc);
}
Shader* Shader::FromSource(const char* name, const char* vertSrc, const char* fragSrc)
{
return new Shader(name, vertSrc, fragSrc);
}
Shader::~Shader()
{
glDeleteProgram(m_ShaderID);
}
GLuint Shader::Load(const char* vertSrc, const char* fragSrc)
{
GLuint program = glCreateProgram();
GLuint vertex = glCreateShader(GL_VERTEX_SHADER);
GLuint fragment = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(vertex, 1, &vertSrc, NULL);
glCompileShader(vertex);
GLint result;
glGetShaderiv(vertex, GL_COMPILE_STATUS, &result);
if (result == GL_FALSE)
{
GLint length;
glGetShaderiv(vertex, GL_INFO_LOG_LENGTH, &length);
std::vector<char> error(length);
glGetShaderInfoLog(vertex, length, &length, &error[0]);
SPARKY_ERROR("Failed to compile vertex shader!");
SPARKY_ERROR(&error[0]);
SPARKY_ASSERT(false, "Failed to compile vertex shader!");
glDeleteShader(vertex);
return 0;
}
glShaderSource(fragment, 1, &fragSrc, NULL);
glCompileShader(fragment);
glGetShaderiv(fragment, GL_COMPILE_STATUS, &result);
if (result == GL_FALSE)
{
GLint length;
glGetShaderiv(fragment, GL_INFO_LOG_LENGTH, &length);
std::vector<char> error(length);
glGetShaderInfoLog(fragment, length, &length, &error[0]);
SPARKY_ERROR("Failed to compile fragment shader!");
SPARKY_ERROR(&error[0]);
SPARKY_ASSERT(false, "Failed to compile fragment shader!");
glDeleteShader(fragment);
return 0;
}
glAttachShader(program, vertex);
glAttachShader(program, fragment);
glLinkProgram(program);
glValidateProgram(program);
glDeleteShader(vertex);
glDeleteShader(fragment);
return program;
}
GLint Shader::GetUniformLocation(const GLchar* name)
{
GLint result = glGetUniformLocation(m_ShaderID, name);
if (result == -1)
SPARKY_ERROR(m_Name, ": could not find uniform ", name, " in shader!");
return result;
}
void Shader::SetUniform1f(const GLchar* name, float value)
{
glUniform1f(GetUniformLocation(name), value);
}
void Shader::SetUniform1fv(const GLchar* name, float* value, int count)
{
glUniform1fv(GetUniformLocation(name), count, value);
}
void Shader::SetUniform1i(const GLchar* name, int value)
{
glUniform1i(GetUniformLocation(name), value);
}
void Shader::SetUniform1iv(const GLchar* name, int* value, int count)
{
glUniform1iv(GetUniformLocation(name), count, value);
}
void Shader::SetUniform2f(const GLchar* name, const maths::vec2& vector)
{
glUniform2f(GetUniformLocation(name), vector.x, vector.y);
}
void Shader::SetUniform3f(const GLchar* name, const maths::vec3& vector)
{
glUniform3f(GetUniformLocation(name), vector.x, vector.y, vector.z);
}
void Shader::SetUniform4f(const GLchar* name, const maths::vec4& vector)
{
glUniform4f(GetUniformLocation(name), vector.x, vector.y, vector.z, vector.w);
}
void Shader::SetUniformMat4(const GLchar* name, const maths::mat4& matrix)
{
glUniformMatrix4fv(GetUniformLocation(name), 1, GL_FALSE, matrix.elements);
}
void Shader::Bind() const
{
glUseProgram(m_ShaderID);
}
void Shader::Unbind() const
{
glUseProgram(0);
}
} } | [
"[email protected]"
] | |
23ca988c0b8a51164b47758cd682c0c6d3dfc63d | b5ab8ab0eb0585ce4ed3650dfb0fdee2934ee0d8 | /TMCDriver.h | 6f2ffffd588756d6417ef4c7945561f26049702a | [] | no_license | wwkkww1983/Stretcher-Unit | 6564359c21936a5336863231bf9e569f5f1b438c | 365c1333d28b04bb35b67c320177e50d79473ff2 | refs/heads/master | 2022-06-12T03:28:08.183167 | 2020-05-04T05:49:54 | 2020-05-04T05:49:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,699 | h | #ifndef TMCDRIVER_H_
#define TMCDRIVER_H_
class TMC2660
{
public:
void init();
//DRVCONF
void slopeControlHigh();
void slopeControlLow();
void motorShortTimer(); //TS2G short to ground timer. (turns off power mosfets)
void stepMode(); //RDSEL 0: step and dir interface, 1: SPI interface
void rmsCurrent(); //VSENSE
void readMode(); //RDSEL Microstep positon or stallguard or coolStep current level readback
//SGCSCONF
void filterMode(); //SFILT 0: standard mode, rapid stall detection 1: Filtered mode for precise load measurement.
void stallGrdThresh(); //SGT the higher the value, the higher the torque required to indicate a stall, start with 0.
void currentScale(); //CS
//SMARTEN
void minCoilCurrent(); //SEIMIN 0: 1/2 of CS 1: 1/4 of CS
void coilDecrementSpd(); //SEDN number of times stallguard2 is above threshold is sampled before decrement.
void coilUpperThreshold(); //SEMAX Threshold (high) is (SEMIN + SEMAX + 1)*32 decreases current scaling when above threshold.
void coilLowerThreshold(); //SEMIN Threshold (low) is (SEMIN)*32 increases current scaling when below threshold.
void coilIncrementSize(); //SEUP The magnitude of compensation when the coil current drops below the low threshold.
//CHOPCONF
void blankTime(); //TBL the number of cycles after a switch, in which the sense resistor ringing is ignored (ripples are bad).
void chopperMode(); //CHM 1: constant off-time mode 0: spreadCycle mode
//Spreadcycle mode (dynamic TOFF mode)
void hystEnd(); //HEND sets minimum allowable offset value from target current.
void hystStart(); //HSTRT sets maximum allowable offset value from target current.
void hystDecrement(); //HDEC sets the rate at which the value decrements from HSTRT+HEND to HEND.
//Constant TOFF mode
void slowDecayTime(); //TOFF t = (1/fclk)*((TOFF * 32) + 12)
//DRVCTRL_STEP/DIR_MODE
void setMicroStep(uint8_t); //MRES
void doubleStepping(); //DEDGE 0: Rising step pulse is active, falling is inactive 1: Both rising and falling edge active
void stepInterpolation(); //INTPOL 0: Disable STEP pulse interpolation 1: Enable step pulse multiplication by 16.
//TODO: DRVCTRL_SPI_MODE
private:
//Bitfield construction
void constructBitField(uint32_t bits, uint32_t reg);
uint32_t DRVCTRL_0;
uint32_t DRVCTRL_1;
uint32_t DRVCONF;
uint32_t CHOPCONF;
uint32_t SMARTEN;
uint32_t SGCSCONF;
};
#endif | [
"[email protected]"
] | |
0fbaf8260a39755f49c1eff1d38a0a401da80b4f | d19c27c64206429c3c412b2c87f5d550efbc6a9b | /src/transform/gcx/pathstepexpression.h | 08e6b051de5607f9f18e2eb3585dc5f8db117860 | [
"BSD-3-Clause"
] | permissive | aep/asgaard-aera | 9823b6334cbccc6bc9072aa72be15d9c4061ed06 | 90b021a1ba65d80f19af1689e7c724631cf05ae9 | refs/heads/master | 2021-01-21T08:01:13.494678 | 2012-05-19T14:59:54 | 2012-05-19T14:59:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,268 | h | /*
| Author: Michael Schmidt;
| Gunnar Jehl (multi-step paths/aggregate functions/optimizations)
===========================================================================
===========================================================================
| Software License Agreement (BSD License)
|
| Copyright (c) 2006-2007, Saarland University Database Group
| All rights reserved.
|
| Redistribution and use of this software in source and binary forms,
| with or without modification, are permitted provided that the following
| conditions are met:
|
| * Redistributions of source code must retain the above
| copyright notice, this list of conditions and the
| following disclaimer.
|
| * Redistributions in binary form must reproduce the above
| copyright notice, this list of conditions and the
| following disclaimer in the documentation and/or other
| materials provided with the distribution.
|
| * Neither the name the of Saarland University Database Group nor the names
| of its contributors may be used to endorse or promote products derived
| from this software without specific prior written permission of the
| Saarland University Database Group.
|
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
| ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
| LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
| CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
| SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
| INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
| CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
| ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
| POSSIBILITY OF SUCH DAMAGE.
*/
/*! @file
* @brief Header file for pathstepexpression.cpp.
* @details Header file specifying constructors, destructor and functions for pathstepexpression.cpp.
* @author Michael Schmidt
* @author Gunnar Jehl (multi-step paths/aggregate functions/optimizations)
* @version 1.01b
* @license Software License Agreement (BSD License)
*/
#ifndef PATHSTEPEXPRESSION_H
#define PATHSTEPEXPRESSION_H
#include "expression.h"
#include "pathstepattribute.h"
/*! @def WEIGHT_AXIS_CHILD
* @brief Weight definition for axis <tt>child</tt> used to determine the evaluation order
* of SignOffExpression if more than one appear in a series.
* @details Weight definition for axis <tt>child</tt> used to determine the evaluation order
* of SignOffExpression if more than one appear in a series.
*/
#define WEIGHT_AXIS_CHILD 1
/*! @def WEIGHT_AXIS_DESCENDANT
* @brief Weight definition for axis <tt>descendant</tt> used to determine the evaluation order
* of SignOffExpression if more than one appear in a series.
* @details Weight definition for axis <tt>descendant</tt> used to determine the evaluation order
* of SignOffExpression if more than one appear in a series.
*/
#define WEIGHT_AXIS_DESCENDANT 3
/*! @def WEIGHT_AXIS_DOS
* @brief Weight definition for axis <tt>dos</tt> used to determine the evaluation order
* of SignOffExpression if more than one appear in a series.
* @details Weight definition for axis <tt>dos</tt> used to determine the evaluation order
* of SignOffExpression if more than one appear in a series.
*/
#define WEIGHT_AXIS_DOS 3
/*! @def WEIGHT_INNER_NODETEST
* @brief Weight definition for all inner nodetests of a path used to determine the evaluation order
* of SignOffExpression if more than one appear in a series.
* @details Weight definition for all inner nodetests used to determine the evaluation order
* of SignOffExpression if more than one appear in a series.
*/
#define WEIGHT_INNER_NODETEST 1
/*! @class PathStepExpression
* @brief Abstract base class for path step expressions.
* @details The base clase defines elements that are common to
* all path step expressions, in particular attributes
* and an axis.
* @author Michael Schmidt
* @author Gunnar Jehl (multi-step paths/aggregate functions/optimizations)
* @version 1.01b
* @license Software License Agreement (BSD License)
*/
class PathStepExpression : public Expression {
public:
/*! @brief Constructor.
* @details Constructor - initializes member variables of the base class.
* @param[in] _type The type of the PathStepExpression (either a tag, star
* text, or node expression).
* @param[in] _axis The axis specification.
* @param[in] _attribute An attribute specification, might be NULL.
*/
PathStepExpression(EXP_TYPE _type, AXIS_TYPE _axis,
PathStepAttribute* _attribute);
/*! @brief Destructor.
* @details Destructor.
*/
virtual ~PathStepExpression();
/*! @brief Returns the axis type.
* @details
* @retval AXIS_TYPE
*/
inline AXIS_TYPE getAxisType() { return axis; }
/*! @brief Sets the axis type.
* @details
* @param[in] _axis The axis type to be specified.
* @retval void
*/
inline void setAxisType(AXIS_TYPE _axis) { axis=_axis; }
/*! @brief Returns the type of the path step expression.
* @details
* @retval NODETEST_TYPE
*/
NODETEST_TYPE getNodeTestType();
/*! @brief Returns the attribute of the path step expression.
* @details The attribute might be NULL (which means true()).
* @retval PathStepAttribute*
*/
inline PathStepAttribute* getAttribute() { return attribute; }
/*! @brief Assigns an attribute to the path step expression.
* @details
* @param[in] _attribute The attribute to be set.
* @retval void
*/
inline void setAttribute(PathStepAttribute* _attribute) { attribute=_attribute; }
/*! @brief Returns true if the path step has an attribute associated.
* @details An example of such an attribute might be "position()=1".
* @pretval bool True if an attribute is associated, false otherwise.
*/
inline bool hasAttribute() { return attribute!=NULL ; }
/*! @brief Returns true if the path step is a tag path step
* @details
* @retval bool
*/
inline bool isTagNodeTest() { return type==et_pathsteptag; }
/*! @brief Returns true if the path step is a star-carrying path step
* @details
* @retval bool
*/
inline bool isStarNodeTest() { return type==et_pathstepstar; }
/*! @brief Returns true if the path step is a node()-carrying path step
* @details
* @retval bool
*/
inline bool isNodeNodeTest() { return type==et_pathstepnode; }
/*! @brief Returns true if the path step is a text()-carrying path step
* @details
* @retval bool
*/
inline bool isTextNodeTest() { return type==et_pathsteptext; }
/*! @brief Returns true if the path step is a descendant-or-self::node()
* path step.
* @details
* @retval bool
*/
inline bool isDosNodeStep() { return axis==at_dos && type==et_pathstepnode; }
/*! @brief Checks syntactical equivalence towards another path step
* @details
* @param[in] ps The path step that is compared to this object.
* @retval bool
*/
bool isSyntacticallyEqualTo(PathStepExpression* ps);
// TODO: document this!!!
unsigned getStepWeight(bool is_last_step);
/*! @brief Checks if this path step matches the passed tag
* @details Abstract method reimplemented in the inherited classes.
* @param[in] tag The tag for which matching is checked.
* @retval bool
*/
virtual bool isMatchingTag(TAG tag)=0;
/*! @brief Prints the path step expression.
* @details Abstract method reimplemented in the inherited classes.
* @param[in] o The output stream to print the path step to.
* @retval void
*/
virtual void print(ostream& o) const=0;
/*! @brief Clones the path step expression.
* @details Abstract method reimplemented in the inherited classes.
* @retval PathStepExpression* The cloned path step expression.
*/
virtual PathStepExpression* clone()=0;
/*! @brief Clones the path step expression while ignoring its attributes.
* @details Abstract method reimplemented in the inherited classes.
* @retval PathStepExpression* The cloned path step expression.
*/
virtual PathStepExpression* cloneWithoutAttributes()=0;
protected:
/*! @var AXIS_TYPE axis
* @brief The axis type of the path step expression.
*/
AXIS_TYPE axis;
/*! @var PathStepAttribute* attribute
* @brief The attribute associated with the path step expression.
* @details NULL is used as an equivalent for attribute true()
*/
PathStepAttribute* attribute;
};
#endif // PATHSTEPEXPRESSION_H
| [
"[email protected]"
] | |
19ed2e659710138c2f4d825a7a8f594a2d4e7b3a | 6618549c2c3d1088c95532f075a77c222e0605d4 | /trunk/angry_bus/Node.h | 7db1000c49c46ca25ba556892d5564a060455351 | [] | no_license | cpzhang/bus | 56ba89eb34bbcc1eb80c4db3691f08b7e2e05ad8 | 705ef7d6145f974b707c1fe843764a4c39207dd5 | refs/heads/master | 2016-09-11T07:52:05.859263 | 2012-02-22T00:37:52 | 2012-02-22T00:37:52 | 2,634,123 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,460 | h | #ifndef _Node_
#define _Node_
#include <vector>
#include <string>
#include "Vector3.h"
#include "Entity.h"
#include "ITouch.h"
enum eNodeType
{
eNodeType_Normal,
eNodeType_Transformation,
eNodeType_Button,
eNodeType_Size,
};
template <class T>
class Node: public ITouch
{
public:
Node(const std::string& name)
:_name(name), _visible(true), _data(0), _enable(true)
{
}
virtual ~Node()
{
}
virtual void addChild(Node* n)
{
_children.push_back(n);
}
virtual void removeChild(Node* n)
{
typename std::vector<Node*>::iterator it = _children.begin();
for (; it != _children.end(); ++it)
{
if (n == *it)
{
_children.erase(it);
return;
}
}
}
virtual size_t getChildrenNumber()
{
return _children.size();
}
virtual Node* getChild(size_t index)
{
return _children[index];
}
virtual void setData(T* d)
{
_data = d;
}
virtual T* getData()
{
return _data;
}
typedef void (T::*do_void_void)();
virtual void breadth_first(do_void_void f)
{
if(_data)
(_data->*f)();
for(size_t i = 0; i != getChildrenNumber(); ++i)
{
_children[i]->breadth_first(f);
}
}
typedef bool (T::*do_bool_float_float)(float, float);
virtual bool breadth_first(do_bool_float_float f, float x, float y)
{
if(_data && ((_data->*f)(x, y)))
return true;
for(size_t i = 0; i != getChildrenNumber(); ++i)
{
if(_children[i]->breadth_first(f, x, y))
return true;
}
return false;
}
typedef bool (T::*do_bool_float_float_float_float)(float, float, float, float);
virtual bool breadth_first(do_bool_float_float_float_float f, float x, float y, float previousX, float previousY)
{
if(_data && ((_data->*f)(x, y, previousX, previousY)))
return true;
for(size_t i = 0; i != getChildrenNumber(); ++i)
{
if(_children[i]->breadth_first(f, x, y, previousX, previousY))
return true;
}
return false;
}
virtual void release()
{
for(size_t i = 0; i != getChildrenNumber(); ++i)
{
_children[i]->release();
}
_children.clear();
delete this;
}
virtual void render(){};
virtual void setTransformation(float s=1.0, bool inherit = true){};
virtual bool touchBegin(float x, float y)
{
if (_visible && _enable)
{
if(touchBeginImp(x, y))
{
return true;
}
else
{
//
for(size_t i = 0; i != getChildrenNumber(); ++i)
{
if(_children[i]->touchBegin(x, y))
return true;
}
}
}
return false;
}
virtual bool touchMoved(float x, float y, float previousX, float previousY)
{
if (_visible && _enable)
{
if(touchMovedImp(x, y, previousX, previousY))
{
return true;
}
else
{
//
for(size_t i = 0; i != getChildrenNumber(); ++i)
{
if(_children[i]->touchMoved(x, y, previousX, previousY))
return true;
}
}
}
return false;
}
virtual bool touchEnd(float x, float y)
{
if (_visible && _enable)
{
if(touchEndImp(x, y))
{
return true;
}
else
{
//
for(size_t i = 0; i != getChildrenNumber(); ++i)
{
if(_children[i]->touchEnd(x, y))
return true;
}
}
}
return false;
}
virtual bool touchBeginImp(float x, float y){return false;}
virtual bool touchMovedImp(float x, float y, float previousX, float previousY){return false;}
virtual bool touchEndImp(float x, float y){return false;}
void hide(){_visible = false;}
void show(){_visible = true;}
void setVisible(bool b){_visible = b;}
bool isVisible(){return _visible;}
inline void enable()
{
_enable = true;
}
inline void disable()
{
_enable = false;
}
inline bool isEnable()
{
return _enable;
}
Node* getNodeByName(const std::string& name)
{
if (_name == name)
{
return this;
}
//
for(size_t i = 0; i != getChildrenNumber(); ++i)
{
Node* n = _children[i]->getNodeByName(name);
if(n)
return n;
}
return 0;
}
virtual void setCallBack(IButtonPushedCallBack* cb){};
virtual void setScale(float sx, float sy, float sz){};
virtual void setPosition(float x, float y, float z){};
virtual void setPosition(const Vector3& p){};
virtual void setRotation(float angle){};
//
virtual void translate(float x, float y, float z){};
virtual void translate(const Vector3& p){};
virtual void rotateZ(float angle){};
virtual Vector3 getScale(){return Vector3::ZERO;};
virtual Vector3 getPosition(){return Vector3::ZERO;};
virtual float getRotation(){return 0.0;};
protected:
std::vector<Node*> _children;
Node* _parent;
T* _data;
std::string _name;
bool _visible;
bool _enable;
};
//template<class T>
class TransformationNode: public Node<Entity>
{
public:
inline TransformationNode(const std::string& name)
:_angle(0.0), Node<Entity>(name)
{
}
~TransformationNode(){};
void render()
{
if (_visible)
{
if(_data)
{
if (_enable)
{
_data->render();
}
else
{
_data->render(Color(0.5, 0.5, 0.5, 1.0));
}
}
for(size_t i = 0; i != getChildrenNumber(); ++i)
{
_children[i]->render();
}
}
}
virtual void setTransformation(float s=1.0, bool inherit = true)
{
if(_data)
{
_data->setPosition(_position);
_data->setScale(_scale * s);
_data->setRotation(_angle);
}
if (inherit)
{
for(size_t i = 0; i != getChildrenNumber(); ++i)
{
_children[i]->setTransformation(s);
}
}
}
virtual void setScale(float sx, float sy, float sz)
{
_scale.x = sx;
_scale.y = sy;
_scale.z = sz;
}
virtual void setPosition(float x, float y, float z)
{
_position.x = x;
_position.y = y;
_position.z = z;
}
virtual void setPosition(const Vector3& p)
{
_position = p;
setTransformation();
};
virtual void setRotation(float angle)
{
_angle = angle;
}
virtual Vector3 getScale(){return _scale;};
virtual Vector3 getPosition(){return _position;};
virtual float getRotation(){return _angle;};
//
virtual void translate(float x, float y, float z)
{
_position.x += x;
_position.y += y;
_position.z += z;
}
virtual void translate(const Vector3& p)
{
_position += p;
}
virtual void rotateZ(float angle)
{
_angle += angle;
}
protected:
Vector3 _position;
Vector3 _scale;
float _angle;
};
class ButtonNode: public TransformationNode
{
public:
ButtonNode(const std::string& name);
~ButtonNode();
virtual bool touchBeginImp(float x, float y);
virtual bool touchMovedImp(float x, float y, float previousX, float previousY);
virtual bool touchEndImp(float x, float y);
virtual void setCallBack(IButtonPushedCallBack* cb);
private:
bool isInside(float x, float y);
void onHover();
void onHoverEnd();
void onPushed();
private:
eButtonState _state;
IButtonPushedCallBack* _callback;
};
#endif
| [
"[email protected]"
] | |
11b96deb8736709de660495f1f98f3916dc4f88b | 0365db07f7469678afaf922542176a3b73357736 | /host/analyze_mjpeg.cpp | 5b939743ec30767e6dcceb0521876dabed9e436f | [
"MIT"
] | permissive | zk1132/stm32f429idiscovery-usb-screen | 9b26f6578d99f96ffb350bf7d283ef394996fbae | 777603e3e0d752bc0eea0764eeb72e21c3ba6e9a | refs/heads/master | 2021-01-12T04:34:22.498160 | 2016-10-02T23:18:02 | 2016-10-02T23:18:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,819 | cpp | #include "stdafx.h"
#include "jpeg.h"
#include "stm32f4_discovery_usb_screen.h"
// astyle --pad-oper --indent=spaces=2 --pad-header analyze_mjpeg.cpp
using namespace std;
#include <boost/algorithm/string.hpp>
using namespace std;
using namespace boost;
using namespace boost::algorithm;
using boost::asio::ip::tcp;
using boost::lexical_cast;
int run(int argc, char* argv[]);
void reduce_and_convert(u16* dst, int dst_w, int dst_h, const u8* src, int src_w, int src_h);
int main(int argc, char* argv[])
{
if (argc != 4) {
cout << "Usage: " << argv[0] << " <server> <port> <path>\n" << endl;
return 1;
}
try {
return run(argc, argv);
}
catch (std::exception& e) {
cout << "Exception: " << e.what() << "\n";
return 1;
}
return 0;
}
int run(int argc, char* argv[])
{
init_usb();
//uint16_t b[320*200*2];
//send_screen(b);
boost::asio::io_service io_service;
// Get a list of endpoints corresponding to the server name.
tcp::resolver resolver(io_service);
tcp::resolver::query query(argv[1], argv[2]);
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
tcp::resolver::iterator end;
// Try each endpoint until we successfully establish a connection.
tcp::socket socket(io_service);
boost::system::error_code error = boost::asio::error::host_not_found;
while (error && endpoint_iterator != end) {
//cout << "trying..." << endl;
socket.close();
socket.connect(*endpoint_iterator++, error);
}
if (error) {
throw boost::system::system_error(error);
}
//cout << "connected" << endl;
// Form the request.
boost::asio::streambuf request;
ostream request_stream(&request);
request_stream << "GET " << argv[3] << " HTTP/1.1\r\n";
// Some buggy cams don't work without a user-agent. The header SHOULD be
// included according to the HTTP spec.
request_stream << "User-Agent: MJPEGviewer\r\n";
request_stream << "Host: " << argv[1] << ":" << argv[2] << "\r\n";
request_stream << "Accept: */*\r\n";
request_stream << "\r\n";
// Send the request.
boost::asio::write(socket, request);
//cout << "sent" << endl;
// Read the response status line. The response streambuf will automatically
// grow to accommodate the entire line. The growth may be limited by passing
// a maximum size to the streambuf constructor.
boost::asio::streambuf response;
boost::asio::read_until(socket, response, "\r\n");
//cout << "got response" << endl;
// Check that response is OK.
istream response_stream(&response);
string http_version;
response_stream >> http_version;
unsigned int status_code;
response_stream >> status_code;
string status_message;
getline(response_stream, status_message);
if (!response_stream || http_version.substr(0, 5) != "HTTP/") {
cout << "Invalid response\n";
return 1;
}
if (status_code != 200) {
cout << "Response returned with status code " << status_code << "\n";
return 1;
}
//cout << "response is ok" << endl;
// Read the response headers, which are terminated by a blank line.
boost::asio::read_until(socket, response, "\r\n\r\n");
//cout << "header read ok" << endl;
// Get the MIME multipart boundary from the headers.
regex rx_content_type("Content-Type:.*boundary=(.*)", regex::icase);
regex rx_content_length("Content-length: (.*)", regex::icase);
smatch match;
string header;
string boundary;
while (getline(response_stream, header) && header != "\r") {
//cout << "HTTP HEADER: " << header << endl;
if (regex_search(header, match, rx_content_type)) {
boundary = match[1];
//cout << "BOUNDARY SELECTED: " << boundary << endl;
}
}
//cout << "got mime ok" << endl;
//cout << "boundary: " << boundary << endl;
// Abort if a boundary was not found.
if (boundary == "") {
cout << "Not a valid MJPEG stream" << endl;
return false;
}
u32 buf_size(0);
char* buf(0);
u32 cycles = 0;
while (1) {
//cout << "-- START CYCLE --" << endl;
//cout << "RESPONSE SIZE, BEFORE READ TO BOUNDARY: " << response.size() << endl;
// Read until there is a boundary in the response. If there is already a
// boundary in the buffer, this is a no-op.
boost::asio::read_until(socket, response, boundary);
//cout << "RESPONSE SIZE, AFTER READ TO BOUNDARY: " << response.size() << endl;
// Remove everything up to and including the boundary that is now known to
// be there.
while (getline(response_stream, header)) {
//cout << "BOUNDARY SEARCH: " << header << endl;
if (header == boundary) {
//cout << "BOUNDARY FOUND: " << header << endl;
break;
}
}
// Read the headers that follow the boundary. These always end with a blank
// line. Content-Length must be one of the header lines, and the size of the
// compressed jpeg is read from it.
//cout << "RESPONSE SIZE, AFTER BOUNDARY SEARCH: " << response.size() << endl;
u32 content_length;
while (getline(response_stream, header) && header != "\r") {
trim(header);
//cout << "MM HEADER: " << header << endl;
if (regex_search(header, match, rx_content_length)) {
content_length = lexical_cast<int>(match[1]);
//cout << "MM HEADER CONTENT-LENGTH FOUND: " << content_length << endl;
}
}
// Read until the entire jpeg is in the response.
if (response.size() < content_length) {
boost::asio::read(socket, response, boost::asio::transfer_at_least(
content_length - response.size()));
}
//cout << "RESPONSE SIZE, BEFORE SGETN: " << response.size() << endl;
if (buf_size < content_length) {
buf_size = content_length;
if (buf) {
free(buf);
}
buf = (char*)malloc(buf_size);
}
response.sgetn(buf, content_length);
//cout << "RESPONSE SIZE, BEFORE JPEG CONSUME: " << response.size() << endl;
//response.consume(content_length);
//cout << "RESPONSE SIZE, AFTER JPEG CONSUME: " << response.size() << endl;
// Dump JPG to file for debugging.
//char buf2[10000] = {0};
//response.sgetn(buf2, 1000);
//ofstream o("out.bin", ios::binary);
//o.write(buf2, 1000);
Image image = decompress_jpeg(buf, content_length);
if (!image.error) {
const u8* image_ptr(&image.image_data[0]);
uint16_t screen_buf[320 * 240];
reduce_and_convert(screen_buf, 320, 240, image_ptr, image.w, image.h);
send_screen(screen_buf);
}
++cycles;
//cout << "cycles: " << cycles << endl;
}
free(buf);
deinit_usb();
return 0;
}
// - Convert from 24-bit RGB to 16-bit RGB.
// - Reduce size from native web cam to 320x240 using pixel averages. If source
// size does not divide evenly by destination size on an axis, part of the
// source is unused in that axis.
// - Rotate image 90 deg to compensate for portrait memory layout on Discovery
// board.
void reduce_and_convert(u16* dst, int dst_w, int dst_h, const u8* src, int src_w, int src_h)
{
int w_ratio = src_w / dst_w;
int h_ratio = src_h / dst_h;
int ratio = w_ratio * h_ratio;
for (int dst_y = 0; dst_y < dst_h; ++dst_y) {
for (int dst_x = 0; dst_x < dst_w; ++dst_x) {
int r = 0;
int g = 0;
int b = 0;
for (int src_y = 0; src_y < h_ratio; ++src_y) {
int pos_y = (dst_y * h_ratio + src_y) * src_w * 3;
for (int src_x = 0; src_x < w_ratio; ++src_x) {
int pos_x = (dst_x * w_ratio + src_x) * 3;
int offset = pos_x + pos_y;
r += src[offset];
g += src[++offset];
b += src[++offset];
}
}
r /= ratio;
g /= ratio;
b /= ratio;
dst[dst_y + dst_h * (dst_w - 1 - dst_x)] = (r >> 3) << 11 | (g >> 2) << 5 | (b >> 3);
}
}
}
| [
"[email protected]"
] | |
11854da4f9625a93e1706cd22c1817d31a832012 | 0df48df9ed35e5995af25812137dc0d9d42f96dc | /sketch/RealtekQuadcopter/mpuxxxx.cpp | f67b0be2e28e15275a37f9f13c8f56edb14cb137 | [
"MIT"
] | permissive | ambiot/amb1_arduino | 81539be6ba18a13cc2a33ec37021c5b27684e047 | 16720c2dcbcffa2acee0c9fe973a959cafc3ba8c | refs/heads/dev | 2023-06-08T15:27:52.848876 | 2023-06-07T02:38:24 | 2023-06-07T02:38:24 | 232,280,578 | 9 | 7 | null | 2022-06-01T08:51:01 | 2020-01-07T08:37:52 | C | UTF-8 | C++ | false | false | 6,303 | cpp | /*
The mpuXXXX.cpp is placed under the MIT license
Copyright (c) 2016 Wu Tung Cheng, Realtek
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.
Notes:
1. This quadcopter project is adapted from Raspberry Pilot (Github: https://github.com/jellyice1986/RaspberryPilot).
2. Some functions in this file are adapted from http://www.i2cdevlib.com/devices/mpu6050#source
*/
#if 1
#include "common_lib.h"
#include "./MPU6050/MPU6050_9Axis_MotionApps41.h"
#include "mpuxxxx.h"
MPU6050 mpu;
static float yaw;
static float pitch;
static float roll;
static float yawGyro;
static float pitchGyro;
static float rollGyro;
static float asaX;
static float asaY;
static float asaZ;
static unsigned char *dmpPacketBuffer;
static unsigned short dmpPacketSize;
volatile bool mpuInterrupt = false;
bool blinkState = false;
bool dmpReady = false;
uint8_t mpuIntStatus;
uint8_t devStatus;
uint16_t packetSize;
uint16_t fifoCount;
uint8_t fifoBuffer[64];
Quaternion q;
VectorInt16 aa;
VectorInt16 aaReal;
VectorInt16 aaWorld;
VectorFloat gravity;
float euler[3];
float ypr[3];
int16_t rate[3];
void setYaw(float t_yaw) {
yaw = t_yaw;
}
void setPitch(float t_pitch) {
pitch = t_pitch;
}
void setRoll(float t_roll) {
roll = t_roll;
}
float getYaw() {
return yaw;
}
float getPitch() {
return pitch;
}
float getRoll() {
return roll;
}
void setYawGyro(float t_yaw_gyro) {
yawGyro = t_yaw_gyro;
}
void setPitchGyro(float t_pitch_gyro) {
pitchGyro = t_pitch_gyro;
}
void setRollGyro(float t_roll_gyro) {
rollGyro = t_roll_gyro;
}
float getYawGyro() {
return yawGyro;
}
float getPitchGyro() {
return pitchGyro;
}
float getRollGyro() {
return rollGyro;
}
void dmpDataReady() {
mpuInterrupt = true;
}
bool mpu6050Init() {
printf("Initializing I2C devices...\n");
mpu.initialize();
// load and configure the DMP
printf("Initializing DMP...\n");
devStatus = mpu.dmpInitialize();
// supply your own gyro offsets here, scaled for min sensitivity
mpu.setXGyroOffset(0);
mpu.setYGyroOffset(0);
mpu.setZGyroOffset(0);
// make sure it worked (returns 0 if so)
if (devStatus == 0) {
// turn on the DMP, now that it's ready
printf("Enabling DMP...\n");
mpu.setDMPEnabled(true);
// enable Arduino interrupt detection
printf("Enabling interrupt detection (Ameba D3 pin)...\n");
attachInterrupt(3, dmpDataReady, RISING);
mpuIntStatus = mpu.getIntStatus();
// set our DMP Ready flag so the main loop() function knows it's okay to use it
printf("DMP ready! Waiting for first interrupt...\n");
dmpReady = true;
// get expected DMP packet size for later comparison
packetSize = mpu.dmpGetFIFOPacketSize();
/* We should avoid send/recv I2C data while there is an interrupt invoked.
* Otherwise the MPU6050 would hang and need a power down/up reset.
* So we set this vale big enough that we can finish task before next interrupt happend.
*/
mpu.setRate(3); // 1khz / (1 + 3) = 200 Hz
// configure LED for output
pinMode(LED_PIN, OUTPUT);
return true;
} else {
// ERROR!
// 1 = initial memory load failed
// 2 = DMP configuration updates failed
// (if it's going to break, usually the code will be 1)
printf("DMP Initialization failed (code %d)\n",devStatus);
return false;
}
}
unsigned char getYawPitchRollInfo(float *yprAttitude, float *yprRate, float *xyzAcc,
float *xyzGravity, float *xyzMagnet) {
if (!dmpReady) return -1;
// wait for MPU interrupt or extra packet(s) available
if (!mpuInterrupt && fifoCount < packetSize) {
return -1;
}
// reset interrupt flag and get INT_STATUS byte
mpuInterrupt = false;
mpuIntStatus = mpu.getIntStatus();
// get current FIFO count
fifoCount = mpu.getFIFOCount();
// check for overflow (this should never happen unless our code is too inefficient)
if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
// reset so we can continue cleanly
mpu.resetFIFO();
printf("FIFO overflow!");
return 2;
// otherwise, check for DMP data ready interrupt (this should happen frequently)
} else if (mpuIntStatus & 0x02) {
// wait for correct available data length, should be a VERY short wait
while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
while (fifoCount >= packetSize){
// read a packet from FIFO
mpu.getFIFOBytes(fifoBuffer, packetSize);
// track FIFO count here in case there is > 1 packet available
// (this lets us immediately read more without waiting for an interrupt)
fifoCount -= packetSize;
}
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetGravity(&gravity, &q);
mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
mpu.dmpGetGyro(rate, fifoBuffer);
yprRate[0] = (float) rate[0];
yprRate[1] = (float) rate[1];
yprRate[2] = (float) rate[2];
yprAttitude[0] = ypr[0] * RAD;
yprAttitude[1] = ypr[1] *RAD;
yprAttitude[2] = ypr[2] * RAD;
//printf("yprAttitude[0]=%f,yprAttitude[1]=%f,yprAttitude[2]=%f\n",yprAttitude[0],yprAttitude[3],yprAttitude[2]);
blinkState = !blinkState;
digitalWrite(LED_PIN, blinkState);
return 0;
}
}
#endif
| [
"[email protected]"
] | |
b27fdb7cae46d64dae857cc4f5cf6c0be0b634ab | 56ace8049811f81bb3422c9ef8dffabd9b880ebd | /semester1/hw02/hw02_task02/hw.02_task.02.cpp | 3452cf0dd559af1528f6190570c0613cd2e788b6 | [] | no_license | ramntry/homeworks | eebb83b1d96a043e0024f9f9a9a5c488b9f48baf | 09a211b0008d95aa877b0c1d83120190ea1cb0fc | refs/heads/master | 2016-09-10T02:14:49.395055 | 2013-05-26T20:19:13 | 2013-05-26T20:19:13 | 2,675,593 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 855 | cpp | // author: Roman Tereshin
// email: [email protected]
// hw 02, task 02
// Реализовать подсчет возведение в целую степень
// (с логарифмической сложностью алгоритма)
// [time start] 21:19 21.09.11
// [time estimate] 00:15 00
#include <iostream>
using namespace std;
template <class T>
T pow(T base, int n)
{
T result = 1;
while (n != 0)
{
if (n & 1)
result *= base;
base *= base;
n >>= 1;
}
return result;
}
int main()
{
clog << "This program calculates base^n\nEnter\t base n: ";
double base = 0.0;
int n = 0;
cin >> base >> n;
cout << base << '^' << n << " = "
<< pow<double>(base, n) << endl;
return 0;
}
// [time done] 21:29 21.09.11
// [time real] 00:10 00
| [
"[email protected]"
] | |
6a8b5e9fcff0205d239ad6e1758f8118f966ccc5 | 2357c9b2e8f30801b45530dbd2f2f54449827a06 | /Bento/src/bento/core/Entity.cpp | fde22c74c88fc11f2d2611b17056cc088b1fb4d3 | [] | no_license | jonathanrpace/BentoCPP | 9c9d7cdfd64918fe518d711f9fa9374652c428f0 | 4e81db3c6c64e6712ec546685f6adba39b64c4c3 | refs/heads/master | 2021-01-17T03:05:10.376561 | 2018-02-16T08:49:55 | 2018-02-16T08:49:55 | 43,240,519 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 120 | cpp | #include "Entity.h"
namespace bento
{
Entity::Entity(std::string _name)
: SceneObject(_name, typeid(Entity))
{
}
} | [
"[email protected]"
] | |
2c6839dd118adef3ffd678da6f0cba172666009e | d1b2b8edcc725770488068bfa47baede1da7058c | /5 dynamic_programming/1 0-1_knapsack/4 Minimum_sum_partition/Min_diff_partition_subset.cpp | 90bf6050ea5bd4aa4b12951cdc15b007b9e64488 | [] | no_license | shubhamg199630/coding_interview_course | dbe060a2f33e21f3c7cbaeeff7571c80358aa2ea | 6f06438758e87ee0e6c9d70a5b5e2d2c2aa5c2e5 | refs/heads/main | 2023-06-08T08:51:59.173107 | 2021-06-19T19:56:46 | 2021-06-19T19:56:46 | 326,496,520 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,063 | cpp | #include<bits/stdc++.h>
using namespace std;
bool dp[1001][1001];
bool subset_sum(int arr[], int n ,int sum)
{
for (int i=1;i<=n;i++)
{
for (int j=1;j<=sum;j++)
{
if(arr[i-1]<=j)
dp[i][j]=dp[i-1][j]||dp[i-1][j-arr[i-1]];
else
dp[i][j]=dp[i-1][j];
}
}
return dp[n][sum];
}
void intialization_of_dp()
{
memset(dp,false,sizeof(dp));
for (int i=0;i<=1000;i++)
{
for (int j=0;j<=1000;j++)
{
if (j==0)
dp[i][j]=true;
else if (i==0)
dp[i][j]=false;
}
}
}
void printdp(int n, int sum)
{
for (int i=0;i<=n;i++)
{
for (int j=0;j<=sum;j++)
{
cout<<dp[i][j]<<" ";
}
cout<<endl;
}
}
int min_diff_partition_subset(int arr[], int n)
{
int range=0;
for (int i=0;i<n;i++)
range=range+arr[i];
subset_sum(arr,n, range);
int mi=INT_MAX;
for (int i=0;i<=range;i++)
if(dp[n][i]==true)
mi=min(mi,abs(range-2*i));
return mi;
}
int main()
{
int n;
n=6;
int arr[]={8, 4, 5, 7, 6, 2 };//sum=10; //Target Sum
intialization_of_dp();
cout<<min_diff_partition_subset(arr,n)<<endl;
//printdp(n,sum);
}
| [
"[email protected]"
] | |
7b7cbd42e0739a3ede1386fdcb8a69db641126d7 | 3c378513afb8e6c2680715c91c31845b67e71885 | /src/KScheme_4Bit_IU.cpp | 83f6e2757c6451b54b037899acefdb27fbbfd6f9 | [] | no_license | yingfeng/integer_encoding_library_sparklezzz | 582f21140a0c6cccae692f8e92464b8a1f093674 | 8ba46561cde38920674f4789f4f413ceed45ef6b | refs/heads/master | 2021-01-17T12:26:12.838738 | 2015-01-14T13:37:40 | 2015-01-14T13:37:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,082 | cpp | /*
* KScheme_4Bit_IU.cpp
*
* Created on: 2013-2-25
* Author: zxd
*/
#include "KScheme_4Bit_IU.hpp"
using namespace paradise::index;
int KScheme_4Bit_IU::encodeUint32(char* des, const uint32_t* src, uint32_t encodeNum) {
return encode<uint32_t> (des, src, encodeNum);
}
int KScheme_4Bit_IU::decodeUint32(uint32_t* des, const char* src, uint32_t decodeNum) {
return decode<uint32_t> (des, src, decodeNum);
}
int KScheme_4Bit_IU::encodeUint16(char* des, const uint16_t* src, uint32_t encodeNum) {
return encode<uint16_t> (des, src, encodeNum);
}
int KScheme_4Bit_IU::decodeUint16(uint16_t* des, const char* src, uint32_t decodeNum) {
return decode<uint16_t> (des, src, decodeNum);
}
int KScheme_4Bit_IU::encodeUint8(char* des, const uint8_t* src, uint32_t encodeNum) {
return encode<uint8_t> (des, src, encodeNum);
}
int KScheme_4Bit_IU::decodeUint8(uint8_t* des, const char* src, uint32_t decodeNum) {
return decode<uint8_t> (des, src, decodeNum);
}
Compressor* KScheme_4Bit_IU::clone() {
Compressor* pNewComp = new KScheme_4Bit_IU(*this);
return pNewComp;
}
| [
"[email protected]"
] | |
1cd28019f65db30869125aa68f0040026fa638dd | 54a0e4f3f7df67cda627b13f88243c6d94058b90 | /lab2/lab2.cpp | 5d78e6af18e9d101e8813f5eec57ed44ecc92260 | [] | no_license | jacobhilty/Jacobhilty-csci20-fall2016 | 11060b349c70278440ea949c20563146ea74fb05 | 34b2f010f6caba2dfd5544885c495721d09a7f45 | refs/heads/master | 2020-11-30T13:53:49.381013 | 2016-09-06T09:54:20 | 2016-09-06T09:54:20 | 66,402,110 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 596 | cpp | //Jacob hilty
//8/25/16
//Creating an algorithm in comments, finished at home.
//1. Computer chooses any number between 1 and 10 that the user cannot see
//2. User picks number between 1 and 10
//3. if user's chosen number is the same as number chosen by the compputer, user is awarded 10 points.
//4. if user's chosen number is not the same as number chosen by the computer, user may guess again, losing 1 possible point in the process of an incorrect guess.
//4-2. example: computer picks 2, user picks 3, user loses 1 possible point out of 10. In the next guess, user picks 2, gets 9 points.
| [
"[email protected]"
] | |
ba3e2faf1e9da7916bac5c828ad40c5cfde34cab | 5b3bf81b22f4eb78a1d9e801b2d1d6a48509a236 | /codeforces/global_round_2/fret.cc | a6e771b030f66a1deb7cbee1711ba9a99f1b46fd | [] | no_license | okoks9011/problem_solving | 42a0843cfdf58846090dff1a2762b6e02362d068 | e86d86bb5e3856fcaaa5e20fe19194871d3981ca | refs/heads/master | 2023-01-21T19:06:14.143000 | 2023-01-08T17:45:16 | 2023-01-08T17:45:16 | 141,427,667 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,090 | cc | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
long long CountUnique(long long w,
const vector<long long>& d,
const vector<long long>& acc) {
auto p = lower_bound(d.begin(), d.end(), w) - d.begin() - 1;
long long result = 0;
if (p >= 0)
result += acc[p];
result += (acc.size()-p) * w;
return result;
}
int main() {
int n;
cin >> n;
vector<long long> s(n);
for (auto& si : s)
cin >> si;
sort(s.begin(), s.end());
int q;
cin >> q;
vector<long long> w(q);
for (int i = 0; i < q; ++i) {
long long lk, rk;
cin >> lk >> rk;
w[i] = rk - lk + 1;
}
vector<long long> d(n-1);
for (int i = 0; i < n-1; ++i)
d[i] = s[i+1] - s[i];
sort(d.begin(), d.end());
vector<long long> acc(n-1);
if (n > 1)
acc[0] = d[0];
for (int i = 1; i < n-1; ++i)
acc[i] = acc[i-1] + d[i];
for (int i = 0; i < q; ++i)
cout << CountUnique(w[i], d, acc) << " ";
cout << endl;
}
| [
"[email protected]"
] | |
80aed4fa8131d6cb15b7bcb7166b61be6559a44b | f6d271233b8a91f63c30148cdcdb86341ba45c2f | /external/TriBITS/tribits/examples/TribitsExampleProject/packages/with_subpackages/b/tests/testlib/b_test_utils.hpp | c0436a413900f739a8cc26ca779849a9cafbdfd9 | [
"BSD-2-Clause",
"BSD-3-Clause",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-permissive",
"MIT"
] | permissive | wawiesel/BootsOnTheGround | 09e7884b9df9c1eb39a4a4f3d3f8f109960aeca0 | bdb63ae6f906c34f66e995973bf09aa6f2999148 | refs/heads/master | 2021-01-11T20:13:10.304516 | 2019-10-09T16:44:33 | 2019-10-09T16:44:33 | 79,069,796 | 4 | 1 | MIT | 2019-10-09T16:44:34 | 2017-01-16T00:47:11 | CMake | UTF-8 | C++ | false | false | 207 | hpp | #ifndef WITHSUBPACKAGES_B_TEST_UTILS_HPP
#define WITHSUBPACKAGES_B_TEST_UTILS_HPP
#include <string>
namespace WithSubpackages {
std::string b_test_utils();
}
#endif // WITHSUBPACKAGES_B_TEST_UTILS_HPP
| [
"[email protected]"
] | |
7d1ed56a00248f1c397d15636ff95441952686df | 5e007aa448d05ef39b1c7731a92be2075df09801 | /Test/UnitMovementFilterTest.cpp | 9fdfca8b118517d89a09377f4324f853f0847721 | [] | no_license | AlvaroChambi/ProjectAI | 04a881047a1a7feabdd4850b09318c676e1686f1 | b5a31d358d91a071ac857afb0c18ce25eb985687 | refs/heads/develop | 2020-04-03T23:31:43.567379 | 2016-09-19T10:03:14 | 2016-09-19T10:03:14 | 32,091,207 | 2 | 0 | null | 2016-09-12T19:40:59 | 2015-03-12T17:29:49 | C++ | UTF-8 | C++ | false | false | 472 | cpp | //
// UnitMovementFilterTest.cpp
// ProjectWar
//
// Created by Alvaro Chambi Campos on 8/6/16.
// Copyright © 2016 Alvaro Chambi Campos. All rights reserved.
//
#include "gtest/gtest.h"
#include "UnitFilter.h"
#include "MockIterator.h"
#include "MockMap.h"
class UnitMovementFilterTest : public ::testing::Test {
public:
UnitMovementFilterTest() {
}
virtual void SetUp() {
}
virtual void TearDown() {
}
}; | [
"[email protected]"
] | |
9ce36c4026a2d20e8227324a8836982c71f80491 | b8969f45075c86526010d7be0c3129b66baed94e | /Adder.h | 46cdc16eee0b693416fe1fe7db7941de783b85e8 | [] | no_license | Paracefas/interactor-model | 3d34f19ede203c7171cc6bfdfdcdf15689f86596 | d1a40320109cc31ab57c3be0ab1047db7d79af57 | refs/heads/master | 2020-08-07T11:56:42.299962 | 2019-10-11T02:11:24 | 2019-10-11T02:11:24 | 213,440,951 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 103 | h | #pragma once
class Adder
{
int m_count;
public:
Adder();
int Add(int);
int GetCount();
}; | [
"[email protected]"
] | |
c1f50da97d8be27015d66d945985365b2ca7418b | 93a113f11d064f099b96031c2eeafb76d41ac948 | /summer/7.25.1.cpp | 3449a474dc42ac0dddf792649bf63ad0bd1459d4 | [] | no_license | yyc794990923/Algorithm | 00905cc64351f8342059594adfa02e51714c070b | 9c31f315540c4797fdc4336cebc1361a3765cc8e | refs/heads/master | 2021-01-20T01:53:38.108368 | 2017-07-25T09:37:32 | 2017-07-25T09:37:32 | 89,342,048 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 614 | cpp | /*************************************************************************
> File Name: 7.25.1.cpp
> Author: yanyuchen
> Mail: [email protected]
> Created Time: 2017年07月25日 星期二 14时51分13秒
************************************************************************/
#include<iostream>
using namespace std;
int gcd(int a, int b)
{
return b==0?a:(gcd(b,a%b));
}
int main()
{
int time;
int a,b,c;
cin >> time;
while(time--) {
cin >> a >> b;
c = 2*b;
while (gcd(a,c) != b) {
c += b;
}
cout << c <<endl;
}
return 0;
}
| [
"[email protected]"
] | |
07893178797b2a59515d7cfbaa18d008397c6581 | e7ec698e7153e8580ad19136a44fd60acc147836 | /src/page/b_plus_tree_page.cpp | db886bbde517b60d69967bfff19498c6fb2f2329 | [
"MIT"
] | permissive | awfeequdng/DatabaseBackendEngine | f641532b14107eb217404a5d7f9b10401fb5aafd | 9cb22617a8de14ea6e6136614e6d91842aa06984 | refs/heads/master | 2021-09-24T11:02:39.031715 | 2018-10-07T01:23:03 | 2018-10-07T01:23:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,666 | cpp | /**
* b_plus_tree_page.cpp
*/
#include "page/b_plus_tree_page.h"
namespace cmudb {
/*
* Helper methods to get/set page type
* Page type enum class is defined in b_plus_tree_page.h
*/
bool BPlusTreePage::IsLeafPage() const {
return (page_type_ == IndexPageType::LEAF_PAGE);
}
bool BPlusTreePage::IsRootPage() const {
return (page_type_ == IndexPageType::INTERNAL_PAGE && parent_page_id_ == INVALID_PAGE_ID);
}
void BPlusTreePage::SetPageType(IndexPageType page_type) { page_type_ = page_type; }
/*
* Helper methods to get/set size (number of key/value pairs stored in that
* page)
*/
int BPlusTreePage::GetSize() const { return size_; }
void BPlusTreePage::SetSize(int size) { size_ = size; }
void BPlusTreePage::IncreaseSize(int amount) { size_+= amount; }
/*
* Helper methods to get/set max size (capacity) of the page
*/
int BPlusTreePage::GetMaxSize() const { return max_size_; }
void BPlusTreePage::SetMaxSize(int size) { max_size_ = size; }
/*
* Helper method to get min page size
* Generally, min page size == max page size / 2
*/
int BPlusTreePage::GetMinSize() const { return max_size_/2; }
/*
* Helper methods to get/set parent page id
*/
page_id_t BPlusTreePage::GetParentPageId() const { return parent_page_id_; }
void BPlusTreePage::SetParentPageId(page_id_t parent_page_id) {
parent_page_id_ = parent_page_id;
}
/*
* Helper methods to get/set self page id
*/
page_id_t BPlusTreePage::GetPageId() const { return page_id_; }
void BPlusTreePage::SetPageId(page_id_t page_id) {
page_id_ = page_id;
}
/*
* Helper methods to set lsn
*/
void BPlusTreePage::SetLSN(lsn_t lsn) { lsn_ = lsn; }
} // namespace cmudb
| [
"[email protected]"
] | |
7b23b562c585d1d8d9d460994be9f3ba9adaa8cf | 2b090d51eb8b0603a02a82f03c7f8bd1a3b90893 | /CCO/DMOJ Mock CCO/ccoprep3p2.cpp | 57cacd582dfe3c18d38ceb339b40cd5a5ac2b7d4 | [] | no_license | AnishMahto/Competitive-Programming-Code-and-Solutions | eecffc3a2c72cf557c48a25fa133a3a2b645cd69 | 20a7bed2cdda0efdb48b915fc4a68d6edc446f69 | refs/heads/master | 2020-04-28T14:13:25.614349 | 2019-03-13T03:07:50 | 2019-03-13T03:07:50 | 175,331,066 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,060 | cpp | #include <iostream>
#include <cstdio>
#include <deque>
#include <string.h>
using namespace std;
long long n, L, dp[3*1000002];
deque <long long> pts;
long long sum[3*1000002];
//(dp[x] + X^2, X)
double slope (long long f, long long s) {
return (double)((dp[f] + sum[f]*sum[f])-(dp[s] + sum[s]*sum[s]))/(double)(2*(sum[f]-sum[s]));
}
int main () {
memset(dp, sizeof(dp), 0);
memset(sum, sizeof(sum), 0);
long long temp, X;
scanf ("%lld %lld", &n, &L);
for (int x = 1; x <= n; x++) {
scanf ("%lld", &temp);
sum[x] = temp + sum[x-1] + 1;
}
sum[0] = dp[0] = 0;
L++;
pts.push_back(0);
for (int x = 1; x <= n; x++) {
while (pts.size() >= 2 && (slope(pts.front(), pts[1]) < (sum[x]-L))) {
pts.pop_front();
}
X = (sum[x]-sum[pts.front()]);
dp[x] = dp[pts.front()] + (X-L)*(X-L);
while (pts.size() >= 2) {
if (slope(x, pts.back()) < slope(pts.back(), pts[pts.size()-2])) {
pts.pop_back();
} else {
break;
}
}
pts.push_back(x);
}
cout << dp[n] << endl;
}
| [
"[email protected]"
] | |
a26d1be3547adc999df23c3bd4b5dec0f46538d3 | 1577e1cf4e89584a125cffb855ca50a9654c6d55 | /WebKit/Source/ThirdParty/ANGLE/src/libANGLE/angletypes.cpp | 95f9c9501b6b1442b71774e3ae98a5a3f6c51222 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | apple-open-source/macos | a4188b5c2ef113d90281d03cd1b14e5ee52ebffb | 2d2b15f13487673de33297e49f00ef94af743a9a | refs/heads/master | 2023-08-01T11:03:26.870408 | 2023-03-27T00:00:00 | 2023-03-27T00:00:00 | 180,595,052 | 124 | 24 | null | 2022-12-27T14:54:09 | 2019-04-10T14:06:23 | null | UTF-8 | C++ | false | false | 33,271 | cpp | //
// Copyright 2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// angletypes.h : Defines a variety of structures and enum types that are used throughout libGLESv2
#include "libANGLE/angletypes.h"
#include "libANGLE/Program.h"
#include "libANGLE/State.h"
#include "libANGLE/VertexArray.h"
#include "libANGLE/VertexAttribute.h"
#include <limits>
namespace gl
{
namespace
{
bool IsStencilNoOp(GLenum stencilFunc,
GLenum stencilFail,
GLenum stencilPassDepthFail,
GLenum stencilPassDepthPass)
{
const bool isNeverAndKeep = stencilFunc == GL_NEVER && stencilFail == GL_KEEP;
const bool isAlwaysAndKeepOrAllKeep = (stencilFunc == GL_ALWAYS || stencilFail == GL_KEEP) &&
stencilPassDepthFail == GL_KEEP &&
stencilPassDepthPass == GL_KEEP;
return isNeverAndKeep || isAlwaysAndKeepOrAllKeep;
}
// Calculate whether the range [outsideLow, outsideHigh] encloses the range [insideLow, insideHigh]
bool EnclosesRange(int outsideLow, int outsideHigh, int insideLow, int insideHigh)
{
return outsideLow <= insideLow && outsideHigh >= insideHigh;
}
bool IsAdvancedBlendEquation(gl::BlendEquationType blendEquation)
{
return blendEquation >= gl::BlendEquationType::Multiply &&
blendEquation <= gl::BlendEquationType::HslLuminosity;
}
} // anonymous namespace
RasterizerState::RasterizerState()
{
memset(this, 0, sizeof(RasterizerState));
rasterizerDiscard = false;
cullFace = false;
cullMode = CullFaceMode::Back;
frontFace = GL_CCW;
polygonOffsetFill = false;
polygonOffsetFactor = 0.0f;
polygonOffsetUnits = 0.0f;
polygonOffsetClamp = 0.0f;
pointDrawMode = false;
multiSample = false;
dither = true;
}
RasterizerState::RasterizerState(const RasterizerState &other)
{
memcpy(this, &other, sizeof(RasterizerState));
}
RasterizerState &RasterizerState::operator=(const RasterizerState &other)
{
memcpy(this, &other, sizeof(RasterizerState));
return *this;
}
bool operator==(const RasterizerState &a, const RasterizerState &b)
{
return memcmp(&a, &b, sizeof(RasterizerState)) == 0;
}
bool operator!=(const RasterizerState &a, const RasterizerState &b)
{
return !(a == b);
}
BlendState::BlendState()
{
memset(this, 0, sizeof(BlendState));
blend = false;
sourceBlendRGB = GL_ONE;
sourceBlendAlpha = GL_ONE;
destBlendRGB = GL_ZERO;
destBlendAlpha = GL_ZERO;
blendEquationRGB = GL_FUNC_ADD;
blendEquationAlpha = GL_FUNC_ADD;
colorMaskRed = true;
colorMaskGreen = true;
colorMaskBlue = true;
colorMaskAlpha = true;
}
BlendState::BlendState(const BlendState &other)
{
memcpy(this, &other, sizeof(BlendState));
}
bool operator==(const BlendState &a, const BlendState &b)
{
return memcmp(&a, &b, sizeof(BlendState)) == 0;
}
bool operator!=(const BlendState &a, const BlendState &b)
{
return !(a == b);
}
DepthStencilState::DepthStencilState()
{
memset(this, 0, sizeof(DepthStencilState));
depthTest = false;
depthFunc = GL_LESS;
depthMask = true;
stencilTest = false;
stencilFunc = GL_ALWAYS;
stencilMask = static_cast<GLuint>(-1);
stencilWritemask = static_cast<GLuint>(-1);
stencilBackFunc = GL_ALWAYS;
stencilBackMask = static_cast<GLuint>(-1);
stencilBackWritemask = static_cast<GLuint>(-1);
stencilFail = GL_KEEP;
stencilPassDepthFail = GL_KEEP;
stencilPassDepthPass = GL_KEEP;
stencilBackFail = GL_KEEP;
stencilBackPassDepthFail = GL_KEEP;
stencilBackPassDepthPass = GL_KEEP;
}
DepthStencilState::DepthStencilState(const DepthStencilState &other)
{
memcpy(this, &other, sizeof(DepthStencilState));
}
DepthStencilState &DepthStencilState::operator=(const DepthStencilState &other)
{
memcpy(this, &other, sizeof(DepthStencilState));
return *this;
}
bool DepthStencilState::isDepthMaskedOut() const
{
return !depthMask;
}
bool DepthStencilState::isStencilMaskedOut() const
{
return (stencilMask & stencilWritemask) == 0;
}
bool DepthStencilState::isStencilNoOp() const
{
return isStencilMaskedOut() ||
IsStencilNoOp(stencilFunc, stencilFail, stencilPassDepthFail, stencilPassDepthPass);
}
bool DepthStencilState::isStencilBackNoOp() const
{
const bool isStencilBackMaskedOut = (stencilBackMask & stencilBackWritemask) == 0;
return isStencilBackMaskedOut ||
IsStencilNoOp(stencilBackFunc, stencilBackFail, stencilBackPassDepthFail,
stencilBackPassDepthPass);
}
bool operator==(const DepthStencilState &a, const DepthStencilState &b)
{
return memcmp(&a, &b, sizeof(DepthStencilState)) == 0;
}
bool operator!=(const DepthStencilState &a, const DepthStencilState &b)
{
return !(a == b);
}
SamplerState::SamplerState()
{
memset(this, 0, sizeof(SamplerState));
setMinFilter(GL_NEAREST_MIPMAP_LINEAR);
setMagFilter(GL_LINEAR);
setWrapS(GL_REPEAT);
setWrapT(GL_REPEAT);
setWrapR(GL_REPEAT);
setMaxAnisotropy(1.0f);
setMinLod(-1000.0f);
setMaxLod(1000.0f);
setCompareMode(GL_NONE);
setCompareFunc(GL_LEQUAL);
setSRGBDecode(GL_DECODE_EXT);
}
SamplerState::SamplerState(const SamplerState &other) = default;
SamplerState &SamplerState::operator=(const SamplerState &other) = default;
// static
SamplerState SamplerState::CreateDefaultForTarget(TextureType type)
{
SamplerState state;
// According to OES_EGL_image_external and ARB_texture_rectangle: For external textures, the
// default min filter is GL_LINEAR and the default s and t wrap modes are GL_CLAMP_TO_EDGE.
if (type == TextureType::External || type == TextureType::Rectangle)
{
state.mMinFilter = GL_LINEAR;
state.mWrapS = GL_CLAMP_TO_EDGE;
state.mWrapT = GL_CLAMP_TO_EDGE;
}
return state;
}
bool SamplerState::setMinFilter(GLenum minFilter)
{
if (mMinFilter != minFilter)
{
mMinFilter = minFilter;
mCompleteness.typed.minFilter = static_cast<uint8_t>(FromGLenum<FilterMode>(minFilter));
return true;
}
return false;
}
bool SamplerState::setMagFilter(GLenum magFilter)
{
if (mMagFilter != magFilter)
{
mMagFilter = magFilter;
mCompleteness.typed.magFilter = static_cast<uint8_t>(FromGLenum<FilterMode>(magFilter));
return true;
}
return false;
}
bool SamplerState::setWrapS(GLenum wrapS)
{
if (mWrapS != wrapS)
{
mWrapS = wrapS;
mCompleteness.typed.wrapS = static_cast<uint8_t>(FromGLenum<WrapMode>(wrapS));
return true;
}
return false;
}
bool SamplerState::setWrapT(GLenum wrapT)
{
if (mWrapT != wrapT)
{
mWrapT = wrapT;
updateWrapTCompareMode();
return true;
}
return false;
}
bool SamplerState::setWrapR(GLenum wrapR)
{
if (mWrapR != wrapR)
{
mWrapR = wrapR;
return true;
}
return false;
}
bool SamplerState::setMaxAnisotropy(float maxAnisotropy)
{
if (mMaxAnisotropy != maxAnisotropy)
{
mMaxAnisotropy = maxAnisotropy;
return true;
}
return false;
}
bool SamplerState::setMinLod(GLfloat minLod)
{
if (mMinLod != minLod)
{
mMinLod = minLod;
return true;
}
return false;
}
bool SamplerState::setMaxLod(GLfloat maxLod)
{
if (mMaxLod != maxLod)
{
mMaxLod = maxLod;
return true;
}
return false;
}
bool SamplerState::setCompareMode(GLenum compareMode)
{
if (mCompareMode != compareMode)
{
mCompareMode = compareMode;
updateWrapTCompareMode();
return true;
}
return false;
}
bool SamplerState::setCompareFunc(GLenum compareFunc)
{
if (mCompareFunc != compareFunc)
{
mCompareFunc = compareFunc;
return true;
}
return false;
}
bool SamplerState::setSRGBDecode(GLenum sRGBDecode)
{
if (mSRGBDecode != sRGBDecode)
{
mSRGBDecode = sRGBDecode;
return true;
}
return false;
}
bool SamplerState::setBorderColor(const ColorGeneric &color)
{
if (mBorderColor != color)
{
mBorderColor = color;
return true;
}
return false;
}
void SamplerState::updateWrapTCompareMode()
{
uint8_t wrap = static_cast<uint8_t>(FromGLenum<WrapMode>(mWrapT));
uint8_t compare = static_cast<uint8_t>(mCompareMode == GL_NONE ? 0x10 : 0x00);
mCompleteness.typed.wrapTCompareMode = wrap | compare;
}
ImageUnit::ImageUnit()
: texture(), level(0), layered(false), layer(0), access(GL_READ_ONLY), format(GL_R32UI)
{}
ImageUnit::ImageUnit(const ImageUnit &other) = default;
ImageUnit::~ImageUnit() = default;
BlendStateExt::BlendStateExt(const size_t drawBufferCount)
: mParameterMask(FactorStorage::GetMask(drawBufferCount)),
mSrcColor(FactorStorage::GetReplicatedValue(BlendFactorType::One, mParameterMask)),
mDstColor(FactorStorage::GetReplicatedValue(BlendFactorType::Zero, mParameterMask)),
mSrcAlpha(FactorStorage::GetReplicatedValue(BlendFactorType::One, mParameterMask)),
mDstAlpha(FactorStorage::GetReplicatedValue(BlendFactorType::Zero, mParameterMask)),
mEquationColor(EquationStorage::GetReplicatedValue(BlendEquationType::Add, mParameterMask)),
mEquationAlpha(EquationStorage::GetReplicatedValue(BlendEquationType::Add, mParameterMask)),
mAllColorMask(
ColorMaskStorage::GetReplicatedValue(PackColorMask(true, true, true, true),
ColorMaskStorage::GetMask(drawBufferCount))),
mColorMask(mAllColorMask),
mAllEnabledMask(0xFF >> (8 - drawBufferCount)),
mDrawBufferCount(drawBufferCount)
{}
BlendStateExt::BlendStateExt(const BlendStateExt &other) = default;
BlendStateExt &BlendStateExt::operator=(const BlendStateExt &other) = default;
void BlendStateExt::setEnabled(const bool enabled)
{
mEnabledMask = enabled ? mAllEnabledMask : DrawBufferMask::Zero();
}
void BlendStateExt::setEnabledIndexed(const size_t index, const bool enabled)
{
ASSERT(index < mDrawBufferCount);
mEnabledMask.set(index, enabled);
}
BlendStateExt::ColorMaskStorage::Type BlendStateExt::expandColorMaskValue(const bool red,
const bool green,
const bool blue,
const bool alpha) const
{
return BlendStateExt::ColorMaskStorage::GetReplicatedValue(
PackColorMask(red, green, blue, alpha), mAllColorMask);
}
BlendStateExt::ColorMaskStorage::Type BlendStateExt::expandColorMaskIndexed(
const size_t index) const
{
return ColorMaskStorage::GetReplicatedValue(
ColorMaskStorage::GetValueIndexed(index, mColorMask), mAllColorMask);
}
void BlendStateExt::setColorMask(const bool red,
const bool green,
const bool blue,
const bool alpha)
{
mColorMask = expandColorMaskValue(red, green, blue, alpha);
}
void BlendStateExt::setColorMaskIndexed(const size_t index, const uint8_t value)
{
ASSERT(index < mDrawBufferCount);
ASSERT(value <= 0xF);
ColorMaskStorage::SetValueIndexed(index, value, &mColorMask);
}
void BlendStateExt::setColorMaskIndexed(const size_t index,
const bool red,
const bool green,
const bool blue,
const bool alpha)
{
ASSERT(index < mDrawBufferCount);
ColorMaskStorage::SetValueIndexed(index, PackColorMask(red, green, blue, alpha), &mColorMask);
}
uint8_t BlendStateExt::getColorMaskIndexed(const size_t index) const
{
ASSERT(index < mDrawBufferCount);
return ColorMaskStorage::GetValueIndexed(index, mColorMask);
}
void BlendStateExt::getColorMaskIndexed(const size_t index,
bool *red,
bool *green,
bool *blue,
bool *alpha) const
{
ASSERT(index < mDrawBufferCount);
UnpackColorMask(ColorMaskStorage::GetValueIndexed(index, mColorMask), red, green, blue, alpha);
}
DrawBufferMask BlendStateExt::compareColorMask(ColorMaskStorage::Type other) const
{
return ColorMaskStorage::GetDiffMask(mColorMask, other);
}
BlendStateExt::EquationStorage::Type BlendStateExt::expandEquationValue(const GLenum mode) const
{
return EquationStorage::GetReplicatedValue(FromGLenum<BlendEquationType>(mode), mParameterMask);
}
BlendStateExt::EquationStorage::Type BlendStateExt::expandEquationValue(
const gl::BlendEquationType equation) const
{
return EquationStorage::GetReplicatedValue(equation, mParameterMask);
}
BlendStateExt::EquationStorage::Type BlendStateExt::expandEquationColorIndexed(
const size_t index) const
{
return EquationStorage::GetReplicatedValue(
EquationStorage::GetValueIndexed(index, mEquationColor), mParameterMask);
}
BlendStateExt::EquationStorage::Type BlendStateExt::expandEquationAlphaIndexed(
const size_t index) const
{
return EquationStorage::GetReplicatedValue(
EquationStorage::GetValueIndexed(index, mEquationAlpha), mParameterMask);
}
void BlendStateExt::setEquations(const GLenum modeColor, const GLenum modeAlpha)
{
const gl::BlendEquationType colorEquation = FromGLenum<BlendEquationType>(modeColor);
const gl::BlendEquationType alphaEquation = FromGLenum<BlendEquationType>(modeAlpha);
mEquationColor = expandEquationValue(colorEquation);
mEquationAlpha = expandEquationValue(alphaEquation);
// Note that advanced blend equations cannot be independently set for color and alpha, so only
// the color equation can be checked.
if (IsAdvancedBlendEquation(colorEquation))
{
mUsesAdvancedBlendEquationMask = mAllEnabledMask;
}
else
{
mUsesAdvancedBlendEquationMask.reset();
}
}
void BlendStateExt::setEquationsIndexed(const size_t index,
const GLenum modeColor,
const GLenum modeAlpha)
{
ASSERT(index < mDrawBufferCount);
const gl::BlendEquationType colorEquation = FromGLenum<BlendEquationType>(modeColor);
const gl::BlendEquationType alphaEquation = FromGLenum<BlendEquationType>(modeAlpha);
EquationStorage::SetValueIndexed(index, colorEquation, &mEquationColor);
EquationStorage::SetValueIndexed(index, alphaEquation, &mEquationAlpha);
mUsesAdvancedBlendEquationMask.set(index, IsAdvancedBlendEquation(colorEquation));
}
void BlendStateExt::setEquationsIndexed(const size_t index,
const size_t sourceIndex,
const BlendStateExt &source)
{
ASSERT(index < mDrawBufferCount);
ASSERT(sourceIndex < source.mDrawBufferCount);
const gl::BlendEquationType colorEquation =
EquationStorage::GetValueIndexed(sourceIndex, source.mEquationColor);
const gl::BlendEquationType alphaEquation =
EquationStorage::GetValueIndexed(sourceIndex, source.mEquationAlpha);
EquationStorage::SetValueIndexed(index, colorEquation, &mEquationColor);
EquationStorage::SetValueIndexed(index, alphaEquation, &mEquationAlpha);
mUsesAdvancedBlendEquationMask.set(index, IsAdvancedBlendEquation(colorEquation));
}
GLenum BlendStateExt::getEquationColorIndexed(size_t index) const
{
ASSERT(index < mDrawBufferCount);
return ToGLenum(EquationStorage::GetValueIndexed(index, mEquationColor));
}
GLenum BlendStateExt::getEquationAlphaIndexed(size_t index) const
{
ASSERT(index < mDrawBufferCount);
return ToGLenum(EquationStorage::GetValueIndexed(index, mEquationAlpha));
}
DrawBufferMask BlendStateExt::compareEquations(const EquationStorage::Type color,
const EquationStorage::Type alpha) const
{
return EquationStorage::GetDiffMask(mEquationColor, color) |
EquationStorage::GetDiffMask(mEquationAlpha, alpha);
}
BlendStateExt::FactorStorage::Type BlendStateExt::expandFactorValue(const GLenum func) const
{
return FactorStorage::GetReplicatedValue(FromGLenum<BlendFactorType>(func), mParameterMask);
}
BlendStateExt::FactorStorage::Type BlendStateExt::expandSrcColorIndexed(const size_t index) const
{
ASSERT(index < mDrawBufferCount);
return FactorStorage::GetReplicatedValue(FactorStorage::GetValueIndexed(index, mSrcColor),
mParameterMask);
}
BlendStateExt::FactorStorage::Type BlendStateExt::expandDstColorIndexed(const size_t index) const
{
ASSERT(index < mDrawBufferCount);
return FactorStorage::GetReplicatedValue(FactorStorage::GetValueIndexed(index, mDstColor),
mParameterMask);
}
BlendStateExt::FactorStorage::Type BlendStateExt::expandSrcAlphaIndexed(const size_t index) const
{
ASSERT(index < mDrawBufferCount);
return FactorStorage::GetReplicatedValue(FactorStorage::GetValueIndexed(index, mSrcAlpha),
mParameterMask);
}
BlendStateExt::FactorStorage::Type BlendStateExt::expandDstAlphaIndexed(const size_t index) const
{
ASSERT(index < mDrawBufferCount);
return FactorStorage::GetReplicatedValue(FactorStorage::GetValueIndexed(index, mDstAlpha),
mParameterMask);
}
void BlendStateExt::setFactors(const GLenum srcColor,
const GLenum dstColor,
const GLenum srcAlpha,
const GLenum dstAlpha)
{
mSrcColor = expandFactorValue(srcColor);
mDstColor = expandFactorValue(dstColor);
mSrcAlpha = expandFactorValue(srcAlpha);
mDstAlpha = expandFactorValue(dstAlpha);
}
void BlendStateExt::setFactorsIndexed(const size_t index,
const GLenum srcColor,
const GLenum dstColor,
const GLenum srcAlpha,
const GLenum dstAlpha)
{
ASSERT(index < mDrawBufferCount);
FactorStorage::SetValueIndexed(index, FromGLenum<BlendFactorType>(srcColor), &mSrcColor);
FactorStorage::SetValueIndexed(index, FromGLenum<BlendFactorType>(dstColor), &mDstColor);
FactorStorage::SetValueIndexed(index, FromGLenum<BlendFactorType>(srcAlpha), &mSrcAlpha);
FactorStorage::SetValueIndexed(index, FromGLenum<BlendFactorType>(dstAlpha), &mDstAlpha);
}
void BlendStateExt::setFactorsIndexed(const size_t index,
const size_t sourceIndex,
const BlendStateExt &source)
{
ASSERT(index < mDrawBufferCount);
ASSERT(sourceIndex < source.mDrawBufferCount);
FactorStorage::SetValueIndexed(
index, FactorStorage::GetValueIndexed(sourceIndex, source.mSrcColor), &mSrcColor);
FactorStorage::SetValueIndexed(
index, FactorStorage::GetValueIndexed(sourceIndex, source.mDstColor), &mDstColor);
FactorStorage::SetValueIndexed(
index, FactorStorage::GetValueIndexed(sourceIndex, source.mSrcAlpha), &mSrcAlpha);
FactorStorage::SetValueIndexed(
index, FactorStorage::GetValueIndexed(sourceIndex, source.mDstAlpha), &mDstAlpha);
}
GLenum BlendStateExt::getSrcColorIndexed(size_t index) const
{
ASSERT(index < mDrawBufferCount);
return ToGLenum(FactorStorage::GetValueIndexed(index, mSrcColor));
}
GLenum BlendStateExt::getDstColorIndexed(size_t index) const
{
ASSERT(index < mDrawBufferCount);
return ToGLenum(FactorStorage::GetValueIndexed(index, mDstColor));
}
GLenum BlendStateExt::getSrcAlphaIndexed(size_t index) const
{
ASSERT(index < mDrawBufferCount);
return ToGLenum(FactorStorage::GetValueIndexed(index, mSrcAlpha));
}
GLenum BlendStateExt::getDstAlphaIndexed(size_t index) const
{
ASSERT(index < mDrawBufferCount);
return ToGLenum(FactorStorage::GetValueIndexed(index, mDstAlpha));
}
DrawBufferMask BlendStateExt::compareFactors(const FactorStorage::Type srcColor,
const FactorStorage::Type dstColor,
const FactorStorage::Type srcAlpha,
const FactorStorage::Type dstAlpha) const
{
return FactorStorage::GetDiffMask(mSrcColor, srcColor) |
FactorStorage::GetDiffMask(mDstColor, dstColor) |
FactorStorage::GetDiffMask(mSrcAlpha, srcAlpha) |
FactorStorage::GetDiffMask(mDstAlpha, dstAlpha);
}
static void MinMax(int a, int b, int *minimum, int *maximum)
{
if (a < b)
{
*minimum = a;
*maximum = b;
}
else
{
*minimum = b;
*maximum = a;
}
}
template <>
bool RectangleImpl<int>::empty() const
{
return width == 0 && height == 0;
}
template <>
bool RectangleImpl<float>::empty() const
{
return std::abs(width) < std::numeric_limits<float>::epsilon() &&
std::abs(height) < std::numeric_limits<float>::epsilon();
}
bool ClipRectangle(const Rectangle &source, const Rectangle &clip, Rectangle *intersection)
{
angle::CheckedNumeric<int> sourceX2(source.x);
sourceX2 += source.width;
if (!sourceX2.IsValid())
{
return false;
}
angle::CheckedNumeric<int> sourceY2(source.y);
sourceY2 += source.height;
if (!sourceY2.IsValid())
{
return false;
}
int minSourceX, maxSourceX, minSourceY, maxSourceY;
MinMax(source.x, sourceX2.ValueOrDie(), &minSourceX, &maxSourceX);
MinMax(source.y, sourceY2.ValueOrDie(), &minSourceY, &maxSourceY);
angle::CheckedNumeric<int> clipX2(clip.x);
clipX2 += clip.width;
if (!clipX2.IsValid())
{
return false;
}
angle::CheckedNumeric<int> clipY2(clip.y);
clipY2 += clip.height;
if (!clipY2.IsValid())
{
return false;
}
int minClipX, maxClipX, minClipY, maxClipY;
MinMax(clip.x, clipX2.ValueOrDie(), &minClipX, &maxClipX);
MinMax(clip.y, clipY2.ValueOrDie(), &minClipY, &maxClipY);
if (minSourceX >= maxClipX || maxSourceX <= minClipX || minSourceY >= maxClipY ||
maxSourceY <= minClipY)
{
return false;
}
int x = std::max(minSourceX, minClipX);
int y = std::max(minSourceY, minClipY);
int width = std::min(maxSourceX, maxClipX) - x;
int height = std::min(maxSourceY, maxClipY) - y;
if (intersection)
{
intersection->x = x;
intersection->y = y;
intersection->width = width;
intersection->height = height;
}
return width != 0 && height != 0;
}
void GetEnclosingRectangle(const Rectangle &rect1, const Rectangle &rect2, Rectangle *rectUnion)
{
// All callers use non-flipped framebuffer-size-clipped rectangles, so both flip and overflow
// are impossible.
ASSERT(!rect1.isReversedX() && !rect1.isReversedY());
ASSERT(!rect2.isReversedX() && !rect2.isReversedY());
ASSERT((angle::CheckedNumeric<int>(rect1.x) + rect1.width).IsValid());
ASSERT((angle::CheckedNumeric<int>(rect1.y) + rect1.height).IsValid());
ASSERT((angle::CheckedNumeric<int>(rect2.x) + rect2.width).IsValid());
ASSERT((angle::CheckedNumeric<int>(rect2.y) + rect2.height).IsValid());
// This function calculates a rectangle that covers both input rectangles:
//
// +---------+
// rect1 --> | |
// | +---+-----+
// | | | | <-- rect2
// +-----+---+ |
// | |
// +---------+
//
// xy0 = min(rect1.xy0, rect2.xy0)
// \
// +---------+-----+
// union --> | . |
// | + . + . . +
// | . . |
// + . . + . + |
// | . |
// +-----+---------+
// /
// xy1 = max(rect1.xy1, rect2.xy1)
int x0 = std::min(rect1.x0(), rect2.x0());
int y0 = std::min(rect1.y0(), rect2.y0());
int x1 = std::max(rect1.x1(), rect2.x1());
int y1 = std::max(rect1.y1(), rect2.y1());
rectUnion->x = x0;
rectUnion->y = y0;
rectUnion->width = x1 - x0;
rectUnion->height = y1 - y0;
}
void ExtendRectangle(const Rectangle &source, const Rectangle &extend, Rectangle *extended)
{
// All callers use non-flipped framebuffer-size-clipped rectangles, so both flip and overflow
// are impossible.
ASSERT(!source.isReversedX() && !source.isReversedY());
ASSERT(!extend.isReversedX() && !extend.isReversedY());
ASSERT((angle::CheckedNumeric<int>(source.x) + source.width).IsValid());
ASSERT((angle::CheckedNumeric<int>(source.y) + source.height).IsValid());
ASSERT((angle::CheckedNumeric<int>(extend.x) + extend.width).IsValid());
ASSERT((angle::CheckedNumeric<int>(extend.y) + extend.height).IsValid());
int x0 = source.x0();
int x1 = source.x1();
int y0 = source.y0();
int y1 = source.y1();
const int extendX0 = extend.x0();
const int extendX1 = extend.x1();
const int extendY0 = extend.y0();
const int extendY1 = extend.y1();
// For each side of the rectangle, calculate whether it can be extended by the second rectangle.
// If so, extend it and continue for the next side with the new dimensions.
// Left: Reduce x0 if the second rectangle's vertical edge covers the source's:
//
// +--- - - - +--- - - -
// | |
// | +--------------+ +-----------------+
// | | source | --> | source |
// | +--------------+ +-----------------+
// | |
// +--- - - - +--- - - -
//
const bool enclosesHeight = EnclosesRange(extendY0, extendY1, y0, y1);
if (extendX0 < x0 && extendX1 >= x0 && enclosesHeight)
{
x0 = extendX0;
}
// Right: Increase x1 simiarly.
if (extendX0 <= x1 && extendX1 > x1 && enclosesHeight)
{
x1 = extendX1;
}
// Top: Reduce y0 if the second rectangle's horizontal edge covers the source's potentially
// extended edge.
const bool enclosesWidth = EnclosesRange(extendX0, extendX1, x0, x1);
if (extendY0 < y0 && extendY1 >= y0 && enclosesWidth)
{
y0 = extendY0;
}
// Right: Increase y1 simiarly.
if (extendY0 <= y1 && extendY1 > y1 && enclosesWidth)
{
y1 = extendY1;
}
extended->x = x0;
extended->y = y0;
extended->width = x1 - x0;
extended->height = y1 - y0;
}
bool Box::valid() const
{
return width != 0 && height != 0 && depth != 0;
}
bool Box::operator==(const Box &other) const
{
return (x == other.x && y == other.y && z == other.z && width == other.width &&
height == other.height && depth == other.depth);
}
bool Box::operator!=(const Box &other) const
{
return !(*this == other);
}
Rectangle Box::toRect() const
{
ASSERT(z == 0 && depth == 1);
return Rectangle(x, y, width, height);
}
bool Box::coversSameExtent(const Extents &size) const
{
return x == 0 && y == 0 && z == 0 && width == size.width && height == size.height &&
depth == size.depth;
}
bool Box::contains(const Box &other) const
{
return x <= other.x && y <= other.y && z <= other.z && x + width >= other.x + other.width &&
y + height >= other.y + other.height && z + depth >= other.z + other.depth;
}
size_t Box::volume() const
{
return width * height * depth;
}
void Box::extend(const Box &other)
{
// This extends the logic of "ExtendRectangle" to 3 dimensions
int x0 = x;
int x1 = x + width;
int y0 = y;
int y1 = y + height;
int z0 = z;
int z1 = z + depth;
const int otherx0 = other.x;
const int otherx1 = other.x + other.width;
const int othery0 = other.y;
const int othery1 = other.y + other.height;
const int otherz0 = other.z;
const int otherz1 = other.z + other.depth;
// For each side of the box, calculate whether it can be extended by the other box.
// If so, extend it and continue to the next side with the new dimensions.
const bool enclosesWidth = EnclosesRange(otherx0, otherx1, x0, x1);
const bool enclosesHeight = EnclosesRange(othery0, othery1, y0, y1);
const bool enclosesDepth = EnclosesRange(otherz0, otherz1, z0, z1);
// Left: Reduce x0 if the other box's Y and Z plane encloses the source
if (otherx0 < x0 && otherx1 >= x0 && enclosesHeight && enclosesDepth)
{
x0 = otherx0;
}
// Right: Increase x1 simiarly.
if (otherx0 <= x1 && otherx1 > x1 && enclosesHeight && enclosesDepth)
{
x1 = otherx1;
}
// Bottom: Reduce y0 if the other box's X and Z plane encloses the source
if (othery0 < y0 && othery1 >= y0 && enclosesWidth && enclosesDepth)
{
y0 = othery0;
}
// Top: Increase y1 simiarly.
if (othery0 <= y1 && othery1 > y1 && enclosesWidth && enclosesDepth)
{
y1 = othery1;
}
// Front: Reduce z0 if the other box's X and Y plane encloses the source
if (otherz0 < z0 && otherz1 >= z0 && enclosesWidth && enclosesHeight)
{
z0 = otherz0;
}
// Back: Increase z1 simiarly.
if (otherz0 <= z1 && otherz1 > z1 && enclosesWidth && enclosesHeight)
{
z1 = otherz1;
}
// Update member var with new dimensions
x = x0;
width = x1 - x0;
y = y0;
height = y1 - y0;
z = z0;
depth = z1 - z0;
}
bool operator==(const Offset &a, const Offset &b)
{
return a.x == b.x && a.y == b.y && a.z == b.z;
}
bool operator!=(const Offset &a, const Offset &b)
{
return !(a == b);
}
bool operator==(const Extents &lhs, const Extents &rhs)
{
return lhs.width == rhs.width && lhs.height == rhs.height && lhs.depth == rhs.depth;
}
bool operator!=(const Extents &lhs, const Extents &rhs)
{
return !(lhs == rhs);
}
bool ValidateComponentTypeMasks(unsigned long outputTypes,
unsigned long inputTypes,
unsigned long outputMask,
unsigned long inputMask)
{
static_assert(IMPLEMENTATION_MAX_DRAW_BUFFERS <= kMaxComponentTypeMaskIndex,
"Output/input masks should fit into 16 bits - 1 bit per draw buffer. The "
"corresponding type masks should fit into 32 bits - 2 bits per draw buffer.");
static_assert(MAX_VERTEX_ATTRIBS <= kMaxComponentTypeMaskIndex,
"Output/input masks should fit into 16 bits - 1 bit per attrib. The "
"corresponding type masks should fit into 32 bits - 2 bits per attrib.");
// For performance reasons, draw buffer and attribute type validation is done using bit masks.
// We store two bits representing the type split, with the low bit in the lower 16 bits of the
// variable, and the high bit in the upper 16 bits of the variable. This is done so we can AND
// with the elswewhere used DrawBufferMask or AttributeMask.
// OR the masks with themselves, shifted 16 bits. This is to match our split type bits.
outputMask |= (outputMask << kMaxComponentTypeMaskIndex);
inputMask |= (inputMask << kMaxComponentTypeMaskIndex);
// To validate:
// 1. Remove any indexes that are not enabled in the input (& inputMask)
// 2. Remove any indexes that exist in output, but not in input (& outputMask)
// 3. Use == to verify equality
return (outputTypes & inputMask) == ((inputTypes & outputMask) & inputMask);
}
GLsizeiptr GetBoundBufferAvailableSize(const OffsetBindingPointer<Buffer> &binding)
{
Buffer *buffer = binding.get();
if (buffer == nullptr)
{
return 0;
}
const GLsizeiptr bufferSize = static_cast<GLsizeiptr>(buffer->getSize());
if (binding.getSize() == 0)
{
return bufferSize;
}
const GLintptr offset = binding.getOffset();
const GLsizeiptr size = binding.getSize();
ASSERT(offset >= 0 && bufferSize >= 0);
if (bufferSize <= offset)
{
return 0;
}
return std::min(size, bufferSize - offset);
}
} // namespace gl
| [
"[email protected]"
] | |
cfd4f195c055c29162163abc6e6bb92bcea227f6 | 789c924def388fb760985f5e39c2464385dac00c | /truss/main.cpp | 7921d2c8b2244194adaacbae27814f546b287cdb | [] | no_license | iicalgorithms/Truss-decomposition | a2e3bf0f883643c2c5cd84c8d6f912f777672491 | fe70fcb1ee5194e8e45b41190778a235178dcb53 | refs/heads/master | 2022-02-23T09:07:41.072301 | 2019-10-12T09:50:05 | 2019-10-12T09:50:05 | 189,707,340 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,971 | cpp | #include "Graph.h"
#include <map>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <string.h>
#include <sstream>
#include <stdlib.h>
#include <time.h>
#include <cmath>
#include <vector>
#include <map>
#define random(x) rand()%x;
using namespace std;
int seed = 100;
Graph G;
int node_num ,edge_num ;//边数,点数
string temp;//文件输出临时存储字符串
//在进行随机插入or删除的时候,需要进行抽样
int changeNum;//抽样数目
map<int,int > rdm; //用于随机抽样,map去重
vector<int > shhuffle_rdm;//用于随机抽样,进行shuffle随机排列
vector<int> v;//保存抽样出的数据的下标
vector<int > stId;//要插入/删除边的起点
vector<int > edId;//要插入/删除边的终点
set<pair<int,int> > clearSet;
set<int > clearNodeSet;
char * filename ;//文件路径
int method = -1;//求解方法 0-贪心 1-分布式
int graphType = -1;//图类型:0-static graph 1-temporal graph
int computeType = -1;//0-不插入不删除 1-插入:逐条初始化并分布式计算 2-插入:批次插入初始化并分布式计算 3-插入:批次插入,初始化为Sup+2并分布式计算 4-删除:批次删除并分布式计算 5-删除:初始化min{sup+2,truss(e)}并分布式计算
int number = -1; //插入/删除 数量级
char write; //'w'-将truss值写入"output.txt"文件
int Pow(int k){
int res = 1;
while(k--) res=res*10;
return res;
}
string getName(char *filename){
int len = strlen(filename);
int st=-1,ed = -1;
int fg1 = 0,fg2 = 0;
for(int i = len-1;i>=0;i--){
if(filename[i]=='.'&&!fg1) {
fg1 = 1;
ed = i-1;
}
if((filename[i]=='/'||filename[i]=='\\')&&!fg2) {
fg2 = 1;
st = i+1;
}
}
if(st == -1) st = 0;
string res = "";
for(int i = st;i<=ed;i++) res += filename[i];
return res;
}
int main(int argc,char * argv[]){
//strcat(filename,argv[1]);
filename = argv[1];
method = argv[2][0] - '0';
graphType = argv[3][0] - '0';
computeType = argv[4][0] - '0';
number = argv[5][0] - '0';
write = argv[6][0];
seed = atoi(argv[7]);
G.recoard(filename,method,graphType,computeType,number);
ifstream in(filename);
if(!in.is_open()) cout<<"fail to open file!\n"<<endl;
if(argv[2][0] == '2'|| argv[2][0] == '3'){//概率图
getline(in,temp);
istringstream strs(temp);
int node_num;
int node;
strs>>node_num>>node;
G.buildGraph(0,node_num);
}
//读入文件头,确定点数和边数,建图
while(getline(in,temp)){
istringstream str(temp);
if(temp[0] == '#'){
if(temp[2]=='N'&&temp[3]=='o'&&temp[4]=='d'){
string t1,t2,t3;
str>>t1>>t2>>node_num>>t3>>edge_num;
//cout<<temp<<endl;
//cout<<t1<<" "<<t2<<" "<<node_num<<" "<<t3<<" "<<edge_num<<" ss"<<endl;
}else continue;
}else break;
}
do{
istringstream str(temp);
if(temp[0] != '#'){
int st,ed;
str>>st>>ed;
int a = min(st,ed);
int b = max(st,ed);
clearSet.insert(make_pair(a,b));
clearNodeSet.insert(a);
clearNodeSet.insert(b);
//cout<<a<<" "<<b<<" "<<clearSet.size()<<endl;
}
}while(getline(in,temp));
edge_num = clearSet.size();
G.buildGraph(edge_num,node_num);
changeNum = number;
changeNum = Pow(changeNum);
int RandomUpBound = 0;
if(graphType == 3) RandomUpBound = node_num;
else RandomUpBound = edge_num;
srand(seed);
if(graphType == 0 || graphType == 3){
for(int i=0;i<RandomUpBound;i++) shhuffle_rdm.push_back(i);
random_shuffle(shhuffle_rdm.begin(),shhuffle_rdm.end());
for(int i=0;i<changeNum;i++) v.push_back(shhuffle_rdm[i]);
if(!v.empty()) sort(v.begin(),v.end());
}else if(graphType == 1){
for(int i=0;i<changeNum;i++){
v.push_back(RandomUpBound-changeNum+i);
}
}else if(graphType == 2){
v.push_back(rand()%RandomUpBound);
}
//for (int i = 0; i < v.size(); i++) cout<<v[i]<<endl;
if(graphType == 3) {
set<int>::iterator it;
int vcnt = 0;
int cnt = 0;
for(it = clearNodeSet.begin();it!=clearNodeSet.end();it++){
if (v[vcnt]==cnt)
{
v[vcnt++] = (*it);
}
cnt++;
}
vector<set<pair<int,int> > > edgeFromNodeToBeInserted;
for(int i=0;i<v.size();i++){
set<pair<int,int> > tempset;
edgeFromNodeToBeInserted.push_back(tempset);
}
set<pair<int,int> >::iterator iter = clearSet.begin();
//cout<<1<<endl;
while(iter!=clearSet.end()){
int st = (*iter).first;
int ed = (*iter).second;
int flg = 0;
for(int i=0;i<v.size();i++){
if(st == v[i]||ed == v[i]){
edgeFromNodeToBeInserted[i].insert(make_pair((*iter).first,(*iter).second));
flg = 1;
break;
}
}
if(flg) {
set<pair<int,int> >::iterator tempIt = iter;
iter++;
clearSet.erase(tempIt);
}else iter++;
}
//cout<<2<<endl;
for(iter = clearSet.begin();iter!=clearSet.end();iter++){
int st = (*iter).first;
int ed = (*iter).second;
G.addEdge(st,ed);
}
if(method == 0){
G.initSup();
G.cover();
G.greed();
}else if(method == 1){
G.initSup();
G.cover();
G.distribute();
}else cout<<"Wrong modle."<<endl;
G.enableAllNodes();
switch (computeType)
{
case 0:
for(int i=0;i<edgeFromNodeToBeInserted.size();i++){
G.SingleNodeInsert(edgeFromNodeToBeInserted[i],v[i]);
}
G.log(changeNum,changeNum,G.totalTime);
break;
case 1:
G.MultNodeInsert(edgeFromNodeToBeInserted,v);
break;
default:
break;
}
}else{
int rNum = 0;
int pNum = 0;
set<pair<int,int> >::iterator iter;
for(iter = clearSet.begin();iter!=clearSet.end();iter++){
int needInsert = 0;
int needDelete = 0;
if(((computeType<=3 && computeType>=1)||computeType == 6 ||computeType == 7||computeType ==8 || computeType ==9) && !v.empty() && v[pNum] == rNum && pNum<changeNum ){
//cout<<rNum<<" "<<pNum<<endl;
pNum++;
needInsert = 1;
if(computeType ==8 || computeType ==9){
needDelete = 1;
needInsert = 0;
}
}
int st = (*iter).first;
int ed = (*iter).second;
//if(needInsert) cout<<st<<" "<<ed<<endl;;
if(!needInsert) {
G.addEdge(st,ed);
}
if(needInsert||computeType==4||computeType==5||needDelete){//如果需要插入或者删除
stId.push_back(min(st,ed));
edId.push_back(max(st,ed));
}
rNum ++;
//cout<<rNum<<endl;
}
if(method == 0){
G.initSup();
G.cover();
G.greed();
}else if(method == 1){
G.initSup();
G.cover();
G.distribute();
}else cout<<"Wrong modle."<<endl;
G.enableAllNodes();
G.startCntSteps = 1;
switch (computeType)
{
case 0:
break;
case 1:
for(int i=0;i<changeNum;i++){
G.dynamicInsert(stId[i],edId[i]);
G.distribute();
}
break;
case 2:
for(int i=0;i<changeNum;i++) G.dynamicInsert(stId[i],edId[i]);
G.distribute();
break;
case 3:
for(int i=0;i<changeNum;i++) G.addEdge(stId[i],edId[i],0);
G.initSup();
G.cover();
G.distribute();
break;
case 4:
for(int i=0;i<changeNum;i++){
G.dynamicDelete(stId[i],edId[i]);
G.distribute();
}
break;
case 5:
for(int i=0;i<changeNum;i++){
G.supInitDelete(stId[i],edId[i]);
}
G.distribute();
break;
case 6:
for(int i=0;i<changeNum;i++){
G.centerInsert(stId[i],edId[i],0);
}
G.log(changeNum,changeNum,G.totalTime);
break;
case 7:
G.centerMultInsert(stId,edId);
break;
case 8:
for(int i=0;i<changeNum;i++){
G.centerDelete(stId[i],edId[i],0);
}
G.log(changeNum,changeNum,G.totalTime);
break;
case 9:
//cout<<stId.size()<<" "<<edId.size()<<endl;
G.centerMultDelete(stId,edId);
break;
default:
if(graphType!=2)
cout<<"Wrong modle!"<<endl;
break;
}
if(computeType!=0 &&graphType!=2 &&computeType !=6 &&computeType!=7 &&computeType!=8 &&computeType!=9) G.outputDynamicInfo(computeType);
}
if(write == 'w'){
string str = getName(filename);
str = argv[5][0] + str;
//cout<<str<<endl;
G.writeFile((char *)str.c_str());
}
} | [
"[email protected]"
] | |
39d605c2caa1c272705289bd86a3dd7e0a4b7c2b | b9264aa2552272b19ca393ba818f9dcb8d91da10 | /hashmap/lib/seqan3/test/unit/core/algorithm/algorithm_result_generator_range_test.cpp | d106ca551f52a6936cfaea989d40484cf9994252 | [
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-public-domain",
"CC0-1.0",
"CC-BY-4.0",
"MIT"
] | permissive | eaasna/low-memory-prefilter | c29b3aeb76f70afc4f26da3d9f063b0bc2e251e0 | efa20dc8a95ce688d2a9d08773d120dff4cccbb6 | refs/heads/master | 2023-07-04T16:45:05.817237 | 2021-08-12T12:01:11 | 2021-08-12T12:01:11 | 383,427,746 | 0 | 0 | BSD-3-Clause | 2021-07-06T13:24:31 | 2021-07-06T10:22:54 | C++ | UTF-8 | C++ | false | false | 4,490 | cpp | // -----------------------------------------------------------------------------------------------------
// Copyright (c) 2006-2020, Knut Reinert & Freie Universität Berlin
// Copyright (c) 2016-2020, Knut Reinert & MPI für molekulare Genetik
// This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License
// shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md
// -----------------------------------------------------------------------------------------------------
#include <gtest/gtest.h>
#include <optional>
#include <vector>
#include <seqan3/core/algorithm/algorithm_result_generator_range.hpp>
#include <seqan3/utility/views/single_pass_input.hpp>
#include "../../range/iterator_test_template.hpp"
// ----------------------------------------------------------------------------
// Simple executor used as mock for the test.
// ----------------------------------------------------------------------------
struct dummy_executor
{
using value_type = size_t;
using reference = value_type;
using difference_type = std::ptrdiff_t;
std::optional<size_t> next_result()
{
auto it = std::ranges::begin(generator);
if (it == std::ranges::end(generator))
{
return {};
}
else
{
std::optional<size_t> opt{*it};
++it;
return opt;
}
}
private:
seqan3::detail::single_pass_input_view<decltype(std::views::iota(0u, 10u))> generator{std::views::iota(0u, 10u)};
};
// ----------------------------------------------------------------------------
// Testing iterator.
// ----------------------------------------------------------------------------
using algorithm_result_generator_range_t = seqan3::algorithm_result_generator_range<dummy_executor>;
using algorithm_result_generator_range_iterator = std::ranges::iterator_t<algorithm_result_generator_range_t>;
template <>
struct iterator_fixture<algorithm_result_generator_range_iterator> : ::testing::Test
{
using iterator_tag = std::input_iterator_tag;
static constexpr bool const_iterable = false;
algorithm_result_generator_range_t test_range{dummy_executor{}};
std::vector<size_t> expected_range{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
};
INSTANTIATE_TYPED_TEST_SUITE_P(algorithm_result_generator_range_iterator, iterator_fixture, algorithm_result_generator_range_iterator, );
// ----------------------------------------------------------------------------
// Testing alignment range concepts and interfaces.
// ----------------------------------------------------------------------------
TEST(algorithm_result_generator_range, concept_test)
{
EXPECT_TRUE(std::ranges::input_range<algorithm_result_generator_range_t>);
EXPECT_FALSE(std::ranges::forward_range<algorithm_result_generator_range_t>);
}
TEST(algorithm_result_generator_range, construction)
{
EXPECT_TRUE(std::is_default_constructible_v<algorithm_result_generator_range_t>);
EXPECT_FALSE(std::is_copy_constructible_v<algorithm_result_generator_range_t>);
EXPECT_TRUE(std::is_move_constructible_v<algorithm_result_generator_range_t>);
EXPECT_FALSE(std::is_copy_assignable_v<algorithm_result_generator_range_t>);
EXPECT_TRUE(std::is_move_assignable_v<algorithm_result_generator_range_t>);
EXPECT_TRUE((std::is_constructible_v<algorithm_result_generator_range_t, dummy_executor>));
}
TEST(algorithm_result_generator_range, type_deduction)
{
seqan3::algorithm_result_generator_range rng{dummy_executor{}};
EXPECT_TRUE((std::is_same_v<decltype(rng), seqan3::algorithm_result_generator_range<dummy_executor>>));
}
TEST(algorithm_result_generator_range, begin)
{
seqan3::algorithm_result_generator_range rng{dummy_executor{}};
auto it = rng.begin();
EXPECT_EQ(*it, 0u);
}
TEST(algorithm_result_generator_range, end)
{
seqan3::algorithm_result_generator_range rng{dummy_executor{}};
auto it = rng.end();
EXPECT_FALSE(it == rng.begin());
EXPECT_FALSE(rng.begin() == it);
}
TEST(algorithm_result_generator_range, iterable)
{
seqan3::algorithm_result_generator_range rng{dummy_executor{}};
size_t sum = 0;
for (size_t res : rng)
sum += res;
EXPECT_EQ(sum, 45u);
}
TEST(algorithm_result_generator_range, default_construction)
{
seqan3::algorithm_result_generator_range<dummy_executor> rng{};
EXPECT_THROW(rng.begin(), std::runtime_error);
}
| [
"[email protected]"
] | |
86c0dc1b98d4c8e072495a2448e4983d334ef9a8 | 1942a0d16bd48962e72aa21fad8d034fa9521a6c | /aws-cpp-sdk-cognito-sync/include/aws/cognito-sync/model/BulkPublishRequest.h | c51aeb5773ee4263ab7e229fae4c1b05d35765ff | [
"Apache-2.0",
"JSON",
"MIT"
] | permissive | yecol/aws-sdk-cpp | 1aff09a21cfe618e272c2c06d358cfa0fb07cecf | 0b1ea31e593d23b5db49ee39d0a11e5b98ab991e | refs/heads/master | 2021-01-20T02:53:53.557861 | 2018-02-11T11:14:58 | 2018-02-11T11:14:58 | 83,822,910 | 0 | 1 | null | 2017-03-03T17:17:00 | 2017-03-03T17:17:00 | null | UTF-8 | C++ | false | false | 3,399 | h | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/cognito-sync/CognitoSync_EXPORTS.h>
#include <aws/cognito-sync/CognitoSyncRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
namespace Aws
{
namespace CognitoSync
{
namespace Model
{
/**
* The input for the BulkPublish operation.<p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/cognito-sync-2014-06-30/BulkPublishRequest">AWS
* API Reference</a></p>
*/
class AWS_COGNITOSYNC_API BulkPublishRequest : public CognitoSyncRequest
{
public:
BulkPublishRequest();
Aws::String SerializePayload() const override;
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE)
* created by Amazon Cognito. GUID generation is unique within a region.
*/
inline const Aws::String& GetIdentityPoolId() const{ return m_identityPoolId; }
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE)
* created by Amazon Cognito. GUID generation is unique within a region.
*/
inline void SetIdentityPoolId(const Aws::String& value) { m_identityPoolIdHasBeenSet = true; m_identityPoolId = value; }
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE)
* created by Amazon Cognito. GUID generation is unique within a region.
*/
inline void SetIdentityPoolId(Aws::String&& value) { m_identityPoolIdHasBeenSet = true; m_identityPoolId = value; }
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE)
* created by Amazon Cognito. GUID generation is unique within a region.
*/
inline void SetIdentityPoolId(const char* value) { m_identityPoolIdHasBeenSet = true; m_identityPoolId.assign(value); }
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE)
* created by Amazon Cognito. GUID generation is unique within a region.
*/
inline BulkPublishRequest& WithIdentityPoolId(const Aws::String& value) { SetIdentityPoolId(value); return *this;}
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE)
* created by Amazon Cognito. GUID generation is unique within a region.
*/
inline BulkPublishRequest& WithIdentityPoolId(Aws::String&& value) { SetIdentityPoolId(value); return *this;}
/**
* A name-spaced GUID (for example, us-east-1:23EC4050-6AEA-7089-A2DD-08002EXAMPLE)
* created by Amazon Cognito. GUID generation is unique within a region.
*/
inline BulkPublishRequest& WithIdentityPoolId(const char* value) { SetIdentityPoolId(value); return *this;}
private:
Aws::String m_identityPoolId;
bool m_identityPoolIdHasBeenSet;
};
} // namespace Model
} // namespace CognitoSync
} // namespace Aws
| [
"[email protected]"
] | |
1fa82df89068db26adb7718d7a77a5a882480b65 | 0400f3ae3051b5e34872e657e9260c0c6784d8d4 | /Assignment 2/HW2PR2.cpp | eb60684dadd5aeafaa237414f20960ff88c68041 | [] | no_license | pionoor/CSCE121 | d4341b870db821214e8694aa8095634bd66d10ff | 1eb8d4ebbc2a3145974459714f0b7498e9c52e45 | refs/heads/master | 2021-01-20T02:20:31.911785 | 2015-05-20T01:57:00 | 2015-05-20T01:57:00 | 35,919,690 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 871 | cpp | //
// main.cpp
// HW2PR1
//
// Created by Noor Thabit on 2/7/13.
// Copyright (c) 2013 Noor Thabit. All rights reserved.
//
#include <iostream>
#include <math.h>
using namespace std;
double my_sqrt_1(double n) //creat a function accept double and return adouble
{
double x=n-1;
double result = 1 + (1/2)*pow(x,1.0) - (1/8)*pow(x,2.0) + (1/16)*pow(x,3.0) - (5/128)*pow(x,4.0);
return result;
}
int main()
{
double n;
double relative_error_per_cent;
for(auto k: {-100,-10,-1,0,1,10,100})
{
n = 3.14159 * pow(10.0,k);
relative_error_per_cent = 100 * ((my_sqrt_1(n) - sqrt(n))/sqrt(n)); //the relative error as a per cent
cout<<n<<'\t'<<sqrt(n)<<'\t'<<my_sqrt_1(n)<<'\t'<<relative_error_per_cent<<endl ; //prints n, sqrt(n), and my_sqrt_1(n) for n
}
return 0;
}
| [
"[email protected]"
] | |
3f56224b3e8961519cc5fa891cb19209e510b2cc | 0f7d29777eee0ddd40a563b77df2a77d8a7aea3b | /src/Wallet.hpp | 895f86e2a3ca20c3fe7c6c948bd28bf193aa17c9 | [
"MIT"
] | permissive | rvillegasm/blocky | f5827c4604d3fb330ec27658d08e0d4e6c86e8df | ca12c4ca7197b7d03d7f360003c4bc1b87890391 | refs/heads/main | 2023-07-11T13:44:43.423524 | 2021-08-16T01:56:15 | 2021-08-16T01:56:15 | 392,487,660 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 307 | hpp | #pragma once
#include "utils/SignatureKeypair.hpp"
namespace blocky
{
class Wallet
{
private:
utils::SignatureKeypair m_keypair = {};
public:
Wallet() = default;
[[nodiscard]] const utils::SignatureKeypair &getKeypair() const { return m_keypair; }
};
}
| [
"[email protected]"
] | |
98099a5d956f847736ed9fa9b39b5c6251116347 | 24f8cfae88683b91c55b027fd2ad39316d90906c | /features/sift.cc | 492f32a9f1bd30fd577f510d048d9ba75f074a89 | [] | no_license | sld66320/mySFM | 63afb83f8f657c893c815678b76e5cb98df5f679 | 9be8469d5f1bda95b4339c2095d919820263b29c | refs/heads/master | 2023-05-04T19:22:41.140674 | 2021-05-03T08:02:53 | 2021-05-03T08:02:53 | 337,611,143 | 9 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 35,055 | cc | /*
* Copyright (C) 2015, Simon Fuhrmann
* TU Darmstadt - Graphics, Capture and Massively Parallel Computing
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD 3-Clause license. See the LICENSE.txt file for details.
*/
#include <iostream>
#include <fstream>
#include <stdexcept>
#include "util/timer.h"
#include "math/functions.h"
#include "math/matrix.h"
#include "math/matrix_tools.h"
#include "core/image_io.h"
#include "core/image_tools.h"
#include "features/sift.h"
FEATURES_NAMESPACE_BEGIN
Sift::Sift (Options const& options)
: options(options)
{
if (this->options.min_octave < -1
|| this->options.min_octave > this->options.max_octave)
throw std::invalid_argument("Invalid octave range");
if (this->options.contrast_threshold < 0.0f)
this->options.contrast_threshold = 0.02f
/ static_cast<float>(this->options.num_samples_per_octave);
if (this->options.debug_output)
this->options.verbose_output = true;
}
/* ---------------------------------------------------------------- */
void
Sift::process (void)
{
util::ClockTimer timer, total_timer;
/*
* Creates the scale space representation of the image by
* sampling the scale space and computing the DoG images.
* See Section 3, 3.2 and 3.3 in SIFT article.
*/
if (this->options.verbose_output)
{
std::cout << "SIFT: Creating "
<< (this->options.max_octave - this->options.min_octave)
<< " octaves (" << this->options.min_octave << " to "
<< this->options.max_octave << ")..." << std::endl;
}
timer.reset();
this->create_octaves();
if (this->options.debug_output)
{
std::cout << "SIFT: Creating octaves took "
<< timer.get_elapsed() << "ms." << std::endl;
}
/*
* Detects local extrema in the DoG function as described in Section 3.1.
*/
if (this->options.debug_output)
{
std::cout << "SIFT: Detecting local extrema..." << std::endl;
}
timer.reset();
this->extrema_detection();
if (this->options.debug_output)
{
std::cout << "SIFT: Detected " << this->keypoints.size()
<< " keypoints, took " << timer.get_elapsed() << "ms." << std::endl;
}
/*
* Accurate keypoint localization and filtering.
* According to Section 4 in SIFT article.
*/
if (this->options.debug_output)
{
std::cout << "SIFT: Localizing and filtering keypoints..." << std::endl;
}
timer.reset();
this->keypoint_localization();
if (this->options.debug_output)
{
std::cout << "SIFT: Retained " << this->keypoints.size() << " stable "
<< "keypoints, took " << timer.get_elapsed() << "ms." << std::endl;
}
/*
* Difference of Gaussian images are not needed anymore.
*/
for (std::size_t i = 0; i < this->octaves.size(); ++i)
this->octaves[i].dog.clear();
/*
* Generate the list of keypoint descriptors.
* See Section 5 and 6 in the SIFT article.
* This list can in general be larger than the amount of keypoints,
* since for each keypoint several descriptors may be created.
*/
if (this->options.verbose_output)
{
std::cout << "SIFT: Generating keypoint descriptors..." << std::endl;
}
timer.reset();
this->descriptor_generation();
if (this->options.debug_output)
{
std::cout << "SIFT: Generated " << this->descriptors.size()
<< " descriptors, took " << timer.get_elapsed() << "ms."
<< std::endl;
}
if (this->options.verbose_output)
{
std::cout << "SIFT: Generated " << this->descriptors.size()
<< " descriptors from " << this->keypoints.size() << " keypoints,"
<< " took " << total_timer.get_elapsed() << "ms." << std::endl;
}
/* Free memory. */
this->octaves.clear();
}
/* ---------------------------------------------------------------- */
void
Sift::set_image (core::ByteImage::ConstPtr img)
{
if (img->channels() != 1 && img->channels() != 3)
throw std::invalid_argument("Gray or color image expected");
// 将图像转化成灰度图
this->orig = core::image::byte_to_float_image(img);
if (img->channels() == 3) {
this->orig = core::image::desaturate<float>
(this->orig, core::image::DESATURATE_AVERAGE);
}
}
/* ---------------------------------------------------------------- */
void
Sift::set_float_image (core::FloatImage::ConstPtr img)
{
if (img->channels() != 1 && img->channels() != 3)
throw std::invalid_argument("Gray or color image expected");
if (img->channels() == 3)
{
this->orig = core::image::desaturate<float>
(img, core::image::DESATURATE_AVERAGE);
}
else
{
this->orig = img->duplicate();
}
}
/* ---------------------------------------------------------------- */
void
Sift::create_octaves (void)
{
this->octaves.clear();
/*
* Create octave -1. The original image is assumed to have blur
* sigma = 0.5. The double size image therefore has sigma = 1.
*/
if (this->options.min_octave < 0)
{
//std::cout << "Creating octave -1..." << std::endl;
core::FloatImage::Ptr img
= core::image::rescale_double_size_supersample<float>(this->orig);
this->add_octave(img, this->options.inherent_blur_sigma * 2.0f,
this->options.base_blur_sigma);
}
/*
* Prepare image for the first positive octave by downsampling.
* This code is executed only if min_octave > 0.
*/
core::FloatImage::ConstPtr img = this->orig;
for (int i = 0; i < this->options.min_octave; ++i)
img = core::image::rescale_half_size_gaussian<float>(img);
/*
* Create new octave from 'img', then subsample octave image where
* sigma is doubled to get a new base image for the next octave.
*/
float img_sigma = this->options.inherent_blur_sigma;
for (int i = std::max(0, this->options.min_octave);
i <= this->options.max_octave; ++i)
{
//std::cout << "Creating octave " << i << "..." << std::endl;
this->add_octave(img, img_sigma, this->options.base_blur_sigma);
core::FloatImage::ConstPtr pre_base = octaves[octaves.size()-1].img[0];
img = core::image::rescale_half_size_gaussian<float>(pre_base);
img_sigma = this->options.base_blur_sigma;
}
}
/* ---------------------------------------------------------------- */
void
Sift::add_octave (core::FloatImage::ConstPtr image,
float has_sigma, float target_sigma)
{
/*
* First, bring the provided image to the target blur.
* Since L * g(sigma1) * g(sigma2) = L * g(sqrt(sigma1^2 + sigma2^2)),
* we need to blur with sigma = sqrt(target_sigma^2 - has_sigma^2).
*/
float sigma = std::sqrt(MATH_POW2(target_sigma) - MATH_POW2(has_sigma));
//std::cout << "Pre-blurring image to sigma " << target_sigma << " (has "
// << has_sigma << ", blur = " << sigma << ")..." << std::endl;
core::FloatImage::Ptr base = (target_sigma > has_sigma
? core::image::blur_gaussian<float>(image, sigma)
: image->duplicate());
/* Create the new octave and add initial image. */
this->octaves.push_back(Octave());
Octave& oct = this->octaves.back();
oct.img.push_back(base);
/* 'k' is the constant factor between the scales in scale space. */
float const k = std::pow(2.0f, 1.0f / this->options.num_samples_per_octave);
sigma = target_sigma;
/* Create other (s+2) samples of the octave to get a total of (s+3). */
for (int i = 1; i < this->options.num_samples_per_octave + 3; ++i)
{
/* Calculate the blur sigma the image will get. */
float sigmak = sigma * k;
float blur_sigma = std::sqrt(MATH_POW2(sigmak) - MATH_POW2(sigma));
/* Blur the image to create a new scale space sample. */
//std::cout << "Blurring image to sigma " << sigmak << " (has " << sigma
// << ", blur = " << blur_sigma << ")..." << std::endl;
core::FloatImage::Ptr img = core::image::blur_gaussian<float>
(base, blur_sigma);
oct.img.push_back(img);
/* Create the Difference of Gaussian image (DoG). */
//计算差分拉普拉斯 // todo revised by sway
core::FloatImage::Ptr dog = core::image::subtract<float>(img, base);
oct.dog.push_back(dog);
/* Update previous image and sigma for next round. */
base = img;
sigma = sigmak;
}
}
/* ---------------------------------------------------------------- */
void
Sift::extrema_detection (void)
{
/* Delete previous keypoints. */
this->keypoints.clear();
/* Detect keypoints in each octave... */
for (std::size_t i = 0; i < this->octaves.size(); ++i)
{
Octave const& oct(this->octaves[i]);
/* In each octave, take three subsequent DoG images and detect. */
for (int s = 0; s < (int)oct.dog.size() - 2; ++s)
{
core::FloatImage::ConstPtr samples[3] =
{ oct.dog[s + 0], oct.dog[s + 1], oct.dog[s + 2] };
this->extrema_detection(samples, static_cast<int>(i)
+ this->options.min_octave, s);
}
}
}
/* ---------------------------------------------------------------- */
std::size_t
Sift::extrema_detection (core::FloatImage::ConstPtr s[3], int oi, int si)
{
int const w = s[1]->width();
int const h = s[1]->height();
/* Offsets for the 9-neighborhood w.r.t. center pixel. */
int noff[9] = { -1 - w, 0 - w, 1 - w, -1, 0, 1, -1 + w, 0 + w, 1 + w };
/*
* Iterate over all pixels in s[1], and check if pixel is maximum
* (or minumum) in its 27-neighborhood.
*/
int detected = 0;
int off = w;
for (int y = 1; y < h - 1; ++y, off += w)
for (int x = 1; x < w - 1; ++x)
{
int idx = off + x;
bool largest = true;
bool smallest = true;
float center_value = s[1]->at(idx);
for (int l = 0; (largest || smallest) && l < 3; ++l)
for (int i = 0; (largest || smallest) && i < 9; ++i)
{
if (l == 1 && i == 4) // Skip center pixel
continue;
if (s[l]->at(idx + noff[i]) >= center_value)
largest = false;
if (s[l]->at(idx + noff[i]) <= center_value)
smallest = false;
}
/* Skip non-maximum values. */
if (!smallest && !largest)
continue;
/* Yummy. Add detected scale space extremum. */
Keypoint kp;
kp.octave = oi;
kp.x = static_cast<float>(x);
kp.y = static_cast<float>(y);
kp.sample = static_cast<float>(si);
this->keypoints.push_back(kp);
detected += 1;
}
return detected;
}
/* ---------------------------------------------------------------- */
void
Sift::keypoint_localization (void)
{
/*
* Iterate over all keypoints, accurately localize minima and maxima
* in the DoG function by fitting a quadratic Taylor polynomial
* around the keypoint.
*/
int num_singular = 0;
int num_keypoints = 0; // Write iterator
for (std::size_t i = 0; i < this->keypoints.size(); ++i)
{
/* Copy keypoint. */
Keypoint kp(this->keypoints[i]);
/* Get corresponding octave and DoG images. */
Octave const& oct(this->octaves[kp.octave - this->options.min_octave]);
int sample = static_cast<int>(kp.sample);
core::FloatImage::ConstPtr dogs[3] = { oct.dog[sample + 0], oct.dog[sample + 1], oct.dog[sample + 2] };
/* Shorthand for image width and height. */
int const w = dogs[0]->width();
int const h = dogs[0]->height();
/* The integer and floating point location of the keypoints. */
int ix = static_cast<int>(kp.x);
int iy = static_cast<int>(kp.y);
int is = static_cast<int>(kp.sample);
float delta_x, delta_y, delta_s;
/* The first and second order derivatives. */
float Dx, Dy, Ds;
float Dxx, Dyy, Dss;
float Dxy, Dxs, Dys;
/*
* Locate the keypoint using second order Taylor approximation.
* The procedure might get iterated around a neighboring pixel if
* the accurate keypoint is off by >0.6 from the center pixel.
*/
# define AT(S,OFF) (dogs[S]->at(px + OFF))
for (int j = 0; j < 5; ++j)
{
std::size_t px = iy * w + ix;
/* Compute first and second derivatives. */
Dx = (AT(1,1) - AT(1,-1)) * 0.5f;
Dy = (AT(1,w) - AT(1,-w)) * 0.5f;
Ds = (AT(2,0) - AT(0,0)) * 0.5f;
Dxx = AT(1,1) + AT(1,-1) - 2.0f * AT(1,0);
Dyy = AT(1,w) + AT(1,-w) - 2.0f * AT(1,0);
Dss = AT(2,0) + AT(0,0) - 2.0f * AT(1,0);
Dxy = (AT(1,1+w) + AT(1,-1-w) - AT(1,-1+w) - AT(1,1-w)) * 0.25f;
Dxs = (AT(2,1) + AT(0,-1) - AT(2,-1) - AT(0,1)) * 0.25f;
Dys = (AT(2,w) + AT(0,-w) - AT(2,-w) - AT(0,w)) * 0.25f;
/* Setup the Hessian matrix. */
math::Matrix3f H;
/****************************task-1-0 构造Hessian矩阵 ******************************/
/*
* 参考第32页slide的Hessian矩阵构造方式填充H矩阵,其中dx=dy=d_sigma=1, 其中A矩阵按照行顺序存储,即
* H=[H[0], H[1], H[2]]
* [H[3], H[4], H[5]]
* [H[6], H[7], H[8]]
*/
/**********************************************************************************/
H[0] = Dxx; H[1] = Dxy; H[2] = Dxs;
H[3] = Dxy; H[4] = Dyy; H[5] = Dys;
H[6] = Dxs; H[7] = Dys; H[8] = Dss;
/* Compute determinant to detect singular matrix. */
float detH = math::matrix_determinant(H);
if (MATH_EPSILON_EQ(detH, 0.0f, 1e-15f))
{
num_singular += 1;
delta_x = delta_y = delta_s = 0.0f; // FIXME: Handle this case?
break;
}
/* Invert the matrix to get the accurate keypoint. */
math::Matrix3f H_inv = math::matrix_inverse(H, detH);
math::Vec3f b(-Dx, -Dy, -Ds);
//math::Vec3f delta;
/****************************task-1-1 求解偏移量deta ******************************/
/* 参考第30页slide delta_x的求解方式 delta_x = inv(H)*b
* 请在此处给出delta的表达式
*/
/* */
/* 此处添加代码 */
/* */
/**********************************************************************************/
math::Vec3f delta = H_inv * b;
delta_x = delta[0];
delta_y = delta[1];
delta_s = delta[2];
/* Check if accurate location is far away from pixel center. */
// dx =0 表示|dx|>0.6f
int dx = (delta_x > 0.6f && ix < w-2) * 1 + (delta_x < -0.6f && ix > 1) * -1;
int dy = (delta_y > 0.6f && iy < h-2) * 1 + (delta_y < -0.6f && iy > 1) * -1;
/* If the accurate location is closer to another pixel,
* repeat localization around the other pixel. */
if (dx != 0 || dy != 0)
{
ix += dx;
iy += dy;
continue;
}
/* Accurate location looks good. */
break;
}
/* Calcualte function value D(x) at accurate keypoint x. */
/*****************************task1-2求解极值点处的DoG值val ***************************/
/*
* 参考第30页slides的机极值点f(x)的求解公式f(x) = f(x0) + 0.5* delta.dot(D)
* 其中
* f(x0)--表示插值点(ix, iy, is) 处的DoG值,可通过dogs[1]->at(ix, iy, 0)获取
* delta--为上述求得的delta=[delta_x, delta_y, delta_s]
* D--为一阶导数,表示为(Dx, Dy, Ds)
* 请给出求解val的代码
*/
//float val = 0.0;
/* */
/* 此处添加代码 */
/* */
/************************************************************************************/
float val = dogs[1]->at(ix, iy, 0) + 0.5f * (Dx * delta_x + Dy * delta_y + Ds * delta_s);
/* Calcualte edge response score Tr(H)^2 / Det(H), see Section 4.1. */
/**************************去除边缘点,参考第33页slide 仔细阅读代码 ****************************/
float hessian_trace = Dxx + Dyy;
float hessian_det = Dxx * Dyy - MATH_POW2(Dxy);
float hessian_score = MATH_POW2(hessian_trace) / hessian_det;
float score_thres = MATH_POW2(this->options.edge_ratio_threshold + 1.0f)
/ this->options.edge_ratio_threshold;
/********************************************************************************/
/*
* Set accurate final keypoint location.
*/
kp.x = (float)ix + delta_x;
kp.y = (float)iy + delta_y;
kp.sample = (float)is + delta_s;
/*
* Discard keypoints with:
* 1. low contrast (value of DoG function at keypoint),
* 2. negative hessian determinant (curvatures with different sign),
* Note that negative score implies negative determinant.
* 3. large edge response (large hessian score),
* 4. unstable keypoint accurate locations,
* 5. keypoints beyond the scale space boundary.
*/
if (std::abs(val) < this->options.contrast_threshold
|| hessian_score < 0.0f || hessian_score > score_thres
|| std::abs(delta_x) > 1.5f || std::abs(delta_y) > 1.5f || std::abs(delta_s) > 1.0f
|| kp.sample < -1.0f
|| kp.sample > (float)this->options.num_samples_per_octave
|| kp.x < 0.0f || kp.x > (float)(w - 1)
|| kp.y < 0.0f || kp.y > (float)(h - 1))
{
//std::cout << " REJECTED!" << std::endl;
continue;
}
/* Keypoint is accepted, copy to write iter and advance. */
this->keypoints[num_keypoints] = kp;
num_keypoints += 1;
}
/* Limit vector size to number of accepted keypoints. */
this->keypoints.resize(num_keypoints);
if (this->options.debug_output && num_singular > 0)
{
std::cout << "SIFT: Warning: " << num_singular
<< " singular matrices detected!" << std::endl;
}
}
/* ---------------------------------------------------------------- */
void
Sift::descriptor_generation (void)
{
if (this->octaves.empty())
throw std::runtime_error("Octaves not available!");
if (this->keypoints.empty())
return;
this->descriptors.clear();
this->descriptors.reserve(this->keypoints.size() * 3 / 2);
/*
* Keep a buffer of S+3 gradient and orientation images for the current
* octave. Once the octave is changed, these images are recomputed.
* To ensure efficiency, the octave index must always increase, never
* decrease, which is enforced during the algorithm.
*/
int octave_index = this->keypoints[0].octave;
Octave* octave = &this->octaves[octave_index - this->options.min_octave];
// todo 计算每个octave中所有图像的梯度值和方向,具体得, octave::grad存储图像的梯度响应值,octave::ori存储梯度方向
this->generate_grad_ori_images(octave);
/* Walk over all keypoints and compute descriptors. */
for (std::size_t i = 0; i < this->keypoints.size(); ++i)
{
Keypoint const& kp(this->keypoints[i]);
/* Generate new gradient and orientation images if octave changed. */
if (kp.octave > octave_index)
{
/* Clear old octave gradient and orientation images. */
if (octave)
{
octave->grad.clear();
octave->ori.clear();
}
/* Setup new octave gradient and orientation images. */
octave_index = kp.octave;
octave = &this->octaves[octave_index - this->options.min_octave];
this->generate_grad_ori_images(octave);
}
else if (kp.octave < octave_index)
{
throw std::runtime_error("Decreasing octave index!");
}
/* Orientation assignment. This returns multiple orientations. */
/* todo 统计直方图找到特征点主方向,找到几个主方向*/
std::vector<float> orientations;
orientations.reserve(8);
this->orientation_assignment(kp, octave, orientations);
/* todo 生成特征向量,同一个特征点可能有多个描述子,为了提升匹配的稳定性*/
/* Feature vector extraction. */
for (std::size_t j = 0; j < orientations.size(); ++j)
{
Descriptor desc;
float const scale_factor = std::pow(2.0f, kp.octave);
desc.x = scale_factor * (kp.x + 0.5f) - 0.5f;
desc.y = scale_factor * (kp.y + 0.5f) - 0.5f;
desc.scale = this->keypoint_absolute_scale(kp);
desc.orientation = orientations[j];
if (this->descriptor_assignment(kp, desc, octave))
this->descriptors.push_back(desc);
}
}
}
/* ---------------------------------------------------------------- */
void
Sift::generate_grad_ori_images (Octave* octave)
{
octave->grad.clear();
octave->grad.reserve(octave->img.size());
octave->ori.clear();
octave->ori.reserve(octave->img.size());
int const width = octave->img[0]->width();
int const height = octave->img[0]->height();
//std::cout << "Generating gradient and orientation images..." << std::endl;
for (std::size_t i = 0; i < octave->img.size(); ++i)
{
core::FloatImage::ConstPtr img = octave->img[i];
core::FloatImage::Ptr grad = core::FloatImage::create(width, height, 1);
core::FloatImage::Ptr ori = core::FloatImage::create(width, height, 1);
int image_iter = width + 1;
for (int y = 1; y < height - 1; ++y, image_iter += 2)
for (int x = 1; x < width - 1; ++x, ++image_iter)
{
float m1x = img->at(image_iter - 1);
float p1x = img->at(image_iter + 1);
float m1y = img->at(image_iter - width);
float p1y = img->at(image_iter + width);
float dx = 0.5f * (p1x - m1x);
float dy = 0.5f * (p1y - m1y);
float atan2f = std::atan2(dy, dx);
grad->at(image_iter) = std::sqrt(dx * dx + dy * dy);
ori->at(image_iter) = atan2f < 0.0f
? atan2f + MATH_PI * 2.0f : atan2f;
}
octave->grad.push_back(grad);
octave->ori.push_back(ori);
}
}
/* ---------------------------------------------------------------- */
void
Sift::orientation_assignment (Keypoint const& kp,
Octave const* octave, std::vector<float>& orientations)
{
int const nbins = 36;
float const nbinsf = static_cast<float>(nbins);
/* Prepare 36-bin histogram. */
float hist[nbins];
std::fill(hist, hist + nbins, 0.0f);
/* Integral x and y coordinates and closest scale sample. */
int const ix = static_cast<int>(kp.x + 0.5f);
int const iy = static_cast<int>(kp.y + 0.5f);
int const is = static_cast<int>(math::round(kp.sample));
float const sigma = this->keypoint_relative_scale(kp);
/* Images with its dimension for the keypoint. */
core::FloatImage::ConstPtr grad(octave->grad[is + 1]);
core::FloatImage::ConstPtr ori(octave->ori[is + 1]);
int const width = grad->width();
int const height = grad->height();
/*
* Compute window size 'win', the full window has 2 * win + 1 pixel.
* The factor 3 makes the window large enough such that the gaussian
* has very little weight beyond the window. The value 1.5 is from
* the SIFT paper. If the window goes beyond the image boundaries,
* the keypoint is discarded.
*/
float const sigma_factor = 1.5f;
int win = static_cast<int>(sigma * sigma_factor * 3.0f);
if (ix < win || ix + win >= width || iy < win || iy + win >= height)
return;
/* Center of keypoint index. */
int center = iy * width + ix;
float const dxf = kp.x - static_cast<float>(ix);
float const dyf = kp.y - static_cast<float>(iy);
float const maxdist = static_cast<float>(win*win) + 0.5f;
/* Populate histogram over window, intersected with (1,1), (w-2,h-2). */
for (int dy = -win; dy <= win; ++dy)
{
int const yoff = dy * width;
for (int dx = -win; dx <= win; ++dx)
{
/* Limit to circular window (centered at accurate keypoint). */
float const dist = MATH_POW2(dx-dxf) + MATH_POW2(dy-dyf);
if (dist > maxdist)
continue;
float gm = grad->at(center + yoff + dx); // gradient magnitude
float go = ori->at(center + yoff + dx); // gradient orientation
float weight = math::gaussian_xx(dist, sigma * sigma_factor);
int bin = static_cast<int>(nbinsf * go / (2.0f * MATH_PI));
bin = math::clamp(bin, 0, nbins - 1);
hist[bin] += gm * weight;
}
}
/* Smooth histogram. */
for (int i = 0; i < 6; ++i)
{
float first = hist[0];
float prev = hist[nbins - 1];
for (int j = 0; j < nbins - 1; ++j)
{
float current = hist[j];
hist[j] = (prev + current + hist[j + 1]) / 3.0f;
prev = current;
}
hist[nbins - 1] = (prev + hist[nbins - 1] + first) / 3.0f;
}
/* Find maximum element. */
float maxh = *std::max_element(hist, hist + nbins);
/* Find peaks within 80% of max element. */
for (int i = 0; i < nbins; ++i)
{
float h0 = hist[(i + nbins - 1) % nbins];
float h1 = hist[i];
float h2 = hist[(i + 1) % nbins];
/* These peaks must be a local maximum! */
if (h1 <= 0.8f * maxh || h1 <= h0 || h1 <= h2)
continue;
/*
* Quadratic interpolation to find accurate maximum.
* f(x) = ax^2 + bx + c, f(-1) = h0, f(0) = h1, f(1) = h2
* --> a = 1/2 (h0 - 2h1 + h2), b = 1/2 (h2 - h0), c = h1.
* x = f'(x) = 2ax + b = 0 --> x = -1/2 * (h2 - h0) / (h0 - 2h1 + h2)
*/
float x = -0.5f * (h2 - h0) / (h0 - 2.0f * h1 + h2);
float o = 2.0f * MATH_PI * (x + (float)i + 0.5f) / nbinsf;
orientations.push_back(o);
}
}
/* ---------------------------------------------------------------- */
bool
Sift::descriptor_assignment (Keypoint const& kp, Descriptor& desc,
Octave const* octave)
{
/*
* The final feature vector has size PXB * PXB * OHB.
* The following constants should not be changed yet, as the
* (PXB^2 * OHB = 128) element feature vector is still hard-coded.
*/
//int const PIX = 16; // Descriptor region with 16x16 pixel
int const PXB = 4; // Pixel bins with 4x4 bins
int const OHB = 8; // Orientation histogram with 8 bins
/* Integral x and y coordinates and closest scale sample. */
int const ix = static_cast<int>(kp.x + 0.5f);
int const iy = static_cast<int>(kp.y + 0.5f);
int const is = static_cast<int>(math::round(kp.sample));
float const dxf = kp.x - static_cast<float>(ix);
float const dyf = kp.y - static_cast<float>(iy);
float const sigma = this->keypoint_relative_scale(kp);
/* Images with its dimension for the keypoint. */
core::FloatImage::ConstPtr grad(octave->grad[is + 1]);
core::FloatImage::ConstPtr ori(octave->ori[is + 1]);
int const width = grad->width();
int const height = grad->height();
/* Clear feature vector. */
desc.data.fill(0.0f);
/* Rotation constants given by descriptor orientation. */
float const sino = std::sin(desc.orientation);
float const coso = std::cos(desc.orientation);
/*
* Compute window size.
* Each spacial bin has an extension of 3 * sigma (sigma is the scale
* of the keypoint). For interpolation we need another half bin at
* both ends in each dimension. And since the window can be arbitrarily
* rotated, we need to multiply with sqrt(2). The window size is:
* 2W = sqrt(2) * 3 * sigma * (PXB + 1).
*/
float const binsize = 3.0f * sigma;
int win = MATH_SQRT2 * binsize * (float)(PXB + 1) * 0.5f;
if (ix < win || ix + win >= width || iy < win || iy + win >= height)
return false;
/*
* Iterate over the window, intersected with the image region
* from (1,1) to (w-2, h-2) since gradients/orientations are
* not defined at the boundary pixels. Add all samples to the
* corresponding bin.
*/
int const center = iy * width + ix; // Center pixel at KP location
for (int dy = -win; dy <= win; ++dy)
{
int const yoff = dy * width;
for (int dx = -win; dx <= win; ++dx)
{
/* Get pixel gradient magnitude and orientation. */
float const mod = grad->at(center + yoff + dx);
float const angle = ori->at(center + yoff + dx);
float theta = angle - desc.orientation;
if (theta < 0.0f)
theta += 2.0f * MATH_PI;
/* Compute fractional coordinates w.r.t. the window. */
float const winx = (float)dx - dxf;
float const winy = (float)dy - dyf;
/*
* Compute normalized coordinates w.r.t. bins. The window
* coordinates are rotated around the keypoint. The bins are
* chosen such that 0 is the coordinate of the first bins center
* in each dimension. In other words, (0,0,0) is the coordinate
* of the first bin center in the three dimensional histogram.
*/
float binoff = (float)(PXB - 1) / 2.0f;
float binx = (coso * winx + sino * winy) / binsize + binoff;
float biny = (-sino * winx + coso * winy) / binsize + binoff;
float bint = theta * (float)OHB / (2.0f * MATH_PI) - 0.5f;
/* Compute circular window weight for the sample. */
float gaussian_sigma = 0.5f * (float)PXB;
float gaussian_weight = math::gaussian_xx
(MATH_POW2(binx - binoff) + MATH_POW2(biny - binoff),
gaussian_sigma);
/* Total contribution of the sample in the histogram is now: */
float contrib = mod * gaussian_weight;
/*
* Distribute values into bins (using trilinear interpolation).
* Each sample is inserted into 8 bins. Some of these bins may
* not exist, because the sample is outside the keypoint window.
*/
int bxi[2] = { (int)std::floor(binx), (int)std::floor(binx) + 1 };
int byi[2] = { (int)std::floor(biny), (int)std::floor(biny) + 1 };
int bti[2] = { (int)std::floor(bint), (int)std::floor(bint) + 1 };
float weights[3][2] = {
{ (float)bxi[1] - binx, 1.0f - ((float)bxi[1] - binx) },
{ (float)byi[1] - biny, 1.0f - ((float)byi[1] - biny) },
{ (float)bti[1] - bint, 1.0f - ((float)bti[1] - bint) }
};
// Wrap around orientation histogram
if (bti[0] < 0)
bti[0] += OHB;
if (bti[1] >= OHB)
bti[1] -= OHB;
/* Iterate the 8 bins and add weighted contrib to each. */
int const xstride = OHB;
int const ystride = OHB * PXB;
for (int y = 0; y < 2; ++y)
for (int x = 0; x < 2; ++x)
for (int t = 0; t < 2; ++t)
{
if (bxi[x] < 0 || bxi[x] >= PXB
|| byi[y] < 0 || byi[y] >= PXB)
continue;
int idx = bti[t] + bxi[x] * xstride + byi[y] * ystride;
desc.data[idx] += contrib * weights[0][x]
* weights[1][y] * weights[2][t];
}
}
}
/* Normalize the feature vector. */
desc.data.normalize();
/* Truncate descriptor values to 0.2. */
for (int i = 0; i < PXB * PXB * OHB; ++i)
desc.data[i] = std::min(desc.data[i], 0.2f);
/* Normalize once again. */
desc.data.normalize();
return true;
}
/* ---------------------------------------------------------------- */
/*
* The scale of a keypoint is: scale = sigma0 * 2^(octave + (s+1)/S).
* sigma0 is the initial blur (1.6), octave the octave index of the
* keypoint (-1, 0, 1, ...) and scale space sample s in [-1,S+1] where
* S is the amount of samples per octave. Since the initial blur 1.6
* corresponds to scale space sample -1, we add 1 to the scale index.
*/
float
Sift::keypoint_relative_scale (Keypoint const& kp)
{
return this->options.base_blur_sigma * std::pow(2.0f,
(kp.sample + 1.0f) / this->options.num_samples_per_octave);
}
float
Sift::keypoint_absolute_scale (Keypoint const& kp)
{
return this->options.base_blur_sigma * std::pow(2.0f,
kp.octave + (kp.sample + 1.0f) / this->options.num_samples_per_octave);
}
/* ---------------------------------------------------------------- */
void
Sift::load_lowe_descriptors (std::string const& filename, Descriptors* result)
{
std::ifstream in(filename.c_str());
if (!in.good())
throw std::runtime_error("Cannot open descriptor file");
int num_descriptors;
int num_dimensions;
in >> num_descriptors >> num_dimensions;
if (num_descriptors > 100000 || num_dimensions != 128)
{
in.close();
throw std::runtime_error("Invalid number of descriptors/dimensions");
}
result->clear();
result->reserve(num_descriptors);
for (int i = 0; i < num_descriptors; ++i)
{
Sift::Descriptor descriptor;
in >> descriptor.y >> descriptor.x
>> descriptor.scale >> descriptor.orientation;
for (int j = 0; j < 128; ++j)
in >> descriptor.data[j];
descriptor.data.normalize();
result->push_back(descriptor);
}
if (!in.good())
{
result->clear();
in.close();
throw std::runtime_error("Error while reading descriptors");
}
in.close();
}
FEATURES_NAMESPACE_END
| [
"[email protected]"
] | |
a3e0e795c91fede0bf0f6ace87a8d4ffb9bbfd9c | 1cf5f0ca5ba9422dfc56ecc524bb72fd56e28312 | /CvGameCoreDLL/CvBuildingClasses.cpp | 057ebbc542195c5ad49cd11b4c244c6e4038a4c5 | [] | no_license | djcolumbia/Community-Patch-DLL | 46ea6f334b0a8c7c214e2cb5e89f3fa97fcffdf7 | a8a5c31bf86e327761ca9c3de3038e2a0b1c9ee7 | refs/heads/master | 2020-12-25T04:27:20.862151 | 2015-02-16T05:19:35 | 2015-02-16T05:19:35 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 86,045 | cpp | /* -------------------------------------------------------------------------------------------------------
© 1991-2012 Take-Two Interactive Software and its subsidiaries. Developed by Firaxis Games.
Sid Meier's Civilization V, Civ, Civilization, 2K Games, Firaxis Games, Take-Two Interactive Software
and their respective logos are all trademarks of Take-Two interactive Software, Inc.
All other marks and trademarks are the property of their respective owners.
All rights reserved.
------------------------------------------------------------------------------------------------------- */
#include "CvGameCoreDLLPCH.h"
#include "ICvDLLUserInterface.h"
#include "CvGameCoreUtils.h"
#include "CvInternalGameCoreUtils.h"
#include "FStlContainerSerialization.h"
#include "CvEnumSerialization.h"
#include "CvDLLUtilDefines.h"
#include "CvDllCity.h"
#include "CvDllPlot.h"
// include after all other headers
#include "LintFree.h"
/// Constructor
CvBuildingEntry::CvBuildingEntry(void):
m_iBuildingClassType(NO_BUILDINGCLASS),
m_pkBuildingClassInfo(NULL),
m_iNearbyTerrainRequired(NO_VICTORY),
m_iProhibitedCityTerrain(NO_VICTORY),
m_iVictoryPrereq(NO_VICTORY),
m_iFreeStartEra(NO_ERA),
m_iMaxStartEra(NO_ERA),
m_iObsoleteTech(NO_TECH),
m_iEnhancedYieldTech(NO_TECH),
m_iGoldMaintenance(0),
m_iMutuallyExclusiveGroup(0),
m_iReplacementBuildingClass(NO_BUILDINGCLASS),
m_iPrereqAndTech(NO_TECH),
m_iSpecialistType(NO_SPECIALIST),
m_iSpecialistCount(0),
m_iSpecialistExtraCulture(0),
m_iGreatPeopleRateChange(0),
m_iFreeBuildingClass(NO_BUILDINGCLASS),
m_iFreeBuildingThisCity(NO_BUILDINGCLASS),
m_iFreePromotion(NO_PROMOTION),
m_iTrainedFreePromotion(NO_PROMOTION),
m_iFreePromotionRemoved(NO_PROMOTION),
m_iProductionCost(0),
m_iNumCityCostMod(0),
m_iHurryCostModifier(0),
m_iNumCitiesPrereq(0),
m_iUnitLevelPrereq(0),
m_iJONSCulture(0),
m_iCultureRateModifier(0),
m_iGlobalCultureRateModifier(0),
m_iGreatPeopleRateModifier(0),
m_iGlobalGreatPeopleRateModifier(0),
m_iGreatGeneralRateModifier(0),
m_iGreatPersonExpendGold(0),
m_iUnitUpgradeCostMod(0),
m_iGoldenAgeModifier(0),
m_iFreeExperience(0),
m_iGlobalFreeExperience(0),
m_iFoodKept(0),
m_iAirlift(0),
m_iAirModifier(0),
m_iNukeModifier(0),
m_iNukeExplosionRand(0),
m_iWorkerSpeedModifier(0),
m_iMilitaryProductionModifier(0),
m_iSpaceProductionModifier(0),
m_iMinAreaSize(0),
m_iConquestProbability(0),
m_iHealRateChange(0),
m_iHappiness(0),
m_iUnmoddedHappiness(0),
m_iUnhappinessModifier(0),
m_iHappinessPerCity(0),
m_iHappinessPerXPolicies(0),
m_iCityCountUnhappinessMod(0),
m_bNoOccupiedUnhappiness(false),
m_iGlobalPopulationChange(0),
m_iTechShare(0),
m_iFreeTechs(0),
m_iFreePolicies(0),
m_iFreeGreatPeople(0),
m_iMedianTechPercentChange(0),
m_iGold(0),
m_bNearbyMountainRequired(false),
m_bAllowsRangeStrike(false),
m_iDefenseModifier(0),
m_iGlobalDefenseModifier(0),
m_iMissionType(NO_MISSION),
m_iMinorFriendshipChange(0),
m_iVictoryPoints(0),
m_iPreferredDisplayPosition(0),
m_iPortraitIndex(-1),
m_bTeamShare(false),
m_bWater(false),
m_bRiver(false),
m_bFreshWater(false),
m_bMountain(false),
m_bHill(false),
m_bFlat(false),
m_bFoundsReligion(false),
m_bIsReligious(false),
m_bBorderObstacle(false),
m_bPlayerBorderObstacle(false),
m_bCapital(false),
m_bGoldenAge(false),
m_bMapCentering(false),
m_bNeverCapture(false),
m_bNukeImmune(false),
m_bExtraLuxuries(false),
m_bDiplomaticVoting(false),
m_bAllowsWaterRoutes(false),
m_bCityWall(false),
m_piLockedBuildingClasses(NULL),
m_piPrereqAndTechs(NULL),
m_piResourceQuantityRequirements(NULL),
m_piResourceCultureChanges(NULL),
m_piProductionTraits(NULL),
m_piSeaPlotYieldChange(NULL),
m_piRiverPlotYieldChange(NULL),
m_piLakePlotYieldChange(NULL),
m_piSeaResourceYieldChange(NULL),
m_piYieldChange(NULL),
m_piYieldChangePerPop(NULL),
m_piYieldModifier(NULL),
m_piAreaYieldModifier(NULL),
m_piGlobalYieldModifier(NULL),
m_piTechEnhancedYieldChange(NULL),
m_piUnitCombatFreeExperience(NULL),
m_piUnitCombatProductionModifiers(NULL),
m_piDomainFreeExperience(NULL),
m_piDomainProductionModifier(NULL),
m_piPrereqNumOfBuildingClass(NULL),
m_piFlavorValue(NULL),
m_piLocalResourceAnds(NULL),
m_piLocalResourceOrs(NULL),
m_paiHurryModifier(NULL),
m_pbBuildingClassNeededInCity(NULL),
m_piNumFreeUnits(NULL),
m_bArtInfoEraVariation(false),
m_bArtInfoCulturalVariation(false),
m_bArtInfoRandomVariation(false),
m_ppaiResourceYieldChange(NULL),
m_ppaiFeatureYieldChange(NULL),
m_ppaiSpecialistYieldChange(NULL),
m_ppaiResourceYieldModifier(NULL)
{
}
/// Destructor
CvBuildingEntry::~CvBuildingEntry(void)
{
SAFE_DELETE_ARRAY(m_piLockedBuildingClasses);
SAFE_DELETE_ARRAY(m_piPrereqAndTechs);
SAFE_DELETE_ARRAY(m_piResourceQuantityRequirements);
SAFE_DELETE_ARRAY(m_piResourceCultureChanges);
SAFE_DELETE_ARRAY(m_piProductionTraits);
SAFE_DELETE_ARRAY(m_piSeaPlotYieldChange);
SAFE_DELETE_ARRAY(m_piRiverPlotYieldChange);
SAFE_DELETE_ARRAY(m_piLakePlotYieldChange);
SAFE_DELETE_ARRAY(m_piSeaResourceYieldChange);
SAFE_DELETE_ARRAY(m_piYieldChange);
SAFE_DELETE_ARRAY(m_piYieldChangePerPop);
SAFE_DELETE_ARRAY(m_piYieldModifier);
SAFE_DELETE_ARRAY(m_piAreaYieldModifier);
SAFE_DELETE_ARRAY(m_piGlobalYieldModifier);
SAFE_DELETE_ARRAY(m_piTechEnhancedYieldChange);
SAFE_DELETE_ARRAY(m_piUnitCombatFreeExperience);
SAFE_DELETE_ARRAY(m_piUnitCombatProductionModifiers);
SAFE_DELETE_ARRAY(m_piDomainFreeExperience);
SAFE_DELETE_ARRAY(m_piDomainProductionModifier);
SAFE_DELETE_ARRAY(m_piPrereqNumOfBuildingClass);
SAFE_DELETE_ARRAY(m_piFlavorValue);
SAFE_DELETE_ARRAY(m_piLocalResourceAnds);
SAFE_DELETE_ARRAY(m_piLocalResourceOrs);
SAFE_DELETE_ARRAY(m_paiHurryModifier);
SAFE_DELETE_ARRAY(m_pbBuildingClassNeededInCity);
SAFE_DELETE_ARRAY(m_piNumFreeUnits);
CvDatabaseUtility::SafeDelete2DArray( m_ppaiResourceYieldChange );
CvDatabaseUtility::SafeDelete2DArray( m_ppaiFeatureYieldChange );
CvDatabaseUtility::SafeDelete2DArray( m_ppaiSpecialistYieldChange );
CvDatabaseUtility::SafeDelete2DArray( m_ppaiResourceYieldModifier );
}
/// Read from XML file
bool CvBuildingEntry::CacheResults(Database::Results& kResults, CvDatabaseUtility& kUtility)
{
if (!CvBaseInfo::CacheResults(kResults, kUtility))
return false;
//Basic Properties
m_iGoldMaintenance = kResults.GetInt("GoldMaintenance");
m_iMutuallyExclusiveGroup = kResults.GetInt("MutuallyExclusiveGroup");
m_bTeamShare = kResults.GetBool("TeamShare");
m_bWater = kResults.GetBool("Water");
m_bRiver = kResults.GetBool("River");
m_bFreshWater = kResults.GetBool("FreshWater");
m_bMountain = kResults.GetBool("Mountain");
m_bHill = kResults.GetBool("Hill");
m_bFlat = kResults.GetBool("Flat");
m_bFoundsReligion = kResults.GetBool("FoundsReligion");
m_bIsReligious = kResults.GetBool("IsReligious");
m_bBorderObstacle = kResults.GetBool("BorderObstacle");
m_bPlayerBorderObstacle = kResults.GetBool("PlayerBorderObstacle");
m_bCapital = kResults.GetBool("Capital");
m_bGoldenAge = kResults.GetBool("GoldenAge");
m_bMapCentering = kResults.GetBool("MapCentering");
m_bNeverCapture = kResults.GetBool("NeverCapture");
m_bNukeImmune = kResults.GetBool("NukeImmune");
m_bCityWall = kResults.GetBool("CityWall");
m_bExtraLuxuries = kResults.GetBool("ExtraLuxuries");
m_bDiplomaticVoting = kResults.GetBool("DiplomaticVoting");
m_bAllowsWaterRoutes = kResults.GetBool("AllowsWaterRoutes");
m_iProductionCost = kResults.GetInt("Cost");
m_iNumCityCostMod = kResults.GetInt("NumCityCostMod");
m_iHurryCostModifier = kResults.GetInt("HurryCostModifier");
m_iMinAreaSize = kResults.GetInt("MinAreaSize");
m_iConquestProbability = kResults.GetInt("ConquestProb");
m_iNumCitiesPrereq = kResults.GetInt("CitiesPrereq");
m_iUnitLevelPrereq = kResults.GetInt("LevelPrereq");
m_iJONSCulture = kResults.GetInt("Culture");
m_iCultureRateModifier = kResults.GetInt("CultureRateModifier");
m_iGlobalCultureRateModifier = kResults.GetInt("GlobalCultureRateModifier");
m_iGreatPeopleRateModifier = kResults.GetInt("GreatPeopleRateModifier");
m_iGlobalGreatPeopleRateModifier = kResults.GetInt("GlobalGreatPeopleRateModifier");
m_iGreatGeneralRateModifier = kResults.GetInt("GreatGeneralRateModifier");
m_iGreatPersonExpendGold = kResults.GetInt("GreatPersonExpendGold");
m_iUnitUpgradeCostMod = kResults.GetInt("UnitUpgradeCostMod");
m_iGoldenAgeModifier = kResults.GetInt("GoldenAgeModifier");
m_iFreeExperience = kResults.GetInt("Experience");
m_iGlobalFreeExperience = kResults.GetInt("GlobalExperience");
m_iFoodKept = kResults.GetInt("FoodKept");
m_iAirlift = kResults.GetInt("Airlift");
m_iAirModifier = kResults.GetInt("AirModifier");
m_iNukeModifier = kResults.GetInt("NukeModifier");
m_iNukeExplosionRand = kResults.GetInt("NukeExplosionRand");
m_iHealRateChange = kResults.GetInt("HealRateChange");
m_iHappiness = kResults.GetInt("Happiness");
m_iUnmoddedHappiness = kResults.GetInt("UnmoddedHappiness");
m_iUnhappinessModifier = kResults.GetInt("UnhappinessModifier");
m_iHappinessPerCity = kResults.GetInt("HappinessPerCity");
m_iHappinessPerXPolicies = kResults.GetInt("HappinessPerXPolicies");
m_iCityCountUnhappinessMod = kResults.GetInt("CityCountUnhappinessMod");
m_bNoOccupiedUnhappiness = kResults.GetBool("NoOccupiedUnhappiness");
m_iWorkerSpeedModifier = kResults.GetInt("WorkerSpeedModifier");
m_iMilitaryProductionModifier = kResults.GetInt("MilitaryProductionModifier");
m_iSpaceProductionModifier = kResults.GetInt("SpaceProductionModifier");
m_iBuildingProductionModifier = kResults.GetInt("BuildingProductionModifier");
m_iWonderProductionModifier = kResults.GetInt("WonderProductionModifier");
m_iTradeRouteModifier = kResults.GetInt("TradeRouteModifier");
m_iCapturePlunderModifier = kResults.GetInt("CapturePlunderModifier");
m_iPolicyCostModifier = kResults.GetInt("PolicyCostModifier");
m_iPlotCultureCostModifier = kResults.GetInt("PlotCultureCostModifier");
m_iGlobalPlotCultureCostModifier = kResults.GetInt("GlobalPlotCultureCostModifier");
m_iPlotBuyCostModifier = kResults.GetInt("PlotBuyCostModifier");
m_iGlobalPlotBuyCostModifier = kResults.GetInt("GlobalPlotBuyCostModifier");
m_iGlobalPopulationChange = kResults.GetInt("GlobalPopulationChange");
m_iTechShare = kResults.GetInt("TechShare");
m_iFreeTechs = kResults.GetInt("FreeTechs");
m_iFreePolicies = kResults.GetInt("FreePolicies");
m_iFreeGreatPeople = kResults.GetInt("FreeGreatPeople");
m_iMedianTechPercentChange = kResults.GetInt("MedianTechPercentChange");
m_iGold = kResults.GetInt("Gold");
m_bNearbyMountainRequired = kResults.GetInt("NearbyMountainRequired");
m_bAllowsRangeStrike = kResults.GetInt("AllowsRangeStrike");
m_iDefenseModifier = kResults.GetInt("Defense");
m_iGlobalDefenseModifier = kResults.GetInt("GlobalDefenseMod");
m_iMinorFriendshipChange = kResults.GetInt("MinorFriendshipChange");
m_iVictoryPoints = kResults.GetInt("VictoryPoints");
m_iPreferredDisplayPosition = kResults.GetInt("DisplayPosition");
m_iPortraitIndex = kResults.GetInt("PortraitIndex");
m_bArtInfoCulturalVariation = kResults.GetBool("ArtInfoCulturalVariation");
m_bArtInfoEraVariation = kResults.GetBool("ArtInfoEraVariation");
m_bArtInfoRandomVariation = kResults.GetBool("ArtInfoRandomVariation");
//References
const char* szTextVal;
szTextVal = kResults.GetText("BuildingClass");
m_iBuildingClassType = GC.getInfoTypeForString(szTextVal, true);
//This may need to be deferred to a routine that is called AFTER pre-fetch has been called for all infos.
m_pkBuildingClassInfo = GC.getBuildingClassInfo(static_cast<BuildingClassTypes>(m_iBuildingClassType));
CvAssertMsg(m_pkBuildingClassInfo, "Could not find BuildingClassInfo for BuildingType. Have BuildingClasses been prefetched yet?");
szTextVal = kResults.GetText("ArtDefineTag");
SetArtDefineTag(szTextVal);
szTextVal = kResults.GetText("WonderSplashAudio");
m_strWonderSplashAudio = szTextVal;
szTextVal = kResults.GetText("NearbyTerrainRequired");
m_iNearbyTerrainRequired = GC.getInfoTypeForString(szTextVal, true);
szTextVal = kResults.GetText("ProhibitedCityTerrain");
m_iProhibitedCityTerrain = GC.getInfoTypeForString(szTextVal, true);
szTextVal = kResults.GetText("VictoryPrereq");
m_iVictoryPrereq = GC.getInfoTypeForString(szTextVal, true);
szTextVal = kResults.GetText("FreeStartEra");
m_iFreeStartEra = GC.getInfoTypeForString(szTextVal, true);
szTextVal = kResults.GetText("MaxStartEra");
m_iMaxStartEra = GC.getInfoTypeForString(szTextVal, true);
szTextVal = kResults.GetText("ObsoleteTech");
m_iObsoleteTech = GC.getInfoTypeForString(szTextVal, true);
szTextVal = kResults.GetText("EnhancedYieldTech");
m_iEnhancedYieldTech = GC.getInfoTypeForString(szTextVal, true);
szTextVal = kResults.GetText("FreeBuilding");
m_iFreeBuildingClass = GC.getInfoTypeForString(szTextVal, true);
szTextVal = kResults.GetText("FreeBuildingThisCity");
m_iFreeBuildingThisCity = GC.getInfoTypeForString(szTextVal, true);
szTextVal = kResults.GetText("FreePromotion");
m_iFreePromotion = GC.getInfoTypeForString(szTextVal, true);
szTextVal = kResults.GetText("TrainedFreePromotion");
m_iTrainedFreePromotion = GC.getInfoTypeForString(szTextVal, true);
szTextVal = kResults.GetText("FreePromotionRemoved");
m_iFreePromotionRemoved = GC.getInfoTypeForString(szTextVal, true);
szTextVal = kResults.GetText("ReplacementBuildingClass");
m_iReplacementBuildingClass= GC.getInfoTypeForString(szTextVal, true);
szTextVal = kResults.GetText("PrereqTech");
m_iPrereqAndTech = GC.getInfoTypeForString(szTextVal, true);
szTextVal = kResults.GetText("SpecialistType");
m_iSpecialistType = GC.getInfoTypeForString(szTextVal, true);
m_iSpecialistCount = kResults.GetInt("SpecialistCount");
m_iSpecialistExtraCulture = kResults.GetInt("SpecialistExtraCulture");
m_iGreatPeopleRateChange= kResults.GetInt("GreatPeopleRateChange");
//Arrays
const char* szBuildingType = GetType();
kUtility.SetFlavors(m_piFlavorValue, "Building_Flavors", "BuildingType", szBuildingType);
kUtility.SetYields(m_piSeaPlotYieldChange, "Building_SeaPlotYieldChanges", "BuildingType", szBuildingType);
kUtility.SetYields(m_piRiverPlotYieldChange, "Building_RiverPlotYieldChanges", "BuildingType", szBuildingType);
kUtility.SetYields(m_piLakePlotYieldChange, "Building_LakePlotYieldChanges", "BuildingType", szBuildingType);
kUtility.SetYields(m_piSeaResourceYieldChange, "Building_SeaResourceYieldChanges", "BuildingType", szBuildingType);
kUtility.SetYields(m_piYieldChange, "Building_YieldChanges", "BuildingType", szBuildingType);
kUtility.SetYields(m_piYieldChangePerPop, "Building_YieldChangesPerPop", "BuildingType", szBuildingType);
kUtility.SetYields(m_piYieldModifier, "Building_YieldModifiers", "BuildingType", szBuildingType);
kUtility.SetYields(m_piAreaYieldModifier, "Building_AreaYieldModifiers", "BuildingType", szBuildingType);
kUtility.SetYields(m_piGlobalYieldModifier, "Building_GlobalYieldModifiers", "BuildingType", szBuildingType);
kUtility.SetYields(m_piTechEnhancedYieldChange, "Building_TechEnhancedYieldChanges", "BuildingType", szBuildingType);
kUtility.PopulateArrayByValue(m_piResourceQuantityRequirements, "Resources", "Building_ResourceQuantityRequirements", "ResourceType", "BuildingType", szBuildingType, "Cost");
kUtility.PopulateArrayByValue(m_piResourceCultureChanges, "Resources", "Building_ResourceCultureChanges", "ResourceType", "BuildingType", szBuildingType, "CultureChange");
kUtility.PopulateArrayByValue(m_paiHurryModifier, "HurryInfos", "Building_HurryModifiers", "HurryType", "BuildingType", szBuildingType, "HurryCostModifier");
//kUtility.PopulateArrayByValue(m_piProductionTraits, "Traits", "Building_ProductionTraits", "TraitType", "BuildingType", szBuildingType, "Trait");
kUtility.PopulateArrayByValue(m_piUnitCombatFreeExperience, "UnitCombatInfos", "Building_UnitCombatFreeExperiences", "UnitCombatType", "BuildingType", szBuildingType, "Experience");
kUtility.PopulateArrayByValue(m_piUnitCombatProductionModifiers, "UnitCombatInfos", "Building_UnitCombatProductionModifiers", "UnitCombatType", "BuildingType", szBuildingType, "Modifier");
kUtility.PopulateArrayByValue(m_piDomainFreeExperience, "Domains", "Building_DomainFreeExperiences", "DomainType", "BuildingType", szBuildingType, "Experience", 0, NUM_DOMAIN_TYPES);
kUtility.PopulateArrayByValue(m_piDomainProductionModifier, "Domains", "Building_DomainProductionModifiers", "DomainType", "BuildingType", szBuildingType, "Modifier", 0, NUM_DOMAIN_TYPES);
kUtility.PopulateArrayByValue(m_piPrereqNumOfBuildingClass, "BuildingClasses", "Building_PrereqBuildingClasses", "BuildingClassType", "BuildingType", szBuildingType, "NumBuildingNeeded");
kUtility.PopulateArrayByExistence(m_pbBuildingClassNeededInCity, "BuildingClasses", "Building_ClassesNeededInCity", "BuildingClassType", "BuildingType", szBuildingType);
//kUtility.PopulateArrayByExistence(m_piNumFreeUnits, "Units", "Building_FreeUnits", "UnitType", "BuildingType", szBuildingType);
kUtility.PopulateArrayByValue(m_piNumFreeUnits, "Units", "Building_FreeUnits", "UnitType", "BuildingType", szBuildingType, "NumUnits");
kUtility.PopulateArrayByExistence(m_piLockedBuildingClasses, "BuildingClasses", "Building_LockedBuildingClasses", "BuildingClassType", "BuildingType", szBuildingType);
kUtility.PopulateArrayByExistence(m_piPrereqAndTechs, "Technologies", "Building_TechAndPrereqs", "TechType", "BuildingType", szBuildingType);
kUtility.PopulateArrayByExistence(m_piLocalResourceAnds, "Resources", "Building_LocalResourceAnds", "ResourceType", "BuildingType", szBuildingType);
kUtility.PopulateArrayByExistence(m_piLocalResourceOrs, "Resources", "Building_LocalResourceOrs", "ResourceType", "BuildingType", szBuildingType);
//ResourceYieldChanges
{
kUtility.Initialize2DArray(m_ppaiResourceYieldChange, "Resources", "Yields");
std::string strKey("Building_ResourceYieldChanges");
Database::Results* pResults = kUtility.GetResults(strKey);
if(pResults == NULL)
{
pResults = kUtility.PrepareResults(strKey, "select Resources.ID as ResourceID, Yields.ID as YieldID, Yield from Building_ResourceYieldChanges inner join Resources on Resources.Type = ResourceType inner join Yields on Yields.Type = YieldType where BuildingType = ?");
}
pResults->Bind(1, szBuildingType);
while(pResults->Step())
{
const int ResourceID = pResults->GetInt(0);
const int YieldID = pResults->GetInt(1);
const int yield = pResults->GetInt(2);
m_ppaiResourceYieldChange[ResourceID][YieldID] = yield;
}
}
//FeatureYieldChanges
{
kUtility.Initialize2DArray(m_ppaiFeatureYieldChange, "Features", "Yields");
std::string strKey("Building_FeatureYieldChanges");
Database::Results* pResults = kUtility.GetResults(strKey);
if(pResults == NULL)
{
pResults = kUtility.PrepareResults(strKey, "select Features.ID as FeatureID, Yields.ID as YieldID, Yield from Building_FeatureYieldChanges inner join Features on Features.Type = FeatureType inner join Yields on Yields.Type = YieldType where BuildingType = ?");
}
pResults->Bind(1, szBuildingType);
while(pResults->Step())
{
const int FeatureID = pResults->GetInt(0);
const int YieldID = pResults->GetInt(1);
const int yield = pResults->GetInt(2);
m_ppaiFeatureYieldChange[FeatureID][YieldID] = yield;
}
}
//SpecialistYieldChanges
{
kUtility.Initialize2DArray(m_ppaiSpecialistYieldChange, "Specialists", "Yields");
std::string strKey("Building_SpecialistYieldChanges");
Database::Results* pResults = kUtility.GetResults(strKey);
if(pResults == NULL)
{
pResults = kUtility.PrepareResults(strKey, "select Specialists.ID as SpecialistID, Yields.ID as YieldID, Yield from Building_SpecialistYieldChanges inner join Specialists on Specialists.Type = SpecialistType inner join Yields on Yields.Type = YieldType where BuildingType = ?");
}
pResults->Bind(1, szBuildingType);
while(pResults->Step())
{
const int SpecialistID = pResults->GetInt(0);
const int YieldID = pResults->GetInt(1);
const int yield = pResults->GetInt(2);
m_ppaiSpecialistYieldChange[SpecialistID][YieldID] = yield;
}
}
//ResourceYieldModifiers
{
kUtility.Initialize2DArray(m_ppaiResourceYieldModifier, "Resources", "Yields");
std::string strKey("Building_ResourceYieldModifiers");
Database::Results* pResults = kUtility.GetResults(strKey);
if(pResults == NULL)
{
pResults = kUtility.PrepareResults(strKey, "select Resources.ID as ResourceID, Yields.ID as YieldID, Yield from Building_ResourceYieldModifiers inner join Resources on Resources.Type = ResourceType inner join Yields on Yields.Type = YieldType where BuildingType = ?");
}
pResults->Bind(1, szBuildingType);
while(pResults->Step())
{
const int ResourceID = pResults->GetInt(0);
const int YieldID = pResults->GetInt(1);
const int yield = pResults->GetInt(2);
m_ppaiResourceYieldModifier[ResourceID][YieldID] = yield;
}
}
return true;
}
/// Class of this building
int CvBuildingEntry::GetBuildingClassType() const
{
return m_iBuildingClassType;
}
const CvBuildingClassInfo& CvBuildingEntry::GetBuildingClassInfo() const
{
if(m_pkBuildingClassInfo == NULL)
{
const char* szError = "ERROR: Building does not contain valid BuildingClass type!!";
GC.LogMessage(szError);
CvAssertMsg(false, szError);
}
#pragma warning ( push )
#pragma warning ( disable : 6011 ) // Dereferencing NULL pointer
return *m_pkBuildingClassInfo;
#pragma warning ( pop )
}
/// Does this building require a city built on or next to a specific terrain type?
int CvBuildingEntry::GetNearbyTerrainRequired() const
{
return m_iNearbyTerrainRequired;
}
/// Does this building need the absence of a terrain under the city?
int CvBuildingEntry::GetProhibitedCityTerrain() const
{
return m_iProhibitedCityTerrain;
}
/// Does a Victory need to be active for this building to be buildable?
int CvBuildingEntry::GetVictoryPrereq() const
{
return m_iVictoryPrereq;
}
/// Do you get this building for free if start in a later era?
int CvBuildingEntry::GetFreeStartEra() const
{
return m_iFreeStartEra;
}
/// Is this building unbuildable if start in a later era?
int CvBuildingEntry::GetMaxStartEra() const
{
return m_iMaxStartEra;
}
/// Tech that makes this building obsolete
int CvBuildingEntry::GetObsoleteTech() const
{
return m_iObsoleteTech;
}
/// Tech that improves the yield from this building
int CvBuildingEntry::GetEnhancedYieldTech() const
{
return m_iEnhancedYieldTech;
}
/// How much GPT does this Building cost?
int CvBuildingEntry::GetGoldMaintenance() const
{
return m_iGoldMaintenance;
}
/// Only one Building from each Group may be constructed in a City
int CvBuildingEntry::GetMutuallyExclusiveGroup() const
{
return m_iMutuallyExclusiveGroup;
}
/// Upgraded version of this building
int CvBuildingEntry::GetReplacementBuildingClass() const
{
return m_iReplacementBuildingClass;
}
/// Techs required for this building
int CvBuildingEntry::GetPrereqAndTech() const
{
return m_iPrereqAndTech;
}
/// What SpecialistType is allowed by this Building
int CvBuildingEntry::GetSpecialistType() const
{
return m_iSpecialistType;
}
/// How many SpecialistTypes are allowed by this Building
int CvBuildingEntry::GetSpecialistCount() const
{
return m_iSpecialistCount;
}
/// Extra culture from every specialist
int CvBuildingEntry::GetSpecialistExtraCulture() const
{
return m_iSpecialistExtraCulture;
}
/// How many GPP does this Building provide (linked to the SpecialistType)
int CvBuildingEntry::GetGreatPeopleRateChange() const
{
return m_iGreatPeopleRateChange;
}
/// Free building in each city from this building/wonder
int CvBuildingEntry::GetFreeBuildingClass() const
{
return m_iFreeBuildingClass;
}
/// Free building in the city that builds this building/wonder
int CvBuildingEntry::GetFreeBuildingThisCity() const
{
return m_iFreeBuildingThisCity;
}
/// Does this building give all units a promotion for free instantly?
int CvBuildingEntry::GetFreePromotion() const
{
return m_iFreePromotion;
}
/// Does this building give units a promotion when trained from this city?
int CvBuildingEntry::GetTrainedFreePromotion() const
{
return m_iTrainedFreePromotion;
}
/// Does this building get rid of an undesirable promotion?
int CvBuildingEntry::GetFreePromotionRemoved() const
{
return m_iFreePromotionRemoved;
}
/// Shields to construct the building
int CvBuildingEntry::GetProductionCost() const
{
return m_iProductionCost;
}
/// Additional cost based on the number of cities in the empire
int CvBuildingEntry::GetNumCityCostMod() const
{
return m_iNumCityCostMod;
}
/// Does this Building modify any hurry costs
int CvBuildingEntry::GetHurryCostModifier() const
{
return m_iHurryCostModifier;
}
/// Number of cities required to build this?
int CvBuildingEntry::GetNumCitiesPrereq() const
{
return m_iNumCitiesPrereq;
}
/// Do we need a unit at a certain level to build this?
int CvBuildingEntry::GetUnitLevelPrereq() const
{
return m_iUnitLevelPrereq;
}
// Culture (for policies) generated per turn
int CvBuildingEntry::GetJONSCulture() const
{
return m_iJONSCulture;
}
/// Multiplier to the rate of accumulating culture for policies
int CvBuildingEntry::GetCultureRateModifier() const
{
return m_iCultureRateModifier;
}
/// Multiplier to the rate of accumulating culture for policies in all Cities
int CvBuildingEntry::GetGlobalCultureRateModifier() const
{
return m_iGlobalCultureRateModifier;
}
/// Change in spawn rate for great people
int CvBuildingEntry::GetGreatPeopleRateModifier() const
{
return m_iGreatPeopleRateModifier;
}
/// Change global spawn rate for great people
int CvBuildingEntry::GetGlobalGreatPeopleRateModifier() const
{
return m_iGlobalGreatPeopleRateModifier;
}
/// Change in spawn rate for great generals
int CvBuildingEntry::GetGreatGeneralRateModifier() const
{
return m_iGreatGeneralRateModifier;
}
/// Gold received when great person expended
int CvBuildingEntry::GetGreatPersonExpendGold() const
{
return m_iGreatPersonExpendGold;
}
/// Reduces cost of unit upgrades?
int CvBuildingEntry::GetUnitUpgradeCostMod() const
{
return m_iUnitUpgradeCostMod;
}
/// Percentage increase in the length of Golden Ages
int CvBuildingEntry::GetGoldenAgeModifier() const
{
return m_iGoldenAgeModifier;
}
/// Free experience for units built in this city
int CvBuildingEntry::GetFreeExperience() const
{
return m_iFreeExperience;
}
/// Free experience for all player units
int CvBuildingEntry::GetGlobalFreeExperience() const
{
return m_iGlobalFreeExperience;
}
/// Percentage of food retained after city growth
int CvBuildingEntry::GetFoodKept() const
{
return m_iFoodKept;
}
/// Does this building allow airlifts?
int CvBuildingEntry::GetAirlift() const
{
return m_iAirlift;
}
/// Modifier to city air defense
int CvBuildingEntry::GetAirModifier() const
{
return m_iAirModifier;
}
/// Modifier to city nuke defense
int CvBuildingEntry::GetNukeModifier() const
{
return m_iNukeModifier;
}
/// Will this building cause a big problem (meltdown) if the city is hit with a nuke?
int CvBuildingEntry::GetNukeExplosionRand() const
{
return m_iNukeExplosionRand;
}
/// Improvement in worker speed
int CvBuildingEntry::GetWorkerSpeedModifier() const
{
return m_iWorkerSpeedModifier;
}
/// Improvement in military unit production
int CvBuildingEntry::GetMilitaryProductionModifier() const
{
return m_iMilitaryProductionModifier;
}
/// Improvement in space race component production
int CvBuildingEntry::GetSpaceProductionModifier() const
{
return m_iSpaceProductionModifier;
}
/// Improvement in building production
int CvBuildingEntry::GetBuildingProductionModifier() const
{
return m_iBuildingProductionModifier;
}
/// Improvement in wonder production
int CvBuildingEntry::GetWonderProductionModifier() const
{
return m_iWonderProductionModifier;
}
/// Trade route gold modifier
int CvBuildingEntry::GetTradeRouteModifier() const
{
return m_iTradeRouteModifier;
}
/// Increased plunder if city captured
int CvBuildingEntry::GetCapturePlunderModifier() const
{
return m_iCapturePlunderModifier;
}
/// Change in culture cost to earn a new policy
int CvBuildingEntry::GetPolicyCostModifier() const
{
return m_iPolicyCostModifier;
}
/// Change in culture cost to earn a new tile
int CvBuildingEntry::GetPlotCultureCostModifier() const
{
return m_iPlotCultureCostModifier;
}
/// Change in culture cost to earn a new tile
int CvBuildingEntry::GetGlobalPlotCultureCostModifier() const
{
return m_iGlobalPlotCultureCostModifier;
}
/// Change in gold cost to earn a new tile
int CvBuildingEntry::GetPlotBuyCostModifier() const
{
return m_iPlotBuyCostModifier;
}
/// Change in gold cost to earn a new tile across the empire
int CvBuildingEntry::GetGlobalPlotBuyCostModifier() const
{
return m_iGlobalPlotBuyCostModifier;
}
/// Required Plot count of the CvArea this City belongs to (Usually used for Water Buildings to prevent Harbors in tiny lakes and such)
int CvBuildingEntry::GetMinAreaSize() const
{
return m_iMinAreaSize;
}
/// Chance of building surviving after conquest
int CvBuildingEntry::GetConquestProbability() const
{
return m_iConquestProbability;
}
/// Improvement in unit heal rate from this building
int CvBuildingEntry::GetHealRateChange() const
{
return m_iHealRateChange;
}
/// Happiness provided by this building
int CvBuildingEntry::GetHappiness() const
{
return m_iHappiness;
}
/// UnmoddedHappiness provided by this building - NOT affected by a city's pop
int CvBuildingEntry::GetUnmoddedHappiness() const
{
return m_iUnmoddedHappiness;
}
/// Get percentage modifier to overall player happiness
int CvBuildingEntry::GetUnhappinessModifier() const
{
return m_iUnhappinessModifier;
}
/// HappinessPerCity provided by this building
int CvBuildingEntry::GetHappinessPerCity() const
{
return m_iHappinessPerCity;
}
/// Happiness per X number of Policies provided by this building
int CvBuildingEntry::GetHappinessPerXPolicies() const
{
return m_iHappinessPerXPolicies;
}
/// CityCountUnhappinessMod provided by this building
int CvBuildingEntry::GetCityCountUnhappinessMod() const
{
return m_iCityCountUnhappinessMod;
}
/// NoOccupiedUnhappiness
bool CvBuildingEntry::IsNoOccupiedUnhappiness() const
{
return m_bNoOccupiedUnhappiness;
}
/// Population added to every City in the player's empire
int CvBuildingEntry::GetGlobalPopulationChange() const
{
return m_iGlobalPopulationChange;
}
/// If this # of players have a Tech then the owner of this Building gets that Tech as well
int CvBuildingEntry::GetTechShare() const
{
return m_iTechShare;
}
/// Number of free techs granted by this building
int CvBuildingEntry::GetFreeTechs() const
{
return m_iFreeTechs;
}
/// Number of free Policies granted by this building
int CvBuildingEntry::GetFreePolicies() const
{
return m_iFreePolicies;
}
/// Number of free Great People granted by this building
int CvBuildingEntry::GetFreeGreatPeople() const
{
return m_iFreeGreatPeople;
}
/// Boost to median tech received from research agreements
int CvBuildingEntry::GetMedianTechPercentChange() const
{
return m_iMedianTechPercentChange;
}
/// Gold generated by this building
int CvBuildingEntry::GetGold() const
{
return m_iGold;
}
/// Does a city need to be near a mountain to build this?
bool CvBuildingEntry::IsNearbyMountainRequired() const
{
return m_bNearbyMountainRequired;
}
/// Does this Building allow us to Range Strike?
bool CvBuildingEntry::IsAllowsRangeStrike() const
{
return m_bAllowsRangeStrike;
}
/// Modifier to city defense
int CvBuildingEntry::GetDefenseModifier() const
{
return m_iDefenseModifier;
}
/// Modifier to every City's Building defense
int CvBuildingEntry::GetGlobalDefenseModifier() const
{
return m_iGlobalDefenseModifier;
}
/// Instant Friendship mod change with City States
int CvBuildingEntry::GetMinorFriendshipChange() const
{
return m_iMinorFriendshipChange;
}
/// VPs added to overall Team score
int CvBuildingEntry::GetVictoryPoints() const
{
return m_iVictoryPoints;
}
/// wWhat ring the engine will try to display this building
int CvBuildingEntry::GetPreferredDisplayPosition() const
{
return m_iPreferredDisplayPosition;
}
/// index of portrait in the texture sheet
int CvBuildingEntry::GetPortraitIndex() const
{
return m_iPortraitIndex;
}
/// Is the presence of this building shared with team allies?
bool CvBuildingEntry::IsTeamShare() const
{
return m_bTeamShare;
}
/// Must this be built in a coastal city?
bool CvBuildingEntry::IsWater() const
{
return m_bWater;
}
/// Must this be built in a river city?
bool CvBuildingEntry::IsRiver() const
{
return m_bRiver;
}
/// Must this be built in a city next to FreshWater?
bool CvBuildingEntry::IsFreshWater() const
{
return m_bFreshWater;
}
/// Must this be built in a city next to Mountain?
bool CvBuildingEntry::IsMountain() const
{
return m_bMountain;
}
/// Must this be built in a city on a hill?
bool CvBuildingEntry::IsHill() const
{
return m_bHill;
}
/// Must this be built in a city on Flat ground?
bool CvBuildingEntry::IsFlat() const
{
return m_bFlat;
}
/// Does this Building Found a Religion?
bool CvBuildingEntry::IsFoundsReligion() const
{
return m_bFoundsReligion;
}
/// Is this a "Religous" Building? (qualifies it for Production bonuses for Policies, etc.)
bool CvBuildingEntry::IsReligious() const
{
return m_bIsReligious;
}
/// Is this an obstacle at the edge of your empire (e.g. Great Wall) -- for you AND your teammates
bool CvBuildingEntry::IsBorderObstacle() const
{
return m_bBorderObstacle;
}
/// Is this an obstacle at the edge of your empire (e.g. Great Wall) -- for just the owning player
bool CvBuildingEntry::IsPlayerBorderObstacle() const
{
return m_bPlayerBorderObstacle;
}
/// Does this trigger drawing a wall around the city
bool CvBuildingEntry::IsCityWall() const
{
return m_bCityWall;
}
/// Does this building define the capital?
bool CvBuildingEntry::IsCapital() const
{
return m_bCapital;
}
/// Does this building spawn a golden age?
bool CvBuildingEntry::IsGoldenAge() const
{
return m_bGoldenAge;
}
/// Is the map centered after this building is constructed?
bool CvBuildingEntry::IsMapCentering() const
{
return m_bMapCentering;
}
/// Can this building never be captured?
bool CvBuildingEntry::IsNeverCapture() const
{
return m_bNeverCapture;
}
/// Is the building immune to nukes?
bool CvBuildingEntry::IsNukeImmune() const
{
return m_bNukeImmune;
}
/// Does the building add an additional of each luxury in city radius
bool CvBuildingEntry::IsExtraLuxuries() const
{
return m_bExtraLuxuries;
}
/// Begins voting for the diplo victory?
bool CvBuildingEntry::IsDiplomaticVoting() const
{
return m_bDiplomaticVoting;
}
/// Does the building allow routes over the water
bool CvBuildingEntry::AllowsWaterRoutes() const
{
return m_bAllowsWaterRoutes;
}
/// Derive property: is this considered a science building?
bool CvBuildingEntry::IsScienceBuilding() const
{
bool bRtnValue = false;
if (IsCapital())
{
bRtnValue = false;
}
else if (GetYieldChange(YIELD_SCIENCE) > 0)
{
bRtnValue = true;
}
else if (GetYieldChangePerPop(YIELD_SCIENCE) > 0)
{
bRtnValue = true;
}
else if (GetTechEnhancedYieldChange(YIELD_SCIENCE) > 0)
{
bRtnValue = true;
}
else if (GetYieldModifier(YIELD_SCIENCE) > 0)
{
bRtnValue = true;
}
return bRtnValue;
}
/// Retrieve art tag
const char* CvBuildingEntry::GetArtDefineTag() const
{
return m_strArtDefineTag.c_str();
}
/// Set art tag
void CvBuildingEntry::SetArtDefineTag(const char* szVal)
{
m_strArtDefineTag = szVal;
}
/// Return whether we should try to find a culture specific variant art tag
const bool CvBuildingEntry::GetArtInfoCulturalVariation() const
{
return m_bArtInfoCulturalVariation;
}
/// Return whether we should try to find an era specific variant art tag
const bool CvBuildingEntry::GetArtInfoEraVariation() const
{
return m_bArtInfoEraVariation;
}
/// Return whether we should try to find an era specific variant art tag
const bool CvBuildingEntry::GetArtInfoRandomVariation() const
{
return m_bArtInfoRandomVariation;
}
const char* CvBuildingEntry::GetWonderSplashAudio () const
{
return m_strWonderSplashAudio.c_str();
}
// ARRAYS
/// Change to yield by type
int CvBuildingEntry::GetYieldChange(int i) const
{
CvAssertMsg(i < NUM_YIELD_TYPES, "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
return m_piYieldChange ? m_piYieldChange[i] : -1;
}
/// Array of yield changes
int* CvBuildingEntry::GetYieldChangeArray() const
{
return m_piYieldChange;
}
/// Change to yield by type
int CvBuildingEntry::GetYieldChangePerPop(int i) const
{
CvAssertMsg(i < NUM_YIELD_TYPES, "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
return m_piYieldChangePerPop ? m_piYieldChangePerPop[i] : -1;
}
/// Array of yield changes
int* CvBuildingEntry::GetYieldChangePerPopArray() const
{
return m_piYieldChangePerPop;
}
/// Modifier to yield by type
int CvBuildingEntry::GetYieldModifier(int i) const
{
CvAssertMsg(i < NUM_YIELD_TYPES, "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
return m_piYieldModifier ? m_piYieldModifier[i] : -1;
}
/// Array of yield modifiers
int* CvBuildingEntry::GetYieldModifierArray() const
{
return m_piYieldModifier;
}
/// Modifier to yield by type in area
int CvBuildingEntry::GetAreaYieldModifier(int i) const
{
CvAssertMsg(i < NUM_YIELD_TYPES, "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
return m_piAreaYieldModifier ? m_piAreaYieldModifier[i] : -1;
}
/// Array of yield modifiers in area
int* CvBuildingEntry::GetAreaYieldModifierArray() const
{
return m_piAreaYieldModifier;
}
/// Global modifier to yield by type
int CvBuildingEntry::GetGlobalYieldModifier(int i) const
{
CvAssertMsg(i < NUM_YIELD_TYPES, "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
return m_piGlobalYieldModifier ? m_piGlobalYieldModifier[i] : -1;
}
/// Array of global yield modifiers
int* CvBuildingEntry::GetGlobalYieldModifierArray() const
{
return m_piGlobalYieldModifier;
}
/// Change to yield based on earning a tech
int CvBuildingEntry::GetTechEnhancedYieldChange(int i) const
{
CvAssertMsg(i < NUM_YIELD_TYPES, "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
return m_piTechEnhancedYieldChange ? m_piTechEnhancedYieldChange[i] : -1;
}
/// Array of yield changes based on earning a tech
int* CvBuildingEntry::GetTechEnhancedYieldChangeArray() const
{
return m_piTechEnhancedYieldChange;
}
/// Sea plot yield changes by type
int CvBuildingEntry::GetSeaPlotYieldChange(int i) const
{
CvAssertMsg(i < NUM_YIELD_TYPES, "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
return m_piSeaPlotYieldChange ? m_piSeaPlotYieldChange[i] : -1;
}
/// Array of sea plot yield changes
int* CvBuildingEntry::GetSeaPlotYieldChangeArray() const
{
return m_piSeaPlotYieldChange;
}
/// River plot yield changes by type
int CvBuildingEntry::GetRiverPlotYieldChange(int i) const
{
CvAssertMsg(i < NUM_YIELD_TYPES, "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
return m_piRiverPlotYieldChange ? m_piRiverPlotYieldChange[i] : -1;
}
/// Array of river plot yield changes
int* CvBuildingEntry::GetRiverPlotYieldChangeArray() const
{
return m_piRiverPlotYieldChange;
}
/// Lake plot yield changes by type
int CvBuildingEntry::GetLakePlotYieldChange(int i) const
{
CvAssertMsg(i < NUM_YIELD_TYPES, "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
return m_piLakePlotYieldChange ? m_piLakePlotYieldChange[i] : -1;
}
/// Array of lake plot yield changes
int* CvBuildingEntry::GetLakePlotYieldChangeArray() const
{
return m_piLakePlotYieldChange;
}
/// Sea resource yield changes by type
int CvBuildingEntry::GetSeaResourceYieldChange(int i) const
{
CvAssertMsg(i < NUM_YIELD_TYPES, "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
return m_piSeaResourceYieldChange ? m_piSeaResourceYieldChange[i] : -1;
}
/// Array of sea resource yield changes
int* CvBuildingEntry::GetSeaResourceYieldChangeArray() const
{
return m_piSeaResourceYieldChange;
}
/// Free combat experience by unit combat type
int CvBuildingEntry::GetUnitCombatFreeExperience(int i) const
{
CvAssertMsg(i < GC.getNumUnitCombatClassInfos(), "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
return m_piUnitCombatFreeExperience ? m_piUnitCombatFreeExperience[i] : -1;
}
/// Free combat experience by unit combat type
int CvBuildingEntry::GetUnitCombatProductionModifier(int i) const
{
CvAssertMsg(i < GC.getNumUnitCombatClassInfos(), "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
return m_piUnitCombatProductionModifiers ? m_piUnitCombatProductionModifiers[i] : -1;
}
/// Free experience gained for units in this domain
int CvBuildingEntry::GetDomainFreeExperience(int i) const
{
CvAssertMsg(i < NUM_DOMAIN_TYPES, "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
return m_piDomainFreeExperience ? m_piDomainFreeExperience[i] : -1;
}
/// Production modifier in this domain
int CvBuildingEntry::GetDomainProductionModifier(int i) const
{
CvAssertMsg(i < NUM_DOMAIN_TYPES, "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
return m_piDomainProductionModifier ? m_piDomainProductionModifier[i] : -1;
}
/// BuildingClasses that may no longer be constructed after this Building is built in a City
int CvBuildingEntry::GetLockedBuildingClasses(int i) const
{
CvAssertMsg(i < GC.getNumBuildingClassInfos(), "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
return m_piLockedBuildingClasses ? m_piLockedBuildingClasses[i] : -1;
}
/// Prerequisite techs with AND
int CvBuildingEntry::GetPrereqAndTechs(int i) const
{
CvAssertMsg(i < GC.getNUM_BUILDING_AND_TECH_PREREQS(), "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
return m_piPrereqAndTechs ? m_piPrereqAndTechs[i] : -1;
}
/// Resources consumed to construct
int CvBuildingEntry::GetResourceQuantityRequirement(int i) const
{
CvAssertMsg(i < GC.getNumResourceInfos(), "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
return m_piResourceQuantityRequirements ? m_piResourceQuantityRequirements[i] : -1;
}
/// Boost in Culture for each of these Resources
int CvBuildingEntry::GetResourceCultureChange(int i) const
{
CvAssertMsg(i < GC.getNumResourceInfos(), "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
return m_piResourceCultureChanges ? m_piResourceCultureChanges[i] : -1;
}
/// Boost in production for leader with this trait
int CvBuildingEntry::GetProductionTraits(int i) const
{
CvAssertMsg(i < GC.getNumTraitInfos(), "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
return m_piProductionTraits ? m_piProductionTraits[i] : 0;
}
/// Number of prerequisite buildings of a particular class
int CvBuildingEntry::GetPrereqNumOfBuildingClass(int i) const
{
CvAssertMsg(i < GC.getNumBuildingClassInfos(), "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
return m_piPrereqNumOfBuildingClass ? m_piPrereqNumOfBuildingClass[i] : -1;
}
/// Find value of flavors associated with this building
int CvBuildingEntry::GetFlavorValue(int i) const
{
CvAssertMsg(i < GC.getNumFlavorTypes(), "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
return m_piFlavorValue ? m_piFlavorValue[i] : 0;
}
/// Prerequisite resources with AND
int CvBuildingEntry::GetLocalResourceAnd(int i) const
{
CvAssertMsg(i < GC.getNUM_BUILDING_RESOURCE_PREREQS(), "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
return m_piLocalResourceAnds ? m_piLocalResourceAnds[i] : -1;
}
/// Prerequisite resources with OR
int CvBuildingEntry::GetLocalResourceOr(int i) const
{
CvAssertMsg(i < GC.getNUM_BUILDING_RESOURCE_PREREQS(), "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
return m_piLocalResourceOrs ? m_piLocalResourceOrs[i] : -1;
}
/// Modifier to Hurry cost
int CvBuildingEntry::GetHurryModifier(int i) const
{
CvAssertMsg(i < GC.getNumHurryInfos(), "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
return m_paiHurryModifier ? m_paiHurryModifier[i] : -1;
}
/// Can it only built if there is a building of this class in the city?
bool CvBuildingEntry::IsBuildingClassNeededInCity(int i) const
{
CvAssertMsg(i < GC.getNumBuildingClassInfos(), "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
return m_pbBuildingClassNeededInCity ? m_pbBuildingClassNeededInCity[i] : false;
}
/// Free units which appear near the capital
int CvBuildingEntry::GetNumFreeUnits(int i) const
{
CvAssertMsg(i < GC.getNumUnitInfos(), "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
return m_piNumFreeUnits ? m_piNumFreeUnits[i] : -1;
}
/// Change to Resource yield by type
int CvBuildingEntry::GetResourceYieldChange(int i, int j) const
{
CvAssertMsg(i < GC.getNumResourceInfos(), "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
CvAssertMsg(j < NUM_YIELD_TYPES, "Index out of bounds");
CvAssertMsg(j > -1, "Index out of bounds");
return m_ppaiResourceYieldChange ? m_ppaiResourceYieldChange[i][j] : -1;
}
/// Array of changes to Resource yield
int* CvBuildingEntry::GetResourceYieldChangeArray(int i) const
{
CvAssertMsg(i < GC.getNumResourceInfos(), "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
return m_ppaiResourceYieldChange[i];
}
/// Change to Feature yield by type
int CvBuildingEntry::GetFeatureYieldChange(int i, int j) const
{
CvAssertMsg(i < GC.getNumFeatureInfos(), "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
CvAssertMsg(j < NUM_YIELD_TYPES, "Index out of bounds");
CvAssertMsg(j > -1, "Index out of bounds");
return m_ppaiFeatureYieldChange ? m_ppaiFeatureYieldChange[i][j] : -1;
}
/// Array of changes to Feature yield
int* CvBuildingEntry::GetFeatureYieldChangeArray(int i) const
{
CvAssertMsg(i < GC.getNumFeatureInfos(), "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
return m_ppaiFeatureYieldChange[i];
}
/// Change to specialist yield by type
int CvBuildingEntry::GetSpecialistYieldChange(int i, int j) const
{
CvAssertMsg(i < GC.getNumSpecialistInfos(), "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
CvAssertMsg(j < NUM_YIELD_TYPES, "Index out of bounds");
CvAssertMsg(j > -1, "Index out of bounds");
return m_ppaiSpecialistYieldChange ? m_ppaiSpecialistYieldChange[i][j] : -1;
}
/// Array of changes to specialist yield
int* CvBuildingEntry::GetSpecialistYieldChangeArray(int i) const
{
CvAssertMsg(i < GC.getNumSpecialistInfos(), "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
return m_ppaiSpecialistYieldChange[i];
}
/// Modifier to resource yield
int CvBuildingEntry::GetResourceYieldModifier(int i, int j) const
{
CvAssertMsg(i < GC.getNumResourceInfos(), "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
CvAssertMsg(j < NUM_YIELD_TYPES, "Index out of bounds");
CvAssertMsg(j > -1, "Index out of bounds");
return m_ppaiResourceYieldModifier ? m_ppaiResourceYieldModifier[i][j] : -1;
}
/// Array of modifiers to resource yield
int* CvBuildingEntry::GetResourceYieldModifierArray(int i) const
{
CvAssertMsg(i < GC.getNumResourceInfos(), "Index out of bounds");
CvAssertMsg(i > -1, "Index out of bounds");
return m_ppaiResourceYieldModifier[i];
}
//=====================================
// CvBuildingXMLEntries
//=====================================
/// Constructor
CvBuildingXMLEntries::CvBuildingXMLEntries(void)
{
}
/// Destructor
CvBuildingXMLEntries::~CvBuildingXMLEntries(void)
{
DeleteArray();
}
/// Returns vector of policy entries
std::vector<CvBuildingEntry*>& CvBuildingXMLEntries::GetBuildingEntries()
{
return m_paBuildingEntries;
}
/// Number of defined policies
int CvBuildingXMLEntries::GetNumBuildings()
{
return m_paBuildingEntries.size();
}
/// Clear policy entries
void CvBuildingXMLEntries::DeleteArray()
{
for (std::vector<CvBuildingEntry*>::iterator it = m_paBuildingEntries.begin(); it != m_paBuildingEntries.end(); ++it)
{
SAFE_DELETE(*it);
}
m_paBuildingEntries.clear();
}
/// Get a specific entry
CvBuildingEntry *CvBuildingXMLEntries::GetEntry(int index)
{
return m_paBuildingEntries[index];
}
//=====================================
// CvCityBuildings
//=====================================
/// Constructor
CvCityBuildings::CvCityBuildings ():
m_paiBuildingProduction (NULL),
m_paiBuildingProductionTime (NULL),
m_paiBuildingOriginalOwner (NULL),
m_paiBuildingOriginalTime (NULL),
m_paiNumRealBuilding (NULL),
m_paiNumFreeBuilding (NULL),
m_iNumBuildings (0),
m_iBuildingProductionModifier (0),
m_iBuildingDefense (0),
m_iBuildingDefenseMod (0),
m_bSoldBuildingThisTurn (false),
m_pBuildings (NULL),
m_pCity (NULL)
{
}
/// Destructor
CvCityBuildings::~CvCityBuildings (void)
{
}
/// Initialize
void CvCityBuildings::Init(CvBuildingXMLEntries *pBuildings, CvCity *pCity)
{
// Store off the pointers to objects we'll need later
m_pBuildings = pBuildings;
m_pCity = pCity;
// Initialize status arrays
int iNumBuildings = m_pBuildings->GetNumBuildings();
CvAssertMsg((0 < iNumBuildings), "m_pBuildings->GetNumBuildings() is not greater than zero but an array is being allocated in CvCityBuildings::Init");
CvAssertMsg(m_paiBuildingProduction==NULL, "about to leak memory, CvCityBuildings::m_paiBuildingProduction");
m_paiBuildingProduction = FNEW(int[iNumBuildings], c_eCiv5GameplayDLL, 0);
CvAssertMsg(m_paiBuildingProductionTime==NULL, "about to leak memory, CvCityBuildings::m_paiBuildingProductionTime");
m_paiBuildingProductionTime = FNEW(int[iNumBuildings], c_eCiv5GameplayDLL, 0);
CvAssertMsg(m_paiBuildingOriginalOwner==NULL, "about to leak memory, CvCityBuildings::m_paiBuildingOriginalOwner");
m_paiBuildingOriginalOwner = FNEW(int[iNumBuildings], c_eCiv5GameplayDLL, 0);
CvAssertMsg(m_paiBuildingOriginalTime==NULL, "about to leak memory, CvCityBuildings::m_paiBuildingOriginalTime");
m_paiBuildingOriginalTime = FNEW(int[iNumBuildings], c_eCiv5GameplayDLL, 0);
CvAssertMsg(m_paiNumRealBuilding==NULL, "about to leak memory, CvCityBuildings::m_paiNumRealBuilding");
m_paiNumRealBuilding = FNEW(int[iNumBuildings], c_eCiv5GameplayDLL, 0);
CvAssertMsg(m_paiNumFreeBuilding==NULL, "about to leak memory, CvCityBuildings::m_paiNumFreeBuilding");
m_paiNumFreeBuilding = FNEW(int[iNumBuildings], c_eCiv5GameplayDLL, 0);
m_aBuildingYieldChange.clear();
Reset();
}
/// Deallocate memory created in initialize
void CvCityBuildings::Uninit()
{
SAFE_DELETE_ARRAY (m_paiBuildingProduction);
SAFE_DELETE_ARRAY (m_paiBuildingProductionTime);
SAFE_DELETE_ARRAY (m_paiBuildingOriginalOwner);
SAFE_DELETE_ARRAY (m_paiBuildingOriginalTime);
SAFE_DELETE_ARRAY (m_paiNumRealBuilding);
SAFE_DELETE_ARRAY (m_paiNumFreeBuilding);
}
/// Reset status arrays to all false
void CvCityBuildings::Reset()
{
int iI;
// Initialize non-arrays
m_iNumBuildings = 0;
m_iBuildingProductionModifier = 0;
m_iBuildingDefense = 0;
m_iBuildingDefenseMod = 0;
m_bSoldBuildingThisTurn = false;
for (iI = 0; iI < m_pBuildings->GetNumBuildings(); iI++)
{
m_paiBuildingProduction[iI] = 0;
m_paiBuildingProductionTime[iI] = 0;
m_paiBuildingOriginalOwner[iI] = NO_PLAYER;
m_paiBuildingOriginalTime[iI] = MIN_INT;
m_paiNumRealBuilding[iI] = 0;
m_paiNumFreeBuilding[iI] = 0;
}
}
/// Serialization read
void CvCityBuildings::Read(FDataStream& kStream)
{
CvAssertMsg(m_pBuildings != NULL && m_pBuildings->GetNumBuildings() > 0, "Number of buildings to serialize is expected to greater than 0");
// Version number to maintain backwards compatibility
uint uiVersion;
kStream >> uiVersion;
kStream >> m_iNumBuildings;
kStream >> m_iBuildingProductionModifier;
kStream >> m_iBuildingDefense;
kStream >> m_iBuildingDefenseMod;
if (uiVersion >= 3)
kStream >> m_bSoldBuildingThisTurn;
else
m_bSoldBuildingThisTurn = false;
if (uiVersion >= 2)
{
BuildingArrayHelpers::Read(kStream, m_paiBuildingProduction);
BuildingArrayHelpers::Read(kStream, m_paiBuildingProductionTime);
BuildingArrayHelpers::Read(kStream, m_paiBuildingOriginalOwner);
BuildingArrayHelpers::Read(kStream, m_paiBuildingOriginalTime);
BuildingArrayHelpers::Read(kStream, m_paiNumRealBuilding);
BuildingArrayHelpers::Read(kStream, m_paiNumFreeBuilding);
}
else
{
ArrayWrapper<int>wrapm_paiBuildingProduction(89, m_paiBuildingProduction);
kStream >> wrapm_paiBuildingProduction;
ArrayWrapper<int>wrapm_paiBuildingProductionTime(89, m_paiBuildingProductionTime);
kStream >> wrapm_paiBuildingProductionTime;
ArrayWrapper<int>wrapm_paiBuildingOriginalOwner(89, m_paiBuildingOriginalOwner);
kStream >> wrapm_paiBuildingOriginalOwner;
ArrayWrapper<int>wrapm_paiBuildingOriginalTime(89, m_paiBuildingOriginalTime);
kStream >> wrapm_paiBuildingOriginalTime;
ArrayWrapper<int>wrapm_paiNumRealBuilding(89, m_paiNumRealBuilding);
kStream >> wrapm_paiNumRealBuilding;
ArrayWrapper<int>wrapm_paiNumFreeBuilding(89, m_paiNumFreeBuilding);
kStream >> wrapm_paiNumFreeBuilding;
}
kStream >> m_aBuildingYieldChange;
}
/// Serialization write
void CvCityBuildings::Write(FDataStream& kStream)
{
CvAssertMsg(m_pBuildings != NULL && m_pBuildings->GetNumBuildings() > 0, "Number of buildings to serialize is expected to greater than 0");
// Current version number
uint uiVersion = 3;
kStream << uiVersion;
kStream << m_iNumBuildings;
kStream << m_iBuildingProductionModifier;
kStream << m_iBuildingDefense;
kStream << m_iBuildingDefenseMod;
if (uiVersion >= 3)
kStream << m_bSoldBuildingThisTurn;
#ifdef _MSC_VER
#pragma warning ( push )
#pragma warning ( disable : 6011 ) // if m_pBuildings is NULL during load, we're screwed. Redesign the class or the loader code.
#endif//_MSC_VER
int iNumBuildings = m_pBuildings->GetNumBuildings();
#ifdef _MSC_VER
#pragma warning ( pop )
#endif//_MSC_VER
BuildingArrayHelpers::Write(kStream, m_paiBuildingProduction, iNumBuildings);
BuildingArrayHelpers::Write(kStream, m_paiBuildingProductionTime, iNumBuildings);
BuildingArrayHelpers::Write(kStream, m_paiBuildingOriginalOwner, iNumBuildings);
BuildingArrayHelpers::Write(kStream, m_paiBuildingOriginalTime, iNumBuildings);
BuildingArrayHelpers::Write(kStream, m_paiNumRealBuilding, iNumBuildings);
BuildingArrayHelpers::Write(kStream, m_paiNumFreeBuilding, iNumBuildings);
kStream << m_aBuildingYieldChange;
}
/// Accessor: Get full array of all building XML data
CvBuildingXMLEntries *CvCityBuildings::GetBuildings() const
{
return m_pBuildings;
}
/// Accessor: Total number of buildings in the city
int CvCityBuildings::GetNumBuildings() const
{
return m_iNumBuildings;
}
/// Accessor: Update total number of buildings in the city
void CvCityBuildings::ChangeNumBuildings(int iChange)
{
m_iNumBuildings = (m_iNumBuildings + iChange);
CvAssert(GetNumBuildings() >= 0);
// GET_PLAYER(m_pCity->getOwner()).updateNumResourceUsed();
}
/// Accessor: How many of these buildings in the city?
int CvCityBuildings::GetNumBuilding(BuildingTypes eIndex) const
{
CvAssertMsg(eIndex != NO_BUILDING, "BuildingType eIndex is expected to not be NO_BUILDING");
if (GC.getCITY_MAX_NUM_BUILDINGS() <= 1)
{
return std::max(GetNumRealBuilding(eIndex), GetNumFreeBuilding(eIndex));
}
else
{
return (GetNumRealBuilding(eIndex) + GetNumFreeBuilding(eIndex));
}
}
/// Accessor: How many of these buildings are not obsolete?
int CvCityBuildings::GetNumActiveBuilding(BuildingTypes eIndex) const
{
CvAssertMsg(eIndex != NO_BUILDING, "BuildingType eIndex is expected to not be NO_BUILDING");
if (GET_TEAM(m_pCity->getTeam()).isObsoleteBuilding(eIndex))
{
return 0;
}
return (GetNumBuilding(eIndex));
}
/// Is the player allowed to sell building eIndex in this city?
bool CvCityBuildings::IsBuildingSellable(const CvBuildingEntry& kBuilding) const
{
// Can't sell more than one building per turn
if (IsSoldBuildingThisTurn())
return false;
// Can't sell a building if it doesn't cost us anything (no exploits)
if (kBuilding.GetGoldMaintenance() <= 0)
return false;
// Is this a free building?
if (GetNumFreeBuilding((BuildingTypes)kBuilding.GetID()) > 0)
return false;
// Science building in capital that has given us a tech boost?
if (m_pCity->isCapital() && kBuilding.IsScienceBuilding())
{
return !(GET_PLAYER(m_pCity->getOwner()).GetPlayerTraits()->IsTechBoostFromCapitalScienceBuildings());
}
return true;
}
/// Sell eIndex~!
void CvCityBuildings::DoSellBuilding(BuildingTypes eIndex)
{
CvAssertMsg(eIndex >= 0, "eIndex expected to be >= 0");
CvAssertMsg(eIndex < m_pBuildings->GetNumBuildings(), "eIndex expected to be < m_pBuildings->GetNumBuildings()");
CvBuildingEntry* pkBuildingEntry = GC.getBuildingInfo(eIndex);
if(!pkBuildingEntry)
return;
// Can we actually do this?
if (!IsBuildingSellable(*pkBuildingEntry))
return;
// Gold refund
int iRefund = GetSellBuildingRefund(eIndex);
GET_PLAYER(m_pCity->getOwner()).GetTreasury()->ChangeGold(iRefund);
// Kick everyone out
m_pCity->GetCityCitizens()->DoRemoveAllSpecialistsFromBuilding(eIndex);
SetNumRealBuilding(eIndex, 0);
SetSoldBuildingThisTurn(true);
}
/// How much of a refund will the player get from selling eIndex?
int CvCityBuildings::GetSellBuildingRefund(BuildingTypes eIndex) const
{
CvAssertMsg(eIndex >= 0, "eIndex expected to be >= 0");
CvAssertMsg(eIndex < m_pBuildings->GetNumBuildings(), "eIndex expected to be < m_pBuildings->GetNumBuildings()");
int iRefund = GET_PLAYER(m_pCity->getOwner()).getProductionNeeded(eIndex);
iRefund /= /*10*/ GC.getBUILDING_SALE_DIVISOR();
return iRefund;
}
/// Has a building already been sold this turn?
bool CvCityBuildings::IsSoldBuildingThisTurn() const
{
return m_bSoldBuildingThisTurn;
}
/// Has a building already been sold this turn?
void CvCityBuildings::SetSoldBuildingThisTurn(bool bValue)
{
if (IsSoldBuildingThisTurn() != bValue)
m_bSoldBuildingThisTurn = bValue;
}
/// What is the total maintenance? (no modifiers)
int CvCityBuildings::GetTotalBaseBuildingMaintenance() const
{
int iTotalCost = 0;
for (int iBuildingLoop = 0; iBuildingLoop < GC.getNumBuildingInfos(); iBuildingLoop++)
{
const BuildingTypes eBuilding = static_cast<BuildingTypes>(iBuildingLoop);
CvBuildingEntry* pkBuildingInfo = GC.getBuildingInfo(eBuilding);
if(pkBuildingInfo)
{
if (GetNumBuilding(eBuilding))
iTotalCost += (pkBuildingInfo->GetGoldMaintenance() * GetNumBuilding(eBuilding));
}
}
return iTotalCost;
}
/// Accessor: How far is construction of this building?
int CvCityBuildings::GetBuildingProduction(BuildingTypes eIndex) const
{
CvAssertMsg(eIndex >= 0, "eIndex expected to be >= 0");
CvAssertMsg(eIndex < m_pBuildings->GetNumBuildings(), "eIndex expected to be < m_pBuildings->GetNumBuildings()");
return m_paiBuildingProduction[eIndex] / 100;
}
/// Accessor: How far is construction of this building? (in hundredths)
int CvCityBuildings::GetBuildingProductionTimes100(BuildingTypes eIndex) const
{
CvAssertMsg(eIndex >= 0, "eIndex expected to be >= 0");
CvAssertMsg(eIndex < m_pBuildings->GetNumBuildings(), "eIndex expected to be < m_pBuildings->GetNumBuildings()");
return m_paiBuildingProduction[eIndex];
}
/// Accessor: Set how much construction is complete for this building
void CvCityBuildings::SetBuildingProduction(BuildingTypes eIndex, int iNewValue)
{
SetBuildingProductionTimes100(eIndex, iNewValue*100);
}
/// Accessor: Set how much construction is complete for this building (in hundredths)
void CvCityBuildings::SetBuildingProductionTimes100(BuildingTypes eIndex, int iNewValue)
{
CvAssertMsg(eIndex >= 0, "eIndex expected to be >= 0");
CvAssertMsg(eIndex < m_pBuildings->GetNumBuildings(), "eIndex expected to be < m_pBuildings->GetNumBuildings())");
if (GetBuildingProductionTimes100(eIndex) != iNewValue)
{
if (GetBuildingProductionTimes100(eIndex) == 0)
{
NotifyNewBuildingStarted(eIndex);
}
m_paiBuildingProduction[eIndex] = iNewValue;
CvAssert(GetBuildingProductionTimes100(eIndex) >= 0);
if ((m_pCity->getOwner() == GC.getGame().getActivePlayer()) && m_pCity->isCitySelected())
{
GC.GetEngineUserInterface()->setDirty(CityScreen_DIRTY_BIT, true);
}
auto_ptr<ICvCity1> pCity = GC.WrapCityPointer(m_pCity);
GC.GetEngineUserInterface()->SetSpecificCityInfoDirty(pCity.get(), CITY_UPDATE_TYPE_BANNER);
}
}
/// Accessor: Update construction progress for this building
void CvCityBuildings::ChangeBuildingProduction(BuildingTypes eIndex, int iChange)
{
ChangeBuildingProductionTimes100(eIndex, iChange*100);
}
/// Accessor: Update construction progress for this building (in hundredths)
void CvCityBuildings::ChangeBuildingProductionTimes100(BuildingTypes eIndex, int iChange)
{
SetBuildingProductionTimes100(eIndex, (GetBuildingProductionTimes100(eIndex) + iChange));
}
/// Accessor: How many turns has this building been under production?
int CvCityBuildings::GetBuildingProductionTime(BuildingTypes eIndex) const
{
CvAssertMsg(eIndex >= 0, "eIndex expected to be >= 0");
CvAssertMsg(eIndex < m_pBuildings->GetNumBuildings(), "eIndex expected to be < m_pBuildings->GetNumBuildings()");
return m_paiBuildingProductionTime[eIndex];
}
/// Accessor: Set number of turns this building been under production
void CvCityBuildings::SetBuildingProductionTime(BuildingTypes eIndex, int iNewValue)
{
CvAssertMsg(eIndex >= 0, "eIndex expected to be >= 0");
CvAssertMsg(eIndex < m_pBuildings->GetNumBuildings(), "eIndex expected to be < m_pBuildings->GetNumBuildings()");
m_paiBuildingProductionTime[eIndex] = iNewValue;
CvAssert(GetBuildingProductionTime(eIndex) >= 0);
}
/// Accessor: Change number of turns this building been under production
void CvCityBuildings::ChangeBuildingProductionTime(BuildingTypes eIndex, int iChange)
{
SetBuildingProductionTime(eIndex, (GetBuildingProductionTime(eIndex) + iChange));
}
/// Accessor: Who owned the city when this building was built?
int CvCityBuildings::GetBuildingOriginalOwner(BuildingTypes eIndex) const
{
CvAssertMsg(eIndex >= 0, "eIndex expected to be >= 0");
CvAssertMsg(eIndex < m_pBuildings->GetNumBuildings(), "eIndex expected to be < m_pBuildings->GetNumBuildings()");
return m_paiBuildingOriginalOwner[eIndex];
}
/// Accessor: Set who owned the city when this building was built
void CvCityBuildings::SetBuildingOriginalOwner(BuildingTypes eIndex, int iNewValue)
{
CvAssertMsg(eIndex >= 0, "eIndex expected to be >= 0");
CvAssertMsg(eIndex < m_pBuildings->GetNumBuildings(), "eIndex expected to be < m_pBuildings->GetNumBuildings()");
m_paiBuildingOriginalOwner[eIndex] = iNewValue;
}
/// Accessor: What year was this building built?
int CvCityBuildings::GetBuildingOriginalTime(BuildingTypes eIndex) const
{
CvAssertMsg(eIndex >= 0, "eIndex expected to be >= 0");
CvAssertMsg(eIndex < m_pBuildings->GetNumBuildings(), "eIndex expected to be < m_pBuildings->GetNumBuildings()");
return m_paiBuildingOriginalTime[eIndex];
}
/// Accessor: Set year building was built
void CvCityBuildings::SetBuildingOriginalTime(BuildingTypes eIndex, int iNewValue)
{
CvAssertMsg(eIndex >= 0, "eIndex expected to be >= 0");
CvAssertMsg(eIndex < m_pBuildings->GetNumBuildings(), "eIndex expected to be < m_pBuildings->GetNumBuildings()");
m_paiBuildingOriginalTime[eIndex] = iNewValue;
}
/// Accessor: How many of these buildings have been constructed in the city?
int CvCityBuildings::GetNumRealBuilding(BuildingTypes eIndex) const
{
CvAssertMsg(eIndex >= 0, "eIndex expected to be >= 0");
CvAssertMsg(eIndex < m_pBuildings->GetNumBuildings(), "eIndex expected to be < m_pBuildings->GetNumBuildings()");
return m_paiNumRealBuilding[eIndex];
}
/// Accessor: Set number of these buildings that have been constructed in the city
void CvCityBuildings::SetNumRealBuilding(BuildingTypes eIndex, int iNewValue)
{
SetNumRealBuildingTimed(eIndex, iNewValue, true, m_pCity->getOwner(), GC.getGame().getGameTurnYear());
}
/// Accessor: Set number of these buildings that have been constructed in the city (with date)
void CvCityBuildings::SetNumRealBuildingTimed(BuildingTypes eIndex, int iNewValue, bool bFirst, PlayerTypes eOriginalOwner, int iOriginalTime)
{
CvPlayer* pPlayer = &GET_PLAYER(m_pCity->getOwner());
CvAssertMsg(eIndex >= 0, "eIndex expected to be >= 0");
CvAssertMsg(eIndex < m_pBuildings->GetNumBuildings(), "eIndex expected to be < m_pBuildings->GetNumBuildings()");
int iChangeNumRealBuilding = iNewValue - GetNumRealBuilding(eIndex);
CvBuildingEntry* buildingEntry = GC.getBuildingInfo(eIndex);
const BuildingClassTypes buildingClassType = (BuildingClassTypes) buildingEntry->GetBuildingClassType();
const CvBuildingClassInfo& kBuildingClassInfo = buildingEntry->GetBuildingClassInfo();
if (iChangeNumRealBuilding != 0)
{
int iOldNumBuilding = GetNumBuilding(eIndex);
m_paiNumRealBuilding[eIndex] = iNewValue;
if (GetNumRealBuilding(eIndex) > 0)
{
SetBuildingOriginalOwner(eIndex, eOriginalOwner);
SetBuildingOriginalTime(eIndex, iOriginalTime);
}
else
{
SetBuildingOriginalOwner(eIndex, NO_PLAYER);
SetBuildingOriginalTime(eIndex, MIN_INT);
}
// Process building effects
if (iOldNumBuilding != GetNumBuilding(eIndex))
{
m_pCity->processBuilding(eIndex, iChangeNumRealBuilding, bFirst);
}
// Maintenance cost
if (buildingEntry->GetGoldMaintenance() != 0)
{
pPlayer->GetTreasury()->ChangeBaseBuildingGoldMaintenance(buildingEntry->GetGoldMaintenance() * iChangeNumRealBuilding);
}
//Achievement for Temples
const char* szBuildingTypeC = buildingEntry->GetType();
CvString szBuildingType = szBuildingTypeC;
if(szBuildingType == "BUILDING_TEMPLE")
{
if(m_pCity->getOwner() == GC.getGame().getActivePlayer())
{
gDLL->IncrementSteamStatAndUnlock( ESTEAMSTAT_TEMPLES, 1000, ACHIEVEMENT_1000TEMPLES );
}
}
if (buildingEntry->GetPreferredDisplayPosition() > 0)
{
auto_ptr<ICvCity1> pDllCity(new CvDllCity(m_pCity));
if (iNewValue > 0)
{
// if this is a WW that (likely has a half-built state)
if (isWorldWonderClass(kBuildingClassInfo))
{
if (GetBuildingProduction(eIndex))
{
GC.GetEngineUserInterface()->AddDeferredWonderCommand(WONDER_EDITED, pDllCity.get(), eIndex, 1);
}
else
{
GC.GetEngineUserInterface()->AddDeferredWonderCommand(WONDER_CREATED, pDllCity.get(), eIndex, 1);
}
}
else
{
GC.GetEngineUserInterface()->AddDeferredWonderCommand(WONDER_CREATED, pDllCity.get(), eIndex, 1);
}
}
else
{
GC.GetEngineUserInterface()->AddDeferredWonderCommand(WONDER_REMOVED, pDllCity.get(), eIndex, 0);
}
}
if (!(kBuildingClassInfo.isNoLimit()))
{
if (isWorldWonderClass(kBuildingClassInfo))
{
m_pCity->changeNumWorldWonders(iChangeNumRealBuilding);
pPlayer->ChangeNumWonders(iChangeNumRealBuilding);
}
else if (isTeamWonderClass(kBuildingClassInfo))
{
m_pCity->changeNumTeamWonders(iChangeNumRealBuilding);
}
else if (isNationalWonderClass(kBuildingClassInfo))
{
m_pCity->changeNumNationalWonders(iChangeNumRealBuilding);
if(m_pCity->isHuman() && !GC.getGame().isGameMultiPlayer())
{
IncrementWonderStats(buildingClassType);
}
}
else
{
ChangeNumBuildings(iChangeNumRealBuilding);
}
}
if (buildingEntry->IsCityWall())
{
auto_ptr<ICvPlot1> pDllPlot(new CvDllPlot(m_pCity->plot()));
gDLL->GameplayWallCreated(pDllPlot.get());
}
// Update the amount of a Resource used up by this Building
int iNumResources = GC.getNumResourceInfos();
for (int iResourceLoop = 0; iResourceLoop < iNumResources; iResourceLoop++)
{
if (buildingEntry->GetResourceQuantityRequirement(iResourceLoop) > 0)
{
pPlayer->changeNumResourceUsed((ResourceTypes) iResourceLoop, iChangeNumRealBuilding * buildingEntry->GetResourceQuantityRequirement(iResourceLoop));
}
}
if (iChangeNumRealBuilding > 0)
{
if (bFirst)
{
if (GC.getGame().isFinalInitialized()/* && !(gDLL->GetWorldBuilderMode() )*/)
{
// World Wonder Notification
if (isWorldWonderClass(kBuildingClassInfo))
{
Localization::String localizedText = Localization::Lookup("TXT_KEY_MISC_COMPLETES_WONDER");
localizedText << pPlayer->getNameKey() << buildingEntry->GetTextKey();
GC.getGame().addReplayMessage(REPLAY_MESSAGE_MAJOR_EVENT, m_pCity->getOwner(), localizedText.toUTF8(), m_pCity->getX(), m_pCity->getY());
bool bDontShowRewardPopup = GC.GetEngineUserInterface()->IsOptionNoRewardPopups();
// Notification in MP games
if(bDontShowRewardPopup || GC.getGame().isNetworkMultiPlayer()) // KWG: Candidate for !GC.getGame().IsOption(GAMEOPTION_SIMULTANEOUS_TURNS)
{
CvNotifications* pNotifications = GET_PLAYER(m_pCity->getOwner()).GetNotifications();
if (pNotifications)
{
localizedText = Localization::Lookup("TXT_KEY_MISC_WONDER_COMPLETED");
localizedText << pPlayer->getNameKey() << buildingEntry->GetTextKey();
pNotifications->Add(NOTIFICATION_WONDER_COMPLETED_ACTIVE_PLAYER, localizedText.toUTF8(), localizedText.toUTF8(), m_pCity->getX(), m_pCity->getY(), eIndex, pPlayer->GetID());
}
}
// Popup in SP games
else
{
if (m_pCity->getOwner() == GC.getGame().getActivePlayer())
{
CvPopupInfo kPopup(BUTTONPOPUP_WONDER_COMPLETED_ACTIVE_PLAYER, eIndex);
GC.GetEngineUserInterface()->AddPopup(kPopup);
if(GET_PLAYER(GC.getGame().getActivePlayer()).isHuman())
{
gDLL->UnlockAchievement( ACHIEVEMENT_BUILD_WONDER );
//look to see if all wonders have been built to unlock the other one
IncrementWonderStats(buildingClassType);
}
}
}
// Wonder notification for all other players
for (int iI = 0; iI < MAX_MAJOR_CIVS; iI++)
{
CvPlayerAI& thisPlayer = GET_PLAYER((PlayerTypes)iI);
if (thisPlayer.isAlive())
{
// Owner already got his messaging
if (iI != m_pCity->getOwner())
{
// If the builder is met, and the city is revealed
// Special case for DLC_06 Scenario: Always show the more informative notification
if ((m_pCity->isRevealed(thisPlayer.getTeam(), false) && GET_TEAM(thisPlayer.getTeam()).isHasMet(m_pCity->getTeam())) || gDLL->IsModActivated(CIV5_DLC_06_SCENARIO_MODID))
{
CvNotifications* pNotifications = thisPlayer.GetNotifications();
if (pNotifications)
{
localizedText = Localization::Lookup("TXT_KEY_MISC_WONDER_COMPLETED");
localizedText << pPlayer->getNameKey() << buildingEntry->GetTextKey();
pNotifications->Add(NOTIFICATION_WONDER_COMPLETED, localizedText.toUTF8(), localizedText.toUTF8(), m_pCity->getX(), m_pCity->getY(), eIndex, pPlayer->GetID());
}
}
else
{
CvNotifications* pNotifications = thisPlayer.GetNotifications();
if (pNotifications)
{
localizedText = Localization::Lookup("TXT_KEY_MISC_WONDER_COMPLETED_UNKNOWN");
localizedText << buildingEntry->GetTextKey();
pNotifications->Add(NOTIFICATION_WONDER_COMPLETED, localizedText.toUTF8(), localizedText.toUTF8(), -1, -1, eIndex, -1);
}
}
}
}
}
}
}
GC.getGame().incrementBuildingClassCreatedCount(buildingClassType);
}
}
m_pCity->updateStrengthValue();
// Building might affect City Banner stats
auto_ptr<ICvCity1> pCity = GC.WrapCityPointer(m_pCity);
GC.GetEngineUserInterface()->SetSpecificCityInfoDirty(pCity.get(), CITY_UPDATE_TYPE_BANNER);
}
}
/// Accessor: Get number of free buildings of this type in city
int CvCityBuildings::GetNumFreeBuilding(BuildingTypes eIndex) const
{
CvAssertMsg(eIndex >= 0, "eIndex expected to be >= 0");
CvAssertMsg(eIndex < m_pBuildings->GetNumBuildings(), "eIndex expected to be < m_pBuildings->GetNumBuildings()");
return m_paiNumFreeBuilding[eIndex];
}
/// Accessor: Set number of free buildings of this type in city
void CvCityBuildings::SetNumFreeBuilding(BuildingTypes eIndex, int iNewValue)
{
CvAssertMsg(eIndex >= 0, "eIndex expected to be >= 0");
CvAssertMsg(eIndex < m_pBuildings->GetNumBuildings(), "eIndex expected to be < m_pBuildings->GetNumBuildings()");
if (GetNumFreeBuilding(eIndex) != iNewValue)
{
int iOldNumBuilding = GetNumBuilding(eIndex);
m_paiNumFreeBuilding[eIndex] = iNewValue;
if (iOldNumBuilding != GetNumBuilding(eIndex))
{
m_pCity->processBuilding(eIndex, iNewValue - iOldNumBuilding, true);
}
}
}
/// Accessor: Get yield boost for a specific building by yield type
int CvCityBuildings::GetBuildingYieldChange(BuildingClassTypes eBuildingClass, YieldTypes eYield) const
{
for (std::vector<BuildingYieldChange>::const_iterator it = m_aBuildingYieldChange.begin(); it != m_aBuildingYieldChange.end(); ++it)
{
if ((*it).eBuildingClass == eBuildingClass && (*it).eYield == eYield)
{
return (*it).iChange;
}
}
return 0;
}
/// Accessor: Set yield boost for a specific building by yield type
void CvCityBuildings::SetBuildingYieldChange(BuildingClassTypes eBuildingClass, YieldTypes eYield, int iChange)
{
for (std::vector<BuildingYieldChange>::iterator it = m_aBuildingYieldChange.begin(); it != m_aBuildingYieldChange.end(); ++it)
{
if ((*it).eBuildingClass == eBuildingClass && (*it).eYield == eYield)
{
int iOldChange = (*it).iChange;
if (iOldChange != iChange)
{
if (iChange == 0)
{
m_aBuildingYieldChange.erase(it);
}
else
{
(*it).iChange = iChange;
}
BuildingTypes eBuilding = (BuildingTypes)GC.getCivilizationInfo(m_pCity->getCivilizationType())->getCivilizationBuildings(eBuildingClass);
if (NO_BUILDING != eBuilding)
{
if (GetNumActiveBuilding(eBuilding) > 0)
{
m_pCity->ChangeBaseYieldRateFromBuildings(eYield, (iChange - iOldChange) * GetNumActiveBuilding(eBuilding));
}
}
}
return;
}
}
if (0 != iChange)
{
BuildingYieldChange kChange;
kChange.eBuildingClass = eBuildingClass;
kChange.eYield = eYield;
kChange.iChange = iChange;
m_aBuildingYieldChange.push_back(kChange);
BuildingTypes eBuilding = (BuildingTypes)m_pCity->getCivilizationInfo().getCivilizationBuildings(eBuildingClass);
if (NO_BUILDING != eBuilding)
{
if (GetNumActiveBuilding(eBuilding) > 0)
{
m_pCity->ChangeBaseYieldRateFromBuildings(eYield, iChange * GetNumActiveBuilding(eBuilding));
}
}
}
}
/// Accessor: Change yield boost for a specific building by yield type
void CvCityBuildings::ChangeBuildingYieldChange(BuildingClassTypes eBuildingClass, YieldTypes eYield, int iChange)
{
SetBuildingYieldChange(eBuildingClass, eYield, GetBuildingYieldChange(eBuildingClass, eYield) + iChange);
}
/// Accessor: Get current production modifier from buildings
int CvCityBuildings::GetBuildingProductionModifier() const
{
return m_iBuildingProductionModifier;
}
/// Accessor: Change current production modifier from buildings
void CvCityBuildings::ChangeBuildingProductionModifier(int iChange)
{
m_iBuildingProductionModifier = (m_iBuildingProductionModifier + iChange);
CvAssert(GetBuildingProductionModifier() >= 0);
}
/// Accessor: Get current defense boost from buildings
int CvCityBuildings::GetBuildingDefense() const
{
return m_iBuildingDefense;
}
/// Accessor: Change current defense boost from buildings
void CvCityBuildings::ChangeBuildingDefense(int iChange)
{
if (iChange != 0)
{
m_iBuildingDefense = (m_iBuildingDefense + iChange);
CvAssert(GetBuildingDefense() >= 0);
m_pCity->plot()->plotAction(PUF_makeInfoBarDirty);
}
}
/// Accessor: Get current defense boost Mod from buildings
int CvCityBuildings::GetBuildingDefenseMod() const
{
return m_iBuildingDefenseMod;
}
/// Accessor: Change current defense boost mod from buildings
void CvCityBuildings::ChangeBuildingDefenseMod(int iChange)
{
if (iChange != 0)
{
m_iBuildingDefenseMod = (m_iBuildingDefenseMod + iChange);
CvAssert(m_iBuildingDefenseMod >= 0);
m_pCity->plot()->plotAction(PUF_makeInfoBarDirty);
}
}
void CvCityBuildings::IncrementWonderStats(BuildingClassTypes eIndex)
{
CvBuildingClassInfo* pkBuildingClassInfo = GC.getBuildingClassInfo(eIndex);
if(pkBuildingClassInfo == NULL)
return;
const char* szWonderTypeChar = pkBuildingClassInfo->GetType();
CvString szWonderType = szWonderTypeChar;
if( szWonderType == "BUILDINGCLASS_HEROIC_EPIC" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_HEROICEPIC );
}
else if( szWonderType == "BUILDINGCLASS_NATIONAL_COLLEGE" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_NATIONALCOLLEGE );
}
else if( szWonderType == "BUILDINGCLASS_NATIONAL_EPIC" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_NATIONALEPIC );
}
else if( szWonderType == "BUILDINGCLASS_IRONWORKS" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_IRONWORKS );
}
else if( szWonderType == "BUILDINGCLASS_OXFORD_UNIVERSITY" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_OXFORDUNIVERSITY );
}
else if( szWonderType == "BUILDINGCLASS_HERMITAGE" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_HERMITAGE );
}
else if( szWonderType == "BUILDINGCLASS_GREAT_LIGHTHOUSE" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_GREATLIGHTHOUSE );
}
else if( szWonderType == "BUILDINGCLASS_STONEHENGE" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_STONEHENGE );
}
else if( szWonderType == "BUILDINGCLASS_GREAT_LIBRARY" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_GREATLIBRARY );
}
else if( szWonderType == "BUILDINGCLASS_PYRAMID" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_PYRAMIDS );
}
else if( szWonderType == "BUILDINGCLASS_COLOSSUS" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_COLOSSUS );
}
else if( szWonderType == "BUILDINGCLASS_ORACLE" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_ORACLE );
}
else if( szWonderType == "BUILDINGCLASS_HANGING_GARDEN" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_HANGINGGARDENS );
}
else if( szWonderType == "BUILDINGCLASS_GREAT_WALL" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_GREATWALL);
}
else if( szWonderType == "BUILDINGCLASS_ANGKOR_WAT" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_ANGKORWAT);
}
else if( szWonderType == "BUILDINGCLASS_HAGIA_SOPHIA" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_HAGIASOPHIA);
}
else if( szWonderType == "BUILDINGCLASS_CHICHEN_ITZA" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_CHICHENITZA);
}
else if( szWonderType == "BUILDINGCLASS_MACHU_PICHU" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_MACHUPICCHU);
}
else if( szWonderType == "BUILDINGCLASS_NOTRE_DAME" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_NOTREDAME);
}
else if( szWonderType == "BUILDINGCLASS_PORCELAIN_TOWER" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_PORCELAINTOWER);
}
else if( szWonderType == "BUILDINGCLASS_HIMEJI_CASTLE" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_HIMEJICASTLE);
}
else if( szWonderType == "BUILDINGCLASS_SISTINE_CHAPEL" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_SISTINECHAPEL);
}
else if( szWonderType == "BUILDINGCLASS_KREMLIN" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_KREMLIN );
}
else if( szWonderType == "BUILDINGCLASS_FORBIDDEN_PALACE" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_FORBIDDENPALACE);
}
else if( szWonderType == "BUILDINGCLASS_TAJ_MAHAL" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_TAJMAHAL);
}
else if( szWonderType == "BUILDINGCLASS_BIG_BEN" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_BIGBEN);
}
else if( szWonderType == "BUILDINGCLASS_LOUVRE" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_LOUVRE);
}
else if( szWonderType == "BUILDINGCLASS_BRANDENBURG_GATE" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_BRANDENBURGGATE);
}
else if( szWonderType == "BUILDINGCLASS_STATUE_OF_LIBERTY" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_STATUEOFLIBERTY);
}
else if( szWonderType == "BUILDINGCLASS_CRISTO_REDENTOR" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_CRISTOREDENTOR);
}
else if( szWonderType == "BUILDINGCLASS_EIFFEL_TOWER" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_EIFFELTOWER);
}
else if( szWonderType == "BUILDINGCLASS_PENTAGON" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_PENTAGON);
}
else if( szWonderType == "BUILDINGCLASS_UNITED_NATIONS" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_UNITEDNATION );
}
else if( szWonderType == "BUILDINGCLASS_SYDNEY_OPERA_HOUSE" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_SYDNEYOPERAHOUSE);
}
else if( szWonderType == "BUILDINGCLASS_STATUE_ZEUS" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_STATUEOFZEUS );
}
else if( szWonderType == "BUILDINGCLASS_TEMPLE_ARTEMIS" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_TEMPLEOFARTEMIS );
}
else if( szWonderType == "BUILDINGCLASS_MAUSOLEUM_HALICARNASSUS" )
{
gDLL->IncrementSteamStat( ESTEAMSTAT_MAUSOLEUMOFHALICARNASSUS );
}
else
{
OutputDebugString("\nNo Stat for selected Wonder: ");
OutputDebugString(szWonderType);
OutputDebugString("\n");
}
bool bCheckForWonders = false;
bCheckForWonders = CheckForAllWondersBuilt();
if (bCheckForWonders)
{
gDLL->UnlockAchievement(ACHIEVEMENT_ALL_WONDERS);
}
//DLC_06
bool bCheckForAncientWonders = false;
bCheckForAncientWonders = CheckForSevenAncientWondersBuilt();
if (bCheckForAncientWonders)
{
gDLL->UnlockAchievement(ACHIEVEMENT_SPECIAL_ANCIENT_WONDERS);
}
}
bool CvCityBuildings::CheckForAllWondersBuilt()
{
int iI;
int iStartStatWonder = 80; //As defined on the backend
int iEndStatWonder = 113;
int32 nStat;
for(iI = iStartStatWonder; iI < iEndStatWonder; iI++)
{
if(gDLL->GetSteamStat( (ESteamStat)iI, &nStat ))
{
if(nStat <= 0 )
{
return false;
}
}
}
return true;
}
bool CvCityBuildings::CheckForSevenAncientWondersBuilt()
{
GUID guid;
ExtractGUID(CIV5_DLC_06_PACKAGEID, guid);
if (gDLL->IsDLCValid(guid))
{
ESteamStat arrWonderStats[7] = {
ESTEAMSTAT_COLOSSUS,
ESTEAMSTAT_GREATLIGHTHOUSE,
ESTEAMSTAT_HANGINGGARDENS,
ESTEAMSTAT_PYRAMIDS,
ESTEAMSTAT_STATUEOFZEUS,
ESTEAMSTAT_TEMPLEOFARTEMIS,
ESTEAMSTAT_MAUSOLEUMOFHALICARNASSUS
};
int32 nStat;
for (int iI = 0; iI < 7; iI++ )
{
if (gDLL->GetSteamStat(arrWonderStats[iI], &nStat))
{
if (nStat <= 0)
{
return false;
}
}
else
{
// Couldn't get one of the SteamStats for some reason
return false;
}
}
return true;
}
return false;
}
/// Uses the notification system to send information out when other players need to know a building has been started
void CvCityBuildings::NotifyNewBuildingStarted (BuildingTypes /*eIndex*/)
{
// JON: Disabling this notification
return;
// is this city starting a wonder? If so, send a notification
//CvBuildingEntry* buildingEntry = GC.getBuildingInfo(eIndex);
//if (isLimitedWonderClass((BuildingClassTypes)(buildingEntry->GetBuildingClassType())) && GetBuildingProductionTimes100(eIndex) == 0)
//{
// Localization::String locString;
// Localization::String locSummaryString;
// for (uint ui = 0; ui < MAX_MAJOR_CIVS; ui++)
// {
// PlayerTypes ePlayer = (PlayerTypes)ui;
// if (ePlayer == m_pCity->getOwner() || !GET_PLAYER(ePlayer).isAlive())
// {
// continue;
// }
// int iX = -1;
// int iY = -1;
// int iPlayerID = -1;
// if (GET_TEAM(m_pCity->getTeam()).isHasMet(GET_PLAYER(ePlayer).getTeam()))
// {
// if (m_pCity->isRevealed(GET_PLAYER(ePlayer).getTeam(), false))
// {
// locString = Localization::Lookup("TXT_KEY_NOTIFICATION_WONDER_STARTED");
// locString << GET_PLAYER(m_pCity->getOwner()).getNameKey() << buildingEntry->GetTextKey() << m_pCity->getNameKey();
// }
// else
// {
// locString = Localization::Lookup("TXT_KEY_NOTIFICATION_WONDER_STARTED_UNKNOWN_LOCATION");
// locString << GET_PLAYER(m_pCity->getOwner()).getNameKey() << buildingEntry->GetTextKey();
// }
// locSummaryString = Localization::Lookup("TXT_KEY_NOTIFICATION_SUMMARY_WONDER_STARTED");
// locSummaryString << GET_PLAYER(m_pCity->getOwner()).getNameKey() << buildingEntry->GetTextKey();
// }
// else
// {
// locString = Localization::Lookup("TXT_KEY_NOTIFICATION_WONDER_STARTED_UNMET");
// locString << buildingEntry->GetTextKey();
// locSummaryString = Localization::Lookup("TXT_KEY_NOTIFICATION_SUMMARY_WONDER_STARTED_UNKNOWN");
// locSummaryString << buildingEntry->GetTextKey();
// }
// CvNotifications* pNotifications = GET_PLAYER(ePlayer).GetNotifications();
// if (pNotifications)
// {
// pNotifications->Add(NOTIFICATION_WONDER_STARTED, locString.toUTF8(), locSummaryString.toUTF8(), iX, iY, eIndex);
// }
// }
//}
}
/// Helper function to read in an integer array of data sized according to number of building types
void BuildingArrayHelpers::Read(FDataStream &kStream, int *paiBuildingArray)
{
int iNumEntries;
FStringFixedBuffer(sTemp, 64);
int iType;
kStream >> iNumEntries;
for (int iI = 0; iI < iNumEntries; iI++)
{
kStream >> sTemp;
if (sTemp != "NO_BUILDING")
{
iType = GC.getInfoTypeForString(sTemp);
if (iType != -1)
{
kStream >> paiBuildingArray[iType];
}
else
{
CvString szError;
szError.Format("LOAD ERROR: Building Type not found: %s", sTemp);
GC.LogMessage(szError.GetCString());
CvAssertMsg(false, szError);
int iDummy;
kStream >> iDummy; // Skip it.
}
}
}
}
/// Helper function to write out an integer array of data sized according to number of building types
void BuildingArrayHelpers::Write(FDataStream &kStream, int *paiBuildingArray, int iArraySize)
{
FStringFixedBuffer(sTemp, 64);
kStream << iArraySize;
for (int iI = 0; iI < iArraySize; iI++)
{
const BuildingTypes eBuilding = static_cast<BuildingTypes>(iI);
CvBuildingEntry* pkBuildingInfo = GC.getBuildingInfo(eBuilding);
if(pkBuildingInfo)
{
sTemp = pkBuildingInfo->GetType();
kStream << sTemp;
kStream << paiBuildingArray[iI];
}
else
{
sTemp = "NO_BUILDING";
kStream << sTemp;
}
}
}
| [
"[email protected]"
] | |
9286a55f04f0e2e8f4c7bd511e02f4c52c99f74f | f5ec6ba1baf301e08728d8892d2a35e59f20b718 | /src/talkcoin-wallet.cpp | d5171eff6dda3a7141fd780e2725c112c6964635 | [
"MIT"
] | permissive | bitcointalkcoin/bitcointalkcoin | 26434eb812e9cedaf174fcafe0409fc4ed5a4c76 | c9112c3b8ce05ee78fe69822035cc3d8bdbca903 | refs/heads/master | 2020-06-26T14:37:43.515919 | 2019-12-02T17:46:15 | 2019-12-02T17:46:15 | 199,659,333 | 0 | 1 | MIT | 2019-12-02T17:46:17 | 2019-07-30T13:41:31 | C++ | UTF-8 | C++ | false | false | 4,635 | cpp | // Copyright (c) 2016-2018 The Talkcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/talkcoin-config.h>
#endif
#include <chainparams.h>
#include <chainparamsbase.h>
#include <logging.h>
#include <util/strencodings.h>
#include <util/system.h>
#include <util/translation.h>
#include <wallet/wallettool.h>
#include <functional>
#include <stdio.h>
const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr;
static void SetupWalletToolArgs()
{
SetupHelpOptions(gArgs);
SetupChainParamsBaseOptions();
gArgs.AddArg("-datadir=<dir>", "Specify data directory", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-wallet=<wallet-name>", "Specify wallet name", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::OPTIONS);
gArgs.AddArg("-debug=<category>", "Output debugging information (default: 0).", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-printtoconsole", "Send trace/debug info to console (default: 1 when no -debug is true, 0 otherwise).", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("info", "Get wallet info", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
gArgs.AddArg("create", "Create new wallet file", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
}
static bool WalletAppInit(int argc, char* argv[])
{
SetupWalletToolArgs();
std::string error_message;
if (!gArgs.ParseParameters(argc, argv, error_message)) {
tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error_message.c_str());
return false;
}
if (argc < 2 || HelpRequested(gArgs)) {
std::string usage = strprintf("%s talkcoin-wallet version", PACKAGE_NAME) + " " + FormatFullVersion() + "\n\n" +
"wallet-tool is an offline tool for creating and interacting with Talkcoin Core wallet files.\n" +
"By default wallet-tool will act on wallets in the default mainnet wallet directory in the datadir.\n" +
"To change the target wallet, use the -datadir, -wallet and -testnet/-regtest arguments.\n\n" +
"Usage:\n" +
" talkcoin-wallet [options] <command>\n\n" +
gArgs.GetHelpMessage();
tfm::format(std::cout, "%s", usage.c_str());
return false;
}
// check for printtoconsole, allow -debug
LogInstance().m_print_to_console = gArgs.GetBoolArg("-printtoconsole", gArgs.GetBoolArg("-debug", false));
if (!CheckDataDirOption()) {
tfm::format(std::cerr, "Error: Specified data directory \"%s\" does not exist.\n", gArgs.GetArg("-datadir", "").c_str());
return false;
}
// Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
SelectParams(gArgs.GetChainName());
return true;
}
int main(int argc, char* argv[])
{
#ifdef WIN32
util::WinCmdLineArgs winArgs;
std::tie(argc, argv) = winArgs.get();
#endif
SetupEnvironment();
RandomInit();
try {
if (!WalletAppInit(argc, argv)) return EXIT_FAILURE;
} catch (const std::exception& e) {
PrintExceptionContinue(&e, "WalletAppInit()");
return EXIT_FAILURE;
} catch (...) {
PrintExceptionContinue(nullptr, "WalletAppInit()");
return EXIT_FAILURE;
}
std::string method {};
for(int i = 1; i < argc; ++i) {
if (!IsSwitchChar(argv[i][0])) {
if (!method.empty()) {
tfm::format(std::cerr, "Error: two methods provided (%s and %s). Only one method should be provided.\n", method.c_str(), argv[i]);
return EXIT_FAILURE;
}
method = argv[i];
}
}
if (method.empty()) {
tfm::format(std::cerr, "No method provided. Run `talkcoin-wallet -help` for valid methods.\n");
return EXIT_FAILURE;
}
// A name must be provided when creating a file
if (method == "create" && !gArgs.IsArgSet("-wallet")) {
tfm::format(std::cerr, "Wallet name must be provided when creating a new wallet.\n");
return EXIT_FAILURE;
}
std::string name = gArgs.GetArg("-wallet", "");
ECCVerifyHandle globalVerifyHandle;
ECC_Start();
if (!WalletTool::ExecuteWalletToolFunc(method, name))
return EXIT_FAILURE;
ECC_Stop();
return EXIT_SUCCESS;
}
| [
"[email protected]"
] | |
509a47bbffeea4e7a2ccc2c8024a22ab3de267da | 78e649c37d6ed6635d480fc81d94e084f8d9c1cb | /CodingInterviewProblems/StringsAndArrays_Problem9.hpp | a5c360f6f5e20fd22a4633bb009873aaaa4a3e22 | [] | no_license | Bukenberger/CodingInterviewProblems | eb08fb3d564485250daf007799127911d87fb050 | d11366029f80d88a7e48a43c7ab463d5566cec26 | refs/heads/main | 2023-02-05T23:56:40.502318 | 2020-12-21T06:55:25 | 2020-12-21T06:55:25 | 322,975,541 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 606 | hpp | /*
* @file StringsAndArrays_Problem9.hpp
* @date 2020-12-19
* @author Teran Bukenberger
*
* @brief Contains function prototypes for the ninth problem of the Strings and Arrays category
*/
#ifndef __STRINGS_AND_ARRAYS_PROBLEM_9_HPP__
#define __STRINGS_AND_ARRAYS_PROBLEM_9_HPP__
#include <string>
#include "Utilities.hpp"
/*
Function Name: string_rotation
Purpose: Check is a string is a rotation of another
Accepts: const string&, const string&
Returns: bool
*/
bool string_rotation( const std::string& str1, const std::string& str2 );
#endif // !__STRINGS_AND_ARRAYS_PROBLEM_9_HPP__ | [
"[email protected]"
] | |
6a261b087866665c9715f5e1aa111337c608d222 | dc603c5e4b8c05b319359b6588e2eadbe3a0f745 | /simple_navigation_goals/src/point_b_navigation_goal.cpp | facf63b40930ac11dd957718728e11f3303cd3a5 | [] | no_license | japerezg86/warehouse_navigation | ebf01515085a56b57eb301f53d6882fa41c5a794 | 3c5100d80e361643255a77f59c1f0a2c37f1d83b | refs/heads/main | 2023-04-18T15:12:16.905864 | 2021-05-02T17:32:10 | 2021-05-02T17:32:10 | 363,567,082 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,498 | cpp | #include <ros/ros.h>
#include <move_base_msgs/MoveBaseAction.h>
#include <actionlib/client/simple_action_client.h>
using namespace std;
typedef actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> MoveBaseClient;
int main(int argc, char** argv){
ros::init(argc, argv, "point_b_navigation_goal");
//tell the action client that we want to spin a thread by default
MoveBaseClient ac("move_base", true);
//wait for the action server to come up
while(!ac.waitForServer(ros::Duration(5.0))){
ROS_INFO("Waiting for the move_base action server to come up");
}
ros::Time begin;
ros::Time end;
ros::Duration duration;
//define the move base goals for each room
move_base_msgs::MoveBaseGoal point_b_goal;
//send the first goal
point_b_goal.target_pose.header.frame_id = "map";
point_b_goal.target_pose.header.stamp = ros::Time::now();
point_b_goal.target_pose.pose.position.x = -13.2508673897;
point_b_goal.target_pose.pose.position.y = -6.03139311508;
point_b_goal.target_pose.pose.orientation.w = 1.0;
ROS_INFO("Sending point_b_goal");
begin = ros::Time::now();
ac.sendGoal(point_b_goal);
ac.waitForResult();
end = ros::Time::now();
duration = end - begin;
cout << "Time to reach goal in sec: " << duration.toSec() << endl;
if(ac.getState() == actionlib::SimpleClientGoalState::SUCCEEDED)
ROS_INFO("Hooray, the task has been achieved");
else
ROS_INFO("The base failed to achieve task for some reason");
return 0;
} | [
"[email protected]"
] | |
e877327bf0027b5ad78b8bb6e647a28b55d12d77 | 09d9b50726c2e5cdc768c57930a84edc984d2a6e | /CSACADEMY/CS_round_55_A.cpp | 3c7d0f96d6d644d351201e209b221063bfbc42a4 | [] | no_license | omar-sharif03/Competitive-Programming | 86b4e99f16a6711131d503eb8e99889daa92b53d | c8bc015af372eeb328c572d16038d0d0aac6bb6a | refs/heads/master | 2022-11-15T08:22:08.474648 | 2020-07-15T12:30:53 | 2020-07-15T12:30:53 | 279,789,803 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 343 | cpp | #include<bits/stdc++.h>
using namespace std;
int room[110];
int main()
{
int n,m;
cin>>n>>m;
for(int i=1;i<=m;i++)
cin>>room[i];
int a,b,c;
for(int i=1;i<=n;i++){
cin>>a>>b;
c=0;
for(int j=1;j<=m;j++){
if(room[j]>=a and room[j]<=b)c++;
}
cout<<c<<endl;
}
}
| [
"[email protected]"
] | |
349ef8d8bb00fe3e56f0f7d5e8040e80c16d903d | de7e771699065ec21a340ada1060a3cf0bec3091 | /demo/src/java/org/apache/lucene/demo/facet/SimpleSortedSetFacetsExample.cpp | fb5961262ce8f23262fef9fd8ca2c6810e9f0cf9 | [] | no_license | sraihan73/Lucene- | 0d7290bacba05c33b8d5762e0a2a30c1ec8cf110 | 1fe2b48428dcbd1feb3e10202ec991a5ca0d54f3 | refs/heads/master | 2020-03-31T07:23:46.505891 | 2018-12-08T14:57:54 | 2018-12-08T14:57:54 | 152,020,180 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,112 | cpp | using namespace std;
#include "SimpleSortedSetFacetsExample.h"
namespace org::apache::lucene::demo::facet
{
using WhitespaceAnalyzer =
org::apache::lucene::analysis::core::WhitespaceAnalyzer;
using Document = org::apache::lucene::document::Document;
using DrillDownQuery = org::apache::lucene::facet::DrillDownQuery;
using FacetResult = org::apache::lucene::facet::FacetResult;
using Facets = org::apache::lucene::facet::Facets;
using FacetsCollector = org::apache::lucene::facet::FacetsCollector;
using FacetsConfig = org::apache::lucene::facet::FacetsConfig;
using DefaultSortedSetDocValuesReaderState =
org::apache::lucene::facet::sortedset::DefaultSortedSetDocValuesReaderState;
using SortedSetDocValuesFacetCounts =
org::apache::lucene::facet::sortedset::SortedSetDocValuesFacetCounts;
using SortedSetDocValuesFacetField =
org::apache::lucene::facet::sortedset::SortedSetDocValuesFacetField;
using SortedSetDocValuesReaderState =
org::apache::lucene::facet::sortedset::SortedSetDocValuesReaderState;
using DirectoryReader = org::apache::lucene::index::DirectoryReader;
using IndexWriter = org::apache::lucene::index::IndexWriter;
using IndexWriterConfig = org::apache::lucene::index::IndexWriterConfig;
using OpenMode = org::apache::lucene::index::IndexWriterConfig::OpenMode;
using IndexSearcher = org::apache::lucene::search::IndexSearcher;
using MatchAllDocsQuery = org::apache::lucene::search::MatchAllDocsQuery;
using Directory = org::apache::lucene::store::Directory;
using RAMDirectory = org::apache::lucene::store::RAMDirectory;
SimpleSortedSetFacetsExample::SimpleSortedSetFacetsExample() {}
void SimpleSortedSetFacetsExample::index()
{
shared_ptr<IndexWriter> indexWriter = make_shared<IndexWriter>(
indexDir,
(make_shared<IndexWriterConfig>(make_shared<WhitespaceAnalyzer>()))
->setOpenMode(IndexWriterConfig::OpenMode::CREATE));
shared_ptr<Document> doc = make_shared<Document>();
doc->push_back(make_shared<SortedSetDocValuesFacetField>(L"Author", L"Bob"));
doc->push_back(
make_shared<SortedSetDocValuesFacetField>(L"Publish Year", L"2010"));
indexWriter->addDocument(config->build(doc));
doc = make_shared<Document>();
doc->push_back(make_shared<SortedSetDocValuesFacetField>(L"Author", L"Lisa"));
doc->push_back(
make_shared<SortedSetDocValuesFacetField>(L"Publish Year", L"2010"));
indexWriter->addDocument(config->build(doc));
doc = make_shared<Document>();
doc->push_back(make_shared<SortedSetDocValuesFacetField>(L"Author", L"Lisa"));
doc->push_back(
make_shared<SortedSetDocValuesFacetField>(L"Publish Year", L"2012"));
indexWriter->addDocument(config->build(doc));
doc = make_shared<Document>();
doc->push_back(
make_shared<SortedSetDocValuesFacetField>(L"Author", L"Susan"));
doc->push_back(
make_shared<SortedSetDocValuesFacetField>(L"Publish Year", L"2012"));
indexWriter->addDocument(config->build(doc));
doc = make_shared<Document>();
doc->push_back(
make_shared<SortedSetDocValuesFacetField>(L"Author", L"Frank"));
doc->push_back(
make_shared<SortedSetDocValuesFacetField>(L"Publish Year", L"1999"));
indexWriter->addDocument(config->build(doc));
delete indexWriter;
}
deque<std::shared_ptr<FacetResult>>
SimpleSortedSetFacetsExample::search()
{
shared_ptr<DirectoryReader> indexReader = DirectoryReader::open(indexDir);
shared_ptr<IndexSearcher> searcher = make_shared<IndexSearcher>(indexReader);
shared_ptr<SortedSetDocValuesReaderState> state =
make_shared<DefaultSortedSetDocValuesReaderState>(indexReader);
// Aggregatses the facet counts
shared_ptr<FacetsCollector> fc = make_shared<FacetsCollector>();
// MatchAllDocsQuery is for "browsing" (counts facets
// for all non-deleted docs in the index); normally
// you'd use a "normal" query:
FacetsCollector::search(searcher, make_shared<MatchAllDocsQuery>(), 10, fc);
// Retrieve results
shared_ptr<Facets> facets =
make_shared<SortedSetDocValuesFacetCounts>(state, fc);
deque<std::shared_ptr<FacetResult>> results =
deque<std::shared_ptr<FacetResult>>();
results.push_back(facets->getTopChildren(10, L"Author"));
results.push_back(facets->getTopChildren(10, L"Publish Year"));
indexReader->close();
return results;
}
shared_ptr<FacetResult>
SimpleSortedSetFacetsExample::drillDown()
{
shared_ptr<DirectoryReader> indexReader = DirectoryReader::open(indexDir);
shared_ptr<IndexSearcher> searcher = make_shared<IndexSearcher>(indexReader);
shared_ptr<SortedSetDocValuesReaderState> state =
make_shared<DefaultSortedSetDocValuesReaderState>(indexReader);
// Now user drills down on Publish Year/2010:
shared_ptr<DrillDownQuery> q = make_shared<DrillDownQuery>(config);
q->add(L"Publish Year", {L"2010"});
shared_ptr<FacetsCollector> fc = make_shared<FacetsCollector>();
FacetsCollector::search(searcher, q, 10, fc);
// Retrieve results
shared_ptr<Facets> facets =
make_shared<SortedSetDocValuesFacetCounts>(state, fc);
shared_ptr<FacetResult> result = facets->getTopChildren(10, L"Author");
indexReader->close();
return result;
}
deque<std::shared_ptr<FacetResult>>
SimpleSortedSetFacetsExample::runSearch()
{
index();
return search();
}
shared_ptr<FacetResult>
SimpleSortedSetFacetsExample::runDrillDown()
{
index();
return drillDown();
}
void SimpleSortedSetFacetsExample::main(std::deque<wstring> &args) throw(
runtime_error)
{
wcout << L"Facet counting example:" << endl;
wcout << L"-----------------------" << endl;
shared_ptr<SimpleSortedSetFacetsExample> example =
make_shared<SimpleSortedSetFacetsExample>();
deque<std::shared_ptr<FacetResult>> results = example->runSearch();
wcout << L"Author: " << results[0] << endl;
wcout << L"Publish Year: " << results[0] << endl;
wcout << L"\n" << endl;
wcout << L"Facet drill-down example (Publish Year/2010):" << endl;
wcout << L"---------------------------------------------" << endl;
wcout << L"Author: " << example->runDrillDown() << endl;
}
} // namespace org::apache::lucene::demo::facet | [
"[email protected]"
] | |
41cb15b26a2cc28c060023b9ab6d1a22027645bb | 5530d7a83cf7e7538452f8073c5a8902a0ff1616 | /_archive_cpp/source/synthese_additive_decisionnelle.h | 38517d83724b821cc07e81c9852e85a00c0b72bf | [
"MIT"
] | permissive | overetou/synthe_alea | eb7aa430e55b35c6d405e431ae9fd17eaa3f1c68 | 3f1e6ba3eb90f70bc7a475f092d2d160089e758e | refs/heads/master | 2020-03-27T03:54:59.243487 | 2018-11-04T15:45:32 | 2018-11-04T15:45:32 | 145,898,440 | 1 | 1 | MIT | 2018-09-10T08:51:01 | 2018-08-23T19:31:36 | C++ | UTF-8 | C++ | false | false | 14,017 | h | #pragma once
#include <vector>
#include <algorithm>
#include <functional>
#include <iostream>
#include <fstream>
#define PI 3.1427
namespace synthese_additive_decisionnelle
{
#pragma region Base de données
// A FAIRE :
// - paramètres pour caractériser les spectres
// - organisation du fichier texte
// Ajoute un nouveau spectre à la collection et en calcule les paramètres
bool ajouter_spectre_dans_la_collection(
const std::vector<double> &litudes_brutes,
const std::vector<double> &frequences_brutes,
const double hauteur_enregistrement)
{
if (amplitudes_brutes.size() != frequences_brutes.size()) return false; // Pas le même nombre de points
if (hauteur_enregistrement < 0) return false; // Fréquence négative
std::vector<std::pair<double, double>> partiels;
for (std::size_t i_partiel = 0; i_partiel < amplitudes_brutes.size(); i_partiel++)
{
partiels.push_back({ amplitudes_brutes[i_partiel], frequences_brutes[i_partiel] });
}
// Etalonnage des amplitudes
double max_amplitude = 0;
for (std::size_t i_amplitude = 0; i_amplitude < partiels.size(); i_amplitude++)
{
max_amplitude = std::fmax(max_amplitude, partiels[i_amplitude].first);
}
std::transform(
partiels.begin(),
partiels.end(),
partiels.begin(),
std::bind(diviser_amplitudes, std::placeholders::_1, max_amplitude));
// Transformation des fréquences en ratios par rapport à la hauteur d'enregistrement
std::transform(
partiels.begin(),
partiels.end(),
partiels.begin(),
std::bind(diviser_frequences, std::placeholders::_1, hauteur_enregistrement));
// Calcul de la puissance du spectre
// Calcul de la dispersion du spectre
//... autres paramètres ?
double ecart_inharmonique;
double somme_ecarts = 0;
for (std::size_t i_partiel; i_partiel < partiels.size(); i_partiel++)
{
ecart_inharmonique = std::fmin(std::fmod(partiels[i_partiel].second, hauteur_enregistrement), std::fabs(hauteur_enregistrement - std::fmod(partiels[i_partiel].second, hauteur_enregistrement))) / hauteur_enregistrement;
somme_ecarts += ecart_inharmonique * partiels[i_partiel].first;
}
double somme_amplitudes = 0;
for (std::size_t i_partiel; i_partiel < partiels.size(); i_partiel++)
{
somme_amplitudes += partiels[i_partiel].first;
}
somme_ecarts /= somme_amplitudes;
// Théorème de Rolle pour nettoyer le spectre
for (std::size_t i_partiel = 1; i_partiel < partiels.size(); i_partiel++)
{
if (!(partiels.at(i_partiel++).first - partiels.at(i_partiel).first < 0 && 0 < partiels.at(i_partiel).first - partiels.at(i_partiel--).first))
{
partiels.at(i_partiel).first = 0;
}
}
// Tri par amplitude décroissante des partiels du spectre
std::sort(
partiels.begin(),
partiels.end(),
trier_partiels_amplitudes_descendant);
// Ajout du nouveau spectre à la collection
spectre nouveau_spectre;
nouveau_spectre.partiels = partiels;
collection_spectres.push_back(nouveau_spectre);
return true;
}
// Charge la collection depuis un fichier sérialisé
bool charger_collection_spectres(const std::string &url_collection)
{
std::ifstream lecture_fichier;
lecture_fichier.open(url_collection, std::ios::in);
if (!lecture_fichier.is_open()) return false;
else
{
// charge le contenu du fichier dans collection_spectres
//ajouter_spectre();
}
lecture_fichier.close();
return true;
}
// Sauvegarde la collection vers un fichier sérialisé
bool sauvegarder_collection_spectres(const std::string &url_collection)
{
std::ofstream ecriture_fichier;
ecriture_fichier.open(url_collection, std::ios::out);
if (!ecriture_fichier.is_open()) return false;
ecriture_fichier << "nom_collection = " << url_collection << std::endl;
ecriture_fichier << "nombre_spectres = " << collection_spectres.size() << std::endl;
ecriture_fichier << std::endl;
// Ecriture des spectres
for (std::size_t i_spectre = 0; i_spectre < collection_spectres.size(); i_spectre++)
{
ecriture_fichier << "indice_spectre = " << i_spectre << std::endl;
ecriture_fichier << std::endl;
// Ecriture des amplitudes
ecriture_fichier << "amplitudes = " << std::endl;
for (std::size_t i_partiel = 0; i_partiel < collection_spectres[i_spectre].partiels.size(); i_partiel++)
{
ecriture_fichier << collection_spectres[i_spectre].partiels[i_partiel].first << std::endl;
}
ecriture_fichier << std::endl;
// Ecriture des fréquences
ecriture_fichier << "frequences = " << std::endl;
for (std::size_t i_partiel = 0; i_partiel < collection_spectres[i_spectre].partiels.size(); i_partiel++)
{
ecriture_fichier << collection_spectres[i_spectre].partiels[i_partiel].second << std::endl;
}
ecriture_fichier << std::endl;
// Ecriture des caractéristiques
ecriture_fichier << "puissance = " << collection_spectres[i_spectre].puissance << std::endl;
ecriture_fichier << "dispersion = " << collection_spectres[i_spectre].dispersion << std::endl;
ecriture_fichier << std::endl;
}
ecriture_fichier.close();
return true;
}
#pragma endregion
#pragma region IA décisionnelle
// Construire le spectre évolutif dans le temps avec les spectres les plus appropriés
bool calcul_collection_oscillateurs(
const std::vector<double> &indices_temporels,
const std::vector<double> &evolution_puissance,
const std::vector<double> &evolution_dispersion,
const std::size_t nombre_oscillateurs)
{
// Tests
//
std::size_t nombre_spectres = indices_temporels.size();
// Trouver pour chaque point temporel le spectre le plus approprié en fonction des paramètres de l'utilisateur à ce point
//
std::vector<std::vector<std::pair<double, double>>> spectres_selectionnes(indices_temporels.size());
for (std::size_t i_spectre = 0; i_spectre < spectres_selectionnes.size(); i_spectre++)
{
// On commence par ne garder que le bon nombre d'oscillateurs
spectres_selectionnes[i_spectre].resize(nombre_oscillateurs);
// Suivi des oscillateurs
if (i_spectre > 0)
{
// Parcourt le spectre précédent
for (std::size_t i_partiel = 0; i_partiel < nombre_oscillateurs; i_partiel++)
{
double min_ecart = 10000;
std::size_t indice_min_ecart;
// Trouve le partiel le plus proche dans le spectre actuel
for (std::size_t ii_partiel = i_partiel; ii_partiel < nombre_oscillateurs; ii_partiel++)
{
double ecart = std::fabs(spectres_selectionnes[i_spectre][ii_partiel].second - spectres_selectionnes[i_spectre - 1][i_partiel].second);
if (ecart < min_ecart)
{
min_ecart = ecart;
indice_min_ecart = ii_partiel;
}
}
// Modifier le spectre actuel pour replacer le partiel le plus proche sur la meme ligne que dans le spectre précédent
// retirer le trouvé du vecteur à spectres_selectionnes[i_spectre][indice_min_ecart]
// le rajouter à la position voulue spectres_selectionnes[i_spectre][i_partiel]
}
}
}
// Construction de la matrice d'interpolation de Vandermonde avec les indices temporels
// Initialisation
std::vector<std::vector<std::size_t>> matrice_interpolation(2 * nombre_spectres);
for (std::size_t i_rang = 0; i_rang < 2 * nombre_spectres; i_rang++) matrice_interpolation[i_rang].resize(nombre_spectres);
// Remplissage
for (std::size_t i_rang = 0; i_rang < 2 * nombre_spectres; i_rang++)
{
for (std::size_t i_colonne = 0; i_colonne < nombre_spectres; i_colonne++)
{
// Augmentation de la matrice
if (i_rang < nombre_spectres)
{
if (i_rang == i_colonne) matrice_interpolation[i_rang][i_colonne] = 1;
else matrice_interpolation[i_rang][i_colonne] = 0;
}
// Matrice de Vandermonde
else
{
matrice_interpolation[nombre_spectres + i_rang][i_colonne] = 0;
}
}
}
// Inversion de la matrice d'interpolation
// Algorithme de gauss
// Calcul pour chaque oscillateur des coefficients du polynôme d'interpolation
for (std::size_t i_oscillateur = 0; i_oscillateur < nombre_oscillateurs; i_oscillateur++)
{
// Pour les amplitudes
// A^-1 * a
// Pour les fréquences
// A^-1 * f
}
}
#pragma endregion
#pragma region Synthèse additive
enum parmetres_synthese
{
parametre_frequence_echantillonnage,
parametre_gain
};
// Modifie un paramètre de la synthèse
bool modifier_parametre_synthese(const std::size_t parametre, const double valeur)
{
switch (parametre)
{
case parametre_frequence_echantillonnage: frequence_echantillonnage = (int)valeur;
case parametre_gain: gain = (double)valeur;
}
return true;
}
// Charge la collection depuis un fichier texte
bool charger_collection_oscillateurs(const std::string &url_collection)
{
std::ifstream lecture_fichier;
lecture_fichier.open(url_collection, std::ios::in);
if (!lecture_fichier.is_open()) return false;
// lire nombre oscillateurs
// lire nombre coefficients
std::size_t nombre_oscillateurs;
std::size_t nombre_coefficients;
// Resize de la collection d'oscillateurs
collection_oscillateurs.resize(nombre_oscillateurs);
for (std::size_t i_oscillateur = 0; i_oscillateur < nombre_oscillateurs; i_oscillateur++)
{
collection_oscillateurs[i_oscillateur].resize(nombre_coefficients);
}
for (std::size_t i_oscillateur = 0; i_oscillateur < nombre_oscillateurs; i_oscillateur++)
{
// verifier l'indice
// Lecture des amplitudes
for (std::size_t i_coefficient = 0; i_coefficient < nombre_coefficients; i_coefficient++)
{
lecture_fichier >> collection_oscillateurs[i_oscillateur][i_coefficient].first;
}
//
// Lecture des fréquences
for (std::size_t i_coefficient = 0; i_coefficient < nombre_coefficients; i_coefficient++)
{
lecture_fichier >> collection_oscillateurs[i_oscillateur][i_coefficient].second;
}
}
lecture_fichier.close();
return true;
}
// Sauvegarde la collection vers un fichier texte
bool sauvegarder_collection_oscillateurs(const std::string &url_collection) // faire les 3 autres comme celui-là
{
std::ofstream ecriture_fichier;
ecriture_fichier.open(url_collection, std::ios::out);
if (!ecriture_fichier.is_open()) return false;
ecriture_fichier << "nom_preset =" << url_collection << std::endl;
ecriture_fichier << "nombre_oscillateurs = " << collection_oscillateurs.size() << std::endl;
ecriture_fichier << "nombre_coefficients = " << collection_oscillateurs[0].size() << std::endl;
ecriture_fichier << std::endl;
// Ecriture des oscillateurs
for (std::size_t i_oscillateur = 0; i_oscillateur < collection_oscillateurs.size(); i_oscillateur++)
{
ecriture_fichier << "indice_oscillateur = " << i_oscillateur << std::endl;
ecriture_fichier << std::endl;
// Ecriture des amplitudes
ecriture_fichier << "amplitudes = " << std::endl;
for (std::size_t i_coefficient = 0; i_coefficient < collection_oscillateurs.size(); i_coefficient++)
{
ecriture_fichier << collection_oscillateurs[i_oscillateur][i_coefficient].first << std::endl;
}
ecriture_fichier << std::endl;
// Ecriture des fréquences
ecriture_fichier << "frequences = " << std::endl;
for (std::size_t i_coefficient = 0; i_coefficient < collection_oscillateurs.size(); i_coefficient++)
{
ecriture_fichier << collection_oscillateurs[i_oscillateur][i_coefficient].second << std::endl;
}
ecriture_fichier << std::endl;
}
ecriture_fichier.close();
return true;
}
// Synthétise le son en temps réel depuis les polynômes d'interpolation
double synthese(const std::size_t indice_echantillon, const double frequence, const double velocite)
{
if (collection_oscillateurs.size() == 0) return false; // Collection d'oscillateurs pas encore chargée
double indice_temporel; // f de indice_echantillon, frequence_echantillonnage
double indice_puissance;
double oscillateur_amplitude;
double oscillateur_frequence;
double somme_oscillateurs = 0;
for (std::size_t i_oscillateur = 0; i_oscillateur < collection_oscillateurs.size(); i_oscillateur++)
{
oscillateur_amplitude = 0;
oscillateur_frequence = 0;
for (std::size_t i_coefficient = 0; i_coefficient < collection_oscillateurs[i_oscillateur].size(); i_coefficient++)
{
indice_puissance = std::pow(indice_temporel, i_coefficient);
oscillateur_amplitude += collection_oscillateurs[i_oscillateur][i_coefficient].first * velocite * indice_puissance;
oscillateur_frequence += collection_oscillateurs[i_oscillateur][i_coefficient].second * frequence * indice_puissance;
}
somme_oscillateurs += oscillateur_amplitude * std::sin(2 * PI * oscillateur_frequence * indice_temporel);
}
if (std::abs(somme_oscillateurs) > 1) gain = 1 / std::abs(somme_oscillateurs);
return somme_oscillateurs * gain;
}
#pragma endregion
#pragma region Private scope
namespace
{
// Spectres
struct spectre
{
std::vector<std::pair<double, double>> partiels; // On utilise .first : amplitudes et .second : fréquences
// Paramètres caractérisant le spectre
double puissance;
double dispersion;
};
std::vector<spectre> collection_spectres;
double diviser_amplitudes(
const std::pair<double, double> &a,
const double b)
{
return (a.first / b);
}
double diviser_frequences(
const std::pair<double, double> &a,
const double b)
{
return (a.second / b);
}
// Trier les partiels par ordre décroissant d'amplitude
bool trier_partiels_amplitudes_descendant(
const std::pair<double, double> &partiel_a,
const std::pair<double, double> &partiel_b)
{
return (partiel_a.first > partiel_b.first);
}
// Oscillateurs [i_oscillateur][i_coefficient_lagrange].first / .second
std::vector<std::vector<std::pair<double, double>>> collection_oscillateurs;
// Paramètres de la synthèse
std::size_t frequence_echantillonnage = 44100;
double gain = 1;
struct note
{
std::size_t midi_note;
std::size_t midi_velocity;
};
}
#pragma endregion
}
| [
"[email protected]"
] | |
4514451a7e7de063b79e12fbabd843845df0e3d6 | e51863bee27f813e2febfe313ca67f45ea9296ec | /spyder/widgets/sourcecode/codeeditor.cpp | 29651e615d690769bcecdaeaad3ac697671c1bd9 | [] | no_license | sk8boy/MySpyder | 3d2ed6dfcf2d29e78be163e5d7e1433651edd852 | 4db4f1eebcbfb337b10b2ab1220922d0da090b4c | refs/heads/master | 2022-09-27T02:55:39.748340 | 2020-06-07T12:09:34 | 2020-06-07T12:09:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 126,638 | cpp | #include "codeeditor.h"
GoToLineDialog::GoToLineDialog(CodeEditor* editor)
: QDialog (editor, Qt::WindowTitleHint
| Qt::WindowCloseButtonHint)
{
setAttribute(Qt::WA_DeleteOnClose);
lineno = -1;
this->editor = editor;
setWindowTitle("Editor");
setModal(true);
QLabel *label = new QLabel("Go to line:");
lineedit = new QLineEdit;
QIntValidator* validator = new QIntValidator(lineedit);
validator->setRange(1, editor->get_line_count());
lineedit->setValidator(validator);
connect(lineedit,SIGNAL(textChanged(const QString &)),
this,SLOT(text_has_changed(const QString &)));
QLabel *cl_label = new QLabel("Current line:");
QLabel *cl_label_v = new QLabel(QString("<b>%1</b>").arg(editor->get_cursor_line_number()));
QLabel *last_label = new QLabel("Line count:");
QLabel *last_label_v = new QLabel(QString("%1").arg(editor->get_line_count()));
QGridLayout* glayout = new QGridLayout();
glayout->addWidget(label, 0, 0, Qt::AlignVCenter|Qt::AlignRight);
glayout->addWidget(lineedit, 0, 1, Qt::AlignVCenter);
glayout->addWidget(cl_label, 1, 0, Qt::AlignVCenter|Qt::AlignRight);
glayout->addWidget(cl_label_v, 1, 1, Qt::AlignVCenter);
glayout->addWidget(last_label, 2, 0, Qt::AlignVCenter|Qt::AlignRight);
glayout->addWidget(last_label_v, 2, 1, Qt::AlignVCenter);
QDialogButtonBox* bbox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel,
Qt::Vertical, this);
connect(bbox,SIGNAL(accepted()),this,SLOT(accept()));
connect(bbox,SIGNAL(rejected()),this,SLOT(reject()));
QVBoxLayout* btnlayout = new QVBoxLayout;
btnlayout->addWidget(bbox);
btnlayout->addStretch(1);
QPushButton* ok_button = bbox->button(QDialogButtonBox::Ok);
ok_button->setEnabled(false);
connect(lineedit,&QLineEdit::textChanged,
[=](const QString& text) { ok_button->setEnabled(text.size()>0); });
QHBoxLayout* layout = new QHBoxLayout;
layout->addLayout(glayout);
layout->addLayout(btnlayout);
setLayout(layout);
lineedit->setFocus();
}
void GoToLineDialog::text_has_changed(const QString &text)
{
if (!text.isEmpty())
lineno = text.toInt();
else
lineno = -1;
}
int GoToLineDialog::get_line_number()
{
return lineno;
}
//***********Viewport widgets
LineNumberArea::LineNumberArea(CodeEditor* editor)
: QWidget (editor)
{
code_editor = editor;
setMouseTracking(true);
}
QSize LineNumberArea::sizeHint() const
{
return QSize(code_editor->compute_linenumberarea_width(), 0);
}
void LineNumberArea::paintEvent(QPaintEvent *event)
{
code_editor->linenumberarea_paint_event(event);
}
void LineNumberArea::mouseMoveEvent(QMouseEvent *event)
{
code_editor->linenumberarea_mousemove_event(event);
}
void LineNumberArea::mouseDoubleClickEvent(QMouseEvent *event)
{
code_editor->linenumberarea_mousedoubleclick_event(event);
}
void LineNumberArea::mousePressEvent(QMouseEvent *event)
{
code_editor->linenumberarea_mousepress_event(event);
}
void LineNumberArea::mouseReleaseEvent(QMouseEvent *event)
{
code_editor->linenumberarea_mouserelease_event(event);
}
void LineNumberArea::wheelEvent(QWheelEvent *event)
{
code_editor->wheelEvent(event);
}
int ScrollFlagArea::WIDTH = 12;
int ScrollFlagArea::FLAGS_DX = 4;
int ScrollFlagArea::FLAGS_DY = 2;
ScrollFlagArea::ScrollFlagArea(CodeEditor* editor)
: QWidget (editor)
{
setAttribute(Qt::WA_OpaquePaintEvent);
code_editor = editor;
connect(editor->verticalScrollBar(),&QAbstractSlider::valueChanged,
[=](int) { this->repaint(); });
}
QSize ScrollFlagArea::sizeHint() const
{
return QSize(WIDTH, 0);
}
void ScrollFlagArea::paintEvent(QPaintEvent *event)
{
code_editor->scrollflagarea_paint_event(event);
}
void ScrollFlagArea::mousePressEvent(QMouseEvent *event)
{
QScrollBar* vsb = code_editor->verticalScrollBar();
double value = this->position_to_value(event->pos().y()-1);
vsb->setValue(static_cast<int>(value-.5*vsb->pageStep()));
}
double ScrollFlagArea::get_scale_factor(bool slider) const
{
int delta = slider ? 0 : 2;
QScrollBar* vsb = code_editor->verticalScrollBar();
int position_height = vsb->height() - delta - 1;
int value_height = vsb->maximum()-vsb->minimum()+vsb->pageStep();
return static_cast<double>(position_height) / value_height;
}
double ScrollFlagArea::value_to_position(int y, bool slider) const
{
int offset = slider ? 0 : 1;
QScrollBar* vsb = code_editor->verticalScrollBar();
return (y-vsb->minimum())*this->get_scale_factor(slider)+offset;
}
double ScrollFlagArea::position_to_value(int y, bool slider) const
{
int offset = slider ? 0 : 1;
QScrollBar* vsb = code_editor->verticalScrollBar();
return vsb->minimum()+qMax(0.0, (y-offset)/this->get_scale_factor(slider));
}
QRect ScrollFlagArea::make_flag_qrect(int position) const
{
return QRect(FLAGS_DX/2, position-FLAGS_DY/2,
WIDTH-FLAGS_DX, FLAGS_DY);
}
QRect ScrollFlagArea::make_slider_range(int value) const
{
QScrollBar* vsb = code_editor->verticalScrollBar();
double pos1 = value_to_position(value, true);
double pos2 = value_to_position(value + vsb->pageStep(), true);
return QRect(1, static_cast<int>(pos1), WIDTH-2, static_cast<int>(pos2-pos1+1));
}
void ScrollFlagArea::wheelEvent(QWheelEvent *event)
{
code_editor->wheelEvent(event);
}
//============EdgeLine
EdgeLine::EdgeLine(QWidget* editor)
: QWidget (editor)
{
code_editor = editor;
column = 79;
setAttribute(Qt::WA_TransparentForMouseEvents);
}
void EdgeLine::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
QColor color(Qt::darkGray);
color.setAlphaF(0.5);
painter.fillRect(event->rect(), color);
}
//============BlockUserData
BlockUserData::BlockUserData(CodeEditor* editor)
: QTextBlockUserData ()
{
this->editor = editor;
this->breakpoint = false;
this->breakpoint_condition = QString();
this->code_analysis = QList<QPair<QString,bool>>();
this->todo = "";
this->editor->blockuserdata_list.append(this);
}
bool BlockUserData::is_empty()
{
return (!breakpoint) && (code_analysis.isEmpty()) && (todo.isEmpty());
}
void BlockUserData::del()
{
editor->blockuserdata_list.removeOne(this);
delete this;
}
static void set_scrollflagarea_painter(QPainter* painter,const QString& light_color)
{
painter->setPen(QColor(light_color).darker(120));
painter->setBrush(QBrush(QColor(light_color)));
}
//提供该函数对QColor的重载是为了scrollflagarea_paint_event()函数
static void set_scrollflagarea_painter(QPainter* painter,const QColor& light_color)
{
painter->setPen(QColor(light_color).darker(120));
painter->setBrush(QBrush(QColor(light_color)));
}
QString get_file_language(const QString& filename,QString text)
{
QFileInfo info(filename);
QString ext = info.suffix();
QString language = ext;
if (ext.isEmpty()) {
if (text.isEmpty()) {
text = encoding::read(filename);
}
foreach (QString line, splitlines(text)) {
if (line.trimmed().isEmpty())
continue;
if (line.startsWith("#!")) {
QString shebang = line.mid(2);
if (shebang.contains("python"))
language = "python";
}
else
break;
}
}
return language;
}
/********** CodeEditor **********/
CodeEditor::CodeEditor(QWidget* parent)
: TextEditBaseWidget (parent)
{
this->LANGUAGES = {{"Python", {"PythonSH", "#"}},
{"Cpp", {"CppSH", "//"}},
{"Markdown", {"MarkdownSH", "#"}}};
this->TAB_ALWAYS_INDENTS = QStringList({"py", "pyw", "python", "c", "cpp", "cl", "h"});
setFocusPolicy(Qt::StrongFocus);
setCursorWidth(CONF_get("main", "cursor/width").toInt());
edge_line_enabled = true;
edge_line = new EdgeLine(this);
blanks_enabled = false;
markers_margin = true;
markers_margin_width = 15;
error_pixmap = ima::icon("error").pixmap(QSize(14, 14));
warning_pixmap = ima::icon("warning").pixmap(QSize(14, 14));
todo_pixmap = ima::icon("todo").pixmap(QSize(14, 14));
bp_pixmap = ima::icon("breakpoint_big").pixmap(QSize(14, 14));
bpc_pixmap = ima::icon("breakpoint_cond_big").pixmap(QSize(14, 14));
linenumbers_margin = true;
linenumberarea_enabled = false;
linenumberarea = new LineNumberArea(this);
connect(this,SIGNAL(blockCountChanged(int)),
this,SLOT(update_linenumberarea_width(int)));
connect(this,SIGNAL(updateRequest(QRect,int)),
this,SLOT(update_linenumberarea(QRect,int)));
linenumberarea_pressed = -1;
linenumberarea_released = -1;
occurrence_color = QColor();
ctrl_click_color = QColor();
sideareas_color = QColor();
matched_p_color = QColor();
unmatched_p_color = QColor();
normal_color = QColor();
comment_color = QColor();
linenumbers_color = QColor(Qt::darkGray);
highlighter_class = "TextSH";
highlighter = nullptr;
//QString ccs = "Spyder";
//if (!sh::COLOR_SCHEME_NAMES.contains(ccs))
// ccs = sh::COLOR_SCHEME_NAMES[0];
this->color_scheme = sh::get_color_scheme();
highlight_current_line_enabled = false;
scrollflagarea_enabled = false;
scrollflagarea = new ScrollFlagArea(this);
scrollflagarea->hide();
warning_color = "#FFAD07";
error_color = "#EA2B0E";
todo_color = "#B4D4F3";
breakpoint_color = "#30E62E";
this->update_linenumberarea_width();
document_id = reinterpret_cast<size_t>(this);
connect(this, SIGNAL(cursorPositionChanged()),
this, SLOT(__cursor_position_changed()));
__find_first_pos = -1;
__find_flags = -1;//本代码并没有用到
supported_language = false;
supported_cell_language = false;
// classfunc_match = None
comment_string = QString();
_kill_ring = new QtKillRing(this);
blockuserdata_list = QList<BlockUserData*>();
connect(this, SIGNAL(blockCountChanged(int)),
this, SLOT(update_breakpoints()));
timer_syntax_highlight = new QTimer(this);
timer_syntax_highlight->setSingleShot(true);
timer_syntax_highlight->setInterval(300);
connect(timer_syntax_highlight,SIGNAL(timeout()),
this,SLOT(run_pygments_highlighter()));
occurrence_highlighting = false;
occurrence_timer = new QTimer(this);
occurrence_timer->setSingleShot(true);
occurrence_timer->setInterval(1500);
connect(occurrence_timer,SIGNAL(timeout()),
this,SLOT(__mark_occurrences()));
occurrences = QList<int>();
occurrence_color = QColor(Qt::yellow).lighter(160);
connect(this,SIGNAL(textChanged()),this,SLOT(__text_has_changed()));
found_results = QList<int>();
found_results_color = QColor(Qt::magenta).lighter(180);
gotodef_action = nullptr;
this->setup_context_menu();
tab_indents = false;
tab_mode = true;
intelligent_backspace = true;
go_to_definition_enabled = false;
close_parentheses_enabled = true;
close_quotes_enabled = false;
add_colons_enabled = true;
auto_unindent_enabled = true;
this->setMouseTracking(true);
__cursor_changed = false;
ctrl_click_color = QColor(Qt::blue);
this->breakpoints = this->get_breakpoints();
shortcuts = this->create_shortcuts();
__visible_blocks = QList<IntIntTextblock>();
connect(this,SIGNAL(painted(QPaintEvent*)),SLOT(_draw_editor_cell_divider()));
connect(verticalScrollBar(),&QAbstractSlider::valueChanged,
[=](int){ this->rehighlight_cells(); });
}
void CodeEditor::cb_maker(int attr)
{
QTextCursor cursor = this->textCursor();
auto move_type = static_cast<QTextCursor::MoveOperation>(attr);
cursor.movePosition(move_type);
this->setTextCursor(cursor);
}
QList<ShortCutStrStr> CodeEditor::create_shortcuts()
{
QString keystr = "Ctrl+Space";
QShortcut* qsc = new QShortcut(QKeySequence(keystr), this);
connect(qsc,&QShortcut::activated, [=](){ this->do_completion(false); });
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr codecomp(qsc,"Editor","Code Completion");
keystr = "Ctrl+Alt+Up";
qsc = new QShortcut(QKeySequence(keystr), this, SLOT(duplicate_line()));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr duplicate_line(qsc,"Editor","Duplicate line");
keystr = "Ctrl+Alt+Down";
qsc = new QShortcut(QKeySequence(keystr), this, SLOT(copy_line()));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr copyline(qsc,"Editor","Copy line");
keystr = "Ctrl+D";
qsc = new QShortcut(QKeySequence(keystr), this, SLOT(delete_line()));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr deleteline(qsc,"Editor","Delete line");
keystr = "Alt+Up";
qsc = new QShortcut(QKeySequence(keystr), this, SLOT(move_line_up()));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr movelineup(qsc,"Editor","Move line up");
keystr = "Alt+Down";
qsc = new QShortcut(QKeySequence(keystr), this, SLOT(move_line_down()));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr movelinedown(qsc,"Editor","Move line down");
keystr = "Ctrl+Shift+Return";
qsc = new QShortcut(QKeySequence(keystr), this, SLOT(go_to_new_line()));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr gotonewline(qsc,"Editor","Go to new line");
keystr = "Ctrl+G";
qsc = new QShortcut(QKeySequence(keystr), this, SLOT(do_go_to_definition()));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr gotodef(qsc,"Editor","Go to definition");
keystr = "Ctrl+1";
qsc = new QShortcut(QKeySequence(keystr), this, SLOT(toggle_comment()));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr toggle_comment(qsc,"Editor","Toggle comment");
keystr = "Ctrl+4";
qsc = new QShortcut(QKeySequence(keystr), this, SLOT(blockcomment()));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr blockcomment(qsc,"Editor","Blockcomment");
keystr = "Ctrl+5";
qsc = new QShortcut(QKeySequence(keystr), this, SLOT(unblockcomment()));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr unblockcomment(qsc,"Editor","Unblockcomment");
keystr = "Ctrl+Shift+U";
qsc = new QShortcut(QKeySequence(keystr), this, SLOT(transform_to_uppercase()));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr transform_uppercase(qsc,"Editor","Transform to uppercase");
keystr = "Ctrl+U";
qsc = new QShortcut(QKeySequence(keystr), this, SLOT(transform_to_lowercase()));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr transform_lowercase(qsc,"Editor","Transform to lowercase");
// lambda表达式
keystr = "Ctrl+]";
qsc = new QShortcut(QKeySequence(keystr), this);
connect(qsc,&QShortcut::activated,[=]() { this->indent(true); });
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr indent(qsc,"Editor","Indent");
keystr = "Ctrl+[";
qsc = new QShortcut(QKeySequence(keystr), this);
connect(qsc,&QShortcut::activated,[=]() { this->unindent(true); });
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr unindent(qsc,"Editor","Unindent");
QSignalMapper* signalMapper = new QSignalMapper(this);
keystr = "Meta+A";//
qsc = new QShortcut(QKeySequence(keystr), this);
connect(qsc,SIGNAL(activated()),signalMapper,SLOT(map()));
signalMapper->setMapping(qsc, static_cast<int>(QTextCursor::StartOfLine));//
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr line_start(qsc,"Editor","Start of line");//
keystr = "Meta+E";
qsc = new QShortcut(QKeySequence(keystr), this);
connect(qsc,SIGNAL(activated()),signalMapper,SLOT(map()));
signalMapper->setMapping(qsc, static_cast<int>(QTextCursor::EndOfLine));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr line_end(qsc,"Editor","End of line");
keystr = "Meta+P";
qsc = new QShortcut(QKeySequence(keystr), this);
connect(qsc,SIGNAL(activated()),signalMapper,SLOT(map()));
signalMapper->setMapping(qsc, static_cast<int>(QTextCursor::Up));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr prev_line(qsc,"Editor","Previous line");
keystr = "Meta+N";
qsc = new QShortcut(QKeySequence(keystr), this);
connect(qsc,SIGNAL(activated()),signalMapper,SLOT(map()));
signalMapper->setMapping(qsc, static_cast<int>(QTextCursor::Down));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr next_line(qsc,"Editor","Next line");
keystr = "Meta+B";
qsc = new QShortcut(QKeySequence(keystr), this);
connect(qsc,SIGNAL(activated()),signalMapper,SLOT(map()));
signalMapper->setMapping(qsc, static_cast<int>(QTextCursor::Left));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr prev_char(qsc,"Editor","Previous char");
keystr = "Meta+F";
qsc = new QShortcut(QKeySequence(keystr), this);
connect(qsc,SIGNAL(activated()),signalMapper,SLOT(map()));
signalMapper->setMapping(qsc, static_cast<int>(QTextCursor::Right));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr next_char(qsc,"Editor","Next char");
keystr = "Meta+Left";
qsc = new QShortcut(QKeySequence(keystr), this);
connect(qsc,SIGNAL(activated()),signalMapper,SLOT(map()));
signalMapper->setMapping(qsc, static_cast<int>(QTextCursor::PreviousWord));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr prev_word(qsc,"Editor","Previous word");
keystr = "Meta+Right";
qsc = new QShortcut(QKeySequence(keystr), this);
connect(qsc,SIGNAL(activated()),signalMapper,SLOT(map()));
signalMapper->setMapping(qsc, static_cast<int>(QTextCursor::NextWord));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr next_word(qsc,"Editor","Next word");
keystr = "Meta+K";
qsc = new QShortcut(QKeySequence(keystr), this, SLOT(kill_line_end()));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr kill_line_end(qsc,"Editor","Kill to line end");
keystr = "Meta+U";
qsc = new QShortcut(QKeySequence(keystr), this, SLOT(kill_line_start()));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr kill_line_start(qsc,"Editor","Kill to line start");
keystr = "Meta+Y";
qsc = new QShortcut(QKeySequence(keystr), this);
connect(qsc,SIGNAL(activated()),_kill_ring,SLOT(yank()));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr yank(qsc,"Editor","Yank");
keystr = "Shift+Meta+Y";
qsc = new QShortcut(QKeySequence(keystr), this);
connect(qsc,SIGNAL(activated()),_kill_ring,SLOT(rotate()));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr kill_ring_rotate(qsc,"Editor","Rotate kill ring");
keystr = "Meta+Backspace";
qsc = new QShortcut(QKeySequence(keystr), this, SLOT(kill_prev_word()));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr kill_prev_word(qsc,"Editor","Kill previous word");
keystr = "Meta+D";
qsc = new QShortcut(QKeySequence(keystr), this, SLOT(kill_next_word()));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr kill_next_word(qsc,"Editor","Kill next word");
//
keystr = "Ctrl+Home";
qsc = new QShortcut(QKeySequence(keystr), this);
connect(qsc,SIGNAL(activated()),signalMapper,SLOT(map()));
signalMapper->setMapping(qsc, static_cast<int>(QTextCursor::Start));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr start_doc(qsc,"Editor","Start of Document");
keystr = "Ctrl+End";
qsc = new QShortcut(QKeySequence(keystr), this);
connect(qsc,SIGNAL(activated()),signalMapper,SLOT(map()));
signalMapper->setMapping(qsc, static_cast<int>(QTextCursor::End));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr end_doc(qsc,"Editor","End of Document");
//
connect(signalMapper, SIGNAL(mapped(int)),
this, SLOT(cb_maker(int)));
keystr = "Ctrl+Z";
qsc = new QShortcut(QKeySequence(keystr), this, SLOT(undo()));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr undo(qsc,"Editor","undo");
keystr = "Ctrl+Shift+Z";
qsc = new QShortcut(QKeySequence(keystr), this, SLOT(redo()));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr redo(qsc,"Editor","redo");
keystr = "Ctrl+X";
qsc = new QShortcut(QKeySequence(keystr), this, SLOT(cut()));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr cut(qsc,"Editor","cut");
keystr = "Ctrl+C";
qsc = new QShortcut(QKeySequence(keystr), this, SLOT(copy()));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr copy(qsc,"Editor","undo");
keystr = "Ctrl+V";
qsc = new QShortcut(QKeySequence(keystr), this, SLOT(paste()));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr paste(qsc,"Editor","paste");
keystr = "Delete";
qsc = new QShortcut(QKeySequence(keystr), this, SLOT(_delete()));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr _delete(qsc,"Editor","delete");
keystr = "Ctrl+A";
qsc = new QShortcut(QKeySequence(keystr), this, SLOT(selectAll()));
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr select_all(qsc,"Editor","Select All");
// lambda表达式
keystr = "Ctrl+Alt+M";
qsc = new QShortcut(QKeySequence(keystr), this);
connect(qsc,&QShortcut::activated,[=]() { this->enter_array_inline(); });
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr array_inline(qsc,"array_builder","enter array inline");
keystr = "Ctrl+M";
qsc = new QShortcut(QKeySequence(keystr), this);
connect(qsc,&QShortcut::activated,[=]() { this->enter_array_table(); });
qsc->setContext(Qt::WidgetWithChildrenShortcut);
ShortCutStrStr array_table(qsc,"array_builder","enter array table");
QList<ShortCutStrStr> res;
res << codecomp<< duplicate_line<< copyline<< deleteline<< movelineup
<< movelinedown<< gotonewline<< gotodef<< toggle_comment<< blockcomment
<< unblockcomment<< transform_uppercase<< transform_lowercase
<< line_start<< line_end<< prev_line<< next_line
<< prev_char<< next_char<< prev_word<< next_word<< kill_line_end
<< kill_line_start<< yank<< kill_ring_rotate<< kill_prev_word
<< kill_next_word<< start_doc<< end_doc<< undo<< redo<< cut<< copy
<< paste<< _delete<< select_all<< array_inline<< array_table<< indent
<< unindent;
return res;
}
QList<ShortCutStrStr> CodeEditor::get_shortcut_data()
{
return shortcuts;
}
void CodeEditor::closeEvent(QCloseEvent *event)
{
TextEditBaseWidget::closeEvent(event);
}
size_t CodeEditor::get_document_id()
{
return document_id;
}
void CodeEditor::set_as_clone(CodeEditor *editor)
{
// Set as clone editor
this->setDocument(editor->document());
document_id = editor->get_document_id();
highlighter = editor->highlighter;
eol_chars = editor->eol_chars;
this->_apply_highlighter_color_scheme();
}
//-----Widget setup and options
void CodeEditor::toggle_wrap_mode(bool enable)
{
this->set_wrap_mode(enable ? "word" : QString());
}
void CodeEditor::setup_editor(const QHash<QString, QVariant> &kwargs)
{
bool linenumbers = kwargs.value("linenumbers", true).toBool();
QString language = kwargs.value("language", QString()).toString();
bool markers = kwargs.value("markers", false).toBool();
// font
QHash<QString, QVariant> dict = kwargs.value("color_scheme", QHash<QString, QVariant>()).toHash();
QHash<QString, ColorBoolBool> color_scheme;
for (auto it=dict.begin();it!=dict.end();it++) {
QString key = it.key();
ColorBoolBool val = it.value().value<ColorBoolBool>();
color_scheme[key] = val;
}
bool wrap = kwargs.value("wrap", false).toBool();
bool tab_mode = kwargs.value("tab_mode", true).toBool();
bool intelligent_backspace = kwargs.value("intelligent_backspace", true).toBool();
bool highlight_current_line = kwargs.value("highlight_current_line", true).toBool();
bool highlight_current_cell = kwargs.value("highlight_current_cell", true).toBool();
bool occurrence_highlighting= kwargs.value("occurrence_highlighting", true).toBool();
bool scrollflagarea = kwargs.value("scrollflagarea", true).toBool();
bool edge_line = kwargs.value("edge_line", true).toBool();
int edge_line_column = kwargs.value("edge_line_column", 79).toInt();
bool codecompletion_auto = kwargs.value("codecompletion_auto", false).toBool();
bool codecompletion_case = kwargs.value("codecompletion_case", true).toBool();
bool codecompletion_enter = kwargs.value("codecompletion_enter", false).toBool();
bool show_blanks = kwargs.value("show_blanks", false).toBool();
// calltips
bool go_to_definition = kwargs.value("go_to_definition", false).toBool();
bool close_parentheses = kwargs.value("close_parentheses", true).toBool();
bool close_quotes = kwargs.value("close_quotes", false).toBool();
bool add_colons = kwargs.value("add_colons", true).toBool();
bool auto_unindent = kwargs.value("auto_unindent", true).toBool();
QString indent_chars = kwargs.value("indent_chars", QString(4,' ')).toString();
int tab_stop_width_spaces = kwargs.value("tab_stop_width_spaces", 4).toInt();
// cloned_from
QString filename = kwargs.value("filename", QString()).toString();
int occurrence_timeout = kwargs.value("occurrence_timeout", 1500).toInt();
this->set_codecompletion_auto(codecompletion_auto);
this->set_codecompletion_case(codecompletion_case);
this->set_codecompletion_enter(codecompletion_enter);
if (kwargs.contains("calltips"))
this->set_calltips(kwargs.value("calltips").toBool());
this->set_go_to_definition_enabled(go_to_definition);
this->set_close_parentheses_enabled(close_parentheses);
this->set_close_quotes_enabled(close_quotes);
this->set_add_colons_enabled(add_colons);
this->set_auto_unindent_enabled(auto_unindent);
this->set_indent_chars(indent_chars);
this->set_scrollflagarea_enabled(scrollflagarea);
this->set_edge_line_enabled(edge_line);
this->set_edge_line_column(edge_line_column);
this->set_blanks_enabled(show_blanks);
if (kwargs.contains("cloned_from") && kwargs.contains("font"))
this->setFont(kwargs.value("font").value<QFont>());
this->setup_margins(linenumbers, markers);
this->set_language(language, filename);
this->set_highlight_current_cell(highlight_current_cell);
this->set_highlight_current_line(highlight_current_line);
this->set_occurrence_highlighting(occurrence_highlighting);
this->set_occurrence_timeout(occurrence_timeout);
this->set_tab_mode(tab_mode);
this->toggle_intelligent_backspace(intelligent_backspace);
if (kwargs.contains("cloned_from")) {
size_t id = kwargs.value("cloned_from").toULongLong();
CodeEditor* cloned_from = reinterpret_cast<CodeEditor*>(id);
this->set_as_clone(cloned_from);
this->update_linenumberarea_width();
}
else if (kwargs.contains("font")) {
QFont font = kwargs.value("font").value<QFont>();
this->set_font(font, color_scheme);
}
else if (!color_scheme.isEmpty())
this->set_color_scheme(color_scheme);
this->set_tab_stop_width_spaces(tab_stop_width_spaces);
this->toggle_wrap_mode(wrap);
}
void CodeEditor::setup_editor(bool linenumbers, const QString& language, bool markers,
const QFont& font, const QHash<QString, ColorBoolBool> &color_scheme, bool wrap, bool tab_mode,
bool intelligent_backspace, bool highlight_current_line,
bool highlight_current_cell, bool occurrence_highlighting,
bool scrollflagarea, bool edge_line, int edge_line_column,
bool codecompletion_auto, bool codecompletion_case,
bool codecompletion_enter, bool show_blanks,
bool calltips, bool go_to_definition,
bool close_parentheses, bool close_quotes,
bool add_colons, bool auto_unindent, const QString& indent_chars,
int tab_stop_width_spaces, CodeEditor* cloned_from, const QString& filename,
int occurrence_timeout)
{
//# Code completion and calltips
set_codecompletion_auto(codecompletion_auto);
set_codecompletion_case(codecompletion_case);
set_codecompletion_enter(codecompletion_enter);
set_calltips(calltips);
set_go_to_definition_enabled(go_to_definition);
set_close_parentheses_enabled(close_parentheses);
set_close_quotes_enabled(close_quotes);
set_add_colons_enabled(add_colons);
set_auto_unindent_enabled(auto_unindent);
set_indent_chars(indent_chars);
set_scrollflagarea_enabled(scrollflagarea);
set_edge_line_enabled(edge_line);
set_edge_line_column(edge_line_column);
set_blanks_enabled(show_blanks);
if (cloned_from)
setFont(font);
setup_margins(linenumbers, markers);
set_language(language, filename);
set_highlight_current_cell(highlight_current_cell);
set_highlight_current_line(highlight_current_line);
set_occurrence_highlighting(occurrence_highlighting);
set_occurrence_timeout(occurrence_timeout);
set_tab_mode(tab_mode);
toggle_intelligent_backspace(intelligent_backspace);
if (cloned_from) {
set_as_clone(cloned_from);
update_linenumberarea_width();
}
else if (font != this->font())
set_font(font, color_scheme);
else if (!color_scheme.isEmpty())
set_color_scheme(color_scheme);
set_tab_stop_width_spaces(tab_stop_width_spaces);
toggle_wrap_mode(wrap);
}
void CodeEditor::set_tab_mode(bool enable)
{
this->tab_mode = enable;
}
void CodeEditor::toggle_intelligent_backspace(bool state)
{
this->intelligent_backspace = state;
}
void CodeEditor::set_go_to_definition_enabled(bool enable)
{
this->go_to_definition_enabled = enable;
}
void CodeEditor::set_close_parentheses_enabled(bool enable)
{
this->close_parentheses_enabled = enable;
}
void CodeEditor::set_close_quotes_enabled(bool enable)
{
this->close_quotes_enabled = enable;
}
void CodeEditor::set_add_colons_enabled(bool enable)
{
this->add_colons_enabled = enable;
}
void CodeEditor::set_auto_unindent_enabled(bool enable)
{
this->auto_unindent_enabled = enable;
}
void CodeEditor::set_occurrence_highlighting(bool enable)
{
this->occurrence_highlighting = enable;
if (!enable)
this->__clear_occurrences();
}
void CodeEditor::set_occurrence_timeout(int timeout)
{
this->occurrence_timer->setInterval(timeout);
}
void CodeEditor::set_highlight_current_line(bool enable)
{
this->highlight_current_line_enabled = enable;
if (this->highlight_current_line_enabled)
this->highlight_current_line();
else
this->unhighlight_current_line();
}
void CodeEditor::set_highlight_current_cell(bool enable)
{
bool hl_cell_enable = enable && this->supported_cell_language;
this->highlight_current_cell_enabled = hl_cell_enable;
if (this->highlight_current_cell_enabled)
this->highlight_current_cell();
else
this->unhighlight_current_cell();
}
void CodeEditor::set_language(const QString &language, const QString &filename)
{
this->tab_indents = this->TAB_ALWAYS_INDENTS.contains(language);
this->comment_string = "";
QString sh_class = "TextSH";
if (!language.isEmpty()) {
//以后在这里添加别的语言,记得在构造函数更新LANGUAGES成员
QStringList list({"Python", "Cpp", "Markdown"});
foreach (QString key, list) {
if (sourcecode::ALL_LANGUAGES[key].contains(language.toLower())) {
this->supported_language = true;
sh_class = LANGUAGES[key][0];
QString comment_string = LANGUAGES[key][1];
this->comment_string = comment_string;
//key in CELL_LANGUAGES等价于key == "Python"
if (key == "Python") {
this->supported_cell_language = true;
this->cell_separators = sourcecode::CELL_LANGUAGES[key];
}
break;
}
}
}
this->_set_highlighter(sh_class);
}
void CodeEditor::_set_highlighter(const QString& sh_class)
{
this->highlighter_class = sh_class;
if (this->highlighter) {
this->highlighter->setParent(nullptr);
this->highlighter->setDocument(nullptr);
}
if (highlighter_class == "PythonSH") {
highlighter = new sh::PythonSH(this->document(),
this->font(),
this->color_scheme);
}
else if (highlighter_class == "CppSH")
highlighter = new sh::CppSH(this->document(),
this->font(),
this->color_scheme);
else if (highlighter_class == "MarkdownSH")
highlighter = new sh::MarkdownSH(this->document(),
this->font(),
this->color_scheme);
else if (highlighter_class == "TextSH")
highlighter = new sh::TextSH(this->document(),
this->font(),
this->color_scheme);
this->_apply_highlighter_color_scheme();
}
bool CodeEditor::is_json()
{
//需要pygments第三方库
return false;
}
bool CodeEditor::is_python()
{
return this->highlighter_class == "PythonSH";
}
bool CodeEditor::is_cpp()
{
return this->highlighter_class == "CppSH";
}
bool CodeEditor::is_cython()
{
return this->highlighter_class == "CythonSH";
}
bool CodeEditor::is_enmal()
{
return this->highlighter_class == "EnamlSH";
}
bool CodeEditor::is_python_like()
{
return this->is_python() || this->is_cython() || this->is_enmal();
}
void CodeEditor::intelligent_tab()
{
QString leading_text = this->get_text("sol","cursor");
if (leading_text.trimmed().isEmpty() || leading_text.endsWith('#'))
this->indent_or_replace();
else if (this->in_comment_or_string() && !leading_text.endsWith(" "))
this->do_completion();
else if (leading_text.endsWith("import ") || leading_text.back()=='.')
this->do_completion();
else if ((leading_text.split(QRegularExpression("\\s+"))[0]=="from" ||
leading_text.split(QRegularExpression("\\s+"))[0]=="import") &&
!leading_text.contains(';'))
this->do_completion();
else if (leading_text.back()=='(' || leading_text.back()==',' || leading_text.endsWith(", "))
this->indent_or_replace();
else if (leading_text.endsWith(' '))
this->indent_or_replace();
// \W匹配非数字字母下划线;\Z匹配字符串结束,如果是存在换行,只匹配到换行前的结束字符串
else if (leading_text.indexOf(QRegularExpression("[^\\d\\W]\\w*\\Z",
QRegularExpression::UseUnicodePropertiesOption)) > -1)
this->do_completion();
else
this->indent_or_replace();
}
void CodeEditor::intelligent_backtab()
{
QString leading_text = this->get_text("sol","cursor");
if (leading_text.trimmed().isEmpty())
this->unindent();
else if (this->in_comment_or_string())
this->unindent();
else if (leading_text.back()=='(' || leading_text.back()==',' || leading_text.endsWith(", ")) {
int position = this->get_position("cursor");
this->show_object_info(position);
}
else
this->unindent();
}
//******************************
void CodeEditor::rehighlight()
{
if (this->highlighter)
this->highlighter->rehighlight();
if (this->highlight_current_cell_enabled)
this->highlight_current_cell();
else
this->unhighlight_current_cell();
if (this->highlight_current_line_enabled)
this->highlight_current_line();
else
this->unhighlight_current_line();
}
void CodeEditor::rehighlight_cells()
{
if (this->highlight_current_cell_enabled)
this->highlight_current_cell();
}
void CodeEditor::setup_margins(bool linenumbers, bool markers)
{
this->linenumbers_margin = linenumbers;
this->markers_margin = markers;
this->set_linenumberarea_enabled(linenumbers || markers);
}
void CodeEditor::remove_trailing_spaces()
{
// 删除尾随空格
QTextCursor cursor = this->textCursor();
cursor.beginEditBlock();
cursor.movePosition(QTextCursor::Start);
while (true) {
cursor.movePosition(QTextCursor::EndOfBlock);
QString text = cursor.block().text();
int length = text.size() - rstrip(text).size();
if (length > 0) {
cursor.movePosition(QTextCursor::Left,QTextCursor::KeepAnchor,
length);
cursor.removeSelectedText();
}
if (cursor.atEnd())
break;
cursor.movePosition(QTextCursor::NextBlock);
}
cursor.endEditBlock();
}
void CodeEditor::fix_indentation()
{
QString text_before = this->toPlainText();
QString text_after = sourcecode::fix_indentation(text_before);
if (text_before != text_after) {
this->setPlainText(text_before);
this->document()->setModified(true);
}
}
QString CodeEditor::get_current_object()
{
QString source_code = this->toPlainText();
int offset = this->get_position("cursor");
return sourcecode::get_primary_at(source_code, offset);
}
//@Slot()
void CodeEditor::_delete()
{
if (!this->has_selected_text()) {
QTextCursor cursor = this->textCursor();
int position = cursor.position();
if (!cursor.atEnd())
cursor.setPosition(position+1, QTextCursor::KeepAnchor);
this->setTextCursor(cursor); // 这里调用了setTextCursor更新可见光标
}
this->remove_selected_text();
}
//------Find occurrences
QTextCursor CodeEditor::__find_first(const QString &text)
{
QTextDocument::FindFlags flags = QTextDocument::FindCaseSensitively | QTextDocument::FindWholeWords;
QTextCursor cursor = this->textCursor();
cursor.movePosition(QTextCursor::Start);
QRegExp regexp(QString("\\b%1\\b").arg(QRegExp::escape(text)), Qt::CaseSensitive);
cursor = this->document()->find(regexp, cursor, flags);
this->__find_first_pos = cursor.position();
return cursor;
}
QTextCursor CodeEditor::__find_next(const QString &text, QTextCursor cursor)
{
QTextDocument::FindFlags flags = QTextDocument::FindCaseSensitively | QTextDocument::FindWholeWords;
QRegExp regexp(QString("\\b%1\\b").arg(QRegExp::escape(text)), Qt::CaseSensitive);
cursor = this->document()->find(regexp, cursor, flags);
if (cursor.position() != this->__find_first_pos)
return cursor;
return QTextCursor();
}
void CodeEditor::__cursor_position_changed()
{
auto pair = this->get_cursor_line_column();
int line = pair.first, column=pair.second;
emit sig_cursor_position_changed(line,column);
if (this->highlight_current_cell_enabled)
this->highlight_current_cell();
else
this->unhighlight_current_cell();
if (this->highlight_current_line_enabled)
this->highlight_current_line();
else
this->unhighlight_current_line();
if (this->occurrence_highlighting) {
this->occurrence_timer->stop();
this->occurrence_timer->start();
}
}
void CodeEditor::__clear_occurrences()
{
occurrences.clear();
clear_extra_selections("occurrences");
scrollflagarea->update();
}
void CodeEditor::__highlight_selection(const QString &key, const QTextCursor &cursor, const QColor &foreground_color,
const QColor &background_color, const QColor &underline_color,
QTextCharFormat::UnderlineStyle underline_style,
bool update)
{
QList<QTextEdit::ExtraSelection> extra_selections = get_extra_selections(key);
QTextEdit::ExtraSelection selection;
if (foreground_color.isValid())
selection.format.setForeground(foreground_color);
if (background_color.isValid())
selection.format.setBackground(background_color);
if (underline_color.isValid()) {
selection.format.setProperty(QTextFormat::TextUnderlineStyle,
underline_style);
selection.format.setProperty(QTextFormat::TextUnderlineColor,
underline_color);
}
selection.format.setProperty(QTextFormat::FullWidthSelection,
true);
selection.cursor = cursor;
extra_selections.append(selection);
set_extra_selections(key,extra_selections);
if (update)
update_extra_selections();
}
//@Slot()
void CodeEditor::__mark_occurrences()
{
__clear_occurrences();
if (!supported_language)
return;
QString text = get_current_word();
if (text.isEmpty())
return;
if (has_selected_text() && get_selected_text()!=text)
return;
if (is_python_like() &&
(sourcecode::is_keyword(text) ||
text == "self"))
return;
QTextCursor cursor = this->__find_first(text);
occurrences.clear();
while (!cursor.isNull()) {
occurrences.append(cursor.blockNumber());
__highlight_selection("occurrences",cursor,
QColor(),occurrence_color);
cursor = __find_next(text, cursor);
}
update_extra_selections();
if (occurrences.size() > 1 && occurrences.last()==0)
occurrences.pop_back();
scrollflagarea->update();
}
//-----highlight found results (find/replace widget)
void CodeEditor::highlight_found_results(QString pattern, bool words, bool regexp)
{
if (pattern.isEmpty())
return;
if (!regexp)
pattern = QRegularExpression::escape(pattern);
pattern = words ? QString("\\b%1\\b").arg(pattern) : pattern;
QString text = this->toPlainText();
QRegularExpression regobj(pattern);
if (!regobj.isValid())
return;
QList<QTextEdit::ExtraSelection> extra_selections;
found_results.clear();
QRegularExpressionMatchIterator iterator = regobj.globalMatch(text);
while (iterator.hasNext()) {
QRegularExpressionMatch match = iterator.next();
int pos1 = match.capturedStart();
int pos2 = match.capturedEnd();
QTextEdit::ExtraSelection selection;
selection.format.setBackground(found_results_color);
selection.cursor = this->textCursor();
selection.cursor.setPosition(pos1);
found_results.append(selection.cursor.blockNumber());
selection.cursor.setPosition(pos2,QTextCursor::KeepAnchor);
extra_selections.append(selection);
}
set_extra_selections("find", extra_selections);
update_extra_selections();
}
void CodeEditor::clear_found_results()
{
found_results.clear();
clear_extra_selections("find");
scrollflagarea->update();
}
void CodeEditor::__text_has_changed()
{
if (!found_results.isEmpty())
clear_found_results();
}
//-----markers
int CodeEditor::get_markers_margin()
{
if (markers_margin)
return markers_margin_width;
else
return 0;
}
//-----linenumberarea
void CodeEditor::set_linenumberarea_enabled(bool state)
{
linenumberarea_enabled = state;
linenumberarea->setVisible(state);
update_linenumberarea_width();
}
int CodeEditor::get_linenumberarea_width()
{
return linenumberarea->contentsRect().width();
}
int CodeEditor::compute_linenumberarea_width()
{
if (!linenumberarea_enabled)
return 0;
int digits = 1;
int maxb = qMax(1, blockCount());
while (maxb >= 10) {
maxb /= 10;
digits++;
}
int linenumbers_margin;
if (this->linenumbers_margin)
linenumbers_margin = 3+this->fontMetrics().width(QString(digits,'9'));
else
linenumbers_margin = 0;
return linenumbers_margin + this->get_markers_margin();
}
void CodeEditor::update_linenumberarea_width(int new_block_count)
{
Q_UNUSED(new_block_count);
this->setViewportMargins(this->compute_linenumberarea_width(),0,
this->get_scrollflagarea_width(),0);
}
void CodeEditor::update_linenumberarea(const QRect &qrect, int dy)
{
if (dy)
this->linenumberarea->scroll(0, dy);
else
this->linenumberarea->update(0, qrect.y(),
linenumberarea->width(),
qrect.height());
if (qrect.contains(this->viewport()->rect()))
this->update_linenumberarea_width();
}
void CodeEditor::linenumberarea_paint_event(QPaintEvent *event)
{
QPainter painter(this->linenumberarea);
painter.fillRect(event->rect(), this->sideareas_color);
QFont font = this->font();
int font_height = this->fontMetrics().height();
QTextBlock active_block = this->textCursor().block();
int active_line_number = active_block.blockNumber()+1;
auto draw_pixmap = [&](int ytop, const QPixmap &pixmap)
{
int pixmap_height;
#if QT_VERSION < QT_VERSION_CHECK(5, 5, 0)
pixmap_height = pixmap.height();
#else
pixmap_height = static_cast<int>(pixmap.height() / pixmap.devicePixelRatio());
#endif
painter.drawPixmap(0, ytop + (font_height-pixmap_height) / 2, pixmap);
};
foreach (auto pair, this->__visible_blocks) {
int top = pair.top;
int line_number = pair.line_number;
QTextBlock block = pair.block;
if (this->linenumbers_margin) {
if (line_number == active_line_number) {
font.setWeight(font.Bold);
painter.setFont(font);
painter.setPen(this->normal_color);
}
else {
font.setWeight(font.Normal);
painter.setFont(font);
painter.setPen(this->linenumbers_color);
}
painter.drawText(0, top, linenumberarea->width(),
font_height,
Qt::AlignRight | Qt::AlignBottom,
QString::number(line_number));
}
BlockUserData* data = dynamic_cast<BlockUserData*>(block.userData());
if (this->markers_margin && data) {
if (!data->code_analysis.isEmpty()) {
bool error = false;
foreach (auto pair, data->code_analysis) {
error = pair.second;
if (error)
break;
}
if (error)
draw_pixmap(top,error_pixmap);
else
draw_pixmap(top,warning_pixmap);
}
if (!data->todo.isEmpty())
draw_pixmap(top,todo_pixmap);
if (data->breakpoint) {
if (data->breakpoint_condition.isEmpty())
draw_pixmap(top,this->bp_pixmap);
else
draw_pixmap(top,this->bpc_pixmap);
}
}
}
}
int CodeEditor::__get_linenumber_from_mouse_event(QMouseEvent *event)
{
QTextBlock block = firstVisibleBlock();
int line_number = block.blockNumber();
double top = blockBoundingGeometry(block).
translated(this->contentOffset()).top();
double bottom = top + blockBoundingRect(block).height();
while (block.isValid() && top < event->pos().y()) {
block = block.next();
top = bottom;
bottom = top + blockBoundingRect(block).height();
line_number++;
}
return line_number;
}
void CodeEditor::linenumberarea_mousemove_event(QMouseEvent *event)
{
int line_number = __get_linenumber_from_mouse_event(event);
QTextBlock block = document()->findBlockByNumber(line_number-1);
BlockUserData* data = dynamic_cast<BlockUserData*>(block.userData());
bool check = this->linenumberarea_released == -1;
if (data && !data->code_analysis.isEmpty() && check)
this->__show_code_analysis_results(line_number,data->code_analysis);
if (event->buttons() == Qt::LeftButton) {
this->linenumberarea_released = line_number;
this->linenumberarea_select_lines(this->linenumberarea_pressed,
this->linenumberarea_released);
}
}
void CodeEditor::linenumberarea_mousedoubleclick_event(QMouseEvent *event)
{
int line_number = this->__get_linenumber_from_mouse_event(event);
bool shift = event->modifiers() & Qt::ShiftModifier;
this->add_remove_breakpoint(line_number,QString(),shift);
}
void CodeEditor::linenumberarea_mousepress_event(QMouseEvent *event)
{
int line_number = this->__get_linenumber_from_mouse_event(event);
this->linenumberarea_pressed = line_number;
this->linenumberarea_released = line_number;
this->linenumberarea_select_lines(this->linenumberarea_pressed,
this->linenumberarea_released);
}
void CodeEditor::linenumberarea_mouserelease_event(QMouseEvent *event)
{
Q_UNUSED(event);
this->linenumberarea_pressed = -1;
this->linenumberarea_released = -1;
}
void CodeEditor::linenumberarea_select_lines(int linenumber_pressed, int linenumber_released)
{
int move_n_blocks = linenumber_released - linenumber_pressed;
int start_line = linenumber_pressed;
QTextBlock start_block = this->document()->findBlockByLineNumber(start_line-1);
QTextCursor cursor = this->textCursor();
cursor.setPosition(start_block.position());
if (move_n_blocks > 0) {
for (int n = 0; n < qAbs(move_n_blocks)+1; ++n)
cursor.movePosition(cursor.NextBlock, cursor.KeepAnchor);
}
else {
cursor.movePosition(cursor.NextBlock);
for (int n = 0; n < qAbs(move_n_blocks)+1; ++n)
cursor.movePosition(cursor.PreviousBlock, cursor.KeepAnchor);
}
if (linenumber_released == this->blockCount())
cursor.movePosition(cursor.EndOfBlock,cursor.KeepAnchor);
else
cursor.movePosition(cursor.StartOfBlock,cursor.KeepAnchor);
this->setTextCursor(cursor);
}
//------Breakpoints
void CodeEditor::add_remove_breakpoint(int line_number, QString condition, bool edit_condition)
{
if (!this->is_python_like())
return;
QTextBlock block;
if (line_number == -1)
block = this->textCursor().block();
else
block = this->document()->findBlockByNumber(line_number-1);
BlockUserData* data = dynamic_cast<BlockUserData*>(block.userData());
if (data == nullptr) {
data = new BlockUserData(this);
data->breakpoint = true;
}
else if (!edit_condition) {
data->breakpoint = !data->breakpoint;
data->breakpoint_condition = QString();
}
if (!condition.isEmpty()) {
data->breakpoint_condition = condition;
}
if (edit_condition) {
condition = data->breakpoint_condition;
bool valid;
condition = QInputDialog::getText(this,
"Breakpoint",
"Condition",
QLineEdit::Normal,condition,&valid);
if (valid == false)
return;
data->breakpoint = true;
data->breakpoint_condition = (!condition.isEmpty()) ? condition : QString();
}
if (data->breakpoint) {
QString text = block.text().trimmed();
// 下一行设置注释以及双引号,单引号不能设置断点
if (text.size()==0 || startswith(text,QStringList({"#","\"","'"})))
data->breakpoint = false;
}
block.setUserData(data); // 在这里往QTextBlock上设置BlockUserData类型的数据
this->linenumberarea->update();
this->scrollflagarea->update();
emit this->breakpoints_changed();
}
QList<QList<QVariant> > CodeEditor::get_breakpoints()
{
QList<QList<QVariant>> breakpoints;
QTextBlock block = this->document()->firstBlock();
for (int line_number = 1; line_number < this->document()->blockCount()+1; ++line_number) {
BlockUserData* data = dynamic_cast<BlockUserData*>(block.userData());
if (data && data->breakpoint) {
QList<QVariant> tmp;
tmp.append(line_number);
tmp.append(data->breakpoint_condition);
breakpoints.append(tmp);
}
block = block.next();
}
return breakpoints;
}
void CodeEditor::clear_breakpoints()
{
breakpoints.clear();
QList<BlockUserData*> tmp = this->blockuserdata_list;
foreach (BlockUserData* data, tmp) {
data->breakpoint = false;
if (data->is_empty())
data->del();
}
/*for (int i = 0; i < blockuserdata_list.size(); ++i) {
blockuserdata_list[i]->breakpoint = false;
if (blockuserdata_list[i]->is_empty()) {
delete blockuserdata_list[i];
blockuserdata_list[i] = nullptr;
}
}
blockuserdata_list.removeAll(nullptr);*/
}
void CodeEditor::set_breakpoints(const QList<QVariant> &breakpoints)
{
this->clear_breakpoints();
foreach (auto breakpoint, breakpoints) {
QList<QVariant> pair = breakpoint.toList();
int line_number = pair[0].toInt();
QString condition = pair[1].toString();
this->add_remove_breakpoint(line_number, condition);
}
}
void CodeEditor::update_breakpoints()
{
emit this->breakpoints_changed();
}
//-----Code introspection
void CodeEditor::do_completion(bool automatic)
{
if (!this->is_completion_widget_visible())
emit this->get_completions(automatic);
}
void CodeEditor::do_go_to_definition()
{
if (!this->in_comment_or_string())
emit go_to_definition(this->textCursor().position());
}
void CodeEditor::show_object_info(int position)
{
emit this->sig_show_object_info(position);
}
//-----edge line
void CodeEditor::set_edge_line_enabled(bool state)
{
this->edge_line_enabled = state;
this->edge_line->setVisible(state);
}
void CodeEditor::set_edge_line_column(int column)
{
this->edge_line->column = column;
this->edge_line->update();
}
//-----blank spaces
void CodeEditor::set_blanks_enabled(bool state)
{
this->blanks_enabled = state;
QTextOption option = this->document()->defaultTextOption();
option.setFlags(option.flags() | QTextOption::AddSpaceForLineAndParagraphSeparators);
if (this->blanks_enabled)
option.setFlags(option.flags() | QTextOption::ShowTabsAndSpaces);
else
option.setFlags(option.flags() & ~QTextOption::ShowTabsAndSpaces);
this->document()->setDefaultTextOption(option);
this->rehighlight();
}
//-----scrollflagarea
void CodeEditor::set_scrollflagarea_enabled(bool state)
{
this->scrollflagarea_enabled = state;
this->scrollflagarea->setVisible(state);
this->update_linenumberarea_width();
}
int CodeEditor::get_scrollflagarea_width()
{
if (this->scrollflagarea_enabled)
return ScrollFlagArea::WIDTH;
else
return 0;
}
void CodeEditor::scrollflagarea_paint_event(QPaintEvent *event)
{
QPainter painter(this->scrollflagarea);
painter.fillRect(event->rect(), this->sideareas_color);
QTextBlock block = this->document()->firstBlock();
for (int line_number = 1; line_number < document()->blockCount()+1; ++line_number) {
BlockUserData* data = dynamic_cast<BlockUserData*>(block.userData());
if (data) {
int position = static_cast<int>(this->scrollflagarea->value_to_position(line_number));
if (!data->code_analysis.isEmpty()) {
QString color = this->warning_color;
foreach (auto pair, data->code_analysis) {
bool error = pair.second;
if (error) {
color = this->error_color;
break;
}
}
set_scrollflagarea_painter(&painter,color);
painter.drawRect(scrollflagarea->make_flag_qrect(position));
}
if (!data->todo.isEmpty()) {
set_scrollflagarea_painter(&painter, this->todo_color);
painter.drawRect(scrollflagarea->make_flag_qrect(position));
}
if (data->breakpoint) {
set_scrollflagarea_painter(&painter,this->breakpoint_color);
painter.drawRect(scrollflagarea->make_flag_qrect(position));
}
}
block = block.next();
}
if (!this->occurrences.isEmpty()) {
set_scrollflagarea_painter(&painter, this->occurrence_color);
foreach (int line_number, this->occurrences) {
int position = static_cast<int>(this->scrollflagarea->value_to_position(line_number));
painter.drawRect(scrollflagarea->make_flag_qrect(position));
}
}
if (!this->found_results.isEmpty()) {
set_scrollflagarea_painter(&painter,this->found_results_color);
foreach (int line_number, this->found_results) {
int position = static_cast<int>(this->scrollflagarea->value_to_position(line_number));
painter.drawRect(scrollflagarea->make_flag_qrect(position));
}
}
QColor pen_color = QColor(Qt::white);
pen_color.setAlphaF(0.8);
painter.setPen(pen_color);
QColor brush_color = QColor(Qt::white);
brush_color.setAlphaF(0.5);
painter.setBrush(QBrush(brush_color));
painter.drawRect(scrollflagarea->make_slider_range(firstVisibleBlock().blockNumber()));
}
void CodeEditor::resizeEvent(QResizeEvent *event)
{
TextEditBaseWidget::resizeEvent(event);
QRect cr = this->contentsRect();
this->linenumberarea->setGeometry(QRect(cr.left(),cr.top(),
compute_linenumberarea_width(),
cr.height()));
this->__set_scrollflagarea_geometry(cr);
}
void CodeEditor::__set_scrollflagarea_geometry(const QRect &contentrect)
{
QRect cr = contentrect;
int vsbw;
if (this->verticalScrollBar()->isVisible())
vsbw = this->verticalScrollBar()->contentsRect().width();
else
vsbw = 0;
int _left, _top, right, _bottom;
this->getContentsMargins(&_left, &_top, &right, &_bottom);
if (right > vsbw)
vsbw = 0;
this->scrollflagarea->setGeometry(QRect(cr.right()-ScrollFlagArea::WIDTH-vsbw,
cr.top(),
this->scrollflagarea->WIDTH,cr.height()));
}
//-----edgeline
bool CodeEditor::viewportEvent(QEvent *event)
{
QPointF offset = this->contentOffset();
double x = this->blockBoundingGeometry(this->firstVisibleBlock())
.translated(offset.x(), offset.y()).left() \
+this->get_linenumberarea_width() \
+this->fontMetrics().width(QString(this->edge_line->column, '9'))+5;
QRect cr = this->contentsRect();
this->edge_line->setGeometry(QRect(static_cast<int>(x), cr.top(), 1, cr.bottom()));
this->__set_scrollflagarea_geometry(cr);
return TextEditBaseWidget::viewportEvent(event);
}
void CodeEditor::_apply_highlighter_color_scheme()
{
sh::BaseSH* hl = highlighter;
if (hl) {
this->set_palette(hl->get_background_color(),
hl->get_foreground_color());
currentline_color = hl->get_currentline_color();
currentcell_color = hl->get_currentcell_color();
occurrence_color = hl->get_occurrence_color();
ctrl_click_color = hl->get_ctrlclick_color();
sideareas_color = hl->get_sideareas_color();
comment_color = hl->get_comment_color();
normal_color = hl->get_foreground_color();
matched_p_color = hl->get_matched_p_color();
unmatched_p_color = hl->get_unmatched_p_color();
}
}
void CodeEditor::apply_highlighter_settings(const QHash<QString, ColorBoolBool> &color_scheme)
{
if (this->highlighter) {
this->highlighter->setup_formats(this->font());
if (!color_scheme.isEmpty())
this->set_color_scheme(color_scheme);
else
this->highlighter->rehighlight();
}
}
QHash<int,sh::OutlineExplorerData> CodeEditor::get_outlineexplorer_data()
{
return highlighter->get_outlineexplorer_data();
}
void CodeEditor::set_font(const QFont &font, const QHash<QString,ColorBoolBool> &color_scheme)
{
if (!color_scheme.isEmpty())
this->color_scheme = color_scheme;
this->setFont(font);
this->update_linenumberarea_width();
this->apply_highlighter_settings(color_scheme);
}
void CodeEditor::set_color_scheme(const QHash<QString,ColorBoolBool> &color_scheme)
{
this->color_scheme = color_scheme;
if (this->highlighter) {
this->highlighter->set_color_scheme(color_scheme);
this->_apply_highlighter_color_scheme();
}
if (this->highlight_current_cell_enabled)
this->highlight_current_cell();
else
this->unhighlight_current_cell();
if (this->highlight_current_line_enabled)
this->highlight_current_line();
else
this->unhighlight_current_line();
}
void CodeEditor::set_text(const QString &text)
{
this->setPlainText(text);
//禁用下面这行,不然会导致调用下面的函数,使未发生改变的文档状态变为isModified,文件名后出现星号
//this->set_eol_chars(text);
}
void CodeEditor::set_text_from_file(const QString &filename, QString language)
{
QString text = encoding::read(filename);
if (language.isEmpty()) {
language = get_file_language(filename, text);
}
this->set_language(language, filename);
this->set_text(text);
}
void CodeEditor::append(const QString &text)
{
QTextCursor cursor = this->textCursor();
cursor.movePosition(QTextCursor::End);
cursor.insertText(text);
}
//@Slot()
void CodeEditor::paste()
{
QClipboard* clipboard = QApplication::clipboard();
QString text = clipboard->text();
if (splitlines(text).size() > 1) {
QString eol_chars = this->get_line_separator();
clipboard->setText((splitlines(text+eol_chars)).join(eol_chars));
}
TextEditBaseWidget::paste();
}
void CodeEditor::get_block_data(const QTextBlock &block)
{
// TODO highlighter.block_data是什么
}
void CodeEditor::get_fold_level(int block_nb)
{
QTextBlock block = this->document()->findBlockByNumber(block_nb);
//QTextBlockUserData* data = block.userData();
// TODO
}
//==============High-level editor features
//@Slot()
void CodeEditor::center_cursor_on_next_focus()
{
this->centerCursor();
disconnect(this,SIGNAL(focus_in()),this,SLOT(center_cursor_on_next_focus()));
}
void CodeEditor::go_to_line(int line, const QString &word)
{
line = qMin(line, this->get_line_count());
QTextBlock block = this->document()->findBlockByNumber(line-1);
this->setTextCursor(QTextCursor(block));
if (this->isVisible())
this->centerCursor();
else
connect(this,SIGNAL(focus_in()),this,SLOT(center_cursor_on_next_focus()));
this->horizontalScrollBar()->setValue(0);
if (!word.isEmpty() && block.text().contains(word))
this->find(word, QTextDocument::FindCaseSensitively);
}
void CodeEditor::exec_gotolinedialog()
{
GoToLineDialog* dlg = new GoToLineDialog(this);
if (dlg->exec())
this->go_to_line(dlg->get_line_number());
}
void CodeEditor::cleanup_code_analysis()
{
setUpdatesEnabled(false);
clear_extra_selections("code_analysis");
QList<BlockUserData*> tmp = this->blockuserdata_list;
foreach (BlockUserData* data, tmp) {
data->code_analysis.clear();
if (data->is_empty())
data->del();
}
this->setUpdatesEnabled(true);
scrollflagarea->update();
linenumberarea->update();
}
void CodeEditor::process_code_analysis(const QList<QList<QVariant> > &check_results)
{
cleanup_code_analysis();
if (check_results.isEmpty())
return;
setUpdatesEnabled(false);
QTextCursor cursor = textCursor();
QTextDocument* document = this->document();
QTextDocument::FindFlags flags = QTextDocument::FindCaseSensitively | QTextDocument::FindWholeWords;
foreach (auto pair, check_results) {
QString message = pair[0].toString();
int line_number = pair[1].toInt();
bool error = message.contains("syntax");
QTextBlock block = this->document()->findBlockByNumber(line_number-1);
BlockUserData* data = dynamic_cast<BlockUserData*>(block.userData());
if (data == nullptr)
data = new BlockUserData(this);
data->code_analysis.append(qMakePair(message, error));
block.setUserData(data);
QRegularExpression re("\\'[a-zA-Z0-9_]*\\'");
QRegularExpressionMatchIterator iterator = re.globalMatch(message);
while (iterator.hasNext()) {
QRegularExpressionMatch match = iterator.next();
QString text = match.captured().chopped(1);
text = text.mid(1);
auto is_line_splitted = [=](int line_no)
{
QString text = document->findBlockByNumber(line_no).text();
QString stripped = text.trimmed();
return stripped.endsWith("\\") || stripped.endsWith(',')
|| stripped.size() == 0;
};
int line2 = line_number-1;
while (line2<this->blockCount()-1 && is_line_splitted(line2))
line2++;
cursor.setPosition(block.position());
cursor.movePosition(QTextCursor::StartOfBlock);
QRegExp regexp(QString("\\b%1\\b").arg(QRegExp::escape(text)),
Qt::CaseSensitive);
QString color = error ? this->error_color : this->warning_color;
cursor = document->find(regexp, cursor, flags);
if (!cursor.isNull()) {
while (!cursor.isNull() && cursor.blockNumber() <= line2
&& cursor.blockNumber() >= line_number-1
&& cursor.position() > 0) {
this->__highlight_selection("code_analysis",cursor,QColor(),
QColor(),QColor(color));
cursor = document->find(text, cursor, flags);
}
}
}
}
update_extra_selections();
setUpdatesEnabled(true);
linenumberarea->update();
}
void CodeEditor::__show_code_analysis_results(int line_number, const QList<QPair<QString, bool> > &code_analysis)
{
QStringList msglist;
foreach (auto pair, code_analysis) {
msglist.append(pair.first);
}
this->show_calltip("Code analysis",msglist,
false,"#129625",line_number);
// 这里调用了show_calltip(text = QtringList)
// show_calltip本代码总共两处调用,这里第一次
}
int CodeEditor::go_to_next_warning()
{
QTextBlock block = this->textCursor().block();
int line_count = this->document()->blockCount();
BlockUserData* data;
while (true) {
if (block.blockNumber()+1 < line_count)
block = block.next();
else
block = this->document()->firstBlock();
data = dynamic_cast<BlockUserData*>(block.userData());
if (data && !data->code_analysis.isEmpty())
break;
}
int line_number = block.blockNumber()+1;
this->go_to_line(line_number);
this->__show_code_analysis_results(line_number, data->code_analysis);
return this->get_position("cursor");
}
int CodeEditor::go_to_previous_warning()
{
QTextBlock block = this->textCursor().block();
BlockUserData* data;
while (true) {
if (block.blockNumber() > 0)
block = block.previous();
else
block = this->document()->lastBlock();
data = dynamic_cast<BlockUserData*>(block.userData());
if (data && !data->code_analysis.isEmpty())
break;
}
int line_number = block.blockNumber()+1;
this->go_to_line(line_number);
this->__show_code_analysis_results(line_number, data->code_analysis);
return this->get_position("cursor");
}
//------Tasks management
int CodeEditor::go_to_next_todo()
{
QTextBlock block = this->textCursor().block();
int line_count = this->document()->blockCount();
BlockUserData* data;
while (true) {
if (block.blockNumber()+1 < line_count)
block = block.next();
else
block = this->document()->firstBlock();
data = dynamic_cast<BlockUserData*>(block.userData());
if (data && !data->todo.isEmpty())
break;
}
int line_number = block.blockNumber()+1;
this->go_to_line(line_number);
this->show_calltip("To do",data->todo,
false,"#3096FC",line_number);
// 这里调用了show_calltip(text = Qtring)
// show_calltip本代码总共两处调用,这里第二次
return this->get_position("cursor");
}
void CodeEditor::process_todo(const QList<QList<QVariant> > &todo_results)
{
QList<BlockUserData*> tmp = this->blockuserdata_list;
foreach (BlockUserData* data, tmp) {
data->todo = "";
if (data->is_empty())
data->del();
}
foreach (auto pair, todo_results) {
QString message = pair[0].toString();
int line_number = pair[1].toInt();
QTextBlock block = this->document()->findBlockByNumber(line_number-1);
BlockUserData* data = dynamic_cast<BlockUserData*>(block.userData());
if (data == nullptr)
data = new BlockUserData(this);
data->todo = message;
block.setUserData(data);
}
this->scrollflagarea->update();
}
//------Comments/Indentation
void CodeEditor::add_prefix(const QString& prefix)
{
QTextCursor cursor = this->textCursor();
if (this->has_selected_text()) {
int start_pos=cursor.selectionStart(), end_pos=cursor.selectionEnd();
int first_pos = qMin(start_pos, end_pos);
QTextCursor first_cursor = this->textCursor();
first_cursor.setPosition(first_pos);
bool begins_at_block_start = first_cursor.atBlockStart();
cursor.beginEditBlock();
cursor.setPosition(end_pos);
if (cursor.atBlockStart()) {
cursor.movePosition(QTextCursor::PreviousBlock);
if (cursor.position() <start_pos)
cursor.setPosition(start_pos);
}
while (cursor.position() >= start_pos) {
cursor.movePosition(QTextCursor::StartOfBlock);
cursor.insertText(prefix);
if (start_pos==0 && cursor.blockNumber()==0)
break;
cursor.movePosition(QTextCursor::PreviousBlock);
cursor.movePosition(QTextCursor::EndOfBlock);
}
cursor.endEditBlock();
if (begins_at_block_start) {
cursor = this->textCursor();
start_pos = cursor.selectionStart();
end_pos = cursor.selectionEnd();
if (start_pos < end_pos)
start_pos -= prefix.size();
else
end_pos -= prefix.size();
cursor.setPosition(start_pos, QTextCursor::MoveAnchor);
cursor.setPosition(end_pos, QTextCursor::KeepAnchor);
this->setTextCursor(cursor);
}
}
else {
cursor.beginEditBlock();
cursor.movePosition(QTextCursor::StartOfBlock);
cursor.insertText(prefix);
cursor.endEditBlock();
}
}
void CodeEditor::__is_cursor_at_start_of_block(QTextCursor *cursor)
{
cursor->movePosition(QTextCursor::StartOfBlock);
}
void CodeEditor::remove_suffix(const QString &suffix)
{
QTextCursor cursor = this->textCursor();
cursor.setPosition(cursor.position()-suffix.size(),
QTextCursor::KeepAnchor);
if (cursor.selectedText() == suffix)
cursor.removeSelectedText();
}
void CodeEditor::remove_prefix(const QString &prefix)
{
QTextCursor cursor = this->textCursor();
if (this->has_selected_text()) {
int start_pos = qMin(cursor.selectionStart(), cursor.selectionEnd());
int end_pos = qMax(cursor.selectionStart(), cursor.selectionEnd());
cursor.setPosition(start_pos);
if (!cursor.atBlockStart()) {
cursor.movePosition(QTextCursor::StartOfBlock);
start_pos = cursor.position();
}
cursor.beginEditBlock();
cursor.setPosition(end_pos);
if (cursor.atBlockStart()) {
cursor.movePosition(QTextCursor::PreviousBlock);
if (cursor.position() <start_pos)
cursor.setPosition(start_pos);
}
cursor.movePosition(QTextCursor::StartOfBlock);
int old_pos = INT_MIN;
while (cursor.position() >= start_pos) {
int new_pos = cursor.position();
if (old_pos == new_pos)
break;
else
old_pos = new_pos;
QString line_text = cursor.block().text();
if ((!prefix.trimmed().isEmpty() && lstrip(line_text).startsWith(prefix))
|| line_text.startsWith(prefix)) {
cursor.movePosition(QTextCursor::Right,
QTextCursor::MoveAnchor,
line_text.indexOf(prefix));
cursor.movePosition(QTextCursor::Right,
QTextCursor::KeepAnchor,prefix.size());
cursor.removeSelectedText();
}
cursor.movePosition(QTextCursor::PreviousBlock);
}
cursor.endEditBlock();
}
else {
cursor.movePosition(QTextCursor::StartOfBlock);
QString line_text = cursor.block().text();
if ((!prefix.trimmed().isEmpty() && lstrip(line_text).startsWith(prefix))
|| line_text.startsWith(prefix)) {
cursor.movePosition(QTextCursor::Right,
QTextCursor::MoveAnchor,
line_text.indexOf(prefix));
cursor.movePosition(QTextCursor::Right,
QTextCursor::KeepAnchor,prefix.size());
cursor.removeSelectedText();
}
}
}
bool CodeEditor::fix_indent(bool forward, bool comment_or_string)
{
if (this->is_python_like())
return this->fix_indent_smart(forward, comment_or_string);
else
return this->simple_indentation(forward, comment_or_string);
}
bool CodeEditor::simple_indentation(bool forward, bool comment_or_string)
{
Q_UNUSED(comment_or_string);
QTextCursor cursor = this->textCursor();
int block_nb = cursor.blockNumber();
QTextBlock prev_block = this->document()->findBlockByLineNumber(block_nb-1);
QString prevline = prev_block.text();
QRegularExpression re("\\s*");
QRegularExpressionMatch match = re.match(prevline);
QString indentation;
if (match.capturedStart() == 0)
indentation = match.captured();
if (!forward)
indentation = indentation.mid(this->indent_chars.size());
cursor.insertText(indentation);
return false;
}
bool CodeEditor::fix_indent_smart(bool forward, bool comment_or_string)
{
QTextCursor cursor = this->textCursor();
int block_nb = cursor.blockNumber();
int diff_paren = 0;
int diff_brack = 0;
int diff_curly = 0;
bool add_indent = false;
int prevline = 0;
QString prevtext = "";
for (prevline = block_nb-1; prevline >= 0; --prevline) {
cursor.movePosition(QTextCursor::PreviousBlock);
prevtext = rstrip(cursor.block().text());
int inline_comment = prevtext.indexOf('#');
if (inline_comment != -1)
prevtext = prevtext.left(inline_comment);
if ((this->is_python_like() &&
!prevtext.trimmed().startsWith('#') && !prevtext.isEmpty()) ||
!prevtext.isEmpty()) {
if (!prevtext.trimmed().split(QRegularExpression("\\s")).mid(0,1).contains("return") &&
(prevtext.trimmed().endsWith(')') ||
prevtext.trimmed().endsWith(']') ||
prevtext.trimmed().endsWith('}')))
comment_or_string = true;
else if (prevtext.trimmed().endsWith(':') && this->is_python_like()) {
add_indent = true;
comment_or_string = true;
}
if (prevtext.count(')') > prevtext.count('('))
diff_paren = prevtext.count(')') - prevtext.count('(');
else if (prevtext.count(']') > prevtext.count('['))
diff_brack = prevtext.count(']') - prevtext.count('[');
else if (prevtext.count('}') > prevtext.count('{'))
diff_curly = prevtext.count('}') - prevtext.count('{');
else if (diff_paren || diff_brack || diff_curly) {
diff_paren += prevtext.count(')') - prevtext.count('(');
diff_brack += prevtext.count(']') - prevtext.count('[');
diff_curly += prevtext.count('}') - prevtext.count('{');
if (!(diff_paren || diff_brack || diff_curly))
break;
}
else
break;
}
}
int correct_indent;
if (prevline)
correct_indent = this->get_block_indentation(prevline);
else
correct_indent = 0;
int indent = this->get_block_indentation(block_nb);
if (add_indent) {
if (this->indent_chars == "\t")
correct_indent += this->tab_stop_width_spaces;
else
correct_indent += this->indent_chars.size();
}
if (!comment_or_string) {
if (prevtext.endsWith(':') && this->is_python_like()) {
if (this->indent_chars == "\t")
correct_indent += this->tab_stop_width_spaces;
else
correct_indent += this->indent_chars.size();
}
else if(this->is_python_like() &&
(prevtext.endsWith("continue") ||
prevtext.endsWith("break") ||
prevtext.endsWith("pass") ||
(prevtext.trimmed().split(QRegularExpression("\\t")).mid(0,1).contains("return") &&
prevtext.split(QRegularExpression("\\(|\\{|\\[")).size() ==
prevtext.split(QRegularExpression("\\)|\\}|\\]")).size()))) {
if (this->indent_chars == "\t")
correct_indent -= this->tab_stop_width_spaces;
else
correct_indent -= this->indent_chars.size();
}
else if (prevtext.split(QRegularExpression("\\(|\\{|\\[")).size() > 1) {
// Dummy elemet to avoid index errors
QStringList stack = {"dummy"};
QChar deactivate = QChar(0);
foreach (QChar c, prevtext) {
if (deactivate != QChar(0)) {
if (c == deactivate)
deactivate = QChar(0);
}
else if (c=='\'' || c=='\"')
deactivate = c;
else if (c=='(' || c=='[' || c=='{')
stack.append(c);
else if (c==')' && stack.last()=="(")
stack.removeLast();
else if (c==']' && stack.last()=="[")
stack.removeLast();
else if (c=='}' && stack.last()=="{")
stack.removeLast();
}
if (stack.size() == 1) {
}
else if (prevtext.indexOf(QRegularExpression("[\\(|\\{|\\[]\\s*$"))>-1 &&
((this->indent_chars=="\t" &&
this->tab_stop_width_spaces*2 < prevtext.size()) ||
(this->indent_chars.startsWith(' ') &&
this->indent_chars.size()*2 < prevtext.size()))) {
if (this->indent_chars == "\t")
correct_indent += this->tab_stop_width_spaces * 2;
else
correct_indent += this->indent_chars.size() * 2;
}
else {
QHash<QChar,QChar> rlmap = {{')','('}, {']','['}, {'}','{'}};
bool break_flag = true;
for (auto it=rlmap.begin();it!=rlmap.end();it++) {
QChar par = it.key();
int i_right = prevtext.lastIndexOf(par);
if (i_right != -1) {
prevtext = prevtext.left(i_right);
for (int _i=0;_i<prevtext.split(par).size();_i++) {
int i_left = prevtext.lastIndexOf(rlmap[par]);
if (i_left != -1)
prevtext = prevtext.left(i_left);
else {
break_flag = false;
break;
}
}
}
}
if (break_flag) {
if (!prevtext.trimmed().isEmpty()) {
if (prevtext.split(QRegularExpression("\\(|\\{|\\[")).size() > 1) {
QString prevexpr = prevtext.split(QRegularExpression("\\(|\\{|\\[")).last();
correct_indent = prevtext.size()-prevexpr.size();
}
else
correct_indent = prevtext.size();
}
}
}
}
}
if (!(diff_paren || diff_brack || diff_curly) &&
!prevtext.endsWith(':') && prevline) {
int cur_indent = this->get_block_indentation(block_nb-1);
bool is_blank = this->get_text_line(block_nb-1).trimmed().isEmpty();
int prevline_indent = this->get_block_indentation(prevline);
QString trailing_text = this->get_text_line(block_nb).trimmed();
if (cur_indent < prevline_indent &&
(!trailing_text.isEmpty() || is_blank)) {
if (cur_indent % this->indent_chars.size() == 0)
correct_indent = cur_indent;
else
correct_indent = cur_indent + (this->indent_chars.size() - cur_indent % this->indent_chars.size());
}
}
if ((forward && indent >= correct_indent) ||
(!forward && indent <= correct_indent))
return false;
if (correct_indent >= 0) {
QTextCursor cursor = this->textCursor();
cursor.movePosition(QTextCursor::StartOfBlock);
if (this->indent_chars == "\t")
indent = indent / this->tab_stop_width_spaces;
cursor.setPosition(cursor.position()+indent,QTextCursor::KeepAnchor);
cursor.removeSelectedText();
QString indent_text;
if (this->indent_chars == "\t")
indent_text = QString(correct_indent / this->tab_stop_width_spaces,'\t')
+ QString(correct_indent % this->tab_stop_width_spaces,' ');
else
indent_text = QString(correct_indent,' ');
cursor.insertText(indent_text);
return true;
}
return false;
}
//@Slot()
void CodeEditor::clear_all_output()
{
try {
qDebug()<<"clear_all_output"<<__FILE__<<__LINE__;
// TODO该函数依赖于第三方库nbformat
} catch (const std::exception &e) {
QMessageBox::critical(this,"Removal error",
QString("It was not possible to remove outputs from this notebook. The error is:\n\n")+e.what());
return;
}
}
//@Slot()
void CodeEditor::convert_notebook()
{
try {
qDebug()<<"convert_notebook"<<__FILE__<<__LINE__;
// TODO该函数依赖于第三方库nbformat
} catch (const std::exception &e) {
QMessageBox::critical(this,"Conversion error",
QString("It was not possible to convert this notebook. The error is:\n\n")+e.what());
return;
}
//TODO emit sig_new_file();
}
void CodeEditor::indent(bool force)
{
QString leading_text = this->get_text("sol","cursor");
if (this->has_selected_text())
this->add_prefix(this->indent_chars);
else if (force || leading_text.trimmed().isEmpty()
|| (this->tab_indents && this->tab_mode)) {
if (this->is_python_like()) {
if (!this->fix_indent(true))
this->add_prefix(this->indent_chars);
}
else
this->add_prefix(this->indent_chars);
}
else {
if (this->indent_chars.size() > 1) {
int length = this->indent_chars.size();
this->insert_text(QString(length-(leading_text.size()%length),' '));
}
else
this->insert_text(this->indent_chars);
}
}
void CodeEditor::indent_or_replace()
{
if ((this->tab_indents && this->tab_mode) || !this->has_selected_text())
this->indent();
else {
QTextCursor cursor = this->textCursor();
if (this->get_selected_text() == cursor.block().text())
this->indent();
else {
QTextCursor cursor1 = this->textCursor();
cursor1.setPosition(cursor.selectionStart());
QTextCursor cursor2 = this->textCursor();
cursor2.setPosition(cursor.selectionEnd());
if (cursor1.blockNumber() != cursor2.blockNumber())
this->indent();
else
this->replace(this->indent_chars);
}
}
}
void CodeEditor::unindent(bool force)
{
if (this->has_selected_text())
this->remove_prefix(this->indent_chars);
else {
QString leading_text = this->get_text("sol","cursor");
if (force || leading_text.trimmed().isEmpty()
|| (this->tab_indents && this->tab_mode)) {
if (this->is_python_like()) {
if (!this->fix_indent(false))
this->remove_prefix(this->indent_chars);
}
else if (leading_text.endsWith("\t"))
this->remove_prefix("\t");
else
this->remove_prefix(this->indent_chars);
}
}
}
// @Slot()
void CodeEditor::toggle_comment()
{
QTextCursor cursor = this->textCursor();
int start_pos = qMin(cursor.selectionStart(), cursor.selectionEnd());
int end_pos = qMax(cursor.selectionStart(), cursor.selectionEnd());
cursor.setPosition(end_pos);
int last_line = cursor.block().blockNumber();
if (cursor.atBlockStart() && start_pos!=end_pos)
last_line -= 1;
cursor.setPosition(start_pos);
int first_line = cursor.block().blockNumber();
bool is_comment_or_whitespace = true;
bool at_least_one_comment = false;
for (int _line_nb = first_line; _line_nb < last_line+1; ++_line_nb) {
QString text = lstrip(cursor.block().text());
bool is_comment = text.startsWith(this->comment_string);
bool is_whitespace = text == "";
is_comment_or_whitespace *= (is_comment || is_whitespace);
if (is_comment)
at_least_one_comment = true;
cursor.movePosition(QTextCursor::NextBlock);
}
if (is_comment_or_whitespace && at_least_one_comment)
this->uncomment();
else
this->comment();
}
void CodeEditor::comment()
{
this->add_prefix(this->comment_string);
}
void CodeEditor::uncomment()
{
this->remove_prefix(this->comment_string);
}
QString CodeEditor::__blockcomment_bar()
{
QString res = this->comment_string + " " + QString(78-this->comment_string.size(), '=');
return res;
}
void CodeEditor::transform_to_uppercase()
{
QTextCursor cursor = this->textCursor();
int prev_pos = cursor.position();
QString selected_text = cursor.selectedText();
if (selected_text.size() == 0) {
prev_pos = cursor.position();
cursor.select(QTextCursor::WordUnderCursor);
selected_text = cursor.selectedText();
}
QString s = selected_text.toUpper();
cursor.insertText(s);
this->set_cursor_position(prev_pos);
}
void CodeEditor::transform_to_lowercase()
{
QTextCursor cursor = this->textCursor();
int prev_pos = cursor.position();
QString selected_text = cursor.selectedText();
if (selected_text.size() == 0) {
prev_pos = cursor.position();
cursor.select(QTextCursor::WordUnderCursor);
selected_text = cursor.selectedText();
}
QString s = selected_text.toLower();
cursor.insertText(s);
this->set_cursor_position(prev_pos);
}
void CodeEditor::blockcomment()
{
QString comline = this->__blockcomment_bar() + this->get_line_separator();
QTextCursor cursor = this->textCursor();
int start_pos, end_pos;
if (this->has_selected_text()) {
this->extend_selection_to_complete_lines();
start_pos = cursor.selectionStart();
end_pos = cursor.selectionEnd();
}
else {
start_pos = cursor.position();
end_pos = cursor.position();
}
cursor.beginEditBlock();
cursor.setPosition(start_pos);
cursor.movePosition(QTextCursor::StartOfBlock);
while (cursor.position() <= end_pos) {
cursor.insertText(this->comment_string + " ");
cursor.movePosition(QTextCursor::EndOfBlock);
if (cursor.atEnd())
break;
cursor.movePosition(QTextCursor::NextBlock);
end_pos += this->comment_string.size() + 1;
}
cursor.setPosition(end_pos);
cursor.movePosition(QTextCursor::EndOfBlock);
if (cursor.atEnd())
cursor.insertText(this->get_line_separator());
else
cursor.movePosition(QTextCursor::NextBlock);
cursor.insertText(comline);
cursor.setPosition(start_pos);
cursor.movePosition(QTextCursor::StartOfBlock);
cursor.insertText(comline);
cursor.endEditBlock();
}
void CodeEditor::unblockcomment()
{
auto __is_comment_bar = [this](const QTextCursor &cursor)
{
return cursor.block().text().startsWith(this->__blockcomment_bar());
};
QTextCursor cursor1 = this->textCursor();
if (__is_comment_bar(cursor1))
return;
while (!__is_comment_bar(cursor1)) {
cursor1.movePosition(QTextCursor::PreviousBlock);
if (cursor1.atStart())
break;
}
if (!__is_comment_bar(cursor1))
return;
auto __in_block_comment = [this](const QTextCursor &cursor)
{
QString cs = this->comment_string;
return cursor.block().text().startsWith(cs);
};
QTextCursor cursor2 = QTextCursor(cursor1);
cursor2.movePosition(QTextCursor::NextBlock);
while (!__is_comment_bar(cursor2) && __in_block_comment(cursor2)) {
cursor2.movePosition(QTextCursor::NextBlock);
if (cursor2.block() == this->document()->lastBlock())
break;
}
if (!__is_comment_bar(cursor2))
return;
QTextCursor cursor3 = this->textCursor();
cursor3.beginEditBlock();
cursor3.setPosition(cursor1.position());
cursor3.movePosition(QTextCursor::NextBlock);
while (cursor3.position() < cursor2.position()) {
cursor3.movePosition(QTextCursor::NextCharacter,
QTextCursor::KeepAnchor);
if (!cursor3.atBlockEnd())
cursor3.movePosition(QTextCursor::NextCharacter,
QTextCursor::KeepAnchor);
cursor3.removeSelectedText();
cursor3.movePosition(QTextCursor::NextBlock);
}
QList<QTextCursor> tmp;
tmp << cursor2 << cursor1;
foreach (QTextCursor cursor, tmp) {
cursor3.setPosition(cursor.position());
cursor3.select(QTextCursor::BlockUnderCursor);
cursor3.removeSelectedText();
}
cursor3.endEditBlock();
}
//------Kill ring handlers
void CodeEditor::kill_line_end()
{
QTextCursor cursor = this->textCursor();
cursor.clearSelection();
cursor.movePosition(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
if (!cursor.hasSelection())
cursor.movePosition(QTextCursor::NextBlock,
QTextCursor::KeepAnchor);
this->_kill_ring->kill_cursor(&cursor);
this->setTextCursor(cursor);
}
void CodeEditor::kill_line_start()
{
QTextCursor cursor = this->textCursor();
cursor.clearSelection();
cursor.movePosition(QTextCursor::StartOfBlock,
QTextCursor::KeepAnchor);
this->_kill_ring->kill_cursor(&cursor);
this->setTextCursor(cursor);
}
QTextCursor CodeEditor::_get_word_start_cursor(int position)
{
QTextDocument* document = this->document();
position--;
while (position && !document->characterAt(position).isLetterOrNumber())
position--;
while (position && document->characterAt(position).isLetterOrNumber())
position--;
QTextCursor cursor = this->textCursor();
cursor.setPosition(position+1);
return cursor;
}
QTextCursor CodeEditor::_get_word_end_cursor(int position)
{
QTextDocument* document = this->document();
QTextCursor cursor = this->textCursor();
position = cursor.position();
cursor.movePosition(QTextCursor::End);
int end = cursor.position();
while (position < end && !document->characterAt(position).isLetterOrNumber())
position++;
while (position < end && document->characterAt(position).isLetterOrNumber())
position++;
cursor.setPosition(position);
return cursor;
}
void CodeEditor::kill_prev_word()
{
int position = this->textCursor().position();
QTextCursor cursor = this->_get_word_start_cursor(position);
cursor.setPosition(position, QTextCursor::KeepAnchor);
this->_kill_ring->kill_cursor(&cursor);
this->setTextCursor(cursor);
}
void CodeEditor::kill_next_word()
{
int position = this->textCursor().position();
QTextCursor cursor = this->_get_word_end_cursor(position);
cursor.setPosition(position, QTextCursor::KeepAnchor);
this->_kill_ring->kill_cursor(&cursor);
this->setTextCursor(cursor);
}
//------Autoinsertion of quotes/colons
QString CodeEditor::__get_current_color(QTextCursor cursor)
{
if (cursor.isNull())
cursor = this->textCursor();
QTextBlock block = cursor.block();
int pos = cursor.position() - block.position();
QTextLayout* layout = block.layout();
QVector<QTextLayout::FormatRange> block_formats = layout->formats();
if (!block_formats.isEmpty()) {
QTextCharFormat current_format;
if (cursor.atBlockEnd())
current_format = block_formats.last().format;
else {
int flag = 1;
foreach (auto fmt, block_formats) {
if ((pos>=fmt.start) && (pos<fmt.start+fmt.length)) {
current_format = fmt.format;
flag = 0;
}
}
if (flag)
return QString();
}
QString color = current_format.foreground().color().name();
return color;
}
else
return QString();
}
bool CodeEditor::in_comment_or_string(QTextCursor cursor)
{
if (this->highlighter) {
QString current_color;
if (cursor.isNull())
current_color = this->__get_current_color();
else
current_color = this->__get_current_color(cursor);
QString comment_color = this->highlighter->get_color_name("comment");
QString string_color = this->highlighter->get_color_name("string");
if ((current_color==comment_color) || (current_color==string_color))
return true;
else
return false;
}
else
return false;
}
bool CodeEditor::__colon_keyword(QString text)
{
QStringList stmt_kws = {"def", "for", "if", "while", "with", "class", "elif",
"except"};
QStringList whole_kws = {"else", "try", "except", "finally"};
text = lstrip(text);
QStringList words = text.split(QRegularExpression("\\s+"));
foreach (const QString& wk, whole_kws) {
if (text == wk)
return true;
}
if (words.size() < 2)
return false;
foreach (const QString& sk, stmt_kws) {
if (words[0] == sk)
return true;
}
return false;
}
bool CodeEditor::__forbidden_colon_end_char(QString text)
{
QList<QChar> end_chars = {':', '\\', '[', '{', '(', ','};
text = rstrip(text);
foreach (const QChar& c, end_chars) {
if (text.endsWith(c))
return true;
}
return false;
}
bool CodeEditor::__unmatched_braces_in_line(const QString &text,const QChar& closing_braces_type)
{
QList<QChar> opening_braces, closing_braces;
if (closing_braces_type == QChar(0)) {
opening_braces = {'(', '[', '{'};
closing_braces = {')', ']', '}'};
}
else {
closing_braces = {closing_braces_type};
QHash<QChar,QChar> dict = {{')','('}, {'}','{'}, {']','['}};
opening_braces = {dict[closing_braces_type]};
}
QTextBlock block = this->textCursor().block();
int line_pos = block.position();
for (int pos = 0; pos < text.size(); ++pos) {
QChar _char = text[pos];
if (opening_braces.contains(_char)) {
int match = this->find_brace_match(line_pos+pos, _char, true);
if ((match == -1) || (match > line_pos+text.size()))
return true;
}
if (closing_braces.contains(_char)) {
int match = this->find_brace_match(line_pos+pos, _char, false);
if ((match == -1) || (match < line_pos))
return true;
}
}
return false;
}
bool CodeEditor::__has_colon_not_in_brackets(const QString &text)
{
for (int pos = 0; pos < text.size(); ++pos) {
QChar _char = text[pos];
if (_char == ':' && !this->__unmatched_braces_in_line(text.left(pos)))
return true;
}
return false;
}
bool CodeEditor::autoinsert_colons()
{
QString line_text = this->get_text("sol","cursor");
if (!this->textCursor().atBlockEnd())
return false;
else if (this->in_comment_or_string())
return false;
else if (!this->__colon_keyword(line_text))
return false;
else if (this->__forbidden_colon_end_char(line_text))
return false;
else if (this->__unmatched_braces_in_line(line_text))
return false;
else if (this->__has_colon_not_in_brackets(line_text))
return false;
else
return true;
}
QString CodeEditor::__unmatched_quotes_in_line(QString text)
{
text.replace("\\'","");
text.replace("\\\"","");
if (text.count("\"") % 2)
return "\"";
else if (text.count("'") % 2)
return "'";
else
return "";
}
QString CodeEditor::__next_char()
{
QTextCursor cursor = this->textCursor();
cursor.movePosition(QTextCursor::NextCharacter,
QTextCursor::KeepAnchor);
QString next_char = cursor.selectedText();
return next_char;
}
bool CodeEditor::__in_comment()
{
if (this->highlighter) {
QString current_color = this->__get_current_color();
QString comment_color = this->highlighter->get_color_name("comment");
if (current_color == comment_color)
return true;
else
return false;
}
else
return false;
}
void CodeEditor::autoinsert_quotes(int key)
{
QHash<int,QChar> dict = {{Qt::Key_QuoteDbl, '"'}, {Qt::Key_Apostrophe, '\''}};
QChar _char = dict[key];
QString line_text = this->get_text("sol","eol");
QString line_to_cursor = this->get_text("sol","cursor");
QTextCursor cursor = this->textCursor();
QString last_three = this->get_text("sol","cursor").right(3);
QString last_two = this->get_text("sol","cursor").right(2);
QString trailing_text = this->get_text("cursor","eol").trimmed();
if (this->has_selected_text()) {
QString text = _char + this->get_selected_text() + _char;
this->insert_text(text);
}
else if (this->__in_comment())
this->insert_text(_char);
else if (trailing_text.size() > 0 &&
!(this->__unmatched_quotes_in_line(line_to_cursor) == _char))
this->insert_text(_char);
else if (!this->__unmatched_quotes_in_line(line_text).isEmpty() &&
!(last_three == QString(3,_char)))
this->insert_text(_char);
else if (this->__next_char() == _char) {
cursor.movePosition(QTextCursor::NextCharacter,
QTextCursor::KeepAnchor, 1);
cursor.clearSelection();
this->setTextCursor(cursor);
}
else if (last_three == QString(3,_char)) {
this->insert_text(QString(3,_char));
cursor = this->textCursor();
cursor.movePosition(QTextCursor::PreviousCharacter,
QTextCursor::KeepAnchor, 3);
cursor.clearSelection();
this->setTextCursor(cursor);
}
else if (last_two == QString(2,_char)) {
this->insert_text(_char);
}
else {
this->insert_text(QString(2,_char));
cursor = this->textCursor();
cursor.movePosition(QTextCursor::PreviousCharacter);
this->setTextCursor(cursor);
}
}
void CodeEditor::setup_context_menu()
{
undo_action = new QAction("Undo",this);
connect(undo_action,SIGNAL(triggered(bool)),this,SLOT(undo()));
undo_action->setIcon(ima::icon("undo"));
undo_action->setShortcut(QKeySequence("Ctrl+Z"));
undo_action->setShortcutContext(Qt::WindowShortcut);
redo_action = new QAction("Redo",this);
connect(redo_action,SIGNAL(triggered(bool)),this,SLOT(redo()));
redo_action->setIcon(ima::icon("redo"));
redo_action->setShortcut(QKeySequence("Ctrl+Shift+Z"));
redo_action->setShortcutContext(Qt::WindowShortcut);
cut_action = new QAction("Cut",this);
connect(cut_action,SIGNAL(triggered(bool)),this,SLOT(cut()));
cut_action->setIcon(ima::icon("editcut"));
cut_action->setShortcut(QKeySequence("Ctrl+X"));
cut_action->setShortcutContext(Qt::WindowShortcut);
copy_action = new QAction("Copy",this);
connect(copy_action,SIGNAL(triggered(bool)),this,SLOT(copy()));
copy_action->setIcon(ima::icon("editcopy"));
copy_action->setShortcut(QKeySequence("Ctrl+C"));
copy_action->setShortcutContext(Qt::WindowShortcut);
paste_action = new QAction("Paste",this);
connect(paste_action,SIGNAL(triggered(bool)),this,SLOT(paste()));
paste_action->setIcon(ima::icon("editpaste"));
paste_action->setShortcut(QKeySequence("Ctrl+V"));
paste_action->setShortcutContext(Qt::WindowShortcut);
QAction* selectall_action = new QAction("Select All",this);
connect(selectall_action,SIGNAL(triggered(bool)),this,SLOT(selectAll()));
selectall_action->setIcon(ima::icon("selectall"));
selectall_action->setShortcut(QKeySequence("Ctrl+A"));
selectall_action->setShortcutContext(Qt::WindowShortcut);
QAction* toggle_comment_action = new QAction("Comment/Uncomment",this);
connect(toggle_comment_action,SIGNAL(triggered(bool)),this,SLOT(toggle_comment()));
toggle_comment_action->setIcon(ima::icon("comment"));
toggle_comment_action->setShortcut(QKeySequence("Ctrl+1"));
toggle_comment_action->setShortcutContext(Qt::WindowShortcut);
clear_all_output_action = new QAction("Clear all output",this);
connect(clear_all_output_action,SIGNAL(triggered(bool)),this,SLOT(clear_all_output()));
clear_all_output_action->setIcon(ima::icon("ipython_console"));
clear_all_output_action->setShortcutContext(Qt::WindowShortcut);
ipynb_convert_action = new QAction("Convert to Python script",this);
connect(ipynb_convert_action,SIGNAL(triggered(bool)),this,SLOT(convert_notebook()));
ipynb_convert_action->setIcon(ima::icon("python"));
ipynb_convert_action->setShortcutContext(Qt::WindowShortcut);
gotodef_action = new QAction("Go to definition",this);
connect(gotodef_action,SIGNAL(triggered(bool)),this,SLOT(go_to_definition_from_cursor()));
gotodef_action->setIcon(ima::icon("go to definition"));
gotodef_action->setShortcut(QKeySequence("Ctrl+G"));
gotodef_action->setShortcutContext(Qt::WindowShortcut);
//# Run actions
run_cell_action = new QAction("Run cell",this);
connect(run_cell_action,SIGNAL(triggered(bool)),this,SIGNAL(run_cell()));
run_cell_action->setIcon(ima::icon("run_cell"));
run_cell_action->setShortcut(QKeySequence("Ctrl+Return"));
run_cell_action->setShortcutContext(Qt::WindowShortcut);
run_cell_and_advance_action = new QAction("Run cell and advance",this);
connect(run_cell_and_advance_action,SIGNAL(triggered(bool)),this,SIGNAL(run_cell_and_advance()));
run_cell_and_advance_action->setIcon(ima::icon("run_cell"));
run_cell_and_advance_action->setShortcut(QKeySequence("Shift+Return"));
run_cell_and_advance_action->setShortcutContext(Qt::WindowShortcut);
re_run_last_cell_action = new QAction("Re-run last cell",this);
connect(re_run_last_cell_action,SIGNAL(triggered(bool)),this,SIGNAL(re_run_last_cell()));
re_run_last_cell_action->setIcon(ima::icon("run_cell"));
re_run_last_cell_action->setShortcut(QKeySequence("Alt+Return"));
re_run_last_cell_action->setShortcutContext(Qt::WindowShortcut);
run_selection_action = new QAction("Run &selection or current line",this);
connect(run_selection_action,SIGNAL(triggered(bool)),this,SIGNAL(run_selection()));
run_selection_action->setIcon(ima::icon("run selection"));
run_selection_action->setShortcut(QKeySequence("F9"));
run_selection_action->setShortcutContext(Qt::WindowShortcut);
//# Zoom actions
QAction* zoom_in_action = new QAction("Zoom in",this);
connect(zoom_in_action,SIGNAL(triggered(bool)),this,SIGNAL(zoom_in()));
zoom_in_action->setIcon(ima::icon("zoom_in"));
zoom_in_action->setShortcut(QKeySequence("ZoomIn"));
zoom_in_action->setShortcutContext(Qt::WindowShortcut);
QAction* zoom_out_action = new QAction("Zoom out",this);
connect(zoom_out_action,SIGNAL(triggered(bool)),this,SIGNAL(zoom_out()));
zoom_out_action->setIcon(ima::icon("zoom_out"));
zoom_out_action->setShortcut(QKeySequence("ZoomOut"));
zoom_out_action->setShortcutContext(Qt::WindowShortcut);
QAction* zoom_reset_action = new QAction("Zoom reset",this);
connect(zoom_reset_action,SIGNAL(triggered(bool)),this,SIGNAL(zoom_reset()));
zoom_reset_action->setShortcut(QKeySequence("Ctrl+0"));
zoom_reset_action->setShortcutContext(Qt::WindowShortcut);
this->menu = new QMenu(this);
QList<QAction*> actions_1 = { this->run_cell_action, this->run_cell_and_advance_action,
this->re_run_last_cell_action, this->run_selection_action,
this->gotodef_action, nullptr, this->undo_action,
this->redo_action, nullptr, this->cut_action,
this->copy_action, this->paste_action, selectall_action };
QList<QAction*> actions_2 = { nullptr, zoom_in_action, zoom_out_action, zoom_reset_action,
nullptr, toggle_comment_action };
QList<QAction*> actions = actions_1 + actions_2;
add_actions(this->menu, actions);
this->readonly_menu = new QMenu(this);
QList<QAction*> tmp = { this->copy_action, nullptr, selectall_action,
this->gotodef_action };
add_actions(this->readonly_menu, tmp);
}
void CodeEditor::keyReleaseEvent(QKeyEvent *event)
{
this->timer_syntax_highlight->start();
TextEditBaseWidget::keyReleaseEvent(event);
event->ignore();
}
void CodeEditor::keyPressEvent(QKeyEvent *event)
{
int key = event->key();
bool ctrl= event->modifiers() & Qt::ControlModifier;
bool shift = event->modifiers() & Qt::ShiftModifier;
QString text = event->text();
bool has_selection = this->has_selected_text();
if (!text.isEmpty())
this->__clear_occurrences();
if (QToolTip::isVisible())
this->hide_tooltip_if_necessary(key);
QList<QPair<QString,QString>> checks = {{qMakePair(QString("SelectAll"), QString("Select All"))},
{qMakePair(QString("Copy"), QString("Copy"))},
{qMakePair(QString("Cut"), QString("Cut"))},
{qMakePair(QString("Paste"), QString("Paste"))}};
//TODO for qname, name in checks:
// seq = getattr(QKeySequence, qname)
QStringList list_two = {"()", "[]", "{}", "\'\'", "\"\""};
QList<QChar> list_one = {',', ')', ']', '}'};
QHash<QString,QString> dict = {{"{", "{}"}, {"[", "[]"}};
if (key == Qt::Key_Enter || key == Qt::Key_Return) {
if (!shift && !ctrl) {
if (this->add_colons_enabled && this->is_python_like() &&
this->autoinsert_colons()) {
this->textCursor().beginEditBlock();
this->insert_text(':' + this->get_line_separator());
this->fix_indent();
this->textCursor().endEditBlock();
}
else if (this->is_completion_widget_visible()
&& this->codecompletion_enter)
this->select_completion_list();
else {
bool cmt_or_str_cursor = this->in_comment_or_string();
QTextCursor cursor = this->textCursor();
cursor.setPosition(cursor.block().position(),
QTextCursor::KeepAnchor);
bool cmt_or_str_line_begin = this->in_comment_or_string(
cursor);
bool cmt_or_str = cmt_or_str_cursor && cmt_or_str_line_begin;
this->textCursor().beginEditBlock();
TextEditBaseWidget::keyPressEvent(event);
this->fix_indent(cmt_or_str);
this->textCursor().endEditBlock();
}
}
else if (shift)
emit this->run_cell_and_advance();
else if (ctrl)
emit this->run_cell();
}
else if (shift && key == Qt::Key_Delete) {
if (has_selection)
this->cut();
else
this->delete_line();
}
else if (shift && key == Qt::Key_Insert)
this->paste();
else if (key == Qt::Key_Insert && !shift && !ctrl)
this->setOverwriteMode(!this->overwriteMode());
else if (key == Qt::Key_Backspace && !shift && !ctrl) {
QString leading_text = this->get_text("sol", "cursor");
int leading_length = leading_text.size();
int trailing_spaces = leading_length - rstrip(leading_text).size();
if (has_selection || !this->intelligent_backspace)
TextEditBaseWidget::keyPressEvent(event);
else {
QString trailing_text = this->get_text("cursor", "eol");
if (leading_text.trimmed().isEmpty()
&& leading_length > this->indent_chars.size()) {
if (leading_length % this->indent_chars.size() == 0)
this->unindent();
else
TextEditBaseWidget::keyPressEvent(event);
}
else if (trailing_spaces and trailing_text.trimmed().isEmpty())
this->remove_suffix(leading_text.right(trailing_spaces));
else if (!leading_text.isEmpty() && !trailing_text.isEmpty() &&
list_two.contains(leading_text.right(1) + trailing_text.left(1))) {
QTextCursor cursor = this->textCursor();
cursor.movePosition(QTextCursor::PreviousCharacter);
cursor.movePosition(QTextCursor::NextCharacter,
QTextCursor::KeepAnchor, 2);
cursor.removeSelectedText();
}
else {
TextEditBaseWidget::keyPressEvent(event);
if (this->is_completion_widget_visible())
this->completion_text.chop(1);
}
}
}
else if (key == Qt::Key_Period) {
this->insert_text(text);
if (this->is_python_like() &&
!this->in_comment_or_string() && this->codecompletion_auto) {
QString last_obj = getobj(this->get_text("sol", "cursor"));
if (!last_obj.isEmpty() && !isdigit(last_obj))
this->do_completion(true);
}
}
else if (key == Qt::Key_Home)
this->stdkey_home(shift, ctrl);
else if (key == Qt::Key_End)
this->stdkey_end(shift, ctrl);
else if (text == "(" && !has_selection) {
this->hide_completion_widget();
this->handle_parentheses(text);
}
else if ((text == "[" || text == "{") && !has_selection &&
this->close_parentheses_enabled) {
QString s_trailing_text = this->get_text("cursor", "eol").trimmed();
if (s_trailing_text.size() == 0 ||
list_one.contains(s_trailing_text[0])) {
this->insert_text(dict[text]);
QTextCursor cursor = this->textCursor();
cursor.movePosition(QTextCursor::PreviousCharacter);
this->setTextCursor(cursor);
}
else
TextEditBaseWidget::keyPressEvent(event);
}
else if ((key == Qt::Key_QuoteDbl || key == Qt::Key_Apostrophe) &&
this->close_quotes_enabled)
this->autoinsert_quotes(key);
else if ((key == Qt::Key_ParenRight || key == Qt::Key_BraceRight || key == Qt::Key_BracketRight)
&& !has_selection && this->close_parentheses_enabled
&& !this->textCursor().atBlockEnd()) {
QTextCursor cursor = this->textCursor();
cursor.movePosition(QTextCursor::NextCharacter,
QTextCursor::KeepAnchor);
QString text = cursor.selectedText();
QHash<int,QString> dict2 = {{Qt::Key_ParenRight, ")"},
{Qt::Key_BraceRight, "}"},
{Qt::Key_BracketRight, "]"}};
bool key_matches_next_char = text == dict2[key];
if (key_matches_next_char
&& !this->__unmatched_braces_in_line(
cursor.block().text(), text[0])) {
cursor.clearSelection();
this->setTextCursor(cursor);
}
else
TextEditBaseWidget::keyPressEvent(event);
}
else if (key == Qt::Key_Colon && !has_selection
&& this->auto_unindent_enabled) {
QString leading_text = this->get_text("sol", "cursor");
if (lstrip(leading_text)=="else" || lstrip(leading_text)=="finally") {
auto ind = [](const QString& txt) ->int { return txt.size()-lstrip(txt).size(); };
QString prevtxt = this->textCursor().block().previous().text();
if (ind(leading_text) == ind(prevtxt))
this->unindent(true);
}
TextEditBaseWidget::keyPressEvent(event);
}
else if (key == Qt::Key_Space && !shift && !ctrl
&& !has_selection && this->auto_unindent_enabled) {
QString leading_text = this->get_text("sol", "cursor");
if (lstrip(leading_text)=="elif" || lstrip(leading_text)=="except") {
auto ind = [](const QString& txt) ->int { return txt.size()-lstrip(txt).size(); };
QString prevtxt = this->textCursor().block().previous().text();
if (ind(leading_text) == ind(prevtxt))
this->unindent(true);
}
TextEditBaseWidget::keyPressEvent(event);
}
else if (key == Qt::Key_Tab) {
if (!has_selection && !this->tab_mode)
this->intelligent_tab();
else
this->indent_or_replace();
}
else if (key == Qt::Key_Backtab)
if (!has_selection && !this->tab_mode)
this->intelligent_backtab();
else
this->unindent();
else {
TextEditBaseWidget::keyPressEvent(event);
if (this->is_completion_widget_visible() && !text.isEmpty())
this->completion_text += text;
}
}
// 该函数依赖于第三方库pygments语法高亮库,因此不去实现它
void CodeEditor::run_pygments_highlighter()
{}
void CodeEditor::handle_parentheses(const QString &text)
{
int position = this->get_position("cursor");
QString rest = rstrip(this->get_text("cursor","eol"));
QList<QChar> list = {',', ')', ']', '}'};
bool valid = rest.isEmpty() || list.contains(rest[0]);
if (this->close_parentheses_enabled && valid) {
this->insert_text("()");
QTextCursor cursor = this->textCursor();
cursor.movePosition(QTextCursor::PreviousCharacter);
this->setTextCursor(cursor);
}
else
this->insert_text(text);
if (this->is_python_like() && !this->get_text("sol","cursor").isEmpty()
&& this->calltips)
emit this->sig_show_object_info(position);
}
void CodeEditor::mouseMoveEvent(QMouseEvent *event)
{
if (this->has_selected_text()) {
TextEditBaseWidget::mouseMoveEvent(event);
return;
}
if (this->go_to_definition_enabled &&
event->modifiers() & Qt::ControlModifier) {
QString text = this->get_word_at(event->pos());
if (!text.isEmpty() && (this->is_python_like())
&& !sourcecode::is_keyword(text)) {
if (!this->__cursor_changed) {
QApplication::setOverrideCursor(QCursor(Qt::PointingHandCursor));
this->__cursor_changed = true;
}
QTextCursor cursor = this->cursorForPosition(event->pos());
cursor.select(QTextCursor::WordUnderCursor);
this->clear_extra_selections("ctrl_click");
this->__highlight_selection("ctrl_click", cursor,
this->ctrl_click_color,
QColor(),
this->ctrl_click_color,
QTextCharFormat::SingleUnderline,
false);
event->accept();
return;
}
}
if (this->__cursor_changed) {
QApplication::restoreOverrideCursor();
this->__cursor_changed = false;
this->clear_extra_selections("ctrl_click");
}
TextEditBaseWidget::mouseMoveEvent(event);
}
void CodeEditor::leaveEvent(QEvent *event)
{
if (this->__cursor_changed) {
QApplication::restoreOverrideCursor();
this->__cursor_changed = false;
this->clear_extra_selections("ctrl_click");
}
TextEditBaseWidget::leaveEvent(event);
}
//@Slot()
void CodeEditor::go_to_definition_from_cursor(QTextCursor cursor)
{
if (!this->go_to_definition_enabled)
return;
if (cursor.isNull())
cursor = this->textCursor();
if (this->in_comment_or_string())
return;
int position = cursor.position();
QString text = cursor.selectedText();
if (text.size() == 0) {
cursor.select(QTextCursor::WordUnderCursor);
text = cursor.selectedText();
}
if (!text.isEmpty())
emit this->go_to_definition(position);
}
void CodeEditor::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton &&
(event->modifiers() & Qt::ControlModifier)) {
TextEditBaseWidget::mousePressEvent(event);
QTextCursor cursor = this->cursorForPosition(event->pos());
this->go_to_definition_from_cursor(cursor);
}
else
TextEditBaseWidget::mousePressEvent(event);
}
void CodeEditor::contextMenuEvent(QContextMenuEvent *event)
{
bool nonempty_selection = this->has_selected_text();
this->copy_action->setEnabled(nonempty_selection);
this->cut_action->setEnabled(nonempty_selection);
// TODO
this->clear_all_output_action->setVisible(this->is_json() && false);
this->ipynb_convert_action->setVisible(this->is_json() && false);
this->run_cell_action->setVisible(this->is_python());
this->run_cell_and_advance_action->setVisible(this->is_python());
this->re_run_last_cell_action->setVisible(this->is_python());
this->gotodef_action->setVisible(this->go_to_definition_enabled
&& this->is_python_like());
QTextCursor cursor = this->textCursor();
QString text = cursor.selectedText();
if (text.size() == 0) {
cursor.select(QTextCursor::WordUnderCursor);
text = cursor.selectedText();
}
this->undo_action->setEnabled(this->document()->isUndoAvailable());
this->redo_action->setEnabled(this->document()->isRedoAvailable());
QMenu* menu = this->menu;
if (this->isReadOnly())
menu = this->readonly_menu;
menu->popup(event->globalPos());
event->accept();
}
void CodeEditor::dragEnterEvent(QDragEnterEvent *event)
{
if (!mimedata2url(event->mimeData()).isEmpty())
event->ignore();
else
TextEditBaseWidget::dragEnterEvent(event);
}
void CodeEditor::dropEvent(QDropEvent *event)
{
if (!mimedata2url(event->mimeData()).isEmpty())
event->ignore();
else
TextEditBaseWidget::dropEvent(event);
}
//------ Paint event
void CodeEditor::paintEvent(QPaintEvent *event)
{
update_visible_blocks(event);
TextEditBaseWidget::paintEvent(event);
emit this->painted(event);
}
void CodeEditor::update_visible_blocks(QPaintEvent *event)
{
Q_UNUSED(event);
this->__visible_blocks.clear();
QTextBlock block = this->firstVisibleBlock();
int blockNumber = block.blockNumber();
int top = static_cast<int>(this->blockBoundingGeometry(block).translated(
this->contentOffset()).top());
int bottom = top + static_cast<int>(this->blockBoundingRect(block).height());
int ebottom_bottom = this->height();
while (block.isValid()) {
bool visible = bottom <= ebottom_bottom;
if (visible == false)
break;
if (block.isVisible())
this->__visible_blocks.append(IntIntTextblock(top, blockNumber+1, block));
block = block.next();
top = bottom;
bottom = top + static_cast<int>(this->blockBoundingRect(block).height());
blockNumber = block.blockNumber();
}
}
void CodeEditor::_draw_editor_cell_divider()
{
if (supported_cell_language) {
QColor cell_line_color = this->comment_color;
QPainter painter(this->viewport());
QPen pen = painter.pen();
pen.setStyle(Qt::SolidLine);
pen.setBrush(cell_line_color);
painter.setPen(pen);
foreach (auto pair, this->__visible_blocks) {
int top = pair.top;
QTextBlock block = pair.block;
// TODO源码是if self.is_cell_separator(block):
if (this->is_cell_separator(QTextCursor(),block))
painter.drawLine(4,top,this->width(),top);
}
}
}
QList<IntIntTextblock> CodeEditor::visible_blocks()
{
return __visible_blocks;
}
bool CodeEditor::is_editor()
{
return true;
}
Printer::Printer(QPrinter::PrinterMode mode, const QFont& header_font)
: QPrinter (mode)
{
this->setColorMode(QPrinter::Color);
this->setPageOrder(QPrinter::FirstPageFirst);
this->date = QDateTime::currentDateTime().toString();
if (header_font != QFont())
this->header_font = header_font;
}
TestWidget::TestWidget(QWidget *parent)
: QSplitter (parent)
{
editor = new CodeEditor(this);
QHash<QString, QVariant> kwargs;
kwargs["linenumbers"] = true;
kwargs["markers"] = true;
kwargs["tab_mode"] = false;
QFont font("Courier New", 10);
kwargs["font"] = QVariant::fromValue(font);
kwargs["show_blanks"] = true;
QHash<QString,ColorBoolBool> color_scheme;
color_scheme["background"] = ColorBoolBool("#3f3f3f");
color_scheme["currentline"] = ColorBoolBool("#333333");
color_scheme["currentcell"] = ColorBoolBool("#2c2c2c");
color_scheme["occurrence"] = ColorBoolBool("#7a738f");
color_scheme["ctrlclick"] = ColorBoolBool("#0000ff");
color_scheme["sideareas"] = ColorBoolBool("#3f3f3f");
color_scheme["matched_p"] = ColorBoolBool("#688060");
color_scheme["unmatched_p"] = ColorBoolBool("#bd6e76");
color_scheme["normal"] = ColorBoolBool("#dcdccc");
color_scheme["keyword"] = ColorBoolBool("#dfaf8f", true);
color_scheme["builtin"] = ColorBoolBool("#efef8f");
color_scheme["definition"] = ColorBoolBool("#efef8f");
color_scheme["comment"] = ColorBoolBool("#7f9f7f", false, true);
color_scheme["string"] = ColorBoolBool("#cc9393");
color_scheme["number"] = ColorBoolBool("#8cd0d3");
color_scheme["instance"] = ColorBoolBool("#dcdccc", false, true);
QHash<QString, QVariant> dict;
for (auto it=color_scheme.begin();it!=color_scheme.end();it++) {
QString key = it.key();
QVariant val = QVariant::fromValue(it.value());
dict[key] = val;
}
kwargs["color_scheme"] = dict;
editor->setup_editor(kwargs);
addWidget(editor);
classtree = new OutlineExplorerWidget(this);
addWidget(classtree);
connect(classtree,&OutlineExplorerWidget::edit_goto,
[this](const QString&,int line,const QString& word){ editor->go_to_line(line,word); });
setStretchFactor(0, 4);
setStretchFactor(1, 1);
setWindowIcon(ima::icon("spyder"));
}
void TestWidget::load(const QString &filename)
{
editor->set_text_from_file(filename);
QFileInfo info(filename);
setWindowTitle(QString("%1 - %2 (%3)").arg("Editor").
arg(info.fileName()).arg(info.absolutePath()));
classtree->set_current_editor(editor,filename,false,false);
}
static void test()
{
TestWidget* win = new TestWidget(nullptr);
win->show();
win->load("F:/MyPython/spyder/widgets/sourcecode/codeeditor.py");
win->resize(900, 700);
}
| [
"[email protected]"
] | |
bca3e7f30280e8392253449bc123dfa1f5c6a5bf | dd9ce079241a72419ba13db821f352df90c561d2 | /Motor.cpp | 04eacefff1e00d3ff92e361df5ed9b2521996301 | [
"MIT"
] | permissive | Darival/hbridge-motor | f872e7ca288e7514afe13606fc81a503c56bad8b | 5bed29577a84c55126ddac7af76b31e8ad73c094 | refs/heads/master | 2021-07-17T11:57:29.554868 | 2017-10-25T06:18:54 | 2017-10-25T06:18:54 | 108,227,641 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 772 | cpp | #include "Arduino.h"
#include "Motor.h"
Motor::Motor(int pinA, int pinB)
{
pinMode(pinA, OUTPUT);
pinMode(pinB, OUTPUT);
_pinA = pinA;
_pinB = pinB;
digitalWrite(_pinA, LOW);
digitalWrite(_pinB, LOW);
}
void Motor::brake(){
digitalWrite(_pinA, LOW);
digitalWrite(_pinB, LOW);
}
void Motor::fordward(){
digitalWrite(_pinA, HIGH);
digitalWrite(_pinB, LOW);
};
void Motor::backward(){
digitalWrite(_pinA, LOW);
digitalWrite(_pinB, HIGH);
};
bool Motor::isMoving(){
return digitalRead(_pinA) != digitalRead(_pinB);
};
bool Motor::isMovingFordward(){
return digitalRead(_pinA) == 1 && digitalRead(_pinB) == 0;
};
bool Motor::isMovingBackward(){
return digitalRead(_pinA) == 0 && digitalRead(_pinB) == 1;
};
| [
"[email protected]"
] | |
26c3ae62bfd349461b5d69bce7d9f21cc5395ee6 | a9736224708f049c901292a1afa508356fed4a35 | /tensorflow/compiler/mlir/tools/kernel_gen/transforms/tf_framework_legalize_to_llvm.cc | 3f64642156953f1d442a5214af7bba66862cb4b6 | [
"MIT",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | rammya29/tensorflow | d2fae99544a87ef44ead761b3326bd6df12af46b | 3795efc9294b52c123a266ebf14e60dad18f40a3 | refs/heads/master | 2023-06-22T21:09:23.465097 | 2021-07-14T06:53:27 | 2021-07-14T06:57:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,367 | cc | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <string>
#include "llvm/Support/FormatVariadic.h"
#include "mlir/Conversion/LLVMCommon/Pattern.h" // from @llvm-project
#include "mlir/Dialect/LLVMIR/LLVMDialect.h" // from @llvm-project
#include "mlir/Dialect/StandardOps/IR/Ops.h" // from @llvm-project
#include "mlir/IR/Attributes.h" // from @llvm-project
#include "mlir/IR/BuiltinOps.h" // from @llvm-project
#include "mlir/IR/BuiltinTypes.h" // from @llvm-project
#include "mlir/IR/Operation.h" // from @llvm-project
#include "mlir/Transforms/DialectConversion.h" // from @llvm-project
#include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.h"
#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/rewriters.h"
namespace mlir {
namespace kernel_gen {
namespace tf_framework {
namespace {
using LLVM::LLVMFuncOp;
static constexpr StringRef kCInterfaceAlloc = "_mlir_ciface_tf_alloc";
static constexpr StringRef kCInterfaceDealloc = "_mlir_ciface_tf_dealloc";
static constexpr StringRef kCInterfaceReportError =
"_mlir_ciface_tf_report_error";
/// Base class for patterns converting TF Framework ops to function calls.
template <typename OpTy>
class ConvertToLLVMCallOpPattern : public ConvertOpToLLVMPattern<OpTy> {
public:
using ConvertOpToLLVMPattern<OpTy>::ConvertOpToLLVMPattern;
// Attempts to find function symbol in the module, adds it if not found.
FlatSymbolRefAttr getOrInsertTFFunction(PatternRewriter &rewriter,
Operation *op) const {
ModuleOp module = op->getParentOfType<ModuleOp>();
StringRef tf_func_name = GetFuncName();
auto tf_func = module.lookupSymbol<LLVMFuncOp>(tf_func_name);
if (!tf_func) {
OpBuilder::InsertionGuard guard(rewriter);
rewriter.setInsertionPointToStart(module.getBody());
auto func_type = GetFuncType();
tf_func = rewriter.create<LLVMFuncOp>(rewriter.getUnknownLoc(),
tf_func_name, func_type);
}
return SymbolRefAttr::get(rewriter.getContext(), tf_func_name);
}
protected:
virtual StringRef GetFuncName() const = 0;
virtual Type GetFuncType() const = 0;
};
class TFAllocOpConverter : public ConvertToLLVMCallOpPattern<TFAllocOp> {
public:
using ConvertToLLVMCallOpPattern<TFAllocOp>::ConvertToLLVMCallOpPattern;
LogicalResult matchAndRewrite(
TFAllocOp tf_alloc_op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
mlir::Operation *op = tf_alloc_op.getOperation();
Location loc = op->getLoc();
TFAllocOp::Adaptor transformed(operands);
MemRefType memref_type = tf_alloc_op.getType();
// Get memref descriptor sizes.
SmallVector<Value, 4> sizes;
SmallVector<Value, 4> strides;
Value sizeBytes;
getMemRefDescriptorSizes(loc, memref_type,
llvm::to_vector<4>(transformed.dyn_sizes()),
rewriter, sizes, strides, sizeBytes);
// Get number of elements.
Value num_elements = getNumElements(loc, sizes, rewriter);
// Get element size.
Value element_size =
getSizeInBytes(loc, memref_type.getElementType(), rewriter);
// Convert `output_index` or set it to -1 if the attribute is missing.
Type llvmInt32Type = IntegerType::get(rewriter.getContext(), 32);
Value output_index = rewriter.create<LLVM::ConstantOp>(
loc, llvmInt32Type,
rewriter.getI32IntegerAttr(tf_alloc_op.output_index().hasValue()
? tf_alloc_op.output_index().getValue()
: -1));
// Convert `candidate_input_indices`.
auto candidates_count_and_ptr = ConvertI32ArrayAttrToStackAllocatedArray(
loc, tf_alloc_op.input_indices(), &rewriter);
// Insert function call.
FlatSymbolRefAttr tf_func_ref = getOrInsertTFFunction(rewriter, op);
Value allocated_byte_ptr =
rewriter
.create<LLVM::CallOp>(
loc, getVoidPtrType(), tf_func_ref,
llvm::makeArrayRef({transformed.ctx(), num_elements,
element_size, output_index,
candidates_count_and_ptr.first,
candidates_count_and_ptr.second}))
.getResult(0);
MemRefDescriptor memRefDescriptor = CreateMemRefDescriptor(
loc, rewriter, memref_type, allocated_byte_ptr, sizes);
// Return the final value of the descriptor.
rewriter.replaceOp(op, {memRefDescriptor});
return success();
}
protected:
StringRef GetFuncName() const override { return kCInterfaceAlloc; }
Type GetFuncType() const override {
Type llvm_i32_type = IntegerType::get(getDialect().getContext(), 32);
Type llvm_i32_ptr_type = LLVM::LLVMPointerType::get(llvm_i32_type);
Type llvm_void_ptr_type = getVoidPtrType();
return LLVM::LLVMFunctionType::get(
llvm_void_ptr_type,
llvm::makeArrayRef(
{/*void* op_kernel_ctx*/ llvm_void_ptr_type,
/*size_t num_elements*/ getIndexType(),
/*size_t element_size*/ getIndexType(),
/*int32_t output_index*/ llvm_i32_type,
/*int32_t num_candidates*/ llvm_i32_type,
/*int32_t* candidate_input_indices*/ llvm_i32_ptr_type}));
}
private:
// TODO(pifon): Remove strides computation.
MemRefDescriptor CreateMemRefDescriptor(Location loc,
ConversionPatternRewriter &rewriter,
MemRefType memref_type,
Value allocated_byte_ptr,
ArrayRef<Value> sizes) const {
auto memref_desc = MemRefDescriptor::undef(
rewriter, loc, typeConverter->convertType(memref_type));
// TF AllocateRaw returns aligned pointer => AllocatedPtr == AlignedPtr.
Value allocated_type_ptr = rewriter.create<LLVM::BitcastOp>(
loc, getElementPtrType(memref_type), allocated_byte_ptr);
memref_desc.setAllocatedPtr(rewriter, loc, allocated_type_ptr);
memref_desc.setAlignedPtr(rewriter, loc, allocated_type_ptr);
memref_desc.setConstantOffset(rewriter, loc, 0);
if (memref_type.getRank() == 0) {
return memref_desc;
}
// Compute strides and populate descriptor `size` and `stride` fields.
Value stride_carried = createIndexConstant(rewriter, loc, 1);
for (int pos = sizes.size() - 1; pos >= 0; --pos) {
Value size = sizes[pos];
memref_desc.setSize(rewriter, loc, pos, size);
memref_desc.setStride(rewriter, loc, pos, stride_carried);
// Update stride
if (pos > 0) {
stride_carried =
rewriter.create<LLVM::MulOp>(loc, stride_carried, size);
}
}
return memref_desc;
}
std::pair<Value, Value> ConvertI32ArrayAttrToStackAllocatedArray(
Location loc, llvm::Optional<ArrayAttr> attr,
ConversionPatternRewriter *rewriter) const {
Type llvm_i32_type = IntegerType::get(getDialect().getContext(), 32);
Type llvm_i32_ptr_type = LLVM::LLVMPointerType::get(llvm_i32_type);
// If the attribute is missing or empty, set the element count to 0 and
// return NULL.
if (!attr.hasValue() || attr.getValue().empty()) {
Value zero = rewriter->create<LLVM::ConstantOp>(
loc, llvm_i32_type, rewriter->getI32IntegerAttr(0));
Value null_ptr = rewriter->create<LLVM::NullOp>(loc, llvm_i32_ptr_type);
return std::make_pair(zero, null_ptr);
}
// Allocate array to store the elements.
auto &array_attr = attr.getValue();
Value array_size = rewriter->create<LLVM::ConstantOp>(
loc, llvm_i32_type, rewriter->getI32IntegerAttr(array_attr.size()));
Value array_ptr = rewriter->create<LLVM::AllocaOp>(
loc, llvm_i32_ptr_type, array_size, /*alignment=*/0);
for (auto &dim : llvm::enumerate(array_attr)) {
Value index = rewriter->create<LLVM::ConstantOp>(
loc, llvm_i32_type, rewriter->getI32IntegerAttr(dim.index()));
Value elem_ptr = rewriter->create<LLVM::GEPOp>(loc, llvm_i32_ptr_type,
array_ptr, index);
Value elem = rewriter->create<LLVM::ConstantOp>(
loc, llvm_i32_type,
rewriter->getI32IntegerAttr(
dim.value().cast<IntegerAttr>().getInt()));
rewriter->create<LLVM::StoreOp>(loc, elem, elem_ptr);
}
return std::make_pair(array_size, array_ptr);
}
};
class TFDeallocOpConverter : public ConvertToLLVMCallOpPattern<TFDeallocOp> {
public:
using ConvertToLLVMCallOpPattern<TFDeallocOp>::ConvertToLLVMCallOpPattern;
LogicalResult matchAndRewrite(
TFDeallocOp op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
TFDeallocOp::Adaptor transformed(operands);
MemRefDescriptor memref(transformed.memref());
Value allocated_bytes_ptr = rewriter.create<LLVM::BitcastOp>(
op.getLoc(), getVoidPtrType(),
memref.allocatedPtr(rewriter, op.getLoc()));
// Insert function call.
FlatSymbolRefAttr tf_func_ref = getOrInsertTFFunction(rewriter, op);
rewriter.replaceOpWithNewOp<LLVM::CallOp>(
op, llvm::None, tf_func_ref,
llvm::makeArrayRef({transformed.ctx(), allocated_bytes_ptr}));
return success();
}
protected:
StringRef GetFuncName() const override { return kCInterfaceDealloc; }
Type GetFuncType() const override {
return LLVM::LLVMFunctionType::get(getVoidType(),
{getVoidPtrType(), getVoidPtrType()});
}
};
class ReportErrorOpConverter
: public ConvertToLLVMCallOpPattern<ReportErrorOp> {
public:
using ConvertToLLVMCallOpPattern<ReportErrorOp>::ConvertToLLVMCallOpPattern;
LogicalResult matchAndRewrite(
ReportErrorOp op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
ReportErrorOp::Adaptor transformed(operands,
op.getOperation()->getAttrDictionary());
Location loc = op.getLoc();
auto module = op->getParentOfType<ModuleOp>();
Value message_constant = GenerateErrorMessageConstant(
loc, module, transformed.msg().getValue(), rewriter);
// Insert function call.
FlatSymbolRefAttr tf_func_ref = getOrInsertTFFunction(rewriter, op);
Value error_code = rewriter.create<LLVM::ConstantOp>(
loc, typeConverter->convertType(rewriter.getI32Type()),
transformed.error_code());
rewriter.replaceOpWithNewOp<LLVM::CallOp>(
op, llvm::None, tf_func_ref,
llvm::makeArrayRef({transformed.ctx(), error_code, message_constant}));
return success();
}
protected:
StringRef GetFuncName() const override { return kCInterfaceReportError; }
Type GetFuncType() const override {
MLIRContext *ctx = &getTypeConverter()->getContext();
auto i8_ptr_type = LLVM::LLVMPointerType::get(IntegerType::get(ctx, 8));
auto i32_type = IntegerType::get(ctx, 32);
return LLVM::LLVMFunctionType::get(
getVoidType(), {getVoidPtrType(), i32_type, i8_ptr_type});
}
private:
// Generates an LLVM IR dialect global that contains the name of the given
// kernel function as a C string, and returns a pointer to its beginning.
Value GenerateErrorMessageConstant(Location loc, Operation *module,
StringRef message,
OpBuilder &builder) const {
std::string err_str;
llvm::raw_string_ostream err_stream(err_str);
err_stream << message;
if (!loc.isa<UnknownLoc>()) {
err_stream << " at ";
loc.print(err_stream);
}
StringRef generated_error(err_stream.str());
std::string global_name =
llvm::formatv("error_message_{0}", llvm::hash_value(generated_error));
Operation *global_constant =
SymbolTable::lookupNearestSymbolFrom(module, global_name);
if (global_constant) {
Value globalPtr = builder.create<LLVM::AddressOfOp>(
loc, cast<LLVM::GlobalOp>(global_constant));
MLIRContext *ctx = &getTypeConverter()->getContext();
Value c0 = builder.create<LLVM::ConstantOp>(
loc, IntegerType::get(ctx, 64),
builder.getIntegerAttr(builder.getIndexType(), 0));
return builder.create<LLVM::GEPOp>(
loc, LLVM::LLVMPointerType::get(IntegerType::get(ctx, 8)), globalPtr,
ValueRange{c0, c0});
}
return LLVM::createGlobalString(loc, builder, global_name, generated_error,
LLVM::Linkage::Internal);
}
};
class NullContextOpConverter : public ConvertOpToLLVMPattern<NullContextOp> {
public:
using ConvertOpToLLVMPattern<NullContextOp>::ConvertOpToLLVMPattern;
LogicalResult matchAndRewrite(
NullContextOp op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
rewriter.replaceOpWithNewOp<LLVM::NullOp>(op, getVoidPtrType());
return success();
}
};
class NullMemRefOpConverter : public ConvertOpToLLVMPattern<NullMemRefOp> {
public:
using ConvertOpToLLVMPattern<NullMemRefOp>::ConvertOpToLLVMPattern;
LogicalResult matchAndRewrite(
NullMemRefOp null_memref_op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
Location loc = null_memref_op->getLoc();
LLVMTypeConverter type_converter = *getTypeConverter();
mlir::Operation *op = null_memref_op.getOperation();
auto shaped_result_type = null_memref_op.getType().cast<BaseMemRefType>();
unsigned address_space = shaped_result_type.getMemorySpaceAsInt();
Type elem_type = shaped_result_type.getElementType();
Type llvm_elem_type = type_converter.convertType(elem_type);
Value zero = createIndexConstant(rewriter, loc, 0);
if (auto result_type = null_memref_op.getType().dyn_cast<MemRefType>()) {
// Set all dynamic sizes to 1 and compute fake strides.
SmallVector<Value, 4> dyn_sizes(result_type.getNumDynamicDims(),
createIndexConstant(rewriter, loc, 1));
SmallVector<Value, 4> sizes, strides;
Value sizeBytes;
getMemRefDescriptorSizes(loc, result_type, dyn_sizes, rewriter, sizes,
strides, sizeBytes);
// Prepare packed args [allocatedPtr, alignedPtr, offset, sizes, strides]
// to create a memref descriptor.
Value null = rewriter.create<LLVM::NullOp>(
loc, LLVM::LLVMPointerType::get(llvm_elem_type, address_space));
SmallVector<Value, 12> packed_values{null, null, zero};
packed_values.append(sizes);
packed_values.append(strides);
rewriter.replaceOp(
op, MemRefDescriptor::pack(rewriter, loc, type_converter, result_type,
packed_values));
return success();
}
auto result_type = null_memref_op.getType().cast<UnrankedMemRefType>();
Type llvm_result_type = type_converter.convertType(result_type);
auto desc =
UnrankedMemRefDescriptor::undef(rewriter, loc, llvm_result_type);
desc.setRank(rewriter, loc, zero);
// Due to the current way of handling unranked memref results escaping, we
// have to actually construct a ranked underlying descriptor instead of just
// setting its pointer to NULL.
SmallVector<Value, 4> sizes;
UnrankedMemRefDescriptor::computeSizes(rewriter, loc, *getTypeConverter(),
desc, sizes);
Value underlying_desc_ptr = rewriter.create<LLVM::AllocaOp>(
loc, getVoidPtrType(), sizes.front(), llvm::None);
// Populate underlying ranked descriptor.
Type elem_ptr_ptr_type = LLVM::LLVMPointerType::get(
LLVM::LLVMPointerType::get(llvm_elem_type, address_space));
Value null = rewriter.create<LLVM::NullOp>(
loc, LLVM::LLVMPointerType::get(llvm_elem_type, address_space));
UnrankedMemRefDescriptor::setAllocatedPtr(
rewriter, loc, underlying_desc_ptr, elem_ptr_ptr_type, null);
UnrankedMemRefDescriptor::setAlignedPtr(rewriter, loc, *getTypeConverter(),
underlying_desc_ptr,
elem_ptr_ptr_type, null);
UnrankedMemRefDescriptor::setOffset(rewriter, loc, *getTypeConverter(),
underlying_desc_ptr, elem_ptr_ptr_type,
zero);
desc.setMemRefDescPtr(rewriter, loc, underlying_desc_ptr);
rewriter.replaceOp(op, {desc});
return success();
}
};
class IsValidMemRefOpConverter
: public ConvertOpToLLVMPattern<IsValidMemRefOp> {
public:
using ConvertOpToLLVMPattern<IsValidMemRefOp>::ConvertOpToLLVMPattern;
LogicalResult matchAndRewrite(
IsValidMemRefOp op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override {
Location loc = op.getLoc();
MemRefDescriptor desc(IsValidMemRefOp::Adaptor(operands).arg());
// Compare every size in the descriptor to 0 to check num_elements == 0.
int64_t rank = op.arg().getType().cast<MemRefType>().getRank();
Value is_empty_shape = rewriter.create<LLVM::ConstantOp>(
loc, rewriter.getI1Type(), rewriter.getBoolAttr(false));
Value zero = createIndexConstant(rewriter, loc, 0);
for (int i = 0; i < rank; ++i) {
Value size = desc.size(rewriter, loc, i);
Value is_zero_size = rewriter.create<LLVM::ICmpOp>(
loc, rewriter.getI1Type(), LLVM::ICmpPredicate::eq, size, zero);
is_empty_shape =
rewriter.create<LLVM::OrOp>(loc, is_empty_shape, is_zero_size);
}
Value ptr = rewriter.create<LLVM::BitcastOp>(
loc, getVoidPtrType(), desc.allocatedPtr(rewriter, loc));
Value null = rewriter.create<LLVM::NullOp>(loc, getVoidPtrType());
Value is_not_nullptr = rewriter.create<LLVM::ICmpOp>(
loc, rewriter.getI1Type(), LLVM::ICmpPredicate::ne, ptr, null);
// Valid memref = ptr != NULL || num_elements == 0;
rewriter.replaceOpWithNewOp<LLVM::OrOp>(op, is_not_nullptr, is_empty_shape);
return success();
}
};
} // namespace
void PopulateTFFrameworkToLLVMConversionPatterns(LLVMTypeConverter *converter,
RewritePatternSet *patterns) {
// clang-format off
patterns->insert<
IsValidMemRefOpConverter,
NullContextOpConverter,
NullMemRefOpConverter,
ReportErrorOpConverter,
TFAllocOpConverter,
TFDeallocOpConverter
>(*converter);
// clang-format on
}
} // namespace tf_framework
} // namespace kernel_gen
} // namespace mlir
| [
"[email protected]"
] | |
43ae3189c32b6ac4a708fbbed9d7b9996ab7090a | a9c2e831585f1e66e9619e181743c1b99926f8c7 | /ImageCropTest.cpp | f75d14be2ee3015efc75460fa650e040a0e755f6 | [] | no_license | header-file/2D_Portfolio_6th | 213186880744651427880716e98caecdbd8a5cb0 | f746894446cd12d8d7d874c312204431276f3f0a | refs/heads/master | 2020-06-02T02:22:43.816665 | 2019-06-09T12:38:01 | 2019-06-09T12:38:01 | 191,005,024 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 832 | cpp | #include "Game.h"
#include "ImageCropTest.h"
ImageCropTest::ImageCropTest()
{
}
ImageCropTest::~ImageCropTest()
{
}
bool ImageCropTest::Init()
{
_background = new Image;
_background->Init(TEXT("Image/BackGround.bmp"), WINSIZEX, WINSIZEY);
_offsetX = _offsetY = 0;
return true;
}
void ImageCropTest::Release()
{
SAFE_DELETE(_background);
}
void ImageCropTest::Update()
{
if (_offsetX <= 0)
_offsetX = 0;
if (_offsetY <= 0)
_offsetY = 0;
if (KEYMANAGER->isStayKeyDown(VK_LEFT))
_offsetX -= 3;
if (KEYMANAGER->isStayKeyDown(VK_RIGHT))
_offsetX += 3;
if (KEYMANAGER->isStayKeyDown(VK_UP))
_offsetY -= 3;
if (KEYMANAGER->isStayKeyDown(VK_DOWN))
_offsetY += 3;
}
void ImageCropTest::Render(HDC hdc)
{
_background->Render(hdc, 0, 0);
_background->Render(hdc, 100, 100, _offsetX, _offsetY, 200, 200);
}
| [
"[email protected]"
] | |
c2ec7e9e7994f3d5fd8590ce7254dfb8c4d1b1af | e4e9d9e089ce7b6987c542d359df5c74d9b19e2d | /TemSensor/Storage.h | 489747e7ffdfb5170219e7b03ffeaff23d2eb837 | [] | no_license | DZdream64/TemSensor | fcc4a76fc52345d5b6a68097ea5ea787921642b7 | bf71e022fd1ddd99bf509e99f73438984c520329 | refs/heads/master | 2021-01-18T14:14:12.437597 | 2016-04-19T04:08:29 | 2016-04-19T04:08:29 | 56,556,702 | 0 | 0 | null | 2016-04-19T02:04:12 | 2016-04-19T02:04:11 | null | UTF-8 | C++ | false | false | 117 | h | #pragma once
class CStorage
{
public:
CStorage();
virtual ~CStorage();
public:
virtual int storageData() = 0;
};
| [
"[email protected]"
] | |
d64bb5cdc30d6ee2524867643459af1766ea65d0 | d04ca01b62c9df153f0bf16748c28cc262ffba09 | /USACO/friday.cpp | 810ee042204ce255caafdafa13e3797ef8f55b1b | [] | no_license | PradCoder/Programming-Contests | 33ae9fc81e26dbb3671d3b674ed293576263fec8 | afbedd8d5db22446391a1efe2f954859540e9193 | refs/heads/master | 2023-01-18T15:26:21.977623 | 2023-01-18T04:44:20 | 2023-01-18T04:44:20 | 140,637,968 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,301 | cpp | /*
ID: 2010pes1
TASK: friday
LANG: C++
*/
#include "bits/stdc++.h"
#include <cstdint>
#define F first
#define S second
#define PG push_back
#define PPB pop_back
#define PF push_front
#define MP make_pair
#define REP0(i,a,b) for (int i = a; i < b; i++)
#define REP1(i,a,b) for (int i = a; i <= b; i++)
#define PPC __builtin_popcount
#define PPCLL __builtin_popcountll
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> pi;
void solveNotLeap(int state, int &n, vi &days){
int i = 1;
//SEP,APR,JUN,NOV have 30, FEB has 28 except on leap years its 29
for(int month = 1; month <= 12;){
if((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && i == 31){
i = 0;
month++;
}else if (month == 2 && ((state == 0 && i == 28) || (state == 1 && i == 29))){
i = 0;
month++;
}else if((month == 4 || month == 6 || month == 9 || month == 11) && i == 30){
i = 0;
month++;
}
if(i == 13){
days[n%7] += 1;
}
i++;
n++;
}
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
ifstream fin ("friday.in");
ofstream fout ("friday.out");
int n;
fin >> n;
vi days = vi(7);
//January 1st 1900 was a Monday
//SEP,APR,JUN,NOV have 30, FEB has 28 except on leap years its 29
//All other months have 31
//Every year evenly divisible by 4 is a leap year
//The above rule doesn't apply for century years not divisible by 400
int day = 1;
for(int i = 0 ; i < n; i++){
if((1900+i)%4 == 0){
if((1900+i)%100 == 0 && (1900+i)%400 == 0){
solveNotLeap(1,day,days);
}else if ((1900+i)%100 == 0 && (1900+i)%400 != 0){
solveNotLeap(0,day,days);
}else{
solveNotLeap(1,day,days);
}
}else{
solveNotLeap(0,day,days);
}
}
for(int i = 0; i < 6; i++){
fout << days[(i+6)%7] << " ";
}
fout << days[(6+6)%7] << "\n";
return 0;
}
| [
"[email protected]"
] | |
fc445c651c858eeeebf1cf2d8f6e49e503aa4a54 | f812cd27b0568316e839f2ab4d6e82e47762db30 | /Trabalho/3ºFase/Generator/Patch.cpp | 469b22a707f0949da67cb3c9d25b81dd5cef49d4 | [] | no_license | Komatsu52/CG | f52eccf841b1f58870db74ed99d3f62e28aeee25 | 9f9f25864f37e09065ffc26738d138a54f21143e | refs/heads/master | 2021-02-12T17:53:40.340113 | 2020-06-18T05:42:20 | 2020-06-18T05:42:20 | 244,614,167 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 4,598 | cpp | #include "Patch.h"
Patch :: Patch(){
}
Patch :: Patch(vector<Point> p){
controlPoints = p;
}
void Patch :: multMatrixVector(float *m, float *v, float *res) {
for(int i = 0; i < 4; ++i){
res[i] = 0;
for(int j = 0; j < 4; ++j)
res[i] += v[j] * m[i * 4 + j];
}
}
Patch ::Patch(int tess, string file) {
tesselation = tess;
parsePatchFile(file);
}
void Patch :: parsePatchFile(string filename) {
int i;
string line, x, y, z;
string fileDir = "../../Files3d/" + filename;
ifstream file(fileDir);
if(file.is_open()){
getline(file, line);
nPatches = stoi(line);
for(i = 0; i < nPatches; i++){
vector<int> patchIndex;
if(getline(file, line)){
char* str = strdup(line.c_str());
char* token = strtok(str, " ,");
while(token != NULL){
patchIndex.push_back(atoi(token));
token = strtok(NULL, " ,");
}
patches[i] = patchIndex;
free(str);
}
else
cout << "Incapaz de obter todos os patchIndex." << endl;
}
getline(file, line);
nPoints = stoi(line);
for(i = 0; i < nPoints; i++){
if(getline(file, line)){
char* str = strdup(line.c_str());
char* token = strtok(str, " ,");
float xx = atof(token);
token = strtok(NULL, " ,");
float yy = atof(token);
token = strtok(NULL, " ,");
float zz = atof(token);
Point *p = new Point(xx,yy,zz);
controlPoints.push_back(*p);
free(str);
}
else
cout << "Incapaz de obter todos os controlPoint." << endl;
}
file.close();
}
else
cout << "Erro na abertura do ficheiro " << filename << endl;
}
Point* Patch :: getPoint(float ta, float tb, float (*coordX)[4], float (*coordY)[4], float (*coordZ)[4]) {
float x = 0.0f, y = 0.0f, z = 0.0f;
float m[4][4] = {{-1.0f, 3.0f, -3.0f, 1.0f},
{ 3.0f, -6.0f, 3.0f, 0.0f},
{-3.0f, 3.0f, 0.0f, 0.0f},
{ 1.0f, 0.0f, 0.0f, 0.0f}};
float a[4] = { ta*ta*ta, ta*ta, ta, 1.0f};
float b[4] = { tb*tb*tb, tb*tb, tb, 1.0f};
float am[4];
multMatrixVector(*m,a,am);
float bm[4];
multMatrixVector(*m,b,bm);
float amCoordenadaX[4], amCoordenadaY[4], amCoordenadaZ[4];
multMatrixVector(*coordX,am,amCoordenadaX);
multMatrixVector(*coordY,am,amCoordenadaY);
multMatrixVector(*coordZ,am,amCoordenadaZ);
for (int i = 0; i < 4; i++)
{
x += amCoordenadaX[i] * bm[i];
y += amCoordenadaY[i] * bm[i];
z += amCoordenadaZ[i] * bm[i];
}
Point *p = new Point(x,y,z);
return p;
}
vector<Point> Patch::getPatchPoints(int patch) {
vector<Point> points;
vector<int> indexesControlPoints = patches.at(patch);
float coordenadasX[4][4], coordenadasY[4][4], coordenadasZ[4][4];
float u,v,uu,vv;
float t = 1.0f /(float)tesselation;
int pos = 0;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
Point controlPoint = controlPoints[indexesControlPoints[pos]];
coordenadasX[i][j] = controlPoint.getX();
coordenadasY[i][j] = controlPoint.getY();
coordenadasZ[i][j] = controlPoint.getZ();
pos++;
}
}
for(int i = 0; i < tesselation; i++)
{
for (int j = 0; j < tesselation; j++)
{
u = (float)i*t;
v = (float)j*t;
uu = (float)(i+1)*t;
vv = (float)(j+1)*t;
Point *p0,*p1,*p2,*p3;
p0 = getPoint(u, v, coordenadasX, coordenadasY, coordenadasZ);
p1 = getPoint(u, vv, coordenadasX, coordenadasY, coordenadasZ);
p2 = getPoint(uu, v, coordenadasX, coordenadasY, coordenadasZ);
p3 = getPoint(uu, vv, coordenadasX, coordenadasY, coordenadasZ);
points.push_back(*p0); points.push_back(*p2); points.push_back(*p1);
points.push_back(*p1); points.push_back(*p2); points.push_back(*p3);
}
}
return points;
}
vector<Point> Patch :: BezierModelGenerator() {
vector<Point> res;
for(int i = 0; i < nPatches; i++){
vector<Point> aux = getPatchPoints(i);
res.insert(res.end(), aux.begin(), aux.end());
}
return res;
} | [
"[email protected]"
] | |
3df84a4828343df699e6734c430745b208531f78 | ac0eac58bfff89e236ed152ba8853c672dfa0f17 | /Laborator 2 - Gramatici/Gramatica.h | d09a73cad490b341fbbf35708df0640d61382f19 | [] | no_license | robert-adrian99/FormalLanguagesAndCompilers | 6e58b6806b73940fc444e6c86ddaf060a351a17c | f5d68906b5b7b6050a3561d398d053d2fe434c62 | refs/heads/master | 2022-04-12T12:24:03.273663 | 2020-03-12T18:31:37 | 2020-03-12T18:31:37 | 246,121,823 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 480 | h | #pragma once
#include <iostream>
#include <fstream>
#include <vector>
#include <random>
#include <time.h>
class Gramatica
{
public:
Gramatica();
void citire();
void afisare();
int verificare();
void generare(bool optiune);
private:
void productiiAplicabile(const std::string& cuvantGenerat, std::vector<int>& prodAplicabile);
private:
std::vector<char> VN;
std::vector<char> VT;
char S;
std::vector<std::string> prodStanga;
std::vector<std::string> prodDreapta;
};
| [
"[email protected]"
] | |
713acfd2fcafe2fb945ac8748f43d91238891e22 | 0cbdd9cd7c395cff651d4f895fa327d9e464ab38 | /Src/KhaosMesh.cpp | 45ca6c29502d8fe93d53cba611058e3bb929e366 | [] | no_license | zengqh/khaos | 128c332a7bf443761e03847da69c6eb9aa9c3b4e | 929e60a8b72bf8e513200b9ce5837ec3e388bba4 | refs/heads/master | 2020-12-02T16:14:58.873539 | 2017-07-07T09:34:06 | 2017-07-07T09:34:06 | 96,522,956 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 18,203 | cpp | #include "KhaosPreHeaders.h"
#include "KhaosMesh.h"
#include "KhaosRenderDevice.h"
namespace Khaos
{
//////////////////////////////////////////////////////////////////////////
SubMesh::SubMesh() : m_primType(PT_TRIANGLELIST)
{
m_bvh = KHAOS_NEW AABBBVH;
m_bvh->_init(this);
}
SubMesh::~SubMesh()
{
KHAOS_DELETE m_bvh;
}
int SubMesh::getPrimitiveCount() const
{
return m_ib->getIndexCount() / getPrimitiveTypeVertexCount(m_primType);
}
int SubMesh::getVertexCount() const
{
return m_vb->getVertexCount();
}
VertexBuffer* SubMesh::createVertexBuffer()
{
if ( m_vb )
return m_vb.get();
m_vb.attach( g_renderDevice->createVertexBuffer() );
return m_vb.get();
}
IndexBuffer* SubMesh::createIndexBuffer()
{
if ( m_ib )
return m_ib.get();
m_ib.attach( g_renderDevice->createIndexBuffer() );
return m_ib.get();
}
void SubMesh::_expandVB( int maskAdd )
{
khaosAssert( m_vb );
VertexDeclaration* vd = m_vb->getDeclaration();
int newID = vd->getID() | maskAdd;
if ( vd->getID() == newID ) // 已经是了
return;
// 创建并复制
VertexDeclaration* vdNew = g_vertexDeclarationManager->getDeclaration(newID);
VertexBuffer* vbNew = g_renderDevice->createVertexBuffer();
vbNew->setDeclaration( vdNew );
vbNew->copyFrom( m_vb.get() );
// 设为新的
m_vb.reset( vbNew );
}
void SubMesh::expandNormal()
{
_expandVB( VFM_NOR );
}
void SubMesh::expandTangent()
{
_expandVB( VFM_TAN );
}
void SubMesh::expandSH( int order )
{
khaosAssert( order == 2 || order == 3 || order == 4 );
if ( order == 2 )
_expandVB( VFM_SH0 | VFM_SH1 );
else if ( order == 3 )
_expandVB( VFM_SH0 | VFM_SH1 | VFM_SH2 );
else if ( order == 4 )
_expandVB( VFM_SH0 | VFM_SH1 | VFM_SH2 | VFM_SH3 );
}
void SubMesh::expandTex2()
{
_expandVB( VFM_TEX2 );
}
void SubMesh::_getVertexAdjList( IntListList& adjList )
{
// 获取每个点的邻接面列表
adjList.resize( getVertexCount() );
int primCount = getPrimitiveCount();
for ( int f = 0; f < primCount; ++f )
{
int v0, v1, v2;
m_ib->getCacheTriIndices( f, v0, v1, v2 );
adjList[v0].push_back(f);
adjList[v1].push_back(f);
adjList[v2].push_back(f);
}
}
Vector3 SubMesh::_getFaceNormal( int face ) const
{
// 得到第f个面的法线
// 面的3个点
Vector3* v0;
Vector3* v1;
Vector3* v2;
const_cast<SubMesh*>(this)->getTriVertices( face, v0, v1, v2 );
// 求法线,注意这里面是逆时针顺序
Vector3 va = *v1 - *v0;
Vector3 vb = *v2 - *v1;
Vector3 vc = va.crossProduct( vb );
return vc; //.normalisedCopy(); // 这里考虑面积因素不单位化
}
void SubMesh::generateNormals( bool forceUpdate, bool refundImm )
{
khaosAssert( m_vb );
// 是否已经有法线了
if ( m_vb->hasElement(VFM_NOR) && !forceUpdate )
return;
// 确保法线
expandNormal();
// 确保缓存
cacheLocalData( true );
// 获取每个点的邻接面列表
IntListList adjList;
_getVertexAdjList( adjList );
// 遍历每个点
int vtxCnt = getVertexCount();
for ( int i = 0; i < vtxCnt; ++i )
{
// 计算该点的所有邻接面的法线和
Vector3 n(Vector3::ZERO);
const IntList& adjs = adjList[i];
int adjCnt = (int)adjs.size();
for ( int j = 0; j < adjCnt; ++j )
{
int faceIdx = adjs[j];
n += _getFaceNormal( faceIdx );
}
*(m_vb->getCacheNormal(i)) = n.normalisedCopy();
}
// 立即上传到gpu?
if ( refundImm )
m_vb->refundLocalData();
}
void SubMesh::generateTangents( bool forceUpdate, bool refundImm )
{
khaosAssert( m_vb );
// 如果没有法线,我们先创建法线
generateNormals( false, false );
// 是否已经有切线了
if ( m_vb->hasElement(VFM_TAN) && !forceUpdate )
return;
// 确保切线
expandTangent();
// 确保缓存
cacheLocalData( true );
// 开始计算切线~~~~~~~~~~~~~
// 计算每个面的切线
int primCount = getPrimitiveCount();
int vertexCount = getVertexCount();
vector<Vector3>::type faceTangents( primCount ); // 每个面的切线
vector<Vector3>::type faceBinormals( primCount ); // 每个面的次法线
IntListList vtxFaces( vertexCount ); // 每个顶点对应的邻接面列表
for ( int i = 0; i < primCount; ++i )
{
// 该面3点索引
int i0, i1, i2;
m_ib->getCacheTriIndices( i, i0, i1, i2 );
// 该面位置
const Vector3& v0 = *(m_vb->getCachePos(i0));
const Vector3& v1 = *(m_vb->getCachePos(i1));
const Vector3& v2 = *(m_vb->getCachePos(i2));
// 该面uv
const Vector2& uv0 = *(m_vb->getCacheTex(i0)); // 在第一套uv
const Vector2& uv1 = *(m_vb->getCacheTex(i1));
const Vector2& uv2 = *(m_vb->getCacheTex(i2));
// 第i个面的切线
Math::calcTangent( v0, v1, v2, uv0, uv1, uv2, faceTangents[i], faceBinormals[i] );
// 记录顶点使用的面
vtxFaces[i0].push_back( i );
vtxFaces[i1].push_back( i );
vtxFaces[i2].push_back( i );
}
// 计算每个顶点的平均切线
for ( int i = 0; i < vertexCount; ++i )
{
IntList& faces = vtxFaces[i]; // 该点邻接面
const Vector3& vnormal = *(m_vb->getCacheNormal(i)); // 该点法线
Vector3 tanget(Vector3::ZERO);
Vector3 binormal(Vector3::ZERO);
// 该点的所有邻接面的切线统计
for ( size_t j = 0; j < faces.size(); ++j )
{
int fi = faces[j];
tanget += faceTangents[fi];
binormal += faceBinormals[fi];
}
// 正交矫正
*(m_vb->getCacheTanget(i)) = Math::gramSchmidtOrthogonalize( tanget, binormal, vnormal );
}
// 立即上传到gpu?
if ( refundImm )
m_vb->refundLocalData();
}
void SubMesh::updateAABB()
{
m_aabb.setNull();
if ( !m_vb )
return;
if ( uint8* vb = (uint8*)m_vb->lock( HBA_READ ) )
{
//int posOffset = m_vb->getDeclaration()->findElement(VFM_POS)->offset;
Vector3* pos = (Vector3*)(vb /*+ posOffset*/); // always 0
m_aabb.merge( pos, m_vb->getVertexCount(), m_vb->getDeclaration()->getStride() );
m_vb->unlock();
}
}
void SubMesh::setAABB( const AxisAlignedBox& aabb )
{
m_aabb = aabb;
}
void SubMesh::draw()
{
g_renderDevice->setVertexBuffer( getVertexBuffer() );
if ( IndexBuffer* ib = getIndexBuffer() )
{
g_renderDevice->setIndexBuffer( ib );
g_renderDevice->drawIndexedPrimitive( getPrimitiveType(), 0, getPrimitiveCount() );
}
else
{
g_renderDevice->drawPrimitive( getPrimitiveType(), 0, getPrimitiveCount() );
}
}
void SubMesh::cacheLocalData( bool forceUpdate )
{
m_vb->cacheLocalData(forceUpdate);
m_ib->cacheLocalData(forceUpdate);
}
void SubMesh::freeLocalData()
{
m_vb->freeLocalData();
m_ib->freeLocalData();
}
void SubMesh::refundLocalData( bool vb, bool ib )
{
if ( vb )
m_vb->refundLocalData();
if ( ib )
m_ib->refundLocalData();
}
void SubMesh::getTriVertices( int face, Vector3*& v0, Vector3*& v1, Vector3*& v2 )
{
int i0, i1, i2;
m_ib->getCacheTriIndices( face, i0, i1, i2 );
v0 = m_vb->getCachePos(i0);
v1 = m_vb->getCachePos(i1);
v2 = m_vb->getCachePos(i2);
}
Vector2 SubMesh::getTriUV( int face, const Vector3& gravity ) const
{
int i0, i1, i2;
m_ib->getCacheTriIndices( face, i0, i1, i2 );
const Vector2& uv0 = *(m_vb->getCacheTex(i0));
const Vector2& uv1 = *(m_vb->getCacheTex(i1));
const Vector2& uv2 = *(m_vb->getCacheTex(i2));
return uv0 * gravity.x + uv1 * gravity.y + uv2 * gravity.z;
}
Vector2 SubMesh::getTriUV2( int face, const Vector3& gravity ) const
{
int i0, i1, i2;
m_ib->getCacheTriIndices( face, i0, i1, i2 );
const Vector2& uv0 = *(m_vb->getCacheTex2(i0));
const Vector2& uv1 = *(m_vb->getCacheTex2(i1));
const Vector2& uv2 = *(m_vb->getCacheTex2(i2));
return uv0 * gravity.x + uv1 * gravity.y + uv2 * gravity.z;
}
Vector3 SubMesh::getTriNormal( int face, const Vector3& gravity ) const
{
int i0, i1, i2;
m_ib->getCacheTriIndices( face, i0, i1, i2 );
const Vector3& norm0 = *(m_vb->getCacheNormal(i0));
const Vector3& norm1 = *(m_vb->getCacheNormal(i1));
const Vector3& norm2 = *(m_vb->getCacheNormal(i2));
return norm0 * gravity.x + norm1 * gravity.y + norm2 * gravity.z;
}
void SubMesh::buildBVH( bool forceUpdate )
{
cacheLocalData( false ); // 最低限度调用
m_bvh->build( forceUpdate );
}
void SubMesh::clearBVH()
{
m_bvh->clear();
}
AABBBVH::Result SubMesh::intersectDetail( const Ray& ray ) const
{
return m_bvh->intersect( ray );
}
AABBBVH::Result SubMesh::intersectDetail( const LimitRay& ray ) const
{
return m_bvh->intersect( ray );
}
void SubMesh::copyFrom( const SubMesh* rhs )
{
this->m_primType = rhs->m_primType;
// copy vb
this->m_vb.release();
if ( rhs->m_vb )
{
VertexBuffer* vb = this->createVertexBuffer();
vb->copyFrom( rhs->m_vb.get() );
}
// copy ib
this->m_ib.release();
if ( rhs->m_ib )
{
IndexBuffer* ib = this->createIndexBuffer();
ib->copyFrom( rhs->m_ib.get() );
}
// misc
this->m_aabb = rhs->m_aabb;
this->m_materialName = rhs->m_materialName;
this->m_bvh->clear(); // 不复制,总清空
}
//////////////////////////////////////////////////////////////////////////
Mesh::~Mesh()
{
_destructResImpl();
}
SubMesh* Mesh::createSubMesh()
{
SubMesh* sm = KHAOS_NEW SubMesh;
m_subMeshList.push_back( sm );
return sm;
}
void Mesh::setMaterialName( const String& mtrName )
{
KHAOS_FOR_EACH( SubMeshList, m_subMeshList, it )
{
(*it)->setMaterialName( mtrName );
}
}
void Mesh::updateAABB( bool forceAll )
{
m_aabb.setNull();
for ( SubMeshList::iterator it = m_subMeshList.begin(), ite = m_subMeshList.end(); it != ite; ++it )
{
SubMesh* sm = *it;
if ( forceAll )
sm->updateAABB();
m_aabb.merge( sm->getAABB() );
}
}
void Mesh::setAABB( const AxisAlignedBox& aabb )
{
m_aabb = aabb;
}
void Mesh::expandSH( int order )
{
for ( SubMeshList::iterator it = m_subMeshList.begin(), ite = m_subMeshList.end(); it != ite; ++it )
{
SubMesh* sm = *it;
sm->expandSH( order );
}
}
void Mesh::expandTex2()
{
for ( SubMeshList::iterator it = m_subMeshList.begin(), ite = m_subMeshList.end(); it != ite; ++it )
{
SubMesh* sm = *it;
sm->expandTex2();
}
}
void Mesh::generateNormals( bool forceUpdate, bool refundImm )
{
for ( SubMeshList::iterator it = m_subMeshList.begin(), ite = m_subMeshList.end(); it != ite; ++it )
{
SubMesh* sm = *it;
sm->generateNormals( forceUpdate, refundImm );
}
}
void Mesh::generateTangents( bool forceUpdate, bool refundImm )
{
for ( SubMeshList::iterator it = m_subMeshList.begin(), ite = m_subMeshList.end(); it != ite; ++it )
{
SubMesh* sm = *it;
sm->generateTangents( forceUpdate, refundImm );
}
}
void Mesh::cacheLocalData( bool forceUpdate )
{
for ( SubMeshList::iterator it = m_subMeshList.begin(), ite = m_subMeshList.end(); it != ite; ++it )
{
SubMesh* sm = *it;
sm->cacheLocalData( forceUpdate );
}
}
int Mesh::getVertexCount() const
{
int cnt = 0;
for ( SubMeshList::const_iterator it = m_subMeshList.begin(), ite = m_subMeshList.end(); it != ite; ++it )
{
const SubMesh* sm = *it;
cnt += sm->getVertexCount();
}
return cnt;
}
void Mesh::freeLocalData()
{
for ( SubMeshList::iterator it = m_subMeshList.begin(), ite = m_subMeshList.end(); it != ite; ++it )
{
SubMesh* sm = *it;
sm->freeLocalData();
}
}
void Mesh::buildBVH( bool forceUpdate )
{
for ( SubMeshList::iterator it = m_subMeshList.begin(), ite = m_subMeshList.end(); it != ite; ++it )
{
SubMesh* sm = *it;
sm->buildBVH( forceUpdate );
}
}
void Mesh::clearBVH()
{
for ( SubMeshList::iterator it = m_subMeshList.begin(), ite = m_subMeshList.end(); it != ite; ++it )
{
SubMesh* sm = *it;
sm->clearBVH();
}
}
template<class T>
bool Mesh::_intersectBoundImpl( const T& ray, float* t ) const
{
std::pair<bool, float> ret = ray.intersects( m_aabb );
if ( t && ret.first )
*t = ret.second;
return ret.first;
}
template<class T>
bool Mesh::_intersectBoundMoreImpl( const T& ray, int* subIdx, float* t ) const
{
int cnt = (int)m_subMeshList.size();
if ( cnt == 1 ) // 只有1个情况,优化成intersectBound
{
bool ret = _intersectBoundImpl( ray, t );
if ( subIdx && ret )
*subIdx = 0; // 1个肯定是0啦
return ret;
}
if ( !ray.intersects(m_aabb).first )
return false;
int sub = -1;
float dist = Math::POS_INFINITY;
for ( int i = 0; i < cnt; ++i )
{
const SubMesh* sm = m_subMeshList[i];
std::pair<bool, float> curr = ray.intersects( sm->getAABB() );
if ( curr.first && curr.second < dist )
{
sub = i;
dist = curr.second;
}
}
if ( sub == -1 )
return false;
if ( subIdx ) *subIdx = sub;
if ( t ) *t = dist;
return true;
}
template<class T>
bool Mesh::_intersectDetailImpl( const T& ray, int* subIdx, int* faceIdx, float* t, Vector3* gravity ) const
{
if ( !ray.intersects(m_aabb).first )
return false;
AABBBVH::Result ret;
int sub = -1;
int cnt = (int)m_subMeshList.size();
for ( int i = 0; i < cnt; ++i )
{
const SubMesh* sm = m_subMeshList[i];
AABBBVH::Result curr = sm->intersectDetail( ray );
if ( curr.face != -1 && curr.distance < ret.distance )
{
ret = curr;
sub = i;
}
}
if ( sub == -1 )
return false;
if ( subIdx ) *subIdx = sub;
if ( faceIdx ) *faceIdx = ret.face;
if ( t ) *t = ret.distance;
if ( gravity ) *gravity = ret.gravity;
return true;
}
bool Mesh::intersectBound( const Ray& ray, float* t ) const
{
return _intersectBoundImpl( ray, t );
}
bool Mesh::intersectBound( const LimitRay& ray, float* t ) const
{
return _intersectBoundImpl( ray, t );
}
bool Mesh::intersectBoundMore( const Ray& ray, int* subIdx, float* t ) const
{
return _intersectBoundMoreImpl( ray, subIdx, t );
}
bool Mesh::intersectBoundMore( const LimitRay& ray, int* subIdx, float* t ) const
{
return _intersectBoundMoreImpl( ray, subIdx, t );
}
bool Mesh::intersectDetail( const Ray& ray, int* subIdx, int* faceIdx, float* t, Vector3* gravity ) const
{
return _intersectDetailImpl( ray, subIdx, faceIdx, t, gravity );
}
bool Mesh::intersectDetail( const LimitRay& ray, int* subIdx, int* faceIdx, float* t, Vector3* gravity ) const
{
return _intersectDetailImpl( ray, subIdx, faceIdx, t, gravity );
}
void Mesh::_clearSubMesh()
{
for ( SubMeshList::iterator it = m_subMeshList.begin(), ite = m_subMeshList.end(); it != ite; ++it )
{
SubMesh* sm = *it;
KHAOS_DELETE sm;
}
m_subMeshList.clear();
}
void Mesh::copyFrom( const Resource* rhs )
{
const Mesh* meshOth = static_cast<const Mesh*>(rhs);
this->_clearSubMesh();
for ( int subIdx = 0; subIdx < meshOth->getSubMeshCount(); ++subIdx )
{
SubMesh* sm = this->createSubMesh();
SubMesh* smOth = meshOth->getSubMesh( subIdx );
sm->copyFrom( smOth );
}
m_aabb = meshOth->m_aabb;
}
void Mesh::_destructResImpl()
{
_clearSubMesh();
}
void Mesh::drawSub( int i )
{
getSubMesh(i)->draw();
}
}
| [
"[email protected]"
] | |
59b9a6f8195324e7fc5f637d7d56740d79a969b3 | 88ae8695987ada722184307301e221e1ba3cc2fa | /third_party/crashpad/crashpad/util/linux/ptrace_broker_test.cc | 0b9e917c943a14420885713d934dc91dde9bce4f | [
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"BSD-3-Clause"
] | permissive | iridium-browser/iridium-browser | 71d9c5ff76e014e6900b825f67389ab0ccd01329 | 5ee297f53dc7f8e70183031cff62f37b0f19d25f | refs/heads/master | 2023-08-03T16:44:16.844552 | 2023-07-20T15:17:00 | 2023-07-23T16:09:30 | 220,016,632 | 341 | 40 | BSD-3-Clause | 2021-08-13T13:54:45 | 2019-11-06T14:32:31 | null | UTF-8 | C++ | false | false | 8,568 | cc | // Copyright 2017 The Crashpad Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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 "util/linux/ptrace_broker.h"
#include <sys/socket.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
#include <utility>
#include "build/build_config.h"
#include "gtest/gtest.h"
#include "test/filesystem.h"
#include "test/linux/get_tls.h"
#include "test/multiprocess.h"
#include "test/scoped_temp_dir.h"
#include "util/file/file_io.h"
#include "util/linux/ptrace_client.h"
#include "util/posix/scoped_mmap.h"
#include "util/synchronization/semaphore.h"
#include "util/thread/thread.h"
namespace crashpad {
namespace test {
namespace {
class ScopedTimeoutThread : public Thread {
public:
ScopedTimeoutThread() : join_sem_(0) {}
ScopedTimeoutThread(const ScopedTimeoutThread&) = delete;
ScopedTimeoutThread& operator=(const ScopedTimeoutThread&) = delete;
~ScopedTimeoutThread() { EXPECT_TRUE(JoinWithTimeout(5.0)); }
protected:
void ThreadMain() override { join_sem_.Signal(); }
private:
bool JoinWithTimeout(double timeout) {
if (!join_sem_.TimedWait(timeout)) {
return false;
}
Join();
return true;
}
Semaphore join_sem_;
};
class RunBrokerThread : public ScopedTimeoutThread {
public:
RunBrokerThread(PtraceBroker* broker)
: ScopedTimeoutThread(), broker_(broker) {}
RunBrokerThread(const RunBrokerThread&) = delete;
RunBrokerThread& operator=(const RunBrokerThread&) = delete;
~RunBrokerThread() {}
private:
void ThreadMain() override {
EXPECT_EQ(broker_->Run(), 0);
ScopedTimeoutThread::ThreadMain();
}
PtraceBroker* broker_;
};
class BlockOnReadThread : public ScopedTimeoutThread {
public:
BlockOnReadThread(int readfd, int writefd)
: ScopedTimeoutThread(), readfd_(readfd), writefd_(writefd) {}
BlockOnReadThread(const BlockOnReadThread&) = delete;
BlockOnReadThread& operator=(const BlockOnReadThread&) = delete;
~BlockOnReadThread() {}
private:
void ThreadMain() override {
pid_t pid = syscall(SYS_gettid);
LoggingWriteFile(writefd_, &pid, sizeof(pid));
LinuxVMAddress tls = GetTLS();
LoggingWriteFile(writefd_, &tls, sizeof(tls));
CheckedReadFileAtEOF(readfd_);
ScopedTimeoutThread::ThreadMain();
}
int readfd_;
int writefd_;
};
class SameBitnessTest : public Multiprocess {
public:
SameBitnessTest() : Multiprocess(), mapping_() {}
SameBitnessTest(const SameBitnessTest&) = delete;
SameBitnessTest& operator=(const SameBitnessTest&) = delete;
~SameBitnessTest() {}
protected:
void PreFork() override {
ASSERT_NO_FATAL_FAILURE(Multiprocess::PreFork());
size_t page_size = getpagesize();
ASSERT_TRUE(mapping_.ResetMmap(nullptr,
page_size * 3,
PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON,
-1,
0));
ASSERT_TRUE(mapping_.ResetAddrLen(mapping_.addr(), page_size * 2));
auto buffer = mapping_.addr_as<char*>();
for (size_t index = 0; index < mapping_.len(); ++index) {
buffer[index] = index % 256;
}
}
private:
void BrokerTests(bool set_broker_pid,
LinuxVMAddress child1_tls,
LinuxVMAddress child2_tls,
pid_t child2_tid,
const base::FilePath& file_dir,
const base::FilePath& test_file,
const std::string& expected_file_contents) {
int socks[2];
ASSERT_EQ(socketpair(AF_UNIX, SOCK_STREAM, 0, socks), 0);
ScopedFileHandle broker_sock(socks[0]);
ScopedFileHandle client_sock(socks[1]);
#if defined(ARCH_CPU_64_BITS)
constexpr bool am_64_bit = true;
#else
constexpr bool am_64_bit = false;
#endif // ARCH_CPU_64_BITS
PtraceBroker broker(
broker_sock.get(), set_broker_pid ? ChildPID() : -1, am_64_bit);
RunBrokerThread broker_thread(&broker);
broker_thread.Start();
PtraceClient client;
ASSERT_TRUE(client.Initialize(client_sock.get(), ChildPID()));
EXPECT_EQ(client.GetProcessID(), ChildPID());
std::vector<pid_t> threads;
ASSERT_TRUE(client.Threads(&threads));
EXPECT_EQ(threads.size(), 2u);
if (threads[0] == ChildPID()) {
EXPECT_EQ(threads[1], child2_tid);
} else {
EXPECT_EQ(threads[0], child2_tid);
EXPECT_EQ(threads[1], ChildPID());
}
EXPECT_TRUE(client.Attach(child2_tid));
EXPECT_EQ(client.Is64Bit(), am_64_bit);
ThreadInfo info1;
ASSERT_TRUE(client.GetThreadInfo(ChildPID(), &info1));
EXPECT_EQ(info1.thread_specific_data_address, child1_tls);
ThreadInfo info2;
ASSERT_TRUE(client.GetThreadInfo(child2_tid, &info2));
EXPECT_EQ(info2.thread_specific_data_address, child2_tls);
auto expected_buffer = mapping_.addr_as<char*>();
char first;
ASSERT_EQ(
client.ReadUpTo(mapping_.addr_as<VMAddress>(), sizeof(first), &first),
1);
EXPECT_EQ(first, expected_buffer[0]);
char last;
ASSERT_EQ(
client.ReadUpTo(mapping_.addr_as<VMAddress>() + mapping_.len() - 1,
sizeof(last),
&last),
1);
EXPECT_EQ(last, expected_buffer[mapping_.len() - 1]);
char unmapped;
EXPECT_EQ(client.ReadUpTo(mapping_.addr_as<VMAddress>() + mapping_.len(),
sizeof(unmapped),
&unmapped),
-1);
std::string file_root = file_dir.value() + '/';
broker.SetFileRoot(file_root.c_str());
std::string file_contents;
ASSERT_TRUE(client.ReadFileContents(test_file, &file_contents));
EXPECT_EQ(file_contents, expected_file_contents);
ScopedTempDir temp_dir2;
base::FilePath test_file2(temp_dir2.path().Append("test_file2"));
ASSERT_TRUE(CreateFile(test_file2));
EXPECT_FALSE(client.ReadFileContents(test_file2, &file_contents));
}
void MultiprocessParent() override {
LinuxVMAddress child1_tls;
ASSERT_TRUE(LoggingReadFileExactly(
ReadPipeHandle(), &child1_tls, sizeof(child1_tls)));
pid_t child2_tid;
ASSERT_TRUE(LoggingReadFileExactly(
ReadPipeHandle(), &child2_tid, sizeof(child2_tid)));
LinuxVMAddress child2_tls;
ASSERT_TRUE(LoggingReadFileExactly(
ReadPipeHandle(), &child2_tls, sizeof(child2_tls)));
ScopedTempDir temp_dir;
base::FilePath file_path(temp_dir.path().Append("test_file"));
std::string expected_file_contents;
{
expected_file_contents.resize(4097);
for (size_t i = 0; i < expected_file_contents.size(); ++i) {
expected_file_contents[i] = static_cast<char>(i % 256);
}
ScopedFileHandle handle(
LoggingOpenFileForWrite(file_path,
FileWriteMode::kCreateOrFail,
FilePermissions::kWorldReadable));
ASSERT_TRUE(LoggingWriteFile(handle.get(),
expected_file_contents.data(),
expected_file_contents.size()));
}
BrokerTests(true,
child1_tls,
child2_tls,
child2_tid,
temp_dir.path(),
file_path,
expected_file_contents);
BrokerTests(false,
child1_tls,
child2_tls,
child2_tid,
temp_dir.path(),
file_path,
expected_file_contents);
}
void MultiprocessChild() override {
LinuxVMAddress tls = GetTLS();
ASSERT_TRUE(LoggingWriteFile(WritePipeHandle(), &tls, sizeof(tls)));
BlockOnReadThread thread(ReadPipeHandle(), WritePipeHandle());
thread.Start();
CheckedReadFileAtEOF(ReadPipeHandle());
}
ScopedMmap mapping_;
};
TEST(PtraceBroker, SameBitness) {
SameBitnessTest test;
test.Run();
}
// TODO(jperaza): Test against a process with different bitness.
} // namespace
} // namespace test
} // namespace crashpad
| [
"[email protected]"
] | |
6dafb1709f149638caa18a42e0134cb622c96851 | b5e8910a20789df489b4c2dff68f1a4f98c91d52 | /SingleCoreLib/scl/UniqueId.h | 336e4bd7d599ca9ec0ab82aa5e15ad488708c41a | [] | no_license | acoross/ComponentModel2 | 152fd27e3865ed833f7b99e660eb09f2a5a9d7c3 | c8f182620dba3120b38c7d4af7de6beaac4a1a78 | refs/heads/master | 2021-01-23T00:53:18.470496 | 2017-06-16T16:41:23 | 2017-06-16T16:41:23 | 85,846,051 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 180 | h | #pragma once
namespace scl
{
template <class T, class Siz = int>
class UniqueId
{
public:
static Siz Generate()
{
static Siz uid = 0;
++uid;
return uid;
}
};
} | [
"[email protected]"
] | |
a33e1f0821911a67b8f9c5179c5889c7f6db4da7 | e5c0c066460aca04a208fef22d44f9a6d1305ebf | /hw2_2/main.cpp | c7b2cd5458658fbd398aab7f6a4d8ea8fcf9c297 | [] | no_license | kamanov/cgcourseau2014autumn | 453152f94a3653d4efc6802a431ac2147425f0b8 | 229d6cdef39664f58c618382abfa79514dec5835 | refs/heads/master | 2020-06-04T14:44:42.727836 | 2015-02-09T09:12:02 | 2015-02-09T09:12:02 | 29,933,839 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 199 | cpp | #include "widget.h"
#include "glwidget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
return 0;
}
| [
"[email protected]"
] | |
dae561d3cad1b72d65ecf485bb73d9a6e5b14c4b | cd4c589986e0cb69c025a50091a6cb083b1c5586 | /QuantumEngine/Entities/GameObjectManager.h | bcb29117bbfd987c24ddb1bb2767a1306c2d1240 | [] | no_license | DarriusWright/QuantumEngine | 245e41afbf2d3eb4284afeb094a1b39b3423f739 | aa1660fb6cb4c3645dcff215438b1b19a68dae06 | refs/heads/master | 2016-09-06T05:30:11.874136 | 2014-12-14T07:58:53 | 2014-12-14T07:58:53 | 27,872,722 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 802 | h | #pragma once
#include <RTTI.h>
#include <ExportHeader.h>
#include <Manager.h>
#include <vector>
#include <map>
#include "GameObject.h"
#define GAMEOBJECT GameObjectManager::getInstance()
class GameObjectManager : public Manager
{
RTTI_DECLARATIONS(GameObjectManager, RTTI);
public:
ENGINE_SHARED ~GameObjectManager();
ENGINE_SHARED GameObject * createGameObject(TransformComponent * transform = nullptr);
ENGINE_SHARED void update()override;
ENGINE_SHARED bool startUp()override;
ENGINE_SHARED bool shutDown()override;
static GameObjectManager * getInstance()
{
static GameObjectManager * gameObjectManager = new GameObjectManager();
return gameObjectManager;
}
protected:
ENGINE_SHARED GameObjectManager();
std::map<int, GameObject*> gameObjects;
static int numGameObjects;
};
| [
"[email protected]"
] | |
4d22ffae5c234dbd322296cc038d7e8f8c33d79a | 3179943d68996d3ca2d81961be0ac207300b7e4a | /c-upgrade/pta-dsstart-2.cpp | 167f530b1d108514fa0517ede3f2b55648fe6d1e | [] | no_license | xucaimao/netlesson | 8425a925fa671fb9fd372610c19b499b0d8a6fc2 | 088004a9b758387ae6860e2a44b587b54dbbd525 | refs/heads/master | 2021-06-07T06:24:35.276948 | 2020-05-30T07:04:02 | 2020-05-30T07:04:02 | 110,668,572 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 702 | cpp | //中国大学MOOC-陈越、何钦铭-数据结构-起步能力自测题-2 素数对猜想
//write by xucaimao ;20171107-20:00
#include<cstdio>
#include<cmath>
const int maxn=100010;
int prime[maxn];
int main(){
for(int i=2;i<maxn;i++)
prime[i]=1;
int sq=sqrt(maxn)+1;
prime[0]=0;
prime[1]=0;
for(int i=2;i<sq;i++)
for(int j=i*i;j<maxn;j+=i)
prime[j]=0;
//for(int i=2;i<maxn;i++)
//if(prime[i]) printf("%d ",i);
int N,tot=0,n=2,n1=3;
scanf("%d",&N);
while(n1<=N){
if( (n1-n) ==2 )tot++;
n=n1;
n1++;//指向下一个数字
while(!prime[n1])//指向下一个素数
n1++;
//printf("%d ",n1);
}
printf("%d\n",tot);
return 0;
} | [
"[email protected]"
] | |
5b76d2b6dbb8cd9ce3d23aee21717d75aa134317 | d5343dc299a6185326f9af2aab69987a95108633 | /src/channel_access/server/cas/convert.hpp | d210e9998ad4ab23b0d2f66761bc0785012b78c4 | [
"MIT"
] | permissive | delta-accelerator/channel_access.server | e90b4017954b47f4d57fe78e32de29742c81df74 | d5f0456bc37bbe80b9d105e84f9dc43a6b438b78 | refs/heads/master | 2023-02-27T19:41:12.386811 | 2022-08-16T12:51:54 | 2022-08-16T12:51:54 | 189,587,814 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,108 | hpp | #ifndef INCLUDE_GUARD_120C2201_BD9B_465C_B2BD_70FE4AA4A6BD
#define INCLUDE_GUARD_120C2201_BD9B_465C_B2BD_70FE4AA4A6BD
#include <Python.h>
#include <casdef.h>
namespace cas {
/** Convert ExistsResponse enum value to pvExistsReturn value
*/
bool to_exist_return(PyObject* value, pvExistReturn& result);
/** Convert AttachResponse to pvAttachReturn value
*/
bool to_attach_return(PyObject* value, pvAttachReturn& result);
/** convert FieldType enum value to aitEnum value
*/
bool to_ait_enum(PyObject* value, aitEnum& result);
/** convert python value to gdd value
* use type as the value type.
* convert any sequence to an array.
*/
bool to_gdd(PyObject* dict, aitEnum type, gdd &result);
/** convert a gdd value to a python value
* If compiled without numpy support, numpy is always false.
* For array values:
* if numpy is true create a numpy array otherwise create a tuple.
*/
PyObject* from_gdd(gdd const& value, bool numpy = false);
/** convert python Trigger value to caEvent mask value
*/
bool to_event_mask(PyObject* value, casEventMask& mask, caServer const& server);
}
#endif
| [
"[email protected]"
] | |
31aa6d8ae6eceffaad0c5e93c4595c9496d02643 | bb1bd534be66f23bc6a8f1d153e20c0690edac6c | /src/PipelineManager.cpp | acbf2fd475cdf6da9df61ea65be36c6cf33e5b6e | [
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | permissive | chenming5828/tiscamera | 417e37d36dc7305b4dbd9c54060a35744594c1cf | f5bf8f02127946027edfe00bfdfd7fccc01e517e | refs/heads/master | 2021-08-14T16:54:21.684854 | 2017-11-14T09:16:04 | 2017-11-14T09:16:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,888 | cpp | /*
* Copyright 2014 The Imaging Source Europe GmbH
*
* 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 "PipelineManager.h"
#include "internal.h"
#include <ctime>
#include <cstring>
#include <algorithm>
#include <utils.h>
using namespace tcam;
PipelineManager::PipelineManager ()
: status(TCAM_PIPELINE_UNDEFINED), current_ppl_buffer(0)
{}
PipelineManager::~PipelineManager ()
{
if (status == TCAM_PIPELINE_PLAYING)
{
stop_playing();
}
available_filter.clear();
filter_pipeline.clear();
filter_properties.clear();
}
std::vector<std::shared_ptr<Property>> PipelineManager::getFilterProperties ()
{
return filter_properties;
}
std::vector<VideoFormatDescription> PipelineManager::getAvailableVideoFormats () const
{
return available_output_formats;
}
bool PipelineManager::setVideoFormat(const VideoFormat& f)
{
this->output_format = f;
return true;
}
VideoFormat PipelineManager::getVideoFormat () const
{
return this->output_format;
}
bool PipelineManager::set_status (TCAM_PIPELINE_STATUS s)
{
if (status == s)
return true;
this->status = s;
if (status == TCAM_PIPELINE_PLAYING)
{
if (create_pipeline())
{
start_playing();
tcam_log(TCAM_LOG_INFO, "All pipeline elements set to PLAYING.");
}
else
{
status = TCAM_PIPELINE_ERROR;
return false;
}
}
else if (status == TCAM_PIPELINE_STOPPED)
{
stop_playing();
}
return true;
}
TCAM_PIPELINE_STATUS PipelineManager::get_status () const
{
return status;
}
bool PipelineManager::destroyPipeline ()
{
set_status(TCAM_PIPELINE_STOPPED);
source = nullptr;
sink = nullptr;
return true;
}
bool PipelineManager::setSource (std::shared_ptr<DeviceInterface> device)
{
if (status == TCAM_PIPELINE_PLAYING || status == TCAM_PIPELINE_PAUSED)
{
return false;
}
device_properties = device->getProperties();
available_input_formats = device->get_available_video_formats();
tcam_log(TCAM_LOG_DEBUG, "Received %zu formats.", available_input_formats.size());
distributeProperties();
this->source = std::make_shared<ImageSource>();
source->setSink(shared_from_this());
source->setDevice(device);
for (const auto& f : available_filter)
{
auto p = f->getFilterProperties();
if (!p.empty())
{
filter_properties.insert(filter_properties.end(), p.begin(), p.end());
}
}
available_output_formats = available_input_formats;
if (available_output_formats.empty())
{
tcam_log(TCAM_LOG_ERROR, "No output formats available.");
return false;
}
return true;
}
std::shared_ptr<ImageSource> PipelineManager::getSource ()
{
return source;
}
bool PipelineManager::setSink (std::shared_ptr<SinkInterface> s)
{
if (status == TCAM_PIPELINE_PLAYING || status == TCAM_PIPELINE_PAUSED)
{
return false;
}
this->sink = s;
this->sink->set_source(shared_from_this());
return true;
}
std::shared_ptr<SinkInterface> PipelineManager::getSink ()
{
return sink;
}
void PipelineManager::distributeProperties ()
{
for (auto& f : available_filter)
{
f->setDeviceProperties(device_properties);
}
}
static bool isFilterApplicable (uint32_t fourcc,
const std::vector<uint32_t>& vec)
{
if (std::find(vec.begin(), vec.end(), fourcc) == vec.end())
{
return false;
}
return true;
}
void PipelineManager::create_input_format (uint32_t fourcc)
{
input_format = output_format;
input_format.set_fourcc(fourcc);
}
std::vector<uint32_t> PipelineManager::getDeviceFourcc ()
{
// for easy usage we create a vector<fourcc> for avail. inputs
std::vector<uint32_t> device_fourcc;
for (const auto& v : available_input_formats)
{
tcam_log(TCAM_LOG_DEBUG,
"Found device fourcc '%s' - %d",
fourcc2description(v.get_fourcc()),
v.get_fourcc());
device_fourcc.push_back(v.get_fourcc());
}
return device_fourcc;
}
bool PipelineManager::set_source_status (TCAM_PIPELINE_STATUS status)
{
if (source == nullptr)
{
tcam_log(TCAM_LOG_ERROR, "Source is not defined");
return false;
}
if (!source->set_status(status))
{
tcam_log(TCAM_LOG_ERROR, "Source did not accept status change");
return false;
}
return true;
}
bool PipelineManager::set_sink_status (TCAM_PIPELINE_STATUS status)
{
if (sink == nullptr)
{
tcam_log(TCAM_LOG_WARNING, "Sink is not defined.");
return false;
}
if (!sink->set_status(status))
{
tcam_log(TCAM_LOG_ERROR, "Sink spewed error");
return false;
}
return true;
}
bool PipelineManager::validate_pipeline ()
{
// check if pipeline is valid
if (source.get() == nullptr || sink.get() == nullptr)
{
return false;
}
// check source format
auto in_format = source->getVideoFormat();
if (in_format != this->input_format)
{
tcam_log(TCAM_LOG_DEBUG,
"Video format in source does not match pipeline: '%s' != '%s'",
in_format.to_string().c_str(),
input_format.to_string().c_str());
return false;
}
else
{
tcam_log(TCAM_LOG_DEBUG,
"Starting pipeline with format: '%s'",
in_format.to_string().c_str());
}
VideoFormat in;
VideoFormat out;
for (auto f : filter_pipeline)
{
f->getVideoFormat(in, out);
if (in != in_format)
{
tcam_log(TCAM_LOG_ERROR,
"Ingoing video format for filter %s is not compatible with previous element. '%s' != '%s'",
f->getDescription().name.c_str(),
in_format.to_string().c_str(),
in.to_string().c_str());
return false;
}
else
{
tcam_log(TCAM_LOG_DEBUG, "Filter %s connected to pipeline -- %s",
f->getDescription().name.c_str(),
out.to_string().c_str());
// save output for next comparison
in_format = out;
}
}
if (in_format != this->output_format)
{
tcam_log(TCAM_LOG_ERROR, "Video format in sink does not match pipeline '%s' != '%s'",
in_format.to_string().c_str(),
output_format.to_string().c_str());
return false;
}
return true;
}
bool PipelineManager::create_conversion_pipeline ()
{
if (source.get() == nullptr || sink.get() == nullptr)
{
return false;
}
auto device_fourcc = getDeviceFourcc();
create_input_format(output_format.get_fourcc());
for (auto f : available_filter)
{
std::string s = f->getDescription().name;
if (f->getDescription().type == FILTER_TYPE_CONVERSION)
{
if (isFilterApplicable(output_format.get_fourcc(), f->getDescription().output_fourcc))
{
bool filter_valid = false;
uint32_t fourcc_to_use = 0;
for (const auto& cc : device_fourcc)
{
if (isFilterApplicable(cc, f->getDescription().input_fourcc))
{
filter_valid = true;
fourcc_to_use = cc;
break;
}
}
// set device format to use correct fourcc
create_input_format(fourcc_to_use);
if (filter_valid)
{
if (f->setVideoFormat(input_format, output_format))
{
tcam_log(TCAM_LOG_DEBUG,
"Added filter \"%s\" to pipeline",
s.c_str());
filter_pipeline.push_back(f);
}
else
{
tcam_log(TCAM_LOG_DEBUG,
"Filter %s did not accept format settings",
s.c_str());
}
}
else
{
tcam_log(TCAM_LOG_DEBUG, "Filter %s does not use the device output formats.", s.c_str());
}
}
else
{
tcam_log(TCAM_LOG_DEBUG, "Filter %s is not applicable", s.c_str());
}
}
}
return true;
}
bool PipelineManager::add_interpretation_filter ()
{
// if a valid pipeline can be created insert additional filter (e.g. autoexposure)
// interpretations should be done as early as possible in the pipeline
for (auto& f : available_filter)
{
if (f->getDescription().type == FILTER_TYPE_INTERPRET)
{
std::string s = f->getDescription().name;
// applicable to sink
bool all_formats = false;
if (f->getDescription().input_fourcc.size() == 1)
{
if (f->getDescription().input_fourcc.at(0) == 0)
{
all_formats = true;
}
}
if (all_formats ||isFilterApplicable(input_format.get_fourcc(), f->getDescription().input_fourcc))
{
tcam_log(TCAM_LOG_DEBUG, "Adding filter '%s' after source", s.c_str());
f->setVideoFormat(input_format, input_format);
filter_pipeline.insert(filter_pipeline.begin(), f);
continue;
}
else
{
tcam_log(TCAM_LOG_DEBUG, "Filter '%s' not usable after source", s.c_str());
}
if (f->setVideoFormat(input_format, input_format))
{
continue;
}
}
}
return true;
}
bool PipelineManager::allocate_conversion_buffer ()
{
pipeline_buffer.clear();
for (int i = 0; i < 5; ++i)
{
tcam_image_buffer b = {};
b.pitch = output_format.get_size().width * img::get_bits_per_pixel(output_format.get_fourcc()) / 8;
b.length = b.pitch * output_format.get_size().height;
b.pData = (unsigned char*)malloc(b.length);
b.format.fourcc = output_format.get_fourcc();
b.format.width = output_format.get_size().width;
b.format.height = output_format.get_size().height;
b.format.framerate = output_format.get_framerate();
this->pipeline_buffer.push_back(std::make_shared<MemoryBuffer>(b));
}
current_ppl_buffer = 0;
return true;
}
bool PipelineManager::create_pipeline ()
{
if (source.get() == nullptr || sink.get() == nullptr)
{
return false;
}
// assure everything is in a defined state
filter_pipeline.clear();
if (!create_conversion_pipeline())
{
tcam_log(TCAM_LOG_ERROR, "Unable to determine conversion pipeline.");
return false;
}
if (!source->setVideoFormat(input_format))
{
tcam_log(TCAM_LOG_ERROR, "Unable to set video format in source.");
return false;
}
if (!sink->setVideoFormat(output_format))
{
tcam_log(TCAM_LOG_ERROR, "Unable to set video format in sink.");
return false;
}
if (!source->set_buffer_collection(sink->get_buffer_collection()))
{
tcam_log(TCAM_LOG_ERROR, "Unable to set buffer collection.");
return false;
}
tcam_log(TCAM_LOG_INFO, "Pipeline creation successful.");
std::string ppl = "source -> ";
for (const auto& f : filter_pipeline)
{
ppl += f->getDescription().name;
ppl += " -> ";
}
ppl += " sink";
tcam_log(TCAM_LOG_INFO, "%s" , ppl.c_str());
return true;
}
bool PipelineManager::start_playing ()
{
if (!set_sink_status(TCAM_PIPELINE_PLAYING))
{
tcam_log(TCAM_LOG_ERROR, "Sink refused to change to state PLAYING");
goto error;
}
if (!set_source_status(TCAM_PIPELINE_PLAYING))
{
tcam_log(TCAM_LOG_ERROR, "Source refused to change to state PLAYING");
goto error;
}
status = TCAM_PIPELINE_PLAYING;
return true;
error:
stop_playing();
return false;
}
bool PipelineManager::stop_playing ()
{
status = TCAM_PIPELINE_STOPPED;
if (!set_source_status(TCAM_PIPELINE_STOPPED))
{
tcam_log(TCAM_LOG_ERROR, "Source refused to change to state STOP");
return false;
}
for (auto& f : filter_pipeline)
{
if (!f->setStatus(TCAM_PIPELINE_STOPPED))
{
tcam_log(TCAM_LOG_ERROR,
"Filter %s refused to change to state STOP",
f->getDescription().name.c_str());
return false;
}
}
set_sink_status(TCAM_PIPELINE_STOPPED);
//destroyPipeline();
return true;
}
void PipelineManager::push_image (std::shared_ptr<MemoryBuffer> buffer)
{
if (status == TCAM_PIPELINE_STOPPED)
{
return;
}
auto& current_buffer = buffer;
for (auto& f : filter_pipeline)
{
if (f->getDescription().type == FILTER_TYPE_INTERPRET)
{
f->apply(current_buffer);
}
else if (f->getDescription().type == FILTER_TYPE_CONVERSION)
{
auto next_buffer = pipeline_buffer.at(current_ppl_buffer);
next_buffer->set_statistics(current_buffer->get_statistics());
f->transform(*current_buffer, *next_buffer);
current_buffer = next_buffer;
current_ppl_buffer++;
if (current_ppl_buffer == pipeline_buffer.size())
current_ppl_buffer = 0;
}
}
if (sink != nullptr)
{
sink->push_image(current_buffer);
}
else
{
tcam_log(TCAM_LOG_ERROR, "Sink is NULL");
}
}
void PipelineManager::requeue_buffer (std::shared_ptr<MemoryBuffer> buffer)
{
if (source)
{
source->requeue_buffer(buffer);
}
}
std::vector<std::shared_ptr<MemoryBuffer>> PipelineManager::get_buffer_collection ()
{
return std::vector<std::shared_ptr<MemoryBuffer>>();
}
| [
"[email protected]"
] | |
af3ace7b92c73c5c73d47f92ebb17e875b83829b | fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd | /net/quic/core/frames/quic_padding_frame.h | 93fb990c451570b9d9ba6418ee8b116de20dd758 | [
"BSD-3-Clause"
] | permissive | wzyy2/chromium-browser | 2644b0daf58f8b3caee8a6c09a2b448b2dfe059c | eb905f00a0f7e141e8d6c89be8fb26192a88c4b7 | refs/heads/master | 2022-11-23T20:25:08.120045 | 2018-01-16T06:41:26 | 2018-01-16T06:41:26 | 117,618,467 | 3 | 2 | BSD-3-Clause | 2022-11-20T22:03:57 | 2018-01-16T02:09:10 | null | UTF-8 | C++ | false | false | 939 | h | // Copyright (c) 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_QUIC_CORE_FRAMES_QUIC_PADDING_FRAME_H_
#define NET_QUIC_CORE_FRAMES_QUIC_PADDING_FRAME_H_
#include <cstdint>
#include <ostream>
#include "net/quic/platform/api/quic_export.h"
namespace net {
// A padding frame contains no payload.
struct QUIC_EXPORT_PRIVATE QuicPaddingFrame {
QuicPaddingFrame() : num_padding_bytes(-1) {}
explicit QuicPaddingFrame(int num_padding_bytes)
: num_padding_bytes(num_padding_bytes) {}
friend QUIC_EXPORT_PRIVATE std::ostream& operator<<(
std::ostream& os,
const QuicPaddingFrame& s);
// -1: full padding to the end of a max-sized packet
// otherwise: only pad up to num_padding_bytes bytes
int num_padding_bytes;
};
} // namespace net
#endif // NET_QUIC_CORE_FRAMES_QUIC_PADDING_FRAME_H_
| [
"[email protected]"
] | |
4b523e03fdc8b15eaa38ac658e5c8c693a1bf0ad | 63fbcf1d489fad90573306b0bb73cae3c0182a98 | /Common/Code/TypeVisualization.hpp | 9707a3802a8ce6171a1548326d8fef992880f38e | [
"MIT"
] | permissive | jamiefang/internetmap | 2b5515696329182ceeddf46058732b8c409ba77e | 13bf01e8e1fde8db64ce8fd417a1c907783100ee | refs/heads/master | 2020-09-12T15:40:53.628635 | 2019-03-01T23:31:31 | 2019-03-01T23:31:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 635 | hpp | //
// TypeVisualization.h
// InternetMap
//
// Created by Nigel Brooke on 2013-01-30.
// Copyright (c) 2013 Peer1. All rights reserved.
//
#ifndef __InternetMap__TypeVisualization__
#define __InternetMap__TypeVisualization__
#include "DefaultVisualization.hpp"
class TypeVisualization : public DefaultVisualization {
public:
TypeVisualization(const std::string& name, int typeToHighlight);
virtual Color nodeColor(NodePointer node);
virtual std::string name(void) { return _name; }
private:
int _typeToHighlight;
std::string _name;
};
#endif /* defined(__InternetMap__TypeVisualization__) */
| [
"[email protected]"
] | |
cb17e88be81c3fe1c074988f3d824da59f56e6bf | 0428c3b8086f12ebbc6de7967ee4437934e2146d | /misc/src/xml_parser.cpp | 5ed1f917b536fe62ce6454a7b95e1644c15c5a0a | [] | no_license | cornway/stm32f4-dcmi-probe | e5cf112f83b09ea0d4af23660c12e78b101504e6 | 9cc677bdb092949d1212ec1fc831b7db3e485fbd | refs/heads/master | 2020-04-28T03:16:52.112141 | 2019-03-11T05:23:51 | 2019-03-11T05:23:51 | 174,930,315 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 101 | cpp | #include "xml_parser.h"
/*
__weak void * operator new (uint32_t size)
{
return (void *)0;
}
*/ | [
"[email protected]"
] | |
dacc4d59b7a4da1b448c053aa83a016c632f9baa | 1e987bd8b8be0dc1c139fa6bf92e8229eb51da27 | /maker/arduino/interface/digital_value_hardware.cc | efd17cd26b4d3fbfa6a3ceda528374ff7aa1c58d | [] | no_license | tszdanger/phd | c97091b4f1d7712a836f0c8e3c6f819d53bd0dd5 | aab7f16bd1f3546f81e349fc6e2325fb17beb851 | refs/heads/master | 2023-01-01T00:54:20.136122 | 2020-10-21T18:07:42 | 2020-10-21T18:09:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 267 | cc | #include <Arduino.h>
#include <Arduino_interface_digital_value.h>
namespace arduino {
/* static */ DigitalValue DigitalValue::High() { return DigitalValue(HIGH); }
/* static */ DigitalValue DigitalValue::Low() { return DigitalValue(LOW); }
} // namespace arduino
| [
"[email protected]"
] | |
5385d4c596efe1410a4e9fe0853e710b39b0b0f4 | ce5d5aa995e61c1df2c303e003ce1b882680d9a4 | /vm.cpp | 852feb02deca12c038f64d0669d447b86b71707e | [] | no_license | matiTechno/ic | 770ccbe1855a915124f64a34086a209b27809320 | 0312a29eda1ebef6ef70c1a6e527c06afbe6528e | refs/heads/master | 2020-09-08T17:59:22.247070 | 2020-02-03T15:28:59 | 2020-02-03T15:28:59 | 221,203,143 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,667 | cpp | #include "ic_impl.h"
#define IC_STACK_SIZE (1024 * 1024)
void ic_vm_init(ic_vm& vm)
{
vm.stack = (ic_data*)malloc(IC_STACK_SIZE * sizeof(ic_data));
}
void ic_vm_free(ic_vm& vm)
{
free(vm.stack);
}
void ic_vm::push()
{
++sp;
assert(sp <= stack + IC_STACK_SIZE);
}
void ic_vm::push_many(int size)
{
sp += size;
assert(sp <= stack + IC_STACK_SIZE);
}
ic_data ic_vm::pop()
{
--sp;
return *sp;
}
void ic_vm::pop_many(int size)
{
sp -= size;
}
ic_data& ic_vm::top()
{
return *(sp - 1);
}
int ic_vm_run(ic_vm& _vm, ic_program& program)
{
ic_vm vm = _vm; // 20% perf gain in visual studio; but there is no gain if a parameter is passed by value, why?
assert(bytes_to_data_size(program.global_data_byte_size) <= IC_STACK_SIZE);
memcpy(vm.stack, program.bytecode, program.strings_byte_size);
// set global non-string data to 0
memset(vm.stack + program.strings_byte_size, 0, program.global_data_byte_size - program.strings_byte_size);
vm.sp = vm.stack + bytes_to_data_size(program.global_data_byte_size);
vm.push_many(3); // main() return value, bp, ip
vm.top().pointer = nullptr; // set a return address, see IC_OPC_RETURN for an explanation
vm.bp = vm.sp;
vm.ip = program.bytecode + program.strings_byte_size;
for(;;)
{
ic_opcode opcode = (ic_opcode)*vm.ip;
++vm.ip;
switch (opcode)
{
case IC_OPC_PUSH_S8:
vm.push();
vm.top().s8 = *(char*)vm.ip;
++vm.ip;
break;
case IC_OPC_PUSH_S32:
vm.push();
vm.top().s32 = read_int(&vm.ip);
break;
case IC_OPC_PUSH_F32:
vm.push();
vm.top().f32 = read_float(&vm.ip);
break;
case IC_OPC_PUSH_F64:
vm.push();
vm.top().f64 = read_double(&vm.ip);
break;
case IC_OPC_PUSH_NULLPTR:
{
vm.push();
vm.top().pointer = nullptr;
break;
}
case IC_OPC_PUSH:
{
vm.push();
break;
}
case IC_OPC_PUSH_MANY:
{
vm.push_many(read_int(&vm.ip));
break;
}
case IC_OPC_POP:
{
vm.pop();
break;
}
case IC_OPC_POP_MANY:
{
int size = read_int(&vm.ip);
vm.pop_many(size);
break;
}
case IC_OPC_SWAP:
{
ic_data tmp = *(vm.sp - 2);
*(vm.sp - 2) = vm.top();
vm.top() = tmp;
break;
}
case IC_OPC_MEMMOVE:
{
void* dst = (char*)vm.sp - read_int(&vm.ip);
void* src = (char*)vm.sp - read_int(&vm.ip);
int byte_size = read_int(&vm.ip);
memmove(dst, src, byte_size);
break;
}
case IC_OPC_CLONE:
{
vm.push();
vm.top() = *(vm.sp - 2);
break;
}
case IC_OPC_CALL:
{
int idx = read_int(&vm.ip);
vm.push();
vm.top().pointer = vm.bp;
vm.push();
vm.top().pointer = vm.ip;
vm.bp = vm.sp;
vm.ip = program.bytecode + idx;
break;
}
case IC_OPC_CALL_HOST:
{
int idx = read_int(&vm.ip);
ic_host_function& fun = program.host_functions[idx];
ic_data* argv = vm.sp - fun.param_size;
ic_data* retv = argv - fun.return_size;
fun.callback(argv, retv, fun.host_data);
break;
}
case IC_OPC_RETURN:
{
vm.sp = vm.bp;
vm.ip = (unsigned char*)vm.pop().pointer;
vm.bp = (ic_data*)vm.pop().pointer;
if (!vm.ip)
return vm.top().s32;
break;
}
case IC_OPC_JUMP_TRUE:
{
int idx = read_int(&vm.ip);
if(vm.pop().s8)
vm.ip = program.bytecode + idx;
break;
}
case IC_OPC_JUMP_FALSE:
{
int idx = read_int(&vm.ip);
if(!vm.pop().s8)
vm.ip = program.bytecode + idx;
break;
}
case IC_OPC_JUMP:
{
int idx = read_int(&vm.ip);
vm.ip = program.bytecode + idx;
break;
}
case IC_LOGICAL_NOT:
{
vm.top().s8 = !vm.top().s8;
break;
}
case IC_OPC_ADDRESS:
{
int byte_offset = read_int(&vm.ip);
vm.push();
vm.top().pointer = (char*)vm.bp + byte_offset;
break;
}
case IC_OPC_ADDRESS_GLOBAL:
{
int byte_offset = read_int(&vm.ip);
vm.push();
vm.top().pointer = (char*)vm.stack + byte_offset;
break;
}
case IC_OPC_STORE_1:
{
void* ptr = vm.pop().pointer;
*(char*)ptr = vm.top().s8;
break;
}
case IC_OPC_STORE_4:
{
void* ptr = vm.pop().pointer;
*(int*)ptr = vm.top().s32;
break;
}
case IC_OPC_STORE_8:
{
void* ptr = vm.pop().pointer;
*(double*)ptr = vm.top().f64;
break;
}
case IC_OPC_STORE_STRUCT:
{
void* dst = vm.pop().pointer;
int byte_size = read_int(&vm.ip);
int data_size = bytes_to_data_size(byte_size);
memcpy(dst, vm.sp - data_size, byte_size);
break;
}
case IC_OPC_LOAD_1:
{
void* ptr = vm.top().pointer;
vm.top().s8 = *(char*)ptr;
break;
}
case IC_OPC_LOAD_4:
{
void* ptr = vm.top().pointer;
vm.top().s32 = *(int*)ptr;
break;
}
case IC_OPC_LOAD_8:
{
void* ptr = vm.top().pointer;
vm.top().f64 = *(double*)ptr;
break;
}
case IC_OPC_LOAD_STRUCT:
{
void* ptr = vm.pop().pointer;
int byte_size = read_int(&vm.ip);
int data_size = bytes_to_data_size(byte_size);
vm.push_many(data_size);
memcpy(vm.sp - data_size, ptr, byte_size);
break;
}
case IC_OPC_COMPARE_E_S32:
{
int rhs = vm.pop().s32;
vm.top().s8 = vm.top().s32 == rhs;
break;
}
case IC_OPC_COMPARE_NE_S32:
{
int rhs = vm.pop().s32;
vm.top().s8 = vm.top().s32 != rhs;
break;
}
case IC_OPC_COMPARE_G_S32:
{
int rhs = vm.pop().s32;
vm.top().s8 = vm.top().s32 > rhs;
break;
}
case IC_OPC_COMPARE_GE_S32:
{
int rhs = vm.pop().s32;
vm.top().s8 = vm.top().s32 >= rhs;
break;
}
case IC_OPC_COMPARE_L_S32:
{
int rhs = vm.pop().s32;
vm.top().s8 = vm.top().s32 < rhs;
break;
}
case IC_OPC_COMPARE_LE_S32:
{
int rhs = vm.pop().s32;
vm.top().s8 = vm.top().s32 <= rhs;
break;
}
case IC_OPC_NEGATE_S32:
{
vm.top().s32 = -vm.top().s32;
break;
}
case IC_OPC_ADD_S32:
{
int rhs = vm.pop().s32;
vm.top().s32 += rhs;
break;
}
case IC_OPC_SUB_S32:
{
int rhs = vm.pop().s32;
vm.top().s32 -= rhs;
break;
}
case IC_OPC_MUL_S32:
{
int rhs = vm.pop().s32;
vm.top().s32 *= rhs;
break;
}
case IC_OPC_DIV_S32:
{
int rhs = vm.pop().s32;
vm.top().s32 /= rhs;
break;
}
case IC_OPC_MODULO_S32:
{
int rhs = vm.pop().s32;
vm.top().s32 = vm.top().s32 % rhs;
break;
}
case IC_OPC_COMPARE_E_F32:
{
float rhs = vm.pop().f32;
vm.top().s8 = vm.top().f32 == rhs;
break;
}
case IC_OPC_COMPARE_NE_F32:
{
float rhs = vm.pop().f32;
vm.top().s8 = vm.top().f32 != rhs;
break;
}
case IC_OPC_COMPARE_G_F32:
{
float rhs = vm.pop().f32;
vm.top().s8 = vm.top().f32 > rhs;
break;
}
case IC_OPC_COMPARE_GE_F32:
{
float rhs = vm.pop().f32;
vm.top().s8 = vm.top().f32 >= rhs;
break;
}
case IC_OPC_COMPARE_L_F32:
{
float rhs = vm.pop().f32;
vm.top().s8 = vm.top().f32 < rhs;
break;
}
case IC_OPC_COMPARE_LE_F32:
{
float rhs = vm.pop().f32;
vm.top().s8 = vm.top().f32 <= rhs;
break;
}
case IC_OPC_NEGATE_F32:
{
vm.top().f32 = -vm.top().f32;
break;
}
case IC_OPC_ADD_F32:
{
float rhs = vm.pop().f32;
vm.top().f32 += rhs;
break;
}
case IC_OPC_SUB_F32:
{
float rhs = vm.pop().f32;
vm.top().f32 -= rhs;
break;
}
case IC_OPC_MUL_F32:
{
float rhs = vm.pop().f32;
vm.top().f32 *= rhs;
break;
}
case IC_OPC_DIV_F32:
{
float rhs = vm.pop().f32;
vm.top().f32 /= rhs;
break;
}
case IC_OPC_COMPARE_E_F64:
{
double rhs = vm.pop().f64;
vm.top().s8 = vm.top().f64 == rhs;
break;
}
case IC_OPC_COMPARE_NE_F64:
{
double rhs = vm.pop().f64;
vm.top().s8 = vm.top().f64 != rhs;
break;
}
case IC_OPC_COMPARE_G_F64:
{
double rhs = vm.pop().f64;
vm.top().s8 = vm.top().f64 > rhs;
break;
}
case IC_OPC_COMPARE_GE_F64:
{
double rhs = vm.pop().f64;
vm.top().s8 = vm.top().f64 >= rhs;
break;
}
case IC_OPC_COMPARE_L_F64:
{
double rhs = vm.pop().f64;
vm.top().s8 = vm.top().f64 < rhs;
break;
}
case IC_OPC_COMPARE_LE_F64:
{
double rhs = vm.pop().f64;
vm.top().s8 = vm.top().f64 <= rhs;
break;
}
case IC_OPC_NEGATE_F64:
{
vm.top().f64 = -vm.top().f64;
break;
}
case IC_OPC_ADD_F64:
{
double rhs = vm.pop().f64;
vm.top().f64 += rhs;
break;
}
case IC_OPC_SUB_F64:
{
double rhs = vm.pop().f64;
vm.top().f64 -= rhs;
break;
}
case IC_OPC_MUL_F64:
{
double rhs = vm.pop().f64;
vm.top().f64 *= rhs;
break;
}
case IC_OPC_DIV_F64:
{
double rhs = vm.pop().f64;
vm.top().f64 /= rhs;
break;
}
case IC_OPC_COMPARE_E_PTR:
{
void* rhs = vm.pop().pointer;
vm.top().s8 = vm.top().pointer == rhs;
break;
}
case IC_OPC_COMPARE_NE_PTR:
{
void* rhs = vm.pop().pointer;
vm.top().s8 = vm.top().pointer != rhs;
break;
}
case IC_OPC_COMPARE_G_PTR:
{
void* rhs = vm.pop().pointer;
vm.top().s8 = vm.top().pointer > rhs;
break;
}
case IC_OPC_COMPARE_GE_PTR:
{
void* rhs = vm.pop().pointer;
vm.top().s8 = vm.top().pointer >= rhs;
break;
}
case IC_OPC_COMPARE_L_PTR:
{
void* rhs = vm.pop().pointer;
vm.top().s8 = vm.top().pointer < rhs;
break;
}
case IC_OPC_COMPARE_LE_PTR:
{
void* rhs = vm.pop().pointer;
vm.top().s8 = vm.top().pointer <= rhs;
break;
}
case IC_OPC_SUB_PTR_PTR:
{
int type_byte_size = read_int(&vm.ip);
assert(type_byte_size);
void* rhs = vm.pop().pointer;
vm.top().s32 = ((char*)vm.top().pointer - (char*)rhs) / type_byte_size;
break;
}
case IC_OPC_ADD_PTR_S32:
{
int type_byte_size = read_int(&vm.ip);
assert(type_byte_size);
int bytes = vm.pop().s32 * type_byte_size;
vm.top().pointer = (char*)vm.top().pointer + bytes;
break;
}
case IC_OPC_SUB_PTR_S32:
{
int type_byte_size = read_int(&vm.ip);
assert(type_byte_size);
int bytes = vm.pop().s32 * type_byte_size;
vm.top().pointer = (char*)vm.top().pointer - bytes;
break;
}
case IC_OPC_B_S8:
vm.top().s8 = (bool)vm.top().s8;
break;
case IC_OPC_B_U8:
vm.top().s8 = (bool)vm.top().u8;
break;
case IC_OPC_B_S32:
vm.top().s8 = (bool)vm.top().s32;
break;
case IC_OPC_B_F32:
vm.top().s8 = (bool)vm.top().f32;
break;
case IC_OPC_B_F64:
vm.top().s8 = (bool)vm.top().f64;
break;
case IC_OPC_B_PTR:
vm.top().s8 = (bool)vm.top().pointer;
break;
case IC_OPC_S8_U8:
vm.top().s8 = vm.top().u8;
break;
case IC_OPC_S8_S32:
vm.top().s8 = vm.top().s32;
break;
case IC_OPC_S8_F32:
vm.top().s8 = vm.top().f32;
break;
case IC_OPC_S8_F64:
vm.top().s8 = vm.top().f64;
break;
case IC_OPC_U8_S8:
vm.top().u8 = vm.top().s8;
break;
case IC_OPC_U8_S32:
vm.top().u8 = vm.top().s32;
break;
case IC_OPC_U8_F32:
vm.top().u8 = vm.top().f32;
break;
case IC_OPC_U8_F64:
vm.top().u8 = vm.top().f64;
break;
case IC_OPC_S32_S8:
vm.top().s32 = vm.top().s8;
break;
case IC_OPC_S32_U8:
vm.top().s32 = vm.top().u8;
break;
case IC_OPC_S32_F32:
vm.top().s32 = vm.top().f32;
break;
case IC_OPC_S32_F64:
vm.top().s32 = vm.top().f64;
break;
case IC_OPC_F32_S8:
vm.top().f32 = vm.top().s8;
break;
case IC_OPC_F32_U8:
vm.top().f32 = vm.top().u8;
break;
case IC_OPC_F32_S32:
vm.top().f32 = vm.top().s32;
break;
case IC_OPC_F32_F64:
vm.top().f32 = vm.top().f64;
break;
case IC_OPC_F64_S8:
vm.top().f64 = vm.top().s8;
break;
case IC_OPC_F64_U8:
vm.top().f64 = vm.top().u8;
break;
case IC_OPC_F64_S32:
vm.top().f64 = vm.top().s32;
break;
case IC_OPC_F64_F32:
vm.top().f64 = vm.top().f32;
break;
default:
assert(false);
}
} // while
}
| [
"[email protected]"
] | |
d512741b750eb3a4091a2c1903db422fac1fd307 | 4b1ee3b6b7a23ab029e59e1744ec2f441c648863 | /DEMCOMP/demcomp2/dem_comp2.cpp | 7c29f550325fe5ccb2260d10861794dbbd2ba00a | [] | no_license | JimFawcett/CppBasicDemos | aa4d489befa7e4b5b5454c913ab889a5376658e7 | 77652c070e7ffa58b008a8afac9f32dd92e30a4f | refs/heads/master | 2021-06-25T04:51:01.991278 | 2021-01-25T00:29:58 | 2021-01-25T00:29:58 | 195,317,448 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,066 | cpp | //////////////////////////////////////////////////////////////////
// DEM_COMP2.CPP - demonstrates composition //
// knows how to copy, assign, and destroy //
// uses inefficient copy ctor design //
//////////////////////////////////////////////////////////////////
#include <iostream>
using namespace std;
class composed {
public:
composed(void);
composed(const composed& b);
composed(int x);
virtual ~composed(void);
composed& operator= (const composed& b);
friend ostream& operator<<(ostream& ostrm, const composed& b);
private:
int data;
};
class composer {
public:
composer(void);
composer(const composer &a);
composer(int x1, int x2);
virtual ~composer(void);
composer& operator=(const composer& a);
friend ostream& operator<<(ostream& ostrm, const composer& a);
private:
composed in1;
composed in2;
};
//
//----< void constructor >-------------------------------------
composed::composed(void) {
cout << " composed void constructor called\n";
}
//----< copy constructor >-------------------------------------
composed::composed(const composed& b) : data(b.data) {
cout << " composed copy constructor called\n";
}
//----< promotion constructor >--------------------------------
composed::composed(int x) : data(x) {
cout << " composed(int) constructor called\n";
cout << " set data = " << data << "\n";
}
//----< destructor >-------------------------------------------
composed::~composed(void) {
cout << " composed destructor called\n";
}
//----< assignment >-------------------------------------------
composed& composed::operator= (const composed& b) {
if(this==&b) return *this;
cout << " composed operator= called\n";
data = b.data;
return *this;
}
//----< insertion >--------------------------------------------
ostream& operator<<(ostream& ostrm, const composed& b) {
ostrm << b.data; return ostrm;
}
//
//----< void constructor >-------------------------------------
composer::composer(void) {
cout << " composer void constructor called\n";
}
//----< copy constructor >-------------------------------------
// this copy method is not efficient - see dem_ag2b
composer::composer(const composer &a) {
cout << " composer copy constructor called\n";
in1 = a.in1;
in2 = a.in2;
}
//----< promotion constructor with initialization >------------
composer::composer(int size1, int size2) : in1(size1), in2(size2) {
cout << " composer(int,int) constructor called\n";
cout << " set in1 = " << in1 << endl;
cout << " set in2 = " << in2 << endl;
}
//----< destructor >-------------------------------------------
composer::~composer(void) {
cout << " composer destructor called\n";
}
//----< assignment >-------------------------------------------
composer& composer::operator=(const composer &a) {
if(this==&a) return *this;
cout << " composer operator= called\n";
in1 = a.in1;
in2 = a.in2;
return *this;
}
//----< annunciator >------------------------------------------
void message(char *s) {
cout << endl << s << " executable statement of main\n";
}
void main() { //----------------------------------------------
message("1st"); composed inner1;
message("2nd"); composed inner2 = inner1;
message("3rd"); inner1 = inner2;
message("4th"); composer outer1;
message("5th"); composer outer2(6,4);
message("6th"); composer outer3 = outer1;
message("7th"); outer3 = outer2;
message("no more");
}
//
// now, composer has a copy ctor, assignment oper, and a dtor
// - we see them being called in 6th statement, 7th
// statement, and in the destruction sequence
// one issue of note here:
// if you compare composer source code for copy ctor and
// annunciations you will see that when composer does a copy
// construction it's elements are first constructed with
// void ctor, then assigned with composed operator=()
// there is a better way - see dem_comp2b
| [
"[email protected]"
] | |
ee7eb2819d9253d0a6a866e184c7760e97b58bf0 | a4c4751cfc24db0824d2d9424b60261582b0b96c | /RU/Files/day2_6/mixer-snappyHexMesh/system/removeZones.topoSetDict | b8f8409059de7e283d99a5f2ac3cc44b6b9cd058 | [] | no_license | shubham2941/TwoDaysMeshingCourse | 02bbca556583e84d5e59a95ea8f98a2542945588 | 26fffa34a3721b952fbc9d38e5c9308d08201902 | refs/heads/master | 2020-06-13T02:20:20.923521 | 2016-01-05T16:31:48 | 2016-01-05T16:31:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 937 | toposetdict | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: dev |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class dictionary;
object topoSetDict;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
actions
(
{
name ami;
type cellZoneSet;
action remove;
}
);
// ************************************************************************* //
| [
"[email protected]"
] | |
0061815e53c872c96ecc1a235d0a7f83e960b8b6 | 019c446b2c8f8e902226851db1b31eb1e3c850d5 | /oneEngine/oneGame/source/after/terrain/system/MemoryManager.cpp | 739b22f92097c2357c04bf86676e6300f90e5eba | [
"FTL",
"BSD-3-Clause"
] | permissive | skarik/1Engine | cc9b6f7cf81903b75663353926a23224b81d1389 | 9f53b4cb19a6b8bb3bf2e3a4104c73614ffd4359 | refs/heads/master | 2023-09-04T23:12:50.706308 | 2023-08-29T05:28:21 | 2023-08-29T05:28:21 | 109,445,379 | 9 | 2 | BSD-3-Clause | 2021-08-30T06:48:27 | 2017-11-03T21:41:51 | C++ | UTF-8 | C++ | false | false | 5,706 | cpp |
#include "MemoryManager.h"
#include "core/settings/CGameSettings.h"
#include "after/terrain/data/Node.h"
#include <iostream>
#include <memory>
#include <thread>
//===============================================================================================//
// Manager settings
//===============================================================================================//
uint32_t Terrain::MemoryManager::MemorySize_Sidebuffer = sizeof(Terrain::terra_b) * 34*34*34;
uint32_t Terrain::MemoryManager::MemorySize_Payload = sizeof(Terrain::terra_b) * BLOCK_COUNT;
uint32_t Terrain::MemoryManager::MemorySize_Node = sizeof(Terrain::Node);
//===============================================================================================//
// Constructor and Destructor
//===============================================================================================//
Terrain::MemoryManager::MemoryManager ( void )
{
if ( !Init() )
{
printf( "Could not allocate enough memory for terrain. Currently at density %d.", CGameSettings::Active()->i_cl_ter_Range );
throw Core::OutOfMemoryException();
}
}
Terrain::MemoryManager::~MemoryManager( void )
{
Free();
}
//===============================================================================================//
// System Start and End
//===============================================================================================//
bool Terrain::MemoryManager::Init ( void )
{
//m_memoryMaxBlocks = (uint32_t)( 64 * 255 * pow(2,1+CGameSettings::Active()->i_cl_ter_Range) );
m_memoryMaxBlocks = (uint32_t)( 64 * pow(2,1+CGameSettings::Active()->i_cl_ter_Range) );
std::cout << " Block size: " << MemorySize_Payload << " with " << m_memoryMaxBlocks << " blocks." << std::endl;
std::cout << " Estimated size: " << ((MemorySize_Payload+1) * m_memoryMaxBlocks)/(1024*1024) << " MB" << std::endl;
try
{
// Terrain Memory Management
uint32_t blocks = m_memoryMaxBlocks;
// Attempt to allocate memory for the terrain
m_memoryData = new char [ blocks * MemorySize_Payload ];
memset( m_memoryData, 0, blocks * MemorySize_Payload );
// Allocate memory for the terra mem flags
m_memoryUsage = new char [ blocks ];
memset( m_memoryUsage, 0, blocks );
// Set the last eight blocks as used
for ( int i = 1; i <= 8; ++i ) {
m_memoryUsage[blocks-i] = 1;
}
}
catch ( std::bad_alloc )
{
return false;
}
return true;
}
void Terrain::MemoryManager::Free ( void )
{
delete [] m_memoryData;
m_memoryData = NULL;
delete [] m_memoryUsage;
m_memoryUsage = NULL;
}
//===============================================================================================//
// Memory Requests
//===============================================================================================//
Terrain::terra_b* Terrain::MemoryManager::NewDataBlock ( void )
//void Terrain::MemoryManager::NewDataBlock ( Terrain::Payload** block )
{
std::lock_guard<std::mutex> lock ( m_memoryLock );
uint32_t blocks = m_memoryMaxBlocks;
uint32_t normalized_index = 0;
// Find the first open index
while ( m_memoryUsage[normalized_index] != 0 )
++normalized_index;
if ( normalized_index >= blocks )
{
std::cout << "OH NO MY BOBA BALLS!" << std::endl;
throw Core::OutOfMemoryException();
}
// Get the new memory index
uint32_t index = normalized_index * MemorySize_Payload;
// Set the block to the new value
//(*block) = (subblock16*)(pTerraData + index);
//(*block) = (Terrain::Sector*)(&(m_memoryData[index])); // should be the same
//(*block) = new(&(m_memoryData[index])) Terrain::Sector; //should still work
terra_b* block = (terra_b*) &(m_memoryData[index]);
// Turn on flag
m_memoryUsage[normalized_index] = 1;
// Return allocated area
return block;
}
void Terrain::MemoryManager::FreeDataBlock ( terra_b* block )
{
std::lock_guard<std::mutex> lock ( m_memoryLock );
uint32_t blocks = m_memoryMaxBlocks;
uint32_t index = 0;
// Figure out the index of block based on the memory address
char* tblock = (char*)block;
while ( tblock != m_memoryData + index )
index += MemorySize_Payload;
// Get the index of the mem flag array
uint32_t normalized_index = index / MemorySize_Payload;
if ( normalized_index >= blocks )
exit(0);
// Turn off flag
m_memoryUsage[normalized_index] = 0;
}
//===============================================================================================//
// System State Query
//===============================================================================================//
Real Terrain::MemoryManager::GetMemoryUsage ( void )
{
std::lock_guard<std::mutex> lock ( m_memoryLock );
struct tBlockCounter {
char* m_memoryUsage;
uint32_t* count;
uint32_t start;
uint32_t end;
void operator () ( void ) {
for ( uint32_t i = start; i < end; ++i ) {
if ( m_memoryUsage[i] ) {
++(*count);
}
}
}
};
// Create 4 counters
uint32_t external_count[4];
tBlockCounter counters [4];
for ( uint i = 0; i < 4; ++i ) {
external_count[i] = 0;
counters[i].m_memoryUsage = m_memoryUsage;
counters[i].count = &(external_count[i]);
counters[i].start = i * (m_memoryMaxBlocks/4);
counters[i].end = (i+1) * (m_memoryMaxBlocks/4);
}
// And run the four counters on four separate threads
std::thread* threads[4];
for ( uint i = 0; i < 4; ++i ) {
threads[i] = new std::thread( counters[i] );
}
for ( uint i = 0; i < 4; ++i ) {
threads[i]->join();
delete threads[i];
}
// Count up the blocks the threads counted up
uint32_t usedBlocks = 0;
for ( uint i = 0; i < 4; ++i ) {
usedBlocks += external_count[i];
}
// Return the percentage of used blocks
return usedBlocks/((Real)(m_memoryMaxBlocks));
}
| [
"[email protected]"
] | |
ab4e53cdf74faf9c7fdce9f69bfb261d7a987072 | fea33fec45835f73155cba1b1ca8756115eafd50 | /minicern/zebra/bknmparq.inc | 095377719135b044e3b1b18094161049ce879b75 | [] | no_license | vmc-project/geant3 | f95a3e6451ec778d28962be8648af4d02a315f1e | 0feb951e5504e2677e4d9919d50ed4497f3fcabf | refs/heads/master | 2023-04-30T05:56:35.048796 | 2023-02-09T13:17:20 | 2023-02-09T13:17:20 | 84,311,188 | 8 | 11 | null | 2023-04-24T12:07:53 | 2017-03-08T11:03:56 | Fortran | UTF-8 | C++ | false | false | 497 | inc | *
* $Id$
*
* $Log: bknmparq.inc,v $
* Revision 1.1.1.1 2002/06/16 15:18:49 hristov
* Separate distribution of Geant3
*
* Revision 1.1.1.1 1999/05/18 15:55:27 fca
* AliRoot sources
*
* Revision 1.1.1.1 1996/03/06 10:46:56 mclareni
* Zebra
*
*
#ifndef CERNLIB_ZEBRA_BKNMPARQ_INC
#define CERNLIB_ZEBRA_BKNMPARQ_INC
*
* BANK NAME PARAMETERS (MZLIFT)
*
* bknmparq.inc
*
PARAMETER(NNMBKQ=5,MNMIDQ=1,MNMNLQ=MNMIDQ+1)
PARAMETER(MNMNSQ=MNMNLQ+1,MNMNDQ=MNMNSQ+1,MNMIOQ=MNMNDQ+1)
#endif
| [
"[email protected]"
] | |
55d86ad99cc08478834634f2d5d598b3a1473b0a | 04fee3ff94cde55400ee67352d16234bb5e62712 | /7.20/source/Stu-27-爆零Starlight/massage.cpp | 0da5cb840b091374ea29853f4b4f01a20428c598 | [] | no_license | zsq001/oi-code | 0bc09c839c9a27c7329c38e490c14bff0177b96e | 56f4bfed78fb96ac5d4da50ccc2775489166e47a | refs/heads/master | 2023-08-31T06:14:49.709105 | 2021-09-14T02:28:28 | 2021-09-14T02:28:28 | 218,049,685 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 418 | cpp | #include<bits/stdc++.h>
using namespace std;
int a1[10010],a2[10010];
int main(){
freopen("massage.in","r",stdin);
freopen("massage.out","w",stdout);
int n,q;
cin>>n>>q;
for(int i=1;i<=n;++i){
cin>>a1[i]>>a2[i];
}
if(n==3&&q==1) cout<<"20\n1033-1039-1049-1249-1279-5279-5179-8179\n20\n1373-3373-3343-3347-5347-5147-8147-8117-8017\n0\n1033";
else if(n==3&&q==0) cout<<"20\n20\n0";
return 0;
}
| [
"[email protected]"
] | |
cde57931fb89c42727a50a05b1eaa5b252e47a02 | 4c0a47abd546571c37e279c283738e825e1a4ac5 | /syncd/ServiceMethodTable.cpp | 2f5f5183510a1cf220039d0dfcbd2adfd917d109 | [
"Apache-2.0"
] | permissive | tonytitus/sonic-sairedis | 054167fe3eb69f1d8ed0fcccee4573b4e6ffa205 | 2347db590f3b1799eacedef7e1e7c9990cc11ca9 | refs/heads/master | 2021-07-18T13:17:48.497968 | 2020-07-31T17:22:34 | 2020-07-31T17:22:34 | 198,504,530 | 0 | 1 | NOASSERTION | 2019-07-23T20:35:35 | 2019-07-23T20:35:35 | null | UTF-8 | C++ | false | false | 2,622 | cpp | #include "ServiceMethodTable.h"
#include "swss/logger.h"
#include <utility>
using namespace syncd;
ServiceMethodTable::SlotBase::SlotBase(
_In_ sai_service_method_table_t smt):
m_handler(nullptr),
m_smt(smt)
{
SWSS_LOG_ENTER();
// empty
}
ServiceMethodTable::SlotBase::~SlotBase()
{
SWSS_LOG_ENTER();
// empty
}
void ServiceMethodTable::SlotBase::setHandler(
_In_ ServiceMethodTable* handler)
{
SWSS_LOG_ENTER();
m_handler = handler;
}
ServiceMethodTable* ServiceMethodTable::SlotBase::getHandler() const
{
SWSS_LOG_ENTER();
return m_handler;
}
const char* ServiceMethodTable::SlotBase::profileGetValue(
_In_ int context,
_In_ sai_switch_profile_id_t profile_id,
_In_ const char* variable)
{
SWSS_LOG_ENTER();
return m_slots.at(context)->m_handler->profileGetValue(profile_id, variable);
}
int ServiceMethodTable::SlotBase::profileGetNextValue(
_In_ int context,
_In_ sai_switch_profile_id_t profile_id,
_Out_ const char** variable,
_Out_ const char** value)
{
return m_slots.at(context)->m_handler->profileGetNextValue(profile_id, variable, value);
}
const sai_service_method_table_t& ServiceMethodTable::SlotBase::getServiceMethodTable() const
{
SWSS_LOG_ENTER();
return m_smt;
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Winline"
template<class B, template<size_t> class D, size_t... i>
constexpr auto declare_static(std::index_sequence<i...>)
{
SWSS_LOG_ENTER();
return std::array<B*, sizeof...(i)>{{new D<i>()...}};
}
template<class B, template<size_t> class D, size_t size>
constexpr auto declare_static()
{
SWSS_LOG_ENTER();
auto arr = declare_static<B,D>(std::make_index_sequence<size>{});
return std::vector<B*>{arr.begin(), arr.end()};
}
std::vector<ServiceMethodTable::SlotBase*> ServiceMethodTable::m_slots =
declare_static<ServiceMethodTable::SlotBase, ServiceMethodTable::Slot, 10>();
#pragma GCC diagnostic pop
ServiceMethodTable::ServiceMethodTable()
{
SWSS_LOG_ENTER();
for (auto& slot: m_slots)
{
if (slot->getHandler() == nullptr)
{
m_slot = slot;
m_slot->setHandler(this);
return;
}
}
SWSS_LOG_THROW("no more available slots, max slots: %zu", m_slots.size());
}
ServiceMethodTable::~ServiceMethodTable()
{
SWSS_LOG_ENTER();
m_slot->setHandler(nullptr);
}
const sai_service_method_table_t& ServiceMethodTable::getServiceMethodTable() const
{
SWSS_LOG_ENTER();
return m_slot->getServiceMethodTable();
}
| [
"[email protected]"
] | |
9f64f557bd36653ac5fc3079221d23f24052773f | 06f035b37775178a407866e8791b484b781bc114 | /MyEngine/BumpMapShaderClass.cpp | 9e9e22fa656cdb1193b53a57132749f5b2c3af8f | [] | no_license | yohan7979/ShaderSample | 0cea2904a1a66cb3a1ff1b004b4a8330dd1d1787 | 0a5e5b8dd97e5d06386760eda03db9cf75278fd5 | refs/heads/master | 2022-04-18T10:50:16.854497 | 2020-04-17T14:47:12 | 2020-04-17T14:47:12 | 256,537,389 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 9,026 | cpp | #include "BumpMapShaderClass.h"
BumpMapShaderClass::BumpMapShaderClass()
: m_matrixBuffer(nullptr)
, m_LightBuffer(nullptr)
, m_sampleState(nullptr)
{
}
BumpMapShaderClass::BumpMapShaderClass(const BumpMapShaderClass& other)
{
}
BumpMapShaderClass::~BumpMapShaderClass()
{
}
bool BumpMapShaderClass::Initialize(ID3D11Device* device, HWND hwnd)
{
bool result;
// Initialize the vertex and pixel shaders.
result = InitializeShader(device, hwnd, L"../MyEngine/Shader/bumpmap.vs", L"../MyEngine/Shader/bumpmap.ps",
"BumpMapVertexShader", "BumpMapPixelShader");
if (!result)
{
return false;
}
return true;
}
void BumpMapShaderClass::Shutdown()
{
ShutdownShader();
}
bool BumpMapShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, WCHAR* vsFilename, WCHAR* psFilename, const char* vsName, const char* psName)
{
Super::InitializeShader(device, hwnd, vsFilename, psFilename, vsName, psName);
D3D11_INPUT_ELEMENT_DESC polygonLayout[6];
polygonLayout[0].SemanticName = "POSITION";
polygonLayout[0].SemanticIndex = 0;
polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
polygonLayout[0].InputSlot = 0;
polygonLayout[0].AlignedByteOffset = 0;
polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[0].InstanceDataStepRate = 0;
polygonLayout[1].SemanticName = "TEXCOORD";
polygonLayout[1].SemanticIndex = 0;
polygonLayout[1].Format = DXGI_FORMAT_R32G32_FLOAT;
polygonLayout[1].InputSlot = 0;
polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[1].InstanceDataStepRate = 0;
polygonLayout[2].SemanticName = "NORMAL";
polygonLayout[2].SemanticIndex = 0;
polygonLayout[2].Format = DXGI_FORMAT_R32G32B32_FLOAT;
polygonLayout[2].InputSlot = 0;
polygonLayout[2].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
polygonLayout[2].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[2].InstanceDataStepRate = 0;
polygonLayout[3].SemanticName = "TANGENT";
polygonLayout[3].SemanticIndex = 0;
polygonLayout[3].Format = DXGI_FORMAT_R32G32B32_FLOAT;
polygonLayout[3].InputSlot = 0;
polygonLayout[3].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
polygonLayout[3].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[3].InstanceDataStepRate = 0;
polygonLayout[4].SemanticName = "BINORMAL";
polygonLayout[4].SemanticIndex = 0;
polygonLayout[4].Format = DXGI_FORMAT_R32G32B32_FLOAT;
polygonLayout[4].InputSlot = 0;
polygonLayout[4].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
polygonLayout[4].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[4].InstanceDataStepRate = 0;
polygonLayout[5].SemanticName = "TEXCOORD";
polygonLayout[5].SemanticIndex = 1;
polygonLayout[5].Format = DXGI_FORMAT_R32G32B32_FLOAT;
polygonLayout[5].InputSlot = 1;
polygonLayout[5].AlignedByteOffset = 0;
polygonLayout[5].InputSlotClass = D3D11_INPUT_PER_INSTANCE_DATA;
polygonLayout[5].InstanceDataStepRate = 1;
UINT numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]);
// 정점 입력 레이아웃 생성
if (FAILED(device->CreateInputLayout(polygonLayout, numElements, m_vertexShaderBuffer->GetBufferPointer(), m_vertexShaderBuffer->GetBufferSize(), &m_layout)))
{
return false;
}
if (m_vertexShaderBuffer)
{
m_vertexShaderBuffer->Release();
m_vertexShaderBuffer = nullptr;
}
if (m_pixelShaderBuffer)
{
m_pixelShaderBuffer->Release();
m_pixelShaderBuffer = nullptr;
}
// 상수 버퍼 생성
D3D11_BUFFER_DESC matrixBufferDesc;
matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType);
matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
matrixBufferDesc.MiscFlags = 0;
matrixBufferDesc.StructureByteStride = 0;
if (FAILED(device->CreateBuffer(&matrixBufferDesc, NULL, &m_matrixBuffer)))
{
return false;
}
// 샘플러 생성
D3D11_SAMPLER_DESC samplerDesc;
samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.MipLODBias = 0.f;
samplerDesc.MaxAnisotropy = 1;
samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
samplerDesc.BorderColor[0] = 0;
samplerDesc.BorderColor[1] = 0;
samplerDesc.BorderColor[2] = 0;
samplerDesc.BorderColor[3] = 0;
samplerDesc.MinLOD = 0;
samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
if (FAILED(device->CreateSamplerState(&samplerDesc, &m_sampleState)))
{
return false;
}
// 광원 상수 버퍼 생성
D3D11_BUFFER_DESC lightBufferDesc;
lightBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
lightBufferDesc.ByteWidth = sizeof(LightBufferType);
lightBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
lightBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
lightBufferDesc.MiscFlags = 0;
lightBufferDesc.StructureByteStride = 0;
if (FAILED(device->CreateBuffer(&lightBufferDesc, NULL, &m_LightBuffer)))
{
return false;
}
return true;
}
void BumpMapShaderClass::ShutdownShader()
{
Super::ShutdownShader();
if (m_matrixBuffer)
{
m_matrixBuffer->Release();
m_matrixBuffer = nullptr;
}
if (m_LightBuffer)
{
m_LightBuffer->Release();
m_LightBuffer = nullptr;
}
if (m_sampleState)
{
m_sampleState->Release();
m_sampleState = nullptr;
}
}
bool BumpMapShaderClass::Render(ID3D11DeviceContext* deviceContext, int vertexCount, int indexCount, int instanceCount, D3DXMATRIX worldMatrix, D3DXMATRIX viewMatrix, D3DXMATRIX projectionMatrix, ID3D11ShaderResourceView** textures, int textureCount, D3DXVECTOR3 lightDirection, D3DXVECTOR4 diffuseColor)
{
bool result;
// Set the shader parameters that it will use for rendering.
result = SetShaderParameters(deviceContext, worldMatrix, viewMatrix, projectionMatrix, textures, textureCount, lightDirection, diffuseColor);
if (!result)
{
return false;
}
// Now render the prepared buffers with the shader.
if (instanceCount > 0)
{
RenderShaderInstanced(deviceContext, vertexCount, instanceCount);
}
else
{
RenderShader(deviceContext, indexCount);
}
return true;
}
bool BumpMapShaderClass::SetShaderParameters(ID3D11DeviceContext* deviceContext, D3DXMATRIX worldMatrix, D3DXMATRIX viewMatrix, D3DXMATRIX projectionMatrix, ID3D11ShaderResourceView** textures, int textureCount, D3DXVECTOR3 lightDirection, D3DXVECTOR4 diffuseColor)
{
// 쉐이더에서 쓸 수 있게 행렬 전치
D3DXMatrixTranspose(&worldMatrix, &worldMatrix);
D3DXMatrixTranspose(&viewMatrix, &viewMatrix);
D3DXMatrixTranspose(&projectionMatrix, &projectionMatrix);
// 상수 버퍼에 쓸 수 있게 잠금
D3D11_MAPPED_SUBRESOURCE mappedResource;
if (FAILED(deviceContext->Map(m_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource)))
{
return false;
}
// 서브리소스를 통해 데이터 쓰기
MatrixBufferType* dataPtr = static_cast<MatrixBufferType*>(mappedResource.pData);
dataPtr->world = worldMatrix;
dataPtr->view = viewMatrix;
dataPtr->projection = projectionMatrix;
// 잠금 해제
deviceContext->Unmap(m_matrixBuffer, 0);
// 정점 쉐이더에 상수 버퍼 갱신
deviceContext->VSSetConstantBuffers(0, 1, &m_matrixBuffer);
// 픽셀 쉐이더에 텍스쳐 배열 세팅 (ShaderResourceView)
deviceContext->PSSetShaderResources(0, textureCount, textures);
// 광원 상수 버퍼 잠금
if (FAILED(deviceContext->Map(m_LightBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource)))
{
return false;
}
LightBufferType* dataPtr2 = static_cast<LightBufferType*>(mappedResource.pData);
dataPtr2->diffuseColor = diffuseColor;
dataPtr2->lightDirection = lightDirection;
// 픽셀 쉐이더에 상수 버퍼 갱신
deviceContext->Unmap(m_LightBuffer, 0);
deviceContext->PSSetConstantBuffers(0, 1, &m_LightBuffer);
return true;
}
void BumpMapShaderClass::RenderShader(ID3D11DeviceContext* deviceContext, int indexCount)
{
// Set the vertex input layout.
deviceContext->IASetInputLayout(m_layout);
// Set the vertex and pixel shaders that will be used to render this triangle.
deviceContext->VSSetShader(m_vertexShader, NULL, 0);
deviceContext->PSSetShader(m_pixelShader, NULL, 0);
// Set the sampler states in the pixel shader.
deviceContext->PSSetSamplers(0, 1, &m_sampleState);
// Render the triangle.
deviceContext->DrawIndexed(indexCount, 0, 0);
}
void BumpMapShaderClass::RenderShaderInstanced(ID3D11DeviceContext* deviceContext, int vertexCount, int instanceCount)
{
// Set the vertex input layout.
deviceContext->IASetInputLayout(m_layout);
// Set the vertex and pixel shaders that will be used to render this triangle.
deviceContext->VSSetShader(m_vertexShader, NULL, 0);
deviceContext->PSSetShader(m_pixelShader, NULL, 0);
// Set the sampler states in the pixel shader.
deviceContext->PSSetSamplers(0, 1, &m_sampleState);
// Render the triangle.
deviceContext->DrawInstanced(vertexCount, instanceCount, 0, 0);
} | [
"[email protected]"
] | |
41c99b4639b18f91d9acd054ec4d88da845add52 | 651bb470cf728abc1161da7dbee6099bff082ea3 | /chardefs.inc | b4081e271b453df628aaf1c29d85569081e68a74 | [] | no_license | glockwork/phMeter | 5678d5bb2478e39a5814eba6c63d65c4fce38637 | d037635390b26cbc4c511368cce6e2decc12a6ab | refs/heads/master | 2020-12-30T23:34:09.083709 | 2011-01-25T19:08:19 | 2011-01-25T19:08:19 | 37,402,549 | 0 | 1 | null | 2015-06-14T06:55:54 | 2015-06-14T06:55:54 | null | UTF-8 | C++ | false | false | 223 | inc |
; Character descriptor structure
.EQU CharCode = 0
.EQU CharWidth = 1
.EQU CharEntry = 2
; Character set descriptor structure
.EQU CharTable = 0
.EQU CharHeight = 2
.EQU CharDefaultWidth =3
| [
"[email protected]"
] | |
d8d1ad6f9cb5c5b3f1056d2a770fa81d4a84ad45 | cf4605896cec9cea2c868d131e4a095c05a4fd1e | /C++/Ch4-C++/Ch4-14-swap-def.cpp | e6ab3d148fa0aa67150ca23f85fd840cdd494aa3 | [] | no_license | alice2100chen/ourProgramming | 1e5a57a3acecb005f63802471d76dfb581f70c86 | a94818371ef86cf1eafaca22cf6cb451b0c50556 | refs/heads/master | 2020-04-20T00:31:50.823679 | 2020-01-06T14:26:49 | 2020-01-06T14:26:49 | 168,523,623 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 491 | cpp | #include <iostream>
using namespace std;
void swap(int a[], int i, int j){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
void print_array(int arr[], int arr_len){
for(int i = 0; i < arr_len; i++){
cout << arr[i] << " ";
}
cout << endl;
}
int main(){
int num_visitors[7] = {70, 10, 14, 7, 25, 30, 50}; // 索引0~6代表星期日到六
print_array(num_visitors, 7);
swap(num_visitors, 0, 6);
print_array(num_visitors, 7);
return 0;
}
| [
"[email protected]"
] | |
984f1dc9a30584bc111fbada107963e7afc54718 | 72f2992a3659ff746ba5ce65362acbe85a918df9 | /apps-src/apps/external/zxing/qrcode/QRBitMatrixParser.h | f749c280c1cfdd8c0801a52ecefce0b14bd0a662 | [
"BSD-2-Clause"
] | permissive | chongtianfeiyu/Rose | 4742f06ee9ecd55f9717ac6378084ccf8bb02a15 | 412175b57265ba2cda1e33dd2047a5a989246747 | refs/heads/main | 2023-05-23T14:03:08.095087 | 2021-06-19T13:23:58 | 2021-06-19T14:00:25 | 391,238,554 | 0 | 1 | BSD-2-Clause | 2021-07-31T02:39:25 | 2021-07-31T02:39:24 | null | UTF-8 | C++ | false | false | 1,503 | h | #pragma once
/*
* Copyright 2016 Nu-book Inc.
* Copyright 2016 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.
*/
namespace ZXing {
class BitMatrix;
class ByteArray;
namespace QRCode {
class Version;
class FormatInformation;
/**
* @author Sean Owen
*/
class BitMatrixParser
{
public:
/**
* @param bitMatrix {@link BitMatrix} to parse
* return false if dimension is not >= 21 and 1 mod 4
*/
static const Version* ReadVersion(const BitMatrix& bitMatrix, bool mirrored);
static FormatInformation ReadFormatInformation(const BitMatrix& bitMatrix, bool mirrored);
/**
* <p>Reads the bits in the {@link BitMatrix} representing the finder pattern in the
* correct order in order to reconstruct the codewords bytes contained within the
* QR Code.</p>
*
* @return bytes encoded within the QR Code
* or empty array if the exact number of bytes expected is not read
*/
static ByteArray ReadCodewords(const BitMatrix& bitMatrix, const Version& version);
};
} // QRCode
} // ZXing
| [
"[email protected]"
] | |
b797394de6d94fc0af6a9dcca68e55e4ecad1b9c | 12a12837e4de40befdce2cae31f245298f1b34e7 | /MyProject/Plugins/FirebaseFeatures/Source/ThirdParty/firebase_cpp_sdk/include/firebase/firestore/field_value.h | 73e940ac1c0f79ceff49c7a568b9400c371fa8b5 | [
"Apache-2.0"
] | permissive | Sergujest/softwareteam-unreal | fddb5f8016d464d4c07efa557e7d72c202725d94 | f2aeec5544ef39312428bf7b911139ab368120cd | refs/heads/master | 2023-06-13T02:03:32.030948 | 2021-07-09T14:09:17 | 2021-07-09T14:09:17 | 384,178,077 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,377 | h | /*
* Copyright 2018 Google
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_VALUE_H_
#define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_VALUE_H_
#include <cstdint>
#include <iosfwd>
#include <limits>
#include <string>
#include <vector>
#include "firebase/internal/type_traits.h"
#include "firebase/firestore/map_field_value.h"
namespace firebase {
class Timestamp;
namespace firestore {
class DocumentReference;
class FieldValueInternal;
class GeoPoint;
/**
* @brief A field value represents variant datatypes as stored by Firestore.
*
* FieldValue can be used when reading a particular field with
* DocumentSnapshot::Get() or fields with DocumentSnapshot::GetData(). When
* writing document fields with DocumentReference::Set() or
* DocumentReference::Update(), it can also represent sentinel values in
* addition to real data values.
*
* For a non-sentinel instance, you can check whether it is of a particular type
* with is_foo() and get the value with foo_value(), where foo can be one of
* null, boolean, integer, double, timestamp, string, blob, reference,
* geo_point, array or map. If the instance is not of type foo, the call to
* foo_value() will fail (and cause a crash).
*/
class FieldValue final {
// Helper aliases for `Increment` member functions.
// Qualifying `is_integer` is to prevent ambiguity with the
// `FieldValue::is_integer` member function.
// Note: normally, `enable_if::type` would be included in the alias, but such
// a declaration breaks SWIG (presumably, SWIG cannot handle `typename` within
// an alias template).
template <typename T>
using EnableIfIntegral = enable_if<::firebase::is_integer<T>::value, int>;
template <typename T>
using EnableIfFloatingPoint = enable_if<is_floating_point<T>::value, int>;
public:
/**
* The enumeration of all valid runtime types of FieldValue.
*/
enum class Type {
kNull,
kBoolean,
kInteger,
kDouble,
kTimestamp,
kString,
kBlob,
kReference,
kGeoPoint,
kArray,
kMap,
// Below are sentinel types. Sentinel types can be passed to Firestore
// methods as arguments, but are never returned from Firestore.
kDelete,
kServerTimestamp,
kArrayUnion,
kArrayRemove,
kIncrementInteger,
kIncrementDouble,
};
/**
* @brief Creates an invalid FieldValue that has to be reassigned before it
* can be used.
*
* Calling any member function on an invalid FieldValue will be a no-op. If
* the function returns a value, it will return a zero, empty, or invalid
* value, depending on the type of the value.
*/
FieldValue();
/**
* @brief Copy constructor.
*
* `FieldValue` is immutable and can be efficiently copied (no deep copy is
* performed).
*
* @param[in] other `FieldValue` to copy from.
*/
FieldValue(const FieldValue& other);
/**
* @brief Move constructor.
*
* Moving is more efficient than copying for a `FieldValue`. After being moved
* from, a `FieldValue` is equivalent to its default-constructed state.
*
* @param[in] other `FieldValue` to move data from.
*/
FieldValue(FieldValue&& other) noexcept;
~FieldValue();
/**
* @brief Copy assignment operator.
*
* `FieldValue` is immutable and can be efficiently copied (no deep copy is
* performed).
*
* @param[in] other `FieldValue` to copy from.
*
* @return Reference to the destination `FieldValue`.
*/
FieldValue& operator=(const FieldValue& other);
/**
* @brief Move assignment operator.
*
* Moving is more efficient than copying for a `FieldValue`. After being moved
* from, a `FieldValue` is equivalent to its default-constructed state.
*
* @param[in] other `FieldValue` to move data from.
*
* @return Reference to the destination `FieldValue`.
*/
FieldValue& operator=(FieldValue&& other) noexcept;
/**
* @brief Constructs a FieldValue containing the given boolean value.
*/
static FieldValue Boolean(bool value);
/**
* @brief Constructs a FieldValue containing the given 64-bit integer value.
*/
static FieldValue Integer(int64_t value);
/**
* @brief Constructs a FieldValue containing the given double-precision
* floating point value.
*/
static FieldValue Double(double value);
/**
* @brief Constructs a FieldValue containing the given Timestamp value.
*/
static FieldValue Timestamp(Timestamp value);
/**
* @brief Constructs a FieldValue containing the given std::string value.
*/
static FieldValue String(std::string value);
/**
* @brief Constructs a FieldValue containing the given blob value of given
* size. `value` is copied into the returned FieldValue.
*/
static FieldValue Blob(const uint8_t* value, size_t size);
/**
* @brief Constructs a FieldValue containing the given reference value.
*/
static FieldValue Reference(DocumentReference value);
/**
* @brief Constructs a FieldValue containing the given GeoPoint value.
*/
static FieldValue GeoPoint(GeoPoint value);
/**
* @brief Constructs a FieldValue containing the given FieldValue vector
* value.
*/
static FieldValue Array(std::vector<FieldValue> value);
/**
* @brief Constructs a FieldValue containing the given FieldValue map value.
*/
static FieldValue Map(MapFieldValue value);
/** @brief Gets the current type contained in this FieldValue. */
Type type() const;
/** @brief Gets whether this FieldValue is currently null. */
bool is_null() const { return type() == Type::kNull; }
/** @brief Gets whether this FieldValue contains a boolean value. */
bool is_boolean() const { return type() == Type::kBoolean; }
/** @brief Gets whether this FieldValue contains an integer value. */
bool is_integer() const { return type() == Type::kInteger; }
/** @brief Gets whether this FieldValue contains a double value. */
bool is_double() const { return type() == Type::kDouble; }
/** @brief Gets whether this FieldValue contains a timestamp. */
bool is_timestamp() const { return type() == Type::kTimestamp; }
/** @brief Gets whether this FieldValue contains a string. */
bool is_string() const { return type() == Type::kString; }
/** @brief Gets whether this FieldValue contains a blob. */
bool is_blob() const { return type() == Type::kBlob; }
/**
* @brief Gets whether this FieldValue contains a reference to a document in
* the same Firestore.
*/
bool is_reference() const { return type() == Type::kReference; }
/** @brief Gets whether this FieldValue contains a GeoPoint. */
bool is_geo_point() const { return type() == Type::kGeoPoint; }
/** @brief Gets whether this FieldValue contains an array of FieldValues. */
bool is_array() const { return type() == Type::kArray; }
/** @brief Gets whether this FieldValue contains a map of std::string to
* FieldValue. */
bool is_map() const { return type() == Type::kMap; }
/** @brief Gets the boolean value contained in this FieldValue. */
bool boolean_value() const;
/** @brief Gets the integer value contained in this FieldValue. */
int64_t integer_value() const;
/** @brief Gets the double value contained in this FieldValue. */
double double_value() const;
/** @brief Gets the timestamp value contained in this FieldValue. */
class Timestamp timestamp_value() const;
/** @brief Gets the string value contained in this FieldValue. */
std::string string_value() const;
/** @brief Gets the blob value contained in this FieldValue. */
const uint8_t* blob_value() const;
/** @brief Gets the blob size contained in this FieldValue. */
size_t blob_size() const;
/** @brief Gets the DocumentReference contained in this FieldValue. */
DocumentReference reference_value() const;
/** @brief Gets the GeoPoint value contained in this FieldValue. */
class GeoPoint geo_point_value() const;
/** @brief Gets the vector of FieldValues contained in this FieldValue. */
std::vector<FieldValue> array_value() const;
/**
* @brief Gets the map of string to FieldValue contained in this FieldValue.
*/
MapFieldValue map_value() const;
/**
* @brief Returns `true` if this `FieldValue` is valid, `false` if it is not
* valid. An invalid `FieldValue` could be the result of:
* - Creating a `FieldValue` using the default constructor.
* - Calling `DocumentSnapshot::Get(field)` for a field that does not exist
* in the document.
*
* @return `true` if this `FieldValue` is valid, `false` if this `FieldValue`
* is invalid.
*/
bool is_valid() const { return internal_ != nullptr; }
/** @brief Constructs a null. */
static FieldValue Null();
/**
* @brief Returns a sentinel for use with Update() to mark a field for
* deletion.
*/
static FieldValue Delete();
/**
* Returns a sentinel that can be used with Set() or Update() to include
* a server-generated timestamp in the written data.
*/
static FieldValue ServerTimestamp();
/**
* Returns a special value that can be used with Set() or Update() that tells
* the server to union the given elements with any array value that already
* exists on the server. Each specified element that doesn't already exist in
* the array will be added to the end. If the field being modified is not
* already an array, it will be overwritten with an array containing exactly
* the specified elements.
*
* @param elements The elements to union into the array.
* @return The FieldValue sentinel for use in a call to Set() or Update().
*/
static FieldValue ArrayUnion(std::vector<FieldValue> elements);
/**
* Returns a special value that can be used with Set() or Update() that tells
* the server to remove the given elements from any array value that already
* exists on the server. All instances of each element specified will be
* removed from the array. If the field being modified is not already an
* array, it will be overwritten with an empty array.
*
* @param elements The elements to remove from the array.
* @return The FieldValue sentinel for use in a call to Set() or Update().
*/
static FieldValue ArrayRemove(std::vector<FieldValue> elements);
/**
* Returns a string representation of this `FieldValue` for logging/debugging
* purposes.
*
* @note the exact string representation is unspecified and subject to
* change; don't rely on the format of the string.
*/
std::string ToString() const;
/**
* Outputs the string representation of this `FieldValue` to the given stream.
*
* @see `ToString()` for comments on the representation format.
*/
friend std::ostream& operator<<(std::ostream& out, const FieldValue& value);
private:
friend class DocumentReferenceInternal;
friend class DocumentSnapshotInternal;
friend class FieldValueInternal;
friend class FirestoreInternal;
friend class QueryInternal;
friend class TransactionInternal;
friend class Wrapper;
friend class WriteBatchInternal;
friend struct ConverterImpl;
friend bool operator==(const FieldValue& lhs, const FieldValue& rhs);
explicit FieldValue(FieldValueInternal* internal);
static FieldValue IntegerIncrement(int64_t by_value);
static FieldValue DoubleIncrement(double by_value);
FieldValueInternal* internal_ = nullptr;
};
/** Checks `lhs` and `rhs` for equality. */
bool operator==(const FieldValue& lhs, const FieldValue& rhs);
/** Checks `lhs` and `rhs` for inequality. */
inline bool operator!=(const FieldValue& lhs, const FieldValue& rhs) {
return !(lhs == rhs);
}
} // namespace firestore
} // namespace firebase
#endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_INCLUDE_FIREBASE_FIRESTORE_FIELD_VALUE_H_
| [
"[email protected]"
] | |
bacc0594b4b1bcdbb6e8ceffba3f142e561deb5c | 5b0f0167080cc0684f507b0e50a872dca73d628f | /LeetCode/Check_Array_Formation_Through_Concatenation.cpp | 47cf9631e9704603f2b25c2073c29d42b71dbd42 | [] | no_license | donggan22/Algorithm | 0918f522cfb0a7ddf67c8d888e242d655f4298cf | e8f988527c301fee1366180d197f3944caac7c76 | refs/heads/main | 2023-07-08T03:36:47.395275 | 2021-08-09T10:47:03 | 2021-08-09T10:47:03 | 323,762,785 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 900 | cpp | class Solution {
public:
bool canFormArray(vector<int>& arr, vector<vector<int>>& pieces) {
if (arr.size() == 0)
return false;
unordered_map<int, int> m;
for (int i = 0; i < arr.size(); i++)
m.insert(make_pair(arr[i], i));
for (int i = 0; i < pieces.size(); i++)
{
int idx = 0;
for (int j = 0; j < pieces[i].size(); j++)
{
if (j == 0)
{
if (m.end() == m.find(pieces[i][j]))
return false;
idx = m.find(pieces[i][j])->second + 1;
}
else
{
if (arr[idx] == pieces[i][j])
idx++;
else
return false;
}
}
}
return true;
}
}; | [
"[email protected]"
] | |
e969085e55e814f28f4940ff3dd0ea6949fcee78 | 1a9462cf8bf332d5171afe1913fba9a0fec262f8 | /externals/boost/boost/functional/detail/hash_float.hpp | 07d19c3040636a130a93c0957d3d7e7a03b234d7 | [
"BSD-2-Clause"
] | permissive | ugozapad/g-ray-engine | 4184fd96cd06572eb7e847cc48fbed1d0ab5767a | 6a28c26541a6f4d50b0ca666375ab45f815c9299 | refs/heads/main | 2023-06-24T06:45:37.003158 | 2021-07-23T01:16:34 | 2021-07-23T01:16:34 | 377,952,802 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,663 | hpp |
// Copyright Daniel James 2005-2006. Use, modification, and distribution are
// subject to 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)
// Based on Peter Dimov's proposal
// http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2005/n1756.pdf
// issue 6.18.
#if !defined(BOOST_FUNCTIONAL_DETAIL_HASH_FLOAT_HEADER)
#define BOOST_FUNCTIONAL_DETAIL_HASH_FLOAT_HEADER
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
#include <boost/functional/detail/float_functions.hpp>
#include <boost/limits.hpp>
#include <boost/assert.hpp>
#include <errno.h>
// Don't use fpclassify or _fpclass for stlport.
#if !defined(__SGI_STL_PORT) && !defined(_STLPORT_VERSION)
# if defined(__GLIBCPP__) || defined(__GLIBCXX__)
// GNU libstdc++ 3
# if (defined(__USE_ISOC99) || defined(_GLIBCXX_USE_C99_MATH)) && \
!(defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__))
# define BOOST_HASH_USE_FPCLASSIFY
# endif
# elif (defined(_YVALS) && !defined(__IBMCPP__)) || defined(_CPPLIB_VER)
// Dinkumware Library, on Visual C++
# if defined(BOOST_MSVC)
# define BOOST_HASH_USE_FPCLASS
# endif
# endif
#endif
namespace boost
{
namespace hash_detail
{
inline void hash_float_combine(std::size_t& seed, std::size_t value)
{
seed ^= value + (seed<<6) + (seed>>2);
}
template <class T>
inline std::size_t float_hash_impl(T v)
{
int exp = 0;
errno = 0;
v = boost::hash_detail::call_frexp(v, &exp);
if(errno) return 0;
std::size_t seed = 0;
std::size_t const length
= (std::numeric_limits<T>::digits +
std::numeric_limits<int>::digits - 1)
/ std::numeric_limits<int>::digits;
for(std::size_t i = 0; i < length; ++i)
{
v = boost::hash_detail::call_ldexp(v, std::numeric_limits<int>::digits);
int const part = static_cast<int>(v);
v -= part;
hash_float_combine(seed, part);
}
hash_float_combine(seed, exp);
return seed;
}
template <class T>
inline std::size_t float_hash_value(T v)
{
#if defined(BOOST_HASH_USE_FPCLASSIFY)
using namespace std;
switch (fpclassify(v)) {
case FP_ZERO:
return 0;
case FP_INFINITE:
return (std::size_t)(v > 0 ? -1 : -2);
case FP_NAN:
return (std::size_t)(-3);
case FP_NORMAL:
case FP_SUBNORMAL:
return float_hash_impl(v);
default:
BOOST_ASSERT(0);
return 0;
}
#elif defined(BOOST_HASH_USE_FPCLASS)
switch(_fpclass(v)) {
case _FPCLASS_NZ:
case _FPCLASS_PZ:
return 0;
case _FPCLASS_PINF:
return (std::size_t)(-1);
case _FPCLASS_NINF:
return (std::size_t)(-2);
case _FPCLASS_SNAN:
case _FPCLASS_QNAN:
return (std::size_t)(-3);
case _FPCLASS_NN:
case _FPCLASS_ND:
return float_hash_impl(v);
case _FPCLASS_PD:
case _FPCLASS_PN:
return float_hash_impl(v);
default:
BOOST_ASSERT(0);
return 0;
}
#else
return float_hash_impl(v);
#endif
}
}
}
#endif
| [
"[email protected]"
] | |
e70b8d53ee7e3e340b0a10ccd797f320adcd245c | 882238b7118ba2f7c2f8eb36212508203d0466a4 | /generator/enum.h | 3c972a63ac7203745dad060ac9781e33a75dad11 | [
"MIT"
] | permissive | alisharifi01/hottentot | 32c0184c9aa2248047eb03ca13d68dc8557b962b | e578a2185c473301076ece5634113ab663996a3e | refs/heads/master | 2020-03-27T10:19:17.074850 | 2016-11-13T07:58:08 | 2016-11-13T07:58:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,458 | h | /* The MIT License (MIT)
*
* Copyright (c) 2015 LabCrypto Org.
*
* 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 _ORG_LABCRYPTO_HOTTENTOT_GENERATOR__ENUM_H_
#define _ORG_LABCRYPTO_HOTTENTOT_GENERATOR__ENUM_H_
#include <map>
#include "declaration.h"
namespace org {
namespace labcrypto {
namespace hottentot {
namespace generator {
namespace java {
class JavaGenerator;
};
namespace cc {
class CCGenerator;
};
class Module;
class Enum {
friend class Hot;
friend class ::org::labcrypto::hottentot::generator::cc::CCGenerator;
friend class ::org::labcrypto::hottentot::generator::java::JavaGenerator;
public:
public:
Enum(Module *module)
: module_(module) {
}
virtual ~Enum() {}
public:
inline virtual void AddItem(std::string name, uint16_t value) {
items_[name] = value;
revItems_[value] = name;
}
inline virtual std::string GetName() const {
return name_;
}
inline virtual void SetName(std::string name) {
name_ = name;
}
inline virtual std::string GetItemName(uint16_t itemValue) {
return revItems_[itemValue];
}
inline virtual uint16_t GetItemValue(std::string itemName) {
return items_[itemName];
}
private:
std::string name_;
std::map<std::string, uint16_t> items_;
std::map<uint16_t, std::string> revItems_;
Module *module_;
};
}
}
}
}
#endif | [
"[email protected]"
] | |
d0ddf6b1193ac6714ed78f721bc24d3fa6c54c05 | 1210df674a4a6ec547f8a6f1e8b2ea0b72bfabf7 | /C7/7_4/StdAfx.cpp | ffe25f652d79b2e74eef4f86dcd416944064498c | [] | no_license | 20191864229/G29 | 05e911e6185afd4ba6a85c4864a16d1e638885bb | 144902d98bc2329a5c28a81ae7a8a7457c47fdc2 | refs/heads/master | 2020-08-16T19:59:42.203215 | 2019-12-16T14:15:33 | 2019-12-16T14:15:33 | 215,545,241 | 0 | 0 | null | 2019-11-02T01:11:42 | 2019-10-16T12:40:58 | C++ | UTF-8 | C++ | false | false | 282 | cpp | // stdafx.cpp : source file that includes just the standard includes
// 7_4.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"[email protected]"
] | |
b3d10a882fbde1ef7b87dd839bb7339f5be497db | 5da7329111ede9432df039182275ad6ae0e4693d | /2012-arduino/TCL_lighting/audio_board/audio_board.ino | 8b5c251801a7deeed2acd1cca1c93de29966eecb | [] | no_license | JamesHagerman/Sensatron | 6bca70d378362978a285b49a7dbc14f14cc88c1c | 9773c23481f83636fc7bc9c2938ea37f4bdc272e | refs/heads/master | 2021-01-20T17:32:55.191392 | 2018-09-25T04:37:47 | 2018-09-25T04:37:47 | 61,709,147 | 2 | 3 | null | 2016-06-22T10:22:17 | 2016-06-22T10:07:22 | null | UTF-8 | C++ | false | false | 3,323 | ino |
// Spectrum analyzer shield pins
int spectrumStrobe = 8;
int spectrumReset = 9;
int spectrumAnalog = 4; //4 for left channel, 5 for right.
//This holds the 15 bit RGB values for each LED.
//You'll need one for each LED, we're using 25 LEDs here.
//Note you've only got limited memory, so you can only control
//Several hundred LEDs on a normal arduino. Double that on a Duemilanove.
int MyDisplay[25];
// Spectrum analyzer read values will be kept here.
int Spectrum[7];
void setup() {
byte Counter;
// Turn on Serial port:
Serial.begin(9600);
Serial.println("");
Serial.println("Spectrum test written by James Hagerman");
//Setup pins to drive the spectrum analyzer.
pinMode(spectrumReset, OUTPUT);
pinMode(spectrumStrobe, OUTPUT);
//Init spectrum analyzer
digitalWrite(spectrumStrobe,LOW);
delay(1);
digitalWrite(spectrumReset,HIGH);
delay(1);
digitalWrite(spectrumStrobe,HIGH);
delay(1);
digitalWrite(spectrumStrobe,LOW);
delay(1);
digitalWrite(spectrumReset,LOW);
delay(5);
// Reading the analyzer now will read the lowest frequency.
}
void loop() {
int Counter, Counter2, Counter3;
showSpectrum();
delay(15); //We wait here for a little while until all the values to the LEDs are written out.
//This is being done in the background by an interrupt.
}
// Read 7 band equalizer.
void readSpectrum() {
// Band 0 = Lowest Frequencies.
byte Band;
for(Band=0;Band <7; Band++) {
Spectrum[Band] = (analogRead(spectrumAnalog) + analogRead(spectrumAnalog) ) >>1; //Read twice and take the average by dividing by 2
digitalWrite(spectrumStrobe,HIGH);
digitalWrite(spectrumStrobe,LOW);
}
}
void showSpectrum() {
//Not I don;t use any floating point numbers - all integers to keep it zippy.
readSpectrum();
byte Band, BarSize, MaxLevel;
static unsigned int Divisor = 80, ChangeTimer=0; //, ReminderDivisor,
unsigned int works, Remainder;
MaxLevel = 0;
for(Band=0;Band<5;Band++) {//We only graph the lowest 5 bands here, there is 2 more unused!
//If value is 0, we don;t show anything on graph
works = Spectrum[Band]/Divisor; //Bands are read in as 10 bit values. Scale them down to be 0 - 5
if(works > MaxLevel) { //Check if this value is the largest so far.
MaxLevel = works;
}
Serial.print("band ");
Serial.print(Band);
Serial.print(" value: ");
//Serial.print(works);
Serial.print(Spectrum[Band]);
Serial.print(" Divisor: ");
Serial.println(Divisor);
// for(BarSize=1;BarSize <=5; BarSize++) {
// if( works > BarSize) {
// LP.setLEDFast( LP.Translate(Band,BarSize-1),BarSize*6,31-(BarSize*5),0);
// } else if ( works == BarSize) {
// LP.setLEDFast( LP.Translate(Band,BarSize-1),BarSize*6,31-(BarSize*5),0); //Was remainder
// } else {
// LP.setLEDFast( LP.Translate(Band,BarSize-1),5,0,5);
// }
// }
}
// Adjust the Divisor if levels are too high/low.
// If below 4 happens 20 times, then very slowly turn up.
if (MaxLevel >= 5) {
Divisor=Divisor+1;
ChangeTimer=0;
} else {
if(MaxLevel < 4) {
if(Divisor > 65) {
if(ChangeTimer++ > 20) {
Divisor--;
ChangeTimer=0;
}
}
} else {
ChangeTimer=0;
}
}
}
| [
"[email protected]"
] | |
b79e65fc586ca15bb23d36f567410e165cdd1cb9 | eaae3bc291b9b8455e3f56650271655089fff997 | /EFE Engine/include/scene/TileLayer.h | 5c14b33a538b06f56d33354c1d8f1c99c4113467 | [] | no_license | mifozski/EFE-Engine | 59b6274830b68fa2e7f21b5d91de9d222297cbcb | 32521a8f534e3ff863617bfb42360f8f568bacd0 | refs/heads/master | 2021-05-28T07:35:55.934515 | 2015-01-02T20:08:55 | 2015-01-02T20:08:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 945 | h | #ifndef EFE_TILELAYER_H
#define EFE_TILELAYER_H
#include <vector>
#include "scene/Tile.h"
#include "math/MathTypes.h"
#include "system/SystemTypes.h"
namespace efe
{
enum eTileLayerType
{
eTileLayerType_Normal,
eTileLayerType_LastEnum
};
typedef std::vector<cTile*> tTileVec;
typedef tTileVec::iterator tTileVecIt;
class cTileLayer
{
friend class cTileMapRectIt;
friend class cTileMapLineIt;
public:
cTileLayer(unsigned int a_lW, unsigned int a_lH, bool a_bCollision, bool a_bLit, eTileLayerType a_Type, float a_fZ = 0);
~cTileLayer();
bool SetTile(unsigned int a_lX, unsigned int a_lY, cTile *a_Val);
cTile *GetAt(int a_lX, int a_lY);
cTile *GetAt(int a_lNum);
void SetZ(float a_fZ){m_fZ = a_fZ;}
float GetZ(){return m_fZ;}
bool HasCollsion(){return m_bCollision;}
private:
tTileVec m_vTile;
cVector2l m_vSize;
bool m_bCollision;
bool m_bLit;
float m_fZ;
eTileLayerType m_Type;
};
};
#endif | [
"[email protected]"
] | |
81658eee6db9dad6c4db552577d67cbc6ca3b9cb | 9dcf91bc705c1e7907afac96cfe8b07d86d1f637 | /include/wm_navigation/WmGlobalNavigation.h | cb32eeffe6244728f83464592a208b965bc6d5f7 | [
"BSD-3-Clause"
] | permissive | fmrico/WaterMellon | 7dd47beca113d95836311e48827fef2beb778985 | 5d61914d9597118735e933e6d61a7e7872d83f5a | refs/heads/master | 2021-01-10T11:42:55.551205 | 2015-10-27T22:08:42 | 2015-10-27T22:08:42 | 43,119,298 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,021 | h | /*
* mapper.h
*
* Created on: 22/08/2015
* Author: paco
*/
#ifndef WMGLOBALNAVIGATION_H_
#define WMGLOBALNAVIGATION_H_
#include "ros/ros.h"
#include <sensor_msgs/PointCloud2.h>
#include <geometry_msgs/PoseWithCovarianceStamped.h>
#include <tf/transform_listener.h>
#include <tf/message_filter.h>
#include <message_filters/subscriber.h>
#include <pcl/point_types.h>
#include <pcl/conversions.h>
#include <pcl_ros/transforms.h>
#include <pcl/sample_consensus/method_types.h>
#include <pcl/sample_consensus/model_types.h>
#include <pcl/segmentation/sac_segmentation.h>
#include <pcl/io/pcd_io.h>
#include <pcl/filters/extract_indices.h>
#include <pcl/filters/passthrough.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl_conversions/pcl_conversions.h>
#include "pcl/point_types_conversion.h"
//#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/octree/octree_search.h>
#include <pcl/octree/octree.h>
#include <sensor_msgs/PointCloud2.h>
#include <nav_msgs/OccupancyGrid.h>
#include <ros/console.h>
#include <float.h>
#include <boost/math/distributions.hpp>
#include <boost/math/distributions/normal.hpp>
#include <stdlib.h>
#include <time.h>
#include <algorithm>
#include <time.h>
//#include <random>
#include <wm_navigation/Particle.h>
#include <costmap_2d/costmap_2d_ros.h>
#include <costmap_2d/costmap_2d_publisher.h>
#include <geometry_msgs/PoseStamped.h>
#include <wm_navigation/Utilities.h>
#include <watermellon/GNavGoalStamped.h>
namespace wm_navigation {
class WmGlobalNavigation {
public:
WmGlobalNavigation(ros::NodeHandle private_nh_ = ros::NodeHandle("~"));
virtual ~WmGlobalNavigation();
virtual void mapCallback(const sensor_msgs::PointCloud2::ConstPtr& map_in);
virtual void goalCallback(const geometry_msgs::PoseStamped::ConstPtr& goal_in);
virtual void poseCallback(const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& goal_in);
virtual void perceptionCallback(const sensor_msgs::PointCloud2::ConstPtr& cloud_in);
virtual void step();
void setGoalPose(const geometry_msgs::PoseStamped& goal_in);
geometry_msgs::Pose getStartingPose();
geometry_msgs::Pose getEndPose();
geometry_msgs::Pose getCurrentPose();
private:
void publish_all();
void publish_static_map();
void publish_dynamic_map();
void publish_gradient();
void publish_goal();
void updateStaticCostmap();
void updateDynamicCostmap();
void updatePath();
inline bool isPath(int i, int j, int cost);
void updateGradient(int i, int j, int cost);
float getLocalizationQuality(const geometry_msgs::PoseWithCovarianceStamped& pos_info);
ros::NodeHandle nh_;
tf::TransformListener tfListener_;
tf::MessageFilter<sensor_msgs::PointCloud2>* tfMapSub_;
tf::MessageFilter<sensor_msgs::PointCloud2>* tfPerceptSub_;
message_filters::Subscriber<sensor_msgs::PointCloud2>* mapSub_;
message_filters::Subscriber<sensor_msgs::PointCloud2>* perceptSub_;
ros::Subscriber goal_sub_;
ros::Subscriber pose_sub_;
std::string worldFrameId_;
std::string baseFrameId_;
double res_;
double pointcloudMinZ_;
double pointcloudMaxZ_;
double dynamic_cost_dec_;
double dynamic_cost_inc_;
double robot_radious_;
static const int MAX_COST=255;
geometry_msgs::PoseWithCovarianceStamped pose_;
pcl::octree::OctreePointCloudSearch<pcl::PointXYZRGB>::Ptr map_;
pcl::PointCloud<pcl::PointXYZRGB>::Ptr last_perception_;
float map_max_x_, map_min_x_, map_max_y_, map_min_y_;
ros::WallTime last_dynamic_map_update_;
costmap_2d::Costmap2D static_costmap_;
costmap_2d::Costmap2D dynamic_costmap_;
costmap_2d::Costmap2D goal_gradient_;
costmap_2d::Costmap2DPublisher static_costmap_pub_;
costmap_2d::Costmap2DPublisher dynamic_costmap_pub_;
costmap_2d::Costmap2DPublisher goal_gradient_pub_;
std::vector<geometry_msgs::PoseStamped> plan_;
geometry_msgs::PoseStamped::Ptr goal_;
geometry_msgs::Pose::Ptr start_;
watermellon::GNavGoalStamped::Ptr goal_vector_;
ros::Publisher goal_vector_pub_;
bool has_goal_;
bool recalcule_path_;
};
}
#endif /* WMGLOBALNAVIGATION_H_ */
| [
"[email protected]"
] | |
61c4532608596185da6e48aa2555899f80f02257 | d8371c58aa8ba6e31ecd40d97e0576bf9f366923 | /include/general/allocation.h | 29a7497200a81150c3f6fde5fc465f4fa541f100 | [] | no_license | simmito/micmac-archeos | 2499066b1652f9ba6a1e0391632f841333ffbcbf | 9c66a1a656621b045173fa41874b39264ca39799 | refs/heads/master | 2021-01-15T21:35:26.952360 | 2013-07-17T15:36:36 | 2013-07-17T15:36:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,652 | h | /*Header-MicMac-eLiSe-25/06/2007
MicMac : Multi Image Correspondances par Methodes Automatiques de Correlation
eLiSe : ELements of an Image Software Environnement
www.micmac.ign.fr
Copyright : Institut Geographique National
Author : Marc Pierrot Deseilligny
Contributors : Gregoire Maillet, Didier Boldo.
[1] M. Pierrot-Deseilligny, N. Paparoditis.
"A multiresolution and optimization-based image matching approach:
An application to surface reconstruction from SPOT5-HRS stereo imagery."
In IAPRS vol XXXVI-1/W41 in ISPRS Workshop On Topographic Mapping From Space
(With Special Emphasis on Small Satellites), Ankara, Turquie, 02-2006.
[2] M. Pierrot-Deseilligny, "MicMac, un lociel de mise en correspondance
d'images, adapte au contexte geograhique" to appears in
Bulletin d'information de l'Institut Geographique National, 2007.
Francais :
MicMac est un logiciel de mise en correspondance d'image adapte
au contexte de recherche en information geographique. Il s'appuie sur
la bibliotheque de manipulation d'image eLiSe. Il est distibue sous la
licences Cecill-B. Voir en bas de fichier et http://www.cecill.info.
English :
MicMac is an open source software specialized in image matching
for research in geographic information. MicMac is built on the
eLiSe image library. MicMac is governed by the "Cecill-B licence".
See below and http://www.cecill.info.
Header-MicMac-eLiSe-25/06/2007*/
#ifndef _ELISE_ALLOCATION_H
#define _ELISE_ALLOCATION_H
class Mcheck
{
public :
void * operator new (size_t sz);
void operator delete (void * ptr) ;
private :
// to avoid use
void * operator new [] (size_t sz);
void operator delete [] (void * ptr) ;
};
template <const INT NBB> class ElListAlloc
{
public :
void * get()
{
if (_l.empty())
_l.push_back(malloc(NBB));
void * res = _l.front();
_l.pop_front();
return res;
}
void put(void * v)
{
_l.push_front(v);
}
void purge()
{
while (! _l.empty())
{
free(_l.front());
_l.pop_front();
}
}
private :
ElSTDNS list<void *> _l;
};
/*******************************************************************/
/* */
/* Classes for garbage collection */
/* */
/*******************************************************************/
/*
Class RC_Object :
References Counting Object
*/
class RC_Object : public Mcheck
{
friend void decr_ref(class Object_cptref * oc);
friend class PRC0;
protected :
RC_Object();
virtual ~RC_Object();
//---- data ----
union
{
int cpt_ref;
RC_Object * next;
} _d;
private :
// declared as static so that they can be called with 0
static void decr_ref(RC_Object *);
public :
static void incr_ref(RC_Object *);
};
/*
Class PRC0 :
Pointer to References Counting Object
*/
class PRC0
{
public :
// big three :
PRC0 (const PRC0&);
~PRC0(void) ;
void operator=(const PRC0 p2);
void * ptr(){return _ptr;}
PRC0 (RC_Object *) ;
protected :
inline PRC0(){_ptr=0;};
//-------- data ----------
RC_Object * _ptr;
private :
static void decr_ref(RC_Object * oc);
// just to avoid use :
// PRC0 * operator &();
};
#endif // ! _ELISE_ALLOCATION_H
/*Footer-MicMac-eLiSe-25/06/2007
Ce logiciel est un programme informatique servant à la mise en
correspondances d'images pour la reconstruction du relief.
Ce logiciel est régi par la licence CeCILL-B soumise au droit français et
respectant les principes de diffusion des logiciels libres. Vous pouvez
utiliser, modifier et/ou redistribuer ce programme sous les conditions
de la licence CeCILL-B telle que diffusée par le CEA, le CNRS et l'INRIA
sur le site "http://www.cecill.info".
En contrepartie de l'accessibilité au code source et des droits de copie,
de modification et de redistribution accordés par cette licence, il n'est
offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
seule une responsabilité restreinte pèse sur l'auteur du programme, le
titulaire des droits patrimoniaux et les concédants successifs.
A cet égard l'attention de l'utilisateur est attirée sur les risques
associés au chargement, à l'utilisation, à la modification et/ou au
développement et à la reproduction du logiciel par l'utilisateur étant
donné sa spécificité de logiciel libre, qui peut le rendre complexe à
manipuler et qui le réserve donc à des développeurs et des professionnels
avertis possédant des connaissances informatiques approfondies. Les
utilisateurs sont donc invités à charger et tester l'adéquation du
logiciel à leurs besoins dans des conditions permettant d'assurer la
sécurité de leurs systèmes et ou de leurs données et, plus généralement,
à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
pris connaissance de la licence CeCILL-B, et que vous en avez accepté les
termes.
Footer-MicMac-eLiSe-25/06/2007*/
| [
"[email protected]"
] | |
976215d6f5cb4801c9cdb59f07191b08392905fc | ea1f01ce32671a1214dd7e0995bc131307e58476 | /A4/GeometryNode.hpp | 75cddb9cd187ccbaf16b135a1f687839c6a8e18c | [] | no_license | mismayil/cs488 | 65a729adfe9757a7c52d0609b381888d64b1f12b | d8938779bc0b1b1fd9ca5a5dd29d25f6e843a721 | refs/heads/master | 2021-01-10T06:45:50.215212 | 2015-12-31T19:27:13 | 2015-12-31T19:27:13 | 48,860,054 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 319 | hpp | #pragma once
#include "SceneNode.hpp"
#include "Primitive.hpp"
#include "Material.hpp"
class GeometryNode : public SceneNode {
public:
GeometryNode( const std::string & name, Primitive *prim,
Material *mat = nullptr );
void setMaterial( Material *material );
Material *m_material;
Primitive *m_primitive;
};
| [
"[email protected]"
] | |
8296d686fa7a1716a2d20c01b4352e7a2d1eafe1 | cf64d8d2d02661f0635b6e44c4d0903965eebe2e | /Round 630 (Div. 2)/A.cpp | 293a7b2bc506c778c47d66c1247586ef0726fc7b | [] | no_license | LavishGulati/Codeforces | 469b741855ce863877e0f6eb725bbe63bef0b91b | 59756c87e37f903a0e8c84060478207d09b1bad2 | refs/heads/master | 2023-08-30T22:46:23.533386 | 2023-08-21T11:26:18 | 2023-08-21T11:26:18 | 145,226,865 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,158 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<long long, long long> pll;
typedef pair<int, int> pii;
typedef pair<int, bool> pib;
#define pb push_back
#define umap unordered_map
#define uset unordered_set
#define f first
#define s second
#define mp make_pair
#define all(x) x.begin(), x.end()
#define pq priority_queue
#define MOD 1000000007
int main(){
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int t;
cin >> t;
while(t--){
int a, b, c, d;
cin >> a >> b >> c >> d;
int x, y, x1, y1, x2, y2;
cin >> x >> y >> x1 >> y1 >> x2 >> y2;
if(x-a+b >= x1 && x-a+b <= x2 && y-c+d >= y1 && y-c+d <= y2){
if(a > b && x1 > x-1){
cout << "No" << endl;
}
else if(a < b && x2 < x+1){
cout << "No" << endl;
}
else if(a == b && a > 0 && x1 > x-1 && x2 < x+1){
cout << "No" << endl;
}
else if(c > d && y1 > y-1){
cout << "No" << endl;
}
else if(c < d && y2 < y+1){
cout << "No" << endl;
}
else if(c == d && c > 0 && y1 > y-1 && y2 < y+1){
cout << "No" << endl;
}
else{
cout << "Yes" << endl;
}
}
else{
cout << "No" << endl;
}
}
} | [
"[email protected]"
] | |
d01eb570ad6b1b5b8a0837cddb323339ba623c2d | d4a7a5a7e2868f5b3563b69d6e457e53d9f1c18e | /我的第一个c++程序.cpp | f57c616415469cd65299223817d62d1197d5d872 | [] | no_license | cli851/noi | 630328d2e08785caf2bc559618fa1c415a39f647 | 3245e8ea84486553ef24d05ab50aa81837d36657 | refs/heads/master | 2023-04-19T16:04:52.275245 | 2021-05-08T14:38:50 | 2021-05-08T14:38:50 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 237 | cpp | #include<iostream>
using namespace std;
int main()
{
cout<<"春晓"<<endl;
cout<<"春眠不觉晓,"<<endl;
cout<<"处处蚊子咬,"<<endl;
cout<<"夜来嗡嗡声,"<<endl;
cout<<"脓包知多少。"<<endl;
return 0;
}
| [
"[email protected]"
] | |
d559e0f9b3d79dd66a2e1ff9648e3974ad4d1abd | ef03edfaaf3437b24d3492ac3865968fcfda7909 | /src/DesignPatterns/src/C++/002-GOFPatterns/003-BehavioralPatterns/004-Strategy/TemplateOperationStrategy/sample.cpp | c7d322e5d149b5c319de31c6844bc5d3937cf8c5 | [] | no_license | durmazmehmet/CSD-UML-Design-Patterns | c60a6a008ec1b2de0cf5bdce74bc1336c4ceeb63 | ae25ec31452016025ff0407e6c6728322624b082 | refs/heads/main | 2023-07-25T23:02:24.703632 | 2021-08-31T23:18:19 | 2021-08-31T23:18:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 419 | cpp | #include <iostream>
#include "IntOperationContext.h"
#include "IntAddOperationStrategy.h"
#include "IntAddWithValueOperationStrategy .h"
using namespace std;
#if 1
int main()
{
IntAddOperationStrategy as;
IntAddWithValueOperationStrategy aws{ 3 };
IntOperationContext context{10, 20, as };
cout << context.execute() << endl;
context.SetStrategy(aws);
cout << context.execute() << endl;
return 0;
}
#endif
| [
"[email protected]"
] | |
87fd18dc7a0c813bc9fcd283f5591cde2e240716 | a4a072ec59436e148121e87889714a68859da9da | /Src/Engine/3_Modules/Render/Assets/Material.h | f94ca71cf04edc08ae31612f0754a1641173e0ea | [] | no_license | morcosan/CYRED | 3615441445bcfdfada3cd55533b3af4c1d14fac6 | a65c7645148c522b2f14a5e447e1fe01ed3455bc | refs/heads/master | 2021-03-23T07:25:30.131090 | 2016-05-10T20:49:47 | 2016-05-10T20:49:47 | 247,435,142 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,805 | h | // Copyright (c) 2015 Morco (www.morco.ro)
// MIT License
#pragma once
#include "../../../1_Required/Required.h"
#include "../../../2_BuildingBlocks/String/String.h"
#include "../../../2_BuildingBlocks/Data/DataUnion.h"
#include "../../../2_BuildingBlocks/Data/DataArray.h"
#include "../../../2_BuildingBlocks/Asset.h"
namespace CYRED
{
class Shader;
class Texture;
}
namespace CYRED
{
namespace Enum_FaceCulling
{
enum Enum
{
CULL_BACK
, CULL_FRONT
, CULL_NONE
};
}
typedef Enum_FaceCulling::Enum FaceCulling;
}
namespace CYRED
{
class DLL Material : public Asset
{
public:
Material();
virtual ~Material() {}
public:
void LoadUniqueID () override;
void LoadFullFile () override;
void ClearAsset () override;
public:
Shader* GetShader () const;
bool IsWireframe () const;
float GetLineWidth () const;
FaceCulling GetFaceCulling () const;
void SetShader ( Shader* shader );
void SetWireframe ( bool value );
void SetLineWidth ( float value );
void SetFaceCulling ( FaceCulling value );
void SetProperty ( const Char* name, Int value );
void SetProperty ( const Char* name, Float value );
void SetProperty ( const Char* name, const Vector2& value );
void SetProperty ( const Char* name, const Vector3& value );
void SetProperty ( const Char* name, const Vector4& value );
void SetProperty ( const Char* name, Texture* value );
UInt GetPropertiesCount ();
DataUnion& GetPropertyDataAt ( UInt index );
const Char* GetPropertyNameAt ( UInt index );
void ClearProperties ();
protected:
struct _Property
{
String name;
DataUnion data;
};
Shader* _shader;
bool _isWireframe;
float _lineWidth;
FaceCulling _faceCulling;
DataArray<_Property> _properties;
};
}
| [
"[email protected]"
] | |
756b6850ae09a618934e035517f99fb911046c65 | de7e771699065ec21a340ada1060a3cf0bec3091 | /spatial3d/src/java/org/apache/lucene/spatial3d/geom/GeoBaseCompositeMembershipShape.h | a18fe0bbfcd731a8f89393638bdeeb95cf7f4d81 | [] | no_license | sraihan73/Lucene- | 0d7290bacba05c33b8d5762e0a2a30c1ec8cf110 | 1fe2b48428dcbd1feb3e10202ec991a5ca0d54f3 | refs/heads/master | 2020-03-31T07:23:46.505891 | 2018-12-08T14:57:54 | 2018-12-08T14:57:54 | 152,020,180 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,234 | h | #pragma once
#include "stringhelper.h"
#include <limits>
#include <memory>
#include <type_traits>
#include <typeinfo>
/*
* Licensed to the Syed Mamun Raihan (sraihan.com) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* sraihan.com licenses this file to You under GPLv3 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
*
* https://www.gnu.org/licenses/gpl-3.0.en.html
*
* 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.
*/
namespace org::apache::lucene::spatial3d::geom
{
/**
* Base class to create a composite of GeoMembershipShapes
*
* @param <T> is the type of GeoMembershipShapes of the composite.
* @lucene.internal
*/
template <typename T>
class GeoBaseCompositeMembershipShape : public GeoBaseCompositeShape<T>,
public GeoMembershipShape
{
GET_CLASS_NAME(GeoBaseCompositeMembershipShape)
static_assert(std::is_base_of<GeoMembershipShape, T>::value,
L"T must inherit from GeoMembershipShape");
/**
* Constructor.
*/
public:
GeoBaseCompositeMembershipShape(std::shared_ptr<PlanetModel> planetModel)
: GeoBaseCompositeShape<T>(planetModel)
{
}
/**
* Constructor for deserialization.
* @param planetModel is the planet model.
* @param inputStream is the input stream.
* @param clazz is the class of the generic.
*/
GeoBaseCompositeMembershipShape(std::shared_ptr<PlanetModel> planetModel,
std::shared_ptr<InputStream> inputStream,
std::type_info<T> &clazz)
: GeoBaseCompositeShape<T>(planetModel, inputStream, clazz)
{
}
double computeOutsideDistance(std::shared_ptr<DistanceStyle> distanceStyle,
std::shared_ptr<GeoPoint> point) override
{
return computeOutsideDistance(distanceStyle, point->x, point->y, point->z);
}
double computeOutsideDistance(std::shared_ptr<DistanceStyle> distanceStyle,
double const x, double const y,
double const z) override
{
if (isWithin(x, y, z)) {
return 0.0;
}
double distance = std::numeric_limits<double>::infinity();
for (std::shared_ptr<GeoMembershipShape> shape : shapes) {
constexpr double normalDistance =
shape->computeOutsideDistance(distanceStyle, x, y, z);
if (normalDistance < distance) {
distance = normalDistance;
}
}
return distance;
}
protected:
std::shared_ptr<GeoBaseCompositeMembershipShape> shared_from_this()
{
return std::static_pointer_cast<GeoBaseCompositeMembershipShape>(
GeoBaseCompositeShape<T>::shared_from_this());
}
};
} // #include "core/src/java/org/apache/lucene/spatial3d/geom/
| [
"[email protected]"
] | |
7eeef307b65116777a3ff74da3d2ca630f1b7046 | 530208803dd07020362230c413cb77be548db263 | /src/rpcrawtransaction.cpp | 0959377d1e54572564a57ac441aad36caa2d13f5 | [
"MIT"
] | permissive | cryptoghass/bitcoinpositive | d93dbb2ad85f9e02e2efa0f34301de0ab6af7ef4 | 3a1f0e29e49efa821f330996d127be2d3883ab6d | refs/heads/master | 2020-04-04T12:34:00.610291 | 2018-01-12T11:14:32 | 2018-01-12T11:14:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,984 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp>
#include "base58.h"
#include "bitcoinrpc.h"
#include "db.h"
#include "init.h"
#include "main.h"
#include "net.h"
#include "wallet.h"
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace json_spirit;
//
// Utilities: convert hex-encoded Values
// (throws error if not hex).
//
uint256 ParseHashV(const Value& v, string strName)
{
string strHex;
if (v.type() == str_type)
strHex = v.get_str();
if (!IsHex(strHex)) // Note: IsHex("") is false
throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
uint256 result;
result.SetHex(strHex);
return result;
}
uint256 ParseHashO(const Object& o, string strKey)
{
return ParseHashV(find_value(o, strKey), strKey);
}
vector<unsigned char> ParseHexV(const Value& v, string strName)
{
string strHex;
if (v.type() == str_type)
strHex = v.get_str();
if (!IsHex(strHex))
throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
return ParseHex(strHex);
}
vector<unsigned char> ParseHexO(const Object& o, string strKey)
{
return ParseHexV(find_value(o, strKey), strKey);
}
void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out)
{
txnouttype type;
vector<CTxDestination> addresses;
int nRequired;
out.push_back(Pair("asm", scriptPubKey.ToString()));
out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired))
{
out.push_back(Pair("type", GetTxnOutputType(TX_NONSTANDARD)));
return;
}
out.push_back(Pair("reqSigs", nRequired));
out.push_back(Pair("type", GetTxnOutputType(type)));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
out.push_back(Pair("addresses", a));
}
void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry)
{
entry.push_back(Pair("txid", tx.GetHash().GetHex()));
entry.push_back(Pair("version", tx.nVersion));
entry.push_back(Pair("locktime", (boost::int64_t)tx.nLockTime));
Array vin;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
Object in;
if (tx.IsCoinBase())
in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
else
{
in.push_back(Pair("txid", txin.prevout.hash.GetHex()));
in.push_back(Pair("vout", (boost::int64_t)txin.prevout.n));
Object o;
o.push_back(Pair("asm", txin.scriptSig.ToString()));
o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
in.push_back(Pair("scriptSig", o));
}
in.push_back(Pair("sequence", (boost::int64_t)txin.nSequence));
vin.push_back(in);
}
entry.push_back(Pair("vin", vin));
Array vout;
for (unsigned int i = 0; i < tx.vout.size(); i++)
{
const CTxOut& txout = tx.vout[i];
Object out;
out.push_back(Pair("value", ValueFromAmount(txout.nValue)));
out.push_back(Pair("n", (boost::int64_t)i));
Object o;
ScriptPubKeyToJSON(txout.scriptPubKey, o);
out.push_back(Pair("scriptPubKey", o));
vout.push_back(out);
}
entry.push_back(Pair("vout", vout));
if (hashBlock != 0)
{
entry.push_back(Pair("blockhash", hashBlock.GetHex()));
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second)
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
{
entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight));
entry.push_back(Pair("time", (boost::int64_t)pindex->nTime));
entry.push_back(Pair("blocktime", (boost::int64_t)pindex->nTime));
}
else
entry.push_back(Pair("confirmations", 0));
}
}
}
Value getrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getrawtransaction <txid> [verbose=0]\n"
"If verbose=0, returns a string that is\n"
"serialized, hex-encoded data for <txid>.\n"
"If verbose is non-zero, returns an Object\n"
"with information about <txid>.");
uint256 hash = ParseHashV(params[0], "parameter 1");
bool fVerbose = false;
if (params.size() > 1)
fVerbose = (params[1].get_int() != 0);
CTransaction tx;
uint256 hashBlock = 0;
if (!GetTransaction(hash, tx, hashBlock, true))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
string strHex = HexStr(ssTx.begin(), ssTx.end());
if (!fVerbose)
return strHex;
Object result;
result.push_back(Pair("hex", strHex));
TxToJSON(tx, hashBlock, result);
return result;
}
Value listunspent(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listunspent [minconf=1] [maxconf=9999999] [\"address\",...]\n"
"Returns array of unspent transaction outputs\n"
"with between minconf and maxconf (inclusive) confirmations.\n"
"Optionally filtered to only include txouts paid to specified addresses.\n"
"Results are an array of Objects, each of which has:\n"
"{txid, vout, scriptPubKey, amount, confirmations}");
RPCTypeCheck(params, list_of(int_type)(int_type)(array_type));
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
int nMaxDepth = 9999999;
if (params.size() > 1)
nMaxDepth = params[1].get_int();
set<CBitcoinAddress> setAddress;
if (params.size() > 2)
{
Array inputs = params[2].get_array();
BOOST_FOREACH(Value& input, inputs)
{
CBitcoinAddress address(input.get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid BitcoinPositive address: ")+input.get_str());
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+input.get_str());
setAddress.insert(address);
}
}
Array results;
vector<COutput> vecOutputs;
assert(pwalletMain != NULL);
pwalletMain->AvailableCoins(vecOutputs, false);
BOOST_FOREACH(const COutput& out, vecOutputs)
{
if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth)
continue;
if (setAddress.size())
{
CTxDestination address;
if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
continue;
if (!setAddress.count(address))
continue;
}
int64 nValue = out.tx->vout[out.i].nValue;
const CScript& pk = out.tx->vout[out.i].scriptPubKey;
Object entry;
entry.push_back(Pair("txid", out.tx->GetHash().GetHex()));
entry.push_back(Pair("vout", out.i));
CTxDestination address;
if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
{
entry.push_back(Pair("address", CBitcoinAddress(address).ToString()));
if (pwalletMain->mapAddressBook.count(address))
entry.push_back(Pair("account", pwalletMain->mapAddressBook[address]));
}
entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end())));
if (pk.IsPayToScriptHash())
{
CTxDestination address;
if (ExtractDestination(pk, address))
{
const CScriptID& hash = boost::get<const CScriptID&>(address);
CScript redeemScript;
if (pwalletMain->GetCScript(hash, redeemScript))
entry.push_back(Pair("redeemScript", HexStr(redeemScript.begin(), redeemScript.end())));
}
}
entry.push_back(Pair("amount",ValueFromAmount(nValue)));
entry.push_back(Pair("confirmations",out.nDepth));
results.push_back(entry);
}
return results;
}
Value createrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"createrawtransaction [{\"txid\":txid,\"vout\":n},...] {address:amount,...}\n"
"Create a transaction spending given inputs\n"
"(array of objects containing transaction id and output number),\n"
"sending to given address(es).\n"
"Returns hex-encoded raw transaction.\n"
"Note that the transaction's inputs are not signed, and\n"
"it is not stored in the wallet or transmitted to the network.");
RPCTypeCheck(params, list_of(array_type)(obj_type));
Array inputs = params[0].get_array();
Object sendTo = params[1].get_obj();
CTransaction rawTx;
BOOST_FOREACH(const Value& input, inputs)
{
const Object& o = input.get_obj();
uint256 txid = ParseHashO(o, "txid");
const Value& vout_v = find_value(o, "vout");
if (vout_v.type() != int_type)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
int nOutput = vout_v.get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
CTxIn in(COutPoint(txid, nOutput));
rawTx.vin.push_back(in);
}
set<CBitcoinAddress> setAddress;
BOOST_FOREACH(const Pair& s, sendTo)
{
CBitcoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid BitcoinPositive address: ")+s.name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_);
setAddress.insert(address);
CScript scriptPubKey;
scriptPubKey.SetDestination(address.Get());
int64 nAmount = AmountFromValue(s.value_);
CTxOut out(nAmount, scriptPubKey);
rawTx.vout.push_back(out);
}
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << rawTx;
return HexStr(ss.begin(), ss.end());
}
Value decoderawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"decoderawtransaction <hex string>\n"
"Return a JSON object representing the serialized, hex-encoded transaction.");
vector<unsigned char> txData(ParseHexV(params[0], "argument"));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
try {
ssData >> tx;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
Object result;
TxToJSON(tx, 0, result);
return result;
}
Value signrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 4)
throw runtime_error(
"signrawtransaction <hex string> [{\"txid\":txid,\"vout\":n,\"scriptPubKey\":hex,\"redeemScript\":hex},...] [<privatekey1>,...] [sighashtype=\"ALL\"]\n"
"Sign inputs for raw transaction (serialized, hex-encoded).\n"
"Second optional argument (may be null) is an array of previous transaction outputs that\n"
"this transaction depends on but may not yet be in the block chain.\n"
"Third optional argument (may be null) is an array of base58-encoded private\n"
"keys that, if given, will be the only keys used to sign the transaction.\n"
"Fourth optional argument is a string that is one of six values; ALL, NONE, SINGLE or\n"
"ALL|ANYONECANPAY, NONE|ANYONECANPAY, SINGLE|ANYONECANPAY.\n"
"Returns json object with keys:\n"
" hex : raw transaction with signature(s) (hex-encoded string)\n"
" complete : 1 if transaction has a complete set of signature (0 if not)"
+ HelpRequiringPassphrase());
RPCTypeCheck(params, list_of(str_type)(array_type)(array_type)(str_type), true);
vector<unsigned char> txData(ParseHexV(params[0], "argument 1"));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
vector<CTransaction> txVariants;
while (!ssData.empty())
{
try {
CTransaction tx;
ssData >> tx;
txVariants.push_back(tx);
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
}
if (txVariants.empty())
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction");
// mergedTx will end up with all the signatures; it
// starts as a clone of the rawtx:
CTransaction mergedTx(txVariants[0]);
bool fComplete = true;
// Fetch previous transactions (inputs):
CCoinsView viewDummy;
CCoinsViewCache view(viewDummy);
{
LOCK(mempool.cs);
CCoinsViewCache &viewChain = *pcoinsTip;
CCoinsViewMemPool viewMempool(viewChain, mempool);
view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
BOOST_FOREACH(const CTxIn& txin, mergedTx.vin) {
const uint256& prevHash = txin.prevout.hash;
CCoins coins;
view.GetCoins(prevHash, coins); // this is certainly allowed to fail
}
view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
}
bool fGivenKeys = false;
CBasicKeyStore tempKeystore;
if (params.size() > 2 && params[2].type() != null_type)
{
fGivenKeys = true;
Array keys = params[2].get_array();
BOOST_FOREACH(Value k, keys)
{
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(k.get_str());
if (!fGood)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
CKey key = vchSecret.GetKey();
tempKeystore.AddKey(key);
}
}
else
EnsureWalletIsUnlocked();
// Add previous txouts given in the RPC call:
if (params.size() > 1 && params[1].type() != null_type)
{
Array prevTxs = params[1].get_array();
BOOST_FOREACH(Value& p, prevTxs)
{
if (p.type() != obj_type)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
Object prevOut = p.get_obj();
RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type));
uint256 txid = ParseHashO(prevOut, "txid");
int nOut = find_value(prevOut, "vout").get_int();
if (nOut < 0)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));
CScript scriptPubKey(pkData.begin(), pkData.end());
CCoins coins;
if (view.GetCoins(txid, coins)) {
if (coins.IsAvailable(nOut) && coins.vout[nOut].scriptPubKey != scriptPubKey) {
string err("Previous output scriptPubKey mismatch:\n");
err = err + coins.vout[nOut].scriptPubKey.ToString() + "\nvs:\n"+
scriptPubKey.ToString();
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);
}
// what todo if txid is known, but the actual output isn't?
}
if ((unsigned int)nOut >= coins.vout.size())
coins.vout.resize(nOut+1);
coins.vout[nOut].scriptPubKey = scriptPubKey;
coins.vout[nOut].nValue = 0; // we don't know the actual output value
view.SetCoins(txid, coins);
// if redeemScript given and not using the local wallet (private keys
// given), add redeemScript to the tempKeystore so it can be signed:
if (fGivenKeys && scriptPubKey.IsPayToScriptHash())
{
RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type)("redeemScript",str_type));
Value v = find_value(prevOut, "redeemScript");
if (!(v == Value::null))
{
vector<unsigned char> rsData(ParseHexV(v, "redeemScript"));
CScript redeemScript(rsData.begin(), rsData.end());
tempKeystore.AddCScript(redeemScript);
}
}
}
}
const CKeyStore& keystore = ((fGivenKeys || !pwalletMain) ? tempKeystore : *pwalletMain);
int nHashType = SIGHASH_ALL;
if (params.size() > 3 && params[3].type() != null_type)
{
static map<string, int> mapSigHashValues =
boost::assign::map_list_of
(string("ALL"), int(SIGHASH_ALL))
(string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))
(string("NONE"), int(SIGHASH_NONE))
(string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY))
(string("SINGLE"), int(SIGHASH_SINGLE))
(string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY))
;
string strHashType = params[3].get_str();
if (mapSigHashValues.count(strHashType))
nHashType = mapSigHashValues[strHashType];
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param");
}
bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
// Sign what we can:
for (unsigned int i = 0; i < mergedTx.vin.size(); i++)
{
CTxIn& txin = mergedTx.vin[i];
CCoins coins;
if (!view.GetCoins(txin.prevout.hash, coins) || !coins.IsAvailable(txin.prevout.n))
{
fComplete = false;
continue;
}
const CScript& prevPubKey = coins.vout[txin.prevout.n].scriptPubKey;
txin.scriptSig.clear();
// Only sign SIGHASH_SINGLE if there's a corresponding output:
if (!fHashSingle || (i < mergedTx.vout.size()))
SignSignature(keystore, prevPubKey, mergedTx, i, nHashType);
// ... and merge in other signatures:
BOOST_FOREACH(const CTransaction& txv, txVariants)
{
txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig);
}
if (!VerifyScript(txin.scriptSig, prevPubKey, mergedTx, i, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC, 0))
fComplete = false;
}
Object result;
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << mergedTx;
result.push_back(Pair("hex", HexStr(ssTx.begin(), ssTx.end())));
result.push_back(Pair("complete", fComplete));
return result;
}
Value sendrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"sendrawtransaction <hex string> [allowhighfees=false]\n"
"Submits raw transaction (serialized, hex-encoded) to local node and network.");
// parse hex string from parameter
vector<unsigned char> txData(ParseHexV(params[0], "parameter"));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
bool fOverrideFees = false;
if (params.size() > 1)
fOverrideFees = params[1].get_bool();
// deserialize binary data stream
try {
ssData >> tx;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
uint256 hashTx = tx.GetHash();
bool fHave = false;
CCoinsViewCache &view = *pcoinsTip;
CCoins existingCoins;
{
fHave = view.GetCoins(hashTx, existingCoins);
if (!fHave) {
// push to local node
CValidationState state;
if (!tx.AcceptToMemoryPool(state, true, false, NULL, !fOverrideFees))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX rejected"); // TODO: report validation state
}
}
if (fHave) {
if (existingCoins.nHeight < 1000000000)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "transaction already in block chain");
// Not in block, but already in the memory pool; will drop
// through to re-relay it.
} else {
SyncWithWallets(hashTx, tx, NULL, true);
}
RelayTransaction(tx, hashTx);
return hashTx.GetHex();
}
Value getnormalizedtxid(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getnormalizedtxid <hex string>\n"
"Return the normalized transaction ID.");
// parse hex string from parameter
vector<unsigned char> txData(ParseHexV(params[0], "parameter"));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
// deserialize binary data stream
try {
ssData >> tx;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
uint256 hashNormalized = tx.GetNormalizedHash();
return hashNormalized.GetHex();
}
| [
"[email protected]"
] | |
10e7a3db1782418e81456090bc58081689c9a968 | 7d71fa3604d4b0538f19ed284bc5c7d8b52515d2 | /Clients/AG/AgOutlookAddIn/Outlook.cpp | f6f72b7ad318b2fd34ab6407bc330a8d74619614 | [] | no_license | lineCode/ArchiveGit | 18e5ddca06330018e4be8ab28c252af3220efdad | f9cf965cb7946faa91b64e95fbcf8ad47f438e8b | refs/heads/master | 2020-12-02T09:59:37.220257 | 2016-01-20T23:55:26 | 2016-01-20T23:55:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,804 | cpp | #include "stdafx.h"
#include "resource.h"
#include "Outlook.h"
#include "MapiAdmin.h"
// Note: Namespace class member has changed to _Namespace in Outlook 2000 and 2002
// #include "msoutl8.h" // Outlook 97
// #include "msoutl85.h" // Outlook 98
// #include "msoutl9.h" // Outlook 2000
// #include "msoutl.h" // Outlook 2002
// #include "msoe.h" // Outlook Express
/////////////////////////////////////////////////////////////////////////////
COutlook::COutlook(IDispatch* pApplication)
{
m_pApplication = pApplication;
}
/////////////////////////////////////////////////////////////////////////////
void COutlook::MapiSendmail()
{
CMapiAdmin mapi;
// MAPI_NEW_SESSION|MAPI_TIMEOUT_SHORT
//j HWND hWndParent = AfxGetMainWnd()->GetSafeHwnd();
if (!mapi.Logon(NULL/*hWndParent*/, NULL/*lpszProfileName*/, NULL/*lpszPassword*/, 0/*flFlags*/))
return;
LPCTSTR ppRecipients[1] = {"[email protected]"};
mapi.CreateMessage(1, ppRecipients, "About our meeting", "Here is a test message", true);
if (mapi.SendMessage())
MessageBox(NULL, "Message sent successfully", "Sent", MB_OK);
}
/////////////////////////////////////////////////////////////////////////////
void COutlook::AddContact()
{
Outlook::_ApplicationPtr pOutlook(m_pApplication);
// Logon. Doesn't hurt if you are already running and logged on
_NameSpacePtr pOutlookNamespace;
pOutlook->GetNamespace(CComBSTR("MAPI"), &pOutlookNamespace);
CComVariant varOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
pOutlookNamespace->Logon(varOptional, varOptional, varOptional, varOptional);
// Create a new contact
IDispatchPtr pCreateDispatch;
pOutlook->CreateItem(Outlook::olContactItem, &pCreateDispatch);
Outlook::_ContactItemPtr pContact(pCreateDispatch);
// Setup Contact information
pContact->put_FullName(CComBSTR("James Smith"));
//j pContact->put_Birthday(CComDateTime(1975,9,15/*nYear,nMonth,nDay*/, 0,0,0/*nHour,nMin,nSec*/));
pContact->put_CompanyName(CComBSTR("Microsoft"));
pContact->put_HomeTelephoneNumber(CComBSTR("704-555-8888"));
pContact->put_Email1Address(CComBSTR("[email protected]"));
pContact->put_JobTitle(CComBSTR("Developer"));
pContact->put_HomeAddress(CComBSTR("111 Main St.\nCharlotte, NC 28226"));
// Save Contact
//j pContact->Save();
// Display
pContact->Display(CComVariant((long)false/*bModal*/));
pOutlookNamespace->Logoff();
}
/////////////////////////////////////////////////////////////////////////////
void COutlook::AddAppointment()
{
Outlook::_ApplicationPtr pOutlook(m_pApplication);
// Logon. Doesn't hurt if you are already running and logged on
_NameSpacePtr pOutlookNamespace;
pOutlook->GetNamespace(CComBSTR("MAPI"), &pOutlookNamespace);
CComVariant varOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
pOutlookNamespace->Logon(varOptional, varOptional, varOptional, varOptional);
// Create a new appointment
IDispatchPtr pCreateDispatch;
pOutlook->CreateItem(Outlook::olAppointmentItem, &pCreateDispatch);
Outlook::_AppointmentItemPtr pAppointment(pCreateDispatch);
// Schedule it for two minutes from now
COleDateTime apptDate = COleDateTime::GetCurrentTime();
pAppointment->put_Start((DATE)apptDate + DATE(2.0/(24.0*60.0)));
// Set other appointment info
pAppointment->put_Duration(60);
pAppointment->put_Subject(CComBSTR("Meeting to discuss plans"));
pAppointment->put_Body(CComBSTR("Meeting with James to discuss plans."));
pAppointment->put_Location(CComBSTR("Home Office"));
pAppointment->put_ReminderMinutesBeforeStart(1);
pAppointment->put_ReminderSet(TRUE);
// Save the appointment
//j pAppointment->Save();
// Display
pAppointment->Display(CComVariant((long)false/*bModal*/));
pOutlookNamespace->Logoff();
}
| [
"[email protected]"
] | |
d6bb8d4c4ce15fb7d5fd9774ce73bbe419ab9455 | da00f367cf627944bf2e70fde1ac740c9cd50f42 | /windows_ce_4_2_081231/WINCE420/PRIVATE/SERVERS/UPNP/UPNPCAPI/upnpcapi.cpp | 9f862334dc8f5d3db80c2f528c854c7c60b7803e | [] | no_license | xiaoqgao/windows_ce_4_2_081231 | 9a5c427aa00f93ca8994cf80ec1777a309544a5d | 2e397f2929a998e72034e3a350fc57d8dc10eaa9 | refs/heads/master | 2022-12-21T20:19:38.308851 | 2020-09-28T19:59:38 | 2020-09-28T19:59:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,096 | cpp | //
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// This source code is licensed under Microsoft Shared Source License
// Version 1.0 for Windows CE.
// For a copy of the license visit http://go.microsoft.com/fwlink/?LinkId=3223.
//
#include <windows.h>
#include <ssdppch.h>
#include <upnpdevapi.h>
#include <ssdpapi.h>
#include <ssdpioctl.h>
#include <service.h>
#include "ssdpfuncc.h"
#include "string.hxx"
#define celems(_x) (sizeof(_x) / sizeof(_x[0]))
BOOL InitCallbackTarget(PCWSTR pszName, PUPNPCALLBACK pfCallback, PVOID pvContext, DWORD *phCallback);
BOOL StopCallbackTarget(PCWSTR pszName);
//LONG cInitialized = 0;
HANDLE g_hUPNPSVC = INVALID_HANDLE_VALUE; // handle to SSDP service
CRITICAL_SECTION g_csUPNPAPI;
static DWORD cbBytesReturned; // not used
int ClientStop();
int ClientStart()
{
EnterCriticalSection(&g_csUPNPAPI);
DBGCHK(L"UPNPAPI", g_hUPNPSVC == INVALID_HANDLE_VALUE);
if (g_hUPNPSVC == INVALID_HANDLE_VALUE)
{
// Try to open the SSDP service
g_hUPNPSVC = CreateFile(TEXT("UPP1:"),
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ|FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, 0, 0);
DWORD dwBytesReturned;
DeviceIoControl(g_hUPNPSVC, IOCTL_SERVICE_START, NULL, 0, NULL, 0, &dwBytesReturned, NULL);
}
LeaveCriticalSection(&g_csUPNPAPI);
return (g_hUPNPSVC != INVALID_HANDLE_VALUE);
}
int ClientStop()
{
EnterCriticalSection(&g_csUPNPAPI);
if (g_hUPNPSVC != INVALID_HANDLE_VALUE)
{
CloseHandle(g_hUPNPSVC);
g_hUPNPSVC = INVALID_HANDLE_VALUE;
}
LeaveCriticalSection(&g_csUPNPAPI);
return TRUE;
}
/*
Device creation
*/
BOOL
WINAPI
UpnpAddDevice(IN UPNPDEVICEINFO *pDev)
{
BOOL fRet = FALSE;
struct AddDeviceParams parms = {pDev};
DWORD dwCallbackHandle;
if (g_hUPNPSVC == INVALID_HANDLE_VALUE)
{
ClientStart();
}
fRet = InitCallbackTarget(pDev->pszDeviceName, pDev->pfCallback, pDev->pvUserDevContext, &dwCallbackHandle);
if (fRet)
{
PVOID pvTemp = pDev->pvUserDevContext;
pDev->pvUserDevContext = (PVOID)dwCallbackHandle;
fRet = DeviceIoControl(
g_hUPNPSVC,
UPNP_IOCTL_ADD_DEVICE,
&parms, sizeof(parms),
NULL, 0,
&cbBytesReturned, NULL);
// restore the changed parameters
pDev->pvUserDevContext = pvTemp;
if (!fRet)
{
StopCallbackTarget(pDev->pszDeviceName);
}
}
return fRet;
}
BOOL
WINAPI
UpnpRemoveDevice(
PCWSTR pszDeviceName)
{
BOOL fRet;
if (g_hUPNPSVC == INVALID_HANDLE_VALUE)
{
ClientStart();
}
fRet = DeviceIoControl(
g_hUPNPSVC,
UPNP_IOCTL_REMOVE_DEVICE,
(PVOID)pszDeviceName, (wcslen(pszDeviceName)+1)*sizeof(WCHAR),
NULL, 0,
&cbBytesReturned, NULL);
StopCallbackTarget(pszDeviceName); // this may fail if the target has already been removed
return fRet;
}
/*
Publication control
*/
BOOL
WINAPI
UpnpPublishDevice(
PCWSTR pszDeviceName)
{
if (g_hUPNPSVC == INVALID_HANDLE_VALUE)
{
ClientStart();
}
return DeviceIoControl(
g_hUPNPSVC,
UPNP_IOCTL_PUBLISH_DEVICE,
(PVOID)pszDeviceName, (wcslen(pszDeviceName)+1)*sizeof(WCHAR),
NULL, 0,
&cbBytesReturned, NULL);
}
BOOL
WINAPI
UpnpUnpublishDevice(
PCWSTR pszDeviceName)
{
if (g_hUPNPSVC == INVALID_HANDLE_VALUE)
{
ClientStart();
}
return DeviceIoControl(
g_hUPNPSVC,
UPNP_IOCTL_UNPUBLISH_DEVICE,
(PVOID)pszDeviceName, (wcslen(pszDeviceName)+1)*sizeof(WCHAR),
NULL, 0,
&cbBytesReturned, NULL);
}
/*
Description info
*/
BOOL
WINAPI
UpnpGetUDN(
IN PCWSTR pszDeviceName, // [in] local device name
IN PCWSTR pszTemplateUDN, // [in, optional] the UDN element in the original device description
OUT PWSTR pszUDNBuf, // [in] buffer to hold the assigned UDN
IN OUT PDWORD pchBuf) // [in,out] size of buffer/ length filled (in WCHARs)
{
struct GetUDNParams parms = {pszDeviceName, pszTemplateUDN, pszUDNBuf, pchBuf};
if (g_hUPNPSVC == INVALID_HANDLE_VALUE)
{
ClientStart();
}
return DeviceIoControl(
g_hUPNPSVC,
UPNP_IOCTL_GET_UDN,
&parms, sizeof(parms),
NULL, 0,
&cbBytesReturned, NULL);
}
BOOL
WINAPI
UpnpGetSCPDPath(
IN PCWSTR pszDeviceName, // [in] local device name
IN PCWSTR pszUDN,
IN PCWSTR pszServiceId, // [in] serviceId (from device description)
OUT PWSTR pszSCPDPath, // [out] file path to SCPD
IN DWORD cchFilePath) // [in] size of pszSCPDFilePath in WCHARs
{
struct GetSCPDPathParams parms= {pszDeviceName, pszUDN, pszServiceId, pszSCPDPath, cchFilePath};
if (g_hUPNPSVC == INVALID_HANDLE_VALUE)
{
ClientStart();
}
return DeviceIoControl(
g_hUPNPSVC,
UPNP_IOCTL_GET_SCPD_PATH,
&parms, sizeof(parms),
NULL, 0,
&cbBytesReturned, NULL);
}
/*
Eventing
*/
BOOL
WINAPI
UpnpSubmitPropertyEvent(
PCWSTR pszDeviceName,
PCWSTR pszUDN,
PCWSTR pszServiceName,
DWORD nArgs,
UPNPPARAM *rgArgs)
{
struct SubmitPropertyEventParams parms = {pszDeviceName, pszUDN, pszServiceName, nArgs, rgArgs};
if (g_hUPNPSVC == INVALID_HANDLE_VALUE)
{
ClientStart();
}
return DeviceIoControl(
g_hUPNPSVC,
UPNP_IOCTL_SUBMIT_PROPERTY_EVENT,
&parms, sizeof(parms),
NULL, 0,
&cbBytesReturned, NULL);
}
bool EncodeForXML(LPCWSTR pwsz, ce::wstring* pstr)
{
wchar_t aCharacters[] = {L'<', L'>', L'\'', L'"', L'&'};
wchar_t* aEntityReferences[] = {L"<", L">", L"'", L""", L"&"};
bool bReplaced;
pstr->reserve(static_cast<ce::wstring::size_type>(1.1 * wcslen(pwsz)));
pstr->resize(0);
for(const wchar_t* pwch = pwsz; *pwch; ++pwch)
{
bReplaced = false;
for(int i = 0; i < sizeof(aCharacters)/sizeof(*aCharacters); ++i)
if(*pwch == aCharacters[i])
{
pstr->append(aEntityReferences[i]);
bReplaced = true;
break;
}
if(!bReplaced)
pstr->append(pwch, 1);
}
return true;
}
/*
<s:Envelope
xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"
s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<s:Body>
<u:actionNameResponse xmlns:u="urn:schemas-upnp-org:service:serviceType:v">
<argumentName>out arg value</argumentName>
other out args and their values go here, if any
</u:actionNameResponse>
</s:Body>
</s:Envelope>
*/
const WCHAR c_szSOAPResp1[] = L"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" \r\n"
L"s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\r\n"
L" <s:Body>\r\n"
L" <u:%sResponse xmlns:u=\"%s\">\r\n";
const WCHAR c_szSOAPResp2[] = L" </u:%sResponse>\r\n"
L" </s:Body>\r\n"
L"</s:Envelope>\r\n";
const WCHAR c_szSOAPArg[] = L"<%s>%s</%s>\r\n";
static bool _UpnpSetControlResponse(
UPNPSERVICECONTROL *pUPNPAction,
DWORD cOutArgs,
UPNPPARAM *aOutArg,
PWSTR* ppszRawResp)
{
int cch = celems(c_szSOAPResp1) + celems(c_szSOAPResp2), cch2;
ce::wstring str;
DWORD i;
// force out argument for QueryStateVariable to be "return"
if (wcscmp(pUPNPAction->pszAction, L"QueryStateVariable") == 0 && cOutArgs == 1)
aOutArg[0].pszName = L"return";
cch += 2*wcslen(pUPNPAction->pszAction) + wcslen(pUPNPAction->pszServiceType);
for (i=0; i < cOutArgs; i++)
{
EncodeForXML(aOutArg[i].pszValue, &str);
cch += wcslen(c_szSOAPArg) + 2*wcslen(aOutArg[i].pszName) + str.length();
}
*ppszRawResp = new WCHAR [cch];
if (!*ppszRawResp)
return false;
cch2 = wsprintfW(*ppszRawResp,c_szSOAPResp1,pUPNPAction->pszAction, pUPNPAction->pszServiceType);
for (i=0; i < cOutArgs; i++)
{
EncodeForXML(aOutArg[i].pszValue, &str);
cch2+=wsprintfW(*ppszRawResp + cch2, c_szSOAPArg, aOutArg[i].pszName, static_cast<LPCWSTR>(str), aOutArg[i].pszName);
}
cch2 += wsprintfW(*ppszRawResp + cch2, c_szSOAPResp2, pUPNPAction->pszAction);
DBGCHK(L"UPNPAPI", cch2 < cch);
return true;
}
BOOL
WINAPI
UpnpSetControlResponse(
UPNPSERVICECONTROL *pUPNPAction,
DWORD cOutArgs,
UPNPPARAM *aOutArg)
{
BOOL fRet = FALSE;
PWSTR pszRawResp = NULL;
__try
{
fRet = _UpnpSetControlResponse(pUPNPAction, cOutArgs, aOutArg, &pszRawResp);
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
SetLastError(ERROR_INVALID_PARAMETER);
fRet = FALSE;
}
if (fRet)
fRet = UpnpSetRawControlResponse(pUPNPAction,HTTP_STATUS_OK, pszRawResp);
if (pszRawResp)
delete[] pszRawResp;
return fRet;
}
const WCHAR c_szSOAPFault[]= L"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"\r\n"
L" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\r\n"
L" <s:Body>\r\n"
L" <s:Fault>\r\n"
L" <faultcode>s:Client</faultcode>\r\n"
L" <faultstring>UPnPError</faultstring>\r\n"
L" <detail>\r\n"
L" <UPnPError xmlns=\"urn:schemas-upnp-org:control-1-0\">\r\n"
L" <errorCode>%d</errorCode>\r\n"
L" <errorDescription>%s</errorDescription>\r\n"
L" </UPnPError>\r\n"
L" </detail>\r\n"
L" </s:Fault>\r\n"
L" </s:Body>\r\n"
L" </s:Envelope>\r\n";
static bool _UpnpSetErrorResponse(
UPNPSERVICECONTROL *pUPNPAction,
DWORD dwErrorCode,
PCWSTR pszErrorDescription, // error code and description
PWSTR* ppszRawResp)
{
int cch;
ce::wstring strErrorDescription;
EncodeForXML(pszErrorDescription, &strErrorDescription);
cch = strErrorDescription.length() + 10 + celems(c_szSOAPFault);
*ppszRawResp = new WCHAR [cch];
if (!*ppszRawResp)
return false;
cch -= wsprintfW(*ppszRawResp, c_szSOAPFault, dwErrorCode, static_cast<LPCWSTR>(strErrorDescription));
DBGCHK(L"UPNPAPI",cch > 0);
return true;
}
BOOL
WINAPI
UpnpSetErrorResponse(
UPNPSERVICECONTROL *pUPNPAction,
DWORD dwErrorCode,
PCWSTR pszErrorDescription // error code and description
)
{
BOOL fRet = FALSE;
PWSTR pszRawResp = NULL;
__try
{
fRet = _UpnpSetErrorResponse(pUPNPAction, dwErrorCode, pszErrorDescription, &pszRawResp);
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
SetLastError(ERROR_INVALID_PARAMETER);
fRet = FALSE;
}
if (fRet)
fRet = UpnpSetRawControlResponse(pUPNPAction, HTTP_STATUS_SERVER_ERROR, pszRawResp);
if (pszRawResp)
delete[] pszRawResp;
return fRet;
}
#ifdef DEBUG
DBGPARAM dpCurSettings = {
TEXT("UPNPCAPI"), {
TEXT("Misc"), TEXT("Init"), TEXT("Announce"), TEXT("Events"),
TEXT("Socket"),TEXT("Search"), TEXT("Parser"),TEXT("Timer"),
TEXT("Cache"),TEXT("Control"),TEXT("Cache"),TEXT(""),
TEXT(""),TEXT(""),TEXT("Trace"),TEXT("Error") },
0x0000806f
};
#endif
//extern CRITICAL_SECTION g_csSSDPAPI;
extern "C"
BOOL
WINAPI
DllMain(IN PVOID DllHandle,
IN ULONG Reason,
IN PVOID Context OPTIONAL)
{
switch (Reason)
{
case DLL_PROCESS_ATTACH:
DEBUGREGISTER((HMODULE)DllHandle);
InitializeCriticalSection(&g_csUPNPAPI);
SocketInit();
// We don't need to receive thread attach and detach
// notifications, so disable them to help application
// performance.
DisableThreadLibraryCalls((HMODULE)DllHandle);
svsutil_Initialize();
break;
case DLL_PROCESS_DETACH:
SocketFinish();
ClientStop();
svsutil_DeInitialize();
DeleteCriticalSection(&g_csUPNPAPI);
break;
}
return TRUE;
}
| [
"[email protected]"
] | |
ff0ef350ed9bee28b7b87248c81d45636e86a859 | ada0e80868447865811b0098381db0d43dd63852 | /ProgrammingPractice/Code/C++ Learning/Functors/Example3.cpp | ab6bd1d56bcba9ad178c4d345fca8ab830d77cd0 | [] | no_license | phantom7knight/ProgrammingPracticeSamples | a4bc2fd9fbfc94dbb36ab3e1bfff88c3405df7ab | a13db3ca2bc8ac7af2b87703908455a3d97b2dfe | refs/heads/master | 2023-08-01T01:40:57.933518 | 2021-09-17T04:38:59 | 2021-09-17T04:38:59 | 250,716,167 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,531 | cpp | #include "../../../Helper Functions/Helper.hpp"
//=================================================================================================
//Lambda function example
//=================================================================================================
int main()
{
int m = 0;
int n = 0;
int Tcase = 4;
switch (Tcase)
{
case 0:
{
[&, n](int a) mutable { m = ++n + a; }(15);
//notes
//[&,n] we send m by reference
//(int a) -> this is the arg list which we want to send in the Lambda fn.
//(15) is the value of arg 'a'.
std::cout << m << std::endl << n << std::endl;
}
break;
case 1:
{
[=](int a) mutable {m = ++n + a; }(10);
std::cout << m << std::endl << n << std::endl;
}
break;
{
int aa = 5;
auto Increment = [&] {
++aa;
};
STDPRINTLINE("The value of a which was 5 is inserted into Increment Lambda expr");
STDPRINTLINE("new value of a is");
Increment();
STDPRINTLINE(aa);
}
break;
case 3:
{
auto checkGreater = [](int a, int b)
{
//std::swap(a, b);
if (a > b)
{
STDPRINTLINE("A is bigger");
}
else
{
STDPRINTLINE("B is bigger");
}
};
checkGreater(5, 15);
}
break;
case 4:
{
std::vector<int> vec_here;
//Push data into the vector
for (int i = 0; i < 12; ++i)
{
vec_here.push_back(i);
}
//Lambda expr to find data which is even
std::for_each(vec_here.begin(), vec_here.end(), [=](int num) {
if (num % 2 == 0)
{
STDPRINTLINE(num);
}
});
}
break;
}
return 0;
} | [
"[email protected]"
] | |
91150c232fd4047e36d70be6baef956f8bbb5aad | e8ed22a5cbdf2f00236612d9244f0b7c296ebe0f | /Source/Toon_Tanks/GameModes/TankGameModeBase.cpp | 47aa1c7e0bf36435bf6572efa0d19e3191f51e0e | [] | no_license | MujibBasha/Tanks-War-Game | 16903439f19d491e51b3651d5e91fa218500a876 | 2d0694a4e8ae44c7c216c00900d18abc6b44b29e | refs/heads/main | 2023-01-23T19:30:20.020722 | 2020-11-30T07:53:27 | 2020-11-30T07:53:27 | 317,148,976 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,838 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "TankGameModeBase.h"
#include "Toon_Tanks/Pawns/PawnTank.h"
#include "Toon_Tanks/Pawns/PawnTurret.h"
#include "Kismet/GamePlayStatics.h"
#include "Toon_Tanks/PlayerControllers/PlayerControllerBase.h"
#include "TimerManager.h"
void ATankGameModeBase::BeginPlay()
{
TargetTurrets = GetTargetTurretCount();
PlayerTank = Cast<APawnTank>(UGameplayStatics::GetPlayerPawn(this, 0));
PlayerControllerRef = Cast<APlayerControllerBase>(UGameplayStatics::GetPlayerController(this, 0));
HandleGameStart();
Super::BeginPlay();
}
int32 ATankGameModeBase::GetTargetTurretCount()
{
TSubclassOf<APawnTurret> ClassToFind;
ClassToFind = APawnTurret::StaticClass();
TArray<AActor*> TurretActors;
UGameplayStatics::GetAllActorsOfClass(GetWorld(), ClassToFind, TurretActors);
return TurretActors.Num();;
}
void ATankGameModeBase::ActorDied(AActor* DeadActor)
{
if (DeadActor == PlayerTank)
{
if (PlayerControllerRef) {
PlayerControllerRef->setPlayerEnableState(false);
}
PlayerTank->PawnDestroyed();
HandleGameOver(false);
}
else if (APawnTurret* DestroyTurret = Cast<APawnTurret>(DeadActor))
{
DestroyTurret->PawnDestroyed();
TargetTurrets--;
if (TargetTurrets == 0)
{
HandleGameOver(true);
}
}
}
void ATankGameModeBase::HandleGameStart()
{
GameStart();
if (PlayerControllerRef) {
PlayerControllerRef->setPlayerEnableState(false);
FTimerHandle PlayerEnableHandle;
FTimerDelegate PlayerEnableDelegate = FTimerDelegate::CreateUObject(PlayerControllerRef, &APlayerControllerBase::setPlayerEnableState,true);
GetWorldTimerManager().SetTimer(PlayerEnableHandle,PlayerEnableDelegate,StartDelay,false);
}
}
void ATankGameModeBase::HandleGameOver(bool PlayerWon)
{
GameOver(PlayerWon);
}
| [
"[email protected]"
] | |
b2fe9dac32915bd258854533afaa16319181e9f8 | 8aaca4789239bd08f6422ec95de4782243fbb55e | /FCX/Plugins/Effekseer/Intermediate/Build/Win64/UE4Editor/Inc/EffekseerEd/EffekseerModelFactory.generated.h | 53335dd81091e6b0aa373a2705b981ba3d89bc61 | [] | no_license | mikemikeMyuta/Future-Creation-Exhibition | 0e8572f20a5eff241a0241da5029399e83443714 | d76795f26ad18e09d4bc2836784587476a8c47f1 | refs/heads/master | 2020-08-02T02:24:39.957952 | 2019-10-18T06:44:33 | 2019-10-18T06:44:33 | 211,202,171 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,231 | h | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/ObjectMacros.h"
#include "UObject/ScriptMacros.h"
PRAGMA_DISABLE_DEPRECATION_WARNINGS
#ifdef EFFEKSEERED_EffekseerModelFactory_generated_h
#error "EffekseerModelFactory.generated.h already included, missing '#pragma once' in EffekseerModelFactory.h"
#endif
#define EFFEKSEERED_EffekseerModelFactory_generated_h
#define FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_RPC_WRAPPERS
#define FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_RPC_WRAPPERS_NO_PURE_DECLS
#define FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_INCLASS_NO_PURE_DECLS \
private: \
static void StaticRegisterNativesUEffekseerModelFactory(); \
friend struct Z_Construct_UClass_UEffekseerModelFactory_Statics; \
public: \
DECLARE_CLASS(UEffekseerModelFactory, UFactory, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/EffekseerEd"), NO_API) \
DECLARE_SERIALIZER(UEffekseerModelFactory)
#define FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_INCLASS \
private: \
static void StaticRegisterNativesUEffekseerModelFactory(); \
friend struct Z_Construct_UClass_UEffekseerModelFactory_Statics; \
public: \
DECLARE_CLASS(UEffekseerModelFactory, UFactory, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/EffekseerEd"), NO_API) \
DECLARE_SERIALIZER(UEffekseerModelFactory)
#define FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_STANDARD_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API UEffekseerModelFactory(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UEffekseerModelFactory) \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UEffekseerModelFactory); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UEffekseerModelFactory); \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API UEffekseerModelFactory(UEffekseerModelFactory&&); \
NO_API UEffekseerModelFactory(const UEffekseerModelFactory&); \
public:
#define FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_ENHANCED_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API UEffekseerModelFactory(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()) : Super(ObjectInitializer) { }; \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API UEffekseerModelFactory(UEffekseerModelFactory&&); \
NO_API UEffekseerModelFactory(const UEffekseerModelFactory&); \
public: \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UEffekseerModelFactory); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UEffekseerModelFactory); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UEffekseerModelFactory)
#define FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_PRIVATE_PROPERTY_OFFSET
#define FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_13_PROLOG
#define FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_GENERATED_BODY_LEGACY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_PRIVATE_PROPERTY_OFFSET \
FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_RPC_WRAPPERS \
FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_INCLASS \
FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_STANDARD_CONSTRUCTORS \
public: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#define FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_GENERATED_BODY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_PRIVATE_PROPERTY_OFFSET \
FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_RPC_WRAPPERS_NO_PURE_DECLS \
FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_INCLASS_NO_PURE_DECLS \
FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h_16_ENHANCED_CONSTRUCTORS \
static_assert(false, "Unknown access specifier for GENERATED_BODY() macro in class EffekseerModelFactory."); \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
template<> EFFEKSEERED_API UClass* StaticClass<class UEffekseerModelFactory>();
#undef CURRENT_FILE_ID
#define CURRENT_FILE_ID FCreationExhibition_Plugins_Effekseer_Source_EffekseerEd_Public_EffekseerModelFactory_h
PRAGMA_ENABLE_DEPRECATION_WARNINGS
| [
"[email protected]"
] | |
cf37d9c6a12e2cadbc48bfa80a224ea9409c1cd5 | 36437a87c8110c0a0dd33fd28b312a6bbf1ef716 | /others/pinhole_test.cpp | 11782f16316abdb52c7da03bcabe8c9c91c83450 | [] | no_license | hanebarla/RayTracing_Practice | 17d5b0a03ad42af2cf7efa6fffe4a04c877eb13b | d05079ea02372e47abb3017692299464014d7a8d | refs/heads/master | 2022-12-26T19:54:23.328483 | 2020-10-12T13:41:41 | 2020-10-12T13:41:41 | 298,297,250 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 619 | cpp | #include "libs\vec3.h"
#include "libs\ray.h"
#include "libs\image.h"
#include "libs\camera.h"
int main(){
Image img(512, 512);
PinholeCamera cam(Vec3(0, 0, 0), Vec3(0, 0, -1), 1);
for(int i=0; i<img.width; i++){
for(int j=0; j<img.height; j++){
double u = (2.0*i - img.width)/img.width;
double v = (2.0*j - img.height)/img.height;
Ray ray = cam.getRay(-u, -v);
Vec3 col = (ray.direction + 1.0)/2.0;
img.setPixel(i, j, col);
}
}
img.ppm_output("images\\pinholw_test.ppm");
return 0;
}
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.