blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fd7d5e4fd1b17e402a2787f8296bfa8e0ded0194 | 2e0a91772d3d1a61a87c24411a7cff42d92a0a1c | /include/Interaction.h | 72c019dd2db63ea4493796ea580033729d90e44a | [] | no_license | lubosz/Collage | 0030e0239ba3a46bb6565a19cca0447e6358f19c | b84db3b19e778db19b9a939badcbca5a65d75e94 | refs/heads/master | 2020-12-24T17:35:22.651576 | 2011-07-13T14:27:31 | 2011-07-13T14:27:31 | 1,031,859 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,424 | h | /*
* Copyright 2010 The Collage Project
*/
#ifndef INTERACTION_H_
#define INTERACTION_H_
template <class T1, class T2>
class AbstractInteraction {
public:
AbstractInteraction() {}
virtual ~AbstractInteraction() {}
T1* first;
T2* second;
void initActors(T1* first, T2* second) {
this->first = first;
this->second = second;
init();
}
virtual void init() = 0;
virtual void interact(float d_t) = 0;
virtual void print() {
first->print();
second->print();
}
};
template <class T1, class T2>
class AbstractCollisionInteraction : public AbstractInteraction<T1, T2> {
public:
bool inside;
void init() {
inside = false;
onInit();
}
void interact(float d_t) {
if (collisionTest()) {
if (inside) {
whileInside(d_t);
} else {
onEnter();
}
inside = true;
} else {
if (inside) {
onLeave();
} else {
whileOutside(d_t);
}
inside = false;
}
}
virtual bool collisionTest() = 0;
virtual void onInit() {}
virtual void onEnter() {}
virtual void onLeave() {}
virtual void whileInside(float d_t) {}
virtual void whileOutside(float d_t) {}
};
template <class T1, class T2>
class Interaction : public AbstractInteraction<T1, T2> {
public:
Interaction() {}
virtual ~Interaction() {}
void init() {}
void interact(float d_t) {}
};
#endif /* INTERACTION_H_ */
| [
"treevg+github@gmail.com"
] | treevg+github@gmail.com |
516b058f542f91af4e852561e7914c6752da934e | f39523072290de7eb64409b6bfdcf52ecffcf537 | /2156/2156.cpp | f027fe1196e311eef91cf2fa19e51f0b8ab6cf87 | [] | no_license | mataeil/baekjoon | e6c00b16d56b29e8f96862a7fb1ff8c2703f6a77 | e26d9144e2831f20c4d15ace7eae9fc271fbd179 | refs/heads/master | 2021-01-20T20:21:51.839495 | 2016-06-20T14:34:18 | 2016-06-20T14:34:18 | 61,509,436 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 602 | cpp | #include <cstdio>
#include <cstdlib>
int d[10001];
int arr[10001];
int main(){
//freopen("test/9465.txt","r", stdin);
int n;
scanf("%d",&n);
for(int i=1; i<=n; i++){
scanf("%d",&arr[i]);
}
d[1] = arr[1];
d[2] = arr[1] + arr[2];
for(int i=3; i<=n; i++){
d[i] = d[i-1];
if(d[i] < d[i-2] + arr[i])
d[i] = d[i-2] + arr[i];
if(d[i] < d[i-3] + arr[i]+arr[i-1])
d[i] = d[i-3] + arr[i]+arr[i-1];
}
printf("%d\n",d[n]);
return 0;
}
| [
"taeil.ma0915@gmail.com"
] | taeil.ma0915@gmail.com |
89df6e0e4de6ddf0dd93b0bd667cc20b8bc5ba07 | 675f101437be7828bfc7dc50250c342a122c909a | /src/CyoClip/pch.cpp | f9cdd2d74c21b4e29785fe2a60dc99da7ded5a2e | [
"MIT"
] | permissive | calzakk/CyoClip | 31ff39309b9df345c2c15b6cc9777d5712f12411 | 70e9277add5a0358ed7c5814bc45efdaee6a0eed | refs/heads/master | 2020-04-18T19:15:34.120004 | 2019-02-23T20:34:54 | 2019-02-23T20:34:54 | 167,707,779 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,111 | cpp | /*
[CyoClip] pch.cpp
MIT License
Copyright (c) 2019 Graham Bull
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 "pch.h"
| [
"kaizohh+github@gmail.com"
] | kaizohh+github@gmail.com |
e699e26ea51e1f7f5d3b34ae931e9ee467dbb6fe | 131620b984b19112be2616fe4e5855164c00c019 | /二叉树1.cpp | 9a80a0dda467cb2a07333759a27d62f019a3ade0 | [] | no_license | lollipopnougat/-C- | 70e966a4af632076667e591b598a187c8794de73 | 99ed0cb4e950e44ee83963dbf7d947b2051399c2 | refs/heads/master | 2021-09-15T14:16:16.585517 | 2018-06-03T15:22:12 | 2018-06-03T15:22:12 | 111,933,053 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,499 | cpp | //coding=UTF-8
#include<iostream>
#include<cstdlib>
#include<string>
using namespace std;
template <typename T>
struct BiNode
{
T data;
BiNode<T>* lchild,* rchild;
};
template <typename T>
class BiTree
{
public:
BiTree(){root=Creat(root);} //建立新二叉树
~BiTree(){Relase(root);} //析构
void PreOrder(){PreOrder(root);} //前序
void InOrder(){InOrder(root);} //中序
void PostOrder(){PostOrder(root);} //后序
void LeverOrder();
private:
BiNode<T>* root;
BiNode<T>* Creat(BiNode<T> *bt); //递归建立新节点
void Relase(BiNode<T> *bt); //递归销毁节点
void PreOrder(BiNode<T> *bt); //递归前序
void InOrder(BiNode<T> *bt); //递归中序
void PostOrder(BiNode<T> *bt); //递归后序
int m,t;
};
template <typename T>
class EasyTree
{
public:
void start();
private:
//BiTree<T> tree;
//string str;
int n;
};
template <typename T>
void BiTree<T>::PreOrder(BiNode<T> *bt)
{
if(bt==NULL) return;
else {
cout<<bt->data;
PreOrder(bt->lchild);
PreOrder(bt->rchild);
}
}
template <typename T>
void BiTree<T>::InOrder(BiNode<T> *bt)
{
if(bt==NULL) return;
else {
InOrder(bt->lchild);
cout<<bt->data;
InOrder(bt->rchild);
}
}
template <typename T>
void BiTree<T>::PostOrder(BiNode<T> *bt)
{
if(bt==NULL) return;
else {
PostOrder(bt->lchild);
PostOrder(bt->rchild);
cout<<bt->data;
}
}
template <typename T>
void BiTree<T>::LeverOrder()
{
int front,rear;
BiNode<T>* Q[50],* q;
front=-1;
rear=-1;
if(root=NULL) return;
Q[++rear]=root; //先加一再使用值
while(front!=rear)
{
q=Q[++front];
if(q->lchild!=NULL) Q[++rear]=q->lchild;
if(q->rchild!=NULL) Q[++rear]=q->rchild;
}
}
template <typename T>
BiNode<T>* BiTree<T>::Creat(BiNode<T>* bt)
{
char ch;
cin>>ch;
if(ch=='#') bt=NULL;
else {
bt=new BiNode<T>;
bt->data=ch;
bt->lchild=Creat(bt->lchild);
bt->rchild=Creat(bt->rchild);
}
return bt;
}
template <typename T>
void BiTree<T>::Relase(BiNode<T>* bt)
{
if(bt!=NULL){
Relase(bt->lchild);
Relase(bt->rchild);
delete bt;
}
}
template <typename T>
void EasyTree<T>::start()
{
BiTree<char> tree;
while(true)
{
cout<<"\n1:前序遍历;\n2:中序遍历;\n3:后序遍历;\n4:层序遍历"<<endl;
cin>>n;
switch(n)
{
case 1:tree.PreOrder();break;
case 2:tree.InOrder();break;
case 3:tree.PostOrder();break;
case 4:tree.LeverOrder();break;
default :cout<<"输入错误"<<endl;
}
}
}
int main()
{
EasyTree<char> newone;
newone.start();
return 0;
}
| [
"33110314+lollipopnougat@users.noreply.github.com"
] | 33110314+lollipopnougat@users.noreply.github.com |
da9b6d29b294fa64d62de474e82479d7f6b193fb | f478932481fe15ab728db2e6eebaf1206a233ae0 | /HashTables/main.cpp | f0b9696ecb841777b50bf78c6df08c52d4291cac | [] | no_license | CoryBrown-42/HashTables | e0d7523d3af49148121795060b6e09fccd8d0f49 | 3945aed09411eed6352b2cf79681aa83fa1c00d3 | refs/heads/master | 2021-01-02T00:26:01.715517 | 2020-02-10T02:21:59 | 2020-02-10T02:21:59 | 239,410,689 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,195 | cpp | #include <iostream>
#include <vector>
#include <algorithm>//sort, random_shuffle
#include <string>
#include "Timer.h"
#include "DirectAddressTable.h"
#include "HashTable.h"
using namespace std;
class Movie
{
public:
int id;//Key to our Direct Address Table.
string movieData;
string name;
int playCount;
string genre;
bool operator<(Movie &rhs) const//const here means this func can't change 'id' or 'name', etc. of the movie
{
return playCount < rhs.playCount;
}
private:
};
//bool operator<(Movie &leftSide, Movie &rightSide)
//{
// return leftSide.id < rightSide.id;
//}
/*Searching
Binary Search O(log(n))
Linear Search, Brute Force Search O(n)
Can we search in O(1) complexity?
Sorting
Bubble Sort O(n^2)
Selection Sort O(n^2)
Insertion Sort O(n^2) - Best Case Big-Omega(n)
Quick Sort O(n^2) - Average case O(nlog(n))
Merge Sort O(nlog(n))
Can we sort in O(n)?
*/
//Downside = only works on positive, unique integers
//And requires an array as big as the largest value + 1 - so you might waste alot of space
//Comparative Sorting = Sort by comparing values to each other
//Counting Sort is NOT a comparative sort (it doesn't compare numbers to determine locations)
//In-place sort = just shuffles things around the original vector (doesn't make new vectors)
//Counting Sort is NOT an in place sort
void CountingSort(vector<int> &vec)//O(n)
{
vector<int> sortedVec(vec.size());//new vector same size as original
for (int i = 0; i < vec.size(); ++i)
sortedVec[vec[i]] = vec[i];
vec = sortedVec;//copy sorted vector back to original
}
int main()
{
int n = 10;
vector<int> numbers;
for(int i = 0; i < n; ++i)
numbers.push_back(i);
random_shuffle(numbers.begin(), numbers.end());
for (int i = 0; i < n; ++i)
cout << numbers[i] << endl;
cout << endl;
CountingSort(numbers);
for (int i = 0; i < n; ++i)
cout << numbers[i] << endl;
Movie lordOfTheRings;
lordOfTheRings.id = 742;
lordOfTheRings.name = "Lord of the Rings";
Movie jurassicParty;
jurassicParty.id = 369;
jurassicParty.name = "Jurassic Party";
Movie dannydevito;
dannydevito.id = 204;
dannydevito.name = "Danny Devito";
Movie civilWar;
civilWar.id = 839;
civilWar.name = "Captain America: Civil War";
DirectAddressTable<Movie> datMovie(850);
datMovie.Add(lordOfTheRings.id, lordOfTheRings);
datMovie.Add(jurassicParty.id, jurassicParty);
datMovie.Add(dannydevito.id, dannydevito);
datMovie.Add(civilWar.id, civilWar);
Movie lotRCopy = datMovie.Search(lordOfTheRings.id);//O(1) search
cout << lotRCopy.name << endl;
HashTable<Movie, int> mHT;//movieHashTable
mHT.Add(lordOfTheRings.id, lordOfTheRings);
mHT.Add(jurassicParty.id, jurassicParty);
mHT.Add(dannydevito.id, dannydevito);
mHT.Add(civilWar.id, civilWar);
//mHT[civilWar.id] = civilWar;//next time...
Movie tempMovie = mHT[civilWar.id];
cout << tempMovie.name << endl;
HashTable<double, int> importantMathConstants;
importantMathConstants.Add(3, 3.14159);
importantMathConstants.Add(1, 6.022e23);
cout << importantMathConstants[3] << endl;
int num = 5;
int num2 = 6;
//jurassicParty = civilWar;//Memberwise assignment
//cout << jurassicParty + civilWar << endl;
return 0;
} | [
"afo.cory@gmail.com"
] | afo.cory@gmail.com |
a27547011ce786fc8fcff650861b5088930b80fd | 96378b829ce5a1c230aa6a17c434460b50397256 | /ps4/hashutil/hashtable.h | 1b2fad19801927a76efc36004d1aedf9a0a0fb2f | [] | no_license | a-dhagat/Advanced_Engineering_Computation | bdd90cc963b668e6e11a0ea20fc967a0915cf725 | 43b6811e0ea1a2d73593e1d62fde073619504738 | refs/heads/master | 2021-05-21T03:03:36.488870 | 2020-04-02T16:51:48 | 2020-04-02T16:51:48 | 252,513,405 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,264 | h | #ifndef HASHTABLE_IS_INCLUDED
#define HASHTABLE_IS_INCLUDED
/* { */
#include <vector>
#include <stdio.h>
#include "hashbase.h"
template <class KeyType,class ValueType>
class HashTable : public HashBase <KeyType>,public HashCommon
{
private:
class Entry
{
public:
KeyType hashKey;
CodeType hashCode;
ValueType value;
};
std::vector <std::vector <Entry> > table;
public:
using HashCommon::Handle;
using HashCommon::CodeType;
using HashBase<KeyType>::HashCode;
HashTable();
~HashTable();
void CleanUp(void);
void Update(const KeyType &key,const ValueType &value);
bool IsIncluded(const KeyType &key) const;
void Resize(long long int tableSize);
void Delete(const KeyType &key);
ValueType *operator[](const KeyType key);
const ValueType *operator[](const KeyType key) const;
Handle First(void) const;
Handle Next(Handle hd) const;
const KeyType *operator[](Handle hd) const;
};
template <class KeyType,class ValueType>
HashTable<KeyType,ValueType>::HashTable()
{
table.resize(MINIMUM_TABLE_SIZE);
}
template <class KeyType,class ValueType>
HashTable<KeyType,ValueType>::~HashTable()
{
}
template <class KeyType,class ValueType>
void HashTable<KeyType,ValueType>::CleanUp(void)
{
HashCommon::CleanUp(table);
}
template <class KeyType,class ValueType>
void HashTable<KeyType,ValueType>::Update(const KeyType &key,const ValueType &value)
{
auto hashCode=HashCode(key);
auto idx=hashCode%table.size();
for(auto &e : table[idx])
{
if(e.hashCode==hashCode && e.hashKey==key)
{
e.value=value;
return;
}
}
Entry entry;
entry.hashKey=key;
entry.hashCode=hashCode;
entry.value=value;
table[idx].push_back(entry);
++nElem;
AutoResize(table);
}
template <class KeyType,class ValueType>
bool HashTable<KeyType,ValueType>::IsIncluded(const KeyType &key) const
{
return HashCommon::IsIncluded(table,key,HashCode(key));
}
template <class KeyType,class ValueType>
void HashTable<KeyType,ValueType>::Resize(long long int tableSize)
{
HashCommon::Resize(table,tableSize);
}
template <class KeyType,class ValueType>
void HashTable<KeyType,ValueType>::Delete(const KeyType &key)
{
HashCommon::Delete(table,key,HashCode(key));
}
template <class KeyType,class ValueType>
ValueType *HashTable<KeyType,ValueType>::operator[](const KeyType key)
{
auto hashCode=HashCode(key);
auto idx=hashCode%table.size();
for(auto &e : table[idx])
{
if(e.hashCode==hashCode && e.hashKey==key)
{
return &e.value;
}
}
return nullptr;
}
template <class KeyType,class ValueType>
const ValueType *HashTable<KeyType,ValueType>::operator[](const KeyType key) const
{
auto hashCode=HashCode(key);
auto idx=hashCode%table.size();
for(auto &e : table[idx])
{
if(e.hashCode==hashCode && e.hashKey==key)
{
return &e.value;
}
}
return nullptr;
}
template <class KeyType,class ValueType>
HashCommon::Handle HashTable<KeyType,ValueType>::Next(Handle hd) const
{
return HashCommon::Next(table,hd);
}
template <class KeyType,class ValueType>
const KeyType *HashTable<KeyType,ValueType>::operator[](Handle hd) const
{
return &table[hd.row][hd.column].hashKey;
}
template <class KeyType,class ValueType>
HashCommon::Handle HashTable<KeyType,ValueType>::First(void) const
{
return HashCommon::First(table);
}
/* } */
#endif
| [
"adhagat@andrew.cmu.edu"
] | adhagat@andrew.cmu.edu |
ea1123a960867db083fb54923071652567554322 | 869d2b0a1ab0e8f3bd8d4ac2345199aa4aff2842 | /mbn_common/include/mbn_common/MarkerSearcherCoordination.hpp | 015593ededcbf5615f4d9940ad2a279f6106f37c | [] | no_license | Bzhnja/MarkerBasedNavigation | 0df19734c751bffd5bcb84ac4c240b0017f48ed1 | e609a30252f1869131241bca186d6f818e8f96ce | refs/heads/master | 2021-05-26T23:07:42.101598 | 2013-03-07T15:42:22 | 2013-03-07T15:42:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,427 | hpp | /********************************************************************************
*
* MarkerSearcherCoordinationio
*
* Copyright (c) 2012
* All rights reserved.
*
* Davide Brugali, Aldo Biziak, Luca Gherardi, Andrea Luzzana
* University of Bergamo
* Dept. of Information Technology and Mathematics
*
* -------------------------------------------------------------------------------
*
* File: MarkerSearcherCoordination.hpp
* Created: June 13, 2012
*
* Author: <A HREF="mailto:luca.gherardi@unibg.it">Luca Gherardi</A>
* Author: <A HREF="mailto:andrea.luzzana@unibg.it">Andrea Luzzana</A>
* Author: <A HREF="mailto:aldo.biziak@unibg.it">Aldo Biziak</A>
*
* Supervised by: <A HREF="mailto:brugali@unibg.it">Davide Brugali</A>
*
* -------------------------------------------------------------------------------
*
* This sofware is published under a dual-license: GNU Lesser General Public
* License LGPL 2.1 and BSD license. The dual-license implies that users of this
* code may choose which terms they prefer.
*
* -------------------------------------------------------------------------------
*
* 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 University of Bergamo nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License LGPL as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version or the BSD license.
*
* 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 Lesser General Public License LGPL and the BSD license for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License LGPL and BSD license along with this program.
*
*******************************************************************************/
#ifndef MARKER_SEARCHER_COORDINATION_HPP
#define MARKER_SEARCHER_COORDINATION_HPP
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <tf/tf.h>
#include <angles/angles.h>
#include "mbn_common/MarkerSearcherComputation.hpp"
#include "mbn_common/Events.hpp"
using namespace std;
namespace mbn_common{
class MarkerSearcherCoordination{
private:
/**
* The possible states of the state machine
*/
typedef enum {
IDLE = 0, /** The marker searcher is idle */
TARGET_RECEIVED = 1, /** The marker searcher has received the target marker and is waiting for new inputs */
GOAL_GENERATED = 2, /** The marker searcher has produced a search pose and is waiting for the movement start */
MOVING = 3 /** The marker searcher has produced a search pose and the movement has started */
} state;
public:
/**
* \param markerSearcherComputer a pointer to the computation instance
*
* Creates a new MarkerSearcherCoordinator.
*/
MarkerSearcherCoordination(MarkerSearcherComputation* markerSearcherComputer);
/**
* Class destroyer.
*/
~MarkerSearcherCoordination(void);
/**
* This method trigger the state machine and has to be called
* when a new target marker is provided
*/
void notifyTargetMarkerIDReceived();
/**
* This method trigger the state machine and has to be called
* when new visible markers IDs are provided
*/
void notifyVisibleMarkersIDsReceived();
/**
* This method trigger the state machine and has to be called
* periodically. It looks whether the target marker has been found
* or not and if needed (marker not found) ask to markerSearcherComputation
* to generate a new search pose.
*/
void notifyTimeElapsed();
/**
* This method trigger the state machine and has to be called
* when the robot starts to move towards the last computed search
* pose
*/
void notifyMotionStarted();
/**
* This method trigger the state machine and has to be called
* when the robot has reached the last computed search pose
*/
void notifySearchPoseReached();
/**
* This method return an output event which is equal to
* "TARGET_MARKER_FOUND" when the target marker has been found.
*/
string getOutputEvent();
private:
/**
* True if the target marker has been found
*/
bool markerFound;
/**
* True if the last generated search pose has been reached
*/
bool motionDone;
/**
* The current state of the state machine
*/
state currentState;
/**
* The output event that will be returned by the method getOutputEvent.
*/
string outputEvent;
/**
* The Marker searcher computer, which is in charge of computing the next search
* pose based on the inputs
*/
MarkerSearcherComputation* markerSearcherComputation;
};
}
#endif
| [
"lucaghera8@gmail.com"
] | lucaghera8@gmail.com |
aa3918f7bf71f11acb07efa1f67aa32ef81121f1 | fd29422c46d2cdec69ec5c5a960e661ecdcf7692 | /Course Work/CG/rubiksss/RubiksCubeSolution/RubiksCube/Quaternion.h | 48e2cdf412fa845096793073f8a32ba91f5f269f | [] | no_license | codechef34/Software-Engineering | 52a8e994e03036345b713f6ce94347e0cbd00251 | 213401d5382461fa3a85bad727a00f3650e208a8 | refs/heads/master | 2016-09-06T08:13:12.703773 | 2015-11-06T15:50:42 | 2015-11-06T15:50:42 | 42,978,546 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 289 | h | #pragma once
#include "Vector3f.h"
//should probably make it like a Vector4f
class Quaternion
{
public:
Quaternion(float _x, float _y, float _z, float w);
~Quaternion(void);
float X() const;
float Y() const;
float Z() const;
float W() const;
private:
Vector3f xyz;
float w;
};
| [
"jayaachyuth34@gmail.com"
] | jayaachyuth34@gmail.com |
254fe17af51dcc2d51ad008ca17dcdcfc322c4bd | f6bb52a9c8261d1cdc631010f9d1c325a7eed522 | /sketchbook/libraries/Adafruit_Motor_Shield_V2_Library/examples/DCMotorTest/DCMotorTest.ino | 8df7b37535197bcfae1af423628473e794327dd8 | [
"BSD-3-Clause",
"BSD-2-Clause",
"MIT",
"bzip2-1.0.6",
"LicenseRef-scancode-x11-doc",
"BSD-Protection",
"LGPL-3.0-or-later",
"MS-PL",
"blessing",
"BSD-4.3TAHOE",
"IJG",
"Zlib",
"LicenseRef-scancode-ibm-dhcp",
"NCSA",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-fftpac... | permissive | technoman72/BlocklyArduino_electrified | f83d55c9bcaa0a8ac1d3d93eeceba6830c6ac7c2 | b91c1d37313ba5f5d0065e8cb264e7d7b45eb2e9 | refs/heads/master | 2020-04-28T23:54:41.710317 | 2019-03-08T18:12:38 | 2019-03-08T18:12:38 | 175,167,947 | 0 | 0 | MIT | 2019-03-12T08:34:04 | 2019-03-12T08:33:52 | null | UTF-8 | C++ | false | false | 1,685 | ino | /*
This is a test sketch for the Adafruit assembled Motor Shield for Arduino v2
It won't work with v1.x motor shields! Only for the v2's with built in PWM
control
For use with the Adafruit Motor Shield v2
----> http://www.adafruit.com/products/1438
*/
#include <Wire.h>
#include <Adafruit_MotorShield.h>
// Create the motor shield object with the default I2C address
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
// Or, create it with a different I2C address (say for stacking)
// Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x61);
// Select which 'port' M1, M2, M3 or M4. In this case, M1
Adafruit_DCMotor *myMotor = AFMS.getMotor(1);
// You can also make another motor on port M2
//Adafruit_DCMotor *myOtherMotor = AFMS.getMotor(2);
void setup() {
Serial.begin(9600); // set up Serial library at 9600 bps
Serial.println("Adafruit Motorshield v2 - DC Motor test!");
AFMS.begin(); // create with the default frequency 1.6KHz
//AFMS.begin(1000); // OR with a different frequency, say 1KHz
// Set the speed to start, from 0 (off) to 255 (max speed)
myMotor->setSpeed(150);
myMotor->run(FORWARD);
// turn on motor
myMotor->run(RELEASE);
}
void loop() {
uint8_t i;
Serial.print("tick");
myMotor->run(FORWARD);
for (i=0; i<255; i++) {
myMotor->setSpeed(i);
delay(10);
}
for (i=255; i!=0; i--) {
myMotor->setSpeed(i);
delay(10);
}
Serial.print("tock");
myMotor->run(BACKWARD);
for (i=0; i<255; i++) {
myMotor->setSpeed(i);
delay(10);
}
for (i=255; i!=0; i--) {
myMotor->setSpeed(i);
delay(10);
}
Serial.print("tech");
myMotor->run(RELEASE);
delay(1000);
} | [
"scanet@libreduc.cc"
] | scanet@libreduc.cc |
e0b355021f47e40cd0ee492143bdce309390c50c | 0683df0449351618fffb8865f3e77ecdcab1b7cb | /src/scripts/struct_enum.cpp | 2af897b7d9f9c8883d713cf628433dd40ee7b5bb | [] | no_license | mtbthebest/C- | 0e1c6aab5697f8d09165dcb78a58fbea110fd6ea | eb4aa51137c8192fa2257df91e94ad767d5fb232 | refs/heads/master | 2021-05-01T03:54:31.677598 | 2018-08-19T09:56:02 | 2018-08-19T09:56:02 | 121,196,082 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,469 | cpp | //
// Created by mtb on 18/08/13.
//
#include <iostream>
using namespace std;
void structure1(){
struct person{
char name[30];
long int tel_num ;
short int id;
};
struct person p;
p.id = 0;
std::cout <<p.id;
}
void structure2(){
struct{
char name[30];
long int tel_num ;
short int id;
} x,y;
x.id = 1;
y= x;
std::cout <<y.id;
}
void structure3(){
struct person{
char name;
long int tel_num ;
short int id;
};
struct person p[10];
p[0].id = 1;
p[1].name='djjjf';
p[0]=p[1];
std::cout <<p[1].id;
std::cout <<p[1].name;
}
void structure4(){
struct person{
char name;
long int tel_num ;
short int id;
}h;
struct person *p;
p=&h;
p->id=1;
std::cout<<h.id;
}
void enumerate(){
enum color{
red,
black,
white
};
enum color t;
t=black;
std::cout<<t;
enum colors{
yellow=100,
brown=102,
green
};
enum colors p;
p=green;
std::cout<<p;
}
void definition(){
typedef double real;
real b =10.0;
std::cout<<b<<endl;
struct person{
char name[30];
long int tel_num ;
short int id;
};
typedef struct person st;
st p;
p.id=0;
std::cout<<p.id;
}
int main(int argc, char const *argv[]) {
definition();
return 0;
}
| [
"mtbthebest11@gmail.com"
] | mtbthebest11@gmail.com |
c9b018ab489d09a60c9b3a722c68c5796154fa4f | 5ebd5cee801215bc3302fca26dbe534e6992c086 | /blazetest/src/mathtest/tsvecdmatmult/VCaLDb.cpp | ac1c1eb15a7ebaec60365d4d1d4bfc6d10284266 | [
"BSD-3-Clause"
] | permissive | mhochsteger/blaze | c66d8cf179deeab4f5bd692001cc917fe23e1811 | fd397e60717c4870d942055496d5b484beac9f1a | refs/heads/master | 2020-09-17T01:56:48.483627 | 2019-11-20T05:40:29 | 2019-11-20T05:41:35 | 223,951,030 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,349 | cpp | //=================================================================================================
/*!
// \file src/mathtest/tsvecdmatmult/VCaLDb.cpp
// \brief Source file for the VCaLDb sparse vector/dense matrix multiplication math test
//
// Copyright (C) 2012-2019 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/CompressedVector.h>
#include <blaze/math/DynamicMatrix.h>
#include <blaze/math/LowerMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/tsvecdmatmult/OperationTest.h>
#include <blazetest/system/MathTest.h>
#ifdef BLAZE_USE_HPX_THREADS
# include <hpx/hpx_main.hpp>
#endif
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'VCaLDb'..." << std::endl;
using blazetest::mathtest::TypeA;
using blazetest::mathtest::TypeB;
try
{
// Matrix type definitions
using VCa = blaze::CompressedVector<TypeA>;
using LDb = blaze::LowerMatrix< blaze::DynamicMatrix<TypeB> >;
// Creator type definitions
using CVCa = blazetest::Creator<VCa>;
using CLDb = blazetest::Creator<LDb>;
// Running tests with small vectors and matrices
for( size_t i=0UL; i<=6UL; ++i ) {
for( size_t j=0UL; j<=i; ++j ) {
RUN_TSVECDMATMULT_OPERATION_TEST( CVCa( i, j ), CLDb( i ) );
}
}
// Running tests with large vectors and matrices
RUN_TSVECDMATMULT_OPERATION_TEST( CVCa( 67UL, 7UL ), CLDb( 67UL ) );
RUN_TSVECDMATMULT_OPERATION_TEST( CVCa( 127UL, 13UL ), CLDb( 127UL ) );
RUN_TSVECDMATMULT_OPERATION_TEST( CVCa( 64UL, 8UL ), CLDb( 64UL ) );
RUN_TSVECDMATMULT_OPERATION_TEST( CVCa( 128UL, 16UL ), CLDb( 128UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during sparse vector/dense matrix multiplication:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| [
"klaus.iglberger@gmail.com"
] | klaus.iglberger@gmail.com |
6d71e4baf5a481be899d10a0bb60b094a5eeeceb | 677a41245532f3ab53adc699a7314b3b08ba6d88 | /main.cpp | 2a6a17db5fe65fd7b589b81dbcb13c97a5109eb7 | [] | no_license | cqcy321/SfM_VGG_Corridor | 8d1b759fb2bdd6881c16292b2dabacd5b1faeacd | e3b66f08ca5c4738976721e942c895bdb55dfe80 | refs/heads/master | 2021-01-25T08:19:16.742292 | 2017-06-08T13:37:35 | 2017-06-08T13:37:35 | 93,752,048 | 0 | 0 | null | 2017-06-08T13:37:36 | 2017-06-08T13:23:56 | C++ | UTF-8 | C++ | false | false | 3,370 | cpp | //#include <opencv2/sfm.hpp>
//#include <opencv2/core.hpp>
//#include <opencv2/viz.hpp>
//#include"reconstruct.hpp"
////#define CERES_FOUND
//#include <iostream>
//#include <fstream>
//#include <string>
//using namespace std;
//using namespace cv;
//using namespace cv::sfm;
//static void help() {
// cout
// << "\n------------------------------------------------------------------\n"
// << " This program shows the two view reconstruction capabilities in the \n"
// << " OpenCV Structure From Motion (SFM) module.\n"
// << " It uses the following data from the VGG datasets at ...\n"
// << " Usage:\n"
// << " reconv2_pts.txt \n "
// << " where the first line has the number of points and each subsequent \n"
// << " line has entries for matched points as: \n"
// << " x1 y1 x2 y2 \n"
// << "------------------------------------------------------------------\n\n"
// << endl;
//}
//int main(int argc, char** argv)
//{
// // Do projective reconstruction
// bool is_projective = true;
// // Read 2D points from text file
// Mat_<double> x1, x2;
// int npts;
// if (argc < 2) {
// help();
// exit(0);
// } else {
// ifstream myfile(argv[1]);
// if (!myfile.is_open()) {
// cout << "Unable to read file: " << argv[1] << endl;
// exit(0);
// } else {
// string line;
// // Read number of points
// getline(myfile, line);
// npts = (int) atof(line.c_str());
// x1 = Mat_<double>(2, npts);
// x2 = Mat_<double>(2, npts);
// // Read the point coordinates
// for (int i = 0; i < npts; ++i) {
// getline(myfile, line);
// stringstream s(line);
// string cord;
// s >> cord;
// x1(0, i) = atof(cord.c_str());
// s >> cord;
// x1(1, i) = atof(cord.c_str());
// s >> cord;
// x2(0, i) = atof(cord.c_str());
// s >> cord;
// x2(1, i) = atof(cord.c_str());
// }
// myfile.close();
// }
// }
// // Call the reconstruction function
// std::vector < Mat_<double> > points2d;
// points2d.push_back(x1);
// points2d.push_back(x2);
// Matx33d K_estimated;
// Mat_<double> points3d_estimated;
// std::vector < cv::Mat > Ps_estimated;
// reconstruct(points2d, Ps_estimated, points3d_estimated, K_estimated, is_projective);
// // Print output
// cout << endl;
// cout << "Projection Matrix of View 1: " << endl;
// cout << "============================ " << endl;
// cout << Ps_estimated[0] << endl << endl;
// cout << "Projection Matrix of View 2: " << endl;
// cout << "============================ " << endl;
// cout << Ps_estimated[1] << endl << endl;
// // Display 3D points using VIZ module
// // Create the pointcloud
// std::vector<cv::Vec3f> point_cloud;
// for (int i = 0; i < npts; ++i) {
// cv::Vec3f point3d((float) points3d_estimated(0, i),
// (float) points3d_estimated(1, i),
// (float) points3d_estimated(2, i));
// point_cloud.push_back(point3d);
// }
// // Create a 3D window
// viz::Viz3d myWindow("Coordinate Frame");
// /// Add coordinate axes
// myWindow.showWidget("Coordinate Widget", viz::WCoordinateSystem());
// viz::WCloud cloud_widget(point_cloud, viz::Color::green());
// myWindow.showWidget("cloud", cloud_widget);
// myWindow.spin();
// return 0;
//}
| [
"cqcy3210@gmail.com"
] | cqcy3210@gmail.com |
93db95eab0a9772de90e5592cabfd834ddc5d4d1 | ad96f75c43216c3b137fe5e9ff370fb139adb77e | /src/blockchain/BlockChain.cpp | 3847d08238312f06d4c1796794cf6f008816f22f | [] | no_license | Realitian/Blockchain | 70e2b237782059b4a5e689325eea3ca39f2ec762 | 1362c65cfa32ae9c83c1cd280b5d6a602e757705 | refs/heads/master | 2020-03-07T08:10:42.379000 | 2016-12-17T14:35:14 | 2016-12-17T14:35:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,345 | cpp | #include "../../include/blockchain/BlockChain.h"
using Cuple = std::tuple<int, string, Block>;
BlockChain::BlockChain() :
blocks([](const Cuple& x, const Cuple& y)
{
if ((std::get<0>(x) > std::get<0>(y)))
return true;
if (std::get<0>(x) == std::get<0>(y))
{
return (std::get<1>(x) > std::get<1>(y));
}
return false;
}),
orphans([](const Cuple& x, const Cuple& y)
{
return (std::get<0>(x) < std::get<0>(y) && std::get<2>(x).get_Header().get_Time() < std::get<2>(y).get_Header().get_Time());
}),
leadingBlock(blocks.begin())
{
}
BlockChain::~BlockChain()
{
}
/*!
*
* \brief Try to add to the blockchain a new block. Update the internal structure of the blockchain by switching to the main branch if necessary
*
* \param : bloc : the bloc to add. As the BlockChain is not connected to the database, there is no check if all the transactions in the block are correct, all the transactions should have been verified before
* \return :int : return a code corresponding to the status of the add
*/
int BlockChain::push_back(const Block& bloc)
{
// If the block is not valid
if (!bloc.isValid())
return BlockChain::ERROR_BLOCK_INVALID;
if (blocks.size() == 0)
{
try {
blocks.insert(Cuple(bloc.get_Header().get_NumeroBloc(), bloc.get_BlockHash(), bloc));
leadingBlock = blocks.begin();
}
catch (const std::exception& e)
{
std::cerr << "An incorrect block has failed to be insert into the BlockChain chain : " << e.what();
};
return BlockChain::FIRS_BLOCK_ADDED;
}
// If the block is not fully compose !
if (bloc.get_BlockHash() == "")
{
try {
orphans.insert(Cuple(bloc.get_Header().get_NumeroBloc(), bloc.get_BlockHash(), bloc));
}
catch (const std::exception& e)
{
std::cerr << "An incorrect block has failed to be insert into the Orphans chain : " << e.what();
};
return BlockChain::PREVIOUS_BLOCK_UNKNOWN;
}
// Pointer to the last element
auto block_ite = blocks.begin();
for (; block_ite != blocks.end(); block_ite++)
{
// If we find the parent
if (std::get<1>(*block_ite) == bloc.get_PreviousBlockHash())
{
try {
Cuple newBloc = Cuple(bloc.get_Header().get_NumeroBloc(), bloc.get_BlockHash(), bloc);
// inserting into the BlockChain
blocks.insert(newBloc);
// modify the leadingBlock if necessary
if (bloc.get_Header().get_NumeroBloc() > std::get<2>(*leadingBlock).get_Header().get_NumeroBloc()) {
for (std::set<Cuple>::iterator x = blocks.begin(); x != blocks.end(); x++)
{
if (std::get<2>(*x) == std::get<2>(newBloc))
{
leadingBlock = x;
break;
}
}
}
return BlockChain::INSERT_NEW_BLOCK;
}
catch (const std::exception& e)
{
std::cerr << "An incorrect block has failed to be insert into the Block chain : " << e.what();
return BlockChain::UNKNOWN_ERROR_WHILE_ADDIND;
};
}
}
/*!< If a parent has not been found. */
if (!(block_ite != blocks.end()))
{
// add it the orphans set !
try {
orphans.insert(Cuple(bloc.get_Header().get_NumeroBloc(), bloc.get_BlockHash(), bloc));
}
catch (const std::exception& e)
{
std::cerr << "An incorrect block has failed to be insert into the Orphans chain : " << e.what();
};
return BlockChain::PREVIOUS_BLOCK_UNKNOWN;
}
return BlockChain::UNKNOWN_ERROR_WHILE_ADDIND;
}
//!
//! \brief Print the Blockchain
//!
//! \return :void
//!
void BlockChain::print(std::ostream& os) const
{
for (const auto& exp : blocks)
{
os << std::get<0>(exp) << " " << std::get<1>(exp) << std::endl
<< std::endl;
}
}
//!
//! \brief Find if a transaction is in the BlockChain
//! \deprecated As Database and Blockchain should be connected, you should check if the transaction is valid directly in the DataBase with
//! \param : trans
//! \return :bool : Return a bool if the transaction is in the BlockChain
//!
bool BlockChain::find(const Transaction& trans) const
{
if (std::any_of(blocks.rbegin(), blocks.rend(), [&trans](const Cuple& bloc) {
if (std::get<2>(bloc).get_BlockHash() == Constante::FIRST_BLOCK_HASH) // TODO for the first Block
return false;
return std::get<2>(bloc).containsTransactions(trans);
}))
return true;
else
return false;
}
//!
//! \brief Clear the blockchain by keeping only the node that are in the main chain.
//! Keep all block that are close to the leading Block. The number of Block to keep can be set in Constante.h
//!
//! \return :void
//!
void BlockChain::clear(std::ostream& os)
{
// Deleting ancient orphans that are no more useful
while (orphans.size() > Constante::MAX_SIZE_ORPHANS)
{
auto it = orphans.begin();
push_back(std::get<2>(*it)); // Try a last time...
orphans.erase(it);
}
// If the blockChain is too small, no need to continue
if (std::get<2>(*blocks.begin()).get_Header().get_NumeroBloc() < Constante::DEPTH_DELETION)
return;
auto block_ite = leadingBlock;
// The Hash of the previous Block
string previous_Block_Hash = std::get<2>(*leadingBlock).get_PreviousBlockHash();
os << "Last hash : " << previous_Block_Hash << std::endl;
while (block_ite != blocks.end())
{
// If it is to early to delete the bloc
if (std::get<2>(*block_ite).get_Header().get_NumeroBloc() > std::get<2>(*leadingBlock).get_Header().get_NumeroBloc() - Constante::DEPTH_DELETION) {
os << "To early to delete " << std::get<0>(*block_ite) << std::endl;
// If the block is in the main chain, update the local variable previous_Block_Hash
if (std::get<2>(*block_ite).get_BlockHash() == previous_Block_Hash)
{
previous_Block_Hash = std::get<2>(*block_ite).get_PreviousBlockHash();
}
block_ite++;
}
// If the block are really far, and there should only be the main BlockChain with confirmed Block
else
{
// If it is in the main chain
if (std::get<2>(*block_ite).get_BlockHash() == previous_Block_Hash)
{
os << "No deletion : " << std::get<0>(*block_ite) << std::endl;
previous_Block_Hash = std::get<2>(*block_ite).get_PreviousBlockHash();
block_ite++;
}
// else delete it
else
{
os << "No too early but deletion : " << std::get<0>(*block_ite) << std::endl;
block_ite = blocks.erase(block_ite);
}
}
}
}
/*!
*
* \brief Return the size of the blockchain
*
* \return :size_t : The size of the BlockChain
*/
size_t BlockChain::size() const
{
return blocks.size() + orphans.size();
}
/*!
*
* \brief return a const reference to the "Block" (actually the tuple) at the head of the main chain
*
* \return :const Cuple : return the Block at the top of the BlockChain, the one that has higher number.
*/
const Cuple BlockChain::get_LeadingBlock() const
{
return *leadingBlock;
}
/*!
*
* \brief Given a Block b, it gives back the previous Block in the BlockChain referenced in the header of b as his previous
*
* \param : cuple : A tuples composed of the block, his hash and his number
* \return :Cuple : A tuples composed of the block, his hash and his number for the previous node
*/
Cuple BlockChain::get_PreviousBlock(const Cuple& cuple) const
{
// Get the previous hash
string PreviousHash = std::get<2>(cuple).get_PreviousBlockHash();
if (PreviousHash == "")
return cuple;
std::set<Cuple>::iterator iter = blocks.find(cuple);
while (iter != blocks.end() && std::get<1>(*iter) != PreviousHash)
{
iter++;
}
return *iter;
} | [
"louis.franc@insa-rouen.fr"
] | louis.franc@insa-rouen.fr |
5d12485301120e24825d30ba1b7ff246ea19d4bc | 051e45f74b0e88c6b3dfa1308695fa71824e85af | /src/displaygreeting.cpp | c313bffc49fdf9187641f924b23ec42b35c6ba26 | [] | no_license | MvGaster/esp-gift | 62acc8ee7c1d56b9fc33562165c6b98fbc5934bf | 8e586aeba97c4a8b56239107b026d54b43462aec | refs/heads/master | 2023-01-31T01:53:09.734114 | 2020-12-15T21:26:22 | 2020-12-15T21:26:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,970 | cpp | #include <Arduino.h>
#define FlashFS LittleFS
#include <SPI.h>
#include <TFT_eSPI.h> // Hardware-specific library
#include "displaygreeting.h"
#include <AnimatedGIF.h>
#include "mc-white.h"
#define DISPLAY_WIDTH 320
#define DISPLAY_HEIGHT 240
#define BUFFER_SIZE 320 // Optimum is >= GIF width or integral division of width
#define tft (*_tft)
uint16_t usTemp[1][BUFFER_SIZE]; // Global to support DMA use
bool dmaBuf = 0;
uint16_t test = 3444;
AnimatedGIF _animGif;
TFT_eSPI *DisplayGreeting::_tft;
Scheduler *DisplayGreeting::_scheduler;
Task *DisplayGreeting::_task;
boolean DisplayGreeting::_showGifInProgress;
DisplayGreeting::DisplayGreeting(Scheduler *scheduler, TFT_eSPI *aTft)
{
DisplayGreeting::_scheduler = scheduler;
DisplayGreeting::_tft = aTft;
}
void DisplayGreeting::begin()
{
// Serial.printf("Test value: %u", test);
Serial.println(F("Starting DisplayGreeting"));
// TFT_eSPI tft = *_tft;
tft.fillScreen(TFT_BLACK);
_animGif.begin(BIG_ENDIAN_PIXELS);
_showGifInProgress = false;
_task = new Task(111, TASK_FOREVER, _taskMethod, _scheduler, true, NULL, _onDisable);
}
void DisplayGreeting::end()
{
// TFT_eSPI tft = *_tft;
Serial.println(F("end() called for display greeting"));
_task->disable();
if (_showGifInProgress)
{
_animGif.close();
tft.endWrite();
_showGifInProgress = false;
}
}
void DisplayGreeting::_onDisable()
{
Serial.println(F("onDisable() called for display greeting"));
end();
}
void DisplayGreeting::_taskMethod()
{
// TFT_eSPI tft = *_tft;
if (_showGifInProgress)
{
if (!_animGif.playFrame(false, NULL))
{
_animGif.close();
tft.endWrite();
_showGifInProgress = false;
}
}
else
{
_animGif.open((uint8_t *)mc_gif, sizeof(mc_gif), _drawGif);
// Serial.printf("Successfully opened GIF; Canvas size = %d x %d\n", _animGif.getCanvasWidth(), _animGif.getCanvasHeight());
tft.startWrite();
_showGifInProgress = true;
}
}
// Draw a line of image directly on the LCD
void DisplayGreeting::_drawGif(GIFDRAW *pDraw)
{
// TFT_eSPI tft = *_tft;
uint8_t *s;
uint16_t *d, *usPalette;
int x, y, iWidth, iCount;
// Displ;ay bounds chech and cropping
iWidth = pDraw->iWidth;
if (iWidth + pDraw->iX > DISPLAY_WIDTH)
iWidth = DISPLAY_WIDTH - pDraw->iX;
usPalette = pDraw->pPalette;
y = pDraw->iY + pDraw->y; // current line
if (y >= DISPLAY_HEIGHT || pDraw->iX >= DISPLAY_WIDTH || iWidth < 1)
return;
// Old image disposal
s = pDraw->pPixels;
if (pDraw->ucDisposalMethod == 2) // restore to background color
{
for (x = 0; x < iWidth; x++)
{
if (s[x] == pDraw->ucTransparent)
s[x] = pDraw->ucBackground;
}
pDraw->ucHasTransparency = 0;
}
// Apply the new pixels to the main image
if (pDraw->ucHasTransparency) // if transparency used
{
uint8_t *pEnd, c, ucTransparent = pDraw->ucTransparent;
pEnd = s + iWidth;
x = 0;
iCount = 0; // count non-transparent pixels
while (x < iWidth)
{
c = ucTransparent - 1;
d = &usTemp[0][0];
while (c != ucTransparent && s < pEnd && iCount < BUFFER_SIZE)
{
c = *s++;
if (c == ucTransparent) // done, stop
{
s--; // back up to treat it like transparent
}
else // opaque
{
*d++ = usPalette[c];
iCount++;
}
} // while looking for opaque pixels
if (iCount) // any opaque pixels?
{
// DMA would degrtade performance here due to short line segments
tft.setAddrWindow(pDraw->iX + x, y, iCount, 1);
tft.pushPixels(usTemp, iCount);
x += iCount;
iCount = 0;
}
// no, look for a run of transparent pixels
c = ucTransparent;
while (c == ucTransparent && s < pEnd)
{
c = *s++;
if (c == ucTransparent)
x++;
else
s--;
}
}
}
else
{
s = pDraw->pPixels;
// Unroll the first pass to boost DMA performance
// Translate the 8-bit pixels through the RGB565 palette (already byte reversed)
if (iWidth <= BUFFER_SIZE)
for (iCount = 0; iCount < iWidth; iCount++)
usTemp[dmaBuf][iCount] = usPalette[*s++];
else
for (iCount = 0; iCount < BUFFER_SIZE; iCount++)
usTemp[dmaBuf][iCount] = usPalette[*s++];
#ifdef USE_DMA // 71.6 fps (ST7796 84.5 fps)
tft.dmaWait();
tft.setAddrWindow(pDraw->iX, y, iWidth, 1);
tft.pushPixelsDMA(&usTemp[dmaBuf][0], iCount);
dmaBuf = !dmaBuf;
#else // 57.0 fps
tft.setAddrWindow(pDraw->iX, y, iWidth, 1);
tft.pushPixels(&usTemp[0][0], iCount);
#endif
iWidth -= iCount;
// Loop if pixel buffer smaller than width
while (iWidth > 0)
{
// Translate the 8-bit pixels through the RGB565 palette (already byte reversed)
if (iWidth <= BUFFER_SIZE)
for (iCount = 0; iCount < iWidth; iCount++)
usTemp[dmaBuf][iCount] = usPalette[*s++];
else
for (iCount = 0; iCount < BUFFER_SIZE; iCount++)
usTemp[dmaBuf][iCount] = usPalette[*s++];
#ifdef USE_DMA
tft.dmaWait();
tft.pushPixelsDMA(&usTemp[dmaBuf][0], iCount);
dmaBuf = !dmaBuf;
#else
tft.pushPixels(&usTemp[0][0], iCount);
#endif
iWidth -= iCount;
}
}
} /* GIFDraw() */
| [
"fenno@dekuiper.com"
] | fenno@dekuiper.com |
1ee91556c50974d44430a0968470a334078d71b9 | 29d542a87293372f43bc05df6f979e54431c0699 | /ABM-Office-System-cpp/MainFrm.cpp | 967f9f86c624072bd9d8e5d732450e62ac021d47 | [] | no_license | abmadmin/ABM-Office-System-Cpp | f2946de5118a7ff13b747aa01a9a27a09636414f | 094b666fc2e106cbf5465dfc60848596490f7056 | refs/heads/master | 2021-01-22T10:17:56.522682 | 2017-11-16T00:11:17 | 2017-11-16T00:11:17 | 26,842,131 | 0 | 0 | null | 2017-11-16T00:11:18 | 2014-11-19T03:12:48 | C++ | UTF-8 | C++ | false | false | 3,925 | cpp |
// MainFrm.cpp : implementation of the CMainFrame class
//
#include "stdafx.h"
#include "ABM-Office-System-cpp.h"
#include "MainFrm.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CMainFrame
IMPLEMENT_DYNAMIC(CMainFrame, CMDIFrameWnd)
BEGIN_MESSAGE_MAP(CMainFrame, CMDIFrameWnd)
ON_WM_CREATE()
ON_COMMAND_RANGE(ID_VIEW_APPLOOK_WIN_2000, ID_VIEW_APPLOOK_WINDOWS_7, &CMainFrame::OnApplicationLook)
ON_UPDATE_COMMAND_UI_RANGE(ID_VIEW_APPLOOK_WIN_2000, ID_VIEW_APPLOOK_WINDOWS_7, &CMainFrame::OnUpdateApplicationLook)
END_MESSAGE_MAP()
// CMainFrame construction/destruction
CMainFrame::CMainFrame()
{
// TODO: add member initialization code here
}
CMainFrame::~CMainFrame()
{
}
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CMDIFrameWnd::OnCreate(lpCreateStruct) == -1)
return -1;
if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
!m_wndToolBar.LoadToolBar(IDR_MAINFRAME))
{
TRACE0("Failed to create toolbar\n");
return -1; // fail to create
}
// TODO: Delete these three lines if you don't want the toolbar to be dockable
m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
EnableDocking(CBRS_ALIGN_ANY);
DockControlBar(&m_wndToolBar);
return 0;
}
BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
if( !CMDIFrameWnd::PreCreateWindow(cs) )
return FALSE;
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return TRUE;
}
// CMainFrame diagnostics
#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
CMDIFrameWnd::AssertValid();
}
void CMainFrame::Dump(CDumpContext& dc) const
{
CMDIFrameWnd::Dump(dc);
}
#endif //_DEBUG
// CMainFrame message handlers
void CMainFrame::OnApplicationLook(UINT id)
{
CWaitCursor wait;
theApp.m_nAppLook = id;
switch (theApp.m_nAppLook)
{
case ID_VIEW_APPLOOK_WIN_2000:
CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManager));
break;
case ID_VIEW_APPLOOK_OFF_XP:
CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerOfficeXP));
break;
case ID_VIEW_APPLOOK_WIN_XP:
CMFCVisualManagerWindows::m_b3DTabsXPTheme = TRUE;
CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows));
break;
case ID_VIEW_APPLOOK_OFF_2003:
CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerOffice2003));
CDockingManager::SetDockingMode(DT_SMART);
break;
case ID_VIEW_APPLOOK_VS_2005:
CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerVS2005));
CDockingManager::SetDockingMode(DT_SMART);
break;
case ID_VIEW_APPLOOK_VS_2008:
CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerVS2008));
CDockingManager::SetDockingMode(DT_SMART);
break;
case ID_VIEW_APPLOOK_WINDOWS_7:
CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows7));
CDockingManager::SetDockingMode(DT_SMART);
break;
default:
switch (theApp.m_nAppLook)
{
case ID_VIEW_APPLOOK_OFF_2007_BLUE:
CMFCVisualManagerOffice2007::SetStyle(CMFCVisualManagerOffice2007::Office2007_LunaBlue);
break;
case ID_VIEW_APPLOOK_OFF_2007_BLACK:
CMFCVisualManagerOffice2007::SetStyle(CMFCVisualManagerOffice2007::Office2007_ObsidianBlack);
break;
case ID_VIEW_APPLOOK_OFF_2007_SILVER:
CMFCVisualManagerOffice2007::SetStyle(CMFCVisualManagerOffice2007::Office2007_Silver);
break;
case ID_VIEW_APPLOOK_OFF_2007_AQUA:
CMFCVisualManagerOffice2007::SetStyle(CMFCVisualManagerOffice2007::Office2007_Aqua);
break;
}
CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerOffice2007));
CDockingManager::SetDockingMode(DT_SMART);
}
RedrawWindow(NULL, NULL, RDW_ALLCHILDREN | RDW_INVALIDATE | RDW_UPDATENOW | RDW_FRAME | RDW_ERASE);
}
void CMainFrame::OnUpdateApplicationLook(CCmdUI* pCmdUI)
{
pCmdUI->SetRadio(theApp.m_nAppLook == pCmdUI->m_nID);
}
| [
"brisbanemission@outlook.com"
] | brisbanemission@outlook.com |
3d5dbe8b392d630dd60e12ed7f5ef915d553ae42 | d13384eb8025ba0c0830fabec28104813b5a474d | /RayTracer/Point3.h | d38b5a0e79d6a5123a830f6aebc02d649592af2c | [] | no_license | devgoose/RayTracer | f61fcd04f027080ad5cdc17c5705e310ab9aa2e1 | d9b369047aa910057fd5065079aebec0c965cbab | refs/heads/main | 2023-02-14T17:09:10.542168 | 2021-01-17T10:05:25 | 2021-01-17T10:05:25 | 308,991,187 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,278 | h | #pragma once
#include "Vector3.h"
/**
* Holds a point in 3D space.
*/
class Point3
{
private:
float x;
float y;
float z;
public:
/**
* Default constructor sets point at the origin.
*/
Point3() {
x = 0;
y = 0;
z = 0;
}
Point3(float x_, float y_, float z_) {
x = x_;
y = y_;
z = z_;
}
Point3(const Point3& p2) {
x = p2.x;
y = p2.y;
z = p2.z;
}
float getX() { return x; }
float getY() { return y; }
float getZ() { return z; }
void setX(float x_) { x = x_; }
void setY(float y_) { y = y_; }
void setZ(float z_) { z = z_; }
/**
* Overloaded addition operator. Adds a point to a vector.
*
* @param v Vector
*
* @return new Point object that is the sum
*/
Point3 operator+(const Vector3& v);
/**
* Overloaded subtraction operator.
*
* @param v Vector
*
* @return new Point object that is the difference
*/
Point3 operator-(const Vector3& v);
/**
* Overloaded subtraction operator.
*
* @param p point
*
* @return new Vector object that points from one point to the other
*/
Vector3 operator-(const Point3& p) const;
/**
* @param p
*
* @return distance from this to p
*/
float distance(const Point3& p) const;
};
| [
"walte735@umn.edu"
] | walte735@umn.edu |
bf2a4905cf92e205ef78802faecc07b590251033 | 37867f639363ab2f188028dc158b483b6e6b81f3 | /Src/Logic/Entity/Components/DamageTrap.cpp | e848a3e5f058b2e8e47ba5020aaca7665f4a8b1a | [] | no_license | ailuoxz/BadPrincess-Game | 704143bcafe1205a2ccdd7dbd68ed284c6fa1d76 | 47caae1a03fdfe8058260e44add25fd8e89f99c3 | refs/heads/master | 2021-12-14T15:13:50.974644 | 2017-05-04T16:31:22 | 2017-05-04T16:31:22 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 3,877 | cpp | /**
@file DamageTrap.cpp
Implementation of DamageTrap component
@see Logic::IComponent
@author Rayco Sánchez García
@date February, 2015
*/
#include "DamageTrap.h"
#include "Logic/GraphicsMessages.h"
#include "Logic/CombatMessages.h"
#include "Logic/RangerMessages.h"
#include "Logic/PhysicMessages.h"
#include "Logic/AudioMessages.h"
#include "Logic/Entity/Entity.h"
#include "Logic/Maps/EntityFactory.h"
#include "Logic/Maps/Map.h"
#include "Map/MapEntity.h"
#include "Physics/Server.h"
#include "Physics/PhysicPerceptionManager.h"
#include "GUI/Server.h"
#include "GUI/MinimapController.h"
namespace Logic
{
IMP_FACTORY(CDamageTrap);
const Physics::CollisionGroup PHYSIC_ENEMY_FILTER[]={Physics::CollisionGroup::eEnemy,Physics::CollisionGroup::eUntargetable};
//---------------------------------------------------------
CDamageTrap::~CDamageTrap() {}
//---------------------------------------------------------
bool CDamageTrap::spawn(CEntity *entity, CMap *map, const Map::CEntity *entityInfo)
{
if(!IComponent::spawn(entity,map,entityInfo))
return false;
assert(entityInfo->hasAttribute("trapDamage") && "Atributo de daño no especificado para el componente trampa");
trapDamage = entityInfo->getIntAttribute("trapDamage");
assert(entityInfo->hasAttribute("radiusOfEffect") && "Atributo de radio de efecto no especificado para el componente trampa");
radiusOfEffect = entityInfo->getFloatAttribute("radiusOfEffect");
return true;
}
void CDamageTrap::awake()
{
trapOwner=nullptr;
activated=false;
timeToDestroy=500;
}
//---------------------------------------------------------
void CDamageTrap::tick(unsigned int msecs)
{
IComponent::tick(msecs);
if (activated)
{
timeToDestroy -= msecs;
if (timeToDestroy <= 0)
Logic::CEntityFactory::getSingletonPtr()->deferredDeleteEntity(_entity);
}
}
//---------------------------------------------------------
bool CDamageTrap::acceptN(const std::shared_ptr<NMessage> &message)
{
return (message->type.compare("OnTriggerEnter") == 0) || (message->type.compare("SetOwner") == 0);
}
//---------------------------------------------------------
void CDamageTrap::processN(const std::shared_ptr<NMessage> &message)
{
if (message->type.compare("SetOwner") == 0)
trapOwner = std::static_pointer_cast<SetOwner>(message)->owner;
else if (!activated)
{
auto onTriggerEnter = std::static_pointer_cast<OnTriggerEnter>(message);
if (onTriggerEnter->collisionEntity->isEnemy())
{
GUI::CServer::getSingletonPtr()->getMinimapController()->addMinimapEvent(_entity->getName(),GUI::EventType::trap,_entity->getPosition());
std::list<Logic::CEntity*>* enemiesInRadiusOfEffect = Physics::CServer::getSingletonPtr()->getPhysicPerceptionManager()->overlapQueries(_entity->getPosition(),
radiusOfEffect, &std::vector<Physics::CollisionGroup> (PHYSIC_ENEMY_FILTER, PHYSIC_ENEMY_FILTER + sizeof(PHYSIC_ENEMY_FILTER) / sizeof(PHYSIC_ENEMY_FILTER[0])));
auto damageMessage = std::make_shared<DamageMessage>();
damageMessage->damage = trapDamage;
for (std::list<Logic::CEntity*>::iterator it = enemiesInRadiusOfEffect->begin(); it != enemiesInRadiusOfEffect->end(); ++it)
(*it)->emitMessageN(damageMessage);
delete enemiesInRadiusOfEffect;
auto trapDestroyedMessage = std::make_shared<TrapDestroyed>();
trapDestroyedMessage->trapType = _entity->getType();
trapOwner->emitMessageN(trapDestroyedMessage);
auto playParticle = std::make_shared<PlayParticle>();
playParticle->particleName = "explosion";
_entity->emitMessageN(playParticle);
_entity->deactivate("CGraphics");
auto playAudioMessage = std::make_shared<PlayAudio>();
playAudioMessage->eventName = "default";
_entity->emitMessageN(playAudioMessage);
activated = true;
}
}
}
} // namespace Logic
| [
"raycosanchezgarcia@gmail.com"
] | raycosanchezgarcia@gmail.com |
c760017a97b26adf2592b0728f0ad941a45e2731 | 80ae6fa40003ac2cfdd1f36a9ec5f7fb2b4b07f5 | /devel/include/grid_map_msgs/ProcessFileRequest.h | 6e9df4de2a73ce2dc50e736504db0b4e7598accc | [] | no_license | Blasterbotica/RobotCode2017 | aa91fb57c46829d486db76e73801b44d980d4525 | 49672b2a6c5c079a8e437a28d053792911e77e51 | refs/heads/master | 2021-01-20T14:18:59.189988 | 2017-02-22T02:19:44 | 2017-02-22T02:19:44 | 82,749,817 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,482 | h | // Generated by gencpp from file grid_map_msgs/ProcessFileRequest.msg
// DO NOT EDIT!
#ifndef GRID_MAP_MSGS_MESSAGE_PROCESSFILEREQUEST_H
#define GRID_MAP_MSGS_MESSAGE_PROCESSFILEREQUEST_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
namespace grid_map_msgs
{
template <class ContainerAllocator>
struct ProcessFileRequest_
{
typedef ProcessFileRequest_<ContainerAllocator> Type;
ProcessFileRequest_()
: file_path() {
}
ProcessFileRequest_(const ContainerAllocator& _alloc)
: file_path(_alloc) {
(void)_alloc;
}
typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _file_path_type;
_file_path_type file_path;
typedef boost::shared_ptr< ::grid_map_msgs::ProcessFileRequest_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::grid_map_msgs::ProcessFileRequest_<ContainerAllocator> const> ConstPtr;
}; // struct ProcessFileRequest_
typedef ::grid_map_msgs::ProcessFileRequest_<std::allocator<void> > ProcessFileRequest;
typedef boost::shared_ptr< ::grid_map_msgs::ProcessFileRequest > ProcessFileRequestPtr;
typedef boost::shared_ptr< ::grid_map_msgs::ProcessFileRequest const> ProcessFileRequestConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::grid_map_msgs::ProcessFileRequest_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::grid_map_msgs::ProcessFileRequest_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace grid_map_msgs
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False}
// {'grid_map_msgs': ['/home/namwob44/new_ws/src/grid_map/grid_map_msgs/msg'], 'std_msgs': ['/opt/ros/indigo/share/std_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/indigo/share/geometry_msgs/cmake/../msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::grid_map_msgs::ProcessFileRequest_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::grid_map_msgs::ProcessFileRequest_<ContainerAllocator> const>
: FalseType
{ };
template <class ContainerAllocator>
struct IsMessage< ::grid_map_msgs::ProcessFileRequest_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::grid_map_msgs::ProcessFileRequest_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::grid_map_msgs::ProcessFileRequest_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::grid_map_msgs::ProcessFileRequest_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::grid_map_msgs::ProcessFileRequest_<ContainerAllocator> >
{
static const char* value()
{
return "a1f82596372c52a517e1fe32d1e998e8";
}
static const char* value(const ::grid_map_msgs::ProcessFileRequest_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0xa1f82596372c52a5ULL;
static const uint64_t static_value2 = 0x17e1fe32d1e998e8ULL;
};
template<class ContainerAllocator>
struct DataType< ::grid_map_msgs::ProcessFileRequest_<ContainerAllocator> >
{
static const char* value()
{
return "grid_map_msgs/ProcessFileRequest";
}
static const char* value(const ::grid_map_msgs::ProcessFileRequest_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::grid_map_msgs::ProcessFileRequest_<ContainerAllocator> >
{
static const char* value()
{
return "\n\
string file_path\n\
\n\
";
}
static const char* value(const ::grid_map_msgs::ProcessFileRequest_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::grid_map_msgs::ProcessFileRequest_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.file_path);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct ProcessFileRequest_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::grid_map_msgs::ProcessFileRequest_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::grid_map_msgs::ProcessFileRequest_<ContainerAllocator>& v)
{
s << indent << "file_path: ";
Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.file_path);
}
};
} // namespace message_operations
} // namespace ros
#endif // GRID_MAP_MSGS_MESSAGE_PROCESSFILEREQUEST_H
| [
"andy.p@comcast.net"
] | andy.p@comcast.net |
73ad81105d2f6368ab989adf20c9018c352bf49f | 454e927a0131d4a94ec60341593c09da204b7024 | /main.cpp | 90a26323e614ffb6a73586b6921d3b641aa95351 | [] | no_license | mysliwy112/Decypher | fdbb8c91b85fd898acb159caa3dc73012325c3d6 | ad722729b594484700e0e2a660218d826364b9d1 | refs/heads/master | 2021-05-10T22:58:16.895733 | 2018-01-20T19:38:40 | 2018-01-20T19:38:40 | 118,271,982 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,283 | cpp | #include <iostream>
#include <conio.h>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
string file;
string dup=".dup";
bool h=0;
int i=0;
int mini=1;
int reset;
char w;
if(argc==2){
ifstream from;
ofstream to;
from.open(argv[1]);
to.open((argv[1]+dup).c_str());
getline(from,file);
string filer="{<C:";
filer=filer+file[4]+">}";
if(file==filer){
reset=file[4]-48;
}
while(!from.eof()){
getline(from,file);
i=0;
while(i<file.size()){
if(file.compare(i, 3,"<E>")==0){
to<<endl;
i+=2;
}else{
if(h==0){
w=file[i]-mini;
}else{
w=file[i]+mini;
mini++;
}
to<<w;
h=!h;
if(mini>reset/2)
mini=1;
}
i++;
}
}
to.close();
}else{
cout<<"No file"<<endl;
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
d4ce33d8c80d7095bdd8f3ccdf9f7ad5d497634c | ac302767a37f8b4c621130c63b73467c78f958a7 | /test/sequence_player_test.cpp | 55b0d815300005f1b12e242c431443014bf259eb | [] | no_license | jimm/mrmkcs | b983f37bea0f8f6c8da98605a51a407b1f3b45e1 | 8c9bd5d4f5b943c671379cd329ebe8aed67bf884 | refs/heads/main | 2023-04-14T13:52:05.646896 | 2021-03-13T20:02:29 | 2021-03-13T20:02:29 | 341,645,508 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,913 | cpp | #include "catch.hpp"
#include "test_helper.h"
#include "../src/sequence_player.h"
#define CATCH_CATEGORY "[sequence_player]"
TEST_CASE("one tick sends multiple events", CATCH_CATEGORY) {
MrMKCS *mrm = create_test_data();
Output *out1 = mrm->outputs()[0];
Output *out2 = mrm->outputs()[1];
// sanity checks
REQUIRE(out1->name == "out 1 port");
REQUIRE(out2->name == "out 2 port");
REQUIRE(out1->num_io_messages == 0);
REQUIRE(out2->num_io_messages == 0);
mrm->play_sequence(char_to_seq_number('P'));
// nothing sent yet because clock ticks not sent
REQUIRE(out1->num_io_messages == 0);
REQUIRE(out2->num_io_messages == 0);
clock_ticks(1);
REQUIRE(out1->num_io_messages == 2);
REQUIRE(out1->io_messages[0] == CLOCK_MESSAGE);
REQUIRE(out1->io_messages[1] == Pm_Message(PROGRAM_CHANGE + 0, 42, 0));
REQUIRE(out2->num_io_messages == 2);
REQUIRE(out2->io_messages[0] == CLOCK_MESSAGE);
REQUIRE(out2->io_messages[1] == Pm_Message(PROGRAM_CHANGE + 1, 99, 0));
delete mrm;
}
TEST_CASE("waits proper number of ticks", CATCH_CATEGORY) {
MrMKCS *mrm = create_test_data();
Clock &clock = mrm->clock();
Output *out1 = mrm->outputs()[0];
mrm->play_sequence(char_to_seq_number('A'));
clock_ticks(1);
REQUIRE(out1->num_io_messages == 5);
REQUIRE(out1->io_messages[0] == CLOCK_MESSAGE);
REQUIRE(out1->io_messages[1] == Pm_Message(NOTE_ON, 64, 127));
REQUIRE(out1->io_messages[2] == Pm_Message(NOTE_ON, 68, 99));
REQUIRE(out1->io_messages[3] == Pm_Message(NOTE_ON, 71, 127));
REQUIRE(out1->io_messages[4] == Pm_Message(CONTROLLER, CC_SUSTAIN, 127));
out1->clear_io_messages();
clock_ticks(47);
REQUIRE(clock.time() == 48);
REQUIRE(out1->num_io_messages == 47);
for (int i = 0; i < 47; ++i)
REQUIRE(out1->io_messages[i] == CLOCK_MESSAGE);
out1->clear_io_messages();
clock_ticks(1);
REQUIRE(clock.time() == 49);
REQUIRE(out1->num_io_messages == 4);
REQUIRE(out1->io_messages[0] == CLOCK_MESSAGE);
REQUIRE(out1->io_messages[1] == Pm_Message(NOTE_OFF, 64, 127));
REQUIRE(out1->io_messages[2] == Pm_Message(NOTE_OFF, 68, 127));
REQUIRE(out1->io_messages[3] == Pm_Message(NOTE_OFF, 71, 64));
out1->clear_io_messages();
clock_ticks(24);
REQUIRE(out1->num_io_messages == 25);
for (int i = 0; i < 24; ++i)
REQUIRE(out1->io_messages[i] == CLOCK_MESSAGE);
REQUIRE(out1->io_messages[24] == Pm_Message(CONTROLLER, CC_SUSTAIN, 0));
delete mrm;
}
TEST_CASE("send all notes off when stopped", CATCH_CATEGORY) {
MrMKCS *mrm = create_test_data();
Output *out1 = mrm->outputs()[0];
SequencePlayer *player = mrm->play_sequence(char_to_seq_number('A'));
clock_ticks(1);
REQUIRE(out1->num_io_messages == 5);
out1->clear_io_messages();
player->stop();
REQUIRE(out1->num_io_messages == 3);
REQUIRE(out1->io_messages[0] == Pm_Message(NOTE_OFF, 64, 127));
REQUIRE(out1->io_messages[1] == Pm_Message(NOTE_OFF, 68, 127));
REQUIRE(out1->io_messages[2] == Pm_Message(NOTE_OFF, 71, 64));
delete mrm;
}
// This test also ensures that a sequence player that is stopped also stops
// all of its sub-sequence players.
TEST_CASE("parent transposes notes in sequence, including stop note offs", CATCH_CATEGORY) {
MrMKCS *mrm = create_test_data();
Output *out1 = mrm->outputs()[0];
SequencePlayer *player = mrm->play_sequence(char_to_seq_number('X'));
clock_ticks(1);
REQUIRE(out1->num_io_messages == 5);
REQUIRE(out1->io_messages[0] == CLOCK_MESSAGE);
REQUIRE(out1->io_messages[1] == Pm_Message(NOTE_ON, 64 + 12, 127));
REQUIRE(out1->io_messages[2] == Pm_Message(NOTE_ON, 68 + 12, 99));
REQUIRE(out1->io_messages[3] == Pm_Message(NOTE_ON, 71 + 12, 127));
REQUIRE(out1->io_messages[4] == Pm_Message(CONTROLLER, CC_SUSTAIN, 127));
out1->clear_io_messages();
player->stop();
REQUIRE(out1->num_io_messages == 3);
REQUIRE(out1->io_messages[0] == Pm_Message(NOTE_OFF, 64 + 12, 127));
REQUIRE(out1->io_messages[1] == Pm_Message(NOTE_OFF, 68 + 12, 127));
REQUIRE(out1->io_messages[2] == Pm_Message(NOTE_OFF, 71 + 12, 64));
delete mrm;
}
TEST_CASE("transpose note offs sent on stop", CATCH_CATEGORY) {
MrMKCS *mrm = create_test_data();
Output *out1 = mrm->outputs()[0];
int xpose = 12;
SequencePlayer *player = mrm->play_sequence(char_to_seq_number('A'));
clock_ticks(1);
REQUIRE(out1->num_io_messages == 5);
out1->clear_io_messages();
player->stop();
REQUIRE(out1->num_io_messages == 3);
REQUIRE(out1->io_messages[0] == Pm_Message(NOTE_OFF, 64, 127));
REQUIRE(out1->io_messages[1] == Pm_Message(NOTE_OFF, 68, 127));
REQUIRE(out1->io_messages[2] == Pm_Message(NOTE_OFF, 71, 64));
delete mrm;
}
TEST_CASE("play whole song with waits", CATCH_CATEGORY) {
MrMKCS *mrm = create_test_data();
Output *out1 = mrm->outputs()[0];
Output *out2 = mrm->outputs()[1];
SequencePlayer *player = mrm->play_sequence(char_to_seq_number('S'));
delete mrm;
}
| [
"jim.menard@warbyparker.com"
] | jim.menard@warbyparker.com |
4f169d7cc2f5c287f55d4708d55dfaf766a204e8 | 7a11814cb2d966035582e0334f184d4786a4f79d | /rocksdb-cloud/include/rocksdb/options.h | c6c71ae63cb7e03e3d45dbb53aa00018b8c799eb | [
"Apache-2.0",
"GPL-2.0-only",
"BSD-3-Clause"
] | permissive | naivewong/YCSB-C | f6e1efadfa69688b1a7311b5ce18fe6b4ca4e9a8 | 9a603e95083950278ed0972e2ee889edf77e4148 | refs/heads/master | 2022-12-16T16:16:00.106547 | 2020-09-13T12:52:50 | 2020-09-13T12:52:50 | 257,572,961 | 0 | 0 | Apache-2.0 | 2020-04-21T11:26:35 | 2020-04-21T11:26:34 | null | UTF-8 | C++ | false | false | 68,591 | h | // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under both the GPLv2 (found in the
// COPYING file in the root directory) and Apache 2.0 License
// (found in the LICENSE.Apache file in the root directory).
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <limits>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include "rocksdb/advanced_options.h"
#include "rocksdb/comparator.h"
#include "rocksdb/env.h"
#include "rocksdb/listener.h"
#include "rocksdb/pre_release_callback.h"
#include "rocksdb/universal_compaction.h"
#include "rocksdb/version.h"
#include "rocksdb/write_buffer_manager.h"
#ifdef max
#undef max
#endif
namespace rocksdb {
class Cache;
class CompactionFilter;
class CompactionFilterFactory;
class Comparator;
class ConcurrentTaskLimiter;
class Env;
enum InfoLogLevel : unsigned char;
class SstFileManager;
class FilterPolicy;
class Logger;
class MergeOperator;
class Snapshot;
class MemTableRepFactory;
class RateLimiter;
class Slice;
class Statistics;
class InternalKeyComparator;
class WalFilter;
// DB contents are stored in a set of blocks, each of which holds a
// sequence of key,value pairs. Each block may be compressed before
// being stored in a file. The following enum describes which
// compression method (if any) is used to compress a block.
enum CompressionType : unsigned char {
// NOTE: do not change the values of existing entries, as these are
// part of the persistent format on disk.
kNoCompression = 0x0,
kSnappyCompression = 0x1,
kZlibCompression = 0x2,
kBZip2Compression = 0x3,
kLZ4Compression = 0x4,
kLZ4HCCompression = 0x5,
kXpressCompression = 0x6,
kZSTD = 0x7,
// Only use kZSTDNotFinalCompression if you have to use ZSTD lib older than
// 0.8.0 or consider a possibility of downgrading the service or copying
// the database files to another service running with an older version of
// RocksDB that doesn't have kZSTD. Otherwise, you should use kZSTD. We will
// eventually remove the option from the public API.
kZSTDNotFinalCompression = 0x40,
// kDisableCompressionOption is used to disable some compression options.
kDisableCompressionOption = 0xff,
};
struct Options;
struct DbPath;
struct ColumnFamilyOptions : public AdvancedColumnFamilyOptions {
// The function recovers options to a previous version. Only 4.6 or later
// versions are supported.
ColumnFamilyOptions* OldDefaults(int rocksdb_major_version = 4,
int rocksdb_minor_version = 6);
// Some functions that make it easier to optimize RocksDB
// Use this if your DB is very small (like under 1GB) and you don't want to
// spend lots of memory for memtables.
// An optional cache object is passed in to be used as the block cache
ColumnFamilyOptions* OptimizeForSmallDb(
std::shared_ptr<Cache>* cache = nullptr);
// Use this if you don't need to keep the data sorted, i.e. you'll never use
// an iterator, only Put() and Get() API calls
//
// Not supported in ROCKSDB_LITE
ColumnFamilyOptions* OptimizeForPointLookup(uint64_t block_cache_size_mb);
// Default values for some parameters in ColumnFamilyOptions are not
// optimized for heavy workloads and big datasets, which means you might
// observe write stalls under some conditions. As a starting point for tuning
// RocksDB options, use the following two functions:
// * OptimizeLevelStyleCompaction -- optimizes level style compaction
// * OptimizeUniversalStyleCompaction -- optimizes universal style compaction
// Universal style compaction is focused on reducing Write Amplification
// Factor for big data sets, but increases Space Amplification. You can learn
// more about the different styles here:
// https://github.com/facebook/rocksdb/wiki/Rocksdb-Architecture-Guide
// Make sure to also call IncreaseParallelism(), which will provide the
// biggest performance gains.
// Note: we might use more memory than memtable_memory_budget during high
// write rate period
//
// OptimizeUniversalStyleCompaction is not supported in ROCKSDB_LITE
ColumnFamilyOptions* OptimizeLevelStyleCompaction(
uint64_t memtable_memory_budget = 512 * 1024 * 1024);
ColumnFamilyOptions* OptimizeUniversalStyleCompaction(
uint64_t memtable_memory_budget = 512 * 1024 * 1024);
// -------------------
// Parameters that affect behavior
// Comparator used to define the order of keys in the table.
// Default: a comparator that uses lexicographic byte-wise ordering
//
// REQUIRES: The client must ensure that the comparator supplied
// here has the same name and orders keys *exactly* the same as the
// comparator provided to previous open calls on the same DB.
const Comparator* comparator = BytewiseComparator();
// REQUIRES: The client must provide a merge operator if Merge operation
// needs to be accessed. Calling Merge on a DB without a merge operator
// would result in Status::NotSupported. The client must ensure that the
// merge operator supplied here has the same name and *exactly* the same
// semantics as the merge operator provided to previous open calls on
// the same DB. The only exception is reserved for upgrade, where a DB
// previously without a merge operator is introduced to Merge operation
// for the first time. It's necessary to specify a merge operator when
// opening the DB in this case.
// Default: nullptr
std::shared_ptr<MergeOperator> merge_operator = nullptr;
// A single CompactionFilter instance to call into during compaction.
// Allows an application to modify/delete a key-value during background
// compaction.
//
// If the client requires a new compaction filter to be used for different
// compaction runs, it can specify compaction_filter_factory instead of this
// option. The client should specify only one of the two.
// compaction_filter takes precedence over compaction_filter_factory if
// client specifies both.
//
// If multithreaded compaction is being used, the supplied CompactionFilter
// instance may be used from different threads concurrently and so should be
// thread-safe.
//
// Default: nullptr
const CompactionFilter* compaction_filter = nullptr;
// This is a factory that provides compaction filter objects which allow
// an application to modify/delete a key-value during background compaction.
//
// A new filter will be created on each compaction run. If multithreaded
// compaction is being used, each created CompactionFilter will only be used
// from a single thread and so does not need to be thread-safe.
//
// Default: nullptr
std::shared_ptr<CompactionFilterFactory> compaction_filter_factory = nullptr;
// -------------------
// Parameters that affect performance
// Amount of data to build up in memory (backed by an unsorted log
// on disk) before converting to a sorted on-disk file.
//
// Larger values increase performance, especially during bulk loads.
// Up to max_write_buffer_number write buffers may be held in memory
// at the same time,
// so you may wish to adjust this parameter to control memory usage.
// Also, a larger write buffer will result in a longer recovery time
// the next time the database is opened.
//
// Note that write_buffer_size is enforced per column family.
// See db_write_buffer_size for sharing memory across column families.
//
// Default: 64MB
//
// Dynamically changeable through SetOptions() API
size_t write_buffer_size = 64 << 20;
// Compress blocks using the specified compression algorithm.
//
// Default: kSnappyCompression, if it's supported. If snappy is not linked
// with the library, the default is kNoCompression.
//
// Typical speeds of kSnappyCompression on an Intel(R) Core(TM)2 2.4GHz:
// ~200-500MB/s compression
// ~400-800MB/s decompression
//
// Note that these speeds are significantly faster than most
// persistent storage speeds, and therefore it is typically never
// worth switching to kNoCompression. Even if the input data is
// incompressible, the kSnappyCompression implementation will
// efficiently detect that and will switch to uncompressed mode.
//
// If you do not set `compression_opts.level`, or set it to
// `CompressionOptions::kDefaultCompressionLevel`, we will attempt to pick the
// default corresponding to `compression` as follows:
//
// - kZSTD: 3
// - kZlibCompression: Z_DEFAULT_COMPRESSION (currently -1)
// - kLZ4HCCompression: 0
// - For all others, we do not specify a compression level
//
// Dynamically changeable through SetOptions() API
CompressionType compression;
// Compression algorithm that will be used for the bottommost level that
// contain files.
//
// Default: kDisableCompressionOption (Disabled). The means that the setting
// specified via Options.compression applies to the bottommost level as well.
// Default: kDisableCompressionOption (Disabled)
CompressionType bottommost_compression = kDisableCompressionOption;
// different options for compression algorithms used by bottommost_compression
// if it is enabled. To enable it, please see the definition of
// CompressionOptions.
CompressionOptions bottommost_compression_opts;
// different options for compression algorithms
CompressionOptions compression_opts;
// Number of files to trigger level-0 compaction. A value <0 means that
// level-0 compaction will not be triggered by number of files at all.
//
// Default: 4
//
// Dynamically changeable through SetOptions() API
int level0_file_num_compaction_trigger = 4;
// If non-nullptr, use the specified function to determine the
// prefixes for keys. These prefixes will be placed in the filter.
// Depending on the workload, this can reduce the number of read-IOP
// cost for scans when a prefix is passed via ReadOptions to
// db.NewIterator(). For prefix filtering to work properly,
// "prefix_extractor" and "comparator" must be such that the following
// properties hold:
//
// 1) key.starts_with(prefix(key))
// 2) Compare(prefix(key), key) <= 0.
// 3) If Compare(k1, k2) <= 0, then Compare(prefix(k1), prefix(k2)) <= 0
// 4) prefix(prefix(key)) == prefix(key)
//
// Default: nullptr
std::shared_ptr<const SliceTransform> prefix_extractor = nullptr;
// Control maximum total data size for a level.
// max_bytes_for_level_base is the max total for level-1.
// Maximum number of bytes for level L can be calculated as
// (max_bytes_for_level_base) * (max_bytes_for_level_multiplier ^ (L-1))
// For example, if max_bytes_for_level_base is 200MB, and if
// max_bytes_for_level_multiplier is 10, total data size for level-1
// will be 200MB, total file size for level-2 will be 2GB,
// and total file size for level-3 will be 20GB.
//
// Default: 256MB.
//
// Dynamically changeable through SetOptions() API
uint64_t max_bytes_for_level_base = 256 * 1048576;
// If non-zero, compactions will periodically refresh the snapshot list. The
// delay for the first refresh is snap_refresh_nanos nano seconds and
// exponentially increases afterwards. When having many short-lived snapshots,
// this option helps reducing the cpu usage of long-running compactions. The
// feature is disabled when max_subcompactions is greater than one.
//
// NOTE: This feautre is currently incompatible with RangeDeletes.
//
// Default: 0
//
// Dynamically changeable through SetOptions() API
uint64_t snap_refresh_nanos = 0;
// Disable automatic compactions. Manual compactions can still
// be issued on this column family
//
// Dynamically changeable through SetOptions() API
bool disable_auto_compactions = false;
// This is a factory that provides TableFactory objects.
// Default: a block-based table factory that provides a default
// implementation of TableBuilder and TableReader with default
// BlockBasedTableOptions.
std::shared_ptr<TableFactory> table_factory;
// A list of paths where SST files for this column family
// can be put into, with its target size. Similar to db_paths,
// newer data is placed into paths specified earlier in the
// vector while older data gradually moves to paths specified
// later in the vector.
// Note that, if a path is supplied to multiple column
// families, it would have files and total size from all
// the column families combined. User should provision for the
// total size(from all the column families) in such cases.
//
// If left empty, db_paths will be used.
// Default: empty
std::vector<DbPath> cf_paths;
// Compaction concurrent thread limiter for the column family.
// If non-nullptr, use given concurrent thread limiter to control
// the max outstanding compaction tasks. Limiter can be shared with
// multiple column families across db instances.
//
// Default: nullptr
std::shared_ptr<ConcurrentTaskLimiter> compaction_thread_limiter = nullptr;
// Create ColumnFamilyOptions with default values for all fields
ColumnFamilyOptions();
// Create ColumnFamilyOptions from Options
explicit ColumnFamilyOptions(const Options& options);
void Dump(Logger* log) const;
};
enum class WALRecoveryMode : char {
// Original levelDB recovery
// We tolerate incomplete record in trailing data on all logs
// Use case : This is legacy behavior
kTolerateCorruptedTailRecords = 0x00,
// Recover from clean shutdown
// We don't expect to find any corruption in the WAL
// Use case : This is ideal for unit tests and rare applications that
// can require high consistency guarantee
kAbsoluteConsistency = 0x01,
// Recover to point-in-time consistency (default)
// We stop the WAL playback on discovering WAL inconsistency
// Use case : Ideal for systems that have disk controller cache like
// hard disk, SSD without super capacitor that store related data
kPointInTimeRecovery = 0x02,
// Recovery after a disaster
// We ignore any corruption in the WAL and try to salvage as much data as
// possible
// Use case : Ideal for last ditch effort to recover data or systems that
// operate with low grade unrelated data
kSkipAnyCorruptedRecords = 0x03,
};
struct DbPath {
std::string path;
uint64_t target_size; // Target size of total files under the path, in byte.
DbPath() : target_size(0) {}
DbPath(const std::string& p, uint64_t t) : path(p), target_size(t) {}
};
struct DBOptions {
// The function recovers options to the option as in version 4.6.
DBOptions* OldDefaults(int rocksdb_major_version = 4,
int rocksdb_minor_version = 6);
// Some functions that make it easier to optimize RocksDB
// Use this if your DB is very small (like under 1GB) and you don't want to
// spend lots of memory for memtables.
// An optional cache object is passed in for the memory of the
// memtable to cost to
DBOptions* OptimizeForSmallDb(std::shared_ptr<Cache>* cache = nullptr);
#ifndef ROCKSDB_LITE
// By default, RocksDB uses only one background thread for flush and
// compaction. Calling this function will set it up such that total of
// `total_threads` is used. Good value for `total_threads` is the number of
// cores. You almost definitely want to call this function if your system is
// bottlenecked by RocksDB.
DBOptions* IncreaseParallelism(int total_threads = 16);
#endif // ROCKSDB_LITE
// If true, the database will be created if it is missing.
// Default: false
bool create_if_missing = false;
// If true, missing column families will be automatically created.
// Default: false
bool create_missing_column_families = false;
// If true, an error is raised if the database already exists.
// Default: false
bool error_if_exists = false;
// If true, RocksDB will aggressively check consistency of the data.
// Also, if any of the writes to the database fails (Put, Delete, Merge,
// Write), the database will switch to read-only mode and fail all other
// Write operations.
// In most cases you want this to be set to true.
// Default: true
bool paranoid_checks = true;
// Use the specified object to interact with the environment,
// e.g. to read/write files, schedule background work, etc.
// Default: Env::Default()
Env* env = Env::Default();
// Use to control write rate of flush and compaction. Flush has higher
// priority than compaction. Rate limiting is disabled if nullptr.
// If rate limiter is enabled, bytes_per_sync is set to 1MB by default.
// Default: nullptr
std::shared_ptr<RateLimiter> rate_limiter = nullptr;
// Use to track SST files and control their file deletion rate.
//
// Features:
// - Throttle the deletion rate of the SST files.
// - Keep track the total size of all SST files.
// - Set a maximum allowed space limit for SST files that when reached
// the DB wont do any further flushes or compactions and will set the
// background error.
// - Can be shared between multiple dbs.
// Limitations:
// - Only track and throttle deletes of SST files in
// first db_path (db_name if db_paths is empty).
//
// Default: nullptr
std::shared_ptr<SstFileManager> sst_file_manager = nullptr;
// Any internal progress/error information generated by the db will
// be written to info_log if it is non-nullptr, or to a file stored
// in the same directory as the DB contents if info_log is nullptr.
// Default: nullptr
std::shared_ptr<Logger> info_log = nullptr;
#ifdef NDEBUG
InfoLogLevel info_log_level = INFO_LEVEL;
#else
InfoLogLevel info_log_level = DEBUG_LEVEL;
#endif // NDEBUG
// Number of open files that can be used by the DB. You may need to
// increase this if your database has a large working set. Value -1 means
// files opened are always kept open. You can estimate number of files based
// on target_file_size_base and target_file_size_multiplier for level-based
// compaction. For universal-style compaction, you can usually set it to -1.
//
// Default: -1
//
// Dynamically changeable through SetDBOptions() API.
int max_open_files = -1;
// If max_open_files is -1, DB will open all files on DB::Open(). You can
// use this option to increase the number of threads used to open the files.
// Default: 16
int max_file_opening_threads = 16;
// Once write-ahead logs exceed this size, we will start forcing the flush of
// column families whose memtables are backed by the oldest live WAL file
// (i.e. the ones that are causing all the space amplification). If set to 0
// (default), we will dynamically choose the WAL size limit to be
// [sum of all write_buffer_size * max_write_buffer_number] * 4
// This option takes effect only when there are more than one column family as
// otherwise the wal size is dictated by the write_buffer_size.
//
// Default: 0
//
// Dynamically changeable through SetDBOptions() API.
uint64_t max_total_wal_size = 0;
// If non-null, then we should collect metrics about database operations
std::shared_ptr<Statistics> statistics = nullptr;
// By default, writes to stable storage use fdatasync (on platforms
// where this function is available). If this option is true,
// fsync is used instead.
//
// fsync and fdatasync are equally safe for our purposes and fdatasync is
// faster, so it is rarely necessary to set this option. It is provided
// as a workaround for kernel/filesystem bugs, such as one that affected
// fdatasync with ext4 in kernel versions prior to 3.7.
bool use_fsync = false;
// A list of paths where SST files can be put into, with its target size.
// Newer data is placed into paths specified earlier in the vector while
// older data gradually moves to paths specified later in the vector.
//
// For example, you have a flash device with 10GB allocated for the DB,
// as well as a hard drive of 2TB, you should config it to be:
// [{"/flash_path", 10GB}, {"/hard_drive", 2TB}]
//
// The system will try to guarantee data under each path is close to but
// not larger than the target size. But current and future file sizes used
// by determining where to place a file are based on best-effort estimation,
// which means there is a chance that the actual size under the directory
// is slightly more than target size under some workloads. User should give
// some buffer room for those cases.
//
// If none of the paths has sufficient room to place a file, the file will
// be placed to the last path anyway, despite to the target size.
//
// Placing newer data to earlier paths is also best-efforts. User should
// expect user files to be placed in higher levels in some extreme cases.
//
// If left empty, only one path will be used, which is db_name passed when
// opening the DB.
// Default: empty
std::vector<DbPath> db_paths;
// This specifies the info LOG dir.
// If it is empty, the log files will be in the same dir as data.
// If it is non empty, the log files will be in the specified dir,
// and the db data dir's absolute path will be used as the log file
// name's prefix.
std::string db_log_dir = "";
// This specifies the absolute dir path for write-ahead logs (WAL).
// If it is empty, the log files will be in the same dir as data,
// dbname is used as the data dir by default
// If it is non empty, the log files will be in kept the specified dir.
// When destroying the db,
// all log files in wal_dir and the dir itself is deleted
std::string wal_dir = "";
// The periodicity when obsolete files get deleted. The default
// value is 6 hours. The files that get out of scope by compaction
// process will still get automatically delete on every compaction,
// regardless of this setting
//
// Default: 6 hours
//
// Dynamically changeable through SetDBOptions() API.
uint64_t delete_obsolete_files_period_micros = 6ULL * 60 * 60 * 1000000;
// Maximum number of concurrent background jobs (compactions and flushes).
//
// Default: 2
//
// Dynamically changeable through SetDBOptions() API.
int max_background_jobs = 2;
// NOT SUPPORTED ANYMORE: RocksDB automatically decides this based on the
// value of max_background_jobs. This option is ignored.
//
// Dynamically changeable through SetDBOptions() API.
int base_background_compactions = -1;
// NOT SUPPORTED ANYMORE: RocksDB automatically decides this based on the
// value of max_background_jobs. For backwards compatibility we will set
// `max_background_jobs = max_background_compactions + max_background_flushes`
// in the case where user sets at least one of `max_background_compactions` or
// `max_background_flushes` (we replace -1 by 1 in case one option is unset).
//
// Maximum number of concurrent background compaction jobs, submitted to
// the default LOW priority thread pool.
//
// If you're increasing this, also consider increasing number of threads in
// LOW priority thread pool. For more information, see
// Env::SetBackgroundThreads
//
// Default: -1
//
// Dynamically changeable through SetDBOptions() API.
int max_background_compactions = -1;
// This value represents the maximum number of threads that will
// concurrently perform a compaction job by breaking it into multiple,
// smaller ones that are run simultaneously.
// Default: 1 (i.e. no subcompactions)
uint32_t max_subcompactions = 1;
// NOT SUPPORTED ANYMORE: RocksDB automatically decides this based on the
// value of max_background_jobs. For backwards compatibility we will set
// `max_background_jobs = max_background_compactions + max_background_flushes`
// in the case where user sets at least one of `max_background_compactions` or
// `max_background_flushes`.
//
// Maximum number of concurrent background memtable flush jobs, submitted by
// default to the HIGH priority thread pool. If the HIGH priority thread pool
// is configured to have zero threads, flush jobs will share the LOW priority
// thread pool with compaction jobs.
//
// It is important to use both thread pools when the same Env is shared by
// multiple db instances. Without a separate pool, long running compaction
// jobs could potentially block memtable flush jobs of other db instances,
// leading to unnecessary Put stalls.
//
// If you're increasing this, also consider increasing number of threads in
// HIGH priority thread pool. For more information, see
// Env::SetBackgroundThreads
// Default: -1
int max_background_flushes = -1;
// Specify the maximal size of the info log file. If the log file
// is larger than `max_log_file_size`, a new info log file will
// be created.
// If max_log_file_size == 0, all logs will be written to one
// log file.
size_t max_log_file_size = 0;
// Time for the info log file to roll (in seconds).
// If specified with non-zero value, log file will be rolled
// if it has been active longer than `log_file_time_to_roll`.
// Default: 0 (disabled)
// Not supported in ROCKSDB_LITE mode!
size_t log_file_time_to_roll = 0;
// Maximal info log files to be kept.
// Default: 1000
size_t keep_log_file_num = 1000;
// Recycle log files.
// If non-zero, we will reuse previously written log files for new
// logs, overwriting the old data. The value indicates how many
// such files we will keep around at any point in time for later
// use. This is more efficient because the blocks are already
// allocated and fdatasync does not need to update the inode after
// each write.
// Default: 0
size_t recycle_log_file_num = 0;
// manifest file is rolled over on reaching this limit.
// The older manifest file be deleted.
// The default value is 1GB so that the manifest file can grow, but not
// reach the limit of storage capacity.
uint64_t max_manifest_file_size = 1024 * 1024 * 1024;
// Number of shards used for table cache.
int table_cache_numshardbits = 6;
// NOT SUPPORTED ANYMORE
// int table_cache_remove_scan_count_limit;
// The following two fields affect how archived logs will be deleted.
// 1. If both set to 0, logs will be deleted asap and will not get into
// the archive.
// 2. If WAL_ttl_seconds is 0 and WAL_size_limit_MB is not 0,
// WAL files will be checked every 10 min and if total size is greater
// then WAL_size_limit_MB, they will be deleted starting with the
// earliest until size_limit is met. All empty files will be deleted.
// 3. If WAL_ttl_seconds is not 0 and WAL_size_limit_MB is 0, then
// WAL files will be checked every WAL_ttl_seconds / 2 and those that
// are older than WAL_ttl_seconds will be deleted.
// 4. If both are not 0, WAL files will be checked every 10 min and both
// checks will be performed with ttl being first.
uint64_t WAL_ttl_seconds = 0;
uint64_t WAL_size_limit_MB = 0;
// Number of bytes to preallocate (via fallocate) the manifest
// files. Default is 4mb, which is reasonable to reduce random IO
// as well as prevent overallocation for mounts that preallocate
// large amounts of data (such as xfs's allocsize option).
size_t manifest_preallocation_size = 4 * 1024 * 1024;
// Allow the OS to mmap file for reading sst tables. Default: false
bool allow_mmap_reads = false;
// Allow the OS to mmap file for writing.
// DB::SyncWAL() only works if this is set to false.
// Default: false
bool allow_mmap_writes = false;
// Enable direct I/O mode for read/write
// they may or may not improve performance depending on the use case
//
// Files will be opened in "direct I/O" mode
// which means that data r/w from the disk will not be cached or
// buffered. The hardware buffer of the devices may however still
// be used. Memory mapped files are not impacted by these parameters.
// Use O_DIRECT for user and compaction reads.
// When true, we also force new_table_reader_for_compaction_inputs to true.
// Default: false
// Not supported in ROCKSDB_LITE mode!
bool use_direct_reads = false;
// Use O_DIRECT for writes in background flush and compactions.
// Default: false
// Not supported in ROCKSDB_LITE mode!
bool use_direct_io_for_flush_and_compaction = false;
// If false, fallocate() calls are bypassed
bool allow_fallocate = true;
// Disable child process inherit open files. Default: true
bool is_fd_close_on_exec = true;
// NOT SUPPORTED ANYMORE -- this options is no longer used
bool skip_log_error_on_recovery = false;
// if not zero, dump rocksdb.stats to LOG every stats_dump_period_sec
//
// Default: 600 (10 min)
//
// Dynamically changeable through SetDBOptions() API.
unsigned int stats_dump_period_sec = 600;
// if not zero, dump rocksdb.stats to RocksDB every stats_persist_period_sec
// Default: 600
unsigned int stats_persist_period_sec = 600;
// If true, automatically persist stats to a hidden column family (column
// family name: ___rocksdb_stats_history___) every
// stats_persist_period_sec seconds; otherwise, write to an in-memory
// struct. User can query through `GetStatsHistory` API.
// If user attempts to create a column family with the same name on a DB
// which have previously set persist_stats_to_disk to true, the column family
// creation will fail, but the hidden column family will survive, as well as
// the previously persisted statistics.
// When peristing stats to disk, the stat name will be limited at 100 bytes.
// Default: false
bool persist_stats_to_disk = false;
// if not zero, periodically take stats snapshots and store in memory, the
// memory size for stats snapshots is capped at stats_history_buffer_size
// Default: 1MB
size_t stats_history_buffer_size = 1024 * 1024;
// If set true, will hint the underlying file system that the file
// access pattern is random, when a sst file is opened.
// Default: true
bool advise_random_on_open = true;
// Amount of data to build up in memtables across all column
// families before writing to disk.
//
// This is distinct from write_buffer_size, which enforces a limit
// for a single memtable.
//
// This feature is disabled by default. Specify a non-zero value
// to enable it.
//
// Default: 0 (disabled)
size_t db_write_buffer_size = 0;
// The memory usage of memtable will report to this object. The same object
// can be passed into multiple DBs and it will track the sum of size of all
// the DBs. If the total size of all live memtables of all the DBs exceeds
// a limit, a flush will be triggered in the next DB to which the next write
// is issued.
//
// If the object is only passed to one DB, the behavior is the same as
// db_write_buffer_size. When write_buffer_manager is set, the value set will
// override db_write_buffer_size.
//
// This feature is disabled by default. Specify a non-zero value
// to enable it.
//
// Default: null
std::shared_ptr<WriteBufferManager> write_buffer_manager = nullptr;
// Specify the file access pattern once a compaction is started.
// It will be applied to all input files of a compaction.
// Default: NORMAL
enum AccessHint { NONE, NORMAL, SEQUENTIAL, WILLNEED };
AccessHint access_hint_on_compaction_start = NORMAL;
// If true, always create a new file descriptor and new table reader
// for compaction inputs. Turn this parameter on may introduce extra
// memory usage in the table reader, if it allocates extra memory
// for indexes. This will allow file descriptor prefetch options
// to be set for compaction input files and not to impact file
// descriptors for the same file used by user queries.
// Suggest to enable BlockBasedTableOptions.cache_index_and_filter_blocks
// for this mode if using block-based table.
//
// Default: false
// This flag has no affect on the behavior of compaction and plan to delete
// in the future.
bool new_table_reader_for_compaction_inputs = false;
// If non-zero, we perform bigger reads when doing compaction. If you're
// running RocksDB on spinning disks, you should set this to at least 2MB.
// That way RocksDB's compaction is doing sequential instead of random reads.
//
// When non-zero, we also force new_table_reader_for_compaction_inputs to
// true.
//
// Default: 0
//
// Dynamically changeable through SetDBOptions() API.
size_t compaction_readahead_size = 0;
// This is a maximum buffer size that is used by WinMmapReadableFile in
// unbuffered disk I/O mode. We need to maintain an aligned buffer for
// reads. We allow the buffer to grow until the specified value and then
// for bigger requests allocate one shot buffers. In unbuffered mode we
// always bypass read-ahead buffer at ReadaheadRandomAccessFile
// When read-ahead is required we then make use of compaction_readahead_size
// value and always try to read ahead. With read-ahead we always
// pre-allocate buffer to the size instead of growing it up to a limit.
//
// This option is currently honored only on Windows
//
// Default: 1 Mb
//
// Special value: 0 - means do not maintain per instance buffer. Allocate
// per request buffer and avoid locking.
size_t random_access_max_buffer_size = 1024 * 1024;
// This is the maximum buffer size that is used by WritableFileWriter.
// On Windows, we need to maintain an aligned buffer for writes.
// We allow the buffer to grow until it's size hits the limit in buffered
// IO and fix the buffer size when using direct IO to ensure alignment of
// write requests if the logical sector size is unusual
//
// Default: 1024 * 1024 (1 MB)
//
// Dynamically changeable through SetDBOptions() API.
size_t writable_file_max_buffer_size = 1024 * 1024;
// Use adaptive mutex, which spins in the user space before resorting
// to kernel. This could reduce context switch when the mutex is not
// heavily contended. However, if the mutex is hot, we could end up
// wasting spin time.
// Default: false
bool use_adaptive_mutex = false;
// Create DBOptions with default values for all fields
DBOptions();
// Create DBOptions from Options
explicit DBOptions(const Options& options);
void Dump(Logger* log) const;
// Allows OS to incrementally sync files to disk while they are being
// written, asynchronously, in the background. This operation can be used
// to smooth out write I/Os over time. Users shouldn't rely on it for
// persistency guarantee.
// Issue one request for every bytes_per_sync written. 0 turns it off.
//
// You may consider using rate_limiter to regulate write rate to device.
// When rate limiter is enabled, it automatically enables bytes_per_sync
// to 1MB.
//
// This option applies to table files
//
// Default: 0, turned off
//
// Note: DOES NOT apply to WAL files. See wal_bytes_per_sync instead
// Dynamically changeable through SetDBOptions() API.
uint64_t bytes_per_sync = 0;
// Same as bytes_per_sync, but applies to WAL files
//
// Default: 0, turned off
//
// Dynamically changeable through SetDBOptions() API.
uint64_t wal_bytes_per_sync = 0;
// When true, guarantees WAL files have at most `wal_bytes_per_sync`
// bytes submitted for writeback at any given time, and SST files have at most
// `bytes_per_sync` bytes pending writeback at any given time. This can be
// used to handle cases where processing speed exceeds I/O speed during file
// generation, which can lead to a huge sync when the file is finished, even
// with `bytes_per_sync` / `wal_bytes_per_sync` properly configured.
//
// - If `sync_file_range` is supported it achieves this by waiting for any
// prior `sync_file_range`s to finish before proceeding. In this way,
// processing (compression, etc.) can proceed uninhibited in the gap
// between `sync_file_range`s, and we block only when I/O falls behind.
// - Otherwise the `WritableFile::Sync` method is used. Note this mechanism
// always blocks, thus preventing the interleaving of I/O and processing.
//
// Note: Enabling this option does not provide any additional persistence
// guarantees, as it may use `sync_file_range`, which does not write out
// metadata.
//
// Default: false
bool strict_bytes_per_sync = false;
// A vector of EventListeners whose callback functions will be called
// when specific RocksDB event happens.
std::vector<std::shared_ptr<EventListener>> listeners;
// If true, then the status of the threads involved in this DB will
// be tracked and available via GetThreadList() API.
//
// Default: false
bool enable_thread_tracking = false;
// The limited write rate to DB if soft_pending_compaction_bytes_limit or
// level0_slowdown_writes_trigger is triggered, or we are writing to the
// last mem table allowed and we allow more than 3 mem tables. It is
// calculated using size of user write requests before compression.
// RocksDB may decide to slow down more if the compaction still
// gets behind further.
// If the value is 0, we will infer a value from `rater_limiter` value
// if it is not empty, or 16MB if `rater_limiter` is empty. Note that
// if users change the rate in `rate_limiter` after DB is opened,
// `delayed_write_rate` won't be adjusted.
//
// Unit: byte per second.
//
// Default: 0
//
// Dynamically changeable through SetDBOptions() API.
uint64_t delayed_write_rate = 0;
// By default, a single write thread queue is maintained. The thread gets
// to the head of the queue becomes write batch group leader and responsible
// for writing to WAL and memtable for the batch group.
//
// If enable_pipelined_write is true, separate write thread queue is
// maintained for WAL write and memtable write. A write thread first enter WAL
// writer queue and then memtable writer queue. Pending thread on the WAL
// writer queue thus only have to wait for previous writers to finish their
// WAL writing but not the memtable writing. Enabling the feature may improve
// write throughput and reduce latency of the prepare phase of two-phase
// commit.
//
// Default: false
bool enable_pipelined_write = false;
// Setting unordered_write to true trades higher write throughput with
// relaxing the immutability guarantee of snapshots. This violates the
// repeatability one expects from ::Get from a snapshot, as well as
// ::MultiGet and Iterator's consistent-point-in-time view property.
// If the application cannot tolerate the relaxed guarantees, it can implement
// its own mechanisms to work around that and yet benefit from the higher
// throughput. Using TransactionDB with WRITE_PREPARED write policy and
// two_write_queues=true is one way to achieve immutable snapshots despite
// unordered_write.
//
// By default, i.e., when it is false, rocksdb does not advance the sequence
// number for new snapshots unless all the writes with lower sequence numbers
// are already finished. This provides the immutability that we except from
// snapshots. Moreover, since Iterator and MultiGet internally depend on
// snapshots, the snapshot immutability results into Iterator and MultiGet
// offering consistent-point-in-time view. If set to true, although
// Read-Your-Own-Write property is still provided, the snapshot immutability
// property is relaxed: the writes issued after the snapshot is obtained (with
// larger sequence numbers) will be still not visible to the reads from that
// snapshot, however, there still might be pending writes (with lower sequence
// number) that will change the state visible to the snapshot after they are
// landed to the memtable.
//
// Default: false
bool unordered_write = false;
// If true, allow multi-writers to update mem tables in parallel.
// Only some memtable_factory-s support concurrent writes; currently it
// is implemented only for SkipListFactory. Concurrent memtable writes
// are not compatible with inplace_update_support or filter_deletes.
// It is strongly recommended to set enable_write_thread_adaptive_yield
// if you are going to use this feature.
//
// Default: true
bool allow_concurrent_memtable_write = true;
// If true, threads synchronizing with the write batch group leader will
// wait for up to write_thread_max_yield_usec before blocking on a mutex.
// This can substantially improve throughput for concurrent workloads,
// regardless of whether allow_concurrent_memtable_write is enabled.
//
// Default: true
bool enable_write_thread_adaptive_yield = true;
// The maximum limit of number of bytes that are written in a single batch
// of WAL or memtable write. It is followed when the leader write size
// is larger than 1/8 of this limit.
//
// Default: 1 MB
uint64_t max_write_batch_group_size_bytes = 1 << 20;
// The maximum number of microseconds that a write operation will use
// a yielding spin loop to coordinate with other write threads before
// blocking on a mutex. (Assuming write_thread_slow_yield_usec is
// set properly) increasing this value is likely to increase RocksDB
// throughput at the expense of increased CPU usage.
//
// Default: 100
uint64_t write_thread_max_yield_usec = 100;
// The latency in microseconds after which a std::this_thread::yield
// call (sched_yield on Linux) is considered to be a signal that
// other processes or threads would like to use the current core.
// Increasing this makes writer threads more likely to take CPU
// by spinning, which will show up as an increase in the number of
// involuntary context switches.
//
// Default: 3
uint64_t write_thread_slow_yield_usec = 3;
// If true, then DB::Open() will not update the statistics used to optimize
// compaction decision by loading table properties from many files.
// Turning off this feature will improve DBOpen time especially in
// disk environment.
//
// Default: false
bool skip_stats_update_on_db_open = false;
// Recovery mode to control the consistency while replaying WAL
// Default: kPointInTimeRecovery
WALRecoveryMode wal_recovery_mode = WALRecoveryMode::kPointInTimeRecovery;
// if set to false then recovery will fail when a prepared
// transaction is encountered in the WAL
bool allow_2pc = false;
// A global cache for table-level rows.
// Default: nullptr (disabled)
// Not supported in ROCKSDB_LITE mode!
std::shared_ptr<Cache> row_cache = nullptr;
#ifndef ROCKSDB_LITE
// A filter object supplied to be invoked while processing write-ahead-logs
// (WALs) during recovery. The filter provides a way to inspect log
// records, ignoring a particular record or skipping replay.
// The filter is invoked at startup and is invoked from a single-thread
// currently.
WalFilter* wal_filter = nullptr;
#endif // ROCKSDB_LITE
// If true, then DB::Open / CreateColumnFamily / DropColumnFamily
// / SetOptions will fail if options file is not detected or properly
// persisted.
//
// DEFAULT: false
bool fail_if_options_file_error = false;
// If true, then print malloc stats together with rocksdb.stats
// when printing to LOG.
// DEFAULT: false
bool dump_malloc_stats = false;
// By default RocksDB replay WAL logs and flush them on DB open, which may
// create very small SST files. If this option is enabled, RocksDB will try
// to avoid (but not guarantee not to) flush during recovery. Also, existing
// WAL logs will be kept, so that if crash happened before flush, we still
// have logs to recover from.
//
// DEFAULT: false
bool avoid_flush_during_recovery = false;
// By default RocksDB will flush all memtables on DB close if there are
// unpersisted data (i.e. with WAL disabled) The flush can be skip to speedup
// DB close. Unpersisted data WILL BE LOST.
//
// DEFAULT: false
//
// Dynamically changeable through SetDBOptions() API.
bool avoid_flush_during_shutdown = false;
// Set this option to true during creation of database if you want
// to be able to ingest behind (call IngestExternalFile() skipping keys
// that already exist, rather than overwriting matching keys).
// Setting this option to true will affect 2 things:
// 1) Disable some internal optimizations around SST file compression
// 2) Reserve bottom-most level for ingested files only.
// 3) Note that num_levels should be >= 3 if this option is turned on.
//
// DEFAULT: false
// Immutable.
bool allow_ingest_behind = false;
// Needed to support differential snapshots.
// If set to true then DB will only process deletes with sequence number
// less than what was set by SetPreserveDeletesSequenceNumber(uint64_t ts).
// Clients are responsible to periodically call this method to advance
// the cutoff time. If this method is never called and preserve_deletes
// is set to true NO deletes will ever be processed.
// At the moment this only keeps normal deletes, SingleDeletes will
// not be preserved.
// DEFAULT: false
// Immutable (TODO: make it dynamically changeable)
bool preserve_deletes = false;
// If enabled it uses two queues for writes, one for the ones with
// disable_memtable and one for the ones that also write to memtable. This
// allows the memtable writes not to lag behind other writes. It can be used
// to optimize MySQL 2PC in which only the commits, which are serial, write to
// memtable.
bool two_write_queues = false;
// If true WAL is not flushed automatically after each write. Instead it
// relies on manual invocation of FlushWAL to write the WAL buffer to its
// file.
bool manual_wal_flush = false;
// If true, RocksDB supports flushing multiple column families and committing
// their results atomically to MANIFEST. Note that it is not
// necessary to set atomic_flush to true if WAL is always enabled since WAL
// allows the database to be restored to the last persistent state in WAL.
// This option is useful when there are column families with writes NOT
// protected by WAL.
// For manual flush, application has to specify which column families to
// flush atomically in DB::Flush.
// For auto-triggered flush, RocksDB atomically flushes ALL column families.
//
// Currently, any WAL-enabled writes after atomic flush may be replayed
// independently if the process crashes later and tries to recover.
bool atomic_flush = false;
// If true, ColumnFamilyHandle's and Iterator's destructors won't delete
// obsolete files directly and will instead schedule a background job
// to do it. Use it if you're destroying iterators or ColumnFamilyHandle-s
// from latency-sensitive threads.
// If set to true, takes precedence over
// ReadOptions::background_purge_on_iterator_cleanup.
bool avoid_unnecessary_blocking_io = false;
// Historically DB ID has always been stored in Identity File in DB folder.
// If this flag is true, the DB ID is written to Manifest file in addition
// to the Identity file. By doing this 2 problems are solved
// 1. We don't checksum the Identity file where as Manifest file is.
// 2. Since the source of truth for DB is Manifest file DB ID will sit with
// the source of truth. Previously the Identity file could be copied
// independent of Manifest and that can result in wrong DB ID.
// We recommend setting this flag to true.
// Default: false
bool write_dbid_to_manifest = false;
// The number of bytes to prefetch when reading the log. This is mostly useful
// for reading a remotely located log, as it can save the number of
// round-trips. If 0, then the prefetching is disabled.
//
// Default: 0
size_t log_readahead_size = 0;
};
// Options to control the behavior of a database (passed to DB::Open)
struct Options : public DBOptions, public ColumnFamilyOptions {
// Create an Options object with default values for all fields.
Options() : DBOptions(), ColumnFamilyOptions() {}
Options(const DBOptions& db_options,
const ColumnFamilyOptions& column_family_options)
: DBOptions(db_options), ColumnFamilyOptions(column_family_options) {}
// The function recovers options to the option as in version 4.6.
Options* OldDefaults(int rocksdb_major_version = 4,
int rocksdb_minor_version = 6);
void Dump(Logger* log) const;
void DumpCFOptions(Logger* log) const;
// Some functions that make it easier to optimize RocksDB
// Set appropriate parameters for bulk loading.
// The reason that this is a function that returns "this" instead of a
// constructor is to enable chaining of multiple similar calls in the future.
//
// All data will be in level 0 without any automatic compaction.
// It's recommended to manually call CompactRange(NULL, NULL) before reading
// from the database, because otherwise the read can be very slow.
Options* PrepareForBulkLoad();
// Use this if your DB is very small (like under 1GB) and you don't want to
// spend lots of memory for memtables.
Options* OptimizeForSmallDb();
};
//
// An application can issue a read request (via Get/Iterators) and specify
// if that read should process data that ALREADY resides on a specified cache
// level. For example, if an application specifies kBlockCacheTier then the
// Get call will process data that is already processed in the memtable or
// the block cache. It will not page in data from the OS cache or data that
// resides in storage.
enum ReadTier {
kReadAllTier = 0x0, // data in memtable, block cache, OS cache or storage
kBlockCacheTier = 0x1, // data in memtable or block cache
kPersistedTier = 0x2, // persisted data. When WAL is disabled, this option
// will skip data in memtable.
// Note that this ReadTier currently only supports
// Get and MultiGet and does not support iterators.
kMemtableTier = 0x3 // data in memtable. used for memtable-only iterators.
};
// Options that control read operations
struct ReadOptions {
// If "snapshot" is non-nullptr, read as of the supplied snapshot
// (which must belong to the DB that is being read and which must
// not have been released). If "snapshot" is nullptr, use an implicit
// snapshot of the state at the beginning of this read operation.
// Default: nullptr
const Snapshot* snapshot;
// `iterate_lower_bound` defines the smallest key at which the backward
// iterator can return an entry. Once the bound is passed, Valid() will be
// false. `iterate_lower_bound` is inclusive ie the bound value is a valid
// entry.
//
// If prefix_extractor is not null, the Seek target and `iterate_lower_bound`
// need to have the same prefix. This is because ordering is not guaranteed
// outside of prefix domain.
//
// Default: nullptr
const Slice* iterate_lower_bound;
// "iterate_upper_bound" defines the extent upto which the forward iterator
// can returns entries. Once the bound is reached, Valid() will be false.
// "iterate_upper_bound" is exclusive ie the bound value is
// not a valid entry. If iterator_extractor is not null, the Seek target
// and iterate_upper_bound need to have the same prefix.
// This is because ordering is not guaranteed outside of prefix domain.
//
// Default: nullptr
const Slice* iterate_upper_bound;
// RocksDB does auto-readahead for iterators on noticing more than two reads
// for a table file. The readahead starts at 8KB and doubles on every
// additional read upto 256KB.
// This option can help if most of the range scans are large, and if it is
// determined that a larger readahead than that enabled by auto-readahead is
// needed.
// Using a large readahead size (> 2MB) can typically improve the performance
// of forward iteration on spinning disks.
// Default: 0
size_t readahead_size;
// A threshold for the number of keys that can be skipped before failing an
// iterator seek as incomplete. The default value of 0 should be used to
// never fail a request as incomplete, even on skipping too many keys.
// Default: 0
uint64_t max_skippable_internal_keys;
// Specify if this read request should process data that ALREADY
// resides on a particular cache. If the required data is not
// found at the specified cache, then Status::Incomplete is returned.
// Default: kReadAllTier
ReadTier read_tier;
// If true, all data read from underlying storage will be
// verified against corresponding checksums.
// Default: true
bool verify_checksums;
// Should the "data block"/"index block"" read for this iteration be placed in
// block cache?
// Callers may wish to set this field to false for bulk scans.
// This would help not to the change eviction order of existing items in the
// block cache. Default: true
bool fill_cache;
// Specify to create a tailing iterator -- a special iterator that has a
// view of the complete database (i.e. it can also be used to read newly
// added data) and is optimized for sequential reads. It will return records
// that were inserted into the database after the creation of the iterator.
// Default: false
// Not supported in ROCKSDB_LITE mode!
bool tailing;
// This options is not used anymore. It was to turn on a functionality that
// has been removed.
bool managed;
// Enable a total order seek regardless of index format (e.g. hash index)
// used in the table. Some table format (e.g. plain table) may not support
// this option.
// If true when calling Get(), we also skip prefix bloom when reading from
// block based table. It provides a way to read existing data after
// changing implementation of prefix extractor.
bool total_order_seek;
// Enforce that the iterator only iterates over the same prefix as the seek.
// This option is effective only for prefix seeks, i.e. prefix_extractor is
// non-null for the column family and total_order_seek is false. Unlike
// iterate_upper_bound, prefix_same_as_start only works within a prefix
// but in both directions.
// Default: false
bool prefix_same_as_start;
// Keep the blocks loaded by the iterator pinned in memory as long as the
// iterator is not deleted, If used when reading from tables created with
// BlockBasedTableOptions::use_delta_encoding = false,
// Iterator's property "rocksdb.iterator.is-key-pinned" is guaranteed to
// return 1.
// Default: false
bool pin_data;
// If true, when PurgeObsoleteFile is called in CleanupIteratorState, we
// schedule a background job in the flush job queue and delete obsolete files
// in background.
// Default: false
bool background_purge_on_iterator_cleanup;
// If true, keys deleted using the DeleteRange() API will be visible to
// readers until they are naturally deleted during compaction. This improves
// read performance in DBs with many range deletions.
// Default: false
bool ignore_range_deletions;
// A callback to determine whether relevant keys for this scan exist in a
// given table based on the table's properties. The callback is passed the
// properties of each table during iteration. If the callback returns false,
// the table will not be scanned. This option only affects Iterators and has
// no impact on point lookups.
// Default: empty (every table will be scanned)
std::function<bool(const TableProperties&)> table_filter;
// Needed to support differential snapshots. Has 2 effects:
// 1) Iterator will skip all internal keys with seqnum < iter_start_seqnum
// 2) if this param > 0 iterator will return INTERNAL keys instead of
// user keys; e.g. return tombstones as well.
// Default: 0 (don't filter by seqnum, return user keys)
SequenceNumber iter_start_seqnum;
// Timestamp of operation. Read should return the latest data visible to the
// specified timestamp. All timestamps of the same database must be of the
// same length and format. The user is responsible for providing a customized
// compare function via Comparator to order <key, timestamp> tuples.
// The user-specified timestamp feature is still under active development,
// and the API is subject to change.
const Slice* timestamp;
ReadOptions();
ReadOptions(bool cksum, bool cache);
};
// Options that control write operations
struct WriteOptions {
// If true, the write will be flushed from the operating system
// buffer cache (by calling WritableFile::Sync()) before the write
// is considered complete. If this flag is true, writes will be
// slower.
//
// If this flag is false, and the machine crashes, some recent
// writes may be lost. Note that if it is just the process that
// crashes (i.e., the machine does not reboot), no writes will be
// lost even if sync==false.
//
// In other words, a DB write with sync==false has similar
// crash semantics as the "write()" system call. A DB write
// with sync==true has similar crash semantics to a "write()"
// system call followed by "fdatasync()".
//
// Default: false
bool sync;
// If true, writes will not first go to the write ahead log,
// and the write may get lost after a crash. The backup engine
// relies on write-ahead logs to back up the memtable, so if
// you disable write-ahead logs, you must create backups with
// flush_before_backup=true to avoid losing unflushed memtable data.
// Default: false
bool disableWAL;
// If true and if user is trying to write to column families that don't exist
// (they were dropped), ignore the write (don't return an error). If there
// are multiple writes in a WriteBatch, other writes will succeed.
// Default: false
bool ignore_missing_column_families;
// If true and we need to wait or sleep for the write request, fails
// immediately with Status::Incomplete().
// Default: false
bool no_slowdown;
// If true, this write request is of lower priority if compaction is
// behind. In this case, no_slowdown = true, the request will be cancelled
// immediately with Status::Incomplete() returned. Otherwise, it will be
// slowed down. The slowdown value is determined by RocksDB to guarantee
// it introduces minimum impacts to high priority writes.
//
// Default: false
bool low_pri;
// See comments for PreReleaseCallback
PreReleaseCallback* pre_release_callback;
// If true, this writebatch will maintain the last insert positions of each
// memtable as hints in concurrent write. It can improve write performance
// in concurrent writes if keys in one writebatch are sequential. In
// non-concurrent writes (when concurrent_memtable_writes is false) this
// option will be ignored.
//
// Default: false
bool memtable_insert_hint_per_batch;
// Timestamp of write operation, e.g. Put. All timestamps of the same
// database must share the same length and format. The user is also
// responsible for providing a customized compare function via Comparator to
// order <key, timestamp> tuples. If the user wants to enable timestamp, then
// all write operations must be associated with timestamp because RocksDB, as
// a single-node storage engine currently has no knowledge of global time,
// thus has to rely on the application.
// The user-specified timestamp feature is still under active development,
// and the API is subject to change.
const Slice* timestamp;
WriteOptions()
: sync(false),
disableWAL(false),
ignore_missing_column_families(false),
no_slowdown(false),
low_pri(false),
pre_release_callback(nullptr),
memtable_insert_hint_per_batch(false),
timestamp(nullptr) {}
};
// Options that control flush operations
struct FlushOptions {
// If true, the flush will wait until the flush is done.
// Default: true
bool wait;
// If true, the flush would proceed immediately even it means writes will
// stall for the duration of the flush; if false the operation will wait
// until it's possible to do flush w/o causing stall or until required flush
// is performed by someone else (foreground call or background thread).
// Default: false
bool allow_write_stall;
FlushOptions() : wait(true), allow_write_stall(false) {}
};
// Create a Logger from provided DBOptions
extern Status CreateLoggerFromOptions(const std::string& dbname,
const DBOptions& options,
std::shared_ptr<Logger>* logger);
// CompactionOptions are used in CompactFiles() call.
struct CompactionOptions {
// Compaction output compression type
// Default: snappy
// If set to `kDisableCompressionOption`, RocksDB will choose compression type
// according to the `ColumnFamilyOptions`, taking into account the output
// level if `compression_per_level` is specified.
CompressionType compression;
// Compaction will create files of size `output_file_size_limit`.
// Default: MAX, which means that compaction will create a single file
uint64_t output_file_size_limit;
// If > 0, it will replace the option in the DBOptions for this compaction.
uint32_t max_subcompactions;
CompactionOptions()
: compression(kSnappyCompression),
output_file_size_limit(std::numeric_limits<uint64_t>::max()),
max_subcompactions(0) {}
};
// For level based compaction, we can configure if we want to skip/force
// bottommost level compaction.
enum class BottommostLevelCompaction {
// Skip bottommost level compaction
kSkip,
// Only compact bottommost level if there is a compaction filter
// This is the default option
kIfHaveCompactionFilter,
// Always compact bottommost level
kForce,
// Always compact bottommost level but in bottommost level avoid
// double-compacting files created in the same compaction
kForceOptimized,
};
// CompactRangeOptions is used by CompactRange() call.
struct CompactRangeOptions {
// If true, no other compaction will run at the same time as this
// manual compaction
bool exclusive_manual_compaction = true;
// If true, compacted files will be moved to the minimum level capable
// of holding the data or given level (specified non-negative target_level).
bool change_level = false;
// If change_level is true and target_level have non-negative value, compacted
// files will be moved to target_level.
int target_level = -1;
// Compaction outputs will be placed in options.db_paths[target_path_id].
// Behavior is undefined if target_path_id is out of range.
uint32_t target_path_id = 0;
// By default level based compaction will only compact the bottommost level
// if there is a compaction filter
BottommostLevelCompaction bottommost_level_compaction =
BottommostLevelCompaction::kIfHaveCompactionFilter;
// If true, will execute immediately even if doing so would cause the DB to
// enter write stall mode. Otherwise, it'll sleep until load is low enough.
bool allow_write_stall = false;
// If > 0, it will replace the option in the DBOptions for this compaction.
uint32_t max_subcompactions = 0;
};
// IngestExternalFileOptions is used by IngestExternalFile()
struct IngestExternalFileOptions {
// Can be set to true to move the files instead of copying them.
bool move_files = false;
// If set to true, ingestion falls back to copy when move fails.
bool failed_move_fall_back_to_copy = true;
// If set to false, an ingested file keys could appear in existing snapshots
// that where created before the file was ingested.
bool snapshot_consistency = true;
// If set to false, IngestExternalFile() will fail if the file key range
// overlaps with existing keys or tombstones in the DB.
bool allow_global_seqno = true;
// If set to false and the file key range overlaps with the memtable key range
// (memtable flush required), IngestExternalFile will fail.
bool allow_blocking_flush = true;
// Set to true if you would like duplicate keys in the file being ingested
// to be skipped rather than overwriting existing data under that key.
// Usecase: back-fill of some historical data in the database without
// over-writing existing newer version of data.
// This option could only be used if the DB has been running
// with allow_ingest_behind=true since the dawn of time.
// All files will be ingested at the bottommost level with seqno=0.
bool ingest_behind = false;
// Set to true if you would like to write global_seqno to a given offset in
// the external SST file for backward compatibility. Older versions of
// RocksDB writes a global_seqno to a given offset within ingested SST files,
// and new versions of RocksDB do not. If you ingest an external SST using
// new version of RocksDB and would like to be able to downgrade to an
// older version of RocksDB, you should set 'write_global_seqno' to true. If
// your service is just starting to use the new RocksDB, we recommend that
// you set this option to false, which brings two benefits:
// 1. No extra random write for global_seqno during ingestion.
// 2. Without writing external SST file, it's possible to do checksum.
// We have a plan to set this option to false by default in the future.
bool write_global_seqno = true;
// Set to true if you would like to verify the checksums of each block of the
// external SST file before ingestion.
// Warning: setting this to true causes slowdown in file ingestion because
// the external SST file has to be read.
bool verify_checksums_before_ingest = false;
// When verify_checksums_before_ingest = true, RocksDB uses default
// readahead setting to scan the file while verifying checksums before
// ingestion.
// Users can override the default value using this option.
// Using a large readahead size (> 2MB) can typically improve the performance
// of forward iteration on spinning disks.
size_t verify_checksums_readahead_size = 0;
};
enum TraceFilterType : uint64_t {
// Trace all the operations
kTraceFilterNone = 0x0,
// Do not trace the get operations
kTraceFilterGet = 0x1 << 0,
// Do not trace the write operations
kTraceFilterWrite = 0x1 << 1
};
// TraceOptions is used for StartTrace
struct TraceOptions {
// To avoid the trace file size grows large than the storage space,
// user can set the max trace file size in Bytes. Default is 64GB
uint64_t max_trace_file_size = uint64_t{64} * 1024 * 1024 * 1024;
// Specify trace sampling option, i.e. capture one per how many requests.
// Default to 1 (capture every request).
uint64_t sampling_frequency = 1;
// Note: The filtering happens before sampling.
uint64_t filter = kTraceFilterNone;
};
// ImportColumnFamilyOptions is used by ImportColumnFamily()
struct ImportColumnFamilyOptions {
// Can be set to true to move the files instead of copying them.
bool move_files = false;
};
// Options used with DB::GetApproximateSizes()
struct SizeApproximationOptions {
// Defines whether the returned size should include the recently written
// data in the mem-tables. If set to false, include_files must be true.
bool include_memtabtles = false;
// Defines whether the returned size should include data serialized to disk.
// If set to false, include_memtabtles must be true.
bool include_files = true;
// When approximating the files total size that is used to store a keys range
// using DB::GetApproximateSizes, allow approximation with an error margin of
// up to total_files_size * files_size_error_margin. This allows to take some
// shortcuts in files size approximation, resulting in better performance,
// while guaranteeing the resulting error is within a reasonable margin.
// E.g., if the value is 0.1, then the error margin of the returned files size
// approximation will be within 10%.
// If the value is non-positive - a more precise yet more CPU intensive
// estimation is performed.
double files_size_error_margin = -1.0;
};
} // namespace rocksdb
| [
"867245430@qq.com"
] | 867245430@qq.com |
6d285c7e11bfc190faa74cc109a48d53c3c05219 | 2c565fe86a03b1e971e696a516749196cd3ae39f | /src/libs/dependency_graph/port.h | 70a2403e7657798c7fc0aa5d796c29b311d7320b | [
"MIT"
] | permissive | ziranjuanchow/possumwood | 0e4ecc053ef2db838e7651d4bbdb506d4a949def | 5357f1fea2a2bf2a00dcba60c48d3c8bcfcaa138 | refs/heads/master | 2020-03-15T10:25:39.447999 | 2018-04-07T16:23:23 | 2018-04-07T16:23:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,821 | h | #pragma once
#include <string>
#include <boost/noncopyable.hpp>
#include <boost/signals2.hpp>
#include "attr.h"
namespace dependency_graph {
class NodeBase;
class Port : public boost::noncopyable {
public:
Port(Port&& p);
const std::string& name() const;
const Attr::Category category() const;
const unsigned index() const;
const std::string type() const;
/// sets a value on the port.
/// Marks all downstream values dirty.
template<typename T>
void set(const T& value);
/// gets a value from the port.
/// Pulls on the inputs and causes recomputation if the value is
/// marked as dirty.
template<typename T>
const T& get();
/// returns true if given port is dirty and will require recomputation
bool isDirty() const;
/// returns a reference to the parent node
NodeBase& node();
/// returns a reference to the parent node
const NodeBase& node() const;
/// creates a connection between this port an the port in argument.
/// The direction is always from *this port to p - only applicable
/// to output ports with an input port as the argument.
void connect(Port& p);
/// disconnects two connected ports
void disconnect(Port& p);
/// returns true if this port is connected to anything
bool isConnected() const;
/// adds a "value changed" callback - to be used by the UI
boost::signals2::connection valueCallback(const std::function<void()>& fn);
/// adds a "flags changed" callback - to be used by the UI
boost::signals2::connection flagsCallback(const std::function<void()>& fn);
private:
Port(unsigned id, NodeBase* parent);
void setDirty(bool dirty);
unsigned m_id;
bool m_dirty;
NodeBase* m_parent;
boost::signals2::signal<void()> m_valueCallbacks, m_flagsCallbacks;
friend class Node;
friend class NodeBase;
};
}
| [
"martin.prazak@gmail.com"
] | martin.prazak@gmail.com |
c0b49f7a2ada6379b22f1b23fd4e0793e1b29e72 | b1fe3e9df7cb0306fb1e1ffbcaa609a00a28711c | /Week7_5/CMP105App/Companion.cpp | 20481c77fa78725710ce7122e6a8e3d1c1dba6dd | [] | no_license | zara-01/CMP105_W7 | 4a304e0cdd5f0224b5fef0a5eb441da044cce730 | deda2788e4b13df14c528f97be37154ea2ee2cf4 | refs/heads/master | 2021-01-27T09:43:48.466436 | 2020-02-27T11:02:07 | 2020-02-27T11:02:07 | 243,477,284 | 1 | 0 | null | 2020-02-27T09:12:32 | 2020-02-27T09:12:32 | null | UTF-8 | C++ | false | false | 326 | cpp | #include "Companion.h"
Companion::Companion()
{
setPosition(500, 500);
setSize(sf::Vector2f(10, 10));
setFillColor(sf::Color::Blue);
setVelocity(500, 0);
}
Companion::~Companion()
{
}
void Companion::update(float dt)
{
move(velocity*dt);
}
void Companion::moveToPlayer(Player* p)
{
setPosition(p->getPosition());
}
| [
"p.robertson@abertay.ac.uk"
] | p.robertson@abertay.ac.uk |
3e6d00e2bb42d06e296ea451d1288351c216a7e7 | 889e3b52ee46863ec0fea1173d7860f15206dbf3 | /src/device_util.cpp | 8a99282cc10937a5b41711658b921e62c35d91a9 | [
"MIT"
] | permissive | guacamoleo/HIP | 83dcb08e19775b6d6a3689a2dcdeb4be956af611 | bca828c2ee07f3b34b44ee82c145beb7be9e669b | refs/heads/master | 2021-01-21T08:51:32.126194 | 2016-05-16T15:45:37 | 2016-05-16T15:49:05 | 58,941,734 | 1 | 0 | null | 2016-05-16T15:03:28 | 2016-05-16T15:03:28 | null | UTF-8 | C++ | false | false | 19,292 | cpp | #include"hip_runtime.h"
#include<hc.hpp>
#include<grid_launch.h>
#include <hc_math.hpp>
// TODO: Choose whether default is precise math or fast math based on compilation flag.
#ifdef __HCC_ACCELERATOR__
using namespace hc::precise_math;
#endif
__device__ float acosf(float x)
{
return hc::precise_math::acosf(x);
}
__device__ float acoshf(float x)
{
return hc::precise_math::acoshf(x);
}
__device__ float asinf(float x)
{
return hc::precise_math::asinf(x);
}
__device__ float asinhf(float x)
{
return hc::precise_math::asinhf(x);
}
__device__ float atan2f(float y, float x)
{
return hc::precise_math::atan2f(x, y);
}
__device__ float atanf(float x)
{
return hc::precise_math::atanf(x);
}
__device__ float atanhf(float x)
{
return hc::precise_math::atanhf(x);
}
__device__ float cbrtf(float x)
{
return hc::precise_math::cbrtf(x);
}
__device__ float ceilf(float x)
{
return hc::precise_math::ceilf(x);
}
__device__ float copysignf(float x, float y)
{
return hc::precise_math::copysignf(x, y);
}
__device__ float cosf(float x)
{
return hc::precise_math::cosf(x);
}
__device__ float coshf(float x)
{
return hc::precise_math::coshf(x);
}
__device__ float cyl_bessel_i0f(float x);
__device__ float cyl_bessel_i1f(float x);
__device__ float erfcf(float x)
{
return hc::precise_math::erfcf(x);
}
__device__ float erfcinvf(float y);
__device__ float erfcxf(float x);
__device__ float erff(float x)
{
return hc::precise_math::erff(x);
}
__device__ float erfinvf(float y);
__device__ float exp10f(float x)
{
return hc::precise_math::exp10f(x);
}
__device__ float exp2f(float x)
{
return hc::precise_math::exp2f(x);
}
__device__ float expf(float x)
{
return hc::precise_math::expf(x);
}
__device__ float expm1f(float x)
{
return hc::precise_math::expm1f(x);
}
__device__ float fabsf(float x)
{
return hc::precise_math::fabsf(x);
}
__device__ float fdimf(float x, float y)
{
return hc::precise_math::fdimf(x, y);
}
__device__ float fdividef(float x, float y);
__device__ float floorf(float x)
{
return hc::precise_math::floorf(x);
}
__device__ float fmaf(float x, float y, float z)
{
return hc::precise_math::fmaf(x, y, z);
}
__device__ float fmaxf(float x, float y)
{
return hc::precise_math::fmaxf(x, y);
}
__device__ float fminf(float x, float y)
{
return hc::precise_math::fminf(x, y);
}
__device__ float fmodf(float x, float y)
{
return hc::precise_math::fmodf(x, y);
}
__device__ float frexpf(float x, float y);
__device__ float hypotf(float x, float y)
{
return hc::precise_math::hypotf(x, y);
}
__device__ float ilogbf(float x)
{
return hc::precise_math::ilogbf(x);
}
__device__ unsigned isfinite(float a)
{
return hc::precise_math::isfinite(a);
}
__device__ unsigned isinf(float a)
{
return hc::precise_math::isinf(a);
}
__device__ unsigned isnan(float a)
{
return hc::precise_math::isnan(a);
}
__device__ float j0f(float x);
__device__ float j1f(float x);
__device__ float jnf(int n, float x);
__device__ float ldexpf(float x, int exp)
{
return hc::precise_math::ldexpf(x, exp);
}
__device__ float lgammaf(float x);
__device__ long long int llrintf(float x);
__device__ long long int llroundf(float x);
__device__ float log10f(float x)
{
return hc::precise_math::log10f(x);
}
__device__ float log1pf(float x)
{
return hc::precise_math::log1pf(x);
}
__device__ float log2f(float x)
{
return hc::precise_math::log2f(x);
}
__device__ float logbf(float x)
{
return hc::precise_math::logbf(x);
}
__device__ float logf(float x)
{
return hc::precise_math::logf(x);
}
__device__ long int lrintf(float x);
__device__ long int lroundf(float x);
__device__ float modff(float x, float *iptr);
__device__ float nanf(const char* tagp)
{
return hc::precise_math::nanf((int)*tagp);
}
__device__ float nearbyintf(float x)
{
return hc::precise_math::nearbyintf(x);
}
__device__ float nextafterf(float x, float y);
__device__ float norm3df(float a, float b, float c);
__device__ float norm4df(float a, float b, float c, float d);
__device__ float normcdff(float y);
__device__ float normcdfinvf(float y);
__device__ float normf(int dim, const float *a);
__device__ float powf(float x, float y)
{
return hc::precise_math::powf(x, y);
}
__device__ float rcbtrf(float x);
__device__ float remainderf(float x, float y)
{
return hc::precise_math::remainderf(x, y);
}
__device__ float remquof(float x, float y, int *quo);
__device__ float rhypotf(float x, float y);
__device__ float rintf(float x);
__device__ float rnorm3df(float a, float b, float c);
__device__ float rnorm4df(float a, float b, float c, float d);
__device__ float rnormf(int dim, const float* a);
__device__ float roundf(float x)
{
return hc::precise_math::roundf(x);
}
__device__ float scalblnf(float x, long int n);
__device__ float scalbnf(float x, int n)
{
return hc::precise_math::scalbnf(x, n);
}
__device__ unsigned signbit(float a)
{
return hc::precise_math::signbit(a);
}
__device__ void sincosf(float x, float *sptr, float *cptr);
__device__ void sincospif(float x, float *sptr, float *cptr);
__device__ float sinf(float x)
{
return hc::precise_math::sinf(x);
}
__device__ float sinhf(float x)
{
return hc::precise_math::sinhf(x);
}
__device__ float tanf(float x)
{
return hc::precise_math::tanf(x);
}
__device__ float tanhf(float x)
{
return hc::precise_math::tanhf(x);
}
__device__ float tgammaf(float x)
{
return hc::precise_math::tgammaf(x);
}
__device__ float truncf(float x)
{
return hc::precise_math::truncf(x);
}
__device__ float y0f(float x);
__device__ float y1f(float x);
__device__ float ynf(int n, float x);
__device__ float cospif(float x)
{
return hc::precise_math::cospif(x);
}
__device__ float sinpif(float x)
{
return hc::precise_math::sinpif(x);
}
__device__ float sqrtf(float x)
{
return hc::precise_math::sqrtf(x);
}
__device__ float rsqrtf(float x)
{
return hc::precise_math::rsqrtf(x);
}
/*
* Double precision device math functions
*/
__device__ double acos(double x)
{
return hc::precise_math::acos(x);
}
__device__ double acosh(double x)
{
return hc::precise_math::acosh(x);
}
__device__ double asin(double x)
{
return hc::precise_math::asin(x);
}
__device__ double asinh(double x)
{
return hc::precise_math::asinh(x);
}
__device__ double atan(double x)
{
return hc::precise_math::atan(x);
}
__device__ double atan2(double y, double x)
{
return hc::precise_math::atan2(y, x);
}
__device__ double atanh(double x)
{
return hc::precise_math::atanh(x);
}
__device__ double cbrt(double x)
{
return hc::precise_math::cbrt(x);
}
__device__ double ceil(double x)
{
return hc::precise_math::ceil(x);
}
__device__ double copysign(double x, double y)
{
return hc::precise_math::copysign(x, y);
}
__device__ double cos(double x)
{
return hc::precise_math::cos(x);
}
__device__ double cosh(double x)
{
return hc::precise_math::cosh(x);
}
__device__ double cospi(double x)
{
return hc::precise_math::cospi(x);
}
__device__ double erf(double x)
{
return hc::precise_math::erf(x);
}
__device__ double erfc(double x)
{
return hc::precise_math::erfc(x);
}
__device__ double exp(double x)
{
return hc::precise_math::exp(x);
}
__device__ double exp10(double x)
{
return hc::precise_math::exp10(x);
}
__device__ double exp2(double x)
{
return hc::precise_math::exp2(x);
}
__device__ double expm1(double x)
{
return hc::precise_math::expm1(x);
}
__device__ double fabs(double x)
{
return hc::precise_math::fabs(x);
}
__device__ double fdim(double x, double y)
{
return hc::precise_math::fdim(x, y);
}
__device__ double floor(double x)
{
return hc::precise_math::floor(x);
}
__device__ double fma(double x, double y, double z)
{
return hc::precise_math::fma(x, y, z);
}
__device__ double fmax(double x, double y)
{
return hc::precise_math::fmax(x, y);
}
__device__ double fmin(double x, double y)
{
return hc::precise_math::fmin(x, y);
}
__device__ double fmod(double x, double y)
{
return hc::precise_math::fmod(x, y);
}
__device__ double hypot(double x, double y)
{
return hc::precise_math::hypot(x, y);
}
__device__ double ilogb(double x)
{
return hc::precise_math::ilogb(x);
}
__device__ unsigned isfinite(double x)
{
return hc::precise_math::isfinite(x);
}
__device__ unsigned isinf(double x)
{
return hc::precise_math::isinf(x);
}
__device__ unsigned isnan(double x)
{
return hc::precise_math::isnan(x);
}
__device__ double ldexp(double x, int exp)
{
return hc::precise_math::ldexp(x, exp);
}
__device__ double log(double x)
{
return hc::precise_math::log(x);
}
__device__ double log10(double x)
{
return hc::precise_math::log10(x);
}
__device__ double log1p(double x)
{
return hc::precise_math::log1p(x);
}
__device__ double log2(double x)
{
return hc::precise_math::log2(x);
}
__device__ double logb(double x)
{
return hc::precise_math::logb(x);
}
__device__ double nan(const char *tagp)
{
return hc::precise_math::nan((int)*tagp);
}
__device__ double nearbyint(double x)
{
return hc::precise_math::nearbyint(x);
}
__device__ double pow(double x, double y)
{
return hc::precise_math::pow(x, y);
}
__device__ double remainder(double x, double y)
{
return hc::precise_math::remainder(x, y);
}
__device__ double round(double x)
{
return hc::precise_math::round(x);
}
__device__ double rsqrt(double x)
{
return hc::precise_math::rsqrt(x);
}
__device__ double scalbn(double x, int n)
{
return hc::precise_math::scalbn(x, n);
}
__device__ unsigned signbit(double x)
{
return hc::precise_math::signbit(x);
}
__device__ double sin(double x)
{
return hc::precise_math::sin(x);
}
__device__ double sinh(double x)
{
return hc::precise_math::sinh(x);
}
__device__ double sinpi(double x)
{
return hc::precise_math::sinpi(x);
}
__device__ double sqrt(double x)
{
return hc::precise_math::sqrt(x);
}
__device__ double tan(double x)
{
return hc::precise_math::tan(x);
}
__device__ double tanh(double x)
{
return hc::precise_math::tanh(x);
}
__device__ double tgamma(double x)
{
return hc::precise_math::tgamma(x);
}
__device__ double trunc(double x)
{
return hc::precise_math::trunc(x);
}
const int warpSize = 64;
__device__ long long int clock64() { return (long long int)hc::__clock_u64(); };
__device__ clock_t clock() { return (clock_t)hc::__clock_u64(); };
//atomicAdd()
__device__ int atomicAdd(int* address, int val)
{
return hc::atomic_fetch_add(address,val);
}
__device__ unsigned int atomicAdd(unsigned int* address,
unsigned int val)
{
return hc::atomic_fetch_add(address,val);
}
__device__ unsigned long long int atomicAdd(unsigned long long int* address,
unsigned long long int val)
{
return (long long int)hc::atomic_fetch_add((uint64_t*)address,(uint64_t)val);
}
__device__ float atomicAdd(float* address, float val)
{
return hc::atomic_fetch_add(address,val);
}
//atomicSub()
__device__ int atomicSub(int* address, int val)
{
return hc::atomic_fetch_sub(address,val);
}
__device__ unsigned int atomicSub(unsigned int* address,
unsigned int val)
{
return hc::atomic_fetch_sub(address,val);
}
//atomicExch()
__device__ int atomicExch(int* address, int val)
{
return hc::atomic_exchange(address,val);
}
__device__ unsigned int atomicExch(unsigned int* address,
unsigned int val)
{
return hc::atomic_exchange(address,val);
}
__device__ unsigned long long int atomicExch(unsigned long long int* address,
unsigned long long int val)
{
return (long long int)hc::atomic_exchange((uint64_t*)address,(uint64_t)val);
}
__device__ float atomicExch(float* address, float val)
{
return hc::atomic_exchange(address,val);
}
//atomicMin()
__device__ int atomicMin(int* address, int val)
{
return hc::atomic_fetch_min(address,val);
}
__device__ unsigned int atomicMin(unsigned int* address,
unsigned int val)
{
return hc::atomic_fetch_min(address,val);
}
__device__ unsigned long long int atomicMin(unsigned long long int* address,
unsigned long long int val)
{
return (long long int)hc::atomic_fetch_min((uint64_t*)address,(uint64_t)val);
}
//atomicMax()
__device__ int atomicMax(int* address, int val)
{
return hc::atomic_fetch_max(address,val);
}
__device__ unsigned int atomicMax(unsigned int* address,
unsigned int val)
{
return hc::atomic_fetch_max(address,val);
}
__device__ unsigned long long int atomicMax(unsigned long long int* address,
unsigned long long int val)
{
return (long long int)hc::atomic_fetch_max((uint64_t*)address,(uint64_t)val);
}
//atomicCAS()
__device__ int atomicCAS(int* address, int compare, int val)
{
hc::atomic_compare_exchange(address,&compare,val);
return *address;
}
__device__ unsigned int atomicCAS(unsigned int* address,
unsigned int compare,
unsigned int val)
{
hc::atomic_compare_exchange(address,&compare,val);
return *address;
}
__device__ unsigned long long int atomicCAS(unsigned long long int* address,
unsigned long long int compare,
unsigned long long int val)
{
hc::atomic_compare_exchange((uint64_t*)address,(uint64_t*)&compare,(uint64_t)val);
return *address;
}
//atomicAnd()
__device__ int atomicAnd(int* address, int val)
{
return hc::atomic_fetch_and(address,val);
}
__device__ unsigned int atomicAnd(unsigned int* address,
unsigned int val)
{
return hc::atomic_fetch_and(address,val);
}
__device__ unsigned long long int atomicAnd(unsigned long long int* address,
unsigned long long int val)
{
return (long long int)hc::atomic_fetch_and((uint64_t*)address,(uint64_t)val);
}
//atomicOr()
__device__ int atomicOr(int* address, int val)
{
return hc::atomic_fetch_or(address,val);
}
__device__ unsigned int atomicOr(unsigned int* address,
unsigned int val)
{
return hc::atomic_fetch_or(address,val);
}
__device__ unsigned long long int atomicOr(unsigned long long int* address,
unsigned long long int val)
{
return (long long int)hc::atomic_fetch_or((uint64_t*)address,(uint64_t)val);
}
//atomicXor()
__device__ int atomicXor(int* address, int val)
{
return hc::atomic_fetch_xor(address,val);
}
__device__ unsigned int atomicXor(unsigned int* address,
unsigned int val)
{
return hc::atomic_fetch_xor(address,val);
}
__device__ unsigned long long int atomicXor(unsigned long long int* address,
unsigned long long int val)
{
return (long long int)hc::atomic_fetch_xor((uint64_t*)address,(uint64_t)val);
}
__device__ unsigned int test__popc(unsigned int input)
{
return hc::__popcount_u32_b32(input);
}
// integer intrinsic function __poc __clz __ffs __brev
__device__ unsigned int __popc( unsigned int input)
{
return hc::__popcount_u32_b32(input);
}
__device__ unsigned int test__popc(unsigned int input);
__device__ unsigned int __popcll( unsigned long long int input)
{
return hc::__popcount_u32_b64(input);
}
__device__ unsigned int __clz(unsigned int input)
{
return hc::__firstbit_u32_u32( input);
}
__device__ unsigned int __clzll(unsigned long long int input)
{
return hc::__firstbit_u32_u64( input);
}
__device__ unsigned int __clz(int input)
{
return hc::__firstbit_u32_s32( input);
}
__device__ unsigned int __clzll(long long int input)
{
return hc::__firstbit_u32_s64( input);
}
__device__ unsigned int __ffs(unsigned int input)
{
return hc::__lastbit_u32_u32( input)+1;
}
__device__ unsigned int __ffsll(unsigned long long int input)
{
return hc::__lastbit_u32_u64( input)+1;
}
__device__ unsigned int __ffs(int input)
{
return hc::__lastbit_u32_s32( input)+1;
}
__device__ unsigned int __ffsll(long long int input)
{
return hc::__lastbit_u32_s64( input)+1;
}
__device__ unsigned int __brev( unsigned int input)
{
return hc::__bitrev_b32( input);
}
__device__ unsigned long long int __brevll( unsigned long long int input)
{
return hc::__bitrev_b64( input);
}
// warp vote function __all __any __ballot
__device__ int __all( int input)
{
return hc::__all( input);
}
__device__ int __any( int input)
{
if( hc::__any( input)!=0) return 1;
else return 0;
}
__device__ unsigned long long int __ballot( int input)
{
return hc::__ballot( input);
}
// warp shuffle functions
__device__ int __shfl(int input, int lane, int width)
{
return hc::__shfl(input,lane,width);
}
__device__ int __shfl_up(int input, unsigned int lane_delta, int width)
{
return hc::__shfl_up(input,lane_delta,width);
}
__device__ int __shfl_down(int input, unsigned int lane_delta, int width)
{
return hc::__shfl_down(input,lane_delta,width);
}
__device__ int __shfl_xor(int input, int lane_mask, int width)
{
return hc::__shfl_xor(input,lane_mask,width);
}
__device__ float __shfl(float input, int lane, int width)
{
return hc::__shfl(input,lane,width);
}
__device__ float __shfl_up(float input, unsigned int lane_delta, int width)
{
return hc::__shfl_up(input,lane_delta,width);
}
__device__ float __shfl_down(float input, unsigned int lane_delta, int width)
{
return hc::__shfl_down(input,lane_delta,width);
}
__device__ float __shfl_xor(float input, int lane_mask, int width)
{
return hc::__shfl_xor(input,lane_mask,width);
}
__host__ __device__ int min(int arg1, int arg2)
{
return (int)(hc::precise_math::fmin((float)arg1, (float)arg2));
}
__host__ __device__ int max(int arg1, int arg2)
{
return (int)(hc::precise_math::fmax((float)arg1, (float)arg2));
}
//TODO - add a couple fast math operations here, the set here will grow :
__device__ float __cosf(float x) {return hc::fast_math::cosf(x); };
__device__ float __expf(float x) {return hc::fast_math::expf(x); };
__device__ float __frsqrt_rn(float x) {return hc::fast_math::rsqrt(x); };
__device__ float __fsqrt_rd(float x) {return hc::fast_math::sqrt(x); };
__device__ float __fsqrt_rn(float x) {return hc::fast_math::sqrt(x); };
__device__ float __fsqrt_ru(float x) {return hc::fast_math::sqrt(x); };
__device__ float __fsqrt_rz(float x) {return hc::fast_math::sqrt(x); };
__device__ float __log10f(float x) {return hc::fast_math::log10f(x); };
__device__ float __log2f(float x) {return hc::fast_math::log2f(x); };
__device__ float __logf(float x) {return hc::fast_math::logf(x); };
__device__ float __powf(float base, float exponent) {return hc::fast_math::powf(base, exponent); };
__device__ void __sincosf(float x, float *s, float *c) {return hc::fast_math::sincosf(x, s, c); };
__device__ float __sinf(float x) {return hc::fast_math::sinf(x); };
__device__ float __tanf(float x) {return hc::fast_math::tanf(x); };
__device__ float __dsqrt_rd(double x) {return hc::fast_math::sqrt(x); };
__device__ float __dsqrt_rn(double x) {return hc::fast_math::sqrt(x); };
__device__ float __dsqrt_ru(double x) {return hc::fast_math::sqrt(x); };
__device__ float __dsqrt_rz(double x) {return hc::fast_math::sqrt(x); };
| [
"maneesh.gupta@amd.com"
] | maneesh.gupta@amd.com |
911373501a1da7cb5dec203c9bd9156bf783d9d3 | 58760cff187f760b6b6bf1aceccfa803c0d043a9 | /omnn/math/Variable.cpp | 51d3db77a72eae41df3542aea74eb67c686d78a0 | [
"BSD-3-Clause"
] | permissive | leannejdong/openmind | 0ed236ca688d5e620ffc3207135ba2b1c7676727 | 69af704c420ffa89100ecd3709ad9ff39ee4da05 | refs/heads/master | 2022-09-22T07:18:32.206294 | 2020-05-23T20:56:25 | 2020-05-25T01:24:41 | 272,738,597 | 1 | 0 | BSD-3-Clause | 2020-06-16T15:02:37 | 2020-06-16T15:02:36 | null | UTF-8 | C++ | false | false | 6,685 | cpp | //
// Created by Сергей Кривонос on 25.09.17.
//
#include "Variable.h"
#include "Exponentiation.h"
#include "Integer.h"
#include "Modulo.h"
#include "Product.h"
#include "Sum.h"
#include "VarHost.h"
namespace omnn{
namespace math {
Variable::Variable()
: varSetHost(&VarHost::Global<>(), [](auto){})
, varId(VarHost::Global<>().NewVarId())
{
hash = varSetHost->Hash(varId);
maxVaExp=1;
}
Variable::Variable(const Variable& v)
: varSetHost(v.varSetHost)
, varId(v.varSetHost->CloneId(v.varId))
{
hash = v.Hash();
maxVaExp=1;
}
void Variable::SetId(boost::any id) {
varId = id;
hash = varSetHost->Hash(id);
}
Variable::Variable(VarHost::ptr varHost)
: varSetHost(varHost)
{
if(!varHost)
throw "the varHost is mandatory parameter";
maxVaExp=1;
}
Valuable Variable::operator -() const
{
return Product{-1, *this};
}
Valuable& Variable::operator +=(const Valuable& v)
{
auto c = cast(v);
if(c && *c==*this)
{
Become(Product{2, *this});
}
else
Become(Sum{*this, v});
return *this;
}
Valuable& Variable::operator *=(const Valuable& v)
{
if (Same(v)) {
return Become(Exponentiation(*this, 2));
}
else if (Exponentiation::cast(v))
return Become(v**this);
return Become(Product{*this, v});
}
bool Variable::MultiplyIfSimplifiable(const Valuable& v)
{
auto is = v.IsVa();
if (is) {
is = operator==(v);
if (is) {
sq();
}
} else if (v.IsSimple()) {
} else {
auto s = v.IsMultiplicationSimplifiable(*this);
is = s.first;
if (is) {
Become(std::move(s.second));
}
}
return is;
}
std::pair<bool,Valuable> Variable::IsMultiplicationSimplifiable(const Valuable& v) const
{
std::pair<bool,Valuable> is;
is.first = v.IsVa() && operator==(v);
if (is.first) {
is.second = Sq();
} else if (v.IsSimple()) {
} else {
is = v.IsMultiplicationSimplifiable(v);
}
return is;
}
Valuable& Variable::operator /=(const Valuable& v)
{
auto i = cast(v);
if (i && *this==*i)
{
Become(Integer(1));
}
else
{
*this *= 1 / v;
}
return *this;
}
Valuable& Variable::operator %=(const Valuable& v)
{
return Become(Modulo(*this, v));
}
Valuable& Variable::operator^=(const Valuable& v)
{
if(v.IsInt() && v == 0_v)
Become(1_v);
else
Become(Exponentiation(*this, v));
return *this;
}
Valuable& Variable::d(const Variable& x)
{
return Become(1_v);
}
bool Variable::operator <(const Valuable& v) const
{
auto i = cast(v);
if (i)
{
if (varSetHost != i->varSetHost) {
throw "Unable to compare variable sequence numbers from different var hosts. Do you need a lambda for delayed comparision during evaluation? implement then.";
}
return varSetHost->CompareIdsLess(varId, i->varId);
}
// not implemented comparison to this Valuable descent
return base::operator <(v);
}
bool Variable::operator ==(const Valuable& v) const
{
if (v.IsVa())
{
auto i = cast(v);
if (varSetHost != i->varSetHost) {
throw "Unable to compare variable sequence numbers from different var hosts. Do you need a lambda for delayed comparision during evaluation? implement then.";
}
return hash == v.Hash()
&& varSetHost->CompareIdsEqual(varId, i->varId);
}
else
{ // compare with non-va
return false;
}
// not implemented comparison to this Valuable descent
return base::operator ==(v);
}
std::ostream& Variable::print(std::ostream& out) const
{
return varSetHost->print(out, varId);
}
bool Variable::IsComesBefore(const Valuable& v) const
{
auto mve = getMaxVaExp();
auto vmve = v.getMaxVaExp();
auto is = mve > vmve;
if (mve != vmve)
{}
else if (v.IsVa())
is = base::IsComesBefore(v);
else if (v.IsProduct())
is = Product{*this}.IsComesBefore(v);
else
is = !v.FindVa();
return is;
}
void Variable::CollectVa(std::set<Variable>& s) const
{
s.insert(*this);
}
void Variable::CollectVaNames(std::map<std::string, Variable>& s) const{
s[str()] = *this;
}
bool Variable::eval(const std::map<Variable, Valuable>& with) {
auto it = with.find(*this);
auto evaluated = it != with.end();
if(evaluated) {
auto c = it->second;
Become(std::move(c));
}
return evaluated;
}
void Variable::Eval(const Variable& va, const Valuable& v)
{
if(va==*this)
{
auto copy = v;
Become(std::move(copy));
}
}
const Valuable::vars_cont_t& Variable::getCommonVars() const
{
vars[*this] = 1_v;
if(vars.size()>1)
{
vars.clear();
getCommonVars();
}
return vars;
}
Valuable Variable::InCommonWith(const Valuable& v) const
{
auto c = 1_v;
if (v.IsProduct()) {
c = v.InCommonWith(*this);
} else if (v.IsExponentiation()) {
auto e = Exponentiation::cast(v);
if (e->getBase() == *this) {
if (e->getExponentiation().IsInt()) {
if (e->getExponentiation() > 0) {
c = *this;
}
} else {
IMPLEMENT
}
}
} else if (v.IsVa()) {
if (*this == v)
c = v;
} else if (v.IsInt() || v.IsSimpleFraction()) {
} else {
IMPLEMENT
}
return c;
}
Valuable Variable::operator()(const Variable& va, const Valuable& augmentation) const
{
if (*this == va) {
return {augmentation};
}
else
IMPLEMENT
}
}}
| [
"sergeikrivonos@gmail.com"
] | sergeikrivonos@gmail.com |
6712a7873de56d3bfb5b8f6355987e86e4a71fd8 | 2d89d3b317d11b0dc61ff94e799a0f6a77966317 | /Bacon/Vertex.h | f2fca85471048d5a9cf2cad5431fb4b226444edd | [] | no_license | CramsGames/Bacon | 756e8edb8a31a570e688ab747615dad50c44665d | 668ff5e63911ba87f52d91affee7304bba26adff | refs/heads/master | 2021-07-11T12:07:03.152802 | 2017-10-14T10:29:04 | 2017-10-14T10:29:04 | 106,472,291 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 239 | h | #pragma once
#include <glm\glm.hpp>
struct Vertex {
public:
Vertex (glm::vec3 position = glm::vec3 (), glm::vec2 texcoord = glm::vec2 (), glm::vec3 normal = glm::vec3 ());
glm::vec3 position;
glm::vec2 texcoord;
glm::vec3 normal;
}; | [
"craigc@cramsgames.co.uk"
] | craigc@cramsgames.co.uk |
9d89455863c86d1c3f1dc1daa98170766cab6373 | 0bf4e9718ac2e2845b2227d427862e957701071f | /tc/tco07/SortMaterials.cpp | 2f0b8d39b42e4d5da5434307cab2cc2a30009a3d | [] | no_license | unjambonakap/prog_contest | adfd6552d396f4845132f3ad416f98d8a5c9efb8 | e538cf6a1686539afb1d06181252e9b3376e8023 | refs/heads/master | 2022-10-18T07:33:46.591777 | 2022-09-30T14:44:47 | 2022-09-30T15:00:33 | 145,024,455 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,865 | cpp | // BEGIN CUT HERE
// END CUT HERE
#line 5 "SortMaterials.cpp"
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <algorithm>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cassert>
#include <climits>
//#include <ext/hash_map>
using namespace std;
using namespace __gnu_cxx;
#define REP(i,n) for(int i = 0; i < int(n); ++i)
#define REPV(i, n) for (int i = (n) - 1; (int)i >= 0; --i)
#define FOR(i, a, b) for(int i = (int)(a); i <= (int)(b); ++i)
#define FORV(i, a, b) for(int i = (int)(a); i >= (int)(b); --i)
#define FE(i,t) for (typeof((t).begin())i=(t).begin();i!=(t).end();++i)
#define FEV(i,t) for (typeof((t).rbegin())i=(t).rbegin();i!=(t).rend();++i)
#define SZ(a) (int((a).size()))
#define two(x) (1 << (x))
#define twoll(x) (1LL << (x))
#define ALL(a) (a).begin(), (a).end()
#define CLR(a) (a).clear()
#define pb push_back
#define PF push_front
#define ST first
#define ND second
#define MP(x,y) make_pair(x, y)
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef vector<int> vi;
typedef vector<string> vs;
typedef queue<int> qi;
template<class T> void checkmin(T &a, T b){if (b<a)a=b;}
template<class T> void checkmax(T &a, T b){if (b>a)a=b;}
template<class T> void out(T t[], int n){REP(i, n)cout<<t[i]<<" "; cout<<endl;}
template<class T> void out(vector<T> t, int n=-1){for (int i=0; i<(n==-1?t.size():n); ++i) cout<<t[i]<<" "; cout<<endl;}
inline int count_bit(int n){return (n == 0)?0:1+count_bit(n&(n-1));}
inline bool bit_set(int a, int b){return (a&two(b));}
inline int low_bit(int n){return (n^n-1)&n;}
inline int ctz(int n){return (n==0?-1:(n==1?0:ctz(n>>1)+1));}
int toInt(string s){int a; istringstream(s)>>a; return a;}
string toStr(int a){ostringstream os; os<<a; return os.str();}
class SortMaterials {
public:
int totalVolume(vector <string> data, vector <string> requirements) {
int a, b; string s;
int ti;
string ts;
int res=0;
FE(it, data){
istringstream ss(*it);
ss>>a>>b>>s;
bool ok=true;
FE(ita, requirements){
string sa=*ita, sb;
REP(i, sa.length()) if (sa[i]=='=') sa[i]=' ';
istringstream ssa(sa);
ssa>>sb;
if (sb=="EDGE"){
ssa>>ti;
if (ti!=a){ok=false; break;}
}else if (sb=="QUALITY"){
ssa>>ti;
if (b<ti){ok=false; break;}
}else{
ssa>>ts;
if (ts!=s){ok=false; break;}
}
}
if (ok) res+=a*a*a;
}
return res;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { string Arr0[] = {"1 20 red", "2 30 blue", "10 1 green"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 1009; verify_case(0, Arg2, totalVolume(Arg0, Arg1)); }
void test_case_1() { string Arr0[] = {"1 20 red", "2 30 blue", "10 1 green"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"QUALITY=20"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 9; verify_case(1, Arg2, totalVolume(Arg0, Arg1)); }
void test_case_2() { string Arr0[] = {"1 20 red", "2 30 blue", "10 1 green", "5 5 red", "5 6 red"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"COLOR=red", "EDGE=5"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 250; verify_case(2, Arg2, totalVolume(Arg0, Arg1)); }
void test_case_3() { string Arr0[] = {"1 20 red", "2 30 blue", "10 1 green", "5 5 red", "5 6 red"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"EDGE=1", "EDGE=5"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 0; verify_case(3, Arg2, totalVolume(Arg0, Arg1)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main(){
SortMaterials ___test;
___test.run_test(-1);
}
// END CUT HERE
| [
"benoit@uuu.com"
] | benoit@uuu.com |
bdcd25cd399085686666b478683e5493088c7295 | 1c6a7125c8ea024050045fb18a685daadcfbcb0f | /codeforces/random/CF 509 A Maximum in Table.cpp | fed5fa6fb0e5b11f6904022140913db85fc1ec4d | [] | no_license | HurayraIIT/competitive-programming | 0e2f40cf1cae76129eac0cd8402b62165a6c29e4 | 3b9bc3066c70284cddab0f3e39ffc3e9cd59225f | refs/heads/master | 2022-12-10T18:33:10.405727 | 2022-12-06T13:15:15 | 2022-12-06T13:15:15 | 236,779,058 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 600 | cpp | /* Name: Abu Hurayra
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
#define pi acos(-1.0)
#define endl '\n'
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
int val(int r , int c)
{
if(r==1 || c==1) return 1 ;
else return val(r-1,c)+val(r,c-1);
}
int main()
{
off;
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n ;
cin >> n ;
cout << val(n,n) << endl;
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
8116032639f4180fe1acbd8a9c2ebc3687827a46 | 03b5b626962b6c62fc3215154b44bbc663a44cf6 | /src/message/code_message.cpp | 450f3f75a0a70cdd12dc8e20edd57c626c50437d | [] | no_license | haochenprophet/iwant | 8b1f9df8ee428148549253ce1c5d821ece0a4b4c | 1c9bd95280216ee8cd7892a10a7355f03d77d340 | refs/heads/master | 2023-06-09T11:10:27.232304 | 2023-05-31T02:41:18 | 2023-05-31T02:41:18 | 67,756,957 | 17 | 5 | null | 2018-08-11T16:37:37 | 2016-09-09T02:08:46 | C++ | UTF-8 | C++ | false | false | 441 | cpp | #include "code_message.h"
int Ccode_message::my_init(void *p)
{
this->name = "Ccode_message";
this->alias = "code_message";
return 0;
}
Ccode_message::Ccode_message()
{
this->my_init();
}
Ccode_message::~Ccode_message()
{
}
#ifndef CODE_MESSAGE_TEST
#define CODE_MESSAGE_TEST 0//1
#endif
#if CODE_MESSAGE_TEST
#include "all_h_include.h"
int main(int argc, char *argv[])
{
std::cout << "CODE_MESSAGE_TEST\n\n";
return 0;
}
#endif | [
"hao.chen@prophet.net.cn"
] | hao.chen@prophet.net.cn |
d773d2d24c7bdbe1c6b74552008da761bf3524be | 86fed93848ee8d6cee3f4dc2997865b721f18165 | /Code Design and Data Structures/Assignments/aieBootstrap-master/Binary Tree/BinaryTree.cpp | 42cb5fa0700f822e012da269e9a31b072835eb1b | [
"MIT"
] | permissive | Sorry-Im-Salty/AIE-2019 | c92facc8aff595fc499f1ba460d9e5cbec21b3a1 | 0cf11a754c597d5aa2222df610cf7a9a6dac6bbd | refs/heads/master | 2020-05-07T18:34:49.582673 | 2019-09-10T06:52:57 | 2019-09-10T06:52:57 | 180,077,077 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,779 | cpp | #include "BinaryTree.h"
BinaryTree::BinaryTree() {
m_pRoot = nullptr;
}
BinaryTree::~BinaryTree() {
}
void BinaryTree::draw(aie::Renderer2D* renderer, TreeNode* selected) {
draw(renderer, m_pRoot, 640, 680, 640, selected);
}
void BinaryTree::draw(aie::Renderer2D* renderer, TreeNode* pNode, int x, int y, int horizontalSpacing, TreeNode* selected) {
horizontalSpacing /= 2;
if (pNode) {
if (pNode->hasLeft()) {
renderer->setRenderColour(1, 0, 0);
renderer->drawLine(x, y, x - horizontalSpacing, y - 80);
draw(renderer, pNode->getLeft(), x - horizontalSpacing, y - 80, horizontalSpacing, selected);
}
if (pNode->hasRight()) {
renderer->setRenderColour(1, 0, 0);
renderer->drawLine(x, y, x + horizontalSpacing, y - 80);
draw(renderer, pNode->getRight(), x + horizontalSpacing, y - 80, horizontalSpacing, selected);
}
pNode->draw(renderer, x, y, (selected == pNode));
}
}
bool BinaryTree::isEmpty() const {
if (m_pRoot == nullptr)
return true;
else
return false;
}
void BinaryTree::insert(int a_nValue) {
TreeNode* newNode = new TreeNode(a_nValue);
if (isEmpty() == true) {
m_pRoot = newNode;
return;
}
TreeNode* currNode = m_pRoot;
TreeNode* parentNode = nullptr;
while (currNode != nullptr) {
if (newNode->getData() < currNode->getData()) {
if (currNode->getLeft() == nullptr) {
currNode->setLeft(newNode);
break;
}
else {
parentNode = currNode;
currNode = currNode->getLeft();
}
}
if (newNode->getData() > currNode->getData()) {
if (currNode->getRight() == nullptr) {
currNode->setRight(newNode);
break;
}
else {
parentNode = currNode;
currNode = currNode->getRight();
}
}
if (newNode->getData() == currNode->getData()) {
break;
}
}
}
void BinaryTree::remove(int a_nValue) {
removePrivate(a_nValue, m_pRoot);
}
void BinaryTree::removePrivate(int a_nValue, TreeNode* Parent) {
if (m_pRoot != nullptr) {
if (m_pRoot->getData() == a_nValue) {
remRootMatch();
}
else {
if (a_nValue < Parent->getData() && Parent->getLeft() != nullptr) {
Parent->getLeft()->getData() == a_nValue ?
remMatch(Parent, Parent->getLeft(), true) :
removePrivate(a_nValue, Parent->getLeft());
}
else if (a_nValue > Parent->getData() && Parent->getRight() != nullptr) {
Parent->getRight()->getData() == a_nValue ?
remMatch(Parent, Parent->getRight(), false) :
removePrivate(a_nValue, Parent->getRight());
}
else {
return;
}
}
}
else {
return;
}
}
void BinaryTree::remRootMatch() {
if (m_pRoot != nullptr) {
TreeNode* delPtr = m_pRoot;
int rootKey = m_pRoot->getData();
int smallestRightSubTree;
// 0 children
if (m_pRoot->getLeft() == nullptr && m_pRoot->getRight() == nullptr) {
m_pRoot = nullptr;
delete delPtr;
}
// 1 child
else if (m_pRoot->getLeft() == nullptr && m_pRoot->getRight() != nullptr) {
m_pRoot = m_pRoot->getRight();
delPtr->setRight(nullptr);
delete delPtr;
}
else if (m_pRoot->getLeft() != nullptr && m_pRoot->getRight() == nullptr) {
m_pRoot = m_pRoot->getLeft();
delPtr->setLeft(nullptr);
delete delPtr;
}
// 2 Children
else {
smallestRightSubTree = findSmallestPrivate(m_pRoot->getRight());
removePrivate(smallestRightSubTree, m_pRoot);
m_pRoot->setData(smallestRightSubTree);
}
}
else {
return;
}
}
void BinaryTree::remMatch(TreeNode* parent, TreeNode* match, bool left) {
if (m_pRoot != nullptr) {
TreeNode* delPtr;
int matchKey = match->getData();
int smallestInRightSubtree;
// 0 children
if (match->getLeft() == nullptr && match->getRight() == nullptr) {
delPtr = match;
left == true ? parent->setLeft(nullptr) : parent->setRight(nullptr);
delete delPtr;
}
// 1 child
else if (match->getLeft() == nullptr && match->getRight() != nullptr) {
left == true ? parent->setLeft(match->getRight()) : parent->setRight(match->getRight());
match->setRight(nullptr);
delPtr = match;
delete delPtr;
}
else if (match->getLeft() != nullptr && match->getRight() == nullptr) {
left == true ? parent->setLeft(match->getLeft()) : parent->setRight(match->getLeft());
match->setLeft(nullptr);
delPtr = match;
delete delPtr;
}
// 2 children
else {
smallestInRightSubtree = findSmallestPrivate(match->getRight());
removePrivate(smallestInRightSubtree, match);
match->setData(smallestInRightSubtree);
}
}
else {
return;
}
}
int BinaryTree::findSmallestPrivate(TreeNode* Ptr) {
if (m_pRoot == nullptr) {
return -1000;
}
else {
if (Ptr->getLeft() != nullptr) {
return findSmallestPrivate(Ptr->getLeft());
}
else {
return Ptr->getData();
}
}
}
bool BinaryTree::findNode(int a_nSearchValue, TreeNode** ppOutNode, TreeNode** ppOutParent) {
TreeNode* searchNode = new TreeNode(a_nSearchValue);
TreeNode* currNode = m_pRoot;
TreeNode* parentNode = nullptr;
while (currNode != nullptr) {
if (searchNode->getData() == currNode->getData()) {
*ppOutNode = currNode;
*ppOutParent = parentNode;
return true;
}
else
if (searchNode->getData() < currNode->getData()) {
parentNode = currNode;
currNode = currNode->getLeft();
}
else {
parentNode = currNode;
currNode = currNode->getRight();
}
}
*ppOutNode = nullptr;
*ppOutParent = nullptr;
return false;
}
TreeNode* BinaryTree::find(int a_nValue) {
TreeNode* ppOutNode = nullptr;
TreeNode* ppOutParent = nullptr;
TreeNode* currNode = m_pRoot;
findNode(a_nValue, &ppOutNode, &ppOutParent);
return ppOutNode;
} | [
"47731654+Sorry-Im-Salty@users.noreply.github.com"
] | 47731654+Sorry-Im-Salty@users.noreply.github.com |
67a497eac284e1d4da7cf02aea0c06ab1f79353c | d7d73f1fe572fcc9ef3615c35caa94550304ca48 | /RoboCore/00.Curso Arduino para Iniciantes - RoboCore/Exemplo_06_Dimmer/Exemplo_06_Dimmer.ino | 9dfe60bbeceb99a568fb5f97a32f44200ed90ea5 | [] | no_license | Jcfurtado/ArduinoProjects | a2740ea17e27608d4c10d3297e27bccf7d41999a | 0b4fdb1c76604a02279dcc1290627811cb4ef169 | refs/heads/master | 2020-05-18T09:18:02.342189 | 2019-04-30T19:40:00 | 2019-04-30T19:40:00 | 184,321,012 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,146 | ino |
/*************************************************************************
** **
** CURSO ARDUINO PARA INICIANTES - ROBOCORE **
** **
** Exemplo 06: Dimmer **
** **
*************************************************************************/
int led = 11; // Pino no qual o LED está conectado, no caso 11
int pot = A0; // Pino no qual o potenciômetro está conectado, no caso A0
int saida = 0; // Valor que será colocado no PWM, varia de 0 a 255
void setup() {
// não precisamos colocar nada no setup, para uma saída analógica não precisa configurar.
}
void loop() {
saida = analogRead(pot); // Lê o valor da entrada analógica (0 – 1023)
saida = map(saida, 0, 1023, 0, 255); // Converte o valor da saída para valores entre 0-255
analogWrite(led, saida); // Acende o LED com intensidade proporcional ao potenciômetro
}
| [
"cardozofurtado@gmail.com"
] | cardozofurtado@gmail.com |
b4fb7a348eb48272f835fa27dcb21d744ed4746e | bfa0562c391fa4019fcd49f0b0aafb4611b696a9 | /net/TimerQueue.h | 729cff1ca23996569c287630a22786600ccf3c47 | [] | no_license | Th824/MySimpleWebServer | 193ffb56097c0f86f031dfa9cf04d2452b2dd460 | bf6d373a8208db8f88c7cdf73abf11c8857f08ee | refs/heads/master | 2021-04-17T07:18:09.570288 | 2020-05-12T09:41:05 | 2020-05-12T09:41:05 | 249,424,255 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,834 | h | # pragma once
# include <vector>
# include <mutex>
# include <set>
# include <atomic>
# include "base/Timestamp.h"
# include "base/Callback.h"
# include "base/noncopyable.h"
# include "Channel.h"
class EventLoop;
class Timer;
class TimerID;
class TimerQueue : noncopyable {
public:
explicit TimerQueue(EventLoop* loop);
~TimerQueue();
TimerID addTimer(TimerCallback cb, Timestamp when, double interval);
void cancel(TimerID timerID);
private:
// 表示时间戳和定时器的二元组
using Entry = std::pair<Timestamp, Timer*>;
// 用集合来表示二元组的集合
using TimerList = std::set<Entry>;
// 表示的是Timer及其对应的存活时间?
using ActiveTimer = std::pair<Timer*, std::int64_t>;
// 依然存活的Timer的集合
using ActiveTimerSet = std::set<ActiveTimer>;
//
void addTimerInLoop(Timer* timer);
void cancelInLoop(TimerID timerID);
// 可读回调函数,其实就是Timer过期处理函数
void handleRead();
// 获取过期的Entry
std::vector<Entry> getExpired(Timestamp now);
// 对过期的Entry进行重置
void reset(const std::vector<Entry>& expired, Timestamp now);
// 插入传入的timer
bool insert(Timer* timer);
EventLoop* loop_;
// 只有一个timerfd
const int timerfd_;
Channel timerfdChannel_;
// 表示当前存活的定时器集合,集合的元素是pair<Timestamp, Timer*>
// 表示在该集合中,元素是按照Timestamp进行排序的,便于定位到超时的定时器
TimerList timers_;
// 表示当前存活的定时器集合,且集合的元素是pair<Timer*, std::int64_t>
// 表示在该集合中,元素是按照timer的地址排序的
ActiveTimerSet activeTimers_;
std::atomic_bool callingExpiredTimers_; // atomic
// 表示注销的定时器集合
ActiveTimerSet cancelingTimers_;
}; | [
"wuzihui64@gmail.com"
] | wuzihui64@gmail.com |
e468968ba4ccf26f240d788eed778d705ac6da30 | 27974ef06083b306028ade82a6c174377ab649fd | /period/freshman/contest/Mission X+2/E.cpp | ccd7c2c70dbb9c3e5836dbca8dc7d480f087d970 | [] | no_license | lightyears1998/a-gzhu-coder | 6ba7fe23f663ee538c162927cfecb57e20bc0dbc | b882a2e8395155db0a57d59e7c5899386c5eb717 | refs/heads/master | 2021-06-05T05:33:14.988053 | 2020-05-23T12:52:57 | 2020-05-23T12:52:57 | 100,114,337 | 14 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,130 | cpp | #include <bits/stdc++.h>
using namespace std;
const char peo[4][4] {".O.", "/|\\", "(.)"};
int h, w;
bool take[150][150];
char pic[150][150];
void dye(int x, int y)
{
for (int i=0; i<3; ++i) {
for (int j=0; j<3; ++j) {
if (peo[i][j] == pic[x+i][y+j]) {
take[x+i][y+j] = true;
}
}
}
}
int check()
{
int ans = 0;
for (int i=5; i<=h+4; ++i) {
for (int j=5; j<=w+4; ++j) {
if (take[i][j]) continue;
if (pic[i][j] == 'O') {
++ans; dye(i, j-1);
}
if (pic[i][j] == '/') {
++ans; dye(i-1, j);
}
if (pic[i][j] == '|') {
++ans; dye(i-1, j-1);
}
if (pic[i][j] == '\\') {
++ans; dye(i-1, j-2);
}
if (pic[i][j] == '(') {
++ans; dye(i-2, j);
}
if (pic[i][j] == ')') {
++ans; dye(i-2, j-2);
}
}
}
return ans;
}
int main()
{
int t; scanf("%d", &t);
while (t--)
{
scanf("%d%d", &h, &w);
memset(take, 0, sizeof(take));
memset(pic, 0, sizeof(pic));
for (int i=5; i<=h+4; ++i) {
for (int j=5; j<=w+4; ++j) {
scanf(" %c", &pic[i][j]);
}
}
printf("%d\n", check());
}
}
| [
"lightyears1998@hotmail.com"
] | lightyears1998@hotmail.com |
28c0959ee33fb7a161bdc63e76c15b22faaa6826 | 67ce8ff142f87980dba3e1338dabe11af50c5366 | /opencv/src/opencv/modules/imgproc/src/filter.simd.hpp | 7c257f3c5003d01250723bc0f609b6678d36a13a | [
"Apache-2.0"
] | permissive | checksummaster/depthmovie | 794ff1c5a99715df4ea81abd4198e8e4e68cc484 | b0f1c233afdaeaaa5546e793a3e4d34c4977ca10 | refs/heads/master | 2023-04-19T01:45:06.237313 | 2021-04-30T20:34:16 | 2021-04-30T20:34:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 141,817 | hpp | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include "precomp.hpp"
#include "opencv2/core/hal/intrin.hpp"
#include "filter.hpp"
#if defined(CV_CPU_BASELINE_MODE)
#if IPP_VERSION_X100 >= 710
#define USE_IPP_SEP_FILTERS 1
#else
#undef USE_IPP_SEP_FILTERS
#endif
#endif
/****************************************************************************************\
Base Image Filter
\****************************************************************************************/
namespace cv {
CV_CPU_OPTIMIZATION_NAMESPACE_BEGIN
// forward declarations
int FilterEngine__start(FilterEngine& this_, const Size &_wholeSize, const Size &sz, const Point &ofs);
int FilterEngine__proceed(FilterEngine& this_, const uchar* src, int srcstep, int count,
uchar* dst, int dststep);
void FilterEngine__apply(FilterEngine& this_, const Mat& src, Mat& dst, const Size& wsz, const Point& ofs);
Ptr<BaseRowFilter> getLinearRowFilter(
int srcType, int bufType,
const Mat& kernel, int anchor,
int symmetryType);
Ptr<BaseColumnFilter> getLinearColumnFilter(
int bufType, int dstType,
const Mat& kernel, int anchor,
int symmetryType, double delta,
int bits);
Ptr<BaseFilter> getLinearFilter(
int srcType, int dstType,
const Mat& filter_kernel, Point anchor,
double delta, int bits);
#ifndef CV_CPU_OPTIMIZATION_DECLARATIONS_ONLY
typedef int CV_DECL_ALIGNED(1) unaligned_int;
#define VEC_ALIGN CV_MALLOC_ALIGN
int FilterEngine__start(FilterEngine& this_, const Size &_wholeSize, const Size &sz, const Point &ofs)
{
CV_INSTRUMENT_REGION();
int i, j;
this_.wholeSize = _wholeSize;
this_.roi = Rect(ofs, sz);
CV_Assert( this_.roi.x >= 0 && this_.roi.y >= 0 && this_.roi.width >= 0 && this_.roi.height >= 0 &&
this_.roi.x + this_.roi.width <= this_.wholeSize.width &&
this_.roi.y + this_.roi.height <= this_.wholeSize.height );
int esz = (int)getElemSize(this_.srcType);
int bufElemSize = (int)getElemSize(this_.bufType);
const uchar* constVal = !this_.constBorderValue.empty() ? &this_.constBorderValue[0] : 0;
int _maxBufRows = std::max(this_.ksize.height + 3,
std::max(this_.anchor.y,
this_.ksize.height-this_.anchor.y-1)*2+1);
if (this_.maxWidth < this_.roi.width || _maxBufRows != (int)this_.rows.size() )
{
this_.rows.resize(_maxBufRows);
this_.maxWidth = std::max(this_.maxWidth, this_.roi.width);
int cn = CV_MAT_CN(this_.srcType);
this_.srcRow.resize(esz*(this_.maxWidth + this_.ksize.width - 1));
if (this_.columnBorderType == BORDER_CONSTANT)
{
CV_Assert(constVal != NULL);
this_.constBorderRow.resize(getElemSize(this_.bufType)*(this_.maxWidth + this_.ksize.width - 1 + VEC_ALIGN));
uchar *dst = alignPtr(&this_.constBorderRow[0], VEC_ALIGN);
int n = (int)this_.constBorderValue.size();
int N = (this_.maxWidth + this_.ksize.width - 1)*esz;
uchar *tdst = this_.isSeparable() ? &this_.srcRow[0] : dst;
for( i = 0; i < N; i += n )
{
n = std::min( n, N - i );
for(j = 0; j < n; j++)
tdst[i+j] = constVal[j];
}
if (this_.isSeparable())
(*this_.rowFilter)(&this_.srcRow[0], dst, this_.maxWidth, cn);
}
int maxBufStep = bufElemSize*(int)alignSize(this_.maxWidth +
(!this_.isSeparable() ? this_.ksize.width - 1 : 0), VEC_ALIGN);
this_.ringBuf.resize(maxBufStep*this_.rows.size()+VEC_ALIGN);
}
// adjust bufstep so that the used part of the ring buffer stays compact in memory
this_.bufStep = bufElemSize*(int)alignSize(this_.roi.width + (!this_.isSeparable() ? this_.ksize.width - 1 : 0), VEC_ALIGN);
this_.dx1 = std::max(this_.anchor.x - this_.roi.x, 0);
this_.dx2 = std::max(this_.ksize.width - this_.anchor.x - 1 + this_.roi.x + this_.roi.width - this_.wholeSize.width, 0);
// recompute border tables
if (this_.dx1 > 0 || this_.dx2 > 0)
{
if (this_.rowBorderType == BORDER_CONSTANT )
{
CV_Assert(constVal != NULL);
int nr = this_.isSeparable() ? 1 : (int)this_.rows.size();
for( i = 0; i < nr; i++ )
{
uchar* dst = this_.isSeparable() ? &this_.srcRow[0] : alignPtr(&this_.ringBuf[0], VEC_ALIGN) + this_.bufStep*i;
memcpy(dst, constVal, this_.dx1*esz);
memcpy(dst + (this_.roi.width + this_.ksize.width - 1 - this_.dx2)*esz, constVal, this_.dx2*esz);
}
}
else
{
int xofs1 = std::min(this_.roi.x, this_.anchor.x) - this_.roi.x;
int btab_esz = this_.borderElemSize, wholeWidth = this_.wholeSize.width;
int* btab = (int*)&this_.borderTab[0];
for( i = 0; i < this_.dx1; i++ )
{
int p0 = (borderInterpolate(i-this_.dx1, wholeWidth, this_.rowBorderType) + xofs1)*btab_esz;
for( j = 0; j < btab_esz; j++ )
btab[i*btab_esz + j] = p0 + j;
}
for( i = 0; i < this_.dx2; i++ )
{
int p0 = (borderInterpolate(wholeWidth + i, wholeWidth, this_.rowBorderType) + xofs1)*btab_esz;
for( j = 0; j < btab_esz; j++ )
btab[(i + this_.dx1)*btab_esz + j] = p0 + j;
}
}
}
this_.rowCount = this_.dstY = 0;
this_.startY = this_.startY0 = std::max(this_.roi.y - this_.anchor.y, 0);
this_.endY = std::min(this_.roi.y + this_.roi.height + this_.ksize.height - this_.anchor.y - 1, this_.wholeSize.height);
if (this_.columnFilter)
this_.columnFilter->reset();
if (this_.filter2D)
this_.filter2D->reset();
return this_.startY;
}
int FilterEngine__proceed(FilterEngine& this_, const uchar* src, int srcstep, int count,
uchar* dst, int dststep)
{
CV_INSTRUMENT_REGION();
CV_DbgAssert(this_.wholeSize.width > 0 && this_.wholeSize.height > 0 );
const int *btab = &this_.borderTab[0];
int esz = (int)getElemSize(this_.srcType), btab_esz = this_.borderElemSize;
uchar** brows = &this_.rows[0];
int bufRows = (int)this_.rows.size();
int cn = CV_MAT_CN(this_.bufType);
int width = this_.roi.width, kwidth = this_.ksize.width;
int kheight = this_.ksize.height, ay = this_.anchor.y;
int _dx1 = this_.dx1, _dx2 = this_.dx2;
int width1 = this_.roi.width + kwidth - 1;
int xofs1 = std::min(this_.roi.x, this_.anchor.x);
bool isSep = this_.isSeparable();
bool makeBorder = (_dx1 > 0 || _dx2 > 0) && this_.rowBorderType != BORDER_CONSTANT;
int dy = 0, i = 0;
src -= xofs1*esz;
count = std::min(count, this_.remainingInputRows());
CV_Assert(src && dst && count > 0);
for(;; dst += dststep*i, dy += i)
{
int dcount = bufRows - ay - this_.startY - this_.rowCount + this_.roi.y;
dcount = dcount > 0 ? dcount : bufRows - kheight + 1;
dcount = std::min(dcount, count);
count -= dcount;
for( ; dcount-- > 0; src += srcstep )
{
int bi = (this_.startY - this_.startY0 + this_.rowCount) % bufRows;
uchar* brow = alignPtr(&this_.ringBuf[0], VEC_ALIGN) + bi*this_.bufStep;
uchar* row = isSep ? &this_.srcRow[0] : brow;
if (++this_.rowCount > bufRows)
{
--this_.rowCount;
++this_.startY;
}
memcpy( row + _dx1*esz, src, (width1 - _dx2 - _dx1)*esz );
if( makeBorder )
{
if( btab_esz*(int)sizeof(int) == esz )
{
const int* isrc = (const int*)src;
int* irow = (int*)row;
for( i = 0; i < _dx1*btab_esz; i++ )
irow[i] = isrc[btab[i]];
for( i = 0; i < _dx2*btab_esz; i++ )
irow[i + (width1 - _dx2)*btab_esz] = isrc[btab[i+_dx1*btab_esz]];
}
else
{
for( i = 0; i < _dx1*esz; i++ )
row[i] = src[btab[i]];
for( i = 0; i < _dx2*esz; i++ )
row[i + (width1 - _dx2)*esz] = src[btab[i+_dx1*esz]];
}
}
if( isSep )
(*this_.rowFilter)(row, brow, width, CV_MAT_CN(this_.srcType));
}
int max_i = std::min(bufRows, this_.roi.height - (this_.dstY + dy) + (kheight - 1));
for( i = 0; i < max_i; i++ )
{
int srcY = borderInterpolate(this_.dstY + dy + i + this_.roi.y - ay,
this_.wholeSize.height, this_.columnBorderType);
if( srcY < 0 ) // can happen only with constant border type
brows[i] = alignPtr(&this_.constBorderRow[0], VEC_ALIGN);
else
{
CV_Assert(srcY >= this_.startY);
if( srcY >= this_.startY + this_.rowCount)
break;
int bi = (srcY - this_.startY0) % bufRows;
brows[i] = alignPtr(&this_.ringBuf[0], VEC_ALIGN) + bi*this_.bufStep;
}
}
if( i < kheight )
break;
i -= kheight - 1;
if (isSep)
(*this_.columnFilter)((const uchar**)brows, dst, dststep, i, this_.roi.width*cn);
else
(*this_.filter2D)((const uchar**)brows, dst, dststep, i, this_.roi.width, cn);
}
this_.dstY += dy;
CV_Assert(this_.dstY <= this_.roi.height);
return dy;
}
void FilterEngine__apply(FilterEngine& this_, const Mat& src, Mat& dst, const Size& wsz, const Point& ofs)
{
CV_INSTRUMENT_REGION();
CV_DbgAssert(src.type() == this_.srcType && dst.type() == this_.dstType);
FilterEngine__start(this_, wsz, src.size(), ofs);
int y = this_.startY - ofs.y;
FilterEngine__proceed(this_,
src.ptr() + y*src.step,
(int)src.step,
this_.endY - this_.startY,
dst.ptr(),
(int)dst.step );
}
struct RowNoVec
{
RowNoVec() {}
RowNoVec(const Mat&) {}
int operator()(const uchar*, uchar*, int, int) const { return 0; }
};
struct ColumnNoVec
{
ColumnNoVec() {}
ColumnNoVec(const Mat&, int, int, double) {}
int operator()(const uchar**, uchar*, int) const { return 0; }
};
struct SymmRowSmallNoVec
{
SymmRowSmallNoVec() {}
SymmRowSmallNoVec(const Mat&, int) {}
int operator()(const uchar*, uchar*, int, int) const { return 0; }
};
struct SymmColumnSmallNoVec
{
SymmColumnSmallNoVec() {}
SymmColumnSmallNoVec(const Mat&, int, int, double) {}
int operator()(const uchar**, uchar*, int) const { return 0; }
};
struct FilterNoVec
{
FilterNoVec() {}
FilterNoVec(const Mat&, int, double) {}
int operator()(const uchar**, uchar*, int) const { return 0; }
};
#if CV_SIMD
///////////////////////////////////// 8u-16s & 8u-8u //////////////////////////////////
struct RowVec_8u32s
{
RowVec_8u32s() { smallValues = false; }
RowVec_8u32s( const Mat& _kernel )
{
kernel = _kernel;
smallValues = true;
int k, ksize = kernel.rows + kernel.cols - 1;
for( k = 0; k < ksize; k++ )
{
int v = kernel.ptr<int>()[k];
if( v < SHRT_MIN || v > SHRT_MAX )
{
smallValues = false;
break;
}
}
}
int operator()(const uchar* _src, uchar* _dst, int width, int cn) const
{
CV_INSTRUMENT_REGION();
int i = 0, k, _ksize = kernel.rows + kernel.cols - 1;
int* dst = (int*)_dst;
const int* _kx = kernel.ptr<int>();
width *= cn;
if( smallValues )
{
for( ; i <= width - v_uint8::nlanes; i += v_uint8::nlanes )
{
const uchar* src = _src + i;
v_int32 s0 = vx_setzero_s32();
v_int32 s1 = vx_setzero_s32();
v_int32 s2 = vx_setzero_s32();
v_int32 s3 = vx_setzero_s32();
k = 0;
for (; k <= _ksize - 2; k += 2, src += 2 * cn)
{
v_int32 f = vx_setall_s32((_kx[k] & 0xFFFF) | (_kx[k + 1] << 16));
v_uint8 x0, x1;
v_zip(vx_load(src), vx_load(src + cn), x0, x1);
s0 += v_dotprod(v_reinterpret_as_s16(v_expand_low(x0)), v_reinterpret_as_s16(f));
s1 += v_dotprod(v_reinterpret_as_s16(v_expand_high(x0)), v_reinterpret_as_s16(f));
s2 += v_dotprod(v_reinterpret_as_s16(v_expand_low(x1)), v_reinterpret_as_s16(f));
s3 += v_dotprod(v_reinterpret_as_s16(v_expand_high(x1)), v_reinterpret_as_s16(f));
}
if (k < _ksize)
{
v_int32 f = vx_setall_s32(_kx[k]);
v_uint16 x0, x1;
v_expand(vx_load(src), x0, x1);
s0 += v_dotprod(v_reinterpret_as_s16(v_expand_low(x0)), v_reinterpret_as_s16(f));
s1 += v_dotprod(v_reinterpret_as_s16(v_expand_high(x0)), v_reinterpret_as_s16(f));
s2 += v_dotprod(v_reinterpret_as_s16(v_expand_low(x1)), v_reinterpret_as_s16(f));
s3 += v_dotprod(v_reinterpret_as_s16(v_expand_high(x1)), v_reinterpret_as_s16(f));
}
v_store(dst + i, s0);
v_store(dst + i + v_int32::nlanes, s1);
v_store(dst + i + 2*v_int32::nlanes, s2);
v_store(dst + i + 3*v_int32::nlanes, s3);
}
if( i <= width - v_uint16::nlanes )
{
const uchar* src = _src + i;
v_int32 s0 = vx_setzero_s32();
v_int32 s1 = vx_setzero_s32();
k = 0;
for( ; k <= _ksize - 2; k += 2, src += 2*cn )
{
v_int32 f = vx_setall_s32((_kx[k] & 0xFFFF) | (_kx[k + 1] << 16));
v_uint16 x0, x1;
v_zip(vx_load_expand(src), vx_load_expand(src + cn), x0, x1);
s0 += v_dotprod(v_reinterpret_as_s16(x0), v_reinterpret_as_s16(f));
s1 += v_dotprod(v_reinterpret_as_s16(x1), v_reinterpret_as_s16(f));
}
if( k < _ksize )
{
v_int32 f = vx_setall_s32(_kx[k]);
v_uint32 x0, x1;
v_expand(vx_load_expand(src), x0, x1);
s0 += v_dotprod(v_reinterpret_as_s16(x0), v_reinterpret_as_s16(f));
s1 += v_dotprod(v_reinterpret_as_s16(x1), v_reinterpret_as_s16(f));
}
v_store(dst + i, s0);
v_store(dst + i + v_int32::nlanes, s1);
i += v_uint16::nlanes;
}
if( i <= width - v_uint32::nlanes )
{
v_int32 d = vx_setzero_s32();
k = 0;
const uchar* src = _src + i;
for (; k <= _ksize - 2; k += 2, src += 2*cn)
{
v_int32 f = vx_setall_s32((_kx[k] & 0xFFFF) | (_kx[k + 1] << 16));
v_uint32 x0, x1;
v_zip(vx_load_expand_q(src), vx_load_expand_q(src + cn), x0, x1);
d += v_dotprod(v_pack(v_reinterpret_as_s32(x0), v_reinterpret_as_s32(x1)), v_reinterpret_as_s16(f));
}
if (k < _ksize)
d += v_dotprod(v_reinterpret_as_s16(vx_load_expand_q(src)), v_reinterpret_as_s16(vx_setall_s32(_kx[k])));
v_store(dst + i, d);
i += v_uint32::nlanes;
}
}
return i;
}
Mat kernel;
bool smallValues;
};
struct SymmRowSmallVec_8u32s
{
SymmRowSmallVec_8u32s() { smallValues = false; symmetryType = 0; }
SymmRowSmallVec_8u32s( const Mat& _kernel, int _symmetryType )
{
kernel = _kernel;
symmetryType = _symmetryType;
smallValues = true;
int k, ksize = kernel.rows + kernel.cols - 1;
for( k = 0; k < ksize; k++ )
{
int v = kernel.ptr<int>()[k];
if( v < SHRT_MIN || v > SHRT_MAX )
{
smallValues = false;
break;
}
}
}
int operator()(const uchar* src, uchar* _dst, int width, int cn) const
{
CV_INSTRUMENT_REGION();
int i = 0, j, k, _ksize = kernel.rows + kernel.cols - 1;
int* dst = (int*)_dst;
bool symmetrical = (symmetryType & KERNEL_SYMMETRICAL) != 0;
const int* kx = kernel.ptr<int>() + _ksize/2;
if( !smallValues )
return 0;
src += (_ksize/2)*cn;
width *= cn;
if( symmetrical )
{
if( _ksize == 1 )
return 0;
if( _ksize == 3 )
{
if( kx[0] == 2 && kx[1] == 1 )
{
for( ; i <= width - v_uint8::nlanes; i += v_uint8::nlanes, src += v_uint8::nlanes )
{
v_uint16 x0l, x0h, x1l, x1h, x2l, x2h;
v_expand(vx_load(src - cn), x0l, x0h);
v_expand(vx_load(src), x1l, x1h);
v_expand(vx_load(src + cn), x2l, x2h);
x1l = v_add_wrap(v_add_wrap(x1l, x1l), v_add_wrap(x0l, x2l));
x1h = v_add_wrap(v_add_wrap(x1h, x1h), v_add_wrap(x0h, x2h));
v_store(dst + i, v_reinterpret_as_s32(v_expand_low(x1l)));
v_store(dst + i + v_int32::nlanes, v_reinterpret_as_s32(v_expand_high(x1l)));
v_store(dst + i + 2*v_int32::nlanes, v_reinterpret_as_s32(v_expand_low(x1h)));
v_store(dst + i + 3*v_int32::nlanes, v_reinterpret_as_s32(v_expand_high(x1h)));
}
if( i <= width - v_uint16::nlanes )
{
v_uint16 x = vx_load_expand(src);
x = v_add_wrap(v_add_wrap(x, x), v_add_wrap(vx_load_expand(src - cn), vx_load_expand(src + cn)));
v_store(dst + i, v_reinterpret_as_s32(v_expand_low(x)));
v_store(dst + i + v_int32::nlanes, v_reinterpret_as_s32(v_expand_high(x)));
i += v_uint16::nlanes; src += v_uint16::nlanes;
}
if( i <= width - v_uint32::nlanes )
{
v_uint32 x = vx_load_expand_q(src);
x = (x + x) + vx_load_expand_q(src - cn) + vx_load_expand_q(src + cn);
v_store(dst + i, v_reinterpret_as_s32(x));
i += v_uint32::nlanes;
}
}
else if( kx[0] == -2 && kx[1] == 1 )
{
for( ; i <= width - v_uint8::nlanes; i += v_uint8::nlanes, src += v_uint8::nlanes )
{
v_uint16 x0l, x0h, x1l, x1h, x2l, x2h;
v_expand(vx_load(src - cn), x0l, x0h);
v_expand(vx_load(src), x1l, x1h);
v_expand(vx_load(src + cn), x2l, x2h);
x1l = v_sub_wrap(v_add_wrap(x0l, x2l), v_add_wrap(x1l, x1l));
x1h = v_sub_wrap(v_add_wrap(x0h, x2h), v_add_wrap(x1h, x1h));
v_store(dst + i, v_expand_low(v_reinterpret_as_s16(x1l)));
v_store(dst + i + v_int32::nlanes, v_expand_high(v_reinterpret_as_s16(x1l)));
v_store(dst + i + 2*v_int32::nlanes, v_expand_low(v_reinterpret_as_s16(x1h)));
v_store(dst + i + 3*v_int32::nlanes, v_expand_high(v_reinterpret_as_s16(x1h)));
}
if( i <= width - v_uint16::nlanes )
{
v_uint16 x = vx_load_expand(src);
x = v_sub_wrap(v_add_wrap(vx_load_expand(src - cn), vx_load_expand(src + cn)), v_add_wrap(x, x));
v_store(dst + i, v_expand_low(v_reinterpret_as_s16(x)));
v_store(dst + i + v_int32::nlanes, v_expand_high(v_reinterpret_as_s16(x)));
i += v_uint16::nlanes; src += v_uint16::nlanes;
}
if( i <= width - v_uint32::nlanes )
{
v_int32 x = v_reinterpret_as_s32(vx_load_expand_q(src));
x = v_reinterpret_as_s32(vx_load_expand_q(src - cn) + vx_load_expand_q(src + cn)) - (x + x);
v_store(dst + i, x);
i += v_uint32::nlanes;
}
}
else
{
v_int16 k0 = vx_setall_s16((short)kx[0]);
v_int16 k1 = vx_setall_s16((short)kx[1]);
for( ; i <= width - v_uint8::nlanes; i += v_uint8::nlanes, src += v_uint8::nlanes )
{
v_uint16 x0l, x0h, x1l, x1h, x2l, x2h;
v_expand(vx_load(src - cn), x0l, x0h);
v_expand(vx_load(src), x1l, x1h);
v_expand(vx_load(src + cn), x2l, x2h);
v_int32 dl, dh;
v_int16 x0, x1;
v_mul_expand(v_reinterpret_as_s16(x1l), k0, dl, dh);
v_zip(v_reinterpret_as_s16(x0l), v_reinterpret_as_s16(x2l), x0, x1);
dl += v_dotprod(x0, k1);
dh += v_dotprod(x1, k1);
v_store(dst + i, dl);
v_store(dst + i + v_int32::nlanes, dh);
v_mul_expand(v_reinterpret_as_s16(x1h), k0, dl, dh);
v_zip(v_reinterpret_as_s16(x0h), v_reinterpret_as_s16(x2h), x0, x1);
dl += v_dotprod(x0, k1);
dh += v_dotprod(x1, k1);
v_store(dst + i + 2*v_int32::nlanes, dl);
v_store(dst + i + 3*v_int32::nlanes, dh);
}
if ( i <= width - v_uint16::nlanes )
{
v_int32 dl, dh;
v_mul_expand(v_reinterpret_as_s16(vx_load_expand(src)), k0, dl, dh);
v_int16 x0, x1;
v_zip(v_reinterpret_as_s16(vx_load_expand(src - cn)), v_reinterpret_as_s16(vx_load_expand(src + cn)), x0, x1);
dl += v_dotprod(x0, k1);
dh += v_dotprod(x1, k1);
v_store(dst + i, dl);
v_store(dst + i + v_int32::nlanes, dh);
i += v_uint16::nlanes; src += v_uint16::nlanes;
}
if ( i <= width - v_uint32::nlanes )
{
v_store(dst + i, v_muladd(v_reinterpret_as_s32(vx_load_expand_q(src)), vx_setall_s32(kx[0]), v_reinterpret_as_s32(vx_load_expand_q(src - cn) + vx_load_expand_q(src + cn)) * vx_setall_s32(kx[1])));
i += v_uint32::nlanes;
}
}
}
else if( _ksize == 5 )
{
if( kx[0] == -2 && kx[1] == 0 && kx[2] == 1 )
{
for( ; i <= width - v_uint8::nlanes; i += v_uint8::nlanes, src += v_uint8::nlanes )
{
v_uint16 x0l, x0h, x1l, x1h, x2l, x2h;
v_expand(vx_load(src - 2*cn), x0l, x0h);
v_expand(vx_load(src), x1l, x1h);
v_expand(vx_load(src + 2*cn), x2l, x2h);
x1l = v_sub_wrap(v_add_wrap(x0l, x2l), v_add_wrap(x1l, x1l));
x1h = v_sub_wrap(v_add_wrap(x0h, x2h), v_add_wrap(x1h, x1h));
v_store(dst + i, v_expand_low(v_reinterpret_as_s16(x1l)));
v_store(dst + i + v_int32::nlanes, v_expand_high(v_reinterpret_as_s16(x1l)));
v_store(dst + i + 2*v_int32::nlanes, v_expand_low(v_reinterpret_as_s16(x1h)));
v_store(dst + i + 3*v_int32::nlanes, v_expand_high(v_reinterpret_as_s16(x1h)));
}
if( i <= width - v_uint16::nlanes )
{
v_uint16 x = vx_load_expand(src);
x = v_sub_wrap(v_add_wrap(vx_load_expand(src - 2*cn), vx_load_expand(src + 2*cn)), v_add_wrap(x, x));
v_store(dst + i, v_expand_low(v_reinterpret_as_s16(x)));
v_store(dst + i + v_int32::nlanes, v_expand_high(v_reinterpret_as_s16(x)));
i += v_uint16::nlanes; src += v_uint16::nlanes;
}
if( i <= width - v_uint32::nlanes )
{
v_int32 x = v_reinterpret_as_s32(vx_load_expand_q(src));
x = v_reinterpret_as_s32(vx_load_expand_q(src - 2*cn) + vx_load_expand_q(src + 2*cn)) - (x + x);
v_store(dst + i, x);
i += v_uint32::nlanes;
}
}
else
{
v_int16 k0 = vx_setall_s16((short)(kx[0]));
v_int16 k12 = v_reinterpret_as_s16(vx_setall_s32((kx[1] & 0xFFFF) | (kx[2] << 16)));
for( ; i <= width - v_uint8::nlanes; i += v_uint8::nlanes, src += v_uint8::nlanes )
{
v_int32 x0, x1, x2, x3;
v_uint16 x0l, x0h, x1l, x1h, x2l, x2h, x3l, x3h;
v_int16 xl, xh;
v_expand(vx_load(src), x0l, x0h);
v_mul_expand(v_reinterpret_as_s16(x0l), k0, x0, x1);
v_mul_expand(v_reinterpret_as_s16(x0h), k0, x2, x3);
v_expand(vx_load(src - cn), x0l, x0h);
v_expand(vx_load(src + cn), x1l, x1h);
v_expand(vx_load(src - 2*cn), x2l, x2h);
v_expand(vx_load(src + 2*cn), x3l, x3h);
v_zip(v_reinterpret_as_s16(x0l + x1l), v_reinterpret_as_s16(x2l + x3l), xl, xh);
x0 += v_dotprod(xl, k12);
x1 += v_dotprod(xh, k12);
v_zip(v_reinterpret_as_s16(x0h + x1h), v_reinterpret_as_s16(x2h + x3h), xl, xh);
x2 += v_dotprod(xl, k12);
x3 += v_dotprod(xh, k12);
v_store(dst + i, x0);
v_store(dst + i + v_int32::nlanes, x1);
v_store(dst + i + 2*v_int32::nlanes, x2);
v_store(dst + i + 3*v_int32::nlanes, x3);
}
if( i <= width - v_uint16::nlanes )
{
v_int32 x1, x2;
v_mul_expand(v_reinterpret_as_s16(vx_load_expand(src)), k0, x1, x2);
v_int16 xl, xh;
v_zip(v_reinterpret_as_s16(vx_load_expand(src - cn) + vx_load_expand(src + cn)), v_reinterpret_as_s16(vx_load_expand(src - 2*cn) + vx_load_expand(src + 2*cn)), xl, xh);
x1 += v_dotprod(xl, k12);
x2 += v_dotprod(xh, k12);
v_store(dst + i, x1);
v_store(dst + i + v_int32::nlanes, x2);
i += v_uint16::nlanes, src += v_uint16::nlanes;
}
if( i <= width - v_uint32::nlanes )
{
v_store(dst + i, v_muladd(v_reinterpret_as_s32(vx_load_expand_q(src)), vx_setall_s32(kx[0]),
v_muladd(v_reinterpret_as_s32(vx_load_expand_q(src - cn) + vx_load_expand_q(src + cn)), vx_setall_s32(kx[1]),
v_reinterpret_as_s32(vx_load_expand_q(src - 2*cn) + vx_load_expand_q(src + 2*cn)) * vx_setall_s32(kx[2]))));
i += v_uint32::nlanes;
}
}
}
else
{
v_int16 k0 = vx_setall_s16((short)(kx[0]));
for( ; i <= width - v_uint8::nlanes; i += v_uint8::nlanes, src += v_uint8::nlanes )
{
v_uint8 v_src = vx_load(src);
v_int32 s0, s1, s2, s3;
v_mul_expand(v_reinterpret_as_s16(v_expand_low(v_src)), k0, s0, s1);
v_mul_expand(v_reinterpret_as_s16(v_expand_high(v_src)), k0, s2, s3);
for (k = 1, j = cn; k <= _ksize / 2 - 1; k += 2, j += 2 * cn)
{
v_int16 k12 = v_reinterpret_as_s16(vx_setall_s32((kx[k] & 0xFFFF) | (kx[k + 1] << 16)));
v_uint8 v_src0 = vx_load(src - j);
v_uint8 v_src1 = vx_load(src - j - cn);
v_uint8 v_src2 = vx_load(src + j);
v_uint8 v_src3 = vx_load(src + j + cn);
v_int16 xl, xh;
v_zip(v_reinterpret_as_s16(v_expand_low(v_src0) + v_expand_low(v_src2)), v_reinterpret_as_s16(v_expand_low(v_src1) + v_expand_low(v_src3)), xl, xh);
s0 += v_dotprod(xl, k12);
s1 += v_dotprod(xh, k12);
v_zip(v_reinterpret_as_s16(v_expand_high(v_src0) + v_expand_high(v_src2)), v_reinterpret_as_s16(v_expand_high(v_src1) + v_expand_high(v_src3)), xl, xh);
s2 += v_dotprod(xl, k12);
s3 += v_dotprod(xh, k12);
}
if( k < _ksize / 2 + 1 )
{
v_int16 k1 = vx_setall_s16((short)(kx[k]));
v_uint8 v_src0 = vx_load(src - j);
v_uint8 v_src1 = vx_load(src + j);
v_int16 xl, xh;
v_zip(v_reinterpret_as_s16(v_expand_low(v_src0)), v_reinterpret_as_s16(v_expand_low(v_src1)), xl, xh);
s0 += v_dotprod(xl, k1);
s1 += v_dotprod(xh, k1);
v_zip(v_reinterpret_as_s16(v_expand_high(v_src0)), v_reinterpret_as_s16(v_expand_high(v_src1)), xl, xh);
s2 += v_dotprod(xl, k1);
s3 += v_dotprod(xh, k1);
}
v_store(dst + i, s0);
v_store(dst + i + v_int32::nlanes, s1);
v_store(dst + i + 2*v_int32::nlanes, s2);
v_store(dst + i + 3*v_int32::nlanes, s3);
}
if( i <= width - v_uint16::nlanes )
{
v_int32 s0, s1;
v_mul_expand(v_reinterpret_as_s16(vx_load_expand(src)), k0, s0, s1);
for (k = 1, j = cn; k <= _ksize / 2 - 1; k+=2, j += 2*cn)
{
v_int16 xl, xh;
v_zip(v_reinterpret_as_s16(vx_load_expand(src - j) + vx_load_expand(src + j)), v_reinterpret_as_s16(vx_load_expand(src - j - cn) + vx_load_expand(src + j + cn)), xl, xh);
v_int16 k12 = v_reinterpret_as_s16(vx_setall_s32((kx[k] & 0xFFFF) | (kx[k+1] << 16)));
s0 += v_dotprod(xl, k12);
s1 += v_dotprod(xh, k12);
}
if ( k < _ksize / 2 + 1 )
{
v_int16 xl, xh;
v_zip(v_reinterpret_as_s16(vx_load_expand(src - j)), v_reinterpret_as_s16(vx_load_expand(src + j)), xl, xh);
v_int16 k1 = vx_setall_s16((short)(kx[k]));
s0 += v_dotprod(xl, k1);
s1 += v_dotprod(xh, k1);
}
v_store(dst + i, s0);
v_store(dst + i + v_int32::nlanes, s1);
i += v_uint16::nlanes; src += v_uint16::nlanes;
}
if( i <= width - v_uint32::nlanes )
{
v_int32 s0 = v_reinterpret_as_s32(vx_load_expand_q(src)) * vx_setall_s32(kx[0]);
for( k = 1, j = cn; k < _ksize / 2 + 1; k++, j += cn )
s0 = v_muladd(v_reinterpret_as_s32(vx_load_expand_q(src - j) + vx_load_expand_q(src + j)), vx_setall_s32(kx[k]), s0);
v_store(dst + i, s0);
i += v_uint32::nlanes;
}
}
}
else
{
if( _ksize == 3 )
{
if( kx[0] == 0 && kx[1] == 1 )
{
for( ; i <= width - v_uint8::nlanes; i += v_uint8::nlanes, src += v_uint8::nlanes )
{
v_uint16 x0l, x0h, x2l, x2h;
v_expand(vx_load(src - cn), x0l, x0h);
v_expand(vx_load(src + cn), x2l, x2h);
v_int16 dl = v_reinterpret_as_s16(v_sub_wrap(x2l, x0l));
v_int16 dh = v_reinterpret_as_s16(v_sub_wrap(x2h, x0h));
v_store(dst + i, v_expand_low(dl));
v_store(dst + i + v_int32::nlanes, v_expand_high(dl));
v_store(dst + i + 2*v_int32::nlanes, v_expand_low(dh));
v_store(dst + i + 3*v_int32::nlanes, v_expand_high(dh));
}
if( i <= width - v_uint16::nlanes )
{
v_int16 dl = v_reinterpret_as_s16(v_sub_wrap(vx_load_expand(src + cn), vx_load_expand(src - cn)));
v_store(dst + i, v_expand_low(dl));
v_store(dst + i + v_int32::nlanes, v_expand_high(dl));
i += v_uint16::nlanes; src += v_uint16::nlanes;
}
if (i <= width - v_uint32::nlanes)
{
v_store(dst + i, v_reinterpret_as_s32(vx_load_expand_q(src + cn)) - v_reinterpret_as_s32(vx_load_expand_q(src - cn)));
i += v_uint32::nlanes;
}
}
else
{
v_int16 k0 = v_reinterpret_as_s16(vx_setall_s32((kx[1] & 0xFFFF) | (-kx[1] << 16)));
for( ; i <= width - v_uint8::nlanes; i += v_uint8::nlanes, src += v_uint8::nlanes )
{
v_uint16 x0l, x0h, x2l, x2h;
v_expand(vx_load(src - cn), x0l, x0h);
v_expand(vx_load(src + cn), x2l, x2h);
v_int16 xl, xh;
v_zip(v_reinterpret_as_s16(x2l), v_reinterpret_as_s16(x0l), xl, xh);
v_store(dst + i, v_dotprod(xl, k0));
v_store(dst + i + v_int32::nlanes, v_dotprod(xh, k0));
v_zip(v_reinterpret_as_s16(x2h), v_reinterpret_as_s16(x0h), xl, xh);
v_store(dst + i + 2*v_int32::nlanes, v_dotprod(xl, k0));
v_store(dst + i + 3*v_int32::nlanes, v_dotprod(xh, k0));
}
if( i <= width - v_uint16::nlanes )
{
v_int16 xl, xh;
v_zip(v_reinterpret_as_s16(vx_load_expand(src + cn)), v_reinterpret_as_s16(vx_load_expand(src - cn)), xl, xh);
v_store(dst + i, v_dotprod(xl, k0));
v_store(dst + i + v_int32::nlanes, v_dotprod(xh, k0));
i += v_uint16::nlanes; src += v_uint16::nlanes;
}
if (i <= width - v_uint32::nlanes)
{
v_store(dst + i, v_muladd(v_reinterpret_as_s32(vx_load_expand_q(src + cn)), vx_setall_s32(kx[1]), v_reinterpret_as_s32(vx_load_expand_q(src - cn)) * vx_setall_s32(-kx[1])));
i += v_uint32::nlanes;
}
}
}
else if( _ksize == 5 )
{
v_int16 k0 = v_reinterpret_as_s16(vx_setall_s32((kx[1] & 0xFFFF) | (kx[2] << 16)));
for( ; i <= width - v_uint8::nlanes; i += v_uint8::nlanes, src += v_uint8::nlanes )
{
v_uint16 x0l, x0h, x1l, x1h, x2l, x2h, x3l, x3h;
v_expand(vx_load(src - cn), x0l, x0h);
v_expand(vx_load(src - 2*cn), x1l, x1h);
v_expand(vx_load(src + cn), x2l, x2h);
v_expand(vx_load(src + 2*cn), x3l, x3h);
v_int16 x0, x1;
v_zip(v_reinterpret_as_s16(v_sub_wrap(x2l, x0l)), v_reinterpret_as_s16(v_sub_wrap(x3l, x1l)), x0, x1);
v_store(dst + i, v_dotprod(x0, k0));
v_store(dst + i + v_int32::nlanes, v_dotprod(x1, k0));
v_zip(v_reinterpret_as_s16(v_sub_wrap(x2h, x0h)), v_reinterpret_as_s16(v_sub_wrap(x3h, x1h)), x0, x1);
v_store(dst + i + 2*v_int32::nlanes, v_dotprod(x0, k0));
v_store(dst + i + 3*v_int32::nlanes, v_dotprod(x1, k0));
}
if( i <= width - v_uint16::nlanes )
{
v_int16 x0, x1;
v_zip(v_reinterpret_as_s16(v_sub_wrap(vx_load_expand(src + cn), vx_load_expand(src - cn))),
v_reinterpret_as_s16(v_sub_wrap(vx_load_expand(src + 2*cn), vx_load_expand(src - 2*cn))), x0, x1);
v_store(dst + i, v_dotprod(x0, k0));
v_store(dst + i + v_int32::nlanes, v_dotprod(x1, k0));
i += v_uint16::nlanes; src += v_uint16::nlanes;
}
if( i <= width - v_uint32::nlanes )
{
v_store(dst + i, v_muladd(v_reinterpret_as_s32(vx_load_expand_q(src + cn)) - v_reinterpret_as_s32(vx_load_expand_q(src - cn)), vx_setall_s32(kx[1]),
(v_reinterpret_as_s32(vx_load_expand_q(src + 2*cn)) - v_reinterpret_as_s32(vx_load_expand_q(src - 2*cn))) * vx_setall_s32(kx[2])));
i += v_uint32::nlanes;
}
}
else
{
v_int16 k0 = vx_setall_s16((short)(kx[0]));
for( ; i <= width - v_uint8::nlanes; i += v_uint8::nlanes, src += v_uint8::nlanes )
{
v_uint8 v_src = vx_load(src);
v_int32 s0, s1, s2, s3;
v_mul_expand(v_reinterpret_as_s16(v_expand_low(v_src)), k0, s0, s1);
v_mul_expand(v_reinterpret_as_s16(v_expand_high(v_src)), k0, s2, s3);
for( k = 1, j = cn; k <= _ksize / 2 - 1; k += 2, j += 2 * cn )
{
v_int16 k12 = v_reinterpret_as_s16(vx_setall_s32((kx[k] & 0xFFFF) | (kx[k + 1] << 16)));
v_uint8 v_src0 = vx_load(src - j);
v_uint8 v_src1 = vx_load(src - j - cn);
v_uint8 v_src2 = vx_load(src + j);
v_uint8 v_src3 = vx_load(src + j + cn);
v_int16 xl, xh;
v_zip(v_reinterpret_as_s16(v_sub_wrap(v_expand_low(v_src2), v_expand_low(v_src0))), v_reinterpret_as_s16(v_sub_wrap(v_expand_low(v_src3), v_expand_low(v_src1))), xl, xh);
s0 += v_dotprod(xl, k12);
s1 += v_dotprod(xh, k12);
v_zip(v_reinterpret_as_s16(v_sub_wrap(v_expand_high(v_src2), v_expand_high(v_src0))), v_reinterpret_as_s16(v_sub_wrap(v_expand_high(v_src3), v_expand_high(v_src1))), xl, xh);
s2 += v_dotprod(xl, k12);
s3 += v_dotprod(xh, k12);
}
if( k < _ksize / 2 + 1 )
{
v_int16 k12 = v_reinterpret_as_s16(vx_setall_s32((kx[k] & 0xFFFF) | (-kx[k] << 16)));
v_uint8 v_src0 = vx_load(src - j);
v_uint8 v_src1 = vx_load(src + j);
v_int16 xl, xh;
v_zip(v_reinterpret_as_s16(v_expand_low(v_src1)), v_reinterpret_as_s16(v_expand_low(v_src0)), xl, xh);
s0 += v_dotprod(xl, k12);
s1 += v_dotprod(xh, k12);
v_zip(v_reinterpret_as_s16(v_expand_high(v_src1)), v_reinterpret_as_s16(v_expand_high(v_src0)), xl, xh);
s2 += v_dotprod(xl, k12);
s3 += v_dotprod(xh, k12);
}
v_store(dst + i, s0);
v_store(dst + i + v_int32::nlanes, s1);
v_store(dst + i + 2*v_int32::nlanes, s2);
v_store(dst + i + 3*v_int32::nlanes, s3);
}
if( i <= width - v_uint16::nlanes )
{
v_int32 s0, s1;
v_mul_expand(v_reinterpret_as_s16(vx_load_expand(src)), k0, s0, s1);
for( k = 1, j = cn; k <= _ksize / 2 - 1; k += 2, j += 2 * cn )
{
v_int16 xl, xh;
v_zip(v_reinterpret_as_s16(v_sub_wrap(vx_load_expand(src + j), vx_load_expand(src - j))), v_reinterpret_as_s16(v_sub_wrap(vx_load_expand(src + j + cn), vx_load_expand(src - j - cn))), xl, xh);
v_int16 k12 = v_reinterpret_as_s16(vx_setall_s32((kx[k] & 0xFFFF) | (kx[k + 1] << 16)));
s0 += v_dotprod(xl, k12);
s1 += v_dotprod(xh, k12);
}
if( k < _ksize / 2 + 1 )
{
v_int16 k1 = v_reinterpret_as_s16(vx_setall_s32((kx[k] & 0xFFFF) | (-kx[k] << 16)));
v_int16 xl, xh;
v_zip(v_reinterpret_as_s16(vx_load_expand(src + j)), v_reinterpret_as_s16(vx_load_expand(src - j)), xl, xh);
s0 += v_dotprod(xl, k1);
s1 += v_dotprod(xh, k1);
}
v_store(dst + i, s0);
v_store(dst + i + v_int32::nlanes, s1);
i += v_uint16::nlanes; src += v_uint16::nlanes;
}
if( i <= width - v_uint32::nlanes )
{
v_int32 s0 = v_reinterpret_as_s32(vx_load_expand_q(src)) * vx_setall_s32(kx[0]);
for (k = 1, j = cn; k < _ksize / 2 + 1; k++, j += cn)
s0 = v_muladd(v_reinterpret_as_s32(vx_load_expand_q(src + j)) - v_reinterpret_as_s32(vx_load_expand_q(src - j)), vx_setall_s32(kx[k]), s0);
v_store(dst + i, s0);
i += v_uint32::nlanes;
}
}
}
return i;
}
Mat kernel;
int symmetryType;
bool smallValues;
};
struct SymmColumnVec_32s8u
{
SymmColumnVec_32s8u() { symmetryType=0; delta = 0; }
SymmColumnVec_32s8u(const Mat& _kernel, int _symmetryType, int _bits, double _delta)
{
symmetryType = _symmetryType;
_kernel.convertTo(kernel, CV_32F, 1./(1 << _bits), 0);
delta = (float)(_delta/(1 << _bits));
CV_Assert( (symmetryType & (KERNEL_SYMMETRICAL | KERNEL_ASYMMETRICAL)) != 0 );
}
int operator()(const uchar** _src, uchar* dst, int width) const
{
CV_INSTRUMENT_REGION();
int _ksize = kernel.rows + kernel.cols - 1;
if( _ksize == 1 )
return 0;
int ksize2 = _ksize/2;
const float* ky = kernel.ptr<float>() + ksize2;
int i = 0, k;
bool symmetrical = (symmetryType & KERNEL_SYMMETRICAL) != 0;
const int** src = (const int**)_src;
v_float32 d4 = vx_setall_f32(delta);
if( symmetrical )
{
v_float32 f0 = vx_setall_f32(ky[0]);
v_float32 f1 = vx_setall_f32(ky[1]);
for( ; i <= width - v_uint8::nlanes; i += v_uint8::nlanes )
{
const int* S = src[0] + i;
v_float32 s0 = v_muladd(v_cvt_f32(vx_load(S)), f0, d4);
v_float32 s1 = v_muladd(v_cvt_f32(vx_load(S + v_int32::nlanes)), f0, d4);
v_float32 s2 = v_muladd(v_cvt_f32(vx_load(S + 2*v_int32::nlanes)), f0, d4);
v_float32 s3 = v_muladd(v_cvt_f32(vx_load(S + 3*v_int32::nlanes)), f0, d4);
const int* S0 = src[1] + i;
const int* S1 = src[-1] + i;
s0 = v_muladd(v_cvt_f32(vx_load(S0) + vx_load(S1)), f1, s0);
s1 = v_muladd(v_cvt_f32(vx_load(S0 + v_int32::nlanes) + vx_load(S1 + v_int32::nlanes)), f1, s1);
s2 = v_muladd(v_cvt_f32(vx_load(S0 + 2 * v_int32::nlanes) + vx_load(S1 + 2 * v_int32::nlanes)), f1, s2);
s3 = v_muladd(v_cvt_f32(vx_load(S0 + 3 * v_int32::nlanes) + vx_load(S1 + 3 * v_int32::nlanes)), f1, s3);
for( k = 2; k <= ksize2; k++ )
{
v_float32 f = vx_setall_f32(ky[k]);
S0 = src[k] + i;
S1 = src[-k] + i;
s0 = v_muladd(v_cvt_f32(vx_load(S0) + vx_load(S1)), f, s0);
s1 = v_muladd(v_cvt_f32(vx_load(S0 + v_int32::nlanes) + vx_load(S1 + v_int32::nlanes)), f, s1);
s2 = v_muladd(v_cvt_f32(vx_load(S0 + 2*v_int32::nlanes) + vx_load(S1 + 2*v_int32::nlanes)), f, s2);
s3 = v_muladd(v_cvt_f32(vx_load(S0 + 3*v_int32::nlanes) + vx_load(S1 + 3*v_int32::nlanes)), f, s3);
}
v_store(dst + i, v_pack_u(v_pack(v_round(s0), v_round(s1)), v_pack(v_round(s2), v_round(s3))));
}
if( i <= width - v_uint16::nlanes )
{
const int* S = src[0] + i;
v_float32 s0 = v_muladd(v_cvt_f32(vx_load(S)), f0, d4);
v_float32 s1 = v_muladd(v_cvt_f32(vx_load(S + v_int32::nlanes)), f0, d4);
const int* S0 = src[1] + i;
const int* S1 = src[-1] + i;
s0 = v_muladd(v_cvt_f32(vx_load(S0) + vx_load(S1)), f1, s0);
s1 = v_muladd(v_cvt_f32(vx_load(S0 + v_int32::nlanes) + vx_load(S1 + v_int32::nlanes)), f1, s1);
for( k = 2; k <= ksize2; k++ )
{
v_float32 f = vx_setall_f32(ky[k]);
S0 = src[k] + i;
S1 = src[-k] + i;
s0 = v_muladd(v_cvt_f32(vx_load(S0) + vx_load(S1)), f, s0);
s1 = v_muladd(v_cvt_f32(vx_load(S0 + v_int32::nlanes) + vx_load(S1 + v_int32::nlanes)), f, s1);
}
v_pack_u_store(dst + i, v_pack(v_round(s0), v_round(s1)));
i += v_uint16::nlanes;
}
#if CV_SIMD_WIDTH > 16
while( i <= width - v_int32x4::nlanes )
#else
if( i <= width - v_int32x4::nlanes )
#endif
{
v_float32x4 s0 = v_muladd(v_cvt_f32(v_load(src[0] + i)), v_setall_f32(ky[0]), v_setall_f32(delta));
s0 = v_muladd(v_cvt_f32(v_load(src[1] + i) + v_load(src[-1] + i)), v_setall_f32(ky[1]), s0);
for( k = 2; k <= ksize2; k++ )
s0 = v_muladd(v_cvt_f32(v_load(src[k] + i) + v_load(src[-k] + i)), v_setall_f32(ky[k]), s0);
v_int32x4 s32 = v_round(s0);
v_int16x8 s16 = v_pack(s32, s32);
*(unaligned_int*)(dst + i) = v_reinterpret_as_s32(v_pack_u(s16, s16)).get0();
i += v_int32x4::nlanes;
}
}
else
{
v_float32 f1 = vx_setall_f32(ky[1]);
for( ; i <= width - v_uint8::nlanes; i += v_uint8::nlanes )
{
const int* S0 = src[1] + i;
const int* S1 = src[-1] + i;
v_float32 s0 = v_muladd(v_cvt_f32(vx_load(S0) - vx_load(S1)), f1, d4);
v_float32 s1 = v_muladd(v_cvt_f32(vx_load(S0 + v_int32::nlanes) - vx_load(S1 + v_int32::nlanes)), f1, d4);
v_float32 s2 = v_muladd(v_cvt_f32(vx_load(S0 + 2 * v_int32::nlanes) - vx_load(S1 + 2 * v_int32::nlanes)), f1, d4);
v_float32 s3 = v_muladd(v_cvt_f32(vx_load(S0 + 3 * v_int32::nlanes) - vx_load(S1 + 3 * v_int32::nlanes)), f1, d4);
for ( k = 2; k <= ksize2; k++ )
{
v_float32 f = vx_setall_f32(ky[k]);
S0 = src[k] + i;
S1 = src[-k] + i;
s0 = v_muladd(v_cvt_f32(vx_load(S0) - vx_load(S1)), f, s0);
s1 = v_muladd(v_cvt_f32(vx_load(S0 + v_int32::nlanes) - vx_load(S1 + v_int32::nlanes)), f, s1);
s2 = v_muladd(v_cvt_f32(vx_load(S0 + 2*v_int32::nlanes) - vx_load(S1 + 2*v_int32::nlanes)), f, s2);
s3 = v_muladd(v_cvt_f32(vx_load(S0 + 3*v_int32::nlanes) - vx_load(S1 + 3*v_int32::nlanes)), f, s3);
}
v_store(dst + i, v_pack_u(v_pack(v_round(s0), v_round(s1)), v_pack(v_round(s2), v_round(s3))));
}
if( i <= width - v_uint16::nlanes )
{
const int* S0 = src[1] + i;
const int* S1 = src[-1] + i;
v_float32 s0 = v_muladd(v_cvt_f32(vx_load(S0) - vx_load(S1)), f1, d4);
v_float32 s1 = v_muladd(v_cvt_f32(vx_load(S0 + v_int32::nlanes) - vx_load(S1 + v_int32::nlanes)), f1, d4);
for ( k = 2; k <= ksize2; k++ )
{
v_float32 f = vx_setall_f32(ky[k]);
S0 = src[k] + i;
S1 = src[-k] + i;
s0 = v_muladd(v_cvt_f32(vx_load(S0) - vx_load(S1)), f, s0);
s1 = v_muladd(v_cvt_f32(vx_load(S0 + v_int32::nlanes) - vx_load(S1 + v_int32::nlanes)), f, s1);
}
v_pack_u_store(dst + i, v_pack(v_round(s0), v_round(s1)));
i += v_uint16::nlanes;
}
#if CV_SIMD_WIDTH > 16
while( i <= width - v_int32x4::nlanes )
#else
if( i <= width - v_int32x4::nlanes )
#endif
{
v_float32x4 s0 = v_muladd(v_cvt_f32(v_load(src[1] + i) - v_load(src[-1] + i)), v_setall_f32(ky[1]), v_setall_f32(delta));
for (k = 2; k <= ksize2; k++)
s0 = v_muladd(v_cvt_f32(v_load(src[k] + i) - v_load(src[-k] + i)), v_setall_f32(ky[k]), s0);
v_int32x4 s32 = v_round(s0);
v_int16x8 s16 = v_pack(s32, s32);
*(unaligned_int*)(dst + i) = v_reinterpret_as_s32(v_pack_u(s16, s16)).get0();
i += v_int32x4::nlanes;
}
}
return i;
}
int symmetryType;
float delta;
Mat kernel;
};
struct SymmColumnSmallVec_32s16s
{
SymmColumnSmallVec_32s16s() { symmetryType=0; delta = 0; }
SymmColumnSmallVec_32s16s(const Mat& _kernel, int _symmetryType, int _bits, double _delta)
{
symmetryType = _symmetryType;
_kernel.convertTo(kernel, CV_32F, 1./(1 << _bits), 0);
delta = (float)(_delta/(1 << _bits));
CV_Assert( (symmetryType & (KERNEL_SYMMETRICAL | KERNEL_ASYMMETRICAL)) != 0 );
}
int operator()(const uchar** _src, uchar* _dst, int width) const
{
CV_INSTRUMENT_REGION();
int ksize2 = (kernel.rows + kernel.cols - 1)/2;
const float* ky = kernel.ptr<float>() + ksize2;
int i = 0;
bool symmetrical = (symmetryType & KERNEL_SYMMETRICAL) != 0;
const int** src = (const int**)_src;
const int *S0 = src[-1], *S1 = src[0], *S2 = src[1];
short* dst = (short*)_dst;
v_float32 df4 = vx_setall_f32(delta);
int d = cvRound(delta);
v_int16 d8 = vx_setall_s16((short)d);
if( symmetrical )
{
if( ky[0] == 2 && ky[1] == 1 )
{
for( ; i <= width - 2*v_int16::nlanes; i += 2*v_int16::nlanes )
{
v_int32 s0 = vx_load(S1 + i);
v_int32 s1 = vx_load(S1 + i + v_int32::nlanes);
v_int32 s2 = vx_load(S1 + i + 2*v_int32::nlanes);
v_int32 s3 = vx_load(S1 + i + 3*v_int32::nlanes);
v_store(dst + i, v_pack(vx_load(S0 + i) + vx_load(S2 + i) + (s0 + s0), vx_load(S0 + i + v_int32::nlanes) + vx_load(S2 + i + v_int32::nlanes) + (s1 + s1)) + d8);
v_store(dst + i + v_int16::nlanes, v_pack(vx_load(S0 + i + 2*v_int32::nlanes) + vx_load(S2 + i + 2*v_int32::nlanes) + (s2 + s2),
vx_load(S0 + i + 3*v_int32::nlanes) + vx_load(S2 + i + 3*v_int32::nlanes) + (s3 + s3)) + d8);
}
if( i <= width - v_int16::nlanes )
{
v_int32 sl = vx_load(S1 + i);
v_int32 sh = vx_load(S1 + i + v_int32::nlanes);
v_store(dst + i, v_pack(vx_load(S0 + i) + vx_load(S2 + i) + (sl + sl), vx_load(S0 + i + v_int32::nlanes) + vx_load(S2 + i + v_int32::nlanes) + (sh + sh)) + d8);
i += v_int16::nlanes;
}
if( i <= width - v_int32::nlanes )
{
v_int32 s = vx_load(S1 + i);
v_pack_store(dst + i, vx_load(S0 + i) + vx_load(S2 + i) + vx_setall_s32(d) + (s + s));
i += v_int32::nlanes;
}
}
else if( ky[0] == -2 && ky[1] == 1 )
{
for( ; i <= width - 2*v_int16::nlanes; i += 2*v_int16::nlanes )
{
v_int32 s0 = vx_load(S1 + i);
v_int32 s1 = vx_load(S1 + i + v_int32::nlanes);
v_int32 s2 = vx_load(S1 + i + 2*v_int32::nlanes);
v_int32 s3 = vx_load(S1 + i + 3*v_int32::nlanes);
v_store(dst + i, v_pack(vx_load(S0 + i) + vx_load(S2 + i) - (s0 + s0),
vx_load(S0 + i + v_int32::nlanes) + vx_load(S2 + i + v_int32::nlanes) - (s1 + s1)) + d8);
v_store(dst + i + v_int16::nlanes, v_pack(vx_load(S0 + i + 2*v_int32::nlanes) + vx_load(S2 + i + 2*v_int32::nlanes) - (s2 + s2),
vx_load(S0 + i + 3*v_int32::nlanes) + vx_load(S2 + i + 3*v_int32::nlanes) - (s3 + s3)) + d8);
}
if( i <= width - v_int16::nlanes )
{
v_int32 sl = vx_load(S1 + i);
v_int32 sh = vx_load(S1 + i + v_int32::nlanes);
v_store(dst + i, v_pack(vx_load(S0 + i) + vx_load(S2 + i) - (sl + sl), vx_load(S0 + i + v_int32::nlanes) + vx_load(S2 + i + v_int32::nlanes) - (sh + sh)) + d8);
i += v_int16::nlanes;
}
if( i <= width - v_int32::nlanes )
{
v_int32 s = vx_load(S1 + i);
v_pack_store(dst + i, vx_load(S0 + i) + vx_load(S2 + i) + vx_setall_s32(d) - (s + s));
i += v_int32::nlanes;
}
}
#if CV_NEON
else if( ky[0] == (float)((int)ky[0]) && ky[1] == (float)((int)ky[1]) )
{
v_int32 k0 = vx_setall_s32((int)ky[0]), k1 = vx_setall_s32((int)ky[1]);
v_int32 d4 = vx_setall_s32(d);
for( ; i <= width - 2*v_int16::nlanes; i += 2*v_int16::nlanes )
{
v_store(dst + i, v_pack(v_muladd(vx_load(S0 + i) + vx_load(S2 + i), k1, v_muladd(vx_load(S1 + i), k0, d4)),
v_muladd(vx_load(S0 + i + v_int32::nlanes) + vx_load(S2 + i + v_int32::nlanes), k1, v_muladd(vx_load(S1 + i + v_int32::nlanes), k0, d4))));
v_store(dst + i + v_int16::nlanes, v_pack(v_muladd(vx_load(S0 + i + 2*v_int32::nlanes) + vx_load(S2 + i + 2*v_int32::nlanes), k1, v_muladd(vx_load(S1 + i + 2*v_int32::nlanes), k0, d4)),
v_muladd(vx_load(S0 + i + 3*v_int32::nlanes) + vx_load(S2 + i + 3*v_int32::nlanes), k1, v_muladd(vx_load(S1 + i + 3*v_int32::nlanes), k0, d4))));
}
if( i <= width - v_int16::nlanes )
{
v_store(dst + i, v_pack(v_muladd(vx_load(S0 + i) + vx_load(S2 + i), k1, v_muladd(vx_load(S1 + i), k0, d4)),
v_muladd(vx_load(S0 + i + v_int32::nlanes) + vx_load(S2 + i + v_int32::nlanes), k1, v_muladd(vx_load(S1 + i + v_int32::nlanes), k0, d4))));
i += v_int16::nlanes;
}
if( i <= width - v_int32::nlanes )
{
v_pack_store(dst + i, v_muladd(vx_load(S0 + i) + vx_load(S2 + i), k1, v_muladd(vx_load(S1 + i), k0, d4)));
i += v_int32::nlanes;
}
}
#endif
else
{
v_float32 k0 = vx_setall_f32(ky[0]), k1 = vx_setall_f32(ky[1]);
for( ; i <= width - 2*v_int16::nlanes; i += 2*v_int16::nlanes )
{
v_store(dst + i, v_pack(v_round(v_muladd(v_cvt_f32(vx_load(S0 + i) + vx_load(S2 + i)), k1, v_muladd(v_cvt_f32(vx_load(S1 + i)), k0, df4))),
v_round(v_muladd(v_cvt_f32(vx_load(S0 + i + v_int32::nlanes) + vx_load(S2 + i + v_int32::nlanes)), k1, v_muladd(v_cvt_f32(vx_load(S1 + i + v_int32::nlanes)), k0, df4)))));
v_store(dst + i + v_int16::nlanes, v_pack(v_round(v_muladd(v_cvt_f32(vx_load(S0 + i + 2*v_int32::nlanes) + vx_load(S2 + i + 2*v_int32::nlanes)), k1, v_muladd(v_cvt_f32(vx_load(S1 + i + 2*v_int32::nlanes)), k0, df4))),
v_round(v_muladd(v_cvt_f32(vx_load(S0 + i + 3*v_int32::nlanes) + vx_load(S2 + i + 3*v_int32::nlanes)), k1, v_muladd(v_cvt_f32(vx_load(S1 + i + 3*v_int32::nlanes)), k0, df4)))));
}
if( i <= width - v_int16::nlanes )
{
v_store(dst + i, v_pack(v_round(v_muladd(v_cvt_f32(vx_load(S0 + i) + vx_load(S2 + i)), k1, v_muladd(v_cvt_f32(vx_load(S1 + i)), k0, df4))),
v_round(v_muladd(v_cvt_f32(vx_load(S0 + i + v_int32::nlanes) + vx_load(S2 + i + v_int32::nlanes)), k1, v_muladd(v_cvt_f32(vx_load(S1 + i + v_int32::nlanes)), k0, df4)))));
i += v_int16::nlanes;
}
if( i <= width - v_int32::nlanes )
{
v_pack_store(dst + i, v_round(v_muladd(v_cvt_f32(vx_load(S0 + i) + vx_load(S2 + i)), k1, v_muladd(v_cvt_f32(vx_load(S1 + i)), k0, df4))));
i += v_int32::nlanes;
}
}
}
else
{
if( fabs(ky[1]) == 1 && ky[1] == -ky[-1] )
{
if( ky[1] < 0 )
std::swap(S0, S2);
for( ; i <= width - 2*v_int16::nlanes; i += 2*v_int16::nlanes )
{
v_store(dst + i, v_pack(vx_load(S2 + i) - vx_load(S0 + i), vx_load(S2 + i + v_int32::nlanes) - vx_load(S0 + i + v_int32::nlanes)) + d8);
v_store(dst + i + v_int16::nlanes, v_pack(vx_load(S2 + i + 2*v_int32::nlanes) - vx_load(S0 + i + 2*v_int32::nlanes), vx_load(S2 + i + 3*v_int32::nlanes) - vx_load(S0 + i + 3*v_int32::nlanes)) + d8);
}
if( i <= width - v_int16::nlanes )
{
v_store(dst + i, v_pack(vx_load(S2 + i) - vx_load(S0 + i), vx_load(S2 + i + v_int32::nlanes) - vx_load(S0 + i + v_int32::nlanes)) + d8);
i += v_int16::nlanes;
}
if( i <= width - v_int32::nlanes )
{
v_pack_store(dst + i, vx_load(S2 + i) - vx_load(S0 + i) + vx_setall_s32(d));
i += v_int32::nlanes;
}
}
else
{
v_float32 k1 = vx_setall_f32(ky[1]);
for( ; i <= width - 2*v_int16::nlanes; i += 2*v_int16::nlanes )
{
v_store(dst + i, v_pack(v_round(v_muladd(v_cvt_f32(vx_load(S2 + i) - vx_load(S0 + i)), k1, df4)),
v_round(v_muladd(v_cvt_f32(vx_load(S2 + i + v_int32::nlanes) - vx_load(S0 + i + v_int32::nlanes)), k1, df4))));
v_store(dst + i + v_int16::nlanes, v_pack(v_round(v_muladd(v_cvt_f32(vx_load(S2 + i + 2*v_int32::nlanes) - vx_load(S0 + i + 2*v_int32::nlanes)), k1, df4)),
v_round(v_muladd(v_cvt_f32(vx_load(S2 + i + 3*v_int32::nlanes) - vx_load(S0 + i + 3*v_int32::nlanes)), k1, df4))));
}
if( i <= width - v_int16::nlanes )
{
v_store(dst + i, v_pack(v_round(v_muladd(v_cvt_f32(vx_load(S2 + i) - vx_load(S0 + i)), k1, df4)),
v_round(v_muladd(v_cvt_f32(vx_load(S2 + i + v_int32::nlanes) - vx_load(S0 + i + v_int32::nlanes)), k1, df4))));
i += v_int16::nlanes;
}
if( i <= width - v_int32::nlanes )
{
v_pack_store(dst + i, v_round(v_muladd(v_cvt_f32(vx_load(S2 + i) - vx_load(S0 + i)), k1, df4)));
i += v_int32::nlanes;
}
}
}
return i;
}
int symmetryType;
float delta;
Mat kernel;
};
/////////////////////////////////////// 16s //////////////////////////////////
struct RowVec_16s32f
{
RowVec_16s32f() {}
RowVec_16s32f( const Mat& _kernel )
{
kernel = _kernel;
}
int operator()(const uchar* _src, uchar* _dst, int width, int cn) const
{
CV_INSTRUMENT_REGION();
int i = 0, k, _ksize = kernel.rows + kernel.cols - 1;
float* dst = (float*)_dst;
const float* _kx = kernel.ptr<float>();
width *= cn;
for( ; i <= width - 2*v_int16::nlanes; i += 2*v_int16::nlanes )
{
const short* src = (const short*)_src + i;
v_float32 s0 = vx_setzero_f32();
v_float32 s1 = vx_setzero_f32();
v_float32 s2 = vx_setzero_f32();
v_float32 s3 = vx_setzero_f32();
for( k = 0; k < _ksize; k++, src += cn )
{
v_float32 f = vx_setall_f32(_kx[k]);
v_int16 xl = vx_load(src);
v_int16 xh = vx_load(src + v_int16::nlanes);
s0 = v_muladd(v_cvt_f32(v_expand_low(xl)), f, s0);
s1 = v_muladd(v_cvt_f32(v_expand_high(xl)), f, s1);
s2 = v_muladd(v_cvt_f32(v_expand_low(xh)), f, s2);
s3 = v_muladd(v_cvt_f32(v_expand_high(xh)), f, s3);
}
v_store(dst + i, s0);
v_store(dst + i + v_float32::nlanes, s1);
v_store(dst + i + 2*v_float32::nlanes, s2);
v_store(dst + i + 3*v_float32::nlanes, s3);
}
if( i <= width - v_int16::nlanes )
{
const short* src = (const short*)_src + i;
v_float32 s0 = vx_setzero_f32();
v_float32 s1 = vx_setzero_f32();
for( k = 0; k < _ksize; k++, src += cn )
{
v_float32 f = vx_setall_f32(_kx[k]);
v_int16 x = vx_load(src);
s0 = v_muladd(v_cvt_f32(v_expand_low(x)), f, s0);
s1 = v_muladd(v_cvt_f32(v_expand_high(x)), f, s1);
}
v_store(dst + i, s0);
v_store(dst + i + v_float32::nlanes, s1);
i += v_int16::nlanes;
}
if( i <= width - v_float32::nlanes )
{
const short* src = (const short*)_src + i;
v_float32 s0 = vx_setzero_f32();
for( k = 0; k < _ksize; k++, src += cn )
s0 = v_muladd(v_cvt_f32(vx_load_expand(src)), vx_setall_f32(_kx[k]), s0);
v_store(dst + i, s0);
i += v_float32::nlanes;
}
return i;
}
Mat kernel;
};
struct SymmColumnVec_32f16s
{
SymmColumnVec_32f16s() { symmetryType=0; delta = 0; }
SymmColumnVec_32f16s(const Mat& _kernel, int _symmetryType, int, double _delta)
{
symmetryType = _symmetryType;
kernel = _kernel;
delta = (float)_delta;
CV_Assert( (symmetryType & (KERNEL_SYMMETRICAL | KERNEL_ASYMMETRICAL)) != 0 );
}
int operator()(const uchar** _src, uchar* _dst, int width) const
{
CV_INSTRUMENT_REGION();
int _ksize = kernel.rows + kernel.cols - 1;
if( _ksize == 1 )
return 0;
int ksize2 = _ksize / 2;
const float* ky = kernel.ptr<float>() + ksize2;
int i = 0, k;
bool symmetrical = (symmetryType & KERNEL_SYMMETRICAL) != 0;
const float** src = (const float**)_src;
short* dst = (short*)_dst;
v_float32 d4 = vx_setall_f32(delta);
if( symmetrical )
{
v_float32 k0 = vx_setall_f32(ky[0]);
v_float32 k1 = vx_setall_f32(ky[1]);
for( ; i <= width - 2*v_int16::nlanes; i += 2*v_int16::nlanes )
{
v_float32 s0 = v_muladd(vx_load(src[0] + i), k0, d4);
v_float32 s1 = v_muladd(vx_load(src[0] + i + v_float32::nlanes), k0, d4);
v_float32 s2 = v_muladd(vx_load(src[0] + i + 2*v_float32::nlanes), k0, d4);
v_float32 s3 = v_muladd(vx_load(src[0] + i + 3*v_float32::nlanes), k0, d4);
s0 = v_muladd(vx_load(src[1] + i) + vx_load(src[-1] + i), k1, s0);
s1 = v_muladd(vx_load(src[1] + i + v_float32::nlanes) + vx_load(src[-1] + i + v_float32::nlanes), k1, s1);
s2 = v_muladd(vx_load(src[1] + i + 2*v_float32::nlanes) + vx_load(src[-1] + i + 2*v_float32::nlanes), k1, s2);
s3 = v_muladd(vx_load(src[1] + i + 3*v_float32::nlanes) + vx_load(src[-1] + i + 3*v_float32::nlanes), k1, s3);
for( k = 2; k <= ksize2; k++ )
{
v_float32 k2 = vx_setall_f32(ky[k]);
s0 = v_muladd(vx_load(src[k] + i) + vx_load(src[-k] + i), k2, s0);
s1 = v_muladd(vx_load(src[k] + i + v_float32::nlanes) + vx_load(src[-k] + i + v_float32::nlanes), k2, s1);
s2 = v_muladd(vx_load(src[k] + i + 2*v_float32::nlanes) + vx_load(src[-k] + i + 2*v_float32::nlanes), k2, s2);
s3 = v_muladd(vx_load(src[k] + i + 3*v_float32::nlanes) + vx_load(src[-k] + i + 3*v_float32::nlanes), k2, s3);
}
v_store(dst + i, v_pack(v_round(s0), v_round(s1)));
v_store(dst + i + v_int16::nlanes, v_pack(v_round(s2), v_round(s3)));
}
if( i <= width - v_int16::nlanes )
{
v_float32 s0 = v_muladd(vx_load(src[0] + i), k0, d4);
v_float32 s1 = v_muladd(vx_load(src[0] + i + v_float32::nlanes), k0, d4);
s0 = v_muladd(vx_load(src[1] + i) + vx_load(src[-1] + i), k1, s0);
s1 = v_muladd(vx_load(src[1] + i + v_float32::nlanes) + vx_load(src[-1] + i + v_float32::nlanes), k1, s1);
for( k = 2; k <= ksize2; k++ )
{
v_float32 k2 = vx_setall_f32(ky[k]);
s0 = v_muladd(vx_load(src[k] + i) + vx_load(src[-k] + i), k2, s0);
s1 = v_muladd(vx_load(src[k] + i + v_float32::nlanes) + vx_load(src[-k] + i + v_float32::nlanes), k2, s1);
}
v_store(dst + i, v_pack(v_round(s0), v_round(s1)));
i += v_int16::nlanes;
}
if( i <= width - v_float32::nlanes )
{
v_float32 s0 = v_muladd(vx_load(src[0] + i), k0, d4);
s0 = v_muladd(vx_load(src[1] + i) + vx_load(src[-1] + i), k1, s0);
for( k = 2; k <= ksize2; k++ )
s0 = v_muladd(vx_load(src[k] + i) + vx_load(src[-k] + i), vx_setall_f32(ky[k]), s0);
v_pack_store(dst + i, v_round(s0));
i += v_float32::nlanes;
}
}
else
{
v_float32 k1 = vx_setall_f32(ky[1]);
for( ; i <= width - 2*v_int16::nlanes; i += 2*v_int16::nlanes )
{
v_float32 s0 = v_muladd(vx_load(src[1] + i) - vx_load(src[-1] + i), k1, d4);
v_float32 s1 = v_muladd(vx_load(src[1] + i + v_float32::nlanes) - vx_load(src[-1] + i + v_float32::nlanes), k1, d4);
v_float32 s2 = v_muladd(vx_load(src[1] + i + 2*v_float32::nlanes) - vx_load(src[-1] + i + 2*v_float32::nlanes), k1, d4);
v_float32 s3 = v_muladd(vx_load(src[1] + i + 3*v_float32::nlanes) - vx_load(src[-1] + i + 3*v_float32::nlanes), k1, d4);
for( k = 2; k <= ksize2; k++ )
{
v_float32 k2 = vx_setall_f32(ky[k]);
s0 = v_muladd(vx_load(src[k] + i) - vx_load(src[-k] + i), k2, s0);
s1 = v_muladd(vx_load(src[k] + i + v_float32::nlanes) - vx_load(src[-k] + i + v_float32::nlanes), k2, s1);
s2 = v_muladd(vx_load(src[k] + i + 2*v_float32::nlanes) - vx_load(src[-k] + i + 2*v_float32::nlanes), k2, s2);
s3 = v_muladd(vx_load(src[k] + i + 3*v_float32::nlanes) - vx_load(src[-k] + i + 3*v_float32::nlanes), k2, s3);
}
v_store(dst + i, v_pack(v_round(s0), v_round(s1)));
v_store(dst + i + v_int16::nlanes, v_pack(v_round(s2), v_round(s3)));
}
if( i <= width - v_int16::nlanes )
{
v_float32 s0 = v_muladd(vx_load(src[1] + i) - vx_load(src[-1] + i), k1, d4);
v_float32 s1 = v_muladd(vx_load(src[1] + i + v_float32::nlanes) - vx_load(src[-1] + i + v_float32::nlanes), k1, d4);
for( k = 2; k <= ksize2; k++ )
{
v_float32 k2 = vx_setall_f32(ky[k]);
s0 = v_muladd(vx_load(src[k] + i) - vx_load(src[-k] + i), k2, s0);
s1 = v_muladd(vx_load(src[k] + i + v_float32::nlanes) - vx_load(src[-k] + i + v_float32::nlanes), k2, s1);
}
v_store(dst + i, v_pack(v_round(s0), v_round(s1)));
i += v_int16::nlanes;
}
if( i <= width - v_float32::nlanes )
{
v_float32 s0 = v_muladd(vx_load(src[1] + i) - vx_load(src[-1] + i), k1, d4);
for( k = 2; k <= ksize2; k++ )
s0 = v_muladd(vx_load(src[k] + i) - vx_load(src[-k] + i), vx_setall_f32(ky[k]), s0);
v_pack_store(dst + i, v_round(s0));
i += v_float32::nlanes;
}
}
return i;
}
int symmetryType;
float delta;
Mat kernel;
};
/////////////////////////////////////// 32f //////////////////////////////////
struct RowVec_32f
{
RowVec_32f()
{
#if defined USE_IPP_SEP_FILTERS
bufsz = -1;
#endif
}
RowVec_32f( const Mat& _kernel )
{
kernel = _kernel;
#if defined USE_IPP_SEP_FILTERS
bufsz = -1;
#endif
}
int operator()(const uchar* _src, uchar* _dst, int width, int cn) const
{
CV_INSTRUMENT_REGION();
#if defined USE_IPP_SEP_FILTERS
CV_IPP_CHECK()
{
int ret = ippiOperator(_src, _dst, width, cn);
if (ret > 0)
return ret;
}
#endif
int _ksize = kernel.rows + kernel.cols - 1;
CV_DbgAssert(_ksize > 0);
const float* src0 = (const float*)_src;
float* dst = (float*)_dst;
const float* _kx = kernel.ptr<float>();
int i = 0, k;
width *= cn;
#if CV_AVX
for (; i <= width - 8; i += 8)
{
const float* src = src0 + i;
__m256 f, x0;
__m256 s0 = _mm256_set1_ps(0.0f);
for (k = 0; k < _ksize; k++, src += cn)
{
f = _mm256_set1_ps(_kx[k]);
x0 = _mm256_loadu_ps(src);
#if CV_FMA3
s0 = _mm256_fmadd_ps(x0, f, s0);
#else
s0 = _mm256_add_ps(s0, _mm256_mul_ps(x0, f));
#endif
}
_mm256_storeu_ps(dst + i, s0);
}
#endif
v_float32 k0 = vx_setall_f32(_kx[0]);
for( ; i <= width - 4*v_float32::nlanes; i += 4*v_float32::nlanes )
{
const float* src = src0 + i;
v_float32 s0 = vx_load(src) * k0;
v_float32 s1 = vx_load(src + v_float32::nlanes) * k0;
v_float32 s2 = vx_load(src + 2*v_float32::nlanes) * k0;
v_float32 s3 = vx_load(src + 3*v_float32::nlanes) * k0;
src += cn;
for( k = 1; k < _ksize; k++, src += cn )
{
v_float32 k1 = vx_setall_f32(_kx[k]);
s0 = v_muladd(vx_load(src), k1, s0);
s1 = v_muladd(vx_load(src + v_float32::nlanes), k1, s1);
s2 = v_muladd(vx_load(src + 2*v_float32::nlanes), k1, s2);
s3 = v_muladd(vx_load(src + 3*v_float32::nlanes), k1, s3);
}
v_store(dst + i, s0);
v_store(dst + i + v_float32::nlanes, s1);
v_store(dst + i + 2*v_float32::nlanes, s2);
v_store(dst + i + 3*v_float32::nlanes, s3);
}
if( i <= width - 2*v_float32::nlanes )
{
const float* src = src0 + i;
v_float32 s0 = vx_load(src) * k0;
v_float32 s1 = vx_load(src + v_float32::nlanes) * k0;
src += cn;
for( k = 1; k < _ksize; k++, src += cn )
{
v_float32 k1 = vx_setall_f32(_kx[k]);
s0 = v_muladd(vx_load(src), k1, s0);
s1 = v_muladd(vx_load(src + v_float32::nlanes), k1, s1);
}
v_store(dst + i, s0);
v_store(dst + i + v_float32::nlanes, s1);
i += 2*v_float32::nlanes;
}
if( i <= width - v_float32::nlanes )
{
const float* src = src0 + i;
v_float32 s0 = vx_load(src) * k0;
src += cn;
for( k = 1; k < _ksize; k++, src += cn )
s0 = v_muladd(vx_load(src), vx_setall_f32(_kx[k]), s0);
v_store(dst + i, s0);
i += v_float32::nlanes;
}
return i;
}
Mat kernel;
#if defined USE_IPP_SEP_FILTERS
private:
mutable int bufsz;
int ippiOperator(const uchar* _src, uchar* _dst, int width, int cn) const
{
CV_INSTRUMENT_REGION_IPP();
int _ksize = kernel.rows + kernel.cols - 1;
if ((1 != cn && 3 != cn) || width < _ksize*8)
return 0;
const float* src = (const float*)_src;
float* dst = (float*)_dst;
const float* _kx = (const float*)kernel.data;
IppiSize roisz = { width, 1 };
if( bufsz < 0 )
{
if( (cn == 1 && ippiFilterRowBorderPipelineGetBufferSize_32f_C1R(roisz, _ksize, &bufsz) < 0) ||
(cn == 3 && ippiFilterRowBorderPipelineGetBufferSize_32f_C3R(roisz, _ksize, &bufsz) < 0))
return 0;
}
AutoBuffer<uchar> buf(bufsz + 64);
uchar* bufptr = alignPtr(buf.data(), 32);
int step = (int)(width*sizeof(dst[0])*cn);
float borderValue[] = {0.f, 0.f, 0.f};
// here is the trick. IPP needs border type and extrapolates the row. We did it already.
// So we pass anchor=0 and ignore the right tail of results since they are incorrect there.
if( (cn == 1 && CV_INSTRUMENT_FUN_IPP(ippiFilterRowBorderPipeline_32f_C1R, src, step, &dst, roisz, _kx, _ksize, 0,
ippBorderRepl, borderValue[0], bufptr) < 0) ||
(cn == 3 && CV_INSTRUMENT_FUN_IPP(ippiFilterRowBorderPipeline_32f_C3R, src, step, &dst, roisz, _kx, _ksize, 0,
ippBorderRepl, borderValue, bufptr) < 0))
{
setIppErrorStatus();
return 0;
}
CV_IMPL_ADD(CV_IMPL_IPP);
return width - _ksize + 1;
}
#endif
};
struct SymmRowSmallVec_32f
{
SymmRowSmallVec_32f() { symmetryType = 0; }
SymmRowSmallVec_32f( const Mat& _kernel, int _symmetryType )
{
kernel = _kernel;
symmetryType = _symmetryType;
}
int operator()(const uchar* _src, uchar* _dst, int width, int cn) const
{
CV_INSTRUMENT_REGION();
int i = 0, _ksize = kernel.rows + kernel.cols - 1;
if( _ksize == 1 )
return 0;
float* dst = (float*)_dst;
const float* src = (const float*)_src + (_ksize/2)*cn;
bool symmetrical = (symmetryType & KERNEL_SYMMETRICAL) != 0;
const float* kx = kernel.ptr<float>() + _ksize/2;
width *= cn;
if( symmetrical )
{
if( _ksize == 3 )
{
if( fabs(kx[0]) == 2 && kx[1] == 1 )
{
#if CV_FMA3 || CV_AVX2
v_float32 k0 = vx_setall_f32(kx[0]);
for( ; i <= width - v_float32::nlanes; i += v_float32::nlanes, src += v_float32::nlanes )
v_store(dst + i, v_muladd(vx_load(src), k0, vx_load(src - cn) + vx_load(src + cn)));
#else
if( kx[0] > 0 )
for( ; i <= width - v_float32::nlanes; i += v_float32::nlanes, src += v_float32::nlanes )
{
v_float32 x = vx_load(src);
v_store(dst + i, vx_load(src - cn) + vx_load(src + cn) + (x + x));
}
else
for( ; i <= width - v_float32::nlanes; i += v_float32::nlanes, src += v_float32::nlanes )
{
v_float32 x = vx_load(src);
v_store(dst + i, vx_load(src - cn) + vx_load(src + cn) - (x + x));
}
#endif
}
else
{
v_float32 k0 = vx_setall_f32(kx[0]), k1 = vx_setall_f32(kx[1]);
for( ; i <= width - v_float32::nlanes; i += v_float32::nlanes, src += v_float32::nlanes )
v_store(dst + i, v_muladd(vx_load(src), k0, (vx_load(src - cn) + vx_load(src + cn)) * k1));
}
}
else if( _ksize == 5 )
{
if( kx[0] == -2 && kx[1] == 0 && kx[2] == 1 )
{
#if CV_FMA3 || CV_AVX2
v_float32 k0 = vx_setall_f32(-2);
for( ; i <= width - v_float32::nlanes; i += v_float32::nlanes, src += v_float32::nlanes )
v_store(dst + i, v_muladd(vx_load(src), k0, vx_load(src - 2*cn) + vx_load(src + 2*cn)));
#else
for( ; i <= width - v_float32::nlanes; i += v_float32::nlanes, src += v_float32::nlanes )
{
v_float32 x = vx_load(src);
v_store(dst + i, vx_load(src - 2*cn) + vx_load(src + 2*cn) - (x + x));
}
#endif
}
else
{
v_float32 k0 = vx_setall_f32(kx[0]), k1 = vx_setall_f32(kx[1]), k2 = vx_setall_f32(kx[2]);
for( ; i <= width - v_float32::nlanes; i += v_float32::nlanes, src += v_float32::nlanes )
v_store(dst + i, v_muladd(vx_load(src + 2*cn) + vx_load(src - 2*cn), k2, v_muladd(vx_load(src), k0, (vx_load(src - cn) + vx_load(src + cn)) * k1)));
}
}
}
else
{
if( _ksize == 3 )
{
if( kx[0] == 0 && kx[1] == 1 )
for( ; i <= width - v_float32::nlanes; i += v_float32::nlanes, src += v_float32::nlanes )
v_store(dst + i, vx_load(src + cn) - vx_load(src - cn));
else
{
v_float32 k1 = vx_setall_f32(kx[1]);
for( ; i <= width - v_float32::nlanes; i += v_float32::nlanes, src += v_float32::nlanes )
v_store(dst + i, (vx_load(src + cn) - vx_load(src - cn)) * k1);
}
}
else if( _ksize == 5 )
{
v_float32 k1 = vx_setall_f32(kx[1]), k2 = vx_setall_f32(kx[2]);
for ( ; i <= width - v_float32::nlanes; i += v_float32::nlanes, src += v_float32::nlanes )
v_store(dst + i, v_muladd(vx_load(src + 2*cn) - vx_load(src - 2*cn), k2, (vx_load(src + cn) - vx_load(src - cn)) * k1));
}
}
return i;
}
Mat kernel;
int symmetryType;
};
struct SymmColumnVec_32f
{
SymmColumnVec_32f() {
symmetryType=0;
delta = 0;
}
SymmColumnVec_32f(const Mat& _kernel, int _symmetryType, int, double _delta)
{
symmetryType = _symmetryType;
kernel = _kernel;
delta = (float)_delta;
CV_Assert( (symmetryType & (KERNEL_SYMMETRICAL | KERNEL_ASYMMETRICAL)) != 0 );
}
int operator()(const uchar** _src, uchar* _dst, int width) const
{
CV_INSTRUMENT_REGION();
int ksize2 = (kernel.rows + kernel.cols - 1)/2;
const float* ky = kernel.ptr<float>() + ksize2;
int i = 0, k;
bool symmetrical = (symmetryType & KERNEL_SYMMETRICAL) != 0;
const float** src = (const float**)_src;
float* dst = (float*)_dst;
if( symmetrical )
{
#if CV_AVX
{
const float *S, *S2;
const __m256 d8 = _mm256_set1_ps(delta);
for( ; i <= width - 16; i += 16 )
{
__m256 f = _mm256_set1_ps(ky[0]);
__m256 s0, s1;
__m256 x0;
S = src[0] + i;
s0 = _mm256_loadu_ps(S);
#if CV_FMA3
s0 = _mm256_fmadd_ps(s0, f, d8);
#else
s0 = _mm256_add_ps(_mm256_mul_ps(s0, f), d8);
#endif
s1 = _mm256_loadu_ps(S+8);
#if CV_FMA3
s1 = _mm256_fmadd_ps(s1, f, d8);
#else
s1 = _mm256_add_ps(_mm256_mul_ps(s1, f), d8);
#endif
for( k = 1; k <= ksize2; k++ )
{
S = src[k] + i;
S2 = src[-k] + i;
f = _mm256_set1_ps(ky[k]);
x0 = _mm256_add_ps(_mm256_loadu_ps(S), _mm256_loadu_ps(S2));
#if CV_FMA3
s0 = _mm256_fmadd_ps(x0, f, s0);
#else
s0 = _mm256_add_ps(s0, _mm256_mul_ps(x0, f));
#endif
x0 = _mm256_add_ps(_mm256_loadu_ps(S+8), _mm256_loadu_ps(S2+8));
#if CV_FMA3
s1 = _mm256_fmadd_ps(x0, f, s1);
#else
s1 = _mm256_add_ps(s1, _mm256_mul_ps(x0, f));
#endif
}
_mm256_storeu_ps(dst + i, s0);
_mm256_storeu_ps(dst + i + 8, s1);
}
}
#endif
const v_float32 d4 = vx_setall_f32(delta);
const v_float32 k0 = vx_setall_f32(ky[0]);
for( ; i <= width - 4*v_float32::nlanes; i += 4*v_float32::nlanes )
{
v_float32 s0 = v_muladd(vx_load(src[0] + i), k0, d4);
v_float32 s1 = v_muladd(vx_load(src[0] + i + v_float32::nlanes), k0, d4);
v_float32 s2 = v_muladd(vx_load(src[0] + i + 2*v_float32::nlanes), k0, d4);
v_float32 s3 = v_muladd(vx_load(src[0] + i + 3*v_float32::nlanes), k0, d4);
for( k = 1; k <= ksize2; k++ )
{
v_float32 k1 = vx_setall_f32(ky[k]);
s0 = v_muladd(vx_load(src[k] + i) + vx_load(src[-k] + i), k1, s0);
s1 = v_muladd(vx_load(src[k] + i + v_float32::nlanes) + vx_load(src[-k] + i + v_float32::nlanes), k1, s1);
s2 = v_muladd(vx_load(src[k] + i + 2*v_float32::nlanes) + vx_load(src[-k] + i + 2*v_float32::nlanes), k1, s2);
s3 = v_muladd(vx_load(src[k] + i + 3*v_float32::nlanes) + vx_load(src[-k] + i + 3*v_float32::nlanes), k1, s3);
}
v_store(dst + i, s0);
v_store(dst + i + v_float32::nlanes, s1);
v_store(dst + i + 2*v_float32::nlanes, s2);
v_store(dst + i + 3*v_float32::nlanes, s3);
}
if( i <= width - 2*v_float32::nlanes )
{
v_float32 s0 = v_muladd(vx_load(src[0] + i), k0, d4);
v_float32 s1 = v_muladd(vx_load(src[0] + i + v_float32::nlanes), k0, d4);
for( k = 1; k <= ksize2; k++ )
{
v_float32 k1 = vx_setall_f32(ky[k]);
s0 = v_muladd(vx_load(src[k] + i) + vx_load(src[-k] + i), k1, s0);
s1 = v_muladd(vx_load(src[k] + i + v_float32::nlanes) + vx_load(src[-k] + i + v_float32::nlanes), k1, s1);
}
v_store(dst + i, s0);
v_store(dst + i + v_float32::nlanes, s1);
i += 2*v_float32::nlanes;
}
if( i <= width - v_float32::nlanes )
{
v_float32 s0 = v_muladd(vx_load(src[0] + i), k0, d4);
for( k = 1; k <= ksize2; k++ )
s0 = v_muladd(vx_load(src[k] + i) + vx_load(src[-k] + i), vx_setall_f32(ky[k]), s0);
v_store(dst + i, s0);
i += v_float32::nlanes;
}
}
else
{
CV_DbgAssert(ksize2 > 0);
#if CV_AVX
{
const float *S2;
const __m256 d8 = _mm256_set1_ps(delta);
for (; i <= width - 16; i += 16)
{
__m256 f, s0 = d8, s1 = d8;
__m256 x0;
for (k = 1; k <= ksize2; k++)
{
const float *S = src[k] + i;
S2 = src[-k] + i;
f = _mm256_set1_ps(ky[k]);
x0 = _mm256_sub_ps(_mm256_loadu_ps(S), _mm256_loadu_ps(S2));
#if CV_FMA3
s0 = _mm256_fmadd_ps(x0, f, s0);
#else
s0 = _mm256_add_ps(s0, _mm256_mul_ps(x0, f));
#endif
x0 = _mm256_sub_ps(_mm256_loadu_ps(S + 8), _mm256_loadu_ps(S2 + 8));
#if CV_FMA3
s1 = _mm256_fmadd_ps(x0, f, s1);
#else
s1 = _mm256_add_ps(s1, _mm256_mul_ps(x0, f));
#endif
}
_mm256_storeu_ps(dst + i, s0);
_mm256_storeu_ps(dst + i + 8, s1);
}
}
#endif
const v_float32 d4 = vx_setall_f32(delta);
const v_float32 k1 = vx_setall_f32(ky[1]);
for( ; i <= width - 4*v_float32::nlanes; i += 4*v_float32::nlanes )
{
v_float32 s0 = v_muladd(vx_load(src[1] + i) - vx_load(src[-1] + i), k1, d4);
v_float32 s1 = v_muladd(vx_load(src[1] + i + v_float32::nlanes) - vx_load(src[-1] + i + v_float32::nlanes), k1, d4);
v_float32 s2 = v_muladd(vx_load(src[1] + i + 2*v_float32::nlanes) - vx_load(src[-1] + i + 2*v_float32::nlanes), k1, d4);
v_float32 s3 = v_muladd(vx_load(src[1] + i + 3*v_float32::nlanes) - vx_load(src[-1] + i + 3*v_float32::nlanes), k1, d4);
for( k = 2; k <= ksize2; k++ )
{
v_float32 k2 = vx_setall_f32(ky[k]);
s0 = v_muladd(vx_load(src[k] + i) - vx_load(src[-k] + i), k2, s0);
s1 = v_muladd(vx_load(src[k] + i + v_float32::nlanes) - vx_load(src[-k] + i + v_float32::nlanes), k2, s1);
s2 = v_muladd(vx_load(src[k] + i + 2*v_float32::nlanes) - vx_load(src[-k] + i + 2*v_float32::nlanes), k2, s2);
s3 = v_muladd(vx_load(src[k] + i + 3*v_float32::nlanes) - vx_load(src[-k] + i + 3*v_float32::nlanes), k2, s3);
}
v_store(dst + i, s0);
v_store(dst + i + v_float32::nlanes, s1);
v_store(dst + i + 2*v_float32::nlanes, s2);
v_store(dst + i + 3*v_float32::nlanes, s3);
}
if( i <= width - 2*v_float32::nlanes )
{
v_float32 s0 = v_muladd(vx_load(src[1] + i) - vx_load(src[-1] + i), k1, d4);
v_float32 s1 = v_muladd(vx_load(src[1] + i + v_float32::nlanes) - vx_load(src[-1] + i + v_float32::nlanes), k1, d4);
for( k = 2; k <= ksize2; k++ )
{
v_float32 k2 = vx_setall_f32(ky[k]);
s0 = v_muladd(vx_load(src[k] + i) - vx_load(src[-k] + i), k2, s0);
s1 = v_muladd(vx_load(src[k] + i + v_float32::nlanes) - vx_load(src[-k] + i + v_float32::nlanes), k2, s1);
}
v_store(dst + i, s0);
v_store(dst + i + v_float32::nlanes, s1);
i += 2*v_float32::nlanes;
}
if( i <= width - v_float32::nlanes )
{
v_float32 s0 = v_muladd(vx_load(src[1] + i) - vx_load(src[-1] + i), k1, d4);
for( k = 2; k <= ksize2; k++ )
s0 = v_muladd(vx_load(src[k] + i) - vx_load(src[-k] + i), vx_setall_f32(ky[k]), s0);
v_store(dst + i, s0);
i += v_float32::nlanes;
}
}
return i;
}
int symmetryType;
float delta;
Mat kernel;
};
struct SymmColumnSmallVec_32f
{
SymmColumnSmallVec_32f() { symmetryType=0; delta = 0; }
SymmColumnSmallVec_32f(const Mat& _kernel, int _symmetryType, int, double _delta)
{
symmetryType = _symmetryType;
kernel = _kernel;
delta = (float)_delta;
CV_Assert( (symmetryType & (KERNEL_SYMMETRICAL | KERNEL_ASYMMETRICAL)) != 0 );
}
int operator()(const uchar** _src, uchar* _dst, int width) const
{
CV_INSTRUMENT_REGION();
int ksize2 = (kernel.rows + kernel.cols - 1)/2;
const float* ky = kernel.ptr<float>() + ksize2;
int i = 0;
bool symmetrical = (symmetryType & KERNEL_SYMMETRICAL) != 0;
const float** src = (const float**)_src;
const float *S0 = src[-1], *S1 = src[0], *S2 = src[1];
float* dst = (float*)_dst;
v_float32 d4 = vx_setall_f32(delta);
if( symmetrical )
{
if( fabs(ky[0]) == 2 && ky[1] == 1 )
{
#if CV_FMA3 || CV_AVX2
v_float32 k0 = vx_setall_f32(ky[0]);
for( ; i <= width - v_float32::nlanes; i += v_float32::nlanes )
v_store(dst + i, v_muladd(vx_load(S1 + i), k0, vx_load(S0 + i) + vx_load(S2 + i) + d4));
#else
if(ky[0] > 0)
for( ; i <= width - v_float32::nlanes; i += v_float32::nlanes )
{
v_float32 x = vx_load(S1 + i);
v_store(dst + i, vx_load(S0 + i) + vx_load(S2 + i) + d4 + (x + x));
}
else
for( ; i <= width - v_float32::nlanes; i += v_float32::nlanes )
{
v_float32 x = vx_load(S1 + i);
v_store(dst + i, vx_load(S0 + i) + vx_load(S2 + i) + d4 - (x + x));
}
#endif
}
else
{
v_float32 k0 = vx_setall_f32(ky[0]), k1 = vx_setall_f32(ky[1]);
for ( ; i <= width - v_float32::nlanes; i += v_float32::nlanes )
v_store(dst + i, v_muladd(vx_load(S0 + i) + vx_load(S2 + i), k1, v_muladd(vx_load(S1 + i), k0, d4)));
}
}
else
{
if( fabs(ky[1]) == 1 && ky[1] == -ky[-1] )
{
if( ky[1] < 0 )
std::swap(S0, S2);
for ( ; i <= width - v_float32::nlanes; i += v_float32::nlanes )
v_store(dst + i, vx_load(S2 + i) - vx_load(S0 + i) + d4);
}
else
{
v_float32 k1 = vx_setall_f32(ky[1]);
for ( ; i <= width - v_float32::nlanes; i += v_float32::nlanes )
v_store(dst + i, v_muladd(vx_load(S2 + i) - vx_load(S0 + i), k1, d4));
}
}
return i;
}
int symmetryType;
float delta;
Mat kernel;
};
/////////////////////////////// non-separable filters ///////////////////////////////
///////////////////////////////// 8u<->8u, 8u<->16s /////////////////////////////////
struct FilterVec_8u
{
FilterVec_8u() { delta = 0; _nz = 0; }
FilterVec_8u(const Mat& _kernel, int _bits, double _delta)
{
Mat kernel;
_kernel.convertTo(kernel, CV_32F, 1./(1 << _bits), 0);
delta = (float)(_delta/(1 << _bits));
std::vector<Point> coords;
preprocess2DKernel(kernel, coords, coeffs);
_nz = (int)coords.size();
}
int operator()(const uchar** src, uchar* dst, int width) const
{
CV_INSTRUMENT_REGION();
CV_DbgAssert(_nz > 0);
const float* kf = (const float*)&coeffs[0];
int i = 0, k, nz = _nz;
v_float32 d4 = vx_setall_f32(delta);
v_float32 f0 = vx_setall_f32(kf[0]);
for( ; i <= width - v_uint8::nlanes; i += v_uint8::nlanes )
{
v_uint16 xl, xh;
v_expand(vx_load(src[0] + i), xl, xh);
v_uint32 x0, x1, x2, x3;
v_expand(xl, x0, x1);
v_expand(xh, x2, x3);
v_float32 s0 = v_muladd(v_cvt_f32(v_reinterpret_as_s32(x0)), f0, d4);
v_float32 s1 = v_muladd(v_cvt_f32(v_reinterpret_as_s32(x1)), f0, d4);
v_float32 s2 = v_muladd(v_cvt_f32(v_reinterpret_as_s32(x2)), f0, d4);
v_float32 s3 = v_muladd(v_cvt_f32(v_reinterpret_as_s32(x3)), f0, d4);
for( k = 1; k < nz; k++ )
{
v_float32 f = vx_setall_f32(kf[k]);
v_expand(vx_load(src[k] + i), xl, xh);
v_expand(xl, x0, x1);
v_expand(xh, x2, x3);
s0 = v_muladd(v_cvt_f32(v_reinterpret_as_s32(x0)), f, s0);
s1 = v_muladd(v_cvt_f32(v_reinterpret_as_s32(x1)), f, s1);
s2 = v_muladd(v_cvt_f32(v_reinterpret_as_s32(x2)), f, s2);
s3 = v_muladd(v_cvt_f32(v_reinterpret_as_s32(x3)), f, s3);
}
v_store(dst + i, v_pack_u(v_pack(v_round(s0), v_round(s1)), v_pack(v_round(s2), v_round(s3))));
}
if( i <= width - v_uint16::nlanes )
{
v_uint32 x0, x1;
v_expand(vx_load_expand(src[0] + i), x0, x1);
v_float32 s0 = v_muladd(v_cvt_f32(v_reinterpret_as_s32(x0)), f0, d4);
v_float32 s1 = v_muladd(v_cvt_f32(v_reinterpret_as_s32(x1)), f0, d4);
for( k = 1; k < nz; k++ )
{
v_float32 f = vx_setall_f32(kf[k]);
v_expand(vx_load_expand(src[k] + i), x0, x1);
s0 = v_muladd(v_cvt_f32(v_reinterpret_as_s32(x0)), f, s0);
s1 = v_muladd(v_cvt_f32(v_reinterpret_as_s32(x1)), f, s1);
}
v_pack_u_store(dst + i, v_pack(v_round(s0), v_round(s1)));
i += v_uint16::nlanes;
}
#if CV_SIMD_WIDTH > 16
while( i <= width - v_int32x4::nlanes )
#else
if( i <= width - v_int32x4::nlanes )
#endif
{
v_float32x4 s0 = v_muladd(v_cvt_f32(v_reinterpret_as_s32(v_load_expand_q(src[0] + i))), v_setall_f32(kf[0]), v_setall_f32(delta));
for( k = 1; k < nz; k++ )
s0 = v_muladd(v_cvt_f32(v_reinterpret_as_s32(v_load_expand_q(src[k] + i))), v_setall_f32(kf[k]), s0);
v_int32x4 s32 = v_round(s0);
v_int16x8 s16 = v_pack(s32, s32);
*(unaligned_int*)(dst + i) = v_reinterpret_as_s32(v_pack_u(s16, s16)).get0();
i += v_int32x4::nlanes;
}
return i;
}
int _nz;
std::vector<uchar> coeffs;
float delta;
};
struct FilterVec_8u16s
{
FilterVec_8u16s() { delta = 0; _nz = 0; }
FilterVec_8u16s(const Mat& _kernel, int _bits, double _delta)
{
Mat kernel;
_kernel.convertTo(kernel, CV_32F, 1./(1 << _bits), 0);
delta = (float)(_delta/(1 << _bits));
std::vector<Point> coords;
preprocess2DKernel(kernel, coords, coeffs);
_nz = (int)coords.size();
}
int operator()(const uchar** src, uchar* _dst, int width) const
{
CV_INSTRUMENT_REGION();
CV_DbgAssert(_nz > 0);
const float* kf = (const float*)&coeffs[0];
short* dst = (short*)_dst;
int i = 0, k, nz = _nz;
v_float32 d4 = vx_setall_f32(delta);
v_float32 f0 = vx_setall_f32(kf[0]);
for( ; i <= width - v_uint8::nlanes; i += v_uint8::nlanes )
{
v_uint16 xl, xh;
v_expand(vx_load(src[0] + i), xl, xh);
v_float32 s0 = v_muladd(v_cvt_f32(v_reinterpret_as_s32(v_expand_low(xl))), f0, d4);
v_float32 s1 = v_muladd(v_cvt_f32(v_reinterpret_as_s32(v_expand_high(xl))), f0, d4);
v_float32 s2 = v_muladd(v_cvt_f32(v_reinterpret_as_s32(v_expand_low(xh))), f0, d4);
v_float32 s3 = v_muladd(v_cvt_f32(v_reinterpret_as_s32(v_expand_high(xh))), f0, d4);
for( k = 1; k < nz; k++ )
{
v_float32 f = vx_setall_f32(kf[k]);
v_expand(vx_load(src[k] + i), xl, xh);
s0 = v_muladd(v_cvt_f32(v_reinterpret_as_s32(v_expand_low(xl))), f, s0);
s1 = v_muladd(v_cvt_f32(v_reinterpret_as_s32(v_expand_high(xl))), f, s1);
s2 = v_muladd(v_cvt_f32(v_reinterpret_as_s32(v_expand_low(xh))), f, s2);
s3 = v_muladd(v_cvt_f32(v_reinterpret_as_s32(v_expand_high(xh))), f, s3);
}
v_store(dst + i, v_pack(v_round(s0), v_round(s1)));
v_store(dst + i + v_int16::nlanes, v_pack(v_round(s2), v_round(s3)));
}
if( i <= width - v_uint16::nlanes )
{
v_uint16 x = vx_load_expand(src[0] + i);
v_float32 s0 = v_muladd(v_cvt_f32(v_reinterpret_as_s32(v_expand_low(x))), f0, d4);
v_float32 s1 = v_muladd(v_cvt_f32(v_reinterpret_as_s32(v_expand_high(x))), f0, d4);
for( k = 1; k < nz; k++ )
{
v_float32 f = vx_setall_f32(kf[k]);
x = vx_load_expand(src[k] + i);
s0 = v_muladd(v_cvt_f32(v_reinterpret_as_s32(v_expand_low(x))), f, s0);
s1 = v_muladd(v_cvt_f32(v_reinterpret_as_s32(v_expand_high(x))), f, s1);
}
v_store(dst + i, v_pack(v_round(s0), v_round(s1)));
i += v_uint16::nlanes;
}
if( i <= width - v_int32::nlanes )
{
v_float32 s0 = v_muladd(v_cvt_f32(v_reinterpret_as_s32(vx_load_expand_q(src[0] + i))), f0, d4);
for( k = 1; k < nz; k++ )
s0 = v_muladd(v_cvt_f32(v_reinterpret_as_s32(vx_load_expand_q(src[k] + i))), vx_setall_f32(kf[k]), s0);
v_pack_store(dst + i, v_round(s0));
i += v_int32::nlanes;
}
return i;
}
int _nz;
std::vector<uchar> coeffs;
float delta;
};
struct FilterVec_32f
{
FilterVec_32f() { delta = 0; _nz = 0; }
FilterVec_32f(const Mat& _kernel, int, double _delta)
{
delta = (float)_delta;
std::vector<Point> coords;
preprocess2DKernel(_kernel, coords, coeffs);
_nz = (int)coords.size();
}
int operator()(const uchar** _src, uchar* _dst, int width) const
{
CV_INSTRUMENT_REGION();
const float* kf = (const float*)&coeffs[0];
const float** src = (const float**)_src;
float* dst = (float*)_dst;
int i = 0, k, nz = _nz;
v_float32 d4 = vx_setall_f32(delta);
v_float32 f0 = vx_setall_f32(kf[0]);
for( ; i <= width - 4*v_float32::nlanes; i += 4*v_float32::nlanes )
{
v_float32 s0 = v_muladd(vx_load(src[0] + i), f0, d4);
v_float32 s1 = v_muladd(vx_load(src[0] + i + v_float32::nlanes), f0, d4);
v_float32 s2 = v_muladd(vx_load(src[0] + i + 2*v_float32::nlanes), f0, d4);
v_float32 s3 = v_muladd(vx_load(src[0] + i + 3*v_float32::nlanes), f0, d4);
for( k = 1; k < nz; k++ )
{
v_float32 f1 = vx_setall_f32(kf[k]);
s0 = v_muladd(vx_load(src[k] + i), f1, s0);
s1 = v_muladd(vx_load(src[k] + i + v_float32::nlanes), f1, s1);
s2 = v_muladd(vx_load(src[k] + i + 2*v_float32::nlanes), f1, s2);
s3 = v_muladd(vx_load(src[k] + i + 3*v_float32::nlanes), f1, s3);
}
v_store(dst + i, s0);
v_store(dst + i + v_float32::nlanes, s1);
v_store(dst + i + 2*v_float32::nlanes, s2);
v_store(dst + i + 3*v_float32::nlanes, s3);
}
if( i <= width - 2*v_float32::nlanes )
{
v_float32 s0 = v_muladd(vx_load(src[0] + i), f0, d4);
v_float32 s1 = v_muladd(vx_load(src[0] + i + v_float32::nlanes), f0, d4);
for( k = 1; k < nz; k++ )
{
v_float32 f1 = vx_setall_f32(kf[k]);
s0 = v_muladd(vx_load(src[k] + i), f1, s0);
s1 = v_muladd(vx_load(src[k] + i + v_float32::nlanes), f1, s1);
}
v_store(dst + i, s0);
v_store(dst + i + v_float32::nlanes, s1);
i += 2*v_float32::nlanes;
}
if( i <= width - v_float32::nlanes )
{
v_float32 s0 = v_muladd(vx_load(src[0] + i), f0, d4);
for( k = 1; k < nz; k++ )
s0 = v_muladd(vx_load(src[k] + i), vx_setall_f32(kf[k]), s0);
v_store(dst + i, s0);
i += v_float32::nlanes;
}
return i;
}
int _nz;
std::vector<uchar> coeffs;
float delta;
};
#else
typedef RowNoVec RowVec_8u32s;
typedef RowNoVec RowVec_16s32f;
typedef RowNoVec RowVec_32f;
typedef SymmRowSmallNoVec SymmRowSmallVec_8u32s;
typedef SymmRowSmallNoVec SymmRowSmallVec_32f;
typedef ColumnNoVec SymmColumnVec_32s8u;
typedef ColumnNoVec SymmColumnVec_32f16s;
typedef ColumnNoVec SymmColumnVec_32f;
typedef SymmColumnSmallNoVec SymmColumnSmallVec_32s16s;
typedef SymmColumnSmallNoVec SymmColumnSmallVec_32f;
typedef FilterNoVec FilterVec_8u;
typedef FilterNoVec FilterVec_8u16s;
typedef FilterNoVec FilterVec_32f;
#endif
template<typename ST, typename DT, class VecOp> struct RowFilter : public BaseRowFilter
{
RowFilter( const Mat& _kernel, int _anchor, const VecOp& _vecOp=VecOp() )
{
if( _kernel.isContinuous() )
kernel = _kernel;
else
_kernel.copyTo(kernel);
anchor = _anchor;
ksize = kernel.rows + kernel.cols - 1;
CV_Assert( kernel.type() == DataType<DT>::type &&
(kernel.rows == 1 || kernel.cols == 1));
vecOp = _vecOp;
}
void operator()(const uchar* src, uchar* dst, int width, int cn) CV_OVERRIDE
{
CV_INSTRUMENT_REGION();
int _ksize = ksize;
const DT* kx = kernel.ptr<DT>();
const ST* S;
DT* D = (DT*)dst;
int i, k;
i = vecOp(src, dst, width, cn);
width *= cn;
#if CV_ENABLE_UNROLLED
for( ; i <= width - 4; i += 4 )
{
S = (const ST*)src + i;
DT f = kx[0];
DT s0 = f*S[0], s1 = f*S[1], s2 = f*S[2], s3 = f*S[3];
for( k = 1; k < _ksize; k++ )
{
S += cn;
f = kx[k];
s0 += f*S[0]; s1 += f*S[1];
s2 += f*S[2]; s3 += f*S[3];
}
D[i] = s0; D[i+1] = s1;
D[i+2] = s2; D[i+3] = s3;
}
#endif
for( ; i < width; i++ )
{
S = (const ST*)src + i;
DT s0 = kx[0]*S[0];
for( k = 1; k < _ksize; k++ )
{
S += cn;
s0 += kx[k]*S[0];
}
D[i] = s0;
}
}
Mat kernel;
VecOp vecOp;
};
template<typename ST, typename DT, class VecOp> struct SymmRowSmallFilter :
public RowFilter<ST, DT, VecOp>
{
SymmRowSmallFilter( const Mat& _kernel, int _anchor, int _symmetryType,
const VecOp& _vecOp = VecOp())
: RowFilter<ST, DT, VecOp>( _kernel, _anchor, _vecOp )
{
symmetryType = _symmetryType;
CV_Assert( (symmetryType & (KERNEL_SYMMETRICAL | KERNEL_ASYMMETRICAL)) != 0 && this->ksize <= 5 );
}
void operator()(const uchar* src, uchar* dst, int width, int cn) CV_OVERRIDE
{
CV_INSTRUMENT_REGION();
int ksize2 = this->ksize/2, ksize2n = ksize2*cn;
const DT* kx = this->kernel.template ptr<DT>() + ksize2;
bool symmetrical = (this->symmetryType & KERNEL_SYMMETRICAL) != 0;
DT* D = (DT*)dst;
int i = this->vecOp(src, dst, width, cn), j, k;
const ST* S = (const ST*)src + i + ksize2n;
width *= cn;
if( symmetrical )
{
if( this->ksize == 1 && kx[0] == 1 )
{
for( ; i <= width - 2; i += 2 )
{
DT s0 = S[i], s1 = S[i+1];
D[i] = s0; D[i+1] = s1;
}
S += i;
}
else if( this->ksize == 3 )
{
if( kx[0] == 2 && kx[1] == 1 )
for( ; i <= width - 2; i += 2, S += 2 )
{
DT s0 = S[-cn] + S[0]*2 + S[cn], s1 = S[1-cn] + S[1]*2 + S[1+cn];
D[i] = s0; D[i+1] = s1;
}
else if( kx[0] == -2 && kx[1] == 1 )
for( ; i <= width - 2; i += 2, S += 2 )
{
DT s0 = S[-cn] - S[0]*2 + S[cn], s1 = S[1-cn] - S[1]*2 + S[1+cn];
D[i] = s0; D[i+1] = s1;
}
else
{
DT k0 = kx[0], k1 = kx[1];
for( ; i <= width - 2; i += 2, S += 2 )
{
DT s0 = S[0]*k0 + (S[-cn] + S[cn])*k1, s1 = S[1]*k0 + (S[1-cn] + S[1+cn])*k1;
D[i] = s0; D[i+1] = s1;
}
}
}
else if( this->ksize == 5 )
{
DT k0 = kx[0], k1 = kx[1], k2 = kx[2];
if( k0 == -2 && k1 == 0 && k2 == 1 )
for( ; i <= width - 2; i += 2, S += 2 )
{
DT s0 = -2*S[0] + S[-cn*2] + S[cn*2];
DT s1 = -2*S[1] + S[1-cn*2] + S[1+cn*2];
D[i] = s0; D[i+1] = s1;
}
else
for( ; i <= width - 2; i += 2, S += 2 )
{
DT s0 = S[0]*k0 + (S[-cn] + S[cn])*k1 + (S[-cn*2] + S[cn*2])*k2;
DT s1 = S[1]*k0 + (S[1-cn] + S[1+cn])*k1 + (S[1-cn*2] + S[1+cn*2])*k2;
D[i] = s0; D[i+1] = s1;
}
}
for( ; i < width; i++, S++ )
{
DT s0 = kx[0]*S[0];
for( k = 1, j = cn; k <= ksize2; k++, j += cn )
s0 += kx[k]*(S[j] + S[-j]);
D[i] = s0;
}
}
else
{
if( this->ksize == 3 )
{
if( kx[0] == 0 && kx[1] == 1 )
for( ; i <= width - 2; i += 2, S += 2 )
{
DT s0 = S[cn] - S[-cn], s1 = S[1+cn] - S[1-cn];
D[i] = s0; D[i+1] = s1;
}
else
{
DT k1 = kx[1];
for( ; i <= width - 2; i += 2, S += 2 )
{
DT s0 = (S[cn] - S[-cn])*k1, s1 = (S[1+cn] - S[1-cn])*k1;
D[i] = s0; D[i+1] = s1;
}
}
}
else if( this->ksize == 5 )
{
DT k1 = kx[1], k2 = kx[2];
for( ; i <= width - 2; i += 2, S += 2 )
{
DT s0 = (S[cn] - S[-cn])*k1 + (S[cn*2] - S[-cn*2])*k2;
DT s1 = (S[1+cn] - S[1-cn])*k1 + (S[1+cn*2] - S[1-cn*2])*k2;
D[i] = s0; D[i+1] = s1;
}
}
for( ; i < width; i++, S++ )
{
DT s0 = kx[0]*S[0];
for( k = 1, j = cn; k <= ksize2; k++, j += cn )
s0 += kx[k]*(S[j] - S[-j]);
D[i] = s0;
}
}
}
int symmetryType;
};
template<class CastOp, class VecOp> struct ColumnFilter : public BaseColumnFilter
{
typedef typename CastOp::type1 ST;
typedef typename CastOp::rtype DT;
ColumnFilter( const Mat& _kernel, int _anchor,
double _delta, const CastOp& _castOp=CastOp(),
const VecOp& _vecOp=VecOp() )
{
if( _kernel.isContinuous() )
kernel = _kernel;
else
_kernel.copyTo(kernel);
anchor = _anchor;
ksize = kernel.rows + kernel.cols - 1;
delta = saturate_cast<ST>(_delta);
castOp0 = _castOp;
vecOp = _vecOp;
CV_Assert( kernel.type() == DataType<ST>::type &&
(kernel.rows == 1 || kernel.cols == 1));
}
void operator()(const uchar** src, uchar* dst, int dststep, int count, int width) CV_OVERRIDE
{
CV_INSTRUMENT_REGION();
const ST* ky = kernel.template ptr<ST>();
ST _delta = delta;
int _ksize = ksize;
int i, k;
CastOp castOp = castOp0;
for( ; count--; dst += dststep, src++ )
{
DT* D = (DT*)dst;
i = vecOp(src, dst, width);
#if CV_ENABLE_UNROLLED
for( ; i <= width - 4; i += 4 )
{
ST f = ky[0];
const ST* S = (const ST*)src[0] + i;
ST s0 = f*S[0] + _delta, s1 = f*S[1] + _delta,
s2 = f*S[2] + _delta, s3 = f*S[3] + _delta;
for( k = 1; k < _ksize; k++ )
{
S = (const ST*)src[k] + i; f = ky[k];
s0 += f*S[0]; s1 += f*S[1];
s2 += f*S[2]; s3 += f*S[3];
}
D[i] = castOp(s0); D[i+1] = castOp(s1);
D[i+2] = castOp(s2); D[i+3] = castOp(s3);
}
#endif
for( ; i < width; i++ )
{
ST s0 = ky[0]*((const ST*)src[0])[i] + _delta;
for( k = 1; k < _ksize; k++ )
s0 += ky[k]*((const ST*)src[k])[i];
D[i] = castOp(s0);
}
}
}
Mat kernel;
CastOp castOp0;
VecOp vecOp;
ST delta;
};
template<class CastOp, class VecOp> struct SymmColumnFilter : public ColumnFilter<CastOp, VecOp>
{
typedef typename CastOp::type1 ST;
typedef typename CastOp::rtype DT;
SymmColumnFilter( const Mat& _kernel, int _anchor,
double _delta, int _symmetryType,
const CastOp& _castOp=CastOp(),
const VecOp& _vecOp=VecOp())
: ColumnFilter<CastOp, VecOp>( _kernel, _anchor, _delta, _castOp, _vecOp )
{
symmetryType = _symmetryType;
CV_Assert( (symmetryType & (KERNEL_SYMMETRICAL | KERNEL_ASYMMETRICAL)) != 0 );
}
void operator()(const uchar** src, uchar* dst, int dststep, int count, int width) CV_OVERRIDE
{
CV_INSTRUMENT_REGION();
int ksize2 = this->ksize/2;
const ST* ky = this->kernel.template ptr<ST>() + ksize2;
int i, k;
bool symmetrical = (symmetryType & KERNEL_SYMMETRICAL) != 0;
ST _delta = this->delta;
CastOp castOp = this->castOp0;
src += ksize2;
if( symmetrical )
{
for( ; count--; dst += dststep, src++ )
{
DT* D = (DT*)dst;
i = (this->vecOp)(src, dst, width);
#if CV_ENABLE_UNROLLED
for( ; i <= width - 4; i += 4 )
{
ST f = ky[0];
const ST* S = (const ST*)src[0] + i, *S2;
ST s0 = f*S[0] + _delta, s1 = f*S[1] + _delta,
s2 = f*S[2] + _delta, s3 = f*S[3] + _delta;
for( k = 1; k <= ksize2; k++ )
{
S = (const ST*)src[k] + i;
S2 = (const ST*)src[-k] + i;
f = ky[k];
s0 += f*(S[0] + S2[0]);
s1 += f*(S[1] + S2[1]);
s2 += f*(S[2] + S2[2]);
s3 += f*(S[3] + S2[3]);
}
D[i] = castOp(s0); D[i+1] = castOp(s1);
D[i+2] = castOp(s2); D[i+3] = castOp(s3);
}
#endif
for( ; i < width; i++ )
{
ST s0 = ky[0]*((const ST*)src[0])[i] + _delta;
for( k = 1; k <= ksize2; k++ )
s0 += ky[k]*(((const ST*)src[k])[i] + ((const ST*)src[-k])[i]);
D[i] = castOp(s0);
}
}
}
else
{
for( ; count--; dst += dststep, src++ )
{
DT* D = (DT*)dst;
i = this->vecOp(src, dst, width);
#if CV_ENABLE_UNROLLED
for( ; i <= width - 4; i += 4 )
{
ST f = ky[0];
const ST *S, *S2;
ST s0 = _delta, s1 = _delta, s2 = _delta, s3 = _delta;
for( k = 1; k <= ksize2; k++ )
{
S = (const ST*)src[k] + i;
S2 = (const ST*)src[-k] + i;
f = ky[k];
s0 += f*(S[0] - S2[0]);
s1 += f*(S[1] - S2[1]);
s2 += f*(S[2] - S2[2]);
s3 += f*(S[3] - S2[3]);
}
D[i] = castOp(s0); D[i+1] = castOp(s1);
D[i+2] = castOp(s2); D[i+3] = castOp(s3);
}
#endif
for( ; i < width; i++ )
{
ST s0 = _delta;
for( k = 1; k <= ksize2; k++ )
s0 += ky[k]*(((const ST*)src[k])[i] - ((const ST*)src[-k])[i]);
D[i] = castOp(s0);
}
}
}
}
int symmetryType;
};
template<class CastOp, class VecOp>
struct SymmColumnSmallFilter : public SymmColumnFilter<CastOp, VecOp>
{
typedef typename CastOp::type1 ST;
typedef typename CastOp::rtype DT;
SymmColumnSmallFilter( const Mat& _kernel, int _anchor,
double _delta, int _symmetryType,
const CastOp& _castOp=CastOp(),
const VecOp& _vecOp=VecOp())
: SymmColumnFilter<CastOp, VecOp>( _kernel, _anchor, _delta, _symmetryType, _castOp, _vecOp )
{
CV_Assert( this->ksize == 3 );
}
void operator()(const uchar** src, uchar* dst, int dststep, int count, int width) CV_OVERRIDE
{
CV_INSTRUMENT_REGION();
int ksize2 = this->ksize/2;
const ST* ky = this->kernel.template ptr<ST>() + ksize2;
int i;
bool symmetrical = (this->symmetryType & KERNEL_SYMMETRICAL) != 0;
bool is_1_2_1 = ky[0] == 2 && ky[1] == 1;
bool is_1_m2_1 = ky[0] == -2 && ky[1] == 1;
bool is_m1_0_1 = ky[0] == 0 && (ky[1] == 1 || ky[1] == -1);
ST f0 = ky[0], f1 = ky[1];
ST _delta = this->delta;
CastOp castOp = this->castOp0;
src += ksize2;
for( ; count--; dst += dststep, src++ )
{
DT* D = (DT*)dst;
i = (this->vecOp)(src, dst, width);
const ST* S0 = (const ST*)src[-1];
const ST* S1 = (const ST*)src[0];
const ST* S2 = (const ST*)src[1];
if( symmetrical )
{
if( is_1_2_1 )
{
#if CV_ENABLE_UNROLLED
for( ; i <= width - 4; i += 4 )
{
ST s0 = S0[i] + S1[i]*2 + S2[i] + _delta;
ST s1 = S0[i+1] + S1[i+1]*2 + S2[i+1] + _delta;
D[i] = castOp(s0);
D[i+1] = castOp(s1);
s0 = S0[i+2] + S1[i+2]*2 + S2[i+2] + _delta;
s1 = S0[i+3] + S1[i+3]*2 + S2[i+3] + _delta;
D[i+2] = castOp(s0);
D[i+3] = castOp(s1);
}
#endif
for( ; i < width; i ++ )
{
ST s0 = S0[i] + S1[i]*2 + S2[i] + _delta;
D[i] = castOp(s0);
}
}
else if( is_1_m2_1 )
{
#if CV_ENABLE_UNROLLED
for( ; i <= width - 4; i += 4 )
{
ST s0 = S0[i] - S1[i]*2 + S2[i] + _delta;
ST s1 = S0[i+1] - S1[i+1]*2 + S2[i+1] + _delta;
D[i] = castOp(s0);
D[i+1] = castOp(s1);
s0 = S0[i+2] - S1[i+2]*2 + S2[i+2] + _delta;
s1 = S0[i+3] - S1[i+3]*2 + S2[i+3] + _delta;
D[i+2] = castOp(s0);
D[i+3] = castOp(s1);
}
#endif
for( ; i < width; i ++ )
{
ST s0 = S0[i] - S1[i]*2 + S2[i] + _delta;
D[i] = castOp(s0);
}
}
else
{
#if CV_ENABLE_UNROLLED
for( ; i <= width - 4; i += 4 )
{
ST s0 = (S0[i] + S2[i])*f1 + S1[i]*f0 + _delta;
ST s1 = (S0[i+1] + S2[i+1])*f1 + S1[i+1]*f0 + _delta;
D[i] = castOp(s0);
D[i+1] = castOp(s1);
s0 = (S0[i+2] + S2[i+2])*f1 + S1[i+2]*f0 + _delta;
s1 = (S0[i+3] + S2[i+3])*f1 + S1[i+3]*f0 + _delta;
D[i+2] = castOp(s0);
D[i+3] = castOp(s1);
}
#endif
for( ; i < width; i ++ )
{
ST s0 = (S0[i] + S2[i])*f1 + S1[i]*f0 + _delta;
D[i] = castOp(s0);
}
}
}
else
{
if( is_m1_0_1 )
{
if( f1 < 0 )
std::swap(S0, S2);
#if CV_ENABLE_UNROLLED
for( ; i <= width - 4; i += 4 )
{
ST s0 = S2[i] - S0[i] + _delta;
ST s1 = S2[i+1] - S0[i+1] + _delta;
D[i] = castOp(s0);
D[i+1] = castOp(s1);
s0 = S2[i+2] - S0[i+2] + _delta;
s1 = S2[i+3] - S0[i+3] + _delta;
D[i+2] = castOp(s0);
D[i+3] = castOp(s1);
}
#endif
for( ; i < width; i ++ )
{
ST s0 = S2[i] - S0[i] + _delta;
D[i] = castOp(s0);
}
if( f1 < 0 )
std::swap(S0, S2);
}
else
{
#if CV_ENABLE_UNROLLED
for( ; i <= width - 4; i += 4 )
{
ST s0 = (S2[i] - S0[i])*f1 + _delta;
ST s1 = (S2[i+1] - S0[i+1])*f1 + _delta;
D[i] = castOp(s0);
D[i+1] = castOp(s1);
s0 = (S2[i+2] - S0[i+2])*f1 + _delta;
s1 = (S2[i+3] - S0[i+3])*f1 + _delta;
D[i+2] = castOp(s0);
D[i+3] = castOp(s1);
}
#endif
for( ; i < width; i++ )
D[i] = castOp((S2[i] - S0[i])*f1 + _delta);
}
}
}
}
};
template<typename ST, typename DT> struct Cast
{
typedef ST type1;
typedef DT rtype;
DT operator()(ST val) const { return saturate_cast<DT>(val); }
};
template<typename ST, typename DT, int bits> struct FixedPtCast
{
typedef ST type1;
typedef DT rtype;
enum { SHIFT = bits, DELTA = 1 << (bits-1) };
DT operator()(ST val) const { return saturate_cast<DT>((val + DELTA)>>SHIFT); }
};
template<typename ST, typename DT> struct FixedPtCastEx
{
typedef ST type1;
typedef DT rtype;
FixedPtCastEx() : SHIFT(0), DELTA(0) {}
FixedPtCastEx(int bits) : SHIFT(bits), DELTA(bits ? 1 << (bits-1) : 0) {}
DT operator()(ST val) const { return saturate_cast<DT>((val + DELTA)>>SHIFT); }
int SHIFT, DELTA;
};
Ptr<BaseRowFilter> getLinearRowFilter(
int srcType, int bufType,
const Mat& kernel, int anchor,
int symmetryType)
{
CV_INSTRUMENT_REGION();
int sdepth = CV_MAT_DEPTH(srcType), ddepth = CV_MAT_DEPTH(bufType);
int cn = CV_MAT_CN(srcType);
CV_Assert( cn == CV_MAT_CN(bufType) &&
ddepth >= std::max(sdepth, CV_32S) &&
kernel.type() == ddepth );
int ksize = kernel.rows + kernel.cols - 1;
if( (symmetryType & (KERNEL_SYMMETRICAL|KERNEL_ASYMMETRICAL)) != 0 && ksize <= 5 )
{
if( sdepth == CV_8U && ddepth == CV_32S )
return makePtr<SymmRowSmallFilter<uchar, int, SymmRowSmallVec_8u32s> >
(kernel, anchor, symmetryType, SymmRowSmallVec_8u32s(kernel, symmetryType));
if( sdepth == CV_32F && ddepth == CV_32F )
return makePtr<SymmRowSmallFilter<float, float, SymmRowSmallVec_32f> >
(kernel, anchor, symmetryType, SymmRowSmallVec_32f(kernel, symmetryType));
}
if( sdepth == CV_8U && ddepth == CV_32S )
return makePtr<RowFilter<uchar, int, RowVec_8u32s> >
(kernel, anchor, RowVec_8u32s(kernel));
if( sdepth == CV_8U && ddepth == CV_32F )
return makePtr<RowFilter<uchar, float, RowNoVec> >(kernel, anchor);
if( sdepth == CV_8U && ddepth == CV_64F )
return makePtr<RowFilter<uchar, double, RowNoVec> >(kernel, anchor);
if( sdepth == CV_16U && ddepth == CV_32F )
return makePtr<RowFilter<ushort, float, RowNoVec> >(kernel, anchor);
if( sdepth == CV_16U && ddepth == CV_64F )
return makePtr<RowFilter<ushort, double, RowNoVec> >(kernel, anchor);
if( sdepth == CV_16S && ddepth == CV_32F )
return makePtr<RowFilter<short, float, RowVec_16s32f> >
(kernel, anchor, RowVec_16s32f(kernel));
if( sdepth == CV_16S && ddepth == CV_64F )
return makePtr<RowFilter<short, double, RowNoVec> >(kernel, anchor);
if( sdepth == CV_32F && ddepth == CV_32F )
return makePtr<RowFilter<float, float, RowVec_32f> >
(kernel, anchor, RowVec_32f(kernel));
if( sdepth == CV_32F && ddepth == CV_64F )
return makePtr<RowFilter<float, double, RowNoVec> >(kernel, anchor);
if( sdepth == CV_64F && ddepth == CV_64F )
return makePtr<RowFilter<double, double, RowNoVec> >(kernel, anchor);
CV_Error_( CV_StsNotImplemented,
("Unsupported combination of source format (=%d), and buffer format (=%d)",
srcType, bufType));
}
Ptr<BaseColumnFilter> getLinearColumnFilter(
int bufType, int dstType,
const Mat& kernel, int anchor,
int symmetryType, double delta,
int bits)
{
CV_INSTRUMENT_REGION();
int sdepth = CV_MAT_DEPTH(bufType), ddepth = CV_MAT_DEPTH(dstType);
int cn = CV_MAT_CN(dstType);
CV_Assert( cn == CV_MAT_CN(bufType) &&
sdepth >= std::max(ddepth, CV_32S) &&
kernel.type() == sdepth );
if( !(symmetryType & (KERNEL_SYMMETRICAL|KERNEL_ASYMMETRICAL)) )
{
if( ddepth == CV_8U && sdepth == CV_32S )
return makePtr<ColumnFilter<FixedPtCastEx<int, uchar>, ColumnNoVec> >
(kernel, anchor, delta, FixedPtCastEx<int, uchar>(bits));
if( ddepth == CV_8U && sdepth == CV_32F )
return makePtr<ColumnFilter<Cast<float, uchar>, ColumnNoVec> >(kernel, anchor, delta);
if( ddepth == CV_8U && sdepth == CV_64F )
return makePtr<ColumnFilter<Cast<double, uchar>, ColumnNoVec> >(kernel, anchor, delta);
if( ddepth == CV_16U && sdepth == CV_32F )
return makePtr<ColumnFilter<Cast<float, ushort>, ColumnNoVec> >(kernel, anchor, delta);
if( ddepth == CV_16U && sdepth == CV_64F )
return makePtr<ColumnFilter<Cast<double, ushort>, ColumnNoVec> >(kernel, anchor, delta);
if( ddepth == CV_16S && sdepth == CV_32F )
return makePtr<ColumnFilter<Cast<float, short>, ColumnNoVec> >(kernel, anchor, delta);
if( ddepth == CV_16S && sdepth == CV_64F )
return makePtr<ColumnFilter<Cast<double, short>, ColumnNoVec> >(kernel, anchor, delta);
if( ddepth == CV_32F && sdepth == CV_32F )
return makePtr<ColumnFilter<Cast<float, float>, ColumnNoVec> >(kernel, anchor, delta);
if( ddepth == CV_64F && sdepth == CV_64F )
return makePtr<ColumnFilter<Cast<double, double>, ColumnNoVec> >(kernel, anchor, delta);
}
else
{
int ksize = kernel.rows + kernel.cols - 1;
if( ksize == 3 )
{
if( ddepth == CV_8U && sdepth == CV_32S )
return makePtr<SymmColumnSmallFilter<
FixedPtCastEx<int, uchar>, SymmColumnVec_32s8u> >
(kernel, anchor, delta, symmetryType, FixedPtCastEx<int, uchar>(bits),
SymmColumnVec_32s8u(kernel, symmetryType, bits, delta));
if( ddepth == CV_16S && sdepth == CV_32S && bits == 0 )
return makePtr<SymmColumnSmallFilter<Cast<int, short>,
SymmColumnSmallVec_32s16s> >(kernel, anchor, delta, symmetryType,
Cast<int, short>(), SymmColumnSmallVec_32s16s(kernel, symmetryType, bits, delta));
if( ddepth == CV_32F && sdepth == CV_32F )
return makePtr<SymmColumnSmallFilter<
Cast<float, float>,SymmColumnSmallVec_32f> >
(kernel, anchor, delta, symmetryType, Cast<float, float>(),
SymmColumnSmallVec_32f(kernel, symmetryType, 0, delta));
}
if( ddepth == CV_8U && sdepth == CV_32S )
return makePtr<SymmColumnFilter<FixedPtCastEx<int, uchar>, SymmColumnVec_32s8u> >
(kernel, anchor, delta, symmetryType, FixedPtCastEx<int, uchar>(bits),
SymmColumnVec_32s8u(kernel, symmetryType, bits, delta));
if( ddepth == CV_8U && sdepth == CV_32F )
return makePtr<SymmColumnFilter<Cast<float, uchar>, ColumnNoVec> >
(kernel, anchor, delta, symmetryType);
if( ddepth == CV_8U && sdepth == CV_64F )
return makePtr<SymmColumnFilter<Cast<double, uchar>, ColumnNoVec> >
(kernel, anchor, delta, symmetryType);
if( ddepth == CV_16U && sdepth == CV_32F )
return makePtr<SymmColumnFilter<Cast<float, ushort>, ColumnNoVec> >
(kernel, anchor, delta, symmetryType);
if( ddepth == CV_16U && sdepth == CV_64F )
return makePtr<SymmColumnFilter<Cast<double, ushort>, ColumnNoVec> >
(kernel, anchor, delta, symmetryType);
if( ddepth == CV_16S && sdepth == CV_32S )
return makePtr<SymmColumnFilter<Cast<int, short>, ColumnNoVec> >
(kernel, anchor, delta, symmetryType);
if( ddepth == CV_16S && sdepth == CV_32F )
return makePtr<SymmColumnFilter<Cast<float, short>, SymmColumnVec_32f16s> >
(kernel, anchor, delta, symmetryType, Cast<float, short>(),
SymmColumnVec_32f16s(kernel, symmetryType, 0, delta));
if( ddepth == CV_16S && sdepth == CV_64F )
return makePtr<SymmColumnFilter<Cast<double, short>, ColumnNoVec> >
(kernel, anchor, delta, symmetryType);
if( ddepth == CV_32F && sdepth == CV_32F )
return makePtr<SymmColumnFilter<Cast<float, float>, SymmColumnVec_32f> >
(kernel, anchor, delta, symmetryType, Cast<float, float>(),
SymmColumnVec_32f(kernel, symmetryType, 0, delta));
if( ddepth == CV_64F && sdepth == CV_64F )
return makePtr<SymmColumnFilter<Cast<double, double>, ColumnNoVec> >
(kernel, anchor, delta, symmetryType);
}
CV_Error_( CV_StsNotImplemented,
("Unsupported combination of buffer format (=%d), and destination format (=%d)",
bufType, dstType));
}
template<typename ST, class CastOp, class VecOp> struct Filter2D : public BaseFilter
{
typedef typename CastOp::type1 KT;
typedef typename CastOp::rtype DT;
Filter2D( const Mat& _kernel, Point _anchor,
double _delta, const CastOp& _castOp=CastOp(),
const VecOp& _vecOp=VecOp() )
{
anchor = _anchor;
ksize = _kernel.size();
delta = saturate_cast<KT>(_delta);
castOp0 = _castOp;
vecOp = _vecOp;
CV_Assert( _kernel.type() == DataType<KT>::type );
preprocess2DKernel( _kernel, coords, coeffs );
ptrs.resize( coords.size() );
}
void operator()(const uchar** src, uchar* dst, int dststep, int count, int width, int cn) CV_OVERRIDE
{
KT _delta = delta;
const Point* pt = &coords[0];
const KT* kf = (const KT*)&coeffs[0];
const ST** kp = (const ST**)&ptrs[0];
int i, k, nz = (int)coords.size();
CastOp castOp = castOp0;
width *= cn;
for( ; count > 0; count--, dst += dststep, src++ )
{
DT* D = (DT*)dst;
for( k = 0; k < nz; k++ )
kp[k] = (const ST*)src[pt[k].y] + pt[k].x*cn;
i = vecOp((const uchar**)kp, dst, width);
#if CV_ENABLE_UNROLLED
for( ; i <= width - 4; i += 4 )
{
KT s0 = _delta, s1 = _delta, s2 = _delta, s3 = _delta;
for( k = 0; k < nz; k++ )
{
const ST* sptr = kp[k] + i;
KT f = kf[k];
s0 += f*sptr[0];
s1 += f*sptr[1];
s2 += f*sptr[2];
s3 += f*sptr[3];
}
D[i] = castOp(s0); D[i+1] = castOp(s1);
D[i+2] = castOp(s2); D[i+3] = castOp(s3);
}
#endif
for( ; i < width; i++ )
{
KT s0 = _delta;
for( k = 0; k < nz; k++ )
s0 += kf[k]*kp[k][i];
D[i] = castOp(s0);
}
}
}
std::vector<Point> coords;
std::vector<uchar> coeffs;
std::vector<uchar*> ptrs;
KT delta;
CastOp castOp0;
VecOp vecOp;
};
Ptr<BaseFilter> getLinearFilter(
int srcType, int dstType,
const Mat& _kernel, Point anchor,
double delta, int bits)
{
CV_INSTRUMENT_REGION();
int sdepth = CV_MAT_DEPTH(srcType), ddepth = CV_MAT_DEPTH(dstType);
int cn = CV_MAT_CN(srcType), kdepth = _kernel.depth();
CV_Assert( cn == CV_MAT_CN(dstType) && ddepth >= sdepth );
anchor = normalizeAnchor(anchor, _kernel.size());
/*if( sdepth == CV_8U && ddepth == CV_8U && kdepth == CV_32S )
return makePtr<Filter2D<uchar, FixedPtCastEx<int, uchar>, FilterVec_8u> >
(_kernel, anchor, delta, FixedPtCastEx<int, uchar>(bits),
FilterVec_8u(_kernel, bits, delta));
if( sdepth == CV_8U && ddepth == CV_16S && kdepth == CV_32S )
return makePtr<Filter2D<uchar, FixedPtCastEx<int, short>, FilterVec_8u16s> >
(_kernel, anchor, delta, FixedPtCastEx<int, short>(bits),
FilterVec_8u16s(_kernel, bits, delta));*/
kdepth = sdepth == CV_64F || ddepth == CV_64F ? CV_64F : CV_32F;
Mat kernel;
if( _kernel.type() == kdepth )
kernel = _kernel;
else
_kernel.convertTo(kernel, kdepth, _kernel.type() == CV_32S ? 1./(1 << bits) : 1.);
if( sdepth == CV_8U && ddepth == CV_8U )
return makePtr<Filter2D<uchar, Cast<float, uchar>, FilterVec_8u> >
(kernel, anchor, delta, Cast<float, uchar>(), FilterVec_8u(kernel, 0, delta));
if( sdepth == CV_8U && ddepth == CV_16U )
return makePtr<Filter2D<uchar,
Cast<float, ushort>, FilterNoVec> >(kernel, anchor, delta);
if( sdepth == CV_8U && ddepth == CV_16S )
return makePtr<Filter2D<uchar, Cast<float, short>, FilterVec_8u16s> >
(kernel, anchor, delta, Cast<float, short>(), FilterVec_8u16s(kernel, 0, delta));
if( sdepth == CV_8U && ddepth == CV_32F )
return makePtr<Filter2D<uchar,
Cast<float, float>, FilterNoVec> >(kernel, anchor, delta);
if( sdepth == CV_8U && ddepth == CV_64F )
return makePtr<Filter2D<uchar,
Cast<double, double>, FilterNoVec> >(kernel, anchor, delta);
if( sdepth == CV_16U && ddepth == CV_16U )
return makePtr<Filter2D<ushort,
Cast<float, ushort>, FilterNoVec> >(kernel, anchor, delta);
if( sdepth == CV_16U && ddepth == CV_32F )
return makePtr<Filter2D<ushort,
Cast<float, float>, FilterNoVec> >(kernel, anchor, delta);
if( sdepth == CV_16U && ddepth == CV_64F )
return makePtr<Filter2D<ushort,
Cast<double, double>, FilterNoVec> >(kernel, anchor, delta);
if( sdepth == CV_16S && ddepth == CV_16S )
return makePtr<Filter2D<short,
Cast<float, short>, FilterNoVec> >(kernel, anchor, delta);
if( sdepth == CV_16S && ddepth == CV_32F )
return makePtr<Filter2D<short,
Cast<float, float>, FilterNoVec> >(kernel, anchor, delta);
if( sdepth == CV_16S && ddepth == CV_64F )
return makePtr<Filter2D<short,
Cast<double, double>, FilterNoVec> >(kernel, anchor, delta);
if( sdepth == CV_32F && ddepth == CV_32F )
return makePtr<Filter2D<float, Cast<float, float>, FilterVec_32f> >
(kernel, anchor, delta, Cast<float, float>(), FilterVec_32f(kernel, 0, delta));
if( sdepth == CV_64F && ddepth == CV_64F )
return makePtr<Filter2D<double,
Cast<double, double>, FilterNoVec> >(kernel, anchor, delta);
CV_Error_( CV_StsNotImplemented,
("Unsupported combination of source format (=%d), and destination format (=%d)",
srcType, dstType));
}
#endif
CV_CPU_OPTIMIZATION_NAMESPACE_END
} // namespace
| [
"alex@shimadzu.ca"
] | alex@shimadzu.ca |
042cafecb59071436227ea89064c7388eb278389 | 5a49b5da44fa9c3a585febcf3d975197d872efc9 | /SGPLibraryCode/modules/sgp_render/font/sgp_FontManager.h | 12e9f1e4d13cbd0aebab80d4343fd4230ceeedb1 | [
"MIT"
] | permissive | phoenixzz/SGPEngine | 1ab3de99fdf6dd791baaf57e029a09e8db3580f7 | 593b4313abdb881d60e82750b36ddda2d7c73c49 | refs/heads/master | 2021-01-24T03:42:44.683083 | 2017-01-24T04:39:43 | 2017-01-24T04:39:43 | 53,315,434 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,155 | h | #ifndef __SGP_FONTMANAGER_HEADER__
#define __SGP_FONTMANAGER_HEADER__
#include <ft2build.h>
#include FT_FREETYPE_H
#include <freetype/ttunpat.h>
#include <freetype/ftoutln.h>
class ISGPFontManager
{
public:
ISGPFontManager(ISGPRenderDevice* pDevice);
~ISGPFontManager();
void Release(void);
bool AddFont( const char* strName, const String& strPath,
uint16 iSize = 20, bool bBold = false, bool bItalic = false );
bool DoDrawTextInPos( const String& sText, float x, float y,
Colour FontColor, uint32 flag, float fFontSize,
bool bKerning, bool bUnderl );
void PreCacheChar(const String& sText);
void FlushAllFonts();
bool IsFontLoaded(const char* strName);
void UnloadFont(const char* strName);
void SetActiveFont( const char* strName );
SGP_TTFFont* GetFontByName(const char* strName);
int GetActiveFontHeight();
void SetActiveFontHotSpot( float HotSpotx, float HotSpoty );
void SetActiveFontScale( float sx, float sy );
private:
ISGPRenderDevice* m_pDevice;
Array<SGP_TTFFont*> m_FontList;
SGP_TTFFont* m_ActiveFont;
FT_Library m_FTLib;
};
#endif // __SGP_FONTMANAGER_HEADER__ | [
"phoenixzz@sina.com"
] | phoenixzz@sina.com |
37532fe06d121e184fd8f5435ce2bccd8802cd79 | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /chrome/browser/android/preferences/prefs_unittest.cc | c59ebc5a046882a5782cc79a2836b1b4f256d577 | [
"BSD-3-Clause"
] | permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 2,968 | cc | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/android/preferences/prefs.h"
#include "base/stl_util.h"
#include "chrome/browser/android/preferences/pref_service_bridge.h"
#include "chrome/common/pref_names.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
class PrefsTest : public ::testing::Test {
protected:
const char* GetPrefName(Pref pref) {
pref_count_++;
return PrefServiceBridge::GetPrefNameExposedToJava(pref);
}
int pref_count_;
};
TEST_F(PrefsTest, TestIndex) {
pref_count_ = 0;
// If one of these checks fails, most likely the Pref enum and
// |kPrefExposedToJava| are out of sync.
EXPECT_EQ(Pref::PREF_NUM_PREFS, base::size(kPrefsExposedToJava));
EXPECT_EQ(prefs::kAllowDeletingBrowserHistory,
GetPrefName(ALLOW_DELETING_BROWSER_HISTORY));
EXPECT_EQ(prefs::kIncognitoModeAvailability,
GetPrefName(INCOGNITO_MODE_AVAILABILITY));
#if BUILDFLAG(ENABLE_FEED_IN_CHROME)
EXPECT_EQ(feed::prefs::kEnableSnippets,
GetPrefName(NTP_ARTICLES_SECTION_ENABLED));
EXPECT_EQ(feed::prefs::kArticlesListVisible,
GetPrefName(NTP_ARTICLES_LIST_VISIBLE));
#else // BUILDFLAG(ENABLE_FEED_IN_CHROME)
EXPECT_EQ(ntp_snippets::prefs::kEnableSnippets,
GetPrefName(NTP_ARTICLES_SECTION_ENABLED));
EXPECT_EQ(ntp_snippets::prefs::kArticlesListVisible,
GetPrefName(NTP_ARTICLES_LIST_VISIBLE));
#endif // BUILDFLAG(ENABLE_FEED_IN_CHROME)
EXPECT_EQ(prefs::kPromptForDownloadAndroid,
GetPrefName(PROMPT_FOR_DOWNLOAD_ANDROID));
EXPECT_EQ(dom_distiller::prefs::kReaderForAccessibility,
GetPrefName(READER_FOR_ACCESSIBILITY_ENABLED));
EXPECT_EQ(prefs::kShowMissingSdCardErrorAndroid,
GetPrefName(SHOW_MISSING_SD_CARD_ERROR_ANDROID));
EXPECT_EQ(payments::kCanMakePaymentEnabled,
GetPrefName(CAN_MAKE_PAYMENT_ENABLED));
EXPECT_EQ(prefs::kContextualSearchEnabled,
GetPrefName(CONTEXTUAL_SEARCH_ENABLED));
EXPECT_EQ(autofill::prefs::kAutofillProfileEnabled,
GetPrefName(AUTOFILL_PROFILE_ENABLED));
EXPECT_EQ(autofill::prefs::kAutofillCreditCardEnabled,
GetPrefName(AUTOFILL_CREDIT_CARD_ENABLED));
EXPECT_EQ(prefs::kUsageStatsEnabled, GetPrefName(USAGE_STATS_ENABLED));
EXPECT_EQ(offline_pages::prefetch_prefs::kUserSettingEnabled,
GetPrefName(OFFLINE_PREFETCH_USER_SETTING_ENABLED));
EXPECT_EQ(
offline_pages::prefetch_prefs::kContentSuggestionsNotificationsEnabled,
GetPrefName(CONTENT_SUGGESTIONS_NOTIFICATIONS_ENABLED));
EXPECT_EQ(prefs::kSafeBrowsingExtendedReportingOptInAllowed,
GetPrefName(SAFE_BROWSING_EXTENDED_REPORTING_OPT_IN_ALLOWED));
// If this check fails, a pref is missing a test case above.
EXPECT_EQ(Pref::PREF_NUM_PREFS, pref_count_);
}
} // namespace
| [
"sunny.nam@samsung.com"
] | sunny.nam@samsung.com |
3f54290bc6ec41756c7f0262cdc7fcd47cf4c801 | 38bd665e7a80f9aa8f3acac7317c7924ed3e745a | /src/server/gui/core/HttpReq.cpp | feaea8a3cb09e04070873aaf045e56b39754ffb7 | [
"BSD-3-Clause"
] | permissive | MayaPosch/NymphCast | 855cb5e05a1b979a600a8b7baf62619f4cc431dd | 7ac8d5a86e1a1b4987092a3398d1fa1987f18eb6 | refs/heads/master | 2023-08-30T06:06:25.443885 | 2023-08-07T17:58:57 | 2023-08-07T17:58:57 | 169,604,606 | 2,405 | 89 | BSD-3-Clause | 2023-04-14T08:54:58 | 2019-02-07T16:38:44 | C++ | UTF-8 | C++ | false | false | 4,568 | cpp | #include "HttpReq.h"
#include "utils/FileSystemUtil.h"
#include "Log.h"
#include <assert.h>
CURLM* HttpReq::s_multi_handle = curl_multi_init();
std::map<CURL*, HttpReq*> HttpReq::s_requests;
std::string HttpReq::urlEncode(const std::string &s)
{
const std::string unreserved = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~";
std::string escaped="";
for(size_t i=0; i<s.length(); i++)
{
if (unreserved.find_first_of(s[i]) != std::string::npos)
{
escaped.push_back(s[i]);
}
else
{
escaped.append("%");
char buf[3];
sprintf(buf, "%.2X", (unsigned char)s[i]);
escaped.append(buf);
}
}
return escaped;
}
bool HttpReq::isUrl(const std::string& str)
{
//the worst guess
return (!str.empty() && !Utils::FileSystem::exists(str) &&
(str.find("http://") != std::string::npos || str.find("https://") != std::string::npos || str.find("www.") != std::string::npos));
}
HttpReq::HttpReq(const std::string& url)
: mStatus(REQ_IN_PROGRESS), mHandle(NULL)
{
mHandle = curl_easy_init();
if(mHandle == NULL)
{
mStatus = REQ_IO_ERROR;
onError("curl_easy_init failed");
return;
}
//set the url
CURLcode err = curl_easy_setopt(mHandle, CURLOPT_URL, url.c_str());
if(err != CURLE_OK)
{
mStatus = REQ_IO_ERROR;
onError(curl_easy_strerror(err));
return;
}
//set curl to handle redirects
err = curl_easy_setopt(mHandle, CURLOPT_FOLLOWLOCATION, 1L);
if(err != CURLE_OK)
{
mStatus = REQ_IO_ERROR;
onError(curl_easy_strerror(err));
return;
}
//set curl max redirects
err = curl_easy_setopt(mHandle, CURLOPT_MAXREDIRS, 2L);
if(err != CURLE_OK)
{
mStatus = REQ_IO_ERROR;
onError(curl_easy_strerror(err));
return;
}
//set curl restrict redirect protocols
err = curl_easy_setopt(mHandle, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);
if(err != CURLE_OK)
{
mStatus = REQ_IO_ERROR;
onError(curl_easy_strerror(err));
return;
}
//tell curl how to write the data
err = curl_easy_setopt(mHandle, CURLOPT_WRITEFUNCTION, &HttpReq::write_content);
if(err != CURLE_OK)
{
mStatus = REQ_IO_ERROR;
onError(curl_easy_strerror(err));
return;
}
//give curl a pointer to this HttpReq so we know where to write the data *to* in our write function
err = curl_easy_setopt(mHandle, CURLOPT_WRITEDATA, this);
if(err != CURLE_OK)
{
mStatus = REQ_IO_ERROR;
onError(curl_easy_strerror(err));
return;
}
//add the handle to our multi
CURLMcode merr = curl_multi_add_handle(s_multi_handle, mHandle);
if(merr != CURLM_OK)
{
mStatus = REQ_IO_ERROR;
onError(curl_multi_strerror(merr));
return;
}
s_requests[mHandle] = this;
}
HttpReq::~HttpReq()
{
if(mHandle)
{
s_requests.erase(mHandle);
CURLMcode merr = curl_multi_remove_handle(s_multi_handle, mHandle);
if(merr != CURLM_OK)
LOG(LogError) << "Error removing curl_easy handle from curl_multi: " << curl_multi_strerror(merr);
curl_easy_cleanup(mHandle);
}
}
HttpReq::Status HttpReq::status()
{
if(mStatus == REQ_IN_PROGRESS)
{
int handle_count;
CURLMcode merr = curl_multi_perform(s_multi_handle, &handle_count);
if(merr != CURLM_OK && merr != CURLM_CALL_MULTI_PERFORM)
{
mStatus = REQ_IO_ERROR;
onError(curl_multi_strerror(merr));
return mStatus;
}
int msgs_left;
CURLMsg* msg;
while((msg = curl_multi_info_read(s_multi_handle, &msgs_left)) != nullptr)
{
if(msg->msg == CURLMSG_DONE)
{
HttpReq* req = s_requests[msg->easy_handle];
if(req == NULL)
{
LOG(LogError) << "Cannot find easy handle!";
continue;
}
if(msg->data.result == CURLE_OK)
{
req->mStatus = REQ_SUCCESS;
}else{
req->mStatus = REQ_IO_ERROR;
req->onError(curl_easy_strerror(msg->data.result));
}
}
}
}
return mStatus;
}
std::string HttpReq::getContent() const
{
assert(mStatus == REQ_SUCCESS);
return mContent.str();
}
void HttpReq::onError(const char* msg)
{
mErrorMsg = msg;
}
std::string HttpReq::getErrorMsg()
{
return mErrorMsg;
}
//used as a curl callback
//size = size of an element, nmemb = number of elements
//return value is number of elements successfully read
size_t HttpReq::write_content(void* buff, size_t size, size_t nmemb, void* req_ptr)
{
std::stringstream& ss = ((HttpReq*)req_ptr)->mContent;
ss.write((char*)buff, size * nmemb);
return nmemb;
}
//used as a curl callback
/*int HttpReq::update_progress(void* req_ptr, double dlTotal, double dlNow, double ulTotal, double ulNow)
{
}*/
| [
"maya@nyanko.ws"
] | maya@nyanko.ws |
3bb13adb5867e4472433ca96a0a492b1bbdd138b | 2de766db3b23b1ae845396fbb30615c01cc1604e | /leetcode/longest-common-prefix.cpp | 4de5e392a06b2c51ccc4a658d26a4f0d2e1e3cec | [] | no_license | delta4d/AlgoSolution | 313c5d0ff72673927ad3862ee7b8fb432943b346 | 5f6f89578d5aa37247a99b2d289d638f76c71281 | refs/heads/master | 2020-04-21T01:28:35.690529 | 2015-01-29T13:38:54 | 2015-01-29T13:38:54 | 8,221,423 | 1 | 0 | null | 2013-04-09T15:10:20 | 2013-02-15T16:09:33 | C++ | UTF-8 | C++ | false | false | 498 | cpp | // 40ms
// simulation
class Solution {
public:
string longestCommonPrefix(vector<string> &strs) {
if (strs.empty()) return "";
int n = (int)strs.size(), len = (int)strs.front().length();
for (int i=0; i<len; ++i) {
for (int j=1; j<n; ++j) {
if ((int)strs[j].length() < i + 1) return strs[0].substr(0, i);
if (strs[j][i] != strs[0][i]) return strs[0].substr(0, i);
}
}
return strs.front();
}
};
| [
"delta4d@gmail.com"
] | delta4d@gmail.com |
4bfdcd08ea842498c98529b1bf3815abac3b9d6b | c58154363ce9235d334249bbd3a150b295676b28 | /FileWatcher/FileWatcherAdapter.h | 1ddeb096810e385a714a105b2f16613e2ac265d8 | [
"Unlicense"
] | permissive | ifukazoo/FileWatcher | 16ebedf6cb9e5ce8864ac93dfc9a962dc98168b2 | 3e0f561e30ae9fd54f55debb695af873072b3b0a | refs/heads/master | 2020-04-04T15:49:04.895966 | 2018-11-04T05:45:54 | 2018-11-04T05:45:54 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 944 | h | #pragma once
namespace FileWatcher {
class FileWatcherAdapter
{
public:
FileWatcherAdapter(HWND);
void StartWatching(const std::string&, const std::vector<std::string>&);
void StopWatching();
void OnChanged(System::Object ^, System::IO::FileSystemEventArgs^);
private:
HWND receiver_;
std::vector<std::string> watchingFiles_;
gcroot<System::IO::FileSystemWatcher^> gcWatcher_;
};
/// <summary>
/// <para>マネージデリゲートにインスタンスメソッドを設定する際は,インスタンスオブジェクトを渡す必要があるが</para>
/// <para>アンマネージインスタンスは渡せないのでラッパーを作る必要がある</para>
/// </summary>
ref class FileSystemEventHandlerAdapter
{
public:
FileSystemEventHandlerAdapter(FileWatcherAdapter*);
void OnChanged(System::Object ^, System::IO::FileSystemEventArgs ^);
private:
FileWatcherAdapter * adapter_;
};
}
| [
"yamanobori_old@yahoo.co.jp"
] | yamanobori_old@yahoo.co.jp |
0747410c8e4a129d1581ca9ae73c2c693d246d37 | b1aa9ad6733efcb53d465809d5109e9174dabf04 | /GameEngineGems3(WithCode)/geg3-chapter4/Include/Libraries/NewtonDynamics/packages/dCustomJoints/CustomInputManager.h | 05ec5c386ed1dfafc7e489ded7dcdf4537e66f9b | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | permissive | dumpinfo/GameMatrixTest | d21545dbef9ade76fe092343a8362da4c8b142ca | 9e4a73ad17555ddb90020c47e2486698b90e4d0d | refs/heads/master | 2023-02-04T01:52:05.342214 | 2020-12-23T17:22:36 | 2020-12-23T17:22:36 | 323,961,033 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,967 | h | /* Copyright (c) <2003-2011> <Julio Jerez, Newton Game Dynamics>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef D_CUSTOM_IMPUT_MANAGER_H_
#define D_CUSTOM_IMPUT_MANAGER_H_
#include <CustomJointLibraryStdAfx.h>
#include <CustomControllerManager.h>
#define INPUT_PLUGIN_NAME "__inputManager__"
class CustomInputController: public CustomControllerBase
{
public:
CUSTOM_JOINTS_API virtual void PreUpdate(dFloat timestep, int threadIndex)
{
//do nothing;
}
CUSTOM_JOINTS_API virtual void PostUpdate(dFloat timestep, int threadIndex)
{
//do nothing;
}
};
class CustomInputManager: public CustomControllerManager<CustomInputController>
{
public:
CUSTOM_JOINTS_API CustomInputManager (NewtonWorld* const world);
CUSTOM_JOINTS_API virtual ~CustomInputManager();
virtual void OnBeginUpdate (dFloat timestepInSecunds) = 0;
virtual void OnEndUpdate (dFloat timestepInSecunds) = 0;
protected:
CUSTOM_JOINTS_API virtual void PreUpdate(dFloat timestep);
CUSTOM_JOINTS_API virtual void PostUpdate (dFloat timestep);
CUSTOM_JOINTS_API virtual void Debug () const {};
};
#endif
| [
"twtravel@126.com"
] | twtravel@126.com |
5c5d59f6cf6ab5bf0c2b4354f283c773332deb22 | 88ae8695987ada722184307301e221e1ba3cc2fa | /third_party/blink/renderer/core/svg/svg_fe_offset_element.cc | 32fdbc8ee05c082c6c43e983291cb25dfb77f8d4 | [
"LGPL-2.0-only",
"BSD-2-Clause",
"LGPL-2.1-only",
"BSD-3-Clause",
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-2.0-only",
"LicenseRef-scancode-other-copyleft"
] | permissive | iridium-browser/iridium-browser | 71d9c5ff76e014e6900b825f67389ab0ccd01329 | 5ee297f53dc7f8e70183031cff62f37b0f19d25f | refs/heads/master | 2023-08-03T16:44:16.844552 | 2023-07-20T15:17:00 | 2023-07-23T16:09:30 | 220,016,632 | 341 | 40 | BSD-3-Clause | 2021-08-13T13:54:45 | 2019-11-06T14:32:31 | null | UTF-8 | C++ | false | false | 3,172 | cc | /*
* Copyright (C) 2004, 2005, 2007 Nikolas Zimmermann <zimmermann@kde.org>
* Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "third_party/blink/renderer/core/svg/svg_fe_offset_element.h"
#include "third_party/blink/renderer/core/svg/graphics/filters/svg_filter_builder.h"
#include "third_party/blink/renderer/core/svg/svg_animated_number.h"
#include "third_party/blink/renderer/core/svg/svg_animated_string.h"
#include "third_party/blink/renderer/core/svg_names.h"
#include "third_party/blink/renderer/platform/graphics/filters/fe_offset.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
namespace blink {
SVGFEOffsetElement::SVGFEOffsetElement(Document& document)
: SVGFilterPrimitiveStandardAttributes(svg_names::kFEOffsetTag, document),
dx_(MakeGarbageCollected<SVGAnimatedNumber>(this,
svg_names::kDxAttr,
0.0f)),
dy_(MakeGarbageCollected<SVGAnimatedNumber>(this,
svg_names::kDyAttr,
0.0f)),
in1_(MakeGarbageCollected<SVGAnimatedString>(this, svg_names::kInAttr)) {
AddToPropertyMap(dx_);
AddToPropertyMap(dy_);
AddToPropertyMap(in1_);
}
void SVGFEOffsetElement::Trace(Visitor* visitor) const {
visitor->Trace(dx_);
visitor->Trace(dy_);
visitor->Trace(in1_);
SVGFilterPrimitiveStandardAttributes::Trace(visitor);
}
void SVGFEOffsetElement::SvgAttributeChanged(
const SvgAttributeChangedParams& params) {
const QualifiedName& attr_name = params.name;
if (attr_name == svg_names::kInAttr || attr_name == svg_names::kDxAttr ||
attr_name == svg_names::kDyAttr) {
SVGElement::InvalidationGuard invalidation_guard(this);
Invalidate();
return;
}
SVGFilterPrimitiveStandardAttributes::SvgAttributeChanged(params);
}
FilterEffect* SVGFEOffsetElement::Build(SVGFilterBuilder* filter_builder,
Filter* filter) {
FilterEffect* input1 = filter_builder->GetEffectById(
AtomicString(in1_->CurrentValue()->Value()));
DCHECK(input1);
auto* effect = MakeGarbageCollected<FEOffset>(
filter, dx_->CurrentValue()->Value(), dy_->CurrentValue()->Value());
effect->InputEffects().push_back(input1);
return effect;
}
} // namespace blink
| [
"jengelh@inai.de"
] | jengelh@inai.de |
0d03ae08fb3564734ac6750c06dc00456d8d40a3 | bc93833a9a2606dd051738dd06d6d17c18cbdcae | /3rdparty/opencv/sources/modules/cudalegacy/include/opencv2/cudalegacy/NCVHaarObjectDetection.hpp | 6b84e8b2553d0d7c0bb9a5916a7fde6604d3e8dc | [
"BSD-3-Clause",
"MIT"
] | permissive | Wizapply/OvrvisionPro | f0552626f22d6fe96824034310a4f08ab874b62e | 41680a1f9cfd617a9d33f1df9d9a91e8ffd4dc4b | refs/heads/master | 2021-11-11T02:37:23.840617 | 2021-05-06T03:00:48 | 2021-05-06T03:00:48 | 43,277,465 | 30 | 32 | NOASSERTION | 2019-12-25T14:07:27 | 2015-09-28T03:17:23 | C | UTF-8 | C++ | false | false | 18,178 | hpp | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
////////////////////////////////////////////////////////////////////////////////
//
// NVIDIA CUDA implementation of Viola-Jones Object Detection Framework
//
// The algorithm and code are explained in the upcoming GPU Computing Gems
// chapter in detail:
//
// Anton Obukhov, "Haar Classifiers for Object Detection with CUDA"
// PDF URL placeholder
// email: aobukhov@nvidia.com, devsupport@nvidia.com
//
// Credits for help with the code to:
// Alexey Mendelenko, Cyril Crassin, and Mikhail Smirnov.
//
////////////////////////////////////////////////////////////////////////////////
#ifndef _ncvhaarobjectdetection_hpp_
#define _ncvhaarobjectdetection_hpp_
#include "opencv2/cudalegacy/NCV.hpp"
//! @addtogroup cudalegacy
//! @{
//==============================================================================
//
// Guaranteed size cross-platform classifier structures
//
//==============================================================================
#if defined __GNUC__ && __GNUC__ > 2 && __GNUC_MINOR__ > 4
typedef Ncv32f __attribute__((__may_alias__)) Ncv32f_a;
#else
typedef Ncv32f Ncv32f_a;
#endif
struct HaarFeature64
{
uint2 _ui2;
#define HaarFeature64_CreateCheck_MaxRectField 0xFF
__host__ NCVStatus setRect(Ncv32u rectX, Ncv32u rectY, Ncv32u rectWidth, Ncv32u rectHeight, Ncv32u /*clsWidth*/, Ncv32u /*clsHeight*/)
{
ncvAssertReturn(rectWidth <= HaarFeature64_CreateCheck_MaxRectField && rectHeight <= HaarFeature64_CreateCheck_MaxRectField, NCV_HAAR_TOO_LARGE_FEATURES);
((NcvRect8u*)&(this->_ui2.x))->x = (Ncv8u)rectX;
((NcvRect8u*)&(this->_ui2.x))->y = (Ncv8u)rectY;
((NcvRect8u*)&(this->_ui2.x))->width = (Ncv8u)rectWidth;
((NcvRect8u*)&(this->_ui2.x))->height = (Ncv8u)rectHeight;
return NCV_SUCCESS;
}
__host__ NCVStatus setWeight(Ncv32f weight)
{
((Ncv32f_a*)&(this->_ui2.y))[0] = weight;
return NCV_SUCCESS;
}
__device__ __host__ void getRect(Ncv32u *rectX, Ncv32u *rectY, Ncv32u *rectWidth, Ncv32u *rectHeight)
{
NcvRect8u tmpRect = *(NcvRect8u*)(&this->_ui2.x);
*rectX = tmpRect.x;
*rectY = tmpRect.y;
*rectWidth = tmpRect.width;
*rectHeight = tmpRect.height;
}
__device__ __host__ Ncv32f getWeight(void)
{
return *(Ncv32f_a*)(&this->_ui2.y);
}
};
struct HaarFeatureDescriptor32
{
private:
#define HaarFeatureDescriptor32_Interpret_MaskFlagTilted 0x80000000
#define HaarFeatureDescriptor32_Interpret_MaskFlagLeftNodeLeaf 0x40000000
#define HaarFeatureDescriptor32_Interpret_MaskFlagRightNodeLeaf 0x20000000
#define HaarFeatureDescriptor32_CreateCheck_MaxNumFeatures 0x1F
#define HaarFeatureDescriptor32_NumFeatures_Shift 24
#define HaarFeatureDescriptor32_CreateCheck_MaxFeatureOffset 0x00FFFFFF
Ncv32u desc;
public:
__host__ NCVStatus create(NcvBool bTilted, NcvBool bLeftLeaf, NcvBool bRightLeaf,
Ncv32u numFeatures, Ncv32u offsetFeatures)
{
if (numFeatures > HaarFeatureDescriptor32_CreateCheck_MaxNumFeatures)
{
return NCV_HAAR_TOO_MANY_FEATURES_IN_CLASSIFIER;
}
if (offsetFeatures > HaarFeatureDescriptor32_CreateCheck_MaxFeatureOffset)
{
return NCV_HAAR_TOO_MANY_FEATURES_IN_CASCADE;
}
this->desc = 0;
this->desc |= (bTilted ? HaarFeatureDescriptor32_Interpret_MaskFlagTilted : 0);
this->desc |= (bLeftLeaf ? HaarFeatureDescriptor32_Interpret_MaskFlagLeftNodeLeaf : 0);
this->desc |= (bRightLeaf ? HaarFeatureDescriptor32_Interpret_MaskFlagRightNodeLeaf : 0);
this->desc |= (numFeatures << HaarFeatureDescriptor32_NumFeatures_Shift);
this->desc |= offsetFeatures;
return NCV_SUCCESS;
}
__device__ __host__ NcvBool isTilted(void)
{
return (this->desc & HaarFeatureDescriptor32_Interpret_MaskFlagTilted) != 0;
}
__device__ __host__ NcvBool isLeftNodeLeaf(void)
{
return (this->desc & HaarFeatureDescriptor32_Interpret_MaskFlagLeftNodeLeaf) != 0;
}
__device__ __host__ NcvBool isRightNodeLeaf(void)
{
return (this->desc & HaarFeatureDescriptor32_Interpret_MaskFlagRightNodeLeaf) != 0;
}
__device__ __host__ Ncv32u getNumFeatures(void)
{
return (this->desc >> HaarFeatureDescriptor32_NumFeatures_Shift) & HaarFeatureDescriptor32_CreateCheck_MaxNumFeatures;
}
__device__ __host__ Ncv32u getFeaturesOffset(void)
{
return this->desc & HaarFeatureDescriptor32_CreateCheck_MaxFeatureOffset;
}
};
struct HaarClassifierNodeDescriptor32
{
uint1 _ui1;
__host__ NCVStatus create(Ncv32f leafValue)
{
*(Ncv32f_a *)&this->_ui1 = leafValue;
return NCV_SUCCESS;
}
__host__ NCVStatus create(Ncv32u offsetHaarClassifierNode)
{
this->_ui1.x = offsetHaarClassifierNode;
return NCV_SUCCESS;
}
__host__ Ncv32f getLeafValueHost(void)
{
return *(Ncv32f_a *)&this->_ui1.x;
}
#ifdef __CUDACC__
__device__ Ncv32f getLeafValue(void)
{
return __int_as_float(this->_ui1.x);
}
#endif
__device__ __host__ Ncv32u getNextNodeOffset(void)
{
return this->_ui1.x;
}
};
#if defined __GNUC__ && __GNUC__ > 2 && __GNUC_MINOR__ > 4
typedef Ncv32u __attribute__((__may_alias__)) Ncv32u_a;
#else
typedef Ncv32u Ncv32u_a;
#endif
struct HaarClassifierNode128
{
uint4 _ui4;
__host__ NCVStatus setFeatureDesc(HaarFeatureDescriptor32 f)
{
this->_ui4.x = *(Ncv32u *)&f;
return NCV_SUCCESS;
}
__host__ NCVStatus setThreshold(Ncv32f t)
{
this->_ui4.y = *(Ncv32u_a *)&t;
return NCV_SUCCESS;
}
__host__ NCVStatus setLeftNodeDesc(HaarClassifierNodeDescriptor32 nl)
{
this->_ui4.z = *(Ncv32u_a *)&nl;
return NCV_SUCCESS;
}
__host__ NCVStatus setRightNodeDesc(HaarClassifierNodeDescriptor32 nr)
{
this->_ui4.w = *(Ncv32u_a *)&nr;
return NCV_SUCCESS;
}
__host__ __device__ HaarFeatureDescriptor32 getFeatureDesc(void)
{
return *(HaarFeatureDescriptor32 *)&this->_ui4.x;
}
__host__ __device__ Ncv32f getThreshold(void)
{
return *(Ncv32f_a*)&this->_ui4.y;
}
__host__ __device__ HaarClassifierNodeDescriptor32 getLeftNodeDesc(void)
{
return *(HaarClassifierNodeDescriptor32 *)&this->_ui4.z;
}
__host__ __device__ HaarClassifierNodeDescriptor32 getRightNodeDesc(void)
{
return *(HaarClassifierNodeDescriptor32 *)&this->_ui4.w;
}
};
struct HaarStage64
{
#define HaarStage64_Interpret_MaskRootNodes 0x0000FFFF
#define HaarStage64_Interpret_MaskRootNodeOffset 0xFFFF0000
#define HaarStage64_Interpret_ShiftRootNodeOffset 16
uint2 _ui2;
__host__ NCVStatus setStageThreshold(Ncv32f t)
{
this->_ui2.x = *(Ncv32u_a *)&t;
return NCV_SUCCESS;
}
__host__ NCVStatus setStartClassifierRootNodeOffset(Ncv32u val)
{
if (val > (HaarStage64_Interpret_MaskRootNodeOffset >> HaarStage64_Interpret_ShiftRootNodeOffset))
{
return NCV_HAAR_XML_LOADING_EXCEPTION;
}
this->_ui2.y = (val << HaarStage64_Interpret_ShiftRootNodeOffset) | (this->_ui2.y & HaarStage64_Interpret_MaskRootNodes);
return NCV_SUCCESS;
}
__host__ NCVStatus setNumClassifierRootNodes(Ncv32u val)
{
if (val > HaarStage64_Interpret_MaskRootNodes)
{
return NCV_HAAR_XML_LOADING_EXCEPTION;
}
this->_ui2.y = val | (this->_ui2.y & HaarStage64_Interpret_MaskRootNodeOffset);
return NCV_SUCCESS;
}
__host__ __device__ Ncv32f getStageThreshold(void)
{
return *(Ncv32f_a*)&this->_ui2.x;
}
__host__ __device__ Ncv32u getStartClassifierRootNodeOffset(void)
{
return (this->_ui2.y >> HaarStage64_Interpret_ShiftRootNodeOffset);
}
__host__ __device__ Ncv32u getNumClassifierRootNodes(void)
{
return (this->_ui2.y & HaarStage64_Interpret_MaskRootNodes);
}
};
NCV_CT_ASSERT(sizeof(HaarFeature64) == 8);
NCV_CT_ASSERT(sizeof(HaarFeatureDescriptor32) == 4);
NCV_CT_ASSERT(sizeof(HaarClassifierNodeDescriptor32) == 4);
NCV_CT_ASSERT(sizeof(HaarClassifierNode128) == 16);
NCV_CT_ASSERT(sizeof(HaarStage64) == 8);
//==============================================================================
//
// Classifier cascade descriptor
//
//==============================================================================
struct HaarClassifierCascadeDescriptor
{
Ncv32u NumStages;
Ncv32u NumClassifierRootNodes;
Ncv32u NumClassifierTotalNodes;
Ncv32u NumFeatures;
NcvSize32u ClassifierSize;
NcvBool bNeedsTiltedII;
NcvBool bHasStumpsOnly;
};
//==============================================================================
//
// Functional interface
//
//==============================================================================
enum
{
NCVPipeObjDet_Default = 0x000,
NCVPipeObjDet_UseFairImageScaling = 0x001,
NCVPipeObjDet_FindLargestObject = 0x002,
NCVPipeObjDet_VisualizeInPlace = 0x004,
};
CV_EXPORTS NCVStatus ncvDetectObjectsMultiScale_device(NCVMatrix<Ncv8u> &d_srcImg,
NcvSize32u srcRoi,
NCVVector<NcvRect32u> &d_dstRects,
Ncv32u &dstNumRects,
HaarClassifierCascadeDescriptor &haar,
NCVVector<HaarStage64> &h_HaarStages,
NCVVector<HaarStage64> &d_HaarStages,
NCVVector<HaarClassifierNode128> &d_HaarNodes,
NCVVector<HaarFeature64> &d_HaarFeatures,
NcvSize32u minObjSize,
Ncv32u minNeighbors, //default 4
Ncv32f scaleStep, //default 1.2f
Ncv32u pixelStep, //default 1
Ncv32u flags, //default NCVPipeObjDet_Default
INCVMemAllocator &gpuAllocator,
INCVMemAllocator &cpuAllocator,
cudaDeviceProp &devProp,
cudaStream_t cuStream);
#define OBJDET_MASK_ELEMENT_INVALID_32U 0xFFFFFFFF
#define HAAR_STDDEV_BORDER 1
CV_EXPORTS NCVStatus ncvApplyHaarClassifierCascade_device(NCVMatrix<Ncv32u> &d_integralImage,
NCVMatrix<Ncv32f> &d_weights,
NCVMatrixAlloc<Ncv32u> &d_pixelMask,
Ncv32u &numDetections,
HaarClassifierCascadeDescriptor &haar,
NCVVector<HaarStage64> &h_HaarStages,
NCVVector<HaarStage64> &d_HaarStages,
NCVVector<HaarClassifierNode128> &d_HaarNodes,
NCVVector<HaarFeature64> &d_HaarFeatures,
NcvBool bMaskElements,
NcvSize32u anchorsRoi,
Ncv32u pixelStep,
Ncv32f scaleArea,
INCVMemAllocator &gpuAllocator,
INCVMemAllocator &cpuAllocator,
cudaDeviceProp &devProp,
cudaStream_t cuStream);
CV_EXPORTS NCVStatus ncvApplyHaarClassifierCascade_host(NCVMatrix<Ncv32u> &h_integralImage,
NCVMatrix<Ncv32f> &h_weights,
NCVMatrixAlloc<Ncv32u> &h_pixelMask,
Ncv32u &numDetections,
HaarClassifierCascadeDescriptor &haar,
NCVVector<HaarStage64> &h_HaarStages,
NCVVector<HaarClassifierNode128> &h_HaarNodes,
NCVVector<HaarFeature64> &h_HaarFeatures,
NcvBool bMaskElements,
NcvSize32u anchorsRoi,
Ncv32u pixelStep,
Ncv32f scaleArea);
#define RECT_SIMILARITY_PROPORTION 0.2f
CV_EXPORTS NCVStatus ncvGrowDetectionsVector_device(NCVVector<Ncv32u> &pixelMask,
Ncv32u numPixelMaskDetections,
NCVVector<NcvRect32u> &hypotheses,
Ncv32u &totalDetections,
Ncv32u totalMaxDetections,
Ncv32u rectWidth,
Ncv32u rectHeight,
Ncv32f curScale,
cudaStream_t cuStream);
CV_EXPORTS NCVStatus ncvGrowDetectionsVector_host(NCVVector<Ncv32u> &pixelMask,
Ncv32u numPixelMaskDetections,
NCVVector<NcvRect32u> &hypotheses,
Ncv32u &totalDetections,
Ncv32u totalMaxDetections,
Ncv32u rectWidth,
Ncv32u rectHeight,
Ncv32f curScale);
CV_EXPORTS NCVStatus ncvHaarGetClassifierSize(const cv::String &filename, Ncv32u &numStages,
Ncv32u &numNodes, Ncv32u &numFeatures);
CV_EXPORTS NCVStatus ncvHaarLoadFromFile_host(const cv::String &filename,
HaarClassifierCascadeDescriptor &haar,
NCVVector<HaarStage64> &h_HaarStages,
NCVVector<HaarClassifierNode128> &h_HaarNodes,
NCVVector<HaarFeature64> &h_HaarFeatures);
CV_EXPORTS NCVStatus ncvHaarStoreNVBIN_host(const cv::String &filename,
HaarClassifierCascadeDescriptor haar,
NCVVector<HaarStage64> &h_HaarStages,
NCVVector<HaarClassifierNode128> &h_HaarNodes,
NCVVector<HaarFeature64> &h_HaarFeatures);
//! @}
#endif // _ncvhaarobjectdetection_hpp_
| [
"info@wizapply.com"
] | info@wizapply.com |
04d99468fad2479d56f0a4eb212bb3f44104228f | 3e50ba512e0850a2caa564242f71cf586255ca4b | /vstgui/lib/ctooltipsupport.h | 26f0639afb4a72a3167cd310cae712b2564a23b2 | [
"BSD-3-Clause"
] | permissive | steinbergmedia/vstgui | c479d31b299fe69dbf37b51a5cfb645c3de90159 | fb7060cd13215bdc4f441c37a754711c772922fd | refs/heads/develop | 2023-09-03T00:11:43.085495 | 2023-08-16T14:38:51 | 2023-08-16T14:38:51 | 48,168,902 | 804 | 157 | NOASSERTION | 2023-08-16T16:12:53 | 2015-12-17T10:46:38 | C++ | UTF-8 | C++ | false | false | 1,292 | h | // This file is part of VSTGUI. It is subject to the license terms
// in the LICENSE file found in the top-level directory of this
// distribution and at http://github.com/steinbergmedia/vstgui/LICENSE
#pragma once
#include "vstguifwd.h"
#include "cpoint.h"
namespace VSTGUI {
//-----------------------------------------------------------------------------
// CTooltipSupport Declaration
//! Generic Tooltip Support class
//-----------------------------------------------------------------------------
class CTooltipSupport : public CBaseObject
{
public:
CTooltipSupport (CFrame* frame, uint32_t delay = 1000);
void onMouseEntered (CView* view);
void onMouseExited (CView* view);
void onMouseMoved (const CPoint& where);
void onMouseDown (const CPoint& where);
void hideTooltip ();
//-------------------------------------------
CLASS_METHODS_NOCOPY(CTooltipSupport, CBaseObject)
protected:
~CTooltipSupport () noexcept override;
bool showTooltip ();
enum {
kHidden,
kVisible,
kHiding,
kShowing,
kForceVisible
};
// CBaseObject
CMessageResult notify (CBaseObject* sender, IdStringPtr msg) override;
SharedPointer<CVSTGUITimer> timer;
CFrame* frame;
SharedPointer<CView> currentView;
uint32_t delay;
int32_t state;
CPoint lastMouseMove;
};
} // VSTGUI
| [
"scheffle@users.noreply.github.com"
] | scheffle@users.noreply.github.com |
225f8c7a547941e5a4bc3029ac99f4501be057aa | 64178ab5958c36c4582e69b6689359f169dc6f0d | /vscode/wg/sdk/UP_Sinking_Ripples_BP_Aquarail_C.hpp | e7fe6ffaac78d2bb0c76082c355e4dd36466a9dc | [] | no_license | c-ber/cber | 47bc1362f180c9e8f0638e40bf716d8ec582e074 | 3cb5c85abd8a6be09e0283d136c87761925072de | refs/heads/master | 2023-06-07T20:07:44.813723 | 2023-02-28T07:43:29 | 2023-02-28T07:43:29 | 40,457,301 | 5 | 5 | null | 2023-05-30T19:14:51 | 2015-08-10T01:37:22 | C++ | UTF-8 | C++ | false | false | 965 | hpp | #pragma once
#include "UTslParticle.hpp"
#ifdef _MSC_VER
#pragma pack(push, 1)
#endif
namespace PUBGSDK {
struct alignas(1) UP_Sinking_Ripples_BP_Aquarail_C // Size: 0x470
: public UTslParticle // Size: 0x470
{
private:
typedef UP_Sinking_Ripples_BP_Aquarail_C t_struct;
typedef ExternalPtr<t_struct> t_structHelper;
public:
static ExternalPtr<struct UClass> StaticClass()
{
static ExternalPtr<struct UClass> ptr;
if(!ptr) ptr = UObject::FindClassFast(116044); // id32("BlueprintGeneratedClass P_Sinking_Ripples_BP_Aquarail.P_Sinking_Ripples_BP_Aquarail_C")
return ptr;
}
};
#ifdef VALIDATE_SDK
namespace Validation{
auto constexpr sizeofUP_Sinking_Ripples_BP_Aquarail_C = sizeof(UP_Sinking_Ripples_BP_Aquarail_C); // 1136
static_assert(sizeof(UP_Sinking_Ripples_BP_Aquarail_C) == 0x470, "Size of UP_Sinking_Ripples_BP_Aquarail_C is not correct.");
}
#endif
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"1395329153@qq.com"
] | 1395329153@qq.com |
cbc5996a313cd9bb8ad9215cb99be9de3d375cc6 | 88b2e9f73e1602350d62e8f0bb8ac988ecff2a54 | /Lights-master/lightConsoleMockup/qtrectitem.h | 33a8079567f0416b8aec40dab05b0f4f74326d7f | [] | no_license | haiderpasha09/hyder_pasha- | 194a74d618a11856043c6ea0f172c9d517c100cd | dccb18a46f72c8098619178820f7191de225ea7d | refs/heads/master | 2020-12-22T20:16:04.441196 | 2020-10-16T07:28:05 | 2020-10-16T07:28:05 | 236,920,038 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 797 | h | #ifndef QTRECTITEM_H
#define QTRECTITEM_H
//#pragma GCC diagnostic push
//#pragma GCC diagnostic ignored "-Weffc++"
//#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
//#pragma GCC diagnostic ignored "-Wunused-but-set-parameter"
#include <QGraphicsRectItem>
#include "qdebug.h"
//#pragma GCC diagnostic pop
struct QtRectItem : public QGraphicsRectItem
{
QtRectItem(QGraphicsItem *parent = 0);
void setID(int mID){ID = mID;}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
QVariant itemChange(GraphicsItemChange change, const QVariant &value);
void setDetails(QString pMan, QString pModel, QString pMode);
bool selected;
QString Man, Model, Mode;
private:
int Width, Height;
int ID;
};
#endif // QTRECTITEM_H
| [
"haiderpasha09@yahoo.com"
] | haiderpasha09@yahoo.com |
271ca8b47c029ca31814277303bf9b67b2291f28 | 8d675d8b658f028400543c18b0243f8dc45c9b03 | /15-3Sum.cpp | 76f69de5419c528e334a0ba7fa29e14a83c0869a | [] | no_license | dc-tw/leetcode | 06b1784ce7111fe43632067750944ce9596df03a | 2556209843dd6d621b8ced305eaf7cf8f39ff294 | refs/heads/master | 2020-05-19T20:23:36.485881 | 2020-02-14T08:02:36 | 2020-02-14T08:02:36 | 185,200,761 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 872 | cpp | class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
int i=0, j=0, k=nums.size()-1;
int num1 = 0;
vector<int> t(3);
vector<vector<int> > vt;
for (i=0; i < k-1; )
{
num1 = 0-nums[i];
t[0] = nums[i];
for (j = i+1, k=nums.size()-1; j < k;)
{
if (nums[j] + nums[k] == num1){
t[1] = nums[j++];
t[2] = nums[k--];
vt.push_back(t);
while (j<k && nums[j] == nums[j-1])++j;
while (j<k && nums[k] == nums[k+1])--k;
}
else if (nums[j] + nums[k] < num1)++j;
else --k;
}
++i;
while (i<k-1 && nums[i] == nums[i-1])++i;
}//for(; i<k-1; i++)
return vt;
}
};
/*
step1 sort
step2 pick the smallest
step3 find the others
*/
| [
"david112358c@gmail.com"
] | david112358c@gmail.com |
4805b57cf62323eeeb6a364bca201538a3064438 | f6530fa2ae8d3d45b2ecb6d73973d3620dcb4c8b | /WEEK5/San Francisco/main.cpp | b6ce72dd5a7520026666686180406b9ee0ef4236 | [] | no_license | dragoljub-duric/Algorithms-Lab-ETH-Zurich-263-0006-00L- | d698073340f056f18c02675c4a1507c71f0c1bb4 | 26888c963d2ba878bcd3cc914b3cc1f69fb3ff96 | refs/heads/master | 2023-02-24T06:56:13.570566 | 2021-01-27T00:49:00 | 2021-01-27T00:49:00 | 298,054,267 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,271 | cpp | #include<bits/stdc++.h>
using namespace std;
long long dp(vector<vector<long long>>& memo, vector<vector<pair<int, int>>>& adj, int position, int moves){
if(memo[position][moves] != -1) return memo[position][moves];
long long maxi = -1;
if(adj[position].size() == 0) maxi = dp(memo, adj, 0, moves);
for(int i = 0; i < adj[position].size(); ++i) maxi = max(maxi, adj[position][i].second + dp(memo, adj, adj[position][i].first, moves -1));
return memo[position][moves] = maxi;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
int t, n, m, k; cin >> t;
long long x;
while(t--){
cin >> n >> m >> x >> k;
vector<vector<pair<int, int>>> adj(n, vector<pair<int, int>>());
for(int i = 0; i < m; ++i){
int u, v, p; cin >> u >> v >> p;
adj[u].push_back(make_pair(v, p));
}
vector<vector<long long>> memo(n, vector<long long>(k+1, -1));
for(int i = 0; i < n; ++i) memo[i][0] = 0;
bool possible = false;
for(int i = 1; i <= k && !possible; ++i)
if(dp(memo, adj, 0, i) >= x){
cout << i << "\n";
possible = true;
}
if(!possible) cout << "Impossible" << "\n";
}
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
cf7096831b875b1426c95905f454bb2625b4ede4 | 46833986169d94e1e5ab2bd3a91c3b05bd50609f | /Práctica 3/freeglut project 3D/freeglut project 3D/Panel.cpp | 68e94a4adf21c8a906a2808346a8b00132755b2d | [] | no_license | AdrianVader/OpenGL-first-practices | d111968a5a904fd4e79ec7709c9f7f29f55138de | 024e07f488ce25d627cbf995c5122f40d8f31867 | refs/heads/master | 2020-12-04T05:37:26.022877 | 2016-08-31T16:51:53 | 2016-08-31T16:51:53 | 67,056,402 | 0 | 0 | null | null | null | null | ISO-8859-2 | C++ | false | false | 4,199 | cpp | /* Authors:
Adrián Rabadán Jurado
and
Teresa Rodríguez Ferreira
*/
#include <iostream>
#include "Panel.h"
Panel::Panel(GLdouble width){
//Inicialización de variables
Panel::_numVert = 32;
Panel::_numNorm = Panel::_numVert;
Panel::_numSid = 22;
Panel::_arrVert = list<PV3D>();
Panel::_arrNorm = list<PV3D>();
Panel::_arrSid = list<Cara>();
//Puntos iniciales donde se empezará a dibujar el panel
GLdouble puntoAncho; //x
GLdouble puntoGrosor; //y
GLdouble puntoLongitud = 0; //z
GLdouble length = 3; //Longitud del panel
GLdouble grosor = 0.3; //Grosor o alto del panel
PV3D p1;
PV3D p2;
PV3D p3;
PV3D p4;
list<PV3D> arrAux = list<PV3D>(); //Lista auxiliar para guardar los 8 puntos relevantes a la hora de dibujar las caras a lo largo
PV3D punto;
//GENERACIÓN DE VÉRTICES
//Guardamos los vértices que generan las rejillas de los extremos
for(int z = 0; z < 2; z++){
puntoGrosor = 0;
for(int i = 0; i < 4; i++){
puntoAncho = 0;
for(int j = 0; j < 4; j++){
punto = PV3D(puntoAncho, puntoGrosor, puntoLongitud, 1);
Panel::_arrVert.push_back(punto);
puntoAncho += width/3.0;
//Si el punto es uno de los necesarios para dibujar el panel a lo largo, lo guardamos
if(j==0 && i== 0)
p1 = punto;
if(j==3 && i== 0)
p2 = punto;
if(j==0 && i== 3)
p4 = punto;
if(j==3 && i== 3)
p3 = punto;
}
puntoGrosor += grosor/3.0;
}
//Guardamos los puntos relevantes en la lista auxiliar
arrAux.push_back(p1);
arrAux.push_back(p2);
arrAux.push_back(p3);
arrAux.push_back(p4);
puntoLongitud += length;
}
//GENERACIÓN DE CARAS
list<PV3D> l = list<PV3D>();
list<PV3D>::iterator itV1 = Panel::_arrVert.begin();
list<PV3D>::iterator itV2 = Panel::_arrVert.begin();
//Primero generamos las caras que forman las rejillas de los extremos
for(int i = 0; i < 4; i++)
itV2++;
for(int z = 0; z < 2; z++){
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
p1 = *itV2;
p2 = *itV1;
itV1++;
itV2++;
p3 = *itV1;
p4 = *itV2;
l.push_back(p1);
l.push_back(p2);
l.push_back(p3);
l.push_back(p4);
// calcula la normal de la cara, con l(vértices de la cara) y lo mete donde está listNorm.
// Generate normals.
PV3D norm = Panel::newellNormal(l);
list<VerticeNormal> listVertNorm = list<VerticeNormal>();
list<PV3D>::iterator itL = l.begin();
for(int z = 0; z < l.size();z++){
listVertNorm.push_back(VerticeNormal(*itL, norm));
itL++;
Panel::_arrNorm.push_back(norm);
}
Panel::_arrSid.push_back(Cara(listVertNorm.size(), listVertNorm));
l.clear();
}
if(itV2 != Panel::_arrVert.end()){
itV1++;
itV2++;
}
}
if(itV2 != Panel::_arrVert.end()){
for(int i = 0; i < 4; i++){
itV1++;
itV2++;
}
}
}
//Ahora generamos las cuatro caras que forman el largo del panel
itV1 = arrAux.begin();
itV2 = arrAux.begin();
for(int i = 0; i < 4; i++)
itV2++;
PV3D fstVertAct = *itV1;
PV3D fstVertNext = *itV2;
PV3D vertAct1;
PV3D vertAct2 = *itV1;
PV3D vertNext1;
PV3D vertNext2 = *itV2;
int cont = 0;
do{
vertAct1 = *itV1;
vertNext1 = *itV2;
itV1++;
itV2++;
if(cont < 3){
vertAct2 = *itV1;
vertNext2 = *itV2;
cont++;
}else{
vertAct2 = fstVertAct;
vertNext2 = fstVertNext;
}
l.push_back(vertAct1);
l.push_back(vertAct2);
l.push_back(vertNext2);
l.push_back(vertNext1);
// calcula la normal de la cara, con l(vértices de la cara) y lo mete donde está listNorm.
// Generate normals.
PV3D norm = Panel::newellNormal(l);
list<VerticeNormal> listVertNorm = list<VerticeNormal>();
list<PV3D>::iterator itL = l.begin();
for(int i = 0; i < l.size();i++){
listVertNorm.push_back(VerticeNormal(*itL, norm));
itL++;
Panel::_arrNorm.push_back(norm);
}
Panel::_arrSid.push_back(Cara(listVertNorm.size(), listVertNorm));
l.clear();
}while(itV2 != arrAux.end());
}
void Panel::draw(){
list<Cara>::iterator it = Panel::_arrSid.begin();
while(it != Panel::_arrSid.end()){
glColor3f(0.0, 1.0, 0.0);
it->draw();
it++;
}
}
Panel::~Panel(void)
{
}
| [
"adri.rabadan@gmail.com"
] | adri.rabadan@gmail.com |
3c3533daa686caa24d656758ba59f36f5a097313 | 2087bc2a508f4b40d302f4456f4751726759ea33 | /Lesson1/Home/Main.cpp | e72eafd49ff5f4887060231ec6c069ba893285cc | [] | no_license | Maciuk85/CppLevelIFundamentalsOfProceduralProgrammingInCpp | 73fe39834ad056a533f65b03809d1c369cb2e602 | bbd59f6fc196dcad34368ab37a0829e69cc7a1b1 | refs/heads/master | 2021-01-22T11:29:59.349471 | 2017-01-12T19:54:57 | 2017-01-12T19:54:57 | 68,733,000 | 0 | 0 | null | 2017-01-12T19:54:58 | 2016-09-20T16:46:52 | C++ | UTF-8 | C++ | false | false | 135 | cpp | #include <iostream>
using namespace std;
int main() {
cout << "Hello World Home Project! :D" << endl;
system("pause");
return 0;
} | [
"Maciek@DESKTOP-B0KQNFC"
] | Maciek@DESKTOP-B0KQNFC |
5b6d65701418979e3427a4517ee1670342263ca3 | 3bb241e281cb35028755111ad41a2276a713898e | /src/governance.h | 84177e273a7317fa6322cbf44579713f06087129 | [
"MIT"
] | permissive | Atlantis-dev/AtlantisCoin | 0201489fe838db4efa3535acd7d85dfb97d9d0f9 | e05b684b35fbc8adcf5f5e827b5b4f96b6716e93 | refs/heads/master | 2021-01-01T18:43:53.300091 | 2017-07-26T12:30:13 | 2017-07-26T12:30:13 | 98,415,350 | 0 | 1 | null | 2017-09-02T21:55:05 | 2017-07-26T11:27:20 | C++ | UTF-8 | C++ | false | false | 11,340 | h | // Copyright (c) 2014-2017 The Atl Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef GOVERNANCE_H
#define GOVERNANCE_H
//#define ENABLE_ATL_DEBUG
#include "bloom.h"
#include "cachemap.h"
#include "cachemultimap.h"
#include "chain.h"
#include "governance-exceptions.h"
#include "governance-object.h"
#include "governance-vote.h"
#include "net.h"
#include "sync.h"
#include "timedata.h"
#include "util.h"
class CGovernanceManager;
class CGovernanceTriggerManager;
class CGovernanceObject;
class CGovernanceVote;
extern std::map<uint256, int64_t> mapAskedForGovernanceObject;
extern CGovernanceManager governance;
typedef std::pair<CGovernanceObject, int64_t> object_time_pair_t;
static const int RATE_BUFFER_SIZE = 5;
class CRateCheckBuffer {
private:
std::vector<int64_t> vecTimestamps;
int nDataStart;
int nDataEnd;
bool fBufferEmpty;
public:
CRateCheckBuffer()
: vecTimestamps(RATE_BUFFER_SIZE),
nDataStart(0),
nDataEnd(0),
fBufferEmpty(true)
{}
void AddTimestamp(int64_t nTimestamp)
{
if((nDataEnd == nDataStart) && !fBufferEmpty) {
// Buffer full, discard 1st element
nDataStart = (nDataStart + 1) % RATE_BUFFER_SIZE;
}
vecTimestamps[nDataEnd] = nTimestamp;
nDataEnd = (nDataEnd + 1) % RATE_BUFFER_SIZE;
fBufferEmpty = false;
}
int64_t GetMinTimestamp()
{
int nIndex = nDataStart;
int64_t nMin = numeric_limits<int64_t>::max();
if(fBufferEmpty) {
return nMin;
}
do {
if(vecTimestamps[nIndex] < nMin) {
nMin = vecTimestamps[nIndex];
}
nIndex = (nIndex + 1) % RATE_BUFFER_SIZE;
} while(nIndex != nDataEnd);
return nMin;
}
int64_t GetMaxTimestamp()
{
int nIndex = nDataStart;
int64_t nMax = 0;
if(fBufferEmpty) {
return nMax;
}
do {
if(vecTimestamps[nIndex] > nMax) {
nMax = vecTimestamps[nIndex];
}
nIndex = (nIndex + 1) % RATE_BUFFER_SIZE;
} while(nIndex != nDataEnd);
return nMax;
}
int GetCount()
{
int nCount = 0;
if(fBufferEmpty) {
return 0;
}
if(nDataEnd > nDataStart) {
nCount = nDataEnd - nDataStart;
}
else {
nCount = RATE_BUFFER_SIZE - nDataStart + nDataEnd;
}
return nCount;
}
double GetRate()
{
int nCount = GetCount();
if(nCount < 2) {
return 0.0;
}
int64_t nMin = GetMinTimestamp();
int64_t nMax = GetMaxTimestamp();
if(nMin == nMax) {
// multiple objects with the same timestamp => infinite rate
return 1.0e10;
}
return double(nCount) / double(nMax - nMin);
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
READWRITE(vecTimestamps);
READWRITE(nDataStart);
READWRITE(nDataEnd);
READWRITE(fBufferEmpty);
}
};
//
// Governance Manager : Contains all proposals for the budget
//
class CGovernanceManager
{
friend class CGovernanceObject;
public: // Types
struct last_object_rec {
last_object_rec(bool fStatusOKIn = true)
: triggerBuffer(),
watchdogBuffer(),
fStatusOK(fStatusOKIn)
{}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
READWRITE(triggerBuffer);
READWRITE(watchdogBuffer);
READWRITE(fStatusOK);
}
CRateCheckBuffer triggerBuffer;
CRateCheckBuffer watchdogBuffer;
bool fStatusOK;
};
typedef std::map<uint256, CGovernanceObject> object_m_t;
typedef object_m_t::iterator object_m_it;
typedef object_m_t::const_iterator object_m_cit;
typedef CacheMap<uint256, CGovernanceObject*> object_ref_cache_t;
typedef std::map<uint256, int> count_m_t;
typedef count_m_t::iterator count_m_it;
typedef count_m_t::const_iterator count_m_cit;
typedef std::map<uint256, CGovernanceVote> vote_m_t;
typedef vote_m_t::iterator vote_m_it;
typedef vote_m_t::const_iterator vote_m_cit;
typedef CacheMap<uint256, CGovernanceVote> vote_cache_t;
typedef CacheMultiMap<uint256, vote_time_pair_t> vote_mcache_t;
typedef object_m_t::size_type size_type;
typedef std::map<COutPoint, last_object_rec > txout_m_t;
typedef txout_m_t::iterator txout_m_it;
typedef txout_m_t::const_iterator txout_m_cit;
typedef std::set<uint256> hash_s_t;
typedef hash_s_t::iterator hash_s_it;
typedef hash_s_t::const_iterator hash_s_cit;
typedef std::map<uint256, object_time_pair_t> object_time_m_t;
typedef object_time_m_t::iterator object_time_m_it;
typedef object_time_m_t::const_iterator object_time_m_cit;
typedef std::map<uint256, int64_t> hash_time_m_t;
typedef hash_time_m_t::iterator hash_time_m_it;
typedef hash_time_m_t::const_iterator hash_time_m_cit;
private:
static const int MAX_CACHE_SIZE = 1000000;
static const std::string SERIALIZATION_VERSION_STRING;
// Keep track of current block index
const CBlockIndex *pCurrentBlockIndex;
int64_t nTimeLastDiff;
int nCachedBlockHeight;
// keep track of the scanning errors
object_m_t mapObjects;
count_m_t mapSeenGovernanceObjects;
object_time_m_t mapMasternodeOrphanObjects;
hash_time_m_t mapWatchdogObjects;
object_ref_cache_t mapVoteToObject;
vote_cache_t mapInvalidVotes;
vote_mcache_t mapOrphanVotes;
txout_m_t mapLastMasternodeObject;
hash_s_t setRequestedObjects;
hash_s_t setRequestedVotes;
bool fRateChecksEnabled;
public:
// critical section to protect the inner data structures
mutable CCriticalSection cs;
CGovernanceManager();
virtual ~CGovernanceManager() {}
int CountProposalInventoryItems()
{
// TODO What is this for ?
return mapSeenGovernanceObjects.size();
//return mapSeenGovernanceObjects.size() + mapSeenVotes.size();
}
/**
* This is called by AlreadyHave in main.cpp as part of the inventory
* retrieval process. Returns true if we want to retrieve the object, otherwise
* false. (Note logic is inverted in AlreadyHave).
*/
bool ConfirmInventoryRequest(const CInv& inv);
void Sync(CNode* node, const uint256& nProp, const CBloomFilter& filter);
void ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv);
void NewBlock();
CGovernanceObject *FindGovernanceObject(const uint256& nHash);
std::vector<CGovernanceVote> GetMatchingVotes(const uint256& nParentHash);
std::vector<CGovernanceVote> GetCurrentVotes(const uint256& nParentHash, const CTxIn& mnCollateralOutpointFilter);
std::vector<CGovernanceObject*> GetAllNewerThan(int64_t nMoreThanTime);
bool IsBudgetPaymentBlock(int nBlockHeight);
bool AddGovernanceObject (CGovernanceObject& govobj);
std::string GetRequiredPaymentsString(int nBlockHeight);
void UpdateCachesAndClean();
void CheckAndRemove() {UpdateCachesAndClean();}
void Clear()
{
LOCK(cs);
LogPrint("gobject", "Governance object manager was cleared\n");
mapObjects.clear();
mapSeenGovernanceObjects.clear();
mapWatchdogObjects.clear();
mapVoteToObject.Clear();
mapInvalidVotes.Clear();
mapOrphanVotes.Clear();
mapLastMasternodeObject.clear();
}
std::string ToString() const;
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
LOCK(cs);
std::string strVersion;
if(ser_action.ForRead()) {
READWRITE(strVersion);
}
else {
strVersion = SERIALIZATION_VERSION_STRING;
READWRITE(strVersion);
}
READWRITE(mapSeenGovernanceObjects);
READWRITE(mapInvalidVotes);
READWRITE(mapOrphanVotes);
READWRITE(mapObjects);
READWRITE(mapWatchdogObjects);
READWRITE(mapLastMasternodeObject);
if(ser_action.ForRead() && (strVersion != SERIALIZATION_VERSION_STRING)) {
Clear();
return;
}
}
void UpdatedBlockTip(const CBlockIndex *pindex);
int64_t GetLastDiffTime() { return nTimeLastDiff; }
void UpdateLastDiffTime(int64_t nTimeIn) { nTimeLastDiff = nTimeIn; }
int GetCachedBlockHeight() { return nCachedBlockHeight; }
// Accessors for thread-safe access to maps
bool HaveObjectForHash(uint256 nHash);
bool HaveVoteForHash(uint256 nHash);
bool SerializeObjectForHash(uint256 nHash, CDataStream& ss);
bool SerializeVoteForHash(uint256 nHash, CDataStream& ss);
void AddSeenGovernanceObject(uint256 nHash, int status);
void AddSeenVote(uint256 nHash, int status);
bool MasternodeRateCheck(const CGovernanceObject& govobj, bool fUpdateLast = false);
bool MasternodeRateCheck(const CGovernanceObject& govobj, bool fUpdateLast, bool fForce, bool& fRateCheckBypassed);
bool ProcessVoteAndRelay(const CGovernanceVote& vote, CGovernanceException& exception) {
bool fOK = ProcessVote(NULL, vote, exception);
if(fOK) {
vote.Relay();
}
return fOK;
}
void CheckMasternodeOrphanVotes();
void CheckMasternodeOrphanObjects();
bool AreRateChecksEnabled() const {
LOCK(cs);
return fRateChecksEnabled;
}
void InitOnLoad();
void RequestGovernanceObjectVotes(CNode* pnode);
void RequestGovernanceObjectVotes(const std::vector<CNode*>& vNodesCopy);
private:
void RequestGovernanceObject(CNode* pfrom, const uint256& nHash, bool fUseFilter = false);
void AddInvalidVote(const CGovernanceVote& vote)
{
mapInvalidVotes.Insert(vote.GetHash(), vote);
}
void AddOrphanVote(const CGovernanceVote& vote)
{
mapOrphanVotes.Insert(vote.GetHash(), vote_time_pair_t(vote, GetAdjustedTime() + GOVERNANCE_ORPHAN_EXPIRATION_TIME));
}
bool ProcessVote(CNode* pfrom, const CGovernanceVote& vote, CGovernanceException& exception);
/// Called to indicate a requested object has been received
bool AcceptObjectMessage(const uint256& nHash);
/// Called to indicate a requested vote has been received
bool AcceptVoteMessage(const uint256& nHash);
static bool AcceptMessage(const uint256& nHash, hash_s_t& setHash);
void CheckOrphanVotes(CGovernanceObject& govobj, CGovernanceException& exception);
void RebuildIndexes();
/// Returns MN index, handling the case of index rebuilds
int GetMasternodeIndex(const CTxIn& masternodeVin);
void RebuildVoteMaps();
void AddCachedTriggers();
};
#endif
| [
"onecoin@sfr.fr"
] | onecoin@sfr.fr |
0c7e7e2845e6cd19e91d59f7e79fdad747e110b3 | c442390d6b800294f1f6c30374e9e139b5eba6c5 | /src/Actions/SetIndexerState.h | 62da6d1884ed11e6423c9d4e322ab6d5c31a9006 | [] | no_license | FRCTeamPhoenix/Phoenix2017 | 61e9ab976d8d9bc7fe3b4ef5f046de6d8d2ce12f | 3282a3c438ada7a96f4b68951fb8173f6d3ab03d | refs/heads/develop | 2021-01-12T02:11:04.240192 | 2017-04-05T11:45:52 | 2017-04-05T11:45:52 | 78,484,243 | 1 | 0 | null | 2017-03-28T23:17:46 | 2017-01-10T01:08:17 | C++ | UTF-8 | C++ | false | false | 857 | h | /*
* SetIndexerState.h
*
* Created on: Mar 6, 2017
* Author: Brin Harper
*/
#ifndef SRC_ACTIONS_SETINDEXERSTATE_H_
#define SRC_ACTIONS_SETINDEXERSTATE_H_
#include "Action.h"
#include "Indexer.h"
#include "dependency.h"
#include <vector>
#include <iostream>
#include "../plog/Log.h"
using namespace std;
class Robot;
class SetIndexerState : public Action
{
public:
// State: 0=TELEOP, 1=ON, 2=OFF
// State numbers have been chosen to match class enums
SetIndexerState(int state, double duration, vector<shared_ptr<dependency>> dependencies, shared_ptr<Robot> robot);
SetIndexerState(json& action, shared_ptr<Robot> robot);
private:
frc::Timer m_timer;
int m_state;
double m_duration;
void run();
void reset();
};
#endif /* SRC_ACTIONS_SETINDEXERSTATE_H_ */
| [
"William.Gebhardt@asdnh.org"
] | William.Gebhardt@asdnh.org |
1c5a3ae62c84dd30cf7d69a4d22376c8c99c77ab | 92eead7872140b0ba00e54629ef19d4432f3be4e | /Chapter-12/12.28.cpp | 3aa7dea6ffe7f5fdd6c01837b32f7c6a1833de40 | [] | no_license | shengchiliu/Cpp-Primer-Answer | acd8a3b3f0ce80fd759055d7d79788c2b5456b13 | 9a932c349b5cd272c47a7c793c3cee8c84f9edbc | refs/heads/master | 2023-03-22T10:35:00.824761 | 2019-08-30T04:57:29 | 2019-08-30T04:57:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 840 | cpp | #include<iostream>
#include<string>
#include<fstream>
#include<vector>
#include<set>
#include<map>
#include<sstream>
int main()
{
std::ifstream ifs("1.txt");
std::vector<std::string> lines;
std::map<std::string, std::set<size_t>> dict;
std::string s;
size_t i = 0;
while(std::getline(ifs, s))
{
++i;
lines.push_back(s);
std::istringstream l(s);
std::string word;
while(l >> word)
dict[word].insert(i);
}
while(true)
{
std::cout << "enter word to look for, or q to quit: ";
std::string s;
if(!(std::cin >> s) || s == "q")
break;
std::cout << s << " occurs " << dict[s].size() << (std::string(" time") + ((dict[s].size() > 1) ? "s" : "" )) << std::endl;
for(size_t i : dict[s])
std::cout << "\t" << "(line " << i << " ) " << lines[i - 1] << std::endl;
std::cout << std::endl;
}
return 0;
}
| [
"jzplp@qq.com"
] | jzplp@qq.com |
a26458ae3e39e8af67d0dd450d08b79c3e761c20 | 003fb5094021351eb82c49c8eadbb6dd5b139004 | /006_BAEKJOON/02206.cpp | effe7c8180c7983284817b9bfad90d4f8ec4538f | [] | no_license | woongbinni/algorithm | ebdb700195ccc158f7be1ebf7af06e9913d4e8fd | a1d5c0bc8b727d4feea670ea35218e701e0ffdb4 | refs/heads/master | 2022-11-16T23:40:44.628307 | 2022-11-11T15:21:26 | 2022-11-11T15:21:26 | 32,263,313 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,759 | cpp | #include <stdio.h>
#include <iostream>
using namespace std;
#include <queue>
typedef struct _loc {
int y;
int x;
int distance;
int wall_break;
}loc;
int N, M;
char map[1001][1001];
bool visited[2][1001][1001];
int dy[4] = {-1, 0, 1, 0};
int dx[4] = {0, 1, 0, -1};
int bfs() {
loc start;
start.y = 1;
start.x = 1;
start.distance = 1;
start.wall_break = 0;
visited[start.wall_break][start.y][start.x] = true;
queue<loc> bfs_queue;
bfs_queue.push(start);
while(!bfs_queue.empty()){
loc pop = bfs_queue.front();
bfs_queue.pop();
if(pop.y == N && pop.x == M) return pop.distance;
for(int i=0; i<4; ++i){
loc next;
next.y = pop.y + dy[i];
next.x = pop.x + dx[i];
next.wall_break = pop.wall_break;
next.distance = pop.distance + 1;
if(next.y < 1 || next.y > N || next.x < 1 || next.x > M){
continue;
}
if(visited[next.wall_break][next.y][next.x]){
continue;
}
if(map[next.y][next.x] == '0'){
visited[next.wall_break][next.y][next.x] = true;
bfs_queue.push(next);
}
if(map[next.y][next.x] == '1' && next.wall_break == 0){
next.wall_break = 1;
visited[next.wall_break][next.y][next.x] = true;
bfs_queue.push(next);
}
}
}
return -1;
}
int main() {
scanf("%d%d", &N, &M);
for(int i=1; i<=N; ++i) {
char temp[1001];
scanf("%s", temp);
for(int j=1; j<=M; ++j){
map[i][j] = temp[j-1];
}
}
printf("%d\n", bfs());
return 0;
} | [
"woongbinni@gmail.com"
] | woongbinni@gmail.com |
074abe32149db563d6c17d31922e5ad1744d39a0 | 9bba90bad4f312c949c0704a6b3a3d94cdca4671 | /test.code/transfer_file/server_noqueue/socket_buff.cc | 0521a2c3a71c2c876fe6b9bd931522c7895cde9d | [
"Apache-2.0"
] | permissive | P79N6A/workspace | 036072fc3788ec50a95744b512e1566c3b16f082 | 2f1b4977ef51e77fcaf7e3c120714138099ce096 | refs/heads/master | 2020-04-23T10:04:37.302251 | 2019-02-17T06:57:18 | 2019-02-17T06:57:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,980 | cc | #include "socket_buff.h"
#include <malloc.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
const int32_t kSize = 8 * 1024;
const int32_t kFreeSize = 4 * 1024;
const int32_t kMaxSize = 1024 * 1024;
SocketBuff::SocketBuff(int32_t socket)
: socket_(socket){
socket_buff_ = (char*) malloc(kMaxSize);
data_ = socket_buff_;
free_ = socket_buff_;
data_len_ = 0;
free_len_ = kMaxSize;
read_size_ = kSize;
}
SocketBuff::~SocketBuff() {
}
// 0: client close
// 1: recv success
// -1: recv fail
int32_t SocketBuff::RecvSocket() {
int32_t recv_size = 0;
do {
if (read_size_ > free_len_) read_size_ = free_len_;
recv_size = ::recv(socket_, free_, read_size_, 0);
if (recv_size < 0) {
return 0;
} else if (recv_size == 0) {
return 0;
} else {
data_len_ += recv_size;
free_len_ -= recv_size;
free_ += recv_size;
if (free_len_ < kSize) {
memmove(socket_buff_, data_, data_len_);
data_ = socket_buff_;
free_ = data_ + data_len_;
free_len_ = kMaxSize - data_len_;
read_size_ = kSize;
}
// 确保收到header
if (data_len_ >= 2) {
uint16_t packet_len = *(uint16_t*) data_;
if (packet_len <= data_len_) {
break;
}
}
}
} while(true);
return 1;
}
bool SocketBuff::NextPacket(char*& packet, int32_t& len) {
if (data_ == free_) {
if (!RecvSocket()) {
return false;
}
}
if (data_len_ < 2 || (*(uint16_t*) data_) > data_len_) {
if (!RecvSocket()) {
return false;
}
}
// 校验
assert(data_len_ >= 2);
assert((*(uint16_t*) data_) <= data_len_);
/*
if (data_len_ < 2 || (*(uint16_t*) data_) > data_len_) {
return false;
}*/
uint16_t packet_len = *(uint16_t*) data_;
packet = data_ + sizeof(uint16_t);
len = packet_len - sizeof(uint16_t);
data_len_ -= packet_len;
data_ += packet_len;
return true;
}
| [
"lianjiang.yulj@alibaba-inc.com"
] | lianjiang.yulj@alibaba-inc.com |
8642ebfa4ad187c5417621851ecd7b3729de2af8 | 60a15a584b00895e47628c5a485bd1f14cfeebbe | /comps/misc/Blood/ResegmentCells.cpp | 8e8602fec6f2d441d701111108fa0636b9d00bc7 | [] | no_license | fcccode/vt5 | ce4c1d8fe819715f2580586c8113cfedf2ab44ac | c88049949ebb999304f0fc7648f3d03f6501c65b | refs/heads/master | 2020-09-27T22:56:55.348501 | 2019-06-17T20:39:46 | 2019-06-17T20:39:46 | null | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 9,752 | cpp | #include "stdafx.h"
#include "ResegmentCells.h"
#include "misc_utils.h"
#include <math.h>
#include "alloc.h"
#include "nameconsts.h"
#include "clone.h"
#include "clonedata.h"
#include "ImagePane.h"
#include "object5.h"
#include "measure5.h"
#include "bytemorpho.h"
#define MaxColor color(-1)
_ainfo_base::arg CResegmentCellsInfo::s_pargs[] =
{
{"SeedThreshold", szArgumentTypeDouble, "0.0", true, false },
{"Threshold", szArgumentTypeDouble, "0.3", true, false },
{"MaxDilate", szArgumentTypeDouble, "10", true, false },
{"Cells", szArgumentTypeObjectList, 0, true, true },
{"Resegmented", szArgumentTypeObjectList, 0, false, true },
{0, 0, 0, false, false },
};
static inline int iround(double x)
{
return int(floor(x+0.5));
}
/////////////////////////////////////////////////////////////////////////////
bool CResegmentCells::InvokeFilter()
{
INamedDataObject2Ptr sptrSrc(GetDataArgument("Cells")); // Object list
INamedDataObject2Ptr sptrDst(GetDataResult()); // Object list
if(sptrSrc==NULL || sptrDst==NULL)
return false;
double fThreshold = GetArgDouble("Threshold");
double fSeedThreshold = GetArgDouble("SeedThreshold");
double fMaxDilate = GetArgDouble("MaxDilate");
long lObjects;
sptrSrc->GetChildsCount(&lObjects);
StartNotification(lObjects,2);
POSITION pos = 0; long i = 0;
sptrSrc->GetFirstChildPosition(&pos);
while (pos)
{
IUnknownPtr ptr;
sptrSrc->GetNextChild(&pos, &ptr);
IClonableObjectPtr sptrClone(ptr);
if(sptrClone == 0) continue;
IUnknownPtr ptr2;
sptrClone->Clone(&ptr2);
IMeasureObjectPtr sptrMO(ptr);
IUnknownPtr ptrImage;
if(sptrMO !=0 )
sptrMO->GetImage(&ptrImage);
IUnknownPtr ptrImage2( ::CreateTypedObject(_bstr_t(szTypeImage)), false);
ICompatibleObjectPtr sptrCO2 = ptrImage2;
if(sptrCO2!=0)
sptrCO2->CreateCompatibleObject(ptrImage,0,0);
IMeasureObjectPtr sptrMO2(ptr2);
if(sptrMO2!=0)
sptrMO2->SetImage(ptrImage2);
IImage3Ptr sptrImage(ptrImage);
if(sptrImage==0) continue;
IImage3Ptr sptrImage2(ptrImage2);
if(sptrImage2==0) continue;
// скопируем контура
{
int nContours=0;
sptrImage->GetContoursCount(&nContours);
sptrImage2->FreeContours();
for(int i=0; i<nContours; i++)
{
Contour* pCont = 0;
sptrImage->GetContour(i, &pCont);
Contour* pCont2 = new Contour;
*pCont2 = *pCont; // скопировали все числа, ссылаемся на старые контура
pCont2->ppoints = new ContourPoint[pCont2->nAllocatedSize];
memcpy(pCont2->ppoints, pCont->ppoints, pCont2->nAllocatedSize*sizeof(ContourPoint));
sptrImage2->AddContour(pCont2);
}
}
// собственно сегментация
int cx=0,cy=0;
sptrImage2->GetSize(&cx,&cy);
smart_alloc(ppc, color*, cy);
smart_alloc(ppm, byte*, cy);
smart_alloc(pDist, double, cx*cy);
smart_alloc(ppDist, double*, cy);
for(int y=0; y<cy; y++)
{
sptrImage2->GetRow(y,1,ppc+y);
sptrImage2->GetRowMask(y, ppm+y );
ppDist[y] = pDist+y*cx;
}
if(fThreshold>=0.0)
{ // --------------- Пересегментация ядер -------------
// найдем пороги для сегментации
double c0=0, c1=0;
double s0=0, s1=0;
double color0=0, color1=65535;
for(int pass=0; pass<4; pass++)
{
for(int y=0; y<cy; y++)
{
for(int x=0; x<cx; x++)
{
double w;
switch(ppm[y][x])
{
case 255: // цитоплазма
w = ppc[y][x]-color0;
w = exp(w/(256*20));
w = max(0,w);
s1 += ppc[y][x]*w;
c1 += w;
case 254: // ядро
w = color1-ppc[y][x];
w = exp(w/(256*20));
w = max(0,w);
s0 += ppc[y][x]*w;
c0 += w;
}
}
}
if(c0) color0 = s0/c0;
if(c1) color1 = s1/c1;
}
// нашли color0 и color1 - примерный диапазон цветов клетки
{
int th0 = int(color0 + (color1-color0)*fSeedThreshold);
int th1 = int(color0 + (color1-color0)*fThreshold);
// сегментация зародышей
for(int y=0; y<cy; y++)
{
for(int x=0; x<cx; x++)
{
ppDist[y][x]=1e30;
if(ppm[y][x]>=254) // цитоплазма или ядро
{
if(ppc[y][x]>th0)
{
ppm[y][x]=255; // цитоплазма
}
else
{
ppm[y][x]=254; // ядро
ppDist[y][x]=0;
}
}
}
}
for(int pass=0; pass<2; pass++)
{
for(int y=1; y<cy-1; y++)
{
for(int x=1; x<cx-1; x++)
{
ppDist[y][x+1] = min(ppDist[y][x+1],ppDist[y][x]+1);
ppDist[y+1][x] = min(ppDist[y+1][x],ppDist[y][x]+1);
if(ppm[y][x]==254) // ядро
{
double th = th1 + (th0-th1)*ppDist[y][x]/fMaxDilate;
if(ppc[y][x+1]<=th) ppm[y][x+1]=254;
if(ppc[y+1][x]<=th) ppm[y+1][x]=254;
}
}
}
for(int y=cy-2; y>0; y--)
{
for(int x=cx-2; x>0; x--)
{
ppDist[y][x-1] = min(ppDist[y][x-1],ppDist[y][x]+1);
ppDist[y-1][x] = min(ppDist[y-1][x],ppDist[y][x]+1);
if(ppm[y][x]==254) // ядро
{
double th = th1 + (th0-th1)*ppDist[y][x]/fMaxDilate;
if(ppc[y][x-1]<=th) ppm[y][x-1]=254;
if(ppc[y-1][x]<=th) ppm[y-1][x]=254;
}
}
}
}
}
// морфология, как в FindCells - чтобы границы были поаккуратнее
int nNucleiCloseSize=GetValueInt(GetAppUnknown(),"\\FindCells", "NucleiCloseSize",5);
if(nNucleiCloseSize%2 == 0) nNucleiCloseSize = nNucleiCloseSize-1;
nNucleiCloseSize = max(1,nNucleiCloseSize);
SetValue(GetAppUnknown(),"\\FindCells", "NucleiCloseSize",long(nNucleiCloseSize));
DilateColor(ppm, cx, cy, nNucleiCloseSize, 254,254,255); // дилатация ядра на фоне цитоплазмы
DilateColor(ppm, cx, cy, 3, 0,255,254); // эрозия ядра - только те части, что примыкают к краю цитоплазмы
DilateColor(ppm, cx, cy, nNucleiCloseSize, 255,255,254); // эрозия ядра
DilateColor(ppm, cx, cy, nNucleiCloseSize, 255,255,254); // эрозия ядра
DilateColor(ppm, cx, cy, nNucleiCloseSize, 254,254,255); // дилатация ядра
DeleteSmallSegments(ppm, cx, cy, 12, 254);
} // --------------- Пересегментация ядер end -------------
else if ( -1.0 == fThreshold )
{ // --------------- Пересегментация цитоплазмы - "бублик" (слой вокруг ядра) -------------
for(int y=0; y<cy; y++)
{
for(int x=0; x<cx; x++)
{
if(ppm[y][x]!=254) // ядро
ppm[y][x]=253; // фон внутри квадрата
}
}
DilateColor(ppm, cx, cy, int(fMaxDilate), 254,255,253); // расползаемся от ядра (254) цитоплазмой (255) на фон (253)
} // --------------- Пересегментация цитоплазмы end -------------
else if ( -2.0 == fThreshold )
{ // --------------- Пересегментация цитоплазмы - ограничение бубликом -------------
DilateColor(ppm, cx, cy, int(fMaxDilate), 254,128,255); // расползаемся от ядра (254) маркером (128) по цитоплазме (255)
for(int y=0; y<cy; y++)
{
for(int x=0; x<cx; x++)
{
if(ppm[y][x]==255) // цитоплазма вне бублика
ppm[y][x]=253; // фон внутри квадрата
else if(ppm[y][x]==128) // цитоплазма внутри бублика
ppm[y][x]=255; // цитоплазма
}
}
} // --------------- Пересегментация цитоплазмы end -------------
else if ( -3.0 == fThreshold )
{ // --------------- Эксперимент - эквалайз -------------
smart_alloc(hist, double, 256);
for(int nPane=0; nPane<3; nPane++)
{
for(int y=0; y<cy; y++)
sptrImage2->GetRow(y,nPane,ppc+y); // Работаем по нужной пане
for(int i=0; i<256; i++) hist[i] = 10; // имитация шума
for(int y=0; y<cy; y++)
{
for(int x=0; x<cx; x++)
{
if(ppm[y][x]<254) continue; // фон и всякую фигню пропускаем
int v = ppc[y][x] / 256;
hist[v] ++;
}
}
// размоем гистограмму
for(int i=1; i<256; i++) hist[i] = hist[i] + (hist[i-1]-hist[i])*0.5;
for(int i=254; i>=0; i--) hist[i] = hist[i] + (hist[i+1]-hist[i])*0.5;
double s=0;
for(int i=0; i<256; i++) s += hist[i];
smart_alloc(ii, int, 256);
double ss=0;
int j=0;
for(int i=0; i<256; i++)
{
ss += hist[i]/s;
int j1 = iround(ss*255);
ii[i] = j1;
//while(j<=j1) ii[j++] = i;
}
for(int y=0; y<cy; y++)
{
for(int x=0; x<cx; x++)
{
//if(ppm[y][x]<254) continue; // фон и всякую фигню пропускаем
int v = ppc[y][x] / 256;
ppc[y][x] = ii[v]*256;
}
}
/*
int i1=0, i5=0, i9=0;
double ss=0;
for(int i=0; i<256; i++)
{
ss += hist[i];
if(ss<=s*0.1) i1 = i;
if(ss<=s*0.5) i5 = i;
if(ss<=s*0.9) i9 = i;
}
//double D = i1*i1*i2 + i2*i2*i3 + i1*i3*i3
// - i1*i1*i3 - i1*i2*i2 - i3*i3*i2;
//double a = 0.1*i2 + 0.5*i3 + 0.9*
double scale = (i9-i1) / (255*0.8);
double shift = i1 - 0.1*255*scale;
// i = i*scale + shift
double center_shift = 255*0.5
*/
}
} // --------------- Эксперимент - эквалайз end -------------
INamedDataObject2Ptr ptrObject(ptr2);
if(ptrObject != 0)
ptrObject->SetParent(sptrDst, 0);
Notify(i++);
}
FinishNotification();
SetModified(true);
return true;
}
| [
"videotestc@gmail.com"
] | videotestc@gmail.com |
17502006a6f0b10c33664cafcccddc9d72d0252b | 8184b135c7c9ec39a345dbb3c33bb06093688a5d | /paopao/Ball.cpp | 806ffb845ba2ee95ec12d818360f568b5c120426 | [] | no_license | woshinyc/paopao | 36aa0bd306c18c1f4812facde17e7e89cf66003f | 7791284649a1f24c72288836896ab6f013c43247 | refs/heads/master | 2020-03-26T15:13:36.046885 | 2013-07-15T10:21:47 | 2013-07-15T10:21:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,016 | cpp | //
// Ball.cpp
// paopao
//
// Created by NycMac on 13-7-10.
//
//
#include "Ball.h"
#include "enumWhole.h"
#include "AppDelegate.h"
#include "GameLayer.h"
bool Ball::init()
{
if (!SpriteBase::init()) {
return false;
}
return true;
}
Ball* Ball::getBall()
{
Ball *ball=Ball::create();
int numType=ballTypeNum;
CCString *st=CCString::createWithFormat("ball%i.png",numType);
ball->initWithSpriteFrameName(st->getCString());
ball->typeNum=numType;
return ball;
}
int Ball::getLineNub()
{
float height =worldHeight-this->getPositionY();
int lineNub=height/paopaoHeight;
return lineNub;
}
int Ball::getNubInLine()
{
float x=this->getRectangle().origin.x;
int nubInLine=(int)x/paopaoWidth;
return nubInLine;
}
void Ball::beStop()
{
SpriteBase::beStop();
// setPositionY((int)(getPositionY()/paopaoHeight)*paopaoHeight);
float height=CCDirector::sharedDirector()->getWinSize().height;
// //int addY=(int)getPositionY()%paopaoHeight;
// int addY= (int)(height-getPositionY())%paopaoHeight;
// CCLog("addY=%i",addY);
// if (addY==0) {
// setPositionY(getPositionY()+addY);
// }else{
// setPositionY(getPositionY()+addY-paopaoHeight);
// }
int lineNum=(int)((height-getPositionY())/paopaoHeight);
if (((int)(height-getPositionY())%paopaoHeight)>paopaoHeight*0.1) {
lineNum++;
}
CCLog("n=%i",lineNum);
setPositionY(height-paopaoWidth*lineNum);
if (mainLayer!=NULL) {
GameLayer *gl=(GameLayer *)mainLayer;
bool isFull=(int)(getPositionY()/paopaoHeight)%2==0?!gl->firstLineIsFull:gl->firstLineIsFull;
int nn=0;
if (((int)getPositionX()%paopaoWidth)>paopaoWidth*0.5) {
nn=1;
}
if (isFull) {
setPositionX((0.5+nn+(int)(getPositionX()/paopaoWidth))*paopaoWidth);
}else{
setPositionX((nn+(int)(getPositionX()/paopaoWidth))*paopaoWidth);
}
}
}
| [
"alvenyuan@limatoMacBook-Pro.local"
] | alvenyuan@limatoMacBook-Pro.local |
4b488afe0d5798e392ad21304350a0a5c3617902 | 9d2e6a246059be7f2a072bdf12525dcf821bc1e9 | /src/OzEngine/src/MeshRend.cpp | a37b1b1e3e0e5526d58aa4014588eee30f33b93b | [] | no_license | OzlFX/Oz_Engine | 196d484512de86970a39b911491bb6a89108a4e7 | dbcb94b5efe22017480f6f576f056767c9f7d335 | refs/heads/master | 2020-08-27T13:44:59.274107 | 2020-01-17T11:04:03 | 2020-01-17T11:04:03 | 217,392,664 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,617 | cpp | #include "OzEngine/src/MeshRend.h"
#include "Components/ComponentIncludes.h"
#include "OzEngine/src/Camera.h"
#include "Light.h"
#include "Mesh.h"
#include "Texture.h"
#include "RenderTexture.h"
#include "Material.h"
#include "RenderSystem/ShaderProgram.h"
namespace Oz
{
void cMeshRenderer::onBegin()
{
if (m_Material == NULL)
{
m_Shader = getCore()->getShader(); //Get the model loader shader
}
else
{
m_Shader = getCore()->loadShader(m_Material->getShader().at(0), m_Material->getShader().at(1));
m_Texture = m_Material->getTexture();
}
}
void cMeshRenderer::onDisplay()
{
if (getCore()->getMainCamera() != NULL)
{
//Check if the material is set
if (m_Material != NULL)
{
m_Lights = getCore()->getLights(); //Get the lights to render from
for (std::list<std::shared_ptr<cGameObject>>::iterator it = m_Lights.begin(); it != m_Lights.end(); it++)
{
m_Shader->setUniform("in_LightPos", (*it)->getTransform()->getPos());
m_Shader->setUniform("in_LightColor", glm::vec3(1.0f));
}
m_Shader->setUniform("in_View", getCore()->getMainCamera()->getView());
m_Shader->setUniform("in_Model", getGameObject()->getTransform()->getModel());
m_Shader->setUniform("in_albedo", m_Texture);
m_Shader->setUniform("in_normalMap", m_Material->getNormal());
m_Shader->setUniform("in_roughness", m_Material->getRoughness());
m_Shader->setUniform("in_metallic", m_Material->getMetallic());
m_Shader->setUniform("in_ao", m_Material->getDisperse());
m_Shader->Draw(m_Mesh);
}
else
{
//m_Shader->setUniform("in_Projection", getCore()->getMainCamera()->getProjection());
m_Shader->setUniform("in_View", getCore()->getMainCamera()->getView());
m_Shader->setUniform("in_Model", getGameObject()->getTransform()->getModel());
m_Shader->setUniform("in_Texture", m_Texture);
m_Shader->Draw(m_Mesh);
}
}
else
{
throw Oz::Exception("No Camera given, cannot render!");
}
}
void cMeshRenderer::setMesh(std::weak_ptr<cMesh> _mesh)
{
m_Mesh = _mesh.lock();
}
void cMeshRenderer::setTexture(std::weak_ptr<cTexture> _texture)
{
m_Texture = _texture.lock();
}
void cMeshRenderer::setMaterial(std::weak_ptr<cMaterial> _material)
{
m_Material = _material.lock();
}
//Get the mesh
std::shared_ptr<cMesh> cMeshRenderer::getMesh()
{
return m_Mesh;
}
//Get texture
std::shared_ptr<cTexture> cMeshRenderer::getTexture()
{
return m_Texture;
}
//Get material
std::shared_ptr<cMaterial> cMeshRenderer::getMaterial()
{
return m_Material;
}
cMeshRenderer::~cMeshRenderer()
{
}
} | [
"39440462+OzlFX@users.noreply.github.com"
] | 39440462+OzlFX@users.noreply.github.com |
6a9e9f1d0ff2e343ccf9ccd5d19dcbbc2fa7507a | aa15c48dc0ad50030d70eb1cce25ad9dfc08640c | /Source/WebKit/GPUProcess/GPUProcess.h | e8887268878fed0d267a054e5c0afca3395877a0 | [] | no_license | Man1029/webkit | c4e986c4f405028ffbe1acef9a92fa62b9cec1a6 | 0020b6fca0bd62a106537a4260e44d80bcc4d066 | refs/heads/master | 2023-05-28T03:05:15.176263 | 2019-12-18T07:00:28 | 2019-12-18T07:00:28 | 228,791,284 | 1 | 0 | null | 2019-12-18T08:16:26 | 2019-12-18T08:16:25 | null | UTF-8 | C++ | false | false | 3,352 | h | /*
* Copyright (C) 2019 Apple 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:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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.
*/
#pragma once
#if ENABLE(GPU_PROCESS)
#include "AuxiliaryProcess.h"
#include "WebPageProxyIdentifier.h"
#include <wtf/Function.h>
#include <wtf/MemoryPressureHandler.h>
#include <wtf/WeakPtr.h>
namespace WebKit {
class GPUConnectionToWebProcess;
struct GPUProcessCreationParameters;
class GPUProcess : public AuxiliaryProcess, public ThreadSafeRefCounted<GPUProcess>, public CanMakeWeakPtr<GPUProcess> {
WTF_MAKE_NONCOPYABLE(GPUProcess);
public:
GPUProcess(AuxiliaryProcessInitializationParameters&&);
~GPUProcess();
static constexpr ProcessType processType = ProcessType::GPU;
void removeGPUConnectionToWebProcess(GPUConnectionToWebProcess&);
void prepareToSuspend(bool isSuspensionImminent, CompletionHandler<void()>&&);
void processDidResume();
void resume();
void connectionToWebProcessClosed(IPC::Connection&);
GPUConnectionToWebProcess* webProcessConnection(WebCore::ProcessIdentifier) const;
private:
void lowMemoryHandler(Critical);
// AuxiliaryProcess
void initializeProcess(const AuxiliaryProcessInitializationParameters&) override;
void initializeProcessName(const AuxiliaryProcessInitializationParameters&) override;
void initializeSandbox(const AuxiliaryProcessInitializationParameters&, SandboxInitializationParameters&) override;
bool shouldTerminate() override;
// IPC::Connection::Client
void didReceiveMessage(IPC::Connection&, IPC::Decoder&) override;
void didClose(IPC::Connection&) override;
// Message Handlers
void initializeGPUProcess(GPUProcessCreationParameters&&);
void createGPUConnectionToWebProcess(WebCore::ProcessIdentifier, CompletionHandler<void(Optional<IPC::Attachment>&&)>&&);
void processDidTransitionToForeground();
void processDidTransitionToBackground();
// Connections to WebProcesses.
HashMap<WebCore::ProcessIdentifier, Ref<GPUConnectionToWebProcess>> m_webProcessConnections;
};
} // namespace WebKit
#endif // ENABLE(GPU_PROCESS)
| [
"timothy_horton@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc"
] | timothy_horton@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc |
6c6461b585ddd641bc53373f995077630afc98fe | e824b56ba99e170a0c7d4fba01495cc6298157f4 | /nemeziz_03.ino | 763b709cb425c22dfbd1b435e0160195e3e55968 | [] | no_license | formworx/Nemeziz-Arduino | b56c7d88ff0b80881d935bdd886d181fc553ece2 | 2df9677d1d4b56b8f43a3066948450ada3d515cb | refs/heads/master | 2022-12-11T04:42:48.629430 | 2017-06-03T21:46:40 | 2017-06-03T21:46:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,023 | ino | /*
Inition Nemeziz Boot SensorCode
Uses Adafruit BNO055 9DOF sensor
Board layout:
+----------+
| *| RST PITCH ROLL HEADING
ADR |* *| SCL
INT |* *| SDA ^ /->
PS1 |* *| GND | |
PS0 |* *| 3VO Y Z--> \-X
| *| VIN
+----------+
4.5" bend sensor from adafruit
SingleTact 1N 8mm pressure sensors x 5
Fabricated capacitive stroke sensors using triangles of copper tape on acetate
HC-SR04 distance sensor for proximity trigger
Data sent as comma separated string to serial in this format:
A, x, y, z, pressure1, pressure2, pressure3, pressure4, pressure5, stroke1, stroke2, stroke3, bend, distance
*/
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BNO055.h>
#include <utility/imumaths.h>
#include <CapacitiveSensor.h>
//Set the delay between fresh samples */
#define BNO055_SAMPLERATE_DELAY_MS (10)
#include <NewPing.h>
//pins for distance sensor
#define TRIGGER_PIN 13 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 12 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
Adafruit_BNO055 bno = Adafruit_BNO055(55);
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance
CapacitiveSensor cs_11_10 = CapacitiveSensor(11, 10); //for stroke sensor1
CapacitiveSensor cs_9_8 = CapacitiveSensor(9, 8); //for stroke sensor2
CapacitiveSensor cs_7_6 = CapacitiveSensor(7, 6); //for stroke sensor2
int bendPin = 0; // select the input pin for the potentiometer
float bendValue = 0; // variable to store the value coming from the sensor
int bendMin = 115; //was 160
int bendMax = 107; //was 130
//define i2c addresses for 5 singletact sensors (set thro singletact PC application)
byte i2cAddress1 = 0x05;
byte i2cAddress2 = 0x06;
byte i2cAddress3 = 0x07;
byte i2cAddress4 = 0x08;
byte i2cAddress5 = 0x09;
//byte i2cAddress6 = 0x10;
long distance; //for distance measure
float qw, qx, qy, qz, x, y, z, xcal;
short data1, data2, data3, data4, data5, data6; //for singletact pressure sensors
long lastTime; //to record time to charge stroke sensor capacitors
long start, total1, total2, total3; //for capacitive values from stroke sensors
boolean sendData = false; //send data when this flag is true
void setup(void)
{
Serial.begin(9600);
Serial.flush();
/* Initialise the sensor */
if (!bno.begin())
{
/* There was a problem detecting the BNO055 ... check your connections */
//Serial.print("Ooops, no BNO055 detected ... Check your wiring or I2C ADDR!");
while (1);
}
delay(1000);
/* Use external crystal for better accuracy */
bno.setExtCrystalUse(true);
lastTime = millis();
}
void loop(void)
{
distance = sonar.ping_cm();
//Serial.println(sonar.ping_cm()); // Send ping, get distance in cm and print result (0 = outside set distance range)
//start counter for measuring capacitance
start = millis();
total1 = cs_11_10.capacitiveSensor(30); //get value for stroke 1
total2 = cs_9_8.capacitiveSensor(30); //get value for stroke2
total3 = cs_7_6.capacitiveSensor(30); //get value for stroke3
//bend sensor
bendValue = analogRead(bendPin);
//Serial.println(bendValue);
bendValue = map(bendValue, bendMin, bendMax, 0, 90);
getPressure();
/* Get a new position sensor event */
sensors_event_t event;
bno.getEvent(&event);
imu::Quaternion quat = bno.getQuat();
//check calibration
uint8_t sys, gyro, accel, mag = 0;
bno.getCalibration(&sys, &gyro, &accel, &mag);
if(sys>0){
sendData=true;
}
//assemble string and send over serial
if (sendData == true) {
/*
Serial.print(sys, DEC);
Serial.print(",");
Serial.print(gyro, DEC);
Serial.print(",");
Serial.print(accel, DEC);
Serial.print(",");
Serial.print(mag, DEC);
Serial.print(",");
*/
Serial.print('A'); //send a character to identify start of string
Serial.print(",");
//send values from position sensor
Serial.print(quat.x(), 4);
Serial.print(",");
Serial.print(quat.y(), 4);
Serial.print(",");
Serial.print(quat.z(), 4);
Serial.print(",");
Serial.print(quat.w(), 4);
Serial.print(",");
//send values from pressure sensors
Serial.print(data1);
Serial.print(",");
Serial.print(data2);
Serial.print(",");
Serial.print(data3);
Serial.print(",");
Serial.print(data4);
Serial.print(",");
Serial.print(data5);
Serial.print(",");
//send stroke sensor values
Serial.print(total1); //stroke sensor1
Serial.print(",");
Serial.print(total2); //stroke sensor2
Serial.print(",");
Serial.print(total3); //stroke sensor3
Serial.print(",");
Serial.print(bendValue);
Serial.print(",");
Serial.print(distance); // Send ping, get distance in cm and print result (0 = outside set distance range)
Serial.println();
//Serial.print("\n");
}
/* Also send calibration data for each sensor. */
// uint8_t sys, gyro, accel, mag = 0;
//bno.getCalibration(&sys, &gyro, &accel, &mag);
//Serial.println(mag, DEC);
/*
Serial.print(F("Calibration: "));
Serial.print(sys, DEC);
Serial.print(F(" "));
Serial.print(gyro, DEC);
Serial.print(F(" "));
Serial.print(accel, DEC);
Serial.print(F(" "));
Serial.println(mag, DEC);
*/
delay(BNO055_SAMPLERATE_DELAY_MS);
}
void getPressure() {
data1 = readDataFromSensor(i2cAddress1);
data2 = readDataFromSensor(i2cAddress2);
data3 = readDataFromSensor(i2cAddress3);
data4 = readDataFromSensor(i2cAddress4);
data5 = readDataFromSensor(i2cAddress5);
// data6 = readDataFromSensor(i2cAddress6);
}
short readDataFromSensor(short address)
{
byte i2cPacketLength = 6;//i2c packet length. Just need 6 bytes from each slave
byte outgoingI2CBuffer[3];//outgoing array buffer
byte incomingI2CBuffer[6];//incoming array buffer
outgoingI2CBuffer[0] = 0x01;//I2c read command
outgoingI2CBuffer[1] = 128;//Slave data offset
outgoingI2CBuffer[2] = i2cPacketLength;//require 6 bytes
Wire.beginTransmission(address); // transmit to device
Wire.write(outgoingI2CBuffer, 3);// send out command
byte error = Wire.endTransmission(); // stop transmitting and check slave status
if (error != 0) return -1; //if slave not exists or has error, return -1
Wire.requestFrom(address, i2cPacketLength);//require 6 bytes from slave
byte incomeCount = 0;
while (incomeCount < i2cPacketLength) // slave may send less than requested
{
if (Wire.available())
{
incomingI2CBuffer[incomeCount] = Wire.read(); // receive a byte as character
incomeCount++;
}
else
{
delayMicroseconds(10); //Wait 10us
}
}
short rawData = (incomingI2CBuffer[4] << 8) + incomingI2CBuffer[5]; //get the raw data
return rawData;
}
| [
"noreply@github.com"
] | noreply@github.com |
048ffdc680bcab826e2c4d0e94b3fddc7fd4d778 | b70cfed6b88d69ae2e398762207e60ea5d953f25 | /simon_says/simon_says.ino | 3d8d183d6feda822b2fa9ce9f756622dcb25a140 | [
"MIT"
] | permissive | davidtimmons/simon-says-circuit | f109acba66ffe712de8f1458e5492de1c92ee168 | 522f23a37cbca61e9812eeb6409997365c7df6b8 | refs/heads/master | 2020-04-09T09:28:25.878886 | 2019-10-25T20:08:11 | 2019-10-25T20:08:11 | 22,733,328 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,737 | ino | /**
* An Arduino circuit design and program that simulates the game "Simon Says".
*
* Author: David Timmons ( http://david.timmons.io )
* License: MIT
*/
// Turn debug mode on or off; this toggles serial monitor printing.
const boolean DEBUG = false;
// Define LED pin positions.
const int RED_1 = 13;
const int RED_2 = 12;
const int RED_3 = 11;
const int SIMON_1 = 5;
const int SIMON_2 = 4;
const int SIMON_3 = 3;
const int SIMON_4 = 2;
const int QTY = 7;
const int LEDS[QTY] = {RED_1, RED_2, RED_3, SIMON_1, SIMON_2, SIMON_3, SIMON_4};
// Define switch pin positions.
const int TILT = 10;
const int BUTTONS = A1;
// Define game settings.
const int LIGHT_DELAY = 700;
const int GAME_SPEED = 700;
const int TOTAL_LEVELS = 128;
const int TOTAL_LIVES = 3;
boolean gameStart = false;
/**
* Initialize the Arduino.
*/
void setup() {
// Print debug results to the serial monitor.
if (DEBUG) Serial.begin(9600);
// Set all LEDs to output mode.
for (int i = 0; i < QTY; i++) {
pinMode(LEDS[i], OUTPUT);
}
// Set tilt switch to input mode.
pinMode(TILT, INPUT);
}
/**
* Control the Arduino.
*/
void loop() {
// Cycle LEDs until the player starts a game while checking for game start.
while (!gameStart) {
playLightShow(); // The tilt switch starts a new game.
}
// Create a random "Simon Says" pattern.
int pattern[TOTAL_LEVELS];
for (int i = 0; i < TOTAL_LEVELS; i++) {
int num = 1 + random(4); // Random between [1, 4].
if (num == 1) pattern[i] = SIMON_1;
else if (num == 2) pattern[i] = SIMON_2;
else if (num == 3) pattern[i] = SIMON_3;
else pattern[i] = SIMON_4;
}
// Begin the game.
playGame(pattern);
// The game is over; turn off all lights and reset.
delay(LIGHT_DELAY);
gameStart = false;
for (int i = 0; i < QTY; i++) {
digitalWrite(LEDS[i], LOW);
}
}
/**
* Return the LED associated with the active button switch.
*
* Args:
* keyVal: an integer from 3 to 1023 containing the analog switch value.
*
* Return:
* The corresponding LED from among the colored game diodes.
*/
int getSimonLed(int keyVal) {
// Get the LED.
if (3 <= keyVal && keyVal <= 50) {
return SIMON_4;
} else if (500 <= keyVal && keyVal <= 550) {
return SIMON_3;
} else if (1000 <= keyVal && keyVal <= 1010) {
return SIMON_2;
} else if (keyVal >= 1020) {
return SIMON_1;
}
// The switch is not active.
return -1;
}
/**
* Run the "Simon Says" game.
*
* Args:
* *pattern: a pointer to an integer array containing the game LED pattern.
*/
void playGame(int *pattern) {
// Set game parameters then begin.
int lives = TOTAL_LIVES;
int currentLevel = 1;
while (gameStart && lives > 0 && currentLevel < TOTAL_LEVELS) {
// Display the pattern.
for (int lvl = 0; lvl < currentLevel; lvl++) {
// Blink the current pattern LED.
digitalWrite(pattern[lvl], HIGH);
delay(GAME_SPEED);
digitalWrite(pattern[lvl], LOW);
// Do not wait after blinking the final pattern LED.
if (lvl + 1 != currentLevel) delay(GAME_SPEED);
}
// Check player input.
if (verifyPlayerInput(pattern, currentLevel)) {
// Check for game reset.
if (digitalRead(TILT)) {
gameStart = false;
signalGameChange(1);
return;
}
// The player was correct; move to the next level.
currentLevel++;
delay(GAME_SPEED);
// The player was incorrect; subtract a life.
} else {
// Remove a life from the current total.
lives--;
// Turn on the next red LED.
if (lives == TOTAL_LIVES - 1) digitalWrite(RED_1, HIGH);
else if (lives == TOTAL_LIVES - 2) digitalWrite(RED_2, HIGH);
else if (lives == TOTAL_LIVES - 3) digitalWrite(RED_3, HIGH);
delay(LIGHT_DELAY);
}
}
}
/**
* Cycles LEDs on and off in a decorative pattern while waiting for game start.
*/
void playLightShow() {
// Cycle lights.
for (int i = 0; i < QTY; i++) {
// Get the last position in the array.
int last = QTY - 1 - i;
// Turn off previous lights.
if (i - 1 >= 0) {
digitalWrite(LEDS[i - 1], LOW);
digitalWrite(LEDS[last + 1], LOW);
}
// Turn on current lights.
digitalWrite(LEDS[i], HIGH);
digitalWrite(LEDS[last], HIGH);
// Check the tilt switch and buttons for a new game.
if (digitalRead(TILT) || analogRead(BUTTONS) > 3) {
gameStart = true;
signalGameChange(2);
return;
}
// Wait before cycling the next set of lights.
delay(LIGHT_DELAY);
}
// Turn off final LED pair.
digitalWrite(LEDS[0], LOW);
digitalWrite(LEDS[QTY-1], LOW);
}
/**
* Blinks all LEDs to signal a change in game state.
*
* Args:
* blinks: an integer containing the number of times to blink all LEDs.
*/
void signalGameChange(int blinks) {
for (int j = 0; j < blinks; j++) {
// Turn on all LEDs.
for (int k = 0; k < QTY; k++) {
digitalWrite(LEDS[k], HIGH);
}
delay(LIGHT_DELAY);
// Turn off all LEDs.
for (int k = 0; k < QTY; k++) {
digitalWrite(LEDS[k], LOW);
}
delay(LIGHT_DELAY * 2);
}
}
/**
* Determine whether the player successfully matched the pattern.
*
* Args:
* *pattern: a pointer to an integer array containing the game LED pattern.
* currentLevel: an integer specifying the current game level.
*
* Return:
* A boolean signaling whether the player correctly entered the current
* game pattern.
*/
boolean verifyPlayerInput(int *pattern, int currentLevel) {
// Get player input up through the current game level.
int lvl = 0;
while (lvl < currentLevel) {
// Wait for a button press.
int simonLed = -1;
while (simonLed == -1) {
// Check for game reset.
if (digitalRead(TILT)) return true;
// Check for a button press.
simonLed = getSimonLed(analogRead(BUTTONS));
}
// Blink the corresponding LED.
digitalWrite(simonLed, HIGH);
delay(GAME_SPEED);
digitalWrite(simonLed, LOW);
// Check if the button press was correct.
if (pattern[lvl] == simonLed) lvl++;
else return false;
}
// The player successfully matched the entire pattern.
return true;
}
| [
"github@timmons.io"
] | github@timmons.io |
3abb90e802ec477a53e6a79868bef1b2e7a907ef | 278e3b84e4e97524928c5d27099e64fa744d67ff | /GLES3Renderer/GLES3Renderer/GfxUniformCamera.h | eec8e914d5944d37fa9dc1d090471f2b79d00362 | [
"Apache-2.0"
] | permissive | LiangYue1981816/CrossEngine-GLES3Renderer | 8f4d47a8c247c4e78d4d34d9887bcd6bee5f2113 | 8d092307c22164895c4f92395ef291c87f2811e6 | refs/heads/master | 2020-03-18T01:44:22.512483 | 2018-08-02T03:04:08 | 2018-08-02T03:04:08 | 134,157,249 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 918 | h | #pragma once
#include "gles3/gl3.h"
#include "glm/glm.hpp"
class CGfxUniformBuffer;
class CGfxUniformCamera
{
private:
typedef struct Params {
glm::mat4 mtxProjection;
glm::mat4 mtxView;
glm::mat4 mtxViewInverse;
glm::mat4 mtxViewInverseTranspose;
} Params;
public:
CGfxUniformCamera(void);
virtual ~CGfxUniformCamera(void);
public:
void SetPerspective(float fovy, float aspect, float zNear, float zFar);
void SetOrtho(float left, float right, float bottom, float top, float zNear, float zFar);
void SetLookat(float eyex, float eyey, float eyez, float centerx, float centery, float centerz, float upx, float upy, float upz);
void SetProjectionMatrix(const float *mtxProjection);
void SetViewMatrix(const float *mtxView);
void Apply(void);
public:
GLuint GetSize(void) const;
GLuint GetBuffer(void) const;
private:
bool m_bDirty;
Params m_params;
CGfxUniformBuffer *m_pUniformBuffer;
};
| [
"LiangYue1981816@Hotmail.com"
] | LiangYue1981816@Hotmail.com |
f9de0f4c7d6517249fef656cd8c3437e9713216e | 1a4eb1d87a4aa50569eb1ab56260c53d6cbb1424 | /codechef solution/chef and churu.cpp | bd8fae2958f4517f01dd38c10029b2f34e3c3648 | [] | no_license | deepak216/codechef_solutions | 8ba4eacc4cf0188788a0ddba1c5aefb571cf5411 | 3cd951e0a5f0e9b0e6c1769d064c631754150a0f | refs/heads/master | 2016-09-03T06:59:22.928009 | 2014-12-09T02:43:23 | 2014-12-09T02:43:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,586 | cpp | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <math.h>
#define lld long long int
using namespace std;
int arr[1001];
lld tree[3000];
lld f[1001];
lld tree_f[3001];
struct range
{
int l,h;
}R[1001];
void build_tree(int node, int a, int b) {
if(a > b) {return ;}
if(a == b) {
tree[node] = (lld)arr[a];
return ;
}
build_tree(node*2+1, a, (a+b)/2);
build_tree(node*2+2, 1+(a+b)/2, b);
tree[node]=(lld)((lld)tree[node*2+1]+(lld)tree[node*2+2]);
}
lld query_tree(int node, int a, int b, int i, int j) {
if(a > b || a > j || b < i) return 0;
if(a >= i && b <= j)
return tree[node];
lld q1 = query_tree(node*2+1, a, (a+b)/2, i, j);
lld q2 = query_tree(2+node*2, 1+(a+b)/2, b, i, j);
return ((lld)((lld)q1+(lld)q2));
}
void build_tree_f(int node,int a,int b)
{
if(a > b) return ;
if(a == b) {
tree_f[node] = f[a];
return ;
}
build_tree_f(node*2+1, a, (a+b)/2);
build_tree_f(node*2+2, 1+(a+b)/2, b);
tree_f[node]=(lld)((lld)tree_f[node*2+1]+(lld)tree_f[node*2+2]);
}
void update_tree_f(int node,int a,int b,int i,int j,int value)
{
if(a > b || a > j || b < i)
return;
if(a == b) {
tree_f[node] +=(lld) (value);
return;
}
update_tree_f(node*2+1, a, (a+b)/2, i, j, value);
update_tree_f(2+node*2, 1+(a+b)/2, b, i, j, value);
tree_f[node]=(lld)((lld)tree_f[node*2+1]+(lld)tree_f[node*2+2]);
}
lld query_tree_f(int node,int a,int b,int i,int j)
{
if(a > b || a > j || b < i) return 0;
if(a >= i && b <= j)
return tree_f[node];
lld q1 = query_tree_f(node*2+1, a, (a+b)/2, i, j);
lld q2 = query_tree_f(2+node*2, 1+(a+b)/2, b, i, j);
return ((lld)((lld)q1+(lld)q2));
}
int main()
{
int n,m,i=0,a,b,q,s,t,u,k=0;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
m=n;
build_tree(0,0,n-1);
i=0;
while(m--)
{
scanf("%d %d",&a,&b);
a=a-1;b=b-1;
R[k].l=a;R[k].h=b;k++;
f[i]=query_tree(0,0,n-1,a,b);
//printf("%lld\n",f[i]);
i++;
}
build_tree_f(0,0,n-1);
scanf("%d",&q);
while(q--)
{
scanf("%d",&s);
if(s==1)
{
scanf("%d %d",&t,&u);
t=t-1;
//update_tree(0,0,n-1,t,t,u);
for(i=0;i<n;i++)
{
if(R[i].l<=t&&R[i].h>=t)
update_tree_f(0,0,n-1,i,i,u-arr[t]); // brute force in segment tree
}
//printf("\n%d\n",arr[t]);
arr[t]=u;
}
else
{
scanf("%d %d",&t,&u);
t=t-1;u=u-1;
printf("%lld\n",query_tree_f(0,0,n-1,t,u));
}
}
return 0;
}
| [
"deepaksingh21mps@gmail.com"
] | deepaksingh21mps@gmail.com |
be8501dbecc8063159be7cebb53769fa68d65ed1 | 5d68d80456e086afd133f2aaa047fcfd08bf44dc | /Laboratory/Lab04.0-TriangleVertexFragmentShaders/src/main.cpp | 4c1acf54f2a565acc81e9609f6feea0a3e642c95 | [] | no_license | hpaucar/computer-graphics-repo | 6a563436576fb51813aee6ec0ca0e22269eacbba | 0a438b88b9af13204781ced17e2f6da70b9bc329 | refs/heads/master | 2021-07-17T09:38:36.176226 | 2021-01-09T02:02:27 | 2021-01-09T02:02:27 | 230,563,579 | 13 | 4 | null | 2020-06-15T03:23:01 | 2019-12-28T05:33:38 | HTML | ISO-8859-1 | C++ | false | false | 7,778 | cpp | //============================================================================
// Name : Dibujo de Triangulo colorido
// Professor : Herminio Paucar
// Version :
// Description : Utilizamos los Vertex y Fragment Shaders
//============================================================================
// Include standard headers
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
// Include GLEW
#define GLEW_STATIC
#include <GL/glew.h>
// Include GLFW
#include <GLFW/glfw3.h>
#include <string>
#include <fstream>
GLuint renderingProgram;
GLfloat* m_Vertices;
GLuint m_VBO;
GLuint m_VAO;
using namespace std;
// displays the contents of OpenGL's log when GLSL compilation failed
void printShaderLog(GLuint shader) {
int len = 0;
int chWrittn = 0;
char* log;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &len);
if (len > 0) {
log = (char*)malloc(len);
glGetShaderInfoLog(shader, len, &chWrittn, log);
cout << "Shader Info Log: " << log << endl;
free(log);
}
}
// displays the contents of OpenGL's log when GLSL linking failed
void printProgramLog(int prog) {
int len = 0;
int chWrittn = 0;
char* log;
glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &len);
if (len > 0) {
log = (char*)malloc(len);
glGetProgramInfoLog(prog, len, &chWrittn, log);
cout << "Program Info Log: " << log << endl;
free(log);
}
}
// checks the OpenGL error flag for the occurrrence of an OpenGL error
// detects both GLSL compilation errors and OpenGL runtime errors
bool checkOpenGLError() {
bool foundError = false;
int glErr = glGetError();
while (glErr != GL_NO_ERROR) {
cout << "glError: " << glErr << endl;
foundError = true;
glErr = glGetError();
}
return foundError;
}
string readShaderSource(const char *filePath) {
string content = "";
ifstream fileStream(filePath, ios::in);
// cerr << "Error: " << strerror(errno) << endl; // No such file or directory
// cout << fileStream.is_open() << endl; // 0
string line = "";
while (!fileStream.eof()) {
getline(fileStream, line);
content.append(line + "\n");
}
fileStream.close();
return content;
}
GLuint createShaderProgram() {
GLint vertCompiled;
GLint fragCompiled;
GLint linked;
string vertShaderStr = readShaderSource("src/vertShader.glsl");
string fragShaderStr = readShaderSource("src/fragShader.glsl");
const char* vertShaderSrc = vertShaderStr.c_str();
const char* fragShaderSrc = fragShaderStr.c_str();
GLuint vShader = glCreateShader(GL_VERTEX_SHADER);
GLuint fShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(vShader, 1, &vertShaderSrc, NULL);
glShaderSource(fShader, 1, &fragShaderSrc, NULL);
glCompileShader(vShader);
checkOpenGLError();
glGetShaderiv(vShader, GL_COMPILE_STATUS, &vertCompiled);
if (vertCompiled != 1) {
cout << "vertex compilation failed" << endl;
printShaderLog(vShader);
}
glCompileShader(fShader);
checkOpenGLError();
glGetShaderiv(fShader, GL_COMPILE_STATUS, &fragCompiled);
if (fragCompiled != 1) {
cout << "fragment compilation failed" << endl;
printShaderLog(fShader);
}
GLuint vfProgram = glCreateProgram();
glAttachShader(vfProgram, vShader);
glAttachShader(vfProgram, fShader);
glLinkProgram(vfProgram);
checkOpenGLError();
glGetProgramiv(vfProgram, GL_LINK_STATUS, &linked);
if (linked != 1) {
cout << "linking failed" << endl;
printProgramLog(vfProgram);
}
return vfProgram;
}
void init () {
renderingProgram = createShaderProgram();
// The first 3 points are to Vertex position of Triangle
// The other 3 points are to Vertex color
m_Vertices = new GLfloat[18] {
-0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0,
0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f,
};
// Crea un ID en la GPU para un array de buffers
glGenVertexArrays(1, &m_VAO);
glBindVertexArray(m_VAO);
// Crea un ID en la GPU para nuestro buffer
glGenBuffers(1, &m_VBO);
glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
// Reserva memoria en la GPU para un TARGET recibir datos
// Copia esos datos para esa área de memoria
glBufferData(
GL_ARRAY_BUFFER, // TARGET asociado a nuestro buffer
18 * sizeof(GLfloat), // tamano del buffer
m_Vertices, // Datos a ser copiados para GPU
GL_STATIC_DRAW // Politica de acceso a los datos, para optimizacion
);
// En este punto ja copiamos nossos dados pra GPU.
// Mas, OpenGL nao faz ideia do que eles representam
// Sao 6 vértices ? 3 vérices e 3 cores ?
// Os vertices vem antes ou depois das cores ?
// Ou estão intercalados vértices depois cores, depois vertices, depois cores novamente....
// Precisamos dizer com nossos dados precisam ser interpretados:
glVertexAttribPointer(
0, // Lembra do (layout = 0 ) no vertex shader ? Esse valor indica qual atributo estamos indicando
3, // cada vertice é composto de 3 valores
GL_FLOAT, // cada valor do vértice é do tipo GLfloat
GL_FALSE, // Quer normalizar os dados e converter tudo pra NDC(Normalized Device Coordinates) ? ( no nosso caso, já esta tudo correto, então deixamos como FALSE)
6 * sizeof(GLfloat),// De quantos em quantos bytes, este atributo é encontrado no buffer ? No nosso caso 3 floats pros vertices + 3 floats pra cor = 6 floats
(GLvoid*) 0 // Onde está o primeiro valor deste atributo no buffer. Nesse caso, está no início do buffer
);
glEnableVertexAttribArray(0); // Habilita este atributo Layout 0
// Faremos a mesma coisa pra cor de cada vértice
glVertexAttribPointer(
1, // Lembra do (layout = 1 ) no vertex shader ? Esse valor indica qual atributo estamos indicando
3, // cada vertice é composto de 3 valores
GL_FLOAT, // cada valor do vértice é do tipo GLfloat
GL_FALSE, // Quer normalizar os dados e converter tudo pra NDC ? ( no nosso caso, já esta tudo correto, então deixamos como FALSE)
6 * sizeof(GLfloat),// De quantos em quantos bytes, este atributo é encontrado no buffer ? No nosso caso 3 floats pros vertices + 3 floats pra cor = 6 floats
(GLvoid*) (3 * sizeof(GLfloat)) // Onde está o primeiro valor deste atributo no buffer. Nesse caso, 3 floats após o início do buffer
);
glEnableVertexAttribArray(1); // Habilita este atributo Layout 1
}
void display(double currentTime) {
glUseProgram(renderingProgram);
// Use este VAO y sus configuraciones
glBindVertexArray(m_VAO);
glDrawArrays(GL_TRIANGLES, 0, 3);
//glPointSize(30);
//glDrawArrays(GL_POINTS, 0, 3);
}
int main(void) {
if (!glfwInit()) {
exit(EXIT_FAILURE);
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); //
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // Resizable option.
GLFWwindow* window = glfwCreateWindow(800, 800, "Lab04: Drawing Triangle with Shader", NULL, NULL);
glfwMakeContextCurrent(window);
if (glewInit() != GLEW_OK) {
exit(EXIT_FAILURE);
}
glfwSwapInterval(1);
init();
while (!glfwWindowShouldClose(window)) {
display(glfwGetTime());
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwDestroyWindow(window);
glfwTerminate();
exit(EXIT_SUCCESS);
}
| [
"herminiopaucar@gmail.com"
] | herminiopaucar@gmail.com |
9bf2e0980040b5dc8d1f519889e337fe036aaa1e | d1fb9cd6373ab9001ae5ce83cc85727ff7d41305 | /GardenMaintenanceApp/TaskList.cpp | a6066f36b63785a71453209605a56079fecbad9a | [] | no_license | koentie96/GardenMaintenanceApp | 3d731e2afe7f182c00fa45bc0ecaee37947af317 | acf9c29a705f5fa6921534fff94bcbab56a66c5d | refs/heads/master | 2020-07-29T22:28:45.081799 | 2019-09-21T16:41:52 | 2019-09-21T16:41:52 | 209,984,728 | 0 | 0 | null | 2019-09-21T16:41:54 | 2019-09-21T12:52:36 | C++ | UTF-8 | C++ | false | false | 53 | cpp | #include "TaskList.hpp"
//CTaskList::CTaskList() {}
| [
"gort.koen@gmail.com"
] | gort.koen@gmail.com |
dd1ef37c8c534e622b3d54a57d74208f194a4b5b | 3db023edb0af1dcf8a1da83434d219c3a96362ba | /windows_nt_3_5_source_code/NT-782/PRIVATE/UTILS/UHPFS/INC/DIRCACHE.HXX | 9219da1e6a695e0f421eb205759c2be05bb32ee5 | [] | no_license | xiaoqgao/windows_nt_3_5_source_code | de30e9b95856bc09469d4008d76191f94379c884 | d2894c9125ff1c14028435ed1b21164f6b2b871a | refs/heads/master | 2022-12-23T17:58:33.768209 | 2020-09-28T20:20:18 | 2020-09-28T20:20:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,022 | hxx | /*++
Copyright (c) 1990 Microsoft Corporation
Module Name:
dircache.hxx
Abstract:
Definitions for the HPFS DIRBLK cache object
Author:
Bill McJohn (billmc) 16-Jan-1989
Notes:
The DIRBLK cache is used by the Directory Tree object.
--*/
#if ! defined(DIRBLK_CACHE_DEFN)
#define DIRBLK_CACHE_DEFN
#include "dirblk.hxx"
//
// Forward references
//
DECLARE_CLASS( DIRBLK_CACHE_ELEMENT );
DECLARE_CLASS( DIRBLK_CACHE );
DECLARE_CLASS( HOTFIXLIST );
DECLARE_CLASS( LOG_IO_DP_DRIVE );
ULONG const DirblkCacheSize = 64;
class DIRBLK_CACHE_ELEMENT : public OBJECT {
public:
DECLARE_CONSTRUCTOR( DIRBLK_CACHE_ELEMENT );
VIRTUAL
~DIRBLK_CACHE_ELEMENT(
);
NONVIRTUAL
BOOLEAN
Initialize(
PLOG_IO_DP_DRIVE Drive,
PHOTFIXLIST HotfixList
);
NONVIRTUAL
BOOLEAN
Read(
LBN DirblkLbn,
BOOLEAN OmitRead
);
NONVIRTUAL
BOOLEAN
Flush(
);
NONVIRTUAL
LBN
QueryLbn(
);
NONVIRTUAL
PDIRBLK
GetDirblk(
);
NONVIRTUAL
VOID
Hold(
);
NONVIRTUAL
VOID
Unhold(
);
NONVIRTUAL
BOOLEAN
IsFree(
);
NONVIRTUAL
VOID
MarkModified(
);
private:
NONVIRTUAL
VOID
Construct (
);
NONVIRTUAL
VOID
Destroy(
);
BOOLEAN _IsUnused;
DIRBLK _Dirblk;
ULONG _HoldCount;
};
class DIRBLK_CACHE : public OBJECT {
public:
DECLARE_CONSTRUCTOR( DIRBLK_CACHE );
VIRTUAL
~DIRBLK_CACHE(
);
NONVIRTUAL
BOOLEAN
Initialize(
PLOG_IO_DP_DRIVE Drive,
PHOTFIXLIST HotfixList
);
NONVIRTUAL
BOOLEAN
Flush(
);
NONVIRTUAL
PDIRBLK_CACHE_ELEMENT
GetCachedDirblk(
LBN DirblkLbn,
BOOLEAN OmitRead = FALSE
);
NONVIRTUAL
GetDrive(
);
private:
NONVIRTUAL
VOID
Construct (
);
NONVIRTUAL
VOID
Destroy(
);
ULONG _NextVictim;
DIRBLK_CACHE_ELEMENT _Cache[DirblkCacheSize];
};
#endif
| [
"benjamin.barratt@icloud.com"
] | benjamin.barratt@icloud.com |
c251d4d3174f55405349bc3330d31230313375f9 | f95975d9454984803586de7f0600f3ecf9918f60 | /lang_service/java/com/intel/daal/algorithms/gbt/regression/prediction/predict_batch.cpp | 8ce8746c24b5c5f1afa28504f4b89e1729db6c9d | [
"Intel",
"Apache-2.0"
] | permissive | jjuribe/daal | f4e05656ca5f01e56debdbd2de51eeb2f506ca3d | 242d358db584dd4c9c65826b345fe63313ff8f2a | refs/heads/master | 2020-09-15T01:33:34.752543 | 2019-11-21T08:27:26 | 2019-11-21T08:27:26 | 223,316,648 | 0 | 0 | Apache-2.0 | 2019-11-22T03:33:41 | 2019-11-22T03:33:39 | null | UTF-8 | C++ | false | false | 2,286 | cpp | /* file: predict_batch.cpp */
/*******************************************************************************
* Copyright 2014-2019 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
#include "daal.h"
#include "com_intel_daal_algorithms_gbt_regression_prediction_PredictionBatch.h"
#include "common_helpers.h"
USING_COMMON_NAMESPACES()
namespace dfrp = daal::algorithms::gbt::regression::prediction;
/*
* Class: com_intel_daal_algorithms_gbt_regression_prediction_PredictionBatch
* Method: cInit
* Signature: (II)J
*/
JNIEXPORT jlong JNICALL Java_com_intel_daal_algorithms_gbt_regression_prediction_PredictionBatch_cInit
(JNIEnv *, jobject thisObj, jint prec, jint method)
{
return jniBatch<dfrp::Method, dfrp::Batch, dfrp::defaultDense>::newObj(prec, method);
}
/*
* Class: com_intel_daal_algorithms_gbt_regression_prediction_PredictionBatch
* Method: cInitParameter
* Signature: (JIII)J
*/
JNIEXPORT jlong JNICALL Java_com_intel_daal_algorithms_gbt_regression_prediction_PredictionBatch_cInitParameter
(JNIEnv *, jobject thisObj, jlong algAddr, jint prec, jint method, jint cmode)
{
return jniBatch<dfrp::Method, dfrp::Batch, dfrp::defaultDense>::getParameter(prec, method, algAddr);
}
/*
* Class: com_intel_daal_algorithms_gbt_regression_prediction_PredictionBatch
* Method: cClone
* Signature: (JII)J
*/
JNIEXPORT jlong JNICALL Java_com_intel_daal_algorithms_gbt_regression_prediction_PredictionBatch_cClone
(JNIEnv *, jobject thisObj, jlong algAddr, jint prec, jint method)
{
return jniBatch<dfrp::Method, dfrp::Batch, dfrp::defaultDense>::getClone(prec, method, algAddr);
}
| [
"nikolay.a.petrov@intel.com"
] | nikolay.a.petrov@intel.com |
74cec9d5c303dae777ed04c7e96bb5258ec6da6c | db8be521b8e2eab424f594a50886275d68dd5a1b | /Competitive Programming/codechef/Epiphany 2012/EPI02.cpp | 7f4c35570509e0ea3018fab4864900bd9924f76b | [] | no_license | purnimamehta/Articles-n-Algorithms | 7f2aa8046c8eef0e510689771a493f84707e9297 | aaea50bf1627585b935f8e43465360866b3b4eac | refs/heads/master | 2021-01-11T01:01:53.382696 | 2017-01-15T04:12:44 | 2017-01-15T04:12:44 | 70,463,305 | 10 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 238 | cpp | #include<stdio.h>
int main()
{
int N,n,i;
scanf("%d",&N);
i=1;
n=N;
while(n)
{
n>>=1;
i<<=1;
}
i>>=1;
int ans=((N-i)*2)+1;
printf("%d\n",ans);
return 0;
}
| [
"me@lefeeza.com"
] | me@lefeeza.com |
f1ca62fed563a5bf8c147c0e2c22d736cf6acbf0 | 9fdda17e5e3deb4dfbc31d557439102b15be2e3f | /src/test/rpc_tests.cpp | 31e821fc2c94919d6ab27253dac2ac5fcf3d5923 | [
"MIT"
] | permissive | bitcoinxash-network/bitcoinxash | 009656529e2ba44a876b25d0de944a9c805825ab | ba46c6f0d54f69fff26b826f82430dd6e6d2e91a | refs/heads/master | 2020-07-10T14:41:27.354149 | 2019-08-13T08:46:21 | 2019-08-13T08:46:21 | 204,287,949 | 0 | 0 | MIT | 2019-08-25T11:58:07 | 2019-08-25T11:58:07 | null | UTF-8 | C++ | false | false | 9,528 | cpp | // Copyright (c) 2012-2013 The Bitcoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpcserver.h"
#include "rpcclient.h"
#include "base58.h"
#include "netbase.h"
#include "test/test_bcx.h"
#include <boost/algorithm/string.hpp>
#include <boost/test/unit_test.hpp>
#include <univalue.h>
using namespace std;
UniValue
createArgs(int nRequired, const char* address1=nullptr, const char* address2=nullptr)
{
UniValue result(UniValue::VARR);
result.push_back(nRequired);
UniValue addresses(UniValue::VARR);
if (address1) addresses.push_back(address1);
if (address2) addresses.push_back(address2);
result.push_back(addresses);
return result;
}
UniValue CallRPC(string args)
{
vector<string> vArgs;
boost::split(vArgs, args, boost::is_any_of(" \t"));
string strMethod = vArgs[0];
vArgs.erase(vArgs.begin());
UniValue params = RPCConvertValues(strMethod, vArgs);
rpcfn_type method = tableRPC[strMethod]->actor;
try {
UniValue result = (*method)(params, false);
return result;
}
catch (const UniValue& objError) {
throw runtime_error(find_value(objError, "message").get_str());
}
}
BOOST_FIXTURE_TEST_SUITE(rpc_tests, TestingSetup)
BOOST_AUTO_TEST_CASE(rpc_rawparams)
{
// Test raw transaction API argument handling
UniValue r;
BOOST_CHECK_THROW(CallRPC("getrawtransaction"), runtime_error);
BOOST_CHECK_THROW(CallRPC("getrawtransaction not_hex"), runtime_error);
BOOST_CHECK_THROW(CallRPC("getrawtransaction a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed not_int"), runtime_error);
BOOST_CHECK_THROW(CallRPC("createrawtransaction"), runtime_error);
BOOST_CHECK_THROW(CallRPC("createrawtransaction null null"), runtime_error);
BOOST_CHECK_THROW(CallRPC("createrawtransaction not_array"), runtime_error);
BOOST_CHECK_THROW(CallRPC("createrawtransaction [] []"), runtime_error);
BOOST_CHECK_THROW(CallRPC("createrawtransaction {} {}"), runtime_error);
BOOST_CHECK_NO_THROW(CallRPC("createrawtransaction [] {}"));
BOOST_CHECK_THROW(CallRPC("createrawtransaction [] {} extra"), runtime_error);
BOOST_CHECK_THROW(CallRPC("decoderawtransaction"), runtime_error);
BOOST_CHECK_THROW(CallRPC("decoderawtransaction null"), runtime_error);
BOOST_CHECK_THROW(CallRPC("decoderawtransaction DEADBEEF"), runtime_error);
string rawtx = "0100000001a15d57094aa7a21a28cb20b59aab8fc7d1149a3bdbcddba9c622e4f5f6a99ece010000006c493046022100f93bb0e7d8db7bd46e40132d1f8242026e045f03a0efe71bbb8e3f475e970d790221009337cd7f1f929f00cc6ff01f03729b069a7c21b59b1736ddfee5db5946c5da8c0121033b9b137ee87d5a812d6f506efdd37f0affa7ffc310711c06c7f3e097c9447c52ffffffff0100e1f505000000001976a9140389035a9225b3839e2bbf32d826a1e222031fd888ac00000000";
BOOST_CHECK_NO_THROW(r = CallRPC(string("decoderawtransaction ")+rawtx));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "version").get_int(), 1);
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "locktime").get_int(), 0);
BOOST_CHECK_THROW(r = CallRPC(string("decoderawtransaction ")+rawtx+" extra"), runtime_error);
BOOST_CHECK_THROW(CallRPC("signrawtransaction"), runtime_error);
BOOST_CHECK_THROW(CallRPC("signrawtransaction null"), runtime_error);
BOOST_CHECK_THROW(CallRPC("signrawtransaction ff00"), runtime_error);
BOOST_CHECK_NO_THROW(CallRPC(string("signrawtransaction ")+rawtx));
BOOST_CHECK_NO_THROW(CallRPC(string("signrawtransaction ")+rawtx+" null null NONE|ANYONECANPAY"));
BOOST_CHECK_NO_THROW(CallRPC(string("signrawtransaction ")+rawtx+" [] [] NONE|ANYONECANPAY"));
BOOST_CHECK_THROW(CallRPC(string("signrawtransaction ")+rawtx+" null null badenum"), runtime_error);
// Only check failure cases for sendrawtransaction, there's no network to send to...
BOOST_CHECK_THROW(CallRPC("sendrawtransaction"), runtime_error);
BOOST_CHECK_THROW(CallRPC("sendrawtransaction null"), runtime_error);
BOOST_CHECK_THROW(CallRPC("sendrawtransaction DEADBEEF"), runtime_error);
BOOST_CHECK_THROW(CallRPC(string("sendrawtransaction ")+rawtx+" extra"), runtime_error);
}
BOOST_AUTO_TEST_CASE(rpc_rawsign)
{
/* TODO: Get correct parameters and reenable test */
/* For now skip check so test succeeds */
/*
UniValue r;
// input is a 1-of-2 multisig (so is output):
string prevout =
"[{\"txid\":\"dd2888870cdc3f6e92661f6b0829667ee4bb07ed086c44205e726bbf3338f726\","
"\"vout\":1,\"scriptPubKey\":\"a914f5404a39a4799d8710e15db4c4512c5e06f97fed87\","
"\"redeemScript\":\"5121021431a18c7039660cd9e3612a2a47dc53b69cb38ea4ad743b7df8245fd0438f8e21029bbeff390ce736bd396af43b52a1c14ed52c086b1e5585c15931f68725772bac52ae\"}]";
r = CallRPC(string("createrawtransaction ")+prevout+" "+
"{\"GPbEQ1hJxpJkWBDKMpc4y2KkugwuUaRUTY\":1}");
string notsigned = r.get_str();
string privkey1 = "\"YVobcS47fr6kceZy9LzLJR8WQ6YRpUwYKoJhrnEXepebMxaSpbnn\"";
string privkey2 = "\"YRyMjG8hbm8jHeDMAfrzSeHq5GgAj7kuHFvJtMudCUH3sCkq1WtA\"";
r = CallRPC(string("signrawtransaction ")+notsigned+" "+prevout+" "+"[]");
BOOST_CHECK(find_value(r.get_obj(), "complete").get_bool() == false);
r = CallRPC(string("signrawtransaction ")+notsigned+" "+prevout+" "+"["+privkey1+","+privkey2+"]");
BOOST_CHECK(find_value(r.get_obj(), "complete").get_bool() == true);
*/
}
BOOST_AUTO_TEST_CASE(rpc_format_monetary_values)
{
BOOST_CHECK(ValueFromAmount(0LL).write() == "0.00000000");
BOOST_CHECK(ValueFromAmount(1LL).write() == "0.00000001");
BOOST_CHECK(ValueFromAmount(17622195LL).write() == "0.17622195");
BOOST_CHECK(ValueFromAmount(50000000LL).write() == "0.50000000");
BOOST_CHECK(ValueFromAmount(89898989LL).write() == "0.89898989");
BOOST_CHECK(ValueFromAmount(100000000LL).write() == "1.00000000");
BOOST_CHECK(ValueFromAmount(2099999999999990LL).write() == "20999999.99999990");
BOOST_CHECK(ValueFromAmount(2099999999999999LL).write() == "20999999.99999999");
BOOST_CHECK_EQUAL(ValueFromAmount(0).write(), "0.00000000");
BOOST_CHECK_EQUAL(ValueFromAmount((COIN/10000)*123456789).write(), "12345.67890000");
BOOST_CHECK_EQUAL(ValueFromAmount(-COIN).write(), "-1.00000000");
BOOST_CHECK_EQUAL(ValueFromAmount(-COIN/10).write(), "-0.10000000");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN*100000000).write(), "100000000.00000000");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN*10000000).write(), "10000000.00000000");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN*1000000).write(), "1000000.00000000");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN*100000).write(), "100000.00000000");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN*10000).write(), "10000.00000000");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN*1000).write(), "1000.00000000");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN*100).write(), "100.00000000");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN*10).write(), "10.00000000");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN).write(), "1.00000000");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN/10).write(), "0.10000000");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN/100).write(), "0.01000000");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN/1000).write(), "0.00100000");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN/10000).write(), "0.00010000");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN/100000).write(), "0.00001000");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN/1000000).write(), "0.00000100");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN/10000000).write(), "0.00000010");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN/100000000).write(), "0.00000001");
}
static UniValue ValueFromString(const std::string &str)
{
UniValue value;
BOOST_CHECK(value.setNumStr(str));
return value;
}
BOOST_AUTO_TEST_CASE(rpc_parse_monetary_values)
{
BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.00000001")), 1LL);
BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.17622195")), 17622195LL);
BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.5")), 50000000LL);
BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.50000000")), 50000000LL);
BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.89898989")), 89898989LL);
BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("1.00000000")), 100000000LL);
BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("20999999.9999999")), 2099999999999990LL);
BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("20999999.99999999")), 2099999999999999LL);
}
BOOST_AUTO_TEST_CASE(json_parse_errors)
{
// Valid
BOOST_CHECK_EQUAL(ParseNonRFCJSONValue("1.0").get_real(), 1.0);
// Valid, with leading or trailing whitespace
BOOST_CHECK_EQUAL(ParseNonRFCJSONValue(" 1.0").get_real(), 1.0);
BOOST_CHECK_EQUAL(ParseNonRFCJSONValue("1.0 ").get_real(), 1.0);
// Invalid, initial garbage
BOOST_CHECK_THROW(ParseNonRFCJSONValue("[1.0"), std::runtime_error);
BOOST_CHECK_THROW(ParseNonRFCJSONValue("a1.0"), std::runtime_error);
// Invalid, trailing garbage
BOOST_CHECK_THROW(ParseNonRFCJSONValue("1.0sds"), std::runtime_error);
BOOST_CHECK_THROW(ParseNonRFCJSONValue("1.0]"), std::runtime_error);
// BTC addresses should fail parsing
BOOST_CHECK_THROW(ParseNonRFCJSONValue("175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W"), std::runtime_error);
BOOST_CHECK_THROW(ParseNonRFCJSONValue("3J98t1WpEZ73CNmQviecrnyiWrnqRhWNL"), std::runtime_error);
}
BOOST_AUTO_TEST_SUITE_END()
| [
"admin@bitcoinxash.com"
] | admin@bitcoinxash.com |
214fccbc301c2c24232540448bf6618fe62b6d07 | ff7352ce3d77498fbc8dbebcb03149ee9753d30d | /yatagarasu/pkg/savepkg/savepkg.cpp | a94346e8b0938534e0d97ae0fda9a50221475412 | [] | no_license | number201724/GalGameTools | c519f76dc6282b94c0f1e18ffc1c6fa6f79972ee | 2619af12c8b391fa7b7d288d76f82deb6f1e8014 | refs/heads/master | 2022-07-07T23:03:17.788827 | 2017-07-04T16:38:13 | 2017-07-04T16:38:13 | 67,941,925 | 38 | 12 | null | null | null | null | GB18030 | C++ | false | false | 5,757 | cpp | // savepkg.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
extern "C"
{
#include "writestream.h"
};
typedef unsigned int uint;
typedef unsigned char byte;
typedef struct pkg_header_s
{
uint file_size;
uint file_count;
}pkg_header_t;
typedef struct pkg_file_s
{
char file_name[116];
uint file_size;
uint file_offset;
uint file_offset_high;
}pkg_file_t;
uint xor_key_buffer[] =
{
0xA13BB527,
0x879FDA11,
0x72FDADBC,
0x1004A4D3,
0x03A0FFB2,
0x21CC32BA,
0x973A2B1C,
0xF7E8E667,
/*0x00006425,
0x30727563,
0x7275632E,
0x00000000,
0x30727563,
0x75632E31,
0x00000072,
0x48727563,
0x2E646E61,
0x00696E61,
0x4F525245,
0x00000052,
0x63656843,
0x7469426B,
0x61727241,
0x81C58279,
0x977A9441,
0x92F082F1,
0x82A682B4,
0x837283E9,
0x92678362,
0x8EF0826C,
0x82C68F51,
0x00BD82B5,
0x4F525245,
0x00000052,
0x42746553,
0x72417469,
0x82796172,
0x944181C5,
0x82F1977A,
0x82B492F0,
0x83E982A6,
0x83628372,
0x826C9267,
0x92778EF0,
0x82B582E8,
0x000000BD,
0x00000000,
0x00000000*/
};
int CovtShiftJISToGB(const char* JISStr, char* GBBuf, int nSize)
{
static wchar_t wbuf[2048];
int nLen;
nLen = strlen(JISStr)+1;
if (wbuf==NULL) return 0;
nLen = MultiByteToWideChar(932, 0, JISStr,
nLen, wbuf, nLen);
if (nLen > 0)
nLen = WideCharToMultiByte(936, 0, wbuf,
nLen, GBBuf, nSize, NULL, 0);
return nLen;
}
int CovtGbkToShiftJIS(const char* JISStr, char* GBBuf, int nSize)
{
static wchar_t wbuf[2048];
int nLen;
nLen = strlen(JISStr)+1;
if (wbuf==NULL) return 0;
nLen = MultiByteToWideChar(936, 0, JISStr,
nLen, wbuf, nLen);
if (nLen > 0)
nLen = WideCharToMultiByte(932, 0, wbuf,
nLen, GBBuf, nSize, NULL, 0);
return nLen;
}
write_stream_t index_list;
FILE* pTmpFile;
void init_temp_file()
{
char szTempFileName[MAX_PATH];
GetCurrentDirectory(sizeof(szTempFileName),szTempFileName);
strcat(szTempFileName,"\\cache.tmp");
DeleteFile(szTempFileName);
pTmpFile = fopen(szTempFileName,"wb+");
fseek(pTmpFile,0,SEEK_SET);
}
unsigned int write_to_temp_file(unsigned char* buf,size_t size)
{
int offs;
offs = ftell(pTmpFile);
fwrite(buf,size,1,pTmpFile);
return offs;
}
void free_temp_file()
{
char szTempFileName[MAX_PATH];
fclose(pTmpFile);
GetCurrentDirectory(sizeof(szTempFileName),szTempFileName);
strcat(szTempFileName,"\\cache.tmp");
DeleteFile(szTempFileName);
}
uint get_file_size(FILE* fp)
{
uint size;
if(fp==NULL)
{
return 0;
}
fseek( fp, 0L, SEEK_END );
size=ftell(fp);
fseek( fp, 0L, SEEK_SET );
return size;
}
void xor_buf(byte* buf,uint size)
{
uint key_max = 0;
key_max = (size >> 2) & 7;
for(uint i=0;i<size;i+=4)
{
*(DWORD*)(buf+i) ^= xor_key_buffer[(i / 4) & key_max];
}
}
void xor_index(byte* buf)
{
for(uint xor_count = 0;xor_count < (sizeof(pkg_file_t)/4);xor_count++)
{
((DWORD*)buf)[xor_count] ^= xor_key_buffer[xor_count & 7];
}
}
bool pack_to_data(char* disk_file_name,char* pack_name)
{
pkg_file_t pkg_item;
FILE* f;
uint file_size;
byte* file_buf;
f = fopen(disk_file_name,"rb");
if(f)
{
printf("packet file:%s\n",pack_name);
file_size = get_file_size(f);
file_buf = new byte[file_size+10];
if(fread(file_buf,1,file_size,f)!=file_size)
abort();
xor_buf(file_buf,file_size);
CovtGbkToShiftJIS(pack_name,pkg_item.file_name,sizeof(pkg_item.file_name));
pkg_item.file_size = file_size;
pkg_item.file_offset_high = 0;
pkg_item.file_offset = write_to_temp_file(file_buf,file_size+10);
WS_WriteBytes(&index_list,(byte*)&pkg_item,sizeof(pkg_item));
fclose(f);
return true;
}
return false;
}
void fix_index_offset()
{
pkg_file_t * pkg_item;
uint addin_offset = sizeof(pkg_header_t) + index_list.size;
uint listsize = index_list.size / sizeof(pkg_file_t);
for(uint i=0;i<listsize;i++)
{
pkg_item = (pkg_file_t*)(index_list.buf + i*sizeof(pkg_file_t));
pkg_item->file_offset += addin_offset;
xor_index((byte*)pkg_item);
}
}
int main(int argc, char* argv[])
{
WIN32_FIND_DATA findData;
HANDLE hFind;
char szTmpFileName[MAX_PATH];
char szDirectory[MAX_PATH];
char szPackDirectory[MAX_PATH];
char szPackfileName[MAX_PATH];
pkg_header_t file_header;
uint data_size;
uint file_size;
FILE* f;
byte* m_buf;
int filecount;
GetCurrentDirectory(sizeof(szDirectory),szDirectory);
strcpy(szPackfileName,szDirectory);
strcpy(szPackDirectory,szDirectory);
strcat(szPackDirectory,"\\output\\*.*");
strcat(szPackfileName,"\\new.pkg");
WS_Init(&index_list);
init_temp_file();
f = fopen(szPackfileName,"wb+");
if(!f)
{
printf("Can't Create new file!\n");
return 0;
}
hFind = FindFirstFileA(szPackDirectory,&findData);
if(hFind == INVALID_HANDLE_VALUE)
{
return 0;
}
filecount = 0;
do
{
if(!(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
strcpy(szTmpFileName,szDirectory);
strcat(szTmpFileName,"\\output\\");
strcat(szTmpFileName,findData.cFileName);
if(pack_to_data(szTmpFileName,findData.cFileName))
{
filecount++;
}
}
}while(FindNextFile(hFind,&findData));
data_size = get_file_size(pTmpFile);
file_size = data_size + index_list.size + sizeof(file_header);
fix_index_offset();
file_header.file_count = filecount ^ 0xA13BB527;
file_header.file_size = file_size ^ 0xA13BB527;
//写入文件头
fwrite(&file_header,sizeof(file_header),1,f);
//写入索引文件
fwrite(index_list.buf,index_list.size,1,f);
m_buf = (byte*)malloc(10240000);
fseek( pTmpFile, 0L, SEEK_SET );
uint length;
do
{
length = fread(m_buf,1,10240000,pTmpFile);
if(length)
{
fwrite(m_buf,length,1,f);
}
}while(length);
fclose(f);
free(m_buf);
free_temp_file();
WS_Release(&index_list);
return 0;
}
| [
"number201724@me.com"
] | number201724@me.com |
38ddd0b1fff17eaabe117f2a591e667202135ea3 | 6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849 | /sstd_boost/sstd/boost/property_map/parallel/unsafe_serialize.hpp | a3692cdbbf2361da26fca6c074d07bb310ab617b | [
"BSL-1.0"
] | permissive | KqSMea8/sstd_library | 9e4e622e1b01bed5de7322c2682539400d13dd58 | 0fcb815f50d538517e70a788914da7fbbe786ce1 | refs/heads/master | 2020-05-03T21:07:01.650034 | 2019-04-01T00:10:47 | 2019-04-01T00:10:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,705 | hpp | // Copyright (C) 2006 The Trustees of Indiana University.
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Authors: Douglas Gregor
// Andrew Lumsdaine
// This file contains the "unsafe_serialize" routine, which transforms
// types they may not be serializable (such as void*) into
// serializable equivalents.
#ifndef BOOST_PROPERTY_MAP_UNSAFE_SERIALIZE_HPP
#define BOOST_PROPERTY_MAP_UNSAFE_SERIALIZE_HPP
#include <sstd/boost/mpi/datatype.hpp>
#include <sstd/boost/serialization/is_bitwise_serializable.hpp>
#include <sstd/boost/mpl/bool.hpp>
#include <sstd/boost/mpl/if.hpp>
#include <sstd/boost/cstdint.hpp>
#include <sstd/boost/static_assert.hpp>
#include <sstd/boost/type_traits.hpp>
#include <utility>
BOOST_IS_BITWISE_SERIALIZABLE(void*)
namespace boost { namespace mpi {
template<> struct is_mpi_datatype<void*> : mpl::true_ { };
} } // end namespace boost::mpi
namespace boost {
typedef mpl::if_c<(sizeof(int) == sizeof(void*)),
int,
mpl::if_c<(sizeof(long) == sizeof(void*)),
long,
mpl::if_c<(sizeof(void*) <= sizeof(boost::intmax_t)),
boost::intmax_t,
void>::type
>::type
>::type ptr_serialize_type;
BOOST_STATIC_ASSERT ((!boost::is_void<ptr_serialize_type>::value));
template<typename T> inline T& unsafe_serialize(T& x) { return x; }
inline ptr_serialize_type& unsafe_serialize(void*& x)
{ return reinterpret_cast<ptr_serialize_type&>(x); }
// Force Boost.MPI to serialize a void* like a ptr_serialize_type
namespace mpi {
template<> inline MPI_Datatype get_mpi_datatype<void*>(void* const& x)
{
return get_mpi_datatype<ptr_serialize_type>();
}
}
template<typename T, typename U>
struct unsafe_pair
{
unsafe_pair() { }
unsafe_pair(const T& t, const U& u) : first(t), second(u) { }
unsafe_pair(const std::pair<T, U>& p) : first(p.first), second(p.second) { }
T first;
U second;
template<typename Archiver>
void serialize(Archiver& ar, const unsigned /*version*/)
{
ar & unsafe_serialize(first) & unsafe_serialize(second);
}
};
template<typename T, typename U>
bool operator<(unsafe_pair<T,U> const& x, unsafe_pair<T,U> const& y)
{
return std::make_pair(x.first, x.second) <
std::make_pair(y.first, y.second);
}
} // end namespace boost
#endif // BOOST_PROPERTY_MAP_UNSAFE_SERIALIZE_HPP
| [
"zhaixueqiang@hotmail.com"
] | zhaixueqiang@hotmail.com |
33e2e9863883c995afa827a356b61102e139cf82 | 45645fd8c0836f239e59bb09f2a022a57c031c17 | /GMAT-R2019aBeta1/src/base/spice/SpiceOrbitKernelWriter.cpp | 19f0f4a674e2a5a29de5033c24a210012f0367a4 | [
"Apache-2.0"
] | permissive | daniestevez/gmat-dslwp-source | 03678e983f814ed1dcfb41079813e1da9bad2a6e | 9f02f6f94e2188161b624cd3d818a9b230c65845 | refs/heads/master | 2022-10-07T07:05:03.266744 | 2020-06-06T13:32:41 | 2020-06-06T13:32:41 | 260,881,226 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 30,016 | cpp | //$Id:$
//------------------------------------------------------------------------------
// SpiceOrbitKernelWriter
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool.
//
// Copyright (c) 2002 - 2018 United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All Other 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.
//
// Developed jointly by NASA/GSFC and Thinking Systems, Inc. under
// FDSS Task order 28.
//
// Author: Wendy C. Shoan
// Created: 2009.12.07
//
/**
* Implementation of the SpiceOrbitKernelWriter, which writes SPICE data (kernel) files.
*
* This code creates a temporary text file, required in order to include META-Data
* (commentary) in the SPK file. The file is deleted from the system after the
* commentary is added to the SPK file. The name of this temporary text file
* takes the form
* GMATtmpSPKcmmnt<objName>.txt
* where <objName> is the name of the object for whom the SPK file is created
*
* If the code is unable to create the temporary file (e.g., because of a permission
* problem), the SPK file will still be generated but will contain no META-data.
*
*/
//------------------------------------------------------------------------------
#include <stdio.h>
#include <sstream>
#include "SpiceOrbitKernelWriter.hpp"
#include "SpiceInterface.hpp"
#include "MessageInterface.hpp"
#include "StringUtil.hpp"
#include "TimeTypes.hpp"
#include "TimeSystemConverter.hpp"
#include "UtilityException.hpp"
#include "RealUtilities.hpp"
#include "FileUtil.hpp"
//#define DEBUG_SPK_WRITING
//#define DEBUG_SPK_INIT
//#define DEBUG_SPK_KERNELS
//---------------------------------
// static data
//---------------------------------
std::string SpiceOrbitKernelWriter::TMP_TXT_FILE_NAME = "GMATtmpSPKcmmnt";
const Integer SpiceOrbitKernelWriter::MAX_FILE_RENAMES = 1000; // currently unused
//---------------------------------
// public methods
//---------------------------------
//------------------------------------------------------------------------------
// SpiceOrbitKernelWriter(const std::string &objName,
// const std::string ¢erName,
// Integer objNAIFId,
// Integer centerNAIFId,
// const std::string &fileName,
// Integer deg,
// const std::string &frame = "J2000",
// bool renameExistingSPK = false)
//------------------------------------------------------------------------------
/**
* This method constructs a SpiceKernelWriter instance.
* (constructor)
*
* @param objName name of the object for which to write the SPK kernel
* @param centerName name of he central body of the object
* @param objNAIFId NAIF ID for the object
* @param centerNAIFId NAIF ID for the central body
* @param fileName name of the kernel to generate
* @param deg degree of interpolating polynomials
* @param frame reference frame (default = "J2000")
* @param renameSPK rename existing SPK file(s) with same name?
* [true = rename; false = overwrite]
*
*/
//------------------------------------------------------------------------------
SpiceOrbitKernelWriter::SpiceOrbitKernelWriter(const std::string &objName, const std::string ¢erName,
Integer objNAIFId, Integer centerNAIFId,
const std::string &fileName, Integer deg,
const std::string &frame, bool renameExistingSPK) :
SpiceKernelWriter(),
objectName (objName),
centralBodyName (centerName),
kernelFileName (fileName),
frameName (frame),
fileOpen (false),
fileFinalized (false),
dataWritten (false),
tmpTxtFile (NULL),
tmpFileOK (false),
appending (false),
fm (NULL),
renameSPK (renameExistingSPK)
{
#ifdef DEBUG_SPK_INIT
MessageInterface::ShowMessage(
"Entering constructor for SPKOrbitWriter with fileName = %s, objectName = %s, "
"centerName = %s\n",
fileName.c_str(), objName.c_str(), centerName.c_str());
#endif
if (GmatMathUtil::IsEven(deg)) // degree must be odd for Data Type 13
{
std::string errmsg = "Error creating SpiceOrbitKernelWriter: degree must be odd for Data Type 13\n";
throw UtilityException(errmsg);
}
// Check for the default NAIF ID
if (objNAIFId == SpiceInterface::DEFAULT_NAIF_ID)
{
MessageInterface::ShowMessage(
"*** WARNING *** NAIF ID for object %s is set to the default NAIF ID (%d). Resulting SPK file will contain that value as the object's ID.\n",
objectName.c_str(), objNAIFId);
}
// Get the FileManage pointer
fm = FileManager::Instance();
// Create the temporary text file to hold the meta data
tmpTxtFileName = fm->GetAbsPathname(FileManager::OUTPUT_PATH);
tmpTxtFileName += TMP_TXT_FILE_NAME + objectName + ".txt";
#ifdef DEBUG_SPK_INIT
MessageInterface::ShowMessage("temporary SPICE file name is: %s\n", tmpTxtFileName.c_str());
#endif
tmpTxtFile = fopen(tmpTxtFileName.c_str(), "w");
if (!tmpTxtFile)
{
std::string errmsg = "Error creating or opening temporary text file for SPK meta data, for object \"";
errmsg += objectName + "\". No meta data will be added to the file.\n";
MessageInterface::PopupMessage(Gmat::WARNING_, errmsg);
tmpFileOK = false;
}
else
{
fclose(tmpTxtFile);
// remove the temporary text file
remove(tmpTxtFileName.c_str());
tmpFileOK = true;
}
/// set up CSPICE data
objectNAIFId = objNAIFId;
if (centerNAIFId == 0) // need to find the NAIF Id for the central body @todo - for object too??
centralBodyNAIFId = GetNaifID(centralBodyName);
else
centralBodyNAIFId = centerNAIFId;
kernelNameSPICE = kernelFileName.c_str();
degree = deg;
referenceFrame = frameName.c_str();
handle = -999;
// first, try to rename an existing file, as SPICE will not overwrite or
// append to an existing file - this is the most common error returned from spkopn
if (GmatFileUtil::DoesFileExist(kernelFileName))
{
if (renameSPK)
{
#ifdef DEBUG_SPK_INIT
MessageInterface::ShowMessage(
"SPKOrbitWriter: the file %s exists, will need to rename ... \n",
kernelFileName.c_str());
#endif
Integer fileCounter = 0;
bool done = false;
std::string fileWithBSP = fileName;
std::string fileNoBSP = fileWithBSP.erase(fileWithBSP.rfind(".bsp"));
std::stringstream fileRename("");
Integer retCode = 0;
while (!done)
{
fileRename.str("");
fileRename << fileNoBSP << "__" << fileCounter << ".bsp";
#ifdef DEBUG_SPK_INIT
MessageInterface::ShowMessage(
"SPKOrbitWriter: renaming %s to %s ... \n",
kernelFileName.c_str(), fileRename.str().c_str());
#endif
if (fm->RenameFile(kernelFileName, fileRename.str(), retCode))
{
done = true;
}
else
{
if (retCode == 0) // if no error from system, but not allowed to overwrite
{
// if (fileCounter < MAX_FILE_RENAMES) // no MAX for now
fileCounter++;
// else
// {
// reset_c(); // reset failure flag in SPICE
// std::string errmsg = "Error renaming existing SPK file \"";
// errmsg += kernelFileName + "\". Maximum number of renames exceeded.\n";
// throw UtilityException(errmsg);
// }
}
else
{
// reset_c(); // reset failure flag in SPICE
std::string errmsg =
"Unknown system error occurred when attempting to rename existing SPK file \"";
errmsg += kernelFileName + "\".\n";
throw UtilityException(errmsg);
}
}
}
}
else
{
// delete the file
remove(kernelFileName.c_str());
}
}
else // otherwise, check to make sure the directory is writable
{
std::string dirName = GmatFileUtil::ParsePathName(kernelFileName, true);
if (dirName == "")
dirName = "./";
if (!GmatFileUtil::DoesDirectoryExist(dirName, true))
{
std::string errmsg =
"Directory \"";
errmsg += dirName + "\" does not exist.\n";
throw UtilityException(errmsg);
}
}
// set up the "basic" meta data here ...
SetBasicMetaData();
// make sure that the NAIF Id is associated with the object name @todo - need to set center's Id as well sometimes?
ConstSpiceChar *itsName = objectName.c_str();
boddef_c(itsName, objectNAIFId); // CSPICE method to set NAIF ID for an object
if (failed_c())
{
ConstSpiceChar option[] = "LONG"; // retrieve long error message
SpiceInt numErrChar = MAX_LONG_MESSAGE_VALUE;
//SpiceChar err[MAX_LONG_MESSAGE_VALUE];
SpiceChar *err = new SpiceChar[MAX_LONG_MESSAGE_VALUE];
getmsg_c(option, numErrChar, err);
std::string errStr(err);
std::stringstream ss("");
ss << "Unable to set NAIF Id for object \"" << objectName << "\" to the value ";
ss << objNAIFId << ". Message received from CSPICE is: ";
ss << errStr << std::endl;
reset_c();
delete [] err;
throw UtilityException(ss.str());
}
}
//------------------------------------------------------------------------------
// SpiceOrbitKernelWriter(const SpiceOrbitKernelWriter ©)
//------------------------------------------------------------------------------
/**
* This method constructs a SpiceKernelWriter instance, copying data from the
* input instance.
* (copy constructor)
*
* @param copy object to copy
*
*/
//------------------------------------------------------------------------------
SpiceOrbitKernelWriter::SpiceOrbitKernelWriter(const SpiceOrbitKernelWriter ©) :
SpiceKernelWriter(copy),
objectName (copy.objectName),
centralBodyName (copy.centralBodyName),
kernelFileName (copy.kernelFileName),
frameName (copy.frameName),
objectNAIFId (copy.objectNAIFId),
centralBodyNAIFId (copy.centralBodyNAIFId),
degree (copy.degree),
handle (copy.handle),
basicMetaData (copy.basicMetaData),
addedMetaData (copy.addedMetaData),
fileOpen (copy.fileOpen), // ??
fileFinalized (copy.fileFinalized),
dataWritten (copy.dataWritten),
tmpTxtFile (copy.tmpTxtFile),
tmpFileOK (copy.tmpFileOK),
appending (copy.appending),
fm (copy.fm),
renameSPK (copy.renameSPK)
{
kernelNameSPICE = kernelFileName.c_str();
referenceFrame = frameName.c_str();
}
//------------------------------------------------------------------------------
// SpiceOrbitKernelWriter& operator=(const SpiceOrbitKernelWriter ©)
//------------------------------------------------------------------------------
/**
* This method copies data from the input SpiceKernelWriter instance to
* "this" instance.
*
* @param copy object whose data to copy
*
*/
//------------------------------------------------------------------------------
SpiceOrbitKernelWriter& SpiceOrbitKernelWriter::operator=(const SpiceOrbitKernelWriter ©)
{
if (© != this)
{
SpiceKernelWriter::operator=(copy);
objectName = copy.objectName;
centralBodyName = copy.centralBodyName;
kernelFileName = copy.kernelFileName;
frameName = copy.frameName;
objectNAIFId = copy.objectNAIFId;
centralBodyNAIFId = copy.centralBodyNAIFId;
degree = copy.degree;
handle = copy.handle;
basicMetaData = copy.basicMetaData;
addedMetaData = copy.addedMetaData;
fileOpen = copy.fileOpen; // ??
fileFinalized = copy.fileFinalized;
dataWritten = copy.dataWritten;
tmpTxtFile = copy.tmpTxtFile; // ??
tmpFileOK = copy.tmpFileOK;
appending = copy.appending;
fm = copy.fm;
renameSPK = copy.renameSPK;
kernelNameSPICE = kernelFileName.c_str();
referenceFrame = frameName.c_str();
}
return *this;
}
//------------------------------------------------------------------------------
// ~SpiceOrbitKernelWriter()
//------------------------------------------------------------------------------
/**
* This method deletes "this" SpiceKernelWriter instance.
* (destructor)
*
*/
//------------------------------------------------------------------------------
SpiceOrbitKernelWriter::~SpiceOrbitKernelWriter()
{
if (!dataWritten)
{
// MessageInterface::ShowMessage(
// "*** WARNING *** SPK kernel %s not written - no data provided\n",
// kernelFileName.c_str());
}
FinalizeKernel();
}
//------------------------------------------------------------------------------
// SpiceOrbitKernelWriter* Clone(void) const
//------------------------------------------------------------------------------
/**
* This method clones the object.
*
* @return new object, cloned from "this" object.
*
*/
//------------------------------------------------------------------------------
SpiceOrbitKernelWriter* SpiceOrbitKernelWriter::Clone(void) const
{
SpiceOrbitKernelWriter * clonedSKW = new SpiceOrbitKernelWriter(*this);
return clonedSKW;
}
//------------------------------------------------------------------------------
// void WriteSegment(const A1Mjd &start, const A1Mjd &end,
// const StateArray &states, const EpochArray &epochs)
//------------------------------------------------------------------------------
/**
* This method writes a segment to the SPK kernel.
*
* @param start start time of the segment data
* @param end end time of the segment data
* @param states array of states to write to the segment
* @param epochs array or corresponding epochs
*
*/
//------------------------------------------------------------------------------
void SpiceOrbitKernelWriter::WriteSegment(const A1Mjd &start, const A1Mjd &end,
const StateArray &states, const EpochArray &epochs)
{
#ifdef DEBUG_SPK_KERNELS
MessageInterface::ShowMessage("In SOKW::WriteSegment, start = %12.10, end = %12.10\n",
start.Get(), end.Get());
MessageInterface::ShowMessage(" writing %d states\n", (Integer) states.size());
MessageInterface::ShowMessage(" fileOpen = %s\n", (fileOpen? "true": "false"));
#endif
// If the file has not been set up yet, open it
if (!fileOpen)
OpenFileForWriting();
SpiceInt numStates = states.size();
if ((Integer) epochs.size() != (Integer) numStates)
{
std::string errmsg = "Error writing segment to SPK file \"";
errmsg += kernelFileName + "\" - size of epoch array does not match size of state array.\n";
throw UtilityException(errmsg);
}
// do time conversions here, for start, end, and all epochs
SpiceDouble startSPICE = A1ToSpiceTime(start.Get());
SpiceDouble endSPICE = A1ToSpiceTime(end.Get());
#ifdef DEBUG_SPK_WRITING
MessageInterface::ShowMessage("In WriteSegment, epochs are:\n");
#endif
SpiceDouble *epochArray; // (deleted at end of method)
epochArray = new SpiceDouble[numStates];
for (Integer ii = 0; ii < numStates; ii++)
{
epochArray[ii] = A1ToSpiceTime(epochs.at(ii)->Get());
#ifdef DEBUG_SPK_WRITING
MessageInterface::ShowMessage("epochArray[%d] = %12.10f\n", ii, (Real) epochArray[ii]);
#endif
}
// put states into SpiceDouble arrays
SpiceDouble *stateArray;
stateArray = new SpiceDouble[numStates * 6];
for (Integer ii = 0; ii < numStates; ii++)
{
for (Integer jj = 0; jj < 6; jj++)
{
stateArray[(ii*6) + jj] = ((states.at(ii))->GetDataVector())[jj];
}
}
// create a segment ID
std::string segmentID = "SPK_SEGMENT";
ConstSpiceChar *segmentIDSPICE = segmentID.c_str();
// pass data to CSPICE method that writes a segment to a Data Type 13 kernel
spkw13_c(handle, objectNAIFId, centralBodyNAIFId, referenceFrame, startSPICE,
endSPICE, segmentIDSPICE, degree, numStates, stateArray, epochArray);
if(failed_c())
{
ConstSpiceChar option[] = "LONG"; // retrieve long error message
SpiceInt numErrChar = MAX_LONG_MESSAGE_VALUE;
//SpiceChar err[MAX_LONG_MESSAGE_VALUE];
SpiceChar *err = new SpiceChar[MAX_LONG_MESSAGE_VALUE];
getmsg_c(option, numErrChar, err);
std::string errStr(err);
std::string errmsg = "Error writing ephemeris data to SPK file \"";
errmsg += kernelFileName + "\". Message received from CSPICE is: ";
errmsg += errStr + "\n";
reset_c();
delete [] err;
throw UtilityException(errmsg);
}
dataWritten = true;
#ifdef DEBUG_SPK_KERNELS
MessageInterface::ShowMessage("In SOKW::WriteSegment, data has been written\n");
#endif
delete [] epochArray;
delete [] stateArray;
}
//------------------------------------------------------------------------------
// void AddMetaData(const std::string &line, bool done)
//------------------------------------------------------------------------------
/**
* This method writes meta data (comments) to the SPK kernel.
*
* @param line line of comments to add.
* @param bool indicates whether or not this is the last line to add
* (if so, file can be finalized)
*/
//------------------------------------------------------------------------------
void SpiceOrbitKernelWriter::AddMetaData(const std::string &line, bool done)
{
if (fileFinalized)
{
std::string errmsg = "Unable to add meta data to SPK kernel \"";
errmsg += kernelFileName + "\". File has been finalized and closed.\n";
throw UtilityException(errmsg);
}
addedMetaData.push_back(line);
if (done)
FinalizeKernel();
}
//------------------------------------------------------------------------------
// void AddMetaData(const StringArray &lines, bool done)
//------------------------------------------------------------------------------
/**
* This method writes meta data (comments) to the SPK kernel.
*
* @param lines lines of comments to add.
* @param bool indicates whether or not this is the last line to add
* (if so, file can be finalized)
*/
//------------------------------------------------------------------------------
void SpiceOrbitKernelWriter::AddMetaData(const StringArray &lines, bool done)
{
if (fileFinalized)
{
std::string errmsg = "Unable to add meta data to SPK kernel \"";
errmsg += kernelFileName + "\". File has been finalized and closed.\n";
throw UtilityException(errmsg);
}
unsigned int sz = lines.size();
for (unsigned int ii = 0; ii < sz; ii++)
addedMetaData.push_back(lines.at(ii));
if (done)
FinalizeKernel();
}
//---------------------------------
// protected methods
//---------------------------------
// none at this time
//---------------------------------
// private methods
//---------------------------------
//------------------------------------------------------------------------------
// SetBasicMetaData()
//------------------------------------------------------------------------------
/**
* This method sets the 'basic' (i.e. written to every kernel) meta data
* (comments).
*
*/
//------------------------------------------------------------------------------
void SpiceOrbitKernelWriter::SetBasicMetaData()
{
basicMetaData.clear();
std::string metaDataLine = "--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---\n";
basicMetaData.push_back(metaDataLine);
metaDataLine = ("SPK EPHEMERIS kernel for object " + objectName) + "\n";
basicMetaData.push_back(metaDataLine);
metaDataLine = "Generated on ";
metaDataLine += GmatTimeUtil::FormatCurrentTime();
metaDataLine += "\n";
basicMetaData.push_back(metaDataLine);
metaDataLine = "Generated by the General Mission Analysis Tool (GMAT) [Build ";
metaDataLine += __DATE__;
metaDataLine += " at ";
metaDataLine += __TIME__;
metaDataLine += "]\n";
basicMetaData.push_back(metaDataLine);
metaDataLine = "--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---\n";
basicMetaData.push_back(metaDataLine);
}
//------------------------------------------------------------------------------
// FinalizeKernel(bool done = true, writeMetaData = true)
//------------------------------------------------------------------------------
/**
* This method writes the meta data (comments) to the kernel and then closes it.
*
*/
//------------------------------------------------------------------------------
void SpiceOrbitKernelWriter::FinalizeKernel(bool done, bool writeMetaData)
{
#ifdef DEBUG_SPK_WRITING
MessageInterface::ShowMessage("In FinalizeKernel .... tmpFileOK = %s\n",
(tmpFileOK? "true" : "false"));
MessageInterface::ShowMessage("In FinalizeKernel .... kernelFileName = %s\n",
kernelFileName.c_str());
MessageInterface::ShowMessage("In FinalizeKernel .... fileOpen = %s\n",
(fileOpen? "true": "false"));
MessageInterface::ShowMessage("In FinalizeKernel .... dataWritten = %s\n",
(dataWritten? "true": "false"));
#endif
if ((fileOpen) && (dataWritten)) // should be both or neither are true
{
// write all the meta data to the file
if (tmpFileOK && (done || writeMetaData)) WriteMetaData();
#ifdef DEBUG_SPK_WRITING
MessageInterface::ShowMessage("In SOKW::FinalizeKernel ... is it loaded? %s\n",
(IsLoaded(kernelFileName)? "true" : "false"));
#endif
// close the SPK file
spkcls_c(handle);
if (failed_c())
{
ConstSpiceChar option[] = "SHORT"; // retrieve short error message, for now
SpiceInt numChar = MAX_SHORT_MESSAGE;
//SpiceChar err[MAX_SHORT_MESSAGE];
SpiceChar *err = new SpiceChar[MAX_SHORT_MESSAGE];
getmsg_c(option, numChar, err);
// This should no longer occur as the method WriteDataToClose is called to
// write 'bogus' data to a segment, if no segment has been written before.
if (eqstr_c(err, "SPICE(NOSEGMENTSFOUND)"))
{
MessageInterface::ShowMessage(
"SPICE cannot close a kernel (%s) with no segments.\n",
kernelFileName.c_str());
}
reset_c();
delete [] err;
}
}
if (done)
{
basicMetaData.clear();
addedMetaData.clear();
fileFinalized = true;
appending = false;
}
else
{
appending = true;
}
fileOpen = false;
}
//------------------------------------------------------------------------------
// Integer GetMinNumberOfStates()
//------------------------------------------------------------------------------
/**
* This method returns the minimum number if states required by SPICE to
* so the interpolation.
*
*/
//------------------------------------------------------------------------------
Integer SpiceOrbitKernelWriter::GetMinNumberOfStates()
{
return degree+1;
}
//------------------------------------------------------------------------------
// WriteMetaData()
//------------------------------------------------------------------------------
/**
* This method writes the meta data (comments) to the kernel.
*
*/
//------------------------------------------------------------------------------
void SpiceOrbitKernelWriter::WriteMetaData()
{
// open the temporary file for writing the metadata
tmpTxtFile = fopen(tmpTxtFileName.c_str(), "w");
// write the meta data to the temporary file (according to SPICE documentation, must use regular C routines)
// close the temporary file, when done
unsigned int basicSize = basicMetaData.size();
unsigned int addedSize = addedMetaData.size();
for (unsigned int ii = 0; ii < basicSize; ii++)
fprintf(tmpTxtFile, "%s", (basicMetaData[ii]).c_str());
fprintf(tmpTxtFile,"\n");
for (unsigned int ii = 0; ii < addedSize; ii++)
fprintf(tmpTxtFile, "%s", (addedMetaData[ii]).c_str());
fprintf(tmpTxtFile,"\n");
fflush(tmpTxtFile);
fclose(tmpTxtFile);
// write the meta data to the SPK file comment area by telling it to read the
// temporary text file
Integer txtLength = tmpTxtFileName.length();
// char tmpTxt[txtLength+1]; // MSVC doesn't like this allocation
char *tmpTxt; // (deleted at end of method)
tmpTxt = new char[txtLength + 1];
for (Integer jj = 0; jj < txtLength; jj++)
tmpTxt[jj] = tmpTxtFileName.at(jj);
tmpTxt[txtLength] = '\0';
integer unit;
char blank[2] = " ";
ftnlen txtLen = txtLength + 1;
txtopr_(tmpTxt, &unit, txtLen); // CSPICE method to open text file for reading
spcac_(&handle, &unit, blank, blank, 1, 1); // CSPICE method to write comments to kernel
if (failed_c())
{
ConstSpiceChar option[] = "LONG"; // retrieve long error message
SpiceInt numErrChar = MAX_LONG_MESSAGE_VALUE;
//SpiceChar err[MAX_LONG_MESSAGE_VALUE];
SpiceChar *err = new SpiceChar[MAX_LONG_MESSAGE_VALUE];
getmsg_c(option, numErrChar, err);
std::string errStr(err);
std::string errmsg = "Error writing meta data to SPK file \"";
errmsg += kernelFileName + "\". Message received from CSPICE is: ";
errmsg += errStr + "\n";
reset_c();
delete [] err;
throw UtilityException(errmsg);
}
// close the text file
ftncls_c(unit); // CSPICE method to close the text file
// remove the temporary text file
remove(tmpTxtFileName.c_str());
delete [] tmpTxt;
}
//------------------------------------------------------------------------------
// bool OpenFileForWriting()
//------------------------------------------------------------------------------
/**
* This method sets up and opens the file for writing.
*
*/
//------------------------------------------------------------------------------
bool SpiceOrbitKernelWriter::OpenFileForWriting()
{
// get a file handle here
SpiceInt maxChar = MAX_CHAR_COMMENT;
#ifdef DEBUG_SPK_INIT
MessageInterface::ShowMessage("... attempting to open SPK file with fileName = %s\n",
kernelFileName.c_str());
MessageInterface::ShowMessage("... and appending = %s\n", (appending? "true" : "false"));
MessageInterface::ShowMessage(" handle = %d\n", (Integer) handle);
#endif
bool fileExists = GmatFileUtil::DoesFileExist(kernelFileName);
if (appending && fileExists)
spkopa_c(kernelNameSPICE, &handle);
else
{
std::string internalFileName = "GMAT-generated SPK file for " + objectName;
ConstSpiceChar *internalSPKName = internalFileName.c_str();
spkopn_c(kernelNameSPICE, internalSPKName, maxChar, &handle); // CSPICE method to create and open an SPK kernel
}
if (failed_c()) // CSPICE method to detect failure of previous call to CSPICE
{
ConstSpiceChar option[] = "LONG"; // retrieve long error message
SpiceInt numErrChar = MAX_LONG_MESSAGE_VALUE;
//SpiceChar err[MAX_LONG_MESSAGE_VALUE];
SpiceChar *err = new SpiceChar[MAX_LONG_MESSAGE_VALUE];
getmsg_c(option, numErrChar, err);
std::string errStr(err);
std::string errmsg = "Error getting file handle for SPK file \"";
errmsg += kernelFileName + "\". Message received from CSPICE is: ";
errmsg += errStr + "\n";
reset_c();
delete [] err;
throw UtilityException(errmsg);
}
fileOpen = true;
return true;
}
//---------------------------------
// private methods
//---------------------------------
//------------------------------------------------------------------------------
// SpiceOrbitKernelWriter()
//------------------------------------------------------------------------------
/**
* This method constructs an instance of SpiceOrbitKernelWriter.
* (default constructor)
*
*/
//------------------------------------------------------------------------------
SpiceOrbitKernelWriter::SpiceOrbitKernelWriter()
{
};
| [
"daniel@destevez.net"
] | daniel@destevez.net |
857954738377be02b66c860c3cff4cb7e69ff7d6 | 0c7e20a002108d636517b2f0cde6de9019fdf8c4 | /Sources/Elastos/External/conscrypt/inc/org/conscrypt/COpenSSLX509CertificateFactory.h | d627388d91981edea2bce189e71f20fda6ffe0e7 | [
"Apache-2.0"
] | permissive | kernal88/Elastos5 | 022774d8c42aea597e6f8ee14e80e8e31758f950 | 871044110de52fcccfbd6fd0d9c24feefeb6dea0 | refs/heads/master | 2021-01-12T15:23:52.242654 | 2016-10-24T08:20:15 | 2016-10-24T08:20:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 487 | h |
#ifndef __ORG_CONSCRYPT_COPENSSLX509CERTIFICATEFACTORY_H__
#define __ORG_CONSCRYPT_COPENSSLX509CERTIFICATEFACTORY_H__
#include "_Org_Conscrypt_COpenSSLX509CertificateFactory.h"
#include "OpenSSLX509CertificateFactory.h"
namespace Org {
namespace Conscrypt {
CarClass(COpenSSLX509CertificateFactory)
, public OpenSSLX509CertificateFactory
{
public:
CAR_OBJECT_DECL()
};
} // namespace Conscrypt
} // namespace Org
#endif //__ORG_CONSCRYPT_COPENSSLX509CERTIFICATEFACTORY_H__
| [
"zhang.yu@kortide.com"
] | zhang.yu@kortide.com |
2bfde93b4b0cf728dd1a0ee6c628102f803ef2f1 | 0084c6a9973b2f484c6cbe57d77929bd42a7d2fc | /deprecated/kfsst/kfsst/source/azimuth.cpp | b2e98591e7fc54a47a0b143eddf8350b9b8674e3 | [] | no_license | positioning/kalmanfilter | db680c7e9cfd8c6edcbab6d1f12a44e153a149ff | 501ec9a28ae05802287aadcf8ca2cfb9229137cb | refs/heads/master | 2023-02-10T00:36:28.576957 | 2023-01-29T13:16:15 | 2023-01-29T13:16:15 | 40,897,081 | 12 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 2,099 | cpp | #include <fvar.hpp>
#include <iostream>
#include <cmath>
const double eps = 1e-8; //small number to avoid divide by 0
dvariable azimuth(const dvariable& y, const dvariable& x)
{
//dvariable z = 180.0*atan(y/(x+eps))/M_PI;
//dvariable d = 90.0 - z;
dvariable d = 90.0 - 180.0*atan(y/(x+eps))/M_PI;
if (x < 0.0)
d += 180;
if (d < 0.0)
d+=360.0;
return(d);
}
double azimuth(const double& y, const double& x)
{
//double z = 180.0*atan(y/(x+eps))/M_PI;
//double d = 90.0 - z;
double d = 90.0 - 180.0*atan(y/(x+eps))/M_PI;
if (x < 0.0)
d += 180;
if (d < 0.0)
d+=360.0;
return(d);
}
dvariable gc_dist(const dvector& y1, const dvar_vector y2)
{
double G1r = y1(1)/180.0*M_PI+1e-8;
double L1r = y1(2)/180.0*M_PI+1e-8;
dvariable G2r = y2(1)/180.0*M_PI+1e-8;
dvariable L2r = y2(2)/180.0*M_PI+1e-8;
dvariable DGr = (y2(1)-y1(1))/180.0*M_PI;
//double DGC1 = 1.852 * 60 * acos(sin(L1r)*sin(L2r) + cos(L1r)*cos(L2r)*cos(DGr))*180/M_PI;
dvariable DGC1 = 60 * acos(sin(L1r)*sin(L2r) + cos(L1r)*cos(L2r)*cos(DGr))*180/M_PI;
return(DGC1);
}
//#define TEST_CODE
#ifdef TEST_CODE
int main(void)
{
gradient_structure gs;
double u,v;
double L1,L2,G1,G2;
dvariable du, dv;
dvector v1(1,2);
dvar_vector v2(1,2);
while (1)
{
/*
cout << "\nEnter u,v: ";
cin >> u >> v;
double chdg = azimuth(v,u);
cout << "cHeading = " << chdg << endl;
du = u;
dv = v;
dvariable dhdg = azimuth(dv,du);
cout << "dHeading = " << dhdg << endl;
*/
cout << "\nEnter L1 G1: ";
cin >> L1 >> G1;
v1(1) = G1;
v1(2) = L1;
cout << "Enter L2 G2: ";
cin >> L2 >> G2;
v2(1) = G2;
v2(2) = L2;
dvariable D = gc_dist(v1,v2);
cout << "Great circle distance from (" << L1 << "," << G1 << ") to (" << L2 << "," << G2 << ") = " << D << " Nmi" << endl;
cout << "Great circle distance from (" << L1 << "," << G1 << ") to (" << L2 << "," << G2 << ") = " << (1.852 * D) << " km" << endl;
}
exit(0);
}
#endif
#undef TEST_CODE
| [
"fishfollower@77a56499-bf6e-355e-e284-15a721bbdb98"
] | fishfollower@77a56499-bf6e-355e-e284-15a721bbdb98 |
b91e2a440d4690a2ce0b39d9a553c96ded1ea999 | 05e79c064879c73b501f51110ee822b694bbe0c7 | /LCA.cpp | e39a60cda32c3b99ca7d6c1ee42cdeb3831fef7e | [] | no_license | AnUnluckyGuy/Code | 5baea1178e222b3f9eba57abb86c2e93eb9c9996 | bc17d692d5e8be827dad972cdf5e8b6d06a4a182 | refs/heads/main | 2023-01-12T08:04:13.276464 | 2020-11-14T14:50:18 | 2020-11-14T14:50:18 | 312,822,850 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,539 | cpp | #include<bits/stdc++.h>
using namespace std;
const int maxn=1e6;
int n,k,u,v,h[maxn]/*do cao*/,T[maxn]/*cha truc tiep*/,p[maxn][20];
vector<int> a[maxn];
void DFS(int u)
{
for(int v:a[u])
{
if(T[v]==-1)
{
T[v]=u;
h[v]=h[u]+1;
DFS(v);
}
}
}
void START()
{
fi>>n>>k;
for(int i=1;i<n;++i)
{
fi>>u>>v;
a[u].push_back(v);
a[v].push_back(u);
}
}
void Prepare()
{
memset(T,-1,sizeof(T));
T[1]=0;h[1]=1;
DFS(1);
memset(p,-1,sizeof(p));
for(int i=1;i<=n;++i)p[i][0]=T[i];//cha thu 2^0 cua i(cha truc tiep)
for(int j=1;1<<j<=n;++j)
{
for(int i=1;i<=n;++i)
{
if(p[i][j-1]!=-1)p[i][j]=p[p[i][j-1]][j-1];
//cha thu 2^j cua i
}
}
}
void NEXT()
{
for(int i=1;i<=k;++i)
{
cin>>u>>v;
if(h[u]<h[v])swap(u,v);
int log=log2(h[u]);
for(int j=log;j>=0;--j)
{
if((h[u]-(1<<j))>=h[v])u=p[u][j];
}
if(u==v)fo<<u<<'\n';
else
{
for(int j=log;j>=0;--j)
{
if(p[u][j]!=-1 && p[u][j]!=p[v][j])
{
u=p[u][j];
v=p[v][j];
}
}
fo<<T[u]<<'\n';
}
}
}
int main()
{
cin>>n>>k;
//nhap cac dg di
Prepare();
NEXT();
}
| [
"noreply@github.com"
] | noreply@github.com |
5bd27cdbf783184c14a2eca2cae6916006a595d5 | 2be8bc6cdf871d97dc4bc356212f6d0c43e0c5c0 | /laba2/Factory.cpp | dcaef1473225fc1aba06aab577ed57154f209c25 | [] | no_license | Cpt0bvious/labs-for-OOP | 7e63dd2d072970ce1aa3b22bdd4a14e47651839e | 126fe91cd730fa7210ad43e0529618ab6e431115 | refs/heads/master | 2020-06-04T19:49:32.609069 | 2019-06-18T18:27:47 | 2019-06-18T18:27:47 | 192,168,265 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,745 | cpp | // Factory.cpp
#include <iostream>
#include "Factory.h"
#include "Menu.h"
#include "SymbString.h"
#include "HexString.h"
#include "OctString.h"
using namespace std;
#define MAX_LEN_STR 100
void Factory:: AddObject() {
int item;
while (true) {
cout << "******************* \n";
cout << "Select object type:\n";
cout << "1. Symbolic string" << endl;
cout << "2. Octal number" << endl;
item = Menu::SelectItem(2);
if (item > 0 && item <= 2) { // условие корректного ввода пункта меню
break;
} else {
cin.get();
}
}
string name;
cout << "Enter object name: ";
cin >> name;
cin.get();
cout << "Enter object value: ";
char buf[MAX_LEN_STR];
cin.getline(buf, MAX_LEN_STR);
string value = buf;
AString* pNewObj;
switch (item) {
case 1:
pNewObj = new SymbString(name, value);
break;
case 2:
if (!IsOctStrVal(value)) {
cout << "Error!" << endl;
return;
}
pNewObj = new OctString(name, value);
break;
}
pObj.push_back(pNewObj);
cout << "Object added." << endl;
}
void Factory::DeleteObject() {
int nItem = pObj.size();
if (!nItem) {
cout << "There are no objects." << endl;
cin.get();
return;
}
int item;
do {
cout << " \n";
cout << "Delete one of the following Object:\n";
for (int i = 0; i < nItem; ++i)
cout << i + 1 << ". " << pObj[i]->GetName() << endl;
item = Menu::SelectItem(nItem);
} while (!(item > 0 && item <= nItem)); // условие корректного ввода номера объекта
string ObjName = pObj[item - 1]->GetName();
pObj.erase(pObj.begin() + item - 1);
cout << "Object " << ObjName << " deleted." << endl;
cin.get();
}
| [
"noreply@github.com"
] | noreply@github.com |
7dd3edb2fbba9664e166881f8918e4a87c1b2b6c | 3f6ce862ed6e693f9251d31dfeda6b16006f8a6a | /gba/src-gba/GBAMode3Framebuffer.hpp | ff52d34bc336e5e68d43a89216593f308c2c318e | [] | no_license | Pwootage/softrend | a7f8e9cd17fab65d0f1ab79bbbd630d87d4bd9cd | 46bd33e864fa032ca390d7e491be885725a96afe | refs/heads/master | 2021-06-06T17:38:00.589253 | 2020-05-16T22:49:40 | 2020-05-16T22:49:40 | 121,485,979 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 708 | hpp | #ifndef SOFTREND_GBAMODE5FRAMEBUFFER_HPP
#define SOFTREND_GBAMODE5FRAMEBUFFER_HPP
#include "../src/buffers/Framebuffer.hpp"
class GBAMode3Framebuffer : public softrend::Framebuffer {
public:
GBAMode3Framebuffer();
void putPixel(softrend::fb_pos_t pos, softrend::color_t color, float depth) override;
void clear(const softrend::color_t &clearColor, bool colorBuffer, bool depthBuffer) override;
softrend::color_t getPixel(const softrend::fb_pos_t &pos) const override;
float getDepth(softrend::fb_pos_t pos) const override;
softrend::fb_pos_t getWidth() const override;
softrend::fb_pos_t getHeight() const override;
float *depthBuffer;
};
#endif //SOFTREND_GBAMODE5FRAMEBUFFER_HPP
| [
"pwootage@gmail.com"
] | pwootage@gmail.com |
92980201bb679a9e515833322b8a36606d741cbc | b39446a01e5270c983614000f36ed7776c37fd5a | /code_snippets/Chapter14/chapter.14.1.2.no-link.cpp | 1465151aac08620cd2d3742c6e465115619e33c3 | [
"MIT"
] | permissive | ltr01/stroustrup-ppp-1 | aa6e063e11b1dccab854602895e85bef876f2ea5 | d9736cc67ef8e2f0483003c8ec35cc0785460cd1 | refs/heads/master | 2023-01-03T09:16:13.399468 | 2020-10-28T10:41:25 | 2020-10-28T10:41:25 | 261,959,252 | 1 | 0 | MIT | 2020-05-07T05:38:23 | 2020-05-07T05:38:22 | null | UTF-8 | C++ | false | false | 1,216 | cpp |
//
// This is example code from Chapter 14.1.2 "Operations" of
// "Programming -- Principles and Practice Using C++" by Bjarne Stroustrup
//
#include "Simple_window.h" // get access to our window library
#include "Graph.h" // get access to our graphics library facilities
//------------------------------------------------------------------------------
void draw_line(Point p1, Point p2); // from p1 to p2 (our style)
void draw_line(int x1, int y1, int x2, int y2); // from (x1,y1) to (x2,y2)
void draw_rectangle(Point p, int w, int h);
void draw_rectangle(int x, int y, int w, int h);
//------------------------------------------------------------------------------
int main()
try
{
Line ln(Point(100,200),Point(300,400));
Mark m(Point(100,200),'x'); // display a single point as an 'x'
Circle c(Point(200,200),250);
draw_rectangle(Point(100,200), 300, 400); // our style
draw_rectangle (100,200,300,400); // alternative
}
catch(exception& e) {
// some error reporting
return 1;
}
catch(...) {
// some more error reporting
return 2;
}
//------------------------------------------------------------------------------
| [
"bewuethr@users.noreply.github.com"
] | bewuethr@users.noreply.github.com |
b98460637125af8627715c149c7edbb0bd3048da | b1ec5452ac46b20b0adc1117ebafae7ee7dc9782 | /work/advcpp/SmartHome/ServerComponents/ConfigurationHandler.cpp | 3a104957e1c11083fde3dd1b2464dce569393da0 | [] | no_license | MishaLivshitz/experis | bce65d9d7a457fc48492105d51f4a9e51ef3ae88 | 038fe5e5a318ed11c595bce6654ff11ac7fbb355 | refs/heads/master | 2020-07-31T13:33:47.318537 | 2019-09-24T14:13:52 | 2019-09-24T14:13:52 | 210,619,343 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,425 | cpp | #include "ConfigurationHandler.h"
#include <iostream>
#include <string>
#include <sstream>
namespace ServerComponents{
using advcpp::SharedPtr;
using SmartHomeDevice::DeviceConfig;
ConfigurationHandler::ConfigurationHandler(char const* fileName) throw (MyException)
: m_file(fileName)
{
if(!m_file.is_open())
{
std::string s = "cannot open file: ";
throw EXCEPTION(MyException,s + fileName + '\n');
}
createConfigs();
}
ConfigurationHandler::Configs const& ConfigurationHandler::configs() const
{
return m_configs;
}
void ConfigurationHandler::createConfigs()
{
std::stringstream str;
std::string id;
std::string room;
std::string floorStr;
std::string type;
std::string config;
while(!m_file.eof())
{
while(id.empty())
{
getline(m_file, id);
}
getline(m_file, type);
getline(m_file, room);
getline(m_file, floorStr);
getline(m_file, config);
type.replace(0,type.find("= ",0,1) + 2,"");
room.replace(0,room.find("= ",0,1) + 2,"");
floorStr.replace(0,floorStr.find("= ",0,1) + 2,"");
config.replace(0,config.find("= ",0,1) + 2,"");
m_configs.push_back(SharedPtr<DeviceConfig>(new DeviceConfig(id, room, atoi(floorStr.c_str()), type, config)));
id.clear();
config.clear();
}
}
}// ServerComponents | [
"michaellivshitz91@gmail.com"
] | michaellivshitz91@gmail.com |
41e46f29396c63a07b63f824714b3321d13bee61 | 996b63336053a9a18c3ca2ba977655015e6789da | /432.cpp | 08d2393adb780d6e01b80fe5526d8a011c720b8e | [] | no_license | birdmanwings/Leetcode400 | d8ce028f1f49e5901e2a8245b0118e440fe65173 | 02b69bb24f9450e27c90d7a2a578e15053e20536 | refs/heads/master | 2021-07-24T05:52:00.888441 | 2020-08-11T08:30:00 | 2020-08-11T08:30:00 | 207,059,723 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,802 | cpp | //
// Created by bdwms on 2020/7/5.
//
#include <string>
#include <unordered_set>
#include <list>
#include <unordered_map>
using namespace std;
class AllOne {
public:
/** Initialize your data structure here. */
AllOne() {
}
/** Inserts a new key <Key> with value 1. Or increments an existing key by 1. */
void inc(string key) {
if (!m.count(key)) { // 如果不存在这个key,分为两种情况
if (l.empty() || l.back().val != 1) { // 一种是l为空,或者不存在val为1的这种情况,那么就要新建val=1的Bucket了
auto newBucket = l.insert(l.end(), {1, {key}});
m[key] = newBucket;
} else { // 存在val=1的Bucket,那么直接将key加入
l.back().keys.insert(key);
m[key] = --l.end();
}
} else {
auto curBucket = m[key], lastBucket = (--m[key]);
if (lastBucket == l.end() || lastBucket->val != curBucket->val + 1) { // 如果不存在 key + 1的Bucket,需要新建它
auto newBucket = l.insert(curBucket, {curBucket->val + 1, {key}});
m[key] = newBucket;
} else {
lastBucket->keys.insert(key);
m[key] = lastBucket;
}
curBucket->keys.erase(key); // 从原来的Bucket中删除key
if (curBucket->keys.empty()) { // 如果Bucket为空了,从list中删除
l.erase(curBucket);
}
}
}
/** Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */
void dec(string key) {
if (!m.count(key)) return;
auto curBucket = m[key];
if (curBucket->val == 1) { // val=1的时候需要删除key,key空了就需要删除Bucket了
curBucket->keys.erase(key);
if (curBucket->keys.empty()) l.erase(curBucket);
m.erase(key);
return;
}
auto nextBucket = ++m[key];
if (nextBucket == l.end() || nextBucket->val != curBucket->val - 1) {
auto newBucket = l.insert(nextBucket, {curBucket->val - 1, {key}});
m[key] = newBucket;
} else {
nextBucket->keys.insert(key);
m[key] = nextBucket;
}
curBucket->keys.erase(key);
if (curBucket->keys.empty()) l.erase(curBucket);
}
/** Returns one of the keys with maximal value. */
string getMaxKey() {
return l.empty() ? "" : *(l.begin()->keys.begin());
}
/** Returns one of the keys with Minimal value. */
string getMinKey() {
return l.empty() ? "" : *(l.rbegin()->keys.begin());
}
private:
struct Bucket {
int val;
unordered_set<string> keys;
};
list<Bucket> l;
unordered_map<string, list<Bucket>::iterator> m;
};
/**
* Your AllOne object will be instantiated and called as such:
* AllOne* obj = new AllOne();
* obj->inc(key);
* obj->dec(key);
* string param_3 = obj->getMaxKey();
* string param_4 = obj->getMinKey();
*/
| [
"747458025@qq.com"
] | 747458025@qq.com |
15473e990b3c91b3aead4dae362fff103d1e74e6 | 786de89be635eb21295070a6a3452f3a7fe6712c | /psddl_hdf2psana/tags/V00-02-03/src/camera.cpp | 319faf5b8b7b198dc581804e2542088ae63056bb | [] | no_license | connectthefuture/psdmrepo | 85267cfe8d54564f99e17035efe931077c8f7a37 | f32870a987a7493e7bf0f0a5c1712a5a030ef199 | refs/heads/master | 2021-01-13T03:26:35.494026 | 2015-09-03T22:22:11 | 2015-09-03T22:22:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,956 | cpp | //--------------------------------------------------------------------------
// File and Version Information:
// $Id$
//
// Description:
// Hand-written supporting types for DDL-HDF5 mapping.
//
//------------------------------------------------------------------------
//-----------------------
// This Class's Header --
//-----------------------
#include "psddl_hdf2psana/camera.h"
//-----------------
// C/C++ Headers --
//-----------------
//-------------------------------
// Collaborating Class Headers --
//-------------------------------
#include "hdf5pp/CompoundType.h"
#include "hdf5pp/Utils.h"
#include "psddl_hdf2psana/HdfParameters.h"
//-----------------------------------------------------------------------
// Local Macros, Typedefs, Structures, Unions and Forward Declarations --
//-----------------------------------------------------------------------
// ----------------------------------------
// -- Public Function Member Definitions --
// ----------------------------------------
namespace psddl_hdf2psana {
namespace Camera {
hdf5pp::Type ns_FrameV1_v0_dataset_data_stored_type()
{
typedef ns_FrameV1_v0::dataset_data DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("width", offsetof(DsType, width), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("height", offsetof(DsType, height), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("depth", offsetof(DsType, depth), hdf5pp::TypeTraits<uint32_t>::stored_type());
type.insert("offset", offsetof(DsType, offset), hdf5pp::TypeTraits<uint32_t>::stored_type());
return type;
}
hdf5pp::Type ns_FrameV1_v0::dataset_data::stored_type()
{
static hdf5pp::Type type = ns_FrameV1_v0_dataset_data_stored_type();
return type;
}
hdf5pp::Type ns_FrameV1_v0_dataset_data_native_type()
{
typedef ns_FrameV1_v0::dataset_data DsType;
hdf5pp::CompoundType type = hdf5pp::CompoundType::compoundType<DsType>();
type.insert("width", offsetof(DsType, width), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("height", offsetof(DsType, height), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("depth", offsetof(DsType, depth), hdf5pp::TypeTraits<uint32_t>::native_type());
type.insert("offset", offsetof(DsType, offset), hdf5pp::TypeTraits<uint32_t>::native_type());
return type;
}
hdf5pp::Type ns_FrameV1_v0::dataset_data::native_type()
{
static hdf5pp::Type type = ns_FrameV1_v0_dataset_data_native_type();
return type;
}
ns_FrameV1_v0::dataset_data::dataset_data()
{
}
ns_FrameV1_v0::dataset_data::dataset_data(const Psana::Camera::FrameV1& psanaobj)
: width(psanaobj.width())
, height(psanaobj.height())
, depth(psanaobj.depth())
, offset(psanaobj.offset())
{
}
ns_FrameV1_v0::dataset_data::~dataset_data()
{
}
uint32_t FrameV1_v0::width() const {
if (not m_ds_data.get()) read_ds_data();
return uint32_t(m_ds_data->width);
}
uint32_t FrameV1_v0::height() const {
if (not m_ds_data.get()) read_ds_data();
return uint32_t(m_ds_data->height);
}
uint32_t FrameV1_v0::depth() const {
if (not m_ds_data.get()) read_ds_data();
return uint32_t(m_ds_data->depth);
}
uint32_t FrameV1_v0::offset() const {
if (not m_ds_data.get()) read_ds_data();
return uint32_t(m_ds_data->offset);
}
ndarray<const uint8_t, 1> FrameV1_v0::_int_pixel_data() const {
if (m_ds_image.empty()) read_ds_image();
return m_ds_image;
}
ndarray<const uint8_t, 2>
FrameV1_v0::data8() const
{
if (this->depth() > 8) return ndarray<const uint8_t, 2>();
if (m_ds_image.empty()) read_ds_image();
return make_ndarray(m_ds_image.data_ptr(), height(), width());
}
ndarray<const uint16_t, 2>
FrameV1_v0::data16() const
{
if (this->depth() <= 8) return ndarray<const uint16_t, 2>();
if (m_ds_image.empty()) read_ds_image();
boost::shared_ptr<const uint16_t> tptr(m_ds_image.data_ptr(), (const uint16_t*)m_ds_image.data_ptr().get());
return make_ndarray(tptr, height(), width());
}
void FrameV1_v0::read_ds_data() const
{
m_ds_data = hdf5pp::Utils::readGroup<Camera::ns_FrameV1_v0::dataset_data>(m_group, "data", m_idx);
}
void FrameV1_v0::read_ds_image() const
{
// Image in HDF5 is stored as rank-2 array of either 8-bit or 16-bit data
// open dataset and check the type
hdf5pp::DataSet ds = m_group.openDataSet("image");
if (ds.type().size() == 1) {
// single-byte
ndarray<const uint8_t, 2> img = hdf5pp::Utils::readNdarray<uint8_t, 2>(ds, m_idx);
m_ds_image = make_ndarray(img.data_ptr(), img.size());
} else {
// otherwise 16-bit
ndarray<const uint16_t, 2> img = hdf5pp::Utils::readNdarray<uint16_t, 2>(m_group, "image", m_idx);
boost::shared_ptr<const uint8_t> tptr(img.data_ptr(), (const uint8_t*)img.data_ptr().get());
m_ds_image = make_ndarray(tptr, img.size()*2);
}
}
void make_datasets_FrameV1_v0(const Psana::Camera::FrameV1& obj,
hdf5pp::Group group, hsize_t chunk_size, int deflate, bool shuffle)
{
{
hdf5pp::Type dstype = ns_FrameV1_v0::dataset_data::stored_type();
unsigned chunk_cache_size = HdfParameters::chunkCacheSize(dstype, chunk_size);
hdf5pp::Utils::createDataset(group, "data", dstype, chunk_size, chunk_cache_size, deflate, shuffle);
}
{
// image can be either 8-bit or 16-bit
hsize_t dims[2];
hdf5pp::Type basetype;
if (obj.depth() > 8) {
const ndarray<const uint16_t, 2>& psana_array = obj.data16();
std::copy(psana_array.shape(), psana_array.shape()+2, dims);
basetype = hdf5pp::TypeTraits<uint16_t>::stored_type();
} else {
const ndarray<const uint8_t, 2>& psana_array = obj.data8();
std::copy(psana_array.shape(), psana_array.shape()+2, dims);
basetype = hdf5pp::TypeTraits<uint8_t>::stored_type();
}
hdf5pp::Type dstype = hdf5pp::ArrayType::arrayType(basetype, 2, dims);
unsigned chunk_cache_size = HdfParameters::chunkCacheSize(dstype, chunk_size);
hdf5pp::Utils::createDataset(group, "image", dstype, chunk_size, chunk_cache_size, deflate, shuffle);
}
}
void store_FrameV1_v0(const Psana::Camera::FrameV1& obj, hdf5pp::Group group, bool append)
{
// store metadata dataset
if (append) {
hdf5pp::Utils::append(group, "data", ns_FrameV1_v0::dataset_data::dataset_data(obj));
} else {
hdf5pp::Utils::storeScalar(group, "data", ns_FrameV1_v0::dataset_data::dataset_data(obj));
}
// store image, it can be either 8-bit or 16-bit
if (obj.depth() > 8) {
ndarray<const uint16_t, 2> img = obj.data16();
if (append) {
hdf5pp::Utils::appendNDArray(group, "image", img);
} else {
hdf5pp::Utils::storeNDArray(group, "image", img);
}
} else {
ndarray<const uint8_t, 2> img = obj.data8();
if (append) {
hdf5pp::Utils::appendNDArray(group, "image", img);
} else {
hdf5pp::Utils::storeNDArray(group, "image", img);
}
}
}
} // namespace Camera
} // namespace psddl_hdf2psana
| [
"salnikov@SLAC.STANFORD.EDU@b967ad99-d558-0410-b138-e0f6c56caec7"
] | salnikov@SLAC.STANFORD.EDU@b967ad99-d558-0410-b138-e0f6c56caec7 |
867dbe3eed89073d8fe8a39c97f5b9710c7f924a | 98fd439c67b904af285779a6d704190de7f1b57e | /code_practice/10/1017_class/6_functor7.cpp | 8dedf5aa696f2a1597265240dba7cad6e669b835 | [
"MIT"
] | permissive | armkernel/armkernel.github.io | 2bb042731730eab2cbc7198050c028575732096a | f74b8ddfc8a69dec8b5eeccb4d92c62dcc6c321a | refs/heads/master | 2020-06-30T00:31:29.317666 | 2019-12-17T14:41:37 | 2019-12-17T14:41:37 | 200,667,359 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 778 | cpp | #include <iostream>
#include <algorithm>
#include <functional> // less<>, greater<> 여기에 있다.
using namespace std;
inline bool cmp1(int a, int b) { return a < b; }
inline bool cmp2(int a, int b) { return a > b; }
// 아래 둘은 기계어 코드가 없다. 치환됨
struct less
{
inline bool operator()(int a, b) { return a < b; }
};
struct greater
{
inline bool operator()(int a, b) { return a > b; }
};
template<typename T> void foo(T f)
{
bool b = f(1,2);
}
int main()
{
Less f1;
Greater f2;
foo(cmp1); // T : bool(*)(int,int)
foo(cmp2); // T : bool(*)(int,int)
foo(f1); // T : Less
foo(f2); // T : Greater
}
// 1. 컴파일 하면 foo함수는 몇 개가 생성될까요? 3
// 2. foo 제외하고 함수가 몇개 더 있을 까요? 3
| [
"sksioi1234@gmail.com"
] | sksioi1234@gmail.com |
dcb9d079d90e3ef5c6c7d3712f41e8403711f302 | f15d6c870d51ffa4a7e6151c42ceb5de0eedf46a | /Vaango/src/CCA/Components/MPM/ConstitutiveModel/PlasticityModels/IsoHardeningFlow.cc | 33bb7ef00250d6d1f5069995ecf9f1f81cfd8915 | [] | no_license | pinebai/ParSim | 1a5ee3687bd1582f31be9dbd88b3914769549095 | f787523ae6c47c87ff1a74e199c7068ca45dc780 | refs/heads/master | 2021-01-24T07:45:12.923015 | 2017-04-22T04:34:44 | 2017-04-22T04:34:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,837 | cc | /*
* The MIT License
*
* Copyright (c) 2013-2014 Callaghan Innovation, New Zealand
*
* 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.
*/
/*
* The MIT License
*
* Copyright (c) 1997-2012 The University of Utah
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "IsoHardeningFlow.h"
#include <Core/Math/FastMatrix.h>
#include <Core/Exceptions/ProblemSetupException.h>
#include <cmath>
using namespace std;
using namespace Uintah;
IsoHardeningFlow::IsoHardeningFlow(ProblemSpecP& ps)
{
ps->require("K",d_CM.K);
ps->require("sigma_Y",d_CM.sigma_0);
// Initialize internal variable labels for evolution
pAlphaLabel = VarLabel::create("p.alpha",
ParticleVariable<double>::getTypeDescription());
pAlphaLabel_preReloc = VarLabel::create("p.alpha+",
ParticleVariable<double>::getTypeDescription());
}
IsoHardeningFlow::IsoHardeningFlow(const IsoHardeningFlow* cm)
{
d_CM.K = cm->d_CM.K;
d_CM.sigma_0 = cm->d_CM.sigma_0;
// Initialize internal variable labels for evolution
pAlphaLabel = VarLabel::create("p.alpha",
ParticleVariable<double>::getTypeDescription());
pAlphaLabel_preReloc = VarLabel::create("p.alpha+",
ParticleVariable<double>::getTypeDescription());
}
IsoHardeningFlow::~IsoHardeningFlow()
{
VarLabel::destroy(pAlphaLabel);
VarLabel::destroy(pAlphaLabel_preReloc);
}
void IsoHardeningFlow::outputProblemSpec(ProblemSpecP& ps)
{
ProblemSpecP flow_ps = ps->appendChild("flow_model");
flow_ps->setAttribute("type","isotropic_hardening");
flow_ps->appendElement("K",d_CM.K);
flow_ps->appendElement("sigma_Y",d_CM.sigma_0);
}
void
IsoHardeningFlow::addInitialComputesAndRequires(Task* task,
const MPMMaterial* matl,
const PatchSet*)
{
const MaterialSubset* matlset = matl->thisMaterial();
task->computes(pAlphaLabel, matlset);
}
void
IsoHardeningFlow::addComputesAndRequires(Task* task,
const MPMMaterial* matl,
const PatchSet*)
{
const MaterialSubset* matlset = matl->thisMaterial();
task->requires(Task::OldDW, pAlphaLabel, matlset,Ghost::None);
task->computes(pAlphaLabel_preReloc, matlset);
}
void
IsoHardeningFlow::addComputesAndRequires(Task* task,
const MPMMaterial* matl,
const PatchSet*,
bool /*recurse*/,
bool SchedParent)
{
const MaterialSubset* matlset = matl->thisMaterial();
if(SchedParent){
task->requires(Task::ParentOldDW, pAlphaLabel, matlset,Ghost::None);
}else{
task->requires(Task::OldDW, pAlphaLabel, matlset,Ghost::None);
}
}
void
IsoHardeningFlow::addParticleState(std::vector<const VarLabel*>& from,
std::vector<const VarLabel*>& to)
{
from.push_back(pAlphaLabel);
to.push_back(pAlphaLabel_preReloc);
}
void
IsoHardeningFlow::allocateCMDataAddRequires(Task* task,
const MPMMaterial* matl,
const PatchSet* ,
MPMLabel* )
{
const MaterialSubset* matlset = matl->thisMaterial();
task->requires(Task::NewDW, pAlphaLabel_preReloc, matlset, Ghost::None);
//task->requires(Task::OldDW, pAlphaLabel, matlset, Ghost::None);
}
void IsoHardeningFlow::allocateCMDataAdd(DataWarehouse* new_dw,
ParticleSubset* addset,
ParticleLabelVariableMap* newState,
ParticleSubset* delset,
DataWarehouse* )
{
// Put stuff in here to initialize each particle's
// constitutive model parameters and deformationMeasure
ParticleVariable<double> pAlpha;
constParticleVariable<double> o_Alpha;
new_dw->allocateTemporary(pAlpha,addset);
new_dw->get(o_Alpha,pAlphaLabel_preReloc,delset);
//old_dw->get(o_Alpha,pAlphaLabel,delset);
ParticleSubset::iterator o,n = addset->begin();
for(o = delset->begin(); o != delset->end(); o++, n++) {
pAlpha[*n] = o_Alpha[*o];
}
(*newState)[pAlphaLabel]=pAlpha.clone();
}
void
IsoHardeningFlow::initializeInternalVars(ParticleSubset* pset,
DataWarehouse* new_dw)
{
new_dw->allocateAndPut(pAlpha_new, pAlphaLabel, pset);
ParticleSubset::iterator iter = pset->begin();
for(;iter != pset->end(); iter++) {
pAlpha_new[*iter] = 0.0;
}
}
void
IsoHardeningFlow::getInternalVars(ParticleSubset* pset,
DataWarehouse* old_dw)
{
old_dw->get(pAlpha, pAlphaLabel, pset);
}
void
IsoHardeningFlow::allocateAndPutInternalVars(ParticleSubset* pset,
DataWarehouse* new_dw)
{
new_dw->allocateAndPut(pAlpha_new, pAlphaLabel_preReloc, pset);
}
void
IsoHardeningFlow::allocateAndPutRigid(ParticleSubset* pset,
DataWarehouse* new_dw)
{
new_dw->allocateAndPut(pAlpha_new, pAlphaLabel_preReloc, pset);
// Initializing to zero for the sake of RigidMPM's carryForward
ParticleSubset::iterator iter = pset->begin();
for(;iter != pset->end(); iter++){
pAlpha_new[*iter] = 0.0;
}
}
void
IsoHardeningFlow::updateElastic(const particleIndex idx)
{
pAlpha_new[idx] = pAlpha[idx];
}
void
IsoHardeningFlow::updatePlastic(const particleIndex idx,
const double& delGamma)
{
pAlpha_new[idx] = pAlpha[idx] + sqrt(2.0/3.0)*delGamma;
}
double
IsoHardeningFlow::computeFlowStress(const PlasticityState* state,
const double& ,
const double& ,
const MPMMaterial* ,
const particleIndex idx)
{
// double flowStress = d_CM.sigma_0 + d_CM.K*pAlpha[idx];
double flowStress = d_CM.sigma_0 + d_CM.K*state->plasticStrain;
return flowStress;
}
double
IsoHardeningFlow::computeEpdot(const PlasticityState* state,
const double& ,
const double& ,
const MPMMaterial* ,
const particleIndex)
{
return state->plasticStrainRate;
}
void
IsoHardeningFlow::computeTangentModulus(const Matrix3& stress,
const PlasticityState* ,
const double& ,
const MPMMaterial* ,
const particleIndex ,
TangentModulusTensor& ,
TangentModulusTensor& )
{
throw InternalError("Empty Function: IsoHardeningFlow::computeTangentModulus", __FILE__, __LINE__);
}
void
IsoHardeningFlow::evalDerivativeWRTScalarVars(const PlasticityState* state,
const particleIndex idx,
Vector& derivs)
{
derivs[0] = evalDerivativeWRTStrainRate(state, idx);
derivs[1] = evalDerivativeWRTTemperature(state, idx);
derivs[2] = evalDerivativeWRTPlasticStrain(state, idx);
}
double
IsoHardeningFlow::evalDerivativeWRTPlasticStrain(const PlasticityState*,
const particleIndex )
{
return d_CM.K;
}
///////////////////////////////////////////////////////////////////////////
/* Compute the shear modulus. */
///////////////////////////////////////////////////////////////////////////
double
IsoHardeningFlow::computeShearModulus(const PlasticityState* state)
{
return state->shearModulus;
}
///////////////////////////////////////////////////////////////////////////
/* Compute the melting temperature */
///////////////////////////////////////////////////////////////////////////
double
IsoHardeningFlow::computeMeltingTemp(const PlasticityState* state)
{
return state->meltingTemp;
}
double
IsoHardeningFlow::evalDerivativeWRTTemperature(const PlasticityState* ,
const particleIndex )
{
return 0.0;
}
double
IsoHardeningFlow::evalDerivativeWRTStrainRate(const PlasticityState* ,
const particleIndex )
{
return 0.0;
}
double
IsoHardeningFlow::evalDerivativeWRTAlpha(const PlasticityState* ,
const particleIndex )
{
return d_CM.K;
}
| [
"b.banerjee.nz@gmail.com"
] | b.banerjee.nz@gmail.com |
63a2b7b83c93c1f89fcd4391d9a60d3c478805ae | 24f26275ffcd9324998d7570ea9fda82578eeb9e | /chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api_unittest.cc | 386feaea2a65506c3783e5746bc6c634fb158e65 | [
"BSD-3-Clause"
] | permissive | Vizionnation/chromenohistory | 70a51193c8538d7b995000a1b2a654e70603040f | 146feeb85985a6835f4b8826ad67be9195455402 | refs/heads/master | 2022-12-15T07:02:54.461083 | 2019-10-25T15:07:06 | 2019-10-25T15:07:06 | 217,557,501 | 2 | 1 | BSD-3-Clause | 2022-11-19T06:53:07 | 2019-10-25T14:58:54 | null | UTF-8 | C++ | false | false | 8,864 | cc | // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api.h"
#include <utility>
#include "base/values.h"
#include "chrome/browser/chromeos/attestation/mock_tpm_challenge_key.h"
#include "chrome/browser/chromeos/login/users/fake_chrome_user_manager.h"
#include "chrome/browser/extensions/extension_function_test_utils.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/browser_with_test_window_test.h"
#include "chrome/test/base/testing_profile_manager.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/signin/public/identity_manager/identity_test_utils.h"
#include "components/user_manager/scoped_user_manager.h"
#include "extensions/common/extension_builder.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using testing::Invoke;
using testing::NiceMock;
namespace utils = extension_function_test_utils;
namespace extensions {
namespace {
const char kUserEmail[] = "test@google.com";
void FakeRunCheckNotRegister(
chromeos::attestation::AttestationKeyType key_type,
Profile* profile,
chromeos::attestation::TpmChallengeKeyCallback callback,
const std::string& challenge,
bool register_key,
const std::string& key_name_for_spkac) {
EXPECT_FALSE(register_key);
std::move(callback).Run(
chromeos::attestation::TpmChallengeKeyResult::MakeResult("response"));
}
class EPKChallengeKeyTestBase : public BrowserWithTestWindowTest {
protected:
EPKChallengeKeyTestBase()
: extension_(ExtensionBuilder("Test").Build()),
fake_user_manager_(new chromeos::FakeChromeUserManager),
user_manager_enabler_(base::WrapUnique(fake_user_manager_)) {
stub_install_attributes_.SetCloudManaged("google.com", "device_id");
}
void SetUp() override {
BrowserWithTestWindowTest::SetUp();
prefs_ = browser()->profile()->GetPrefs();
SetAuthenticatedUser();
}
void SetMockTpmChallenger() {
auto mock_tpm_challenge_key = std::make_unique<
NiceMock<chromeos::attestation::MockTpmChallengeKey>>();
// Will be used with EXPECT_CALL.
mock_tpm_challenge_key_ = mock_tpm_challenge_key.get();
mock_tpm_challenge_key->EnableFake();
// transfer ownership inside factory
chromeos::attestation::TpmChallengeKeyFactory::SetForTesting(
std::move(mock_tpm_challenge_key));
}
// This will be called by BrowserWithTestWindowTest::SetUp();
TestingProfile* CreateProfile() override {
fake_user_manager_->AddUserWithAffiliation(
AccountId::FromUserEmail(kUserEmail), true);
return profile_manager()->CreateTestingProfile(kUserEmail);
}
// Derived classes can override this method to set the required authenticated
// user in the IdentityManager class.
virtual void SetAuthenticatedUser() {
signin::MakePrimaryAccountAvailable(
IdentityManagerFactory::GetForProfile(browser()->profile()),
kUserEmail);
}
// Like extension_function_test_utils::RunFunctionAndReturnError but with an
// explicit ListValue.
std::string RunFunctionAndReturnError(ExtensionFunction* function,
std::unique_ptr<base::ListValue> args,
Browser* browser) {
utils::RunFunction(function, std::move(args), browser,
extensions::api_test_utils::NONE);
EXPECT_EQ(ExtensionFunction::FAILED, *function->response_type());
return function->GetError();
}
// Like extension_function_test_utils::RunFunctionAndReturnSingleResult but
// with an explicit ListValue.
base::Value* RunFunctionAndReturnSingleResult(
ExtensionFunction* function,
std::unique_ptr<base::ListValue> args,
Browser* browser) {
scoped_refptr<ExtensionFunction> function_owner(function);
// Without a callback the function will not generate a result.
function->set_has_callback(true);
utils::RunFunction(function, std::move(args), browser,
extensions::api_test_utils::NONE);
EXPECT_TRUE(function->GetError().empty())
<< "Unexpected error: " << function->GetError();
const base::Value* single_result = NULL;
if (function->GetResultList() != NULL &&
function->GetResultList()->Get(0, &single_result)) {
return single_result->DeepCopy();
}
return NULL;
}
scoped_refptr<const extensions::Extension> extension_;
chromeos::StubInstallAttributes stub_install_attributes_;
// fake_user_manager_ is owned by user_manager_enabler_.
chromeos::FakeChromeUserManager* fake_user_manager_ = nullptr;
user_manager::ScopedUserManager user_manager_enabler_;
PrefService* prefs_ = nullptr;
chromeos::attestation::MockTpmChallengeKey* mock_tpm_challenge_key_ = nullptr;
};
class EPKChallengeMachineKeyTest : public EPKChallengeKeyTestBase {
protected:
EPKChallengeMachineKeyTest()
: func_(new EnterprisePlatformKeysChallengeMachineKeyFunction()) {
func_->set_extension(extension_.get());
}
// Returns an error string for the given code.
std::string GetCertificateError(int error_code) {
return base::StringPrintf(
chromeos::attestation::TpmChallengeKeyImpl::kGetCertificateFailedError,
error_code);
}
std::unique_ptr<base::ListValue> CreateArgs() {
return CreateArgsInternal(nullptr);
}
std::unique_ptr<base::ListValue> CreateArgsNoRegister() {
return CreateArgsInternal(std::make_unique<bool>(false));
}
std::unique_ptr<base::ListValue> CreateArgsRegister() {
return CreateArgsInternal(std::make_unique<bool>(true));
}
std::unique_ptr<base::ListValue> CreateArgsInternal(
std::unique_ptr<bool> register_key) {
std::unique_ptr<base::ListValue> args(new base::ListValue);
args->Append(base::Value::CreateWithCopiedBuffer("challenge", 9));
if (register_key) {
args->AppendBoolean(*register_key);
}
return args;
}
scoped_refptr<EnterprisePlatformKeysChallengeMachineKeyFunction> func_;
base::ListValue args_;
};
TEST_F(EPKChallengeMachineKeyTest, ExtensionNotWhitelisted) {
base::ListValue empty_whitelist;
prefs_->Set(prefs::kAttestationExtensionWhitelist, empty_whitelist);
EXPECT_EQ(EPKPChallengeKey::kExtensionNotWhitelistedError,
RunFunctionAndReturnError(func_.get(), CreateArgs(), browser()));
}
TEST_F(EPKChallengeMachineKeyTest, Success) {
SetMockTpmChallenger();
base::Value whitelist(base::Value::Type::LIST);
whitelist.Append(extension_->id());
prefs_->Set(prefs::kAttestationExtensionWhitelist, whitelist);
std::unique_ptr<base::Value> value(
RunFunctionAndReturnSingleResult(func_.get(), CreateArgs(), browser()));
ASSERT_TRUE(value->is_blob());
std::string response(value->GetBlob().begin(), value->GetBlob().end());
EXPECT_EQ("response", response);
}
TEST_F(EPKChallengeMachineKeyTest, KeyNotRegisteredByDefault) {
SetMockTpmChallenger();
base::ListValue whitelist;
whitelist.AppendString(extension_->id());
prefs_->Set(prefs::kAttestationExtensionWhitelist, whitelist);
EXPECT_CALL(*mock_tpm_challenge_key_, Run)
.WillOnce(Invoke(FakeRunCheckNotRegister));
EXPECT_TRUE(utils::RunFunction(func_.get(), CreateArgs(), browser(),
extensions::api_test_utils::NONE));
}
class EPKChallengeUserKeyTest : public EPKChallengeKeyTestBase {
protected:
EPKChallengeUserKeyTest()
: func_(new EnterprisePlatformKeysChallengeUserKeyFunction()) {
func_->set_extension(extension_.get());
}
void SetUp() override {
EPKChallengeKeyTestBase::SetUp();
// Set the user preferences.
prefs_->SetBoolean(prefs::kAttestationEnabled, true);
}
std::unique_ptr<base::ListValue> CreateArgs() {
return CreateArgsInternal(true);
}
std::unique_ptr<base::ListValue> CreateArgsNoRegister() {
return CreateArgsInternal(false);
}
std::unique_ptr<base::ListValue> CreateArgsInternal(bool register_key) {
std::unique_ptr<base::ListValue> args(new base::ListValue);
args->Append(base::Value::CreateWithCopiedBuffer("challenge", 9));
args->AppendBoolean(register_key);
return args;
}
EPKPChallengeKey impl_;
scoped_refptr<EnterprisePlatformKeysChallengeUserKeyFunction> func_;
};
TEST_F(EPKChallengeUserKeyTest, ExtensionNotWhitelisted) {
base::ListValue empty_whitelist;
prefs_->Set(prefs::kAttestationExtensionWhitelist, empty_whitelist);
EXPECT_EQ(EPKPChallengeKey::kExtensionNotWhitelistedError,
RunFunctionAndReturnError(func_.get(), CreateArgs(), browser()));
}
} // namespace
} // namespace extensions
| [
"rjkroege@chromium.org"
] | rjkroege@chromium.org |
f6733c14df0164cc92fb982e1764e8b4f5c7a267 | 8e0fbd384623e689a5109fff1efa071e1198b149 | /Subtask2/density.cpp | ad51cbc88fec50dbe659c2772a766981ab28e22a | [] | no_license | Prat1510/Traffic-Density-Estimation | 736902ea357dbe30df4e166d65cdd8ad865cde92 | ecda59fa41ab18717a1c61e8229700eb2b534fe1 | refs/heads/main | 2023-04-21T11:04:01.951159 | 2021-05-16T02:30:39 | 2021-05-16T02:30:39 | 340,706,333 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,626 | cpp | #include "cam.h"
#include <iostream>
#include <sstream>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/video.hpp>
#include <fstream>
using namespace cv;
using namespace std;
int main(int argc, char* argv[])
{
if (argc == 1) //ensures that name of image is given
{
cout<<"Please provide the video name as an arguement along with the program name.\n";
return -1;
}
if (argc > 2) //ensuring that extra names are not given
{
cout<<"Only one arguement has to be provided specifying the name of input video.\n";
return -1;
}
string name = argv[1]; //storing the name of video
Ptr<BackgroundSubtractor> pBackSub1; //creating two backgroundSubstractor instances and
Ptr<BackgroundSubtractor> pBackSub2; //two pointers p[ointing to each of them
pBackSub1 = createBackgroundSubtractorMOG2(500,128,false);
pBackSub2 = createBackgroundSubtractorMOG2(300,16,false);
VideoCapture capture(name + ".mp4"); //open the video
if (!capture.isOpened()){ //cheacking if video exists, returning error otherwise
cout << "This video: "<< name <<" is not in the same directory! Put the video in the same directory or give the correct video name." << endl;
return 0;
}
Mat frame = imread("Background.jpg"); //reading empty image of road for using as background
if (frame.empty()) { //ensures that image exists in the folder
cout<<"Please enter the correct background image name.\n";
return -1;
}
double pixels;
Mat fgMask1, fgMask2;
ofstream myfile;
myfile.open("output.txt");
myfile << "Time" << "," << "Queue Density" << "," << "Dynamic Density" << "\n";
cout << "Time" << "," << "Queue Density" << "," << "Dynamic Density" << "\n";
double whitePixels1, whitePixels2;
while (true) {
pixels = double(frame.total());
pBackSub1->apply(frame, fgMask1, 0);
pBackSub2->apply(frame, fgMask2);
stringstream ss; //reading frame and storing it as string
ss << capture.get(CAP_PROP_POS_FRAMES);
string frameNum = ss.str();
// imshow("Frame", frame);
// imshow("FG Mask1", fgMask1);
// imshow("FG Mask2", fgMask2);
whitePixels1 = (countNonZero(fgMask1))/pixels ; //counting no of white pixels and then priting values on console
whitePixels2 = (countNonZero(fgMask2))/pixels ;
float Time = (float)stoi(frameNum)/15;
cout << Time << "," << whitePixels1 << "," << whitePixels2 << "\n";
myfile << Time << "," << whitePixels1 << "," << whitePixels2 << "\n";
int keyboard = waitKey(20); //stopping if esc is pressed on keyboard
if (keyboard == 27)
break;
capture >> frame; //reading next frames, we are processing every third frame only
capture >> frame; //for faster execution of program
capture >> frame;
if (frame.empty()) //stop if video has ended
break;
frame = angle_correction(frame); //correcting perception using code of pevious subtask
}
myfile.close();
return 0;
}
| [
"gunjan3723@gmail.com"
] | gunjan3723@gmail.com |
b5095aa81a36453bbab5c17a52095812a1dc5ba2 | e4e13bd6b1f6cbd17f73e34509236a4af83e063b | /Source/FBXLoader.cpp | 55517e62df3cd362494d086dee130eaa90464f63 | [] | no_license | on1659/DiretX12 | 5db952b7ba9d6310c5a75686f0288191947d4ae8 | a4a327620be14af847755616e132e22dc9832bb2 | refs/heads/main | 2023-07-14T10:04:05.524906 | 2021-09-04T11:29:29 | 2021-09-04T11:29:29 | 392,380,914 | 1 | 0 | null | null | null | null | UHC | C++ | false | false | 34,571 | cpp | ////////////////////////////////////////////////////////////////////////////////
// Filename: FBXLoader.cpp
////////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "FBXLoader.h"
FBXModelLoader::FBXModelLoader(std::string filename, float modelScale, bool isVoxel)
: m_isVoxel(isVoxel)
, m_manager(nullptr)
{
//m_pMeshNodeInfo = new FBXSDK_MESH_NODE();
//m_pMeshNodeInfo->Re lease();
m_pMeshNodeInfo.clear();
CreateFBXScene(filename);
ImportFBX(filename);
//DirectX방식의 축으로 변환
FbxAxisSystem OurAxisSystem = FbxAxisSystem::DirectX;
FbxAxisSystem SceneAxisSystem = m_scene->GetGlobalSettings().GetAxisSystem();
if (SceneAxisSystem != OurAxisSystem)
{
FbxAxisSystem::DirectX.ConvertScene(m_scene);
}
FbxSystemUnit SceneSystemUnit = m_scene->GetGlobalSettings().GetSystemUnit();
if (SceneSystemUnit.GetScaleFactor() != 1.0)
{
FbxSystemUnit::cm.ConvertScene(m_scene);
}
#ifdef FBX_GLOBAL_MANAGER
FbxGeometryConverter GeomConverter(g_FBXManager);
#else
FbxGeometryConverter GeomConverter(m_manager);
#endif
GeomConverter.Triangulate(m_scene, true);
SetModelScale(modelScale);
m_fileName = filename;
m_getfirstPos = false;
m_highestX = 0.0f;
m_lowestX = 0.0f;
m_highestY = 0.0f;
m_lowestY = 0.0f;
m_highestZ = 0.0f;
m_lowestZ = 0.0f;
}
FBXModelLoader::FBXModelLoader(FbxScene* scene, float modelScale, bool isVoxel)
: m_isVoxel(isVoxel)
{
m_scene = scene;
SetModelScale(modelScale);
m_fileName = nullptr;
}
FBXModelLoader::~FBXModelLoader()
{
m_pMeshNodeInfo.clear();
if (m_importer)
{
m_importer->Destroy();
m_importer = nullptr;
}
if (m_scene)
{
m_scene->Destroy();
m_scene = nullptr;
}
#ifndef FBX_GLOBAL_MANAGER
if (m_manager)
{
m_manager->Destroy();
m_manager = nullptr;
}
#endif
}
void FBXModelLoader::CreateFBXScene(std::string filename)
{
#ifdef FBX_GLOBAL_MANAGER
if (!bManagerSetting)
{
g_FBXManager = FbxManager::Create();
g_FBXIOsettings = FbxIOSettings::Create(g_FBXManager, IOSROOT);
g_FBXManager->SetIOSettings(g_FBXIOsettings);
bManagerSetting = true;
}
m_scene = FbxScene::Create(g_FBXManager, filename.c_str());
#else
try {
m_manager = FbxManager::Create();
}
catch (int e)
{
return;
}
m_ioSettings = FbxIOSettings::Create(m_manager, IOSROOT);
m_manager->SetIOSettings(m_ioSettings);
m_scene = FbxScene::Create(m_manager, "tempName");
#endif
}
void FBXModelLoader::ImportFBX(std::string path)
{
#ifdef FBX_GLOBAL_MANAGER
m_importer = FbxImporter::Create(g_FBXManager, "");
if (!m_importer->Initialize(path.c_str(), -1, g_FBXManager->GetIOSettings()))
{
std::string ErrorTitle = "FBX Import Error";
GMessageBox(ErrorTitle, path);
}
#else
m_importer = FbxImporter::Create(m_manager, "");
if (!m_importer->Initialize(path.c_str(), -1, m_manager->GetIOSettings()))
{
std::string ErrorTitle = "FBX Import Error";
GMessageBox(ErrorTitle, path);
}
#endif
m_importer->Import(m_scene);
m_importer->Destroy();
}
void FBXModelLoader::ProcessMeshInfo()
{
FbxNode* rootNode = m_scene->GetRootNode();
if (rootNode) { this->TraversalFBXTree_forMesh(rootNode); }
}
void FBXModelLoader::ProcessMeshInfo(FbxScene* scene)
{
FbxNode* rootNode = scene->GetRootNode();
if (rootNode) { this->TraversalFBXTree_forMesh(rootNode); }
}
void FBXModelLoader::TraversalFBXTree_forMesh(FbxNode* Node)
{
int numChild = Node->GetChildCount();
FbxNode *childNode = nullptr;
if (0 != m_pMeshNodeInfo.size())
{
m_pMeshNodeInfo.clear();
}
for (int i = 0; i < numChild; i++)
{
childNode = Node->GetChild(i);
FbxMesh *childMesh = childNode->GetMesh();
if (childMesh != nullptr)
{
FBXSDK_MESH_NODE* tempMeshNodeInfo = new FBXSDK_MESH_NODE();
tempMeshNodeInfo->Release();
tempMeshNodeInfo->m_polygonCount = childMesh->GetPolygonCount();
//=================================================================================================================
//=================================================================================================================
//정점
LoadVertexInformation(childMesh, tempMeshNodeInfo);
//인덱스
//주의!!!! 이 인덱스는 정점 순서를 표현하는 것이지 노멀&UV에 순서를 표현하는 것이 아님니다!!!!!!!
//std::cout << "\n#인덱스 추출";
tempMeshNodeInfo->m_numIndices = childMesh->GetPolygonVertexCount();
tempMeshNodeInfo->m_indices = new int[tempMeshNodeInfo->m_numIndices];
tempMeshNodeInfo->m_indices = childMesh->GetPolygonVertices();
//=================================================================================================================
//=================================================================================================================
//std::cout << "\n" << "#노멀값";
//노멀값
LoadNormalInformation(childMesh, tempMeshNodeInfo);
//=================================================================================================================
//=================================================================================================================
//std::cout << "\n" << "#텍스쳐UV";
//텍스쳐 uv
LoadUVInformation(childMesh, tempMeshNodeInfo);
//=================================================================================================================
//=================================================================================================================
m_pMeshNodeInfo.push_back(*tempMeshNodeInfo);
delete tempMeshNodeInfo;
}
}
}
void FBXModelLoader::LoadVertexInformation(FbxMesh* pMesh, FBXSDK_MESH_NODE* tempMeshNodeInfo)
{
int numVerts = pMesh->GetControlPointsCount();
for (unsigned int i = 0; i < numVerts; ++i)
{
FBX_DATATYPE3 currPosition;
if (m_isVoxel)
{
currPosition.x = static_cast<float>(pMesh->GetControlPointAt(i).mData[0] * m_modelScale);
currPosition.y = static_cast<float>(pMesh->GetControlPointAt(i).mData[2] * m_modelScale);
currPosition.z = static_cast<float>(pMesh->GetControlPointAt(i).mData[1] * m_modelScale);
}
else
{
currPosition.x = static_cast<float>(pMesh->GetControlPointAt(i).mData[0] * m_modelScale);
currPosition.y = static_cast<float>(pMesh->GetControlPointAt(i).mData[1] * m_modelScale);
currPosition.z = static_cast<float>(pMesh->GetControlPointAt(i).mData[2] * m_modelScale);
}
if (m_getfirstPos)
{
if (m_highestX < currPosition.x) { m_highestX = currPosition.x; }
if (m_lowestX > currPosition.x) { m_lowestX = currPosition.x; }
if (m_highestY < currPosition.y) { m_highestY = currPosition.y; }
if (m_lowestY > currPosition.y) { m_lowestY = currPosition.y; }
if (m_highestZ < currPosition.z) { m_highestZ = currPosition.z; }
if (m_lowestZ > currPosition.z) { m_lowestZ = currPosition.z; }
}
else {
m_highestX = currPosition.x;
m_lowestX = currPosition.x;
m_highestY = currPosition.y;
m_lowestY = currPosition.y;
m_highestZ = currPosition.z;
m_lowestZ = currPosition.z;
m_getfirstPos = true;
}
tempMeshNodeInfo->m_positions.push_back(currPosition);
}
}
void FBXModelLoader::LoadNormalInformation(FbxMesh* pMesh, FBXSDK_MESH_NODE* tempMeshNodeInfo)
{
FbxGeometryElementNormal* normalElement = pMesh->GetElementNormal();
if (normalElement)
{
if (FbxGeometryElement::eByControlPoint == normalElement->GetMappingMode())
{
for (int vertexIndex = 0; vertexIndex < pMesh->GetControlPointsCount(); vertexIndex++)
{
int normalIndex = 0;
//reference mode is direct, the normal index is same as vertex index.
//get normals by the index of control vertex
if (normalElement->GetReferenceMode() == FbxGeometryElement::eDirect)
normalIndex = vertexIndex;
//reference mode is index-to-direct, get normals by the index-to-direct
if (normalElement->GetReferenceMode() == FbxGeometryElement::eIndexToDirect)
normalIndex = normalElement->GetIndexArray().GetAt(vertexIndex);
//Got normals of each vertex.
FbxVector4 getNormal = normalElement->GetDirectArray().GetAt(normalIndex);
tempMeshNodeInfo->m_normals.push_back(FBX_DATATYPE3((float)getNormal[0], (float)getNormal[1], (float)getNormal[2]));
}
}
else if (FbxGeometryElement::eByPolygonVertex == normalElement->GetMappingMode())
{
int indexByPolygonVertex = 0;
//Let's get normals of each polygon, since the mapping mode of normal element is by polygon-vertex.
for (int polygonIndex = 0; polygonIndex < tempMeshNodeInfo->m_polygonCount; polygonIndex++)
{
//get polygon size, you know how many vertices in current polygon.
int polygonSize = pMesh->GetPolygonSize(polygonIndex);
//retrieve each vertex of current polygon.
for (int i = 0; i < polygonSize; i++)
{
int lNormalIndex = 0;
//reference mode is direct, the normal index is same as indexByPolygonVertex.
if (normalElement->GetReferenceMode() == FbxGeometryElement::eDirect)
lNormalIndex = indexByPolygonVertex;
//reference mode is index-to-direct, get normals by the index-to-direct
if (normalElement->GetReferenceMode() == FbxGeometryElement::eIndexToDirect)
lNormalIndex = normalElement->GetIndexArray().GetAt(indexByPolygonVertex);
//Got normals of each polygon-vertex.
FbxVector4 getNormal = normalElement->GetDirectArray().GetAt(lNormalIndex);
tempMeshNodeInfo->m_normals.push_back(FBX_DATATYPE3((float)getNormal[0], (float)getNormal[1], (float)getNormal[2]));
indexByPolygonVertex++;
}
}
}
}
}
void FBXModelLoader::LoadUVInformation(FbxMesh* pMesh, FBXSDK_MESH_NODE* tempMeshNodeInfo)
{
//UV 이름 리스트를 가져온다. 이름은 UV Channel 1 식으로 나열.
FbxStringList lUVSetNameList;
pMesh->GetUVSetNames(lUVSetNameList);
//iterating over all uv sets
for (int lUVSetIndex = 0; lUVSetIndex < lUVSetNameList.GetCount(); lUVSetIndex++)
{
//get lUVSetIndex-th uv set
const char* lUVSetName = lUVSetNameList.GetStringAt(lUVSetIndex);
const FbxGeometryElementUV* lUVElement = pMesh->GetElementUV(lUVSetName);
if (!lUVElement)
continue;
// only support mapping mode eByPolygonVertex and eByControlPoint
if (lUVElement->GetMappingMode() != FbxGeometryElement::eByPolygonVertex &&
lUVElement->GetMappingMode() != FbxGeometryElement::eByControlPoint)
return;
//index array, where holds the index referenced to the uv data
const bool lUseIndex = lUVElement->GetReferenceMode() != FbxGeometryElement::eDirect;
const int lIndexCount = (lUseIndex) ? lUVElement->GetIndexArray().GetCount() : 0;
//iterating through the data by polygon
const int lPolyCount = pMesh->GetPolygonCount();
if (lUVElement->GetMappingMode() == FbxGeometryElement::eByControlPoint)
{
for (int lPolyIndex = 0; lPolyIndex < lPolyCount; ++lPolyIndex)
{
// build the max index array that we need to pass into MakePoly
const int lPolySize = pMesh->GetPolygonSize(lPolyIndex);
for (int lVertIndex = 0; lVertIndex < lPolySize; ++lVertIndex)
{
FbxVector2 lUVValue;
//get the index of the current vertex in control points array
int lPolyVertIndex = pMesh->GetPolygonVertex(lPolyIndex, lVertIndex);
//the UV index depends on the reference mode
int lUVIndex = lUseIndex ? lUVElement->GetIndexArray().GetAt(lPolyVertIndex) : lPolyVertIndex;
lUVValue = lUVElement->GetDirectArray().GetAt(lUVIndex);
float dataU = 0, dataV = 0;
if ((float)lUVValue.mData[0] > 1.0f)
{
dataU = (float)lUVValue.mData[0] - (int)lUVValue.mData[0];
}
else if ((float)lUVValue.mData[0] < 0.0f)
{
dataU = 1.0f - ((float)lUVValue.mData[0] - (int)lUVValue.mData[0]);
}
else
{
dataU = (float)lUVValue.mData[0];
}
if ((float)lUVValue.mData[1] > 1.0f)
{
dataV = (float)lUVValue.mData[1] - (int)lUVValue.mData[1];
}
else if ((float)lUVValue.mData[1] < 0.0f)
{
dataV = 1.0f - ((float)lUVValue.mData[1] - (int)lUVValue.mData[1]);
}
else
{
dataV = (float)lUVValue.mData[1];
}
tempMeshNodeInfo->m_textureCoords.push_back(FBX_DATATYPE2(dataU, dataV));
}
}
}
else if (lUVElement->GetMappingMode() == FbxGeometryElement::eByPolygonVertex)
{
int lPolyIndexCounter = 0;
for (int lPolyIndex = 0; lPolyIndex < lPolyCount; ++lPolyIndex)
{
// build the max index array that we need to pass into MakePoly
const int lPolySize = pMesh->GetPolygonSize(lPolyIndex);
for (int lVertIndex = 0; lVertIndex < lPolySize; ++lVertIndex)
{
if (lPolyIndexCounter < lIndexCount)
{
FbxVector2 lUVValue;
//the UV index depends on the reference mode
int lUVIndex = lUseIndex ? lUVElement->GetIndexArray().GetAt(lPolyIndexCounter) : lPolyIndexCounter;
lUVValue = lUVElement->GetDirectArray().GetAt(lUVIndex);
float dataU = 0, dataV = 0;
if ((float)lUVValue.mData[0] > 1.0f)
{
dataU = (float)lUVValue.mData[0] - (int)lUVValue.mData[0];
}
else if((float)lUVValue.mData[0] < 0.0f)
{
dataU = 1.0f + ((float)lUVValue.mData[0] - (int)lUVValue.mData[0]);
}
else
{
dataU = (float)lUVValue.mData[0];
}
if ((float)lUVValue.mData[1] > 1.0f)
{
dataV = (float)lUVValue.mData[1] - (int)lUVValue.mData[1];
}
else if ((float)lUVValue.mData[1] < 0.0f)
{
dataV = 1.0f + ((float)lUVValue.mData[1] - (int)lUVValue.mData[1]);
}
else
{
dataV = (float)lUVValue.mData[1];
}
tempMeshNodeInfo->m_textureCoords.push_back(FBX_DATATYPE2((float)dataU, (float)dataV));
lPolyIndexCounter++;
}
}
}
}
}
}
FBXAnimationModelLoader::FBXAnimationModelLoader(std::string filename, float modelScale, bool isVoxel)
: FBXModelLoader(filename, modelScale, isVoxel)
{
//애니메이션 스택명 저장
m_scene->FillAnimStackNameArray(m_animStackNameArray);
//AnimationLayerData animdata;
FbxAnimStack* currAnimStack = m_scene->GetSrcObject<FbxAnimStack>(0);
FbxString animStackName = currAnimStack->GetName();
FbxTakeInfo* takeInfo = m_scene->GetTakeInfo(animStackName);
m_animTimeStart = takeInfo->mLocalTimeSpan.GetStart();
m_animTimeEnd = takeInfo->mLocalTimeSpan.GetStop();
m_animTimeLength = m_animTimeEnd.GetFrameCount(FBX_FPS)
- (m_animTimeStart.GetFrameCount(FBX_FPS) + 1);
m_path = filename;
}
FBXAnimationModelLoader::~FBXAnimationModelLoader()
{
FBXModelLoader::~FBXModelLoader();
}
void FBXAnimationModelLoader::ProcessAnimationInfo()
{
// 본(Bone) 계층구조
ProcessSkeletonHierarchy(m_scene->GetRootNode());
FbxNode* rootNode = m_scene->GetRootNode();
if (rootNode) {
this->TraversalFBXTree_forAnimation(rootNode);
}
}
void FBXAnimationModelLoader::ProcessSkeletonHierarchy(FbxNode* inRootNode)
{
for (int childIndex = 0; childIndex < inRootNode->GetChildCount(); ++childIndex)
{
FbxNode* currNode = inRootNode->GetChild(childIndex);
// 본(Bone)의 최상위의 인덱스는 -1 단계별로 뻗어갈 때보다 +1
ProcessSkeletonHierarchyRecursively(currNode, 0, 0, -1);
}
#pragma region[플레이어 캐릭터(여성) 본체계 재설정 160423]
if (m_fileName == "../Assets/02_ModelData/01_CHARACTER_MEI/Jeni.fbx"
|| m_fileName == "../Assets/02_ModelData/01_CHARACTER_MEI/Jeni_idle.fbx"
|| m_fileName == "../Assets/02_ModelData/01_CHARACTER_MEI/Jeni_running.fbx"
|| m_fileName == "../Assets/02_ModelData/01_CHARACTER_MEI/Jeni_left_strafe.fbx"
|| m_fileName == "../Assets/02_ModelData/01_CHARACTER_MEI/Jeni_right_strafe.fbx"
|| m_fileName == "../Assets/02_ModelData/01_CHARACTER_MEI/Jeni_left_forward_diagonal.fbx"
|| m_fileName == "../Assets/02_ModelData/01_CHARACTER_MEI/Jeni_right_forward_diagonal.fbx"
|| m_fileName == "../Assets/02_ModelData/01_CHARACTER_MEI/Jeni_smash.fbx"
|| m_fileName == "../Assets/02_ModelData/01_CHARACTER_MEI/Jeni_running_backward.fbx"
|| m_fileName == "../Assets/02_ModelData/01_CHARACTER_MEI/Jeni_standing_react_death_forward.FBX")
{
std::vector<Joint> tmpJoints;
tmpJoints = m_Skeleton.m_joints;
m_Skeleton.m_joints.clear();
m_Skeleton.m_joints.push_back(tmpJoints[14]); //Head
m_Skeleton.m_joints.push_back(tmpJoints[20]); //HairC1
m_Skeleton.m_joints.push_back(tmpJoints[19]); //HairC
m_Skeleton.m_joints.push_back(tmpJoints[18]); //HairB
m_Skeleton.m_joints.push_back(tmpJoints[17]); //HairA
m_Skeleton.m_joints.push_back(tmpJoints[13]); //Neck
m_Skeleton.m_joints.push_back(tmpJoints[21]); //Ponytail
m_Skeleton.m_joints.push_back(tmpJoints[22]); //Ponytail1
m_Skeleton.m_joints.push_back(tmpJoints[23]); //Ponytail2
m_Skeleton.m_joints.push_back(tmpJoints[12]); //Spine2
m_Skeleton.m_joints.push_back(tmpJoints[15]); //Bow_Left
m_Skeleton.m_joints.push_back(tmpJoints[16]); //Bow_Right
m_Skeleton.m_joints.push_back(tmpJoints[49]); //RightHand
m_Skeleton.m_joints.push_back(tmpJoints[50]); //RightHandThumb1
m_Skeleton.m_joints.push_back(tmpJoints[53]); //RightHandIndex1
m_Skeleton.m_joints.push_back(tmpJoints[56]); //RightHandMiddle1
m_Skeleton.m_joints.push_back(tmpJoints[57]); //RightHandMiddle2
m_Skeleton.m_joints.push_back(tmpJoints[58]); //RightHandMiddle3
m_Skeleton.m_joints.push_back(tmpJoints[59]); //RightHandRing1
m_Skeleton.m_joints.push_back(tmpJoints[61]); //RightHandRing3
m_Skeleton.m_joints.push_back(tmpJoints[62]); //RightHandPinky1
m_Skeleton.m_joints.push_back(tmpJoints[64]); //RightHandPinky3
m_Skeleton.m_joints.push_back(tmpJoints[54]); //RightHandIndex2
m_Skeleton.m_joints.push_back(tmpJoints[55]); //RightHandIndex3
m_Skeleton.m_joints.push_back(tmpJoints[60]); //RightHandRing2
m_Skeleton.m_joints.push_back(tmpJoints[3]); //LeftLeg
m_Skeleton.m_joints.push_back(tmpJoints[4]); //LeftFoot
m_Skeleton.m_joints.push_back(tmpJoints[5]); //LeftToeBase
m_Skeleton.m_joints.push_back(tmpJoints[9]); //RightToeBase
m_Skeleton.m_joints.push_back(tmpJoints[1]); //Pelvis
m_Skeleton.m_joints.push_back(tmpJoints[2]); //LeftUpLeg
m_Skeleton.m_joints.push_back(tmpJoints[6]); //RightUpLeg
m_Skeleton.m_joints.push_back(tmpJoints[10]); //Spine
m_Skeleton.m_joints.push_back(tmpJoints[11]); //Spine1
m_Skeleton.m_joints.push_back(tmpJoints[7]); //RightLeg
m_Skeleton.m_joints.push_back(tmpJoints[8]); //RightFoot
m_Skeleton.m_joints.push_back(tmpJoints[70]); //Belly
m_Skeleton.m_joints.push_back(tmpJoints[24]); //LeftShoulder
m_Skeleton.m_joints.push_back(tmpJoints[46]); //RightShoulder
m_Skeleton.m_joints.push_back(tmpJoints[68]); //Left_Breast
m_Skeleton.m_joints.push_back(tmpJoints[45]); //LeftUpArmCounterTwist
m_Skeleton.m_joints.push_back(tmpJoints[71]); //SkirtA
m_Skeleton.m_joints.push_back(tmpJoints[72]); //SkirtA1
m_Skeleton.m_joints.push_back(tmpJoints[75]); //SkirtB
m_Skeleton.m_joints.push_back(tmpJoints[73]); //SkirtC
m_Skeleton.m_joints.push_back(tmpJoints[76]); //SkirtB1
m_Skeleton.m_joints.push_back(tmpJoints[44]); //LeftUpArmTwist
m_Skeleton.m_joints.push_back(tmpJoints[74]); //SkirtC1
m_Skeleton.m_joints.push_back(tmpJoints[67]); //RightUpArmCounterTwist
m_Skeleton.m_joints.push_back(tmpJoints[69]); //Right_Breast
m_Skeleton.m_joints.push_back(tmpJoints[66]); //RightUpArmTwist
m_Skeleton.m_joints.push_back(tmpJoints[27]); //LeftHand
m_Skeleton.m_joints.push_back(tmpJoints[28]); //LeftHandThumb1
m_Skeleton.m_joints.push_back(tmpJoints[43]); //LeftWristTwist
m_Skeleton.m_joints.push_back(tmpJoints[29]); //LeftHandThumb2
m_Skeleton.m_joints.push_back(tmpJoints[30]); //LeftHandThumb3
m_Skeleton.m_joints.push_back(tmpJoints[33]); //LeftHandIndex3
m_Skeleton.m_joints.push_back(tmpJoints[31]); //LeftHandIndex1
m_Skeleton.m_joints.push_back(tmpJoints[32]); //LeftHandIndex2
m_Skeleton.m_joints.push_back(tmpJoints[40]); //LeftHandPinky1
m_Skeleton.m_joints.push_back(tmpJoints[41]); //LeftHandPinky2
m_Skeleton.m_joints.push_back(tmpJoints[37]); //LeftHandRing1
m_Skeleton.m_joints.push_back(tmpJoints[38]); //LeftHandRing2
m_Skeleton.m_joints.push_back(tmpJoints[34]); //LeftHandMiddle1
m_Skeleton.m_joints.push_back(tmpJoints[35]); //LeftHandMiddle2
m_Skeleton.m_joints.push_back(tmpJoints[36]); //LeftHandMiddle3
m_Skeleton.m_joints.push_back(tmpJoints[42]); //LeftHandPinky3
m_Skeleton.m_joints.push_back(tmpJoints[39]); //LeftHandRing3
m_Skeleton.m_joints.push_back(tmpJoints[26]); //LeftForeArm
m_Skeleton.m_joints.push_back(tmpJoints[52]); //RightHandThumb3
m_Skeleton.m_joints.push_back(tmpJoints[51]); //RightHandThumb2
m_Skeleton.m_joints.push_back(tmpJoints[63]); //RightHandPinky2
m_Skeleton.m_joints.push_back(tmpJoints[65]); //RightWristTwist
m_Skeleton.m_joints.push_back(tmpJoints[48]); //RightForeArm
}
#pragma endregion
#pragma region[플레이어 캐릭터(남성) 본체계 재설정 160413]
if (m_fileName == "../Assets/02_ModelData/02_CHARACTER_LIZZY/Juno.fbx"
|| m_fileName == "../Assets/02_ModelData/02_CHARACTER_LIZZY/Juno_idle.fbx"
|| m_fileName == "../Assets/02_ModelData/02_CHARACTER_LIZZY/Juno_running.fbx"
|| m_fileName == "../Assets/02_ModelData/02_CHARACTER_LIZZY/Juno_left_strafe.fbx"
|| m_fileName == "../Assets/02_ModelData/02_CHARACTER_LIZZY/Juno_right_strafe.fbx"
|| m_fileName == "../Assets/02_ModelData/02_CHARACTER_LIZZY/Juno_left_forward_diagonal.fbx"
|| m_fileName == "../Assets/02_ModelData/02_CHARACTER_LIZZY/Juno_right_forward_diagonal.fbx"
|| m_fileName == "../Assets/02_ModelData/02_CHARACTER_LIZZY/Juno_smash.fbx"
|| m_fileName == "../Assets/02_ModelData/02_CHARACTER_LIZZY/Juno_running_backward.fbx"
|| m_fileName == "../Assets/02_ModelData/02_CHARACTER_LIZZY/Juno_standing_react_death_forward.FBX")
{
std::vector<Joint> tmpJoints;
tmpJoints = m_Skeleton.m_joints;
m_Skeleton.m_joints.clear();
m_Skeleton.m_joints.push_back(tmpJoints[18]); //head
m_Skeleton.m_joints.push_back(tmpJoints[0]); //hips
m_Skeleton.m_joints.push_back(tmpJoints[69]); //RHoodieString1
m_Skeleton.m_joints.push_back(tmpJoints[70]); //RHoodieString2
m_Skeleton.m_joints.push_back(tmpJoints[16]); //Spine2
m_Skeleton.m_joints.push_back(tmpJoints[42]); //RightShoulder
m_Skeleton.m_joints.push_back(tmpJoints[68]); //RHoodieString
m_Skeleton.m_joints.push_back(tmpJoints[17]); //Neck
m_Skeleton.m_joints.push_back(tmpJoints[66]); //LHoodieString1
m_Skeleton.m_joints.push_back(tmpJoints[67]); //LHoodieString2
m_Skeleton.m_joints.push_back(tmpJoints[22]); //LeftShoulder
m_Skeleton.m_joints.push_back(tmpJoints[65]); //LHoodieString
m_Skeleton.m_joints.push_back(tmpJoints[14]); //Spine
m_Skeleton.m_joints.push_back(tmpJoints[62]); //Backpack
m_Skeleton.m_joints.push_back(tmpJoints[23]); //LeftArm
m_Skeleton.m_joints.push_back(tmpJoints[24]); //LeftForeArm
m_Skeleton.m_joints.push_back(tmpJoints[2]); //LeftUpLeg
m_Skeleton.m_joints.push_back(tmpJoints[71]); //LBackpack_Strap
m_Skeleton.m_joints.push_back(tmpJoints[43]); //RightArm
m_Skeleton.m_joints.push_back(tmpJoints[72]); //RBackpack_Strap
m_Skeleton.m_joints.push_back(tmpJoints[48]); //RightHandThumb3
m_Skeleton.m_joints.push_back(tmpJoints[51]); //RightHandIndex3
m_Skeleton.m_joints.push_back(tmpJoints[49]); //RightHandIndex1
m_Skeleton.m_joints.push_back(tmpJoints[50]); //RightHandIndex2
m_Skeleton.m_joints.push_back(tmpJoints[45]); //RightHand
m_Skeleton.m_joints.push_back(tmpJoints[47]); //RightHandThumb2
m_Skeleton.m_joints.push_back(tmpJoints[46]); //RightHandThumb1
m_Skeleton.m_joints.push_back(tmpJoints[58]); //RightHandPinky1
m_Skeleton.m_joints.push_back(tmpJoints[59]); //RightHandPinky2
m_Skeleton.m_joints.push_back(tmpJoints[60]); //RightHandPinky3
m_Skeleton.m_joints.push_back(tmpJoints[52]); //RightHandMiddle1
m_Skeleton.m_joints.push_back(tmpJoints[53]); //RightHandMiddle2
m_Skeleton.m_joints.push_back(tmpJoints[54]); //RightHandMiddle3
m_Skeleton.m_joints.push_back(tmpJoints[55]); //RightHandRing1
m_Skeleton.m_joints.push_back(tmpJoints[56]); //RightHandRing2
m_Skeleton.m_joints.push_back(tmpJoints[57]); //RightHandRing3
m_Skeleton.m_joints.push_back(tmpJoints[44]); //RightForeArm
m_Skeleton.m_joints.push_back(tmpJoints[25]); //LeftHand
m_Skeleton.m_joints.push_back(tmpJoints[26]); //LeftHandThumb1
m_Skeleton.m_joints.push_back(tmpJoints[28]); //LeftHandThumb3
m_Skeleton.m_joints.push_back(tmpJoints[31]); //LeftHandIndex3
m_Skeleton.m_joints.push_back(tmpJoints[29]); //LeftHandIndex1
m_Skeleton.m_joints.push_back(tmpJoints[30]); //LeftHandIndex2
m_Skeleton.m_joints.push_back(tmpJoints[27]); //LeftHandThumb2
m_Skeleton.m_joints.push_back(tmpJoints[38]); //LeftHandPinky1
m_Skeleton.m_joints.push_back(tmpJoints[32]); //LeftHandMiddle1
m_Skeleton.m_joints.push_back(tmpJoints[35]); //LeftHandRing1
m_Skeleton.m_joints.push_back(tmpJoints[39]); //LeftHandPinky2
m_Skeleton.m_joints.push_back(tmpJoints[40]); //LeftHandPinky3
m_Skeleton.m_joints.push_back(tmpJoints[33]); //LeftHandMiddle2
m_Skeleton.m_joints.push_back(tmpJoints[34]); //LeftHandMiddle3
m_Skeleton.m_joints.push_back(tmpJoints[37]); //LeftHandRing3
m_Skeleton.m_joints.push_back(tmpJoints[36]); //LeftHandRing2
m_Skeleton.m_joints.push_back(tmpJoints[19]); //HairB
m_Skeleton.m_joints.push_back(tmpJoints[20]); //HairA
m_Skeleton.m_joints.push_back(tmpJoints[8]); //RightUpLeg
m_Skeleton.m_joints.push_back(tmpJoints[3]); //LeftLeg
m_Skeleton.m_joints.push_back(tmpJoints[9]); //RightLeg
m_Skeleton.m_joints.push_back(tmpJoints[4]); //LeftFoot
m_Skeleton.m_joints.push_back(tmpJoints[7]); //LeftPantLeg
m_Skeleton.m_joints.push_back(tmpJoints[5]); //LeftToBase
m_Skeleton.m_joints.push_back(tmpJoints[6]); //LFootTongue
m_Skeleton.m_joints.push_back(tmpJoints[10]); //RightFoot
m_Skeleton.m_joints.push_back(tmpJoints[13]); //RightPantLeg
m_Skeleton.m_joints.push_back(tmpJoints[11]); //RightToeBase
m_Skeleton.m_joints.push_back(tmpJoints[12]); //RFootTongue
m_Skeleton.m_joints.push_back(tmpJoints[61]); //RSleeve
m_Skeleton.m_joints.push_back(tmpJoints[41]); //LSleeve
m_Skeleton.m_joints.push_back(tmpJoints[21]); //Hat
m_Skeleton.m_joints.push_back(tmpJoints[63]); //Hood
m_Skeleton.m_joints.push_back(tmpJoints[64]); //Hood1
}
#pragma endregion
//20160401 송인희 교수님이 주관하는 중간 발표에서 좀비토끼를 보여드리기 위해
//본 체계를 직접 정하여 만들었습니다.
//이러한 방식은 모델마다 따로따로 지정해야하는 만큼 비효율적인 방법이지만,
//본 체계가 망가진 모델을 다루기 위해서는 차선책입니다.
#pragma region[좀비토끼 본체계 재설정]
if (m_fileName == "../Assets/02_ModelData/03_Monster/Zombunny.FBX"
|| m_fileName == "../Assets/02_ModelData/03_Monster/Zombunny_running.fbx")
{
std::vector<Joint> tmpJoints;
tmpJoints = m_Skeleton.m_joints;
m_Skeleton.m_joints.clear();
m_Skeleton.m_joints.push_back(tmpJoints[0]);
m_Skeleton.m_joints.push_back(tmpJoints[1]);
m_Skeleton.m_joints.push_back(tmpJoints[10]);
m_Skeleton.m_joints.push_back(tmpJoints[2]);
m_Skeleton.m_joints.push_back(tmpJoints[5]);
m_Skeleton.m_joints.push_back(tmpJoints[6]);
m_Skeleton.m_joints.push_back(tmpJoints[4]);
m_Skeleton.m_joints.push_back(tmpJoints[11]);
m_Skeleton.m_joints.push_back(tmpJoints[8]);
m_Skeleton.m_joints.push_back(tmpJoints[9]);
m_Skeleton.m_joints.push_back(tmpJoints[7]);
m_Skeleton.m_joints.push_back(tmpJoints[3]);
}
#pragma endregion
}
void FBXAnimationModelLoader::ProcessSkeletonHierarchyRecursively(FbxNode* inNode, int inDepth, int myIndex, int inParentIndex)
{
if (inNode->GetNodeAttribute()
&& inNode->GetNodeAttribute()->GetAttributeType()
&& inNode->GetNodeAttribute()->GetAttributeType() == FbxNodeAttribute::eSkeleton)
{
Joint currJoint;
currJoint.mParentIndex = inParentIndex;
currJoint.mName = inNode->GetName();
m_Skeleton.m_joints.push_back(currJoint);
}
for (int i = 0; i < inNode->GetChildCount(); i++)
{
ProcessSkeletonHierarchyRecursively(inNode->GetChild(i), inDepth + 1, m_Skeleton.m_joints.size(), myIndex);
}
}
void FBXAnimationModelLoader::TraversalFBXTree_forAnimation(FbxNode* Node)
{
int numChild = Node->GetChildCount();
FbxNode *childNode = nullptr;
for (int i = 0; i < numChild; i++)
{
childNode = Node->GetChild(i);
FbxMesh *childMesh = childNode->GetMesh();
if (childMesh != nullptr)
{
if (0 == m_pMeshNodeInfo.size())
{
//20160404 애니메이션 정보에서 필요한 정보.
//메쉬 정보를 얻지 않았을 경우에도 필요하다.
//메쉬 정보가 없으면 인덱스 값만 추출한다.
FBXSDK_MESH_NODE* tempMeshNodeInfo = new FBXSDK_MESH_NODE();
tempMeshNodeInfo->m_numIndices = childMesh->GetPolygonVertexCount();
tempMeshNodeInfo->m_indices = new int[tempMeshNodeInfo->m_numIndices];
tempMeshNodeInfo->m_indices = childMesh->GetPolygonVertices();
m_pMeshNodeInfo.push_back(*tempMeshNodeInfo);
delete tempMeshNodeInfo;
}
//LoadControlPoints(childNode);
//LoadSkeletalInfo(childMesh, geometryTransform);
LoadSkeletalInfo(childNode);
}
}
}
void FBXAnimationModelLoader::LoadControlPoints(FbxNode* inNode)
{
FbxMesh* currMesh = inNode->GetMesh();
unsigned int ctrlPointCount = currMesh->GetControlPointsCount();
for (unsigned int i = 0; i < ctrlPointCount; ++i)
{
XMFLOAT3 currPosition;
currPosition.x = static_cast<float>(currMesh->GetControlPointAt(i).mData[0]);
currPosition.y = static_cast<float>(currMesh->GetControlPointAt(i).mData[1]);
currPosition.z = static_cast<float>(currMesh->GetControlPointAt(i).mData[2]);
//m_blendingInfo[i].m_position = currPosition;
}
}
void FBXAnimationModelLoader::LoadSkeletalInfo(FbxNode* inNode)
{
//int numDeformers = fbxMesh->GetDeformerCount();
FbxSkin* skin = (FbxSkin*)inNode->GetMesh()->GetDeformer(0, FbxDeformer::eSkin);
if (skin != nullptr)
{
int boneCount = skin->GetClusterCount();
std::vector<std::pair<unsigned int, std::string>> namelist;
for (int boneIndex = 0; boneIndex < boneCount; ++boneIndex)
{
FbxCluster* cluster = skin->GetCluster(boneIndex);
std::string currJointName = cluster->GetLink()->GetName();
unsigned int currJointIndex = FindJointIndexUsingName(currJointName);
namelist.push_back(make_pair(currJointIndex, currJointName));
FbxAMatrix transformMatrix;
FbxAMatrix transformLinkMatrix; //부모의 월드변환행렬
FbxAMatrix globalBindposeInverseMatrix; //본 기준위치에 역행렬
FbxNode* boneNode = cluster->GetLink();
//bind pose(본의 기준위치)의 역행렬(globalBindposeInverseMatrix) 얻기
cluster->GetTransformMatrix(transformMatrix);
cluster->GetTransformLinkMatrix(transformLinkMatrix);
//GetGeometryTransformation(inNode) : 노드의 지역행렬.
globalBindposeInverseMatrix
= transformLinkMatrix.Inverse() * transformMatrix * GetGeometryTransformation(inNode);
globalBindposeInverseMatrix.SetT(
FbxVector4(globalBindposeInverseMatrix.GetT().mData[0] * m_modelScale,
globalBindposeInverseMatrix.GetT().mData[1] * m_modelScale,
globalBindposeInverseMatrix.GetT().mData[2] * m_modelScale));
FbxAMatrix a = GetGeometryTransformation(inNode);
// Update the information in mSkeleton
m_Skeleton.m_joints[currJointIndex].mGlobalBindposeInverse
= globalBindposeInverseMatrix;
m_Skeleton.m_joints[currJointIndex].mNode
= cluster->GetLink();
//본 정점들의 인덱스 배열
int *boneVertexIndices = cluster->GetControlPointIndices();
//본 정점들의 Weight값 배열
double *boneVertexWeights = cluster->GetControlPointWeights();
// 본에 영향을 미치는 정점들을 갱신(스키닝)
int numBoneVertexIndices = cluster->GetControlPointIndicesCount();
for (int i = 0; i < numBoneVertexIndices; i++)
{
//20160317
m_blendingInfo[boneVertexIndices[i]].mInfo
.push_back(std::make_pair(currJointIndex, (float)cluster->GetControlPointWeights()[i]));
}
//매 프레임 당 애니메이션 변환행렬 추출
for (FbxLongLong frameCount = m_animTimeStart.GetFrameCount(FBX_FPS); frameCount <= m_animTimeEnd.GetFrameCount(FBX_FPS); ++frameCount)
{
FbxTime currentTime;
currentTime.SetFrame(frameCount, FBX_FPS);
KeyFrame tempKeyFrame;
tempKeyFrame.mFrameNum = (int)frameCount;
FbxAMatrix currnetTransformOffset = inNode->EvaluateGlobalTransform(currentTime) * GetGeometryTransformation(inNode);
tempKeyFrame.mGlobalTransform
= currnetTransformOffset.Inverse() * cluster->GetLink()->EvaluateGlobalTransform(currentTime);
tempKeyFrame.mGlobalTransform.SetT(
FbxVector4(tempKeyFrame.mGlobalTransform.GetT().mData[0] * m_modelScale,
tempKeyFrame.mGlobalTransform.GetT().mData[1] * m_modelScale,
tempKeyFrame.mGlobalTransform.GetT().mData[2] * m_modelScale));
m_Skeleton.m_joints[boneIndex].mKeyFrames.push_back(tempKeyFrame);
}
}
//if (m_fileName == "../Assets/02_ModelData/01_CHARACTER_MEI/Claire.fbx"
// || m_fileName == "../Assets/02_ModelData/01_CHARACTER_MEI/Claire_running.fbx")
//{
// std::cout << namelist.begin()->first << " / "<< namelist.begin()->second << std::endl;
//}
}
}
//노드의 지역행렬을 구한다.
FbxAMatrix FBXAnimationModelLoader::GetGeometryTransformation(FbxNode* inNode)
{
if (!inNode)
{
throw std::exception("Null for mesh geometry");
}
const FbxVector4 lT = inNode->GetGeometricTranslation(FbxNode::eSourcePivot);
const FbxVector4 lR = inNode->GetGeometricRotation(FbxNode::eSourcePivot);
const FbxVector4 lS = inNode->GetGeometricScaling(FbxNode::eSourcePivot);
return FbxAMatrix(lT, lR, lS);
}
unsigned int FBXAnimationModelLoader::FindJointIndexUsingName(std::string jointName)
{
for (unsigned int i = 0; i < m_Skeleton.m_joints.size(); i++)
{
if (m_Skeleton.m_joints[i].mName == jointName)
{
return i;
}
}
//영태가 임의로 추가
return 0;
}
FbxAMatrix FBXAnimationModelLoader::GetSkeletonJointGlobalTransform(unsigned int jointIndex, int keyframeNum)
{
if (GetSkeletonJoint(jointIndex).mKeyFrames.size() != 0)
{
return GetSkeletonJoint(jointIndex).mKeyFrames[keyframeNum].mGlobalTransform;
}
else
{
FbxAMatrix m;
m.SetIdentity();
return m;
}
}
bool FBXAnimationModelLoader::HasAnitamionKeyframe()
{
if (m_Skeleton.m_joints.cbegin()->mKeyFrames.size() != 0)
{
return true;
}
else
return false;
} | [
"on1659@naver.com"
] | on1659@naver.com |
6a09a591c744bd8673b30931db53e70d3c12cc66 | 7d1f7bbe443df15811dbc523fcd1d4e08e5f5dc6 | /test/client/UdpClient.cpp | 76636a48be0c681c4e7e946e59b72e79d9fd8846 | [
"MIT"
] | permissive | prsood/kuma | 508fc9b15b77de054b3e6d1478eb3d87f6247cf7 | 467a38ef1df376c4f043cc57c190b57a7b1bad3e | refs/heads/master | 2021-01-22T03:49:27.409739 | 2017-05-24T10:18:07 | 2017-05-24T10:18:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,286 | cpp | #include "UdpClient.h"
#if defined(KUMA_OS_WIN)
# include <Ws2tcpip.h>
#else
# include <arpa/inet.h>
#endif
UdpClient::UdpClient(TestLoop* loop, long conn_id)
: loop_(loop)
, udp_(loop->eventLoop())
, conn_id_(conn_id)
, index_(0)
, max_send_count_(200000)
{
}
KMError UdpClient::bind(const char* bind_host, uint16_t bind_port)
{
udp_.setReadCallback([this] (KMError err) { onReceive(err); });
udp_.setErrorCallback([this] (KMError err) { onClose(err); });
return udp_.bind(bind_host, bind_port);
}
int UdpClient::close()
{
udp_.close();
return 0;
}
void UdpClient::startSend(const char* host, uint16_t port)
{
host_ = host;
port_ = port;
start_point_ = std::chrono::steady_clock::now();
sendData();
}
void UdpClient::sendData()
{
uint8_t buf[1024];
*(uint32_t*)buf = htonl(++index_);
udp_.send(buf, sizeof(buf), host_.c_str(), port_);
}
void UdpClient::onReceive(KMError err)
{
char buf[4096] = {0};
char ip[128];
uint16_t port = 0;
do {
int bytes_read = udp_.receive((uint8_t*)buf, sizeof(buf), ip, sizeof(ip), port);
if(bytes_read > 0) {
uint32_t index = 0;
if(bytes_read >= 4) {
index = ntohl(*(uint32_t*)buf);
}
if(index % 10000 == 0) {
printf("UdpClient::onReceive, bytes_read=%d, index=%d\n", bytes_read, index);
}
if(index < max_send_count_) {
sendData();
} else {
std::chrono::steady_clock::time_point end_point = std::chrono::steady_clock::now();
std::chrono::milliseconds diff_ms = std::chrono::duration_cast<std::chrono::milliseconds>(end_point - start_point_);
printf("spent %lld ms to echo %u packets\n", diff_ms.count(), max_send_count_);
break;
}
} else if (0 == bytes_read) {
break;
} else {
printf("UdpClient::onReceive, err=%d\n", getLastError());
break;
}
} while (true);
}
void UdpClient::onClose(KMError err)
{
printf("UdpClient::onClose, err=%d\n", err);
udp_.close();
loop_->removeObject(conn_id_);
}
| [
"jamol@live.com"
] | jamol@live.com |
d908418926af5809ec1b43f63a364bebb68743a5 | 1b4a242e63b5bb031c98eaa373588600f828eb3e | /Source/SplineDemo4/SplineDemo4.cpp | 54e324f6ee9b73174c935bd153398352cf05162f | [] | no_license | shankarghimire/SplineUsingCPP | 4452012f793201c36c96615a0a9a467b11e350c3 | 3775965332490618b69846864f1456da0ac782df | refs/heads/main | 2023-03-17T22:06:00.573933 | 2021-03-08T13:37:50 | 2021-03-08T13:37:50 | 345,010,086 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 198 | cpp | // Copyright Epic Games, Inc. All Rights Reserved.
#include "SplineDemo4.h"
#include "Modules/ModuleManager.h"
IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, SplineDemo4, "SplineDemo4" );
| [
"ssghimire@gmail.com"
] | ssghimire@gmail.com |
fc53a976e99d8fbfb50cef18b69cb62b7129fdad | 128b6ad7c062e7c5025530e6abd5bfe1e679a49c | /src/rpc/names.cpp | dca149e3d656b208c8aacd3eba7f87d624e8776d | [
"MIT"
] | permissive | sbnair/xaya | 16ee6c66d3388e32c8a266755001ee1cbe579856 | f5899f10752e02fae2acfbee2e10d8ef0271922c | refs/heads/master | 2022-06-05T20:18:59.816489 | 2020-04-27T11:24:57 | 2020-04-27T11:24:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,543 | cpp | // Copyright (c) 2014-2020 Daniel Kraft
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <base58.h>
#include <chainparams.h>
#include <core_io.h>
#include <init.h>
#include <key_io.h>
#include <names/common.h>
#include <names/main.h>
#include <primitives/transaction.h>
#include <rpc/names.h>
#include <rpc/server.h>
#include <script/names.h>
#include <txmempool.h>
#include <util/strencodings.h>
#include <validation.h>
#ifdef ENABLE_WALLET
# include <wallet/rpcwallet.h>
# include <wallet/wallet.h>
#endif
#include <univalue.h>
#include <boost/xpressive/xpressive_dynamic.hpp>
#include <algorithm>
#include <cassert>
#include <memory>
#include <stdexcept>
namespace
{
NameEncoding
EncodingFromOptionsJson (const UniValue& options, const std::string& field,
const NameEncoding defaultValue)
{
NameEncoding res = defaultValue;
RPCTypeCheckObj (options,
{
{field, UniValueType (UniValue::VSTR)},
},
true, false);
if (options.exists (field))
try
{
res = EncodingFromString (options[field].get_str ());
}
catch (const std::invalid_argument& exc)
{
LogPrintf ("Invalid value for %s in options: %s\n using default %s\n",
field, exc.what (), EncodingToString (defaultValue));
}
return res;
}
} // anonymous namespace
/**
* Utility routine to construct a "name info" object to return. This is used
* for name_show and also name_list.
*/
UniValue
getNameInfo (const UniValue& options,
const valtype& name, const valtype& value,
const COutPoint& outp, const CScript& addr)
{
UniValue obj(UniValue::VOBJ);
AddEncodedNameToUniv (obj, "name", name,
EncodingFromOptionsJson (options, "nameEncoding",
ConfiguredNameEncoding ()));
AddEncodedNameToUniv (obj, "value", value,
EncodingFromOptionsJson (options, "valueEncoding",
ConfiguredValueEncoding ()));
obj.pushKV ("txid", outp.hash.GetHex ());
obj.pushKV ("vout", static_cast<int> (outp.n));
/* Try to extract the address. May fail if we can't parse the script
as a "standard" script. */
CTxDestination dest;
std::string addrStr;
if (ExtractDestination (addr, dest))
addrStr = EncodeDestination (dest);
else
addrStr = "<nonstandard>";
obj.pushKV ("address", addrStr);
return obj;
}
/**
* Return name info object for a CNameData object.
*/
UniValue
getNameInfo (const UniValue& options,
const valtype& name, const CNameData& data)
{
UniValue result = getNameInfo (options,
name, data.getValue (),
data.getUpdateOutpoint (),
data.getAddress ());
addHeightInfo (data.getHeight (), result);
return result;
}
void
addHeightInfo (const int height, UniValue& data)
{
data.pushKV ("height", height);
}
#ifdef ENABLE_WALLET
/**
* Adds the "ismine" field giving ownership info to the JSON object.
*/
void
addOwnershipInfo (const CScript& addr, const CWallet* pwallet,
UniValue& data)
{
if (pwallet == nullptr)
return;
AssertLockHeld (pwallet->cs_wallet);
const isminetype mine = pwallet->IsMine (addr);
const bool isMine = (mine & ISMINE_SPENDABLE);
data.pushKV ("ismine", isMine);
}
#endif
namespace
{
valtype
DecodeNameValueFromRPCOrThrow (const UniValue& val, const UniValue& opt,
const std::string& optKey,
const NameEncoding defaultEnc)
{
const NameEncoding enc = EncodingFromOptionsJson (opt, optKey, defaultEnc);
try
{
return DecodeName (val.get_str (), enc);
}
catch (const InvalidNameString& exc)
{
std::ostringstream msg;
msg << "Name/value is invalid for encoding " << EncodingToString (enc);
throw JSONRPCError (RPC_NAME_INVALID_ENCODING, msg.str ());
}
}
} // anonymous namespace
valtype
DecodeNameFromRPCOrThrow (const UniValue& val, const UniValue& opt)
{
return DecodeNameValueFromRPCOrThrow (val, opt, "nameEncoding",
ConfiguredNameEncoding ());
}
valtype
DecodeValueFromRPCOrThrow (const UniValue& val, const UniValue& opt)
{
return DecodeNameValueFromRPCOrThrow (val, opt, "valueEncoding",
ConfiguredValueEncoding ());
}
namespace
{
/**
* Helper class that extracts the wallet for the current RPC request, if any.
* It handles the case of disabled wallet support or no wallet being present,
* so that it is suitable for the non-wallet RPCs here where we just want to
* provide optional extra features (like the "ismine" field).
*
* The main benefit of having this class is that we can easily LOCK2 with the
* wallet and another lock we need, without having to care about the special
* cases where no wallet is present or wallet support is disabled.
*/
class MaybeWalletForRequest
{
private:
#ifdef ENABLE_WALLET
std::shared_ptr<CWallet> wallet;
#endif
public:
explicit MaybeWalletForRequest (const JSONRPCRequest& request)
{
#ifdef ENABLE_WALLET
wallet = GetWalletForJSONRPCRequest (request);
#endif
}
RecursiveMutex*
getLock () const
{
#ifdef ENABLE_WALLET
return (wallet != nullptr ? &wallet->cs_wallet : nullptr);
#else
return nullptr;
#endif
}
#ifdef ENABLE_WALLET
CWallet*
getWallet ()
{
return wallet.get ();
}
const CWallet*
getWallet () const
{
return wallet.get ();
}
#endif
};
/**
* Variant of addOwnershipInfo that uses a MaybeWalletForRequest. This takes
* care of disabled wallet support.
*/
void
addOwnershipInfo (const CScript& addr, const MaybeWalletForRequest& wallet,
UniValue& data)
{
#ifdef ENABLE_WALLET
addOwnershipInfo (addr, wallet.getWallet (), data);
#endif
}
/**
* Utility variant of getNameInfo that already includes ownership information.
* This is the most common call for methods in this file.
*/
UniValue
getNameInfo (const UniValue& options,
const valtype& name, const CNameData& data,
const MaybeWalletForRequest& wallet)
{
UniValue res = getNameInfo (options, name, data);
addOwnershipInfo (data.getAddress (), wallet, res);
return res;
}
} // anonymous namespace
/* ************************************************************************** */
NameInfoHelp::NameInfoHelp ()
{
withField ({RPCResult::Type::STR, "name", "the requested name"});
withField ({RPCResult::Type::STR, "name_encoding", "the encoding of \"name\""});
withField ({RPCResult::Type::STR, "name_error",
"replaces \"name\" in case there is an error"});
withField ({RPCResult::Type::STR, "value", "the name's current value"});
withField ({RPCResult::Type::STR, "value_encoding", "the encoding of \"value\""});
withField ({RPCResult::Type::STR, "value_error",
"replaces \"value\" in case there is an error"});
withField ({RPCResult::Type::STR_HEX, "txid", "the name's last update tx"});
withField ({RPCResult::Type::NUM, "vout",
"the index of the name output in the last update"});
withField ({RPCResult::Type::STR, "address", "the address holding the name"});
#ifdef ENABLE_WALLET
withField ({RPCResult::Type::BOOL, "ismine",
"whether the name is owned by the wallet"});
#endif
}
NameInfoHelp&
NameInfoHelp::withHeight ()
{
withField ({RPCResult::Type::NUM, "height", "the name's last update height"});
return *this;
}
NameOptionsHelp::NameOptionsHelp ()
{}
NameOptionsHelp&
NameOptionsHelp::withArg (const std::string& name, const RPCArg::Type type,
const std::string& doc)
{
return withArg (name, type, "", doc);
}
NameOptionsHelp&
NameOptionsHelp::withArg (const std::string& name, const RPCArg::Type type,
const std::string& defaultValue,
const std::string& doc)
{
if (defaultValue.empty ())
innerArgs.push_back (RPCArg (name, type, RPCArg::Optional::OMITTED, doc));
else
innerArgs.push_back (RPCArg (name, type, defaultValue, doc));
return *this;
}
NameOptionsHelp&
NameOptionsHelp::withWriteOptions ()
{
withArg ("destAddress", RPCArg::Type::STR,
"The address to send the name output to");
withArg ("sendCoins", RPCArg::Type::OBJ_USER_KEYS,
"Addresses to which coins should be sent additionally");
withArg ("burn", RPCArg::Type::OBJ_USER_KEYS,
"Data and amounts of CHI to burn in the transaction");
return *this;
}
NameOptionsHelp&
NameOptionsHelp::withNameEncoding ()
{
withArg ("nameEncoding", RPCArg::Type::STR,
"Encoding (\"ascii\", \"utf8\" or \"hex\") of the name argument");
return *this;
}
NameOptionsHelp&
NameOptionsHelp::withValueEncoding ()
{
withArg ("valueEncoding", RPCArg::Type::STR,
"Encoding (\"ascii\", \"utf8\" or \"hex\") of the value argument");
return *this;
}
RPCArg
NameOptionsHelp::buildRpcArg () const
{
return RPCArg ("options", RPCArg::Type::OBJ,
RPCArg::Optional::OMITTED_NAMED_ARG,
"Options for this RPC call",
innerArgs, "options");
}
/* ************************************************************************** */
namespace
{
UniValue
name_show (const JSONRPCRequest& request)
{
NameOptionsHelp optHelp;
optHelp
.withNameEncoding ()
.withValueEncoding ();
RPCHelpMan ("name_show",
"\nLooks up the current data for the given name. Fails if the name doesn't exist.\n",
{
{"name", RPCArg::Type::STR, RPCArg::Optional::NO, "The name to query for"},
optHelp.buildRpcArg (),
},
NameInfoHelp ()
.withHeight ()
.finish (),
RPCExamples {
HelpExampleCli ("name_show", "\"myname\"")
+ HelpExampleRpc ("name_show", "\"myname\"")
}
).Check (request);
RPCTypeCheck (request.params, {UniValue::VSTR, UniValue::VOBJ});
if (::ChainstateActive ().IsInitialBlockDownload ())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD,
"Xaya is downloading blocks...");
UniValue options(UniValue::VOBJ);
if (request.params.size () >= 2)
options = request.params[1].get_obj ();
const valtype name
= DecodeNameFromRPCOrThrow (request.params[0], options);
CNameData data;
{
LOCK (cs_main);
if (!::ChainstateActive ().CoinsTip ().GetName (name, data))
{
std::ostringstream msg;
msg << "name not found: " << EncodeNameForMessage (name);
throw JSONRPCError (RPC_WALLET_ERROR, msg.str ());
}
}
MaybeWalletForRequest wallet(request);
LOCK2 (cs_main, wallet.getLock ());
return getNameInfo (options, name, data, wallet);
}
/* ************************************************************************** */
UniValue
name_history (const JSONRPCRequest& request)
{
NameOptionsHelp optHelp;
optHelp
.withNameEncoding ()
.withValueEncoding ();
RPCHelpMan ("name_history",
"\nLooks up the current and all past data for the given name. -namehistory must be enabled.\n",
{
{"name", RPCArg::Type::STR, RPCArg::Optional::NO, "The name to query for"},
optHelp.buildRpcArg (),
},
RPCResult {RPCResult::Type::ARR, "", "",
{
NameInfoHelp ()
.withHeight ()
.finish ()
}
},
RPCExamples {
HelpExampleCli ("name_history", "\"myname\"")
+ HelpExampleRpc ("name_history", "\"myname\"")
}
).Check (request);
RPCTypeCheck (request.params, {UniValue::VSTR, UniValue::VOBJ});
if (!fNameHistory)
throw std::runtime_error ("-namehistory is not enabled");
if (::ChainstateActive ().IsInitialBlockDownload ())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD,
"Xaya is downloading blocks...");
UniValue options(UniValue::VOBJ);
if (request.params.size () >= 2)
options = request.params[1].get_obj ();
const valtype name
= DecodeNameFromRPCOrThrow (request.params[0], options);
CNameData data;
CNameHistory history;
{
LOCK (cs_main);
const auto& coinsTip = ::ChainstateActive ().CoinsTip ();
if (!coinsTip.GetName (name, data))
{
std::ostringstream msg;
msg << "name not found: " << EncodeNameForMessage (name);
throw JSONRPCError (RPC_WALLET_ERROR, msg.str ());
}
if (!coinsTip.GetNameHistory (name, history))
assert (history.empty ());
}
MaybeWalletForRequest wallet(request);
LOCK2 (cs_main, wallet.getLock ());
UniValue res(UniValue::VARR);
for (const auto& entry : history.getData ())
res.push_back (getNameInfo (options, name, entry, wallet));
res.push_back (getNameInfo (options, name, data, wallet));
return res;
}
/* ************************************************************************** */
UniValue
name_scan (const JSONRPCRequest& request)
{
NameOptionsHelp optHelp;
optHelp
.withNameEncoding ()
.withValueEncoding ()
.withArg ("minConf", RPCArg::Type::NUM, "1",
"Minimum number of confirmations")
.withArg ("maxConf", RPCArg::Type::NUM,
"Maximum number of confirmations")
.withArg ("prefix", RPCArg::Type::STR,
"Filter for names with the given prefix")
.withArg ("regexp", RPCArg::Type::STR,
"Filter for names matching the regexp");
RPCHelpMan ("name_scan",
"\nLists names in the database.\n",
{
{"start", RPCArg::Type::STR, "", "Skip initially to this name"},
{"count", RPCArg::Type::NUM, "500", "Stop after this many names"},
optHelp.buildRpcArg (),
},
RPCResult {RPCResult::Type::ARR, "", "",
{
NameInfoHelp ()
.withHeight ()
.finish ()
}
},
RPCExamples {
HelpExampleCli ("name_scan", "")
+ HelpExampleCli ("name_scan", "\"d/abc\"")
+ HelpExampleCli ("name_scan", "\"d/abc\" 10")
+ HelpExampleRpc ("name_scan", "\"d/abc\"")
}
).Check (request);
RPCTypeCheck (request.params,
{UniValue::VSTR, UniValue::VNUM, UniValue::VOBJ});
if (::ChainstateActive ().IsInitialBlockDownload ())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD,
"Xaya is downloading blocks...");
UniValue options(UniValue::VOBJ);
if (request.params.size () >= 3)
options = request.params[2].get_obj ();
valtype start;
if (request.params.size () >= 1)
start = DecodeNameFromRPCOrThrow (request.params[0], options);
int count = 500;
if (request.params.size () >= 2)
count = request.params[1].get_int ();
/* Parse and interpret the name_scan-specific options. */
RPCTypeCheckObj (options,
{
{"minConf", UniValueType (UniValue::VNUM)},
{"maxConf", UniValueType (UniValue::VNUM)},
{"prefix", UniValueType (UniValue::VSTR)},
{"regexp", UniValueType (UniValue::VSTR)},
},
true, false);
int minConf = 1;
if (options.exists ("minConf"))
minConf = options["minConf"].get_int ();
if (minConf < 1)
throw JSONRPCError (RPC_INVALID_PARAMETER, "minConf must be >= 1");
int maxConf = -1;
if (options.exists ("maxConf"))
{
maxConf = options["maxConf"].get_int ();
if (maxConf < 0)
throw JSONRPCError (RPC_INVALID_PARAMETER,
"maxConf must not be negative");
}
valtype prefix;
if (options.exists ("prefix"))
prefix = DecodeNameFromRPCOrThrow (options["prefix"], options);
bool haveRegexp = false;
boost::xpressive::sregex regexp;
if (options.exists ("regexp"))
{
haveRegexp = true;
regexp = boost::xpressive::sregex::compile (options["regexp"].get_str ());
}
/* Iterate over names and produce the result. */
UniValue res(UniValue::VARR);
if (count <= 0)
return res;
MaybeWalletForRequest wallet(request);
LOCK2 (cs_main, wallet.getLock ());
const int maxHeight = ::ChainActive ().Height () - minConf + 1;
int minHeight = -1;
if (maxConf >= 0)
minHeight = ::ChainActive ().Height () - maxConf + 1;
valtype name;
CNameData data;
const auto& coinsTip = ::ChainstateActive ().CoinsTip ();
std::unique_ptr<CNameIterator> iter(coinsTip.IterateNames ());
for (iter->seek (start); count > 0 && iter->next (name, data); )
{
const int height = data.getHeight ();
if (height > maxHeight)
continue;
if (minHeight >= 0 && height < minHeight)
continue;
if (name.size () < prefix.size ())
continue;
if (!std::equal (prefix.begin (), prefix.end (), name.begin ()))
continue;
if (haveRegexp)
{
try
{
const std::string nameStr = EncodeName (name, NameEncoding::UTF8);
boost::xpressive::smatch matches;
if (!boost::xpressive::regex_search (nameStr, matches, regexp))
continue;
}
catch (const InvalidNameString& exc)
{
continue;
}
}
res.push_back (getNameInfo (options, name, data, wallet));
--count;
}
return res;
}
/* ************************************************************************** */
UniValue
name_pending (const JSONRPCRequest& request)
{
NameOptionsHelp optHelp;
optHelp
.withNameEncoding ()
.withValueEncoding ();
RPCHelpMan ("name_pending",
"\nLists unconfirmed name operations in the mempool.\n"
"\nIf a name is given, only check for operations on this name.\n",
{
{"name", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, "Only look for this name"},
optHelp.buildRpcArg (),
},
RPCResult {RPCResult::Type::ARR, "", "",
{
NameInfoHelp ()
.withField ({RPCResult::Type::STR, "op", "the operation being performed"})
.withHeight ()
.finish ()
}
},
RPCExamples {
HelpExampleCli ("name_pending", "")
+ HelpExampleCli ("name_pending", "\"d/domob\"")
+ HelpExampleRpc ("name_pending", "")
}
).Check (request);
RPCTypeCheck (request.params, {UniValue::VSTR, UniValue::VOBJ}, true);
MaybeWalletForRequest wallet(request);
LOCK2 (wallet.getLock (), mempool.cs);
UniValue options(UniValue::VOBJ);
if (request.params.size () >= 2)
options = request.params[1].get_obj ();
std::vector<uint256> txHashes;
mempool.queryHashes (txHashes);
const bool hasNameFilter = !request.params[0].isNull ();
valtype nameFilter;
if (hasNameFilter)
nameFilter = DecodeNameFromRPCOrThrow (request.params[0], options);
UniValue arr(UniValue::VARR);
for (const auto& txHash : txHashes)
{
std::shared_ptr<const CTransaction> tx = mempool.get (txHash);
if (!tx)
continue;
for (size_t n = 0; n < tx->vout.size (); ++n)
{
const auto& txOut = tx->vout[n];
const CNameScript op(txOut.scriptPubKey);
if (!op.isNameOp () || !op.isAnyUpdate ())
continue;
if (hasNameFilter && op.getOpName () != nameFilter)
continue;
UniValue obj = getNameInfo (options,
op.getOpName (), op.getOpValue (),
COutPoint (tx->GetHash (), n),
op.getAddress ());
addOwnershipInfo (op.getAddress (), wallet, obj);
switch (op.getNameOp ())
{
case OP_NAME_REGISTER:
obj.pushKV ("op", "name_register");
break;
case OP_NAME_UPDATE:
obj.pushKV ("op", "name_update");
break;
default:
assert (false);
}
arr.push_back (obj);
}
}
return arr;
}
/* ************************************************************************** */
UniValue
namerawtransaction (const JSONRPCRequest& request)
{
RPCHelpMan ("namerawtransaction",
"\nAdds a name operation to an existing raw transaction.\n"
"\nUse createrawtransaction first to create the basic transaction, including the required inputs and outputs also for the name.\n",
{
{"hexstring", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction hex string"},
{"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The vout of the desired name output"},
{"nameop", RPCArg::Type::OBJ, RPCArg::Optional::NO, "The name operation to create",
{
{"op", RPCArg::Type::STR, RPCArg::Optional::NO, "The operation to perform, can be \"name_new\", \"name_firstupdate\" and \"name_update\""},
{"name", RPCArg::Type::STR, RPCArg::Optional::NO, "The name to operate on"},
{"value", RPCArg::Type::STR, RPCArg::Optional::NO, "The new value for the name"},
},
"nameop"},
},
RPCResult {RPCResult::Type::OBJ, "", "",
{
{RPCResult::Type::STR_HEX, "hex", "Hex string of the updated transaction"},
},
},
RPCExamples {
HelpExampleCli ("namerawtransaction", R"("raw tx hex" 1 "{\"op\":\"name_register\",\"name\":\"my-name\",\"value\":\"new value\")")
+ HelpExampleCli ("namerawtransaction", R"("raw tx hex" 1 "{\"op\":\"name_update\",\"name\":\"my-name\",\"value\":\"new value\")")
+ HelpExampleRpc ("namerawtransaction", R"("raw tx hex", 1, "{\"op\":\"name_update\",\"name\":\"my-name\",\"value\":\"new value\")")
}
).Check (request);
RPCTypeCheck (request.params,
{UniValue::VSTR, UniValue::VNUM, UniValue::VOBJ});
CMutableTransaction mtx;
if (!DecodeHexTx (mtx, request.params[0].get_str (), true))
throw JSONRPCError (RPC_DESERIALIZATION_ERROR, "TX decode failed");
const size_t nOut = request.params[1].get_int ();
if (nOut >= mtx.vout.size ())
throw JSONRPCError (RPC_INVALID_PARAMETER, "vout is out of range");
/* namerawtransaction does not have an options argument. This would just
make the already long list of arguments longer. Instead of using
namerawtransaction, namecoin-tx can be used anyway to create name
operations with arbitrary hex data. */
const UniValue NO_OPTIONS(UniValue::VOBJ);
const UniValue nameOp = request.params[2].get_obj ();
RPCTypeCheckObj (nameOp,
{
{"op", UniValueType (UniValue::VSTR)},
{"name", UniValueType (UniValue::VSTR)},
{"value", UniValueType (UniValue::VSTR)},
}
);
const std::string op = find_value (nameOp, "op").get_str ();
const valtype name
= DecodeNameFromRPCOrThrow (find_value (nameOp, "name"), NO_OPTIONS);
const valtype value
= DecodeValueFromRPCOrThrow (find_value (nameOp, "value"), NO_OPTIONS);
UniValue result(UniValue::VOBJ);
if (op == "name_register")
mtx.vout[nOut].scriptPubKey
= CNameScript::buildNameRegister (mtx.vout[nOut].scriptPubKey,
name, value);
else if (op == "name_update")
mtx.vout[nOut].scriptPubKey
= CNameScript::buildNameUpdate (mtx.vout[nOut].scriptPubKey,
name, value);
else
throw JSONRPCError (RPC_INVALID_PARAMETER, "Invalid name operation");
result.pushKV ("hex", EncodeHexTx (CTransaction (mtx)));
return result;
}
/* ************************************************************************** */
UniValue
name_checkdb (const JSONRPCRequest& request)
{
RPCHelpMan ("name_checkdb",
"\nValidates the name DB's consistency.\n"
"\nRoughly between blocks 139,000 and 180,000, this call is expected to fail due to the historic 'name stealing' bug.\n",
{},
RPCResult {RPCResult::Type::BOOL, "", "whether the state is valid"},
RPCExamples {
HelpExampleCli ("name_checkdb", "")
+ HelpExampleRpc ("name_checkdb", "")
}
).Check (request);
LOCK (cs_main);
auto& coinsTip = ::ChainstateActive ().CoinsTip ();
coinsTip.Flush ();
return coinsTip.ValidateNameDB ();
}
} // namespace
/* ************************************************************************** */
void RegisterNameRPCCommands(CRPCTable &t)
{
static const CRPCCommand commands[] =
{ // category name actor (function) argNames
// --------------------- ------------------------ ----------------------- ----------
{ "names", "name_show", &name_show, {"name","options"} },
{ "names", "name_history", &name_history, {"name","options"} },
{ "names", "name_scan", &name_scan, {"start","count","options"} },
{ "names", "name_pending", &name_pending, {"name","options"} },
{ "names", "name_checkdb", &name_checkdb, {} },
{ "rawtransactions", "namerawtransaction", &namerawtransaction, {"hexstring","vout","nameop"} },
};
for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
t.appendCommand(commands[vcidx].name, &commands[vcidx]);
}
| [
"d@domob.eu"
] | d@domob.eu |
b86ba09a1dfc490efed03ded06b2045bebcfb1e3 | dde00a05cfe6e4704b723862d7249e45cc27d78a | /src/stream/MUL-OMPTarget.cpp | 53d018d6487ceb64661980c8a0b371ec6f8d7afe | [
"BSD-3-Clause"
] | permissive | brandonneth/RAJAPerf | c4a43e2f1690cd2ffeffb79a7e7a1fd249dc59af | f71b30d0dcf0ab86845bbefb492264ebfa15e8ac | refs/heads/develop | 2023-03-03T13:58:02.410360 | 2021-08-20T22:24:51 | 2021-08-20T22:24:51 | 219,371,216 | 0 | 0 | BSD-3-Clause | 2022-01-06T18:48:50 | 2019-11-03T21:59:26 | C++ | UTF-8 | C++ | false | false | 2,273 | cpp | //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Copyright (c) 2017-21, Lawrence Livermore National Security, LLC
// and RAJA Performance Suite project contributors.
// See the RAJAPerf/LICENSE file for details.
//
// SPDX-License-Identifier: (BSD-3-Clause)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
#include "MUL.hpp"
#include "RAJA/RAJA.hpp"
#if defined(RAJA_ENABLE_TARGET_OPENMP)
#include "common/OpenMPTargetDataUtils.hpp"
#include <iostream>
namespace rajaperf
{
namespace stream
{
//
// Define threads per team for target execution
//
const size_t threads_per_team = 256;
#define MUL_DATA_SETUP_OMP_TARGET \
int hid = omp_get_initial_device(); \
int did = omp_get_default_device(); \
\
allocAndInitOpenMPDeviceData(b, m_b, iend, did, hid); \
allocAndInitOpenMPDeviceData(c, m_c, iend, did, hid);
#define MUL_DATA_TEARDOWN_OMP_TARGET \
getOpenMPDeviceData(m_b, b, iend, hid, did); \
deallocOpenMPDeviceData(b, did); \
deallocOpenMPDeviceData(c, did);
void MUL::runOpenMPTargetVariant(VariantID vid)
{
const Index_type run_reps = getRunReps();
const Index_type ibegin = 0;
const Index_type iend = getActualProblemSize();
MUL_DATA_SETUP;
if ( vid == Base_OpenMPTarget ) {
MUL_DATA_SETUP_OMP_TARGET;
startTimer();
for (RepIndex_type irep = 0; irep < run_reps; ++irep) {
#pragma omp target is_device_ptr(b, c) device( did )
#pragma omp teams distribute parallel for thread_limit(threads_per_team) schedule(static, 1)
for (Index_type i = ibegin; i < iend; ++i ) {
MUL_BODY;
}
}
stopTimer();
MUL_DATA_TEARDOWN_OMP_TARGET;
} else if ( vid == RAJA_OpenMPTarget ) {
MUL_DATA_SETUP_OMP_TARGET;
startTimer();
for (RepIndex_type irep = 0; irep < run_reps; ++irep) {
RAJA::forall<RAJA::omp_target_parallel_for_exec<threads_per_team>>(
RAJA::RangeSegment(ibegin, iend), [=](Index_type i) {
MUL_BODY;
});
}
stopTimer();
MUL_DATA_TEARDOWN_OMP_TARGET;
} else {
std::cout << "\n MUL : Unknown OMP Target variant id = " << vid << std::endl;
}
}
} // end namespace stream
} // end namespace rajaperf
#endif // RAJA_ENABLE_TARGET_OPENMP
| [
"hornung1@llnl.gov"
] | hornung1@llnl.gov |
f13331bc73c98d5fdeba98a18802c7ccb3c7dc8f | 286bbf17db63fe00aa9b2190e905eef7f07d9ef2 | /social-graph-dynamics/Network_Dynamics/SocialNetworkAlgorithm.h | 35ee9c3bec68164ff080a0c527506072611fc6d4 | [] | no_license | muggin/agh-coursework | 7a4766ca7c966c724a540354f31f94c43e2d005b | 7a452d4bf73bbc0daa4404fde64f9dc734899f31 | refs/heads/master | 2021-07-20T19:31:20.340059 | 2017-10-25T21:55:25 | 2017-10-25T21:55:25 | 106,218,163 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,820 | h | //
// SocialNetworkAlgorithm.h
// Social Network
//
// Created by Aleksander Wójcik on 01.12.2014.
// Copyright (c) 2014 Aleksander Wójcik. All rights reserved.
//
#ifndef __Social_Network__SocialNetworkAlgorithm__
#define __Social_Network__SocialNetworkAlgorithm__
#include <iostream>
#include <vector>
#include <boost/foreach.hpp>
#include "SocialNetworkGraph.h"
template <typename K, typename V>
V GetWithDef(const std::map <K,V> & m, const K & key, const V & defval ) {
typename std::map<K,V>::const_iterator it = m.find( key );
if ( it == m.end() ) {
return defval;
}
else {
return it->second;
}
}
struct SimillarityComparator {
bool operator() (std::pair<long,double> i,std::pair<long,double> j) { return (i.second>j.second);}
};
class SocialNetworkAlgorithm{
private:
SocialNetworkGraph& socialNetorkGraph;
void limitedDFS(long startId, long currentId,int DFSlimit,int currentLevel,std::vector<std::pair<long, double>>& retVector,std::map<long,bool>& visitMap);
public:
SocialNetworkAlgorithm(SocialNetworkGraph& graph):socialNetorkGraph(graph){}
std::vector<std::pair<long,double>> getIdDistancePairs(long startdId,int DFSlimit);
void makeMove(double DFSprobability,int DFSlimit,int oneNodeConnections);
void makeRandomConnections(int randomConnectionCount);
class NetworkVisitor:public boost::default_dfs_visitor {
private:
int curentDepthCount;
int maxDepth;
public:
NetworkVisitor(int maxDepth);
void discover_vertex(boost::graph_traits<Graph>::vertex_descriptor u, Graph g);
void finish_vertex(boost::graph_traits<Graph>::vertex_descriptor u, Graph g);
bool operator()();
};
};
#endif /* defined(__Social_Network__SocialNetworkAlgorithm__) */
| [
"wkryscinski@gmail.com"
] | wkryscinski@gmail.com |
545c98f1d481f5b85d10bcb854e76de3a4baf78f | 245ef7563b7337408e84ddea7add70b87f96c7c9 | /BlinkTest/BlinkTest.ino | d939e4a76484d09819ad60c7707ea324bffbf89b | [] | no_license | maciek01/arduino | 23424ffb80a71e1aafd6552aa6867aaa4774b767 | c7741103561bfba36e1fc68ee929ae639e062564 | refs/heads/master | 2021-01-12T17:50:29.324603 | 2016-11-12T00:29:46 | 2016-11-12T00:29:46 | 71,647,318 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 903 | ino | /*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.
Most Arduinos have an on-board LED you can control. On the Uno and
Leonardo, it is attached to digital pin 13. If you're unsure what
pin the on-board LED is connected to on your Arduino model, check
the documentation at http://www.arduino.cc
This example code is in the public domain.
modified 8 May 2014
by Scott Fitzgerald
*/
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin 13 as an output.
pinMode(13, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1); // wait for a second
digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
delay(30); // wait for a second
}
| [
"maciek@kolesnik.org"
] | maciek@kolesnik.org |
51ddc2e2ceb6c4c2ebe83a016cafeb628236596d | 54b090d85e3a86e144d63fff9f6654773ae7cf7d | /code/find_params.cpp | 19d805e5a6304a5d197b5b3cd3b111fee958807d | [
"MIT"
] | permissive | patrickgtwalker/malaria_in_pregnancy_istp_model_open | 6b2ea7b67c26954108cc9777dfa39ca41cb6882e | b6a7fd6b08cff687b036417d244d15bab1d9a17d | refs/heads/master | 2023-02-23T23:48:54.200583 | 2020-01-03T14:32:30 | 2020-01-03T14:32:30 | 231,604,946 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,727 | cpp | /// FOR IMPORTING PARAMETERS ////
#include <map>
typedef map<string, pair<double, string> > Parameter_map;
Parameter_map parameter_map;
using namespace std;
double from_map(const string &s, const double low=0, const double high=1E20, const double x=-99999){
Parameter_map::const_iterator p=parameter_map.find(s);
const bool found=p!=parameter_map.end();
if(!found && x==-99999)
error_crit("Parameter "+s+" was not found in any of the input files");
const double y=found ? p->second.first : x;
const double eps=1E-8;
if(y<low && y>low-eps)
return low;
else if(y>high && y<high+eps)
return high;
else if(y<=low-eps || y>=high+eps)
error_crit("Parameter "+s+" has value "+as_string(y)+" , should be between "+as_string(low)+" and "+as_string(high)+ (found ? " in file \n"+p->second.second : " as default"));
return y;
}
void add_to_map(const string &s, const double x){
parameter_map[s]=pair<double, string>(x, "batch file");
}
void modify_map(const string &s, const double x){
Parameter_map::iterator p=parameter_map.find(s);
if(p == parameter_map.end())
error_crit("Trying to modify parameter "+s+" from the command line, but that parameter name was not found in any of the input files");
p->second.first=x;
}
bool in_map(const string &s){
return parameter_map.find(s) != parameter_map.end();
}
void import_to_map(const string &file, const bool add=false){
ifstream input(file, ios::in);
if(!input)
error_crit("Can't open file "+file+" for input");
while(!input.eof()){
string s;
double x;
input >> s >> x;
cout<<s<<"\t"<<x<<"\n";
if(!input.eof()){
if(!input.good())
error_crit("Error in importing data from "+file);
if(add){
if(in_map(s))
modify_map(s, x);
else{
parameter_map.insert(pair<string, pair<double, string> >(s, pair<double, string>(x, file)));}
}
else{
pair<Parameter_map::const_iterator, bool> pb=parameter_map.insert(pair<string, pair<double, string> >(s, pair<double, string>(x, file)));
if(!pb.second)
error_crit("Importing parameter "+s+" from file\n"+file+", but a parameter with that name has already been imported from file\n"+pb.first->second.second);
}
}
}
input.close();
}
bool from_map_bool(const string &s, const double x=-99999){
Parameter_map::const_iterator p=parameter_map.find(s);
const bool found=p!=parameter_map.end();
if(!found && x==-99999)
error_crit("Parameter "+s+" was not found in any of the input files");
const double y=found ? p->second.first : x;
if(y==0)
return false;
else if(y==1)
return true;
else
error_crit("Parameter "+s+" has value "+as_string(y)+" , only 0 or 1 allowed" + (found ? " in file \n"+p->second.second : " as default"));
return true;
}
| [
"patrickwalker143@googlemail.com"
] | patrickwalker143@googlemail.com |
48cac130d4aa3eabab59c4b540850679b7936c88 | 002582c0f43596fc8f5f4d07f8117dae2a91e7df | /Reference Code/Reference DRAGON AWAKENS(CODE WITH MP3SHIELD(issues) ,SERVO, SONAR AND LEDCONNECTED TO ARDUINO).ino | 69bcf7759929435bab7300903001cbccf5d133e7 | [] | no_license | DeepKamani/Tech-Studio | aa2f1c7dafdbce41c74f12f8db1bd51f56227b3c | 9c2adb5dd275be04f217e521c0345650b600065a | refs/heads/master | 2020-04-08T23:43:03.737484 | 2018-11-30T15:38:28 | 2018-11-30T15:38:28 | 159,836,988 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,975 | ino | /* //// DRAGON AWAKEN //// */
/* // MAIN COMPONENTS // */
// Lightsaber toy or led set (x1)
// ARDUINO UNO (x1)
// VS1053b MP3 Shield for ARDUINO (x1)
// Micro Servo motor SG90 or compatible with wiring (x1)
// HC - SR04 Ultrasonic Distance Measuring Sensor Module for Arduino (x1)
// SD card (x1)
// externally powered speakers (x2) [avoid powering from the Arduino, this might cause malfunction of MP3 Shield].
// regular LED (x6)
// ARDUINO jumper cables and alligator cables (>20+)
// USB cable (x1)
// PC/MAC (x1)
/* /// For configuration please see wire diagram and inside-lighsaber pictures. Thank you /// */
/* servo+led+lightsaber+sensor+random+MP3 */
/* START OF MP3 Shield configuration MP3TF */
#include <SPI.h>
//Libraries
#include <SdFat.h>
#include <SdFatUtil.h>
//and the MP3 Shield Library
#include <SFEMP3Shield.h>
//create and name the library object
SFEMP3Shield MP3player;
SdFat sd;
SdFile file;
// Define variables that we might use but in this specific example are not needed.
// See https://github.com/mpflaga/Sparkfun-MP3-Player-Shield-Arduino-Library
byte temp;
byte result;
/* END OF MP3 Shield configuration MP3TF */
#include <Servo.h>
#include <NewPing.h>
#define TRIGGER_PIN 10
#define ECHO_PIN 9
#define MAX_DISTANCE 300
// Create servo Motor object
Servo myservo;
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
// Define random variable to determine if an individual has the force
long randNumber;
int timer =50;
int sound = 250;
void setup() {
Serial.begin(115200);
pinMode(TRIGGER_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
myservo.attach(11);
// if analog input pin 0 is unconnected, random analog
// noise will cause the call to randomSeed() to generate
// different seed numbers each time the sketch runs.
// randomSeed() will then shuffle the random function.
randomSeed(analogRead(0));
//mp3 shield powering in varibles initializing
sd.begin(SD_SEL, SPI_HALF_SPEED);
//boot up the MP3 Player Shield
result = MP3player.begin();
MP3player.setVolume(10, 10);
}
void loop() {
delay(1000);
int uS = sonar.ping();
long distance,pos=0,i;
long duration;
Serial.print("Ping: ");
distance =uS / US_ROUNDTRIP_CM;
Serial.print(distance);
Serial.println("cm");
Serial.println("Hello");
Serial.println("Preparing to play a song");
int randNumber = 1;
Serial.println(randNumber);
//
Serial.print(distance);
Serial.println(" cm");
//the person has to be within the sensors range and closer than 10cm and farther than 30cm to the installation
if(distance > 10 && distance<=30){
//It is assumed that only 20% has the force
Serial.println("Dragon sound");
//add track for person with the force
char trackName[] = "track001.mp3";
//tell the MP3 Shield to play that file
result = MP3player.playMP3(trackName);
//check result, see readme for error codes.
if(result != 0) {
Serial.print("Error code: ");
Serial.print(result);
Serial.println(" when trying to play track");
}
//darth vader turns to look at you if you have the force
myservo.write(180);
for (int thisPin = 2; thisPin < 8; thisPin++) {
// turn the pin on:
digitalWrite(thisPin, HIGH);
delay(timer);
// turn the pin off:
digitalWrite(thisPin, LOW);
}
// loop from the highest pin to the lowest:
for (int thisPin = 7; thisPin >= 2; thisPin--) {
// turn the pin on:
digitalWrite(thisPin, HIGH);
delay(timer);
// turn the pin off:
digitalWrite(thisPin, LOW);
}
// wait 1.5 seconds
delay(1500);
myservo.write(0);
}
//the person has to be within the sensors range and closer than 30cm and farther than 60cm to the installation
if(distance > 30 && distance<=60){
if (randNumber==1) {
Serial.println("Dragon sound");
//add track for person with the force
char trackName[] = "track002.mp3";
//tell the MP3 Shield to play that file
result = MP3player.playMP3(trackName);
//check result, see readme for error codes.
if(result != 0) {
Serial.print("Error code: ");
Serial.print(result);
Serial.println(" when trying to play track");
}
//darth vader turns to look at you if you have the force
myservo.write(180);
for (int thisPin = 2; thisPin < 8; thisPin++) {
// turn the pin on:
digitalWrite(thisPin, HIGH);
delay(timer);
// turn the pin off:
digitalWrite(thisPin, LOW);
}
// loop from the highest pin to the lowest:
for (int thisPin = 7; thisPin >= 2; thisPin--) {
// turn the pin on:
digitalWrite(thisPin, HIGH);
delay(timer);
// turn the pin off:
digitalWrite(thisPin, LOW);
}
// wait 1.5 seconds
delay(1500);
myservo.write(0);
}
}
//the person has to be within the sensors range and closer than 60cm and farther than 100cm to the installation
if(distance > 60 && distance<=100){
if (randNumber==1) {
Serial.println("Dragon sound");
//add track for person with the force
char trackName[] = "track003.mp3";
//tell the MP3 Shield to play that file
result = MP3player.playMP3(trackName);
//check result, see readme for error codes.
if(result != 0) {
Serial.print("Error code: ");
Serial.print(result);
Serial.println(" when trying to play track");
}
//darth vader turns to look at you if you have the force
myservo.write(180);
for (int thisPin = 2; thisPin < 8; thisPin++) {
// turn the pin on:
digitalWrite(thisPin, HIGH);
delay(timer);
// turn the pin off:
digitalWrite(thisPin, LOW);
}
// loop from the highest pin to the lowest:
for (int thisPin = 7; thisPin >= 2; thisPin--) {
// turn the pin on:
digitalWrite(thisPin, HIGH);
delay(timer);
// turn the pin off:
digitalWrite(thisPin, LOW);
}
// wait 1.5 seconds
delay(1500);
myservo.write(0);
}
}
//the person has to be within the sensors range and closer than 100cm and farther than 150cm to the installation
if(distance > 100 && distance<=150){
if (randNumber==1) {
Serial.println("Dragon sound");
//add track for person with the force
char trackName[] = "track004.mp3";
//tell the MP3 Shield to play that file
result = MP3player.playMP3(trackName);
//check result, see readme for error codes.
if(result != 0) {
Serial.print("Error code: ");
Serial.print(result);
Serial.println(" when trying to play track");
}
//darth vader turns to look at you if you have the force
myservo.write(180);
for (int thisPin = 2; thisPin < 8; thisPin++) {
// turn the pin on:
digitalWrite(thisPin, HIGH);
delay(timer);
// turn the pin off:
digitalWrite(thisPin, LOW);
}
// loop from the highest pin to the lowest:
for (int thisPin = 7; thisPin >= 2; thisPin--) {
// turn the pin on:
digitalWrite(thisPin, HIGH);
delay(timer);
// turn the pin off:
digitalWrite(thisPin, LOW);
}
// wait 1.5 seconds
delay(1500);
myservo.write(0);
}
}
else{
Serial.print(distance);
char trackName[] = "track003.mp3";
if(result != 0) {
Serial.print("Error code: ");
Serial.print(result);
Serial.println(" when trying to play track");
}
//tell the MP3 Shield to play that file
result = MP3player.playMP3(trackName);
Serial.println("Out of range");
delay(3000);
}
}
| [
"deep.kamani24@gmail.com"
] | deep.kamani24@gmail.com |
fc391b53aa42d09f420e6fa935ff20db25d89f75 | d932716790743d0e2ae7db7218fa6d24f9bc85dc | /services/preferences/public/cpp/pref_service_factory.cc | 2f1f4316492f6490a861889d2e6703219fca3038 | [
"BSD-3-Clause"
] | permissive | vade/chromium | c43f0c92fdede38e8a9b858abd4fd7c2bb679d9c | 35c8a0b1c1a76210ae000a946a17d8979b7d81eb | refs/heads/Syphon | 2023-02-28T00:10:11.977720 | 2017-05-24T16:38:21 | 2017-05-24T16:38:21 | 80,049,719 | 19 | 3 | null | 2017-05-24T19:05:34 | 2017-01-25T19:31:53 | null | UTF-8 | C++ | false | false | 5,078 | cc | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/preferences/public/cpp/pref_service_factory.h"
#include "base/callback_helpers.h"
#include "components/prefs/persistent_pref_store.h"
#include "components/prefs/pref_notifier_impl.h"
#include "components/prefs/pref_registry.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/pref_value_store.h"
#include "services/preferences/public/cpp/persistent_pref_store_client.h"
#include "services/preferences/public/cpp/pref_registry_serializer.h"
#include "services/preferences/public/cpp/pref_store_client.h"
#include "services/preferences/public/interfaces/preferences.mojom.h"
#include "services/service_manager/public/cpp/connector.h"
namespace prefs {
namespace {
// Used to implement a "fire and forget" pattern where we call an interface
// method, with an attached error handler, but don't care to hold on to the
// InterfacePtr after.
template <typename Interface>
class RefCountedInterfacePtr
: public base::RefCounted<RefCountedInterfacePtr<Interface>> {
public:
mojo::InterfacePtr<Interface>& get() { return ptr_; }
void reset() { ptr_.reset(); }
private:
friend class base::RefCounted<RefCountedInterfacePtr<Interface>>;
~RefCountedInterfacePtr() = default;
mojo::InterfacePtr<Interface> ptr_;
};
void DoNothingHandleReadError(PersistentPrefStore::PrefReadError error) {}
scoped_refptr<PrefStore> CreatePrefStoreClient(
PrefValueStore::PrefStoreType store_type,
std::unordered_map<PrefValueStore::PrefStoreType,
mojom::PrefStoreConnectionPtr>* connections) {
auto pref_store_it = connections->find(store_type);
if (pref_store_it != connections->end()) {
return make_scoped_refptr(
new PrefStoreClient(std::move(pref_store_it->second)));
} else {
return nullptr;
}
}
void OnConnect(
scoped_refptr<RefCountedInterfacePtr<mojom::PrefStoreConnector>>
connector_ptr,
scoped_refptr<PrefRegistry> pref_registry,
ConnectCallback callback,
mojom::PersistentPrefStoreConnectionPtr persistent_pref_store_connection,
std::unordered_map<PrefValueStore::PrefStoreType,
mojom::PrefStoreConnectionPtr> connections) {
scoped_refptr<PrefStore> managed_prefs =
CreatePrefStoreClient(PrefValueStore::MANAGED_STORE, &connections);
scoped_refptr<PrefStore> supervised_user_prefs = CreatePrefStoreClient(
PrefValueStore::SUPERVISED_USER_STORE, &connections);
scoped_refptr<PrefStore> extension_prefs =
CreatePrefStoreClient(PrefValueStore::EXTENSION_STORE, &connections);
scoped_refptr<PrefStore> command_line_prefs =
CreatePrefStoreClient(PrefValueStore::COMMAND_LINE_STORE, &connections);
scoped_refptr<PrefStore> recommended_prefs =
CreatePrefStoreClient(PrefValueStore::RECOMMENDED_STORE, &connections);
// TODO(crbug.com/719770): Once owning registrations are supported, pass the
// default values of owned prefs to the service and connect to the service's
// defaults pref store instead of using a local one.
scoped_refptr<PersistentPrefStore> persistent_pref_store(
new PersistentPrefStoreClient(
std::move(persistent_pref_store_connection)));
PrefNotifierImpl* pref_notifier = new PrefNotifierImpl();
auto* pref_value_store = new PrefValueStore(
managed_prefs.get(), supervised_user_prefs.get(), extension_prefs.get(),
command_line_prefs.get(), persistent_pref_store.get(),
recommended_prefs.get(), pref_registry->defaults().get(), pref_notifier);
callback.Run(base::MakeUnique<::PrefService>(
pref_notifier, pref_value_store, persistent_pref_store.get(),
pref_registry.get(), base::Bind(&DoNothingHandleReadError), true));
connector_ptr->reset();
}
void OnConnectError(
scoped_refptr<RefCountedInterfacePtr<mojom::PrefStoreConnector>>
connector_ptr,
ConnectCallback callback) {
callback.Run(nullptr);
connector_ptr->reset();
}
} // namespace
void ConnectToPrefService(
service_manager::Connector* connector,
scoped_refptr<PrefRegistry> pref_registry,
std::vector<PrefValueStore::PrefStoreType> already_connected_types,
ConnectCallback callback,
base::StringPiece service_name) {
already_connected_types.push_back(PrefValueStore::DEFAULT_STORE);
auto connector_ptr = make_scoped_refptr(
new RefCountedInterfacePtr<mojom::PrefStoreConnector>());
connector->BindInterface(service_name.as_string(), &connector_ptr->get());
connector_ptr->get().set_connection_error_handler(base::Bind(
&OnConnectError, connector_ptr, base::Passed(ConnectCallback{callback})));
auto serialized_pref_registry = SerializePrefRegistry(*pref_registry);
connector_ptr->get()->Connect(
std::move(serialized_pref_registry), std::move(already_connected_types),
base::Bind(&OnConnect, connector_ptr, base::Passed(&pref_registry),
base::Passed(&callback)));
}
} // namespace prefs
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
645c641bd4b8086ba9483cd63b6d26484118d178 | 062a5099de7ab2fd1b12d6e98bdc446473cea455 | /140724/Game/Graphic/base/texture.cpp | 1cc18c71da58d41aa9816192f44e3d84dd94c82f | [
"MIT"
] | permissive | lthnim371/DirectX3D | 8fbda7a3f9b1cec2fad3c410465b4ab14bd87cf2 | 13848ae691747d5ec1d3b42e55a765cbbdc809c9 | refs/heads/master | 2016-09-05T21:44:02.897351 | 2014-08-22T03:43:30 | 2014-08-22T03:43:30 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,825 | cpp |
#include "stdafx.h"
#include "texture.h"
using namespace graphic;
cTexture::cTexture() :
m_texture(NULL)
{
}
cTexture::~cTexture()
{
Clear();
}
bool cTexture::Create(const string &fileName, bool isSizePow2)//isSizePow2=true
{
if (isSizePow2)
{
if (FAILED(D3DXCreateTextureFromFileA(GetDevice(), fileName.c_str(), &m_texture)))
return false;
}
else
{
return CreateEx(fileName);
}
return true;
}
bool cTexture::Create(const int width, const int height, const D3DFORMAT format)
{
if (FAILED(GetDevice()->CreateTexture( width, height, 1, 0, format,
D3DPOOL_MANAGED, &m_texture, NULL )))
return false;
D3DLOCKED_RECT lockrect;
m_texture->LockRect( 0, &lockrect, NULL, 0 );
memset( lockrect.pBits, 0x00, lockrect.Pitch*height );
m_texture->UnlockRect( 0 );
return true;
}
// D3DX_DEFAULT_NONPOW2 옵션을 켠 상태에서 텍스쳐를 생성한다.
bool cTexture::CreateEx(const string &fileName)
{
if (FAILED(D3DXCreateTextureFromFileExA(
GetDevice(), fileName.c_str(),
D3DX_DEFAULT_NONPOW2, D3DX_DEFAULT_NONPOW2, // option On
NULL, NULL, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT,
0,
&m_imageInfo,
NULL,
&m_texture)))
{
return false;
}
return true;
}
void cTexture::Bind(int stage)
{
GetDevice()->SetSamplerState(stage, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
GetDevice()->SetSamplerState(stage, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
GetDevice()->SetSamplerState(stage, D3DSAMP_MIPFILTER, D3DTEXF_POINT);
GetDevice()->SetTexture(stage, m_texture);
}
void cTexture::Bind(cShader &shader, const string &key)
{
shader.SetTexture(key, *this);
}
void cTexture::Lock(D3DLOCKED_RECT &out)
{
m_texture->LockRect( 0, &out, NULL, 0 );
}
void cTexture::Unlock()
{
m_texture->UnlockRect( 0 );
}
void cTexture::Clear()
{
SAFE_RELEASE(m_texture);
}
| [
"taehoon0720@naver.com"
] | taehoon0720@naver.com |
d0864433c0d24dd41e77deee767daf4326d1e8ca | 13c3630445d73fb2703e5574b70942742f37fb89 | /Stable/Gunz/ZPlayerListBox.cpp | f2d0159b387e1caa236fe40f729b13f7102faff7 | [] | no_license | NovaDV/Gunz1.5 | 8cb660462c386f4c35d7f5198e614a29d5276547 | 97e7bc51fd082e37f3de0f02c5e2ce6c33530c50 | refs/heads/main | 2023-06-14T15:41:07.759755 | 2021-07-11T18:25:07 | 2021-07-11T18:25:07 | 385,099,338 | 1 | 0 | null | 2021-07-12T02:10:18 | 2021-07-12T02:10:18 | null | UHC | C++ | false | false | 44,290 | cpp | #include "stdafx.h"
#include "zapplication.h"
#include "MMatchObjCache.h"
#include ".\zplayerlistbox.h"
#include "MBitmap.h"
#include "MListBox.h"
#include "zpost.h"
#include "ZCharacterView.h"
#include "ZPlayerMenu.h"
#include "MToolTip.h"
#include "ZButton.h"
#include "ZMyInfo.h"
#define PLAYER_SLOT_GAP 1
#define PLAYERLIST_ITEM_HEIGHT 23
bool GetUserGradeIDColor(MMatchUserGradeID gid,MCOLOR& UserNameColor,char* sp_name);
bool GetUserInfoUID(MUID uid,MCOLOR& _color,char* sp_name,MMatchUserGradeID& gid);
void ZPlayerListBoxLook::OnItemDraw2(MDrawContext* pDC, MRECT& r, const char* szText, MCOLOR color, bool bSelected, bool bFocus, int nAdjustWidth)
{
if(szText==NULL) return;
pDC->SetColor(color);
MRECT rtemp, rtemp2;
rtemp2 = rtemp = pDC->GetClipRect();
rtemp2.x += r.x;
rtemp2.y += r.y;
rtemp2.w = r.w;
rtemp2.h = r.h;
pDC->SetClipRect(rtemp2);
#ifdef COLORTEXT_SUPPORT
pDC->TextMultiLine(r, szText,0,false);
#else
pDC->Text(r.x, r.y+(r.h-pDC->GetFont()->GetHeight())/2, szText);
#endif
pDC->SetClipRect(rtemp);
}
void ZPlayerListBoxLook::OnItemDraw2(MDrawContext* pDC, MRECT& r, MBitmap* pBitmap, bool bSelected, bool bFocus, int nAdjustWidth)
{
if(pBitmap==NULL) return;
MRECT rtemp, rtemp2;
rtemp2 = rtemp = pDC->GetClipRect();
rtemp2.w -= nAdjustWidth;
pDC->SetClipRect(rtemp2);
pDC->SetBitmap(pBitmap);
// pDC->Draw(r.x, r.y);
pDC->Draw(r, MRECT(0,0,pBitmap->GetWidth(),pBitmap->GetHeight()));
pDC->SetClipRect(rtemp);
}
MRECT ZPlayerListBoxLook::GetClientRect(MListBox* pListBox, MRECT& r)
{
return r;
}
float GetF(float _new)
{
float adjustWidth = _new / 800.f;
if (RGetWidthScreen() != 0.75f)
{
if (RGetIsWidthScreen())
adjustWidth = _new / 960.f;
if (RGetIs16x9())
adjustWidth = _new / 1024.f;
}
return adjustWidth;
}
void ZPlayerListBoxLook::OnDraw(MListBox* pListBox, MDrawContext* pDC)
{
((ZPlayerListBox*)pListBox)->UpdateList(((ZPlayerListBox*)pListBox)->GetPlayerListMode());
// float fA = ((ZPlayerListBox*)pListBox)->OnReSize();
int newW = RGetScreenWidth();
float fA = GetF(newW);
m_SelectedPlaneColor = MCOLOR(180,220,180);
int nItemHeight = 23*fA;//pListBox->GetItemHeight();
int nShowCount = 0;
MRECT r = pListBox->GetClientRect();
MPOINT pos = pListBox->GetPosition();
int nHeaderHeight = nItemHeight;
MRECT rr = pListBox->m_Rect;
rr.x = 0;
rr.y = 0;
bool bShowClanCreateFrame =
((ZPlayerListBox*)pListBox)->GetMode()==ZPlayerListBox::PLAYERLISTMODE_CHANNEL_CLAN
&& !ZGetMyInfo()->IsClanJoined();
// 바탕그려주고(동환이가 삭제...)
// if(bShowClanCreateFrame)
// pDC->SetColor(32,32,32);
// else
// pDC->SetColor(60,60,60);
// pDC->FillRectangle(rr.x,rr.y+1,rr.w,rr.h);
pDC->SetColor(10,10,10);
ZPlayerListBox::PLAYERLISTMODE pm = ((ZPlayerListBox*)pListBox)->GetPlayerListMode();
int nMode = 0;// 0 : lobby 1 : stage
if( pm == ZPlayerListBox::PLAYERLISTMODE_STAGE || pm == ZPlayerListBox::PLAYERLISTMODE_STAGE_FRIEND)
nMode = 1;
// 테두리 그려주고
/*
MRECT cliprect = pDC->GetClipRect();//잠시풀어준다..
pDC->SetClipRect(0,0,RGetScreenWidth(),RGetScreenHeight());
pDC->SetColor(128,128,128);
pDC->Rectangle( MRECT(rr.x,rr.y,rr.w,rr.h) );
*/
/*
//오른쪽 검은색으로 그려주고
pDC->SetColor(0,0,0);
pDC->FillRectangle(MRECT(rr.x+rr.w-23*fA,rr.y+1,23*fA,rr.h-2));
// 오른쪽에 이미지 그려주고
if( ((ZPlayerListBox*)pListBox)->GetBitmap()) {
MBitmap* pBitmap = ((ZPlayerListBox*)pListBox)->GetBitmap();
pDC->SetBitmap(pBitmap);
pDC->Draw(MRECT(rr.x+rr.w-pBitmap->GetWidth()*fA,rr.y+1,pBitmap->GetWidth()*fA,pBitmap->GetHeight()*fA),
MRECT(0,0,pBitmap->GetWidth(),pBitmap->GetHeight()));
}
*/
// pDC->SetClipRect(cliprect);
/* if(!bShowClanCreateFrame)
{
pDC->SetColor(0,0,0);
for(int i=0; i<pListBox->GetShowItemCount(); i++) {
MPOINT p;
p.x = r.x;
p.y = r.y+nItemHeight*i+1;
pDC->HLine(1,p.y+nItemHeight-1,rr.w-1);
}
}
*/
MBitmap* pBaseBmp = NULL;
for(int i=pListBox->GetStartItem(); i<pListBox->GetCount(); i++) {
MPOINT p;
p.x = r.x;
p.y = r.y+nHeaderHeight+nItemHeight*nShowCount;
// p.x = 0;
// p.y = 0+nHeaderHeight+nItemHeight*nShowCount;
// mlog(" ------- p.y = %d %d \n",p.y,nItemHeight);
MListItem* pItem = pListBox->Get(i);
bool bSelected = pItem->m_bSelected;
// bool bSelected = (pListBox->IsSelected()) ? (pListBox->GetSelIndex()==i) : false;
bool bFocused = (pListBox->IsFocus());
int nFieldStartX = 0;
// if(bSelected && bFocused) {//선택된아이템표시
if(bSelected) {
// pDC->SetColor(109,207,246);
// pDC->FillRectangle(MRECT(p.x,p.y+1,r.x+r.w,nItemHeight-1));
pDC->SetColor(130,130,130);
pDC->Rectangle(MRECT(p.x+2,p.y+5,r.x+r.w-8,nItemHeight-4)); // 다시 그림(동환)
}
for(int j=0; j<max(pListBox->GetFieldCount(), 1); j++){
int nTabSize = r.w;
if(j<pListBox->GetFieldCount()) nTabSize = pListBox->GetField(j)->nTabSize;
int nWidth = min(nTabSize, r.w-nFieldStartX);
if(pListBox->m_bAbsoulteTabSpacing==false) nWidth = r.w*nTabSize/100;
int nAdjustWidth = 0;
if(pListBox->GetScrollBar()->IsVisible()){
nAdjustWidth = pListBox->GetScrollBar()->GetRect().w + pListBox->GetScrollBar()->GetRect().w/2;
}
// MRECT ir(p.x+nFieldStartX+4+5, p.y+4, nWidth-8, nItemHeight-8);
// MRECT irt(p.x+nFieldStartX+2+5, p.y+2, nWidth, nItemHeight);
MRECT ir(p.x+nFieldStartX+5, p.y+7, nWidth-7, nItemHeight-7); // 다시 그림(동환)
MRECT irt(p.x+nFieldStartX, p.y+5, nWidth, nItemHeight);
const char* szText = pItem->GetString(j);
MBitmap* pBitmap = pItem->GetBitmap(j);
MCOLOR color = pItem->GetColor();
if(pBitmap!=NULL)//이미지 그리고
OnItemDraw2(pDC, ir, pBitmap, bSelected, bFocused, nAdjustWidth);
if(szText!=NULL)// 텍스트 그리고
{
// if(bSelected && bFocused)
// if(bSelected)
// color = MCOLOR(0,0,0);
OnItemDraw2(pDC, irt, szText, color, bSelected, bFocused, nAdjustWidth);
}
nFieldStartX += nWidth;
if(nFieldStartX>=r.w) break;
}
nShowCount++;
if(nShowCount>=pListBox->GetShowItemCount()) break;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
IMPLEMENT_LOOK(ZPlayerListBox, ZPlayerListBoxLook)
ZPlayerListBox::ZPlayerListBox(const char* szName, MWidget* pParent, MListener* pListener)
: MListBox(szName, pParent, pListener)
{
LOOK_IN_CONSTRUCTOR()
/*
if(strcmp(szName,"StagePlayerList_")==0) {
m_nMode = PLAYERLISTMODE_STAGE;
}
else
m_nMode = PLAYERLISTMODE_CHANNEL;
*/
SetVisibleHeader(false);
m_bAbsoulteTabSpacing = true;
// m_MyUID = MUID(0,0);
// m_uidChannel = MUID(0,0);
m_nTotalPlayerCount = 0;
m_nPage = 0;
m_bVisible = true;
m_bVisibleHeader = true;
// AddField(" ", 23);//icon
// AddField(" ",130);//name
// AddField(" ", 23);//icon
// AddField(" ", 32);//level
SetItemHeight(PLAYERLIST_ITEM_HEIGHT);
// m_pBitmap = NULL;
// m_pBitmapIn = NULL;
mSelectedPlayer = 0;
mStartToDisplay = 0;
// mPlayerOrder.reserve( sizeof(MUID)*100 );
// m_pScrollBar = new MScrollBar( this, this );
// ZApplication::GetGameInterface()->GetIDLResource()->InsertWidget("PlayerListScrollBar", m_pScrollBar );
m_bAlwaysVisibleScrollbar = false;
m_bHideScrollBar = true;
m_pScrollBar->SetVisible(false);
m_pScrollBar->Enable(false);
m_pScrollBar->m_nDebugType = 3;
m_nDebugType = 2;
m_nOldW = RGetScreenWidth();
SetListener(this);
m_pButton = new ZBmButton(NULL,this,this);
m_pButton->SetStretch(true);
m_nMode = PLAYERLISTMODE_CHANNEL;
InitUI(m_nMode);
}
ZPlayerListBox::~ZPlayerListBox(void)
{
SAFE_DELETE(m_pButton);
}
void ZPlayerListBox::SetupButton(const char *szOn, const char *szOff)
{
m_pButton->SetUpBitmap(MBitmapManager::Get(szOff));
m_pButton->SetDownBitmap(MBitmapManager::Get(szOn));
m_pButton->SetOverBitmap(MBitmapManager::Get(szOff));
}
void ZPlayerListBox::InitUI(PLAYERLISTMODE nMode)
{
int newW = RGetScreenWidth();
float fA = GetF(newW);
m_nMode = nMode;
_ASSERT(nMode>=0 && nMode<PLAYERLISTMODE_END);
RemoveAllField();
// 필드 개수테이블
const int nFields[PLAYERLISTMODE_END] = { 6,6,2,2,4,4 };
for(int i=0;i<nFields[nMode];i++) {
AddField("",10); // 일단 필드를 더해놓고 나중에 리사이즈한다
}
OnSize(0,0);
bool bShowClanCreateFrame = false;
switch(m_nMode) {
case PLAYERLISTMODE_CHANNEL: SetupButton("pltab_lobby_on.tga","pltab_lobby_off.tga");break;
case PLAYERLISTMODE_STAGE: SetupButton("pltab_game_on.tga","pltab_game_off.tga");break;
case PLAYERLISTMODE_CHANNEL_FRIEND:
case PLAYERLISTMODE_STAGE_FRIEND: SetupButton("pltab_friends_on.tga","pltab_friends_off.tga");break;
case PLAYERLISTMODE_CHANNEL_CLAN:
case PLAYERLISTMODE_STAGE_CLAN:
{
SetupButton("pltab_clan_on.tga","pltab_clan_off.tga");
bShowClanCreateFrame = !ZGetMyInfo()->IsClanJoined();
}break;
}
// (좋지않은 구조) 클랜인데 클랜에 가입이 안되어있으면 생성 창을 보인다
MWidget *pFrame = ZGetGameInterface()->GetIDLResource()->FindWidget("LobbyPlayerListClanCreateFrame");
MButton* pButtonUp = (MButton*)ZGetGameInterface()->GetIDLResource()->FindWidget("LobbyChannelPlayerListPrev");
MButton* pButtonDn = (MButton*)ZGetGameInterface()->GetIDLResource()->FindWidget("LobbyChannelPlayerListNext");
if( pFrame)
{
pFrame->Show(bShowClanCreateFrame);
pButtonUp->Show(!bShowClanCreateFrame);
pButtonDn->Show(!bShowClanCreateFrame);
}
}
void ZPlayerListBox::RefreshUI()
{
InitUI(GetMode());
}
void ZPlayerListBox::SetMode(PLAYERLISTMODE nMode)
{
ZPlayerListBox* pWidget = (ZPlayerListBox*)ZApplication::GetGameInterface()->GetIDLResource()->FindWidget("LobbyChannelPlayerList");
if(pWidget) {
pWidget->RemoveAll();
}
// mlog("ZPlayerListBox::SetMode %d \n" , nMode);
InitUI(nMode);
if(!ZGetGameClient()) return;
if(nMode==PLAYERLISTMODE_CHANNEL) {
if (ZGetGameClient()->IsConnected()) {
//UpdateList(nMode);
if(pWidget) {
int nPage = pWidget->m_nPage;
ZPostRequestChannelPlayerList(ZGetGameClient()->GetPlayerUID(),ZGetGameClient()->GetChannelUID(),nPage);
}
}
}
else if(nMode==PLAYERLISTMODE_STAGE) {
if (ZGetGameClient()->IsConnected())
ZPostRequestStagePlayerList(ZGetGameClient()->GetStageUID());
}
else if(nMode==PLAYERLISTMODE_CHANNEL_FRIEND || nMode==PLAYERLISTMODE_STAGE_FRIEND) {
if (ZGetGameClient()->IsConnected())
ZPostFriendList();
}
else if (nMode==PLAYERLISTMODE_CHANNEL_CLAN || nMode==PLAYERLISTMODE_STAGE_CLAN) {
if (ZGetGameClient()->IsConnected())
ZPostRequestClanMemberList(ZGetGameClient()->GetPlayerUID());
}
}
/*
void ZPlayerListBox::SetBitmap( MBitmap* pBitmap)
{
m_pBitmap = pBitmap;
}
*/
void ZPlayerListBox::AddTestItems()
{
/* switch (m_nMode)
{
case PLAYERLISTMODE_CHANNEL:
AddPlayer(MUID(0,0),PS_FIGHT,34,"TestPlayer1","TestClan",24401,MMUG_FREE,1);
AddPlayer(MUID(0,1),PS_WAIT ,10,"TestPlayer2","TestClan",24401,MMUG_FREE,2);
AddPlayer(MUID(0,2),PS_LOBBY,11,"TestPlayer3","TestClan",24401,MMUG_FREE,3);
AddPlayer(MUID(0,3),PS_LOBBY,99,"TestPlayer4","TestClan",24401,MMUG_FREE,4);
AddPlayer(MUID(0,4),PS_LOBBY, 3,"TestPlayer5","TestClan",24401,MMUG_FREE,5);
AddPlayer(MUID(0,5),PS_LOBBY, 1,"TestPlayer6","TestClan",24401,MMUG_FREE,6);
AddPlayer(MUID(0,6),PS_LOBBY,33,"TestPlayer7","TestClan",24401,MMUG_FREE,7);
AddPlayer(MUID(0,7),PS_LOBBY,45,"TestPlayer8","TestClan",24401,MMUG_FREE,8);
AddPlayer(MUID(0,8),PS_LOBBY,44,"TestPlayer9","TestClan",24401,MMUG_FREE,9);
break;
}
*/
}
void GetRectMul(MRECT* rect,MRECT* org_rect,float f)
{
rect->x = org_rect->x * f;
rect->y = org_rect->y * f;
rect->w = org_rect->w * f;
rect->h = org_rect->h * f;
}
void ZPlayerListBox::OnSize(int w,int h)
{
if(m_Fields.GetCount()==0) return;
int newW = RGetScreenWidth();
float fA = GetF(newW);
m_nItemHeight = PLAYERLIST_ITEM_HEIGHT * fA;
// m_pButton->SetBounds(1,1,m_Rect.w*.8f,m_nItemHeight+1);
m_pButton->SetBounds(0, 0, m_Rect.w, (int)(28.0/*이미지 높이가 28이라서...*/*fA)); // 다시 그림(동환)
switch(m_nMode) {
case PLAYERLISTMODE_CHANNEL:
{
m_Fields.Get(0)->nTabSize = 23*fA; //icon
m_Fields.Get(1)->nTabSize = 16*fA; //level
m_Fields.Get(2)->nTabSize = 23*fA; //icon (duel tournament grade)
m_Fields.Get(3)->nTabSize = 94*fA; //name
m_Fields.Get(4)->nTabSize = 23*fA; //icon
m_Fields.Get(5)->nTabSize = 94*fA; //clan name
}
break;
case PLAYERLISTMODE_STAGE:
{
m_Fields.Get(0)->nTabSize = 23*fA; //icon
m_Fields.Get(1)->nTabSize = 16*fA; //level
m_Fields.Get(2)->nTabSize = 23*fA; //icon (duel tournament grade)
m_Fields.Get(3)->nTabSize = 94*fA; //name
m_Fields.Get(4)->nTabSize = 23*fA; //icon
m_Fields.Get(5)->nTabSize = 94*fA; //clan name
}
break;
case PLAYERLISTMODE_STAGE_FRIEND:
case PLAYERLISTMODE_CHANNEL_FRIEND:
{
m_Fields.Get(0)->nTabSize = 23*fA; //icon
m_Fields.Get(1)->nTabSize = 72*fA; //name
}
break;
case PLAYERLISTMODE_CHANNEL_CLAN:
case PLAYERLISTMODE_STAGE_CLAN:
{
m_Fields.Get(0)->nTabSize = 23*fA; //icon
m_Fields.Get(1)->nTabSize = 85*fA; //name
m_Fields.Get(2)->nTabSize = 23*fA; //icon
m_Fields.Get(3)->nTabSize = 90*fA; //clan grade
}
break;
};
RecalcList();
}
// mode PLAYERLISTMODE_CHANNEL
void ZPlayerListBox::AddPlayer(MUID& puid, ePlayerState state, int nLevel,char* szName, char *szClanName, unsigned int nClanID, MMatchUserGradeID nGrade, int duelTournamentGrade )
{
auto len = strlen(szName);
if ( len == 0)
return;
char szFileName[64] = "";
char szLevel[64] = "";
char* szRefName = NULL;
MCOLOR _color;
char sp_name[256];
bool bSpUser = false;
if (GetUserGradeIDColor(nGrade, _color, sp_name)) {
sprintf(szLevel, "%2d", nLevel);
szRefName = szName;
bSpUser = true;
}
else {
sprintf(szLevel, "%2d", nLevel);
szRefName = szName;
}
switch (state) {
case PS_FIGHT : strcpy(szFileName, "player_status_player.tga"); break;
case PS_WAIT : strcpy(szFileName, "player_status_game.tga"); break;
case PS_LOBBY : strcpy(szFileName, "player_status_lobby.tga"); break;
}
char szDTGradeIconFileName[64];
GetDuelTournamentGradeIconFileName(szDTGradeIconFileName, duelTournamentGrade);
MBitmap* pBmpDTGradeIcon = MBitmapManager::Get( szDTGradeIconFileName );
//// 클랜 엠블럼
//MBitmap* pBitmapEmblem = NULL;
//if ( strcmp( szClanName, "") != 0)
// pBitmapEmblem = ZGetEmblemInterface()->GetClanEmblem( nClanID );
ZLobbyPlayerListItem* pItem = new ZLobbyPlayerListItem(puid, MBitmapManager::Get(szFileName), nClanID, szLevel, szRefName, szClanName, state, nGrade, pBmpDTGradeIcon );
if(bSpUser)
pItem->SetColor(_color);
MListBox::Add( pItem );
}
// mode PLAYERLISTMODE_STAGE
void ZPlayerListBox::AddPlayer(MUID& puid, MMatchObjectStageState state, int nLevel, char* szName, char* szClanName, unsigned int nClanID, bool isMaster, MMatchTeam nTeam, int duelTournamentGrade)
{
auto len = strlen(szName);
if (len == 0)
return;
char szFileName[64] = "";
char szFileNameState[64] = "";
char szLevel[64] = "";
char* szRefName = NULL;
MCOLOR _color;
char sp_name[256];
bool bSpUser = false;
MMatchUserGradeID gid = MMUG_FREE;
if (GetUserInfoUID(puid, _color, sp_name, gid)) {
sprintf(szLevel, "%2d", nLevel);
szRefName = szName;
bSpUser = true;
}
else {
sprintf(szLevel, "%2d", nLevel);
szRefName = szName;
}
MBitmap* pBitmap = NULL;
if(isMaster) {
switch (state) {
case MOSS_NONREADY :
if(nTeam == MMT_RED) strcpy(szFileName, "stg_status_master_red.tga");
else if(nTeam == MMT_BLUE) strcpy(szFileName, "stg_status_master_blue.tga");
else if(nTeam == MMT_SPECTATOR) strcpy(szFileName, "stg_status_master_observer.tga");
else strcpy(szFileName, "stg_status_master_normal.tga");
break;
case MOSS_READY :
if(nTeam == MMT_RED) strcpy(szFileName, "stg_status_master_red_ready.tga");
else if(nTeam == MMT_BLUE) strcpy(szFileName, "stg_status_master_blue_ready.tga");
else if(nTeam == MMT_SPECTATOR) strcpy(szFileName, "stg_status_master_observer.tga");
else strcpy(szFileName, "stg_status_master_normal_ready.tga");
break;
case MOSS_EQUIPMENT :
if(nTeam == MMT_RED) strcpy(szFileName, "stg_status_master_red_equip.tga");
else if(nTeam == MMT_BLUE) strcpy(szFileName, "stg_status_master_blue_equip.tga");
else if(nTeam == MMT_SPECTATOR) strcpy(szFileName, "stg_status_master_observer.tga");
else strcpy(szFileName, "stg_status_master_normal_equip.tga");
break;
default :
strcpy(szFileName, " ");
break;
}
}
else {
switch (state) {
case MOSS_NONREADY :
if(nTeam == MMT_RED) strcpy(szFileName, "stg_status_member_red.tga");
else if(nTeam == MMT_BLUE) strcpy(szFileName, "stg_status_member_blue.tga");
else if(nTeam == MMT_SPECTATOR) strcpy(szFileName, "stg_status_member_observer.tga");
else strcpy(szFileName, "stg_status_member_normal.tga");
break;
case MOSS_READY :
if(nTeam == MMT_RED) strcpy(szFileName, "stg_status_member_red_ready.tga");
else if(nTeam == MMT_BLUE) strcpy(szFileName, "stg_status_member_blue_ready.tga");
else if(nTeam == MMT_SPECTATOR) strcpy(szFileName, "stg_status_member_observer.tga");
else strcpy(szFileName, "stg_status_member_normal_ready.tga");
break;
case MOSS_EQUIPMENT :
if(nTeam == MMT_RED) strcpy(szFileName, "stg_status_member_red_equip.tga");
else if(nTeam == MMT_BLUE) strcpy(szFileName, "stg_status_member_blue_equip.tga");
else if(nTeam == MMT_SPECTATOR) strcpy(szFileName, "stg_status_member_observer.tga");
else strcpy(szFileName, "stg_status_member_normal_equip.tga");
break;
}
}
pBitmap = MBitmapManager::Get(szFileName);
char szDTGradeIconFileName[64];
GetDuelTournamentGradeIconFileName(szDTGradeIconFileName, duelTournamentGrade);
MBitmap* pBmpDTGradeIcon = MBitmapManager::Get( szDTGradeIconFileName );
//// 클랜 엠블럼
//MBitmap* pBitmapEmblem = NULL;
//if ( strcmp( szClanName, "") != 0)
// pBitmapEmblem = ZGetEmblemInterface()->GetClanEmblem( nClanID );
ZStagePlayerListItem* pItem = new ZStagePlayerListItem(puid, pBitmap, nClanID, szRefName, szClanName, szLevel, gid, pBmpDTGradeIcon);
if(bSpUser)
pItem->SetColor(_color);
MListBox::Add( pItem );
if( ZGetMyUID() == puid )
{
bool bBlue, bRed;
bBlue = bRed = false;
if( nTeam == MMT_BLUE) bBlue = true;
if( nTeam == MMT_RED) bRed = true;
MButton* pButton = (MButton*)ZApplication::GetGameInterface()->GetIDLResource()->FindWidget("StageTeamBlue");
pButton->SetCheck( bBlue );
pButton = (MButton*)ZApplication::GetGameInterface()->GetIDLResource()->FindWidget("StageTeamRed");
pButton->SetCheck( bRed );
}
}
// mode PLAYERLISTMODE_CHANNEL_FRIEND, PLAYERLISTMODE_STAGE_FRIEND
void ZPlayerListBox::AddPlayer(ePlayerState state, char* szName, char* szLocation)
{
if ( (int32_t)strlen( szName) == 0)
return;
char szFileName[64] = "";
switch (state) {
case PS_FIGHT : strcpy(szFileName, "player_status_player.tga"); break;
case PS_WAIT : strcpy(szFileName, "player_status_game.tga"); break;
case PS_LOBBY : strcpy(szFileName, "player_status_lobby.tga"); break;
}
MListBox::Add(new ZFriendPlayerListItem(MUID(0,0),MBitmapManager::Get(szFileName), szName,NULL,szLocation,state,MMUG_FREE));
}
// mode PLAYERLISTMODE_CHANNEL_CLAN
void ZPlayerListBox::AddPlayer(MUID& puid, ePlayerState state, char* szName, int nLevel ,MMatchClanGrade nGrade )
{
auto len = strlen(szName);
if (len == 0)
return;
char szFileName[64] = "";
char szGradeName[64];
char* szRefName = NULL;
MCOLOR _color = MCOLOR(240,64,64);
// char sp_name[256];
bool bSpUser = false;
switch(nGrade) {
case MCG_MASTER :
sprintf(szGradeName, ZMsg( MSG_WORD_CLAN_MASTER));
bSpUser = true;
break;
case MCG_ADMIN :
sprintf(szGradeName, ZMsg( MSG_WORD_CLAN_ADMIN));
bSpUser = true;
break;
default : sprintf(szGradeName, ZMsg( MSG_WORD_CLAN_MEMBER));
break;
}
szRefName = szName;
switch (state) {
case PS_FIGHT : strcpy(szFileName, "player_status_player.tga"); break;
case PS_WAIT : strcpy(szFileName, "player_status_game.tga"); break;
case PS_LOBBY : strcpy(szFileName, "player_status_lobby.tga"); break;
}
ZClanPlayerListItem* pItem = new ZClanPlayerListItem(puid, MBitmapManager::Get(szFileName), szRefName, szGradeName, NULL, state, nGrade );
if(bSpUser)
pItem->SetColor(_color);
MListBox::Add( pItem );
}
void ZPlayerListBox::DelPlayer(MUID& puid)
{
ZPlayerListItem* pItem = NULL;
for(int i=0;i<GetCount();i++) {
pItem = (ZPlayerListItem*)Get(i);
if(pItem->m_PlayerUID==puid){
Remove(i);
return;
}
}
}
// 나중에 바꾸자 바쁘다.. 새벽 5:16분..
ZPlayerListItem* ZPlayerListBox::GetUID(MUID uid)
{
ZPlayerListItem* pItem = NULL;
for(int i=0;i<GetCount();i++) {
pItem = (ZPlayerListItem*)Get(i);
if(pItem->m_PlayerUID==uid)
return pItem;
}
return NULL;
}
const char* ZPlayerListBox::GetPlayerName( int nIndex)
{
ZPlayerListItem* pItem = (ZPlayerListItem*)Get( nIndex);
if ( !pItem)
return NULL;
return pItem->m_szName;
}
// 위치는 좀 이상하지만~
static DWORD g_zplayer_list_update_time = 0;
#define ZPLAYERLIST_UPDATE_TIME 2000
void ZPlayerListBox::UpdateList(int mode)
{
if (ZGetGameClient()->IsConnected() == false) return;
DWORD this_time = timeGetTime();
if( this_time < g_zplayer_list_update_time + ZPLAYERLIST_UPDATE_TIME)
return;
if(mode==PLAYERLISTMODE_CHANNEL) {
/* ZPlayerListBox* pWidget = (ZPlayerListBox*)ZApplication::GetGameInterface()->GetIDLResource()->FindWidget("LobbyChannelPlayerList");
int nPage = pWidget->m_nPage;
if(pWidget)
{
ZPostRequestChannelPlayerList(pWidget->m_MyUID,pWidget->m_uidChannel,nPage);
}*/
}
else if(mode==PLAYERLISTMODE_STAGE) {
// Do Nothing !!
}
else if(mode==PLAYERLISTMODE_CHANNEL_CLAN) {
// test로 여기서 업데이트할때 클랜 리스트달라고도 계~속 요청한다. 테스트끝나면 삭제요망 - by bird
//#ifndef _PUBLISH
// ZPostRequestClanMemberList(ZGetGameClient()->GetPlayerUID());
//#endif
}
g_zplayer_list_update_time = this_time;
}
void ZPlayerListBox::UpdatePlayer(MUID& puid,MMatchObjectStageState state, bool isMaster,MMatchTeam nTeam)
{
ZStagePlayerListItem* pItem = (ZStagePlayerListItem*)GetUID(puid);
if(pItem) {
char szFileName[64] = "";
char szFileNameState[64] = "";
MBitmap* pBitmap = NULL;
MBitmap* pBitmapState = NULL;
const MSTAGE_SETTING_NODE* pStageSetting = ZGetGameClient()->GetMatchStageSetting()->GetStageSetting();
if ( (nTeam != MMT_SPECTATOR) && (ZGetGameTypeManager()->IsTeamGame(pStageSetting->nGameType) == false))
{
nTeam = MMT_ALL;
}
if(isMaster) {
switch (state) {
case MOSS_NONREADY :
if(nTeam == MMT_RED) { strcpy(szFileName, "stg_status_master_red.tga"); pItem->m_nTeam = 1;}
else if(nTeam == MMT_BLUE) { strcpy(szFileName, "stg_status_master_blue.tga"); pItem->m_nTeam = 2;}
else if(nTeam == MMT_SPECTATOR) { strcpy(szFileName, "stg_status_master_observer.tga"); pItem->m_nTeam = 3;}
else { strcpy(szFileName, "stg_status_master_normal.tga"); pItem->m_nTeam = 0;}
break;
case MOSS_READY :
if(nTeam == MMT_RED) { strcpy(szFileName, "stg_status_master_red_ready.tga"); pItem->m_nTeam = 1;}
else if(nTeam == MMT_BLUE) { strcpy(szFileName, "stg_status_master_blue_ready.tga"); pItem->m_nTeam = 2;}
else if(nTeam == MMT_SPECTATOR) { strcpy(szFileName, "stg_status_master_observer.tga"); pItem->m_nTeam = 3;}
else { strcpy(szFileName, "stg_status_master_normal_ready.tga"); pItem->m_nTeam = 0;}
break;
case MOSS_EQUIPMENT :
if(nTeam == MMT_RED) { strcpy(szFileName, "stg_status_master_red_equip.tga"); pItem->m_nTeam = 1;}
else if(nTeam == MMT_BLUE) { strcpy(szFileName, "stg_status_master_blue_equip.tga"); pItem->m_nTeam = 2;}
else if(nTeam == MMT_SPECTATOR) { strcpy(szFileName, "stg_status_master_observer.tga"); pItem->m_nTeam = 3;}
else { strcpy(szFileName, "stg_status_master_normal_equip.tga"); pItem->m_nTeam = 0;}
break;
default :
strcpy(szFileName, " ");
break;
}
}
else {
switch (state) {
case MOSS_NONREADY :
if(nTeam == MMT_RED) { strcpy(szFileName, "stg_status_member_red.tga"); pItem->m_nTeam = 1;}
else if(nTeam == MMT_BLUE) { strcpy(szFileName, "stg_status_member_blue.tga"); pItem->m_nTeam = 2;}
else if(nTeam == MMT_SPECTATOR) { strcpy(szFileName, "stg_status_member_observer.tga"); pItem->m_nTeam = 3;}
else { strcpy(szFileName, "stg_status_member_normal.tga"); pItem->m_nTeam = 0;}
break;
case MOSS_READY :
if(nTeam == MMT_RED) { strcpy(szFileName, "stg_status_member_red_ready.tga"); pItem->m_nTeam = 1;}
else if(nTeam == MMT_BLUE) { strcpy(szFileName, "stg_status_member_blue_ready.tga"); pItem->m_nTeam = 2;}
else if(nTeam == MMT_SPECTATOR) { strcpy(szFileName, "stg_status_member_observer.tga"); pItem->m_nTeam = 3;}
else { strcpy(szFileName, "stg_status_member_normal_ready.tga"); pItem->m_nTeam = 0;}
break;
case MOSS_EQUIPMENT :
if(nTeam == MMT_RED) { strcpy(szFileName, "stg_status_member_red_equip.tga"); pItem->m_nTeam = 1;}
else if(nTeam == MMT_BLUE) { strcpy(szFileName, "stg_status_member_blue_equip.tga"); pItem->m_nTeam = 2;}
else if(nTeam == MMT_SPECTATOR) { strcpy(szFileName, "stg_status_member_observer.tga"); pItem->m_nTeam = 3;}
else { strcpy(szFileName, "stg_status_member_normal_equip.tga"); pItem->m_nTeam = 0;}
break;
}
}
/* switch (state) {
case MOSS_NONREADY : strcpy(szFileNameState, " "); break;
case MOSS_READY : strcpy(szFileNameState, "char_stat_ready.tga"); break;
case MOSS_SHOP : strcpy(szFileNameState, "char_stat_shop.tga"); break;
case MOSS_EQUIPMENT : strcpy(szFileNameState, "char_stat_equip.tga"); break;
}
*/
pBitmap = MBitmapManager::Get(szFileName);
// pBitmapState = MBitmapManager::Get(szFileNameState);
pItem->m_pBitmap = pBitmap;
// pItem->m_pBitmapState = pBitmapState;
// char temp[256];
// sprintf(temp,"UpdatePlayer (%s,%s)/%d \n",szFileName,szFileNameState,GetCount() );
// OutputDebugString(temp);
}
ZCharacterView* pCharView = (ZCharacterView*)ZApplication::GetGameInterface()->GetIDLResource()->FindWidget("Stage_Charviewer_");
if( pCharView != 0 && puid == pCharView->m_Info.UID )
{
pCharView->m_Info.bMaster = isMaster;
pCharView->m_Info.m_pMnTeam->Set_CheckCrc((int) nTeam);
pCharView->m_Info.nStageState = state;
}
if( (nTeam != MMT_SPECTATOR) && (ZGetMyUID() == puid ))
{
bool bBlue, bRed;
bBlue = bRed = false;
if( nTeam == MMT_BLUE) bBlue = true;
if( nTeam == MMT_RED) bRed = true;
MButton* pButton = (MButton*)ZApplication::GetGameInterface()->GetIDLResource()->FindWidget("StageTeamBlue");
pButton->SetCheck( bBlue );
pButton = (MButton*)ZApplication::GetGameInterface()->GetIDLResource()->FindWidget("StageTeamRed");
pButton->SetCheck( bRed );
}
}
void ZPlayerListBox::UpdatePlayer(MUID& puid,MMatchObjectStageState state, char* szName, int nLevel ,bool isMaster,MMatchTeam nTeam)
{
return;
ZStagePlayerListItem* pItem = (ZStagePlayerListItem*)GetUID(puid);
if(pItem) {
char szFileName[64] = "";
char szFileNameState[64] = "";
char szLevel[64];
MBitmap* pBitmap = NULL;
MBitmap* pBitmapState = NULL;
if(isMaster) {
switch (state) {
case MOSS_NONREADY :
if(nTeam == MMT_RED) strcpy(szFileName, "stg_status_master_red.tga");
else if(nTeam == MMT_BLUE) strcpy(szFileName, "stg_status_master_blue.tga");
else if(nTeam == MMT_SPECTATOR) strcpy(szFileName, "stg_status_master_observer.tga");
else strcpy(szFileName, "stg_status_master_normal.tga");
break;
case MOSS_READY :
if(nTeam == MMT_RED) strcpy(szFileName, "stg_status_master_red_ready.tga");
else if(nTeam == MMT_BLUE) strcpy(szFileName, "stg_status_master_blue_ready.tga");
else if(nTeam == MMT_SPECTATOR) strcpy(szFileName, "stg_status_master_observer.tga");
else strcpy(szFileName, "stg_status_master_normal_ready.tga");
break;
case MOSS_EQUIPMENT :
if(nTeam == MMT_RED) strcpy(szFileName, "stg_status_master_red_equip.tga");
else if(nTeam == MMT_BLUE) strcpy(szFileName, "stg_status_master_blue_equip.tga");
else if(nTeam == MMT_SPECTATOR) strcpy(szFileName, "stg_status_master_observer.tga");
else strcpy(szFileName, "stg_status_master_normal_equip.tga");
break;
default :
strcpy(szFileName, " ");
break;
}
}
else {
switch (state) {
case MOSS_NONREADY :
if(nTeam == MMT_RED) strcpy(szFileName, "stg_status_member_red.tga");
else if(nTeam == MMT_BLUE) strcpy(szFileName, "stg_status_member_blue.tga");
else if(nTeam == MMT_SPECTATOR) strcpy(szFileName, "stg_status_member_observer.tga");
else strcpy(szFileName, "stg_status_member_normal.tga");
break;
case MOSS_READY :
if(nTeam == MMT_RED) strcpy(szFileName, "stg_status_member_red_ready.tga");
else if(nTeam == MMT_BLUE) strcpy(szFileName, "stg_status_member_blue_ready.tga");
else if(nTeam == MMT_SPECTATOR) strcpy(szFileName, "stg_status_member_observer.tga");
else strcpy(szFileName, "stg_status_member_normal_ready.tga");
break;
case MOSS_EQUIPMENT :
if(nTeam == MMT_RED) strcpy(szFileName, "stg_status_member_red_equip.tga");
else if(nTeam == MMT_BLUE) strcpy(szFileName, "stg_status_member_blue_equip.tga");
else if(nTeam == MMT_SPECTATOR) strcpy(szFileName, "stg_status_member_observer.tga");
else strcpy(szFileName, "stg_status_member_normal_equip.tga");
break;
}
}
/*
switch (state) {
case MOSS_NONREADY : strcpy(szFileNameState, " "); break;
case MOSS_READY : strcpy(szFileNameState, "char_stat_ready.tga"); break;
case MOSS_SHOP : strcpy(szFileNameState, "char_stat_shop.tga"); break;
case MOSS_EQUIPMENT : strcpy(szFileNameState, "char_stat_equip.tga"); break;
}
*/
pBitmap = MBitmapManager::Get(szFileName);
// pBitmapState = MBitmapManager::Get(szFileNameState);
pItem->m_pBitmap = pBitmap;
// pItem->m_pBitmapState = pBitmapState;
///////////////////////////////////////////////////////
/*
MCOLOR _color;
char sp_name[256];
if(GetUserInfoUID(puid,_color,sp_name,gid)) {
sprintf(szLevel,"Lv ---");
strcpy(pItem->m_szLevel,szLevel);
strcpy(pItem->m_szName,sp_name);
}
else {
sprintf(szLevel,"Lv %2d",nLevel);
strcpy(pItem->m_szLevel,szLevel);
strcpy(pItem->m_szName,szName);
}
*/
sprintf(szLevel,"Lv %2d",nLevel);
strcpy(pItem->m_szLevel,szLevel);
strcpy(pItem->m_szName,szName);
}
ZCharacterView* pCharView = (ZCharacterView*)ZApplication::GetGameInterface()->GetIDLResource()->FindWidget("Stage_Charviewer_");
if( pCharView != 0 && puid == pCharView->m_Info.UID )
{
pCharView->m_Info.bMaster = isMaster;
pCharView->m_Info.m_pMnTeam->Set_CheckCrc((int) nTeam);
pCharView->m_Info.nStageState = state;
pCharView->m_Info.nLevel = nLevel;
pCharView->SetText(szName);
}
if( ZGetMyUID() == puid )
{
bool bBlue, bRed;
bBlue = bRed = false;
if( nTeam == MMT_BLUE) bBlue = true;
if( nTeam == MMT_RED) bRed = true;
MButton* pButton = (MButton*)ZApplication::GetGameInterface()->GetIDLResource()->FindWidget("StageTeamBlue");
pButton->SetCheck( bBlue );
pButton = (MButton*)ZApplication::GetGameInterface()->GetIDLResource()->FindWidget("StageTeamRed");
pButton->SetCheck( bRed );
}
// pCharView->m_Info.m_pMnTeam->SetWarpingAdd(GetTickCount());
}
bool ZPlayerListBox::OnCommand(MWidget* pWidget, const char* szMessage)
{
if(pWidget==m_pButton) {
if( strcmp(szMessage, MBTN_CLK_MSG)==0 ) {
switch(GetMode()) {
//채널안에서 로테이트
case PLAYERLISTMODE_CHANNEL :
SetMode(PLAYERLISTMODE_CHANNEL_FRIEND);
break;
case PLAYERLISTMODE_CHANNEL_FRIEND :
SetMode(PLAYERLISTMODE_CHANNEL_CLAN);
break;
case PLAYERLISTMODE_CHANNEL_CLAN :
SetMode(PLAYERLISTMODE_CHANNEL);
break;
// 스테이지 안에서..
case PLAYERLISTMODE_STAGE :
// SetMode(PLAYERLISTMODE_STAGE_FRIEND);
break;
case PLAYERLISTMODE_STAGE_FRIEND :
/*
if(!ZGetMyInfo()->IsClanJoined()) // 클랜이 없으면 넘어간다
SetMode(PLAYERLISTMODE_STAGE);
else
SetMode(PLAYERLISTMODE_STAGE_CLAN);
*/
break;
case PLAYERLISTMODE_STAGE_CLAN :
// SetMode(PLAYERLISTMODE_STAGE);
break;
default:
SetMode(PLAYERLISTMODE_CHANNEL);
break;
}
return true;
}
}else
if( strcmp(szMessage, "selected")==0 ) {
if(m_nSelItem != -1) {
ZStagePlayerListItem* pItem = (ZStagePlayerListItem*)Get(m_nSelItem);
if(pItem) {
MUID uid = pItem->m_PlayerUID;
// 플레이어를 클릭하면 좌측의 캐릭터뷰에 해당 캐릭터 이미지가
// 뜨는거 막음. 아직 캐릭터 정보까지 변경 안되는 관계로... -_-;(동환)
ZCharacterView* pCharView = (ZCharacterView*)ZApplication::GetGameInterface()->GetIDLResource()->FindWidget("Stage_Charviewer");
if(pCharView!=0) pCharView->SetCharacter( uid );
}
}
// ZStagePlayerListItem* pItem = (ZStagePlayerListItem*) pWidget;
return true;
}
else if(strcmp(szMessage, "selected2")==0) {
// 차후 메뉴로 수정~
if((GetKeyState(VK_MENU)&0x8000)!=0) {
// ZStagePlayerListItem* pItem = (ZStagePlayerListItem*) pWidget;
if(m_nSelItem != -1) {
ZStagePlayerListItem* pItem = (ZStagePlayerListItem*)Get(m_nSelItem);
if(pItem) {
char temp[1024];
sprintf(temp,"/kick %s", pItem->m_szName);
ZPostStageChat(ZGetGameClient()->GetPlayerUID(), ZGetGameClient()->GetStageUID(), temp);
}
}
}
}
return true;
}
bool ZPlayerListBox::OnEvent(MEvent* pEvent, MListener* pListener)
{
MRECT rtClient = GetClientRect();
if(pEvent->nMessage==MWM_RBUTTONDOWN) {
if(rtClient.InPoint(pEvent->Pos)==true) {
int nSelItem = FindItem(pEvent->Pos);
if (nSelItem != -1) {
ZLobbyPlayerListItem* pItem = (ZLobbyPlayerListItem*)Get(nSelItem);
bool bShow = true;
MCOLOR _color;
char sp_name[256];
MMatchUserGradeID gid;
if(pItem->GetUID() == ZGetMyUID() &&
GetMode()!=PLAYERLISTMODE_CHANNEL_CLAN)
bShow = false;
GetUserInfoUID(pItem->GetUID(),_color,sp_name,gid);
if((gid==MMUG_DEVELOPER) || (gid==MMUG_ADMIN) || (gid == MMUG_STAFF) || (gid == MMUG_EVENTMASTER)) { // 개발자나 관리자라면..
bShow = false;
}
SetSelIndex(nSelItem);
if (bShow) {
ZPlayerMenu* pMenu = ZApplication::GetGameInterface()->GetPlayerMenu();
pMenu->SetTargetName(pItem->GetString());
pMenu->SetTargetUID(pItem->GetUID());
switch(GetMode()) {
case PLAYERLISTMODE_CHANNEL:
pMenu->SetupMenu(ZPLAYERMENU_SET_LOBBY);
break;
case PLAYERLISTMODE_STAGE:
pMenu->SetupMenu(ZPLAYERMENU_SET_STAGE);
break;
case PLAYERLISTMODE_CHANNEL_FRIEND:
pMenu->SetupMenu(ZPLAYERMENU_SET_FRIEND);
break;
case PLAYERLISTMODE_STAGE_FRIEND:
pMenu->SetupMenu(ZPLAYERMENU_SET_FRIEND);
break;
case PLAYERLISTMODE_CHANNEL_CLAN:
if(pItem->GetUID() == ZGetMyUID())
pMenu->SetupMenu(ZPLAYERMENU_SET_CLAN_ME);
else
pMenu->SetupMenu(ZPLAYERMENU_SET_CLAN);
break;
default:
_ASSERT("Unknown PlayerMenu Setup");
};
// 위치를 조절해준다
/* MPOINT posItem;
GetItemPos(&posItem, nSelItem);
MPOINT posMenu;
posMenu.x = posItem.x + GetRect().w/2;
posMenu.y = posItem.y + GetItemHeight()/2;
posMenu=MClientToScreen(this,posMenu);
if(posMenu.y+pMenu->GetRect().h > MGetWorkspaceHeight()) {
posMenu.y-= pMenu->GetRect().h ;
}
pMenu->Show(posMenu.x, posMenu.y, true);
*/
MPOINT posItem;
posItem = pEvent->Pos;
MPOINT posMenu = MClientToScreen(this, posItem);
if ( (posMenu.x + pMenu->GetClientRect().w) > (MGetWorkspaceWidth() - 5))
posMenu.x = MGetWorkspaceWidth() - pMenu->GetClientRect().w - 5;
if ( (posMenu.y + pMenu->GetClientRect().h) > (MGetWorkspaceHeight() - 5))
posMenu.y = MGetWorkspaceHeight() - pMenu->GetClientRect().h - 5;
pMenu->Show( posMenu.x, posMenu.y);
}
return true;
}
}
}
// 플레이어 정보 출력
else if ( pEvent->nMessage == MWM_LBUTTONDBLCLK)
{
if ( rtClient.InPoint( pEvent->Pos) == true)
{
int nSelItem = FindItem( pEvent->Pos);
if ( nSelItem != -1)
{
}
}
}
/* if (GetToolTip()) {
if ( (GetMode() == PLAYERLISTMODE_CHANNEL_FRIEND) || (GetMode() == PLAYERLISTMODE_STAGE_FRIEND) ) {
if(rtClient.InPoint(pEvent->Pos)==true) {
int nSelItem = FindItem(pEvent->Pos);
if (nSelItem != -1) {
ZFriendPlayerListItem* pItem = (ZFriendPlayerListItem*)Get(nSelItem);
MPOINT posItem;
GetItemPos(&posItem, nSelItem);
MPOINT posToolTip;
posToolTip.x = GetRect().x + posItem.x + GetRect().w/2;
posToolTip.y = GetRect().y + posItem.y + GetItemHeight()/2;
GetToolTip()->SetPosition(posToolTip.x, posToolTip.y);
GetToolTip()->SetText(pItem->GetLocation());
} else {
GetToolTip()->Show(false);
}
}
} else {
GetToolTip()->Show(false);
}
}
*/
return MListBox::OnEvent(pEvent, pListener);;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/*
IMPLEMENT_LOOK(ZStagePlayerListBox, ZPlayerListBoxLook)
////////////////////////////////////////////////////////////////////////////////////////////////////
ZStagePlayerListBox::ZStagePlayerListBox(const char* szName, MWidget* pParent, MListener* pListener)
: MListBox(szName, pParent, pListener)
{
LOOK_IN_CONSTRUCTOR()
SetVisibleHeader(false);
m_bAbsoulteTabSpacing = true;
m_MyUID = MUID(0,0);
m_uidChannel = MUID(0,0);
m_nTotalPlayerCount = 0;
m_nPage = 0;
m_bVisible = true;
AddField(" ", 23);//icon
AddField(" ",130);//name
AddField(" ", 23);//state icon
AddField(" ", 32);//level
SetItemHeight(23);
// m_pBitmap = NULL;
m_pBitmap = MBitmapManager::Get("playerlist_tab_game.png");
mSelectedPlayer = 0;
mStartToDisplay = 0;
mPlayerOrder.reserve( sizeof(MUID)*100 );
// m_pScrollBar = new MScrollBar( this, this );
// ZApplication::GetGameInterface()->GetIDLResource()->InsertWidget("PlayerListScrollBar", m_pScrollBar );
// AddPlayer(MUID(0,0), MOSS_READY , "aaaaa", 10 ,true ,MMT_RED );
// AddPlayer(MUID(0,1), MOSS_SHOP , "bbbbb", 11 ,false,MMT_BLUE);
// AddPlayer(MUID(0,2), MOSS_EQUIPMENT , "ccccc", 12 ,false,MMT_RED );
// AddPlayer(MUID(0,3), MOSS_NONREADY , "ddddd", 13 ,false,MMT_BLUE);
m_bAlwaysVisibleScrollbar = false;
m_bHideScrollBar = true;
m_pScrollBar->SetVisible(false);
m_pScrollBar->Enable(false);
m_pScrollBar->m_nDebugType = 3;
m_nDebugType = 2;
m_nOldW = RGetScreenWidth();
}
ZStagePlayerListBox::~ZStagePlayerListBox(void)
{
}
void ZStagePlayerListBox::SetBitmap( MBitmap* pBitmap)
{
m_pBitmap = pBitmap;
}
void ZStagePlayerListBox::Resize(float x,float y)
{
// OnReSize();
}
float ZStagePlayerListBox::OnReSize()
{
int newW = RGetScreenWidth();
float fA = GetF(newW);
m_nItemHeight = 23 * fA;
MLISTFIELD* fi;
for(int i=0;i<m_Fields.GetCount();i++) {
fi = m_Fields.Get(i);
if(i==0) fi->nTabSize = 23 * fA;
else if(i==1) fi->nTabSize = 130 * fA;
else if(i==2) fi->nTabSize = 23 * fA;
else if(i==3) fi->nTabSize = 32 * fA;
}
return fA;
}
void ZStagePlayerListBox::DelPlayer(MUID& puid)
{
ZStagePlayerListItem* pItem = NULL;
for(int i=0;i<GetCount();i++) {
pItem = (ZStagePlayerListItem*)Get(i);
if(pItem->m_PlayerUID==puid){
Remove(i);
return;
}
}
}
// 나중에 바꾸자 바쁘다.. 새벽 5:16분..
ZStagePlayerListItem* ZStagePlayerListBox::GetUID(MUID uid)
{
ZStagePlayerListItem* pItem = NULL;
for(int i=0;i<GetCount();i++) {
pItem = (ZStagePlayerListItem*)Get(i);
if(pItem->m_PlayerUID==uid)
return pItem;
}
return NULL;
}
void ZStagePlayerListBox::UpdatePlayer(MUID& puid,eStagePlayerState state, char* szName, int nLevel ,bool isMaster,int nTeam)
{
ZStagePlayerListItem* pItem = GetUID(puid);
if(pItem) {
char szFileName[64] = "";
char szFileNameState[64] = "";
char szLevel[64];
sprintf(szLevel,"Lv %2d",nLevel);
MBitmap* pBitmap = NULL;
MBitmap* pBitmapState = NULL;
if(isMaster) {
if(nTeam == MMT_RED) strcpy(szFileName, "stg_status_master_red.tga");
else if(nTeam == MMT_BLUE) strcpy(szFileName, "stg_status_master_blue.tga");
else strcpy(szFileName, "stg_status_master_normal.tga");
}
else {
if(nTeam == MMT_RED) strcpy(szFileName, "stg_status_member_red.tga");
else if(nTeam == MMT_BLUE) strcpy(szFileName, "stg_status_member_blue.tga");
else strcpy(szFileName, " ");
}
switch (state) {
case MOSS_NONREADY : strcpy(szFileNameState, " "); break;
case MOSS_READY : strcpy(szFileNameState, "char_stat_ready.tga"); break;
case MOSS_SHOP : strcpy(szFileNameState, "char_stat_shop.tga"); break;
case MOSS_EQUIPMENT : strcpy(szFileNameState, "char_stat_equip.tga"); break;
}
pBitmap = MBitmapManager::Get(szFileName);
pBitmapState = MBitmapManager::Get(szFileNameState);
pItem->m_pBitmap = pBitmap;
pItem->m_pBitmapState = pBitmapState;
sprintf(szLevel,"Lv %2d",nLevel);
strcpy(pItem->m_szLevel,szLevel);
strcpy(pItem->m_szName,szName);
}
}
void ZStagePlayerListBox::AddPlayer(MMatchObjCache* pCache)
{
if(!pCache) return;
AddPlayer(pCache->GetUID(), MOSS_NONREADY,pCache->GetName(), pCache->GetLevel(),false,MMT_ALL);
}
void ZStagePlayerListBox::AddPlayer(MUID& puid, MMatchObjectStageState state, char* szName, int nLevel ,bool isMaster,MMatchTeam nTeam)
{
char szFileName[64] = "";
char szFileNameState[64] = "";
char szLevel[64];
sprintf(szLevel,"Lv %2d",nLevel);
MBitmap* pBitmap = NULL;
MBitmap* pBitmapState = NULL;
if(isMaster) {
if(nTeam == MMT_RED) strcpy(szFileName, "stg_status_master_red.tga");
else if(nTeam == MMT_BLUE) strcpy(szFileName, "stg_status_master_blue.tga");
else strcpy(szFileName, "stg_status_master_normal.tga");
}
else {
if(nTeam == MMT_RED) strcpy(szFileName, "stg_status_member_red.tga");
else if(nTeam == MMT_BLUE) strcpy(szFileName, "stg_status_member_blue.tga");
else strcpy(szFileName, " ");
}
switch (state) {
case MOSS_NONREADY : strcpy(szFileNameState, " "); break;
case MOSS_READY : strcpy(szFileNameState, "char_stat_ready.tga"); break;
case MOSS_SHOP : strcpy(szFileNameState, "char_stat_shop.tga"); break;
case MOSS_EQUIPMENT : strcpy(szFileNameState, "char_stat_equip.tga"); break;
}
pBitmap = MBitmapManager::Get(szFileName);
pBitmapState = MBitmapManager::Get(szFileNameState);
// MListBox::Add(new ZLobbyPlayerListItem(puid, pBitmap, szName, szLevel));
MListBox::Add(new ZStagePlayerListItem(puid, pBitmap, pBitmapState, szName, szLevel));
}
bool ZStagePlayerListBox::OnEvent(MEvent* pEvent, MListener* pListener)
{
if(pEvent->nMessage==MWM_MOUSEMOVE) {
}
else if(pEvent->nMessage==MWM_MBUTTONDOWN) {
int k=0;
}
return MListBox::OnEvent(pEvent, pListener);
}
*/
/*
void ZStagePlayerListBox::AddPlayer( MMatchObjCache* pCache )
{
MUID uid = pCache->GetUID();
sPlayerInfo* pInfo = new sPlayerInfo;
strcpy( pInfo->szName, pCache->GetName() );
pInfo->Level = pCache->GetLevel();
MListBox::Add(new ZLobbyPlayerListItem(uidItem, pIconBitmap, szName, szWeight, szSlot, szPrice));
}
*/
MUID ZPlayerListBox::GetSelectedPlayerUID()
{
ZLobbyPlayerListItem* pItem = (ZLobbyPlayerListItem*)GetSelItem();
if(!pItem) return MUID(0,0);
return pItem->GetUID();
}
void ZPlayerListBox::SelectPlayer(MUID uid)
{
for(int i=0;i<GetCount();i++)
{
ZLobbyPlayerListItem* pItem = (ZLobbyPlayerListItem*)Get(i);
if(pItem->GetUID()==uid){
SetSelIndex(i);
return;
}
}
}
void ZPlayerListBox::MultiplySize( float byIDLWidth, float byIDLHeight, float byCurrWidth, float byCurrHeight )
{
MListBox::MultiplySize(byIDLWidth, byIDLHeight, byCurrWidth, byCurrHeight);
OnSize(GetRect().w, GetRect().h); // onsize안에서 커스텀하게 처리하는 부분들을 실행시키자
} | [
"jduncan0392@gmail.com"
] | jduncan0392@gmail.com |
fdcc6409003593cf677e17af993790ea11e79f41 | 65bdd54c9459fb5c2f5a2e8c601888046e663602 | /tower_of_hanoi.cpp | 73fcb3a732f09eb186422b75f3ca9ece4598c8e7 | [] | no_license | Adityasharma15/Agorithms | 67f6478985d572f451a78ea82878d9bf55b9cafe | 5ff6d08c79fccc5f494de67e3ad850f693c8ee80 | refs/heads/master | 2021-07-07T21:55:21.830493 | 2020-11-19T12:55:51 | 2020-11-19T12:55:51 | 212,204,052 | 5 | 2 | null | 2020-10-04T08:23:23 | 2019-10-01T21:36:06 | C++ | UTF-8 | C++ | false | false | 512 | cpp | #include<bits/stdc++.h>
#define ll long long
using namespace std;
void tower_of_hanoi(ll n , ll a,ll c,ll b)
{
if(n==1)
{
cout << "move disk 1 from rod " << a << " to rod " << c << "\n";
return;
}
tower_of_hanoi(n-1, a, b,c);
cout << "move disk " << n << "from rod " << a << " to rod " << c << "\n";
tower_of_hanoi(n-1,b,c,a);
}
int main()
{
ll t;
cin >> t;
while(t--)
{
ll n;
cin >> n;
ll a = 1, c = 2 , b = 3;
tower_of_hanoi(n , a, b, c);
}
cout << "\n";
} | [
"aditya.sharma5645@gmail.com"
] | aditya.sharma5645@gmail.com |
8e7c4f0a2fc439b747cc24aece30c0aa4b2a8b17 | c9f6a1d35a6879fb3cd18b57a6b89d2fd5d316d6 | /src/include/type/decimal_type.h | feeaf4fa2eba53e6238145cfb61185c5c57197a0 | [
"MIT"
] | permissive | kevinjzhang/bustub | 1b1c446a40841263d6c93ab0642ae104818f4edd | 4e1ac2fa482054ec4e9d90580067a06df0fada31 | refs/heads/master | 2020-11-24T02:56:11.917553 | 2020-01-31T12:45:07 | 2020-01-31T12:45:07 | 227,935,446 | 0 | 0 | MIT | 2019-12-13T22:56:20 | 2019-12-13T22:56:19 | null | UTF-8 | C++ | false | false | 2,438 | h | //===----------------------------------------------------------------------===//
//
// BusTub
//
// decimal_type.h
//
// Identification: src/include/type/decimal_type.h
//
// Copyright (c) 2015-2019, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#pragma once
#include <string>
#include "type/numeric_type.h"
namespace bustub {
class DecimalType : public NumericType {
public:
DecimalType();
// DecimalValue(DecDef definition);
// Other mathematical functions
Value Add(const Value &left, const Value &right) const override;
Value Subtract(const Value &left, const Value &right) const override;
Value Multiply(const Value &left, const Value &right) const override;
Value Divide(const Value &left, const Value &right) const override;
Value Modulo(const Value &left, const Value &right) const override;
Value Min(const Value &left, const Value &right) const override;
Value Max(const Value &left, const Value &right) const override;
Value Sqrt(const Value &val) const override;
bool IsZero(const Value &val) const override;
// Comparison functions
CmpBool CompareEquals(const Value &left, const Value &right) const override;
CmpBool CompareNotEquals(const Value &left, const Value &right) const override;
CmpBool CompareLessThan(const Value &left, const Value &right) const override;
CmpBool CompareLessThanEquals(const Value &left, const Value &right) const override;
CmpBool CompareGreaterThan(const Value &left, const Value &right) const override;
CmpBool CompareGreaterThanEquals(const Value &left, const Value &right) const override;
Value CastAs(const Value &val, TypeId type_id) const override;
// Decimal types are always inlined
bool IsInlined(const Value &val) const override { return true; }
// Debug
std::string ToString(const Value &val) const override;
// Serialize this value into the given storage space
void SerializeTo(const Value &val, char *storage) const override;
// Deserialize a value of the given type from the given storage space.
Value DeserializeFrom(const char *storage) const override;
// Create a copy of this value
Value Copy(const Value &val) const override;
private:
Value OperateNull(const Value &left, const Value &right) const override;
};
} // namespace bustub
| [
"root@DESKTOP-P2AL5JC.localdomain"
] | root@DESKTOP-P2AL5JC.localdomain |
dd392106151b1d0befd00a4e4d298b5dd51bf38a | ad273708d98b1f73b3855cc4317bca2e56456d15 | /aws-cpp-sdk-synthetics/source/model/DescribeRuntimeVersionsRequest.cpp | 739316d75f9199f40751c994b6f3c5c16f880c9d | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | novaquark/aws-sdk-cpp | b390f2e29f86f629f9efcf41c4990169b91f4f47 | a0969508545bec9ae2864c9e1e2bb9aff109f90c | refs/heads/master | 2022-08-28T18:28:12.742810 | 2020-05-27T15:46:18 | 2020-05-27T15:46:18 | 267,351,721 | 1 | 0 | Apache-2.0 | 2020-05-27T15:08:16 | 2020-05-27T15:08:15 | null | UTF-8 | C++ | false | false | 1,293 | cpp | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/synthetics/model/DescribeRuntimeVersionsRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Synthetics::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
DescribeRuntimeVersionsRequest::DescribeRuntimeVersionsRequest() :
m_nextTokenHasBeenSet(false),
m_maxResults(0),
m_maxResultsHasBeenSet(false)
{
}
Aws::String DescribeRuntimeVersionsRequest::SerializePayload() const
{
JsonValue payload;
if(m_nextTokenHasBeenSet)
{
payload.WithString("NextToken", m_nextToken);
}
if(m_maxResultsHasBeenSet)
{
payload.WithInteger("MaxResults", m_maxResults);
}
return payload.View().WriteReadable();
}
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
558ac644e3b70322830ad020c77aec818255be87 | 2ea03c322a0911154683f096ac9598442cdc26a7 | /epuck-simulation/src/sort_loop_function.cpp | 1f8e31e637149fc61ca7e11f9e867a645513565b | [] | no_license | knudsen97/bachelor-thesis | 4fa4a863bcdcbe69b91a552c0c2966e8539d5431 | 94a94e05a57c2984fc66849a9ac0e6fb4b3d3ccc | refs/heads/master | 2023-05-09T21:51:07.178726 | 2021-05-30T10:26:16 | 2021-05-30T10:26:16 | 333,049,308 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,906 | cpp | #include "sort_loop_function.h"
#include <argos3/plugins/simulator/entities/box_entity.h>
#include <argos3/plugins/simulator/entities/cylinder_entity.h>
#include <argos3/plugins/robots/foot-bot/simulator/footbot_entity.h>
#include <sstream>
#include <list>
/****************************************/
/****************************************/
static const Real FB_RADIUS = 0.085036758f;
static const Real FB_AREA = ARGOS_PI * Square(0.085036758f);
static const std::string FB_CONTROLLER = "ffc";
static const UInt32 MAX_PLACE_TRIALS = 20;
static const UInt32 MAX_ROBOT_TRIALS = 20;
/****************************************/
/****************************************/
CSortLoopFunction::CSortLoopFunction() {
}
/****************************************/
/****************************************/
CSortLoopFunction::~CSortLoopFunction() {
}
/****************************************/
/****************************************/
void CSortLoopFunction::Init(TConfigurationNode& t_tree) {
try {
CVector3 min_range, max_range;
CVector3 min_orientation, max_orientation;
CVector3 min_size, max_size;
UInt32 unBox;
TConfigurationNodeIterator itDistr;
/* Get current node */
for(itDistr = itDistr.begin(&t_tree);
itDistr != itDistr.end();
++itDistr)
{
TConfigurationNode& tDistr = *itDistr;
if(itDistr->Value() == "box") {
GetNodeAttribute(tDistr, "min_range", min_range);
GetNodeAttribute(tDistr, "max_range", max_range);
GetNodeAttribute(tDistr, "min_orientation", min_orientation);
GetNodeAttribute(tDistr, "max_orientation", max_orientation);
GetNodeAttribute(tDistr, "min_size", min_size);
GetNodeAttribute(tDistr, "max_size", max_size);
GetNodeAttribute(tDistr, "quantity", unBox);
PlaceBox(min_range, max_range, min_orientation, max_orientation, min_size, max_size, unBox);
}
}
}
catch(CARGoSException& ex) {
THROW_ARGOSEXCEPTION_NESTED("Error initializing the loop functions", ex);
}
}
/****************************************/
/****************************************/
void CSortLoopFunction::PlaceBox( const CVector3& min_range,
const CVector3& max_range,
const CVector3& min_size,
const CVector3& max_size,
const CVector3& _whiteGoal,
const CVector3& _blueGoal,
UInt32 un_box,
const double distanceThreshold){
try {
CBoxEntity* pcB;
std::ostringstream cBId;
for(size_t i = 0; i < un_box; ++i) {
/* Make the id */
cBId.str("");
cBId << "box_" << i;
CRandom::CRNG* pcRNG = CRandom::CreateRNG("argos");
CVector3 c_position;
CQuaternion c_orientation_quartention;
CVector3 c_size;
/* Get range for position */
CRange<double> cRangeRangeX(min_range[0], max_range[0]);
CRange<double> cRangeRangeY(min_range[1], max_range[1]);
CRange<double> cRangeRangeZ(min_range[2], max_range[2]);
/* Find positions not too close too eachother according to threshold */
argos::Real dist = 0;
if(boxLocations.size() == 0)
{
c_position.SetX(pcRNG->Uniform(cRangeRangeX));
c_position.SetY(pcRNG->Uniform(cRangeRangeY));
c_position.SetZ(pcRNG->Uniform(cRangeRangeZ));
boxLocations.push_back(c_position);
}
else
{
bool validLocationFound = false;
argos::Real dist = 0.0f;
while(!validLocationFound)
{
c_position.SetX(pcRNG->Uniform(cRangeRangeX));
c_position.SetY(pcRNG->Uniform(cRangeRangeY));
c_position.SetZ(pcRNG->Uniform(cRangeRangeZ));
int count = 0;
for(auto pos : boxLocations)
{
dist = argos::Distance(pos, c_position);
if(dist > distanceThreshold)
count++;
else
{
break;
}
}
if(count == boxLocations.size())
{
//argos::LOG << "dist: " << dist <<std::endl;
boxLocations.push_back(c_position);
dist = 0;
validLocationFound = true;
}
else
{
pcRNG = CRandom::CreateRNG("argos"); //Update random seed
}
count = 0;
}
}
/* Calculate orientation according to goal */
argos::CRadians orientation;
if(i%2 == 0) //Add blue box
orientation = argos::ATan2(_blueGoal.GetX() - c_position.GetX(), _blueGoal.GetY() - c_position.GetY());
else //Add white box
orientation = argos::ATan2(_whiteGoal.GetX() - c_position.GetX(), _whiteGoal.GetY() - c_position.GetY());
std::vector<argos::CRadians> box_orientation = {
orientation + argos::ToRadians(argos::CDegrees(45)),
argos::ToRadians(argos::CDegrees(0)),
argos::ToRadians(argos::CDegrees(0))
};
c_orientation_quartention.FromEulerAngles(
box_orientation[0],
box_orientation[1],
box_orientation[2]
);
/* Randomize size */
CRange<double> cRangeSizeX(min_size[0], max_size[0]);
CRange<double> cRangeSizeY(min_size[1], max_size[1]);
CRange<double> cRangeSizeZ(min_size[2], max_size[2]);
c_size.SetX(pcRNG->Uniform(cRangeSizeX));
c_size.SetY(pcRNG->Uniform(cRangeSizeY));
c_size.SetZ(pcRNG->Uniform(cRangeSizeZ));
/* Define new CBoxEntity */
pcB = new CBoxEntity(
cBId.str(),
c_position,
c_orientation_quartention,
true, //moveable
c_size,
20); //mass
argos::CLoopFunctions::AddEntity(*pcB);
if(i%2 == 0) //Add blue led
{
pcB->AddLED(argos::CVector3(0,0,0.2), argos::CColor::BLUE);
}
else //Add white led
{
pcB->AddLED(argos::CVector3(0,0,0.2), argos::CColor::WHITE);
}
}
}
catch(CARGoSException& ex) {
THROW_ARGOSEXCEPTION_NESTED("While placing boxes", ex);
}
}
/****************************************/
/****************************************/
REGISTER_LOOP_FUNCTIONS(CSortLoopFunction, "sort_loop_function");
/****************************************/
/****************************************/
| [
"claus.huynh@yahoo.dk"
] | claus.huynh@yahoo.dk |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.