blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 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 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
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 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c76901b79ddc1fde28ec5b381a51268310540deb | 5b4613175235957af30f4982b26f58ca7e0d126e | /source/GcLib/directx/VertexBuffer.hpp | 4ffb6df07bdf3bfd8ac74c43be84f856e18db866 | [] | no_license | illusion-star/Touhou-Danmakufu-ph3sx-2 | b6b8596a6fa15a98768239d1ec5ae4f537f2de60 | 3a0f5329aae41f9191ec28c67191882ea303f24f | refs/heads/master | 2023-08-01T18:04:09.349811 | 2021-10-05T03:12:03 | 2021-10-05T03:12:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,436 | hpp | #pragma once
#include "../pch.h"
#include "DxConstant.hpp"
namespace directx {
struct BufferLockParameter {
UINT lockOffset = 0U;
DWORD lockFlag = 0U;
void* data = nullptr;
size_t dataCount = 0U;
size_t dataStride = 1U;
BufferLockParameter() {
lockOffset = 0U;
lockFlag = 0U;
data = nullptr;
dataCount = 0U;
dataStride = 1U;
};
BufferLockParameter(DWORD _lockFlag) {
lockOffset = 0U;
lockFlag = _lockFlag;
data = nullptr;
dataCount = 0U;
dataStride = 1U;
};
BufferLockParameter(void* _data, size_t _count, size_t _stride, DWORD _lockFlag) {
lockOffset = 0U;
lockFlag = _lockFlag;
data = 0U;
dataCount = _count;
dataStride = _stride;
};
template<typename T>
void SetSource(T& vecSrc, size_t countMax, size_t _stride) {
data = vecSrc.data();
dataCount = std::min(countMax, vecSrc.size());
dataStride = _stride;
}
};
class VertexBufferManager;
template<typename T>
class BufferBase {
static_assert(std::is_base_of<IDirect3DResource9, T>::value, "T must be a Direct3D resource");
public:
BufferBase();
BufferBase(IDirect3DDevice9* device);
virtual ~BufferBase();
inline void Release() { ptr_release(buffer_); }
HRESULT UpdateBuffer(BufferLockParameter* pLock);
virtual HRESULT Create() = 0;
T* GetBuffer() { return buffer_; }
size_t GetSize() { return size_; }
size_t GetSizeInBytes() { return sizeInBytes_; }
protected:
IDirect3DDevice9* pDevice_;
T* buffer_;
size_t size_;
size_t stride_;
size_t sizeInBytes_;
};
class FixedVertexBuffer : public BufferBase<IDirect3DVertexBuffer9> {
public:
FixedVertexBuffer(IDirect3DDevice9* device);
virtual ~FixedVertexBuffer();
virtual void Setup(size_t iniSize, size_t stride, DWORD fvf);
virtual HRESULT Create();
private:
DWORD fvf_;
};
class FixedIndexBuffer : public BufferBase<IDirect3DIndexBuffer9> {
public:
FixedIndexBuffer(IDirect3DDevice9* device);
virtual ~FixedIndexBuffer();
virtual void Setup(size_t iniSize, size_t stride, D3DFORMAT format);
virtual HRESULT Create();
private:
D3DFORMAT format_;
};
template<typename T>
class GrowableBuffer : public BufferBase<T> {
public:
GrowableBuffer(IDirect3DDevice9* device);
virtual ~GrowableBuffer();
virtual HRESULT Create() = 0;
virtual void Expand(size_t newSize) = 0;
};
class GrowableVertexBuffer : public GrowableBuffer<IDirect3DVertexBuffer9> {
public:
GrowableVertexBuffer(IDirect3DDevice9* device);
virtual ~GrowableVertexBuffer();
virtual void Setup(size_t iniSize, size_t stride, DWORD fvf);
virtual HRESULT Create();
virtual void Expand(size_t newSize);
private:
DWORD fvf_;
};
class GrowableIndexBuffer : public GrowableBuffer<IDirect3DIndexBuffer9> {
public:
GrowableIndexBuffer(IDirect3DDevice9* device);
virtual ~GrowableIndexBuffer();
virtual void Setup(size_t iniSize, size_t stride, D3DFORMAT format);
virtual HRESULT Create();
virtual void Expand(size_t newSize);
private:
D3DFORMAT format_;
};
class DirectGraphics;
class VertexBufferManager : public DirectGraphicsListener {
static VertexBufferManager* thisBase_;
public:
enum : size_t {
MAX_STRIDE_STATIC = 65536U,
};
VertexBufferManager();
~VertexBufferManager();
static VertexBufferManager* GetBase() { return thisBase_; }
virtual void ReleaseDxResource();
virtual void RestoreDxResource();
virtual bool Initialize(DirectGraphics* graphics);
virtual void Release();
FixedVertexBuffer* GetVertexBufferTLX() { return vertexBuffers_[0]; }
FixedVertexBuffer* GetVertexBufferLX() { return vertexBuffers_[1]; }
FixedVertexBuffer* GetVertexBufferNX() { return vertexBuffers_[2]; }
FixedIndexBuffer* GetIndexBuffer() { return indexBuffer_; }
GrowableVertexBuffer* GetGrowableVertexBuffer() { return vertexBufferGrowable_; }
GrowableIndexBuffer* GetGrowableIndexBuffer() { return indexBufferGrowable_; }
GrowableVertexBuffer* GetInstancingVertexBuffer() { return vertexBuffer_HWInstancing_; }
static void AssertBuffer(HRESULT hr, const std::wstring& bufferID);
private:
/*
* 0 -> TLX
* 1 -> LX
* 2 -> NX
*/
std::vector<FixedVertexBuffer*> vertexBuffers_;
FixedIndexBuffer* indexBuffer_;
GrowableVertexBuffer* vertexBufferGrowable_;
GrowableIndexBuffer* indexBufferGrowable_;
GrowableVertexBuffer* vertexBuffer_HWInstancing_;
virtual void CreateBuffers(IDirect3DDevice9* device);
};
} | [
"32347635+Natashi@users.noreply.github.com"
] | 32347635+Natashi@users.noreply.github.com |
0c7e412c1bb7d289b054db0581581c8870fbda15 | c6b2a8cd924e89e484a2b00b8cc5c8e8a6ed349e | /ArkTransactions.ino | 13d10f5311d1f5b0c9afe4154a53534008eb6ed9 | [] | no_license | PhillipJacobsen/Ark_IOT_BasicDemo1 | 058e1c1080d48b0f1b390d1b0cc94e53a699c87b | 3fba6c96715df914f0f02ee5c5a7b18c9871c1e2 | refs/heads/master | 2020-05-01T12:26:10.263811 | 2019-03-24T23:23:28 | 2019-03-24T23:23:28 | 177,465,556 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,202 | ino | /********************************************************************************
This file contains functions that interact with Ark client C++ API
code here is a hack right now. Just learning the API and working on basic program flow and function
********************************************************************************/
/********************************************************************************
This routine searches the block chain with receive address and page as input parameters
It returns details for 1 transaction if available.
Returns '0' if no transaction exist
returns parameters in
id -> transaction ID
amount -> amount of Arktoshi
senderAddress -> transaction sender address
vendorfield -> 64 Byte vendor field
********************************************************************************/
int searchReceivedTransaction(const char *const address, int page, const char* &id, int &amount, const char* &senderAddress, const char* &vendorField ) {
//Serial.print("\nSearch Received Address: ");
//Serial.println(address);
//Serial.print("\nSearch page: ");
//Serial.println(page );
//const std::map<std::string, std::string>& body_parameters, int limit = 5,
std::string vendorFieldHexString;
vendorFieldHexString = "6964647955";
//std::string transactionSearchResponse = connection.api.transactions.search( {{"vendorFieldHex", vendorFieldHexString}, {"orderBy", "timestamp:asc"} },1,1);
//--------------------------------------------
//peform the API
//sort by oldest transactions first. For simplicity set limit = 1 so we only get 1 transaction returned
std::string transactionSearchResponse = connection.api.transactions.search( {{"recipientId", address}, {"orderBy", "timestamp:asc"} }, 1, page);
/**
transactionSearchResponse return response is a json-formatted object
The "pretty print" version would look something like this:
{
"meta": {
"count": 1,
"pageCount": 16,
"totalCount": 16,
"next": "/api/v2/transactions/search?page=2&limit=1",
"previous": null,
"self": "/api/v2/transactions/search?page=1&limit=1",
"first": "/api/v2/transactions/search?page=1&limit=1",
"last": "/api/v2/transactions/search?page=16&limit=1"
},
"data": [
{
"id": "cf1aad5e14f4edb134269e0dc7f9457093f458a9785ea03914effa3932e7dffe",
"blockId": "1196453921719185829",
"version": 1,
"type": 0,
"amount": 1000000000,
"fee": 1000000,
"sender": "DFcWwEGwBaYCNb1wxGErGN1TJu8QdQYgCt",
"recipient": "DHy5z5XNKXhxztLDpT88iD2ozR7ab5Sw2w",
"signature": "3045022100d55a219edd8690e89a368399084aa8a468629b570e332e0e618e0af83b1a474602200f57b67e628389533b78db915b1139d8529fee133b9198576b30b98ea5a1ce28",
"confirmations": 21771,
"timestamp": {
"epoch": 62689306,
"unix": 1552790506,
"human": "2019-03-17T02:41:46.000Z"
}
}
]
}
*/
//--------------------------------------------
// Print the entire return response string
// Serial.print("\nSearch Result Transactions: ");
// Serial.println(transactionSearchResponse.c_str()); // The response is a 'std::string', to Print on Arduino, we need the c_string type.
//--------------------------------------------
// Deserialize the returned JSON
// All of the returned parameters are parsed which is not necessary but may be usefull for testing.
const size_t capacity = JSON_ARRAY_SIZE(1) + JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(8) + JSON_OBJECT_SIZE(11) + 810;
DynamicJsonBuffer jsonBuffer(capacity);
//this is an exapmle of the JSON string that is returned
//const char* json = "{\"meta\":{\"count\":1,\"pageCount\":16,\"totalCount\":16,\"next\":\"/api/v2/transactions/search?page=2&limit=1\",\"previous\":null,\"self\":\"/api/v2/transactions/search?page=1&limit=1\",\"first\":\"/api/v2/transactions/search?page=1&limit=1\",\"last\":\"/api/v2/transactions/search?page=16&limit=1\"},\"data\":[{\"id\":\"cf1aad5e14f4edb134269e0dc7f9457093f458a9785ea03914effa3932e7dffe\",\"blockId\":\"1196453921719185829\",\"version\":1,\"type\":0,\"amount\":1000000000,\"fee\":1000000,\"sender\":\"DFcWwEGwBaYCNb1wxGErGN1TJu8QdQYgCt\",\"recipient\":\"DHy5z5XNKXhxztLDpT88iD2ozR7ab5Sw2w\",\"signature\":\"3045022100d55a219edd8690e89a368399084aa8a468629b570e332e0e618e0af83b1a474602200f57b67e628389533b78db915b1139d8529fee133b9198576b30b98ea5a1ce28\",\"confirmations\":21771,\"timestamp\":{\"epoch\":62689306,\"unix\":1552790506,\"human\":\"2019-03-17T02:41:46.000Z\"}}]}";
JsonObject& root = jsonBuffer.parseObject(transactionSearchResponse.c_str());
JsonObject& meta = root["meta"];
int meta_count = meta["count"]; // 1
int meta_pageCount = meta["pageCount"]; // 16
int meta_totalCount = meta["totalCount"]; // 16
const char* meta_next = meta["next"]; // "/api/v2/transactions/search?page=3&limit=1"
const char* meta_previous = meta["previous"]; // "/api/v2/transactions/search?page=1&limit=1"
const char* meta_self = meta["self"]; // "/api/v2/transactions/search?page=2&limit=1"
const char* meta_first = meta["first"]; // "/api/v2/transactions/search?page=1&limit=1"
const char* meta_last = meta["last"]; // "/api/v2/transactions/search?page=16&limit=1"
JsonObject& data_0 = root["data"][0];
const char* data_0_id = data_0["id"]; // "8990a1c7772731c1cc8f2671f070fb7919d1cdac54dc5de619447a6e88899585"
const char* data_0_blockId = data_0["blockId"]; // "3154443675765724828"
int data_0_version = data_0["version"]; // 1
int data_0_type = data_0["type"]; // 0
int data_0_amount = data_0["amount"]; // 1
long data_0_fee = data_0["fee"]; // 10000000
const char* data_0_sender = data_0["sender"]; // "DFcWwEGwBaYCNb1wxGErGN1TJu8QdQYgCt"
const char* data_0_recipient = data_0["recipient"]; // "DHy5z5XNKXhxztLDpT88iD2ozR7ab5Sw2w"
const char* data_0_signature = data_0["signature"]; // "30450221008ef28fe9020e1dd26836fc6a1c4d576c022bde9cc14278bc4d6779339c080f7902204946a3c3b2b37fbe4767a9e3d7cb4514faf194c89595cdb280d74af52a76ad21"
const char* data_0_vendorField = data_0["vendorField"]; // "e2620f612a9b9abb96fee4d03391c51e597f8ffbefd7c8db2fbf84e6a5e26c99"
long data_0_confirmations = data_0["confirmations"]; // 74713
JsonObject& data_0_timestamp = data_0["timestamp"];
long data_0_timestamp_epoch = data_0_timestamp["epoch"]; // 62262442
long data_0_timestamp_unix = data_0_timestamp["unix"]; // 1552363642
const char* data_0_timestamp_human = data_0_timestamp["human"]; // "2019-03-12T04:07:22.000Z"
//--------------------------------------------
// The meta parameters that are returned are currently not reliable and are "estimates". Apparently this is due to lower performance nodes
// For this reason I will not use any of the meta parameters
//--------------------------------------------
// the data_0_id parameter will be used to determine if a valid transaction was found.
if (data_0_id == nullptr) {
Serial.print("\n data_0_id is null");
return 0; //no transaction found
}
else {
// Serial.print("\n data_0_id is available");
id = data_0_id;
amount = data_0_amount;
senderAddress = data_0_sender;
vendorField = data_0_vendorField;
}
return 1; //transaction found
}
/********************************************************************************
This routine checks to see if Ark node is syncronized to the chain.
This is a maybe a good way to see if node communication is working correctly.
This might be a good routine to run periodically
Returns True if node is synced
********************************************************************************/
bool checkArkNodeStatus() {
/**
The following method can be used to get the Status of a Node.
This is equivalant to calling '167.114.29.49:4003/api/v2/node/status'
The response should be a json-formatted object
The "pretty print" version would look something like this:
{
"data": {
"synced": true,
"now": 1178395,
"blocksCount": 0
}
}
*/
const auto nodeStatus = connection.api.node.status();
Serial.print("\nNode Status: ");
Serial.println(nodeStatus.c_str()); // The response is a 'std::string', to Print on Arduino, we need the c_string type.
const size_t capacity = JSON_OBJECT_SIZE(1) + JSON_OBJECT_SIZE(3) + 50;
DynamicJsonBuffer jsonBuffer(capacity);
JsonObject& root = jsonBuffer.parseObject(nodeStatus.c_str());
JsonObject& data = root["data"];
bool data_synced = data["synced"]; // true
//long data_now = data["now"]; // 1178395
//int data_blocksCount = data["blocksCount"]; // 0
return data_synced;
/****************************************/
}
/********************************************************************************
This routine will search through all the received transactions of ArkAddress wallet starting from the oldest.
"searching wallet + page#" will be displayed. text will toggle between red/white every received transaction
The page number of the last transaction in the search will be displayed.
This is the page to the most newest receive transaction on the chain.
The final page number is also equal to the total number of received transactions in the wallet.
The routine returns the page number of the most recent transaction.
Empty wallet will return '0' (NOT YET TESTED)
********************************************************************************/
int getMostRecentReceivedTransaction() {
Serial.print("\n\n\nHere are all the transactions in a wallet\n");
int CursorXtemp;
int CursorYtemp;
int page = 1;
while ( searchReceivedTransaction(ArkAddress, page, id, amount, senderAddress, vendorField) ) {
Serial.print("Page: ");
Serial.println(page);
// Serial.print("Transaction id: ");
// Serial.println(id);
// Serial.print("Amount(Arktoshi): ");
// Serial.println(amount);
// Serial.print("Amount(Ark): ");
// Serial.println(float(amount) / 100000000, 8);
// Serial.print("Sender address: ");
// Serial.println(senderAddress);
Serial.print("Vendor Field: ");
Serial.println(vendorField);
tft.setCursor(CursorX, CursorY);
if ( (page & 0x01) == 0) {
tft.setTextColor(ILI9341_WHITE);
tft.print("searching wallet: ");
CursorXtemp = tft.getCursorX();
CursorYtemp = tft.getCursorY();
tft.setTextColor(ILI9341_BLACK);
tft.print(page - 1);
tft.setCursor(CursorXtemp, CursorYtemp);
tft.setTextColor(ILI9341_WHITE);
tft.println(page);
}
else {
tft.setTextColor(ILI9341_RED);
tft.print("searching wallet: ");
CursorXtemp = tft.getCursorX();
CursorYtemp = tft.getCursorY();
tft.setTextColor(ILI9341_BLACK);
tft.print(page - 1);
tft.setCursor(CursorXtemp, CursorYtemp);
tft.setTextColor(ILI9341_RED);
tft.println(page);
//We need to clear the pixels around the page number every time we refresh.
}
page++;
};
tft.setCursor(CursorXtemp, CursorYtemp);
tft.setTextColor(ILI9341_BLACK);
tft.println(page - 1);
Serial.print("No more Transactions ");
Serial.print("\nThe most recent transaction was page #: ");
Serial.println(page - 1);
return page - 1;
}
//quick test routine.
void searchTransaction() {
//const std::map<std::string, std::string>& body_parameters, int limit = 5,
std::string vendorFieldHexString;
vendorFieldHexString = "6964647955";
//std::string transactionSearchResponse = connection.api.transactions.search( {{"vendorFieldHex", vendorFieldHexString}, {"orderBy", "timestamp:asc"} },1,1);
std::string transactionSearchResponse = connection.api.transactions.search( {{"recipientId", ArkAddress}, {"orderBy", "timestamp:asc"} }, 1, 1);
Serial.print("\nSearch Result Transactions: ");
Serial.println(transactionSearchResponse.c_str()); // The response is a 'std::string', to Print on Arduino, we need the c_string type.
}
| [
"33669966+PhillipJacobsen@users.noreply.github.com"
] | 33669966+PhillipJacobsen@users.noreply.github.com |
cc2dcfea52939245f47000c480e053e21ef0e4b9 | 9a3f8c3d4afe784a34ada757b8c6cd939cac701d | /leetFindCorrNodeOfTreeInClone.cpp | 8750b92a73c27e8c0e4e63a06a93df7154ee98d7 | [] | no_license | madhav-bits/Coding_Practice | 62035a6828f47221b14b1d2a906feae35d3d81a8 | f08d6403878ecafa83b3433dd7a917835b4f1e9e | refs/heads/master | 2023-08-17T04:58:05.113256 | 2023-08-17T02:00:53 | 2023-08-17T02:00:53 | 106,217,648 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,344 | cpp | /*
*
//******************************1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree.******************************
https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/description/
*******************************************************************TEST CASES:************************************************************
//These are the examples I had tweaked and worked on.
[7,4,3,null,null,6,19]
3
[8,null,6,null,5,null,4,null,3,null,2,null,1]
4
// Time Complexity: O(n).
// Space Complexity: O(1). // n- total #nodes in the tree.
//********************************************************THIS IS LEET ACCEPTED CODE.***************************************************
*/
//************************************************************Solution 1:************************************************************
//*****************************************************THIS IS LEET ACCEPTED CODE.***********************************************
// Time Complexity: O(n).
// Space Complexity: O(1). // n- total #nodes in the tree.
// This algorithm is iteration based. Here, we iter. over both the trees parallely, whenever we found target node in orig. tree, we
// return the curr. node from the duplicate tree iter.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* iterateTree(TreeNode* node1, TreeNode* node2, TreeNode* target){ // Iter. parallelly on both trees.
if(node1==NULL) return NULL;
if(node1==target) return node2; // If target node found, dup's curr. node is returned.
TreeNode* lt=iterateTree(node1->left, node2->left, target);
if(lt) return lt; // If left subtree has ans, we return ans from the child.
return iterateTree(node1->right, node2->right, target); // If left don't have ans, we return right child's response.
}
TreeNode* getTargetCopy(TreeNode* original, TreeNode* cloned, TreeNode* target) {
return iterateTree(original, cloned, target); // Func. call to start iter. on two trees parallelly.
}
};
| [
"kasamsaimadhavk@gmail.com"
] | kasamsaimadhavk@gmail.com |
94a9f361206b04755a7660397ce84d06744a6353 | 0865e1c71ad4ceb5502377d1d94e672f9ab8b08d | /Greatest_Common_Divisor.cpp | 796187e04528bcf0eea919eb4986fbf042541ab3 | [] | no_license | xznxzy/Algorithm | c57cf9824c7ee96b487851842aa7362ed0adccaf | 7eedb7460e860a735e89e2f6a50054a6e93ba1a5 | refs/heads/master | 2021-09-18T20:35:36.869818 | 2018-07-19T15:27:09 | 2018-07-19T15:27:09 | 105,955,013 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,213 | cpp | //
// main.cpp
// Greatest_Common_Divisor
// 最大公约数
// 1.题目描述:求解两个整数(不能是负数)的最大公约数(要求两数不能同时为0)
// 2.方法:
// (1)穷举法
// (2)相减法
// (3)欧几里得辗转相除法
// (4)欧几里得辗转相除法:递归实现
// Created by zhangying on 10/5/17.
// Copyright © 2017 zhangying. All rights reserved.
//
//穷举法
unsigned long GCD1(unsigned long a, unsigned long b){
if (a == 0) {
return b;
} else if(b == 0){
return a;
} else if(a == b){
return a;
}
unsigned long gcd = a > b ? b : a;
while (gcd > 1) {
if ((a%gcd==0) && (b%gcd==0)) {
return gcd;
}
gcd--;
}
return gcd;
}
//相减法
unsigned long GCD2(unsigned long a, unsigned long b){
if (a == 0) {
return b;
} else if(b == 0){
return a;
} else if(a == b){
return a;
}
unsigned long gcd = 0;
while (a != b) {
//用较大的一个减去较小的一个,直到两者相等,就得到了最大公约数
gcd = a > b ? (a-=b) : (b-=a);
}
return gcd;
}
//欧几里得辗转相除法
unsigned long GCD3(unsigned long a, unsigned long b){
if (a == 0) {
return b;
} else if(b == 0){
return a;
} else if(a == b){
return a;
}
unsigned long mod = a % b;
while (mod != 0) {
a = b;
b = mod;
mod = a % b;
}
return b;
}
//欧几里得辗转相除法:递归实现
unsigned long GCD4(unsigned long a, unsigned long b){
if (b == 0) {
return a;
} else {
return GCD4(b, a % b);
}
}
#include <iostream>
using namespace std;
int main(int argc, const char * argv[]) {
unsigned long a, b;
cout << "Please input a and b: ";
cin >> a >> b;
unsigned long gcd;
gcd = GCD1(a, b);
cout << "1.gcd = " << gcd << endl;
gcd = GCD2(a, b);
cout << "2.gcd = " << gcd << endl;
gcd = GCD3(a, b);
cout << "3.gcd = " << gcd << endl;
gcd = GCD4(a, b);
cout << "4.gcd = " << gcd << endl;
return 0;
}
| [
"ying5@g.clemson.edu"
] | ying5@g.clemson.edu |
7de5d53b837d791d3125a432884b505633281464 | 855521b1d4bbc4a2f42b91bd1c2bf3c0b68c439c | /source/engine/Component.cpp | 62b5ec8a4159291ef98a3e70170e5f930948c63d | [] | no_license | asam139/gameEngine | 30995b6eb64a8679b1daeda8e2746795d3375f08 | 55257426bc02ad3a2292d782d841a5474a6ca900 | refs/heads/master | 2021-09-07T15:01:21.988625 | 2018-02-24T12:12:11 | 2018-02-24T12:12:11 | 115,192,409 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 358 | cpp | //
// Created by Saul Moreno Abril on 04/02/2018.
//
#include "Component.h"
#import "GameObject.h"
const std::size_t Component::Type = std::hash<std::string>()(TO_STRING(Component));
bool Component::IsClassType(const std::size_t classType) const {
return classType == Type;
}
GameObject& Component::getGameObject() const {
return *_gameObject;
} | [
"sam6.13.93@hotmail.com"
] | sam6.13.93@hotmail.com |
a4f6d0e543c002fa28f2ef1867a35dc5e5bf21e6 | b146b54363a20726b3e1dc0ef0fadc82051234f9 | /Lodestar/symbolic/OrdinaryDifferentialEquation.hpp | 8b4520a185ba000261308d0981d36d96e4bc0ccb | [
"BSD-3-Clause"
] | permissive | helkebir/Lodestar | 90a795bbbd7e496313c54e34f68f3527134b88ce | 465eef7fe3994339f29d8976a321715441e28c84 | refs/heads/master | 2022-03-12T23:16:03.981989 | 2022-03-03T05:08:42 | 2022-03-03T05:08:42 | 361,901,401 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,916 | hpp | //
// Created by Hamza El-Kebir on 5/8/21.
//
#ifndef LODESTAR_ORDINARYDIFFERENTIALEQUATION_HPP
#define LODESTAR_ORDINARYDIFFERENTIALEQUATION_HPP
#ifdef LS_USE_GINAC
#include <Eigen/Dense>
#include "ginac/ginac.h"
#include "Lodestar/systems/StateSpace.hpp"
#include <string>
#include <deque>
namespace ls {
namespace symbolic {
class OrdinaryDifferentialEquation {
public:
OrdinaryDifferentialEquation() :
functions_(GiNaC::lst{GiNaC::ex(0)}),
states_(GiNaC::lst{GiNaC::symbol("x")}),
inputs_(GiNaC::lst{GiNaC::symbol("u")}),
time_(GiNaC::symbol("t"))
{
makeSymbolMap();
}
OrdinaryDifferentialEquation(const GiNaC::lst &functions,
const GiNaC::lst &states,
const GiNaC::lst &inputs) :
functions_(functions),
states_(states),
inputs_(inputs),
time_(GiNaC::symbol("t"))
{
makeSymbolMap();
}
OrdinaryDifferentialEquation(const GiNaC::lst &functions,
const GiNaC::lst &states,
const GiNaC::lst &inputs,
const GiNaC::symbol &time) :
functions_(functions),
states_(states),
inputs_(inputs),
time_(time)
{
makeSymbolMap();
}
GiNaC::exmap generateExpressionMap() const;
GiNaC::exmap generateExpressionMap(
const std::vector<GiNaC::relational> &relationals) const;
GiNaC::exmap
generateExpressionMap(const std::vector<double> &states,
const std::vector<double> &inputs) const;
GiNaC::exmap generateExpressionMap(double t,
const std::vector<double> &states,
const std::vector<double> &inputs) const;
GiNaC::symbol getSymbol(const std::string &symbolName) const;
GiNaC::symbol getStateSymbol(unsigned int i) const;
GiNaC::symbol getInputSymbol(unsigned int i) const;
GiNaC::symbol getTimeSymbol() const;
const GiNaC::lst &getFunctions() const;
void setFunctions(const GiNaC::lst &functions);
const GiNaC::lst &getStates() const;
void setStates(const GiNaC::lst &states);
const GiNaC::lst &getInputs() const;
void setInputs(const GiNaC::lst &inputs);
Eigen::MatrixXd evalf(const GiNaC::exmap &m) const;
Eigen::MatrixXd evalf(const std::vector<double> &states,
const std::vector<double> &inputs) const;
Eigen::MatrixXd
evalf(double t, const std::vector<double> &states,
const std::vector<double> &inputs) const;
GiNaC::matrix generateJacobian(const GiNaC::lst &variables) const;
GiNaC::matrix generateJacobianStates() const;
std::string generateJacobianStatesCppFunc(const std::string &functionName, const bool dynamicType = false) const;
std::string generateJacobianStatesArrayInputCppFunc(const std::string &functionName, const bool dynamicType = false) const;
GiNaC::matrix generateJacobianInputs() const;
std::string generateJacobianInputsCppFunc(const std::string &functionName, const bool dynamicType = false) const;
std::string generateJacobianInputsArrayInputCppFunc(const std::string &functionName, const bool dynamicType = false) const;
Eigen::MatrixXd generateJacobianMatrix(const GiNaC::lst &variables,
const GiNaC::exmap &exmap) const;
Eigen::MatrixXd
generateJacobianMatrix(const GiNaC::matrix &jacobian,
const GiNaC::exmap &exmap) const;
Eigen::MatrixXd
generateJacobianMatrixStates(const GiNaC::exmap &exmap) const;
Eigen::MatrixXd
generateJacobianMatrixInputs(const GiNaC::exmap &exmap) const;
std::string generateMatrixCppFunc(const GiNaC::matrix &ginacMatrix, const std::string &functionName, const bool dynamicType = false) const;
std::string generateMatrixArrayInputCppFunc(const GiNaC::matrix &ginacMatrix, const std::string &functionName, const bool dynamicType = false) const;
systems::StateSpace<> linearize(const GiNaC::exmap &exmap) const;
systems::StateSpace<> linearize(const std::vector<double> &states,
const std::vector<double> &inputs) const;
systems::StateSpace<> linearize(double t,
const std::vector<double> &states,
const std::vector<double> &inputs) const;
systems::StateSpace<> linearize(const GiNaC::matrix &jacobianStates,
const GiNaC::matrix &jacobianInputs,
const GiNaC::exmap &exmap) const;
systems::StateSpace<> linearize(const GiNaC::matrix &jacobianStates,
const GiNaC::matrix &jacobianInputs,
const std::vector<double> &states,
const std::vector<double> &inputs) const;
systems::StateSpace<> linearize(const GiNaC::matrix &jacobianStates,
const GiNaC::matrix &jacobianInputs,
double t,
const std::vector<double> &states,
const std::vector<double> &inputs) const;
static Eigen::MatrixXd matrixToMatrixXd(const GiNaC::matrix &mat);
static Eigen::MatrixXd matrixToMatrixXd(const GiNaC::ex &ex);
protected:
GiNaC::lst functions_;
GiNaC::symbol time_;
GiNaC::lst states_;
GiNaC::lst inputs_;
std::map<std::string, GiNaC::symbol> symbolMap_;
void makeSymbolMap();
static void replaceString(std::string &str, const std::string &source, const std::string &dest);
static void replaceStringAll(std::string &str, const std::string &source, const std::string &dest);
static std::string stripWhiteSpace(std::string &str);
};
}
}
#endif
#endif //LODESTAR_ORDINARYDIFFERENTIALEQUATION_HPP
| [
"ha.elkebir@gmail.com"
] | ha.elkebir@gmail.com |
6863f703f8a40aa48fb126df24b08bada6792cb7 | a5f35d0dfaddb561d3595c534b6b47f304dbb63d | /Source/BansheeCore/Resources/BsResourceHandle.h | 88e80c13582a6729171af50d4b67fdd846238c81 | [] | no_license | danielkrupinski/BansheeEngine | 3ff835e59c909853684d4985bd21bcfa2ac86f75 | ae820eb3c37b75f2998ddeaf7b35837ceb1bbc5e | refs/heads/master | 2021-05-12T08:30:30.564763 | 2018-01-27T12:55:25 | 2018-01-27T12:55:25 | 117,285,819 | 1 | 0 | null | 2018-01-12T20:38:41 | 2018-01-12T20:38:41 | null | UTF-8 | C++ | false | false | 11,174 | h | //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
//**************** Copyright (c) 2016 Marko Pintera (marko.pintera@gmail.com). All rights reserved. **********************//
#pragma once
#include "Reflection/BsIReflectable.h"
#include "Utility/BsUUID.h"
namespace bs
{
/** @addtogroup Implementation
* @{
*/
/** Data that is shared between all resource handles. */
struct BS_CORE_EXPORT ResourceHandleData
{
ResourceHandleData()
:mIsCreated(false), mRefCount(0)
{ }
SPtr<Resource> mPtr;
UUID mUUID;
bool mIsCreated;
UINT32 mRefCount;
};
/**
* Represents a handle to a resource. Handles are similar to a smart pointers, but they have two advantages:
* - When loading a resource asynchronously you can be immediately returned the handle that you may use throughout
* the engine. The handle will be made valid as soon as the resource is loaded.
* - Handles can be serialized and deserialized, therefore saving/restoring references to their original resource.
*/
class BS_CORE_EXPORT ResourceHandleBase : public IReflectable
{
public:
virtual ~ResourceHandleBase();
/**
* Checks if the resource is loaded. Until resource is loaded this handle is invalid and you may not get the
* internal resource from it.
*
* @param[in] checkDependencies If true, and if resource has any dependencies, this method will also check if
* they are loaded.
*/
bool isLoaded(bool checkDependencies = true) const;
/**
* Blocks the current thread until the resource is fully loaded.
*
* @note Careful not to call this on the thread that does the loading.
*/
void blockUntilLoaded(bool waitForDependencies = true) const;
/**
* Releases an internal reference to this resource held by the resources system, if there is one.
*
* @see Resources::release(ResourceHandleBase&)
*/
void release();
/** Returns the UUID of the resource the handle is referring to. */
const UUID& getUUID() const { return mData != nullptr ? mData->mUUID : UUID::EMPTY; }
public: // ***** INTERNAL ******
/** @name Internal
* @{
*/
/** Gets the handle data. For internal use only. */
const SPtr<ResourceHandleData>& getHandleData() const { return mData; }
/** @} */
protected:
ResourceHandleBase();
/** Destroys the resource the handle is pointing to. */
void destroy();
/**
* Sets the created flag to true and assigns the resource pointer. Called by the constructors, or if you
* constructed just using a UUID, then you need to call this manually before you can access the resource from
* this handle.
*
* @note
* This is needed because two part construction is required due to multithreaded nature of resource loading.
* @note
* Internal method.
*/
void setHandleData(const SPtr<Resource>& ptr, const UUID& uuid);
/** Increments the reference count of the handle. Only to be used by Resources for keeping internal references. */
void addInternalRef();
/** Decrements the reference count of the handle. Only to be used by Resources for keeping internal references. */
void removeInternalRef();
/**
* @note
* All handles to the same source must share this same handle data. Otherwise things like counting number of
* references or replacing pointed to resource become impossible without additional logic. */
SPtr<ResourceHandleData> mData;
private:
friend class Resources;
static Signal mResourceCreatedCondition;
static Mutex mResourceCreatedMutex;
protected:
void throwIfNotLoaded() const;
};
/**
* @copydoc ResourceHandleBase
*
* Handles differences in reference counting depending if the handle is normal or weak.
*/
template <bool WeakHandle>
class BS_CORE_EXPORT TResourceHandleBase : public ResourceHandleBase
{ };
/** Specialization of TResourceHandleBase for weak handles. Weak handles do no reference counting. */
template<>
class BS_CORE_EXPORT TResourceHandleBase<true> : public ResourceHandleBase
{
public:
virtual ~TResourceHandleBase() { }
protected:
void addRef() { };
void releaseRef() { };
/************************************************************************/
/* RTTI */
/************************************************************************/
public:
friend class WeakResourceHandleRTTI;
static RTTITypeBase* getRTTIStatic();
RTTITypeBase* getRTTI() const override;
};
/** Specialization of TResourceHandleBase for normal (non-weak) handles. */
template<>
class BS_CORE_EXPORT TResourceHandleBase<false> : public ResourceHandleBase
{
public:
virtual ~TResourceHandleBase() { }
protected:
void addRef() { if (mData) mData->mRefCount++; };
void releaseRef()
{
if (mData)
{
mData->mRefCount--;
if (mData->mRefCount == 0)
destroy();
}
};
/************************************************************************/
/* RTTI */
/************************************************************************/
public:
friend class WeakResourceHandleRTTI;
friend class ResourceHandleRTTI;
static RTTITypeBase* getRTTIStatic();
RTTITypeBase* getRTTI() const override;
};
/** @copydoc ResourceHandleBase */
template <typename T, bool WeakHandle>
class TResourceHandle : public TResourceHandleBase<WeakHandle>
{
public:
TResourceHandle()
{ }
/** Copy constructor. */
TResourceHandle(const TResourceHandle<T, WeakHandle>& ptr)
{
this->mData = ptr.getHandleData();
this->addRef();
}
virtual ~TResourceHandle()
{
this->releaseRef();
}
/** Converts a specific handle to generic Resource handle. */
operator TResourceHandle<Resource, WeakHandle>() const
{
TResourceHandle<Resource, WeakHandle> handle;
handle.setHandleData(this->getHandleData());
return handle;
}
/**
* Returns internal resource pointer.
*
* @note Throws exception if handle is invalid.
*/
T* operator->() const { return get(); }
/**
* Returns internal resource pointer and dereferences it.
*
* @note Throws exception if handle is invalid.
*/
T& operator*() const { return *get(); }
/** Clears the handle making it invalid and releases any references held to the resource. */
TResourceHandle<T, WeakHandle>& operator=(std::nullptr_t ptr)
{
this->releaseRef();
this->mData = nullptr;
return *this;
}
/** Normal assignment operator. */
TResourceHandle<T, WeakHandle>& operator=(const TResourceHandle<T, WeakHandle>& rhs)
{
setHandleData(rhs.getHandleData());
return *this;
}
template<class _Ty>
struct Bool_struct
{
int _Member;
};
/**
* Allows direct conversion of handle to bool.
*
* @note This is needed because we can't directly convert to bool since then we can assign pointer to bool and
* that's weird.
*/
operator int Bool_struct<T>::*() const
{
return ((this->mData != nullptr && !this->mData->mUUID.empty()) ? &Bool_struct<T>::_Member : 0);
}
/**
* Returns internal resource pointer and dereferences it.
*
* @note Throws exception if handle is invalid.
*/
T* get() const
{
this->throwIfNotLoaded();
return reinterpret_cast<T*>(this->mData->mPtr.get());
}
/**
* Returns the internal shared pointer to the resource.
*
* @note Throws exception if handle is invalid.
*/
SPtr<T> getInternalPtr() const
{
this->throwIfNotLoaded();
return std::static_pointer_cast<T>(this->mData->mPtr);
}
/** Converts a handle into a weak handle. */
TResourceHandle<T, true> getWeak() const
{
TResourceHandle<T, true> handle;
handle.setHandleData(this->getHandleData());
return handle;
}
protected:
friend Resources;
template<class _T, bool _Weak>
friend class TResourceHandle;
template<class _Ty1, class _Ty2, bool Weak>
friend TResourceHandle<_Ty1, Weak> static_resource_cast(const TResourceHandle<_Ty2, Weak>& other);
/**
* Constructs a new valid handle for the provided resource with the provided UUID.
*
* @note Handle will take ownership of the provided resource pointer, so make sure you don't delete it elsewhere.
*/
explicit TResourceHandle(T* ptr, const UUID& uuid)
:TResourceHandleBase<WeakHandle>()
{
this->mData = bs_shared_ptr_new<ResourceHandleData>();
this->addRef();
this->setHandleData(SPtr<Resource>(ptr), uuid);
}
/**
* Constructs an invalid handle with the specified UUID. You must call setHandleData() with the actual resource
* pointer to make the handle valid.
*/
TResourceHandle(const UUID& uuid)
{
this->mData = bs_shared_ptr_new<ResourceHandleData>();
this->mData->mUUID = uuid;
this->addRef();
}
/** Constructs a new valid handle for the provided resource with the provided UUID. */
TResourceHandle(const SPtr<T> ptr, const UUID& uuid)
{
this->mData = bs_shared_ptr_new<ResourceHandleData>();
this->addRef();
setHandleData(ptr, uuid);
}
/** Replaces the internal handle data pointer, effectively transforming the handle into a different handle. */
void setHandleData(const SPtr<ResourceHandleData>& data)
{
this->releaseRef();
this->mData = data;
this->addRef();
}
/** Converts a weak handle into a normal handle. */
TResourceHandle<T, false> lock() const
{
TResourceHandle<Resource, false> handle;
handle.setHandleData(this->getHandleData());
return handle;
}
using ResourceHandleBase::setHandleData;
};
/** Checks if two handles point to the same resource. */
template<class _Ty1, bool _Weak1, class _Ty2, bool _Weak2>
bool operator==(const TResourceHandle<_Ty1, _Weak1>& _Left, const TResourceHandle<_Ty2, _Weak2>& _Right)
{
if(_Left.getHandleData() != nullptr && _Right.getHandleData() != nullptr)
return _Left.getHandleData()->mPtr == _Right.getHandleData()->mPtr;
return _Left.getHandleData() == _Right.getHandleData();
}
/** Checks if a handle is null. */
template<class _Ty1, bool _Weak1, class _Ty2, bool _Weak2>
bool operator==(const TResourceHandle<_Ty1, _Weak1>& _Left, std::nullptr_t _Right)
{
return _Left.getHandleData() == nullptr || _Left.getHandleData()->mUUID.empty();
}
template<class _Ty1, bool _Weak1, class _Ty2, bool _Weak2>
bool operator!=(const TResourceHandle<_Ty1, _Weak1>& _Left, const TResourceHandle<_Ty2, _Weak2>& _Right)
{
return (!(_Left == _Right));
}
/** @} */
/** @addtogroup Resources
* @{
*/
/** @copydoc ResourceHandleBase */
template <typename T>
using ResourceHandle = TResourceHandle<T, false>;
/**
* @copydoc ResourceHandleBase
*
* Weak handles don't prevent the resource from being unloaded.
*/
template <typename T>
using WeakResourceHandle = TResourceHandle<T, true>;
/** Casts one resource handle to another. */
template<class _Ty1, class _Ty2, bool Weak>
TResourceHandle<_Ty1, Weak> static_resource_cast(const TResourceHandle<_Ty2, Weak>& other)
{
TResourceHandle<_Ty1, Weak> handle;
handle.setHandleData(other.getHandleData());
return handle;
}
/** @} */
}
| [
"bearishsun@gmail.com"
] | bearishsun@gmail.com |
4d6d965dc0f04d54144e9f9ad66a33bbf96f6111 | 30e1dc84fe8c54d26ef4a1aff000a83af6f612be | /src/external/boost/boost_1_68_0/libs/bimap/test/test_structured_pair.cpp | 2d4fbdc5cc5609c5683a7cefc3300c075f9c53c2 | [
"BSD-3-Clause",
"BSL-1.0"
] | permissive | Sitispeaks/turicreate | 0bda7c21ee97f5ae7dc09502f6a72abcb729536d | d42280b16cb466a608e7e723d8edfbe5977253b6 | refs/heads/main | 2023-05-19T17:55:21.938724 | 2021-06-14T17:53:17 | 2021-06-14T17:53:17 | 385,034,849 | 1 | 0 | BSD-3-Clause | 2021-07-11T19:23:21 | 2021-07-11T19:23:20 | null | UTF-8 | C++ | false | false | 2,328 | cpp | // Boost.Bimap
//
// Copyright (c) 2006-2007 Matias Capeletto
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// VC++ 8.0 warns on usage of certain Standard Library and API functions that
// can be cause buffer overruns or other possible security issues if misused.
// See http://msdn.microsoft.com/msdnmag/issues/05/05/SafeCandC/default.aspx
// But the wording of the warning is misleading and unsettling, there are no
// portable alternative functions, and VC++ 8.0's own libraries use the
// functions in question. So turn off the warnings.
#define _CRT_SECURE_NO_DEPRECATE
#define _SCL_SECURE_NO_DEPRECATE
#include <boost/config.hpp>
// Boost.Test
#include <boost/test/minimal.hpp>
// std
#include <utility>
#include <cstddef>
// Boost.Static_assert
#include <boost/static_assert.hpp>
// Boost.Bimap
#include <boost/bimap/detail/test/check_metadata.hpp>
#include <boost/bimap/relation/structured_pair.hpp>
BOOST_BIMAP_TEST_STATIC_FUNCTION( static_metadata_test )
{
using namespace boost::bimaps::relation;
struct data_a { char data; };
struct data_b { double data; };
typedef structured_pair
<
data_a,
data_b,
normal_layout
> sp_ab;
typedef structured_pair
<
data_b,
data_a,
mirror_layout
> sp_ba;
BOOST_BIMAP_CHECK_METADATA(sp_ab, first_type , data_a);
BOOST_BIMAP_CHECK_METADATA(sp_ab, second_type, data_b);
BOOST_BIMAP_CHECK_METADATA(sp_ba, first_type , data_b);
BOOST_BIMAP_CHECK_METADATA(sp_ba, second_type, data_a);
}
void test_basic()
{
using namespace boost::bimaps::relation;
// Instanciate two pairs and test the storage alignmentDataData
typedef structured_pair< short, double, normal_layout > pair_type;
typedef structured_pair< double, short, mirror_layout > mirror_type;
pair_type pa( 2, 3.1416 );
mirror_type pb( 3.1416, 2 );
BOOST_CHECK( pa.first == pb.second );
BOOST_CHECK( pa.second == pb.first );
}
int test_main( int, char* [] )
{
BOOST_BIMAP_CALL_TEST_STATIC_FUNCTION( static_are_storage_compatible_test );
BOOST_BIMAP_CALL_TEST_STATIC_FUNCTION( static_metadata_test );
test_basic();
return 0;
}
| [
"znation@apple.com"
] | znation@apple.com |
9df4f84464466d05b097655f6435504762d6bb5a | b0c1a37e3cf5cb08541a045e2f9f3120e1af4fce | /LinearRemapFV.h | a437f671de416c257587305f79ef4f30a59a2011 | [] | no_license | mmundt/MRMtempestremap | 6678fb228716762a3ee6b8c9f0111c33f9268ddc | a995c919638bd298b5d038a6d1454c43ade7f128 | refs/heads/master | 2021-01-15T23:27:17.046170 | 2015-07-30T15:33:19 | 2015-07-30T15:33:19 | 30,560,664 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,905 | h | ///////////////////////////////////////////////////////////////////////////////
///
/// \file LinearRemapFV.h
/// \author Paul Ullrich
/// \version September 1, 2014
///
/// <remarks>
/// Copyright 2000-2014 Paul Ullrich
///
/// This file is distributed as part of the Tempest source code package.
/// Permission is granted to use, copy, modify and distribute this
/// source code and its documentation under the terms of the GNU General
/// Public License. This software is provided "as is" without express
/// or implied warranty.
/// </remarks>
#ifndef _LINEARREMAPFV_H_
#define _LINEARREMAPFV_H_
#include "DataMatrix3D.h"
///////////////////////////////////////////////////////////////////////////////
class Mesh;
class OfflineMap;
///////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Generate the OfflineMap for remapping from finite volumes to finite
/// volumes.
/// </summary>
void LinearRemapFVtoFV(
const Mesh & meshInput,
const Mesh & meshOutput,
const Mesh & meshOverlap,
int nOrder,
OfflineMap & mapRemap
);
///////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Generate the OfflineMap for remapping from finite volumes to finite
/// elements using simple sampling of the FV reconstruction.
/// </summary>
void LinearRemapFVtoGLL_Simple(
const Mesh & meshInput,
const Mesh & meshOutput,
const Mesh & meshOverlap,
const DataMatrix3D<int> & dataGLLNodes,
const DataMatrix3D<double> & dataGLLJacobian,
const DataVector<double> & dataGLLNodalArea,
int nOrder,
OfflineMap & mapRemap,
bool fMonotone,
bool fContinuous
);
///////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Generate the OfflineMap for remapping from finite volumes to finite
/// elements.
/// </summary>
void LinearRemapFVtoGLL(
const Mesh & meshInput,
const Mesh & meshOutput,
const Mesh & meshOverlap,
const DataMatrix3D<int> & dataGLLNodes,
const DataMatrix3D<double> & dataGLLJacobian,
const DataVector<double> & dataGLLNodalArea,
int nOrder,
OfflineMap & mapRemap,
bool fMonotone,
bool fContinuous
);
///////////////////////////////////////////////////////////////////////////////
/*
/// <summary>
/// Generate the OfflineMap for remapping from finite elements to finite
/// elements.
/// </summary>
void LinearRemapGLLtoGLL(
const Mesh & meshInput,
const Mesh & meshOutput,
const Mesh & meshOverlap,
const DataMatrix3D<int> & dataGLLNodesIn,
const DataMatrix3D<double> & dataGLLJacobianIn,
const DataMatrix3D<int> & dataGLLNodesOut,
const DataMatrix3D<double> & dataGLLJacobianOut,
const DataVector<double> & dataNodalAreaOut,
int nPin,
int nPout,
OfflineMap & mapRemap,
bool fMonotone,
bool fContinuousIn,
bool fContinuousOut
);
*/
///////////////////////////////////////////////////////////////////////////////
#endif
| [
"paullrich@ucdavis.edu"
] | paullrich@ucdavis.edu |
7c1304b2248d87b3af516d31b8e7a6e0e0bebd53 | 1381d80073068f122672484273142687d7e2479a | /execises/Network-Uva.cpp | bf5ce83a2c3eb88d0dfdd7b97fcad008484e81e5 | [] | no_license | Guilherme26/algorithm_practices | 17c313745f692934ef6a976bee99259cbf0787d0 | ac3c65969173f6cc754b98e6fb3ae48d45e3c3c5 | refs/heads/master | 2021-06-27T21:46:50.087521 | 2020-09-22T14:40:48 | 2020-09-22T14:40:48 | 131,619,766 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,098 | cpp | #include <bits/stdc++.h>
using namespace std;
#define WHITE 1
#define BLACK 0
typedef struct{
int color;
vector<int> adjs;
} Vertex;
Vertex graph[111];
void initialize(bool clear){
for(int i = 0; i < 111; ++i){
graph[i].color = WHITE;
if(clear)
graph[i].adjs.clear();
}
}
void DFS(int initial){
// printf("%d\n", initial);
graph[initial].color = BLACK;
for(int i = 0; i < graph[initial].adjs.size(); ++i){
int curVertex = graph[initial].adjs[i];
if(graph[curVertex].color)
DFS(curVertex);
}
}
int main(){
int N;
while(cin >> N and N){
int V, VNg, criticals = 0;
char scape;
initialize(true);
while(cin >> V and V){
while(scanf("%d%c", &VNg, &scape) == 2){
graph[V].adjs.push_back(VNg);
graph[VNg].adjs.push_back(V);
if(scape == '\n')
break;
}
}
for(int i = 1; i <= N; ++i){
int calls = 0;
graph[i].color = BLACK;
for(int j = 1; j <= N; ++j){
if(graph[j].color){
DFS(j);
calls += 1;
}
}
initialize(false);
if(calls > 1)
criticals += 1;
}
printf("%d\n", criticals);
}
return 0;
} | [
"guilherme.hra26@gmail.com"
] | guilherme.hra26@gmail.com |
66109cb2333938dafed6f1d1d81d550ce957bbb6 | a1c82112744d7bab6055d723b7fc648ef484e064 | /Employee/Source.cpp | d8eb62aaefcfdf308686b35c92bdfdffb42dcfe5 | [] | no_license | Aashutoshh/Tut5-Employee | aa663760ca8ecee8c8a4e275f3bf8800c775ec96 | 5c6e90b8e8a158f0ec50f7731c70f879cb86a4dc | refs/heads/master | 2021-01-13T00:42:44.707998 | 2016-03-23T14:50:50 | 2016-03-23T14:50:50 | 54,557,615 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 606 | cpp | #include "Employee.h"
#include "CommisionEmployee.h"
#include "HourlyEmployee.h"
#include "SalaryEmployee.h"
int main()
{//array of employees
//commision employee
CommisionEmployee cEmp("Tom", 1);
cEmp.setBaseSalary(20000.00);
cEmp.setRate(500.00);
cEmp.setRevenue(5000.00);
float sal1 = cEmp.salary();
//Hourly empolyee
HourlyEmployee hEmp("Jane",2);
hEmp.setHourlyRate(1000.00);
hEmp.setHoursWorked(50);
float sal2 = hEmp.salary();
//Salary employeee
SalaryEmployee sEmp("MerryM" ,3);
sEmp.setSalary(50000.00);
float sal3 = sEmp.salary();
//store into arrays
//display
} | [
"214506607@stu.ukzn.ac.za"
] | 214506607@stu.ukzn.ac.za |
7aed2890b7fa7e77d35496cb1eb12528826bd04d | 3c4a127a1c76be81d47eb45f417808ecf0d21f23 | /3 parcial/Arboles/pruebas/5-Arbol AVL con doble apuntador.cpp | c039adee742379d2d566fd09ba591ff36496de7b | [] | no_license | Wicho1313/Estructuras-de-datos | cc9b02d93bcab1a8884ac7ec1e9850e0d184267c | 21166885ef72def9f37a4ae6f89f728d9a614622 | refs/heads/master | 2023-06-09T17:43:54.011511 | 2021-07-02T20:28:57 | 2021-07-02T20:28:57 | 309,032,966 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,110 | cpp | #include <stdio.h>
#include <conio.h>
#include <stdlib.h>
struct nodo{
int dato;
int bal;
struct nodo *ptrDer;
struct nodo *ptrIzq;
};
struct nodo *crearnodo(int dato1){
struct nodo *ptrN;
ptrN=(struct nodo*)malloc(sizeof(struct nodo));
ptrN->dato=dato1;
ptrN->ptrDer=NULL;
ptrN->ptrIzq=NULL;
return ptrN;
}
int altura(struct nodo **ptr){
if(*ptr==NULL)
return 0;
else
return ((*ptr)->bal);
}
int maximo(int a, int b){
if (a>b)
return a;
else
return b;
}
void calculaAltura(struct nodo **p){
(*p)->bal=1+maximo(altura(&(*p)->ptrIzq),altura(&(*p)->ptrDer));
}
struct nodo *rotaIzq(struct nodo **ptr){
struct nodo *temp;
temp=(*ptr)->ptrDer;
(*ptr)->ptrDer=temp->ptrIzq;
temp->ptrIzq=(*ptr);
calculaAltura(&(*ptr));
calculaAltura(&temp);
return temp;
}
struct nodo *rotaDer(struct nodo **ptr){
struct nodo *temp;
temp=(*ptr)->ptrIzq;
(*ptr)->ptrIzq=temp->ptrDer;
temp->ptrDer=(*ptr);
calculaAltura(&(*ptr));
calculaAltura(&temp);
return temp;
}
struct nodo *balancear(struct nodo **ptr){
calculaAltura(&(*ptr));
if(altura(&(*ptr)->ptrIzq)-altura(&(*ptr)->ptrDer)==2){
printf("Se rota\n");
if(altura(&(*ptr)->ptrIzq->ptrDer)> altura(&(*ptr)->ptrIzq->ptrIzq)){
(*ptr)->ptrIzq=rotaIzq(&(*ptr)->ptrIzq);
return rotaDer(&(*ptr));
}
}
else if(altura(&(*ptr)->ptrDer)-altura(&(*ptr)->ptrIzq)==2){
printf("se rota\n");
if(altura(&(*ptr)->ptrDer->ptrIzq)>altura(&(*ptr)->ptrDer->ptrDer)){
(*ptr)->ptrDer=rotaDer(&(*ptr)->ptrDer);
return rotaIzq(&(*ptr));
}
}
printf("\n %d",(*ptr)->bal);
return (*ptr);
}
struct nodo * insertar(struct nodo **ptrRaiz, int miDato1){
if(*ptrRaiz==NULL){
return crearnodo(miDato1);
}
else if(miDato1<(*ptrRaiz)->dato){
(*ptrRaiz)->ptrIzq=insertar(&((*ptrRaiz)->ptrIzq),miDato1);
}
else if(miDato1>(*ptrRaiz)->dato ){
(*ptrRaiz)->ptrDer=insertar(&((*ptrRaiz)->ptrDer),miDato1);
}
else
(*ptrRaiz)->dato=miDato1;
return balancear(&(*ptrRaiz));
}
void recorrerPunt(struct nodo **ptr, struct nodo **ptrH,struct nodo *ptrA){
if((*ptrH)->ptrDer!=NULL){
recorrerPunt(ptr,&(*ptrH)->ptrDer,ptrA);
}
else{
(*ptr)->dato=(*ptrH)->dato;
ptrA=(*ptrH);
*ptrH=(*ptrH)->ptrIzq;
}
}
struct nodo * eliminar(struct nodo **ptr, int clave){
if(*ptr==NULL){
printf("No esta en el arbol");
}
else if(clave<(*ptr)->dato) {
eliminar(&(*ptr)->ptrIzq, clave);
}
else if(clave>(*ptr)->dato){
eliminar(&(*ptr)->ptrDer, clave);
}
else {
struct nodo *aux;
aux=(*ptr);
if (aux->ptrIzq==NULL){
(*ptr)=aux->ptrDer;
}
else if(aux->ptrDer==NULL){
(*ptr)=aux->ptrDer;
}
else{
recorrerPunt(ptr,&(*ptr)->ptrIzq,aux);
free(aux);
}
}
(*ptr)->dato=clave;
balancear(&(*ptr));
}
void imprimirArbol(struct nodo **ptrRaiz, int contador){
int i,j;
i=contador;
if(*ptrRaiz!=NULL){
imprimirArbol(&(*ptrRaiz)->ptrDer, i+1);
printf("\n");
for(j=1;j<i;j++)
printf("-");
printf("%d \n",(*ptrRaiz)->dato);
imprimirArbol(&(*ptrRaiz)->ptrIzq,i+1);
}
}
int maxProfundidad(struct nodo **ptrRaiz){
if(*ptrRaiz!=NULL){
int profIzq, profDer;
profIzq=maxProfundidad(&(*ptrRaiz)->ptrIzq);
profDer=maxProfundidad(&(*ptrRaiz)->ptrDer);
if (profIzq>profDer){
return(profIzq+1);
}
else{
return (profDer+1);
}
}
else
return 0;
}
struct nodo * busca(struct nodo **ptr, int clave){
if(*ptr==NULL)
return NULL;
else if(clave==(*ptr)->dato)
return (*ptr);
else if(clave<(*ptr)->dato)
return busca(&(*ptr)->ptrIzq,clave);
else
return busca(&(*ptr)->ptrDer,clave);
}
void in_orden(struct nodo **ptrRaiz){
if(*ptrRaiz==NULL) return;
in_orden(&(*ptrRaiz)->ptrIzq);
printf(" %d ",(*ptrRaiz)->dato);
in_orden(&(*ptrRaiz)->ptrDer);
}
void post_orden(struct nodo **ptrRaiz){
if (*ptrRaiz==NULL)return;
post_orden(&(*ptrRaiz)->ptrIzq);
post_orden(&(*ptrRaiz)->ptrDer);
printf(" %d ",(*ptrRaiz)->dato);
}
void pre_orden(struct nodo **ptrRaiz){
if(*ptrRaiz==NULL)return;
printf(" %d ",(*ptrRaiz)->dato);
pre_orden(&(*ptrRaiz)->ptrIzq);
pre_orden(&(*ptrRaiz)->ptrDer);
}
int main (){
int datoEnt, opc;
struct nodo *ptrc=NULL;
struct nodo **ptrc2;
ptrc2=&ptrc;
do{
fflush(stdin);
printf ("\n 1.- Meter en el Arbol \n ");
printf ("\n 2.- sacar del Arbol \n ");
printf ("\n 3.- Maxima profundidad del Arbol \n ");
printf ("\n 4.- Imprimir en in-orden el Arbol \n ");
printf ("\n 5.- Imprimir en post-orden el Arbol \n ");
printf ("\n 6.- Imprimir en pre-orden el Arbol \n ");
printf ("\n 7.- Visualizar Arbol \n ");
printf ("\n 8.- Buscar un dato \n ");
printf ("\n 9.- Verificar si es hoja \n ");
printf ("\n 10.- Salir \n ");
scanf ("%d", &opc);
switch (opc){
case 1:
system("cls");
printf("Ingrese entero: ");
scanf("%d",&datoEnt);
insertar(ptrc2, datoEnt);
imprimirArbol(ptrc2, datoEnt);
system("pause");
system("cls");
break;
case 2:
system("cls");
printf("Que dato quieres sacar? ");
scanf("%d",&datoEnt);
eliminar(ptrc2,datoEnt);
imprimirArbol(ptrc2, datoEnt);
system("pause");
system("cls");
break;
case 3:
system("cls");
maxProfundidad(ptrc2);
system("pause");
system("cls");
break;
case 4:
system("cls");
imprimirArbol(ptrc2, datoEnt);
printf("\n En in-orden: \n");
in_orden(ptrc2);
system("pause");
system("cls");
break;
case 5:
system("cls");
imprimirArbol(ptrc2, datoEnt);
printf("\n En post-orden: \n");
post_orden(ptrc2);
system("pause");
system("cls");
break;
case 6:
system("cls");
imprimirArbol(ptrc2, datoEnt);
printf("\n En pre-orden: \n");
pre_orden(ptrc2);
system("pause");
system("cls");
break;
case 7:
system("cls");
imprimirArbol(ptrc2, datoEnt);
system("pause");
system("cls");
break;
case 8:
printf("ingresa un valor para buscar: ");
scanf("%d",&datoEnt);
if(busca(ptrc2,datoEnt)!=NULL)
printf("\n Si esta en el arbol\n");
else
printf("\n No se encontro \n ");
break;
case 9:
//if(eshoja(ptrc2)==1)
// printf("El dato es hoja");
// else
// printf("no es hoja");
// break;
case 10:
exit (0);
break;
}
}while(opc!=10);
}
| [
"lrojase1@gmail.com"
] | lrojase1@gmail.com |
c4d7311e9d80171e618ccd892cfbd0717b383483 | 16aa5d7812bb7a18cdfb85d0eaf1773d15b4284f | /type_to_enum.cpp | ae6a6e87e8ef7fffee9a64f70c61a7d6d8061264 | [] | no_license | strvert/cpp-playground | b56339a565832319166ed3c78286876a6a3de670 | bcdb154fcb80b01af13da4a595570d7e725e03e5 | refs/heads/master | 2023-07-27T14:56:06.472613 | 2021-09-07T14:26:52 | 2021-09-07T14:26:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,447 | cpp | #include <iostream>
#include <map>
enum class TypeEnum : uint8_t {
Unknown = 1,
Int,
Float,
Double,
Char,
};
template<typename T>
struct Mapper {
struct MTable;
using ET = TypeEnum;
using enum ET;
template<ET E>
struct ToEnum {
char _[static_cast<std::underlying_type_t<ET>>(E)];
};
inline static constexpr const ET Value =
static_cast<ET>(sizeof(MTable::From(static_cast<T*>(nullptr))));
template<typename NP> using Type = std::add_pointer_t<NP>;
struct MTable {
static ToEnum<Unknown> From(...);
static ToEnum<Int> From(Type<int>);
static ToEnum<Float> From(Type<float>);
static ToEnum<Double> From(Type<double>);
static ToEnum<Char> From(Type<char>);
};
};
template<typename T>
TypeEnum MapperV = Mapper<T>::Value;
int main()
{
const std::map<TypeEnum, const char*> ToString = {
{ TypeEnum::Unknown, "Unknown" }, { TypeEnum::Int, "Int" },
{ TypeEnum::Float, "Float" }, { TypeEnum::Double, "Double" },
{ TypeEnum::Char, "Char" },
};
std::cout << ToString.at(MapperV<int>) << std::endl;
std::cout << ToString.at(MapperV<float>) << std::endl;
std::cout << ToString.at(MapperV<double>) << std::endl;
std::cout << ToString.at(MapperV<char>) << std::endl;
std::cout << ToString.at(MapperV<bool>) << std::endl;
std::cout << ToString.at(MapperV<TypeEnum>) << std::endl;
}
| [
"strv13570@gmail.com"
] | strv13570@gmail.com |
e922606e1cec0f99f8bfef6c9e22c52fe3556d7f | 14c7ee95170d0013b98cfd47d127332f78a27ab7 | /Hunt the Wumpus (Maze Game)/game.hpp | 7379e992eb1c57a38572e020816ec043f930098c | [] | no_license | lidenn/CS-162-Assignments | 68efb15b1cd589facea7e40c6b90ac9f289aff6e | 2f9df2be0c4887a19765bf6493e448ee06d68c44 | refs/heads/master | 2021-01-23T10:57:28.809174 | 2017-06-02T00:50:51 | 2017-06-02T00:50:51 | 93,111,279 | 0 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 1,285 | hpp | /********
* Program Filename: game.hpp
* Author:Dennis Li
* Date: 3/7/17
* Description: Contains the game class
* Input: None
* Output: None
*/
#ifndef GAME_H
#define GAME_H
#include<vector>
#include<iostream>
#include<cstdlib>
#include<string>
#include"room.hpp"
#include"event.hpp"
#include"wumpus.hpp"
using namespace std;
class Game{
private:
int cave_size;
vector<vector<Room*> >cave;
int user_x, user_y;
int start_user_x, start_user_y; //to remember starting point of user for new game
int arrow_x, arrow_y; //location of arrows
int arrows = 3; // number of arrows
int wumpus_x, wumpus_y; //location of wumpus
int start_wumpus_x, start_wumpus_y; //location of wumpus
bool wumpus = false; //wumpus killed
bool gold = false; //retrieved gold
bool is_alive = true; //game ender
bool win = false; // game ender
public:
Game(int size);
void print_nearby_event();
void print_board();
void set_board();
void print_adventurer_board();
void move_adventurer(int direction);
void shoot_arrow(int direction);
void run_event();
bool check_is_alive();
void game_reset();
bool get_is_alive();
bool get_win();
~Game();
};
#endif
//CURRENTLY SEGFAULTING IN THE DESTRUCTOR, IT NEEDS TO DESTRUCT EPTR
| [
"noreply@github.com"
] | lidenn.noreply@github.com |
92bf3bdaba1a0005629063db4643d4158d4faec8 | f739df1f252d7c961ed881be3b8babaf62ff4170 | /softs/SCADAsoft/5.3.2/ACE_Wrappers/ace/os_include/os_dirent.h | 2a881e40b0901b1dcad507128c42de8695adfd93 | [] | no_license | billpwchan/SCADA-nsl | 739484691c95181b262041daa90669d108c54234 | 1287edcd38b2685a675f1261884f1035f7f288db | refs/heads/master | 2023-04-30T09:15:49.104944 | 2021-01-10T21:53:10 | 2021-01-10T21:53:10 | 328,486,982 | 0 | 0 | null | 2023-04-22T07:10:56 | 2021-01-10T21:53:19 | C++ | UTF-8 | C++ | false | false | 2,826 | h | // -*- C++ -*-
//=============================================================================
/**
* @file os_dirent.h
*
* format of directory entries
*
* $Id: os_dirent.h 935 2008-12-10 21:47:27Z mitza $
*
* @author Don Hinton <dhinton@dresystems.com>
* @author This code was originally in various places including ace/OS.h.
*/
//=============================================================================
#ifndef ACE_OS_INCLUDE_OS_DIRENT_H
#define ACE_OS_INCLUDE_OS_DIRENT_H
#include /**/ "ace/pre.h"
#include /**/ "ace/config-all.h"
#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */
#include "ace/os_include/sys/os_types.h"
#include "ace/os_include/os_limits.h"
#if defined (ACE_VXWORKS) && (ACE_VXWORKS < 0x620)
# include "ace/os_include/os_unistd.h" // VxWorks needs this to compile
#endif /* ACE_VXWORKS */
#if !defined (ACE_LACKS_DIRENT_H)
# include /**/ <dirent.h>
#endif /* !ACE_LACKS_DIRENT_H */
// Place all additions (especially function declarations) within extern "C" {}
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
#if !defined (MAXNAMLEN)
# define MAXNAMLEN NAME_MAX
#endif /* !MAXNAMLEN */
// At least compile on some of the platforms without <ACE_DIR> info yet.
#if !defined (ACE_HAS_DIRENT)
typedef int ACE_DIR;
struct dirent {
};
#endif /* ACE_HAS_DIRENT */
#if defined (ACE_LACKS_STRUCT_DIR)
struct dirent {
unsigned short d_ino;
unsigned short d_off;
unsigned short d_reclen;
// This must be a ACE_TCHAR * and not a one element
// ACE_TCHAR array. It causes problems on wide
// character builds with Visual C++ 6.0.
ACE_TCHAR *d_name;
};
#define ACE_DIRENT dirent
#define ACE_HAS_TCHAR_DIRENT
struct ACE_DIR {
/// The name of the directory we are looking into
ACE_TCHAR *directory_name_;
/// Remember the handle between calls.
HANDLE current_handle_;
/// The struct for the results
ACE_DIRENT *dirent_;
/// The struct for intermediate results.
ACE_TEXT_WIN32_FIND_DATA fdata_;
/// A flag to remember if we started reading already.
int started_reading_;
};
#elif defined (ACE_WIN32) && (__BORLANDC__) && defined (ACE_USES_WCHAR)
#define ACE_HAS_TCHAR_DIRENT
#define ACE_DIRENT wdirent
typedef wDIR ACE_DIR;
#else
#define ACE_DIRENT dirent
typedef DIR ACE_DIR;
#endif /* ACE_LACKS_STRUCT_DIR */
#if defined (ACE_LACKS_SCANDIR_PROTOTYPE)
int scandir (const char *,
struct dirent ***,
int (*) (const struct dirent *),
int (*) (const void *, const void *));
#endif /* ACE_LACKS_SCANDIR_PROTOTYPE */
#if defined (ACE_LACKS_ALPHASORT_PROTOTYPE)
int alphasort (const void *, const void *);
#endif /* ACE_LACKS_ALPHASORT_PROTOTYPE */
#ifdef __cplusplus
}
#endif /* __cplusplus */
#include /**/ "ace/post.h"
#endif /* ACE_OS_INCLUDE_OS_DIRENT_H */
| [
"billpwchan@hotmail.com"
] | billpwchan@hotmail.com |
c81878695e097dfcc5dca151c288a4b14a42aabb | 057a475216e9beed41983481aafcaf109bbf58da | /base/poco/Foundation/src/Bugcheck.cpp | 14f5170c842df210dbc673a9fd3b0e220ede2fa8 | [
"BSL-1.0",
"Apache-2.0"
] | permissive | ClickHouse/ClickHouse | fece5204263a5b4d693854b6039699265f1bb27f | 6649328db809d51a694c358571539bc5820464be | refs/heads/master | 2023-08-31T18:48:36.615225 | 2023-08-31T17:51:24 | 2023-08-31T17:51:24 | 60,246,359 | 23,878 | 5,449 | Apache-2.0 | 2023-09-14T20:10:52 | 2016-06-02T08:28:18 | C++ | UTF-8 | C++ | false | false | 2,188 | cpp | //
// Bugcheck.cpp
//
// Library: Foundation
// Package: Core
// Module: Bugcheck
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "Poco/Bugcheck.h"
#include "Poco/Debugger.h"
#include "Poco/Exception.h"
#include <sstream>
namespace Poco {
void Bugcheck::assertion(const char* cond, const char* file, int line, const char* text)
{
std::string message("Assertion violation: ");
message += cond;
if (text)
{
message += " (";
message += text;
message += ")";
}
Debugger::enter(message, file, line);
throw AssertionViolationException(what(cond, file, line, text));
}
void Bugcheck::nullPointer(const char* ptr, const char* file, int line)
{
Debugger::enter(std::string("NULL pointer: ") + ptr, file, line);
throw NullPointerException(what(ptr, file, line));
}
void Bugcheck::bugcheck(const char* file, int line)
{
Debugger::enter("Bugcheck", file, line);
throw BugcheckException(what(0, file, line));
}
void Bugcheck::bugcheck(const char* msg, const char* file, int line)
{
std::string m("Bugcheck");
if (msg)
{
m.append(": ");
m.append(msg);
}
Debugger::enter(m, file, line);
throw BugcheckException(what(msg, file, line));
}
void Bugcheck::unexpected(const char* file, int line)
{
#ifdef _DEBUG
try
{
std::string msg("Unexpected exception in noexcept function or destructor: ");
try
{
throw;
}
catch (Poco::Exception& exc)
{
msg += exc.displayText();
}
catch (std::exception& exc)
{
msg += exc.what();
}
catch (...)
{
msg += "unknown exception";
}
Debugger::enter(msg, file, line);
}
catch (...)
{
}
#endif
}
void Bugcheck::debugger(const char* file, int line)
{
Debugger::enter(file, line);
}
void Bugcheck::debugger(const char* msg, const char* file, int line)
{
Debugger::enter(msg, file, line);
}
std::string Bugcheck::what(const char* msg, const char* file, int line, const char* text)
{
std::ostringstream str;
if (msg) str << msg << " ";
if (text != NULL) str << "(" << text << ") ";
str << "in file \"" << file << "\", line " << line;
return str.str();
}
} // namespace Poco
| [
"noreply@github.com"
] | ClickHouse.noreply@github.com |
c5583dc9e366bbf48c27d1fd9bb21327b3b524ec | c7be52078daa48f8e2efa3102782d3be99bf6478 | /HidEngine/HidEngine.cpp | 68b74a70a4d2463632f27452545b8886164fa2ef | [] | no_license | ogatatsu/HID-Playground-Lib | db36d447397ce494ca33cc62f7e6bbabd0c4a249 | 22d71b98a35446b4762c4d4a1708377cf268a7b3 | refs/heads/master | 2022-12-07T21:38:55.843618 | 2022-11-27T08:33:01 | 2022-11-30T13:59:26 | 187,300,341 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 23,507 | cpp | /*
The MIT License (MIT)
Copyright (c) 2019 ogatatsu.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "HidEngine.h"
#include "ArduinoMacro.h"
#include "CommandTapper.h"
#include "HidCore.h"
#include "HidEngineTask.h"
#include "utility.h"
namespace hidpg
{
namespace Internal
{
etl::span<Key> HidEngineClass::_keymap;
etl::span<KeyShift> HidEngineClass::_key_shift_map;
etl::span<Combo> HidEngineClass::_combo_map;
etl::span<Gesture> HidEngineClass::_gesture_map;
etl::span<Encoder> HidEngineClass::_encoder_map;
etl::span<EncoderShift> HidEngineClass::_encoder_shift_map;
HidEngineClass::read_pointer_delta_callback_t HidEngineClass::_read_pointer_delta_cb = nullptr;
HidEngineClass::read_encoder_step_callback_t HidEngineClass::_read_encoder_step_cb = nullptr;
HidEngineClass::ComboInterruptionEvent HidEngineClass::_combo_interruption_event;
etl::intrusive_list<Key> HidEngineClass::_pressed_key_list;
etl::intrusive_list<KeyShiftIdLink> HidEngineClass::_started_key_shift_id_list;
etl::intrusive_list<GestureIdLink> HidEngineClass::_started_gesture_id_list;
etl::intrusive_list<EncoderShiftIdLink> HidEngineClass::_started_encoder_shift_id_list;
void HidEngineClass::setKeymap(etl::span<Key> keymap)
{
_keymap = keymap;
}
void HidEngineClass::setKeyShiftMap(etl::span<KeyShift> key_shift_map)
{
_key_shift_map = key_shift_map;
}
void HidEngineClass::setComboMap(etl::span<Combo> combo_map)
{
_combo_map = combo_map;
}
void HidEngineClass::setGestureMap(etl::span<Gesture> gesture_map)
{
_gesture_map = gesture_map;
}
void HidEngineClass::setEncoderMap(etl::span<Encoder> encoder_map)
{
_encoder_map = encoder_map;
}
void HidEngineClass::setEncoderShiftMap(etl::span<EncoderShift> encoder_shift_map)
{
_encoder_shift_map = encoder_shift_map;
}
void HidEngineClass::setHidReporter(HidReporter *hid_reporter)
{
Hid.setReporter(hid_reporter);
}
void HidEngineClass::start()
{
HidEngineTask.start();
}
void HidEngineClass::applyToKeymap(const Set &key_ids)
{
EventData evt{ApplyToKeymapEventData{key_ids}};
HidEngineTask.enqueEvent(evt);
}
void HidEngineClass::movePointer(PointingDeviceId pointing_device_id)
{
EventData evt{MovePointerEventData{pointing_device_id}};
HidEngineTask.enqueEvent(evt);
}
void HidEngineClass::rotateEncoder(EncoderId encoder_id)
{
EventData evt{RotateEncoderEventData{encoder_id}};
HidEngineTask.enqueEvent(evt);
}
void HidEngineClass::setReadPointerDeltaCallback(read_pointer_delta_callback_t cb)
{
_read_pointer_delta_cb = cb;
}
void HidEngineClass::setReadEncoderStepCallback(read_encoder_step_callback_t cb)
{
_read_encoder_step_cb = cb;
}
//------------------------------------------------------------------+
// ApplyToKeymap
//------------------------------------------------------------------+
void HidEngineClass::applyToKeymap_impl(Set &key_ids)
{
static Set prev_ids;
{
Set press_ids = key_ids - prev_ids;
uint8_t arr[press_ids.count()];
press_ids.toArray(arr);
for (uint8_t key_id : arr)
{
processComboAndKey(Action::Press, key_id);
}
}
{
Set release_ids = prev_ids - key_ids;
uint8_t arr[release_ids.count()];
release_ids.toArray(arr);
for (uint8_t key_id : arr)
{
processComboAndKey(Action::Release, key_id);
}
}
prev_ids = key_ids;
}
void HidEngineClass::processComboAndKey(Action action, etl::optional<uint8_t> key_id)
{
static etl::optional<uint8_t> first_commbo_id;
static etl::intrusive_list<Combo> success_combo_list;
switch (action)
{
case Action::Press:
{
// コンボ実行中のid(片方のキーだけreleaseされて再度pressされた。)の場合は新しいコンボを開始しないで通常のKeyPress
for (auto &combo : success_combo_list)
{
if (combo.first_id == key_id || combo.second_id == key_id)
{
performKeyPress(key_id.value());
return;
}
}
// first_id check
if (first_commbo_id.has_value() == false)
{
for (auto &combo : _combo_map)
{
if (combo.isMatchFirstId(key_id.value()))
{
// first_id success
first_commbo_id = key_id;
_combo_interruption_event.start(combo.combo_term_ms);
return;
}
}
// first_id failure
performKeyPress(key_id.value());
return;
}
// second_id check
for (auto &combo : _combo_map)
{
if (combo.isMatchIds(first_commbo_id.value(), key_id.value()))
{
// combo success
_combo_interruption_event.stop();
combo.first_id_rereased = false;
combo.second_id_rereased = false;
combo.command->press();
success_combo_list.push_back(combo);
first_commbo_id = etl::nullopt;
return;
}
}
// second_id failure
_combo_interruption_event.stop();
performKeyPress(first_commbo_id.value());
performKeyPress(key_id.value());
first_commbo_id = etl::nullopt;
}
break;
case Action::Release:
{
// combo実行中のidがreleaseされた場合
for (auto &combo : success_combo_list)
{
if (combo.first_id == key_id && combo.first_id_rereased == false)
{
combo.first_id_rereased = true;
if ((combo.isFastRelease() && combo.second_id_rereased == false) ||
(combo.isSlowRelease() && combo.second_id_rereased))
{
combo.command->release();
}
if (combo.second_id_rereased)
{
auto i_item = etl::intrusive_list<Combo>::iterator(combo);
success_combo_list.erase(i_item);
}
return;
}
if (combo.second_id == key_id && combo.second_id_rereased == false)
{
combo.second_id_rereased = true;
if ((combo.isFastRelease() && combo.first_id_rereased == false) ||
(combo.isSlowRelease() && combo.first_id_rereased))
{
combo.command->release();
}
if (combo.first_id_rereased)
{
auto i_item = etl::intrusive_list<Combo>::iterator(combo);
success_combo_list.erase(i_item);
}
return;
}
}
// first_idがタップされた場合
if (first_commbo_id == key_id)
{
_combo_interruption_event.stop();
first_commbo_id = etl::nullopt;
performKeyPress(key_id.value());
performKeyRelease(key_id.value());
return;
}
// first_idより前に押されていたidがreleaseされた場合
if (first_commbo_id.has_value())
{
_combo_interruption_event.stop();
performKeyPress(first_commbo_id.value());
performKeyRelease(key_id.value());
first_commbo_id = etl::nullopt;
return;
}
// 他
performKeyRelease(key_id.value());
}
break;
case Action::ComboInterruption:
{
_combo_interruption_event.stop();
if (first_commbo_id.has_value())
{
performKeyPress(first_commbo_id.value());
first_commbo_id = etl::nullopt;
}
}
break;
default:
break;
}
}
void HidEngineClass::performKeyPress(uint8_t key_id)
{
for (auto &key : _pressed_key_list)
{
if (key.key_id == key_id)
{
return;
}
}
BeforeOtherKeyPressEventListener::_notifyBeforeOtherKeyPress(key_id);
auto tpl = getCurrentKey(key_id);
auto key_shift = std::get<0>(tpl);
auto key = std::get<1>(tpl);
if (key == nullptr)
{
return;
}
if (key_shift != nullptr &&
key_shift->pre_command.has_value() &&
key_shift->pre_command.value().is_pressed == false)
{
key_shift->pre_command.value().is_pressed = true;
key_shift->pre_command.value().command->press();
if (key_shift->pre_command.value().timing == Timing::InsteadOfFirstAction)
{
return;
}
}
_pressed_key_list.push_front(*key);
key->command->press();
}
void HidEngineClass::performKeyRelease(uint8_t key_id)
{
for (auto &key : _pressed_key_list)
{
if (key.key_id == key_id)
{
auto i_item = etl::intrusive_list<Key>::iterator(key);
_pressed_key_list.erase(i_item);
key.command->release();
return;
}
}
}
std::tuple<KeyShift *, Key *> HidEngineClass::getCurrentKey(uint8_t key_id)
{
for (auto &started_key_shift_id : _started_key_shift_id_list)
{
for (auto &key_shift : _key_shift_map)
{
if (key_shift.key_shift_id.value == started_key_shift_id.value)
{
for (auto &key : key_shift.keymap)
{
if (key.key_id == key_id)
{
return {&key_shift, &key};
}
}
if (key_shift.keymap_overlay == KeymapOverlay::Disable)
{
return {&key_shift, nullptr};
}
}
}
}
for (auto &key : _keymap)
{
if (key.key_id == key_id)
{
return {nullptr, &key};
}
}
return {nullptr, nullptr};
}
void HidEngineClass::startKeyShift(KeyShiftIdLink &key_shift_id)
{
if (key_shift_id.is_linked())
{
return;
}
_started_key_shift_id_list.push_front(key_shift_id);
// pre_command
for (auto &key_shift : _key_shift_map)
{
if (key_shift.key_shift_id.value == key_shift_id.value &&
key_shift.pre_command.has_value() &&
key_shift.pre_command.value().timing == Timing::Immediately &&
key_shift.pre_command.value().is_pressed == false)
{
key_shift.pre_command.value().is_pressed = true;
key_shift.pre_command.value().command->press();
}
}
}
void HidEngineClass::stopKeyShift(KeyShiftIdLink &key_shift_id)
{
if (key_shift_id.is_linked() == false)
{
return;
}
auto i_item = etl::intrusive_list<KeyShiftIdLink>::iterator(key_shift_id);
_started_key_shift_id_list.erase(i_item);
key_shift_id.clear();
// 同じidが同時に押されることもあり得るので最後に押されていたかチェック
for (auto &started_key_shift_id : _started_key_shift_id_list)
{
if (started_key_shift_id.value == key_shift_id.value)
{
return;
}
}
// 最後のidならclean up
for (auto &key_shift : _key_shift_map)
{
if (key_shift.key_shift_id.value == key_shift_id.value &&
key_shift.pre_command.has_value() &&
key_shift.pre_command.value().is_pressed == true)
{
key_shift.pre_command.value().is_pressed = false;
key_shift.pre_command.value().command->release();
}
}
}
//------------------------------------------------------------------+
// MovePointer
//------------------------------------------------------------------+
void HidEngineClass::movePointer_impl(PointingDeviceId pointing_device_id)
{
if (_read_pointer_delta_cb == nullptr)
{
return;
}
Hid.waitReady();
int16_t delta_x = 0, delta_y = 0;
_read_pointer_delta_cb(pointing_device_id, delta_x, delta_y);
if (delta_x == 0 && delta_y == 0)
{
return;
}
BeforeMovePointerEventListener::_notifyBeforeMovePointer(pointing_device_id, delta_x, delta_y);
Gesture *gesture = getCurrentGesture(pointing_device_id);
if (gesture != nullptr)
{
processGesture(*gesture, delta_x, delta_y);
}
else
{
Hid.mouseMove(delta_x, delta_y);
}
}
Gesture *HidEngineClass::getCurrentGesture(PointingDeviceId pointing_device_id)
{
for (auto &started_gesture_id : _started_gesture_id_list)
{
for (auto &gesture : _gesture_map)
{
if ((started_gesture_id.value == gesture.gesture_id.value) && (gesture.pointing_device_id == pointing_device_id))
{
return &gesture;
}
}
}
return nullptr;
}
void HidEngineClass::processGesture(Gesture &gesture, int16_t delta_x, int16_t delta_y)
{
#if (HID_ENGINE_WAIT_TIME_AFTER_INSTEAD_OF_FIRST_GESTURE_MS != 0)
if (gesture.instead_of_first_gesture_millis.has_value())
{
uint32_t curr_millis = millis();
if (static_cast<uint32_t>(curr_millis - gesture.instead_of_first_gesture_millis.value()) <= HID_ENGINE_WAIT_TIME_AFTER_INSTEAD_OF_FIRST_GESTURE_MS)
{
return;
}
gesture.instead_of_first_gesture_millis = etl::nullopt;
}
#endif
// 逆方向に動いたら距離をリセット
if (bitRead(gesture.total_distance_x ^ static_cast<int32_t>(delta_x), 31))
{
gesture.total_distance_x = 0;
}
if (bitRead(gesture.total_distance_y ^ static_cast<int32_t>(delta_y), 31))
{
gesture.total_distance_y = 0;
}
// 距離を足す
gesture.total_distance_x += delta_x;
gesture.total_distance_y += delta_y;
// 直近のマウスの移動距離の大きさによって実行する順序を変える
if (abs(delta_x) >= abs(delta_y))
{
processGestureX(gesture);
processGestureY(gesture);
}
else
{
processGestureY(gesture);
processGestureX(gesture);
}
}
void HidEngineClass::processGestureX(Gesture &gesture)
{
uint8_t n_times = std::min<int32_t>(abs(gesture.total_distance_x / gesture.distance), UINT8_MAX);
if (n_times == 0)
{
return;
}
BeforeGestureEventListener::_notifyBeforeGesture(gesture.gesture_id, gesture.pointing_device_id);
bool is_right = gesture.total_distance_x > 0;
gesture.total_distance_x %= gesture.distance;
if (gesture.angle_snap == AngleSnap::Enable)
{
gesture.total_distance_y = 0;
}
processGesturePreCommand(gesture, n_times);
if (n_times == 0)
{
return;
}
if (is_right)
{
CommandTapper.tap(gesture.right_command, n_times);
}
else
{
CommandTapper.tap(gesture.left_command, n_times);
}
}
void HidEngineClass::processGestureY(Gesture &gesture)
{
uint8_t n_times = std::min<int32_t>(abs(gesture.total_distance_y / gesture.distance), UINT8_MAX);
if (n_times == 0)
{
return;
}
BeforeGestureEventListener::_notifyBeforeGesture(gesture.gesture_id, gesture.pointing_device_id);
bool is_down = gesture.total_distance_y > 0;
gesture.total_distance_y %= gesture.distance;
if (gesture.angle_snap == AngleSnap::Enable)
{
gesture.total_distance_x = 0;
}
processGesturePreCommand(gesture, n_times);
if (n_times == 0)
{
return;
}
if (is_down > 0)
{
CommandTapper.tap(gesture.down_command, n_times);
}
else
{
CommandTapper.tap(gesture.up_command, n_times);
}
}
void HidEngineClass::processGesturePreCommand(Gesture &gesture, uint8_t &n_timse)
{
if (gesture.pre_command.has_value() &&
gesture.pre_command.value().is_pressed == false)
{
gesture.pre_command.value().is_pressed = true;
gesture.pre_command.value().command->press();
if (gesture.pre_command.value().timing == Timing::InsteadOfFirstAction)
{
n_timse--;
gesture.instead_of_first_gesture_millis = millis();
}
}
}
void HidEngineClass::startGesture(GestureIdLink &gesture_id)
{
if (gesture_id.is_linked())
{
return;
}
_started_gesture_id_list.push_front(gesture_id);
// pre_command
for (auto &gesture : _gesture_map)
{
if (gesture.gesture_id.value == gesture_id.value &&
gesture.pre_command.has_value() &&
gesture.pre_command.value().timing == Timing::Immediately &&
gesture.pre_command.value().is_pressed == false)
{
gesture.pre_command.value().is_pressed = true;
gesture.pre_command.value().command->press();
}
}
}
void HidEngineClass::stopGesture(GestureIdLink &gesture_id)
{
if (gesture_id.is_linked() == false)
{
return;
}
auto i_item = etl::intrusive_list<GestureIdLink>::iterator(gesture_id);
_started_gesture_id_list.erase(i_item);
gesture_id.clear();
// 同じidが同時に押されることもあり得るので最後に押されていたかチェック
for (auto &started_gesture_id : _started_gesture_id_list)
{
if (started_gesture_id.value == gesture_id.value)
{
return;
}
}
// 最後のidならclean up
for (auto &gesture : _gesture_map)
{
if (gesture.gesture_id.value == gesture_id.value)
{
if (gesture.pre_command.has_value() &&
gesture.pre_command.value().is_pressed == true)
{
gesture.pre_command.value().is_pressed = false;
gesture.pre_command.value().command->release();
gesture.instead_of_first_gesture_millis = etl::nullopt;
}
gesture.total_distance_x = 0;
gesture.total_distance_y = 0;
}
}
}
//------------------------------------------------------------------+
// RotateEncoder
//------------------------------------------------------------------+
void HidEngineClass::rotateEncoder_impl(EncoderId encoder_id)
{
if (_read_encoder_step_cb == nullptr)
{
return;
}
Hid.waitReady();
int16_t step = 0;
_read_encoder_step_cb(encoder_id, step);
if (step == 0)
{
return;
}
BeforeRotateEncoderEventListener::_notifyBeforeRotateEncoder(encoder_id, step);
EncoderShift *encoder = getCurrentEncoder(encoder_id);
if (encoder == nullptr)
{
return;
}
encoder->total_step = etl::clamp(encoder->total_step + step, INT32_MIN, INT32_MAX);
uint8_t n_times = std::min<int32_t>(abs(encoder->total_step) / encoder->step, UINT8_MAX);
if (n_times == 0)
{
return;
}
encoder->total_step %= encoder->step;
if (encoder->pre_command.has_value() &&
encoder->pre_command.value().is_pressed == false)
{
encoder->pre_command.value().is_pressed = true;
encoder->pre_command.value().command->press();
if (encoder->pre_command.value().timing == Timing::InsteadOfFirstAction)
{
n_times--;
if (n_times == 0)
{
return;
}
}
}
if (step > 0)
{
CommandTapper.tap(encoder->clockwise_command, n_times);
}
else
{
CommandTapper.tap(encoder->counterclockwise_command, n_times);
}
}
EncoderShift *HidEngineClass::getCurrentEncoder(EncoderId encoder_id)
{
for (auto &started_encoder_shift_id : _started_encoder_shift_id_list)
{
for (auto &encoder : _encoder_shift_map)
{
if ((started_encoder_shift_id.value == encoder.encoder_shift_id.value) && (encoder.encoder_id == encoder_id))
{
return &encoder;
}
}
}
for (auto &encoder : _encoder_map)
{
if (encoder.encoder_id == encoder_id)
{
return &encoder;
}
}
return nullptr;
}
void HidEngineClass::startEncoderShift(EncoderShiftIdLink &encoder_shift_id)
{
if (encoder_shift_id.is_linked())
{
return;
}
_started_encoder_shift_id_list.push_front(encoder_shift_id);
// pre_command
for (auto &encoder : _encoder_shift_map)
{
if (encoder.encoder_shift_id.value == encoder_shift_id.value &&
encoder.pre_command.has_value() &&
encoder.pre_command.value().timing == Timing::Immediately &&
encoder.pre_command.value().is_pressed == false)
{
encoder.pre_command.value().is_pressed = true;
encoder.pre_command.value().command->press();
}
}
}
void HidEngineClass::stopEncoderShift(EncoderShiftIdLink &encoder_shift_id)
{
if (encoder_shift_id.is_linked() == false)
{
return;
}
auto i_item = etl::intrusive_list<EncoderShiftIdLink>::iterator(encoder_shift_id);
_started_encoder_shift_id_list.erase(i_item);
encoder_shift_id.clear();
// 同じidが同時に押されることもあり得るので最後に押されていたかチェック
for (auto &started_encoder_id : _started_encoder_shift_id_list)
{
if (started_encoder_id.value == encoder_shift_id.value)
{
return;
}
}
// 最後のidならclean up
for (auto &encoder : _encoder_shift_map)
{
if (encoder.encoder_shift_id.value == encoder_shift_id.value)
{
if (encoder.pre_command.has_value() &&
encoder.pre_command.value().is_pressed == true)
{
encoder.pre_command.value().is_pressed = false;
encoder.pre_command.value().command->release();
}
encoder.total_step = 0;
}
}
}
} // namespace Internal
Internal::HidEngineClass HidEngine;
} // namespace hidpg
| [
"ogwrtty@gmail.com"
] | ogwrtty@gmail.com |
04daa99c37f017fcb6dbf4599f4486580c24d74f | 7e458c5c0b8c2953ccd7618bd534bd783513fbf3 | /mod/ls/LSCompiler.cpp | 9b9b43d16ab9ff9c5052fab821b4ed6353ecbfa2 | [
"LicenseRef-scancode-public-domain",
"Unlicense"
] | permissive | WindowxDeveloper/L | bdf2fac26861d5b3ae62039a5975a12837190655 | 0d390a6931a8121c9c6b38c363878e475f33211f | refs/heads/master | 2021-04-21T12:57:22.392499 | 2020-03-11T21:04:42 | 2020-03-11T21:04:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,101 | cpp | #include "LSCompiler.h"
#include <L/src/stream/CFileStream.h>
#include "ls.h"
using namespace L;
static const Symbol local_symbol("local"), set_symbol("set"), object_symbol("{object}"), array_symbol("[array]"),
fun_symbol("fun"), return_symbol("return"), foreach_symbol("foreach"), do_symbol("do"), if_symbol("if"), self_symbol("self"),
switch_symbol("switch"), while_symbol("while"), and_symbol("and"), or_symbol("or"), not_symbol("not"),
add_symbol("+"), sub_symbol("-"), mul_symbol("*"), div_symbol("/"), mod_symbol("%"),
add_assign_symbol("+="), sub_assign_symbol("-="), mul_assign_symbol("*="), div_assign_symbol("/="), mod_assign_symbol("%="),
less_symbol("<"), less_equal_symbol("<="), equal_symbol("="), greater_symbol(">"), greater_equal_symbol(">="), not_equal_symbol("<>");
bool LSCompiler::read(const char* text, size_t size) {
return _parser.read(_context, text, size);
}
bool LSCompiler::compile(ScriptFunction& script_function) {
{ // Clean previous state
for(Function* function : _functions) {
Memory::delete_type(function);
}
_functions.clear();
_script = ref<Script>();
}
{ // Compiling
Function& main_function(make_function(_parser.finish()));
resolve_locals(main_function, main_function.code);
if(!compile_function(main_function)) {
return false;
}
}
{ // Bundling functions together
for(Function* function : _functions) {
function->bytecode.push(ScriptInstruction {Return}); // Better safe than sorry
function->bytecode_offset = uint32_t(_script->bytecode.size());
_script->bytecode.insertArray(_script->bytecode.size(), function->bytecode);
}
}
{ // Linking
for(ScriptInstruction& inst : _script->bytecode) {
if(inst.opcode == LoadFun) {
inst.bc16 = int16_t(_functions[inst.bc16]->bytecode_offset);
}
}
}
// Use for debugging
//_script->print(out);
script_function.script = _script;
script_function.offset = 0;
return true;
}
LSCompiler::Function& LSCompiler::make_function(const Var& code, Function* parent) {
_functions.push();
Function*& function(_functions.back());
function = Memory::new_type<Function>();
function->parent = parent;
function->code = code;
function->local_count = 2; // Account for return value and self
function->local_table[self_symbol] = 1; // Self is always at offset 1
return *function;
}
bool LSCompiler::find_outer(Function& func, const Symbol& symbol, uint8_t& outer) {
if(func.parent) {
if(const Symbol* outer_ptr = func.outers.find(symbol)) {
outer = uint8_t(outer_ptr - func.outers.begin());
return true;
} else if(func.parent->local_table.find(symbol)) {
outer = uint8_t(func.outers.size());
func.outers.push(symbol);
return true;
} else if(find_outer(*func.parent, symbol, outer)) {
outer = uint8_t(func.outers.size());
func.outers.push(symbol);
return true;
}
}
return false;
}
void LSCompiler::resolve_locals(Function& func, const L::Var& v) {
if(v.is<Array<Var>>()) {
const Array<Var>& array(v.as<Array<Var>>());
L_ASSERT(array.size() > 0);
if(array[0].is<Symbol>()) { // May be a special construct or a function call
Symbol sym(array[0].as<Symbol>());
if(sym == local_symbol) { // Local var declaration
L_ASSERT(array[1].is<Symbol>());
func.local_table[array[1].as<Symbol>()] = func.local_count++;
} else if(sym == foreach_symbol) {
if(array.size() >= 4) // Value only
func.local_table[array[1].as<Symbol>()] = func.local_count++;
if(array.size() >= 5) // Key value
func.local_table[array[2].as<Symbol>()] = func.local_count++;
} else if(sym == fun_symbol) {
return;
}
}
for(const Var& e : array)
resolve_locals(func, e);
}
}
bool LSCompiler::compile(Function& func, const Var& v, uint8_t offset) {
if(v.is<Array<Var>>()) {
const Array<Var>& array(v.as<Array<Var>>());
L_ASSERT(array.size() > 0);
if(array[0].is<Symbol>()) { // May be a special construct or a function call
const Symbol sym(array[0].as<Symbol>());
if(sym == set_symbol || sym == local_symbol) {
if(array.size() >= 3) {
compile(func, array[2], offset);
compile_assignment(func, array[1], offset, offset + 1);
}
} else if(sym == object_symbol) {
func.bytecode.push(ScriptInstruction {MakeObject, offset});
for(uintptr_t i = 1; i < array.size(); i += 2) {
compile(func, array[i], offset + 1); // Key
compile(func, array[i + 1], offset + 2); // Value
func.bytecode.push(ScriptInstruction {SetItem, offset, uint8_t(offset + 1), uint8_t(offset + 2)});
}
} else if(sym == array_symbol) {
func.bytecode.push(ScriptInstruction {MakeArray, offset});
for(uintptr_t i = 1; i < array.size(); i++) {
compile(func, array[i], offset + 1); // Value
func.bytecode.push(ScriptInstruction {PushItem, offset, uint8_t(offset + 1)});
}
} else if(sym == if_symbol) { // If
for(uintptr_t i(1); i < array.size() - 1; i += 2) {
compile(func, array[i], offset); // Put condition result at offset
// If the result is true, jump right afterwards
func.bytecode.push(ScriptInstruction {CondJump, offset});
func.bytecode.back().bc16 = 1;
// If the result is false, jump after the execution block (will get updated after compilation)
func.bytecode.push(ScriptInstruction {Jump});
const uintptr_t if_not_jump(func.bytecode.size() - 1);
compile(func, array[i + 1], offset);
// Handle else branch
const bool else_branch(!(array.size() & 1) && i == array.size() - 3);
if(else_branch) {
// If the result is false, jump after the execution block (will get updated after compilation)
func.bytecode.push(ScriptInstruction {Jump});
const uintptr_t else_avoid_jump(func.bytecode.size() - 1);
// This is where we jump if the condition hasn't been met before
func.bytecode[if_not_jump].bc16 = int16_t(func.bytecode.size() - if_not_jump) - 1;
compile(func, array.back(), offset);
// This is where we jump to avoid the else branch (condition was met before)
func.bytecode[else_avoid_jump].bc16 = int16_t(func.bytecode.size() - else_avoid_jump) - 1;
} else { // No else branch
// This is where we jump if the condition hasn't been met before
func.bytecode[if_not_jump].bc16 = int16_t(func.bytecode.size() - if_not_jump) - 1;
}
}
} else if(sym == while_symbol) { // While
const uintptr_t start_index(func.bytecode.size());
// Compute condition at offset
compile(func, array[1], offset);
// If the result is true, jump right afterwards
func.bytecode.push(ScriptInstruction {CondJump, offset});
func.bytecode.back().bc16 = 1;
// If the result is false, jump after the execution block (will get updated after compilation)
func.bytecode.push(ScriptInstruction {Jump});
const uintptr_t if_not_jump(func.bytecode.size() - 1);
compile(func, array[2], offset);
// Jump back to the start
func.bytecode.push(ScriptInstruction {Jump});
func.bytecode.back().bc16 = int16_t(start_index) - int16_t(func.bytecode.size());
// This is where we jump if the condition hasn't been met before
func.bytecode[if_not_jump].bc16 = int16_t(func.bytecode.size() - if_not_jump) - 1;
} else if(sym == foreach_symbol) {
if(array.size() < 4) {
warning("ls: %s:%d: foreach is missing parameters: (foreach [key] value iterable statement)", _context.begin(), 0);
return false;
}
const Var& key = array.size() == 4 ? array[1] : array[1];
const Var& value = array.size() == 4 ? array[1] : array[2];
const Var& iterable = array.size() == 4 ? array[2] : array[3];
const Var& statement = array.size() == 4 ? array[3] : array[4];
// Compute object at offset
compile(func, iterable, offset);
func.bytecode.push(ScriptInstruction {MakeIterator, uint8_t(offset + 1), offset});
// If the iteration has ended, jump after the loop
func.bytecode.push(ScriptInstruction {IterEndJump, uint8_t(offset + 1)});
const uintptr_t end_jump(func.bytecode.size() - 1);
// Get next key/value pair
const uint8_t key_local(*func.local_table.find(key.as<Symbol>()));
const uint8_t value_local(*func.local_table.find(value.as<Symbol>()));
func.bytecode.push(ScriptInstruction {Iterate, key_local, value_local, uint8_t(offset + 1)});
// Execute loop body
compile(func, statement, offset + 2);
// Jump back to beginning of loop
func.bytecode.push(ScriptInstruction {Jump});
func.bytecode.back().bc16 = int16_t(end_jump) - int16_t(func.bytecode.size());
// This is where we jump if the iterator has reached the end
func.bytecode[end_jump].bc16 = int16_t(func.bytecode.size() - end_jump) - 1;
} else if(sym == switch_symbol) { // Switch
// Put first compare value at offset
compile(func, array[1], offset);
Array<uintptr_t> cond_jumps; // Will jump to appropriate code block if condition was met
Array<uintptr_t> end_jumps; // Will jump *after* the switch
// Start by doing comparisons until one matches
for(uintptr_t i(2); i < array.size() - 1; i += 2) {
// Put second compare value at offset+1
compile(func, array[i], offset + 1);
// Replace second compare value by comparison result
func.bytecode.push(ScriptInstruction {Equal, uint8_t(offset + 1), offset, uint8_t(offset + 1)});
// Use result to jump conditionally
func.bytecode.push(ScriptInstruction {CondJump, uint8_t(offset + 1)});
cond_jumps.push(func.bytecode.size() - 1);
}
// Compile the default case if there's one
// We'll fallthrough here if none of the conditions were met
if((array.size() & 1) != 0) {
// Default case is always at the end of the switch
compile(func, array.back(), offset);
}
// Jump to after the switch
func.bytecode.push(ScriptInstruction {Jump});
end_jumps.push(func.bytecode.size() - 1);
// Compile other cases
for(uintptr_t i(2); i < array.size() - 1; i += 2) {
// Update corresponding conditional jump to jump here
const uintptr_t cond_jump(cond_jumps[(i - 2) / 2]);
func.bytecode[cond_jump].bc16 = int16_t(func.bytecode.size() - cond_jump) - 1;
// Compile the code
compile(func, array[i + 1], offset);
// Jump to after the switch
func.bytecode.push(ScriptInstruction {Jump});
end_jumps.push(func.bytecode.size() - 1);
}
// Update all end jumps to jump here
for(uintptr_t end_jump : end_jumps) {
func.bytecode[end_jump].bc16 = int16_t(func.bytecode.size() - end_jump) - 1;
}
} else if(sym == and_symbol) { // And
Array<uintptr_t> end_jumps; // Will jump *after* the and
for(uintptr_t i(1); i < array.size(); i++) {
compile(func, array[i], offset);
func.bytecode.push(ScriptInstruction {CondNotJump, offset});
end_jumps.push(func.bytecode.size() - 1);
}
// Update all end jumps to jump here
for(uintptr_t end_jump : end_jumps) {
func.bytecode[end_jump].bc16 = int16_t(func.bytecode.size() - end_jump) - 1;
}
} else if(sym == or_symbol) { // Or
Array<uintptr_t> end_jumps; // Will jump *after* the or
for(uintptr_t i(1); i < array.size(); i++) {
compile(func, array[i], offset);
func.bytecode.push(ScriptInstruction {CondJump, offset});
end_jumps.push(func.bytecode.size() - 1);
}
// Update all end jumps to jump here
for(uintptr_t end_jump : end_jumps) {
func.bytecode[end_jump].bc16 = int16_t(func.bytecode.size() - end_jump) - 1;
}
} else if(sym == not_symbol) { // Not
compile(func, array[1], offset);
func.bytecode.push(ScriptInstruction {Not, offset});
} else if(sym == fun_symbol) { // Function
if(array.size() > 1) {
// Make a new function from the last item of the array
// because the last part is always the code
Function& new_function(make_function(array.back(), &func));
{ // Deal with potential parameters
for(uintptr_t i = 1; i < array.size() - 1; i++) {
if(array[i].is<Symbol>()) {
new_function.local_table[array[i].as<Symbol>()] = new_function.local_count++;
} else {
warning("ls: %s:%d: Function parameter names must be symbols", _context.begin(), 0);
return false;
}
}
}
// Save index of function in LoadFun to allow linking later
func.bytecode.push(ScriptInstruction {LoadFun, offset});
func.bytecode.back().bc16 = int16_t(_functions.size() - 1);
resolve_locals(new_function, new_function.code);
compile_function(new_function);
// Capture outers
for(const Symbol& symbol : new_function.outers) {
if(const uint8_t* local = func.local_table.find(symbol)) {
func.bytecode.push(ScriptInstruction {CaptLocal, offset, *local});
} else if(const Symbol* outer_ptr = func.outers.find(symbol)) {
func.bytecode.push(ScriptInstruction {CaptOuter, offset, uint8_t(outer_ptr - func.outers.begin())});
}
}
}
return true;
} else if(sym == return_symbol) {
for(uintptr_t i = 1; i < array.size(); i++) {
compile(func, array[i], uint8_t(offset + i - 1));
}
for(uintptr_t i = 1; i < array.size(); i++) {
func.bytecode.push(ScriptInstruction {CopyLocal, uint8_t(i - 1), uint8_t(offset + i - 1)});
}
func.bytecode.push(ScriptInstruction {Return});
} else if(sym == add_assign_symbol) {
compile_op_assign(func, array, offset, Add);
} else if(sym == sub_assign_symbol) {
compile_op_assign(func, array, offset, Sub);
} else if(sym == mul_assign_symbol) {
compile_op_assign(func, array, offset, Mul);
} else if(sym == div_assign_symbol) {
compile_op_assign(func, array, offset, Div);
} else if(sym == mod_assign_symbol) {
compile_op_assign(func, array, offset, Mod);
} else if(sym == add_symbol) { // Addition
compile_operator(func, array, offset, Add);
} else if(sym == sub_symbol) { // Subtraction and invert
if(array.size() > 2) {
compile_operator(func, array, offset, Sub);
} else {
compile(func, array[1], offset);
func.bytecode.push(ScriptInstruction {Inv, offset});
}
} else if(sym == mul_symbol) { // Multiplication
compile_operator(func, array, offset, Mul);
} else if(sym == div_symbol) { // Division
compile_operator(func, array, offset, Div);
} else if(sym == mod_symbol) { // Modulo
compile_operator(func, array, offset, Mod);
} else if(sym == less_symbol) { // Less
compile_comparison(func, array, offset, LessThan);
} else if(sym == less_equal_symbol) { // Less equal
compile_comparison(func, array, offset, LessEqual);
} else if(sym == equal_symbol) { // Equal
compile_comparison(func, array, offset, Equal);
} else if(sym == greater_symbol) { // Greater
compile_comparison(func, array, offset, LessEqual, true);
} else if(sym == greater_equal_symbol) { // Greater equal
compile_comparison(func, array, offset, LessThan, true);
} else if(sym == not_equal_symbol) { // Not equal
compile_comparison(func, array, offset, Equal, true);
} else if(sym == do_symbol) {
for(uint32_t i(1); i < array.size(); i++) {
compile(func, array[i], offset);
}
} else { // It's a function call
compile_function_call(func, array, offset);
}
} else { // It's also a function call
compile_function_call(func, array, offset);
}
} else if(v.is<AccessChain>()) {
compile_access_chain(func, v.as<AccessChain>().array, offset, true);
} else if(v.is<Symbol>()) {
uint8_t outer;
if(const uint8_t* local = func.local_table.find(v.as<Symbol>())) {
func.bytecode.push(ScriptInstruction {CopyLocal, offset, *local});
} else if(find_outer(func, v.as<Symbol>(), outer)) {
func.bytecode.push(ScriptInstruction {LoadOuter, offset, outer});
} else {
func.bytecode.push(ScriptInstruction {LoadGlobal, offset});
func.bytecode.back().bcu16 = _script->global(v.as<Symbol>());
}
} else {
Var cst(v);
if(v.is<RawSymbol>()) {
const Symbol sym(v.as<RawSymbol>().sym);
cst = sym;
}
func.bytecode.push(ScriptInstruction {LoadConst, offset});
func.bytecode.back().bcu16 = _script->constant(cst);
}
return true;
}
bool LSCompiler::compile_function(Function& func) {
// Use local_count as start offset to avoid overwriting parameters
const uint8_t func_offset(func.local_count);
if(!compile(func, func.code, func_offset)) {
return false;
}
// We're compiling to target func_offset as a return value,
// copy that to the actual return value (0)
func.bytecode.push(ScriptInstruction {CopyLocal, 0, func_offset});
return true;
}
void LSCompiler::compile_access_chain(Function& func, const Array<Var>& array, uint8_t offset, bool get) {
L_ASSERT(array.size() >= 2);
compile(func, array[0], offset + 1); // Object
compile(func, array[1], offset + 2); // Index
for(uint32_t i(2); i < array.size(); i++) {
// Put Object[Index] where Object was
func.bytecode.push(ScriptInstruction {GetItem, uint8_t(offset + 1), uint8_t(offset + 2), uint8_t(offset + 1)});
// Replace Index with next index in array
compile(func, array[i], offset + 2);
}
if(get) {
// Do final access
func.bytecode.push(ScriptInstruction {GetItem, uint8_t(offset + 1), uint8_t(offset + 2), offset});
} else {
func.bytecode.push(ScriptInstruction {CopyLocal, offset, uint8_t(offset + 2)});
}
}
void LSCompiler::compile_function_call(Function& func, const Array<Var>& array, uint8_t offset) {
compile(func, array[0], offset);
// Self should already be at offset+1 if specified
for(uint32_t i(1); i < array.size(); i++) {
compile(func, array[i], uint8_t(offset + i + 1));
}
func.bytecode.push(ScriptInstruction {Call, offset, uint8_t(array.size() - 1)});
}
void LSCompiler::compile_assignment(Function& func, const L::Var& dst, uint8_t src, uint8_t offset) {
if(dst.is<Symbol>()) {
uint8_t outer;
if(const uint8_t* local = func.local_table.find(dst.as<Symbol>())) {
func.bytecode.push(ScriptInstruction {CopyLocal, *local, src});
} else if(find_outer(func, dst.as<Symbol>(), outer)) {
func.bytecode.push(ScriptInstruction {StoreOuter, outer, src});
} else {
func.bytecode.push(ScriptInstruction {StoreGlobal, src});
func.bytecode.back().bcu16 = _script->global(dst.as<Symbol>());
}
} else if(dst.is<AccessChain>()) {
const Array<Var>& access_chain(dst.as<AccessChain>().array);
compile_access_chain(func, access_chain, offset, false);
func.bytecode.push(ScriptInstruction {SetItem, uint8_t(offset + 1), offset, src});
} else {
error("Trying to set a literal value or something?");
}
}
void LSCompiler::compile_operator(Function& func, const L::Array<L::Var>& array, uint8_t offset, ScriptOpCode opcode) {
L_ASSERT(array.size() > 1);
compile(func, array[1], offset);
for(uint32_t i(2); i < array.size(); i++) {
compile(func, array[i], offset + 1);
func.bytecode.push(ScriptInstruction {opcode, offset, uint8_t(offset + 1)});
}
}
void LSCompiler::compile_op_assign(Function& func, const Array<Var>& array, uint8_t offset, ScriptOpCode opcode) {
L_ASSERT(array.size() >= 3);
// There's a special case for local targets but otherwise we'll do a copy, operate on it, then assign it back
// To be honest this special case could be dealt with during optimization later
if(array[1].is<Symbol>()) {
if(uint8_t* found = func.local_table.find(array[1].as<Symbol>())) {
for(uintptr_t i(2); i < array.size(); i++) {
compile(func, array[i], offset);
func.bytecode.push(ScriptInstruction {opcode, *found, offset});
}
return;
}
}
compile(func, array[1], offset);
for(uintptr_t i(2); i < array.size(); i++) {
compile(func, array[i], offset + 1);
func.bytecode.push(ScriptInstruction {opcode, offset, uint8_t(offset + 1)});
}
compile_assignment(func, array[1], offset, offset + 1);
}
void LSCompiler::compile_comparison(Function& func, const L::Array<L::Var>& array, uint8_t offset, ScriptOpCode cmp, bool not) {
L_ASSERT(array.size() >= 3);
if(array.size() >= 3) {
Array<uintptr_t> end_jumps; // Will jump *after* the comparison
compile(func, array[1], offset + 1);
for(uintptr_t i(2); i < array.size(); i++) {
compile(func, array[i], uint8_t(offset + i));
func.bytecode.push(ScriptInstruction {cmp, offset, uint8_t(offset + i - 1), uint8_t(offset + i)});
if(not) {
func.bytecode.push(ScriptInstruction {Not, offset});
}
func.bytecode.push(ScriptInstruction {CondNotJump, offset});
end_jumps.push(func.bytecode.size() - 1);
}
// Update all end jumps to jump here
for(uintptr_t end_jump : end_jumps) {
func.bytecode[end_jump].bc16 = int16_t(func.bytecode.size() - end_jump) - 1;
}
} else {
error("Comparisons need at least two operands");
}
} | [
"lutopia@hotmail.fr"
] | lutopia@hotmail.fr |
16f4640694be942494c95e736078113659b21422 | 501ab25fa68690556d90d528b0c8fb6ef5b0eeee | /Белый пояс/Неделя 1/Второе вхождение/Vtor.vhoz.cpp | 90f262061b86a95882481de0084254b8e45c0ebc | [] | no_license | spectrdort/kurs_yandex | 2ec6badf4532eb2ae70a44c54bfafabe7f9f7407 | 3c2571720947f9b508bd577f8c4fd435cd984193 | refs/heads/master | 2023-06-09T14:09:08.869588 | 2021-06-15T19:55:38 | 2021-06-15T19:55:38 | 366,669,939 | 0 | 0 | null | 2021-06-15T19:55:39 | 2021-05-12T09:58:06 | C++ | UTF-8 | C++ | false | false | 360 | cpp | #include <iostream>
#include <vector>
#include <string>
#include <algorithm>
int main()
{
std::string n;
std::cin >> n;
int x = 0;
for (int i = 0; i < n.size(); ++i)
{
if (n[i] == 'f')
{
x++;
if (x >= 2)
{
std::cout << i;
return 0;
}
}
}
if (x == 0)
{
std::cout << "-2";
}
else
{
std::cout << "-1";
}
return 0;
} | [
"sms1995@rocketmail.com"
] | sms1995@rocketmail.com |
936422abc7f1c877dc8f0f8718e8363a4efaa886 | 161f5c2652f7e1784adc17325ab8ad7120b224c4 | /src/rangeslider.cpp | 434501ffef0706e3f5a2432e4e11eee9375b205a | [
"Apache-2.0"
] | permissive | hbtalha/MediaCutter | 82da98fa50854a0687e2dd714573bbc66439e587 | e803191cea9e056d620f06d2e485916e884c3735 | refs/heads/main | 2023-08-29T19:17:13.995883 | 2021-10-12T21:39:10 | 2021-10-12T21:39:10 | 414,444,491 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29,659 | cpp | /*=========================================================================
Library: CTK
Copyright (c) Kitware Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
// Qt includes
#include <QDebug>
#include <QMouseEvent>
#include <QKeyEvent>
#include <QStyleOptionSlider>
#include <QApplication>
#include <QStylePainter>
#include <QStyle>
#include <QToolTip>
// CTK includes
#include "rangeslider.h"
class RangeSliderPrivate
{
Q_DECLARE_PUBLIC(RangeSlider);
protected:
RangeSlider* const q_ptr;
public:
/// Boolean indicates the selected handle
/// True for the minimum range handle, false for the maximum range handle
enum Handle
{
NoHandle = 0x0,
MinimumHandle = 0x1,
MaximumHandle = 0x2
};
Q_DECLARE_FLAGS(Handles, Handle);
RangeSliderPrivate(RangeSlider& object);
void init();
/// Return the handle at the given pos, or none if no handle is at the pos.
/// If a handle is selected, handleRect is set to the handle rect.
/// otherwise return NoHandle and handleRect is set to the combined rect of
/// the min and max handles
Handle handleAtPos(const QPoint& pos, QRect& handleRect)const;
/// Copied verbatim from QSliderPrivate class (see QSlider.cpp)
int pixelPosToRangeValue(int pos) const;
int pixelPosFromRangeValue(int val) const;
/// Draw the bottom and top sliders.
void drawMinimumSlider( QStylePainter* painter ) const;
void drawMaximumSlider( QStylePainter* painter ) const;
/// End points of the range on the Model
int m_MaximumValue;
int m_MinimumValue;
/// End points of the range on the GUI. This is synced with the model.
int m_MaximumPosition;
int m_MinimumPosition;
/// Controls selected ?
QStyle::SubControl m_MinimumSliderSelected;
QStyle::SubControl m_MaximumSliderSelected;
/// See QSliderPrivate::clickOffset.
/// Overrides this ivar
int m_SubclassClickOffset;
/// See QSliderPrivate::position
/// Overrides this ivar.
int m_SubclassPosition;
/// Original width between the 2 bounds before any moves
int m_SubclassWidth;
RangeSliderPrivate::Handles m_SelectedHandles;
/// When symmetricMoves is true, moving a handle will move the other handle
/// symmetrically, otherwise the handles are independent.
bool m_SymmetricMoves;
QString m_HandleToolTip;
private:
Q_DISABLE_COPY(RangeSliderPrivate);
};
// --------------------------------------------------------------------------
RangeSliderPrivate::RangeSliderPrivate(RangeSlider& object)
:q_ptr(&object)
{
this->m_MinimumValue = 0;
this->m_MaximumValue = 100;
this->m_MinimumPosition = 0;
this->m_MaximumPosition = 100;
this->m_MinimumSliderSelected = QStyle::SC_None;
this->m_MaximumSliderSelected = QStyle::SC_None;
this->m_SubclassClickOffset = 0;
this->m_SubclassPosition = 0;
this->m_SubclassWidth = 0;
this->m_SelectedHandles = NoHandle;
this->m_SymmetricMoves = false;
}
// --------------------------------------------------------------------------
void RangeSliderPrivate::init()
{
Q_Q(RangeSlider);
this->m_MinimumValue = q->minimum();
this->m_MaximumValue = q->maximum();
this->m_MinimumPosition = q->minimum();
this->m_MaximumPosition = q->maximum();
q->connect(q, SIGNAL(rangeChanged(int,int)), q, SLOT(onRangeChanged(int,int)));
}
// --------------------------------------------------------------------------
RangeSliderPrivate::Handle RangeSliderPrivate::handleAtPos(const QPoint& pos, QRect& handleRect)const
{
Q_Q(const RangeSlider);
QStyleOptionSlider option;
q->initStyleOption( &option );
// The functinos hitTestComplexControl only know about 1 handle. As we have
// 2, we change the position of the handle and test if the pos correspond to
// any of the 2 positions.
// Test the MinimumHandle
option.sliderPosition = this->m_MinimumPosition;
option.sliderValue = this->m_MinimumValue;
QStyle::SubControl minimumControl = q->style()->hitTestComplexControl(
QStyle::CC_Slider, &option, pos, q);
QRect minimumHandleRect = q->style()->subControlRect(
QStyle::CC_Slider, &option, QStyle::SC_SliderHandle, q);
// Test if the pos is under the Maximum handle
option.sliderPosition = this->m_MaximumPosition;
option.sliderValue = this->m_MaximumValue;
QStyle::SubControl maximumControl = q->style()->hitTestComplexControl(
QStyle::CC_Slider, &option, pos, q);
QRect maximumHandleRect = q->style()->subControlRect(
QStyle::CC_Slider, &option, QStyle::SC_SliderHandle, q);
// The pos is above both handles, select the closest handle
if (minimumControl == QStyle::SC_SliderHandle &&
maximumControl == QStyle::SC_SliderHandle)
{
int minDist = 0;
int maxDist = 0;
if (q->orientation() == Qt::Horizontal)
{
minDist = pos.x() - minimumHandleRect.left();
maxDist = maximumHandleRect.right() - pos.x();
}
else //if (q->orientation() == Qt::Vertical)
{
minDist = minimumHandleRect.bottom() - pos.y();
maxDist = pos.y() - maximumHandleRect.top();
}
Q_ASSERT( minDist >= 0 && maxDist >= 0);
minimumControl = minDist < maxDist ? minimumControl : QStyle::SC_None;
}
if (minimumControl == QStyle::SC_SliderHandle)
{
handleRect = minimumHandleRect;
return MinimumHandle;
}
else if (maximumControl == QStyle::SC_SliderHandle)
{
handleRect = maximumHandleRect;
return MaximumHandle;
}
handleRect = minimumHandleRect.united(maximumHandleRect);
return NoHandle;
}
// --------------------------------------------------------------------------
// Copied verbatim from QSliderPrivate::pixelPosToRangeValue. See QSlider.cpp
//
int RangeSliderPrivate::pixelPosToRangeValue( int pos ) const
{
Q_Q(const RangeSlider);
QStyleOptionSlider option;
q->initStyleOption( &option );
QRect gr = q->style()->subControlRect( QStyle::CC_Slider,
&option,
QStyle::SC_SliderGroove,
q );
QRect sr = q->style()->subControlRect( QStyle::CC_Slider,
&option,
QStyle::SC_SliderHandle,
q );
int sliderMin, sliderMax, sliderLength;
if (option.orientation == Qt::Horizontal)
{
sliderLength = sr.width();
sliderMin = gr.x();
sliderMax = gr.right() - sliderLength + 1;
}
else
{
sliderLength = sr.height();
sliderMin = gr.y();
sliderMax = gr.bottom() - sliderLength + 1;
}
return QStyle::sliderValueFromPosition( q->minimum(),
q->maximum(),
pos - sliderMin,
sliderMax - sliderMin,
option.upsideDown );
}
//---------------------------------------------------------------------------
int RangeSliderPrivate::pixelPosFromRangeValue( int val ) const
{
Q_Q(const RangeSlider);
QStyleOptionSlider option;
q->initStyleOption( &option );
QRect gr = q->style()->subControlRect( QStyle::CC_Slider,
&option,
QStyle::SC_SliderGroove,
q );
QRect sr = q->style()->subControlRect( QStyle::CC_Slider,
&option,
QStyle::SC_SliderHandle,
q );
int sliderMin, sliderMax, sliderLength;
if (option.orientation == Qt::Horizontal)
{
sliderLength = sr.width();
sliderMin = gr.x();
sliderMax = gr.right() - sliderLength + 1;
}
else
{
sliderLength = sr.height();
sliderMin = gr.y();
sliderMax = gr.bottom() - sliderLength + 1;
}
return QStyle::sliderPositionFromValue( q->minimum(),
q->maximum(),
val,
sliderMax - sliderMin,
option.upsideDown ) + sliderMin;
}
//---------------------------------------------------------------------------
// Draw slider at the bottom end of the range
void RangeSliderPrivate::drawMinimumSlider( QStylePainter* painter ) const
{
Q_Q(const RangeSlider);
QStyleOptionSlider option;
q->initMinimumSliderStyleOption( &option );
option.subControls = QStyle::SC_SliderHandle;
option.sliderValue = m_MinimumValue;
option.sliderPosition = m_MinimumPosition;
if (q->isMinimumSliderDown())
{
option.activeSubControls = QStyle::SC_SliderHandle;
option.state |= QStyle::State_Sunken;
}
#ifdef Q_OS_MAC
// On mac style, drawing just the handle actually draws also the groove.
QRect clip = q->style()->subControlRect(QStyle::CC_Slider, &option,
QStyle::SC_SliderHandle, q);
painter->setClipRect(clip);
#endif
painter->drawComplexControl(QStyle::CC_Slider, option);
}
//---------------------------------------------------------------------------
// Draw slider at the top end of the range
void RangeSliderPrivate::drawMaximumSlider( QStylePainter* painter ) const
{
Q_Q(const RangeSlider);
QStyleOptionSlider option;
q->initMaximumSliderStyleOption( &option );
option.subControls = QStyle::SC_SliderHandle;
option.sliderValue = m_MaximumValue;
option.sliderPosition = m_MaximumPosition;
if (q->isMaximumSliderDown())
{
option.activeSubControls = QStyle::SC_SliderHandle;
option.state |= QStyle::State_Sunken;
}
#ifdef Q_OS_MAC
// On mac style, drawing just the handle actually draws also the groove.
QRect clip = q->style()->subControlRect(QStyle::CC_Slider, &option,
QStyle::SC_SliderHandle, q);
painter->setClipRect(clip);
#endif
painter->drawComplexControl(QStyle::CC_Slider, option);
}
// --------------------------------------------------------------------------
RangeSlider::RangeSlider(QWidget* _parent)
: QSlider(_parent)
, d_ptr(new RangeSliderPrivate(*this))
{
Q_D(RangeSlider);
d->init();
}
// --------------------------------------------------------------------------
RangeSlider::RangeSlider( Qt::Orientation o,
QWidget* parentObject )
:QSlider(o, parentObject)
, d_ptr(new RangeSliderPrivate(*this))
{
Q_D(RangeSlider);
d->init();
}
// --------------------------------------------------------------------------
RangeSlider::RangeSlider(RangeSliderPrivate* impl, QWidget* _parent)
: QSlider(_parent)
, d_ptr(impl)
{
Q_D(RangeSlider);
d->init();
}
// --------------------------------------------------------------------------
RangeSlider::RangeSlider( RangeSliderPrivate* impl, Qt::Orientation o,
QWidget* parentObject )
:QSlider(o, parentObject)
, d_ptr(impl)
{
Q_D(RangeSlider);
d->init();
}
// --------------------------------------------------------------------------
RangeSlider::~RangeSlider()
{
}
// --------------------------------------------------------------------------
int RangeSlider::minimumValue() const
{
Q_D(const RangeSlider);
return d->m_MinimumValue;
}
// --------------------------------------------------------------------------
void RangeSlider::setMinimumValue( int min )
{
Q_D(RangeSlider);
this->setValues( min, qMax(d->m_MaximumValue,min) );
}
// --------------------------------------------------------------------------
int RangeSlider::maximumValue() const
{
Q_D(const RangeSlider);
return d->m_MaximumValue;
}
// --------------------------------------------------------------------------
void RangeSlider::setMaximumValue( int max )
{
Q_D(RangeSlider);
this->setValues( qMin(d->m_MinimumValue, max), max );
}
// --------------------------------------------------------------------------
void RangeSlider::setValues(int l, int u)
{
Q_D(RangeSlider);
const int minValue =
qBound(this->minimum(), qMin(l,u), this->maximum());
const int maxValue =
qBound(this->minimum(), qMax(l,u), this->maximum());
bool emitMinValChanged = (minValue != d->m_MinimumValue);
bool emitMaxValChanged = (maxValue != d->m_MaximumValue);
d->m_MinimumValue = minValue;
d->m_MaximumValue = maxValue;
bool emitMinPosChanged =
(minValue != d->m_MinimumPosition);
bool emitMaxPosChanged =
(maxValue != d->m_MaximumPosition);
d->m_MinimumPosition = minValue;
d->m_MaximumPosition = maxValue;
if (isSliderDown())
{
if (emitMinPosChanged || emitMaxPosChanged)
{
emit positionsChanged(d->m_MinimumPosition, d->m_MaximumPosition);
}
if (emitMinPosChanged)
{
emit minimumPositionChanged(d->m_MinimumPosition);
}
if (emitMaxPosChanged)
{
emit maximumPositionChanged(d->m_MaximumPosition);
}
}
if (emitMinValChanged || emitMaxValChanged)
{
emit valuesChanged(d->m_MinimumValue,
d->m_MaximumValue);
}
if (emitMinValChanged)
{
emit minimumValueChanged(d->m_MinimumValue);
}
if (emitMaxValChanged)
{
emit maximumValueChanged(d->m_MaximumValue);
}
if (emitMinPosChanged || emitMaxPosChanged ||
emitMinValChanged || emitMaxValChanged)
{
this->update();
}
}
// --------------------------------------------------------------------------
int RangeSlider::minimumPosition() const
{
Q_D(const RangeSlider);
return d->m_MinimumPosition;
}
// --------------------------------------------------------------------------
int RangeSlider::maximumPosition() const
{
Q_D(const RangeSlider);
return d->m_MaximumPosition;
}
// --------------------------------------------------------------------------
void RangeSlider::setMinimumPosition(int l)
{
Q_D(const RangeSlider);
this->setPositions(l, qMax(l, d->m_MaximumPosition));
}
// --------------------------------------------------------------------------
void RangeSlider::setMaximumPosition(int u)
{
Q_D(const RangeSlider);
this->setPositions(qMin(d->m_MinimumPosition, u), u);
}
// --------------------------------------------------------------------------
void RangeSlider::setPositions(int min, int max)
{
Q_D(RangeSlider);
const int minPosition =
qBound(this->minimum(), qMin(min, max), this->maximum());
const int maxPosition =
qBound(this->minimum(), qMax(min, max), this->maximum());
bool emitMinPosChanged = (minPosition != d->m_MinimumPosition);
bool emitMaxPosChanged = (maxPosition != d->m_MaximumPosition);
if (!emitMinPosChanged && !emitMaxPosChanged)
{
return;
}
d->m_MinimumPosition = minPosition;
d->m_MaximumPosition = maxPosition;
if (!this->hasTracking())
{
this->update();
}
if (isSliderDown())
{
if (emitMinPosChanged)
{
emit minimumPositionChanged(d->m_MinimumPosition);
}
if (emitMaxPosChanged)
{
emit maximumPositionChanged(d->m_MaximumPosition);
}
if (emitMinPosChanged || emitMaxPosChanged)
{
emit positionsChanged(d->m_MinimumPosition, d->m_MaximumPosition);
}
}
if (this->hasTracking())
{
this->triggerAction(SliderMove);
this->setValues(d->m_MinimumPosition, d->m_MaximumPosition);
}
}
// --------------------------------------------------------------------------
void RangeSlider::setSymmetricMoves(bool symmetry)
{
Q_D(RangeSlider);
d->m_SymmetricMoves = symmetry;
}
// --------------------------------------------------------------------------
bool RangeSlider::symmetricMoves()const
{
Q_D(const RangeSlider);
return d->m_SymmetricMoves;
}
// --------------------------------------------------------------------------
void RangeSlider::onRangeChanged(int _minimum, int _maximum)
{
Q_UNUSED(_minimum);
Q_UNUSED(_maximum);
Q_D(RangeSlider);
this->setValues(d->m_MinimumValue, d->m_MaximumValue);
}
// --------------------------------------------------------------------------
// Render
void RangeSlider::paintEvent( QPaintEvent* )
{
Q_D(RangeSlider);
QStyleOptionSlider option;
this->initStyleOption(&option);
QStylePainter painter(this);
option.subControls = QStyle::SC_SliderGroove;
// Move to minimum to not highlight the SliderGroove.
// On mac style, drawing just the slider groove also draws the handles,
// therefore we give a negative (outside of view) position.
option.sliderValue = this->minimum() - this->maximum();
option.sliderPosition = this->minimum() - this->maximum();
painter.drawComplexControl(QStyle::CC_Slider, option);
option.sliderPosition = d->m_MinimumPosition;
const QRect lr = style()->subControlRect( QStyle::CC_Slider,
&option,
QStyle::SC_SliderHandle,
this);
option.sliderPosition = d->m_MaximumPosition;
const QRect ur = style()->subControlRect( QStyle::CC_Slider,
&option,
QStyle::SC_SliderHandle,
this);
QRect sr = style()->subControlRect( QStyle::CC_Slider,
&option,
QStyle::SC_SliderGroove,
this);
QRect rangeBox;
if (option.orientation == Qt::Horizontal)
{
rangeBox = QRect(
QPoint(qMin( lr.center().x(), ur.center().x() ), sr.center().y() - 2),
QPoint(qMax( lr.center().x(), ur.center().x() ), sr.center().y() + 1));
}
else
{
rangeBox = QRect(
QPoint(sr.center().x() - 2, qMin( lr.center().y(), ur.center().y() )),
QPoint(sr.center().x() + 1, qMax( lr.center().y(), ur.center().y() )));
}
// -----------------------------
// Render the range
//
QRect groove = this->style()->subControlRect( QStyle::CC_Slider,
&option,
QStyle::SC_SliderGroove,
this );
groove.adjust(0, 0, -1, 0);
// Create default colors based on the transfer function.
//
QColor highlight = this->palette().color(QPalette::Normal, QPalette::Highlight);
QLinearGradient gradient;
if (option.orientation == Qt::Horizontal)
{
gradient = QLinearGradient( groove.center().x(), groove.top(),
groove.center().x(), groove.bottom());
}
else
{
gradient = QLinearGradient( groove.left(), groove.center().y(),
groove.right(), groove.center().y());
}
// TODO: Set this based on the supplied transfer function
//QColor l = Qt::darkGray;
//QColor u = Qt::black;
gradient.setColorAt(0, highlight.darker(120));
gradient.setColorAt(1, highlight.lighter(160));
painter.setPen(QPen(highlight.darker(150), 0));
painter.setBrush(gradient);
painter.drawRect( rangeBox.intersected(groove) );
// -----------------------------------
// Render the sliders
//
if (this->isMinimumSliderDown())
{
d->drawMaximumSlider( &painter );
d->drawMinimumSlider( &painter );
}
else
{
d->drawMinimumSlider( &painter );
d->drawMaximumSlider( &painter );
}
}
// --------------------------------------------------------------------------
// Standard Qt UI events
void RangeSlider::mousePressEvent(QMouseEvent* mouseEvent)
{
Q_D(RangeSlider);
if (minimum() == maximum() || (mouseEvent->buttons() ^ mouseEvent->button()))
{
mouseEvent->ignore();
return;
}
int mepos = this->orientation() == Qt::Horizontal ?
mouseEvent->pos().x() : mouseEvent->pos().y();
QStyleOptionSlider option;
this->initStyleOption( &option );
QRect handleRect;
RangeSliderPrivate::Handle handle_ = d->handleAtPos(mouseEvent->pos(), handleRect);
if (handle_ != RangeSliderPrivate::NoHandle)
{
d->m_SubclassPosition = (handle_ == RangeSliderPrivate::MinimumHandle)?
d->m_MinimumPosition : d->m_MaximumPosition;
// save the position of the mouse inside the handle for later
d->m_SubclassClickOffset = mepos - (this->orientation() == Qt::Horizontal ?
handleRect.left() : handleRect.top());
this->setSliderDown(true);
if (d->m_SelectedHandles != handle_)
{
d->m_SelectedHandles = handle_;
this->update(handleRect);
}
// Accept the mouseEvent
mouseEvent->accept();
return;
}
// if we are here, no handles have been pressed
// Check if we pressed on the groove between the 2 handles
QStyle::SubControl control = this->style()->hitTestComplexControl(
QStyle::CC_Slider, &option, mouseEvent->pos(), this);
QRect sr = style()->subControlRect(
QStyle::CC_Slider, &option, QStyle::SC_SliderGroove, this);
int minCenter = (this->orientation() == Qt::Horizontal ?
handleRect.left() : handleRect.top());
int maxCenter = (this->orientation() == Qt::Horizontal ?
handleRect.right() : handleRect.bottom());
if (control == QStyle::SC_SliderGroove &&
mepos > minCenter && mepos < maxCenter)
{
// warning lost of precision it might be fatal
d->m_SubclassPosition = (d->m_MinimumPosition + d->m_MaximumPosition) / 2.;
d->m_SubclassClickOffset = mepos - d->pixelPosFromRangeValue(d->m_SubclassPosition);
d->m_SubclassWidth = (d->m_MaximumPosition - d->m_MinimumPosition) / 2;
qMax(d->m_SubclassPosition - d->m_MinimumPosition, d->m_MaximumPosition - d->m_SubclassPosition);
this->setSliderDown(true);
if (!this->isMinimumSliderDown() || !this->isMaximumSliderDown())
{
d->m_SelectedHandles =
QFlags<RangeSliderPrivate::Handle>(RangeSliderPrivate::MinimumHandle) |
QFlags<RangeSliderPrivate::Handle>(RangeSliderPrivate::MaximumHandle);
this->update(handleRect.united(sr));
}
mouseEvent->accept();
return;
}
mouseEvent->ignore();
}
// --------------------------------------------------------------------------
// Standard Qt UI events
void RangeSlider::mouseMoveEvent(QMouseEvent* mouseEvent)
{
Q_D(RangeSlider);
if (!d->m_SelectedHandles)
{
mouseEvent->ignore();
return;
}
int mepos = this->orientation() == Qt::Horizontal ?
mouseEvent->pos().x() : mouseEvent->pos().y();
QStyleOptionSlider option;
this->initStyleOption(&option);
const int m = style()->pixelMetric( QStyle::PM_MaximumDragDistance, &option, this );
int newPosition = d->pixelPosToRangeValue(mepos - d->m_SubclassClickOffset);
if (m >= 0)
{
const QRect r = rect().adjusted(-m, -m, m, m);
if (!r.contains(mouseEvent->pos()))
{
newPosition = d->m_SubclassPosition;
}
}
// Only the lower/left slider is down
if (this->isMinimumSliderDown() && !this->isMaximumSliderDown())
{
double newMinPos = qMin(newPosition,d->m_MaximumPosition);
this->setPositions(newMinPos, d->m_MaximumPosition +
(d->m_SymmetricMoves ? d->m_MinimumPosition - newMinPos : 0));
}
// Only the upper/right slider is down
else if (this->isMaximumSliderDown() && !this->isMinimumSliderDown())
{
double newMaxPos = qMax(d->m_MinimumPosition, newPosition);
this->setPositions(d->m_MinimumPosition -
(d->m_SymmetricMoves ? newMaxPos - d->m_MaximumPosition: 0),
newMaxPos);
}
// Both handles are down (the user clicked in between the handles)
else if (this->isMinimumSliderDown() && this->isMaximumSliderDown())
{
this->setPositions(newPosition - d->m_SubclassWidth,
newPosition + d->m_SubclassWidth );
}
mouseEvent->accept();
}
// --------------------------------------------------------------------------
// Standard Qt UI mouseEvents
void RangeSlider::mouseReleaseEvent(QMouseEvent* mouseEvent)
{
Q_D(RangeSlider);
this->QSlider::mouseReleaseEvent(mouseEvent);
setSliderDown(false);
d->m_SelectedHandles = RangeSliderPrivate::NoHandle;
this->update();
}
// --------------------------------------------------------------------------
bool RangeSlider::isMinimumSliderDown()const
{
Q_D(const RangeSlider);
return d->m_SelectedHandles & RangeSliderPrivate::MinimumHandle;
}
// --------------------------------------------------------------------------
bool RangeSlider::isMaximumSliderDown()const
{
Q_D(const RangeSlider);
return d->m_SelectedHandles & RangeSliderPrivate::MaximumHandle;
}
// --------------------------------------------------------------------------
void RangeSlider::initMinimumSliderStyleOption(QStyleOptionSlider* option) const
{
this->initStyleOption(option);
}
// --------------------------------------------------------------------------
void RangeSlider::initMaximumSliderStyleOption(QStyleOptionSlider* option) const
{
this->initStyleOption(option);
}
// --------------------------------------------------------------------------
QString RangeSlider::handleToolTip()const
{
Q_D(const RangeSlider);
return d->m_HandleToolTip;
}
// --------------------------------------------------------------------------
void RangeSlider::setHandleToolTip(const QString& _toolTip)
{
Q_D(RangeSlider);
d->m_HandleToolTip = _toolTip;
}
// --------------------------------------------------------------------------
bool RangeSlider::event(QEvent* _event)
{
Q_D(RangeSlider);
switch(_event->type())
{
case QEvent::ToolTip:
{
QHelpEvent* helpEvent = static_cast<QHelpEvent*>(_event);
QStyleOptionSlider opt;
// Test the MinimumHandle
opt.sliderPosition = d->m_MinimumPosition;
opt.sliderValue = d->m_MinimumValue;
this->initStyleOption(&opt);
QStyle::SubControl hoveredControl =
this->style()->hitTestComplexControl(
QStyle::CC_Slider, &opt, helpEvent->pos(), this);
if (!d->m_HandleToolTip.isEmpty() &&
hoveredControl == QStyle::SC_SliderHandle)
{
QToolTip::showText(helpEvent->globalPos(), d->m_HandleToolTip.arg(this->minimumValue()));
_event->accept();
return true;
}
// Test the MaximumHandle
opt.sliderPosition = d->m_MaximumPosition;
opt.sliderValue = d->m_MaximumValue;
this->initStyleOption(&opt);
hoveredControl = this->style()->hitTestComplexControl(
QStyle::CC_Slider, &opt, helpEvent->pos(), this);
if (!d->m_HandleToolTip.isEmpty() &&
hoveredControl == QStyle::SC_SliderHandle)
{
QToolTip::showText(helpEvent->globalPos(), d->m_HandleToolTip.arg(this->maximumValue()));
_event->accept();
return true;
}
}
default:
break;
}
return this->Superclass::event(_event);
}
| [
"noreply@github.com"
] | hbtalha.noreply@github.com |
5b2191d22e7ff9d4dd1fbddc170ef623bb6ca102 | e3ceca6a34bf3426b90b3952782d4fd94c54d08a | /b問題/b_chocolate.cpp | c19b4db14f1c3a0cbc38383eeb4d9561086c74c3 | [] | no_license | THEosusi/atcoder | ede5bffb44d59e266c6c4763a64cddeed8d8101f | 0e9a17a82562e469198a6cc81922db5ac13efa6d | refs/heads/master | 2023-06-21T06:45:28.128553 | 2021-07-27T09:02:55 | 2021-07-27T09:02:55 | 336,729,745 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 518 | cpp | #include <bits/stdc++.h>
using namespace std;
int main() {
int N,D,X;
cin >> N >> D >>X;
vector<int> vec(N);
for(int i=0;i<N;i++){
cin >>vec.at(i);
}
int count=0;
for(int j=0;j<N;j++){
if(vec.at(j)==1){
if(N==1){
count++;
continue;
}
count += D;
continue;
}
count += D/vec.at(j);
count ++;
if(D%vec.at(j)==0){
count--;
}
}
cout << count+X << endl;
} | [
"bp20129shibaura-it.ac.j@shibaura-it.ac.jp"
] | bp20129shibaura-it.ac.j@shibaura-it.ac.jp |
eee188f0c7bcfe9c81187469b2ed11b178ab890c | 57126f65a47d4b8ccd8932425178c6717639c989 | /external/glbinding-2.0.0/source/glbinding/include/glbinding/gl31/enum.h | ffb1de207180ecc648d1c87b621d998d12dd9fda | [
"MIT"
] | permissive | 3d-scan/rgbd-recon | 4c435e06ecee867fd7bd365363eff92ef7513a39 | c4a5614eaa55dd93c74da70d6fb3d813d74f2903 | refs/heads/master | 2020-03-22T16:09:56.569088 | 2018-04-28T10:58:51 | 2018-04-28T10:58:51 | 140,307,666 | 1 | 0 | MIT | 2018-07-09T15:47:26 | 2018-07-09T15:47:26 | null | UTF-8 | C++ | false | false | 49,577 | h | #pragma once
#include <glbinding/nogl.h>
#include <glbinding/gl/enum.h>
namespace gl31
{
// import enums to namespace
// AccumOp
using gl::GL_ACCUM;
using gl::GL_LOAD;
using gl::GL_RETURN;
using gl::GL_MULT;
using gl::GL_ADD;
// AlphaFunction
using gl::GL_NEVER;
using gl::GL_LESS;
using gl::GL_EQUAL;
using gl::GL_LEQUAL;
using gl::GL_GREATER;
using gl::GL_NOTEQUAL;
using gl::GL_GEQUAL;
using gl::GL_ALWAYS;
// BlendEquationModeEXT
using gl::GL_LOGIC_OP;
// BlendingFactorDest
using gl::GL_ZERO;
using gl::GL_SRC_COLOR;
using gl::GL_ONE_MINUS_SRC_COLOR;
using gl::GL_SRC_ALPHA;
using gl::GL_ONE_MINUS_SRC_ALPHA;
using gl::GL_DST_ALPHA;
using gl::GL_ONE_MINUS_DST_ALPHA;
using gl::GL_ONE;
// BlendingFactorSrc
// using gl::GL_ZERO; // reuse BlendingFactorDest
// using gl::GL_SRC_ALPHA; // reuse BlendingFactorDest
// using gl::GL_ONE_MINUS_SRC_ALPHA; // reuse BlendingFactorDest
// using gl::GL_DST_ALPHA; // reuse BlendingFactorDest
// using gl::GL_ONE_MINUS_DST_ALPHA; // reuse BlendingFactorDest
using gl::GL_DST_COLOR;
using gl::GL_ONE_MINUS_DST_COLOR;
using gl::GL_SRC_ALPHA_SATURATE;
// using gl::GL_ONE; // reuse BlendingFactorDest
// ClipPlaneName
using gl::GL_CLIP_DISTANCE0;
using gl::GL_CLIP_PLANE0;
using gl::GL_CLIP_DISTANCE1;
using gl::GL_CLIP_PLANE1;
using gl::GL_CLIP_DISTANCE2;
using gl::GL_CLIP_PLANE2;
using gl::GL_CLIP_DISTANCE3;
using gl::GL_CLIP_PLANE3;
using gl::GL_CLIP_DISTANCE4;
using gl::GL_CLIP_PLANE4;
using gl::GL_CLIP_DISTANCE5;
using gl::GL_CLIP_PLANE5;
using gl::GL_CLIP_DISTANCE6;
using gl::GL_CLIP_DISTANCE7;
// ColorMaterialFace
using gl::GL_FRONT;
using gl::GL_BACK;
using gl::GL_FRONT_AND_BACK;
// ColorMaterialParameter
using gl::GL_AMBIENT;
using gl::GL_DIFFUSE;
using gl::GL_SPECULAR;
using gl::GL_EMISSION;
using gl::GL_AMBIENT_AND_DIFFUSE;
// ColorPointerType
using gl::GL_BYTE;
using gl::GL_UNSIGNED_BYTE;
using gl::GL_SHORT;
using gl::GL_UNSIGNED_SHORT;
using gl::GL_INT;
using gl::GL_UNSIGNED_INT;
using gl::GL_FLOAT;
using gl::GL_DOUBLE;
// CullFaceMode
// using gl::GL_FRONT; // reuse ColorMaterialFace
// using gl::GL_BACK; // reuse ColorMaterialFace
// using gl::GL_FRONT_AND_BACK; // reuse ColorMaterialFace
// DepthFunction
// using gl::GL_NEVER; // reuse AlphaFunction
// using gl::GL_LESS; // reuse AlphaFunction
// using gl::GL_EQUAL; // reuse AlphaFunction
// using gl::GL_LEQUAL; // reuse AlphaFunction
// using gl::GL_GREATER; // reuse AlphaFunction
// using gl::GL_NOTEQUAL; // reuse AlphaFunction
// using gl::GL_GEQUAL; // reuse AlphaFunction
// using gl::GL_ALWAYS; // reuse AlphaFunction
// DrawBufferMode
using gl::GL_NONE;
using gl::GL_FRONT_LEFT;
using gl::GL_FRONT_RIGHT;
using gl::GL_BACK_LEFT;
using gl::GL_BACK_RIGHT;
// using gl::GL_FRONT; // reuse ColorMaterialFace
// using gl::GL_BACK; // reuse ColorMaterialFace
using gl::GL_LEFT;
using gl::GL_RIGHT;
// using gl::GL_FRONT_AND_BACK; // reuse ColorMaterialFace
using gl::GL_AUX0;
using gl::GL_AUX1;
using gl::GL_AUX2;
using gl::GL_AUX3;
// EnableCap
using gl::GL_POINT_SMOOTH;
using gl::GL_LINE_SMOOTH;
using gl::GL_LINE_STIPPLE;
using gl::GL_POLYGON_SMOOTH;
using gl::GL_POLYGON_STIPPLE;
using gl::GL_CULL_FACE;
using gl::GL_LIGHTING;
using gl::GL_COLOR_MATERIAL;
using gl::GL_FOG;
using gl::GL_DEPTH_TEST;
using gl::GL_STENCIL_TEST;
using gl::GL_NORMALIZE;
using gl::GL_ALPHA_TEST;
using gl::GL_DITHER;
using gl::GL_BLEND;
using gl::GL_INDEX_LOGIC_OP;
using gl::GL_COLOR_LOGIC_OP;
using gl::GL_SCISSOR_TEST;
using gl::GL_TEXTURE_GEN_S;
using gl::GL_TEXTURE_GEN_T;
using gl::GL_TEXTURE_GEN_R;
using gl::GL_TEXTURE_GEN_Q;
using gl::GL_AUTO_NORMAL;
using gl::GL_MAP1_COLOR_4;
using gl::GL_MAP1_INDEX;
using gl::GL_MAP1_NORMAL;
using gl::GL_MAP1_TEXTURE_COORD_1;
using gl::GL_MAP1_TEXTURE_COORD_2;
using gl::GL_MAP1_TEXTURE_COORD_3;
using gl::GL_MAP1_TEXTURE_COORD_4;
using gl::GL_MAP1_VERTEX_3;
using gl::GL_MAP1_VERTEX_4;
using gl::GL_MAP2_COLOR_4;
using gl::GL_MAP2_INDEX;
using gl::GL_MAP2_NORMAL;
using gl::GL_MAP2_TEXTURE_COORD_1;
using gl::GL_MAP2_TEXTURE_COORD_2;
using gl::GL_MAP2_TEXTURE_COORD_3;
using gl::GL_MAP2_TEXTURE_COORD_4;
using gl::GL_MAP2_VERTEX_3;
using gl::GL_MAP2_VERTEX_4;
using gl::GL_TEXTURE_1D;
using gl::GL_TEXTURE_2D;
using gl::GL_POLYGON_OFFSET_POINT;
using gl::GL_POLYGON_OFFSET_LINE;
// using gl::GL_CLIP_PLANE0; // reuse ClipPlaneName
// using gl::GL_CLIP_PLANE1; // reuse ClipPlaneName
// using gl::GL_CLIP_PLANE2; // reuse ClipPlaneName
// using gl::GL_CLIP_PLANE3; // reuse ClipPlaneName
// using gl::GL_CLIP_PLANE4; // reuse ClipPlaneName
// using gl::GL_CLIP_PLANE5; // reuse ClipPlaneName
using gl::GL_LIGHT0;
using gl::GL_LIGHT1;
using gl::GL_LIGHT2;
using gl::GL_LIGHT3;
using gl::GL_LIGHT4;
using gl::GL_LIGHT5;
using gl::GL_LIGHT6;
using gl::GL_LIGHT7;
using gl::GL_POLYGON_OFFSET_FILL;
using gl::GL_VERTEX_ARRAY;
using gl::GL_NORMAL_ARRAY;
using gl::GL_COLOR_ARRAY;
using gl::GL_INDEX_ARRAY;
using gl::GL_TEXTURE_COORD_ARRAY;
using gl::GL_EDGE_FLAG_ARRAY;
// ErrorCode
using gl::GL_NO_ERROR;
using gl::GL_INVALID_ENUM;
using gl::GL_INVALID_VALUE;
using gl::GL_INVALID_OPERATION;
using gl::GL_STACK_OVERFLOW;
using gl::GL_STACK_UNDERFLOW;
using gl::GL_OUT_OF_MEMORY;
using gl::GL_INVALID_FRAMEBUFFER_OPERATION;
// FeedBackToken
using gl::GL_PASS_THROUGH_TOKEN;
using gl::GL_POINT_TOKEN;
using gl::GL_LINE_TOKEN;
using gl::GL_POLYGON_TOKEN;
using gl::GL_BITMAP_TOKEN;
using gl::GL_DRAW_PIXEL_TOKEN;
using gl::GL_COPY_PIXEL_TOKEN;
using gl::GL_LINE_RESET_TOKEN;
// FeedbackType
using gl::GL_2D;
using gl::GL_3D;
using gl::GL_3D_COLOR;
using gl::GL_3D_COLOR_TEXTURE;
using gl::GL_4D_COLOR_TEXTURE;
// FogCoordinatePointerType
// using gl::GL_FLOAT; // reuse ColorPointerType
// using gl::GL_DOUBLE; // reuse ColorPointerType
// FogMode
using gl::GL_EXP;
using gl::GL_EXP2;
using gl::GL_LINEAR;
// FogParameter
using gl::GL_FOG_INDEX;
using gl::GL_FOG_DENSITY;
using gl::GL_FOG_START;
using gl::GL_FOG_END;
using gl::GL_FOG_MODE;
using gl::GL_FOG_COLOR;
// FogPointerTypeEXT
// using gl::GL_FLOAT; // reuse ColorPointerType
// using gl::GL_DOUBLE; // reuse ColorPointerType
// FogPointerTypeIBM
// using gl::GL_FLOAT; // reuse ColorPointerType
// using gl::GL_DOUBLE; // reuse ColorPointerType
// FrontFaceDirection
using gl::GL_CW;
using gl::GL_CCW;
// GetMapQuery
using gl::GL_COEFF;
using gl::GL_ORDER;
using gl::GL_DOMAIN;
// GetPName
using gl::GL_CURRENT_COLOR;
using gl::GL_CURRENT_INDEX;
using gl::GL_CURRENT_NORMAL;
using gl::GL_CURRENT_TEXTURE_COORDS;
using gl::GL_CURRENT_RASTER_COLOR;
using gl::GL_CURRENT_RASTER_INDEX;
using gl::GL_CURRENT_RASTER_TEXTURE_COORDS;
using gl::GL_CURRENT_RASTER_POSITION;
using gl::GL_CURRENT_RASTER_POSITION_VALID;
using gl::GL_CURRENT_RASTER_DISTANCE;
// using gl::GL_POINT_SMOOTH; // reuse EnableCap
using gl::GL_POINT_SIZE;
using gl::GL_POINT_SIZE_RANGE;
using gl::GL_SMOOTH_POINT_SIZE_RANGE;
using gl::GL_POINT_SIZE_GRANULARITY;
using gl::GL_SMOOTH_POINT_SIZE_GRANULARITY;
// using gl::GL_LINE_SMOOTH; // reuse EnableCap
using gl::GL_LINE_WIDTH;
using gl::GL_LINE_WIDTH_RANGE;
using gl::GL_SMOOTH_LINE_WIDTH_RANGE;
using gl::GL_LINE_WIDTH_GRANULARITY;
using gl::GL_SMOOTH_LINE_WIDTH_GRANULARITY;
// using gl::GL_LINE_STIPPLE; // reuse EnableCap
using gl::GL_LINE_STIPPLE_PATTERN;
using gl::GL_LINE_STIPPLE_REPEAT;
using gl::GL_LIST_MODE;
using gl::GL_MAX_LIST_NESTING;
using gl::GL_LIST_BASE;
using gl::GL_LIST_INDEX;
using gl::GL_POLYGON_MODE;
// using gl::GL_POLYGON_SMOOTH; // reuse EnableCap
// using gl::GL_POLYGON_STIPPLE; // reuse EnableCap
using gl::GL_EDGE_FLAG;
// using gl::GL_CULL_FACE; // reuse EnableCap
using gl::GL_CULL_FACE_MODE;
using gl::GL_FRONT_FACE;
// using gl::GL_LIGHTING; // reuse EnableCap
using gl::GL_LIGHT_MODEL_LOCAL_VIEWER;
using gl::GL_LIGHT_MODEL_TWO_SIDE;
using gl::GL_LIGHT_MODEL_AMBIENT;
using gl::GL_SHADE_MODEL;
using gl::GL_COLOR_MATERIAL_FACE;
using gl::GL_COLOR_MATERIAL_PARAMETER;
// using gl::GL_COLOR_MATERIAL; // reuse EnableCap
// using gl::GL_FOG; // reuse EnableCap
// using gl::GL_FOG_INDEX; // reuse FogParameter
// using gl::GL_FOG_DENSITY; // reuse FogParameter
// using gl::GL_FOG_START; // reuse FogParameter
// using gl::GL_FOG_END; // reuse FogParameter
// using gl::GL_FOG_MODE; // reuse FogParameter
// using gl::GL_FOG_COLOR; // reuse FogParameter
using gl::GL_DEPTH_RANGE;
// using gl::GL_DEPTH_TEST; // reuse EnableCap
using gl::GL_DEPTH_WRITEMASK;
using gl::GL_DEPTH_CLEAR_VALUE;
using gl::GL_DEPTH_FUNC;
using gl::GL_ACCUM_CLEAR_VALUE;
// using gl::GL_STENCIL_TEST; // reuse EnableCap
using gl::GL_STENCIL_CLEAR_VALUE;
using gl::GL_STENCIL_FUNC;
using gl::GL_STENCIL_VALUE_MASK;
using gl::GL_STENCIL_FAIL;
using gl::GL_STENCIL_PASS_DEPTH_FAIL;
using gl::GL_STENCIL_PASS_DEPTH_PASS;
using gl::GL_STENCIL_REF;
using gl::GL_STENCIL_WRITEMASK;
using gl::GL_MATRIX_MODE;
// using gl::GL_NORMALIZE; // reuse EnableCap
using gl::GL_VIEWPORT;
using gl::GL_MODELVIEW_STACK_DEPTH;
using gl::GL_PROJECTION_STACK_DEPTH;
using gl::GL_TEXTURE_STACK_DEPTH;
using gl::GL_MODELVIEW_MATRIX;
using gl::GL_PROJECTION_MATRIX;
using gl::GL_TEXTURE_MATRIX;
using gl::GL_ATTRIB_STACK_DEPTH;
using gl::GL_CLIENT_ATTRIB_STACK_DEPTH;
// using gl::GL_ALPHA_TEST; // reuse EnableCap
using gl::GL_ALPHA_TEST_FUNC;
using gl::GL_ALPHA_TEST_REF;
// using gl::GL_DITHER; // reuse EnableCap
using gl::GL_BLEND_DST;
using gl::GL_BLEND_SRC;
// using gl::GL_BLEND; // reuse EnableCap
using gl::GL_LOGIC_OP_MODE;
// using gl::GL_INDEX_LOGIC_OP; // reuse EnableCap
// using gl::GL_LOGIC_OP; // reuse BlendEquationModeEXT
// using gl::GL_COLOR_LOGIC_OP; // reuse EnableCap
using gl::GL_AUX_BUFFERS;
using gl::GL_DRAW_BUFFER;
using gl::GL_READ_BUFFER;
using gl::GL_SCISSOR_BOX;
// using gl::GL_SCISSOR_TEST; // reuse EnableCap
using gl::GL_INDEX_CLEAR_VALUE;
using gl::GL_INDEX_WRITEMASK;
using gl::GL_COLOR_CLEAR_VALUE;
using gl::GL_COLOR_WRITEMASK;
using gl::GL_INDEX_MODE;
using gl::GL_RGBA_MODE;
using gl::GL_DOUBLEBUFFER;
using gl::GL_STEREO;
using gl::GL_RENDER_MODE;
using gl::GL_PERSPECTIVE_CORRECTION_HINT;
using gl::GL_POINT_SMOOTH_HINT;
using gl::GL_LINE_SMOOTH_HINT;
using gl::GL_POLYGON_SMOOTH_HINT;
using gl::GL_FOG_HINT;
// using gl::GL_TEXTURE_GEN_S; // reuse EnableCap
// using gl::GL_TEXTURE_GEN_T; // reuse EnableCap
// using gl::GL_TEXTURE_GEN_R; // reuse EnableCap
// using gl::GL_TEXTURE_GEN_Q; // reuse EnableCap
using gl::GL_PIXEL_MAP_I_TO_I_SIZE;
using gl::GL_PIXEL_MAP_S_TO_S_SIZE;
using gl::GL_PIXEL_MAP_I_TO_R_SIZE;
using gl::GL_PIXEL_MAP_I_TO_G_SIZE;
using gl::GL_PIXEL_MAP_I_TO_B_SIZE;
using gl::GL_PIXEL_MAP_I_TO_A_SIZE;
using gl::GL_PIXEL_MAP_R_TO_R_SIZE;
using gl::GL_PIXEL_MAP_G_TO_G_SIZE;
using gl::GL_PIXEL_MAP_B_TO_B_SIZE;
using gl::GL_PIXEL_MAP_A_TO_A_SIZE;
using gl::GL_UNPACK_SWAP_BYTES;
using gl::GL_UNPACK_LSB_FIRST;
using gl::GL_UNPACK_ROW_LENGTH;
using gl::GL_UNPACK_SKIP_ROWS;
using gl::GL_UNPACK_SKIP_PIXELS;
using gl::GL_UNPACK_ALIGNMENT;
using gl::GL_PACK_SWAP_BYTES;
using gl::GL_PACK_LSB_FIRST;
using gl::GL_PACK_ROW_LENGTH;
using gl::GL_PACK_SKIP_ROWS;
using gl::GL_PACK_SKIP_PIXELS;
using gl::GL_PACK_ALIGNMENT;
using gl::GL_MAP_COLOR;
using gl::GL_MAP_STENCIL;
using gl::GL_INDEX_SHIFT;
using gl::GL_INDEX_OFFSET;
using gl::GL_RED_SCALE;
using gl::GL_RED_BIAS;
using gl::GL_ZOOM_X;
using gl::GL_ZOOM_Y;
using gl::GL_GREEN_SCALE;
using gl::GL_GREEN_BIAS;
using gl::GL_BLUE_SCALE;
using gl::GL_BLUE_BIAS;
using gl::GL_ALPHA_SCALE;
using gl::GL_ALPHA_BIAS;
using gl::GL_DEPTH_SCALE;
using gl::GL_DEPTH_BIAS;
using gl::GL_MAX_EVAL_ORDER;
using gl::GL_MAX_LIGHTS;
using gl::GL_MAX_CLIP_DISTANCES;
using gl::GL_MAX_CLIP_PLANES;
using gl::GL_MAX_TEXTURE_SIZE;
using gl::GL_MAX_PIXEL_MAP_TABLE;
using gl::GL_MAX_ATTRIB_STACK_DEPTH;
using gl::GL_MAX_MODELVIEW_STACK_DEPTH;
using gl::GL_MAX_NAME_STACK_DEPTH;
using gl::GL_MAX_PROJECTION_STACK_DEPTH;
using gl::GL_MAX_TEXTURE_STACK_DEPTH;
using gl::GL_MAX_VIEWPORT_DIMS;
using gl::GL_MAX_CLIENT_ATTRIB_STACK_DEPTH;
using gl::GL_SUBPIXEL_BITS;
using gl::GL_INDEX_BITS;
using gl::GL_RED_BITS;
using gl::GL_GREEN_BITS;
using gl::GL_BLUE_BITS;
using gl::GL_ALPHA_BITS;
using gl::GL_DEPTH_BITS;
using gl::GL_STENCIL_BITS;
using gl::GL_ACCUM_RED_BITS;
using gl::GL_ACCUM_GREEN_BITS;
using gl::GL_ACCUM_BLUE_BITS;
using gl::GL_ACCUM_ALPHA_BITS;
using gl::GL_NAME_STACK_DEPTH;
// using gl::GL_AUTO_NORMAL; // reuse EnableCap
// using gl::GL_MAP1_COLOR_4; // reuse EnableCap
// using gl::GL_MAP1_INDEX; // reuse EnableCap
// using gl::GL_MAP1_NORMAL; // reuse EnableCap
// using gl::GL_MAP1_TEXTURE_COORD_1; // reuse EnableCap
// using gl::GL_MAP1_TEXTURE_COORD_2; // reuse EnableCap
// using gl::GL_MAP1_TEXTURE_COORD_3; // reuse EnableCap
// using gl::GL_MAP1_TEXTURE_COORD_4; // reuse EnableCap
// using gl::GL_MAP1_VERTEX_3; // reuse EnableCap
// using gl::GL_MAP1_VERTEX_4; // reuse EnableCap
// using gl::GL_MAP2_COLOR_4; // reuse EnableCap
// using gl::GL_MAP2_INDEX; // reuse EnableCap
// using gl::GL_MAP2_NORMAL; // reuse EnableCap
// using gl::GL_MAP2_TEXTURE_COORD_1; // reuse EnableCap
// using gl::GL_MAP2_TEXTURE_COORD_2; // reuse EnableCap
// using gl::GL_MAP2_TEXTURE_COORD_3; // reuse EnableCap
// using gl::GL_MAP2_TEXTURE_COORD_4; // reuse EnableCap
// using gl::GL_MAP2_VERTEX_3; // reuse EnableCap
// using gl::GL_MAP2_VERTEX_4; // reuse EnableCap
using gl::GL_MAP1_GRID_DOMAIN;
using gl::GL_MAP1_GRID_SEGMENTS;
using gl::GL_MAP2_GRID_DOMAIN;
using gl::GL_MAP2_GRID_SEGMENTS;
// using gl::GL_TEXTURE_1D; // reuse EnableCap
// using gl::GL_TEXTURE_2D; // reuse EnableCap
using gl::GL_FEEDBACK_BUFFER_SIZE;
using gl::GL_FEEDBACK_BUFFER_TYPE;
using gl::GL_SELECTION_BUFFER_SIZE;
using gl::GL_POLYGON_OFFSET_UNITS;
// using gl::GL_POLYGON_OFFSET_POINT; // reuse EnableCap
// using gl::GL_POLYGON_OFFSET_LINE; // reuse EnableCap
// using gl::GL_CLIP_PLANE0; // reuse ClipPlaneName
// using gl::GL_CLIP_PLANE1; // reuse ClipPlaneName
// using gl::GL_CLIP_PLANE2; // reuse ClipPlaneName
// using gl::GL_CLIP_PLANE3; // reuse ClipPlaneName
// using gl::GL_CLIP_PLANE4; // reuse ClipPlaneName
// using gl::GL_CLIP_PLANE5; // reuse ClipPlaneName
// using gl::GL_LIGHT0; // reuse EnableCap
// using gl::GL_LIGHT1; // reuse EnableCap
// using gl::GL_LIGHT2; // reuse EnableCap
// using gl::GL_LIGHT3; // reuse EnableCap
// using gl::GL_LIGHT4; // reuse EnableCap
// using gl::GL_LIGHT5; // reuse EnableCap
// using gl::GL_LIGHT6; // reuse EnableCap
// using gl::GL_LIGHT7; // reuse EnableCap
// using gl::GL_POLYGON_OFFSET_FILL; // reuse EnableCap
using gl::GL_POLYGON_OFFSET_FACTOR;
using gl::GL_TEXTURE_BINDING_1D;
using gl::GL_TEXTURE_BINDING_2D;
using gl::GL_TEXTURE_BINDING_3D;
// using gl::GL_VERTEX_ARRAY; // reuse EnableCap
// using gl::GL_NORMAL_ARRAY; // reuse EnableCap
// using gl::GL_COLOR_ARRAY; // reuse EnableCap
// using gl::GL_INDEX_ARRAY; // reuse EnableCap
// using gl::GL_TEXTURE_COORD_ARRAY; // reuse EnableCap
// using gl::GL_EDGE_FLAG_ARRAY; // reuse EnableCap
using gl::GL_VERTEX_ARRAY_SIZE;
using gl::GL_VERTEX_ARRAY_TYPE;
using gl::GL_VERTEX_ARRAY_STRIDE;
using gl::GL_NORMAL_ARRAY_TYPE;
using gl::GL_NORMAL_ARRAY_STRIDE;
using gl::GL_COLOR_ARRAY_SIZE;
using gl::GL_COLOR_ARRAY_TYPE;
using gl::GL_COLOR_ARRAY_STRIDE;
using gl::GL_INDEX_ARRAY_TYPE;
using gl::GL_INDEX_ARRAY_STRIDE;
using gl::GL_TEXTURE_COORD_ARRAY_SIZE;
using gl::GL_TEXTURE_COORD_ARRAY_TYPE;
using gl::GL_TEXTURE_COORD_ARRAY_STRIDE;
using gl::GL_EDGE_FLAG_ARRAY_STRIDE;
using gl::GL_LIGHT_MODEL_COLOR_CONTROL;
using gl::GL_ALIASED_POINT_SIZE_RANGE;
using gl::GL_ALIASED_LINE_WIDTH_RANGE;
// GetPixelMap
using gl::GL_PIXEL_MAP_I_TO_I;
using gl::GL_PIXEL_MAP_S_TO_S;
using gl::GL_PIXEL_MAP_I_TO_R;
using gl::GL_PIXEL_MAP_I_TO_G;
using gl::GL_PIXEL_MAP_I_TO_B;
using gl::GL_PIXEL_MAP_I_TO_A;
using gl::GL_PIXEL_MAP_R_TO_R;
using gl::GL_PIXEL_MAP_G_TO_G;
using gl::GL_PIXEL_MAP_B_TO_B;
using gl::GL_PIXEL_MAP_A_TO_A;
// GetPointervPName
using gl::GL_FEEDBACK_BUFFER_POINTER;
using gl::GL_SELECTION_BUFFER_POINTER;
using gl::GL_VERTEX_ARRAY_POINTER;
using gl::GL_NORMAL_ARRAY_POINTER;
using gl::GL_COLOR_ARRAY_POINTER;
using gl::GL_INDEX_ARRAY_POINTER;
using gl::GL_TEXTURE_COORD_ARRAY_POINTER;
using gl::GL_EDGE_FLAG_ARRAY_POINTER;
// GetTextureParameter
using gl::GL_TEXTURE_WIDTH;
using gl::GL_TEXTURE_HEIGHT;
using gl::GL_TEXTURE_COMPONENTS;
using gl::GL_TEXTURE_INTERNAL_FORMAT;
using gl::GL_TEXTURE_BORDER_COLOR;
using gl::GL_TEXTURE_BORDER;
using gl::GL_TEXTURE_MAG_FILTER;
using gl::GL_TEXTURE_MIN_FILTER;
using gl::GL_TEXTURE_WRAP_S;
using gl::GL_TEXTURE_WRAP_T;
using gl::GL_TEXTURE_RED_SIZE;
using gl::GL_TEXTURE_GREEN_SIZE;
using gl::GL_TEXTURE_BLUE_SIZE;
using gl::GL_TEXTURE_ALPHA_SIZE;
using gl::GL_TEXTURE_LUMINANCE_SIZE;
using gl::GL_TEXTURE_INTENSITY_SIZE;
using gl::GL_TEXTURE_PRIORITY;
using gl::GL_TEXTURE_RESIDENT;
// HintMode
using gl::GL_DONT_CARE;
using gl::GL_FASTEST;
using gl::GL_NICEST;
// HintTarget
// using gl::GL_PERSPECTIVE_CORRECTION_HINT; // reuse GetPName
// using gl::GL_POINT_SMOOTH_HINT; // reuse GetPName
// using gl::GL_LINE_SMOOTH_HINT; // reuse GetPName
// using gl::GL_POLYGON_SMOOTH_HINT; // reuse GetPName
// using gl::GL_FOG_HINT; // reuse GetPName
using gl::GL_GENERATE_MIPMAP_HINT;
using gl::GL_TEXTURE_COMPRESSION_HINT;
using gl::GL_FRAGMENT_SHADER_DERIVATIVE_HINT;
// IndexPointerType
// using gl::GL_SHORT; // reuse ColorPointerType
// using gl::GL_INT; // reuse ColorPointerType
// using gl::GL_FLOAT; // reuse ColorPointerType
// using gl::GL_DOUBLE; // reuse ColorPointerType
// InterleavedArrayFormat
using gl::GL_V2F;
using gl::GL_V3F;
using gl::GL_C4UB_V2F;
using gl::GL_C4UB_V3F;
using gl::GL_C3F_V3F;
using gl::GL_N3F_V3F;
using gl::GL_C4F_N3F_V3F;
using gl::GL_T2F_V3F;
using gl::GL_T4F_V4F;
using gl::GL_T2F_C4UB_V3F;
using gl::GL_T2F_C3F_V3F;
using gl::GL_T2F_N3F_V3F;
using gl::GL_T2F_C4F_N3F_V3F;
using gl::GL_T4F_C4F_N3F_V4F;
// InternalFormat
using gl::GL_R3_G3_B2;
using gl::GL_ALPHA4;
using gl::GL_ALPHA8;
using gl::GL_ALPHA12;
using gl::GL_ALPHA16;
using gl::GL_LUMINANCE4;
using gl::GL_LUMINANCE8;
using gl::GL_LUMINANCE12;
using gl::GL_LUMINANCE16;
using gl::GL_LUMINANCE4_ALPHA4;
using gl::GL_LUMINANCE6_ALPHA2;
using gl::GL_LUMINANCE8_ALPHA8;
using gl::GL_LUMINANCE12_ALPHA4;
using gl::GL_LUMINANCE12_ALPHA12;
using gl::GL_LUMINANCE16_ALPHA16;
using gl::GL_INTENSITY;
using gl::GL_INTENSITY4;
using gl::GL_INTENSITY8;
using gl::GL_INTENSITY12;
using gl::GL_INTENSITY16;
using gl::GL_RGB4;
using gl::GL_RGB5;
using gl::GL_RGB8;
using gl::GL_RGB10;
using gl::GL_RGB12;
using gl::GL_RGB16;
using gl::GL_RGBA2;
using gl::GL_RGBA4;
using gl::GL_RGB5_A1;
using gl::GL_RGBA8;
using gl::GL_RGB10_A2;
using gl::GL_RGBA12;
using gl::GL_RGBA16;
// LightEnvModeSGIX
// using gl::GL_ADD; // reuse AccumOp
using gl::GL_REPLACE;
using gl::GL_MODULATE;
// LightModelColorControl
using gl::GL_SINGLE_COLOR;
using gl::GL_SEPARATE_SPECULAR_COLOR;
// LightModelParameter
// using gl::GL_LIGHT_MODEL_LOCAL_VIEWER; // reuse GetPName
// using gl::GL_LIGHT_MODEL_TWO_SIDE; // reuse GetPName
// using gl::GL_LIGHT_MODEL_AMBIENT; // reuse GetPName
// using gl::GL_LIGHT_MODEL_COLOR_CONTROL; // reuse GetPName
// LightName
// using gl::GL_LIGHT0; // reuse EnableCap
// using gl::GL_LIGHT1; // reuse EnableCap
// using gl::GL_LIGHT2; // reuse EnableCap
// using gl::GL_LIGHT3; // reuse EnableCap
// using gl::GL_LIGHT4; // reuse EnableCap
// using gl::GL_LIGHT5; // reuse EnableCap
// using gl::GL_LIGHT6; // reuse EnableCap
// using gl::GL_LIGHT7; // reuse EnableCap
// LightParameter
// using gl::GL_AMBIENT; // reuse ColorMaterialParameter
// using gl::GL_DIFFUSE; // reuse ColorMaterialParameter
// using gl::GL_SPECULAR; // reuse ColorMaterialParameter
using gl::GL_POSITION;
using gl::GL_SPOT_DIRECTION;
using gl::GL_SPOT_EXPONENT;
using gl::GL_SPOT_CUTOFF;
using gl::GL_CONSTANT_ATTENUATION;
using gl::GL_LINEAR_ATTENUATION;
using gl::GL_QUADRATIC_ATTENUATION;
// ListMode
using gl::GL_COMPILE;
using gl::GL_COMPILE_AND_EXECUTE;
// ListNameType
// using gl::GL_BYTE; // reuse ColorPointerType
// using gl::GL_UNSIGNED_BYTE; // reuse ColorPointerType
// using gl::GL_SHORT; // reuse ColorPointerType
// using gl::GL_UNSIGNED_SHORT; // reuse ColorPointerType
// using gl::GL_INT; // reuse ColorPointerType
// using gl::GL_UNSIGNED_INT; // reuse ColorPointerType
// using gl::GL_FLOAT; // reuse ColorPointerType
using gl::GL_2_BYTES;
using gl::GL_3_BYTES;
using gl::GL_4_BYTES;
// LogicOp
using gl::GL_CLEAR;
using gl::GL_AND;
using gl::GL_AND_REVERSE;
using gl::GL_COPY;
using gl::GL_AND_INVERTED;
using gl::GL_NOOP;
using gl::GL_XOR;
using gl::GL_OR;
using gl::GL_NOR;
using gl::GL_EQUIV;
using gl::GL_INVERT;
using gl::GL_OR_REVERSE;
using gl::GL_COPY_INVERTED;
using gl::GL_OR_INVERTED;
using gl::GL_NAND;
using gl::GL_SET;
// MapTarget
// using gl::GL_MAP1_COLOR_4; // reuse EnableCap
// using gl::GL_MAP1_INDEX; // reuse EnableCap
// using gl::GL_MAP1_NORMAL; // reuse EnableCap
// using gl::GL_MAP1_TEXTURE_COORD_1; // reuse EnableCap
// using gl::GL_MAP1_TEXTURE_COORD_2; // reuse EnableCap
// using gl::GL_MAP1_TEXTURE_COORD_3; // reuse EnableCap
// using gl::GL_MAP1_TEXTURE_COORD_4; // reuse EnableCap
// using gl::GL_MAP1_VERTEX_3; // reuse EnableCap
// using gl::GL_MAP1_VERTEX_4; // reuse EnableCap
// using gl::GL_MAP2_COLOR_4; // reuse EnableCap
// using gl::GL_MAP2_INDEX; // reuse EnableCap
// using gl::GL_MAP2_NORMAL; // reuse EnableCap
// using gl::GL_MAP2_TEXTURE_COORD_1; // reuse EnableCap
// using gl::GL_MAP2_TEXTURE_COORD_2; // reuse EnableCap
// using gl::GL_MAP2_TEXTURE_COORD_3; // reuse EnableCap
// using gl::GL_MAP2_TEXTURE_COORD_4; // reuse EnableCap
// using gl::GL_MAP2_VERTEX_3; // reuse EnableCap
// using gl::GL_MAP2_VERTEX_4; // reuse EnableCap
// MaterialFace
// using gl::GL_FRONT; // reuse ColorMaterialFace
// using gl::GL_BACK; // reuse ColorMaterialFace
// using gl::GL_FRONT_AND_BACK; // reuse ColorMaterialFace
// MaterialParameter
// using gl::GL_AMBIENT; // reuse ColorMaterialParameter
// using gl::GL_DIFFUSE; // reuse ColorMaterialParameter
// using gl::GL_SPECULAR; // reuse ColorMaterialParameter
// using gl::GL_EMISSION; // reuse ColorMaterialParameter
using gl::GL_SHININESS;
// using gl::GL_AMBIENT_AND_DIFFUSE; // reuse ColorMaterialParameter
using gl::GL_COLOR_INDEXES;
// MatrixMode
using gl::GL_MODELVIEW;
using gl::GL_PROJECTION;
using gl::GL_TEXTURE;
// MeshMode1
using gl::GL_POINT;
using gl::GL_LINE;
// MeshMode2
// using gl::GL_POINT; // reuse MeshMode1
// using gl::GL_LINE; // reuse MeshMode1
using gl::GL_FILL;
// NormalPointerType
// using gl::GL_BYTE; // reuse ColorPointerType
// using gl::GL_SHORT; // reuse ColorPointerType
// using gl::GL_INT; // reuse ColorPointerType
// using gl::GL_FLOAT; // reuse ColorPointerType
// using gl::GL_DOUBLE; // reuse ColorPointerType
// PixelCopyType
using gl::GL_COLOR;
using gl::GL_DEPTH;
using gl::GL_STENCIL;
// PixelFormat
// using gl::GL_UNSIGNED_SHORT; // reuse ColorPointerType
// using gl::GL_UNSIGNED_INT; // reuse ColorPointerType
using gl::GL_COLOR_INDEX;
using gl::GL_STENCIL_INDEX;
using gl::GL_DEPTH_COMPONENT;
using gl::GL_RED;
using gl::GL_GREEN;
using gl::GL_BLUE;
using gl::GL_ALPHA;
using gl::GL_RGB;
using gl::GL_RGBA;
using gl::GL_LUMINANCE;
using gl::GL_LUMINANCE_ALPHA;
// PixelMap
// using gl::GL_PIXEL_MAP_I_TO_I; // reuse GetPixelMap
// using gl::GL_PIXEL_MAP_S_TO_S; // reuse GetPixelMap
// using gl::GL_PIXEL_MAP_I_TO_R; // reuse GetPixelMap
// using gl::GL_PIXEL_MAP_I_TO_G; // reuse GetPixelMap
// using gl::GL_PIXEL_MAP_I_TO_B; // reuse GetPixelMap
// using gl::GL_PIXEL_MAP_I_TO_A; // reuse GetPixelMap
// using gl::GL_PIXEL_MAP_R_TO_R; // reuse GetPixelMap
// using gl::GL_PIXEL_MAP_G_TO_G; // reuse GetPixelMap
// using gl::GL_PIXEL_MAP_B_TO_B; // reuse GetPixelMap
// using gl::GL_PIXEL_MAP_A_TO_A; // reuse GetPixelMap
// PixelStoreParameter
// using gl::GL_UNPACK_SWAP_BYTES; // reuse GetPName
// using gl::GL_UNPACK_LSB_FIRST; // reuse GetPName
// using gl::GL_UNPACK_ROW_LENGTH; // reuse GetPName
// using gl::GL_UNPACK_SKIP_ROWS; // reuse GetPName
// using gl::GL_UNPACK_SKIP_PIXELS; // reuse GetPName
// using gl::GL_UNPACK_ALIGNMENT; // reuse GetPName
// using gl::GL_PACK_SWAP_BYTES; // reuse GetPName
// using gl::GL_PACK_LSB_FIRST; // reuse GetPName
// using gl::GL_PACK_ROW_LENGTH; // reuse GetPName
// using gl::GL_PACK_SKIP_ROWS; // reuse GetPName
// using gl::GL_PACK_SKIP_PIXELS; // reuse GetPName
// using gl::GL_PACK_ALIGNMENT; // reuse GetPName
using gl::GL_PACK_SKIP_IMAGES;
using gl::GL_PACK_IMAGE_HEIGHT;
using gl::GL_UNPACK_SKIP_IMAGES;
using gl::GL_UNPACK_IMAGE_HEIGHT;
// PixelTexGenMode
// using gl::GL_NONE; // reuse DrawBufferMode
// using gl::GL_RGB; // reuse PixelFormat
// using gl::GL_RGBA; // reuse PixelFormat
// using gl::GL_LUMINANCE; // reuse PixelFormat
// using gl::GL_LUMINANCE_ALPHA; // reuse PixelFormat
// PixelTransferParameter
// using gl::GL_MAP_COLOR; // reuse GetPName
// using gl::GL_MAP_STENCIL; // reuse GetPName
// using gl::GL_INDEX_SHIFT; // reuse GetPName
// using gl::GL_INDEX_OFFSET; // reuse GetPName
// using gl::GL_RED_SCALE; // reuse GetPName
// using gl::GL_RED_BIAS; // reuse GetPName
// using gl::GL_GREEN_SCALE; // reuse GetPName
// using gl::GL_GREEN_BIAS; // reuse GetPName
// using gl::GL_BLUE_SCALE; // reuse GetPName
// using gl::GL_BLUE_BIAS; // reuse GetPName
// using gl::GL_ALPHA_SCALE; // reuse GetPName
// using gl::GL_ALPHA_BIAS; // reuse GetPName
// using gl::GL_DEPTH_SCALE; // reuse GetPName
// using gl::GL_DEPTH_BIAS; // reuse GetPName
// PixelType
// using gl::GL_BYTE; // reuse ColorPointerType
// using gl::GL_UNSIGNED_BYTE; // reuse ColorPointerType
// using gl::GL_SHORT; // reuse ColorPointerType
// using gl::GL_UNSIGNED_SHORT; // reuse ColorPointerType
// using gl::GL_INT; // reuse ColorPointerType
// using gl::GL_UNSIGNED_INT; // reuse ColorPointerType
// using gl::GL_FLOAT; // reuse ColorPointerType
using gl::GL_BITMAP;
using gl::GL_UNSIGNED_BYTE_3_3_2;
using gl::GL_UNSIGNED_SHORT_4_4_4_4;
using gl::GL_UNSIGNED_SHORT_5_5_5_1;
using gl::GL_UNSIGNED_INT_8_8_8_8;
using gl::GL_UNSIGNED_INT_10_10_10_2;
// PointParameterNameSGIS
using gl::GL_POINT_SIZE_MIN;
using gl::GL_POINT_SIZE_MAX;
using gl::GL_POINT_FADE_THRESHOLD_SIZE;
using gl::GL_POINT_DISTANCE_ATTENUATION;
// PolygonMode
// using gl::GL_POINT; // reuse MeshMode1
// using gl::GL_LINE; // reuse MeshMode1
// using gl::GL_FILL; // reuse MeshMode2
// PrimitiveType
using gl::GL_POINTS;
using gl::GL_LINES;
using gl::GL_LINE_LOOP;
using gl::GL_LINE_STRIP;
using gl::GL_TRIANGLES;
using gl::GL_TRIANGLE_STRIP;
using gl::GL_TRIANGLE_FAN;
using gl::GL_QUADS;
using gl::GL_QUAD_STRIP;
using gl::GL_POLYGON;
// ReadBufferMode
// using gl::GL_FRONT_LEFT; // reuse DrawBufferMode
// using gl::GL_FRONT_RIGHT; // reuse DrawBufferMode
// using gl::GL_BACK_LEFT; // reuse DrawBufferMode
// using gl::GL_BACK_RIGHT; // reuse DrawBufferMode
// using gl::GL_FRONT; // reuse ColorMaterialFace
// using gl::GL_BACK; // reuse ColorMaterialFace
// using gl::GL_LEFT; // reuse DrawBufferMode
// using gl::GL_RIGHT; // reuse DrawBufferMode
// using gl::GL_AUX0; // reuse DrawBufferMode
// using gl::GL_AUX1; // reuse DrawBufferMode
// using gl::GL_AUX2; // reuse DrawBufferMode
// using gl::GL_AUX3; // reuse DrawBufferMode
// RenderingMode
using gl::GL_RENDER;
using gl::GL_FEEDBACK;
using gl::GL_SELECT;
// ShadingModel
using gl::GL_FLAT;
using gl::GL_SMOOTH;
// StencilFunction
// using gl::GL_NEVER; // reuse AlphaFunction
// using gl::GL_LESS; // reuse AlphaFunction
// using gl::GL_EQUAL; // reuse AlphaFunction
// using gl::GL_LEQUAL; // reuse AlphaFunction
// using gl::GL_GREATER; // reuse AlphaFunction
// using gl::GL_NOTEQUAL; // reuse AlphaFunction
// using gl::GL_GEQUAL; // reuse AlphaFunction
// using gl::GL_ALWAYS; // reuse AlphaFunction
// StencilOp
// using gl::GL_ZERO; // reuse BlendingFactorDest
// using gl::GL_INVERT; // reuse LogicOp
using gl::GL_KEEP;
// using gl::GL_REPLACE; // reuse LightEnvModeSGIX
using gl::GL_INCR;
using gl::GL_DECR;
// StringName
using gl::GL_VENDOR;
using gl::GL_RENDERER;
using gl::GL_VERSION;
using gl::GL_EXTENSIONS;
// TexCoordPointerType
// using gl::GL_SHORT; // reuse ColorPointerType
// using gl::GL_INT; // reuse ColorPointerType
// using gl::GL_FLOAT; // reuse ColorPointerType
// using gl::GL_DOUBLE; // reuse ColorPointerType
// TextureCoordName
using gl::GL_S;
using gl::GL_T;
using gl::GL_R;
using gl::GL_Q;
// TextureEnvMode
// using gl::GL_ADD; // reuse AccumOp
// using gl::GL_BLEND; // reuse EnableCap
// using gl::GL_MODULATE; // reuse LightEnvModeSGIX
using gl::GL_DECAL;
// TextureEnvParameter
using gl::GL_TEXTURE_ENV_MODE;
using gl::GL_TEXTURE_ENV_COLOR;
// TextureEnvTarget
using gl::GL_TEXTURE_ENV;
// TextureGenMode
using gl::GL_EYE_LINEAR;
using gl::GL_OBJECT_LINEAR;
using gl::GL_SPHERE_MAP;
// TextureGenParameter
using gl::GL_TEXTURE_GEN_MODE;
using gl::GL_OBJECT_PLANE;
using gl::GL_EYE_PLANE;
// TextureMagFilter
using gl::GL_NEAREST;
// using gl::GL_LINEAR; // reuse FogMode
// TextureMinFilter
// using gl::GL_NEAREST; // reuse TextureMagFilter
// using gl::GL_LINEAR; // reuse FogMode
using gl::GL_NEAREST_MIPMAP_NEAREST;
using gl::GL_LINEAR_MIPMAP_NEAREST;
using gl::GL_NEAREST_MIPMAP_LINEAR;
using gl::GL_LINEAR_MIPMAP_LINEAR;
// TextureParameterName
// using gl::GL_TEXTURE_BORDER_COLOR; // reuse GetTextureParameter
// using gl::GL_TEXTURE_MAG_FILTER; // reuse GetTextureParameter
// using gl::GL_TEXTURE_MIN_FILTER; // reuse GetTextureParameter
// using gl::GL_TEXTURE_WRAP_S; // reuse GetTextureParameter
// using gl::GL_TEXTURE_WRAP_T; // reuse GetTextureParameter
// using gl::GL_TEXTURE_PRIORITY; // reuse GetTextureParameter
using gl::GL_TEXTURE_WRAP_R;
using gl::GL_GENERATE_MIPMAP;
// TextureTarget
// using gl::GL_TEXTURE_1D; // reuse EnableCap
// using gl::GL_TEXTURE_2D; // reuse EnableCap
using gl::GL_PROXY_TEXTURE_1D;
using gl::GL_PROXY_TEXTURE_2D;
using gl::GL_TEXTURE_3D;
using gl::GL_PROXY_TEXTURE_3D;
using gl::GL_TEXTURE_MIN_LOD;
using gl::GL_TEXTURE_MAX_LOD;
using gl::GL_TEXTURE_BASE_LEVEL;
using gl::GL_TEXTURE_MAX_LEVEL;
// TextureWrapMode
using gl::GL_CLAMP;
using gl::GL_REPEAT;
using gl::GL_CLAMP_TO_BORDER;
using gl::GL_CLAMP_TO_EDGE;
// VertexPointerType
// using gl::GL_SHORT; // reuse ColorPointerType
// using gl::GL_INT; // reuse ColorPointerType
// using gl::GL_FLOAT; // reuse ColorPointerType
// using gl::GL_DOUBLE; // reuse ColorPointerType
// __UNGROUPED__
using gl::GL_HALF_FLOAT;
using gl::GL_CONSTANT_COLOR;
using gl::GL_ONE_MINUS_CONSTANT_COLOR;
using gl::GL_CONSTANT_ALPHA;
using gl::GL_ONE_MINUS_CONSTANT_ALPHA;
using gl::GL_FUNC_ADD;
using gl::GL_MIN;
using gl::GL_MAX;
using gl::GL_BLEND_EQUATION_RGB;
using gl::GL_FUNC_SUBTRACT;
using gl::GL_FUNC_REVERSE_SUBTRACT;
using gl::GL_RESCALE_NORMAL;
using gl::GL_TEXTURE_DEPTH;
using gl::GL_MAX_3D_TEXTURE_SIZE;
using gl::GL_MULTISAMPLE;
using gl::GL_SAMPLE_ALPHA_TO_COVERAGE;
using gl::GL_SAMPLE_ALPHA_TO_ONE;
using gl::GL_SAMPLE_COVERAGE;
using gl::GL_SAMPLE_BUFFERS;
using gl::GL_SAMPLES;
using gl::GL_SAMPLE_COVERAGE_VALUE;
using gl::GL_SAMPLE_COVERAGE_INVERT;
using gl::GL_BLEND_DST_RGB;
using gl::GL_BLEND_SRC_RGB;
using gl::GL_BLEND_DST_ALPHA;
using gl::GL_BLEND_SRC_ALPHA;
using gl::GL_BGR;
using gl::GL_BGRA;
using gl::GL_MAX_ELEMENTS_VERTICES;
using gl::GL_MAX_ELEMENTS_INDICES;
using gl::GL_DEPTH_COMPONENT16;
using gl::GL_DEPTH_COMPONENT24;
using gl::GL_DEPTH_COMPONENT32;
using gl::GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING;
using gl::GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE;
using gl::GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE;
using gl::GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE;
using gl::GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE;
using gl::GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE;
using gl::GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE;
using gl::GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE;
using gl::GL_FRAMEBUFFER_DEFAULT;
using gl::GL_FRAMEBUFFER_UNDEFINED;
using gl::GL_DEPTH_STENCIL_ATTACHMENT;
using gl::GL_MAJOR_VERSION;
using gl::GL_MINOR_VERSION;
using gl::GL_NUM_EXTENSIONS;
using gl::GL_CONTEXT_FLAGS;
using gl::GL_INDEX;
using gl::GL_COMPRESSED_RED;
using gl::GL_COMPRESSED_RG;
using gl::GL_RG;
using gl::GL_RG_INTEGER;
using gl::GL_R8;
using gl::GL_R16;
using gl::GL_RG8;
using gl::GL_RG16;
using gl::GL_R16F;
using gl::GL_R32F;
using gl::GL_RG16F;
using gl::GL_RG32F;
using gl::GL_R8I;
using gl::GL_R8UI;
using gl::GL_R16I;
using gl::GL_R16UI;
using gl::GL_R32I;
using gl::GL_R32UI;
using gl::GL_RG8I;
using gl::GL_RG8UI;
using gl::GL_RG16I;
using gl::GL_RG16UI;
using gl::GL_RG32I;
using gl::GL_RG32UI;
using gl::GL_UNSIGNED_BYTE_2_3_3_REV;
using gl::GL_UNSIGNED_SHORT_5_6_5;
using gl::GL_UNSIGNED_SHORT_5_6_5_REV;
using gl::GL_UNSIGNED_SHORT_4_4_4_4_REV;
using gl::GL_UNSIGNED_SHORT_1_5_5_5_REV;
using gl::GL_UNSIGNED_INT_8_8_8_8_REV;
using gl::GL_UNSIGNED_INT_2_10_10_10_REV;
using gl::GL_MIRRORED_REPEAT;
using gl::GL_FOG_COORDINATE_SOURCE;
using gl::GL_FOG_COORD_SRC;
using gl::GL_FOG_COORD;
using gl::GL_FOG_COORDINATE;
using gl::GL_FRAGMENT_DEPTH;
using gl::GL_CURRENT_FOG_COORD;
using gl::GL_CURRENT_FOG_COORDINATE;
using gl::GL_FOG_COORDINATE_ARRAY_TYPE;
using gl::GL_FOG_COORD_ARRAY_TYPE;
using gl::GL_FOG_COORDINATE_ARRAY_STRIDE;
using gl::GL_FOG_COORD_ARRAY_STRIDE;
using gl::GL_FOG_COORDINATE_ARRAY_POINTER;
using gl::GL_FOG_COORD_ARRAY_POINTER;
using gl::GL_FOG_COORDINATE_ARRAY;
using gl::GL_FOG_COORD_ARRAY;
using gl::GL_COLOR_SUM;
using gl::GL_CURRENT_SECONDARY_COLOR;
using gl::GL_SECONDARY_COLOR_ARRAY_SIZE;
using gl::GL_SECONDARY_COLOR_ARRAY_TYPE;
using gl::GL_SECONDARY_COLOR_ARRAY_STRIDE;
using gl::GL_SECONDARY_COLOR_ARRAY_POINTER;
using gl::GL_SECONDARY_COLOR_ARRAY;
using gl::GL_CURRENT_RASTER_SECONDARY_COLOR;
using gl::GL_TEXTURE0;
using gl::GL_TEXTURE1;
using gl::GL_TEXTURE2;
using gl::GL_TEXTURE3;
using gl::GL_TEXTURE4;
using gl::GL_TEXTURE5;
using gl::GL_TEXTURE6;
using gl::GL_TEXTURE7;
using gl::GL_TEXTURE8;
using gl::GL_TEXTURE9;
using gl::GL_TEXTURE10;
using gl::GL_TEXTURE11;
using gl::GL_TEXTURE12;
using gl::GL_TEXTURE13;
using gl::GL_TEXTURE14;
using gl::GL_TEXTURE15;
using gl::GL_TEXTURE16;
using gl::GL_TEXTURE17;
using gl::GL_TEXTURE18;
using gl::GL_TEXTURE19;
using gl::GL_TEXTURE20;
using gl::GL_TEXTURE21;
using gl::GL_TEXTURE22;
using gl::GL_TEXTURE23;
using gl::GL_TEXTURE24;
using gl::GL_TEXTURE25;
using gl::GL_TEXTURE26;
using gl::GL_TEXTURE27;
using gl::GL_TEXTURE28;
using gl::GL_TEXTURE29;
using gl::GL_TEXTURE30;
using gl::GL_TEXTURE31;
using gl::GL_ACTIVE_TEXTURE;
using gl::GL_CLIENT_ACTIVE_TEXTURE;
using gl::GL_MAX_TEXTURE_UNITS;
using gl::GL_TRANSPOSE_MODELVIEW_MATRIX;
using gl::GL_TRANSPOSE_PROJECTION_MATRIX;
using gl::GL_TRANSPOSE_TEXTURE_MATRIX;
using gl::GL_TRANSPOSE_COLOR_MATRIX;
using gl::GL_SUBTRACT;
using gl::GL_MAX_RENDERBUFFER_SIZE;
using gl::GL_COMPRESSED_ALPHA;
using gl::GL_COMPRESSED_LUMINANCE;
using gl::GL_COMPRESSED_LUMINANCE_ALPHA;
using gl::GL_COMPRESSED_INTENSITY;
using gl::GL_COMPRESSED_RGB;
using gl::GL_COMPRESSED_RGBA;
using gl::GL_TEXTURE_RECTANGLE;
using gl::GL_TEXTURE_BINDING_RECTANGLE;
using gl::GL_PROXY_TEXTURE_RECTANGLE;
using gl::GL_MAX_RECTANGLE_TEXTURE_SIZE;
using gl::GL_DEPTH_STENCIL;
using gl::GL_UNSIGNED_INT_24_8;
using gl::GL_MAX_TEXTURE_LOD_BIAS;
using gl::GL_TEXTURE_FILTER_CONTROL;
using gl::GL_TEXTURE_LOD_BIAS;
using gl::GL_INCR_WRAP;
using gl::GL_DECR_WRAP;
using gl::GL_NORMAL_MAP;
using gl::GL_REFLECTION_MAP;
using gl::GL_TEXTURE_CUBE_MAP;
using gl::GL_TEXTURE_BINDING_CUBE_MAP;
using gl::GL_TEXTURE_CUBE_MAP_POSITIVE_X;
using gl::GL_TEXTURE_CUBE_MAP_NEGATIVE_X;
using gl::GL_TEXTURE_CUBE_MAP_POSITIVE_Y;
using gl::GL_TEXTURE_CUBE_MAP_NEGATIVE_Y;
using gl::GL_TEXTURE_CUBE_MAP_POSITIVE_Z;
using gl::GL_TEXTURE_CUBE_MAP_NEGATIVE_Z;
using gl::GL_PROXY_TEXTURE_CUBE_MAP;
using gl::GL_MAX_CUBE_MAP_TEXTURE_SIZE;
using gl::GL_COMBINE;
using gl::GL_COMBINE_RGB;
using gl::GL_COMBINE_ALPHA;
using gl::GL_RGB_SCALE;
using gl::GL_ADD_SIGNED;
using gl::GL_INTERPOLATE;
using gl::GL_CONSTANT;
using gl::GL_PRIMARY_COLOR;
using gl::GL_PREVIOUS;
using gl::GL_SOURCE0_RGB;
using gl::GL_SRC0_RGB;
using gl::GL_SOURCE1_RGB;
using gl::GL_SRC1_RGB;
using gl::GL_SOURCE2_RGB;
using gl::GL_SRC2_RGB;
using gl::GL_SOURCE0_ALPHA;
using gl::GL_SRC0_ALPHA;
using gl::GL_SOURCE1_ALPHA;
using gl::GL_SRC1_ALPHA;
using gl::GL_SOURCE2_ALPHA;
using gl::GL_SRC2_ALPHA;
using gl::GL_OPERAND0_RGB;
using gl::GL_OPERAND1_RGB;
using gl::GL_OPERAND2_RGB;
using gl::GL_OPERAND0_ALPHA;
using gl::GL_OPERAND1_ALPHA;
using gl::GL_OPERAND2_ALPHA;
using gl::GL_VERTEX_ARRAY_BINDING;
using gl::GL_VERTEX_ATTRIB_ARRAY_ENABLED;
using gl::GL_VERTEX_ATTRIB_ARRAY_SIZE;
using gl::GL_VERTEX_ATTRIB_ARRAY_STRIDE;
using gl::GL_VERTEX_ATTRIB_ARRAY_TYPE;
using gl::GL_CURRENT_VERTEX_ATTRIB;
using gl::GL_PROGRAM_POINT_SIZE;
using gl::GL_VERTEX_PROGRAM_POINT_SIZE;
using gl::GL_VERTEX_PROGRAM_TWO_SIDE;
using gl::GL_VERTEX_ATTRIB_ARRAY_POINTER;
using gl::GL_TEXTURE_COMPRESSED_IMAGE_SIZE;
using gl::GL_TEXTURE_COMPRESSED;
using gl::GL_NUM_COMPRESSED_TEXTURE_FORMATS;
using gl::GL_COMPRESSED_TEXTURE_FORMATS;
using gl::GL_DOT3_RGB;
using gl::GL_DOT3_RGBA;
using gl::GL_BUFFER_SIZE;
using gl::GL_BUFFER_USAGE;
using gl::GL_STENCIL_BACK_FUNC;
using gl::GL_STENCIL_BACK_FAIL;
using gl::GL_STENCIL_BACK_PASS_DEPTH_FAIL;
using gl::GL_STENCIL_BACK_PASS_DEPTH_PASS;
using gl::GL_RGBA32F;
using gl::GL_RGB32F;
using gl::GL_RGBA16F;
using gl::GL_RGB16F;
using gl::GL_MAX_DRAW_BUFFERS;
using gl::GL_DRAW_BUFFER0;
using gl::GL_DRAW_BUFFER1;
using gl::GL_DRAW_BUFFER2;
using gl::GL_DRAW_BUFFER3;
using gl::GL_DRAW_BUFFER4;
using gl::GL_DRAW_BUFFER5;
using gl::GL_DRAW_BUFFER6;
using gl::GL_DRAW_BUFFER7;
using gl::GL_DRAW_BUFFER8;
using gl::GL_DRAW_BUFFER9;
using gl::GL_DRAW_BUFFER10;
using gl::GL_DRAW_BUFFER11;
using gl::GL_DRAW_BUFFER12;
using gl::GL_DRAW_BUFFER13;
using gl::GL_DRAW_BUFFER14;
using gl::GL_DRAW_BUFFER15;
using gl::GL_BLEND_EQUATION_ALPHA;
using gl::GL_TEXTURE_DEPTH_SIZE;
using gl::GL_DEPTH_TEXTURE_MODE;
using gl::GL_TEXTURE_COMPARE_MODE;
using gl::GL_TEXTURE_COMPARE_FUNC;
using gl::GL_COMPARE_REF_TO_TEXTURE;
using gl::GL_COMPARE_R_TO_TEXTURE;
using gl::GL_POINT_SPRITE;
using gl::GL_COORD_REPLACE;
using gl::GL_QUERY_COUNTER_BITS;
using gl::GL_CURRENT_QUERY;
using gl::GL_QUERY_RESULT;
using gl::GL_QUERY_RESULT_AVAILABLE;
using gl::GL_MAX_VERTEX_ATTRIBS;
using gl::GL_VERTEX_ATTRIB_ARRAY_NORMALIZED;
using gl::GL_MAX_TEXTURE_COORDS;
using gl::GL_MAX_TEXTURE_IMAGE_UNITS;
using gl::GL_ARRAY_BUFFER;
using gl::GL_ELEMENT_ARRAY_BUFFER;
using gl::GL_ARRAY_BUFFER_BINDING;
using gl::GL_ELEMENT_ARRAY_BUFFER_BINDING;
using gl::GL_VERTEX_ARRAY_BUFFER_BINDING;
using gl::GL_NORMAL_ARRAY_BUFFER_BINDING;
using gl::GL_COLOR_ARRAY_BUFFER_BINDING;
using gl::GL_INDEX_ARRAY_BUFFER_BINDING;
using gl::GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING;
using gl::GL_EDGE_FLAG_ARRAY_BUFFER_BINDING;
using gl::GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING;
using gl::GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING;
using gl::GL_FOG_COORD_ARRAY_BUFFER_BINDING;
using gl::GL_WEIGHT_ARRAY_BUFFER_BINDING;
using gl::GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING;
using gl::GL_READ_ONLY;
using gl::GL_WRITE_ONLY;
using gl::GL_READ_WRITE;
using gl::GL_BUFFER_ACCESS;
using gl::GL_BUFFER_MAPPED;
using gl::GL_BUFFER_MAP_POINTER;
using gl::GL_STREAM_DRAW;
using gl::GL_STREAM_READ;
using gl::GL_STREAM_COPY;
using gl::GL_STATIC_DRAW;
using gl::GL_STATIC_READ;
using gl::GL_STATIC_COPY;
using gl::GL_DYNAMIC_DRAW;
using gl::GL_DYNAMIC_READ;
using gl::GL_DYNAMIC_COPY;
using gl::GL_PIXEL_PACK_BUFFER;
using gl::GL_PIXEL_UNPACK_BUFFER;
using gl::GL_PIXEL_PACK_BUFFER_BINDING;
using gl::GL_PIXEL_UNPACK_BUFFER_BINDING;
using gl::GL_DEPTH24_STENCIL8;
using gl::GL_TEXTURE_STENCIL_SIZE;
using gl::GL_VERTEX_ATTRIB_ARRAY_INTEGER;
using gl::GL_MAX_ARRAY_TEXTURE_LAYERS;
using gl::GL_MIN_PROGRAM_TEXEL_OFFSET;
using gl::GL_MAX_PROGRAM_TEXEL_OFFSET;
using gl::GL_SAMPLES_PASSED;
using gl::GL_CLAMP_VERTEX_COLOR;
using gl::GL_CLAMP_FRAGMENT_COLOR;
using gl::GL_CLAMP_READ_COLOR;
using gl::GL_FIXED_ONLY;
using gl::GL_UNIFORM_BUFFER;
using gl::GL_UNIFORM_BUFFER_BINDING;
using gl::GL_UNIFORM_BUFFER_START;
using gl::GL_UNIFORM_BUFFER_SIZE;
using gl::GL_MAX_VERTEX_UNIFORM_BLOCKS;
using gl::GL_MAX_GEOMETRY_UNIFORM_BLOCKS;
using gl::GL_MAX_FRAGMENT_UNIFORM_BLOCKS;
using gl::GL_MAX_COMBINED_UNIFORM_BLOCKS;
using gl::GL_MAX_UNIFORM_BUFFER_BINDINGS;
using gl::GL_MAX_UNIFORM_BLOCK_SIZE;
using gl::GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS;
using gl::GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS;
using gl::GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS;
using gl::GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT;
using gl::GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH;
using gl::GL_ACTIVE_UNIFORM_BLOCKS;
using gl::GL_UNIFORM_TYPE;
using gl::GL_UNIFORM_SIZE;
using gl::GL_UNIFORM_NAME_LENGTH;
using gl::GL_UNIFORM_BLOCK_INDEX;
using gl::GL_UNIFORM_OFFSET;
using gl::GL_UNIFORM_ARRAY_STRIDE;
using gl::GL_UNIFORM_MATRIX_STRIDE;
using gl::GL_UNIFORM_IS_ROW_MAJOR;
using gl::GL_UNIFORM_BLOCK_BINDING;
using gl::GL_UNIFORM_BLOCK_DATA_SIZE;
using gl::GL_UNIFORM_BLOCK_NAME_LENGTH;
using gl::GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS;
using gl::GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES;
using gl::GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER;
using gl::GL_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER;
using gl::GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER;
using gl::GL_FRAGMENT_SHADER;
using gl::GL_VERTEX_SHADER;
using gl::GL_MAX_FRAGMENT_UNIFORM_COMPONENTS;
using gl::GL_MAX_VERTEX_UNIFORM_COMPONENTS;
using gl::GL_MAX_VARYING_COMPONENTS;
using gl::GL_MAX_VARYING_FLOATS;
using gl::GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS;
using gl::GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS;
using gl::GL_SHADER_TYPE;
using gl::GL_FLOAT_VEC2;
using gl::GL_FLOAT_VEC3;
using gl::GL_FLOAT_VEC4;
using gl::GL_INT_VEC2;
using gl::GL_INT_VEC3;
using gl::GL_INT_VEC4;
using gl::GL_BOOL;
using gl::GL_BOOL_VEC2;
using gl::GL_BOOL_VEC3;
using gl::GL_BOOL_VEC4;
using gl::GL_FLOAT_MAT2;
using gl::GL_FLOAT_MAT3;
using gl::GL_FLOAT_MAT4;
using gl::GL_SAMPLER_1D;
using gl::GL_SAMPLER_2D;
using gl::GL_SAMPLER_3D;
using gl::GL_SAMPLER_CUBE;
using gl::GL_SAMPLER_1D_SHADOW;
using gl::GL_SAMPLER_2D_SHADOW;
using gl::GL_SAMPLER_2D_RECT;
using gl::GL_SAMPLER_2D_RECT_SHADOW;
using gl::GL_FLOAT_MAT2x3;
using gl::GL_FLOAT_MAT2x4;
using gl::GL_FLOAT_MAT3x2;
using gl::GL_FLOAT_MAT3x4;
using gl::GL_FLOAT_MAT4x2;
using gl::GL_FLOAT_MAT4x3;
using gl::GL_DELETE_STATUS;
using gl::GL_COMPILE_STATUS;
using gl::GL_LINK_STATUS;
using gl::GL_VALIDATE_STATUS;
using gl::GL_INFO_LOG_LENGTH;
using gl::GL_ATTACHED_SHADERS;
using gl::GL_ACTIVE_UNIFORMS;
using gl::GL_ACTIVE_UNIFORM_MAX_LENGTH;
using gl::GL_SHADER_SOURCE_LENGTH;
using gl::GL_ACTIVE_ATTRIBUTES;
using gl::GL_ACTIVE_ATTRIBUTE_MAX_LENGTH;
using gl::GL_SHADING_LANGUAGE_VERSION;
using gl::GL_ACTIVE_PROGRAM_EXT;
using gl::GL_CURRENT_PROGRAM;
using gl::GL_TEXTURE_RED_TYPE;
using gl::GL_TEXTURE_GREEN_TYPE;
using gl::GL_TEXTURE_BLUE_TYPE;
using gl::GL_TEXTURE_ALPHA_TYPE;
using gl::GL_TEXTURE_LUMINANCE_TYPE;
using gl::GL_TEXTURE_INTENSITY_TYPE;
using gl::GL_TEXTURE_DEPTH_TYPE;
using gl::GL_UNSIGNED_NORMALIZED;
using gl::GL_TEXTURE_1D_ARRAY;
using gl::GL_PROXY_TEXTURE_1D_ARRAY;
using gl::GL_TEXTURE_2D_ARRAY;
using gl::GL_PROXY_TEXTURE_2D_ARRAY;
using gl::GL_TEXTURE_BINDING_1D_ARRAY;
using gl::GL_TEXTURE_BINDING_2D_ARRAY;
using gl::GL_TEXTURE_BUFFER;
using gl::GL_MAX_TEXTURE_BUFFER_SIZE;
using gl::GL_TEXTURE_BINDING_BUFFER;
using gl::GL_TEXTURE_BUFFER_DATA_STORE_BINDING;
using gl::GL_R11F_G11F_B10F;
using gl::GL_UNSIGNED_INT_10F_11F_11F_REV;
using gl::GL_RGB9_E5;
using gl::GL_UNSIGNED_INT_5_9_9_9_REV;
using gl::GL_TEXTURE_SHARED_SIZE;
using gl::GL_SRGB;
using gl::GL_SRGB8;
using gl::GL_SRGB_ALPHA;
using gl::GL_SRGB8_ALPHA8;
using gl::GL_SLUMINANCE_ALPHA;
using gl::GL_SLUMINANCE8_ALPHA8;
using gl::GL_SLUMINANCE;
using gl::GL_SLUMINANCE8;
using gl::GL_COMPRESSED_SRGB;
using gl::GL_COMPRESSED_SRGB_ALPHA;
using gl::GL_COMPRESSED_SLUMINANCE;
using gl::GL_COMPRESSED_SLUMINANCE_ALPHA;
using gl::GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH;
using gl::GL_TRANSFORM_FEEDBACK_BUFFER_MODE;
using gl::GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS;
using gl::GL_TRANSFORM_FEEDBACK_VARYINGS;
using gl::GL_TRANSFORM_FEEDBACK_BUFFER_START;
using gl::GL_TRANSFORM_FEEDBACK_BUFFER_SIZE;
using gl::GL_PRIMITIVES_GENERATED;
using gl::GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN;
using gl::GL_RASTERIZER_DISCARD;
using gl::GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS;
using gl::GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS;
using gl::GL_INTERLEAVED_ATTRIBS;
using gl::GL_SEPARATE_ATTRIBS;
using gl::GL_TRANSFORM_FEEDBACK_BUFFER;
using gl::GL_TRANSFORM_FEEDBACK_BUFFER_BINDING;
using gl::GL_POINT_SPRITE_COORD_ORIGIN;
using gl::GL_LOWER_LEFT;
using gl::GL_UPPER_LEFT;
using gl::GL_STENCIL_BACK_REF;
using gl::GL_STENCIL_BACK_VALUE_MASK;
using gl::GL_STENCIL_BACK_WRITEMASK;
using gl::GL_DRAW_FRAMEBUFFER_BINDING;
using gl::GL_FRAMEBUFFER_BINDING;
using gl::GL_RENDERBUFFER_BINDING;
using gl::GL_READ_FRAMEBUFFER;
using gl::GL_DRAW_FRAMEBUFFER;
using gl::GL_READ_FRAMEBUFFER_BINDING;
using gl::GL_RENDERBUFFER_SAMPLES;
using gl::GL_DEPTH_COMPONENT32F;
using gl::GL_DEPTH32F_STENCIL8;
using gl::GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE;
using gl::GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME;
using gl::GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL;
using gl::GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE;
using gl::GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER;
using gl::GL_FRAMEBUFFER_COMPLETE;
using gl::GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
using gl::GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT;
using gl::GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER;
using gl::GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER;
using gl::GL_FRAMEBUFFER_UNSUPPORTED;
using gl::GL_MAX_COLOR_ATTACHMENTS;
using gl::GL_COLOR_ATTACHMENT0;
using gl::GL_COLOR_ATTACHMENT1;
using gl::GL_COLOR_ATTACHMENT2;
using gl::GL_COLOR_ATTACHMENT3;
using gl::GL_COLOR_ATTACHMENT4;
using gl::GL_COLOR_ATTACHMENT5;
using gl::GL_COLOR_ATTACHMENT6;
using gl::GL_COLOR_ATTACHMENT7;
using gl::GL_COLOR_ATTACHMENT8;
using gl::GL_COLOR_ATTACHMENT9;
using gl::GL_COLOR_ATTACHMENT10;
using gl::GL_COLOR_ATTACHMENT11;
using gl::GL_COLOR_ATTACHMENT12;
using gl::GL_COLOR_ATTACHMENT13;
using gl::GL_COLOR_ATTACHMENT14;
using gl::GL_COLOR_ATTACHMENT15;
using gl::GL_COLOR_ATTACHMENT16;
using gl::GL_COLOR_ATTACHMENT17;
using gl::GL_COLOR_ATTACHMENT18;
using gl::GL_COLOR_ATTACHMENT19;
using gl::GL_COLOR_ATTACHMENT20;
using gl::GL_COLOR_ATTACHMENT21;
using gl::GL_COLOR_ATTACHMENT22;
using gl::GL_COLOR_ATTACHMENT23;
using gl::GL_COLOR_ATTACHMENT24;
using gl::GL_COLOR_ATTACHMENT25;
using gl::GL_COLOR_ATTACHMENT26;
using gl::GL_COLOR_ATTACHMENT27;
using gl::GL_COLOR_ATTACHMENT28;
using gl::GL_COLOR_ATTACHMENT29;
using gl::GL_COLOR_ATTACHMENT30;
using gl::GL_COLOR_ATTACHMENT31;
using gl::GL_DEPTH_ATTACHMENT;
using gl::GL_STENCIL_ATTACHMENT;
using gl::GL_FRAMEBUFFER;
using gl::GL_RENDERBUFFER;
using gl::GL_RENDERBUFFER_WIDTH;
using gl::GL_RENDERBUFFER_HEIGHT;
using gl::GL_RENDERBUFFER_INTERNAL_FORMAT;
using gl::GL_STENCIL_INDEX1;
using gl::GL_STENCIL_INDEX4;
using gl::GL_STENCIL_INDEX8;
using gl::GL_STENCIL_INDEX16;
using gl::GL_RENDERBUFFER_RED_SIZE;
using gl::GL_RENDERBUFFER_GREEN_SIZE;
using gl::GL_RENDERBUFFER_BLUE_SIZE;
using gl::GL_RENDERBUFFER_ALPHA_SIZE;
using gl::GL_RENDERBUFFER_DEPTH_SIZE;
using gl::GL_RENDERBUFFER_STENCIL_SIZE;
using gl::GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE;
using gl::GL_MAX_SAMPLES;
using gl::GL_RGBA32UI;
using gl::GL_RGB32UI;
using gl::GL_RGBA16UI;
using gl::GL_RGB16UI;
using gl::GL_RGBA8UI;
using gl::GL_RGB8UI;
using gl::GL_RGBA32I;
using gl::GL_RGB32I;
using gl::GL_RGBA16I;
using gl::GL_RGB16I;
using gl::GL_RGBA8I;
using gl::GL_RGB8I;
using gl::GL_RED_INTEGER;
using gl::GL_GREEN_INTEGER;
using gl::GL_BLUE_INTEGER;
using gl::GL_ALPHA_INTEGER;
using gl::GL_RGB_INTEGER;
using gl::GL_RGBA_INTEGER;
using gl::GL_BGR_INTEGER;
using gl::GL_BGRA_INTEGER;
using gl::GL_FLOAT_32_UNSIGNED_INT_24_8_REV;
using gl::GL_FRAMEBUFFER_SRGB;
using gl::GL_COMPRESSED_RED_RGTC1;
using gl::GL_COMPRESSED_SIGNED_RED_RGTC1;
using gl::GL_COMPRESSED_RG_RGTC2;
using gl::GL_COMPRESSED_SIGNED_RG_RGTC2;
using gl::GL_SAMPLER_1D_ARRAY;
using gl::GL_SAMPLER_2D_ARRAY;
using gl::GL_SAMPLER_BUFFER;
using gl::GL_SAMPLER_1D_ARRAY_SHADOW;
using gl::GL_SAMPLER_2D_ARRAY_SHADOW;
using gl::GL_SAMPLER_CUBE_SHADOW;
using gl::GL_UNSIGNED_INT_VEC2;
using gl::GL_UNSIGNED_INT_VEC3;
using gl::GL_UNSIGNED_INT_VEC4;
using gl::GL_INT_SAMPLER_1D;
using gl::GL_INT_SAMPLER_2D;
using gl::GL_INT_SAMPLER_3D;
using gl::GL_INT_SAMPLER_CUBE;
using gl::GL_INT_SAMPLER_2D_RECT;
using gl::GL_INT_SAMPLER_1D_ARRAY;
using gl::GL_INT_SAMPLER_2D_ARRAY;
using gl::GL_INT_SAMPLER_BUFFER;
using gl::GL_UNSIGNED_INT_SAMPLER_1D;
using gl::GL_UNSIGNED_INT_SAMPLER_2D;
using gl::GL_UNSIGNED_INT_SAMPLER_3D;
using gl::GL_UNSIGNED_INT_SAMPLER_CUBE;
using gl::GL_UNSIGNED_INT_SAMPLER_2D_RECT;
using gl::GL_UNSIGNED_INT_SAMPLER_1D_ARRAY;
using gl::GL_UNSIGNED_INT_SAMPLER_2D_ARRAY;
using gl::GL_UNSIGNED_INT_SAMPLER_BUFFER;
using gl::GL_QUERY_WAIT;
using gl::GL_QUERY_NO_WAIT;
using gl::GL_QUERY_BY_REGION_WAIT;
using gl::GL_QUERY_BY_REGION_NO_WAIT;
using gl::GL_COPY_READ_BUFFER;
using gl::GL_COPY_READ_BUFFER_BINDING;
using gl::GL_COPY_WRITE_BUFFER;
using gl::GL_COPY_WRITE_BUFFER_BINDING;
using gl::GL_R8_SNORM;
using gl::GL_RG8_SNORM;
using gl::GL_RGB8_SNORM;
using gl::GL_RGBA8_SNORM;
using gl::GL_R16_SNORM;
using gl::GL_RG16_SNORM;
using gl::GL_RGB16_SNORM;
using gl::GL_RGBA16_SNORM;
using gl::GL_SIGNED_NORMALIZED;
using gl::GL_PRIMITIVE_RESTART;
using gl::GL_PRIMITIVE_RESTART_INDEX;
using gl::GL_BUFFER_ACCESS_FLAGS;
using gl::GL_BUFFER_MAP_LENGTH;
using gl::GL_BUFFER_MAP_OFFSET;
} // namespace gl31
| [
"jakob.wagner@uni-weimar.de"
] | jakob.wagner@uni-weimar.de |
3a6f65ee6673a254155fc247c5707af18ae097ac | b77054fd04c2ae73f9eeb71c25e3acc6174bc158 | /ReadAnalogVoltage1.ino | 99324671a9b64e2d0ecc8f40f34ae539120c6cf1 | [] | no_license | abhishek1769/IOT-and-Embedded-projects-and-Experiments | cae991830f1ccf2022cd26b8cd4d614524aa4f78 | 014cae4e399bfe07ec552612f49f619201ee7288 | refs/heads/master | 2020-03-10T21:47:05.946353 | 2018-04-15T11:24:51 | 2018-04-15T11:24:51 | 129,602,892 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,449 | ino | /*
ReadAnalogVoltage
Reads an analog input on pin 0, converts it to voltage, and prints the result to the serial monitor.
Graphical representation is available using serial plotter (Tools > Serial Plotter menu)
Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.
This example code is in the public domain.
*/
// the setup routine runs once when you press reset:
#include<LiquidCrystal.h>
LiquidCrystal lcd(12,9,5,4,3,1);
void setup() {
// initialize serial communication at 9600 bits per second:
pinMode(11,OUTPUT);
pinMode(10,OUTPUT);
lcd.begin(16,2);
}
// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float voltage = sensorValue * (5.0 / 1023.0);
float v1 = voltage;
lcd.setCursor(0,0);
lcd.print("VOLT=");
lcd.setCursor(5,0);
lcd.print(v1);
lcd.setCursor(8,0);
lcd.print("V");
delay(1000);
if(v1!=voltage){
lcd.clear();
}else{
lcd.setCursor(0,0);
lcd.print("VOLT=");
lcd.setCursor(5,0);
lcd.print(v1);
lcd.setCursor(8,0);
lcd.print("V");
delay(1000);
}
if(voltage>=4.3){
digitalWrite(11,1);
// delay(1000);
}else if(voltage<=2.3){
digitalWrite(10,1);
// delay(1000);
}else{
digitalWrite(11,0);
digitalWrite(10,0);
//delay(5000);
}
}
| [
"noreply@github.com"
] | abhishek1769.noreply@github.com |
022c23cfebf067463df682437ea2ccd30aeec772 | 9ae5d2ce9daed564edbe9502872477cbc623ad27 | /ThirdPersonTest/Source/ThirdPersonTest/ThirdPersonTestCharacter.cpp | 3f6edd7798a381f19cd64e88b2a751244a543157 | [] | no_license | homeguatlla/UnrealGASTest | d4b1f88a8d12c59dd68b1c00420d7209ca066e60 | decf8fd3215fb6c770d2fffb5eda5fca9b732c81 | refs/heads/main | 2023-03-25T03:08:46.962309 | 2021-03-05T18:44:27 | 2021-03-05T18:44:27 | 340,334,270 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,604 | cpp | // Copyright Epic Games, Inc. All Rights Reserved.
#include "ThirdPersonTestCharacter.h"
#include "AttributeSet.h"
#include "HeadMountedDisplayFunctionLibrary.h"
#include "MyPlayerState.h"
#include "Utils.h"
#include "Camera/CameraComponent.h"
#include "Components/CapsuleComponent.h"
#include "Components/InputComponent.h"
#include "GameFramework/CharacterMovementComponent.h"
#include "GameFramework/Controller.h"
#include "GameFramework/SpringArmComponent.h"
#include "GAS/AbilityInputDefinition.h"
#include "GAS/Attributes/AttributeSetHealth.h"
//////////////////////////////////////////////////////////////////////////
// AThirdPersonTestCharacter
AThirdPersonTestCharacter::AThirdPersonTestCharacter()
{
if(HasAuthority())
{
UE_LOG(LogTemp, Error, TEXT("SERVER:"));
}
else
{
UE_LOG(LogTemp, Warning, TEXT("CLIENT:"));
}
UE_LOG(LogTemp, Warning, TEXT("AThirdPersonTestCharacter::AThirdPersonTestCharacter %s"), *GetName());
UE_LOG(LogTemp, Warning, TEXT("Role: %s Remote Role: %s"), *TransformRoleToFString(GetLocalRole()), *TransformRoleToFString(GetRemoteRole()));
// Set size for collision capsule
GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f);
// set our turn rates for input
BaseTurnRate = 45.f;
BaseLookUpRate = 45.f;
// Don't rotate when the controller rotates. Let that just affect the camera.
bUseControllerRotationPitch = false;
bUseControllerRotationYaw = false;
bUseControllerRotationRoll = false;
// Configure character movement
GetCharacterMovement()->bOrientRotationToMovement = true; // Character moves in the direction of input...
GetCharacterMovement()->RotationRate = FRotator(0.0f, 540.0f, 0.0f); // ...at this rotation rate
GetCharacterMovement()->JumpZVelocity = 600.f;
GetCharacterMovement()->AirControl = 0.2f;
// Create a camera boom (pulls in towards the player if there is a collision)
CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom"));
CameraBoom->SetupAttachment(RootComponent);
CameraBoom->TargetArmLength = 300.0f; // The camera follows at this distance behind the character
CameraBoom->bUsePawnControlRotation = true; // Rotate the arm based on the controller
// Create a follow camera
FollowCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("FollowCamera"));
FollowCamera->SetupAttachment(CameraBoom, USpringArmComponent::SocketName); // Attach the camera to the end of the boom and let the boom adjust to match the controller orientation
FollowCamera->bUsePawnControlRotation = false; // Camera does not rotate relative to arm
// Note: The skeletal mesh and anim blueprint references on the Mesh component (inherited from Character)
// are set in the derived blueprint asset named MyCharacter (to avoid direct content references in C++)
}
void AThirdPersonTestCharacter::BeginPlay()
{
Super::BeginPlay();
if(GetWorld()->IsServer())
{
UE_LOG(LogTemp, Error, TEXT("SERVER:"));
}
else
{
UE_LOG(LogTemp, Warning, TEXT("CLIENT:"));
}
UE_LOG(LogTemp, Warning, TEXT("AThirdPersonTestCharacter::BeginPlay %s"), *GetName());
UE_LOG(LogTemp, Warning, TEXT("Role: %s Remote Role: %s"), *TransformRoleToFString(GetLocalRole()), *TransformRoleToFString(GetRemoteRole()));
}
void AThirdPersonTestCharacter::PossessedBy(AController* NewController)
{
//Server only
Super::PossessedBy(NewController);
if(GetWorld()->IsServer())
{
UE_LOG(LogTemp, Error, TEXT("SERVER:"));
}
else
{
UE_LOG(LogTemp, Warning, TEXT("CLIENT:"));
}
UE_LOG(LogTemp, Warning, TEXT("AThirdPersonTestCharacter::PossessedBy character: %s possessed by player controller: %s"), *GetName(), *NewController->GetName());
UE_LOG(LogTemp, Warning, TEXT("Role: %s Remote Role: %s"), *TransformRoleToFString(GetLocalRole()), *TransformRoleToFString(GetRemoteRole()));
if(GetAbilitySystemComponent())
{
GetAbilitySystemComponent()->InitAbilityActorInfo(GetPlayerState(), this);
}
}
void AThirdPersonTestCharacter::UnPossessed()
{
if(GetWorld()->IsServer())
{
UE_LOG(LogTemp, Error, TEXT("SERVER:"));
}
else
{
UE_LOG(LogTemp, Warning, TEXT("CLIENT:"));
}
auto controller = GetController();
UE_LOG(LogTemp, Warning, TEXT("AThirdPersonTestCharacter::UnPossessed possessed by %s"), *controller->GetName());
Super::UnPossessed();
UE_LOG(LogTemp, Warning, TEXT("AThirdPersonTestCharacter::UnPossessed %s"), *GetName());
UE_LOG(LogTemp, Warning, TEXT("Role: %s Remote Role: %s"), *TransformRoleToFString(GetLocalRole()), *TransformRoleToFString(GetRemoteRole()));
}
void AThirdPersonTestCharacter::OnRep_PlayerState()
{
Super::OnRep_PlayerState();
//Client only
if(GetWorld()->IsServer())
{
UE_LOG(LogTemp, Error, TEXT("SERVER:"));
}
else
{
UE_LOG(LogTemp, Warning, TEXT("CLIENT:"));
}
UE_LOG(LogTemp, Warning, TEXT("AThirdPersonTestCharacter::OnRep_PlayerState character: %s"), *GetName());
UE_LOG(LogTemp, Warning, TEXT("Role: %s Remote Role: %s"), *TransformRoleToFString(GetLocalRole()), *TransformRoleToFString(GetRemoteRole()));
if(GetAbilitySystemComponent())
{
GetAbilitySystemComponent()->InitAbilityActorInfo(GetPlayerState(), this);
}
}
//////////////////////////////////////////////////////////////////////////
// Input
void AThirdPersonTestCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
// Set up gameplay key bindings
PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ACharacter::Jump);
PlayerInputComponent->BindAction("Jump", IE_Released, this, &ACharacter::StopJumping);
PlayerInputComponent->BindAxis("MoveForward", this, &AThirdPersonTestCharacter::MoveForward);
PlayerInputComponent->BindAxis("MoveRight", this, &AThirdPersonTestCharacter::MoveRight);
// We have 2 versions of the rotation bindings to handle different kinds of devices differently
// "turn" handles devices that provide an absolute delta, such as a mouse.
// "turnrate" is for devices that we choose to treat as a rate of change, such as an analog joystick
PlayerInputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput);
PlayerInputComponent->BindAxis("TurnRate", this, &AThirdPersonTestCharacter::TurnAtRate);
PlayerInputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput);
PlayerInputComponent->BindAxis("LookUpRate", this, &AThirdPersonTestCharacter::LookUpAtRate);
// handle touch devices
PlayerInputComponent->BindTouch(IE_Pressed, this, &AThirdPersonTestCharacter::TouchStarted);
PlayerInputComponent->BindTouch(IE_Released, this, &AThirdPersonTestCharacter::TouchStopped);
if(GetWorld()->IsServer())
{
UE_LOG(LogTemp, Error, TEXT("SERVER:"));
}
else
{
UE_LOG(LogTemp, Warning, TEXT("CLIENT:"));
}
UE_LOG(LogTemp, Warning, TEXT("AThirdPersonTestCharacter::SetupPlayerInputComponent %s"), *GetName());
const auto playerState = Cast<AMyPlayerState>(GetPlayerState());
mAbilitySystemComponent = playerState ? playerState->GetAbilitySystemComponent() : nullptr;
mAbilitySystemComponentBuilder.WithInputComponent(PlayerInputComponent)
.WithPlayerState(playerState)
.WithCharacter(this)
.Build();
}
void AThirdPersonTestCharacter::TouchStarted(ETouchIndex::Type FingerIndex, FVector Location)
{
Jump();
}
void AThirdPersonTestCharacter::TouchStopped(ETouchIndex::Type FingerIndex, FVector Location)
{
StopJumping();
}
void AThirdPersonTestCharacter::TurnAtRate(float Rate)
{
// calculate delta for this frame from the rate information
AddControllerYawInput(Rate * BaseTurnRate * GetWorld()->GetDeltaSeconds());
}
void AThirdPersonTestCharacter::LookUpAtRate(float Rate)
{
// calculate delta for this frame from the rate information
AddControllerPitchInput(Rate * BaseLookUpRate * GetWorld()->GetDeltaSeconds());
}
void AThirdPersonTestCharacter::MoveForward(float Value)
{
if ((Controller != nullptr) && (Value != 0.0f))
{
// find out which way is forward
const FRotator Rotation = Controller->GetControlRotation();
const FRotator YawRotation(0, Rotation.Yaw, 0);
// get forward vector
const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X);
AddMovementInput(Direction, Value);
}
}
void AThirdPersonTestCharacter::MoveRight(float Value)
{
if ( (Controller != nullptr) && (Value != 0.0f) )
{
// find out which way is right
const FRotator Rotation = Controller->GetControlRotation();
const FRotator YawRotation(0, Rotation.Yaw, 0);
// get right vector
const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y);
// add movement in that direction
AddMovementInput(Direction, Value);
}
}
| [
"dguerrero_bcn@hotmail.com"
] | dguerrero_bcn@hotmail.com |
b103ce66cecc09bea2dba14a61e6519267f4af60 | 1aaa697e8a716ee1dee3a8fb9f67d8c6432c1320 | /Framework/Shared/Camp/CampBindings.h | 04f76383dc8616fe3a175b1c75ab8ef0b0e002c8 | [] | no_license | MelvinRook/Diversia | a4a6d0dd6ec1e8509a0839e8a0ab1a9d4fd5a596 | 6e7bfbfa48bbd733da5c786dfad8e7d3a3645b42 | refs/heads/master | 2021-01-20T20:36:24.736608 | 2012-02-05T19:36:16 | 2012-02-05T19:36:16 | 60,241,791 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,745 | h | /*
-----------------------------------------------------------------------------
Copyright (c) 2008-2010 Diversia
This file is part of Diversia.
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 DIVERSIA_SHARED_CAMPBINDINGS_H
#define DIVERSIA_SHARED_CAMPBINDINGS_H
#include "Shared/Platform/Prerequisites.h"
namespace Diversia
{
namespace Shared
{
namespace Bindings
{
//------------------------------------------------------------------------------
class DIVERSIA_SHARED_API CampBindings
{
public:
static void bindPluginManager();
static void bindPlugin();
static void bindServerInfo();
static void bindServerNeighbors();
static void bindDirection();
static void bindPluginTypeEnum();
static void bindComponentTypeEnum();
static void bindResourceInfo();
static void bindTerrainTypeEnum();
static void bindHeightmapTypeEnum();
static void bindLayerInstance();
static void bindUserInfo();
static void bindPhysicsType();
static void bindPhysicsShape();
static void bindLuaManager();
static void bindLuaSecurityLevel();
static void bindCrashReporter();
#if DIVERSIA_PLATFORM == DIVERSIA_PLATFORM_WIN32
static void bindWindowsCrashReporter();
#endif
static void bindPermission();
static void bindPropertySynchronization();
static void bindGraphicsShape();
static void bindResourceLocationType();
static void bindResourceType();
static void bindSkyType();
static void bindLightType();
};
//------------------------------------------------------------------------------
} // Namespace Bindings
} // Namespace Shared
} // Namespace Diversia
#endif // DIVERSIA_SHARED_CAMPBINDINGS_H | [
"gabrielkonat@gmail.com"
] | gabrielkonat@gmail.com |
38205e65b5eaadbc45cdfa297a42b7641655cc81 | 67b7a7085447b7561208ed6df95dd3133df580e2 | /may01/macri/src/Shaders/IawShader.h | e6e7246ce818462111b776ce5a4961a18d47d258 | [
"LicenseRef-scancode-other-permissive"
] | permissive | dwilliamson/GDMagArchive | 81fd5b708417697bfb2caf8a983dd3ad7decdaf7 | 701948bbd74b7ae765be8cdaf4ae0f875e2bbf8e | refs/heads/master | 2021-06-07T23:41:08.343776 | 2016-10-31T14:42:20 | 2016-10-31T14:42:20 | 72,441,821 | 74 | 4 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 10,904 | h | // IawShader.h App Wizard Version 2.0 Beta 1
// ----------------------------------------------------------------------
//
// Copyright © 2001 Intel Corporation
// All Rights Reserved
//
// Permission is granted to use, copy, distribute and prepare derivative works of this
// software for any purpose and without fee, provided, that the above copyright notice
// and this statement appear in all copies. Intel makes no representations about the
// suitability of this software for any purpose. This software is provided "AS IS."
//
// Intel specifically disclaims all warranties, express or implied, and all liability,
// including consequential and other indirect damages, for the use of this software,
// including liability for infringement of any proprietary rights, and including the
// warranties of merchantability and fitness for a particular purpose. Intel does not
// assume any responsibility for any errors which may appear in this software nor any
// responsibility to update it.
// ----------------------------------------------------------------------
// Authors: Kim Pallister,Dean Macri - Intel Technology Diffusion Team
// ----------------------------------------------------------------------
#if !defined(IawShader_h)
#define IawShader_h
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
/*
//This class is used encapsulate a component of a shader pass.
class IawShaderComponent {
//public methods
public:
IawShaderComponent(char* strname = "Unnamed");
virtual ~IawShaderComponent();
HRESULT ActivateShaderComponent();
HRESULT SetStateBlock(DWORD dwSB);
HRESULT SetVertexShader(DWORD dwVS);
HRESULT SetPixelShader(DWORD dwPS);
HRESULT SetMatrix(IawMatrix mx, DWORD mxtype);
HRESULT SetName(char *strname);
inline DWORD GetComponentType () {return m_dwComponentType};
inline DWORD GetStateBlock () {return m_dwStateBlock};
inline DWORD GetVertexShader () {return m_dwVertexShader};
inline DWORD GetPixelShader () {return m_dwPixelShader};
inline IawMatrix GetMatrix() {return m_mxMat};
inline DWORD GetMatrixType() {return m_dwMatType};
HRESULT AddChild(IawShaderComponent *pComponent);
inline IawShaderComponent* GetChild() {return m_pNext;}
void TargetChanging();
void CheckProperties(CD3DWrapper *pD3DWrapper, bool &b_alpha);
HRESULT Activate();
//private methods & member vars
private:
char m_strShaderComponentName[255];
DWORD m_dwShaderComponentType;
DWORD m_dwStateBlock;
DWORD m_dwVertexShader;
DWORD m_dwPixelShader;
IawMatrix m_mxMat;
DWORD m_dwMatType;
bool m_bValidOnCurrentDevice;
// IawShaderComponent *m_pNext;
HRESULT CheckAgainstChildren(IawShaderComponent *pPotentialParent, IawShaderComponent *pPotentialChild);
};
*/
/**
* This class describes a shader element.
*/
class IawShaderElement
{
public:
/**
* Constructor.
* @param Id The Id for this element.
* @param name A name for this element.
*/
IawShaderElement(int Id, char* name = "Unnamed Element");
/** Destructor */
virtual ~IawShaderElement();
/** Set the element name */
HRESULT SetName(char* name);
//@{
/** Access method */
IawShaderElement* GetNext() {return mpNext;}
void SetNext(IawShaderElement* pTemp) {mpNext = pTemp;}
int GetId() {return mElementId;}
char* GetName() {return mElementName;}
void SetValid(bool valid) {mValid = valid;}
bool GetValid() {return mValid;}
HRESULT SetStateBlock(DWORD stateBlock, DWORD flags);
DWORD GetStateBlock() {return mStateBlock;}
//@}
/**
* Delete the state block for this element.
* @param pWrapper The wrapper for the device this element as a state block on
*/
HRESULT DeleteStateBlock(IawD3dWrapper* pWrapper);
/**
* Add a child to this element's hierarchy.
*/
HRESULT AddChild(IawShaderElement* pChildElement);
/** Flag this element as a state block */
static const int STATE_BLOCK;
/** Flag this element as a vertex shader */
static const int VERTEX_SHADER;
/** Flag this element as a pixel shader */
static const int PIXEL_SHADER;
/** Flag this element as a matrix */
static const int MATRIX;
private:
char mElementName[255];
int mElementId;
DWORD mStateBlock;
DWORD mFlags;
bool mValid;
IawShaderElement* mpNext;
HRESULT CheckAgainstChildren(IawShaderElement* pPotentialParent,
IawShaderElement* pPotentialChild);
};
/**
* This class encapsulates a component of a shader pass.
*/
class IawShaderComponent
{
public:
/**
* Constructor.
* @param Id The Id for this component.
* @param name A name for this component.
* @param flags Any flags (END_OF_PASS, NEGATING,etc...).
*/
IawShaderComponent(int Id, char* name = "Unnamed Component", DWORD flags = 0);
/** Destructor */
virtual ~IawShaderComponent();
/** Set the component name */
HRESULT SetName(char* name);
//@{
/** Access method */
IawShaderComponent* GetNext() {return mpNext;}
void SetNext(IawShaderComponent* pTemp) {mpNext = pTemp;}
int GetId() {return mComponentId;}
char* GetName() {return mComponentName;}
DWORD GetFlags() {return mFlags;}
IawShaderElement* GetElement() {return mpElement;}
void SetElement(IawShaderElement* pElement) {mpElement = pElement;}
//@}
/** Add a child to this component hierarchy */
HRESULT AddChild(IawShaderComponent* pChildComponent);
//void TargetChanging();
//void CheckProperties(CD3DWrapper *pD3DWrapper, bool &b_alpha);
//bool Validate();
//bool Activate();
/** Flags the end of a shader for a render pass */
static const int END_OF_PASS;
/** Component negating */
static const int NEGATING;
private:
char mComponentName[255];
int mComponentId;
// int mNumIds;
IawShaderElement* mpElement;
DWORD mFlags;
IawShaderComponent* mpNext;
//bool mValidOnCurrentDevice;
HRESULT CheckAgainstChildren(IawShaderComponent* pPotentialParent,
IawShaderComponent* pPotentialChild);
};
/**
* A shader implementation.
* An implementation may be made up of one or more render passes.
*
* Each implementation may also have a string of "exit components"
*
* Each render pass is comprised of one or more components, the final one of
* which is flagged as 'END_OF_PASS'.
*/
class IawShaderImplementation
{
public:
/**
* Constructor.
* @param Id An Id for the implementation.
* @param name A name for the implementation.
*/
IawShaderImplementation(int Id, char* name = "Unnamed");
/** Destructor */
virtual ~IawShaderImplementation();
/** Set the implementation name */
HRESULT SetName(char* name);
/**
* Create a component for this implementation
* @param pId The Id number that will be assigned to the component.
* @param name The component name.
* @param flags Any additional flags.
*/
HRESULT CreateComponent(int *pId, char* name = "Unnamed Shader Component", DWORD flags = 0);
//@{
/** Access method */
IawShaderImplementation* GetNext() {return mpNext;}
IawShaderComponent* GetFirstComponent() {return mpFirstComponent;}
IawShaderComponent* GetFirstNegatingComponent() {return mpFirstNegatingComponent;}
void SetNext(IawShaderImplementation* pTemp) {mpNext = pTemp;}
int GetId() {return mImplementationId;}
char* GetName() {return mImplementationName;}
IawShaderComponent* GetComponentPtr(int componentId);
//@}
/** Add a child to this implementation hierarchy */
HRESULT AddChild(IawShaderImplementation* pChildImplementation);
// void TargetChanging();
// void CheckProperties(CD3DWrapper *pD3DWrapper, bool &b_alpha);
// bool Validate();
//bool Activate();
// inline int GetNumPasses() {return mNumPasses};
private:
char mImplementationName[255];
int mImplementationId;
int mNumIds; //total number handed out
int mNumPasses;
int mNumComponents;
IawShaderComponent* mpFirstComponent;
IawShaderComponent* mpFirstNegatingComponent;
//IawShaderComponent *mpFirstStateResetComponent;
IawShaderImplementation* mpNext;
//bool mValidOnCurrentDevice;
HRESULT CheckAgainstChildren(IawShaderImplementation* pPotentialParent,
IawShaderImplementation* pPotentialChild);
};
/**
* This class encapsulates a shader.
*
* Each shader can have more than one implementation, and each implementation
* may be made up of one or more render passes.
*
* Each implementation may also have a string of "exit components"
*
* Each render pass is comprised of one or more components, the final one of
* which is flagged as 'END_OF_PASS'.
*
* @see IawShaderImplementation
* @see IawShaderComponent
* @see IawShaderElement
*/
class IawShader
{
public:
/**
* Constructor.
* @param Id The shader id number.
* @param name A name for the shader.
*/
IawShader(int Id, char* name = "Unnamed");
/** Destructor */
virtual ~IawShader();
/** Set the shader name */
HRESULT SetName(char* name);
/** Create an implementation for this shader */
HRESULT CreateImplementation(int* pId, char* name = "Unnamed Shader Implementation");
/**
* Delete a specified implementation of this shader.
* @param Id The Id number of the implementation to delete.
*/
HRESULT DeleteImplementation(int Id);
/**
* Create a component for this shader.
* @param implementationId The Id of the implementation this component will belong to.
* @param pId The Id number that will be assigned to the component.
* @param name A name for the component.
* @param flags Any additional flags for the component.
*/
HRESULT CreateComponent(int implementationId, int *pId, char* name = "Unnamed Shader Component", DWORD flags = 0);
//@{
/** Access method */
IawShader* GetNext() {return mpNext;}
IawShaderImplementation* GetFirstImplementation() {return mpFirstImplementation;}
IawShaderImplementation* GetActiveImplementation() {return mpActiveImplementation;}
void SetActiveImplementation(IawShaderImplementation* pTemp) {mpActiveImplementation = pTemp;}
void SetNext(IawShader* pTemp) {mpNext = pTemp;}
int GetId() {return mShaderId;}
char* GetName() {return mShaderName;}
int GetImplementationId(char* name);
IawShaderImplementation* GetImplementationPtr(int implementationId);
//@}
/** Add a child to this shader hierarchy */
HRESULT AddChild(IawShader* pChildShader);
// void CheckProperties(CD3DWrapper *pD3DWrapper, bool &b_alpha);
// bool Validate();
// bool Activate();
// inline int GetNumPasses() {return miNumPasses;}
private:
char mShaderName[255];
int mShaderId;
int mNumImplementations;
int mNumIds;
IawShaderImplementation* mpFirstImplementation;
IawShaderImplementation* mpActiveImplementation;
IawShader* mpNext;
HRESULT CheckAgainstChildren(IawShader* pPotentialParent,
IawShader* pPotentialChild);
};
#endif // IawShader_h
| [
"dwilliamson_coder@hotmail.com"
] | dwilliamson_coder@hotmail.com |
f8b4945c4576b319eedce33e505242c75b2e8026 | 67d0cd3da850aeee51241e39b2c86484a1382bec | /Scintilla/src/EditView.cxx | 95fd75494a150c5982e3d470b159bb8d3d1e9d2d | [
"MIT"
] | permissive | tobeypeters/Scintilla | 4f6c4d99a2bbf8e254c70fb8b4c30c82027875e5 | 3f1ccba00b5817a5ba548288822a59b0a0f73d92 | refs/heads/master | 2020-05-20T18:32:52.747016 | 2019-05-09T02:41:45 | 2019-05-09T02:41:45 | 185,708,169 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 109,145 | cxx | // Scintilla source code edit control
/** @file EditView.cxx
** Defines the appearance of the main text area of the editor window.
**/
// Copyright 1998-2014 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <cstddef>
#include <cstdlib>
#include <cassert>
#include <cstring>
#include <cctype>
#include <cstdio>
#include <cmath>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
#include <map>
#include <forward_list>
#include <algorithm>
#include <iterator>
#include <memory>
#include <chrono>
#include "Platform.h"
#include "ILoader.h"
#include "ILexer.h"
#include "Scintilla.h"
#include "CharacterSet.h"
#include "Position.h"
#include "IntegerRectangle.h"
#include "UniqueString.h"
#include "SplitVector.h"
#include "Partitioning.h"
#include "RunStyles.h"
#include "ContractionState.h"
#include "CellBuffer.h"
#include "PerLine.h"
#include "KeyMap.h"
#include "Indicator.h"
#include "LineMarker.h"
#include "Style.h"
#include "ViewStyle.h"
#include "CharClassify.h"
#include "Decoration.h"
#include "CaseFolder.h"
#include "Document.h"
#include "UniConversion.h"
#include "Selection.h"
#include "PositionCache.h"
#include "EditModel.h"
#include "MarginView.h"
#include "EditView.h"
#include "ElapsedPeriod.h"
using namespace Scintilla;
static constexpr bool IsControlCharacter(int ch) noexcept {
// iscntrl returns true for lots of chars > 127 which are displayable
return ch >= 0 && ch < ' ';
}
PrintParameters::PrintParameters() {
magnification = 0;
colourMode = SC_PRINT_NORMAL;
wrapState = eWrapWord;
}
namespace Scintilla {
bool ValidStyledText(const ViewStyle &vs, size_t styleOffset, const StyledText &st) {
if (st.multipleStyles) {
for (size_t iStyle = 0; iStyle<st.length; iStyle++) {
if (!vs.ValidStyle(styleOffset + st.styles[iStyle]))
return false;
}
} else {
if (!vs.ValidStyle(styleOffset + st.style))
return false;
}
return true;
}
static int WidthStyledText(Surface *surface, const ViewStyle &vs, int styleOffset,
const char *text, const unsigned char *styles, size_t len) {
int width = 0;
size_t start = 0;
while (start < len) {
const unsigned char style = styles[start];
size_t endSegment = start;
while ((endSegment + 1 < len) && (styles[endSegment + 1] == style))
endSegment++;
FontAlias fontText = vs.styles[style + styleOffset].font;
const std::string_view sv(text + start, endSegment - start + 1);
width += static_cast<int>(surface->WidthText(fontText, sv));
start = endSegment + 1;
}
return width;
}
int WidestLineWidth(Surface *surface, const ViewStyle &vs, int styleOffset, const StyledText &st) {
int widthMax = 0;
size_t start = 0;
while (start < st.length) {
const size_t lenLine = st.LineLength(start);
int widthSubLine;
if (st.multipleStyles) {
widthSubLine = WidthStyledText(surface, vs, styleOffset, st.text + start, st.styles + start, lenLine);
} else {
FontAlias fontText = vs.styles[styleOffset + st.style].font;
const std::string_view text(st.text + start, lenLine);
widthSubLine = static_cast<int>(surface->WidthText(fontText, text));
}
if (widthSubLine > widthMax)
widthMax = widthSubLine;
start += lenLine + 1;
}
return widthMax;
}
void DrawTextNoClipPhase(Surface *surface, PRectangle rc, const Style &style, XYPOSITION ybase,
std::string_view text, DrawPhase phase) {
FontAlias fontText = style.font;
if (phase & drawBack) {
if (phase & drawText) {
// Drawing both
surface->DrawTextNoClip(rc, fontText, ybase, text,
style.fore, style.back);
} else {
surface->FillRectangle(rc, style.back);
}
} else if (phase & drawText) {
surface->DrawTextTransparent(rc, fontText, ybase, text, style.fore);
}
}
void DrawStyledText(Surface *surface, const ViewStyle &vs, int styleOffset, PRectangle rcText,
const StyledText &st, size_t start, size_t length, DrawPhase phase) {
if (st.multipleStyles) {
int x = static_cast<int>(rcText.left);
size_t i = 0;
while (i < length) {
size_t end = i;
size_t style = st.styles[i + start];
while (end < length - 1 && st.styles[start + end + 1] == style)
end++;
style += styleOffset;
FontAlias fontText = vs.styles[style].font;
const std::string_view text(st.text + start + i, end - i + 1);
const int width = static_cast<int>(surface->WidthText(fontText, text));
PRectangle rcSegment = rcText;
rcSegment.left = static_cast<XYPOSITION>(x);
rcSegment.right = static_cast<XYPOSITION>(x + width + 1);
DrawTextNoClipPhase(surface, rcSegment, vs.styles[style],
rcText.top + vs.maxAscent, text, phase);
x += width;
i = end + 1;
}
} else {
const size_t style = st.style + styleOffset;
DrawTextNoClipPhase(surface, rcText, vs.styles[style],
rcText.top + vs.maxAscent,
std::string_view(st.text + start, length), phase);
}
}
}
const XYPOSITION epsilon = 0.0001f; // A small nudge to avoid floating point precision issues
EditView::EditView() {
tabWidthMinimumPixels = 2; // needed for calculating tab stops for fractional proportional fonts
hideSelection = false;
drawOverstrikeCaret = true;
bufferedDraw = true;
phasesDraw = phasesTwo;
lineWidthMaxSeen = 0;
additionalCaretsBlink = true;
additionalCaretsVisible = true;
imeCaretBlockOverride = false;
llc.SetLevel(LineLayoutCache::llcCaret);
posCache.SetSize(0x400);
tabArrowHeight = 4;
customDrawTabArrow = nullptr;
customDrawWrapMarker = nullptr;
}
EditView::~EditView() {
}
bool EditView::SetTwoPhaseDraw(bool twoPhaseDraw) {
const PhasesDraw phasesDrawNew = twoPhaseDraw ? phasesTwo : phasesOne;
const bool redraw = phasesDraw != phasesDrawNew;
phasesDraw = phasesDrawNew;
return redraw;
}
bool EditView::SetPhasesDraw(int phases) {
const PhasesDraw phasesDrawNew = static_cast<PhasesDraw>(phases);
const bool redraw = phasesDraw != phasesDrawNew;
phasesDraw = phasesDrawNew;
return redraw;
}
bool EditView::LinesOverlap() const {
return phasesDraw == phasesMultiple;
}
void EditView::ClearAllTabstops() {
ldTabstops.reset();
}
XYPOSITION EditView::NextTabstopPos(Sci::Line line, XYPOSITION x, XYPOSITION tabWidth) const {
const int next = GetNextTabstop(line, static_cast<int>(x + tabWidthMinimumPixels));
if (next > 0)
return static_cast<XYPOSITION>(next);
return (static_cast<int>((x + tabWidthMinimumPixels) / tabWidth) + 1) * tabWidth;
}
bool EditView::ClearTabstops(Sci::Line line) {
return ldTabstops && ldTabstops->ClearTabstops(line);
}
bool EditView::AddTabstop(Sci::Line line, int x) {
if (!ldTabstops) {
ldTabstops = std::make_unique<LineTabstops>();
}
return ldTabstops && ldTabstops->AddTabstop(line, x);
}
int EditView::GetNextTabstop(Sci::Line line, int x) const {
if (ldTabstops) {
return ldTabstops->GetNextTabstop(line, x);
} else {
return 0;
}
}
void EditView::LinesAddedOrRemoved(Sci::Line lineOfPos, Sci::Line linesAdded) {
if (ldTabstops) {
if (linesAdded > 0) {
for (Sci::Line line = lineOfPos; line < lineOfPos + linesAdded; line++) {
ldTabstops->InsertLine(line);
}
} else {
for (Sci::Line line = (lineOfPos + -linesAdded) - 1; line >= lineOfPos; line--) {
ldTabstops->RemoveLine(line);
}
}
}
}
void EditView::DropGraphics(bool freeObjects) {
if (freeObjects) {
pixmapLine.reset();
pixmapIndentGuide.reset();
pixmapIndentGuideHighlight.reset();
} else {
if (pixmapLine)
pixmapLine->Release();
if (pixmapIndentGuide)
pixmapIndentGuide->Release();
if (pixmapIndentGuideHighlight)
pixmapIndentGuideHighlight->Release();
}
}
void EditView::AllocateGraphics(const ViewStyle &vsDraw) {
if (!pixmapLine)
pixmapLine.reset(Surface::Allocate(vsDraw.technology));
if (!pixmapIndentGuide)
pixmapIndentGuide.reset(Surface::Allocate(vsDraw.technology));
if (!pixmapIndentGuideHighlight)
pixmapIndentGuideHighlight.reset(Surface::Allocate(vsDraw.technology));
}
static const char *ControlCharacterString(unsigned char ch) {
const char * const reps[] = {
"NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL",
"BS", "HT", "LF", "VT", "FF", "CR", "SO", "SI",
"DLE", "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB",
"CAN", "EM", "SUB", "ESC", "FS", "GS", "RS", "US"
};
if (ch < std::size(reps)) {
return reps[ch];
} else {
return "BAD";
}
}
static void DrawTabArrow(Surface *surface, PRectangle rcTab, int ymid, const ViewStyle &vsDraw) {
const IntegerRectangle ircTab(rcTab);
if ((rcTab.left + 2) < (rcTab.right - 1))
surface->MoveTo(ircTab.left + 2, ymid);
else
surface->MoveTo(ircTab.right - 1, ymid);
surface->LineTo(ircTab.right - 1, ymid);
// Draw the arrow head if needed
if (vsDraw.tabDrawMode == tdLongArrow) {
int ydiff = (ircTab.bottom - ircTab.top) / 2;
int xhead = ircTab.right - 1 - ydiff;
if (xhead <= rcTab.left) {
ydiff -= ircTab.left - xhead - 1;
xhead = ircTab.left - 1;
}
surface->LineTo(xhead, ymid - ydiff);
surface->MoveTo(ircTab.right - 1, ymid);
surface->LineTo(xhead, ymid + ydiff);
}
}
void EditView::RefreshPixMaps(Surface *surfaceWindow, WindowID wid, const ViewStyle &vsDraw) {
if (!pixmapIndentGuide->Initialised()) {
// 1 extra pixel in height so can handle odd/even positions and so produce a continuous line
pixmapIndentGuide->InitPixMap(1, vsDraw.lineHeight + 1, surfaceWindow, wid);
pixmapIndentGuideHighlight->InitPixMap(1, vsDraw.lineHeight + 1, surfaceWindow, wid);
const PRectangle rcIG = PRectangle::FromInts(0, 0, 1, vsDraw.lineHeight);
pixmapIndentGuide->FillRectangle(rcIG, vsDraw.styles[STYLE_INDENTGUIDE].back);
pixmapIndentGuide->PenColour(vsDraw.styles[STYLE_INDENTGUIDE].fore);
pixmapIndentGuideHighlight->FillRectangle(rcIG, vsDraw.styles[STYLE_BRACELIGHT].back);
pixmapIndentGuideHighlight->PenColour(vsDraw.styles[STYLE_BRACELIGHT].fore);
for (int stripe = 1; stripe < vsDraw.lineHeight + 1; stripe += 2) {
const PRectangle rcPixel = PRectangle::FromInts(0, stripe, 1, stripe + 1);
pixmapIndentGuide->FillRectangle(rcPixel, vsDraw.styles[STYLE_INDENTGUIDE].fore);
pixmapIndentGuideHighlight->FillRectangle(rcPixel, vsDraw.styles[STYLE_BRACELIGHT].fore);
}
}
}
LineLayout *EditView::RetrieveLineLayout(Sci::Line lineNumber, const EditModel &model) {
const Sci::Position posLineStart = model.pdoc->LineStart(lineNumber);
const Sci::Position posLineEnd = model.pdoc->LineStart(lineNumber + 1);
PLATFORM_ASSERT(posLineEnd >= posLineStart);
const Sci::Line lineCaret = model.pdoc->SciLineFromPosition(model.sel.MainCaret());
return llc.Retrieve(lineNumber, lineCaret,
static_cast<int>(posLineEnd - posLineStart), model.pdoc->GetStyleClock(),
model.LinesOnScreen() + 1, model.pdoc->LinesTotal());
}
/**
* Fill in the LineLayout data for the given line.
* Copy the given @a line and its styles from the document into local arrays.
* Also determine the x position at which each character starts.
*/
void EditView::LayoutLine(const EditModel &model, Sci::Line line, Surface *surface, const ViewStyle &vstyle, LineLayout *ll, int width) {
if (!ll)
return;
PLATFORM_ASSERT(line < model.pdoc->LinesTotal());
PLATFORM_ASSERT(ll->chars != NULL);
const Sci::Position posLineStart = model.pdoc->LineStart(line);
Sci::Position posLineEnd = model.pdoc->LineStart(line + 1);
// If the line is very long, limit the treatment to a length that should fit in the viewport
if (posLineEnd >(posLineStart + ll->maxLineLength)) {
posLineEnd = posLineStart + ll->maxLineLength;
}
if (ll->validity == LineLayout::llCheckTextAndStyle) {
Sci::Position lineLength = posLineEnd - posLineStart;
if (!vstyle.viewEOL) {
lineLength = model.pdoc->LineEnd(line) - posLineStart;
}
if (lineLength == ll->numCharsInLine) {
// See if chars, styles, indicators, are all the same
bool allSame = true;
// Check base line layout
int styleByte = 0;
int numCharsInLine = 0;
while (numCharsInLine < lineLength) {
const Sci::Position charInDoc = numCharsInLine + posLineStart;
const char chDoc = model.pdoc->CharAt(charInDoc);
styleByte = model.pdoc->StyleIndexAt(charInDoc);
allSame = allSame &&
(ll->styles[numCharsInLine] == styleByte);
if (vstyle.styles[ll->styles[numCharsInLine]].caseForce == Style::caseMixed)
allSame = allSame &&
(ll->chars[numCharsInLine] == chDoc);
else if (vstyle.styles[ll->styles[numCharsInLine]].caseForce == Style::caseLower)
allSame = allSame &&
(ll->chars[numCharsInLine] == MakeLowerCase(chDoc));
else if (vstyle.styles[ll->styles[numCharsInLine]].caseForce == Style::caseUpper)
allSame = allSame &&
(ll->chars[numCharsInLine] == MakeUpperCase(chDoc));
else { // Style::caseCamel
if ((model.pdoc->IsASCIIWordByte(ll->chars[numCharsInLine])) &&
((numCharsInLine == 0) || (!model.pdoc->IsASCIIWordByte(ll->chars[numCharsInLine - 1])))) {
allSame = allSame && (ll->chars[numCharsInLine] == MakeUpperCase(chDoc));
} else {
allSame = allSame && (ll->chars[numCharsInLine] == MakeLowerCase(chDoc));
}
}
numCharsInLine++;
}
allSame = allSame && (ll->styles[numCharsInLine] == styleByte); // For eolFilled
if (allSame) {
ll->validity = LineLayout::llPositions;
} else {
ll->validity = LineLayout::llInvalid;
}
} else {
ll->validity = LineLayout::llInvalid;
}
}
if (ll->validity == LineLayout::llInvalid) {
ll->widthLine = LineLayout::wrapWidthInfinite;
ll->lines = 1;
if (vstyle.edgeState == EDGE_BACKGROUND) {
Sci::Position edgePosition = model.pdoc->FindColumn(line, vstyle.theEdge.column);
if (edgePosition >= posLineStart) {
edgePosition -= posLineStart;
}
ll->edgeColumn = static_cast<int>(edgePosition);
} else {
ll->edgeColumn = -1;
}
// Fill base line layout
const int lineLength = static_cast<int>(posLineEnd - posLineStart);
model.pdoc->GetCharRange(ll->chars.get(), posLineStart, lineLength);
model.pdoc->GetStyleRange(ll->styles.get(), posLineStart, lineLength);
const int numCharsBeforeEOL = static_cast<int>(model.pdoc->LineEnd(line) - posLineStart);
const int numCharsInLine = (vstyle.viewEOL) ? lineLength : numCharsBeforeEOL;
for (Sci::Position styleInLine = 0; styleInLine < numCharsInLine; styleInLine++) {
const unsigned char styleByte = ll->styles[styleInLine];
ll->styles[styleInLine] = styleByte;
}
const unsigned char styleByteLast = (lineLength > 0) ? ll->styles[lineLength - 1] : 0;
if (vstyle.someStylesForceCase) {
for (int charInLine = 0; charInLine<lineLength; charInLine++) {
const char chDoc = ll->chars[charInLine];
if (vstyle.styles[ll->styles[charInLine]].caseForce == Style::caseUpper)
ll->chars[charInLine] = MakeUpperCase(chDoc);
else if (vstyle.styles[ll->styles[charInLine]].caseForce == Style::caseLower)
ll->chars[charInLine] = MakeLowerCase(chDoc);
else if (vstyle.styles[ll->styles[charInLine]].caseForce == Style::caseCamel) {
if ((model.pdoc->IsASCIIWordByte(ll->chars[charInLine])) &&
((charInLine == 0) || (!model.pdoc->IsASCIIWordByte(ll->chars[charInLine - 1])))) {
ll->chars[charInLine] = MakeUpperCase(chDoc);
} else {
ll->chars[charInLine] = MakeLowerCase(chDoc);
}
}
}
}
ll->xHighlightGuide = 0;
// Extra element at the end of the line to hold end x position and act as
ll->chars[numCharsInLine] = 0; // Also triggers processing in the loops as this is a control character
ll->styles[numCharsInLine] = styleByteLast; // For eolFilled
// Layout the line, determining the position of each character,
// with an extra element at the end for the end of the line.
ll->positions[0] = 0;
bool lastSegItalics = false;
BreakFinder bfLayout(ll, nullptr, Range(0, numCharsInLine), posLineStart, 0, false, model.pdoc, &model.reprs, nullptr);
while (bfLayout.More()) {
const TextSegment ts = bfLayout.Next();
std::fill(&ll->positions[ts.start + 1], &ll->positions[ts.end() + 1], 0.0f);
if (vstyle.styles[ll->styles[ts.start]].visible) {
if (ts.representation) {
XYPOSITION representationWidth = vstyle.controlCharWidth;
if (ll->chars[ts.start] == '\t') {
// Tab is a special case of representation, taking a variable amount of space
const XYPOSITION x = ll->positions[ts.start];
representationWidth = NextTabstopPos(line, x, vstyle.tabWidth) - ll->positions[ts.start];
} else {
if (representationWidth <= 0.0) {
XYPOSITION positionsRepr[256]; // Should expand when needed
posCache.MeasureWidths(surface, vstyle, STYLE_CONTROLCHAR, ts.representation->stringRep.c_str(),
static_cast<unsigned int>(ts.representation->stringRep.length()), positionsRepr, model.pdoc);
representationWidth = positionsRepr[ts.representation->stringRep.length() - 1] + vstyle.ctrlCharPadding;
}
}
for (int ii = 0; ii < ts.length; ii++)
ll->positions[ts.start + 1 + ii] = representationWidth;
} else {
if ((ts.length == 1) && (' ' == ll->chars[ts.start])) {
// Over half the segments are single characters and of these about half are space characters.
ll->positions[ts.start + 1] = vstyle.styles[ll->styles[ts.start]].spaceWidth;
} else {
posCache.MeasureWidths(surface, vstyle, ll->styles[ts.start], &ll->chars[ts.start],
ts.length, &ll->positions[ts.start + 1], model.pdoc);
}
}
lastSegItalics = (!ts.representation) && ((ll->chars[ts.end() - 1] != ' ') && vstyle.styles[ll->styles[ts.start]].italic);
}
for (Sci::Position posToIncrease = ts.start + 1; posToIncrease <= ts.end(); posToIncrease++) {
ll->positions[posToIncrease] += ll->positions[ts.start];
}
}
// Small hack to make lines that end with italics not cut off the edge of the last character
if (lastSegItalics) {
ll->positions[numCharsInLine] += vstyle.lastSegItalicsOffset;
}
ll->numCharsInLine = numCharsInLine;
ll->numCharsBeforeEOL = numCharsBeforeEOL;
ll->validity = LineLayout::llPositions;
}
// Hard to cope when too narrow, so just assume there is space
if (width < 20) {
width = 20;
}
if ((ll->validity == LineLayout::llPositions) || (ll->widthLine != width)) {
ll->widthLine = width;
if (width == LineLayout::wrapWidthInfinite) {
ll->lines = 1;
} else if (width > ll->positions[ll->numCharsInLine]) {
// Simple common case where line does not need wrapping.
ll->lines = 1;
} else {
if (vstyle.wrapVisualFlags & SC_WRAPVISUALFLAG_END) {
width -= static_cast<int>(vstyle.aveCharWidth); // take into account the space for end wrap mark
}
XYPOSITION wrapAddIndent = 0; // This will be added to initial indent of line
switch (vstyle.wrapIndentMode) {
case SC_WRAPINDENT_FIXED:
wrapAddIndent = vstyle.wrapVisualStartIndent * vstyle.aveCharWidth;
break;
case SC_WRAPINDENT_INDENT:
wrapAddIndent = model.pdoc->IndentSize() * vstyle.spaceWidth;
break;
case SC_WRAPINDENT_DEEPINDENT:
wrapAddIndent = model.pdoc->IndentSize() * 2 * vstyle.spaceWidth;
break;
}
ll->wrapIndent = wrapAddIndent;
if (vstyle.wrapIndentMode != SC_WRAPINDENT_FIXED) {
for (int i = 0; i < ll->numCharsInLine; i++) {
if (!IsSpaceOrTab(ll->chars[i])) {
ll->wrapIndent += ll->positions[i]; // Add line indent
break;
}
}
}
// Check for text width minimum
if (ll->wrapIndent > width - static_cast<int>(vstyle.aveCharWidth) * 15)
ll->wrapIndent = wrapAddIndent;
// Check for wrapIndent minimum
if ((vstyle.wrapVisualFlags & SC_WRAPVISUALFLAG_START) && (ll->wrapIndent < vstyle.aveCharWidth))
ll->wrapIndent = vstyle.aveCharWidth; // Indent to show start visual
ll->lines = 0;
// Calculate line start positions based upon width.
Sci::Position lastGoodBreak = 0;
Sci::Position lastLineStart = 0;
XYACCUMULATOR startOffset = 0;
Sci::Position p = 0;
while (p < ll->numCharsInLine) {
if ((ll->positions[p + 1] - startOffset) >= width) {
if (lastGoodBreak == lastLineStart) {
// Try moving to start of last character
if (p > 0) {
lastGoodBreak = model.pdoc->MovePositionOutsideChar(p + posLineStart, -1)
- posLineStart;
}
if (lastGoodBreak == lastLineStart) {
// Ensure at least one character on line.
lastGoodBreak = model.pdoc->MovePositionOutsideChar(lastGoodBreak + posLineStart + 1, 1)
- posLineStart;
}
}
lastLineStart = lastGoodBreak;
ll->lines++;
ll->SetLineStart(ll->lines, static_cast<int>(lastGoodBreak));
startOffset = ll->positions[lastGoodBreak];
// take into account the space for start wrap mark and indent
startOffset -= ll->wrapIndent;
p = lastGoodBreak + 1;
continue;
}
if (p > 0) {
if (vstyle.wrapState == eWrapChar) {
lastGoodBreak = model.pdoc->MovePositionOutsideChar(p + posLineStart, -1)
- posLineStart;
p = model.pdoc->MovePositionOutsideChar(p + 1 + posLineStart, 1) - posLineStart;
continue;
} else if ((vstyle.wrapState == eWrapWord) && (ll->styles[p] != ll->styles[p - 1])) {
lastGoodBreak = p;
} else if (IsSpaceOrTab(ll->chars[p - 1]) && !IsSpaceOrTab(ll->chars[p])) {
lastGoodBreak = p;
}
}
p++;
}
ll->lines++;
}
ll->validity = LineLayout::llLines;
}
}
// Fill the LineLayout bidirectional data fields according to each char style
void EditView::UpdateBidiData(const EditModel &model, const ViewStyle &vstyle, LineLayout *ll) {
if (model.BidirectionalEnabled()) {
ll->EnsureBidiData();
for (int stylesInLine = 0; stylesInLine < ll->numCharsInLine; stylesInLine++) {
ll->bidiData->stylesFonts[stylesInLine].MakeAlias(vstyle.styles[ll->styles[stylesInLine]].font);
}
ll->bidiData->stylesFonts[ll->numCharsInLine].ClearFont();
for (int charsInLine = 0; charsInLine < ll->numCharsInLine; charsInLine++) {
const int charWidth = UTF8DrawBytes(reinterpret_cast<unsigned char *>(&ll->chars[charsInLine]), ll->numCharsInLine - charsInLine);
const Representation *repr = model.reprs.RepresentationFromCharacter(&ll->chars[charsInLine], charWidth);
ll->bidiData->widthReprs[charsInLine] = 0.0f;
if (repr && ll->chars[charsInLine] != '\t') {
ll->bidiData->widthReprs[charsInLine] = ll->positions[charsInLine + charWidth] - ll->positions[charsInLine];
}
if (charWidth > 1) {
for (int c = 1; c < charWidth; c++) {
charsInLine++;
ll->bidiData->widthReprs[charsInLine] = 0.0f;
}
}
}
ll->bidiData->widthReprs[ll->numCharsInLine] = 0.0f;
} else {
ll->bidiData.reset();
}
}
Point EditView::LocationFromPosition(Surface *surface, const EditModel &model, SelectionPosition pos, Sci::Line topLine,
const ViewStyle &vs, PointEnd pe, const PRectangle rcClient) {
Point pt;
if (pos.Position() == INVALID_POSITION)
return pt;
Sci::Line lineDoc = model.pdoc->SciLineFromPosition(pos.Position());
Sci::Position posLineStart = model.pdoc->LineStart(lineDoc);
if ((pe & peLineEnd) && (lineDoc > 0) && (pos.Position() == posLineStart)) {
// Want point at end of first line
lineDoc--;
posLineStart = model.pdoc->LineStart(lineDoc);
}
const Sci::Line lineVisible = model.pcs->DisplayFromDoc(lineDoc);
AutoLineLayout ll(llc, RetrieveLineLayout(lineDoc, model));
if (surface && ll) {
LayoutLine(model, lineDoc, surface, vs, ll, model.wrapWidth);
const int posInLine = static_cast<int>(pos.Position() - posLineStart);
pt = ll->PointFromPosition(posInLine, vs.lineHeight, pe);
pt.x += vs.textStart - model.xOffset;
if (model.BidirectionalEnabled()) {
// Fill the line bidi data
UpdateBidiData(model, vs, ll);
// Find subLine
const int subLine = ll->SubLineFromPosition(posInLine, pe);
const int caretPosition = posInLine - ll->LineStart(subLine);
// Get the point from current position
const ScreenLine screenLine(ll, subLine, vs, rcClient.right, tabWidthMinimumPixels);
std::unique_ptr<IScreenLineLayout> slLayout = surface->Layout(&screenLine);
pt.x = slLayout->XFromPosition(caretPosition);
pt.x += vs.textStart - model.xOffset;
pt.y = 0;
if (posInLine >= ll->LineStart(subLine)) {
pt.y = static_cast<XYPOSITION>(subLine*vs.lineHeight);
}
}
pt.y += (lineVisible - topLine) * vs.lineHeight;
}
pt.x += pos.VirtualSpace() * vs.styles[ll->EndLineStyle()].spaceWidth;
return pt;
}
Range EditView::RangeDisplayLine(Surface *surface, const EditModel &model, Sci::Line lineVisible, const ViewStyle &vs) {
Range rangeSubLine = Range(0, 0);
if (lineVisible < 0) {
return rangeSubLine;
}
const Sci::Line lineDoc = model.pcs->DocFromDisplay(lineVisible);
const Sci::Position positionLineStart = model.pdoc->LineStart(lineDoc);
AutoLineLayout ll(llc, RetrieveLineLayout(lineDoc, model));
if (surface && ll) {
LayoutLine(model, lineDoc, surface, vs, ll, model.wrapWidth);
const Sci::Line lineStartSet = model.pcs->DisplayFromDoc(lineDoc);
const int subLine = static_cast<int>(lineVisible - lineStartSet);
if (subLine < ll->lines) {
rangeSubLine = ll->SubLineRange(subLine, LineLayout::Scope::visibleOnly);
if (subLine == ll->lines-1) {
rangeSubLine.end = model.pdoc->LineStart(lineDoc + 1) -
positionLineStart;
}
}
}
rangeSubLine.start += positionLineStart;
rangeSubLine.end += positionLineStart;
return rangeSubLine;
}
SelectionPosition EditView::SPositionFromLocation(Surface *surface, const EditModel &model, PointDocument pt, bool canReturnInvalid,
bool charPosition, bool virtualSpace, const ViewStyle &vs, const PRectangle rcClient) {
pt.x = pt.x - vs.textStart;
Sci::Line visibleLine = static_cast<int>(floor(pt.y / vs.lineHeight));
if (!canReturnInvalid && (visibleLine < 0))
visibleLine = 0;
const Sci::Line lineDoc = model.pcs->DocFromDisplay(visibleLine);
if (canReturnInvalid && (lineDoc < 0))
return SelectionPosition(INVALID_POSITION);
if (lineDoc >= model.pdoc->LinesTotal())
return SelectionPosition(canReturnInvalid ? INVALID_POSITION :
model.pdoc->Length());
const Sci::Position posLineStart = model.pdoc->LineStart(lineDoc);
AutoLineLayout ll(llc, RetrieveLineLayout(lineDoc, model));
if (surface && ll) {
LayoutLine(model, lineDoc, surface, vs, ll, model.wrapWidth);
const Sci::Line lineStartSet = model.pcs->DisplayFromDoc(lineDoc);
const int subLine = static_cast<int>(visibleLine - lineStartSet);
if (subLine < ll->lines) {
const Range rangeSubLine = ll->SubLineRange(subLine, LineLayout::Scope::visibleOnly);
const XYPOSITION subLineStart = ll->positions[rangeSubLine.start];
if (subLine > 0) // Wrapped
pt.x -= ll->wrapIndent;
Sci::Position positionInLine = 0;
if (model.BidirectionalEnabled()) {
// Fill the line bidi data
UpdateBidiData(model, vs, ll);
const ScreenLine screenLine(ll, subLine, vs, rcClient.right, tabWidthMinimumPixels);
std::unique_ptr<IScreenLineLayout> slLayout = surface->Layout(&screenLine);
positionInLine = slLayout->PositionFromX(static_cast<XYPOSITION>(pt.x), charPosition) +
rangeSubLine.start;
} else {
positionInLine = ll->FindPositionFromX(static_cast<XYPOSITION>(pt.x + subLineStart),
rangeSubLine, charPosition);
}
if (positionInLine < rangeSubLine.end) {
return SelectionPosition(model.pdoc->MovePositionOutsideChar(positionInLine + posLineStart, 1));
}
if (virtualSpace) {
const XYPOSITION spaceWidth = vs.styles[ll->EndLineStyle()].spaceWidth;
const int spaceOffset = static_cast<int>(
(pt.x + subLineStart - ll->positions[rangeSubLine.end] + spaceWidth / 2) / spaceWidth);
return SelectionPosition(rangeSubLine.end + posLineStart, spaceOffset);
} else if (canReturnInvalid) {
if (pt.x < (ll->positions[rangeSubLine.end] - subLineStart)) {
return SelectionPosition(model.pdoc->MovePositionOutsideChar(rangeSubLine.end + posLineStart, 1));
}
} else {
return SelectionPosition(rangeSubLine.end + posLineStart);
}
}
if (!canReturnInvalid)
return SelectionPosition(ll->numCharsInLine + posLineStart);
}
return SelectionPosition(canReturnInvalid ? INVALID_POSITION : posLineStart);
}
/**
* Find the document position corresponding to an x coordinate on a particular document line.
* Ensure is between whole characters when document is in multi-byte or UTF-8 mode.
* This method is used for rectangular selections and does not work on wrapped lines.
*/
SelectionPosition EditView::SPositionFromLineX(Surface *surface, const EditModel &model, Sci::Line lineDoc, int x, const ViewStyle &vs) {
AutoLineLayout ll(llc, RetrieveLineLayout(lineDoc, model));
if (surface && ll) {
const Sci::Position posLineStart = model.pdoc->LineStart(lineDoc);
LayoutLine(model, lineDoc, surface, vs, ll, model.wrapWidth);
const Range rangeSubLine = ll->SubLineRange(0, LineLayout::Scope::visibleOnly);
const XYPOSITION subLineStart = ll->positions[rangeSubLine.start];
const Sci::Position positionInLine = ll->FindPositionFromX(x + subLineStart, rangeSubLine, false);
if (positionInLine < rangeSubLine.end) {
return SelectionPosition(model.pdoc->MovePositionOutsideChar(positionInLine + posLineStart, 1));
}
const XYPOSITION spaceWidth = vs.styles[ll->EndLineStyle()].spaceWidth;
const int spaceOffset = static_cast<int>(
(x + subLineStart - ll->positions[rangeSubLine.end] + spaceWidth / 2) / spaceWidth);
return SelectionPosition(rangeSubLine.end + posLineStart, spaceOffset);
}
return SelectionPosition(0);
}
Sci::Line EditView::DisplayFromPosition(Surface *surface, const EditModel &model, Sci::Position pos, const ViewStyle &vs) {
const Sci::Line lineDoc = model.pdoc->SciLineFromPosition(pos);
Sci::Line lineDisplay = model.pcs->DisplayFromDoc(lineDoc);
AutoLineLayout ll(llc, RetrieveLineLayout(lineDoc, model));
if (surface && ll) {
LayoutLine(model, lineDoc, surface, vs, ll, model.wrapWidth);
const Sci::Position posLineStart = model.pdoc->LineStart(lineDoc);
const Sci::Position posInLine = pos - posLineStart;
lineDisplay--; // To make up for first increment ahead.
for (int subLine = 0; subLine < ll->lines; subLine++) {
if (posInLine >= ll->LineStart(subLine)) {
lineDisplay++;
}
}
}
return lineDisplay;
}
Sci::Position EditView::StartEndDisplayLine(Surface *surface, const EditModel &model, Sci::Position pos, bool start, const ViewStyle &vs) {
const Sci::Line line = model.pdoc->SciLineFromPosition(pos);
AutoLineLayout ll(llc, RetrieveLineLayout(line, model));
Sci::Position posRet = INVALID_POSITION;
if (surface && ll) {
const Sci::Position posLineStart = model.pdoc->LineStart(line);
LayoutLine(model, line, surface, vs, ll, model.wrapWidth);
const Sci::Position posInLine = pos - posLineStart;
if (posInLine <= ll->maxLineLength) {
for (int subLine = 0; subLine < ll->lines; subLine++) {
if ((posInLine >= ll->LineStart(subLine)) &&
(posInLine <= ll->LineStart(subLine + 1)) &&
(posInLine <= ll->numCharsBeforeEOL)) {
if (start) {
posRet = ll->LineStart(subLine) + posLineStart;
} else {
if (subLine == ll->lines - 1)
posRet = ll->numCharsBeforeEOL + posLineStart;
else
posRet = ll->LineStart(subLine + 1) + posLineStart - 1;
}
}
}
}
}
return posRet;
}
static ColourDesired SelectionBackground(const ViewStyle &vsDraw, bool main, bool primarySelection) {
return main ?
(primarySelection ? vsDraw.selColours.back : vsDraw.selBackground2) :
vsDraw.selAdditionalBackground;
}
static ColourDesired TextBackground(const EditModel &model, const ViewStyle &vsDraw, const LineLayout *ll,
ColourOptional background, int inSelection, bool inHotspot, int styleMain, Sci::Position i) {
if (inSelection == 1) {
if (vsDraw.selColours.back.isSet && (vsDraw.selAlpha == SC_ALPHA_NOALPHA)) {
return SelectionBackground(vsDraw, true, model.primarySelection);
}
} else if (inSelection == 2) {
if (vsDraw.selColours.back.isSet && (vsDraw.selAdditionalAlpha == SC_ALPHA_NOALPHA)) {
return SelectionBackground(vsDraw, false, model.primarySelection);
}
} else {
if ((vsDraw.edgeState == EDGE_BACKGROUND) &&
(i >= ll->edgeColumn) &&
(i < ll->numCharsBeforeEOL))
return vsDraw.theEdge.colour;
if (inHotspot && vsDraw.hotspotColours.back.isSet)
return vsDraw.hotspotColours.back;
}
if (background.isSet && (styleMain != STYLE_BRACELIGHT) && (styleMain != STYLE_BRACEBAD)) {
return background;
} else {
return vsDraw.styles[styleMain].back;
}
}
void EditView::DrawIndentGuide(Surface *surface, Sci::Line lineVisible, int lineHeight, XYPOSITION start, PRectangle rcSegment, bool highlight) {
const Point from = Point::FromInts(0, ((lineVisible & 1) && (lineHeight & 1)) ? 1 : 0);
const PRectangle rcCopyArea(start + 1, rcSegment.top,
start + 2, rcSegment.bottom);
surface->Copy(rcCopyArea, from,
highlight ? *pixmapIndentGuideHighlight : *pixmapIndentGuide);
}
static void SimpleAlphaRectangle(Surface *surface, PRectangle rc, ColourDesired fill, int alpha) {
if (alpha != SC_ALPHA_NOALPHA) {
surface->AlphaRectangle(rc, 0, fill, alpha, fill, alpha, 0);
}
}
static void DrawTextBlob(Surface *surface, const ViewStyle &vsDraw, PRectangle rcSegment,
std::string_view text, ColourDesired textBack, ColourDesired textFore, bool fillBackground) {
if (rcSegment.Empty())
return;
if (fillBackground) {
surface->FillRectangle(rcSegment, textBack);
}
FontAlias ctrlCharsFont = vsDraw.styles[STYLE_CONTROLCHAR].font;
const int normalCharHeight = static_cast<int>(ceil(vsDraw.styles[STYLE_CONTROLCHAR].capitalHeight));
PRectangle rcCChar = rcSegment;
rcCChar.left = rcCChar.left + 1;
rcCChar.top = rcSegment.top + vsDraw.maxAscent - normalCharHeight;
rcCChar.bottom = rcSegment.top + vsDraw.maxAscent + 1;
PRectangle rcCentral = rcCChar;
rcCentral.top++;
rcCentral.bottom--;
surface->FillRectangle(rcCentral, textFore);
PRectangle rcChar = rcCChar;
rcChar.left++;
rcChar.right--;
surface->DrawTextClipped(rcChar, ctrlCharsFont,
rcSegment.top + vsDraw.maxAscent, text,
textBack, textFore);
}
static void DrawFrame(Surface *surface, ColourDesired colour, int alpha, PRectangle rcFrame) {
if (alpha != SC_ALPHA_NOALPHA)
surface->AlphaRectangle(rcFrame, 0, colour, alpha, colour, alpha, 0);
else
surface->FillRectangle(rcFrame, colour);
}
static void DrawCaretLineFramed(Surface *surface, const ViewStyle &vsDraw, const LineLayout *ll, PRectangle rcLine, int subLine) {
const int width = vsDraw.GetFrameWidth();
if (subLine == 0 || ll->wrapIndent == 0 || vsDraw.caretLineAlpha != SC_ALPHA_NOALPHA) {
// Left
DrawFrame(surface, vsDraw.caretLineBackground, vsDraw.caretLineAlpha,
PRectangle(rcLine.left, rcLine.top, rcLine.left + width, rcLine.bottom));
}
if (subLine == 0) {
// Top
DrawFrame(surface, vsDraw.caretLineBackground, vsDraw.caretLineAlpha,
PRectangle(rcLine.left + width, rcLine.top, rcLine.right - width, rcLine.top + width));
}
if (subLine == ll->lines - 1 || vsDraw.caretLineAlpha != SC_ALPHA_NOALPHA) {
// Right
DrawFrame(surface, vsDraw.caretLineBackground, vsDraw.caretLineAlpha,
PRectangle(rcLine.right - width, rcLine.top, rcLine.right, rcLine.bottom));
}
if (subLine == ll->lines - 1) {
// Bottom
DrawFrame(surface, vsDraw.caretLineBackground, vsDraw.caretLineAlpha,
PRectangle(rcLine.left + width, rcLine.bottom - width, rcLine.right - width, rcLine.bottom));
}
}
void EditView::DrawEOL(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, const LineLayout *ll,
PRectangle rcLine, Sci::Line line, Sci::Position lineEnd, int xStart, int subLine, XYACCUMULATOR subLineStart,
ColourOptional background) {
const Sci::Position posLineStart = model.pdoc->LineStart(line);
PRectangle rcSegment = rcLine;
const bool lastSubLine = subLine == (ll->lines - 1);
XYPOSITION virtualSpace = 0;
if (lastSubLine) {
const XYPOSITION spaceWidth = vsDraw.styles[ll->EndLineStyle()].spaceWidth;
virtualSpace = model.sel.VirtualSpaceFor(model.pdoc->LineEnd(line)) * spaceWidth;
}
const XYPOSITION xEol = static_cast<XYPOSITION>(ll->positions[lineEnd] - subLineStart);
// Fill the virtual space and show selections within it
if (virtualSpace > 0.0f) {
rcSegment.left = xEol + xStart;
rcSegment.right = xEol + xStart + virtualSpace;
surface->FillRectangle(rcSegment, background.isSet ? background : vsDraw.styles[ll->styles[ll->numCharsInLine]].back);
if (!hideSelection && ((vsDraw.selAlpha == SC_ALPHA_NOALPHA) || (vsDraw.selAdditionalAlpha == SC_ALPHA_NOALPHA))) {
const SelectionSegment virtualSpaceRange(SelectionPosition(model.pdoc->LineEnd(line)),
SelectionPosition(model.pdoc->LineEnd(line),
model.sel.VirtualSpaceFor(model.pdoc->LineEnd(line))));
for (size_t r = 0; r<model.sel.Count(); r++) {
const int alpha = (r == model.sel.Main()) ? vsDraw.selAlpha : vsDraw.selAdditionalAlpha;
if (alpha == SC_ALPHA_NOALPHA) {
const SelectionSegment portion = model.sel.Range(r).Intersect(virtualSpaceRange);
if (!portion.Empty()) {
const XYPOSITION spaceWidth = vsDraw.styles[ll->EndLineStyle()].spaceWidth;
rcSegment.left = xStart + ll->positions[portion.start.Position() - posLineStart] -
static_cast<XYPOSITION>(subLineStart)+portion.start.VirtualSpace() * spaceWidth;
rcSegment.right = xStart + ll->positions[portion.end.Position() - posLineStart] -
static_cast<XYPOSITION>(subLineStart)+portion.end.VirtualSpace() * spaceWidth;
rcSegment.left = (rcSegment.left > rcLine.left) ? rcSegment.left : rcLine.left;
rcSegment.right = (rcSegment.right < rcLine.right) ? rcSegment.right : rcLine.right;
surface->FillRectangle(rcSegment, SelectionBackground(vsDraw, r == model.sel.Main(), model.primarySelection));
}
}
}
}
}
int eolInSelection = 0;
int alpha = SC_ALPHA_NOALPHA;
if (!hideSelection) {
const Sci::Position posAfterLineEnd = model.pdoc->LineStart(line + 1);
eolInSelection = lastSubLine ? model.sel.InSelectionForEOL(posAfterLineEnd) : 0;
alpha = (eolInSelection == 1) ? vsDraw.selAlpha : vsDraw.selAdditionalAlpha;
}
// Draw the [CR], [LF], or [CR][LF] blobs if visible line ends are on
XYPOSITION blobsWidth = 0;
if (lastSubLine) {
for (Sci::Position eolPos = ll->numCharsBeforeEOL; eolPos<ll->numCharsInLine; eolPos++) {
rcSegment.left = xStart + ll->positions[eolPos] - static_cast<XYPOSITION>(subLineStart)+virtualSpace;
rcSegment.right = xStart + ll->positions[eolPos + 1] - static_cast<XYPOSITION>(subLineStart)+virtualSpace;
blobsWidth += rcSegment.Width();
char hexits[4] = "";
const char *ctrlChar;
const unsigned char chEOL = ll->chars[eolPos];
const int styleMain = ll->styles[eolPos];
const ColourDesired textBack = TextBackground(model, vsDraw, ll, background, eolInSelection, false, styleMain, eolPos);
if (UTF8IsAscii(chEOL)) {
ctrlChar = ControlCharacterString(chEOL);
} else {
const Representation *repr = model.reprs.RepresentationFromCharacter(&ll->chars[eolPos], ll->numCharsInLine - eolPos);
if (repr) {
ctrlChar = repr->stringRep.c_str();
eolPos = ll->numCharsInLine;
} else {
sprintf(hexits, "x%2X", chEOL);
ctrlChar = hexits;
}
}
ColourDesired textFore = vsDraw.styles[styleMain].fore;
if (eolInSelection && vsDraw.selColours.fore.isSet) {
textFore = (eolInSelection == 1) ? vsDraw.selColours.fore : vsDraw.selAdditionalForeground;
}
if (eolInSelection && vsDraw.selColours.back.isSet && (line < model.pdoc->LinesTotal() - 1)) {
if (alpha == SC_ALPHA_NOALPHA) {
surface->FillRectangle(rcSegment, SelectionBackground(vsDraw, eolInSelection == 1, model.primarySelection));
} else {
surface->FillRectangle(rcSegment, textBack);
}
} else {
surface->FillRectangle(rcSegment, textBack);
}
DrawTextBlob(surface, vsDraw, rcSegment, ctrlChar, textBack, textFore, phasesDraw == phasesOne);
if (eolInSelection && vsDraw.selColours.back.isSet && (line < model.pdoc->LinesTotal() - 1) && (alpha != SC_ALPHA_NOALPHA)) {
SimpleAlphaRectangle(surface, rcSegment, SelectionBackground(vsDraw, eolInSelection == 1, model.primarySelection), alpha);
}
}
}
// Draw the eol-is-selected rectangle
rcSegment.left = xEol + xStart + virtualSpace + blobsWidth;
rcSegment.right = rcSegment.left + vsDraw.aveCharWidth;
if (eolInSelection && vsDraw.selColours.back.isSet && (line < model.pdoc->LinesTotal() - 1) && (alpha == SC_ALPHA_NOALPHA)) {
surface->FillRectangle(rcSegment, SelectionBackground(vsDraw, eolInSelection == 1, model.primarySelection));
} else {
if (background.isSet) {
surface->FillRectangle(rcSegment, background);
} else if (line < model.pdoc->LinesTotal() - 1) {
surface->FillRectangle(rcSegment, vsDraw.styles[ll->styles[ll->numCharsInLine]].back);
} else if (vsDraw.styles[ll->styles[ll->numCharsInLine]].eolFilled) {
surface->FillRectangle(rcSegment, vsDraw.styles[ll->styles[ll->numCharsInLine]].back);
} else {
surface->FillRectangle(rcSegment, vsDraw.styles[STYLE_DEFAULT].back);
}
if (eolInSelection && vsDraw.selColours.back.isSet && (line < model.pdoc->LinesTotal() - 1) && (alpha != SC_ALPHA_NOALPHA)) {
SimpleAlphaRectangle(surface, rcSegment, SelectionBackground(vsDraw, eolInSelection == 1, model.primarySelection), alpha);
}
}
rcSegment.left = rcSegment.right;
if (rcSegment.left < rcLine.left)
rcSegment.left = rcLine.left;
rcSegment.right = rcLine.right;
const bool fillRemainder = !lastSubLine || model.foldDisplayTextStyle == SC_FOLDDISPLAYTEXT_HIDDEN || !model.pcs->GetFoldDisplayTextShown(line);
if (fillRemainder) {
// Fill the remainder of the line
FillLineRemainder(surface, model, vsDraw, ll, line, rcSegment, subLine);
}
bool drawWrapMarkEnd = false;
if (subLine + 1 < ll->lines) {
if (vsDraw.wrapVisualFlags & SC_WRAPVISUALFLAG_END) {
drawWrapMarkEnd = ll->LineStart(subLine + 1) != 0;
}
if (vsDraw.IsLineFrameOpaque(model.caret.active, ll->containsCaret)) {
const int width = vsDraw.GetFrameWidth();
// Draw right of frame under marker
DrawFrame(surface, vsDraw.caretLineBackground, vsDraw.caretLineAlpha,
PRectangle(rcLine.right - width, rcLine.top, rcLine.right, rcLine.bottom));
}
}
if (drawWrapMarkEnd) {
PRectangle rcPlace = rcSegment;
if (vsDraw.wrapVisualFlagsLocation & SC_WRAPVISUALFLAGLOC_END_BY_TEXT) {
rcPlace.left = xEol + xStart + virtualSpace;
rcPlace.right = rcPlace.left + vsDraw.aveCharWidth;
} else {
// rcLine is clipped to text area
rcPlace.right = rcLine.right;
rcPlace.left = rcPlace.right - vsDraw.aveCharWidth;
}
if (!customDrawWrapMarker) {
DrawWrapMarker(surface, rcPlace, true, vsDraw.WrapColour());
} else {
customDrawWrapMarker(surface, rcPlace, true, vsDraw.WrapColour());
}
}
}
static void DrawIndicator(int indicNum, Sci::Position startPos, Sci::Position endPos, Surface *surface, const ViewStyle &vsDraw,
const LineLayout *ll, int xStart, PRectangle rcLine, Sci::Position secondCharacter, int subLine, Indicator::DrawState drawState,
int value, bool bidiEnabled, int tabWidthMinimumPixels) {
const XYPOSITION subLineStart = ll->positions[ll->LineStart(subLine)];
std::vector<PRectangle> rectangles;
const PRectangle rcIndic(
ll->positions[startPos] + xStart - subLineStart,
rcLine.top + vsDraw.maxAscent,
ll->positions[endPos] + xStart - subLineStart,
rcLine.top + vsDraw.maxAscent + 3);
if (bidiEnabled) {
ScreenLine screenLine(ll, subLine, vsDraw, rcLine.right - xStart, tabWidthMinimumPixels);
const Range lineRange = ll->SubLineRange(subLine, LineLayout::Scope::visibleOnly);
std::unique_ptr<IScreenLineLayout> slLayout = surface->Layout(&screenLine);
std::vector<Interval> intervals = slLayout->FindRangeIntervals(
startPos - lineRange.start, endPos - lineRange.start);
for (const Interval &interval : intervals) {
PRectangle rcInterval = rcIndic;
rcInterval.left = interval.left + xStart;
rcInterval.right = interval.right + xStart;
rectangles.push_back(rcInterval);
}
} else {
rectangles.push_back(rcIndic);
}
for (const PRectangle &rc : rectangles) {
PRectangle rcFirstCharacter = rc;
// Allow full descent space for character indicators
rcFirstCharacter.bottom = rcLine.top + vsDraw.maxAscent + vsDraw.maxDescent;
if (secondCharacter >= 0) {
rcFirstCharacter.right = ll->positions[secondCharacter] + xStart - subLineStart;
} else {
// Indicator continued from earlier line so make an empty box and don't draw
rcFirstCharacter.right = rcFirstCharacter.left;
}
vsDraw.indicators[indicNum].Draw(surface, rc, rcLine, rcFirstCharacter, drawState, value);
}
}
static void DrawIndicators(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, const LineLayout *ll,
Sci::Line line, int xStart, PRectangle rcLine, int subLine, Sci::Position lineEnd, bool under, int tabWidthMinimumPixels) {
// Draw decorators
const Sci::Position posLineStart = model.pdoc->LineStart(line);
const Sci::Position lineStart = ll->LineStart(subLine);
const Sci::Position posLineEnd = posLineStart + lineEnd;
for (const IDecoration *deco : model.pdoc->decorations->View()) {
if (under == vsDraw.indicators[deco->Indicator()].under) {
Sci::Position startPos = posLineStart + lineStart;
if (!deco->ValueAt(startPos)) {
startPos = deco->EndRun(startPos);
}
while ((startPos < posLineEnd) && (deco->ValueAt(startPos))) {
const Range rangeRun(deco->StartRun(startPos), deco->EndRun(startPos));
const Sci::Position endPos = std::min(rangeRun.end, posLineEnd);
const bool hover = vsDraw.indicators[deco->Indicator()].IsDynamic() &&
rangeRun.ContainsCharacter(model.hoverIndicatorPos);
const int value = deco->ValueAt(startPos);
const Indicator::DrawState drawState = hover ? Indicator::drawHover : Indicator::drawNormal;
const Sci::Position posSecond = model.pdoc->MovePositionOutsideChar(rangeRun.First() + 1, 1);
DrawIndicator(deco->Indicator(), startPos - posLineStart, endPos - posLineStart,
surface, vsDraw, ll, xStart, rcLine, posSecond - posLineStart, subLine, drawState,
value, model.BidirectionalEnabled(), tabWidthMinimumPixels);
startPos = endPos;
if (!deco->ValueAt(startPos)) {
startPos = deco->EndRun(startPos);
}
}
}
}
// Use indicators to highlight matching braces
if ((vsDraw.braceHighlightIndicatorSet && (model.bracesMatchStyle == STYLE_BRACELIGHT)) ||
(vsDraw.braceBadLightIndicatorSet && (model.bracesMatchStyle == STYLE_BRACEBAD))) {
const int braceIndicator = (model.bracesMatchStyle == STYLE_BRACELIGHT) ? vsDraw.braceHighlightIndicator : vsDraw.braceBadLightIndicator;
if (under == vsDraw.indicators[braceIndicator].under) {
const Range rangeLine(posLineStart + lineStart, posLineEnd);
if (rangeLine.ContainsCharacter(model.braces[0])) {
const Sci::Position braceOffset = model.braces[0] - posLineStart;
if (braceOffset < ll->numCharsInLine) {
const Sci::Position secondOffset = model.pdoc->MovePositionOutsideChar(model.braces[0] + 1, 1) - posLineStart;
DrawIndicator(braceIndicator, braceOffset, braceOffset + 1, surface, vsDraw, ll, xStart, rcLine, secondOffset,
subLine, Indicator::drawNormal, 1, model.BidirectionalEnabled(), tabWidthMinimumPixels);
}
}
if (rangeLine.ContainsCharacter(model.braces[1])) {
const Sci::Position braceOffset = model.braces[1] - posLineStart;
if (braceOffset < ll->numCharsInLine) {
const Sci::Position secondOffset = model.pdoc->MovePositionOutsideChar(model.braces[1] + 1, 1) - posLineStart;
DrawIndicator(braceIndicator, braceOffset, braceOffset + 1, surface, vsDraw, ll, xStart, rcLine, secondOffset,
subLine, Indicator::drawNormal, 1, model.BidirectionalEnabled(), tabWidthMinimumPixels);
}
}
}
}
}
void EditView::DrawFoldDisplayText(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, const LineLayout *ll,
Sci::Line line, int xStart, PRectangle rcLine, int subLine, XYACCUMULATOR subLineStart, DrawPhase phase) {
const bool lastSubLine = subLine == (ll->lines - 1);
if (!lastSubLine)
return;
if ((model.foldDisplayTextStyle == SC_FOLDDISPLAYTEXT_HIDDEN) || !model.pcs->GetFoldDisplayTextShown(line))
return;
PRectangle rcSegment = rcLine;
const std::string_view foldDisplayText = model.pcs->GetFoldDisplayText(line);
FontAlias fontText = vsDraw.styles[STYLE_FOLDDISPLAYTEXT].font;
const int widthFoldDisplayText = static_cast<int>(surface->WidthText(fontText, foldDisplayText));
int eolInSelection = 0;
int alpha = SC_ALPHA_NOALPHA;
if (!hideSelection) {
const Sci::Position posAfterLineEnd = model.pdoc->LineStart(line + 1);
eolInSelection = (subLine == (ll->lines - 1)) ? model.sel.InSelectionForEOL(posAfterLineEnd) : 0;
alpha = (eolInSelection == 1) ? vsDraw.selAlpha : vsDraw.selAdditionalAlpha;
}
const XYPOSITION spaceWidth = vsDraw.styles[ll->EndLineStyle()].spaceWidth;
const XYPOSITION virtualSpace = model.sel.VirtualSpaceFor(
model.pdoc->LineEnd(line)) * spaceWidth;
rcSegment.left = xStart + static_cast<XYPOSITION>(ll->positions[ll->numCharsInLine] - subLineStart) + virtualSpace + vsDraw.aveCharWidth;
rcSegment.right = rcSegment.left + static_cast<XYPOSITION>(widthFoldDisplayText);
const ColourOptional background = vsDraw.Background(model.pdoc->GetMark(line), model.caret.active, ll->containsCaret);
FontAlias textFont = vsDraw.styles[STYLE_FOLDDISPLAYTEXT].font;
ColourDesired textFore = vsDraw.styles[STYLE_FOLDDISPLAYTEXT].fore;
if (eolInSelection && (vsDraw.selColours.fore.isSet)) {
textFore = (eolInSelection == 1) ? vsDraw.selColours.fore : vsDraw.selAdditionalForeground;
}
const ColourDesired textBack = TextBackground(model, vsDraw, ll, background, eolInSelection,
false, STYLE_FOLDDISPLAYTEXT, -1);
if (model.trackLineWidth) {
if (rcSegment.right + 1> lineWidthMaxSeen) {
// Fold display text border drawn on rcSegment.right with width 1 is the last visble object of the line
lineWidthMaxSeen = static_cast<int>(rcSegment.right + 1);
}
}
if (phase & drawBack) {
surface->FillRectangle(rcSegment, textBack);
// Fill Remainder of the line
PRectangle rcRemainder = rcSegment;
rcRemainder.left = rcRemainder.right;
if (rcRemainder.left < rcLine.left)
rcRemainder.left = rcLine.left;
rcRemainder.right = rcLine.right;
FillLineRemainder(surface, model, vsDraw, ll, line, rcRemainder, subLine);
}
if (phase & drawText) {
if (phasesDraw != phasesOne) {
surface->DrawTextTransparent(rcSegment, textFont,
rcSegment.top + vsDraw.maxAscent, foldDisplayText,
textFore);
} else {
surface->DrawTextNoClip(rcSegment, textFont,
rcSegment.top + vsDraw.maxAscent, foldDisplayText,
textFore, textBack);
}
}
if (phase & drawIndicatorsFore) {
if (model.foldDisplayTextStyle == SC_FOLDDISPLAYTEXT_BOXED) {
surface->PenColour(textFore);
PRectangle rcBox = rcSegment;
rcBox.left = round(rcSegment.left);
rcBox.right = round(rcSegment.right);
const IntegerRectangle ircBox(rcBox);
surface->MoveTo(ircBox.left, ircBox.top);
surface->LineTo(ircBox.left, ircBox.bottom);
surface->MoveTo(ircBox.right, ircBox.top);
surface->LineTo(ircBox.right, ircBox.bottom);
surface->MoveTo(ircBox.left, ircBox.top);
surface->LineTo(ircBox.right, ircBox.top);
surface->MoveTo(ircBox.left, ircBox.bottom - 1);
surface->LineTo(ircBox.right, ircBox.bottom - 1);
}
}
if (phase & drawSelectionTranslucent) {
if (eolInSelection && vsDraw.selColours.back.isSet && (line < model.pdoc->LinesTotal() - 1) && alpha != SC_ALPHA_NOALPHA) {
SimpleAlphaRectangle(surface, rcSegment, SelectionBackground(vsDraw, eolInSelection == 1, model.primarySelection), alpha);
}
}
}
static constexpr bool AnnotationBoxedOrIndented(int annotationVisible) noexcept {
return annotationVisible == ANNOTATION_BOXED || annotationVisible == ANNOTATION_INDENTED;
}
void EditView::DrawAnnotation(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, const LineLayout *ll,
Sci::Line line, int xStart, PRectangle rcLine, int subLine, DrawPhase phase) {
const int indent = static_cast<int>(model.pdoc->GetLineIndentation(line) * vsDraw.spaceWidth);
PRectangle rcSegment = rcLine;
const int annotationLine = subLine - ll->lines;
const StyledText stAnnotation = model.pdoc->AnnotationStyledText(line);
if (stAnnotation.text && ValidStyledText(vsDraw, vsDraw.annotationStyleOffset, stAnnotation)) {
if (phase & drawBack) {
surface->FillRectangle(rcSegment, vsDraw.styles[0].back);
}
rcSegment.left = static_cast<XYPOSITION>(xStart);
if (model.trackLineWidth || AnnotationBoxedOrIndented(vsDraw.annotationVisible)) {
// Only care about calculating width if tracking or need to draw indented box
int widthAnnotation = WidestLineWidth(surface, vsDraw, vsDraw.annotationStyleOffset, stAnnotation);
if (AnnotationBoxedOrIndented(vsDraw.annotationVisible)) {
widthAnnotation += static_cast<int>(vsDraw.spaceWidth * 2); // Margins
rcSegment.left = static_cast<XYPOSITION>(xStart + indent);
rcSegment.right = rcSegment.left + widthAnnotation;
}
if (widthAnnotation > lineWidthMaxSeen)
lineWidthMaxSeen = widthAnnotation;
}
const int annotationLines = model.pdoc->AnnotationLines(line);
size_t start = 0;
size_t lengthAnnotation = stAnnotation.LineLength(start);
int lineInAnnotation = 0;
while ((lineInAnnotation < annotationLine) && (start < stAnnotation.length)) {
start += lengthAnnotation + 1;
lengthAnnotation = stAnnotation.LineLength(start);
lineInAnnotation++;
}
PRectangle rcText = rcSegment;
if ((phase & drawBack) && AnnotationBoxedOrIndented(vsDraw.annotationVisible)) {
surface->FillRectangle(rcText,
vsDraw.styles[stAnnotation.StyleAt(start) + vsDraw.annotationStyleOffset].back);
rcText.left += vsDraw.spaceWidth;
}
DrawStyledText(surface, vsDraw, vsDraw.annotationStyleOffset, rcText,
stAnnotation, start, lengthAnnotation, phase);
if ((phase & drawBack) && (vsDraw.annotationVisible == ANNOTATION_BOXED)) {
surface->PenColour(vsDraw.styles[vsDraw.annotationStyleOffset].fore);
const IntegerRectangle ircSegment(rcSegment);
surface->MoveTo(ircSegment.left, ircSegment.top);
surface->LineTo(ircSegment.left, ircSegment.bottom);
surface->MoveTo(ircSegment.right, ircSegment.top);
surface->LineTo(ircSegment.right, ircSegment.bottom);
if (subLine == ll->lines) {
surface->MoveTo(ircSegment.left, ircSegment.top);
surface->LineTo(ircSegment.right, ircSegment.top);
}
if (subLine == ll->lines + annotationLines - 1) {
surface->MoveTo(ircSegment.left, ircSegment.bottom - 1);
surface->LineTo(ircSegment.right, ircSegment.bottom - 1);
}
}
}
}
static void DrawBlockCaret(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, const LineLayout *ll,
int subLine, int xStart, Sci::Position offset, Sci::Position posCaret, PRectangle rcCaret, ColourDesired caretColour) {
const Sci::Position lineStart = ll->LineStart(subLine);
Sci::Position posBefore = posCaret;
Sci::Position posAfter = model.pdoc->MovePositionOutsideChar(posCaret + 1, 1);
Sci::Position numCharsToDraw = posAfter - posCaret;
// Work out where the starting and ending offsets are. We need to
// see if the previous character shares horizontal space, such as a
// glyph / combining character. If so we'll need to draw that too.
Sci::Position offsetFirstChar = offset;
Sci::Position offsetLastChar = offset + (posAfter - posCaret);
while ((posBefore > 0) && ((offsetLastChar - numCharsToDraw) >= lineStart)) {
if ((ll->positions[offsetLastChar] - ll->positions[offsetLastChar - numCharsToDraw]) > 0) {
// The char does not share horizontal space
break;
}
// Char shares horizontal space, update the numChars to draw
// Update posBefore to point to the prev char
posBefore = model.pdoc->MovePositionOutsideChar(posBefore - 1, -1);
numCharsToDraw = posAfter - posBefore;
offsetFirstChar = offset - (posCaret - posBefore);
}
// See if the next character shares horizontal space, if so we'll
// need to draw that too.
if (offsetFirstChar < 0)
offsetFirstChar = 0;
numCharsToDraw = offsetLastChar - offsetFirstChar;
while ((offsetLastChar < ll->LineStart(subLine + 1)) && (offsetLastChar <= ll->numCharsInLine)) {
// Update posAfter to point to the 2nd next char, this is where
// the next character ends, and 2nd next begins. We'll need
// to compare these two
posBefore = posAfter;
posAfter = model.pdoc->MovePositionOutsideChar(posAfter + 1, 1);
offsetLastChar = offset + (posAfter - posCaret);
if ((ll->positions[offsetLastChar] - ll->positions[offsetLastChar - (posAfter - posBefore)]) > 0) {
// The char does not share horizontal space
break;
}
// Char shares horizontal space, update the numChars to draw
numCharsToDraw = offsetLastChar - offsetFirstChar;
}
// We now know what to draw, update the caret drawing rectangle
rcCaret.left = ll->positions[offsetFirstChar] - ll->positions[lineStart] + xStart;
rcCaret.right = ll->positions[offsetFirstChar + numCharsToDraw] - ll->positions[lineStart] + xStart;
// Adjust caret position to take into account any word wrapping symbols.
if ((ll->wrapIndent != 0) && (lineStart != 0)) {
const XYPOSITION wordWrapCharWidth = ll->wrapIndent;
rcCaret.left += wordWrapCharWidth;
rcCaret.right += wordWrapCharWidth;
}
// This character is where the caret block is, we override the colours
// (inversed) for drawing the caret here.
const int styleMain = ll->styles[offsetFirstChar];
FontAlias fontText = vsDraw.styles[styleMain].font;
const std::string_view text(&ll->chars[offsetFirstChar], numCharsToDraw);
surface->DrawTextClipped(rcCaret, fontText,
rcCaret.top + vsDraw.maxAscent, text, vsDraw.styles[styleMain].back,
caretColour);
}
void EditView::DrawCarets(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, const LineLayout *ll,
Sci::Line lineDoc, int xStart, PRectangle rcLine, int subLine) const {
// When drag is active it is the only caret drawn
const bool drawDrag = model.posDrag.IsValid();
if (hideSelection && !drawDrag)
return;
const Sci::Position posLineStart = model.pdoc->LineStart(lineDoc);
// For each selection draw
for (size_t r = 0; (r<model.sel.Count()) || drawDrag; r++) {
const bool mainCaret = r == model.sel.Main();
SelectionPosition posCaret = (drawDrag ? model.posDrag : model.sel.Range(r).caret);
if (vsDraw.caretStyle == CARETSTYLE_BLOCK && !drawDrag && posCaret > model.sel.Range(r).anchor) {
if (posCaret.VirtualSpace() > 0)
posCaret.SetVirtualSpace(posCaret.VirtualSpace() - 1);
else
posCaret.SetPosition(model.pdoc->MovePositionOutsideChar(posCaret.Position()-1, -1));
}
const int offset = static_cast<int>(posCaret.Position() - posLineStart);
const XYPOSITION spaceWidth = vsDraw.styles[ll->EndLineStyle()].spaceWidth;
const XYPOSITION virtualOffset = posCaret.VirtualSpace() * spaceWidth;
if (ll->InLine(offset, subLine) && offset <= ll->numCharsBeforeEOL) {
XYPOSITION xposCaret = ll->positions[offset] + virtualOffset - ll->positions[ll->LineStart(subLine)];
if (model.BidirectionalEnabled() && (posCaret.VirtualSpace() == 0)) {
// Get caret point
const ScreenLine screenLine(ll, subLine, vsDraw, rcLine.right, tabWidthMinimumPixels);
const int caretPosition = static_cast<int>(posCaret.Position() - posLineStart - ll->LineStart(subLine));
std::unique_ptr<IScreenLineLayout> slLayout = surface->Layout(&screenLine);
const XYPOSITION caretLeft = slLayout->XFromPosition(caretPosition);
// In case of start of line, the cursor should be at the right
xposCaret = caretLeft + virtualOffset;
}
if (ll->wrapIndent != 0) {
const Sci::Position lineStart = ll->LineStart(subLine);
if (lineStart != 0) // Wrapped
xposCaret += ll->wrapIndent;
}
const bool caretBlinkState = (model.caret.active && model.caret.on) || (!additionalCaretsBlink && !mainCaret);
const bool caretVisibleState = additionalCaretsVisible || mainCaret;
if ((xposCaret >= 0) && (vsDraw.caretWidth > 0) && (vsDraw.caretStyle != CARETSTYLE_INVISIBLE) &&
((model.posDrag.IsValid()) || (caretBlinkState && caretVisibleState))) {
bool caretAtEOF = false;
bool caretAtEOL = false;
bool drawBlockCaret = false;
XYPOSITION widthOverstrikeCaret;
XYPOSITION caretWidthOffset = 0;
PRectangle rcCaret = rcLine;
if (posCaret.Position() == model.pdoc->Length()) { // At end of document
caretAtEOF = true;
widthOverstrikeCaret = vsDraw.aveCharWidth;
} else if ((posCaret.Position() - posLineStart) >= ll->numCharsInLine) { // At end of line
caretAtEOL = true;
widthOverstrikeCaret = vsDraw.aveCharWidth;
} else {
const int widthChar = model.pdoc->LenChar(posCaret.Position());
widthOverstrikeCaret = ll->positions[offset + widthChar] - ll->positions[offset];
}
if (widthOverstrikeCaret < 3) // Make sure its visible
widthOverstrikeCaret = 3;
if (xposCaret > 0)
caretWidthOffset = 0.51f; // Move back so overlaps both character cells.
xposCaret += xStart;
if (model.posDrag.IsValid()) {
/* Dragging text, use a line caret */
rcCaret.left = round(xposCaret - caretWidthOffset);
rcCaret.right = rcCaret.left + vsDraw.caretWidth;
} else if (model.inOverstrike && drawOverstrikeCaret) {
/* Overstrike (insert mode), use a modified bar caret */
rcCaret.top = rcCaret.bottom - 2;
rcCaret.left = xposCaret + 1;
rcCaret.right = rcCaret.left + widthOverstrikeCaret - 1;
} else if ((vsDraw.caretStyle == CARETSTYLE_BLOCK) || imeCaretBlockOverride) {
/* Block caret */
rcCaret.left = xposCaret;
if (!caretAtEOL && !caretAtEOF && (ll->chars[offset] != '\t') && !(IsControlCharacter(ll->chars[offset]))) {
drawBlockCaret = true;
rcCaret.right = xposCaret + widthOverstrikeCaret;
} else {
rcCaret.right = xposCaret + vsDraw.aveCharWidth;
}
} else {
/* Line caret */
rcCaret.left = round(xposCaret - caretWidthOffset);
rcCaret.right = rcCaret.left + vsDraw.caretWidth;
}
const ColourDesired caretColour = mainCaret ? vsDraw.caretcolour : vsDraw.additionalCaretColour;
if (drawBlockCaret) {
DrawBlockCaret(surface, model, vsDraw, ll, subLine, xStart, offset, posCaret.Position(), rcCaret, caretColour);
} else {
surface->FillRectangle(rcCaret, caretColour);
}
}
}
if (drawDrag)
break;
}
}
static void DrawWrapIndentAndMarker(Surface *surface, const ViewStyle &vsDraw, const LineLayout *ll,
int xStart, PRectangle rcLine, ColourOptional background, DrawWrapMarkerFn customDrawWrapMarker,
bool caretActive) {
// default bgnd here..
surface->FillRectangle(rcLine, background.isSet ? background :
vsDraw.styles[STYLE_DEFAULT].back);
if (vsDraw.IsLineFrameOpaque(caretActive, ll->containsCaret)) {
const int width = vsDraw.GetFrameWidth();
// Draw left of frame under marker
DrawFrame(surface, vsDraw.caretLineBackground, vsDraw.caretLineAlpha,
PRectangle(rcLine.left, rcLine.top, rcLine.left + width, rcLine.bottom));
}
if (vsDraw.wrapVisualFlags & SC_WRAPVISUALFLAG_START) {
// draw continuation rect
PRectangle rcPlace = rcLine;
rcPlace.left = static_cast<XYPOSITION>(xStart);
rcPlace.right = rcPlace.left + ll->wrapIndent;
if (vsDraw.wrapVisualFlagsLocation & SC_WRAPVISUALFLAGLOC_START_BY_TEXT)
rcPlace.left = rcPlace.right - vsDraw.aveCharWidth;
else
rcPlace.right = rcPlace.left + vsDraw.aveCharWidth;
if (!customDrawWrapMarker) {
DrawWrapMarker(surface, rcPlace, false, vsDraw.WrapColour());
} else {
customDrawWrapMarker(surface, rcPlace, false, vsDraw.WrapColour());
}
}
}
void EditView::DrawBackground(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, const LineLayout *ll,
PRectangle rcLine, Range lineRange, Sci::Position posLineStart, int xStart,
int subLine, ColourOptional background) const {
const bool selBackDrawn = vsDraw.SelectionBackgroundDrawn();
bool inIndentation = subLine == 0; // Do not handle indentation except on first subline.
const XYACCUMULATOR subLineStart = ll->positions[lineRange.start];
// Does not take margin into account but not significant
const int xStartVisible = static_cast<int>(subLineStart)-xStart;
BreakFinder bfBack(ll, &model.sel, lineRange, posLineStart, xStartVisible, selBackDrawn, model.pdoc, &model.reprs, nullptr);
const bool drawWhitespaceBackground = vsDraw.WhitespaceBackgroundDrawn() && !background.isSet;
// Background drawing loop
while (bfBack.More()) {
const TextSegment ts = bfBack.Next();
const Sci::Position i = ts.end() - 1;
const Sci::Position iDoc = i + posLineStart;
PRectangle rcSegment = rcLine;
rcSegment.left = ll->positions[ts.start] + xStart - static_cast<XYPOSITION>(subLineStart);
rcSegment.right = ll->positions[ts.end()] + xStart - static_cast<XYPOSITION>(subLineStart);
// Only try to draw if really visible - enhances performance by not calling environment to
// draw strings that are completely past the right side of the window.
if (!rcSegment.Empty() && rcSegment.Intersects(rcLine)) {
// Clip to line rectangle, since may have a huge position which will not work with some platforms
if (rcSegment.left < rcLine.left)
rcSegment.left = rcLine.left;
if (rcSegment.right > rcLine.right)
rcSegment.right = rcLine.right;
const int inSelection = hideSelection ? 0 : model.sel.CharacterInSelection(iDoc);
const bool inHotspot = (ll->hotspot.Valid()) && ll->hotspot.ContainsCharacter(iDoc);
ColourDesired textBack = TextBackground(model, vsDraw, ll, background, inSelection,
inHotspot, ll->styles[i], i);
if (ts.representation) {
if (ll->chars[i] == '\t') {
// Tab display
if (drawWhitespaceBackground && vsDraw.WhiteSpaceVisible(inIndentation))
textBack = vsDraw.whitespaceColours.back;
} else {
// Blob display
inIndentation = false;
}
surface->FillRectangle(rcSegment, textBack);
} else {
// Normal text display
surface->FillRectangle(rcSegment, textBack);
if (vsDraw.viewWhitespace != wsInvisible) {
for (int cpos = 0; cpos <= i - ts.start; cpos++) {
if (ll->chars[cpos + ts.start] == ' ') {
if (drawWhitespaceBackground && vsDraw.WhiteSpaceVisible(inIndentation)) {
const PRectangle rcSpace(
ll->positions[cpos + ts.start] + xStart - static_cast<XYPOSITION>(subLineStart),
rcSegment.top,
ll->positions[cpos + ts.start + 1] + xStart - static_cast<XYPOSITION>(subLineStart),
rcSegment.bottom);
surface->FillRectangle(rcSpace, vsDraw.whitespaceColours.back);
}
} else {
inIndentation = false;
}
}
}
}
} else if (rcSegment.left > rcLine.right) {
break;
}
}
}
static void DrawEdgeLine(Surface *surface, const ViewStyle &vsDraw, const LineLayout *ll, PRectangle rcLine,
Range lineRange, int xStart) {
if (vsDraw.edgeState == EDGE_LINE) {
PRectangle rcSegment = rcLine;
const int edgeX = static_cast<int>(vsDraw.theEdge.column * vsDraw.spaceWidth);
rcSegment.left = static_cast<XYPOSITION>(edgeX + xStart);
if ((ll->wrapIndent != 0) && (lineRange.start != 0))
rcSegment.left -= ll->wrapIndent;
rcSegment.right = rcSegment.left + 1;
surface->FillRectangle(rcSegment, vsDraw.theEdge.colour);
} else if (vsDraw.edgeState == EDGE_MULTILINE) {
for (size_t edge = 0; edge < vsDraw.theMultiEdge.size(); edge++) {
if (vsDraw.theMultiEdge[edge].column >= 0) {
PRectangle rcSegment = rcLine;
const int edgeX = static_cast<int>(vsDraw.theMultiEdge[edge].column * vsDraw.spaceWidth);
rcSegment.left = static_cast<XYPOSITION>(edgeX + xStart);
if ((ll->wrapIndent != 0) && (lineRange.start != 0))
rcSegment.left -= ll->wrapIndent;
rcSegment.right = rcSegment.left + 1;
surface->FillRectangle(rcSegment, vsDraw.theMultiEdge[edge].colour);
}
}
}
}
// Draw underline mark as part of background if not transparent
static void DrawMarkUnderline(Surface *surface, const EditModel &model, const ViewStyle &vsDraw,
Sci::Line line, PRectangle rcLine) {
int marks = model.pdoc->GetMark(line);
for (int markBit = 0; (markBit < 32) && marks; markBit++) {
if ((marks & 1) && (vsDraw.markers[markBit].markType == SC_MARK_UNDERLINE) &&
(vsDraw.markers[markBit].alpha == SC_ALPHA_NOALPHA)) {
PRectangle rcUnderline = rcLine;
rcUnderline.top = rcUnderline.bottom - 2;
surface->FillRectangle(rcUnderline, vsDraw.markers[markBit].back);
}
marks >>= 1;
}
}
static void DrawTranslucentSelection(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, const LineLayout *ll,
Sci::Line line, PRectangle rcLine, int subLine, Range lineRange, int xStart, int tabWidthMinimumPixels) {
if ((vsDraw.selAlpha != SC_ALPHA_NOALPHA) || (vsDraw.selAdditionalAlpha != SC_ALPHA_NOALPHA)) {
const Sci::Position posLineStart = model.pdoc->LineStart(line);
const XYACCUMULATOR subLineStart = ll->positions[lineRange.start];
// For each selection draw
Sci::Position virtualSpaces = 0;
if (subLine == (ll->lines - 1)) {
virtualSpaces = model.sel.VirtualSpaceFor(model.pdoc->LineEnd(line));
}
const SelectionPosition posStart(posLineStart + lineRange.start);
const SelectionPosition posEnd(posLineStart + lineRange.end, virtualSpaces);
const SelectionSegment virtualSpaceRange(posStart, posEnd);
for (size_t r = 0; r < model.sel.Count(); r++) {
const int alpha = (r == model.sel.Main()) ? vsDraw.selAlpha : vsDraw.selAdditionalAlpha;
if (alpha != SC_ALPHA_NOALPHA) {
const SelectionSegment portion = model.sel.Range(r).Intersect(virtualSpaceRange);
if (!portion.Empty()) {
const XYPOSITION spaceWidth = vsDraw.styles[ll->EndLineStyle()].spaceWidth;
if (model.BidirectionalEnabled()) {
const int selectionStart = static_cast<int>(portion.start.Position() - posLineStart - lineRange.start);
const int selectionEnd = static_cast<int>(portion.end.Position() - posLineStart - lineRange.start);
const ColourDesired background = SelectionBackground(vsDraw, r == model.sel.Main(), model.primarySelection);
const ScreenLine screenLine(ll, subLine, vsDraw, rcLine.right, tabWidthMinimumPixels);
std::unique_ptr<IScreenLineLayout> slLayout = surface->Layout(&screenLine);
const std::vector<Interval> intervals = slLayout->FindRangeIntervals(selectionStart, selectionEnd);
for (const Interval &interval : intervals) {
const XYPOSITION rcRight = interval.right + xStart;
const XYPOSITION rcLeft = interval.left + xStart;
const PRectangle rcSelection(rcLeft, rcLine.top, rcRight, rcLine.bottom);
SimpleAlphaRectangle(surface, rcSelection, background, alpha);
}
if (portion.end.VirtualSpace()) {
const XYPOSITION xStartVirtual = ll->positions[lineRange.end] -
static_cast<XYPOSITION>(subLineStart) + xStart;
PRectangle rcSegment = rcLine;
rcSegment.left = xStartVirtual + portion.start.VirtualSpace() * spaceWidth;
rcSegment.right = xStartVirtual + portion.end.VirtualSpace() * spaceWidth;
SimpleAlphaRectangle(surface, rcSegment, background, alpha);
}
} else {
PRectangle rcSegment = rcLine;
rcSegment.left = xStart + ll->positions[portion.start.Position() - posLineStart] -
static_cast<XYPOSITION>(subLineStart) + portion.start.VirtualSpace() * spaceWidth;
rcSegment.right = xStart + ll->positions[portion.end.Position() - posLineStart] -
static_cast<XYPOSITION>(subLineStart) + portion.end.VirtualSpace() * spaceWidth;
if ((ll->wrapIndent != 0) && (lineRange.start != 0)) {
if ((portion.start.Position() - posLineStart) == lineRange.start && model.sel.Range(r).ContainsCharacter(portion.start.Position() - 1))
rcSegment.left -= static_cast<int>(ll->wrapIndent); // indentation added to xStart was truncated to int, so we do the same here
}
rcSegment.left = (rcSegment.left > rcLine.left) ? rcSegment.left : rcLine.left;
rcSegment.right = (rcSegment.right < rcLine.right) ? rcSegment.right : rcLine.right;
if (rcSegment.right > rcLine.left)
SimpleAlphaRectangle(surface, rcSegment, SelectionBackground(vsDraw, r == model.sel.Main(), model.primarySelection), alpha);
}
}
}
}
}
}
// Draw any translucent whole line states
static void DrawTranslucentLineState(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, const LineLayout *ll,
Sci::Line line, PRectangle rcLine, int subLine) {
if ((model.caret.active || vsDraw.alwaysShowCaretLineBackground) && vsDraw.showCaretLineBackground && ll->containsCaret &&
vsDraw.caretLineAlpha != SC_ALPHA_NOALPHA) {
if (vsDraw.caretLineFrame) {
DrawCaretLineFramed(surface, vsDraw, ll, rcLine, subLine);
} else {
SimpleAlphaRectangle(surface, rcLine, vsDraw.caretLineBackground, vsDraw.caretLineAlpha);
}
}
const int marksOfLine = model.pdoc->GetMark(line);
int marksDrawnInText = marksOfLine & vsDraw.maskDrawInText;
for (int markBit = 0; (markBit < 32) && marksDrawnInText; markBit++) {
if (marksDrawnInText & 1) {
if (vsDraw.markers[markBit].markType == SC_MARK_BACKGROUND) {
SimpleAlphaRectangle(surface, rcLine, vsDraw.markers[markBit].back, vsDraw.markers[markBit].alpha);
} else if (vsDraw.markers[markBit].markType == SC_MARK_UNDERLINE) {
PRectangle rcUnderline = rcLine;
rcUnderline.top = rcUnderline.bottom - 2;
SimpleAlphaRectangle(surface, rcUnderline, vsDraw.markers[markBit].back, vsDraw.markers[markBit].alpha);
}
}
marksDrawnInText >>= 1;
}
int marksDrawnInLine = marksOfLine & vsDraw.maskInLine;
for (int markBit = 0; (markBit < 32) && marksDrawnInLine; markBit++) {
if (marksDrawnInLine & 1) {
SimpleAlphaRectangle(surface, rcLine, vsDraw.markers[markBit].back, vsDraw.markers[markBit].alpha);
}
marksDrawnInLine >>= 1;
}
}
void EditView::DrawForeground(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, const LineLayout *ll,
Sci::Line lineVisible, PRectangle rcLine, Range lineRange, Sci::Position posLineStart, int xStart,
int subLine, ColourOptional background) {
const bool selBackDrawn = vsDraw.SelectionBackgroundDrawn();
const bool drawWhitespaceBackground = vsDraw.WhitespaceBackgroundDrawn() && !background.isSet;
bool inIndentation = subLine == 0; // Do not handle indentation except on first subline.
const XYACCUMULATOR subLineStart = ll->positions[lineRange.start];
const XYPOSITION indentWidth = model.pdoc->IndentSize() * vsDraw.spaceWidth;
// Does not take margin into account but not significant
const int xStartVisible = static_cast<int>(subLineStart)-xStart;
// Foreground drawing loop
BreakFinder bfFore(ll, &model.sel, lineRange, posLineStart, xStartVisible,
(((phasesDraw == phasesOne) && selBackDrawn) || vsDraw.selColours.fore.isSet), model.pdoc, &model.reprs, &vsDraw);
while (bfFore.More()) {
const TextSegment ts = bfFore.Next();
const Sci::Position i = ts.end() - 1;
const Sci::Position iDoc = i + posLineStart;
PRectangle rcSegment = rcLine;
rcSegment.left = ll->positions[ts.start] + xStart - static_cast<XYPOSITION>(subLineStart);
rcSegment.right = ll->positions[ts.end()] + xStart - static_cast<XYPOSITION>(subLineStart);
// Only try to draw if really visible - enhances performance by not calling environment to
// draw strings that are completely past the right side of the window.
if (rcSegment.Intersects(rcLine)) {
const int styleMain = ll->styles[i];
ColourDesired textFore = vsDraw.styles[styleMain].fore;
FontAlias textFont = vsDraw.styles[styleMain].font;
//hotspot foreground
const bool inHotspot = (ll->hotspot.Valid()) && ll->hotspot.ContainsCharacter(iDoc);
if (inHotspot) {
if (vsDraw.hotspotColours.fore.isSet)
textFore = vsDraw.hotspotColours.fore;
}
if (vsDraw.indicatorsSetFore) {
// At least one indicator sets the text colour so see if it applies to this segment
for (const IDecoration *deco : model.pdoc->decorations->View()) {
const int indicatorValue = deco->ValueAt(ts.start + posLineStart);
if (indicatorValue) {
const Indicator &indicator = vsDraw.indicators[deco->Indicator()];
const bool hover = indicator.IsDynamic() &&
((model.hoverIndicatorPos >= ts.start + posLineStart) &&
(model.hoverIndicatorPos <= ts.end() + posLineStart));
if (hover) {
if (indicator.sacHover.style == INDIC_TEXTFORE) {
textFore = indicator.sacHover.fore;
}
} else {
if (indicator.sacNormal.style == INDIC_TEXTFORE) {
if (indicator.Flags() & SC_INDICFLAG_VALUEFORE)
textFore = ColourDesired(indicatorValue & SC_INDICVALUEMASK);
else
textFore = indicator.sacNormal.fore;
}
}
}
}
}
const int inSelection = hideSelection ? 0 : model.sel.CharacterInSelection(iDoc);
if (inSelection && (vsDraw.selColours.fore.isSet)) {
textFore = (inSelection == 1) ? vsDraw.selColours.fore : vsDraw.selAdditionalForeground;
}
ColourDesired textBack = TextBackground(model, vsDraw, ll, background, inSelection, inHotspot, styleMain, i);
if (ts.representation) {
if (ll->chars[i] == '\t') {
// Tab display
if (phasesDraw == phasesOne) {
if (drawWhitespaceBackground && vsDraw.WhiteSpaceVisible(inIndentation))
textBack = vsDraw.whitespaceColours.back;
surface->FillRectangle(rcSegment, textBack);
}
if (inIndentation && vsDraw.viewIndentationGuides == ivReal) {
for (int indentCount = static_cast<int>((ll->positions[i] + epsilon) / indentWidth);
indentCount <= (ll->positions[i + 1] - epsilon) / indentWidth;
indentCount++) {
if (indentCount > 0) {
const XYPOSITION xIndent = floor(indentCount * indentWidth);
DrawIndentGuide(surface, lineVisible, vsDraw.lineHeight, xIndent + xStart, rcSegment,
(ll->xHighlightGuide == xIndent));
}
}
}
if (vsDraw.viewWhitespace != wsInvisible) {
if (vsDraw.WhiteSpaceVisible(inIndentation)) {
if (vsDraw.whitespaceColours.fore.isSet)
textFore = vsDraw.whitespaceColours.fore;
surface->PenColour(textFore);
const PRectangle rcTab(rcSegment.left + 1, rcSegment.top + tabArrowHeight,
rcSegment.right - 1, rcSegment.bottom - vsDraw.maxDescent);
const int segmentTop = static_cast<int>(rcSegment.top + vsDraw.lineHeight / 2);
if (!customDrawTabArrow)
DrawTabArrow(surface, rcTab, segmentTop, vsDraw);
else
customDrawTabArrow(surface, rcTab, segmentTop);
}
}
} else {
inIndentation = false;
if (vsDraw.controlCharSymbol >= 32) {
// Using one font for all control characters so it can be controlled independently to ensure
// the box goes around the characters tightly. Seems to be no way to work out what height
// is taken by an individual character - internal leading gives varying results.
FontAlias ctrlCharsFont = vsDraw.styles[STYLE_CONTROLCHAR].font;
const char cc[2] = { static_cast<char>(vsDraw.controlCharSymbol), '\0' };
surface->DrawTextNoClip(rcSegment, ctrlCharsFont,
rcSegment.top + vsDraw.maxAscent,
cc, textBack, textFore);
} else {
DrawTextBlob(surface, vsDraw, rcSegment, ts.representation->stringRep,
textBack, textFore, phasesDraw == phasesOne);
}
}
} else {
// Normal text display
if (vsDraw.styles[styleMain].visible) {
const std::string_view text(&ll->chars[ts.start], i - ts.start + 1);
if (phasesDraw != phasesOne) {
surface->DrawTextTransparent(rcSegment, textFont,
rcSegment.top + vsDraw.maxAscent, text, textFore);
} else {
surface->DrawTextNoClip(rcSegment, textFont,
rcSegment.top + vsDraw.maxAscent, text, textFore, textBack);
}
}
if (vsDraw.viewWhitespace != wsInvisible ||
(inIndentation && vsDraw.viewIndentationGuides != ivNone)) {
for (int cpos = 0; cpos <= i - ts.start; cpos++) {
if (ll->chars[cpos + ts.start] == ' ') {
if (vsDraw.viewWhitespace != wsInvisible) {
if (vsDraw.whitespaceColours.fore.isSet)
textFore = vsDraw.whitespaceColours.fore;
if (vsDraw.WhiteSpaceVisible(inIndentation)) {
const XYPOSITION xmid = (ll->positions[cpos + ts.start] + ll->positions[cpos + ts.start + 1]) / 2;
if ((phasesDraw == phasesOne) && drawWhitespaceBackground) {
textBack = vsDraw.whitespaceColours.back;
const PRectangle rcSpace(
ll->positions[cpos + ts.start] + xStart - static_cast<XYPOSITION>(subLineStart),
rcSegment.top,
ll->positions[cpos + ts.start + 1] + xStart - static_cast<XYPOSITION>(subLineStart),
rcSegment.bottom);
surface->FillRectangle(rcSpace, textBack);
}
const int halfDotWidth = vsDraw.whitespaceSize / 2;
PRectangle rcDot(xmid + xStart - halfDotWidth - static_cast<XYPOSITION>(subLineStart),
rcSegment.top + vsDraw.lineHeight / 2, 0.0f, 0.0f);
rcDot.right = rcDot.left + vsDraw.whitespaceSize;
rcDot.bottom = rcDot.top + vsDraw.whitespaceSize;
surface->FillRectangle(rcDot, textFore);
}
}
if (inIndentation && vsDraw.viewIndentationGuides == ivReal) {
for (int indentCount = static_cast<int>((ll->positions[cpos + ts.start] + epsilon) / indentWidth);
indentCount <= (ll->positions[cpos + ts.start + 1] - epsilon) / indentWidth;
indentCount++) {
if (indentCount > 0) {
const XYPOSITION xIndent = floor(indentCount * indentWidth);
DrawIndentGuide(surface, lineVisible, vsDraw.lineHeight, xIndent + xStart, rcSegment,
(ll->xHighlightGuide == xIndent));
}
}
}
} else {
inIndentation = false;
}
}
}
}
if (ll->hotspot.Valid() && vsDraw.hotspotUnderline && ll->hotspot.ContainsCharacter(iDoc)) {
PRectangle rcUL = rcSegment;
rcUL.top = rcUL.top + vsDraw.maxAscent + 1;
rcUL.bottom = rcUL.top + 1;
if (vsDraw.hotspotColours.fore.isSet)
surface->FillRectangle(rcUL, vsDraw.hotspotColours.fore);
else
surface->FillRectangle(rcUL, textFore);
} else if (vsDraw.styles[styleMain].underline) {
PRectangle rcUL = rcSegment;
rcUL.top = rcUL.top + vsDraw.maxAscent + 1;
rcUL.bottom = rcUL.top + 1;
surface->FillRectangle(rcUL, textFore);
}
} else if (rcSegment.left > rcLine.right) {
break;
}
}
}
void EditView::DrawIndentGuidesOverEmpty(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, const LineLayout *ll,
Sci::Line line, Sci::Line lineVisible, PRectangle rcLine, int xStart, int subLine) {
if ((vsDraw.viewIndentationGuides == ivLookForward || vsDraw.viewIndentationGuides == ivLookBoth)
&& (subLine == 0)) {
const Sci::Position posLineStart = model.pdoc->LineStart(line);
int indentSpace = model.pdoc->GetLineIndentation(line);
int xStartText = static_cast<int>(ll->positions[model.pdoc->GetLineIndentPosition(line) - posLineStart]);
// Find the most recent line with some text
Sci::Line lineLastWithText = line;
while (lineLastWithText > std::max(line - 20, static_cast<Sci::Line>(0)) && model.pdoc->IsWhiteLine(lineLastWithText)) {
lineLastWithText--;
}
if (lineLastWithText < line) {
xStartText = 100000; // Don't limit to visible indentation on empty line
// This line is empty, so use indentation of last line with text
int indentLastWithText = model.pdoc->GetLineIndentation(lineLastWithText);
const int isFoldHeader = model.pdoc->GetLevel(lineLastWithText) & SC_FOLDLEVELHEADERFLAG;
if (isFoldHeader) {
// Level is one more level than parent
indentLastWithText += model.pdoc->IndentSize();
}
if (vsDraw.viewIndentationGuides == ivLookForward) {
// In viLookForward mode, previous line only used if it is a fold header
if (isFoldHeader) {
indentSpace = std::max(indentSpace, indentLastWithText);
}
} else { // viLookBoth
indentSpace = std::max(indentSpace, indentLastWithText);
}
}
Sci::Line lineNextWithText = line;
while (lineNextWithText < std::min(line + 20, model.pdoc->LinesTotal()) && model.pdoc->IsWhiteLine(lineNextWithText)) {
lineNextWithText++;
}
if (lineNextWithText > line) {
xStartText = 100000; // Don't limit to visible indentation on empty line
// This line is empty, so use indentation of first next line with text
indentSpace = std::max(indentSpace,
model.pdoc->GetLineIndentation(lineNextWithText));
}
for (int indentPos = model.pdoc->IndentSize(); indentPos < indentSpace; indentPos += model.pdoc->IndentSize()) {
const XYPOSITION xIndent = floor(indentPos * vsDraw.spaceWidth);
if (xIndent < xStartText) {
DrawIndentGuide(surface, lineVisible, vsDraw.lineHeight, xIndent + xStart, rcLine,
(ll->xHighlightGuide == xIndent));
}
}
}
}
void EditView::DrawLine(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, const LineLayout *ll,
Sci::Line line, Sci::Line lineVisible, int xStart, PRectangle rcLine, int subLine, DrawPhase phase) {
if (subLine >= ll->lines) {
DrawAnnotation(surface, model, vsDraw, ll, line, xStart, rcLine, subLine, phase);
return; // No further drawing
}
// See if something overrides the line background color.
const ColourOptional background = vsDraw.Background(model.pdoc->GetMark(line), model.caret.active, ll->containsCaret);
const Sci::Position posLineStart = model.pdoc->LineStart(line);
const Range lineRange = ll->SubLineRange(subLine, LineLayout::Scope::visibleOnly);
const Range lineRangeIncludingEnd = ll->SubLineRange(subLine, LineLayout::Scope::includeEnd);
const XYACCUMULATOR subLineStart = ll->positions[lineRange.start];
if ((ll->wrapIndent != 0) && (subLine > 0)) {
if (phase & drawBack) {
DrawWrapIndentAndMarker(surface, vsDraw, ll, xStart, rcLine, background, customDrawWrapMarker, model.caret.active);
}
xStart += static_cast<int>(ll->wrapIndent);
}
if (phasesDraw != phasesOne) {
if (phase & drawBack) {
DrawBackground(surface, model, vsDraw, ll, rcLine, lineRange, posLineStart, xStart,
subLine, background);
DrawFoldDisplayText(surface, model, vsDraw, ll, line, xStart, rcLine, subLine, subLineStart, drawBack);
phase = static_cast<DrawPhase>(phase & ~drawBack); // Remove drawBack to not draw again in DrawFoldDisplayText
DrawEOL(surface, model, vsDraw, ll, rcLine, line, lineRange.end,
xStart, subLine, subLineStart, background);
if (vsDraw.IsLineFrameOpaque(model.caret.active, ll->containsCaret))
DrawCaretLineFramed(surface, vsDraw, ll, rcLine, subLine);
}
if (phase & drawIndicatorsBack) {
DrawIndicators(surface, model, vsDraw, ll, line, xStart, rcLine, subLine,
lineRangeIncludingEnd.end, true, tabWidthMinimumPixels);
DrawEdgeLine(surface, vsDraw, ll, rcLine, lineRange, xStart);
DrawMarkUnderline(surface, model, vsDraw, line, rcLine);
}
}
if (phase & drawText) {
DrawForeground(surface, model, vsDraw, ll, lineVisible, rcLine, lineRange, posLineStart, xStart,
subLine, background);
}
if (phase & drawIndentationGuides) {
DrawIndentGuidesOverEmpty(surface, model, vsDraw, ll, line, lineVisible, rcLine, xStart, subLine);
}
if (phase & drawIndicatorsFore) {
DrawIndicators(surface, model, vsDraw, ll, line, xStart, rcLine, subLine,
lineRangeIncludingEnd.end, false, tabWidthMinimumPixels);
}
DrawFoldDisplayText(surface, model, vsDraw, ll, line, xStart, rcLine, subLine, subLineStart, phase);
if (phasesDraw == phasesOne) {
DrawEOL(surface, model, vsDraw, ll, rcLine, line, lineRange.end,
xStart, subLine, subLineStart, background);
if (vsDraw.IsLineFrameOpaque(model.caret.active, ll->containsCaret))
DrawCaretLineFramed(surface, vsDraw, ll, rcLine, subLine);
DrawEdgeLine(surface, vsDraw, ll, rcLine, lineRange, xStart);
DrawMarkUnderline(surface, model, vsDraw, line, rcLine);
}
if (!hideSelection && (phase & drawSelectionTranslucent)) {
DrawTranslucentSelection(surface, model, vsDraw, ll, line, rcLine, subLine, lineRange, xStart, tabWidthMinimumPixels);
}
if (phase & drawLineTranslucent) {
DrawTranslucentLineState(surface, model, vsDraw, ll, line, rcLine, subLine);
}
}
static void DrawFoldLines(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, Sci::Line line, PRectangle rcLine) {
const bool expanded = model.pcs->GetExpanded(line);
const int level = model.pdoc->GetLevel(line);
const int levelNext = model.pdoc->GetLevel(line + 1);
if ((level & SC_FOLDLEVELHEADERFLAG) &&
(LevelNumber(level) < LevelNumber(levelNext))) {
// Paint the line above the fold
if ((expanded && (model.foldFlags & SC_FOLDFLAG_LINEBEFORE_EXPANDED))
||
(!expanded && (model.foldFlags & SC_FOLDFLAG_LINEBEFORE_CONTRACTED))) {
PRectangle rcFoldLine = rcLine;
rcFoldLine.bottom = rcFoldLine.top + 1;
surface->FillRectangle(rcFoldLine, vsDraw.styles[STYLE_DEFAULT].fore);
}
// Paint the line below the fold
if ((expanded && (model.foldFlags & SC_FOLDFLAG_LINEAFTER_EXPANDED))
||
(!expanded && (model.foldFlags & SC_FOLDFLAG_LINEAFTER_CONTRACTED))) {
PRectangle rcFoldLine = rcLine;
rcFoldLine.top = rcFoldLine.bottom - 1;
surface->FillRectangle(rcFoldLine, vsDraw.styles[STYLE_DEFAULT].fore);
}
}
}
void EditView::PaintText(Surface *surfaceWindow, const EditModel &model, PRectangle rcArea,
PRectangle rcClient, const ViewStyle &vsDraw) {
// Allow text at start of line to overlap 1 pixel into the margin as this displays
// serifs and italic stems for aliased text.
const int leftTextOverlap = ((model.xOffset == 0) && (vsDraw.leftMarginWidth > 0)) ? 1 : 0;
// Do the painting
if (rcArea.right > vsDraw.textStart - leftTextOverlap) {
Surface *surface = surfaceWindow;
if (bufferedDraw) {
surface = pixmapLine.get();
PLATFORM_ASSERT(pixmapLine->Initialised());
}
surface->SetUnicodeMode(SC_CP_UTF8 == model.pdoc->dbcsCodePage);
surface->SetDBCSMode(model.pdoc->dbcsCodePage);
surface->SetBidiR2L(model.BidirectionalR2L());
const Point ptOrigin = model.GetVisibleOriginInMain();
const int screenLinePaintFirst = static_cast<int>(rcArea.top) / vsDraw.lineHeight;
const int xStart = vsDraw.textStart - model.xOffset + static_cast<int>(ptOrigin.x);
SelectionPosition posCaret = model.sel.RangeMain().caret;
if (model.posDrag.IsValid())
posCaret = model.posDrag;
const Sci::Line lineCaret = model.pdoc->SciLineFromPosition(posCaret.Position());
PRectangle rcTextArea = rcClient;
if (vsDraw.marginInside) {
rcTextArea.left += vsDraw.textStart;
rcTextArea.right -= vsDraw.rightMarginWidth;
} else {
rcTextArea = rcArea;
}
// Remove selection margin from drawing area so text will not be drawn
// on it in unbuffered mode.
if (!bufferedDraw && vsDraw.marginInside) {
PRectangle rcClipText = rcTextArea;
rcClipText.left -= leftTextOverlap;
surfaceWindow->SetClip(rcClipText);
}
// Loop on visible lines
#if defined(TIME_PAINTING)
double durLayout = 0.0;
double durPaint = 0.0;
double durCopy = 0.0;
ElapsedPeriod epWhole;
#endif
const bool bracesIgnoreStyle = ((vsDraw.braceHighlightIndicatorSet && (model.bracesMatchStyle == STYLE_BRACELIGHT)) ||
(vsDraw.braceBadLightIndicatorSet && (model.bracesMatchStyle == STYLE_BRACEBAD)));
Sci::Line lineDocPrevious = -1; // Used to avoid laying out one document line multiple times
AutoLineLayout ll(llc, nullptr);
std::vector<DrawPhase> phases;
if ((phasesDraw == phasesMultiple) && !bufferedDraw) {
for (DrawPhase phase = drawBack; phase <= drawCarets; phase = static_cast<DrawPhase>(phase * 2)) {
phases.push_back(phase);
}
} else {
phases.push_back(drawAll);
}
for (const DrawPhase &phase : phases) {
int ypos = 0;
if (!bufferedDraw)
ypos += screenLinePaintFirst * vsDraw.lineHeight;
int yposScreen = screenLinePaintFirst * vsDraw.lineHeight;
Sci::Line visibleLine = model.TopLineOfMain() + screenLinePaintFirst;
while (visibleLine < model.pcs->LinesDisplayed() && yposScreen < rcArea.bottom) {
const Sci::Line lineDoc = model.pcs->DocFromDisplay(visibleLine);
// Only visible lines should be handled by the code within the loop
PLATFORM_ASSERT(model.pcs->GetVisible(lineDoc));
const Sci::Line lineStartSet = model.pcs->DisplayFromDoc(lineDoc);
const int subLine = static_cast<int>(visibleLine - lineStartSet);
// Copy this line and its styles from the document into local arrays
// and determine the x position at which each character starts.
#if defined(TIME_PAINTING)
ElapsedPeriod ep;
#endif
if (lineDoc != lineDocPrevious) {
ll.Set(nullptr);
ll.Set(RetrieveLineLayout(lineDoc, model));
LayoutLine(model, lineDoc, surface, vsDraw, ll, model.wrapWidth);
lineDocPrevious = lineDoc;
}
#if defined(TIME_PAINTING)
durLayout += ep.Duration(true);
#endif
if (ll) {
ll->containsCaret = !hideSelection && (lineDoc == lineCaret);
ll->hotspot = model.GetHotSpotRange();
PRectangle rcLine = rcTextArea;
rcLine.top = static_cast<XYPOSITION>(ypos);
rcLine.bottom = static_cast<XYPOSITION>(ypos + vsDraw.lineHeight);
const Range rangeLine(model.pdoc->LineStart(lineDoc),
model.pdoc->LineStart(lineDoc + 1));
// Highlight the current braces if any
ll->SetBracesHighlight(rangeLine, model.braces, static_cast<char>(model.bracesMatchStyle),
static_cast<int>(model.highlightGuideColumn * vsDraw.spaceWidth), bracesIgnoreStyle);
if (leftTextOverlap && (bufferedDraw || ((phasesDraw < phasesMultiple) && (phase & drawBack)))) {
// Clear the left margin
PRectangle rcSpacer = rcLine;
rcSpacer.right = rcSpacer.left;
rcSpacer.left -= 1;
surface->FillRectangle(rcSpacer, vsDraw.styles[STYLE_DEFAULT].back);
}
if (model.BidirectionalEnabled()) {
// Fill the line bidi data
UpdateBidiData(model, vsDraw, ll);
}
DrawLine(surface, model, vsDraw, ll, lineDoc, visibleLine, xStart, rcLine, subLine, phase);
#if defined(TIME_PAINTING)
durPaint += ep.Duration(true);
#endif
// Restore the previous styles for the brace highlights in case layout is in cache.
ll->RestoreBracesHighlight(rangeLine, model.braces, bracesIgnoreStyle);
if (phase & drawFoldLines) {
DrawFoldLines(surface, model, vsDraw, lineDoc, rcLine);
}
if (phase & drawCarets) {
DrawCarets(surface, model, vsDraw, ll, lineDoc, xStart, rcLine, subLine);
}
if (bufferedDraw) {
const Point from = Point::FromInts(vsDraw.textStart - leftTextOverlap, 0);
const PRectangle rcCopyArea = PRectangle::FromInts(vsDraw.textStart - leftTextOverlap, yposScreen,
static_cast<int>(rcClient.right - vsDraw.rightMarginWidth),
yposScreen + vsDraw.lineHeight);
surfaceWindow->Copy(rcCopyArea, from, *pixmapLine);
}
lineWidthMaxSeen = std::max(
lineWidthMaxSeen, static_cast<int>(ll->positions[ll->numCharsInLine]));
#if defined(TIME_PAINTING)
durCopy += ep.Duration(true);
#endif
}
if (!bufferedDraw) {
ypos += vsDraw.lineHeight;
}
yposScreen += vsDraw.lineHeight;
visibleLine++;
}
}
ll.Set(nullptr);
#if defined(TIME_PAINTING)
if (durPaint < 0.00000001)
durPaint = 0.00000001;
#endif
// Right column limit indicator
PRectangle rcBeyondEOF = (vsDraw.marginInside) ? rcClient : rcArea;
rcBeyondEOF.left = static_cast<XYPOSITION>(vsDraw.textStart);
rcBeyondEOF.right = rcBeyondEOF.right - ((vsDraw.marginInside) ? vsDraw.rightMarginWidth : 0);
rcBeyondEOF.top = static_cast<XYPOSITION>((model.pcs->LinesDisplayed() - model.TopLineOfMain()) * vsDraw.lineHeight);
if (rcBeyondEOF.top < rcBeyondEOF.bottom) {
surfaceWindow->FillRectangle(rcBeyondEOF, vsDraw.styles[STYLE_DEFAULT].back);
if (vsDraw.edgeState == EDGE_LINE) {
const int edgeX = static_cast<int>(vsDraw.theEdge.column * vsDraw.spaceWidth);
rcBeyondEOF.left = static_cast<XYPOSITION>(edgeX + xStart);
rcBeyondEOF.right = rcBeyondEOF.left + 1;
surfaceWindow->FillRectangle(rcBeyondEOF, vsDraw.theEdge.colour);
} else if (vsDraw.edgeState == EDGE_MULTILINE) {
for (size_t edge = 0; edge < vsDraw.theMultiEdge.size(); edge++) {
if (vsDraw.theMultiEdge[edge].column >= 0) {
const int edgeX = static_cast<int>(vsDraw.theMultiEdge[edge].column * vsDraw.spaceWidth);
rcBeyondEOF.left = static_cast<XYPOSITION>(edgeX + xStart);
rcBeyondEOF.right = rcBeyondEOF.left + 1;
surfaceWindow->FillRectangle(rcBeyondEOF, vsDraw.theMultiEdge[edge].colour);
}
}
}
}
//Platform::DebugPrintf("start display %d, offset = %d\n", model.pdoc->Length(), model.xOffset);
#if defined(TIME_PAINTING)
Platform::DebugPrintf(
"Layout:%9.6g Paint:%9.6g Ratio:%9.6g Copy:%9.6g Total:%9.6g\n",
durLayout, durPaint, durLayout / durPaint, durCopy, epWhole.Duration());
#endif
}
}
void EditView::FillLineRemainder(Surface *surface, const EditModel &model, const ViewStyle &vsDraw, const LineLayout *ll,
Sci::Line line, PRectangle rcArea, int subLine) const {
int eolInSelection = 0;
int alpha = SC_ALPHA_NOALPHA;
if (!hideSelection) {
const Sci::Position posAfterLineEnd = model.pdoc->LineStart(line + 1);
eolInSelection = (subLine == (ll->lines - 1)) ? model.sel.InSelectionForEOL(posAfterLineEnd) : 0;
alpha = (eolInSelection == 1) ? vsDraw.selAlpha : vsDraw.selAdditionalAlpha;
}
const ColourOptional background = vsDraw.Background(model.pdoc->GetMark(line), model.caret.active, ll->containsCaret);
if (eolInSelection && vsDraw.selEOLFilled && vsDraw.selColours.back.isSet && (line < model.pdoc->LinesTotal() - 1) && (alpha == SC_ALPHA_NOALPHA)) {
surface->FillRectangle(rcArea, SelectionBackground(vsDraw, eolInSelection == 1, model.primarySelection));
} else {
if (background.isSet) {
surface->FillRectangle(rcArea, background);
} else if (vsDraw.styles[ll->styles[ll->numCharsInLine]].eolFilled) {
surface->FillRectangle(rcArea, vsDraw.styles[ll->styles[ll->numCharsInLine]].back);
} else {
surface->FillRectangle(rcArea, vsDraw.styles[STYLE_DEFAULT].back);
}
if (eolInSelection && vsDraw.selEOLFilled && vsDraw.selColours.back.isSet && (line < model.pdoc->LinesTotal() - 1) && (alpha != SC_ALPHA_NOALPHA)) {
SimpleAlphaRectangle(surface, rcArea, SelectionBackground(vsDraw, eolInSelection == 1, model.primarySelection), alpha);
}
}
}
// Space (3 space characters) between line numbers and text when printing.
#define lineNumberPrintSpace " "
static ColourDesired InvertedLight(ColourDesired orig) {
unsigned int r = orig.GetRed();
unsigned int g = orig.GetGreen();
unsigned int b = orig.GetBlue();
const unsigned int l = (r + g + b) / 3; // There is a better calculation for this that matches human eye
const unsigned int il = 0xff - l;
if (l == 0)
return ColourDesired(0xff, 0xff, 0xff);
r = r * il / l;
g = g * il / l;
b = b * il / l;
return ColourDesired(std::min(r, 0xffu), std::min(g, 0xffu), std::min(b, 0xffu));
}
Sci::Position EditView::FormatRange(bool draw, const Sci_RangeToFormat *pfr, Surface *surface, Surface *surfaceMeasure,
const EditModel &model, const ViewStyle &vs) {
// Can't use measurements cached for screen
posCache.Clear();
ViewStyle vsPrint(vs);
vsPrint.technology = SC_TECHNOLOGY_DEFAULT;
// Modify the view style for printing as do not normally want any of the transient features to be printed
// Printing supports only the line number margin.
int lineNumberIndex = -1;
for (size_t margin = 0; margin < vs.ms.size(); margin++) {
if ((vsPrint.ms[margin].style == SC_MARGIN_NUMBER) && (vsPrint.ms[margin].width > 0)) {
lineNumberIndex = static_cast<int>(margin);
} else {
vsPrint.ms[margin].width = 0;
}
}
vsPrint.fixedColumnWidth = 0;
vsPrint.zoomLevel = printParameters.magnification;
// Don't show indentation guides
// If this ever gets changed, cached pixmap would need to be recreated if technology != SC_TECHNOLOGY_DEFAULT
vsPrint.viewIndentationGuides = ivNone;
// Don't show the selection when printing
vsPrint.selColours.back.isSet = false;
vsPrint.selColours.fore.isSet = false;
vsPrint.selAlpha = SC_ALPHA_NOALPHA;
vsPrint.selAdditionalAlpha = SC_ALPHA_NOALPHA;
vsPrint.whitespaceColours.back.isSet = false;
vsPrint.whitespaceColours.fore.isSet = false;
vsPrint.showCaretLineBackground = false;
vsPrint.alwaysShowCaretLineBackground = false;
// Don't highlight matching braces using indicators
vsPrint.braceHighlightIndicatorSet = false;
vsPrint.braceBadLightIndicatorSet = false;
// Set colours for printing according to users settings
for (size_t sty = 0; sty < vsPrint.styles.size(); sty++) {
if (printParameters.colourMode == SC_PRINT_INVERTLIGHT) {
vsPrint.styles[sty].fore = InvertedLight(vsPrint.styles[sty].fore);
vsPrint.styles[sty].back = InvertedLight(vsPrint.styles[sty].back);
} else if (printParameters.colourMode == SC_PRINT_BLACKONWHITE) {
vsPrint.styles[sty].fore = ColourDesired(0, 0, 0);
vsPrint.styles[sty].back = ColourDesired(0xff, 0xff, 0xff);
} else if (printParameters.colourMode == SC_PRINT_COLOURONWHITE) {
vsPrint.styles[sty].back = ColourDesired(0xff, 0xff, 0xff);
} else if (printParameters.colourMode == SC_PRINT_COLOURONWHITEDEFAULTBG) {
if (sty <= STYLE_DEFAULT) {
vsPrint.styles[sty].back = ColourDesired(0xff, 0xff, 0xff);
}
}
}
// White background for the line numbers if SC_PRINT_SCREENCOLOURS isn't used
if (printParameters.colourMode != SC_PRINT_SCREENCOLOURS)
vsPrint.styles[STYLE_LINENUMBER].back = ColourDesired(0xff, 0xff, 0xff);
// Printing uses different margins, so reset screen margins
vsPrint.leftMarginWidth = 0;
vsPrint.rightMarginWidth = 0;
vsPrint.Refresh(*surfaceMeasure, model.pdoc->tabInChars);
// Determining width must happen after fonts have been realised in Refresh
int lineNumberWidth = 0;
if (lineNumberIndex >= 0) {
lineNumberWidth = static_cast<int>(surfaceMeasure->WidthText(vsPrint.styles[STYLE_LINENUMBER].font,
"99999" lineNumberPrintSpace));
vsPrint.ms[lineNumberIndex].width = lineNumberWidth;
vsPrint.Refresh(*surfaceMeasure, model.pdoc->tabInChars); // Recalculate fixedColumnWidth
}
const Sci::Line linePrintStart =
model.pdoc->SciLineFromPosition(static_cast<Sci::Position>(pfr->chrg.cpMin));
Sci::Line linePrintLast = linePrintStart + (pfr->rc.bottom - pfr->rc.top) / vsPrint.lineHeight - 1;
if (linePrintLast < linePrintStart)
linePrintLast = linePrintStart;
const Sci::Line linePrintMax =
model.pdoc->SciLineFromPosition(static_cast<Sci::Position>(pfr->chrg.cpMax));
if (linePrintLast > linePrintMax)
linePrintLast = linePrintMax;
//Platform::DebugPrintf("Formatting lines=[%0d,%0d,%0d] top=%0d bottom=%0d line=%0d %0d\n",
// linePrintStart, linePrintLast, linePrintMax, pfr->rc.top, pfr->rc.bottom, vsPrint.lineHeight,
// surfaceMeasure->Height(vsPrint.styles[STYLE_LINENUMBER].font));
Sci::Position endPosPrint = model.pdoc->Length();
if (linePrintLast < model.pdoc->LinesTotal())
endPosPrint = model.pdoc->LineStart(linePrintLast + 1);
// Ensure we are styled to where we are formatting.
model.pdoc->EnsureStyledTo(endPosPrint);
const int xStart = vsPrint.fixedColumnWidth + pfr->rc.left;
int ypos = pfr->rc.top;
Sci::Line lineDoc = linePrintStart;
Sci::Position nPrintPos = static_cast<Sci::Position>(pfr->chrg.cpMin);
int visibleLine = 0;
int widthPrint = pfr->rc.right - pfr->rc.left - vsPrint.fixedColumnWidth;
if (printParameters.wrapState == eWrapNone)
widthPrint = LineLayout::wrapWidthInfinite;
while (lineDoc <= linePrintLast && ypos < pfr->rc.bottom) {
// When printing, the hdc and hdcTarget may be the same, so
// changing the state of surfaceMeasure may change the underlying
// state of surface. Therefore, any cached state is discarded before
// using each surface.
surfaceMeasure->FlushCachedState();
// Copy this line and its styles from the document into local arrays
// and determine the x position at which each character starts.
LineLayout ll(static_cast<int>(model.pdoc->LineStart(lineDoc + 1) - model.pdoc->LineStart(lineDoc) + 1));
LayoutLine(model, lineDoc, surfaceMeasure, vsPrint, &ll, widthPrint);
ll.containsCaret = false;
PRectangle rcLine = PRectangle::FromInts(
pfr->rc.left,
ypos,
pfr->rc.right - 1,
ypos + vsPrint.lineHeight);
// When document line is wrapped over multiple display lines, find where
// to start printing from to ensure a particular position is on the first
// line of the page.
if (visibleLine == 0) {
const Sci::Position startWithinLine = nPrintPos -
model.pdoc->LineStart(lineDoc);
for (int iwl = 0; iwl < ll.lines - 1; iwl++) {
if (ll.LineStart(iwl) <= startWithinLine && ll.LineStart(iwl + 1) >= startWithinLine) {
visibleLine = -iwl;
}
}
if (ll.lines > 1 && startWithinLine >= ll.LineStart(ll.lines - 1)) {
visibleLine = -(ll.lines - 1);
}
}
if (draw && lineNumberWidth &&
(ypos + vsPrint.lineHeight <= pfr->rc.bottom) &&
(visibleLine >= 0)) {
const std::string number = std::to_string(lineDoc + 1) + lineNumberPrintSpace;
PRectangle rcNumber = rcLine;
rcNumber.right = rcNumber.left + lineNumberWidth;
// Right justify
rcNumber.left = rcNumber.right - surfaceMeasure->WidthText(
vsPrint.styles[STYLE_LINENUMBER].font, number);
surface->FlushCachedState();
surface->DrawTextNoClip(rcNumber, vsPrint.styles[STYLE_LINENUMBER].font,
static_cast<XYPOSITION>(ypos + vsPrint.maxAscent), number,
vsPrint.styles[STYLE_LINENUMBER].fore,
vsPrint.styles[STYLE_LINENUMBER].back);
}
// Draw the line
surface->FlushCachedState();
for (int iwl = 0; iwl < ll.lines; iwl++) {
if (ypos + vsPrint.lineHeight <= pfr->rc.bottom) {
if (visibleLine >= 0) {
if (draw) {
rcLine.top = static_cast<XYPOSITION>(ypos);
rcLine.bottom = static_cast<XYPOSITION>(ypos + vsPrint.lineHeight);
DrawLine(surface, model, vsPrint, &ll, lineDoc, visibleLine, xStart, rcLine, iwl, drawAll);
}
ypos += vsPrint.lineHeight;
}
visibleLine++;
if (iwl == ll.lines - 1)
nPrintPos = model.pdoc->LineStart(lineDoc + 1);
else
nPrintPos += ll.LineStart(iwl + 1) - ll.LineStart(iwl);
}
}
++lineDoc;
}
// Clear cache so measurements are not used for screen
posCache.Clear();
return nPrintPos;
}
| [
"noreply@github.com"
] | tobeypeters.noreply@github.com |
99cdc2d23710339b1d103c7a8e0ffa64a1a43032 | ead0b1c60e787f319242de5a56d246991d6e5464 | /test/TestApp/GDK/ATGTK/SampleGUI.h | 74ae6b0d97f80f0b393562d33585ca3645af1e11 | [] | no_license | jplafonta/XPlatCSdk | fbc9edcf7dadf88c5e20f26b6deaafa3bb512909 | 302c021dcfd7518959551b33c65499a45d7829de | refs/heads/main | 2023-07-30T04:54:27.901376 | 2021-08-31T14:26:52 | 2021-08-31T14:26:52 | 347,189,117 | 0 | 0 | null | 2021-04-15T01:09:33 | 2021-03-12T20:26:17 | C++ | UTF-8 | C++ | false | false | 36,089 | h | //--------------------------------------------------------------------------------------
// File: SampleGUI.h
//
// A simple set of UI widgets for use in ATG samples
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//-------------------------------------------------------------------------------------
#pragma once
#include "GamePad.h"
#include "Keyboard.h"
#include "Mouse.h"
#if defined(__d3d12_h__) || defined(__d3d12_x_h__) || defined(__XBOX_D3D12_X__)
#include "DescriptorHeap.h"
#include "ResourceUploadBatch.h"
#endif
#include <wchar.h>
#include <algorithm>
#include <functional>
#include <memory>
#include <string>
#include <vector>
#ifndef _CPPRTTI
#error ATG Sample GUI requires RTTI
#endif
namespace ATG
{
class IPanel;
//----------------------------------------------------------------------------------
// A control is an individual UI element
class IControl
{
public:
virtual ~IControl() {}
// Methods
virtual void Render() = 0;
virtual bool Contains(long x, long y) const
{
return (m_screenRect.left <= x) && (x < m_screenRect.right) && (m_screenRect.top <= y) && (y < m_screenRect.bottom);
}
virtual void ComputeLayout(const RECT& parent);
virtual void ComputeLayout(const RECT& bounds, float dx, float dy);
virtual bool CanFocus() const { return false; }
virtual bool DefaultFocus() const { return false; }
virtual void OnFocus(bool in)
{
m_focus = in;
if (in && m_focusCb)
{
m_focusCb(nullptr, this);
}
}
virtual bool OnSelected(IPanel*) { return false; }
virtual bool Update(float /*elapsedTime*/, const DirectX::GamePad::State&) { return false; }
virtual bool Update(float /*elapsedTime*/, const DirectX::Mouse::State&, const DirectX::Keyboard::State&) { return false; }
// Properties
using callback_t = std::function<void(_In_ IPanel*, _In_ IControl*)>;
void SetCallback(_In_opt_ callback_t callback)
{
m_callBack = callback;
}
void SetFocusCb(_In_opt_ callback_t callback)
{
m_focusCb = callback;
}
unsigned GetHotKey() const { return m_hotKey; }
void SetHotKey(unsigned hotkey) { m_hotKey = hotkey; }
void SetId(unsigned id) { m_id = id; }
unsigned GetId() const { return m_id; }
void SetUser(void* user) { m_user = user; }
void* GetUser() const { return m_user; }
void SetParent(IPanel* panel) { m_parent = panel; }
void SetVisible(bool visible = true);
bool IsVisible() const { return m_visible; }
const RECT* GetRectangle() const { return &m_screenRect; }
protected:
IControl(const RECT& rect, unsigned id) :
m_visible(true),
m_focus(false),
m_layoutRect(rect),
m_screenRect(rect),
m_hotKey(0),
m_id(id),
m_user(nullptr),
m_parent(nullptr)
{
}
bool m_visible;
bool m_focus;
RECT m_layoutRect;
RECT m_screenRect;
callback_t m_callBack;
callback_t m_focusCb;
unsigned m_hotKey;
unsigned m_id;
void* m_user;
IPanel* m_parent;
};
// Static text label
class TextLabel : public IControl
{
public:
TextLabel(unsigned id, _In_z_ const wchar_t* text, const RECT& rect, unsigned style = 0);
// Properties
void XM_CALLCONV SetForegroundColor(DirectX::FXMVECTOR color) { DirectX::XMStoreFloat4(&m_fgColor, color); }
void XM_CALLCONV SetBackgroundColor(DirectX::FXMVECTOR color) { DirectX::XMStoreFloat4(&m_bgColor, color); }
static const unsigned c_StyleAlignLeft = 0;
static const unsigned c_StyleAlignCenter = 0x1;
static const unsigned c_StyleAlignRight = 0x2;
static const unsigned c_StyleAlignTop = 0x0;
static const unsigned c_StyleAlignMiddle = 0x4;
static const unsigned c_StyleAlignBottom = 0x8;
static const unsigned c_StyleTransparent = 0x10;
static const unsigned c_StyleWordWrap = 0x20;
static const unsigned c_StyleFontSmall = 0x10000;
static const unsigned c_StyleFontMid = 0;
static const unsigned c_StyleFontLarge = 0x20000;
static const unsigned c_StyleFontBold = 0x40000;
static const unsigned c_StyleFontItalic = 0x80000;
void SetStyle(unsigned style) { m_style = style; }
unsigned GetStyle() const { return m_style; }
void SetText(const wchar_t* text);
const wchar_t* GetText() const { return m_text.c_str(); }
// IControl
void Render() override;
void ComputeLayout(const RECT& parent) override;
void ComputeLayout(const RECT& bounds, float dx, float dy) override;
bool Contains(long, long) const override { return false; }
private:
unsigned m_style;
DirectX::XMFLOAT4 m_fgColor;
DirectX::XMFLOAT4 m_bgColor;
std::wstring m_text;
std::wstring m_wordWrap;
};
// Static image
class Image : public IControl
{
public:
Image(unsigned id, unsigned imageId, const RECT& rect);
void SetImageId(unsigned imageId) { m_imageId = imageId; }
unsigned GetImageId() const { return m_imageId; }
// IControl
void Render() override;
bool Contains(long, long) const override { return false; }
private:
unsigned m_imageId;
};
// Static text label that supports the controller font
class Legend : public IControl
{
public:
Legend(unsigned id, _In_z_ const wchar_t* text, const RECT& rect, unsigned style = 0);
// Properties
void XM_CALLCONV SetForegroundColor(DirectX::FXMVECTOR color) { DirectX::XMStoreFloat4(&m_fgColor, color); }
void XM_CALLCONV SetBackgroundColor(DirectX::FXMVECTOR color) { DirectX::XMStoreFloat4(&m_bgColor, color); }
static const unsigned c_StyleAlignLeft = 0;
static const unsigned c_StyleAlignCenter = 0x1;
static const unsigned c_StyleAlignRight = 0x2;
static const unsigned c_StyleAlignTop = 0x0;
static const unsigned c_StyleAlignMiddle = 0x4;
static const unsigned c_StyleAlignBottom = 0x8;
static const unsigned c_StyleTransparent = 0x10;
static const unsigned c_StyleFontSmall = 0x10000;
static const unsigned c_StyleFontMid = 0;
static const unsigned c_StyleFontLarge = 0x20000;
static const unsigned c_StyleFontBold = 0x40000;
static const unsigned c_StyleFontItalic = 0x80000;
void SetStyle(unsigned style) { m_style = style; }
unsigned GetStyle() const { return m_style; }
void SetText(const wchar_t* text) { m_text = text; }
const wchar_t* GetText() const { return m_text.c_str(); }
// IControl
void Render() override;
bool Contains(long, long) const override { return false; }
private:
unsigned m_style;
DirectX::XMFLOAT4 m_bgColor;
DirectX::XMFLOAT4 m_fgColor;
std::wstring m_text;
};
// Pressable button
class Button : public IControl
{
public:
Button(unsigned id, _In_z_ const wchar_t* text, const RECT& rect);
// Properties
void ShowBorder(bool show = true) { m_showBorder = show; }
void NoFocusColor(bool noFocusColor = true) { m_noFocusColor = noFocusColor; }
void FocusOnText(bool focusOnText = true ) { m_focusOnText = focusOnText; }
void SetEnabled(bool enabled = true) { m_enabled = enabled; }
bool IsEnabled() const { return m_enabled; }
void XM_CALLCONV SetColor(DirectX::FXMVECTOR color) { DirectX::XMStoreFloat4(&m_color, color); }
static const unsigned c_StyleExit = 0x1;
static const unsigned c_StyleDefault = 0x2;
static const unsigned c_StyleTransparent = 0x4;
static const unsigned c_StyleFontSmall = 0x10000;
static const unsigned c_StyleFontMid = 0;
static const unsigned c_StyleFontLarge = 0x20000;
static const unsigned c_StyleFontBold = 0x40000;
static const unsigned c_StyleFontItalic = 0x80000;
void SetStyle(unsigned style) { m_style = style; }
unsigned GetStyle() const { return m_style; }
void SetText(const wchar_t* text) { m_text = text; }
const wchar_t* GetText() const { return m_text.c_str(); }
// IControl
void Render() override;
bool CanFocus() const override { return m_enabled; }
bool DefaultFocus() const override { return (m_style & c_StyleDefault) != 0; }
bool OnSelected(IPanel* panel) override;
private:
bool m_enabled;
bool m_showBorder;
bool m_noFocusColor;
bool m_focusOnText;
unsigned m_style;
std::wstring m_text;
DirectX::XMFLOAT4 m_color;
};
// Pressable image
class ImageButton : public IControl
{
public:
ImageButton(unsigned id, unsigned imageId, const RECT& rect);
// Properties
void SetEnabled(bool enabled = true) { m_enabled = enabled; }
bool IsEnabled() const { return m_enabled; }
static const unsigned c_StyleExit = 0x1;
static const unsigned c_StyleDefault = 0x2;
static const unsigned c_StyleBackground = 0x4;
static const unsigned c_StyleTransparent = 0x8;
void SetStyle(unsigned style) { m_style = style; }
unsigned GetStyle() const { return m_style; }
void SetImageId(unsigned imageId) { m_imageId = imageId; }
unsigned GetImageId() const { return m_imageId; }
// IControl
void Render() override;
bool CanFocus() const override { return m_enabled; }
bool DefaultFocus() const override { return (m_style & c_StyleDefault) != 0; }
bool OnSelected(IPanel* panel) override;
private:
bool m_enabled;
unsigned m_style;
unsigned m_imageId;
};
// Two-state check box
class CheckBox : public IControl
{
public:
CheckBox(unsigned id, _In_z_ const wchar_t* text, const RECT& rect, bool checked = false);
// Properties
void SetEnabled(bool enabled = true) { m_enabled = enabled; }
bool IsEnabled() const { return m_enabled; }
void SetChecked(bool checked = true) { m_checked = checked; }
bool IsChecked() const { return m_checked; }
static const unsigned c_StyleTransparent = 0x1;
static const unsigned c_StyleFontSmall = 0x10000;
static const unsigned c_StyleFontMid = 0;
static const unsigned c_StyleFontLarge = 0x20000;
static const unsigned c_StyleFontBold = 0x40000;
static const unsigned c_StyleFontItalic = 0x80000;
void SetStyle(unsigned style) { m_style = style; }
unsigned GetStyle() const { return m_style; }
void SetText(const wchar_t* text) { m_text = text; }
const wchar_t* GetText() const { return m_text.c_str(); }
// IControl
void Render() override;
bool CanFocus() const override { return m_enabled; }
bool OnSelected(IPanel* panel) override;
private:
bool m_enabled;
bool m_checked;
unsigned m_style;
std::wstring m_text;
};
// Slider
class Slider : public IControl
{
public:
Slider(unsigned id, const RECT& rect, int value = 50, int minValue = 0, int maxValue = 100);
// Properties
void SetEnabled(bool enabled = true) { m_enabled = enabled; if (!enabled) m_dragging = false; }
bool IsEnabled() const { return m_enabled; }
static const unsigned c_StyleTransparent = 0x1;
void SetStyle(unsigned style) { m_style = style; }
unsigned GetStyle() const { return m_style; }
void SetValue(int value);
int GetValue() const { return m_value; }
void SetRange(int minValue, int maxValue);
void GetRange(int& minValue, int& maxValue) const { minValue = m_minValue; maxValue = m_maxValue; }
// IControl
void Render() override;
bool CanFocus() const override { return m_enabled; }
void OnFocus(bool in) override;
bool Update(float elapsedTime, const DirectX::GamePad::State& pad) override;
bool Update(float elapsedTime, const DirectX::Mouse::State& mstate, const DirectX::Keyboard::State& kbstate) override;
private:
bool m_enabled;
bool m_dragging;
unsigned m_style;
int m_value;
int m_minValue;
int m_maxValue;
RECT m_thumbRect;
};
// Progress bar that goes from 0.0 to 1.0
class ProgressBar : public IControl
{
public:
ProgressBar(unsigned id, const RECT& rect, bool visible = false, float start = 0.f);
~ProgressBar();
// Properties
void SetProgress(float progress) { m_progress = std::min( std::max(progress, 0.f), 1.f); }
float GetProgress() const { return m_progress; }
void ShowPercentage(bool show = true) { m_showPct = show; }
// IControl
void Render() override;
private:
float m_progress;
bool m_showPct;
};
// TextList
class TextList : public IControl
{
public:
TextList(unsigned id, const RECT& rect, unsigned style = 0, int itemHeight = 0);
~TextList();
// Items
struct Item
{
std::wstring text;
DirectX::XMFLOAT4 color;
};
void XM_CALLCONV AddItem(_In_z_ const wchar_t* text, DirectX::FXMVECTOR color = DirectX::Colors::White);
void XM_CALLCONV InsertItem(int index, _In_z_ const wchar_t* text, DirectX::FXMVECTOR color = DirectX::Colors::White);
void RemoveItem(int index);
void RemoveAllItems();
// IControl
void Render() override;
bool CanFocus() const override { return false; }
bool Update(float elapsedTime, const DirectX::GamePad::State& pad) override;
bool Update(float elapsedTime, const DirectX::Mouse::State& mstate, const DirectX::Keyboard::State& kbstate) override;
private:
int m_itemHeight;
unsigned m_style;
int m_topItem;
RECT m_itemRect;
int m_lastHeight;
std::vector<Item> m_items;
};
// List box
class ListBox : public IControl
{
public:
ListBox(unsigned id, const RECT& rect, unsigned style = 0, int itemHeight = 0);
~ListBox();
// Items
struct Item
{
std::wstring text;
void* user;
bool selected;
Item() : user(nullptr), selected(false) {}
// TODO - add optional image
};
void AddItem(_In_z_ const wchar_t* text, _In_opt_ void *user = nullptr);
void InsertItem(int index, _In_z_ const wchar_t* text, _In_opt_ void *user = nullptr);
void RemoveItem(int index);
void RemoveAllItems();
int GetSelectedItem() const;
std::vector<int> GetSelectedItems() const;
void ClearSelection();
void SelectItem(int index);
const Item* GetItem(int index) const { return &m_items[size_t(index)]; }
Item* GetItem(int index) { return &m_items[size_t(index)]; }
// Properties
void SetEnabled(bool enabled = true) { m_enabled = enabled; }
bool IsEnabled() const { return m_enabled; }
static const unsigned c_StyleMultiSelection = 0x1;
static const unsigned c_StyleTransparent = 0x2;
static const unsigned c_StyleScrollBar = 0x4;
static const unsigned c_StyleFontSmall = 0x10000;
static const unsigned c_StyleFontMid = 0;
static const unsigned c_StyleFontLarge = 0x20000;
static const unsigned c_StyleFontBold = 0x40000;
static const unsigned c_StyleFontItalic = 0x80000;
void SetStyle(unsigned style) { m_style = style; }
unsigned GetStyle() const { return m_style; }
// IControl
void Render() override;
bool CanFocus() const override { return m_enabled; }
bool Update(float elapsedTime, const DirectX::GamePad::State& pad) override;
bool Update(float elapsedTime, const DirectX::Mouse::State& mstate, const DirectX::Keyboard::State& kbstate) override;
private:
bool m_enabled;
int m_itemHeight;
unsigned m_style;
int m_topItem;
int m_focusItem;
RECT m_itemRect;
RECT m_scrollRect;
RECT m_trackRect;
RECT m_thumbRect;
int m_lastHeight;
std::vector<Item> m_items;
void UpdateRects();
};
// Text box
class TextBox : public IControl
{
public:
TextBox(unsigned id, _In_z_ const wchar_t* text, const RECT& rect, unsigned style = 0);
~TextBox();
// Properties
void XM_CALLCONV SetForegroundColor(DirectX::FXMVECTOR color) { DirectX::XMStoreFloat4(&m_color, color); }
static const unsigned c_StyleTransparent = 0x1;
static const unsigned c_StyleScrollBar = 0x2;
static const unsigned c_StyleNoBackground = 0x4;
static const unsigned c_StyleFontSmall = 0x10000;
static const unsigned c_StyleFontMid = 0;
static const unsigned c_StyleFontLarge = 0x20000;
static const unsigned c_StyleFontBold = 0x40000;
static const unsigned c_StyleFontItalic = 0x80000;
void SetStyle(unsigned style) { m_style = style; }
unsigned GetStyle() const { return m_style; }
void SetText(const wchar_t* text);
const wchar_t* GetText() const { return m_text.c_str(); }
// IControl
void Render() override;
void ComputeLayout(const RECT& parent) override;
void ComputeLayout(const RECT& bounds, float dx, float dy) override;
bool CanFocus() const override { return true; }
bool Update(float elapsedTime, const DirectX::GamePad::State& pad) override;
bool Update(float elapsedTime, const DirectX::Mouse::State& mstate, const DirectX::Keyboard::State& kbstate) override;
private:
unsigned m_style;
int m_topLine;
RECT m_itemRect;
RECT m_scrollRect;
RECT m_trackRect;
RECT m_thumbRect;
int m_lastHeight;
DirectX::XMFLOAT4 m_color;
std::wstring m_text;
std::wstring m_wordWrap;
std::vector<size_t> m_wordWrapLines;
int m_lastWheelValue;
void UpdateRects();
};
//----------------------------------------------------------------------------------
// A panel is a container for UI controls
class IPanel
{
public:
virtual ~IPanel() {}
// Methods
virtual void Show() = 0;
virtual void Render() = 0;
virtual bool Update(float elapsedTime, const DirectX::GamePad::State& pad) = 0;
virtual bool Update(float elapsedTime, const DirectX::Mouse::State& mstate, const DirectX::Keyboard::State& kbstate) = 0;
virtual void Update(float /*elapsedTime*/) { };
virtual void Close() = 0;
virtual void Cancel() {}
virtual void Add(_In_ IControl* ctrl) = 0;
virtual IControl* Find(unsigned id) = 0;
virtual void SetFocus(_In_ IControl*) {}
virtual void OnWindowSize(const RECT& layout) = 0;
// Properties
using callback_t = std::function<void(_In_ IPanel*, unsigned)>;
void SetCallback(_In_opt_ callback_t callback)
{
m_callBack = callback;
}
void SetUser(void* user) { m_user = user; }
void* GetUser() const { return m_user; }
bool IsVisible() const { return m_visible; }
protected:
IPanel(const RECT& rect) :
m_visible(false),
m_layoutRect(rect),
m_screenRect(rect),
m_user(nullptr)
{
}
bool m_visible;
RECT m_layoutRect;
RECT m_screenRect;
callback_t m_callBack;
void* m_user;
};
// Style flags for Popup and Overlay
const unsigned int c_styleCustomPanel = 1; // Use this if you want a custom panel where you add controls programatically
const unsigned int c_stylePopupEmphasis = 2; // Fades out other UI elements when rendering the popup in order to give it emphasis
const unsigned int c_styleSuppressCancel = 4; // Suppress the default cancel behavior that would normally occur when 'B' is pressed
class Popup : public IPanel
{
public:
Popup(const RECT& rect, unsigned int styleFlags = 0);
~Popup();
// IPanel
void Show() override;
void Render() override;
bool Update(float elapsedTime, const DirectX::GamePad::State& pad) override;
bool Update(float elapsedTime, const DirectX::Mouse::State& mstate, const DirectX::Keyboard::State& kbstate) override;
void Update(float) override {}
void Close() override;
void Cancel() override;
void Add(_In_ IControl* ctrl) override;
IControl* Find(unsigned id) override;
void SetFocus(_In_ IControl* ctrl) override;
void OnWindowSize(const RECT& layout) override;
private:
bool m_select;
bool m_cancel;
bool m_suppressCancel;
bool m_emphasis;
const bool m_custom;
IControl* m_focusControl;
std::vector<IControl*> m_controls;
};
class HUD : public IPanel
{
public:
HUD(const RECT& rect);
~HUD();
// IPanel
void Show() override;
void Render() override;
bool Update(float, const DirectX::GamePad::State&) override { return false; }
bool Update(float, const DirectX::Mouse::State&, const DirectX::Keyboard::State&) override { return false; }
void Update(float) override {}
void Close() override;
void Add(_In_ IControl* ctrl) override;
IControl* Find(unsigned id) override;
void OnWindowSize(const RECT& layout) override;
private:
std::vector<IControl*> m_controls;
};
class Overlay : public IPanel
{
public:
Overlay(const RECT& rect, unsigned int styleFlags = 0);
~Overlay();
// IPanel
void Show() override;
void Render() override;
bool Update(float elapsedTime, const DirectX::GamePad::State& pad) override;
bool Update(float elapsedTime, const DirectX::Mouse::State& mstate, const DirectX::Keyboard::State& kbstate) override;
void Update(float) override {}
void Close() override;
void Cancel() override;
void Add(_In_ IControl* ctrl) override;
IControl* Find(unsigned id) override;
void SetFocus(_In_ IControl* ctrl) override;
void OnWindowSize(const RECT& layout) override;
private:
bool m_select;
bool m_cancel;
bool m_suppressCancel;
const bool m_custom;
IControl* m_focusControl;
std::vector<IControl*> m_controls;
};
//----------------------------------------------------------------------------------
struct UIConfig
{
bool forceSRGB;
bool pmAlpha;
wchar_t largeFontName[MAX_PATH];
wchar_t largeItalicFontName[MAX_PATH];
wchar_t largeBoldFontName[MAX_PATH];
wchar_t midFontName[MAX_PATH];
wchar_t midItalicFontName[MAX_PATH];
wchar_t midBoldFontName[MAX_PATH];
wchar_t smallFontName[MAX_PATH];
wchar_t smallItalicFontName[MAX_PATH];
wchar_t smallBoldFontName[MAX_PATH];
wchar_t largeLegendName[MAX_PATH];
wchar_t smallLegendName[MAX_PATH];
DirectX::XMFLOAT4 colorNormal;
DirectX::XMFLOAT4 colorDisabled;
DirectX::XMFLOAT4 colorHighlight;
DirectX::XMFLOAT4 colorSelected;
DirectX::XMFLOAT4 colorFocus;
DirectX::XMFLOAT4 colorBackground;
DirectX::XMFLOAT4 colorTransparent;
DirectX::XMFLOAT4 colorProgress;
enum COLORS
{
RED,
GREEN,
BLUE,
ORANGE,
YELLOW,
DARK_GREY,
MID_GREY,
LIGHT_GREY,
OFF_WHITE,
WHITE,
BLACK,
MAX_COLORS,
};
DirectX::XMFLOAT4 colorDictionary[MAX_COLORS];
UIConfig(bool linear = false, bool pmalpha = true) :
forceSRGB(linear),
pmAlpha(pmalpha)
{
using DirectX::XMFLOAT4;
wcscpy_s(largeFontName, L"SegoeUI_36.spritefont");
wcscpy_s(largeItalicFontName, L"SegoeUI_36_Italic.spritefont");
wcscpy_s(largeBoldFontName, L"SegoeUI_36_Bold.spritefont");
wcscpy_s(midFontName, L"SegoeUI_22.spritefont");
wcscpy_s(midItalicFontName, L"SegoeUI_22_Italic.spritefont");
wcscpy_s(midBoldFontName, L"SegoeUI_22_Bold.spritefont");
wcscpy_s(smallFontName, L"SegoeUI_18.spritefont");
wcscpy_s(smallItalicFontName, L"SegoeUI_18_Italic.spritefont");
wcscpy_s(smallBoldFontName, L"SegoeUI_18_Bold.spritefont");
wcscpy_s(largeLegendName, L"XboxOneControllerLegend.spritefont");
wcscpy_s(smallLegendName, L"XboxOneControllerLegendSmall.spritefont");
if (linear)
{
colorNormal = XMFLOAT4(0.361306787f, 0.361306787f, 0.361306787f, 1.f); // OffWhite
colorDisabled = XMFLOAT4(0.194617808f, 0.194617808f, 0.194617808f, 1.f); // LightGrey
colorHighlight = XMFLOAT4(0.545724571f, 0.026241219f, 0.001517635f, 1.f); // Orange
colorSelected = XMFLOAT4(0.955973506f, 0.955973506f, 0.955973506f, 1.f); // White
colorFocus = XMFLOAT4(0.005181516f, 0.201556236f, 0.005181516f, 1.f); // Green
colorBackground = XMFLOAT4(0.f, 0.f, 0.f, 1.f); // Black
colorTransparent = XMFLOAT4(0.033105f, 0.033105f, 0.033105f, 0.5f);
colorProgress = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.f); // MidGrey
colorDictionary[RED] = XMFLOAT4(1.f, 0.f, 0.f, 1.f);
colorDictionary[GREEN] = XMFLOAT4(0.005181516f, 0.201556236f, 0.005181516f, 1.f);
colorDictionary[BLUE] = XMFLOAT4(0.001517635f, 0.114435382f, 0.610495627f, 1.f);
colorDictionary[ORANGE] = XMFLOAT4(0.545724571f, 0.026241219f, 0.001517635f, 1.f);
colorDictionary[YELLOW] = XMFLOAT4(1.f, 1.f, 0.f, 1.f);
colorDictionary[DARK_GREY] = XMFLOAT4(0.033104762f, 0.033104762f, 0.033104762f, 1.f);
colorDictionary[MID_GREY] = XMFLOAT4(0.113861285f, 0.113861285f, 0.113861285f, 1.f);
colorDictionary[LIGHT_GREY] = XMFLOAT4(0.194617808f, 0.194617808f, 0.194617808f, 1.f);
colorDictionary[OFF_WHITE] = XMFLOAT4(0.361306787f, 0.361306787f, 0.361306787f, 1.f);
colorDictionary[WHITE] = XMFLOAT4(0.955973506f, 0.955973506f, 0.955973506f, 1.f);
colorDictionary[BLACK] = XMFLOAT4(0.f, 0.f, 0.f, 1.f);
}
else
{
colorNormal = XMFLOAT4(0.635294139f, 0.635294139f, 0.635294139f, 1.f); // OffWhite
colorDisabled = XMFLOAT4(0.478431374f, 0.478431374f, 0.478431374f, 1.f); // LightGrey
colorHighlight = XMFLOAT4(0.764705896f, 0.176470593f, 0.019607844f, 1.f); // Orange
colorSelected = XMFLOAT4(0.980392158f, 0.980392158f, 0.980392158f, 1.f); // White
colorFocus = XMFLOAT4(0.062745102f, 0.486274511f, 0.062745102f, 1.f); // Green
colorBackground = XMFLOAT4(0.f, 0.f, 0.f, 1.f); // Black
colorTransparent = XMFLOAT4(0.2f, 0.2f, 0.2f, 0.5f);
colorProgress = XMFLOAT4(0.5f, 0.5f, 0.5f, 1.f); // MidGrey
colorDictionary[RED] = XMFLOAT4(1.f, 0.f, 0.f, 1.f);
colorDictionary[GREEN] = XMFLOAT4(0.062745102f, 0.486274511f, 0.062745102f, 1.f);
colorDictionary[BLUE] = XMFLOAT4(0.019607844f, 0.372549027f, 0.803921580f, 1.f);
colorDictionary[ORANGE] = XMFLOAT4(0.764705896f, 0.176470593f, 0.019607844f, 1.f);
colorDictionary[YELLOW] = XMFLOAT4(1.f, 1.f, 0.f, 1.f);
colorDictionary[DARK_GREY] = XMFLOAT4(0.200000003f, 0.200000003f, 0.200000003f, 1.f);
colorDictionary[MID_GREY] = XMFLOAT4(0.371653974f, 0.371653974f, 0.371653974f, 1.f);
colorDictionary[LIGHT_GREY] = XMFLOAT4(0.478431374f, 0.478431374f, 0.478431374f, 1.f);
colorDictionary[OFF_WHITE] = XMFLOAT4(0.635294139f, 0.635294139f, 0.635294139f, 1.f);
colorDictionary[WHITE] = XMFLOAT4(0.980392158f, 0.980392158f, 0.980392158f, 1.f);
colorDictionary[BLACK] = XMFLOAT4(0.f, 0.f, 0.f, 1.f);
}
}
};
class UIManager
{
public:
UIManager(const UIConfig& config);
#if defined(__d3d12_h__) || defined(__d3d12_x_h__) || defined(__XBOX_D3D12_X__)
UIManager(_In_ ID3D12Device *device,
const DirectX::RenderTargetState& renderTarget,
DirectX::ResourceUploadBatch& resourceUpload,
DirectX::DescriptorPile& pile,
const UIConfig& config);
#elif defined(__d3d11_h__) || defined(__d3d11_x_h__)
UIManager(_In_ ID3D11DeviceContext* context, const UIConfig& config);
#else
# error Please #include <d3d11.h> or <d3d12.h>
#endif
UIManager(UIManager&& moveFrom);
UIManager& operator= (UIManager&& moveFrom);
UIManager(UIManager const&) = delete;
UIManager& operator=(UIManager const&) = delete;
virtual ~UIManager();
// Load UI layout from disk
void LoadLayout(const wchar_t* layoutFile, const wchar_t* imageDir = nullptr, unsigned offset = 0);
// Add a panel (takes ownership)
void Add(unsigned id, _In_ IPanel* panel);
// Find a panel
IPanel* Find(unsigned id) const;
template<class T>
T* FindPanel(unsigned id) const
{
auto panel = dynamic_cast<T*>(Find(id));
if (panel)
{
return panel;
}
throw std::exception("Find (panel)");
}
// Find a control
template<class T>
T* FindControl(unsigned panelId, unsigned ctrlId) const
{
auto panel = Find(panelId);
if (panel)
{
auto ctrl = dynamic_cast<T*>(panel->Find(ctrlId));
if (ctrl)
return ctrl;
}
throw std::exception("Find (control)");
}
// Close all visible panels
void CloseAll();
// Process user input for gamepad controls
bool Update(float elapsedTime, const DirectX::GamePad::State& pad);
// Process user input for keyboard & mouse controls
bool Update(float elapsedTime, DirectX::Mouse& mouse, DirectX::Keyboard& kb);
// Render the visible UI panels
#if defined(__d3d12_h__) || defined(__d3d12_x_h__) || defined(__XBOX_D3D12_X__)
void Render(_In_ ID3D12GraphicsCommandList* commandList);
#elif defined(__d3d11_h__) || defined(__d3d11_x_h__)
void Render();
#endif
// Set the screen viewport
void SetWindow(const RECT& layout);
// Set view rotation
void SetRotation(DXGI_MODE_ROTATION rotation);
// Texture registry for images (used by controls)
static const unsigned c_LayoutImageIdStart = 0x10000;
#if defined(__d3d12_h__) || defined(__d3d12_x_h__) || defined(__XBOX_D3D12_X__)
void RegisterImage(unsigned id, D3D12_GPU_DESCRIPTOR_HANDLE tex, DirectX::XMUINT2 texSize);
#elif defined(__d3d11_h__) || defined(__d3d11_x_h__)
void RegisterImage(unsigned id, _In_ ID3D11ShaderResourceView* tex);
#endif
void UnregisterImage(unsigned id);
void UnregisterAllImages();
// Direct3D device management
void ReleaseDevice();
#if defined(__d3d12_h__) || defined(__d3d12_x_h__) || defined(__XBOX_D3D12_X__)
void RestoreDevice(_In_ ID3D12Device* device,
const DirectX::RenderTargetState& renderTarget,
DirectX::ResourceUploadBatch& resourceUpload,
DirectX::DescriptorPile& pile);
#elif defined(__d3d11_h__) || defined(__d3d11_x_h__)
void RestoreDevice(_In_ ID3D11DeviceContext* context);
#endif
// Reset UI state (such as coming back from suspend)
void Reset();
// Release all objects
void Clear();
// Enumerators
void Enumerate(std::function<void(unsigned id, IPanel*)> enumCallback);
// Common callback adapters
void CallbackYesNoCancel(_In_ IPanel* panel, std::function<void(bool, bool)> yesnocallback);
private:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
friend class IControl;
friend class TextLabel;
friend class Image;
friend class Legend;
friend class Button;
friend class ImageButton;
friend class CheckBox;
friend class Slider;
friend class ProgressBar;
friend class ListBox;
friend class TextBox;
friend class TextList;
friend class Popup;
friend class HUD;
friend class Overlay;
};
}
| [
"jlafonta0550@gmail.com"
] | jlafonta0550@gmail.com |
90640ee2452c5ce91e3109819e6ee41710e6c52e | a2973e7238e0dc8c7b70da7d92e3c5712af0f4ae | /graphicsProgramming/runaway shapes rasist/MacGraphicsStarter/Triangle.h | 470169203cbebbbbb154a24097ed9910ccaa1f84 | [] | no_license | codybrowncit/C-plus-plus | 581487db5e3b35ee9388f1a110a40d27c38cf343 | 2cea4d315b96f0537a598e16fcbcb430e1bd47a4 | refs/heads/master | 2020-12-25T19:04:11.471095 | 2015-05-14T23:16:57 | 2015-05-14T23:16:57 | 31,285,389 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 535 | h | //
// Triangle.h
// MacGraphicsStarter
//
// Created by Cody Brown on 11/2/14.
//
//
#ifndef _TRIANGLE_H_
#define _TRIANGLE_H_
#include "Shape.h"
#include <stdio.h>
#ifdef _WIN32
#include "glut.h"
#else
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#endif
class Triangle : public Shape
{
public:
Triangle(double x1, double y1, double x2, double y2, double x3, double y3, double red, double green, double blue, bool solid);
void draw();
};
#endif /* defined(__MacGraphicsStarter__Triangle__) */
| [
"codybrowncit@gmail.com"
] | codybrowncit@gmail.com |
f1e8046f4fd8a4e81e69cd2187dec7ecc7b168e3 | fb72a82827496e66e04ecb29abbca788a1ea0525 | /src/rpc/rawtransaction.cpp | b130783db6f85798a215a9edd3192c0d6f6dff61 | [
"MIT"
] | permissive | exiliumcore/exilium | 92631c2e7abeeae6a80debbb699441d6b56e2fee | 6aa88fe0c40fe72850e5bdb265741a375b2ab766 | refs/heads/master | 2020-03-14T05:50:41.214608 | 2018-05-13T01:00:24 | 2018-05-13T01:00:24 | 131,472,364 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 39,585 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2018 The Exilium Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "chain.h"
#include "coins.h"
#include "consensus/validation.h"
#include "core_io.h"
#include "init.h"
#include "keystore.h"
#include "validation.h"
#include "merkleblock.h"
#include "net.h"
#include "policy/policy.h"
#include "primitives/transaction.h"
#include "rpc/server.h"
#include "script/script.h"
#include "script/script_error.h"
#include "script/sign.h"
#include "script/standard.h"
#include "txmempool.h"
#include "uint256.h"
#include "utilstrencodings.h"
#include "instantx.h"
#ifdef ENABLE_WALLET
#include "wallet/wallet.h"
#endif
#include <stdint.h>
#include <boost/assign/list_of.hpp>
#include <univalue.h>
using namespace std;
void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex)
{
txnouttype type;
vector<CTxDestination> addresses;
int nRequired;
out.push_back(Pair("asm", ScriptToAsmStr(scriptPubKey)));
if (fIncludeHex)
out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) {
out.push_back(Pair("type", GetTxnOutputType(type)));
return;
}
out.push_back(Pair("reqSigs", nRequired));
out.push_back(Pair("type", GetTxnOutputType(type)));
UniValue a(UniValue::VARR);
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, UniValue& entry)
{
uint256 txid = tx.GetHash();
entry.push_back(Pair("txid", txid.GetHex()));
entry.push_back(Pair("size", (int)::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION)));
entry.push_back(Pair("version", tx.nVersion));
entry.push_back(Pair("locktime", (int64_t)tx.nLockTime));
UniValue vin(UniValue::VARR);
BOOST_FOREACH(const CTxIn& txin, tx.vin) {
UniValue in(UniValue::VOBJ);
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", (int64_t)txin.prevout.n));
UniValue o(UniValue::VOBJ);
o.push_back(Pair("asm", ScriptToAsmStr(txin.scriptSig, true)));
o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
in.push_back(Pair("scriptSig", o));
// Add address and value info if spentindex enabled
CSpentIndexValue spentInfo;
CSpentIndexKey spentKey(txin.prevout.hash, txin.prevout.n);
if (GetSpentIndex(spentKey, spentInfo)) {
in.push_back(Pair("value", ValueFromAmount(spentInfo.satoshis)));
in.push_back(Pair("valueSat", spentInfo.satoshis));
if (spentInfo.addressType == 1) {
in.push_back(Pair("address", CBitcoinAddress(CKeyID(spentInfo.addressHash)).ToString()));
} else if (spentInfo.addressType == 2) {
in.push_back(Pair("address", CBitcoinAddress(CScriptID(spentInfo.addressHash)).ToString()));
}
}
}
in.push_back(Pair("sequence", (int64_t)txin.nSequence));
vin.push_back(in);
}
entry.push_back(Pair("vin", vin));
UniValue vout(UniValue::VARR);
for (unsigned int i = 0; i < tx.vout.size(); i++) {
const CTxOut& txout = tx.vout[i];
UniValue out(UniValue::VOBJ);
out.push_back(Pair("value", ValueFromAmount(txout.nValue)));
out.push_back(Pair("valueSat", txout.nValue));
out.push_back(Pair("n", (int64_t)i));
UniValue o(UniValue::VOBJ);
ScriptPubKeyToJSON(txout.scriptPubKey, o, true);
out.push_back(Pair("scriptPubKey", o));
// Add spent information if spentindex is enabled
CSpentIndexValue spentInfo;
CSpentIndexKey spentKey(txid, i);
if (GetSpentIndex(spentKey, spentInfo)) {
out.push_back(Pair("spentTxId", spentInfo.txid.GetHex()));
out.push_back(Pair("spentIndex", (int)spentInfo.inputIndex));
out.push_back(Pair("spentHeight", spentInfo.blockHeight));
}
vout.push_back(out);
}
entry.push_back(Pair("vout", vout));
if (!hashBlock.IsNull()) {
entry.push_back(Pair("blockhash", hashBlock.GetHex()));
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second) {
CBlockIndex* pindex = (*mi).second;
if (chainActive.Contains(pindex)) {
entry.push_back(Pair("height", pindex->nHeight));
entry.push_back(Pair("confirmations", 1 + chainActive.Height() - pindex->nHeight));
entry.push_back(Pair("time", pindex->GetBlockTime()));
entry.push_back(Pair("blocktime", pindex->GetBlockTime()));
} else {
entry.push_back(Pair("height", -1));
entry.push_back(Pair("confirmations", 0));
}
}
}
}
UniValue getrawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getrawtransaction \"txid\" ( verbose )\n"
"\nNOTE: By default this function only works sometimes. This is when the tx is in the mempool\n"
"or there is an unspent output in the utxo for this transaction. To make it always work,\n"
"you need to maintain a transaction index, using the -txindex command line option.\n"
"\nReturn the raw transaction data.\n"
"\nIf verbose=0, returns a string that is serialized, hex-encoded data for 'txid'.\n"
"If verbose is non-zero, returns an Object with information about 'txid'.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id\n"
"2. verbose (numeric, optional, default=0) If 0, return a string, other return a json object\n"
"\nResult (if verbose is not set or set to 0):\n"
"\"data\" (string) The serialized, hex-encoded data for 'txid'\n"
"\nResult (if verbose > 0):\n"
"{\n"
" \"hex\" : \"data\", (string) The serialized, hex-encoded data for 'txid'\n"
" \"txid\" : \"id\", (string) The transaction id (same as provided)\n"
" \"size\" : n, (numeric) The transaction size\n"
" \"version\" : n, (numeric) The version\n"
" \"locktime\" : ttt, (numeric) The lock time\n"
" \"vin\" : [ (array of json objects)\n"
" {\n"
" \"txid\": \"id\", (string) The transaction id\n"
" \"vout\": n, (numeric) \n"
" \"scriptSig\": { (json object) The script\n"
" \"asm\": \"asm\", (string) asm\n"
" \"hex\": \"hex\" (string) hex\n"
" },\n"
" \"sequence\": n (numeric) The script sequence number\n"
" }\n"
" ,...\n"
" ],\n"
" \"vout\" : [ (array of json objects)\n"
" {\n"
" \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n"
" \"n\" : n, (numeric) index\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"asm\", (string) the asm\n"
" \"hex\" : \"hex\", (string) the hex\n"
" \"reqSigs\" : n, (numeric) The required sigs\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
" \"addresses\" : [ (json array of string)\n"
" \"exiliumaddress\" (string) exilium address\n"
" ,...\n"
" ]\n"
" }\n"
" }\n"
" ,...\n"
" ],\n"
" \"blockhash\" : \"hash\", (string) the block hash\n"
" \"confirmations\" : n, (numeric) The confirmations\n"
" \"time\" : ttt, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"blocktime\" : ttt (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getrawtransaction", "\"mytxid\"")
+ HelpExampleCli("getrawtransaction", "\"mytxid\" 1")
+ HelpExampleRpc("getrawtransaction", "\"mytxid\", 1")
);
LOCK(cs_main);
uint256 hash = ParseHashV(params[0], "parameter 1");
bool fVerbose = false;
if (params.size() > 1)
fVerbose = (params[1].get_int() != 0);
CTransaction tx;
uint256 hashBlock;
if (!GetTransaction(hash, tx, Params().GetConsensus(), hashBlock, true))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
string strHex = EncodeHexTx(tx);
if (!fVerbose)
return strHex;
UniValue result(UniValue::VOBJ);
result.push_back(Pair("hex", strHex));
TxToJSON(tx, hashBlock, result);
return result;
}
UniValue gettxoutproof(const UniValue& params, bool fHelp)
{
if (fHelp || (params.size() != 1 && params.size() != 2))
throw runtime_error(
"gettxoutproof [\"txid\",...] ( blockhash )\n"
"\nReturns a hex-encoded proof that \"txid\" was included in a block.\n"
"\nNOTE: By default this function only works sometimes. This is when there is an\n"
"unspent output in the utxo for this transaction. To make it always work,\n"
"you need to maintain a transaction index, using the -txindex command line option or\n"
"specify the block in which the transaction is included in manually (by blockhash).\n"
"\nReturn the raw transaction data.\n"
"\nArguments:\n"
"1. \"txids\" (string) A json array of txids to filter\n"
" [\n"
" \"txid\" (string) A transaction hash\n"
" ,...\n"
" ]\n"
"2. \"block hash\" (string, optional) If specified, looks for txid in the block with this hash\n"
"\nResult:\n"
"\"data\" (string) A string that is a serialized, hex-encoded data for the proof.\n"
"\nExamples:\n"
+ HelpExampleCli("gettxoutproof", "'[\"mytxid\",...]'")
+ HelpExampleCli("gettxoutproof", "'[\"mytxid\",...]' \"blockhash\"")
+ HelpExampleRpc("gettxoutproof", "[\"mytxid\",...], \"blockhash\"")
);
set<uint256> setTxids;
uint256 oneTxid;
UniValue txids = params[0].get_array();
for (unsigned int idx = 0; idx < txids.size(); idx++) {
const UniValue& txid = txids[idx];
if (txid.get_str().length() != 64 || !IsHex(txid.get_str()))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid txid ")+txid.get_str());
uint256 hash(uint256S(txid.get_str()));
if (setTxids.count(hash))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated txid: ")+txid.get_str());
setTxids.insert(hash);
oneTxid = hash;
}
LOCK(cs_main);
CBlockIndex* pblockindex = NULL;
uint256 hashBlock;
if (params.size() > 1)
{
hashBlock = uint256S(params[1].get_str());
if (!mapBlockIndex.count(hashBlock))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
pblockindex = mapBlockIndex[hashBlock];
} else {
const Coin& coin = AccessByTxid(*pcoinsTip, oneTxid);
if (!coin.IsSpent() && coin.nHeight > 0 && coin.nHeight <= chainActive.Height()) {
pblockindex = chainActive[coin.nHeight];
}
}
if (pblockindex == NULL)
{
CTransaction tx;
if (!GetTransaction(oneTxid, tx, Params().GetConsensus(), hashBlock, false) || hashBlock.IsNull())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block");
if (!mapBlockIndex.count(hashBlock))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Transaction index corrupt");
pblockindex = mapBlockIndex[hashBlock];
}
CBlock block;
if(!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus()))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
unsigned int ntxFound = 0;
BOOST_FOREACH(const CTransaction&tx, block.vtx)
if (setTxids.count(tx.GetHash()))
ntxFound++;
if (ntxFound != setTxids.size())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "(Not all) transactions not found in specified block");
CDataStream ssMB(SER_NETWORK, PROTOCOL_VERSION);
CMerkleBlock mb(block, setTxids);
ssMB << mb;
std::string strHex = HexStr(ssMB.begin(), ssMB.end());
return strHex;
}
UniValue verifytxoutproof(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"verifytxoutproof \"proof\"\n"
"\nVerifies that a proof points to a transaction in a block, returning the transaction it commits to\n"
"and throwing an RPC error if the block is not in our best chain\n"
"\nArguments:\n"
"1. \"proof\" (string, required) The hex-encoded proof generated by gettxoutproof\n"
"\nResult:\n"
"[\"txid\"] (array, strings) The txid(s) which the proof commits to, or empty array if the proof is invalid\n"
"\nExamples:\n"
+ HelpExampleCli("verifytxoutproof", "\"proof\"")
+ HelpExampleRpc("gettxoutproof", "\"proof\"")
);
CDataStream ssMB(ParseHexV(params[0], "proof"), SER_NETWORK, PROTOCOL_VERSION);
CMerkleBlock merkleBlock;
ssMB >> merkleBlock;
UniValue res(UniValue::VARR);
vector<uint256> vMatch;
if (merkleBlock.txn.ExtractMatches(vMatch) != merkleBlock.header.hashMerkleRoot)
return res;
LOCK(cs_main);
if (!mapBlockIndex.count(merkleBlock.header.GetHash()) || !chainActive.Contains(mapBlockIndex[merkleBlock.header.GetHash()]))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain");
BOOST_FOREACH(const uint256& hash, vMatch)
res.push_back(hash.GetHex());
return res;
}
UniValue createrawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
throw runtime_error(
"createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] {\"address\":amount,\"data\":\"hex\",...} ( locktime )\n"
"\nCreate a transaction spending the given inputs and creating new outputs.\n"
"Outputs can be addresses or data.\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.\n"
"\nArguments:\n"
"1. \"transactions\" (string, required) A json array of json objects\n"
" [\n"
" {\n"
" \"txid\":\"id\", (string, required) The transaction id\n"
" \"vout\":n (numeric, required) The output number\n"
" }\n"
" ,...\n"
" ]\n"
"2. \"outputs\" (string, required) a json object with outputs\n"
" {\n"
" \"address\": x.xxx (numeric or string, required) The key is the exilium address, the numeric value (can be string) is the " + CURRENCY_UNIT + " amount\n"
" \"data\": \"hex\", (string, required) The key is \"data\", the value is hex encoded data\n"
" ...\n"
" }\n"
"3. locktime (numeric, optional, default=0) Raw locktime. Non-0 value also locktime-activates inputs\n"
"\nResult:\n"
"\"transaction\" (string) hex string of the transaction\n"
"\nExamples\n"
+ HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"address\\\":0.01}\"")
+ HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"data\\\":\\\"00010203\\\"}\"")
+ HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"address\\\":0.01}\"")
+ HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"data\\\":\\\"00010203\\\"}\"")
);
LOCK(cs_main);
RPCTypeCheck(params, boost::assign::list_of(UniValue::VARR)(UniValue::VOBJ)(UniValue::VNUM), true);
if (params[0].isNull() || params[1].isNull())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, arguments 1 and 2 must be non-null");
UniValue inputs = params[0].get_array();
UniValue sendTo = params[1].get_obj();
CMutableTransaction rawTx;
if (params.size() > 2 && !params[2].isNull()) {
int64_t nLockTime = params[2].get_int64();
if (nLockTime < 0 || nLockTime > std::numeric_limits<uint32_t>::max())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, locktime out of range");
rawTx.nLockTime = nLockTime;
}
for (unsigned int idx = 0; idx < inputs.size(); idx++) {
const UniValue& input = inputs[idx];
const UniValue& o = input.get_obj();
uint256 txid = ParseHashO(o, "txid");
const UniValue& vout_v = find_value(o, "vout");
if (!vout_v.isNum())
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");
uint32_t nSequence = (rawTx.nLockTime ? std::numeric_limits<uint32_t>::max() - 1 : std::numeric_limits<uint32_t>::max());
CTxIn in(COutPoint(txid, nOutput), CScript(), nSequence);
rawTx.vin.push_back(in);
}
set<CBitcoinAddress> setAddress;
vector<string> addrList = sendTo.getKeys();
BOOST_FOREACH(const string& name_, addrList) {
if (name_ == "data") {
std::vector<unsigned char> data = ParseHexV(sendTo[name_].getValStr(),"Data");
CTxOut out(0, CScript() << OP_RETURN << data);
rawTx.vout.push_back(out);
} else {
CBitcoinAddress address(name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid exilium address: ")+name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+name_);
setAddress.insert(address);
CScript scriptPubKey = GetScriptForDestination(address.Get());
CAmount nAmount = AmountFromValue(sendTo[name_]);
CTxOut out(nAmount, scriptPubKey);
rawTx.vout.push_back(out);
}
}
return EncodeHexTx(rawTx);
}
UniValue decoderawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"decoderawtransaction \"hexstring\"\n"
"\nReturn a JSON object representing the serialized, hex-encoded transaction.\n"
"\nArguments:\n"
"1. \"hex\" (string, required) The transaction hex string\n"
"\nResult:\n"
"{\n"
" \"txid\" : \"id\", (string) The transaction id\n"
" \"size\" : n, (numeric) The transaction size\n"
" \"version\" : n, (numeric) The version\n"
" \"locktime\" : ttt, (numeric) The lock time\n"
" \"vin\" : [ (array of json objects)\n"
" {\n"
" \"txid\": \"id\", (string) The transaction id\n"
" \"vout\": n, (numeric) The output number\n"
" \"scriptSig\": { (json object) The script\n"
" \"asm\": \"asm\", (string) asm\n"
" \"hex\": \"hex\" (string) hex\n"
" },\n"
" \"sequence\": n (numeric) The script sequence number\n"
" }\n"
" ,...\n"
" ],\n"
" \"vout\" : [ (array of json objects)\n"
" {\n"
" \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n"
" \"n\" : n, (numeric) index\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"asm\", (string) the asm\n"
" \"hex\" : \"hex\", (string) the hex\n"
" \"reqSigs\" : n, (numeric) The required sigs\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
" \"addresses\" : [ (json array of string)\n"
" \"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" (string) exilium address\n"
" ,...\n"
" ]\n"
" }\n"
" }\n"
" ,...\n"
" ],\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("decoderawtransaction", "\"hexstring\"")
+ HelpExampleRpc("decoderawtransaction", "\"hexstring\"")
);
LOCK(cs_main);
RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR));
CTransaction tx;
if (!DecodeHexTx(tx, params[0].get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
UniValue result(UniValue::VOBJ);
TxToJSON(tx, uint256(), result);
return result;
}
UniValue decodescript(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"decodescript \"hex\"\n"
"\nDecode a hex-encoded script.\n"
"\nArguments:\n"
"1. \"hex\" (string) the hex encoded script\n"
"\nResult:\n"
"{\n"
" \"asm\":\"asm\", (string) Script public key\n"
" \"hex\":\"hex\", (string) hex encoded public key\n"
" \"type\":\"type\", (string) The output type\n"
" \"reqSigs\": n, (numeric) The required signatures\n"
" \"addresses\": [ (json array of string)\n"
" \"address\" (string) exilium address\n"
" ,...\n"
" ],\n"
" \"p2sh\",\"address\" (string) address of P2SH script wrapping this redeem script (not returned if the script is already a P2SH).\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("decodescript", "\"hexstring\"")
+ HelpExampleRpc("decodescript", "\"hexstring\"")
);
RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR));
UniValue r(UniValue::VOBJ);
CScript script;
if (params[0].get_str().size() > 0){
vector<unsigned char> scriptData(ParseHexV(params[0], "argument"));
script = CScript(scriptData.begin(), scriptData.end());
} else {
// Empty scripts are valid
}
ScriptPubKeyToJSON(script, r, false);
UniValue type;
type = find_value(r, "type");
if (type.isStr() && type.get_str() != "scripthash") {
// P2SH cannot be wrapped in a P2SH. If this script is already a P2SH,
// don't return the address for a P2SH of the P2SH.
r.push_back(Pair("p2sh", CBitcoinAddress(CScriptID(script)).ToString()));
}
return r;
}
/** Pushes a JSON object for script verification or signing errors to vErrorsRet. */
static void TxInErrorToJSON(const CTxIn& txin, UniValue& vErrorsRet, const std::string& strMessage)
{
UniValue entry(UniValue::VOBJ);
entry.push_back(Pair("txid", txin.prevout.hash.ToString()));
entry.push_back(Pair("vout", (uint64_t)txin.prevout.n));
entry.push_back(Pair("scriptSig", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
entry.push_back(Pair("sequence", (uint64_t)txin.nSequence));
entry.push_back(Pair("error", strMessage));
vErrorsRet.push_back(entry);
}
UniValue signrawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 4)
throw runtime_error(
"signrawtransaction \"hexstring\" ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] [\"privatekey1\",...] sighashtype )\n"
"\nSign inputs for raw transaction (serialized, hex-encoded).\n"
"The 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"
"The 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"
#ifdef ENABLE_WALLET
+ HelpRequiringPassphrase() + "\n"
#endif
"\nArguments:\n"
"1. \"hexstring\" (string, required) The transaction hex string\n"
"2. \"prevtxs\" (string, optional) An json array of previous dependent transaction outputs\n"
" [ (json array of json objects, or 'null' if none provided)\n"
" {\n"
" \"txid\":\"id\", (string, required) The transaction id\n"
" \"vout\":n, (numeric, required) The output number\n"
" \"scriptPubKey\": \"hex\", (string, required) script key\n"
" \"redeemScript\": \"hex\" (string, required for P2SH) redeem script\n"
" }\n"
" ,...\n"
" ]\n"
"3. \"privatekeys\" (string, optional) A json array of base58-encoded private keys for signing\n"
" [ (json array of strings, or 'null' if none provided)\n"
" \"privatekey\" (string) private key in base58-encoding\n"
" ,...\n"
" ]\n"
"4. \"sighashtype\" (string, optional, default=ALL) The signature hash type. Must be one of\n"
" \"ALL\"\n"
" \"NONE\"\n"
" \"SINGLE\"\n"
" \"ALL|ANYONECANPAY\"\n"
" \"NONE|ANYONECANPAY\"\n"
" \"SINGLE|ANYONECANPAY\"\n"
"\nResult:\n"
"{\n"
" \"hex\" : \"value\", (string) The hex-encoded raw transaction with signature(s)\n"
" \"complete\" : true|false, (boolean) If the transaction has a complete set of signatures\n"
" \"errors\" : [ (json array of objects) Script verification errors (if there are any)\n"
" {\n"
" \"txid\" : \"hash\", (string) The hash of the referenced, previous transaction\n"
" \"vout\" : n, (numeric) The index of the output to spent and used as input\n"
" \"scriptSig\" : \"hex\", (string) The hex-encoded signature script\n"
" \"sequence\" : n, (numeric) Script sequence number\n"
" \"error\" : \"text\" (string) Verification or signing error related to the input\n"
" }\n"
" ,...\n"
" ]\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("signrawtransaction", "\"myhex\"")
+ HelpExampleRpc("signrawtransaction", "\"myhex\"")
);
#ifdef ENABLE_WALLET
LOCK2(cs_main, pwalletMain ? &pwalletMain->cs_wallet : NULL);
#else
LOCK(cs_main);
#endif
RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)(UniValue::VARR)(UniValue::VARR)(UniValue::VSTR), true);
vector<unsigned char> txData(ParseHexV(params[0], "argument 1"));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
vector<CMutableTransaction> txVariants;
while (!ssData.empty()) {
try {
CMutableTransaction tx;
ssData >> tx;
txVariants.push_back(tx);
}
catch (const std::exception&) {
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:
CMutableTransaction mergedTx(txVariants[0]);
// 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) {
view.AccessCoin(txin.prevout); // Load entries from viewChain into view; can fail.
}
view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
}
bool fGivenKeys = false;
CBasicKeyStore tempKeystore;
if (params.size() > 2 && !params[2].isNull()) {
fGivenKeys = true;
UniValue keys = params[2].get_array();
for (unsigned int idx = 0; idx < keys.size(); idx++) {
UniValue k = keys[idx];
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();
if (!key.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
tempKeystore.AddKey(key);
}
}
#ifdef ENABLE_WALLET
else if (pwalletMain)
EnsureWalletIsUnlocked();
#endif
// Add previous txouts given in the RPC call:
if (params.size() > 1 && !params[1].isNull()) {
UniValue prevTxs = params[1].get_array();
for (unsigned int idx = 0; idx < prevTxs.size(); idx++) {
const UniValue& p = prevTxs[idx];
if (!p.isObject())
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
UniValue prevOut = p.get_obj();
RPCTypeCheckObj(prevOut, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM)("scriptPubKey", UniValue::VSTR));
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");
COutPoint out(txid, nOut);
vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));
CScript scriptPubKey(pkData.begin(), pkData.end());
{
const Coin& coin = view.AccessCoin(out);
if (!coin.IsSpent() && coin.out.scriptPubKey != scriptPubKey) {
string err("Previous output scriptPubKey mismatch:\n");
err = err + ScriptToAsmStr(coin.out.scriptPubKey) + "\nvs:\n"+
ScriptToAsmStr(scriptPubKey);
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);
}
Coin newcoin;
newcoin.out.scriptPubKey = scriptPubKey;
newcoin.out.nValue = 0;
newcoin.nHeight = 1;
view.AddCoin(out, std::move(newcoin), true);
}
// 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()) {
RPCTypeCheckObj(prevOut, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM)("scriptPubKey", UniValue::VSTR)("redeemScript",UniValue::VSTR));
UniValue v = find_value(prevOut, "redeemScript");
if (!v.isNull()) {
vector<unsigned char> rsData(ParseHexV(v, "redeemScript"));
CScript redeemScript(rsData.begin(), rsData.end());
tempKeystore.AddCScript(redeemScript);
}
}
}
}
#ifdef ENABLE_WALLET
const CKeyStore& keystore = ((fGivenKeys || !pwalletMain) ? tempKeystore : *pwalletMain);
#else
const CKeyStore& keystore = tempKeystore;
#endif
int nHashType = SIGHASH_ALL;
if (params.size() > 3 && !params[3].isNull()) {
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);
// Script verification errors
UniValue vErrors(UniValue::VARR);
// Sign what we can:
for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
CTxIn& txin = mergedTx.vin[i];
const Coin& coin = view.AccessCoin(txin.prevout);
if (coin.IsSpent()) {
TxInErrorToJSON(txin, vErrors, "Input not found or already spent");
continue;
}
const CScript& prevPubKey = coin.out.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 CMutableTransaction& txv, txVariants) {
txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig);
}
ScriptError serror = SCRIPT_ERR_OK;
if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i), &serror)) {
TxInErrorToJSON(txin, vErrors, ScriptErrorString(serror));
}
}
bool fComplete = vErrors.empty();
UniValue result(UniValue::VOBJ);
result.push_back(Pair("hex", EncodeHexTx(mergedTx)));
result.push_back(Pair("complete", fComplete));
if (!vErrors.empty()) {
result.push_back(Pair("errors", vErrors));
}
return result;
}
UniValue sendrawtransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 3)
throw runtime_error(
"sendrawtransaction \"hexstring\" ( allowhighfees instantsend )\n"
"\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\n"
"\nAlso see createrawtransaction and signrawtransaction calls.\n"
"\nArguments:\n"
"1. \"hexstring\" (string, required) The hex string of the raw transaction)\n"
"2. allowhighfees (boolean, optional, default=false) Allow high fees\n"
"3. instantsend (boolean, optional, default=false) Use InstantSend to send this transaction\n"
"\nResult:\n"
"\"hex\" (string) The transaction hash in hex\n"
"\nExamples:\n"
"\nCreate a transaction\n"
+ HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") +
"Sign the transaction, and get back the hex\n"
+ HelpExampleCli("signrawtransaction", "\"myhex\"") +
"\nSend the transaction (signed hex)\n"
+ HelpExampleCli("sendrawtransaction", "\"signedhex\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("sendrawtransaction", "\"signedhex\"")
);
LOCK(cs_main);
RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)(UniValue::VBOOL)(UniValue::VBOOL));
// parse hex string from parameter
CTransaction tx;
if (!DecodeHexTx(tx, params[0].get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
uint256 hashTx = tx.GetHash();
bool fOverrideFees = false;
if (params.size() > 1)
fOverrideFees = params[1].get_bool();
bool fInstantSend = false;
if (params.size() > 2)
fInstantSend = params[2].get_bool();
CCoinsViewCache &view = *pcoinsTip;
bool fHaveChain = false;
for (size_t o = 0; !fHaveChain && o < tx.vout.size(); o++) {
const Coin& existingCoin = view.AccessCoin(COutPoint(hashTx, o));
fHaveChain = !existingCoin.IsSpent();
}
bool fHaveMempool = mempool.exists(hashTx);
if (!fHaveMempool && !fHaveChain) {
// push to local node and sync with wallets
if (fInstantSend && !instantsend.ProcessTxLockRequest(tx, *g_connman)) {
throw JSONRPCError(RPC_TRANSACTION_ERROR, "Not a valid InstantSend transaction, see debug.log for more info");
}
CValidationState state;
bool fMissingInputs;
if (!AcceptToMemoryPool(mempool, state, tx, false, &fMissingInputs, false, !fOverrideFees)) {
if (state.IsInvalid()) {
throw JSONRPCError(RPC_TRANSACTION_REJECTED, strprintf("%i: %s", state.GetRejectCode(), state.GetRejectReason()));
} else {
if (fMissingInputs) {
throw JSONRPCError(RPC_TRANSACTION_ERROR, "Missing inputs");
}
throw JSONRPCError(RPC_TRANSACTION_ERROR, state.GetRejectReason());
}
}
} else if (fHaveChain) {
throw JSONRPCError(RPC_TRANSACTION_ALREADY_IN_CHAIN, "transaction already in block chain");
}
if(!g_connman)
throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
g_connman->RelayTransaction(tx);
return hashTx.GetHex();
}
| [
"devexilium@gmail.com"
] | devexilium@gmail.com |
97e466ef9ce9ec11921d28b127559626f374a82d | d75c8f301f369fde8ef2ad1b54168978906f129f | /tajadac/Tajada/AST/Expression.hh | d95b501a1ccbf248efeccc2233a64c85203e169e | [] | no_license | mgomezch/Tajada | efb006b64f278725fc8a542d613574e6c43e7776 | 4fc9ca6e93632ad2a2c73588582235627d6faae1 | refs/heads/master | 2016-09-06T19:07:42.782966 | 2012-07-12T23:04:49 | 2012-07-12T23:04:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,389 | hh | #ifndef TAJADA_AST_EXPRESSION_HH
#define TAJADA_AST_EXPRESSION_HH
#include <string>
// Superclasses:
#include "Tajada/AST/AST.hh"
#include "Tajada/Code/Block.hh"
#include "Tajada/Code/Intermediate/Address/Address.hh"
#include "Tajada/Type/Type.hh"
namespace Tajada {
namespace AST {
class Expression:
public virtual Tajada::AST::AST
{
public:
Tajada::Type::Type * type;
bool is_lvalue;
Expression(
Tajada::Type::Type * type,
bool is_lvalue
);
// TODO: make this pure virtual once all subclasses have their implementation
virtual Tajada::Code::Intermediate::Address::Address * genl(
Tajada::Code::Block * b
);
// TODO: make this pure virtual once all subclasses have their implementation
virtual Tajada::Code::Intermediate::Address::Address * genr(
Tajada::Code::Block * b
);
};
}
}
#endif
| [
"targen@gmail.com"
] | targen@gmail.com |
19688079901577c712eab4620050ba201f779d0a | 1d928c3f90d4a0a9a3919a804597aa0a4aab19a3 | /c++/ClickHouse/2017/8/ASTLiteral.cpp | bd88a90a301382cb3b948a25b67a24466b144457 | [
"BSL-1.0"
] | permissive | rosoareslv/SED99 | d8b2ff5811e7f0ffc59be066a5a0349a92cbb845 | a062c118f12b93172e31e8ca115ce3f871b64461 | refs/heads/main | 2023-02-22T21:59:02.703005 | 2021-01-28T19:40:51 | 2021-01-28T19:40:51 | 306,497,459 | 1 | 1 | null | 2020-11-24T20:56:18 | 2020-10-23T01:18:07 | null | UTF-8 | C++ | false | false | 810 | cpp | #include <Common/SipHash.h>
#include <Core/FieldVisitors.h>
#include <Parsers/ASTLiteral.h>
#include <IO/WriteHelpers.h>
namespace DB
{
String ASTLiteral::getColumnNameImpl() const
{
/// Special case for very large arrays. Instead of listing all elements, will use hash of them.
/// (Otherwise column name will be too long, that will lead to significant slowdown of expression analysis.)
if (value.getType() == Field::Types::Array
&& value.get<const Array &>().size() > 100) /// 100 - just arbitary value.
{
SipHash hash;
applyVisitor(FieldVisitorHash(hash), value);
UInt64 low, high;
hash.get128(low, high);
return "__array_" + toString(low) + "_" + toString(high);
}
return applyVisitor(FieldVisitorToString(), value);
}
}
| [
"rodrigosoaresilva@gmail.com"
] | rodrigosoaresilva@gmail.com |
e662c436eb642e7a44130d20688dbfa5e6a14778 | dc61e8c951f9e91930c2edff8a53c32d7a99bb94 | /include/inviwo/qt/widgets/properties/lightpropertywidgetqt.h | 5ba7c43bbe9afa60e4aa53659c3b4fd42487c66d | [
"BSD-2-Clause"
] | permissive | johti626/inviwo | d4b2766742522d3c8d57c894a60e345ec35beafc | c429a15b972715157b99f3686b05d581d3e89e92 | refs/heads/master | 2021-01-17T08:14:10.118104 | 2016-05-25T14:38:33 | 2016-05-25T14:46:31 | 31,444,269 | 2 | 0 | null | 2015-02-27T23:45:02 | 2015-02-27T23:45:01 | null | UTF-8 | C++ | false | false | 2,762 | h | /*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2013-2015 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*
*********************************************************************************/
#ifndef IVW_LIGHTPROPERTYWIDGETQT_H
#define IVW_LIGHTPROPERTYWIDGETQT_H
#include <inviwo/qt/widgets/inviwoqtwidgetsdefine.h>
#include <inviwo/core/properties/ordinalproperty.h>
#include <inviwo/qt/widgets/customdoublespinboxqt.h>
#include <inviwo/qt/widgets/editablelabelqt.h>
#include <inviwo/qt/widgets/lightpositionwidgetqt.h>
#include <inviwo/qt/widgets/properties/propertywidgetqt.h>
#include <warn/push>
#include <warn/ignore/all>
#include <QtCore/qmath.h>
#include <QSpinBox>
#include <warn/pop>
namespace inviwo {
class IVW_QTWIDGETS_API LightPropertyWidgetQt : public PropertyWidgetQt {
#include <warn/push>
#include <warn/ignore/all>
Q_OBJECT
#include <warn/pop>
public:
LightPropertyWidgetQt(FloatVec3Property* property);
virtual ~LightPropertyWidgetQt();
void updateFromProperty();
private:
FloatVec3Property* property_;
LightPositionWidgetQt* lightWidget_;
CustomDoubleSpinBoxQt* radiusSpinBox_;
EditableLabelQt* label_;
void generateWidget();
public slots:
void onPositionLightWidgetChanged();
void onRadiusSpinBoxChanged(double radius);
};
} // namespace
#endif // IVW_LightPropertyWidgetQt_H
| [
"eriksunden85@gmail.com"
] | eriksunden85@gmail.com |
d03cd90e49dd06083e6a75fb1eca63860d8bb368 | dcc6234fa754f09bab518f2c430ada8011783f90 | /SqlEngine.cc | b08de7b77443ab4f4d5a7e7978c306005da2906c | [] | no_license | cjsub/cs143_project2 | 2dd92f66aa21efc702827d5ceaa6d98adde9215d | 89ff17ee6b30e2d974511508c0c0842ccfd633ee | refs/heads/master | 2021-01-24T03:48:20.903331 | 2013-02-23T02:08:40 | 2013-02-23T02:08:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,552 | cc | /**
* Copyright (C) 2008 by The Regents of the University of California
* Redistribution of this file is permitted under the terms of the GNU
* Public License (GPL).
*
* @author Junghoo "John" Cho <cho AT cs.ucla.edu>
* @date 3/24/2008
*/
#include <cstdio>
#include <iostream>
#include <fstream>
#include "Bruinbase.h"
#include "SqlEngine.h"
using namespace std;
// external functions and variables for load file and sql command parsing
extern FILE* sqlin;
int sqlparse(void);
RC SqlEngine::run(FILE* commandline)
{
fprintf(stdout, "Bruinbase> ");
// set the command line input and start parsing user input
sqlin = commandline;
sqlparse(); // sqlparse() is defined in SqlParser.tab.c generated from
// SqlParser.y by bison (bison is GNU equivalent of yacc)
return 0;
}
RC SqlEngine::select(int attr, const string& table, const vector<SelCond>& cond)
{
RecordFile rf; // RecordFile containing the table
RecordId rid; // record cursor for table scanning
RC rc;
int key;
string value;
int count;
int diff;
// open the table file
if ((rc = rf.open(table + ".tbl", 'r')) < 0) {
fprintf(stderr, "Error: table %s does not exist\n", table.c_str());
return rc;
}
// scan the table file from the beginning
rid.pid = rid.sid = 0;
count = 0;
while (rid < rf.endRid()) {
// read the tuple
if ((rc = rf.read(rid, key, value)) < 0) {
fprintf(stderr, "Error: while reading a tuple from table %s\n", table.c_str());
goto exit_select;
}
// check the conditions on the tuple
for (unsigned i = 0; i < cond.size(); i++) {
// compute the difference between the tuple value and the condition value
switch (cond[i].attr) {
case 1:
diff = key - atoi(cond[i].value);
break;
case 2:
diff = strcmp(value.c_str(), cond[i].value);
break;
}
// skip the tuple if any condition is not met
switch (cond[i].comp) {
case SelCond::EQ:
if (diff != 0) goto next_tuple;
break;
case SelCond::NE:
if (diff == 0) goto next_tuple;
break;
case SelCond::GT:
if (diff <= 0) goto next_tuple;
break;
case SelCond::LT:
if (diff >= 0) goto next_tuple;
break;
case SelCond::GE:
if (diff < 0) goto next_tuple;
break;
case SelCond::LE:
if (diff > 0) goto next_tuple;
break;
}
}
// the condition is met for the tuple.
// increase matching tuple counter
count++;
// print the tuple
switch (attr) {
case 1: // SELECT key
fprintf(stdout, "%d\n", key);
break;
case 2: // SELECT value
fprintf(stdout, "%s\n", value.c_str());
break;
case 3: // SELECT *
fprintf(stdout, "%d '%s'\n", key, value.c_str());
break;
}
// move to the next tuple
next_tuple:
++rid;
}
// print matching tuple count if "select count(*)"
if (attr == 4) {
fprintf(stdout, "%d\n", count);
}
rc = 0;
// close the table file and return
exit_select:
rf.close();
return rc;
}
RC SqlEngine::load(const string& table, const string& loadfile, bool index)
{
ifstream inputFile;
RecordFile rf;
RecordId rid;
RC rc;
if((rc = rf.open(table + ".tbl", 'w')) < 0) {
fprintf(stderr, "Error while creating table %s\n", table.c_str());
return rc;
}
inputFile.open(loadfile.c_str());
if(!inputFile.is_open()) {
fprintf(stderr, "Error Opening File");
goto exit_select;
}
while (1) {
string line;
int key;
string value;
getline (inputFile, line);
if(!inputFile.good())
break;
parseLoadLine(line, key, value);
if(rf.append(key, value, rid) < 0)
{
fprintf(stderr, "Error appending tuple");
goto exit_select;
}
}
exit_select:
inputFile.close();
rf.close();
return rc;
}
RC SqlEngine::parseLoadLine(const string& line, int& key, string& value)
{
const char *s;
char c;
string::size_type loc;
// ignore beginning white spaces
c = *(s = line.c_str());
while (c == ' ' || c == '\t') { c = *++s; }
// get the integer key value
key = atoi(s);
// look for comma
s = strchr(s, ',');
if (s == NULL) { return RC_INVALID_FILE_FORMAT; }
// ignore white spaces
do { c = *++s; } while (c == ' ' || c == '\t');
// if there is nothing left, set the value to empty string
if (c == 0) {
value.erase();
return 0;
}
// is the value field delimited by ' or "?
if (c == '\'' || c == '"') {
s++;
} else {
c = '\n';
}
// get the value string
value.assign(s);
loc = value.find(c, 0);
if (loc != string::npos) { value.erase(loc); }
return 0;
}
| [
"sehunchoi@gmail.com"
] | sehunchoi@gmail.com |
698d50530f487ef794ba0e80419aff41e27b02f8 | 7e1e036af3a15dd1d1c0940109f5943010144f7e | /Aula 03/Pos-Aula 03.cpp | 5217a95611494b9ecef15c9ffa978e114079ad39 | [] | no_license | GustaFreitas/AulasAED | 7ecb1f03c70c1eac91aa83d1833d5b84f29b947f | 5ed05ecf1bca04a9f24ca1bdbd1ae7fa5f55a6c9 | refs/heads/master | 2021-03-04T23:21:21.890940 | 2020-06-01T21:31:46 | 2020-06-01T21:31:46 | 246,075,313 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 2,825 | cpp | #include <math.h>
#include <conio.h>
#include <stdio.h>
#include <locale.h>
#include <stdlib.h>
#include <string.h>
struct Bolsa
{
char Nom[50], Are[20];
float Val_Atu, Val_Ant, Dif;
double Var;
};
float Media (float x)
{
return (x / 5);
}
float Novo (float x, float y)
{
return (x + y);
}
int main (void)
{
setlocale (LC_ALL, "Portuguese");
struct Bolsa V[6];
char Aux = '%';
for (int i = 1; i <= 5; i++)
{
printf ("Informe o nome da compania: ");
scanf ("%s", &V[i].Nom);
fflush (stdin);
printf ("Informe a área de atuação da compania: ");
scanf ("%s", &V[i].Are);
fflush (stdin);
printf ("Informe o valor atual das ações: ");
scanf ("%f", &V[i].Val_Atu);
fflush (stdin);
printf ("Informe o valor anterior das ações: ");
scanf ("%f", &V[i].Val_Ant);
fflush (stdin);
V[i].Dif = V[i].Val_Atu - V[i].Val_Ant;
V[i].Var = (V[i].Dif * 100) / V[i].Val_Ant;
if (V[i].Dif < 0)
{
printf ("A compania %s do ramo de %s teve uma queda de %.2lf%c desde a abertura da bolsa.\n", V[i].Nom, V[i].Are, V[i].Var, Aux);
}
else
{
printf ("\n\n A compania %s do ramo de %s teve um aumento de %.2lf%C desde a abertura da bolsa.\n", V[i].Nom, V[i].Are, V[i].Var, Aux);
}
printf ("----------------------------------------------------------------------------------\n");
}
system ("pause");
system ("cls");
float Val, Med, Par;
printf ("Informe um valor de ação: ");
scanf ("%f", &Val);
printf ("As seguintes ações estão do indicado:\n");
for (int i = 1; i <= 5; i++)
{
if (Val > V[i].Val_Atu)
{
printf ("Compania: %s\n", V[i].Nom);
printf ("Valor das ações: %.2f\n\n", V[i].Val_Atu);
}
Med = Med + V[i].Val_Atu;
}
system ("pause");
system ("cls");
printf ("A média das ações é: %.2f\n\n", Media (Med));
system ("pause");
system ("cls");
printf ("Escolha um novo parametro para alterar as acões de todas as companias: ");
scanf ("%f", &Par);
("----------------------------------------------------------------------------------\n\n");
for (int i = 1; i <= 5; i++)
{
V[i].Val_Atu = Novo (Par, V[i].Val_Atu);
V[i].Dif = V[i].Val_Atu - V[i].Val_Ant;
V[i].Var = (V[i].Dif * 100) / V[i].Val_Ant;
printf ("Compania: %s\n", V[i].Nom);
printf ("Novo valor de ações: %.2f\n", V[i].Val_Atu);
if (V[i].Dif < 0)
{
printf ("A compania %s do ramo de %s teve uma queda de %.2lf%c desde a abertura da bolsa.\n", V[i].Nom, V[i].Are, V[i].Var, Aux);
}
else
{
printf ("\n\n A compania %s do ramo de %s teve um aumento de %.2lf%C desde a abertura da bolsa.\n", V[i].Nom, V[i].Are, V[i].Var, Aux);
}
printf ("----------------------------------------------------------------------------------\n");
}
getch();
return 0;
}
| [
"gustavoluizdefreitas@hotmail.com.br"
] | gustavoluizdefreitas@hotmail.com.br |
fcb4311f6f18fc608b4a938e55d3cee38192f212 | c075cfe521103977789d600b61ad05b605f4fb10 | /PI/ZAD_A.cpp | accad407d4909894943044aaeb2058198318eac3 | [] | no_license | igoroogle/codeforces | dd3c99b6a5ceb19d7d9495b370d4b2ef8949f534 | 579cd1d2aa30a0b0b4cc61d104a02499c69ac152 | refs/heads/master | 2020-07-20T12:37:07.225539 | 2019-09-05T19:21:27 | 2019-09-05T19:35:26 | 206,639,451 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 630 | cpp | #include <iostream>
#include <iomanip>
#include <cstdio>
#include <algorithm>
#include <cstdlib>
#include <vector>
#include <set>
#include <cmath>
#include <map>
using namespace std;
typedef long long ll;
const ll INF = 1000000000000000000;
ll a[100010];
int main()
{
ll n, i, x, y;
cin >> n;
for (i = 0; i < n; i++) scanf("%I64d", &a[i]);
for (i = 0; i < n; i++)
{
x = INF;
if (i - 1 >= 0) x = abs(a[i - 1] - a[i]);
y = INF;
if (i + 1 < n) y = abs(a[i + 1] - a[i]);
printf("%I64d %I64d\n", min(x, y), max(abs(a[0] - a[i]), abs(a[n - 1] - a[i])));
}
return 0;
}
| [
"160698qnigor98"
] | 160698qnigor98 |
9131de57b8b629101b0fad4e2b340203867d00de | 5370b9e27da3064f35a59610b7746a263204e621 | /CodeForces/Div3/Round498/b.cpp | 9c2fdeb07f274250d7440d2c6e024720ca372538 | [] | no_license | Paryul10/Competetive-Coding | 4619d84b282d58303dc5db9cb8bdad769fc3176d | 3cc06f80dfffe4dc742fd5d8a4b427a9de778d85 | refs/heads/master | 2020-04-02T11:12:49.838056 | 2018-08-02T11:36:04 | 2018-08-02T11:36:04 | 154,376,787 | 0 | 1 | null | 2019-10-19T12:00:45 | 2018-10-23T18:22:09 | C++ | UTF-8 | C++ | false | false | 1,086 | cpp | #include "bits/stdc++.h"
#include "string"
using namespace std;
int main()
{
int n, k;
cin >> n >> k;
int arr[n];
for (int i=0; i<n; i++) cin >> arr[i];
vector <pair<int, int> > ind;
for (int i=0; i<n; i++)
{
ind.push_back(make_pair(arr[i], i));
}
sort(ind.begin(), ind.end());
int inx[k];
long long max = 0;
int x = 0;
for (int i=(n-1); i>=(n-k); i--)
{
inx[x] = ind[i].second;
max += ind[i].first;
x++;
}
cout << max << endl;
sort(inx, inx+k);
if (k == 1) cout << n << endl;
else
{
cout << inx[0] + 1 << " ";
for (int i=1; i<k; i++)
{
if (inx[k-1]!=(n-1))
{
if (i!=(k-1)) cout << inx[i] - inx[i-1] << " ";
else cout << (n-1) - inx[k-2] << " ";
}
else
{
if (i!=(k-1)) cout << inx[i] - inx[i-1] << " ";
else cout << inx[k-1] - inx[k-2] << " ";
}
}
cout << endl;
}
return 0;
} | [
"eeshadutta99@gmail.com"
] | eeshadutta99@gmail.com |
92c6b2d5de2bdbec5503462c3736bb14137f32e8 | 8d672a07b0f1182471aefea80e26bfdac4d2eac5 | /Repo Server/Repo Server/Pro2/Version/version.cpp | 2e8dd8b42fe8ad0a32b9aeb14210d6c06b49ce45 | [] | no_license | nileshivam/Repo_Build_server | 80a80770934a330ee229daa01d21286e71b9ab43 | 218fc0bae7c3edc6d31918a9f8213637efcaea09 | refs/heads/master | 2020-03-18T16:45:10.590787 | 2018-05-28T22:49:42 | 2018-05-28T22:49:42 | 134,984,583 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,104 | cpp | //////////////////////////////////////////////////////////////////////
// Version.cpp - Implements Version Functionalities //
// ver 1.0 //
// Source: Jim Jawcett //
// Dwivedi Nilesh, CSE687 - Object Oriented Design, Spring 2018 //
//////////////////////////////////////////////////////////////////////
#include<string>
#include "version.h"
#include "../../FileSystem-Windows/FileSystemDemo/FileSystem.h"
using namespace RepoCore;
//----<Return the Latest Version of File>----------
int Version::getLatestVersion(std::string fileName)
{
int ver = 0;
while (repo_.db().contains(fileName + "." + std::to_string(ver + 1)))
{
ver++;
}
return ver;
}
//----<Function to test Functionality of Version>----------
bool TestRepoCore::testVersion(RepositoryCore& r)
{
RepoCore::Version v(r);
std::cout << "Getting the latest version of C::C.h ---> " << v.getLatestVersion("C::C.h") << std::endl;
return true;
}
#ifdef TEST_VERSION
//----<Entry Point of Version>----------
int main()
{
RepositoryCore r;
TestRepoCore::testVersion(r);
}
#endif | [
"dwivedinilesh11@gmail.com"
] | dwivedinilesh11@gmail.com |
510efa5ce86b2b9878848b0688d003617704d6dc | 0b66e8133c28fd50e2ffddba741710bdc7756cb4 | /1.BinaryTree/1325. Delete Leaves With a Given Value.cc | a96f6632253a9479a5828cc6cd4a674af0b98e0d | [] | no_license | tonyxwz/leetcode | 21abed951622ed3606fc89c580cd32cda7b84a2f | 1b7d06e638c0ff278c62d3bae27076b0881b5fde | refs/heads/master | 2023-04-05T07:10:18.342010 | 2021-04-13T11:45:58 | 2021-04-13T11:45:58 | 71,467,875 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 980 | cc | // https:// leetcode.com/problems/delete-leaves-with-a-given-value/
#include "leetcode.h"
// 思路:后序遍历树如果左孩子和右孩子都是空且root
// ->val等于target,那么删除当前节点。删除的方式是返回空值即可。
// ```cpp
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x),
* left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* removeLeafNodes(TreeNode* root, int target) {
// dfs
if (!root) return root;
root->left = removeLeafNodes(root->left, target);
root->right = removeLeafNodes(root->right, target);
if (!root->left && !root->right && root->val == target) {
return nullptr;
}
return root;
}
};
// ``` | [
"tonyxwz@yahoo.com"
] | tonyxwz@yahoo.com |
a86a3cdb105058cf4b7a43042198ce12b29eb609 | 88026fecc64f11bb17c4c7f938fc3ff60c80e72f | /src/wallet/rpcwallet.cpp | af0f90db3709ce5b018f47f4ce6ba9978d41a441 | [
"MIT"
] | permissive | docharlow/spoomy | 59c54e9a97fd91e54cdf46daafb50215edcc0025 | 794c5cbed698857d1078efede59bad1e73d4af8d | refs/heads/master | 2020-04-16T10:49:30.187434 | 2019-01-13T15:24:22 | 2019-01-13T15:24:22 | 165,518,257 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 121,387 | cpp | // Copyright (c) 2009-2018 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin Developers
// Copyright (c) 2014-2018 The Dash Core Developers
// Copyright (c) 2017-2018 Spoomy Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "amount.h"
#include "base58.h"
#include "chain.h"
#include "core_io.h"
#include "init.h"
#include "keepass.h"
#include "main.h"
#include "net.h"
#include "netbase.h"
#include "policy/rbf.h"
#include "rpcserver.h"
#include "timedata.h"
#include "util.h"
#include "utilmoneystr.h"
#include "wallet.h"
#include "walletdb.h"
#include <univalue.h>
#include <stdint.h>
#include <boost/assign/list_of.hpp>
int64_t nWalletUnlockTime;
static CCriticalSection cs_nWalletUnlockTime;
std::string HelpRequiringPassphrase()
{
return pwalletMain && pwalletMain->IsCrypted()
? "\nRequires wallet passphrase to be set with walletpassphrase call."
: "";
}
bool EnsureWalletIsAvailable(bool avoidException)
{
if (!pwalletMain)
{
if (!avoidException)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
else
return false;
}
return true;
}
void EnsureWalletIsUnlocked()
{
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
}
void WalletTxToJSON(const CWalletTx& wtx, UniValue& entry)
{
int confirms = wtx.GetDepthInMainChain(false);
int confirmsTotal = GetISConfirmations(wtx.GetHash()) + confirms;
entry.push_back(Pair("confirmations", confirmsTotal));
entry.push_back(Pair("bcconfirmations", confirms));
if (wtx.IsCoinBase())
entry.push_back(Pair("generated", true));
if (confirms > 0)
{
entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex()));
entry.push_back(Pair("blockindex", wtx.nIndex));
entry.push_back(Pair("blocktime", mapBlockIndex[wtx.hashBlock]->GetBlockTime()));
} else {
entry.push_back(Pair("trusted", wtx.IsTrusted()));
}
uint256 hash = wtx.GetHash();
entry.push_back(Pair("txid", hash.GetHex()));
UniValue conflicts(UniValue::VARR);
BOOST_FOREACH(const uint256& conflict, wtx.GetConflicts())
conflicts.push_back(conflict.GetHex());
entry.push_back(Pair("walletconflicts", conflicts));
entry.push_back(Pair("time", wtx.GetTxTime()));
entry.push_back(Pair("timereceived", (int64_t)wtx.nTimeReceived));
// Add opt-in RBF status
std::string rbfStatus = "no";
if (confirms <= 0) {
LOCK(mempool.cs);
if (!mempool.exists(hash)) {
if (SignalsOptInRBF(wtx)) {
rbfStatus = "yes";
} else {
rbfStatus = "unknown";
}
} else if (IsRBFOptIn(*mempool.mapTx.find(hash), mempool)) {
rbfStatus = "yes";
}
}
entry.push_back(Pair("bip125-replaceable", rbfStatus));
BOOST_FOREACH(const PAIRTYPE(std::string,std::string)& item, wtx.mapValue)
entry.push_back(Pair(item.first, item.second));
}
std::string AccountFromValue(const UniValue& value)
{
std::string strAccount = value.get_str();
if (strAccount == "*")
throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name");
return strAccount;
}
UniValue getnewaddress(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 1)
throw std::runtime_error(
"getnewaddress ( \"account\" )\n"
"\nReturns a new Spoomy address for receiving payments.\n"
"If 'account' is specified (DEPRECATED), it is added to the address book \n"
"so payments received with the address will be credited to 'account'.\n"
"\nArguments:\n"
"1. \"account\" (string, optional) DEPRECATED. The account name for the address to be linked to. If not provided, the default account \"\" is used. It can also be set to the empty string \"\" to represent the default account. The account does not need to exist, it will be created if there is no account by the given name.\n"
"\nResult:\n"
"\"zumyaddress\" (string) The new spoomy address\n"
"\nExamples:\n"
+ HelpExampleCli("getnewaddress", "")
+ HelpExampleRpc("getnewaddress", "")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
// Parse the account first so we don't generate a key if there's an error
std::string strAccount;
if (params.size() > 0)
strAccount = AccountFromValue(params[0]);
if (!pwalletMain->IsLocked(true))
pwalletMain->TopUpKeyPool();
// Generate a new key that is added to wallet
CPubKey newKey;
if (!pwalletMain->GetKeyFromPool(newKey, false))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
CKeyID keyID = newKey.GetID();
pwalletMain->SetAddressBook(keyID, strAccount, "receive");
return CSpoomyAddress(keyID).ToString();
}
CSpoomyAddress GetAccountAddress(std::string strAccount, bool bForceNew=false)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
CAccount account;
walletdb.ReadAccount(strAccount, account);
bool bKeyUsed = false;
// Check if the current key has been used
if (account.vchPubKey.IsValid())
{
CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID());
for (std::map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin();
it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid();
++it)
{
const CWalletTx& wtx = (*it).second;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
bKeyUsed = true;
}
}
// Generate a new key
if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed)
{
if (!pwalletMain->GetKeyFromPool(account.vchPubKey, false))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
pwalletMain->SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
walletdb.WriteAccount(strAccount, account);
}
return CSpoomyAddress(account.vchPubKey.GetID());
}
UniValue getaccountaddress(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 1)
throw std::runtime_error(
"getaccountaddress \"account\"\n"
"\nDEPRECATED. Returns the current Spoomy address for receiving payments to this account.\n"
"\nArguments:\n"
"1. \"account\" (string, required) The account name for the address. It can also be set to the empty string \"\" to represent the default account. The account does not need to exist, it will be created and a new address created if there is no account by the given name.\n"
"\nResult:\n"
"\"zumyaddress\" (string) The account spoomy address\n"
"\nExamples:\n"
+ HelpExampleCli("getaccountaddress", "")
+ HelpExampleCli("getaccountaddress", "\"\"")
+ HelpExampleCli("getaccountaddress", "\"myaccount\"")
+ HelpExampleRpc("getaccountaddress", "\"myaccount\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
// Parse the account first so we don't generate a key if there's an error
std::string strAccount = AccountFromValue(params[0]);
UniValue ret(UniValue::VSTR);
ret = GetAccountAddress(strAccount).ToString();
return ret;
}
UniValue getrawchangeaddress(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 1)
throw std::runtime_error(
"getrawchangeaddress\n"
"\nReturns a new Spoomy address, for receiving change.\n"
"This is for use with raw transactions, NOT normal use.\n"
"\nResult:\n"
"\"address\" (string) The address\n"
"\nExamples:\n"
+ HelpExampleCli("getrawchangeaddress", "")
+ HelpExampleRpc("getrawchangeaddress", "")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
if (!pwalletMain->IsLocked(true))
pwalletMain->TopUpKeyPool();
CReserveKey reservekey(pwalletMain);
CPubKey vchPubKey;
if (!reservekey.GetReservedKey(vchPubKey, true))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
reservekey.KeepKey();
CKeyID keyID = vchPubKey.GetID();
return CSpoomyAddress(keyID).ToString();
}
UniValue setaccount(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 1 || params.size() > 2)
throw std::runtime_error(
"setaccount \"zumyaddress\" \"account\"\n"
"\nDEPRECATED. Sets the account associated with the given address.\n"
"\nArguments:\n"
"1. \"zumyaddress\" (string, required) The spoomy address to be associated with an account.\n"
"2. \"account\" (string, required) The account to assign the address to.\n"
"\nExamples:\n"
+ HelpExampleCli("setaccount", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\" \"tabby\"")
+ HelpExampleRpc("setaccount", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\", \"tabby\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
CSpoomyAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Spoomy address");
std::string strAccount;
if (params.size() > 1)
strAccount = AccountFromValue(params[1]);
// Only add the account if the address is yours.
if (IsMine(*pwalletMain, address.Get()))
{
// Detect when changing the account of an address that is the 'unused current key' of another account:
if (pwalletMain->mapAddressBook.count(address.Get()))
{
std::string strOldAccount = pwalletMain->mapAddressBook[address.Get()].name;
if (address == GetAccountAddress(strOldAccount))
GetAccountAddress(strOldAccount, true);
}
pwalletMain->SetAddressBook(address.Get(), strAccount, "receive");
}
else
throw JSONRPCError(RPC_MISC_ERROR, "setaccount can only be used with own address");
return NullUniValue;
}
UniValue getaccount(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 1)
throw std::runtime_error(
"getaccount \"zumyaddress\"\n"
"\nDEPRECATED. Returns the account associated with the given address.\n"
"\nArguments:\n"
"1. \"zumyaddress\" (string, required) The spoomy address for account lookup.\n"
"\nResult:\n"
"\"accountname\" (string) the account address\n"
"\nExamples:\n"
+ HelpExampleCli("getaccount", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\"")
+ HelpExampleRpc("getaccount", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
CSpoomyAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Spoomy address");
std::string strAccount;
std::map<CTxDestination, CAddressBookData>::iterator mi = pwalletMain->mapAddressBook.find(address.Get());
if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.name.empty())
strAccount = (*mi).second.name;
return strAccount;
}
UniValue getaddressesbyaccount(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 1)
throw std::runtime_error(
"getaddressesbyaccount \"account\"\n"
"\nDEPRECATED. Returns the list of addresses for the given account.\n"
"\nArguments:\n"
"1. \"account\" (string, required) The account name.\n"
"\nResult:\n"
"[ (json array of string)\n"
" \"zumyaddress\" (string) a spoomy address associated with the given account\n"
" ,...\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("getaddressesbyaccount", "\"tabby\"")
+ HelpExampleRpc("getaddressesbyaccount", "\"tabby\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
std::string strAccount = AccountFromValue(params[0]);
// Find all addresses that have the given account
UniValue ret(UniValue::VARR);
BOOST_FOREACH(const PAIRTYPE(CSpoomyAddress, CAddressBookData)& item, pwalletMain->mapAddressBook)
{
const CSpoomyAddress& address = item.first;
const std::string& strName = item.second.name;
if (strName == strAccount)
ret.push_back(address.ToString());
}
return ret;
}
static void SendMoney(const CTxDestination &address, CAmount nValue, bool fSubtractFeeFromAmount, CWalletTx& wtxNew, bool fUseInstantSend=false, bool fUsePrivateSend=false)
{
CAmount curBalance = pwalletMain->GetBalance();
// Check amount
if (nValue <= 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid amount");
if (nValue > curBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds");
// Parse Spoomy address
CScript scriptPubKey = GetScriptForDestination(address);
// Create and send the transaction
CReserveKey reservekey(pwalletMain);
CAmount nFeeRequired;
std::string strError;
std::vector<CRecipient> vecSend;
int nChangePosRet = -1;
CRecipient recipient = {scriptPubKey, nValue, fSubtractFeeFromAmount};
vecSend.push_back(recipient);
if (!pwalletMain->CreateTransaction(vecSend, wtxNew, reservekey, nFeeRequired, nChangePosRet,
strError, NULL, true, fUsePrivateSend ? ONLY_DENOMINATED : ALL_COINS, fUseInstantSend)) {
if (!fSubtractFeeFromAmount && nValue + nFeeRequired > pwalletMain->GetBalance())
strError = strprintf("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!", FormatMoney(nFeeRequired));
throw JSONRPCError(RPC_WALLET_ERROR, strError);
}
if (!pwalletMain->CommitTransaction(wtxNew, reservekey, fUseInstantSend ? NetMsgType::TXLOCKREQUEST : NetMsgType::TX))
throw JSONRPCError(RPC_WALLET_ERROR, "Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.");
}
UniValue sendtoaddress(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 2 || params.size() > 7)
throw std::runtime_error(
"sendtoaddress \"zumyaddress\" amount ( \"comment\" \"comment-to\" subtractfeefromamount use_is use_ps )\n"
"\nSend an amount to a given address.\n"
+ HelpRequiringPassphrase() +
"\nArguments:\n"
"1. \"zumyaddress\" (string, required) The spoomy address to send to.\n"
"2. \"amount\" (numeric or string, required) The amount in " + CURRENCY_UNIT + " to send. eg 0.1\n"
"3. \"comment\" (string, optional) A comment used to store what the transaction is for. \n"
" This is not part of the transaction, just kept in your wallet.\n"
"4. \"comment-to\" (string, optional) A comment to store the name of the person or organization \n"
" to which you're sending the transaction. This is not part of the \n"
" transaction, just kept in your wallet.\n"
"5. subtractfeefromamount (boolean, optional, default=false) The fee will be deducted from the amount being sent.\n"
" The recipient will receive less Spoomy than you enter in the amount field.\n"
"6. \"use_is\" (bool, optional) Send this transaction as InstantSend (default: false)\n"
"7. \"use_ps\" (bool, optional) Use anonymized funds only (default: false)\n"
"\nResult:\n"
"\"transactionid\" (string) The transaction id.\n"
"\nExamples:\n"
+ HelpExampleCli("sendtoaddress", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\" 0.1")
+ HelpExampleCli("sendtoaddress", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\" 0.1 \"donation\" \"seans outpost\"")
+ HelpExampleCli("sendtoaddress", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\" 0.1 \"\" \"\" true")
+ HelpExampleRpc("sendtoaddress", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\", 0.1, \"donation\", \"seans outpost\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
CSpoomyAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Spoomy address");
// Amount
CAmount nAmount = AmountFromValue(params[1]);
if (nAmount <= 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
// Wallet comments
CWalletTx wtx;
if (params.size() > 2 && !params[2].isNull() && !params[2].get_str().empty())
wtx.mapValue["comment"] = params[2].get_str();
if (params.size() > 3 && !params[3].isNull() && !params[3].get_str().empty())
wtx.mapValue["to"] = params[3].get_str();
bool fSubtractFeeFromAmount = false;
if (params.size() > 4)
fSubtractFeeFromAmount = params[4].get_bool();
bool fUseInstantSend = false;
bool fUsePrivateSend = false;
if (params.size() > 5)
fUseInstantSend = params[5].get_bool();
if (params.size() > 6)
fUsePrivateSend = params[6].get_bool();
EnsureWalletIsUnlocked();
SendMoney(address.Get(), nAmount, fSubtractFeeFromAmount, wtx, fUseInstantSend, fUsePrivateSend);
return wtx.GetHash().GetHex();
}
UniValue instantsendtoaddress(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 2 || params.size() > 5)
throw std::runtime_error(
"instantsendtoaddress \"zumyaddress\" amount ( \"comment\" \"comment-to\" subtractfeefromamount )\n"
"\nSend an amount to a given address. The amount is a real and is rounded to the nearest 0.00000001\n"
+ HelpRequiringPassphrase() +
"\nArguments:\n"
"1. \"zumyaddress\" (string, required) The spoomy address to send to.\n"
"2. \"amount\" (numeric, required) The amount in btc to send. eg 0.1\n"
"3. \"comment\" (string, optional) A comment used to store what the transaction is for. \n"
" This is not part of the transaction, just kept in your wallet.\n"
"4. \"comment-to\" (string, optional) A comment to store the name of the person or organization \n"
" to which you're sending the transaction. This is not part of the \n"
" transaction, just kept in your wallet.\n"
"5. subtractfeefromamount (boolean, optional, default=false) The fee will be deducted from the amount being sent.\n"
" The recipient will receive less Spoomy than you enter in the amount field.\n"
"\nResult:\n"
"\"transactionid\" (string) The transaction id.\n"
"\nExamples:\n"
+ HelpExampleCli("instantsendtoaddress", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\" 0.1")
+ HelpExampleCli("instantsendtoaddress", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\" 0.1 \"donation\" \"seans outpost\"")
+ HelpExampleCli("instantsendtoaddress", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\" 0.1 \"\" \"\" true")
+ HelpExampleRpc("instantsendtoaddress", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\", 0.1, \"donation\", \"seans outpost\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
CSpoomyAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Spoomy address");
// Amount
CAmount nAmount = AmountFromValue(params[1]);
if (nAmount <= 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
// Wallet comments
CWalletTx wtx;
if (params.size() > 2 && !params[2].isNull() && !params[2].get_str().empty())
wtx.mapValue["comment"] = params[2].get_str();
if (params.size() > 3 && !params[3].isNull() && !params[3].get_str().empty())
wtx.mapValue["to"] = params[3].get_str();
bool fSubtractFeeFromAmount = false;
if (params.size() > 4)
fSubtractFeeFromAmount = params[4].get_bool();
EnsureWalletIsUnlocked();
SendMoney(address.Get(), nAmount, fSubtractFeeFromAmount, wtx, true);
return wtx.GetHash().GetHex();
}
UniValue listaddressgroupings(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp)
throw std::runtime_error(
"listaddressgroupings\n"
"\nLists groups of addresses which have had their common ownership\n"
"made public by common use as inputs or as the resulting change\n"
"in past transactions\n"
"\nResult:\n"
"[\n"
" [\n"
" [\n"
" \"zumyaddress\", (string) The spoomy address\n"
" amount, (numeric) The amount in " + CURRENCY_UNIT + "\n"
" \"account\" (string, optional) The account (DEPRECATED)\n"
" ]\n"
" ,...\n"
" ]\n"
" ,...\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("listaddressgroupings", "")
+ HelpExampleRpc("listaddressgroupings", "")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
UniValue jsonGroupings(UniValue::VARR);
std::map<CTxDestination, CAmount> balances = pwalletMain->GetAddressBalances();
BOOST_FOREACH(std::set<CTxDestination> grouping, pwalletMain->GetAddressGroupings())
{
UniValue jsonGrouping(UniValue::VARR);
BOOST_FOREACH(CTxDestination address, grouping)
{
UniValue addressInfo(UniValue::VARR);
addressInfo.push_back(CSpoomyAddress(address).ToString());
addressInfo.push_back(ValueFromAmount(balances[address]));
{
if (pwalletMain->mapAddressBook.find(CSpoomyAddress(address).Get()) != pwalletMain->mapAddressBook.end())
addressInfo.push_back(pwalletMain->mapAddressBook.find(CSpoomyAddress(address).Get())->second.name);
}
jsonGrouping.push_back(addressInfo);
}
jsonGroupings.push_back(jsonGrouping);
}
return jsonGroupings;
}
UniValue signmessage(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 2)
throw std::runtime_error(
"signmessage \"zumyaddress\" \"message\"\n"
"\nSign a message with the private key of an address"
+ HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. \"zumyaddress\" (string, required) The spoomy address to use for the private key.\n"
"2. \"message\" (string, required) The message to create a signature of.\n"
"\nResult:\n"
"\"signature\" (string) The signature of the message encoded in base 64\n"
"\nExamples:\n"
"\nUnlock the wallet for 30 seconds\n"
+ HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
"\nCreate the signature\n"
+ HelpExampleCli("signmessage", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\" \"my message\"") +
"\nVerify the signature\n"
+ HelpExampleCli("verifymessage", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\" \"signature\" \"my message\"") +
"\nAs json rpc\n"
+ HelpExampleRpc("signmessage", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\", \"my message\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
EnsureWalletIsUnlocked();
std::string strAddress = params[0].get_str();
std::string strMessage = params[1].get_str();
CSpoomyAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
CKey key;
if (!pwalletMain->GetKey(keyID, key))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
std::vector<unsigned char> vchSig;
if (!key.SignCompact(ss.GetHash(), vchSig))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
return EncodeBase64(&vchSig[0], vchSig.size());
}
UniValue getreceivedbyaddress(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 1 || params.size() > 2)
throw std::runtime_error(
"getreceivedbyaddress \"zumyaddress\" ( minconf )\n"
"\nReturns the total amount received by the given zumyaddress in transactions with at least minconf confirmations.\n"
"\nArguments:\n"
"1. \"zumyaddress\" (string, required) The spoomy address for transactions.\n"
"2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
"\nResult:\n"
"amount (numeric) The total amount in " + CURRENCY_UNIT + " received at this address.\n"
"\nExamples:\n"
"\nThe amount from transactions with at least 1 confirmation\n"
+ HelpExampleCli("getreceivedbyaddress", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\"") +
"\nThe amount including unconfirmed transactions, zero confirmations\n"
+ HelpExampleCli("getreceivedbyaddress", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\" 0") +
"\nThe amount with at least 10 confirmation, very safe\n"
+ HelpExampleCli("getreceivedbyaddress", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\" 10") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("getreceivedbyaddress", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\", 10")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
// Spoomy address
CSpoomyAddress address = CSpoomyAddress(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Spoomy address");
CScript scriptPubKey = GetScriptForDestination(address.Get());
if (!IsMine(*pwalletMain, scriptPubKey))
return ValueFromAmount(0);
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Tally
CAmount nAmount = 0;
for (std::map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !CheckFinalTx(wtx))
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
return ValueFromAmount(nAmount);
}
UniValue getreceivedbyaccount(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 1 || params.size() > 2)
throw std::runtime_error(
"getreceivedbyaccount \"account\" ( minconf )\n"
"\nDEPRECATED. Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.\n"
"\nArguments:\n"
"1. \"account\" (string, required) The selected account, may be the default account using \"\".\n"
"2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
"\nResult:\n"
"amount (numeric) The total amount in " + CURRENCY_UNIT + " received for this account.\n"
"\nExamples:\n"
"\nAmount received by the default account with at least 1 confirmation\n"
+ HelpExampleCli("getreceivedbyaccount", "\"\"") +
"\nAmount received at the tabby account including unconfirmed amounts with zero confirmations\n"
+ HelpExampleCli("getreceivedbyaccount", "\"tabby\" 0") +
"\nThe amount with at least 10 confirmation, very safe\n"
+ HelpExampleCli("getreceivedbyaccount", "\"tabby\" 10") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("getreceivedbyaccount", "\"tabby\", 10")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Get the set of pub keys assigned to account
std::string strAccount = AccountFromValue(params[0]);
std::set<CTxDestination> setAddress = pwalletMain->GetAccountAddresses(strAccount);
// Tally
CAmount nAmount = 0;
for (std::map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !CheckFinalTx(wtx))
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address))
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
}
return ValueFromAmount(nAmount);
}
UniValue getbalance(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 3)
throw std::runtime_error(
"getbalance ( \"account\" minconf includeWatchonly )\n"
"\nIf account is not specified, returns the server's total available balance.\n"
"If account is specified (DEPRECATED), returns the balance in the account.\n"
"Note that the account \"\" is not the same as leaving the parameter out.\n"
"The server total may be different to the balance in the default \"\" account.\n"
"\nArguments:\n"
"1. \"account\" (string, optional) DEPRECATED. The selected account, or \"*\" for entire wallet. It may be the default account using \"\".\n"
"2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
"3. includeWatchonly (bool, optional, default=false) Also include balance in watchonly addresses (see 'importaddress')\n"
"\nResult:\n"
"amount (numeric) The total amount in " + CURRENCY_UNIT + " received for this account.\n"
"\nExamples:\n"
"\nThe total amount in the wallet\n"
+ HelpExampleCli("getbalance", "") +
"\nThe total amount in the wallet at least 5 blocks confirmed\n"
+ HelpExampleCli("getbalance", "\"*\" 10") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("getbalance", "\"*\", 10")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
if (params.size() == 0)
return ValueFromAmount(pwalletMain->GetBalance());
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
isminefilter filter = ISMINE_SPENDABLE;
if(params.size() > 2)
if(params[2].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
if (params[0].get_str() == "*") {
// Calculate total balance a different way from GetBalance()
// (GetBalance() sums up all unspent TxOuts)
// getbalance and "getbalance * 1 true" should return the same number
CAmount nBalance = 0;
for (std::map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < 0)
continue;
CAmount allFee;
std::string strSentAccount;
std::list<COutputEntry> listReceived;
std::list<COutputEntry> listSent;
wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
if (wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const COutputEntry& r, listReceived)
nBalance += r.amount;
}
BOOST_FOREACH(const COutputEntry& s, listSent)
nBalance -= s.amount;
nBalance -= allFee;
}
return ValueFromAmount(nBalance);
}
std::string strAccount = AccountFromValue(params[0]);
CAmount nBalance = pwalletMain->GetAccountBalance(strAccount, nMinDepth, filter);
return ValueFromAmount(nBalance);
}
UniValue getunconfirmedbalance(const UniValue ¶ms, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 0)
throw std::runtime_error(
"getunconfirmedbalance\n"
"Returns the server's total unconfirmed balance\n");
LOCK2(cs_main, pwalletMain->cs_wallet);
return ValueFromAmount(pwalletMain->GetUnconfirmedBalance());
}
UniValue movecmd(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 3 || params.size() > 5)
throw std::runtime_error(
"move \"fromaccount\" \"toaccount\" amount ( minconf \"comment\" )\n"
"\nDEPRECATED. Move a specified amount from one account in your wallet to another.\n"
"\nArguments:\n"
"1. \"fromaccount\" (string, required) The name of the account to move funds from. May be the default account using \"\".\n"
"2. \"toaccount\" (string, required) The name of the account to move funds to. May be the default account using \"\".\n"
"3. amount (numeric) Quantity of " + CURRENCY_UNIT + " to move between accounts.\n"
"4. minconf (numeric, optional, default=1) Only use funds with at least this many confirmations.\n"
"5. \"comment\" (string, optional) An optional comment, stored in the wallet only.\n"
"\nResult:\n"
"true|false (boolean) true if successful.\n"
"\nExamples:\n"
"\nMove 0.01 " + CURRENCY_UNIT + " from the default account to the account named tabby\n"
+ HelpExampleCli("move", "\"\" \"tabby\" 0.01") +
"\nMove 0.01 " + CURRENCY_UNIT + " timotei to akiko with a comment and funds have 10 confirmations\n"
+ HelpExampleCli("move", "\"timotei\" \"akiko\" 0.01 10 \"happy birthday!\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("move", "\"timotei\", \"akiko\", 0.01, 10, \"happy birthday!\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
std::string strFrom = AccountFromValue(params[0]);
std::string strTo = AccountFromValue(params[1]);
CAmount nAmount = AmountFromValue(params[2]);
if (nAmount <= 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
if (params.size() > 3)
// unused parameter, used to be nMinDepth, keep type-checking it though
(void)params[3].get_int();
std::string strComment;
if (params.size() > 4)
strComment = params[4].get_str();
CWalletDB walletdb(pwalletMain->strWalletFile);
if (!walletdb.TxnBegin())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
int64_t nNow = GetAdjustedTime();
// Debit
CAccountingEntry debit;
debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
debit.strAccount = strFrom;
debit.nCreditDebit = -nAmount;
debit.nTime = nNow;
debit.strOtherAccount = strTo;
debit.strComment = strComment;
pwalletMain->AddAccountingEntry(debit, walletdb);
// Credit
CAccountingEntry credit;
credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
credit.strAccount = strTo;
credit.nCreditDebit = nAmount;
credit.nTime = nNow;
credit.strOtherAccount = strFrom;
credit.strComment = strComment;
pwalletMain->AddAccountingEntry(credit, walletdb);
if (!walletdb.TxnCommit())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
return true;
}
UniValue sendfrom(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 3 || params.size() > 6)
throw std::runtime_error(
"sendfrom \"fromaccount\" \"tozumyaddress\" amount ( minconf \"comment\" \"comment-to\" )\n"
"\nDEPRECATED (use sendtoaddress). Sent an amount from an account to a spoomy address."
+ HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. \"fromaccount\" (string, required) The name of the account to send funds from. May be the default account using \"\".\n"
"2. \"tozumyaddress\" (string, required) The spoomy address to send funds to.\n"
"3. amount (numeric or string, required) The amount in " + CURRENCY_UNIT + " (transaction fee is added on top).\n"
"4. minconf (numeric, optional, default=1) Only use funds with at least this many confirmations.\n"
"5. \"comment\" (string, optional) A comment used to store what the transaction is for. \n"
" This is not part of the transaction, just kept in your wallet.\n"
"6. \"comment-to\" (string, optional) An optional comment to store the name of the person or organization \n"
" to which you're sending the transaction. This is not part of the transaction, \n"
" it is just kept in your wallet.\n"
"\nResult:\n"
"\"transactionid\" (string) The transaction id.\n"
"\nExamples:\n"
"\nSend 0.01 " + CURRENCY_UNIT + " from the default account to the address, must have at least 1 confirmation\n"
+ HelpExampleCli("sendfrom", "\"\" \"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\" 0.01") +
"\nSend 0.01 from the tabby account to the given address, funds must have at least 10 confirmations\n"
+ HelpExampleCli("sendfrom", "\"tabby\" \"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\" 0.01 10 \"donation\" \"seans outpost\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("sendfrom", "\"tabby\", \"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\", 0.01, 10, \"donation\", \"seans outpost\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
std::string strAccount = AccountFromValue(params[0]);
CSpoomyAddress address(params[1].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Spoomy address");
CAmount nAmount = AmountFromValue(params[2]);
if (nAmount <= 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
int nMinDepth = 1;
if (params.size() > 3)
nMinDepth = params[3].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 4 && !params[4].isNull() && !params[4].get_str().empty())
wtx.mapValue["comment"] = params[4].get_str();
if (params.size() > 5 && !params[5].isNull() && !params[5].get_str().empty())
wtx.mapValue["to"] = params[5].get_str();
EnsureWalletIsUnlocked();
// Check funds
CAmount nBalance = pwalletMain->GetAccountBalance(strAccount, nMinDepth, ISMINE_SPENDABLE);
if (nAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
SendMoney(address.Get(), nAmount, false, wtx);
return wtx.GetHash().GetHex();
}
UniValue sendmany(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 2 || params.size() > 7)
throw std::runtime_error(
"sendmany \"fromaccount\" {\"address\":amount,...} ( minconf \"comment\" [\"address\",...] subtractfeefromamount use_is use_ps )\n"
"\nSend multiple times. Amounts are double-precision floating point numbers."
+ HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. \"fromaccount\" (string, required) DEPRECATED. The account to send the funds from. Should be \"\" for the default account\n"
"2. \"amounts\" (string, required) A json object with addresses and amounts\n"
" {\n"
" \"address\":amount (numeric or string) The spoomy address is the key, the numeric amount (can be string) in " + CURRENCY_UNIT + " is the value\n"
" ,...\n"
" }\n"
"3. minconf (numeric, optional, default=1) Only use the balance confirmed at least this many times.\n"
"4. \"comment\" (string, optional) A comment\n"
"5. subtractfeefromamount (string, optional) A json array with addresses.\n"
" The fee will be equally deducted from the amount of each selected address.\n"
" Those recipients will receive less Spoomy than you enter in their corresponding amount field.\n"
" If no addresses are specified here, the sender pays the fee.\n"
" [\n"
" \"address\" (string) Subtract fee from this address\n"
" ,...\n"
" ]\n"
"6. \"use_is\" (bool, optional) Send this transaction as InstantSend (default: false)\n"
"7. \"use_ps\" (bool, optional) Use anonymized funds only (default: false)\n"
"\nResult:\n"
"\"transactionid\" (string) The transaction id for the send. Only 1 transaction is created regardless of \n"
" the number of addresses.\n"
"\nExamples:\n"
"\nSend two amounts to two different addresses:\n"
+ HelpExampleCli("sendmany", "\"tabby\" \"{\\\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\\\":0.01,\\\"C1MfcDTf7Zsef8gMGL2fhWA9ZslrP4K5tf\\\":0.02}\"") +
"\nSend two amounts to two different addresses setting the confirmation and comment:\n"
+ HelpExampleCli("sendmany", "\"tabby\" \"{\\\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\\\":0.01,\\\"C1MfcDTf7Zsef8gMGL2fhWA9ZslrP4K5tf\\\":0.02}\" 10 \"testing\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("sendmany", "\"tabby\", \"{\\\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\\\":0.01,\\\"C1MfcDTf7Zsef8gMGL2fhWA9ZslrP4K5tf\\\":0.02}\", 10, \"testing\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
std::string strAccount = AccountFromValue(params[0]);
UniValue sendTo = params[1].get_obj();
int nMinDepth = 1;
if (params.size() > 2)
nMinDepth = params[2].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 3 && !params[3].isNull() && !params[3].get_str().empty())
wtx.mapValue["comment"] = params[3].get_str();
UniValue subtractFeeFromAmount(UniValue::VARR);
if (params.size() > 4)
subtractFeeFromAmount = params[4].get_array();
std::set<CSpoomyAddress> setAddress;
std::vector<CRecipient> vecSend;
CAmount totalAmount = 0;
std::vector<std::string> keys = sendTo.getKeys();
BOOST_FOREACH(const std::string& name_, keys)
{
CSpoomyAddress address(name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid Spoomy address: ")+name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ")+name_);
setAddress.insert(address);
CScript scriptPubKey = GetScriptForDestination(address.Get());
CAmount nAmount = AmountFromValue(sendTo[name_]);
if (nAmount <= 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
totalAmount += nAmount;
bool fSubtractFeeFromAmount = false;
for (unsigned int idx = 0; idx < subtractFeeFromAmount.size(); idx++) {
const UniValue& addr = subtractFeeFromAmount[idx];
if (addr.get_str() == name_)
fSubtractFeeFromAmount = true;
}
CRecipient recipient = {scriptPubKey, nAmount, fSubtractFeeFromAmount};
vecSend.push_back(recipient);
}
EnsureWalletIsUnlocked();
// Check funds
CAmount nBalance = pwalletMain->GetAccountBalance(strAccount, nMinDepth, ISMINE_SPENDABLE);
if (totalAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
CReserveKey keyChange(pwalletMain);
CAmount nFeeRequired = 0;
int nChangePosRet = -1;
std::string strFailReason;
bool fUseInstantSend = false;
bool fUsePrivateSend = false;
if (params.size() > 5)
fUseInstantSend = params[5].get_bool();
if (params.size() > 6)
fUsePrivateSend = params[6].get_bool();
bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, nChangePosRet, strFailReason,
NULL, true, fUsePrivateSend ? ONLY_DENOMINATED : ALL_COINS, fUseInstantSend);
if (!fCreated)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason);
if (!pwalletMain->CommitTransaction(wtx, keyChange, fUseInstantSend ? NetMsgType::TXLOCKREQUEST : NetMsgType::TX))
throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed");
return wtx.GetHash().GetHex();
}
// Defined in rpcmisc.cpp
extern CScript _createmultisig_redeemScript(const UniValue& params);
UniValue addmultisigaddress(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 2 || params.size() > 3)
{
std::string msg = "addmultisigaddress nrequired [\"key\",...] ( \"account\" )\n"
"\nAdd a nrequired-to-sign multisignature address to the wallet.\n"
"Each key is a Spoomy address or hex-encoded public key.\n"
"If 'account' is specified (DEPRECATED), assign address to that account.\n"
"\nArguments:\n"
"1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n"
"2. \"keysobject\" (string, required) A json array of spoomy addresses or hex-encoded public keys\n"
" [\n"
" \"address\" (string) spoomy address or hex-encoded public key\n"
" ...,\n"
" ]\n"
"3. \"account\" (string, optional) DEPRECATED. An account to assign the addresses to.\n"
"\nResult:\n"
"\"zumyaddress\" (string) A spoomy address associated with the keys.\n"
"\nExamples:\n"
"\nAdd a multisig address from 2 addresses\n"
+ HelpExampleCli("addmultisigaddress", "2 \"[\\\"D8RHNF9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\\\",\\\"D2sMrF9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\\\"]\"") +
"\nAs json rpc call\n"
+ HelpExampleRpc("addmultisigaddress", "2, \"[\\\"D8RHNF9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\\\",\\\"D2sMrF9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\\\"]\"")
;
throw std::runtime_error(msg);
}
LOCK2(cs_main, pwalletMain->cs_wallet);
std::string strAccount;
if (params.size() > 2)
strAccount = AccountFromValue(params[2]);
// Construct using pay-to-script-hash:
CScript inner = _createmultisig_redeemScript(params);
CScriptID innerID(inner);
pwalletMain->AddCScript(inner);
pwalletMain->SetAddressBook(innerID, strAccount, "send");
return CSpoomyAddress(innerID).ToString();
}
struct tallyitem
{
CAmount nAmount;
int nConf;
int nBCConf;
std::vector<uint256> txids;
bool fIsWatchonly;
tallyitem()
{
nAmount = 0;
nConf = std::numeric_limits<int>::max();
nBCConf = std::numeric_limits<int>::max();
fIsWatchonly = false;
}
};
UniValue ListReceived(const UniValue& params, bool fByAccounts)
{
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
// Whether to include empty accounts
bool fIncludeEmpty = false;
if (params.size() > 1)
fIncludeEmpty = params[1].get_bool();
isminefilter filter = ISMINE_SPENDABLE;
if(params.size() > 2)
if(params[2].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
// Tally
std::map<CSpoomyAddress, tallyitem> mapTally;
for (std::map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !CheckFinalTx(wtx))
continue;
int nDepth = wtx.GetDepthInMainChain();
int nBCDepth = wtx.GetDepthInMainChain(false);
if (nDepth < nMinDepth)
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address))
continue;
isminefilter mine = IsMine(*pwalletMain, address);
if(!(mine & filter))
continue;
tallyitem& item = mapTally[address];
item.nAmount += txout.nValue;
item.nConf = std::min(item.nConf, nDepth);
item.nBCConf = std::min(item.nBCConf, nBCDepth);
item.txids.push_back(wtx.GetHash());
if (mine & ISMINE_WATCH_ONLY)
item.fIsWatchonly = true;
}
}
// Reply
UniValue ret(UniValue::VARR);
std::map<std::string, tallyitem> mapAccountTally;
BOOST_FOREACH(const PAIRTYPE(CSpoomyAddress, CAddressBookData)& item, pwalletMain->mapAddressBook)
{
const CSpoomyAddress& address = item.first;
const std::string& strAccount = item.second.name;
std::map<CSpoomyAddress, tallyitem>::iterator it = mapTally.find(address);
if (it == mapTally.end() && !fIncludeEmpty)
continue;
CAmount nAmount = 0;
int nConf = std::numeric_limits<int>::max();
int nBCConf = std::numeric_limits<int>::max();
bool fIsWatchonly = false;
if (it != mapTally.end())
{
nAmount = (*it).second.nAmount;
nConf = (*it).second.nConf;
nBCConf = (*it).second.nBCConf;
fIsWatchonly = (*it).second.fIsWatchonly;
}
if (fByAccounts)
{
tallyitem& _item = mapAccountTally[strAccount];
_item.nAmount += nAmount;
_item.nConf = std::min(_item.nConf, nConf);
_item.nBCConf = std::min(_item.nBCConf, nBCConf);
_item.fIsWatchonly = fIsWatchonly;
}
else
{
UniValue obj(UniValue::VOBJ);
if(fIsWatchonly)
obj.push_back(Pair("involvesWatchonly", true));
obj.push_back(Pair("address", address.ToString()));
obj.push_back(Pair("account", strAccount));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
obj.push_back(Pair("bcconfirmations", (nBCConf == std::numeric_limits<int>::max() ? 0 : nBCConf)));
if (!fByAccounts)
obj.push_back(Pair("label", strAccount));
UniValue transactions(UniValue::VARR);
if (it != mapTally.end())
{
BOOST_FOREACH(const uint256& _item, (*it).second.txids)
{
transactions.push_back(_item.GetHex());
}
}
obj.push_back(Pair("txids", transactions));
ret.push_back(obj);
}
}
if (fByAccounts)
{
for (std::map<std::string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
{
CAmount nAmount = (*it).second.nAmount;
int nConf = (*it).second.nConf;
int nBCConf = (*it).second.nBCConf;
UniValue obj(UniValue::VOBJ);
if((*it).second.fIsWatchonly)
obj.push_back(Pair("involvesWatchonly", true));
obj.push_back(Pair("account", (*it).first));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
obj.push_back(Pair("bcconfirmations", (nBCConf == std::numeric_limits<int>::max() ? 0 : nBCConf)));
ret.push_back(obj);
}
}
return ret;
}
UniValue listreceivedbyaddress(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 3)
throw std::runtime_error(
"listreceivedbyaddress ( minconf includeempty includeWatchonly)\n"
"\nList balances by receiving address.\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n"
"2. includeempty (bool, optional, default=false) Whether to include addresses that haven't received any payments.\n"
"3. includeWatchonly (bool, optional, default=false) Whether to include watchonly addresses (see 'importaddress').\n"
"\nResult:\n"
"[\n"
" {\n"
" \"involvesWatchonly\" : true, (bool) Only returned if imported addresses were involved in transaction\n"
" \"address\" : \"receivingaddress\", (string) The receiving address\n"
" \"account\" : \"accountname\", (string) DEPRECATED. The account of the receiving address. The default account is \"\".\n"
" \"amount\" : x.xxx, (numeric) The total amount in " + CURRENCY_UNIT + " received by the address\n"
" \"confirmations\" : n, (numeric) The number of confirmations of the most recent transaction included\n"
" \"bcconfirmations\" : n (numeric) The number of blockchain confirmations of the most recent transaction included\n"
" \"label\" : \"label\" (string) A comment for the address/transaction, if any\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("listreceivedbyaddress", "")
+ HelpExampleCli("listreceivedbyaddress", "10 true")
+ HelpExampleRpc("listreceivedbyaddress", "10, true, true")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
return ListReceived(params, false);
}
UniValue listreceivedbyaccount(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 3)
throw std::runtime_error(
"listreceivedbyaccount ( minconf includeempty includeWatchonly)\n"
"\nDEPRECATED. List balances by account.\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n"
"2. includeempty (bool, optional, default=false) Whether to include accounts that haven't received any payments.\n"
"3. includeWatchonly (bool, optional, default=false) Whether to include watchonly addresses (see 'importaddress').\n"
"\nResult:\n"
"[\n"
" {\n"
" \"involvesWatchonly\" : true, (bool) Only returned if imported addresses were involved in transaction\n"
" \"account\" : \"accountname\", (string) The account name of the receiving account\n"
" \"amount\" : x.xxx, (numeric) The total amount received by addresses with this account\n"
" \"confirmations\" : n (numeric) The number of confirmations of the most recent transaction included\n"
" \"bcconfirmations\" : n (numeric) The number of blockchain confirmations of the most recent transaction included\n"
" \"label\" : \"label\" (string) A comment for the address/transaction, if any\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("listreceivedbyaccount", "")
+ HelpExampleCli("listreceivedbyaccount", "10 true")
+ HelpExampleRpc("listreceivedbyaccount", "10, true, true")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
return ListReceived(params, true);
}
static void MaybePushAddress(UniValue & entry, const CTxDestination &dest)
{
CSpoomyAddress addr;
if (addr.Set(dest))
entry.push_back(Pair("address", addr.ToString()));
}
void ListTransactions(const CWalletTx& wtx, const std::string& strAccount, int nMinDepth, bool fLong, UniValue& ret, const isminefilter& filter)
{
CAmount nFee;
std::string strSentAccount;
std::list<COutputEntry> listReceived;
std::list<COutputEntry> listSent;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, filter);
bool fAllAccounts = (strAccount == std::string("*"));
bool involvesWatchonly = wtx.IsFromMe(ISMINE_WATCH_ONLY);
// Sent
if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
{
BOOST_FOREACH(const COutputEntry& s, listSent)
{
UniValue entry(UniValue::VOBJ);
if(involvesWatchonly || (::IsMine(*pwalletMain, s.destination) & ISMINE_WATCH_ONLY))
entry.push_back(Pair("involvesWatchonly", true));
entry.push_back(Pair("account", strSentAccount));
MaybePushAddress(entry, s.destination);
std::map<std::string, std::string>::const_iterator it = wtx.mapValue.find("PS");
entry.push_back(Pair("category", (it != wtx.mapValue.end() && it->second == "1") ? "privatesend" : "send"));
entry.push_back(Pair("amount", ValueFromAmount(-s.amount)));
if (pwalletMain->mapAddressBook.count(s.destination))
entry.push_back(Pair("label", pwalletMain->mapAddressBook[s.destination].name));
entry.push_back(Pair("vout", s.vout));
entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
if (fLong)
WalletTxToJSON(wtx, entry);
entry.push_back(Pair("abandoned", wtx.isAbandoned()));
ret.push_back(entry);
}
}
// Received
if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const COutputEntry& r, listReceived)
{
std::string account;
if (pwalletMain->mapAddressBook.count(r.destination))
account = pwalletMain->mapAddressBook[r.destination].name;
if (fAllAccounts || (account == strAccount))
{
UniValue entry(UniValue::VOBJ);
if(involvesWatchonly || (::IsMine(*pwalletMain, r.destination) & ISMINE_WATCH_ONLY))
entry.push_back(Pair("involvesWatchonly", true));
entry.push_back(Pair("account", account));
MaybePushAddress(entry, r.destination);
if (wtx.IsCoinBase())
{
if (wtx.GetDepthInMainChain() < 1)
entry.push_back(Pair("category", "orphan"));
else if (wtx.GetBlocksToMaturity() > 0)
entry.push_back(Pair("category", "immature"));
else
entry.push_back(Pair("category", "generate"));
}
else
{
entry.push_back(Pair("category", "receive"));
}
entry.push_back(Pair("amount", ValueFromAmount(r.amount)));
if (pwalletMain->mapAddressBook.count(r.destination))
entry.push_back(Pair("label", account));
entry.push_back(Pair("vout", r.vout));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
}
}
void AcentryToJSON(const CAccountingEntry& acentry, const std::string& strAccount, UniValue& ret)
{
bool fAllAccounts = (strAccount == std::string("*"));
if (fAllAccounts || acentry.strAccount == strAccount)
{
UniValue entry(UniValue::VOBJ);
entry.push_back(Pair("account", acentry.strAccount));
entry.push_back(Pair("category", "move"));
entry.push_back(Pair("time", acentry.nTime));
entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
entry.push_back(Pair("comment", acentry.strComment));
ret.push_back(entry);
}
}
UniValue listtransactions(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 4)
throw std::runtime_error(
"listtransactions ( \"account\" count from includeWatchonly)\n"
"\nReturns up to 'count' most recent transactions skipping the first 'from' transactions for account 'account'.\n"
"\nArguments:\n"
"1. \"account\" (string, optional) DEPRECATED. The account name. Should be \"*\".\n"
"2. count (numeric, optional, default=10) The number of transactions to return\n"
"3. from (numeric, optional, default=0) The number of transactions to skip\n"
"4. includeWatchonly (bool, optional, default=false) Include transactions to watchonly addresses (see 'importaddress')\n"
"\nResult:\n"
"[\n"
" {\n"
" \"account\":\"accountname\", (string) DEPRECATED. The account name associated with the transaction. \n"
" It will be \"\" for the default account.\n"
" \"address\":\"zumyaddress\", (string) The spoomy address of the transaction. Not present for \n"
" move transactions (category = move).\n"
" \"category\":\"send|receive|move\", (string) The transaction category. 'move' is a local (off blockchain)\n"
" transaction between accounts, and not associated with an address,\n"
" transaction id or block. 'send' and 'receive' transactions are \n"
" associated with an address, transaction id and block details\n"
" \"amount\": x.xxx, (numeric) The amount in " + CURRENCY_UNIT + ". This is negative for the 'send' category, and for the\n"
" 'move' category for moves outbound. It is positive for the 'receive' category,\n"
" and for the 'move' category for inbound funds.\n"
" \"vout\": n, (numeric) the vout value\n"
" \"fee\": x.xxx, (numeric) The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the \n"
" 'send' category of transactions.\n"
" \"confirmations\": n, (numeric) The number of confirmations for the transaction. Available for 'send' and \n"
" 'receive' category of transactions. Negative confirmations indicate the\n"
" transation conflicts with the block chain\n"
" \"bcconfirmations\": n, (numeric) The number of blockchain confirmations for the transaction. Available for 'send' and \n"
" 'receive' category of transactions. Negative confirmations indicate the\n"
" transation conflicts with the block chain\n"
" \"trusted\": xxx (bool) Whether we consider the outputs of this unconfirmed transaction safe to spend.\n"
" \"blockhash\": \"hashvalue\", (string) The block hash containing the transaction. Available for 'send' and 'receive'\n"
" category of transactions.\n"
" \"blockindex\": n, (numeric) The index of the transaction in the block that includes it. Available for 'send' and 'receive'\n"
" category of transactions.\n"
" \"blocktime\": xxx, (numeric) The block time in seconds since epoch (1 Jan 1970 GMT).\n"
" \"txid\": \"transactionid\", (string) The transaction id. Available for 'send' and 'receive' category of transactions.\n"
" \"time\": xxx, (numeric) The transaction time in seconds since epoch (midnight Jan 1 1970 GMT).\n"
" \"timereceived\": xxx, (numeric) The time received in seconds since epoch (midnight Jan 1 1970 GMT). Available \n"
" for 'send' and 'receive' category of transactions.\n"
" \"comment\": \"...\", (string) If a comment is associated with the transaction.\n"
" \"label\": \"label\" (string) A comment for the address/transaction, if any\n"
" \"otheraccount\": \"accountname\", (string) For the 'move' category of transactions, the account the funds came \n"
" from (for receiving funds, positive amounts), or went to (for sending funds,\n"
" negative amounts).\n"
" \"bip125-replaceable\": \"yes|no|unknown\" (string) Whether this transaction could be replaced due to BIP125 (replace-by-fee);\n"
" may be unknown for unconfirmed transactions not in the mempool\n"
" }\n"
"]\n"
"\nExamples:\n"
"\nList the most recent 10 transactions in the systems\n"
+ HelpExampleCli("listtransactions", "") +
"\nList transactions 100 to 120\n"
+ HelpExampleCli("listtransactions", "\"*\" 20 100") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("listtransactions", "\"*\", 20, 100")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
std::string strAccount = "*";
if (params.size() > 0)
strAccount = params[0].get_str();
int nCount = 10;
if (params.size() > 1)
nCount = params[1].get_int();
int nFrom = 0;
if (params.size() > 2)
nFrom = params[2].get_int();
isminefilter filter = ISMINE_SPENDABLE;
if(params.size() > 3)
if(params[3].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
if (nCount < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count");
if (nFrom < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from");
UniValue ret(UniValue::VARR);
const CWallet::TxItems & txOrdered = pwalletMain->wtxOrdered;
// iterate backwards until we have nCount items to return:
for (CWallet::TxItems::const_reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
{
CWalletTx *const pwtx = (*it).second.first;
if (pwtx != 0)
ListTransactions(*pwtx, strAccount, 0, true, ret, filter);
CAccountingEntry *const pacentry = (*it).second.second;
if (pacentry != 0)
AcentryToJSON(*pacentry, strAccount, ret);
if ((int)ret.size() >= (nCount+nFrom)) break;
}
// ret is newest to oldest
if (nFrom > (int)ret.size())
nFrom = ret.size();
if ((nFrom + nCount) > (int)ret.size())
nCount = ret.size() - nFrom;
std::vector<UniValue> arrTmp = ret.getValues();
std::vector<UniValue>::iterator first = arrTmp.begin();
std::advance(first, nFrom);
std::vector<UniValue>::iterator last = arrTmp.begin();
std::advance(last, nFrom+nCount);
if (last != arrTmp.end()) arrTmp.erase(last, arrTmp.end());
if (first != arrTmp.begin()) arrTmp.erase(arrTmp.begin(), first);
std::reverse(arrTmp.begin(), arrTmp.end()); // Return oldest to newest
ret.clear();
ret.setArray();
ret.push_backV(arrTmp);
return ret;
}
UniValue listaccounts(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 2)
throw std::runtime_error(
"listaccounts ( minconf includeWatchonly)\n"
"\nDEPRECATED. Returns Object that has account names as keys, account balances as values.\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) Only include transactions with at least this many confirmations\n"
"2. includeWatchonly (bool, optional, default=false) Include balances in watchonly addresses (see 'importaddress')\n"
"\nResult:\n"
"{ (json object where keys are account names, and values are numeric balances\n"
" \"account\": x.xxx, (numeric) The property name is the account name, and the value is the total balance for the account.\n"
" ...\n"
"}\n"
"\nExamples:\n"
"\nList account balances where there at least 1 confirmation\n"
+ HelpExampleCli("listaccounts", "") +
"\nList account balances including zero confirmation transactions\n"
+ HelpExampleCli("listaccounts", "0") +
"\nList account balances for 10 or more confirmations\n"
+ HelpExampleCli("listaccounts", "10") +
"\nAs json rpc call\n"
+ HelpExampleRpc("listaccounts", "10")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
isminefilter includeWatchonly = ISMINE_SPENDABLE;
if(params.size() > 1)
if(params[1].get_bool())
includeWatchonly = includeWatchonly | ISMINE_WATCH_ONLY;
std::map<std::string, CAmount> mapAccountBalances;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& entry, pwalletMain->mapAddressBook) {
if (IsMine(*pwalletMain, entry.first) & includeWatchonly) // This address belongs to me
mapAccountBalances[entry.second.name] = 0;
}
for (std::map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
CAmount nFee;
std::string strSentAccount;
std::list<COutputEntry> listReceived;
std::list<COutputEntry> listSent;
int nDepth = wtx.GetDepthInMainChain();
if (wtx.GetBlocksToMaturity() > 0 || nDepth < 0)
continue;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, includeWatchonly);
mapAccountBalances[strSentAccount] -= nFee;
BOOST_FOREACH(const COutputEntry& s, listSent)
mapAccountBalances[strSentAccount] -= s.amount;
if (nDepth >= nMinDepth)
{
BOOST_FOREACH(const COutputEntry& r, listReceived)
if (pwalletMain->mapAddressBook.count(r.destination))
mapAccountBalances[pwalletMain->mapAddressBook[r.destination].name] += r.amount;
else
mapAccountBalances[""] += r.amount;
}
}
const std::list<CAccountingEntry> & acentries = pwalletMain->laccentries;
BOOST_FOREACH(const CAccountingEntry& entry, acentries)
mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
UniValue ret(UniValue::VOBJ);
BOOST_FOREACH(const PAIRTYPE(std::string, CAmount)& accountBalance, mapAccountBalances) {
ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
}
return ret;
}
UniValue listsinceblock(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp)
throw std::runtime_error(
"listsinceblock ( \"blockhash\" target-confirmations includeWatchonly)\n"
"\nGet all transactions in blocks since block [blockhash], or all transactions if omitted\n"
"\nArguments:\n"
"1. \"blockhash\" (string, optional) The block hash to list transactions since\n"
"2. target-confirmations: (numeric, optional) The confirmations required, must be 1 or more\n"
"3. includeWatchonly: (bool, optional, default=false) Include transactions to watchonly addresses (see 'importaddress')"
"\nResult:\n"
"{\n"
" \"transactions\": [\n"
" \"account\":\"accountname\", (string) DEPRECATED. The account name associated with the transaction. Will be \"\" for the default account.\n"
" \"address\":\"zumyaddress\", (string) The spoomy address of the transaction. Not present for move transactions (category = move).\n"
" \"category\":\"send|receive\", (string) The transaction category. 'send' has negative amounts, 'receive' has positive amounts.\n"
" \"amount\": x.xxx, (numeric) The amount in " + CURRENCY_UNIT + ". This is negative for the 'send' category, and for the 'move' category for moves \n"
" outbound. It is positive for the 'receive' category, and for the 'move' category for inbound funds.\n"
" \"vout\" : n, (numeric) the vout value\n"
" \"fee\": x.xxx, (numeric) The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the 'send' category of transactions.\n"
" \"confirmations\": n, (numeric) The number of confirmations for the transaction. Available for 'send' and 'receive' category of transactions.\n"
" \"bcconfirmations\" : n, (numeric) The number of blockchain confirmations for the transaction. Available for 'send' and 'receive' category of transactions.\n"
" \"blockhash\": \"hashvalue\", (string) The block hash containing the transaction. Available for 'send' and 'receive' category of transactions.\n"
" \"blockindex\": n, (numeric) The index of the transaction in the block that includes it. Available for 'send' and 'receive' category of transactions.\n"
" \"blocktime\": xxx, (numeric) The block time in seconds since epoch (1 Jan 1970 GMT).\n"
" \"txid\": \"transactionid\", (string) The transaction id. Available for 'send' and 'receive' category of transactions.\n"
" \"time\": xxx, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT).\n"
" \"timereceived\": xxx, (numeric) The time received in seconds since epoch (Jan 1 1970 GMT). Available for 'send' and 'receive' category of transactions.\n"
" \"comment\": \"...\", (string) If a comment is associated with the transaction.\n"
" \"label\" : \"label\" (string) A comment for the address/transaction, if any\n"
" \"to\": \"...\", (string) If a comment to is associated with the transaction.\n"
" ],\n"
" \"lastblock\": \"lastblockhash\" (string) The hash of the last block\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("listsinceblock", "")
+ HelpExampleCli("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\" 10")
+ HelpExampleRpc("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\", 10")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
CBlockIndex *pindex = NULL;
int target_confirms = 1;
isminefilter filter = ISMINE_SPENDABLE;
if (params.size() > 0)
{
uint256 blockId;
blockId.SetHex(params[0].get_str());
BlockMap::iterator it = mapBlockIndex.find(blockId);
if (it != mapBlockIndex.end())
pindex = it->second;
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid blockhash");
}
if (params.size() > 1)
{
target_confirms = params[1].get_int();
if (target_confirms < 1)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
}
if(params.size() > 2)
if(params[2].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
int depth = pindex ? (1 + chainActive.Height() - pindex->nHeight) : -1;
UniValue transactions(UniValue::VARR);
for (std::map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++)
{
CWalletTx tx = (*it).second;
if (depth == -1 || tx.GetDepthInMainChain(false) < depth)
ListTransactions(tx, "*", 0, true, transactions, filter);
}
CBlockIndex *pblockLast = chainActive[chainActive.Height() + 1 - target_confirms];
uint256 lastblock = pblockLast ? pblockLast->GetBlockHash() : uint256();
UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("transactions", transactions));
ret.push_back(Pair("lastblock", lastblock.GetHex()));
return ret;
}
UniValue gettransaction(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 1 || params.size() > 2)
throw std::runtime_error(
"gettransaction \"txid\" ( includeWatchonly )\n"
"\nGet detailed information about in-wallet transaction <txid>\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id\n"
"2. \"includeWatchonly\" (bool, optional, default=false) Whether to include watchonly addresses in balance calculation and details[]\n"
"\nResult:\n"
"{\n"
" \"amount\" : x.xxx, (numeric) The transaction amount in " + CURRENCY_UNIT + "\n"
" \"confirmations\" : n, (numeric) The number of confirmations\n"
" \"bcconfirmations\" : n, (numeric) The number of blockchain confirmations\n"
" \"blockhash\" : \"hash\", (string) The block hash\n"
" \"blockindex\" : xx, (numeric) The index of the transaction in the block that includes it\n"
" \"blocktime\" : ttt, (numeric) The time in seconds since epoch (1 Jan 1970 GMT)\n"
" \"txid\" : \"transactionid\", (string) The transaction id.\n"
" \"time\" : ttt, (numeric) The transaction time in seconds since epoch (1 Jan 1970 GMT)\n"
" \"timereceived\" : ttt, (numeric) The time received in seconds since epoch (1 Jan 1970 GMT)\n"
" \"bip125-replaceable\": \"yes|no|unknown\" (string) Whether this transaction could be replaced due to BIP125 (replace-by-fee);\n"
" may be unknown for unconfirmed transactions not in the mempool\n"
" \"details\" : [\n"
" {\n"
" \"account\" : \"accountname\", (string) DEPRECATED. The account name involved in the transaction, can be \"\" for the default account.\n"
" \"address\" : \"zumyaddress\", (string) The spoomy address involved in the transaction\n"
" \"category\" : \"send|receive\", (string) The category, either 'send' or 'receive'\n"
" \"amount\" : x.xxx, (numeric) The amount in " + CURRENCY_UNIT + "\n"
" \"label\" : \"label\", (string) A comment for the address/transaction, if any\n"
" \"vout\" : n, (numeric) the vout value\n"
" }\n"
" ,...\n"
" ],\n"
" \"hex\" : \"data\" (string) Raw data for transaction\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
+ HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\" true")
+ HelpExampleRpc("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
uint256 hash;
hash.SetHex(params[0].get_str());
isminefilter filter = ISMINE_SPENDABLE;
if(params.size() > 1)
if(params[1].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
UniValue entry(UniValue::VOBJ);
if (!pwalletMain->mapWallet.count(hash))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id");
const CWalletTx& wtx = pwalletMain->mapWallet[hash];
CAmount nCredit = wtx.GetCredit(filter);
CAmount nDebit = wtx.GetDebit(filter);
CAmount nNet = nCredit - nDebit;
CAmount nFee = (wtx.IsFromMe(filter) ? wtx.GetValueOut() - nDebit : 0);
entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
if (wtx.IsFromMe(filter))
entry.push_back(Pair("fee", ValueFromAmount(nFee)));
WalletTxToJSON(wtx, entry);
UniValue details(UniValue::VARR);
ListTransactions(wtx, "*", 0, false, details, filter);
entry.push_back(Pair("details", details));
std::string strHex = EncodeHexTx(static_cast<CTransaction>(wtx));
entry.push_back(Pair("hex", strHex));
return entry;
}
UniValue abandontransaction(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 1)
throw std::runtime_error(
"abandontransaction \"txid\"\n"
"\nMark in-wallet transaction <txid> as abandoned\n"
"This will mark this transaction and all its in-wallet descendants as abandoned which will allow\n"
"for their inputs to be respent. It can be used to replace \"stuck\" or evicted transactions.\n"
"It only works on transactions which are not included in a block and are not currently in the mempool.\n"
"It has no effect on transactions which are already conflicted or abandoned.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id\n"
"\nResult:\n"
"\nExamples:\n"
+ HelpExampleCli("abandontransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
+ HelpExampleRpc("abandontransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
uint256 hash;
hash.SetHex(params[0].get_str());
if (!pwalletMain->mapWallet.count(hash))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id");
if (!pwalletMain->AbandonTransaction(hash))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not eligible for abandonment");
return NullUniValue;
}
UniValue backupwallet(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 1)
throw std::runtime_error(
"backupwallet \"destination\"\n"
"\nSafely copies wallet.dat to destination, which can be a directory or a path with filename.\n"
"\nArguments:\n"
"1. \"destination\" (string) The destination directory or file\n"
"\nExamples:\n"
+ HelpExampleCli("backupwallet", "\"backup.dat\"")
+ HelpExampleRpc("backupwallet", "\"backup.dat\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
std::string strDest = params[0].get_str();
if (!BackupWallet(*pwalletMain, strDest))
throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!");
return NullUniValue;
}
UniValue keypoolrefill(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 1)
throw std::runtime_error(
"keypoolrefill ( newsize )\n"
"\nFills the keypool."
+ HelpRequiringPassphrase() + "\n"
"\nArguments\n"
"1. newsize (numeric, optional, default=" + itostr(DEFAULT_KEYPOOL_SIZE) + ") The new keypool size\n"
"\nExamples:\n"
+ HelpExampleCli("keypoolrefill", "")
+ HelpExampleRpc("keypoolrefill", "")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
// 0 is interpreted by TopUpKeyPool() as the default keypool size given by -keypool
unsigned int kpSize = 0;
if (params.size() > 0) {
if (params[0].get_int() < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected valid size.");
kpSize = (unsigned int)params[0].get_int();
}
EnsureWalletIsUnlocked();
pwalletMain->TopUpKeyPool(kpSize);
if (pwalletMain->GetKeyPoolSize() < (pwalletMain->IsHDEnabled() ? kpSize * 2 : kpSize))
throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool.");
return NullUniValue;
}
static void LockWallet(CWallet* pWallet)
{
LOCK(cs_nWalletUnlockTime);
nWalletUnlockTime = 0;
pWallet->Lock();
}
UniValue walletpassphrase(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (pwalletMain->IsCrypted() && (fHelp || params.size() < 2 || params.size() > 3))
throw std::runtime_error(
"walletpassphrase \"passphrase\" timeout ( mixingonly )\n"
"\nStores the wallet decryption key in memory for 'timeout' seconds.\n"
"This is needed prior to performing transactions related to private keys such as sending Spoomy\n"
"\nArguments:\n"
"1. \"passphrase\" (string, required) The wallet passphrase\n"
"2. timeout (numeric, required) The time to keep the decryption key in seconds.\n"
"3. mixingonly (boolean, optional, default=false) If is true sending functions are disabled."
"\nNote:\n"
"Issuing the walletpassphrase command while the wallet is already unlocked will set a new unlock\n"
"time that overrides the old one.\n"
"\nExamples:\n"
"\nUnlock the wallet for 60 seconds\n"
+ HelpExampleCli("walletpassphrase", "\"my pass phrase\" 60") +
"\nUnlock the wallet for 60 seconds but allow PrivateSend mixing only\n"
+ HelpExampleCli("walletpassphrase", "\"my pass phrase\" 60 true") +
"\nLock the wallet again (before 60 seconds)\n"
+ HelpExampleCli("walletlock", "") +
"\nAs json rpc call\n"
+ HelpExampleRpc("walletpassphrase", "\"my pass phrase\", 60")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called.");
// Note that the walletpassphrase is stored in params[0] which is not mlock()ed
SecureString strWalletPass;
strWalletPass.reserve(100);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
strWalletPass = params[0].get_str().c_str();
int64_t nSleepTime = params[1].get_int64();
bool fForMixingOnly = false;
if (params.size() >= 3)
fForMixingOnly = params[2].get_bool();
if (fForMixingOnly && !pwalletMain->IsLocked(true) && pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already unlocked for mixing only.");
if (!pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already fully unlocked.");
if (!pwalletMain->Unlock(strWalletPass, fForMixingOnly))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
pwalletMain->TopUpKeyPool();
LOCK(cs_nWalletUnlockTime);
nWalletUnlockTime = GetTime() + nSleepTime;
RPCRunLater("lockwallet", boost::bind(LockWallet, pwalletMain), nSleepTime);
return NullUniValue;
}
UniValue walletpassphrasechange(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
throw std::runtime_error(
"walletpassphrasechange \"oldpassphrase\" \"newpassphrase\"\n"
"\nChanges the wallet passphrase from 'oldpassphrase' to 'newpassphrase'.\n"
"\nArguments:\n"
"1. \"oldpassphrase\" (string) The current passphrase\n"
"2. \"newpassphrase\" (string) The new passphrase\n"
"\nExamples:\n"
+ HelpExampleCli("walletpassphrasechange", "\"old one\" \"new one\"")
+ HelpExampleRpc("walletpassphrasechange", "\"old one\", \"new one\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.");
// TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strOldWalletPass;
strOldWalletPass.reserve(100);
strOldWalletPass = params[0].get_str().c_str();
SecureString strNewWalletPass;
strNewWalletPass.reserve(100);
strNewWalletPass = params[1].get_str().c_str();
if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1)
throw std::runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
return NullUniValue;
}
UniValue walletlock(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0))
throw std::runtime_error(
"walletlock\n"
"\nRemoves the wallet encryption key from memory, locking the wallet.\n"
"After calling this method, you will need to call walletpassphrase again\n"
"before being able to call any methods which require the wallet to be unlocked.\n"
"\nExamples:\n"
"\nSet the passphrase for 2 minutes to perform a transaction\n"
+ HelpExampleCli("walletpassphrase", "\"my pass phrase\" 120") +
"\nPerform a send (requires passphrase set)\n"
+ HelpExampleCli("sendtoaddress", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\" 1.0") +
"\nClear the passphrase since we are done before 2 minutes is up\n"
+ HelpExampleCli("walletlock", "") +
"\nAs json rpc call\n"
+ HelpExampleRpc("walletlock", "")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called.");
{
LOCK(cs_nWalletUnlockTime);
pwalletMain->Lock();
nWalletUnlockTime = 0;
}
return NullUniValue;
}
UniValue encryptwallet(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1))
throw std::runtime_error(
"encryptwallet \"passphrase\"\n"
"\nEncrypts the wallet with 'passphrase'. This is for first time encryption.\n"
"After this, any calls that interact with private keys such as sending or signing \n"
"will require the passphrase to be set prior the making these calls.\n"
"Use the walletpassphrase call for this, and then walletlock call.\n"
"If the wallet is already encrypted, use the walletpassphrasechange call.\n"
"Note that this will shutdown the server.\n"
"\nArguments:\n"
"1. \"passphrase\" (string) The pass phrase to encrypt the wallet with. It must be at least 1 character, but should be long.\n"
"\nExamples:\n"
"\nEncrypt you wallet\n"
+ HelpExampleCli("encryptwallet", "\"my pass phrase\"") +
"\nNow set the passphrase to use the wallet, such as for signing or sending spoomy\n"
+ HelpExampleCli("walletpassphrase", "\"my pass phrase\"") +
"\nNow we can so something like sign\n"
+ HelpExampleCli("signmessage", "\"zumyaddress\" \"test message\"") +
"\nNow lock the wallet again by removing the passphrase\n"
+ HelpExampleCli("walletlock", "") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("encryptwallet", "\"my pass phrase\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
if (fHelp)
return true;
if (pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called.");
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strWalletPass;
strWalletPass.reserve(100);
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() < 1)
throw std::runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (!pwalletMain->EncryptWallet(strWalletPass))
throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet.");
// BDB seems to have a bad habit of writing old data into
// slack space in .dat files; that is bad if the old data is
// unencrypted private keys. So:
StartShutdown();
return "Wallet encrypted; Spoomy server stopping, restart to run with encrypted wallet. The keypool has been flushed and a new HD seed was generated (if you are using HD). You need to make a new backup.";
}
UniValue lockunspent(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 1 || params.size() > 2)
throw std::runtime_error(
"lockunspent unlock [{\"txid\":\"txid\",\"vout\":n},...]\n"
"\nUpdates list of temporarily unspendable outputs.\n"
"Temporarily lock (unlock=false) or unlock (unlock=true) specified transaction outputs.\n"
"A locked transaction output will not be chosen by automatic coin selection, when spending Spoomy.\n"
"Locks are stored in memory only. Nodes start with zero locked outputs, and the locked output list\n"
"is always cleared (by virtue of process exit) when a node stops or fails.\n"
"Also see the listunspent call\n"
"\nArguments:\n"
"1. unlock (boolean, required) Whether to unlock (true) or lock (false) the specified transactions\n"
"2. \"transactions\" (string, required) A json array of objects. Each object the txid (string) vout (numeric)\n"
" [ (json array of json objects)\n"
" {\n"
" \"txid\":\"id\", (string) The transaction id\n"
" \"vout\": n (numeric) The output number\n"
" }\n"
" ,...\n"
" ]\n"
"\nResult:\n"
"true|false (boolean) Whether the command was successful or not\n"
"\nExamples:\n"
"\nList the unspent transactions\n"
+ HelpExampleCli("listunspent", "") +
"\nLock an unspent transaction\n"
+ HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nList the locked transactions\n"
+ HelpExampleCli("listlockunspent", "") +
"\nUnlock the transaction again\n"
+ HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("lockunspent", "false, \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
if (params.size() == 1)
RPCTypeCheck(params, boost::assign::list_of(UniValue::VBOOL));
else
RPCTypeCheck(params, boost::assign::list_of(UniValue::VBOOL)(UniValue::VARR));
bool fUnlock = params[0].get_bool();
if (params.size() == 1) {
if (fUnlock)
pwalletMain->UnlockAllCoins();
return true;
}
UniValue outputs = params[1].get_array();
for (unsigned int idx = 0; idx < outputs.size(); idx++) {
const UniValue& output = outputs[idx];
if (!output.isObject())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected object");
const UniValue& o = output.get_obj();
RPCTypeCheckObj(o, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM));
std::string txid = find_value(o, "txid").get_str();
if (!IsHex(txid))
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");
int nOutput = find_value(o, "vout").get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
COutPoint outpt(uint256S(txid), nOutput);
if (fUnlock)
pwalletMain->UnlockCoin(outpt);
else
pwalletMain->LockCoin(outpt);
}
return true;
}
UniValue listlockunspent(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 0)
throw std::runtime_error(
"listlockunspent\n"
"\nReturns list of temporarily unspendable outputs.\n"
"See the lockunspent call to lock and unlock transactions for spending.\n"
"\nResult:\n"
"[\n"
" {\n"
" \"txid\" : \"transactionid\", (string) The transaction id locked\n"
" \"vout\" : n (numeric) The vout value\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n"
"\nList the unspent transactions\n"
+ HelpExampleCli("listunspent", "") +
"\nLock an unspent transaction\n"
+ HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nList the locked transactions\n"
+ HelpExampleCli("listlockunspent", "") +
"\nUnlock the transaction again\n"
+ HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("listlockunspent", "")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
std::vector<COutPoint> vOutpts;
pwalletMain->ListLockedCoins(vOutpts);
UniValue ret(UniValue::VARR);
BOOST_FOREACH(COutPoint &outpt, vOutpts) {
UniValue o(UniValue::VOBJ);
o.push_back(Pair("txid", outpt.hash.GetHex()));
o.push_back(Pair("vout", (int)outpt.n));
ret.push_back(o);
}
return ret;
}
UniValue settxfee(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 1 || params.size() > 1)
throw std::runtime_error(
"settxfee amount\n"
"\nSet the transaction fee per kB. Overwrites the paytxfee parameter.\n"
"\nArguments:\n"
"1. amount (numeric or sting, required) The transaction fee in " + CURRENCY_UNIT + "/kB\n"
"\nResult\n"
"true|false (boolean) Returns true if successful\n"
"\nExamples:\n"
+ HelpExampleCli("settxfee", "0.00001")
+ HelpExampleRpc("settxfee", "0.00001")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
// Amount
CAmount nAmount = AmountFromValue(params[0]);
payTxFee = CFeeRate(nAmount, 1000);
return true;
}
UniValue getwalletinfo(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 0)
throw std::runtime_error(
"getwalletinfo\n"
"Returns an object containing various wallet state info.\n"
"\nResult:\n"
"{\n"
" \"walletversion\": xxxxx, (numeric) the wallet version\n"
" \"balance\": xxxxxxx, (numeric) the total confirmed balance of the wallet in " + CURRENCY_UNIT + "\n"
" \"unconfirmed_balance\": xxx, (numeric) the total unconfirmed balance of the wallet in " + CURRENCY_UNIT + "\n"
" \"immature_balance\": xxxxxx, (numeric) the total immature balance of the wallet in " + CURRENCY_UNIT + "\n"
" \"txcount\": xxxxxxx, (numeric) the total number of transactions in the wallet\n"
" \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since GMT epoch) of the oldest pre-generated key in the key pool\n"
" \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated (only counts external keys)\n"
" \"keypoolsize_hd_internal\": xxxx, (numeric) how many new keys are pre-generated for internal use (used for change outputs, only appears if the wallet is using this feature, otherwise external keys are used)\n"
" \"keys_left\": xxxx, (numeric) how many new keys are left since last automatic backup\n"
" \"unlocked_until\": ttt, (numeric) the timestamp in seconds since epoch (midnight Jan 1 1970 GMT) that the wallet is unlocked for transfers, or 0 if the wallet is locked\n"
" \"paytxfee\": x.xxxx, (numeric) the transaction fee configuration, set in " + CURRENCY_UNIT + "/kB\n"
" \"hdchainid\": \"<hash>\", (string) the ID of the HD chain\n"
" \"hdaccountcount\": xxx, (numeric) how many accounts of the HD chain are in this wallet\n"
" [\n"
" {\n"
" \"hdaccountindex\": xxx, (numeric) the index of the account\n"
" \"hdexternalkeyindex\": xxxx, (numeric) current external childkey index\n"
" \"hdinternalkeyindex\": xxxx, (numeric) current internal childkey index\n"
" }\n"
" ,...\n"
" ]\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getwalletinfo", "")
+ HelpExampleRpc("getwalletinfo", "")
);
LOCK2(cs_main, pwalletMain->cs_wallet);
CHDChain hdChainCurrent;
bool fHDEnabled = pwalletMain->GetHDChain(hdChainCurrent);
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
obj.push_back(Pair("unconfirmed_balance", ValueFromAmount(pwalletMain->GetUnconfirmedBalance())));
obj.push_back(Pair("immature_balance", ValueFromAmount(pwalletMain->GetImmatureBalance())));
obj.push_back(Pair("txcount", (int)pwalletMain->mapWallet.size()));
obj.push_back(Pair("keypoololdest", pwalletMain->GetOldestKeyPoolTime()));
obj.push_back(Pair("keypoolsize", (int64_t)pwalletMain->KeypoolCountExternalKeys()));
if (fHDEnabled) {
obj.push_back(Pair("keypoolsize_hd_internal", (int64_t)(pwalletMain->KeypoolCountInternalKeys())));
}
obj.push_back(Pair("keys_left", pwalletMain->nKeysLeftSinceAutoBackup));
if (pwalletMain->IsCrypted())
obj.push_back(Pair("unlocked_until", nWalletUnlockTime));
obj.push_back(Pair("paytxfee", ValueFromAmount(payTxFee.GetFeePerK())));
if (fHDEnabled) {
obj.push_back(Pair("hdchainid", hdChainCurrent.GetID().GetHex()));
obj.push_back(Pair("hdaccountcount", (int64_t)hdChainCurrent.CountAccounts()));
UniValue accounts(UniValue::VARR);
for (size_t i = 0; i < hdChainCurrent.CountAccounts(); ++i)
{
CHDAccount acc;
UniValue account(UniValue::VOBJ);
account.push_back(Pair("hdaccountindex", (int64_t)i));
if(hdChainCurrent.GetAccount(i, acc)) {
account.push_back(Pair("hdexternalkeyindex", (int64_t)acc.nExternalChainCounter));
account.push_back(Pair("hdinternalkeyindex", (int64_t)acc.nInternalChainCounter));
} else {
account.push_back(Pair("error", strprintf("account %d is missing", i)));
}
accounts.push_back(account);
}
obj.push_back(Pair("hdaccounts", accounts));
}
return obj;
}
UniValue keepass(const UniValue& params, bool fHelp)
{
std::string strCommand;
if (params.size() >= 1)
strCommand = params[0].get_str();
if (fHelp ||
(strCommand != "genkey" && strCommand != "init" && strCommand != "setpassphrase"))
throw std::runtime_error(
"keepass <genkey|init|setpassphrase>\n");
if (strCommand == "genkey")
{
SecureString sResult;
// Generate RSA key
SecureString sKey = CKeePassIntegrator::generateKeePassKey();
sResult = "Generated Key: ";
sResult += sKey;
return sResult.c_str();
}
else if(strCommand == "init")
{
// Generate base64 encoded 256 bit RSA key and associate with KeePassHttp
SecureString sResult;
SecureString sKey;
std::string strId;
keePassInt.rpcAssociate(strId, sKey);
sResult = "Association successful. Id: ";
sResult += strId.c_str();
sResult += " - Key: ";
sResult += sKey.c_str();
return sResult.c_str();
}
else if(strCommand == "setpassphrase")
{
if(params.size() != 2) {
return "setlogin: invalid number of parameters. Requires a passphrase";
}
SecureString sPassphrase = SecureString(params[1].get_str().c_str());
keePassInt.updatePassphrase(sPassphrase);
return "setlogin: Updated credentials.";
}
return "Invalid command";
}
UniValue resendwallettransactions(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() != 0)
throw std::runtime_error(
"resendwallettransactions\n"
"Immediately re-broadcast unconfirmed wallet transactions to all peers.\n"
"Intended only for testing; the wallet code periodically re-broadcasts\n"
"automatically.\n"
"Returns array of transaction ids that were re-broadcast.\n"
);
LOCK2(cs_main, pwalletMain->cs_wallet);
std::vector<uint256> txids = pwalletMain->ResendWalletTransactionsBefore(GetTime());
UniValue result(UniValue::VARR);
BOOST_FOREACH(const uint256& txid, txids)
{
result.push_back(txid.ToString());
}
return result;
}
UniValue listunspent(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() > 3)
throw std::runtime_error(
"listunspent ( minconf maxconf [\"address\",...] )\n"
"\nReturns array of unspent transaction outputs\n"
"with between minconf and maxconf (inclusive) confirmations.\n"
"Optionally filter 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}\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) The minimum confirmations to filter\n"
"2. maxconf (numeric, optional, default=9999999) The maximum confirmations to filter\n"
"3. \"addresses\" (string) A json array of spoomy addresses to filter\n"
" [\n"
" \"address\" (string) spoomy address\n"
" ,...\n"
" ]\n"
"\nResult\n"
"[ (array of json object)\n"
" {\n"
" \"txid\" : \"txid\", (string) the transaction id \n"
" \"vout\" : n, (numeric) the vout value\n"
" \"address\" : \"address\", (string) the Spoomy address\n"
" \"account\" : \"account\", (string) DEPRECATED. The associated account, or \"\" for the default account\n"
" \"scriptPubKey\" : \"key\", (string) the script key\n"
" \"amount\" : x.xxx, (numeric) the transaction amount in " + CURRENCY_UNIT + "\n"
" \"confirmations\" : n (numeric) The number of confirmations\n"
" \"ps_rounds\" : n (numeric) The number of PS round\n"
" \"spendable\" : true|false (boolean) True if spendable\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples\n"
+ HelpExampleCli("listunspent", "")
+ HelpExampleCli("listunspent", "10 9999999 \"[\\\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\\\",\\\"C1MfcDTf7Zsef8gMGL2fhWA9ZslrP4K5tf\\\"]\"")
+ HelpExampleRpc("listunspent", "10, 9999999 \"[\\\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\\\",\\\"C1MfcDTf7Zsef8gMGL2fhWA9ZslrP4K5tf\\\"]\"")
);
RPCTypeCheck(params, boost::assign::list_of(UniValue::VNUM)(UniValue::VNUM)(UniValue::VARR));
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
int nMaxDepth = 9999999;
if (params.size() > 1)
nMaxDepth = params[1].get_int();
std::set<CSpoomyAddress> setAddress;
if (params.size() > 2) {
UniValue inputs = params[2].get_array();
for (unsigned int idx = 0; idx < inputs.size(); idx++) {
const UniValue& input = inputs[idx];
CSpoomyAddress address(input.get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid Spoomy address: ")+input.get_str());
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ")+input.get_str());
setAddress.insert(address);
}
}
UniValue results(UniValue::VARR);
std::vector<COutput> vecOutputs;
assert(pwalletMain != NULL);
LOCK2(cs_main, pwalletMain->cs_wallet);
pwalletMain->AvailableCoins(vecOutputs, false, NULL, true);
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;
}
CAmount nValue = out.tx->vout[out.i].nValue;
const CScript& pk = out.tx->vout[out.i].scriptPubKey;
UniValue entry(UniValue::VOBJ);
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", CSpoomyAddress(address).ToString()));
if (pwalletMain->mapAddressBook.count(address))
entry.push_back(Pair("account", pwalletMain->mapAddressBook[address].name));
}
entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end())));
if (pk.IsPayToScriptHash()) {
CTxDestination address;
if (ExtractDestination(pk, address)) {
const CScriptID& hash = boost::get<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));
entry.push_back(Pair("ps_rounds", pwalletMain->GetInputPrivateSendRounds(CTxIn(out.tx->GetHash(), out.i))));
entry.push_back(Pair("spendable", out.fSpendable));
results.push_back(entry);
}
return results;
}
UniValue fundrawtransaction(const UniValue& params, bool fHelp)
{
if (!EnsureWalletIsAvailable(fHelp))
return NullUniValue;
if (fHelp || params.size() < 1 || params.size() > 2)
throw std::runtime_error(
"fundrawtransaction \"hexstring\" includeWatching\n"
"\nAdd inputs to a transaction until it has enough in value to meet its out value.\n"
"This will not modify existing inputs, and will add one change output to the outputs.\n"
"Note that inputs which were signed may need to be resigned after completion since in/outputs have been added.\n"
"The inputs added will not be signed, use signrawtransaction for that.\n"
"Note that all existing inputs must have their previous output transaction be in the wallet.\n"
"Note that all inputs selected must be of standard form and P2SH scripts must be"
"in the wallet using importaddress or addmultisigaddress (to calculate fees).\n"
"Only pay-to-pubkey, multisig, and P2SH versions thereof are currently supported for watch-only\n"
"\nArguments:\n"
"1. \"hexstring\" (string, required) The hex string of the raw transaction\n"
"2. includeWatching (boolean, optional, default false) Also select inputs which are watch only\n"
"\nResult:\n"
"{\n"
" \"hex\": \"value\", (string) The resulting raw transaction (hex-encoded string)\n"
" \"fee\": n, (numeric) Fee the resulting transaction pays\n"
" \"changepos\": n (numeric) The position of the added change output, or -1\n"
"}\n"
"\"hex\" \n"
"\nExamples:\n"
"\nCreate a transaction with no inputs\n"
+ HelpExampleCli("createrawtransaction", "\"[]\" \"{\\\"myaddress\\\":0.01}\"") +
"\nAdd sufficient unsigned inputs to meet the output value\n"
+ HelpExampleCli("fundrawtransaction", "\"rawtransactionhex\"") +
"\nSign the transaction\n"
+ HelpExampleCli("signrawtransaction", "\"fundedtransactionhex\"") +
"\nSend the transaction\n"
+ HelpExampleCli("sendrawtransaction", "\"signedtransactionhex\"")
);
RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)(UniValue::VBOOL));
// parse hex string from parameter
CTransaction origTx;
if (!DecodeHexTx(origTx, params[0].get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
if (origTx.vout.size() == 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "TX must have at least one output");
bool includeWatching = false;
if (params.size() > 1)
includeWatching = params[1].get_bool();
CMutableTransaction tx(origTx);
CAmount nFee;
std::string strFailReason;
int nChangePos = -1;
if(!pwalletMain->FundTransaction(tx, nFee, nChangePos, strFailReason, includeWatching))
throw JSONRPCError(RPC_INTERNAL_ERROR, strFailReason);
UniValue result(UniValue::VOBJ);
result.push_back(Pair("hex", EncodeHexTx(tx)));
result.push_back(Pair("changepos", nChangePos));
result.push_back(Pair("fee", ValueFromAmount(nFee)));
return result;
}
UniValue makekeypair(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw std::runtime_error(
"makekeypair [prefix]\n"
"Make a public/private key pair.\n"
"[prefix] is optional preferred prefix for the public key.\n");
std::string strPrefix = "";
if (params.size() > 0)
strPrefix = params[0].get_str();
CKey key;
int nCount = 0;
do
{
key.MakeNewKey(false);
nCount++;
} while (nCount < 10000 && strPrefix != HexStr(key.GetPubKey()).substr(0, strPrefix.size()));
if (strPrefix != HexStr(key.GetPubKey()).substr(0, strPrefix.size()))
return NullUniValue;
CPrivKey vchPrivKey = key.GetPrivKey();
UniValue result(UniValue::VOBJ);
result.push_back(Pair("PrivateKey", HexStr<CPrivKey::iterator>(vchPrivKey.begin(), vchPrivKey.end())));
result.push_back(Pair("PublicKey", HexStr(key.GetPubKey())));
return result;
}
| [
"dev@zumy.co"
] | dev@zumy.co |
f0cbe107198ae902d704935269727cb7c2e1ccbb | e7aadf0214af5077d3516f7201a9c7e753c22e5b | /extensions/ringqt/gdial.cpp | f3bc029389e82587ef0b12498bae6bc761516e39 | [
"MIT"
] | permissive | sethgreen23/ring | 7e45524a946e41af8bf6dda488b6e2e6d7d7fc60 | 2c4e0717a30f056ce677b2cce5e0b0a2a7680787 | refs/heads/master | 2020-06-17T20:23:56.435446 | 2016-11-26T09:11:57 | 2016-11-26T09:11:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,909 | cpp |
/* Copyright (c) 2013-2016 Mahmoud Fayed <msfclipper@yahoo.com> */
extern "C" {
#include "ring.h"
}
#include "gdial.h"
GDial::GDial(QWidget *parent,VM *pVM) : QDial(parent)
{
this->pVM = pVM;
this->pParaList = ring_list_new(0);
strcpy(this->cactionTriggeredEvent,"");
strcpy(this->crangeChangedEvent,"");
strcpy(this->csliderMovedEvent,"");
strcpy(this->csliderPressedEvent,"");
strcpy(this->csliderReleasedEvent,"");
strcpy(this->cvalueChangedEvent,"");
QObject::connect(this, SIGNAL(actionTriggered(int)),this, SLOT(actionTriggeredSlot()));
QObject::connect(this, SIGNAL(rangeChanged(int,int)),this, SLOT(rangeChangedSlot()));
QObject::connect(this, SIGNAL(sliderMoved(int)),this, SLOT(sliderMovedSlot()));
QObject::connect(this, SIGNAL(sliderPressed()),this, SLOT(sliderPressedSlot()));
QObject::connect(this, SIGNAL(sliderReleased()),this, SLOT(sliderReleasedSlot()));
QObject::connect(this, SIGNAL(valueChanged(int)),this, SLOT(valueChangedSlot()));
}
GDial::~GDial()
{
ring_list_delete(this->pParaList);
}
void GDial::geteventparameters(void)
{
void *pPointer;
pPointer = this->pVM;
RING_API_RETLIST(this->pParaList);
}
void GDial::setactionTriggeredEvent(const char *cStr)
{
if (strlen(cStr)<100)
strcpy(this->cactionTriggeredEvent,cStr);
}
void GDial::setrangeChangedEvent(const char *cStr)
{
if (strlen(cStr)<100)
strcpy(this->crangeChangedEvent,cStr);
}
void GDial::setsliderMovedEvent(const char *cStr)
{
if (strlen(cStr)<100)
strcpy(this->csliderMovedEvent,cStr);
}
void GDial::setsliderPressedEvent(const char *cStr)
{
if (strlen(cStr)<100)
strcpy(this->csliderPressedEvent,cStr);
}
void GDial::setsliderReleasedEvent(const char *cStr)
{
if (strlen(cStr)<100)
strcpy(this->csliderReleasedEvent,cStr);
}
void GDial::setvalueChangedEvent(const char *cStr)
{
if (strlen(cStr)<100)
strcpy(this->cvalueChangedEvent,cStr);
}
void GDial::actionTriggeredSlot()
{
if (strcmp(this->cactionTriggeredEvent,"")==0)
return ;
ring_vm_runcode(this->pVM,this->cactionTriggeredEvent);
}
void GDial::rangeChangedSlot()
{
if (strcmp(this->crangeChangedEvent,"")==0)
return ;
ring_vm_runcode(this->pVM,this->crangeChangedEvent);
}
void GDial::sliderMovedSlot()
{
if (strcmp(this->csliderMovedEvent,"")==0)
return ;
ring_vm_runcode(this->pVM,this->csliderMovedEvent);
}
void GDial::sliderPressedSlot()
{
if (strcmp(this->csliderPressedEvent,"")==0)
return ;
ring_vm_runcode(this->pVM,this->csliderPressedEvent);
}
void GDial::sliderReleasedSlot()
{
if (strcmp(this->csliderReleasedEvent,"")==0)
return ;
ring_vm_runcode(this->pVM,this->csliderReleasedEvent);
}
void GDial::valueChangedSlot()
{
if (strcmp(this->cvalueChangedEvent,"")==0)
return ;
ring_vm_runcode(this->pVM,this->cvalueChangedEvent);
}
| [
"msfclipper@yahoo.com"
] | msfclipper@yahoo.com |
1fcb4e818ab38f916dea8bedeb0cbd950721c95b | e24e674ababf1763f9ba43f810c6b5828ebcf68f | /Linked Lists/InsertHead_Circularll.cpp | 1ee138409feb75e31dced606522f8c709f91727c | [] | no_license | ACES-DYPCOE/Data-Structure | 8f833b86876e233e8a1e46e067c1808c164fc6b8 | 292b3c1f3dec3b7e5ae3f5143146201892e3ed4d | refs/heads/master | 2023-07-22T16:08:11.710042 | 2021-09-07T10:44:42 | 2021-09-07T10:44:42 | 299,687,733 | 22 | 44 | null | 2021-09-07T10:44:42 | 2020-09-29T17:19:32 | C++ | UTF-8 | C++ | false | false | 567 | cpp | //Given a circular linked list of size N, you need to insert an element data before the head and make it the new head. The tail of the linked list is connected to head.
//solution
Node *insertInHead(Node * head, int data)
{
Node* newn=new Node(data);
if(head==NULL)
{
head=newn;
newn->next=head;
}
else
{
Node* temp=head;
do{
temp=temp->next;
}while(temp->next!=head);
newn->next=head;
head=newn;
temp->next=head;
}
return head;
} | [
"noreply@github.com"
] | ACES-DYPCOE.noreply@github.com |
b28d8002248070bc0a260aff788045ac20056452 | c3ba724f8fde86f644690e1d3aeec855d9dc395b | /third_person/Source/third_person/third_personGameMode.h | 147c80e36498c79c8027f5628e58bf7b36589871 | [] | no_license | wyxloading/ue4-samples | 4577522de40404104b7cc5cc76cab55e72b54a45 | 878c070f6f4dc1a5144f98475f237b111a688736 | refs/heads/master | 2021-06-07T03:01:56.077095 | 2016-09-07T00:18:52 | 2016-09-07T00:18:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 282 | h | // Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "GameFramework/GameMode.h"
#include "third_personGameMode.generated.h"
UCLASS(minimalapi)
class Athird_personGameMode : public AGameMode
{
GENERATED_BODY()
public:
Athird_personGameMode();
};
| [
"tonculture@hotmail.com"
] | tonculture@hotmail.com |
3f8363e10dfa330b21fa9d0ad32970c7c97e28c3 | af0e1b9507d4ade87c312b0cc0bf1bf167fa83a0 | /3d_reconstruction/refinement.h | 85c1a59a78af32a8cc60e9413a9ece115ba3964c | [] | no_license | kolina/diploma | 07f560b24ae63e4449c5658f69b958f64ce93c94 | bc161e642d2db20be0162afd974f3328b16293bc | refs/heads/master | 2021-01-11T08:03:53.526604 | 2016-11-05T09:37:41 | 2016-11-05T09:37:41 | 72,917,046 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,454 | h | #ifndef INC_3D_RECONSTRUCTION_REFINEMENT_H
#define INC_3D_RECONSTRUCTION_REFINEMENT_H
#include "optimization.h"
struct AbsolutePoseEstimationOptions {
bool estimate_focal_length = false;
size_t num_focal_length_samples = 30;
double min_focal_length_ratio = 0.2;
double max_focal_length_ratio = 5;
int num_threads = ThreadPool::kMaxNumThreads;
RANSACOptions ransac_options;
void Check() const {
ransac_options.Check();
}
};
struct AbsolutePoseRefinementOptions {
double gradient_tolerance = 1.0;
int max_num_iterations = 100;
double loss_function_scale = 1.0;
bool refine_focal_length = true;
bool refine_extra_params = true;
bool print_summary = true;
void Check() const {
}
};
bool EstimateAbsolutePose(const AbsolutePoseEstimationOptions& options,
const std::vector<Eigen::Vector2d>& points2D,
const std::vector<Eigen::Vector3d>& points3D,
Eigen::Vector4d* qvec, Eigen::Vector3d* tvec,
Camera* camera, size_t* num_inliers,
std::vector<bool>* inlier_mask);
size_t EstimateRelativePose(const RANSACOptions& ransac_options,
const std::vector<Eigen::Vector2d>& points1,
const std::vector<Eigen::Vector2d>& points2,
Eigen::Vector4d* qvec, Eigen::Vector3d* tvec);
bool RefineAbsolutePose(const AbsolutePoseRefinementOptions& options,
const std::vector<bool>& inlier_mask,
const std::vector<Eigen::Vector2d>& points2D,
const std::vector<Eigen::Vector3d>& points3D,
Eigen::Vector4d* qvec, Eigen::Vector3d* tvec,
Camera* camera);
bool RefineRelativePose(const ceres::Solver::Options& options,
const std::vector<Eigen::Vector2d>& points1,
const std::vector<Eigen::Vector2d>& points2,
Eigen::Vector4d* qvec, Eigen::Vector3d* tvec);
bool RefineEssentialMatrix(const ceres::Solver::Options& options,
const std::vector<Eigen::Vector2d>& points1,
const std::vector<Eigen::Vector2d>& points2,
const std::vector<bool>& inlier_mask,
Eigen::Matrix3d* E);
#endif //INC_3D_RECONSTRUCTION_REFINEMENT_H
| [
"kolina93@yandex-team.ru"
] | kolina93@yandex-team.ru |
8a6c8c4c56f8907cf18522567ea1c6402e847703 | 12d3908fc4a374e056041df306e383d95d8ff047 | /Programs/prog14.cpp | 9c65a7e36a4f92e0db39b5f7b581dc3f34539d9a | [
"MIT"
] | permissive | rux616/c201 | aca5898c506aeb1792aa8b1f9dcf3d797a1cd888 | d8509e8d49e52e7326486249ad8d567560bf4ad4 | refs/heads/master | 2021-01-01T16:14:44.747670 | 2017-07-20T05:14:24 | 2017-07-20T05:14:24 | 97,792,948 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,940 | cpp | /* Prog14.cpp
Shows how to pass command line arguments to a function and how to
reference individual characters of command line arguments.
------------------------------------------------------------------------*/
#include <iostream>
#include <string>
using namespace std;
void ShowCommandLineArgs (int ArgCount, char* Argument[]);
//************************** main *************************************
void main (int argc, char* argv[]) // Allow command line args
{
ShowCommandLineArgs (argc, argv);
}
/********************** ShowCommandLineArgs *****************************
Reveals some information about command line arguments that have been
passed to main().
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/
void ShowCommandLineArgs (int ArgCount, char* Argument[])
{
cout << "\nNumber of command line args: " << ArgCount
<< "\n\nHere's what you entered on the command line: \n\n";
for ( int N = 0; N < ArgCount ; ++N )
cout << Argument[N] << " ";
cout << "\n\nThe first character of argv[1] is '" << Argument[1][0] << "'"
<< "\nThe third character of argv[1] is '" << Argument[1][2] << "'"
<< "\n\nThe length of the second argument is " << strlen(Argument[1]);
}
/********************* program notes *****************************
1) Refer to prog12.cpp for introductory comments on command line args.
2) If the user ran this program via the command, "prog14 /abc def"
the program would output:
Number of command line args: 3
Here's what you entered on the command line:
PROG14.EXE /abd def
The first character of argv[1] is '/'
The third character of argv[1] is 'b'
The length of the second argument is 4
3) A careful reading of the function ShowCommandLineArgs will yield
insights into how to send command line info to a function and how
to process command line info. */ | [
"dan.cassidy.1983@gmail.com"
] | dan.cassidy.1983@gmail.com |
bcc04f8fe31e868237a1153c5a4bf70468d7f7e6 | a679dba6ef0364962b94ed65d0caad1a88da6c43 | /OrginalServerCode/OrginalCode/labixiaoxin/ACE_wrappers/ASNMP/asnmp/oid.cpp | 8cbd4c661616d3ba19249529ccc77fa67550b63a | [
"MIT-CMU",
"LicenseRef-scancode-hp-snmp-pp"
] | permissive | w5762847/Learn | 7f84933fe664e6cf52089a9f4b9140fca8b9a783 | a5494181ea791fd712283fa8e78ca0287bf05318 | refs/heads/master | 2020-08-27T05:43:35.496579 | 2016-12-02T12:16:12 | 2016-12-02T12:16:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,829 | cpp | // $Id: oid.cpp 91670 2010-09-08 18:02:26Z johnnyw $
// ============================================================================
//
// = LIBRARY
// asnmp
//
// = FILENAME
// oid.cpp
//
// = DESCRIPTION
// This module contains the implementation of the oid class. This
// includes all protected and public member functions. The oid class
// may be compiled stand alone without the use of any other library.
//
// = AUTHOR
// Peter E Mellquist
// Michael R MacFaden mrm@cisco.com - rework & ACE port
// ============================================================================
/*===================================================================
Copyright (c) 1996
Hewlett-Packard Company
ATTENTION: USE OF THIS SOFTWARE IS SUBJECT TO THE FOLLOWING TERMS.
Permission to use, copy, modify, distribute and/or sell this software
and/or its documentation is hereby granted without fee. User agrees
to display the above copyright notice and this license notice in all
copies of the software and any documentation of the software. User
agrees to assume all liability for the use of the software; Hewlett-Packard
makes no representations about the suitability of this software for any
purpose. It is provided "AS-IS" without warranty of any kind,either express
or implied. User hereby grants a royalty-free license to any and all
derivatives based upon this software code base.
=====================================================================*/
//---------[ external C libaries used ]--------------------------------
#include "asnmp/oid.h" // include def for oid class
#include "ace/OS_NS_string.h"
#include "ace/OS_NS_stdio.h"
#include "ace/OS_Memory.h"
#include "ace/OS_NS_ctype.h"
enum Defs {SNMPBUFFSIZE=300,
SNMPCHARSIZE=15}; // max oid value (4294967295UL)
#define NO_MEM_STR "ERROR: Oid::to_string: memory allocation failure"
//=============[Oid::get_syntax(void)]====================================
SmiUINT32 Oid::get_syntax()
{
return sNMP_SYNTAX_OID;
}
//=============[Oid::Oid( const char *dotted_string ]=====================
// constructor using a dotted string
//
// do a string to oid using the string passed in
Oid::Oid( const char * dotted_oid_string, size_t size)
{
// can't init enum SmiValue so just memset it clean
set_null();
size_t z;
if ((z = ACE_OS::strlen(dotted_oid_string)) == 0) {
set_invalid();
return;
}
if (size == (unsigned int)-1)
size = z;
if (size > z)
size = z;
char *ptr = (char *)dotted_oid_string;;
if (size < z) {
// create new buffer if needed
ACE_NEW(ptr, char [size]);
// sz should be in StrToOid?
ACE_OS::memcpy( (void *)ptr, dotted_oid_string, size);
}
size_t byte_counter;
if (StrToOid( (char *) ptr, &smival.value.oid, byte_counter) < 0)
set_invalid();
if (ptr != dotted_oid_string)
delete [] ptr;
}
//=============[Oid::Oid( const Oid &oid) ]================================
// constructor using another oid object
//
// do an oid copy using the oid object passed in
Oid::Oid ( const Oid &oid)
: SnmpSyntax (oid)
{
set_null();
// allocate some memory for the oid
// in this case the size to allocate is the same
// size as the source oid
if (oid.smival.value.oid.len) {
ACE_NEW(smival.value.oid.ptr, SmiUINT32[ oid.smival.value.oid.len]);
size_t byte_counter;
OidCopy( (SmiLPOID) &(oid.smival.value.oid),(SmiLPOID)
&smival.value.oid, byte_counter);
}
}
//=============[Oid::Oid( const unsigned long *raw_oid, int oid_len) ]====
// constructor using raw numeric form
//
// copy the integer values into the private member
Oid::Oid(const unsigned long *raw_oid, size_t oid_len)
{
set_null();
smival.syntax = sNMP_SYNTAX_OID;
set_invalid();
if (raw_oid && oid_len > 0) {
ACE_NEW(smival.value.oid.ptr, SmiUINT32[ oid_len]);
smival.value.oid.len = oid_len;
for (size_t i=0; i < oid_len; i++)
smival.value.oid.ptr[i] = raw_oid[i];
}
}
//=============[Oid::~Oid]==============================================
// destructor
//
// free up the descriptor space
Oid::~Oid()
{
// free up the octet deep memory
if ( smival.value.oid.ptr ) {
set_invalid();
}
// free up the output string
if ( iv_str != 0)
delete [] iv_str;
}
//=============[Oid::operator = const char * dotted_string ]==============
// assignment to a string operator overloaded
//
// free the existing oid
// create the new oid from the string
// return this object
void Oid::set_data( const char *dotted_oid_string)
{
// delete the old value
if ( smival.value.oid.ptr ) {
set_invalid();
}
// assign the new value
size_t byte_counter;
if (StrToOid( (char *) dotted_oid_string, &smival.value.oid, byte_counter) <0)
set_invalid();
}
//=============[Oid:: operator = const Oid &oid ]==========================
// assignment to another oid object overloaded
//
// free the existing oid
// create a new one from the object passed in
// TODO: measure perf vs memory of no realloc in case where len >= oid.len
Oid& Oid::operator=( const Oid &oid)
{
// protect against assignment from self
if ( this == &oid)
return *this;
set_invalid();
// check for zero len on source
if ( oid.smival.value.oid.len == 0)
return *this;
const SmiLPOID srcOid = (SmiLPOID) &(oid.smival.value.oid);
init_value(srcOid, oid.smival.value.oid.len);
return *this;
}
// assign this object the oid, set to invalid if copy fails
void Oid::init_value(const SmiLPOID srcOid, size_t len)
{
// allocate some memory for the oid
ACE_NEW(smival.value.oid.ptr, SmiUINT32[ len]);
size_t byte_counter;
OidCopy( srcOid, (SmiLPOID) &smival.value.oid, byte_counter);
}
void Oid::init_value(const unsigned long *raw_oid, size_t oid_len)
{
if (smival.value.oid.ptr)
delete [] smival.value.oid.ptr;
ACE_NEW(smival.value.oid.ptr, SmiUINT32[ oid_len]);
ACE_OS::memcpy((SmiLPBYTE) smival.value.oid.ptr,
(SmiLPBYTE) raw_oid,
(size_t) (oid_len * sizeof(SmiUINT32)));
smival.value.oid.len = oid_len;
}
//==============[Oid:: operator += const char *a ]=========================
// append operator, appends a string
//
// allocate some space for a max oid string
// extract current string into space
// concat new string
// free up existing oid
// make a new oid from string
// delete allocated space
Oid& Oid::operator+=( const char *a)
{
unsigned long n;
if (!a)
return *this;
if ( *a=='.')
a++;
size_t sz = ACE_OS::strlen(a);
if (valid()) {
n = (smival.value.oid.len *SNMPCHARSIZE) + smival.value.oid.len + 1 + sz;
char *ptr;
ACE_NEW_RETURN(ptr, char[ n], *this);
size_t byte_counter;
if (OidToStr(&smival.value.oid, n,ptr, byte_counter) > 0) {
delete [] ptr;
set_invalid();
return *this;
}
if (ACE_OS::strlen(ptr))
ACE_OS::strcat(ptr,".");
ACE_OS::strcat(ptr,a);
if ( smival.value.oid.len !=0) {
set_invalid();
}
if (StrToOid( (char *) ptr, &smival.value.oid, byte_counter) < 0) {
set_invalid();
}
delete [] ptr;
}
else {
size_t byte_counter;
if (StrToOid( (char *) a, &smival.value.oid, byte_counter) < 0) {
set_invalid();
}
}
return *this;
}
//=============[ bool operator == oid,oid ]=================================
// equivlence operator overloaded
bool operator==( const Oid &lhs, const Oid &rhs)
{
// ensure same len, then use left_comparison
if (rhs.length() != lhs.length())
return false;
if( lhs.left_comparison( rhs.length(), rhs) == 0)
return true;
else
return false;
}
//==============[ bool operator!=( Oid &x,Oid &y) ]=======================
//not equivlence operator overloaded
bool operator!=( const Oid &lhs,const Oid &rhs)
{
return (!(lhs == rhs));
}
//==============[ bool operator<( Oid &x,Oid &y) ]========================
// less than < overloaded
bool operator<( const Oid &lhs,const Oid &rhs)
{
int result;
// call left_comparison with the current
// Oidx, Oidy and len of Oidx
if ((result = lhs.left_comparison( rhs.length(), rhs)) < 0)
return true;
else if (result > 0)
return false;
else{
// if here, equivalent substrings, call the shorter one <
if (lhs.length() < rhs.length())
return true;
else
return false;
}
}
//==============[ bool operator<=( Oid &x,Oid &y) ]=======================
// less than <= overloaded
bool operator<=( const Oid &x,const Oid &y)
{
if ( (x < y) || (x == y) )
return true;
else
return false;
}
//==============[ bool operator>( Oid &x,Oid &y) ]========================
// greater than > overloaded
bool operator>( const Oid &x,const Oid &y)
{
// just invert existing <=
if (!(x<=y))
return true;
else
return false;
}
//==============[ bool operator>=( Oid &x,Oid &y) ]=======================
// greater than >= overloaded
bool operator>=( const Oid &x,const Oid &y)
{
// just invert existing <
if (!(x<y))
return true;
else
return false;
}
//===============[Oid::oidval ]=============================================
// return the WinSnmp oid part
SmiLPOID Oid::oidval()
{
return (SmiLPOID) &smival.value.oid;
}
//===============[Oid::set_data ]==---=====================================
// copy data from raw form...
void Oid::set_data( const unsigned long *raw_oid, const size_t oid_len)
{
if (smival.value.oid.len < oid_len) {
if ( smival.value.oid.ptr) {
set_invalid();
}
}
init_value(raw_oid, oid_len);
}
//===============[Oid::len ]================================================
// return the len of the oid
size_t Oid::length() const
{
return smival.value.oid.len;
}
//===============[Oid::trim( unsigned int) ]============================
// trim off the n leftmost values of an oid
// Note!, does not adjust actual space for
// speed
void Oid::trim( const size_t n)
{
// verify that n is legal
if ((n<=smival.value.oid.len)&&(n>0)) {
smival.value.oid.len -= n;
if (smival.value.oid.len == 0) {
set_invalid();
}
}
}
//===============[Oid::set_invalid() ]====================
// make this object invalid by resetting all values
void Oid::set_invalid() {
delete [] smival.value.oid.ptr;
smival.value.oid.ptr = 0;
smival.value.oid.len = 0;
delete [] iv_str;
iv_str = 0;
}
//===============[Oid::set_null() ]====================
void Oid::set_null() {
smival.syntax = sNMP_SYNTAX_OID;
smival.value.oid.ptr = 0;
smival.value.oid.len = 0;
iv_str = 0;
}
//===============[Oid::operator += const unsigned int) ]====================
// append operator, appends an int
//
// allocate some space for a max oid string
// extract current string into space
// concat new string
// free up existing oid
// make a new oid from string
// delete allocated space
Oid& Oid::operator+=( const unsigned long i)
{
unsigned long n = (smival.value.oid.len * SNMPCHARSIZE)
+ ( smival.value.oid.len -1) + 1 + 4;
char buffer[SNMPBUFFSIZE];
// two cases: null oid, existing oid
if (valid()) {
// allocate some temporary space
char *ptr;
ACE_NEW_RETURN(ptr, char[ n], *this);
size_t byte_counter;
if (OidToStr(&smival.value.oid, n, ptr, byte_counter) < 0) {
set_invalid();
delete [] ptr;
return *this;
}
if (ACE_OS::strlen(ptr))
ACE_OS::strcat(ptr,".");
if (ACE_OS::sprintf( buffer,"%lu",i) != -1) {
ACE_OS::strcat(ptr, buffer);
if ( smival.value.oid.ptr ) {
set_invalid();
}
if (StrToOid( (char *) ptr, &smival.value.oid, byte_counter) < 0) {
set_invalid();
}
delete [] ptr;
}
}
else {
init_value((const unsigned long *)&i, (size_t)1);
}
return *this;
}
//===============[Oid::operator += const Oid) ]========================
// append operator, appends an Oid
//
// allocate some space for a max oid string
// extract current string into space
// concat new string
// free up existing oid
// make a new oid from string
// delete allocated space
Oid& Oid::operator+=( const Oid &o)
{
SmiLPUINT32 new_oid;
if (o.smival.value.oid.len == 0)
return *this;
ACE_NEW_RETURN(new_oid,
SmiUINT32[ smival.value.oid.len + o.smival.value.oid.len], *this);
if (smival.value.oid.ptr) {
ACE_OS::memcpy((SmiLPBYTE) new_oid,
(SmiLPBYTE) smival.value.oid.ptr,
(size_t) (smival.value.oid.len*sizeof(SmiUINT32)));
delete [] smival.value.oid.ptr;
}
// out with the old, in with the new...
smival.value.oid.ptr = new_oid;
ACE_OS::memcpy((SmiLPBYTE) &new_oid[smival.value.oid.len],
(SmiLPBYTE) o.smival.value.oid.ptr,
(size_t) (o.smival.value.oid.len*sizeof(SmiUINT32)));
smival.value.oid.len += o.smival.value.oid.len;
return *this;
}
// return string portion of the oid
//
const char * Oid::to_string()
{
unsigned long n;
if (!valid())
return ""; // be consistent with other classes
// the worst case char len of an oid can be..
// oid.len*3 + dots in between if each oid is XXXX
// so.. size = (len*4) + (len-1) + 1 , extra for a null
n = (smival.value.oid.len *SNMPCHARSIZE) + ( smival.value.oid.len -1) + 1 ;
if (n == 0)
n = 1; // need at least 1 byte for a null string
// adjust the len of output array in case size was adjusted
if ( iv_str != 0)
delete [] iv_str;
// allocate some space for the output string
ACE_NEW_RETURN(iv_str, char[ n], "");
// convert to an output string
size_t how_many;
if ( valid() && iv_str != 0)
if (OidToStr(&smival.value.oid,n,iv_str, how_many) < 0)
return "ERROR: Oid::OidToStr failed";
return iv_str;
}
//==============[Oid::suboid( unsigned int start, n) ]=============
int Oid::suboid(Oid& new_oid, size_t start, size_t how_many)
{
if (how_many == 0)
return 0;
else
if (how_many == (size_t)-1)
how_many = length();
else
if (how_many > length())
how_many = length();
// reset new_oid
new_oid.set_invalid();
size_t new_size = how_many - start;
if (new_size == 0)
new_size++;
new_oid.smival.value.oid.len = new_size;
ACE_NEW_RETURN(new_oid.smival.value.oid.ptr,
SmiUINT32 [ new_oid.smival.value.oid.len], -1);
// copy source to destination
ACE_OS::memcpy( (SmiLPBYTE) new_oid.smival.value.oid.ptr,
(SmiLPBYTE) (smival.value.oid.ptr + start),
new_size * sizeof(SmiLPBYTE));
return 0;
}
//=============[Oid::StrToOid( char *string, SmiLPOID dst) ]==============
// convert a string to an oid
int Oid::StrToOid( const char *string, SmiLPOID dstOid, size_t& how_many)
{
size_t index = 0;
size_t number = 0;
// make a temp buffer to copy the data into first
SmiLPUINT32 temp;
unsigned long nz;
if (string && *string) {
nz = ACE_OS::strlen( string);
}
else {
dstOid->len = 0;
dstOid->ptr = 0;
return -1;
}
ACE_NEW_RETURN(temp, SmiUINT32[ nz], -1);
while (*string!=0 && index<nz) {
// init the number for each token
number = 0;
// skip over the dot
if (*string=='.')
string++;
// grab a digit token and convert it to a long int
while (ACE_OS::ace_isdigit(*string))
number=number*10 + *(string++)-'0';
// check for invalid chars
if (*string!=0 && *string!='.') {
// Error: Invalid character in string
delete [] temp;
return -1;
}
// stuff the value into the array
temp[index] = number;
index++; // bump the counter
}
// get some space for the real oid
ACE_NEW_RETURN(dstOid->ptr, SmiUINT32[ index], -1);
// TODO: make tmp autoptr type delete [] temp to prevent leak
// copy in the temp data
ACE_OS::memcpy((SmiLPBYTE) dstOid->ptr, (SmiLPBYTE) temp,
(size_t) (index*sizeof(SmiUINT32)));
// set the len of the oid
dstOid->len = index;
// free up temp data
delete [] temp;
how_many = index;
return 0;
}
//===============[Oid::OidCopy( source, destination) ]====================
// Copy an oid, return bytes copied
int Oid::OidCopy( SmiLPOID srcOid, SmiLPOID dstOid, size_t& how_many_bytes)
{
// check source len ! zero
if (srcOid->len == 0)
return -1;
// copy source to destination
ACE_OS::memcpy((SmiLPBYTE) dstOid->ptr,
(SmiLPBYTE) srcOid->ptr,
(size_t) (srcOid->len * sizeof(SmiUINT32)));
//set the new len
dstOid->len = srcOid->len;
how_many_bytes = srcOid->len;
return 0;
}
//===============[Oid::left_comparison( n, Oid) ]=================================
// compare the n leftmost values of two oids ( left-to_right )
//
// self == Oid then return 0, they are equal
// self < Oid then return -1, <
// self > Oid then return 1, >
int Oid::left_comparison( const unsigned long n, const Oid &o) const
{
unsigned long z;
unsigned long len = n;
int reduced_len = 0;
// 1st case they both are null
if (( len==0)&&( this->smival.value.oid.len==0))
return 0; // equal
// verify that n is valid, must be >= 0
if ( len <=0)
return 1; // ! equal
// only compare for the minimal length
if (len > this->smival.value.oid.len) {
len = this->smival.value.oid.len;
reduced_len = 1;
}
if (len > o.smival.value.oid.len) {
len = o.smival.value.oid.len;
reduced_len = 1;
}
z = 0;
while(z < len) {
if ( this->smival.value.oid.ptr[z] < o.smival.value.oid.ptr[z])
return -1; // less than
if ( this->smival.value.oid.ptr[z] > o.smival.value.oid.ptr[z])
return 1; // greater than
z++;
}
// if we truncated the len then these may not be equal
if (reduced_len) {
if (this->smival.value.oid.len < o.smival.value.oid.len)
return -1;
if (this->smival.value.oid.len > o.smival.value.oid.len)
return 1;
}
return 0; // equal
}
//===============[Oid::left_comparison( n, Oid) ]=================================
// compare the n rightmost bytes (right-to-left)
// returns 0, equal
// returns -1, <
// returns 1 , >
int Oid::right_comparison( const unsigned long n, const Oid &o) const
{
// oid to compare must have at least the same number
// of sub-ids to comparison else the argument Oid is
// less than THIS
if ( o.length() < n)
return -1;
// also can't compare argument oid for sub-ids which
// THIS does not have
if ( this->length() < n)
return -1;
int start = (int) this->length();
int end = (int) start - (int) n;
for ( int z=start;z< end;z--)
{
if ( o.smival.value.oid.ptr[z] < this->smival.value.oid.ptr[z])
return -1;
if ( o.smival.value.oid.ptr[z] > this->smival.value.oid.ptr[z])
return 1;
}
return 0; // they are equal
}
//================[ Oid::valid() ]========================================
// is the Oid object valid
// returns validity
int Oid::valid() const
{
return ( smival.value.oid.ptr ? 1 : 0 );
}
//================[Oid::OidToStr ]=========================================
// convert an oid to a string
int Oid::OidToStr( SmiLPOID srcOid, unsigned long size,
char *string, size_t& how_many_bytes)
{
unsigned long index = 0;
unsigned totLen = 0;
char szNumber[SNMPBUFFSIZE];
// init the string
string[totLen] = 0;
// verify there is something to copy
if (srcOid->len == 0)
return -1;
// loop through and build up a string
for (index=0; index < srcOid->len; index++) {
// convert data element to a string
if (ACE_OS::sprintf( szNumber,"%lu", srcOid->ptr[index]) == -1)
return -1;
// verify len is not over
if (totLen + ACE_OS::strlen(szNumber) + 1 >= size)
return -2;
// if not at end, pad with a dot
if (totLen!=0)
string[totLen++] = '.';
// copy the string token into the main string
ACE_OS::strcpy(string + totLen, szNumber);
// adjust the total len
totLen += ACE_OS::strlen(szNumber);
}
how_many_bytes = totLen + 1;
return 0;
}
//================[ general Value = operator ]========================
SnmpSyntax& Oid::operator=( SnmpSyntax &val)
{
// protect against assignment from self
if ( this == &val )
return *this;
// blow away old value
smival.value.oid.len = 0;
if (smival.value.oid.ptr) {
set_invalid();
}
// assign new value
if (val.valid()) {
switch (val.get_syntax()) {
case sNMP_SYNTAX_OID:
set_data( ((Oid &)val).smival.value.oid.ptr,
(unsigned int)((Oid &)val).smival.value.oid.len);
break;
}
}
return *this;
}
//================[ [] operator ]=====================================
unsigned long& Oid::operator[](size_t position)
{
return smival.value.oid.ptr[position];
}
//================[ clone ]===========================================
SnmpSyntax *Oid::clone() const
{
return (SnmpSyntax *) new Oid(*this);
}
| [
"flyer_son@126.com"
] | flyer_son@126.com |
ce3d89925dfbc340b2ceed86c6459b05d4c28928 | 1066b428e123f4212431cd124bc5b71b60a3bf90 | /src/util/xmlsettings/xmlsettings.cpp | 4916d9c044a083fd90c0b9301eb94b78e68d4f6d | [] | no_license | amigomcu/bterm | 54523c9ceb15538cb8d93ec8161deb8e81db609c | a92bd0dcd31e82beda0fbe8b205ddfd5927eb502 | refs/heads/master | 2021-06-11T16:18:06.508638 | 2016-12-25T11:39:48 | 2016-12-25T11:39:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,818 | cpp | /******************************************************************************
* Description: See class declaration in header file
*
******************************************************************************/
/******************************************************************************************
* INCLUDED FILES
*****************************************************************************************/
#include "xmlsettings.h"
#include <QDomDocument>
#include <QDebug>
#include <QDataStream>
#include <QRect>
#include <QSize>
#include <QByteArray>
#include <QStringList>
/******************************************************************************************
* PRIVATE DATA
*****************************************************************************************/
const QString XmlSettings::XML_TAG_NAME__ROOT = "root";
const QString XmlSettings::XML_ATTR_NAME__ITEM__VALUE = "value";
/******************************************************************************************
* DEFINITIONS
*****************************************************************************************/
/******************************************************************************************
* CONSTRUCTOR, DESTRUCTOR
*****************************************************************************************/
/* public */
XmlSettings::XmlSettings( QString fname )
{
if ( fname.isEmpty() ){
fname = "noname.xml";
}
static const QSettings::Format XmlFormat = QSettings::registerFormat("xml", readXmlFile, writeXmlFile);
p_settings = std::shared_ptr<QSettings>(new QSettings( fname, XmlFormat ));
}
/******************************************************************************************
* STATIC METHODS
*****************************************************************************************/
/* private */
bool XmlSettings::readXmlFile(QIODevice &device, QSettings::SettingsMap &map)
{
QDomDocument doc("");
if ( !doc.setContent( &device ) ) return false;
//-- get the root element of the document (which is XML_TAG_NAME__ROOT actually)
QDomElement root = doc.documentElement();
//-- handle all the root children
{
QDomNodeList children = root.childNodes();
for (int i = 0; i < children.count(); ++i){
QDomElement currentChild = children.item(i).toElement();
processReadKey("", map, currentChild);
}
}
return true;
}
bool XmlSettings::writeXmlFile(QIODevice &device, const QSettings::SettingsMap &map)
{
QDomDocument doc("");
QDomElement root = doc.createElement(XML_TAG_NAME__ROOT);
doc.appendChild(root);
QMapIterator<QString, QVariant> i(map);
while ( i.hasNext() )
{
i.next();
QString sKey = i.key();
QVariant value = i.value();
processWriteKey( doc, root, sKey, i.value() );
};
QDomNode xmlNode = doc.createProcessingInstruction("xml","version=\"1.0\" encoding=\"UTF-8\"");
doc.insertBefore(xmlNode, doc.firstChild());
QTextStream out( &device );
doc.save(out, 3);
return true;
}
void XmlSettings::processWriteKey( QDomDocument& doc, QDomElement& domElement, QString key, const QVariant& value )
{
int slashPos = key.indexOf( '/' );
if (slashPos < 0){
//-- given key is a param (not folder)
QDomElement item_element = doc.createElement(key);
item_element.setAttribute(XML_ATTR_NAME__ITEM__VALUE, XmlSettings::variantToString(value));
domElement.appendChild(item_element);
} else {
//-- given key is a folder
//-- get the name of the group for appropriate xml node
QString groupName = key.left( slashPos );
//-- get/create node for the key
QDomElement groupElement;
QDomNode foundGroupNode = domElement.namedItem( groupName );
if ( foundGroupNode.isNull() ){
groupElement = doc.createElement( groupName );
domElement.appendChild( groupElement );
} else {
groupElement = foundGroupNode.toElement();
}
//-- create truncated part of the key
key = key.right( key.size() - slashPos - 1 );
//-- continue handling (creation/looking_for groups),
// until it is eventually succeed
processWriteKey( doc, groupElement, key, value );
}
}
void XmlSettings::processReadKey( QString parentKey, QSettings::SettingsMap &map, QDomElement& domElement )
{
QString currentKey = parentKey + domElement.tagName();
QString currentKeyForChildren = currentKey + "/";
QDomNamedNodeMap namedNodeMap = domElement.attributes();
QDomNode value_node = namedNodeMap.namedItem(XML_ATTR_NAME__ITEM__VALUE);
if (!value_node.isNull()){
//-- value is set for this item. Let's add it to the resulting map.
map.insert(currentKey, stringToVariant(value_node.nodeValue()));
}
//-- handle all the children
{
QDomNodeList children = domElement.childNodes();
for (int i = 0; i < children.count(); ++i){
QDomElement currentChild = children.item(i).toElement();
processReadKey(currentKeyForChildren, map, currentChild);
}
}
}
/**
* This function is copied from Qt src/corelib/io/qsettings.cpp
*/
QString XmlSettings::variantToString(const QVariant &v)
{
QString result;
switch (v.type()) {
case QVariant::Invalid:
result = QLatin1String("@Invalid()");
break;
case QVariant::ByteArray: {
QByteArray a = v.toByteArray();
result = QLatin1String("@ByteArray(");
result += QString::fromLatin1(a.constData(), a.size());
result += QLatin1Char(')');
break;
}
case QVariant::String:
case QVariant::LongLong:
case QVariant::ULongLong:
case QVariant::Int:
case QVariant::UInt:
case QVariant::Bool:
case QVariant::Double:
case QVariant::KeySequence: {
result = v.toString();
if (result.startsWith(QLatin1Char('@')))
result.prepend(QLatin1Char('@'));
break;
}
case QVariant::Rect: {
QRect r = qvariant_cast<QRect>(v);
result += QLatin1String("@Rect(");
result += QString::number(r.x());
result += QLatin1Char(' ');
result += QString::number(r.y());
result += QLatin1Char(' ');
result += QString::number(r.width());
result += QLatin1Char(' ');
result += QString::number(r.height());
result += QLatin1Char(')');
break;
}
case QVariant::Size: {
QSize s = qvariant_cast<QSize>(v);
result += QLatin1String("@Size(");
result += QString::number(s.width());
result += QLatin1Char(' ');
result += QString::number(s.height());
result += QLatin1Char(')');
break;
}
case QVariant::Point: {
QPoint p = qvariant_cast<QPoint>(v);
result += QLatin1String("@Point(");
result += QString::number(p.x());
result += QLatin1Char(' ');
result += QString::number(p.y());
result += QLatin1Char(')');
break;
}
default: {
QByteArray a;
{
QDataStream s(&a, QIODevice::WriteOnly);
s.setVersion(QDataStream::Qt_4_0);
s << v;
}
result = QLatin1String("@Variant(");
result += QString::fromLatin1(a.constData(), a.size());
result += QLatin1Char(')');
break;
}
}
return result;
}
/**
* This function is copied from Qt src/corelib/io/qsettings.cpp
*/
QVariant XmlSettings::stringToVariant(const QString &s)
{
if (s.startsWith(QLatin1Char('@'))) {
if (s.endsWith(QLatin1Char(')'))) {
if (s.startsWith(QLatin1String("@ByteArray("))) {
return QVariant(s.toLatin1().mid(11, s.size() - 12));
} else if (s.startsWith(QLatin1String("@Variant("))) {
QByteArray a(s.toLatin1().mid(9));
QDataStream stream(&a, QIODevice::ReadOnly);
stream.setVersion(QDataStream::Qt_4_0);
QVariant result;
stream >> result;
return result;
} else if (s.startsWith(QLatin1String("@Rect("))) {
QStringList args = XmlSettings::splitArgs(s, 5);
if (args.size() == 4)
return QVariant(QRect(args[0].toInt(), args[1].toInt(), args[2].toInt(), args[3].toInt()));
} else if (s.startsWith(QLatin1String("@Size("))) {
QStringList args = XmlSettings::splitArgs(s, 5);
if (args.size() == 2)
return QVariant(QSize(args[0].toInt(), args[1].toInt()));
} else if (s.startsWith(QLatin1String("@Point("))) {
QStringList args = XmlSettings::splitArgs(s, 6);
if (args.size() == 2)
return QVariant(QPoint(args[0].toInt(), args[1].toInt()));
} else if (s == QLatin1String("@Invalid()")) {
return QVariant();
}
}
if (s.startsWith(QLatin1String("@@")))
return QVariant(s.mid(1));
}
return QVariant(s);
}
/**
* This function is copied from Qt src/corelib/io/qsettings.cpp
*/
QStringList XmlSettings::splitArgs(const QString &s, int idx)
{
int l = s.length();
Q_ASSERT(l > 0);
Q_ASSERT(s.at(idx) == QLatin1Char('('));
Q_ASSERT(s.at(l - 1) == QLatin1Char(')'));
QStringList result;
QString item;
for (++idx; idx < l; ++idx) {
QChar c = s.at(idx);
if (c == QLatin1Char(')')) {
Q_ASSERT(idx == l - 1);
result.append(item);
} else if (c == QLatin1Char(' ')) {
result.append(item);
item.clear();
} else {
item.append(c);
}
}
return result;
}
/* protected */
/* public */
/******************************************************************************************
* METHODS
*****************************************************************************************/
/* private */
/* protected */
/* public */
QVariant XmlSettings::value( const QString & key, const QVariant & defaultValue )
{
if ( !settings().contains( key ) ){
settings().setValue( key, defaultValue );
}
return settings().value( key );
}
void XmlSettings::setValue ( const QString & key, const QVariant & value )
{
settings().setValue( key, value );
}
| [
"dimon.frank@gmail.com"
] | dimon.frank@gmail.com |
2aa6ef371aa6cf24afd6510cb495a41fb2e377fc | 62d4601d67c3f86287f107843d800e1c4dd09c9c | /code/main.cpp | 85b6eb8d9b74784c7661f99194469a1327051872 | [] | no_license | JorgeBarcena3/SDL2-Base-project | c7549743f8559d753cdecb1b41c5f083655be1bf | 616b8bb6e90049f3d8e74ce58991443a863087f0 | refs/heads/master | 2020-09-08T22:57:53.627280 | 2020-03-25T02:44:24 | 2020-03-25T02:44:24 | 221,268,448 | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 2,264 | cpp | // File: main.cpp
// Description : Proyecto base con la libreria de SDL2
// Author: Jorge Bárcena Lumbreras
// © Copyright (C) 2019 Jorge Bárcena Lumbreras
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//
#include <SDL.h>
#include <SDL_main.h>
extern "C"
int main(int numer_of_arguments, char * arguments[])
{
SDL_Window* window; // Declare a pointer
SDL_Init(SDL_INIT_VIDEO); // Initialize SDL2
// Create an application window with the following settings:
window = SDL_CreateWindow(
"SDL EXAMPLE WINDOW", // window title
SDL_WINDOWPOS_UNDEFINED, // initial x position
SDL_WINDOWPOS_UNDEFINED, // initial y position
640, // width, in pixels
480, // height, in pixels
SDL_WINDOW_OPENGL // flags - see below
);
// Check that the window was successfully created
if (window == NULL) {
// In the case that the window could not be made...
return 1;
}
// The window is open: could enter program loop here (see SDL_PollEvent())
//Main loop flag
bool quit = false;
//Event handler
SDL_Event e;
//While application is running
while (!quit)
{
//Handle events on queue
while (SDL_PollEvent(&e) != 0)
{
//User requests quit
if (e.type == SDL_QUIT)
{
quit = true;
}
}
}
// Close and destroy the window
SDL_DestroyWindow(window);
// Clean up
SDL_Quit();
return 0;
} | [
"j.barcenalumbreras@gmail.com"
] | j.barcenalumbreras@gmail.com |
0bfb89a556d1f3e507fe2a17f7604f32388a33b9 | 75d568beed72fa3d705bafd158c1b95cc219f675 | /node.h | 515b71c245cc4227460dc05de70cb70595d8cbe9 | [] | no_license | MilenaFilippova/Haffman_cod | 245bddfd4be09e4a37e7b48a25467d04b9ae34f0 | 1693b71671e9538bd9d34c840d009c609aa888f5 | refs/heads/master | 2020-06-04T13:22:16.156713 | 2019-06-15T05:30:15 | 2019-06-15T05:30:15 | 192,039,404 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 542 | h | #ifndef NODE_H_INCLUDED
#define NODE_H_INCLUDED
#include <map>
#include <vector>
#include <iostream>
#include "sort.h"
#include "coder.h"
#include "decoder.h"
using namespace std;
class Node
{
private:
Node* L;
Node* R;
public:
Node *left;
Node *right;
int w;//вес узла
char symbol;
//конструктор по умолчанию
Node()
{
left = right = NULL;
w=0;//вес узла
symbol=0;
}
Node(Node* L,Node* R)
{
left=L;
right=R;
w=L->w+R->w;
symbol=0;
}
};
#endif
| [
"noreply@github.com"
] | MilenaFilippova.noreply@github.com |
aa9edb21b8037e19d421980cc5b8f0f5606f16af | 787bde65fe076cca1f985390f3d4e87ddf58964f | /Batch Runs/7 BR/4.00/MyDirection.cpp | cc0a0df15f8f88844a0f8ccfa4e1cba8be9a56ae | [] | no_license | VajiraK/Marc | 8630b1c4f579bccb088a2e3a1e79f2b56e886bdb | 33d6ac18c0c9a85feb3d377b12b2012d26979c51 | refs/heads/main | 2023-01-12T17:17:13.029472 | 2020-11-15T14:49:24 | 2020-11-15T14:49:24 | 313,052,531 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,892 | cpp | // MyDirection.cpp: implementation of the CMyDirection class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "MyDirection.h"
CMyDirection::~CMyDirection(){}
//----------------------------------------------------------------------------------------
CMyDirection::CMyDirection()
{
m_facing = FACE_DOWN;
}
//----------------------------------------------------------------------------------------
void CMyDirection::SetFacing(Angle a)
{
switch (a)
{
case DEGREES_90:
switch (m_facing)
{
case FACE_UP:
m_facing = FACE_RIGHT;
break;
case FACE_DOWN:
m_facing = FACE_LEFT;
break;
case FACE_LEFT:
m_facing = FACE_UP;
break;
case FACE_RIGHT:
m_facing = FACE_DOWN;
break;
}
break;
case DEGREES_180:
switch (m_facing)
{
case FACE_UP:
m_facing = FACE_DOWN;
break;
case FACE_DOWN:
m_facing = FACE_UP;
break;
case FACE_LEFT:
m_facing = FACE_RIGHT;
break;
case FACE_RIGHT:
m_facing = FACE_LEFT;
break;
}
break;
case DEGREES_MINUS_90:
switch (m_facing)
{
case FACE_UP:
m_facing = FACE_LEFT;
break;
case FACE_DOWN:
m_facing = FACE_RIGHT;
break;
case FACE_LEFT:
m_facing = FACE_DOWN;
break;
case FACE_RIGHT:
m_facing = FACE_UP;
break;
}
break;
}
}
//----------------------------------------------------------------------------------------
BYTE CMyDirection::GetNextDirection(BYTE d)
{
switch (d)
{
case FACE_DOWN:
return FACE_LEFT;
break;
case FACE_LEFT:
return FACE_UP;
break;
case FACE_RIGHT:
return FACE_DOWN;
break;
case FACE_UP:
return FACE_RIGHT;
break;
}
return 0;
}
//----------------------------------------------------------------------------------------
void CMyDirection::SetDirection(CRobot &robot,BYTE d)
{
switch (d)
{
case FACE_UP:
switch (m_facing)
{
case FACE_DOWN:
DoTurn(robot,DEGREES_180);
break;
case FACE_LEFT:
DoTurn(robot,DEGREES_90);
break;
case FACE_RIGHT:
DoTurn(robot,DEGREES_MINUS_90);
break;
}
m_facing = FACE_UP;
break;
case FACE_DOWN:
switch (m_facing)
{
case FACE_UP:
DoTurn(robot,DEGREES_180);
break;
case FACE_LEFT:
DoTurn(robot,DEGREES_MINUS_90);
break;
case FACE_RIGHT:
DoTurn(robot,DEGREES_90);
break;
}
m_facing = FACE_DOWN;
break;
case FACE_LEFT:
switch (m_facing)
{
case FACE_UP:
DoTurn(robot,DEGREES_MINUS_90);
break;
case FACE_DOWN:
DoTurn(robot,DEGREES_90);
break;
case FACE_RIGHT:
DoTurn(robot,DEGREES_180);
break;
}
m_facing = FACE_LEFT;
break;
case FACE_RIGHT:
switch (m_facing)
{
case FACE_UP:
DoTurn(robot,DEGREES_90);
break;
case FACE_DOWN:
DoTurn(robot,DEGREES_MINUS_90);
break;
case FACE_LEFT:
DoTurn(robot,DEGREES_180);
break;
}
m_facing = FACE_RIGHT;
break;
}
} | [
"vajira.kulatunga@pearson.com"
] | vajira.kulatunga@pearson.com |
5747e3682874ede22d23f926cccf91f574e165e5 | 493ac26ce835200f4844e78d8319156eae5b21f4 | /CHT_heat_transfer/constant/solid_15/polyMesh/faceZones | 8b03d9dfd282d08ea694fd5d235ee2a2d3c1dd21 | [] | no_license | mohan-padmanabha/worm_project | 46f65090b06a2659a49b77cbde3844410c978954 | 7a39f9384034e381d5f71191122457a740de3ff0 | refs/heads/master | 2022-12-14T14:41:21.237400 | 2020-08-21T13:33:10 | 2020-08-21T13:33:10 | 289,277,792 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 885 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: v1912 |
| \\ / A nd | Website: www.openfoam.com |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class regIOobject;
location "constant/solid_15/polyMesh";
object faceZones;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
0()
// ************************************************************************* //
| [
"mohan.2611@gmail.com"
] | mohan.2611@gmail.com | |
f48d357a3cc2fb4b3aefb77ff07510353530a48b | 65e7602d4f2fd18a010ec82e05e35347de78fe54 | /sorceFiles/MyReservation.cpp | 96f501c9cdad39f4f8fa08f8f390caef7e0b6d12 | [] | no_license | noagol/AirlineDataManagement | edf6986786d668bf3c1108978b4c3a02e0bda045 | 44dc8b12937a58212acda5245b3b73353fc05fe4 | refs/heads/master | 2020-05-21T21:16:24.632258 | 2019-05-11T15:34:49 | 2019-05-11T15:34:49 | 186,150,285 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,762 | cpp | #include "MyReservation.h"
/**
* Constractor
* @param customerId
* @param flihgtId
* @param cls
* @param baggage
*/
MyReservation::MyReservation(Customer *customerId, Flight *flihgtId, Classes cls, int baggage) :
customer(customerId), flight(flihgtId), classes(cls), maxBaggage(baggage),
reservationId() {}
/**
* Constractor
* @param res
* @param customer1
* @param flight1
*/
MyReservation::MyReservation(vector<string> *res, Customer *customer1, Flight *flight1) :
reservationId(res->at(0)),
classes(static_cast<Classes >(stoi(res->at(3)))),
maxBaggage(stoi(res->at(4))), flight(flight1), customer(customer1) {}
/**
*
* @return the reservation customer
*/
Customer *MyReservation::getCustomer() {
return customer;
}
/**
*
* @return the flight
*/
Flight *MyReservation::getFlight() {
return flight;
}
/**
*
* @return the class
*/
Classes MyReservation::getClass() {
return classes;
}
/**
*
* @return max baggage
*/
int MyReservation::getMaxBaggage() {
return maxBaggage;
}
/**
*
* @return the reservation id
*/
string MyReservation::getID() {
return reservationId.getId();
}
/**
* the function write the format of the print
* @param stream to write
* @param reservation
* @return the stream
*/
ostream &operator<<(ostream &stream, Reservation &reservation) {
string sign = ",";
stream << reservation.getID() << sign << reservation.getCustomer()->getID()
<< sign << reservation.getFlight()->getID() << sign <<
reservation.getClass() << sign << reservation.getMaxBaggage()
<< endl;
return stream;
}
MyReservation::~MyReservation() {}
| [
"noreply@github.com"
] | noagol.noreply@github.com |
fb625acb879fed0a0fe959409853a58e2e7101fb | 3c311327423d13735edc298230d3c36d2691f5c7 | /tensorflow/lite/tools/optimize/operator_property.cc | 01a10a575671f736e9a0dffb9585faffb6f3d543 | [
"Apache-2.0"
] | permissive | drewszurko/tensorflow | 6075aafff00893837da583ccc13fb399a6e40bcd | f2a9a2cdd87673182e94b3c25fcfc210315d014b | refs/heads/master | 2020-04-25T00:07:56.946637 | 2019-04-18T18:51:56 | 2019-04-18T18:51:56 | 172,368,205 | 0 | 0 | Apache-2.0 | 2019-04-18T18:44:45 | 2019-02-24T17:33:14 | C++ | UTF-8 | C++ | false | false | 5,682 | cc | /* Copyright 2019 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 "tensorflow/lite/tools/optimize/operator_property.h"
namespace tflite {
namespace optimize {
namespace operator_property {
TfLiteStatus GetOperatorProperty(const BuiltinOperator& op,
OperatorProperty* property) {
if (op == BuiltinOperator_ADD || op == BuiltinOperator_MUL) {
property->per_axis = false;
property->per_axis_index = 0;
property->arbitrary_inputs = false;
property->input_indexes = {0, 1};
property->output_indexes = {0};
property->biases = {};
property->restrict_same_input_output_scale = false;
property->restriction_on_output = false;
property->restricted_value_on_output = {};
return kTfLiteOk;
}
if (op == BuiltinOperator_AVERAGE_POOL_2D ||
op == BuiltinOperator_MAX_POOL_2D || op == BuiltinOperator_SQUEEZE) {
property->per_axis = false;
property->per_axis_index = 0;
property->arbitrary_inputs = false;
property->input_indexes = {0};
property->output_indexes = {0};
property->biases = {};
property->restrict_same_input_output_scale = true;
property->restriction_on_output = false;
property->restricted_value_on_output = {};
return kTfLiteOk;
}
if (op == BuiltinOperator_CONCATENATION) {
property->per_axis = false;
property->per_axis_index = 0;
property->arbitrary_inputs = true;
property->input_indexes = {};
property->output_indexes = {0};
property->biases = {};
property->restrict_same_input_output_scale = true;
property->restriction_on_output = false;
property->restricted_value_on_output = {};
return kTfLiteOk;
}
if (op == BuiltinOperator_CONV_2D) {
property->per_axis = true;
property->per_axis_index = 0;
property->arbitrary_inputs = false;
property->input_indexes = {0, 1};
property->output_indexes = {0};
property->biases = {2};
property->restrict_same_input_output_scale = false;
property->restriction_on_output = false;
property->restricted_value_on_output = {};
return kTfLiteOk;
}
if (op == BuiltinOperator_DEPTHWISE_CONV_2D) {
property->per_axis = true;
property->per_axis_index = 3;
property->arbitrary_inputs = false;
property->input_indexes = {0, 1};
property->output_indexes = {0};
property->biases = {2};
property->restrict_same_input_output_scale = false;
property->restriction_on_output = false;
property->restricted_value_on_output = {};
return kTfLiteOk;
}
if (op == BuiltinOperator_FULLY_CONNECTED) {
property->per_axis = false;
property->per_axis_index = 0;
property->arbitrary_inputs = false;
property->input_indexes = {0, 1};
property->output_indexes = {0};
property->biases = {2};
property->restrict_same_input_output_scale = false;
property->restriction_on_output = false;
property->restricted_value_on_output = {};
return kTfLiteOk;
}
if (op == BuiltinOperator_MEAN || op == BuiltinOperator_PAD ||
op == BuiltinOperator_QUANTIZE || op == BuiltinOperator_RESHAPE) {
property->per_axis = false;
property->per_axis_index = 0;
property->arbitrary_inputs = false;
property->input_indexes = {0};
property->output_indexes = {0};
property->biases = {};
property->restrict_same_input_output_scale = false;
property->restriction_on_output = false;
property->restricted_value_on_output = {};
return kTfLiteOk;
}
if (op == BuiltinOperator_SOFTMAX) {
// Softmax requires output with 1/256 as scale and -128 as zero point.
property->per_axis = false;
property->per_axis_index = 0;
property->arbitrary_inputs = false;
property->input_indexes = {0};
property->output_indexes = {0};
property->biases = {};
property->restrict_same_input_output_scale = false;
property->restriction_on_output = true;
property->restricted_value_on_output = {1 / 256.0, -128};
return kTfLiteOk;
}
if (op == BuiltinOperator_TANH) {
// Tanh requires output with 1/128 as scale and 0 as zero point.
property->per_axis = false;
property->per_axis_index = 0;
property->arbitrary_inputs = false;
property->input_indexes = {0};
property->output_indexes = {0};
property->biases = {};
property->restrict_same_input_output_scale = false;
property->restriction_on_output = true;
property->restricted_value_on_output = {1 / 128.0, 0};
return kTfLiteOk;
}
if (op == BuiltinOperator_ARG_MAX) {
property->per_axis = false;
property->per_axis_index = 0;
property->arbitrary_inputs = false;
property->input_indexes = {0};
// ArgMax has no quantizable output, so there is nothing to do here.
property->output_indexes = {};
property->biases = {};
property->restrict_same_input_output_scale = false;
property->restriction_on_output = false;
property->restricted_value_on_output = {};
return kTfLiteOk;
}
return kTfLiteError;
}
} // namespace operator_property
} // namespace optimize
} // namespace tflite
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
fabb85fc1d7896ddecd72a73d69997a9de63a946 | 622974cd61d5a4c6cb90ce39775198989e0a2b4c | /cuda/io/include/pcl/cuda/io/predicate.h | 2d4d9ae11b9c4d551ec565852ecbed9f574053b5 | [
"BSD-3-Clause"
] | permissive | kalectro/pcl_groovy | bd996ad15a7f6581c79fedad94bc7aaddfbaea0a | 10b2f11a1d3b10b4ffdd575950f8c1977f92a83c | refs/heads/master | 2021-01-22T21:00:10.455119 | 2013-05-13T02:44:37 | 2013-05-13T02:44:37 | 8,296,825 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,013 | h | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id: predicate.h 6459 2012-07-18 07:50:37Z dpb $
*
*/
#ifndef PCL_CUDA_PREDICATE_H_
#define PCL_CUDA_PREDICATE_H_
//#if THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC
//#undef __MMX__
#include <pcl/cuda/point_cloud.h>
#include <pcl/cuda/point_types.h>
//#else
//#endif
namespace pcl
{
namespace cuda
{
template <class T>
struct isNotZero
{
__inline__ __host__ __device__ bool
operator()(T x) { return (x != 0); }
};
struct isInlier
{
__inline__ __host__ __device__ bool
operator()(int x) { return (x != -1); }
};
struct isNotInlier
{
__inline__ __host__ __device__ bool
operator()(int x) { return (x == -1); }
};
struct SetColor
{
SetColor (const OpenNIRGB& color) : color_(color) {}
__inline__ __host__ __device__ void
operator()(PointXYZRGB& point) { point.rgb.r = color_.r; point.rgb.g = color_.g; point.rgb.b = color_.b;}
OpenNIRGB color_;
};
struct ChangeColor
{
ChangeColor (const OpenNIRGB& color) : color_(color) {}
__inline__ __host__ __device__ PointXYZRGB&
operator()(PointXYZRGB& point)
{
point.rgb.r = color_.r; point.rgb.g = color_.g; point.rgb.b = color_.b;
return point;
}
OpenNIRGB color_;
};
} // namespace
} // namespace
#endif //#ifndef PCL_CUDA_PREDICATE_H_
| [
"jkammerl@rbh.willowgarage.com"
] | jkammerl@rbh.willowgarage.com |
c8a8311151ccfa752ff7fbfc0bab0768eeeb5c21 | 3ad968797a01a4e4b9a87e2200eeb3fb47bf269a | /MFC CodeGuru/splitter/SplitterTog_source/SplitFrame.h | bf10ac6006fbf65faed545935c9aaa9069ac9ad5 | [] | no_license | LittleDrogon/MFC-Examples | 403641a1ae9b90e67fe242da3af6d9285698f10b | 1d8b5d19033409cd89da3aba3ec1695802c89a7a | refs/heads/main | 2023-03-20T22:53:02.590825 | 2020-12-31T09:56:37 | 2020-12-31T09:56:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,133 | h | #if ! defined( __SPLITFRAME_H__ )
#define __SPLITFRAME_H__
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
/*
** Author: Guy Gascoigne - Piggford
** Internet: guy@wyrdrune.com
**
** You can use this source in any way you like as long as you don't try to sell it.
**
** Any attempt to sell this in source code form must have the permission
** of the original author. You can produce commercial executables with
** this source, but you may not sell it.
**
** Copyright, 1994-98 Guy Gascoigne - Piggford
**
*/
#include "TogSplitterWnd.h"
class CSplitFrame : public CMDIChildWnd
{
BOOL m_bInitialOrientation;
CSize m_splitSizes[2];
CTogSplitterWnd m_wndSplitter;
CRuntimeClass * m_pView1;
CRuntimeClass * m_pView2;
protected: // create from serialization / derivation only
CSplitFrame( CRuntimeClass * pView1, CRuntimeClass * pView2 );
DECLARE_DYNAMIC(CSplitFrame)
// Attributes
public:
BOOL BarIsHorizontal() const { return m_wndSplitter.BarIsHorizontal(); }
void SetInitialOrienation( BOOL bHoriz );
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CSplitFrame)
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CSplitFrame();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected: // control bar embedded members
void MakeSplitSizes( BOOL horizBar, CSize & sz1, CSize & sz2 );
// Generated message map functions
protected:
virtual BOOL OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext);
void viewSomeView( int iView );
CSize ReadCachedSize( BOOL horizBar );
void CacheSize();
//{{AFX_MSG(CSplitFrame)
afx_msg void OnToggleSplitter();
afx_msg void OnUpdateToggleSplitter(CCmdUI* pCmdUI);
afx_msg void OnViewBoth();
afx_msg void OnViewFirstView();
afx_msg void OnViewSecondView();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
#endif //__SPLITFRAME_H__
| [
"pkedpekr@gmail.com"
] | pkedpekr@gmail.com |
20f408772f0f1dc537584e1369149398a495ea95 | 4081245b8ed21b053664ebd66340db8d38ab8c4f | /BuildBSTDCB.cpp | 163729d9fa75a5a8c18481fbddc53627086eacff | [] | no_license | anandaditya444/LEETCODE | 5240f0adf1df6a87747e00842f87566b0df59f92 | 82e597c21efa965cfe9e75254011ce4f49c2de36 | refs/heads/master | 2020-05-07T15:48:19.081727 | 2019-08-25T16:03:57 | 2019-08-25T16:03:57 | 180,653,012 | 2 | 1 | null | 2019-10-05T13:45:29 | 2019-04-10T19:48:40 | C++ | UTF-8 | C++ | false | false | 955 | cpp | #include <bits/stdc++.h>
using namespace std;
#define int long long int
#define IOS ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define ff first
#define ss second
#define pb push_back
#define pf push_front
#define endl "\n"
const int N = 1e3+5;
int a[N];
int t,n;
struct node
{
int data;
struct node* left;
struct node* right;
};
node* constructBST(int start,int end)
{
if(start > end)
return NULL;
int mid = (start+end)/2;
node* root = new node;
root->data = a[mid];
root->left = constructBST(start,mid-1);
root->right = constructBST(mid+1,end);
return root;
}
void preorder(node* root)
{
if(root == NULL)
return;
cout<<root->data<<" ";
preorder(root->left);
preorder(root->right);
}
int32_t main()
{
IOS;
cin>>t;
while(t--)
{
cin>>n;
for(int i=0;i<n;i++)
cin>>a[i];
//node* root = new node;
int start = 0,end = n-1;
node* root = constructBST(start,end);
preorder(root);
}
return 0;
} | [
"anandaditya444@gmail.com"
] | anandaditya444@gmail.com |
07ee6988fb7b86e6fe9fb410facdd09df33dab39 | ab1712d65f8510a705a1f28064e4d3fc5a48cf64 | /SDK/SoT_WildRoseDefinition_classes.hpp | b8e743efd863e1aabd134859c109397f3b243e65 | [] | no_license | zk2013/SoT-SDK | 577f4e26ba969c3fa21a9191a210afc116a11dba | 04eb22c1c31aaa4d5cf822b0a816786c99e3ea2f | refs/heads/master | 2020-05-29T20:06:57.165354 | 2019-05-29T16:46:51 | 2019-05-29T16:46:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,063 | hpp | #pragma once
// Sea of Thieves (2.0) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "SoT_WildRoseDefinition_structs.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass WildRoseDefinition.WildRoseDefinition_C
// 0x0148 (0x0170 - 0x0028)
class UWildRoseDefinition_C : public UTaleQuestDefinition
{
public:
struct FDS_WildRoseDefinition Definition; // 0x0028(0x0110) (Edit, BlueprintVisible)
class UQuestBookPageBundle* InitialBundle; // 0x0138(0x0008) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UQuestBookPageBundle* FinalBundle; // 0x0140(0x0008) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UAISpawner* Spawner; // 0x0148(0x0008) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UQuestBookPageBundle* DeathNote; // 0x0150(0x0008) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
class UQuestBookPageBundle* OurMemories; // 0x0158(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
TArray<class UAISpawner*> RookeEncounterSpawners; // 0x0160(0x0010) (Edit, BlueprintVisible, ZeroConstructor)
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>(_xor_("BlueprintGeneratedClass WildRoseDefinition.WildRoseDefinition_C"));
return ptr;
}
void GetIslandForActor(TAssetPtr<class AActor> Actor, struct FName* Name);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"igromanru@yahoo.de"
] | igromanru@yahoo.de |
db0b032dced7dae81036ab31c0c51040887fb123 | c2621eab966ec23d2293d0fb8e00087d9b86003e | /components/cpp_utils/FreeRTOS.cpp | 7b2be5d024f1be673362fba77cf57e97bbafdcc0 | [] | no_license | NguyenPham0106/esp32-snippets-enchancements-test | e976042d0c41bbb21ba8d1b43d350d95a8043203 | 9f1715b01a7b7c30e3efce893fc1a380eb23dede | refs/heads/master | 2023-04-08T07:34:43.579773 | 2018-10-06T16:00:03 | 2018-10-06T16:00:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,531 | cpp | /*
* FreeRTOS.cpp
*
* Created on: Feb 24, 2017
* Author: kolban
*/
#include <freertos/FreeRTOS.h> // Include the base FreeRTOS definitions
#include <freertos/task.h> // Include the task definitions
#include <freertos/semphr.h> // Include the semaphore definitions
#include <string>
#include <sstream>
#include <iomanip>
#include "FreeRTOS.h"
#include <esp_log.h>
#include "sdkconfig.h"
static const char* LOG_TAG = "FreeRTOS";
/**
* Sleep for the specified number of milliseconds.
* @param[in] ms The period in milliseconds for which to sleep.
*/
void FreeRTOS::sleep(uint32_t ms) {
::vTaskDelay(ms/portTICK_PERIOD_MS);
} // sleep
/**
* Start a new task.
* @param[in] task The function pointer to the function to be run in the task.
* @param[in] taskName A string identifier for the task.
* @param[in] param An optional parameter to be passed to the started task.
* @param[in] stackSize An optional paremeter supplying the size of the stack in which to run the task.
*/
void FreeRTOS::startTask(void task(void*), std::string taskName, void *param, int stackSize) {
::xTaskCreate(task, taskName.data(), stackSize, param, 5, NULL);
} // startTask
/**
* Delete the task.
* @param[in] pTask An optional handle to the task to be deleted. If not supplied the calling task will be deleted.
*/
void FreeRTOS::deleteTask(TaskHandle_t pTask) {
::vTaskDelete(pTask);
} // deleteTask
/**
* Get the time in milliseconds since the %FreeRTOS scheduler started.
* @return The time in milliseconds since the %FreeRTOS scheduler started.
*/
uint32_t FreeRTOS::getTimeSinceStart() {
return (uint32_t)(xTaskGetTickCount()*portTICK_PERIOD_MS);
} // getTimeSinceStart
/*
* public:
Semaphore(std::string = "<Unknown>");
~Semaphore();
void give();
void take(std::string owner="<Unknown>");
void take(uint32_t timeoutMs, std::string owner="<Unknown>");
private:
SemaphoreHandle_t m_semaphore;
std::string m_name;
std::string m_owner;
};
*
*/
/**
* @brief Wait for a semaphore to be released by trying to take it and
* then releasing it again.
* @param [in] owner A debug tag.
* @return The value associated with the semaphore.
*/
uint32_t FreeRTOS::Semaphore::wait(std::string owner) {
ESP_LOGV(LOG_TAG, ">> wait: Semaphore waiting: %s for %s", toString().c_str(), owner.c_str());
bool rc = false;
if (m_usePthreads) {
pthread_mutex_lock(&m_pthread_mutex);
} else {
rc = take(portMAX_DELAY, owner);
}
m_owner = owner;
if (m_usePthreads) {
pthread_mutex_unlock(&m_pthread_mutex);
} else {
if (rc) xSemaphoreGive(m_semaphore);
}
ESP_LOGV(LOG_TAG, "<< wait: Semaphore released: %s", toString().c_str());
if(rc)
m_owner = std::string("<N/A>");
return m_value;
} // wait
FreeRTOS::Semaphore::Semaphore(std::string name) {
m_usePthreads = false; // Are we using pThreads or FreeRTOS?
if (m_usePthreads) {
pthread_mutex_init(&m_pthread_mutex, nullptr);
} else {
m_semaphore = xSemaphoreCreateMutex();
}
m_name = name;
m_owner = std::string("<N/A>");
m_value = 0;
}
FreeRTOS::Semaphore::~Semaphore() {
if (m_usePthreads) {
pthread_mutex_destroy(&m_pthread_mutex);
} else {
vSemaphoreDelete(m_semaphore);
}
}
/**
* @brief Give a semaphore.
* The Semaphore is given.
*/
void FreeRTOS::Semaphore::give() {
ESP_LOGV(LOG_TAG, "Semaphore giving: %s", toString().c_str());
if (m_usePthreads) {
pthread_mutex_unlock(&m_pthread_mutex);
} else {
xSemaphoreGive(m_semaphore);
}
// #ifdef ARDUINO_ARCH_ESP32
// FreeRTOS::sleep(10);
// #endif
m_owner = std::string("<N/A>");
} // Semaphore::give
/**
* @brief Give a semaphore.
* The Semaphore is given with an associated value.
* @param [in] value The value to associate with the semaphore.
*/
void FreeRTOS::Semaphore::give(uint32_t value) {
m_value = value;
give();
} // give
/**
* @brief Give a semaphore from an ISR.
*/
void FreeRTOS::Semaphore::giveFromISR() {
BaseType_t higherPriorityTaskWoken;
if (m_usePthreads) {
assert(false);
} else {
xSemaphoreGiveFromISR(m_semaphore, &higherPriorityTaskWoken);
}
} // giveFromISR
/**
* @brief Take a semaphore.
* Take a semaphore and wait indefinitely.
* @param [in] owner The new owner (for debugging)
* @return True if we took the semaphore.
*/
bool FreeRTOS::Semaphore::take(std::string owner)
{
ESP_LOGV(LOG_TAG, "Semaphore taking: %s for %s", toString().c_str(), owner.c_str());
bool rc = false;
if (m_usePthreads) {
pthread_mutex_lock(&m_pthread_mutex);
} else {
rc = ::xSemaphoreTake(m_semaphore, portMAX_DELAY);
}
m_owner = owner;
if (rc) {
ESP_LOGV(LOG_TAG, "Semaphore taken: %s", toString().c_str());
} else {
ESP_LOGE(LOG_TAG, "Semaphore NOT taken: %s", toString().c_str());
}
return rc;
} // Semaphore::take
/**
* @brief Take a semaphore.
* Take a semaphore but return if we haven't obtained it in the given period of milliseconds.
* @param [in] timeoutMs Timeout in milliseconds.
* @param [in] owner The new owner (for debugging)
* @return True if we took the semaphore.
*/
bool FreeRTOS::Semaphore::take(uint32_t timeoutMs, std::string owner) {
ESP_LOGV(LOG_TAG, "Semaphore taking: %s for %s", toString().c_str(), owner.c_str());
bool rc = false;
if (m_usePthreads) {
assert(false); // We apparently don't have a timed wait for pthreads.
} else {
rc = ::xSemaphoreTake(m_semaphore, timeoutMs/portTICK_PERIOD_MS);
}
m_owner = owner;
if (rc) {
ESP_LOGV(LOG_TAG, "Semaphore taken: %s", toString().c_str());
} else {
ESP_LOGE(LOG_TAG, "Semaphore NOT taken: %s", toString().c_str());
}
return rc;
} // Semaphore::take
/**
* @brief Create a string representation of the semaphore.
* @return A string representation of the semaphore.
*/
std::string FreeRTOS::Semaphore::toString() {
std::stringstream stringStream;
stringStream << "name: "<< m_name << " (0x" << std::hex << std::setfill('0') << (uint32_t)m_semaphore << "), owner: " << m_owner;
return stringStream.str();
} // toString
/**
* @brief Set the name of the semaphore.
* @param [in] name The name of the semaphore.
*/
void FreeRTOS::Semaphore::setName(std::string name) {
m_name = name;
} // setName
/**
* @brief Create a ring buffer.
* @param [in] length The amount of storage to allocate for the ring buffer.
* @param [in] type The type of buffer. One of RINGBUF_TYPE_NOSPLIT, RINGBUF_TYPE_ALLOWSPLIT, RINGBUF_TYPE_BYTEBUF.
*/
Ringbuffer::Ringbuffer(size_t length, ringbuf_type_t type) {
m_handle = ::xRingbufferCreate(length, type);
} // Ringbuffer
Ringbuffer::~Ringbuffer() {
::vRingbufferDelete(m_handle);
} // ~Ringbuffer
/**
* @brief Receive data from the buffer.
* @param [out] size On return, the size of data returned.
* @param [in] wait How long to wait.
* @return A pointer to the storage retrieved.
*/
void* Ringbuffer::receive(size_t* size, TickType_t wait) {
return ::xRingbufferReceive(m_handle, size, wait);
} // receive
/**
* @brief Return an item.
* @param [in] item The item to be returned/released.
*/
void Ringbuffer::returnItem(void* item) {
::vRingbufferReturnItem(m_handle, item);
} // returnItem
/**
* @brief Send data to the buffer.
* @param [in] data The data to place into the buffer.
* @param [in] length The length of data to place into the buffer.
* @param [in] wait How long to wait before giving up. The default is to wait indefinitely.
* @return
*/
uint32_t Ringbuffer::send(void* data, size_t length, TickType_t wait) {
return ::xRingbufferSend(m_handle, data, length, wait);
} // send
| [
"imperiaonline4@gmail.com"
] | imperiaonline4@gmail.com |
f346f64cbeadb4c7a9b4e5913dcb82b9d923e0f7 | 633ae1a2eb5151143dbe3744eb7fe70ba1112812 | /Chip-8/src/main.cpp | ad419783433c3b16aedbb8d8e16c07d8ad8e98f0 | [
"MIT"
] | permissive | MehTheHedgehog/Chiper8 | ff6118892082e91f47ef3155d93d36be215c4619 | 65cd16684e3edadb78dc27a32fa0dbe34cb1d46a | refs/heads/master | 2021-01-01T16:31:39.488061 | 2017-07-21T22:21:38 | 2017-07-21T22:21:38 | 97,849,987 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,433 | cpp | #include <string>
#include <tclap/CmdLine.h>
#include "SubSystem\Emulator.hpp"
int main(int argc, char** argv)
{
bool isDebug = false;
std::string strFileName;
//Parsing Command line arguments
try {
TCLAP::CmdLine cmd("Chip-8 emulator", ' ', "0.0.1a");
TCLAP::UnlabeledValueArg<std::string> fileArg("file", "Patch to executable Chip-8 file", true, "", "path_to_file", cmd);
TCLAP::SwitchArg dbgArg("d", "debug", "Display debug information about running program", cmd);
cmd.parse(argc, argv);
strFileName = fileArg.getValue();
isDebug = dbgArg.getValue();
}
catch (TCLAP::ArgException &e) {
std::cerr << "Exception while parsing args: " << e.error() << " for arg " << e.argId() << std::endl;
return 1;
}
FILE* progFile;
fopen_s(&progFile, strFileName.c_str(), "rb");
if (progFile == NULL) {
std::cerr << "Cannot open file!" << std::endl;
return 2;
}
fseek(progFile, 0, SEEK_END);
if (ftell(progFile) > 0xFFF - 0x200)
return 3;
unsigned char* buffer;
unsigned __int8 byteSize = ftell(progFile);
rewind(progFile);
// allocate memory to contain the whole file:
buffer = (unsigned char*)malloc(sizeof(char)*byteSize);
if (buffer == NULL) { fputs("Memory error", stderr); exit(2); }
// copy the file into the buffer:
fread(buffer, 1, byteSize, progFile);
Emulator Chip8Emu;
Chip8Emu.setRAM(0x200, buffer, byteSize);
Chip8Emu.run();
// terminate
fclose(progFile);
free(buffer);
} | [
"mehthehedgehog@gmail.com"
] | mehthehedgehog@gmail.com |
f7065d246c1eff486d04c4d4d275e7016919ddc6 | 9247d93d625768940e0a28b418879014286861e5 | /algorithm_winterstudy/27_백준10844_(틀림)쉬운계단수_120119.cpp | f1a324db076865c7d0ca80cf7aac099c7d6fab7c | [] | no_license | inhoinno/BOSSMONSTER | 5cf15fe2b0943ff709de1b42c657c5cebcff7ffb | 699db45efe1c75ba1e448b3e774bd5092018b2fc | refs/heads/master | 2020-12-31T23:36:49.368242 | 2020-02-24T05:23:12 | 2020-02-24T05:23:12 | 239,078,563 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 903 | cpp | #include <iostream>
#include <cstdio>
using namespace std;
int D_Stair(int n){
int d[101];
d[0] = 0;
d[1] = 9;
if(d[n]>0) return d[n];
else{
d[n] = D_Stair(n-1)*2 -1;
return d[n];
}
};
int main (){
int N;
scanf_s("%d", &N);
if(N>=1 && N<=100) printf("%d", D_Stair(N));
else printf("오류\n");
return 0;
} | [
"56788537+inhoinno@users.noreply.github.com"
] | 56788537+inhoinno@users.noreply.github.com |
9a87325c2c7c2703065440d75efc42e720bfeba2 | 4c0e956ba72bd9aeffae22ae4db32036a1c33a9e | /La_Library/demo43_41.cpp | 6349903686b079313e8d37254eeb2905812b4f85 | [] | no_license | dzylikecode/La_Library | 277650a3be19263acb9f5e83d86710498d5c884e | e46d126890bc1feb33ecac343588e096b478b525 | refs/heads/master | 2023-07-30T17:03:37.076898 | 2021-09-05T03:10:45 | 2021-09-05T03:10:45 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 9,360 | cpp |
/*
***************************************************************************************
* 程 序:
*
* 作 者: LaDzy
*
* 邮 箱: mathbewithcode@gmail.com
*
* 编译环境: Visual Studio 2019
*
* 创建时间: 2021/08/31 9:14:54
* 最后修改:
*
* 简 介:
*
***************************************************************************************
*/
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <conio.h>
#include <iostream>
#include "La_Windows.h"
#include "La_WinGDI.h"
#include "La_GameBox.h"
#include "La_Graphic.h"
#include "La_GraphicEx.h"
#include "La_Input.h"
#include "La_Audio.h"
#include "La_3D.h"
#include "La_Master.h"
using namespace std;
const int SCREEN_WIDTH = 800;
const int SCREEN_HEIGHT = 600;
FRAMECounter fpsSet;
GAMEBox gameBox;
using namespace AUDIO;
using namespace GDI;
using namespace GRAPHIC;
using namespace INPUT_;
KEYBOARD keyboard;
#define WINDOW_WIDTH SCREEN_WIDTH
#define WINDOW_HEIGHT SCREEN_HEIGHT
// defines for the game universe
#define UNIVERSE_RADIUS 4000
#define POINT_SIZE 200
#define NUM_POINTS_X (2*UNIVERSE_RADIUS/POINT_SIZE)
#define NUM_POINTS_Z (2*UNIVERSE_RADIUS/POINT_SIZE)
#define NUM_POINTS (NUM_POINTS_X*NUM_POINTS_Z)
// defines for objects
#define NUM_TOWERS 64 // 96
#define NUM_TANKS 32 // 24
#define TANK_SPEED 15
// initialize camera position and direction
VECTOR4D cam_pos = { 0,40,0 };
VECTOR4D cam_target = { 0,0,0 };
VECTOR4D cam_dir = { 0,0,0 };
// all your initialization code goes here...
VECTOR4D vscale = { 1.0,1.0,1.0 },
vpos = { 0,0,0 },
vrot = { 0,0,0 };
CAM4DV1 cam; // the single camera
OBJECT4DV1 obj_tower, // used to hold the master tower
obj_tank, // used to hold the master tank
obj_marker, // the ground marker
obj_player; // the player object
VECTOR4D towers[NUM_TOWERS],
tanks[NUM_TANKS];
RENDERLIST4DV1 rend_list; // the render list
void StartUp(void)
{
TSTRING path = TEXT("F:\\Git_WorkSpace\\La_Library\\La_Library\\Resource\\demo41\\");
// initialize the camera with 90 FOV, normalized coordinates
cam.set(
CAM_MODEL_EULER, // the euler model
cam_pos, // initial camera position
cam_dir, // initial camera angles
&cam_target, // no target
200.0, // near and far clipping planes
12000.0,
120.0, // field of view in degrees
WINDOW_WIDTH, // size of final screen viewport
WINDOW_HEIGHT);
LoadPLG(obj_tank, path + TEXT("tank3.plg"), vpos, VECTOR4D(0.75, 0.75, 0.75), vrot);
LoadPLG(obj_player, path + TEXT("tank2.plg"), vpos, VECTOR4D(0.75, 0.75, 0.75), vrot);
LoadPLG(obj_tower, path + TEXT("tower1.plg"), vpos, VECTOR4D(1.0, 2.0, 1.0), vrot);
LoadPLG(obj_marker, path + TEXT("marker1.plg"), vpos, VECTOR4D(3.0, 3.0, 3.0), vrot);
// position the tanks
for (int index = 0; index < NUM_TANKS; index++)
{
// randomly position the tanks
tanks[index].x = RAND_RANGE(-UNIVERSE_RADIUS, UNIVERSE_RADIUS);
tanks[index].y = 0; // obj_tank.max_radius;
tanks[index].z = RAND_RANGE(-UNIVERSE_RADIUS, UNIVERSE_RADIUS);
tanks[index].w = RAND_RANGE(0, 360);
}
// position the towers
for (int index = 0; index < NUM_TOWERS; index++)
{
// randomly position the tower
towers[index].x = RAND_RANGE(-UNIVERSE_RADIUS, UNIVERSE_RADIUS);
towers[index].y = 0; // obj_tower.max_radius;
towers[index].z = RAND_RANGE(-UNIVERSE_RADIUS, UNIVERSE_RADIUS);
}
keyboard.create();
fpsSet.set(30);
}
void GameBody(void)
{
if (KEY_DOWN(VK_ESCAPE))
gameBox.exitFromGameBody();
graphicOut.fillColor();
keyboard.read();
static MATRIX4X4 mrot; // general rotation matrix
// these are used to create a circling camera
static float view_angle = 0;
static float camera_distance = 6000;
static VECTOR4D pos = { 0,0,0 };
static float tank_speed;
static float turning = 0;
char work_string[256]; // temp string
// game logic here...
// draw the sky
DrawRectangle(0, 0, WINDOW_WIDTH - 1, WINDOW_HEIGHT / 2, RGB_DX(0, 140, 192));
// draw the ground
DrawRectangle(0, WINDOW_HEIGHT / 2, WINDOW_WIDTH - 1, WINDOW_HEIGHT - 1, RGB_DX(103, 62, 3));
// reset the render list
Reset(rend_list);
// allow user to move camera
// turbo
if (keyboard[DIK_SPACE]) tank_speed = 5 * TANK_SPEED;
else tank_speed = TANK_SPEED;
// forward/backward
if (keyboard[DIK_UP])
{
// move forward
cam.pos.x += tank_speed * SinFast(cam.dir.y);
cam.pos.z += tank_speed * CosFast(cam.dir.y);
}
if (keyboard[DIK_DOWN])
{
// move backward
cam.pos.x -= tank_speed * SinFast(cam.dir.y);
cam.pos.z -= tank_speed * CosFast(cam.dir.y);
}
// rotate
if (keyboard[DIK_RIGHT])
{
cam.dir.y += 3;
// add a little turn to object
if ((turning += 2) > 15)
turning = 15;
}
if (keyboard[DIK_LEFT])
{
cam.dir.y -= 3;
// add a little turn to object
if ((turning -= 2) < -15)
turning = -15;
}
else // center heading again
{
if (turning > 0)
turning -= 1;
else if (turning < 0)
turning += 1;
}
// generate camera matrix
BuildEuler(cam, CAM_ROT_SEQ_ZYX);
// insert the player into the world
// reset the object (this only matters for backface and object removal)
Reset(obj_player);
// set position of tank
obj_player.world_pos.x = cam.pos.x + 300 * SinFast(cam.dir.y);
obj_player.world_pos.y = cam.pos.y - 70;
obj_player.world_pos.z = cam.pos.z + 300 * CosFast(cam.dir.y);
// generate rotation matrix around y axis
BuildXYZRotation(0, cam.dir.y + turning, 0, mrot);
// rotate the local coords of the object
Transform(obj_player, mrot, TRANSFORM_LOCAL_TO_TRANS);
// perform world transform
ModelToWorld(obj_player, TRANSFORM_TRANS_ONLY);
// insert the object into render list
Insert2(rend_list, obj_player, 0, 0);
// insert the tanks in the world
for (int index = 0; index < NUM_TANKS; index++)
{
// reset the object (this only matters for backface and object removal)
Reset(obj_tank);
// generate rotation matrix around y axis
BuildXYZRotation(0, tanks[index].w, 0, mrot);
// rotate the local coords of the object
Transform(obj_tank, mrot, TRANSFORM_LOCAL_TO_TRANS);
// set position of tank
obj_tank.world_pos.x = tanks[index].x;
obj_tank.world_pos.y = tanks[index].y;
obj_tank.world_pos.z = tanks[index].z;
// attempt to cull object
if (!Cull(obj_tank, cam, CULL_OBJECT_XYZ_PLANES))
{
// if we get here then the object is visible at this world position
// so we can insert it into the rendering list
// perform local/model to world transform
ModelToWorld(obj_tank, TRANSFORM_TRANS_ONLY);
// insert the object into render list
Insert2(rend_list, obj_tank, 0, 0);
}
}
// insert the towers in the world
for (int index = 0; index < NUM_TOWERS; index++)
{
// reset the object (this only matters for backface and object removal)
Reset(obj_tower);
// set position of tower
obj_tower.world_pos.x = towers[index].x;
obj_tower.world_pos.y = towers[index].y;
obj_tower.world_pos.z = towers[index].z;
// attempt to cull object
if (!Cull(obj_tower, cam, CULL_OBJECT_XYZ_PLANES))
{
// if we get here then the object is visible at this world position
// so we can insert it into the rendering list
// perform local/model to world transform
ModelToWorld(obj_tower);
// insert the object into render list
Insert2(rend_list, obj_tower, 0, 0);
}
}
// insert the ground markers into the world
for (int index_x = 0; index_x < NUM_POINTS_X; index_x++)
for (int index_z = 0; index_z < NUM_POINTS_Z; index_z++)
{
// reset the object (this only matters for backface and object removal)
Reset(obj_marker);
// set position of tower
obj_marker.world_pos.x = RAND_RANGE(-10, 10) - UNIVERSE_RADIUS + index_x * POINT_SIZE;
obj_marker.world_pos.y = obj_marker.max_radius;
obj_marker.world_pos.z = RAND_RANGE(-10, 10) - UNIVERSE_RADIUS + index_z * POINT_SIZE;
// attempt to cull object
if (!Cull(obj_marker, cam, CULL_OBJECT_XYZ_PLANES))
{
// if we get here then the object is visible at this world position
// so we can insert it into the rendering list
// perform local/model to world transform
ModelToWorld(obj_marker);
// insert the object into render list
Insert2(rend_list, obj_marker, 0, 0);
}
}
// remove backfaces
RemoveBackfaces(rend_list, cam);
// apply world to camera transform
WorldToCamera(rend_list, cam);
// apply camera to perspective transformation
CameraToPerspective(rend_list, cam);
// apply screen transform
PerspectiveToScreen(rend_list, cam);
sprintf(work_string, "pos:[%f, %f, %f] heading:[%f] elev:[%f]",
cam.pos.x, cam.pos.y, cam.pos.z, cam.dir.y, cam.dir.x);
gPrintf(0, WINDOW_HEIGHT - 20, RGB(0, 255, 0), AToT(work_string));
// draw instructions
gPrintf(0, 0, RGB(0, 255, 0), TEXT("Press ESC to exit. Press Arrow Keys to Move. Space for TURBO."));
BeginDrawOn();
// render the object
DrawSolid(rend_list);
EndDrawOn();
fpsSet.adjust();
gPrintf(0, 0, RED_GDI, TEXT("%d"), fpsSet.get());
Flush();
}
void GameClose()
{
}
int main(int argc, char* argv[])
{
//gameBox.setWndMode(false, true);
gameBox.create(SCREEN_WIDTH, SCREEN_HEIGHT, TEXT("键盘控制移动"));
gameBox.setGameStart(StartUp);
gameBox.setGameBody(GameBody);
gameBox.setGameEnd(GameClose);
gameBox.startCommuication();
return argc;
}
| [
"1494977853@qq.com"
] | 1494977853@qq.com |
d06d9d02dc25da3358c879f29b2b36551d71ba3c | 700bd6fb0f9eb2ec1d23ff39b069e5a3d7b26576 | /src/main.cpp | de74a6ea27d02346a50680020c25fa2823cd48ee | [] | no_license | iniwap/LeapMotion-SmallGame-With-OF | 6da32e0099cb8572ef51eba119cdd09c1214edd1 | c5fb0c97d4685c7cbeb4550d2ce33d36d584e3b9 | refs/heads/master | 2021-01-23T07:27:12.846640 | 2013-11-29T15:23:39 | 2013-11-29T15:23:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 413 | cpp | #include "ofMain.h"
#include "gameApp.h"
#include "ofAppGlutWindow.h"
//========================================================================
int main( ){
ofAppGlutWindow window;
ofSetupOpenGL(&window, 800,600, OF_WINDOW); // <-------- setup the GL context
// this kicks off the running of my app
// can be OF_WINDOW or OF_FULLSCREEN
// pass in width and height too:
ofRunApp( new gameApp());
}
| [
"iafun@iafuns-MacBook-Pro.local"
] | iafun@iafuns-MacBook-Pro.local |
86c98c5a5047ab3e0626b58aa26bfd5f3605e144 | 21aa7d1dbf2b6ae0582797b653090d0fb13d4da0 | /common/include/common/ConsoleLogger.h | 94143f554b7eb1fc22d6a8f27b06c8426da73daf | [
"MIT",
"LicenseRef-scancode-unknown",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | define-private-public/SpvGenTwo | 3b4e66a7ffb0732a8b3d28cedb11a1430ac4c767 | 5ff86437a0548134e7a3173f97edbefb5bedf7c3 | refs/heads/master | 2022-11-27T11:20:01.073015 | 2020-07-30T13:56:09 | 2020-07-30T13:56:09 | 284,812,481 | 0 | 0 | MIT | 2020-08-03T21:37:30 | 2020-08-03T21:37:29 | null | UTF-8 | C++ | false | false | 345 | h | #pragma once
#include "spvgentwo/Logger.h"
namespace spvgentwo
{
class ConsoleLogger : public ILogger
{
public:
ConsoleLogger();
ConsoleLogger(const ConsoleLogger&) = delete;
ConsoleLogger(ConsoleLogger&&) = delete;
private:
static void LogImpl(ILogger* _pInstance, LogLevel _level, const char* _pFormat, ...);
};
} // !spvgentwo | [
"fwahlster@outlook.com"
] | fwahlster@outlook.com |
b1938f62740a3f9a2853d1547de65b7300f4dc68 | f1ac5501fd36e4e420dfbc912890b4c848e4acc3 | /src/script/serverchecker.cpp | 9be7932a7dd5634e391cccadecd47644ba55270a | [] | no_license | whojan/KomodoOcean | 20ca84ea11ed791c407bed17b155134b640796e8 | f604a95d848222af07db0005c33dc4852b5203a3 | refs/heads/master | 2022-08-07T13:10:15.341628 | 2019-06-14T17:27:57 | 2019-06-14T17:27:57 | 274,690,003 | 1 | 0 | null | 2020-06-24T14:28:50 | 2020-06-24T14:28:49 | null | UTF-8 | C++ | false | false | 3,897 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "serverchecker.h"
#include "script/cc.h"
#include "cc/eval.h"
#include "pubkey.h"
#include "random.h"
#include "uint256.h"
#include "util.h"
#undef __cpuid
#include <boost/thread.hpp>
#include <boost/tuple/tuple_comparison.hpp>
namespace {
/**
* Valid signature cache, to avoid doing expensive ECDSA signature checking
* twice for every transaction (once when accepted into memory pool, and
* again when accepted into the block chain)
*/
class CSignatureCache
{
private:
//! sigdata_type is (signature hash, signature, public key):
typedef boost::tuple<uint256, std::vector<unsigned char>, CPubKey> sigdata_type;
std::set< sigdata_type> setValid;
boost::shared_mutex cs_serverchecker;
public:
bool
Get(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
{
boost::shared_lock<boost::shared_mutex> lock(cs_serverchecker);
sigdata_type k(hash, vchSig, pubKey);
std::set<sigdata_type>::iterator mi = setValid.find(k);
if (mi != setValid.end())
return true;
return false;
}
void Set(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
{
// DoS prevention: limit cache size to less than 10MB
// (~200 bytes per cache entry times 50,000 entries)
// Since there can be no more than 20,000 signature operations per block
// 50,000 is a reasonable default.
int64_t nMaxCacheSize = GetArg("-maxservercheckersize", 50000);
if (nMaxCacheSize <= 0) return;
boost::unique_lock<boost::shared_mutex> lock(cs_serverchecker);
while (static_cast<int64_t>(setValid.size()) > nMaxCacheSize)
{
// Evict a random entry. Random because that helps
// foil would-be DoS attackers who might try to pre-generate
// and re-use a set of valid signatures just-slightly-greater
// than our cache size.
uint256 randomHash = GetRandHash();
std::vector<unsigned char> unused;
std::set<sigdata_type>::iterator it =
setValid.lower_bound(sigdata_type(randomHash, unused, unused));
if (it == setValid.end())
it = setValid.begin();
setValid.erase(*it);
}
sigdata_type k(hash, vchSig, pubKey);
setValid.insert(k);
}
};
}
bool ServerTransactionSignatureChecker::VerifySignature(const std::vector<unsigned char>& vchSig, const CPubKey& pubkey, const uint256& sighash) const
{
static CSignatureCache signatureCache;
if (signatureCache.Get(sighash, vchSig, pubkey))
return true;
if (!TransactionSignatureChecker::VerifySignature(vchSig, pubkey, sighash))
return false;
if (store)
signatureCache.Set(sighash, vchSig, pubkey);
return true;
}
/*
* The reason that these functions are here is that the what used to be the
* CachingTransactionSignatureChecker, now the ServerTransactionSignatureChecker,
* is an entry point that the server uses to validate signatures and which is not
* included as part of bitcoin common libs. Since Crypto-Condtions eval methods
* may call server code (GetTransaction etc), the best way to get it to run this
* code without pulling the whole bitcoin server code into bitcoin common was
* using this class. Thus it has been renamed to ServerTransactionSignatureChecker.
*/
int ServerTransactionSignatureChecker::CheckEvalCondition(const CC *cond) const
{
//LogPrintf("call RunCCeval from ServerTransactionSignatureChecker::CheckEvalCondition\n");
return RunCCEval(cond, *txTo, nIn);
}
| [
"ip_gpu@mail.ru"
] | ip_gpu@mail.ru |
b0f04c3c4b787f6a3d7503fb71895791abdcee40 | f8d41b5c66e8daa27121824bbb16cc827a785cc2 | /Code/GraphMol/CIPLabeler/rules/Rules.h | 1d75c8d700020e76c996380a6edc54c86ecd802c | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | greglandrum/rdkit | 56a0e6531dd187308489122aaa67aa9907f9635e | 0eacf4824833b31a49de7fa7ad3ae00c946b7f14 | refs/heads/master | 2023-08-31T23:59:33.246643 | 2023-03-23T09:57:25 | 2023-03-23T09:57:25 | 40,303,040 | 3 | 3 | BSD-3-Clause | 2023-09-07T11:01:54 | 2015-08-06T12:14:42 | HTML | UTF-8 | C++ | false | false | 2,063 | h | //
//
// Copyright (C) 2020 Schrödinger, LLC
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#pragma once
#include <initializer_list>
#include <vector>
#include "Rule5.h"
#include "SequenceRule.h"
namespace RDKit {
namespace CIPLabeler {
class Rules : public SequenceRule {
public:
Rules() = delete;
Rules(std::initializer_list<SequenceRule *> rules) {
for (auto &rule : rules) {
add(rule);
}
}
~Rules() override {
for (auto &rule : d_rules) {
delete rule;
}
}
void add(SequenceRule *rule) {
if (rule == nullptr) {
throw std::runtime_error("No sequence rule provided");
}
d_rules.push_back(rule);
rule->setSorter(new Sort(d_rules));
}
int getNumSubRules() const { return d_rules.size(); }
const Sort *getSorter() const override {
if (dp_sorter == nullptr) {
const_cast<Rules *>(this)->setSorter(new Sort(this));
}
return dp_sorter.get();
}
int compare(const Edge *o1, const Edge *o2) const override {
// Try using each rules. The rules will expand the search exhaustively
// to all child substituents
for (const auto &rule : d_rules) {
// compare expands exhaustively across the whole graph
int value = rule->recursiveCompare(o1, o2);
if (value != 0) {
return value;
}
}
return 0;
}
int getComparision(const Edge *a, const Edge *b, bool deep) const override {
(void)deep;
// Try using each rules. The rules will expand the search exhaustively
// to all child substituents
for (const auto &rule : d_rules) {
// compare expands exhaustively across the whole graph
int value = rule->recursiveCompare(a, b);
if (value != 0) {
return value;
}
}
return 0;
}
private:
std::vector<const SequenceRule *> d_rules;
};
} // namespace CIPLabeler
} // namespace RDKit
| [
"noreply@github.com"
] | greglandrum.noreply@github.com |
b5883035081eeeaf6a7d682e3a0aebdd2052ee70 | 2f10f807d3307b83293a521da600c02623cdda82 | /deps/boost/win/debug/include/boost/process/detail/windows/locale.hpp | da78bf0dd96785885ea645fdc9b3a5c7a89a1476 | [] | no_license | xpierrohk/dpt-rp1-cpp | 2ca4e377628363c3e9d41f88c8cbccc0fc2f1a1e | 643d053983fce3e6b099e2d3c9ab8387d0ea5a75 | refs/heads/master | 2021-05-23T08:19:48.823198 | 2019-07-26T17:35:28 | 2019-07-26T17:35:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 129 | hpp | version https://git-lfs.github.com/spec/v1
oid sha256:70e4104c44c9ba6d080542f5bc81dbcdd1a77212c9e0d719105ca80ade49495d
size 3154
| [
"YLiLarry@gmail.com"
] | YLiLarry@gmail.com |
def54fb831d8465aeb9d3f285236390c775cb212 | 13b25f161cc1f878c8aaa6e4635c20678068759f | /cplusplus_learning/rcf_client_learning/demo_client.cpp | aa4b7040febb591da6d00e883977e739ffd44887 | [] | no_license | JayL323/cpluspluslearning | d3df70859020e5758a68c1e74102f0dadba1b4e0 | 8f7912791bb15d6dd8019e42687f088c5270f94f | refs/heads/master | 2022-03-26T23:13:26.239058 | 2020-01-01T13:04:16 | 2020-01-01T13:05:06 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,012 | cpp | #include<iostream>
#include<iterator>
#include<RCF/RCF.hpp>
#include"demo_interface.h"
int main()
{
RCF::RcfInit rcfInit;
std::string ip = "127.0.0.1";
int port = 50001;
std::cout << "将要连接到" << ip << ":" << port << "\n";
std::vector<std::string> v;
v.push_back("one");
v.push_back("two");
v.push_back("three");
try
{
std::cout << "Before\n";
std::copy(v.begin(), v.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
//RcfClient<I_DemoService>(RCF::TcpEndpoint(ip, port)).Reverse(v);
//RcfClient<I_DemoService> client = RcfClient<I_DemoService>(RCF::TcpEndpoint(ip,
// port));
RcfClient<I_DemoService> client((RCF::TcpEndpoint(ip,port)));
client.Reverse(v);
std::cout << "After\n";
std::copy(v.begin(), v.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
}
catch (const RCF::Exception& e)
{
std::cout << "get exception\n";
std::cout << e.getErrorMessage();
}
std::cout << "按任意键退出\n";
std::cin.get();
return 0;
} | [
"942296928@qq.com"
] | 942296928@qq.com |
237f461adbe2e62bd6bc2eb39a490f2d7f8e96c7 | 1bf1d70e40faa87d458942abf9fc7b0856476efc | /uri/2374.2.cpp | 3d06c7443f2b24e715f116c408007696897ba148 | [] | no_license | lilianefreitas/competitive-programming-questions | 418bfe9c60b30c1e21e5332862b45ff36b6f12aa | fe832f68b9cd89514a6b3888219db01cc8c93877 | refs/heads/master | 2023-03-29T21:48:37.156877 | 2021-03-28T07:38:45 | 2021-03-28T07:38:45 | 267,492,757 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 387 | cpp | #include <bits/stdc++.h>
using namespace std;
// N = pressão desejada pelo motorista
// M = pressão lida pela bomba
int N, M;
int main() {
// pegar as entradas
scanf("%d%d", &N, &M);
// diferença entre a pressao desejada e a lida
int diferenca = N - M;
// imprimindo a diferença
// colocar barra N apos o %d
printf("%d", diferenca);
return 0;
}
| [
"alunalilianefreitas@gmail.com"
] | alunalilianefreitas@gmail.com |
9b9e1cd87852e72f62111137e22d054e1b1fddba | 45d87d819c13793102d01696dfde50619e14f243 | /src/visualization.h | 5488e4312da8d2cc5f32bfcc27f33f8169ab86a3 | [] | no_license | paraficial/perlin_noise_marching_cubes | aef77a75df024e6e0f28d09c52d63be1be6057dc | 33894becac715bb561afc18667d5bdbaaf30d47f | refs/heads/master | 2020-12-26T18:17:31.284278 | 2020-02-03T11:46:58 | 2020-02-03T11:46:58 | 237,593,565 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 446 | h | #ifndef VISUALIZATION_H
#define VISUALIZATION_H
#include <SDL2/SDL.h>
#include <glm/glm.hpp>
class Mesh;
class Shader;
class Visualization
{
public:
Visualization(int width, int height);
int init(int width, int height);
void loop(Mesh *mesh, Shader *shader, float angle);
private:
SDL_Window *window;
SDL_GLContext context;
glm::mat4 projection, view, model, mvp;
float m_angle = 0.0f;
};
#endif // VISUALIZATION_H
| [
"gregor.wiese@gmx.de"
] | gregor.wiese@gmx.de |
fa72dd4ce48cf6fde1a6bcc772eab33f17bfd3b2 | c84629bf7158041eb5309f11cf5c678f116081b4 | /backUp/!_SHADER_GALLERY_noIndices/_SHADERS/velvet/velvet_INIT.cpp | 54e93413f74dc7f73145266c7743e94e85e287b4 | [] | no_license | marcclintdion/iOS_WIN3 | ce6358be75900a143f6639057c1d96b5e3f546b3 | d339cfab929534903abbdc6043ac0280ff68e558 | refs/heads/master | 2016-09-06T05:54:23.058832 | 2015-09-16T07:37:12 | 2015-09-16T07:37:12 | 42,571,722 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,335 | cpp | #ifdef __APPLE__
#import <OpenGLES/ES2/gl.h>
#import <OpenGLES/ES2/glext.h>
#endif
//===============================================================================================
velvet_SHADER = glCreateProgram();
//---------------------------------------------------------------------
const GLchar *vertexSource_velvet =
" #define highp \n"
" uniform highp vec4 light_POSITION_01; \n"
" uniform mat4 mvpMatrix; \n"
" uniform mat4 lightMatrix; \n"
" attribute vec4 position; \n"
" attribute vec2 texture; \n"
" varying highp vec4 lightPosition_PASS; \n"
" varying highp vec2 varTexcoord; \n"
" varying highp vec4 diffuse; \n"
" varying highp vec4 ambient; \n"
" varying highp vec4 ambientGlobal; \n"
" varying highp float dist; \n"
" highp vec4 ecPos; \n"
" highp vec3 aux; \n"
" void main() \n"
" { \n"
" ecPos = mvpMatrix * position; \n"
" aux = vec3(light_POSITION_01 - ecPos); \n"
" dist = length(aux); \n"
" diffuse = vec4( 1.00, 1.0, 1.00, 1.0) * vec4(1.0, 48.6, 1.0, 1.0); \n"
" ambient = vec4(-1.75, -1.75, 0.0, 1.0) * vec4(1.1, 26.1, 1.1, 1.0); \n"
" ambientGlobal = vec4(-1.75, -1.75, 0.0, 1.0); \n"
" lightPosition_PASS = normalize(lightMatrix * light_POSITION_01); \n"
" varTexcoord = texture; \n"
" gl_Position = mvpMatrix * position; \n"
" }\n";
//---------------------------------------------------------------------
velvet_SHADER_VERTEX = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(velvet_SHADER_VERTEX, 1, &vertexSource_velvet, NULL);
glCompileShader(velvet_SHADER_VERTEX);
//---------------------------------------------------------------------
const GLchar *fragmentSource_velvet =
" #ifdef GL_ES \n"
" #else \n"
" #define highp \n"
" #endif \n"
" uniform sampler2D Texture1; \n"
" uniform sampler2D NormalMap; \n"
" uniform highp float shininess; \n"
" uniform highp float attenuation; \n"
" varying highp vec4 lightPosition_PASS; \n"
" varying highp vec2 varTexcoord; \n"
" highp float NdotL1; \n"
" highp vec3 normal; \n"
" highp vec3 NormalTex; \n"
" varying highp vec4 diffuse; \n"
" varying highp vec4 ambient; \n"
" varying highp vec4 ambientGlobal; \n"
" varying highp float dist; \n"
" highp float att; \n"
" highp vec4 color; \n"
" void main() \n"
" { \n"
" NormalTex = texture2D(NormalMap, varTexcoord).xyz; \n"
" NormalTex = (NormalTex - 0.5); \n"
" normal = normalize(NormalTex); \n"
" NdotL1 = dot(normal, lightPosition_PASS.xyz); \n"
" att = 1.0 / attenuation; \n"
" color = ambientGlobal + (att * (diffuse + ambient)); \n"
" color += vec4(-0.60, -11.0, 0.60, 1.0) * pow(NdotL1, 13.84); \n"
" color -= vec4(1.0, 1.0,1.0, 1.0) * pow(NdotL1, shininess); \n"
" gl_FragColor = texture2D(Texture1, varTexcoord.st) *color * NdotL1 * 2.0; \n"
" }\n";
//---------------------------------------------------------------------
velvet_SHADER_FRAGMENT = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(velvet_SHADER_FRAGMENT, 1, &fragmentSource_velvet, NULL);
glCompileShader(velvet_SHADER_FRAGMENT);
//------------------------------------------------
glAttachShader(velvet_SHADER, velvet_SHADER_VERTEX);
glAttachShader(velvet_SHADER, velvet_SHADER_FRAGMENT);
//------------------------------------------------
glBindAttribLocation(velvet_SHADER, 0, "position");
glBindAttribLocation(velvet_SHADER, 1, "normal");
glBindAttribLocation(velvet_SHADER, 2, "texture");
//------------------------------------------------
glLinkProgram(velvet_SHADER);
//------------------------------------------------
#ifdef __APPLE__
glDetachShader(velvet_SHADER, velvet_SHADER_VERTEX);
glDetachShader(velvet_SHADER, velvet_SHADER_FRAGMENT);
#endif
//------------------------------------------------
glDeleteShader(velvet_SHADER_VERTEX);
glDeleteShader(velvet_SHADER_FRAGMENT);
//------------------------------------------------------------------------------------------------------------//___LOAD_UNIFORMS
UNIFORM_MODELVIEWPROJ_velvet = glGetUniformLocation(velvet_SHADER, "mvpMatrix");
UNIFORM_LIGHT_MATRIX_velvet = glGetUniformLocation(velvet_SHADER, "lightMatrix");
UNIFORM_LIGHT_POSITION_01_velvet = glGetUniformLocation(velvet_SHADER, "light_POSITION_01");
UNIFORM_SHININESS_velvet = glGetUniformLocation(velvet_SHADER, "shininess");
UNIFORM_ATTENUATION_velvet = glGetUniformLocation(velvet_SHADER, "attenuation");
UNIFORM_TEXTURE_DOT3_velvet = glGetUniformLocation(velvet_SHADER, "NormalMap");
UNIFORM_TEXTURE_velvet = glGetUniformLocation(velvet_SHADER, "Texture1");
| [
"marcclintdion@Marcs-iMac.local"
] | marcclintdion@Marcs-iMac.local |
780021fc00970191d05fbc233e8c2baf8e05fd4d | f7d8dfb897e4ab2a6b2b769ab16e3093d7ff7dc1 | /main.cpp | 9233a2beb76ecd6ebff21d9aa14ad63fb2628ee2 | [] | no_license | Rogan003/SwimmingCareerSimulatorDemo | 228a85a0f4e63921ed087752b64bfd3993956ab5 | 3c41b31a2df75a858cc9b4c298d8d89b6262d716 | refs/heads/master | 2021-04-11T19:22:59.596928 | 2020-12-18T11:39:11 | 2020-12-18T11:39:11 | 249,046,687 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,347 | cpp | #include <iostream>
#include <cmath>
#include <ctime>
#include <cstdlib>
#include <list>
using namespace std;
enum drzava{Egipat,Jamajka,Srbija,Hrvatska,Svajcarska,Austrija,Italija,Rusija,Nemacka,Brazil,Australija,Kanada,Kina,VelikaBritanija,Japan,SAD};
enum Marka{TYR,Speedo,Arena};
#include "drzava.hpp"
#include "trener.hpp"
#include "bazen.hpp"
#include "oprema.hpp"
#include "uprava.hpp"
#include "plivaci.hpp"
#include "klub.hpp"
#include "porodica.hpp"
#include "drustvo.hpp"
#include "slobodnovreme.hpp"
#include "spavanje.hpp"
#include "opustanje.hpp"
#include "ljubav.hpp"
#include "zivot.hpp"
#include "tipicnaoprema.hpp"
#include "licnaoprema.hpp"
#include "treninzi.hpp"
#include "vodenitrening.hpp"
#include "teretana.hpp"
#include "suvi.hpp"
#include "trenazniproces.hpp"
#include "plivac.hpp"
int main()
{
srand(time(NULL));
int nedelja=1,mesec=1,godina=2020,jacina,izbor,ss=0,brtakm[2],d1[10],d2[10],d3[10],d4[10],dolaz;
int br[3]={0,0,0};
char l;
string ime,prezime;
int godine;
float rezultat,wrez=20.91,rez1=70.00,m[4],r[4];
string provera;
Plivac p1("","",0,0);
cout<<"Zdravo! Unesite ime, prezime i godine plivaca: ";
cin>>p1;
cout<<"Da li ste nekad ranije bili plivac? Unesite jednostavno da ili ne: ";
cin>>provera;
if(provera=="da"){
cout<<"Unesite rezultat koji ste imali: ";
cin>>rezultat;
}
else
rezultat=64.5;
if(rezultat==64.5)
p1.setPocetniRez(rezultat);
else
p1.setPocetniRez(rezultat+20);
p1.setBRez(rezultat);
bool odustajanje=false;
Plivac p2("Protivnik","Jedan",p1.getGodine(),rezultat-5);
Plivac p3("Protivnik","Dva",p1.getGodine(),rezultat-5);
Plivac p4("Protivnik","Tri",p1.getGodine(),rezultat-5);
system("cls");
do{
cout<<"Nedelja: "<<nedelja<<" Mesec: "<<mesec<<" Godina: "<<godina<<"("<<p1.getGodine()<<" godina)"<<endl;
if(nedelja==1 && mesec==1){
cout<<"Da li zelite da dodate bazen: ";
string rec;
cin>>rec;
if(rec=="da"){
cout<<"Unesite udaljenost: ";
int udalj;
cin>>udalj;
float us=(rand()%400+100)/100.00;
p1.dodajBazen(us,udalj);
}
cout<<"Unesite redni broj bazena na kom zelite da trenirate sl godine: ";
int baz;
cin>>baz;
bool pomocnaprom=false;
while(!pomocnaprom){
pomocnaprom=p1.izaberBazen(baz);
if(pomocnaprom==false){
cout<<"Nepostojeci redni broj bazena! Pokusajte ponovo: "<<endl;
cout<<"Unesite redni broj bazena na kom zelite da trenirate sl godine: ";
cin>>baz;
}
}
cout<<"Unesite koju opremu zelite da kupite(redom karbon,naocare,kapa,mrezica)(0-nista, 1-TYR, 2-Speedo, 3-Arena): ";
cin>>p1.getOprema();
cout<<"Koliko takmicenja zelite da imate ove godine: ";
cin>>brtakm[0];
cout<<"Koliko njih ce biti ekstremno bitno: ";
cin>>brtakm[1];
}
if(brtakm[1]>brtakm[0])
brtakm[1]=brtakm[0];
int i=0;
if(mesec!=1 || nedelja!=1)
i=2;
for(;i<2;++i){
if(brtakm[0]==0){
brtakm[1]=0;
break;
}
for(i=0;i<brtakm[0];++i){
cout<<i+1<<". mesec takmicenja: ";
cin>>d1[i];
cout<<"Nedelja: ";
cin>>d2[i];
}
if(brtakm[1]==0)
break;
for(i=0;i<brtakm[1];++i){
int v[brtakm[1]];
cout<<"Koja takmicenja ce biti bitna: ";
cin>>v[i];
d3[i]=d1[v[i]-1];
d4[i]=d2[v[i]-1];
}
}
cout<<"Takmicenja su u:"<<endl;
for(i=0;i<brtakm[0];++i){
cout<<d1[i]<<". mesec "<<d2[i]<<". nedelja"<<endl;
}
cout<<"Bitna su u:"<<endl;
for(i=0;i<brtakm[1];++i){
cout<<d3[i]<<". mesec "<<d4[i]<<". nedelja"<<endl;
}
cout<<"Unesite koliko jako zelite da trenirate(sve od 0-5(0-odmor), prvo voda, izbor teretana ili suvi, pa jacina tamo 0-5): ";
cin>>p1.getTrening();
int pom1=rand()%10;
if(pom1==0)
p2.odmaraj();
else if(pom1<=2)
p2.vodaTreniraj1();
else if(pom1==3)
p2.vodaTreniraj2();
else if(pom1==4)
p2.vodaTreniraj3();
else if(pom1<=6)
p2.vodaTreniraj4();
else
p2.vodaTreniraj5();
if(pom1!=0){
pom1=rand()%10+1;
if(pom1%2==0){
if(pom1==2)
p2.teretanaTreniraj1();
if(pom1==4)
p2.teretanaTreniraj2();
if(pom1==6)
p2.teretanaTreniraj3();
if(pom1==8)
p2.teretanaTreniraj4();
else
p2.teretanaTreniraj5();
}
if(pom1%2==1){
if(pom1==1)
p2.suviTreniraj1();
if(pom1==3)
p2.suviTreniraj2();
if(pom1==5)
p2.suviTreniraj3();
if(pom1==7)
p2.suviTreniraj4();
else
p2.suviTreniraj5();
}
}
pom1=rand()%10;
if(pom1==0)
p3.odmaraj();
else if(pom1<=2)
p3.vodaTreniraj1();
else if(pom1==3)
p3.vodaTreniraj2();
else if(pom1==4)
p3.vodaTreniraj3();
else if(pom1<=6)
p3.vodaTreniraj4();
else
p3.vodaTreniraj5();
if(pom1!=0){
pom1=rand()%10+1;
if(pom1%2==0){
if(pom1==2)
p3.teretanaTreniraj1();
if(pom1==4)
p3.teretanaTreniraj2();
if(pom1==6)
p3.teretanaTreniraj3();
if(pom1==8)
p3.teretanaTreniraj4();
else
p3.teretanaTreniraj5();
}
if(pom1%2==1){
if(pom1==1)
p3.suviTreniraj1();
if(pom1==3)
p3.suviTreniraj2();
if(pom1==5)
p3.suviTreniraj3();
if(pom1==7)
p3.suviTreniraj4();
else
p3.suviTreniraj5();
}
}
pom1=rand()%10;
if(pom1==0)
p4.odmaraj();
else if(pom1<=2)
p4.vodaTreniraj1();
else if(pom1==3)
p4.vodaTreniraj2();
else if(pom1==4)
p4.vodaTreniraj3();
else if(pom1<=6)
p4.vodaTreniraj4();
else
p4.vodaTreniraj5();
if(pom1!=0){
pom1=rand()%10+1;
if(pom1%2==0){
if(pom1==2)
p4.teretanaTreniraj1();
if(pom1==4)
p4.teretanaTreniraj2();
if(pom1==6)
p4.teretanaTreniraj3();
if(pom1==8)
p4.teretanaTreniraj4();
else
p4.teretanaTreniraj5();
}
if(pom1%2==1){
if(pom1==1)
p4.suviTreniraj1();
if(pom1==3)
p4.suviTreniraj2();
if(pom1==5)
p4.suviTreniraj3();
if(pom1==7)
p4.suviTreniraj4();
else
p4.suviTreniraj5();
}
}
for(i=0;i<brtakm[0];++i){
if(mesec==d1[i] && nedelja==d2[i]){
cout<<"Vreme je za takmicenje!"<<endl;
bool bitnost=false;
for(int sklj=0;sklj<brtakm[1];++sklj)
if(mesec==d3[sklj] && nedelja==d4[sklj])
bitnost=true;
float pom=p1.getRezultat(bitnost,true);
int pl=0;
int je=0;
int j;
m[3]=pom;
m[0]=p2.getRezultat(bitnost,false);
m[1]=p3.getRezultat(bitnost,false);
m[2]=p4.getRezultat(bitnost,false);
for(je=0;je<4;++je){
r[je]=600;
for(j=0;j<4;++j){
if(m[j]<r[je]){
for(int p=0;p<4;++p){
if(m[j]==r[p]){
++pl;
}
}
if(pl==0)
r[je]=m[j];
}
pl=0;
}
}
for(j=0;j<4;++j){
cout<<j+1<<". mesto: "<<r[j]<<endl;
if(r[j]<wrez){
cout<<"OVO JE NOVI SVETSKI REKORD!!"<<endl;
wrez=r[j];
}
if(r[j]==m[3]){
cout<<"--Ovo je tvoj rezultat!"<<endl;
if(pom<p1.getBRez()){
cout<<"--Novi najbolji rezultat!"<<endl;
p1.setBRez(pom);
}
if(j!=3)
br[j]+=1;
}
}
cout<<"Pritisnite bilo sta da nastavimo: ";
cin>>l;
}
}
++nedelja;
if(nedelja==5){
mesec++;
nedelja=1;
}
if(mesec==13){
dolaz=p1.getDolaznost();
p1.godisnji(2);
mesec=1;
godina++;
cout<<"Da li zelite da odustanete? Napisite da da odustanete: ";
string pr;
cin>>pr;
if(pr=="da")
odustajanje=true;
else{
cout<<"Da li zelite da promenite trenera?: ";
string pomm;
cin>>pomm;
if(pomm=="da"){
cout<<"Unesite 1 za novog trenera, a 2 za vec postojeceg: ";
int brojtr;
cin>>brojtr;
string imeTrenera;
cout<<"Unesite ime trenera: ";
cin>>imeTrenera;
if(brojtr==1){
float nes=(rand()%400+100)/100.00;
p1.dodajTrenera(imeTrenera,nes);
}
bool pomoc=false;
while(!pomoc){
pomoc=p1.izaberiTrenera(imeTrenera);
if(!pomoc){
cout<<"Nepostojeci trener! Izaberite ponovo: "<<endl;
cout<<"Unesite ime trenera: ";
cin>>imeTrenera;
}
}
}
}
p1.povecajGodine();
}
system("cls");
}while(odustajanje==false);
p1.setDolaznost(dolaz);
cout<<"Svaka cast na vasoj plivackoj karijeri!"<<endl;
Plivac p5=p1;
if(p1!=p2 && p1!=p3 && p1!=p4 && p1==p5)
cout<<"Bili ste jedinstven plivac!"<<endl;
if(p1>p2 && p1>p3 && p1>p4)
cout<<"Bili ste najbolji plivac!"<<endl;
else{
int pomocna=1;
if(p1<p2)
pomocna++;
if(p1<p3)
pomocna++;
if(p1<p4)
pomocna++;
cout<<"Bili ste "<<pomocna<<". plivac!"<<endl;
}
cout<<"Vas najbolji rezultat: "<<p1.getBRez()<<endl;
cout<<"Zlatne medalje: "<<br[0]<<" Srebrne medalje: "<<br[1]<<" Bronzane medalje: "<<br[2]<<endl;
cout<<p1;
return 0;
}
| [
"roganovic.veselin@jjzmaj.edu.rs"
] | roganovic.veselin@jjzmaj.edu.rs |
2115f14f719ef66e3c7f4549fdc338cb4d524a66 | 7b3856478d8009a2b6bbd7101352e9452e7b1414 | /October 4/October 4 Solution.cpp | 7cc37aa87638a441a684c38349128510f0d45685 | [] | no_license | Sanjays2402/Leetcode-October-Challenge | 40ef29d6dafaa307303f836bb5470e783bc1a8fc | 922956d772a91632787f7993d647dc032a8c3f3f | refs/heads/main | 2023-01-05T14:25:07.122022 | 2020-10-28T17:49:26 | 2020-10-28T17:49:26 | 300,665,444 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 732 | cpp | class Solution {
public:
static bool comp(vector<int>& a, vector<int>& b)
{
if(a[0] == b[0])
return a[1] > b[1];
return a[0] < b[0];
}
int removeCoveredIntervals(vector<vector<int>>& intervals) {
if(intervals.size() == 0)
return 0;
int n=intervals.size();
int count=n;
sort(intervals.begin(), intervals.end(), comp);
vector<int> temp(intervals[0].begin(), intervals[0].end());
for(int i=1; i<n; i++)
{
if( temp[1] >= intervals[i][1] )
count--;
else
{
temp=intervals[i];
}
}
return count;
}
};
| [
"noreply@github.com"
] | Sanjays2402.noreply@github.com |
10cbeb320b3df4a6572a5fa4430aab306363449a | c2fb6846d5b932928854cfd194d95c79c723f04c | /4rth_Sem_c++_backup/Amlyan/shit/arka.cpp | f24511a7e641de93ef0c21860f97c049ea65a80d | [
"MIT"
] | permissive | Jimut123/code-backup | ef90ccec9fb6483bb6dae0aa6a1f1cc2b8802d59 | 8d4c16b9e960d352a7775786ea60290b29b30143 | refs/heads/master | 2022-12-07T04:10:59.604922 | 2021-04-28T10:22:19 | 2021-04-28T10:22:19 | 156,666,404 | 9 | 5 | MIT | 2022-12-02T20:27:22 | 2018-11-08T07:22:48 | Jupyter Notebook | UTF-8 | C++ | false | false | 319 | cpp | #include<iostream>
#include<cmath>
using namespace std;
int main()
{
int i,size = 20,pow=1,j;
float sum = 0,den;
for(i=0;i<20;i++)
{
cout<<1<<"/"<<(i+1)<<"*"<<3<<"^"<<i<<" + ";
pow=1;
for(j=1;j<=i;j++)
pow=pow*3;
den = (i+1)*pow;
sum = sum + 1/den;
}
cout<<"Sum = "<<sum<<endl;
return 0;
}
| [
"jimutbahanpal@yahoo.com"
] | jimutbahanpal@yahoo.com |
9fec39404899b69d0d269079355c32fd27ffdf6b | f3bdc5713fcbf31a5098e5c6bc7b536f63be1609 | /GameEngine/src/EventDispatcher.cpp | 2b63008d33ece7a180eeafe5f87e985f3f783aad | [] | no_license | leonardo98/GameEngine | 1cceaf0f6dc8bc66d9d1862f8523b8199ef54356 | 2f3c218437434c05afe9eaac0900c3ff46ff7055 | refs/heads/master | 2020-04-05T22:56:53.009769 | 2015-07-16T14:59:07 | 2015-07-16T14:59:07 | 33,198,384 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,319 | cpp | #include "EventDispatcher.h"
#include "Event.h"
namespace oxygine
{
EventDispatcher::EventDispatcher():_lastID(0), _listeners(0)
{
}
EventDispatcher::~EventDispatcher()
{
__doCheck();
delete _listeners;
}
int EventDispatcher::addEventListener(eventType et, EventCallback cb)
{
__doCheck();
if (!_listeners)
_listeners = new listeners;
_lastID++;
/*
#ifdef OX_DEBUG
for (listeners::iterator i = _listeners->begin(); i != _listeners->end(); ++i)
{
const listener& ls = *i;
if (ls.type == et && cb == ls.cb)
{
OX_ASSERT(!"you are already added this event listener");
}
}
#endif
*/
listener ls;
ls.type = et;
ls.cb = cb;
ls.id = _lastID;
_listeners->push_back(ls);
return ls.id;
}
void EventDispatcher::removeEventListener(int id)
{
__doCheck();
OX_ASSERT(_listeners);
if (!_listeners)
return;
for (size_t size = _listeners->size(), i = 0; i != size; ++i)
{
const listener &ls = _listeners->at(i);
if (ls.id == id)
{
_listeners->erase(_listeners->begin() + i);
break;
}
}
}
void EventDispatcher::removeEventListener(eventType et, EventCallback cb)
{
__doCheck();
//OX_ASSERT(_listeners);
if (!_listeners)
return;
for (size_t size = _listeners->size(), i = 0; i != size; ++i)
{
const listener& ls = _listeners->at(i);
if (ls.type == et && cb == ls.cb)
{
_listeners->erase(_listeners->begin() + i);
break;
//OX_ASSERT(hasEventListeners(et, cb) == false);
//--i;
}
}
}
bool EventDispatcher::hasEventListeners(void *CallbackThis)
{
__doCheck();
if (!_listeners)
return false;
for (size_t size = _listeners->size(), i = 0; i != size; ++i)
{
const listener& ls = _listeners->at(i);
if (ls.cb.p_this == CallbackThis)
return true;
}
return false;
}
bool EventDispatcher::hasEventListeners(eventType et, EventCallback cb)
{
__doCheck();
if (!_listeners)
return false;
for (size_t size = _listeners->size(), i = 0; i != size; ++i)
{
const listener& ls = _listeners->at(i);
if (ls.type == et && cb == ls.cb)
return true;
}
return false;
}
void EventDispatcher::removeEventListeners(void *CallbackThis)
{
__doCheck();
if (!_listeners)
return;
for (size_t i = 0; i < _listeners->size(); ++i)
{
const listener& ls = _listeners->at(i);
if (ls.cb.p_this == CallbackThis)
{
_listeners->erase(_listeners->begin() + i);
//OX_ASSERT(hasEventListeners(CallbackThis) == false);
--i;
}
}
}
void EventDispatcher::removeAllEventListeners()
{
delete _listeners;
_listeners = 0;
}
void EventDispatcher::dispatchEvent(Event *event)
{
__doCheck();
if (!_listeners)
return;
size_t size = _listeners->size();
listenerbase* copy = (listenerbase*)alloca(sizeof(listenerbase) * size);
size_t num = 0;
for (size_t i = 0; i != size; ++i)
{
listener& ls = _listeners->at(i);
if (ls.type != event->type)
continue;
new(copy + num) listenerbase(ls);
++num;
}
for (size_t i = 0; i != num; ++i)
{
listenerbase& ls = copy[i];
event->currentTarget = this;
ls.cb(event);
if (event->stopsImmediatePropagation)
break;
}
for (size_t i = 0; i != num; ++i)
{
listenerbase& ls = copy[i];
ls.~listenerbase();
}
}
} | [
"am98pln@gmail.com"
] | am98pln@gmail.com |
d967e9ce296f1e9863ada34d4923e275531e31aa | 9ce1f0f2652f81903f31452451bfd17ae6873623 | /Code/Tools/FBuild/FBuildCore/FBuild.cpp | 8f51ef7c788f1489e9edf36fcc2bc2d3508e4aa3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-other-permissive"
] | permissive | missmah/fastbuild | 7044b4f62b696956dbd1651b12262aa0bd052e06 | 310dcff973cf8e6902b2608cf72dbf928fe89e9c | refs/heads/master | 2021-01-19T16:50:38.890910 | 2017-04-14T19:27:44 | 2017-04-14T19:27:44 | 88,291,891 | 1 | 2 | null | 2019-10-30T04:37:30 | 2017-04-14T18:17:37 | C++ | UTF-8 | C++ | false | false | 21,962 | cpp | // FBuild - the main application
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include "Tools/FBuild/FBuildCore/PrecompiledHeader.h"
#include "FBuild.h"
#include "FLog.h"
#include "BFF/BFFMacros.h"
#include "BFF/BFFParser.h"
#include "BFF/Functions/Function.h"
#include "Cache/ICache.h"
#include "Cache/Cache.h"
#include "Cache/CachePlugin.h"
#include "Graph/Node.h"
#include "Graph/NodeGraph.h"
#include "Graph/NodeProxy.h"
#include "Helpers/Report.h"
#include "Protocol/Client.h"
#include "Protocol/Protocol.h"
#include "WorkerPool/JobQueue.h"
#include "WorkerPool/WorkerThread.h"
#include "Core/Env/Assert.h"
#include "Core/Env/Env.h"
#include "Core/Env/Types.h"
#include "Core/FileIO/FileIO.h"
#include "Core/FileIO/FileStream.h"
#include "Core/FileIO/MemoryStream.h"
#include "Core/Math/xxHash.h"
#include "Core/Mem/SmallBlockAllocator.h"
#include "Core/Process/SystemMutex.h"
#include "Core/Profile/Profile.h"
#include "Core/Strings/AStackString.h"
#include "Core/Tracing/Tracing.h"
#include <stdio.h>
#include <time.h>
//#define DEBUG_CRT_MEMORY_USAGE // Uncomment this for (very slow) detailed mem checks
#ifdef DEBUG_CRT_MEMORY_USAGE
#include <crtdbg.h>
#endif
// Static
//------------------------------------------------------------------------------
/*static*/ bool FBuild::s_StopBuild( false );
// CONSTRUCTOR - FBuild
//------------------------------------------------------------------------------
FBuild::FBuild( const FBuildOptions & options )
: m_DependencyGraph( nullptr )
, m_JobQueue( nullptr )
, m_Client( nullptr )
, m_Cache( nullptr )
, m_LastProgressOutputTime( 0.0f )
, m_LastProgressCalcTime( 0.0f )
, m_SmoothedProgressCurrent( 0.0f )
, m_SmoothedProgressTarget( 0.0f )
, m_WorkerList( 0, true )
, m_EnvironmentString( nullptr )
, m_EnvironmentStringSize( 0 )
, m_ImportedEnvironmentVars( 0, true )
{
#ifdef DEBUG_CRT_MEMORY_USAGE
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF |
_CRTDBG_CHECK_ALWAYS_DF | //_CRTDBG_CHECK_EVERY_16_DF |
_CRTDBG_CHECK_CRT_DF |
_CRTDBG_DELAY_FREE_MEM_DF |
_CRTDBG_LEAK_CHECK_DF );
#endif
m_Macros = FNEW( BFFMacros() );
// store all user provided options
m_Options = options;
// track the old working dir to restore if modified (mainly for unit tests)
VERIFY( FileIO::GetCurrentDir( m_OldWorkingDir ) );
// check for cache environment variable to use as default
AStackString<> cachePath;
if ( Env::GetEnvVariable( "FASTBUILD_CACHE_PATH", cachePath ) )
{
if ( cachePath.IsEmpty() == false )
{
SetCachePath( cachePath );
}
}
// poke options where required
FLog::SetShowInfo( m_Options.m_ShowInfo );
FLog::SetShowErrors( m_Options.m_ShowErrors );
FLog::SetShowProgress( m_Options.m_ShowProgress );
FLog::SetMonitorEnabled( m_Options.m_EnableMonitor );
Function::Create();
}
// DESTRUCTOR
//------------------------------------------------------------------------------
FBuild::~FBuild()
{
PROFILE_FUNCTION
Function::Destroy();
FDELETE m_Macros;
FDELETE m_DependencyGraph;
FDELETE m_Client;
FREE( m_EnvironmentString );
if ( m_Cache )
{
m_Cache->Shutdown();
FDELETE m_Cache;
}
// restore the old working dir to restore
ASSERT( !m_OldWorkingDir.IsEmpty() );
if ( !FileIO::SetCurrentDir( m_OldWorkingDir ) )
{
FLOG_ERROR( "Failed to restore working dir: '%s' (error: %u)", m_OldWorkingDir.Get(), Env::GetLastErr() );
}
}
// Initialize
//------------------------------------------------------------------------------
bool FBuild::Initialize( const char * nodeGraphDBFile )
{
PROFILE_FUNCTION
// handle working dir
if ( !FileIO::SetCurrentDir( m_Options.GetWorkingDir() ) )
{
FLOG_ERROR( "Failed to set working dir: '%s' (error: %u)", m_Options.GetWorkingDir().Get(), Env::GetLastErr() );
return false;
}
const char * bffFile = m_Options.m_ConfigFile.IsEmpty() ? GetDefaultBFFFileName()
: m_Options.m_ConfigFile.Get();
if ( nodeGraphDBFile != nullptr )
{
m_DependencyGraphFile = nodeGraphDBFile;
}
else
{
m_DependencyGraphFile = bffFile;
if ( m_DependencyGraphFile.EndsWithI( ".bff" ) )
{
m_DependencyGraphFile.SetLength( m_DependencyGraphFile.GetLength() - 4 );
}
m_DependencyGraphFile += ".fdb";
}
SmallBlockAllocator::SetSingleThreadedMode( true );
m_DependencyGraph = NodeGraph::Initialize( bffFile, m_DependencyGraphFile.Get() );
SmallBlockAllocator::SetSingleThreadedMode( false );
if ( m_DependencyGraph == nullptr )
{
return false;
}
// if the cache is enabled, make sure the path is set and accessible
if ( m_Options.m_UseCacheRead || m_Options.m_UseCacheWrite )
{
if ( !m_CachePluginDLL.IsEmpty() )
{
m_Cache = FNEW( CachePlugin( m_CachePluginDLL ) );
}
else
{
m_Cache = FNEW( Cache() );
}
if ( m_Cache->Init( m_CachePath ) == false )
{
m_Options.m_UseCacheRead = false;
m_Options.m_UseCacheWrite = false;
}
}
//
// create the connection management system if we might need it
if ( m_Options.m_AllowDistributed )
{
Array< AString > workers;
if ( m_WorkerList.IsEmpty() )
{
// check for workers through brokerage
// TODO:C This could be moved out of the main code path
m_WorkerBrokerage.FindWorkers( workers );
}
else
{
workers = m_WorkerList;
}
if ( workers.IsEmpty() )
{
FLOG_WARN( "No workers available - Distributed compilation disabled" );
m_Options.m_AllowDistributed = false;
}
else
{
OUTPUT( "Distributed Compilation : %u Workers in pool\n", workers.GetSize() );
m_Client = FNEW( Client( workers ) );
}
}
return true;
}
// Build
//------------------------------------------------------------------------------
bool FBuild::Build( const AString & target )
{
ASSERT( !target.IsEmpty() );
Array< AString > targets( 1, false );
targets.Append( target );
return Build( targets );
}
// Build
//------------------------------------------------------------------------------
bool FBuild::Build( const Array< AString > & targets )
{
ASSERT( !targets.IsEmpty() );
// Get the nodes for all the targets
const size_t numTargets = targets.GetSize();
Dependencies nodes( numTargets, 0 );
for ( size_t i=0; i<numTargets; ++i )
{
const AString & target = targets[ i ];
// get the node being requested (search for exact match, to find aliases etc first)
Node * node = m_DependencyGraph->FindNodeInternal( target );
if ( node == nullptr )
{
// failed to find the node, try looking for a fully pathed equivalent
node = m_DependencyGraph->FindNode( target );
}
if ( node == nullptr )
{
FLOG_ERROR( "Unknown build target '%s'", target.Get() );
// Gets the 5 targets with minimal distance to user input
Array< NodeGraph::NodeWithDistance > nearestNodes( 5, false );
m_DependencyGraph->FindNearestNodesInternal( target, nearestNodes, 0xFFFFFFFF );
if ( false == nearestNodes.IsEmpty() )
{
FLOG_WARN( "Did you mean one of these ?" );
const size_t count = nearestNodes.GetSize();
for ( size_t j = 0 ; j < count ; ++j )
FLOG_WARN( " %s", nearestNodes[j].m_Node->GetName().Get() );
}
return false;
}
nodes.Append( Dependency( node ) );
}
// create a temporary node, not hooked into the DB
NodeProxy proxy( AStackString< 32 >( "*proxy*" ) );
proxy.m_StaticDependencies = nodes;
// build all targets in one sweep
bool result = Build( &proxy );
// output per-target results
for ( size_t i=0; i<targets.GetSize(); ++i )
{
bool nodeResult = ( nodes[ i ].GetNode()->GetState() == Node::UP_TO_DATE );
OUTPUT( "FBuild: %s: %s\n", nodeResult ? "OK" : "Error: BUILD FAILED", targets[ i ].Get() );
}
return result;
}
// SaveDependencyGraph
//------------------------------------------------------------------------------
bool FBuild::SaveDependencyGraph( const char * nodeGraphDBFile ) const
{
ASSERT( nodeGraphDBFile != nullptr );
PROFILE_FUNCTION
FLOG_INFO( "Saving DepGraph '%s'", nodeGraphDBFile );
Timer t;
// serialize into memory first
MemoryStream memoryStream( 32 * 1024 * 1024, 8 * 1024 * 1024 );
m_DependencyGraph->Save( memoryStream, nodeGraphDBFile );
// We'll save to a tmp file first
AStackString<> tmpFileName( nodeGraphDBFile );
tmpFileName += ".tmp";
// Ensure output dir exists where we'll save the DB
const char * lastSlash = tmpFileName.FindLast( '/' );
lastSlash = lastSlash ? lastSlash : tmpFileName.FindLast( '\\' );
if ( lastSlash )
{
AStackString<> pathOnly( tmpFileName.Get(), lastSlash );
if ( FileIO::EnsurePathExists( pathOnly ) == false )
{
FLOG_ERROR( "Failed to create directory for DepGraph saving '%s'", pathOnly.Get() );
return false;
}
}
// try to open the file
FileStream fileStream;
if ( fileStream.Open( tmpFileName.Get(), FileStream::WRITE_ONLY ) == false )
{
// failing to open the dep graph for saving is a serious problem
FLOG_ERROR( "Failed to open DepGraph for saving '%s'", nodeGraphDBFile );
return false;
}
// write in-memory serialized data to disk
if ( fileStream.Write( memoryStream.GetData(), memoryStream.GetSize() ) != memoryStream.GetSize() )
{
FLOG_ERROR( "Saving DepGraph FAILED!" );
return false;
}
fileStream.Close();
// rename tmp file
if ( FileIO::FileMove( tmpFileName, AStackString<>( nodeGraphDBFile ) ) == false )
{
FLOG_ERROR( "Failed to rename temp DB file '%s' (%i)", tmpFileName.Get(), Env::GetLastErr() );
return false;
}
FLOG_INFO( "Saving DepGraph Complete in %2.3fs", t.GetElapsed() );
return true;
}
// SaveDependencyGraph
//------------------------------------------------------------------------------
void FBuild::SaveDependencyGraph( IOStream & stream, const char* nodeGraphDBFile ) const
{
m_DependencyGraph->Save( stream, nodeGraphDBFile );
}
// Build
//------------------------------------------------------------------------------
bool FBuild::Build( Node * nodeToBuild )
{
ASSERT( nodeToBuild );
s_StopBuild = false; // allow multiple runs in same process
// create worker threads
m_JobQueue = FNEW( JobQueue( m_Options.m_NumWorkerThreads ) );
m_Timer.Start();
m_LastProgressOutputTime = 0.0f;
m_LastProgressCalcTime = 0.0f;
m_SmoothedProgressCurrent = 0.0f;
m_SmoothedProgressTarget = 0.0f;
FLog::StartBuild();
// create worker dir for main thread build case
if ( m_Options.m_NumWorkerThreads == 0 )
{
WorkerThread::CreateThreadLocalTmpDir();
}
bool stopping( false );
// keep doing build passes until completed/failed
for ( ;; )
{
// process completed jobs
m_JobQueue->FinalizeCompletedJobs( *m_DependencyGraph );
if ( !stopping )
{
// do a sweep of the graph to create more jobs
m_DependencyGraph->DoBuildPass( nodeToBuild );
}
if ( m_Options.m_NumWorkerThreads == 0 )
{
// no local threads - do build directly
WorkerThread::Update();
}
bool complete = ( nodeToBuild->GetState() == Node::UP_TO_DATE ) ||
( nodeToBuild->GetState() == Node::FAILED );
if ( s_StopBuild || complete )
{
if ( stopping == false )
{
// free the network distribution system (if there is one)
FDELETE m_Client;
m_Client = nullptr;
// wait for workers to exit. Can still be building even though we've failed:
// - only 1 failed node propagating up to root while others are not yet complete
// - aborted build, so workers can be incomplete
m_JobQueue->SignalStopWorkers();
stopping = true;
}
}
if ( !stopping )
{
if ( m_Options.m_WrapperChild )
{
SystemMutex wrapperMutex( m_Options.GetMainProcessMutexName().Get() );
if ( wrapperMutex.TryLock() )
{
// parent process has terminated
s_StopBuild = true;
}
}
}
// completely stopped?
if ( stopping && m_JobQueue->HaveWorkersStopped() )
{
break;
}
// Wait until more work to process or time has elapsed
m_JobQueue->MainThreadWait( 500 );
// update progress
UpdateBuildStatus( nodeToBuild );
}
// wrap up/free any jobs that come from the last build pass
m_JobQueue->FinalizeCompletedJobs( *m_DependencyGraph );
FDELETE m_JobQueue;
m_JobQueue = nullptr;
FLog::StopBuild();
// even if the build has failed, we can still save the graph.
// This is desireable because:
// - it will save parsing the bff next time
// - it will record the items that did build, so they won't build again
if ( m_Options.m_SaveDBOnCompletion )
{
SaveDependencyGraph( m_DependencyGraphFile.Get() );
}
// TODO:C Move this into BuildStats
float timeTaken = m_Timer.GetElapsed();
m_BuildStats.m_TotalBuildTime = timeTaken;
m_BuildStats.OnBuildStop( nodeToBuild );
return ( nodeToBuild->GetState() == Node::UP_TO_DATE );
}
// SetEnvironmentString
//------------------------------------------------------------------------------
void FBuild::SetEnvironmentString( const char * envString, uint32_t size, const AString & libEnvVar )
{
FREE( m_EnvironmentString );
m_EnvironmentString = (char *)ALLOC( size + 1 );
m_EnvironmentStringSize = size;
AString::Copy( envString, m_EnvironmentString, size );
m_LibEnvVar = libEnvVar;
}
// ImportEnvironmentVar
//------------------------------------------------------------------------------
bool FBuild::ImportEnvironmentVar( const char * name, bool optional, AString & value, uint32_t & hash )
{
// check if system environment contains the variable
if ( Env::GetEnvVariable( name, value ) == false )
{
if ( !optional )
{
FLOG_ERROR( "Could not import environment variable '%s'", name );
return false;
}
// set the hash to the "missing variable" value of 0
hash = 0;
}
else
{
// compute hash value for actual value
hash = xxHash::Calc32( value );
}
// check if the environment var was already imported
const EnvironmentVarAndHash * it = m_ImportedEnvironmentVars.Begin();
const EnvironmentVarAndHash * const end = m_ImportedEnvironmentVars.End();
while ( it < end )
{
if ( it->GetName() == name )
{
// check if imported environment changed since last import
if ( it->GetHash() != hash )
{
FLOG_ERROR( "Overwriting imported environment variable '%s' with a different value = '%s'",
name, value.Get() );
return false;
}
// skip registration when already imported with same hash value
return true;
}
it++;
}
// import new variable name with its hash value
const EnvironmentVarAndHash var( name, hash );
m_ImportedEnvironmentVars.Append( var );
return true;
}
// GetLibEnvVar
//------------------------------------------------------------------------------
void FBuild::GetLibEnvVar( AString & value ) const
{
// has environment been overridden in BFF?
if ( m_EnvironmentString )
{
// use overridden LIB path (which maybe empty)
value = m_LibEnvVar;
}
else
{
// use real environment LIB path
Env::GetEnvVariable( "LIB", value );
}
}
// OnBuildError
//------------------------------------------------------------------------------
/*static*/ void FBuild::OnBuildError()
{
if ( FBuild::Get().GetOptions().m_StopOnFirstError )
{
s_StopBuild = true;
}
}
// UpdateBuildStatus
//------------------------------------------------------------------------------
void FBuild::UpdateBuildStatus( const Node * node )
{
PROFILE_FUNCTION
if ( FBuild::Get().GetOptions().m_ShowProgress == false )
{
if ( FBuild::Get().GetOptions().m_EnableMonitor == false )
{
return;
}
}
const float OUTPUT_FREQUENCY( 1.0f );
const float CALC_FREQUENCY( 5.0f );
float timeNow = m_Timer.GetElapsed();
bool doUpdate = ( ( timeNow - m_LastProgressOutputTime ) >= OUTPUT_FREQUENCY );
if ( doUpdate == false )
{
return;
}
// recalculate progress estimate?
if ( ( timeNow - m_LastProgressCalcTime ) >= CALC_FREQUENCY )
{
PROFILE_SECTION( "CalcPogress" )
FBuildStats & bs = m_BuildStats;
bs.m_NodeTimeProgressms = 0;
bs.m_NodeTimeTotalms = 0;
m_DependencyGraph->UpdateBuildStatus( node, bs.m_NodeTimeProgressms, bs.m_NodeTimeTotalms );
m_LastProgressCalcTime = m_Timer.GetElapsed();
// calculate percentage
float doneRatio = (float)( (double)bs.m_NodeTimeProgressms / (double)bs.m_NodeTimeTotalms );
// don't allow it to reach 100% (handles rounding inaccuracies)
float donePerc = Math::Min< float >( doneRatio * 100.0f, 99.9f );
// don't allow progress to go backwards
m_SmoothedProgressTarget = Math::Max< float >( donePerc, m_SmoothedProgressTarget );
}
m_SmoothedProgressCurrent = ( 0.5f * m_SmoothedProgressCurrent ) + ( m_SmoothedProgressTarget * 0.5f );
// get node counts
uint32_t numJobs = 0;
uint32_t numJobsActive = 0;
uint32_t numJobsDist = 0;
uint32_t numJobsDistActive = 0;
if ( JobQueue::IsValid() )
{
JobQueue::Get().GetJobStats( numJobs, numJobsActive, numJobsDist, numJobsDistActive );
}
if ( FBuild::Get().GetOptions().m_ShowProgress )
{
FLog::OutputProgress( timeNow, m_SmoothedProgressCurrent, numJobs, numJobsActive, numJobsDist, numJobsDistActive );
}
FLOG_MONITOR( "PROGRESS_STATUS %f \n", m_SmoothedProgressCurrent );
m_LastProgressOutputTime = timeNow;
}
// GetDefaultBFFFileName
//------------------------------------------------------------------------------
/*static*/ const char * FBuild::GetDefaultBFFFileName()
{
return "fbuild.bff";
}
// SetCachePath
//------------------------------------------------------------------------------
void FBuild::SetCachePath( const AString & path )
{
m_CachePath = path;
}
// GetCacheFileName
//------------------------------------------------------------------------------
void FBuild::GetCacheFileName( uint64_t keyA, uint32_t keyB, uint64_t keyC, uint64_t keyD, AString & path ) const
{
// cache version - bump if cache format is changed
static const int cacheVersion( 8 );
// format example: 2377DE32AB045A2D_FED872A1_AB62FEAA23498AAC-32A2B04375A2D7DE.7
path.Format( "%016llX_%08X_%016llX-%016llX.%u", keyA, keyB, keyC, keyD, cacheVersion );
}
// DisplayTargetList
//------------------------------------------------------------------------------
void FBuild::DisplayTargetList() const
{
OUTPUT( "FBuild: List of available targets\n" );
const size_t totalNodes = m_DependencyGraph->GetNodeCount();
for ( size_t i = 0; i < totalNodes; ++i )
{
Node * node = m_DependencyGraph->GetNodeByIndex( i );
bool displayName = false;
switch ( node->GetType() )
{
case Node::PROXY_NODE: ASSERT( false ); break;
case Node::COPY_FILE_NODE: break;
case Node::DIRECTORY_LIST_NODE: break;
case Node::EXEC_NODE: break;
case Node::FILE_NODE: break;
case Node::LIBRARY_NODE: break;
case Node::OBJECT_NODE: break;
case Node::ALIAS_NODE: displayName = true; break;
case Node::EXE_NODE: break;
case Node::CS_NODE: break;
case Node::UNITY_NODE: displayName = true; break;
case Node::TEST_NODE: break;
case Node::COMPILER_NODE: break;
case Node::DLL_NODE: break;
case Node::VCXPROJECT_NODE: break;
case Node::OBJECT_LIST_NODE: displayName = true; break;
case Node::COPY_DIR_NODE: break;
case Node::SLN_NODE: break;
case Node::REMOVE_DIR_NODE: break;
case Node::XCODEPROJECT_NODE: break;
case Node::NUM_NODE_TYPES: ASSERT( false ); break;
}
if ( displayName )
{
OUTPUT( "\t%s\n", node->GetName().Get() );
}
}
}
//------------------------------------------------------------------------------
| [
"franta.fulin@gmail.com"
] | franta.fulin@gmail.com |
afa3ba926bc6a429b4d3d29dbc84898a68b18500 | 8f3ef878f138146a9df34440103d45607afeb48e | /Qt/Canvas/MainWindow.h | f19fa6f91c9a0665a5f9cca8a84124db1ae17b77 | [] | no_license | afester/CodeSamples | aa67a8d6f5c451dc92131a8722f301d026f5a894 | 10a2675f77e779d793d63e973672548aa263597b | refs/heads/main | 2023-01-05T06:45:52.130668 | 2022-12-23T21:36:36 | 2022-12-23T21:36:36 | 8,028,224 | 10 | 11 | null | 2022-10-02T18:53:29 | 2013-02-05T11:57:35 | Java | UTF-8 | C++ | false | false | 633 | h | /**
* This work is licensed under the Creative Commons Attribution 3.0 Unported
* License. To view a copy of this license, visit
* http://creativecommons.org/licenses/by/3.0/ or send a letter to Creative
* Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA.
*/
#include <QMainWindow>
class Ui_MainWindow;
class Canvas;
class MainWindow : public QMainWindow {
Q_OBJECT
public:
MainWindow(QWidget* parent);
~MainWindow();
Ui_MainWindow* ui;
Canvas* canvas;
public slots:
void actionPrint();
void actionLine();
void actionCircle();
void actionRectangle();
};
| [
"Andreas.Fester@gmx.de"
] | Andreas.Fester@gmx.de |
670f419a089b0fc0015986991832c21ac74b99c9 | f180cdea1a82e9656c793a667081783029378b8e | /Derivator/sources/tree_dot_converter.cpp | 9367b89d5c18e6e9c81597050632eb853ae3a301 | [] | no_license | uberpup/industrial-programming-course | 21a09b600ac1c18c70c6669a2e615e103d48e171 | 50dec017ca2eb883e6af882c39dfe0418ea43ae4 | refs/heads/master | 2020-07-26T07:32:57.699106 | 2020-01-04T14:26:45 | 2020-01-04T14:26:45 | 208,578,669 | 0 | 0 | null | 2020-01-04T14:26:46 | 2019-09-15T10:41:06 | C++ | UTF-8 | C++ | false | false | 1,708 | cpp | #include "tree_dot_converter.h"
TreeDotConverter::TreeDotConverter(std::string filename) :
filename(std::move(filename)) {}
TreeDotConverter::~TreeDotConverter() {}
void TreeDotConverter::PrintTree(const Derivator& derivator) {
file = std::fopen(filename.c_str(), "w");
fprintf(file, "%s\n", "digraph G {");
assert(derivator.root_ != nullptr);
if (derivator.root_->func == 0) {
fprintf(file, "node%zu [label = root];\n", derivator.root_.get());
} else {
fprintf(file, "node%zu [label = \"%s\"];\n", derivator.root_.get(),
FUNC_NAMES[derivator.root_->func].c_str());
}
Traverse(derivator.root_);
fprintf(file, "\n%s", "}");
fclose(file);
}
void TreeDotConverter::Print(const std::shared_ptr<Derivator::Node>& current_node,
const std::shared_ptr<Derivator::Node>& parent) {
fprintf(file, "node%zu [label = \"", current_node.get());
if (!current_node->is_const || current_node->func > 0) {
fprintf(file, "%s\"]\n", FUNC_NAMES[current_node->func].c_str());
} else {
fprintf(file, "%d\"]\n", current_node->value);
}
fprintf(file, "node%zu -> node%zu;\n", parent.get(), current_node.get());
fflush(file);
}
void TreeDotConverter::Traverse(const std::shared_ptr<Derivator::Node>& current_node) {
if (current_node->left != nullptr) {
Print(current_node->left, current_node);
Traverse(current_node->left);
}
if (current_node->right != nullptr) {
Print(current_node->right, current_node);
Traverse(current_node->right);
}
if (current_node->left == nullptr && current_node->right == nullptr) {
return;
}
} | [
"tochilin.vn@phystech.edu"
] | tochilin.vn@phystech.edu |
276ed172ba95ca61cab0b2981ea9cd169e3e39f2 | 16137a5967061c2f1d7d1ac5465949d9a343c3dc | /cpp_code/meta/fib-slow.hpp | c41fa7fd7ff2e4c36579552b331d5c0dbcd304cf | [] | no_license | MIPT-ILab/cpp-lects-rus | 330f977b93f67771b118ad03ee7b38c3615deef3 | ba8412dbf4c8f3bee7c6344a89e0780ee1dd38f2 | refs/heads/master | 2022-07-28T07:36:59.831016 | 2022-07-20T08:34:26 | 2022-07-20T08:34:26 | 104,261,623 | 27 | 4 | null | 2021-02-04T21:39:23 | 2017-09-20T19:56:44 | TeX | UTF-8 | C++ | false | false | 460 | hpp | namespace Slower
{
template <unsigned TreePos, unsigned N>
struct FibSlower
{
enum
{
value = FibSlower<TreePos, N - 1>::value + FibSlower<TreePos + (1 << N), N - 2>::value
};
};
template <unsigned TreePos>
struct FibSlower<TreePos, 1>
{
enum
{
value = 1
};
};
template <unsigned TreePos>
struct FibSlower<TreePos, 0>
{
enum
{
value = 0
};
};
template <unsigned N>
using Fibonacci = FibSlower<0, N>;
}
| [
"konstantin.vladimirov@gmail.com"
] | konstantin.vladimirov@gmail.com |
678f8b1aa0dde8c824c72298218e5757d73b6334 | 8f58614751bd1eeace81c8b62ca51ea49c474645 | /uva/266/D.cpp | 640903cfa2cec8075d019f25af17776b6db060e2 | [] | no_license | iwiwi/programming-contests | 14d8a0c5739a4c31f1c3a4d90506e478fa4d08b5 | 8909560f9036de8f275f677dec615dc5fa993aff | refs/heads/master | 2021-01-25T04:08:39.627057 | 2015-05-10T13:28:20 | 2015-05-10T13:28:20 | 2,676,087 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,207 | cpp | #include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>
#include <cassert>
using namespace std;
#define all(c) (c).begin(), (c).end()
#define iter(c) __typeof((c).begin())
#define cpresent(c, e) (find(all(c), (e)) != (c).end())
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define tr(c, i) for (iter(c) i = (c).begin(); i != (c).end(); ++i)
#define pb(e) push_back(e)
#define mp(a, b) make_pair(a, b)
int main() {
for (;;) {
int L, W, x, y, R, a, v, s;
cin >> L >> W >> x >> y >> R >> a >> v >> s;
if (L == 0) break;
// L - 2R, W - 2R
x -= R;
y -= R;
double tx = x + cos(a / 180.0 * M_PI) * v * s;
double ty = y + sin(a / 180.0 * M_PI) * v * s;
double tl = L - 2 * R;
double tw = W - 2 * R;
double sx = fmod(tx, tl * 2);
double sy = fmod(ty, tw * 2);
if (sx < 0) sx += tl * 2;
if (sy < 0) sy += tw * 2;
if (sx > tl) sx = tl * 2 - sx;
if (sy > tw) sy = tw * 2 - sy;
printf("%.2f %.2f\n", sx + R, sy + R);
}
return 0;
}
| [
"iw@iwi.tc"
] | iw@iwi.tc |
04e0f357c4185b13cab03f81baa283d46702ab88 | 347ec1a55e81d0c793554cb297d10a3d01184705 | /Mesh.cpp | 6f0a43bb99d78623d7bd4bcb201e5f8e4d67db6f | [] | no_license | hobgreenson/electrophysiology-stimulus | e36a303d0d03573f170f8ef629ee6258ed68b69c | 2fcae6c3fe0d93fa7a5a46d94d7a949235ede23e | refs/heads/master | 2020-05-27T09:38:36.259452 | 2015-08-21T15:09:50 | 2015-08-21T15:09:50 | 30,271,596 | 1 | 0 | null | 2015-08-21T15:09:50 | 2015-02-04T00:02:25 | C++ | UTF-8 | C++ | false | false | 11,653 | cpp | #include "Mesh.h"
Mesh::Mesh(const char* vs_path, const char* fs_path)
: vertex_shader_path_(vs_path),
fragment_shader_path_(fs_path) {
// set transform matrix to identity
GLfloat matrix[16] = {
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0
};
for (int i = 0; i < 16; ++i) {
transform_matrix_[i] = matrix[i];
}
}
Mesh::~Mesh() {
free(vertices_);
free(indices_);
}
/*********** Color ********************************/
void Mesh::color(float R, float G, float B, float A) {
GLubyte color[4];
color[0] = R;
color[1] = G;
color[2] = B;
color[3] = A;
for (int i = 0; i < num_vertices_; ++i) {
vertices_[i].color[0] = color[0];
vertices_[i].color[1] = color[1];
vertices_[i].color[2] = color[2];
vertices_[i].color[3] = color[3];
}
}
/******** Simple spatial transforms *******************************/
void Mesh::translateX(double dx) {
transform_matrix_[12] += dx;
}
void Mesh::translateXmod(double dx, double n) {
transform_matrix_[12] += dx;
if(transform_matrix_[12] > n) {
transform_matrix_[12] -= n;
}
if(transform_matrix_[12] < -n) {
transform_matrix_[12] += n;
}
}
void Mesh::translateY(double dy) {
transform_matrix_[13] += dy;
}
void Mesh::translateYmod(double dy, double n) {
transform_matrix_[13] += dy;
if(transform_matrix_[13] > n) {
transform_matrix_[13] -= n;
}
if(transform_matrix_[13] < -n) {
transform_matrix_[13] += n;
}
}
void Mesh::translateZ(double dz) {
transform_matrix_[14] += dz;
}
void Mesh::centerXY(double x, double y) {
transform_matrix_[12] = x;
transform_matrix_[13] = y;
}
void Mesh::scaleX(double da) {
transform_matrix_[0] *= da;
}
void Mesh::scaleY(double da) {
transform_matrix_[5] *= da;
}
void Mesh::scaleXY(double da) {
scaleX(da);
scaleY(da);
}
void Mesh::resetScale() {
transform_matrix_[0] = 1.0;
transform_matrix_[5] = 1.0;
}
/********* RECTANGLE ********************************/
void Mesh::rect(float lower_x, float lower_y,
float upper_x, float upper_y) {
makeVerticesRect(lower_x, lower_y,
upper_x, upper_y);
makeIndicesRect();
}
void Mesh::makeVerticesRect(float lower_x, float lower_y,
float upper_x, float upper_y) {
num_vertices_ = 4;
vertices_ = (Vertex2D*) malloc(num_vertices_ * sizeof(Vertex2D));
vertices_[0].position[0] = lower_x;
vertices_[0].position[1] = lower_y;
vertices_[1].position[0] = upper_x;
vertices_[1].position[1] = lower_y;
vertices_[2].position[0] = upper_x;
vertices_[2].position[1] = upper_y;
vertices_[3].position[0] = lower_x;
vertices_[3].position[1] = upper_y;
}
void Mesh::makeIndicesRect() {
num_indices_ = 6;
indices_ = (GLushort*) malloc(num_indices_ * sizeof(GLushort));
// first triangle
indices_[0] = 0;
indices_[1] = 1;
indices_[2] = 2;
// second triangle
indices_[3] = 0;
indices_[4] = 2;
indices_[5] = 3;
}
/********* CIRCLE ********************************/
void Mesh::circle(float radius, float cx, float cy) {
makeVerticesCircle(radius, cx, cy);
makeIndicesCircle();
}
void Mesh::makeVerticesCircle(float radius, float cx, float cy) {
/* by default we make 10 degree steps and
this makes a fairly hi-res circle.
*/
GLfloat da = 10.0;
num_vertices_ = 2 + (int)(360 / da);
vertices_ = (Vertex2D*) malloc(num_vertices_ * sizeof(Vertex2D));
// first vertex is at the origin
vertices_[0].position[0] = 0.0;
vertices_[0].position[1] = 0.0;
GLfloat x, y;
for (int i = 0; i < num_vertices_; ++i) {
x = cx + radius * cos(i * M_PI * da / 180.0);
y = cy + radius * sin(i * M_PI * da / 180.0);
vertices_[i].position[0] = x;
vertices_[i].position[1] = y;
}
}
void Mesh::makeIndicesCircle() {
num_indices_ = 3 * (num_vertices_ - 1);
indices_ = (GLushort*) malloc(num_indices_ * sizeof(GLushort));
int j = 1;
for (int i = 0; i < num_indices_ - 1; i += 3) {
indices_[i] = 0;
indices_[i + 1] = j;
indices_[i + 2] = (j + 1) % num_vertices_;
j++;
}
}
/******************** VERTICAL GRATING ****************************/
void Mesh::rotatingGrating(int periods) {
makeRotatingGratingVertices(periods);
makeRotatingGratingIndices(periods);
}
void Mesh::linearGrating(int periods) {
makeLinearGratingVertices(periods);
makeLinearGratingIndices(periods);
}
void Mesh::makeLinearGratingVertices(int periods) {
/* this is a variation on the function "makeVertices()"
that allows for simulation of a linear grating presented
below the fish. The real magic happens in the vertex shader.
*/
GLubyte white[4] = {0, 0, 150, 1};
GLubyte black[4] = {0, 0, 0, 1};
GLubyte* color;
int num_squares = 3 * 2 * periods;
num_vertices_ = 2 * 4 * num_squares;
vertices_ = (Vertex2D*) malloc(num_vertices_ * sizeof(Vertex2D));
float w_step;
int N;
if (periods == 0) {
w_step = 6;
N = 1;
} else {
w_step = 1.0 / (float)periods;
N = 3 * 2 * periods;
}
int vi = 0;
for (int i = 0; i <= N; ++i) {
if (i == 0 || i == N) {
vertices_[vi + 0].position[0] = -3 + i * w_step;
vertices_[vi + 0].position[1] = -1;
vertices_[vi + 1].position[0] = -3 + i * w_step;
vertices_[vi + 1].position[1] = 1;
if (periods == 0) {
color = white;
} else {
color = (i == 0) ? white : black;
}
for (int ii = 0; ii < 4; ++ii) {
vertices_[vi + 0].color[ii] = color[ii];
}
for (int ii = 0; ii < 4; ++ii) {
vertices_[vi + 1].color[ii] = color[ii];
}
vi += 2;
} else {
for (int ii = 0; ii < 4; ++ii) {
vertices_[vi + ii].position[0] = -3 + i * w_step;
}
vertices_[vi + 0].position[1] = -1;
vertices_[vi + 1].position[1] = 1;
vertices_[vi + 2].position[1] = -1;
vertices_[vi + 3].position[1] = 1;
color = i % 2 ? white : black;
for (int ii = 0; ii < 4; ++ii) {
vertices_[vi + 0].color[ii] = color[ii];
}
for (int ii = 0; ii < 4; ++ii) {
vertices_[vi + 1].color[ii] = color[ii];
}
color = i % 2 ? black : white;
for (int ii = 0; ii < 4; ++ii) {
vertices_[vi + 2].color[ii] = color[ii];
}
for (int ii = 0; ii < 4; ++ii) {
vertices_[vi + 3].color[ii] = color[ii];
}
vi += 4;
}
}
int ii = vi - 1, jj = vi;
Vertex2D my_v;
while (ii >= 0) {
my_v = vertices_[ii--];
my_v.position[1] *= 2;
vertices_[jj++] = my_v;
}
}
void Mesh::makeRotatingGratingVertices(int periods) {
// each stripe of the grating will have color black or white
GLubyte white[4] = {0, 0, 150, 1};
GLubyte black[4] = {0, 0, 0/*100*/, 1};
GLubyte* color;
int num_squares = 3 * 2 * periods;
num_vertices_ = 4 * num_squares;
// allocate an array of vertex structs
vertices_ = (Vertex2D*) malloc(num_vertices_ * sizeof(Vertex2D));
// set step size along x-axis
float x_step;
int N;
if (periods == 0) {
x_step = 6;
N = 1;
} else {
x_step = 1.0 / (float)periods;
N = 3 * 2 * periods;
}
int vi = 0;
for (int i = 0; i <= N; ++i) {
if (i == 0 || i == N) {
vertices_[vi + 0].position[0] = -3 + i * x_step;
vertices_[vi + 0].position[1] = -1;
vertices_[vi + 1].position[0] = -3 + i * x_step;
vertices_[vi + 1].position[1] = 1;
if(periods == 0) {
color = white;
} else {
color = (i == 0) ? white : black;
}
for (int ii = 0; ii < 4; ++ii) {
vertices_[vi + 0].color[ii] = color[ii];
}
for (int ii = 0; ii < 4; ++ii) {
vertices_[vi + 0].color[ii] = color[ii];
}
vi += 2;
} else {
for (int ii = 0; ii < 4; ++ii) {
vertices_[vi + ii].position[0] = -3 + i * x_step;
}
vertices_[vi + 0].position[1] = -1;
vertices_[vi + 1].position[1] = 1;
vertices_[vi + 2].position[1] = -1;
vertices_[vi + 3].position[1] = 1;
color = (i % 2) ? white : black;
for (int ii = 0; ii < 4; ++ii) {
vertices_[vi + 0].color[ii] = color[ii];
}
for (int ii = 0; ii < 4; ++ii) {
vertices_[vi + 1].color[ii] = color[ii];
}
color = (i % 2) ? black : white;
for (int ii = 0; ii < 4; ++ii) {
vertices_[vi + 2].color[ii] = color[ii];
}
for (int ii = 0; ii < 4; ++ii) {
vertices_[vi + 3].color[ii] = color[ii];
}
vi += 4;
}
}
}
void Mesh::makeRotatingGratingIndices(int periods) {
const int vertices_per_rectangle = 4;
const int indices_per_rectangle = 6;
int num_rects = indices_per_rectangle * periods;
num_indices_ = indices_per_rectangle * num_rects;
indices_ = (GLushort*) malloc(num_indices_ * sizeof(GLushort));
int vi = 0, ii = 0, N;
N = (periods > 0) ? indices_per_rectangle * periods : 1;
for (int i = 0; i < N; ++i) {
indices_[ii + 0] = vi;
indices_[ii + 1] = vi + 2;
indices_[ii + 2] = vi + 3;
indices_[ii + 3] = vi;
indices_[ii + 4] = vi + 3;
indices_[ii + 5] = vi + 1;
vi += vertices_per_rectangle;
ii += indices_per_rectangle;
}
}
void Mesh::makeLinearGratingIndices(int periods) {
const int vertices_per_rectangle = 4;
const int indices_per_rectangle = 6;
int num_squares = indices_per_rectangle * periods;
num_indices_ = 2 * indices_per_rectangle * num_squares;
indices_ = (GLushort*) malloc(num_indices_ * sizeof(GLushort));
int vi = 0, ii = 0, N;
N = (periods > 0) ? indices_per_rectangle * periods : 1;
for (int i = 0; i < N; ++i) {
indices_[ii + 0] = vi;
indices_[ii + 1] = vi + 2;
indices_[ii + 2] = vi + 3;
indices_[ii + 3] = vi;
indices_[ii + 4] = vi + 3;
indices_[ii + 5] = vi + 1;
vi += vertices_per_rectangle;
ii += indices_per_rectangle;
}
for (int i = N; i < 2 * N; ++i) {
indices_[ii + 0] = vi;
indices_[ii + 1] = vi + 3;
indices_[ii + 2] = vi + 2;
indices_[ii + 3] = vi;
indices_[ii + 4] = vi + 1;
indices_[ii + 5] = vi + 3;
vi += vertices_per_rectangle;
ii += indices_per_rectangle;
}
}
| [
"m.hobson.green@gmail.com"
] | m.hobson.green@gmail.com |
727d9325b96507e69279b3f598819c892b4e50a1 | 831e7458aeae4c3bedd56ef49eb412915a83be8c | /utils/frisoutil.cpp | 6d07b31d6b072ab7c30617da816cfb88b64e9c9b | [] | no_license | frankiegu/WriterFly | 2510dea04fd3218854fa14fa76235b0ac1efdc36 | 6680b93eee34901dadbf4bd11a324909d14fd0f5 | refs/heads/master | 2020-04-29T07:14:37.060475 | 2019-03-13T07:55:08 | 2019-03-13T07:55:08 | 175,945,175 | 2 | 0 | null | 2019-03-16T08:17:59 | 2019-03-16T08:17:59 | null | UTF-8 | C++ | false | false | 1,683 | cpp | #include "frisoutil.h"
FrisoUtil::FrisoUtil()
{
inited = false;
initing = false;
valid = true;
}
FrisoUtil::~FrisoUtil()
{
Destructor();
}
QStringList FrisoUtil::WordSegment(QString _text)
{
Q_UNUSED(_text);
#if defined(Q_OS_WIN)
if (!valid)
return sList;
if (!inited)
{
init();
if (inited == false) // 初始化失败
{
QStringList list;
int len = _text.length();
for (int i = 0; i < len; i++)
list.append(_text.mid(i, 1));
return list;
}
}
if (_text == _recent) return sList;
_recent = _text;
friso_task_t task = friso_new_task();
fstring text = _text.toUtf8().data();
friso_set_text(task, text);
sList.clear();
while ( (friso_next(friso, config, task)) != nullptr )
{
sList.append(task->hits->word);
}
friso_free_task(task);
#endif
return sList;
}
void FrisoUtil::Destructor()
{
#if defined(Q_OS_WIN)
friso_free_config(config);
friso_free(friso);
#endif
}
bool FrisoUtil::init()
{
#if defined(Q_OS_Android)
initing = true;
valid = false;
#elif defined(Q_OS_WIN)
if (initing) return false;
initing = true;
char pa[1000] = "";
strcpy(pa, QApplication::applicationDirPath().toLocal8Bit().data());
strcat(pa, "/tools/friso/friso.ini");
fstring _ifile = pa;
friso = friso_new();
config = friso_new_config();
if (friso_init_from_ifile(friso, config, _ifile) != 1) {
qDebug() << "fail to initialize friso and config.";
return initing = false;
}
initing = false;
inited = true;
#endif
return true;
}
| [
"wxy19980615@gmail.com"
] | wxy19980615@gmail.com |
9bf34289e7ab442b22cb72c6c1dac21db7cbcfc9 | 33d33eb0a459f8fd5f3fbd5f3e2ff95cbb804f64 | /40.combination-sum-ii.73403291.ac.cpp | 816fb5c08882b1450e8bafb4564b6f8412c7ab7e | [] | no_license | wszk1992/LeetCode-Survival-Notes | 7b4b7c9b1a5b7251b8053111510e2cefa06a0390 | 01f01330964f5c2269116038d0dde0370576f1e4 | refs/heads/master | 2021-01-01T17:59:32.945290 | 2017-09-15T17:57:40 | 2017-09-15T17:57:40 | 98,215,658 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 860 | cpp | class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<vector<int>> res;
vector<int> cmb;
sort(candidates.begin(), candidates.end());
combinationSumHelper(res, cmb, candidates, target, 0);
return res;
}
void combinationSumHelper(vector<vector<int>>& res, vector<int>& cmb, vector<int>& candidates, int target, int k) {
if(target == 0) {
res.push_back(cmb);
return;
}
for(int i = k; i < candidates.size() && candidates[i] <= target; i++) {
if(i == k || candidates[i] != candidates[i - 1]) {
cmb.push_back(candidates[i]);
combinationSumHelper(res, cmb, candidates, target - candidates[i], i + 1);
cmb.pop_back();
}
}
}
}; | [
"wszk1992@gmail.com"
] | wszk1992@gmail.com |
ec39ae6e69fc39c428f27bb348721af9f821d227 | ce122446cb0493e2f744e37a7e6c3b0d2bb06f44 | /be/src/vec/exprs/lambda_function/varray_map_function.cpp | c3a26f18b162e23c70b62601d9d2861629bdc0de | [
"BSD-3-Clause",
"PSF-2.0",
"GPL-2.0-only",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"dtoa",
"MIT",
"LicenseRef-scancode-facebook-patent-rights-2",
"bzip2-1.0.6",
"OpenSSL"
] | permissive | yanghongkjxy/palo | 1ce1ae3602e88f4ea8246135e310fddf3ba0c98e | afed14ba3181d0f0949acf5b1eec93e99fa3cf88 | refs/heads/master | 2023-04-02T12:42:03.643847 | 2023-03-18T02:49:09 | 2023-03-18T02:49:09 | 143,609,059 | 0 | 0 | Apache-2.0 | 2018-09-26T09:01:47 | 2018-08-05T12:01:32 | C++ | UTF-8 | C++ | false | false | 7,305 | cpp | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include <fmt/core.h>
#include "common/status.h"
#include "vec/columns/column_array.h"
#include "vec/core/block.h"
#include "vec/data_types/data_type_array.h"
#include "vec/exprs/lambda_function/lambda_function.h"
#include "vec/exprs/lambda_function/lambda_function_factory.h"
#include "vec/exprs/vexpr.h"
#include "vec/exprs/vexpr_context.h"
#include "vec/utils/util.hpp"
namespace doris::vectorized {
class ArrayMapFunction : public LambdaFunction {
public:
~ArrayMapFunction() override = default;
static constexpr auto name = "array_map";
static LambdaFunctionPtr create() { return std::make_shared<ArrayMapFunction>(); }
std::string get_name() const override { return name; }
doris::Status execute(VExprContext* context, doris::vectorized::Block* block,
int* result_column_id, DataTypePtr result_type,
const std::vector<VExpr*>& children) override {
///* array_map(lambda,arg1,arg2,.....) *///
//1. child[1:end]->execute(src_block)
doris::vectorized::ColumnNumbers arguments(children.size() - 1);
for (int i = 1; i < children.size(); ++i) {
int column_id = -1;
RETURN_IF_ERROR(children[i]->execute(context, block, &column_id));
arguments[i - 1] = column_id;
}
// used for save column array outside null map
auto outside_null_map =
ColumnUInt8::create(block->get_by_position(arguments[0])
.column->convert_to_full_column_if_const()
->size(),
0);
// offset column
MutableColumnPtr array_column_offset;
int nested_array_column_rows = 0;
//2. get the result column from executed expr, and the needed is nested column of array
Block lambda_block;
for (int i = 0; i < arguments.size(); ++i) {
const auto& array_column_type_name = block->get_by_position(arguments[i]);
auto column_array = array_column_type_name.column;
column_array = column_array->convert_to_full_column_if_const();
auto type_array = array_column_type_name.type;
if (type_array->is_nullable()) {
// get the nullmap of nullable column
const auto& column_array_nullmap =
assert_cast<const ColumnNullable&>(*array_column_type_name.column)
.get_null_map_column();
// get the array column from nullable column
column_array =
assert_cast<const ColumnNullable*>(array_column_type_name.column.get())
->get_nested_column_ptr();
// get the nested type from nullable type
type_array = assert_cast<const DataTypeNullable*>(array_column_type_name.type.get())
->get_nested_type();
// need to union nullmap from all columns
VectorizedUtils::update_null_map(outside_null_map->get_data(),
column_array_nullmap.get_data());
}
// here is the array column
const ColumnArray& col_array = assert_cast<const ColumnArray&>(*column_array);
const auto& col_type = assert_cast<const DataTypeArray&>(*type_array);
if (i == 0) {
nested_array_column_rows = col_array.get_data_ptr()->size();
auto& off_data = assert_cast<const ColumnArray::ColumnOffsets&>(
col_array.get_offsets_column());
array_column_offset = off_data.clone_resized(col_array.get_offsets_column().size());
} else {
// select array_map((x,y)->x+y,c_array1,[0,1,2,3]) from array_test2;
// c_array1: [0,1,2,3,4,5,6,7,8,9]
if (nested_array_column_rows != col_array.get_data_ptr()->size()) {
return Status::InternalError(
"in array map function, the input column nested column data rows are "
"not equal, the first size is {}, but with {}th size is {}.",
nested_array_column_rows, i + 1, col_array.get_data_ptr()->size());
}
}
// insert the data column to the new block
ColumnWithTypeAndName data_column {col_array.get_data_ptr(), col_type.get_nested_type(),
"R" + array_column_type_name.name};
lambda_block.insert(std::move(data_column));
}
//3. child[0]->execute(new_block)
RETURN_IF_ERROR(children[0]->execute(context, &lambda_block, result_column_id));
auto res_col = lambda_block.get_by_position(*result_column_id)
.column->convert_to_full_column_if_const();
auto res_type = lambda_block.get_by_position(*result_column_id).type;
auto res_name = lambda_block.get_by_position(*result_column_id).name;
//4. get the result column after execution, reassemble it into a new array column, and return.
ColumnWithTypeAndName result_arr;
if (res_type->is_nullable()) {
result_arr = {ColumnNullable::create(
ColumnArray::create(res_col, std::move(array_column_offset)),
std::move(outside_null_map)),
result_type, res_name};
} else {
// need to create the nested column null map for column array
auto nested_null_map = ColumnUInt8::create(res_col->size(), 0);
result_arr = {ColumnNullable::create(
ColumnArray::create(ColumnNullable::create(
res_col, std::move(nested_null_map)),
std::move(array_column_offset)),
std::move(outside_null_map)),
result_type, res_name};
}
block->insert(std::move(result_arr));
*result_column_id = block->columns() - 1;
return Status::OK();
}
};
void register_function_array_map(doris::vectorized::LambdaFunctionFactory& factory) {
factory.register_function<ArrayMapFunction>();
}
} // namespace doris::vectorized
| [
"noreply@github.com"
] | yanghongkjxy.noreply@github.com |
37483ecc07f364f97236e6750815fa8e88668ace | 558b75f4715273ebb01e36e0b92446130c1a5c08 | /engine/src/qlcfixturedefcache.h | 316d75eeddec94822f159857ffb16069cb0f2af5 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | sbenejam/qlcplus | c5c83efe36830dcd75d41b3fba50944dc22019e1 | 2f2197ff086f2441d755c03f7d67c11f72ad21df | refs/heads/master | 2023-08-25T09:06:57.397956 | 2023-08-17T16:02:42 | 2023-08-17T16:02:42 | 502,436,497 | 0 | 0 | Apache-2.0 | 2022-06-11T19:17:52 | 2022-06-11T19:17:51 | null | UTF-8 | C++ | false | false | 5,715 | h | /*
Q Light Controller
qlcfixturedefcache.h
Copyright (c) Heikki Junnila
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef QLCFIXTUREDEFCACHE_H
#define QLCFIXTUREDEFCACHE_H
#include <QStringList>
#include <QString>
#include <QMap>
#include <QDir>
class QXmlStreamReader;
class QLCFixtureDef;
/** @addtogroup engine Engine
* @{
*/
/**
* QLCFixtureDefCache is a cache of fixture definitions that are currently
* available to the application. Application can get a list of available
* manufacturer names with QLCFixturedefCache::manufacturers() and subsequently
* all models for a particular manufacturer with QLCFixtureDefCache::models().
*
* The internal structure is a two-tier map (m_models), with the first tier
* containing manufacturer names as the keys for the first map. The value of
* each key is another map (the second-tier) whose keys are model names. The
* value for each model name entry in the second-tier map is the actual
* QLCFixtureDef instance.
*
* Multiple manufacturer & model combinations are discarded.
*
* Because this component is meant to be used only on the application side,
* the returned fixture definitions are const, preventing any modifications to
* the definitions. Modifying the definitions would also screw up the mapping
* since they are made only during addFixtureDef() based on the definitions'
* manufacturer() & model() data.
*/
class QLCFixtureDefCache
{
public:
/**
* Create a new fixture definition cache instance.
*/
QLCFixtureDefCache();
/**
* Destroy a fixture definition cache instance.
*/
~QLCFixtureDefCache();
/**
* Get a fixture definition by its manufacturer and model. Only
* const methods can be accessed for returned fixture definitions.
*
* @param manufacturer The fixture definition's manufacturer
* @param model The fixture definition's model
* @return A matching fixture definition or NULL if not found
*/
QLCFixtureDef* fixtureDef(const QString& manufacturer,
const QString& model) const;
/**
* Get a list of available manufacturer names.
*/
QStringList manufacturers() const;
/**
* Get a list of available model names for the given manufacturer.
*/
QStringList models(const QString& manufacturer) const;
/** Get a complete map of the available fixtures as:
* manufacturer, <model, isUser>
*/
QMap<QString, QMap<QString, bool> > fixtureCache() const;
/**
* Add a fixture definition to the model map.
*
* @param fixtureDef The fixture definition to add
* @return true, if $fixtureDef was added, otherwise false
*/
bool addFixtureDef(QLCFixtureDef* fixtureDef);
/**
* Store a fixture in the fixtures user data folder
* if a fixture with the same name already exists, it
* will be overwritten
*
* @param filename the target fixture file name
* @param data the content of a fixture XML data
* @return
*/
bool storeFixtureDef(QString filename, QString data);
/**
* Load fixture definitions from the given path. Ignores duplicates.
* Returns true even if $fixturePath doesn't contain any fixtures,
* if it is still accessible (and exists).
*
* @param dir The directory to load definitions from.
* @return true, if the path could be accessed, otherwise false.
*/
bool load(const QDir& dir);
/**
* Load all the fixture information found for the given manufacturer.
*
* @param doc reference to the XML loader
* @param manufacturer used to elapse the fixture file name relative path
* @return the number of fixtures found
*/
int loadMapManufacturer(QXmlStreamReader *doc, QString manufacturer);
/**
* Load a map of hardcoded fixture definitions that represent
* the minimum information to cache a fixture when it is required
*
* @param dir The directory to load definitions from.
* @return true, if the path could be accessed, otherwise false.
*/
bool loadMap(const QDir& dir);
/**
* Cleans the contents of the fixture definition cache, deleting
* all fixture definitions.
*/
void clear();
/**
* Get the default system fixture definition directory that contains
* installed fixture definitions. The location varies greatly between
* platforms.
*
* @return System fixture definition directory
*/
static QDir systemDefinitionDirectory();
/**
* Get the user's own default fixture definition directory that is used to
* save custom fixture definitions. The location varies greatly between
* platforms.
*
* @return User fixture definition directory
*/
static QDir userDefinitionDirectory();
/** Load a QLC native fixture definition from the file specified in $path */
bool loadQXF(const QString& path, bool isUser = false);
/** Load an Avolites D4 fixture definition from the file specified in $path */
bool loadD4(const QString& path);
private:
QString m_mapAbsolutePath;
QList <QLCFixtureDef*> m_defs;
};
/** @} */
#endif
| [
"massimocallegari@yahoo.it"
] | massimocallegari@yahoo.it |
b06026c1c4399aeff61afe8e47faf58a27f385d2 | 5950c4973a1862d2b67e072deeea8f4188d23d97 | /Export/macos/obj/src/lime/_internal/format/Zlib.cpp | 21f17693b5e3be87344aae43fb108c7a8932d361 | [
"MIT"
] | permissive | TrilateralX/TrilateralLimeTriangle | b3cc0283cd3745b57ccc9131fcc9b81427414718 | 219d8e54fc3861dc1ffeb3da25da6eda349847c1 | refs/heads/master | 2022-10-26T11:51:28.578254 | 2020-06-16T12:32:35 | 2020-06-16T12:32:35 | 272,572,760 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 3,762 | cpp | // Generated by Haxe 4.2.0-rc.1+cb30bd580
#include <hxcpp.h>
#ifndef INCLUDED_haxe_io_Bytes
#include <haxe/io/Bytes.h>
#endif
#ifndef INCLUDED_lime__internal_backend_native_NativeCFFI
#include <lime/_internal/backend/native/NativeCFFI.h>
#endif
#ifndef INCLUDED_lime__internal_format_Zlib
#include <lime/_internal/format/Zlib.h>
#endif
HX_LOCAL_STACK_FRAME(_hx_pos_1e53264516846038_20_compress,"lime._internal.format.Zlib","compress",0x612ac019,"lime._internal.format.Zlib.compress","lime/_internal/format/Zlib.hx",20,0x132edd28)
HX_LOCAL_STACK_FRAME(_hx_pos_1e53264516846038_50_decompress,"lime._internal.format.Zlib","decompress",0x83a84c5a,"lime._internal.format.Zlib.decompress","lime/_internal/format/Zlib.hx",50,0x132edd28)
namespace lime{
namespace _internal{
namespace format{
void Zlib_obj::__construct() { }
Dynamic Zlib_obj::__CreateEmpty() { return new Zlib_obj; }
void *Zlib_obj::_hx_vtable = 0;
Dynamic Zlib_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< Zlib_obj > _hx_result = new Zlib_obj();
_hx_result->__construct();
return _hx_result;
}
bool Zlib_obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x7f314115;
}
::haxe::io::Bytes Zlib_obj::compress( ::haxe::io::Bytes bytes){
HX_STACKFRAME(&_hx_pos_1e53264516846038_20_compress)
HXDLIN( 20) ::haxe::io::Bytes _hx_tmp = ::haxe::io::Bytes_obj::alloc(0);
HXDLIN( 20) return ( ( ::Dynamic)(::lime::_internal::backend::native::NativeCFFI_obj::lime_zlib_compress(::hx::DynamicPtr(bytes),::hx::DynamicPtr(_hx_tmp))) );
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(Zlib_obj,compress,return )
::haxe::io::Bytes Zlib_obj::decompress( ::haxe::io::Bytes bytes){
HX_STACKFRAME(&_hx_pos_1e53264516846038_50_decompress)
HXDLIN( 50) ::haxe::io::Bytes _hx_tmp = ::haxe::io::Bytes_obj::alloc(0);
HXDLIN( 50) return ( ( ::Dynamic)(::lime::_internal::backend::native::NativeCFFI_obj::lime_zlib_decompress(::hx::DynamicPtr(bytes),::hx::DynamicPtr(_hx_tmp))) );
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(Zlib_obj,decompress,return )
Zlib_obj::Zlib_obj()
{
}
bool Zlib_obj::__GetStatic(const ::String &inName, Dynamic &outValue, ::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 8:
if (HX_FIELD_EQ(inName,"compress") ) { outValue = compress_dyn(); return true; }
break;
case 10:
if (HX_FIELD_EQ(inName,"decompress") ) { outValue = decompress_dyn(); return true; }
}
return false;
}
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo *Zlib_obj_sMemberStorageInfo = 0;
static ::hx::StaticInfo *Zlib_obj_sStaticStorageInfo = 0;
#endif
::hx::Class Zlib_obj::__mClass;
static ::String Zlib_obj_sStaticFields[] = {
HX_("compress",a2,47,bf,83),
HX_("decompress",23,88,14,da),
::String(null())
};
void Zlib_obj::__register()
{
Zlib_obj _hx_dummy;
Zlib_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("lime._internal.format.Zlib",d7,d2,35,70);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &Zlib_obj::__GetStatic;
__mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(Zlib_obj_sStaticFields);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(0 /* sMemberFields */);
__mClass->mCanCast = ::hx::TCanCast< Zlib_obj >;
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = Zlib_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = Zlib_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace lime
} // end namespace _internal
} // end namespace format
| [
"none"
] | none |
125ff7c1cdd36286e335004d9853858f868e2054 | ae1350bf9241eae5c7f83a86a3b84792adc0d2e3 | /Bai 5.cpp | dcba24232e02f001a00eeb183e304677f73fec07 | [] | no_license | vietanhsbox/B-i-t-p-th-c-t-p | 0f7b31f15102ff374a6e89a020608626bad4824a | 8457624538078de45ebc1d0b824636e27b7960ad | refs/heads/master | 2020-03-19T01:07:28.857820 | 2018-05-31T05:09:45 | 2018-05-31T05:09:45 | 135,524,467 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 999 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
float check1, check2, check3, ngay, thang, nam;
check1 = scanf_s("%f", &ngay);
check2 = scanf_s("%f", &thang);
check3 = scanf_s("%f", &nam);
if (check1 == 0 || check2 == 0 || check3 == 0 || ngay != (int)ngay || thang != (int)thang || nam != (int)nam || ngay<1 || ngay>31 || thang<1 || thang>12 || nam<1)
{
printf("khong hop le!");
}
else {
if ((int)nam % 400 == 0 || ((int)nam % 4 == 0 && (int)nam % 100 != 0)) {
if (thang = 2) {
if (ngay >= 30) {
printf("khong hop le!");
}
}
if (thang == 4 || thang == 6 || thang == 7 || thang == 8 || thang == 9 || thang == 11) {
ngay>30;
printf("khong hop le!");
}
printf("nam nhuan");
}
else {
if (thang == 2) {
if (ngay >= 29) {
printf("khong hop le!");
}
}
else {
printf("nam khong nhuan");
}
}
}
_getch();
return 0;
} | [
"noreply@github.com"
] | vietanhsbox.noreply@github.com |
f9529045320a5d906366cb6ba17268c783ec6a93 | 9007e49918e2b3f41188439d0c1c9ebfa5ab6f9d | /Cplusplus98/main.cc | f8898e11b24ea5fde9b971e911280f24d536bd64 | [] | no_license | lishaohsuai/threadpool | a60a30ada35628cfa741c77c583808b18f0d92ed | 6ab71cd1916bcf6c35b2b3157cf454a12f05f1e7 | refs/heads/main | 2023-03-13T00:35:05.433725 | 2021-02-25T11:37:48 | 2021-02-25T11:37:48 | 341,180,502 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,136 | cc | #include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <vector>
#include "threadPool.hh"
class MyTask: public zl::Task
{
public:
MyTask(){}
virtual int run() {
printf("thread[%lu] : %d\n", pthread_self(), *(int*)this->arg_);
// sleep(1);
const int MM = 100000;
for(int i=0; i<MM; i++)
for(int j=0; j<MM; j++);
return 0;
}
};
int main() {
char szTmp[] = "hello world";
std::vector<MyTask> taskObj;
taskObj.resize(100);
std::vector<int> vv(100);
for(int i=0; i<100; i++){
vv[i] = i;
taskObj[i].setArg((void*)&vv[i]);
}
zl::ThreadPool threadPool(16);
for(int i = 0; i < 100; i++) {
threadPool.addTask(&taskObj[i]);
}
while(1) {
printf("there are still %d tasks need to process\n", threadPool.size());
if (threadPool.size() == 0) {
threadPool.stop();
printf("Now I will exit from main\n");
exit(0);
}
sleep(2);
}
return 0;
} | [
"1049188593@qq.com"
] | 1049188593@qq.com |
620ccb08c730b22e5d16a229cd44a2b9558f41a4 | 083ca3df7dba08779976d02d848315f85c45bf75 | /DungeonGame.cpp | 5bb3cd62583701edfed384c5947848a84e9253ee | [] | no_license | jiangshen95/UbuntuLeetCode | 6427ce4dc8d9f0f6e74475faced1bcaaa9fc9f94 | fa02b469344cf7c82510249fba9aa59ae0cb4cc0 | refs/heads/master | 2021-05-07T02:04:47.215580 | 2020-06-11T02:33:35 | 2020-06-11T02:33:35 | 110,397,909 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,304 | cpp | #include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
int calculateMinimumHP(vector<vector<int> >& dungeon) {
int m = dungeon.size(), n = dungeon[0].size();
vector<vector<int> > dp(m, vector<int>(n));
dp[m-1][n-1] = max(1, 1 - dungeon[m-1][n-1]);
for(int i=m-1;i>=0;i--){
for(int j=n-1;j>=0;j--){
if(i == m-1 && j == n-1){
continue;
}
if(i == m-1){
dp[i][j] = max(1, dp[i][j+1] - dungeon[i][j]);
}else if(j == n-1){
dp[i][j] = max(1, dp[i+1][j] - dungeon[i][j]);
}else{
dp[i][j] = max(min(dp[i+1][j], dp[i][j+1]) - dungeon[i][j], 1);
}
}
}
return dp[0][0];
}
};
int main(){
int m, n;
cin>>m>>n;
vector<vector<int> > dungeon;
for(int i=0;i<m;i++){
vector<int> raw;
for(int j=0;j<n;j++){
int num;
cin>>num;
raw.push_back(num);
}
dungeon.push_back(raw);
}
Solution *solution = new Solution();
cout<<solution->calculateMinimumHP(dungeon);
return 0;
}
| [
"jiangshen95@163.com"
] | jiangshen95@163.com |
96f6217baf607bd5e28e25f0fb70b8a7ccd771a5 | 1130bcd2ab620dcc7c5ea81e6d275283fdfb9f88 | /channelinfo.cpp | 8faa4c83dfdacd089ca879afa2789351b9003b29 | [] | no_license | 372272083/mfds | c2245f98ee4d5e5ec89379e72e61826f00d3d334 | 659f01e9e206ff12c2aa327968d24ef717d2b65d | refs/heads/master | 2020-04-14T15:03:51.850005 | 2019-08-12T08:54:54 | 2019-08-12T08:54:54 | 143,227,303 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 75 | cpp | #include "channelinfo.h"
ChannelInfo::ChannelInfo() : TreeNodeInfo()
{
}
| [
"372272083@qq.com"
] | 372272083@qq.com |
4ecd991fc4f3a7fa6a380ab861ee92ef6c21d754 | 737d18cdcc25bc1932d5888e5144c977af377eda | /Mouse Interfacing/src/mainwindow.cpp | 3c6df08e39958c5d399d56e7682268e82b455494 | [] | no_license | Kshitij09/Computer-Graphics | e2c94ee7d5dd15cf8b14a85a874b9c49155a6b07 | 736c8d1c41dc5c477c4e88c79428107c5e12b771 | refs/heads/master | 2020-03-09T02:48:00.749239 | 2018-04-09T22:00:20 | 2018-04-09T22:00:20 | 128,548,964 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,280 | cpp | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include "clicklabel.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->label->setMouseTracking(true);
connect(ui->label,SIGNAL(mouse_pos()),this,SLOT(mouse_pos()));
connect(ui->label,SIGNAL(mouse_pressed()),this,SLOT(mouse_pressed()));
connect(ui->label,SIGNAL(mouse_released()),this,SLOT(mouse_released()));
connect(ui->label,SIGNAL(mouse_right_clicked()),this,SLOT(mouse_right_clicked()));
connect(ui->label,SIGNAL(mouse_left()),this,SLOT(mouse_left()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::mouse_pos()
{
ui->mouse_cord->setText(QString("X = %1, Y = %2")
.arg(ui->label->x)
.arg(ui->label->y));
ui->mouse_eve->setText(QString("Mouse Moving !"));
}
void MainWindow::mouse_pressed()
{
ui->mouse_eve->setText(QString("Mouse Clicked !"));
}
void MainWindow::mouse_released()
{
ui->mouse_eve->setText(QString("Mouse Released !"));
}
void MainWindow::mouse_right_clicked()
{
ui->mouse_eve->setText(QString("Mouse Right Clicked !"));
}
void MainWindow::mouse_left()
{
ui->mouse_eve->setText(QString("Mouse Left !"));
}
| [
"kshitijpatil98@gmail.com"
] | kshitijpatil98@gmail.com |
d8f5788723d71489a009b0c81715a4b6e690a2ce | f0cbd1891b71b73645e30a66eb3669512325ebd0 | /CarbonRender/Inc/CRGLHelper.h | bcd587b8682a54ce0302c7157f74e9b2a0a49641 | [
"MIT"
] | permissive | Hanggansta/CarbonRender | 0cba7b1abf0853069c117cd9124d9c831fe5d889 | f484dfbdf45403f0b548d51a4adbe72840aabdec | refs/heads/master | 2020-07-31T06:23:20.885346 | 2019-09-23T21:53:36 | 2019-09-23T21:53:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 585 | h | #ifndef CR_GLHELPER
#define CR_GLHELPER
#include "..\Inc\CRGloble.h"
class GLHelper
{
public:
static void SetGLArrayBuffer(GLuint bIndex, GLsizeiptr bSize, const GLvoid* bData, GLuint eSize, GLenum eType, GLuint aPos);
static GLuint SetGLRenderTexture(GLsizei w, GLsizei h, GLint internalFormat, GLenum format, GLenum type, GLenum attach, bool mipmap);
static void SetGLRenderTexture(GLuint rt, GLenum attach);
static GLuint SetGLCubeRenderTexture(GLsizei size, GLint internalFormat, GLenum format, GLenum type);
static GLuint SetGLDepthBuffer(GLsizei w, GLsizei h);
};
#endif
| [
"carbonsunsu@gmail.com"
] | carbonsunsu@gmail.com |
5c448fedde2f5d8c0bd3ac58b756e03900e86169 | d7a5503983afe9cefe20ede4ff95d5f161d17e69 | /uva11364.cpp | c6f9b54e45ca50201fe8ea56a22104920c3e8e88 | [] | no_license | x8522207x/uva | 93acf2caeb5d04e5a6353187b32124a6d29bac9f | c120baee2fc6d8734eec6a12348a2042a8d0032d | refs/heads/master | 2022-02-13T02:35:42.184762 | 2019-07-19T10:58:36 | 2019-07-19T10:58:36 | 107,366,185 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 379 | cpp | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
int Case=0;
cin>>Case;
while(Case--){
int nums=0,sum=0;
cin>>nums;
vector<int>park;
for(int i=0,g=0;i<nums;i++){
cin>>g;
park.push_back(g);
}
sort(park.begin(),park.end());
for(int i=0;i<park.size()-1;i++){
sum+=park[i+1]-park[i];
}
cout<<2*sum<<endl;
}
}
| [
"noreply@github.com"
] | x8522207x.noreply@github.com |
6b05cfeef0c81bc602cd9227b30c9ffc6498d62c | 82815230eeaf24d53f38f2a3f144dd8e8d4bc6b5 | /Laminar Pipe/laminarPipe3/system/blockMeshDict | 3491effb200ecd07d59f9db4f54f45ef738366ab | [
"MIT"
] | permissive | ishantja/KUHPC | 6355c61bf348974a7b81b4c6bf8ce56ac49ce111 | 74967d1b7e6c84fdadffafd1f7333bf533e7f387 | refs/heads/main | 2023-01-21T21:57:02.402186 | 2020-11-19T13:10:42 | 2020-11-19T13:10:42 | 312,429,902 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,740 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: v1912 |
| \\ / A nd | Website: www.openfoam.com |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class dictionary;
object blockMeshDict;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
scale 0.01;
a 75;
b 25;
c 25;
yi -51;
yf 51;
zi -51;
zf 51;
xi 5;
xf 295;
vertices
(
($xi $yi $zi) //0
($xf $yi $zi) //1
($xf $yf $zi) //2
($xi $yf $zi) //3
($xi $yi $zf) //4
($xf $yi $zf) //5
($xf $yf $zf) //6
($xi $yf $zf) //7
);
blocks
(
hex (0 1 2 3 4 5 6 7) ($a $b $c) simpleGrading (1 1 1)
);
edges
(
);
boundary
(
frontAndBack
{
type patch;
faces
(
(3 7 6 2)
(1 5 4 0)
);
}
inlet
{
type patch;
faces
(
(0 4 7 3)
);
}
outlet
{
type patch;
faces
(
(2 6 5 1)
);
}
lowerWall
{
type wall;
faces
(
(0 3 2 1)
);
}
upperWall
{
type patch;
faces
(
(4 5 6 7)
);
}
);
// ************************************************************************* //
| [
"ishantamrakat24@gmail.com"
] | ishantamrakat24@gmail.com | |
8f7fe346591e99e07b1521ac18f23a48fa07129d | 7a3fb6fafb5dff31d998d8db529361d462acca1d | /Games/Tactics/Code/Game/Rendering/Mesh.hpp | cfccf21c6c4101227c588da246b4ab422c9a96e2 | [] | no_license | jholan/Kaleidoscope | 643cc65bdcf43cfac292137f08ba5789396d51dc | 5aa3c91c75d73c8ed3718c031ae449b6199e1d44 | refs/heads/master | 2020-05-23T08:55:00.707693 | 2019-06-26T20:05:08 | 2019-06-26T20:05:08 | 186,697,847 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,701 | hpp | #pragma once
#include <vector>
#include <map>
#include "Engine/Strings/HashedString.hpp"
#include "Engine/XML/XMLUtils.hpp"
#include "Engine/Math/Primitives.hpp"
#include "Engine/Rendering/LowLevel/RenderingEnums.hpp"
class VertexBuffer;
class IndexBuffer;
class VertexLayout;
enum eResourceLoadState;
class SubMeshDescription
{
public:
SubMeshDescription() {};
~SubMeshDescription() {};
public:
ePrimitiveTopology primitiveTopology = PRIMITIVE_TOPOLOGY_TRIANGLES;
uint elementCount = 0;
uint startIndex = 0;
bool isIndexed = false;
};
class SubMesh
{
public:
// Composition
SubMesh();
~SubMesh();
// State
void SetVertices(const void* vertices, uint vertexSizeBytes, uint vertexCount);
void SetIndices(const uint* indices, uint count);
void SetVertexLayout(const VertexLayout* layout);
void SetDescription(const SubMeshDescription& description);
void SetBounds(const AABB& bounds);
// Access
const SubMeshDescription& GetDescription() const;
const VertexBuffer* GetVertexBuffer() const;
const IndexBuffer* GetIndexBuffer() const;
const VertexLayout* GetVertexLayout() const;
const AABB& GetBounds() const;
private:
SubMeshDescription m_description;
VertexBuffer* m_vertexBuffer = nullptr;
IndexBuffer* m_indexBuffer = nullptr;
const VertexLayout* m_vertexLayout = nullptr;
AABB m_bounds;
};
class Mesh
{
public:
// Composition
Mesh();
~Mesh();
void UnloadSubMeshes();
// Name
void SetName(const HashedString& name);
const HashedString& GetName() const;
// Load Location
void SetFileContainingDefinition(const std::string& dbFile);
const std::string& GetFileContainingDefinition() const;
void SetFilepath(const std::string& filepath);
const std::string& GetFilepath() const;
// SubMeshes
void AddSubMesh(SubMesh* submesh);
const SubMesh* GetSubMesh(uint index);
uint GetNumSubMeshes() const;
// LoadState
void SetResourceLoadState(eResourceLoadState state);
eResourceLoadState GetResourceLoadState() const;
public:
// Database
static void LoadDatabaseFile(const std::string& filepath);
static Mesh* CreateMeshFromDatabaseEntry(const XMLEle* entry, const std::string& filepath);
// Access
static bool DoesMeshExist(const HashedString& name);
static const Mesh* Get(const HashedString& name);
static const Mesh* GetBlocking(const HashedString& name);
// Async Loading Management
static void EndFrame();
private:
HashedString m_name;
std::string m_fileContainingDefinition;
std::string m_filepath;
std::vector<SubMesh*> m_subMeshes;
ulonglong m_lastFrameUsed = 0;
eResourceLoadState m_loadState;
private:
static std::map<HashedString, Mesh*> s_meshes;
static uint s_lastFrameLoaded;
};
| [
"jholan@smu.edu"
] | jholan@smu.edu |
24bcf3591d31761d3deb26c0b8d3405372b36d91 | 5c41d1e2eb0f4a73c939b061657045363d4e667c | /src/graph/timing_internal_graph.cpp | 5b1326afcfec4c1f9f8c52ffe9ca20263a378369 | [] | no_license | me2x/iNARK | 93d2f2179466d6fd7c509e1789057fd39407db58 | f59dcfdedbe0306ebb814aaf6d26d3a6b0ec1096 | refs/heads/master | 2020-05-21T12:27:42.023362 | 2017-04-04T14:21:58 | 2017-04-04T14:21:58 | 47,130,570 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,971 | cpp | #include "timing_internal_graph.hpp"
#include "custom_visitors.hpp"
timing_internal_graph::timing_internal_graph()
{
ig = Timing_Graph();
}
void timing_internal_graph::build_graph(std::shared_ptr<Source_Graph> g){
std::cout<<"print called"<<std::endl;
PRINT_DEBUG("print called");
ig.clear();
std::pair<vertex_iter, vertex_iter> vp;
for (vp = boost::vertices(*g); vp.first != vp.second; ++vp.first)
{
PRINT_DEBUG("timing graph construction: vertex loop, layer is: "+boost::lexical_cast<std::string>((*g)[*vp.first].get_layer()) +" and name is: "+boost::lexical_cast<std::string>((*g)[*vp.first].get_name()));
(*g)[*vp.first].explode_component_timing(ig,components_map);
}
PRINT_DEBUG("components map size is: "+boost::lexical_cast<std::string>(components_map.size()));
edge_iter ei, ei_end;
for (boost::tie(ei, ei_end) = boost::edges(*g); ei != ei_end; ++ei)
{
timing_edge_t e; bool b;
vertex_t old_graph_source,old_graph_target;
old_graph_source = boost::source(*ei,*g);
old_graph_target = boost::target(*ei,*g);
timing_vertex_t new_source, new_target;
PRINT_DEBUG("the source component is: "+(*g)[old_graph_source].get_name()+" and its port is: "+boost::lexical_cast<std::string>((*g)[*ei].from_port));
PRINT_DEBUG("the target component is: "+(*g)[old_graph_target].get_name()+" and its port is: "+boost::lexical_cast<std::string>((*g)[*ei].to_port));
PRINT_DEBUG("the case is: "+boost::lexical_cast<std::string>((*g)[old_graph_source].get_layer()+(*g)[old_graph_target].get_layer()));
//mancano 4 to 5: da moltiplicare.
//all edges are in 1:1 between the physical graph to the internal representation, exept the edges from l4 to l5.
//OS to processor have to be multiplied
//task to os has to be fixed. to port dovrebbe mappare allo scheduler slot. ed infatti funziona.
//for that layer i have to build one edge for each new resource to the physical component
//!((*g)[old_graph_source].get_layer() != PHYSICAL && (*g)[old_graph_target].get_layer() == PHYSICAL)&& !((*g)[old_graph_source].get_layer() == PHYSICAL && (*g)[old_graph_target].get_layer() != PHYSICAL)
//fai con uno switch su somma layers. caso base: edges 1:1
//cases: 0 func to func, 1 func to task, 2 tast to task, 3 task to os, 4 os to os, 5 os to processor, 6 resource to resource, 7 resource to physical
switch((*g)[old_graph_source].get_layer()+(*g)[old_graph_target].get_layer())
{
case 0:
case 2:
case 6:
case 8:
{
if (components_map.count((*g)[old_graph_source].get_name()) != 0)
{
new_source = get_node_reference(components_map.at((*g)[old_graph_source].get_name()).at((*g)[*ei].from_port !=NO_PORT? (*g)[*ei].from_port:1)); //pos 1 se non specificato serve per prendere componenti unici che sono stati in qualche modo toccati nella funzione di explode.
}
else
{
new_source = get_node_reference((*g)[old_graph_source].get_name());
}
if (components_map.count((*g)[old_graph_target].get_name()) != 0)
{
new_target = get_node_reference(components_map.at((*g)[old_graph_target].get_name()).at((*g)[*ei].to_port !=NO_PORT? (*g)[*ei].to_port:1));
}
else
{
new_target = get_node_reference((*g)[old_graph_target].get_name());
}
boost::tie(e,b) = boost::add_edge(new_source,new_target,ig);
break;
}
case 1:
{
if (components_map.count((*g)[old_graph_source].get_name()) != 0)
{
new_source = get_node_reference(components_map.at((*g)[old_graph_source].get_name()).at((*g)[*ei].from_port !=NO_PORT? (*g)[*ei].from_port:1)); //pos 1 se non specificato serve per prendere componenti unici che sono stati in qualche modo toccati nella funzione di explode.
}
else
{
new_source = get_node_reference((*g)[old_graph_source].get_name());
}
if (components_map.count((*g)[old_graph_target].get_name()) != 0)
{
new_target = get_node_reference(components_map.at((*g)[old_graph_target].get_name()).at((*g)[*ei].to_port !=NO_PORT? (*g)[*ei].to_port:1));
}
else
{
new_target = get_node_reference((*g)[old_graph_target].get_name());
}
boost::tie(e,b) = boost::add_edge(new_source,new_target,ig);
boost::tie(e,b) = boost::add_edge(new_target,new_source,ig);
break;
}
case 3:
{
//devo recuperare priority dallo scheduler slot del to component.
//back edges have already been inserted in the previous graph. have to be handled here so if source is the controller layer component have to be handled too.
if ((*g)[old_graph_target].get_layer() == Layer::CONTROLLER)
{
std::shared_ptr<Third_Level_Vertex> vtx = ((*g)[old_graph_target]).get_shared_ptr_l3();
switch (vtx->OS_scheduler_type)
{
case ROUND_ROBIN:
{
//no name changes.
new_source = get_node_reference((*g)[old_graph_source].get_name());
new_target = get_node_reference((*g)[old_graph_target].get_name());
boost::tie(e,b) = boost::add_edge(new_source,new_target,ig);
boost::tie(e,b) = boost::add_edge(new_target,new_source,ig);
break;
}
case PRIORITY:
{
//get slot, read priority, get correct component: 0 for no priority, 1 for mission critical, 2 for safety critical.
int pr = vtx->priority_slots->at((*g)[*ei].to_port).pr;
new_source = get_node_reference((*g)[old_graph_source].get_name());
new_target = get_node_reference(components_map.at((*g)[old_graph_target].get_name()).at(pr));
boost::tie(e,b) = boost::add_edge(new_source,new_target,ig);
boost::tie(e,b) = boost::add_edge(new_target,new_source,ig);
break;
}
case TDMA:
{
new_source = get_node_reference((*g)[old_graph_source].get_name());
new_target = get_node_reference(components_map.at((*g)[old_graph_target].get_name()).at((*g)[*ei].to_port));
boost::tie(e,b) = boost::add_edge(new_source,new_target,ig);
boost::tie(e,b) = boost::add_edge(new_target,new_source,ig);
break;
}
default:
{
throw std::runtime_error("Error in input: priority handling error");
}
}
}
else if ((*g)[old_graph_source].get_layer() == Layer::CONTROLLER)
{
std::shared_ptr<Third_Level_Vertex> vtx = ((*g)[old_graph_source]).get_shared_ptr_l3();
switch (vtx->OS_scheduler_type)
{
case ROUND_ROBIN:
{
//no name changes.
new_source = get_node_reference((*g)[old_graph_source].get_name());
new_target = get_node_reference((*g)[old_graph_target].get_name());
boost::tie(e,b) = boost::add_edge(new_source,new_target,ig);
boost::tie(e,b) = boost::add_edge(new_target,new_source,ig);
break;
}
case PRIORITY:
{
//get slot, read priority, get correct component: 0 for no priority, 1 for mission critical, 2 for safety critical.
int pr = vtx->priority_slots->at((*g)[*ei].from_port).pr;
PRINT_DEBUG("the priority of port "+boost::lexical_cast<std::string>((*g)[*ei].from_port)+"is"+boost::lexical_cast<std::string>(pr));
new_target = get_node_reference((*g)[old_graph_target].get_name());
new_source = get_node_reference(components_map.at((*g)[old_graph_source].get_name()).at(pr));
boost::tie(e,b) = boost::add_edge(new_source,new_target,ig);
boost::tie(e,b) = boost::add_edge(new_target,new_source,ig);
break;
}
case TDMA:
{
new_target = get_node_reference((*g)[old_graph_target].get_name());
new_source = get_node_reference(components_map.at((*g)[old_graph_source].get_name()).at((*g)[*ei].from_port));
boost::tie(e,b) = boost::add_edge(new_source,new_target,ig);
boost::tie(e,b) = boost::add_edge(new_target,new_source,ig);
break;
}
default:
{
throw std::runtime_error("Error in input: priority handling error");
}
}
}
else
throw std::runtime_error("Error in input: OS not involved");
break;
}
case 4: //all to all. è un po' overkill ma non dovrebbe creare dipendenze supplementari. aggiunge un sacco di edges e non so se ciò possa rallentare esplorazione.
{
PRINT_DEBUG("edge creation: inside switch, case 4");
if (components_map.count((*g)[old_graph_source].get_name()) != 0)
{
if (components_map.count((*g)[old_graph_target].get_name()) != 0)
{
//doppio for
for (std::map<int,std::string>::iterator many_to_one = components_map.at((*g)[old_graph_source].get_name()).begin();many_to_one != components_map.at((*g)[old_graph_source].get_name()).end();++many_to_one)
{
for (std::map<int,std::string>::iterator one_to_many_iter = components_map.at((*g)[old_graph_target].get_name()).begin();one_to_many_iter != components_map.at((*g)[old_graph_target].get_name()).end();++one_to_many_iter)
{
new_source = get_node_reference((*many_to_one).second);
new_target = get_node_reference((*one_to_many_iter).second);
boost::tie(e,b) = boost::add_edge(new_source,new_target,ig);
}
}
}
else
{
//singolo for
for (std::map<int,std::string>::iterator many_to_one = components_map.at((*g)[old_graph_source].get_name()).begin();many_to_one != components_map.at((*g)[old_graph_source].get_name()).end();++many_to_one)
{
new_target = get_node_reference((*g)[old_graph_target].get_name());
new_source = get_node_reference((*many_to_one).second);
boost::tie(e,b) = boost::add_edge(new_source,new_target,ig);
}
}
}
else
{
if (components_map.count((*g)[old_graph_target].get_name()) != 0)
{
//singolo for
for (std::map<int,std::string>::iterator one_to_many_iter = components_map.at((*g)[old_graph_target].get_name()).begin();one_to_many_iter != components_map.at((*g)[old_graph_target].get_name()).end();++one_to_many_iter)
{
new_source = get_node_reference((*g)[old_graph_source].get_name());
new_target = get_node_reference((*one_to_many_iter).second);
boost::tie(e,b) = boost::add_edge(new_source,new_target,ig);
}
}
else
{
//niente for
boost::tie(e,b) = boost::add_edge(get_node_reference((*g)[old_graph_source].get_name()),get_node_reference((*g)[old_graph_target].get_name()),ig);
}
}
break;
}
case 5:
{
PRINT_DEBUG("edge creation: inside switch, case 5");
bool l4_is_source = (*g)[old_graph_source].get_layer() == RESOURCE;
if (components_map.count((*g)[l4_is_source?old_graph_target:old_graph_source].get_name()) != 0)
{
PRINT_DEBUG("edge creation: inside switch, case 5, if branch");
for (std::map<int,std::string>::iterator l3_to_l4_iter = components_map.at((*g)[l4_is_source?old_graph_target:old_graph_source].get_name()).begin();l3_to_l4_iter != components_map.at((*g)[l4_is_source?old_graph_target:old_graph_source].get_name()).end();++l3_to_l4_iter)
{
PRINT_DEBUG("edge creation: components map at: "+(*g)[l4_is_source?old_graph_target:old_graph_source].get_name()+ " size is: "+boost::lexical_cast<std::string>(components_map.at((*g)[l4_is_source?old_graph_target:old_graph_source].get_name()).size()));
new_source = get_node_reference(l4_is_source? (*g)[old_graph_source].get_name()+"$$1" : (*l3_to_l4_iter).second);
if (l4_is_source)
{
PRINT_DEBUG("edge creation: old graph source name is: "+(*g)[old_graph_source].get_name() +"but the retrieved node is: "+ig[new_source].name);
//PRINT_DEBUG("the result of get node reference is: "+ boost::lexical_cast<std::string>(get_node_reference((*g)[old_graph_source].get_name())));
}
new_target = get_node_reference(l4_is_source? (*l3_to_l4_iter).second:(*g)[old_graph_target].get_name()+"$$1"); //the $$1 is added only to processors.
PRINT_DEBUG("edge creation: source node is: "+ig[new_source].name+ "while old graph source is: "+(*g)[old_graph_source].get_name()+" and target is: "+ig[new_target].name+" while old graph target is: "+(*g)[old_graph_target].get_name());
boost::tie(e,b) = boost::add_edge(new_source,new_target,ig);
boost::tie(e,b) = boost::add_edge(new_target,new_source,ig);
}
}
else
{
PRINT_DEBUG("edge creation: inside switch, case 5, else branch");
bool l4_is_source = (*g)[old_graph_source].get_layer() == RESOURCE;
new_source = get_node_reference((*g)[old_graph_source].get_name()+(l4_is_source?"$$1":""));
new_target = get_node_reference((*g)[old_graph_target].get_name()+(l4_is_source?"":"$$1"));
boost::tie(e,b) = boost::add_edge(new_source,new_target,ig);
boost::tie(e,b) = boost::add_edge(new_target,new_source,ig);
}
break;
}
case 7:
{
bool l4_is_source = (*g)[old_graph_source].get_layer() == RESOURCE;
for (std::map<int,std::string>::iterator l4_to_l5_iter = components_map.at((*g)[l4_is_source?old_graph_source:old_graph_target].get_name()).begin();l4_to_l5_iter != components_map.at((*g)[l4_is_source?old_graph_source:old_graph_target].get_name()).end();++l4_to_l5_iter)
{
PRINT_DEBUG("components map at: "+(*g)[l4_is_source?old_graph_source:old_graph_target].get_name()+ " size is: "+boost::lexical_cast<std::string>(components_map.at((*g)[l4_is_source?old_graph_source:old_graph_target].get_name()).size()));
new_source = get_node_reference(l4_is_source? (*l4_to_l5_iter).second:(*g)[old_graph_source].get_name() );
new_target = get_node_reference(l4_is_source? (*g)[old_graph_target].get_name() : (*l4_to_l5_iter).second);
boost::tie(e,b) = boost::add_edge(new_source,new_target,ig);
boost::tie(e,b) = boost::add_edge(new_target,new_source,ig);
}
break;
}
default:
{
PRINT_DEBUG("edge transformation in default case that should never be reached");
throw std::runtime_error("edge transformation in default case that should never be reached");
break;
}
}
PRINT_DEBUG("edge creation end");
}
std::ofstream myfile2;
myfile2.open ("/home/emanuele/Documents/tmp_graph/aaaedged.dot");
boost::write_graphviz(myfile2, ig,make_vertex_writer(boost::get(&Timing_Node::layer, ig),boost::get (&Timing_Node::name, ig)));
myfile2.close();
//search for master tasks.
//preparation: get processors
std::pair<timing_vertex_iter, timing_vertex_iter> tvp;
std::vector <timing_vertex_t> processor_vertex_t;
for (tvp = vertices(ig); tvp.first != tvp.second; ++tvp.first)
{
if(ig[*tvp.first].type == PROCESSOR)
{
processor_vertex_t.push_back(*tvp.first);
}
}
//search tasks for every processor
boost::filtered_graph<Timing_Graph,true_edge_predicate<Timing_Graph>,task_search_filter_c> task_per_processor_fg (ig,true_edge_predicate<Timing_Graph>(ig),task_search_filter_c(ig));
masters_task_research_visitor::colormap map = get(boost::vertex_color, task_per_processor_fg);
std::pair<boost::filtered_graph<Timing_Graph,true_edge_predicate<Timing_Graph>,task_search_filter_c>::vertex_iterator, boost::filtered_graph<Timing_Graph,true_edge_predicate<Timing_Graph>,task_search_filter_c>::vertex_iterator> processor_to_task_f_vp;
std::map<timing_vertex_t, std::vector <std::string>> processor_to_task_map;
for(std::vector<timing_vertex_t>::iterator processor_iter = processor_vertex_t.begin();processor_iter != processor_vertex_t.end();++processor_iter)
{
std::vector <std::string> vtxes;
masters_task_research_visitor vis = masters_task_research_visitor(vtxes);
vis.vertex_coloring = map; //should be passed by copy, so it should be ok. no. it is modified by reference so has to be resetted every time. note that it also has to be re_blackened
//filtered graph?
boost::depth_first_visit(task_per_processor_fg, *processor_iter,vis, map);
processor_to_task_map.insert(std::make_pair(*processor_iter, vtxes));
for (processor_to_task_f_vp = vertices(task_per_processor_fg); processor_to_task_f_vp.first != processor_to_task_f_vp.second; ++processor_to_task_f_vp.first)
map[*processor_to_task_f_vp.first] = boost::default_color_type::white_color;
}
#ifdef DEBUG
PRINT_DEBUG("processor to task mapping done. size of map is: "+boost::lexical_cast<std::string>(processor_to_task_map.size()));
for(std::map<timing_vertex_t, std::vector <std::string>>::iterator debug_iter = processor_to_task_map.begin(); debug_iter != processor_to_task_map.end(); ++debug_iter)
{
PRINT_DEBUG("processor to task mapping done. size of vector is: "+boost::lexical_cast<std::string>((*debug_iter).second.size()));
PRINT_DEBUG("processor to task mapping done. name of processor is is: "+ig[(*debug_iter).first].name);
for(std::vector <std::string>::iterator debug_iter2 = (*debug_iter).second.begin();debug_iter2 != (*debug_iter).second.end();++debug_iter2)
{
PRINT_DEBUG("processor to task mapping done. names of the vector are: "+*debug_iter2);
}
}
#endif
//filter graph (keep only 4th level)
boost::filtered_graph<Timing_Graph,true_edge_predicate<Timing_Graph>,lv4_vertex_predicate_c> ifg (ig,true_edge_predicate<Timing_Graph>(ig),lv4_vertex_predicate_c(ig));
std::ofstream myfile;
myfile.open ("/home/emanuele/Documents/tmp_graph/aaafiltrato.dot");
boost::write_graphviz(myfile, ifg,make_vertex_writer(boost::get(&Timing_Node::layer, ifg),boost::get (&Timing_Node::name, ifg)));
myfile.close();
//build a map with the association name :: timing_vertex_t to pass to the following algorithms. only the 4th level nodes are needed
std::pair<boost::filtered_graph<Timing_Graph,true_edge_predicate<Timing_Graph>,lv4_vertex_predicate_c>::vertex_iterator, boost::filtered_graph<Timing_Graph,true_edge_predicate<Timing_Graph>,lv4_vertex_predicate_c>::vertex_iterator> ftvp;
for (ftvp = vertices(ifg); ftvp.first != ftvp.second; ++ftvp.first)
{
name_to_node_map.insert(std::make_pair(ifg[*ftvp.first].name,*ftvp.first ));
}
//for eaech processor, do a dfs or bfs to search interfered tasks. that is, master ports reached from a slave one.
// start: slave port of processor: flag = true.
// next: is_master, flag -> save, unset, continue
// next: is_master, !flag -> continue
// next: is_slave, !flag -> set
// un po' piu complessa: devo salvare su una mappa le master attraversate e fare context swith con le slaves, di modo che le master siano sbiancate on backtrack delle slaves. questo perche lo stesso componente
//puo essere attraversato in piu direzioni e se le master sono scurite si perdono informazioni.
masters_task_setter_visitor::colormap master_setter_map = get(boost::vertex_color, ifg);
for(std::vector<timing_vertex_t>::iterator processor_iter = processor_vertex_t.begin();processor_iter != processor_vertex_t.end();++processor_iter)
{
std::vector<timing_vertex_t> result;
for (ftvp = vertices(ifg); ftvp.first != ftvp.second; ++ftvp.first)
master_setter_map[*ftvp.first] = boost::default_color_type::white_color;
masters_task_setter_visitor master_setter_vis = masters_task_setter_visitor(result, name_to_node_map);
master_setter_vis.vertex_coloring=master_setter_map;
boost::depth_first_visit(ifg, *processor_iter,master_setter_vis, master_setter_map);
//analyze result.
for(std::vector<timing_vertex_t>::iterator result_it = result.begin(); result_it != result.end(); ++result_it)
for(std::vector <std::string>::iterator task_it =processor_to_task_map.at(*processor_iter).begin();task_it != processor_to_task_map.at(*processor_iter).end(); ++task_it)
ig[*result_it].master_tasks.insert(*task_it);
}
for (tvp = vertices(ig); tvp.first != tvp.second; ++tvp.first)
{
PRINT_DEBUG("after master setter step. the master of: "+ig[*tvp.first].name+" are (size): "+boost::lexical_cast<std::string>(ig[*tvp.first].master_tasks.size()));
for (std::set<std::string>::iterator debug_iter=ig[*tvp.first].master_tasks.begin();debug_iter!=ig[*tvp.first].master_tasks.end();++debug_iter)
PRINT_DEBUG("and the task are: "+*debug_iter);
}
}
timing_vertex_t timing_internal_graph::get_node_reference(std::string str)
{
timing_vertex_iter vi, vi_end;
boost::tie(vi, vi_end) = boost::vertices(ig);
for (; vi != vi_end; ++vi)
{
if (ig[*vi].name == str)
return *vi;
}
throw std::runtime_error ("node "+str+" does not exist in the graph");
return Timing_Graph::null_vertex();
}
bool timing_internal_graph::search_path(std::string from, std::string to, Layer l)
{
//check from and to are valid names for the graph:
if (get_node_reference(from)== Timing_Graph::null_vertex())
throw std::runtime_error ("node "+from+" does not exist in the graph");
if (get_node_reference(to)== Timing_Graph::null_vertex())
throw std::runtime_error ("node "+to+" does not exist in the graph");
PRINT_DEBUG("from is: "+from +"and get_node_reference(from) returns vertex: "+ig[get_node_reference(from)].name);
PRINT_DEBUG("to is: "+to +"and get_node_reference(from) returns vertex: "+ig[get_node_reference(to)].name);
boost::filtered_graph<Timing_Graph,true_edge_predicate<Timing_Graph>,layer_filter_vertex_predicate_c> ifg (ig,true_edge_predicate<Timing_Graph>(ig),layer_filter_vertex_predicate_c(ig,l));
PRINT_DEBUG("in the filtered graph those nodes are from: "+ifg[get_node_reference(from)].name+" and to: "+ifg[get_node_reference(to)].name);
exploration_from_interferes_with_to_visitor::colormap master_setter_map = get(boost::vertex_color, ifg);
std::pair<boost::filtered_graph<Timing_Graph,true_edge_predicate<Timing_Graph>,layer_filter_vertex_predicate_c>::vertex_iterator, boost::filtered_graph<Timing_Graph,true_edge_predicate<Timing_Graph>,layer_filter_vertex_predicate_c>::vertex_iterator> ftvp;
for (ftvp = vertices(ifg); ftvp.first != ftvp.second; ++ftvp.first)
master_setter_map[*ftvp.first] = boost::default_color_type::white_color;
exploration_from_interferes_with_to_visitor master_setter_vis = exploration_from_interferes_with_to_visitor(get_node_reference(to), name_to_node_map, l);
master_setter_vis.vertex_coloring=master_setter_map;
try {
boost::depth_first_visit(ifg, get_node_reference(from),master_setter_vis, master_setter_map);
}
catch (std::runtime_error e)
{
//std::cout << e.what();
return false;
}
#if 0
vertex_t source_os;
if (l != CONTROLLER)
{
boost::graph_traits<Timing_Graph>::out_edge_iterator edges_out, edges_out_end;
boost::tie (edges_out,edges_out_end) = boost::out_edges(get_node_reference(from),ig);
for(;edges_out != edges_out_end; ++edges_out)
{
PRINT_DEBUG("considered edge is: ("+ig[boost::source(*edges_out,ig)].name+" , "+ig[boost::target(*edges_out,ig)].name+")");
if (ig[boost::target(*edges_out,ig)].layer == CONTROLLER)
{
PRINT_DEBUG("if condition is true" );
source_os = boost::target(*edges_out,ig);
break;
}
}
PRINT_DEBUG ("starting search. source OS is: "+ig[source_os].name);
}
else
{
source_os=0;
PRINT_DEBUG ("starting search. else branch source OS is: "+ig[source_os].name);
}
std::vector<vertex_t> path;
boost::filtered_graph<Timing_Graph,inner_edge_predicate_c,inner_vertex_predicate_c> ifg (ig,inner_edge_predicate_c(ig,l,get_node_reference(to))/*doesnt really matter. can be deleted*/,inner_vertex_predicate_c(ig,l,ig[source_os].name));
source_to_target_visitor vis = source_to_target_visitor(path,get_node_reference(to));
//#if 0
std::ofstream myfile;
myfile.open ("/home/emanuele/Documents/tmp_graph/aaafiltrato.dot");
boost::write_graphviz(myfile, ifg,make_vertex_writer(boost::get(&Custom_Vertex::layer, ifg),boost::get (&Custom_Vertex::name, ifg),boost::get(&Custom_Vertex::ports, ifg), boost::get(&Custom_Vertex::type,ifg ), boost::get(&Custom_Vertex::priority_category,ifg))
,/*make_edge_writer(boost::get(&Custom_Edge::priority,ig),boost::get(&Custom_Edge::from_port,ig),boost::get(&Custom_Edge::to_port,ig))*/
boost::make_label_writer(boost::get(&Custom_Edge::priority,ig)));
myfile.close();
//#endif
try {
boost::depth_first_search(
ifg, boost::root_vertex(get_node_reference(from)).visitor(vis)
);
}
catch (int exception) {
if (exception == 3)
{
PRINT_DEBUG ("SEARCH: path found, and is:");
for (vertex_t v : path)
{
PRINT_DEBUG(ig[v].name); //TODO ricompattare gli "esplosi" se ne vale la pena. senti il capo.
}
return true;
}
else if (exception == 2)
{
PRINT_DEBUG ("SEARCH: restarting, path not foundd");
return false;
}
}
#endif
return true;
}
#if 0
//posso usarla per entrambe le ricerche. reverse "decide" se grafo dritto (ovvero this node interferes with) oppure al contrario (this node is interfered by)
void timing_internal_graph::search_interfered_nodes (std::string source, bool reverse)
{
PRINT_DEBUG("interfered node search: start");
vertex_t source_os;
boost::graph_traits<Timing_Graph>::out_edge_iterator edges_out, edges_out_end;
boost::tie (edges_out,edges_out_end) = boost::out_edges(get_node_reference(source),ig);
for(;edges_out != edges_out_end; ++edges_out)
{
PRINT_DEBUG("interfered node search considered edge is: ("+ig[boost::source(*edges_out,ig)].name+" , "+ig[boost::target(*edges_out,ig)].name+")");
if (ig[boost::target(*edges_out,ig)].layer == CONTROLLER)
{
PRINT_DEBUG("interfered node search if condition is true" );
source_os = boost::target(*edges_out,ig);
break;
}
}
PRINT_DEBUG ("interfered node search starting search. source OS is: "+ig[source_os].name);
std::vector<vertex_t> controller_reached_tasks;
std::vector<vertex_t> components_reached_tasks;
std::vector<vertex_t> physical_reached_tasks;
//Timing_Graph target_graph = reverse ?boost::make_reverse_graph(ig) :ig;
boost::filtered_graph<Timing_Graph,inner_edge_predicate_c,inner_vertex_predicate_c> ifg (target_graph,inner_edge_predicate_c(target_graph,LAYER_ERROR,get_node_reference(0))/*doesnt really matter. can be deleted*/,inner_vertex_predicate_c(target_graph,l,ig[source_os].name));
interference_visitor vis_con = interference_visitor(controller_reached_tasks);
interference_visitor vis_com = interference_visitor(components_reached_tasks);
interference_visitor vis_phy = interference_visitor(physical_reached_tasks);
try {
boost::depth_first_search(
ifg, boost::root_vertex(get_node_reference(source)).visitor(vis_con)
);
}
catch (int exception) {
if (exception == 2)
{
PRINT_DEBUG ("SEARCH: restarting, path not foundd");
for (vertex_t v : controller_reached_tasks)
{
PRINT_DEBUG(target_graph[v].name); //TODO ricompattare gli "esplosi" se ne vale la pena. senti il capo.
}
}
}
try {
boost::depth_first_search(
ifg, boost::root_vertex(get_node_reference(source)).visitor(vis_com)
);
}
catch (int exception) {
if (exception == 2)
{
PRINT_DEBUG ("SEARCH: restarting, path not foundd");
for (vertex_t v : components_reached_tasks)
{
PRINT_DEBUG(target_graph[v].name); //TODO ricompattare gli "esplosi" se ne vale la pena. senti il capo.
}
}
}
try {
boost::depth_first_search(
ifg, boost::root_vertex(get_node_reference(source)).visitor(vis_phy)
);
}
catch (int exception) {
if (exception == 2)
{
PRINT_DEBUG ("SEARCH: restarting, path not foundd");
for (vertex_t v : physical_reached_tasks)
{
PRINT_DEBUG(target_graph[v].name); //TODO ricompattare gli "esplosi" se ne vale la pena. senti il capo.
}
}
}
}
#endif | [
"vitali.ema@hotmail.it"
] | vitali.ema@hotmail.it |
c1e7472e39f0b344d4fca6bd44fc67f300b3280d | 9ebede2bbe515e7e0c5b24284ae91fd1ce759de4 | /labust_mission/include/labust_mission/serviceCall.hpp | f5f3ef3310f5af631fb81c8ac481270b1bfe3148 | [] | no_license | compiaffe/labust-ros-pkg | f0476f73c8a51d12d404a47c0703515eb0e75dfc | e4e5fc2093575932d6d86cb23ff652848171461c | refs/heads/master | 2021-01-18T16:52:18.457602 | 2014-08-26T16:27:58 | 2014-08-26T16:27:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,409 | hpp |
/*********************************************************************
* serviceCall.hpp
*
* Created on: Feb 26, 2014
* Author: Filip Mandic
*
********************************************************************/
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2014, LABUST, UNIZG-FER
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the LABUST nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#ifndef SERVICECALL_HPP_
#define SERVICECALL_HPP_
#include <ros/ros.h>
namespace utils {
template <typename custom_srv>
void callService(ros::ServiceClient& client, custom_srv& request){
if (client.call(request)){
ROS_INFO("Call to service %s successful", client.getService().c_str());
} else {
ROS_ERROR("Call to service %s failed", client.getService().c_str());
}
}
}
#endif /* SERVICECALL_HPP_ */
| [
"filip.mandic@gmail.com"
] | filip.mandic@gmail.com |
52f55123b63e1c1d68a253a92e37cbca9eff51d3 | 4cdaf1bcf4ade491da75053d5240fc5b8c3c0566 | /TIDCore/TIDModel.cpp | f019ea714e92ab4fae017b53322e3a4f009cb179 | [] | no_license | presscad/Tid | 2deae59b344363e0ce132ae8d8c5a6d422eee489 | 528afa2fea893e3131fa8bb7673363fba5d6e67b | refs/heads/master | 2021-02-15T20:28:35.226199 | 2020-02-26T07:57:09 | 2020-02-26T07:57:09 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 81,676 | cpp | #include "StdAfx.h"
#include "tidmodel.h"
#include "SegI.h"
#include "list.h"
#include "ArrayList.h"
#include "LogFile.h"
#include "WirePlaceCode.h"
#if defined(_DEBUG)&&!defined(_DISABLE_DEBUG_NEW_)
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
//////////////////////////////////////////////////////////////////////////
// 全局工具函数
#ifndef _DISABLE_MOD_CORE_
#include "ModCore.h"
static GECS TransToUcs(MOD_CS modCs)
{
GECS cs;
cs.origin.Set(modCs.origin.x,modCs.origin.y,modCs.origin.z);
cs.axis_x.Set(modCs.axisX.x,modCs.axisX.y,modCs.axisX.z);
cs.axis_y.Set(modCs.axisY.x,modCs.axisY.y,modCs.axisY.z);
cs.axis_z.Set(modCs.axisZ.x,modCs.axisZ.y,modCs.axisZ.z);
return cs;
}
#endif
static TID_CS ConvertCSFrom(const GECS& ucs)
{
TID_CS cs;
cs.origin.Set(ucs.origin.x, ucs.origin.y, ucs.origin.z);
cs.axisX.Set(ucs.axis_x.x, ucs.axis_x.y, ucs.axis_x.z);
cs.axisY.Set(ucs.axis_y.x, ucs.axis_y.y, ucs.axis_y.z);
cs.axisZ.Set(ucs.axis_z.x, ucs.axis_z.y, ucs.axis_z.z);
return cs;
}
static UCS_STRU ConvertUCSFrom(const TID_CS& cs)
{
UCS_STRU ucs;
ucs.origin.Set(cs.origin.x, cs.origin.y, cs.origin.z);
ucs.axis_x.Set(cs.axisX.x, cs.axisX.y, cs.axisX.z);
ucs.axis_y.Set(cs.axisY.x, cs.axisY.y, cs.axisY.z);
ucs.axis_z.Set(cs.axisZ.x, cs.axisZ.y, cs.axisZ.z);
return ucs;
}
static bool IsIncludeObject(CFGWORD moduleCfgWord, BYTE arrQuadLegNo[4], CFGWORD objCfgWord, BYTE cLegQuad)
{
bool validpart = false;
if (cLegQuad == 0 || cLegQuad > 4)
{ //cLegQuad>4时表示数据不合法,暂按塔身处理 wjh-2016.2.16
if (objCfgWord.And(moduleCfgWord))
validpart = true;
}
else if (cLegQuad <= 4)
{
if (objCfgWord.IsHasNo(arrQuadLegNo[cLegQuad - 1]))
validpart = true;
}
return validpart;
}
static bool IsIncludeObject(CFGWORD moduleCfgWord, CFGWORD objCfgWord, BYTE cLegQuad)
{
bool validpart = false;
if (cLegQuad == 0 || cLegQuad > 4)
{ //cLegQuad>4时表示数据不合法,暂按塔身处理
if (objCfgWord.And(moduleCfgWord))
validpart = true;
}
else
{ //1~4时,按塔腿处理
if (moduleCfgWord.And(objCfgWord))
validpart = true;
}
return validpart;
}
//////////////////////////////////////////////////////////////////////////
// CTidModel
CTidModel::CTidModel(long serial/*=0*/)
{
m_iSerial=serial;
m_dwAssmblyIter=1;
m_dwBoltCount=m_dwPartCount=m_dwBlockCount=0;
}
CTidModel::~CTidModel()
{
}
bool CTidModel::ReadTidFile(const char* file_path)
{
FILE* fp=fopen(file_path,"rb");
if(fp==NULL)
return false;
fseek(fp,0,SEEK_END);
DWORD file_len=ftell(fp);
fseek(fp,0,SEEK_SET);
DYN_ARRAY<char> pool(file_len);
fread(pool,1,file_len,fp);
fclose(fp);
InitTidBuffer(pool,file_len);
return true;
}
bool CTidModel::InitTidBuffer(const char* src_buf,long buf_len)
{
if(!m_xTidBuffer.InitBuffer(src_buf,buf_len))
return false;
m_xModuleSection=m_xTidBuffer.ModuleSection();
m_xFoundationSection = m_xTidBuffer.SubLegFoundationSection();
m_xWireNodeSection = m_xTidBuffer.WireNodeSection();
m_xProjectInfoSection = m_xTidBuffer.ProjectInfoSection();
m_xPartSection=m_xTidBuffer.PartSection();
m_xBoltLib.sectdata=m_xTidBuffer.BoltSection();
m_xBlockSection=m_xTidBuffer.BlockSection();
m_xAssembleSection=m_xTidBuffer.AssembleSection();
m_xNodeSection=m_xAssembleSection.NodeSection();
m_xAssemblyParts=m_xAssembleSection.PartSection();
m_xAssemblyBolts=m_xAssembleSection.BoltSection();
m_dwPartCount=m_xAssemblyParts.AssemblyCount();
m_dwBoltCount=m_xAssemblyBolts.AssemblyCount();
m_dwBlockCount=m_xBlockSection.GetBlockCount();
//
m_xBoltLib.hashBoltSeries.Empty();
hashHeightGroup.Empty();
hashHangPoint.Empty();
hashTidNode.Empty();
hashAssemblePart.Empty();
hashAssembleBolt.Empty();
hashAssembleAnchorBolt.Empty();
InitTidDataInfo();
return true;
}
void CTidModel::InitTidDataInfo()
{
UINT uCount = 0, iHuGaoKey = 0, iPartKey = 0, iBoltKey = 0, iNodeKey = 0;
//提取呼高信息
uCount = m_xModuleSection.GetModuleCount();
for (UINT i = 0; i < uCount; i++)
{
CTidHeightGroup* pHeightGroup = hashHeightGroup.Add(++iHuGaoKey);
pHeightGroup->m_pModel = this;
pHeightGroup->module = m_xModuleSection.GetModuleAt(i);
}
//节点信息
CTidNode* pTidNode = NULL;
uCount = m_xNodeSection.NodeCount();
for (UINT i = 0; i < uCount; i++)
{
NODE_ASSEMBLY node;
m_xNodeSection.GetNodeByIndexId(i + 1, true, node);
//
pTidNode = hashTidNode.Add(++iNodeKey);
pTidNode->SetBelongModel(this);
pTidNode->node = node;
}
uCount = m_xNodeSection.NodeCount(false);
for (UINT i = 0; i < uCount; i++)
{
NODE_ASSEMBLY node;
m_xNodeSection.GetNodeByIndexId(i + 1, false, node);
UINT uBlkRef = m_xAssembleSection.BlockAssemblyCount();
for (UINT indexId = 1; indexId <= uBlkRef; indexId++)
{
BLOCK_ASSEMBLY blkassembly = m_xAssembleSection.GetAssemblyByIndexId(indexId);
if (blkassembly.wIndexId != node.wBlockIndexId)
continue; //该构件不属于当前部件装配对象
TOWER_BLOCK block = m_xBlockSection.GetBlockAt(blkassembly.wIndexId - 1);
node.xPosition = block.lcs.TransPToCS(node.xPosition);
node.xPosition = blkassembly.acs.TransPFromCS(node.xPosition);
//
pTidNode = hashTidNode.Add(++iNodeKey);
pTidNode->SetBelongModel(this);
pTidNode->node = node;
}
}
//提取杆塔装配构件
CTidAssemblePart* pAssmPart = NULL;
uCount = m_xAssemblyParts.AssemblyCount();
for (UINT i = 0; i < uCount; i++)
{
PART_ASSEMBLY assemble;
m_xAssemblyParts.GetAssemblyByIndexId(i + 1, true, assemble);
PART_INFO partinfo = m_xPartSection.GetPartInfoByIndexId(assemble.dwIndexId);
//
pAssmPart = hashAssemblePart.Add(++iPartKey);
pAssmPart->SetBelongModel(this);
pAssmPart->part = assemble;
pAssmPart->solid.CopySolidBuffer(partinfo.solid.BufferPtr(), partinfo.solid.BufferLength());
pAssmPart->solid.TransToACS(ConvertCSFrom(assemble.acs));
}
//提取部件装配构件
uCount = m_xAssemblyParts.AssemblyCount(false);
for (UINT i = 0; i < uCount; i++)
{
PART_ASSEMBLY assemble;
m_xAssemblyParts.GetAssemblyByIndexId(i + 1, false, assemble);
PART_INFO partinfo = m_xPartSection.GetPartInfoByIndexId(assemble.dwIndexId);
UINT uBlkRef = m_xAssembleSection.BlockAssemblyCount();
for (UINT indexId = 1; indexId <= uBlkRef; indexId++)
{
BLOCK_ASSEMBLY blkassembly = m_xAssembleSection.GetAssemblyByIndexId(indexId);
if (blkassembly.wIndexId != assemble.wBlockIndexId)
continue; //该构件不属于当前部件装配对象
TOWER_BLOCK block = m_xBlockSection.GetBlockAt(blkassembly.wIndexId - 1);
//
pAssmPart = hashAssemblePart.Add(++iPartKey);
pAssmPart->SetBelongModel(this);
pAssmPart->part = assemble;
pAssmPart->solid.CopySolidBuffer(partinfo.solid.BufferPtr(), partinfo.solid.BufferLength());
pAssmPart->solid.TransToACS(ConvertCSFrom(assemble.acs));
pAssmPart->solid.TransACS(ConvertCSFrom(block.lcs), ConvertCSFrom(blkassembly.acs));
}
}
//提取杆塔装配螺栓
IBoltSeriesLib* pBoltLibrary = GetBoltLib();
uCount = m_xAssemblyBolts.AssemblyCount();
for (UINT i = 0; i < uCount; i++)
{
BOLT_ASSEMBLY assemble;
assemble = m_xAssemblyBolts.GetAssemblyByIndexId(i + 1, true);
IBoltSeries* pBoltSeries = pBoltLibrary->GetBoltSeriesAt(assemble.cSeriesId - 1);
IBoltSizeSpec* pBoltSize = pBoltSeries->GetBoltSizeSpecById(assemble.wIndexId);
if (pBoltSize == NULL)
{
logerr.Log("BoltSizeSpec@%d not found!\n", assemble.wIndexId);
continue;
}
CTidSolidBody* pBoltSolid = (CTidSolidBody*)pBoltSize->GetBoltSolid();
CTidSolidBody* pNutSolid = (CTidSolidBody*)pBoltSize->GetNutSolid();
if (pBoltSolid == NULL || pNutSolid == NULL)
{
logerr.Log("BoltSolid@%d not found!\n", assemble.wIndexId);
continue;
}
//
CTidAssembleBolt* pAssmBolt = hashAssembleBolt.Add(++iBoltKey);
pAssmBolt->SetBelongModel(this);
pAssmBolt->bolt = assemble;
pAssmBolt->solid.bolt.CopySolidBuffer(pBoltSolid->SolidBufferPtr(), pBoltSolid->SolidBufferLength());
pAssmBolt->solid.nut.CopySolidBuffer(pNutSolid->SolidBufferPtr(), pNutSolid->SolidBufferLength());
TID_CS bolt_acs, nut_acs;
nut_acs = bolt_acs = pAssmBolt->GetAcs();
nut_acs.origin.x += bolt_acs.axisZ.x*assemble.wL0;
nut_acs.origin.y += bolt_acs.axisZ.y*assemble.wL0;
nut_acs.origin.z += bolt_acs.axisZ.z*assemble.wL0;
pAssmBolt->solid.bolt.TransToACS(bolt_acs);
pAssmBolt->solid.nut.TransToACS(nut_acs);
}
//提取部件装配螺栓
uCount = m_xAssemblyBolts.AssemblyCount(false);
for (UINT i = 0; i < uCount; i++)
{
BOLT_ASSEMBLY assemble = m_xAssemblyBolts.GetAssemblyByIndexId(i + 1, false);
IBoltSeries* pBoltSeries = pBoltLibrary->GetBoltSeriesAt(assemble.cSeriesId - 1);
IBoltSizeSpec* pBoltSize = pBoltSeries->GetBoltSizeSpecById(assemble.wIndexId);
if (pBoltSize == NULL)
{
logerr.Log("BoltSizeSpec@%d not found!\n", assemble.wIndexId);
continue;
}
CTidSolidBody* pBoltSolid = (CTidSolidBody*)pBoltSize->GetBoltSolid();
CTidSolidBody* pNutSolid = (CTidSolidBody*)pBoltSize->GetNutSolid();
if (pBoltSolid == NULL || pNutSolid == NULL)
{
logerr.Log("BoltSolid@%d not found!\n", assemble.wIndexId);
continue;
}
UINT uBlkRef = m_xAssembleSection.BlockAssemblyCount();
for (UINT indexId = 1; indexId <= uBlkRef; indexId++)
{
BLOCK_ASSEMBLY blkassembly = m_xAssembleSection.GetAssemblyByIndexId(indexId);
if (blkassembly.wIndexId != assemble.wBlockIndexId)
continue; //该构件不属于当前部件装配对象
TOWER_BLOCK block = m_xBlockSection.GetBlockAt(blkassembly.wIndexId - 1);
//
CTidAssembleBolt* pAssmBolt = hashAssembleBolt.Add(++iBoltKey);
pAssmBolt->SetBelongModel(this);
pAssmBolt->bolt = assemble;
pAssmBolt->solid.bolt.CopySolidBuffer(pBoltSolid->SolidBufferPtr(), pBoltSolid->SolidBufferLength());
pAssmBolt->solid.nut.CopySolidBuffer(pNutSolid->SolidBufferPtr(), pNutSolid->SolidBufferLength());
TID_CS bolt_acs, nut_acs;
nut_acs = bolt_acs = pAssmBolt->GetAcs();
nut_acs.origin.x += bolt_acs.axisZ.x*assemble.wL0;
nut_acs.origin.y += bolt_acs.axisZ.y*assemble.wL0;
nut_acs.origin.z += bolt_acs.axisZ.z*assemble.wL0;
pAssmBolt->solid.bolt.TransToACS(bolt_acs);
pAssmBolt->solid.nut.TransToACS(nut_acs);
pAssmBolt->solid.bolt.TransACS(ConvertCSFrom(block.lcs), ConvertCSFrom(blkassembly.acs));
pAssmBolt->solid.nut.TransACS(ConvertCSFrom(block.lcs), ConvertCSFrom(blkassembly.acs));
}
}
//解析工程信息内存区
for (int i = 0; i < m_xProjectInfoSection.m_ciSubProjSectionCount; i++)
{
CProjInfoSubSection xSubSection= m_xProjectInfoSection.GetSubSectionAt(i);
CBuffer sectbuf(xSubSection.BufferPtr(), xSubSection.BufferLength());
if (xSubSection.m_uidSubSection == 23545686)
{ //GIM工程属性信息
sectbuf.Read(m_xGimFileHeadInfo.m_sFileTag, 16);
sectbuf.Read(m_xGimFileHeadInfo.m_sFileName, 256);
sectbuf.Read(m_xGimFileHeadInfo.m_sDesigner, 64);
sectbuf.Read(m_xGimFileHeadInfo.m_sUnit, 256);
sectbuf.Read(m_xGimFileHeadInfo.m_sSoftName, 128);
sectbuf.Read(m_xGimFileHeadInfo.m_sTime, 16);
sectbuf.Read(m_xGimFileHeadInfo.m_sSoftMajorVer, 8);
sectbuf.Read(m_xGimFileHeadInfo.m_sSoftMinorVer, 8);
sectbuf.Read(m_xGimFileHeadInfo.m_sMajorVersion, 8);
sectbuf.Read(m_xGimFileHeadInfo.m_sMinorVersion, 8);
sectbuf.Read(m_xGimFileHeadInfo.m_sBufSize, 8);
//
sectbuf.ReadInteger(&m_xGimPropertyInfo.m_nCircuit);
sectbuf.ReadDouble(&m_xGimPropertyInfo.m_fWindSpeed);
sectbuf.ReadDouble(&m_xGimPropertyInfo.m_fNiceThick);
sectbuf.ReadDouble(&m_xGimPropertyInfo.m_fFrontRulingSpan);
sectbuf.ReadDouble(&m_xGimPropertyInfo.m_fBackRulingSpan);
sectbuf.ReadDouble(&m_xGimPropertyInfo.m_fMaxSpan);
sectbuf.ReadDouble(&m_xGimPropertyInfo.m_fDesignKV);
sectbuf.ReadDouble(&m_xGimPropertyInfo.m_fFrequencyRockAngle);
sectbuf.ReadDouble(&m_xGimPropertyInfo.m_fLightningRockAngle);
sectbuf.ReadDouble(&m_xGimPropertyInfo.m_fSwitchingRockAngle);
sectbuf.ReadDouble(&m_xGimPropertyInfo.m_fWorkingRockAngle);
sectbuf.ReadString(m_xGimPropertyInfo.m_sVoltGrade);
sectbuf.ReadString(m_xGimPropertyInfo.m_sType);
sectbuf.ReadString(m_xGimPropertyInfo.m_sTexture);
sectbuf.ReadString(m_xGimPropertyInfo.m_sFixedType);
sectbuf.ReadString(m_xGimPropertyInfo.m_sTaType);
sectbuf.ReadString(m_xGimPropertyInfo.m_sCWireSpec);
sectbuf.ReadString(m_xGimPropertyInfo.m_sEWireSpec);
sectbuf.ReadString(m_xGimPropertyInfo.m_sWindSpan);
sectbuf.ReadString(m_xGimPropertyInfo.m_sWeightSpan);
sectbuf.ReadString(m_xGimPropertyInfo.m_sAngleRange);
sectbuf.ReadString(m_xGimPropertyInfo.m_sRatedHeight);
sectbuf.ReadString(m_xGimPropertyInfo.m_sHeightRange);
sectbuf.ReadString(m_xGimPropertyInfo.m_sTowerWeight);
sectbuf.ReadString(m_xGimPropertyInfo.m_sManuFacturer);
sectbuf.ReadString(m_xGimPropertyInfo.m_sMaterialCode);
sectbuf.ReadString(m_xGimPropertyInfo.m_sProModelCode);
}
if (xSubSection.m_uidSubSection == 11111111)
{ //挂点信息
WORD nCount = 0;
sectbuf.ReadWord(&nCount);
for (int i = 0; i < nCount; i++)
{
CTidHangPoint* pHangPoint = hashHangPoint.Add(i + 1);
sectbuf.SeekPosition(2 + i * 112);
sectbuf.ReadWord(&pHangPoint->wireNode.wiCode);
sectbuf.ReadPoint(pHangPoint->wireNode.position);
sectbuf.ReadPoint(pHangPoint->wireNode.relaHolePt[0]);
sectbuf.ReadPoint(pHangPoint->wireNode.relaHolePt[1]);
sectbuf.Read(pHangPoint->wireNode.name, 38);
}
}
}
}
int CTidModel::GetTowerTypeName(char* towerTypeName,UINT maxBufLength/*=0*/)
{
StrCopy(towerTypeName,m_xTidBuffer.GetTowerType(),maxBufLength);
return strlen(towerTypeName);
}
TID_CS CTidModel::ModelCoordSystem()
{
GECS cs=m_xTidBuffer.ModelCoordSystem();
TID_CS tidCS;
tidCS.origin=cs.origin;
tidCS.axisX=cs.axis_x;
tidCS.axisY=cs.axis_y;
tidCS.axisZ=cs.axis_z;
return tidCS;
}
double CTidModel::GetNamedHeightZeroZ()
{
return m_xModuleSection.m_fNamedHeightZeroZ;
}
//基础地脚螺栓信息
bool CTidModel::GetAnchorBoltSolid(CTidSolidBody* pBoltSolid,CTidSolidBody* pNutSolid)
{
if(compareVersion(m_xTidBuffer.Version(),"1.4")>=0)
{
pBoltSolid->CopySolidBuffer(m_xBoltLib.sectdata.xAnchorSolid.bolt.BufferPtr(),m_xBoltLib.sectdata.xAnchorSolid.bolt.BufferLength());
pNutSolid->CopySolidBuffer(m_xBoltLib.sectdata.xAnchorSolid.nut.BufferPtr(),m_xBoltLib.sectdata.xAnchorSolid.nut.BufferLength());
return true;
}
else
return false;
}
WORD CTidModel::GetBasePlateThick()
{
return m_xFoundationSection.ciBasePlateThick;
}
WORD CTidModel::GetAnchorCount()
{
return m_xFoundationSection.cnAnchorBoltCount;
}
bool CTidModel::GetAnchorAt(short index,short* psiPosX,short* psiPosY)
{
if(index<0||index>=m_xFoundationSection.cnAnchorBoltCount)
return false;
ANCHOR_LOCATION location=m_xFoundationSection.GetAnchorLocationAt((short)index);
if(psiPosX)
*psiPosX=location.siPosX;
if(psiPosY)
*psiPosY=location.siPosY;
return true;
}
WORD CTidModel::GetSubLegCount(BYTE ciBodySerial)
{
return m_xFoundationSection.cnSubLegCount;
}
//获取指定呼高下某接腿的基础坐标
bool CTidModel::GetSubLegBaseLocation(BYTE ciBodySerial,BYTE ciLegSerial,double* pos3d)
{
GEPOINT pos=m_xFoundationSection.GetSubLegFoundationOrgBySerial(ciBodySerial,ciLegSerial);
if(pos3d!=NULL)
memcpy(pos3d,(double*)pos,24);
return true;
}
//获取指定呼高下某接腿的基础根开
double CTidModel::GetSubLegBaseWidth(BYTE ciBodySerial, BYTE ciLegSerial)
{
GEPOINT pos = m_xFoundationSection.GetSubLegFoundationOrgBySerial(ciBodySerial, ciLegSerial);
double fHalfFrontBaseWidth = pos.x;
return fHalfFrontBaseWidth * 2;
}
ISteelMaterialLibrary* CTidModel::GetSteelMatLib()
{
m_xSteelMatLib.matsect=m_xPartSection.GetMatLibrarySection();
return &m_xSteelMatLib;
}
ITidPartsLib* CTidModel::GetTidPartsLib()
{
m_xPartLib.sectdata=m_xTidBuffer.PartSection();
return &m_xPartLib;
}
IBoltSeriesLib* CTidModel::GetBoltLib()
{
m_xBoltLib.sectdata=m_xTidBuffer.BoltSection();
return &m_xBoltLib;
}
ITidHeightGroup* CTidModel::GetHeightGroupAt(short i)
{
if(i<0||i>=m_xModuleSection.GetModuleCount())
return NULL;
CTidHeightGroup* pHeightGroup=hashHeightGroup.GetValue(i+1);
if(pHeightGroup==NULL)
{
pHeightGroup=hashHeightGroup.Add(i+1);
pHeightGroup->module=m_xModuleSection.GetModuleAt(i);
}
pHeightGroup->m_pModel=this;
return pHeightGroup;
}
ITidHangPoint* CTidModel::GetHangPointAt(DWORD i)
{
if(i<0||i>m_xWireNodeSection.m_wnWireNodeCount)
return NULL;
CTidHangPoint* pHangPoint=hashHangPoint.GetValue(i+1);
if(pHangPoint==NULL)
{
pHangPoint=hashHangPoint.Add(i+1);
pHangPoint->wireNode=m_xWireNodeSection.GetWireNodeAt(i);
}
pHangPoint->m_pModel=this;
return pHangPoint;
}
ITidNode* CTidModel::EnumTidNodeFirst(long hHeightSerial /*= 0*/)
{
ITidNode* pTidNode = hashTidNode.GetFirst();
if (hHeightSerial == 0)
return pTidNode;
else
{
CTidHeightGroup* pHuGao = (CTidHeightGroup*)GetHeightGroup(hHeightSerial);
if (pHuGao == NULL)
{
logerr.Log("%d呼高不存在!", hHeightSerial);
return NULL;
}
while (pTidNode != NULL)
{
CFGWORD node_cfg = ((CTidNode*)pTidNode)->node.cfgword;
if (IsIncludeObject(pHuGao->module.m_dwLegCfgWord, node_cfg, pTidNode->GetLegQuad()))
return pTidNode;
else
pTidNode = hashTidNode.GetNext();
}
return NULL;
}
}
ITidNode* CTidModel::EnumTidNodeNext(long hHeightSerial /*= 0*/)
{
ITidNode* pTidNode = hashTidNode.GetNext();
if (hHeightSerial == 0)
return pTidNode;
else
{
CTidHeightGroup* pHuGao = (CTidHeightGroup*)GetHeightGroup(hHeightSerial);
if (pHuGao == NULL)
{
logerr.Log("%d呼高不存在!", hHeightSerial);
return NULL;
}
while (pTidNode != NULL)
{
CFGWORD node_cfg = ((CTidNode*)pTidNode)->node.cfgword;
if (IsIncludeObject(pHuGao->module.m_dwLegCfgWord, node_cfg, pTidNode->GetLegQuad()))
return pTidNode;
else
pTidNode = hashTidNode.GetNext();
}
return NULL;
}
}
ITidAssemblePart* CTidModel::EnumAssemblePartFirst(long hHeightSerial /*= 0*/)
{
ITidAssemblePart* pAssemPart = hashAssemblePart.GetFirst();
if (hHeightSerial == 0)
return pAssemPart;
else
{
CTidHeightGroup* pHuGao = (CTidHeightGroup*)GetHeightGroup(hHeightSerial);
if (pHuGao == NULL)
{
logerr.Log("%d呼高不存在!",hHeightSerial);
return NULL;
}
while (pAssemPart != NULL)
{
CFGWORD part_cfg = ((CTidAssemblePart*)pAssemPart)->part.cfgword;
if (IsIncludeObject(pHuGao->module.m_dwLegCfgWord, part_cfg,pAssemPart->GetLegQuad()))
return pAssemPart;
else
pAssemPart = hashAssemblePart.GetNext();
}
return NULL;
}
}
ITidAssemblePart* CTidModel::EnumAssemblePartNext(long hHeightSerial /*= 0*/)
{
ITidAssemblePart* pAssemPart = hashAssemblePart.GetNext();
if (hHeightSerial == 0)
return pAssemPart;
else
{
CTidHeightGroup* pHuGao = (CTidHeightGroup*)GetHeightGroup(hHeightSerial);
if (pHuGao == NULL)
{
logerr.Log("%d呼高不存在!", hHeightSerial);
return NULL;
}
while (pAssemPart != NULL)
{
CFGWORD part_cfg = ((CTidAssemblePart*)pAssemPart)->part.cfgword;
if (IsIncludeObject(pHuGao->module.m_dwLegCfgWord, part_cfg,pAssemPart->GetLegQuad()))
return pAssemPart;
else
pAssemPart = hashAssemblePart.GetNext();
}
return NULL;
}
}
ITidAssembleBolt* CTidModel::EnumAssembleBoltFirst(long hHeightSerial /*= 0*/)
{
ITidAssembleBolt* pAssemBolt = hashAssembleBolt.GetFirst();
if (hHeightSerial == 0)
return pAssemBolt;
else
{
CTidHeightGroup* pHuGao = (CTidHeightGroup*)GetHeightGroup(hHeightSerial);
if (pHuGao)
{
logerr.Log("%d呼高不存在!", hHeightSerial);
return NULL;
}
while (pAssemBolt != NULL)
{
CFGWORD bolt_cfg = ((CTidAssembleBolt*)pAssemBolt)->bolt.cfgword;
if (IsIncludeObject(pHuGao->module.m_dwLegCfgWord, bolt_cfg,pAssemBolt->GetLegQuad()))
return pAssemBolt;
else
pAssemBolt = hashAssembleBolt.GetNext();
}
return NULL;
}
}
ITidAssembleBolt* CTidModel::EnumAssembleBoltNext(long hHeightSerial /*= 0*/)
{
ITidAssembleBolt* pAssemBolt = hashAssembleBolt.GetNext();
if (hHeightSerial == 0)
return pAssemBolt;
else
{
CTidHeightGroup* pHuGao = (CTidHeightGroup*)GetHeightGroup(hHeightSerial);
if (pHuGao)
{
logerr.Log("%d呼高不存在!", hHeightSerial);
return NULL;
}
while (pAssemBolt != NULL)
{
CFGWORD bolt_cfg = ((CTidAssembleBolt*)pAssemBolt)->bolt.cfgword;
if (IsIncludeObject(pHuGao->module.m_dwLegCfgWord, bolt_cfg,pAssemBolt->GetLegQuad()))
return pAssemBolt;
else
pAssemBolt = hashAssembleBolt.GetNext();
}
return NULL;
}
}
bool CTidModel::ExportModFile(const char* sFileName)
{
#ifdef _DISABLE_MOD_CORE_
return false;
#else
IModModel* pModModel=CModModelFactory::CreateModModel();
//计算MOD模型的坐标系
double fMaxNodeZ=0;
UINT uCount=m_xNodeSection.NodeCount();
for(UINT i=0;i<uCount;i++)
{
NODE_ASSEMBLY node;
m_xNodeSection.GetNodeByIndexId(i+1,true,node);
if(fMaxNodeZ<node.xPosition.z)
fMaxNodeZ=node.xPosition.z;
}
pModModel->SetTowerHeight(fMaxNodeZ);
GECS ucs=TransToUcs(pModModel->BuildUcsByModCS());
//提取MOD呼高信息,建立MOD坐标系
for(int i=0;i<HeightGroupCount();i++)
{
CTidHeightGroup* pModule=(CTidHeightGroup*)GetHeightGroupAt(i);
//
IModHeightGroup* pHeightGroup=pModModel->AppendHeightGroup(pModule->GetSerialId());
pHeightGroup->SetBelongModel(pModModel);
pHeightGroup->SetLowestZ(pModule->GetLowestZ());
pHeightGroup->SetLegCfg(pModule->module.m_dwLegCfgWord.flag.bytes);
pHeightGroup->SetNameHeight(pModule->GetNamedHeight());
}
//提取节点信息
for(UINT i=0;i<uCount;i++)
{
NODE_ASSEMBLY node;
m_xNodeSection.GetNodeByIndexId(i+1,true,node);
GEPOINT org_pt=ucs.TransPFromCS(node.xPosition);
//
IModNode* pModNode=pModModel->AppendNode(i+1);
pModNode->SetBelongModel(pModModel);
pModNode->SetCfgword(node.cfgword.flag.bytes);
pModNode->SetLdsOrg(MOD_POINT(node.xPosition));
pModNode->SetOrg(MOD_POINT(org_pt));
if(node.cLegQuad>=1&&node.cLegQuad<=4)
pModNode->SetLayer('L'); //腿部Leg
else
pModNode->SetLayer('B'); //塔身Body
}
uCount=m_xAssemblyParts.AssemblyCount();
for(UINT i=0;i<uCount;i++)
{
PART_ASSEMBLY assemble;
m_xAssemblyParts.GetAssemblyByIndexId(i+1,true,assemble);
PART_INFO partinfo=m_xPartSection.GetPartInfoByIndexId(assemble.dwIndexId);
if(!assemble.bIsRod)
continue;
IModNode* pModNodeS=pModModel->FindNode(assemble.uiStartPointI);
IModNode* pModNodeE=pModModel->FindNode(assemble.uiEndPointI);
if(pModNodeS==NULL || pModNodeE==NULL)
continue; //短角钢
IModRod* pModRod=pModModel->AppendRod(i+1);
pModRod->SetBelongModel(pModModel);
pModRod->SetNodeS(pModNodeS);
pModRod->SetNodeE(pModNodeE);
pModRod->SetCfgword(assemble.cfgword.flag.bytes);
pModRod->SetMaterial(partinfo.cMaterial);
pModRod->SetWidth(partinfo.fWidth);
pModRod->SetThick(partinfo.fThick);
if(assemble.cLegQuad>=1&&assemble.cLegQuad<=4)
pModRod->SetLayer('L'); //腿部Leg
else
pModRod->SetLayer('B'); //塔身Body
if(partinfo.cPartType==1)
{
pModRod->SetRodType(1);
GEPOINT vec_wing_x=ucs.TransVToCS(assemble.acs.axis_x);
GEPOINT vec_wing_y=ucs.TransVToCS(assemble.acs.axis_y);
pModRod->SetWingXVec(MOD_POINT(vec_wing_x));
pModRod->SetWingYVec(MOD_POINT(vec_wing_y));
}
else
pModRod->SetRodType(2);
}
//提取挂点信息
int nHangPt=HangPointCount();
for(int i=0;i<nHangPt;i++)
{
ITidHangPoint* pHangPt=GetHangPointAt(i);
if(pHangPt==NULL)
continue;
CXhChar50 sDes;
pHangPt->GetWireDescription(sDes);
TID_COORD3D pt=pHangPt->GetPos();
//
MOD_HANG_NODE* pHangNode=pModModel->AppendHangNode();
pHangNode->m_xHangPos=ucs.TransPFromCS(f3dPoint(pt));
strcpy(pHangNode->m_sHangName,sDes);
pHangNode->m_ciWireType=pHangPt->GetWireType();
}
//初始化多胡高塔型的MOD结构
pModModel->InitMultiModData();
//生成Mod文件
FILE *fp=fopen(sFileName,"wt,ccs=UTF-8");
if(fp==NULL)
return false;
pModModel->WriteModFileByUtf8(fp);
return true;
#endif
}
//////////////////////////////////////////////////////////////////////////
// CTidHangPoint
short CTidHangPoint::GetWireDescription(char* sDes)
{
if(sDes)
{
strcpy(sDes,wireNode.name);
return strlen(wireNode.name);
}
else
return 0;
}
bool CTidHangPoint::IsCircuitDC()
{
WIREPLACE_CODE code(wireNode.wiCode);
return code.blCircuitDC;
}
BYTE CTidHangPoint::GetCircuitSerial()
{
WIREPLACE_CODE code(wireNode.wiCode);
return code.ciCircuitSerial;
}
BYTE CTidHangPoint::GetTensionType()
{
WIREPLACE_CODE code(wireNode.wiCode);
return code.ciTensionType;
}
BYTE CTidHangPoint::GetWireDirection()
{
WIREPLACE_CODE code(wireNode.wiCode);
return code.ciWireDirection;
}
BYTE CTidHangPoint::GetPhaseSerial()
{
WIREPLACE_CODE code(wireNode.wiCode);
return code.ciPhaseSerial;
}
BYTE CTidHangPoint::GetWireType()
{
WIREPLACE_CODE code(wireNode.wiCode);
return code.ciWireType;
}
BYTE CTidHangPoint::GetHangingStyle()
{
WIREPLACE_CODE code(wireNode.wiCode);
return code.ciHangingStyle;
}
BYTE CTidHangPoint::GetPostCode()
{
WIREPLACE_CODE code(wireNode.wiCode);
return code.ciPostCode;
}
BYTE CTidHangPoint::GetSerial()
{
WIREPLACE_CODE code(wireNode.wiCode);
return code.iSerial;
}
BYTE CTidHangPoint::GetPosSymbol()
{
WIREPLACE_CODE code(wireNode.wiCode);
if (code.ciWireType == 'J' || code.ciTensionType != 2)
return 0; //跳线及悬垂导地线不区分前后
if (code.ciWireDirection == 'Y') //线缆方向为Y即挂点在X横担上
{ //根据GIM规范要求:X向横担以Y轴正向为前,负向为后;但是建模坐标系的Y轴与GIM模型坐标系的Y轴是反向的
if (wireNode.position.y < -0.03)
return 'Q';
else
return 'H';
}
else //if(code.ciWireDirection=='X') //线缆方向为X即挂点在Y横担上
{ //根据GIM规范要求:Y向横担以X轴负向为前,正向为后;且建模坐标系的X轴与GIM模型坐标系的X轴同向
if (wireNode.position.x < -0.03)
return 'Q';
else
return 'H';
}
}
BYTE CTidHangPoint::GetRelaHoleNum()
{
int nNum = 0;
if (!wireNode.relaHolePt[0].IsZero())
nNum++;
if (!wireNode.relaHolePt[1].IsZero())
nNum++;
return nNum;
}
TID_COORD3D CTidHangPoint::GetRelaHolePos(int index)
{
if (index == 0)
return TID_COORD3D(wireNode.relaHolePt[0]);
else if(index==1)
return TID_COORD3D(wireNode.relaHolePt[1]);
else
return TID_COORD3D();
}
//////////////////////////////////////////////////////////////////////////
// CTidHeightGroup
int CTidHeightGroup::GetName(char *moduleName,UINT maxBufLength/*=0*/)
{
if(!StrCopy(moduleName,module.name,maxBufLength))
strcpy(moduleName,module.name);
return strlen(moduleName);
}
BYTE CTidHeightGroup::RetrieveSerialInitBitPos()
{
int ciInitSerialBitPosition=0;
for(int i=1;i<=192;i++)
{
if(module.m_dwLegCfgWord.IsHasNo(i))
return i;
}
return ciInitSerialBitPosition;
}
int CTidHeightGroup::GetLegSerialArr(int* legSerialArr)
{
ARRAY_LIST<int> legArr(0,8);
int legSerial=0;
for(int i=1;i<=192;i++)
{
if(module.m_dwLegCfgWord.IsHasNo(i))
{
if(legSerial==0)
legSerial=1;
legArr.append(legSerial);
}
if(legSerial>0)
legSerial++;
if(legSerial>24)
break; //一组呼高最多允许有24组接腿
}
if(legSerialArr!=NULL)
memcpy(legSerialArr,legArr.m_pData,sizeof(int)*legArr.GetSize());
return legArr.GetSize();
}
BYTE CTidHeightGroup::GetLegBitSerialFromSerialId(int serial)
{
int legBitSerial=0;
for(int i=1;i<=192;i++)
{
if(module.m_dwLegCfgWord.IsHasNo(i))
{
if(legBitSerial==0)
legBitSerial=1;
}
if(legBitSerial==serial)
return i;
if(legBitSerial>0)
legBitSerial++;
if(legBitSerial>24)
break; //一组呼高最多允许有24组接腿
}
return 0;
}
static int f2i(double fval)
{
if(fval>=0)
return (int)(fval+0.5);
else
return (int)(fval-0.5);
}
int CTidHeightGroup::GetLegSerial(double heightDifference)
{
int init_level=module.m_cbLegInfo>>6; //前三位是1号腿的反向垂高落差级别调节数
int level_height =module.m_cbLegInfo&0x3f; //分米
if(level_height==0)
level_height=15;
heightDifference*=10;
int nLevel=f2i(heightDifference)/level_height; //高度落差级数
return (init_level+1-nLevel);
}
double CTidHeightGroup::GetLegHeightDifference(int legSerial)
{
int init_level=module.m_cbLegInfo>>6; //前两位是1号腿的反向垂高落差级别调节数
int level_height =module.m_cbLegInfo&0x3f; //分米
if(level_height==0)
level_height=15;
return (init_level+1-legSerial)*level_height*0.1;
}
ITidTowerInstance* CTidHeightGroup::GetTowerInstance(int legSerialQuad1, int legSerialQuad2, int legSerialQuad3, int legSerialQuad4)
{
union UNIQUEID{
BYTE bytes[4];
DWORD id;
}key;
key.bytes[0]=GetLegBitSerialFromSerialId(legSerialQuad1);
key.bytes[1]=GetLegBitSerialFromSerialId(legSerialQuad2);
key.bytes[2]=GetLegBitSerialFromSerialId(legSerialQuad3);
key.bytes[3]=GetLegBitSerialFromSerialId(legSerialQuad4);
CTidTowerInstance* pTidTowerInstance=hashTowerInstance.Add(key.id);
pTidTowerInstance->SetBelongHeight(this);
memcpy(pTidTowerInstance->arrLegBitSerial,key.bytes,4);
pTidTowerInstance->InitAssemblePartAndBolt();
return pTidTowerInstance;
}
double CTidHeightGroup::GetLowestZ()
{
double fMaxNodeZ = 0;
ITidNode* pTidNode = NULL;
for (pTidNode = m_pModel->EnumTidNodeFirst(m_id); pTidNode; pTidNode = m_pModel->EnumTidNodeNext(m_id))
fMaxNodeZ = max(fMaxNodeZ, pTidNode->GetPos().z);
return fMaxNodeZ;
}
double CTidHeightGroup::GetBody2LegTransitZ()
{
double fTransitZ = 0;
ITidAssemblePart* pPart = NULL;
for (pPart = m_pModel->EnumAssemblePartFirst(m_id); pPart; pPart = m_pModel->EnumAssemblePartNext(m_id))
{
if(!pPart->IsHasBriefRodLine() ||
(pPart->GetLegQuad() >= 1 && pPart->GetLegQuad() <= 4))
continue; //非塔身杆件
fTransitZ = max(fTransitZ, pPart->BriefLineStart().z);
fTransitZ = max(fTransitZ, pPart->BriefLineEnd().z);
}
return fTransitZ;
}
double CTidHeightGroup::GetBodyNamedHeight()
{
double fBody2LegTransZ = GetBody2LegTransitZ();
double fNamedHeightZeroZ = m_pModel->GetNamedHeightZeroZ();
double fBody2LegHeight = fBody2LegTransZ - fNamedHeightZeroZ;
return fBody2LegHeight;
}
bool CTidHeightGroup::GetConfigBytes(BYTE* cfgword_bytes24)
{
if (cfgword_bytes24 == NULL)
return false;
memcpy(cfgword_bytes24, module.m_dwLegCfgWord.flag.bytes, 24);
return true;
}
//////////////////////////////////////////////////////////////////////////
// CTidTowerInstance
CTidTowerInstance::CTidTowerInstance()
{
m_pModel=NULL;
m_pBelongHeight=NULL;
m_fInstanceHeight=0;
arrLegBitSerial[0]=arrLegBitSerial[1]=arrLegBitSerial[2]=arrLegBitSerial[3]=0;
}
ITidHeightGroup* CTidTowerInstance::SetBelongHeight(ITidHeightGroup* pHeightGroup)
{
m_pBelongHeight=(CTidHeightGroup*)pHeightGroup;
if(m_pBelongHeight)
m_pModel=m_pBelongHeight->BelongModel();
return m_pBelongHeight;
}
short CTidTowerInstance::GetLegSerialIdByQuad(short siQuad)
{
siQuad--;
if(siQuad<0||siQuad>=4)
return 0;
BYTE initPosition=m_pBelongHeight->RetrieveSerialInitBitPos(); //1为起始基数
return arrLegBitSerial[siQuad]-initPosition+1;
}
void CTidTowerInstance::InitAssemblePartAndBolt()
{
if(Nodes.GetNodeNum()==0)
{
double fMaxNodeZ=0;
NODE_ASSEMBLY node;
UINT uCount=m_pModel->m_xNodeSection.NodeCount();
for(UINT i=0;i<uCount;i++)
{
m_pModel->m_xNodeSection.GetNodeByIndexId(i+1,true,node);
if(!IsIncludeObject(m_pBelongHeight->module.m_dwLegCfgWord,arrLegBitSerial,node.cfgword,node.cLegQuad))
continue;
CTidNode* pNode=Nodes.Add(i+1);
pNode->node=node;
pNode->SetBelongModel(m_pModel);
if(fMaxNodeZ<node.xPosition.z)
fMaxNodeZ=node.xPosition.z;
}
uCount=m_pModel->m_xNodeSection.NodeCount(false);
for(UINT i=0;i<uCount;i++)
{
m_pModel->m_xNodeSection.GetNodeByIndexId(i+1,false,node);
UINT uBlkRef=m_pModel->m_xAssembleSection.BlockAssemblyCount();
for(UINT indexId=1;indexId<=uBlkRef;indexId++)
{
BLOCK_ASSEMBLY blkassembly=m_pModel->m_xAssembleSection.GetAssemblyByIndexId(indexId);
if(blkassembly.wIndexId!=node.wBlockIndexId)
continue; //该构件不属于当前部件装配对象
if(!IsIncludeObject(m_pBelongHeight->module.m_dwLegCfgWord,arrLegBitSerial,blkassembly.cfgword,blkassembly.cLegQuad))
continue;
TOWER_BLOCK block=m_pModel->m_xBlockSection.GetBlockAt(blkassembly.wIndexId-1);
TID_CS fromTidCS=ConvertCSFrom(block.lcs);
TID_CS toTidCS=ConvertCSFrom(blkassembly.acs);
//coord_trans(node.xPosition,block.lcs,FALSE,TRUE);
//coord_trans(node.xPosition,blkassembly.acs,TRUE,TRUE);
node.xPosition=block.lcs.TransPToCS(node.xPosition);
node.xPosition=blkassembly.acs.TransPFromCS(node.xPosition);
//
CTidNode* pNode=Nodes.Add(i+1);
pNode->node=node;
pNode->SetBelongModel(m_pModel);
}
}
m_fInstanceHeight=fMaxNodeZ;
}
int iKey=0;
if(partAssembly.GetNodeNum()==0)
{ //需要提取构件装配集合
UINT uCount=m_pModel->m_xAssemblyParts.AssemblyCount();
for(UINT i=0;i<uCount;i++)
{
PART_ASSEMBLY assemble;
m_pModel->m_xAssemblyParts.GetAssemblyByIndexId(i+1,true,assemble);
if(!IsIncludeObject(m_pBelongHeight->module.m_dwLegCfgWord,arrLegBitSerial,assemble.cfgword,assemble.cLegQuad))
continue;
CTidAssemblePart* pAssmPart=partAssembly.Add(++iKey);
pAssmPart->part=assemble;
pAssmPart->SetBelongModel(m_pModel);
PART_INFO partinfo=m_pModel->m_xPartSection.GetPartInfoByIndexId(assemble.dwIndexId);
pAssmPart->solid.CopySolidBuffer(partinfo.solid.BufferPtr(),partinfo.solid.BufferLength());
TID_CS acs=pAssmPart->GetAcs();
pAssmPart->solid.TransToACS(acs);
}
uCount=m_pModel->m_xAssemblyParts.AssemblyCount(false);
for(UINT i=0;i<uCount;i++)
{
PART_ASSEMBLY assemble;
m_pModel->m_xAssemblyParts.GetAssemblyByIndexId(i+1,false,assemble);
UINT uBlkRef=m_pModel->m_xAssembleSection.BlockAssemblyCount();
for(UINT indexId=1;indexId<=uBlkRef;indexId++)
{
BLOCK_ASSEMBLY blkassembly=m_pModel->m_xAssembleSection.GetAssemblyByIndexId(indexId);
if(blkassembly.wIndexId!=assemble.wBlockIndexId)
continue; //该构件不属于当前部件装配对象
if(!IsIncludeObject(m_pBelongHeight->module.m_dwLegCfgWord,arrLegBitSerial,blkassembly.cfgword,blkassembly.cLegQuad))
continue;
CTidAssemblePart* pAssmPart=partAssembly.Add(++iKey);
pAssmPart->part=assemble;
pAssmPart->SetBelongModel(m_pModel);
PART_INFO partinfo=m_pModel->m_xPartSection.GetPartInfoByIndexId(assemble.dwIndexId);
pAssmPart->solid.CopySolidBuffer(partinfo.solid.BufferPtr(),partinfo.solid.BufferLength());
pAssmPart->solid.TransToACS(ConvertCSFrom(assemble.acs));
TOWER_BLOCK block=m_pModel->m_xBlockSection.GetBlockAt(blkassembly.wIndexId-1);
pAssmPart->solid.TransACS(ConvertCSFrom(block.lcs),ConvertCSFrom(blkassembly.acs));
}
}
}
if(boltAssembly.GetNodeNum()==0)
{ //需要提取螺栓装配集合
UINT uCount=m_pModel->m_xAssemblyBolts.AssemblyCount();
for(UINT i=0;i<uCount;i++)
{
BOLT_ASSEMBLY assemble;
assemble=m_pModel->m_xAssemblyBolts.GetAssemblyByIndexId(i+1,true);
if(!IsIncludeObject(m_pBelongHeight->module.m_dwLegCfgWord,arrLegBitSerial,assemble.cfgword,assemble.cLegQuad))
continue;
IBoltSeriesLib* pBoltLibrary=m_pModel->GetBoltLib();
IBoltSeries* pBoltSeries=pBoltLibrary->GetBoltSeriesAt(assemble.cSeriesId-1);
IBoltSizeSpec* pBoltSize=pBoltSeries->GetBoltSizeSpecById(assemble.wIndexId);
if(pBoltSize==NULL)
{
logerr.Log("BoltSizeSpec@%d not found!\n",assemble.wIndexId);
continue;
}
CTidSolidBody* pBoltSolid=(CTidSolidBody*)pBoltSize->GetBoltSolid();
CTidSolidBody* pNutSolid=(CTidSolidBody*)pBoltSize->GetNutSolid();
//
CTidAssembleBolt* pAssmBolt=boltAssembly.Add(++iKey);
pAssmBolt->bolt=assemble;
pAssmBolt->SetBelongModel(m_pModel);
pAssmBolt->solid.bolt.CopySolidBuffer(pBoltSolid->SolidBufferPtr(),pBoltSolid->SolidBufferLength());
pAssmBolt->solid.nut.CopySolidBuffer(pNutSolid->SolidBufferPtr(),pNutSolid->SolidBufferLength());
TID_CS acs=pAssmBolt->GetAcs();
pAssmBolt->solid.bolt.TransToACS(acs);
acs.origin.x+=acs.axisZ.x*assemble.wL0;
acs.origin.y+=acs.axisZ.y*assemble.wL0;
acs.origin.z+=acs.axisZ.z*assemble.wL0;
pAssmBolt->solid.nut.TransToACS(acs);
}
uCount=m_pModel->m_xAssemblyBolts.AssemblyCount(false);
for(UINT i=0;i<uCount;i++)
{
BOLT_ASSEMBLY assemble=m_pModel->m_xAssemblyBolts.GetAssemblyByIndexId(i+1,false);
UINT uBlkRef=m_pModel->m_xAssembleSection.BlockAssemblyCount();
for(UINT indexId=1;indexId<=uBlkRef;indexId++)
{
BLOCK_ASSEMBLY blkassembly=m_pModel->m_xAssembleSection.GetAssemblyByIndexId(indexId);
if(blkassembly.wIndexId!=assemble.wBlockIndexId)
continue; //该构件不属于当前部件装配对象
if(!IsIncludeObject(m_pBelongHeight->module.m_dwLegCfgWord,arrLegBitSerial,blkassembly.cfgword,blkassembly.cLegQuad))
continue;
IBoltSeriesLib* pBoltLibrary=m_pModel->GetBoltLib();
IBoltSeries* pBoltSeries=pBoltLibrary->GetBoltSeriesAt(assemble.cSeriesId-1);
IBoltSizeSpec* pBoltSize=pBoltSeries->GetBoltSizeSpecById(assemble.wIndexId);
if(pBoltSize==NULL)
{
logerr.Log("BoltSizeSpec@%d not found!\n",assemble.wIndexId);
continue;
}
CTidSolidBody* pBoltSolid=(CTidSolidBody*)pBoltSize->GetBoltSolid();
CTidSolidBody* pNutSolid=(CTidSolidBody*)pBoltSize->GetNutSolid();
//
CTidAssembleBolt* pAssmBolt=boltAssembly.Add(++iKey);
pAssmBolt->bolt=assemble;
pAssmBolt->SetBelongModel(m_pModel);
pAssmBolt->solid.bolt.CopySolidBuffer(pBoltSolid->SolidBufferPtr(),pBoltSolid->SolidBufferLength());
pAssmBolt->solid.nut.CopySolidBuffer(pNutSolid->SolidBufferPtr(),pNutSolid->SolidBufferLength());
TID_CS acs=pAssmBolt->GetAcs();
pAssmBolt->solid.bolt.TransToACS(acs);
acs.origin.x+=acs.axisZ.x*assemble.wL0;
acs.origin.y+=acs.axisZ.y*assemble.wL0;
acs.origin.z+=acs.axisZ.z*assemble.wL0;
pAssmBolt->solid.nut.TransToACS(acs);
TOWER_BLOCK block=m_pModel->m_xBlockSection.GetBlockAt(blkassembly.wIndexId-1);
pAssmBolt->solid.bolt.TransACS(ConvertCSFrom(block.lcs),ConvertCSFrom(blkassembly.acs));
pAssmBolt->solid.nut.TransACS(ConvertCSFrom(block.lcs),ConvertCSFrom(blkassembly.acs));
}
}
}
if(hashAnchorBolts.GetNodeNum()==0)
{
WORD wiAnchorCountPerBase=m_pModel->GetAnchorCount();
for(WORD i=0;i<4;i++)
{
GEPOINT xBaseLocation;
BYTE ciLegSerial=(BYTE)GetLegSerialIdByQuad(i+1);
if(!m_pModel->GetSubLegBaseLocation(this->m_pBelongHeight->GetSerialId(),ciLegSerial,xBaseLocation))
continue;
if(i==1||i==3) //相对1象限Y轴对称
xBaseLocation.x*=-1.0;
if(i==2||i==3) //相对1象限X轴对称
xBaseLocation.y*=-1.0;
for(WORD j=0;j<wiAnchorCountPerBase;j++)
{
short siPosX=0,siPosY=0;
m_pModel->GetAnchorAt(j,&siPosX,&siPosY);
//
CTidAssembleAnchorBolt* pAnchorBolt=hashAnchorBolts.Add(++iKey);
pAnchorBolt->SetBelongModel(m_pModel);
pAnchorBolt->xLocation.Set(xBaseLocation.x+siPosX,xBaseLocation.y+siPosY,xBaseLocation.z);
pAnchorBolt->m_ciLegQuad=i+1;
m_pModel->GetAnchorBoltSolid(&pAnchorBolt->solid.bolt,&pAnchorBolt->solid.nut);
TID_CS acs=pAnchorBolt->GetAcs();
pAnchorBolt->solid.bolt.TransToACS(acs);
acs.origin.x+=acs.axisZ.x*m_pModel->GetBasePlateThick();
acs.origin.y+=acs.axisZ.y*m_pModel->GetBasePlateThick();
acs.origin.z+=acs.axisZ.z*m_pModel->GetBasePlateThick();
pAnchorBolt->solid.nut.TransToACS(acs);
}
}
}
}
bool CTidTowerInstance::ExportModFile(const char* sFileName)
{
#ifdef _DISABLE_MOD_CORE_
return false;
#else
if(BelongHeightGroup()==NULL||BelongTidModel()==NULL)
return false;
IModModel* pModModel=CModModelFactory::CreateModModel();
if(pModModel==NULL)
return false;
CLogErrorLife logErrLife;
pModModel->SetTowerHeight(GetInstanceHeight());
GECS ucs=TransToUcs(pModModel->BuildUcsByModCS());
//初始化MOD模型的节点与杆件
CXhChar16 sLayer;
for(ITidNode* pNode=EnumNodeFirst();pNode;pNode=EnumNodeNext())
{
pNode->GetLayer(sLayer);
TID_COORD3D pos=pNode->GetPos();
f3dPoint node_org=ucs.TransPFromCS(f3dPoint(pos.x,pos.y,pos.z));
//
IModNode* pModNode=pModModel->AppendNode(pNode->GetId());
pModNode->SetBelongModel(pModModel);
pModNode->SetOrg(MOD_POINT(node_org));
if(sLayer[0]=='L'||sLayer[0]=='l')
pModNode->SetLayer('L'); //腿部Leg
else
pModNode->SetLayer('B'); //塔身Body
}
for(ITidAssemblePart* pAssmPart=EnumAssemblePartFirst();pAssmPart;pAssmPart=EnumAssemblePartNext())
{
if(!pAssmPart->IsHasBriefRodLine())
continue;
ITidPart* pTidPart=pAssmPart->GetPart();
if(pTidPart==NULL)
continue;
UINT iNodeIdS=pAssmPart->GetStartNodeId();
UINT iNodeIdE=pAssmPart->GetEndNodeId();
IModNode* pModNodeS=pModModel->FindNode(iNodeIdS);
IModNode* pModNodeE=pModModel->FindNode(iNodeIdE);
if(pModNodeS==NULL || pModNodeE==NULL)
{
//logerr.Log("S:%d-E:%d节点找不到",iNodeIdS,iNodeIdE);
continue; //短角钢
}
pAssmPart->GetLayer(sLayer);
TID_CS assm_cs=pAssmPart->GetAcs();
//
IModRod* pModRod=pModModel->AppendRod(pAssmPart->GetId());
pModRod->SetBelongModel(pModModel);
pModRod->SetMaterial(pTidPart->GetBriefMark());
pModRod->SetWidth(pTidPart->GetWidth());
pModRod->SetThick(pTidPart->GetThick());
if(pTidPart->GetPartType()==ITidPart::TYPE_ANGLE)
{
f3dPoint vWingX(assm_cs.axisX),vWingY(assm_cs.axisY);
pModRod->SetRodType(1);
pModRod->SetWingXVec(MOD_POINT(ucs.TransVToCS(vWingX)));
pModRod->SetWingYVec(MOD_POINT(ucs.TransVToCS(vWingY)));
}
else
pModRod->SetRodType(2);
if(sLayer[0]=='L'||sLayer[0]=='l')
pModRod->SetLayer('L'); //腿部Leg
else
pModRod->SetLayer('B'); //塔身Body
if(pModRod->IsLegRod())
{ //根据腿部杆件,添加过渡节点
if(pModNodeS && !pModNodeS->IsLegNode())
{
IModNode* pNewModNode=pModModel->AppendNode(0);
pNewModNode->SetBelongModel(pModModel);
pNewModNode->SetOrg(pModNodeS->NodePos());
pNewModNode->SetLayer('S');
pModNodeS=pNewModNode;
}
if(pModNodeE && !pModNodeE->IsLegNode())
{
IModNode* pNewModNode=pModModel->AppendNode(0);
pNewModNode->SetBelongModel(pModModel);
pNewModNode->SetOrg(pModNodeE->NodePos());
pNewModNode->SetLayer('S');
pModNodeE=pNewModNode;
}
}
pModRod->SetNodeS(pModNodeS);
pModRod->SetNodeE(pModNodeE);
}
//初始化单基塔例的MOD结构(计算该塔例的实际呼高值)
double fNameHeightZeroZ = BelongTidModel()->GetNamedHeightZeroZ();
double fActualHeight = m_fInstanceHeight-fNameHeightZeroZ;
pModModel->InitSingleModData(fActualHeight);
//添加挂点
int nHangPt=BelongTidModel()->HangPointCount();
for(int i=0;i<nHangPt;i++)
{
ITidHangPoint* pHangPt=BelongTidModel()->GetHangPointAt(i);
if(pHangPt==NULL)
continue;
CXhChar50 sDes;
pHangPt->GetWireDescription(sDes);
TID_COORD3D pt=pHangPt->GetPos();
//
MOD_HANG_NODE* pHangNode=pModModel->AppendHangNode();
pHangNode->m_xHangPos=ucs.TransPFromCS(f3dPoint(pt));
strcpy(pHangNode->m_sHangName,sDes);
pHangNode->m_ciWireType=pHangPt->GetWireType();
}
//生成Mod文件
FILE *fp=fopen(sFileName,"wt,ccs=UTF-8");
if(fp==NULL)
{
logerr.Log("%s文件打开失败!",sFileName);
return false;
}
pModModel->WriteModFileByUtf8(fp);
return true;
#endif
}
//////////////////////////////////////////////////////////////////////////
// CBoltSeriesLib
int CBoltSeriesLib::GetCount()
{
return sectdata.BoltSeriesCount();
}
IBoltSeries* CBoltSeriesLib::GetBoltSeriesAt(int i)
{
if(i<0||i>=sectdata.BoltSeriesCount())
return NULL;
CTidBoltSeries* pBoltSeries=hashBoltSeries.GetValue(i+1);
if(pBoltSeries==NULL)
{
pBoltSeries=hashBoltSeries.Add(i+1);
pBoltSeries->sectdata=sectdata.GetBoltSeriesAt(i);
}
return pBoltSeries;
}
IBoltSizeSpec* CBoltSeriesLib::GetBoltSizeSpec(int seriesId,int sizeSpecId)
{
IBoltSeries* pBoltSeries=GetBoltSeriesAt(seriesId-1);
if(pBoltSeries!=NULL)
return pBoltSeries->GetBoltSizeSpecById(sizeSpecId);
return NULL;
}
//////////////////////////////////////////////////////////////////////////
// CTidPartsLib
int CTidPartsLib::GetCount()
{
return sectdata.GetPartCount();
}
ITidPart* CTidPartsLib::GetTidPartBySerialId(int serialid)
{
if(serialid<=0||serialid>(int)sectdata.GetPartCount())
return NULL;
CTidPart* pTidPart=hashTidParts.GetValue(serialid);
if(pTidPart==NULL)
{
pTidPart=hashTidParts.Add(serialid);
pTidPart->partinfo=sectdata.GetPartInfoByIndexId(serialid);
}
return pTidPart;
}
//////////////////////////////////////////////////////////////////////////
// CTidBoltSeries
short CTidBoltSeries::GetName(char* name)
{
CXhChar24 seriesname=sectdata.GetSeriesName();
if(name)
strcpy(name,seriesname);
return seriesname.GetLength();
}
/*
bool CTidBoltSeries::IsFootNail() //脚钉
{
return false;
}
bool CTidBoltSeries::IsBurglarproof() //是否为防盗螺栓
{
return false;
}
*/
IBoltSizeSpec* CTidBoltSeries::EnumFirst()
{
m_iterIndex=1;
return GetBoltSizeSpecById(m_iterIndex);
}
IBoltSizeSpec* CTidBoltSeries::EnumNext()
{
m_iterIndex++;
return GetBoltSizeSpecById(m_iterIndex);
}
IBoltSizeSpec* CTidBoltSeries::GetBoltSizeSpecById(int id)
{
if(id<=0||id>GetCount())
return NULL;
CBoltSizeSection boltsect;
if(!sectdata.GetBoltSizeAt(id-1,boltsect))
return NULL;
CTidBoltSizeSpec* pSizeSpec=hashBoltSizes.Add(id);
pSizeSpec->sectdata=boltsect;
pSizeSpec->solid.bolt.AttachBuffer(boltsect.solid.bolt.BufferPtr(),boltsect.solid.bolt.BufferLength());
pSizeSpec->solid.nut.AttachBuffer(boltsect.solid.nut.BufferPtr(),boltsect.solid.nut.BufferLength());
pSizeSpec->SetSeriesId(GetSeriesId());
return pSizeSpec;
}
//////////////////////////////////////////////////////////////////////////
// CTidPart
short CTidPart::GetSegStr(char* segstr)
{
SEGI segi=partinfo.dwSeg;
strcpy(segstr,segi.ToString());
return strlen(segstr);
}
short CTidPart::GetSpec(char* sizeSpec)
{
if(strlen(partinfo.spec)>0)
strcpy(sizeSpec,partinfo.spec);
else
sprintf(sizeSpec,"%g*%g",partinfo.fWidth,partinfo.fThick);
return strlen(sizeSpec);
}
short CTidPart::GetLabel(char* label)
{
strcpy(label,partinfo.sPartNo);
return strlen(label);
}
ITidSolidBody* CTidPart::GetSolidPart()
{
solid.AttachBuffer(partinfo.solid.BufferPtr(),partinfo.solid.BufferLength());
return &solid;
}
UINT CTidPart::GetProcessBuffBytes(char* processbytes,UINT maxBufLength/*=0*/)
{
if(processbytes==NULL)
return partinfo.dwProcessBuffSize;
int copybuffsize=maxBufLength<=0?partinfo.dwProcessBuffSize:min(maxBufLength,partinfo.dwProcessBuffSize);
memcpy(processbytes,partinfo.processBuffBytes,copybuffsize);
return 0;
}
//////////////////////////////////////////////////////////////////////////
// CTidBoltSizeSpec
CTidBoltSizeSpec::CTidBoltSizeSpec(DWORD key/*=0*/)
{
m_id=key;
m_uiSeriesId=0;
}
ITidSolidBody* CTidBoltSizeSpec::GetBoltSolid()//螺栓实体
{
return &solid.bolt;
}
ITidSolidBody* CTidBoltSizeSpec::GetNutSolid()//螺栓实体
{
return &solid.nut;
}
//////////////////////////////////////////////////////////////////////////
//CTidAssembleAnchorBolt
IAnchorBoltSpec* CTidAssembleAnchorBolt::GetAnchorBolt()
{
xAnchorBolt.anchor_bolt.d = m_pModel->m_xBoltLib.sectdata.anchorInfo.d; //地脚螺栓名义直径
xAnchorBolt.anchor_bolt.wiLe = m_pModel->m_xBoltLib.sectdata.anchorInfo.wiLe; //地脚螺栓出露长(mm)
xAnchorBolt.anchor_bolt.wiLa = m_pModel->m_xBoltLib.sectdata.anchorInfo.wiLa; //地脚螺栓无扣长(mm) <底座板厚度
xAnchorBolt.anchor_bolt.wiWidth = m_pModel->m_xBoltLib.sectdata.anchorInfo.wiWidth; //地脚螺栓垫板宽度
xAnchorBolt.anchor_bolt.wiThick = m_pModel->m_xBoltLib.sectdata.anchorInfo.wiThick; //地脚螺栓垫板厚度
xAnchorBolt.anchor_bolt.wiHoleD = m_pModel->m_xBoltLib.sectdata.anchorInfo.wiHoleD; //地脚螺栓板孔径
xAnchorBolt.anchor_bolt.wiBasePlateHoleD = m_pModel->m_xBoltLib.sectdata.anchorInfo.wiBasePlateHoleD;
memcpy(xAnchorBolt.anchor_bolt.szSizeSymbol, m_pModel->m_xBoltLib.sectdata.anchorInfo.szSizeSymbol, 64);
xAnchorBolt.m_nBaseThick = m_pModel->m_xFoundationSection.ciBasePlateThick;
return &xAnchorBolt;
}
TID_CS CTidAssembleAnchorBolt::GetAcs()
{
TID_CS acs;
acs.origin = TID_COORD3D(xLocation);
acs.axisZ = TID_COORD3D(0, 0, -1);
acs.axisX = TID_COORD3D(1, 0, 0);//GEPOINT(acs.axisZ).Perpendicular(true);
acs.axisY = GEPOINT(acs.axisZ) ^ GEPOINT(acs.axisX);
return acs;
}
ITidSolidBody* CTidAssembleAnchorBolt::GetBoltSolid()
{
return &solid.bolt;
}
ITidSolidBody* CTidAssembleAnchorBolt::GetNutSolid()
{
return &solid.nut;
}
//////////////////////////////////////////////////////////////////////////
// CTidAssembleBolt
CTidAssembleBolt::CTidAssembleBolt()
{
m_id = 0;
m_pModel = NULL;
}
CTidAssembleBolt::~CTidAssembleBolt()
{
}
IBoltSizeSpec *CTidAssembleBolt::GetTidBolt()
{
CBoltSeries series=m_pModel->m_xBoltLib.sectdata.GetBoltSeriesAt(bolt.cSeriesId-1);
CBoltSizeSection boltsect;
if(!series.GetBoltSizeAt(bolt.wIndexId-1,boltsect))
return NULL;
sizespec.sectdata=boltsect;
sizespec.SetSeriesId(bolt.cSeriesId); //设定归属螺栓规格系列的标识
sizespec.solid.bolt.AttachBuffer(boltsect.solid.bolt.BufferPtr(),boltsect.solid.bolt.BufferLength());
sizespec.solid.nut.AttachBuffer(boltsect.solid.nut.BufferPtr(),boltsect.solid.nut.BufferLength());
return &sizespec;
}
TID_CS CTidAssembleBolt::GetAcs()
{
TID_CS acs;
acs.origin=TID_COORD3D(bolt.origin);
acs.axisZ =TID_COORD3D(bolt.work_norm);
acs.axisX =GEPOINT(acs.axisZ).Perpendicular(true);
acs.axisY = GEPOINT(acs.axisZ)^GEPOINT(acs.axisX);
return acs;
}
ITidSolidBody* CTidAssembleBolt::GetBoltSolid()
{
return &solid.bolt;
}
ITidSolidBody* CTidAssembleBolt::GetNutSolid()
{
return &solid.nut;
}
//段号前缀字符(可含2个字符),段号数字部分;[杆塔空间装配螺栓属性]
//如果统材类型中首位为1时,此4个字节表示该螺栓的段号统计范围字符串的存储地址
int CTidAssembleBolt::SegmentBelongStr(char* seg_str) //[杆塔空间装配螺栓属性]
{
if(bolt.cStatFlag&0x80) //同时归属多个段号
{
if(seg_str)
strcpy(seg_str,bolt.statSegStr);
return bolt.statSegStr.GetLength();
}
else
{
CXhChar16 segstr=SEGI(bolt.dwSeg).ToString();
if(seg_str)
strcpy(seg_str,segstr);
return segstr.GetLength();
}
}
bool CTidAssembleBolt::GetConfigBytes(BYTE* cfgword_bytes24)
{
if (cfgword_bytes24 == NULL)
return false;
memcpy(cfgword_bytes24, bolt.cfgword.flag.bytes, 24);
return true;
}
//////////////////////////////////////////////////////////////////////////
// CTidAssemblePart
short CTidAssemblePart::GetType()
{
ITidPart* pTidPart=GetPart();
if(pTidPart)
return pTidPart->GetPartType();
else
return 0; //构件分类,1:角钢2:螺栓3:钢板4:钢管5:扁铁6:槽钢
}
ITidPart *CTidAssemblePart::GetPart()
{
PART_INFO partinfo=m_pModel->m_xPartSection.GetPartInfoByIndexId(part.dwIndexId);
CTidPart* pTidPart=hashTidParts.Add(part.dwIndexId);
pTidPart->partinfo=partinfo;
return pTidPart;
}
TID_CS CTidAssemblePart::GetAcs()
{
TID_CS acs;
acs.origin=TID_COORD3D(part.acs.origin);
acs.axisX=TID_COORD3D(part.acs.axis_x);
acs.axisY=TID_COORD3D(part.acs.axis_y);
acs.axisZ=TID_COORD3D(part.acs.axis_z);
return acs;
}
ITidSolidBody* CTidAssemblePart::GetSolidPart()
{
return &solid;
}
short CTidAssemblePart::GetLayer(char* sizeLayer)
{
strcpy(sizeLayer,part.szLayerSymbol);
return strlen(sizeLayer);
}
bool CTidAssemblePart::GetConfigBytes(BYTE* cfgword_bytes24)
{
if (cfgword_bytes24 == NULL)
return false;
memcpy(cfgword_bytes24, part.cfgword.flag.bytes, 24);
return true;
}
//////////////////////////////////////////////////////////////////////////
// CTidRawSolidEdge
DWORD CTidRawSolidEdge::LineStartId()
{
if(IsReverse())
return edge.LineEndId;
else
return edge.LineStartId;
}
DWORD CTidRawSolidEdge::LineEndId()
{
if(IsReverse())
return edge.LineStartId;
else
return edge.LineEndId;
}
TID_COORD3D CTidRawSolidEdge::WorkNorm()
{
TID_COORD3D worknorm(edge.WorkNorm);
if(!worknorm.IsZero()&&IsReverse())
worknorm.Set(worknorm.x,worknorm.y,worknorm.z);
return worknorm;
}
//////////////////////////////////////////////////////////////////////////
// CTidFaceLoop
CTidRawSolidEdge* CreateTidRawSolidEdge(int idClsType,DWORD key,void* pContext) //必设回调函数
{
return new CTidRawSolidEdge(key,(CSolidBody*)pContext);
}
CTidFaceLoop::CTidFaceLoop(DWORD id/*=0*/,CSolidBody* pSolidBody/*=NULL*/)
{
m_id=id;
hashEdges.m_pContext=m_pSolidBody=pSolidBody;
hashEdges.CreateNewAtom=CreateTidRawSolidEdge;
}
bool CTidFaceLoop::EdgeLineAt(int i,TidArcline* pArcline)
{
CRawSolidEdge edge;
if(!loop.GetLoopEdgeLineAt(m_pSolidBody,i,edge))
return false;
pArcline->FromByteArr(edge.BufferPtr(),edge.Size());
return true;
}
ITidRawSolidEdge* CTidFaceLoop::EdgeLineAt(int index)
{
CTidRawSolidEdge* pEdge=hashEdges.Add(index+1);
DWORD edgeid=loop.LoopEdgeLineIdAt(index);
pEdge->SetReverse((edgeid&0x80000000)>0);
edgeid&=0x7fffffff;
m_pSolidBody->GetKeyEdgeLineAt(edgeid-1,pEdge->edge);
return pEdge;
}
//////////////////////////////////////////////////////////////////////////
// CTidRawFace
CTidFaceLoop* CreateTidFaceLoop(int idClsType,DWORD key,void* pContext) //必设回调函数
{
return new CTidFaceLoop(key,(CSolidBody*)pContext);
}
CTidRawFace::CTidRawFace(DWORD id/*=0*/,CSolidBody* pSolidBody/*=NULL*/)
{
m_id=id;
outer.hashEdges.m_pContext=outer.m_pSolidBody=m_pSolidBody=pSolidBody;
hashInnerLoops.m_pContext=pSolidBody;
hashInnerLoops.CreateNewAtom=CreateTidFaceLoop;
}
CTidRawFace::~CTidRawFace()
{
outer.Empty();
hashInnerLoops.Empty();
}
COLORREF CTidRawFace::MatColor() // 可用于记录此面的特征信息(如材质等)
{
return face.MatColor();
}
DWORD CTidRawFace::FaceId() //用于标识多边形面链中的某一特定面
{
return face.FaceId();
}
WORD CTidRawFace::InnerLoopNum()
{
return face.InnerLoopNum();;
}
IFaceLoop* CTidRawFace::InnerLoopAt(int i)
{
CTidFaceLoop* pLoop=hashInnerLoops.Add(i+1);
pLoop->loop=face.GetInnerLoopAt(i);
return pLoop;
}
IFaceLoop* CTidRawFace::OutterLoop()
{
outer.loop= face.GetOutterLoop();
return &outer;
}
TID_COORD3D CTidRawFace::WorkNorm()
{
return TID_COORD3D(face.WorkNorm);
}
//////////////////////////////////////////////////////////////////////////
// CTidBasicFace
//TID_COORD3D CTidBasicFace::Normal()
//{
// return basicface.
//}
CTidBasicFace::CTidBasicFace(DWORD id/*=0*/,CSolidBody* pSolidBody/*=NULL*/)
{
m_id=id;
m_pSolidBody=pSolidBody;
}
COLORREF CTidBasicFace::Color()
{
if(basicface.BufferSize==0)
return 0;
else
return basicface.Color;
}
WORD CTidBasicFace::FacetClusterNumber()
{
if(basicface.BufferSize==0)
return 0;
else
return basicface.FacetClusterNumber;
}
IFacetCluster* CTidBasicFace::FacetClusterAt(int index)
{
CFacetCluster facet;
if(!basicface.GetFacetClusterAt(index,facet))
return NULL;
CTidFacetCluster* pFacet=listFacets.Add(index+1);
pFacet->cluster=facet;
return pFacet;
}
//////////////////////////////////////////////////////////////////////////
// CTidRawSolidEdge
CTidRawSolidEdge::CTidRawSolidEdge(DWORD id/*=0*/,CSolidBody* pSolid/*=NULL*/)
{
m_pSolid=pSolid;
m_id=id;
reverseStartEnd=false;
}
BYTE CTidRawSolidEdge::EdgeType()
{
return STRAIGHT;
}
//////////////////////////////////////////////////////////////////////////
// CTidSolidBody
#include "SolidBodyBuffer.h"
/*
CTidRawSolidEdge* CreateTidRawSolidEdge(int idClsType,DWORD key,void* pContext) //必设回调函数
{
return new CTidRawSolidEdge(key,(CSolidBody*)pContext);
}
*/
CTidRawFace* CreateTidRawFace(int idClsType,DWORD key,void* pContext) //必设回调函数
{
return new CTidRawFace(key,(CSolidBody*)pContext);
}
CTidBasicFace* CreateTidBasicFace(int idClsType,DWORD key,void* pContext) //必设回调函数
{
return new CTidBasicFace(key,(CSolidBody*)pContext);
}
CTidSolidBody::CTidSolidBody(char* buf/*=NULL*/,DWORD size/*=0*/)
{
hashEdges.m_pContext=&solid;
hashEdges.CreateNewAtom=CreateTidRawSolidEdge;
hashRawFaces.m_pContext=&solid;
hashRawFaces.CreateNewAtom=CreateTidRawFace;
hashBasicFaces.m_pContext=&solid;
hashBasicFaces.CreateNewAtom=CreateTidBasicFace;
solid.AttachBuffer(buf,size);
}
void CTidSolidBody::AttachBuffer(char* buf/*=NULL*/,DWORD size/*=0*/)
{
solid.AttachBuffer(buf,size);
}
void CTidSolidBody::CopySolidBuffer(char* buf/*=NULL*/,DWORD size/*=0*/)
{
solid.CopyBuffer(buf,size);
}
void CTidSolidBody::ReleaseTemporaryBuffer()
{
hashEdges.Empty();
hashRawFaces.Empty();
hashBasicFaces.Empty();
}
#include "./Splitter/glDrawTool.h"
bool Standize(double* vector3d)
{
double mod_len=vector3d[0]*vector3d[0]+vector3d[1]*vector3d[1]+vector3d[2]*vector3d[2];
mod_len=sqrt(max(0,mod_len));
if(mod_len<EPS)
return false;
vector3d[0]/=mod_len;
vector3d[1]/=mod_len;
vector3d[2]/=mod_len;
return true;
}
int FloatToInt(double f)
{
int fi=(int)f;
return f-fi>0.5?fi+1:fi;
}
int CalArcResolution(double radius,double sector_angle)
{
double user2scr_scale=1.0;
int sampling=5; //圆弧绘制时的抽样长度(象素数)
UINT uMinSlices=36; //整圆弧显示的最低平滑度片数
double length=sector_angle*radius;
int n = FloatToInt((length/user2scr_scale)/sampling);
int min_n=FloatToInt(uMinSlices*sector_angle/Pi)/2;
int max_n=FloatToInt(72*sector_angle/Pi);
if(max_n==0)
max_n=1;
if(min_n==0)
min_n=1;
n=max(n,min_n);
n=min(n,max_n);
return n;
}
void GetArcSimuPolyVertex(f3dArcLine* pArcLine, GEPOINT vertex_arr[], int slices)
{
int i,sign=1;
if(pArcLine->ID&0x80000000) //负边
sign=-1;
double slice_angle = pArcLine->SectorAngle()/slices;
if(pArcLine->WorkNorm()==pArcLine->ColumnNorm()) //圆弧
{
if(sign<0)
slice_angle*=-1;
double sina = sin(slice_angle); //扇片角正弦
double cosa = cos(slice_angle); //扇片角余弦
vertex_arr[0].Set(pArcLine->Radius());
for(i=1;i<=slices;i++)
{
vertex_arr[i].x=vertex_arr[i-1].x*cosa-vertex_arr[i-1].y*sina;
vertex_arr[i].y=vertex_arr[i-1].y*cosa+vertex_arr[i-1].x*sina;
}
GEPOINT origin=pArcLine->Center();
GEPOINT axis_x=pArcLine->Start()-origin;
Standize(axis_x);
GEPOINT axis_y=pArcLine->WorkNorm()^axis_x;
for(i=0;i<=slices;i++)
{
vertex_arr[i].Set( origin.x+vertex_arr[i].x*axis_x.x+vertex_arr[i].y*axis_y.x,
origin.y+vertex_arr[i].x*axis_x.y+vertex_arr[i].y*axis_y.y,
origin.z+vertex_arr[i].x*axis_x.z+vertex_arr[i].y*axis_y.z);
}
}
else //椭圆弧
{
if(sign<0)
{
for(i=slices;i>=0;i--)
vertex_arr[i] = pArcLine->PositionInAngle(i*slice_angle);
}
else
{
for(i=0;i<=slices;i++)
vertex_arr[i] = pArcLine->PositionInAngle(i*slice_angle);
}
}
}
static f3dPoint GetPolyFaceWorkNorm(CSolidBody* pBody,CRawSolidFace& rawface)
{
CFaceLoop loop=rawface.GetOutterLoop();
f3dPoint vec1,vec2,norm;//临时作为中间三维矢量
long n = loop.LoopEdgeLineNum();
if(n<3)
return norm;
//--------------VVVVVVVVV---2.建立多边形面用户坐标系ucs---------------------
if(rawface.WorkNorm.IsZero())
{ //非指定法线情况
f3dArcLine line1,line2;
for(long start=0;start<n;start++)
{
loop.GetLoopEdgeLineAt(pBody,start,line1);
if(line1.ID&0x80000000)
Sub_Pnt( vec1, line1.Start(), line1.End());
else
Sub_Pnt( vec1, line1.End(), line1.Start());
Standize(vec1);
long i,j;
for(i=start+1;i<n;i++)
{
loop.GetLoopEdgeLineAt(pBody,i,line2);
if(line2.ID&0x80000000) //负边
Sub_Pnt( vec2, line2.Start(), line2.End());
else
Sub_Pnt( vec2, line2.End(), line2.Start());
Standize(vec2);
norm = vec1^vec2;
double dd=norm.mod();
if(dd>EPS2)
{
norm /= dd; //单位化
break;
}
}
if( i==n)
return norm; //多边形面定义有误(所有边界线重合)返回零向量
//通过建立临时坐标系,判断法线正负方向
GECS cs;
cs.origin=line1.Start();
cs.axis_x=vec1;
cs.axis_z=norm;
cs.axis_y=cs.axis_z^cs.axis_x;
for(j=0;j<n;j++)
{
if(j==0||j==i)
continue;
loop.GetLoopEdgeLineAt(pBody,start+j,line2);
f3dPoint vertice=line2.End();
vertice=cs.TransPToCS(vertice);
if(vertice.y<-EPS) //遍历点在直线上或附近时,应容许计算误差
break;
}
if(j==n) //全部顶点都在当前边的左侧,即表示计算的法线为正法线,否则应继续寻找
break;
}
}
else
norm=rawface.WorkNorm;
return norm;
}
void WriteToSolidBuffer(CSolidBodyBuffer& solidbuf,int indexBasicFace,CXhSimpleList<CTidGLFace>& listFacets,COLORREF color,const double* poly_norm)
{
//写入一组基本面片数据(对应一个多边形面拆分成的若干基本面片簇
solidbuf.SeekPosition(solidbuf.BasicFaceIndexStartAddr+indexBasicFace*4);
DWORD basicface_lenpos=solidbuf.GetLength();
solidbuf.WriteDword(basicface_lenpos); //将数据区位置写入索引区
solidbuf.SeekToEnd();
solidbuf.WriteWord((WORD)0); //CTidBasicFace的数据记录长度
solidbuf.Write(&color,4);
WORD facets_n=0;
LIST_NODE<CTidGLFace>* pTailNode=listFacets.EnumTail();
if(pTailNode!=NULL)
facets_n=(WORD)listFacets.EnumTail()->serial;
BUFFERPOP stack(&solidbuf,facets_n);
solidbuf.WriteWord(facets_n);
for(CTidGLFace* pGLFace=listFacets.EnumObjectFirst();pGLFace;pGLFace=listFacets.EnumObjectNext())
{
WORD cluster_buf_n=1+24+2+pGLFace->header.uVertexNum*24;
solidbuf.WriteWord(cluster_buf_n);
solidbuf.WriteByte(pGLFace->header.mode);
if(pGLFace->header.clr_norm&0x02)
{ //指定面片簇法线值
solidbuf.WriteDouble(pGLFace->nx);
solidbuf.WriteDouble(pGLFace->ny);
solidbuf.WriteDouble(pGLFace->nz);
}
else //面片簇法线即为原始定义面的法线
solidbuf.WritePoint(GEPOINT(poly_norm));
//写入连续三角面片数量
if(pGLFace->header.mode==GL_TRIANGLES)
solidbuf.WriteWord((WORD)(pGLFace->header.uVertexNum/3));
else
solidbuf.WriteWord((WORD)(pGLFace->header.uVertexNum-2));
solidbuf.Write(pGLFace->m_pVertexCoordArr,pGLFace->header.uVertexNum*24);
stack.Increment();
}
//solidbuf.WriteWord((WORD)stack.Count());
stack.VerifyAndRestore(true,2);
WORD wBasicfaceBufLen=(WORD)(solidbuf.GetCursorPosition()-basicface_lenpos-2);
solidbuf.SeekPosition(basicface_lenpos);
solidbuf.WriteWord(wBasicfaceBufLen);
solidbuf.SeekToEnd();
}
bool CTidSolidBody::SplitToBasicFacets()
{
CRawSolidFace rawface;
f3dPoint vertice;
double alpha = 0.6; //考虑到显示效果的经验系数
int i,j,n=0,face_n=solid.PolyFaceNum();
CXhSimpleList<CTidGLFace> listFacets;
CXhSimpleList<GEPOINT> listVertices;
GEPOINT *pp;
//迁移原实体定义内存同时,腾出基于三角面片的基本实体显示面数据区空间
CSolidBodyBuffer solidbuf;
solidbuf.Write(solid.BufferPtr(),33);//solid.BufferLength());
solidbuf.BasicFaceNumber=face_n; //写入基本面片数=原始多边形面数
DWORD dwIndexBufSize=(solid.KeyEdgeLineNum()+solid.PolyFaceNum())*4;
solidbuf.WriteAt(45,solid.BufferPtr()+45,dwIndexBufSize);
solidbuf.BasicFaceIndexStartAddr=45+dwIndexBufSize;
solidbuf.SeekToEnd(); //BasicFaceIndexStartAddr=赋值会变当前存储指针位置
solidbuf.Write(NULL,face_n*4); //@45+dwIndexBufSize 实体基本面片索引区暂写入相应的空字节占位
DWORD dwDataBufSize=solid.BufferLength()-solidbuf.VertexDataStartAddr;
if(solid.BasicGLFaceNum()>0) //只复制实体原始定义数据区域,忽略原有的基本面片数据区
dwDataBufSize=solid.BasicFaceDataStartAddr()-solidbuf.VertexDataStartAddr;
long iNewVertexDataStartAddr=solidbuf.GetCursorPosition(); //=VertexDataStartAddr+4*face_n
long iOldVertexDataStartAddr=solidbuf.VertexDataStartAddr;
solidbuf.VertexDataStartAddr=iNewVertexDataStartAddr; //=VertexDataStartAddr+4*face_n
solidbuf.EdgeDataStartAddr=solidbuf.EdgeDataStartAddr+4*face_n;
solidbuf.RawFaceDataStartAddr=solidbuf.RawFaceDataStartAddr+4*face_n;
solidbuf.SeekToEnd();
solidbuf.Write(solid.BufferPtr()+iOldVertexDataStartAddr,dwDataBufSize); //写入原实体定义的数据区内存
//计算因增加基本面片索引记录数带来的后续地址位移值
int addr_offset=(face_n-solid.BasicGLFaceNum())*4;
if(addr_offset!=0)
{ //重新移位各项基本图元索引所指向的内存地址偏移
DWORD* RawFaceAddr=(DWORD*)(solidbuf.GetBufferPtr()+solidbuf.RawFaceIndexStartAddr);
for(i=0;i<face_n;i++)
*(RawFaceAddr+i)+=addr_offset;
DWORD* RawEdgeAddr=(DWORD*)(solidbuf.GetBufferPtr()+solidbuf.EdgeIndexStartAddr);
for(i=0;i<face_n;i++)
*(RawEdgeAddr+i)+=addr_offset;
}
if(solidbuf.BasicFaceDataStartAddr==0) //以前基本面片数为空
solidbuf.BasicFaceDataStartAddr=solidbuf.GetCursorPosition();
else //重写原基本面片数据区
solidbuf.BasicFaceDataStartAddr=solidbuf.BasicFaceDataStartAddr+4*face_n;
for(int indexFace=0;indexFace<face_n;indexFace++)
{
listFacets.DeleteList();
listVertices.DeleteList();
if(!solid.GetPolyFaceAt(indexFace,rawface))
{
WriteToSolidBuffer(solidbuf,indexFace,listFacets,0,GEPOINT(0,0,0));
continue;//return false;
}
/*对于一个复杂面,肯定有一个外环,此外还可能有无数个内环,它们的法线方向是相同的
相对法线来说,外环应该逆时针方向,而内环则应该是顺时针方向,
*/
f3dArcLine edgeLine[4];
GEPOINT poly_norm=rawface.WorkNorm;
CFaceLoop outerloop=rawface.GetOutterLoop();
if(outerloop.LoopEdgeLineNum()==3)
{
outerloop.GetLoopEdgeLineAt(&solid,0,edgeLine[0]);
outerloop.GetLoopEdgeLineAt(&solid,1,edgeLine[1]);
outerloop.GetLoopEdgeLineAt(&solid,2,edgeLine[2]);
f3dPoint pt_arr[3];
if(edgeLine[0].ID&0x80000000) //负边
pt_arr[0] = edgeLine[0].End();
else
pt_arr[0] = edgeLine[0].Start();
if(edgeLine[1].ID&0x80000000) //负边
pt_arr[1] = edgeLine[1].End();
else
pt_arr[1] = edgeLine[1].Start();
if(edgeLine[2].ID&0x80000000) //负边
pt_arr[2] = edgeLine[2].End();
else
pt_arr[2] = edgeLine[2].Start();
poly_norm=rawface.WorkNorm;
if(poly_norm.IsZero())
{
f3dPoint vec1=pt_arr[1]-pt_arr[0];
f3dPoint vec2=pt_arr[2]-pt_arr[1];
poly_norm=vec1^vec2;
}
if(!Standize(poly_norm))
{
WriteToSolidBuffer(solidbuf,indexFace,listFacets,rawface.MatColor(),poly_norm);
continue;//return false;
}
//设置三角面法线、光照颜色及顶点坐标等信息
CTidGLFace *pGLFace=listFacets.AttachObject();
pGLFace->nx=poly_norm.x;
pGLFace->ny=poly_norm.y;
pGLFace->nz=poly_norm.z;
pGLFace->red = GetRValue(rawface.MatColor())/255.0f;
pGLFace->green = GetGValue(rawface.MatColor())/255.0f;
pGLFace->blue = GetBValue(rawface.MatColor())/255.0f;
pGLFace->alpha = (GLfloat)alpha;
pGLFace->header.uVertexNum=3;
pGLFace->header.clr_norm=0x03; //默认变换颜色及法线
pGLFace->m_pVertexCoordArr=new GLdouble[9];
for(j=0;j<3;j++)
{
pGLFace->m_pVertexCoordArr[3*j]=pt_arr[j].x;
pGLFace->m_pVertexCoordArr[3*j+1]=pt_arr[j].y;
pGLFace->m_pVertexCoordArr[3*j+2]=pt_arr[j].z;
}
WriteToSolidBuffer(solidbuf,indexFace,listFacets,rawface.MatColor(),poly_norm);
continue;
}
if(outerloop.LoopEdgeLineNum()==4)
{
outerloop.GetLoopEdgeLineAt(&solid,0,edgeLine[0]);
outerloop.GetLoopEdgeLineAt(&solid,1,edgeLine[1]);
outerloop.GetLoopEdgeLineAt(&solid,2,edgeLine[2]);
outerloop.GetLoopEdgeLineAt(&solid,3,edgeLine[3]);
if(rawface.WorkNorm.IsZero())//->poly_norm.IsZero())
{
f3dPoint vec1=edgeLine[0].End()-edgeLine[0].Start();
f3dPoint vec2=edgeLine[1].End()-edgeLine[1].Start();
poly_norm=vec1^vec2;
int sign1=1,sign2=1;
if(edgeLine[0].ID&0x80000000)
sign1=-1;
if(edgeLine[1].ID&0x80000000)
sign2=-1;
if(sign1+sign2==0) //异号边线
poly_norm*=-1;
}
else
poly_norm=rawface.WorkNorm;//pFace->poly_norm;
if(!Standize(poly_norm))
{
if(edgeLine[0].SectorAngle()>0)
{
poly_norm=edgeLine[0].WorkNorm();
if(edgeLine[0].ID&0x80000000)
poly_norm*=-1;
}
else if(edgeLine[1].SectorAngle()>0)
{
poly_norm=edgeLine[1].WorkNorm();
if(edgeLine[1].ID&0x80000000)
poly_norm*=-1;
}
//TODO: 未理解原意,可能是担心共线边出现
//edgeLine[0]=NULL;
}
if(edgeLine[0].SectorAngle()>0&&edgeLine[1].SectorAngle()==0&&edgeLine[2].SectorAngle()>0&&edgeLine[3].SectorAngle()==0
&&fabs(edgeLine[0].WorkNorm()*poly_norm)<EPS_COS)
{
n=max(edgeLine[0].m_uDisplaySlices,edgeLine[2].m_uDisplaySlices);
if(n==0)
{
int n1=CalArcResolution(edgeLine[0].Radius(),edgeLine[0].SectorAngle());
int n2=CalArcResolution(edgeLine[2].Radius(),edgeLine[2].SectorAngle());
n=max(n1,n2);
}
n=min(n,200);
GEPOINT vertex_arr1[200],vertex_arr2[200];
GetArcSimuPolyVertex(&edgeLine[0],vertex_arr1,n);
GetArcSimuPolyVertex(&edgeLine[2],vertex_arr2,n);
// double part_angle1=edgeLine[0]->SectorAngle()/n;
// double part_angle2=edgeLine[2]->SectorAngle()/n;
// double posAngle;
for(i=0;i<n;i++)
{
f3dPoint pt_arr[3];
//1号圆弧中间点
//posAngle=edgeLine[0]->SectorAngle()-i*part_angle1;
pt_arr[0] = vertex_arr1[n-i];//edgeLine[0]->PositionInAngle(posAngle);
//2号圆弧中间点
//posAngle=i*part_angle2;
pt_arr[1] = vertex_arr2[i];//edgeLine[2]->PositionInAngle(posAngle);
//2号圆弧中间点
//posAngle=(i+1)*part_angle2;
pt_arr[2] = vertex_arr2[i+1];//edgeLine[2]->PositionInAngle(posAngle);
f3dPoint axis_x=pt_arr[1]-pt_arr[0];
f3dPoint axis_y=pt_arr[2]-pt_arr[0];
poly_norm=axis_x^axis_y;
Standize(poly_norm);
//设置三角面法线、光照颜色及顶点坐标等信息
CTidGLFace *pGLFace=listFacets.AttachObject();
pGLFace->nx=poly_norm.x;
pGLFace->ny=poly_norm.y;
pGLFace->nz=poly_norm.z;
pGLFace->red = GetRValue(rawface.MatColor())/255.0f;
pGLFace->green = GetGValue(rawface.MatColor())/255.0f;
pGLFace->blue = GetBValue(rawface.MatColor())/255.0f;
pGLFace->alpha = (GLfloat)alpha;
pGLFace->header.uVertexNum=3;
pGLFace->m_pVertexCoordArr=new GLdouble[9];
for(j=0;j<3;j++)
{
pGLFace->m_pVertexCoordArr[3*j]=pt_arr[j].x;
pGLFace->m_pVertexCoordArr[3*j+1]=pt_arr[j].y;
pGLFace->m_pVertexCoordArr[3*j+2]=pt_arr[j].z;
}
//2号圆弧中间点
//posAngle=(i+1)*part_angle2;
pt_arr[0] = vertex_arr2[i+1];//edgeLine[2]->PositionInAngle(posAngle);
//1号圆弧中间点
//posAngle=edgeLine[0]->SectorAngle()-(i+1)*part_angle1;
pt_arr[1] = vertex_arr1[n-i-1];//edgeLine[0]->PositionInAngle(posAngle);
//1号圆弧中间点
//posAngle=edgeLine[0]->SectorAngle()-i*part_angle1;
pt_arr[2] = vertex_arr1[n-i];//edgeLine[0]->PositionInAngle(posAngle);
axis_x = pt_arr[1]-pt_arr[0];
axis_y = pt_arr[2]-pt_arr[0];
poly_norm=axis_x^axis_y;
Standize(poly_norm);
//设置三角面法线、光照颜色及顶点坐标等信息
pGLFace=listFacets.AttachObject();
pGLFace->nx=poly_norm.x;
pGLFace->ny=poly_norm.y;
pGLFace->nz=poly_norm.z;
pGLFace->red = GetRValue(rawface.MatColor())/255.0f;
pGLFace->green = GetGValue(rawface.MatColor())/255.0f;
pGLFace->blue = GetBValue(rawface.MatColor())/255.0f;
pGLFace->alpha = (GLfloat)alpha;
pGLFace->header.uVertexNum=3;
pGLFace->m_pVertexCoordArr=new GLdouble[9];
for(j=0;j<3;j++)
{
pGLFace->m_pVertexCoordArr[3*j]=pt_arr[j].x;
pGLFace->m_pVertexCoordArr[3*j+1]=pt_arr[j].y;
pGLFace->m_pVertexCoordArr[3*j+2]=pt_arr[j].z;
}
}
WriteToSolidBuffer(solidbuf,indexFace,listFacets,rawface.MatColor(),poly_norm);
continue;
}
else if(edgeLine[0].SectorAngle()==0&&edgeLine[1].SectorAngle()>0&&edgeLine[2].SectorAngle()==0&&edgeLine[3].SectorAngle()>0
&&fabs(edgeLine[1].WorkNorm()*poly_norm)<EPS_COS)
{
n=max(edgeLine[1].m_uDisplaySlices,edgeLine[3].m_uDisplaySlices);
if(n==0)
{
int n1=CalArcResolution(edgeLine[1].Radius(),edgeLine[1].SectorAngle());
int n2=CalArcResolution(edgeLine[3].Radius(),edgeLine[3].SectorAngle());
n=max(n1,n2);
}
n=min(n,200);
GEPOINT vertex_arr1[200],vertex_arr2[200];
GetArcSimuPolyVertex(&edgeLine[1],vertex_arr1,n);
GetArcSimuPolyVertex(&edgeLine[3],vertex_arr2,n);
// double part_angle1=edgeLine[1]->SectorAngle()/n;
// double part_angle2=edgeLine[3]->SectorAngle()/n;
// double posAngle;
glEnable(GL_NORMALIZE);
glEnable(GL_AUTO_NORMAL);
for(i=0;i<n;i++)
{
f3dPoint pt_arr[3];
//1号圆弧中间点
//posAngle=edgeLine[1]->SectorAngle()-i*part_angle1;
pt_arr[0] = vertex_arr1[n-i];//edgeLine[1]->PositionInAngle(posAngle);
//2号圆弧中间点
//posAngle=i*part_angle2;
pt_arr[1] = vertex_arr2[i];//edgeLine[3]->PositionInAngle(posAngle);
//2号圆弧中间点
//posAngle=(i+1)*part_angle2;
pt_arr[2] = vertex_arr2[i+1];//edgeLine[3]->PositionInAngle(posAngle);
f3dPoint axis_x=pt_arr[1]-pt_arr[0];
f3dPoint axis_y=pt_arr[2]-pt_arr[0];
poly_norm=axis_x^axis_y;
Standize(poly_norm);
CTidGLFace *pGLFace=listFacets.AttachObject();
//设置三角面法线、光照颜色及顶点坐标等信息
pGLFace->nx=poly_norm.x;
pGLFace->ny=poly_norm.y;
pGLFace->nz=poly_norm.z;
pGLFace->red = GetRValue(rawface.MatColor())/255.0f;
pGLFace->green = GetGValue(rawface.MatColor())/255.0f;
pGLFace->blue = GetBValue(rawface.MatColor())/255.0f;
pGLFace->alpha = (GLfloat)alpha;
pGLFace->header.uVertexNum=3;
pGLFace->m_pVertexCoordArr=new GLdouble[9];
for(j=0;j<3;j++)
{
pGLFace->m_pVertexCoordArr[3*j]=pt_arr[j].x;
pGLFace->m_pVertexCoordArr[3*j+1]=pt_arr[j].y;
pGLFace->m_pVertexCoordArr[3*j+2]=pt_arr[j].z;
}
//2号圆弧中间点
//posAngle=(i+1)*part_angle2;
pt_arr[0] = vertex_arr2[i+1];//edgeLine[3]->PositionInAngle(posAngle);
//1号圆弧中间点
//posAngle=edgeLine[1]->SectorAngle()-(i+1)*part_angle1;
pt_arr[1] = vertex_arr1[n-i-1];//edgeLine[1]->PositionInAngle(posAngle);
//1号圆弧中间点
//posAngle=edgeLine[1]->SectorAngle()-i*part_angle1;
pt_arr[2] = vertex_arr1[n-i];//edgeLine[1]->PositionInAngle(posAngle);
axis_x=pt_arr[1]-pt_arr[0];
axis_y=pt_arr[2]-pt_arr[0];
poly_norm=axis_x^axis_y;
Standize(poly_norm);
//设置三角面法线、光照颜色及顶点坐标等信息
pGLFace=listFacets.AttachObject();
pGLFace->nx=poly_norm.x;
pGLFace->ny=poly_norm.y;
pGLFace->nz=poly_norm.z;
pGLFace->red = GetRValue(rawface.MatColor())/255.0f;
pGLFace->green = GetGValue(rawface.MatColor())/255.0f;
pGLFace->blue = GetBValue(rawface.MatColor())/255.0f;
pGLFace->alpha = (GLfloat)alpha;
pGLFace->header.uVertexNum=3;
pGLFace->m_pVertexCoordArr=new GLdouble[9];
for(j=0;j<3;j++)
{
pGLFace->m_pVertexCoordArr[3*j]=pt_arr[j].x;
pGLFace->m_pVertexCoordArr[3*j+1]=pt_arr[j].y;
pGLFace->m_pVertexCoordArr[3*j+2]=pt_arr[j].z;
}
}
WriteToSolidBuffer(solidbuf,indexFace,listFacets,rawface.MatColor(),poly_norm);
continue;
}
}
CGLTesselator t;
t.SetFilling(TRUE);
t.SetWindingRule(GLU_TESS_WINDING_ODD);
if(poly_norm.IsZero())
poly_norm=GetPolyFaceWorkNorm(&solid,rawface);
t.StartDef();
t.TessNormal(poly_norm.x,poly_norm.y,poly_norm.z);
//第一个为外环(参见B-rep模型)
int ei=0,edge_n=outerloop.LoopEdgeLineNum();
//for(pLine=pFace->outer_edge.GetFirst();pLine!=NULL;pLine=pFace->outer_edge.GetNext())
f3dArcLine line;
for(ei=0;ei<edge_n;ei++)
{
outerloop.GetLoopEdgeLineAt(&solid,ei,line);
if(line.SectorAngle()==0)
{
if(line.Start()==line.End())
continue;
if(line.ID&0x80000000)
vertice = line.End();
else
vertice = line.Start();
listVertices.AttachObject(vertice);
}
else
{
if(line.m_uDisplaySlices>0)
n=line.m_uDisplaySlices;
else
n=CalArcResolution(line.Radius(),line.SectorAngle());
double piece_angle=line.SectorAngle()/n;
for(i=0;i<n;i++)
{
if(line.ID&0x80000000)
{
if(i==0)
vertice=line.End();
else
vertice = line.PositionInAngle((n-i-1)*piece_angle);
}
else
{
if(i==0)
vertice=line.Start();
else
vertice = line.PositionInAngle(i*piece_angle);
}
listVertices.AttachObject(vertice);
}
}
}
for(pp=listVertices.EnumObjectFirst();pp!=NULL;pp=listVertices.EnumObjectNext())
t.AddVertex(*pp);
//第二个为内环
//for(pLoop=pFace->inner_loop.GetFirst();pLoop!=NULL;pLoop=pFace->inner_loop.GetNext())
for(int loopi=0;loopi<rawface.InnerLoopNum();loopi++)
{
CFaceLoop innerloop=rawface.GetInnerLoopAt(loopi);
t.ContourSeparator(); //环边界区分
edge_n=innerloop.LoopEdgeLineNum();
//for(pLine=pLoop->loop->GetFirst();pLine!=NULL;pLine=pLoop->loop->GetNext())
for(ei=0;ei<edge_n;ei++)
{
innerloop.GetLoopEdgeLineAt(&solid,ei,line);
if(line.SectorAngle()==0)
{
vertice = line.Start();
pp=listVertices.AttachObject(vertice);
t.AddVertex(*pp);
}
else
{
if(line.m_uDisplaySlices>0)
n=line.m_uDisplaySlices;
else
n=CalArcResolution(line.Radius(),line.SectorAngle());
double piece_angle=line.SectorAngle()/n;
for(j=0;j<n;j++)
{
if(j==0)
vertice=line.Start();
else
vertice = line.PositionInAngle(j*piece_angle);
pp=listVertices.AttachObject(vertice);
t.AddVertex(*pp);
}
}
}
}
t.EndDef();
trianglesBuffer.SeekPosition(0);
while(trianglesBuffer.GetRemnantSize()>0)
{
//设置三角面法线、光照颜色及顶点坐标等信息
CTidGLFace *pGLFace=listFacets.AttachObject();
pGLFace->nx=poly_norm.x;
pGLFace->ny=poly_norm.y;
pGLFace->nz=poly_norm.z;
pGLFace->red = GetRValue(rawface.MatColor())/255.0f;
pGLFace->green = GetGValue(rawface.MatColor())/255.0f;
pGLFace->blue = GetBValue(rawface.MatColor())/255.0f;
pGLFace->alpha = (GLfloat)alpha;
CTidGLFace *pPrevGLFace=listFacets.EnumObjectTail();
pGLFace->header.clr_norm=0x03; //默认变换颜色及法线
if(pPrevGLFace!=NULL)
{
if( pPrevGLFace->red==pGLFace->red&&pPrevGLFace->green==pGLFace->green&&
pPrevGLFace->blue==pGLFace->blue&&pPrevGLFace->alpha==pGLFace->alpha)
pGLFace->header.clr_norm &= 0x02;
if( pPrevGLFace->nx==pGLFace->nx&&pPrevGLFace->ny==pGLFace->ny&&pPrevGLFace->nz==pGLFace->nz)
pGLFace->header.clr_norm &= 0x01;
}
trianglesBuffer.ReadByte(&pGLFace->header.mode);
trianglesBuffer.ReadWord(&pGLFace->header.uVertexNum);
pGLFace->m_pVertexCoordArr=new GLdouble[pGLFace->header.uVertexNum*3];
trianglesBuffer.Read(pGLFace->m_pVertexCoordArr,pGLFace->header.uVertexNum*24);
}
WriteToSolidBuffer(solidbuf,indexFace,listFacets,rawface.MatColor(),poly_norm);
}
solid.CopyBuffer(solidbuf.GetBufferPtr(),solidbuf.GetLength());
return true;
}
int CTidSolidBody::KeyPointNum()
{
return solid.KeyPointNum();
}
TID_COORD3D CTidSolidBody::GetKeyPointAt(int i)
{
GEPOINT vertex=solid.GetKeyPointAt(i);
return TID_COORD3D(vertex);
}
int CTidSolidBody::KeyEdgeLineNum()
{
return solid.KeyEdgeLineNum();
}
ITidRawSolidEdge* CTidSolidBody::GetKeyEdgeLineAt(int i)
{
CTidRawSolidEdge* pEdge=hashEdges.Add(i+1);
solid.GetKeyEdgeLineAt(i,pEdge->edge);
return pEdge;
}
bool CTidSolidBody::GetKeyEdgeLineAt(int i,TidArcline& line)
{
f3dArcLine arcline;
if(!solid.GetKeyEdgeLineAt(i,arcline))
return false;
char linebuf[200]={0};
DWORD size=arcline.ToByteArr(linebuf);
line.FromByteArr(linebuf,size);
return true;
}
int CTidSolidBody::PolyFaceNum()
{
return solid.PolyFaceNum();
}
IRawSolidFace* CTidSolidBody::GetPolyFaceAt(int i)
{
CRawSolidFace face;
if(!solid.GetPolyFaceAt(i,face))
return false;
CTidRawFace* pFace=hashRawFaces.Add(i+1);
pFace->m_pSolidBody=&solid;
pFace->face=face;
return pFace;
}
int CTidSolidBody::BasicFaceNum()
{
return solid.BasicGLFaceNum();
}
ITidBasicFace* CTidSolidBody::GetBasicFaceAt(int i)
{
CBasicGlFace basicface;
if(!solid.GetBasicGLFaceAt(i,basicface))
return NULL;
CTidBasicFace* pFace=hashBasicFaces.Add(i+1);
pFace->basicface=basicface;
return pFace;
}
//将实体从装配坐标系fromACS移位到装配坐标系toACS
void CTidSolidBody::TransACS(const TID_CS& fromACS,const TID_CS& toACS)
{
if(solid.IsExternalSolidBuffer())
solid.ToInternalBuffer();
UCS_STRU fromacs=ConvertUCSFrom(fromACS),toacs=ConvertUCSFrom(toACS);
solid.TransACS(fromacs,toacs);
}
void CTidSolidBody::TransFromACS(const TID_CS& fromACS)
{
if(solid.IsExternalSolidBuffer())
solid.ToInternalBuffer();
solid.TransFromACS(ConvertUCSFrom(fromACS));
}
void CTidSolidBody::TransToACS(const TID_CS& toACS)
{
if(solid.IsExternalSolidBuffer())
solid.ToInternalBuffer();
solid.TransToACS(ConvertUCSFrom(toACS));
}
TID_STEELMAT CSteelMaterialLibrary::GetSteelMatAt(int i)
{
TID_STEELMAT mat;
mat.cBriefSymbol=matsect.BriefSymbolAt(i);
matsect.NameCodeAt(i,mat.nameCodeStr); //返回字符串长度,允许输入NULL
return mat;
}
char CSteelMaterialLibrary::QuerySteelBriefSymbol(const char *steelmark)
{
char nameCode[8]={0};
for(BYTE i=0;i<matsect.TypeCount();i++)
{
matsect.NameCodeAt(i,nameCode);
if(_stricmp(nameCode,steelmark)==0)
return matsect.BriefSymbolAt(i);
}
return 0;
}
bool CSteelMaterialLibrary::QuerySteelNameCode(char briefmark,char* steelmark)
{
for(BYTE i=0;i<matsect.TypeCount();i++)
{
if(matsect.BriefSymbolAt(i)==briefmark)
return matsect.NameCodeAt(i,steelmark)>0;
}
return false;
}
| [
"wxc_sxy@163.com"
] | wxc_sxy@163.com |
b0ed8a2cbed8c17ff2e7e7f5c2b83df2d7948b47 | cbca949c25ef12fb2f1134752d7f684251c00052 | /core/modules/cliff_settings.cpp | ca771b8ce01890b59d96f403381028471de5a6d3 | [
"MIT"
] | permissive | lebedyanka/rf | 7427dd5471e75951302e043a511eb40adafc2dd0 | aaedc7c8b7bdf6caf2732bf214db8936fa8dc018 | refs/heads/master | 2023-04-27T19:23:09.086283 | 2021-05-11T15:41:28 | 2021-05-11T15:41:28 | 366,419,878 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,140 | cpp | #include "cliff.h"
namespace prowogene {
namespace modules {
using std::string;
using utils::JsonObject;
static const string kEnabled = "enabled";
static const string kOctaves = "octaves";
static const string kLevels = "levels";
static const string kSeed = "seed";
static const string kGrain = "grain";
void CliffSettings::Deserialize(JsonObject config) {
enabled = config[kEnabled];
octaves = config[kOctaves];
levels = config[kLevels];
seed = config[kSeed];
grain = config[kGrain];
}
JsonObject CliffSettings::Serialize() const {
JsonObject config;
config[kEnabled] = enabled;
config[kOctaves] = octaves;
config[kLevels] = levels;
config[kSeed] = seed;
config[kGrain] = grain;
return config;
}
string CliffSettings::GetName() const {
return kConfigCliff;
}
void CliffSettings::Check() const {
CheckCondition(octaves > 0, "octaves is less than 1");
CheckCondition(levels > 1, "levels is less than 2");
CheckCondition(seed >= 0, "seed is less than 1");
CheckInRange(grain, 0.f, 1.f, "grain");
}
} // namespace modules
} // namespace prowogene
| [
"lebedyanka97@gmail.com"
] | lebedyanka97@gmail.com |
eb481c4bc3c811826fe377121a4763d6f3c1bc8f | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/Dependencies/Xerces/include/xercesc/internal/VecAttributesImpl.cpp | 421153a8851b0024e40bf368a251d425551fae51 | [] | no_license | svn2github/ngene | b2cddacf7ec035aa681d5b8989feab3383dac012 | 61850134a354816161859fe86c2907c8e73dc113 | refs/heads/master | 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,083 | cpp | /*
* Copyright 1999-2001,2004 The Apache Software Foundation.
*
* 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.
*/
/*
* $Id: VecAttributesImpl.cpp 191054 2005-06-17 02:56:35Z jberry $
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/Janitor.hpp>
#include <xercesc/internal/VecAttributesImpl.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Constructors and Destructor
// ---------------------------------------------------------------------------
VecAttributesImpl::VecAttributesImpl() :
fAdopt(false)
, fCount(0)
, fVector(0)
, fScanner(0)
{
}
VecAttributesImpl::~VecAttributesImpl()
{
//
// Note that some compilers can't deal with the fact that the pointer
// is to a const object, so we have to cast off the const'ness here!
//
if (fAdopt)
delete (RefVectorOf<XMLAttr>*)fVector;
}
// ---------------------------------------------------------------------------
// Implementation of the attribute list interface
// ---------------------------------------------------------------------------
unsigned int VecAttributesImpl::getLength() const
{
return fCount;
}
const XMLCh* VecAttributesImpl::getURI(const unsigned int index) const
{
// since this func really needs to be const, like the rest, not sure how we
// make it const and re-use the fURIBuffer member variable. we're currently
// creating a buffer each time you need a URI. there has to be a better
// way to do this...
//XMLBuffer tempBuf;
if (index >= fCount) {
return 0;
}
//fValidator->getURIText(fVector->elementAt(index)->getURIId(), tempBuf) ;
//return tempBuf.getRawBuffer() ;
return fScanner->getURIText(fVector->elementAt(index)->getURIId());
}
const XMLCh* VecAttributesImpl::getLocalName(const unsigned int index) const
{
if (index >= fCount) {
return 0;
}
return fVector->elementAt(index)->getName();
}
const XMLCh* VecAttributesImpl::getQName(const unsigned int index) const
{
if (index >= fCount) {
return 0;
}
return fVector->elementAt(index)->getQName();
}
const XMLCh* VecAttributesImpl::getType(const unsigned int index) const
{
if (index >= fCount) {
return 0;
}
return XMLAttDef::getAttTypeString(fVector->elementAt(index)->getType(), fVector->getMemoryManager());
}
const XMLCh* VecAttributesImpl::getValue(const unsigned int index) const
{
if (index >= fCount) {
return 0;
}
return fVector->elementAt(index)->getValue();
}
int VecAttributesImpl::getIndex(const XMLCh* const uri, const XMLCh* const localPart ) const
{
//
// Search the vector for the attribute with the given name and return
// its type.
//
XMLBuffer uriBuffer(1023, fVector->getMemoryManager()) ;
for (unsigned int index = 0; index < fCount; index++)
{
const XMLAttr* curElem = fVector->elementAt(index);
fScanner->getURIText(curElem->getURIId(), uriBuffer) ;
if ( (XMLString::equals(curElem->getName(), localPart)) &&
(XMLString::equals(uriBuffer.getRawBuffer(), uri)) )
return index ;
}
return -1;
}
int VecAttributesImpl::getIndex(const XMLCh* const qName ) const
{
//
// Search the vector for the attribute with the given name and return
// its type.
//
for (unsigned int index = 0; index < fCount; index++)
{
const XMLAttr* curElem = fVector->elementAt(index);
if (XMLString::equals(curElem->getQName(), qName))
return index ;
}
return -1;
}
const XMLCh* VecAttributesImpl::getType(const XMLCh* const uri, const XMLCh* const localPart ) const
{
int retVal = getIndex(uri, localPart);
return ((retVal < 0) ? 0 : getType(retVal));
}
const XMLCh* VecAttributesImpl::getType(const XMLCh* const qName) const
{
int retVal = getIndex(qName);
return ((retVal < 0) ? 0 : getType(retVal));
}
const XMLCh* VecAttributesImpl::getValue(const XMLCh* const uri, const XMLCh* const localPart ) const
{
int retVal = getIndex(uri, localPart);
return ((retVal < 0) ? 0 : getValue(retVal));
}
const XMLCh* VecAttributesImpl::getValue(const XMLCh* const qName) const
{
int retVal = getIndex(qName);
return ((retVal < 0) ? 0 : getValue(retVal));
}
// ---------------------------------------------------------------------------
// Setter methods
// ---------------------------------------------------------------------------
void VecAttributesImpl::setVector(const RefVectorOf<XMLAttr>* const srcVec
, const unsigned int count
, const XMLScanner * const scanner
, const bool adopt)
{
//
// Delete the previous vector (if any) if we are adopting. Note that some
// compilers can't deal with the fact that the pointer is to a const
// object, so we have to cast off the const'ness here!
//
if (fAdopt)
delete (RefVectorOf<XMLAttr>*)fVector;
fAdopt = adopt;
fCount = count;
fVector = srcVec;
fScanner = scanner ;
}
XERCES_CPP_NAMESPACE_END
| [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
] | Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57 |
f06c7946b8ece14ad3cd6a4226c2a1f669fc46cf | b136d3337b25b08bef4d60582e10fe14a24daa57 | /src/model/cpu/SignedMorsel.h | ef8169585aa7f8b0dc5ecee4ada7876c68a33ca6 | [] | no_license | jcantrell/cpusim | f5f61f52d5a35c9cd7f21a50c9986b854f280d84 | 619a3fe0f30c7eb8acc78b35bb47e50bd14b7fff | refs/heads/master | 2023-03-27T08:34:06.519382 | 2020-04-20T05:52:10 | 2020-04-20T05:52:10 | 351,300,683 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,581 | h | #ifndef SIGNEDMORSEL_H
#define SIGNEDMORSEL_H
#include <boost/dynamic_bitset.hpp>
#include <boost/functional/hash.hpp>
#include <iostream>
#include "UnsignedMorsel.h"
using namespace std;
using namespace boost;
class UnsignedMorsel;
class SignedMorsel
{
private:
UnsignedMorsel um;
friend class UnsignedMorsel;
public:
SignedMorsel() : um(0ul) {}
size_t count();
SignedMorsel(dynamic_bitset<> in);
SignedMorsel(unsigned long long int in);
SignedMorsel(const UnsignedMorsel in);
SignedMorsel operator+(const SignedMorsel& other) ;
SignedMorsel operator+(int rhs);
SignedMorsel operator-(const SignedMorsel& other);
friend SignedMorsel operator-(int lhsInt, const SignedMorsel& other);
SignedMorsel operator-=(const SignedMorsel& other);
SignedMorsel& operator++(int);
SignedMorsel& operator=(unsigned long long int in);
SignedMorsel& operator=(const SignedMorsel& other);
string asString() const ;
friend std::ostream& operator<<( std::ostream& stream, const SignedMorsel& addr ) ;
bool operator<(const SignedMorsel other) const;
bool operator<(int other);
bool operator<=(const SignedMorsel& other);
bool operator<=(int other);
friend bool operator<=(int lhs, const SignedMorsel& rhs);
bool operator>(int other);
friend bool operator>(int lhs, SignedMorsel rhs);
bool operator>(SignedMorsel other);
bool operator>=(const SignedMorsel& other);
SignedMorsel operator/(const SignedMorsel& other);
SignedMorsel operator%(const SignedMorsel& other);
unsigned int size() const;
bool operator==(SignedMorsel other) const ;
bool operator==(int other) const ;
unsigned int asInt() const;
SignedMorsel operator&(const SignedMorsel& other);
SignedMorsel operator&(int otherInt);
SignedMorsel operator|(const SignedMorsel& other);
SignedMorsel operator|=(const SignedMorsel& other);
SignedMorsel operator~();
SignedMorsel operator-();
SignedMorsel operator^(const SignedMorsel& other) const;
SignedMorsel operator<<(const SignedMorsel& other);
SignedMorsel operator<<(int other);
SignedMorsel pb(int other);
SignedMorsel operator>>(int other);
SignedMorsel operator>>(const SignedMorsel& other);
SignedMorsel operator*(const SignedMorsel& other);
friend SignedMorsel operator*(int lhs, const SignedMorsel& other);
SignedMorsel& operator<<=(uint64_t in);
bool operator!=(const SignedMorsel& other);
bool operator!=(unsigned long long int in);
float asFloat() const;
unsigned char asChar();
SignedMorsel& resize(unsigned int newsize);
UnsignedMorsel asUnsignedMorsel();
};
#endif
| [
"cantrel2@pdx.edu"
] | cantrel2@pdx.edu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.