blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 7
109
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
3
| license_type
stringclasses 2
values | repo_name
stringlengths 9
56
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 5
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 8.26M
223M
⌀ | star_events_count
int64 0
25
| fork_events_count
int64 0
11
| gha_license_id
stringclasses 4
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 2
values | src_encoding
stringclasses 5
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 35
345k
| extension
stringclasses 7
values | content
stringlengths 35
345k
| authors
sequencelengths 1
29
| author_lines
sequencelengths 1
29
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
819eb928fa03acd974c3e18443532022f13c2f05 | 711b11d08abdb3a7df2574b0b4c86af21c5c6750 | /dest.h | e06af74e0264187915ab70b86b0e67aa85d2a79f | [] | no_license | nflath/MSP430Emulator | 4aee9e093113cc41d9041a1728eedd742fd786b2 | a97a1b97b895b3533597bcdb69bec8b75db395df | refs/heads/master | 2021-01-13T01:54:55.258203 | 2015-08-25T05:10:04 | 2015-08-25T05:10:04 | 41,343,926 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,382 | h | #include <assert.h>
#ifndef DEST_H
#define DEST_H
#include "error.h"
// Classes representing 'Destinations' types in MSP430 - See the section
// 'MSP430 addressing modes' in https://en.wikipedia.org/wiki/TI_MSP430#MSP430_CPU
class State;
class Dest {
// Virtual base clase.
public:
virtual void set(short value) { notimplemented(); }
// Sets the value of this destination
virtual void setByte(unsigned char value) { notimplemented(); }
// Sets the value of this destination (byte addressing mode)
virtual short value() { notimplemented(); return 0;}
// Returns the value of this destination
virtual unsigned char valueByte() { notimplemented(); return 0;}
// Returns the value of this destination(byte addressing mode)
virtual std::string toString() = 0;
// Returns a string representation of this destination
virtual bool usedExtensionWord() { return false; }
// Whether an extension word was used to represent this destination
virtual unsigned char size() { return usedExtensionWord() ? 2 : 0; }
// How many extra bytes this destination took up in the assembly
};
class RegisterDest : public Dest {
// Destination representing a register (r14)
public:
virtual std::string toString();
virtual void set(short value);
virtual void setByte(unsigned char value);
virtual short value();
virtual unsigned char valueByte();
RegisterDest(unsigned short reg_) : reg(reg_) {}
unsigned short reg;
};
class RegisterOffsetDest : public RegisterDest {
// Destination representing the memory address at a register plus an offset (0x40(r14))
public:
virtual std::string toString();
virtual bool usedExtensionWord() { return true; }
virtual void set(short value);
virtual void setByte(unsigned char value);
virtual short value();
virtual unsigned char valueByte();
RegisterOffsetDest(unsigned short reg_, short offset_) :
RegisterDest(reg_),
offset(offset_) {
}
short offset;
};
class AbsoluteDest : public Dest {
// Destination that is just a memory address (&0x4400)
public:
virtual std::string toString();
virtual bool usedExtensionWord() { return true; }
virtual void set(short value);
virtual void setByte(unsigned char value);
virtual unsigned char valueByte();
AbsoluteDest(unsigned short address_) :
address(address_) {
}
unsigned short address;
};
extern State* s;
#endif
| [
"[email protected]"
] | [
[
[
1,
89
]
]
] |
06c1ab5ff8ab138987ba9ad1ed0f423d945bafe7 | 6817617489ef291d4d53ac844ba7a2b14cc17ae2 | /11942.cpp | dcc6c32bd3395a76801df96fb6b8693215e020ec | [] | no_license | Asad51/UVA-Problem-Solving | 1932f2cd73261cd702f58d4f189a4a134dbd6286 | af28ae36a2074d4e2a67670dbbbd507438c56c3e | refs/heads/master | 2020-03-23T14:52:49.420143 | 2019-10-24T17:03:37 | 2019-10-24T17:03:37 | 120,592,261 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 449 | cpp | #include <bits/stdc++.h>
using namespace std;
int main(int argc, char const *argv[])
{
int t;
cin>>t;
cout<<"Lumberjacks:\n";
while(t--){
bool in = true;
bool dec = true;
int p;
for(int i=0; i<10; i++){
int n;
cin>>n;
if(!i){
p = n;
continue;
}
if(n<p || !in)
in = false;
if(n>p || !dec)
dec = false;
p = n;
}
if(!in && !dec)
cout<<"Unordered\n";
else
cout<<"Ordered\n";
}
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
32
]
]
] |
cbee84c2e52dc1341528f8254aaf41ac321f936c | 2869112fdc836e565f9fe68e290affc1e223c1d8 | /pythran/pythonic/include/__builtin__/set/isdisjoint.hpp | 10ac38270e03ff35d15b79143e6164321a7b5afb | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | coyotte508/pythran | ab26e9ddb9a9e00e77b457df316aa33dc8435914 | a5da78f2aebae712a2c6260ab691dab7d09e307c | refs/heads/master | 2021-01-15T10:07:09.597297 | 2015-05-01T07:00:42 | 2015-05-01T07:00:42 | 35,020,532 | 0 | 0 | null | 2015-05-04T07:27:29 | 2015-05-04T07:27:29 | null | UTF-8 | C++ | false | false | 621 | hpp | #ifndef PYTHONIC_INCLUDE_BUILTIN_SET_ISDISJOINT_HPP
#define PYTHONIC_INCLUDE_BUILTIN_SET_ISDISJOINT_HPP
#include "pythonic/utils/proxy.hpp"
#include "pythonic/types/set.hpp"
namespace pythonic {
namespace __builtin__ {
namespace set {
template<class T, class U>
bool
isdisjoint(types::set<T> const& calling_set, U const& arg_set);
template<class U>
bool
isdisjoint(types::empty_set const& calling_set, U const& arg_set);
PROXY_DECL(pythonic::__builtin__::set, isdisjoint);
}
}
}
#endif
| [
"[email protected]"
] | [
[
[
1,
27
]
]
] |
36ffd69f21bf2277cef7fea364841c3a12967399 | d04b3793ed3611d5bdc8e3bc990bf9eb8562cece | /CheatSheet.cpp | e00970193f00ed69d57e398e36db43427aaf83b0 | [] | no_license | nebulou5/CppExamples | c7198cdc24ba1d681cc20738a3b21e2b17b98498 | 98044227b888a7f9faa8934ab76bb3cac443b75e | refs/heads/master | 2023-09-01T18:55:44.584418 | 2016-01-25T17:57:40 | 2016-01-25T17:57:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,222 | cpp | #include <iostream>
using namespace std;
void printI(int &i) {
cout << "Printing i: " << i << endl;
}
int main() {
// defining a basic 10 integer array
int x[10];
int xLen = sizeof(x) / sizeof(x[0]);
for (int i = 0; i < xLen; i++) {
cout << x[i] << endl;
}
// defining an array in place
float v[] = {1.1, 2.2, 3.3};
int vLen = sizeof(v) / sizeof(v[0]);
for (int i = 0; i < vLen; i++ ) {
cout << v[i] << endl;
}
// multidimensional array
float ab[3][3];
int abLen = sizeof(ab) / sizeof(ab[0]);
for (int i = 0; i < abLen; i++) {
printI(i);
for (int j = 0; j < abLen; j++) {
cout << "Element: " << i << ", " << j << ": " << ab[i][j] << endl;
}
}
// array allocated at runtime
int someUserDefinedSize = 3;
float* rta = new float[someUserDefinedSize]; // pointer dynamically allocates memory at runtime
delete[] rta; // but programmer must clean up the memory afterwards
// basic pointer usage
int i = 3;
int *j = &i; // store address of i @ "j"
int k = *j; // dereference address stored @ "j"
// initializing a nullptr
// valid in c++ 11 and beyond
int *nullPointer = nullptr;
int *nullPointerSynonymous{}; // also sets a nullptr
}
| [
"[email protected]"
] | [
[
[
1,
52
]
]
] |
73bbdcfbe50a724cb152edeb3ed8f2aed3d76d69 | 28b90ad96790edd30edc5ba95137cc20261599b5 | /nodemcu/MPU_6050_flask_json/MPU_6050_flask_json.ino | 134d2fabdbfb2a13cb534495c378ee4397e38c4e | [] | no_license | anshulahuja98/Codefundo-18-IITJ | b09e1b200a5e5d9bbe23f58addc3460a1a19d732 | bfae0dde99cd9133bdeabd06fdb73b512214b1f9 | refs/heads/master | 2020-03-30T01:52:30.166915 | 2019-02-10T04:34:35 | 2019-02-10T04:34:35 | 150,599,578 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 5,804 | ino |
#include <Wire.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
const uint8_t MPU6050SlaveAddress = 0x68;
const uint8_t scl = D1;
const uint8_t sda = D2;
const uint16_t AccelScaleFactor = 16384;
const uint16_t GyroScaleFactor = 131;
const uint8_t MPU6050_REGISTER_SMPLRT_DIV = 0x19;
const uint8_t MPU6050_REGISTER_USER_CTRL = 0x6A;
const uint8_t MPU6050_REGISTER_PWR_MGMT_1 = 0x6B;
const uint8_t MPU6050_REGISTER_PWR_MGMT_2 = 0x6C;
const uint8_t MPU6050_REGISTER_CONFIG = 0x1A;
const uint8_t MPU6050_REGISTER_GYRO_CONFIG = 0x1B;
const uint8_t MPU6050_REGISTER_ACCEL_CONFIG = 0x1C;
const uint8_t MPU6050_REGISTER_FIFO_EN = 0x23;
const uint8_t MPU6050_REGISTER_INT_ENABLE = 0x38;
const uint8_t MPU6050_REGISTER_ACCEL_XOUT_H = 0x3B;
const uint8_t MPU6050_REGISTER_SIGNAL_PATH_RESET = 0x68;
int16_t AccelX, AccelY, AccelZ, Temperature, GyroX, GyroY, GyroZ;
String flag_payload = "";
int o =0;
void setup() {
Serial.begin(115200);
Wire.begin(sda, scl);
MPU6050_Init();
WiFi.begin("null", "patanahi1");
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.println("Waiting for connection");
}
pinMode(10 , OUTPUT);
digitalWrite(10, LOW);
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
double Ax, Ay, Az, T, Gx, Gy, Gz, dev_id;
Read_RawValue(MPU6050SlaveAddress, MPU6050_REGISTER_ACCEL_XOUT_H);
//divide each with their sensititvity scale factor
Ax = (double)AccelX / AccelScaleFactor;
Ay = (double)AccelY / AccelScaleFactor;
Az = (double)AccelZ / AccelScaleFactor;
T = (double)Temperature / 340 + 36.53; //temperature formula
Gx = (double)GyroX / GyroScaleFactor;
Gy = (double)GyroY / GyroScaleFactor;
Gz = (double)GyroZ / GyroScaleFactor;
dev_id = 2222;
Serial.print("Ax: "); Serial.print(Ax);
Serial.print(" Ay: "); Serial.print(Ay);
Serial.print(" Az: "); Serial.print(Az);
Serial.print(" T: "); Serial.print(T);
Serial.print(" Gx: "); Serial.print(Gx);
Serial.print(" Gy: "); Serial.print(Gy);
Serial.print(" Gz: "); Serial.println(Gz);
StaticJsonBuffer<300> JSONbuffer; //Declaring static JSON buffer
JsonObject& JSONencoder = JSONbuffer.createObject();
JSONencoder["Sensor type"] = "Acceleration";
JSONencoder["deviceid"] = dev_id;
JsonArray& values = JSONencoder.createNestedArray("values"); //JSON array
values.add(Ax); //Add value to array
values.add(Ay); //Add value to array
values.add(Az); //Add value to array
values.add(T); //Add value to array
JsonArray& timestamps = JSONencoder.createNestedArray("direction1"); //JSON array
timestamps.add("x direction"); //Add value to array
timestamps.add("y direction"); //Add value to array
timestamps.add("z direction"); //Add value to array
timestamps.add("Temperature"); //Add vaues to array
char JSONmessageBuffer[300];
JSONencoder.prettyPrintTo(JSONmessageBuffer, sizeof(JSONmessageBuffer));
Serial.println(JSONmessageBuffer);
HTTPClient http; //Declare object of class HTTPClient
http.begin("http://192.168.43.75:8090/post"); //Specify request destination
http.addHeader("Content-Type", "application/json"); //Specify content-type header
int httpCode = http.POST(JSONmessageBuffer); //Send the request
String payload = http.getString(); //Get the response payload
Serial.println(httpCode); //Print HTTP return code
Serial.println(payload); //Print request response payload
http.end(); //Close connection
http.begin("http://192.168.43.75:8090/get");
int httpCode1 = http.GET(); //Send the request
String payload_get = http.getString();
Serial.println(httpCode1); //Print HTTP return code
Serial.println(payload_get); //Print request response payload
if (payload_get == "1")
{
Serial.println("lasjdf liasdj fli");
o = 1;
}
http.end(); //Close connection
if (o == 1)
{
digitalWrite(10, HIGH);
}
}
else
{
Serial.println("Error in WiFi connection");
}
delay(100);
}
void I2C_Write(uint8_t deviceAddress, uint8_t regAddress, uint8_t data) {
Wire.beginTransmission(deviceAddress);
Wire.write(regAddress);
Wire.write(data);
Wire.endTransmission();
}
// read all 14 register
void Read_RawValue(uint8_t deviceAddress, uint8_t regAddress) {
Wire.beginTransmission(deviceAddress);
Wire.write(regAddress);
Wire.endTransmission();
Wire.requestFrom(deviceAddress, (uint8_t)14);
AccelX = (((int16_t)Wire.read() << 8) | Wire.read());
AccelY = (((int16_t)Wire.read() << 8) | Wire.read());
AccelZ = (((int16_t)Wire.read() << 8) | Wire.read());
Temperature = (((int16_t)Wire.read() << 8) | Wire.read());
GyroX = (((int16_t)Wire.read() << 8) | Wire.read());
GyroY = (((int16_t)Wire.read() << 8) | Wire.read());
GyroZ = (((int16_t)Wire.read() << 8) | Wire.read());
}
//configure MPU6050
void MPU6050_Init() {
delay(150);
I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_SMPLRT_DIV, 0x07);
I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_PWR_MGMT_1, 0x01);
I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_PWR_MGMT_2, 0x00);
I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_CONFIG, 0x00);
I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_GYRO_CONFIG, 0x00);//set +/-250 degree/second full scale
I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_ACCEL_CONFIG, 0x00);// set +/- 2g full scale
I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_FIFO_EN, 0x00);
I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_INT_ENABLE, 0x01);
I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_SIGNAL_PATH_RESET, 0x00);
I2C_Write(MPU6050SlaveAddress, MPU6050_REGISTER_USER_CTRL, 0x00);
}
| [
"[email protected]"
] | [
[
[
1,
163
]
]
] |
77e95d74adb0d91068d318a9f567bd723eb4bd30 | 8a970882a0be9f3d85edbf6ecec0050b762e8d80 | /GazEngine/gazengine/Entity.h | ded187d2149547f453fc7c141f5bfa9b3cc59aa9 | [] | no_license | simplegsb/gazengine | 472d1de8d300c8406ffec148844911fd21d5c1e0 | b0a7300aa535b14494789fb88c16d6dda1c4e622 | refs/heads/master | 2016-09-05T21:02:49.531802 | 2013-04-29T08:33:16 | 2013-04-29T08:33:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,553 | h | #ifndef ENTITY_H_
#define ENTITY_H_
#include <memory>
#include <string>
#include <vector>
class Component;
class Entity
{
public:
static const unsigned short UNCATEGORIZED = 0;
Entity(unsigned short category = UNCATEGORIZED, const std::string& name = std::string());
virtual ~Entity();
/**
* <p>
* Adds a component.
* </p>
*
* @param component The component to add.
*/
void addComponent(Component* component);
unsigned short getCategory() const;
/**
* <p>
* Retrieves the components.
* </p>
*
* @return The components.
*/
template<typename ComponentType>
std::vector<ComponentType*> getComponents() const;
unsigned int getId() const;
/**
* <p>
* Retrieves the name of this <code>Entity</code>.
* </p>
*
* @return The name of this <code>Entity</code>.
*/
const std::string& getName() const;
/**
* <p>
* Retrieves a single component.
* </p>
*
* @return The single component.
*/
template<typename ComponentType>
ComponentType* getSingleComponent() const;
/**
* <p>
* Removes a component.
* </p>
*
* @param component The component to remove.
*/
void removeComponent(const Component& component);
private:
unsigned short category;
/**
* <p>
* The components.
* </p>
*/
std::vector<Component*> components;
unsigned int id;
/**
* <p>
* The name of this <code>Entity</code>.
* </p>
*/
std::string name;
static unsigned int nextId;
};
#include "Entity.tpp"
#endif /* ENTITY_H_ */
| [
"[email protected]"
] | [
[
[
1,
94
]
]
] |
c1be7ed8331d413fbb32c4f4da225eabb0c94905 | 2d4346d0da0a4145f6bcc91a8cb2c0ab4d669d7e | /chat-up-server/src/Authentication/AuthenticationService.h | b172c8a7281e736007294715851af51947b6b669 | [] | no_license | xgallom/chat-up | 5570d069a495acf6398bdf1f62b1fb1d91289376 | 7cb664ce745cf041fb508b04165d2179563aa010 | refs/heads/master | 2020-04-18T05:40:58.487905 | 2019-01-29T22:36:04 | 2019-01-29T22:36:04 | 167,287,878 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 608 | h | //
// Created by xgallom on 1/27/19.
//
#ifndef CHAT_UP_AUTHENTICATIONSERVICE_H
#define CHAT_UP_AUTHENTICATIONSERVICE_H
#include <Messaging/Message.h>
#include <Messaging/MessageSender.h>
#include <Outcome.h>
#include <Authentication/User.h>
class AuthenticationStorage;
class AuthenticationService {
AuthenticationStorage &m_storage;
User m_user = User();
public:
AuthenticationService() noexcept;
Outcome::Enum run(MessageSender &sender, const Message &message);
bool registerUser(const User &user);
User user() const noexcept;
};
#endif //CHAT_UP_AUTHENTICATIONSERVICE_H
| [
"[email protected]"
] | [
[
[
1,
30
]
]
] |
fdb075167409c531a8ffa63f4eb5c358ff9f4c08 | 8da9d3c3e769ead17f5ad4a4cba6fb3e84a9e340 | /src/chila/lib/node/util.hpp | 51b98169af1da8738e7ec4fea35fe3d0da6b3455 | [] | no_license | blockspacer/chila | 6884a540fafa73db37f2bf0117410c33044adbcf | b95290725b54696f7cefc1c430582f90542b1dec | refs/heads/master | 2021-06-05T10:22:53.536352 | 2016-08-24T15:07:49 | 2016-08-24T15:07:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,721 | hpp | /* Copyright 2011-2015 Roberto Daniel Gimenez Gamarra ([email protected])
* (C.I.: 1.439.390 - Paraguay)
*/
#ifndef CHILA_LIB_NODE__UTIL_HPP
#define CHILA_LIB_NODE__UTIL_HPP
#include <chila/lib/misc/util.hpp>
#include "exceptions.hpp"
#define my_assert CHILA_LIB_MISC__ASSERT
#define CHILA_META_NODE__DEF_CHECK_BASES_ELEM(n, data, elem) \
chila::lib::node::checkAndAdd(list, [&]{ elem::check(newData.get()); });
#define CHILA_META_NODE__DEF_CHECK_BASES(Bases, defMyCheck) \
BOOST_PP_IF(defMyCheck, chila::lib::node::CheckDataUPtr createCheckData(chila::lib::node::CheckData *data) const;, ); \
BOOST_PP_IF(defMyCheck, void myCheck(chila::lib::node::CheckData *data = nullptr) const;, ); \
void check(chila::lib::node::CheckData *data = nullptr) const override \
{ \
chila::lib::node::CheckExceptionList list; \
auto newData = BOOST_PP_IF(defMyCheck, createCheckData(data), chila::lib::node::CheckDataUPtr()); \
BOOST_PP_SEQ_FOR_EACH(CHILA_META_NODE__DEF_CHECK_BASES_ELEM,,Bases) \
BOOST_PP_IF(defMyCheck, BOOST_PP_IDENTITY(\
chila::lib::node::checkAndAdd(list, [&]{ myCheck(newData.get()); }); \
), BOOST_PP_EMPTY)(); \
if (!list.exceptions.empty()) throw list; \
}
#define CHILA_META_NODE__DEF_CHECK \
void check(chila::lib::node::CheckData *data = nullptr) const override;
#include "nspDef.hpp"
MY_NSP_START
{
template <typename CheckFun>
void checkAndAdd(chila::lib::node::CheckExceptionList &list, const CheckFun &checkFun) try
{
checkFun();
}
catch (ExceptionWrapper &ex)
{
list.add(ex.ex);
}
catch (CheckExceptionList &ex)
{
list.add(ex);
}
catch (Exception &ex)
{
list.add(ex);
}
chila::lib::misc::Path getNodePath(const Node &node); // to avoid cyclical dependency
template <typename Fun>
inline auto catchThrow(const Node &node, const Fun &fun) -> decltype(fun()) try
{
return fun();
}
catch (const boost::exception &ex)
{
ex << chila::lib::misc::ExceptionInfo::Path(getNodePath(node));
throw;
}
template <typename ToType, typename Node>
inline const ToType &castNode(const Node &node) try
{
return catchThrow(node, [&]() -> const ToType& { return chila::lib::misc::dynamicCast<ToType>(node); });
}
catch (const boost::exception &ex)
{
InvalidNode exx;
insert_error_info(chila::lib::misc::ExceptionInfo::TypeFrom)
insert_error_info(chila::lib::misc::ExceptionInfo::TypeTo)
insert_error_info(chila::lib::misc::ExceptionInfo::ActualType)
insert_error_info(chila::lib::misc::ExceptionInfo::Path)
BOOST_THROW_EXCEPTION(exx);
}
template <typename ToType, typename Node>
inline ToType &castNode(Node &node) try
{
return catchThrow(node, [&]() -> ToType& { return chila::lib::misc::dynamicCast<ToType>(node); });
}
catch (const boost::exception &ex)
{
InvalidNode exx;
insert_error_info(chila::lib::misc::ExceptionInfo::TypeFrom)
insert_error_info(chila::lib::misc::ExceptionInfo::TypeTo)
insert_error_info(chila::lib::misc::ExceptionInfo::ActualType)
insert_error_info(chila::lib::misc::ExceptionInfo::Path)
BOOST_THROW_EXCEPTION(exx);
}
NodeWithChildren &mainParent(NodeWithChildren &node);
PathVec getReferences(
NodeWithChildren &node,
const chila::lib::misc::Path &path);
void replaceReferences(NodeWithChildren &node, const PathVec &paths, const Node &newRefNode);
}
MY_NSP_END
#include "nspUndef.hpp"
#endif
| [
"[email protected]"
] | [
[
[
1,
114
]
]
] |
f387d41d0e3251ca4e290372f77e819aa8f41c08 | 8c8ea797b0821400c3176add36dd59f866b8ac3d | /AOJ/aoj0578.cpp | 9b35642e4fd0541224a11ccbbf275376f137bc2c | [] | no_license | fushime2/competitive | d3d6d8e095842a97d4cad9ca1246ee120d21789f | b2a0f5957d8ae758330f5450306b629006651ad5 | refs/heads/master | 2021-01-21T16:00:57.337828 | 2017-05-20T06:45:46 | 2017-05-20T06:45:46 | 78,257,409 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 682 | cpp | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
using namespace std;
int N;
bool isName(string shop, string board) {
int m = board.length();
for(int step=1; step<=m; step++) {
for(int i=0; i<m; i++) {
string s = "";
for(int j=i; j<m; j+=step) {
s += board[j];
}
if(s.find(shop) != string::npos) return true;
}
}
return false;
}
int main(void) {
cin >> N;
string shop, board;
cin >> shop;
int ans = 0;
for(int i=0; i<N; i++) {
cin >> board;
if(isName(shop, board)) ans++;
}
cout << ans << endl;
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
34
]
]
] |
6121382505592535a09b239e90ed50ff680fc2e6 | 91fcb836ee5af301a2125624ddb96cf49b19494d | /queue/restoreQueue.cpp | 2e49fc23784e34f26b2deade801fe414d1b21cb1 | [] | no_license | hellozxs/C | fe11911222595ffcdc425218407711bbe59a3b10 | 1f3815966a8d5668f149ff9957672819a2d2b57d | refs/heads/master | 2020-04-06T07:03:14.596747 | 2016-09-18T10:25:27 | 2016-09-18T10:25:27 | 65,121,708 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,272 | cpp | //对一个队列执行以下操作后,发现输出为 1,2,3,4,……,n
// 操作:(如果队列不为空)
// 1:取队头元素,放入队尾,将队头pop
// 2;输出队头,将队头pop
// 输入n,求原始队列?
//
//输入:z -> 表示将要输入的数据的个数
//输入z个n的具体值
#include <iostream>
#include <vector>
using namespace std;
typedef struct MyData
{
int _data;
bool _flag;
}MyData;
int main()
{
int z;
cin >> z;
vector<int> arr(z);
for (int i = 0; i < z; i++)
{
cin >> arr[i];
}
int i = 0;
for (i = 0; i< z; i++)
{
if (arr[i] == 1)
cout << 1 << endl;
else
{
vector<MyData> a(arr[i]);
int j = 0;
int count = arr[i];
int tmp = 1;
for (; count--; j ++)
{
int flag = 1;
while (flag)
{
if (j == arr[i])
j = 0;
if (a[j]._flag == false)
flag--;
j++;
}
if (j == arr[i])
j = 0;
while (a[j]._flag == true)
{
j++;
if (j == arr[i])
j = 0;
}
a[j]._data =tmp++;
a[j]._flag = true;
}
int k = 0;
for (; k < arr[i]; k++)
cout << a[k]._data << " ";
cout << endl;
}
}
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
81
]
]
] |
19203a417004197a3b51e22fe5a3dc21d6bcd8c4 | 57f87cd5fb9448bc6cdbf10769365393efae3a00 | /firmware_v5/telelogger/teleclient.h | a6433b87bd84452fb52cfd90b903677e97fb909f | [] | no_license | NatroNx/Freematics | 6a366805aef406d6f4deae050414f9611bbe710e | 011ae3212f57fdee7648eb34171e141c55a413ed | refs/heads/master | 2020-03-25T02:15:51.919396 | 2018-07-31T13:14:23 | 2018-07-31T13:14:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,569 | h | class TeleClient
{
public:
virtual void reset()
{
txCount = 0;
txBytes = 0;
rxBytes = 0;
}
virtual bool notify(byte event, const char* serverKey, const char* payload = 0) { return true; }
virtual bool connect() { return true; }
virtual bool transmit(const char* packetBuffer, unsigned int packetSize) { return true; }
virtual void inbound() {}
virtual bool begin() { return true; }
virtual void end() {}
uint32_t txCount = 0;
uint32_t txBytes = 0;
uint32_t rxBytes = 0;
uint32_t lastSyncTime = 0;
uint32_t lastSentTime = 0;
uint16_t feedid = 0;
};
class TeleClientUDP : public TeleClient
{
public:
bool notify(byte event, const char* serverKey, const char* payload = 0);
bool connect();
bool transmit(const char* packetBuffer, unsigned int packetSize);
void inbound();
bool verifyChecksum(char* data);
#if NET_DEVICE == NET_WIFI
UDPClientWIFI net;
#elif NET_DEVICE == NET_SIM800
UDPClientSIM800 net;
#elif NET_DEVICE == NET_SIM5360
UDPClientSIM5360 net;
#elif NET_DEVICE == NET_SIM7600
UDPClientSIM7600 net;
#else
NullClient net;
#endif
};
class TeleClientHTTP : public TeleClient
{
public:
bool connect();
bool transmit(const char* packetBuffer, unsigned int packetSize);
#if NET_DEVICE == NET_WIFI
HTTPClientWIFI net;
#elif NET_DEVICE == NET_SIM800
HTTPClientSIM800 net;
#elif NET_DEVICE == NET_SIM5360
HTTPClientSIM5360 net;
#elif NET_DEVICE == NET_SIM7600
HTTPClientSIM7600 net;
#else
NullClient net;
#endif
}; | [
"[email protected]"
] | [
[
[
1,
61
]
]
] |
7ade5627a226f91a37d1e00ba158ba1f1eace614 | 6a56f4e8bfa2da98cfc51a883b7cae01736c3046 | /ovaldi-code-r1804-trunk/src/probes/unix/PasswordProbe.h | 03062e89f9d72a9942bd7a1aac071a565a9a4ae6 | [] | no_license | tmcclain-taptech/Ovaldi-Win10 | 6b11e495c8d37fd73aae6c0281287cadbc491e59 | 7214d742c66f3df808d70e880ba9dad69cea403d | refs/heads/master | 2021-07-07T09:36:30.776260 | 2019-03-28T19:11:29 | 2019-03-28T19:11:29 | 164,451,763 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,857 | h | //
//
//****************************************************************************************//
// Copyright (c) 2002-2014, The MITRE Corporation
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this list
// of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice, this
// list of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
// * Neither the name of The MITRE Corporation nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
// OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
// TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//****************************************************************************************//
#ifndef PASSWORDPROBE_H
#define PASSWORDPROBE_H
#include "AbsProbe.h"
#include "Item.h"
#include "Object.h"
#include <pwd.h>
#include <string>
/**
This class is responsible for collecting information about unix password_objects.
*/
class PasswordProbe : public AbsProbe {
public:
virtual ~PasswordProbe();
/** Get all the files on the system that match the pattern and collect their attributes. */
virtual ItemVector* CollectItems(Object* object);
/** Return a new Item created for storing file information */
virtual Item* CreateItem();
/** Ensure that the PasswordProbe is a singleton. */
static AbsProbe* Instance();
private:
PasswordProbe();
/** Creates an item from a passwd struct */
Item *CreateItemFromPasswd(struct passwd const *pwInfo);
/** Finds a single item by name. */
Item *GetSingleItem(const std::string& username);
/** Finds multiple items according to the given object entity. */
ItemVector *GetMultipleItems(Object *passwordObject);
/** Singleton instance */
static PasswordProbe* instance;
};
#endif
| [
"[email protected]"
] | [
[
[
1,
75
]
]
] |
8b494503d9bf74ff5d28e840affc467e8a440a51 | 34a3165ded55c6ac5ffe2ff17c9996c66e0e80b5 | /cpp/ETProtect.cpp | 989ebb94e3100accc0e0e0fd02bff4f34144df29 | [] | no_license | monkeyde17/et-protect-package | d806a3196c28c4176374bc21e7ec5769faa72347 | 77e04d1834d0723c2de7f424a1cbc1efd2321991 | refs/heads/master | 2016-09-06T05:53:58.824045 | 2014-12-07T02:29:37 | 2014-12-07T02:29:37 | 27,655,865 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,888 | cpp | //
// ETProtect.cpp
// testcpp
//
// Created by etond on 14/12/3.
//
//
#include "ETProtect.h"
bool ETProtect::isOriginPackage()
{
unsigned int uHashValue = calculateValueFromFile();
unsigned int uReadValue = readValueFromFile();
#if (ETPROTECTDEBUG)
CCLOG("[log] -- hash %u", uHashValue);
CCLOG("[log] -- read %u", uReadValue);
#endif
if (uReadValue == 0 || uHashValue == 0)
{
return false;
}
return uReadValue == uHashValue;
}
unsigned int ETProtect::readValueFromFile(std::string filename /* default = config.et */)
{
unsigned int uValue = 0;
Data data = FileUtils::getInstance()->getDataFromFile(filename);
if (data.getSize() > 0)
{
uValue = ((ETProtectData *)data.getBytes())->getHashValue();
}
return uValue;
}
unsigned int ETProtect::calculateValueFromFile(unsigned int seed /* default = 0x12345678 */)
{
std::string path = "";
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
JniMethodInfo minfo;
bool isHave = JniHelper::getStaticMethodInfo(minfo,
"org/cocos2dx/cpp/AppActivity",
"getPath",
"()Ljava/lang/String;");
if (isHave)
{
jobject jobj = minfo.env->CallStaticObjectMethod(minfo.classID, minfo.methodID);
/* get the return value */
path = JniHelper::jstring2string((jstring)jobj).c_str();
CCLOG("JNI SUCCESS!");
}
#endif
unsigned int value = 0;
if (path.length() > 0)
{
ssize_t len = 0;
unsigned char *buf = FileUtils::getInstance()->getFileDataFromZip(path, "classes.dex", &len);
if (buf)
{
value = XXH32(buf, len, seed);
}
delete[] buf;
}
return value;
}
| [
"[email protected]"
] | [
[
[
1,
77
]
]
] |
b13420aa4004b14e74a53305e3368b5f4ee9dc92 | 72d1b579366934a24af7aff13ebf9b8cdaf58d8c | /ReadImages.cpp | a8f247f3d5b7fd89ce0c49662b42f6ef479207a1 | [] | no_license | hgpvision/Keypoint-Matcher | 48496a59dbaffefe6e89e8e14efabdb9883848bb | bf265aba62b325fab300aba2bad357ff7321ba4a | refs/heads/master | 2021-01-15T15:05:50.913505 | 2017-08-08T14:45:53 | 2017-08-08T14:45:53 | 99,702,359 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 1,454 | cpp | /*
* 文件名称:ReadImages.cpp
* 摘 要:读取图片类,图片序列放入到一个文件夹中,如"C:\\imgFile",按一定格式命名,比如"0001.jpg","00010.jpg","1.jpg"
* 使用实例:
* 包含头文件: #include "ReadImages.h"
* 先声明要给读入图片类:ReadImages imageReader("C:\\imgFile", "", ".jpg");
* 读入图片: Mat prev = imageReader.loadImage(1,0); //将读入"1.jpg"图片,灰度格式
* 2016.05.23
*/
#include "ReadImages.h"
#pragma once
ReadImages::ReadImages(std::string basepath, const std::string imagename, const std::string suffix)
{
//将路径中的文件夹分隔符统一为'/'(可以不需要这个for循环,会自动统一,该语句使用的命令参考C++ Primer)
for (auto &c : basepath)
{
if (c == '\\')
{
c = '/';
}
}
_imgSource._basepath = basepath + "/"; //这里采用'/',而不是'\\'
_imgSource._imagename = imagename; //图片名(不含编号)
_imgSource._suffix = suffix; //图像扩展名
}
//读入单张图片
//输入:imgId,一般要读入序列图片,图片都有个编号
cv::Mat ReadImages::loadImage(int imgId, int imgType)
{
//将图片编号转好字符串
std::stringstream ss;
std::string imgNum;
ss << imgId;
ss >> imgNum;
//得到图片的完整绝对路径
std::string path = _imgSource._basepath + _imgSource._imagename + imgNum + _imgSource._suffix;
cv::Mat img = cv::imread(path,imgType);
return img;
} | [
"[email protected]"
] | [
[
[
1,
47
]
]
] |
82be31fc3524835f627befe774786637aae24645 | 469370ad9a81ec746270f54a6433853e517bafde | /input.h | fa59213d1dc084e2a98556a154757033ecde6c1c | [] | no_license | masaedw/landscaper | 42431ee6ea952a2476583b838b7ae31e687e6421 | 7b84f39d16a37de12d20be15e17f199737e1d6a8 | refs/heads/master | 2016-09-06T00:23:36.120087 | 2010-02-01T14:52:41 | 2010-02-01T14:52:41 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 3,666 | h | #ifndef _INPUT_H_
#define _INPUT_H_
#include <map>
#include "collision.h"
namespace space{
//キーボード情報
//キーボードの値は整数に変換される。どういう変換かは使う人が考えること。
class Keyboard
{
public:
typedef std::map<unsigned short,unsigned short> KeyMap;
protected:
KeyMap keys;
public:
void clear(){keys.clear();}
Keyboard(){clear();}
~Keyboard(){}
//セット
void pushkey(unsigned short _k) { keys[_k] = _k; }
//アンセット
void pullkey(unsigned short _k) {
KeyMap::iterator it = keys.find(_k);
if( it != keys.end() ) keys.erase(it);
}
//情報をもらう
bool ispush(unsigned short _k) const{
if( keys.find(_k) == keys.end() ) return false;
return true;
}
//キーを全部丸ごとプレゼントする
const KeyMap& getkeys() const{ return keys;}
};
//ジョイスティック情報
//ボタン数は13と仮定。
class Joystick
{
bool button[13];
int x,y,z;
public:
void clear(){
x=0;y=0;z=0;
for(int i=0;i<16;i++) button[i]=false;
}
Joystick(){clear();}
~Joystick(){}
//セット(unsetの必要なし)
void setx(int _k) { x=_k; }
void sety(int _k) { y=_k; }
void setz(int _k) { z=_k; }
//ボタン系セット
void pushbutton(unsigned int _b){ if(_b>=13)return; button[_b]=true; }
//ボタン系アンセット
void pullbutton(unsigned int _b){ if(_b>=13)return; button[_b]=false; }
//情報をもらう
int getx() const { return x; }
int gety() const { return y; }
int getz() const { return z; }
bool ispush(unsigned int _b) const { if(_b>=13)return false; return button[_b]; }
};
//マウス
//4ボタン以上とか知らん。
class Mouse
{
public:
struct Button
{
private:
bool ispush;
Matrix21<int> pushpos;
Matrix21<int> pullpos;
public:
void clear(){
ispush=false;
pushpos = Matrix21<int>(0,0);
pullpos = Matrix21<int>(0,0);
}
Button(){ clear(); }
void push(const Matrix21<int>& _pos){ispush=true; pushpos=_pos;}
void pull(const Matrix21<int>& _pos){ispush=false;pullpos=_pos;}
const Matrix21<int>& getPushpos() const {return pushpos;}
const Matrix21<int>& getPullpos() const {return pullpos;}
bool isPush() const {return ispush;}
std::string output() const{
std::stringstream ss("");
ss << "::" << ispush << ":ps(" << pushpos.x << "," << pushpos.y << "):pl(" << pullpos.x << "," << pullpos.y << ")";
return ss.str();
}
};
protected:
Button left,right,middle;
Matrix21<int> nowpos;
public:
void clear(){
left.clear();
right.clear();
middle.clear();
nowpos = Matrix21<int>(0,0);
}
Mouse(){clear();}
//セット(アンセット必要なし)
void setpos(const Matrix21<int> &_pos){ nowpos=_pos; }
//ゲット
const Matrix21<int>& getpos() const { return nowpos; }
//返すだけ
const Button &getleft() const {return left;}
const Button &getmiddle() const {return middle;}
const Button &getright()const {return right;}
Button &setleft() {return left;}
Button &setmiddle() {return middle;}
Button &setright() { return right;}
std::string output() const{
std::stringstream ss("");
ss << "*l" << left.output() << "::m" << middle.output() << "::r" << right.output() << "::p(" << nowpos.x << "," << nowpos.y << ")";
return ss.str();
}
};
struct Input
{
Keyboard keyboard;
Mouse mouse;
Joystick joystick;
void clear(){
keyboard.clear();
mouse.clear();
joystick.clear();
}
std::string output() const{
std::stringstream ss("");
ss << "**ms" << mouse.output();
return ss.str();
}
};
}
#endif
| [
"[email protected]"
] | [
[
[
1,
161
]
]
] |
bba7327fa47b292b7a2a12379dbea888640a0e70 | 58790459d953a3e4b6722ed3ee939f82d9de8c3e | /my/PDF插件/sdkDC_v1_win/Adobe/Acrobat DC SDK/Version 1/PluginSupport/PIBrokerSDK/simple-ipc-lib/src/pipe_win.h | 4625bef0dc76752fdcc7b3a4966d087839cbd12f | [] | no_license | tisn05/VS | bb84deb993eb18d43d8edaf81afb753afa3d3188 | da56d392a518ba21edcb1a367b4b4378d65506f0 | refs/heads/master | 2020-09-25T05:49:31.713773 | 2016-08-22T01:22:16 | 2016-08-22T01:22:16 | 66,229,337 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,659 | h | // Copyright (c) 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef SIMPLE_IPC_PIPE_WIN_H_
#define SIMPLE_IPC_PIPE_WIN_H_
#include "os_includes.h"
#include "ipc_constants.h"
class PipePair {
public:
PipePair(bool inherit_fd2 = false);
HANDLE fd1() const { return srv_; }
HANDLE fd2() const { return cln_; }
static HANDLE OpenPipeServer(const wchar_t* name, bool low_integrity = false);
static HANDLE OpenPipeClient(const wchar_t* name, bool inherit, bool impersonate);
private:
HANDLE srv_;
HANDLE cln_;
};
class PipeWin {
public:
PipeWin();
~PipeWin();
bool OpenClient(HANDLE pipe);
bool OpenServer(HANDLE pipe, bool connect = false);
bool Write(const void* buf, size_t sz);
bool Read(void* buf, size_t* sz);
bool IsConnected() const { return INVALID_HANDLE_VALUE != pipe_; }
private:
HANDLE pipe_;
};
class PipeTransport : public PipeWin {
public:
static const size_t kBufferSz = 4096;
size_t Send(const void* buf, size_t sz) {
return Write(buf, sz) ? ipc::RcOK : ipc::RcErrTransportWrite;
}
char* Receive(size_t* size);
private:
IPCCharVector buf_;
};
#endif // SIMPLE_IPC_PIPE_WIN_H_
| [
"[email protected]"
] | [
[
[
1,
67
]
]
] |
6290623071614e1a5caf46e39ddc6e959b56f6cb | 256767f888195384e8a91bff0864d0afc3f7e4e9 | /AIS_TrackingAndDetection/tests/moc_euclideanDistance.cpp | 8e8d5da02912f8bd3b87c8b1bc3d57a65875d708 | [] | no_license | HelenHarman/AIS_Object_Tracking | a71b9c2df78c02180b7bb1ac2561a03a570ef935 | 3ec7128a739387299ac3e4a648e8c8f30274af97 | refs/heads/master | 2021-01-15T08:28:06.415775 | 2016-01-23T13:01:20 | 2016-01-23T13:01:20 | 43,375,968 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 35 | cpp | #include "moc_euclideanDistance.h"
| [
"[email protected]"
] | [
[
[
1,
1
]
]
] |
aad85aa770183929d8ccd9df0aacf59df35f147f | 465a87bdead9aee133a7b36b0c2e826ece517cbb | /ARStudy(Image processing)/ARStudy/main.cpp | 5ebb0f7ee747397046be8ca1b609d9d04b460e5c | [] | no_license | kshy9598/ARStudy | a5b55f3808d1e64cc96ee3e9266e4f4c23c3d611 | c55ce51cb595f677eb07549203d0032430a90aef | refs/heads/master | 2020-06-29T05:20:21.879048 | 2016-12-08T16:22:03 | 2016-12-08T16:22:03 | 74,446,922 | 0 | 1 | null | null | null | null | UHC | C++ | false | false | 4,927 | cpp | #include <iostream>
#include <fstream>
#include <cmath>
#include "opencv2\highgui\highgui.hpp"
#include "opencv2\opencv.hpp"
#pragma comment(lib, "opencv_world300d.lib")
const double PI = 3.14159265;
using namespace std;
using namespace cv;
bool bLBDown = false; // 마우스 버튼 눌렀는지 체크
bool checkDrag; // 드래그가 이루어졌는지 체크
CvRect box; // 드래그로 그린 박스
// 사각형 그리기
void draw_box(IplImage* img, CvRect rect)
{
cvRectangle(img, cvPoint(rect.x, rect.y),
cvPoint(rect.x + rect.width, rect.y + rect.height),
cvScalar(0xff, 0x00, 0x00));
}
// 마우스 드래그
void on_mouse(int event, int x, int y, int flag, void* params)
{
IplImage* image = (IplImage*)params;
if (event == CV_EVENT_LBUTTONDOWN){ // 왼쪽 버튼 눌렀을 시, 박스 초기화
bLBDown = true;
box = cvRect(x, y, 0, 0);
}
else if (event == CV_EVENT_LBUTTONUP){ // 왼쪽 버튼 눌렀다가 뗐을 때, 박스의 넓이, 높이를 설정한다.
bLBDown = false;
checkDrag = true;
if (box.width < 0)
{
box.x += box.width;
box.width *= -1;
}
if (box.height < 0)
{
box.y += box.height;
box.height *= -1;
}
draw_box(image, box);
}
else if (event == CV_EVENT_MOUSEMOVE && bLBDown){ // 드래그 중에는 박스의 넓이, 높이를 갱신한다.
box.width = x - box.x;
box.height = y - box.y;
}
}
// 이미지 복사
Mat copyMat(Mat source)
{
// source의 Mat을 result로 복사하는 작업
// opencv에 이미 구현이 되어있는 작업이다.
// source.copyTo(result);
Mat result = Mat::zeros(source.size(), source.type());
for (int i = 0; i < source.cols; i++){
for (int j = 0; j < source.rows; j++){
result.at<Vec3b>(j, i) = source.at<Vec3b>(j, i);
}
}
return result;
}
// 박스내 이미지 복사
Mat copyBoxMat(Mat source)
{
return source(box);
}
// y축반전
Mat yReflecting(Mat source)
{
Mat result = copyMat(source);
for (int i = 0; i < box.width; i++){
for (int j = 0; j < box.height; j++){
result.at<Vec3b>((box.y + j), (box.x + i)) = source.at<Vec3b>(box.y + j, (box.width + box.x - 1) - i);
}
}
return result;
}
// x축반전
Mat xReflecting(Mat source)
{
Mat result = copyMat(source);
for (int i = 0; i < box.width; i++){
for (int j = 0; j < box.height; j++){
result.at<Vec3b>((box.y + j), (box.x + i)) = source.at<Vec3b>((box.height + box.y - 1) - j, (box.x + i));
}
}
return result;
}
// 회전
Mat rotating(Mat source, double degree)
{
Mat result = copyMat(source);
int x0 = box.x + (box.width / 2);
int y0 = box.y + (box.height / 2);
double cosd = cos(degree*PI / 180);
double sind = sin(degree*PI / 180);
// 원본에 덮어씌우는 부분으로 인해 왼쪽 90도, 오른쪽 90도만 가능
for (int i = 0; i < box.width; i++){
for (int j = 0; j < box.height; j++){
int x1 = (box.x + i);
int y1 = (box.y + j);
int x = ((cosd * (x1 - x0)) - (sind * (y1 - y0)) + x0);
int y = ((sind * (x1 - x0)) - (cosd * (y1 - y0)) + y0);
result.at<Vec3b>(y, x) = source.at<Vec3b>((box.y + j), (box.x + i));
}
}
return result;
}
// 확대
Mat scaling(Mat source, Mat boxMat, double scale)
{
Mat result = copyMat(source);
Mat scaleBoxMat;
// 사각형 안의 Mat의 크기를 scale배 늘린다.
int boxWidth = (int)(boxMat.size().width * scale);
int boxHeight = (int)(boxMat.size().height * scale);
cv::resize(boxMat, scaleBoxMat, Size(boxWidth, boxHeight));
// 붙여넣을 때 시작 위치 정보를 갱신한다.
int x = box.x - (box.width / 2);
int y = box.y - (box.height / 2);
for (int i = 0; i < boxWidth; i++){
for (int j = 0; j < boxHeight; j++){
result.at<Vec3b>((y + j), (x + i)) = scaleBoxMat.at<Vec3b>(j, i);
}
}
return result;
}
int main()
{
IplImage copy;
IplImage * resultImage;
Mat resultMat, xReflectMat, yReflectMat, leftRotateMat, scaleMat, boxMat;
// 이미지 불러오기
Mat gMatImage = imread("./picture/pic.jpg", 1);
// Mat 이미지를 IplImage 로 복사한다.
copy = gMatImage;
resultImage = ©
checkDrag = false;
namedWindow("image");
setMouseCallback("image", on_mouse, resultImage);
cvShowImage("image", resultImage);
//드래그 대기
while (!checkDrag){
waitKey(100);
}
cvShowImage("image", resultImage);
//사각형 추가된 사진 저장
resultMat = cvarrToMat(resultImage);
boxMat = copyBoxMat(resultMat);
cout << box.x << ' ' << box.y << ' ' << box.width << ' ' << box.height << endl;
yReflectMat = yReflecting(resultMat); // y축 반전
xReflectMat = xReflecting(resultMat); // x축 반전
scaleMat = scaling(resultMat, boxMat, 1.5); // 크기 변경
leftRotateMat = rotating(resultMat, -90.0); // 90도 회전
waitKey(2000);
imshow("y반전 이미지", yReflectMat);
imshow("x반전 이미지", xReflectMat);
imshow("왼쪽 90도 회전 이미지", leftRotateMat);
imshow("1.5배 확대 이미지", scaleMat);
waitKey(0);
return 0;
} | [
"[email protected]"
] | [
[
[
1,
200
]
]
] |
9902eb5452ca24078c32fd40c10f077849f5b441 | 948d5663fe68495eb4090350e3bcfae33c3d314d | /include/forecast_io/factories/SynchronicDataPointDetailsSetter.hpp | d9eb866ded44e428527ccc44cf017d1059a870b9 | [
"Apache-2.0"
] | permissive | Crystalix007/DarkSky-CPP | b102f000f85d4413a559d79fa04b421a301bc14a | 10497ff292efdc460a67bc5dc44811b3a1459beb | refs/heads/master | 2020-06-17T04:49:55.946260 | 2019-07-08T21:17:18 | 2019-07-08T21:21:27 | 195,802,094 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,951 | hpp | #ifndef SYNCHRONICDATAPOINTDETAILSSETTER_HPP
#define SYNCHRONICDATAPOINTDETAILSSETTER_HPP
#include "../../common/InstanceReferenceHolder.hpp" // Base class: common::InstanceReferenceHolder
#include "../listeners/SynchronicDataPointDetailsListener.hpp" // Base class: forecast_io::listeners::SynchronicDataPointDetailsListener
#include "../SynchronicDataPoint.hpp"
#include "SingleDataPointDetailsSetter.hpp"
namespace forecast_io
{
namespace factories
{
class SynchronicDataPointDetailsSetter : public listeners::SynchronicDataPointDetailsListener,
public common::InstanceReferenceHolder<SynchronicDataPoint>
{
public:
SynchronicDataPointDetailsSetter(SynchronicDataPoint& instance) noexcept;
virtual void notifyApparentTemperature(double temperature);
virtual void notifyCloudCover(double cloudCover);
virtual void notifyDewPoint(double dewPoint);
virtual void notifyHumidity(double humidity);
virtual void notifyIcon(const std::string& name);
virtual void notifyNearestStormBearing(double bearing);
virtual void notifyNearestStormDistance(double distance);
virtual void notifyOzone(double ozone);
virtual void notifyPrecipitationIntensity(double intensity);
virtual void notifyPrecipitationProbability(double probability);
virtual void notifyPrecipitationType(const std::string& type);
virtual void notifyPressure(double pressure);
virtual void notifySummary(const std::string& summary);
virtual void notifyTemperature(double temperature);
virtual void notifyTime(time_t time);
virtual void notifyUVIndex(double uvIndex);
virtual void notifyVisibility(double visibility);
virtual void notifyWindBearing(double bearing);
virtual void notifyWindGust(double gust);
virtual void notifyWindSpeed(double speed);
private:
SingleDataPointDetailsSetter singleDataPointDetailsSetter;
};
} // namespace factories
} // namespace forecast_io
#endif // SYNCHRONICDATAPOINTDETAILSSETTER_HPP
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
4
],
[
6,
7
],
[
9,
15
],
[
18,
36
],
[
38,
39
],
[
41,
46
],
[
48,
48
],
[
50,
51
]
],
[
[
5,
5
],
[
8,
8
],
[
16,
17
],
[
37,
37
],
[
40,
40
],
[
47,
47
],
[
49,
49
]
]
] |
a702a5d40a3a672624e691115d63b4a004c979d0 | 7aa189c718f8a63c256685a435d027ace3833f6b | /include/ogonek/error.h++ | ca7ff1f2bc1d6ac11fcbdaacee61fbdef1c7430d | [
"CC0-1.0"
] | permissive | rmartinho/ogonek | d5523145108de1255298a17c1c25065beb19b82c | 0042f30c6c674effd21d379c53658c88054c58b9 | refs/heads/devel | 2020-05-21T15:17:39.490890 | 2019-09-29T10:58:31 | 2019-09-29T10:58:31 | 8,255,019 | 16 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 4,549 | // Ogonek
//
// Written in 2017 by Martinho Fernandes <[email protected]>
//
// To the extent possible under law, the author(s) have dedicated all copyright and related
// and neighboring rights to this software to the public domain worldwide. This software is
// distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
/**
* Error handling
* ==============
*/
#ifndef OGONEK_ERROR_HPP
#define OGONEK_ERROR_HPP
#include <ogonek/error_fwd.h++>
#include <ogonek/concepts.h++>
#include <ogonek/types.h++>
#include <ogonek/encoding.h++>
#include <range/v3/range_concepts.hpp>
#include <range/v3/range_traits.hpp>
#include <stdexcept>
namespace ogonek {
/**
* .. class:: unicode_error
*
* The base class for all Unicode-related errors.
*/
struct unicode_error
: virtual std::exception {
char const* what() const noexcept override {
return u8"Unicode error";
}
};
/**
* .. class:: template <EncodingForm Encoding>\
* encode_error : virtual unicode_error
*
* :thrown: when an error occurs during an encoding operation.
*/
template <typename Encoding>
struct encode_error
: virtual unicode_error {
CONCEPT_ASSERT(EncodingForm<Encoding>());
char const* what() const noexcept override {
return u8"encoding failed ";
}
};
/**
* .. class:: template <EncodingForm Encoding>\
* decode_error : virtual unicode_error
*
* :thrown: when an error occurs during a decoding operation.
*/
template <typename Encoding>
struct decode_error
: virtual unicode_error {
CONCEPT_ASSERT(EncodingForm<Encoding>());
char const* what() const noexcept override {
return u8"decoding failed";
}
};
/**
* .. var:: auto assume_valid
*
* A tag used to request that encoding/decoding functions assume the
* input has been validated before.
*
* .. warning::
*
* Using this tag with input that isn't actually valid yields
* undefined behavior.
*/
struct assume_valid_t {} constexpr assume_valid {};
/**
* .. var:: auto discard_errors
*
* An error handler for encoding/decoding functions that simply
* discards the portions of the input that have errors.
*/
struct discard_errors_t {
template <typename E>
optional<code_point> operator()(E) const {
return {};
}
} constexpr discard_errors {};
CONCEPT_ASSERT(EncodeErrorHandler<discard_errors_t, archetypes::EncodingForm>());
CONCEPT_ASSERT(DecodeErrorHandler<discard_errors_t, archetypes::EncodingForm>());
/**
* .. var:: auto replace_errors
*
* An error handler for encoding/decoding functions that replaces
* portions of the input that have errors with a replacement character.
* When decoding, this is |u-fffd|, but when encoding and the target
* doesn't support it, some encoding-specific character is used
* instead.
*/
struct replace_errors_t {
template <typename Encoding,
CONCEPT_REQUIRES_(EncodingForm<Encoding>())>
optional<code_point> operator()(encode_error<Encoding>) const {
return replacement_character_v<Encoding>;
}
template <typename Encoding,
CONCEPT_REQUIRES_(EncodingForm<Encoding>())>
optional<code_point> operator()(decode_error<Encoding>) const {
return { U'\uFFFD' };
}
} constexpr replace_errors {};
CONCEPT_ASSERT(EncodeErrorHandler<replace_errors_t, archetypes::EncodingForm>());
CONCEPT_ASSERT(DecodeErrorHandler<replace_errors_t, archetypes::EncodingForm>());
/**
* .. var:: auto throw_error
*
* An error handler for encoding/decoding functions that throws when an
* error is found in the input.
*/
struct throw_error_t {
template <typename E>
optional<code_point> operator()(E e) const {
throw e;
}
} constexpr throw_error {};
CONCEPT_ASSERT(EncodeErrorHandler<throw_error_t, archetypes::EncodingForm>());
CONCEPT_ASSERT(DecodeErrorHandler<throw_error_t, archetypes::EncodingForm>());
} // namespace ogonek
#endif // OGONEK_ERROR_HPP
| [
"[email protected]"
] | [
[
[
1,
148
]
]
] |
|
0293e83add680ed3f8e92ecea17c897a91d1270b | 1ca3477d99bddb6611f2feb67c8ce0c4569d8a4b | /Memendo.cc | 7ac722a8f7b952968a9ec15d38a1c9bbc3afc637 | [] | no_license | TaoJun724/DesignPattern | 0da37a3a34fba54ba21cb809875b20d9eeba3443 | b0c62668cfad5b48b85b413e78ee9334812a74b2 | refs/heads/master | 2020-06-30T08:57:32.156222 | 2019-08-07T07:42:09 | 2019-08-07T07:42:09 | 200,785,533 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,461 | cc | #include <stdio.h>
#include<string>
class Memento {
public:
Memento(int n, std::string s) {
_s = s;
_money = n;
}
void setMoney(int n) {
_money = n;
}
int getMoney() {
return _money;
}
void setState(std::string s) {
_s = s;
}
std::string getState() {
return _s;
}
private:
int _money;
std::string _s;
};
class Worker {
public:
Worker(std::string name, int money, std::string s) {
_name = name;
_money = money;
_s = s;
}
void show() {
printf("%s现在有钱%d元,生活状态%s!\n", _name.c_str(), _money, _s.c_str());
}
void setState(int money, std::string s) {
_money = money;
_s = s;
}
Memento* createMemnto() {
return new Memento(_money,_s);
}
void restoreMemnto(Memento* m) {
_money = m->getMoney();
_s = m->getState();
}
private:
std::string _name;
int _money;
std::string _s;
};
class WorkerStorage {
public:
void setMemento(Memento* m) {
_memento = m;
}
Memento* getMement() {
return _memento;
}
private:
Memento* _memento;
};
int main() {
Worker* zhangsan = new Worker("张三", 10000, "富裕");
zhangsan->show();
//记住张三现在的状态
WorkerStorage* storage = new WorkerStorage;
storage->setMemento(zhangsan->createMemnto());
//张三赌博输了钱,只剩下10元
zhangsan->setState(10, "贫困");
zhangsan->show();
//经过努力张三又回到了之前的状态。
zhangsan->restoreMemnto(storage->getMement());
zhangsan->show();
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
93
]
]
] |
9b67f6e27a369c3b66f7fb8bf435dc44a8750a9f | 5dbdb28b66c4828bf83564f1cf63f82480d6395f | /HelloWorld_demo_game/Classes/DemoGame/GameClock.h | 0376404ad2fc38c0fa7670b28ad9433a96177a3c | [] | no_license | gengyu-mamba/CardGames | 87a2b8fca377a6bd3de0ba4c6fe09a9e85e22848 | d2b0133c02cc04b75a49ca164a086aaa5603715d | refs/heads/master | 2020-04-02T18:23:19.395504 | 2018-11-08T02:34:23 | 2018-11-08T02:34:23 | 154,698,113 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 487 | h | #ifndef GAME_CLOCK_H
#define GAME_CLOCK_H
#include "cocos2d.h"
USING_NS_CC;
class GameLayer;
class GameClock :public CCLayer
{
public:
GameClock(GameLayer *pGameLayer);
virtual ~GameClock();
void ShowClock(int iTime,int iTablePos);
void ResetClock();
private:
virtual void onEnter();
virtual void onExit();
void OnSecondTimer(float dt);
CCSprite *m_pSpriteBG;
CCLabelAtlas *m_pNumLable;
int m_iTime;
int m_iTablePos;
GameLayer *m_pGameLayer;
};
#endif
| [
"[email protected]"
] | [
[
[
1,
34
]
]
] |
4ff557683a174bc39aea59e06a19b563d55927d6 | cde943952b79d67f4972d180d20b97fc823db548 | /preprocesser/preprocesser/self2.hpp | 0892b2563bae695f02d2254829e81a6cb84c630e | [] | no_license | yourgracee/preprocesser | e66a0b0c9680442717652185e9ed2dc5172f7771 | 349453d4092ffe7927b0c1067d3cefc8bf2bdfff | refs/heads/master | 2020-04-09T10:52:16.135824 | 2018-12-04T02:46:03 | 2018-12-04T02:46:03 | 160,285,495 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,701 | hpp | #ifdef LIMIT_2
#include "tuple.hpp"
#define START_2 TUPLE(0, LIMIT_2)
#define FINISH_2 TUPLE(1, LIMIT_2)
#undef DEPTH
#define DEPTH 2
# if START_2 <= 0 && FINISH_2 >= 0
# define ITERATION_2 0
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 1 && FINISH_2 >= 1
# define ITERATION_2 1
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 2 && FINISH_2 >= 2
# define ITERATION_2 2
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 3 && FINISH_2 >= 3
# define ITERATION_2 3
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 4 && FINISH_2 >= 4
# define ITERATION_2 4
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 5 && FINISH_2 >= 5
# define ITERATION_2 5
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 6 && FINISH_2 >= 6
# define ITERATION_2 6
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 7 && FINISH_2 >= 7
# define ITERATION_2 7
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 8 && FINISH_2 >= 8
# define ITERATION_2 8
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 9 && FINISH_2 >= 9
# define ITERATION_2 9
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 10 && FINISH_2 >= 10
# define ITERATION_2 10
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 11 && FINISH_2 >= 11
# define ITERATION_2 11
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 12 && FINISH_2 >= 12
# define ITERATION_2 12
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 13 && FINISH_2 >= 13
# define ITERATION_2 13
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 14 && FINISH_2 >= 14
# define ITERATION_2 14
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 15 && FINISH_2 >= 15
# define ITERATION_2 15
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 16 && FINISH_2 >= 16
# define ITERATION_2 16
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 17 && FINISH_2 >= 17
# define ITERATION_2 17
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 18 && FINISH_2 >= 18
# define ITERATION_2 18
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 19 && FINISH_2 >= 19
# define ITERATION_2 19
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 20 && FINISH_2 >= 20
# define ITERATION_2 20
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 21 && FINISH_2 >= 21
# define ITERATION_2 21
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 22 && FINISH_2 >= 22
# define ITERATION_2 22
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 23 && FINISH_2 >= 23
# define ITERATION_2 23
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 24 && FINISH_2 >= 24
# define ITERATION_2 24
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 25 && FINISH_2 >= 25
# define ITERATION_2 25
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 26 && FINISH_2 >= 26
# define ITERATION_2 26
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 27 && FINISH_2 >= 27
# define ITERATION_2 27
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 28 && FINISH_2 >= 28
# define ITERATION_2 28
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 29 && FINISH_2 >= 29
# define ITERATION_2 29
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 30 && FINISH_2 >= 30
# define ITERATION_2 30
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 31 && FINISH_2 >= 31
# define ITERATION_2 31
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 32 && FINISH_2 >= 32
# define ITERATION_2 32
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 33 && FINISH_2 >= 33
# define ITERATION_2 33
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 34 && FINISH_2 >= 34
# define ITERATION_2 34
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 35 && FINISH_2 >= 35
# define ITERATION_2 35
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 36 && FINISH_2 >= 36
# define ITERATION_2 36
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 37 && FINISH_2 >= 37
# define ITERATION_2 37
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 38 && FINISH_2 >= 38
# define ITERATION_2 38
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 39 && FINISH_2 >= 39
# define ITERATION_2 39
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 40 && FINISH_2 >= 40
# define ITERATION_2 40
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 41 && FINISH_2 >= 41
# define ITERATION_2 41
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 42 && FINISH_2 >= 42
# define ITERATION_2 42
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 43 && FINISH_2 >= 43
# define ITERATION_2 43
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 44 && FINISH_2 >= 44
# define ITERATION_2 44
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 45 && FINISH_2 >= 45
# define ITERATION_2 45
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 46 && FINISH_2 >= 46
# define ITERATION_2 46
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 47 && FINISH_2 >= 47
# define ITERATION_2 47
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 48 && FINISH_2 >= 48
# define ITERATION_2 48
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 49 && FINISH_2 >= 49
# define ITERATION_2 49
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 50 && FINISH_2 >= 50
# define ITERATION_2 50
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 51 && FINISH_2 >= 51
# define ITERATION_2 51
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 52 && FINISH_2 >= 52
# define ITERATION_2 52
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 53 && FINISH_2 >= 53
# define ITERATION_2 53
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 54 && FINISH_2 >= 54
# define ITERATION_2 54
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 55 && FINISH_2 >= 55
# define ITERATION_2 55
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 56 && FINISH_2 >= 56
# define ITERATION_2 56
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 57 && FINISH_2 >= 57
# define ITERATION_2 57
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 58 && FINISH_2 >= 58
# define ITERATION_2 58
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 59 && FINISH_2 >= 59
# define ITERATION_2 59
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 60 && FINISH_2 >= 60
# define ITERATION_2 60
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 61 && FINISH_2 >= 61
# define ITERATION_2 61
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 62 && FINISH_2 >= 62
# define ITERATION_2 62
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 63 && FINISH_2 >= 63
# define ITERATION_2 63
# include FILENAME_2
# undef ITERATION_2
# endif
# if START_2 <= 64 && FINISH_2 >= 64
# define ITERATION_2 64
# include FILENAME_2
# undef ITERATION_2
# endif
#undef DEPTH
#define DEPTH 1
#endif | [
"[email protected]"
] | [
[
[
1,
336
]
]
] |
3c1b9a977eb477d5b194c9d62796fdbdb650af98 | 74b07eb2bc01383744514b70b385571fb90a1a04 | /test/test.cpp | c870d6500c7d2c64c80815743dbbe2e47990c430 | [] | no_license | yksym/x86_64_hook_without_ld_preload | 8ae067c195bf1eb0f23d67a1087ad3f8ebcfab4a | 2ed1eaf37f688199f12e3aa34a6f3435b906b932 | refs/heads/master | 2016-09-05T11:08:33.212588 | 2015-09-03T13:02:04 | 2015-09-03T13:02:04 | 40,049,578 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 742 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <hook.h>
extern "C" {
void* calloc_hook(size_t n, size_t size)
{
DECL_ORG_FUNC(calloc, org_calloc);
puts( __FUNCTION__ );
return org_calloc(n, size);
}
};
void test(const char* program)
{
puts(__FILE__ ": 1st");
{
HOOK(program, calloc, calloc_hook);
void* b = calloc(1, 10);
free(b);
}
puts(__FILE__ ": 2nd");
void* c = calloc(1, 10);
free(c);
puts(__FILE__ ": 3rd");
{
HOOK(program, calloc, calloc_hook);
void* b = calloc(1, 10);
free(b);
}
}
void test2(const char* program);
int main(int argc, char** argv)
{
test(argv[0]);
test2(LIB_NAME);
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
43
]
]
] |
7394745b36ae5104c00825320576a873b5d50654 | c5ed2d57496cafa1b10925814b4fc670fb9d84af | /Opensankore/build-Sankore_3.1-Unnamed-Release/build/win32/release/moc/moc_UBExportCFF.cpp | ccd670b2c223a0e089afb0adb057245688ac9bac | [] | no_license | Educabile/Ardesia | 5f5175fef5d7a15ea79469901bdd4c068cc8fec7 | 9b7b0bfe1c89e89c0ef28f93f6b1e0ac8c348230 | refs/heads/master | 2020-03-31T17:16:50.538146 | 2018-10-10T12:34:43 | 2018-10-10T12:34:43 | 152,416,207 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,429 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'UBExportCFF.h'
**
** Created: Fri 4. May 12:28:36 2018
** by: The Qt Meta Object Compiler version 63 (Qt 4.8.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../../../../Sankore-3.1/src/adaptors/UBExportCFF.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'UBExportCFF.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 63
#error "This file was generated using the moc from 4.8.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_UBExportCFF[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
static const char qt_meta_stringdata_UBExportCFF[] = {
"UBExportCFF\0"
};
void UBExportCFF::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
const QMetaObjectExtraData UBExportCFF::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject UBExportCFF::staticMetaObject = {
{ &UBExportAdaptor::staticMetaObject, qt_meta_stringdata_UBExportCFF,
qt_meta_data_UBExportCFF, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &UBExportCFF::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *UBExportCFF::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *UBExportCFF::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_UBExportCFF))
return static_cast<void*>(const_cast< UBExportCFF*>(this));
return UBExportAdaptor::qt_metacast(_clname);
}
int UBExportCFF::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = UBExportAdaptor::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_END_MOC_NAMESPACE
| [
"salvatore.naddeo@€ducabile.it"
] | [
[
[
1,
81
]
]
] |
bcee12c3aa60f8c1d8f0802c1bfdfe7600a1e3ef | 067b197860f7712e3f92564d0f8d88b0cf34f9d7 | /ext/hera/wasserstein/include/dnn/parallel/tbb.h | 64c59e0ee985223027151daa201d626258eb299b | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | tgebhart/dionysus_tensorflow | be8757369beb4997b12246c5c7d3cbdbb2fd84bb | 344769bb6d5446c8fd43462b1dfd6a08d35631a8 | refs/heads/master | 2021-09-28T10:03:56.406883 | 2018-11-16T17:15:34 | 2018-11-16T17:15:34 | 112,226,756 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,126 | h | #ifndef PARALLEL_H
#define PARALLEL_H
//#include <iostream>
#include <vector>
#include <boost/range.hpp>
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#ifdef TBB
#include <tbb/tbb.h>
#include <tbb/concurrent_hash_map.h>
#include <tbb/scalable_allocator.h>
#include <boost/serialization/split_free.hpp>
#include <boost/serialization/collections_load_imp.hpp>
#include <boost/serialization/collections_save_imp.hpp>
namespace dnn
{
using tbb::mutex;
using tbb::task_scheduler_init;
using tbb::task_group;
using tbb::task;
template<class T>
struct vector
{
typedef tbb::concurrent_vector<T> type;
};
template<class T>
struct atomic
{
typedef tbb::atomic<T> type;
static T compare_and_swap(type& v, T n, T o) { return v.compare_and_swap(n,o); }
};
template<class Iterator, class F>
void do_foreach(Iterator begin, Iterator end, const F& f) { tbb::parallel_do(begin, end, f); }
template<class Range, class F>
void for_each_range_(const Range& r, const F& f)
{
for (typename Range::iterator cur = r.begin(); cur != r.end(); ++cur)
f(*cur);
}
template<class F>
void for_each_range(size_t from, size_t to, const F& f)
{
//static tbb::affinity_partitioner ap;
//tbb::parallel_for(c.range(), boost::bind(&for_each_range_<typename Container::range_type, F>, _1, f), ap);
tbb::parallel_for(from, to, f);
}
template<class Container, class F>
void for_each_range(const Container& c, const F& f)
{
//static tbb::affinity_partitioner ap;
//tbb::parallel_for(c.range(), boost::bind(&for_each_range_<typename Container::range_type, F>, _1, f), ap);
tbb::parallel_for(c.range(), boost::bind(&for_each_range_<typename Container::const_range_type, F>, _1, f));
}
template<class Container, class F>
void for_each_range(Container& c, const F& f)
{
//static tbb::affinity_partitioner ap;
//tbb::parallel_for(c.range(), boost::bind(&for_each_range_<typename Container::range_type, F>, _1, f), ap);
tbb::parallel_for(c.range(), boost::bind(&for_each_range_<typename Container::range_type, F>, _1, f));
}
template<class ID, class NodePointer, class IDTraits, class Allocator>
struct map_traits
{
typedef tbb::concurrent_hash_map<ID, NodePointer, IDTraits, Allocator> type;
typedef typename type::range_type range;
};
struct progress_timer
{
progress_timer(): start(tbb::tick_count::now()) {}
~progress_timer()
{ std::cout << (tbb::tick_count::now() - start).seconds() << " s" << std::endl; }
tbb::tick_count start;
};
}
// Serialization for tbb::concurrent_vector<...>
namespace boost
{
namespace serialization
{
template<class Archive, class T, class A>
void save(Archive& ar, const tbb::concurrent_vector<T,A>& v, const unsigned int file_version)
{ stl::save_collection(ar, v); }
template<class Archive, class T, class A>
void load(Archive& ar, tbb::concurrent_vector<T,A>& v, const unsigned int file_version)
{
stl::load_collection<Archive,
tbb::concurrent_vector<T,A>,
stl::archive_input_seq< Archive, tbb::concurrent_vector<T,A> >,
stl::reserve_imp< tbb::concurrent_vector<T,A> >
>(ar, v);
}
template<class Archive, class T, class A>
void serialize(Archive& ar, tbb::concurrent_vector<T,A>& v, const unsigned int file_version)
{ split_free(ar, v, file_version); }
template<class Archive, class T>
void save(Archive& ar, const tbb::atomic<T>& v, const unsigned int file_version)
{ T v_ = v; ar << v_; }
template<class Archive, class T>
void load(Archive& ar, tbb::atomic<T>& v, const unsigned int file_version)
{ T v_; ar >> v_; v = v_; }
template<class Archive, class T>
void serialize(Archive& ar, tbb::atomic<T>& v, const unsigned int file_version)
{ split_free(ar, v, file_version); }
}
}
#else
#include <algorithm>
#include <map>
#include <boost/progress.hpp>
namespace dnn
{
template<class T>
struct vector
{
typedef ::std::vector<T> type;
};
template<class T>
struct atomic
{
typedef T type;
static T compare_and_swap(type& v, T n, T o) { if (v != o) return v; v = n; return o; }
};
template<class Iterator, class F>
void do_foreach(Iterator begin, Iterator end, const F& f) { std::for_each(begin, end, f); }
template<class F>
void for_each_range(size_t from, size_t to, const F& f)
{
for (size_t i = from; i < to; ++i)
f(i);
}
template<class Container, class F>
void for_each_range(Container& c, const F& f)
{
BOOST_FOREACH(const typename Container::value_type& i, c)
f(i);
}
template<class Container, class F>
void for_each_range(const Container& c, const F& f)
{
BOOST_FOREACH(const typename Container::value_type& i, c)
f(i);
}
struct mutex
{
struct scoped_lock
{
scoped_lock() {}
scoped_lock(mutex& ) {}
void acquire(mutex& ) const {}
void release() const {}
};
};
struct task_scheduler_init
{
task_scheduler_init(unsigned) {}
void initialize(unsigned) {}
static const unsigned automatic = 0;
static const unsigned deferred = 0;
};
struct task_group
{
template<class Functor>
void run(const Functor& f) const { f(); }
void wait() const {}
};
template<class ID, class NodePointer, class IDTraits, class Allocator>
struct map_traits
{
typedef std::map<ID, NodePointer,
typename IDTraits::Comparison,
Allocator> type;
typedef type range;
};
using boost::progress_timer;
}
#endif // TBB
namespace dnn
{
template<class Range, class F>
void do_foreach(const Range& range, const F& f) { do_foreach(boost::begin(range), boost::end(range), f); }
}
#endif
| [
"[email protected]"
] | [
[
[
1,
220
]
]
] |
95534aae2f06adbc3b44e859658780f8bf0cf800 | 3f9081b23333e414fb82ccb970e15b8e74072c54 | /bs2k/behaviors/skills/oneortwo_step_kick_bms.h | e7f968c14d8092e86a4e41ed23b6e7ac3a2558ab | [] | no_license | rc2dcc/Brainstormers05PublicRelease | 5c8da63ac4dd3b84985bdf791a4e5580bbf0ba59 | 2141093960fad33bf2b3186d6364c08197e9fe8e | refs/heads/master | 2020-03-22T07:32:36.757350 | 2018-07-04T18:28:32 | 2018-07-04T18:28:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,945 | h | /*
Brainstormers 2D (Soccer Simulation League 2D)
PUBLIC SOURCE CODE RELEASE 2005
Copyright (C) 1998-2005 Neuroinformatics Group,
University of Osnabrueck, Germany
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef _ONEORTWO_STEP_KICK_BMS_H_
#define _ONEORTWO_STEP_KICK_BMS_H_
/* This behavior is a port of Move_1or2_Step_Kick into the behavior
framework. get_cmd will try to kick in one step and otherwise return
a cmd that will start a two-step kick. There are some functions
that return information about the reachable velocities and the needed
steps, so that you can prepare in your code for what this behavior will
do.
This behavior usually takes the current player position as reference point,
but you can override this by calling set_state() prior to any other function.
This makes it possible to "fake" the player's position during the current cycle.
Use reset_state to re-read the WS information, or wait until the next cycle.
Note that kick_to_pos_with_final_vel() is rather unprecise concerning the
final velocity of the ball. I don't know how to calculate the needed starting
vel precisely, so I have taken the formula from the original Neuro_Kick2 move
(which was even more unprecise...) and tweaked it a bit, but it is still
not perfect.
Note also that this behavior, as opposed to the original move, has a working
collision check - the original move ignored the player's vel...
(w) 2002 Manuel Nickschas
*/
#include "../base_bm.h"
#include "one_step_kick_bms.h"
#include "angle.h"
#include "Vector.h"
#include "tools.h"
#include "cmd.h"
#include "n++.h"
#include "macro_msg.h"
#include "valueparser.h"
#include "options.h"
#include "ws_info.h"
#include "log_macros.h"
#include "mystate.h"
#include "../../policy/abstract_mdp.h"
class OneOrTwoStepKickItrActions {
static const Value kick_pwr_min = 20;
static const Value kick_pwr_inc = 10;
static const Value kick_pwr_max = 100;
static const Value kick_ang_min = 0;
static const Value kick_ang_inc = 2*PI/8.;
// static const Value kick_ang_inc = 2*PI/36.; // ridi: I think it should be as much! too much
static const Value kick_ang_max = 2*PI-kick_ang_inc;
static const Value dash_pwr_min = 20;
static const Value dash_pwr_inc = 20;
static const Value dash_pwr_max = 100;
static const Value turn_ang_min = 0;
static const Value turn_ang_inc = 2*PI/18.;
// static const Value turn_ang_max = 2*PI-turn_ang_inc;
static const Value turn_ang_max = 0; // ridi: do not allow turns
static const Value kick_pwr_steps = (kick_pwr_max-kick_pwr_min)/kick_pwr_inc + 1;
static const Value dash_pwr_steps = (dash_pwr_max-dash_pwr_min)/dash_pwr_inc + 1;
static const Value turn_ang_steps = (turn_ang_max-turn_ang_min)/turn_ang_inc + 1;
static const Value kick_ang_steps = (kick_ang_max-kick_ang_min)/kick_ang_inc + 1;
Cmd_Main action;
Value kick_pwr,dash_pwr;
ANGLE kick_ang,turn_ang;
int kick_pwr_done,kick_ang_done,dash_pwr_done,turn_ang_done;
public:
void reset() {
kick_pwr_done=0;kick_ang_done=0;dash_pwr_done=0;turn_ang_done=0;
kick_pwr=kick_pwr_min;kick_ang= ANGLE(kick_ang_min);dash_pwr=dash_pwr_min;
turn_ang=ANGLE(turn_ang_min);
}
Cmd_Main *next() {
if(kick_pwr_done<kick_pwr_steps && kick_ang_done<kick_ang_steps) {
action.unset_lock();
action.unset_cmd();
action.set_kick(kick_pwr,kick_ang.get_value_mPI_pPI());
kick_ang+= ANGLE(kick_ang_inc);
if(++kick_ang_done>=kick_ang_steps) {
kick_ang=ANGLE(kick_ang_min);
kick_ang_done=0;
kick_pwr+=kick_pwr_inc;
kick_pwr_done++;
}
return &action;
}
if(dash_pwr_done<dash_pwr_steps) {
action.unset_lock();
action.unset_cmd();
action.set_dash(dash_pwr);
dash_pwr+=dash_pwr_inc;
dash_pwr_done++;
return &action;
}
if(turn_ang_done<turn_ang_steps) {
action.unset_lock();
action.unset_cmd();
action.set_turn(turn_ang);
turn_ang+= ANGLE(turn_ang_inc);
turn_ang_done++;
return &action;
}
return NULL;
}
};
class OneOrTwoStepKick: public BaseBehavior {
static bool initialized;
#if 0
struct MyState {
Vector my_vel;
Vector my_pos;
ANGLE my_angle;
Vector ball_pos;
Vector ball_vel;
Vector op_pos;
ANGLE op_bodydir;
};
#endif
OneStepKick *onestepkick;
OneOrTwoStepKickItrActions itr_actions;
Cmd_Main result_cmd1,result_cmd2;
Value result_vel1,result_vel2;
bool result_status;
bool need_2_steps;
long set_in_cycle;
Vector target_pos;
ANGLE target_dir;
Value target_vel;
bool kick_to_pos;
bool calc_done;
MyState fake_state;
long fake_state_time;
void get_ws_state(MyState &state);
MyState get_cur_state();
bool calculate(const MyState &state,Value vel,const ANGLE &dir,const Vector &pos,bool to_pos,
Cmd_Main &res_cmd1,Value &res_vel1,Cmd_Main &res_cmd2,Value &res_vel2,
bool &need_2steps);
bool do_calc();
public:
/** This makes it possible to "fake" WS information.
This must be called _BEFORE_ any of the kick functions, and is valid for
the current cycle only.
*/
void set_state(const Vector &mypos,const Vector &myvel,const ANGLE &myang,
const Vector &ballpos,const Vector &ballvel,
const Vector &op_pos = Vector(1000,1000),
const ANGLE &op_bodydir = ANGLE(0),
const int op_bodydir_age = 1000);
void set_state( const AState & state );
/** Resets the current state to that found in WS.
This must be called _BEFORE_ any of the kick functions.
*/
void reset_state();
void kick_in_dir_with_initial_vel(Value vel,const ANGLE &dir);
void kick_in_dir_with_max_vel(const ANGLE &dir);
void kick_to_pos_with_initial_vel(Value vel,const Vector &point);
void kick_to_pos_with_final_vel(Value vel,const Vector &point);
void kick_to_pos_with_max_vel(const Vector &point);
/** false is returned if we do not reach our desired vel within two cycles.
Note that velocities are set to zero if the resulting pos is not ok,
meaning that even if a cmd would reach the desired vel, we will ignore
it if the resulting pos is not ok.
*/
bool get_vel(Value &vel_1step,Value &vel_2step);
bool get_cmd(Cmd &cmd_1step,Cmd &cmd_2step);
bool get_vel(Value &best_vel); // get best possible vel (1 or 2 step)
bool get_cmd(Cmd &best_cmd); // get best possible cmd (1 or 2 step)
// returns 0 if kick is not possible, 1 if kick in 1 step is possible, 2 if in 2 steps. probably modifies vel
int is_kick_possible(Value &speed,const ANGLE &dir);
bool need_two_steps();
bool can_keep_ball_in_kickrange();
static bool init(char const * conf_file, int argc, char const* const* argv) {
if(initialized) return true;
initialized = true;
if(OneStepKick::init(conf_file,argc,argv)) {
cout << "\nOneOrTwoStepKick behavior initialized.";
} else {
ERROR_OUT << "\nCould not initialize OneStepKick behavior - stop loading.";
exit(1);
}
return true;
}
OneOrTwoStepKick() {
set_in_cycle = -1;
onestepkick = new OneStepKick();
onestepkick->set_log(false); // we don't want OneStepKick-Info in our logs!
}
virtual ~OneOrTwoStepKick() {
delete onestepkick;
}
};
#endif
| [
"[email protected]"
] | [
[
[
1,
238
]
]
] |
40bc68efa1d237aacc7f1b2a5010046f0e4cf13c | 4b1289b0eb41c045a24b4626857097571c988e9b | /Least_Loose_Number_In_The_Array.cpp | 01dac7320be1eee1ec1af9b49c0962158327697f | [] | no_license | Arvy1998/Calculus-and-Play-with-New-Syntax | 136d942c1be8dc59d3b6d764881d7a9aea5a68cd | b442156a850dad2ed7c53ce86d3435fb35d78fe9 | refs/heads/master | 2021-07-11T02:05:09.180547 | 2019-03-12T22:00:42 | 2019-03-12T22:00:42 | 129,288,984 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 965 | cpp | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
long long n, seka[101], MIN_TEIG = 0, count;
vector <long long> izulus_teig_sk;
cin >> n;
for (auto x = 0; x < n; x++) {
cin >> seka[x];
}
for (auto i = 0; i < n; i++) {
if (i == 0) {
if (seka[i] > seka[i + 1]) {
izulus_teig_sk.push_back(seka[i]);
}
}
if (i > 0 && i < n - 1) {
if (seka[i] > seka[i - 1] && seka[i] > seka[i + 1]) {
izulus_teig_sk.push_back(seka[i]);
}
}
if (i == n - 1) {
if (seka[i] > seka[i - 1]) {
izulus_teig_sk.push_back(seka[i]);
}
}
}
if (izulus_teig_sk.size() == 0 || n <= 1) {
cout << "NO";
exit(0);
}
else {
sort(izulus_teig_sk.begin(), izulus_teig_sk.end());
for (size_t j = 0; j < izulus_teig_sk.size(); j++) {
if (izulus_teig_sk[j] > 0) {
MIN_TEIG = izulus_teig_sk[j];
cout << MIN_TEIG;
break;
}
}
}
if (MIN_TEIG == 0) {
cout << "NO";
}
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
50
]
]
] |
0f14955c67c8ded4e0b25301b31b8648ae16b52f | 4985aad8ecfceca8027709cf488bc2c601443385 | /build/Android/Debug/app/src/main/include/Fuse.Resources.Resour-7da5075.h | bb740adfa48c8d9b5e34d9b3bf2a2c23882e8030 | [] | no_license | pacol85/Test1 | a9fd874711af67cb6b9559d9a4a0e10037944d89 | c7bb59a1b961bfb40fe320ee44ca67e068f0a827 | refs/heads/master | 2021-01-25T11:39:32.441939 | 2017-06-12T21:48:37 | 2017-06-12T21:48:37 | 93,937,614 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 883 | h | // This file was generated based on '../../AppData/Local/Fusetools/Packages/Fuse.Nodes/1.0.2/$.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.h>
namespace g{namespace Fuse{namespace Resources{struct ResourceConverters;}}}
namespace g{namespace Uno{namespace Collections{struct Dictionary;}}}
namespace g{
namespace Fuse{
namespace Resources{
// internal static class ResourceConverters :3538
// {
uClassType* ResourceConverters_typeof();
void ResourceConverters__Get_fn(uType* __type, uObject** __retval);
struct ResourceConverters : uObject
{
static uSStrong< ::g::Uno::Collections::Dictionary*> _converters_;
static uSStrong< ::g::Uno::Collections::Dictionary*>& _converters() { return ResourceConverters_typeof()->Init(), _converters_; }
static uObject* Get(uType* __type);
};
// }
}}} // ::g::Fuse::Resources
| [
"[email protected]"
] | [
[
[
1,
27
]
]
] |
f45da0032ec95894d113360f36e2c7e74a3b4bd2 | be522f6110d4ed6f330da41a653460e4fb1ed3a7 | /runtime/nf/httpparser/Buffer.cc | e4717f524b583c4cfdc3f533c545bdec74c3946c | [] | no_license | yxd886/nfa | 2a796b10e6e2085470e54dd4f9a4a3721c0d27a9 | 209fd992ab931f955afea11562673fec943dd8a6 | refs/heads/master | 2020-06-17T22:09:37.259587 | 2017-03-24T03:07:38 | 2017-03-24T03:07:38 | 74,966,034 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 981 | cc |
#include "Buffer.h"
void CBuffer_Reset(struct CBuffer& Cbuf){
if(!Cbuf.buf){
Cbuf.buf = (char*) malloc(BUFFER_SIZE);
memset(Cbuf.buf,0x00,Cbuf._free);
}
if(Cbuf.len > BUFFER_SIZE * 2 && Cbuf.buf){
//如果目前buf的大小是默认值的2倍,则对其裁剪内存,保持buf的大小为默认值,减小内存耗费
char* newbuf = (char*) realloc(Cbuf.buf,BUFFER_SIZE);
if(newbuf != Cbuf.buf)
Cbuf.buf = newbuf;
}
Cbuf.len = 0;
Cbuf._free = BUFFER_SIZE;
}
bool Append(struct CBuffer& Cbuf,char* p, size_t size){
if(!p || !size)
return true;
if(size < Cbuf._free){
memcpy(Cbuf.buf + Cbuf.len, p , size);
Cbuf.len += size;
Cbuf._free -= size;
}else{
return false;
}
return true;
}
char* GetBuf(struct CBuffer Cbuf,uint32_t& size){
size = Cbuf.len;
return Cbuf.buf;
}
uint32_t GetBufLen(struct CBuffer Cbuf){
return Cbuf.len;
}
void Buf_init(struct CBuffer& Cbuf){
Cbuf.len=0;
Cbuf._free=0;
Cbuf.buf=0;
CBuffer_Reset(Cbuf);
}
| [
"[email protected]"
] | [
[
[
1,
52
]
]
] |
b7c78a511904d321aa74ab25ce20a44c3a3f0a0e | d51d72f1b6e834d89c8551bb07487bed84cdaa31 | /src/output/osg/customCode/osg/AnimationPath_pmoc.cpp | dc66ae9496a4b899d13c9038f85bec5d8cc50019 | [] | no_license | wangfeilong321/osg4noob | 221204aa15efa18f1f049548ad076ef27371ecad | 99a15c3fd2523c4bd537fa3afb0b47e15c8f335a | refs/heads/master | 2021-01-12T20:00:43.854775 | 2015-11-06T15:37:01 | 2015-11-06T15:37:01 | 48,840,543 | 0 | 1 | null | 2015-12-31T07:56:31 | 2015-12-31T07:56:31 | null | UTF-8 | C++ | false | false | 1,778 | cpp | #include <osg/AnimationPath>
//includes
#include <MetaQQuickLibraryRegistry.h>
#include <customCode/osg/AnimationPath_pmoc.hpp>
using namespace pmoc;
osg::QMLAnimationPath::QMLAnimationPath(pmoc::Instance *i,QObject* parent):QReflect_AnimationPath(i,parent){
//custom initializations
}
QQuickItem* osg::QMLAnimationPath::connect2View(QQuickItem*i){
this->_view=QReflect_AnimationPath::connect2View(i);
///connect this's signals/slot to its qml component////////////////////////////////////////////////////////////////
///CustomiZE here
return this->_view;
}
void osg::QMLAnimationPath::updateModel(){
QReflect_AnimationPath::updateModel();
///update this according to state of _model when it has been changed via pmoc/////////////////////////////////////////////
///CustomiZE here
}
#ifndef AUTOMOCCPP
#define AUTOMOCCPP 1
#include "moc_AnimationPath_pmoc.cpp"
#endif
#include <MetaQQuickLibraryRegistry.h>
#include <customCode/osg/AnimationPath_pmoc.hpp>
using namespace pmoc;
osg::QMLAnimationPathCallback::QMLAnimationPathCallback(pmoc::Instance *i,QObject* parent):QReflect_AnimationPathCallback(i,parent){
//custom initializations
}
QQuickItem* osg::QMLAnimationPathCallback::connect2View(QQuickItem*i){
this->_view=QReflect_AnimationPathCallback::connect2View(i);
///connect this's signals/slot to its qml component////////////////////////////////////////////////////////////////
///CustomiZE here
return this->_view;
}
void osg::QMLAnimationPathCallback::updateModel(){
QReflect_AnimationPathCallback::updateModel();
///update this according to state of _model when it has been changed via pmoc/////////////////////////////////////////////
///CustomiZE here
}
#ifndef AUTOMOCCPP
#define AUTOMOCCPP 1
#include "moc_AnimationPath_pmoc.cpp"
#endif
| [
"[email protected]"
] | [
[
[
1,
56
]
]
] |
58b00a4202d32fd15e1533444149d9af6d0445dd | e1cda708e5087296dab0fc224a44dc8d7368c63c | /PWGPP/TPC/AliPerformanceRes.cxx | b459e100d86013154e2bec140f3af8694d0034fa | [] | no_license | pbatzing/AliPhysics | 36039c28c9670d08bb8de2bcf369840a3a191bbb | 8f0962d72943081031580a544a17d6e52e74c481 | refs/heads/master | 2021-01-22T22:44:31.003908 | 2017-04-04T11:14:26 | 2017-04-04T11:14:26 | 85,572,640 | 0 | 0 | null | 2017-03-20T12:10:32 | 2017-03-20T12:10:32 | null | UTF-8 | C++ | false | false | 45,205 | cxx | //------------------------------------------------------------------------------
// Implementation of AliPerformanceRes class. It keeps information from
// comparison of reconstructed and MC particle tracks. In addtion,
// it keeps selection cuts used during comparison. The comparison
// information is stored in the ROOT histograms. Analysis of these
// histograms can be done by using Analyse() class function. The result of
// the analysis (histograms/graphs) are stored in the folder which is
// a data member of AliPerformanceRes.
//
// Author: J.Otwinowski 04/02/2008
//------------------------------------------------------------------------------
/*
// after running comparison task, read the file, and get component
gROOT->LoadMacro("$ALICE_PHYSICS/PWGPP/Macros/LoadMyLibs.C");
LoadMyLibs();
TFile f("Output.root");
AliPerformanceRes * compObj = (AliPerformanceRes*)coutput->FindObject("AliPerformanceRes");
// analyse comparison data
compObj->Analyse();
// the output histograms/graphs will be stored in the folder "folderRes"
compObj->GetAnalysisFolder()->ls("*");
// user can save whole comparison object (or only folder with anlysed histograms)
// in the seperate output file (e.g.)
TFile fout("Analysed_Res.root","recreate");
compObj->Write(); // compObj->GetAnalysisFolder()->Write();
fout.Close();
*/
#include "TCanvas.h"
#include "TH1.h"
#include "TH2.h"
#include "TAxis.h"
#include "TF1.h"
#include "AliPerformanceRes.h"
#include "AliESDEvent.h"
#include "AliESDVertex.h"
#include "AliESDtrack.h"
#include "AliESDfriendTrack.h"
#include "AliESDfriend.h"
#include "AliLog.h"
#include "AliMCEvent.h"
#include "AliMCParticle.h"
#include "AliHeader.h"
#include "AliGenEventHeader.h"
#include "AliStack.h"
#include "AliMCInfoCuts.h"
#include "AliRecInfoCuts.h"
#include "AliTracker.h"
#include "AliTreeDraw.h"
using namespace std;
ClassImp(AliPerformanceRes)
Double_t AliPerformanceRes::fgkMergeEntriesCut=5000000.; //5*10**6 tracks (small default to keep default memory foorprint low)
//_____________________________________________________________________________
AliPerformanceRes::AliPerformanceRes(const Char_t* name, const Char_t* title, Int_t analysisMode, Bool_t hptGenerator):
AliPerformanceObject(name,title),
fResolHisto(0),
fPullHisto(0),
// Cuts
fCutsRC(0),
fCutsMC(0),
// histogram folder
fAnalysisFolder(0)
{
// named constructor
//
SetAnalysisMode(analysisMode);
SetHptGenerator(hptGenerator);
Init();
}
//_____________________________________________________________________________
AliPerformanceRes::~AliPerformanceRes()
{
// destructor
if(fResolHisto) delete fResolHisto; fResolHisto=0;
if(fPullHisto) delete fPullHisto; fPullHisto=0;
if(fAnalysisFolder) delete fAnalysisFolder; fAnalysisFolder=0;
}
//_____________________________________________________________________________
void AliPerformanceRes::Init(){
//
// histogram bining
//
// set pt bins
Int_t nPtBins = 50;
Double_t ptMin = 1.e-1, ptMax = 20.;
Double_t *binsPt = 0;
if (IsHptGenerator()) {
ptMax = 100.;
}
binsPt = CreateLogAxis(nPtBins,ptMin,ptMax);
Double_t yMin = -0.02, yMax = 0.02;
Double_t zMin = -12.0, zMax = 12.0;
if(GetAnalysisMode() == 3) { // TrackRef coordinate system
yMin = -100.; yMax = 100.;
zMin = -100.; zMax = 100.;
}
// res_y:res_z:res_phi,res_lambda:res_pt:y:z:eta:phi:pt
Int_t binsResolHisto[10]={100,100,100,100,100,25,50,144,30,nPtBins};
Double_t minResolHisto[10]={-1.,-1.,-0.03,-0.03,-0.2, yMin, zMin, 0., -1.5, ptMin};
Double_t maxResolHisto[10]={ 1., 1., 0.03, 0.03, 0.2, yMax, zMax, 2.*TMath::Pi(), 1.5, ptMax};
fResolHisto = new THnSparseF("fResolHisto","res_y:res_z:res_phi:res_lambda:res_pt:y:z:phi:eta:pt",10,binsResolHisto,minResolHisto,maxResolHisto);
//fResolHisto->SetBinEdges(9,binsPt);
fResolHisto->GetAxis(9)->Set(nPtBins,binsPt);
fResolHisto->GetAxis(0)->SetTitle("y-y_{mc} (cm)");
fResolHisto->GetAxis(1)->SetTitle("z-z_{mc} (cm)");
fResolHisto->GetAxis(2)->SetTitle("#phi-#phi_{mc} (rad)");
fResolHisto->GetAxis(3)->SetTitle("#lambda-#lambda_{mc} (rad)");
fResolHisto->GetAxis(4)->SetTitle("(p_{T}/p_{Tmc}-1)");
fResolHisto->GetAxis(5)->SetTitle("y_{mc} (cm)");
fResolHisto->GetAxis(6)->SetTitle("z_{mc} (cm)");
fResolHisto->GetAxis(7)->SetTitle("#phi_{mc} (rad)");
fResolHisto->GetAxis(8)->SetTitle("#eta_{mc}");
fResolHisto->GetAxis(9)->SetTitle("p_{Tmc} (GeV/c)");
fResolHisto->Sumw2();
////pull_y:pull_z:pull_phi:pull_lambda:pull_1pt:y:z:eta:phi:pt
//Int_t binsPullHisto[10]={100,100,100,100,100,50,50,30,144,nPtBins};
//Double_t minPullHisto[10]={-5.,-5.,-5.,-5.,-5.,yMin, zMin,-1.5, 0., ptMin};
//Double_t maxPullHisto[10]={ 5., 5., 5., 5., 5., yMax, zMax, 1.5, 2.*TMath::Pi(),ptMax};
//fPullHisto = new THnSparseF("fPullHisto","pull_y:pull_z:pull_phi:pull_lambda:pull_1pt:y:z:eta:phi:pt",10,binsPullHisto,minPullHisto,maxPullHisto);
//pull_y:pull_z:pull_snp:pull_tgl:pull_1pt:y:z:snp:tgl:1pt
//Int_t binsPullHisto[10]={100,100,100,100,100,50,50,50,50,nPtBins};
//Double_t minPullHisto[10]={-5.,-5.,-5.,-5.,-5.,yMin, zMin,-1., -2.0, ptMin};
//Double_t maxPullHisto[10]={ 5., 5., 5., 5., 5., yMax, zMax, 1., 2.0, ptMax};
Int_t binsPullHisto[10]={100,100,100,100,100,50,50,50,50,20};
Double_t minPullHisto[10]={-5.,-5.,-5.,-5.,-5.,yMin, zMin,-1., -2.0, 0.};
Double_t maxPullHisto[10]={ 5., 5., 5., 5., 5., yMax, zMax, 1., 2.0, 10.};
fPullHisto = new THnSparseF("fPullHisto","pull_y:pull_z:pull_y:pull_z:pull_snp:pull_tgl:pull_1pt:y:z:snp:tgl:1pt",10,binsPullHisto,minPullHisto,maxPullHisto);
/*
if(!IsHptGenerator()) fPullHisto->SetBinEdges(9,bins1Pt);
fPullHisto->GetAxis(0)->SetTitle("(y-y_{mc})/#sigma");
fPullHisto->GetAxis(1)->SetTitle("(z-z_{mc})/#sigma");
fPullHisto->GetAxis(2)->SetTitle("(#phi-#phi_{mc})/#sigma");
fPullHisto->GetAxis(3)->SetTitle("(#lambda-#lambda_{mc})/#sigma");
fPullHisto->GetAxis(4)->SetTitle("(p_{Tmc}/p_{T}-1)/#sigma");
fPullHisto->GetAxis(5)->SetTitle("y_{mc} (cm)");
fPullHisto->GetAxis(6)->SetTitle("z_{mc} (cm)");
fPullHisto->GetAxis(7)->SetTitle("#eta_{mc}");
fPullHisto->GetAxis(8)->SetTitle("#phi_{mc} (rad)");
fPullHisto->GetAxis(9)->SetTitle("p_{Tmc} (GeV/c)");
fPullHisto->Sumw2();
*/
fPullHisto->GetAxis(9)->Set(nPtBins,binsPt);
fPullHisto->GetAxis(0)->SetTitle("(y-y_{mc})/#sigma");
fPullHisto->GetAxis(1)->SetTitle("(z-z_{mc})/#sigma");
fPullHisto->GetAxis(2)->SetTitle("(sin#phi-sin#phi_{mc})/#sigma");
fPullHisto->GetAxis(3)->SetTitle("(tan#lambda-tan#lambda_{mc})/#sigma");
fPullHisto->GetAxis(4)->SetTitle("(p_{Tmc}/p_{T}-1)/#sigma");
fPullHisto->GetAxis(5)->SetTitle("y_{mc} (cm)");
fPullHisto->GetAxis(6)->SetTitle("z_{mc} (cm)");
fPullHisto->GetAxis(7)->SetTitle("sin#phi_{mc}");
fPullHisto->GetAxis(8)->SetTitle("tan#lambda_{mc}");
fPullHisto->GetAxis(9)->SetTitle("1/p_{Tmc} (GeV/c)^{-1}");
fPullHisto->Sumw2();
// Init cuts
if(!fCutsMC)
AliDebug(AliLog::kError, "ERROR: Cannot find AliMCInfoCuts object");
if(!fCutsRC)
AliDebug(AliLog::kError, "ERROR: Cannot find AliRecInfoCuts object");
// init folder
fAnalysisFolder = CreateFolder("folderRes","Analysis Resolution Folder");
}
//_____________________________________________________________________________
void AliPerformanceRes::ProcessTPC(AliStack* const stack, AliESDtrack *const esdTrack, AliESDEvent* const esdEvent)
{
if(!esdEvent) return;
if(!esdTrack) return;
if( IsUseTrackVertex() )
{
// Relate TPC inner params to prim. vertex
const AliESDVertex *vtxESD = esdEvent->GetPrimaryVertexTracks();
Double_t x[3]; esdTrack->GetXYZ(x);
Double_t b[3]; AliTracker::GetBxByBz(x,b);
Bool_t isOK = esdTrack->RelateToVertexTPCBxByBz(vtxESD, b, kVeryBig);
if(!isOK) return;
/*
// JMT -- recaluclate DCA for HLT if not present
if ( dca[0] == 0. && dca[1] == 0. ) {
track->GetDZ( vtxESD->GetX(), vtxESD->GetY(), vtxESD->GetZ(), esdEvent->GetMagneticField(), dca );
}
*/
}
// Fill TPC only resolution comparison information
const AliExternalTrackParam* tmpTrack = esdTrack->GetTPCInnerParam();
if(!tmpTrack) return;
AliExternalTrackParam track = *tmpTrack;
Float_t dca[2], cov[3]; // dca_xy, dca_z, sigma_xy, sigma_xy_z, sigma_z
esdTrack->GetImpactParametersTPC(dca,cov);
//
// Fill rec vs MC information
//
if(!stack) return;
Int_t label = esdTrack->GetTPCLabel(); //Use TPC-only label for TPC-only resolution analysis
if (label <= 0) return;
TParticle* particle = stack->Particle(label);
if(!particle) return;
if(!particle->GetPDG()) return;
if(particle->GetPDG()->Charge()==0) return;
//printf("charge %d \n",particle->GetPDG()->Charge());
// Only 5 charged particle species (e,mu,pi,K,p)
if (fCutsMC->IsPdgParticle(TMath::Abs(particle->GetPdgCode())) == kFALSE) return;
// exclude electrons
if (fCutsMC->GetEM()==TMath::Abs(particle->GetPdgCode())) return;
Float_t deltaPtTPC, deltaYTPC, deltaZTPC, deltaPhiTPC, deltaLambdaTPC;
Float_t pull1PtTPC, pullYTPC, pullZTPC, pullPhiTPC, pullLambdaTPC;
Float_t mceta = particle->Eta();
Float_t mcphi = particle->Phi();
if(mcphi<0) mcphi += 2.*TMath::Pi();
Float_t mcpt = particle->Pt();
Float_t mcsnp = TMath::Sin(TMath::ATan2(particle->Py(),particle->Px()));
Float_t mctgl = TMath::Tan(TMath::ATan2(particle->Pz(),particle->Pt()));
// nb. TPC clusters cut
if (esdTrack->GetTPCNcls()<fCutsRC->GetMinNClustersTPC()) return;
// select primaries
if(TMath::Abs(dca[0])<fCutsRC->GetMaxDCAToVertexXY() && TMath::Abs(dca[1])<fCutsRC->GetMaxDCAToVertexZ())
{
if(mcpt == 0) return;
double Bz = esdEvent->GetMagneticField();
Double_t mclocal[4]; //Rotated x,y,px,py mc-coordinates - the MC data should be rotated since the track is propagated best along x
Double_t c = TMath::Cos(track.GetAlpha());
Double_t s = TMath::Sin(track.GetAlpha());
Double_t x = particle->Vx();
Double_t y = particle->Vy();
mclocal[0] = x*c + y*s;
mclocal[1] =-x*s + y*c;
Double_t px = particle->Px();
Double_t py = particle->Py();
mclocal[2] = px*c + py*s;
mclocal[3] =-px*s + py*c;
Float_t mcsnplocal = TMath::Sin(TMath::ATan2(mclocal[3],mclocal[2]));
track.AliExternalTrackParam::PropagateTo(mclocal[0],Bz);
deltaYTPC= track.GetY()-mclocal[1];
deltaZTPC = track.GetZ()-particle->Vz();
deltaLambdaTPC = TMath::ATan2(track.Pz(),track.Pt())-TMath::ATan2(particle->Pz(),particle->Pt());
//See comments in ProcessInnerTPC for remarks on local and global momentum coordinates for deltaPhi / pullSnp calculation
deltaPhiTPC = TMath::ATan2(track.Py(),track.Px())-TMath::ATan2(particle->Py(),particle->Px());
//delta1PtTPC = (track.OneOverPt()-1./mcpt)*mcpt;
deltaPtTPC = (track.Pt()-mcpt) / mcpt;
pullYTPC= deltaYTPC / TMath::Sqrt(track.GetSigmaY2());
pullZTPC = deltaZTPC / TMath::Sqrt(track.GetSigmaZ2());
//Double_t sigma_lambda = 1./(1.+track.GetTgl()*track.GetTgl()) * TMath::Sqrt(track.GetSigmaTgl2());
//Double_t sigma_phi = 1./TMath::Sqrt(1-track.GetSnp()*track.GetSnp()) * TMath::Sqrt(track.GetSigmaSnp2());
pullPhiTPC = (track.GetSnp() - mcsnplocal) / TMath::Sqrt(track.GetSigmaSnp2());
pullLambdaTPC = (track.GetTgl() - mctgl) / TMath::Sqrt(track.GetSigmaTgl2());
//pullLambdaTPC = deltaLambdaTPC / TMath::Sqrt(track.GetSigmaTgl2());
//pullPhiTPC = deltaPhiTPC / TMath::Sqrt(track.GetSigmaSnp2());
if (mcpt) pull1PtTPC = (track.OneOverPt()-1./mcpt) / TMath::Sqrt(track.GetSigma1Pt2());
else pull1PtTPC = 0.;
Double_t vResolHisto[10] = {deltaYTPC,deltaZTPC,deltaPhiTPC,deltaLambdaTPC,deltaPtTPC,particle->Vy(),particle->Vz(),mcphi,mceta,mcpt};
fResolHisto->Fill(vResolHisto);
Double_t vPullHisto[10] = {pullYTPC,pullZTPC,pullPhiTPC,pullLambdaTPC,pull1PtTPC,particle->Vy(),particle->Vz(),mcsnp,mctgl,1./mcpt};
fPullHisto->Fill(vPullHisto);
}
}
//_____________________________________________________________________________
void AliPerformanceRes::ProcessTPCITS(AliStack* const stack, AliESDtrack *const esdTrack, AliESDEvent* const esdEvent)
{
// Fill resolution comparison information (TPC+ITS)
if(!esdEvent) return;
if(!esdTrack) return;
if( IsUseTrackVertex() )
{
// Relate TPC inner params to prim. vertex
const AliESDVertex *vtxESD = esdEvent->GetPrimaryVertexTracks();
Double_t x[3]; esdTrack->GetXYZ(x);
Double_t b[3]; AliTracker::GetBxByBz(x,b);
Bool_t isOK = esdTrack->RelateToVertexBxByBz(vtxESD, b, kVeryBig);
if(!isOK) return;
/*
// JMT -- recaluclate DCA for HLT if not present
if ( dca[0] == 0. && dca[1] == 0. ) {
track->GetDZ( vtxESD->GetX(), vtxESD->GetY(), vtxESD->GetZ(), esdEvent->GetMagneticField(), dca );
}
*/
}
Float_t dca[2], cov[3]; // dca_xy, dca_z, sigma_xy, sigma_xy_z, sigma_z
esdTrack->GetImpactParameters(dca,cov);
//
// Fill rec vs MC information
//
if(!stack) return;
Int_t label = TMath::Abs(esdTrack->GetLabel()); //Use global label for combined resolution analysis
TParticle* particle = stack->Particle(label);
if(!particle) return;
if(!particle->GetPDG()) return;
if(particle->GetPDG()->Charge()==0) return;
//printf("charge %d \n",particle->GetPDG()->Charge());
// Only 5 charged particle species (e,mu,pi,K,p)
if (fCutsMC->IsPdgParticle(TMath::Abs(particle->GetPdgCode())) == kFALSE) return;
// exclude electrons
if (fCutsMC->GetEM()==TMath::Abs(particle->GetPdgCode())) return;
Float_t mceta = particle->Eta();
Float_t mcphi = particle->Phi();
if(mcphi<0) mcphi += 2.*TMath::Pi();
Float_t mcpt = particle->Pt();
Float_t mcsnp = TMath::Sin(TMath::ATan2(particle->Py(),particle->Px()));
Float_t mctgl = TMath::Tan(TMath::ATan2(particle->Pz(),particle->Pt()));
if ((esdTrack->GetStatus()&AliESDtrack::kTPCrefit)==0) return; // TPC refit
if (esdTrack->GetTPCNcls()<fCutsRC->GetMinNClustersTPC()) return; // min. nb. TPC clusters
if(esdTrack->GetITSclusters(0)<fCutsRC->GetMinNClustersITS()) return; // min. nb. ITS clusters
Float_t deltaPtTPC, deltaYTPC, deltaZTPC, deltaPhiTPC, deltaLambdaTPC;
Float_t pull1PtTPC, pullYTPC, pullZTPC, pullPhiTPC, pullLambdaTPC;
// select primaries
if(TMath::Abs(dca[0])<fCutsRC->GetMaxDCAToVertexXY() && TMath::Abs(dca[1])<fCutsRC->GetMaxDCAToVertexZ())
{
if(mcpt == 0) return;
deltaYTPC= esdTrack->GetY()-particle->Vy();
deltaZTPC = esdTrack->GetZ()-particle->Vz();
deltaLambdaTPC = TMath::ATan2(esdTrack->Pz(),esdTrack->Pt())-TMath::ATan2(particle->Pz(),particle->Pt());
deltaPhiTPC = TMath::ATan2(esdTrack->Py(),esdTrack->Px())-TMath::ATan2(particle->Py(),particle->Px());
//delta1PtTPC = (esdTrack->OneOverPt()-1./mcpt)*mcpt;
deltaPtTPC = (esdTrack->Pt()-mcpt) / mcpt;
pullYTPC= (esdTrack->GetY()-particle->Vy()) / TMath::Sqrt(esdTrack->GetSigmaY2());
pullZTPC = (esdTrack->GetZ()-particle->Vz()) / TMath::Sqrt(esdTrack->GetSigmaZ2());
//Double_t sigma_lambda = 1./(1.+esdTrack->GetTgl()*esdTrack->GetTgl()) * TMath::Sqrt(esdTrack->GetSigmaTgl2());
//Double_t sigma_phi = 1./TMath::Sqrt(1-esdTrack->GetSnp()*esdTrack->GetSnp()) * TMath::Sqrt(esdTrack->GetSigmaSnp2());
pullPhiTPC = (esdTrack->GetSnp() - mcsnp) / TMath::Sqrt(esdTrack->GetSigmaSnp2());
pullLambdaTPC = (esdTrack->GetTgl() - mctgl) / TMath::Sqrt(esdTrack->GetSigmaTgl2());
//pullLambdaTPC = deltaLambdaTPC / TMath::Sqrt(esdTrack->GetSigmaTgl2());
//pullPhiTPC = deltaPhiTPC / TMath::Sqrt(esdTrack->GetSigmaSnp2());
if (mcpt) pull1PtTPC = (esdTrack->OneOverPt()-1./mcpt) / TMath::Sqrt(esdTrack->GetSigma1Pt2());
else pull1PtTPC = 0.;
Double_t vResolHisto[10] = {deltaYTPC,deltaZTPC,deltaPhiTPC,deltaLambdaTPC,deltaPtTPC,particle->Vy(),particle->Vz(),mcphi,mceta,mcpt};
fResolHisto->Fill(vResolHisto);
Double_t vPullHisto[10] = {pullYTPC,pullZTPC,pullPhiTPC,pullLambdaTPC,pull1PtTPC,particle->Vy(),particle->Vz(),mcsnp,mctgl,1./mcpt};
fPullHisto->Fill(vPullHisto);
/*
deltaYTPC= esdTrack->GetY()-particle->Vy();
deltaZTPC = esdTrack->GetZ()-particle->Vz();
deltaLambdaTPC = TMath::ATan2(esdTrack->Pz(),esdTrack->Pt())-TMath::ATan2(particle->Pz(),particle->Pt());
deltaPhiTPC = TMath::ATan2(esdTrack->Py(),esdTrack->Px())-TMath::ATan2(particle->Py(),particle->Px());
delta1PtTPC = (esdTrack->OneOverPt()-1./mcpt)*mcpt;
pullYTPC= (esdTrack->GetY()-particle->Vy()) / TMath::Sqrt(esdTrack->GetSigmaY2());
pullZTPC = (esdTrack->GetZ()-particle->Vz()) / TMath::Sqrt(esdTrack->GetSigmaZ2());
Double_t sigma_lambda = 1./(1.+esdTrack->GetTgl()*esdTrack->GetTgl()) * TMath::Sqrt(esdTrack->GetSigmaTgl2());
Double_t sigma_phi = 1./TMath::Sqrt(1-esdTrack->GetSnp()*esdTrack->GetSnp()) * TMath::Sqrt(esdTrack->GetSigmaSnp2());
pullLambdaTPC = deltaLambdaTPC / sigma_lambda;
pullPhiTPC = deltaPhiTPC / sigma_phi;
//pullLambdaTPC = deltaLambdaTPC / TMath::Sqrt(esdTrack->GetSigmaTgl2());
//pullPhiTPC = deltaPhiTPC / TMath::Sqrt(esdTrack->GetSigmaSnp2());
if (mcpt) pull1PtTPC = (esdTrack->OneOverPt()-1./mcpt) / TMath::Sqrt(esdTrack->GetSigma1Pt2());
else pull1PtTPC = 0.;
Double_t vResolHisto[10] = {deltaYTPC,deltaZTPC,deltaPhiTPC,deltaLambdaTPC,delta1PtTPC,particle->Vy(),particle->Vz(),mceta,mcphi,mcpt};
fResolHisto->Fill(vResolHisto);
Double_t vPullHisto[10] = {pullYTPC,pullZTPC,pullPhiTPC,pullLambdaTPC,pull1PtTPC,particle->Vy(),particle->Vz(),mceta,mcphi,mcpt};
fPullHisto->Fill(vPullHisto);
*/
}
}
//_____________________________________________________________________________
void AliPerformanceRes::ProcessConstrained(AliStack* const stack, AliESDtrack *const esdTrack, AliESDEvent* const esdEvent)
{
// Fill resolution comparison information (constarained parameters)
//
if(!esdEvent) return;
if(!esdTrack) return;
if( IsUseTrackVertex() )
{
// Relate TPC inner params to prim. vertex
const AliESDVertex *vtxESD = esdEvent->GetPrimaryVertexTracks();
Double_t x[3]; esdTrack->GetXYZ(x);
Double_t b[3]; AliTracker::GetBxByBz(x,b);
Bool_t isOK = esdTrack->RelateToVertexBxByBz(vtxESD, b, kVeryBig);
if(!isOK) return;
/*
// JMT -- recaluclate DCA for HLT if not present
if ( dca[0] == 0. && dca[1] == 0. ) {
track->GetDZ( vtxESD->GetX(), vtxESD->GetY(), vtxESD->GetZ(), esdEvent->GetMagneticField(), dca );
}
*/
}
const AliExternalTrackParam * track = esdTrack->GetConstrainedParam();
if(!track) return;
Float_t dca[2], cov[3]; // dca_xy, dca_z, sigma_xy, sigma_xy_z, sigma_z
esdTrack->GetImpactParameters(dca,cov);
//
// Fill rec vs MC information
//
if(!stack) return;
Int_t label = TMath::Abs(esdTrack->GetLabel());
TParticle* particle = stack->Particle(label);
if(!particle) return;
if(!particle->GetPDG()) return;
if(particle->GetPDG()->Charge()==0) return;
//printf("charge %d \n",particle->GetPDG()->Charge());
// Only 5 charged particle species (e,mu,pi,K,p)
if (fCutsMC->IsPdgParticle(TMath::Abs(particle->GetPdgCode())) == kFALSE) return;
// exclude electrons
if (fCutsMC->GetEM()==TMath::Abs(particle->GetPdgCode())) return;
Float_t mceta = particle->Eta();
Float_t mcphi = particle->Phi();
if(mcphi<0) mcphi += 2.*TMath::Pi();
Float_t mcpt = particle->Pt();
Float_t mcsnp = TMath::Sin(TMath::ATan2(particle->Py(),particle->Px()));
Float_t mctgl = TMath::Tan(TMath::ATan2(particle->Pz(),particle->Pt()));
if ((esdTrack->GetStatus()&AliESDtrack::kTPCrefit)==0) return; // TPC refit
if (esdTrack->GetTPCNcls()<fCutsRC->GetMinNClustersTPC()) return; // min. nb. TPC clusters
Float_t deltaPtTPC, deltaYTPC, deltaZTPC, deltaPhiTPC, deltaLambdaTPC;
Float_t pull1PtTPC, pullYTPC, pullZTPC, pullPhiTPC, pullLambdaTPC;
// select primaries
if(TMath::Abs(dca[0])<fCutsRC->GetMaxDCAToVertexXY() && TMath::Abs(dca[1])<fCutsRC->GetMaxDCAToVertexZ())
{
if(mcpt == 0) return;
deltaYTPC= track->GetY()-particle->Vy();
deltaZTPC = track->GetZ()-particle->Vz();
deltaLambdaTPC = TMath::ATan2(track->Pz(),track->Pt())-TMath::ATan2(particle->Pz(),particle->Pt());
deltaPhiTPC = TMath::ATan2(track->Py(),track->Px())-TMath::ATan2(particle->Py(),particle->Px());
//delta1PtTPC = (track->OneOverPt()-1./mcpt)*mcpt;
deltaPtTPC = (track->Pt()-mcpt) / mcpt;
pullYTPC= (track->GetY()-particle->Vy()) / TMath::Sqrt(track->GetSigmaY2());
pullZTPC = (track->GetZ()-particle->Vz()) / TMath::Sqrt(track->GetSigmaZ2());
//Double_t sigma_lambda = 1./(1.+track->GetTgl()*track->GetTgl()) * TMath::Sqrt(track->GetSigmaTgl2());
//Double_t sigma_phi = 1./TMath::Sqrt(1-track->GetSnp()*track->GetSnp()) * TMath::Sqrt(track->GetSigmaSnp2());
pullPhiTPC = (track->GetSnp() - mcsnp) / TMath::Sqrt(track->GetSigmaSnp2());
pullLambdaTPC = (track->GetTgl() - mctgl) / TMath::Sqrt(track->GetSigmaTgl2());
//pullLambdaTPC = deltaLambdaTPC / TMath::Sqrt(track->GetSigmaTgl2());
//pullPhiTPC = deltaPhiTPC / TMath::Sqrt(track->GetSigmaSnp2());
if (mcpt) pull1PtTPC = (track->OneOverPt()-1./mcpt) / TMath::Sqrt(track->GetSigma1Pt2());
else pull1PtTPC = 0.;
Double_t vResolHisto[10] = {deltaYTPC,deltaZTPC,deltaPhiTPC,deltaLambdaTPC,deltaPtTPC,particle->Vy(),particle->Vz(),mcphi,mceta,mcpt};
fResolHisto->Fill(vResolHisto);
Double_t vPullHisto[10] = {pullYTPC,pullZTPC,pullPhiTPC,pullLambdaTPC,pull1PtTPC,particle->Vy(),particle->Vz(),mcsnp,mctgl,1./mcpt};
fPullHisto->Fill(vPullHisto);
/*
deltaYTPC= track->GetY()-particle->Vy();
deltaZTPC = track->GetZ()-particle->Vz();
deltaLambdaTPC = TMath::ATan2(track->Pz(),track->Pt())-TMath::ATan2(particle->Pz(),particle->Pt());
deltaPhiTPC = TMath::ATan2(track->Py(),track->Px())-TMath::ATan2(particle->Py(),particle->Px());
delta1PtTPC = (track->OneOverPt()-1./mcpt)*mcpt;
pullYTPC= (track->GetY()-particle->Vy()) / TMath::Sqrt(track->GetSigmaY2());
pullZTPC = (track->GetZ()-particle->Vz()) / TMath::Sqrt(track->GetSigmaZ2());
Double_t sigma_lambda = 1./(1.+track->GetTgl()*track->GetTgl()) * TMath::Sqrt(track->GetSigmaTgl2());
Double_t sigma_phi = 1./TMath::Sqrt(1-track->GetSnp()*track->GetSnp()) * TMath::Sqrt(track->GetSigmaSnp2());
pullLambdaTPC = deltaLambdaTPC / sigma_lambda;
pullPhiTPC = deltaPhiTPC / sigma_phi;
//pullLambdaTPC = deltaLambdaTPC / TMath::Sqrt(track->GetSigmaTgl2());
//pullPhiTPC = deltaPhiTPC / TMath::Sqrt(track->GetSigmaSnp2());
if (mcpt) pull1PtTPC = (track->OneOverPt()-1./mcpt) / TMath::Sqrt(track->GetSigma1Pt2());
else pull1PtTPC = 0.;
Double_t vResolHisto[10] = {deltaYTPC,deltaZTPC,deltaPhiTPC,deltaLambdaTPC,delta1PtTPC,particle->Vy(),particle->Vz(),mceta,mcphi,mcpt};
fResolHisto->Fill(vResolHisto);
Double_t vPullHisto[10] = {pullYTPC,pullZTPC,pullPhiTPC,pullLambdaTPC,pull1PtTPC,particle->Vy(),particle->Vz(),mceta,mcphi,mcpt};
fPullHisto->Fill(vPullHisto);
*/
}
}
//_____________________________________________________________________________
void AliPerformanceRes::ProcessInnerTPC(AliMCEvent *const mcEvent, AliESDtrack *const esdTrack, AliESDEvent* const esdEvent)
{
//
// Fill resolution comparison information (inner params at TPC reference point)
//
if(!esdEvent) return;
if(!esdTrack) return;
if( IsUseTrackVertex() )
{
// Relate TPC inner params to prim. vertex
const AliESDVertex *vtxESD = esdEvent->GetPrimaryVertexTracks();
Double_t x[3]; esdTrack->GetXYZ(x);
Double_t b[3]; AliTracker::GetBxByBz(x,b);
Bool_t isOK = esdTrack->RelateToVertexTPCBxByBz(vtxESD, b, kVeryBig);
if(!isOK) return;
/*
// JMT -- recaluclate DCA for HLT if not present
if ( dca[0] == 0. && dca[1] == 0. ) {
track->GetDZ( vtxESD->GetX(), vtxESD->GetY(), vtxESD->GetZ(), esdEvent->GetMagneticField(), dca );
}
*/
}
const AliExternalTrackParam * innerParam = esdTrack->GetInnerParam();
if(!innerParam) return;
// create new AliExternalTrackParam
AliExternalTrackParam *track = new AliExternalTrackParam(*innerParam);
if(!track) return;
Float_t dca[2], cov[3]; // dca_xy, dca_z, sigma_xy, sigma_xy_z, sigma_z
esdTrack->GetImpactParametersTPC(dca,cov);
//
// Fill rec vs MC information
//
if(!mcEvent) return;
Int_t label = esdTrack->GetTPCLabel(); //Use TPC-only label for TPC-only resolution analysis
if (label <= 0) return;
AliMCParticle *mcParticle = (AliMCParticle*) mcEvent->GetTrack(label);
if(!mcParticle) return;
// get the first TPC track reference
AliTrackReference *ref0 = GetFirstTPCTrackRef(mcParticle);
if(!ref0) return;
// Only 5 charged particle species (e,mu,pi,K,p)
TParticle *particle = mcParticle->Particle();
if(!particle) return;
if (fCutsMC->IsPdgParticle(TMath::Abs(particle->GetPdgCode())) == kFALSE) return;
// exclude electrons
if (fCutsMC->GetEM()==TMath::Abs(particle->GetPdgCode())) return;
Double_t mclocal[4]; //Rotated x,y,Px,Py mc-coordinates - the MC data should be rotated since the track is propagated best along x
Double_t c = TMath::Cos(track->GetAlpha());
Double_t s = TMath::Sin(track->GetAlpha());
Double_t x = ref0->X();
Double_t y = ref0->Y();
mclocal[0] = x*c + y*s;
mclocal[1] =-x*s + y*c;
Double_t px = ref0->Px();
Double_t py = ref0->Py();
mclocal[2] = px*c + py*s;
mclocal[3] =-px*s + py*c;
//Double_t xyz[3] = {ref0->X(),ref0->Y(),ref0->Z()};
// propagate track to the radius of the first track reference within TPC
//Double_t trRadius = TMath::Sqrt(xyz[1] * xyz[1] + xyz[0] * xyz[0]);
Double_t field[3]; track->GetBxByBz(field);
if (TGeoGlobalMagField::Instance()->GetField() == NULL) {
Error("ProcessInnerTPC", "Magnetic Field not set");
}
Bool_t isOK = track->PropagateToBxByBz(mclocal[0],field);
if(!isOK) {return;}
//track->AliExternalTrackParam::PropagateTo(mclocal[0],esdEvent->GetMagneticField()); //Use different propagation since above methods returns zero B field and does not work
Float_t mceta = -TMath::Log(TMath::Tan(0.5 * ref0->Theta()));
Float_t mcphi = ref0->Phi();
if(mcphi<0) mcphi += 2.*TMath::Pi();
Float_t mcpt = ref0->Pt();
Float_t mcsnp = TMath::Sin(TMath::ATan2(ref0->Py(),ref0->Px()));
Float_t mcsnplocal = TMath::Sin(TMath::ATan2(mclocal[3],mclocal[2]));
Float_t mctgl = TMath::Tan(TMath::ATan2(ref0->Pz(),ref0->Pt()));
if ((esdTrack->GetStatus()&AliESDtrack::kTPCrefit)==0) return; // TPC refit
if (esdTrack->GetTPCNcls()<fCutsRC->GetMinNClustersTPC()) return; // min. nb. TPC clusters
Float_t deltaPtTPC, deltaYTPC, deltaZTPC, deltaPhiTPC, deltaLambdaTPC;
Float_t pull1PtTPC, pullYTPC, pullZTPC, pullPhiTPC, pullLambdaTPC;
// select primaries
Bool_t isPrimary;
if ( IsUseTrackVertex() )
{
isPrimary = TMath::Abs(dca[0])<fCutsRC->GetMaxDCAToVertexXY() && TMath::Abs(dca[1])<fCutsRC->GetMaxDCAToVertexZ();
}
else
{
//If Track vertex is not used the above check does not work, hence we use the MC reference track
isPrimary = label < mcEvent->Stack()->GetNprimary();
}
if(isPrimary)
{
if(mcpt == 0) return;
deltaYTPC= track->GetY()-mclocal[1];
deltaZTPC = track->GetZ()-ref0->Z();
deltaLambdaTPC = TMath::ATan2(track->Pz(),track->Pt())-TMath::ATan2(ref0->Pz(),ref0->Pt());
//track->Px() etc returns momentum in global coordinates, hence mc momentum must not be rotated.
deltaPhiTPC = TMath::ATan2(track->Py(),track->Px())-TMath::ATan2(ref0->Py(),ref0->Px());
//delta1PtTPC = (track->OneOverPt()-1./mcpt)*mcpt;
deltaPtTPC = (track->Pt()-mcpt) / mcpt;
pullYTPC= deltaYTPC / TMath::Sqrt(track->GetSigmaY2());
pullZTPC = deltaZTPC / TMath::Sqrt(track->GetSigmaZ2());
//Double_t sigma_lambda = 1./(1.+track->GetTgl()*track->GetTgl()) * TMath::Sqrt(track->GetSigmaTgl2());
//Double_t sigma_phi = 1./TMath::Sqrt(1-track->GetSnp()*track->GetSnp()) * TMath::Sqrt(track->GetSigmaSnp2());
//track->GetSnp returns value in local coordinates, hence here, in contrast to deltaPhiTPC, the mc momentum must be rotated
pullPhiTPC = (track->GetSnp() - mcsnplocal) / TMath::Sqrt(track->GetSigmaSnp2());
pullLambdaTPC = (track->GetTgl() - mctgl) / TMath::Sqrt(track->GetSigmaTgl2());
//pullLambdaTPC = deltaLambdaTPC / TMath::Sqrt(track->GetSigmaTgl2());
//pullPhiTPC = deltaPhiTPC / TMath::Sqrt(track->GetSigmaSnp2());
if (mcpt) pull1PtTPC = (track->OneOverPt()-1./mcpt) / TMath::Sqrt(track->GetSigma1Pt2());
else pull1PtTPC = 0.;
Double_t vResolHisto[10] = {deltaYTPC,deltaZTPC,deltaPhiTPC,deltaLambdaTPC,deltaPtTPC,ref0->Y(),ref0->Z(),mcphi,mceta,mcpt};
fResolHisto->Fill(vResolHisto);
Double_t vPullHisto[10] = {pullYTPC,pullZTPC,pullPhiTPC,pullLambdaTPC,pull1PtTPC,ref0->Y(),ref0->Z(),mcsnp,mctgl,1./mcpt};
fPullHisto->Fill(vPullHisto);
}
if(track) delete track;
}
//_____________________________________________________________________________
void AliPerformanceRes::ProcessOuterTPC(AliMCEvent *const mcEvent, AliESDtrack *const esdTrack, AliESDfriendTrack *const friendTrack, AliESDEvent* const esdEvent)
{
//
// Fill resolution comparison information (outer params at TPC reference point)
//
if(!friendTrack) return;
if(!esdEvent) return;
if(!esdTrack) return;
if( IsUseTrackVertex() )
{
// Relate TPC inner params to prim. vertex
const AliESDVertex *vtxESD = esdEvent->GetPrimaryVertexTracks();
Double_t x[3]; esdTrack->GetXYZ(x);
Double_t b[3]; AliTracker::GetBxByBz(x,b);
Bool_t isOK = esdTrack->RelateToVertexTPCBxByBz(vtxESD, b, kVeryBig);
if(!isOK) return;
/*
// JMT -- recaluclate DCA for HLT if not present
if ( dca[0] == 0. && dca[1] == 0. ) {
track->GetDZ( vtxESD->GetX(), vtxESD->GetY(), vtxESD->GetZ(), esdEvent->GetMagneticField(), dca );
}
*/
}
const AliExternalTrackParam * outerParam = friendTrack->GetTPCOut();
if(!outerParam) return;
// create new AliExternalTrackParam
AliExternalTrackParam *track = new AliExternalTrackParam(*outerParam);
if(!track) return;
Float_t dca[2], cov[3]; // dca_xy, dca_z, sigma_xy, sigma_xy_z, sigma_z
esdTrack->GetImpactParametersTPC(dca,cov);
//
// Fill rec vs MC information
//
if(!mcEvent) return;
Int_t label = esdTrack->GetTPCLabel(); //Use TPC-only label for TPC-only resolution analysis
if (label <= 0) return;
AliMCParticle *mcParticle = (AliMCParticle*) mcEvent->GetTrack(label);
if(!mcParticle) return;
// get the last TPC track reference
AliTrackReference *ref0 = GetLastTPCTrackRef(mcParticle);
if(!ref0) return;
// Only 5 charged particle species (e,mu,pi,K,p)
TParticle *particle = mcParticle->Particle();
if(!particle) return;
if (fCutsMC->IsPdgParticle(TMath::Abs(particle->GetPdgCode())) == kFALSE) return;
// exclude electrons
if (fCutsMC->GetEM()==TMath::Abs(particle->GetPdgCode())) return;
// calculate alpha angle
Double_t xyz[3] = {ref0->X(),ref0->Y(),ref0->Z()};
Double_t alpha = TMath::ATan2(xyz[1],xyz[0]);
//if (alpha<0) alpha += TMath::TwoPi();
// rotate outer track to local coordinate system
// and propagate to the radius of the last track reference of TPC
Double_t trRadius = TMath::Sqrt(xyz[1] * xyz[1] + xyz[0] * xyz[0]);
//Bool_t isOK = track->Propagate(alpha,trRadius,AliTracker::GetBz());
Double_t field[3]; track->GetBxByBz(field);
Bool_t isOK = track->PropagateBxByBz(alpha,trRadius,field);
if(!isOK) return;
Float_t mceta = -TMath::Log(TMath::Tan(0.5 * ref0->Theta()));
Float_t mcphi = ref0->Phi();
if(mcphi<0) mcphi += 2.*TMath::Pi();
Float_t mcpt = ref0->Pt();
Float_t mcsnp = TMath::Sin(TMath::ATan2(ref0->Py(),ref0->Px()));
Float_t mctgl = TMath::Tan(TMath::ATan2(ref0->Pz(),ref0->Pt()));
if ((esdTrack->GetStatus()&AliESDtrack::kTPCrefit)==0) return; // TPC refit
if (esdTrack->GetTPCNcls()<fCutsRC->GetMinNClustersTPC()) return; // min. nb. TPC clusters
Float_t deltaPtTPC, deltaYTPC, deltaZTPC, deltaPhiTPC, deltaLambdaTPC;
Float_t pull1PtTPC, pullYTPC, pullZTPC, pullPhiTPC, pullLambdaTPC;
// select primaries
if(TMath::Abs(dca[0])<fCutsRC->GetMaxDCAToVertexXY() && TMath::Abs(dca[1])<fCutsRC->GetMaxDCAToVertexZ())
{
if(mcpt == 0) return;
deltaYTPC= track->GetY(); // already rotated
deltaZTPC = track->GetZ()-ref0->Z();
deltaLambdaTPC = TMath::ATan2(track->Pz(),track->Pt())-TMath::ATan2(ref0->Pz(),ref0->Pt());
deltaPhiTPC = TMath::ATan2(track->Py(),track->Px())-TMath::ATan2(ref0->Py(),ref0->Px());
//delta1PtTPC = (track->OneOverPt()-1./mcpt)*mcpt;
deltaPtTPC = (track->Pt()-mcpt) / mcpt;
pullYTPC= track->GetY() / TMath::Sqrt(track->GetSigmaY2());
pullZTPC = (track->GetZ()-ref0->Z()) / TMath::Sqrt(track->GetSigmaZ2());
//Double_t sigma_lambda = 1./(1.+track->GetTgl()*track->GetTgl()) * TMath::Sqrt(track->GetSigmaTgl2());
//Double_t sigma_phi = 1./TMath::Sqrt(1-track->GetSnp()*track->GetSnp()) * TMath::Sqrt(track->GetSigmaSnp2());
pullPhiTPC = (track->GetSnp() - mcsnp) / TMath::Sqrt(track->GetSigmaSnp2());
pullLambdaTPC = (track->GetTgl() - mctgl) / TMath::Sqrt(track->GetSigmaTgl2());
//pullLambdaTPC = deltaLambdaTPC / TMath::Sqrt(track->GetSigmaTgl2());
//pullPhiTPC = deltaPhiTPC / TMath::Sqrt(track->GetSigmaSnp2());
if (mcpt) pull1PtTPC = (track->OneOverPt()-1./mcpt) / TMath::Sqrt(track->GetSigma1Pt2());
else pull1PtTPC = 0.;
Double_t vResolHisto[10] = {deltaYTPC,deltaZTPC,deltaPhiTPC,deltaLambdaTPC,deltaPtTPC,ref0->Y(),ref0->Z(),mcphi,mceta,mcpt};
fResolHisto->Fill(vResolHisto);
Double_t vPullHisto[10] = {pullYTPC,pullZTPC,pullPhiTPC,pullLambdaTPC,pull1PtTPC,ref0->Y(),ref0->Z(),mcsnp,mctgl,1./mcpt};
fPullHisto->Fill(vPullHisto);
}
if(track) delete track;
}
//_____________________________________________________________________________
AliTrackReference * AliPerformanceRes::GetFirstTPCTrackRef(AliMCParticle *mcParticle)
{
// return first TPC track reference
if(!mcParticle) return 0;
// find first track reference
// check direction to select proper reference point for looping tracks
Int_t nTrackRef = mcParticle->GetNumberOfTrackReferences();
AliTrackReference *ref = 0;
AliTrackReference *refIn = 0;
for (Int_t iref = 0; iref < nTrackRef; iref++) {
ref = mcParticle->GetTrackReference(iref);
if(ref && (ref->DetectorId()==AliTrackReference::kTPC))
{
Float_t dir = ref->X()*ref->Px()+ref->Y()*ref->Py();
if(dir < 0.) break;
refIn = ref;
break;
}
}
return refIn;
}
//_____________________________________________________________________________
AliTrackReference * AliPerformanceRes::GetLastTPCTrackRef(AliMCParticle *mcParticle)
{
// return last TPC track reference
if(!mcParticle) return 0;
// find last track reference
// check direction to select proper reference point for looping tracks
Int_t nTrackRef = mcParticle->GetNumberOfTrackReferences();
AliTrackReference *ref = 0;
AliTrackReference *refOut = 0;
for (Int_t iref = 0; iref < nTrackRef; iref++) {
ref = mcParticle->GetTrackReference(iref);
if(ref && (ref->DetectorId()==AliTrackReference::kTPC)) {
Float_t dir=ref->X()*ref->Px()+ref->Y()*ref->Py();
if(dir< 0.0) break;
refOut = ref;
}
}
return refOut;
}
//_____________________________________________________________________________
void AliPerformanceRes::Exec(AliMCEvent* const mcEvent, AliESDEvent *const esdEvent, AliESDfriend *const esdFriend, const Bool_t bUseMC, const Bool_t bUseESDfriend)
{
// Process comparison information
if(!esdEvent)
{
Error("Exec","esdEvent not available");
return;
}
AliHeader* header = 0;
AliGenEventHeader* genHeader = 0;
AliStack* stack = 0;
TArrayF vtxMC(3);
if(bUseMC)
{
if(!mcEvent) {
Error("Exec","mcEvent not available");
return;
}
// get MC event header
header = mcEvent->Header();
if (!header) {
Error("Exec","Header not available");
return;
}
// MC particle stack
stack = mcEvent->Stack();
if (!stack) {
Error("Exec","Stack not available");
return;
}
// get MC vertex
genHeader = header->GenEventHeader();
if (!genHeader) {
Error("Exec","Could not retrieve genHeader from Header");
return;
}
genHeader->PrimaryVertex(vtxMC);
}
else {
Error("Exec","MC information required!");
return;
}
// use ESD friends
if(bUseESDfriend) {
if(!esdFriend) {
Error("Exec","esdFriend not available");
return;
}
}
// get event vertex
const AliESDVertex *vtxESD = NULL;
if( IsUseTrackVertex() )
{
// track vertex
vtxESD = esdEvent->GetPrimaryVertexTracks();
if(vtxESD && (vtxESD->GetStatus()<=0)) return;
}
// Coverity - removed else branch as vtxESD is not further used in method
// else {
// // TPC track vertex
// vtxESD = esdEvent->GetPrimaryVertexTPC();
// }
// Process events
for (Int_t iTrack = 0; iTrack < esdEvent->GetNumberOfTracks(); iTrack++)
{
AliESDtrack *track = esdEvent->GetTrack(iTrack);
if(!track) continue;
AliESDfriendTrack *friendTrack=0;
Int_t label = TMath::Abs(track->GetLabel());
if ( label > stack->GetNtrack() )
{
ULong_t status = track->GetStatus();
printf ("Error : ESD MCLabel %d - StackSize %d - Status %lu \n",
track->GetLabel(), stack->GetNtrack(), status );
printf(" NCluster %d \n", track->GetTPCclusters(0) );
/*
if ((status&AliESDtrack::kTPCrefit)== 0 ) printf(" kTPCrefit \n");
if ((status&AliESDtrack::kTPCin)== 0 ) printf(" kTPCin \n");
if ((status&AliESDtrack::kTPCout)== 0 ) printf(" kTPCout \n");
if ((status&AliESDtrack::kTRDrefit)== 0 ) printf(" kTRDrefit \n");
if ((status&AliESDtrack::kTRDin)== 0 ) printf(" kTRDin \n");
if ((status&AliESDtrack::kTRDout)== 0 ) printf(" kTRDout \n");
if ((status&AliESDtrack::kITSrefit)== 0 ) printf(" kITSrefit \n");
if ((status&AliESDtrack::kITSin)== 0 ) printf(" kITSin \n");
if ((status&AliESDtrack::kITSout)== 0 ) printf(" kITSout \n");
*/
continue;
}
if (label == 0) continue; //Cannot distinguish between track or fake track
if (track->GetLabel() < 0) continue; //Do not consider fake tracks
if(GetAnalysisMode() == 0) ProcessTPC(stack,track,esdEvent);
else if(GetAnalysisMode() == 1) ProcessTPCITS(stack,track,esdEvent);
else if(GetAnalysisMode() == 2) ProcessConstrained(stack,track,esdEvent);
else if(GetAnalysisMode() == 3) ProcessInnerTPC(mcEvent,track,esdEvent);
else if(GetAnalysisMode() == 4) {
if(bUseESDfriend) {
friendTrack=esdFriend->GetTrack(iTrack);
if(!friendTrack) continue;
}
ProcessOuterTPC(mcEvent,track,friendTrack,esdEvent);
}
else {
printf("ERROR: AnalysisMode %d \n",fAnalysisMode);
return;
}
}
}
//_____________________________________________________________________________
TH1F* AliPerformanceRes::MakeResol(TH2F * his, Int_t integ, Bool_t type, Int_t cut){
// Create resolution histograms
TH1F *hisr, *hism;
if (!gPad) new TCanvas;
hisr = AliTreeDraw::CreateResHistoII(his,&hism,integ,kTRUE,cut);
if (type) return hism;
else
return hisr;
}
//_____________________________________________________________________________
void AliPerformanceRes::Analyse() {
// Analyse comparison information and store output histograms
// in the folder "folderRes"
//
TH1::AddDirectory(kFALSE);
TH1F *h=0;
TH2F *h2D=0;
TObjArray *aFolderObj = new TObjArray;
if(!aFolderObj) return;
// write results in the folder
TCanvas * c = new TCanvas("Phi resol Tan","Phi resol Tan");
c->cd();
char name[256];
char title[256];
for(Int_t i=0; i<5; i++)
{
for(Int_t j=5; j<10; j++)
{
if(j!=8) fResolHisto->GetAxis(8)->SetRangeUser(-0.9,0.89); // eta window
//if(j!=8) fResolHisto->GetAxis(8)->SetRangeUser(0.0,0.89); // eta window
else fResolHisto->GetAxis(8)->SetRangeUser(-1.5,1.49);
if(GetAnalysisMode() == 3) fResolHisto->GetAxis(5)->SetRangeUser(-80.,79.99); // y range
h2D = (TH2F*)fResolHisto->Projection(i,j);
h = AliPerformanceRes::MakeResol(h2D,1,0,100);
snprintf(name,256,"h_res_%d_vs_%d",i,j);
h->SetName(name);
h->GetXaxis()->SetTitle(fResolHisto->GetAxis(j)->GetTitle());
snprintf(title,256,"%s %s",fResolHisto->GetAxis(i)->GetTitle(),"(resolution)");
h->GetYaxis()->SetTitle(title);
snprintf(title,256,"%s vs %s",title,fResolHisto->GetAxis(j)->GetTitle());
h->SetTitle(title);
if(j==9) h->SetBit(TH1::kLogX);
aFolderObj->Add(h);
h = AliPerformanceRes::MakeResol(h2D,1,1,100);
//h = (TH1F*)arr->At(1);
snprintf(name,256,"h_mean_res_%d_vs_%d",i,j);
h->SetName(name);
h->GetXaxis()->SetTitle(fResolHisto->GetAxis(j)->GetTitle());
snprintf(title,256,"%s %s",fResolHisto->GetAxis(i)->GetTitle(),"(mean)");
h->GetYaxis()->SetTitle(title);
snprintf(title,256,"%s vs %s",title,fResolHisto->GetAxis(j)->GetTitle());
h->SetTitle(title);
if(j==9) h->SetBit(TH1::kLogX);
aFolderObj->Add(h);
fResolHisto->GetAxis(8)->SetRangeUser(-1.5,1.5);
fResolHisto->GetAxis(9)->SetRangeUser(0.1,100.);
//
if(j!=8) fPullHisto->GetAxis(8)->SetRangeUser(-0.9,0.89); // eta window
//if(j!=8) fPullHisto->GetAxis(8)->SetRangeUser(0.0,0.89); // eta window
else fPullHisto->GetAxis(8)->SetRangeUser(-1.5,1.49); // eta window
fPullHisto->GetAxis(9)->SetRangeUser(0.,9.99); // 1./pt threshold
if(GetAnalysisMode() == 3) fPullHisto->GetAxis(5)->SetRangeUser(-80.,79.99); // y range
h2D = (TH2F*)fPullHisto->Projection(i,j);
h = AliPerformanceRes::MakeResol(h2D,1,0,100);
snprintf(name,256,"h_pull_%d_vs_%d",i,j);
h->SetName(name);
h->GetXaxis()->SetTitle(fPullHisto->GetAxis(j)->GetTitle());
snprintf(title,256,"%s %s",fPullHisto->GetAxis(i)->GetTitle(),"(resolution)");
h->GetYaxis()->SetTitle(title);
snprintf(title,256,"%s vs %s",title,fPullHisto->GetAxis(j)->GetTitle());
h->SetTitle(title);
//if(j==9) h->SetBit(TH1::kLogX);
aFolderObj->Add(h);
h = AliPerformanceRes::MakeResol(h2D,1,1,100);
snprintf(name,256,"h_mean_pull_%d_vs_%d",i,j);
h->SetName(name);
h->GetXaxis()->SetTitle(fPullHisto->GetAxis(j)->GetTitle());
snprintf(title,256,"%s %s",fPullHisto->GetAxis(i)->GetTitle(),"(mean)");
h->GetYaxis()->SetTitle(title);
snprintf(title,256,"%s vs %s",title,fPullHisto->GetAxis(j)->GetTitle());
h->SetTitle(title);
//if(j==9) h->SetBit(TH1::kLogX);
aFolderObj->Add(h);
}
}
for (Int_t i = 0;i < fResolHisto->GetNdimensions();i++)
{
fResolHisto->GetAxis(i)->SetRange(1,0); //Reset Range
}
for (Int_t i = 0;i < fPullHisto->GetNdimensions();i++)
{
fPullHisto->GetAxis(i)->SetRange(1,0); //Reset Range
}
// export objects to analysis folder
fAnalysisFolder = ExportToFolder(aFolderObj);
// delete only TObjArray
if(aFolderObj) delete aFolderObj;
}
//_____________________________________________________________________________
TFolder* AliPerformanceRes::ExportToFolder(TObjArray * array)
{
// recreate folder avery time and export objects to new one
//
AliPerformanceRes * comp=this;
TFolder *folder = comp->GetAnalysisFolder();
TString name, title;
TFolder *newFolder = 0;
Int_t i = 0;
Int_t size = array->GetSize();
if(folder) {
// get name and title from old folder
name = folder->GetName();
title = folder->GetTitle();
// delete old one
delete folder;
// create new one
newFolder = CreateFolder(name.Data(),title.Data());
newFolder->SetOwner();
// add objects to folder
while(i < size) {
newFolder->Add(array->At(i));
i++;
}
}
return newFolder;
}
//_____________________________________________________________________________
Long64_t AliPerformanceRes::Merge(TCollection* const list)
{
// Merge list of objects (needed by PROOF)
if (!list)
return 0;
if (list->IsEmpty())
return 1;
TIterator* iter = list->MakeIterator();
TObject* obj = 0;
// collection of generated histograms
Int_t count=0;
while((obj = iter->Next()) != 0)
{
AliPerformanceRes* entry = dynamic_cast<AliPerformanceRes*>(obj);
if (entry == 0) continue;
if (fResolHisto->GetEntries()<fgkMergeEntriesCut){
fResolHisto->Add(entry->fResolHisto);
fPullHisto->Add(entry->fPullHisto);
}
count++;
}
return count;
}
//_____________________________________________________________________________
TFolder* AliPerformanceRes::CreateFolder(TString name,TString title) {
// create folder for analysed histograms
//
TFolder *folder = 0;
folder = new TFolder(name.Data(),title.Data());
return folder;
}
| [
"jotwinow@f7af4fe6-9843-0410-8265-dc069ae4e863",
"[email protected]",
"mkrzewic@f7af4fe6-9843-0410-8265-dc069ae4e863",
"jthaeder@f7af4fe6-9843-0410-8265-dc069ae4e863",
"marian@f7af4fe6-9843-0410-8265-dc069ae4e863"
] | [
[
[
1,
15
],
[
17,
61
],
[
63,
64
],
[
66,
220
],
[
225,
253
],
[
255,
263
],
[
292,
292
],
[
297,
297
],
[
302,
617
],
[
629,
630
],
[
632,
633
],
[
641,
645
],
[
647,
655
],
[
667,
669
],
[
671,
672
],
[
674,
677
],
[
680,
682
],
[
685,
930
],
[
932,
932
],
[
939,
972
],
[
976,
1029
],
[
1032,
1104
],
[
1114,
1159
],
[
1161,
1175
],
[
1180,
1195
]
],
[
[
16,
16
]
],
[
[
62,
62
],
[
65,
65
]
],
[
[
221,
224
],
[
254,
254
],
[
264,
291
],
[
293,
296
],
[
298,
301
],
[
618,
628
],
[
631,
631
],
[
634,
640
],
[
646,
646
],
[
656,
666
],
[
670,
670
],
[
673,
673
],
[
678,
679
],
[
683,
684
],
[
931,
931
],
[
933,
938
],
[
973,
975
],
[
1030,
1031
],
[
1105,
1113
]
],
[
[
1160,
1160
],
[
1176,
1179
]
]
] |
fb91f6eaa8d8ee4570429a0ed27d843cbd9b7e4f | 1d3220f8f390aa9f5847ace75afdb045531e6cd5 | /DMUploadingRule.cpp | afbd8ae8d3bf984ef96b2eeb2910225e7677da0c | [] | no_license | persenlee/FileTransfer | d85d7577e3366c5515d86ef47c8c925feb2d62d1 | fff2f0b9649fd6259cece45e6b2adfa3bb26d008 | refs/heads/master | 2021-01-01T03:46:55.882496 | 2016-05-20T03:22:28 | 2016-05-20T03:22:28 | 58,631,662 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,625 | cpp | //
// DMUploadingRule.cpp
// FileTransfer
//
// Created by duomai on 16/5/16.
//
//
#include "DMUploadingRule.hpp"
#include "DMFileUploadManager.hpp"
#include "DMFileTransferException.hpp"
#include "DMFileTransferDef.h"
using namespace web;
using namespace web::json;
void logRequest(http_request request);
void logResponse(http_response response);
void DMUploadingRule::setUserToken(string const &token)
{
_userToken = token;
}
#pragma mark - Ovrride Methods
bool DMUploadingRule::preProcess()
{
return checkFileMeta();
}
bool DMUploadingRule::doUpload()
{
return uploadFileChunk();
}
bool DMUploadingRule::endProcess()
{
return true;
}
#pragma mark - Private Methods
bool DMUploadingRule::checkFileMeta()
{
json::value params = json::value::object();
utility::string_t file_hash(U("file_hash"));
params[file_hash] = json::value(_file.SHA1());
utility::string_t file_crc(U("file_crc"));
params[file_crc] = json::value(_file.CRC32());
utility::string_t file_name(U("file_name"));
params[file_name] = json::value(_file.fileName);
utility::string_t total_size(U("total_size"));
params[total_size] = json::value(_file.fileSize());
const method mtd = methods::POST;
const utility::string_t field_name1 = U("user_session_token");
const utility::string_t value1 = _userToken;
http_request request(mtd);
request.set_request_uri(U("check_file_meta"));
request.headers().add(field_name1, value1);
request.set_body(params);
request.headers().add(U("User-Agent"), "DMFileUploadManager");
pplx::task<http_response> responsetTask = _client.request(request);
logRequest(request);
http_response resp ;
try {
resp = responsetTask.get();
} catch (http_exception ex) {
DMFileTransferException dmException((int)DMFileTransfer_CouldNotGetResponse);
throw dmException;
}
logResponse(resp);
if (resp.status_code() == 200)
{
pplx::task<json::value> jsonTask = resp.extract_json();
json::value result= jsonTask.get();
json::value file_status = result[U("file_status")]; //
json::value file_upload_token = result[U("file_upload_token")];
json::value file_url = result[U("file_url")];
json::value last_ok_chunk_sn = result[U("last_ok_chunk_sn")];
json::value chunk_size = result[U("chunk_size")];
cfmrModel = CheckFileMetaResponseModel((DMFileUploadStatus)file_status.as_integer(),
!file_upload_token.is_null() ? file_upload_token.as_string() : "",
!chunk_size.is_null() ? chunk_size.as_integer() : 0,
!last_ok_chunk_sn.is_null() ? last_ok_chunk_sn.as_integer() : 0,
!file_url.is_null() ? file_url.as_string() : "");
switch (cfmrModel.file_status)
{
case 0:
{
_handler->uploadingProgressHandler(0, _file.fileSize());
}
break;
case 1:
{
_handler->uploadingProgressHandler(cfmrModel.chunk_size * cfmrModel.last_ok_chunk_sn, _file.fileSize());
}
break;
case 2:
{
_handler->uploadCompleteHandler(true,file_url.as_string());
_handler->uploadingProgressHandler(_file.fileSize(), _file.fileSize());
return false;
}
break;
default:
break;
}
return true;
}
else
{
_handler->uploadCompleteHandler(false, "");
return false;
}
}
bool DMUploadingRule::uploadFileChunk()
{
bool success = false;
const method mtd = methods::POST;
const utility::string_t field_name1 = U("upload_token");
const utility::string_t value1 = cfmrModel.file_upload_token;
http_request request(mtd);
request.set_request_uri(U("upload_file_chunk"));
request.headers().add(field_name1, value1);
request.headers().set_content_length(INTMAX_MAX);
request.headers().add(U("User-Agent"), "DMFileUploadManager");
int64_t File_Size = _file.fileLength();
_file.openFile(/*iostream::binary*/);
//续传
int64_t uploadedSize = cfmrModel.last_ok_chunk_sn * cfmrModel.chunk_size;
if (uploadedSize > 0) {
_file.moveFileReadPos(uploadedSize);
}
do {
int request_again_times = 0;
int readSize = cfmrModel.chunk_size;
if (uploadedSize + cfmrModel.chunk_size > File_Size) {
readSize = File_Size % cfmrModel.chunk_size;
}
std::vector<unsigned char> body;
_file.readFile2Vector(body, readSize);
request.set_body(body);
request_again:
request_again_times ++;
logRequest(request);
pplx::task<http_response> responsetTask = _client.request(request);
http_response resp ;
try {
resp = responsetTask.get();
} catch (http_exception ex) {
DMFileTransferException dmException((int)DMFileTransfer_CouldNotGetResponse);
throw dmException;
}
logResponse(resp);
if (resp.status_code() == 200)
{
pplx::task<json::value> jsonTask = resp.extract_json();
json::value result= jsonTask.get();
cout << "response body : " << result.serialize() << endl;
json::value file_status = result[U("file_status")]; //
json::value chunk_status = result[U("chunk_status")];
json::value file_url = result[U("file_url")];
switch (file_status.as_integer())
{
case 1: //正在上传
{
if (chunk_status.as_integer() == -1) { // 标识数据块保存失败
goto request_again;
} else if(chunk_status.as_integer() == 0){
uploadedSize += readSize;
_handler->uploadingProgressHandler(uploadedSize, File_Size);
}
}
break;
case 2: //上传成功
{
uploadedSize += readSize;
_handler->uploadingProgressHandler(uploadedSize, File_Size);
_handler->uploadCompleteHandler(true,file_url.as_string());
success = true;
}
break;
case -1: //文件上传失败
{
_handler->uploadCompleteHandler(false, "");;
}
break;
default:
break;
}
}
else
{
_handler->uploadCompleteHandler(false, "");
}
} while (uploadedSize < File_Size);
_file.closeFile();
return success;
}
void logRequest(http_request request)
{
cout << "---------------------request start------------------" << endl;
cout << request.to_string() << endl;
cout << "---------------------request end------------------" << endl << endl;
}
void logResponse(http_response response)
{
cout << "++++++++++++++++++++response start++++++++++++++++++++" << endl;
cout << response.to_string() << endl;
cout << "++++++++++++++++++++response end++++++++++++++++++++" << endl << endl;
} | [
"[email protected]"
] | [
[
[
1,
238
]
]
] |
376f659de9de4170c19135d4e5e6f4fa7d95e938 | bc33abf80f11c4df023d6b1f0882bff1e30617cf | /CPP/other/李泉彰/hhh.cpp | 0e114bad33f893d5b9c3e166e74c22c9172ffe76 | [] | no_license | pkuzhd/ALL | 0fad250c710b4804dfd6f701d8f45381ee1a5d11 | c18525decdfa70346ec32ca2f47683951f4c39e0 | refs/heads/master | 2022-07-11T18:20:26.435897 | 2019-11-20T13:25:24 | 2019-11-20T13:25:24 | 119,031,607 | 0 | 0 | null | 2022-06-21T21:10:42 | 2018-01-26T09:19:23 | C++ | UTF-8 | C++ | false | false | 6,060 | cpp | #include <stdio.h>
#include <iostream>
using namespace std;
int qipan[15][15] = { 0 };
int times = 0;
int print();
bool is_win(int x, int y, int flag);
bool is_near(int x, int y);
bool AI_set(int flag);
int calc_value(int x, int y, int flag, int depth, int _max_value);
int qixing(int x, int y);
int main(int argc, char **argv)
{
int flag = 1;
while (true)
{
++times;
print();
int x, y;
if (flag == 1)
{
while (true)
{
cin >> x >> y;
if (!qipan[x][y] || x < 0 || x >= 15 || y < 0 || y >= 15)
break;
}
qipan[x][y] = flag;
if (is_win(x, y, flag))
break;
}
else
{
if (AI_set(flag))
break;
}
flag *= -1;
}
if (flag == 1)
{
printf("black\n");
}
else
{
printf("white\n");
}
system("pause");
return 0;
}
int print()
{
for (int i = 0; i < 15; ++i)
{
for (int j = 0; j < 15; ++j)
cout << (qipan[i][j] ? (qipan[i][j] == 1 ? "*" : "#") : "0");
cout << endl;
}
cout << endl;
return 0;
}
bool is_win(int x, int y, int flag)
{
int number = 1;
for (int i = x + 1; i < 15; ++i)
{
if (qipan[i][y] == flag)
++number;
else
break;
}
for (int i = x - 1; i >= 0; --i)
{
if (qipan[i][y] == flag)
++number;
else
break;
}
if (number >= 5)
return true;
number = 1;
for (int i = y + 1; i < 15; ++i)
{
if (qipan[x][i] == flag)
++number;
else
break;
}
for (int i = y - 1; i >= 0; --i)
{
if (qipan[x][i] == flag)
++number;
else
break;
}
if (number >= 5)
return true;
number = 1;
for (int j = 1; x + j < 15 && y + j < 15; ++j)
{
if (qipan[x + j][y + j] == flag)
++number;
else
break;
}
for (int j = 1; x - j >= 0 && y - j >= 0; ++j)
{
if (qipan[x - j][y - j] == flag)
++number;
else
break;
}
if (number >= 5)
return true;
number = 1;
for (int j = 1; x + j < 15 && y - j >= 0; ++j)
{
if (qipan[x + j][y - j] == flag)
++number;
else
break;
}
for (int j = 1; x - j >= 0 && y + j < 15; ++j)
{
if (qipan[x - j][y + j] == flag)
++number;
else
break;
}
if (number >= 5)
return true;
return false;
}
bool is_near(int x, int y)
{
// cout << x << " " << y << endl;
int _near = 2;
for (int i = (x - _near >= 0 ? x - _near : 0); i <= (x + _near < 15 ? x + _near : 14); ++i)
{
for (int j = (y - _near >= 0 ? y - _near : 0); j <= (y + _near < 15 ? y + _near : 14); ++j)
{
if (qipan[i][j])
return true;
}
}
return false;
}
bool AI_set(int flag)
{
int max_value = -10000000;
int x = 7, y = 7;
for (int i = 0; i < 15; ++i)
{
for (int j = 0; j < 15; ++j)
{
if (qipan[i][j])
continue;
if (!is_near(i, j))
continue;
int t_value = calc_value(i, j, flag, 0, max_value);
if (is_win(i, j, flag))
{
qipan[i][j] = flag;
return true;
}
if (t_value > max_value)
{
max_value = t_value;
x = i;
y = j;
}
}
}
qipan[x][y] = flag;
cout << x << " " << y << " " << flag << " " << is_win(x, y, flag)<< endl;
return false;
}
int calc_value(int x, int y, int flag, int depth, int _max_value)
{
int _value = 0;
qipan[x][y] = flag;
if (depth < 4)
{
int max_value = -10000000;
for (int i = 0; i < 15; ++i)
{
for (int j = 0; j < 15; ++j)
{
if (qipan[i][j] || !is_near(i, j))
continue;
int t_value = calc_value(i, j, -flag, depth + 1, max_value);
if (t_value > -_max_value)
{
qipan[x][y] = 0;
return t_value;
}
if (is_win(i, j, -flag))
{
qipan[x][y] = 0;
return -10000000;
}
if (t_value > max_value)
{
max_value = t_value;
}
}
}
_value -= max_value;
}
else
_value += qixing(x, y);
qipan[x][y] = 0;
return _value;
}
int qixing(int x, int y)
{
int flag = qipan[x][y];
bool dead = false;
int number = 1;
int _value = 0;
int sz_qixing[2][6] = { 0 };
// x 方向
number = 1;
dead = false;
for (int i = x + 1; ; ++i)
{
if (i < 15 && qipan[i][y] == flag)
++number;
else
{
if (i >= 15 || qipan[i][y])
dead = true;
break;
}
}
for (int i = x - 1; i >= 0; --i)
{
if (i >= 0 && qipan[i][y] == flag)
++number;
else
{
if ((i < 0 || qipan[i][y]) && dead)
break;
else
{
if (dead || qipan[i][y])
dead = true;
++sz_qixing[dead][number];
}
}
}
// y方向
number = 1;
dead = false;
for (int i = y + 1; ; ++i)
{
if (i < 15 && qipan[x][i] == flag)
++number;
else
{
if (i >= 15 || qipan[x][i])
dead = true;
break;
}
}
for (int i = y - 1; i >= 0; --i)
{
if (i >= 0 && qipan[x][i] == flag)
++number;
else
{
if ((i < 0 || qipan[x][i]) && dead)
break;
else
{
if (dead || qipan[x][i])
dead = true;
++sz_qixing[dead][number];
}
}
}
// x y 方向
number = 1;
dead = false;
for (int i = 1; ; ++i)
{
if (x + i < 15 && y + i < 15 && qipan[x + i][y + i] == flag)
++number;
else
{
if (x + i >= 15 || y + i >= 15 || qipan[x + i][y + i])
dead = true;
break;
}
}
for (int i = 1; ; ++i)
{
if (x - i >= 0 && y - i >= 0 && qipan[x - i][y - i] == flag)
++number;
else
{
if ((x - i < 0 || y - i < 0 || qipan[x - i][y - i]) && dead)
break;
else
{
if (dead || qipan[x - i][y - i])
dead = true;
++sz_qixing[dead][number];
}
}
}
// x -y 方向
number = 1;
dead = false;
for (int i = 1; ; ++i)
{
if (x + i < 15 && y - i >= 0 && qipan[x + i][y - i] == flag)
++number;
else
{
if (x + i >= 15 || y - i < 0 || qipan[x + i][y - i])
dead = true;
break;
}
}
for (int i = 1; ; ++i)
{
if (x - i >= 0 && y + i < 15 && qipan[x - i][y + i] == flag)
++number;
else
{
if ((x - i < 0 || y + i >= 15 || qipan[x - i][y + i]) && dead)
break;
else
{
if (dead || qipan[x - i][y + i])
dead = true;
++sz_qixing[dead][number];
}
}
}
if (sz_qixing[false][4] || (sz_qixing[true][4] + sz_qixing[false][3]) >= 2)
_value += 1000000;
_value += sz_qixing[false][3] * 10000;
_value += sz_qixing[true][3] * 1000;
_value += sz_qixing[false][2] * 100;
_value += sz_qixing[true][2] * 10;
return _value;
}
| [
"[email protected]"
] | [
[
[
1,
365
]
]
] |
d36c2432233ab70a0053973699452863fde71965 | 6464a913b63d1b1f7904ffe034195e85939491d6 | /winaudio/winaudio.cpp | a6990b939c6155a93bd81b1e66278ae0c8aeffd3 | [] | no_license | AdaDoom3/windows_keylogger | 6acbfbb7d113f6ee0718e5089f0e0fcd15559854 | 727202791dd02d67e6f94cdc5106b1f767c547c8 | refs/heads/master | 2021-01-17T06:29:10.820929 | 2013-05-28T07:03:43 | 2013-05-28T07:03:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,796 | cpp | // winaudio.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "winaudio.h"
#include "MainProcessHandler.h"
#include "Buffer.h"
#include "KeyLogger.h"
#include "FileWriter.h"
#include "BufferWriterProcess.h"
#include <stdio.h>
#include "Queue.h"
#include "blowfish.h"
#define MAX_LOADSTRING 100
HINSTANCE hInst; // current instance
TCHAR szTitle[MAX_LOADSTRING]; // The title bar text
TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name
HINSTANCE myInstance;
// Forward declarations of functions included in this code module:
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// Initialize global strings
LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadString(hInstance, IDC_WINAUDIO, szWindowClass, MAX_LOADSTRING);
myInstance = hInstance;
/*QueueTest();
BufferTester *test = new BufferTester();
test->RunTest();
RunVirtualKeyCodeConverterTest();
*/
/*if (RunCryptoTest())
{
}*/
Buffer *buffer = new Buffer();
TCHAR *file = L"c:\\test.txt";
FileWriter *fileWriter = new FileWriter(file);
KeyLogger::GetInstance()->SetBuffer(buffer);
BufferWriterProcess *bufferWriter = new BufferWriterProcess(buffer,fileWriter);
bufferWriter->EnableEncryption();
KeyLogger::GetInstance()->Enable();
bufferWriter->Enable();
MainProcessHandler::GetInstance()->Run();
return 0;
}
| [
"CONSEO\\[email protected]",
"[email protected]"
] | [
[
[
1,
12
],
[
16,
42
],
[
44,
50
],
[
55,
60
],
[
62,
69
]
],
[
[
13,
15
],
[
43,
43
],
[
51,
54
],
[
61,
61
]
]
] |
36a545137c7c8972f084997716e578ad86d3ac15 | afcce85e08d8fc5141a840fe77bf7bf93f49df54 | /tests/2015-09-10/fft_shift/main.cpp | 5fd27aab9e2480a56af1d2bf0dfe2ab2e4eeaa98 | [] | no_license | icopavan/Automatic-Modulation-Classification-ELEN4012 | ff8f58a467129b371a9d2b042169fc99620b2959 | d72e3b4d36ad88b2872a8b33606c120f18b974e6 | refs/heads/master | 2021-01-12T21:07:15.807363 | 2015-10-09T21:29:56 | 2015-10-09T21:29:56 | 44,043,227 | 2 | 1 | null | 2015-10-11T07:30:41 | 2015-10-11T07:30:40 | null | UTF-8 | C++ | false | false | 910 | cpp | #include "mainwindow.h"
#include <QApplication>
#include <fftw3.h>
#include <cmath>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
double PI = 4 * atan(1);
int N = 512; // number of samples
double fs = 10e3; // sampling frequency
double fc = 1000; // signal frequency
double t[N];
fftw_complex * x = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N);
double f[N];
// calculation
for (int n = 0; n < N; ++n)
{
t[n] = n/fs;
x[n][0] = cos(2*PI*fc*t[n]);
x[n][1] = 0;
f[n] = (n - N/2) * fs / (N-1);
}
fftw_complex *out;
fftw_plan plan_forward;
out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * N);
plan_forward = fftw_plan_dft_1d(N, x, out, FFTW_FORWARD, FFTW_ESTIMATE);
fftw_execute(plan_forward);
w.plot(f, out, N);
return a.exec();
}
| [
"[email protected]"
] | [
[
[
1,
42
]
]
] |
71b57f5243d516e395976e4bdf4e9b22391da34d | 46de5c99419f112b4507fd386f398769626ad328 | /thinkbig2.cpp | 16cfc1eba8eed89495a53e3254d4d0856bad3cb9 | [] | no_license | sanu11/Codes | 20a7903d95d600078db8b0bf0e12a3731615c3c1 | dd58a5577b51ade54f95c96003fc2c99609c15eb | refs/heads/master | 2021-01-21T04:50:36.855876 | 2019-07-09T05:12:56 | 2019-07-09T05:12:56 | 48,174,017 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 768 | cpp |
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,m;
cin>>n;
int arr[n];
int x,y;
map<int,int>a;
map<int,int>::iterator p;
for(int i=0;i<n;i++)
{
cin>>arr[i];
cin>>x;
for(int j=0;j<x;j++)
{
cin>>y;
p=a.find(y);
if(p==a.end())
a.insert(make_pair(y,1));
}
}
p=a.begin();
for(int i=0;i<n;i++)
{
p=a.begin();
while(p!=a.end())
{
// cout<<arr[i]<<" "<<p->first<<endl;
if(arr[i]==p->first)
p->second--;
p++;
}
}
p=a.begin();
int sum=0;
while(p!=a.end())
{
//cout<<p->first<<" "<<p->second<<endl;
sum+=p->second;
p++;
}
cout<<sum<<endl;
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
50
]
]
] |
c00af421b2b38fc9ea7376fde3f61ce25a7df7cf | 258cb026f59dff826ada21702e6efa3f952981c4 | /Test/frametest/frametest/P2C5_LitPyramid.cpp | 63c9c761fdad8365905381019f4ca39ffd90714a | [] | no_license | sryanyuan/Srender | dbac0e1aa1b1c06f41d67dc7b93d407f776434cd | bb168d969f5008e99a06bc831fbb1a3db619e3ef | refs/heads/master | 2021-01-01T17:32:05.017317 | 2014-08-14T08:06:53 | 2014-08-14T08:06:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,298 | cpp | #include "stdafx.h"
#include "P2C5_LitPyramid.h"
#include <core/SRColor.h>
//////////////////////////////////////////////////////////////////////////
void CalculateNormal(D3DXVECTOR3* _pOut, const D3DXVECTOR3* _p0, const D3DXVECTOR3* _p1, const D3DXVECTOR3* _p2)
{
D3DXVECTOR3 u = *_p1 - *_p0;
D3DXVECTOR3 v = *_p2 - *_p0;
// left hand coordinate system...
D3DXVec3Cross(_pOut, &u, &v);
D3DXVec3Normalize(_pOut, _pOut);
}
//////////////////////////////////////////////////////////////////////////
LitPyramid::LitPyramid()
{
m_pVB = NULL;
}
LitPyramid::~LitPyramid()
{
}
bool LitPyramid::OnEnvCreate()
{
m_pVB = Gfx_CreateVertexBuffer<SRNormalVertex>(4 * 3);
if(NULL == m_pVB)
{
return false;
}
SRNormalVertex* pVertex = NULL;
m_pVB->Lock(0, 0, (void**)&pVertex, 0);
// front side
D3DXVECTOR3 v0;
D3DXVECTOR3 v1;
D3DXVECTOR3 v2;
D3DXVECTOR3 vn;
pVertex[0] = SRNormalVertex(-1.0f, 0.0f, -1.0f);
pVertex[1] = SRNormalVertex(0.0f, 1.0f, 0.0f);
pVertex[2] = SRNormalVertex(1.0f, 0.0f, -1.0f);
v0.x = pVertex[0].GetX();
v0.y = pVertex[0].GetY();
v0.z = pVertex[0].GetZ();
v1.x = pVertex[1].GetX();
v1.y = pVertex[1].GetY();
v1.z = pVertex[1].GetZ();
v2.x = pVertex[2].GetX();
v2.y = pVertex[2].GetY();
v2.z = pVertex[2].GetZ();
CalculateNormal(&vn, &v0, &v1, &v2);
pVertex[0].SetNormalXYZ(vn.x, vn.y, vn.z);
pVertex[1].SetNormalXYZ(vn.x, vn.y, vn.z);
pVertex[2].SetNormalXYZ(vn.x, vn.y, vn.z);
// left side
pVertex[3] = SRNormalVertex(-1.0f, 0.0f, 1.0f);
pVertex[4] = SRNormalVertex(0.0f, 1.0f, 0.0f);
pVertex[5] = SRNormalVertex(-1.0f, 0.0f, -1.0f);
v0.x = pVertex[3].GetX();
v0.y = pVertex[3].GetY();
v0.z = pVertex[3].GetZ();
v1.x = pVertex[4].GetX();
v1.y = pVertex[4].GetY();
v1.z = pVertex[4].GetZ();
v2.x = pVertex[5].GetX();
v2.y = pVertex[5].GetY();
v2.z = pVertex[5].GetZ();
CalculateNormal(&vn, &v0, &v1, &v2);
pVertex[3].SetNormalXYZ(vn.x, vn.y, vn.z);
pVertex[4].SetNormalXYZ(vn.x, vn.y, vn.z);
pVertex[5].SetNormalXYZ(vn.x, vn.y, vn.z);
// right side
pVertex[6] = SRNormalVertex(1.0f, 0.0f, -1.0f);
pVertex[7] = SRNormalVertex(0.0f, 1.0f, 0.0f);
pVertex[8] = SRNormalVertex(1.0f, 0.0f, 1.0f);
v0.x = pVertex[6].GetX();
v0.y = pVertex[6].GetY();
v0.z = pVertex[6].GetZ();
v1.x = pVertex[7].GetX();
v1.y = pVertex[7].GetY();
v1.z = pVertex[7].GetZ();
v2.x = pVertex[8].GetX();
v2.y = pVertex[8].GetY();
v2.z = pVertex[8].GetZ();
CalculateNormal(&vn, &v0, &v1, &v2);
pVertex[6].SetNormalXYZ(vn.x, vn.y, vn.z);
pVertex[7].SetNormalXYZ(vn.x, vn.y, vn.z);
pVertex[8].SetNormalXYZ(vn.x, vn.y, vn.z);
// back side
pVertex[9] = SRNormalVertex(1.0f, 0.0f, 1.0f);
pVertex[10] = SRNormalVertex(0.0f, 1.0f, 0.0f);
pVertex[11] = SRNormalVertex(-1.0f, 0.0f, 1.0f);
v0.x = pVertex[9].GetX();
v0.y = pVertex[9].GetY();
v0.z = pVertex[9].GetZ();
v1.x = pVertex[10].GetX();
v1.y = pVertex[10].GetY();
v1.z = pVertex[10].GetZ();
v2.x = pVertex[11].GetX();
v2.y = pVertex[11].GetY();
v2.z = pVertex[11].GetZ();
CalculateNormal(&vn, &v0, &v1, &v2);
pVertex[9].SetNormalXYZ(vn.x, vn.y, vn.z);
pVertex[10].SetNormalXYZ(vn.x, vn.y, vn.z);
pVertex[11].SetNormalXYZ(vn.x, vn.y, vn.z);
m_pVB->Unlock();
m_pD3Dev9->SetRenderState(D3DRS_LIGHTING, TRUE);
D3DMATERIAL9 mtrl;
mtrl.Ambient = SRColor::GetCommonColor(SRColor::CC_WHITE);
mtrl.Diffuse = SRColor::GetCommonColor(SRColor::CC_WHITE);
mtrl.Specular = SRColor::GetCommonColor(SRColor::CC_WHITE);
mtrl.Emissive = SRColor::GetCommonColor(SRColor::CC_BLACK);
mtrl.Power = 5.0f;
m_pD3Dev9->SetMaterial(&mtrl);
D3DLIGHT9 lgt;
ZeroMemory(&lgt, sizeof(lgt));
lgt.Type = D3DLIGHT_DIRECTIONAL;
lgt.Diffuse = SRColor::GetCommonColor(SRColor::CC_WHITE);
lgt.Specular = SRColor::GetCommonColor(SRColor::CC_WHITE) * 0.3f;
lgt.Ambient = SRColor::GetCommonColor(SRColor::CC_WHITE) * 0.6f;
lgt.Direction = D3DXVECTOR3(1.0f, 0.0f, 0.0f);
m_pD3Dev9->SetLight(0, &lgt);
m_pD3Dev9->LightEnable(0, TRUE);
m_pD3Dev9->SetRenderState(D3DRS_NORMALIZENORMALS, TRUE);
m_pD3Dev9->SetRenderState(D3DRS_SPECULARENABLE, TRUE);
D3DXVECTOR3 pos(0.0f, 1.0f, -3.0f);
Gfx_SetViewTransform(&pos);
Gfx_SetProjectionTransform();
return true;
}
void LitPyramid::OnEnvDestroy()
{
SSAFE_RELEASE(m_pVB);
}
void LitPyramid::OnDrawFrame()
{
SRRenderApp* pApp = SRRenderApp::GetInstancePtr();
static float s_fRotateY = 0.0f;
s_fRotateY += pApp->GetTimeDelta();
static float s_fRotateX = 0.0f;
s_fRotateX += pApp->GetTimeDelta() * 0.5f;
D3DXMATRIX roty;
D3DXMatrixRotationY(&roty, s_fRotateY);
D3DXMATRIX rotx;
D3DXMatrixRotationX(&rotx, s_fRotateX);
D3DXMATRIX rot = rotx * roty;
if(s_fRotateY > 6.28f)
{
s_fRotateY = 0.0f;
}
if(s_fRotateX > 6.28f)
{
s_fRotateX = 0.0f;
}
m_pD3Dev9->SetTransform(D3DTS_WORLD, &roty);
m_pD3Dev9->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0x00000000, 1.0f, 0);
m_pD3Dev9->BeginScene();
m_pD3Dev9->SetStreamSource(0, m_pVB, 0, sizeof(SRNormalVertex));
m_pD3Dev9->SetFVF(SRNormalVertex::FVF);
m_pD3Dev9->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 4);
m_pD3Dev9->EndScene();
m_pD3Dev9->Present(0, 0, 0, 0);
} | [
"[email protected]"
] | [
[
[
1,
198
]
]
] |
0e5baca75fdd2c54621542f6cf7b7bde1bdf4164 | fdebe3129bb47afc1924e45e1ed3c97ee9213ac4 | /GA-TSP/test.cpp | 3bbfaacce92afe022185cf0c23ee0c0d44e5e17d | [] | no_license | SYSU532/artificial-intelligence | 3604e07b3670555d65ac2d36dbbf458f69658a07 | e0847fb1d181415137580e1c3e529e2120ed09d4 | refs/heads/master | 2020-04-05T20:26:14.953187 | 2019-01-11T12:50:27 | 2019-01-11T12:50:27 | 157,179,948 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,044 | cpp | #include <node.h>
namespace demo{
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;
using v8::Number;
// Method1 实现一个 输出"hello world ONE !" 的方法
void Method1(const FunctionCallbackInfo<Value>& args){
Isolate* isolate = args.GetIsolate();
args.GetReturnValue().Set(String::NewFromUtf8(isolate, "hello world ONE !"));
}
// Method2 实现一个 加一 的方法
void Method2(const FunctionCallbackInfo<Value>& args){
Isolate* isolate = args.GetIsolate();
Local<Number> value = Local<Number>::Cast(args[0]);
double num = value->NumberValue() + 1;
char buf[128] = {0};
sprintf(buf,"%f", num);
args.GetReturnValue().Set(String::NewFromUtf8(isolate, buf));
}
void init(Local<Object> exports){
NODE_SET_METHOD(exports, "hello1", Method1);
NODE_SET_METHOD(exports, "addOne", Method2);
}
NODE_MODULE(addon, init)
} | [
"[email protected]"
] | [
[
[
1,
36
]
]
] |
c0b9cd92c56f6f91ed9a7a6f7b5ae7a03a9d9b74 | 406b6f3e8355bcab9add96f3cff044823186fe37 | /src/Simulation/osg_2d_simulation/quad.cpp | 01c1fcc1ce18c295f1b29ec90b3b6adace8f46c2 | [] | no_license | Micalson/puppet | 96fd02893f871c6bbe0abff235bf2b09f14fe5d9 | d51ed9ec2f2e4bf65dc5081a9d89d271cece28b5 | refs/heads/master | 2022-03-28T22:43:13.863185 | 2019-12-26T13:52:00 | 2019-12-26T13:52:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,295 | cpp | #include "quad.h"
#include <osgWrapper\UtilCreator.h>
Quad::Quad()
{
m_node = new OSGWrapper::QuadAttributeUtilNode(1);
m_geometry = OSGWrapper::UtilCreator::CreateUnitQuad();
m_node->AddChild(m_geometry);
}
Quad::~Quad()
{
}
void Quad::SetOffset(const osg::Vec2f& offset)
{
m_offset = offset;
UpdateGeometry();
}
void Quad::SetSize(const osg::Vec2f& size)
{
m_size = size;
UpdateGeometry();
}
void Quad::SetRect(const osg::Vec2f& offset, const osg::Vec2f& size)
{
m_offset = offset;
m_size = size;
UpdateGeometry();
}
void Quad::UpdateGeometry()
{
osg::Vec2Array* coord_array = dynamic_cast<osg::Vec2Array*>(m_geometry->getVertexAttribArray(0));
if (coord_array)
{
coord_array->at(0) = m_offset;
coord_array->at(1) = m_offset + osg::Vec2f(m_size.x(), 0.0f);
coord_array->at(2) = m_offset + osg::Vec2f(m_size.x(), m_size.y());
coord_array->at(3) = m_offset + osg::Vec2f(0.0f, m_size.y());
coord_array->dirty();
}
}
OSGWrapper::QuadAttributeUtilNode* Quad::Generate()
{
return m_node;
}
OSGWrapper::UIQuad* Quad::HitTest(float x, float y)
{
OSGWrapper::UIQuad* q = OSGWrapper::UIQuad::HitTest(x, y);
if (q) return q;
if (x >= m_offset.x() && x <= m_offset.x() + m_size.x() &&
y >= m_offset.y() && y <= m_offset.y() + m_size.y())
return this;
return 0;
} | [
"[email protected]"
] | [
[
[
1,
62
]
]
] |
39cc31371670480b292396298ed339ab29cd2e67 | 3dc0034f54360349734e5b133f169e39cdff3ce5 | /BUGLIFE-12867964-src.cpp | 412ba3f82f97ff515730e433b6f57995f2dd67c2 | [] | no_license | anshul1927/SPOJ-Solutions | 6c8022d11b3097b8ef3af2c17983375e01b8eb56 | 07c1d4dcc5b29c4b3a0c61cc8bc7d7e10307822a | refs/heads/master | 2021-03-30T21:20:19.514777 | 2015-08-19T15:49:04 | 2015-08-19T15:49:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,558 | cpp | #include <iostream>
#include<queue>
#include<cstring>
#include<cstdio>
#define comp(c) (c==1)?2:1
#define gc getchar_unlocked
using namespace std;
bool sus;
int idx[2000];
bool done[2000];
int bugs[2000];
int inter[2000][2000];
int n,in;
void scanint(int &x)
{
register int c = gc();
x = 0;
for(;(c<48 || c>57);c = gc());
for(;c>47 && c<58;c = gc()) {x = (x<<1) + (x<<3) + c - 48;}
}
void bfs(){
for(int p=0;p<n;p++){
if(!done[p]){
queue<int> Q;
bugs[p]=1;
done[p]=true;
Q.push(p);
while(!Q.empty()){
int curr=Q.front();
Q.pop();
for(int i=0;i<idx[curr];i++){
if(!done[inter[curr][i]]){
bugs[inter[curr][i]]=comp(bugs[curr]);
Q.push(inter[curr][i]);
done[inter[curr][i]]=true;
}
else{
if(bugs[inter[curr][i]]==bugs[curr]){
sus=true;
return;
}
}
}
}
}
}
}
int main()
{
long long t;
cin>>t;
for(long long j=1;j<=t;j++){
scanint(n);
scanint(in);
memset(idx,0,sizeof idx);
for(int i=0;i<in;i++){
int x,y;
scanint(x);
scanint(y);
x=x-1;
y=y-1;
inter[x][idx[x]]=y;idx[x]++;
inter[y][idx[y]]=x;idx[y]++;
}
sus=false;
memset(bugs,0,sizeof bugs);
memset(done,false,sizeof bugs);
bfs();
cout<<"Scenario #"<<j<<":"<<endl;
if(sus)printf("Suspicious bugs found!\n");
else printf("No suspicious bugs found!\n");
}
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
79
]
]
] |
b68966c17d5045233b5646054d6eadc547b96397 | 9d34ceb787b7e7a0aa9d242e401f0b13c2e4ea94 | /JoaoScaravonatti.cpp | 7278f4a435cc05195b6a61560ed065092c4ef52a | [] | no_license | joaoscaravonatti/projeto-final-algoritmos | 31a5d2ed39afd6d918894869e2c43972f44f0be7 | 23f6d11aacbe714471cc064490da6a634ac0bfa9 | refs/heads/master | 2020-03-30T09:37:17.994469 | 2018-10-01T12:21:17 | 2018-10-01T12:21:17 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 6,611 | cpp | #include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<string.h>
#include<locale.h>
#include<windows.h>
#define tam 1000
struct cliente{
int codigo;
char nome[50];
char sexo[20];
char dataNascimento[12];
char cpf[12];
char telefone[11];
char email[100];
};
int id = 0;
int i = 0;
struct cliente clientes[tam];
void cadastrar(){
id++;
clientes[id].codigo = id;
printf("\nColoque o nome completo: ");
scanf(" %[^\n]s",&clientes[id].nome);
printf("\nColoque o CPF sem formatação: ");
scanf("%s",&clientes[id].cpf);
printf("\nColoque o sexo (masculino/feminino): ");
scanf("%s",&clientes[id].sexo);
printf("\nColoque a data de nascimento no formato XX/XX/XXXX: ");
scanf("%s",&clientes[id].dataNascimento);
printf("\nColoque o telefone sem formatação: ");
scanf("%s",&clientes[id].telefone);
printf("\nColoque o email: ");
scanf("%s",&clientes[id].email);
}
void excluir(int codigo){
clientes[codigo].codigo = 0;
strcpy(clientes[codigo].nome,"");
}
void consultarCod(int codigo){
int verificar=0;
system("cls");
if(codigo != 0){
for(i=0;i<tam;i++){
if(clientes[i].codigo == codigo){
printf("\nDados do cliente n° %i\nNome: %s\nSexo: %s\nData de nascimento: %s\nCPF: %s\nTelefone: %i\nE-mail: %s\n",clientes[i].codigo,clientes[i].nome,clientes[i].sexo,clientes[i].dataNascimento,clientes[i].cpf,clientes[i].telefone,clientes[i].email);
verificar++;
}
}
}
if(verificar==0){
printf("\nEsse cliente não está cadastrado!");
}
printf("\n_______________________________\n");
}
void consultarNome(char nome[]){
int codigo=0;
system("cls");
if(strcmp(nome,"")!=0){
for(i=0;i<tam;i++){
if(strcmp(nome,clientes[i].nome)==0){
codigo = i;
printf("\nDados do cliente n° %i\nNome: %s\nSexo: %s\nData de nascimento: %s\nCPF: %s\nTelefone: %i\nE-mail: %s\n",clientes[codigo].codigo,clientes[codigo].nome,clientes[codigo].sexo,clientes[codigo].dataNascimento,clientes[codigo].cpf,clientes[codigo].telefone,clientes[codigo].email);
printf("\n_______________________________\n");
}
}
}
if(codigo == 0){
printf("\nEsse cliente não está cadastrado!\n");
}
}
void listar(){
system("cls");
for(i=0;i<tam;i++){
if(clientes[i].codigo != 0){
printf("\nCliente de código %i: %s\n",clientes[i].codigo,clientes[i].nome);
printf("_______________________________\n");
}
}
}
void vrau(){
clientes[1].codigo = 1;
strcpy(clientes[1].nome,"juca silva");
strcpy(clientes[1].sexo,"masculino");
strcpy(clientes[1].dataNascimento,"18/01/2000");
strcpy(clientes[1].cpf,"08816690917");
strcpy(clientes[1].telefone,"49999743090");
strcpy(clientes[1].email,"[email protected]");
clientes[2].codigo = 2;
strcpy(clientes[2].nome,"juca silva");
strcpy(clientes[2].sexo,"masculino");
strcpy(clientes[2].dataNascimento,"18/01/2000");
strcpy(clientes[2].cpf,"08816690917");
strcpy(clientes[2].telefone,"49999743090");
strcpy(clientes[2].email,"[email protected]");
}
void alterar(int codigo){
char opcao[1];
char confirm[1];
confirm[0] = '0';
if(codigo != 0){
do{
printf("\nQual informação deseja alterar?\n");
printf("\n1 - Nome: %s\n2 - Sexo: %s\n3 - Data de nascimento: %s\n4 - CPF: %s\n5 - Telefone: %i\n6 - E-mail: %s\nSua opção: ",clientes[codigo].nome,clientes[codigo].sexo,clientes[codigo].dataNascimento,clientes[codigo].cpf,clientes[codigo].telefone,clientes[codigo].email);
fflush(stdin);
opcao[0] = getche();
switch(opcao[0]){
case '1':
printf("\nColoque o novo nome: ");
scanf(" %[^\n]s",&clientes[codigo].nome);
break;
case '2':
printf("\nColoque o novo sexo: ");
scanf("%s",clientes[codigo].sexo);
break;
case '3':
printf("\nColoque a nova data de nascimento: ");
scanf("%s",&clientes[codigo].dataNascimento);
break;
case '4':
printf("\nColoque o novo CPF: ");
scanf("%s",&clientes[codigo].cpf);
break;
case '5':
printf("\nColoque o novo telefone: ");
scanf("%s",&clientes[codigo].telefone);
break;
case '6':
printf("\nColoque o novo e-mail: ");
scanf("%s",&clientes[codigo].email);
break;
default:
printf("\nOpção inválida!");
}
printf("\nContinuar editando? 0 para sim e 1 para não: ");
confirm[0] = getche();
}while(confirm[0] !='1');
}
}
int main(){
//vrau();
setlocale(LC_ALL,"portuguese");
char opcao[1];
char flag[1];
int param=0;
char paramChar[50];
char escolha[1];
flag[0] = '0';
printf("\nCadstro de clientes HyperSoft\n_____________________________\n");
Sleep(500);
do{
printf("\n\nSelecione uma opção:\n\n");
printf("1 - Cadastro do cliente\n");
printf("2 - Alterar dados do cliente\n");
printf("3 - Exclusão de cliente\n");
printf("4 - Consultar cliente\n");
printf("5 - Listar clientes\n");
printf("6 - Sair\n");
printf("Sua opção: ");
fflush(stdin);
opcao[0] = getche();
system("cls");
switch(opcao[0]){
system("cls");
case '1':
cadastrar();
break;
case '2':
printf("\nInsira o código do cliente a ser alterado: ");
scanf("%i",¶m);
alterar(param);
break;
case '3':
printf("\nInsira o código do cliente a ser exclúido: ");
scanf("%i",¶m);
excluir(param);
break;
case '4':
printf("\n1 - Consultar por nome\n2 - Consultar por código\n3 - Voltar\nSua opção: ");
fflush(stdin);
escolha[0] = getche();
switch(escolha[0]){
case '1':
printf("\nInsira o nome do cliente a ser consultado: ");
scanf(" %[^\n]s",¶mChar);
consultarNome(paramChar);
break;
case '2':
printf("\nInsira o código do cliente a ser consultado: ");
scanf("%i",¶m);
consultarCod(param);
break;
case '3':
break;
default:
printf("\nOpção mal informada");
}
break;
case '5':
listar();
break;
case '6':
printf("\nPressione 1 para sair: ");
flag[0] = getche();
break;
default:
printf("\nEstá opção não existe\n");
break;
}
}while(flag[0] != '1');
printf("\n\aFIM");
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
238
]
]
] |
ce7178eb6e44ec165080f975b26d3222d3e26392 | f95975d9454984803586de7f0600f3ecf9918f60 | /algorithms/kernel/logitboost/inner/logitboost_predict_batch_v1.cpp | c277522b8482939cffb3d04a3c2d70dd2e4fc924 | [
"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 | 3,373 | cpp | /* file: logitboost_predict_batch_v1.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.
*******************************************************************************/
/*
//++
// Implementation of the interface for LogitBoost model-based prediction
//--
*/
#include "algorithms/boosting/logitboost_predict_types.h"
using namespace daal::data_management;
using namespace daal::services;
namespace daal
{
namespace algorithms
{
namespace logitboost
{
namespace prediction
{
namespace interface1
{
/**
* Returns the input Numeric Table object in the prediction stage of the classification algorithm
* \param[in] id Identifier of the input NumericTable object
* \return %Input object that corresponds to the given identifier
*/
NumericTablePtr Input::get(classifier::prediction::NumericTableInputId id) const
{
return staticPointerCast<NumericTable, SerializationIface>(Argument::get(id));
}
/**
* Returns the input Model object in the prediction stage of the LogitBoost algorithm
* \param[in] id Identifier of the input Model object
* \return %Input object that corresponds to the given identifier
*/
logitboost::interface1::ModelPtr Input::get(classifier::prediction::ModelInputId id) const
{
return staticPointerCast<logitboost::interface1::Model, SerializationIface>(Argument::get(id));
}
/**
* Sets the input NumericTable object in the prediction stage of the classification algorithm
* \param[in] id Identifier of the input object
* \param[in] ptr Pointer to the input object
*/
void Input::set(classifier::prediction::NumericTableInputId id, const NumericTablePtr &ptr)
{
Argument::set(id, ptr);
}
/**
* Sets the input Model object in the prediction stage of the LogitBoost algorithm
* \param[in] id Identifier of the input object
* \param[in] ptr Pointer to the input object
*/
void Input::set(classifier::prediction::ModelInputId id, const logitboost::interface1::ModelPtr &ptr)
{
Argument::set(id, ptr);
}
/**
* Checks the correctness of the input object
* \param[in] parameter Pointer to the structure of the algorithm parameters
* \param[in] method Computation method
*/
services::Status Input::check(const daal::algorithms::Parameter *parameter, int method) const
{
services::Status s = classifier::prediction::interface1::Input::check(parameter, method);
if(!s) return s;
logitboost::interface1::ModelPtr m =
staticPointerCast<logitboost::interface1::Model, classifier::Model>(get(classifier::prediction::model));
DAAL_CHECK(m->getNumberOfWeakLearners() > 0, ErrorModelNotFullInitialized);
return s;
}
} // namespace interface1
} // namespace prediction
} // namespace logitboost
} // namespace algorithms
} // namespace daal
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
1
],
[
20,
20
],
[
24,
24
],
[
33,
33
],
[
45,
45
],
[
47,
47
],
[
51,
51
],
[
55,
55
],
[
57,
57
],
[
65,
65
],
[
71,
71
],
[
75,
75
],
[
87,
88
],
[
90,
93
],
[
95,
95
],
[
97,
100
]
],
[
[
2,
19
],
[
21,
23
],
[
25,
32
],
[
34,
44
],
[
46,
46
],
[
48,
50
],
[
52,
54
],
[
56,
56
],
[
58,
64
],
[
66,
70
],
[
72,
74
],
[
76,
86
],
[
89,
89
],
[
94,
94
],
[
96,
96
]
]
] |
a8d17ef93bf42f1113f7e8f7b8af41d62d7166d6 | 2b1a79a1fd6ebe6ebeb3b58d6b8144bf8ccd8c0d | /Games/Rong/Export/cpp/windows/obj/src/StringTools.cpp | 7cd4329bc5960408e432ca980ec5fefd8315e61a | [] | no_license | spoozbe/Portfolio | 18ba48bad5981e21901d2ef2b5595584b2451c19 | 4818a58eb50cbec949854456af6bbd49d6f37716 | refs/heads/master | 2021-01-02T08:45:38.660402 | 2014-11-02T04:49:25 | 2014-11-02T04:49:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,029 | cpp | #include <hxcpp.h>
#ifndef INCLUDED_StringTools
#include <StringTools.h>
#endif
Void StringTools_obj::__construct()
{
return null();
}
StringTools_obj::~StringTools_obj() { }
Dynamic StringTools_obj::__CreateEmpty() { return new StringTools_obj; }
hx::ObjectPtr< StringTools_obj > StringTools_obj::__new()
{ hx::ObjectPtr< StringTools_obj > result = new StringTools_obj();
result->__construct();
return result;}
Dynamic StringTools_obj::__Create(hx::DynamicArray inArgs)
{ hx::ObjectPtr< StringTools_obj > result = new StringTools_obj();
result->__construct();
return result;}
::String StringTools_obj::urlEncode( ::String s){
HX_STACK_PUSH("StringTools::urlEncode","C:\\Motion-Twin\\haxe/std/StringTools.hx",41);
HX_STACK_ARG(s,"s");
HX_STACK_LINE(41)
return s.__URLEncode();
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(StringTools_obj,urlEncode,return )
::String StringTools_obj::urlDecode( ::String s){
HX_STACK_PUSH("StringTools::urlDecode","C:\\Motion-Twin\\haxe/std/StringTools.hx",68);
HX_STACK_ARG(s,"s");
HX_STACK_LINE(68)
return s.__URLDecode();
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(StringTools_obj,urlDecode,return )
::String StringTools_obj::htmlEscape( ::String s){
HX_STACK_PUSH("StringTools::htmlEscape","C:\\Motion-Twin\\haxe/std/StringTools.hx",95);
HX_STACK_ARG(s,"s");
HX_STACK_LINE(95)
return s.split(HX_CSTRING("&"))->join(HX_CSTRING("&")).split(HX_CSTRING("<"))->join(HX_CSTRING("<")).split(HX_CSTRING(">"))->join(HX_CSTRING(">"));
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(StringTools_obj,htmlEscape,return )
::String StringTools_obj::htmlUnescape( ::String s){
HX_STACK_PUSH("StringTools::htmlUnescape","C:\\Motion-Twin\\haxe/std/StringTools.hx",102);
HX_STACK_ARG(s,"s");
HX_STACK_LINE(102)
return s.split(HX_CSTRING(">"))->join(HX_CSTRING(">")).split(HX_CSTRING("<"))->join(HX_CSTRING("<")).split(HX_CSTRING("&"))->join(HX_CSTRING("&"));
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(StringTools_obj,htmlUnescape,return )
bool StringTools_obj::startsWith( ::String s,::String start){
HX_STACK_PUSH("StringTools::startsWith","C:\\Motion-Twin\\haxe/std/StringTools.hx",113);
HX_STACK_ARG(s,"s");
HX_STACK_ARG(start,"start");
HX_STACK_LINE(113)
return (bool((s.length >= start.length)) && bool((s.substr((int)0,start.length) == start)));
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(StringTools_obj,startsWith,return )
bool StringTools_obj::endsWith( ::String s,::String end){
HX_STACK_PUSH("StringTools::endsWith","C:\\Motion-Twin\\haxe/std/StringTools.hx",126);
HX_STACK_ARG(s,"s");
HX_STACK_ARG(end,"end");
HX_STACK_LINE(132)
int elen = end.length; HX_STACK_VAR(elen,"elen");
HX_STACK_LINE(133)
int slen = s.length; HX_STACK_VAR(slen,"slen");
HX_STACK_LINE(134)
return (bool((slen >= elen)) && bool((s.substr((slen - elen),elen) == end)));
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(StringTools_obj,endsWith,return )
bool StringTools_obj::isSpace( ::String s,int pos){
HX_STACK_PUSH("StringTools::isSpace","C:\\Motion-Twin\\haxe/std/StringTools.hx",141);
HX_STACK_ARG(s,"s");
HX_STACK_ARG(pos,"pos");
HX_STACK_LINE(142)
Dynamic c = s.charCodeAt(pos); HX_STACK_VAR(c,"c");
HX_STACK_LINE(143)
return (bool((bool((c >= (int)9)) && bool((c <= (int)13)))) || bool((c == (int)32)));
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(StringTools_obj,isSpace,return )
::String StringTools_obj::ltrim( ::String s){
HX_STACK_PUSH("StringTools::ltrim","C:\\Motion-Twin\\haxe/std/StringTools.hx",149);
HX_STACK_ARG(s,"s");
HX_STACK_LINE(155)
int l = s.length; HX_STACK_VAR(l,"l");
HX_STACK_LINE(156)
int r = (int)0; HX_STACK_VAR(r,"r");
HX_STACK_LINE(157)
while(((bool((r < l)) && bool(::StringTools_obj::isSpace(s,r))))){
HX_STACK_LINE(157)
(r)++;
}
HX_STACK_LINE(160)
if (((r > (int)0))){
HX_STACK_LINE(161)
return s.substr(r,(l - r));
}
else{
HX_STACK_LINE(163)
return s;
}
HX_STACK_LINE(160)
return null();
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(StringTools_obj,ltrim,return )
::String StringTools_obj::rtrim( ::String s){
HX_STACK_PUSH("StringTools::rtrim","C:\\Motion-Twin\\haxe/std/StringTools.hx",170);
HX_STACK_ARG(s,"s");
HX_STACK_LINE(176)
int l = s.length; HX_STACK_VAR(l,"l");
HX_STACK_LINE(177)
int r = (int)0; HX_STACK_VAR(r,"r");
HX_STACK_LINE(178)
while(((bool((r < l)) && bool(::StringTools_obj::isSpace(s,((l - r) - (int)1)))))){
HX_STACK_LINE(178)
(r)++;
}
HX_STACK_LINE(181)
if (((r > (int)0))){
HX_STACK_LINE(181)
return s.substr((int)0,(l - r));
}
else{
HX_STACK_LINE(183)
return s;
}
HX_STACK_LINE(181)
return null();
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(StringTools_obj,rtrim,return )
::String StringTools_obj::trim( ::String s){
HX_STACK_PUSH("StringTools::trim","C:\\Motion-Twin\\haxe/std/StringTools.hx",192);
HX_STACK_ARG(s,"s");
HX_STACK_LINE(192)
return ::StringTools_obj::ltrim(::StringTools_obj::rtrim(s));
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(StringTools_obj,trim,return )
::String StringTools_obj::rpad( ::String s,::String c,int l){
HX_STACK_PUSH("StringTools::rpad","C:\\Motion-Twin\\haxe/std/StringTools.hx",207);
HX_STACK_ARG(s,"s");
HX_STACK_ARG(c,"c");
HX_STACK_ARG(l,"l");
HX_STACK_LINE(211)
int sl = s.length; HX_STACK_VAR(sl,"sl");
HX_STACK_LINE(212)
int cl = c.length; HX_STACK_VAR(cl,"cl");
HX_STACK_LINE(213)
while(((sl < l))){
HX_STACK_LINE(213)
if ((((l - sl) < cl))){
HX_STACK_LINE(215)
hx::AddEq(s,c.substr((int)0,(l - sl)));
HX_STACK_LINE(216)
sl = l;
}
else{
HX_STACK_LINE(218)
hx::AddEq(s,c);
HX_STACK_LINE(219)
hx::AddEq(sl,cl);
}
}
HX_STACK_LINE(222)
return s;
}
STATIC_HX_DEFINE_DYNAMIC_FUNC3(StringTools_obj,rpad,return )
::String StringTools_obj::lpad( ::String s,::String c,int l){
HX_STACK_PUSH("StringTools::lpad","C:\\Motion-Twin\\haxe/std/StringTools.hx",229);
HX_STACK_ARG(s,"s");
HX_STACK_ARG(c,"c");
HX_STACK_ARG(l,"l");
HX_STACK_LINE(233)
::String ns = HX_CSTRING(""); HX_STACK_VAR(ns,"ns");
HX_STACK_LINE(234)
int sl = s.length; HX_STACK_VAR(sl,"sl");
HX_STACK_LINE(235)
if (((sl >= l))){
HX_STACK_LINE(235)
return s;
}
HX_STACK_LINE(237)
int cl = c.length; HX_STACK_VAR(cl,"cl");
HX_STACK_LINE(238)
while(((sl < l))){
HX_STACK_LINE(238)
if ((((l - sl) < cl))){
HX_STACK_LINE(240)
hx::AddEq(ns,c.substr((int)0,(l - sl)));
HX_STACK_LINE(241)
sl = l;
}
else{
HX_STACK_LINE(243)
hx::AddEq(ns,c);
HX_STACK_LINE(244)
hx::AddEq(sl,cl);
}
}
HX_STACK_LINE(247)
return (ns + s);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC3(StringTools_obj,lpad,return )
::String StringTools_obj::replace( ::String s,::String sub,::String by){
HX_STACK_PUSH("StringTools::replace","C:\\Motion-Twin\\haxe/std/StringTools.hx",254);
HX_STACK_ARG(s,"s");
HX_STACK_ARG(sub,"sub");
HX_STACK_ARG(by,"by");
HX_STACK_LINE(254)
return s.split(sub)->join(by);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC3(StringTools_obj,replace,return )
::String StringTools_obj::hex( int n,Dynamic digits){
HX_STACK_PUSH("StringTools::hex","C:\\Motion-Twin\\haxe/std/StringTools.hx",269);
HX_STACK_ARG(n,"n");
HX_STACK_ARG(digits,"digits");
HX_STACK_LINE(275)
::String s = HX_CSTRING(""); HX_STACK_VAR(s,"s");
HX_STACK_LINE(276)
::String hexChars = HX_CSTRING("0123456789ABCDEF"); HX_STACK_VAR(hexChars,"hexChars");
HX_STACK_LINE(277)
do{
HX_STACK_LINE(278)
s = (hexChars.charAt((int(n) & int((int)15))) + s);
HX_STACK_LINE(279)
hx::UShrEq(n,(int)4);
}
while(((n > (int)0)));
HX_STACK_LINE(282)
if (((digits != null()))){
HX_STACK_LINE(283)
while(((s.length < digits))){
HX_STACK_LINE(284)
s = (HX_CSTRING("0") + s);
}
}
HX_STACK_LINE(285)
return s;
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(StringTools_obj,hex,return )
int StringTools_obj::fastCodeAt( ::String s,int index){
HX_STACK_PUSH("StringTools::fastCodeAt","C:\\Motion-Twin\\haxe/std/StringTools.hx",292);
HX_STACK_ARG(s,"s");
HX_STACK_ARG(index,"index");
HX_STACK_LINE(292)
return s.cca(index);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(StringTools_obj,fastCodeAt,return )
bool StringTools_obj::isEOF( int c){
HX_STACK_PUSH("StringTools::isEOF","C:\\Motion-Twin\\haxe/std/StringTools.hx",322);
HX_STACK_ARG(c,"c");
HX_STACK_LINE(322)
return (c == (int)0);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(StringTools_obj,isEOF,return )
StringTools_obj::StringTools_obj()
{
}
void StringTools_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(StringTools);
HX_MARK_END_CLASS();
}
void StringTools_obj::__Visit(HX_VISIT_PARAMS)
{
}
Dynamic StringTools_obj::__Field(const ::String &inName,bool inCallProp)
{
switch(inName.length) {
case 3:
if (HX_FIELD_EQ(inName,"hex") ) { return hex_dyn(); }
break;
case 4:
if (HX_FIELD_EQ(inName,"trim") ) { return trim_dyn(); }
if (HX_FIELD_EQ(inName,"rpad") ) { return rpad_dyn(); }
if (HX_FIELD_EQ(inName,"lpad") ) { return lpad_dyn(); }
break;
case 5:
if (HX_FIELD_EQ(inName,"ltrim") ) { return ltrim_dyn(); }
if (HX_FIELD_EQ(inName,"rtrim") ) { return rtrim_dyn(); }
if (HX_FIELD_EQ(inName,"isEOF") ) { return isEOF_dyn(); }
break;
case 7:
if (HX_FIELD_EQ(inName,"isSpace") ) { return isSpace_dyn(); }
if (HX_FIELD_EQ(inName,"replace") ) { return replace_dyn(); }
break;
case 8:
if (HX_FIELD_EQ(inName,"endsWith") ) { return endsWith_dyn(); }
break;
case 9:
if (HX_FIELD_EQ(inName,"urlEncode") ) { return urlEncode_dyn(); }
if (HX_FIELD_EQ(inName,"urlDecode") ) { return urlDecode_dyn(); }
break;
case 10:
if (HX_FIELD_EQ(inName,"htmlEscape") ) { return htmlEscape_dyn(); }
if (HX_FIELD_EQ(inName,"startsWith") ) { return startsWith_dyn(); }
if (HX_FIELD_EQ(inName,"fastCodeAt") ) { return fastCodeAt_dyn(); }
break;
case 12:
if (HX_FIELD_EQ(inName,"htmlUnescape") ) { return htmlUnescape_dyn(); }
}
return super::__Field(inName,inCallProp);
}
Dynamic StringTools_obj::__SetField(const ::String &inName,const Dynamic &inValue,bool inCallProp)
{
return super::__SetField(inName,inValue,inCallProp);
}
void StringTools_obj::__GetFields(Array< ::String> &outFields)
{
super::__GetFields(outFields);
};
static ::String sStaticFields[] = {
HX_CSTRING("urlEncode"),
HX_CSTRING("urlDecode"),
HX_CSTRING("htmlEscape"),
HX_CSTRING("htmlUnescape"),
HX_CSTRING("startsWith"),
HX_CSTRING("endsWith"),
HX_CSTRING("isSpace"),
HX_CSTRING("ltrim"),
HX_CSTRING("rtrim"),
HX_CSTRING("trim"),
HX_CSTRING("rpad"),
HX_CSTRING("lpad"),
HX_CSTRING("replace"),
HX_CSTRING("hex"),
HX_CSTRING("fastCodeAt"),
HX_CSTRING("isEOF"),
String(null()) };
static ::String sMemberFields[] = {
String(null()) };
static void sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(StringTools_obj::__mClass,"__mClass");
};
static void sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(StringTools_obj::__mClass,"__mClass");
};
Class StringTools_obj::__mClass;
void StringTools_obj::__register()
{
Static(__mClass) = hx::RegisterClass(HX_CSTRING("StringTools"), hx::TCanCast< StringTools_obj> ,sStaticFields,sMemberFields,
&__CreateEmpty, &__Create,
&super::__SGetClass(), 0, sMarkStatics, sVisitStatics);
}
void StringTools_obj::__boot()
{
}
| [
"[email protected]"
] | [
[
[
1,
410
]
]
] |
6a5800c8150e8c9144d23429c10f35136b06e222 | 578ceec075394968a5ac0ef3ed5961697d8cd826 | /daemon/DekdCommand.h | 7a1648ba3f971ea0a278f233a006d43f4fa34003 | [] | no_license | olicmoon/dekd | 3938a6f76cdb8b0a9ef915b273f94ac8fa9276d9 | c5a88ec8330a67ce952351970bf5657813977eae | refs/heads/master | 2021-01-19T06:24:54.282288 | 2015-08-31T21:17:06 | 2015-09-01T00:40:38 | 40,740,525 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 365 | h | /*
* DekdCommand.h
*
* Created on: Aug 17, 2015
* Author: olic
*/
#ifndef DEKDCOMMAND_H_
#define DEKDCOMMAND_H_
#include <FrameworkCommand.h>
class DekdCommand : public FrameworkCommand {
public:
DekdCommand(const char *cmd);
virtual ~DekdCommand() {}
int runCommand(SocketClient *c, int argc, char **argv);
};
#endif /* DEKDCOMMAND_H_ */
| [
"[email protected]"
] | [
[
[
1,
22
]
]
] |
2b17e47589ce2b7bb6579f599aad8e4a664896b5 | b8487f927d9fb3fa5529ad3686535714c687dd50 | /include/hermes/VM/JIT/DenseUInt64.h | 7cb45f61cba99d132ac4e42fc17f6b4a3b55cbc0 | [
"MIT"
] | permissive | hoangtuanhedspi/hermes | 4a1399f05924f0592c36a9d4b3fd1f804f383c14 | 02dbf3c796da4d09ec096ae1d5808dcb1b6062bf | refs/heads/master | 2020-07-12T21:21:53.781167 | 2019-08-27T22:58:17 | 2019-08-27T22:59:55 | 204,908,743 | 1 | 0 | MIT | 2019-08-28T17:44:49 | 2019-08-28T10:44:49 | null | UTF-8 | C++ | false | false | 2,568 | h | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*/
#ifndef HERMES_VM_JIT_DENSEUINT64_H
#define HERMES_VM_JIT_DENSEUINT64_H
#include "hermes/VM/HermesValue.h"
#include "llvm/ADT/DenseMapInfo.h"
namespace hermes {
namespace vm {
/// A wrapper for using uint64_t with llvm::DenseMap/Set.
class DenseUInt64 {
public:
/// Enum to differentiate between LLVM's empty/tombstone and normal values.
enum class MapKeyType {
empty,
tombstone,
valid,
};
DenseUInt64(uint64_t cval) : keyType_(MapKeyType::valid), rawValue_(cval) {}
DenseUInt64(void *addr)
: keyType_(MapKeyType::valid), rawValue_((uint64_t)addr) {}
DenseUInt64(HermesValue hv)
: keyType_(MapKeyType::valid), rawValue_(hv.getRaw()) {}
DenseUInt64(double v) : DenseUInt64(HermesValue::encodeDoubleValue(v)) {}
DenseUInt64(MapKeyType keyType) : keyType_(keyType), rawValue_(0) {
assert(keyType_ != MapKeyType::valid && "valid entries must have a value");
}
bool operator==(const DenseUInt64 &other) const {
return keyType_ == other.keyType_ && rawValue_ == other.rawValue_;
}
HermesValue valueAsHV() const {
assert(
keyType_ == MapKeyType::valid &&
"attempting to get the value of tombstone/empty entry");
return HermesValue(rawValue_);
}
void *valueAsAddr() const {
assert(
keyType_ == MapKeyType::valid &&
"attempting to get the value of tombstone/empty entry");
return (void *)rawValue_;
}
uint64_t rawValue() const {
return rawValue_;
}
private:
/// The type of value we have: empty/tombstone/normal.
MapKeyType keyType_;
/// A raw uint64_t: it could be a HermesValue or an address
uint64_t rawValue_;
};
} // namespace vm
} // namespace hermes
namespace llvm {
/// Traits to enable using UInt64Constant with llvm::DenseSet/Map.
template <>
struct DenseMapInfo<hermes::vm::DenseUInt64> {
using UInt64Constant = hermes::vm::DenseUInt64;
using MapKeyType = UInt64Constant::MapKeyType;
static inline UInt64Constant getEmptyKey() {
return MapKeyType::empty;
}
static inline UInt64Constant getTombstoneKey() {
return MapKeyType::tombstone;
}
static inline unsigned getHashValue(UInt64Constant x) {
return DenseMapInfo<uint64_t>::getHashValue(x.rawValue());
}
static inline bool isEqual(UInt64Constant a, UInt64Constant b) {
return a == b;
}
};
} // namespace llvm
#endif // HERMES_VM_JIT_DENSEUINT64_H
| [
"[email protected]"
] | [
[
[
1,
93
]
]
] |
849e17e440d0e9523fb0dd1a5f7f9d2bf5e1f416 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5686313294495744_0/C++/vidhan13j07/test.cpp | 5edfd10037fb916f2f5fbdef7cf9305b0b29d5b9 | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 2,489 | cpp | #include<bits/stdc++.h>
#define sc(v) v.size()
#define eb push_back
#define pb pop_back
#define f(i,a,b) for(int i=a;i<b;i++)
#define TC() int t;cin>>t;while(t--)
#define all(x) x.begin(),x.end()
#define mk make_pair
#define fi first
#define se second
#define endl "\n"
#define eps 1e-9
#define pw(x) (1ll<<(x))
#define trace1(x) cout <<#x<<": "<<x<<endl;
#define trace2(x, y) cout <<#x<<": "<<x<<" | "<<#y<<": "<<y<< endl;
#define trace3(x, y, z) cout <<#x<<": "<<x<<" | "<<#y<<": "<<y<<" | "<<#z<<": "<<z<<endl;
#define trace4(a, b, c, d) cout <<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<endl;
#define trace5(a, b, c, d, e) cout <<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<<": "<<e<<endl;
using namespace std;
typedef long long int ll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef pair<string,string> pi;
typedef pair<ll,ll> pll;
inline bool EQ(double a,double b) { return fabs(a - b) < 1e-9; }
inline void set_bit(int & n, int b) { n |= pw(b); }
inline void unset_bit(int & n, int b) { n &= ~pw(b); }
int main()
{
#ifndef ONLINE_JUDGE
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
#endif
clock_t tStart = clock();
int tc = 1;
int n;
map< pi,int > mp;
vector< pi > v;
set< pi > vv;
vector<string> f,rr;
string x,y;
set<string> a,b;
TC()
{
printf("Case #%d: ", tc++);
mp.clear();
v.clear();
a.clear();
b.clear();
scanf("%d",&n);
f(i,0,n)
{
cin>>x>>y;
v.eb(mk(x,y));
mp[mk(x,y)] = 1;
}
int ans = 0;
f(i,0,1 << n)
{
f.clear();
rr.clear();
vv.clear();
int c = 0;
f(j,0,n)
if(i&(1 << j))
{
f.eb(v[j].fi);
rr.eb(v[j].se);
vv.insert(v[j]);
}
f(j,0,sc(f))
f(k,0,sc(rr))
{
if(vv.find(mk(f[j],rr[k])) != vv.end())
continue;
if(mp[mk(f[j],rr[k])])
c++;
}
ans = max(ans,c);
}
printf("%d\n",ans);
}
//printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
90
]
]
] |
83c1a88dc48365856197594c6712168628615a60 | 52a932a54983d3c1a40d30d0cd546085deb1fd86 | /source/Mobs/Zombie.h | 61f8e3bb84ee3895ca4f367a944df4e218e15e7a | [
"Apache-2.0"
] | permissive | Xury/MCServer | ce8068fd4cf9401b5348769dcc6ed7b670dcae08 | c019e8f0c568163967de4b6c370964cfc0b1adb3 | refs/heads/master | 2021-01-18T02:49:50.005403 | 2013-09-03T12:54:50 | 2013-09-03T12:55:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 326 | h | #pragma once
#include "AggressiveMonster.h"
class cZombie :
public cAggressiveMonster
{
typedef cAggressiveMonster super;
public:
cZombie();
CLASS_PROTODEF(cZombie);
virtual void Tick(float a_Dt, cChunk & a_Chunk) override;
virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override;
} ;
| [
"[email protected]@0a769ca7-a7f5-676a-18bf-c427514a06d6",
"[email protected]@0a769ca7-a7f5-676a-18bf-c427514a06d6"
] | [
[
[
1,
2
],
[
4,
4
],
[
11,
11
],
[
14,
16
],
[
25,
25
]
],
[
[
3,
3
],
[
5,
10
],
[
12,
13
],
[
17,
24
]
]
] |
e80178df0d6d8e25163f4e3d848c8940e1e40d2f | 8ea2c608d0ea52bdf26e045ada1367b93f76c046 | /OpenGL/objeto.h | 6ebbac6737b5475febb0a458045ceb0aa82a7255 | [] | no_license | Alexandrecajamos/geometria_comp | 0aedf467e337ffc2627e68564c9ade03354f3881 | d0264e2ec8bfb0da50c1ee8ec14042779d860612 | refs/heads/master | 2021-04-12T09:52:11.906345 | 2018-06-21T21:17:36 | 2018-06-21T21:17:36 | 126,262,600 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,027 | h | #ifndef OBJETO_H
#define OBJETO_H
#include<vector>
#include "stdio.h"
#include "coord_3d.h"
#include "esfera.h"
#include <fstream>
#include "face.h"
#include<cmath>
#define TAM 4
class Objeto
{
public:
Objeto();
void addPoint(float x, float y, float z);
void addFace(int iP1, int iP2, int iP3);
float Ray_intersept(Coord_3D Po, Coord_3D Dir, int *iFace);
bool Tiro(Coord_3D Ponto);
void calc_Esfera();
void ImpPoints();
void ImpFaces();
bool Obstaculo(Coord_3D Pint, Coord_3D l);
void Libera();
void Ordena(int eixo);
void CopiaPontos(Objeto* O);
Coord_3D Centro();
float Area_Externa();
float Volume();
int MaiorX();//Retorna Indice
int MenorX();//Retorna Indice
int MaiorY();//Retorna Indice
int MenorY();//Retorna Indice
int MaiorZ();//Retorna Indice
int MenorZ();//Retorna Indice
bool Pertence(int iP1, int iP2, int iP3);
Esfera Esf;
std::vector<Coord_3D*> points;
std::vector<Face*> faces;
};
#endif // OBJETO_H
| [
"[email protected]"
] | [
[
[
1,
50
]
]
] |
fa606684822edaeb65a3facbab4e69b8044c96ef | 6aeccfb60568a360d2d143e0271f0def40747d73 | /sandbox/SOC/2011/simd/boost/simd/toolbox/constant/include/constants/minexponent.hpp | 0fd6c857f2cef5aa7fcc1f22aca4daf4a5f7a9c3 | [] | no_license | ttyang/sandbox | 1066b324a13813cb1113beca75cdaf518e952276 | e1d6fde18ced644bb63e231829b2fe0664e51fac | refs/heads/trunk | 2021-01-19T17:17:47.452557 | 2013-06-07T14:19:55 | 2013-06-07T14:19:55 | 13,488,698 | 1 | 3 | null | 2023-03-20T11:52:19 | 2013-10-11T03:08:51 | C++ | UTF-8 | C++ | false | false | 232 | hpp | #ifndef BOOST_SIMD_TOOLBOX_CONSTANT_INCLUDE_CONSTANTS_MINEXPONENT_HPP_INCLUDED
#define BOOST_SIMD_TOOLBOX_CONSTANT_INCLUDE_CONSTANTS_MINEXPONENT_HPP_INCLUDED
#include <boost/simd/toolbox/constant/constants/minexponent.hpp>
#endif
| [
"[email protected]"
] | [
[
[
1,
6
]
]
] |
b54f8af3b8d91ec3312f1936cc121941612c52f9 | 33c05858242f026297d97a902656ee8f066683a8 | /satellite_sniffer_BoTFSM/src/Canvas.cpp | ad8ababfa55c65250d872cc2f5187e0f6e6b207d | [] | no_license | CodecoolBP20171/cpp-satellite-sniffer-botfsm | d8bcb902da2c4f3e2d7b827da0558343022687c3 | b29818ae7dc1d2f7f3967c278a3d01c447786df8 | refs/heads/master | 2021-06-01T16:43:46.978984 | 2018-09-30T13:10:56 | 2018-09-30T13:10:56 | 113,032,533 | 4 | 2 | null | 2018-09-30T13:10:57 | 2017-12-04T11:09:09 | C | UTF-8 | C++ | false | false | 883 | cpp | #include "stdafx.h"
#include "Canvas.h"
#include "Resources.h"
#include <SDL.h>
Canvas::Canvas(const int width, const int height)
{
this->height = height;
this->width = width;
texture = SDL_CreateTexture(Resources::getInstance()->getRenderer(), SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, width, height);
SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND);
}
void Canvas::resize(const int width, const int height)
{
if (texture) SDL_DestroyTexture(texture);
this->height = height;
this->width = width;
texture = SDL_CreateTexture(Resources::getInstance()->getRenderer(), SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, width, height);
SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND);
}
void Canvas::setAsRenderTarget()
{
SDL_SetRenderTarget(Resources::getInstance()->getRenderer(), texture);
}
Canvas::~Canvas()
{
}
| [
"[email protected]"
] | [
[
[
1,
31
]
]
] |
cf94e7e7f6a5aa06a4c6a7230f8e8a546b0206a4 | 607829232b9ec8d6733fb67be85e8555d19e1ee0 | /libs/core/include/fcppt/math/vector/ceil_div_signed.hpp | 6ebdffb5f1f010dcdee214d5164fac81c3a66cd8 | [
"BSL-1.0"
] | permissive | cnsuhao/fcppt | 3b917196d5faf477d769b8f04e0001361a857776 | 104c035118a04011c5fd9574cc78b2889550ea65 | refs/heads/master | 2021-01-13T06:30:29.527419 | 2016-11-05T13:33:41 | 2016-11-05T13:33:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,306 | hpp | // Copyright Carl Philipp Reh 2009 - 2016.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef FCPPT_MATH_VECTOR_CEIL_DIV_SIGNED_HPP_INCLUDED
#define FCPPT_MATH_VECTOR_CEIL_DIV_SIGNED_HPP_INCLUDED
#include <fcppt/math/ceil_div_signed.hpp>
#include <fcppt/math/map.hpp>
#include <fcppt/math/size_type.hpp>
#include <fcppt/math/vector/object_impl.hpp>
#include <fcppt/math/vector/static.hpp>
#include <fcppt/config/external_begin.hpp>
#include <type_traits>
#include <fcppt/config/external_end.hpp>
namespace fcppt
{
namespace math
{
namespace vector
{
/**
\brief Division rounded up for signed vectors
\ingroup fcpptmathvector
*/
template<
typename T,
fcppt::math::size_type N,
typename S
>
fcppt::math::vector::static_<
T,
N
>
ceil_div_signed(
fcppt::math::vector::object<
T,
N,
S
> const _vector,
T const _factor
)
{
static_assert(
std::is_signed<
T
>::value,
"T must be signed"
);
return
fcppt::math::map<
fcppt::math::vector::static_<
T,
N
>
>(
_vector,
[
_factor
](
T const _value
)
{
return
fcppt::math::ceil_div_signed(
_value,
_factor
);
}
);
}
}
}
}
#endif
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
1
],
[
12,
12
],
[
14,
14
],
[
27,
31
],
[
34,
34
],
[
37,
37
],
[
39,
40
],
[
59,
59
],
[
61,
61
]
],
[
[
2,
11
],
[
13,
13
],
[
15,
26
],
[
32,
33
],
[
35,
36
],
[
38,
38
],
[
41,
58
],
[
60,
60
],
[
62,
84
]
]
] |
334f0712fc8566ea028524f0cd56702b83f8dbd4 | 9b273539e02cca8d408e8cf793007ee84e6637d5 | /ext/bliss/src/iterators/edge_iterator.hpp | 2217a705bef1dc4b94ba3493a6facab66fe6ad3e | [
"Apache-2.0"
] | permissive | tuan1225/parconnect_sc16 | 23b82c956eed4dabe5deec8bd48cc8ead91af615 | bcd6f99101685d746cf30e22fa3c3f63ddd950c9 | refs/heads/master | 2020-12-24T12:01:13.846352 | 2016-11-07T16:51:29 | 2016-11-07T16:51:29 | 73,055,274 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,760 | hpp | /*
* edge_iterator.hpp
*
* Created on: Aug 4, 2015
* Author: yongchao
*/
#ifndef EDGE_ITERATOR_HPP_
#define EDGE_ITERATOR_HPP_
#include <iterator>
#include "common/alphabets.hpp"
namespace bliss
{
namespace iterator
{
// careful with the use of enable_if. evaluation should occur at function call time,
// i.e. class template params will be evaluated with no substitution.
// instead, a function should declare a template parameter proxy for the class template parameter.
// then enable_if evaluates using the proxy.
// e.g. template< class c = C; typename std::enable_if<std::is_same<c, std::string>::value, int>::type x = 0>
/**
* @class edge_iterator
* @brief given a k-mer position, retrieve its left and right bases, including the dummy bases at both ends
* @details specializations of this class uses a byte to manage the edge info.
* upper 4 bits holds the left base (encoded), lower 4 bits holds the right base (encoded)
*
* no reverse complement or reordering is applied.
*
* edge iterator should be valid for std::distance(_data_end - _data_start - k + 1) iterations.
*/
template<typename IT, typename ALPHA = bliss::common::DNA16>
class edge_iterator : public ::std::iterator<::std::forward_iterator_tag, uint8_t>
{
protected:
// curr position
IT _curr;
//previous position
IT _left;
//a position of distance k from the _curr on the right
IT _right;
/*data*/
const IT _data_start;
const IT _data_end;
public:
typedef ALPHA Alphabet;
typedef edge_iterator<IT, ALPHA> self_type; /*define edge iterator type*/
typedef uint8_t edge_type; //type to represent an edge
// accessors
IT& getBase()
{
return _curr;
}
//constructor
edge_iterator(IT data_start, IT data_end, const uint32_t k)
: _curr (data_start), _left(data_end), _right(data_start), _data_start(data_start), _data_end(data_end)
{
/*compute the offset*/
::std::advance(_curr, k - 1);
_right = _curr;
::std::advance(_right, 1);
}
edge_iterator(IT data_end)
: _curr(data_end), _left(data_end), _right(data_end), _data_start(data_end), _data_end(data_end)
{
}
/// copy constructor
edge_iterator(const self_type& Other)
: _curr (Other._curr), _left(Other._left), _right(Other._right),
_data_start(Other._data_start), _data_end(Other._data_end)
{
/*do nothing*/
}
/// copy assignment iterator
self_type& operator=(const self_type& Other)
{
_curr = Other._curr;
_left = Other._left;
_right = Other._right;
_data_start = Other._data_start;
_data_end = Other._data_end;
return *this;
}
/// increment to next matching element in base iterator
self_type& operator++()
{ // if _curr at end, subsequent calls should not move _curr.
// on call, if not at end, need to move first then evaluate.
if (_curr == _data_end){ // if at end, don't move it.
return *this;
}
/*save the previous position*/
if (_left == _data_end) _left = _data_start;
else ++_left;
/*move forward by 1*/
++_curr;
/*ensure that _right does not exceed _end*/
if(_right != _data_end){
++_right;
}
return *this;
}
/**
* post increment. make a copy then increment that.
*/
self_type operator++(int)
{
self_type output(*this);
this->operator++();
return output;
}
/// compare 2 filter iterators
inline bool operator==(const self_type& rhs)
{
return _curr == rhs._curr;
}
/// compare 2 filter iterators
inline bool operator!=(const self_type& rhs)
{
return _curr != rhs._curr;
}
/// dereference operator. _curr is guaranteed to be valid
inline edge_type operator*()
{
/*using four bits to represent an edge*/
if(_left != _data_end && _right != _data_end){
/*internal k-mer node*/
return (ALPHA::FROM_ASCII[*_left] << 4) | ALPHA::FROM_ASCII[*_right];
}else if(_left == _data_end && _right != _data_end){ /*the left-most k-mer node*/
return ALPHA::FROM_ASCII[*_right];
}else if(_left != _data_end && _right == _data_end){ /*the rigth-most k-mer node*/
return ALPHA::FROM_ASCII[*_left] << 4;
}
/*if(_left == _end && _right == _end)*/
return 0;
}
};
template<typename IT>
using DNA16_edge_iterator = edge_iterator<IT, bliss::common::DNA16>;
template<typename IT>
using DNA_IUPAC_edge_iterator = edge_iterator<IT, bliss::common::DNA_IUPAC>;
// not suitable for edge iterator since there is no value for unknown char.
template<typename IT>
using DNA_edge_iterator = edge_iterator<IT, bliss::common::DNA>;
template<typename IT>
using DNA5_edge_iterator = edge_iterator<IT, bliss::common::DNA5>;
// not suitable for edge iterator since there is no value for unknown char.
template<typename IT>
using RNA_edge_iterator = edge_iterator<IT, bliss::common::RNA>;
template<typename IT>
using RNA5_edge_iterator = edge_iterator<IT, bliss::common::RNA5>;
/*EdgeType = short unsigned int*/
template<typename IT>
class edge_iterator<IT, bliss::common::ASCII>: public ::std::iterator<::std::forward_iterator_tag, uint16_t>
{
protected:
// curr position
IT _curr;
//previous position
IT _left;
//a position of distance k from the _curr on the right
IT _right;
/*data*/
const IT _data_start;
const IT _data_end;
public:
typedef bliss::common::ASCII Alphabet;
typedef edge_iterator<IT, bliss::common::ASCII> self_type; /*define edge iterator type*/
typedef uint16_t edge_type; //type to represent an edge
// accessors
IT& getBase()
{
return _curr;
}
//constructor
edge_iterator(IT data_start, IT data_end, const uint32_t k)
: _curr (data_start), _left(data_end), _right(data_start), _data_start(data_start), _data_end(data_end)
{
/*compute the offset*/
::std::advance(_curr, k-1);
_right = _curr;
::std::advance(_right, 1);
}
edge_iterator(IT data_end)
: _curr(data_end), _left(data_end), _right(data_end), _data_start(data_end), _data_end(data_end)
{
}
/// copy constructor
edge_iterator(const self_type& Other)
: _curr (Other._curr), _left(Other._left), _right(Other._right),
_data_start(Other._data_start), _data_end(Other._data_end)
{
/*do nothing*/
}
/// copy assignment iterator
self_type& operator=(const self_type& Other)
{
_curr = Other._curr;
_left = Other._left;
_right = Other._right;
_data_start = Other._data_start;
_data_end = Other._data_end;
return *this;
}
/// increment to next matching element in base iterator
self_type& operator++()
{ // if _curr at end, subsequent calls should not move _curr.
// on call, if not at end, need to move first then evaluate.
if (_curr == _data_end){ // if at end, don'IT move it.
return *this;
}
/*save the previous position*/
if (_left == _data_end) _left = _data_start;
else ++_left;
/*move forward by 1*/
++_curr;
/*ensure that _right does not exceed _end*/
if(_right != _data_end){
++_right;
}
return *this;
}
/**
* post increment. make a copy then increment that.
*/
self_type operator++(int)
{
self_type output(*this);
this->operator++();
return output;
}
/// compare 2 filter iterators
inline bool operator==(const self_type& rhs)
{
return _curr == rhs._curr;
}
/// compare 2 filter iterators
inline bool operator!=(const self_type& rhs)
{
return _curr != rhs._curr;
}
/// dereference operator. _curr is guaranteed to be valid
inline edge_type operator*()
{
/*using 8 bits to represent an edge*/
if(_left != _data_end && _right != _data_end){
/*internal k-mer node*/
return (*_left << 8) | *_right;
}else if(_left == _data_end && _right != _data_end){ /*the left-most k-mer node*/
return *_right & 0x0ff;
}else if(_left != _data_end && _right == _data_end){ /*the rigth-most k-mer node*/
return *_left << 8;
}
/*if(_left == _end && _right == _end)*/
return 0;
}
};
template<typename IT>
using raw_edge_iterator = edge_iterator<IT, bliss::common::ASCII>;
} // iterator
} // bliss
#endif /* EDGE_ITERATOR_HPP_ */
| [
"[email protected]"
] | [
[
[
1,
312
]
]
] |
125d9dfb6a31d7b8178cff53df30313fe499c04f | 7749a4165ee0dbc239aa2d6415087d3bf8356819 | /cpp/datautil.cpp | 9f2efed3beffa1587636dd9f57d23743e072f2f8 | [
"Unlicense",
"CC-BY-4.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | csavur/c2gQtCon_x | e792dac2fdc92b64245527d5032fe5dc3b1b17a4 | 510019256f9243e7ebeafefbf58285ce71d24c9f | refs/heads/master | 2021-01-12T14:56:36.621567 | 2017-09-05T20:57:36 | 2017-09-05T20:57:36 | 89,668,134 | 0 | 0 | null | 2017-04-28T04:41:26 | 2017-04-28T04:41:26 | null | UTF-8 | C++ | false | false | 68,114 | cpp | #include "datautil.hpp"
#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>
#include <QFile>
#include <QDir>
#include <QImage>
const QString YYYY_MM_DD = "yyyy-MM-dd";
const QString HH_MM = "HH:mm";
const QString LOCAL_HH_MM = "hh:mm";
const QString YYYY_MM_DD_HH_MM = "yyyy-MM-ddHH:mm";
const QString DAYNAME = "dddd";
const QString DAYNAME_HH_MM = "dddd, HH:mm";
const QString DEFAULT_SPEAKER_IMAGE_URL = "http://conf.qtcon.org/person_original.png";
const QString EMPTY_TRACK = "*****";
DataUtil::DataUtil(QObject *parent) : QObject(parent)
{
}
void DataUtil::init(DataManager* dataManager, DataServer* dataServer)
{
mDataManager = dataManager;
mDataServer = dataServer;
mConferenceDataPath = mDataManager->mDataPath + "conference/";
mDataServer->setConferenceDataPath(mConferenceDataPath);
// used for temp dynamic lists as QQmlPropertyLists
mSessionLists = mDataManager->createSessionLists();
// connections
bool res = connect(mDataServer, SIGNAL(serverSuccess()), this,
SLOT(onServerSuccess()));
if (!res) {
Q_ASSERT(res);
}
res = connect(mDataServer, SIGNAL(serverFailed(QString)), this,
SLOT(onServerFailed(QString)));
if (!res) {
Q_ASSERT(res);
}
res = connect(mDataServer, SIGNAL(versionSuccess(QByteArray)), this,
SLOT(onVersionSuccess(QByteArray)));
if (!res) {
Q_ASSERT(res);
}
res = connect(mDataServer, SIGNAL(versionFailed(QString)), this,
SLOT(onVersionFailed(QString)));
if (!res) {
Q_ASSERT(res);
}
}
QString DataUtil::conferenceDataPath4QML() {
return "file://"+mConferenceDataPath;
}
bool DataUtil::isDateTooLate()
{
QString todayDate = QDate::currentDate().toString(YYYY_MM_DD);
if(mDataManager->mAllDay.empty())
return false;
QString lastConferenceDay = ((Day*) mDataManager->mAllDay.last())->conferenceDay().toString(YYYY_MM_DD);
qDebug() << "todayDate" << todayDate << "lastConferenceDay" << lastConferenceDay;
return todayDate > lastConferenceDay;
}
/**
* @brief DataUtil::sessionInfoForSpeaker
* @param speaker
* @return all Session Title line by line
*/
QString DataUtil::sessionInfoForSpeaker(Speaker *speaker)
{
QString info;
if(!speaker) {
return info;
}
for (int i = 0; i < speaker->sessions().size(); ++i) {
if(i > 0) {
info.append("\n");
}
info.append(speaker->sessions().at(i)->title());
}
return info;
}
QString DataUtil::speakerNamesForSession(Session *session)
{
QString info;
if(!session) {
return info;
}
for (int i = 0; i < session->presenter().size(); ++i) {
QString name = session->presenter().at(i)->name();
if(name.length()) {
if(info.length()) {
info.append(", ");
}
info.append(name);
}
}
return info;
}
QString DataUtil::scheduleItemImageForSession(Session *session)
{
if(!session || !session->hasScheduleItem()) {
return "";
}
if(session->scheduleItemAsDataObject()->isRegistration()) {
return "key.png";
}
if(session->scheduleItemAsDataObject()->isLunch()) {
return "lunch.png";
}
if(session->scheduleItemAsDataObject()->isEvent()) {
return "party_event.png";
}
return "break.png";
}
QString DataUtil::letterForButton(Session *session)
{
if(!session) {
return "S";
}
if(session->isTraining()) {
return "T";
}
if(session->isLightning()) {
return "L";
}
if (session->isKeynote()) {
return "K";
}
if(session->isCommunity()) {
return "C";
}
if(session->isMeeting()) {
return "M";
}
if(session->isUnconference()) {
return "U";
}
return "S";
}
QString DataUtil::textForSessionTrack(Session *session)
{
if(!session || !session->hasSessionTrack()) {
return "";
}
QString name = session->sessionTrackAsDataObject()->name();
// if(name == "Community") {
// return "";
// }
if(name == "*****") {
return "";
}
if(name == "Unconference") {
return "";
}
return name;
}
QString DataUtil::textForSessionType(Session *session)
{
if(!session) {
return "";
}
QString info = " (" + QString::number(session->minutes()) + tr(" Minutes)");
if(session->hasScheduleItem()) {
if(session->scheduleItemAsDataObject()->isRegistration()) {
return tr("Registration")+info;
}
if(session->scheduleItemAsDataObject()->isEvent()) {
return tr("Event")+info;
}
if(session->scheduleItemAsDataObject()->isLunch()) {
return tr("Lunch")+info;
}
return tr("Break")+info;
}
if(session->isTraining()) {
return tr("Training")+info;
}
if(session->isLightning()) {
return tr("Lightning Talk")+info;
}
if(session->isKeynote()) {
return tr("Keynote")+info;
}
if(session->isCommunity()) {
return tr("Community")+info;
}
if(session->isUnconference()) {
return tr("Unconference")+info;
}
if(session->isMeeting()) {
return tr("Meeting")+info;
}
return tr("Session")+info;
}
QString DataUtil::trackColor(const int trackId)
{
switch (trackId) {
case 3:
// *****
return "transparent";
case 27:
// 3D
return "#FFCDD2";
case 28:
// Automotive, Mobile and Embedded
return "#F06292";
case 29:
// Best practices
return "#BA68C8";
case 30:
// Beyond Code
return "#D1C4E9";
case 31:
// Break "#FFFFFF"
return "grey";
case 32:
// Codecs
return "#E8EAF6";
case 33:
// Community
return "#B3E5FC";
case 34:
// Distributing Software and Resources
return "#64B5F6";
case 35:
// Free Software policies and politics
return "#4DD0E1";
case 36:
// Geolocation
return "#CDDC39";
case 37:
// In depth
return "#26A69A";
case 38:
// KDE‘s Latest and Greatest
return "#2196F3";
case 39:
// Let‘s talk business
return "#FFEB3B";
case 40:
// Let‘s talk software
return "#FFC107";
case 41:
// Misc
return "#FF9890";
case 42:
// Multithreading
return "#FF7043";
case 43:
// OpenGL and 3D
return "#E53935";
case 44:
// Platforms and Integration
return "#BCAAA4";
case 45:
// Qt in Use
return "#4CAF50";
case 46:
// QtQuick
return "#8BC34A";
case 47:
// Technical Discussions
return "#8D6E63";
case 48:
// Testing and Continuous Integration
return "#E0E0E0";
case 49:
// Tooling
return "#90A4AE";
case 50:
// Web
return "#607D8B";
default:
// transparent
return "transparent";
}
}
// if update failed Data in memory is inconsistent
// delete all, then do init again
void DataUtil::reloadData() {
// delete all to avoid orphans
mProgressInfotext.append(tr(" Rollback"));
emit progressInfo(mProgressInfotext);
// DO IT
// reload
mProgressInfotext.append(tr(" Reload"));
emit progressInfo(mProgressInfotext);
// DO IT
mDataManager->init();
}
// creates missing dirs if preparing conference (pre-conf-stuff)
// or checking for schedule updates
bool DataUtil::checkDirs()
{
// data/conference
QString directory = mDataManager->mDataPath + "conference/";
QDir myDir;
bool exists;
exists = myDir.exists(directory);
if (!exists) {
bool ok = myDir.mkpath(directory);
if(!ok) {
qWarning() << "Couldn't create conference dir " << directory;
return false;
}
qDebug() << "created directory conference " << directory;
}
// data/conference/speakerImages
directory.append("speakerImages/");
exists = myDir.exists(directory);
if (!exists) {
bool ok = myDir.mkpath(directory);
if(!ok) {
qWarning() << "Couldn't create speakerImages dir " << directory;
return false;
}
qDebug() << "created directory speakerImages " << directory;
}
return true;
}
// P R E C O N F E R E N C E S T U F F
/**
* Prepare will be done before submitting the App to AppStore
* Use public Cache
* Best practice:
* 1. remove app from dev device
* 2. start app, switch to public cache
* 3. restart app
* If all done send files from Phone to PC/Mac
* Copy them into data-assets /prod or /test
* Test again after deleting app from dev device
* Now Users will get this directly by installing the app
* and updates are fast
*/
void DataUtil::prepareConference() {
// must use public cache
if(!mDataManager->settingsData()->hasPublicCache()) {
qWarning() << "Preparation must be done from public cache";
return;
}
qDebug() << "PREPARE CONFERENCE ";
// check dirs for pre-conference stuff
bool dirsOk = checkDirs();
if(!dirsOk) {
qWarning() << "cannot create directories";
return;
}
// create some data for this specific conference
prepareEventData();
// prepare speaker
prepareSpeaker();
// prepare sessions
// speaker must exist because sessions will be added to
prepareSessions();
// download speaker images
prepareSpeakerImages();
// now cache all the data
// if ok - copied to qrc: data-assets
qDebug() << "cache DATA";
mDataManager->saveConferenceToCache();
mDataManager->saveDayToCache();
mDataManager->saveBuildingToCache();
mDataManager->saveFloorToCache();
mDataManager->saveRoomToCache();
mDataManager->saveSessionToCache();
// sort Tracks
QMultiMap<QString, SessionTrack*> sessionTrackSortMap;
for (int i = 0; i < mDataManager->allSessionTrack().size(); ++i) {
SessionTrack* sessionTrack = (SessionTrack*) mDataManager->allSessionTrack().at(i);
sessionTrackSortMap.insert(sessionTrack->name(), sessionTrack);
}
mDataManager->mAllSessionTrack.clear();
QMapIterator<QString, SessionTrack*> sessionTrackIterator(sessionTrackSortMap);
while (sessionTrackIterator.hasNext()) {
sessionTrackIterator.next();
SessionTrack* sessionTrack = sessionTrackIterator.value();
mDataManager->insertSessionTrack(sessionTrack);
}
mDataManager->saveSessionTrackToCache();
mDataManager->saveScheduleItemToCache();
mDataManager->saveSessionLinkToCache();
mDataManager->saveSpeakerToCache();
// set API Version
mDataManager->mSettingsData->setApiVersion(mNewApi);
qDebug() << "PREPARE D O N E - WAIT FOR IMAGES";
}
// conference, days, building-floor-rooms
void DataUtil::prepareEventData() {
qDebug() << "PREPARE EVENT ";
// CONFERENCE
mDataManager->deleteConference();
mDataManager->deleteDay();
mDataManager->deleteSession();
mDataManager->deleteScheduleItem();
mDataManager->deleteSessionLink();
mDataManager->deleteSpeaker();
mDataManager->deleteSpeakerImage();
//
Conference* conference = mDataManager->createConference();
int lastNr = 0;
for (int i = 0; i < mDataManager->allBuilding().size(); ++i) {
Building* building = (Building*) mDataManager->allBuilding().at(i);
if(building->buildingId() > lastNr) {
lastNr = building->buildingId();
}
}
conference->setLastBuildingId(lastNr);
lastNr = 0;
for (int i = 0; i < mDataManager->allFloor().size(); ++i) {
Floor* floor = (Floor*) mDataManager->allFloor().at(i);
if(floor->floorId() > lastNr) {
lastNr = floor->floorId();
}
}
conference->setLastFloorId(lastNr);
lastNr = 0;
for (int i = 0; i < mDataManager->allRoom().size(); ++i) {
Room* room = (Room*) mDataManager->allRoom().at(i);
if(room->roomId() > lastNr) {
lastNr = room->roomId();
}
room->clearSessions();
}
conference->setLastRoomId(lastNr);
lastNr = 0;
for (int i = 0; i < mDataManager->allSessionTrack().size(); ++i) {
SessionTrack* track = (SessionTrack*) mDataManager->allSessionTrack().at(i);
if(track->trackId() > lastNr) {
lastNr = track->trackId();
}
track->clearSessions();
}
conference->setLastSessionTrackId(lastNr);
conference->setConferenceName("SoSE 2017");
conference->setConferenceCity("Hawaii");
QString venueAddress;
venueAddress = "Waikoloa Hilton Village, Hawaii";
venueAddress.append("\n");
venueAddress.append("Waikoloa Beach Drive");
// venueAddress.append("\n");
// venueAddress.append("Alexanderstr. 11");
venueAddress.append("\n");
venueAddress.append("96738 Hawaii");
venueAddress.append("\n");
venueAddress.append("USA");
conference->setAddress(venueAddress);
conference->setTimeZoneName("Hawaii-Aleutian");
conference->setTimeZoneOffsetSeconds(1 * 60 * 60); // +01:00 GMT
conference->setConferenceFrom(QDate::fromString("2017-06-18", YYYY_MM_DD));
conference->setConferenceTo(QDate::fromString("2017-06-21", YYYY_MM_DD));
conference->setHashTag("#SoSE2017");
conference->setHomePage("http://sosengineering.org/");
QString coordinate;
coordinate = QString::number(52.520778)+";"+QString::number(13.416515);
// conference->coordinate()->setLatitude(52.520778);
// conference->coordinate()->setLongitude(13.416515);
conference->setCoordinate(coordinate);
mDataManager->insertConference(conference);
// DAYS
// Days dayOfWeek 1=monday, 7 = sunday
// thursday
Day* day = mDataManager->createDay();
day->setId(1);
day->setWeekDay(4);
day->setConferenceDay(QDate::fromString("2017-06-18", YYYY_MM_DD));
conference->addToDays(day);
mDataManager->insertDay(day);
// friday
day = mDataManager->createDay();
day->setId(2);
day->setWeekDay(5);
day->setConferenceDay(QDate::fromString("2017-06-19", YYYY_MM_DD));
conference->addToDays(day);
mDataManager->insertDay(day);
// saturday
day = mDataManager->createDay();
day->setId(3);
day->setWeekDay(6);
day->setConferenceDay(QDate::fromString("2017-06-20", YYYY_MM_DD));
conference->addToDays(day);
mDataManager->insertDay(day);
// sunday
day = mDataManager->createDay();
day->setId(4);
day->setWeekDay(1);
day->setConferenceDay(QDate::fromString("2017-06-21", YYYY_MM_DD));
conference->addToDays(day);
mDataManager->insertDay(day);
// BUILDING
// Building and FLOORS already created
// ROOMS created, but delete current sessions yet
qDebug() << "ROOMS: #" << mDataManager->allRoom().size();
for (int r = 0; r < mDataManager->allRoom().size(); ++r) {
Room* room = (Room*) mDataManager->allRoom().at(r);
room->clearSessions();
}
//
}
QVariantMap DataUtil::readScheduleFile(const QString schedulePath) {
QVariantMap map;
QFile readFile(schedulePath);
if(!readFile.exists()) {
qWarning() << "Schedule Path not found " << schedulePath;
return map;
}
if (!readFile.open(QIODevice::ReadOnly)) {
qWarning() << "Couldn't open file: " << schedulePath;
return map;
}
QJsonDocument jda = QJsonDocument::fromJson(readFile.readAll());
readFile.close();
if(!jda.isObject()) {
qWarning() << "Couldn't create JSON from file: " << schedulePath;
return map;
}
qDebug() << "QJsonDocument for schedule with Object :)";
map = jda.toVariant().toMap();
return map;
}
Day* DataUtil::findDayForServerDate(const QString& dayDate) {
Day* day = nullptr;
bool found = false;
for (int dl = 0; dl < mDataManager->mAllDay.size(); ++dl) {
day = (Day*) mDataManager->mAllDay.at(dl);
if( day->conferenceDay().toString(YYYY_MM_DD) == dayDate) {
found = true;
break;
}
}
if(found) {
qDebug() << "Day found";
return day;
}
qDebug() << "Day not found";
return 0;
}
void DataUtil::adjustPersons(QVariantMap& sessionMap) {
QStringList personKeys;
QVariantList personsList;
personsList = sessionMap.value("persons").toList();
if (personsList.size() > 0) {
for (int pvl = 0; pvl < personsList.size(); ++pvl) {
QVariantMap map = personsList.at(pvl).toMap();
if(map.contains("id")) {
personKeys.append(map.value("id").toString());
}
}
sessionMap.insert("persons", personKeys);
}
}
void DataUtil::createAndAdjustLinks(QVariantMap& sessionMap) {
QStringList linkKeys;
QVariantList linksList;
linksList = sessionMap.value("links").toList();
if (linksList.size() > 0) {
for (int lvl = 0; lvl < linksList.size(); ++lvl) {
QVariantMap map = linksList.at(lvl).toMap();
if(map.contains("url")) {
SessionLink* sessionLink = mDataManager->createSessionLink();
sessionLink->setUrl(map.value("url").toString());
sessionLink->setTitle(map.value("title").toString());
mDataManager->insertSessionLink(sessionLink);
linkKeys.append(sessionLink->uuid());
}
}
sessionMap.insert("links", linkKeys);
}
}
bool DataUtil::checkIfIgnored(SessionAPI* sessionAPI)
{
QString room = "Kohala Promenade";
qDebug() << "room " << sessionAPI->room();
if(sessionAPI->title() == "Registration and Coffee" && sessionAPI->room() != room) {
qDebug() << "unwanted session: " << sessionAPI->sessionId() << " " << sessionAPI->title() << " " << sessionAPI->room();
return true;
}
if(sessionAPI->title() == "Lunch" && sessionAPI->room() != room) {
qDebug() << "unwanted session: " << sessionAPI->sessionId() << " " << sessionAPI->title() << " " << sessionAPI->room();
return true;
}
if(sessionAPI->title() == "Coffee break" && sessionAPI->room() != room) {
qDebug() << "unwanted session: " << sessionAPI->sessionId() << " " << sessionAPI->title() << " " << sessionAPI->room();
return true;
}
if(sessionAPI->title() == "Evening event" && sessionAPI->room() != room) {
qDebug() << "unwanted session: " << sessionAPI->sessionId() << " " << sessionAPI->title() << " " << sessionAPI->room();
return true;
}
if(sessionAPI->title() == "Welcome" && sessionAPI->room() != room) {
qDebug() << "unwanted session: " << sessionAPI->sessionId() << " " << sessionAPI->title() << " " << sessionAPI->room();
return true;
}
return false;
}
void DataUtil::setDuration(SessionAPI* sessionAPI, Session* session) {
QStringList duration;
duration = sessionAPI->duration().split(":");
int minutes = 0;
if(duration.length() == 2) {
minutes = duration.last().toInt();
minutes += duration.first().toInt()*60;
} else {
qWarning() << "Duration wrong: " << sessionAPI->duration() << " session ID: " << sessionAPI->sessionId();
}
session->setMinutes(minutes);
session->setEndTime(session->startTime().addSecs(minutes * 60));
}
void DataUtil::setTrackAndType(SessionAPI* sessionAPI, Session* session, Conference* conference, const bool isUpdate) {
SessionTrack* sessionTrack = nullptr;
bool found = false;
QString trackName;
trackName = sessionAPI->track();
if(trackName.isEmpty()) {
trackName = EMPTY_TRACK;
}
for (int tr = 0; tr < mDataManager->mAllSessionTrack.size(); ++tr) {
sessionTrack = (SessionTrack*) mDataManager->mAllSessionTrack.at(tr);
if(sessionTrack->name() == trackName) {
found = true;
break;
}
}
if(!found) {
sessionTrack = mDataManager->createSessionTrack();
conference->setLastSessionTrackId(conference->lastSessionTrackId()+1);
sessionTrack->setTrackId(conference->lastSessionTrackId());
sessionTrack->setName(trackName);
sessionTrack->setInAssets(isUpdate?false:true);
mDataManager->insertSessionTrack(sessionTrack);
}
if (sessionTrack) {
session->setSessionTrack(sessionTrack->trackId());
session->resolveSessionTrackAsDataObject(sessionTrack);
}
// SCHEDULE or what else
// setting some boolean here makes it easier to distinguish in UI
if (trackName == "Break" || (trackName == "Misc" && session->title().contains("Registration"))) {
ScheduleItem* scheduleItem;
if(isUpdate && session->hasScheduleItem()) {
scheduleItem = session->scheduleItemAsDataObject();
} else {
scheduleItem = mDataManager->createScheduleItem();
scheduleItem->setSessionId(session->sessionId());
session->setScheduleItem(scheduleItem->sessionId());
session->resolveScheduleItemAsDataObject(scheduleItem);
scheduleItem->setSession(session->sessionId());
mDataManager->insertScheduleItem(scheduleItem);
}
if(session->title().contains("Evening event") || session->title().contains("SHOW EUROPE")) {
scheduleItem->setIsEvent(true);
} else {
if(session->title().contains("Registration")) {
scheduleItem->setIsRegistration(true);
} else {
if(session->title().contains("Lunch")) {
scheduleItem->setIsLunch(true);
} else {
scheduleItem->setIsBreak(true);
}
}
}
} else {
if(isUpdate && session->hasScheduleItem()) {
// Session type changed, so remove any old schedule items
mDataManager->deleteScheduleItemBySessionId(session->sessionId());
}
if(session->title().contains("Lightning") || session->sessionType().contains("lightning_talk")) {
session->setIsLightning(true);
} else {
if(session->title().contains("Keynote")) {
session->setIsKeynote(true);
} else {
if(trackName == "Community") {
session->setIsCommunity(true);
} else {
if(session->sessionDayAsDataObject()->conferenceDay().toString(YYYY_MM_DD) == "2017-06-18" && session->title().contains("Training")) {
session->setIsTraining(true);
} else {
if(session->sessionType() == "meeting") {
session->setIsMeeting(true);
} else {
if(session->title().contains("Unconference")) {
session->setIsUnconference(true);
} else {
session->setIsSession(true);
}
}
}
}
}
}
}
}
void DataUtil::prepareSessions()
{
const QString schedulePath = mDataManager->mDataAssetsPath + "conference/schedule.json";
qDebug() << "PREPARE SESSIONS ";
QVariantMap map;
map = readScheduleFile(schedulePath);
if(map.isEmpty()) {
qWarning() << "Schedule is no Map";
return;
}
map = map.value("schedule").toMap();
if(map.isEmpty()) {
qWarning() << "No 'schedule' found";
return;
}
mNewApi = map.value("version").toString();
qDebug() << "VERSION: " + mNewApi;
map = map.value("conference").toMap();
if(map.isEmpty()) {
qWarning() << "No 'conference' found";
return;
}
qDebug() << "TITLE: " << map.value("title").toString();
Conference* conference;
conference = (Conference*) mDataManager->allConference().first();
QVariantList dayList;
dayList = map.value("days").toList();
if(dayList.isEmpty()) {
qWarning() << "No 'days' found";
return;
}
mMultiSession.clear();
qDebug() << "DAYS: " << dayList.size();
for (int i = 0; i < dayList.size(); ++i) {
QVariantMap dayMap;
dayMap = dayList.at(i).toMap();
if(dayMap.isEmpty()) {
qWarning() << "No 'DAY' found #" << i;
continue;
}
QString dayDate;
dayDate = dayMap.value("date").toString();
qDebug() << "processing DATE: " << dayDate;
Day* day = findDayForServerDate(dayDate);
if(!day) {
qWarning() << "No Day* found for " << dayDate;
continue;
}
bool found = false;
QVariantMap roomMap;
roomMap = dayMap.value("rooms").toMap();
QStringList roomKeys = roomMap.keys();
if(roomKeys.isEmpty()) {
qWarning() << "No 'ROOMS' found for DAY # i";
continue;
}
for (int r = 0; r < roomKeys.size(); ++r) {
QVariantList sessionList;
sessionList = roomMap.value(roomKeys.at(r)).toList();
if(sessionList.isEmpty()) {
qWarning() << "DAY: " << dayDate << " ROOM: " << roomKeys.at(r) << " ignored - No Sessions available";
continue;
}
Room* room = nullptr;
found = false;
for (int rl = 0; rl < mDataManager->mAllRoom.size(); ++rl) {
room = (Room*) mDataManager->mAllRoom.at(rl);
if(room->roomName() == roomKeys.at(r)) {
found = true;
break;
}
}
if(!found) {
qWarning() << "Room* not found for " << dayDate << " Room: " << roomKeys.at(r);
// TODO add new Room
continue;
}
for (int sl = 0; sl < sessionList.size(); ++sl) {
QVariantMap sessionMap;
sessionMap = sessionList.at(sl).toMap();
if(sessionMap.isEmpty()) {
qWarning() << "No 'SESSION' Map DAY: " << dayDate << " ROOM: " << roomKeys.at(r);
continue;
}
// adjust persons
adjustPersons(sessionMap);
// create and adjust links
createAndAdjustLinks(sessionMap);
SessionAPI* sessionAPI = mDataManager->createSessionAPI();
sessionAPI->fillFromForeignMap(sessionMap);
// ignore unwanted Sessions
if (checkIfIgnored(sessionAPI)) {
continue;
}
Session* session = mDataManager->createSession();
session->fillFromMap(sessionAPI->toMap());
setDuration(sessionAPI, session);
// refs
// DAY
session->setSessionDay(day->id());
// ROOM
session->setRoom(room->roomId());
// TRACK TYPE SCHEDULE
setTrackAndType(sessionAPI, session, conference, false);
// SORT
session->setSortKey(day->conferenceDay().toString(YYYY_MM_DD)+session->startTime().toString(HH_MM));
mMultiSession.insert(session->sortKey(), session);
} // end for session of a room
} // room keys
} // for days list
// insert sorted Sessions
sortedSessionsIntoRoomDayTrackSpeaker();
}
// sessions must be cleared before for Day Track, Room, Speaker
// always if prepare Conference, explicitely if Update Schedule
void DataUtil::sortedSessionsIntoRoomDayTrackSpeaker() {
QMapIterator<QString, Session*> sessionIterator(mMultiSession);
while (sessionIterator.hasNext()) {
sessionIterator.next();
Session* session = sessionIterator.value();
mDataManager->insertSession(session);
Room* room = mDataManager->findRoomByRoomId(session->room());
if(room != NULL) {
room->addToSessions(session);
} else {
qWarning() << "ROOM is NULL for Session " << session->sessionId() << " #:" << session->room();
}
Day* day = mDataManager->findDayById(session->sessionDay());
if(day != NULL) {
day->addToSessions(session);
} else {
qWarning() << "DAY is NULL for Session " << session->sessionId() << " #:" << session->sessionDay();
}
SessionTrack* sessionTrack = mDataManager->findSessionTrackByTrackId(session->sessionTrack());
if(sessionTrack != NULL) {
sessionTrack->addToSessions(session);
} else {
qWarning() << "TRACK is NULL for Session " << session->sessionId() << " #:" << session->sessionTrack();
}
for (int i = 0; i < session->presenterKeys().size(); ++i) {
int pKey = session->presenterKeys().at(i).toInt();
Speaker* speaker = (Speaker*) mDataManager->findSpeakerBySpeakerId(pKey);
if(speaker != NULL) {
speaker->addToSessions(session);
} else {
qWarning() << "SPEAKER is NULL for Session " << session->sessionId() << " #:" << pKey;
}
} // for presenter
} // while all sessions
}
QVariantList DataUtil::readSpeakerFile(const QString speakerPath) {
QVariantList dataList;
QFile readFile(speakerPath);
if(!readFile.exists()) {
qWarning() << "Speaker Path not found " << speakerPath;
return dataList;
}
if (!readFile.open(QIODevice::ReadOnly)) {
qWarning() << "Couldn't open file: " << speakerPath;
return dataList;
}
QJsonDocument jda = QJsonDocument::fromJson(readFile.readAll());
readFile.close();
if(!jda.isArray()) {
qWarning() << "Couldn't create JSON from file: " << speakerPath;
return dataList;
}
qDebug() << "QJsonDocument for speaker with Array :)";
dataList = jda.toVariant().toList();
return dataList;
}
void DataUtil::calcSpeakerName(Speaker* speaker, SpeakerAPI* speakerAPI) {
speaker->setName(speakerAPI->firstName());
if(speaker->name().length() > 0) {
speaker->setName(speaker->name()+" ");
}
speaker->setName(speaker->name()+speakerAPI->lastName());
if(speaker->name().length() > 0) {
if(speakerAPI->lastName().length() > 0) {
speaker->setSortKey(speakerAPI->lastName().left(5).toUpper());
} else {
speaker->setSortKey(speakerAPI->firstName().left(5).toUpper());
}
speaker->setSortGroup(speaker->sortKey().left(1));
} else {
speaker->setSortKey("*");
speaker->setSortGroup("*");
}
}
void DataUtil::prepareSpeaker()
{
const QString speakersPath = mDataManager->mDataAssetsPath + "conference/speaker.json";
qDebug() << "PREPARE SPEAKER ";
QVariantList dataList;
dataList = readSpeakerFile(speakersPath);
if(dataList.size() == 0) {
qWarning() << "Speaker List empty";
return;
}
mMultiSpeaker.clear();
for (int i = 0; i < dataList.size(); ++i) {
SpeakerAPI* speakerAPI = mDataManager->createSpeakerAPI();
speakerAPI->fillFromForeignMap(dataList.at(i).toMap());
Speaker* speaker = mDataManager->createSpeaker();
speaker->setSpeakerId(speakerAPI->id());
calcSpeakerName(speaker, speakerAPI);
speaker->setBio(speakerAPI->bio());
if(speakerAPI->avatar().length() > 0 && speakerAPI->avatar() != DEFAULT_SPEAKER_IMAGE_URL) {
QString avatar = speakerAPI->avatar();
QStringList sl = avatar.split("?");
if(sl.size() > 1) {
sl.removeLast();
avatar = sl.join("?");
}
sl = avatar.split(".");
if(sl.size() < 2) {
qWarning() << "AVATAR wrong "+speakerAPI->avatar();
} else {
avatar = avatar.replace("http://","https://");
SpeakerImage* speakerImage = mDataManager->createSpeakerImage();
speakerImage->setSpeakerId(speaker->speakerId());
speakerImage->setOriginImageUrl(avatar);
speakerImage->setSuffix(sl.last());
mDataManager->insertSpeakerImage(speakerImage);
speaker->resolveSpeakerImageAsDataObject(speakerImage);
}
}
// using MultiMap to get Speakers sorted
mMultiSpeaker.insert(speaker->sortKey(), speaker);
} // end for all SpeakersAPI
// insert sorted Speakers
mDataManager->mAllSpeaker.clear();
QMapIterator<QString, Speaker*> speakerIterator(mMultiSpeaker);
while (speakerIterator.hasNext()) {
speakerIterator.next();
mDataManager->insertSpeaker(speakerIterator.value());
}
}
void DataUtil::prepareSpeakerImages()
{
const QString speakerImagesPath = mConferenceDataPath + "speakerImages/";
for (int i = 0; i < mDataManager->allSpeakerImage().size(); ++i) {
SpeakerImage* speakerImage = (SpeakerImage*) mDataManager->allSpeakerImage().at(i);
if (!speakerImage->downloadSuccess() && !speakerImage->downloadFailed()) {
qDebug() << "loading..." << speakerImage->speakerId();
QString fileName;
fileName = "speaker_";
fileName.append(QString::number(speakerImage->speakerId()));
fileName.append('.');
fileName.append(speakerImage->suffix());
mImageLoader = new ImageLoader(speakerImage->originImageUrl(), speakerImagesPath+fileName, this);
bool res = connect(mImageLoader, SIGNAL(loaded(QObject*, int, int)), this,
SLOT(onSpeakerImageLoaded(QObject*, int, int)));
if (!res) {
Q_ASSERT(res);
}
res = connect(mImageLoader, SIGNAL(loadingFailed(QObject*, QString)), this,
SLOT(onSpeakerImageFailed(QObject*, QString)));
if (!res) {
Q_ASSERT(res);
}
mImageLoader->loadSpeaker(speakerImage);
return;
}
} // for all speaker images
// N OW cache speaker images
mDataManager->saveSpeakerImageToCache();
qDebug() << "SPEAKER IMAGES D O W N L O A D E D";
}
void DataUtil::checkVersion()
{
mDataServer->requestVersion();
}
void DataUtil::startUpdate()
{
bool dirOk = checkDirs();
if(!dirOk) {
qWarning() << "Cannot create Directories";
emit updateFailed(tr("startUpdate - Cannot create Directories"));
return;
}
mProgressInfotext = tr("Request Schedule and Speakers from Server");
emit progressInfo(mProgressInfotext);
mDataServer->requestSchedule();
}
void DataUtil::continueUpdate()
{
mProgressInfotext = tr("Save Favorites");
emit progressInfo(mProgressInfotext);
// save F A V O R I T E S and bookmarks
saveSessionFavorites();
// S P E A K E R
mProgressInfotext = tr("Sync Speaker");
emit progressInfo(mProgressInfotext);
const QString speakersPath = mConferenceDataPath + "speaker.json";
qDebug() << "PREPARE SPEAKER ";
QVariantList dataList;
dataList = readSpeakerFile(speakersPath);
if(dataList.size() == 0) {
qWarning() << "Speaker List empty";
emit updateFailed(tr("Update failed. No Speaker received.\nReloading current Data"));
return;
}
mMultiSession.clear();
mMultiSpeaker.clear();
mMultiSpeakerImages.clear();
for (int i = 0; i < dataList.size(); ++i) {
SpeakerAPI* speakerAPI = mDataManager->createSpeakerAPI();
speakerAPI->fillFromForeignMap(dataList.at(i).toMap());
Speaker* speaker = mDataManager->findSpeakerBySpeakerId(speakerAPI->id());
if(!speaker) {
// NEW speaker
qDebug() << "NEW SPEAKER";
mProgressInfotext.append("+");
speaker = mDataManager->createSpeaker();
speaker->setSpeakerId(speakerAPI->id());
} else {
// update Speaker
mProgressInfotext.append(".");
}
emit progressInfo(mProgressInfotext);
calcSpeakerName(speaker, speakerAPI);
speaker->setBio(speakerAPI->bio());
if(speakerAPI->avatar().length() > 0 && speakerAPI->avatar() != DEFAULT_SPEAKER_IMAGE_URL) {
QString avatar = speakerAPI->avatar();
QStringList sl = avatar.split("?");
if(sl.size() > 1) {
sl.removeLast();
avatar = sl.join("?");
}
sl = avatar.split(".");
if(sl.size() < 2) {
qWarning() << "AVATAR wrong "+speakerAPI->avatar();
} else {
// check if modified
//avatar = avatar.replace("http://","https://");
if(speaker->hasSpeakerImage()) {
if(speaker->speakerImageAsDataObject()->originImageUrl() != avatar) {
qDebug() << "IMAGE Changed";
SpeakerImage* speakerImage = speaker->speakerImageAsDataObject();
speakerImage->setOriginImageUrl(avatar);
speakerImage->setSuffix(sl.last());
mMultiSpeakerImages.insert(false, speakerImage);
}
} else {
qDebug() << "IMAGE NEW";
SpeakerImage* speakerImage = mDataManager->createSpeakerImage();
speakerImage->setSpeakerId(speaker->speakerId());
speakerImage->setOriginImageUrl(avatar);
speakerImage->setSuffix(sl.last());
speakerImage->setInAssets(false);
speaker->resolveSpeakerImageAsDataObject(speakerImage);
mMultiSpeakerImages.insert(false, speakerImage);
}
} // end if valid Avatar URL
} // end check avatar if URL && not default
// using MultiMap to get Speakers sorted
mMultiSpeaker.insert(speaker->sortKey(), speaker);
} // for speaker from server
//
qDebug() << "SPEAKERS: " << mDataManager->mAllSpeaker.size() << " --> " << mMultiSpeaker.size() << " IMG: " << mMultiSpeakerImages.size();
mProgressInfotext.append("\n").append(tr("Sync Speaker Images"));
emit progressInfo(mProgressInfotext);
updateSpeakerImages();
}
void DataUtil::updateSpeakerImages() {
if(mMultiSpeakerImages.size() > 0) {
QList<SpeakerImage*> waitingForDownload = mMultiSpeakerImages.values(false);
if(waitingForDownload.size() > 0) {
mProgressInfotext.append(".");
emit progressInfo(mProgressInfotext);
// DO IT
const QString speakerImagesPath = mConferenceDataPath + "speakerImages/";
SpeakerImage* speakerImage = waitingForDownload.first();
QString fileName;
fileName = "speaker_";
fileName.append(QString::number(speakerImage->speakerId()));
fileName.append('.');
fileName.append(speakerImage->suffix());
mImageLoader = new ImageLoader(speakerImage->originImageUrl(), speakerImagesPath+fileName, this);
bool res = connect(mImageLoader, SIGNAL(loaded(QObject*, int, int)), this,
SLOT(onSpeakerImageUpdateLoaded(QObject*, int, int)));
if (!res) {
Q_ASSERT(res);
}
res = connect(mImageLoader, SIGNAL(loadingFailed(QObject*, QString)), this,
SLOT(onSpeakerImageUpdateFailed(QObject*, QString)));
if (!res) {
Q_ASSERT(res);
}
mImageLoader->loadSpeaker(speakerImage);
return;
} // waiting for download
} // new images map
// all done
updateSessions();
}
void DataUtil::updateAndAdjustLinks(QVariantMap &sessionMap) {
QStringList linkKeys;
QVariantList linksList;
linksList = sessionMap.value("links").toList();
if (linksList.size() > 0) {
for (int lvl = 0; lvl < linksList.size(); ++lvl) {
QVariantMap map = linksList.at(lvl).toMap();
if(map.contains("url")) {
QString linkUrl = map.value("url").toString();
SessionLink* sessionLink = nullptr;
bool linkFound = false;
for (int xsl = 0; xsl < mDataManager->allSessionLink().size(); ++xsl) {
sessionLink = (SessionLink*) mDataManager->allSessionLink().at(xsl);
if(sessionLink->url() == linkUrl) {
linkFound = true;
break;
}
} // end for all existing links
if(!linkFound) {
sessionLink = mDataManager->createSessionLink();
}
sessionLink->setUrl(linkUrl);
sessionLink->setTitle(map.value("title").toString());
if(!linkFound) {
mDataManager->insertSessionLink(sessionLink);
}
linkKeys.append(sessionLink->uuid());
} // map contains url
} // end for all links
sessionMap.insert("links", linkKeys);
} // end if linklist size
}
void DataUtil::updateSessions() {
mProgressInfotext.append("\n").append(tr("Sync Sessions"));
emit progressInfo(mProgressInfotext);
mMultiSession.clear();
const QString schedulePath = mConferenceDataPath + "schedule.json";
QVariantMap map;
map = readScheduleFile(schedulePath);
if(map.isEmpty()) {
qWarning() << "Schedule is no Map";
emit updateFailed(tr("Error: Received Map is empty."));
return;
}
map = map.value("schedule").toMap();
if(map.isEmpty()) {
qWarning() << "No 'schedule' found";
emit updateFailed(tr("Error: Received Map missed 'schedule'."));
return;
}
map = map.value("conference").toMap();
if(map.isEmpty()) {
qWarning() << "No 'conference' found";
emit updateFailed(tr("Error: Received Map missed 'conference'."));
return;
}
Conference* conference;
if(mDataManager->allConference().isEmpty()) {
emit updateFailed(tr("Error: Conference Not Found!"));
return;
}
conference = (Conference*) mDataManager->allConference().first();
QVariantList dayList;
dayList = map.value("days").toList();
if(dayList.isEmpty()) {
qWarning() << "No 'days' found";
emit updateFailed(tr("Error: Received Map missed 'days'."));
return;
}
if(dayList.size() != 4) {
qWarning() << "Wrong number of 'days' found";
emit updateFailed(tr("Error: # of 'days' expected: 4 - but got ")+QString::number(dayList.size()));
return;
}
for (int i = 0; i < dayList.size(); ++i) {
QVariantMap dayMap;
dayMap = dayList.at(i).toMap();
if(dayMap.isEmpty()) {
qWarning() << "No 'DAY' found #" << i;
emit updateFailed(tr("Map for Day missed from Server"));
continue;
}
QString dayDate;
dayDate = dayMap.value("date").toString();
qDebug() << "processing DATE: " << dayDate;
Day* day = findDayForServerDate(dayDate);
if(!day) {
qWarning() << "No Day* found for " << dayDate;
emit updateFailed(tr("No Day* found for ")+dayDate);
return;
}
bool found = false;
QVariantMap roomMap;
roomMap = dayMap.value("rooms").toMap();
QStringList roomKeys = roomMap.keys();
if(roomKeys.isEmpty()) {
qWarning() << "No 'ROOMS' found for DAY # i";
emit updateFailed(tr("No 'ROOMS' found for DAY ") + dayDate);
return;
}
for (int r = 0; r < roomKeys.size(); ++r) {
QVariantList sessionList;
sessionList = roomMap.value(roomKeys.at(r)).toList();
if(sessionList.isEmpty()) {
qWarning() << "DAY: " << dayDate << " ROOM: " << roomKeys.at(r) << " ignored - No Sessions available";
continue;
}
Room* room = nullptr;
found = false;
for (int rl = 0; rl < mDataManager->mAllRoom.size(); ++rl) {
room = (Room*) mDataManager->mAllRoom.at(rl);
if(room->roomName() == roomKeys.at(r)) {
found = true;
break;
}
}
if(!found) {
qDebug() << "Room* not found for " << dayDate << " Room: " << roomKeys.at(r);
room = mDataManager->createRoom();
conference->setLastRoomId(conference->lastRoomId()+1);
room->setRoomId(conference->lastRoomId());
room->setInAssets(false);
room->setRoomName(roomKeys.at(r));
mDataManager->insertRoom(room);
mProgressInfotext.append("R");
progressInfo(mProgressInfotext);
}
for (int sl = 0; sl < sessionList.size(); ++sl) {
QVariantMap sessionMap;
sessionMap = sessionList.at(sl).toMap();
if(sessionMap.isEmpty()) {
qWarning() << "No 'SESSION' Map DAY: " << dayDate << " ROOM: " << roomKeys.at(r);
continue;
}
// adjust persons
adjustPersons(sessionMap);
// update and adjust SessionLink
updateAndAdjustLinks(sessionMap);
SessionAPI* sessionAPI = mDataManager->createSessionAPI();
sessionAPI->fillFromForeignMap(sessionMap);
// ignore unwanted Sessions
if (checkIfIgnored(sessionAPI)) {
continue;
}
Session* session = mDataManager->findSessionBySessionId(sessionAPI->sessionId());
if(!session) {
// NEW
qDebug() << "NEW Session " << QString::number(sessionAPI->sessionId());
mProgressInfotext.append("+");
session = mDataManager->createSession();
session->setSessionId(sessionAPI->sessionId());
} else {
// Update
qDebug() << "Update Session " << QString::number(sessionAPI->sessionId());
mProgressInfotext.append(".");
}
emit progressInfo(mProgressInfotext);
session->fillFromMap(sessionAPI->toMap());
setDuration(sessionAPI, session);
// refs
// DAY
session->setSessionDay(day->id());
session->resolveSessionDayAsDataObject(day);
// ROOM
session->setRoom(room->roomId());
session->resolveRoomAsDataObject(room);
// TRACK TYPE SCHEDULE isUpdate=true
setTrackAndType(sessionAPI, session, conference, true);
// SessionLinks
// SORT
session->setSortKey(day->conferenceDay().toString(YYYY_MM_DD)+session->startTime().toString(HH_MM));
mMultiSession.insert(session->sortKey(), session);
} // end for sessions of a room of a day
} // end for rooms of a day
} // end for list of days from server
qDebug() << "SESSIONS: " << mDataManager->mAllSession.size() << " --> " << mMultiSession.size();
// speaker, images, sessions, days, rooms, tracks --> cache
// delete orphans
mProgressInfotext.append("\n").append(tr("Schedule and Speaker successfully synchronized :)"));
emit progressInfo(mProgressInfotext);
finishUpdate();
}
void DataUtil::finishUpdate() {
mProgressInfotext.append("\n").append(tr("Now saving Conference Data to Cache"));
emit progressInfo(mProgressInfotext);
// Conference save last xxx Id's
mDataManager->saveConferenceToCache();
qDebug() << "FINISH: Conference saved";
// Building not changed - always initialized from Prepare Conference
// Floor not changed - always initialized from Prepare Conference
// Room: clear sessions for update
for (int r = 0; r < mDataManager->allRoom().size(); ++r) {
Room* room = (Room*) mDataManager->allRoom().at(r);
room->clearSessions();
}
// to reset all correct
resolveSessionsForRooms();
qDebug() << "FINISH: Rooms sessions cleared";
// SessionTrack: clear sessions for update
for (int st = 0; st < mDataManager->allSessionTrack().size(); ++st) {
SessionTrack* track = (SessionTrack*) mDataManager->allSessionTrack().at(st);
track->clearSessions();
qDebug() << "clear sessions for Track " << track->name();
}
// to reset all correct
resolveSessionsForTracks();
qDebug() << "FINISH: Tracks sessions cleared";
// Day: clear sessions for update
for (int d = 0; d < mDataManager->allDay().size(); ++d) {
Day* day = (Day*) mDataManager->allDay().at(d);
day->clearSessions();
}
// to reset all correct
resolveSessionsForSchedule();
qDebug() << "FINISH: Days sessions cleared";
// Speaker: insert sorted Speakers, clear Sessions
mDataManager->mAllSpeaker.clear();
QMapIterator<QString, Speaker*> speakerIterator(mMultiSpeaker);
while (speakerIterator.hasNext()) {
speakerIterator.next();
Speaker* speaker = speakerIterator.value();
speaker->clearSessions();
resolveSessionsForSpeaker(speaker);
mDataManager->insertSpeaker(speaker);
}
qDebug() << "FINISH: Sorted Speakers inserted";
// Check orphans
for (int i = 0; i < mDataManager->mAllSession.size(); ++i) {
Session* session = (Session*) mDataManager->mAllSession.at(i);
bool sessionFound = false;
QMapIterator<QString, Session*> sessionIterator(mMultiSession);
while (sessionIterator.hasNext()) {
sessionIterator.next();
Session* updatedSession = sessionIterator.value();
if(updatedSession->sessionId() == session->sessionId()) {
sessionFound = true;
break;
}
}
if(!sessionFound) {
session->deleteLater();
qDebug() << "Session removed: " << session->sessionId();
}
}
qDebug() << "FINISH: Session orphans deleted";
// Session: insert sorted Sessions
// presenter, sessionLinks, day, room, track scheduleItem are updated
mDataManager->mAllSession.clear();
// now insert sorted Sessions, update sessions for Day, Room, Tracks, Speaker
sortedSessionsIntoRoomDayTrackSpeaker();
qDebug() << "FINISH: Rooms Days Tracks Speaker Sessions sorted";
mDataManager->saveSessionToCache();
qDebug() << "FINISH: Sessions saved";
// SessionLink
mDataManager->saveSessionLinkToCache();
qDebug() << "FINISH: SessionLinks saved";
// ScheduleItem
mDataManager->saveScheduleItemToCache();
qDebug() << "FINISH: ScheduleItems saved";
// SPEAKER
mDataManager->saveSpeakerToCache();
qDebug() << "FINISH: Speaker saved";
// insert Speaker Images
// do NOT mDataManager->mAllSpeakerImage.clear();
// mMultiSpeakerImages contains NEW or UPDATED Speaker Images !
QMapIterator<bool, SpeakerImage*> speakerImagesIterator(mMultiSpeakerImages);
while (speakerImagesIterator.hasNext()) {
speakerImagesIterator.next();
SpeakerImage* speakerImage = speakerImagesIterator.value();
if(!mDataManager->findSpeakerImageBySpeakerId(speakerImage->speakerId())) {
// a NEW Speaker Image
qDebug() << "detcted NEW Speaker Image: " << speakerImage->speakerId();
mDataManager->insertSpeakerImage(speakerImage);
} else {
qDebug() << "detcted UPDATED Speaker Image: " << speakerImage->speakerId();
}
}
mDataManager->saveSpeakerImageToCache();
qDebug() << "FINISH: Speaker Images saved";
// Track sort by Name
QMultiMap<QString, SessionTrack*> sessionTrackSortMap;
for (int i = 0; i < mDataManager->allSessionTrack().size(); ++i) {
SessionTrack* sessionTrack = (SessionTrack*) mDataManager->allSessionTrack().at(i);
sessionTrackSortMap.insert(sessionTrack->name(), sessionTrack);
}
qDebug() << "FINISH: Tracks sorted by Name";
mDataManager->mAllSessionTrack.clear();
QMapIterator<QString, SessionTrack*> sessionTrackIterator(sessionTrackSortMap);
while (sessionTrackIterator.hasNext()) {
sessionTrackIterator.next();
SessionTrack* sessionTrack = sessionTrackIterator.value();
mDataManager->insertSessionTrack(sessionTrack);
}
// save all Tracks with sorted Sessions
mDataManager->saveSessionTrackToCache();
qDebug() << "FINISH: Tracks saved";
// Day: save all days with sorted Sessions
mDataManager->saveDayToCache();
qDebug() << "FINISH: Days saved";
// Rooms: save all Rooms with sorted Sessions
mDataManager->saveRoomToCache();
qDebug() << "FINISH: Rooms saved";
// SETTINGS update API
mDataManager->mSettingsData->setApiVersion(mNewApi);
mDataManager->mSettingsData->setLastUpdate(QDateTime::currentDateTime());
//
mProgressInfotext.append("\n").append(tr("All done"));
emit progressInfo(mProgressInfotext);
qDebug() << "FINISH: All Done";
emit updateDone();
}
// U T I L I T Y S to manage Conference data
/**
* Favorites are transient on Sessions
* Sessions are read-only
* So at startup the propertie will be set
*/
void DataUtil::setSessionFavorites()
{
for (int i = 0; i < mDataManager->mAllFavorite.size(); ++i) {
Favorite* favorite = (Favorite*) mDataManager->mAllFavorite.at(i);
Session* session = mDataManager->findSessionBySessionId(favorite->sessionId());
if(session != NULL) {
session->setIsFavorite(true);
}
}
}
/**
* Favorites are transient on Sessions
* Sessions are read-only
* So while caching data Favorites will be created
*/
void DataUtil::saveSessionFavorites()
{
mDataManager->mAllFavorite.clear();
for (int i = 0; i < mDataManager->mAllSession.size(); ++i) {
Session* session = (Session*) mDataManager->mAllSession.at(i);
if(session->isFavorite()) {
Favorite* favorite = mDataManager->createFavorite();
favorite->setSessionId(session->sessionId());
mDataManager->insertFavorite(favorite);
}
}
}
/**
* list of sessions for a Day are lazy
* (only IDs stored in an Array)
* for the Conference we always need all to create the schedule
* so at startup or update this will be called
*/
void DataUtil::resolveSessionsForSchedule() {
for (int i = 0; i < mDataManager->mAllDay.size(); ++i) {
Day* day = (Day*) mDataManager->mAllDay.at(i);
day->resolveSessionsKeys(mDataManager->listOfSessionForKeys(day->sessionsKeys()));
}
}
/**
* list of sessions for a Track are lazy
* (only IDs stored in an Array)
* this will be called as soon as Tracks are first time displayed
*/
void DataUtil::resolveSessionsForTracks()
{
for (int i = 0; i < mDataManager->mAllSessionTrack.size(); ++i) {
SessionTrack* sessionTrack = (SessionTrack*) mDataManager->mAllSessionTrack.at(i);
sessionTrack->resolveSessionsKeys(mDataManager->listOfSessionForKeys(sessionTrack->sessionsKeys()));
}
}
void DataUtil::resolveSessionsForRooms()
{
for (int i = 0; i < mDataManager->mAllRoom.size(); ++i) {
Room* room = (Room*) mDataManager->mAllRoom.at(i);
room->resolveSessionsKeys(mDataManager->listOfSessionForKeys(room->sessionsKeys()));
}
}
void DataUtil::resolveSessionsForSpeaker(Speaker* speaker)
{
speaker->resolveSessionsKeys(mDataManager->listOfSessionForKeys(speaker->sessionsKeys()));
}
QString DataUtil::scheduleTabName(int tabBarIndex)
{
if(mDataManager->mAllDay.size()<(tabBarIndex +1)) {
return "??";
}
Day* day = (Day*) mDataManager->mAllDay.at(tabBarIndex);
//return day->conferenceDay().toString("ddd (dd)");
return QDate::shortDayName(day->conferenceDay().dayOfWeek());
}
SessionLists *DataUtil::mySchedule()
{
return mSessionLists;
}
void DataUtil::refreshMySchedule()
{
mSessionLists->clearScheduledSessions();
for (int i = 0; i < mDataManager->allSession().size(); ++i) {
Session* session = (Session*) mDataManager->allSession().at(i);
if(!session->isDeprecated() && session->isFavorite()) {
mSessionLists->addToScheduledSessions(session);
}
}
qDebug() << "MY SCHEDLUE #:" << mSessionLists->scheduledSessionsCount();
emit myScheduleRefreshed();
}
int DataUtil::findFirstSessionItem(int conferenceDayIndex, QString pickedTime)
{
if(conferenceDayIndex < 0 || conferenceDayIndex > (mDataManager->mAllDay.size()-1)) {
qDebug() << "Day Index wrong: conferenceDayIndex";
return -1;
}
Day* day = (Day*) mDataManager->mAllDay.at(conferenceDayIndex);
for (int i = 0; i < day->sessions().size(); ++i) {
Session* session = day->sessions().at(i);
QString theTime = session->sortKey().right(5);
if(theTime >= pickedTime) {
return i;
}
}
return day->sessions().size();
}
int DataUtil::findFirstSpeakerItem(QString letter)
{
for (int i = 0; i < mDataManager->mAllSpeaker.size(); ++i) {
Speaker* speaker = (Speaker*) mDataManager->mAllSpeaker.at(i);
if(speaker->sortGroup() >= letter) {
return i;
}
}
return mDataManager->mAllSpeaker.size();
}
// Sortkey: day->conferenceDay().toString(YYYY_MM_DD)+session->startTime().toString("HH:mm")
QString DataUtil::localWeekdayAndTime(QString sessionSortkey)
{
QDateTime sortTime = QDateTime::fromString(sessionSortkey, YYYY_MM_DD_HH_MM);
QString weekDayAndTime = sortTime.toString(DAYNAME);
weekDayAndTime.append(", ");
QTime myTime = QTime::fromString(sessionSortkey.right(5));
weekDayAndTime.append(myTime.toString(Qt::SystemLocaleShortDate));
return weekDayAndTime;
}
QString DataUtil::apiInfo()
{
QString apiInfo = tr("API Version ");
apiInfo.append(mDataManager->settingsData()->apiVersion());
apiInfo.append(("\n")).append(tr("Last Update "));
if(mDataManager->mSettingsData->hasLastUpdate()) {
apiInfo.append(mDataManager->mSettingsData->lastUpdate().toString(Qt::SystemLocaleShortDate));
} else {
apiInfo.append("n/a");
}
return apiInfo;
}
// DOWNLOAD S P E A K E R I M A G E S
// SLOT UPDATE CONFERENCE
void DataUtil::onSpeakerImageUpdateLoaded(QObject *dataObject, int width, int height)
{
mImageLoader->deleteLater();
SpeakerImage* speakerImage = (SpeakerImage*) dataObject;
qDebug() << "onSpeakerImage L O A D E D ";
speakerImage->setDownloadSuccess(true);
speakerImage->setDownloadFailed(false);
speakerImage->setInAssets(false);
speakerImage->setInData(true);
prepareHighDpiImages(speakerImage, width, height);
// set update flag
int count = mMultiSpeakerImages.remove(false, speakerImage);
if(count != 1) {
qWarning() << "something went wrong: the SpeakerImage MUST exist in MultiMap";
}
mMultiSpeakerImages.insert(true, speakerImage);
// check for more
updateSpeakerImages();
}
void DataUtil::onSpeakerImageUpdateFailed(QObject *dataObject, QString message) {
mImageLoader->deleteLater();
SpeakerImage* speakerImage = (SpeakerImage*) dataObject;
qDebug() << "UPDATE: Cannot load Speaker Image: " << message << speakerImage->speakerId();
speakerImage->setDownloadSuccess(false);
speakerImage->setDownloadFailed(true);
speakerImage->setInAssets(false);
speakerImage->setInData(false);
// set update flag
int count = mMultiSpeakerImages.remove(false, speakerImage);
if(count != 1) {
qWarning() << "something went wrong: the SpeakerImage MUST exist in MultiMap";
}
mMultiSpeakerImages.insert(true, speakerImage);
// check for more
updateSpeakerImages();
}
// SLOT PREPARE CONFERENCE
void DataUtil::onSpeakerImageLoaded(QObject *dataObject, int width, int height)
{
mImageLoader->deleteLater();
SpeakerImage* speakerImage = (SpeakerImage*) dataObject;
qDebug() << "loaded..." << speakerImage->speakerId() << " " << width << "x" << height;
speakerImage->setDownloadSuccess(true);
speakerImage->setDownloadFailed(false);
speakerImage->setInAssets(true);
speakerImage->setInData(false);
prepareHighDpiImages(speakerImage, width, height);
// more to load ?
prepareSpeakerImages();
}
void DataUtil::onSpeakerImageFailed(QObject *dataObject, QString message) {
mImageLoader->deleteLater();
SpeakerImage* speakerImage = (SpeakerImage*) dataObject;
qDebug() << "PREPARE: Cannot load Speaker Image: " << message << speakerImage->speakerId();
speakerImage->setDownloadSuccess(false);
speakerImage->setDownloadFailed(true);
speakerImage->setInAssets(false);
speakerImage->setInData(false);
// more to load ?
prepareSpeakerImages();
}
void DataUtil::prepareHighDpiImages(SpeakerImage* speakerImage, int width, int height) {
const QString speakerImagesPath = mConferenceDataPath + "speakerImages/";
QString fileName;
fileName = speakerImagesPath + "speaker_";
fileName.append(QString::number(speakerImage->speakerId()));
QString originFileName;
originFileName = fileName + "." + speakerImage->suffix();
const int size1 = 64;
const int size2 = 128;
const int size3 = 192;
const int size4 = 256;
if(width >= height) {
if(width < size1) {
speakerImage->setMaxScaleFactor(0);
return;
}
QFile originFile(originFileName);
if(!originFile.exists()) {
qWarning() << "SpeakerImage Path not found " << originFileName;
return;
}
if (!originFile.open(QIODevice::ReadOnly)) {
qWarning() << "Couldn't open file: " << originFileName;
return;
}
QImage originImage = QImage::fromData(originFile.readAll());
if(originImage.isNull()) {
qWarning() << "Cannot construct Image from file: " << originFileName;
return;
}
QImage scaledImage;
if(width >= size1) {
scaledImage = originImage.scaledToWidth(size1);
scaledImage.save(originFileName);
speakerImage->setMaxScaleFactor(1);
}
if(width >= size2) {
scaledImage = originImage.scaledToWidth(size2);
scaledImage.save(fileName+"@2x."+speakerImage->suffix());
speakerImage->setMaxScaleFactor(2);
}
if(width >= size3) {
scaledImage = originImage.scaledToWidth(size3);
scaledImage.save(fileName+"@3x."+speakerImage->suffix());
speakerImage->setMaxScaleFactor(3);
}
if(width >= size4) {
scaledImage = originImage.scaledToWidth(size4);
scaledImage.save(fileName+"@4x."+speakerImage->suffix());
speakerImage->setMaxScaleFactor(4);
}
} else {
if(height < size1) {
speakerImage->setMaxScaleFactor(0);
return;
}
QFile originFile(originFileName);
if(!originFile.exists()) {
qWarning() << "SpeakerImage Path not found " << originFileName;
return;
}
if (!originFile.open(QIODevice::ReadOnly)) {
qWarning() << "Couldn't open file: " << originFileName;
return;
}
QImage originImage = QImage::fromData(originFile.readAll());
if(originImage.isNull()) {
qWarning() << "Cannot construct Image from file: " << originFileName;
return;
}
QImage scaledImage;
if(height >= size1) {
scaledImage = originImage.scaledToHeight(size1);
scaledImage.save(originFileName);
speakerImage->setMaxScaleFactor(1);
}
if(height >= size2) {
scaledImage = originImage.scaledToHeight(size2);
scaledImage.save(fileName+"@2x."+speakerImage->suffix());
speakerImage->setMaxScaleFactor(2);
}
if(height >= size3) {
scaledImage = originImage.scaledToHeight(size3);
scaledImage.save(fileName+"@3x."+speakerImage->suffix());
speakerImage->setMaxScaleFactor(3);
}
if(height >= size4) {
scaledImage = originImage.scaledToHeight(size4);
scaledImage.save(fileName+"@4x."+speakerImage->suffix());
speakerImage->setMaxScaleFactor(4);
}
}
}
// S L O T S
void DataUtil::onServerSuccess()
{
qDebug() << "S U C C E S S";
const QString schedulePath = mConferenceDataPath + "schedule.json";
qDebug() << "CHECK FOR UPDATE SESSIONS ";
QVariantMap map;
map = readScheduleFile(schedulePath);
if(map.isEmpty()) {
qWarning() << "Schedule is no Map";
emit checkForUpdateFailed(tr("Error: Received Map is empty."));
return;
}
map = map.value("schedule").toMap();
if(map.isEmpty()) {
qWarning() << "No 'schedule' found";
emit checkForUpdateFailed(tr("Error: Received Map missed 'schedule'."));
return;
}
// now do the real work
continueUpdate();
}
void DataUtil::onVersionSuccess(QByteArray currentVersionBytes)
{
QJsonDocument jda;
jda = QJsonDocument::fromJson(currentVersionBytes);
if(!jda.isObject()) {
onVersionFailed(tr("No JSON Object received for Version Check"));
return;
}
QVariantMap versionMap = jda.toVariant().toMap();
if(versionMap.isEmpty()) {
onVersionFailed(tr("Version Check: received Version Map is empty"));
return;
}
if(!versionMap.contains("version")) {
onVersionFailed(tr("Version Check: received Version Map missed Version Property"));
return;
}
mNewApi = versionMap.value("version").toString();
if(mNewApi.isEmpty()) {
onVersionFailed(tr("Error: Received Map missed 'version'."));
return;
}
qDebug() << "VERSION: " + mNewApi;
QStringList versionList;
versionList = mNewApi.split(".");
if(versionList.size() != 2) {
emit onVersionFailed(tr("Error: 'Version' wrong: ")+mNewApi);
return;
}
if(mDataManager->mSettingsData->apiVersion().length() == 0) {
emit updateAvailable(mNewApi);
return;
}
QStringList oldVersionList;
oldVersionList = mDataManager->mSettingsData->apiVersion().split(".");
if(oldVersionList.size() != 2) {
emit updateAvailable(mNewApi);
return;
}
int oldValue = oldVersionList.at(0).toInt();
int newValue = versionList.at(0).toInt();
if(oldValue > newValue) {
emit noUpdateRequired();
return;
}
oldValue = oldVersionList.at(0).toInt();
newValue = versionList.at(0).toInt();
if(oldValue < newValue) {
emit updateAvailable(mNewApi);
return;
}
oldValue = oldVersionList.at(1).toInt();
newValue = versionList.at(1).toInt();
if(oldValue < newValue) {
emit updateAvailable(mNewApi);
return;
}
emit noUpdateRequired();
}
void DataUtil::onVersionFailed(const QString message)
{
qDebug() << "Version failed" << message;
emit checkForUpdateFailed(message);
}
void DataUtil::onServerFailed(QString message)
{
qDebug() << "FAILED: " << message;
emit updateFailed(message);
}
| [
[
[
1,
63
],
[
67,
68
],
[
70,
215
],
[
217,
218
],
[
220,
221
],
[
223,
224
],
[
226,
227
],
[
229,
230
],
[
232,
233
],
[
235,
236
],
[
238,
239
],
[
241,
242
],
[
244,
245
],
[
247,
248
],
[
250,
251
],
[
253,
254
],
[
256,
257
],
[
259,
260
],
[
262,
263
],
[
265,
266
],
[
268,
269
],
[
271,
272
],
[
274,
275
],
[
277,
278
],
[
280,
281
],
[
283,
284
],
[
286,
455
],
[
458,
458
],
[
460,
460
],
[
464,
464
],
[
466,
466
],
[
468,
468
],
[
470,
470
],
[
475,
486
],
[
488,
493
],
[
495,
500
],
[
502,
507
],
[
509,
549
],
[
551,
596
],
[
602,
604
],
[
606,
608
],
[
610,
612
],
[
614,
616
],
[
618,
638
],
[
640,
705
],
[
707,
792
],
[
794,
1080
],
[
1082,
1153
],
[
1155,
1202
],
[
1208,
1253
],
[
1255,
1894
]
],
[
[
64,
66
],
[
69,
69
],
[
216,
216
],
[
219,
219
],
[
222,
222
],
[
225,
225
],
[
228,
228
],
[
231,
231
],
[
234,
234
],
[
237,
237
],
[
240,
240
],
[
243,
243
],
[
246,
246
],
[
249,
249
],
[
252,
252
],
[
255,
255
],
[
258,
258
],
[
261,
261
],
[
264,
264
],
[
267,
267
],
[
270,
270
],
[
273,
273
],
[
276,
276
],
[
279,
279
],
[
282,
282
],
[
285,
285
],
[
456,
457
],
[
459,
459
],
[
461,
463
],
[
465,
465
],
[
467,
467
],
[
469,
469
],
[
471,
474
],
[
487,
487
],
[
494,
494
],
[
501,
501
],
[
508,
508
],
[
550,
550
],
[
597,
601
],
[
605,
605
],
[
609,
609
],
[
613,
613
],
[
617,
617
],
[
706,
706
],
[
1081,
1081
],
[
1203,
1207
]
],
[
[
639,
639
],
[
793,
793
],
[
1154,
1154
],
[
1254,
1254
]
]
] |
|
6f9e2a1251e0d80527ebef9b1764f62a60cc7984 | c26e9d3f92d95f7ce9d0fd5ef2c18dd95ec209a5 | /hackerrank/graph/murderer.cpp | 1fb9dd65652537e7209bab94ed2d7f66c6acb818 | [] | no_license | crystal95/Competetive-Programming-at-different-platforms | c9ad1684f6258539309d07960ed6abfa7d1a16d0 | 92d283171b0ae0307e9ded473c6eea16f62cb60e | refs/heads/master | 2021-01-09T21:44:28.175506 | 2016-03-27T21:26:26 | 2016-03-27T21:26:26 | 54,848,617 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,083 | cpp | using namespace std;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include <iostream>
#include <queue>
#include <algorithm>
#include <unordered_set>
typedef long long int ll;
typedef pair<int,int> ii;
void bfs(vector<vector<int> > &adj,int s,vector<int> &dis,int n)
{
int i ;
unordered_set<int> unvisited;
for(i=1;i<=n;i++)
unvisited.insert(i);
queue<int> q;
q.push(s);
unvisited.erase(s);
while(!q.empty())
{
int tmp=q.front();
q.pop();
for(auto it=unvisited.begin();it!=unvisited.end();++it)
{
if(find(adj[tmp].begin(),adj[tmp].end(),*it)==adj[tmp].end())
{
q.push(*it);
dis[*it]=dis[tmp]+1;
unvisited.erase(*it);
}
}
}
}
int main()
{
int T;
cin>>T;
while(T--)
{
int i,n,m,u,v,s,w,start;
cin>>n>>m;
vector<vector<int > > adj(n+1);
vector<int> dis(n+1,0);
for(i=0;i<m;i++)
{
cin>>u>>v;
adj[u].push_back(v);
adj[v].push_back(u);
}
cin>>start;
bfs(adj,start,dis,n);
for(i=1;i<=n;i++)
{
if(start!=i)
cout<<dis[i]<<" ";
}
cout<<endl;
}
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
69
]
]
] |
4e89d201e9071b02907197f3ed2bc6f329965e34 | a764bdaf1b24a8257648537d14e6a9f02edd7af8 | /src/Location.h | 4bec0c1d8d57e464b5a7022d5e47f7715cc21eab | [
"MIT"
] | permissive | jonatajefferson/irp | ced568bb82dcfcd29da54c1e8f48a8ab43b6d6fd | 7171a506550eac8b3a8683b2d4dba198969828b3 | refs/heads/master | 2021-01-17T01:52:01.615145 | 2015-11-25T18:21:14 | 2015-11-25T18:21:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 990 | h | #ifndef LOCATION_H
#define LOCATION_H
#include <vector>
class Base;
class Customer;
class Source;
class Location
{
public:
Location();
Location(int index, std::vector<Base*> &neighborsBases, std::vector<Customer*> &neighborsCustomers, std::vector<Source*> &neighborsSources);
enum Type{BASE, CUSTOMER, SOURCE};
virtual ~Location();
int getIndex();
std::vector<Base*> getNeighborsBases() const;
std::vector<Customer*> getNeighborsCustomers() const;
std::vector<Source*> getNeighborsSources() const;
void setIndex(int);
void setNeighborsBases(std::vector<Base*>);
void setNeighborsCustomers(std::vector<Customer*>);
void setNeighborsSources(std::vector<Source*>);
protected:
int index_;
std::vector<Base*> neighborsBases_;
std::vector<Customer*> neighborsCustomers_;
std::vector<Source*> neighborsSources_;
Type type_;
};
#endif // LOCATION_H
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
20
],
[
22,
34
]
],
[
[
21,
21
]
]
] |
da305b7fa058459e59591d534b6f8ccafc370f33 | e542234cbf0eea3883b934ee67f97326377de02f | /EnemySnipper.hpp | 194187a1b40c4a3a73a79907b77035df6c48f895 | [
"MIT"
] | permissive | kaitokidi/WhoTookMyHat | 8e66e510e10451a3499a2fa361c8892e8f7b818f | dc4ebdbe880a10cb681bf2749095f4bbbbe51f88 | refs/heads/master | 2021-04-19T00:56:37.700324 | 2016-10-27T22:29:11 | 2016-10-27T22:29:11 | 51,254,343 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 459 | hpp | #ifndef ENEMYSNIPPER_HPP
#define ENEMYSNIPPER_HPP
#include "Enemy.hpp"
#include "Player.hpp"
#include "EnemyShooter.hpp"
class EnemySnipper : public Enemy, public EnemyShooter {
public:
//TODO
virtual void init();
EnemySnipper(std::list < Enemy* >* e, Player* p);
virtual void update(float deltaTime, Background* bg);
virtual void movement(float deltaTime, Background *bg);
protected:
Player* _player;
};
#endif // ENEMYSNIPPER_HPP
| [
"[email protected]"
] | [
[
[
1,
19
]
]
] |
8cd8538339e5a1170a27aef802a5f18cacfeeeab | 6115a9fffbc4e0d94a8aae1bffe79557ae059a09 | /FinalProject/avltreeindex.h | 2f774eea408d83aa6352573bdd3f0f40ebf8690f | [] | no_license | natesotoole1/SearchEngine | 74bc40a3b438758699a9f3a662a61c9f72125a96 | b3623634acda01f9135e80cd7d00deae3d8f756c | refs/heads/master | 2021-01-16T22:08:15.300799 | 2016-04-12T12:39:08 | 2016-04-12T12:39:08 | 45,565,794 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,139 | h |
#ifndef AVLTreeIndex_H
#define AVLTreeIndex_H
#include <iostream>
#include <fstream>
#include <string>
#include <cstdio>
#include "indexinterface.h"
#include "term.h"
// git
using namespace std;
/*! \brief
* AVL Node implementation for the AVL Tree structure.
*/
// Node declaration
struct AVL_Node
{
Term* data;///< Term pointer where all the data is held
//struct AVL_Node root;
struct AVL_Node *left; ///< left child
struct AVL_Node *right; ///< right child
int height; ///< height of tree
};
/*! \brief
* AVLTreeIndex.h has AVL Trees public and private classes in them.
*/
// Class declaration
class AVLTreeIndex
{
public:
AVLTreeIndex(); ///< constructor
void insert(Term*); ///< public insert function that calls the private function
AVL_Node* balance(AVL_Node*&); ///< figures out when to rotate child or not
int height(AVL_Node *&); ///< returns the height of the tree
int diff(AVL_Node *&); ///< returns the difference in height
int max(int, int); ///< gets the max height
AVL_Node* rotateRightChild(AVL_Node*&); ///< rotate right child
AVL_Node* rotateLeftChild(AVL_Node*&); ///< rotate left child
AVL_Node* doubleLeftChild(AVL_Node*&); ///< rotate left child than rotate right child
AVL_Node* doubleRightChild(AVL_Node*&); ///< rotate right child than rotate left child
Term* find(string); ///< public find function that is called from the interface and than passes it to private function
void createPersistence(int, ofstream&); ///< public call to create persistence than calls the private function
void clearTree(); ///< public call to clear index than calls the private function
private:
AVL_Node* root; ///< root of the tree
void insert(AVL_Node*& ,Term*); ///< inserts node if null than checks balance to see if it is needed to rotate
void createPersistence(AVL_Node*& , int, ofstream&); ///< creates the persistence from each individual avl tree
void continue_search(AVL_Node*& curr, string word); ///< finds word called by query
void clearTree(AVL_Node*); /// <clear the tree
};
#endif // AVLTreeINDEX_H
| [
"[email protected]"
] | [
[
[
1,
63
]
]
] |
31c05ddd07b9d79686913c8c08a00eaf1395abbb | 6fdd703d48a01bb73bf658c8d3aac0d98f965967 | /src_cpp/elfgames/go/train/data_loader.h | 472fb3d536934f874a4ab6fd4147fce6d3ed1d0d | [
"BSD-3-Clause"
] | permissive | roughsoft/ELF | 27f762aad66f4946411f2fdae71a45fabd028730 | 751eb1cf85aac15e3c3c792a47afa1ac64ea810c | refs/heads/master | 2020-03-25T19:54:55.579846 | 2018-08-08T21:34:11 | 2018-08-08T21:34:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,596 | h | /**
* Copyright (c) 2018-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include "../common/record.h"
#include "elf/distributed/shared_reader.h"
#include "elf/distributed/shared_rw_buffer2.h"
struct Stats {
std::atomic<int> client_size;
std::atomic<int> buffer_size;
std::atomic<int> failed_count;
std::atomic<int> msg_count;
std::atomic<uint64_t> total_msg_size;
Stats()
: client_size(0),
buffer_size(0),
failed_count(0),
msg_count(0),
total_msg_size(0) {}
std::string info() const {
std::stringstream ss;
ss << "#msg: " << buffer_size << " #client: " << client_size << ", ";
ss << "Msg count: " << msg_count
<< ", avg msg size: " << (float)(total_msg_size) / msg_count
<< ", failed count: " << failed_count;
return ss.str();
}
void feed(const elf::shared::InsertInfo& insert_info) {
if (!insert_info.success) {
failed_count++;
} else {
buffer_size += insert_info.delta;
msg_count++;
total_msg_size += insert_info.msg_size;
}
}
};
class DataInterface {
public:
virtual void OnStart() {}
virtual elf::shared::InsertInfo OnReceive(
const std::string& identity,
const std::string& msg) = 0;
virtual bool OnReply(const std::string& identity, std::string* msg) = 0;
};
class DataOnlineLoader {
public:
DataOnlineLoader(const elf::shared::Options& net_options)
: logger_(elf::logging::getLogger("DataOnlineLoader-", "")) {
auto curr_timestamp = time(NULL);
const std::string database_name =
"data-" + std::to_string(curr_timestamp) + ".db";
reader_.reset(new elf::shared::Reader(database_name, net_options));
std::cout << reader_->info() << std::endl;
}
void start(DataInterface* interface) {
auto proc_func = [&, interface](
elf::shared::Reader* reader,
const std::string& identity,
const std::string& msg) -> bool {
(void)reader;
try {
auto info = interface->OnReceive(identity, msg);
stats_.feed(info);
/*
if (options_.verbose) {
std::cout << "Content from " << identity
<< ", msg_size: " << msg.size() << ", " << stats_.info()
<< std::endl;
}
*/
if (stats_.msg_count % 1000 == 0) {
std::cout << elf_utils::now() << ", last_identity: " << identity
<< ", " << stats_.info() << std::endl;
}
return info.success;
} catch (...) {
logger_->error("Data malformed! String is {}", msg);
return false;
}
};
auto replier_func = [&, interface](
elf::shared::Reader* reader,
const std::string& identity,
std::string* msg) -> bool {
(void)reader;
interface->OnReply(identity, msg);
if (logger_->should_log(spdlog::level::level_enum::debug)) {
logger_->debug(
"Replier: about to send: recipient {}; msg {}; reader {}",
identity,
*msg,
reader_->info());
}
return true;
};
reader_->startReceiving(
proc_func, replier_func, [interface]() { interface->OnStart(); });
}
~DataOnlineLoader() {}
private:
std::unique_ptr<elf::shared::Reader> reader_;
Stats stats_;
std::shared_ptr<spdlog::logger> logger_;
};
| [
"[email protected]"
] | [
[
[
1,
126
]
]
] |
759a015ca9170f3456ab0ac5f3a1626efca68ad7 | 483428f23277dc3fd2fad6588de334fc9b8355d2 | /hpp/iOSDevice32/Release/uTPLb_MemoryStreamPool.hpp | bee8378fa9718a035cca20b9ad1bd10f11e6c5d4 | [] | no_license | gzwplato/LockBox3-1 | 7084932d329beaaa8169b94729c4b05c420ebe44 | 89e300b47f8c1393aefbec01ffb89ddf96306c55 | refs/heads/master | 2021-05-10T18:41:18.748523 | 2015-07-04T09:48:06 | 2015-07-04T09:48:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,375 | hpp | // CodeGear C++Builder
// Copyright (c) 1995, 2015 by Embarcadero Technologies, Inc.
// All rights reserved
// (DO NOT EDIT: machine generated header) 'uTPLb_MemoryStreamPool.pas' rev: 29.00 (iOS)
#ifndef Utplb_memorystreampoolHPP
#define Utplb_memorystreampoolHPP
#pragma delphiheader begin
#pragma option push
#pragma option -w- // All warnings off
#pragma option -Vx // Zero-length empty class member
#pragma pack(push,8)
#include <System.hpp>
#include <SysInit.hpp>
#include <System.Classes.hpp>
//-- user supplied -----------------------------------------------------------
namespace Utplb_memorystreampool
{
//-- forward type declarations -----------------------------------------------
__interface IMemoryStreamPool;
typedef System::DelphiInterface<IMemoryStreamPool> _di_IMemoryStreamPool;
class DELPHICLASS TPooledMemoryStream;
//-- type declarations -------------------------------------------------------
__interface INTERFACE_UUID("{ADB2D4BA-40F6-4249-923E-201D4719609B}") IMemoryStreamPool : public System::IInterface
{
virtual int __fastcall BayCount(void) = 0 ;
virtual void __fastcall GetUsage(int Size, int &Current, int &Peak) = 0 ;
virtual int __fastcall GetSize(int Idx) = 0 ;
virtual System::Classes::TMemoryStream* __fastcall NewMemoryStream(int InitSize) = 0 ;
};
#pragma pack(push,4)
class PASCALIMPLEMENTATION TPooledMemoryStream : public System::Classes::TMemoryStream
{
typedef System::Classes::TMemoryStream inherited;
protected:
_di_IMemoryStreamPool FPool;
int FCoVector;
virtual void * __fastcall Realloc(int &NewCapacity);
public:
__fastcall TPooledMemoryStream(const _di_IMemoryStreamPool Pool1);
public:
/* TMemoryStream.Destroy */ inline __fastcall virtual ~TPooledMemoryStream(void) { }
};
#pragma pack(pop)
//-- var, const, procedure ---------------------------------------------------
extern DELPHI_PACKAGE _di_IMemoryStreamPool __fastcall NewPool(void);
} /* namespace Utplb_memorystreampool */
#if !defined(DELPHIHEADER_NO_IMPLICIT_NAMESPACE_USE) && !defined(NO_USING_NAMESPACE_UTPLB_MEMORYSTREAMPOOL)
using namespace Utplb_memorystreampool;
#endif
#pragma pack(pop)
#pragma option pop
#pragma delphiheader end.
//-- end unit ----------------------------------------------------------------
#endif // Utplb_memorystreampoolHPP
| [
"[email protected]"
] | [
[
[
1,
66
]
]
] |
55d577d1a75a9ab17fa7b5d2dfee420f67de653e | c4d0cc1b8f7a0c4eefb405e105ac9727e1a98aad | /FlashCards/src/StringWordSplitter.cpp | fdab3206d76415785a84cd483dcc64795aae68ce | [] | no_license | KNITcpp/FlashCards | 513ed1f7fb2829692538636e0e6b65847bad8da9 | 7ac1c359d6a6f0aa5639bb64a39696b2f5eb63e2 | refs/heads/master | 2020-03-07T14:15:49.733326 | 2018-05-28T09:43:41 | 2018-05-28T09:43:41 | 127,522,390 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 505 | cpp |
#include "StringWordSplitter.h"
#include <string>
#include <vector>
StringWordSplitter::StringWordSplitter(std::wstring strToBeSplitted)
{
std::wstring singleWord;
for(int i=0; i<strToBeSplitted.length(); ++i)
{
if(strToBeSplitted[i] == L' ')
{
if(singleWord.size()!=0)
{
words.push_back(singleWord);
singleWord.clear();
}
}
else
singleWord.push_back(strToBeSplitted[i]);
}
if(singleWord.size()!=0) //something left to push after loop
words.push_back(singleWord);
}
| [
"[email protected]"
] | [
[
[
1,
26
]
]
] |
aaa8f706eca185ad9f7dd72dda3930415ee4cc22 | e4f29494a0ecb0a19b231a17e51127a7ddbfe387 | /TcpDebug.ino | 4c4d7c9df0d7cf9d84c51667ee552e72d3a97973 | [] | no_license | EvertDekker/Nixieclock3V1 | de9fb41a14decd21a2a86ba4914bc6c5b1839414 | 67a97d38f1895dbb285c541efe6988dcb04496fc | refs/heads/master | 2020-05-29T15:43:43.041005 | 2019-05-29T13:26:52 | 2019-05-29T13:26:52 | 189,228,943 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 436 | ino | void init_telnet_debug(){
#ifdef TELNET
if (MDNS.begin(hostn)) {
Serial.println("* MDNS responder started. Hostname -> ");
Serial.println(hostn);
}
MDNS.addService("telnet", "tcp", 23); // Initialize the telnet server of RemoteDebug
Debug.begin(hostn); // Initiaze the telnet server
Debug.setResetCmdEnabled(true); // Enable the reset command
//Debug.showTime(true); // To show time
#endif
}
| [
"[email protected]"
] | [
[
[
1,
12
]
]
] |
378d41da667801b00bd623eb7fc43dcdb5cc28d6 | 2bd4fa284f4c891fa35b7465449ea04534ea01fb | /hdmaproifilter/src/perception/lib/base/registerer.cpp | 6c5407d1b73c0605cbf0c3b88b4f854a302b290e | [] | no_license | Playfish/apollo_perception | cdd74e4a802159ceadc513e9f46ae1799e911ba1 | 6a50f529f0f6d789d2a06077480e79c9f4bc68c8 | refs/heads/master | 2021-09-14T13:42:07.159927 | 2018-05-14T13:51:20 | 2018-05-14T13:51:20 | 113,520,993 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,536 | cpp | /******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "perception/lib/base/registerer.h"
#include <string>
#include <vector>
namespace apollo {
namespace perception {
BaseClassMap& GlobalFactoryMap() {
static BaseClassMap factory_map;
return factory_map;
}
bool GetRegisteredClasses(
const std::string& base_class_name,
std::vector<std::string>* registered_derived_classes_names) {
CHECK_NOTNULL(registered_derived_classes_names);
BaseClassMap& map = GlobalFactoryMap();
auto iter = map.find(base_class_name);
if (iter == map.end()) {
AERROR << "class not registered:" << base_class_name;
return false;
}
for (auto pair : iter->second) {
registered_derived_classes_names->push_back(pair.first);
}
return true;
}
} // namespace perception
} // namespace apollo
| [
"[email protected]"
] | [
[
[
1,
47
]
]
] |
d968c4cfa9c0b7cc62efc1236b19bd9c23b807d5 | d78ab1e4cb8a669fbd4b5346683345c3926f4e07 | /Engine/script/runtimescriptvalue.h | 133267d203b3d4efedec67a08ef70fad569de9be | [
"LicenseRef-scancode-unknown-license-reference",
"Artistic-2.0"
] | permissive | sonneveld/ags | 4baca2321a1c1a13621322eb107d5338e9231fbf | 539a40a25f4caa7b7cec678084cfcde252418c77 | refs/heads/ags3--sdl2 | 2022-04-30T19:38:51.480211 | 2019-07-27T11:08:38 | 2019-11-03T06:53:44 | 40,235,193 | 2 | 0 | NOASSERTION | 2022-02-20T11:15:37 | 2015-08-05T08:54:39 | C | UTF-8 | C++ | false | false | 12,292 | h | //=============================================================================
//
// Adventure Game Studio (AGS)
//
// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
// The full list of copyright holders can be found in the Copyright.txt
// file, which is part of this source code distribution.
//
// The AGS source code is provided under the Artistic License 2.0.
// A copy of this license can be found in the file License.txt and at
// http://www.opensource.org/licenses/artistic-license-2.0.php
//
//=============================================================================
//
// Runtime script value struct
//
//=============================================================================
#ifndef __AGS_EE_SCRIPT__RUNTIMESCRIPTVALUE_H
#define __AGS_EE_SCRIPT__RUNTIMESCRIPTVALUE_H
#include "script/script_api.h"
#include "util/memory.h"
#include "ac/dynobj/cc_dynamicobject.h"
struct ICCStaticObject;
struct StaticArray;
enum ScriptValueType
{
kScValUndefined, // to detect errors
kScValInteger, // as strictly 32-bit integer (for integer math)
kScValFloat, // as float (for floating point math), 32-bit
kScValPluginArg, // an 32-bit value, passed to a script function when called
// directly by plugin; is allowed to represent object pointer
kScValStackPtr, // as a pointer to stack entry
kScValData, // as a container for randomly sized data (usually array)
kScValGlobalVar, // as a pointer to script variable; used only for global vars,
// as pointer to local vars must have StackPtr type so that the
// stack allocation could work
kScValStringLiteral,// as a pointer to literal string (array of chars)
kScValStaticObject, // as a pointer to static global script object
kScValStaticArray, // as a pointer to static global array (of static or dynamic objects)
kScValDynamicObject,// as a pointer to managed script object
kScValPluginObject, // as a pointer to object managed by plugin (similar to
// kScValDynamicObject, but has backward-compatible limitations)
kScValStaticFunction,// as a pointer to static function
kScValPluginFunction,// temporary workaround for plugins (unsafe function ptr)
kScValObjectFunction,// as a pointer to object member function, gets object pointer as
// first parameter
kScValCodePtr, // as a pointer to element in byte-code array
};
struct RuntimeScriptValue
{
public:
RuntimeScriptValue()
{
Type = kScValUndefined;
IValue = 0;
Ptr = nullptr;
MgrPtr = nullptr;
Size = 0;
}
RuntimeScriptValue(int32_t val)
{
Type = kScValInteger;
IValue = val;
Ptr = nullptr;
MgrPtr = nullptr;
Size = 4;
}
ScriptValueType Type;
// The 32-bit value used for integer/float math and for storing
// variable/element offset relative to object (and array) address
union
{
int32_t IValue; // access Value as int32 type
float FValue; // access Value as float type
};
// Pointer is used for storing... pointers - to objects, arrays,
// functions and stack entries (other RSV)
union
{
char *Ptr; // generic data pointer
RuntimeScriptValue *RValue;// access ptr as a pointer to Runtime Value
ScriptAPIFunction *SPfn; // access ptr as a pointer to Script API Static Function
ScriptAPIObjectFunction *ObjPfn; // access ptr as a pointer to Script API Object Function
};
// TODO: separation to Ptr and MgrPtr is only needed so far as there's
// a separation between Script*, Dynamic* and game entity classes.
// Once those classes are merged, it will no longer be needed.
union
{
void *MgrPtr;// generic object manager pointer
ICCStaticObject *StcMgr;// static object manager
StaticArray *StcArr;// static array manager
ICCDynamicObject *DynMgr;// dynamic object manager
};
// The "real" size of data, either one stored in I/FValue,
// or the one referenced by Ptr. Used for calculating stack
// offsets.
// Original AGS scripts always assumed pointer is 32-bit.
// Therefore for stored pointers Size is always 4 both for x32
// and x64 builds, so that the script is interpreted correctly.
int Size;
inline bool IsValid() const
{
return Type != kScValUndefined;
}
inline bool IsNull() const
{
return Ptr == nullptr && IValue == 0;
}
inline bool GetAsBool() const
{
return !IsNull();
}
inline char* GetPtrWithOffset() const
{
return Ptr + IValue;
}
inline RuntimeScriptValue &Invalidate()
{
Type = kScValUndefined;
IValue = 0;
Ptr = nullptr;
MgrPtr = nullptr;
Size = 0;
return *this;
}
inline RuntimeScriptValue &SetUInt8(uint8_t val)
{
Type = kScValInteger;
IValue = val;
Ptr = nullptr;
MgrPtr = nullptr;
Size = 1;
return *this;
}
inline RuntimeScriptValue &SetInt16(int16_t val)
{
Type = kScValInteger;
IValue = val;
Ptr = nullptr;
MgrPtr = nullptr;
Size = 2;
return *this;
}
inline RuntimeScriptValue &SetInt32(int32_t val)
{
Type = kScValInteger;
IValue = val;
Ptr = nullptr;
MgrPtr = nullptr;
Size = 4;
return *this;
}
inline RuntimeScriptValue &SetFloat(float val)
{
Type = kScValFloat;
FValue = val;
Ptr = nullptr;
MgrPtr = nullptr;
Size = 4;
return *this;
}
inline RuntimeScriptValue &SetInt32AsBool(bool val)
{
return SetInt32(val ? 1 : 0);
}
inline RuntimeScriptValue &SetFloatAsBool(bool val)
{
return SetFloat(val ? 1.0F : 0.0F);
}
inline RuntimeScriptValue &SetPluginArgument(int32_t val)
{
Type = kScValPluginArg;
IValue = val;
Ptr = nullptr;
MgrPtr = nullptr;
Size = 4;
return *this;
}
inline RuntimeScriptValue &SetStackPtr(RuntimeScriptValue *stack_entry)
{
Type = kScValStackPtr;
IValue = 0;
RValue = stack_entry;
MgrPtr = nullptr;
Size = 4;
return *this;
}
inline RuntimeScriptValue &SetData(char *data, int size)
{
Type = kScValData;
IValue = 0;
Ptr = data;
MgrPtr = nullptr;
Size = size;
return *this;
}
inline RuntimeScriptValue &SetGlobalVar(RuntimeScriptValue *glvar_value)
{
Type = kScValGlobalVar;
IValue = 0;
RValue = glvar_value;
MgrPtr = nullptr;
Size = 4;
return *this;
}
// TODO: size?
inline RuntimeScriptValue &SetStringLiteral(const char *str)
{
Type = kScValStringLiteral;
IValue = 0;
Ptr = const_cast<char *>(str);
MgrPtr = nullptr;
Size = 4;
return *this;
}
inline RuntimeScriptValue &SetStaticObject(void *object, ICCStaticObject *manager)
{
Type = kScValStaticObject;
IValue = 0;
Ptr = (char*)object;
StcMgr = manager;
Size = 4;
return *this;
}
inline RuntimeScriptValue &SetStaticArray(void *object, StaticArray *manager)
{
Type = kScValStaticArray;
IValue = 0;
Ptr = (char*)object;
StcArr = manager;
Size = 4;
return *this;
}
inline RuntimeScriptValue &SetDynamicObject(void *object, ICCDynamicObject *manager)
{
Type = kScValDynamicObject;
IValue = 0;
Ptr = (char*)object;
DynMgr = manager;
Size = 4;
return *this;
}
inline RuntimeScriptValue &SetPluginObject(void *object, ICCDynamicObject *manager)
{
Type = kScValPluginObject;
IValue = 0;
Ptr = (char*)object;
DynMgr = manager;
Size = 4;
return *this;
}
inline RuntimeScriptValue &SetStaticFunction(ScriptAPIFunction *pfn)
{
Type = kScValStaticFunction;
IValue = 0;
SPfn = pfn;
MgrPtr = nullptr;
Size = 4;
return *this;
}
inline RuntimeScriptValue &SetPluginFunction(void *pfn)
{
Type = kScValPluginFunction;
IValue = 0;
Ptr = (char*)pfn;
MgrPtr = nullptr;
Size = 4;
return *this;
}
inline RuntimeScriptValue &SetObjectFunction(ScriptAPIObjectFunction *pfn)
{
Type = kScValObjectFunction;
IValue = 0;
ObjPfn = pfn;
MgrPtr = nullptr;
Size = 4;
return *this;
}
inline RuntimeScriptValue &SetCodePtr(char *ptr)
{
Type = kScValCodePtr;
IValue = 0;
Ptr = ptr;
MgrPtr = nullptr;
Size = 4;
return *this;
}
inline RuntimeScriptValue operator !() const
{
return RuntimeScriptValue().SetInt32AsBool(!GetAsBool());
}
inline bool operator ==(const RuntimeScriptValue &rval)
{
return ((intptr_t)Ptr + (intptr_t)IValue) == ((intptr_t)rval.Ptr + (intptr_t)rval.IValue);
}
inline bool operator !=(const RuntimeScriptValue &rval)
{
return !(*this == rval);
}
// FIXME: find out all certain cases when we are reading a pointer and store it
// as 32-bit value here. There should be a solution to distinct these cases and
// store value differently, otherwise it won't work for 64-bit build.
inline RuntimeScriptValue ReadValue()
{
RuntimeScriptValue rval;
switch(this->Type) {
case kScValStackPtr:
{
if (RValue->Type == kScValData)
{
rval.SetInt32(*(int32_t*)(RValue->GetPtrWithOffset() + this->IValue));
}
else
{
rval = *RValue;
}
}
break;
case kScValGlobalVar:
{
if (RValue->Type == kScValData)
{
rval.SetInt32(AGS::Common::Memory::ReadInt32LE(RValue->GetPtrWithOffset() + this->IValue));
}
else
{
rval = *RValue;
}
}
break;
case kScValStaticObject: case kScValStaticArray:
{
rval.SetInt32(this->StcMgr->ReadInt32(this->Ptr, this->IValue));
}
break;
case kScValDynamicObject:
{
rval.SetInt32(this->DynMgr->ReadInt32(this->Ptr, this->IValue));
}
break;
default:
{
// 64 bit: Memory reads are still 32 bit
rval.SetInt32(*(int32_t*)this->GetPtrWithOffset());
}
}
return rval;
}
// Helper functions for reading or writing values from/to
// object, referenced by this Runtime Value.
// Copy implementation depends on value type.
uint8_t ReadByte();
int16_t ReadInt16();
int32_t ReadInt32();
bool WriteByte(uint8_t val);
bool WriteInt16(int16_t val);
bool WriteInt32(int32_t val);
bool WriteValue(const RuntimeScriptValue &rval);
// Convert to most simple pointer type by resolving RValue ptrs and applying offsets;
// non pointer types are left unmodified
RuntimeScriptValue &DirectPtr();
// Similar to above, a slightly speed-optimised version for situations when we can
// tell for certain that we are expecting a pointer to the object and not its (first) field.
RuntimeScriptValue &DirectPtrObj();
// Resolve and return direct pointer to the referenced data; non pointer types return IValue
intptr_t GetDirectPtr() const;
};
#endif // __AGS_EE_SCRIPT__RUNTIMESCRIPTVALUE_H
| [
[
[
1,
2
],
[
15,
20
],
[
24,
31
],
[
33,
35
],
[
41,
45
],
[
51,
59
],
[
62,
68
],
[
71,
87
],
[
90,
114
],
[
116,
130
],
[
133,
139
],
[
142,
148
],
[
151,
157
],
[
160,
166
],
[
169,
183
],
[
186,
193
],
[
195,
197
],
[
199,
199
],
[
201,
202
],
[
204,
206
],
[
208,
208
],
[
210,
210
],
[
213,
216
],
[
218,
220
],
[
223,
261
],
[
263,
265
],
[
268,
270
],
[
281,
283
],
[
295,
312
],
[
364,
385
]
],
[
[
3,
14
],
[
21,
21
],
[
32,
32
],
[
36,
40
],
[
46,
50
],
[
88,
89
],
[
198,
198
],
[
200,
200
],
[
207,
207
],
[
209,
209
],
[
211,
211
],
[
262,
262
],
[
266,
266
],
[
271,
275
],
[
277,
280
],
[
284,
284
],
[
286,
293
]
],
[
[
22,
23
],
[
313,
363
]
],
[
[
60,
61
],
[
69,
70
],
[
115,
115
],
[
131,
132
],
[
140,
141
],
[
149,
150
],
[
158,
159
],
[
167,
168
],
[
184,
185
],
[
194,
194
],
[
203,
203
],
[
212,
212
],
[
217,
217
],
[
221,
222
],
[
267,
267
],
[
276,
276
],
[
285,
285
],
[
294,
294
]
]
] |
|
d43be44d339e4c748144208e5d4bd8fe9a5894e7 | 3368db882d23eba1fd8046d9e46583d7324d4dea | /Lesson 6/source/06.) Textures/win_OpenGLApp.cpp | 2a8751f01791f7cd05950c39fb5a5f26b9865e4b | [] | no_license | Juniperbrew/MS-OpenGLTutorial-Win32 | 8313923fc34948aafd7bc71de8d99552f734a454 | 6f6908999f1d887e41e311c019ab96724a60ac24 | refs/heads/master | 2021-01-10T16:39:55.731220 | 2016-01-02T09:49:59 | 2016-01-02T09:49:59 | 48,902,337 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,077 | cpp | #include "common_header.h"
#include "win_OpenGLApp.h"
COpenGLWinApp appMain;
char Keys::kp[256] = {0};
/*-----------------------------------------------
Name: key
Params: iKey - virtual key code
Result: Return true if key is pressed.
/*---------------------------------------------*/
int Keys::key(int iKey)
{
return (GetAsyncKeyState(iKey)>>15)&1;
}
/*-----------------------------------------------
Name: onekey
Params: iKey - virtual key code
Result: Return true if key was pressed, but only
once (the key must be released).
/*---------------------------------------------*/
int Keys::onekey(int iKey)
{
if(key(iKey) && !kp[iKey]){kp[iKey] = 1; return 1;}
if(!key(iKey))kp[iKey] = 0;
return 0;
}
/*-----------------------------------------------
Name: resetTimer
Params: none
Result: Resets application timer (for example
after re-activation of application).
/*---------------------------------------------*/
void COpenGLWinApp::resetTimer()
{
tLastFrame = clock();
fFrameInterval = 0.0f;
}
/*-----------------------------------------------
Name: updateTimer
Params: none
Result: Updates application timer.
/*---------------------------------------------*/
void COpenGLWinApp::updateTimer()
{
clock_t tCur = clock();
fFrameInterval = float(tCur-tLastFrame)/float(CLOCKS_PER_SEC);
tLastFrame = tCur;
}
/*-----------------------------------------------
Name: sof
Params: fVal
Result: Stands for speed optimized float.
/*---------------------------------------------*/
float COpenGLWinApp::sof(float fVal)
{
return fVal*fFrameInterval;
}
/*-----------------------------------------------
Name: initializeApp
Params: a_sAppName
Result: Initializes app with specified (unique)
application identifier.
/*---------------------------------------------*/
bool COpenGLWinApp::initializeApp(string a_sAppName)
{
sAppName = a_sAppName;
hMutex = CreateMutex(NULL, 1, sAppName.c_str());
if(GetLastError() == ERROR_ALREADY_EXISTS)
{
MessageBox(NULL, "This application already runs!", "Multiple Instances Found.", MB_ICONINFORMATION | MB_OK);
return 0;
}
return 1;
}
/*-----------------------------------------------
Name: registerAppClass
Params: a_hInstance - application instance handle
Result: Registers application window class.
/*---------------------------------------------*/
LRESULT CALLBACK globalMessageHandler(HWND hWnd, UINT uiMsg, WPARAM wParam, LPARAM lParam)
{
return appMain.msgHandlerMain(hWnd, uiMsg, wParam, lParam);
}
void COpenGLWinApp::registerAppClass(HINSTANCE a_hInstance)
{
WNDCLASSEX wcex;
memset(&wcex, 0, sizeof(WNDCLASSEX));
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_OWNDC;
wcex.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wcex.hIcon = LoadIcon(hInstance, IDI_WINLOGO);
wcex.hIconSm = LoadIcon(hInstance, IDI_WINLOGO);
wcex.hCursor = LoadCursor(hInstance, IDC_ARROW);
wcex.hInstance = hInstance;
wcex.lpfnWndProc =
globalMessageHandler;
wcex.lpszClassName = sAppName.c_str();
wcex.lpszMenuName = NULL;
RegisterClassEx(&wcex);
}
/*-----------------------------------------------
Name: createWindow
Params: sTitle - title of created window
Result: Creates main application window.
/*---------------------------------------------*/
bool COpenGLWinApp::createWindow(string sTitle)
{
if(MessageBox(NULL, "Would you like to run in fullscreen?", "Fullscreen", MB_ICONQUESTION | MB_YESNO) == IDYES)
{
DEVMODE dmSettings = {0};
EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dmSettings); // Get current display settings
hWnd = CreateWindowEx(0, sAppName.c_str(), sTitle.c_str(), WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, // This is the commonly used style for fullscreen
0, 0, dmSettings.dmPelsWidth, dmSettings.dmPelsHeight, NULL,
NULL, hInstance, NULL);
}
else hWnd = CreateWindowEx(0, sAppName.c_str(), sTitle.c_str(), WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
0, 0, CW_USEDEFAULT, CW_USEDEFAULT, NULL,
NULL, hInstance, NULL);
if(!oglControl.initOpenGL(hInstance, &hWnd, 3, 3, initScene, renderScene, releaseScene, &oglControl))return false;
ShowWindow(hWnd, SW_SHOW);
// Just to send WM_SIZE message again
ShowWindow(hWnd, SW_SHOWMAXIMIZED);
UpdateWindow(hWnd);
return true;
}
/*-----------------------------------------------
Name: appBody
Params: none
Result: Main application body infinite loop.
/*---------------------------------------------*/
void COpenGLWinApp::appBody()
{
MSG msg;
while(1)
{
if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
if(msg.message == WM_QUIT)break; // If the message was WM_QUIT then exit application
else
{
TranslateMessage(&msg); // Otherwise send message to appropriate window
DispatchMessage(&msg);
}
}
else if(bAppActive)
{
updateTimer();
oglControl.render(&oglControl);
}
else Sleep(200); // Do not consume processor power if application isn't active
}
}
/*-----------------------------------------------
Name: shutdown
Params: none
Result: Shuts down application and releases used
memory.
/*---------------------------------------------*/
void COpenGLWinApp::shutdown()
{
oglControl.releaseOpenGLControl(&oglControl);
DestroyWindow(hWnd);
UnregisterClass(sAppName.c_str(), hInstance);
COpenGLControl::unregisterSimpleOpenGLClass(hInstance);
ReleaseMutex(hMutex);
}
/*-----------------------------------------------
Name: msgHandlerMain
Params: whatever
Result: Application messages handler.
/*---------------------------------------------*/
LRESULT CALLBACK COpenGLWinApp::msgHandlerMain(HWND hWnd, UINT uiMsg, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
switch(uiMsg)
{
case WM_PAINT:
BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
break;
case WM_CLOSE:
PostQuitMessage(0);
break;
case WM_ACTIVATE:
{
switch(LOWORD(wParam))
{
case WA_ACTIVE:
case WA_CLICKACTIVE:
bAppActive = true;
resetTimer();
break;
case WA_INACTIVE:
bAppActive = false;
break;
}
break;
}
case WM_SIZE:
oglControl.resizeOpenGLViewportFull();
oglControl.setProjection3D(45.0f, float(LOWORD(lParam))/float(HIWORD(lParam)), 0.001f, 1000.0f);
break;
default:
return DefWindowProc(hWnd, uiMsg, wParam, lParam);
}
return 0;
}
/*-----------------------------------------------
Name: getInstance
Params: none
Result: Returns application instance.
/*---------------------------------------------*/
HINSTANCE COpenGLWinApp::getInstance()
{
return hInstance;
}
/*-----------------------------------------------
Name: msgHandlerMain
Params: whatever
Result: Application messages handler.
/*---------------------------------------------*/
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR sCmdLine, int iShow)
{
if(!appMain.initializeApp("06_opengl_3_3"))
return 0;
appMain.registerAppClass(hInstance);
if(!appMain.createWindow("06.) Textures - Tutorial by Michal Bubnar (www.mbsoftworks.sk)"))
return 0;
appMain.resetTimer();
appMain.appBody();
appMain.shutdown();
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
334
]
]
] |
8bfe178d65efb2f52470e306b87737b39f700ce6 | f80d267d410b784458e61e4c4603605de368de9b | /TESTONE/exampleios/usr/local/include/fit_developer_field_description.hpp | a5af5c51d16055664f81433af69b821385dd83c5 | [] | no_license | bleeckerj/Xcode-FIT-TEST | 84bdb9e1969a93a6380a9c64dce0a0e715d81fe8 | 37490e3b1e913dc3dfabdae39b48bddea24f1023 | refs/heads/master | 2021-01-20T14:39:53.249495 | 2017-02-22T05:59:28 | 2017-02-22T05:59:28 | 82,766,547 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,772 | hpp | ////////////////////////////////////////////////////////////////////////////////
// The following FIT Protocol software provided may be used with FIT protocol
// devices only and remains the copyrighted property of Dynastream Innovations Inc.
// The software is being provided on an "as-is" basis and as an accommodation,
// and therefore all warranties, representations, or guarantees of any kind
// (whether express, implied or statutory) including, without limitation,
// warranties of merchantability, non-infringement, or fitness for a particular
// purpose, are specifically disclaimed.
//
// Copyright 2017 Dynastream Innovations Inc.
////////////////////////////////////////////////////////////////////////////////
// ****WARNING**** This file is auto-generated! Do NOT edit this file.
// Profile Version = 20.24Release
// Tag = production/akw/20.24.01-0-g5fa480b
////////////////////////////////////////////////////////////////////////////////
#if !defined(FIT_DEVELOPER_FIELD_DESCRIPTION_HPP)
#define FIT_DEVELOPER_FIELD_DESCRIPTION_HPP
#include "fit_field_description_mesg.hpp"
#include "fit_developer_data_id_mesg.hpp"
#include <vector>
namespace fit
{
class DeveloperFieldDescription
{
public:
DeveloperFieldDescription() = delete;
DeveloperFieldDescription(const DeveloperFieldDescription& other);
DeveloperFieldDescription(const FieldDescriptionMesg& desc, const DeveloperDataIdMesg& developer);
virtual ~DeveloperFieldDescription();
FIT_UINT32 GetApplicationVersion() const;
FIT_UINT8 GetFieldDefinitionNumber() const;
std::vector<FIT_UINT8> GetApplicationId() const;
private:
FieldDescriptionMesg* description;
DeveloperDataIdMesg* developer;
};
} // namespace fit
#endif // defined(FIT_FIELD_DEFINITION_HPP)
| [
"[email protected]"
] | [
[
[
1,
46
]
]
] |
ec71eee9144a294508e930330ca1e438fb3fc919 | 32b88f828b33279cfe33420c2ed969131a7df987 | /Code/Core/Mem/MemTracker.cpp | 777a97039b84548fb8dbfdacb216b93ff26a076f | [
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | punitchandra/fastbuild | 53b51f001350104629e71434bb5e521a1bb63cae | 8a445d77343bc4881b33a5ebcf31a2ec8777ae2d | refs/heads/master | 2021-01-15T13:23:26.995800 | 2017-08-21T15:05:32 | 2017-08-21T15:05:32 | 38,138,811 | 0 | 0 | null | 2015-06-26T23:30:24 | 2015-06-26T23:30:23 | null | UTF-8 | C++ | false | false | 7,281 | cpp | // MemTracker.cpp
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include "Core/PrecompiledHeader.h"
#include "MemTracker.h"
//------------------------------------------------------------------------------
#if defined( MEMTRACKER_ENABLED )
// Includes
//------------------------------------------------------------------------------
#include "Core/Mem/MemPoolBlock.h"
#include "Core/Process/Atomic.h"
#include "Core/Process/Thread.h"
#include "Core/Tracing/Tracing.h"
// system
#include <memory.h> // for memset
// Static Data
//------------------------------------------------------------------------------
/*static*/ uint32_t MemTracker::s_Id( 0 );
/*static*/ bool MemTracker::s_Enabled( true );
/*static*/ bool MemTracker::s_Initialized( false );
/*static*/ uint32_t MemTracker::s_AllocationCount( 0 );
/*static*/ uint64_t MemTracker::s_Mutex[];
/*static*/ MemTracker::Allocation ** MemTracker::s_AllocationHashTable = nullptr;
/*static*/ MemPoolBlock * MemTracker::s_Allocations( nullptr );
// Thread-Local Data
//------------------------------------------------------------------------------
THREAD_LOCAL uint32_t g_MemTrackerDisabledOnThisThread( 0 );
// Defines
#define ALLOCATION_MINIMUM_ALIGN ( 0x4 ) // assume at least 4 byte alignment
#define ALLOCATION_HASH_SHIFT ( 0x2 ) // shift off lower bits
#define ALLOCATION_HASH_SIZE ( 0x100000 ) // one megabyte
#define ALLOCATION_HASH_MASK ( 0x0FFFFF ) // mask off upper bits
// Alloc
//------------------------------------------------------------------------------
/*static*/ void MemTracker::Alloc( void * ptr, size_t size, const char * file, int line )
{
if ( !s_Enabled )
{
return;
}
// handle allocations during initialization
if ( g_MemTrackerDisabledOnThisThread )
{
return;
}
++g_MemTrackerDisabledOnThisThread;
if ( !s_Initialized )
{
Init();
}
const size_t hashIndex = ( ( (size_t)ptr >> ALLOCATION_HASH_SHIFT ) & ALLOCATION_HASH_MASK );
{
MutexHolder mh( GetMutex() );
Allocation * a = (Allocation *)s_Allocations->Alloc( sizeof( Allocation ) );
++s_AllocationCount;
a->m_Id = ++s_Id;
a->m_Ptr = ptr;
a->m_Size = size;
a->m_Next = s_AllocationHashTable[ hashIndex ];
a->m_File = file;
a->m_Line = line;
static size_t breakOnSize = (size_t)-1;
static uint32_t breakOnId = 0;
if ( ( size == breakOnSize ) || ( a->m_Id == breakOnId ) )
{
BREAK_IN_DEBUGGER;
}
s_AllocationHashTable[ hashIndex ] = a;
}
--g_MemTrackerDisabledOnThisThread;
}
// Free
//------------------------------------------------------------------------------
/*static*/ void MemTracker::Free( void * ptr )
{
if ( !s_Enabled )
{
return;
}
if ( !s_Initialized )
{
return;
}
if ( g_MemTrackerDisabledOnThisThread )
{
return;
}
const size_t hashIndex = ( ( (size_t)ptr >> ALLOCATION_HASH_SHIFT ) & ALLOCATION_HASH_MASK );
MutexHolder mh( GetMutex() );
Allocation * a = s_AllocationHashTable[ hashIndex ];
Allocation * prev = nullptr;
while ( a )
{
if ( a->m_Ptr == ptr )
{
if ( prev == nullptr )
{
s_AllocationHashTable[ hashIndex ] = a->m_Next;
}
else
{
prev->m_Next = a->m_Next;
}
++g_MemTrackerDisabledOnThisThread;
s_Allocations->Free( a );
--s_AllocationCount;
--g_MemTrackerDisabledOnThisThread;
break;
}
prev = a;
a = a->m_Next;
}
}
// DumpAllocations
//------------------------------------------------------------------------------
/*static*/ void MemTracker::DumpAllocations()
{
if ( s_Enabled == false )
{
OUTPUT( "DumpAllocations failed - MemTracker not enabled\n" );
return;
}
if ( s_Initialized == false )
{
OUTPUT( "DumpAllocations : No allocations\n" );
return;
}
MutexHolder mh( GetMutex() );
if ( s_AllocationCount == 0 )
{
OUTPUT( "DumpAllocations : No allocations\n" );
return;
}
uint64_t total = 0;
uint64_t numAllocs = 0;
// for each leak, we'll print a view of the memory
unsigned char displayChar[256];
memset( displayChar, '.', sizeof( displayChar ) );
const unsigned char * okChars = (const unsigned char *)"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~`1234567890-=!@#$^&*()_+[]{};:'\",<>/?|\\";
const unsigned char * ok = okChars;
for ( ;; ) { unsigned char c = *ok; if ( c == 0 ) break; displayChar[ c ] = c; ++ok; }
char memView[ 32 ] = { 0 };
OUTPUT( "--- DumpAllocations ------------------------------------------------\n" );
for ( size_t i=0; i<ALLOCATION_HASH_SIZE; ++i )
{
Allocation * a = s_AllocationHashTable[ i ];
while ( a )
{
uint32_t id = a->m_Id;
uint64_t addr = (size_t)a->m_Ptr;
uint64_t size = a->m_Size;
// format a view of the memory contents
const char * src = (const char *)addr;
char * dst = memView;
const size_t num = Math::Min< size_t >( (size_t)size, 31 );
for ( uint32_t j=0; j<num; ++j )
{
unsigned char c = *src;
*dst = displayChar[ c ];
++src;
++dst;
}
*dst = 0;
OUTPUT( "%s(%u): Id %u : %u bytes @ 0x%016llx (Mem: %s)\n", a->m_File, a->m_Line, id, size, addr, memView );
++numAllocs;
total += size;
a = a->m_Next;
}
}
OUTPUT( "--------------------------------------------------------------------\n" );
OUTPUT( "Total: %llu bytes in %llu allocs\n", total, numAllocs );
OUTPUT( "--------------------------------------------------------------------\n" );
}
// Reset
//------------------------------------------------------------------------------
/*static*/ void MemTracker::Reset()
{
MutexHolder mh( GetMutex() );
++g_MemTrackerDisabledOnThisThread;
// free all allocation tracking
for ( size_t i=0; i<ALLOCATION_HASH_SIZE; ++i )
{
Allocation * a = s_AllocationHashTable[ i ];
while ( a )
{
s_Allocations->Free( a );
--s_AllocationCount;
a = a->m_Next;
}
s_AllocationHashTable[ i ] = nullptr;
}
ASSERT( s_AllocationCount == 0 );
s_Id = 0;
--g_MemTrackerDisabledOnThisThread;
}
// Init
//------------------------------------------------------------------------------
/*static*/ void MemTracker::Init()
{
CTASSERT( sizeof( MemTracker::s_Mutex ) == sizeof( Mutex ) );
ASSERT( g_MemTrackerDisabledOnThisThread );
// first caller does init
static uint32_t threadSafeGuard( 0 );
if ( AtomicIncU32( &threadSafeGuard ) != 1 )
{
// subsequent callers wait for init
while ( !s_Initialized ) {}
return;
}
// construct primary mutex in-place
INPLACE_NEW ( &GetMutex() ) Mutex;
// init hash table
s_AllocationHashTable = new Allocation*[ ALLOCATION_HASH_SIZE ];
memset( s_AllocationHashTable, 0, ALLOCATION_HASH_SIZE * sizeof( Allocation * ) );
// init pool for allocation structures
s_Allocations = new MemPoolBlock( sizeof( Allocation ), __alignof( Allocation ) );
MemoryBarrier();
s_Initialized = true;
}
//------------------------------------------------------------------------------
#endif // MEMTRACKER_ENABLED
//------------------------------------------------------------------------------
| [
"[email protected]"
] | [
[
[
1,
274
]
]
] |
95f7befcf665c6bd7d6cf9cdcc561666e56f2e88 | cf88c1e3d9587f2bdc8cf40397bca3f0b5f11e7c | /Arrays/Array_Rearrangement/MaxLengthBitonicSubsequence.cpp | fb2e5de210006b85afeb4f3b2d78fe1f36e1b413 | [] | no_license | shaival141/Practice_Old | f6193b4ae2365548d70c047180de429f9a9fdc1d | f02d55faf1c0a861093bf0e094747c64bdd81b34 | refs/heads/master | 2022-01-05T12:54:54.863035 | 2018-05-18T18:05:06 | 2018-05-18T18:05:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,321 | cpp | /* Dynamic Programming implementation of longest bitonic subsequence problem */
#include<stdio.h>
#include<stdlib.h>
/* lbs() returns the length of the Longest Bitonic Subsequence in
arr[] of size n. The function mainly creates two temporary arrays
lis[] and lds[] and returns the maximum lis[i] + lds[i] - 1.
lis[i] ==> Longest Increasing subsequence ending with arr[i]
lds[i] ==> Longest decreasing subsequence starting with arr[i]
*/
int lbs( int arr[], int n )
{
int i,j;
int lis[n];
int lds[n];
for(i=0;i<n;i++)
lis[i]=1;
for(i=0;i<n;i++)
lds[i]=1;
for(i=1;i<n;i++)
{
for(j=0;j<i;j++)
{
if(arr[j]<arr[i] && lis[i]<lis[j]+1)
lis[i]=lis[j]+1;
}
}
for(i=n-1;i>=0;i--)
{
for(j=n-1;j>i;j--)
{
if(arr[j]<arr[i] && lds[i]<lds[j]+1)
lds[i]=lds[j]+1;
}
}
int max=0;
for(i=0;i<n;i++)
{
if(lis[i]+lds[i]-1>max)
{
max =lis[i] + lds[i] - 1;
}
}
return max;
}
/* Driver program to test above function */
int main()
{
int arr[] = {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5,
13, 3, 11, 7, 15};
int n = sizeof(arr)/sizeof(arr[0]);
printf("Length of LBS is %d\n", lbs( arr, n ) );
return 0;
} | [
"[email protected]"
] | [
[
[
1,
57
]
]
] |
3839e99ec45940f1c94baf2131e7849a8871b51c | 4f37081ed62e44afa0b2465388a8adf9b5490b13 | /ash/login/ui/login_user_view.h | 4d27549c5a7f8e8dda6fd0bc769f65efd3439630 | [
"BSD-3-Clause"
] | permissive | zowhair/chromium | 05b9eed58a680941c3595d52c3c77b620ef2c3ac | d84d5ef83e401ec210fcb14a92803bf339e1ccce | refs/heads/master | 2023-03-04T23:15:10.914156 | 2018-03-15T11:27:44 | 2018-03-15T11:27:44 | 125,359,706 | 1 | 0 | null | 2018-03-15T11:50:44 | 2018-03-15T11:50:43 | null | UTF-8 | C++ | false | false | 3,544 | h | // 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.
#ifndef ASH_LOGIN_UI_LOGIN_USER_VIEW_H_
#define ASH_LOGIN_UI_LOGIN_USER_VIEW_H_
#include "ash/ash_export.h"
#include "ash/login/ui/login_display_style.h"
#include "ash/public/interfaces/login_user_info.mojom.h"
#include "base/macros.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/view.h"
namespace ash {
class HoverNotifier;
class LoginBubble;
class LoginButton;
// Display the user's profile icon, name, and a menu icon in various layout
// styles.
class ASH_EXPORT LoginUserView : public views::View,
public views::ButtonListener {
public:
// TestApi is used for tests to get internal implementation details.
class ASH_EXPORT TestApi {
public:
explicit TestApi(LoginUserView* view);
~TestApi();
LoginDisplayStyle display_style() const;
const base::string16& displayed_name() const;
views::View* user_label() const;
views::View* tap_button() const;
bool is_opaque() const;
private:
LoginUserView* const view_;
};
using OnTap = base::RepeatingClosure;
// Returns the width of this view for the given display style.
static int WidthForLayoutStyle(LoginDisplayStyle style);
LoginUserView(LoginDisplayStyle style,
bool show_dropdown,
bool show_domain,
const OnTap& on_tap);
~LoginUserView() override;
// Update the user view to display the given user information.
void UpdateForUser(const mojom::LoginUserInfoPtr& user, bool animate);
// Set if the view must be opaque.
void SetForceOpaque(bool force_opaque);
// Enables or disables tapping the view.
void SetTapEnabled(bool enabled);
const mojom::LoginUserInfoPtr& current_user() const { return current_user_; }
// views::View:
const char* GetClassName() const override;
gfx::Size CalculatePreferredSize() const override;
void Layout() override;
// views::ButtonListener:
void ButtonPressed(views::Button* sender, const ui::Event& event) override;
private:
class UserDomainInfoView;
class UserImage;
class UserLabel;
class TapButton;
// Called when hover state changes.
void OnHover(bool has_hover);
// Updates UI element values so they reflect the data in |current_user_|.
void UpdateCurrentUserState();
// Updates view opacity based on input state and |force_opaque_|.
void UpdateOpacity();
void SetLargeLayout();
void SetSmallishLayout();
// Executed when the user view is pressed.
OnTap on_tap_;
// The user that is currently being displayed (or will be displayed when an
// animation completes).
mojom::LoginUserInfoPtr current_user_;
// Used to dispatch opacity update events.
std::unique_ptr<HoverNotifier> hover_notifier_;
LoginDisplayStyle display_style_;
UserImage* user_image_ = nullptr;
UserLabel* user_label_ = nullptr;
LoginButton* user_dropdown_ = nullptr;
TapButton* tap_button_ = nullptr;
std::unique_ptr<LoginBubble> user_menu_;
// Show the domain information for public account user.
UserDomainInfoView* user_domain_ = nullptr;
// True iff the view is currently opaque (ie, opacity = 1).
bool is_opaque_ = false;
// True if the view must be opaque (ie, opacity = 1) regardless of input
// state.
bool force_opaque_ = false;
DISALLOW_COPY_AND_ASSIGN(LoginUserView);
};
} // namespace ash
#endif // ASH_LOGIN_UI_LOGIN_USER_VIEW_H_
| [
"[email protected]"
] | [
[
[
1,
123
]
]
] |
694381b4055f06ae7dad5f6a5f7b6abd76cc1bb2 | 4ca2b9af703d0a9066fdbf7ac45fd7c5f25a72ea | /proton-c/bindings/cpp/include/proton/codec/decoder.hpp | 3dc6d570d2c4b11fdffda5c5c32b4e67cdd0ed71 | [
"Apache-2.0",
"BSD-3-Clause"
] | permissive | gberginc/qpid-proton | 23847cc2a6b7014f021baff27089ea727bfa28e0 | 9eaca615c5f5aa97d89d1b87471d81bff7237df0 | refs/heads/master | 2021-01-16T17:58:30.964461 | 2017-08-10T12:27:43 | 2017-08-10T12:27:43 | 100,028,035 | 0 | 0 | null | 2017-08-11T12:13:02 | 2017-08-11T12:13:02 | null | UTF-8 | C++ | false | false | 7,621 | hpp | #ifndef PROTON_CODEC_DECODER_HPP
#define PROTON_CODEC_DECODER_HPP
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
#include "../internal/data.hpp"
#include "../internal/type_traits.hpp"
#include "../types_fwd.hpp"
#include "./common.hpp"
#include <proton/type_compat.h>
#include <utility>
namespace proton {
class annotation_key;
class message_id;
class scalar;
class value;
namespace internal {
class value_base;
}
namespace codec {
/// **Experimental** - Stream-like decoder from AMQP bytes to C++
/// values.
///
/// For internal use only.
///
/// @see @ref types_page for the recommended ways to manage AMQP data
class decoder : public internal::data {
public:
/// Wrap a Proton C data object. The exact flag if set means
/// decode only when there is an exact match between the AMQP and
/// C++ type. If not set then perform automatic conversions.
explicit decoder(const data& d, bool exact=false) : data(d), exact_(exact) {}
/// Attach decoder to a proton::value. The decoder is rewound to
/// the start of the data.
PN_CPP_EXTERN explicit decoder(const internal::value_base&, bool exact=false);
/// Decode AMQP data from a buffer and add it to the end of the
/// decoders stream.
PN_CPP_EXTERN void decode(const char* buffer, size_t size);
/// Decode AMQP data from a std::string and add it to the end of
/// the decoders stream.
PN_CPP_EXTERN void decode(const std::string&);
/// Return true if there are more value to extract at the current level.
PN_CPP_EXTERN bool more();
/// Get the type of the next value that will be read by
/// operator>>.
///
/// @throw conversion_error if no more values. @see
/// decoder::more().
PN_CPP_EXTERN type_id next_type();
/// @name Extract built-in types
///
/// @throw conversion_error if the decoder is empty or has an
/// incompatible type.
///
/// @{
PN_CPP_EXTERN decoder& operator>>(bool&);
PN_CPP_EXTERN decoder& operator>>(uint8_t&);
PN_CPP_EXTERN decoder& operator>>(int8_t&);
PN_CPP_EXTERN decoder& operator>>(uint16_t&);
PN_CPP_EXTERN decoder& operator>>(int16_t&);
PN_CPP_EXTERN decoder& operator>>(uint32_t&);
PN_CPP_EXTERN decoder& operator>>(int32_t&);
PN_CPP_EXTERN decoder& operator>>(wchar_t&);
PN_CPP_EXTERN decoder& operator>>(uint64_t&);
PN_CPP_EXTERN decoder& operator>>(int64_t&);
PN_CPP_EXTERN decoder& operator>>(timestamp&);
PN_CPP_EXTERN decoder& operator>>(float&);
PN_CPP_EXTERN decoder& operator>>(double&);
PN_CPP_EXTERN decoder& operator>>(decimal32&);
PN_CPP_EXTERN decoder& operator>>(decimal64&);
PN_CPP_EXTERN decoder& operator>>(decimal128&);
PN_CPP_EXTERN decoder& operator>>(uuid&);
PN_CPP_EXTERN decoder& operator>>(std::string&);
PN_CPP_EXTERN decoder& operator>>(symbol&);
PN_CPP_EXTERN decoder& operator>>(binary&);
PN_CPP_EXTERN decoder& operator>>(message_id&);
PN_CPP_EXTERN decoder& operator>>(annotation_key&);
PN_CPP_EXTERN decoder& operator>>(scalar&);
PN_CPP_EXTERN decoder& operator>>(internal::value_base&);
PN_CPP_EXTERN decoder& operator>>(null&);
///@}
/// Start decoding a container type, such as an ARRAY, LIST or
/// MAP. This "enters" the container, more() will return false at
/// the end of the container. Call finish() to "exit" the
/// container and move on to the next value.
PN_CPP_EXTERN decoder& operator>>(start&);
/// Finish decoding a container type, and move on to the next
/// value in the stream.
PN_CPP_EXTERN decoder& operator>>(const finish&);
/// @cond INTERNAL
template <class T> struct sequence_ref { T& ref; sequence_ref(T& r) : ref(r) {} };
template <class T> struct associative_ref { T& ref; associative_ref(T& r) : ref(r) {} };
template <class T> struct pair_sequence_ref { T& ref; pair_sequence_ref(T& r) : ref(r) {} };
template <class T> static sequence_ref<T> sequence(T& x) { return sequence_ref<T>(x); }
template <class T> static associative_ref<T> associative(T& x) { return associative_ref<T>(x); }
template <class T> static pair_sequence_ref<T> pair_sequence(T& x) { return pair_sequence_ref<T>(x); }
/// @endcond
/// Extract any AMQP sequence (ARRAY, LIST or MAP) to a C++
/// sequence container of T if the elements types are convertible
/// to T. A MAP is extracted as `[key1, value1, key2, value2...]`.
template <class T> decoder& operator>>(sequence_ref<T> r) {
start s;
*this >> s;
if (s.is_described) next();
r.ref.resize(s.size);
for (typename T::iterator i = r.ref.begin(); i != r.ref.end(); ++i)
*this >> *i;
return *this;
}
/// Extract an AMQP MAP to a C++ associative container
template <class T> decoder& operator>>(associative_ref<T> r) {
using namespace internal;
start s;
*this >> s;
assert_type_equal(MAP, s.type);
r.ref.clear();
for (size_t i = 0; i < s.size/2; ++i) {
typename remove_const<typename T::key_type>::type k;
typename remove_const<typename T::mapped_type>::type v;
*this >> k >> v;
r.ref[k] = v;
}
return *this;
}
/// Extract an AMQP MAP to a C++ push_back sequence of pairs
/// preserving encoded order.
template <class T> decoder& operator>>(pair_sequence_ref<T> r) {
using namespace internal;
start s;
*this >> s;
assert_type_equal(MAP, s.type);
r.ref.clear();
for (size_t i = 0; i < s.size/2; ++i) {
typedef typename T::value_type value_type;
typename remove_const<typename value_type::first_type>::type k;
typename remove_const<typename value_type::second_type>::type v;
*this >> k >> v;
r.ref.push_back(value_type(k, v));
}
return *this;
}
private:
type_id pre_get();
template <class T, class U> decoder& extract(T& x, U (*get)(pn_data_t*));
bool exact_;
friend class message;
};
/// @cond INTERNAL
/// XXX Document this
template<class T> T get(decoder& d) {
assert_type_equal(internal::type_id_of<T>::value, d.next_type());
T x;
d >> x;
return x;
}
/// @endcond
/// operator>> for integer types that are not covered by the standard
/// overrides.
template <class T> typename internal::enable_if<internal::is_unknown_integer<T>::value, decoder&>::type
operator>>(decoder& d, T& i) {
using namespace internal;
typename integer_type<sizeof(T), is_signed<T>::value>::type v;
d >> v; // Extract as a known integer type
i = v; // C++ conversion to the target type.
return d;
}
} // codec
} // proton
#endif // PROTON_CODEC_DECODER_HPP
| [
[
[
1,
3
],
[
5,
5
],
[
22,
22
],
[
47,
48
],
[
50,
52
],
[
55,
57
],
[
60,
61
],
[
64,
65
],
[
68,
69
],
[
75,
79
],
[
83,
86
],
[
115,
118
],
[
121,
122
],
[
125,
125
],
[
133,
133
],
[
135,
137
],
[
148,
148
],
[
190,
191
],
[
198,
198
],
[
200,
201
],
[
213,
214
]
],
[
[
4,
4
],
[
6,
21
],
[
23,
24
],
[
29,
29
],
[
32,
39
],
[
42,
42
],
[
44,
46
],
[
49,
49
],
[
54,
54
],
[
58,
59
],
[
63,
63
],
[
66,
67
],
[
70,
74
],
[
80,
82
],
[
87,
110
],
[
112,
114
],
[
119,
120
],
[
123,
124
],
[
126,
132
],
[
134,
134
],
[
138,
147
],
[
149,
187
],
[
189,
189
],
[
192,
197
],
[
199,
199
],
[
202,
212
]
],
[
[
25,
28
],
[
30,
31
],
[
53,
53
],
[
188,
188
]
],
[
[
40,
41
],
[
43,
43
],
[
62,
62
],
[
111,
111
]
]
] |
|
594e71c07f5c14b0e47d84c3887fb2634517984c | 7a5a713cc999fdc1f64457949b003980e288567a | /Classes/ExplodeSmoke.h | a878d13147d91a026074988ee4903c9dfe3be564 | [] | no_license | highfence/ShootingGameProject | 2b564d09ea02ae64fb65d85b59ecb6e0d170ec53 | 61e57136d52e8b1d980eec304dd474774f239f94 | refs/heads/master | 2021-01-20T12:28:31.574956 | 2017-04-05T06:49:42 | 2017-04-05T06:49:42 | 82,655,552 | 0 | 0 | null | 2017-03-16T10:04:44 | 2017-02-21T08:33:06 | C++ | UTF-8 | C++ | false | false | 328 | h | #pragma once
#include "Effect.h"
class ExplodeSmoke : public Effect
{
public :
ExplodeSmoke() = delete;
ExplodeSmoke(const _In_ Vec);
ExplodeSmoke(
const _In_ Vec,
const _In_ FLOAT,
const _In_ Vec);
~ExplodeSmoke();
private :
void init();
void LoadInitialImg() override;
void InitialDataSubstitude() override;
}; | [
"[email protected]"
] | [
[
[
1,
20
]
]
] |
e1120ecc3bd0b1626b5a3a1c8eca3d090e2a14a8 | 8f961bc022f5ce587d854b7458909c3e0f1ef4bb | /framework/amorphous/Physics/Engines/PhysX/NxMathConv.hpp | b163b85dda141f7d07dd3f1265268ddae0095f82 | [] | no_license | takashikumagai/amorphous | 73f0bd8c5f5d947a71bbad696ce728f25c456aae | 8e5f5ec9368757a639ed4cf7aeb02a4b201e6b42 | refs/heads/master | 2020-05-17T10:55:59.428403 | 2018-07-05T02:48:59 | 2018-07-05T02:48:59 | 183,671,422 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,439 | hpp | #ifndef __NxMathConv_H__
#define __NxMathConv_H__
#include "3DMath/Matrix34.hpp"
#include "3DMath/AABB3.hpp"
#include "NxPhysics.h"
namespace amorphous
{
namespace physics
{
// PhysX to Framework conversions
inline Vector3 ToVector3( const NxVec3& src )
{
return Vector3( src.x, src.y, src.z );
}
inline Matrix33 ToMatrix33( const NxMat33& src )
{
return Matrix33(
ToVector3( src.getColumn(0) ),
ToVector3( src.getColumn(1) ),
ToVector3( src.getColumn(2) )
);
}
inline Matrix34 ToMatrix34( const NxMat34& src )
{
return Matrix34( ToVector3(src.t), ToMatrix33(src.M) );
}
inline AABB3 ToAABB3( const NxBounds3& src )
{
return AABB3( ToVector3(src.min), ToVector3(src.max) );
}
// Framework to PhysX conversions
inline NxVec3 ToNxVec3( const Vector3& src )
{
return NxVec3( src.x, src.y, src.z );
}
inline NxMat33 ToNxMat33( const Matrix33& src )
{
NxMat33 dest;
dest.setColumn( 0, ToNxVec3(src.GetColumn(0)) );
dest.setColumn( 1, ToNxVec3(src.GetColumn(1)) );
dest.setColumn( 2, ToNxVec3(src.GetColumn(2)) );
return dest;
}
inline NxMat34 ToNxMat34( const Matrix34& src )
{
NxMat34 dest;
dest.t = ToNxVec3( src.vPosition );
dest.M = ToNxMat33( src.matOrient );
return dest;
}
inline NxBounds3 ToNxBounds3( const AABB3& src )
{
NxBounds3 dest;
dest.set( ToNxVec3(src.vMin), ToNxVec3(src.vMax) );
return dest;
}
} // namespace physics
} // namespace amorphous
#endif /* __NxMathConv_H__ */
| [
"Takashi Kumagai@b80c8c75-5753-0c4f-8f2c-6ef837923b1e",
"blue@b80c8c75-5753-0c4f-8f2c-6ef837923b1e"
] | [
[
[
1,
5
],
[
7,
9
],
[
14,
16
],
[
18,
40
],
[
50,
71
],
[
79,
81
],
[
85,
86
]
],
[
[
6,
6
],
[
10,
13
],
[
17,
17
],
[
41,
49
],
[
72,
78
],
[
82,
84
]
]
] |
ca83a558bcc72c5055c6fbf661b26acbaf1aeb08 | 6701a2c3fb95baba0da5754b88d23f79a2b10f7f | /protocol/mcbp/libmcbp/mcbp_packet_printer.cc | 6329b15ffaeaf2a08d698518c5c195e5ef3a5e8b | [] | no_license | teligent-ru/kv_engine | 80630b4271d72df9c47b505a586f2e8275895d3e | 4a1b741ee22ae3e7a46e21a423451c58186a2374 | refs/heads/master | 2018-11-07T20:52:54.132785 | 2018-01-15T16:34:10 | 2018-01-17T08:29:54 | 117,808,163 | 1 | 0 | null | 2018-01-17T08:34:05 | 2018-01-17T08:34:05 | null | UTF-8 | C++ | false | false | 4,594 | cc | /* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2017 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <getopt.h>
#include <mcbp/mcbp.h>
#include <platform/dirutils.h>
#include <platform/memorymap.h>
#include <platform/sized_buffer.h>
#include <algorithm>
#include <iostream>
enum class Format { Raw, Gdb, Lldb };
Format parseFormat(std::string format) {
std::transform(format.begin(), format.end(), format.begin(), toupper);
if (format == "RAW") {
return Format::Raw;
}
if (format == "GDB") {
return Format::Gdb;
}
if (format == "LLDB") {
return Format::Lldb;
}
throw std::invalid_argument("Unknown format: " + format);
}
int main(int argc, char** argv) {
Format format{Format::Raw};
static struct option longopts[] = {
{"format", required_argument, nullptr, 'f'},
{nullptr, 0, nullptr, 0}};
int cmd;
while ((cmd = getopt_long(argc, argv, "f:", longopts, nullptr)) != -1) {
switch (cmd) {
case 'f':
try {
format = parseFormat(optarg);
} catch (const std::invalid_argument& e) {
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
break;
default:
std::cerr
<< "Usage: " << cb::io::basename(argv[0])
<< " [options] file1-n" << std::endl
<< std::endl
<< "\t--format=raw|gdb|lldb\tThe format for the input file"
<< std::endl
<< std::endl
<< "For gdb the expected output would be produced by "
"executing: "
<< std::endl
<< std::endl
<< "(gdb) x /24xb c->rcurr" << std::endl
<< "0x7f43387d7e7a: 0x81 0x0d 0x00 0x00 0x00 0x00 0x00 0x00"
<< std::endl
<< "0x7f43387d7e82: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00"
<< std::endl
<< "0x7f43387d7e8a: 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00"
<< std::endl
<< std::endl
<< "For lldb the expected output would be generated by "
"executing: "
<< std::endl
<< std::endl
<< "(lldb) x -c 32 c->rbuf" << std::endl
<< "0x7f43387d7e7a: 81 0d 00 01 04 00 00 00 00 00 00 06 00 "
"00 00 06 ................"
<< std::endl
<< "0x7f43387d7e7a: 14 bf f4 26 8a e0 00 00 00 00 00 00 61 "
"61 81 0a ................"
<< std::endl
<< std::endl;
return EXIT_FAILURE;
}
}
if (optind == argc) {
std::cerr << "No file specified" << std::endl;
return EXIT_FAILURE;
}
while (optind < argc) {
try {
cb::byte_buffer buf;
std::vector<uint8_t> data;
cb::MemoryMappedFile map(argv[optind],
cb::MemoryMappedFile::Mode::RDONLY);
map.open();
buf = {static_cast<uint8_t*>(map.getRoot()), map.getSize()};
switch (format) {
case Format::Raw:
break;
case Format::Gdb:
data = cb::mcbp::gdb::parseDump(buf);
buf = {data.data(), data.size()};
break;
case Format::Lldb:
data = cb::mcbp::lldb::parseDump(buf);
buf = {data.data(), data.size()};
break;
}
cb::mcbp::dumpStream(buf, std::cout);
} catch (const std::exception& error) {
std::cerr << error.what() << std::endl;
return EXIT_FAILURE;
}
++optind;
}
return EXIT_SUCCESS;
}
| [
"[email protected]"
] | [
[
[
1,
139
]
]
] |
160beafcd0375ee1abc289f6df9dc822b8749eb5 | 4b0a3fffa69840fac4fa77ba40f3aed8ae51442c | /FinalProject/workingfolder/Erin's Updates/bouncingcube/BouncingCube.h | a06731fe152c89b5848227598c4d455e34849b77 | [] | no_license | hoffm386/graphics-final-project | 732633bf55482051730e0087c025ab1d6e5253e7 | 584a16eda13572d6a92bad690da6b4a903eef084 | refs/heads/master | 2021-01-10T20:14:04.415740 | 2014-04-30T02:50:22 | 2014-04-30T02:50:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 725 | h |
// BouncingCube.h : main header file for the BouncingCube application
//
#pragma once
#ifndef __AFXWIN_H__
#error "include 'stdafx.h' before including this file for PCH"
#endif
#include "resource.h" // main symbols
// CBouncingCubeApp:
// See BouncingCube.cpp for the implementation of this class
//
class CBouncingCubeApp : public CWinAppEx
{
public:
CBouncingCubeApp();
// Overrides
public:
virtual BOOL InitInstance();
virtual int ExitInstance();
// Implementation
public:
UINT m_nAppLook;
BOOL m_bHiColorIcons;
virtual void PreLoadState();
virtual void LoadCustomState();
virtual void SaveCustomState();
afx_msg void OnAppAbout();
DECLARE_MESSAGE_MAP()
};
extern CBouncingCubeApp theApp;
| [
"[email protected]"
] | [
[
[
1,
43
]
]
] |
8ab716daca33856e610a208732527f0dd9de4e8e | 70d18762f2443bb5df8df38967bcd38277573cdb | /arch/generic/kernel/gen_ke_arch64.cpp | 1f2b16ecf52f14ac9a8389e3bec0a1176360b3fd | [] | no_license | 15831944/evita-common-lisp | f829defc5386cd1988754c59f2056f0367c77ed7 | cb2cbd3cc541878d25dcedb4abd88cf8e2c881d9 | refs/heads/master | 2021-05-27T16:35:25.208083 | 2013-12-01T06:21:32 | 2013-12-01T06:21:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,776 | cpp | //////////////////////////////////////////////////////////////////////////////
//
// evcl - kernel - arch 64
// kernel/ke_arch64.cpp
//
// This file is part of Evita Common Lisp.
//
// Copyright (C) 1996-2006 by Project Vogue.
// Written by Yoshifumi "VOGUE" INOUE. ([email protected])
//
// @(#)$Id: //proj/evcl3/mainline/arch/generic/kernel/gen_ke_arch64.cpp#3 $
//
#if SIZEOF_VAL == 8
#include "../../../kernel/ke_arch.h"
namespace Kernel
{
const uint64
Kernel::Arch64::k_rgfBit[64] =
{
1ull << 0, 1ull << 1, 1ull << 2, 1ull << 3, 1ull << 4,
1ull << 5, 1ull << 6, 1ull << 7, 1ull << 8, 1ull << 9,
1ull << 10, 1ull << 11, 1ull << 12, 1ull << 13, 1ull << 14,
1ull << 15, 1ull << 16, 1ull << 17, 1ull << 18, 1ull << 19,
1ull << 20, 1ull << 21, 1ull << 22, 1ull << 23, 1ull << 24,
1ull << 25, 1ull << 26, 1ull << 27, 1ull << 28, 1ull << 29,
1ull << 30, 1ull << 31, 1ull << 32, 1ull << 33, 1ull << 34,
1ull << 35, 1ull << 36, 1ull << 37, 1ull << 38, 1ull << 39,
1ull << 40, 1ull << 41, 1ull << 42, 1ull << 43, 1ull << 44,
1ull << 45, 1ull << 46, 1ull << 47, 1ull << 48, 1ull << 49,
1ull << 50, 1ull << 51, 1ull << 52, 1ull << 53, 1ull << 54,
1ull << 55, 1ull << 56, 1ull << 57, 1ull << 58, 1ull << 59,
1ull << 60, 1ull << 61, 1ull << 62, 1ull << 63
}; // Kernel::Arch64::k_rgfBit
//////////////////////////////////////////////////////////////////////
//
// Mask For Bit Stream Leader and Trailer
//
// Bit Stream:
// LLLL LLLL xxxx xxxx ... xxxx xxxx TTTT TTTT
//
// x = bits for processing
// L = leader bits (not affect)
// T = trailer bits (not affect)
//
// Note: Bit stream is stored in each 32bit word from LSB to MSB.
//
//
// (loop for i below 64 do (format t "0x~16,'0Xull, // ~D~%" (1- (ash 1 i)) i))
const Arch64::BitEltT
Arch64::k_rgnLeaderMask[64] =
{
0x0000000000000000ull, // 0
0x0000000000000001ull, // 1
0x0000000000000003ull, // 2
0x0000000000000007ull, // 3
0x000000000000000Full, // 4
0x000000000000001Full, // 5
0x000000000000003Full, // 6
0x000000000000007Full, // 7
0x00000000000000FFull, // 8
0x00000000000001FFull, // 9
0x00000000000003FFull, // 10
0x00000000000007FFull, // 11
0x0000000000000FFFull, // 12
0x0000000000001FFFull, // 13
0x0000000000003FFFull, // 14
0x0000000000007FFFull, // 15
0x000000000000FFFFull, // 16
0x000000000001FFFFull, // 17
0x000000000003FFFFull, // 18
0x000000000007FFFFull, // 19
0x00000000000FFFFFull, // 20
0x00000000001FFFFFull, // 21
0x00000000003FFFFFull, // 22
0x00000000007FFFFFull, // 23
0x0000000000FFFFFFull, // 24
0x0000000001FFFFFFull, // 25
0x0000000003FFFFFFull, // 26
0x0000000007FFFFFFull, // 27
0x000000000FFFFFFFull, // 28
0x000000001FFFFFFFull, // 29
0x000000003FFFFFFFull, // 30
0x000000007FFFFFFFull, // 31
0x00000000FFFFFFFFull, // 32
0x00000001FFFFFFFFull, // 33
0x00000003FFFFFFFFull, // 34
0x00000007FFFFFFFFull, // 35
0x0000000FFFFFFFFFull, // 36
0x0000001FFFFFFFFFull, // 37
0x0000003FFFFFFFFFull, // 38
0x0000007FFFFFFFFFull, // 39
0x000000FFFFFFFFFFull, // 40
0x000001FFFFFFFFFFull, // 41
0x000003FFFFFFFFFFull, // 42
0x000007FFFFFFFFFFull, // 43
0x00000FFFFFFFFFFFull, // 44
0x00001FFFFFFFFFFFull, // 45
0x00003FFFFFFFFFFFull, // 46
0x00007FFFFFFFFFFFull, // 47
0x0000FFFFFFFFFFFFull, // 48
0x0001FFFFFFFFFFFFull, // 49
0x0003FFFFFFFFFFFFull, // 50
0x0007FFFFFFFFFFFFull, // 51
0x000FFFFFFFFFFFFFull, // 52
0x001FFFFFFFFFFFFFull, // 53
0x003FFFFFFFFFFFFFull, // 54
0x007FFFFFFFFFFFFFull, // 55
0x00FFFFFFFFFFFFFFull, // 56
0x01FFFFFFFFFFFFFFull, // 57
0x03FFFFFFFFFFFFFFull, // 58
0x07FFFFFFFFFFFFFFull, // 59
0x0FFFFFFFFFFFFFFFull, // 60
0x1FFFFFFFFFFFFFFFull, // 61
0x3FFFFFFFFFFFFFFFull, // 62
0x7FFFFFFFFFFFFFFFull, // 63
}; // k_rgnLeaderMask
// (loop with x = (1- (ash 1 64)) for i below 64 for m = (1- (ash 1 i))
// do (format t " 0x~16,'0Xull, // ~D~%" (- x m) i) )
const Arch64::BitEltT
Arch64::k_rgnTrailerMask[64] =
{
0xFFFFFFFFFFFFFFFFull, // 0
0xFFFFFFFFFFFFFFFEull, // 1
0xFFFFFFFFFFFFFFFCull, // 2
0xFFFFFFFFFFFFFFF8ull, // 3
0xFFFFFFFFFFFFFFF0ull, // 4
0xFFFFFFFFFFFFFFE0ull, // 5
0xFFFFFFFFFFFFFFC0ull, // 6
0xFFFFFFFFFFFFFF80ull, // 7
0xFFFFFFFFFFFFFF00ull, // 8
0xFFFFFFFFFFFFFE00ull, // 9
0xFFFFFFFFFFFFFC00ull, // 10
0xFFFFFFFFFFFFF800ull, // 11
0xFFFFFFFFFFFFF000ull, // 12
0xFFFFFFFFFFFFE000ull, // 13
0xFFFFFFFFFFFFC000ull, // 14
0xFFFFFFFFFFFF8000ull, // 15
0xFFFFFFFFFFFF0000ull, // 16
0xFFFFFFFFFFFE0000ull, // 17
0xFFFFFFFFFFFC0000ull, // 18
0xFFFFFFFFFFF80000ull, // 19
0xFFFFFFFFFFF00000ull, // 20
0xFFFFFFFFFFE00000ull, // 21
0xFFFFFFFFFFC00000ull, // 22
0xFFFFFFFFFF800000ull, // 23
0xFFFFFFFFFF000000ull, // 24
0xFFFFFFFFFE000000ull, // 25
0xFFFFFFFFFC000000ull, // 26
0xFFFFFFFFF8000000ull, // 27
0xFFFFFFFFF0000000ull, // 28
0xFFFFFFFFE0000000ull, // 29
0xFFFFFFFFC0000000ull, // 30
0xFFFFFFFF80000000ull, // 31
0xFFFFFFFF00000000ull, // 32
0xFFFFFFFE00000000ull, // 33
0xFFFFFFFC00000000ull, // 34
0xFFFFFFF800000000ull, // 35
0xFFFFFFF000000000ull, // 36
0xFFFFFFE000000000ull, // 37
0xFFFFFFC000000000ull, // 38
0xFFFFFF8000000000ull, // 39
0xFFFFFF0000000000ull, // 40
0xFFFFFE0000000000ull, // 41
0xFFFFFC0000000000ull, // 42
0xFFFFF80000000000ull, // 43
0xFFFFF00000000000ull, // 44
0xFFFFE00000000000ull, // 45
0xFFFFC00000000000ull, // 46
0xFFFF800000000000ull, // 47
0xFFFF000000000000ull, // 48
0xFFFE000000000000ull, // 49
0xFFFC000000000000ull, // 50
0xFFF8000000000000ull, // 51
0xFFF0000000000000ull, // 52
0xFFE0000000000000ull, // 53
0xFFC0000000000000ull, // 54
0xFF80000000000000ull, // 55
0xFF00000000000000ull, // 56
0xFE00000000000000ull, // 57
0xFC00000000000000ull, // 58
0xF800000000000000ull, // 59
0xF000000000000000ull, // 60
0xE000000000000000ull, // 61
0xC000000000000000ull, // 62
0x8000000000000000ull, // 63
}; // k_rgnTrailerMask
CASSERT(sizeof(Arch64::k_rgnLeaderMask) == sizeof(Arch64::k_rgnTrailerMask));
} // Kernel
#endif // SIZEOF_VAL == 8
| [
"[email protected]"
] | [
[
[
1,
199
]
]
] |
ad1a3828949d014ce64f842d5f3e0ad0e9eaefc3 | 44289ecb892b6f3df043bab40142cf8530ac2ba4 | /Sources/Elastos/Frameworks/Droid/DevSamples/MemoryDumper/CMemoryDumper.h | a23684f02fd71ed7bb224705c8bdf2e8968a621a | [
"Apache-2.0"
] | permissive | warrenween/Elastos | a6ef68d8fb699fd67234f376b171c1b57235ed02 | 5618eede26d464bdf739f9244344e3e87118d7fe | refs/heads/master | 2021-01-01T04:07:12.833674 | 2017-06-17T15:34:33 | 2017-06-17T15:34:33 | 97,120,576 | 2 | 1 | null | 2017-07-13T12:33:20 | 2017-07-13T12:33:20 | null | UTF-8 | C++ | false | false | 2,368 | h | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#ifndef __ELASTOS_MEMORYDEUMPER_CMEMORYDUMPER_H__
#define __ELASTOS_MEMORYDEUMPER_CMEMORYDUMPER_H__
#include "elastos/droid/ext/frameworkext.h"
#include <elastos/core/Object.h>
#include <elastos/utility/etl/List.h>
using Elastos::Core::Object;
using Elastos::Utility::Etl::List;
namespace Elastos {
namespace MemoryDumper {
class CMemoryDumper
{
public:
static CARAPI SendDumpRequest();
static CARAPI OutputBackTrace(
/* [in] */ const String& diffFile,
/* [in] */ Int32 pid);
private:
class MapInfoManager
: public Object
{
public:
struct MapInfo {
struct MapInfo* next;
unsigned start;
unsigned end;
char name[];
};
MapInfoManager(
/* [in] */ Int32 pid);
~MapInfoManager();
MapInfo* miList;
CARAPI InitMapInfo(
/* [in] */ Int32 pid);
void DeinitMapInfo();
const char *Map2Name(
/* [in] */ unsigned pc,
/* [in] */ const char* def);
const MapInfo *Pc2Mapinfo(
/* [in] */ unsigned pc,
/* [out] */ unsigned *rel_pc);
private:
MapInfo* ParseMapsLine(
/* [in] */ char* line);
};
static CARAPI ProcessAllocEntry(
/* [in] */ char* oneLine,
/* [in] */ Int32 pid);
static CARAPI Print(
/* [in] */ List<String>* list,
/* [in] */ Int32 pid);
};
}
}
#endif // __ELASTOS_MEMORYDEUMPER_CMEMORYDUMPER_H__
| [
[
[
1,
16
],
[
34,
34
]
],
[
[
17,
17
],
[
20,
21
],
[
23,
24
],
[
26,
33
],
[
35,
40
],
[
44,
88
]
],
[
[
18,
19
],
[
22,
22
],
[
25,
25
],
[
41,
43
],
[
89,
89
]
]
] |
|
583d34be535e307cea59286df8c350b922d68244 | 4dabe3dca7a679a5ba7c79cd4e0384657657dec2 | /views/console/proposedCombinationView.cpp | 71f0f78cfcc080d0bf61444707db3121b212baf5 | [] | no_license | carlosv5/MasterMind | 47285e4a3b191294bc07650873fb13e46459e42d | b45c61a264c936191e8db23f27234b91943e7638 | refs/heads/master | 2020-04-20T12:26:51.642639 | 2019-05-11T19:05:23 | 2019-05-11T19:05:23 | 150,888,071 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,741 | cpp | #include <assert.h>
#include <iostream>
#include "proposedCombinationView.hpp"
#include "../../controllers/colocateController.hpp"
#include "../../models/proposedCombination.hpp"
using namespace std;
ProposedCombinationView::ProposedCombinationView(){};
ProposedCombination ProposedCombinationView::readProposedCombination(ProposedCombination proposedCombination, int SIZE_COMBINATION){
showColorOptions();
std::cout << "--Insert your colors (XXXX)--" << std::endl;
std::string combinationString;
getline(std::cin, combinationString);
char * combination = proposedCombination.getCombination();
for (int i = 0; i < SIZE_COMBINATION; i++)
{
char *colorArray = new char[Color::numberOfColors];
Color::values(colorArray);
bool isAColor = false;
for (int j = 0; j < Color::numberOfColors; j++)
{
if (combinationString[i] == colorArray[j])
{
isAColor = true;
}
}
assert(isAColor);
char colorToInsert = combinationString[i];
combination[i] = colorToInsert;
}
return proposedCombination;
}
void ProposedCombinationView::showColorOptions()
{
std::cout << "You can use these colors:" << std::endl;
char *colorArray = new char[Color::numberOfColors];
Color::values(colorArray);
for (int i = 0; i < Color::numberOfColors; i++)
{
std::cout << colorArray[i] << " ";
}
std::cout << std::endl;
delete (colorArray);
}
void ProposedCombinationView::printResults(ProposedCombination * proposedCombinations, int turn)
{
std::cout << "Results:" << std::endl;
for (int i = 0; i < turn + 1; i++){
for (int j = 0; j < proposedCombinations[0].getSize(); j++)
{
std::cout << "|" << proposedCombinations[i].getCombination()[j] << "|"
<< " ";
}
std::cout << "Results:|" << proposedCombinations[i].getResults()[INDEX_BLACK_RESULT] << " Blacks|" << proposedCombinations[i].getResults()[INDEX_WHITE_RESULT] << "Whites|"
<< " " << std::endl;
}
}
void ProposedCombinationView::printPreviewCombinations(ProposedCombination * proposedCombinations, int turn)
{
std::cout << "The board is:" << std::endl;
for (int i = 0; i < turn; i++){
for (int j = 0; j < proposedCombinations[0].getSize(); j++)
{
std::cout << "|" << proposedCombinations[i].getCombination()[j] << "|"
<< " ";
}
std::cout << "Results:|" << proposedCombinations[i].getResults()[INDEX_BLACK_RESULT] << " Blacks|" << proposedCombinations[i].getResults()[INDEX_WHITE_RESULT] << "Whites|"
<< " " << std::endl;
}
} | [
"[email protected]"
] | [
[
[
1,
79
]
]
] |
f2fd573fb8ac9dde4919620147f9c6d1cc0536a0 | d47ad8721876e05cc92a48ea772981dd2541d27c | /FPMLib/lib/bfc/autores.h | 78620a35bff0d40b0b1f790be9dc42de2b418042 | [] | no_license | cjld/ANNO-video | 5ac5f604d43e00a3ee8b2a40050413ffd8334c3e | e8ad4f1d617f8b2393db5241a40f98c156127e52 | refs/heads/master | 2021-01-25T06:45:24.164963 | 2017-06-12T15:54:19 | 2017-06-12T15:54:19 | 93,606,386 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,150 | h |
#ifndef _FF_BFC_AUTORES_H
#define _FF_BFC_AUTORES_H
#include <utility>
#include <iterator>
#include"ffdef.h"
_FF_BEG
//To help implement reference-counter in @AutoRes.
template<typename ValT>
class ReferenceCounter
{
typedef std::pair<int,ValT> _CounterT;
private:
_CounterT *_pdata;
void _inc() const
{
++_pdata->first;
}
void _dec() const
{
--_pdata->first;
}
public:
ReferenceCounter()
:_pdata(new _CounterT(1,ValT()))
{
}
ReferenceCounter(const ValT& val)
:_pdata(new _CounterT(1,val))
{
}
ReferenceCounter(const ReferenceCounter& right)
:_pdata(right._pdata)
{
this->_inc();
}
ReferenceCounter& operator=(const ReferenceCounter& right)
{
if(_pdata!=right._pdata)
{
if(this->IsLast())
delete _pdata;
else
this->_dec();
_pdata=right._pdata;
right._inc();
}
return *this;
}
//whether current reference is the last one.
bool IsLast() const
{
return _pdata->first==1;
}
//get the value stored with the counter.
const ValT& Value() const
{
return _pdata->second;
}
ValT& Value()
{
return _pdata->second;
}
//swap two counters.
void Swap(ReferenceCounter& right)
{
std::swap(this->_pdata,right._pdata);
}
~ReferenceCounter()
{
if(this->IsLast())
delete _pdata;
else
this->_dec();
}
};
//auto-resource, which is the base to implement AutoPtr,AutoArrayPtr and AutoComPtr.
template<typename PtrT,typename RetPtrT,typename ReleaseOpT>
class AutoRes
{
enum{_F_DETACHED=0x01};
struct _ValT
{
PtrT ptr;
ReleaseOpT rel_op;
int flag;
public:
_ValT()
:ptr(PtrT()),flag(0)
{
}
_ValT(const PtrT & _ptr,const ReleaseOpT & _rel_op, int _flag=0)
:ptr(_ptr),rel_op(_rel_op),flag(_flag)
{
}
void release()
{
if((flag&_F_DETACHED)==0)
rel_op(ptr);
}
};
typedef ReferenceCounter<_ValT> _CounterT;
protected:
_CounterT _counter;
void _release()
{ //release the referenced object with the stored operator.
_counter.Value().release();
}
public:
AutoRes()
{
}
explicit AutoRes(PtrT ptr,const ReleaseOpT& op=ReleaseOpT())
:_counter(_ValT(ptr,op))
{
}
AutoRes& operator=(const AutoRes& right)
{
if(this!=&right)
{
if(_counter.IsLast())
this->_release();
_counter=right._counter;
}
return *this;
}
RetPtrT operator->() const
{
return &*_counter.Value().ptr;
}
typename std::iterator_traits<RetPtrT>::reference operator*() const
{
return *_counter.Value().ptr;
}
void Swap(AutoRes& right)
{
_counter.Swap(right._counter);
}
//detach the referenced object from @*this.
RetPtrT Detach()
{
_counter.Value().flag|=_F_DETACHED;
return &*_counter.Value().ptr;
}
operator PtrT()
{
return _counter.Value().ptr;
}
~AutoRes() throw()
{
if(_counter.IsLast())
this->_release();
}
};
//operator to delete a single object.
class DeleteObj
{
public:
template<typename _PtrT>
void operator()(_PtrT ptr)
{
delete ptr;
}
};
template<typename _ObjT>
class AutoPtr
:public AutoRes<_ObjT*,_ObjT*,DeleteObj>
{
public:
explicit AutoPtr(_ObjT* ptr=NULL)
:AutoRes<_ObjT*,_ObjT*,DeleteObj>(ptr)
{
}
};
//operator to delete array of objects.
class DeleteArray
{
public:
template<typename _PtrT>
void operator()(_PtrT ptr)
{
delete[]ptr;
}
};
template<typename _ObjT>
class AutoArrayPtr
:public AutoRes<_ObjT*,_ObjT*,DeleteArray>
{
public:
explicit AutoArrayPtr(_ObjT* ptr=NULL)
:AutoRes<_ObjT*,_ObjT*,DeleteArray>(ptr)
{
}
//_ObjT& operator[](int i) const
//{
// return this->_counter.Value().ptr[i];
//}
};
class OpCloseFile
{
public:
void operator()(const FILE *fp)
{
if(fp)
fclose((FILE*)fp);
}
};
class AutoFilePtr
:public AutoRes<FILE*,FILE*,OpCloseFile>
{
public:
explicit AutoFilePtr(FILE *fp=NULL)
:AutoRes<FILE*,FILE*,OpCloseFile>(fp)
{
}
};
//operator to release COM object.
class ReleaseObj
{
public:
template<typename _PtrT>
void operator()(_PtrT ptr)
{
if(ptr)
ptr->Release();
}
};
template<typename _ObjT>
class AutoComPtr
:public AutoRes<_ObjT*,_ObjT*,ReleaseObj>
{
public:
explicit AutoComPtr(_ObjT* ptr=NULL)
:AutoRes<_ObjT*,_ObjT*,ReleaseObj>(ptr)
{
}
};
class DestroyObj
{
public:
template<typename _PtrT>
void operator()(_PtrT ptr)
{
if(ptr)
ptr->Destroy();
}
};
template<typename _ObjT>
class AutoDestroyPtr
:public AutoRes<_ObjT*,_ObjT*,DestroyObj>
{
public:
explicit AutoDestroyPtr(_ObjT* ptr=NULL)
:AutoRes<_ObjT*,_ObjT*,DestroyObj>(ptr)
{
}
};
template<typename _ServerPtrT>
class ReleaseClientOp
{
private:
_ServerPtrT m_pServer;
public:
ReleaseClientOp(_ServerPtrT pServer=_ServerPtrT())
:m_pServer(pServer)
{
}
template<typename _ClientPtrT>
void operator()(_ClientPtrT ptr)
{
if(m_pServer)
m_pServer->ReleaseClient(ptr);
}
};
template<typename _ServerPtrT,typename _ClientPtrT>
class AutoClientPtr
:public AutoRes<_ClientPtrT,_ClientPtrT,ReleaseClientOp<_ServerPtrT> >
{
typedef AutoRes<_ClientPtrT,_ClientPtrT,ReleaseClientOp<_ServerPtrT> > _MyBaseT;
public:
explicit AutoClientPtr(_ServerPtrT pServer=_ServerPtrT(),_ClientPtrT pClient=_ClientPtrT())
:_MyBaseT(pClient,ReleaseClientOp<_ServerPtrT>(pServer))
{
}
};
_FF_END
#endif
| [
"[email protected]"
] | [
[
[
1,
315
]
]
] |
483636595ef27a032fb65294e55c02e76cef77eb | 89421a99baeeb9a368104340ad4efa5f68e2268b | /cpp/Fem1d/Fem1d.cpp | 1795d3ce24e60bc2e100e31feb3145252abc3cbc | [] | no_license | mtsodf/ppgi_elem | c16c510c3f78c1e0eb363a36178f79be60818c0a | 910155619cb94423eb47dfe793f64be01e750c5a | refs/heads/master | 2021-09-06T07:20:18.995847 | 2018-02-03T18:24:21 | 2018-02-03T18:24:21 | 105,206,139 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,068 | cpp | #include "Fem1d.h"
#include "../definitions.h"
#include <stdlib.h>
#include "../LinearAlgebra/Jacobi.h"
#include "../LinearAlgebra/Operations.h"
#include <cmath>
#include "../Utils/Utils.h"
using namespace std;
class UndefinedFuncForm: public exception
{
virtual const char* what() const throw()
{
return "Undefined func form";
}
};
real FuncForm(real qsi, char func){
if(func == 0) return (1.0 - qsi)/2.0;
if(func == 1) return (1.0 + qsi)/2.0;
UndefinedFuncForm ex;
throw ex;
}
real DFuncForm(real qsi, char func){
if(func == 0) return -1.0/2.0;
if(func == 1) return 1.0/2.0;
UndefinedFuncForm ex;
throw ex;
}
void LocalMatrix(real alpha, real beta, real he, real* lm){
real w;
w = sqrt(3.0)/3.0;
for (size_t i = 0; i < 2; i++)
{
for (size_t j = 0; j < 2; j++)
{
lm[2*i+j] = (he/2)*beta*(FuncForm(-w,i)*FuncForm(-w,j)) + (2/he)*alpha*(DFuncForm(-w,i)*DFuncForm(-w,j));
lm[2*i+j] += (he/2)*beta*(FuncForm( w,i)*FuncForm( w,j)) + (2/he)*alpha*(DFuncForm( w,i)*DFuncForm( w,j));
}
}
}
void GlobalMatrix(int n, real alpha, real beta, real *K, int boundary){
real * hs;
real h = 1.0/n;
hs = (real*) malloc(sizeof(real)*n);
for (size_t i = 0; i < n; i++)
{
hs[i] = h;
}
GlobalMatrix(n, alpha, beta, hs, K, boundary);
}
void GlobalMatrix(int n, real alpha, real beta, real* hs, real *K, int boundary){
real lm[4];
int ndofs = n + 1;
for (size_t i = 0; i < n; i++)
{
LocalMatrix(alpha, beta, hs[i], lm);
K[DIM(i,i,ndofs)] += lm[0];
K[DIM(i,i+1,ndofs)] += lm[1];
K[DIM(i+1,i,ndofs)] += lm[2];
K[DIM(i+1,i+1,ndofs)] += lm[3];
}
if(boundary == DIRICHLET || boundary == DIRICHLET_NEUMANN){
K[DIM(0,0,ndofs)] = 1.0;
K[DIM(0,1,ndofs)] = 0.0;
K[DIM(1,0,ndofs)] = 0.0;
}
if(boundary == DIRICHLET || boundary == NEUMANN_DIRICHLET){
K[DIM(ndofs-1,ndofs-2,ndofs)] = 0.0;
K[DIM(ndofs-2,ndofs-1,ndofs)] = 0.0;
K[DIM(ndofs-1,ndofs-1,ndofs)] = 1.0;
}
}
void RhsLocal(real he, real f1, real f2, real *Fe){
real w = sqrt(3)/3.0;
Fe[0] = f1*(he/2)*(FuncForm(-w,0) * FuncForm(-w,0) + FuncForm(w,0) * FuncForm(w,0));
Fe[0] += f2*(he/2)*(FuncForm(-w,0) * FuncForm(-w,1) + FuncForm(w,0) * FuncForm(w,1));
Fe[1] = f1*(he/2)*(FuncForm(-w,1) * FuncForm(-w,0) + FuncForm(w,1) * FuncForm(w,0));
Fe[1] += f2*(he/2)*(FuncForm(-w,1) * FuncForm(-w,1) + FuncForm(w,1) * FuncForm(w,1));
}
void RhsGlobal(int n, real h, real *fs, real *F, real p, real q, real alpha, real beta, int boundary){
real *hs = (real*) malloc(n*sizeof(real));
for (size_t i = 0; i < n; i++)
{
hs[i] = h;
}
RhsGlobal(n, hs, fs, F, p, q, alpha, beta, boundary);
free(hs);
}
void RhsGlobal(int n, real *hs, real *fs, real *F, real p, real q, real alpha, real beta, int boundary){
int ndofs = n + 1;
for (size_t i = 0; i < ndofs; i++)
{
F[i] = 0.0;
}
real Fe[2];
for (size_t i = 0; i < n; i++)
{
RhsLocal(hs[i], fs[i], fs[i+1], Fe);
F[i] += Fe[0];
F[i+1] += Fe[1];
}
if(boundary == DIRICHLET || boundary == DIRICHLET_NEUMANN){
F[0] = p;
real w = sqrt(3)/3.0; real he = hs[0];
F[1] -= p*((he/2)*beta*(FuncForm(-w,0)*FuncForm(-w,1)) + (2/he)*alpha*(DFuncForm(-w,0)*DFuncForm(-w,1)));
F[1] -= p*((he/2)*beta*(FuncForm( w,0)*FuncForm( w,1)) + (2/he)*alpha*(DFuncForm( w,0)*DFuncForm( w,1)));
}
if(boundary == DIRICHLET || boundary == NEUMANN_DIRICHLET){
real w = sqrt(3)/3.0; real he = hs[n-1];
F[ndofs - 1] = q;
F[ndofs-2] -= q*((he/2)*beta*(FuncForm(-w,0)*FuncForm(-w,1)) + (2/he)*alpha*(DFuncForm(-w,0)*DFuncForm(-w,1)));
F[ndofs-2] -= q*((he/2)*beta*(FuncForm( w,0)*FuncForm( w,1)) + (2/he)*alpha*(DFuncForm( w,0)*DFuncForm( w,1)));
}
if(boundary == NEUMANN || boundary == NEUMANN_DIRICHLET){
F[0] -= alpha*p;
}
if(boundary == NEUMANN || boundary == DIRICHLET_NEUMANN){
F[ndofs-1] += alpha*q;
}
}
extern "C"{
real * Fem1dTest(int n, int entrada){
real *x, *F, *fs, *sol;
real *K;
real alpha, beta, p, q;
int boundary;
int unknowns = n + 1;
real h = 1.0/n;
zero(unknowns, &x);
zero(unknowns, &F);
zero(unknowns, &fs);
zero(unknowns, &sol);
zero(unknowns*unknowns, &K);
x[0] = 0.0;
for (size_t i = 1; i < unknowns; i++)
{
x[i] = x[i-1] + h;
}
/*
######################################################################
# Selecao da entrada
######################################################################
*/
for (size_t i = 0; i < unknowns; i++)
{
switch (entrada)
{
case 0:
alpha = 1.0;
beta = 1.0;
fs[i] = 4*M_PI*M_PI*sin(2*M_PI*x[i]) + sin(2*M_PI*x[i]);
sol[i] = sin(2*M_PI*x[i]);
boundary = DIRICHLET;
p = 0.0;
q = 0.0;
break;
case 1:
alpha = 1.0;
beta = 0.0;
fs[i] = 2*alpha;
boundary = DIRICHLET;
p = 0.0;
q = 0.0;
break;
case 2:
alpha = 1.0;
beta = 0.5;
boundary = DIRICHLET;
fs[i] = 0.5*x[i];
p = 0.0;
q = 1.0;
break;
case 3:
alpha = 0.0;
beta = 1.0;
boundary = DIRICHLET;
fs[i] = beta*x[i]*(1-x[i]);
p = 0.0;
q = 0.0;
break;
case 4:
alpha = 2.0;
beta = 1.0;
boundary = DIRICHLET;
fs[i] = -7*exp(2*x[i]);
p = 1.0;
q = exp(2.0);
break;
case 5:
alpha = 2.0;
beta = 1.0;
boundary = NEUMANN;
fs[i] = -7*exp(2*x[i]);
p = 2.0;
q = 2*exp(2.0);
break;
case 6:
alpha = 2.0;
beta = 1.0;
boundary = NEUMANN_DIRICHLET;
fs[i] = -7*exp(2*x[i]);
p = 2.0;
q = exp(2.0);
break;
case 7:
alpha = 2.0;
beta = 1.0;
boundary = DIRICHLET_NEUMANN;
fs[i] = -7*exp(2*x[i]);
p = 1.0;
q = 2*exp(2.0);
break;
case 8:
alpha = 1.0;
beta = 1.0;
boundary = NEUMANN;
fs[i] = 4*M_PI*M_PI*sin(2*M_PI*x[i]) + sin(2*M_PI*x[i]);
p = 2*M_PI;
q = 2*M_PI;
break;
default:
break;
}
}
/*
######################################################################
# Criando Matriz Global
######################################################################
*/
GlobalMatrix(n, alpha, beta, K, boundary);
/*
######################################################################
# Criando Lado Direito
######################################################################
*/
RhsGlobal(n, h, fs, F, p, q, alpha, beta, boundary);
/*
######################################################################
# Solucao do Sistema Linear
######################################################################
*/
real * calc;
zero(unknowns, &calc);
cg(unknowns, K, F, calc);
free(x);
free(F);
free(fs);
free(sol);
free(K);
return calc;
}
}
| [
"[email protected]"
] | [
[
[
1,
311
]
]
] |
fb140c6343d8cb845bec30e15d68b2741357c692 | 5668d876245e982c842409466b39e6660e5fc740 | /servo_brazo_potenciometros_guardaposicion.ino | 3ef4e592616b58aabc9c2a86ef50a4ec55730403 | [] | no_license | RiquiMora/Brazo-Robotico-4DOF | 5dea34ff7115e9e5e126d5e292b84d92cfcb2d4b | a472bd7ea25e75f91f6079aa184c3a1e47ec18b2 | refs/heads/master | 2020-03-19T02:04:27.984336 | 2018-05-31T15:05:30 | 2018-05-31T15:05:30 | 135,596,748 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,326 | ino | #include <Servo.h>
Servo hombro, brazo, base, garra;
int potpi = 0;
int pot = 1;
int potp = 2;
int po = 3;
int val; // variable to read the value from the analog pin
int val1;
int val2;
int val3;
const int max_root = 180;
char valores;
String codigo = "";
boolean mode = true;
void setup() {
Serial.begin(9600);
base.attach(11);
brazo.attach(10);
hombro.attach(9);
garra.attach(8);
}
void loop() {
val = analogRead(potpi); // reads the value of the potentiometer (value between 0 and 1023)
val = map(val, 0, 1023, 0, 180); // scale it to use it with the servo (value between 0 and 180)
hombro.write(val); // sets the servo position according to the scaled value
delay(15); // waits for the servo to get there
val1 = analogRead(pot); // reads the value of the potentiometer (value between 0 and 1023)
val1 = map(val1, 0, 1023, 0, 180); // scale it to use it with the servo (value between 0 and 180)
brazo.write(val1); // sets the servo position according to the scaled value
delay(15); // waits for the servo to get there
val2 = analogRead(potp); // reads the value of the potentiometer (value between 0 and 1023)
val2 = map(val2, 0, 1023, 0, 180); // scale it to use it with the servo (value between 0 and 180)
base.write(val2); // sets the servo position according to the scaled value
delay(15); // waits for the servo to get there
val3 = analogRead(po); // reads the value of the potentiometer (value between 0 and 1023)
val3 = map(val3, 0, 1023, 0, 180); // scale it to use it with the servo (value between 0 and 180)
garra.write(val3); // sets the servo position according to the scaled value
delay(15); // waits for the servo to get there
String metodo="",init = ""; boolean tipo = false;
int posicion = 0;
base.write(60);
brazo.write(60);
hombro.write(60);
garra.write(60);
if(Serial.available() > 0)
{
codigo = "";
while(Serial.available() > 0)
{
valores = Decimal_to_ASCII(Serial.read());
Serial.print(valores);
codigo = codigo + valores;
}
delay(2000);
}
Serial.println(codigo);
delay(2000);
for( int i=0; i < codigo.length(); i++)
{
if(tipo == false)
{
if(codigo.charAt(i) == '(')
{
tipo = true;
continue;
}
metodo = metodo + codigo.charAt(i);
} else
{
init = init + codigo.charAt(i);
if(codigo.charAt(i) == ')')
{
continue;
}else if(codigo.charAt(i) == ';'){
delay(2000);
posicion = init.toInt();
if(metodo == "brazo")
{
posicion < 180 ? brazo.write(posicion) : brazo.write(180);
Serial.println("brazo");
delay(2000);
}else if(metodo == "base")
{
posicion < max_root ? base.write(posicion) : base.write(180);
Serial.println("base");
delay(2000);
}else if(metodo == "hombro")
{
posicion < max_root ? hombro.write(posicion) : hombro.write(180);
Serial.println("hombro");
delay(2000);
}else if(metodo == "garra")
{
posicion < max_root ? garra.write(posicion) : garra.write(180);
Serial.println("garra");
delay(2000);
}
metodo = "";
tipo = false;
init = "";
}
}
}
}
char Decimal_to_ASCII(int entrada){
char salida=' ';
switch(entrada){
case 32:
salida=' ';
break;
case 33:
salida='!';
break;
case 34:
salida='"';
break;
case 35:
salida='#';
break;
case 36:
salida='$';
break;
case 37:
salida='%';
break;
case 38:
salida='&';
break;
case 39:
salida=' ';
break;
case 40:
salida='(';
break;
case 41:
salida=')';
break;
case 42:
salida='*';
break;
case 43:
salida='+';
break;
case 44:
salida=',';
break;
case 45:
salida='-';
break;
case 46:
salida='.';
break;
case 47:
salida='/';
break;
case 48:
salida='0';
break;
case 49:
salida='1';
break;
case 50:
salida='2';
break;
case 51:
salida='3';
break;
case 52:
salida='4';
break;
case 53:
salida='5';
break;
case 54:
salida='6';
break;
case 55:
salida='7';
break;
case 56:
salida='8';
break;
case 57:
salida='9';
break;
case 58:
salida=':';
break;
case 59:
salida=';';
break;
case 60:
salida='<';
break;
case 61:
salida='=';
break;
case 62:
salida='>';
break;
case 63:
salida='?';
break;
case 64:
salida='@';
break;
case 65:
salida='A';
break;
case 66:
salida='B';
break;
case 67:
salida='C';
break;
case 68:
salida='D';
break;
case 69:
salida='E';
break;
case 70:
salida='F';
break;
case 71:
salida='G';
break;
case 72:
salida='H';
break;
case 73:
salida='I';
break;
case 74:
salida='J';
break;
case 75:
salida='K';
break;
case 76:
salida='L';
break;
case 77:
salida='M';
break;
case 78:
salida='N';
break;
case 79:
salida='O';
break;
case 80:
salida='P';
break;
case 81:
salida='Q';
break;
case 82:
salida='R';
break;
case 83:
salida='S';
break;
case 84:
salida='T';
break;
case 85:
salida='U';
break;
case 86:
salida='V';
break;
case 87:
salida='W';
break;
case 88:
salida='X';
break;
case 89:
salida='Y';
break;
case 90:
salida='Z';
break;
case 91:
salida='[';
break;
case 92:
salida=' ';
break;
case 93:
salida=']';
break;
case 94:
salida='^';
break;
case 95:
salida='_';
break;
case 96:
salida='`';
break;
case 97:
salida='a';
break;
case 98:
salida='b';
break;
case 99:
salida='c';
break;
case 100:
salida='d';
break;
case 101:
salida='e';
break;
case 102:
salida='f';
break;
case 103:
salida='g';
break;
case 104:
salida='h';
break;
case 105:
salida='i';
break;
case 106:
salida='j';
break;
case 107:
salida='k';
break;
case 108:
salida='l';
break;
case 109:
salida='m';
break;
case 110:
salida='n';
break;
case 111:
salida='o';
break;
case 112:
salida='p';
break;
case 113:
salida='q';
break;
case 114:
salida='r';
break;
case 115:
salida='s';
break;
case 116:
salida='t';
break;
case 117:
salida='u';
break;
case 118:
salida='v';
break;
case 119:
salida='w';
break;
case 120:
salida='x';
break;
case 121:
salida='y';
break;
case 122:
salida='z';
break;
case 123:
salida='{';
break;
case 124:
salida='|';
break;
case 125:
salida='}';
break;
case 126:
salida='~';
break;
}
return salida;
}
| [
"[email protected]"
] | [
[
[
1,
421
]
]
] |
18296b24c1a4c774d930261e017e37a0cf8d04fa | d0601b28a3060105e82c2a839d435c4329fe82a9 | /OpenGL_Material/build-OpenGL_Material-Desktop_Qt_5_8_0_MSVC2015_64bit-Debug/debug/moc_mainwindow.cpp | 51b68186ab06892d4bfefdfe122cf57267d5fcdf | [] | no_license | guoerba/opengl | 9458b1b3827e24884bcd0a1b91d122ab6a252f8e | 103da63ada1703a3f450cfde19f41b04e922187e | refs/heads/master | 2020-07-10T15:40:49.828059 | 2019-08-25T13:52:58 | 2019-08-25T13:52:58 | 204,300,456 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,706 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'mainwindow.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.8.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../OpenGL_Material/mainwindow.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'mainwindow.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.8.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_MainWindow_t {
QByteArrayData data[1];
char stringdata0[11];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_MainWindow_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_MainWindow_t qt_meta_stringdata_MainWindow = {
{
QT_MOC_LITERAL(0, 0, 10) // "MainWindow"
},
"MainWindow"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_MainWindow[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
void MainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
const QMetaObject MainWindow::staticMetaObject = {
{ &QMainWindow::staticMetaObject, qt_meta_stringdata_MainWindow.data,
qt_meta_data_MainWindow, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *MainWindow::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *MainWindow::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_MainWindow.stringdata0))
return static_cast<void*>(const_cast< MainWindow*>(this));
return QMainWindow::qt_metacast(_clname);
}
int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QMainWindow::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| [
"[email protected]"
] | [
[
[
1,
92
]
]
] |
f46de1bd281fa3736931ddc5c85eb5849f2b7ee0 | 723b67f6a8b202dc5bb009427f60ffd9f185dba8 | /devel/include/ros_arduino_msgs/ServoWriteResponse.h | ef1a29d38d970bae98cdea4932c90d41f162ce62 | [] | no_license | Dhawgupta/catkin_ws | 15edced50d3d69bf78851315658646cd671eb911 | edab645f1a94c83925836b36d38ecf2ad8f42abc | refs/heads/master | 2021-01-19T10:56:09.954495 | 2017-04-11T09:52:20 | 2017-04-11T09:52:20 | 87,917,514 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,028 | h | // Generated by gencpp from file ros_arduino_msgs/ServoWriteResponse.msg
// DO NOT EDIT!
#ifndef ROS_ARDUINO_MSGS_MESSAGE_SERVOWRITERESPONSE_H
#define ROS_ARDUINO_MSGS_MESSAGE_SERVOWRITERESPONSE_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 ros_arduino_msgs
{
template <class ContainerAllocator>
struct ServoWriteResponse_
{
typedef ServoWriteResponse_<ContainerAllocator> Type;
ServoWriteResponse_()
{
}
ServoWriteResponse_(const ContainerAllocator& _alloc)
{
(void)_alloc;
}
typedef boost::shared_ptr< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> const> ConstPtr;
}; // struct ServoWriteResponse_
typedef ::ros_arduino_msgs::ServoWriteResponse_<std::allocator<void> > ServoWriteResponse;
typedef boost::shared_ptr< ::ros_arduino_msgs::ServoWriteResponse > ServoWriteResponsePtr;
typedef boost::shared_ptr< ::ros_arduino_msgs::ServoWriteResponse const> ServoWriteResponseConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace ros_arduino_msgs
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False}
// {'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'ros_arduino_msgs': ['/home/dawg/catkin_ws/src/ros_arduino_bridge/ros_arduino_msgs/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< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> >
{
static const char* value()
{
return "d41d8cd98f00b204e9800998ecf8427e";
}
static const char* value(const ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0xd41d8cd98f00b204ULL;
static const uint64_t static_value2 = 0xe9800998ecf8427eULL;
};
template<class ContainerAllocator>
struct DataType< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> >
{
static const char* value()
{
return "ros_arduino_msgs/ServoWriteResponse";
}
static const char* value(const ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> >
{
static const char* value()
{
return "\n\
";
}
static const char* value(const ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream&, T)
{}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct ServoWriteResponse_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream&, const std::string&, const ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator>&)
{}
};
} // namespace message_operations
} // namespace ros
#endif // ROS_ARDUINO_MSGS_MESSAGE_SERVOWRITERESPONSE_H
| [
"[email protected]"
] | [
[
[
1,
178
]
]
] |
fc66a1678930bf9093bd076f90dd380635b60366 | ceeddddcf3e99e909c4af5ff2b9fad4a8ecaeb2a | /branches/releases/1.3.NET/source/Irrlicht/CGUIColorSelectDialog.h | fed63371d4d75b6f6d20e164aab8c2e8f2527655 | [
"Zlib",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-other-permissive"
] | permissive | jivibounty/irrlicht | d9d6993bd0aee00dce2397a887b7f547ade74fbb | c5c80cde40b6d14fe5661440638d36a16b41d7ab | refs/heads/master | 2021-01-18T02:56:08.844268 | 2015-07-21T08:02:25 | 2015-07-21T08:02:25 | 39,405,895 | 0 | 0 | null | 2015-07-20T20:07:06 | 2015-07-20T20:07:06 | null | UTF-8 | C++ | false | false | 1,684 | h | // Copyright (C) 2002-2007 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __C_GUI_COLOR_SELECT_DIALOG_H_INCLUDED__
#define __C_GUI_COLOR_SELECT_DIALOG_H_INCLUDED__
#include "IGUIColorSelectDialog.h"
#include "IGUIButton.h"
#include "IGUIEditBox.h"
#include "IGUIScrollBar.h"
#include "IGUIImage.h"
#include "irrArray.h"
namespace irr
{
namespace gui
{
class CGUIColorSelectDialog : public IGUIColorSelectDialog
{
public:
//! constructor
CGUIColorSelectDialog(const wchar_t* title, IGUIEnvironment* environment, IGUIElement* parent, s32 id);
//! destructor
virtual ~CGUIColorSelectDialog();
//! called if an event happened.
virtual bool OnEvent(SEvent event);
//! draws the element and its children
virtual void draw();
private:
//! sends the event that the file has been selected.
void sendSelectedEvent();
//! sends the event that the file choose process has been canceld
void sendCancelEvent();
core::position2d<s32> DragStart;
bool Dragging;
IGUIButton* CloseButton;
IGUIButton* OKButton;
IGUIButton* CancelButton;
struct SBatteryItem
{
f32 Incoming;
f32 Outgoing;
IGUIEditBox * Edit;
IGUIScrollBar *Scrollbar;
};
core::array< SBatteryItem > Battery;
struct SColorCircle
{
IGUIImage * Control;
video::ITexture * Texture;
};
SColorCircle ColorRing;
void buildColorRing( const core::dimension2d<s32> & dim, s32 supersample, const u32 borderColor );
};
} // end namespace gui
} // end namespace irr
#endif
| [
"hybrid@dfc29bdd-3216-0410-991c-e03cc46cb475"
] | [
[
[
1,
76
]
]
] |
28ccee844626dc8f532b974e14b830d2f77d8276 | fce00ed7da745340691c8c6cf47905ba4fe5a08e | /UchClient/FrmMain.cpp | 632d7a2b262d04091ced8c1a66af203405b47a34 | [
"Unlicense"
] | permissive | EAirPeter/Uch | bc9bae801721a9241afbfe8add293cf5dcf7a322 | 193ee52fb98d2d224cd22483b2523caf02805cfe | refs/heads/master | 2021-07-24T15:06:17.555444 | 2017-11-05T14:25:50 | 2017-11-05T14:25:50 | 109,581,211 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,153 | cpp | #include "Common.hpp"
#include "FrmFileRecv.hpp"
#include "FrmFileSend.hpp"
#include "FrmMain.hpp"
#include "Ucl.hpp"
#include <nana/gui/filebox.hpp>
using namespace nana;
FrmMain::FrmMain() :
form(nullptr, {768, 480}, appear::decorate<
appear::taskbar, appear::minimize, appear::maximize, appear::sizable
>())
{
caption(Title(L"Client"));
events().destroy(std::bind(&FrmMain::X_OnDestroy, this, std::placeholders::_1));
events().user(std::bind(&FrmMain::X_OnUser, this, std::placeholders::_1));
events().unload([this] (const arg_unload &e) {
msgbox mbx {nullptr, TitleU8(L"Exit"), msgbox::yes_no};
mbx.icon(msgbox::icon_question);
mbx << L"Are you sure to exit Uch?";
if (mbx() != mbx.pick_yes)
e.cancel = true;
});
x_btnSend.caption(L"Send");
x_btnSend.events().click(std::bind(&FrmMain::X_OnSend, this));
x_btnSend.events().key_press([this] (const arg_keyboard &e) {
if (e.key == keyboard::enter)
X_OnSend();
});
x_btnFile.caption(L"Send File");
x_btnFile.events().click(std::bind(&FrmMain::X_OnFile, this));
x_btnFile.events().key_press([this] (const arg_keyboard &e) {
if (e.key == keyboard::enter)
X_OnFile();
});
x_btnExit.caption(L"Exit");
x_btnExit.events().click(std::bind(&FrmMain::close, this));
x_btnExit.events().key_press([this] (const arg_keyboard &e) {
if (e.key == keyboard::enter)
close();
});
x_txtMessage.multi_lines(false).tip_string(u8"Message:");
x_txtMessage.events().focus([this] (const arg_focus &e) {
x_txtMessage.select(e.getting);
});
x_txtMessage.events().key_press([this] (const arg_keyboard &e) {
if (e.key == keyboard::enter)
X_OnSend();
});
x_lbxUsers.enable_single(true, false);
x_lbxUsers.append_header(L"Who", 110);
x_lbxUsers.append({L"Online", L"Offline"});
x_lbxMessages.sortable(false);
x_lbxMessages.append_header(L"When", 80);
x_lbxMessages.append_header(L"How", 180);
x_lbxMessages.append_header(L"What", 310);
x_pl.div(
"margin=[14,16]"
" <weight=120 List> <weight=8>"
" <vert"
" <Msgs> <weight=7>"
" <weight=25 Imsg> <weight=7>"
" <weight=25 <> <weight=259 gap=8 Btns>>"
" >"
);
x_pl["List"] << x_lbxUsers;
x_pl["Msgs"] << x_lbxMessages;
x_pl["Imsg"] << x_txtMessage;
x_pl["Btns"] << x_btnExit << x_btnFile << x_btnSend;
x_pl.collocate();
Ucl::Bus().Register(*this);
}
void FrmMain::OnEvent(event::EvMessage &e) noexcept {
constexpr static auto kszFmt = L"(%s) %s => %s";
x_lbxMessages.at(0).append({
FormattedTime(),
FormatString(L"(%s) %s => %s", e.sCat.c_str(), e.sFrom.c_str(), e.sTo.c_str()),
e.sWhat
});
x_lbxMessages.scroll(true);
}
void FrmMain::OnEvent(event::EvListUon &e) noexcept {
x_lbxUsers.at(1).model<std::recursive_mutex>(
e.vecUon,
[] (auto &c) {
return AsWideString(c.front().text);
},
[] (auto &s) {
return std::vector<listbox::cell> {AsUtf8String(s)};
}
);
}
void FrmMain::OnEvent(event::EvListUff &e) noexcept {
x_lbxUsers.at(2).model<std::recursive_mutex>(
e.vecUff,
[] (auto &c) {
return AsWideString(c.front().text);
},
[] (auto &s) {
return std::vector<listbox::cell> {AsUtf8String(s)};
}
);
}
void FrmMain::OnEvent(event::EvFileReq &e) noexcept {
user(std::make_unique<event::EvFileReq>(e).release());
}
void FrmMain::X_OnSend() {
auto vec = x_lbxUsers.selected();
if (vec.empty()) {
msgbox mbx {nullptr, TitleU8(L"Send message"), msgbox::ok};
mbx.icon(msgbox::icon_error);
mbx << L"Please select a recipient";
mbx();
return;
}
auto &idx = vec.front();
auto sUser = AsWideString(x_lbxUsers.at(idx.cat).at(idx.item).text(0));
switch (idx.cat) {
case 1:
// Online
X_AddMessage({kszCatChat, kszSelf, sUser, x_txtMessage.caption_wstring()});
(*Ucl::Pmg())[sUser].PostPacket(protocol::EvpMessage {
x_txtMessage.caption_wstring()
});
break;
case 2:
// Offline
X_AddMessage({kszCatFmsg, kszSelf, sUser, x_txtMessage.caption_wstring()});
Ucl::Con()->PostPacket(protocol::EvcMessageTo {
sUser, x_txtMessage.caption_wstring()
});
break;
default:
throw ExnIllegalState {};
}
x_txtMessage.caption(String {});
}
void FrmMain::X_OnFile() {
auto vec = x_lbxUsers.selected();
if (vec.empty()) {
msgbox mbx {TitleU8(L"Send file")};
mbx.icon(msgbox::icon_error);
mbx << L"Please select a recipient";
mbx();
return;
}
auto &idx = vec.front();
if (idx.cat != 1) {
msgbox mbx {TitleU8(L"Send file")};
mbx.icon(msgbox::icon_error);
mbx << L"Please select an online user";
mbx();
return;
}
auto sUser = AsWideString(x_lbxUsers.at(idx.cat).at(idx.item).text(0));
filebox fbx {nullptr, true};
if (!fbx())
return;
auto sPath = AsWideString(fbx.file());
UccPipl *pPipl;
try {
pPipl = &(*Ucl::Pmg())[sUser];
}
catch (std::out_of_range) {
msgbox mbx {TitleU8(L"Send file")};
mbx << L"The user if offline";
mbx();
return;
}
form_loader<FrmFileSend>() (*this, pPipl, sPath).show();
}
void FrmMain::X_OnDestroy(const nana::arg_destroy &e) {
Ucl::Con()->PostPacket(protocol::EvcExit {Ucl::Usr()});
Ucl::Con()->Shutdown();
Ucl::Pmg()->Shutdown();
Ucl::Bus().Unregister(*this);
}
void FrmMain::X_OnUser(const nana::arg_user &e) {
std::unique_ptr<event::EvFileReq> up {
reinterpret_cast<event::EvFileReq *>(e.param)
};
try {
form_loader<FrmFileRecv>() (*this, up->pPipl, up->eReq).show();
}
catch (ExnIllegalState) {}
}
void FrmMain::X_AddMessage(event::EvMessage &&e) noexcept {
OnEvent(e);
}
| [
"[email protected]"
] | [
[
[
1,
201
]
]
] |
d906994d3f90133151039af0434882e3553ba719 | 1c02e13a776e5e8bc3e2a6182b5df4efb2c71d32 | /core/unit_test/tstDeepCopy.hpp | b3fdab4da5ef0b61357d256cf996dae1b69884f0 | [
"BSD-3-Clause"
] | permissive | junghans/Cabana | 91b82827dd9fb8321bea9ea3750c196946a6aac0 | 7b9078f81bde68c949fd6ae913ce80eeaf0f8f8a | refs/heads/master | 2021-06-14T09:57:01.658234 | 2019-01-04T22:24:45 | 2019-01-04T22:24:45 | 150,330,482 | 1 | 1 | BSD-3-Clause | 2019-01-07T16:24:20 | 2018-09-25T21:17:53 | C++ | UTF-8 | C++ | false | false | 5,252 | hpp | /****************************************************************************
* Copyright (c) 2018 by the Cabana authors *
* All rights reserved. *
* *
* This file is part of the Cabana library. Cabana is distributed under a *
* BSD 3-clause license. For the licensing terms see the LICENSE file in *
* the top-level directory. *
* *
* SPDX-License-Identifier: BSD-3-Clause *
****************************************************************************/
#include <Cabana_DeepCopy.hpp>
#include <Cabana_AoSoA.hpp>
#include <Cabana_Types.hpp>
#include <gtest/gtest.h>
namespace Test
{
//---------------------------------------------------------------------------//
// Check the data given a set of values.
template<class aosoa_type>
void checkDataMembers(
aosoa_type aosoa,
const float fval, const double dval, const int ival,
const int dim_1, const int dim_2, const int dim_3 )
{
auto slice_0 = aosoa.template slice<0>();
auto slice_1 = aosoa.template slice<1>();
auto slice_2 = aosoa.template slice<2>();
auto slice_3 = aosoa.template slice<3>();
for ( std::size_t idx = 0; idx < aosoa.size(); ++idx )
{
// Member 0.
for ( int i = 0; i < dim_1; ++i )
for ( int j = 0; j < dim_2; ++j )
for ( int k = 0; k < dim_3; ++k )
EXPECT_EQ( slice_0( idx, i, j, k ),
fval * (i+j+k) );
// Member 1.
EXPECT_EQ( slice_1( idx ), ival );
// Member 2.
for ( int i = 0; i < dim_1; ++i )
EXPECT_EQ( slice_2( idx, i ), dval * i );
// Member 3.
for ( int i = 0; i < dim_1; ++i )
for ( int j = 0; j < dim_2; ++j )
EXPECT_EQ( slice_3( idx, i, j ), dval * (i+j) );
}
}
//---------------------------------------------------------------------------//
// Perform a deep copy test.
template<class DstMemorySpace, class SrcMemorySpace,
int DstVectorLength, int SrcVectorLength>
void testDeepCopy()
{
// Data dimensions.
const int dim_1 = 3;
const int dim_2 = 2;
const int dim_3 = 4;
// Declare data types.
using DataTypes =
Cabana::MemberTypes<float[dim_1][dim_2][dim_3],
int,
double[dim_1],
double[dim_1][dim_2]
>;
// Declare the AoSoA types.
using DstAoSoA_t = Cabana::AoSoA<DataTypes,DstMemorySpace,DstVectorLength>;
using SrcAoSoA_t = Cabana::AoSoA<DataTypes,SrcMemorySpace,SrcVectorLength>;
// Create AoSoAs.
int num_data = 357;
DstAoSoA_t dst_aosoa( num_data );
SrcAoSoA_t src_aosoa( num_data );
// Initialize data with the rank accessors.
float fval = 3.4;
double dval = 1.23;
int ival = 1;
auto slice_0 = src_aosoa.template slice<0>();
auto slice_1 = src_aosoa.template slice<1>();
auto slice_2 = src_aosoa.template slice<2>();
auto slice_3 = src_aosoa.template slice<3>();
for ( std::size_t idx = 0; idx < src_aosoa.size(); ++idx )
{
// Member 0.
for ( int i = 0; i < dim_1; ++i )
for ( int j = 0; j < dim_2; ++j )
for ( int k = 0; k < dim_3; ++k )
slice_0( idx, i, j, k ) = fval * (i+j+k);
// Member 1.
slice_1( idx ) = ival;
// Member 2.
for ( int i = 0; i < dim_1; ++i )
slice_2( idx, i ) = dval * i;
// Member 3.
for ( int i = 0; i < dim_1; ++i )
for ( int j = 0; j < dim_2; ++j )
slice_3( idx, i, j ) = dval * (i+j);
}
// Deep copy
Cabana::deep_copy( dst_aosoa, src_aosoa );
// Check values.
checkDataMembers( dst_aosoa, fval, dval, ival, dim_1, dim_2, dim_3 );
}
//---------------------------------------------------------------------------//
// TESTS
//---------------------------------------------------------------------------//
TEST_F( TEST_CATEGORY, deep_copy_to_host_same_layout_test )
{
testDeepCopy<Cabana::HostSpace,TEST_MEMSPACE,16,16>();
}
//---------------------------------------------------------------------------//
TEST_F( TEST_CATEGORY, deep_copy_from_host_same_layout_test )
{
testDeepCopy<TEST_MEMSPACE,Cabana::HostSpace,16,16>();
}
//---------------------------------------------------------------------------//
TEST_F( TEST_CATEGORY, deep_copy_to_host_different_layout_test )
{
testDeepCopy<Cabana::HostSpace,TEST_MEMSPACE,16,32>();
testDeepCopy<Cabana::HostSpace,TEST_MEMSPACE,64,8>();
}
//---------------------------------------------------------------------------//
TEST_F( TEST_CATEGORY, deep_copy_from_host_different_layout_test )
{
testDeepCopy<TEST_MEMSPACE,Cabana::HostSpace,64,8>();
testDeepCopy<TEST_MEMSPACE,Cabana::HostSpace,16,32>();
}
//---------------------------------------------------------------------------//
} // end namespace Test
| [
"[email protected]"
] | [
[
[
1,
151
]
]
] |
22b4b85995b27b9bf5a3b2c844bcb56c4ab65e55 | 090243cf699213f32f870baf2902eb4211f825d6 | /cf/621/D.cpp | 27cba968aae8be25270c8a561e72debc59131184 | [] | no_license | zhu-he/ACM-Source | 0d4d0ac0668b569846b12297e7ed4abbb1c16571 | 02e3322e50336063d0d2dad37b2761ecb3d4e380 | refs/heads/master | 2021-06-07T18:27:19.702607 | 2016-07-10T09:20:48 | 2016-07-10T09:20:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 625 | cpp | #include <cstdio>
#include <cmath>
const char s[12][10] = {"x^y^z", "x^z^y", "(x^y)^z", "(x^z)^y", "y^x^z", "y^z^x", "(y^x)^z", "(y^z)^x", "z^x^y", "z^y^x", "(z^x)^y", "(z^y)^x"};
double d[12];
int main()
{
double x, y, z;
scanf("%lf %lf %lf", &x, &y, &z);
d[0] = pow(y, z) * log(x);
d[1] = pow(z, y) * log(x);
d[2] = d[3] = y * z * log(x);
d[4] = pow(x, z) * log(y);
d[5] = pow(z, x) * log(y);
d[6] = d[7] = x * z * log(y);
d[8] = pow(x, y) * log(z);
d[9] = pow(y, x) * log(z);
d[10] = d[11] = x * y * log(z);
int mx = 0;
for (int i = 1; i < 12; ++i)
if (d[i] > d[mx])
mx = i;
puts(s[mx]);
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
26
]
]
] |
39fef5bcedac295c0ef9e8b56f71ce5a982fc908 | 814fd0bea5bc063a4e34ebdd0a5597c9ff67532b | /chrome/browser/chromeos/drive/file_task_executor.h | 56f1d73681c2ef875beca64ba192b24f1dfae39d | [
"BSD-3-Clause"
] | permissive | rzr/chromium-crosswalk | 1b22208ff556d69c009ad292bc17dca3fe15c493 | d391344809adf7b4f39764ac0e15c378169b805f | refs/heads/master | 2021-01-21T09:11:07.316526 | 2015-02-16T11:52:21 | 2015-02-16T11:52:21 | 38,887,985 | 0 | 0 | NOASSERTION | 2019-08-07T21:59:20 | 2015-07-10T15:35:50 | C++ | UTF-8 | C++ | false | false | 2,578 | h | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_CHROMEOS_DRIVE_FILE_TASK_EXECUTOR_H_
#define CHROME_BROWSER_CHROMEOS_DRIVE_FILE_TASK_EXECUTOR_H_
#include <string>
#include <vector>
#include "base/callback.h"
#include "base/memory/weak_ptr.h"
#include "chrome/browser/chromeos/drive/file_errors.h"
#include "chrome/browser/chromeos/file_manager/file_tasks.h"
#include "google_apis/drive/gdata_errorcode.h"
namespace drive {
class DriveServiceInterface;
class FileSystemInterface;
class ResourceEntry;
// Delegate class for hooking fake instances and behaviors for testing.
class FileTaskExecutorDelegate {
public:
virtual ~FileTaskExecutorDelegate() {}
virtual FileSystemInterface* GetFileSystem() = 0;
virtual DriveServiceInterface* GetDriveService() = 0;
virtual void OpenBrowserWindow(const GURL& open_link) = 0;
};
// This class implements an "executor" class that will execute tasks for
// third party Drive apps that store data in Drive itself. To do that, it
// needs to find the file resource IDs and pass them to a server-side function
// that will authorize the app to open the given document and return a URL
// for opening the document in that app directly.
class FileTaskExecutor {
public:
// Creates FileTaskExecutor with delegate derived from |profile|. Used in
// product environment.
FileTaskExecutor(Profile* profile, const std::string& app_id);
// Creates FileTaskExecutor with a specific delegate.
FileTaskExecutor(scoped_ptr<FileTaskExecutorDelegate> delegate,
const std::string& app_id);
// Executes file tasks, runs |done| and deletes |this|.
void Execute(const std::vector<storage::FileSystemURL>& file_urls,
const file_manager::file_tasks::FileTaskFinishedCallback& done);
private:
~FileTaskExecutor();
void OnFileEntryFetched(FileError error, scoped_ptr<ResourceEntry> entry);
void OnAppAuthorized(const std::string& resource_id,
google_apis::GDataErrorCode error,
const GURL& open_link);
// Calls |done_| with |success| status and deletes |this|.
void Done(bool success);
scoped_ptr<FileTaskExecutorDelegate> delegate_;
std::string app_id_;
int current_index_;
file_manager::file_tasks::FileTaskFinishedCallback done_;
base::WeakPtrFactory<FileTaskExecutor> weak_ptr_factory_;
};
} // namespace drive
#endif // CHROME_BROWSER_CHROMEOS_DRIVE_FILE_TASK_EXECUTOR_H_
| [
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98",
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98",
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98",
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98",
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98",
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98",
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98",
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98"
] | [
[
[
1,
4
],
[
7,
7
],
[
16,
16
],
[
18,
18
],
[
22,
22
],
[
33,
37
],
[
39,
39
],
[
43,
43
],
[
51,
51
],
[
54,
54
],
[
56,
56
],
[
59,
59
],
[
61,
62
],
[
65,
65
],
[
69,
70
],
[
72,
72
]
],
[
[
5,
6
],
[
11,
11
],
[
13,
14
],
[
17,
17
],
[
21,
21
],
[
66,
66
],
[
71,
71
],
[
73,
73
]
],
[
[
8,
10
]
],
[
[
12,
12
],
[
38,
38
],
[
42,
42
],
[
48,
48
],
[
52,
53
],
[
55,
55
],
[
60,
60
],
[
64,
64
],
[
67,
68
]
],
[
[
15,
15
],
[
19,
20
],
[
23,
32
],
[
40,
41
],
[
44,
47
],
[
50,
50
],
[
63,
63
]
],
[
[
49,
49
]
],
[
[
57,
57
]
],
[
[
58,
58
]
]
] |
3c562a4243e222e2a5d2afd6f33ac1002b5d77d5 | e49020bee62e9a7006b7a603588aff026ac19402 | /clang/lib/Basic/IdentifierTable.cpp | 621bcc265020d77a202936efaba490ba1a2832a7 | [
"NCSA"
] | permissive | angopher/llvm | 10d540f4d38fd184506d9096fb02a288af8a1aa1 | 163def217817c90fb982a6daf384744d8472b92b | refs/heads/master | 2020-06-10T09:59:52.274700 | 2018-05-10T23:14:40 | 2018-05-10T23:14:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,406 | cpp | //===- IdentifierTable.cpp - Hash table for identifier lookup -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the IdentifierInfo, IdentifierVisitor, and
// IdentifierTable interfaces.
//
//===----------------------------------------------------------------------===//
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/OperatorKinds.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Basic/TokenKinds.h"
#include "llvm/ADT/DenseMapInfo.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <cassert>
#include <cstdio>
#include <cstring>
#include <string>
using namespace clang;
//===----------------------------------------------------------------------===//
// IdentifierInfo Implementation
//===----------------------------------------------------------------------===//
IdentifierInfo::IdentifierInfo() {
TokenID = tok::identifier;
ObjCOrBuiltinID = 0;
HasMacro = false;
HadMacro = false;
IsExtension = false;
IsFutureCompatKeyword = false;
IsPoisoned = false;
IsCPPOperatorKeyword = false;
NeedsHandleIdentifier = false;
IsFromAST = false;
ChangedAfterLoad = false;
FEChangedAfterLoad = false;
RevertedTokenID = false;
OutOfDate = false;
IsModulesImport = false;
}
//===----------------------------------------------------------------------===//
// IdentifierTable Implementation
//===----------------------------------------------------------------------===//
IdentifierIterator::~IdentifierIterator() = default;
IdentifierInfoLookup::~IdentifierInfoLookup() = default;
namespace {
/// A simple identifier lookup iterator that represents an
/// empty sequence of identifiers.
class EmptyLookupIterator : public IdentifierIterator
{
public:
StringRef Next() override { return StringRef(); }
};
} // namespace
IdentifierIterator *IdentifierInfoLookup::getIdentifiers() {
return new EmptyLookupIterator();
}
IdentifierTable::IdentifierTable(IdentifierInfoLookup *ExternalLookup)
: HashTable(8192), // Start with space for 8K identifiers.
ExternalLookup(ExternalLookup) {}
IdentifierTable::IdentifierTable(const LangOptions &LangOpts,
IdentifierInfoLookup *ExternalLookup)
: IdentifierTable(ExternalLookup) {
// Populate the identifier table with info about keywords for the current
// language.
AddKeywords(LangOpts);
}
//===----------------------------------------------------------------------===//
// Language Keyword Implementation
//===----------------------------------------------------------------------===//
// Constants for TokenKinds.def
namespace {
enum {
KEYC99 = 0x1,
KEYCXX = 0x2,
KEYCXX11 = 0x4,
KEYGNU = 0x8,
KEYMS = 0x10,
BOOLSUPPORT = 0x20,
KEYALTIVEC = 0x40,
KEYNOCXX = 0x80,
KEYBORLAND = 0x100,
KEYOPENCL = 0x200,
KEYC11 = 0x400,
KEYARC = 0x800,
KEYNOMS18 = 0x01000,
KEYNOOPENCL = 0x02000,
WCHARSUPPORT = 0x04000,
HALFSUPPORT = 0x08000,
CHAR8SUPPORT = 0x10000,
KEYCONCEPTS = 0x20000,
KEYOBJC2 = 0x40000,
KEYZVECTOR = 0x80000,
KEYCOROUTINES = 0x100000,
KEYMODULES = 0x200000,
KEYCXX2A = 0x400000,
KEYALLCXX = KEYCXX | KEYCXX11 | KEYCXX2A,
KEYALL = (0x7fffff & ~KEYNOMS18 &
~KEYNOOPENCL) // KEYNOMS18 and KEYNOOPENCL are used to exclude.
};
/// How a keyword is treated in the selected standard.
enum KeywordStatus {
KS_Disabled, // Disabled
KS_Extension, // Is an extension
KS_Enabled, // Enabled
KS_Future // Is a keyword in future standard
};
} // namespace
/// Translates flags as specified in TokenKinds.def into keyword status
/// in the given language standard.
static KeywordStatus getKeywordStatus(const LangOptions &LangOpts,
unsigned Flags) {
if (Flags == KEYALL) return KS_Enabled;
if (LangOpts.CPlusPlus && (Flags & KEYCXX)) return KS_Enabled;
if (LangOpts.CPlusPlus11 && (Flags & KEYCXX11)) return KS_Enabled;
if (LangOpts.CPlusPlus2a && (Flags & KEYCXX2A)) return KS_Enabled;
if (LangOpts.C99 && (Flags & KEYC99)) return KS_Enabled;
if (LangOpts.GNUKeywords && (Flags & KEYGNU)) return KS_Extension;
if (LangOpts.MicrosoftExt && (Flags & KEYMS)) return KS_Extension;
if (LangOpts.Borland && (Flags & KEYBORLAND)) return KS_Extension;
if (LangOpts.Bool && (Flags & BOOLSUPPORT)) return KS_Enabled;
if (LangOpts.Half && (Flags & HALFSUPPORT)) return KS_Enabled;
if (LangOpts.WChar && (Flags & WCHARSUPPORT)) return KS_Enabled;
if (LangOpts.Char8 && (Flags & CHAR8SUPPORT)) return KS_Enabled;
if (LangOpts.AltiVec && (Flags & KEYALTIVEC)) return KS_Enabled;
if (LangOpts.OpenCL && (Flags & KEYOPENCL)) return KS_Enabled;
if (!LangOpts.CPlusPlus && (Flags & KEYNOCXX)) return KS_Enabled;
if (LangOpts.C11 && (Flags & KEYC11)) return KS_Enabled;
// We treat bridge casts as objective-C keywords so we can warn on them
// in non-arc mode.
if (LangOpts.ObjC2 && (Flags & KEYARC)) return KS_Enabled;
if (LangOpts.ObjC2 && (Flags & KEYOBJC2)) return KS_Enabled;
if (LangOpts.ConceptsTS && (Flags & KEYCONCEPTS)) return KS_Enabled;
if (LangOpts.CoroutinesTS && (Flags & KEYCOROUTINES)) return KS_Enabled;
if (LangOpts.ModulesTS && (Flags & KEYMODULES)) return KS_Enabled;
if (LangOpts.CPlusPlus && (Flags & KEYALLCXX)) return KS_Future;
return KS_Disabled;
}
/// AddKeyword - This method is used to associate a token ID with specific
/// identifiers because they are language keywords. This causes the lexer to
/// automatically map matching identifiers to specialized token codes.
static void AddKeyword(StringRef Keyword,
tok::TokenKind TokenCode, unsigned Flags,
const LangOptions &LangOpts, IdentifierTable &Table) {
KeywordStatus AddResult = getKeywordStatus(LangOpts, Flags);
// Don't add this keyword under MSVCCompat.
if (LangOpts.MSVCCompat && (Flags & KEYNOMS18) &&
!LangOpts.isCompatibleWithMSVC(LangOptions::MSVC2015))
return;
// Don't add this keyword under OpenCL.
if (LangOpts.OpenCL && (Flags & KEYNOOPENCL))
return;
// Don't add this keyword if disabled in this language.
if (AddResult == KS_Disabled) return;
IdentifierInfo &Info =
Table.get(Keyword, AddResult == KS_Future ? tok::identifier : TokenCode);
Info.setIsExtensionToken(AddResult == KS_Extension);
Info.setIsFutureCompatKeyword(AddResult == KS_Future);
}
/// AddCXXOperatorKeyword - Register a C++ operator keyword alternative
/// representations.
static void AddCXXOperatorKeyword(StringRef Keyword,
tok::TokenKind TokenCode,
IdentifierTable &Table) {
IdentifierInfo &Info = Table.get(Keyword, TokenCode);
Info.setIsCPlusPlusOperatorKeyword();
}
/// AddObjCKeyword - Register an Objective-C \@keyword like "class" "selector"
/// or "property".
static void AddObjCKeyword(StringRef Name,
tok::ObjCKeywordKind ObjCID,
IdentifierTable &Table) {
Table.get(Name).setObjCKeywordID(ObjCID);
}
/// AddKeywords - Add all keywords to the symbol table.
///
void IdentifierTable::AddKeywords(const LangOptions &LangOpts) {
// Add keywords and tokens for the current language.
#define KEYWORD(NAME, FLAGS) \
AddKeyword(StringRef(#NAME), tok::kw_ ## NAME, \
FLAGS, LangOpts, *this);
#define ALIAS(NAME, TOK, FLAGS) \
AddKeyword(StringRef(NAME), tok::kw_ ## TOK, \
FLAGS, LangOpts, *this);
#define CXX_KEYWORD_OPERATOR(NAME, ALIAS) \
if (LangOpts.CXXOperatorNames) \
AddCXXOperatorKeyword(StringRef(#NAME), tok::ALIAS, *this);
#define OBJC1_AT_KEYWORD(NAME) \
if (LangOpts.ObjC1) \
AddObjCKeyword(StringRef(#NAME), tok::objc_##NAME, *this);
#define OBJC2_AT_KEYWORD(NAME) \
if (LangOpts.ObjC2) \
AddObjCKeyword(StringRef(#NAME), tok::objc_##NAME, *this);
#define TESTING_KEYWORD(NAME, FLAGS)
#include "clang/Basic/TokenKinds.def"
if (LangOpts.ParseUnknownAnytype)
AddKeyword("__unknown_anytype", tok::kw___unknown_anytype, KEYALL,
LangOpts, *this);
if (LangOpts.DeclSpecKeyword)
AddKeyword("__declspec", tok::kw___declspec, KEYALL, LangOpts, *this);
// Add the '_experimental_modules_import' contextual keyword.
get("import").setModulesImport(true);
}
/// Checks if the specified token kind represents a keyword in the
/// specified language.
/// \returns Status of the keyword in the language.
static KeywordStatus getTokenKwStatus(const LangOptions &LangOpts,
tok::TokenKind K) {
switch (K) {
#define KEYWORD(NAME, FLAGS) \
case tok::kw_##NAME: return getKeywordStatus(LangOpts, FLAGS);
#include "clang/Basic/TokenKinds.def"
default: return KS_Disabled;
}
}
/// Returns true if the identifier represents a keyword in the
/// specified language.
bool IdentifierInfo::isKeyword(const LangOptions &LangOpts) const {
switch (getTokenKwStatus(LangOpts, getTokenID())) {
case KS_Enabled:
case KS_Extension:
return true;
default:
return false;
}
}
/// Returns true if the identifier represents a C++ keyword in the
/// specified language.
bool IdentifierInfo::isCPlusPlusKeyword(const LangOptions &LangOpts) const {
if (!LangOpts.CPlusPlus || !isKeyword(LangOpts))
return false;
// This is a C++ keyword if this identifier is not a keyword when checked
// using LangOptions without C++ support.
LangOptions LangOptsNoCPP = LangOpts;
LangOptsNoCPP.CPlusPlus = false;
LangOptsNoCPP.CPlusPlus11 = false;
LangOptsNoCPP.CPlusPlus2a = false;
return !isKeyword(LangOptsNoCPP);
}
tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const {
// We use a perfect hash function here involving the length of the keyword,
// the first and third character. For preprocessor ID's there are no
// collisions (if there were, the switch below would complain about duplicate
// case values). Note that this depends on 'if' being null terminated.
#define HASH(LEN, FIRST, THIRD) \
(LEN << 5) + (((FIRST-'a') + (THIRD-'a')) & 31)
#define CASE(LEN, FIRST, THIRD, NAME) \
case HASH(LEN, FIRST, THIRD): \
return memcmp(Name, #NAME, LEN) ? tok::pp_not_keyword : tok::pp_ ## NAME
unsigned Len = getLength();
if (Len < 2) return tok::pp_not_keyword;
const char *Name = getNameStart();
switch (HASH(Len, Name[0], Name[2])) {
default: return tok::pp_not_keyword;
CASE( 2, 'i', '\0', if);
CASE( 4, 'e', 'i', elif);
CASE( 4, 'e', 's', else);
CASE( 4, 'l', 'n', line);
CASE( 4, 's', 'c', sccs);
CASE( 5, 'e', 'd', endif);
CASE( 5, 'e', 'r', error);
CASE( 5, 'i', 'e', ident);
CASE( 5, 'i', 'd', ifdef);
CASE( 5, 'u', 'd', undef);
CASE( 6, 'a', 's', assert);
CASE( 6, 'd', 'f', define);
CASE( 6, 'i', 'n', ifndef);
CASE( 6, 'i', 'p', import);
CASE( 6, 'p', 'a', pragma);
CASE( 7, 'd', 'f', defined);
CASE( 7, 'i', 'c', include);
CASE( 7, 'w', 'r', warning);
CASE( 8, 'u', 'a', unassert);
CASE(12, 'i', 'c', include_next);
CASE(14, '_', 'p', __public_macro);
CASE(15, '_', 'p', __private_macro);
CASE(16, '_', 'i', __include_macros);
#undef CASE
#undef HASH
}
}
//===----------------------------------------------------------------------===//
// Stats Implementation
//===----------------------------------------------------------------------===//
/// PrintStats - Print statistics about how well the identifier table is doing
/// at hashing identifiers.
void IdentifierTable::PrintStats() const {
unsigned NumBuckets = HashTable.getNumBuckets();
unsigned NumIdentifiers = HashTable.getNumItems();
unsigned NumEmptyBuckets = NumBuckets-NumIdentifiers;
unsigned AverageIdentifierSize = 0;
unsigned MaxIdentifierLength = 0;
// TODO: Figure out maximum times an identifier had to probe for -stats.
for (llvm::StringMap<IdentifierInfo*, llvm::BumpPtrAllocator>::const_iterator
I = HashTable.begin(), E = HashTable.end(); I != E; ++I) {
unsigned IdLen = I->getKeyLength();
AverageIdentifierSize += IdLen;
if (MaxIdentifierLength < IdLen)
MaxIdentifierLength = IdLen;
}
fprintf(stderr, "\n*** Identifier Table Stats:\n");
fprintf(stderr, "# Identifiers: %d\n", NumIdentifiers);
fprintf(stderr, "# Empty Buckets: %d\n", NumEmptyBuckets);
fprintf(stderr, "Hash density (#identifiers per bucket): %f\n",
NumIdentifiers/(double)NumBuckets);
fprintf(stderr, "Ave identifier length: %f\n",
(AverageIdentifierSize/(double)NumIdentifiers));
fprintf(stderr, "Max identifier length: %d\n", MaxIdentifierLength);
// Compute statistics about the memory allocated for identifiers.
HashTable.getAllocator().PrintStats();
}
//===----------------------------------------------------------------------===//
// SelectorTable Implementation
//===----------------------------------------------------------------------===//
unsigned llvm::DenseMapInfo<clang::Selector>::getHashValue(clang::Selector S) {
return DenseMapInfo<void*>::getHashValue(S.getAsOpaquePtr());
}
namespace clang {
/// MultiKeywordSelector - One of these variable length records is kept for each
/// selector containing more than one keyword. We use a folding set
/// to unique aggregate names (keyword selectors in ObjC parlance). Access to
/// this class is provided strictly through Selector.
class MultiKeywordSelector
: public DeclarationNameExtra, public llvm::FoldingSetNode {
MultiKeywordSelector(unsigned nKeys) {
ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys;
}
public:
// Constructor for keyword selectors.
MultiKeywordSelector(unsigned nKeys, IdentifierInfo **IIV) {
assert((nKeys > 1) && "not a multi-keyword selector");
ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys;
// Fill in the trailing keyword array.
IdentifierInfo **KeyInfo = reinterpret_cast<IdentifierInfo **>(this+1);
for (unsigned i = 0; i != nKeys; ++i)
KeyInfo[i] = IIV[i];
}
// getName - Derive the full selector name and return it.
std::string getName() const;
unsigned getNumArgs() const { return ExtraKindOrNumArgs - NUM_EXTRA_KINDS; }
using keyword_iterator = IdentifierInfo *const *;
keyword_iterator keyword_begin() const {
return reinterpret_cast<keyword_iterator>(this+1);
}
keyword_iterator keyword_end() const {
return keyword_begin()+getNumArgs();
}
IdentifierInfo *getIdentifierInfoForSlot(unsigned i) const {
assert(i < getNumArgs() && "getIdentifierInfoForSlot(): illegal index");
return keyword_begin()[i];
}
static void Profile(llvm::FoldingSetNodeID &ID,
keyword_iterator ArgTys, unsigned NumArgs) {
ID.AddInteger(NumArgs);
for (unsigned i = 0; i != NumArgs; ++i)
ID.AddPointer(ArgTys[i]);
}
void Profile(llvm::FoldingSetNodeID &ID) {
Profile(ID, keyword_begin(), getNumArgs());
}
};
} // namespace clang.
unsigned Selector::getNumArgs() const {
unsigned IIF = getIdentifierInfoFlag();
if (IIF <= ZeroArg)
return 0;
if (IIF == OneArg)
return 1;
// We point to a MultiKeywordSelector.
MultiKeywordSelector *SI = getMultiKeywordSelector();
return SI->getNumArgs();
}
IdentifierInfo *Selector::getIdentifierInfoForSlot(unsigned argIndex) const {
if (getIdentifierInfoFlag() < MultiArg) {
assert(argIndex == 0 && "illegal keyword index");
return getAsIdentifierInfo();
}
// We point to a MultiKeywordSelector.
MultiKeywordSelector *SI = getMultiKeywordSelector();
return SI->getIdentifierInfoForSlot(argIndex);
}
StringRef Selector::getNameForSlot(unsigned int argIndex) const {
IdentifierInfo *II = getIdentifierInfoForSlot(argIndex);
return II? II->getName() : StringRef();
}
std::string MultiKeywordSelector::getName() const {
SmallString<256> Str;
llvm::raw_svector_ostream OS(Str);
for (keyword_iterator I = keyword_begin(), E = keyword_end(); I != E; ++I) {
if (*I)
OS << (*I)->getName();
OS << ':';
}
return OS.str();
}
std::string Selector::getAsString() const {
if (InfoPtr == 0)
return "<null selector>";
if (getIdentifierInfoFlag() < MultiArg) {
IdentifierInfo *II = getAsIdentifierInfo();
if (getNumArgs() == 0) {
assert(II && "If the number of arguments is 0 then II is guaranteed to "
"not be null.");
return II->getName();
}
if (!II)
return ":";
return II->getName().str() + ":";
}
// We have a multiple keyword selector.
return getMultiKeywordSelector()->getName();
}
void Selector::print(llvm::raw_ostream &OS) const {
OS << getAsString();
}
/// Interpreting the given string using the normal CamelCase
/// conventions, determine whether the given string starts with the
/// given "word", which is assumed to end in a lowercase letter.
static bool startsWithWord(StringRef name, StringRef word) {
if (name.size() < word.size()) return false;
return ((name.size() == word.size() || !isLowercase(name[word.size()])) &&
name.startswith(word));
}
ObjCMethodFamily Selector::getMethodFamilyImpl(Selector sel) {
IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
if (!first) return OMF_None;
StringRef name = first->getName();
if (sel.isUnarySelector()) {
if (name == "autorelease") return OMF_autorelease;
if (name == "dealloc") return OMF_dealloc;
if (name == "finalize") return OMF_finalize;
if (name == "release") return OMF_release;
if (name == "retain") return OMF_retain;
if (name == "retainCount") return OMF_retainCount;
if (name == "self") return OMF_self;
if (name == "initialize") return OMF_initialize;
}
if (name == "performSelector" || name == "performSelectorInBackground" ||
name == "performSelectorOnMainThread")
return OMF_performSelector;
// The other method families may begin with a prefix of underscores.
while (!name.empty() && name.front() == '_')
name = name.substr(1);
if (name.empty()) return OMF_None;
switch (name.front()) {
case 'a':
if (startsWithWord(name, "alloc")) return OMF_alloc;
break;
case 'c':
if (startsWithWord(name, "copy")) return OMF_copy;
break;
case 'i':
if (startsWithWord(name, "init")) return OMF_init;
break;
case 'm':
if (startsWithWord(name, "mutableCopy")) return OMF_mutableCopy;
break;
case 'n':
if (startsWithWord(name, "new")) return OMF_new;
break;
default:
break;
}
return OMF_None;
}
ObjCInstanceTypeFamily Selector::getInstTypeMethodFamily(Selector sel) {
IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
if (!first) return OIT_None;
StringRef name = first->getName();
if (name.empty()) return OIT_None;
switch (name.front()) {
case 'a':
if (startsWithWord(name, "array")) return OIT_Array;
break;
case 'd':
if (startsWithWord(name, "default")) return OIT_ReturnsSelf;
if (startsWithWord(name, "dictionary")) return OIT_Dictionary;
break;
case 's':
if (startsWithWord(name, "shared")) return OIT_ReturnsSelf;
if (startsWithWord(name, "standard")) return OIT_Singleton;
break;
case 'i':
if (startsWithWord(name, "init")) return OIT_Init;
default:
break;
}
return OIT_None;
}
ObjCStringFormatFamily Selector::getStringFormatFamilyImpl(Selector sel) {
IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
if (!first) return SFF_None;
StringRef name = first->getName();
switch (name.front()) {
case 'a':
if (name == "appendFormat") return SFF_NSString;
break;
case 'i':
if (name == "initWithFormat") return SFF_NSString;
break;
case 'l':
if (name == "localizedStringWithFormat") return SFF_NSString;
break;
case 's':
if (name == "stringByAppendingFormat" ||
name == "stringWithFormat") return SFF_NSString;
break;
}
return SFF_None;
}
namespace {
struct SelectorTableImpl {
llvm::FoldingSet<MultiKeywordSelector> Table;
llvm::BumpPtrAllocator Allocator;
};
} // namespace
static SelectorTableImpl &getSelectorTableImpl(void *P) {
return *static_cast<SelectorTableImpl*>(P);
}
SmallString<64>
SelectorTable::constructSetterName(StringRef Name) {
SmallString<64> SetterName("set");
SetterName += Name;
SetterName[3] = toUppercase(SetterName[3]);
return SetterName;
}
Selector
SelectorTable::constructSetterSelector(IdentifierTable &Idents,
SelectorTable &SelTable,
const IdentifierInfo *Name) {
IdentifierInfo *SetterName =
&Idents.get(constructSetterName(Name->getName()));
return SelTable.getUnarySelector(SetterName);
}
size_t SelectorTable::getTotalMemory() const {
SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
return SelTabImpl.Allocator.getTotalMemory();
}
Selector SelectorTable::getSelector(unsigned nKeys, IdentifierInfo **IIV) {
if (nKeys < 2)
return Selector(IIV[0], nKeys);
SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
// Unique selector, to guarantee there is one per name.
llvm::FoldingSetNodeID ID;
MultiKeywordSelector::Profile(ID, IIV, nKeys);
void *InsertPos = nullptr;
if (MultiKeywordSelector *SI =
SelTabImpl.Table.FindNodeOrInsertPos(ID, InsertPos))
return Selector(SI);
// MultiKeywordSelector objects are not allocated with new because they have a
// variable size array (for parameter types) at the end of them.
unsigned Size = sizeof(MultiKeywordSelector) + nKeys*sizeof(IdentifierInfo *);
MultiKeywordSelector *SI =
(MultiKeywordSelector *)SelTabImpl.Allocator.Allocate(
Size, alignof(MultiKeywordSelector));
new (SI) MultiKeywordSelector(nKeys, IIV);
SelTabImpl.Table.InsertNode(SI, InsertPos);
return Selector(SI);
}
SelectorTable::SelectorTable() {
Impl = new SelectorTableImpl();
}
SelectorTable::~SelectorTable() {
delete &getSelectorTableImpl(Impl);
}
const char *clang::getOperatorSpelling(OverloadedOperatorKind Operator) {
switch (Operator) {
case OO_None:
case NUM_OVERLOADED_OPERATORS:
return nullptr;
#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
case OO_##Name: return Spelling;
#include "clang/Basic/OperatorKinds.def"
}
llvm_unreachable("Invalid OverloadedOperatorKind!");
}
StringRef clang::getNullabilitySpelling(NullabilityKind kind,
bool isContextSensitive) {
switch (kind) {
case NullabilityKind::NonNull:
return isContextSensitive ? "nonnull" : "_Nonnull";
case NullabilityKind::Nullable:
return isContextSensitive ? "nullable" : "_Nullable";
case NullabilityKind::Unspecified:
return isContextSensitive ? "null_unspecified" : "_Null_unspecified";
}
llvm_unreachable("Unknown nullability kind.");
}
| [
"[email protected]"
] | [
[
[
1,
711
]
]
] |
a2217316639cd4eab47041d6423b923823df03c1 | c89bbbf91d09899202c6a430b88a80c47171b504 | /RdbCache.h | 757ca49f71fe782b5ab5abbd4290467d5db55f1a | [
"GPL-2.0-or-later",
"Apache-2.0"
] | permissive | diffbot/open-source-search-engine | 7a7a410885059da09d79a8cb9a642c62c4798222 | deb5c5b1327303e87c3b182d5396caaeb87191ad | refs/heads/master | 2020-12-25T17:44:38.936899 | 2018-06-14T16:17:32 | 2018-06-14T16:17:32 | 12,497,126 | 25 | 11 | Apache-2.0 | 2018-06-14T16:17:33 | 2013-08-30T22:59:19 | C++ | UTF-8 | C++ | false | false | 12,591 | h | // . Matt Wells, copyright Feb 2001
// . we use a big buffer, m_buf, into which we sequentially store records as
// they are added to the cache
// . each record we store in the big buffer has a header which consists
// of a key_t, recordSize(int32_t), timestamp and the record data
// . the header is as follows:
// a collnum_t (use sizeof(collnum_t)) that identifies the collection
// a 12 byte key_t (actually, it is now m_cks bytes)
// a 4 bytes timestamp (seconds since the epoch, like time_t)
// a 4 bytes data size
// the data
// . we have a hash table that maps a key_t to a ptr to a record header in the
// big buffer
// . what if we run out of room in the hash table? we delete the oldest
// records in the big buffer so we can remove their ptrs from the hash table
// . we keep an "tail" ptr into the hash table that point to the last
// non-overwritten record in the big buffer
// . when we run out of room in the big buffer we wrap our ptr to the start
// and we remove any records from the hashtable that we overwrite using
// the tail ptr
// . when a record is read from the cache we also promote it by copying it to
// the head of m_buf, m_bufOffset. since modern day pentiums do 2.5-6.4GB/s
// this is ok, it will not be the bottleneck by far. if the record is
// expired we do not promote it. The advantage is we don't have ANY memory
// fragmentation and utilize 100% of the memory. Copying a 6 Megabyte
// list takes like 2.4ms on a new pentium, so we should allow regular
// allocating if the record size is 256k or more. Copying 256k only
// takes .1 ms on the P4 2.60CGHz. This is on the TODO list.
#ifndef RDBCACHE_H
#define RDBCACHE_H
// . TODO:
// . if size of added rec is ABOVE this, then don't use our memory buffer
// . because we copy a rec to the head of memory buffer (m_bufOffset) every
// time that rec is accessed and doing that for big recs is more intensive
// . the idea is that allocating/freeing memory for smaller recs is what
// causes the memory fragmentation
// . to stay under m_maxMem we should limit each memory buffer to 1M or so
// and free the tailing memory buffer to make room for a large unbuffered rec
//#define MEM_LIMIT (256*1024)
#include <time.h> // time_t
#include "Mem.h" // g_mem.calloc()
#include "RdbList.h"
extern bool g_cacheWritesEnabled;
class RdbCache {
public:
friend class Rdb;
// constructor & destructor
RdbCache();
~RdbCache();
void reset();
// . this just clears the contents of the cache for a particular coll
// . used by g_collectiondb.delRec() call to Rdb::delColl() to
// clear out the collection's stuff in the cache
void clear ( collnum_t collnum ) ;
bool isInitialized () {
if ( m_ptrs ) return true;
return false;
};
// . we are allowed to keep a min mem of "minCacheSize"
// . a fixedDataSize of -1 means the dataSize varies from rec to rec
// . set "maxNumNodes" to -1 for it to be auto determined
// . can only do this if fixedDataSize is not -1
bool init ( int32_t maxCacheMem ,
int32_t fixedDataSize ,
bool supportLists ,
int32_t maxCacheNodes ,
bool useHalfKeys ,
char *dbname ,
//bool loadFromDisk );
bool loadFromDisk ,
char cacheKeySize = 12 ,
char dataKeySize = 12 ,
int32_t numPtrsMax = -1 );
// . a quick hack for SpiderCache.cpp
// . if your record is always a 4 byte int32_t call this
// . returns -1 if not found, so don't store -1 in there then
int64_t getLongLong ( collnum_t collnum ,
uint32_t key , int32_t maxAge , // in seconds
bool promoteRecord );
// this puts a int32_t in there
void addLongLong ( collnum_t collnum ,
uint32_t key , int64_t value ,
char **retRecPtr = NULL ) ;
// . both key and data are int64_ts here
// . returns -1 if not found
int64_t getLongLong2 ( collnum_t collnum ,
uint64_t key ,
int32_t maxAge , // in seconds
bool promoteRecord );
// this puts a int32_t in there
void addLongLong2 ( collnum_t collnum ,
uint64_t key , int64_t value ,
char **retRecPtr = NULL ) ;
// same routines for int32_ts now, but key is a int64_t
int32_t getLong ( collnum_t collnum ,
uint64_t key , int32_t maxAge , // in seconds
bool promoteRecord );
void addLong ( collnum_t collnum ,
uint64_t key , int32_t value ,
char **retRecPtr = NULL ) ;
// . returns true if found, false if not found in cache
// . sets *rec and *recSize iff found
// . sets *cachedTime to time the rec was cached
// . use maxAge of -1 to have no limit to the age of cached rec
bool getRecord ( collnum_t collnum ,
//key_t cacheKey ,
char *cacheKey ,
char **rec ,
int32_t *recSize ,
bool doCopy ,
int32_t maxAge , // in seconds
bool incCounts ,
time_t *cachedTime = NULL ,
bool promoteRecord = true );
bool getRecord ( char *coll ,
//key_t cacheKey ,
char *cacheKey ,
char **rec ,
int32_t *recSize ,
bool doCopy ,
int32_t maxAge , // in seconds
bool incCounts ,
time_t *cachedTime = NULL ,
bool promoteRecord = true);
bool getRecord ( collnum_t collnum ,
key_t cacheKey ,
char **rec ,
int32_t *recSize ,
bool doCopy ,
int32_t maxAge , // in seconds
bool incCounts ,
time_t *cachedTime = NULL,
bool promoteRecord = true) {
return getRecord (collnum,(char *)&cacheKey,rec,recSize,doCopy,
maxAge,incCounts,cachedTime, promoteRecord);
};
bool getRecord ( char *coll ,
key_t cacheKey ,
char **rec ,
int32_t *recSize ,
bool doCopy ,
int32_t maxAge , // in seconds
bool incCounts ,
time_t *cachedTime = NULL,
bool promoteRecord = true) {
return getRecord (coll,(char *)&cacheKey,rec,recSize,doCopy,
maxAge,incCounts,cachedTime, promoteRecord);
};
bool setTimeStamp ( collnum_t collnum ,
key_t cacheKey ,
int32_t newTimeStamp ) {
return setTimeStamp ( collnum ,
(char *)&cacheKey ,
newTimeStamp );
};
bool setTimeStamp ( collnum_t collnum ,
char *cacheKey ,
int32_t newTimeStamp );
// . returns true if found, false if not found
// . sets errno no error
// . if "copyRecords" is true then COPIES into a new buffer
// . maxAge constraint for ignoring the stale nodes
// . promotes the returned list to the head of the linked list
// . maxAge of -1 means no maxAge
// . maxAge of 0 means do not check the cache
// . uses "startKey" to get the list
// . if "incCounts" is true and we hit we inc the hit count
// . if "incCounts" is true and we miss we inc the miss count
bool getList ( collnum_t collnum ,
//key_t cacheKey ,
//key_t startKey ,
char *cacheKey ,
char *startKey ,
RdbList *list ,
bool doCopy ,
int32_t maxAge , // in seconds
bool incCounts );
// use this key for cache lookup of the list rather than form from
// startKey/endKey
bool addList ( collnum_t collnum , char *cacheKey , RdbList *list );
bool addList ( collnum_t collnum , key_t cacheKey , RdbList *list ) {
return addList(collnum,(char *)&cacheKey,list); };
bool addList ( char *coll , char *cacheKey , RdbList *list );
bool addList ( char *coll , key_t cacheKey , RdbList *list ) {
return addList(coll,(char *)&cacheKey,list); };
// . add a list of only 1 record
// . return false on error and set g_errno, otherwise return true
// . recOffset is proper offset into the buffer system
bool addRecord ( collnum_t collnum ,
//key_t cacheKey ,
char *cacheKey ,
char *rec ,
int32_t recSize ,
int32_t timestamp = 0 ,
char **retRecPtr = NULL ) ;
bool addRecord ( char *coll ,
//key_t cacheKey ,
char *cacheKey ,
char *rec ,
int32_t recSize ,
int32_t timestamp = 0 );
bool addRecord ( collnum_t collnum ,
key_t cacheKey ,
char *rec ,
int32_t recSize ,
int32_t timestamp = 0 ) {
return addRecord(collnum,(char *)&cacheKey,rec,recSize,
timestamp); };
bool addRecord ( char *coll ,
key_t cacheKey ,
char *rec ,
int32_t recSize ,
int32_t timestamp = 0 ) {
return addRecord(coll,(char *)&cacheKey,rec,recSize,
timestamp); };
void verify();
// . just checks to see if a record is in the cache
// . does not promote record
// . used by Msg34.cpp for disk load balancing
bool isInCache ( collnum_t collnum , char *cacheKey , int32_t maxAge );
bool isInCache ( collnum_t collnum , key_t cacheKey , int32_t maxAge ) {
return isInCache(collnum,(char *)&cacheKey,maxAge);};
// these include our mem AND our tree's mem combined
int32_t getMemOccupied () {
return m_memOccupied ; };
int32_t getMemAlloced () {
return m_memAlloced ; };
//int32_t getRecOverhead () {
// return 3*4 + m_tree.m_overhead; };
int32_t getMaxMem () { return m_maxMem; };
//int32_t getBaseMem () {
// return m_baseMem + m_tree.m_baseMem; };
// cache stats
int64_t getNumHits () { return m_numHits; };
int64_t getNumMisses () { return m_numMisses; };
int64_t getHitBytes () { return m_hitBytes; };
int32_t getNumUsedNodes () { return m_numPtrsUsed; };
int32_t getNumTotalNodes () { return m_numPtrsMax ; };
bool useDisk ( ) { return m_useDisk; };
bool load ( char *dbname );
bool save ( bool useThreads );
bool save_r ( );
bool save2_r ( int fd );
void threadDone ( );
bool load ( );
int32_t m_saveError;
// called internally by save()
bool saveSome_r ( int fd, int32_t *iptr , int32_t *off ) ;
// remove a key range from the cache
void removeKeyRange ( collnum_t collnum,
char *startKey,
char *endKey );
char *getDbname () { return m_dbname ; };
char *m_dbname;
// private:
bool addRecord ( collnum_t collnum ,
//key_t cacheKey ,
char *cacheKey ,
char *rec1 ,
int32_t recSize1 ,
char *rec2 ,
int32_t recSize2 ,
int32_t timestamp ,
char **retRecPtr = NULL ) ;
bool deleteRec ( );
//void addKey ( collnum_t collnum , key_t key , char *ptr ) ;
//void removeKey ( collnum_t collnum , key_t key , char *rec ) ;
void addKey ( collnum_t collnum , char *key , char *ptr ) ;
void removeKey ( collnum_t collnum , char *key , char *rec ) ;
void markDeletedRecord(char *ptr);
bool convertCache ( int32_t numPtrsMax , int32_t maxMem ) ;
bool m_convert;
int32_t m_convertNumPtrsMax;
int32_t m_convertMaxMem;
bool m_isSaving;
// . mem stats -- just for arrays we contain -- not in tree
// . memory that is allocated and in use, including dataSizes
int32_t m_memOccupied;
// total memory allocated including dataSizes of our records
int32_t m_memAlloced;
// allocated memory for m_next/m_prev/m_time arrays
//int32_t m_baseMem;
// don't let m_memAlloced exceed this
int32_t m_maxMem;
// . data is stored in m_bufs, an array of buffers
// . we may have to use multiple bufs because we cannot allocate more
// than 128 Megabytes without pthread_create() failing
// . we can have up to 32 bufs of 128M each, that's 4 gigs, plenty
char *m_bufs [32];
int32_t m_bufSizes [32]; // size of the alloc'd space
int32_t m_numBufs;
int32_t m_totalBufSize; // gbpwrite() assumes 32 bits
int32_t m_offset; // where next rec is stored
int32_t m_tail; // next rec to delete
// the hash table, buckets are ptrs into an m_bufs[i]
char **m_ptrs;
int32_t m_numPtrsMax;
int32_t m_numPtrsUsed;
int32_t m_threshold;
// use this for testing to make sure cache doesn't fuck up the content
//int32_t *m_crcs;
// cache hits and misses
int64_t m_numHits; // includes partial hits & cached not-founds too
//int64_t m_numPartialHits;
int64_t m_numMisses;
int64_t m_hitBytes;
int32_t m_fixedDataSize;
bool m_supportLists;
bool m_useHalfKeys;
bool m_useDisk; // load/save from disk?
// have we wrapped yet?
int8_t m_wrapped;
// keySize of cache keys in bytes
char m_cks;
// keysize of lists for addList() and getList()
char m_dks;
// count the add ops
int64_t m_adds;
int64_t m_deletes;
char m_needsSave;
char m_corruptionDetected;
int64_t m_maxColls;
};
#endif
| [
"mwells@titan.(none)",
"[email protected]",
"[email protected]"
] | [
[
[
1,
5
],
[
7,
30
],
[
33,
75
],
[
78,
78
],
[
80,
85
],
[
87,
88
],
[
90,
90
],
[
93,
94
],
[
96,
96
],
[
98,
99
],
[
101,
101
],
[
105,
106
],
[
108,
108
],
[
110,
111
],
[
115,
116
],
[
118,
122
],
[
124,
127
],
[
129,
129
],
[
131,
138
],
[
140,
140
],
[
142,
148
],
[
150,
150
],
[
152,
161
],
[
163,
163
],
[
165,
173
],
[
175,
181
],
[
183,
200
],
[
202,
220
],
[
223,
228
],
[
231,
234
],
[
237,
242
],
[
245,
252
],
[
255,
257
],
[
259,
259
],
[
261,
261
],
[
263,
263
],
[
265,
265
],
[
267,
268
],
[
274,
278
],
[
280,
281
],
[
283,
284
],
[
286,
301
],
[
303,
303
],
[
306,
314
],
[
316,
316
],
[
319,
323
],
[
325,
325
],
[
327,
327
],
[
329,
329
],
[
331,
336
],
[
342,
344
],
[
348,
348
],
[
350,
351
],
[
356,
356
],
[
358,
362
],
[
364,
371
],
[
374,
377
],
[
380,
382
]
],
[
[
6,
6
],
[
31,
32
],
[
76,
77
],
[
79,
79
],
[
86,
86
],
[
89,
89
],
[
91,
92
],
[
95,
95
],
[
97,
97
],
[
100,
100
],
[
102,
104
],
[
107,
107
],
[
109,
109
],
[
112,
114
],
[
117,
117
],
[
123,
123
],
[
128,
128
],
[
130,
130
],
[
139,
139
],
[
141,
141
],
[
149,
149
],
[
151,
151
],
[
162,
162
],
[
164,
164
],
[
174,
174
],
[
182,
182
],
[
201,
201
],
[
221,
222
],
[
229,
230
],
[
235,
236
],
[
243,
244
],
[
253,
254
],
[
258,
258
],
[
260,
260
],
[
262,
262
],
[
264,
264
],
[
266,
266
],
[
269,
273
],
[
279,
279
],
[
282,
282
],
[
285,
285
],
[
302,
302
],
[
304,
305
],
[
315,
315
],
[
317,
318
],
[
324,
324
],
[
326,
326
],
[
328,
328
],
[
330,
330
],
[
337,
341
],
[
345,
347
],
[
349,
349
],
[
352,
355
],
[
357,
357
],
[
363,
363
],
[
372,
373
],
[
379,
379
]
],
[
[
378,
378
]
]
] |
e1b1240b296621b5523630b31d65b88d88af048e | d8f1638d63e611ed1619755ca26de4ea96bf1d7b | /PC_Interface/Interface/Interface.ino | 4fdf5155133640117e627d876a20a1401953a9b5 | [] | no_license | schmitfe/Stimulator_FPGA | 27b3e14bdb0330579ac6c8e2bada5dd41820bf74 | 1016d487b89ac5f1de4d3648e18f312f3439ba7e | refs/heads/master | 2023-02-11T19:23:52.376766 | 2019-12-31T15:10:30 | 2019-12-31T15:10:30 | 199,415,384 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,776 | ino | /*
Copyright (c) 2019 Stefan Kremser
This software is licensed under the MIT License. See the license file for details.
Source: github.com/spacehuhn/SimpleCLI
*/
/*
Adapted by Felix Schmitt to create Interface for Stimulator.
PLEASE NOTE: 115200 is the baud rate and Newline is enabled in the serial monitor
*/
// Inlcude Library Command Line
#include <SimpleCLI.h>
#include <SPI.h>
#include "SdFat.h"
#include "sdios.h"
//#include "Pins.h"
#include "JsonStreamingParser.h"
#include "JsonListener.h"
#include "Parser.h"
#define Channels 2
//Defines number of Channels, not tested with more channels possible errors at the write functin
//for channel adress, trig and
// Create CLI Object
SimpleCLI cli;
// Commands
Command cmdLs;
Command cmdRm;
Command cmdStore;
Command cmdReset;
Command cmdWF;
Command cmdtrig;
Command cmdHelp;
Command cmdDesc;
Command cmdAmpli;
Command cmdInterIv;
Command cmdInterPer;
Command cmdWave;
Command cmdDoutDebug;
// set up variables using the SD utility library functions:
// File system object.
SdFat sd;
// Directory file.
SdFile root;
// Use for file creation in folders.
SdFile file;
//----------Pins---------------//
const unsigned int Ptrig[] = {49, 51, 53}; //Ptrig all, ch0 -x
const unsigned int P_RESET = 68;
const unsigned int P_RESET_CH = 69;
const unsigned int PinsInterPeriod[] = {61, 60, 59, 58, 57, 56, 55, 54};//{54, 55, 56, 57, 58, 59, 60, 61};
const unsigned int PinsInterInterval[] = {10, 9, 8, 7, 6, 5, 4, 3}; //{3, 4, 5, 6, 7,8,9,10};
const unsigned int PinsAmplitude[] = {21, 20, 19, 18};
const unsigned int PWrite = 63;
const unsigned int PWrite2 = 36;
const unsigned int PWrite3 = 37;
const unsigned int P_EnWrite = 62;
const unsigned int PWaveAddr[] = {64};
const unsigned int PWriteConfig = {65};
const unsigned int PChanAdress[] = {66};
const unsigned int PChanAdress2[] = {38};
const unsigned int PChanAdress3[] = {39};
const unsigned int PDout[] = {25, 26, 27, 28, 14, 15, 29, 11}; // Has to be on same port of SAM, Arduino ports are not ordered!
const unsigned int chipSelect = 52; //SD-Card
//---------------buffers---------------------//
char bufferJson[40];
//-------struct to store data of channels----//
typedef struct {
int amplitude;
int iinterval;
int iperiod;
int waveadress;
} SChannelSet;
SChannelSet *ChannelSet = NULL;
void setup() {
//--------setup of pins---------------//
int ii;
for ( ii = 0; ii < sizeof(Ptrig) / sizeof(Ptrig[0]); ii = ii + 1 ) {
pinMode(Ptrig[ii], OUTPUT);
digitalWrite(Ptrig[ii], LOW);
}
for ( ii = 0; ii < sizeof(PinsInterPeriod) / sizeof(PinsInterPeriod[0]); ii = ii + 1 ) {
pinMode(PinsInterPeriod[ii], OUTPUT);
digitalWrite(PinsInterPeriod[ii], LOW);
}
for ( ii = 0; ii < sizeof(PinsInterInterval) / sizeof(PinsInterInterval[0]); ii = ii + 1 ) {
pinMode(PinsInterInterval[ii], OUTPUT);
digitalWrite(PinsInterInterval[ii], LOW);
}
for ( ii = 0; ii < sizeof(PWaveAddr) / sizeof(PWaveAddr[0]); ii = ii + 1 ) {
pinMode(PWaveAddr[ii], OUTPUT);
digitalWrite(PWaveAddr[ii], LOW);
}
for ( ii = 0; ii < sizeof(PinsAmplitude) / sizeof(PinsAmplitude[0]); ii = ii + 1 ) {
pinMode(PinsAmplitude[ii], OUTPUT);
digitalWrite(PinsAmplitude[ii], LOW);
}
for ( ii = 0; ii < sizeof(PChanAdress) / sizeof(PChanAdress[0]); ii = ii + 1 ) {
pinMode(PChanAdress[ii], OUTPUT);
digitalWrite(PChanAdress[ii], LOW);
pinMode(PChanAdress2[ii], OUTPUT);
digitalWrite(PChanAdress2[ii], LOW);
pinMode(PChanAdress3[ii], OUTPUT);
digitalWrite(PChanAdress3[ii], LOW);
}
for ( ii = 0; ii < sizeof(PDout) / sizeof(PDout[0]); ii = ii + 1 ) {
pinMode(PDout[ii], OUTPUT);
digitalWrite(PDout[ii], LOW);
}
pinMode(P_RESET, OUTPUT);
digitalWrite(P_RESET, LOW);
pinMode(P_RESET_CH, OUTPUT);
digitalWrite(P_RESET_CH, LOW);
pinMode(PWrite, OUTPUT);
digitalWrite(PWrite, LOW);
pinMode(PWrite2, OUTPUT);
digitalWrite(PWrite, LOW);
pinMode(PWrite3, OUTPUT);
digitalWrite(PWrite, LOW);
pinMode(P_EnWrite, OUTPUT);
digitalWrite(P_EnWrite, LOW);
pinMode(PWriteConfig, OUTPUT);
digitalWrite(PWriteConfig, LOW);
//--------setup of interface---------------//
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.println("\nInitializing SD card...");
// we'll use the initialization code from the utility libraries
// since we're just testing if the card is working!
// Initialize at the highest speed supported by the board that is
// not over 50 MHz. Try a lower speed if SPI errors occur.
if (!sd.begin(chipSelect, SD_SCK_MHZ(50))) { //should be 50
sd.initErrorHalt();
}
//--------setup of channel settings---------------//
ChannelSet = (SChannelSet*) malloc(sizeof * ChannelSet * (Channels + 1));
//Channel zero contains defaultvalues
ChannelSet[0].amplitude = 1;
ChannelSet[0].iinterval = 0;
ChannelSet[0].iperiod = 0;
ChannelSet[0].waveadress = 0;
for ( ii = 1; ii < Channels + 1 ; ii = ii + 1 ) {
ChannelSet[ii].amplitude = ChannelSet[0].amplitude;
ChannelSet[ii].iinterval = ChannelSet[0].iinterval;
ChannelSet[ii].iperiod = ChannelSet[0].iperiod;
ChannelSet[ii].waveadress = ChannelSet[0].waveadress;
}
//--------creation of commands---------------//
cmdLs = cli.addCmd("ls");
cmdRm = cli.addCmd("rm");
cmdRm.addPosArg("file");
cmdStore = cli.addCmd("store");
cmdStore.addPosArg("file");
cmdReset = cli.addCmd("reset");
cmdReset.addPosArg("ID");
cmdWF = cli.addCmd("WF");
cmdWF.addPosArg("file");
cmdWF.addPosArg("ID");
cmdtrig = cli.addCmd("trig");
cmdtrig.addPosArg("ID");
cmdDesc = cli.addCmd("descrip");
cmdDesc.addPosArg("file");
cmdAmpli = cli.addCmd("amp");
cmdAmpli.addPosArg("ID");
cmdAmpli.addPosArg("value");
cmdInterIv = cli.addCmd("iniv");
cmdInterIv.addPosArg("ID");
cmdInterIv.addPosArg("value");
cmdInterPer = cli.addCmd("inper");
cmdInterPer.addPosArg("ID");
cmdInterPer.addPosArg("value");
cmdWave = cli.addCmd("wave");
cmdWave.addPosArg("ID");
cmdWave.addPosArg("value");
cmdHelp = cli.addCommand("help");
cmdDoutDebug=cli.addCmd("ddeb"); //debuggig command
cmdDoutDebug.addPosArg("value");
Serial.println("CLI: type help for commandlist");
}
void loop() {
//--------CLI loop---------------//
if (Serial.available()) {
String input = Serial.readStringUntil('\n');
if (input.length() > 0) {
// Serial.print("# ");
cli.parse(input);
}
}
if (cli.available()) {
Command c = cli.getCmd();
int argNum = c.countArgs();
/* Serial.print("> ");
// Serial.print(c.getName());
// Serial.print(' ');
for (int i = 0; i < argNum; ++i) {
Argument arg = c.getArgument(i);
// if(arg.isSet()) {
Serial.print(arg.toString());
Serial.print(' ');
}
Serial.println();
*/
//--------if input available find corresponding command---------------//
if (c == cmdLs) {
listFolder();
} else if (c == cmdRm) {
RemoveDir (c.getArgument(0));
} else if (c == cmdStore) {
SaveFile(c.getArgument(0));
} else if (c == cmdDesc) {
description(c.getArgument(0));
} else if (c == cmdAmpli) {
setAmplitude(c.getArgument(0), c.getArgument(1));
} else if (c == cmdInterIv) {
setInterInterval(c.getArgument(0), c.getArgument(1));
} else if (c == cmdInterPer) {
setInterPeriod(c.getArgument(0), c.getArgument(1));
} else if (c == cmdWave) {
setWaveadress(c.getArgument(0), c.getArgument(1));
} else if (c == cmdReset) {
reset(c.getArgument(0));
} else if (c == cmdWF) {
loadWaveform(c.getArgument(0), c.getArgument(1));
} else if (c == cmdtrig) {
Argument str = c.getArgument(0);
trigger(str.getValue().toInt());
} else if (c == cmdHelp) {
Serial.println("Help:");
Serial.println(cli.toString());
} else if(c == cmdDoutDebug){
Serial.println(c.getArgument(0).getValue());
WriteDoutDebug(c.getArgument(0));
}
}
if (cli.errored()) {
CommandError cmdError = cli.getError();
Serial.print("ERROR: ");
Serial.println(cmdError.toString());
if (cmdError.hasCommand()) {
Serial.print("Did you mean \"");
Serial.print(cmdError.getCommand().toString());
Serial.println("\"?");
}
}
}
//--------functions to call in loop---------------//
void storeChannel(Argument id)
{
unsigned long curTime;
digitalWrite(PWriteConfig, LOW);
curTime=micros();
Channeladress(id.getValue().toInt());
writePinArray(ChannelSet[id.getValue().toInt()].amplitude, PinsAmplitude, sizeof(PinsAmplitude) / sizeof(PinsAmplitude[0]));
writePinArray(ChannelSet[id.getValue().toInt()].iperiod, PinsInterPeriod, sizeof(PinsInterPeriod) / sizeof(PinsInterPeriod[0]));
writePinArray(ChannelSet[id.getValue().toInt()].iinterval, PinsInterInterval, sizeof(PinsInterInterval) / sizeof(PinsInterInterval[0]));
writePinArray( ChannelSet[id.getValue().toInt()].waveadress, PWaveAddr, sizeof(PWaveAddr) / sizeof(PWaveAddr[0]));
while(micros()-curTime <2);
digitalWrite(PWriteConfig, HIGH);
}
void writePinArray(int value, const unsigned int *Pins, int NPins)
{
int ii;
for(ii = 0; ii < NPins ; ii = ii + 1 ) {
if( bitRead(value,ii)==1){
digitalWrite(Pins[NPins-1-ii],HIGH);
} else{
digitalWrite(Pins[NPins-1-ii],LOW);
}
}
}
void setAmplitude(Argument id, Argument value)
{
ChannelSet[id.getValue().toInt()].amplitude = value.getValue().toInt();
storeChannel(id);
}
void setInterInterval(Argument id, Argument value)
{
ChannelSet[id.getValue().toInt()].iinterval = value.getValue().toInt();
storeChannel(id);
}
void setWaveadress(Argument id, Argument value)
{
ChannelSet[id.getValue().toInt()].waveadress = value.getValue().toInt();
storeChannel(id);
}
void setInterPeriod(Argument id, Argument value)
{
ChannelSet[id.getValue().toInt()].iperiod = value.getValue().toInt();
storeChannel(id);
}
void loadWaveform(Argument pathStr, Argument id)
{
bool WriteWFs = true; //Let parser write to FPGA
String Description = "";
//reset(id);
JsonStreamingParser parser;
Listener listener(&WriteWFs, &Description, PWrite, PWrite2, PWrite3, PWriteConfig, PWaveAddr, 2); //bad way of introducing additional parameters
parser.setListener(&listener);
File myFile;
if (!sd.chdir("/")) {
Serial.println("Error: opening root!");
}
sd.chdir("WF");
char path[12];
pathStr.getValue().toCharArray(path, 12);
myFile = sd.open(path, FILE_READ);
Channeladress(id.getValue().toInt());
digitalWrite(P_EnWrite, HIGH);
unsigned long curTime;
curTime = micros();
while (micros() - curTime < 500);
while (myFile.available()) {
parser.parse(myFile.read());
}
myFile.close();
digitalWrite(P_EnWrite, LOW);
Channeladress(0);
WriteWFs = false;
}
void description(Argument pathStr)
{
bool WriteWFs = false;
String Description = "";
JsonStreamingParser parser;
Listener listener(&WriteWFs, &Description,PWrite, PWrite2, PWrite3, PWriteConfig, PWaveAddr, 2); //bad way of introducing additional parameters
parser.setListener(&listener);
File myFile;
if (!sd.chdir("/")) {
Serial.println("Error: opening root!");
}
sd.chdir("WF");
char path[12];
pathStr.getValue().toCharArray(path, 12);
myFile = sd.open(path, FILE_READ);
WriteWFs = false; //Let parser write to FPGA
while (myFile.available()) {
parser.parse(myFile.read());
}
myFile.close();
Serial.print("Description of " + pathStr.getValue() + " : ");
Serial.println(Description);
Description = "";
}
void listFolder()
{
if (!sd.chdir("/")) {
Serial.println("Error: opening root!");
}
if (!sd.chdir("WF")) {
sd.mkdir("WF");
sd.chdir("WF");
}
sd.ls("/WF", LS_R);
}
void trigger(int id)
{
unsigned long curTime;
digitalWrite(Ptrig[id], HIGH);
curTime = micros();
while (micros() - curTime < 20);
digitalWrite(Ptrig[id], LOW);
}
void reset(Argument id)
{
int ii = 0;
unsigned long curTime;
if (id.getValue().toInt() == 0) {
digitalWrite(P_RESET, HIGH);
curTime = micros();
while (micros() - curTime < 2);
digitalWrite(P_RESET, LOW);
for ( ii = 1; ii < Channels + 1 ; ii = ii + 1 ) {
ChannelSet[ii].amplitude = ChannelSet[0].amplitude;
ChannelSet[ii].iinterval = ChannelSet[0].iinterval;
ChannelSet[ii].iperiod = ChannelSet[0].iperiod;
ChannelSet[ii].waveadress = ChannelSet[0].waveadress;
}
} else {
digitalWrite(P_RESET_CH, HIGH);
curTime = micros();
ChannelSet[id.getValue().toInt()].amplitude = ChannelSet[0].amplitude;
ChannelSet[id.getValue().toInt()].iinterval = ChannelSet[0].iinterval;
ChannelSet[id.getValue().toInt()].iperiod = ChannelSet[0].iperiod;
ChannelSet[id.getValue().toInt()].waveadress = ChannelSet[0].waveadress;
while (micros() - curTime < 2);
storeChannel(id);
digitalWrite(P_RESET_CH, LOW);
storeChannel(id);
}
}
void Channeladress(int id)
{
int adress=0;
if (id == 0) {
digitalWrite(*PChanAdress, LOW);
digitalWrite(*PChanAdress2, LOW);
digitalWrite(*PChanAdress3, LOW);
} else {
writePinArray(id-1, PChanAdress, sizeof(PChanAdress) / sizeof(PChanAdress[0]));
writePinArray(id-1, PChanAdress2, sizeof(PChanAdress2) / sizeof(PChanAdress2[0]));
writePinArray(id-1, PChanAdress3, sizeof(PChanAdress3) / sizeof(PChanAdress3[0]));
}
}
void RemoveDir (Argument str)
{
char path[12];
str.getValue().toCharArray(path, 12);
if (!sd.chdir("/")) {
Serial.println("Error: opening root!");
}
sd.chdir("WF");
sd.remove(path);
}
void SaveFile (Argument str)
{
File myFile;
char path[12];
uint8_t incomingByte;
str.getValue().toCharArray(path, 12);
if (!sd.chdir("/")) {
Serial.println("Error: opening root!");
}
sd.chdir("WF");
sd.remove(path);
myFile = sd.open(path, FILE_WRITE);
Serial.println("Please send File.");
while (Serial.available() == 0);
// read the incoming byte:
incomingByte = Serial.read();
while (incomingByte != 10) {
myFile.write(incomingByte);
while (Serial.available() == 0);
incomingByte = Serial.read();
}
myFile.close();
Serial.println("File saved!");
}
//Debug function to find right order of pins
void WriteDoutDebug(Argument value)
{
unsigned long curTime;
PIOD->PIO_SODR= value.getValue().toInt();
PIOD->PIO_CODR=~value.getValue().toInt()&0x00FF;
digitalWrite(PWrite, LOW);
curTime=micros();
while(micros()-curTime <20);
digitalWrite(PWrite, HIGH);
curTime=micros();
while(micros()-curTime <20);
}
| [
"[email protected]"
] | [
[
[
1,
575
]
]
] |
23a5265142f9e8174c5821cc0d4c21e628db3217 | d7d7dabc0002a09b87736f8d5163424cfe1c14cf | /source/Plugins/Process/Utility/UnwindLLDB.cpp | 203d4c1f658b9ac86aba4481de175fbb9d53f78c | [
"NCSA"
] | permissive | Keno/lldb | c29df7c850db9dd3db614a8b5e9a1284ee842342 | 2d75775deee48874159a76f01ed48f8b4d2e2a1b | refs/heads/master | 2020-02-26T15:34:38.678249 | 2013-12-29T17:25:48 | 2013-12-29T17:25:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,884 | cpp | //===-- UnwindLLDB.cpp -------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/Core/Module.h"
#include "lldb/Core/Log.h"
#include "lldb/Symbol/FuncUnwinders.h"
#include "lldb/Symbol/Function.h"
#include "lldb/Symbol/UnwindPlan.h"
#include "lldb/Target/Thread.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/RegisterContext.h"
#include "UnwindLLDB.h"
#include "RegisterContextLLDB.h"
using namespace lldb;
using namespace lldb_private;
UnwindLLDB::UnwindLLDB (Thread &thread) :
Unwind (thread),
m_frames(),
m_unwind_complete(false)
{
}
uint32_t
UnwindLLDB::DoGetFrameCount()
{
if (!m_unwind_complete)
{
//#define DEBUG_FRAME_SPEED 1
#if DEBUG_FRAME_SPEED
#define FRAME_COUNT 10000
TimeValue time_value (TimeValue::Now());
#endif
if (!AddFirstFrame ())
return 0;
ProcessSP process_sp (m_thread.GetProcess());
ABI *abi = process_sp ? process_sp->GetABI().get() : NULL;
while (AddOneMoreFrame (abi))
{
#if DEBUG_FRAME_SPEED
if ((m_frames.size() % FRAME_COUNT) == 0)
{
TimeValue now(TimeValue::Now());
uint64_t delta_t = now - time_value;
printf ("%u frames in %" PRIu64 ".%09llu ms (%g frames/sec)\n",
FRAME_COUNT,
delta_t / TimeValue::NanoSecPerSec,
delta_t % TimeValue::NanoSecPerSec,
(float)FRAME_COUNT / ((float)delta_t / (float)TimeValue::NanoSecPerSec));
time_value = now;
}
#endif
}
}
return m_frames.size ();
}
bool
UnwindLLDB::AddFirstFrame ()
{
if (m_frames.size() > 0)
return true;
// First, set up the 0th (initial) frame
CursorSP first_cursor_sp(new Cursor ());
RegisterContextLLDBSP reg_ctx_sp (new RegisterContextLLDB (m_thread,
RegisterContextLLDBSP(),
first_cursor_sp->sctx,
0, *this));
if (reg_ctx_sp.get() == NULL)
goto unwind_done;
if (!reg_ctx_sp->IsValid())
goto unwind_done;
if (!reg_ctx_sp->GetCFA (first_cursor_sp->cfa))
goto unwind_done;
if (!reg_ctx_sp->ReadPC (first_cursor_sp->start_pc))
goto unwind_done;
// Everything checks out, so release the auto pointer value and let the
// cursor own it in its shared pointer
first_cursor_sp->reg_ctx_lldb_sp = reg_ctx_sp;
m_frames.push_back (first_cursor_sp);
return true;
unwind_done:
Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_UNWIND));
if (log)
{
log->Printf ("th%d Unwind of this thread is complete.", m_thread.GetIndexID());
}
m_unwind_complete = true;
return false;
}
// For adding a non-zero stack frame to m_frames.
bool
UnwindLLDB::AddOneMoreFrame (ABI *abi)
{
// If we've already gotten to the end of the stack, don't bother to try again...
if (m_unwind_complete)
return false;
Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_UNWIND));
CursorSP cursor_sp(new Cursor ());
// Frame zero is a little different
if (m_frames.size() == 0)
return false;
uint32_t cur_idx = m_frames.size ();
RegisterContextLLDBSP reg_ctx_sp(new RegisterContextLLDB (m_thread,
m_frames[cur_idx - 1]->reg_ctx_lldb_sp,
cursor_sp->sctx,
cur_idx,
*this));
// We want to detect an unwind that cycles erronously and stop backtracing.
// Don't want this maximum unwind limit to be too low -- if you have a backtrace
// with an "infinitely recursing" bug, it will crash when the stack blows out
// and the first 35,000 frames are uninteresting - it's the top most 5 frames that
// you actually care about. So you can't just cap the unwind at 10,000 or something.
// Realistically anything over around 200,000 is going to blow out the stack space.
// If we're still unwinding at that point, we're probably never going to finish.
if (cur_idx > 300000)
{
if (log)
log->Printf ("%*sFrame %d unwound too many frames, assuming unwind has gone astray, stopping.",
cur_idx < 100 ? cur_idx : 100, "", cur_idx);
goto unwind_done;
}
if (reg_ctx_sp.get() == NULL)
{
if (log)
log->Printf ("%*sFrame %d did not get a RegisterContext, stopping.",
cur_idx < 100 ? cur_idx : 100, "", cur_idx);
goto unwind_done;
}
if (!reg_ctx_sp->IsValid())
{
if (log)
{
log->Printf("%*sFrame %d invalid RegisterContext for this frame, stopping stack walk",
cur_idx < 100 ? cur_idx : 100, "", cur_idx);
}
goto unwind_done;
}
if (!reg_ctx_sp->GetCFA (cursor_sp->cfa))
{
if (log)
{
log->Printf("%*sFrame %d did not get CFA for this frame, stopping stack walk",
cur_idx < 100 ? cur_idx : 100, "", cur_idx);
}
goto unwind_done;
}
if (abi && !abi->CallFrameAddressIsValid(cursor_sp->cfa))
{
if (log)
{
log->Printf("%*sFrame %d did not get a valid CFA for this frame, stopping stack walk",
cur_idx < 100 ? cur_idx : 100, "", cur_idx);
}
goto unwind_done;
}
if (!reg_ctx_sp->ReadPC (cursor_sp->start_pc))
{
if (log)
{
log->Printf("%*sFrame %d did not get PC for this frame, stopping stack walk",
cur_idx < 100 ? cur_idx : 100, "", cur_idx);
}
goto unwind_done;
}
if (abi && !abi->CodeAddressIsValid (cursor_sp->start_pc))
{
if (log)
{
log->Printf("%*sFrame %d did not get a valid PC, stopping stack walk",
cur_idx < 100 ? cur_idx : 100, "", cur_idx);
}
goto unwind_done;
}
if (!m_frames.empty())
{
// Infinite loop where the current cursor is the same as the previous one...
if (m_frames.back()->start_pc == cursor_sp->start_pc && m_frames.back()->cfa == cursor_sp->cfa)
{
if (log)
log->Printf ("th%d pc of this frame is the same as the previous frame and CFAs for both frames are identical -- stopping unwind", m_thread.GetIndexID());
goto unwind_done;
}
}
cursor_sp->reg_ctx_lldb_sp = reg_ctx_sp;
m_frames.push_back (cursor_sp);
return true;
unwind_done:
if (log)
{
log->Printf ("th%d Unwind of this thread is complete.", m_thread.GetIndexID());
}
m_unwind_complete = true;
return false;
}
bool
UnwindLLDB::DoGetFrameInfoAtIndex (uint32_t idx, addr_t& cfa, addr_t& pc)
{
if (m_frames.size() == 0)
{
if (!AddFirstFrame())
return false;
}
ProcessSP process_sp (m_thread.GetProcess());
ABI *abi = process_sp ? process_sp->GetABI().get() : NULL;
while (idx >= m_frames.size() && AddOneMoreFrame (abi))
;
if (idx < m_frames.size ())
{
cfa = m_frames[idx]->cfa;
pc = m_frames[idx]->start_pc;
return true;
}
return false;
}
lldb::RegisterContextSP
UnwindLLDB::DoCreateRegisterContextForFrame (StackFrame *frame)
{
lldb::RegisterContextSP reg_ctx_sp;
uint32_t idx = frame->GetConcreteFrameIndex ();
if (idx == 0)
{
return m_thread.GetRegisterContext();
}
if (m_frames.size() == 0)
{
if (!AddFirstFrame())
return reg_ctx_sp;
}
ProcessSP process_sp (m_thread.GetProcess());
ABI *abi = process_sp ? process_sp->GetABI().get() : NULL;
while (idx >= m_frames.size())
{
if (!AddOneMoreFrame (abi))
break;
}
const uint32_t num_frames = m_frames.size();
if (idx < num_frames)
{
Cursor *frame_cursor = m_frames[idx].get();
reg_ctx_sp = frame_cursor->reg_ctx_lldb_sp;
}
return reg_ctx_sp;
}
UnwindLLDB::RegisterContextLLDBSP
UnwindLLDB::GetRegisterContextForFrameNum (uint32_t frame_num)
{
RegisterContextLLDBSP reg_ctx_sp;
if (frame_num < m_frames.size())
reg_ctx_sp = m_frames[frame_num]->reg_ctx_lldb_sp;
return reg_ctx_sp;
}
bool
UnwindLLDB::SearchForSavedLocationForRegister (uint32_t lldb_regnum, lldb_private::UnwindLLDB::RegisterLocation ®loc, uint32_t starting_frame_num, bool pc_reg)
{
int64_t frame_num = starting_frame_num;
if (frame_num >= m_frames.size())
return false;
// Never interrogate more than one level while looking for the saved pc value. If the value
// isn't saved by frame_num, none of the frames lower on the stack will have a useful value.
if (pc_reg)
{
UnwindLLDB::RegisterSearchResult result;
result = m_frames[frame_num]->reg_ctx_lldb_sp->SavedLocationForRegister (lldb_regnum, regloc);
if (result == UnwindLLDB::RegisterSearchResult::eRegisterFound)
return true;
else
return false;
}
while (frame_num >= 0)
{
UnwindLLDB::RegisterSearchResult result;
result = m_frames[frame_num]->reg_ctx_lldb_sp->SavedLocationForRegister (lldb_regnum, regloc);
// If we have unwind instructions saying that register N is saved in register M in the middle of
// the stack (and N can equal M here, meaning the register was not used in this function), then
// change the register number we're looking for to M and keep looking for a concrete location
// down the stack, or an actual value from a live RegisterContext at frame 0.
if (result == UnwindLLDB::RegisterSearchResult::eRegisterFound
&& regloc.type == UnwindLLDB::RegisterLocation::eRegisterInRegister
&& frame_num > 0)
{
result = UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
lldb_regnum = regloc.location.register_number;
}
if (result == UnwindLLDB::RegisterSearchResult::eRegisterFound)
return true;
if (result == UnwindLLDB::RegisterSearchResult::eRegisterIsVolatile)
return false;
frame_num--;
}
return false;
}
| [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
] | [
[
[
1,
10
],
[
12,
14
],
[
19,
19
],
[
23,
27
],
[
30,
33
],
[
35,
35
],
[
37,
37
],
[
43,
44
],
[
65,
71
],
[
75,
76
],
[
96,
98
],
[
100,
104
],
[
107,
110
],
[
112,
112
],
[
118,
124
],
[
130,
145
],
[
147,
150
],
[
152,
153
],
[
155,
160
],
[
162,
162
],
[
164,
169
],
[
171,
171
],
[
173,
178
],
[
180,
180
],
[
182,
187
],
[
189,
189
],
[
199,
208
],
[
211,
212
],
[
215,
218
],
[
221,
223
],
[
225,
231
],
[
236,
246
],
[
248,
249
],
[
252,
260
],
[
262,
263
],
[
272,
272
],
[
280,
281
],
[
283,
284
],
[
288,
333
]
],
[
[
11,
11
],
[
15,
18
],
[
20,
22
],
[
38,
42
],
[
45,
55
],
[
57,
57
],
[
61,
64
],
[
77,
81
],
[
83,
84
],
[
86,
87
],
[
89,
90
],
[
92,
95
],
[
111,
111
],
[
117,
117
],
[
125,
129
],
[
146,
146
],
[
154,
154
],
[
163,
163
],
[
172,
172
],
[
181,
181
],
[
190,
196
],
[
198,
198
],
[
210,
210
],
[
232,
235
],
[
247,
247
],
[
250,
251
],
[
261,
261
],
[
264,
271
],
[
273,
279
],
[
282,
282
],
[
285,
287
]
],
[
[
28,
29
],
[
34,
34
],
[
36,
36
],
[
72,
74
],
[
82,
82
],
[
85,
85
],
[
88,
88
],
[
91,
91
],
[
99,
99
],
[
105,
106
],
[
113,
116
],
[
151,
151
],
[
161,
161
],
[
170,
170
],
[
179,
179
],
[
188,
188
],
[
197,
197
],
[
213,
214
],
[
219,
220
],
[
224,
224
]
],
[
[
56,
56
]
],
[
[
58,
60
]
],
[
[
209,
209
]
]
] |
06cfb9ca96a61137a348fc2045f8693d23f03832 | d160bb839227b14bb25e6b1b70c8dffb8d270274 | /MCMS/Main/Processes/Resource/ResourceLib/ConfResources.cpp | 6a1729f5225cd051689ecd1184f8de8e5b900429 | [] | no_license | somesh-ballia/mcms | 62a58baffee123a2af427b21fa7979beb1e39dd3 | 41aaa87d5f3b38bc186749861140fef464ddadd4 | refs/heads/master | 2020-12-02T22:04:46.442309 | 2017-07-03T06:02:21 | 2017-07-03T06:02:21 | 96,075,113 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 38,433 | cpp | #include "ConfResources.h"
#include "StatusesGeneral.h"
#include "ProcessBase.h"
#include "TraceStream.h"
#include "ResourceManager.h"
#include "WrappersResource.h"
#include "HelperFuncs.h"
#include "VideoApiDefinitionsStrings.h"
#include <algorithm>
#include <functional>
////////////////////////////////////////////////////////////////////////////
// CUdpRsrcDesc
////////////////////////////////////////////////////////////////////////////
CUdpRsrcDesc::CUdpRsrcDesc(WORD rsrcPartyId, WORD servId, WORD subServId, WORD PQMid)
{
m_rsrcPartyId = rsrcPartyId;
m_servId = servId;
m_PQMid = PQMid;
m_subServId = subServId;
memset(&m_udp, 0, sizeof(UdpAddresses));
for (int i = 0; i < MAX_NUM_OF_ALLOCATED_PARTY_UDP_PORTS; i++)
{
m_rtp_channels[i] = 0;
m_rtcp_channels[i] = 0;
}
}
////////////////////////////////////////////////////////////////////////////
CUdpRsrcDesc::~CUdpRsrcDesc()
{
}
////////////////////////////////////////////////////////////////////////////
bool operator==(const CUdpRsrcDesc& lhs,const CUdpRsrcDesc& rhs)
{
return ((lhs.m_rsrcPartyId == rhs.m_rsrcPartyId) && (lhs.m_type == rhs.m_type ));
}
////////////////////////////////////////////////////////////////////////////
bool operator<(const CUdpRsrcDesc& lhs,const CUdpRsrcDesc& rhs)
{
if (lhs.m_rsrcPartyId != rhs.m_rsrcPartyId)
return (lhs.m_rsrcPartyId < rhs.m_rsrcPartyId);
return (lhs.m_type < rhs.m_type);
}
////////////////////////////////////////////////////////////////////////////
void CUdpRsrcDesc::SetIpAddresses(ipAddressV4If ipAddressV4, const ipv6AddressArray& ipAddressV6)
{
CIPV4Wrapper v4wrapper(m_udp.IpV4Addr);
v4wrapper.CopyData(ipAddressV4);
CIPV6AraryWrapper v6wrapper(m_udp.IpV6AddrArray);
v6wrapper.CopyData(ipAddressV6);
}
////////////////////////////////////////////////////////////////////////////
// CRsrcDesc
////////////////////////////////////////////////////////////////////////////
CRsrcDesc::CRsrcDesc(DWORD connectionId, eLogicalResourceTypes type, DWORD rsrcConfId, WORD rsrcPartyId,
WORD boxId , WORD bId, WORD subBid, WORD uid, WORD acceleratorId, WORD firstPortId, ECntrlType cntrl,
WORD channelId, BOOL bIsUpdated /*= FALSE*/ )
{
m_connectionId = connectionId;
m_type = type;
m_rsrcConfId = rsrcConfId;
m_rsrcPartyId = rsrcPartyId;
m_boxId = boxId;
m_boardId = bId;
m_subBoardId = subBid;
m_unitId = uid;
m_acceleratorId = acceleratorId;
m_firstPortId = firstPortId;
m_numPorts = 1;
m_cntrl = cntrl;
m_channelId = channelId;
m_bIsUpdated = bIsUpdated;
memset(&m_IpV4Addr, 0, sizeof(m_IpV4Addr));
}
////////////////////////////////////////////////////////////////////////////
CRsrcDesc::~CRsrcDesc()
{
}
////////////////////////////////////////////////////////////////////////////
bool operator==(const CRsrcDesc& lhs,const CRsrcDesc& rhs)
{
//net ports can be the same except for the board, portid, unit_id (=span id) and accelerator_id, so check this
if (lhs.m_type == eLogical_net && rhs.m_type == eLogical_net)
if (lhs.m_firstPortId != rhs.m_firstPortId || lhs.m_unitId != rhs.m_unitId || lhs.m_acceleratorId != rhs.m_acceleratorId || lhs.m_boardId != rhs.m_boardId)
return FALSE;
return ((lhs.m_rsrcPartyId == rhs.m_rsrcPartyId) &&
(lhs.m_type == rhs.m_type ) && (lhs.m_cntrl == rhs.m_cntrl));
}
////////////////////////////////////////////////////////////////////////////
bool operator<(const CRsrcDesc& lhs,const CRsrcDesc& rhs)
{
if (lhs.m_rsrcPartyId != rhs.m_rsrcPartyId)
return (lhs.m_rsrcPartyId < rhs.m_rsrcPartyId);
else if (lhs.m_type != rhs.m_type)
return (lhs.m_type < rhs.m_type);
else if (lhs.m_type != eLogical_net)
return (lhs.m_cntrl < rhs.m_cntrl);
else //if it's net type
{
if (lhs.m_firstPortId != rhs.m_firstPortId)
return (lhs.m_firstPortId < rhs.m_firstPortId);
else if (lhs.m_acceleratorId != rhs.m_acceleratorId)
return (lhs.m_acceleratorId < rhs.m_acceleratorId);
else if (lhs.m_unitId != rhs.m_unitId)
return (lhs.m_unitId < rhs.m_unitId);
else
return (lhs.m_boardId < rhs.m_boardId);
}
}
////////////////////////////////////////////////////////////////////////////
void CRsrcDesc::SetIpAddresses(ipAddressV4If ipAddressV4)
{
CIPV4Wrapper v4wrapper(m_IpV4Addr);
v4wrapper.CopyData(ipAddressV4);
}
////////////////////////////////////////////////////////////////////////////
eResourceTypes CRsrcDesc::GetPhysicalType() const
{
switch (m_type)
{
case eLogical_audio_encoder:
return ePhysical_art;
case eLogical_audio_decoder:
return ePhysical_art;
case eLogical_audio_controller:
return ePhysical_audio_controller;
case eLogical_video_encoder:
case eLogical_video_encoder_content:
case eLogical_COP_CIF_encoder:
case eLogical_COP_VSW_encoder:
case eLogical_COP_PCM_encoder:
case eLogical_COP_HD720_encoder:
case eLogical_COP_HD1080_encoder:
case eLogical_COP_4CIF_encoder:
return ePhysical_video_encoder;
case eLogical_video_decoder:
case eLogical_COP_Dynamic_decoder:
case eLogical_COP_VSW_decoder:
case eLogical_COP_LM_decoder:
return ePhysical_video_decoder;
case eLogical_rtp:
return ePhysical_art;
/*Not in use for now
case eLogical_ip_signaling:
return ePhysical_res_none;
*/
case eLogical_net:
return ePhysical_rtm;
case eLogical_ivr_controller:
return ePhysical_ivr_controller;
case eLogical_mux:
return ePhysical_art;
// OLGA - Soft MCU
case eLogical_relay_rtp:
case eLogical_relay_svc_to_avc_rtp:
case eLogical_relay_video_encoder:
return ePhysical_mrmp;
case eLogical_relay_audio_encoder:
case eLogical_relay_audio_decoder:
case eLogical_legacy_to_SAC_audio_encoder:
case eLogical_relay_avc_to_svc_rtp:
case eLogical_relay_avc_to_svc_rtp_with_audio_encoder:
return ePhysical_art;
case eLogical_relay_avc_to_svc_video_encoder_1:
case eLogical_relay_avc_to_svc_video_encoder_2:
return ePhysical_video_encoder;
default:
return ePhysical_res_none;
}
}
////////////////////////////////////////////////////////////////////////////
std::ostream& operator<<(std::ostream& os, CRsrcDesc& obj)
{
os
<< "\n ConnectionId :" << obj.m_connectionId
<< "\n ResourceType :" << obj.m_type
<< "\n ConfId :" << obj.m_rsrcConfId
<< "\n PartyId :" << obj.m_rsrcPartyId
<< "\n BoxId :" << obj.m_boxId
<< "\n BoardId :" << obj.m_boardId
<< "\n SubBoardId :" << obj.m_subBoardId
<< "\n UnitId :" << obj.m_unitId
<< "\n AcceleratorId :" << obj.m_acceleratorId
<< "\n FirstPortId :" << obj.m_firstPortId;
return os;
}
////////////////////////////////////////////////////////////////////////////
// CConfRsrc
////////////////////////////////////////////////////////////////////////////
CConfRsrc::CConfRsrc(DWORD monitorConfId, eSessionType sessionType, eLogicalResourceTypes encoderLogicalType, eConfMediaType confMediaType)
{
m_monitorConfId = monitorConfId;
m_sessionType = sessionType;
m_rsrcConfId = 0; //0 - not allocated.
m_num_Parties = 0;
m_pUdpRsrcDescList = new std::set<CUdpRsrcDesc>;
m_encoderTypeCOP = encoderLogicalType;
m_confMediaState = eMediaStateEmpty;
m_confMediaType = confMediaType;
m_mrcMcuId = 1;
}
////////////////////////////////////////////////////////////////////////////
CConfRsrc::CConfRsrc(const CConfRsrc& other) : CPObject(other), m_pUdpRsrcDescList(new std::set<CUdpRsrcDesc>(*(other.m_pUdpRsrcDescList)))
{
m_monitorConfId = other.m_monitorConfId;
m_sessionType = other.m_sessionType;
m_bondingPhones = other.m_bondingPhones;
m_parties = other.m_parties;
m_rsrcConfId = other.m_rsrcConfId; //0 - not allocated.
m_num_Parties = other.m_num_Parties;
m_encoderTypeCOP = other.m_encoderTypeCOP;
m_confMediaState = other.m_confMediaState;
m_confMediaType = other.m_confMediaType;
m_mrcMcuId = other.m_mrcMcuId;
m_pRsrcDescList = other.m_pRsrcDescList;
}
////////////////////////////////////////////////////////////////////////////
CConfRsrc::~CConfRsrc()
{
m_pUdpRsrcDescList->clear();
PDELETE( m_pUdpRsrcDescList);
m_pUdpRsrcDescList = 0 ;
}
////////////////////////////////////////////////////////////////////////////
WORD operator==(const CConfRsrc& lhs,const CConfRsrc& rhs)
{
return (lhs.m_monitorConfId == rhs.m_monitorConfId);
}
////////////////////////////////////////////////////////////////////////////
bool operator<(const CConfRsrc& lhs,const CConfRsrc& rhs)
{
return (lhs.m_monitorConfId < rhs.m_monitorConfId);
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::AddUdpDesc(CUdpRsrcDesc* pUdpRsrcDesc)
{
PASSERT_AND_RETURN_VALUE(!pUdpRsrcDesc, STATUS_FAIL);
std::set<CUdpRsrcDesc>::iterator _itr = m_pUdpRsrcDescList->find(*pUdpRsrcDesc);
PASSERT_AND_RETURN_VALUE(_itr != m_pUdpRsrcDescList->end(), STATUS_FAIL);
m_pUdpRsrcDescList->insert(*pUdpRsrcDesc);
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
// The function only updates existing desc, not adding new one, if not found
STATUS CConfRsrc::UpdateUdpDesc(WORD rsrcpartyId, CUdpRsrcDesc* pUdpRsrcDesc)
{
PASSERT_AND_RETURN_VALUE(!pUdpRsrcDesc, STATUS_FAIL);
CUdpRsrcDesc desc(rsrcpartyId);
std::set<CUdpRsrcDesc>::iterator _itr = m_pUdpRsrcDescList->find(desc);
PASSERT_AND_RETURN_VALUE(_itr == m_pUdpRsrcDescList->end(), STATUS_FAIL);
m_pUdpRsrcDescList->erase(_itr);
m_pUdpRsrcDescList->insert(*pUdpRsrcDesc);
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::RemoveUdpDesc(WORD rsrcpartyId)
{
std::set<CUdpRsrcDesc>::iterator i;
CUdpRsrcDesc desc(rsrcpartyId);
i = m_pUdpRsrcDescList->find(desc);
if (i == m_pUdpRsrcDescList->end())//not exists
{
PASSERT(1);
return STATUS_FAIL;
}
m_pUdpRsrcDescList->erase(i);
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
const CUdpRsrcDesc* CConfRsrc::GetUdpDesc(WORD rsrcpartyId)const
{
std::set<CUdpRsrcDesc>::iterator i;
CUdpRsrcDesc desc(rsrcpartyId);
i = m_pUdpRsrcDescList->find(desc);
if (i == m_pUdpRsrcDescList->end())//not exists
{
PASSERT(1);
return NULL;
}
return (&(*i));
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::AddDesc(CRsrcDesc* pRsrcDesc)
{
if (!pRsrcDesc || pRsrcDesc->GetRsrcConfId() != m_rsrcConfId)
{
DBGPASSERT(1);
if (pRsrcDesc)
TRACEINTOLVLERR << "ERROR: m_rsrcConfId = " << m_rsrcConfId << ", GetRsrcConfId()=" << pRsrcDesc->GetRsrcConfId();
return STATUS_FAIL;
}
if (m_pRsrcDescList.find(*pRsrcDesc) != m_pRsrcDescList.end())
{//desc already exists
TRACEINTOLVLERR << "Failed, descriptor already exists" << *pRsrcDesc;
PASSERT_AND_RETURN_VALUE(1, STATUS_FAIL);
}
m_pRsrcDescList.insert(*pRsrcDesc);
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::RemoveDesc(WORD rsrcpartyId, eLogicalResourceTypes type, ECntrlType cntrl, WORD portId, WORD unitId, WORD acceleratorId, WORD boardId)
{
CRsrcDesc desc(0, type, 0, rsrcpartyId, 0, boardId, 0, unitId, acceleratorId, portId, cntrl);
RSRC_DESC_MULTISET_ITR itr = m_pRsrcDescList.find(desc);
if (itr == m_pRsrcDescList.end()) // not exists
{
TRACEINTOLVLERR << "Failed, descriptor not exist" << desc;
PASSERT_AND_RETURN_VALUE(1, STATUS_FAIL);
}
m_pRsrcDescList.erase(itr);
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
CRsrcDesc* CConfRsrc::GetDescFromConnectionId(DWORD connectionId)
{
RSRC_DESC_MULTISET_ITR itr;
for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++)
{
if ((itr->GetConnId() == connectionId))
{
return ((CRsrcDesc*)(&(*itr)));
}
}
return NULL;
}
////////////////////////////////////////////////////////////////////////////
const CRsrcDesc* CConfRsrc::GetDesc(WORD rsrcpartyId, eLogicalResourceTypes type, ECntrlType cntrl, WORD portId, WORD unitId, WORD acceleratorId, WORD boardId)
{
CRsrcDesc desc(0, type, 0, rsrcpartyId, 0, boardId, 0, unitId, acceleratorId, portId, cntrl);
RSRC_DESC_MULTISET_ITR i = m_pRsrcDescList.find(desc);
if (i == m_pRsrcDescList.end()) // not exists
{
// PASSERT(1);
return NULL;
}
return (&(*i));
}
////////////////////////////////////////////////////////////////////////////
const CRsrcDesc* CConfRsrc::GetDescByType(eLogicalResourceTypes type, ECntrlType cntrl)
{
RSRC_DESC_MULTISET_ITR itr;
for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++)
{
if (itr->GetType() == type && itr->GetCntrlType() == cntrl)
{
return ((CRsrcDesc*)(&(*itr)));
}
}
return NULL;
}
////////////////////////////////////////////////////////////////////////////
int CConfRsrc::GetDescArray( CRsrcDesc**& pRsrcDescArray)
{
int arrSize = m_pRsrcDescList.size();
if( 0 == arrSize )
return 0;
pRsrcDescArray = new CRsrcDesc*[arrSize];
RSRC_DESC_MULTISET_ITR itr;
int i = 0;
for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++)
{
pRsrcDescArray[i] = (CRsrcDesc*)&(*itr);
i++;
}
return i;
}
////////////////////////////////////////////////////////////////////////////
// Need to receive in pRsrcDescList memory of MAX_NUM_ALLOCATED_RSRCS_NET pointers (CRsrcDesc*) allocated for the output (and initialized to all NULLs)
// Returns number of RsrcDescs found.
WORD CConfRsrc::GetDescArrayPerResourceTypeByRsrcId(WORD rsrcpartyId,eLogicalResourceTypes type, CRsrcDesc** pRsrcDescArray, BYTE arrSize) const
{
RSRC_DESC_MULTISET_ITR itr;
int i = 0;
for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++)
{
if ((itr->GetRsrcPartyId() == rsrcpartyId ) && ( (itr->GetType() == type) || (eLogical_res_none == type)))
{
if (i < arrSize) // For protection
{
pRsrcDescArray[i] = (CRsrcDesc*)&(*itr);
i++;
}
else
PASSERTMSG(1, "CConfRsrc::GetDescArrayPerResourceTypeByRsrcId - error in call to function");
}
}
return i;
}
////////////////////////////////////////////////////////////////////////////
const CPartyRsrc* CConfRsrc::GetPartyRsrcByRsrcPartyId(PartyRsrcID partyId) const
{
PARTIES::iterator _iiEnd = m_parties.end();
for (PARTIES::iterator _ii = m_parties.begin(); _ii != _iiEnd; ++_ii)
{
if (_ii->GetRsrcPartyId() == partyId)
return &(*_ii);
}
return NULL;
}
////////////////////////////////////////////////////////////////////////////
WORD CConfRsrc::GetNumVideoPartiesPerBoard(WORD boardId)
{
WORD numVideoParties = 0;
PARTIES::iterator _iiEnd = m_parties.end();
for (PARTIES::iterator _ii = m_parties.begin(); _ii != _iiEnd; ++_ii)
{
PartyRsrcID partyId = _ii->GetRsrcPartyId();
CPartyRsrc* pParty = const_cast<CPartyRsrc*>(GetPartyRsrcByRsrcPartyId(partyId));
if (pParty)
{
eVideoPartyType videoPartyType = pParty->GetVideoPartyType();
if (eVideo_party_type_none != videoPartyType)
{
CRsrcDesc* pDecDesc = const_cast<CRsrcDesc*>(GetDesc(partyId, eLogical_video_decoder));
if (pDecDesc)
{
if (boardId == pDecDesc->GetBoardId())
numVideoParties++;
}
}
}
}
return numVideoParties;
}
////////////////////////////////////////////////////////////////////////////
// CPartyRsrc
////////////////////////////////////////////////////////////////////////////
CPartyRsrc::CPartyRsrc(PartyMonitorID monitorPartyId, eNetworkPartyType networkPartyType, eVideoPartyType videoPartyType, WORD ARTChannels, ePartyRole partyRole,eHdVswTypesInMixAvcSvc hdVswTypeInMixAvcSvcMode)
{
m_monitorPartyId = monitorPartyId;
m_networkPartyType = networkPartyType;
m_videoPartyType = videoPartyType;
m_resourcePartyType = e_Audio;
m_partyRole = partyRole;
m_rsrcPartyId = 0; //0 - not allocated.
m_CSconnId = 0;
#ifdef MS_LYNC_AVMCU_LINK
// MS Lync
m_partySigOrganizerConnId = 0;
m_partySigFocusConnId = 0;
m_partySigEventPackConnId = 0;
#endif
m_DialInReservedPorts = 0;
m_ARTChannels = ARTChannels;
m_roomPartyId = 0; //TIP Cisco
m_tipPartyType = eTipNone;
m_countPartyAsICEinMFW = FALSE;
m_ssrcAudio = 0;
m_tipNumOfScreens = 0;
m_HdVswTypeInMixAvcSvcMode = hdVswTypeInMixAvcSvcMode;
memset(m_ssrcContent, 0, sizeof(m_ssrcContent));
memset(m_ssrcVideo, 0, sizeof(m_ssrcVideo));
}
////////////////////////////////////////////////////////////////////////////
CPartyRsrc::CPartyRsrc(const CPartyRsrc& other) : CPObject(other),
m_monitorPartyId(other.m_monitorPartyId),
m_rsrcPartyId(other.m_rsrcPartyId),
m_roomPartyId(other.m_roomPartyId),
m_tipPartyType(other.m_tipPartyType),
m_tipNumOfScreens(other.m_tipNumOfScreens),
m_networkPartyType(other.m_networkPartyType),
m_videoPartyType(other.m_videoPartyType),
m_resourcePartyType(other.m_resourcePartyType),
m_partyRole(other.m_partyRole),
m_ARTChannels(other.m_ARTChannels),
m_CSconnId(other.m_CSconnId),
#ifdef MS_LYNC_AVMCU_LINK
// MS Lync
m_partySigOrganizerConnId(other.m_partySigOrganizerConnId),
m_partySigFocusConnId(other.m_partySigFocusConnId),
m_partySigEventPackConnId(other.m_partySigEventPackConnId),
#endif
m_DialInReservedPorts(other.m_DialInReservedPorts),
m_countPartyAsICEinMFW(other.m_countPartyAsICEinMFW),
m_HdVswTypeInMixAvcSvcMode(other.m_HdVswTypeInMixAvcSvcMode)
{
m_ssrcAudio = other.m_ssrcAudio;
for(WORD i=0;i<MAX_NUM_RECV_STREAMS_FOR_CONTENT;i++)
m_ssrcContent[i] = other.m_ssrcContent[i];
for(WORD i=0;i<MAX_NUM_RECV_STREAMS_FOR_VIDEO;i++)
m_ssrcVideo[i] = other.m_ssrcVideo[i];
}
////////////////////////////////////////////////////////////////////////////
CPartyRsrc::~CPartyRsrc()
{
}
////////////////////////////////////////////////////////////////////////////
void CPartyRsrc::SetARTChannels(WORD ARTChannels)
{
m_ARTChannels = ARTChannels;
// bridge-809: assert only not in soft MCU - in soft MCU ARTChannels set to 0, not to limit soft ART capacity
CSystemResources* pSyst = CHelperFuncs::GetSystemResources();
if (pSyst && !CHelperFuncs::IsSoftMCU(pSyst->GetProductType()))
{
DBGPASSERT(0 == ARTChannels);
}
}
////////////////////////////////////////////////////////////////////////////
WORD operator==(const CPartyRsrc& lhs,const CPartyRsrc& rhs)
{
return (lhs.m_monitorPartyId == rhs.m_monitorPartyId);
}
////////////////////////////////////////////////////////////////////////////
bool operator<(const CPartyRsrc& lhs,const CPartyRsrc& rhs)
{
return (lhs.m_monitorPartyId < rhs.m_monitorPartyId);
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::AddParty(CPartyRsrc& party)
{
PASSERTSTREAM_AND_RETURN_VALUE(m_parties.find(party) != m_parties.end(), "MonitorPartyId:" << party.GetMonitorPartyId() << " - Already exist", STATUS_FAIL);
TRACEINTO << "MonitorPartyId:" << party.GetMonitorPartyId() << ", PartyLogicalType:" << party.GetPartyResourceType();
m_parties.insert(party);
m_num_Parties++;
UpdateConfMediaStateByPartiesList();
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
BOOL CConfRsrc::CheckIfOneMorePartyCanBeAddedToConf2C(eVideoPartyType videoPartyType)
{
CSystemResources *pSystemResources = CHelperFuncs::GetSystemResources();
eSystemCardsMode systemCardsMode = pSystemResources ? pSystemResources->GetSystemCardsMode() : eSystemCardsMode_illegal;
if (eVSW_video_party_type == videoPartyType)
{
if((eVSW_28_session == m_sessionType && m_num_Parties > MAX_PARTIES_IN_CONF_2C_VSW28) ||
(eVSW_56_session == m_sessionType && m_num_Parties > MAX_PARTIES_IN_CONF_2C_VSW56))
{
return FALSE;
}
else if (eVSW_Auto_session == m_sessionType)
{
if ((eSystemCardsMode_breeze == systemCardsMode && m_num_Parties > 180))
return FALSE;
}
}
else if (eCOP_party_type == videoPartyType)
{
DWORD max_cop_parties = 160; //on breeze
CReservator* pReservator = CHelperFuncs::GetReservator();
if (pReservator)
max_cop_parties = pReservator->GetDongleRestriction();
TRACEINTO << " CConfRsrc::CheckIfOneMorePartyCanBeAddedToConf2C : max_cop_parties = " << max_cop_parties;
if ((eCOP_HD1080_session == m_sessionType || eCOP_HD720_50_session == m_sessionType) && m_num_Parties >= max_cop_parties)//192
return FALSE;
}
return TRUE;
}
////////////////////////////////////////////////////////////////////////////
WORD CConfRsrc::RemoveAllParties(BYTE force_kill_all_ports)
{
CResourceManager* pRsrcMngr = (CResourceManager*)(CProcessBase::GetProcess()->GetCurrentTask());
if (!pRsrcMngr)
{
PASSERT(1); return 0;
}
DEALLOC_PARTY_REQ_PARAMS_S* pdeallocateParams = new DEALLOC_PARTY_REQ_PARAMS_S;
memset(pdeallocateParams, 0, sizeof(DEALLOC_PARTY_REQ_PARAMS_S));
DEALLOC_PARTY_IND_PARAMS_S* pResult = new DEALLOC_PARTY_IND_PARAMS_S;
pdeallocateParams->numOfRsrcsWithProblems = 0;
pdeallocateParams->monitor_conf_id = m_monitorConfId;
pdeallocateParams->force_kill_all_ports = force_kill_all_ports;
// make a copy of parties container
PARTIES PartyRsrcList = m_parties;
PARTIES::iterator itr = PartyRsrcList.begin();
DWORD monitorPartyId = 0;
WORD numOfRemovedParties = 0;
for (itr = PartyRsrcList.begin(); itr != PartyRsrcList.end(); itr++)
{
monitorPartyId = ((CPartyRsrc*)(&(*itr)))->GetMonitorPartyId();
TRACEINTO << "monitorPartyId=" << monitorPartyId;
memset(pResult, 0, sizeof(DEALLOC_PARTY_IND_PARAMS_S));
pdeallocateParams->monitor_party_id = monitorPartyId;
pRsrcMngr->DeAlloc(pdeallocateParams, pResult);
if (pResult->status == STATUS_OK)
++numOfRemovedParties;
}
delete pdeallocateParams;
delete pResult;
return numOfRemovedParties;
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::RemoveParty(PartyMonitorID monitorPartyId)
{
CPartyRsrc party(monitorPartyId);
PARTIES::iterator itr = m_parties.find(party);
PASSERTSTREAM_AND_RETURN_VALUE(itr == m_parties.end(), "MonitorPartyId:" << monitorPartyId << " - Party not exist", STATUS_FAIL);
m_parties.erase(itr);
m_num_Parties--;
UpdateConfMediaStateByPartiesList();
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
const CPartyRsrc* CConfRsrc::GetParty(PartyMonitorID monitorPartyId) const
{
CPartyRsrc party(monitorPartyId);
PARTIES::iterator itr = m_parties.find(party);
TRACECOND_AND_RETURN_VALUE(itr == m_parties.end(), "MonitorPartyId:" << monitorPartyId << " - Party not exist", NULL);
return &(*itr);
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::AddTempBondingPhoneNumber(PartyRsrcID partyId, Phone* pPhone)
{
PASSERT_AND_RETURN_VALUE(!pPhone, STATUS_FAIL);
Phone* phone = new Phone;
strcpy_safe(phone->phone_number, pPhone->phone_number);
m_bondingPhones.insert(BONDING_PHONES::value_type(partyId, phone));
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::RemoveTempBondingPhoneNumber(PartyRsrcID partyId)
{
BONDING_PHONES::iterator itr = m_bondingPhones.find(partyId);
if (itr == m_bondingPhones.end())
return STATUS_FAIL;
delete itr->second;
m_bondingPhones.erase(itr);
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
Phone* CConfRsrc::GetTempBondingPhoneNumberByRsrcPartyId(PartyRsrcID partyId) const
{
BONDING_PHONES::const_iterator itr = m_bondingPhones.find(partyId);
if (itr == m_bondingPhones.end())
return NULL;
return itr->second;
}
////////////////////////////////////////////////////////////////////////////
WORD CConfRsrc::IsBoardIdAllocatedToConf(WORD boardId)
{
//if board allocated o conf -
// there is have to be at least on RsrcDesc of this board.
//WORD bId = 2;
RSRC_DESC_MULTISET_ITR itr;
for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++)
{
if (itr->GetBoardId() == boardId)
return TRUE;
}
return FALSE;
}
////////////////////////////////////////////////////////////////////////////
void CConfRsrc::AddListOfPartiesDescriptorsOnBoard(WORD boardId, WORD subBoardId, std::map<std::string,CONF_PARTY_ID_S*>* listOfConfIdPartyIdPair) const
{
RSRC_DESC_MULTISET_ITR itr;
CRsrcDesc rsrcdesc;
std::string strKey;
CONF_PARTY_ID_S* pConf_party_id_s = NULL;
for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++)
{
rsrcdesc = ((CRsrcDesc)(*itr));
if (rsrcdesc.GetBoardId() == boardId)
{
//if subboard is 1 (MFA), this means that the whole card will be taken out, including the RTM
//so it doesn't matter on which subboard it is
if (subBoardId == MFA_SUBBOARD_ID || rsrcdesc.GetSubBoardId() == subBoardId)
{
strKey = GetPartyKey(rsrcdesc.GetRsrcConfId() ,rsrcdesc.GetRsrcPartyId());
if (listOfConfIdPartyIdPair->find(strKey) == listOfConfIdPartyIdPair->end())
{
pConf_party_id_s = new CONF_PARTY_ID_S();
pConf_party_id_s->monitor_conf_id = GetMonitorConfId();
CPartyRsrc* pParty = (CPartyRsrc*)(GetPartyRsrcByRsrcPartyId(rsrcdesc.GetRsrcPartyId()));
if (pParty == NULL)
{
POBJDELETE(pConf_party_id_s);
PASSERT(1);
continue;
}
else
{
pConf_party_id_s->monitor_party_id = pParty->GetMonitorPartyId();
}
(*listOfConfIdPartyIdPair)[strKey] = pConf_party_id_s;
}
}
}
}
}
////////////////////////////////////////////////////////////////////////////
std::string CConfRsrc::GetPartyKey(DWORD rsrcConfId, DWORD rsrcPartyId) const
{
std::ostringstream o;
o << rsrcConfId << "_" << rsrcPartyId;
return o.str();
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::GetFreeVideoRsrcVSW(CRsrcDesc*& pEncDesc, CRsrcDesc*& pDecDesc)
{
WORD rsrcId = 0, enc_found = 0, dec_found = 0;
RSRC_DESC_MULTISET_ITR itr;
for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++)
{
CRsrcDesc* pRsrcDesc = (CRsrcDesc*)&(*itr);
BOOL isDecType = CHelperFuncs::IsLogicalVideoDecoderType( pRsrcDesc->GetType());
BOOL isEncType = CHelperFuncs::IsLogicalVideoEncoderType( pRsrcDesc->GetType());
if (pRsrcDesc->GetIsUpdated() || (!isDecType && !isEncType) ||
(isDecType && dec_found) || (isEncType && enc_found))
continue;
rsrcId = pRsrcDesc->GetRsrcPartyId();
if (isDecType)
{
dec_found = rsrcId;
pDecDesc = pRsrcDesc;
}
else
{
enc_found = rsrcId;
pEncDesc = pRsrcDesc;
}
if (dec_found && enc_found && dec_found == enc_found)
break;
}
if (!pEncDesc || !pDecDesc)
return STATUS_FAIL;
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::GetBoardUnitIdByRoomIdTIP(DWORD room_id, WORD& boardIdTIP, WORD& unitIdTIP) //TIP Cisco
{
PARTIES::iterator _iiEnd = m_parties.end();
for (PARTIES::iterator _ii = m_parties.begin(); _ii != _iiEnd; ++_ii)
{
if (_ii->GetRoomPartyId() == room_id)
{
const CRsrcDesc* pAudEncDesc = GetDesc(_ii->GetRsrcPartyId(), eLogical_audio_encoder);
if (pAudEncDesc)
{
boardIdTIP = pAudEncDesc->GetBoardId();
unitIdTIP = pAudEncDesc->GetUnitId();
return STATUS_OK;
}
}
}
return STATUS_FAIL;
}
////////////////////////////////////////////////////////////////////////////
WORD CConfRsrc::GetBoardIdForRelayParty() //olga
{
PARTIES::iterator _it = std::find_if(m_parties.begin(), m_parties.end(), compareVideoPartyFunc());
if (_it != m_parties.end())
{
const CRsrcDesc* pRtpDesc = GetDesc(_it->GetRsrcPartyId(), eLogical_rtp);
if (pRtpDesc)
return pRtpDesc->GetBoardId();
}
TRACEINTO << "Relay party is not allocated on any board";
return 0;
}
////////////////////////////////////////////////////////////////////////////
bool CConfRsrc::CheckIfThereAreRelayParty() const
{
PARTIES::iterator _it = std::find_if(m_parties.begin(), m_parties.end(), compareVideoPartyFunc());
return (_it != m_parties.end());
}
////////////////////////////////////////////////////////////////////////////
bool CConfRsrc::CheckIfThereAreNotRelayParty() const
{
PARTIES::iterator _it = std::find_if(m_parties.begin(), m_parties.end(), not1(compareVideoPartyFunc()));
return (_it != m_parties.end());
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::GetBoardUnitIdByAvMcuLinkMain(PartyRsrcID mainPartyRsrcID, WORD& boardId, WORD& unitId)
{
const CRsrcDesc* pRtpDesc = GetDesc(mainPartyRsrcID, eLogical_rtp);
if (pRtpDesc)
{
boardId = pRtpDesc->GetBoardId();
unitId = pRtpDesc->GetUnitId();
return STATUS_OK;
}
return STATUS_FAIL;
}
////////////////////////////////////////////////////////////////////////////
void CConfRsrc::CountAvcSvcParties(WORD& numAvc, WORD& numSvc) const
{
numAvc = 0;
numSvc = 0;
PARTIES::iterator _iiEnd = m_parties.end();
for (PARTIES::iterator _ii = m_parties.begin(); _ii != _iiEnd; ++_ii)
{
if (CHelperFuncs::IsVideoRelayParty(_ii->GetVideoPartyType()))
numSvc++;
else
numAvc++;
}
}
////////////////////////////////////////////////////////////////////////////
// Need to receive in pRsrcDescList memory of MAX_NUM_ALLOCATED_RSRCS_NET pointers (CRsrcDesc*) allocated for the output (and initialized to all NULLs)
// Returns number of RsrcDescs found.
WORD CConfRsrc::GetPartyRcrsDescArrayByRsrcId(DWORD rsrcpartyId, CRsrcDesc** pRsrcDescArray, WORD arrSize)
{
RSRC_DESC_MULTISET_ITR itr;
int num_party_resources = 0;
for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++)
{
if (itr->GetRsrcPartyId() == rsrcpartyId)
{
if (num_party_resources < arrSize) // For protection
{
pRsrcDescArray[num_party_resources] = (CRsrcDesc*)&(*itr);
num_party_resources++;
}
else{
PASSERTMSG(num_party_resources, "CConfRsrc::GetDescArrayPerResourceTypeByRsrcId - error in call to function");
}
}
}
return num_party_resources;
}
////////////////////////////////////////////////////////////////////////////
WORD CConfRsrc::GetPartyRTPDescArrayByRsrcId(DWORD rsrcpartyId, CRsrcDesc** pRsrcDescArray, WORD arrSize)
{
RSRC_DESC_MULTISET_ITR itr;
int num_party_resources = 0;
for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++)
{
if (itr->GetRsrcPartyId() == rsrcpartyId && CHelperFuncs::IsLogicalRTPtype(itr->GetType()))
{
if (num_party_resources < arrSize) // For protection
{
pRsrcDescArray[num_party_resources] = (CRsrcDesc*)&(*itr);
num_party_resources++;
}
else{
PASSERTMSG(num_party_resources, "CConfRsrc::GetDescArrayPerResourceTypeByRsrcId - error in call to function");
}
}
}
return num_party_resources;
}
////////////////////////////////////////////////////////////////////////////
void CConfRsrc::UpdateConfMediaStateByPartiesList()
{
bool hasRelayParties = CheckIfThereAreRelayParty();
bool hasNotRelayParties = CheckIfThereAreNotRelayParty();
if (eMediaStateMixAvcSvc == m_confMediaState)
{
// since we don't support downgrade - we don't change ConfMediaState after it already in mixed
return;
}
if (!hasRelayParties && !hasNotRelayParties)
{
SetConfMediaState(eMediaStateEmpty);
}
else if (hasRelayParties && !hasNotRelayParties)
{
SetConfMediaState(eMediaStateSvcOnly);
}
else if (!hasRelayParties && hasNotRelayParties)
{
SetConfMediaState(eMediaStateAvcOnly);
}
}
////////////////////////////////////////////////////////////////////////////
// CConfRsrcDB
////////////////////////////////////////////////////////////////////////////
CConfRsrcDB::CConfRsrcDB()
{
m_numConfRsrcs = 0;
}
////////////////////////////////////////////////////////////////////////////
CConfRsrcDB::~CConfRsrcDB()
{
m_numConfRsrcs = 0;
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrcDB::AddConfRsrc(CConfRsrc* pConfRsrc)
{
PASSERT_AND_RETURN_VALUE(!pConfRsrc, STATUS_FAIL);
PASSERT_AND_RETURN_VALUE(m_confList.find(*pConfRsrc) != m_confList.end(), STATUS_FAIL);
m_confList.insert(*pConfRsrc);
ConfRsrcID id = pConfRsrc->GetRsrcConfId();
if (STANDALONE_CONF_ID != id)
m_numConfRsrcs++;
TRACEINTO << "ConfId:" << id << ", NumOngoingConf:" << m_numConfRsrcs;
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrcDB::RemoveConfRsrc(ConfMonitorID confId)
{
CConfRsrc conf(confId);
RSRC_CONF_LIST::iterator _itr = m_confList.find(conf);
if (_itr == m_confList.end())
return STATUS_FAIL;
ConfRsrcID id = _itr->GetRsrcConfId();
if (STANDALONE_CONF_ID != id)
{
if (m_numConfRsrcs > 0)
m_numConfRsrcs--;
else
PASSERT(1);
}
m_confList.erase(_itr);
TRACEINTO << "ConfId:" << id << ", NumOngoingConf:" << m_numConfRsrcs;
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
CConfRsrc* CConfRsrcDB::GetConfRsrc(ConfMonitorID confId)
{
CConfRsrc conf(confId);
RSRC_CONF_LIST::iterator _itr = m_confList.find(conf);
if (_itr != m_confList.end())
return (CConfRsrc*)(&(*_itr));
return NULL;
}
////////////////////////////////////////////////////////////////////////////
CConfRsrc* CConfRsrcDB::GetConfRsrcByRsrcConfId(ConfRsrcID confId)
{
RSRC_CONF_LIST::iterator _end = m_confList.end();
for (RSRC_CONF_LIST::iterator _itr = m_confList.begin(); _itr != _end; ++_itr)
{
if (_itr->GetRsrcConfId() == confId)
return (CConfRsrc*)(&(*_itr));
}
return NULL;
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrcDB::GetMonitorIdsRsrcIds(ConfRsrcID confId, PartyRsrcID partyId, ConfMonitorID& monitorConfId, PartyMonitorID& monitorPartyId)
{
monitorConfId = 0xFFFFFFFF;
monitorPartyId = 0xFFFFFFFF;
RSRC_CONF_LIST::iterator _end = m_confList.end();
for (RSRC_CONF_LIST::iterator _itr = m_confList.begin(); _itr != _end; ++_itr)
{
if (_itr->GetRsrcConfId() == confId)
{
monitorConfId = _itr->GetMonitorConfId();
const CPartyRsrc* pParty = _itr->GetPartyRsrcByRsrcPartyId(partyId);
if (pParty)
{
monitorPartyId = pParty->GetMonitorPartyId();
return STATUS_OK;
}
}
}
return STATUS_FAIL;
}
////////////////////////////////////////////////////////////////////////////
bool CConfRsrcDB::IsExitingConf(ConfMonitorID confId)
{
const CConfRsrc* pConfRsrc = GetConfRsrc(confId);
return (pConfRsrc == NULL)? false : true;
}
////////////////////////////////////////////////////////////////////////////
bool CConfRsrcDB::IsEmptyConf(ConfMonitorID confId)
{
CConfRsrc* pConfRsrc = GetConfRsrc(confId);
PASSERT_AND_RETURN_VALUE(!pConfRsrc, true);
return pConfRsrc->GetNumParties() ? false : true;
}
////////////////////////////////////////////////////////////////////////////
ConfRsrcID CConfRsrcDB::MonitorToRsrcConfId(ConfMonitorID confId)
{
CConfRsrc* pConfRsrc = GetConfRsrc(confId);
return pConfRsrc ? pConfRsrc->GetRsrcConfId() : 0;
}
////////////////////////////////////////////////////////////////////////////
void CConfRsrcDB::GetAllPartiesOnBoard(WORD boardId, WORD subBoardId, std::map<std::string, CONF_PARTY_ID_S*>* listOfConfIdPartyIdPair)
{
RSRC_CONF_LIST::iterator _end = m_confList.end();
for (RSRC_CONF_LIST::iterator _itr = m_confList.begin(); _itr != _end; ++_itr)
_itr->AddListOfPartiesDescriptorsOnBoard(boardId, subBoardId, listOfConfIdPartyIdPair);
}
////////////////////////////////////////////////////////////////////////////
void CConfRsrcDB::FillISDNServiceName(ConfMonitorID confId, PartyMonitorID partyId, char serviceName[GENERAL_SERVICE_PROVIDER_NAME_LEN])
{
CSystemResources* pSystemResources = CHelperFuncs::GetSystemResources();
PASSERT_AND_RETURN(!pSystemResources);
const CConfRsrc* pConfRsrc = GetConfRsrc(confId);
TRACECOND_AND_RETURN(!pConfRsrc, "MonitorConfId:" << confId << " - Failed, conference not found");
const CPartyRsrc* pPartyRsrc = pConfRsrc->GetParty(partyId);
TRACECOND_AND_RETURN(!pPartyRsrc, "MonitorPartyId:" << partyId << " - Failed, participant not found");
CRsrcDesc** pRsrcDescArray = new CRsrcDesc*[MAX_NUM_ALLOCATED_RSRCS_NET];
for (int i = 0 ; i < MAX_NUM_ALLOCATED_RSRCS_NET ; i++)
pRsrcDescArray[i] = NULL;
// Get all resource descriptors of RTM per a given party
pConfRsrc->GetDescArrayPerResourceTypeByRsrcId(pPartyRsrc->GetRsrcPartyId(), eLogical_net, pRsrcDescArray);
if (pRsrcDescArray[0] == NULL)
{
TRACEINTO << "MonitorPartyId:" << partyId << " - Failed, RTMs not found for party";
delete []pRsrcDescArray;
return;
}
WORD boardId = pRsrcDescArray[0]->GetBoardId();
WORD unitId = pRsrcDescArray[0]->GetUnitId();
delete []pRsrcDescArray;
CBoard* pBoard = pSystemResources->GetBoard(boardId);
PASSERT_AND_RETURN(!pBoard);
const CSpanRTM* pSpan = pBoard->GetRTM(unitId);
PASSERT_AND_RETURN(!pSpan);
const char* serviceNameFromSpan = pSpan->GetSpanServiceName();
if (serviceNameFromSpan)
strcpy_safe(serviceName, sizeof(serviceName), serviceNameFromSpan);
}
////////////////////////////////////////////////////////////////////////////
PartyRsrcID CConfRsrcDB::MonitorToRsrcPartyId(ConfMonitorID confId, PartyMonitorID partyId)
{
const CConfRsrc* pConfRsrc = GetConfRsrc(confId);
if (pConfRsrc)
{
const CPartyRsrc* pPartyRsrc = pConfRsrc->GetParty(partyId);
if (pPartyRsrc)
return pPartyRsrc->GetRsrcPartyId();
}
return 0;
}
////////////////////////////////////////////////////////////////////////////
bool CConfRsrcDB::GetPartyType(ConfMonitorID confId, PartyMonitorID partyId,
eNetworkPartyType& networkPartyType,
eVideoPartyType& videoPartyType,
ePartyRole& partyRole,
WORD& artChannels,
eSessionType& sessionType)
{
const CConfRsrc* pConfRsrc = GetConfRsrc(confId);
TRACECOND_AND_RETURN_VALUE(!pConfRsrc, "MonitorConfId:" << confId << " - Failed, conference not found", false);
const CPartyRsrc* pPartyRsrc = pConfRsrc->GetParty(partyId);
TRACECOND_AND_RETURN_VALUE(!pPartyRsrc, "MonitorPartyId:" << partyId << " - Failed, participant not found", false);
networkPartyType = pPartyRsrc->GetNetworkPartyType();
videoPartyType = pPartyRsrc->GetVideoPartyType();
partyRole = pPartyRsrc->GetPartyRole();
artChannels = pPartyRsrc->GetARTChannels();
sessionType = pConfRsrc->GetSessionType();
return true;
}
| [
"[email protected]"
] | [
[
[
1,
1227
]
]
] |
6bb71dcc34b99d77ceb1ceff65cfbc759d142cb5 | fb72a82827496e66e04ecb29abbca788a1ea0525 | /src/wallet/wallet.h | 5c79de2b263b987cf010ed0c6314bf311d8d6581 | [
"MIT"
] | permissive | exiliumcore/exilium | 92631c2e7abeeae6a80debbb699441d6b56e2fee | 6aa88fe0c40fe72850e5bdb265741a375b2ab766 | refs/heads/master | 2020-03-14T05:50:41.214608 | 2018-05-13T01:00:24 | 2018-05-13T01:00:24 | 131,472,364 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 37,762 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2018 The Exilium Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_WALLET_WALLET_H
#define BITCOIN_WALLET_WALLET_H
#include "amount.h"
#include "base58.h"
#include "streams.h"
#include "tinyformat.h"
#include "ui_interface.h"
#include "util.h"
#include "utilstrencodings.h"
#include "validationinterface.h"
#include "wallet/crypter.h"
#include "wallet/wallet_ismine.h"
#include "wallet/walletdb.h"
#include "privatesend.h"
#include <algorithm>
#include <map>
#include <set>
#include <stdexcept>
#include <stdint.h>
#include <string>
#include <utility>
#include <vector>
#include <boost/shared_ptr.hpp>
/**
* Settings
*/
extern CFeeRate payTxFee;
extern CAmount maxTxFee;
extern unsigned int nTxConfirmTarget;
extern bool bSpendZeroConfChange;
extern bool fSendFreeTransactions;
static const unsigned int DEFAULT_KEYPOOL_SIZE = 1000;
//! -paytxfee default
static const CAmount DEFAULT_TRANSACTION_FEE = 0;
//! -paytxfee will warn if called with a higher fee than this amount (in satoshis) per KB
static const CAmount nHighTransactionFeeWarning = 0.01 * COIN;
//! -fallbackfee default
static const CAmount DEFAULT_FALLBACK_FEE = 1000;
//! -mintxfee default
static const CAmount DEFAULT_TRANSACTION_MINFEE = 1000;
//! -maxtxfee default
static const CAmount DEFAULT_TRANSACTION_MAXFEE = 0.2 * COIN; // "smallest denom" + X * "denom tails"
//! minimum change amount
static const CAmount MIN_CHANGE = CENT;
//! Default for -spendzeroconfchange
static const bool DEFAULT_SPEND_ZEROCONF_CHANGE = true;
//! Default for -sendfreetransactions
static const bool DEFAULT_SEND_FREE_TRANSACTIONS = false;
//! -txconfirmtarget default
static const unsigned int DEFAULT_TX_CONFIRM_TARGET = 2;
//! -maxtxfee will warn if called with a higher fee than this amount (in satoshis)
static const CAmount nHighTransactionMaxFeeWarning = 100 * nHighTransactionFeeWarning;
//! Largest (in bytes) free transaction we're willing to create
static const unsigned int MAX_FREE_TRANSACTION_CREATE_SIZE = 1000;
static const bool DEFAULT_WALLETBROADCAST = true;
//! if set, all keys will be derived by using BIP39/BIP44
static const bool DEFAULT_USE_HD_WALLET = false;
class CBlockIndex;
class CCoinControl;
class COutput;
class CReserveKey;
class CScript;
class CTxMemPool;
class CWalletTx;
/** (client) version numbers for particular wallet features */
enum WalletFeature
{
FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
FEATURE_WALLETCRYPT = 40000, // wallet encryption
FEATURE_COMPRPUBKEY = 60000, // compressed public keys
FEATURE_HD = 120200, // Hierarchical key derivation after BIP32 (HD Wallet), BIP44 (multi-coin), BIP39 (mnemonic)
// which uses on-the-fly private key derivation
FEATURE_LATEST = 61000
};
enum AvailableCoinsType
{
ALL_COINS,
ONLY_DENOMINATED,
ONLY_NONDENOMINATED,
ONLY_1000, // find masternode outputs including locked ones (use with caution)
ONLY_PRIVATESEND_COLLATERAL
};
struct CompactTallyItem
{
CTxDestination txdest;
CAmount nAmount;
std::vector<CTxIn> vecTxIn;
CompactTallyItem()
{
nAmount = 0;
}
};
/** A key pool entry */
class CKeyPool
{
public:
int64_t nTime;
CPubKey vchPubKey;
bool fInternal; // for change outputs
CKeyPool();
CKeyPool(const CPubKey& vchPubKeyIn, bool fInternalIn);
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(nTime);
READWRITE(vchPubKey);
if (ser_action.ForRead()) {
try {
READWRITE(fInternal);
}
catch (std::ios_base::failure&) {
/* flag as external address if we can't read the internal boolean
(this will be the case for any wallet before the HD chain split version) */
fInternal = false;
}
}
else {
READWRITE(fInternal);
}
}
};
/** Address book data */
class CAddressBookData
{
public:
std::string name;
std::string purpose;
CAddressBookData()
{
purpose = "unknown";
}
typedef std::map<std::string, std::string> StringMap;
StringMap destdata;
};
struct CRecipient
{
CScript scriptPubKey;
CAmount nAmount;
bool fSubtractFeeFromAmount;
};
typedef std::map<std::string, std::string> mapValue_t;
static void ReadOrderPos(int64_t& nOrderPos, mapValue_t& mapValue)
{
if (!mapValue.count("n"))
{
nOrderPos = -1; // TODO: calculate elsewhere
return;
}
nOrderPos = atoi64(mapValue["n"].c_str());
}
static void WriteOrderPos(const int64_t& nOrderPos, mapValue_t& mapValue)
{
if (nOrderPos == -1)
return;
mapValue["n"] = i64tostr(nOrderPos);
}
struct COutputEntry
{
CTxDestination destination;
CAmount amount;
int vout;
};
/** A transaction with a merkle branch linking it to the block chain. */
class CMerkleTx : public CTransaction
{
private:
/** Constant used in hashBlock to indicate tx has been abandoned */
static const uint256 ABANDON_HASH;
public:
uint256 hashBlock;
/* An nIndex == -1 means that hashBlock (in nonzero) refers to the earliest
* block in the chain we know this or any in-wallet dependency conflicts
* with. Older clients interpret nIndex == -1 as unconfirmed for backward
* compatibility.
*/
int nIndex;
CMerkleTx()
{
Init();
}
CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
{
Init();
}
void Init()
{
hashBlock = uint256();
nIndex = -1;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
std::vector<uint256> vMerkleBranch; // For compatibility with older versions.
READWRITE(*(CTransaction*)this);
nVersion = this->nVersion;
READWRITE(hashBlock);
READWRITE(vMerkleBranch);
READWRITE(nIndex);
}
int SetMerkleBranch(const CBlock& block);
/**
* Return depth of transaction in blockchain:
* <0 : conflicts with a transaction this deep in the blockchain
* 0 : in memory pool, waiting to be included in a block
* >=1 : this many blocks deep in the main chain
*/
int GetDepthInMainChain(const CBlockIndex* &pindexRet, bool enableIX = true) const;
int GetDepthInMainChain(bool enableIX = true) const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet, enableIX); }
bool IsInMainChain() const { const CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet) > 0; }
int GetBlocksToMaturity() const;
bool AcceptToMemoryPool(bool fLimitFree=true, bool fRejectAbsurdFee=true);
bool hashUnset() const { return (hashBlock.IsNull() || hashBlock == ABANDON_HASH); }
bool isAbandoned() const { return (hashBlock == ABANDON_HASH); }
void setAbandoned() { hashBlock = ABANDON_HASH; }
};
/**
* A transaction with a bunch of additional info that only the owner cares about.
* It includes any unrecorded transactions needed to link it back to the block chain.
*/
class CWalletTx : public CMerkleTx
{
private:
const CWallet* pwallet;
public:
mapValue_t mapValue;
std::vector<std::pair<std::string, std::string> > vOrderForm;
unsigned int fTimeReceivedIsTxTime;
unsigned int nTimeReceived; //! time received by this node
unsigned int nTimeSmart;
char fFromMe;
std::string strFromAccount;
int64_t nOrderPos; //! position in ordered transaction list
// memory only
mutable bool fDebitCached;
mutable bool fCreditCached;
mutable bool fImmatureCreditCached;
mutable bool fAvailableCreditCached;
mutable bool fAnonymizedCreditCached;
mutable bool fDenomUnconfCreditCached;
mutable bool fDenomConfCreditCached;
mutable bool fWatchDebitCached;
mutable bool fWatchCreditCached;
mutable bool fImmatureWatchCreditCached;
mutable bool fAvailableWatchCreditCached;
mutable bool fChangeCached;
mutable CAmount nDebitCached;
mutable CAmount nCreditCached;
mutable CAmount nImmatureCreditCached;
mutable CAmount nAvailableCreditCached;
mutable CAmount nAnonymizedCreditCached;
mutable CAmount nDenomUnconfCreditCached;
mutable CAmount nDenomConfCreditCached;
mutable CAmount nWatchDebitCached;
mutable CAmount nWatchCreditCached;
mutable CAmount nImmatureWatchCreditCached;
mutable CAmount nAvailableWatchCreditCached;
mutable CAmount nChangeCached;
CWalletTx()
{
Init(NULL);
}
CWalletTx(const CWallet* pwalletIn)
{
Init(pwalletIn);
}
CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
{
Init(pwalletIn);
}
CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
{
Init(pwalletIn);
}
void Init(const CWallet* pwalletIn)
{
pwallet = pwalletIn;
mapValue.clear();
vOrderForm.clear();
fTimeReceivedIsTxTime = false;
nTimeReceived = 0;
nTimeSmart = 0;
fFromMe = false;
strFromAccount.clear();
fDebitCached = false;
fCreditCached = false;
fImmatureCreditCached = false;
fAvailableCreditCached = false;
fAnonymizedCreditCached = false;
fDenomUnconfCreditCached = false;
fDenomConfCreditCached = false;
fWatchDebitCached = false;
fWatchCreditCached = false;
fImmatureWatchCreditCached = false;
fAvailableWatchCreditCached = false;
fChangeCached = false;
nDebitCached = 0;
nCreditCached = 0;
nImmatureCreditCached = 0;
nAvailableCreditCached = 0;
nAnonymizedCreditCached = 0;
nDenomUnconfCreditCached = 0;
nDenomConfCreditCached = 0;
nWatchDebitCached = 0;
nWatchCreditCached = 0;
nAvailableWatchCreditCached = 0;
nImmatureWatchCreditCached = 0;
nChangeCached = 0;
nOrderPos = -1;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
if (ser_action.ForRead())
Init(NULL);
char fSpent = false;
if (!ser_action.ForRead())
{
mapValue["fromaccount"] = strFromAccount;
WriteOrderPos(nOrderPos, mapValue);
if (nTimeSmart)
mapValue["timesmart"] = strprintf("%u", nTimeSmart);
}
READWRITE(*(CMerkleTx*)this);
std::vector<CMerkleTx> vUnused; //! Used to be vtxPrev
READWRITE(vUnused);
READWRITE(mapValue);
READWRITE(vOrderForm);
READWRITE(fTimeReceivedIsTxTime);
READWRITE(nTimeReceived);
READWRITE(fFromMe);
READWRITE(fSpent);
if (ser_action.ForRead())
{
strFromAccount = mapValue["fromaccount"];
ReadOrderPos(nOrderPos, mapValue);
nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(mapValue["timesmart"]) : 0;
}
mapValue.erase("fromaccount");
mapValue.erase("version");
mapValue.erase("spent");
mapValue.erase("n");
mapValue.erase("timesmart");
}
//! make sure balances are recalculated
void MarkDirty()
{
fCreditCached = false;
fAvailableCreditCached = false;
fImmatureCreditCached = false;
fAnonymizedCreditCached = false;
fDenomUnconfCreditCached = false;
fDenomConfCreditCached = false;
fWatchDebitCached = false;
fWatchCreditCached = false;
fAvailableWatchCreditCached = false;
fImmatureWatchCreditCached = false;
fDebitCached = false;
fChangeCached = false;
}
void BindWallet(CWallet *pwalletIn)
{
pwallet = pwalletIn;
MarkDirty();
}
//! filter decides which addresses will count towards the debit
CAmount GetDebit(const isminefilter& filter) const;
CAmount GetCredit(const isminefilter& filter) const;
CAmount GetImmatureCredit(bool fUseCache=true) const;
CAmount GetAvailableCredit(bool fUseCache=true) const;
CAmount GetImmatureWatchOnlyCredit(const bool& fUseCache=true) const;
CAmount GetAvailableWatchOnlyCredit(const bool& fUseCache=true) const;
CAmount GetChange() const;
CAmount GetAnonymizedCredit(bool fUseCache=true) const;
CAmount GetDenominatedCredit(bool unconfirmed, bool fUseCache=true) const;
void GetAmounts(std::list<COutputEntry>& listReceived,
std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const;
void GetAccountAmounts(const std::string& strAccount, CAmount& nReceived,
CAmount& nSent, CAmount& nFee, const isminefilter& filter) const;
bool IsFromMe(const isminefilter& filter) const
{
return (GetDebit(filter) > 0);
}
// True if only scriptSigs are different
bool IsEquivalentTo(const CWalletTx& tx) const;
bool InMempool() const;
bool IsTrusted() const;
bool WriteToDisk(CWalletDB *pwalletdb);
int64_t GetTxTime() const;
int GetRequestCount() const;
bool RelayWalletTransaction(CConnman* connman, std::string strCommand="tx");
std::set<uint256> GetConflicts() const;
};
class COutput
{
public:
const CWalletTx *tx;
int i;
int nDepth;
bool fSpendable;
bool fSolvable;
COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn, bool fSolvableIn)
{
tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn; fSolvable = fSolvableIn;
}
//Used with Darksend. Will return largest nondenom, then denominations, then very small inputs
int Priority() const;
std::string ToString() const;
};
/** Private key that includes an expiration date in case it never gets used. */
class CWalletKey
{
public:
CPrivKey vchPrivKey;
int64_t nTimeCreated;
int64_t nTimeExpires;
std::string strComment;
//! todo: add something to note what created it (user, getnewaddress, change)
//! maybe should have a map<string, string> property map
CWalletKey(int64_t nExpires=0);
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(vchPrivKey);
READWRITE(nTimeCreated);
READWRITE(nTimeExpires);
READWRITE(LIMITED_STRING(strComment, 65536));
}
};
/**
* Internal transfers.
* Database key is acentry<account><counter>.
*/
class CAccountingEntry
{
public:
std::string strAccount;
CAmount nCreditDebit;
int64_t nTime;
std::string strOtherAccount;
std::string strComment;
mapValue_t mapValue;
int64_t nOrderPos; //! position in ordered transaction list
uint64_t nEntryNo;
CAccountingEntry()
{
SetNull();
}
void SetNull()
{
nCreditDebit = 0;
nTime = 0;
strAccount.clear();
strOtherAccount.clear();
strComment.clear();
nOrderPos = -1;
nEntryNo = 0;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
//! Note: strAccount is serialized as part of the key, not here.
READWRITE(nCreditDebit);
READWRITE(nTime);
READWRITE(LIMITED_STRING(strOtherAccount, 65536));
if (!ser_action.ForRead())
{
WriteOrderPos(nOrderPos, mapValue);
if (!(mapValue.empty() && _ssExtra.empty()))
{
CDataStream ss(nType, nVersion);
ss.insert(ss.begin(), '\0');
ss << mapValue;
ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
strComment.append(ss.str());
}
}
READWRITE(LIMITED_STRING(strComment, 65536));
size_t nSepPos = strComment.find("\0", 0, 1);
if (ser_action.ForRead())
{
mapValue.clear();
if (std::string::npos != nSepPos)
{
CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
ss >> mapValue;
_ssExtra = std::vector<char>(ss.begin(), ss.end());
}
ReadOrderPos(nOrderPos, mapValue);
}
if (std::string::npos != nSepPos)
strComment.erase(nSepPos);
mapValue.erase("n");
}
private:
std::vector<char> _ssExtra;
};
/**
* A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
* and provides the ability to create new transactions.
*/
class CWallet : public CCryptoKeyStore, public CValidationInterface
{
private:
/**
* Select a set of coins such that nValueRet >= nTargetValue and at least
* all coins from coinControl are selected; Never select unconfirmed coins
* if they are not ours
*/
bool SelectCoins(const CAmount& nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl *coinControl = NULL, AvailableCoinsType nCoinType=ALL_COINS, bool fUseInstantSend = true) const;
CWalletDB *pwalletdbEncryption;
//! the current wallet version: clients below this version are not able to load the wallet
int nWalletVersion;
//! the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
int nWalletMaxVersion;
int64_t nNextResend;
int64_t nLastResend;
bool fBroadcastTransactions;
mutable bool fAnonymizableTallyCached;
mutable std::vector<CompactTallyItem> vecAnonymizableTallyCached;
mutable bool fAnonymizableTallyCachedNonDenom;
mutable std::vector<CompactTallyItem> vecAnonymizableTallyCachedNonDenom;
/**
* Used to keep track of spent outpoints, and
* detect and report conflicts (double-spends or
* mutated transactions where the mutant gets mined).
*/
typedef std::multimap<COutPoint, uint256> TxSpends;
TxSpends mapTxSpends;
void AddToSpends(const COutPoint& outpoint, const uint256& wtxid);
void AddToSpends(const uint256& wtxid);
std::set<COutPoint> setWalletUTXO;
/* Mark a transaction (and its in-wallet descendants) as conflicting with a particular block. */
void MarkConflicted(const uint256& hashBlock, const uint256& hashTx);
void SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator>);
/* HD derive new child key (on internal or external chain) */
void DeriveNewChildKey(const CKeyMetadata& metadata, CKey& secretRet, uint32_t nAccountIndex, bool fInternal /*= false*/);
public:
/*
* Main wallet lock.
* This lock protects all the fields added by CWallet
* except for:
* fFileBacked (immutable after instantiation)
* strWalletFile (immutable after instantiation)
*/
mutable CCriticalSection cs_wallet;
bool fFileBacked;
const std::string strWalletFile;
void LoadKeyPool(int nIndex, const CKeyPool &keypool)
{
if (keypool.fInternal) {
setInternalKeyPool.insert(nIndex);
} else {
setExternalKeyPool.insert(nIndex);
}
// If no metadata exists yet, create a default with the pool key's
// creation time. Note that this may be overwritten by actually
// stored metadata for that key later, which is fine.
CKeyID keyid = keypool.vchPubKey.GetID();
if (mapKeyMetadata.count(keyid) == 0)
mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
}
std::set<int64_t> setInternalKeyPool;
std::set<int64_t> setExternalKeyPool;
std::map<CKeyID, CKeyMetadata> mapKeyMetadata;
typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
MasterKeyMap mapMasterKeys;
unsigned int nMasterKeyMaxID;
CWallet()
{
SetNull();
}
CWallet(const std::string& strWalletFileIn)
: strWalletFile(strWalletFileIn)
{
SetNull();
fFileBacked = true;
}
~CWallet()
{
delete pwalletdbEncryption;
pwalletdbEncryption = NULL;
}
void SetNull()
{
nWalletVersion = FEATURE_BASE;
nWalletMaxVersion = FEATURE_BASE;
fFileBacked = false;
nMasterKeyMaxID = 0;
pwalletdbEncryption = NULL;
nOrderPosNext = 0;
nNextResend = 0;
nLastResend = 0;
nTimeFirstKey = 0;
fBroadcastTransactions = false;
fAnonymizableTallyCached = false;
fAnonymizableTallyCachedNonDenom = false;
vecAnonymizableTallyCached.clear();
vecAnonymizableTallyCachedNonDenom.clear();
}
std::map<uint256, CWalletTx> mapWallet;
std::list<CAccountingEntry> laccentries;
typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
typedef std::multimap<int64_t, TxPair > TxItems;
TxItems wtxOrdered;
int64_t nOrderPosNext;
std::map<uint256, int> mapRequestCount;
std::map<CTxDestination, CAddressBookData> mapAddressBook;
CPubKey vchDefaultKey;
std::set<COutPoint> setLockedCoins;
int64_t nTimeFirstKey;
int64_t nKeysLeftSinceAutoBackup;
std::map<CKeyID, CHDPubKey> mapHdPubKeys; //<! memory map of HD extended pubkeys
const CWalletTx* GetWalletTx(const uint256& hash) const;
//! check whether we are allowed to upgrade (or already support) to the named feature
bool CanSupportFeature(enum WalletFeature wf) { AssertLockHeld(cs_wallet); return nWalletMaxVersion >= wf; }
/**
* populate vCoins with vector of available COutputs.
*/
void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl = NULL, bool fIncludeZeroValue=false, AvailableCoinsType nCoinType=ALL_COINS, bool fUseInstantSend = false) const;
/**
* Shuffle and select coins until nTargetValue is reached while avoiding
* small change; This method is stochastic for some inputs and upon
* completion the coin set and corresponding actual target value is
* assembled
*/
bool SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, std::vector<COutput> vCoins, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, bool fUseInstantSend = false) const;
// Coin selection
bool SelectCoinsByDenominations(int nDenom, CAmount nValueMin, CAmount nValueMax, std::vector<CTxDSIn>& vecTxDSInRet, std::vector<COutput>& vCoinsRet, CAmount& nValueRet, int nPrivateSendRoundsMin, int nPrivateSendRoundsMax);
bool GetCollateralTxDSIn(CTxDSIn& txdsinRet, CAmount& nValueRet) const;
bool SelectCoinsDark(CAmount nValueMin, CAmount nValueMax, std::vector<CTxIn>& vecTxInRet, CAmount& nValueRet, int nPrivateSendRoundsMin, int nPrivateSendRoundsMax) const;
bool SelectCoinsGrouppedByAddresses(std::vector<CompactTallyItem>& vecTallyRet, bool fSkipDenominated = true, bool fAnonymizable = true, bool fSkipUnconfirmed = true) const;
/// Get 1000exilium output and keys which can be used for the Masternode
bool GetMasternodeOutpointAndKeys(COutPoint& outpointRet, CPubKey& pubKeyRet, CKey& keyRet, std::string strTxHash = "", std::string strOutputIndex = "");
/// Extract txin information and keys from output
bool GetOutpointAndKeysFromOutput(const COutput& out, COutPoint& outpointRet, CPubKey& pubKeyRet, CKey& keyRet);
bool HasCollateralInputs(bool fOnlyConfirmed = true) const;
int CountInputsWithAmount(CAmount nInputAmount);
// get the PrivateSend chain depth for a given input
int GetRealOutpointPrivateSendRounds(const COutPoint& outpoint, int nRounds) const;
// respect current settings
int GetOutpointPrivateSendRounds(const COutPoint& outpoint) const;
bool IsDenominated(const COutPoint& outpoint) const;
bool IsSpent(const uint256& hash, unsigned int n) const;
bool IsLockedCoin(uint256 hash, unsigned int n) const;
void LockCoin(COutPoint& output);
void UnlockCoin(COutPoint& output);
void UnlockAllCoins();
void ListLockedCoins(std::vector<COutPoint>& vOutpts);
/**
* keystore implementation
* Generate a new key
*/
CPubKey GenerateNewKey(uint32_t nAccountIndex, bool fInternal /*= false*/);
//! HaveKey implementation that also checks the mapHdPubKeys
bool HaveKey(const CKeyID &address) const;
//! GetPubKey implementation that also checks the mapHdPubKeys
bool GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const;
//! GetKey implementation that can derive a HD private key on the fly
bool GetKey(const CKeyID &address, CKey& keyOut) const;
//! Adds a HDPubKey into the wallet(database)
bool AddHDPubKey(const CExtPubKey &extPubKey, bool fInternal);
//! loads a HDPubKey into the wallets memory
bool LoadHDPubKey(const CHDPubKey &hdPubKey);
//! Adds a key to the store, and saves it to disk.
bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey);
//! Adds a key to the store, without saving it to disk (used by LoadWallet)
bool LoadKey(const CKey& key, const CPubKey &pubkey) { return CCryptoKeyStore::AddKeyPubKey(key, pubkey); }
//! Load metadata (used by LoadWallet)
bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata);
bool LoadMinVersion(int nVersion) { AssertLockHeld(cs_wallet); nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
//! Adds an encrypted key to the store, and saves it to disk.
bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
//! Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
bool AddCScript(const CScript& redeemScript);
bool LoadCScript(const CScript& redeemScript);
//! Adds a destination data tuple to the store, and saves it to disk
bool AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
//! Erases a destination data tuple in the store and on disk
bool EraseDestData(const CTxDestination &dest, const std::string &key);
//! Adds a destination data tuple to the store, without saving it to disk
bool LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value);
//! Look up a destination data tuple in the store, return true if found false otherwise
bool GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const;
//! Adds a watch-only address to the store, and saves it to disk.
bool AddWatchOnly(const CScript &dest);
bool RemoveWatchOnly(const CScript &dest);
//! Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
bool LoadWatchOnly(const CScript &dest);
bool Unlock(const SecureString& strWalletPassphrase, bool fForMixingOnly = false);
bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
bool EncryptWallet(const SecureString& strWalletPassphrase);
void GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const;
/**
* Increment the next transaction order id
* @return next transaction order id
*/
int64_t IncOrderPosNext(CWalletDB *pwalletdb = NULL);
void MarkDirty();
bool AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet, CWalletDB* pwalletdb);
void SyncTransaction(const CTransaction& tx, const CBlock* pblock);
bool AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate);
int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
void ReacceptWalletTransactions();
void ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman);
std::vector<uint256> ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman);
CAmount GetBalance() const;
CAmount GetUnconfirmedBalance() const;
CAmount GetImmatureBalance() const;
CAmount GetWatchOnlyBalance() const;
CAmount GetUnconfirmedWatchOnlyBalance() const;
CAmount GetImmatureWatchOnlyBalance() const;
CAmount GetAnonymizableBalance(bool fSkipDenominated = false, bool fSkipUnconfirmed = true) const;
CAmount GetAnonymizedBalance() const;
float GetAverageAnonymizedRounds() const;
CAmount GetNormalizedAnonymizedBalance() const;
CAmount GetNeedsToBeAnonymizedBalance(CAmount nMinBalance = 0) const;
CAmount GetDenominatedBalance(bool unconfirmed=false) const;
bool GetBudgetSystemCollateralTX(CTransaction& tx, uint256 hash, CAmount amount, bool fUseInstantSend);
bool GetBudgetSystemCollateralTX(CWalletTx& tx, uint256 hash, CAmount amount, bool fUseInstantSend);
/**
* Insert additional inputs into the transaction by
* calling CreateTransaction();
*/
bool FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosRet, std::string& strFailReason, bool includeWatching);
/**
* Create a new transaction paying the recipients with a set of coins
* selected by SelectCoins(); Also create the change output, when needed
*/
bool CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosRet,
std::string& strFailReason, const CCoinControl *coinControl = NULL, bool sign = true, AvailableCoinsType nCoinType=ALL_COINS, bool fUseInstantSend=false);
bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, std::string strCommand="tx");
bool CreateCollateralTransaction(CMutableTransaction& txCollateral, std::string& strReason);
bool ConvertList(std::vector<CTxIn> vecTxIn, std::vector<CAmount>& vecAmounts);
bool AddAccountingEntry(const CAccountingEntry&, CWalletDB & pwalletdb);
static CFeeRate minTxFee;
static CFeeRate fallbackFee;
/**
* Estimate the minimum fee considering user set parameters
* and the required fee
*/
static CAmount GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool);
/**
* Return the minimum required fee taking into account the
* floating relay fee and user set minimum transaction fee
*/
static CAmount GetRequiredFee(unsigned int nTxBytes);
bool NewKeyPool();
size_t KeypoolCountExternalKeys();
size_t KeypoolCountInternalKeys();
bool TopUpKeyPool(unsigned int kpSize = 0);
void ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fInternal);
void KeepKey(int64_t nIndex);
void ReturnKey(int64_t nIndex, bool fInternal);
bool GetKeyFromPool(CPubKey &key, bool fInternal /*= false*/);
int64_t GetOldestKeyPoolTime();
void GetAllReserveKeys(std::set<CKeyID>& setAddress) const;
std::set< std::set<CTxDestination> > GetAddressGroupings();
std::map<CTxDestination, CAmount> GetAddressBalances();
std::set<CTxDestination> GetAccountAddresses(const std::string& strAccount) const;
isminetype IsMine(const CTxIn& txin) const;
CAmount GetDebit(const CTxIn& txin, const isminefilter& filter) const;
isminetype IsMine(const CTxOut& txout) const;
CAmount GetCredit(const CTxOut& txout, const isminefilter& filter) const;
bool IsChange(const CTxOut& txout) const;
CAmount GetChange(const CTxOut& txout) const;
bool IsMine(const CTransaction& tx) const;
/** should probably be renamed to IsRelevantToMe */
bool IsFromMe(const CTransaction& tx) const;
CAmount GetDebit(const CTransaction& tx, const isminefilter& filter) const;
CAmount GetCredit(const CTransaction& tx, const isminefilter& filter) const;
CAmount GetChange(const CTransaction& tx) const;
void SetBestChain(const CBlockLocator& loc);
DBErrors LoadWallet(bool& fFirstRunRet);
DBErrors ZapWalletTx(std::vector<CWalletTx>& vWtx);
bool SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& purpose);
bool DelAddressBook(const CTxDestination& address);
bool UpdatedTransaction(const uint256 &hashTx);
void Inventory(const uint256 &hash)
{
{
LOCK(cs_wallet);
std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
if (mi != mapRequestCount.end())
(*mi).second++;
}
}
void GetScriptForMining(boost::shared_ptr<CReserveScript> &script);
void ResetRequestCount(const uint256 &hash)
{
LOCK(cs_wallet);
mapRequestCount[hash] = 0;
};
unsigned int GetKeyPoolSize()
{
AssertLockHeld(cs_wallet); // set{Ex,In}ternalKeyPool
return setInternalKeyPool.size() + setExternalKeyPool.size();
}
bool SetDefaultKey(const CPubKey &vchPubKey);
//! signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
//! change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
bool SetMaxVersion(int nVersion);
//! get the current wallet format (the oldest client version guaranteed to understand this wallet)
int GetVersion() { LOCK(cs_wallet); return nWalletVersion; }
//! Get wallet transactions that conflict with given transaction (spend same outputs)
std::set<uint256> GetConflicts(const uint256& txid) const;
//! Flush wallet (bitdb flush)
void Flush(bool shutdown=false);
//! Verify the wallet database and perform salvage if required
static bool Verify(const std::string& walletFile, std::string& warningString, std::string& errorString);
/**
* Address book entry changed.
* @note called with lock cs_wallet held.
*/
boost::signals2::signal<void (CWallet *wallet, const CTxDestination
&address, const std::string &label, bool isMine,
const std::string &purpose,
ChangeType status)> NotifyAddressBookChanged;
/**
* Wallet transaction added, removed or updated.
* @note called with lock cs_wallet held.
*/
boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx,
ChangeType status)> NotifyTransactionChanged;
/** Show progress e.g. for rescan */
boost::signals2::signal<void (const std::string &title, int nProgress)> ShowProgress;
/** Watch-only address added */
boost::signals2::signal<void (bool fHaveWatchOnly)> NotifyWatchonlyChanged;
/** Inquire whether this wallet broadcasts transactions. */
bool GetBroadcastTransactions() const { return fBroadcastTransactions; }
/** Set whether this wallet broadcasts transactions. */
void SetBroadcastTransactions(bool broadcast) { fBroadcastTransactions = broadcast; }
/* Mark a transaction (and it in-wallet descendants) as abandoned so its inputs may be respent. */
bool AbandonTransaction(const uint256& hashTx);
/**
* HD Wallet Functions
*/
/* Returns true if HD is enabled */
bool IsHDEnabled();
/* Generates a new HD chain */
void GenerateNewHDChain();
/* Set the HD chain model (chain child index counters) */
bool SetHDChain(const CHDChain& chain, bool memonly);
bool SetCryptedHDChain(const CHDChain& chain, bool memonly);
bool GetDecryptedHDChain(CHDChain& hdChainRet);
};
/** A key allocated from the key pool. */
class CReserveKey : public CReserveScript
{
protected:
CWallet* pwallet;
int64_t nIndex;
CPubKey vchPubKey;
bool fInternal;
public:
CReserveKey(CWallet* pwalletIn)
{
nIndex = -1;
pwallet = pwalletIn;
fInternal = false;
}
~CReserveKey()
{
ReturnKey();
}
void ReturnKey();
bool GetReservedKey(CPubKey &pubkey, bool fInternalIn /*= false*/);
void KeepKey();
void KeepScript() { KeepKey(); }
};
/**
* Account information.
* Stored in wallet with key "acc"+string account name.
*/
class CAccount
{
public:
CPubKey vchPubKey;
CAccount()
{
SetNull();
}
void SetNull()
{
vchPubKey = CPubKey();
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(vchPubKey);
}
};
#endif // BITCOIN_WALLET_WALLET_H
| [
"[email protected]"
] | [
[
[
1,
1097
]
]
] |
8b9b6cee9f4a3bdf5a803cc6d17ae5edb97e8f6e | 510a162f34810012b90de49893dd12e1b760f8ac | /main.cpp | df1e65c2de255b41f25520def95f2773d5fe65a1 | [] | no_license | dionsaputra/framebuffer-paint | 97e19a0e623ac670ff40d96a12e61af9e15b758b | d8bc6cbf72dbecec09c5dff433285800eb07d7db | refs/heads/master | 2020-04-28T04:04:30.521444 | 2019-03-15T16:55:13 | 2019-03-15T16:55:13 | 174,963,715 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30,476 | cpp | #include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <fcntl.h>
#include <linux/fb.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <stdio.h>
#include <sys/types.h>
#include <termios.h>
#include <ctype.h>
#include <time.h>
#include <vector>
#include <map>
#include <iterator>
#include "Drawer.h"
#include "Point.h"
#include "Color.h"
#include "Parser.h"
#include "Wireframe.h"
#include "PaintController.h"
#include "Letter.h"
#define CANVAS_WIDTH 1200
#define CANVAS_LENGTH 900
using namespace std;
// Global variable
PaintController controller;
Drawer drawer;
Parser parser;
string filename;
vector<Point> cornerWindow;
string currentWireframe;
map<string,Wireframe> wireframes;
Wireframe window;
Wireframe horizontalScrollBar;
Wireframe verticalScrollBar;
Wireframe horizontalScrollBarBorder;
Wireframe verticalScrollBarBorder;
Wireframe legend;
Point disorientation;
float diffX,diffY;
bool useBatik;
void credits(){
drawer.clear_screen();
for (int y = drawer.vinfo.yres - 1; y >= 0; y-=5){
drawer.draw_word("DONATLAB",Point(400, y), 25, 4, Color(74, 123, 192));
drawer.draw_word("MUHAMAD ILYAS MUSTAFA - SMAN 4 BANDUNG",Point(100, y + 150), 11, 2, Color(20, 200, 100));
drawer.draw_word("DION SAPUTRA - SMAN 10 PADANG", Point(100, y + 200), 10, 2, Color(100, 100, 171));
drawer.draw_word("DAFI IHSANDIYA FARAZ - SMAN 3 BANDUNG", Point(100, y + 250), 11, 2, Color(154, 200, 200));
drawer.draw_word("KRISHNA AURELIO N - SMAN 7 CIMAHI", Point(100, y + 300), 11, 2, Color(12, 32, 111));
drawer.draw_word("RIFO AHMAD GENADI - SMAN 1 GARUT", Point(100, y + 350), 11, 2, Color(131, 100, 171));
drawer.draw_word("ADAM FADHEL R - SMAN 2 TANGERANG", Point(100, y + 400), 11, 2, Color(153, 132, 12));
usleep(20000);
if (y <= 5){
drawer.clear_screen();
break;
}
drawer.draw_word("DONATLAB", Point(400, y), 25, 4, Color(0, 0, 0));
drawer.draw_word("MUHAMAD ILYAS MUSTAFA - SMAN 4 BANDUNG", Point(100, y + 150), 11, 2, Color(0, 0, 0));
drawer.draw_word("DION SAPUTRA - SMAN 10 PADANG", Point(100, y + 200), 11, 2, Color(0, 0, 0));
drawer.draw_word("DAFI IHSANDIYA FARAZ - SMAN 3 BANDUNG", Point(100, y + 250), 11, 2, Color(0, 0, 0));
drawer.draw_word("KRISHNA AURELIO N - SMAN 7 CIMAHI", Point(100, y + 300), 11, 2, Color(0, 0, 0));
drawer.draw_word("RIFO AHMAD GENADI - SMAN 1 GARUT", Point(100, y + 350), 11, 2, Color(0, 0, 0));
drawer.draw_word("ADAM FADHEL R - SMAN 2 TANGERANG", Point(100, y + 400), 11, 2, Color(0, 0, 0));
}
}
Wireframe createRectangle(Point topLeft, Point bottomRight) {
vector<Point> points;
points.push_back(topLeft);
points.push_back(Point(bottomRight.getX(), topLeft.getY()));
points.push_back(bottomRight);
points.push_back(Point(topLeft.getX(), bottomRight.getY()));
Wireframe wireframe;
wireframe.setPoints(points);
wireframe.updateEnvelope();
return wireframe;
}
void setupWindow() {
int xres = drawer.vinfo.xres, yres = drawer.vinfo.yres;
window = createRectangle(Point(350,50), Point(xres-50, yres-250));
window.setBorderColor(Color(0,250,0));
disorientation = window.getTopLeft();
useBatik = false;
diffX = (float) (xres-350)/CANVAS_WIDTH;
diffY = (float) (yres-100)/CANVAS_LENGTH;
drawer.draw_wireframe(window);
}
void setupLegend() {
int xres = drawer.vinfo.xres, yres = drawer.vinfo.yres;
legend = createRectangle(Point(350,yres-200),Point(xres-30,yres-30));
legend.setBorderColor(Color(0,250,0));
drawer.draw_wireframe(legend);
int xStart = 400, xEnd = xres-30-50;
int dx = xEnd-xStart;
int yStart = yres-180;
drawer.draw_word("FILE", Point(xStart-25, yStart), 20, 3, Color(0, 255, 255));
drawer.draw_word("NEW", Point(xStart, yStart+30), 15, 2, Color(0, 255, 0));
drawer.draw_word("OPEN", Point(xStart, yStart+50), 15, 2, Color(0, 255, 0));
drawer.draw_word("SAVE", Point(xStart, yStart+70), 15, 2, Color(0, 255, 0));
drawer.draw_word("EXIT", Point(xStart, yStart+90), 15, 2, Color(0, 255, 0));
int xCol2 = xStart + (dx/5);
drawer.draw_word("VIEW", Point(xCol2-25, yStart), 20, 3, Color(0, 255, 255));
drawer.draw_word("ZOOM", Point(xCol2, yStart+30), 15, 2, Color(0, 255, 0));
drawer.draw_word("SCROLL", Point(xCol2, yStart+50), 15, 2, Color(0, 255, 0));
drawer.draw_word("TRANSLATE", Point(xCol2, yStart+70), 15, 2, Color(0, 255, 0));
int xCol3 = xStart + (2*dx/5);
drawer.draw_word("ATTRIBUTE", Point(xCol3-25, yStart), 20, 3, Color(0, 255, 255));
drawer.draw_word("LINE-COLOR", Point(xCol3, yStart+30), 15, 2, Color(0, 255, 0));
drawer.draw_word("THICKNESS", Point(xCol3, yStart+50), 15, 2, Color(0, 255, 0));
drawer.draw_word("LINE-STYLE", Point(xCol3, yStart+70), 15, 2, Color(0, 255, 0));
drawer.draw_word("FILL", Point(xCol3, yStart+90), 15, 2, Color(0, 255, 0));
drawer.draw_word("UNFILL", Point(xCol3, yStart+110), 15, 2, Color(0, 255, 0));
drawer.draw_word("USE-BATIK", Point(xCol3, yStart+130), 15, 2, Color(0, 255, 0));
int xCol4 = xStart + (3*dx/5);
drawer.draw_word("OBJECT", Point(xCol4-25, yStart), 20, 3, Color(0, 255, 255));
drawer.draw_word("LINE", Point(xCol4, yStart+30), 15, 2, Color(0, 255, 0));
drawer.draw_word("TRIANGLE", Point(xCol4, yStart+50), 15, 2, Color(0, 255, 0));
drawer.draw_word("RECTANGLE", Point(xCol4, yStart+70), 15, 2, Color(0, 255, 0));
drawer.draw_word("POLYGON", Point(xCol4, yStart+90), 15, 2, Color(0, 255, 0));
drawer.draw_word("SELECT", Point(xCol4, yStart+110), 15, 2, Color(0, 255, 0));
drawer.draw_word("DELETE", Point(xCol4, yStart+130), 15, 2, Color(0, 255, 0));
int xCol5 = xStart + (4*dx/5);
drawer.draw_word("ANIMATION", Point(xCol5-25, yStart), 20, 3, Color(0, 255, 255));
drawer.draw_word("CREDITS", Point(xCol5, yStart+30), 15, 2, Color(0, 255, 0));
}
void setupHorizontalScrollBarBorder() {
int xres = drawer.vinfo.xres, yres = drawer.vinfo.yres;
horizontalScrollBarBorder = createRectangle(Point(350,yres-249), Point(xres-50, yres-230));
horizontalScrollBarBorder.setBorderColor(Color(0,250,0));
drawer.draw_wireframe(horizontalScrollBarBorder);
}
void setupVerticalScrollBarBorder() {
int xres = drawer.vinfo.xres, yres = drawer.vinfo.yres;
verticalScrollBarBorder = createRectangle(Point(xres-49,50), Point(xres-31, yres-250));
verticalScrollBarBorder.setBorderColor(Color(0,250,0));
drawer.draw_wireframe(verticalScrollBarBorder);
}
void setupScrollbars() {
int xres = drawer.vinfo.xres, yres = drawer.vinfo.yres;
horizontalScrollBar = createRectangle(Point(450,yres-249), Point(xres-250, yres-230));
horizontalScrollBar.setBorderColor(Color(0,250,0));
horizontalScrollBar.setFillColor(Color(0,250,0));
horizontalScrollBar.setInnerPoint(Point((450+xres-250)/2, (yres-249+yres-230)/2));
drawer.draw_wireframe(horizontalScrollBar);
drawer.queueFloodFill(horizontalScrollBar);
verticalScrollBar = createRectangle(Point(xres-50,250), Point(xres-30, yres-450));
verticalScrollBar.setBorderColor(Color(0,250,0));
verticalScrollBar.setFillColor(Color(0,250,0));
verticalScrollBar.setInnerPoint(Point((xres-50+xres-30)/2, (250+yres-450)/2));
drawer.draw_wireframe(verticalScrollBar);
drawer.queueFloodFill(verticalScrollBar);
}
void resizeHorizontalScrollBar(int dx){
int xres = drawer.vinfo.xres, yres = drawer.vinfo.yres;
Point newTopLeft = Point(horizontalScrollBar.getTopLeft().getX()+dx,yres-249);
Point newBottomRight = Point(horizontalScrollBar.getBottomRight().getX()-dx,yres-230);
horizontalScrollBar = createRectangle(newTopLeft, newBottomRight);
horizontalScrollBar.setBorderColor(Color(0,250,0));
horizontalScrollBar.setFillColor(Color(0,250,0));
horizontalScrollBar.setInnerPoint(Point((newTopLeft.getX() + newBottomRight.getX())/2, (newTopLeft.getY() + newBottomRight.getY())/2));
}
void resizeVerticalScrollBar(int dy){
int xres = drawer.vinfo.xres, yres = drawer.vinfo.yres;
Point newTopLeft = Point(xres-50,verticalScrollBar.getTopLeft().getY()+dy);
Point newBottomRight = Point(xres-30,verticalScrollBar.getBottomRight().getY()-dy);
verticalScrollBar = createRectangle(newTopLeft, newBottomRight);
verticalScrollBar.setBorderColor(Color(0,250,0));
verticalScrollBar.setFillColor(Color(0,250,0));
verticalScrollBar.setInnerPoint(Point((newTopLeft.getX() + newBottomRight.getX())/2, (newTopLeft.getY() + newBottomRight.getY())/2));
}
void redrawScrollbars(){
drawer.draw_wireframe(horizontalScrollBar);
drawer.draw_wireframe(verticalScrollBar);
drawer.queueFloodFill(horizontalScrollBar);
drawer.queueFloodFill(verticalScrollBar);
drawer.draw_wireframe(horizontalScrollBarBorder);
drawer.draw_wireframe(verticalScrollBarBorder);
}
void scroll(int dx, int dy){
int leftScrollbarBorder = horizontalScrollBarBorder.getTopLeft().getX();
int rightScrollbarBorder = horizontalScrollBarBorder.getBottomRight().getX();
int topScrollbarBorder = verticalScrollBarBorder.getTopLeft().getY();
int bottomScrollbarBorder = verticalScrollBarBorder.getBottomRight().getY();
if (horizontalScrollBar.getTopLeft().getX()+dx >= leftScrollbarBorder
&& horizontalScrollBar.getBottomRight().getX()+dx <= rightScrollbarBorder
&& verticalScrollBar.getTopLeft().getY()+dy >= topScrollbarBorder
&& verticalScrollBar.getBottomRight().getY()+dy <= bottomScrollbarBorder){
drawer.erase_wireframe(horizontalScrollBar);
drawer.unfill_wireframe(horizontalScrollBar);
drawer.erase_wireframe(verticalScrollBar);
drawer.unfill_wireframe(verticalScrollBar);
drawer.erase_canvas(wireframes,disorientation);
if (dx != 0)
horizontalScrollBar.translate(dx,dy);
if (dy != 0)
verticalScrollBar.translate(dx,dy);
for (auto itr = wireframes.begin(); itr!=wireframes.end();itr++){
itr->second.translate(-dx,-dy);
}
drawer.draw_canvas(wireframes,window,disorientation,true,useBatik);
redrawScrollbars();
}
}
bool checkZoomOut(int dx, int dy){
int leftScrollbarBorder = horizontalScrollBarBorder.getTopLeft().getX();
int rightScrollbarBorder = horizontalScrollBarBorder.getBottomRight().getX();
int topScrollbarBorder = verticalScrollBarBorder.getTopLeft().getY();
int bottomScrollbarBorder = verticalScrollBarBorder.getBottomRight().getY();
return (dx > 0 && horizontalScrollBar.getTopLeft().getX()+dx >= leftScrollbarBorder
&& horizontalScrollBar.getBottomRight().getX()-dx <= rightScrollbarBorder
&& ((horizontalScrollBar.getBottomRight().getX() - horizontalScrollBar.getTopLeft().getX()) > 100)
&& verticalScrollBar.getTopLeft().getY()-dy >= topScrollbarBorder
&& verticalScrollBar.getBottomRight().getY()+dy <= bottomScrollbarBorder
&& (verticalScrollBar.getBottomRight().getY() - verticalScrollBar.getTopLeft().getY()> 55));
}
bool checkZoomIn(int dx, int dy){
int leftScrollbarBorder = horizontalScrollBarBorder.getTopLeft().getX();
int rightScrollbarBorder = horizontalScrollBarBorder.getBottomRight().getX();
int topScrollbarBorder = verticalScrollBarBorder.getTopLeft().getY();
int bottomScrollbarBorder = verticalScrollBarBorder.getBottomRight().getY();
return (dx < 0 && horizontalScrollBar.getTopLeft().getX()+dx >= leftScrollbarBorder
&& horizontalScrollBar.getBottomRight().getX()-dx <= rightScrollbarBorder
&& verticalScrollBar.getTopLeft().getY()-dy >= topScrollbarBorder
&& verticalScrollBar.getBottomRight().getY()+dy <= bottomScrollbarBorder);
}
void zoom(float scale){
int dx,dy;
int xres = drawer.vinfo.xres, yres = drawer.vinfo.yres;
if (scale < 1){
dx = -35;
dy = -15;
} else {
dx = 35;
dy = 15;
}
if (checkZoomOut(dx,dy) || checkZoomIn(dx,dy)){
drawer.erase_wireframe(horizontalScrollBar);
drawer.unfill_wireframe(horizontalScrollBar);
drawer.erase_wireframe(verticalScrollBar);
drawer.unfill_wireframe(verticalScrollBar);
drawer.erase_canvas(wireframes,disorientation);
for (auto itr = wireframes.begin(); itr!=wireframes.end();itr++){
itr->second.scale(Point((250+xres-50)/2, (50+yres-50)/2), scale);
}
resizeHorizontalScrollBar(dx);
resizeVerticalScrollBar(dy);
drawer.draw_canvas(wireframes,window,disorientation,true,useBatik);
redrawScrollbars();
drawer.draw_wireframe(horizontalScrollBarBorder);
drawer.draw_wireframe(verticalScrollBarBorder);
}
}
void moveScrollBar(Wireframe* scrollbar,int x,int y){
drawer.erase_wireframe(*scrollbar);
drawer.unfill_wireframe(*scrollbar);
scrollbar->translate(x,y);
drawer.draw_wireframe(*scrollbar);
drawer.queueFloodFill(*scrollbar);
drawer.draw_wireframe(horizontalScrollBarBorder);
drawer.draw_wireframe(verticalScrollBarBorder);
}
void setup() {
setupWindow();
setupLegend();
setupHorizontalScrollBarBorder();
setupVerticalScrollBarBorder();
setupScrollbars();
redrawScrollbars();
}
void hideLabels(){
for (auto itr = wireframes.begin(); itr != wireframes.end(); itr++) {
string name = itr->first;
Point loc = itr->second.getInnerPoint();
loc.translate(200, 0);
drawer.draw_word(name, loc, 25, 3, Color(0,0,0));
}
drawer.draw_canvas(wireframes,window,disorientation,true,useBatik);
}
int main() {
// Load file
string inputCommand;
for (int i=1; i<=100; i++) printf("\n");
setup();
// cout << "filename : ";
// cin >> filename;
// wireframes = controller.load(filename);
drawer.draw_canvas(wireframes, window, disorientation);
// Setup input mode
struct termios oldSettings, newSettings;
tcgetattr( fileno( stdin ), &oldSettings );
newSettings = oldSettings;
newSettings.c_lflag &= (~ICANON & ~ECHO); // one key mode
// Load file
flush(cout);
// Receive command
while(1){
printf("$ ");
flush(cout);
cin >> inputCommand;
hideLabels();
if (inputCommand == "new") {
if(!wireframes.empty()){
drawer.erase_canvas(wireframes,disorientation);
}
wireframes.clear();
currentWireframe = "";
} else if (inputCommand == "open") {
// TODO: add open command
cout << "filename : ";
cin >> filename;
if(!wireframes.empty()){
drawer.erase_canvas(wireframes,disorientation);
}
currentWireframe = "";
wireframes = controller.load(filename);
drawer.draw_canvas(wireframes, window, disorientation);
}else if(inputCommand == "select"){
cout << "----list----" << endl;
for (auto itr = wireframes.begin(); itr!=wireframes.end();itr++){
if (currentWireframe == itr->first){
cout << itr->first << " (selected)" << endl;
} else {
cout << itr->first << endl;
}
}
cout << "------------" << endl;
cin >> currentWireframe;
for (auto & c: currentWireframe) c = toupper(c);
cout << currentWireframe <<" selected" << endl;
} else if (inputCommand == "save") {
cout << "filename: ";
cin >> filename;
controller.save(wireframes,filename);
cout << "saved" << endl;
} else if (inputCommand == "current") {
cout << currentWireframe << endl;
int xres = drawer.vinfo.xres, yres = drawer.vinfo.yres;
} else if (inputCommand == "scroll"){
tcsetattr( fileno( stdin ), TCSANOW, &newSettings );
cout << "Use WASD to navigate" << endl;
cout << "Enter 'x' to return" << endl;
while (1){
char c;
read( fileno( stdin ), &c, 1 );
// printf( "Input available %c %d\n",c,c);
if (c == 'w' && verticalScrollBar.getTopLeft().getY()>50){
drawer.erase_canvas(wireframes,disorientation);
disorientation.translate(0,5);
moveScrollBar(&verticalScrollBar,0,-5 * diffY);
drawer.draw_wireframe(horizontalScrollBarBorder);
drawer.draw_wireframe(verticalScrollBarBorder);
setupLegend();
// Scroll up
} else if (c == 'a' && horizontalScrollBar.getTopLeft().getX()>350){
drawer.erase_canvas(wireframes,disorientation);
disorientation.translate(5,0);
drawer.draw_wireframe(horizontalScrollBarBorder);
drawer.draw_wireframe(verticalScrollBarBorder);
setupLegend();
moveScrollBar(&horizontalScrollBar,-5 * diffX,0);
// Scroll left
} else if (c == 's' && verticalScrollBar.getBottomRight().getY()<drawer.vinfo.yres-250){
drawer.erase_canvas(wireframes,disorientation);
disorientation.translate(0,-5);
moveScrollBar(&verticalScrollBar,0,5*diffY);
drawer.draw_wireframe(horizontalScrollBarBorder);
drawer.draw_wireframe(verticalScrollBarBorder);
setupLegend();
// Scroll down
} else if (c == 'd' && horizontalScrollBar.getBottomRight().getX()<drawer.vinfo.xres-50){
drawer.erase_canvas(wireframes,disorientation);
disorientation.translate(-5,0);
moveScrollBar(&horizontalScrollBar,5*diffX,0);
drawer.draw_wireframe(horizontalScrollBarBorder);
drawer.draw_wireframe(verticalScrollBarBorder);
setupLegend();
// Scroll right
} else if(c=='x'){
// Change settings
tcsetattr( fileno( stdin ), TCSANOW, &oldSettings );
break;
}
drawer.draw_canvas(wireframes,window,disorientation,true,useBatik);
}
} else if (inputCommand == "exit") {
exit(1);
} else if (inputCommand == "translate" && currentWireframe != ""){
tcsetattr( fileno( stdin ), TCSANOW, &newSettings );
cout << "Use WASD to move " << currentWireframe << " object" << endl;
cout << "Enter 'x' to finish" << endl;
while (1){
char c;
read( fileno( stdin ), &c, 1 );
if (c == 'w'){
drawer.erase_canvas(wireframes,disorientation);
wireframes.find(currentWireframe)->second.translate(0, -10);
} else if (c == 'a'){
drawer.erase_canvas(wireframes,disorientation);
wireframes.find(currentWireframe)->second.translate(-10, 0);
} else if (c == 's'){
drawer.erase_canvas(wireframes,disorientation);
wireframes.find(currentWireframe)->second.translate(0, 10);
} else if (c == 'd'){
drawer.erase_canvas(wireframes,disorientation);
wireframes.find(currentWireframe)->second.translate(10, 0);
} else if(c=='x'){
// Change settings
tcsetattr( fileno( stdin ), TCSANOW, &oldSettings );
break;
}
drawer.draw_canvas(wireframes,window,disorientation,true,useBatik);
drawer.draw_wireframe(horizontalScrollBarBorder);
drawer.draw_wireframe(verticalScrollBarBorder);
redrawScrollbars();
setupLegend();
drawer.draw_wireframe(window);
}
} else if (inputCommand == "rotate" && currentWireframe != ""){
tcsetattr( fileno( stdin ), TCSANOW, &newSettings );
cout << "Use 'p' rotate clockwise " << currentWireframe << " object" << endl;
cout << "Use 'o' rotate counter clockwise " << currentWireframe << " object" << endl;
cout << "Enter 'x' to finish" << endl;
while (1){
char c;
read( fileno( stdin ), &c, 1 );
if (c == 'o'){
drawer.erase_canvas(wireframes,disorientation);
wireframes.find(currentWireframe)->second.rotate(-10);
} else if (c == 'p'){
drawer.erase_canvas(wireframes,disorientation);
wireframes.find(currentWireframe)->second.rotate(10);
} else if(c=='x'){
// Change settings
tcsetattr( fileno( stdin ), TCSANOW, &oldSettings );
break;
}
drawer.draw_canvas(wireframes,window,disorientation,true,useBatik);
drawer.draw_wireframe(horizontalScrollBarBorder);
drawer.draw_wireframe(verticalScrollBarBorder);
redrawScrollbars();
setupLegend();
drawer.draw_wireframe(window);
}
} else if (inputCommand == "zoom") {
tcsetattr( fileno( stdin ), TCSANOW, &newSettings );
cout << "Use '=' to zoom in" << endl;
cout << "Use '-' to zoom out" << endl;
cout << "Enter 'x' to return" << endl;
while (1){
char c;
read( fileno( stdin ), &c, 1 );
if (c == '='){
zoom(1.15);
} else if (c == '-'){
zoom(0.75);
} else if(c=='x'){
// Change settings
tcsetattr( fileno( stdin ), TCSANOW, &oldSettings);
break;
}
drawer.draw_wireframe(horizontalScrollBarBorder);
drawer.draw_wireframe(verticalScrollBarBorder);
redrawScrollbars();
setupLegend();
}
} else if (inputCommand == "scale" && currentWireframe != "") {
tcsetattr( fileno( stdin ), TCSANOW, &newSettings );
cout << "Use '=' to scale up " << currentWireframe << " object" << endl;
cout << "Use '-' to scale down " << currentWireframe << " object" << endl;
cout << "Enter 'x' to finish" << endl;
while (1){
char c;
read( fileno( stdin ), &c, 1 );
if (c == '='){
drawer.erase_canvas(wireframes,disorientation);
wireframes.find(currentWireframe)->second.scale(1.15);
} else if (c == '-'){
drawer.erase_canvas(wireframes,disorientation);
wireframes.find(currentWireframe)->second.scale(0.75);
} else if(c=='x'){
// Change settings
tcsetattr( fileno( stdin ), TCSANOW, &oldSettings);
break;
}
drawer.draw_canvas(wireframes,window,disorientation,true,useBatik);
}
drawer.draw_wireframe(horizontalScrollBarBorder);
drawer.draw_wireframe(verticalScrollBarBorder);
redrawScrollbars();
setupLegend();
} else if (inputCommand == "fill" && currentWireframe != "") {
int red, green, blue;
cout << "fill color (r g b): ";
cin >> red >> green >> blue;
drawer.erase_canvas(wireframes,disorientation);
wireframes.find(currentWireframe)->second.setFillColor(Color(red, green, blue));
drawer.draw_canvas(wireframes,window,disorientation,true);
} else if (inputCommand == "unfill") {
drawer.erase_canvas(wireframes,disorientation);
wireframes.find(currentWireframe)->second.setFillColor(Color::background());
drawer.draw_canvas(wireframes,window,disorientation,true);
} else if (inputCommand == "create"){
int radius, nPoint, xCenter, yCenter, red, green, boy;
string nameShape;
cout << "shape's name: ";
cin >> nameShape;
cout << "center (x y): ";
cin >> xCenter >> yCenter;
cout << "radius: ";
cin >> radius;
cout << "number of point: ";
cin >> nPoint;
cout << "color (r g b): ";
cin >> red >> green >> boy;
for (auto & c: nameShape) c = toupper(c);
Wireframe wireframe(radius, nPoint, Point(xCenter, yCenter), Color(red, green, boy));
wireframes.insert(pair<string, Wireframe>(nameShape, wireframe));
drawer.draw_canvas(wireframes,window,disorientation,true,useBatik);
} else if (inputCommand == "triangle"){
int radius, xCenter, yCenter, red, green, boy;
string nameShape;
cout << "shape's name: ";
cin >> nameShape;
cout << "center (x y): ";
cin >> xCenter >> yCenter;
cout << "radius: ";
cin >> radius;
cout << "color (r g b): ";
cin >> red >> green >> boy;
for (auto & c: nameShape) c = toupper(c);
Wireframe wireframe(radius, 3, Point(xCenter, yCenter), Color(red, green, boy));
wireframes.insert(pair<string, Wireframe>(nameShape, wireframe));
drawer.draw_canvas(wireframes,window,disorientation,true,useBatik);
}else if (inputCommand == "rectangle"){
int radius, xCenter, yCenter, red, green, boy;
string nameShape;
cout << "shape's name: ";
cin >> nameShape;
cout << "center (x y): ";
cin >> xCenter >> yCenter;
cout << "radius: ";
cin >> radius;
cout << "color (r g b): ";
cin >> red >> green >> boy;
for (auto & c: nameShape) c = toupper(c);
Wireframe wireframe(radius, 4, Point(xCenter, yCenter), Color(red, green, boy));
wireframes.insert(pair<string, Wireframe>(nameShape, wireframe));
drawer.draw_canvas(wireframes,window,disorientation,true,useBatik);
}else if (inputCommand == "thickness" && currentWireframe != "") {
float thickness;
cout << "width: ";
cin >> thickness;
drawer.erase_canvas(wireframes,disorientation);
if(thickness >= 1.0f){
wireframes.find(currentWireframe)->second.setThickness(thickness);
};
drawer.draw_canvas(wireframes,window, disorientation, true, useBatik);
} else if (inputCommand == "line-style" && currentWireframe != "") {
char lineStyle;
cout << "dot/solid (d/s): ";
cin >> lineStyle;
drawer.erase_canvas(wireframes,disorientation);
if(lineStyle == 's' || lineStyle == 'd'){
wireframes.find(currentWireframe)->second.setLineStyle(lineStyle);
}
drawer.draw_canvas(wireframes,window, disorientation, true, useBatik);
} else if (inputCommand == "line-color" && currentWireframe != "") {
int red, green, blue;
cout << "color(r g b): ";
cin >> red >> green >> blue;
drawer.erase_canvas(wireframes,disorientation);
if(red >= 0 && red <=255 && green >= 0 && green <=255 && blue >= 0 && blue <=255){
wireframes.find(currentWireframe)->second.setBorderColor(Color(red, green, blue));
} else {
cout << "Wrong format" << endl;
}
drawer.draw_canvas(wireframes,window, disorientation, true, useBatik);
} else if (inputCommand == "show-label"){
for (auto itr = wireframes.begin(); itr != wireframes.end(); itr++) {
string name = itr->first;
Point loc = itr->second.getInnerPoint();
loc.translate(200, 0);
drawer.draw_word(name, loc, 25, 3, Color(0, 255, 0));
}
} else if (inputCommand == "hide-label"){
hideLabels();
} else if (inputCommand == "use-batik"){
useBatik = true;
drawer.erase_canvas(wireframes,disorientation);
drawer.draw_canvas(wireframes,window,disorientation,true,useBatik);
} else if (inputCommand == "off-batik"){
useBatik = false;
drawer.erase_canvas(wireframes,disorientation);
drawer.draw_canvas(wireframes,window,disorientation,true,useBatik);
}else if (inputCommand == "credits"){
credits();
setup();
drawer.draw_canvas(wireframes,window,disorientation,true,useBatik);
} else if (inputCommand == "delete" && currentWireframe != ""){
drawer.erase_canvas(wireframes,disorientation);
wireframes.erase(currentWireframe);
currentWireframe = "";
drawer.draw_canvas(wireframes,window,disorientation,true,useBatik);
} else if ("line" == inputCommand) {
int radius, xCenter, yCenter, red, green, boy;
string nameShape;
cout << "shape's name: ";
cin >> nameShape;
cout << "center (x y): ";
cin >> xCenter >> yCenter;
cout << "radius: ";
cin >> radius;
cout << "color (r g b): ";
cin >> red >> green >> boy;
for (auto & c: nameShape) c = toupper(c);
Wireframe wireframe(radius, 2, Point(xCenter, yCenter), Color(red, green, boy));
wireframes.insert(pair<string, Wireframe>(nameShape, wireframe));
}else{
cout << "Please enter a valid command" << endl;
}
}
tcsetattr( fileno( stdin ), TCSANOW, &oldSettings );
} | [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
] | [
[
[
1,
7
],
[
11,
13
],
[
16,
18
],
[
21,
21
],
[
25,
26
],
[
29,
29
],
[
38,
40
],
[
43,
43
],
[
47,
47
],
[
76,
92
],
[
95,
95
],
[
98,
101
],
[
103,
145
],
[
148,
148
],
[
161,
161
],
[
163,
163
],
[
166,
166
],
[
175,
176
],
[
178,
178
],
[
192,
192
],
[
199,
199
],
[
294,
295
],
[
306,
308
],
[
313,
314
],
[
324,
324
],
[
344,
344
],
[
347,
347
],
[
350,
350
],
[
352,
352
],
[
359,
360
],
[
378,
378
],
[
386,
386
],
[
391,
391
],
[
393,
393
],
[
556,
560
],
[
580,
580
],
[
598,
598
],
[
657,
657
],
[
678,
694
]
],
[
[
8,
10
],
[
383,
383
],
[
388,
388
],
[
440,
442
],
[
474,
474
],
[
522,
522
],
[
548,
552
],
[
554,
554
],
[
561,
574
],
[
577,
578
],
[
617,
621
],
[
623,
627
],
[
629,
637
],
[
639,
651
],
[
665,
665
],
[
673,
677
]
],
[
[
14,
15
],
[
19,
19
],
[
23,
24
],
[
27,
27
],
[
33,
33
],
[
37,
37
],
[
44,
46
],
[
48,
75
],
[
93,
94
],
[
96,
96
],
[
232,
232
],
[
289,
289
],
[
296,
301
],
[
304,
305
],
[
322,
322
],
[
329,
333
],
[
348,
349
],
[
353,
358
],
[
361,
373
],
[
376,
377
],
[
379,
380
],
[
384,
385
],
[
387,
387
],
[
389,
389
],
[
399,
405
],
[
408,
413
],
[
416,
422
],
[
424,
430
],
[
437,
438
],
[
450,
450
],
[
453,
453
],
[
456,
456
],
[
459,
459
],
[
466,
467
],
[
470,
471
],
[
483,
483
],
[
486,
486
],
[
493,
493
],
[
496,
498
],
[
517,
520
],
[
531,
531
],
[
534,
534
],
[
541,
541
],
[
543,
547
],
[
553,
553
],
[
555,
555
],
[
579,
579
],
[
581,
597
],
[
599,
616
],
[
622,
622
],
[
628,
628
],
[
638,
638
],
[
661,
664
],
[
666,
672
],
[
695,
695
],
[
697,
697
]
],
[
[
20,
20
],
[
28,
28
],
[
30,
32
],
[
34,
36
],
[
41,
42
],
[
97,
97
],
[
102,
102
],
[
146,
147
],
[
149,
160
],
[
162,
162
],
[
164,
165
],
[
167,
174
],
[
177,
177
],
[
179,
191
],
[
193,
198
],
[
200,
231
],
[
233,
288
],
[
290,
293
],
[
302,
303
],
[
309,
312
],
[
315,
321
],
[
323,
323
],
[
325,
328
],
[
334,
343
],
[
345,
346
],
[
351,
351
],
[
374,
375
],
[
381,
382
],
[
390,
390
],
[
392,
392
],
[
394,
398
],
[
406,
407
],
[
414,
415
],
[
423,
423
],
[
431,
436
],
[
439,
439
],
[
443,
449
],
[
451,
452
],
[
454,
455
],
[
457,
458
],
[
460,
465
],
[
468,
469
],
[
472,
473
],
[
475,
482
],
[
484,
485
],
[
487,
492
],
[
494,
495
],
[
499,
516
],
[
521,
521
],
[
523,
530
],
[
532,
533
],
[
535,
540
],
[
542,
542
],
[
575,
576
],
[
652,
652
],
[
654,
656
],
[
659,
660
],
[
696,
696
],
[
698,
700
]
],
[
[
22,
22
],
[
653,
653
],
[
658,
658
]
]
] |
be342d25f24c065b687f2354984709c3205a3034 | 03c9dcedb5c93f6930fbe274d188199df574e87c | /node_location/code/MultiviewGeometryUtility.cpp | bfe4419fde1892cae668b58fc56a44cb6e5a9d18 | [] | no_license | marvinCMU/marvin | 6b5f6af693746657650a66b78f899fadbb937071 | 6f6e378f78447d6b8de2e8b97b82e1bc7f3f5cfc | refs/heads/master | 2016-09-06T04:51:17.572255 | 2014-06-17T03:43:45 | 2014-06-17T03:43:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 345,280 | cpp | #include "MultiviewGeometryUtility.h"
#include <assert.h>
using namespace std;
//void BilinearCameraPoseEstimation(vector<Feature> vFeature, int initialFrame1, int initialFrame2, double ransacThreshold, int ransacMaxIter, CvMat *K, CvMat &P, CvMat &X, vector<int> &visibleStructureID)
//{
// PrintAlgorithm("Bilinear Camera Pose Estimation");
// CvMat cx1, cx2, nx1, nx2;
// vector<int> visibleFeatureID;
// X = *cvCreateMat(vFeature.size(), 3, CV_32FC1);
// VisibleIntersection(vFeature, initialFrame1, initialFrame2, cx1, cx2, visibleFeatureID);
// assert(visibleFeatureID.size() > 7);
// CvMat *F = cvCreateMat(3,3,CV_32FC1);
//
// Classifier classifier;
// vector<int> visibleID;
// classifier.SetRansacParam(ransacThreshold, ransacMaxIter);
// classifier.SetCorrespondance(&cx1, &cx2, visibleFeatureID);
// classifier.Classify();
// vector<int> vInlierID, vOutlierID;
// classifier.GetClassificationResultByFeatureID(vInlierID, vOutlierID);
// visibleFeatureID = vInlierID;
// F = cvCloneMat(classifier.F);
// cx1 = *cvCreateMat(classifier.inlier1->rows, classifier.inlier1->cols, CV_32FC1);
// cx2 = *cvCreateMat(classifier.inlier2->rows, classifier.inlier2->cols, CV_32FC1);
// cx1 = *cvCloneMat(classifier.inlier1);
// cx2 = *cvCloneMat(classifier.inlier2);
//
// //vector<int> vInlierID;
// //CvMat *status = cvCreateMat(1,cx1.rows,CV_8UC1);
// //int n = cvFindFundamentalMat(&cx1, &cx2, F, CV_FM_LMEDS , 1, 0.99, status);
// //for (int i = 0; i < cx1.rows; i++)
// //{
// // if (cvGetReal2D(status, 0, i) == 1)
// // {
// // vInlierID.push_back(visibleFeatureID[i]);
// // }
// //}
// //visibleFeatureID = vInlierID;
// //CvMat *tempCx1 = cvCreateMat(vInlierID.size(), 2, CV_32FC1);
// //CvMat *tempCx2 = cvCreateMat(vInlierID.size(), 2, CV_32FC1);
// //int temprow = 0;
// //for (int i = 0; i < cx1.rows; i++)
// //{
// // if (cvGetReal2D(status, 0, i) == 1)
// // {
// // cvSetReal2D(tempCx1, temprow, 0, cvGetReal2D(&cx1, i, 0));
// // cvSetReal2D(tempCx1, temprow, 1, cvGetReal2D(&cx1, i, 1));
// // cvSetReal2D(tempCx2, temprow, 0, cvGetReal2D(&cx2, i, 0));
// // cvSetReal2D(tempCx2, temprow, 1, cvGetReal2D(&cx2, i, 1));
// // temprow++;
// // }
// //}
// //cx1 = *cvCreateMat(tempCx1->rows, tempCx1->cols, CV_32FC1);
// //cx2 = *cvCreateMat(tempCx2->rows, tempCx2->cols, CV_32FC1);
// //cx1 = *cvCloneMat(tempCx1);
// //cx2 = *cvCloneMat(tempCx2);
// //cvReleaseMat(&status);
// //cvReleaseMat(&tempCx1);
// //cvReleaseMat(&tempCx2);
//
// CvMat *E = cvCreateMat(3, 3, CV_32FC1);
// CvMat *temp33 = cvCreateMat(3, 3, CV_32FC1);
// CvMat *temp34 = cvCreateMat(3, 4, CV_32FC1);
//
// cvTranspose(K, temp33);
// cvMatMul(temp33, F, temp33);
// cvMatMul(temp33, K, E);
//
// CvMat *invK = cvCreateMat(3,3,CV_32FC1);
// cvInvert(K, invK);
// Pxx_inhomo(invK, &cx1, nx1);
// Pxx_inhomo(invK, &cx2, nx2);
//
// GetExtrinsicParameterFromE(E, &nx1, &nx2, P);
// CvMat *P0 = cvCreateMat(3, 4, CV_32FC1);
// cvSetIdentity(P0);
// CvMat cX;
//
// LinearTriangulation(&nx1, P0, &nx2, &P, cX);
// cvSetZero(&X);
// SetIndexedMatRowwise(&X, visibleFeatureID, &cX);
// cvMatMul(K, &P, temp34);
// P = *cvCloneMat(temp34);
//
// visibleStructureID = visibleFeatureID;
//
// cvReleaseMat(&F);
// cvReleaseMat(&E);
// cvReleaseMat(&temp33);
// cvReleaseMat(&temp34);
// cvReleaseMat(&invK);
// cvReleaseMat(&P0);
//}
void BilinearCameraPoseEstimation_OPENCV(vector<Feature> vFeature, int initialFrame1, int initialFrame2, double ransacThreshold, int ransacMaxIter, CvMat *K, CvMat &P, CvMat &X, vector<int> &visibleStructureID)
{
PrintAlgorithm("Bilinear Camera Pose Estimation");
CvMat cx1, cx2, nx1, nx2;
vector<int> visibleFeatureID;
X = *cvCreateMat(vFeature.size(), 3, CV_32FC1);
VisibleIntersection(vFeature, initialFrame1, initialFrame2, cx1, cx2, visibleFeatureID);
assert(visibleFeatureID.size() > 7);
CvMat *F = cvCreateMat(3,3,CV_32FC1);
//Classifier classifier;
//vector<int> visibleID;
//classifier.SetRansacParam(ransacThreshold, ransacMaxIter);
//classifier.SetCorrespondance(&cx1, &cx2, visibleFeatureID);
//classifier.Classify();
//vector<int> vInlierID, vOutlierID;
//classifier.GetClassificationResultByFeatureID(vInlierID, vOutlierID);
//visibleFeatureID = vInlierID;
//F = cvCloneMat(classifier.F);
//cx1 = *cvCreateMat(classifier.inlier1->rows, classifier.inlier1->cols, CV_32FC1);
//cx2 = *cvCreateMat(classifier.inlier2->rows, classifier.inlier2->cols, CV_32FC1);
//cx1 = *cvCloneMat(classifier.inlier1);
//cx2 = *cvCloneMat(classifier.inlier2);
vector<int> vInlierID;
CvMat *status = cvCreateMat(1,cx1.rows,CV_8UC1);
int n = cvFindFundamentalMat(&cx1, &cx2, F, CV_FM_RANSAC , 1, 0.99, status);
for (int i = 0; i < cx1.rows; i++)
{
if (cvGetReal2D(status, 0, i) == 1)
{
vInlierID.push_back(visibleFeatureID[i]);
}
}
visibleFeatureID = vInlierID;
CvMat *tempCx1 = cvCreateMat(vInlierID.size(), 2, CV_32FC1);
CvMat *tempCx2 = cvCreateMat(vInlierID.size(), 2, CV_32FC1);
int temprow = 0;
for (int i = 0; i < cx1.rows; i++)
{
if (cvGetReal2D(status, 0, i) == 1)
{
cvSetReal2D(tempCx1, temprow, 0, cvGetReal2D(&cx1, i, 0));
cvSetReal2D(tempCx1, temprow, 1, cvGetReal2D(&cx1, i, 1));
cvSetReal2D(tempCx2, temprow, 0, cvGetReal2D(&cx2, i, 0));
cvSetReal2D(tempCx2, temprow, 1, cvGetReal2D(&cx2, i, 1));
temprow++;
}
}
cx1 = *cvCreateMat(tempCx1->rows, tempCx1->cols, CV_32FC1);
cx2 = *cvCreateMat(tempCx2->rows, tempCx2->cols, CV_32FC1);
cx1 = *cvCloneMat(tempCx1);
cx2 = *cvCloneMat(tempCx2);
cvReleaseMat(&status);
cvReleaseMat(&tempCx1);
cvReleaseMat(&tempCx2);
CvMat *E = cvCreateMat(3, 3, CV_32FC1);
CvMat *temp33 = cvCreateMat(3, 3, CV_32FC1);
CvMat *temp34 = cvCreateMat(3, 4, CV_32FC1);
cvTranspose(K, temp33);
cvMatMul(temp33, F, temp33);
cvMatMul(temp33, K, E);
CvMat *invK = cvCreateMat(3,3,CV_32FC1);
cvInvert(K, invK);
Pxx_inhomo(invK, &cx1, nx1);
Pxx_inhomo(invK, &cx2, nx2);
GetExtrinsicParameterFromE(E, &nx1, &nx2, P);
CvMat *P0 = cvCreateMat(3, 4, CV_32FC1);
cvSetIdentity(P0);
CvMat cX;
LinearTriangulation(&nx1, P0, &nx2, &P, cX);
cvSetZero(&X);
SetIndexedMatRowwise(&X, visibleFeatureID, &cX);
cvMatMul(K, &P, temp34);
P = *cvCloneMat(temp34);
visibleStructureID = visibleFeatureID;
cvReleaseMat(&F);
cvReleaseMat(&E);
cvReleaseMat(&temp33);
cvReleaseMat(&temp34);
cvReleaseMat(&invK);
cvReleaseMat(&P0);
}
int BilinearCameraPoseEstimation_OPENCV(vector<Feature> vFeature, int initialFrame1, int initialFrame2, int max_nFrames, vector<Camera> vCamera, CvMat &P, CvMat &X, vector<int> &visibleStructureID)
{
PrintAlgorithm("Bilinear Camera Pose Estimation");
CvMat cx1, cx2, nx1, nx2;
vector<int> visibleFeatureID;
X = *cvCreateMat(vFeature.size(), 3, CV_32FC1);
VisibleIntersection(vFeature, initialFrame1, initialFrame2, cx1, cx2, visibleFeatureID);
assert(visibleFeatureID.size() > 7);
CvMat *F = cvCreateMat(3,3,CV_32FC1);
vector<int> vInlierID;
CvMat *status = cvCreateMat(1,cx1.rows,CV_8UC1);
int n = cvFindFundamentalMat(&cx1, &cx2, F, CV_FM_LMEDS , 1, 0.99, status);
//int n = cvFindFundamentalMat(&cx1, &cx2, F, CV_FM_8POINT , 3, 0.99, status);
PrintMat(F, "Fundamental Matrix");
for (int i = 0; i < cx1.rows; i++)
{
if (cvGetReal2D(status, 0, i) == 1)
{
vInlierID.push_back(visibleFeatureID[i]);
}
}
visibleFeatureID = vInlierID;
CvMat *tempCx1 = cvCreateMat(vInlierID.size(), 2, CV_32FC1);
CvMat *tempCx2 = cvCreateMat(vInlierID.size(), 2, CV_32FC1);
int temprow = 0;
for (int i = 0; i < cx1.rows; i++)
{
if (cvGetReal2D(status, 0, i) == 1)
{
cvSetReal2D(tempCx1, temprow, 0, cvGetReal2D(&cx1, i, 0));
cvSetReal2D(tempCx1, temprow, 1, cvGetReal2D(&cx1, i, 1));
cvSetReal2D(tempCx2, temprow, 0, cvGetReal2D(&cx2, i, 0));
cvSetReal2D(tempCx2, temprow, 1, cvGetReal2D(&cx2, i, 1));
temprow++;
}
}
cx1 = *cvCreateMat(tempCx1->rows, tempCx1->cols, CV_32FC1);
cx2 = *cvCreateMat(tempCx2->rows, tempCx2->cols, CV_32FC1);
cx1 = *cvCloneMat(tempCx1);
cx2 = *cvCloneMat(tempCx2);
cvReleaseMat(&status);
cvReleaseMat(&tempCx1);
cvReleaseMat(&tempCx2);
CvMat *E = cvCreateMat(3, 3, CV_32FC1);
CvMat *temp33 = cvCreateMat(3, 3, CV_32FC1);
CvMat *temp34 = cvCreateMat(3, 4, CV_32FC1);
CvMat *K1 = cvCreateMat(3,3,CV_32FC1);
CvMat *K2 = cvCreateMat(3,3,CV_32FC1);
int camera1 = (int)((double)initialFrame1/max_nFrames);
int camera2 = (int)((double)initialFrame2/max_nFrames);
vector<int> ::const_iterator it1 = find(vCamera[camera1].vTakenFrame.begin(), vCamera[camera1].vTakenFrame.end(), initialFrame1%max_nFrames);
vector<int> ::const_iterator it2 = find(vCamera[camera2].vTakenFrame.begin(), vCamera[camera2].vTakenFrame.end(), initialFrame2%max_nFrames);
int idx1 = (int) (it1 - vCamera[camera1].vTakenFrame.begin());
int idx2 = (int) (it2 - vCamera[camera2].vTakenFrame.begin());
K1 = cvCloneMat(vCamera[camera1].vK[idx1]);
K2 = cvCloneMat(vCamera[camera2].vK[idx2]);
cvTranspose(K2, temp33);
cvMatMul(temp33, F, temp33);
cvMatMul(temp33, K1, E);
CvMat *invK1 = cvCreateMat(3,3,CV_32FC1);
CvMat *invK2 = cvCreateMat(3,3,CV_32FC1);
cvInvert(K1, invK1);
cvInvert(K2, invK2);
Pxx_inhomo(invK1, &cx1, nx1);
Pxx_inhomo(invK2, &cx2, nx2);
GetExtrinsicParameterFromE(E, &nx1, &nx2, P);
CvMat *P0 = cvCreateMat(3, 4, CV_32FC1);
cvSetIdentity(P0);
CvMat cX;
LinearTriangulation(&nx1, P0, &nx2, &P, cX);
cvSetZero(&X);
SetIndexedMatRowwise(&X, visibleFeatureID, &cX);
cvMatMul(K2, &P, temp34);
P = *cvCloneMat(temp34);
visibleStructureID = visibleFeatureID;
cvReleaseMat(&F);
cvReleaseMat(&E);
cvReleaseMat(&temp33);
cvReleaseMat(&temp34);
cvReleaseMat(&K1);
cvReleaseMat(&K2);
cvReleaseMat(&invK1);
cvReleaseMat(&invK2);
cvReleaseMat(&P0);
return n;
}
void SetCvMatFromVectors(vector<vector<double> > x, CvMat *X)
{
for (int i = 0; i < x.size(); i++)
{
for (int j = 0; j < x[i].size(); j++)
cvSetReal2D(X, i, j, x[i][j]);
}
}
int BilinearCameraPoseEstimation_OPENCV_mem(vector<Feature> &vFeature, int initialFrame1, int initialFrame2, int max_nFrames, vector<Camera> vCamera, CvMat *P, CvMat *X, vector<int> &visibleStructureID)
{
PrintAlgorithm("Bilinear Camera Pose Estimation");
vector<int> visibleFeatureID;
vector<vector<double> > cx1_vec, cx2_vec, nx1_vec, nx2_vec;
VisibleIntersection_mem(vFeature, initialFrame1, initialFrame2, cx1_vec, cx2_vec, visibleFeatureID);
CvMat *cx1 = cvCreateMat(cx1_vec.size(), 2, CV_32FC1);
CvMat *cx2 = cvCreateMat(cx2_vec.size(), 2, CV_32FC1);
SetCvMatFromVectors(cx1_vec, cx1);
SetCvMatFromVectors(cx2_vec, cx2);
assert(visibleFeatureID.size() > 7);
CvMat *F = cvCreateMat(3,3,CV_32FC1);
vector<int> vInlierID;
CvMat *status = cvCreateMat(1,cx1->rows,CV_8UC1);
int n = cvFindFundamentalMat(cx1, cx2, F, CV_FM_LMEDS , 1, 0.99, status);
PrintMat(F, "Fundamental Matrix");
for (int i = 0; i < cx1->rows; i++)
{
if (cvGetReal2D(status, 0, i) == 1)
{
vInlierID.push_back(visibleFeatureID[i]);
}
}
visibleFeatureID = vInlierID;
CvMat *tempCx1 = cvCreateMat(vInlierID.size(), 2, CV_32FC1);
CvMat *tempCx2 = cvCreateMat(vInlierID.size(), 2, CV_32FC1);
int temprow = 0;
for (int i = 0; i < cx1->rows; i++)
{
if (cvGetReal2D(status, 0, i) == 1)
{
cvSetReal2D(tempCx1, temprow, 0, cvGetReal2D(cx1, i, 0));
cvSetReal2D(tempCx1, temprow, 1, cvGetReal2D(cx1, i, 1));
cvSetReal2D(tempCx2, temprow, 0, cvGetReal2D(cx2, i, 0));
cvSetReal2D(tempCx2, temprow, 1, cvGetReal2D(cx2, i, 1));
temprow++;
}
}
cvReleaseMat(&cx1);
cvReleaseMat(&cx2);
cx1 = cvCloneMat(tempCx1);
cx2 = cvCloneMat(tempCx2);
cvReleaseMat(&status);
cvReleaseMat(&tempCx1);
cvReleaseMat(&tempCx2);
CvMat *E = cvCreateMat(3, 3, CV_32FC1);
CvMat *temp33 = cvCreateMat(3, 3, CV_32FC1);
CvMat *temp34 = cvCreateMat(3, 4, CV_32FC1);
//CvMat *K1 = cvCreateMat(3,3,CV_32FC1);
//CvMat *K2 = cvCreateMat(3,3,CV_32FC1);
int camera1 = (int)((double)initialFrame1/max_nFrames);
int camera2 = (int)((double)initialFrame2/max_nFrames);
vector<int> ::const_iterator it1 = find(vCamera[camera1].vTakenFrame.begin(), vCamera[camera1].vTakenFrame.end(), initialFrame1%max_nFrames);
vector<int> ::const_iterator it2 = find(vCamera[camera2].vTakenFrame.begin(), vCamera[camera2].vTakenFrame.end(), initialFrame2%max_nFrames);
int idx1 = (int) (it1 - vCamera[camera1].vTakenFrame.begin());
int idx2 = (int) (it2 - vCamera[camera2].vTakenFrame.begin());
CvMat *K1 = cvCloneMat(vCamera[camera1].vK[idx1]);
CvMat *K2 = cvCloneMat(vCamera[camera2].vK[idx2]);
cvTranspose(K2, temp33);
cvMatMul(temp33, F, temp33);
cvMatMul(temp33, K1, E);
CvMat *invK1 = cvCreateMat(3,3,CV_32FC1);
CvMat *invK2 = cvCreateMat(3,3,CV_32FC1);
cvInvert(K1, invK1);
cvInvert(K2, invK2);
CvMat *nx1 = cvCreateMat(cx1->rows, cx1->cols, CV_32FC1);
CvMat *nx2 = cvCreateMat(cx2->rows, cx2->cols, CV_32FC1);
Pxx_inhomo(invK1, cx1, nx1);
Pxx_inhomo(invK2, cx2, nx2);
GetExtrinsicParameterFromE(E, nx1, nx2, P);
CvMat *P0 = cvCreateMat(3, 4, CV_32FC1);
cvSetIdentity(P0);
CvMat *cX = cvCreateMat(nx1->rows, 3, CV_32FC1);
LinearTriangulation(nx1, P0, nx2, P, cX);
cvSetZero(X);
SetIndexedMatRowwise(X, visibleFeatureID, cX);
cvMatMul(K2, P, temp34);
SetSubMat(P, 0, 0, temp34);
visibleStructureID = visibleFeatureID;
cvReleaseMat(&F);
cvReleaseMat(&E);
cvReleaseMat(&temp33);
cvReleaseMat(&temp34);
cvReleaseMat(&K1);
cvReleaseMat(&K2);
cvReleaseMat(&invK1);
cvReleaseMat(&invK2);
cvReleaseMat(&P0);
cvReleaseMat(&cx1);
cvReleaseMat(&cx2);
cvReleaseMat(&nx1);
cvReleaseMat(&nx2);
cvReleaseMat(&cX);
return n;
}
int BilinearCameraPoseEstimation_OPENCV_mem_fast(vector<Feature> &vFeature, int initialFrame1, int initialFrame2, int max_nFrames, vector<Camera> vCamera, CvMat *P, CvMat *X)
{
PrintAlgorithm("Bilinear Camera Pose Estimation");
vector<int> visibleFeatureID;
vector<vector<double> > cx1_vec, cx2_vec, nx1_vec, nx2_vec;
VisibleIntersection_mem(vFeature, initialFrame1, initialFrame2, cx1_vec, cx2_vec, visibleFeatureID);
CvMat *cx1 = cvCreateMat(cx1_vec.size(), 2, CV_32FC1);
CvMat *cx2 = cvCreateMat(cx2_vec.size(), 2, CV_32FC1);
SetCvMatFromVectors(cx1_vec, cx1);
SetCvMatFromVectors(cx2_vec, cx2);
assert(visibleFeatureID.size() > 7);
CvMat *F = cvCreateMat(3,3,CV_32FC1);
vector<int> vInlierID;
CvMat *status = cvCreateMat(1,cx1->rows,CV_8UC1);
int n = cvFindFundamentalMat(cx1, cx2, F, CV_FM_LMEDS , 1, 0.99, status);
PrintMat(F, "Fundamental Matrix");
//for (int i = 0; i < cx1->rows; i++)
//{
// if (cvGetReal2D(status, 0, i) == 1)
// {
// vInlierID.push_back(visibleFeatureID[i]);
// }
//}
cout << n << endl;
vector<int> vCX_indx;
for (int i = 0; i < cx1->rows; i++)
{
CvMat *xM2 = cvCreateMat(1,3,CV_32FC1);
CvMat *xM1 = cvCreateMat(3,1,CV_32FC1);
CvMat *s = cvCreateMat(1,1, CV_32FC1);
cvSetReal2D(xM2, 0, 0, cvGetReal2D(cx2, i, 0));
cvSetReal2D(xM2, 0, 1, cvGetReal2D(cx2, i, 1));
cvSetReal2D(xM2, 0, 2, 1);
cvSetReal2D(xM1, 0, 0, cvGetReal2D(cx1, i, 0));
cvSetReal2D(xM1, 1, 0, cvGetReal2D(cx1, i, 1));
cvSetReal2D(xM1, 2, 0, 1);
cvMatMul(xM2, F, xM2);
cvMatMul(xM2, xM1, s);
double l1 = cvGetReal2D(xM2, 0, 0);
double l2 = cvGetReal2D(xM2, 0, 1);
double l3 = cvGetReal2D(xM2, 0, 2);
double dist = abs(cvGetReal2D(s, 0, 0))/sqrt(l1*l1+l2*l2);
if (dist < 5)
{
vInlierID.push_back(visibleFeatureID[i]);
vCX_indx.push_back(i);
}
cvReleaseMat(&xM2);
cvReleaseMat(&xM1);
cvReleaseMat(&s);
//if (cvGetReal2D(status, 0, i) == 1)
//{
// cvSetReal2D(tempCx1, temprow, 0, cvGetReal2D(cx1, i, 0));
// cvSetReal2D(tempCx1, temprow, 1, cvGetReal2D(cx1, i, 1));
// cvSetReal2D(tempCx2, temprow, 0, cvGetReal2D(cx2, i, 0));
// cvSetReal2D(tempCx2, temprow, 1, cvGetReal2D(cx2, i, 1));
// temprow++;
//}
}
visibleFeatureID = vInlierID;
CvMat *tempCx1 = cvCreateMat(vCX_indx.size(), 2, CV_32FC1);
CvMat *tempCx2 = cvCreateMat(vCX_indx.size(), 2, CV_32FC1);
for (int iInlier = 0; iInlier < vInlierID.size(); iInlier++)
{
cvSetReal2D(tempCx1, iInlier, 0, cvGetReal2D(cx1, vCX_indx[iInlier], 0));
cvSetReal2D(tempCx1, iInlier, 1, cvGetReal2D(cx1, vCX_indx[iInlier], 1));
cvSetReal2D(tempCx2, iInlier, 0, cvGetReal2D(cx2, vCX_indx[iInlier], 0));
cvSetReal2D(tempCx2, iInlier, 1, cvGetReal2D(cx2, vCX_indx[iInlier], 1));
}
cvReleaseMat(&cx1);
cvReleaseMat(&cx2);
cx1 = cvCloneMat(tempCx1);
cx2 = cvCloneMat(tempCx2);
cvReleaseMat(&status);
cvReleaseMat(&tempCx1);
cvReleaseMat(&tempCx2);
CvMat *E = cvCreateMat(3, 3, CV_32FC1);
CvMat *temp33 = cvCreateMat(3, 3, CV_32FC1);
CvMat *temp34 = cvCreateMat(3, 4, CV_32FC1);
//CvMat *K1 = cvCreateMat(3,3,CV_32FC1);
//CvMat *K2 = cvCreateMat(3,3,CV_32FC1);
int camera1 = (int)((double)initialFrame1/max_nFrames);
int camera2 = (int)((double)initialFrame2/max_nFrames);
vector<int> ::const_iterator it1 = find(vCamera[camera1].vTakenFrame.begin(), vCamera[camera1].vTakenFrame.end(), initialFrame1%max_nFrames);
vector<int> ::const_iterator it2 = find(vCamera[camera2].vTakenFrame.begin(), vCamera[camera2].vTakenFrame.end(), initialFrame2%max_nFrames);
int idx1 = (int) (it1 - vCamera[camera1].vTakenFrame.begin());
int idx2 = (int) (it2 - vCamera[camera2].vTakenFrame.begin());
CvMat *K1 = cvCloneMat(vCamera[camera1].vK[idx1]);
CvMat *K2 = cvCloneMat(vCamera[camera2].vK[idx2]);
cvTranspose(K2, temp33);
cvMatMul(temp33, F, temp33);
cvMatMul(temp33, K1, E);
CvMat *invK1 = cvCreateMat(3,3,CV_32FC1);
CvMat *invK2 = cvCreateMat(3,3,CV_32FC1);
cvInvert(K1, invK1);
cvInvert(K2, invK2);
CvMat *nx1 = cvCreateMat(cx1->rows, cx1->cols, CV_32FC1);
CvMat *nx2 = cvCreateMat(cx2->rows, cx2->cols, CV_32FC1);
Pxx_inhomo(invK1, cx1, nx1);
Pxx_inhomo(invK2, cx2, nx2);
GetExtrinsicParameterFromE(E, nx1, nx2, P);
CvMat *P0 = cvCreateMat(3, 4, CV_32FC1);
cvSetIdentity(P0);
CvMat *cX = cvCreateMat(nx1->rows, 3, CV_32FC1);
PrintMat(P);
cvMatMul(K1, P0, P0);
cvMatMul(K2, P, P);
PrintMat(P);
//LinearTriangulation(nx1, P0, nx2, P, cX);
LinearTriangulation(cx1, P0, cx2, P, cX);
//PrintMat(cX);
cvSetZero(X);
SetIndexedMatRowwise(X, visibleFeatureID, cX);
for (int i = 0; i < visibleFeatureID.size(); i++)
{
vFeature[visibleFeatureID[i]].isRegistered = true;
}
cvReleaseMat(&F);
cvReleaseMat(&E);
cvReleaseMat(&temp33);
cvReleaseMat(&temp34);
cvReleaseMat(&K1);
cvReleaseMat(&K2);
cvReleaseMat(&invK1);
cvReleaseMat(&invK2);
cvReleaseMat(&P0);
cvReleaseMat(&cx1);
cvReleaseMat(&cx2);
cvReleaseMat(&nx1);
cvReleaseMat(&nx2);
cvReleaseMat(&cX);
return vInlierID.size();
}
int BilinearCameraPoseEstimation_OPENCV_mem_fast_AD(vector<Feature> &vFeature, int initialFrame1, int initialFrame2, int max_nFrames, vector<Camera> vCamera, CvMat *P, CvMat *X, vector<vector<int> > &vvPointIndex)
{
PrintAlgorithm("Bilinear Camera Pose Estimation");
vector<int> visibleFeatureID;
vector<vector<double> > cx1_vec, cx2_vec, nx1_vec, nx2_vec;
VisibleIntersection_mem(vFeature, initialFrame1, initialFrame2, cx1_vec, cx2_vec, visibleFeatureID);
CvMat *cx1 = cvCreateMat(cx1_vec.size(), 2, CV_32FC1);
CvMat *cx2 = cvCreateMat(cx2_vec.size(), 2, CV_32FC1);
SetCvMatFromVectors(cx1_vec, cx1);
SetCvMatFromVectors(cx2_vec, cx2);
assert(visibleFeatureID.size() > 7);
CvMat *F = cvCreateMat(3,3,CV_32FC1);
vector<int> vInlierID;
CvMat *status = cvCreateMat(1,cx1->rows,CV_8UC1);
int n = cvFindFundamentalMat(cx1, cx2, F, CV_FM_LMEDS , 1, 0.99, status);
PrintMat(F, "Fundamental Matrix");
//for (int i = 0; i < cx1->rows; i++)
//{
// if (cvGetReal2D(status, 0, i) == 1)
// {
// vInlierID.push_back(visibleFeatureID[i]);
// }
//}
cout << n << endl;
vector<int> vCX_indx;
for (int i = 0; i < cx1->rows; i++)
{
CvMat *xM2 = cvCreateMat(1,3,CV_32FC1);
CvMat *xM1 = cvCreateMat(3,1,CV_32FC1);
CvMat *s = cvCreateMat(1,1, CV_32FC1);
cvSetReal2D(xM2, 0, 0, cvGetReal2D(cx2, i, 0));
cvSetReal2D(xM2, 0, 1, cvGetReal2D(cx2, i, 1));
cvSetReal2D(xM2, 0, 2, 1);
cvSetReal2D(xM1, 0, 0, cvGetReal2D(cx1, i, 0));
cvSetReal2D(xM1, 1, 0, cvGetReal2D(cx1, i, 1));
cvSetReal2D(xM1, 2, 0, 1);
cvMatMul(xM2, F, xM2);
cvMatMul(xM2, xM1, s);
double l1 = cvGetReal2D(xM2, 0, 0);
double l2 = cvGetReal2D(xM2, 0, 1);
double l3 = cvGetReal2D(xM2, 0, 2);
double dist = abs(cvGetReal2D(s, 0, 0))/sqrt(l1*l1+l2*l2);
if (dist < 5)
{
vInlierID.push_back(visibleFeatureID[i]);
vCX_indx.push_back(i);
}
cvReleaseMat(&xM2);
cvReleaseMat(&xM1);
cvReleaseMat(&s);
//if (cvGetReal2D(status, 0, i) == 1)
//{
// cvSetReal2D(tempCx1, temprow, 0, cvGetReal2D(cx1, i, 0));
// cvSetReal2D(tempCx1, temprow, 1, cvGetReal2D(cx1, i, 1));
// cvSetReal2D(tempCx2, temprow, 0, cvGetReal2D(cx2, i, 0));
// cvSetReal2D(tempCx2, temprow, 1, cvGetReal2D(cx2, i, 1));
// temprow++;
//}
}
visibleFeatureID = vInlierID;
CvMat *tempCx1 = cvCreateMat(vCX_indx.size(), 2, CV_32FC1);
CvMat *tempCx2 = cvCreateMat(vCX_indx.size(), 2, CV_32FC1);
for (int iInlier = 0; iInlier < vInlierID.size(); iInlier++)
{
cvSetReal2D(tempCx1, iInlier, 0, cvGetReal2D(cx1, vCX_indx[iInlier], 0));
cvSetReal2D(tempCx1, iInlier, 1, cvGetReal2D(cx1, vCX_indx[iInlier], 1));
cvSetReal2D(tempCx2, iInlier, 0, cvGetReal2D(cx2, vCX_indx[iInlier], 0));
cvSetReal2D(tempCx2, iInlier, 1, cvGetReal2D(cx2, vCX_indx[iInlier], 1));
}
cvReleaseMat(&cx1);
cvReleaseMat(&cx2);
cx1 = cvCloneMat(tempCx1);
cx2 = cvCloneMat(tempCx2);
cvReleaseMat(&status);
cvReleaseMat(&tempCx1);
cvReleaseMat(&tempCx2);
CvMat *E = cvCreateMat(3, 3, CV_32FC1);
CvMat *temp33 = cvCreateMat(3, 3, CV_32FC1);
CvMat *temp34 = cvCreateMat(3, 4, CV_32FC1);
//CvMat *K1 = cvCreateMat(3,3,CV_32FC1);
//CvMat *K2 = cvCreateMat(3,3,CV_32FC1);
int camera1 = (int)((double)initialFrame1/max_nFrames);
int camera2 = (int)((double)initialFrame2/max_nFrames);
vector<int> ::const_iterator it1 = find(vCamera[camera1].vTakenFrame.begin(), vCamera[camera1].vTakenFrame.end(), initialFrame1%max_nFrames);
vector<int> ::const_iterator it2 = find(vCamera[camera2].vTakenFrame.begin(), vCamera[camera2].vTakenFrame.end(), initialFrame2%max_nFrames);
int idx1 = (int) (it1 - vCamera[camera1].vTakenFrame.begin());
int idx2 = (int) (it2 - vCamera[camera2].vTakenFrame.begin());
CvMat *K1 = cvCloneMat(vCamera[camera1].vK[idx1]);
CvMat *K2 = cvCloneMat(vCamera[camera2].vK[idx2]);
cvTranspose(K2, temp33);
cvMatMul(temp33, F, temp33);
cvMatMul(temp33, K1, E);
CvMat *invK1 = cvCreateMat(3,3,CV_32FC1);
CvMat *invK2 = cvCreateMat(3,3,CV_32FC1);
cvInvert(K1, invK1);
cvInvert(K2, invK2);
CvMat *nx1 = cvCreateMat(cx1->rows, cx1->cols, CV_32FC1);
CvMat *nx2 = cvCreateMat(cx2->rows, cx2->cols, CV_32FC1);
Pxx_inhomo(invK1, cx1, nx1);
Pxx_inhomo(invK2, cx2, nx2);
GetExtrinsicParameterFromE(E, nx1, nx2, P);
CvMat *P0 = cvCreateMat(3, 4, CV_32FC1);
cvSetIdentity(P0);
CvMat *cX = cvCreateMat(nx1->rows, 3, CV_32FC1);
PrintMat(P);
cvMatMul(K1, P0, P0);
cvMatMul(K2, P, P);
PrintMat(P);
//LinearTriangulation(nx1, P0, nx2, P, cX);
LinearTriangulation(cx1, P0, cx2, P, cX);
//PrintMat(cX);
cvSetZero(X);
SetIndexedMatRowwise(X, visibleFeatureID, cX);
vvPointIndex.push_back(visibleFeatureID);
vvPointIndex.push_back(visibleFeatureID);
for (int i = 0; i < visibleFeatureID.size(); i++)
{
vFeature[visibleFeatureID[i]].isRegistered = true;
}
cvReleaseMat(&F);
cvReleaseMat(&E);
cvReleaseMat(&temp33);
cvReleaseMat(&temp34);
cvReleaseMat(&K1);
cvReleaseMat(&K2);
cvReleaseMat(&invK1);
cvReleaseMat(&invK2);
cvReleaseMat(&P0);
cvReleaseMat(&cx1);
cvReleaseMat(&cx2);
cvReleaseMat(&nx1);
cvReleaseMat(&nx2);
cvReleaseMat(&cX);
return vInlierID.size();
}
int BilinearCameraPoseEstimation_OPENCV_OrientationRefinement(vector<Feature> &vFeature, int initialFrame1, int initialFrame2, int max_nFrames,
vector<Camera> vCamera, CvMat *M, CvMat *m, vector<int> &vVisibleID)
{
//PrintAlgorithm("Bilinear Camera Pose Estimation");
vector<int> visibleFeatureID;
vector<vector<double> > cx1_vec, cx2_vec, nx1_vec, nx2_vec;
VisibleIntersection_mem(vFeature, initialFrame1, initialFrame2, cx1_vec, cx2_vec, visibleFeatureID);
if (visibleFeatureID.size() < 40)
return 0;
CvMat *cx1 = cvCreateMat(cx1_vec.size(), 2, CV_32FC1);
CvMat *cx2 = cvCreateMat(cx2_vec.size(), 2, CV_32FC1);
SetCvMatFromVectors(cx1_vec, cx1);
SetCvMatFromVectors(cx2_vec, cx2);
if (visibleFeatureID.size() < 8)
{
return visibleFeatureID.size();
}
CvMat *F = cvCreateMat(3,3,CV_32FC1);
vector<int> vInlierID;
CvMat *status = cvCreateMat(1,cx1->rows,CV_8UC1);
int n = cvFindFundamentalMat(cx1, cx2, F, CV_FM_LMEDS , 1, 0.99, status);
//cout << n << endl;
vector<int> vCX_indx;
for (int i = 0; i < cx1->rows; i++)
{
CvMat *xM2 = cvCreateMat(1,3,CV_32FC1);
CvMat *xM1 = cvCreateMat(3,1,CV_32FC1);
CvMat *s = cvCreateMat(1,1, CV_32FC1);
cvSetReal2D(xM2, 0, 0, cvGetReal2D(cx2, i, 0));
cvSetReal2D(xM2, 0, 1, cvGetReal2D(cx2, i, 1));
cvSetReal2D(xM2, 0, 2, 1);
cvSetReal2D(xM1, 0, 0, cvGetReal2D(cx1, i, 0));
cvSetReal2D(xM1, 1, 0, cvGetReal2D(cx1, i, 1));
cvSetReal2D(xM1, 2, 0, 1);
cvMatMul(xM2, F, xM2);
cvMatMul(xM2, xM1, s);
double l1 = cvGetReal2D(xM2, 0, 0);
double l2 = cvGetReal2D(xM2, 0, 1);
double l3 = cvGetReal2D(xM2, 0, 2);
double dist = abs(cvGetReal2D(s, 0, 0))/sqrt(l1*l1+l2*l2);
if (dist < 5)
{
vInlierID.push_back(visibleFeatureID[i]);
vCX_indx.push_back(i);
}
cvReleaseMat(&xM2);
cvReleaseMat(&xM1);
cvReleaseMat(&s);
}
visibleFeatureID = vInlierID;
CvMat *tempCx1 = cvCreateMat(vCX_indx.size(), 2, CV_32FC1);
CvMat *tempCx2 = cvCreateMat(vCX_indx.size(), 2, CV_32FC1);
for (int iInlier = 0; iInlier < vInlierID.size(); iInlier++)
{
cvSetReal2D(tempCx1, iInlier, 0, cvGetReal2D(cx1, vCX_indx[iInlier], 0));
cvSetReal2D(tempCx1, iInlier, 1, cvGetReal2D(cx1, vCX_indx[iInlier], 1));
cvSetReal2D(tempCx2, iInlier, 0, cvGetReal2D(cx2, vCX_indx[iInlier], 0));
cvSetReal2D(tempCx2, iInlier, 1, cvGetReal2D(cx2, vCX_indx[iInlier], 1));
}
cvReleaseMat(&cx1);
cvReleaseMat(&cx2);
cx1 = cvCloneMat(tempCx1);
cx2 = cvCloneMat(tempCx2);
cvReleaseMat(&status);
cvReleaseMat(&tempCx1);
cvReleaseMat(&tempCx2);
CvMat *E = cvCreateMat(3, 3, CV_32FC1);
CvMat *temp33 = cvCreateMat(3, 3, CV_32FC1);
CvMat *temp34 = cvCreateMat(3, 4, CV_32FC1);
//CvMat *K1 = cvCreateMat(3,3,CV_32FC1);
//CvMat *K2 = cvCreateMat(3,3,CV_32FC1);
int camera1 = (int)((double)initialFrame1/max_nFrames);
int camera2 = (int)((double)initialFrame2/max_nFrames);
vector<int> ::const_iterator it1 = find(vCamera[camera1].vTakenFrame.begin(), vCamera[camera1].vTakenFrame.end(), initialFrame1%max_nFrames);
vector<int> ::const_iterator it2 = find(vCamera[camera2].vTakenFrame.begin(), vCamera[camera2].vTakenFrame.end(), initialFrame2%max_nFrames);
int idx1 = (int) (it1 - vCamera[camera1].vTakenFrame.begin());
int idx2 = (int) (it2 - vCamera[camera2].vTakenFrame.begin());
CvMat *K1 = cvCloneMat(vCamera[camera1].vK[idx1]);
CvMat *K2 = cvCloneMat(vCamera[camera2].vK[idx2]);
cvTranspose(K2, temp33);
cvMatMul(temp33, F, temp33);
cvMatMul(temp33, K1, E);
CvMat *invK1 = cvCreateMat(3,3,CV_32FC1);
CvMat *invK2 = cvCreateMat(3,3,CV_32FC1);
cvInvert(K1, invK1);
cvInvert(K2, invK2);
CvMat *nx1 = cvCreateMat(cx1->rows, cx1->cols, CV_32FC1);
CvMat *nx2 = cvCreateMat(cx2->rows, cx2->cols, CV_32FC1);
Pxx_inhomo(invK1, cx1, nx1);
Pxx_inhomo(invK2, cx2, nx2);
CvMat *P = cvCreateMat(3,4,CV_32FC1);
GetExtrinsicParameterFromE(E, nx1, nx2, P);
CvMat *P0 = cvCreateMat(3, 4, CV_32FC1);
cvSetIdentity(P0);
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
cvSetReal2D(M, i, j, cvGetReal2D(P, i, j));
}
}
for (int i = 0; i < 3; i++)
{
cvSetReal2D(m, i, 0, cvGetReal2D(P, i, 3));
}
cvReleaseMat(&F);
cvReleaseMat(&E);
cvReleaseMat(&temp33);
cvReleaseMat(&temp34);
cvReleaseMat(&K1);
cvReleaseMat(&K2);
cvReleaseMat(&invK1);
cvReleaseMat(&invK2);
cvReleaseMat(&P0);
cvReleaseMat(&cx1);
cvReleaseMat(&cx2);
cvReleaseMat(&nx1);
cvReleaseMat(&nx2);
cvReleaseMat(&P);
vVisibleID = vInlierID;
return vInlierID.size();
}
void BilinearCameraPoseEstimation(vector<Feature> vFeature, int initialFrame1, int initialFrame2, double ransacThreshold, int ransacMaxIter, int max_nFrames, vector<Camera> vCamera, CvMat &P, CvMat &X, vector<int> &visibleStructureID)
{
PrintAlgorithm("Bilinear Camera Pose Estimation");
CvMat cx1, cx2, nx1, nx2;
vector<int> visibleFeatureID;
X = *cvCreateMat(vFeature.size(), 3, CV_32FC1);
VisibleIntersection(vFeature, initialFrame1, initialFrame2, cx1, cx2, visibleFeatureID);
cout << "Visible intersection between 2 and 3: " << visibleFeatureID.size() << endl;
assert(visibleFeatureID.size() > 7);
CvMat *F = cvCreateMat(3,3,CV_32FC1);
EightPointAlgorithm(&cx1, &cx2, F);
ScalarMul(F, 1/cvGetReal2D(F, 2,2), F);
PrintMat(F, "Fundamental Matrix");
//Classifier classifier;
//vector<int> visibleID;
//classifier.SetRansacParam(ransacThreshold, ransacMaxIter);
//classifier.SetCorrespondance(&cx1, &cx2, visibleFeatureID);
//classifier.Classify();
//vector<int> vInlierID, vOutlierID;
//classifier.GetClassificationResultByFeatureID(vInlierID, vOutlierID);
//visibleFeatureID = vInlierID;
//F = cvCloneMat(classifier.F);
//double F33 = cvGetReal2D(F, 2,2);
//ScalarMul(F, 1/F33, F);
//PrintMat(F, "Fundamental Matrix");
//cx1 = *cvCreateMat(classifier.inlier1->rows, classifier.inlier1->cols, CV_32FC1);
//cx2 = *cvCreateMat(classifier.inlier2->rows, classifier.inlier2->cols, CV_32FC1);
//cx1 = *cvCloneMat(classifier.inlier1);
//cx2 = *cvCloneMat(classifier.inlier2);
CvMat *E = cvCreateMat(3, 3, CV_32FC1);
CvMat *temp33 = cvCreateMat(3, 3, CV_32FC1);
CvMat *temp34 = cvCreateMat(3, 4, CV_32FC1);
CvMat *K1 = cvCreateMat(3,3,CV_32FC1);
CvMat *K2 = cvCreateMat(3,3,CV_32FC1);
int camera1 = (int)((double)initialFrame1/max_nFrames);
int camera2 = (int)((double)initialFrame2/max_nFrames);
vector<int> ::const_iterator it1 = find(vCamera[camera1].vTakenFrame.begin(), vCamera[camera1].vTakenFrame.end(), initialFrame1%max_nFrames);
vector<int> ::const_iterator it2 = find(vCamera[camera2].vTakenFrame.begin(), vCamera[camera2].vTakenFrame.end(), initialFrame2%max_nFrames);
int idx1 = (int) (it1 - vCamera[camera1].vTakenFrame.begin());
int idx2 = (int) (it2 - vCamera[camera2].vTakenFrame.begin());
K1 = cvCloneMat(vCamera[camera1].vK[idx1]);
K2 = cvCloneMat(vCamera[camera2].vK[idx1]);
cvTranspose(K2, temp33);
cvMatMul(temp33, F, temp33);
cvMatMul(temp33, K1, E);
CvMat *invK1 = cvCreateMat(3,3,CV_32FC1);
CvMat *invK2 = cvCreateMat(3,3,CV_32FC1);
cvInvert(K1, invK1);
cvInvert(K2, invK2);
Pxx_inhomo(invK1, &cx1, nx1);
Pxx_inhomo(invK2, &cx2, nx2);
GetExtrinsicParameterFromE(E, &nx1, &nx2, P);
CvMat *P0 = cvCreateMat(3, 4, CV_32FC1);
cvSetIdentity(P0);
CvMat cX;
LinearTriangulation(&nx1, P0, &nx2, &P, cX);
cvSetZero(&X);
SetIndexedMatRowwise(&X, visibleFeatureID, &cX);
cvMatMul(K2, &P, temp34);
P = *cvCloneMat(temp34);
visibleStructureID = visibleFeatureID;
cvReleaseMat(&F);
cvReleaseMat(&E);
cvReleaseMat(&temp33);
cvReleaseMat(&temp34);
cvReleaseMat(&K1);
cvReleaseMat(&K2);
cvReleaseMat(&invK1);
cvReleaseMat(&invK2);
cvReleaseMat(&P0);
}
void EightPointAlgorithm(CvMat *x1_8, CvMat *x2_8, CvMat *F_8)
{
CvMat *A = cvCreateMat(x1_8->rows, 9, CV_32FC1);
CvMat *U = cvCreateMat(x1_8->rows, x1_8->rows, CV_32FC1);
CvMat *D = cvCreateMat(x1_8->rows, 9, CV_32FC1);
CvMat *V = cvCreateMat(9, 9, CV_32FC1);
for (int iIdx = 0; iIdx < x1_8->rows; iIdx++)
{
double x11 = cvGetReal2D(x1_8, iIdx, 0);
double x12 = cvGetReal2D(x1_8, iIdx, 1);
double x21 = cvGetReal2D(x2_8, iIdx, 0);
double x22 = cvGetReal2D(x2_8, iIdx, 1);
cvSetReal2D(A, iIdx, 0, x21*x11);
cvSetReal2D(A, iIdx, 1, x21*x12);
cvSetReal2D(A, iIdx, 2, x21);
cvSetReal2D(A, iIdx, 3, x22*x11);
cvSetReal2D(A, iIdx, 4, x22*x12);
cvSetReal2D(A, iIdx, 5, x22);
cvSetReal2D(A, iIdx, 6, x11);
cvSetReal2D(A, iIdx, 7, x12);
cvSetReal2D(A, iIdx, 8, 1);
}
cvSVD(A, D, U, V, 0);
cvSetReal2D(F_8, 0, 0, cvGetReal2D(V, 0, 8)); cvSetReal2D(F_8, 0, 1, cvGetReal2D(V, 1, 8)); cvSetReal2D(F_8, 0, 2, cvGetReal2D(V, 2, 8));
cvSetReal2D(F_8, 1, 0, cvGetReal2D(V, 3, 8)); cvSetReal2D(F_8, 1, 1, cvGetReal2D(V, 4, 8)); cvSetReal2D(F_8, 1, 2, cvGetReal2D(V, 5, 8));
cvSetReal2D(F_8, 2, 0, cvGetReal2D(V, 6, 8)); cvSetReal2D(F_8, 2, 1, cvGetReal2D(V, 7, 8)); cvSetReal2D(F_8, 2, 2, cvGetReal2D(V, 8, 8));
CvMat *UD, *Vt;
U = cvCreateMat(3, 3, CV_32FC1);
D = cvCreateMat(3, 3, CV_32FC1);
V = cvCreateMat(3, 3, CV_32FC1);
UD = cvCreateMat(U->rows, D->cols, CV_32FC1);
Vt = cvCreateMat(V->cols, V->rows, CV_32FC1);
cvSVD(F_8, D, U, V, 0);
cvSetReal2D(D, 2, 2, 0);
cvMatMul(U, D, UD);
cvTranspose(V, Vt);
cvMatMul(UD, Vt, F_8);
cvReleaseMat(&UD);
cvReleaseMat(&Vt);
cvReleaseMat(&A);
cvReleaseMat(&U);
cvReleaseMat(&D);
cvReleaseMat(&V);
}
void VisibleIntersection(vector<Feature> vFeature, int frame1, int frame2, CvMat &cx1, CvMat &cx2, vector<int> &visibleFeatureID)
{
vector<double> x1, y1, x2, y2;
for (int iFeature = 0; iFeature < vFeature.size(); iFeature++)
{
vector<int>::iterator it1 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame1);
vector<int>::iterator it2 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame2);
if ((it1 != vFeature[iFeature].vFrame.end()) && (it2 != vFeature[iFeature].vFrame.end()))
{
int idx = int(it1-vFeature[iFeature].vFrame.begin());
x1.push_back(vFeature[iFeature].vx[idx]);
y1.push_back(vFeature[iFeature].vy[idx]);
idx = int(it2-vFeature[iFeature].vFrame.begin());
x2.push_back(vFeature[iFeature].vx[idx]);
y2.push_back(vFeature[iFeature].vy[idx]);
visibleFeatureID.push_back(vFeature[iFeature].id);
}
}
cout << "# intersection: " << visibleFeatureID.size() << endl;
cx1 = *cvCreateMat(x1.size(), 2, CV_32FC1);
cx2 = *cvCreateMat(x1.size(), 2, CV_32FC1);
for (int i = 0; i < x1.size(); i++)
{
cvSetReal2D(&cx1, i, 0, x1[i]); cvSetReal2D(&cx1, i, 1, y1[i]);
cvSetReal2D(&cx2, i, 0, x2[i]); cvSetReal2D(&cx2, i, 1, y2[i]);
}
}
void VisibleIntersection_mem(vector<Feature> &vFeature, int frame1, int frame2, vector<vector<double> > &cx1, vector<vector<double> > &cx2, vector<int> &visibleFeatureID)
{
vector<double> x1, y1, x2, y2;
for (int iFeature = 0; iFeature < vFeature.size(); iFeature++)
{
vector<int>::iterator it1 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame1);
vector<int>::iterator it2 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame2);
if ((it1 != vFeature[iFeature].vFrame.end()) && (it2 != vFeature[iFeature].vFrame.end()))
{
int idx = int(it1-vFeature[iFeature].vFrame.begin());
x1.push_back(vFeature[iFeature].vx[idx]);
y1.push_back(vFeature[iFeature].vy[idx]);
idx = int(it2-vFeature[iFeature].vFrame.begin());
x2.push_back(vFeature[iFeature].vx[idx]);
y2.push_back(vFeature[iFeature].vy[idx]);
visibleFeatureID.push_back(vFeature[iFeature].id);
}
}
//cout << "# intersection: " << visibleFeatureID.size() << endl;
for (int i = 0; i < x1.size(); i++)
{
vector<double> x1_vec, x2_vec;
x1_vec.push_back(x1[i]);
x1_vec.push_back(y1[i]);
x2_vec.push_back(x2[i]);
x2_vec.push_back(y2[i]);
cx1.push_back(x1_vec);
cx2.push_back(x2_vec);
}
}
void VisibleIntersection_Simple(vector<Feature> vFeature, int frame1, int frame2, vector<int> &visibleFeatureID)
{
vector<double> x1, y1, x2, y2;
for (int iFeature = 0; iFeature < vFeature.size(); iFeature++)
{
vector<int>::iterator it1 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame1);
vector<int>::iterator it2 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame2);
if ((it1 != vFeature[iFeature].vFrame.end()) && (it2 != vFeature[iFeature].vFrame.end()))
{
visibleFeatureID.push_back(vFeature[iFeature].id);
}
}
}
int VisibleIntersection23(vector<Feature> vFeature, int frame1, CvMat *X, vector<int> visibleStructureID, CvMat &cx, CvMat &cX, vector<int> &visibleID)
{
vector<double> x_, y_, X_, Y_, Z_;
for (int iFeature = 0; iFeature < vFeature.size(); iFeature++)
{
vector<int>::iterator it1 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame1);
vector<int>::iterator it2 = find(visibleStructureID.begin(),visibleStructureID.end(),vFeature[iFeature].id);
if ((it1 != vFeature[iFeature].vFrame.end()) && (it2 != visibleStructureID.end()))
{
int idx1 = int(it1-vFeature[iFeature].vFrame.begin());
int idx2 = int(it2-visibleStructureID.begin());
x_.push_back(vFeature[iFeature].vx[idx1]);
y_.push_back(vFeature[iFeature].vy[idx1]);
X_.push_back(cvGetReal2D(X, vFeature[iFeature].id, 0));
Y_.push_back(cvGetReal2D(X, vFeature[iFeature].id, 1));
Z_.push_back(cvGetReal2D(X, vFeature[iFeature].id, 2));
visibleID.push_back(vFeature[iFeature].id);
}
}
if (x_.size() < 1)
return 0;
cx = *cvCreateMat(x_.size(), 2, CV_32FC1);
cX = *cvCreateMat(x_.size(), 3, CV_32FC1);
for (int i = 0; i < x_.size(); i++)
{
cvSetReal2D(&cx, i, 0, x_[i]); cvSetReal2D(&cx, i, 1, y_[i]);
cvSetReal2D(&cX, i, 0, X_[i]); cvSetReal2D(&cX, i, 1, Y_[i]); cvSetReal2D(&cX, i, 2, Z_[i]);
}
return 1;
}
int VisibleIntersection23_mem(vector<Feature> vFeature, int frame1, CvMat *X, vector<int> visibleStructureID, vector<vector<double> > &cx, vector<vector<double> > &cX, vector<int> &visibleID)
{
vector<double> x_, y_, X_, Y_, Z_;
for (int iFeature = 0; iFeature < vFeature.size(); iFeature++)
{
vector<int>::iterator it1 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame1);
vector<int>::iterator it2 = find(visibleStructureID.begin(),visibleStructureID.end(),vFeature[iFeature].id);
if ((it1 != vFeature[iFeature].vFrame.end()) && (it2 != visibleStructureID.end()))
{
int idx1 = int(it1-vFeature[iFeature].vFrame.begin());
int idx2 = int(it2-visibleStructureID.begin());
x_.push_back(vFeature[iFeature].vx[idx1]);
y_.push_back(vFeature[iFeature].vy[idx1]);
X_.push_back(cvGetReal2D(X, vFeature[iFeature].id, 0));
Y_.push_back(cvGetReal2D(X, vFeature[iFeature].id, 1));
Z_.push_back(cvGetReal2D(X, vFeature[iFeature].id, 2));
visibleID.push_back(vFeature[iFeature].id);
}
}
if (x_.size() < 1)
return 0;
for (int i = 0; i < x_.size(); i++)
{
vector<double> cx_vec, cX_vec;
cx_vec.push_back(x_[i]);
cx_vec.push_back(y_[i]);
cX_vec.push_back(X_[i]);
cX_vec.push_back(Y_[i]);
cX_vec.push_back(Z_[i]);
cx.push_back(cx_vec);
cX.push_back(cX_vec);
}
return visibleID.size();
}
int VisibleIntersection23_mem_fast(vector<Feature> &vFeature, int frame1, CvMat *X, vector<vector<double> > &cx, vector<vector<double> > &cX, vector<int> &visibleID)
{
for (int iFeature = 0; iFeature < vFeature.size(); iFeature++)
{
vector<double> cx_vec, cX_vec;
vector<int>::iterator it1 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame1);
if ((it1 != vFeature[iFeature].vFrame.end()) && (vFeature[iFeature].isRegistered))
{
int idx1 = int(it1-vFeature[iFeature].vFrame.begin());
cx_vec.push_back(vFeature[iFeature].vx[idx1]);
cx_vec.push_back(vFeature[iFeature].vy[idx1]);
cX_vec.push_back(cvGetReal2D(X, vFeature[iFeature].id, 0));
cX_vec.push_back(cvGetReal2D(X, vFeature[iFeature].id, 1));
cX_vec.push_back(cvGetReal2D(X, vFeature[iFeature].id, 2));
cx.push_back(cx_vec);
cX.push_back(cX_vec);
visibleID.push_back(vFeature[iFeature].id);
}
}
if (cx.size() < 1)
return 0;
return visibleID.size();
}
int VisibleIntersection23_Simple(vector<Feature> &vFeature, int frame1, vector<int> visibleStructureID, vector<int> &visibleID)
{
vector<double> x_, y_, X_, Y_, Z_;
for (int iFeature = 0; iFeature < vFeature.size(); iFeature++)
{
vector<int>::iterator it1 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame1);
if (it1 == vFeature[iFeature].vFrame.end())
continue;
vector<int>::iterator it2 = find(visibleStructureID.begin(),visibleStructureID.end(),vFeature[iFeature].id);
if ((it1 != vFeature[iFeature].vFrame.end()) && (it2 != visibleStructureID.end()))
{
int idx1 = int(it1-vFeature[iFeature].vFrame.begin());
int idx2 = int(it2-visibleStructureID.begin());
visibleID.push_back(vFeature[iFeature].id);
}
}
x_.clear();
y_.clear();
X_.clear();
Y_.clear();
Z_.clear();
return visibleID.size();
}
int VisibleIntersection23_Simple_fast(vector<Feature> &vFeature, int frame1)
{
int count = 0;
for (int iFeature = 0; iFeature < vFeature.size(); iFeature++)
{
vector<int>::iterator it1 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame1);
if (it1 == vFeature[iFeature].vFrame.end())
continue;
else if (vFeature[iFeature].isRegistered)
count++;
}
return count;
}
//int VisibleIntersection23(vector<Feature> vFeature, int frame1, CvMat *X, vector<int> visibleStructureID, CvMat *x, vector<int> &visibleID)
//{
// vector<double> x_, y_, X_, Y_, Z_;
// for (int iFeature = 0; iFeature < vFeature.size(); iFeature++)
// {
// vector<int>::iterator it1 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame1);
// vector<int>::iterator it2 = find(visibleStructureID.begin(),visibleStructureID.end(),vFeature[iFeature].id);
//
// if ((it1 != vFeature[iFeature].vFrame.end()) && (it2 != visibleStructureID.end()))
// {
// int idx1 = int(it1-vFeature[iFeature].vFrame.begin());
// int idx2 = int(it2-visibleStructureID.begin());
// x_.push_back(vFeature[iFeature].vx[idx1]);
// y_.push_back(vFeature[iFeature].vy[idx1]);
// X_.push_back(cvGetReal2D(X, vFeature[iFeature].id, 0));
// Y_.push_back(cvGetReal2D(X, vFeature[iFeature].id, 1));
// Z_.push_back(cvGetReal2D(X, vFeature[iFeature].id, 2));
// visibleID.push_back(vFeature[iFeature].id);
// }
// }
//
// if (x_.size() < 1)
// return 0;
// cx = *cvCreateMat(x_.size(), 2, CV_32FC1);
// cX = *cvCreateMat(x_.size(), 3, CV_32FC1);
// for (int i = 0; i < x_.size(); i++)
// {
// cvSetReal2D(&cx, i, 0, x_[i]); cvSetReal2D(&cx, i, 1, y_[i]);
// cvSetReal2D(&cX, i, 0, X_[i]); cvSetReal2D(&cX, i, 1, Y_[i]); cvSetReal2D(&cX, i, 2, Z_[i]);
// }
// return 1;
//}
int VisibleIntersectionXOR3(vector<Feature> vFeature, int frame1, int frame2, vector<int> visibleStructureID, CvMat &cx1, CvMat &cx2, vector<int> &visibleID)
{
vector<double> x1_, y1_, x2_, y2_;
visibleID.clear();
for (int iFeature = 0; iFeature < vFeature.size(); iFeature++)
{
vector<int>::iterator it1 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame1);
vector<int>::iterator it2 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame2);
vector<int>::iterator it3 = find(visibleStructureID.begin(),visibleStructureID.end(),vFeature[iFeature].id);
if ((it1 != vFeature[iFeature].vFrame.end()) && (it2 != vFeature[iFeature].vFrame.end()) && (it3 == visibleStructureID.end()))
{
int idx1 = int(it1-vFeature[iFeature].vFrame.begin());
int idx2 = int(it2-vFeature[iFeature].vFrame.begin());
x1_.push_back(vFeature[iFeature].vx[idx1]);
y1_.push_back(vFeature[iFeature].vy[idx1]);
x2_.push_back(vFeature[iFeature].vx[idx2]);
y2_.push_back(vFeature[iFeature].vy[idx2]);
visibleID.push_back(vFeature[iFeature].id);
}
}
if (x1_.size() == 0)
{
visibleID.clear();
return 0;
}
cx1 = *cvCreateMat(x1_.size(), 2, CV_32FC1);
cx2 = *cvCreateMat(x1_.size(), 2, CV_32FC1);
for (int i = 0; i < x1_.size(); i++)
{
cvSetReal2D(&cx1, i, 0, x1_[i]); cvSetReal2D(&cx1, i, 1, y1_[i]);
cvSetReal2D(&cx2, i, 0, x2_[i]); cvSetReal2D(&cx2, i, 1, y2_[i]);
}
return 1;
}
int VisibleIntersectionXOR3_mem(vector<Feature> &vFeature, int frame1, int frame2, vector<int> visibleStructureID, vector<vector<double> > &cx1, vector<vector<double> > &cx2, vector<int> &visibleID)
{
vector<double> x1_, y1_, x2_, y2_;
visibleID.clear();
for (int iFeature = 0; iFeature < vFeature.size(); iFeature++)
{
vector<int>::iterator it1 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame1);
vector<int>::iterator it2 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame2);
vector<int>::iterator it3 = find(visibleStructureID.begin(),visibleStructureID.end(),vFeature[iFeature].id);
if ((it1 != vFeature[iFeature].vFrame.end()) && (it2 != vFeature[iFeature].vFrame.end()) && (it3 == visibleStructureID.end()))
{
int idx1 = int(it1-vFeature[iFeature].vFrame.begin());
int idx2 = int(it2-vFeature[iFeature].vFrame.begin());
x1_.push_back(vFeature[iFeature].vx[idx1]);
y1_.push_back(vFeature[iFeature].vy[idx1]);
x2_.push_back(vFeature[iFeature].vx[idx2]);
y2_.push_back(vFeature[iFeature].vy[idx2]);
visibleID.push_back(vFeature[iFeature].id);
}
}
if (x1_.size() == 0)
{
visibleID.clear();
return 0;
}
for (int i = 0; i < x1_.size(); i++)
{
vector<double> cx1_vec, cx2_vec;
cx1_vec.push_back(x1_[i]);
cx1_vec.push_back(y1_[i]);
cx2_vec.push_back(x2_[i]);
cx2_vec.push_back(y2_[i]);
cx1.push_back(cx1_vec);
cx2.push_back(cx2_vec);
}
return cx1.size();
}
int VisibleIntersectionXOR3_mem_fast(vector<Feature> &vFeature, int frame1, int frame2, vector<vector<double> > &cx1, vector<vector<double> > &cx2, vector<int> &visibleID)
{
visibleID.clear();
for (int iFeature = 0; iFeature < vFeature.size(); iFeature++)
{
if (vFeature[iFeature].isRegistered)
continue;
vector<int>::iterator it1 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame1);
if (it1 == vFeature[iFeature].vFrame.end())
continue;
vector<int>::iterator it2 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame2);
if (it2 == vFeature[iFeature].vFrame.end())
continue;
vector<double> cx1_vec, cx2_vec;
int idx1 = int(it1-vFeature[iFeature].vFrame.begin());
int idx2 = int(it2-vFeature[iFeature].vFrame.begin());
cx1_vec.push_back(vFeature[iFeature].vx[idx1]);
cx1_vec.push_back(vFeature[iFeature].vy[idx1]);
cx2_vec.push_back(vFeature[iFeature].vx[idx2]);
cx2_vec.push_back(vFeature[iFeature].vy[idx2]);
cx1.push_back(cx1_vec);
cx2.push_back(cx2_vec);
visibleID.push_back(vFeature[iFeature].id);
}
if (visibleID.size() == 0)
{
return 0;
}
return cx1.size();
}
//int VisibleIntersectionXOR3(vector<Feature> vFeature, int frame1, int frame2, vector<int> visibleStructureID, vector<int> &visibleID)
//{
// vector<double> x1_, y1_, x2_, y2_;
// visibleID.clear();
// for (int iFeature = 0; iFeature < vFeature.size(); iFeature++)
// {
// vector<int>::iterator it1 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame1);
// vector<int>::iterator it2 = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),frame2);
// vector<int>::iterator it3 = find(visibleStructureID.begin(),visibleStructureID.end(),vFeature[iFeature].id);
//
// if ((it1 != vFeature[iFeature].vFrame.end()) && (it2 != vFeature[iFeature].vFrame.end()) && (it3 == visibleStructureID.end()))
// {
// int idx1 = int(it1-vFeature[iFeature].vFrame.begin());
// int idx2 = int(it2-vFeature[iFeature].vFrame.begin());
// x1_.push_back(vFeature[iFeature].vx[idx1]);
// y1_.push_back(vFeature[iFeature].vy[idx1]);
// x2_.push_back(vFeature[iFeature].vx[idx2]);
// y2_.push_back(vFeature[iFeature].vy[idx2]);
// visibleID.push_back(vFeature[iFeature].id);
// }
// }
//
// if (x1_.size() == 0)
// {
// visibleID.clear();
// return 0;
// }
//
// cx1 = *cvCreateMat(x1_.size(), 2, CV_32FC1);
// cx2 = *cvCreateMat(x1_.size(), 2, CV_32FC1);
// for (int i = 0; i < x1_.size(); i++)
// {
// cvSetReal2D(&cx1, i, 0, x1_[i]); cvSetReal2D(&cx1, i, 1, y1_[i]);
// cvSetReal2D(&cx2, i, 0, x2_[i]); cvSetReal2D(&cx2, i, 1, y2_[i]);
// }
// return 1;
//}
//int ExcludeOutliers(CvMat *cx1, CvMat *cx2, double ransacThreshold, double ransacMaxIter, vector<int> visibleID, CvMat &ex1, CvMat &ex2, vector<int> &eVisibleID)
//{
// Classifier classifier;
// classifier.SetRansacParam(ransacThreshold, ransacMaxIter);
// classifier.SetCorrespondance(cx1, cx2, visibleID);
// classifier.Classify();
// vector<int> vInlierID, vOutlierID;
// classifier.GetClassificationResultByFeatureID(vInlierID, vOutlierID);
//
// if (vInlierID.size() > 0)
// {
// ex1 = *cvCreateMat(classifier.inlier1->rows, classifier.inlier1->cols, CV_32FC1);
// ex2 = *cvCreateMat(classifier.inlier1->rows, classifier.inlier1->cols, CV_32FC1);
// eVisibleID = vInlierID;
// ex1 = *cvCloneMat(classifier.inlier1);
// ex2 = *cvCloneMat(classifier.inlier2);
// return 1;
// }
// else
// {
// return 0;
// }
//}
int ExcludeOutliers(CvMat *cx1, CvMat *P1, CvMat *cx2, CvMat *P2, CvMat *K, double threshold, vector<int> visibleID, CvMat &ex1, CvMat &ex2, vector<int> &eVisibleID)
{
// Find epipole
CvMat *e_homo = cvCreateMat(3,1,CV_32FC1);
CvMat *C = cvCreateMat(3,1,CV_32FC1);
CvMat *R = cvCreateMat(3,3,CV_32FC1);
GetCameraParameter(P1, K, R, C);
CvMat *C_homo = cvCreateMat(4,1,CV_32FC1);
Inhomo2HomoVec(C, C_homo);
cvMatMul(P2, C_homo, e_homo);
double enorm = NormL2(e_homo);
ScalarMul(e_homo, 1/enorm, e_homo);
CvMat *pinvP1 = cvCreateMat(4,3,CV_32FC1);
cvInvert(P1, pinvP1, CV_SVD);
CvMat *temp33 = cvCreateMat(3,3,CV_32FC1);
cvMatMul(P2, pinvP1, temp33);
CvMat *skewE = cvCreateMat(3,3,CV_32FC1);
Vec2Skew(e_homo, skewE);
CvMat *F = cvCreateMat(3,3,CV_32FC1);
CvMat *FF = cvCreateMat(3,3,CV_32FC1);
cvMatMul(skewE, temp33, F);
double Fnorm = NormL2(F);
ScalarMul(F, 1/Fnorm, F);
cvTranspose(F, temp33);
cvMatMul(temp33, F, FF);
CvMat *D1=cvCreateMat(cx1->rows,1,CV_32FC1), *D2=cvCreateMat(cx1->rows,1,CV_32FC1), *D=cvCreateMat(cx1->rows,1,CV_32FC1);
xPy_inhomo(cx2, cx1, F, D1);
xPx_inhomo(cx1, FF, D2);
for (int iIdx = 0; iIdx < D2->rows; iIdx++)
{
cvSetReal2D(D2, iIdx, 0, sqrt(cvGetReal2D(D2, iIdx, 0)));
}
cvDiv(D1, D2, D);
cvMul(D, D, D);
eVisibleID.clear();
for (int iIdx = 0; iIdx < cx1->rows; iIdx++)
{
if (abs(cvGetReal2D(D, iIdx, 0)) < threshold)
{
eVisibleID.push_back(visibleID[iIdx]);
}
}
if (eVisibleID.size() > 0)
{
ex1 = *cvCreateMat(eVisibleID.size(), 2, CV_32FC1);
ex2 = *cvCreateMat(eVisibleID.size(), 2, CV_32FC1);
int k = 0;
for (int iIdx = 0; iIdx < cx1->rows; iIdx++)
{
if (abs(cvGetReal2D(D, iIdx, 0)) < threshold)
{
cvSetReal2D(&ex1, k, 0, cvGetReal2D(cx1, iIdx, 0));
cvSetReal2D(&ex1, k, 1, cvGetReal2D(cx1, iIdx, 1));
cvSetReal2D(&ex2, k, 0, cvGetReal2D(cx2, iIdx, 0));
cvSetReal2D(&ex2, k, 1, cvGetReal2D(cx2, iIdx, 1));
k++;
}
}
}
cvReleaseMat(&e_homo);
cvReleaseMat(&C);
cvReleaseMat(&R);
cvReleaseMat(&C_homo);
cvReleaseMat(&pinvP1);
cvReleaseMat(&temp33);
cvReleaseMat(&skewE);
cvReleaseMat(&F);
cvReleaseMat(&FF);
cvReleaseMat(&D1);
cvReleaseMat(&D2);
cvReleaseMat(&D);
if (eVisibleID.size() >0)
return 1;
else
return 0;
}
int ExcludeOutliers_mem(CvMat *cx1, CvMat *P1, CvMat *cx2, CvMat *P2, CvMat *K, double threshold, vector<int> visibleID, vector<vector<double> > &ex1, vector<vector<double> > &ex2, vector<int> &eVisibleID)
{
// Find epipole
CvMat *e_homo = cvCreateMat(3,1,CV_32FC1);
CvMat *C = cvCreateMat(3,1,CV_32FC1);
CvMat *R = cvCreateMat(3,3,CV_32FC1);
GetCameraParameter(P1, K, R, C);
CvMat *C_homo = cvCreateMat(4,1,CV_32FC1);
Inhomo2HomoVec(C, C_homo);
cvMatMul(P2, C_homo, e_homo);
double enorm = NormL2(e_homo);
ScalarMul(e_homo, 1/enorm, e_homo);
CvMat *pinvP1 = cvCreateMat(4,3,CV_32FC1);
cvInvert(P1, pinvP1, CV_SVD);
CvMat *temp33 = cvCreateMat(3,3,CV_32FC1);
cvMatMul(P2, pinvP1, temp33);
CvMat *skewE = cvCreateMat(3,3,CV_32FC1);
Vec2Skew(e_homo, skewE);
CvMat *F = cvCreateMat(3,3,CV_32FC1);
CvMat *FF = cvCreateMat(3,3,CV_32FC1);
cvMatMul(skewE, temp33, F);
double Fnorm = NormL2(F);
ScalarMul(F, 1/Fnorm, F);
cvTranspose(F, temp33);
cvMatMul(temp33, F, FF);
CvMat *D1=cvCreateMat(cx1->rows,1,CV_32FC1), *D2=cvCreateMat(cx1->rows,1,CV_32FC1), *D=cvCreateMat(cx1->rows,1,CV_32FC1);
xPy_inhomo(cx2, cx1, F, D1);
xPx_inhomo(cx1, FF, D2);
for (int iIdx = 0; iIdx < D2->rows; iIdx++)
{
cvSetReal2D(D2, iIdx, 0, sqrt(cvGetReal2D(D2, iIdx, 0)));
}
cvDiv(D1, D2, D);
cvMul(D, D, D);
eVisibleID.clear();
for (int iIdx = 0; iIdx < cx1->rows; iIdx++)
{
if (abs(cvGetReal2D(D, iIdx, 0)) < threshold)
{
eVisibleID.push_back(visibleID[iIdx]);
}
}
if (eVisibleID.size() > 0)
{
//ex1 = *cvCreateMat(eVisibleID.size(), 2, CV_32FC1);
//ex2 = *cvCreateMat(eVisibleID.size(), 2, CV_32FC1);
int k = 0;
for (int iIdx = 0; iIdx < cx1->rows; iIdx++)
{
if (abs(cvGetReal2D(D, iIdx, 0)) < threshold)
{
vector<double> ex1_vec, ex2_vec;
ex1_vec.push_back(cvGetReal2D(cx1, iIdx, 0));
ex1_vec.push_back(cvGetReal2D(cx1, iIdx, 1));
ex2_vec.push_back(cvGetReal2D(cx2, iIdx, 0));
ex2_vec.push_back(cvGetReal2D(cx2, iIdx, 1));
ex1.push_back(ex1_vec);
ex2.push_back(ex2_vec);
k++;
}
}
}
cvReleaseMat(&e_homo);
cvReleaseMat(&C);
cvReleaseMat(&R);
cvReleaseMat(&C_homo);
cvReleaseMat(&pinvP1);
cvReleaseMat(&temp33);
cvReleaseMat(&skewE);
cvReleaseMat(&F);
cvReleaseMat(&FF);
cvReleaseMat(&D1);
cvReleaseMat(&D2);
cvReleaseMat(&D);
if (eVisibleID.size() >0)
return 1;
else
return 0;
}
int ExcludeOutliers_mem_fast(CvMat *cx1, CvMat *P1, CvMat *cx2, CvMat *P2, CvMat *K, double threshold, vector<int> visibleID, vector<vector<double> > &ex1, vector<vector<double> > &ex2, vector<int> &eVisibleID)
{
// Find epipole
CvMat *e_homo = cvCreateMat(3,1,CV_32FC1);
CvMat *C = cvCreateMat(3,1,CV_32FC1);
CvMat *R = cvCreateMat(3,3,CV_32FC1);
GetCameraParameter(P1, K, R, C);
CvMat *C_homo = cvCreateMat(4,1,CV_32FC1);
Inhomo2HomoVec(C, C_homo);
cvMatMul(P2, C_homo, e_homo);
double enorm = NormL2(e_homo);
ScalarMul(e_homo, 1/enorm, e_homo);
CvMat *pinvP1 = cvCreateMat(4,3,CV_32FC1);
cvInvert(P1, pinvP1, CV_SVD);
CvMat *temp33 = cvCreateMat(3,3,CV_32FC1);
cvMatMul(P2, pinvP1, temp33);
CvMat *skewE = cvCreateMat(3,3,CV_32FC1);
Vec2Skew(e_homo, skewE);
CvMat *F = cvCreateMat(3,3,CV_32FC1);
CvMat *FF = cvCreateMat(3,3,CV_32FC1);
cvMatMul(skewE, temp33, F);
double Fnorm = NormL2(F);
ScalarMul(F, 1/Fnorm, F);
cvTranspose(F, temp33);
cvMatMul(temp33, F, FF);
//CvMat *D1=cvCreateMat(cx1->rows,1,CV_32FC1), *D2=cvCreateMat(cx1->rows,1,CV_32FC1), *D=cvCreateMat(cx1->rows,1,CV_32FC1);
//xPy_inhomo(cx2, cx1, F, D1);
//xPx_inhomo(cx1, FF, D2);
//for (int iIdx = 0; iIdx < D2->rows; iIdx++)
//{
// cvSetReal2D(D2, iIdx, 0, sqrt(cvGetReal2D(D2, iIdx, 0)));
//}
//cvDiv(D1, D2, D);
//cvMul(D, D, D);
eVisibleID.clear();
for (int iIdx = 0; iIdx < cx1->rows; iIdx++)
{
CvMat *xM2 = cvCreateMat(1, 3, CV_32FC1);
CvMat *xM1 = cvCreateMat(3, 1, CV_32FC1);
CvMat *s = cvCreateMat(1, 1, CV_32FC1);
cvSetReal2D(xM2, 0, 0, cvGetReal2D(cx2, iIdx, 0));
cvSetReal2D(xM2, 0, 1, cvGetReal2D(cx2, iIdx, 1));
cvSetReal2D(xM2, 0, 2, 1);
cvSetReal2D(xM1, 0, 0, cvGetReal2D(cx1, iIdx, 0));
cvSetReal2D(xM1, 1, 0, cvGetReal2D(cx2, iIdx, 1));
cvSetReal2D(xM1, 2, 0, 1);
cvMatMul(xM2, F, xM2);
cvMatMul(xM2, xM1, s);
double l1 = cvGetReal2D(xM2, 0, 0);
double l2 = cvGetReal2D(xM2, 0, 1);
double l3 = cvGetReal2D(xM2, 0, 2);
double dist = abs(cvGetReal2D(s, 0, 0))/sqrt(l1*l1+l2*l2);
cout << dist << endl;
if (abs(dist) < threshold)
{
vector<double> ex1_vec, ex2_vec;
ex1_vec.push_back(cvGetReal2D(cx1, iIdx, 0));
ex1_vec.push_back(cvGetReal2D(cx1, iIdx, 1));
ex2_vec.push_back(cvGetReal2D(cx2, iIdx, 0));
ex2_vec.push_back(cvGetReal2D(cx2, iIdx, 1));
ex1.push_back(ex1_vec);
ex2.push_back(ex2_vec);
eVisibleID.push_back(visibleID[iIdx]);
}
cvReleaseMat(&xM2);
cvReleaseMat(&xM1);
cvReleaseMat(&s);
}
cvReleaseMat(&e_homo);
cvReleaseMat(&C);
cvReleaseMat(&R);
cvReleaseMat(&C_homo);
cvReleaseMat(&pinvP1);
cvReleaseMat(&temp33);
cvReleaseMat(&skewE);
cvReleaseMat(&F);
cvReleaseMat(&FF);
//cvReleaseMat(&D1);
//cvReleaseMat(&D2);
//cvReleaseMat(&D);
if (eVisibleID.size() > 0)
return 1;
else
return 0;
}
void NonlinearTriangulation(CvMat *x1, CvMat *x2, CvMat *F, CvMat &xhat1, CvMat &xhat2)
{
for (int ix = 0; ix < x1->rows; ix++)
{
CvMat *T1 = cvCreateMat(3,3,CV_32FC1);
CvMat *T2 = cvCreateMat(3,3,CV_32FC1);
cvSetZero(T1);
cvSetReal2D(T1, 0, 0, 1.0);
cvSetReal2D(T1, 1, 1, 1.0);
cvSetReal2D(T1, 2, 2, 1.0);
cvSetReal2D(T1, 0, 2, -cvGetReal2D(x1, ix, 0));
cvSetReal2D(T1, 1, 2, -cvGetReal2D(x1, ix, 1));
cvSetZero(T2);
cvSetReal2D(T2, 0, 0, 1.0);
cvSetReal2D(T2, 1, 1, 1.0);
cvSetReal2D(T2, 2, 2, 1.0);
cvSetReal2D(T2, 0, 2, -cvGetReal2D(x2, ix, 0));
cvSetReal2D(T2, 1, 2, -cvGetReal2D(x2, ix, 1));
CvMat *nF = cvCreateMat(3,3,CV_32FC1);
nF = cvCloneMat(F);
CvMat *FinvT1 = cvCreateMat(3,3,CV_32FC1);
CvMat *invT1 = cvCreateMat(3,3,CV_32FC1);
CvMat *invT2 = cvCreateMat(3,3,CV_32FC1);
CvMat *invT2t = cvCreateMat(3,3,CV_32FC1);
cvInvert(T1, invT1); cvInvert(T2, invT2); cvTranspose(invT2, invT2t);
cvMatMul(nF, invT1, FinvT1);
cvMatMul(invT2t, FinvT1, nF);
CvMat *U = cvCreateMat(3,3,CV_32FC1);
CvMat *D = cvCreateMat(3,3,CV_32FC1);
CvMat *Vt = cvCreateMat(3,3,CV_32FC1);
cvSVD(nF, D, U, Vt, CV_SVD_V_T); cvSetReal2D(D, 2, 2, 0);
CvMat *temp33 = cvCreateMat(3,3,CV_32FC1); CvMat *temp33_1 = cvCreateMat(3,3,CV_32FC1);
cvMatMul(U, D, temp33);
cvMatMul(temp33, Vt, nF);
CvMat *e1 = cvCreateMat(3,1,CV_32FC1);
CvMat *e2 = cvCreateMat(3,1,CV_32FC1);
double e11 = cvGetReal2D(Vt,2,0); double e12 = cvGetReal2D(Vt,2,1); double e13 = cvGetReal2D(Vt,2,2);
CvMat *nFt = cvCreateMat(3,3,CV_32FC1);
cvTranspose(nF, nFt);
cvSVD(nFt, D, U, Vt, CV_SVD_V_T);
double norm_e1 = sqrt(e11*e11+e12*e12);
double e21 = cvGetReal2D(Vt,2,0); double e22 = cvGetReal2D(Vt,2,1); double e23 = cvGetReal2D(Vt,2,2);
double norm_e2 = sqrt(e21*e21+e22*e22);
cvSetReal2D(e1,0,0,e11/norm_e1); cvSetReal2D(e1,1,0,e12/norm_e1); cvSetReal2D(e1,2,0,e13/norm_e1);
cvSetReal2D(e2,0,0,e21/norm_e2); cvSetReal2D(e2,1,0,e22/norm_e2); cvSetReal2D(e2,2,0,e23/norm_e2);
CvMat *R1 = cvCreateMat(3,3,CV_32FC1);
CvMat *R2 = cvCreateMat(3,3,CV_32FC1);
cvSetIdentity(R1); cvSetIdentity(R2);
cvSetReal2D(R1, 0, 0, cvGetReal2D(e1, 0, 0)); cvSetReal2D(R1, 0, 1, cvGetReal2D(e1, 1, 0));
cvSetReal2D(R1, 1, 0, -cvGetReal2D(e1, 1, 0)); cvSetReal2D(R1, 1, 1, cvGetReal2D(e1, 0, 0));
cvSetReal2D(R2, 0, 0, cvGetReal2D(e2, 0, 0)); cvSetReal2D(R2, 0, 1, cvGetReal2D(e2, 1, 0));
cvSetReal2D(R2, 1, 0, -cvGetReal2D(e2, 1, 0)); cvSetReal2D(R2, 1, 1, cvGetReal2D(e2, 0, 0));
cvMatMul(R2, nF, temp33);
cvTranspose(R1, temp33_1);
cvMatMul(temp33, temp33_1, nF);
double f1 = cvGetReal2D(e1, 2, 0);
double f2 = cvGetReal2D(e2, 2, 0);
double a = cvGetReal2D(nF, 1, 1);
double b = cvGetReal2D(nF, 1, 2);
double c = cvGetReal2D(nF, 2, 1);
double d = cvGetReal2D(nF, 2, 2);
double g1 = -(a*d-b*c)*f1*f1*f1*f1*a*c;
double g2 = (a*a+f2*f2*c*c)*(a*a+f2*f2*c*c)-(a*d-b*c)*f1*f1*f1*f1*b*c-(a*d-b*c)*f1*f1*f1*f1*a*d;
double g3 = (2*(2*b*a+2*f2*f2*d*c)*(a*a+f2*f2*c*c)-2*(a*d-b*c)*f1*f1*a*c-(a*d-b*c)*f1*f1*f1*f1*b*d);
double g4 = (-2*(a*d-b*c)*f1*f1*b*c-2*(a*d-b*c)*f1*f1*a*d+2*(b*b+f2*f2*d*d)*(a*a+f2*f2*c*c)+(2*b*a+2*f2*f2*d*c)*(2*b*a+2*f2*f2*d*c));
double g5 = (-(a*d-b*c)*a*c-2*(a*d-b*c)*f1*f1*b*d+2*(b*b+f2*f2*d*d)*(2*b*a+2*f2*f2*d*c));
double g6 = ((b*b+f2*f2*d*d)*(b*b+f2*f2*d*d)-(a*d-b*c)*b*c-(a*d-b*c)*a*d);
double g7 = -(a*d-b*c)*b*d;
CvMat *G = cvCreateMat(7,1,CV_32FC1);
CvMat *root = cvCreateMat(6,1, CV_32FC2);
cvSetReal2D(G, 0, 0, g1);
cvSetReal2D(G, 1, 0, g2);
cvSetReal2D(G, 2, 0, g3);
cvSetReal2D(G, 3, 0, g4);
cvSetReal2D(G, 4, 0, g5);
cvSetReal2D(G, 5, 0, g6);
cvSetReal2D(G, 6, 0, g7);
cvSolvePoly(G, root, 1e+3, 10);
for (int i = 0; i < 6; i++)
{
CvScalar r = cvGet2D(root, i, 0);
cout << r.val[0] << " " << r.val[1]<< endl;
}
}
// e1 = null(F); e1 = e1/sqrt(e1(1)^2+e1(2)^2);
//e2 = null(F'); e2 = e2/sqrt(e2(1)^2+e2(2)^2);
// R1 = [e1(1) e1(2) 0; -e1(2) e1(1) 0; 0 0 1];
//R2 = [e2(1) e2(2) 0; -e2(2) e2(1) 0; 0 0 1];
//F = R2*F*R1';
// f1 = e1(3); f2 = e2(3);
//a = F(2,2); b = F(2,3); c = F(3,2); d = F(3,3);
//g = [-(a*d-b*c)*f1^4*a*c,...
// (a^2+f2^2*c^2)^2-(a*d-b*c)*f1^4*b*c-(a*d-b*c)*f1^4*a*d,...
// (2*(2*b*a+2*f2^2*d*c)*(a^2+f2^2*c^2)-2*(a*d-b*c)*f1^2*a*c-(a*d-b*c)*f1^4*b*d),...
// (-2*(a*d-b*c)*f1^2*b*c-2*(a*d-b*c)*f1^2*a*d+2*(b^2+f2^2*d^2)*(a^2+f2^2*c^2)+(2*b*a+2*f2^2*d*c)^2),...
// (-(a*d-b*c)*a*c-2*(a*d-b*c)*f1^2*b*d+2*(b^2+f2^2*d^2)*(2*b*a+2*f2^2*d*c)),...
// ((b^2+f2^2*d^2)^2-(a*d-b*c)*b*c-(a*d-b*c)*a*d),...
// -(a*d-b*c)*b*d];
//t = roots(g);
//t = real(t);
//s = t.^2./(1+f1^2*t.^2) + (c*t+d).^2./((a*t+b).^2 + f2^2*(c*t+d).^2);
//s(end+1) = 1/f1^2+c^2/(a^2+f2^2*c^2);
//[mins,minidx] = min(s);
//if minidx <= length(t)
// t = t(minidx);
//else
// t = 1e+6;
//end
// l1 = [t*f1, 1, -t];
//l2 = F*[0; t; 1];
//xhat1_t = [-l1(1)*l1(3); -l1(2)*l1(3); l1(1)^2+l1(2)^2];
//xhat2_t = [-l2(1)*l2(3); -l2(2)*l2(3); l2(1)^2+l2(2)^2];
//xhat1_t = inv(T1)*R1'*xhat1_t;
// xhat2_t = inv(T2)*R2'*xhat2_t;
// xhat1_t = xhat1_t/xhat1_t(3);
//xhat2_t = xhat2_t/xhat2_t(3);
//xhat1(i,:) = xhat1_t;
//xhat2(i,:) = xhat2_t;
//end
}
void GetExtrinsicParameterFromE(CvMat *E, CvMat *x1, CvMat *x2, CvMat &P)
{
CvMat *W = cvCreateMat(3, 3, CV_32FC1);
CvMat *U = cvCreateMat(3, 3, CV_32FC1);
CvMat *D = cvCreateMat(3, 3, CV_32FC1);
CvMat *Vt = cvCreateMat(3, 3, CV_32FC1);
CvMat *Wt = cvCreateMat(3, 3, CV_32FC1);
cvSVD(E, D, U, Vt, CV_SVD_V_T);
//cvSetReal2D(D, 1,1,cvGetReal2D(D,0,0));
//cvMatMul(U, D, E);
//cvMatMul(E, Vt, E);
//cvSVD(E, D, U, Vt, CV_SVD_V_T);
cvSetReal2D(W, 0, 0, 0); cvSetReal2D(W, 0, 1, -1); cvSetReal2D(W, 0, 2, 0);
cvSetReal2D(W, 1, 0, 1); cvSetReal2D(W, 1, 1, 0); cvSetReal2D(W, 1, 2, 0);
cvSetReal2D(W, 2, 0, 0); cvSetReal2D(W, 2, 1, 0); cvSetReal2D(W, 2, 2, 1);
cvTranspose(W, Wt);
CvMat *P0 = cvCreateMat(3, 4, CV_32FC1);
cvSetIdentity(P0);
P = *cvCreateMat(3, 4, CV_32FC1);
CvMat *P1 = cvCreateMat(3, 4, CV_32FC1);
CvMat *P2 = cvCreateMat(3, 4, CV_32FC1);
CvMat *P3 = cvCreateMat(3, 4, CV_32FC1);
CvMat *P4 = cvCreateMat(3, 4, CV_32FC1);
CvMat *R1 = cvCreateMat(3, 3, CV_32FC1);
CvMat *R2 = cvCreateMat(3, 3, CV_32FC1);
CvMat *t1 = cvCreateMat(3, 1, CV_32FC1);
CvMat *t2 = cvCreateMat(3, 1, CV_32FC1);
CvMat *temp33 = cvCreateMat(3, 3, CV_32FC1);
cvMatMul(U, W, temp33);
cvMatMul(temp33, Vt, R1);
cvMatMul(U, Wt, temp33);
cvMatMul(temp33, Vt, R2);
cvSetReal2D(t1, 0, 0, cvGetReal2D(U,0,2));
cvSetReal2D(t1, 1, 0, cvGetReal2D(U,1,2));
cvSetReal2D(t1, 2, 0, cvGetReal2D(U,2,2));
ScalarMul(t1, -1, t2);
SetSubMat(P1, 0, 0, R1);
SetSubMat(P1, 0, 3, t1);
SetSubMat(P2, 0, 0, R1);
SetSubMat(P2, 0, 3, t2);
SetSubMat(P3, 0, 0, R2);
SetSubMat(P3, 0, 3, t1);
SetSubMat(P4, 0, 0, R2);
SetSubMat(P4, 0, 3, t2);
if (cvDet(R1) < 0)
{
ScalarMul(P1, -1, P1);
ScalarMul(P2, -1, P2);
}
if (cvDet(R2) < 0)
{
ScalarMul(P3, -1, P3);
ScalarMul(P4, -1, P4);
}
CvMat X1;
LinearTriangulation(x1, P0, x2, P1, X1);
CvMat X2;
LinearTriangulation(x1, P0, x2, P2, X2);
CvMat X3;
LinearTriangulation(x1, P0, x2, P3, X3);
CvMat X4;
LinearTriangulation(x1, P0, x2, P4, X4);
int x1neg = 0, x2neg = 0, x3neg = 0, x4neg = 0;
CvMat *H1 = cvCreateMat(4, 4, CV_32FC1); CvMat *invH1 = cvCreateMat(4, 4, CV_32FC1); CvMat HX1;
cvSetIdentity(H1);
SetSubMat(H1, 0, 0, P1);
cvInvert(H1, invH1);
Pxx_inhomo(H1, &X1, HX1);
CvMat *H2 = cvCreateMat(4, 4, CV_32FC1); CvMat *invH2 = cvCreateMat(4, 4, CV_32FC1); CvMat HX2;
cvSetIdentity(H2);
SetSubMat(H2, 0, 0, P2);
cvInvert(H2, invH2);
Pxx_inhomo(H2, &X2, HX2);
CvMat *H3 = cvCreateMat(4, 4, CV_32FC1); CvMat *invH3 = cvCreateMat(4, 4, CV_32FC1); CvMat HX3;
cvSetIdentity(H3);
SetSubMat(H3, 0, 0, P3);
cvInvert(H3, invH3);
Pxx_inhomo(H3, &X3, HX3);
CvMat *H4 = cvCreateMat(4, 4, CV_32FC1); CvMat *invH4 = cvCreateMat(4, 4, CV_32FC1); CvMat HX4;
cvSetIdentity(H4);
SetSubMat(H4, 0, 0, P4);
cvInvert(H4, invH4);
Pxx_inhomo(H4, &X4, HX4);
for (int ix = 0; ix < x1->rows; ix++)
{
if ((cvGetReal2D(&X1, ix, 2)<0) || (cvGetReal2D(&HX1, ix, 2)<0))
x1neg++;
if ((cvGetReal2D(&X2, ix, 2)<0) || (cvGetReal2D(&HX2, ix, 2)<0))
x2neg++;
if ((cvGetReal2D(&X3, ix, 2)<0) || (cvGetReal2D(&HX3, ix, 2)<0))
x3neg++;
if ((cvGetReal2D(&X4, ix, 2)<0) || (cvGetReal2D(&HX4, ix, 2)<0))
x4neg++;
}
CvMat *temp34 = cvCreateMat(3, 4, CV_32FC1);
if ((x1neg <= x2neg) && (x1neg <= x3neg) && (x1neg <= x4neg))
P = *cvCloneMat(P1);
else if ((x2neg <= x1neg) && (x2neg <= x3neg) && (x2neg <= x4neg))
P = *cvCloneMat(P2);
else if ((x3neg <= x1neg) && (x3neg <= x2neg) && (x3neg <= x4neg))
P = *cvCloneMat(P3);
else
P = *cvCloneMat(P4);
cvReleaseMat(&W);
cvReleaseMat(&U);
cvReleaseMat(&D);
cvReleaseMat(&Vt);
cvReleaseMat(&Wt);
cvReleaseMat(&P0);
cvReleaseMat(&P1);
cvReleaseMat(&P2);
cvReleaseMat(&P3);
cvReleaseMat(&P4);
cvReleaseMat(&R1);
cvReleaseMat(&R2);
cvReleaseMat(&t1);
cvReleaseMat(&t2);
cvReleaseMat(&temp33);
cvReleaseMat(&temp34);
cvReleaseMat(&H1);
cvReleaseMat(&invH1);
cvReleaseMat(&H2);
cvReleaseMat(&invH2);
cvReleaseMat(&H3);
cvReleaseMat(&invH3);
cvReleaseMat(&H4);
cvReleaseMat(&invH4);
}
void GetExtrinsicParameterFromE(CvMat *E, CvMat *x1, CvMat *x2, CvMat *P)
{
CvMat *W = cvCreateMat(3, 3, CV_32FC1);
CvMat *U = cvCreateMat(3, 3, CV_32FC1);
CvMat *D = cvCreateMat(3, 3, CV_32FC1);
CvMat *Vt = cvCreateMat(3, 3, CV_32FC1);
CvMat *Wt = cvCreateMat(3, 3, CV_32FC1);
cvSVD(E, D, U, Vt, CV_SVD_V_T);
//cvSetReal2D(D, 1,1,cvGetReal2D(D,0,0));
//cvMatMul(U, D, E);
//cvMatMul(E, Vt, E);
//cvSVD(E, D, U, Vt, CV_SVD_V_T);
cvSetReal2D(W, 0, 0, 0); cvSetReal2D(W, 0, 1, -1); cvSetReal2D(W, 0, 2, 0);
cvSetReal2D(W, 1, 0, 1); cvSetReal2D(W, 1, 1, 0); cvSetReal2D(W, 1, 2, 0);
cvSetReal2D(W, 2, 0, 0); cvSetReal2D(W, 2, 1, 0); cvSetReal2D(W, 2, 2, 1);
cvTranspose(W, Wt);
CvMat *P0 = cvCreateMat(3, 4, CV_32FC1);
cvSetIdentity(P0);
CvMat *P1 = cvCreateMat(3, 4, CV_32FC1);
CvMat *P2 = cvCreateMat(3, 4, CV_32FC1);
CvMat *P3 = cvCreateMat(3, 4, CV_32FC1);
CvMat *P4 = cvCreateMat(3, 4, CV_32FC1);
CvMat *R1 = cvCreateMat(3, 3, CV_32FC1);
CvMat *R2 = cvCreateMat(3, 3, CV_32FC1);
CvMat *t1 = cvCreateMat(3, 1, CV_32FC1);
CvMat *t2 = cvCreateMat(3, 1, CV_32FC1);
CvMat *temp33 = cvCreateMat(3, 3, CV_32FC1);
cvMatMul(U, W, temp33);
cvMatMul(temp33, Vt, R1);
cvMatMul(U, Wt, temp33);
cvMatMul(temp33, Vt, R2);
cvSetReal2D(t1, 0, 0, cvGetReal2D(U,0,2));
cvSetReal2D(t1, 1, 0, cvGetReal2D(U,1,2));
cvSetReal2D(t1, 2, 0, cvGetReal2D(U,2,2));
ScalarMul(t1, -1, t2);
SetSubMat(P1, 0, 0, R1);
SetSubMat(P1, 0, 3, t1);
SetSubMat(P2, 0, 0, R1);
SetSubMat(P2, 0, 3, t2);
SetSubMat(P3, 0, 0, R2);
SetSubMat(P3, 0, 3, t1);
SetSubMat(P4, 0, 0, R2);
SetSubMat(P4, 0, 3, t2);
if (cvDet(R1) < 0)
{
ScalarMul(P1, -1, P1);
ScalarMul(P2, -1, P2);
}
if (cvDet(R2) < 0)
{
ScalarMul(P3, -1, P3);
ScalarMul(P4, -1, P4);
}
CvMat *X1 = cvCreateMat(x1->rows, 3, CV_32FC1);
LinearTriangulation(x1, P0, x2, P1, X1);
CvMat *X2 = cvCreateMat(x1->rows, 3, CV_32FC1);;
LinearTriangulation(x1, P0, x2, P2, X2);
CvMat *X3 = cvCreateMat(x1->rows, 3, CV_32FC1);;
LinearTriangulation(x1, P0, x2, P3, X3);
CvMat *X4 = cvCreateMat(x1->rows, 3, CV_32FC1);;
LinearTriangulation(x1, P0, x2, P4, X4);
int x1neg = 0, x2neg = 0, x3neg = 0, x4neg = 0;
CvMat *H1 = cvCreateMat(4, 4, CV_32FC1); CvMat *invH1 = cvCreateMat(4, 4, CV_32FC1); CvMat *HX1 = cvCreateMat(X1->rows, X1->cols, CV_32FC1);
cvSetIdentity(H1);
SetSubMat(H1, 0, 0, P1);
cvInvert(H1, invH1);
Pxx_inhomo(H1, X1, HX1);
CvMat *H2 = cvCreateMat(4, 4, CV_32FC1); CvMat *invH2 = cvCreateMat(4, 4, CV_32FC1); CvMat *HX2 = cvCreateMat(X1->rows, X1->cols, CV_32FC1);
cvSetIdentity(H2);
SetSubMat(H2, 0, 0, P2);
cvInvert(H2, invH2);
Pxx_inhomo(H2, X2, HX2);
CvMat *H3 = cvCreateMat(4, 4, CV_32FC1); CvMat *invH3 = cvCreateMat(4, 4, CV_32FC1); CvMat *HX3 = cvCreateMat(X1->rows, X1->cols, CV_32FC1);
cvSetIdentity(H3);
SetSubMat(H3, 0, 0, P3);
cvInvert(H3, invH3);
Pxx_inhomo(H3, X3, HX3);
CvMat *H4 = cvCreateMat(4, 4, CV_32FC1); CvMat *invH4 = cvCreateMat(4, 4, CV_32FC1); CvMat *HX4 = cvCreateMat(X1->rows, X1->cols, CV_32FC1);
cvSetIdentity(H4);
SetSubMat(H4, 0, 0, P4);
cvInvert(H4, invH4);
Pxx_inhomo(H4, X4, HX4);
for (int ix = 0; ix < x1->rows; ix++)
{
if ((cvGetReal2D(X1, ix, 2)<0) || (cvGetReal2D(HX1, ix, 2)<0))
x1neg++;
if ((cvGetReal2D(X2, ix, 2)<0) || (cvGetReal2D(HX2, ix, 2)<0))
x2neg++;
if ((cvGetReal2D(X3, ix, 2)<0) || (cvGetReal2D(HX3, ix, 2)<0))
x3neg++;
if ((cvGetReal2D(X4, ix, 2)<0) || (cvGetReal2D(HX4, ix, 2)<0))
x4neg++;
}
CvMat *temp34 = cvCreateMat(3, 4, CV_32FC1);
if ((x1neg <= x2neg) && (x1neg <= x3neg) && (x1neg <= x4neg))
SetSubMat(P, 0, 0, P1);
else if ((x2neg <= x1neg) && (x2neg <= x3neg) && (x2neg <= x4neg))
SetSubMat(P, 0, 0, P2);
else if ((x3neg <= x1neg) && (x3neg <= x2neg) && (x3neg <= x4neg))
SetSubMat(P, 0, 0, P3);
else
SetSubMat(P, 0, 0, P4);
//cout << x1neg << " " << x2neg << " " << " " << x3neg << " " << x4neg << endl;
cvReleaseMat(&W);
cvReleaseMat(&U);
cvReleaseMat(&D);
cvReleaseMat(&Vt);
cvReleaseMat(&Wt);
cvReleaseMat(&P0);
cvReleaseMat(&P1);
cvReleaseMat(&P2);
cvReleaseMat(&P3);
cvReleaseMat(&P4);
cvReleaseMat(&R1);
cvReleaseMat(&R2);
cvReleaseMat(&t1);
cvReleaseMat(&t2);
cvReleaseMat(&temp33);
cvReleaseMat(&temp34);
cvReleaseMat(&H1);
cvReleaseMat(&invH1);
cvReleaseMat(&H2);
cvReleaseMat(&invH2);
cvReleaseMat(&H3);
cvReleaseMat(&invH3);
cvReleaseMat(&H4);
cvReleaseMat(&invH4);
cvReleaseMat(&X1);
cvReleaseMat(&X2);
cvReleaseMat(&X3);
cvReleaseMat(&X4);
cvReleaseMat(&HX1);
cvReleaseMat(&HX2);
cvReleaseMat(&HX3);
cvReleaseMat(&HX4);
}
void LinearTriangulation(CvMat *x1, CvMat *P1, CvMat *x2, CvMat *P2, CvMat &X)
{
X = *cvCreateMat(x1->rows, 3, CV_32FC1);
cvSetZero(&X);
for (int ix = 0; ix < x1->rows; ix++)
{
CvMat *A = cvCreateMat(4, 4, CV_32FC1);
CvMat *A1 = cvCreateMat(1, 4, CV_32FC1);
CvMat *A2 = cvCreateMat(1, 4, CV_32FC1);
CvMat *A3 = cvCreateMat(1, 4, CV_32FC1);
CvMat *A4 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P1_1 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P1_2 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P1_3 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P2_1 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P2_2 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P2_3 = cvCreateMat(1, 4, CV_32FC1);
CvMat *temp14_1 = cvCreateMat(1, 4, CV_32FC1);
GetSubMatRowwise(P1, 0, 0, P1_1);
GetSubMatRowwise(P1, 1, 1, P1_2);
GetSubMatRowwise(P1, 2, 2, P1_3);
GetSubMatRowwise(P2, 0, 0, P2_1);
GetSubMatRowwise(P2, 1, 1, P2_2);
GetSubMatRowwise(P2, 2, 2, P2_3);
ScalarMul(P1_3, cvGetReal2D(x1, ix, 0), temp14_1);
cvSub(temp14_1, P1_1, A1);
ScalarMul(P1_3, cvGetReal2D(x1, ix, 1), temp14_1);
cvSub(temp14_1, P1_2, A2);
ScalarMul(P2_3, cvGetReal2D(x2, ix, 0), temp14_1);
cvSub(temp14_1, P2_1, A3);
ScalarMul(P2_3, cvGetReal2D(x2, ix, 1), temp14_1);
cvSub(temp14_1, P2_2, A4);
SetSubMat(A, 0, 0, A1);
SetSubMat(A, 1, 0, A2);
SetSubMat(A, 2, 0, A3);
SetSubMat(A, 3, 0, A4);
CvMat x;
LS_homogeneous(A, x);
double v = cvGetReal2D(&x, 3, 0);
cvSetReal2D(&X, ix, 0, cvGetReal2D(&x, 0, 0)/v);
cvSetReal2D(&X, ix, 1, cvGetReal2D(&x, 1, 0)/v);
cvSetReal2D(&X, ix, 2, cvGetReal2D(&x, 2, 0)/v);
cvReleaseMat(&A);
cvReleaseMat(&A1);
cvReleaseMat(&A2);
cvReleaseMat(&A3);
cvReleaseMat(&A4);
cvReleaseMat(&P1_1);
cvReleaseMat(&P1_2);
cvReleaseMat(&P1_3);
cvReleaseMat(&P2_1);
cvReleaseMat(&P2_2);
cvReleaseMat(&P2_3);
cvReleaseMat(&temp14_1);
}
}
void LinearTriangulation(CvMat *x1, CvMat *P1, CvMat *x2, CvMat *P2, CvMat *X)
{
for (int ix = 0; ix < x1->rows; ix++)
{
CvMat *A = cvCreateMat(4, 4, CV_32FC1);
CvMat *A1 = cvCreateMat(1, 4, CV_32FC1);
CvMat *A2 = cvCreateMat(1, 4, CV_32FC1);
CvMat *A3 = cvCreateMat(1, 4, CV_32FC1);
CvMat *A4 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P1_1 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P1_2 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P1_3 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P2_1 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P2_2 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P2_3 = cvCreateMat(1, 4, CV_32FC1);
CvMat *temp14_1 = cvCreateMat(1, 4, CV_32FC1);
GetSubMatRowwise(P1, 0, 0, P1_1);
GetSubMatRowwise(P1, 1, 1, P1_2);
GetSubMatRowwise(P1, 2, 2, P1_3);
GetSubMatRowwise(P2, 0, 0, P2_1);
GetSubMatRowwise(P2, 1, 1, P2_2);
GetSubMatRowwise(P2, 2, 2, P2_3);
ScalarMul(P1_3, cvGetReal2D(x1, ix, 0), temp14_1);
cvSub(temp14_1, P1_1, A1);
ScalarMul(P1_3, cvGetReal2D(x1, ix, 1), temp14_1);
cvSub(temp14_1, P1_2, A2);
ScalarMul(P2_3, cvGetReal2D(x2, ix, 0), temp14_1);
cvSub(temp14_1, P2_1, A3);
ScalarMul(P2_3, cvGetReal2D(x2, ix, 1), temp14_1);
cvSub(temp14_1, P2_2, A4);
SetSubMat(A, 0, 0, A1);
SetSubMat(A, 1, 0, A2);
SetSubMat(A, 2, 0, A3);
SetSubMat(A, 3, 0, A4);
CvMat *x = cvCreateMat(A->cols, 1, CV_32FC1);
LS_homogeneous(A, x);
double v = cvGetReal2D(x, 3, 0);
cvSetReal2D(X, ix, 0, cvGetReal2D(x, 0, 0)/v);
cvSetReal2D(X, ix, 1, cvGetReal2D(x, 1, 0)/v);
cvSetReal2D(X, ix, 2, cvGetReal2D(x, 2, 0)/v);
cvReleaseMat(&A);
cvReleaseMat(&A1);
cvReleaseMat(&A2);
cvReleaseMat(&A3);
cvReleaseMat(&A4);
cvReleaseMat(&P1_1);
cvReleaseMat(&P1_2);
cvReleaseMat(&P1_3);
cvReleaseMat(&P2_1);
cvReleaseMat(&P2_2);
cvReleaseMat(&P2_3);
cvReleaseMat(&temp14_1);
cvReleaseMat(&x);
}
}
int LinearTriangulation(CvMat *x1, CvMat *P1, CvMat *x2, CvMat *P2, vector<int> featureID, CvMat &X, vector<int> &filteredFeatureID)
{
//X = *cvCreateMat(x1->rows, 3, CV_32FC1);
//cvSetZero(&X);
vector<double> X1, X2, X3;
filteredFeatureID.clear();
for (int ix = 0; ix < x1->rows; ix++)
{
CvMat *A = cvCreateMat(4, 4, CV_32FC1);
CvMat *A1 = cvCreateMat(1, 4, CV_32FC1);
CvMat *A2 = cvCreateMat(1, 4, CV_32FC1);
CvMat *A3 = cvCreateMat(1, 4, CV_32FC1);
CvMat *A4 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P1_1 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P1_2 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P1_3 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P2_1 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P2_2 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P2_3 = cvCreateMat(1, 4, CV_32FC1);
CvMat *temp14_1 = cvCreateMat(1, 4, CV_32FC1);
GetSubMatRowwise(P1, 0, 0, P1_1);
GetSubMatRowwise(P1, 1, 1, P1_2);
GetSubMatRowwise(P1, 2, 2, P1_3);
GetSubMatRowwise(P2, 0, 0, P2_1);
GetSubMatRowwise(P2, 1, 1, P2_2);
GetSubMatRowwise(P2, 2, 2, P2_3);
ScalarMul(P1_3, cvGetReal2D(x1, ix, 0), temp14_1);
cvSub(temp14_1, P1_1, A1);
ScalarMul(P1_3, cvGetReal2D(x1, ix, 1), temp14_1);
cvSub(temp14_1, P1_2, A2);
ScalarMul(P2_3, cvGetReal2D(x2, ix, 0), temp14_1);
cvSub(temp14_1, P2_1, A3);
ScalarMul(P2_3, cvGetReal2D(x2, ix, 1), temp14_1);
cvSub(temp14_1, P2_2, A4);
SetSubMat(A, 0, 0, A1);
SetSubMat(A, 1, 0, A2);
SetSubMat(A, 2, 0, A3);
SetSubMat(A, 3, 0, A4);
CvMat x;
LS_homogeneous(A, x);
double v = cvGetReal2D(&x, 3, 0);
//cout << v << " " << abs(v)<< endl;
if (abs(v) < POINT_AT_INFINITY_ZERO)
continue;
X1.push_back(cvGetReal2D(&x, 0, 0)/v);
X2.push_back(cvGetReal2D(&x, 1, 0)/v);
X3.push_back(cvGetReal2D(&x, 2, 0)/v);
filteredFeatureID.push_back(featureID[ix]);
cvReleaseMat(&A);
cvReleaseMat(&A1);
cvReleaseMat(&A2);
cvReleaseMat(&A3);
cvReleaseMat(&A4);
cvReleaseMat(&P1_1);
cvReleaseMat(&P1_2);
cvReleaseMat(&P1_3);
cvReleaseMat(&P2_1);
cvReleaseMat(&P2_2);
cvReleaseMat(&P2_3);
cvReleaseMat(&temp14_1);
}
if (X1.size() == 0)
return 0;
X = *cvCreateMat(X1.size(), 3, CV_32FC1);
for (int i = 0; i < X1.size(); i++)
{
cvSetReal2D(&X, i, 0, X1[i]);
cvSetReal2D(&X, i, 1, X2[i]);
cvSetReal2D(&X, i, 2, X3[i]);
}
return 1;
}
int LinearTriangulation_mem(CvMat *x1, CvMat *P1, CvMat *x2, CvMat *P2, vector<int> featureID, vector<vector<double> > &X, vector<int> &filteredFeatureID)
{
vector<double> X1, X2, X3;
filteredFeatureID.clear();
for (int ix = 0; ix < x1->rows; ix++)
{
CvMat *A = cvCreateMat(4, 4, CV_32FC1);
CvMat *A1 = cvCreateMat(1, 4, CV_32FC1);
CvMat *A2 = cvCreateMat(1, 4, CV_32FC1);
CvMat *A3 = cvCreateMat(1, 4, CV_32FC1);
CvMat *A4 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P1_1 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P1_2 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P1_3 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P2_1 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P2_2 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P2_3 = cvCreateMat(1, 4, CV_32FC1);
CvMat *temp14_1 = cvCreateMat(1, 4, CV_32FC1);
GetSubMatRowwise(P1, 0, 0, P1_1);
GetSubMatRowwise(P1, 1, 1, P1_2);
GetSubMatRowwise(P1, 2, 2, P1_3);
GetSubMatRowwise(P2, 0, 0, P2_1);
GetSubMatRowwise(P2, 1, 1, P2_2);
GetSubMatRowwise(P2, 2, 2, P2_3);
ScalarMul(P1_3, cvGetReal2D(x1, ix, 0), temp14_1);
cvSub(temp14_1, P1_1, A1);
ScalarMul(P1_3, cvGetReal2D(x1, ix, 1), temp14_1);
cvSub(temp14_1, P1_2, A2);
ScalarMul(P2_3, cvGetReal2D(x2, ix, 0), temp14_1);
cvSub(temp14_1, P2_1, A3);
ScalarMul(P2_3, cvGetReal2D(x2, ix, 1), temp14_1);
cvSub(temp14_1, P2_2, A4);
SetSubMat(A, 0, 0, A1);
SetSubMat(A, 1, 0, A2);
SetSubMat(A, 2, 0, A3);
SetSubMat(A, 3, 0, A4);
CvMat *x = cvCreateMat(A->cols, 1, CV_32FC1);
LS_homogeneous(A, x);
double v = cvGetReal2D(x, 3, 0);
if (abs(v) < POINT_AT_INFINITY_ZERO)
{
cvReleaseMat(&A);
cvReleaseMat(&A1);
cvReleaseMat(&A2);
cvReleaseMat(&A3);
cvReleaseMat(&A4);
cvReleaseMat(&P1_1);
cvReleaseMat(&P1_2);
cvReleaseMat(&P1_3);
cvReleaseMat(&P2_1);
cvReleaseMat(&P2_2);
cvReleaseMat(&P2_3);
cvReleaseMat(&temp14_1);
cvReleaseMat(&x);
continue;
}
X1.push_back(cvGetReal2D(x, 0, 0)/v);
X2.push_back(cvGetReal2D(x, 1, 0)/v);
X3.push_back(cvGetReal2D(x, 2, 0)/v);
filteredFeatureID.push_back(featureID[ix]);
cvReleaseMat(&A);
cvReleaseMat(&A1);
cvReleaseMat(&A2);
cvReleaseMat(&A3);
cvReleaseMat(&A4);
cvReleaseMat(&P1_1);
cvReleaseMat(&P1_2);
cvReleaseMat(&P1_3);
cvReleaseMat(&P2_1);
cvReleaseMat(&P2_2);
cvReleaseMat(&P2_3);
cvReleaseMat(&temp14_1);
cvReleaseMat(&x);
}
if (X1.size() == 0)
return 0;
for (int i = 0; i < X1.size(); i++)
{
vector<double> X_vec;
X_vec.push_back(X1[i]);
X_vec.push_back(X2[i]);
X_vec.push_back(X3[i]);
X.push_back(X_vec);
}
return X.size();
}
int LinearTriangulation_mem_fast(CvMat *x1, CvMat *P1, CvMat *x2, CvMat *P2, vector<int> &featureID, vector<vector<double> > &X, vector<int> &filteredFeatureID)
{
filteredFeatureID.clear();
CvMat *A = cvCreateMat(4, 4, CV_32FC1);
CvMat *A1 = cvCreateMat(1, 4, CV_32FC1);
CvMat *A2 = cvCreateMat(1, 4, CV_32FC1);
CvMat *A3 = cvCreateMat(1, 4, CV_32FC1);
CvMat *A4 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P1_1 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P1_2 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P1_3 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P2_1 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P2_2 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P2_3 = cvCreateMat(1, 4, CV_32FC1);
CvMat *temp14_1 = cvCreateMat(1, 4, CV_32FC1);
CvMat *x = cvCreateMat(A->cols, 1, CV_32FC1);
for (int ix = 0; ix < x1->rows; ix++)
{
GetSubMatRowwise(P1, 0, 0, P1_1);
GetSubMatRowwise(P1, 1, 1, P1_2);
GetSubMatRowwise(P1, 2, 2, P1_3);
GetSubMatRowwise(P2, 0, 0, P2_1);
GetSubMatRowwise(P2, 1, 1, P2_2);
GetSubMatRowwise(P2, 2, 2, P2_3);
ScalarMul(P1_3, cvGetReal2D(x1, ix, 0), temp14_1);
cvSub(temp14_1, P1_1, A1);
ScalarMul(P1_3, cvGetReal2D(x1, ix, 1), temp14_1);
cvSub(temp14_1, P1_2, A2);
ScalarMul(P2_3, cvGetReal2D(x2, ix, 0), temp14_1);
cvSub(temp14_1, P2_1, A3);
ScalarMul(P2_3, cvGetReal2D(x2, ix, 1), temp14_1);
cvSub(temp14_1, P2_2, A4);
SetSubMat(A, 0, 0, A1);
SetSubMat(A, 1, 0, A2);
SetSubMat(A, 2, 0, A3);
SetSubMat(A, 3, 0, A4);
LS_homogeneous(A, x);
double v = cvGetReal2D(x, 3, 0);
if (abs(v) < POINT_AT_INFINITY_ZERO)
{
continue;
}
vector<double> X_vec;
X_vec.push_back(cvGetReal2D(x, 0, 0)/v);
X_vec.push_back(cvGetReal2D(x, 1, 0)/v);
X_vec.push_back(cvGetReal2D(x, 2, 0)/v);
X.push_back(X_vec);
filteredFeatureID.push_back(featureID[ix]);
}
cvReleaseMat(&A);
cvReleaseMat(&A1);
cvReleaseMat(&A2);
cvReleaseMat(&A3);
cvReleaseMat(&A4);
cvReleaseMat(&P1_1);
cvReleaseMat(&P1_2);
cvReleaseMat(&P1_3);
cvReleaseMat(&P2_1);
cvReleaseMat(&P2_2);
cvReleaseMat(&P2_3);
cvReleaseMat(&temp14_1);
cvReleaseMat(&x);
if (filteredFeatureID.size() == 0)
return 0;
return X.size();
}
bool LinearTriangulation(vector<CvMat *> vP, vector<double> vx, vector<double> vy, double &X, double &Y, double &Z)
{
if (vP.size() < 2)
return false;
CvMat *A = cvCreateMat(2*vP.size(), 4, CV_32FC1);
CvMat *A1 = cvCreateMat(1, 4, CV_32FC1);
CvMat *A2 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P_1 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P_2 = cvCreateMat(1, 4, CV_32FC1);
CvMat *P_3 = cvCreateMat(1, 4, CV_32FC1);
CvMat *temp14_1 = cvCreateMat(1, 4, CV_32FC1);
CvMat *x = cvCreateMat(A->cols, 1, CV_32FC1);
for (int iP = 0; iP < vP.size(); iP++)
{
GetSubMatRowwise(vP[iP], 0, 0, P_1);
GetSubMatRowwise(vP[iP], 1, 1, P_2);
GetSubMatRowwise(vP[iP], 2, 2, P_3);
ScalarMul(P_3, vx[iP], temp14_1);
cvSub(temp14_1, P_1, A1);
ScalarMul(P_3, vy[iP], temp14_1);
cvSub(temp14_1, P_2, A2);
SetSubMat(A, 2*iP, 0, A1);
SetSubMat(A, 2*iP+1, 0, A2);
}
LS_homogeneous(A, x);
CvMat *Ax = cvCreateMat(A->rows, 1, CV_32FC1);
cvMatMul(A, x, Ax);
//PrintMat(Ax);
double v = cvGetReal2D(x, 3, 0);
if (abs(v) < POINT_AT_INFINITY_ZERO)
{
return false;
}
X = cvGetReal2D(x, 0, 0)/v;
Y = cvGetReal2D(x, 1, 0)/v;
Z = cvGetReal2D(x, 2, 0)/v;
cvReleaseMat(&A);
cvReleaseMat(&A1);
cvReleaseMat(&A2);
cvReleaseMat(&P_1);
cvReleaseMat(&P_2);
cvReleaseMat(&P_3);
cvReleaseMat(&temp14_1);
cvReleaseMat(&x);
return true;
}
int DLT_ExtrinsicCameraParamEstimation(CvMat *X, CvMat *x, CvMat *K, CvMat *P)
{
if (X->rows < 6)
return 0;
CvMat *Xtilde = cvCreateMat(X->rows, 3, CV_32FC1);
CvMat *xtilde = cvCreateMat(x->rows, 2, CV_32FC1);
CvMat *U = cvCreateMat(4,4, CV_32FC1);
CvMat *T = cvCreateMat(3,3, CV_32FC1);
Normalization3D(X, Xtilde, U);
Normalization(x, xtilde, T);
CvMat *A = cvCreateMat(X->rows*2,12,CV_32FC1);
for (int iX = 0; iX < X->rows; iX++)
{
CvMat *A1 = cvCreateMat(1, 12, CV_32FC1);
CvMat *A2 = cvCreateMat(1, 12, CV_32FC1);
cvSetZero(A1); cvSetZero(A2);
CvMat *A1_2 = cvCreateMat(1, 4, CV_32FC1);
CvMat *A1_3 = cvCreateMat(1, 4, CV_32FC1);
CvMat *A2_1 = cvCreateMat(1, 4, CV_32FC1);
CvMat *A2_3 = cvCreateMat(1, 4, CV_32FC1);
// A1_2
cvSetReal2D(A1_2, 0, 0, -cvGetReal2D(Xtilde, iX, 0));
cvSetReal2D(A1_2, 0, 1, -cvGetReal2D(Xtilde, iX, 1));
cvSetReal2D(A1_2, 0, 2, -cvGetReal2D(Xtilde, iX, 2));
cvSetReal2D(A1_2, 0, 3, -1);
// A1_3
cvSetReal2D(A1_3, 0, 0, cvGetReal2D(xtilde, iX, 1)*cvGetReal2D(Xtilde, iX, 0));
cvSetReal2D(A1_3, 0, 1, cvGetReal2D(xtilde, iX, 1)*cvGetReal2D(Xtilde, iX, 1));
cvSetReal2D(A1_3, 0, 2, cvGetReal2D(xtilde, iX, 1)*cvGetReal2D(Xtilde, iX, 2));
cvSetReal2D(A1_3, 0, 3, cvGetReal2D(xtilde, iX, 1));
// A2_1
cvSetReal2D(A2_1, 0, 0, cvGetReal2D(Xtilde, iX, 0));
cvSetReal2D(A2_1, 0, 1, cvGetReal2D(Xtilde, iX, 1));
cvSetReal2D(A2_1, 0, 2, cvGetReal2D(Xtilde, iX, 2));
cvSetReal2D(A2_1, 0, 3, 1);
// A1_3
cvSetReal2D(A2_3, 0, 0, -cvGetReal2D(xtilde, iX, 0)*cvGetReal2D(Xtilde, iX, 0));
cvSetReal2D(A2_3, 0, 1, -cvGetReal2D(xtilde, iX, 0)*cvGetReal2D(Xtilde, iX, 1));
cvSetReal2D(A2_3, 0, 2, -cvGetReal2D(xtilde, iX, 0)*cvGetReal2D(Xtilde, iX, 2));
cvSetReal2D(A2_3, 0, 3, -cvGetReal2D(xtilde, iX, 0));
SetSubMat(A1, 0, 4, A1_2); SetSubMat(A1, 0, 8, A1_3);
SetSubMat(A2, 0, 0, A2_1); SetSubMat(A2, 0, 8, A2_3);
SetSubMat(A, 2*iX, 0, A1);
SetSubMat(A, 2*iX+1, 0, A2);
cvReleaseMat(&A1);
cvReleaseMat(&A2);
cvReleaseMat(&A1_2);
cvReleaseMat(&A1_3);
cvReleaseMat(&A2_1);
cvReleaseMat(&A2_3);
}
CvMat *p = cvCreateMat(A->cols, 1, CV_32FC1);
LS_homogeneous(A, p);
cvSetReal2D(P, 0, 0, cvGetReal2D(p, 0, 0)); cvSetReal2D(P, 0, 1, cvGetReal2D(p, 1, 0)); cvSetReal2D(P, 0, 2, cvGetReal2D(p, 2, 0)); cvSetReal2D(P, 0, 3, cvGetReal2D(p, 3, 0));
cvSetReal2D(P, 1, 0, cvGetReal2D(p, 4, 0)); cvSetReal2D(P, 1, 1, cvGetReal2D(p, 5, 0)); cvSetReal2D(P, 1, 2, cvGetReal2D(p, 6, 0)); cvSetReal2D(P, 1, 3, cvGetReal2D(p, 7, 0));
cvSetReal2D(P, 2, 0, cvGetReal2D(p, 8, 0)); cvSetReal2D(P, 2, 1, cvGetReal2D(p, 9, 0)); cvSetReal2D(P, 2, 2, cvGetReal2D(p, 10, 0)); cvSetReal2D(P, 2, 3, cvGetReal2D(p, 11, 0));
CvMat *temp34 = cvCreateMat(3,4,CV_32FC1);
CvMat *invT = cvCreateMat(3,3,CV_32FC1);
cvInvert(T, invT);
cvMatMul(invT, P, temp34);
cvMatMul(temp34, U, P);
CvMat *P_ = cvCreateMat(3,4, CV_32FC1);
CvMat *invK = cvCreateMat(3,3,CV_32FC1);
cvInvert(K, invK);
cvMatMul(invK, P, P_);
CvMat *P1 = cvCreateMat(3,1,CV_32FC1);
GetSubMatColwise(P_, 0, 0, P1);
CvMat *R = cvCreateMat(3,3,CV_32FC1);
GetSubMatColwise(P_, 0, 2, R);
double norm = NormL2(P1);
double determinant = cvDet(R);
double sign = 1;
if (determinant < 0)
sign = -1;
ScalarMul(P_,sign/norm, P);
cvMatMul(K, P, P);
cvReleaseMat(&temp34);
cvReleaseMat(&invT);
cvReleaseMat(&P_);
cvReleaseMat(&invK);
cvReleaseMat(&P1);
cvReleaseMat(&R);
cvReleaseMat(&Xtilde);
cvReleaseMat(&xtilde);
cvReleaseMat(&U);
cvReleaseMat(&T);
cvReleaseMat(&A);
cvReleaseMat(&p);
return 1;
}
int EPNP_ExtrinsicCameraParamEstimation(CvMat *X, CvMat *x, CvMat *K, CvMat *P)
{
epnp PnP;
PnP.set_internal_parameters(cvGetReal2D(K, 0, 2), cvGetReal2D(K, 1, 2), cvGetReal2D(K, 0, 0), cvGetReal2D(K, 1, 1));
PnP.set_maximum_number_of_correspondences(X->rows);
PnP.reset_correspondences();
for(int i = 0; i < X->rows; i++) {
PnP.add_correspondence(cvGetReal2D(X, i, 0), cvGetReal2D(X, i, 1), cvGetReal2D(X, i, 2), cvGetReal2D(x, i, 0), cvGetReal2D(x, i, 1));
}
double R_est[3][3], t_est[3];
double err2 = PnP.compute_pose(R_est, t_est);
cvSetReal2D(P, 0, 3, t_est[0]);
cvSetReal2D(P, 1, 3, t_est[1]);
cvSetReal2D(P, 2, 3, t_est[2]);
cvSetReal2D(P, 0, 0, R_est[0][0]); cvSetReal2D(P, 0, 1, R_est[0][1]); cvSetReal2D(P, 0, 2, R_est[0][2]);
cvSetReal2D(P, 1, 0, R_est[1][0]); cvSetReal2D(P, 1, 1, R_est[1][1]); cvSetReal2D(P, 1, 2, R_est[1][2]);
cvSetReal2D(P, 2, 0, R_est[2][0]); cvSetReal2D(P, 2, 1, R_est[2][1]); cvSetReal2D(P, 2, 2, R_est[2][2]);
cvMatMul(K, P, P);
return 1;
}
int DLT_ExtrinsicCameraParamEstimation_KRT(CvMat *X, CvMat *x, CvMat *K, CvMat *P)
{
if (X->rows < 6)
return 0;
CvMat *Xtilde = cvCreateMat(X->rows, 3, CV_32FC1);
CvMat *xtilde = cvCreateMat(x->rows, 2, CV_32FC1);
CvMat *U = cvCreateMat(4,4, CV_32FC1);
CvMat *T = cvCreateMat(3,3, CV_32FC1);
Normalization3D(X, Xtilde, U);
Normalization(x, xtilde, T);
CvMat *A = cvCreateMat(X->rows*2,12,CV_32FC1);
for (int iX = 0; iX < X->rows; iX++)
{
CvMat *A1 = cvCreateMat(1, 12, CV_32FC1);
CvMat *A2 = cvCreateMat(1, 12, CV_32FC1);
cvSetZero(A1); cvSetZero(A2);
CvMat *A1_2 = cvCreateMat(1, 4, CV_32FC1);
CvMat *A1_3 = cvCreateMat(1, 4, CV_32FC1);
CvMat *A2_1 = cvCreateMat(1, 4, CV_32FC1);
CvMat *A2_3 = cvCreateMat(1, 4, CV_32FC1);
// A1_2
cvSetReal2D(A1_2, 0, 0, -cvGetReal2D(Xtilde, iX, 0));
cvSetReal2D(A1_2, 0, 1, -cvGetReal2D(Xtilde, iX, 1));
cvSetReal2D(A1_2, 0, 2, -cvGetReal2D(Xtilde, iX, 2));
cvSetReal2D(A1_2, 0, 3, -1);
// A1_3
cvSetReal2D(A1_3, 0, 0, cvGetReal2D(xtilde, iX, 1)*cvGetReal2D(Xtilde, iX, 0));
cvSetReal2D(A1_3, 0, 1, cvGetReal2D(xtilde, iX, 1)*cvGetReal2D(Xtilde, iX, 1));
cvSetReal2D(A1_3, 0, 2, cvGetReal2D(xtilde, iX, 1)*cvGetReal2D(Xtilde, iX, 2));
cvSetReal2D(A1_3, 0, 3, cvGetReal2D(xtilde, iX, 1));
// A2_1
cvSetReal2D(A2_1, 0, 0, cvGetReal2D(Xtilde, iX, 0));
cvSetReal2D(A2_1, 0, 1, cvGetReal2D(Xtilde, iX, 1));
cvSetReal2D(A2_1, 0, 2, cvGetReal2D(Xtilde, iX, 2));
cvSetReal2D(A2_1, 0, 3, 1);
// A1_3
cvSetReal2D(A2_3, 0, 0, -cvGetReal2D(xtilde, iX, 0)*cvGetReal2D(Xtilde, iX, 0));
cvSetReal2D(A2_3, 0, 1, -cvGetReal2D(xtilde, iX, 0)*cvGetReal2D(Xtilde, iX, 1));
cvSetReal2D(A2_3, 0, 2, -cvGetReal2D(xtilde, iX, 0)*cvGetReal2D(Xtilde, iX, 2));
cvSetReal2D(A2_3, 0, 3, -cvGetReal2D(xtilde, iX, 0));
SetSubMat(A1, 0, 4, A1_2); SetSubMat(A1, 0, 8, A1_3);
SetSubMat(A2, 0, 0, A2_1); SetSubMat(A2, 0, 8, A2_3);
SetSubMat(A, 2*iX, 0, A1);
SetSubMat(A, 2*iX+1, 0, A2);
cvReleaseMat(&A1);
cvReleaseMat(&A2);
cvReleaseMat(&A1_2);
cvReleaseMat(&A1_3);
cvReleaseMat(&A2_1);
cvReleaseMat(&A2_3);
}
CvMat *p = cvCreateMat(A->cols, 1, CV_32FC1);
LS_homogeneous(A, p);
cvSetReal2D(P, 0, 0, cvGetReal2D(p, 0, 0)); cvSetReal2D(P, 0, 1, cvGetReal2D(p, 1, 0)); cvSetReal2D(P, 0, 2, cvGetReal2D(p, 2, 0)); cvSetReal2D(P, 0, 3, cvGetReal2D(p, 3, 0));
cvSetReal2D(P, 1, 0, cvGetReal2D(p, 4, 0)); cvSetReal2D(P, 1, 1, cvGetReal2D(p, 5, 0)); cvSetReal2D(P, 1, 2, cvGetReal2D(p, 6, 0)); cvSetReal2D(P, 1, 3, cvGetReal2D(p, 7, 0));
cvSetReal2D(P, 2, 0, cvGetReal2D(p, 8, 0)); cvSetReal2D(P, 2, 1, cvGetReal2D(p, 9, 0)); cvSetReal2D(P, 2, 2, cvGetReal2D(p, 10, 0)); cvSetReal2D(P, 2, 3, cvGetReal2D(p, 11, 0));
//for (int i = 0; i < X->rows; i++)
//{
// CvMat *tX = cvCreateMat(4,1,CV_32FC1);
// cvSetReal2D(tX, 0, 0, cvGetReal2D(Xtilde, i, 0));
// cvSetReal2D(tX, 1, 0, cvGetReal2D(Xtilde, i, 1));
// cvSetReal2D(tX, 2, 0, cvGetReal2D(Xtilde, i, 2));
// cvSetReal2D(tX, 3, 0, 1);
// CvMat *tx = cvCreateMat(3,1, CV_32FC1);
// cvMatMul(P, tX, tx);
// ScalarMul(tx, 1/cvGetReal2D(tx, 2, 0), tx);
// PrintMat(tx, "tx");
// CvMat *ttx = cvCreateMat(2,1,CV_32FC1);
// cvSetReal2D(ttx, 0, 0, cvGetReal2D(xtilde, i, 0));
// cvSetReal2D(ttx, 1, 0, cvGetReal2D(xtilde, i, 1));
// PrintMat(ttx, "ttx");
//}
CvMat *temp34 = cvCreateMat(3,4,CV_32FC1);
CvMat *invT = cvCreateMat(3,3,CV_32FC1);
cvInvert(T, invT);
cvMatMul(invT, P, temp34);
cvMatMul(temp34, U, P);
ScalarMul(P, 1/cvGetReal2D(P, 2, 3), P);
CvMat *R = cvCreateMat(3,3, CV_32FC1);
CvMat *C = cvCreateMat(4,1, CV_32FC1);
//ScalarMul(P, -1, P);
cvDecomposeProjectionMatrix(P, K, R, C);
//cout << "det " << cvDet(R) << endl;
//PrintMat(C, "C");
//CvMat *P_ = cvCreateMat(3,4, CV_32FC1);
//CvMat *invK = cvCreateMat(3,3,CV_32FC1);
//cvInvert(K, invK);
//cvMatMul(invK, P, P_);
//CvMat *P1 = cvCreateMat(3,1,CV_32FC1);
//GetSubMatColwise(P_, 0, 0, P1);
//CvMat *R = cvCreateMat(3,3,CV_32FC1);
//GetSubMatColwise(P_, 0, 2, R);
//double norm = NormL2(P1);
//double determinant = cvDet(R);
//double sign = 1;
//if (determinant < 0)
// sign = -1;
//ScalarMul(P_,sign/norm, P);
//cvMatMul(K, P, P);
cvReleaseMat(&temp34);
cvReleaseMat(&invT);
//cvReleaseMat(&P_);
//cvReleaseMat(&invK);
//cvReleaseMat(&P1);
cvReleaseMat(&R);
cvReleaseMat(&Xtilde);
cvReleaseMat(&xtilde);
cvReleaseMat(&U);
cvReleaseMat(&T);
cvReleaseMat(&A);
cvReleaseMat(&p);
cvReleaseMat(&C);
return 1;
}
int DLT_ExtrinsicCameraParamEstimationWRansac(CvMat *X, CvMat *x, CvMat *K, CvMat &P, double ransacThreshold, int ransacMaxIter)
{
int min_set = 5;
if (X->rows < min_set)
return 0;
/////////////////////////////////////////////////////////////////
// Ransac
vector<int> vInlierIndex, vOutlierIndex;
vInlierIndex.clear();
vOutlierIndex.clear();
vector<int> vInlier, vOutlier;
int maxInlier = 0;
CvMat *X_homoT = cvCreateMat(4, X->rows, CV_32FC1);
CvMat *X_homo = cvCreateMat(X->rows, 4, CV_32FC1);
CvMat *x_homoT = cvCreateMat(3, x->rows, CV_32FC1);
CvMat *x_homo = cvCreateMat(x->rows, 3, CV_32FC1);
Inhomo2Homo(X, X_homo);
cvTranspose(X_homo, X_homoT);
Inhomo2Homo(x, x_homo);
cvTranspose(x_homo, x_homoT);
int nIter = 0;
for (int iRansacIter = 0; iRansacIter < ransacMaxIter; iRansacIter++)
{
nIter++;
if (nIter > 1e+4)
return 0;
int *randIdx = (int *) malloc(min_set * sizeof(int));
for (int iIdx = 0; iIdx < min_set; iIdx++)
randIdx[iIdx] = rand()%X->rows;
CvMat *randx = cvCreateMat(min_set, 2, CV_32FC1);
CvMat *randX = cvCreateMat(min_set, 3, CV_32FC1);
CvMat *randP = cvCreateMat(3,4,CV_32FC1);
for (int iIdx = 0; iIdx < min_set; iIdx++)
{
cvSetReal2D(randx, iIdx, 0, cvGetReal2D(x, randIdx[iIdx], 0));
cvSetReal2D(randx, iIdx, 1, cvGetReal2D(x, randIdx[iIdx], 1));
cvSetReal2D(randX, iIdx, 0, cvGetReal2D(X, randIdx[iIdx], 0));
cvSetReal2D(randX, iIdx, 1, cvGetReal2D(X, randIdx[iIdx], 1));
cvSetReal2D(randX, iIdx, 2, cvGetReal2D(X, randIdx[iIdx], 2));
}
free(randIdx);
DLT_ExtrinsicCameraParamEstimation(randX, randx, K, randP);
CvMat *H = cvCreateMat(4, 4, CV_32FC1); CvMat *HX = cvCreateMat(randX->rows, randX->cols, CV_32FC1);
cvSetIdentity(H);
SetSubMat(H, 0, 0, randP);
Pxx_inhomo(H, randX, HX);
bool isFront = true;
for (int i = 0; i < min_set; i++)
{
if (cvGetReal2D(HX, i, 2) < 0)
isFront = false;
}
cvReleaseMat(&H);
cvReleaseMat(&HX);
if (!isFront)
{
cvReleaseMat(&randx);
cvReleaseMat(&randX);
cvReleaseMat(&randP);
iRansacIter--;
continue;
}
vInlier.clear();
vOutlier.clear();
for (int ip = 0; ip < X->rows; ip++)
{
CvMat *reproj = cvCreateMat(3,1,CV_32FC1);
CvMat *homo_X = cvCreateMat(4,1,CV_32FC1);
cvSetReal2D(homo_X, 0, 0, cvGetReal2D(X, ip, 0));
cvSetReal2D(homo_X, 1, 0, cvGetReal2D(X, ip, 1));
cvSetReal2D(homo_X, 2, 0, cvGetReal2D(X, ip, 2));
cvSetReal2D(homo_X, 3, 0, 1);
cvMatMul(randP, homo_X, reproj);
double u = cvGetReal2D(reproj, 0, 0)/cvGetReal2D(reproj, 2, 0);
double v = cvGetReal2D(reproj, 1, 0)/cvGetReal2D(reproj, 2, 0);
//if ((ip == randIdx[0]) || (ip == randIdx[1]) || (ip == randIdx[2]) || (ip == randIdx[3]))
// cout << cvGetReal2D(x, ip, 0) << " " << u << " " << cvGetReal2D(x, ip, 1) << " " << v << endl;
double dist = (u-cvGetReal2D(x, ip, 0))*(u-cvGetReal2D(x, ip, 0))+(v-cvGetReal2D(x, ip, 1))*(v-cvGetReal2D(x, ip, 1));
if (dist < ransacThreshold)
{
vInlier.push_back(ip);
}
else
{
vOutlier.push_back(ip);
}
cvReleaseMat(&reproj);
cvReleaseMat(&homo_X);
}
// Distance function
//CvMat *x_ = cvCreateMat(3, X->rows, CV_32FC1);
//CvMat *e = cvCreateMat(3, X->rows, CV_32FC1);
//cvMatMul(randP, X_homoT, x_);
//NormalizingByRow(x_, 2);
//cvSub(x_homoT, x_, e);
//for (int ie = 0; ie < e->cols; ie++)
//{
// CvMat *ei = cvCreateMat(3,1,CV_32FC1);
// CvMat *xi = cvCreateMat(3,1, CV_32FC1);
// GetSubMatColwise(x_homoT, ie, ie, xi);
// GetSubMatColwise(e, ie, ie, ei);
// double norm = NormL2(ei);
// double denorm = NormL2(xi);
// double d = norm;
// if (d < ransacThreshold)
// vInlier.push_back(ie);
// else
// vOutlier.push_back(ie);
// cvReleaseMat(&ei);
// cvReleaseMat(&xi);
//}
//if (vInlier.size() > maxInlier)
//{
// maxInlier = vInlier.size();
// P = *cvCloneMat(randP);
// vInlierIndex = vInlier;
// vOutlierIndex = vOutlier;
//}
//cvReleaseMat(&x_);
//cvReleaseMat(&e);
cvReleaseMat(&randx);
cvReleaseMat(&randX);
cvReleaseMat(&randP);
}
cvReleaseMat(&X_homoT);
cvReleaseMat(&X_homo);
cvReleaseMat(&x_homoT);
cvReleaseMat(&X_homo);
if (vInlierIndex.size() < min_set)
return 0;
cout << "Number of features to do DLT camera pose estimation: " << vInlierIndex.size() << endl;
return 1;
}
int DLT_ExtrinsicCameraParamEstimationWRansac_EPNP(CvMat *X, CvMat *x, CvMat *K, CvMat &P, double ransacThreshold, int ransacMaxIter)
{
int min_set = 4;
if (X->rows < min_set)
return 0;
/////////////////////////////////////////////////////////////////
// Ransac
vector<int> vInlierIndex, vOutlierIndex;
vInlierIndex.clear();
vOutlierIndex.clear();
vector<int> vInlier, vOutlier;
int maxInlier = 0;
CvMat *X_homoT = cvCreateMat(4, X->rows, CV_32FC1);
CvMat *X_homo = cvCreateMat(X->rows, 4, CV_32FC1);
CvMat *x_homoT = cvCreateMat(3, x->rows, CV_32FC1);
CvMat *x_homo = cvCreateMat(x->rows, 3, CV_32FC1);
Inhomo2Homo(X, X_homo);
cvTranspose(X_homo, X_homoT);
Inhomo2Homo(x, x_homo);
cvTranspose(x_homo, x_homoT);
for (int iRansacIter = 0; iRansacIter < ransacMaxIter; iRansacIter++)
{
int *randIdx = (int *) malloc(min_set * sizeof(int));
for (int iIdx = 0; iIdx < min_set; iIdx++)
randIdx[iIdx] = rand()%X->rows;
CvMat *randx = cvCreateMat(min_set, 2, CV_32FC1);
CvMat *randX = cvCreateMat(min_set, 3, CV_32FC1);
CvMat *randP = cvCreateMat(3,4,CV_32FC1);
for (int iIdx = 0; iIdx < min_set; iIdx++)
{
cvSetReal2D(randx, iIdx, 0, cvGetReal2D(x, randIdx[iIdx], 0));
cvSetReal2D(randx, iIdx, 1, cvGetReal2D(x, randIdx[iIdx], 1));
cvSetReal2D(randX, iIdx, 0, cvGetReal2D(X, randIdx[iIdx], 0));
cvSetReal2D(randX, iIdx, 1, cvGetReal2D(X, randIdx[iIdx], 1));
cvSetReal2D(randX, iIdx, 2, cvGetReal2D(X, randIdx[iIdx], 2));
}
//DLT_ExtrinsicCameraParamEstimation(randX, randx, K, randP);
EPNP_ExtrinsicCameraParamEstimation(randX, randx, K, randP);
vInlier.clear();
vOutlier.clear();
for (int ip = 0; ip < X->rows; ip++)
{
CvMat *reproj = cvCreateMat(3,1,CV_32FC1);
CvMat *homo_X = cvCreateMat(4,1,CV_32FC1);
cvSetReal2D(homo_X, 0, 0, cvGetReal2D(X, ip, 0));
cvSetReal2D(homo_X, 1, 0, cvGetReal2D(X, ip, 1));
cvSetReal2D(homo_X, 2, 0, cvGetReal2D(X, ip, 2));
cvSetReal2D(homo_X, 3, 0, 1);
cvMatMul(randP, homo_X, reproj);
double u = cvGetReal2D(reproj, 0, 0)/cvGetReal2D(reproj, 2, 0);
double v = cvGetReal2D(reproj, 1, 0)/cvGetReal2D(reproj, 2, 0);
//if ((ip == randIdx[0]) || (ip == randIdx[1]) || (ip == randIdx[2]) || (ip == randIdx[3]))
// cout << cvGetReal2D(x, ip, 0) << " " << u << " " << cvGetReal2D(x, ip, 1) << " " << v << endl;
double dist = (u-cvGetReal2D(x, ip, 0))*(u-cvGetReal2D(x, ip, 0))+(v-cvGetReal2D(x, ip, 1))*(v-cvGetReal2D(x, ip, 1));
if (dist < ransacThreshold)
{
vInlier.push_back(ip);
}
else
{
vOutlier.push_back(ip);
}
cvReleaseMat(&reproj);
cvReleaseMat(&homo_X);
}
free(randIdx);
if (vInlier.size() > maxInlier)
{
maxInlier = vInlier.size();
P = *cvCloneMat(randP);
vInlierIndex = vInlier;
vOutlierIndex = vOutlier;
}
cvReleaseMat(&randx);
cvReleaseMat(&randX);
cvReleaseMat(&randP);
}
cvReleaseMat(&X_homoT);
cvReleaseMat(&X_homo);
cvReleaseMat(&x_homoT);
cvReleaseMat(&X_homo);
if (vInlierIndex.size() < 20)
return 0;
cout << "Number of features to do DLT camera pose estimation: " << vInlierIndex.size() << endl;
return 1;
}
int DLT_ExtrinsicCameraParamEstimationWRansac_EPNP_mem(CvMat *X, CvMat *x, CvMat *K, CvMat *P, double ransacThreshold, int ransacMaxIter)
{
int min_set = 4;
if (X->rows < min_set)
return 0;
/////////////////////////////////////////////////////////////////
// Ransac
vector<int> vInlierIndex, vOutlierIndex;
vInlierIndex.clear();
vOutlierIndex.clear();
vector<int> vInlier, vOutlier;
int maxInlier = 0;
CvMat *X_homoT = cvCreateMat(4, X->rows, CV_32FC1);
CvMat *X_homo = cvCreateMat(X->rows, 4, CV_32FC1);
CvMat *x_homoT = cvCreateMat(3, x->rows, CV_32FC1);
CvMat *x_homo = cvCreateMat(x->rows, 3, CV_32FC1);
Inhomo2Homo(X, X_homo);
cvTranspose(X_homo, X_homoT);
Inhomo2Homo(x, x_homo);
cvTranspose(x_homo, x_homoT);
CvMat *randx = cvCreateMat(min_set, 2, CV_32FC1);
CvMat *randX = cvCreateMat(min_set, 3, CV_32FC1);
CvMat *randP = cvCreateMat(3,4,CV_32FC1);
int *randIdx = (int *) malloc(min_set * sizeof(int));
CvMat *reproj = cvCreateMat(3,1,CV_32FC1);
CvMat *homo_X = cvCreateMat(4,1,CV_32FC1);
for (int iRansacIter = 0; iRansacIter < ransacMaxIter; iRansacIter++)
{
for (int iIdx = 0; iIdx < min_set; iIdx++)
randIdx[iIdx] = rand()%X->rows;
for (int iIdx = 0; iIdx < min_set; iIdx++)
{
cvSetReal2D(randx, iIdx, 0, cvGetReal2D(x, randIdx[iIdx], 0));
cvSetReal2D(randx, iIdx, 1, cvGetReal2D(x, randIdx[iIdx], 1));
cvSetReal2D(randX, iIdx, 0, cvGetReal2D(X, randIdx[iIdx], 0));
cvSetReal2D(randX, iIdx, 1, cvGetReal2D(X, randIdx[iIdx], 1));
cvSetReal2D(randX, iIdx, 2, cvGetReal2D(X, randIdx[iIdx], 2));
}
EPNP_ExtrinsicCameraParamEstimation(randX, randx, K, randP);
vInlier.clear();
vOutlier.clear();
for (int ip = 0; ip < X->rows; ip++)
{
cvSetReal2D(homo_X, 0, 0, cvGetReal2D(X, ip, 0));
cvSetReal2D(homo_X, 1, 0, cvGetReal2D(X, ip, 1));
cvSetReal2D(homo_X, 2, 0, cvGetReal2D(X, ip, 2));
cvSetReal2D(homo_X, 3, 0, 1);
cvMatMul(randP, homo_X, reproj);
double u = cvGetReal2D(reproj, 0, 0)/cvGetReal2D(reproj, 2, 0);
double v = cvGetReal2D(reproj, 1, 0)/cvGetReal2D(reproj, 2, 0);
double dist = sqrt((u-cvGetReal2D(x, ip, 0))*(u-cvGetReal2D(x, ip, 0))+(v-cvGetReal2D(x, ip, 1))*(v-cvGetReal2D(x, ip, 1)));
if (dist < ransacThreshold)
{
vInlier.push_back(ip);
}
else
{
vOutlier.push_back(ip);
}
}
if (vInlier.size() > maxInlier)
{
maxInlier = vInlier.size();
SetSubMat(P, 0, 0, randP);
vInlierIndex = vInlier;
vOutlierIndex = vOutlier;
}
if (vInlier.size() > X->rows * 0.8)
{
break;
}
}
CvMat *Xin = cvCreateMat(vInlierIndex.size(), 3, CV_32FC1);
CvMat *xin = cvCreateMat(vInlierIndex.size(), 2, CV_32FC1);
for (int iInlier = 0; iInlier < vInlierIndex.size(); iInlier++)
{
cvSetReal2D(Xin, iInlier, 0, cvGetReal2D(X, vInlierIndex[iInlier], 0));
cvSetReal2D(Xin, iInlier, 1, cvGetReal2D(X, vInlierIndex[iInlier], 1));
cvSetReal2D(Xin, iInlier, 2, cvGetReal2D(X, vInlierIndex[iInlier], 2));
cvSetReal2D(xin, iInlier, 0, cvGetReal2D(x, vInlierIndex[iInlier], 0));
cvSetReal2D(xin, iInlier, 1, cvGetReal2D(x, vInlierIndex[iInlier], 1));
}
EPNP_ExtrinsicCameraParamEstimation(Xin, xin, K, P);
cvReleaseMat(&Xin);
cvReleaseMat(&xin);
cvReleaseMat(&reproj);
cvReleaseMat(&homo_X);
free(randIdx);
cvReleaseMat(&randx);
cvReleaseMat(&randX);
cvReleaseMat(&randP);
cvReleaseMat(&X_homoT);
cvReleaseMat(&x_homo);
cvReleaseMat(&x_homoT);
cvReleaseMat(&X_homo);
if (vInlierIndex.size() < 40)
return 0;
cout << "Number of features ePnP: " << vInlierIndex.size() << endl;
return vInlierIndex.size();
}
int DLT_ExtrinsicCameraParamEstimationWRansac_EPNP_mem_AD(CvMat *X, CvMat *x, CvMat *K, CvMat *P, double ransacThreshold, int ransacMaxIter, vector<int> &vInlier1)
{
int min_set = 4;
if (X->rows < min_set)
return 0;
/////////////////////////////////////////////////////////////////
// Ransac
vector<int> vInlierIndex, vOutlierIndex;
vInlierIndex.clear();
vOutlierIndex.clear();
vector<int> vInlier, vOutlier;
int maxInlier = 0;
CvMat *X_homoT = cvCreateMat(4, X->rows, CV_32FC1);
CvMat *X_homo = cvCreateMat(X->rows, 4, CV_32FC1);
CvMat *x_homoT = cvCreateMat(3, x->rows, CV_32FC1);
CvMat *x_homo = cvCreateMat(x->rows, 3, CV_32FC1);
Inhomo2Homo(X, X_homo);
cvTranspose(X_homo, X_homoT);
Inhomo2Homo(x, x_homo);
cvTranspose(x_homo, x_homoT);
CvMat *randx = cvCreateMat(min_set, 2, CV_32FC1);
CvMat *randX = cvCreateMat(min_set, 3, CV_32FC1);
CvMat *randP = cvCreateMat(3,4,CV_32FC1);
int *randIdx = (int *) malloc(min_set * sizeof(int));
CvMat *reproj = cvCreateMat(3,1,CV_32FC1);
CvMat *homo_X = cvCreateMat(4,1,CV_32FC1);
for (int iRansacIter = 0; iRansacIter < ransacMaxIter; iRansacIter++)
{
for (int iIdx = 0; iIdx < min_set; iIdx++)
randIdx[iIdx] = rand()%X->rows;
for (int iIdx = 0; iIdx < min_set; iIdx++)
{
cvSetReal2D(randx, iIdx, 0, cvGetReal2D(x, randIdx[iIdx], 0));
cvSetReal2D(randx, iIdx, 1, cvGetReal2D(x, randIdx[iIdx], 1));
cvSetReal2D(randX, iIdx, 0, cvGetReal2D(X, randIdx[iIdx], 0));
cvSetReal2D(randX, iIdx, 1, cvGetReal2D(X, randIdx[iIdx], 1));
cvSetReal2D(randX, iIdx, 2, cvGetReal2D(X, randIdx[iIdx], 2));
}
EPNP_ExtrinsicCameraParamEstimation(randX, randx, K, randP);
vInlier.clear();
vOutlier.clear();
for (int ip = 0; ip < X->rows; ip++)
{
cvSetReal2D(homo_X, 0, 0, cvGetReal2D(X, ip, 0));
cvSetReal2D(homo_X, 1, 0, cvGetReal2D(X, ip, 1));
cvSetReal2D(homo_X, 2, 0, cvGetReal2D(X, ip, 2));
cvSetReal2D(homo_X, 3, 0, 1);
cvMatMul(randP, homo_X, reproj);
double u = cvGetReal2D(reproj, 0, 0)/cvGetReal2D(reproj, 2, 0);
double v = cvGetReal2D(reproj, 1, 0)/cvGetReal2D(reproj, 2, 0);
double dist = sqrt((u-cvGetReal2D(x, ip, 0))*(u-cvGetReal2D(x, ip, 0))+(v-cvGetReal2D(x, ip, 1))*(v-cvGetReal2D(x, ip, 1)));
if (dist < ransacThreshold)
{
vInlier.push_back(ip);
}
else
{
vOutlier.push_back(ip);
}
}
if (vInlier.size() > maxInlier)
{
maxInlier = vInlier.size();
SetSubMat(P, 0, 0, randP);
vInlierIndex = vInlier;
vOutlierIndex = vOutlier;
}
if (vInlier.size() > X->rows * 0.8)
{
break;
}
}
CvMat *Xin = cvCreateMat(vInlierIndex.size(), 3, CV_32FC1);
CvMat *xin = cvCreateMat(vInlierIndex.size(), 2, CV_32FC1);
for (int iInlier = 0; iInlier < vInlierIndex.size(); iInlier++)
{
cvSetReal2D(Xin, iInlier, 0, cvGetReal2D(X, vInlierIndex[iInlier], 0));
cvSetReal2D(Xin, iInlier, 1, cvGetReal2D(X, vInlierIndex[iInlier], 1));
cvSetReal2D(Xin, iInlier, 2, cvGetReal2D(X, vInlierIndex[iInlier], 2));
cvSetReal2D(xin, iInlier, 0, cvGetReal2D(x, vInlierIndex[iInlier], 0));
cvSetReal2D(xin, iInlier, 1, cvGetReal2D(x, vInlierIndex[iInlier], 1));
}
EPNP_ExtrinsicCameraParamEstimation(Xin, xin, K, P);
cvReleaseMat(&Xin);
cvReleaseMat(&xin);
cvReleaseMat(&reproj);
cvReleaseMat(&homo_X);
free(randIdx);
cvReleaseMat(&randx);
cvReleaseMat(&randX);
cvReleaseMat(&randP);
cvReleaseMat(&X_homoT);
cvReleaseMat(&x_homo);
cvReleaseMat(&x_homoT);
cvReleaseMat(&X_homo);
vInlier1 = vInlierIndex;
if (vInlierIndex.size() < 40)
return 0;
cout << "Number of features ePnP: " << vInlierIndex.size() << endl;
return vInlierIndex.size();
}
int DLT_ExtrinsicCameraParamEstimationWRansac_EPNP_mem_abs(CvMat *X, CvMat *x, CvMat *K, CvMat *P, double ransacThreshold, int ransacMaxIter, vector<int> &vInlierIndex)
{
int min_set = 4;
if (X->rows < min_set)
return 0;
/////////////////////////////////////////////////////////////////
// Ransac
vector<int> vOutlierIndex;
vInlierIndex.clear();
vOutlierIndex.clear();
vector<int> vInlier, vOutlier;
int maxInlier = 0;
CvMat *X_homoT = cvCreateMat(4, X->rows, CV_32FC1);
CvMat *X_homo = cvCreateMat(X->rows, 4, CV_32FC1);
CvMat *x_homoT = cvCreateMat(3, x->rows, CV_32FC1);
CvMat *x_homo = cvCreateMat(x->rows, 3, CV_32FC1);
Inhomo2Homo(X, X_homo);
cvTranspose(X_homo, X_homoT);
Inhomo2Homo(x, x_homo);
cvTranspose(x_homo, x_homoT);
CvMat *randx = cvCreateMat(min_set, 2, CV_32FC1);
CvMat *randX = cvCreateMat(min_set, 3, CV_32FC1);
CvMat *randP = cvCreateMat(3,4,CV_32FC1);
int *randIdx = (int *) malloc(min_set * sizeof(int));
CvMat *reproj = cvCreateMat(3,1,CV_32FC1);
CvMat *homo_X = cvCreateMat(4,1,CV_32FC1);
for (int iRansacIter = 0; iRansacIter < ransacMaxIter; iRansacIter++)
{
for (int iIdx = 0; iIdx < min_set; iIdx++)
randIdx[iIdx] = rand()%X->rows;
for (int iIdx = 0; iIdx < min_set; iIdx++)
{
cvSetReal2D(randx, iIdx, 0, cvGetReal2D(x, randIdx[iIdx], 0));
cvSetReal2D(randx, iIdx, 1, cvGetReal2D(x, randIdx[iIdx], 1));
cvSetReal2D(randX, iIdx, 0, cvGetReal2D(X, randIdx[iIdx], 0));
cvSetReal2D(randX, iIdx, 1, cvGetReal2D(X, randIdx[iIdx], 1));
cvSetReal2D(randX, iIdx, 2, cvGetReal2D(X, randIdx[iIdx], 2));
}
EPNP_ExtrinsicCameraParamEstimation(randX, randx, K, randP);
vInlier.clear();
vOutlier.clear();
for (int ip = 0; ip < X->rows; ip++)
{
cvSetReal2D(homo_X, 0, 0, cvGetReal2D(X, ip, 0));
cvSetReal2D(homo_X, 1, 0, cvGetReal2D(X, ip, 1));
cvSetReal2D(homo_X, 2, 0, cvGetReal2D(X, ip, 2));
cvSetReal2D(homo_X, 3, 0, 1);
cvMatMul(randP, homo_X, reproj);
double u = cvGetReal2D(reproj, 0, 0)/cvGetReal2D(reproj, 2, 0);
double v = cvGetReal2D(reproj, 1, 0)/cvGetReal2D(reproj, 2, 0);
double dist = sqrt((u-cvGetReal2D(x, ip, 0))*(u-cvGetReal2D(x, ip, 0))+(v-cvGetReal2D(x, ip, 1))*(v-cvGetReal2D(x, ip, 1)));
if (dist < ransacThreshold)
{
vInlier.push_back(ip);
}
else
{
vOutlier.push_back(ip);
}
}
if (vInlier.size() > maxInlier)
{
maxInlier = vInlier.size();
SetSubMat(P, 0, 0, randP);
vInlierIndex = vInlier;
vOutlierIndex = vOutlier;
}
//if (vInlier.size() > X->rows * 0.8)
//{
// break;
//}
}
CvMat *Xin = cvCreateMat(vInlierIndex.size(), 3, CV_32FC1);
CvMat *xin = cvCreateMat(vInlierIndex.size(), 2, CV_32FC1);
for (int iInlier = 0; iInlier < vInlierIndex.size(); iInlier++)
{
cvSetReal2D(Xin, iInlier, 0, cvGetReal2D(X, vInlierIndex[iInlier], 0));
cvSetReal2D(Xin, iInlier, 1, cvGetReal2D(X, vInlierIndex[iInlier], 1));
cvSetReal2D(Xin, iInlier, 2, cvGetReal2D(X, vInlierIndex[iInlier], 2));
cvSetReal2D(xin, iInlier, 0, cvGetReal2D(x, vInlierIndex[iInlier], 0));
cvSetReal2D(xin, iInlier, 1, cvGetReal2D(x, vInlierIndex[iInlier], 1));
}
EPNP_ExtrinsicCameraParamEstimation(Xin, xin, K, P);
cvReleaseMat(&Xin);
cvReleaseMat(&xin);
cvReleaseMat(&reproj);
cvReleaseMat(&homo_X);
free(randIdx);
cvReleaseMat(&randx);
cvReleaseMat(&randX);
cvReleaseMat(&randP);
cvReleaseMat(&X_homoT);
cvReleaseMat(&x_homo);
cvReleaseMat(&x_homoT);
cvReleaseMat(&X_homo);
//if (vInlierIndex.size() < 20)
// return 0;
cout << "Number of features to do ePNP camera pose estimation: " << vInlierIndex.size() << endl;
return vInlierIndex.size();
}
int DLT_ExtrinsicCameraParamEstimationWRansac_EPNP_face(CvMat *X, CvMat *x, CvMat *K, CvMat &P)
{
CvMat *P_ = cvCreateMat(3,4,CV_32FC1);
EPNP_ExtrinsicCameraParamEstimation(X, x, K, P_);
P = *cvCloneMat(P_);
cvReleaseMat(&P_);
return 1;
}
int DLT_ExtrinsicCameraParamEstimationWRansac_KRT(CvMat *X, CvMat *x, CvMat *K, CvMat &P, double ransacThreshold, int ransacMaxIter)
{
if (X->rows < 6)
return 0;
/////////////////////////////////////////////////////////////////
// Ransac
vector<int> vInlierIndex, vOutlierIndex;
vInlierIndex.clear();
vOutlierIndex.clear();
vector<int> vInlier, vOutlier;
int maxInlier = 0;
CvMat *X_homoT = cvCreateMat(4, X->rows, CV_32FC1);
CvMat *X_homo = cvCreateMat(X->rows, 4, CV_32FC1);
CvMat *x_homoT = cvCreateMat(3, x->rows, CV_32FC1);
CvMat *x_homo = cvCreateMat(x->rows, 3, CV_32FC1);
Inhomo2Homo(X, X_homo);
cvTranspose(X_homo, X_homoT);
Inhomo2Homo(x, x_homo);
cvTranspose(x_homo, x_homoT);
for (int iRansacIter = 0; iRansacIter < ransacMaxIter; iRansacIter++)
{
int *randIdx = (int *) malloc(6 * sizeof(int));
for (int iIdx = 0; iIdx < 6; iIdx++)
randIdx[iIdx] = rand()%X->rows;
CvMat *randx = cvCreateMat(6, 2, CV_32FC1);
CvMat *randX = cvCreateMat(6, 3, CV_32FC1);
CvMat *randP = cvCreateMat(3,4,CV_32FC1);
for (int iIdx = 0; iIdx < 6; iIdx++)
{
cvSetReal2D(randx, iIdx, 0, cvGetReal2D(x, randIdx[iIdx], 0));
cvSetReal2D(randx, iIdx, 1, cvGetReal2D(x, randIdx[iIdx], 1));
cvSetReal2D(randX, iIdx, 0, cvGetReal2D(X, randIdx[iIdx], 0));
cvSetReal2D(randX, iIdx, 1, cvGetReal2D(X, randIdx[iIdx], 1));
cvSetReal2D(randX, iIdx, 2, cvGetReal2D(X, randIdx[iIdx], 2));
}
free(randIdx);
CvMat *K_ = cvCreateMat(3,3,CV_32FC1);
DLT_ExtrinsicCameraParamEstimation_KRT(randX, randx, K_, randP);
double k33 = cvGetReal2D(K_, 2, 2);
ScalarMul(K_, 1/k33, K_);
CvMat *H = cvCreateMat(4, 4, CV_32FC1); CvMat *HX = cvCreateMat(randX->rows, randX->cols, CV_32FC1);
cvSetIdentity(H);
SetSubMat(H, 0, 0, randP);
Pxx_inhomo(H, randX, HX);
bool isFront = true;
for (int i = 0; i < 6; i++)
{
if (cvGetReal2D(HX, i, 2) < 0)
isFront = false;
}
cvReleaseMat(&H);
cvReleaseMat(&HX);
if ((!isFront) || (cvGetReal2D(K, 0,0) < 0))
{
cvReleaseMat(&randx);
cvReleaseMat(&randX);
cvReleaseMat(&randP);
iRansacIter--;
continue;
}
vInlier.clear();
vOutlier.clear();
// Distance function
CvMat *x_ = cvCreateMat(3, X->rows, CV_32FC1);
CvMat *e = cvCreateMat(3, X->rows, CV_32FC1);
cvMatMul(randP, X_homoT, x_);
NormalizingByRow(x_, 2);
cvSub(x_homoT, x_, e);
for (int ie = 0; ie < e->cols; ie++)
{
CvMat *ei = cvCreateMat(3,1,CV_32FC1);
CvMat *xi = cvCreateMat(3,1, CV_32FC1);
GetSubMatColwise(x_homoT, ie, ie, xi);
GetSubMatColwise(e, ie, ie, ei);
double norm = NormL2(ei);
double denorm = NormL2(xi);
double d = norm;
if (d < ransacThreshold)
vInlier.push_back(ie);
else
vOutlier.push_back(ie);
cvReleaseMat(&ei);
cvReleaseMat(&xi);
}
if (vInlier.size() > maxInlier)
{
maxInlier = vInlier.size();
P = *cvCloneMat(randP);
K = cvCloneMat(K_);
vInlierIndex = vInlier;
vOutlierIndex = vOutlier;
}
cvReleaseMat(&x_);
cvReleaseMat(&e);
cvReleaseMat(&randx);
cvReleaseMat(&randX);
cvReleaseMat(&randP);
cvReleaseMat(&K_);
}
cvReleaseMat(&X_homoT);
cvReleaseMat(&X_homo);
cvReleaseMat(&x_homoT);
cvReleaseMat(&X_homo);
if (vInlierIndex.size() < 10)
return 0;
cout << "Number of features to do DLT camera pose estimation: " << vInlierIndex.size() << endl;
return 1;
}
int DLT_ExtrinsicCameraParamEstimation_KRT(CvMat *X, CvMat *x, CvMat *K, CvMat &P)
{
if (X->rows < 6)
return 0;
CvMat *P_ = cvCreateMat(3,4,CV_32FC1);
DLT_ExtrinsicCameraParamEstimation_KRT(X, x, K, P_);
P = *cvCloneMat(P_);
return 1;
}
void SparseBundleAdjustment_MOT(vector<Feature> vFeature, vector<int> vUsedFrame, vector<CvMat *> &cP, CvMat *X, CvMat *K, vector<int> visibleStructureID)
{
//PrintAlgorithm("Sparse bundle adjustment motion only");
//vector<double> cameraParameter, feature2DParameter;
//vector<char> vMask;
//double *dCovFeatures = 0;
//AdditionalData adata;// focal_x focal_y princ_x princ_y
//double intrinsic[4];
//intrinsic[0] = cvGetReal2D(K, 0, 0);
//intrinsic[1] = cvGetReal2D(K, 1, 1);
//intrinsic[2] = cvGetReal2D(K, 0, 2);
//intrinsic[3] = cvGetReal2D(K, 1, 2);
//adata.intrinsic = intrinsic;
//GetParameterForSBA(vFeature, vUsedFrame, cP, X, K, visibleStructureID, cameraParameter, feature2DParameter, vMask);
//double nCameraParam = 7;
//int nFeatures = vFeature.size();
//int nFrames = vUsedFrame.size();
//char *dVMask = (char *) malloc(vMask.size() * sizeof(char));
//double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double));
//double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double));
//
//for (int i = 0; i < cameraParameter.size(); i++)
// dCameraParameter[i] = cameraParameter[i];
//for (int i = 0; i < vMask.size(); i++)
// dVMask[i] = vMask[i];
//for (int i = 0; i < feature2DParameter.size(); i++)
// dFeature2DParameter[i] = feature2DParameter[i];
//adata.XYZ = &(dCameraParameter[7*vUsedFrame.size()]);
//double opt[5];
//opt[0] = 1e-3;
//opt[1] = 1e-12;
//opt[2] = 1e-12;
//opt[3] = 1e-12;
//opt[4] = 0;
//double info[12];
//sba_mot_levmar(visibleStructureID.size(), vUsedFrame.size(), 1, dVMask, dCameraParameter, 7, dFeature2DParameter, dCovFeatures, 2, Projection3Donto2D_MOT, NULL, &adata,
// 1e+3, 0, opt, info);
//PrintSBAInfo(info);
//RetrieveParameterFromSBA(dCameraParameter, K, cP, X, visibleStructureID);
//free(dVMask);
//free(dFeature2DParameter);
//free(dCameraParameter);
}
void SparseBundleAdjustment_MOTSTR(vector<Feature> vFeature, vector<int> vUsedFrame, vector<CvMat *> &cP, CvMat *X, CvMat *K, vector<int> visibleStructureID)
{
//PrintAlgorithm("Sparse bundle adjustment motion and structure");
//vector<double> cameraParameter, feature2DParameter;
//vector<char> vMask;
//double *dCovFeatures = 0;
//AdditionalData adata;// focal_x focal_y princ_x princ_y
//double intrinsic[4];
//intrinsic[0] = cvGetReal2D(K, 0, 0);
//intrinsic[1] = cvGetReal2D(K, 1, 1);
//intrinsic[2] = cvGetReal2D(K, 0, 2);
//intrinsic[3] = cvGetReal2D(K, 1, 2);
//adata.intrinsic = intrinsic;
//GetParameterForSBA(vFeature, vUsedFrame, cP, X, K, visibleStructureID, cameraParameter, feature2DParameter, vMask);
//int NZ = 0;
//for (int i = 0; i < vMask.size(); i++)
//{
// if (vMask[i])
// NZ++;
//}
//double nCameraParam = 7;
//int nFeatures = vFeature.size();
//int nFrames = vUsedFrame.size();
//char *dVMask = (char *) malloc(vMask.size() * sizeof(char));
//double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double));
//double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double));
//for (int i = 0; i < cameraParameter.size(); i++)
// dCameraParameter[i] = cameraParameter[i];
//for (int i = 0; i < vMask.size(); i++)
// dVMask[i] = vMask[i];
//for (int i = 0; i < feature2DParameter.size(); i++)
// dFeature2DParameter[i] = feature2DParameter[i];
//double opt[5];
//opt[0] = 1e-3;
//opt[1] = 1e-5;//1e-12;
//opt[2] = 1e-5;//1e-12;
//opt[3] = 1e-5;//1e-12;
//opt[4] = 0;
//double info[12];
//sba_motstr_levmar(visibleStructureID.size(), 0, vUsedFrame.size(), 1, dVMask, dCameraParameter, nCameraParam, 3, dFeature2DParameter, dCovFeatures, 2, Projection3Donto2D_MOTSTR, NULL, &adata,
// 1e+3, 0, opt, info);
//PrintSBAInfo(info);
//RetrieveParameterFromSBA(dCameraParameter, K, cP, X, visibleStructureID);
//free(dVMask);
//free(dFeature2DParameter);
//free(dCameraParameter);
}
void SparseBundleAdjustment_MOTSTR(vector<Feature> vFeature, vector<int> vUsedFrame, vector<CvMat *> &cP, CvMat *X, vector<Camera> vCamera, vector<int> visibleStructureID)
{
PrintAlgorithm("Sparse bundle adjustment motion and structure");
vector<double> cameraParameter, feature2DParameter;
vector<char> vMask;
double *dCovFeatures = 0;
AdditionalData adata;// focal_x focal_y princ_x princ_y
for (int iCamera = 0; iCamera < vCamera.size(); iCamera++)
{
double *intrinsic = (double *) malloc(4 * sizeof(double));
intrinsic[0] = cvGetReal2D(vCamera[iCamera].K, 0, 0);
intrinsic[1] = cvGetReal2D(vCamera[iCamera].K, 1, 1);
intrinsic[2] = cvGetReal2D(vCamera[iCamera].K, 0, 2);
intrinsic[3] = cvGetReal2D(vCamera[iCamera].K, 1, 2);
adata.vIntrinsic.push_back(intrinsic);
}
int max_nFrames = 0;
for (int iCamera = 0; iCamera < vCamera.size(); iCamera++)
{
for (int iFrame = 0; iFrame < vCamera[iCamera].vTakenFrame.size(); iFrame++)
{
if (vCamera[iCamera].vTakenFrame[iFrame] > max_nFrames)
max_nFrames = vCamera[iCamera].vTakenFrame[iFrame];
}
}
max_nFrames++;
adata.max_nFrames = max_nFrames;
adata.vUsedFrame = vUsedFrame;
GetParameterForSBA(vFeature, vUsedFrame, cP, X, vCamera, max_nFrames, visibleStructureID, cameraParameter, feature2DParameter, vMask);
int NZ = 0;
for (int i = 0; i < vMask.size(); i++)
{
if (vMask[i])
NZ++;
}
double nCameraParam = 7;
int nFeatures = vFeature.size();
int nFrames = vUsedFrame.size();
char *dVMask = (char *) malloc(vMask.size() * sizeof(char));
double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double));
double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double));
for (int i = 0; i < cameraParameter.size(); i++)
dCameraParameter[i] = cameraParameter[i];
for (int i = 0; i < vMask.size(); i++)
dVMask[i] = vMask[i];
for (int i = 0; i < feature2DParameter.size(); i++)
dFeature2DParameter[i] = feature2DParameter[i];
double opt[5];
opt[0] = 1e-3;
opt[1] = 1e-12;
opt[2] = 1e-12;
opt[3] = 1e-12;
opt[4] = 0;
double info[12];
sba_motstr_levmar(visibleStructureID.size(), 0, vUsedFrame.size(), 1, dVMask, dCameraParameter, nCameraParam, 3, dFeature2DParameter, dCovFeatures, 2, Projection3Donto2D_MOTSTR, NULL, &adata,
1e+3, 0, opt, info);
PrintSBAInfo(info, feature2DParameter.size()/2);
RetrieveParameterFromSBA(dCameraParameter, vCamera, cP, X, visibleStructureID, vUsedFrame, max_nFrames);
cout << "kk" << endl;
free(dVMask);
free(dFeature2DParameter);
free(dCameraParameter);
free(dCovFeatures);
cout << "kk" << endl;
for (int i = 0; i < adata.vIntrinsic.size(); i++)
{
free(adata.vIntrinsic[i]);
}
cout << "kk" << endl;
}
void SparseBundleAdjustment_MOTSTR_mem(vector<Feature> vFeature, vector<int> vUsedFrame, vector<CvMat *> &cP, CvMat *X, vector<Camera> vCamera, vector<int> visibleStructureID)
{
PrintAlgorithm("Sparse bundle adjustment motion and structure");
vector<double> cameraParameter, feature2DParameter;
vector<char> vMask;
double *dCovFeatures = 0;
AdditionalData adata;// focal_x focal_y princ_x princ_y
for (int iCamera = 0; iCamera < vCamera.size(); iCamera++)
{
double *intrinsic = (double *) malloc(4 * sizeof(double));
intrinsic[0] = cvGetReal2D(vCamera[iCamera].K, 0, 0);
intrinsic[1] = cvGetReal2D(vCamera[iCamera].K, 1, 1);
intrinsic[2] = cvGetReal2D(vCamera[iCamera].K, 0, 2);
intrinsic[3] = cvGetReal2D(vCamera[iCamera].K, 1, 2);
adata.vIntrinsic.push_back(intrinsic);
}
int max_nFrames = 0;
for (int iCamera = 0; iCamera < vCamera.size(); iCamera++)
{
for (int iFrame = 0; iFrame < vCamera[iCamera].vTakenFrame.size(); iFrame++)
{
if (vCamera[iCamera].vTakenFrame[iFrame] > max_nFrames)
max_nFrames = vCamera[iCamera].vTakenFrame[iFrame];
}
}
max_nFrames++;
adata.max_nFrames = max_nFrames;
adata.vUsedFrame = vUsedFrame;
GetParameterForSBA(vFeature, vUsedFrame, cP, X, vCamera, max_nFrames, visibleStructureID, cameraParameter, feature2DParameter, vMask);
int NZ = 0;
for (int i = 0; i < vMask.size(); i++)
{
if (vMask[i])
NZ++;
}
double nCameraParam = 7;
int nFeatures = vFeature.size();
int nFrames = vUsedFrame.size();
char *dVMask = (char *) malloc(vMask.size() * sizeof(char));
double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double));
double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double));
for (int i = 0; i < cameraParameter.size(); i++)
dCameraParameter[i] = cameraParameter[i];
for (int i = 0; i < vMask.size(); i++)
dVMask[i] = vMask[i];
for (int i = 0; i < feature2DParameter.size(); i++)
dFeature2DParameter[i] = feature2DParameter[i];
double opt[5];
opt[0] = 1e-3;
opt[1] = 1e-12;
opt[2] = 1e-12;
opt[3] = 1e-12;
opt[4] = 0;
double info[12];
PrintMat(cP[1]);
sba_motstr_levmar(visibleStructureID.size(), 0, vUsedFrame.size(), 1, dVMask, dCameraParameter, nCameraParam, 3, dFeature2DParameter, dCovFeatures, 2, Projection3Donto2D_MOTSTR_fast, NULL, &adata,
1e+3, 0, opt, info);
PrintSBAInfo(info, feature2DParameter.size()/2);
RetrieveParameterFromSBA_mem(dCameraParameter, vCamera, cP, X, visibleStructureID, vUsedFrame, max_nFrames);
PrintMat(cP[1]);
cout << "----------------" << endl;
free(dVMask);
free(dFeature2DParameter);
free(dCameraParameter);
free(dCovFeatures);
for (int i = 0; i < adata.vIntrinsic.size(); i++)
{
free(adata.vIntrinsic[i]);
}
adata.vIntrinsic.clear();
}
void SparseBundleAdjustment_MOTSTR_mem_fast(vector<Feature> &vFeature, vector<int> vUsedFrame, vector<CvMat *> &cP, CvMat *X, vector<Camera> vCamera)
{
PrintAlgorithm("Sparse bundle adjustment motion and structure");
vector<int> visibleStructureID;
for (int iFeature = 0; iFeature < vFeature.size(); iFeature++)
{
if (vFeature[iFeature].isRegistered)
{
visibleStructureID.push_back(vFeature[iFeature].id);
}
}
vector<double> cameraParameter, feature2DParameter;
vector<char> vMask;
double *dCovFeatures = 0;
AdditionalData adata;// focal_x focal_y princ_x princ_y
for (int iFrame = 0; iFrame < vCamera[0].vTakenFrame.size(); iFrame++)
{
double *intrinsic = (double *) malloc(4 * sizeof(double));
intrinsic[0] = cvGetReal2D(vCamera[0].vK[iFrame], 0, 0);
intrinsic[1] = cvGetReal2D(vCamera[0].vK[iFrame], 1, 1);
intrinsic[2] = cvGetReal2D(vCamera[0].vK[iFrame], 0, 2);
intrinsic[3] = cvGetReal2D(vCamera[0].vK[iFrame], 1, 2);
adata.vIntrinsic.push_back(intrinsic);
}
int max_nFrames = 0;
for (int iCamera = 0; iCamera < vCamera.size(); iCamera++)
{
for (int iFrame = 0; iFrame < vCamera[iCamera].vTakenFrame.size(); iFrame++)
{
if (vCamera[iCamera].vTakenFrame[iFrame] > max_nFrames)
max_nFrames = vCamera[iCamera].vTakenFrame[iFrame];
}
}
max_nFrames++;
adata.max_nFrames = max_nFrames;
adata.vUsedFrame = vUsedFrame;
GetParameterForSBA(vFeature, vUsedFrame, cP, X, vCamera, max_nFrames, visibleStructureID, cameraParameter, feature2DParameter, vMask);
int NZ = 0;
for (int i = 0; i < vMask.size(); i++)
{
if (vMask[i])
NZ++;
}
double nCameraParam = 7;
int nFeatures = vFeature.size();
int nFrames = vUsedFrame.size();
char *dVMask = (char *) malloc(vMask.size() * sizeof(char));
double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double));
double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double));
for (int i = 0; i < cameraParameter.size(); i++)
dCameraParameter[i] = cameraParameter[i];
for (int i = 0; i < vMask.size(); i++)
dVMask[i] = vMask[i];
for (int i = 0; i < feature2DParameter.size(); i++)
dFeature2DParameter[i] = feature2DParameter[i];
double opt[5];
opt[0] = 1e-3;
opt[1] = 1e-12;
opt[2] = 1e-12;
opt[3] = 1e-12;
opt[4] = 0;
double info[12];
sba_motstr_levmar(visibleStructureID.size(), 0, vUsedFrame.size(), 1, dVMask, dCameraParameter, nCameraParam, 3, dFeature2DParameter, dCovFeatures, 2, Projection3Donto2D_MOTSTR_fast, NULL, &adata,
1e+2, 0, opt, info);
PrintSBAInfo(info, feature2DParameter.size()/2);
RetrieveParameterFromSBA_mem(dCameraParameter, vCamera, cP, X, visibleStructureID, vUsedFrame, max_nFrames);
free(dVMask);
free(dFeature2DParameter);
free(dCameraParameter);
free(dCovFeatures);
for (int i = 0; i < adata.vIntrinsic.size(); i++)
{
free(adata.vIntrinsic[i]);
}
adata.vIntrinsic.clear();
}
void SparseBundleAdjustment_MOTSTR_mem_fast_Distortion(vector<Feature> &vFeature, vector<int> vUsedFrame, vector<CvMat *> &cP, CvMat *X, vector<Camera> vCamera, double omega)
{
PrintAlgorithm("Sparse bundle adjustment motion and structure");
vector<int> visibleStructureID;
for (int iFeature = 0; iFeature < vFeature.size(); iFeature++)
{
if (vFeature[iFeature].isRegistered)
{
visibleStructureID.push_back(vFeature[iFeature].id);
}
}
vector<double> cameraParameter, feature2DParameter;
vector<char> vMask;
double *dCovFeatures = 0;
AdditionalData adata;// focal_x focal_y princ_x princ_y
for (int iCamera = 0; iCamera < vCamera.size(); iCamera++)
{
double *intrinsic = (double *) malloc(6 * sizeof(double));
intrinsic[0] = cvGetReal2D(vCamera[iCamera].K, 0, 0);
intrinsic[1] = cvGetReal2D(vCamera[iCamera].K, 1, 1);
intrinsic[2] = cvGetReal2D(vCamera[iCamera].K, 0, 2);
intrinsic[3] = cvGetReal2D(vCamera[iCamera].K, 1, 2);
intrinsic[4] = omega;
intrinsic[5] = 2*tan(omega/2);
adata.vIntrinsic.push_back(intrinsic);
}
int max_nFrames = 0;
for (int iCamera = 0; iCamera < vCamera.size(); iCamera++)
{
for (int iFrame = 0; iFrame < vCamera[iCamera].vTakenFrame.size(); iFrame++)
{
if (vCamera[iCamera].vTakenFrame[iFrame] > max_nFrames)
max_nFrames = vCamera[iCamera].vTakenFrame[iFrame];
}
}
max_nFrames++;
adata.max_nFrames = max_nFrames;
adata.vUsedFrame = vUsedFrame;
GetParameterForSBA_Distortion(vFeature, vUsedFrame, cP, X, vCamera, max_nFrames, visibleStructureID, cameraParameter, feature2DParameter, vMask);
int NZ = 0;
for (int i = 0; i < vMask.size(); i++)
{
if (vMask[i])
NZ++;
}
double nCameraParam = 7;
int nFeatures = vFeature.size();
int nFrames = vUsedFrame.size();
char *dVMask = (char *) malloc(vMask.size() * sizeof(char));
double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double));
double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double));
for (int i = 0; i < cameraParameter.size(); i++)
dCameraParameter[i] = cameraParameter[i];
for (int i = 0; i < vMask.size(); i++)
dVMask[i] = vMask[i];
for (int i = 0; i < feature2DParameter.size(); i++)
dFeature2DParameter[i] = feature2DParameter[i];
double opt[5];
opt[0] = 1e-3;
opt[1] = 1e-12;
opt[2] = 1e-12;
opt[3] = 1e-12;
opt[4] = 0;
double info[12];
sba_motstr_levmar(visibleStructureID.size(), 0, vUsedFrame.size(), 1, dVMask, dCameraParameter, nCameraParam, 3, dFeature2DParameter, dCovFeatures, 2, Projection3Donto2D_MOTSTR_fast_Distortion, NULL, &adata,
1e+2, 0, opt, info);
PrintSBAInfo(info, feature2DParameter.size()/2);
RetrieveParameterFromSBA_mem(dCameraParameter, vCamera, cP, X, visibleStructureID, vUsedFrame, max_nFrames);
free(dVMask);
free(dFeature2DParameter);
free(dCameraParameter);
free(dCovFeatures);
for (int i = 0; i < adata.vIntrinsic.size(); i++)
{
free(adata.vIntrinsic[i]);
}
adata.vIntrinsic.clear();
}
void SparseBundleAdjustment_MOTSTR_mem_fast_Distortion_ObstacleDetection(vector<Feature> &vFeature, vector<int> vUsedFrame, vector<CvMat *> &cP, CvMat *X, vector<Camera> vCamera,
double omega, double princ_x1, double princ_y1)
{
PrintAlgorithm("Sparse bundle adjustment motion and structure");
vector<int> visibleStructureID;
for (int iFeature = 0; iFeature < vFeature.size(); iFeature++)
{
if (vFeature[iFeature].isRegistered)
{
visibleStructureID.push_back(vFeature[iFeature].id);
}
}
vector<double> cameraParameter, feature2DParameter;
vector<char> vMask;
double *dCovFeatures = 0;
AdditionalData adata;// focal_x focal_y princ_x princ_y
for (int iCamera = 0; iCamera < vCamera.size(); iCamera++)
{
double *intrinsic = (double *) malloc(8 * sizeof(double));
intrinsic[0] = cvGetReal2D(vCamera[iCamera].K, 0, 0);
intrinsic[1] = cvGetReal2D(vCamera[iCamera].K, 1, 1);
intrinsic[2] = cvGetReal2D(vCamera[iCamera].K, 0, 2);
intrinsic[3] = cvGetReal2D(vCamera[iCamera].K, 1, 2);
intrinsic[4] = omega;
intrinsic[5] = 2*tan(omega/2);
intrinsic[6] = princ_x1;
intrinsic[7] = princ_y1;
adata.vIntrinsic.push_back(intrinsic);
}
int max_nFrames = 0;
for (int iCamera = 0; iCamera < vCamera.size(); iCamera++)
{
for (int iFrame = 0; iFrame < vCamera[iCamera].vTakenFrame.size(); iFrame++)
{
if (vCamera[iCamera].vTakenFrame[iFrame] > max_nFrames)
max_nFrames = vCamera[iCamera].vTakenFrame[iFrame];
}
}
max_nFrames++;
adata.max_nFrames = max_nFrames;
adata.vUsedFrame = vUsedFrame;
//cout << "OK" << endl;
//for (int i = 0; i < cP.size(); i++)
//{
// PrintMat(cP[i]);
//}
//for (int i = 0; i < visibleStructureID.size(); i++)
//{
// cout << cvGetReal2D(X, visibleStructureID[i], 0) << " " <<cvGetReal2D(X, visibleStructureID[i], 1) << " " <<cvGetReal2D(X, visibleStructureID[i], 2) << " " << endl;
//}
GetParameterForSBA_Distortion(vFeature, vUsedFrame, cP, X, vCamera, max_nFrames, visibleStructureID, cameraParameter, feature2DParameter, vMask);
cout << "OK" << endl;
int NZ = 0;
for (int i = 0; i < vMask.size(); i++)
{
if (vMask[i])
NZ++;
}
double nCameraParam = 7;
int nFeatures = vFeature.size();
int nFrames = vUsedFrame.size();
char *dVMask = (char *) malloc(vMask.size() * sizeof(char));
double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double));
double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double));
for (int i = 0; i < cameraParameter.size(); i++)
dCameraParameter[i] = cameraParameter[i];
for (int i = 0; i < vMask.size(); i++)
dVMask[i] = vMask[i];
for (int i = 0; i < feature2DParameter.size(); i++)
dFeature2DParameter[i] = feature2DParameter[i];
double opt[5];
opt[0] = 1e-3;
opt[1] = 1e-12;
opt[2] = 1e-12;
opt[3] = 1e-12;
opt[4] = 0;
double info[12];
cout << "OK" << endl;
sba_motstr_levmar(visibleStructureID.size(), 0, vUsedFrame.size(), 1, dVMask, dCameraParameter, nCameraParam, 3, dFeature2DParameter, dCovFeatures, 2, Projection3Donto2D_MOTSTR_fast_Distortion_ObstacleDetection, NULL, &adata,
1e+2, 0, opt, info);
PrintSBAInfo(info, feature2DParameter.size()/2);
RetrieveParameterFromSBA_mem(dCameraParameter, vCamera, cP, X, visibleStructureID, vUsedFrame, max_nFrames);
free(dVMask);
free(dFeature2DParameter);
free(dCameraParameter);
free(dCovFeatures);
for (int i = 0; i < adata.vIntrinsic.size(); i++)
{
free(adata.vIntrinsic[i]);
}
adata.vIntrinsic.clear();
}
void SparseBundleAdjustment_KMOTSTR(vector<Feature> vFeature, vector<int> vUsedFrame, vector<CvMat *> &cP, CvMat *X, vector<Camera> vCamera, vector<int> visibleStructureID)
{
PrintAlgorithm("Sparse bundle adjustment motion and structure");
vector<double> cameraParameter, feature2DParameter;
vector<char> vMask;
double *dCovFeatures = 0;
AdditionalData adata;// focal_x focal_y princ_x princ_y
//for (int iCamera = 0; iCamera < vCamera.size(); iCamera++)
//{
// double *intrinsic = (double *) malloc(4 * sizeof(double));
// intrinsic[0] = cvGetReal2D(vCamera[iCamera].K, 0, 0);
// intrinsic[1] = cvGetReal2D(vCamera[iCamera].K, 1, 1);
// intrinsic[2] = cvGetReal2D(vCamera[iCamera].K, 0, 2);
// intrinsic[3] = cvGetReal2D(vCamera[iCamera].K, 1, 2);
// adata.vIntrinsic.push_back(intrinsic);
//}
int max_nFrames = 0;
for (int iCamera = 0; iCamera < vCamera.size(); iCamera++)
{
for (int iFrame = 0; iFrame < vCamera[iCamera].vTakenFrame.size(); iFrame++)
{
if (vCamera[iCamera].vTakenFrame[iFrame] > max_nFrames)
max_nFrames = vCamera[iCamera].vTakenFrame[iFrame];
}
}
max_nFrames++;
adata.max_nFrames = max_nFrames;
adata.vUsedFrame = vUsedFrame;
GetParameterForSBA_KRT(vFeature, vUsedFrame, cP, X, vCamera, max_nFrames, visibleStructureID, cameraParameter, feature2DParameter, vMask);
int NZ = 0;
for (int i = 0; i < vMask.size(); i++)
{
if (vMask[i])
NZ++;
}
double nCameraParam = 7+4;
int nFeatures = visibleStructureID.size();
int nFrames = vUsedFrame.size();
char *dVMask = (char *) malloc(vMask.size() * sizeof(char));
double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double));
double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double));
for (int i = 0; i < cameraParameter.size(); i++)
dCameraParameter[i] = cameraParameter[i];
for (int i = 0; i < vMask.size(); i++)
{
dVMask[i] = vMask[i];
}
for (int i = 0; i < feature2DParameter.size(); i++)
dFeature2DParameter[i] = feature2DParameter[i];
double opt[5];
opt[0] = 1e-3;
opt[1] = 1e-12;
opt[2] = 1e-12;
opt[3] = 1e-12;
opt[4] = 0;
double info[12];
sba_motstr_levmar(visibleStructureID.size(), 0, vUsedFrame.size(), 1, dVMask, dCameraParameter, nCameraParam, 3, dFeature2DParameter, dCovFeatures, 2, Projection3Donto2D_KMOTSTR, NULL, &adata,
1e+3, 0, opt, info);
PrintSBAInfo(info, feature2DParameter.size()/2);
RetrieveParameterFromSBA_KRT(dCameraParameter, vCamera, cP, X, visibleStructureID, vUsedFrame, max_nFrames);
free(dVMask);
free(dFeature2DParameter);
free(dCameraParameter);
}
void SparseBundleAdjustment_KMOTSTR_x(vector<Feature> vFeature, vector<int> vUsedFrame, vector<CvMat *> &cP, CvMat *X, vector<Camera> vCamera, vector<int> visibleStructureID)
{
PrintAlgorithm("Sparse bundle adjustment motion and structure");
vector<double> cameraParameter, feature2DParameter;
vector<char> vMask;
double *dCovFeatures = 0;
AdditionalData adata;// focal_x focal_y princ_x princ_y
//for (int iCamera = 0; iCamera < vCamera.size(); iCamera++)
//{
// double *intrinsic = (double *) malloc(4 * sizeof(double));
// intrinsic[0] = cvGetReal2D(vCamera[iCamera].K, 0, 0);
// intrinsic[1] = cvGetReal2D(vCamera[iCamera].K, 1, 1);
// intrinsic[2] = cvGetReal2D(vCamera[iCamera].K, 0, 2);
// intrinsic[3] = cvGetReal2D(vCamera[iCamera].K, 1, 2);
// adata.vIntrinsic.push_back(intrinsic);
//}
int max_nFrames = 0;
for (int iCamera = 0; iCamera < vCamera.size(); iCamera++)
{
for (int iFrame = 0; iFrame < vCamera[iCamera].vTakenFrame.size(); iFrame++)
{
if (vCamera[iCamera].vTakenFrame[iFrame] > max_nFrames)
max_nFrames = vCamera[iCamera].vTakenFrame[iFrame];
}
}
max_nFrames++;
adata.max_nFrames = max_nFrames;
adata.vUsedFrame = vUsedFrame;
GetParameterForSBA_KRT(vFeature, vUsedFrame, cP, X, vCamera, max_nFrames, visibleStructureID, cameraParameter, feature2DParameter, vMask);
int NZ = 0;
for (int i = 0; i < vMask.size(); i++)
{
if (vMask[i])
NZ++;
}
double nCameraParam = 7+4;
int nFeatures = visibleStructureID.size();
int nFrames = vUsedFrame.size();
char *dVMask = (char *) malloc(vMask.size() * sizeof(char));
double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double));
double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double));
for (int i = 0; i < cameraParameter.size(); i++)
dCameraParameter[i] = cameraParameter[i];
for (int i = 0; i < vMask.size(); i++)
{
dVMask[i] = vMask[i];
}
for (int i = 0; i < feature2DParameter.size(); i++)
dFeature2DParameter[i] = feature2DParameter[i];
double opt[5];
opt[0] = 1e-3;
opt[1] = 1e-12;
opt[2] = 1e-12;
opt[3] = 1e-12;
opt[4] = 0;
double info[12];
sba_motstr_levmar(visibleStructureID.size(), 0, vUsedFrame.size(), 1, dVMask, dCameraParameter, nCameraParam, 3, dFeature2DParameter, dCovFeatures, 2, Projection3Donto2D_KMOTSTR, NULL, &adata,
1e+3, 0, opt, info);
PrintSBAInfo(info);
RetrieveParameterFromSBA_KRT(dCameraParameter, vCamera, cP, X, visibleStructureID, vUsedFrame, max_nFrames);
free(dVMask);
free(dFeature2DParameter);
free(dCameraParameter);
}
void SparseBundleAdjustment_KDMOTSTR(vector<Feature> vFeature, vector<int> vUsedFrame, vector<CvMat *> &cP, CvMat *X, vector<Camera> vCamera, vector<int> visibleStructureID)
{
PrintAlgorithm("Sparse bundle adjustment motion and structure");
vector<double> cameraParameter, feature2DParameter;
vector<char> vMask;
double *dCovFeatures = 0;
AdditionalData adata;// focal_x focal_y princ_x princ_y
int max_nFrames = 0;
for (int iCamera = 0; iCamera < vCamera.size(); iCamera++)
{
for (int iFrame = 0; iFrame < vCamera[iCamera].vTakenFrame.size(); iFrame++)
{
if (vCamera[iCamera].vTakenFrame[iFrame] > max_nFrames)
max_nFrames = vCamera[iCamera].vTakenFrame[iFrame];
}
}
max_nFrames++;
adata.max_nFrames = max_nFrames;
adata.vUsedFrame = vUsedFrame;
GetParameterForSBA_KDRT(vFeature, vUsedFrame, cP, X, vCamera, max_nFrames, visibleStructureID, cameraParameter, feature2DParameter, vMask);
int NZ = 0;
for (int i = 0; i < vMask.size(); i++)
{
if (vMask[i])
NZ++;
}
double nCameraParam = 7+4+2;
int nFeatures = vFeature.size();
int nFrames = vUsedFrame.size();
char *dVMask = (char *) malloc(vMask.size() * sizeof(char));
double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double));
double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double));
for (int i = 0; i < cameraParameter.size(); i++)
dCameraParameter[i] = cameraParameter[i];
for (int i = 0; i < vMask.size(); i++)
dVMask[i] = vMask[i];
for (int i = 0; i < feature2DParameter.size(); i++)
dFeature2DParameter[i] = feature2DParameter[i];
double opt[5];
opt[0] = 1e-3;
opt[1] = 1e-12;
opt[2] = 1e-12;
opt[3] = 1e-12;
opt[4] = 0;
double info[12];
sba_motstr_levmar(visibleStructureID.size(), 0, vUsedFrame.size(), 1, dVMask, dCameraParameter, nCameraParam, 3, dFeature2DParameter, dCovFeatures, 2, Projection3Donto2D_KDMOTSTR, NULL, &adata,
1e+3, 0, opt, info);
PrintSBAInfo(info);
RetrieveParameterFromSBA_KDRT(dCameraParameter, vCamera, cP, X, visibleStructureID, vUsedFrame, max_nFrames);
free(dVMask);
free(dFeature2DParameter);
free(dCameraParameter);
}
void PatchTriangulationRefinement(CvMat *K, vector<CvMat *> vC, vector<CvMat *> vR,
vector<double> vx11, vector<double> vy11,
vector<double> vx12, vector<double> vy12,
vector<double> vx21, vector<double> vy21,
vector<double> vx22, vector<double> vy22,
double X, double Y, double Z,
CvMat *X11, CvMat *X12, CvMat *X21, CvMat *X22, CvMat *pi)
{
PrintAlgorithm("Patch Triangulation Refinement");
vector<CvMat *> vP;
for (int i = 0; i < vC.size(); i++)
{
CvMat *P = cvCreateMat(3,4,CV_32FC1);
CvMat *t = cvCreateMat(3,1,CV_32FC1);
ScalarMul(vC[i], -1, t);
cvSetIdentity(P);
SetSubMat(P, 0, 3, t);
cvMatMul(vR[i], P, P);
cvMatMul(K, P, P);
vP.push_back(P);
}
AdditionalData adata;
adata.vP = vP;
adata.X = X; adata.Y = Y; adata.Z = Z;
vector<double> XParameter, feature2DParameter;
XParameter.push_back(cvGetReal2D(pi, 0, 0));
XParameter.push_back(cvGetReal2D(pi, 1, 0));
XParameter.push_back(cvGetReal2D(pi, 2, 0));
XParameter.push_back(cvGetReal2D(X11, 0, 0));
XParameter.push_back(cvGetReal2D(X11, 1, 0));
XParameter.push_back(cvGetReal2D(X12, 0, 0));
XParameter.push_back(cvGetReal2D(X12, 1, 0));
XParameter.push_back(cvGetReal2D(X21, 0, 0));
XParameter.push_back(cvGetReal2D(X21, 1, 0));
XParameter.push_back(cvGetReal2D(X22, 0, 0));
XParameter.push_back(cvGetReal2D(X22, 1, 0));
for (int iFeature = 0; iFeature < vx11.size(); iFeature++)
{
feature2DParameter.push_back(vx11[iFeature]);
feature2DParameter.push_back(vy11[iFeature]);
feature2DParameter.push_back(vx12[iFeature]);
feature2DParameter.push_back(vy12[iFeature]);
feature2DParameter.push_back(vx21[iFeature]);
feature2DParameter.push_back(vy21[iFeature]);
feature2DParameter.push_back(vx22[iFeature]);
feature2DParameter.push_back(vy22[iFeature]);
}
//for (int i = 0; i < feature2DParameter.size(); i++)
//{
// cout << feature2DParameter[i] << " ";
//}
//cout << endl;
int nFeatures = vx11.size();
double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double));
double *dXParameter = (double *) malloc(XParameter.size() * sizeof(double));
for (int i = 0; i < XParameter.size(); i++)
dXParameter[i] = XParameter[i];
for (int i = 0; i < feature2DParameter.size(); i++)
dFeature2DParameter[i] = feature2DParameter[i];
double opt[5];
opt[0] = 1e-3;
opt[1] = 1e-12;
opt[2] = 1e-12;
opt[3] = 1e-12;
opt[4] = 0;
double info[12];
double *work = (double*)malloc((LM_DIF_WORKSZ(XParameter.size(), feature2DParameter.size())+XParameter.size()*XParameter.size())*sizeof(double));
if(!work)
fprintf(stderr, "memory allocation request failed in main()\n");
int ret = dlevmar_dif(Projection3Donto2D_Patch, dXParameter, dFeature2DParameter, XParameter.size(), feature2DParameter.size(),
1e+3, opt, info, work, NULL, &adata);
double pi1 = dXParameter[0];
double pi2 = dXParameter[1];
double pi3 = dXParameter[2];
double pi4 = -pi1*X-pi2*Y-pi3*Z;
cvSetReal2D(pi, 0, 0, dXParameter[0]);
cvSetReal2D(pi, 1, 0, dXParameter[1]);
cvSetReal2D(pi, 2, 0, dXParameter[2]);
cvSetReal2D(pi, 3, 0, pi4);
cvSetReal2D(X11, 0, 0, dXParameter[3]);
cvSetReal2D(X11, 1, 0, dXParameter[4]);
double Z11 = (-pi4-pi1*cvGetReal2D(X11, 0, 0)-pi2*cvGetReal2D(X11, 1, 0))/pi3;
cvSetReal2D(X11, 2, 0, Z11);
cvSetReal2D(X12, 0, 0, dXParameter[5]);
cvSetReal2D(X12, 1, 0, dXParameter[6]);
double Z12 = (-pi4-pi1*cvGetReal2D(X12, 0, 0)-pi2*cvGetReal2D(X12, 1, 0))/pi3;
cvSetReal2D(X12, 2, 0, Z12);
cvSetReal2D(X21, 0, 0, dXParameter[7]);
cvSetReal2D(X21, 1, 0, dXParameter[8]);
double Z21 = (-pi4-pi1*cvGetReal2D(X21, 0, 0)-pi2*cvGetReal2D(X21, 1, 0))/pi3;
cvSetReal2D(X21, 2, 0, Z21);
cvSetReal2D(X22, 0, 0, dXParameter[9]);
cvSetReal2D(X22, 1, 0, dXParameter[10]);
double Z22 = (-pi4-pi1*cvGetReal2D(X22, 0, 0)-pi2*cvGetReal2D(X22, 1, 0))/pi3;
cvSetReal2D(X22, 2, 0, Z22);
PrintSBAInfo(info, feature2DParameter.size());
free(dFeature2DParameter);
free(dXParameter);
free(work);
for (int i = 0; i < vP.size(); i++)
{
cvReleaseMat(&vP[i]);
}
}
void TriangulationRefinement(CvMat *K, double omega, vector<CvMat *> vP, vector<double> vx, vector<double> vy, double &X, double &Y, double &Z)
{
PrintAlgorithm("Point Triangulation Refinement");
AdditionalData adata;
double intrinsic[5] = {cvGetReal2D(K, 0, 0), cvGetReal2D(K, 1, 1), cvGetReal2D(K, 0, 2), cvGetReal2D(K, 1, 2), omega};
adata.vIntrinsic.push_back(intrinsic);
adata.vP = vP;
vector<double> XParameter, feature2DParameter;
XParameter.push_back(X);
XParameter.push_back(Y);
XParameter.push_back(Z);
for (int iFeature = 0; iFeature < vx.size(); iFeature++)
{
feature2DParameter.push_back(vx[iFeature]);
feature2DParameter.push_back(vy[iFeature]);
}
int nFeatures = vx.size();
double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double));
double *dXParameter = (double *) malloc(XParameter.size() * sizeof(double));
for (int i = 0; i < XParameter.size(); i++)
dXParameter[i] = XParameter[i];
for (int i = 0; i < feature2DParameter.size(); i++)
dFeature2DParameter[i] = feature2DParameter[i];
double opt[5];
opt[0] = 1e-3;
opt[1] = 1e-12;
opt[2] = 1e-12;
opt[3] = 1e-12;
opt[4] = 0;
double info[12];
double *work = (double*)malloc((LM_DIF_WORKSZ(XParameter.size(), feature2DParameter.size())+XParameter.size()*XParameter.size())*sizeof(double));
if(!work)
fprintf(stderr, "memory allocation request failed in main()\n");
int ret = dlevmar_dif(Projection3Donto2D_STR_fast_SO, dXParameter, dFeature2DParameter, XParameter.size(), feature2DParameter.size(),
1e+3, opt, info, work, NULL, &adata);
X = dXParameter[0];
Y = dXParameter[1];
Z = dXParameter[2];
PrintSBAInfo(info, feature2DParameter.size());
free(dFeature2DParameter);
free(dXParameter);
free(work);
//for (int i = 0; i < adata.vP.size(); i++)
//{
// cvReleaseMat(&adata.vP[i]);
//}
}
void TriangulationRefinement_NoDistortion(CvMat *K, vector<CvMat *> vP, vector<double> vx, vector<double> vy, double &X, double &Y, double &Z)
{
PrintAlgorithm("Point Triangulation Refinement");
AdditionalData adata;
double intrinsic[4] = {cvGetReal2D(K, 0, 0), cvGetReal2D(K, 1, 1), cvGetReal2D(K, 0, 2), cvGetReal2D(K, 1, 2)};
adata.vIntrinsic.push_back(intrinsic);
adata.vP = vP;
vector<double> XParameter, feature2DParameter;
XParameter.push_back(X);
XParameter.push_back(Y);
XParameter.push_back(Z);
for (int iFeature = 0; iFeature < vx.size(); iFeature++)
{
feature2DParameter.push_back(vx[iFeature]);
feature2DParameter.push_back(vy[iFeature]);
}
int nFeatures = vx.size();
double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double));
double *dXParameter = (double *) malloc(XParameter.size() * sizeof(double));
for (int i = 0; i < XParameter.size(); i++)
dXParameter[i] = XParameter[i];
for (int i = 0; i < feature2DParameter.size(); i++)
dFeature2DParameter[i] = feature2DParameter[i];
double opt[5];
opt[0] = 1e-3;
opt[1] = 1e-12;
opt[2] = 1e-12;
opt[3] = 1e-12;
opt[4] = 0;
double info[12];
double *work = (double*)malloc((LM_DIF_WORKSZ(XParameter.size(), feature2DParameter.size())+XParameter.size()*XParameter.size())*sizeof(double));
if(!work)
fprintf(stderr, "memory allocation request failed in main()\n");
int ret = dlevmar_dif(Projection3Donto2D_STR_fast_SO_NoDistortion, dXParameter, dFeature2DParameter, XParameter.size(), feature2DParameter.size(),
1e+3, opt, info, work, NULL, &adata);
X = dXParameter[0];
Y = dXParameter[1];
Z = dXParameter[2];
PrintSBAInfo(info, feature2DParameter.size());
free(dFeature2DParameter);
free(dXParameter);
free(work);
//for (int i = 0; i < adata.vP.size(); i++)
//{
// cvReleaseMat(&adata.vP[i]);
//}
}
void AbsoluteCameraPoseRefinement(CvMat *X, CvMat *x, CvMat *P, CvMat *K)
{
PrintAlgorithm("Absolute Camera Pose Refinement");
vector<double> cameraParameter, feature2DParameter;
AdditionalData adata;// focal_x focal_y princ_x princ_y
double intrinsic[4] = {cvGetReal2D(K, 0, 0), cvGetReal2D(K, 1, 1), cvGetReal2D(K, 0, 2), cvGetReal2D(K, 1, 2)};
adata.vIntrinsic.push_back(intrinsic);
CvMat *q = cvCreateMat(4,1,CV_32FC1);
CvMat *R = cvCreateMat(3,3,CV_32FC1);
CvMat *t = cvCreateMat(3,1,CV_32FC1);
CvMat *invK = cvCreateMat(3,3,CV_32FC1);
CvMat *invR = cvCreateMat(3,3,CV_32FC1);
GetSubMatColwise(P, 0, 2, R);
GetSubMatColwise(P, 3, 3, t);
cvInvert(K, invK);
cvMatMul(invK, R, R);
cvInvert(R, invR);
cvMatMul(invK, t, t);
cvMatMul(invR, t, t);
ScalarMul(t, -1, t);
Rotation2Quaternion(R, q);
cameraParameter.push_back(cvGetReal2D(q, 0, 0));
cameraParameter.push_back(cvGetReal2D(q, 1, 0));
cameraParameter.push_back(cvGetReal2D(q, 2, 0));
cameraParameter.push_back(cvGetReal2D(q, 3, 0));
cameraParameter.push_back(cvGetReal2D(t, 0, 0));
cameraParameter.push_back(cvGetReal2D(t, 1, 0));
cameraParameter.push_back(cvGetReal2D(t, 2, 0));
for (int iFeature = 0; iFeature < X->rows; iFeature++)
{
feature2DParameter.push_back(cvGetReal2D(x, iFeature, 0));
feature2DParameter.push_back(cvGetReal2D(x, iFeature, 1));
}
int nCameraParam = 7;
int nFeatures = X->rows;
double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double));
double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double));
double *dXParameter = (double *) malloc(X->rows * 3 * sizeof(double));
for (int i = 0; i < cameraParameter.size(); i++)
dCameraParameter[i] = cameraParameter[i];
for (int i = 0; i < feature2DParameter.size(); i++)
dFeature2DParameter[i] = feature2DParameter[i];
for (int i = 0; i < X->rows; i++)
{
dXParameter[3*i] = cvGetReal2D(X, i, 0);
dXParameter[3*i+1] = cvGetReal2D(X, i, 1);
dXParameter[3*i+2] = cvGetReal2D(X, i, 2);
}
adata.XYZ = dXParameter;
double opt[5];
opt[0] = 1e-3;
opt[1] = 1e-12;
opt[2] = 1e-12;
opt[3] = 1e-12;
opt[4] = 0;
double info[12];
double *work = (double*)malloc((LM_DIF_WORKSZ(cameraParameter.size(), feature2DParameter.size())+cameraParameter.size()*cameraParameter.size())*sizeof(double));
if(!work)
fprintf(stderr, "memory allocation request failed in main()\n");
int ret = dlevmar_dif(Projection3Donto2D_MOT_fast, dCameraParameter, dFeature2DParameter, cameraParameter.size(), feature2DParameter.size(),
1e+3, opt, info, work, NULL, &adata);
cvSetIdentity(P);
cvSetReal2D(P, 0, 3, -dCameraParameter[4]);
cvSetReal2D(P, 1, 3, -dCameraParameter[5]);
cvSetReal2D(P, 2, 3, -dCameraParameter[6]);
cvSetReal2D(q, 0, 0, dCameraParameter[0]);
cvSetReal2D(q, 1, 0, dCameraParameter[1]);
cvSetReal2D(q, 2, 0, dCameraParameter[2]);
cvSetReal2D(q, 3, 0, dCameraParameter[3]);
Quaternion2Rotation(q, R);
cvMatMul(K, R, R);
cvMatMul(R, P, P);
//cout << ret << endl;
PrintSBAInfo(info, X->rows);
free(dFeature2DParameter);
free(dCameraParameter);
cvReleaseMat(&R);
cvReleaseMat(&t);
cvReleaseMat(&q);
cvReleaseMat(&invK);
cvReleaseMat(&invR);
}
void Projection3Donto2D_Patch(double *rt, double *hx, int m, int n, void *adata)
{
// Set intrinsic parameter
double X = ((AdditionalData *) adata)->X;
double Y = ((AdditionalData *) adata)->Y;
double Z = ((AdditionalData *) adata)->Z;
double pi1 = rt[0];
double pi2 = rt[1];
double pi3 = rt[2];
double pi4 = -pi1*X - pi2*Y - pi3*Z;
double X11 = rt[3];
double Y11 = rt[4];
double Z11 = (-pi4-pi1*X11-pi2*Y11)/pi3;
double X12 = rt[5];
double Y12 = rt[6];
double Z12 = (-pi4-pi1*X12-pi2*Y12)/pi3;
double X21 = rt[7];
double Y21 = rt[8];
double Z21 = (-pi4-pi1*X21-pi2*Y21)/pi3;
double X22 = rt[9];
double Y22 = rt[10];
double Z22 = (-pi4-pi1*X22-pi2*Y22)/pi3;
for (int iP = 0; iP < ((AdditionalData *) adata)->vP.size(); iP++)
{
double P11 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 0, 0);
double P12 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 0, 1);
double P13 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 0, 2);
double P14 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 0, 3);
double P21 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 1, 0);
double P22 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 1, 1);
double P23 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 1, 2);
double P24 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 1, 3);
double P31 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 2, 0);
double P32 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 2, 1);
double P33 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 2, 2);
double P34 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 2, 3);
double x11 = P11*X11+P12*Y11+P13*Z11+P14;
double y11 = P21*X11+P22*Y11+P23*Z11+P24;
double z11 = P31*X11+P32*Y11+P33*Z11+P34;
double x12 = P11*X12+P12*Y12+P13*Z12+P14;
double y12 = P21*X12+P22*Y12+P23*Z12+P24;
double z12 = P31*X12+P32*Y12+P33*Z12+P34;
double x21 = P11*X21+P12*Y21+P13*Z21+P14;
double y21 = P21*X21+P22*Y21+P23*Z21+P24;
double z21 = P31*X21+P32*Y21+P33*Z21+P34;
double x22 = P11*X22+P12*Y22+P13*Z22+P14;
double y22 = P21*X22+P22*Y22+P23*Z22+P24;
double z22 = P31*X22+P32*Y22+P33*Z22+P34;
hx[8*iP] = x11/z11;
hx[8*iP+1] = y11/z11;
hx[8*iP+2] = x12/z12;
hx[8*iP+3] = y12/z12;
hx[8*iP+4] = x21/z21;
hx[8*iP+5] = y21/z21;
hx[8*iP+6] = x22/z22;
hx[8*iP+7] = y22/z22;
//cout << x11/z11 << " " << y11/z11 << " ";
//cout << x12/z12 << " " << y12/z12 << " ";
//cout << x21/z21 << " " << y21/z21 << " ";
//cout << x22/z22 << " " << y22/z22 << endl;
}
}
void Projection3Donto2D_STR_fast_SO(double *rt, double *hx, int m, int n, void *adata)
{
// Set intrinsic parameter
double K11 = ((((AdditionalData *) adata)->vIntrinsic)[0])[0];
double K12 = 0;
double K13 = ((((AdditionalData *) adata)->vIntrinsic)[0])[2];
double K21 = 0;
double K22 = ((((AdditionalData *) adata)->vIntrinsic)[0])[1];
double K23 = ((((AdditionalData *) adata)->vIntrinsic)[0])[3];
double K31 = 0;
double K32 = 0;
double K33 = 1;
double omega = ((((AdditionalData *) adata)->vIntrinsic)[0])[4];
double tan_omega_half_2 = 2*tan(omega/2);
double X = rt[0];
double Y = rt[1];
double Z = rt[2];
for (int iP = 0; iP < ((AdditionalData *) adata)->vP.size(); iP++)
{
double P11 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 0, 0);
double P12 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 0, 1);
double P13 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 0, 2);
double P14 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 0, 3);
double P21 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 1, 0);
double P22 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 1, 1);
double P23 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 1, 2);
double P24 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 1, 3);
double P31 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 2, 0);
double P32 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 2, 1);
double P33 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 2, 2);
double P34 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 2, 3);
double x = P11*X+P12*Y+P13*Z+P14;
double y = P21*X+P22*Y+P23*Z+P24;
double z = P31*X+P32*Y+P33*Z+P34;
x /= z;
y /= z;
double u_n = x/K11 - K13/K11;
double v_n = y/K22 - K23/K22;
double r_u = sqrt(u_n*u_n+v_n*v_n);
double r_d = 1/omega*atan(r_u*tan_omega_half_2);
double u_d_n = r_d/r_u * u_n;
double v_d_n = r_d/r_u * v_n;
double u_d = u_d_n*K11 + K13;
double v_d = v_d_n*K22 + K23;
hx[2*iP] = u_d;
hx[2*iP+1] = v_d;
}
}
void Projection3Donto2D_STR_fast_SO_NoDistortion(double *rt, double *hx, int m, int n, void *adata)
{
// Set intrinsic parameter
double K11 = ((((AdditionalData *) adata)->vIntrinsic)[0])[0];
double K12 = 0;
double K13 = ((((AdditionalData *) adata)->vIntrinsic)[0])[2];
double K21 = 0;
double K22 = ((((AdditionalData *) adata)->vIntrinsic)[0])[1];
double K23 = ((((AdditionalData *) adata)->vIntrinsic)[0])[3];
double K31 = 0;
double K32 = 0;
double K33 = 1;
//double omega = ((((AdditionalData *) adata)->vIntrinsic)[0])[4];
//double tan_omega_half_2 = 2*tan(omega/2);
double X = rt[0];
double Y = rt[1];
double Z = rt[2];
for (int iP = 0; iP < ((AdditionalData *) adata)->vP.size(); iP++)
{
double P11 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 0, 0);
double P12 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 0, 1);
double P13 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 0, 2);
double P14 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 0, 3);
double P21 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 1, 0);
double P22 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 1, 1);
double P23 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 1, 2);
double P24 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 1, 3);
double P31 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 2, 0);
double P32 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 2, 1);
double P33 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 2, 2);
double P34 = cvGetReal2D(((AdditionalData *) adata)->vP[iP], 2, 3);
double x = P11*X+P12*Y+P13*Z+P14;
double y = P21*X+P22*Y+P23*Z+P24;
double z = P31*X+P32*Y+P33*Z+P34;
x /= z;
y /= z;
//double u_n = x/K11 - K13/K11;
//double v_n = y/K22 - K23/K22;
//double r_u = sqrt(u_n*u_n+v_n*v_n);
//double r_d = 1/omega*atan(r_u*tan_omega_half_2);
//double u_d_n = r_d/r_u * u_n;
//double v_d_n = r_d/r_u * v_n;
//double u_d = u_d_n*K11 + K13;
//double v_d = v_d_n*K22 + K23;
hx[2*iP] = x;
hx[2*iP+1] = y;
}
}
void Projection3Donto2D_MOT_fast(double *rt, double *hx, int m, int n, void *adata)
{
// Set intrinsic parameter
double K11 = ((((AdditionalData *) adata)->vIntrinsic)[0])[0];
double K12 = 0;
double K13 = ((((AdditionalData *) adata)->vIntrinsic)[0])[2];
double K21 = 0;
double K22 = ((((AdditionalData *) adata)->vIntrinsic)[0])[1];
double K23 = ((((AdditionalData *) adata)->vIntrinsic)[0])[3];
double K31 = 0;
double K32 = 0;
double K33 = 1;
// Set orientation
double qw = rt[0];
double qx = rt[1];
double qy = rt[2];
double qz = rt[3];
double q_norm = sqrt(qw*qw + qx*qx + qy*qy + qz*qz);
qw /= q_norm;
qx /= q_norm;
qy /= q_norm;
qz /= q_norm;
double R11 = 1.0-2*qy*qy-2*qz*qz; double R12 = 2*qx*qy-2*qz*qw; double R13 = 2*qx*qz+2*qy*qw;
double R21 = 2*qx*qy+2*qz*qw; double R22 = 1.0-2*qx*qx-2*qz*qz; double R23 = 2*qz*qy-2*qx*qw;
double R31 = 2*qx*qz-2*qy*qw; double R32 = 2*qy*qz+2*qx*qw; double R33 = 1.0-2*qx*qx-2*qy*qy;
// Set translation
double C1 = rt[4];
double C2 = rt[5];
double C3 = rt[6];
for (int iPoint = 0; iPoint < n/2; iPoint++)
{
double X1 = ((AdditionalData *) adata)->XYZ[3*iPoint];
double X2 = ((AdditionalData *) adata)->XYZ[3*iPoint+1];
double X3 = ((AdditionalData *) adata)->XYZ[3*iPoint+2];
// Building projection
double RX1 = R11*X1+R12*X2+R13*X3;
double RX2 = R21*X1+R22*X2+R23*X3;
double RX3 = R31*X1+R32*X2+R33*X3;
double KRX1 = K11*RX1+K12*RX2+K13*RX3;
double KRX2 = K21*RX1+K22*RX2+K23*RX3;
double KRX3 = K31*RX1+K32*RX2+K33*RX3;
double RC1 = R11*C1+R12*C2+R13*C3;
double RC2 = R21*C1+R22*C2+R23*C3;
double RC3 = R31*C1+R32*C2+R33*C3;
double KRC1 = K11*RC1+K12*RC2+K13*RC3;
double KRC2 = K21*RC1+K22*RC2+K23*RC3;
double KRC3 = K31*RC1+K32*RC2+K33*RC3;
double proj1 = KRX1-KRC1;
double proj2 = KRX2-KRC2;
double proj3 = KRX3-KRC3;
hx[2*iPoint] = proj1/proj3;
hx[2*iPoint+1] = proj2/proj3;
}
}
void ObjectiveOrientationRefinement(double *rt, double *hx, int m, int n, void *adata)
{
int nFrames = (((AdditionalData *) adata)->nFrames);
vector<double> vR11, vR12, vR13, vR21, vR22, vR23, vR31, vR32, vR33;
vector<double> vm1, vm2, vm3;
for (int iFrame = 0; iFrame < nFrames; iFrame++)
{
// Set orientation
double qw = rt[7*iFrame+0];
double qx = rt[7*iFrame+1];
double qy = rt[7*iFrame+2];
double qz = rt[7*iFrame+3];
double q_norm = sqrt(qw*qw + qx*qx + qy*qy + qz*qz);
qw /= q_norm;
qx /= q_norm;
qy /= q_norm;
qz /= q_norm;
double R11 = 1.0-2*qy*qy-2*qz*qz; double R12 = 2*qx*qy-2*qz*qw; double R13 = 2*qx*qz+2*qy*qw;
double R21 = 2*qx*qy+2*qz*qw; double R22 = 1.0-2*qx*qx-2*qz*qz; double R23 = 2*qz*qy-2*qx*qw;
double R31 = 2*qx*qz-2*qy*qw; double R32 = 2*qy*qz+2*qx*qw; double R33 = 1.0-2*qx*qx-2*qy*qy;
vR11.push_back(R11); vR12.push_back(R12); vR13.push_back(R13);
vR21.push_back(R21); vR22.push_back(R22); vR23.push_back(R23);
vR31.push_back(R31); vR32.push_back(R32); vR33.push_back(R33);
vm1.push_back(rt[7*iFrame+4]);
vm2.push_back(rt[7*iFrame+5]);
vm3.push_back(rt[7*iFrame+6]);
//cout << R11 << " " << R12 << " " << R13 << endl;
//cout << R21 << " " << R22 << " " << R23 << endl;
//cout << R31 << " " << R32 << " " << R33 << endl;
}
//vector<CvMat *> vP = (((AdditionalData *) adata)->vP);
double R11 = 1; double R12 = 0; double R13 = 0;
double R21 = 0; double R22 = 1; double R23 = 0;
double R31 = 0; double R32 = 0; double R33 = 1;
for (int iFrame = 0; iFrame < nFrames; iFrame++)
{
double R11_t, R12_t, R13_t, R21_t, R22_t, R23_t, R31_t, R32_t, R33_t;
R11_t = vR11[iFrame]*R11 + vR12[iFrame]*R21 + vR13[iFrame]*R31;
R12_t = vR11[iFrame]*R12 + vR12[iFrame]*R22 + vR13[iFrame]*R32;
R13_t = vR11[iFrame]*R13 + vR12[iFrame]*R23 + vR13[iFrame]*R33;
R21_t = vR21[iFrame]*R11 + vR22[iFrame]*R21 + vR23[iFrame]*R31;
R22_t = vR21[iFrame]*R12 + vR22[iFrame]*R22 + vR23[iFrame]*R32;
R23_t = vR21[iFrame]*R13 + vR22[iFrame]*R23 + vR23[iFrame]*R33;
R31_t = vR31[iFrame]*R11 + vR32[iFrame]*R21 + vR33[iFrame]*R31;
R32_t = vR31[iFrame]*R12 + vR32[iFrame]*R22 + vR33[iFrame]*R32;
R33_t = vR31[iFrame]*R13 + vR32[iFrame]*R23 + vR33[iFrame]*R33;
R11 = R11_t; R12 = R12_t; R13 = R13_t;
R21 = R21_t; R22 = R22_t; R23 = R23_t;
R31 = R31_t; R32 = R32_t; R33 = R33_t;
}
double qw = sqrt(abs(1.0+R11+R22+R33))/2;
double qx, qy, qz;
if (qw > QW_ZERO)
{
qx = (R32-R23)/4/qw;
qy = (R13-R31)/4/qw;
qz = (R21-R12)/4/qw;
}
else
{
double d = sqrt((R12*R12*R13*R13+R12*R12*R23*R23+R13*R13*R23*R23));
qx = R12*R13/d;
qy = R12*R23/d;
qz = R13*R23/d;
}
double norm_q = sqrt(qx*qx+qy*qy+qz*qz+qw*qw);
hx[0] = qw/norm_q;
hx[1] = qx/norm_q;
hx[2] = qy/norm_q;
hx[3] = qz/norm_q;
//cout << qw/norm_q << " " << qx/norm_q << " " << qy/norm_q << " " << qz/norm_q << endl;
vector<CvMat *> *vx1 = (((AdditionalData *) adata)->vx1);
vector<CvMat *> *vx2 = (((AdditionalData *) adata)->vx2);
int idx = 4;
for (int iFrame = 0; iFrame < nFrames; iFrame++)
{
double E11 = -vm3[iFrame]*vR21[iFrame] + vm2[iFrame]*vR31[iFrame];
double E12 = -vm3[iFrame]*vR22[iFrame] + vm2[iFrame]*vR32[iFrame];
double E13 = -vm3[iFrame]*vR23[iFrame] + vm2[iFrame]*vR33[iFrame];
double E21 = vm3[iFrame]*vR11[iFrame] - vm1[iFrame]*vR31[iFrame];
double E22 = vm3[iFrame]*vR12[iFrame] - vm1[iFrame]*vR32[iFrame];
double E23 = vm3[iFrame]*vR13[iFrame] - vm1[iFrame]*vR33[iFrame];
double E31 = -vm2[iFrame]*vR11[iFrame] + vm1[iFrame]*vR21[iFrame];
double E32 = -vm2[iFrame]*vR12[iFrame] + vm1[iFrame]*vR22[iFrame];
double E33 = -vm2[iFrame]*vR13[iFrame] + vm1[iFrame]*vR23[iFrame];
double out = 0;
if ((*vx1)[iFrame]->rows == 1)
continue;
for (int ix = 0; ix < (*vx1)[iFrame]->rows; ix++)
{
double x1 = cvGetReal2D((*vx1)[iFrame], ix, 0);
double x2 = cvGetReal2D((*vx1)[iFrame], ix, 1);
double x3 = 1;
double xp1 = cvGetReal2D((*vx2)[iFrame], ix, 0);
double xp2 = cvGetReal2D((*vx2)[iFrame], ix, 1);
double xp3 = 1;
double Ex1 = E11*x1 + E12*x2 + E13*x3;
double Ex2 = E21*x1 + E22*x2 + E23*x3;
double Ex3 = E31*x1 + E32*x2 + E33*x3;
double Etxp1 = E11*xp1 + E21*xp2 + E31*xp3;
double Etxp2 = E12*xp1 + E22*xp2 + E32*xp3;
double Etxp3 = E13*xp1 + E23*xp2 + E33*xp3;
double xpEx = xp1*Ex1 + xp2*Ex2 + xp3*Ex3;
double dist = xpEx*xpEx * (1/(Ex1*Ex1+Ex2*Ex2)+1/(Etxp1*Etxp1+Etxp2*Etxp2));
out += sqrt(dist)/(*vx1)[iFrame]->rows;
//hx[idx] = dist;
//idx++;
}
for (int j = 0; j < 10; j++)
{
idx++;
hx[idx] = 0.1*out;
}
}
}
void ObjectiveOrientationRefinement1(double *rt, double *hx, int m, int n, void *adata)
{
// Set orientation
double qw = (((AdditionalData *) adata)->qw);
double qx = (((AdditionalData *) adata)->qx);
double qy = (((AdditionalData *) adata)->qy);
double qz = (((AdditionalData *) adata)->qz);
double q_norm = sqrt(qw*qw + qx*qx + qy*qy + qz*qz);
qw /= q_norm;
qx /= q_norm;
qy /= q_norm;
qz /= q_norm;
double R11 = 1.0-2*qy*qy-2*qz*qz; double R12 = 2*qx*qy-2*qz*qw; double R13 = 2*qx*qz+2*qy*qw;
double R21 = 2*qx*qy+2*qz*qw; double R22 = 1.0-2*qx*qx-2*qz*qz; double R23 = 2*qz*qy-2*qx*qw;
double R31 = 2*qx*qz-2*qy*qw; double R32 = 2*qy*qz+2*qx*qw; double R33 = 1.0-2*qx*qx-2*qy*qy;
double m1 = rt[0];
double m2 = rt[1];
double m3 = rt[2];
double norm_m = sqrt(m1*m1+m2*m2+m3*m3);
m1 /= norm_m;
m2 /= norm_m;
m3 /= norm_m;
vector<double> *vx1 = (((AdditionalData *) adata)->vx1_a);
vector<double> *vy1 = (((AdditionalData *) adata)->vy1_a);
vector<double> *vx2 = (((AdditionalData *) adata)->vx2_a);
vector<double> *vy2 = (((AdditionalData *) adata)->vy2_a);
double E11 = -m3*R21 + m2*R31;
double E12 = -m3*R22 + m2*R32;
double E13 = -m3*R23 + m2*R33;
double E21 = m3*R11 - m1*R31;
double E22 = m3*R12 - m1*R32;
double E23 = m3*R13 - m1*R33;
double E31 = -m2*R11 + m1*R21;
double E32 = -m2*R12 + m1*R22;
double E33 = -m2*R13 + m1*R23;
for (int ix = 0; ix < (*vx1).size(); ix++)
{
double x1 = (*vx1)[ix];
double x2 = (*vy1)[ix];
double x3 = 1;
double xp1 = (*vx2)[ix];
double xp2 = (*vy2)[ix];
double xp3 = 1;
double Ex1 = E11*x1 + E12*x2 + E13*x3;
double Ex2 = E21*x1 + E22*x2 + E23*x3;
double Ex3 = E31*x1 + E32*x2 + E33*x3;
double Etxp1 = E11*xp1 + E21*xp2 + E31*xp3;
double Etxp2 = E12*xp1 + E22*xp2 + E32*xp3;
double Etxp3 = E13*xp1 + E23*xp2 + E33*xp3;
double xpEx = xp1*Ex1 + xp2*Ex2 + xp3*Ex3;
double dist = xpEx*xpEx * (1/(Ex1*Ex1+Ex2*Ex2)+1/(Etxp1*Etxp1+Etxp2*Etxp2));
hx[ix] = 100*dist;
}
}
void CameraCenterInterpolationWithDegree(CvMat *R_1, vector<int> vFrame1, vector<int> vFrame2, vector<CvMat *> vM, vector<CvMat *> vm,
vector<int> vFrame1_r, vector<int> vFrame2_r, vector<CvMat *> vM_r, vector<CvMat *> vm_r,
vector<CvMat *> vC_c, vector<CvMat *> vR_c, vector<int> vFrame_c, vector<CvMat *> &vC, vector<CvMat *> &vR, double weight)
{
// Frame normalization
int first = vFrame1[0];
for (int iFrame = 0; iFrame < vFrame1.size(); iFrame++)
{
vFrame1[iFrame] = vFrame1[iFrame] - first;
vFrame2[iFrame] = vFrame2[iFrame] - first;
double m1 = cvGetReal2D(vm[iFrame], 0, 0);
double m2 = cvGetReal2D(vm[iFrame], 1, 0);
double m3 = cvGetReal2D(vm[iFrame], 2, 0);
double norm_m = sqrt(m1*m1+m2*m2+m3*m3);
ScalarMul(vm[iFrame], 1/norm_m, vm[iFrame]);
}
for (int iFrame = 0; iFrame < vFrame1_r.size(); iFrame++)
{
vFrame1_r[iFrame] = vFrame1_r[iFrame] - first;
vFrame2_r[iFrame] = vFrame2_r[iFrame] - first;
double m1 = cvGetReal2D(vm_r[iFrame], 0, 0);
double m2 = cvGetReal2D(vm_r[iFrame], 1, 0);
double m3 = cvGetReal2D(vm_r[iFrame], 2, 0);
double norm_m = sqrt(m1*m1+m2*m2+m3*m3);
ScalarMul(vm_r[iFrame], 1/norm_m, vm_r[iFrame]);
}
for (int iFrame = 0; iFrame < vFrame_c.size(); iFrame++)
{
vFrame_c[iFrame] = vFrame_c[iFrame] - first;
}
int nFrames = vFrame_c[vFrame_c.size()-1] - vFrame_c[0]+1;
vR.resize(nFrames);
vector<bool> vIsR(nFrames, false);
for (int ic = 0; ic < vFrame_c.size(); ic++)
{
vR[vFrame_c[ic]] = cvCloneMat(vR_c[ic]);
vIsR[vFrame_c[ic]] = true;
}
for (int iFrame = 0; iFrame < vFrame1.size(); iFrame++)
{
CvMat *R = cvCreateMat(3,3,CV_32FC1);
int j = 0;
if (!vIsR[vFrame1[iFrame]-j])
{
while (!vIsR[vFrame1[iFrame]-j])
{
j++;
}
for (int i = j-1; i >= 0; i--)
{
vR[vFrame1[iFrame]-i] = cvCloneMat(vR[vFrame1[iFrame]-j]);
}
}
cvMatMul(vM[iFrame], vR[vFrame1[iFrame]], R);
vR[vFrame2[iFrame]] = cvCloneMat(R);
vIsR[vFrame2[iFrame]] = true;
cvReleaseMat(&R);
}
for (int ic = 0; ic < vFrame_c.size(); ic++)
{
vR[vFrame_c[ic]] = cvCloneMat(vR_c[ic]);
}
int nBasis = floor((double)nFrames/3);
CvMat *theta_all = cvCreateMat(nFrames, nFrames, CV_32FC1);
GetIDCTMappingMatrix(theta_all, nFrames);
CvMat *theta_i = cvCreateMat(1, nBasis, CV_32FC1);
CvMat *Theta_i = cvCreateMat(3, 3*nBasis, CV_32FC1);
CvMat *A = cvCreateMat(3*vM.size(), 3*nBasis, CV_32FC1);
CvMat *b = cvCreateMat(3*vM.size(), 1, CV_32FC1);
cvSetZero(b);
for (int im = 0; im < vM.size(); im++)
{
for (int ith = 0; ith < nBasis; ith++)
{
cvSetReal2D(theta_i, 0, ith, cvGetReal2D(theta_all, vFrame1[im], ith)-cvGetReal2D(theta_all, vFrame2[im], ith));
}
SetSubMat(Theta_i, 0, 0, theta_i);
SetSubMat(Theta_i, 1, nBasis, theta_i);
SetSubMat(Theta_i, 2, 2*nBasis, theta_i);
CvMat *skewm = cvCreateMat(3,3,CV_32FC1);
Vec2Skew(vm[im], skewm);
CvMat *temp33 = cvCreateMat(3,3,CV_32FC1);
cvMatMul(skewm, vR[vFrame2[im]], temp33);
CvMat *temp3nBasis = cvCreateMat(3, 3*nBasis, CV_32FC1);
cvMatMul(temp33, Theta_i, temp3nBasis);
SetSubMat(A, 3*im, 0, temp3nBasis);
cvReleaseMat(&skewm);
cvReleaseMat(&temp33);
cvReleaseMat(&temp3nBasis);
}
CvMat *A_r = cvCreateMat(3*vM_r.size(), 3*nBasis, CV_32FC1);
CvMat *b_r = cvCreateMat(3*vM_r.size(), 1, CV_32FC1);
cvSetZero(b_r);
for (int im = 0; im < vM_r.size(); im++)
{
for (int ith = 0; ith < nBasis; ith++)
{
cvSetReal2D(theta_i, 0, ith, cvGetReal2D(theta_all, vFrame1_r[im], ith)-cvGetReal2D(theta_all, vFrame2_r[im], ith));
}
SetSubMat(Theta_i, 0, 0, theta_i);
SetSubMat(Theta_i, 1, nBasis, theta_i);
SetSubMat(Theta_i, 2, 2*nBasis, theta_i);
CvMat *skewm = cvCreateMat(3,3,CV_32FC1);
Vec2Skew(vm_r[im], skewm);
CvMat *temp33 = cvCreateMat(3,3,CV_32FC1);
cvMatMul(skewm, vR[vFrame2_r[im]], temp33);
CvMat *temp3nBasis = cvCreateMat(3, 3*nBasis, CV_32FC1);
cvMatMul(temp33, Theta_i, temp3nBasis);
SetSubMat(A_r, 3*im, 0, temp3nBasis);
cvReleaseMat(&skewm);
cvReleaseMat(&temp33);
cvReleaseMat(&temp3nBasis);
}
CvMat *A_c = cvCreateMat(3*vFrame_c.size(), 3*nBasis, CV_32FC1);
CvMat *b_c = cvCreateMat(3*vFrame_c.size(), 1, CV_32FC1);
for (int ic = 0; ic < vFrame_c.size(); ic++)
{
for (int ith = 0; ith < nBasis; ith++)
{
cvSetReal2D(theta_i, 0, ith, cvGetReal2D(theta_all, vFrame_c[ic], ith));
}
SetSubMat(Theta_i, 0, 0, theta_i);
SetSubMat(Theta_i, 1, nBasis, theta_i);
SetSubMat(Theta_i, 2, 2*nBasis, theta_i);
SetSubMat(A_c, 3*ic, 0, Theta_i);
SetSubMat(b_c, 3*ic, 0, vC_c[ic]);
}
ScalarMul(A_c, weight, A_c);
ScalarMul(b_c, weight, b_c);
CvMat *At = cvCreateMat(A->rows+A_r->rows+A_c->rows, A->cols, CV_32FC1);
CvMat *bt = cvCreateMat(A->rows+A_r->rows+A_c->rows, 1, CV_32FC1);
SetSubMat(At, 0, 0, A);
SetSubMat(bt, 0, 0, b);
SetSubMat(At, A->rows, 0, A_r);
SetSubMat(bt, A->rows, 0, b_r);
SetSubMat(At, A->rows+A_r->rows, 0, A_c);
SetSubMat(bt, A->rows+A_r->rows, 0, b_c);
CvMat *beta = cvCreateMat(3*nBasis, 1, CV_32FC1);
cvSolve(At, bt, beta);
//cvSolve(A_c, b_c, beta);
for (int iFrame = 0; iFrame < nFrames; iFrame++)
{
for (int ith = 0; ith < nBasis; ith++)
{
cvSetReal2D(theta_i, 0, ith, cvGetReal2D(theta_all, iFrame, ith));
}
SetSubMat(Theta_i, 0, 0, theta_i);
SetSubMat(Theta_i, 1, nBasis, theta_i);
SetSubMat(Theta_i, 2, 2*nBasis, theta_i);
CvMat *C = cvCreateMat(3,1,CV_32FC1);
cvMatMul(Theta_i, beta, C);
vC.push_back(C);
}
cvReleaseMat(&beta);
cvReleaseMat(&At);
cvReleaseMat(&bt);
cvReleaseMat(&A);
cvReleaseMat(&b);
cvReleaseMat(&A_r);
cvReleaseMat(&b_r);
cvReleaseMat(&A_c);
cvReleaseMat(&b_c);
cvReleaseMat(&theta_all);
cvReleaseMat(&theta_i);
cvReleaseMat(&Theta_i);
}
void SparseBundleAdjustment_KDMOT(vector<Feature> vFeature, vector<int> vUsedFrame, vector<CvMat *> &cP, CvMat *X, vector<Camera> vCamera, vector<int> visibleStructureID)
{
PrintAlgorithm("Sparse bundle adjustment motion only");
vector<double> cameraParameter, feature2DParameter;
vector<char> vMask;
double *dCovFeatures = 0;
AdditionalData adata;// focal_x focal_y princ_x princ_y
int max_nFrames = 0;
for (int iCamera = 0; iCamera < vCamera.size(); iCamera++)
{
for (int iFrame = 0; iFrame < vCamera[iCamera].vTakenFrame.size(); iFrame++)
{
if (vCamera[iCamera].vTakenFrame[iFrame] > max_nFrames)
max_nFrames = vCamera[iCamera].vTakenFrame[iFrame];
}
}
max_nFrames++;
adata.max_nFrames = max_nFrames;
adata.vUsedFrame = vUsedFrame;
GetParameterForSBA_KDRT(vFeature, vUsedFrame, cP, X, vCamera, max_nFrames, visibleStructureID, cameraParameter, feature2DParameter, vMask);
int nCameraParam = 7+4+2;
int nFeatures = vFeature.size();
int nFrames = vUsedFrame.size();
char *dVMask = (char *) malloc(vMask.size() * sizeof(char));
double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double));
double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double));
for (int i = 0; i < cameraParameter.size(); i++)
dCameraParameter[i] = cameraParameter[i];
for (int i = 0; i < vMask.size(); i++)
dVMask[i] = vMask[i];
for (int i = 0; i < feature2DParameter.size(); i++)
dFeature2DParameter[i] = feature2DParameter[i];
adata.XYZ = &(dCameraParameter[nCameraParam*vUsedFrame.size()]);
double opt[5];
opt[0] = 1e-3;
opt[1] = 1e-12;
opt[2] = 1e-12;
opt[3] = 1e-12;
opt[4] = 0;
double info[12];
sba_mot_levmar(visibleStructureID.size(), vUsedFrame.size(), 1, dVMask, dCameraParameter, nCameraParam, dFeature2DParameter, dCovFeatures, 2, Projection3Donto2D_KDMOT, NULL, &adata,
1e+3, 0, opt, info);
PrintSBAInfo(info);
RetrieveParameterFromSBA_KDRT(dCameraParameter, vCamera, cP, X, visibleStructureID, vUsedFrame, max_nFrames);
free(dVMask);
free(dFeature2DParameter);
free(dCameraParameter);
}
void SparseBundleAdjustment_TEMPORAL(vector<Feature> vFeature, vector<Theta> &vTheta, vector<Camera> &vCamera)
{
PrintAlgorithm("Sparse bundle adjustment - Temporal adjustment");
vector<double> cameraParameter, feature2DParameter;
vector<char> vMask;
double *dCovFeatures = 0;
AdditionalData adata;// focal_x focal_y princ_x princ_y
int max_nFrames = 0;
for (int iCamera = 0; iCamera < vCamera.size(); iCamera++)
{
for (int iFrame = 0; iFrame < vCamera[iCamera].vTakenFrame.size(); iFrame++)
{
if (vCamera[iCamera].vTakenFrame[iFrame] > max_nFrames)
max_nFrames = vCamera[iCamera].vTakenFrame[iFrame];
}
}
max_nFrames++;
adata.max_nFrames = max_nFrames;
vector<int> vUsedFrame;
vector<CvMat *> vP;
vector<double> vdP;
for (int iCamera = 0; iCamera < vCamera.size(); iCamera++)
{
for (int iFrame = 0; iFrame < vCamera[iCamera].vTakenFrame.size(); iFrame++)
{
vUsedFrame.push_back(iCamera*max_nFrames+vCamera[iCamera].vTakenFrame[iFrame]);
vP.push_back(vCamera[iCamera].vP[iFrame]);
for (int iP = 0; iP < 3; iP++)
for (int jP = 0; jP < 4; jP++)
vdP.push_back(cvGetReal2D(vCamera[iCamera].vP[iFrame], iP, jP));
}
}
adata.vUsedFrame = vUsedFrame;
adata.vP = vP;
adata.vdP = vdP;
adata.nBase = vTheta[0].thetaX.size();
adata.vTheta = vTheta;
GetParameterForSBA_TEMPORAL(vFeature, vTheta, vCamera, max_nFrames, cameraParameter, feature2DParameter, vMask);
int nCameraParam = 1;
int nFeatures = vTheta.size();
int nFrames = vUsedFrame.size();
char *dVMask = (char *) malloc(vMask.size() * sizeof(char));
double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double));
double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double));
for (int i = 0; i < cameraParameter.size(); i++)
dCameraParameter[i] = cameraParameter[i];
for (int i = 0; i < vMask.size(); i++)
dVMask[i] = vMask[i];
for (int i = 0; i < feature2DParameter.size(); i++)
dFeature2DParameter[i] = feature2DParameter[i];
adata.XYZ = &(dCameraParameter[nCameraParam*vUsedFrame.size()]);
double opt[5];
opt[0] = 1e-3;
opt[1] = 1e-5;
opt[2] = 1e-5;
opt[3] = 1e-5;
opt[4] = 0;
double info[12];
sba_motstr_levmar(vTheta.size(), 0, vUsedFrame.size(), 0, dVMask, dCameraParameter, nCameraParam, 3*adata.nBase, dFeature2DParameter, dCovFeatures, 4, ProjectionThetaonto2D_TEMPORAL, NULL, &adata,
1e+3, 0, opt, info);
PrintSBAInfo(info);
RetrieveParameterFromSBA_TEMPORAL(dCameraParameter, vCamera, vTheta);
free(dVMask);
free(dFeature2DParameter);
free(dCameraParameter);
}
void SparseBundleAdjustment_TEMPORAL_LEVMAR(vector<Feature> vFeature, vector<Theta> &vTheta, vector<Camera> &vCamera)
{
//for (int i = 0; i < 106; i++)
//{
// vFeature.pop_back();
// vTheta.pop_back();
//}
//PrintAlgorithm("Sparse bundle adjustment - Temporal adjustment, Levenburg-Marquedt");
//vector<double> cameraParameter, feature2DParameter;
//vector<char> vMask;
//double *dCovFeatures = 0;
//AdditionalData adata;// focal_x focal_y princ_x princ_y
//int max_nFrames = 0;
//for (int iCamera = 0; iCamera < vCamera.size(); iCamera++)
//{
// for (int iFrame = 0; iFrame < vCamera[iCamera].vTakenFrame.size(); iFrame++)
// {
// if (vCamera[iCamera].vTakenFrame[iFrame] > max_nFrames)
// max_nFrames = vCamera[iCamera].vTakenFrame[iFrame];
// }
//}
//max_nFrames++;
//adata.max_nFrames = max_nFrames;
//vector<int> vUsedFrame;
//vector<CvMat *> vP;
//vector<double> vdP;
//for (int iCamera = 0; iCamera < vCamera.size(); iCamera++)
//{
// for (int iFrame = 0; iFrame < vCamera[iCamera].vTakenFrame.size(); iFrame++)
// {
// vUsedFrame.push_back(iCamera*max_nFrames+vCamera[iCamera].vTakenFrame[iFrame]);
// vP.push_back(vCamera[iCamera].vP[iFrame]);
// for (int iP = 0; iP < 3; iP++)
// for (int jP = 0; jP < 4; jP++)
// vdP.push_back(cvGetReal2D(vCamera[iCamera].vP[iFrame], iP, jP));
// }
//}
//adata.vUsedFrame = vUsedFrame;
////adata.vP = vP;
//adata.vdP = vdP;
//adata.nBase = vTheta[0].thetaX.size();
//adata.nFeatures = vTheta.size();
//adata.vTheta = vTheta;
//GetParameterForSBA_TEMPORAL_LEVMAR(vFeature, vTheta, vCamera, max_nFrames, cameraParameter, feature2DParameter);
//int nCameraParam = 1;
//int nFeatures = vTheta.size();
//int nFrames = vUsedFrame.size();
////char *dVMask = (char *) malloc(vMask.size() * sizeof(char));
//double *dFeature2DParameter = (double *) malloc((feature2DParameter.size()+nFeatures) * sizeof(double));
//double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double));
//for (int i = 0; i < cameraParameter.size(); i++)
// dCameraParameter[i] = cameraParameter[i];
//for (int i = 0; i < feature2DParameter.size(); i++)
// dFeature2DParameter[i] = feature2DParameter[i]/1e-6;
//for (int i = 0; i < nFeatures; i++)
// dFeature2DParameter[feature2DParameter.size()+i] = 0.0;
//adata.isStatic = false;
////adata.XYZ = &(dCameraParameter[nCameraParam*vUsedFrame.size()]);
//adata.measurements = feature2DParameter;
//double opt[5];
//opt[0] = 1e-1;
//opt[1] = 1e-20;
//opt[2] = 1e-15;
//opt[3] = 1e-15;
//opt[4] = 0;
//double info[12];
//double *work = (double*)malloc((LM_DIF_WORKSZ(cameraParameter.size(), feature2DParameter.size()+nFeatures)+cameraParameter.size()*cameraParameter.size())*sizeof(double));
//if(!work)
// fprintf(stderr, "memory allocation request failed in main()\n");
//int ret = dlevmar_dif(ProjectionThetaonto2D_TEMPORAL_LEVMAR, dCameraParameter, dFeature2DParameter, cameraParameter.size(), feature2DParameter.size()+nFeatures,
// 1e+3, opt, info, work, NULL, &adata);
//cout << ret << endl;
//PrintSBAInfo(info);
//RetrieveParameterFromSBA_TEMPORAL(dCameraParameter, vCamera, vTheta);
//free(dFeature2DParameter);
//free(dCameraParameter);
}
void GlobalBundleAdjustment(vector<Feature> vFeature, vector<Camera> vCamera, vector<Theta> vTheta, CvMat *K, int nFrames, int nBase, int nFeatures_static)
{
//PrintAlgorithm("Global bundle adjustment motion and structure");
//vector<double> cameraParameter, feature2DParameter;
//vector<char> vMask;
//double *dCovFeatures = 0;
//AdditionalData adata;// focal_x focal_y princ_x princ_y
//double intrinsic[4];
//intrinsic[0] = cvGetReal2D(K, 0, 0);
//intrinsic[1] = cvGetReal2D(K, 1, 1);
//intrinsic[2] = cvGetReal2D(K, 0, 2);
//intrinsic[3] = cvGetReal2D(K, 1, 2);
//adata.intrinsic = intrinsic;
//adata.nCameraParameters = 7;
//adata.nImagePointPrameraters = 2;
//adata.nBase = nBase;
//adata.nFrames = nFrames;
//adata.nFeature_static = nFeatures_static;
//bool *isStatic = (bool *) malloc(vFeature.size() * sizeof(bool));
//for (int iStatic = 0; iStatic < vFeature.size(); iStatic++)
//{
// if (iStatic < nFeatures_static)
// isStatic[iStatic] = true;
// else
// isStatic[iStatic] = false;
//}
//adata.isStatic = isStatic;
//GetParameterForGBA(vFeature, vCamera, vTheta, K, nFrames, cameraParameter, feature2DParameter, vMask);
//int NZ = 0;
//for (int i = 0; i < vMask.size(); i++)
//{
// if (vMask[i])
// NZ++;
//}
//double nCameraParam = 7;
//int nFeatures = vFeature.size();
//char *dVMask = (char *) malloc(vMask.size() * sizeof(char));
//double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double));
//double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double));
//for (int i = 0; i < cameraParameter.size(); i++)
// dCameraParameter[i] = cameraParameter[i];
//for (int i = 0; i < vMask.size(); i++)
// dVMask[i] = vMask[i];
//for (int i = 0; i < feature2DParameter.size(); i++)
// dFeature2DParameter[i] = feature2DParameter[i];
//double opt[5];
//opt[0] = 1e-3;
//opt[1] = 1e-5;//1e-12;
//opt[2] = 1e-5;//1e-12;
//opt[3] = 1e-5;//1e-12;
//opt[4] = 0;
//double info[12];
//sba_motstr_levmar_x(vFeature.size(), 0, nFrames*vCamera.size(), 1, dVMask, dCameraParameter, nCameraParam, 3*nBase, dFeature2DParameter, dCovFeatures, 2, ProjectionThetaonto2D_MOTSTR_x, NULL, &adata,
// 1e+3, 0, opt, info);
//PrintSBAInfo(info);
//RetrieveParameterFromGBA(dCameraParameter, K, vCamera, vTheta, nFrames);
//free(isStatic);
//free(dVMask);
//free(dFeature2DParameter);
//free(dCameraParameter);
}
void GlobalBundleAdjustment_LEVMAR(vector<Feature> vFeature, vector<Camera> vCamera, vector<Theta> vTheta, CvMat *K, int nFrames, int nBase, int nFeatures_static)
{
//PrintAlgorithm("Global bundle adjustment motion and structure");
//vector<double> cameraParameter, feature2DParameter;
//double *dCovFeatures = 0;
//AdditionalData adata;// focal_x focal_y princ_x princ_y
//double intrinsic[4];
//intrinsic[0] = cvGetReal2D(K, 0, 0);
//intrinsic[1] = cvGetReal2D(K, 1, 1);
//intrinsic[2] = cvGetReal2D(K, 0, 2);
//intrinsic[3] = cvGetReal2D(K, 1, 2);
//adata.intrinsic = intrinsic;
//adata.nCameraParameters = 7;
//adata.nImagePointPrameraters = 2;
//adata.nBase = nBase;
//adata.nFrames = nFrames*vCamera.size();
//adata.nFeature_static = nFeatures_static;
//bool *isStatic = (bool *) malloc(vFeature.size() * sizeof(bool));
//for (int iStatic = 0; iStatic < vFeature.size(); iStatic++)
//{
// if (iStatic < nFeatures_static)
// isStatic[iStatic] = true;
// else
// isStatic[iStatic] = false;
//}
//adata.isStatic = isStatic;
//adata.nNZ = (double)feature2DParameter.size()/2;
//CvMat visibilityMask;
//GetParameterForGBA(vFeature, vCamera, vTheta, K, nFrames, cameraParameter, feature2DParameter, visibilityMask);
//CvMat *vMask = cvCreateMat(visibilityMask.rows, visibilityMask.cols, CV_32FC1);
//vMask = cvCloneMat(&visibilityMask);
//adata.visibilityMask = vMask;
//double nCameraParam = 7;
//int nFeatures = vFeature.size();
//double *dFeature2DParameter = (double *) malloc(feature2DParameter.size() * sizeof(double));
//double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double));
//double opt[5];
//opt[0] = 1e-3;
//opt[1] = 1e-5;//1e-12;
//opt[2] = 1e-5;//1e-12;
//opt[3] = 1e-5;//1e-12;
//opt[4] = 0;
//double info[12];
//double *work=(double*)malloc((LM_DIF_WORKSZ(cameraParameter.size(), feature2DParameter.size())+cameraParameter.size()*cameraParameter.size())*sizeof(double));
//if(!work)
// fprintf(stderr, "memory allocation request failed in main()\n");
//feature2DParameter.clear();
//cameraParameter.clear();
//for (int i = 0; i < 10000;i++)
// feature2DParameter.push_back(0);
//for (int i = 0; i < 10000-1; i++)
// cameraParameter.push_back(0);
//for (int i = 0; i < cameraParameter.size(); i++)
// dCameraParameter[i] = cameraParameter[i];
//for (int i = 0; i < feature2DParameter.size(); i++)
// dFeature2DParameter[i] = feature2DParameter[i];
//slevmar_dif(ProjectionThetaonto2D_MOTSTR_LEVMAR, (float*)dCameraParameter, (float*)dFeature2DParameter, cameraParameter.size(), feature2DParameter.size(),
// 1e+3, (float*)opt, (float*)info, (float*)work, NULL, &adata);
//PrintSBAInfo(info);
//RetrieveParameterFromGBA(dCameraParameter, K, vCamera, vTheta, nFrames);
//cvReleaseMat(&vMask);
//free(isStatic);
//free(dFeature2DParameter);
//free(dCameraParameter);
}
void ProjectionThetaonto2D_MOTSTR_LEVMAR(double *p, double *hx, int m, int n, void *adata_)
{
//for (int i = 0; i <n; i++)
// hx[i] = 1;
//return;
//AdditionalData *adata = (AdditionalData *)adata_;
//bool *isStatic = adata->isStatic;
//int nFrames = adata->nFrames;
//int nCameraParameters = adata->nCameraParameters;
//int nImagePointParameters = adata->nImagePointPrameraters;
//int nBase = adata->nBase;
//int nFeature_static = adata->nFeature_static;
//double *XYZ = p + nCameraParameters*nFrames;
//double *rt;
//double *xij;
//
//int last = 0;
//for (int iFeature = 0; iFeature < ((AdditionalData*)adata_)->visibilityMask->rows; iFeature++)
//{
// for (int iFrame = 0; iFrame < ((AdditionalData*)adata_)->visibilityMask->cols; iFrame++)
// {
// if (cvGetReal2D(((AdditionalData*)adata_)->visibilityMask, iFeature, iFrame))
// {
// if (isStatic[iFeature])
// {
// double x, y;
// //xij = hx + nImagePointParameters*last;
// rt = p + iFrame*nCameraParameters;
// XYZ = p + nFrames*nCameraParameters + iFeature*3;
// ProjectionThetaonto2D_MOTSTR_LEVMAR(iFrame, iFeature, rt, XYZ, x, y, adata);
// hx[nImagePointParameters*last] = 0;
// hx[nImagePointParameters*last+1] = 0;
// last++;
// }
// else
// {
// double x, y;
// //xij = hx + nImagePointParameters*last;
// rt = p + iFrame*nCameraParameters;
// XYZ = p + nFrames*nCameraParameters + nFeature_static*3 + (iFeature-nFeature_static)*3*nBase;
// ProjectionThetaonto2D_MOTSTR_LEVMAR(iFrame, iFeature, rt, XYZ, x, y, adata);
// hx[nImagePointParameters*last] = 0;
// hx[nImagePointParameters*last+1] = 0;
// last++;
// }
// }
// }
//}
}
void ProjectionThetaonto2D_TEMPORAL_LEVMAR(double *p, double *hx, int m, int n, void *adata)
{
if (!((AdditionalData *)adata)->isStatic)
{
((AdditionalData *)adata)->isStatic = true;
((AdditionalData *)adata)->ptr = p;
}
p = ((AdditionalData *)adata)->ptr;
for (int ihx = 0; ihx < n; ihx++)
hx[ihx] = 0.0;
int max_nFrames = ((AdditionalData *) adata)->max_nFrames;
int nFeatures = ((AdditionalData *) adata)->nFeatures;
vector<int> vUsedFrame = ((AdditionalData *) adata)->vUsedFrame;
int nBase = ((AdditionalData*) adata)->nBase;
vector<Theta> vTheta = ((AdditionalData *) adata)->vTheta;
vector<double> measurements = ((AdditionalData *) adata)->measurements;
for (int iFeature = 0; iFeature < nFeatures; iFeature++)
{
double *xyz = p+vUsedFrame.size()+nBase*3*iFeature;
for (int iFrame = 0; iFrame < vUsedFrame.size(); iFrame++)
{
double *rt = p+iFrame;
int iCamera = (int)((double)vUsedFrame[iFrame]/max_nFrames);
int cFrame = vUsedFrame[iFrame] % max_nFrames;
CvMat *P = cvCreateMat(3,4, CV_32FC1);
for (int iP = 0; iP < 3; iP++)
for (int jP = 0; jP < 4; jP++)
cvSetReal2D(P, iP, jP, ((AdditionalData *) adata)->vdP[12*iFrame+iP*4+jP]);
double dt = rt[0];
double t = (double)cFrame + dt;
CvMat *B = cvCreateMat(1, nBase, CV_32FC1);
cvSetReal2D(B, 0, 0, sqrt(1.0/(double)max_nFrames));
for (int iB = 1; iB < nBase; iB++)
cvSetReal2D(B, 0, iB, sqrt(2.0/(double)max_nFrames)*cos((2*t-1)*(iB)*PI/2.0/(double)max_nFrames));
CvMat *thetaX = cvCreateMat(nBase,1, CV_32FC1);
CvMat *thetaY = cvCreateMat(nBase,1, CV_32FC1);
CvMat *thetaZ = cvCreateMat(nBase,1, CV_32FC1);
for (int iTheta = 0; iTheta < nBase; iTheta++)
cvSetReal2D(thetaX, iTheta, 0, xyz[iTheta]);
for (int iTheta = 0; iTheta < nBase; iTheta++)
cvSetReal2D(thetaY, iTheta, 0, xyz[nBase+iTheta]);
for (int iTheta = 0; iTheta < nBase; iTheta++)
cvSetReal2D(thetaZ, iTheta, 0, xyz[2*nBase+iTheta]);
CvMat *X3 = cvCreateMat(1,1,CV_32FC1);
CvMat *Y3 = cvCreateMat(1,1,CV_32FC1);
CvMat *Z3 = cvCreateMat(1,1,CV_32FC1);
cvMatMul(B, thetaX, X3);
cvMatMul(B, thetaY, Y3);
cvMatMul(B, thetaZ, Z3);
CvMat *X = cvCreateMat(4,1,CV_32FC1);
cvSetReal2D(X, 0, 0, cvGetReal2D(X3,0,0));
cvSetReal2D(X, 1, 0, cvGetReal2D(Y3,0,0));
cvSetReal2D(X, 2, 0, cvGetReal2D(Z3,0,0));
cvSetReal2D(X, 3, 0, 1);
CvMat *x = cvCreateMat(3,1,CV_32FC1);
cvMatMul(P, X, x);
double pm_x = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0);
double pm_y = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0);
double m_x = measurements[2*(iFeature*vUsedFrame.size()+iFrame)];
double m_y = measurements[2*(iFeature*vUsedFrame.size()+iFrame)+1];
//hx[2*(iFeature*vUsedFrame.size()+iFrame)] = (pm_x-m_x)*(pm_x-m_x);
//hx[2*(iFeature*vUsedFrame.size()+iFrame)+1] = (pm_y-m_y)*(pm_y-m_y);
hx[2*(iFeature*vUsedFrame.size()+iFrame)] = pm_x/1e-6;
hx[2*(iFeature*vUsedFrame.size()+iFrame)+1] = pm_y/1e-6;
cvReleaseMat(&X);
cvReleaseMat(&x);
cvReleaseMat(&P);
cvReleaseMat(&B);
cvReleaseMat(&thetaX);
cvReleaseMat(&thetaY);
cvReleaseMat(&thetaZ);
cvReleaseMat(&X3);
cvReleaseMat(&Y3);
cvReleaseMat(&Z3);
}
int error = 0;
for (int iBase = 0; iBase < nBase; iBase++)
{
error += (xyz[iBase]-vTheta[iFeature].thetaX[iBase])*(xyz[iBase]-vTheta[iFeature].thetaX[iBase]);
}
for (int iBase = 0; iBase < nBase; iBase++)
{
error += (xyz[nBase+iBase]-vTheta[iFeature].thetaY[iBase])*(xyz[nBase+iBase]-vTheta[iFeature].thetaY[iBase]);
}
for (int iBase = 0; iBase < nBase; iBase++)
{
error += (xyz[2*nBase+iBase]-vTheta[iFeature].thetaZ[iBase])*(xyz[2*nBase+iBase]-vTheta[iFeature].thetaZ[iBase]);
}
hx[2*(nFeatures*vUsedFrame.size())+iFeature] = 0.0;//error/10;
}
//for (int i = 0; i < n; i++)
// cout << hx[i] << " ";
//cout << endl;
}
void ProjectionThetaonto2D_MOTSTR_LEVMAR(float *p, float *hx, int m, int n, void *adata_)
{
//for (int i = 0; i <n; i++)
// hx[i] = 1;
//return;
//AdditionalData *adata = (AdditionalData *)adata_;
//bool *isStatic = adata->isStatic;
//int nFrames = adata->nFrames;
//int nCameraParameters = adata->nCameraParameters;
//int nImagePointParameters = adata->nImagePointPrameraters;
//int nBase = adata->nBase;
//int nFeature_static = adata->nFeature_static;
//float *XYZ = p + nCameraParameters*nFrames;
//float *rt;
//float *xij;
//int last = 0;
////for (int iFeature = 0; iFeature < ((AdditionalData*)adata_)->visibilityMask->rows; iFeature++)
////{
//// for (int iFrame = 0; iFrame < ((AdditionalData*)adata_)->visibilityMask->cols; iFrame++)
//// {
//// if (cvGetReal2D(((AdditionalData*)adata_)->visibilityMask, iFeature, iFrame))
//// {
//// if (isStatic[iFeature])
//// {
//// float x, y;
//// //xij = hx + nImagePointParameters*last;
//// rt = p + iFrame*nCameraParameters;
//// XYZ = p + nFrames*nCameraParameters + iFeature*3;
//// ProjectionThetaonto2D_MOTSTR_LEVMAR(iFrame, iFeature, (double*)rt, (double*)XYZ, (double)x, (double)y, adata);
//// hx[nImagePointParameters*last] = 0;
//// hx[nImagePointParameters*last+1] = 0;
//// last++;
//// }
//// else
//// {
//// float x, y;
//// //xij = hx + nImagePointParameters*last;
//// rt = p + iFrame*nCameraParameters;
//// XYZ = p + nFrames*nCameraParameters + nFeature_static*3 + (iFeature-nFeature_static)*3*nBase;
//// ProjectionThetaonto2D_MOTSTR_LEVMAR(iFrame, iFeature, (double*)rt, (double*)XYZ, (double)x, (double)y, adata);
//// hx[nImagePointParameters*last] = 0;
//// hx[nImagePointParameters*last+1] = 0;
//// last++;
//// }
//// }
//// }
////}
}
void ProjectionThetaonto2D_MOTSTR_x(double *p, struct sba_crsm *idxij, int *rcidxs, int *rcsubs, double *hx, void *adata)
{
//int i, j;
//int cnp, pnp, mnp;
//double *pa, *pb, *pqr, *pt, *ppt, *pmeas, *Kparms, *pr0, lrot[4], trot[4];
////int n;
//int m, nnz;
//AdditionalData *gl;
//gl= (AdditionalData *)adata;
//cnp=gl->nCameraParameters;
//mnp=gl->nImagePointPrameraters;
////n=idxij->nr;
//m=idxij->nc;
//pa=p; // Pointer for camera
//pb=p+m*cnp; // Point for xyz
//for(j=0; j<m; ++j)
//{
// /* j-th camera parameters */
// double *rt = pa + j*cnp;
// double *xyz;
// nnz=sba_crsm_col_elmidxs(idxij, j, rcidxs, rcsubs); /* find nonzero hx_ij, i=0...n-1 */
// for(i=0; i<nnz; ++i)
// {
// if (gl->isStatic[i])
// {
// xyz = pb + rcsubs[i]*3;
// }
// else
// {
// xyz = pb + gl->nFeature_static*3 + (rcsubs[i]-gl->nFeature_static)*3*gl->nBase;
// }
// double *xij = hx + idxij->val[rcidxs[i]]*mnp; // set pmeas to point to hx_ij
// ProjectionThetaonto2D_MOTSTR(j, i, rt, xyz, xij, adata);
// //calcImgProjFullR(Kparms, trot, pt, ppt, pmeas); // evaluate Q in pmeas
// //calcImgProj(Kparms, pr0, pqr, pt, ppt, pmeas); // evaluate Q in pmeas
// }
//}
}
void PrintSBAInfo(double *info)
{
cout << "SBA result -------" << endl;
cout << "Mean squared reprojection error: " << info[0] << " ==> " << info[1] << endl;
cout << "Total number of iteration: " << info[5] << endl;
cout << "Reason for terminating: ";
if (info[6] == 1)
cout << "Stopped by small ||J^T e||" <<endl;
else if (info[6] == 2)
cout << "Stopped by small ||delta||" << endl;
else if (info[6] == 3)
cout << "Stopped by maximum iteration" << endl;
else if (info[6] == 4)
cout << "Stopped by small relative reduction in ||e||" << endl;
else if (info[6] == 5)
cout << "Stopped by small ||e||" << endl;
else if (info[6] == 6)
cout << "Stopped due to excessive failed attempts to increase damping for getting a positive definite normal equations" << endl;
else if (info[6] == 7)
cout << "Stopped due to infinite values in the coordinates of the set of predicted projections x" << endl;
cout << "Total number of projection function evaluation: " << info[7] <<endl;
cout << "Total number of times that normal equations were solved: " << info[9] << endl;
}
void PrintSBAInfo(double *info, int nVisiblePoints)
{
cout << "SBA result -------" << endl;
cout << "Mean squared reprojection error: " << info[0]/(double)nVisiblePoints << " ==> " << info[1]/(double)nVisiblePoints << endl;
cout << "Total number of iteration: " << info[5] << endl;
cout << "Reason for terminating: ";
if (info[6] == 1)
cout << "Stopped by small ||J^T e||" <<endl;
else if (info[6] == 2)
cout << "Stopped by small ||delta||" << endl;
else if (info[6] == 3)
cout << "Stopped by maximum iteration" << endl;
else if (info[6] == 4)
cout << "Stopped by small relative reduction in ||e||" << endl;
else if (info[6] == 5)
cout << "Stopped by small ||e||" << endl;
else if (info[6] == 6)
cout << "Stopped due to excessive failed attempts to increase damping for getting a positive definite normal equations" << endl;
else if (info[6] == 7)
cout << "Stopped due to infinite values in the coordinates of the set of predicted projections x" << endl;
cout << "Total number of projection function evaluation: " << info[7] <<endl;
cout << "Total number of times that normal equations were solved: " << info[9] << endl;
}
void RetrieveParameterFromSBA(double *dCameraParameter, CvMat *K, vector<CvMat *> &cP, CvMat *X, vector<int> visibleStructureID)
{
int nFrames = cP.size();
cP.clear();
CvMat *P;
for (int iFrame = 0; iFrame < nFrames; iFrame++)
{
CvMat *q = cvCreateMat(4,1,CV_32FC1);
CvMat *C = cvCreateMat(3,1,CV_32FC1);
cvSetReal2D(q, 0, 0, dCameraParameter[7*iFrame]);
cvSetReal2D(q, 1, 0, dCameraParameter[7*iFrame+1]);
cvSetReal2D(q, 2, 0, dCameraParameter[7*iFrame+2]);
cvSetReal2D(q, 3, 0, dCameraParameter[7*iFrame+3]);
cvSetReal2D(C, 0, 0, dCameraParameter[7*iFrame+4]);
cvSetReal2D(C, 1, 0, dCameraParameter[7*iFrame+5]);
cvSetReal2D(C, 2, 0, dCameraParameter[7*iFrame+6]);
CvMat *R = cvCreateMat(3,3,CV_32FC1);
CvMat *P_ = cvCreateMat(3,4,CV_32FC1);
P = cvCreateMat(3,4,CV_32FC1);
Quaternion2Rotation(q, R);
CreateCameraMatrix(R, C, K, P_);
P = cvCloneMat(P_);
cP.push_back(P);
cvReleaseMat(&q);
cvReleaseMat(&C);
cvReleaseMat(&R);
cvReleaseMat(&P_);
}
P = cvCreateMat(3,4,CV_32FC1);
cvReleaseMat(&P);
CvMat *X_ = cvCreateMat(visibleStructureID.size(), 3, CV_32FC1);
for (int iFeature = 0; iFeature < visibleStructureID.size(); iFeature++)
{
cvSetReal2D(X_, iFeature, 0, dCameraParameter[7*cP.size()+3*iFeature]);
cvSetReal2D(X_, iFeature, 1, dCameraParameter[7*cP.size()+3*iFeature+1]);
cvSetReal2D(X_, iFeature, 2, dCameraParameter[7*cP.size()+3*iFeature+2]);
}
SetIndexedMatRowwise(X, visibleStructureID, X_);
}
void RetrieveParameterFromSBA_mem(double *dCameraParameter, vector<Camera> vCamera, vector<CvMat *> &cP, CvMat *X, vector<int> visibleStructureID, vector<int> vUsedFrame, int max_nFrames)
{
int nFrames = cP.size();
for (int i = 0; i < cP.size(); i++)
cvReleaseMat(&(cP[i]));
cP.clear();
for (int iFrame = 0; iFrame < nFrames; iFrame++)
{
int frame = vUsedFrame[iFrame]%max_nFrames;
int cam = (int) vUsedFrame[iFrame]/max_nFrames;
CvMat *q = cvCreateMat(4,1,CV_32FC1);
CvMat *C = cvCreateMat(3,1,CV_32FC1);
cvSetReal2D(q, 0, 0, dCameraParameter[7*iFrame]);
cvSetReal2D(q, 1, 0, dCameraParameter[7*iFrame+1]);
cvSetReal2D(q, 2, 0, dCameraParameter[7*iFrame+2]);
cvSetReal2D(q, 3, 0, dCameraParameter[7*iFrame+3]);
cvSetReal2D(C, 0, 0, dCameraParameter[7*iFrame+4]);
cvSetReal2D(C, 1, 0, dCameraParameter[7*iFrame+5]);
cvSetReal2D(C, 2, 0, dCameraParameter[7*iFrame+6]);
CvMat *R = cvCreateMat(3,3,CV_32FC1);
CvMat *P = cvCreateMat(3,4,CV_32FC1);
Quaternion2Rotation(q, R);
CreateCameraMatrix(R, C, vCamera[cam].vK[frame], P);
cP.push_back(P);
cvReleaseMat(&q);
cvReleaseMat(&C);
cvReleaseMat(&R);
}
CvMat *X_ = cvCreateMat(visibleStructureID.size(), 3, CV_32FC1);
for (int iFeature = 0; iFeature < visibleStructureID.size(); iFeature++)
{
cvSetReal2D(X_, iFeature, 0, dCameraParameter[7*cP.size()+3*iFeature]);
cvSetReal2D(X_, iFeature, 1, dCameraParameter[7*cP.size()+3*iFeature+1]);
cvSetReal2D(X_, iFeature, 2, dCameraParameter[7*cP.size()+3*iFeature+2]);
}
SetIndexedMatRowwise(X, visibleStructureID, X_);
cvReleaseMat(&X_);
}
void RetrieveParameterFromSBA(double *dCameraParameter, vector<Camera> vCamera, vector<CvMat *> &cP, CvMat *X, vector<int> visibleStructureID, vector<int> vUsedFrame, int max_nFrames)
{
int nFrames = cP.size();
cP.clear();
for (int iFrame = 0; iFrame < nFrames; iFrame++)
{
int frame = vUsedFrame[iFrame]%max_nFrames;
int cam = (int) vUsedFrame[iFrame]/max_nFrames;
CvMat *q = cvCreateMat(4,1,CV_32FC1);
CvMat *C = cvCreateMat(3,1,CV_32FC1);
cvSetReal2D(q, 0, 0, dCameraParameter[7*iFrame]);
cvSetReal2D(q, 1, 0, dCameraParameter[7*iFrame+1]);
cvSetReal2D(q, 2, 0, dCameraParameter[7*iFrame+2]);
cvSetReal2D(q, 3, 0, dCameraParameter[7*iFrame+3]);
cvSetReal2D(C, 0, 0, dCameraParameter[7*iFrame+4]);
cvSetReal2D(C, 1, 0, dCameraParameter[7*iFrame+5]);
cvSetReal2D(C, 2, 0, dCameraParameter[7*iFrame+6]);
CvMat *R = cvCreateMat(3,3,CV_32FC1);
CvMat *P = cvCreateMat(3,4,CV_32FC1);
Quaternion2Rotation(q, R);
CreateCameraMatrix(R, C, vCamera[cam].K, P);
cP.push_back(P);
cvReleaseMat(&q);
cvReleaseMat(&C);
cvReleaseMat(&R);
}
CvMat *X_ = cvCreateMat(visibleStructureID.size(), 3, CV_32FC1);
for (int iFeature = 0; iFeature < visibleStructureID.size(); iFeature++)
{
cvSetReal2D(X_, iFeature, 0, dCameraParameter[7*cP.size()+3*iFeature]);
cvSetReal2D(X_, iFeature, 1, dCameraParameter[7*cP.size()+3*iFeature+1]);
cvSetReal2D(X_, iFeature, 2, dCameraParameter[7*cP.size()+3*iFeature+2]);
}
SetIndexedMatRowwise(X, visibleStructureID, X_);
cvReleaseMat(&X_);
}
void RetrieveParameterFromSBA_KRT(double *dCameraParameter, vector<Camera> vCamera, vector<CvMat *> &cP, CvMat *X, vector<int> visibleStructureID, vector<int> vUsedFrame, int max_nFrames)
{
int nFrames = cP.size();
cP.clear();
CvMat *P;
for (int iFrame = 0; iFrame < nFrames; iFrame++)
{
int frame = vUsedFrame[iFrame]%max_nFrames;
int cam = (int) vUsedFrame[iFrame]/max_nFrames;
CvMat *q = cvCreateMat(4,1,CV_32FC1);
CvMat *C = cvCreateMat(3,1,CV_32FC1);
cvSetReal2D(q, 0, 0, dCameraParameter[11*iFrame]);
cvSetReal2D(q, 1, 0, dCameraParameter[11*iFrame+1]);
cvSetReal2D(q, 2, 0, dCameraParameter[11*iFrame+2]);
cvSetReal2D(q, 3, 0, dCameraParameter[11*iFrame+3]);
cvSetReal2D(C, 0, 0, dCameraParameter[11*iFrame+4]);
cvSetReal2D(C, 1, 0, dCameraParameter[11*iFrame+5]);
cvSetReal2D(C, 2, 0, dCameraParameter[11*iFrame+6]);
vector<int>::const_iterator it = find(vCamera[cam].vTakenFrame.begin(), vCamera[cam].vTakenFrame.end(), frame);
if (it == vCamera[cam].vTakenFrame.end())
return;
int iTakenFrame = (int) (it - vCamera[cam].vTakenFrame.begin());
cvSetReal2D(vCamera[cam].vK[iTakenFrame], 0, 0, dCameraParameter[11*iFrame+7]);
cvSetReal2D(vCamera[cam].vK[iTakenFrame], 1, 1, dCameraParameter[11*iFrame+8]);
cvSetReal2D(vCamera[cam].vK[iTakenFrame], 0, 2, dCameraParameter[11*iFrame+9]);
cvSetReal2D(vCamera[cam].vK[iTakenFrame], 1, 2, dCameraParameter[11*iFrame+10]);
CvMat *R = cvCreateMat(3,3,CV_32FC1);
CvMat *P_ = cvCreateMat(3,4,CV_32FC1);
P = cvCreateMat(3,4,CV_32FC1);
Quaternion2Rotation(q, R);
CreateCameraMatrix(R, C, vCamera[cam].vK[iTakenFrame], P_);
P = cvCloneMat(P_);
cP.push_back(P);
cvReleaseMat(&q);
cvReleaseMat(&C);
cvReleaseMat(&R);
cvReleaseMat(&P_);
}
P = cvCreateMat(3,4,CV_32FC1);
cvReleaseMat(&P);
CvMat *X_ = cvCreateMat(visibleStructureID.size(), 3, CV_32FC1);
for (int iFeature = 0; iFeature < visibleStructureID.size(); iFeature++)
{
cvSetReal2D(X_, iFeature, 0, dCameraParameter[11*cP.size()+3*iFeature]);
cvSetReal2D(X_, iFeature, 1, dCameraParameter[11*cP.size()+3*iFeature+1]);
cvSetReal2D(X_, iFeature, 2, dCameraParameter[11*cP.size()+3*iFeature+2]);
}
SetIndexedMatRowwise(X, visibleStructureID, X_);
cvReleaseMat(&X_);
}
void RetrieveParameterFromSBA_TEMPORAL(double *dCameraParameter, vector<Camera> &vCamera, vector<Theta> &vTheta)
{
int cFrame = 0;
for (int iCamera = 0; iCamera < vCamera.size(); iCamera++)
{
for (int iFrame = 0; iFrame < vCamera[iCamera].vTakenFrame.size(); iFrame++)
{
vCamera[iCamera].vTakenInstant.push_back(vCamera[iCamera].vTakenFrame[iFrame]+dCameraParameter[cFrame]);
cout << vCamera[iCamera].vTakenFrame[iFrame]+dCameraParameter[cFrame] << " ";
cFrame++;
}
}
for (int iTheta = 0; iTheta < vTheta.size(); iTheta++)
{
Theta theta;
theta = vTheta[iTheta];
theta.thetaX.clear();
theta.thetaY.clear();
theta.thetaZ.clear();
for (int i = 0; i < vTheta[0].thetaX.size(); i++)
{
theta.thetaX.push_back(dCameraParameter[cFrame]);
cFrame++;
}
for (int i = 0; i < vTheta[0].thetaX.size(); i++)
{
theta.thetaY.push_back(dCameraParameter[cFrame]);
cFrame++;
}
for (int i = 0; i < vTheta[0].thetaX.size(); i++)
{
theta.thetaZ.push_back(dCameraParameter[cFrame]);
cFrame++;
}
vTheta[iTheta] = theta;
}
}
void RetrieveParameterFromSBA_KDRT(double *dCameraParameter, vector<Camera> vCamera, vector<CvMat *> &cP, CvMat *X, vector<int> visibleStructureID, vector<int> vUsedFrame, int max_nFrames)
{
int nFrames = cP.size();
cP.clear();
CvMat *P;
for (int iFrame = 0; iFrame < nFrames; iFrame++)
{
int frame = vUsedFrame[iFrame]%max_nFrames;
int cam = (int) vUsedFrame[iFrame]/max_nFrames;
CvMat *q = cvCreateMat(4,1,CV_32FC1);
CvMat *C = cvCreateMat(3,1,CV_32FC1);
cvSetReal2D(q, 0, 0, dCameraParameter[13*iFrame]);
cvSetReal2D(q, 1, 0, dCameraParameter[13*iFrame+1]);
cvSetReal2D(q, 2, 0, dCameraParameter[13*iFrame+2]);
cvSetReal2D(q, 3, 0, dCameraParameter[13*iFrame+3]);
cvSetReal2D(C, 0, 0, dCameraParameter[13*iFrame+4]);
cvSetReal2D(C, 1, 0, dCameraParameter[13*iFrame+5]);
cvSetReal2D(C, 2, 0, dCameraParameter[13*iFrame+6]);
vector<int>::const_iterator it = find(vCamera[cam].vTakenFrame.begin(), vCamera[cam].vTakenFrame.end(), frame);
if (it == vCamera[cam].vTakenFrame.end())
return;
int iTakenFrame = (int) (it - vCamera[cam].vTakenFrame.begin());
cvSetReal2D(vCamera[cam].vK[iTakenFrame], 0, 0, dCameraParameter[13*iFrame+7]);
cvSetReal2D(vCamera[cam].vK[iTakenFrame], 1, 1, dCameraParameter[13*iFrame+8]);
cvSetReal2D(vCamera[cam].vK[iTakenFrame], 0, 2, dCameraParameter[13*iFrame+9]);
cvSetReal2D(vCamera[cam].vK[iTakenFrame], 1, 2, dCameraParameter[13*iFrame+10]);
vCamera[cam].vk1[iTakenFrame] = dCameraParameter[13*iFrame+11];
vCamera[cam].vk2[iTakenFrame] = dCameraParameter[13*iFrame+12];
CvMat *R = cvCreateMat(3,3,CV_32FC1);
CvMat *P_ = cvCreateMat(3,4,CV_32FC1);
P = cvCreateMat(3,4,CV_32FC1);
Quaternion2Rotation(q, R);
CreateCameraMatrix(R, C, vCamera[cam].vK[iTakenFrame], P_);
P = cvCloneMat(P_);
cP.push_back(P);
cvReleaseMat(&q);
cvReleaseMat(&C);
cvReleaseMat(&R);
cvReleaseMat(&P_);
}
P = cvCreateMat(3,4,CV_32FC1);
cvReleaseMat(&P);
CvMat *X_ = cvCreateMat(visibleStructureID.size(), 3, CV_32FC1);
for (int iFeature = 0; iFeature < visibleStructureID.size(); iFeature++)
{
cvSetReal2D(X_, iFeature, 0, dCameraParameter[13*cP.size()+3*iFeature]);
cvSetReal2D(X_, iFeature, 1, dCameraParameter[13*cP.size()+3*iFeature+1]);
cvSetReal2D(X_, iFeature, 2, dCameraParameter[13*cP.size()+3*iFeature+2]);
}
SetIndexedMatRowwise(X, visibleStructureID, X_);
cvReleaseMat(&X_);
}
void RetrieveParameterFromGBA(double *dCameraParameter, CvMat *K, vector<Camera> &vCamera, vector<Theta> &vTheta, int nFrames)
{
CvMat *P;
for (int cFrame = 0; cFrame < nFrames*vCamera.size(); cFrame++)
{
int iFrame = cFrame % nFrames;
int iCamera = (int) cFrame / nFrames;
vector<int>::const_iterator it = find(vCamera[iCamera].vTakenFrame.begin(), vCamera[iCamera].vTakenFrame.end(), iFrame);
if (it == vCamera[iCamera].vTakenFrame.end())
continue;
CvMat *q = cvCreateMat(4,1,CV_32FC1);
CvMat *C = cvCreateMat(3,1,CV_32FC1);
cvSetReal2D(q, 0, 0, dCameraParameter[7*cFrame]);
cvSetReal2D(q, 1, 0, dCameraParameter[7*cFrame+1]);
cvSetReal2D(q, 2, 0, dCameraParameter[7*cFrame+2]);
cvSetReal2D(q, 3, 0, dCameraParameter[7*cFrame+3]);
cvSetReal2D(C, 0, 0, dCameraParameter[7*cFrame+4]);
cvSetReal2D(C, 1, 0, dCameraParameter[7*cFrame+5]);
cvSetReal2D(C, 2, 0, dCameraParameter[7*cFrame+6]);
CvMat *R = cvCreateMat(3,3,CV_32FC1);
CvMat *P_ = cvCreateMat(3,4,CV_32FC1);
P = cvCreateMat(3,4,CV_32FC1);
Quaternion2Rotation(q, R);
CreateCameraMatrix(R, C, K, P_);
P = cvCloneMat(P_);
int idx = (int) (it - vCamera[iCamera].vTakenFrame.begin());
vCamera[iCamera].vP[idx] = P;
cvReleaseMat(&q);
cvReleaseMat(&C);
cvReleaseMat(&R);
cvReleaseMat(&P_);
}
P = cvCreateMat(3,4,CV_32FC1);
cvReleaseMat(&P);
CvMat *A = cvCreateMat(nFrames, nFrames, CV_32FC1);
GetDCTMappingMatrix(A, nFrames);
CvMat *A1 = cvCreateMat(1, nFrames, CV_32FC1);
GetSubMatRowwise(A, 0, 0, A1);
for (int iTheta = 0; iTheta < vTheta.size(); iTheta++)
{
int nBase = vTheta[iTheta].thetaX.size();
if (vTheta[iTheta].isStatic)
{
CvMat *X = cvCreateMat(nFrames, 1, CV_32FC1);
CvMat *theta1 = cvCreateMat(1,1,CV_32FC1);
for (int iX = 0; iX < nFrames; iX++)
{
cvSetReal2D(X, iX, 0, dCameraParameter[7*nFrames*vCamera.size()+3*(1+nBase)*iTheta]);
}
cvMatMul(A1, X, theta1);
vTheta[iTheta].thetaX[0] = cvGetReal2D(theta1, 0, 0);
for (int iBase = 1; iBase < nBase; iBase++)
vTheta[iTheta].thetaX[iBase] = 0;
for (int iX = 0; iX < nFrames; iX++)
{
cvSetReal2D(X, iX, 0, dCameraParameter[7*nFrames*vCamera.size()+3*(1+nBase)*iTheta+1]);
}
cvMatMul(A1, X, theta1);
vTheta[iTheta].thetaY[0] = cvGetReal2D(theta1, 0, 0);
for (int iBase = 1; iBase < nBase; iBase++)
vTheta[iTheta].thetaY[iBase] = 0;
for (int iX = 0; iX < nFrames; iX++)
{
cvSetReal2D(X, iX, 0, dCameraParameter[7*nFrames*vCamera.size()+3*(1+nBase)*iTheta+2]);
}
cvMatMul(A1, X, theta1);
vTheta[iTheta].thetaZ[0] = cvGetReal2D(theta1, 0, 0);
for (int iBase = 1; iBase < nBase; iBase++)
vTheta[iTheta].thetaZ[iBase] = 0;
}
else
{
for (int iBase = 0; iBase < nBase; iBase++)
vTheta[iTheta].thetaX[iBase] = dCameraParameter[7*nFrames*vCamera.size()+3*(1+nBase)*iTheta+3+iBase];
for (int iBase = 0; iBase < nBase; iBase++)
vTheta[iTheta].thetaY[iBase] = dCameraParameter[7*nFrames*vCamera.size()+3*(1+nBase)*iTheta+3+nBase+iBase];
for (int iBase = 0; iBase < nBase; iBase++)
vTheta[iTheta].thetaZ[iBase] = dCameraParameter[7*nFrames*vCamera.size()+3*(1+nBase)*iTheta+3+2*nBase+iBase];
}
}
}
void Projection3Donto2D_MOTSTR(int j, int i, double *rt, double *xyz, double *xij, void *adata)
{
CvMat *K = cvCreateMat(3,3,CV_32FC1);
cvSetIdentity(K);
int max_nFrames = ((AdditionalData *) adata)->max_nFrames;
vector<int> vUsedFrame = ((AdditionalData *) adata)->vUsedFrame;
int iCamera = (int)((double)vUsedFrame[j]/max_nFrames);
//double *intrinsic = (((AdditionalData *) adata)->vIntrinsic)[iCamera];
cvSetReal2D(K, 0, 0, ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[0]);
cvSetReal2D(K, 1, 1, ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[1]);
cvSetReal2D(K, 0, 2, ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[2]);
cvSetReal2D(K, 1, 2, ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[3]);
CvMat *q = cvCreateMat(4,1,CV_32FC1);
CvMat *C = cvCreateMat(3,1,CV_32FC1);
CvMat *R = cvCreateMat(3,3,CV_32FC1);
cvSetReal2D(q, 0, 0, rt[0]);
cvSetReal2D(q, 1, 0, rt[1]);
cvSetReal2D(q, 2, 0, rt[2]);
cvSetReal2D(q, 3, 0, rt[3]);
cvSetReal2D(C, 0, 0, rt[4]);
cvSetReal2D(C, 1, 0, rt[5]);
cvSetReal2D(C, 2, 0, rt[6]);
Quaternion2Rotation(q, R);
CvMat *temp33 = cvCreateMat(3,3,CV_32FC1);
CvMat *P = cvCreateMat(3,4,CV_32FC1);
cvMatMul(K, R, temp33);
cvSetIdentity(P);
ScalarMul(C, -1, C);
SetSubMat(P, 0,3,C);
cvMatMul(temp33, P, P);
CvMat *X = cvCreateMat(4,1,CV_32FC1);
cvSetReal2D(X, 0, 0, xyz[0]);
cvSetReal2D(X, 1, 0, xyz[1]);
cvSetReal2D(X, 2, 0, xyz[2]);
cvSetReal2D(X, 3, 0, 1);
CvMat *x = cvCreateMat(3,1,CV_32FC1);
cvMatMul(P, X, x);
if (j == 1)
int k = 1;
xij[0] = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0);
xij[1] = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0);
cvReleaseMat(&K);
cvReleaseMat(&X);
cvReleaseMat(&x);
cvReleaseMat(&P);
cvReleaseMat(&temp33);
cvReleaseMat(&q);
cvReleaseMat(&C);
cvReleaseMat(&R);
}
void Projection3Donto2D_MOTSTR_fast(int j, int i, double *rt, double *xyz, double *xij, void *adata)
{
int max_nFrames = ((AdditionalData *) adata)->max_nFrames;
vector<int> vUsedFrame = ((AdditionalData *) adata)->vUsedFrame;
int iCamera = (int)((double)vUsedFrame[j]/max_nFrames);
int iFrame = vUsedFrame[j] % max_nFrames;
if (j == 1)
int k = 1;
// Set intrinsic parameter
double K11 = ((((AdditionalData *) adata)->vIntrinsic)[iFrame])[0];
double K12 = 0;
double K13 = ((((AdditionalData *) adata)->vIntrinsic)[iFrame])[2];
double K21 = 0;
double K22 = ((((AdditionalData *) adata)->vIntrinsic)[iFrame])[1];
double K23 = ((((AdditionalData *) adata)->vIntrinsic)[iFrame])[3];
double K31 = 0;
double K32 = 0;
double K33 = 1;
// Set orientation
double qw = rt[0];
double qx = rt[1];
double qy = rt[2];
double qz = rt[3];
double q_norm = sqrt(qw*qw + qx*qx + qy*qy + qz*qz);
qw /= q_norm;
qx /= q_norm;
qy /= q_norm;
qz /= q_norm;
double R11 = 1.0-2*qy*qy-2*qz*qz; double R12 = 2*qx*qy-2*qz*qw; double R13 = 2*qx*qz+2*qy*qw;
double R21 = 2*qx*qy+2*qz*qw; double R22 = 1.0-2*qx*qx-2*qz*qz; double R23 = 2*qz*qy-2*qx*qw;
double R31 = 2*qx*qz-2*qy*qw; double R32 = 2*qy*qz+2*qx*qw; double R33 = 1.0-2*qx*qx-2*qy*qy;
//cout << R11 << " " << R12 << " " << R13 << endl;
//cout << R21 << " " << R22 << " " << R23 << endl;
//cout << R31 << " " << R32 << " " << R33 << endl;
// Set translation
double C1 = rt[4];
double C2 = rt[5];
double C3 = rt[6];
double X1 = xyz[0];
double X2 = xyz[1];
double X3 = xyz[2];
// Building projection
double RX1 = R11*X1+R12*X2+R13*X3;
double RX2 = R21*X1+R22*X2+R23*X3;
double RX3 = R31*X1+R32*X2+R33*X3;
double KRX1 = K11*RX1+K12*RX2+K13*RX3;
double KRX2 = K21*RX1+K22*RX2+K23*RX3;
double KRX3 = K31*RX1+K32*RX2+K33*RX3;
double RC1 = R11*C1+R12*C2+R13*C3;
double RC2 = R21*C1+R22*C2+R23*C3;
double RC3 = R31*C1+R32*C2+R33*C3;
double KRC1 = K11*RC1+K12*RC2+K13*RC3;
double KRC2 = K21*RC1+K22*RC2+K23*RC3;
double KRC3 = K31*RC1+K32*RC2+K33*RC3;
double proj1 = KRX1-KRC1;
double proj2 = KRX2-KRC2;
double proj3 = KRX3-KRC3;
xij[0] = proj1/proj3;
xij[1] = proj2/proj3;
}
void Projection3Donto2D_MOTSTR_fast_Distortion(int j, int i, double *rt, double *xyz, double *xij, void *adata)
{
int max_nFrames = ((AdditionalData *) adata)->max_nFrames;
vector<int> vUsedFrame = ((AdditionalData *) adata)->vUsedFrame;
int iCamera = (int)((double)vUsedFrame[j]/max_nFrames);
double omega = ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[4];
double tan_omega_half_2 = ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[5];
if (j == 1)
int k = 1;
if (j == 2)
int k = 1;
// Set intrinsic parameter
double K11 = ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[0];
double K12 = 0;
double K13 = ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[2];
double K21 = 0;
double K22 = ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[1];
double K23 = ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[3];
double K31 = 0;
double K32 = 0;
double K33 = 1;
// Set orientation
double qw = rt[0];
double qx = rt[1];
double qy = rt[2];
double qz = rt[3];
double q_norm = sqrt(qw*qw + qx*qx + qy*qy + qz*qz);
qw /= q_norm;
qx /= q_norm;
qy /= q_norm;
qz /= q_norm;
double R11 = 1.0-2*qy*qy-2*qz*qz; double R12 = 2*qx*qy-2*qz*qw; double R13 = 2*qx*qz+2*qy*qw;
double R21 = 2*qx*qy+2*qz*qw; double R22 = 1.0-2*qx*qx-2*qz*qz; double R23 = 2*qz*qy-2*qx*qw;
double R31 = 2*qx*qz-2*qy*qw; double R32 = 2*qy*qz+2*qx*qw; double R33 = 1.0-2*qx*qx-2*qy*qy;
//cout << R11 << " " << R12 << " " << R13 << endl;
//cout << R21 << " " << R22 << " " << R23 << endl;
//cout << R31 << " " << R32 << " " << R33 << endl;
// Set translation
double C1 = rt[4];
double C2 = rt[5];
double C3 = rt[6];
double X1 = xyz[0];
double X2 = xyz[1];
double X3 = xyz[2];
// Building projection
double RX1 = R11*X1+R12*X2+R13*X3;
double RX2 = R21*X1+R22*X2+R23*X3;
double RX3 = R31*X1+R32*X2+R33*X3;
double KRX1 = K11*RX1+K12*RX2+K13*RX3;
double KRX2 = K21*RX1+K22*RX2+K23*RX3;
double KRX3 = K31*RX1+K32*RX2+K33*RX3;
double RC1 = R11*C1+R12*C2+R13*C3;
double RC2 = R21*C1+R22*C2+R23*C3;
double RC3 = R31*C1+R32*C2+R33*C3;
double KRC1 = K11*RC1+K12*RC2+K13*RC3;
double KRC2 = K21*RC1+K22*RC2+K23*RC3;
double KRC3 = K31*RC1+K32*RC2+K33*RC3;
double proj1 = KRX1-KRC1;
double proj2 = KRX2-KRC2;
double proj3 = KRX3-KRC3;
double u = proj1/proj3;
double v = proj2/proj3;
double u_n = u/K11 - K13/K11;
double v_n = v/K22 - K23/K22;
double r_u = sqrt(u_n*u_n+v_n*v_n);
double r_d = 1/omega*atan(r_u*tan_omega_half_2);
double u_d_n = r_d/r_u * u_n;
double v_d_n = r_d/r_u * v_n;
double u_d = u_d_n*K11 + K13;
double v_d = v_d_n*K22 + K23;
xij[0] = u_d;
xij[1] = v_d;
}
void Projection3Donto2D_MOTSTR_fast_Distortion_ObstacleDetection(int j, int i, double *rt, double *xyz, double *xij, void *adata)
{
int max_nFrames = ((AdditionalData *) adata)->max_nFrames;
vector<int> vUsedFrame = ((AdditionalData *) adata)->vUsedFrame;
int iCamera = (int)((double)vUsedFrame[j]/max_nFrames);
double omega = ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[4];
double tan_omega_half_2 = ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[5];
double princ_x1 = ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[6];
double princ_y1 = ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[7];
// Set intrinsic parameter
double K11 = ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[0];
double K12 = 0;
double K13 = ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[2];
double K21 = 0;
double K22 = ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[1];
double K23 = ((((AdditionalData *) adata)->vIntrinsic)[iCamera])[3];
double K31 = 0;
double K32 = 0;
double K33 = 1;
// Set orientation
double qw = rt[0];
double qx = rt[1];
double qy = rt[2];
double qz = rt[3];
double q_norm = sqrt(qw*qw + qx*qx + qy*qy + qz*qz);
qw /= q_norm;
qx /= q_norm;
qy /= q_norm;
qz /= q_norm;
double R11 = 1.0-2*qy*qy-2*qz*qz; double R12 = 2*qx*qy-2*qz*qw; double R13 = 2*qx*qz+2*qy*qw;
double R21 = 2*qx*qy+2*qz*qw; double R22 = 1.0-2*qx*qx-2*qz*qz; double R23 = 2*qz*qy-2*qx*qw;
double R31 = 2*qx*qz-2*qy*qw; double R32 = 2*qy*qz+2*qx*qw; double R33 = 1.0-2*qx*qx-2*qy*qy;
//cout << R11 << " " << R12 << " " << R13 << endl;
//cout << R21 << " " << R22 << " " << R23 << endl;
//cout << R31 << " " << R32 << " " << R33 << endl;
// Set translation
double C1 = rt[4];
double C2 = rt[5];
double C3 = rt[6];
double X1 = xyz[0];
double X2 = xyz[1];
double X3 = xyz[2];
// Building projection
double RX1 = R11*X1+R12*X2+R13*X3;
double RX2 = R21*X1+R22*X2+R23*X3;
double RX3 = R31*X1+R32*X2+R33*X3;
double KRX1 = K11*RX1+K12*RX2+K13*RX3;
double KRX2 = K21*RX1+K22*RX2+K23*RX3;
double KRX3 = K31*RX1+K32*RX2+K33*RX3;
double RC1 = R11*C1+R12*C2+R13*C3;
double RC2 = R21*C1+R22*C2+R23*C3;
double RC3 = R31*C1+R32*C2+R33*C3;
double KRC1 = K11*RC1+K12*RC2+K13*RC3;
double KRC2 = K21*RC1+K22*RC2+K23*RC3;
double KRC3 = K31*RC1+K32*RC2+K33*RC3;
double proj1 = KRX1-KRC1;
double proj2 = KRX2-KRC2;
double proj3 = KRX3-KRC3;
double u = proj1/proj3;
double v = proj2/proj3;
//double u_n = u/K11 - K13/K11;
//double v_n = v/K22 - K23/K22;
double u_n = u - princ_x1;
double v_n = v - princ_y1;
double r_u = sqrt(u_n*u_n+v_n*v_n);
double r_d = 1/omega*atan(r_u*tan_omega_half_2);
double u_d_n = r_d/r_u * u_n;
double v_d_n = r_d/r_u * v_n;
double u_d = u_d_n + princ_x1;
double v_d = v_d_n + princ_y1;
xij[0] = u_d;
xij[1] = v_d;
}
void Projection3Donto2D_KMOTSTR(int j, int i, double *rt, double *xyz, double *xij, void *adata)
{
CvMat *K = cvCreateMat(3,3,CV_32FC1);
cvSetIdentity(K);
//int max_nFrames = ((AdditionalData *) adata)->max_nFrames;
//vector<int> vUsedFrame = ((AdditionalData *) adata)->vUsedFrame;
//int iCamera = (int)((double)vUsedFrame[j]/max_nFrames);
//double *intrinsic = (((AdditionalData *) adata)->vIntrinsic)[iCamera];
//cvSetReal2D(K, 0, 0, intrinsic[0]);
//cvSetReal2D(K, 1, 1, intrinsic[1]);
//cvSetReal2D(K, 0, 2, intrinsic[2]);
//cvSetReal2D(K, 1, 2, intrinsic[3]);
CvMat *q = cvCreateMat(4,1,CV_32FC1);
CvMat *C = cvCreateMat(3,1,CV_32FC1);
CvMat *R = cvCreateMat(3,3,CV_32FC1);
cvSetReal2D(q, 0, 0, rt[0]);
cvSetReal2D(q, 1, 0, rt[1]);
cvSetReal2D(q, 2, 0, rt[2]);
cvSetReal2D(q, 3, 0, rt[3]);
cvSetReal2D(C, 0, 0, rt[4]);
cvSetReal2D(C, 1, 0, rt[5]);
cvSetReal2D(C, 2, 0, rt[6]);
cvSetReal2D(K, 0, 0, rt[7]);
cvSetReal2D(K, 1, 1, rt[8]);
cvSetReal2D(K, 0, 2, rt[9]);
cvSetReal2D(K, 1, 2, rt[10]);
Quaternion2Rotation(q, R);
CvMat *temp33 = cvCreateMat(3,3,CV_32FC1);
CvMat *P = cvCreateMat(3,4,CV_32FC1);
cvMatMul(K, R, temp33);
cvSetIdentity(P);
ScalarMul(C, -1, C);
SetSubMat(P, 0,3,C);
cvMatMul(temp33, P, P);
CvMat *X = cvCreateMat(4,1,CV_32FC1);
cvSetReal2D(X, 0, 0, xyz[0]);
cvSetReal2D(X, 1, 0, xyz[1]);
cvSetReal2D(X, 2, 0, xyz[2]);
cvSetReal2D(X, 3, 0, 1);
CvMat *x = cvCreateMat(3,1,CV_32FC1);
cvMatMul(P, X, x);
xij[0] = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0);
xij[1] = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0);
cvReleaseMat(&K);
cvReleaseMat(&X);
cvReleaseMat(&x);
cvReleaseMat(&P);
cvReleaseMat(&temp33);
cvReleaseMat(&q);
cvReleaseMat(&C);
cvReleaseMat(&R);
}
void ProjectionThetaonto2D_TEMPORAL(int j, int i, double *rt, double *xyz, double *xij, void *adata)
{
int max_nFrames = ((AdditionalData *) adata)->max_nFrames;
vector<int> vUsedFrame = ((AdditionalData *) adata)->vUsedFrame;
int iCamera = (int)((double)vUsedFrame[j]/max_nFrames);
int cFrame = vUsedFrame[j] % max_nFrames;
int nBase = ((AdditionalData*) adata)->nBase;
vector<Theta> vTheta = ((AdditionalData *) adata)->vTheta;
CvMat *P = cvCreateMat(3,4, CV_32FC1);
for (int iP = 0; iP < 3; iP++)
for (int jP = 0; jP < 4; jP++)
cvSetReal2D(P, iP, jP, ((AdditionalData *) adata)->vdP[12*j+iP*4+jP]);
double dt = rt[0];
double t = cFrame + dt;
CvMat *B = cvCreateMat(1, nBase, CV_32FC1);
cvSetReal2D(B, 0, 0, sqrt(1.0/(double)max_nFrames));
for (int iB = 1; iB < nBase; iB++)
cvSetReal2D(B, 0, iB, sqrt(2.0/(double)max_nFrames)*cos((2*t-1)*(iB)*PI/2.0/(double)max_nFrames));
//PrintMat(B);
CvMat *thetaX = cvCreateMat(nBase,1, CV_32FC1);
CvMat *thetaY = cvCreateMat(nBase,1, CV_32FC1);
CvMat *thetaZ = cvCreateMat(nBase,1, CV_32FC1);
for (int iTheta = 0; iTheta < nBase; iTheta++)
cvSetReal2D(thetaX, iTheta, 0, xyz[iTheta]);
for (int iTheta = 0; iTheta < nBase; iTheta++)
cvSetReal2D(thetaY, iTheta, 0, xyz[nBase+iTheta]);
for (int iTheta = 0; iTheta < nBase; iTheta++)
cvSetReal2D(thetaZ, iTheta, 0, xyz[2*nBase+iTheta]);
//PrintMat(thetaX);
//PrintMat(thetaY);
//PrintMat(thetaZ);
//for (int iTheta = 0; iTheta < nBase; iTheta++)
// cout << xyz[iTheta] << " ";
//cout << endl;
CvMat *X3 = cvCreateMat(1,1,CV_32FC1);
CvMat *Y3 = cvCreateMat(1,1,CV_32FC1);
CvMat *Z3 = cvCreateMat(1,1,CV_32FC1);
cvMatMul(B, thetaX, X3);
cvMatMul(B, thetaY, Y3);
cvMatMul(B, thetaZ, Z3);
CvMat *X = cvCreateMat(4,1,CV_32FC1);
cvSetReal2D(X, 0, 0, cvGetReal2D(X3,0,0));
cvSetReal2D(X, 1, 0, cvGetReal2D(Y3,0,0));
cvSetReal2D(X, 2, 0, cvGetReal2D(Z3,0,0));
cvSetReal2D(X, 3, 0, 1);
CvMat *x = cvCreateMat(3,1,CV_32FC1);
cvMatMul(P, X, x);
xij[0] = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0);
xij[1] = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0);
int error = 0;
for (int iBase = 0; iBase < nBase; iBase++)
{
error += (xyz[iBase]-vTheta[i].thetaX[iBase])*(xyz[iBase]-vTheta[i].thetaX[iBase]);
}
for (int iBase = 0; iBase < nBase; iBase++)
{
error += (xyz[nBase+iBase]-vTheta[i].thetaY[iBase])*(xyz[nBase+iBase]-vTheta[i].thetaY[iBase]);
}
for (int iBase = 0; iBase < nBase; iBase++)
{
error += (xyz[2*nBase+iBase]-vTheta[i].thetaZ[iBase])*(xyz[2*nBase+iBase]-vTheta[i].thetaZ[iBase]);
}
xij[2] = 10*error;
xij[3] = 10*rt[0];
cvReleaseMat(&X);
cvReleaseMat(&x);
cvReleaseMat(&P);
cvReleaseMat(&B);
cvReleaseMat(&thetaX);
cvReleaseMat(&thetaY);
cvReleaseMat(&thetaZ);
cvReleaseMat(&X3);
cvReleaseMat(&Y3);
cvReleaseMat(&Z3);
}
void Projection3Donto2D_KDMOTSTR(int j, int i, double *rt, double *xyz, double *xij, void *adata)
{
CvMat *K = cvCreateMat(3,3,CV_32FC1);
cvSetIdentity(K);
int max_nFrames = ((AdditionalData *) adata)->max_nFrames;
vector<int> vUsedFrame = ((AdditionalData *) adata)->vUsedFrame;
int iCamera = (int)((double)vUsedFrame[j]/max_nFrames);
//double *intrinsic = (((AdditionalData *) adata)->vIntrinsic)[iCamera];
//cvSetReal2D(K, 0, 0, intrinsic[0]);
//cvSetReal2D(K, 1, 1, intrinsic[1]);
//cvSetReal2D(K, 0, 2, intrinsic[2]);
//cvSetReal2D(K, 1, 2, intrinsic[3]);
CvMat *q = cvCreateMat(4,1,CV_32FC1);
CvMat *C = cvCreateMat(3,1,CV_32FC1);
CvMat *R = cvCreateMat(3,3,CV_32FC1);
cvSetReal2D(q, 0, 0, rt[0]);
cvSetReal2D(q, 1, 0, rt[1]);
cvSetReal2D(q, 2, 0, rt[2]);
cvSetReal2D(q, 3, 0, rt[3]);
cvSetReal2D(C, 0, 0, rt[4]);
cvSetReal2D(C, 1, 0, rt[5]);
cvSetReal2D(C, 2, 0, rt[6]);
cvSetReal2D(K, 0, 0, rt[7]);
cvSetReal2D(K, 1, 1, rt[8]);
cvSetReal2D(K, 0, 2, rt[9]);
cvSetReal2D(K, 1, 2, rt[10]);
Quaternion2Rotation(q, R);
double k11 = rt[7];
double k22 = rt[8];
double px = rt[9];
double py = rt[10];
double k1 = rt[11];
double k2 = rt[12];
CvMat *temp33 = cvCreateMat(3,3,CV_32FC1);
CvMat *P = cvCreateMat(3,4,CV_32FC1);
cvMatMul(K, R, temp33);
cvSetIdentity(P);
ScalarMul(C, -1, C);
SetSubMat(P, 0,3,C);
cvMatMul(temp33, P, P);
CvMat *X = cvCreateMat(4,1,CV_32FC1);
cvSetReal2D(X, 0, 0, xyz[0]);
cvSetReal2D(X, 1, 0, xyz[1]);
cvSetReal2D(X, 2, 0, xyz[2]);
cvSetReal2D(X, 3, 0, 1);
CvMat *x = cvCreateMat(3,1,CV_32FC1);
cvMatMul(P, X, x);
xij[0] = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0);
xij[1] = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0);
// taking into account distortion
CvMat *invK = cvCreateMat(3,3,CV_32FC1);
cvInvert(K, invK);
double ik11 = cvGetReal2D(invK, 0, 0); double ik12 = cvGetReal2D(invK, 0, 1); double ik13 = cvGetReal2D(invK, 0, 2);
double ik21 = cvGetReal2D(invK, 1, 0); double ik22 = cvGetReal2D(invK, 1, 1); double ik23 = cvGetReal2D(invK, 1, 2);
double ik31 = cvGetReal2D(invK, 2, 0); double ik32 = cvGetReal2D(invK, 2, 1); double ik33 = cvGetReal2D(invK, 2, 2);
double nz = (ik31*xij[0]+ik32*xij[1]+ik33);
double nx = (ik11*xij[0]+ik12*xij[1]+ik13)/nz;
double ny = (ik21*xij[0]+ik22*xij[1]+ik23)/nz;
double r = sqrt((nx)*(nx)+(ny)*(ny));
double L = 1 + k1*r + k2*r*r;
nx = L*(nx);
ny = L*(ny);
xij[0] = (k11*nx+px);
xij[1] = (k22*ny+py);
cvReleaseMat(&K);
cvReleaseMat(&invK);
cvReleaseMat(&X);
cvReleaseMat(&x);
cvReleaseMat(&P);
cvReleaseMat(&temp33);
cvReleaseMat(&q);
cvReleaseMat(&C);
cvReleaseMat(&R);
}
void ProjectionThetaonto2D_MOTSTR(int j, int i, double *rt, double *xyz, double *xij, void *adata)
{
//CvMat *K = cvCreateMat(3,3,CV_32FC1);
//cvSetIdentity(K);
//cvSetReal2D(K, 0, 0, ((AdditionalData *) adata)->intrinsic[0]);
//cvSetReal2D(K, 1, 1, ((AdditionalData *) adata)->intrinsic[1]);
//cvSetReal2D(K, 0, 2, ((AdditionalData *) adata)->intrinsic[2]);
//cvSetReal2D(K, 1, 2, ((AdditionalData *) adata)->intrinsic[3]);
//bool isStatic = ((AdditionalData *) adata)->isStatic[i];
//CvMat *q = cvCreateMat(4,1,CV_32FC1);
//CvMat *C = cvCreateMat(3,1,CV_32FC1);
//CvMat *R = cvCreateMat(3,3,CV_32FC1);
//cvSetReal2D(q, 0, 0, rt[0]);
//cvSetReal2D(q, 1, 0, rt[1]);
//cvSetReal2D(q, 2, 0, rt[2]);
//cvSetReal2D(q, 3, 0, rt[3]);
//cvSetReal2D(C, 0, 0, rt[4]);
//cvSetReal2D(C, 1, 0, rt[5]);
//cvSetReal2D(C, 2, 0, rt[6]);
//Quaternion2Rotation(q, R);
//CvMat *temp33 = cvCreateMat(3,3,CV_32FC1);
//CvMat *P = cvCreateMat(3,4,CV_32FC1);
//cvMatMul(K, R, temp33);
//cvSetIdentity(P);
//ScalarMul(C, -1, C);
//SetSubMat(P, 0,3,C);
//cvMatMul(temp33, P, P);
//if (!isStatic)
//{
// int iFrame = j % ((AdditionalData *) adata)->nFrames;
// int nBase = ((AdditionalData *) adata)->nBase;
// int nFrames = ((AdditionalData *) adata)->nFrames;
// CvMat *x = cvCreateMat(2,1,CV_32FC1);
// CvMat *theta = cvCreateMat(3*nBase, 1, CV_32FC1);
// for (int iTheta = 0; iTheta < 3*nBase; iTheta++)
// cvSetReal2D(theta, iTheta, 0, xyz[iTheta]);
// DCTProjection(P, theta, nFrames, iFrame, nBase, x);
// xij[0] = cvGetReal2D(x, 0, 0);
// xij[1] = cvGetReal2D(x, 1, 0);
// cvReleaseMat(&x);
// cvReleaseMat(&theta);
//}
//else
//{
// CvMat *X = cvCreateMat(4,1,CV_32FC1);
// cvSetReal2D(X, 0, 0, xyz[0]);
// cvSetReal2D(X, 1, 0, xyz[1]);
// cvSetReal2D(X, 2, 0, xyz[2]);
// cvSetReal2D(X, 3, 0, 1);
// CvMat *x = cvCreateMat(3,1,CV_32FC1);
// cvMatMul(P, X, x);
//
// xij[0] = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0);
// xij[1] = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0);
// cvReleaseMat(&X);
// cvReleaseMat(&x);
//}
//cvReleaseMat(&K);
//cvReleaseMat(&P);
//cvReleaseMat(&temp33);
//cvReleaseMat(&q);
//cvReleaseMat(&C);
//cvReleaseMat(&R);
}
void ProjectionThetaonto2D_MOTSTR_LEVMAR(int j, int i, double *rt, double *xyz, double &xi, double &yi, void *adata)
{
//CvMat *K = cvCreateMat(3,3,CV_32FC1);
//cvSetIdentity(K);
//cvSetReal2D(K, 0, 0, ((AdditionalData *) adata)->intrinsic[0]);
//cvSetReal2D(K, 1, 1, ((AdditionalData *) adata)->intrinsic[1]);
//cvSetReal2D(K, 0, 2, ((AdditionalData *) adata)->intrinsic[2]);
//cvSetReal2D(K, 1, 2, ((AdditionalData *) adata)->intrinsic[3]);
//bool isStatic = ((AdditionalData *) adata)->isStatic[i];
//CvMat *q = cvCreateMat(4,1,CV_32FC1);
//CvMat *C = cvCreateMat(3,1,CV_32FC1);
//CvMat *R = cvCreateMat(3,3,CV_32FC1);
//cvSetReal2D(q, 0, 0, rt[0]);
//cvSetReal2D(q, 1, 0, rt[1]);
//cvSetReal2D(q, 2, 0, rt[2]);
//cvSetReal2D(q, 3, 0, rt[3]);
//cvSetReal2D(C, 0, 0, rt[4]);
//cvSetReal2D(C, 1, 0, rt[5]);
//cvSetReal2D(C, 2, 0, rt[6]);
//Quaternion2Rotation(q, R);
//CvMat *temp33 = cvCreateMat(3,3,CV_32FC1);
//CvMat *P = cvCreateMat(3,4,CV_32FC1);
//cvMatMul(K, R, temp33);
//cvSetIdentity(P);
//ScalarMul(C, -1, C);
//SetSubMat(P, 0,3,C);
//cvMatMul(temp33, P, P);
//if (!isStatic)
//{
// int iFrame = j % ((AdditionalData *) adata)->nFrames;
// int nBase = ((AdditionalData *) adata)->nBase;
// int nFrames = ((AdditionalData *) adata)->nFrames;
// CvMat *x = cvCreateMat(2,1,CV_32FC1);
// CvMat *theta = cvCreateMat(3*nBase, 1, CV_32FC1);
// for (int iTheta = 0; iTheta < 3*nBase; iTheta++)
// cvSetReal2D(theta, iTheta, 0, xyz[iTheta]);
// DCTProjection(P, theta, nFrames, iFrame, nBase, x);
// xi = cvGetReal2D(x, 0, 0);
// yi = cvGetReal2D(x, 1, 0);
// cvReleaseMat(&x);
// cvReleaseMat(&theta);
//}
//else
//{
// CvMat *X = cvCreateMat(4,1,CV_32FC1);
// cvSetReal2D(X, 0, 0, xyz[0]);
// cvSetReal2D(X, 1, 0, xyz[1]);
// cvSetReal2D(X, 2, 0, xyz[2]);
// cvSetReal2D(X, 3, 0, 1);
// CvMat *x = cvCreateMat(3,1,CV_32FC1);
// cvMatMul(P, X, x);
// xi = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0);
// yi = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0);
// cvReleaseMat(&X);
// cvReleaseMat(&x);
//}
//cvReleaseMat(&K);
//cvReleaseMat(&P);
//cvReleaseMat(&temp33);
//cvReleaseMat(&q);
//cvReleaseMat(&C);
//cvReleaseMat(&R);
}
void Projection3Donto2D_MOT(int j, int i, double *rt, double *xij, void *adata)
{
//CvMat *K = cvCreateMat(3,3,CV_32FC1);
//cvSetIdentity(K);
//cvSetReal2D(K, 0, 0, ((AdditionalData *) adata)->intrinsic[0]);
//cvSetReal2D(K, 1, 1, ((AdditionalData *) adata)->intrinsic[1]);
//cvSetReal2D(K, 0, 2, ((AdditionalData *) adata)->intrinsic[2]);
//cvSetReal2D(K, 1, 2, ((AdditionalData *) adata)->intrinsic[3]);
//CvMat *q = cvCreateMat(4,1,CV_32FC1);
//CvMat *C = cvCreateMat(3,1,CV_32FC1);
//CvMat *R = cvCreateMat(3,3,CV_32FC1);
//cvSetReal2D(q, 0, 0, rt[0]);
//cvSetReal2D(q, 1, 0, rt[1]);
//cvSetReal2D(q, 2, 0, rt[2]);
//cvSetReal2D(q, 3, 0, rt[3]);
//cvSetReal2D(C, 0, 0, rt[4]);
//cvSetReal2D(C, 1, 0, rt[5]);
//cvSetReal2D(C, 2, 0, rt[6]);
//Quaternion2Rotation(q, R);
//CvMat *temp33 = cvCreateMat(3,3,CV_32FC1);
//CvMat *P = cvCreateMat(3,4,CV_32FC1);
//cvMatMul(K, R, temp33);
//cvSetIdentity(P);
//ScalarMul(C, -1, C);
//SetSubMat(P, 0,3,C);
//cvMatMul(temp33, P, P);
//CvMat *X = cvCreateMat(4,1,CV_32FC1);
//cvSetReal2D(X, 0, 0, ((AdditionalData *) adata)->XYZ[3*i]);
//cvSetReal2D(X, 1, 0, ((AdditionalData *) adata)->XYZ[3*i+1]);
//cvSetReal2D(X, 2, 0, ((AdditionalData *) adata)->XYZ[3*i+2]);
//cvSetReal2D(X, 3, 0, 1);
////PrintMat(X, "X");
////PrintMat(C, "C");
////cout << i << endl;
////if (j == 1)
//// int k = 1;
//CvMat *x = cvCreateMat(3,1,CV_32FC1);
//cvMatMul(P, X, x);
//xij[0] = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0);
//xij[1] = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0);
//cvReleaseMat(&K);
//cvReleaseMat(&X);
//cvReleaseMat(&x);
//cvReleaseMat(&P);
//cvReleaseMat(&temp33);
//cvReleaseMat(&q);
//cvReleaseMat(&C);
}
void Projection3Donto2D_KDMOT(int j, int i, double *rt, double *xij, void *adata)
{
CvMat *K = cvCreateMat(3,3,CV_32FC1);
cvSetIdentity(K);
int max_nFrames = ((AdditionalData *) adata)->max_nFrames;
vector<int> vUsedFrame = ((AdditionalData *) adata)->vUsedFrame;
int iCamera = (int)((double)vUsedFrame[j]/max_nFrames);
CvMat *q = cvCreateMat(4,1,CV_32FC1);
CvMat *C = cvCreateMat(3,1,CV_32FC1);
CvMat *R = cvCreateMat(3,3,CV_32FC1);
cvSetReal2D(q, 0, 0, rt[0]);
cvSetReal2D(q, 1, 0, rt[1]);
cvSetReal2D(q, 2, 0, rt[2]);
cvSetReal2D(q, 3, 0, rt[3]);
cvSetReal2D(C, 0, 0, rt[4]);
cvSetReal2D(C, 1, 0, rt[5]);
cvSetReal2D(C, 2, 0, rt[6]);
cvSetReal2D(K, 0, 0, rt[7]);
cvSetReal2D(K, 1, 1, rt[8]);
cvSetReal2D(K, 0, 2, rt[9]);
cvSetReal2D(K, 1, 2, rt[10]);
Quaternion2Rotation(q, R);
double k11 = rt[7];
double k22 = rt[8];
double px = rt[9];
double py = rt[10];
double k1 = rt[11];
double k2 = rt[12];
CvMat *temp33 = cvCreateMat(3,3,CV_32FC1);
CvMat *P = cvCreateMat(3,4,CV_32FC1);
cvMatMul(K, R, temp33);
cvSetIdentity(P);
ScalarMul(C, -1, C);
SetSubMat(P, 0,3,C);
cvMatMul(temp33, P, P);
CvMat *X = cvCreateMat(4,1,CV_32FC1);
cvSetReal2D(X, 0, 0, ((AdditionalData *) adata)->XYZ[3*i]);
cvSetReal2D(X, 1, 0, ((AdditionalData *) adata)->XYZ[3*i+1]);
cvSetReal2D(X, 2, 0, ((AdditionalData *) adata)->XYZ[3*i+2]);
cvSetReal2D(X, 3, 0, 1);
CvMat *x = cvCreateMat(3,1,CV_32FC1);
cvMatMul(P, X, x);
xij[0] = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0);
xij[1] = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0);
// taking into account distortion
CvMat *invK = cvCreateMat(3,3,CV_32FC1);
cvInvert(K, invK);
double ik11 = cvGetReal2D(invK, 0, 0); double ik12 = cvGetReal2D(invK, 0, 1); double ik13 = cvGetReal2D(invK, 0, 2);
double ik21 = cvGetReal2D(invK, 1, 0); double ik22 = cvGetReal2D(invK, 1, 1); double ik23 = cvGetReal2D(invK, 1, 2);
double ik31 = cvGetReal2D(invK, 2, 0); double ik32 = cvGetReal2D(invK, 2, 1); double ik33 = cvGetReal2D(invK, 2, 2);
double nz = (ik31*xij[0]+ik32*xij[1]+ik33);
double nx = (ik11*xij[0]+ik12*xij[1]+ik13)/nz;
double ny = (ik21*xij[0]+ik22*xij[1]+ik23)/nz;
double r = sqrt((nx)*(nx)+(ny)*(ny));
double L = 1 + k1*r + k2*r*r;
nx = L*(nx);
ny = L*(ny);
xij[0] = (k11*nx+px);
xij[1] = (k22*ny+py);
cvReleaseMat(&K);
cvReleaseMat(&invK);
cvReleaseMat(&X);
cvReleaseMat(&x);
cvReleaseMat(&P);
cvReleaseMat(&temp33);
cvReleaseMat(&q);
cvReleaseMat(&C);
cvReleaseMat(&R);
}
void GetParameterForSBA(vector<Feature> vFeature, vector<int> vUsedFrame, vector<CvMat *> cP, CvMat *X, CvMat *K, vector<int> visibleStructureID,
vector<double> &cameraParameter, vector<double> &feature2DParameter, vector<char> &vMask)
{
int nFrames = cP.size();
int nFeatures = X->rows;
for (int iFrame = 0; iFrame < vUsedFrame.size(); iFrame++)
{
int cFrame = vUsedFrame[iFrame];
CvMat *q = cvCreateMat(4,1,CV_32FC1);
CvMat *R = cvCreateMat(3,3,CV_32FC1);
CvMat *t = cvCreateMat(3,1,CV_32FC1);
CvMat *invK = cvCreateMat(3,3,CV_32FC1);
CvMat *invR = cvCreateMat(3,3,CV_32FC1);
cvInvert(K, invK);
GetSubMatColwise(cP[iFrame], 0, 2, R);
GetSubMatColwise(cP[iFrame], 3, 3, t);
cvMatMul(invK, R, R);
cvInvert(R, invR);
cvMatMul(invK, t, t);
cvMatMul(invR, t, t);
ScalarMul(t, -1, t);
Rotation2Quaternion(R, q);
cameraParameter.push_back(cvGetReal2D(q, 0, 0));
cameraParameter.push_back(cvGetReal2D(q, 1, 0));
cameraParameter.push_back(cvGetReal2D(q, 2, 0));
cameraParameter.push_back(cvGetReal2D(q, 3, 0));
cameraParameter.push_back(cvGetReal2D(t, 0, 0));
cameraParameter.push_back(cvGetReal2D(t, 1, 0));
cameraParameter.push_back(cvGetReal2D(t, 2, 0));
cvReleaseMat(&R);
cvReleaseMat(&t);
cvReleaseMat(&q);
cvReleaseMat(&invK);
cvReleaseMat(&invR);
}
for (int cFeature = 0; cFeature < visibleStructureID.size(); cFeature++)
{
int iFeature = visibleStructureID[cFeature];
cameraParameter.push_back(cvGetReal2D(X, iFeature, 0));
cameraParameter.push_back(cvGetReal2D(X, iFeature, 1));
cameraParameter.push_back(cvGetReal2D(X, iFeature, 2));
}
CvMat *visibilityMask = cvCreateMat(visibleStructureID.size(), nFrames, CV_32FC1);
cvSetZero(visibilityMask);
int NZ = 0;
for (int cFeature = 0; cFeature < visibleStructureID.size(); cFeature++)
{
int iFeature = visibleStructureID[cFeature];
for (int iVisibleFrame = 0; iVisibleFrame < vUsedFrame.size(); iVisibleFrame++)
{
vector<int>::iterator it = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),vUsedFrame[iVisibleFrame]);
if (it != vFeature[iFeature].vFrame.end())
{
int idx = int(it-vFeature[iFeature].vFrame.begin());
feature2DParameter.push_back(vFeature[iFeature].vx[idx]);
feature2DParameter.push_back(vFeature[iFeature].vy[idx]);
cvSetReal2D(visibilityMask, cFeature, iVisibleFrame, 1);
NZ++;
}
}
}
for (int iFeature = 0; iFeature < visibilityMask->rows; iFeature++)
{
for (int iFrame = 0; iFrame < visibilityMask->cols; iFrame++)
{
vMask.push_back(cvGetReal2D(visibilityMask, iFeature, iFrame));
}
}
cvReleaseMat(&visibilityMask);
}
void GetParameterForSBA(vector<Feature> &vFeature, vector<int> vUsedFrame, vector<CvMat *> cP, CvMat *X, vector<Camera> vCamera, int max_nFrames, vector<int> visibleStructureID,
vector<double> &cameraParameter, vector<double> &feature2DParameter, vector<char> &vMask)
{
int nFrames = cP.size();
int nFeatures = X->rows;
for (int iFrame = 0; iFrame < vUsedFrame.size(); iFrame++)
{
int cFrame = vUsedFrame[iFrame];
int iCamera = (int) ((double)vUsedFrame[iFrame]/max_nFrames);
CvMat *q = cvCreateMat(4,1,CV_32FC1);
CvMat *R = cvCreateMat(3,3,CV_32FC1);
CvMat *t = cvCreateMat(3,1,CV_32FC1);
CvMat *invK = cvCreateMat(3,3,CV_32FC1);
CvMat *invR = cvCreateMat(3,3,CV_32FC1);
cvInvert(vCamera[iCamera].vK[cFrame], invK);
GetSubMatColwise(cP[iFrame], 0, 2, R);
GetSubMatColwise(cP[iFrame], 3, 3, t);
cvMatMul(invK, R, R);
cvInvert(R, invR);
cvMatMul(invK, t, t);
cvMatMul(invR, t, t);
ScalarMul(t, -1, t);
Rotation2Quaternion(R, q);
cameraParameter.push_back(cvGetReal2D(q, 0, 0));
cameraParameter.push_back(cvGetReal2D(q, 1, 0));
cameraParameter.push_back(cvGetReal2D(q, 2, 0));
cameraParameter.push_back(cvGetReal2D(q, 3, 0));
cameraParameter.push_back(cvGetReal2D(t, 0, 0));
cameraParameter.push_back(cvGetReal2D(t, 1, 0));
cameraParameter.push_back(cvGetReal2D(t, 2, 0));
cvReleaseMat(&R);
cvReleaseMat(&t);
cvReleaseMat(&q);
cvReleaseMat(&invK);
cvReleaseMat(&invR);
}
for (int cFeature = 0; cFeature < visibleStructureID.size(); cFeature++)
{
int iFeature = visibleStructureID[cFeature];
cameraParameter.push_back(cvGetReal2D(X, iFeature, 0));
cameraParameter.push_back(cvGetReal2D(X, iFeature, 1));
cameraParameter.push_back(cvGetReal2D(X, iFeature, 2));
}
CvMat *visibilityMask = cvCreateMat(visibleStructureID.size(), nFrames, CV_32FC1);
cvSetZero(visibilityMask);
int NZ = 0;
for (int cFeature = 0; cFeature < visibleStructureID.size(); cFeature++)
{
int iFeature = visibleStructureID[cFeature];
for (int iVisibleFrame = 0; iVisibleFrame < vUsedFrame.size(); iVisibleFrame++)
{
vector<int>::iterator it = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),vUsedFrame[iVisibleFrame]);
if (it != vFeature[iFeature].vFrame.end())
{
int idx = int(it-vFeature[iFeature].vFrame.begin());
feature2DParameter.push_back(vFeature[iFeature].vx[idx]);
feature2DParameter.push_back(vFeature[iFeature].vy[idx]);
cvSetReal2D(visibilityMask, cFeature, iVisibleFrame, 1);
//cvSetReal2D(visibilityMask, iFeature, iVisibleFrame, 1);
NZ++;
}
}
}
for (int iFeature = 0; iFeature < visibilityMask->rows; iFeature++)
{
for (int iFrame = 0; iFrame < visibilityMask->cols; iFrame++)
{
vMask.push_back(cvGetReal2D(visibilityMask, iFeature, iFrame));
}
}
cvReleaseMat(&visibilityMask);
}
void GetParameterForSBA_Distortion(vector<Feature> &vFeature, vector<int> vUsedFrame, vector<CvMat *> cP, CvMat *X, vector<Camera> vCamera, int max_nFrames, vector<int> visibleStructureID,
vector<double> &cameraParameter, vector<double> &feature2DParameter, vector<char> &vMask)
{
int nFrames = cP.size();
int nFeatures = X->rows;
for (int iFrame = 0; iFrame < vUsedFrame.size(); iFrame++)
{
int cFrame = vUsedFrame[iFrame];
int iCamera = (int) ((double)vUsedFrame[iFrame]/max_nFrames);
CvMat *q = cvCreateMat(4,1,CV_32FC1);
CvMat *R = cvCreateMat(3,3,CV_32FC1);
CvMat *t = cvCreateMat(3,1,CV_32FC1);
CvMat *invK = cvCreateMat(3,3,CV_32FC1);
CvMat *invR = cvCreateMat(3,3,CV_32FC1);
cvInvert(vCamera[iCamera].K, invK);
GetSubMatColwise(cP[iFrame], 0, 2, R);
GetSubMatColwise(cP[iFrame], 3, 3, t);
cvMatMul(invK, R, R);
cvInvert(R, invR);
cvMatMul(invK, t, t);
cvMatMul(invR, t, t);
ScalarMul(t, -1, t);
Rotation2Quaternion(R, q);
cameraParameter.push_back(cvGetReal2D(q, 0, 0));
cameraParameter.push_back(cvGetReal2D(q, 1, 0));
cameraParameter.push_back(cvGetReal2D(q, 2, 0));
cameraParameter.push_back(cvGetReal2D(q, 3, 0));
cameraParameter.push_back(cvGetReal2D(t, 0, 0));
cameraParameter.push_back(cvGetReal2D(t, 1, 0));
cameraParameter.push_back(cvGetReal2D(t, 2, 0));
cvReleaseMat(&R);
cvReleaseMat(&t);
cvReleaseMat(&q);
cvReleaseMat(&invK);
cvReleaseMat(&invR);
}
for (int cFeature = 0; cFeature < visibleStructureID.size(); cFeature++)
{
int iFeature = visibleStructureID[cFeature];
cameraParameter.push_back(cvGetReal2D(X, iFeature, 0));
cameraParameter.push_back(cvGetReal2D(X, iFeature, 1));
cameraParameter.push_back(cvGetReal2D(X, iFeature, 2));
}
CvMat *visibilityMask = cvCreateMat(visibleStructureID.size(), nFrames, CV_32FC1);
cvSetZero(visibilityMask);
int NZ = 0;
for (int cFeature = 0; cFeature < visibleStructureID.size(); cFeature++)
{
int iFeature = visibleStructureID[cFeature];
for (int iVisibleFrame = 0; iVisibleFrame < vUsedFrame.size(); iVisibleFrame++)
{
vector<int>::iterator it = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),vUsedFrame[iVisibleFrame]);
if (it != vFeature[iFeature].vFrame.end())
{
int idx = int(it-vFeature[iFeature].vFrame.begin());
feature2DParameter.push_back(vFeature[iFeature].vx_dis[idx]);
feature2DParameter.push_back(vFeature[iFeature].vy_dis[idx]);
cvSetReal2D(visibilityMask, cFeature, iVisibleFrame, 1);
//cvSetReal2D(visibilityMask, iFeature, iVisibleFrame, 1);
NZ++;
}
}
}
for (int iFeature = 0; iFeature < visibilityMask->rows; iFeature++)
{
for (int iFrame = 0; iFrame < visibilityMask->cols; iFrame++)
{
vMask.push_back(cvGetReal2D(visibilityMask, iFeature, iFrame));
}
}
cvReleaseMat(&visibilityMask);
}
void GetParameterForSBA_KRT(vector<Feature> vFeature, vector<int> vUsedFrame, vector<CvMat *> cP, CvMat *X, vector<Camera> vCamera, int max_nFrames, vector<int> visibleStructureID,
vector<double> &cameraParameter, vector<double> &feature2DParameter, vector<char> &vMask)
{
int nFrames = cP.size();
int nFeatures = visibleStructureID.size();
cout << "nFeatures: " << X->rows << " nFeatures_: " << nFeatures <<endl;
for (int iFrame = 0; iFrame < vUsedFrame.size(); iFrame++)
{
int cFrame = vUsedFrame[iFrame];
int takenFrame = vUsedFrame[iFrame] % max_nFrames;
int iCamera = (int) ((double)vUsedFrame[iFrame]/max_nFrames);
CvMat *q = cvCreateMat(4,1,CV_32FC1);
CvMat *R = cvCreateMat(3,3,CV_32FC1);
CvMat *t = cvCreateMat(3,1,CV_32FC1);
CvMat *invK = cvCreateMat(3,3,CV_32FC1);
CvMat *invR = cvCreateMat(3,3,CV_32FC1);
vector<int>::const_iterator it = find(vCamera[iCamera].vTakenFrame.begin(), vCamera[iCamera].vTakenFrame.end(), takenFrame);
if (it == vCamera[iCamera].vTakenFrame.end())
return;
int iTakenFrame = (int) (it - vCamera[iCamera].vTakenFrame.begin());
cvInvert(vCamera[iCamera].vK[iTakenFrame], invK);
double k11 = cvGetReal2D(vCamera[iCamera].vK[iTakenFrame], 0, 0);
double k22 = cvGetReal2D(vCamera[iCamera].vK[iTakenFrame], 1, 1);
double k13 = cvGetReal2D(vCamera[iCamera].vK[iTakenFrame], 0, 2);
double k23 = cvGetReal2D(vCamera[iCamera].vK[iTakenFrame], 1, 2);
GetSubMatColwise(cP[iFrame], 0, 2, R);
GetSubMatColwise(cP[iFrame], 3, 3, t);
cvMatMul(invK, R, R);
cvInvert(R, invR);
cvMatMul(invK, t, t);
cvMatMul(invR, t, t);
ScalarMul(t, -1, t);
Rotation2Quaternion(R, q);
//PrintMat(R);
cameraParameter.push_back(cvGetReal2D(q, 0, 0));
cameraParameter.push_back(cvGetReal2D(q, 1, 0));
cameraParameter.push_back(cvGetReal2D(q, 2, 0));
cameraParameter.push_back(cvGetReal2D(q, 3, 0));
cameraParameter.push_back(cvGetReal2D(t, 0, 0));
cameraParameter.push_back(cvGetReal2D(t, 1, 0));
cameraParameter.push_back(cvGetReal2D(t, 2, 0));
cameraParameter.push_back(k11);
cameraParameter.push_back(k22);
cameraParameter.push_back(k13);
cameraParameter.push_back(k23);
cvReleaseMat(&R);
cvReleaseMat(&t);
cvReleaseMat(&q);
cvReleaseMat(&invK);
cvReleaseMat(&invR);
}
for (int cFeature = 0; cFeature < visibleStructureID.size(); cFeature++)
{
int iFeature = visibleStructureID[cFeature];
cameraParameter.push_back(cvGetReal2D(X, iFeature, 0));
cameraParameter.push_back(cvGetReal2D(X, iFeature, 1));
cameraParameter.push_back(cvGetReal2D(X, iFeature, 2));
}
CvMat *visibilityMask = cvCreateMat(visibleStructureID.size(), nFrames, CV_32FC1);
cvSetZero(visibilityMask);
int NZ = 0;
for (int cFeature = 0; cFeature < visibleStructureID.size(); cFeature++)
{
int iFeature = visibleStructureID[cFeature];
for (int iVisibleFrame = 0; iVisibleFrame < vUsedFrame.size(); iVisibleFrame++)
{
vector<int>::iterator it = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),vUsedFrame[iVisibleFrame]);
if (it != vFeature[iFeature].vFrame.end())
{
int idx = int(it-vFeature[iFeature].vFrame.begin());
feature2DParameter.push_back(vFeature[iFeature].vx[idx]);
feature2DParameter.push_back(vFeature[iFeature].vy[idx]);
cvSetReal2D(visibilityMask, cFeature, iVisibleFrame, 1);
NZ++;
}
}
}
for (int iFeature = 0; iFeature < visibilityMask->rows; iFeature++)
{
for (int iFrame = 0; iFrame < visibilityMask->cols; iFrame++)
{
vMask.push_back(cvGetReal2D(visibilityMask, iFeature, iFrame));
}
}
cvReleaseMat(&visibilityMask);
}
void GetParameterForSBA_KDRT(vector<Feature> vFeature, vector<int> vUsedFrame, vector<CvMat *> cP, CvMat *X, vector<Camera> vCamera, int max_nFrames, vector<int> visibleStructureID,
vector<double> &cameraParameter, vector<double> &feature2DParameter, vector<char> &vMask)
{
int nFrames = cP.size();
int nFeatures = visibleStructureID.size();
for (int iFrame = 0; iFrame < vUsedFrame.size(); iFrame++)
{
PrintMat(cP[iFrame],"P");
int cFrame = vUsedFrame[iFrame];
int takenFrame = vUsedFrame[iFrame] % max_nFrames;
int iCamera = (int) ((double)vUsedFrame[iFrame]/max_nFrames);
CvMat *q = cvCreateMat(4,1,CV_32FC1);
CvMat *R = cvCreateMat(3,3,CV_32FC1);
CvMat *t = cvCreateMat(3,1,CV_32FC1);
CvMat *invK = cvCreateMat(3,3,CV_32FC1);
CvMat *invR = cvCreateMat(3,3,CV_32FC1);
vector<int>::const_iterator it = find(vCamera[iCamera].vTakenFrame.begin(), vCamera[iCamera].vTakenFrame.end(), takenFrame);
if (it == vCamera[iCamera].vTakenFrame.end())
return;
int iTakenFrame = (int) (it - vCamera[iCamera].vTakenFrame.begin());
cvInvert(vCamera[iCamera].vK[iTakenFrame], invK);
double k11 = cvGetReal2D(vCamera[iCamera].vK[iTakenFrame], 0, 0);
double k22 = cvGetReal2D(vCamera[iCamera].vK[iTakenFrame], 1, 1);
double k13 = cvGetReal2D(vCamera[iCamera].vK[iTakenFrame], 0, 2);
double k23 = cvGetReal2D(vCamera[iCamera].vK[iTakenFrame], 1, 2);
GetSubMatColwise(cP[iFrame], 0, 2, R);
GetSubMatColwise(cP[iFrame], 3, 3, t);
cvMatMul(invK, R, R);
cvInvert(R, invR);
cvMatMul(invK, t, t);
cvMatMul(invR, t, t);
ScalarMul(t, -1, t);
Rotation2Quaternion(R, q);
cameraParameter.push_back(cvGetReal2D(q, 0, 0));
cameraParameter.push_back(cvGetReal2D(q, 1, 0));
cameraParameter.push_back(cvGetReal2D(q, 2, 0));
cameraParameter.push_back(cvGetReal2D(q, 3, 0));
cameraParameter.push_back(cvGetReal2D(t, 0, 0));
cameraParameter.push_back(cvGetReal2D(t, 1, 0));
cameraParameter.push_back(cvGetReal2D(t, 2, 0));
cameraParameter.push_back(k11);
cameraParameter.push_back(k22);
cameraParameter.push_back(k13);
cameraParameter.push_back(k23);
cameraParameter.push_back(vCamera[iCamera].vk1[iTakenFrame]);
cameraParameter.push_back(vCamera[iCamera].vk2[iTakenFrame]);
cvReleaseMat(&R);
cvReleaseMat(&t);
cvReleaseMat(&q);
cvReleaseMat(&invK);
cvReleaseMat(&invR);
}
for (int cFeature = 0; cFeature < visibleStructureID.size(); cFeature++)
{
int iFeature = visibleStructureID[cFeature];
cameraParameter.push_back(cvGetReal2D(X, iFeature, 0));
cameraParameter.push_back(cvGetReal2D(X, iFeature, 1));
cameraParameter.push_back(cvGetReal2D(X, iFeature, 2));
}
CvMat *visibilityMask = cvCreateMat(visibleStructureID.size(), nFrames, CV_32FC1);
cvSetZero(visibilityMask);
int NZ = 0;
for (int cFeature = 0; cFeature < visibleStructureID.size(); cFeature++)
{
int iFeature = visibleStructureID[cFeature];
for (int iVisibleFrame = 0; iVisibleFrame < vUsedFrame.size(); iVisibleFrame++)
{
vector<int>::iterator it = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),vUsedFrame[iVisibleFrame]);
if (it != vFeature[iFeature].vFrame.end())
{
int idx = int(it-vFeature[iFeature].vFrame.begin());
feature2DParameter.push_back(vFeature[iFeature].vx[idx]);
feature2DParameter.push_back(vFeature[iFeature].vy[idx]);
cvSetReal2D(visibilityMask, cFeature, iVisibleFrame, 1);
NZ++;
}
}
}
for (int iFeature = 0; iFeature < visibilityMask->rows; iFeature++)
{
for (int iFrame = 0; iFrame < visibilityMask->cols; iFrame++)
{
vMask.push_back(cvGetReal2D(visibilityMask, iFeature, iFrame));
}
}
cvReleaseMat(&visibilityMask);
}
void GetParameterForSBA_TEMPORAL(vector<Feature> vFeature, vector<Theta> vTheta, vector<Camera> vCamera, int max_nFrames,
vector<double> &cameraParameter, vector<double> &feature2DParameter, vector<char> &vMask)
{
int nFrames = 0;
vector<int> vUsedFrame;
for (int iCamera = 0; iCamera < vCamera.size(); iCamera++)
{
for (int iFrame = 0; iFrame < vCamera[iCamera].vTakenFrame.size(); iFrame++)
{
// Temporal error initialization
cameraParameter.push_back(0);
vUsedFrame.push_back(iCamera*max_nFrames+vCamera[iCamera].vTakenFrame[iFrame]);
nFrames++;
}
}
for (int iTheta = 0; iTheta < vTheta.size(); iTheta++)
{
for (int iTheta_x = 0; iTheta_x < vTheta[iTheta].thetaX.size(); iTheta_x++)
cameraParameter.push_back(vTheta[iTheta].thetaX[iTheta_x]);
for (int iTheta_x = 0; iTheta_x < vTheta[iTheta].thetaX.size(); iTheta_x++)
cameraParameter.push_back(vTheta[iTheta].thetaY[iTheta_x]);
for (int iTheta_x = 0; iTheta_x < vTheta[iTheta].thetaX.size(); iTheta_x++)
cameraParameter.push_back(vTheta[iTheta].thetaZ[iTheta_x]);
}
CvMat *visibilityMask = cvCreateMat(vTheta.size(), nFrames, CV_32FC1);
cvSetZero(visibilityMask);
int NZ = 0;
for (int iFeature = 0; iFeature < vFeature.size(); iFeature++)
{
for (int iVisibleFrame = 0; iVisibleFrame < vUsedFrame.size(); iVisibleFrame++)
{
vector<int>::iterator it = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),vUsedFrame[iVisibleFrame]);
if (it != vFeature[iFeature].vFrame.end())
{
int idx = int(it-vFeature[iFeature].vFrame.begin());
feature2DParameter.push_back(vFeature[iFeature].vx[idx]);
feature2DParameter.push_back(vFeature[iFeature].vy[idx]);
feature2DParameter.push_back(0.0);
feature2DParameter.push_back(0.0);
cvSetReal2D(visibilityMask, iFeature, iVisibleFrame, 1);
NZ++;
}
}
}
for (int iFeature = 0; iFeature < visibilityMask->rows; iFeature++)
{
for (int iFrame = 0; iFrame < visibilityMask->cols; iFrame++)
{
vMask.push_back(cvGetReal2D(visibilityMask, iFeature, iFrame));
}
}
cvReleaseMat(&visibilityMask);
}
void GetParameterForSBA_TEMPORAL_LEVMAR(vector<Feature> vFeature, vector<Theta> vTheta, vector<Camera> vCamera, int max_nFrames,
vector<double> &cameraParameter, vector<double> &feature2DParameter)
{
int nFrames = 0;
vector<int> vUsedFrame;
for (int iCamera = 0; iCamera < vCamera.size(); iCamera++)
{
for (int iFrame = 0; iFrame < vCamera[iCamera].vTakenFrame.size(); iFrame++)
{
// Temporal error initialization
cameraParameter.push_back(0);
vUsedFrame.push_back(iCamera*max_nFrames+vCamera[iCamera].vTakenFrame[iFrame]);
nFrames++;
}
}
for (int iTheta = 0; iTheta < vTheta.size(); iTheta++)
{
for (int iTheta_x = 0; iTheta_x < vTheta[iTheta].thetaX.size(); iTheta_x++)
cameraParameter.push_back(vTheta[iTheta].thetaX[iTheta_x]);
for (int iTheta_x = 0; iTheta_x < vTheta[iTheta].thetaX.size(); iTheta_x++)
cameraParameter.push_back(vTheta[iTheta].thetaY[iTheta_x]);
for (int iTheta_x = 0; iTheta_x < vTheta[iTheta].thetaX.size(); iTheta_x++)
cameraParameter.push_back(vTheta[iTheta].thetaZ[iTheta_x]);
}
for (int iFeature = 0; iFeature < vFeature.size(); iFeature++)
{
for (int iVisibleFrame = 0; iVisibleFrame < vUsedFrame.size(); iVisibleFrame++)
{
vector<int>::iterator it = find(vFeature[iFeature].vFrame.begin(),vFeature[iFeature].vFrame.end(),vUsedFrame[iVisibleFrame]);
if (it != vFeature[iFeature].vFrame.end())
{
int idx = int(it-vFeature[iFeature].vFrame.begin());
feature2DParameter.push_back(vFeature[iFeature].vx[idx]);
feature2DParameter.push_back(vFeature[iFeature].vy[idx]);
}
else
{
feature2DParameter.push_back(0);
feature2DParameter.push_back(0);
}
}
}
}
void GetParameterForGBA(vector<Feature> vFeature, vector<Camera> vCamera, vector<Theta> vTheta, CvMat *K, int nFrames,
vector<double> &cameraParameter, vector<double> &feature2DParameter, vector<char> &vMask)
{
int nFeatures = vFeature.size();
for (int iCamera = 0; iCamera < vCamera.size(); iCamera++)
{
for (int iFrame = 0; iFrame < nFrames; iFrame++)
{
vector<int>::const_iterator it = find(vCamera[iCamera].vTakenFrame.begin(), vCamera[iCamera].vTakenFrame.end(), iFrame);
if (it == vCamera[iCamera].vTakenFrame.end())
{
cameraParameter.push_back(0);
cameraParameter.push_back(0);
cameraParameter.push_back(0);
cameraParameter.push_back(0);
cameraParameter.push_back(0);
cameraParameter.push_back(0);
cameraParameter.push_back(0);
}
else
{
CvMat *q = cvCreateMat(4,1,CV_32FC1);
CvMat *R = cvCreateMat(3,3,CV_32FC1);
CvMat *t = cvCreateMat(3,1,CV_32FC1);
CvMat *invK = cvCreateMat(3,3,CV_32FC1);
CvMat *invR = cvCreateMat(3,3,CV_32FC1);
cvInvert(K, invK);
GetSubMatColwise(vCamera[iCamera].vP[iFrame], 0, 2, R);
GetSubMatColwise(vCamera[iCamera].vP[iFrame], 3, 3, t);
cvMatMul(invK, R, R);
cvInvert(R, invR);
cvMatMul(invK, t, t);
cvMatMul(invR, t, t);
ScalarMul(t, -1, t);
Rotation2Quaternion(R, q);
cameraParameter.push_back(cvGetReal2D(q, 0, 0));
cameraParameter.push_back(cvGetReal2D(q, 1, 0));
cameraParameter.push_back(cvGetReal2D(q, 2, 0));
cameraParameter.push_back(cvGetReal2D(q, 3, 0));
cameraParameter.push_back(cvGetReal2D(t, 0, 0));
cameraParameter.push_back(cvGetReal2D(t, 1, 0));
cameraParameter.push_back(cvGetReal2D(t, 2, 0));
cvReleaseMat(&R);
cvReleaseMat(&t);
cvReleaseMat(&q);
cvReleaseMat(&invK);
cvReleaseMat(&invR);
}
}
}
for (int iTheta = 0; iTheta < vTheta.size(); iTheta++)
{
if (vTheta[iTheta].isStatic)
{
double IDCT = sqrt(1.0/(double)nFrames);
double X = vTheta[iTheta].thetaX[0]*IDCT;
double Y = vTheta[iTheta].thetaY[0]*IDCT;
double Z = vTheta[iTheta].thetaZ[0]*IDCT;
cameraParameter.push_back(X);
cameraParameter.push_back(Y);
cameraParameter.push_back(Z);
}
else
{
for (int iBase = 0; iBase < vTheta[iTheta].thetaX.size(); iBase++)
{
cameraParameter.push_back(vTheta[iTheta].thetaX[iBase]);
}
for (int iBase = 0; iBase < vTheta[iTheta].thetaX.size(); iBase++)
{
cameraParameter.push_back(vTheta[iTheta].thetaY[iBase]);
}
for (int iBase = 0; iBase < vTheta[iTheta].thetaX.size(); iBase++)
{
cameraParameter.push_back(vTheta[iTheta].thetaZ[iBase]);
}
}
}
CvMat *visibilityMask = cvCreateMat(vTheta.size(), vCamera.size()*nFrames, CV_32FC1);
cvSetZero(visibilityMask);
int NZ = 0;
for (int iFeature = 0; iFeature < vFeature.size(); iFeature++)
{
for (int iFrame = 0; iFrame < vFeature[iFeature].vFrame.size(); iFrame++)
{
feature2DParameter.push_back(vFeature[iFeature].vx[iFrame]);
feature2DParameter.push_back(vFeature[iFeature].vy[iFrame]);
cvSetReal2D(visibilityMask, iFeature, iFrame, 1);
}
}
for (int iFeature = 0; iFeature < visibilityMask->rows; iFeature++)
{
for (int iFrame = 0; iFrame < visibilityMask->cols; iFrame++)
{
vMask.push_back(cvGetReal2D(visibilityMask, iFeature, iFrame));
}
}
cvReleaseMat(&visibilityMask);
}
void GetParameterForGBA(vector<Feature> vFeature, vector<Camera> vCamera, vector<Theta> vTheta, CvMat *K, int nFrames,
vector<double> &cameraParameter, vector<double> &feature2DParameter, CvMat &visibilityMask)
{
int nFeatures = vFeature.size();
for (int iCamera = 0; iCamera < vCamera.size(); iCamera++)
{
for (int iFrame = 0; iFrame < nFrames; iFrame++)
{
vector<int>::const_iterator it = find(vCamera[iCamera].vTakenFrame.begin(), vCamera[iCamera].vTakenFrame.end(), iFrame);
if (it == vCamera[iCamera].vTakenFrame.end())
{
cameraParameter.push_back(0);
cameraParameter.push_back(0);
cameraParameter.push_back(0);
cameraParameter.push_back(0);
cameraParameter.push_back(0);
cameraParameter.push_back(0);
cameraParameter.push_back(0);
}
else
{
CvMat *q = cvCreateMat(4,1,CV_32FC1);
CvMat *R = cvCreateMat(3,3,CV_32FC1);
CvMat *t = cvCreateMat(3,1,CV_32FC1);
CvMat *invK = cvCreateMat(3,3,CV_32FC1);
CvMat *invR = cvCreateMat(3,3,CV_32FC1);
cvInvert(K, invK);
GetSubMatColwise(vCamera[iCamera].vP[iFrame], 0, 2, R);
GetSubMatColwise(vCamera[iCamera].vP[iFrame], 3, 3, t);
cvMatMul(invK, R, R);
cvInvert(R, invR);
cvMatMul(invK, t, t);
cvMatMul(invR, t, t);
ScalarMul(t, -1, t);
Rotation2Quaternion(R, q);
cameraParameter.push_back(cvGetReal2D(q, 0, 0));
cameraParameter.push_back(cvGetReal2D(q, 1, 0));
cameraParameter.push_back(cvGetReal2D(q, 2, 0));
cameraParameter.push_back(cvGetReal2D(q, 3, 0));
cameraParameter.push_back(cvGetReal2D(t, 0, 0));
cameraParameter.push_back(cvGetReal2D(t, 1, 0));
cameraParameter.push_back(cvGetReal2D(t, 2, 0));
cvReleaseMat(&R);
cvReleaseMat(&t);
cvReleaseMat(&q);
cvReleaseMat(&invK);
cvReleaseMat(&invR);
}
}
}
for (int iTheta = 0; iTheta < vTheta.size(); iTheta++)
{
if (vTheta[iTheta].isStatic)
{
double IDCT = sqrt(1.0/(double)nFrames);
double X = vTheta[iTheta].thetaX[0]*IDCT;
double Y = vTheta[iTheta].thetaY[0]*IDCT;
double Z = vTheta[iTheta].thetaZ[0]*IDCT;
cameraParameter.push_back(X);
cameraParameter.push_back(Y);
cameraParameter.push_back(Z);
}
else
{
for (int iBase = 0; iBase < vTheta[iTheta].thetaX.size(); iBase++)
{
cameraParameter.push_back(vTheta[iTheta].thetaX[iBase]);
}
for (int iBase = 0; iBase < vTheta[iTheta].thetaX.size(); iBase++)
{
cameraParameter.push_back(vTheta[iTheta].thetaY[iBase]);
}
for (int iBase = 0; iBase < vTheta[iTheta].thetaX.size(); iBase++)
{
cameraParameter.push_back(vTheta[iTheta].thetaZ[iBase]);
}
}
}
visibilityMask = *cvCreateMat(vTheta.size(), vCamera.size()*nFrames, CV_32FC1);
cvSetZero(&visibilityMask);
int NZ = 0;
for (int iFeature = 0; iFeature < vFeature.size(); iFeature++)
{
for (int iFrame = 0; iFrame < vFeature[iFeature].vFrame.size(); iFrame++)
{
feature2DParameter.push_back(vFeature[iFeature].vx[iFrame]);
feature2DParameter.push_back(vFeature[iFeature].vy[iFrame]);
cvSetReal2D(&visibilityMask, iFeature, iFrame, 1);
}
}
}
//void GetCameraParameter(CvMat *P, CvMat *K, CvMat &R, CvMat &C)
//{
// R = *cvCreateMat(3,3,CV_32FC1);
// C = *cvCreateMat(3,1,CV_32FC1);
// CvMat *temp34 = cvCreateMat(3,4,CV_32FC1);
// CvMat *invK = cvCreateMat(3,3,CV_32FC1);
// cvInvert(K, invK);
// cvMatMul(invK, P, temp34);
// GetSubMatColwise(temp34, 0,2,&R);
// GetSubMatColwise(temp34, 3,3,&C);
// CvMat *invR = cvCreateMat(3,3,CV_32FC1);
// cvInvert(&R, invR);
// cvMatMul(invR, &C, &C);
// ScalarMul(&C, -1, &C);
//
// cvReleaseMat(&temp34);
// cvReleaseMat(&invK);
// cvReleaseMat(&invR);
//}
//
//void GetCameraParameter(CvMat *P, CvMat *K, CvMat *R, CvMat *C)
//{
// //R = *cvCreateMat(3,3,CV_32FC1);
// //C = *cvCreateMat(3,1,CV_32FC1);
// CvMat *temp34 = cvCreateMat(3,4,CV_32FC1);
// CvMat *invK = cvCreateMat(3,3,CV_32FC1);
// cvInvert(K, invK);
// cvMatMul(invK, P, temp34);
// GetSubMatColwise(temp34, 0,2,R);
// GetSubMatColwise(temp34, 3,3,C);
// CvMat *invR = cvCreateMat(3,3,CV_32FC1);
// cvInvert(R, invR);
// cvMatMul(invR, C, C);
// ScalarMul(C, -1, C);
//
// cvReleaseMat(&temp34);
// cvReleaseMat(&invK);
// cvReleaseMat(&invR);
//}
void CreateCameraMatrix(CvMat *R, CvMat *C, CvMat *K, CvMat &P)
{
P = *cvCreateMat(3,4,CV_32FC1);
cvSetIdentity(&P);
ScalarMul(C, -1, C);
SetSubMat(&P, 0,3, C);
cvMatMul(R, &P, &P);
cvMatMul(K, &P, &P);
}
void CreateCameraMatrix(CvMat *R, CvMat *C, CvMat *K, CvMat *P)
{
cvSetIdentity(P);
ScalarMul(C, -1, C);
SetSubMat(P, 0,3, C);
cvMatMul(R, P, P);
cvMatMul(K, P, P);
}
int ExcludePointBehindCamera(CvMat *X, CvMat *P1, CvMat *P2, vector<int> featureID, vector<int> &excludedFeatureID, CvMat &cX)
{
CvMat *H1 = cvCreateMat(4, 4, CV_32FC1); CvMat *invH1 = cvCreateMat(4, 4, CV_32FC1);
CvMat *HX1 = cvCreateMat(X->rows, X->cols, CV_32FC1);
cvSetIdentity(H1);
SetSubMat(H1, 0, 0, P1);
cvInvert(H1, invH1);
Pxx_inhomo(H1, X, HX1);
CvMat *H2 = cvCreateMat(4, 4, CV_32FC1); CvMat *invH2 = cvCreateMat(4, 4, CV_32FC1);
CvMat *HX2 = cvCreateMat(X->rows, X->cols, CV_32FC1);
cvSetIdentity(H2);
SetSubMat(H2, 0, 0, P2);
cvInvert(H2, invH2);
Pxx_inhomo(H2, X, HX2);
excludedFeatureID.clear();
for (int i = 0; i < X->rows; i++)
{
if ((cvGetReal2D(HX1, i, 2) > 0) && (cvGetReal2D(HX2, i, 2) > 0))
excludedFeatureID.push_back(featureID[i]);
}
if (excludedFeatureID.size() == 0)
return 0;
cX = *cvCreateMat(excludedFeatureID.size(),3, CV_32FC1);
int k = 0;
for (int i = 0; i < X->rows; i++)
{
if ((cvGetReal2D(HX1, i, 2) > 0) && (cvGetReal2D(HX2, i, 2) > 0))
{
cvSetReal2D(&cX, k, 0, cvGetReal2D(X, i, 0));
cvSetReal2D(&cX, k, 1, cvGetReal2D(X, i, 1));
cvSetReal2D(&cX, k, 2, cvGetReal2D(X, i, 2));
k++;
}
}
return 1;
}
int ExcludePointBehindCamera_mem(CvMat *X, CvMat *P1, CvMat *P2, vector<int> featureID, vector<int> &excludedFeatureID, vector<vector<double> > &cX)
{
CvMat *H1 = cvCreateMat(4, 4, CV_32FC1); CvMat *invH1 = cvCreateMat(4, 4, CV_32FC1);
CvMat *HX1 = cvCreateMat(X->rows, X->cols, CV_32FC1);
cvSetIdentity(H1);
SetSubMat(H1, 0, 0, P1);
cvInvert(H1, invH1);
Pxx_inhomo(H1, X, HX1);
CvMat *H2 = cvCreateMat(4, 4, CV_32FC1); CvMat *invH2 = cvCreateMat(4, 4, CV_32FC1);
CvMat *HX2 = cvCreateMat(X->rows, X->cols, CV_32FC1);
cvSetIdentity(H2);
SetSubMat(H2, 0, 0, P2);
cvInvert(H2, invH2);
Pxx_inhomo(H2, X, HX2);
excludedFeatureID.clear();
for (int i = 0; i < X->rows; i++)
{
if ((cvGetReal2D(HX1, i, 2) > 0) && (cvGetReal2D(HX2, i, 2) > 0))
excludedFeatureID.push_back(featureID[i]);
}
if (excludedFeatureID.size() == 0)
{
cvReleaseMat(&H1);
cvReleaseMat(&HX1);
cvReleaseMat(&H2);
cvReleaseMat(&HX2);
cvReleaseMat(&invH1);
cvReleaseMat(&invH2);
return 0;
}
//cX = *cvCreateMat(excludedFeatureID.size(),3, CV_32FC1);
int k = 0;
for (int i = 0; i < X->rows; i++)
{
if ((cvGetReal2D(HX1, i, 2) > 0) && (cvGetReal2D(HX2, i, 2) > 0))
{
vector<double> cX_vec;
cX_vec.push_back(cvGetReal2D(X, i, 0));
cX_vec.push_back(cvGetReal2D(X, i, 1));
cX_vec.push_back(cvGetReal2D(X, i, 2));
cX.push_back(cX_vec);
k++;
}
}
cvReleaseMat(&H1);
cvReleaseMat(&HX1);
cvReleaseMat(&H2);
cvReleaseMat(&HX2);
cvReleaseMat(&invH1);
cvReleaseMat(&invH2);
return cX.size();
}
int ExcludePointBehindCamera_mem_fast(CvMat *X, CvMat *P1, CvMat *P2, vector<int> &featureID, vector<int> &excludedFeatureID, vector<vector<double> > &cX)
{
CvMat *H1 = cvCreateMat(4, 4, CV_32FC1); CvMat *invH1 = cvCreateMat(4, 4, CV_32FC1);
CvMat *HX1 = cvCreateMat(X->rows, X->cols, CV_32FC1);
cvSetIdentity(H1);
SetSubMat(H1, 0, 0, P1);
cvInvert(H1, invH1);
Pxx_inhomo(H1, X, HX1);
CvMat *H2 = cvCreateMat(4, 4, CV_32FC1); CvMat *invH2 = cvCreateMat(4, 4, CV_32FC1);
CvMat *HX2 = cvCreateMat(X->rows, X->cols, CV_32FC1);
cvSetIdentity(H2);
SetSubMat(H2, 0, 0, P2);
cvInvert(H2, invH2);
Pxx_inhomo(H2, X, HX2);
excludedFeatureID.clear();
for (int i = 0; i < X->rows; i++)
{
if ((cvGetReal2D(HX1, i, 2) > 0) && (cvGetReal2D(HX2, i, 2) > 0))
{
excludedFeatureID.push_back(featureID[i]);
vector<double> cX_vec;
cX_vec.push_back(cvGetReal2D(X, i, 0));
cX_vec.push_back(cvGetReal2D(X, i, 1));
cX_vec.push_back(cvGetReal2D(X, i, 2));
cX.push_back(cX_vec);
}
}
if (excludedFeatureID.size() == 0)
{
cvReleaseMat(&H1);
cvReleaseMat(&HX1);
cvReleaseMat(&H2);
cvReleaseMat(&HX2);
cvReleaseMat(&invH1);
cvReleaseMat(&invH2);
return 0;
}
cvReleaseMat(&H1);
cvReleaseMat(&HX1);
cvReleaseMat(&H2);
cvReleaseMat(&HX2);
cvReleaseMat(&invH1);
cvReleaseMat(&invH2);
return cX.size();
}
int ExcludePointAtInfinity(CvMat *X, CvMat *P1, CvMat *P2, CvMat *K1, CvMat *K2, vector<int> featureID, vector<int> &excludedFeatureID, CvMat &cX)
{
CvMat *q1 = cvCreateMat(4,1,CV_32FC1);
CvMat *R1 = cvCreateMat(3,3,CV_32FC1);
CvMat *t1 = cvCreateMat(3,1,CV_32FC1);
CvMat *invK1 = cvCreateMat(3,3,CV_32FC1);
CvMat *invR1 = cvCreateMat(3,3,CV_32FC1);
CvMat *q2 = cvCreateMat(4,1,CV_32FC1);
CvMat *R2 = cvCreateMat(3,3,CV_32FC1);
CvMat *t2 = cvCreateMat(3,1,CV_32FC1);
CvMat *invK2 = cvCreateMat(3,3,CV_32FC1);
CvMat *invR2 = cvCreateMat(3,3,CV_32FC1);
GetSubMatColwise(P1, 0, 2, R1);
GetSubMatColwise(P1, 3, 3, t1);
cvInvert(K1, invK1);
cvMatMul(invK1, R1, R1);
cvInvert(R1, invR1);
cvMatMul(invK1, t1, t1);
cvMatMul(invR1, t1, t1);
ScalarMul(t1, -1, t1);
GetSubMatColwise(P2, 0, 2, R2);
GetSubMatColwise(P2, 3, 3, t2);
cvInvert(K2, invK2);
cvMatMul(invK2, R2, R2);
cvInvert(R2, invR2);
cvMatMul(invK2, t2, t2);
cvMatMul(invR2, t2, t2);
ScalarMul(t2, -1, t2);
double xC1 = cvGetReal2D(t1, 0, 0);
double yC1 = cvGetReal2D(t1, 1, 0);
double zC1 = cvGetReal2D(t1, 2, 0);
double xC2 = cvGetReal2D(t2, 0, 0);
double yC2 = cvGetReal2D(t2, 1, 0);
double zC2 = cvGetReal2D(t2, 2, 0);
excludedFeatureID.clear();
vector<double> vInner;
for (int i = 0; i < X->rows; i++)
{
double x3D = cvGetReal2D(X, i, 0);
double y3D = cvGetReal2D(X, i, 1);
double z3D = cvGetReal2D(X, i, 2);
double v1x = x3D - xC1; double v1y = y3D - yC1; double v1z = z3D - zC1;
double v2x = x3D - xC2; double v2y = y3D - yC2; double v2z = z3D - zC2;
double nv1 = sqrt(v1x*v1x+v1y*v1y+v1z*v1z);
double nv2 = sqrt(v2x*v2x+v2y*v2y+v2z*v2z);
v1x /= nv1; v1y /= nv1; v1z /= nv1;
v2x /= nv2; v2y /= nv2; v2z /= nv2;
double inner = v1x*v2x+v1y*v2y+v1z*v2z;
vInner.push_back(inner);
if ((abs(inner) < cos(PI/180*3)) && (inner > 0))
excludedFeatureID.push_back(featureID[i]);
}
if (excludedFeatureID.size() == 0)
return 0;
cX = *cvCreateMat(excludedFeatureID.size(),3, CV_32FC1);
int k = 0;
for (int i = 0; i < X->rows; i++)
{
if ((abs(vInner[i]) < cos(PI/180*3)) && (vInner[i] > 0))
{
cvSetReal2D(&cX, k, 0, cvGetReal2D(X, i, 0));
cvSetReal2D(&cX, k, 1, cvGetReal2D(X, i, 1));
cvSetReal2D(&cX, k, 2, cvGetReal2D(X, i, 2));
k++;
}
}
return 1;
}
int ExcludePointAtInfinity_mem(CvMat *X, CvMat *P1, CvMat *P2, CvMat *K1, CvMat *K2, vector<int> featureID, vector<int> &excludedFeatureID, vector<vector<double> > &cX)
{
CvMat *q1 = cvCreateMat(4,1,CV_32FC1);
CvMat *R1 = cvCreateMat(3,3,CV_32FC1);
CvMat *t1 = cvCreateMat(3,1,CV_32FC1);
CvMat *invK1 = cvCreateMat(3,3,CV_32FC1);
CvMat *invR1 = cvCreateMat(3,3,CV_32FC1);
CvMat *q2 = cvCreateMat(4,1,CV_32FC1);
CvMat *R2 = cvCreateMat(3,3,CV_32FC1);
CvMat *t2 = cvCreateMat(3,1,CV_32FC1);
CvMat *invK2 = cvCreateMat(3,3,CV_32FC1);
CvMat *invR2 = cvCreateMat(3,3,CV_32FC1);
GetSubMatColwise(P1, 0, 2, R1);
GetSubMatColwise(P1, 3, 3, t1);
cvInvert(K1, invK1);
cvMatMul(invK1, R1, R1);
cvInvert(R1, invR1);
cvMatMul(invK1, t1, t1);
cvMatMul(invR1, t1, t1);
ScalarMul(t1, -1, t1);
GetSubMatColwise(P2, 0, 2, R2);
GetSubMatColwise(P2, 3, 3, t2);
cvInvert(K2, invK2);
cvMatMul(invK2, R2, R2);
cvInvert(R2, invR2);
cvMatMul(invK2, t2, t2);
cvMatMul(invR2, t2, t2);
ScalarMul(t2, -1, t2);
double xC1 = cvGetReal2D(t1, 0, 0);
double yC1 = cvGetReal2D(t1, 1, 0);
double zC1 = cvGetReal2D(t1, 2, 0);
double xC2 = cvGetReal2D(t2, 0, 0);
double yC2 = cvGetReal2D(t2, 1, 0);
double zC2 = cvGetReal2D(t2, 2, 0);
excludedFeatureID.clear();
vector<double> vInner;
for (int i = 0; i < X->rows; i++)
{
double x3D = cvGetReal2D(X, i, 0);
double y3D = cvGetReal2D(X, i, 1);
double z3D = cvGetReal2D(X, i, 2);
double v1x = x3D - xC1; double v1y = y3D - yC1; double v1z = z3D - zC1;
double v2x = x3D - xC2; double v2y = y3D - yC2; double v2z = z3D - zC2;
double nv1 = sqrt(v1x*v1x+v1y*v1y+v1z*v1z);
double nv2 = sqrt(v2x*v2x+v2y*v2y+v2z*v2z);
v1x /= nv1; v1y /= nv1; v1z /= nv1;
v2x /= nv2; v2y /= nv2; v2z /= nv2;
double inner = v1x*v2x+v1y*v2y+v1z*v2z;
vInner.push_back(inner);
if ((abs(inner) < cos(PI/180*3)) && (inner > 0))
excludedFeatureID.push_back(featureID[i]);
}
if (excludedFeatureID.size() == 0)
{
cvReleaseMat(&q1);
cvReleaseMat(&R1);
cvReleaseMat(&t1);
cvReleaseMat(&invK1);
cvReleaseMat(&invR1);
cvReleaseMat(&q2);
cvReleaseMat(&R2);
cvReleaseMat(&t2);
cvReleaseMat(&invK2);
cvReleaseMat(&invR2);
return 0;
}
int k = 0;
for (int i = 0; i < X->rows; i++)
{
if ((abs(vInner[i]) < cos(PI/180*3)) && (vInner[i] > 0))
{
vector<double> cX_vec;
cX_vec.push_back(cvGetReal2D(X, i, 0));
cX_vec.push_back(cvGetReal2D(X, i, 1));
cX_vec.push_back(cvGetReal2D(X, i, 2));
cX.push_back(cX_vec);
k++;
}
}
cvReleaseMat(&q1);
cvReleaseMat(&R1);
cvReleaseMat(&t1);
cvReleaseMat(&invK1);
cvReleaseMat(&invR1);
cvReleaseMat(&q2);
cvReleaseMat(&R2);
cvReleaseMat(&t2);
cvReleaseMat(&invK2);
cvReleaseMat(&invR2);
return cX.size();
}
int ExcludePointAtInfinity_mem_fast(CvMat *X, CvMat *P1, CvMat *P2, CvMat *K1, CvMat *K2, vector<int> &featureID, vector<int> &excludedFeatureID, vector<vector<double> > &cX)
{
CvMat *q1 = cvCreateMat(4,1,CV_32FC1);
CvMat *R1 = cvCreateMat(3,3,CV_32FC1);
CvMat *t1 = cvCreateMat(3,1,CV_32FC1);
CvMat *invK1 = cvCreateMat(3,3,CV_32FC1);
CvMat *invR1 = cvCreateMat(3,3,CV_32FC1);
CvMat *q2 = cvCreateMat(4,1,CV_32FC1);
CvMat *R2 = cvCreateMat(3,3,CV_32FC1);
CvMat *t2 = cvCreateMat(3,1,CV_32FC1);
CvMat *invK2 = cvCreateMat(3,3,CV_32FC1);
CvMat *invR2 = cvCreateMat(3,3,CV_32FC1);
GetSubMatColwise(P1, 0, 2, R1);
GetSubMatColwise(P1, 3, 3, t1);
cvInvert(K1, invK1);
cvMatMul(invK1, R1, R1);
cvInvert(R1, invR1);
cvMatMul(invK1, t1, t1);
cvMatMul(invR1, t1, t1);
ScalarMul(t1, -1, t1);
GetSubMatColwise(P2, 0, 2, R2);
GetSubMatColwise(P2, 3, 3, t2);
cvInvert(K2, invK2);
cvMatMul(invK2, R2, R2);
cvInvert(R2, invR2);
cvMatMul(invK2, t2, t2);
cvMatMul(invR2, t2, t2);
ScalarMul(t2, -1, t2);
double xC1 = cvGetReal2D(t1, 0, 0);
double yC1 = cvGetReal2D(t1, 1, 0);
double zC1 = cvGetReal2D(t1, 2, 0);
double xC2 = cvGetReal2D(t2, 0, 0);
double yC2 = cvGetReal2D(t2, 1, 0);
double zC2 = cvGetReal2D(t2, 2, 0);
excludedFeatureID.clear();
vector<double> vInner;
for (int i = 0; i < X->rows; i++)
{
double x3D = cvGetReal2D(X, i, 0);
double y3D = cvGetReal2D(X, i, 1);
double z3D = cvGetReal2D(X, i, 2);
double v1x = x3D - xC1; double v1y = y3D - yC1; double v1z = z3D - zC1;
double v2x = x3D - xC2; double v2y = y3D - yC2; double v2z = z3D - zC2;
double nv1 = sqrt(v1x*v1x+v1y*v1y+v1z*v1z);
double nv2 = sqrt(v2x*v2x+v2y*v2y+v2z*v2z);
v1x /= nv1; v1y /= nv1; v1z /= nv1;
v2x /= nv2; v2y /= nv2; v2z /= nv2;
double inner = v1x*v2x+v1y*v2y+v1z*v2z;
vInner.push_back(inner);
if ((abs(inner) < cos(PI/180*3)) && (inner > 0))
{
vector<double> cX_vec;
cX_vec.push_back(x3D);
cX_vec.push_back(y3D);
cX_vec.push_back(z3D);
cX.push_back(cX_vec);
excludedFeatureID.push_back(featureID[i]);
}
}
if (excludedFeatureID.size() == 0)
{
cvReleaseMat(&q1);
cvReleaseMat(&R1);
cvReleaseMat(&t1);
cvReleaseMat(&invK1);
cvReleaseMat(&invR1);
cvReleaseMat(&q2);
cvReleaseMat(&R2);
cvReleaseMat(&t2);
cvReleaseMat(&invK2);
cvReleaseMat(&invR2);
return 0;
}
cvReleaseMat(&q1);
cvReleaseMat(&R1);
cvReleaseMat(&t1);
cvReleaseMat(&invK1);
cvReleaseMat(&invR1);
cvReleaseMat(&q2);
cvReleaseMat(&R2);
cvReleaseMat(&t2);
cvReleaseMat(&invK2);
cvReleaseMat(&invR2);
return cX.size();
}
void ExcludePointHighReprojectionError(vector<Feature> vFeature, vector<CvMat *> cP, vector<int> vUsedFrame, vector<int> &visibleStrucrtureID, CvMat *X_tot)
{
vector<bool> temp;
temp.resize(visibleStrucrtureID.size(), true);
for (int iP = 0; iP < cP.size(); iP++)
{
for (int iVS = 0; iVS < visibleStrucrtureID.size(); iVS++)
{
vector<int>:: const_iterator it = find(vFeature[visibleStrucrtureID[iVS]].vFrame.begin(), vFeature[visibleStrucrtureID[iVS]].vFrame.end(), vUsedFrame[iP]);
if (it != vFeature[visibleStrucrtureID[iVS]].vFrame.end())
{
int idx = (int) (it - vFeature[visibleStrucrtureID[iVS]].vFrame.begin());
CvMat *X = cvCreateMat(4, 1, CV_32FC1);
CvMat *x = cvCreateMat(3, 1, CV_32FC1);
cvSetReal2D(X, 0, 0, cvGetReal2D(X_tot, visibleStrucrtureID[iVS], 0));
cvSetReal2D(X, 1, 0, cvGetReal2D(X_tot, visibleStrucrtureID[iVS], 1));
cvSetReal2D(X, 2, 0, cvGetReal2D(X_tot, visibleStrucrtureID[iVS], 2));
cvSetReal2D(X, 3, 0, 1);
cvMatMul(cP[iP], X, x);
double u0 = vFeature[visibleStrucrtureID[iVS]].vx[idx];
double v0 = vFeature[visibleStrucrtureID[iVS]].vy[idx];
double u1 = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0);
double v1 = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0);
if (sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)) > 5)
{
cout << visibleStrucrtureID[iVS] << "th 3D point erased " << sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)) << endl;
if(temp[iVS])
temp[iVS] = false;
}
cvReleaseMat(&X);
cvReleaseMat(&x);
}
}
}
vector<int> tempID;
for (int iVS = 0; iVS < visibleStrucrtureID.size(); iVS++)
{
if (temp[iVS])
{
tempID.push_back(visibleStrucrtureID[iVS]);
}
}
visibleStrucrtureID = tempID;
}
void ExcludePointHighReprojectionError_mem(vector<Feature> &vFeature, vector<CvMat *> &cP, vector<int> vUsedFrame, vector<int> &visibleStrucrtureID, CvMat *X_tot)
{
vector<bool> temp;
temp.resize(visibleStrucrtureID.size(), true);
CvMat *X = cvCreateMat(4, 1, CV_32FC1);
CvMat *x = cvCreateMat(3, 1, CV_32FC1);
for (int iP = 0; iP < cP.size(); iP++)
{
for (int iVS = 0; iVS < visibleStrucrtureID.size(); iVS++)
{
vector<int>:: const_iterator it = find(vFeature[visibleStrucrtureID[iVS]].vFrame.begin(), vFeature[visibleStrucrtureID[iVS]].vFrame.end(), vUsedFrame[iP]);
if (it != vFeature[visibleStrucrtureID[iVS]].vFrame.end())
{
int idx = (int) (it - vFeature[visibleStrucrtureID[iVS]].vFrame.begin());
cvSetReal2D(X, 0, 0, cvGetReal2D(X_tot, visibleStrucrtureID[iVS], 0));
cvSetReal2D(X, 1, 0, cvGetReal2D(X_tot, visibleStrucrtureID[iVS], 1));
cvSetReal2D(X, 2, 0, cvGetReal2D(X_tot, visibleStrucrtureID[iVS], 2));
cvSetReal2D(X, 3, 0, 1);
cvMatMul(cP[iP], X, x);
double u0 = vFeature[visibleStrucrtureID[iVS]].vx[idx];
double v0 = vFeature[visibleStrucrtureID[iVS]].vy[idx];
double u1 = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0);
double v1 = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0);
if (sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)) > 5)
{
cout << visibleStrucrtureID[iVS] << "th 3D point erased " << sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)) << endl;
if(temp[iVS])
temp[iVS] = false;
}
}
}
}
cvReleaseMat(&X);
cvReleaseMat(&x);
vector<int> tempID;
for (int iVS = 0; iVS < visibleStrucrtureID.size(); iVS++)
{
if (temp[iVS])
{
tempID.push_back(visibleStrucrtureID[iVS]);
}
}
visibleStrucrtureID = tempID;
}
int ExcludePointHighReprojectionError_mem_fast(vector<Feature> &vFeature, vector<CvMat *> &cP, vector<int> vUsedFrame, CvMat *X_tot)
{
CvMat *X = cvCreateMat(4, 1, CV_32FC1);
CvMat *x = cvCreateMat(3, 1, CV_32FC1);
int count1=0, count2=0;
for (int iFeature = 0; iFeature < vFeature.size(); iFeature++)
{
if (vFeature[iFeature].isRegistered)
{
count1++;
int nProj = 0;
for (int iP = 0; iP < cP.size(); iP++)
{
vector<int>:: const_iterator it = find(vFeature[iFeature].vFrame.begin(), vFeature[iFeature].vFrame.end(), vUsedFrame[iP]);
if (it != vFeature[iFeature].vFrame.end())
{
nProj++;
}
}
if (nProj == 0)
continue;
for (int iP = 0; iP < cP.size(); iP++)
{
vector<int>:: const_iterator it = find(vFeature[iFeature].vFrame.begin(), vFeature[iFeature].vFrame.end(), vUsedFrame[iP]);
if (it != vFeature[iFeature].vFrame.end())
{
int idx = (int) (it - vFeature[iFeature].vFrame.begin());
cvSetReal2D(X, 0, 0, cvGetReal2D(X_tot, iFeature, 0));
cvSetReal2D(X, 1, 0, cvGetReal2D(X_tot, iFeature, 1));
cvSetReal2D(X, 2, 0, cvGetReal2D(X_tot, iFeature, 2));
cvSetReal2D(X, 3, 0, 1);
cvMatMul(cP[iP], X, x);
//PrintMat(X);
//PrintMat(cP[iP]);
//PrintMat(x);
double u0 = vFeature[iFeature].vx[idx];
double v0 = vFeature[iFeature].vy[idx];
double u1 = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0);
double v1 = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0);
double dist = sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1));
//cout << dist << endl;
if (dist > 3)
{
vFeature[iFeature].vFrame.erase(vFeature[iFeature].vFrame.begin()+idx);
vFeature[iFeature].vx.erase(vFeature[iFeature].vx.begin()+idx);
vFeature[iFeature].vy.erase(vFeature[iFeature].vy.begin()+idx);
vFeature[iFeature].vx_dis.erase(vFeature[iFeature].vx_dis.begin()+idx);
vFeature[iFeature].vy_dis.erase(vFeature[iFeature].vy_dis.begin()+idx);
vFeature[iFeature].vCamera.erase(vFeature[iFeature].vCamera.begin()+idx);
nProj--;
if (nProj < 2)
{
vFeature[iFeature].isRegistered = false;
count2++;
break;
}
}
}
}
}
}
cout << count2 << " points are deleted." << endl;
cvReleaseMat(&X);
cvReleaseMat(&x);
return count1;
}
int ExcludePointHighReprojectionError_mem_fast_Distortion(vector<Feature> &vFeature, vector<CvMat *> &cP, vector<int> vUsedFrame, CvMat *X_tot, double omega, CvMat *K)
{
CvMat *X = cvCreateMat(4, 1, CV_32FC1);
CvMat *x = cvCreateMat(3, 1, CV_32FC1);
int count1=0, count2=0;
for (int iFeature = 0; iFeature < vFeature.size(); iFeature++)
{
if (vFeature[iFeature].isRegistered)
{
count1++;
int nProj = 0;
for (int iP = 0; iP < cP.size(); iP++)
{
vector<int>:: const_iterator it = find(vFeature[iFeature].vFrame.begin(), vFeature[iFeature].vFrame.end(), vUsedFrame[iP]);
if (it != vFeature[iFeature].vFrame.end())
{
nProj++;
}
}
if (nProj == 0)
continue;
for (int iP = 0; iP < cP.size(); iP++)
{
vector<int>:: const_iterator it = find(vFeature[iFeature].vFrame.begin(), vFeature[iFeature].vFrame.end(), vUsedFrame[iP]);
if (it != vFeature[iFeature].vFrame.end())
{
int idx = (int) (it - vFeature[iFeature].vFrame.begin());
cvSetReal2D(X, 0, 0, cvGetReal2D(X_tot, iFeature, 0));
cvSetReal2D(X, 1, 0, cvGetReal2D(X_tot, iFeature, 1));
cvSetReal2D(X, 2, 0, cvGetReal2D(X_tot, iFeature, 2));
cvSetReal2D(X, 3, 0, 1);
cvMatMul(cP[iP], X, x);
double u = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0);
double v = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0);
double tan_omega_half_2 = tan(omega/2)*2;
double K11 = cvGetReal2D(K, 0, 0);
double K22 = cvGetReal2D(K, 1, 1);
double K13 = cvGetReal2D(K, 0, 2);
double K23 = cvGetReal2D(K, 1, 2);
double u_n = u/K11 - K13/K11;
double v_n = v/K22 - K23/K22;
double r_u = sqrt(u_n*u_n+v_n*v_n);
double r_d = 1/omega*atan(r_u*tan_omega_half_2);
double u_d_n = r_d/r_u * u_n;
double v_d_n = r_d/r_u * v_n;
double u1 = u_d_n*K11 + K13;
double v1 = v_d_n*K22 + K23;
double u0 = vFeature[iFeature].vx_dis[idx];
double v0 = vFeature[iFeature].vy_dis[idx];
double dist = sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1));
//cout << dist << endl;
if (dist > 3)
{
vFeature[iFeature].vFrame.erase(vFeature[iFeature].vFrame.begin()+idx);
vFeature[iFeature].vx.erase(vFeature[iFeature].vx.begin()+idx);
vFeature[iFeature].vy.erase(vFeature[iFeature].vy.begin()+idx);
vFeature[iFeature].vx_dis.erase(vFeature[iFeature].vx_dis.begin()+idx);
vFeature[iFeature].vy_dis.erase(vFeature[iFeature].vy_dis.begin()+idx);
vFeature[iFeature].vCamera.erase(vFeature[iFeature].vCamera.begin()+idx);
nProj--;
if (nProj < 2)
{
vFeature[iFeature].isRegistered = false;
count2++;
break;
}
}
}
}
}
}
cout << count2 << " points are deleted." << endl;
cvReleaseMat(&X);
cvReleaseMat(&x);
return count1;
}
int ExcludePointHighReprojectionError_mem_fast_Distortion_AD(vector<Feature> &vFeature, vector<CvMat *> &cP, vector<int> vUsedFrame, CvMat *X_tot, double omega, CvMat *K, vector<vector<int> > &vvPointIndex)
{
CvMat *X = cvCreateMat(4, 1, CV_32FC1);
CvMat *x = cvCreateMat(3, 1, CV_32FC1);
int count1=0, count2=0;
for (int iFeature = 0; iFeature < vFeature.size(); iFeature++)
{
if (vFeature[iFeature].isRegistered)
{
count1++;
int nProj = 0;
for (int iP = 0; iP < cP.size(); iP++)
{
vector<int>:: const_iterator it = find(vFeature[iFeature].vFrame.begin(), vFeature[iFeature].vFrame.end(), vUsedFrame[iP]);
if (it != vFeature[iFeature].vFrame.end())
{
nProj++;
}
}
if (nProj == 0)
continue;
for (int iP = 0; iP < cP.size(); iP++)
{
vector<int>:: const_iterator it = find(vFeature[iFeature].vFrame.begin(), vFeature[iFeature].vFrame.end(), vUsedFrame[iP]);
if (it != vFeature[iFeature].vFrame.end())
{
int idx = (int) (it - vFeature[iFeature].vFrame.begin());
cvSetReal2D(X, 0, 0, cvGetReal2D(X_tot, iFeature, 0));
cvSetReal2D(X, 1, 0, cvGetReal2D(X_tot, iFeature, 1));
cvSetReal2D(X, 2, 0, cvGetReal2D(X_tot, iFeature, 2));
cvSetReal2D(X, 3, 0, 1);
cvMatMul(cP[iP], X, x);
double u = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0);
double v = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0);
double tan_omega_half_2 = tan(omega/2)*2;
double K11 = cvGetReal2D(K, 0, 0);
double K22 = cvGetReal2D(K, 1, 1);
double K13 = cvGetReal2D(K, 0, 2);
double K23 = cvGetReal2D(K, 1, 2);
double u_n = u/K11 - K13/K11;
double v_n = v/K22 - K23/K22;
double r_u = sqrt(u_n*u_n+v_n*v_n);
double r_d = 1/omega*atan(r_u*tan_omega_half_2);
double u_d_n = r_d/r_u * u_n;
double v_d_n = r_d/r_u * v_n;
double u1 = u_d_n*K11 + K13;
double v1 = v_d_n*K22 + K23;
double u0 = vFeature[iFeature].vx_dis[idx];
double v0 = vFeature[iFeature].vy_dis[idx];
double dist = sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1));
//cout << dist << endl;
if (dist > 3)
{
vector<int>::const_iterator it = find(vvPointIndex[iP].begin(), vvPointIndex[iP].end(), vFeature[iFeature].id);
//if (it != vvPointIndex[iP].end())
{
int idx_point = (int) (it - vvPointIndex[iP].begin());
vvPointIndex[iP].erase(vvPointIndex[iP].begin()+idx_point);
}
vFeature[iFeature].vFrame.erase(vFeature[iFeature].vFrame.begin()+idx);
vFeature[iFeature].vx.erase(vFeature[iFeature].vx.begin()+idx);
vFeature[iFeature].vy.erase(vFeature[iFeature].vy.begin()+idx);
vFeature[iFeature].vx_dis.erase(vFeature[iFeature].vx_dis.begin()+idx);
vFeature[iFeature].vy_dis.erase(vFeature[iFeature].vy_dis.begin()+idx);
vFeature[iFeature].vCamera.erase(vFeature[iFeature].vCamera.begin()+idx);
nProj--;
if (nProj < 2)
{
vFeature[iFeature].isRegistered = false;
count2++;
break;
}
}
}
}
}
}
cout << count2 << " points are deleted." << endl;
cvReleaseMat(&X);
cvReleaseMat(&x);
return count1;
}
int ExcludePointHighReprojectionError_mem_fast_AD(vector<Feature> &vFeature, vector<CvMat *> &cP, vector<int> vUsedFrame, CvMat *X_tot, CvMat *K, vector<vector<int> > &vvPointIndex)
{
CvMat *X = cvCreateMat(4, 1, CV_32FC1);
CvMat *x = cvCreateMat(3, 1, CV_32FC1);
int count1=0, count2=0;
for (int iFeature = 0; iFeature < vFeature.size(); iFeature++)
{
if (vFeature[iFeature].isRegistered)
{
count1++;
int nProj = 0;
for (int iP = 0; iP < cP.size(); iP++)
{
vector<int>:: const_iterator it = find(vFeature[iFeature].vFrame.begin(), vFeature[iFeature].vFrame.end(), vUsedFrame[iP]);
if (it != vFeature[iFeature].vFrame.end())
{
nProj++;
}
}
if (nProj == 0)
continue;
for (int iP = 0; iP < cP.size(); iP++)
{
vector<int>:: const_iterator it = find(vFeature[iFeature].vFrame.begin(), vFeature[iFeature].vFrame.end(), vUsedFrame[iP]);
if (it != vFeature[iFeature].vFrame.end())
{
int idx = (int) (it - vFeature[iFeature].vFrame.begin());
cvSetReal2D(X, 0, 0, cvGetReal2D(X_tot, iFeature, 0));
cvSetReal2D(X, 1, 0, cvGetReal2D(X_tot, iFeature, 1));
cvSetReal2D(X, 2, 0, cvGetReal2D(X_tot, iFeature, 2));
cvSetReal2D(X, 3, 0, 1);
cvMatMul(cP[iP], X, x);
double u1 = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0);
double v1 = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0);
//double tan_omega_half_2 = tan(omega/2)*2;
//double K11 = cvGetReal2D(K, 0, 0);
//double K22 = cvGetReal2D(K, 1, 1);
//double K13 = cvGetReal2D(K, 0, 2);
//double K23 = cvGetReal2D(K, 1, 2);
//double u_n = u/K11 - K13/K11;
//double v_n = v/K22 - K23/K22;
//double r_u = sqrt(u_n*u_n+v_n*v_n);
//double r_d = 1/omega*atan(r_u*tan_omega_half_2);
//double u_d_n = r_d/r_u * u_n;
//double v_d_n = r_d/r_u * v_n;
//double u1 = u_d_n*K11 + K13;
//double v1 = v_d_n*K22 + K23;
double u0 = vFeature[iFeature].vx_dis[idx];
double v0 = vFeature[iFeature].vy_dis[idx];
double dist = sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1));
//cout << dist << endl;
if (dist > 3)
{
vector<int>::const_iterator it = find(vvPointIndex[iP].begin(), vvPointIndex[iP].end(), vFeature[iFeature].id);
if (it != vvPointIndex[iP].end())
{
int idx_point = (int) (it - vvPointIndex[iP].begin());
vvPointIndex[iP].erase(vvPointIndex[iP].begin()+idx_point);
}
vFeature[iFeature].vFrame.erase(vFeature[iFeature].vFrame.begin()+idx);
vFeature[iFeature].vx.erase(vFeature[iFeature].vx.begin()+idx);
vFeature[iFeature].vy.erase(vFeature[iFeature].vy.begin()+idx);
vFeature[iFeature].vx_dis.erase(vFeature[iFeature].vx_dis.begin()+idx);
vFeature[iFeature].vy_dis.erase(vFeature[iFeature].vy_dis.begin()+idx);
vFeature[iFeature].vCamera.erase(vFeature[iFeature].vCamera.begin()+idx);
nProj--;
if (nProj < 2)
{
vFeature[iFeature].isRegistered = false;
count2++;
break;
}
}
}
}
}
}
cout << count2 << " points are deleted." << endl;
cvReleaseMat(&X);
cvReleaseMat(&x);
return count1;
}
int ExcludePointHighReprojectionError_mem_fast_Distortion_ObstacleDetection(vector<Feature> &vFeature, vector<CvMat *> &cP, vector<int> vUsedFrame, CvMat *X_tot, double omega, double princ_x1, double princ_y1, CvMat *K)
{
CvMat *X = cvCreateMat(4, 1, CV_32FC1);
CvMat *x = cvCreateMat(3, 1, CV_32FC1);
int count1=0, count2=0;
for (int iFeature = 0; iFeature < vFeature.size(); iFeature++)
{
if (vFeature[iFeature].isRegistered)
{
count1++;
int nProj = 0;
for (int iP = 0; iP < cP.size(); iP++)
{
vector<int>:: const_iterator it = find(vFeature[iFeature].vFrame.begin(), vFeature[iFeature].vFrame.end(), vUsedFrame[iP]);
if (it != vFeature[iFeature].vFrame.end())
{
nProj++;
}
}
if (nProj == 0)
continue;
for (int iP = 0; iP < cP.size(); iP++)
{
vector<int>:: const_iterator it = find(vFeature[iFeature].vFrame.begin(), vFeature[iFeature].vFrame.end(), vUsedFrame[iP]);
if (it != vFeature[iFeature].vFrame.end())
{
int idx = (int) (it - vFeature[iFeature].vFrame.begin());
cvSetReal2D(X, 0, 0, cvGetReal2D(X_tot, iFeature, 0));
cvSetReal2D(X, 1, 0, cvGetReal2D(X_tot, iFeature, 1));
cvSetReal2D(X, 2, 0, cvGetReal2D(X_tot, iFeature, 2));
cvSetReal2D(X, 3, 0, 1);
cvMatMul(cP[iP], X, x);
double u = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0);
double v = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0);
double tan_omega_half_2 = tan(omega/2)*2;
//double K11 = cvGetReal2D(K, 0, 0);
//double K22 = cvGetReal2D(K, 1, 1);
//double K13 = cvGetReal2D(K, 0, 2);
//double K23 = cvGetReal2D(K, 1, 2);
//double u_n = u/K11 - K13/K11;
//double v_n = v/K22 - K23/K22;
double u_n = u - princ_x1;
double v_n = v - princ_y1;
double r_u = sqrt(u_n*u_n+v_n*v_n);
double r_d = 1/omega*atan(r_u*tan_omega_half_2);
double u_d_n = r_d/r_u * u_n;
double v_d_n = r_d/r_u * v_n;
double u1 = u_d_n + princ_x1;
double v1 = v_d_n + princ_y1;
double u0 = vFeature[iFeature].vx_dis[idx];
double v0 = vFeature[iFeature].vy_dis[idx];
double dist = sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1));
//cout << dist << endl;
if (dist > 3)
{
vFeature[iFeature].vFrame.erase(vFeature[iFeature].vFrame.begin()+idx);
vFeature[iFeature].vx.erase(vFeature[iFeature].vx.begin()+idx);
vFeature[iFeature].vy.erase(vFeature[iFeature].vy.begin()+idx);
vFeature[iFeature].vx_dis.erase(vFeature[iFeature].vx_dis.begin()+idx);
vFeature[iFeature].vy_dis.erase(vFeature[iFeature].vy_dis.begin()+idx);
vFeature[iFeature].vCamera.erase(vFeature[iFeature].vCamera.begin()+idx);
nProj--;
if (nProj < 2)
{
vFeature[iFeature].isRegistered = false;
count2++;
break;
}
}
}
}
}
}
cout << count2 << " points are deleted." << endl;
cvReleaseMat(&X);
cvReleaseMat(&x);
return count1;
}
bool ExcludePointHighReprojectionError_AddingFrame(vector<Feature> vFeature, vector<CvMat *> cP, vector<int> vUsedFrame
, vector<int> &visibleStrucrtureID, CvMat &X_tot
, vector<int> &visibleStrucrtureID_new, CvMat &X_tot_new)
{
visibleStrucrtureID_new.clear();
vector<double> vx, vy, vz;
for (int iVS = 0; iVS < visibleStrucrtureID.size(); iVS++)
{
bool isIn = true;
for (int iP = 0; iP < cP.size(); iP++)
{
vector<int>:: const_iterator it = find(vFeature[visibleStrucrtureID[iVS]].vFrame.begin(), vFeature[visibleStrucrtureID[iVS]].vFrame.end(), vUsedFrame[iP]);
if (it != vFeature[visibleStrucrtureID[iVS]].vFrame.end())
{
int idx = (int) (it - vFeature[visibleStrucrtureID[iVS]].vFrame.begin());
CvMat *X = cvCreateMat(4, 1, CV_32FC1);
CvMat *x = cvCreateMat(3, 1, CV_32FC1);
cvSetReal2D(X, 0, 0, cvGetReal2D(&X_tot, iVS, 0));
cvSetReal2D(X, 1, 0, cvGetReal2D(&X_tot, iVS, 1));
cvSetReal2D(X, 2, 0, cvGetReal2D(&X_tot, iVS, 2));
cvSetReal2D(X, 3, 0, 1);
cvMatMul(cP[iP], X, x);
double u0 = vFeature[visibleStrucrtureID[iVS]].vx[idx];
double v0 = vFeature[visibleStrucrtureID[iVS]].vy[idx];
double u1 = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0);
double v1 = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0);
if (sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)) > 5)
{
//cout << visibleStrucrtureID[iVS] << "th 3D point erased " << sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)) << endl;
isIn = false;
break;
}
cvReleaseMat(&X);
cvReleaseMat(&x);
}
}
if (isIn)
{
visibleStrucrtureID_new.push_back(visibleStrucrtureID[iVS]);
vx.push_back(cvGetReal2D(&X_tot, iVS, 0));
vy.push_back(cvGetReal2D(&X_tot, iVS, 1));
vz.push_back(cvGetReal2D(&X_tot, iVS, 2));
}
}
if (visibleStrucrtureID_new.size() == 0)
return false;
X_tot_new = *cvCreateMat(visibleStrucrtureID_new.size(), 3, CV_32FC1);
for (int ivx = 0; ivx < visibleStrucrtureID_new.size(); ivx++)
{
cvSetReal2D(&X_tot_new, ivx, 0, vx[ivx]);
cvSetReal2D(&X_tot_new, ivx, 1, vy[ivx]);
cvSetReal2D(&X_tot_new, ivx, 2, vz[ivx]);
}
return true;
}
bool ExcludePointHighReprojectionError_AddingFrame_mem(vector<Feature> &vFeature, vector<CvMat *> cP, vector<int> vUsedFrame
, vector<int> &visibleStrucrtureID, CvMat *X_tot
, vector<int> &visibleStrucrtureID_new, vector<vector<double> > &X_tot_new)
{
visibleStrucrtureID_new.clear();
vector<double> vx, vy, vz;
for (int iVS = 0; iVS < visibleStrucrtureID.size(); iVS++)
{
bool isIn = true;
for (int iP = 0; iP < cP.size(); iP++)
{
vector<int>:: const_iterator it = find(vFeature[visibleStrucrtureID[iVS]].vFrame.begin(), vFeature[visibleStrucrtureID[iVS]].vFrame.end(), vUsedFrame[iP]);
if (it != vFeature[visibleStrucrtureID[iVS]].vFrame.end())
{
int idx = (int) (it - vFeature[visibleStrucrtureID[iVS]].vFrame.begin());
CvMat *X = cvCreateMat(4, 1, CV_32FC1);
CvMat *x = cvCreateMat(3, 1, CV_32FC1);
cvSetReal2D(X, 0, 0, cvGetReal2D(X_tot, iVS, 0));
cvSetReal2D(X, 1, 0, cvGetReal2D(X_tot, iVS, 1));
cvSetReal2D(X, 2, 0, cvGetReal2D(X_tot, iVS, 2));
cvSetReal2D(X, 3, 0, 1);
cvMatMul(cP[iP], X, x);
double u0 = vFeature[visibleStrucrtureID[iVS]].vx[idx];
double v0 = vFeature[visibleStrucrtureID[iVS]].vy[idx];
double u1 = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0);
double v1 = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0);
if (sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)) > 5)
{
//cout << visibleStrucrtureID[iVS] << "th 3D point erased " << sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)) << endl;
isIn = false;
cvReleaseMat(&X);
cvReleaseMat(&x);
break;
}
cvReleaseMat(&X);
cvReleaseMat(&x);
}
}
if (isIn)
{
visibleStrucrtureID_new.push_back(visibleStrucrtureID[iVS]);
vx.push_back(cvGetReal2D(X_tot, iVS, 0));
vy.push_back(cvGetReal2D(X_tot, iVS, 1));
vz.push_back(cvGetReal2D(X_tot, iVS, 2));
}
}
if (visibleStrucrtureID_new.size() == 0)
return false;
for (int ivx = 0; ivx < visibleStrucrtureID_new.size(); ivx++)
{
vector<double> X_tot_new_vec;
X_tot_new_vec.push_back(vx[ivx]);
X_tot_new_vec.push_back(vy[ivx]);
X_tot_new_vec.push_back(vz[ivx]);
X_tot_new.push_back(X_tot_new_vec);
}
return true;
}
bool ExcludePointHighReprojectionError_AddingFrame_mem_fast(vector<Feature> &vFeature, vector<CvMat *> &cP, vector<int> &vUsedFrame
, vector<int> &visibleStrucrtureID, CvMat *X_tot
, vector<int> &visibleStrucrtureID_new, vector<vector<double> > &X_tot_new)
{
visibleStrucrtureID_new.clear();
CvMat *X = cvCreateMat(4, 1, CV_32FC1);
CvMat *x = cvCreateMat(3, 1, CV_32FC1);
for (int iVS = 0; iVS < visibleStrucrtureID.size(); iVS++)
{
bool isIn = true;
for (int iP = 0; iP < cP.size(); iP++)
{
vector<int>:: const_iterator it = find(vFeature[visibleStrucrtureID[iVS]].vFrame.begin(), vFeature[visibleStrucrtureID[iVS]].vFrame.end(), vUsedFrame[iP]);
if (it != vFeature[visibleStrucrtureID[iVS]].vFrame.end())
{
int idx = (int) (it - vFeature[visibleStrucrtureID[iVS]].vFrame.begin());
cvSetReal2D(X, 0, 0, cvGetReal2D(X_tot, iVS, 0));
cvSetReal2D(X, 1, 0, cvGetReal2D(X_tot, iVS, 1));
cvSetReal2D(X, 2, 0, cvGetReal2D(X_tot, iVS, 2));
cvSetReal2D(X, 3, 0, 1);
cvMatMul(cP[iP], X, x);
double u0 = vFeature[visibleStrucrtureID[iVS]].vx[idx];
double v0 = vFeature[visibleStrucrtureID[iVS]].vy[idx];
double u1 = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0);
double v1 = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0);
if (sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)) > 5)
{
//cout << visibleStrucrtureID[iVS] << "th 3D point erased " << sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)) << endl;
isIn = false;
break;
}
}
}
if (isIn)
{
visibleStrucrtureID_new.push_back(visibleStrucrtureID[iVS]);
vector<double> X_tot_new_vec;
X_tot_new_vec.push_back(cvGetReal2D(X_tot, iVS, 0));
X_tot_new_vec.push_back(cvGetReal2D(X_tot, iVS, 1));
X_tot_new_vec.push_back(cvGetReal2D(X_tot, iVS, 2));
X_tot_new.push_back(X_tot_new_vec);
}
}
cvReleaseMat(&X);
cvReleaseMat(&x);
if (visibleStrucrtureID_new.size() == 0)
return false;
return true;
}
bool ExcludePointHighReprojectionError_AddingFrame_mem_fast_Distortion(vector<Feature> &vFeature, vector<CvMat *> &cP, vector<int> &vUsedFrame
, vector<int> &visibleStrucrtureID, CvMat *X_tot
, vector<int> &visibleStrucrtureID_new, vector<vector<double> > &X_tot_new,
double omega, CvMat *K)
{
visibleStrucrtureID_new.clear();
CvMat *X = cvCreateMat(4, 1, CV_32FC1);
CvMat *x = cvCreateMat(3, 1, CV_32FC1);
for (int iVS = 0; iVS < visibleStrucrtureID.size(); iVS++)
{
bool isIn = true;
for (int iP = 0; iP < cP.size(); iP++)
{
vector<int>:: const_iterator it = find(vFeature[visibleStrucrtureID[iVS]].vFrame.begin(), vFeature[visibleStrucrtureID[iVS]].vFrame.end(), vUsedFrame[iP]);
if (it != vFeature[visibleStrucrtureID[iVS]].vFrame.end())
{
int idx = (int) (it - vFeature[visibleStrucrtureID[iVS]].vFrame.begin());
cvSetReal2D(X, 0, 0, cvGetReal2D(X_tot, iVS, 0));
cvSetReal2D(X, 1, 0, cvGetReal2D(X_tot, iVS, 1));
cvSetReal2D(X, 2, 0, cvGetReal2D(X_tot, iVS, 2));
cvSetReal2D(X, 3, 0, 1);
cvMatMul(cP[iP], X, x);
double u = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0);
double v = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0);
double tan_omega_half_2 = tan(omega/2)*2;
double K11 = cvGetReal2D(K, 0, 0);
double K22 = cvGetReal2D(K, 1, 1);
double K13 = cvGetReal2D(K, 0, 2);
double K23 = cvGetReal2D(K, 1, 2);
double u_n = u/K11 - K13/K11;
double v_n = v/K22 - K23/K22;
double r_u = sqrt(u_n*u_n+v_n*v_n);
double r_d = 1/omega*atan(r_u*tan_omega_half_2);
double u_d_n = r_d/r_u * u_n;
double v_d_n = r_d/r_u * v_n;
double u1 = u_d_n*K11 + K13;
double v1 = v_d_n*K22 + K23;
double u0 = vFeature[visibleStrucrtureID[iVS]].vx_dis[idx];
double v0 = vFeature[visibleStrucrtureID[iVS]].vy_dis[idx];
//double u1 = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0);
//double v1 = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0);
if (sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)) > 3)
{
//cout << visibleStrucrtureID[iVS] << "th 3D point erased " << sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)) << endl;
isIn = false;
break;
}
}
}
if (isIn)
{
visibleStrucrtureID_new.push_back(visibleStrucrtureID[iVS]);
vector<double> X_tot_new_vec;
X_tot_new_vec.push_back(cvGetReal2D(X_tot, iVS, 0));
X_tot_new_vec.push_back(cvGetReal2D(X_tot, iVS, 1));
X_tot_new_vec.push_back(cvGetReal2D(X_tot, iVS, 2));
X_tot_new.push_back(X_tot_new_vec);
}
}
cvReleaseMat(&X);
cvReleaseMat(&x);
if (visibleStrucrtureID_new.size() == 0)
return false;
return true;
}
bool ExcludePointHighReprojectionError_AddingFrame_mem_fast_Distortion_ObstacleDetection(vector<Feature> &vFeature, vector<CvMat *> &cP, vector<int> &vUsedFrame
, vector<int> &visibleStrucrtureID, CvMat *X_tot
, vector<int> &visibleStrucrtureID_new, vector<vector<double> > &X_tot_new,
double omega, double princ_x1, double princ_y1, CvMat *K)
{
visibleStrucrtureID_new.clear();
CvMat *X = cvCreateMat(4, 1, CV_32FC1);
CvMat *x = cvCreateMat(3, 1, CV_32FC1);
for (int iVS = 0; iVS < visibleStrucrtureID.size(); iVS++)
{
bool isIn = true;
for (int iP = 0; iP < cP.size(); iP++)
{
vector<int>:: const_iterator it = find(vFeature[visibleStrucrtureID[iVS]].vFrame.begin(), vFeature[visibleStrucrtureID[iVS]].vFrame.end(), vUsedFrame[iP]);
if (it != vFeature[visibleStrucrtureID[iVS]].vFrame.end())
{
int idx = (int) (it - vFeature[visibleStrucrtureID[iVS]].vFrame.begin());
cvSetReal2D(X, 0, 0, cvGetReal2D(X_tot, iVS, 0));
cvSetReal2D(X, 1, 0, cvGetReal2D(X_tot, iVS, 1));
cvSetReal2D(X, 2, 0, cvGetReal2D(X_tot, iVS, 2));
cvSetReal2D(X, 3, 0, 1);
cvMatMul(cP[iP], X, x);
double u = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0);
double v = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0);
double tan_omega_half_2 = tan(omega/2)*2;
//double K11 = cvGetReal2D(K, 0, 0);
//double K22 = cvGetReal2D(K, 1, 1);
//double K13 = cvGetReal2D(K, 0, 2);
//double K23 = cvGetReal2D(K, 1, 2);
//double u_n = u/K11 - K13/K11;
//double v_n = v/K22 - K23/K22;
double u_n = u - princ_x1;
double v_n = v - princ_y1;
double r_u = sqrt(u_n*u_n+v_n*v_n);
double r_d = 1/omega*atan(r_u*tan_omega_half_2);
double u_d_n = r_d/r_u * u_n;
double v_d_n = r_d/r_u * v_n;
double u1 = u_d_n + princ_x1;
double v1 = v_d_n + princ_y1;
double u0 = vFeature[visibleStrucrtureID[iVS]].vx_dis[idx];
double v0 = vFeature[visibleStrucrtureID[iVS]].vy_dis[idx];
//double u1 = cvGetReal2D(x, 0, 0)/cvGetReal2D(x, 2, 0);
//double v1 = cvGetReal2D(x, 1, 0)/cvGetReal2D(x, 2, 0);
if (sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)) > 3)
{
//cout << visibleStrucrtureID[iVS] << "th 3D point erased " << sqrt((u0-u1)*(u0-u1)+(v0-v1)*(v0-v1)) << endl;
isIn = false;
break;
}
}
}
if (isIn)
{
visibleStrucrtureID_new.push_back(visibleStrucrtureID[iVS]);
vector<double> X_tot_new_vec;
X_tot_new_vec.push_back(cvGetReal2D(X_tot, iVS, 0));
X_tot_new_vec.push_back(cvGetReal2D(X_tot, iVS, 1));
X_tot_new_vec.push_back(cvGetReal2D(X_tot, iVS, 2));
X_tot_new.push_back(X_tot_new_vec);
}
}
cvReleaseMat(&X);
cvReleaseMat(&x);
if (visibleStrucrtureID_new.size() == 0)
return false;
return true;
}
void OrientationRefinement(CvMat *R_1, CvMat *R_F, vector<int> vFrame1, vector<int> vFrame2, vector<CvMat*> &vM, vector<CvMat*> &vm, vector<CvMat *> &vx1, vector<CvMat *> &vx2)
{
//PrintAlgorithm("Orientation Refinement");
//vector<double> cameraParameter, measurement;
//AdditionalData adata;// focal_x focal_y princ_x princ_y
////double intrinsic[4] = {cvGetReal2D(K, 0, 0), cvGetReal2D(K, 1, 1), cvGetReal2D(K, 0, 2), cvGetReal2D(K, 1, 2)};
////adata.vIntrinsic.push_back(intrinsic);
//adata.nFrames = vFrame1.size();
//adata.vx1 = &vx1;
//adata.vx2 = &vx2;
//for (int iFrame = 0; iFrame < vFrame1.size(); iFrame++)
//{
// CvMat *q = cvCreateMat(4,1,CV_32FC1);
// Rotation2Quaternion(vM[iFrame], q);
// cameraParameter.push_back(cvGetReal2D(q, 0, 0));
// cameraParameter.push_back(cvGetReal2D(q, 1, 0));
// cameraParameter.push_back(cvGetReal2D(q, 2, 0));
// cameraParameter.push_back(cvGetReal2D(q, 3, 0));
// cameraParameter.push_back(cvGetReal2D(vm[iFrame], 0, 0));
// cameraParameter.push_back(cvGetReal2D(vm[iFrame], 1, 0));
// cameraParameter.push_back(cvGetReal2D(vm[iFrame], 2, 0));
// cvReleaseMat(&q);
//}
//CvMat *R_r = cvCreateMat(3,3,CV_32FC1);
//CvMat *R_1_inv = cvCreateMat(3,3,CV_32FC1);
//cvInvert(R_1, R_1_inv);
//cvMatMul(R_F, R_1_inv, R_r);
//CvMat *q_r = cvCreateMat(4,1,CV_32FC1);
//Rotation2Quaternion(R_r, q_r);
//measurement.push_back(cvGetReal2D(q_r, 0, 0));
//measurement.push_back(cvGetReal2D(q_r, 1, 0));
//measurement.push_back(cvGetReal2D(q_r, 2, 0));
//measurement.push_back(cvGetReal2D(q_r, 3, 0));
//for (int i = 0; i < vx1.size(); i++)
//{
// if (vx1[i]->rows == 1)
// continue;
// //for (int j = 0; j < vx1[i]->rows; j++)
// for (int j = 0; j < 10; j++)
// measurement.push_back(0);
//}
//cvReleaseMat(&R_r);
//cvReleaseMat(&R_1_inv);
//cvReleaseMat(&q_r);
//double *dmeasurement = (double *) malloc(measurement.size() * sizeof(double));
//double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double));
//for (int i = 0; i < cameraParameter.size(); i++)
// dCameraParameter[i] = cameraParameter[i];
//for (int i = 0; i < measurement.size(); i++)
// dmeasurement[i] = measurement[i];
//double opt[5];
//opt[0] = 1e-3;
//opt[1] = 1e-12;
//opt[2] = 1e-12;
//opt[3] = 1e-12;
//opt[4] = 0;
//double info[12];
//double *work = (double*)malloc((LM_DIF_WORKSZ(cameraParameter.size(), measurement.size())+cameraParameter.size()*cameraParameter.size())*sizeof(double));
//if(!work)
// fprintf(stderr, "memory allocation request failed in main()\n");
//int ret = dlevmar_dif(ObjectiveOrientationRefinement, dCameraParameter, dmeasurement, cameraParameter.size(), measurement.size(),
// 1e+2, opt, info, work, NULL, &adata);
//PrintSBAInfo(info);
//for (int iFrame = 0; iFrame < vFrame1.size(); iFrame++)
//{
// CvMat *q = cvCreateMat(4,1,CV_32FC1);
// CvMat *R = cvCreateMat(3,3,CV_32FC1);
// cvSetReal2D(q, 0, 0, dCameraParameter[7*iFrame+0]);
// cvSetReal2D(q, 1, 0, dCameraParameter[7*iFrame+1]);
// cvSetReal2D(q, 2, 0, dCameraParameter[7*iFrame+2]);
// cvSetReal2D(q, 3, 0, dCameraParameter[7*iFrame+3]);
// Quaternion2Rotation(q, R);
// for (int i = 0; i < 3; i++)
// {
// for (int j = 0; j < 3; j++)
// {
// cvSetReal2D(vM[iFrame], i, j, cvGetReal2D(R, i, j));
// }
// }
// cvReleaseMat(&q);
// cvReleaseMat(&R);
// cvSetReal2D(vm[iFrame], 0, 0, dCameraParameter[7*iFrame+4]);
// cvSetReal2D(vm[iFrame], 1, 0, dCameraParameter[7*iFrame+5]);
// cvSetReal2D(vm[iFrame], 2, 0, dCameraParameter[7*iFrame+6]);
//
//}
//free(dmeasurement);
//free(dCameraParameter);
//free(work);
}
void OrientationRefinement1(CvMat *R_1, CvMat *R_F, vector<int> vFrame1, vector<int> vFrame2, vector<CvMat*> &vM, vector<CvMat*> &vm, vector<CvMat *> &vx1, vector<CvMat *> &vx2,
vector<int> vFrame1_r, vector<int> vFrame2_r, vector<CvMat*> &vM_r, vector<CvMat*> &vm_r, vector<CvMat *> &vx1_r, vector<CvMat *> &vx2_r)
{
//PrintAlgorithm("Orientation Refinement for non-consecutive frame");
//
//// focal_x focal_y princ_x princ_y
////double intrinsic[4] = {cvGetReal2D(K, 0, 0), cvGetReal2D(K, 1, 1), cvGetReal2D(K, 0, 2), cvGetReal2D(K, 1, 2)};
////adata.vIntrinsic.push_back(intrinsic);
//for (int iFrame = 0; iFrame < vFrame1_r.size(); iFrame++)
//{
// vector<double> cameraParameter, measurement;
// AdditionalData adata;
// //cout << endl << "Orientation Refinement for non-consecutive frame: " << vFrame1_r[iFrame] << " " << vFrame2_r[iFrame] << endl;
// cout << vFrame1_r[iFrame] << " ";
// cameraParameter.clear();
// measurement.clear();
// vector<double> vx1_a, vy1_a, vx2_a, vy2_a;
// for (int ix = 0; ix < vx1_r[iFrame]->rows; ix++)
// {
// vx1_a.push_back(cvGetReal2D(vx1_r[iFrame], ix, 0));
// vy1_a.push_back(cvGetReal2D(vx1_r[iFrame], ix, 1));
// vx2_a.push_back(cvGetReal2D(vx2_r[iFrame], ix, 0));
// vy2_a.push_back(cvGetReal2D(vx2_r[iFrame], ix, 1));
// measurement.push_back(0);
// }
// adata.vx1_a = &vx1_a;
// adata.vy1_a = &vy1_a;
// adata.vx2_a = &vx2_a;
// adata.vy2_a = &vy2_a;
//
// vector<int>::iterator it1 = find(vFrame1.begin(), vFrame1.end(), vFrame1_r[iFrame]);
// vector<int>::iterator it2 = find(vFrame2.begin(), vFrame2.end(), vFrame2_r[iFrame]);
// int idx1 = (int) (it1 - vFrame1.begin());
// int idx2 = (int) (it2 - vFrame2.begin());
// CvMat *R_r = cvCreateMat(3,3,CV_32FC1);
// cvSetIdentity(R_r);
// for (int iIdx = idx1; iIdx < idx2+1; iIdx++)
// {
// cvMatMul(vM[iIdx], R_r, R_r);
// }
// CvMat *q = cvCreateMat(4,1,CV_32FC1);
// Rotation2Quaternion(R_r, q);
// //Rotation2Quaternion(vM_r[iFrame], q);
// adata.qw = cvGetReal2D(q, 0, 0);
// adata.qx = cvGetReal2D(q, 1, 0);
// adata.qy = cvGetReal2D(q, 2, 0);
// adata.qz = cvGetReal2D(q, 3, 0);
// cvReleaseMat(&q);
// cameraParameter.push_back(cvGetReal2D(vm_r[iFrame], 0, 0));
// cameraParameter.push_back(cvGetReal2D(vm_r[iFrame], 1, 0));
// cameraParameter.push_back(cvGetReal2D(vm_r[iFrame], 2, 0));
//
// cvSetReal2D(vM_r[iFrame], 0, 0, cvGetReal2D(R_r, 0, 0)); cvSetReal2D(vM_r[iFrame], 0, 1, cvGetReal2D(R_r, 0, 1)); cvSetReal2D(vM_r[iFrame], 0, 2, cvGetReal2D(R_r, 0, 2));
// cvSetReal2D(vM_r[iFrame], 1, 0, cvGetReal2D(R_r, 1, 0)); cvSetReal2D(vM_r[iFrame], 1, 1, cvGetReal2D(R_r, 1, 1)); cvSetReal2D(vM_r[iFrame], 1, 2, cvGetReal2D(R_r, 1, 2));
// cvSetReal2D(vM_r[iFrame], 2, 0, cvGetReal2D(R_r, 2, 0)); cvSetReal2D(vM_r[iFrame], 2, 1, cvGetReal2D(R_r, 2, 1)); cvSetReal2D(vM_r[iFrame], 2, 2, cvGetReal2D(R_r, 2, 2));
// //for (int i = 0; i < vx1_r.size(); i++)
// //{
// // for (int j = 0; j < vx1[i]->rows; j++)
// // measurement.push_back(0);
// //}
// double *dmeasurement = (double *) malloc(measurement.size() * sizeof(double));
// double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double));
// for (int i = 0; i < cameraParameter.size(); i++)
// dCameraParameter[i] = cameraParameter[i];
// for (int i = 0; i < measurement.size(); i++)
// dmeasurement[i] = measurement[i];
// double opt[5];
// opt[0] = 1e-3;
// opt[1] = 1e-12;
// opt[2] = 1e-12;
// opt[3] = 1e-12;
// opt[4] = 0;
// double info[12];
// double *work = (double*)malloc((LM_DIF_WORKSZ(cameraParameter.size(), measurement.size())+cameraParameter.size()*cameraParameter.size())*sizeof(double));
// if(!work)
// fprintf(stderr, "memory allocation request failed in main()\n");
// int ret = dlevmar_dif(ObjectiveOrientationRefinement1, dCameraParameter, dmeasurement, cameraParameter.size(), measurement.size(),
// 1e+2, opt, info, work, NULL, &adata);
// //PrintSBAInfo(info);
// cvReleaseMat(&R_r);
// cvSetReal2D(vm_r[iFrame], 0, 0, dCameraParameter[0]);
// cvSetReal2D(vm_r[iFrame], 1, 0, dCameraParameter[1]);
// cvSetReal2D(vm_r[iFrame], 2, 0, dCameraParameter[2]);
// free(dmeasurement);
// free(dCameraParameter);
// free(work);
//}
//cout << endl;
}
//void OrientationRefinement_sba(CvMat *R_1, CvMat *R_F, vector<int> vFrame1, vector<int> vFrame2, vector<CvMat*> &vM, vector<CvMat*> &vm, vector<CvMat *> &vx1, vector<CvMat *> &vx2,
// vector<int> vFrame1_r, vector<int> vFrame2_r, vector<CvMat*> &vM_r, vector<CvMat*> &vm_r, vector<CvMat *> &vx1_r, vector<CvMat *> &vx2_r)
//{
// PrintAlgorithm("Orientation Refinement - sba");
// vector<double> cameraParameter, measurement;
// AdditionalData adata;// focal_x focal_y princ_x princ_y
// //double intrinsic[4] = {cvGetReal2D(K, 0, 0), cvGetReal2D(K, 1, 1), cvGetReal2D(K, 0, 2), cvGetReal2D(K, 1, 2)};
// //adata.vIntrinsic.push_back(intrinsic);
// //adata.vFrame1 = vFrame1;
// //adata.vFrame2 = vFrame2;
// //adata.vFrame1_r = vFrame1_r;
// //adata.vFrame2_r = vFrame2_r;
//
// //adata.vx1 = &vx1;
// //adata.vx2 = &vx2;
//
// //adata.vx1_r = &vx1_r;
// //adata.vx2_r = &vx2_r;
//
// //for (int iFrame = 0; iFrame < vFrame1.size(); iFrame++)
// //{
// // CvMat *q = cvCreateMat(4,1,CV_32FC1);
// // Rotation2Quaternion(vM[iFrame], q);
// // cameraParameter.push_back(cvGetReal2D(q, 0, 0));
// // cameraParameter.push_back(cvGetReal2D(q, 1, 0));
// // cameraParameter.push_back(cvGetReal2D(q, 2, 0));
// // cameraParameter.push_back(cvGetReal2D(q, 3, 0));
// // cvReleaseMat(&q);
//
// // cameraParameter.push_back(cvGetReal2D(vm[iFrame], 0, 0));
// // cameraParameter.push_back(cvGetReal2D(vm[iFrame], 1, 0));
// // cameraParameter.push_back(cvGetReal2D(vm[iFrame], 2, 0));
// //}
//
// //for (int iFrame = 0; iFrame < vFrame1_r.size(); iFrame++)
// //{
// // cameraParameter.push_back(cvGetReal2D(vm_r[iFrame], 0, 0));
// // cameraParameter.push_back(cvGetReal2D(vm_r[iFrame], 1, 0));
// // cameraParameter.push_back(cvGetReal2D(vm_r[iFrame], 2, 0));
// //}
//
// CvMat *R_r = cvCreateMat(3,3,CV_32FC1);
// CvMat *R_1_inv = cvCreateMat(3,3,CV_32FC1);
// cvInvert(R_1, R_1_inv);
// cvMatMul(R_F, R_1_inv, R_r);
// CvMat *q_r = cvCreateMat(4,1,CV_32FC1);
// Rotation2Quaternion(R_r, q_r);
// //measurement.push_back(cvGetReal2D(q_r, 0, 0));
// //measurement.push_back(cvGetReal2D(q_r, 1, 0));
// //measurement.push_back(cvGetReal2D(q_r, 2, 0));
// //measurement.push_back(cvGetReal2D(q_r, 3, 0));
//
// for (int i = 0; i < vx1.size(); i++)
// {
// for (int j = 0; j < vx1[i]->rows; j++)
// //for (int j = 0; j < 7; j++)
// measurement.push_back(0);
// }
//
// //for (int i = 0; i < vx1_r.size(); i++)
// //{
// // for (int j = 0; j < vx1[i]->rows; j++)
// // //for (int j = 0; j < 3; j++)
// // measurement.push_back(0);
// //}
//
// cameraParameter.push_back(cvGetReal2D(q_r, 0, 0));
// cameraParameter.push_back(cvGetReal2D(q_r, 1, 0));
// cameraParameter.push_back(cvGetReal2D(q_r, 2, 0));
// cameraParameter.push_back(cvGetReal2D(q_r, 3, 0));
//
// for (int iFrame = 0; iFrame < vFrame1.size(); iFrame++)
// {
// CvMat *q = cvCreateMat(4,1,CV_32FC1);
// Rotation2Quaternion(vM[iFrame], q);
// cameraParameter.push_back(cvGetReal2D(q, 0, 0));
// cameraParameter.push_back(cvGetReal2D(q, 1, 0));
// cameraParameter.push_back(cvGetReal2D(q, 2, 0));
// cameraParameter.push_back(cvGetReal2D(q, 3, 0));
// cvReleaseMat(&q);
//
// cameraParameter.push_back(cvGetReal2D(vm[iFrame], 0, 0));
// cameraParameter.push_back(cvGetReal2D(vm[iFrame], 1, 0));
// cameraParameter.push_back(cvGetReal2D(vm[iFrame], 2, 0));
// }
//
//
//
// cvReleaseMat(&R_r);
// cvReleaseMat(&R_1_inv);
// cvReleaseMat(&q_r);
//
// double *dmeasurement = (double *) malloc(measurement.size() * sizeof(double));
// double *dCameraParameter = (double *) malloc(cameraParameter.size() * sizeof(double));
//
// for (int i = 0; i < cameraParameter.size(); i++)
// dCameraParameter[i] = cameraParameter[i];
// for (int i = 0; i < measurement.size(); i++)
// dmeasurement[i] = measurement[i];
//
// double opt[5];
// opt[0] = 1e-3;
// opt[1] = 1e-5;
// opt[2] = 1e-5;
// opt[3] = 1e-5;
// opt[4] = 0;
// double info[12];
//
// int ret = sba_mot_levmar()
//
// double *work = (double*)malloc((LM_DIF_WORKSZ(cameraParameter.size(), measurement.size())+cameraParameter.size()*cameraParameter.size())*sizeof(double));
// if(!work)
// fprintf(stderr, "memory allocation request failed in main()\n");
//
// int ret = dlevmar_dif(ObjectiveOrientationRefinement1, dCameraParameter, dmeasurement, cameraParameter.size(), measurement.size(),
// 1e+2, opt, info, work, NULL, &adata);
//
// PrintSBAInfo(info);
// vector<double> vR11, vR12, vR13, vR21, vR22, vR23, vR31, vR32, vR33;
// for (int iFrame = 0; iFrame < vFrame1.size(); iFrame++)
// {
// CvMat *q = cvCreateMat(4,1,CV_32FC1);
// CvMat *R = cvCreateMat(3,3,CV_32FC1);
// cvSetReal2D(q, 0, 0, dCameraParameter[7*iFrame+0]);
// cvSetReal2D(q, 1, 0, dCameraParameter[7*iFrame+1]);
// cvSetReal2D(q, 2, 0, dCameraParameter[7*iFrame+2]);
// cvSetReal2D(q, 3, 0, dCameraParameter[7*iFrame+3]);
// Quaternion2Rotation(q, R);
// for (int i = 0; i < 3; i++)
// {
// for (int j = 0; j < 3; j++)
// {
// cvSetReal2D(vM[iFrame], i, j, cvGetReal2D(R, i, j));
// }
// }
//
// vR11.push_back(cvGetReal2D(R, 0, 0)); vR12.push_back(cvGetReal2D(R, 0, 1)); vR13.push_back(cvGetReal2D(R, 0, 2));
// vR21.push_back(cvGetReal2D(R, 1, 0)); vR22.push_back(cvGetReal2D(R, 1, 1)); vR23.push_back(cvGetReal2D(R, 1, 2));
// vR31.push_back(cvGetReal2D(R, 2, 0)); vR32.push_back(cvGetReal2D(R, 2, 1)); vR33.push_back(cvGetReal2D(R, 2, 2));
// cvReleaseMat(&q);
// cvReleaseMat(&R);
//
// cvSetReal2D(vm[iFrame], 0, 0, dCameraParameter[7*iFrame+4]);
// cvSetReal2D(vm[iFrame], 1, 0, dCameraParameter[7*iFrame+5]);
// cvSetReal2D(vm[iFrame], 2, 0, dCameraParameter[7*iFrame+6]);
// }
//
// for (int iFrame_r = 0; iFrame_r < vFrame1_r.size(); iFrame_r++)
// {
// double R11 = 1; double R12 = 0; double R13 = 0;
// double R21 = 0; double R22 = 1; double R23 = 0;
// double R31 = 0; double R32 = 0; double R33 = 1;
//
// for (int iFrame = vFrame1_r[iFrame_r]; iFrame < vFrame2_r[iFrame_r]; iFrame++)
// {
// R11 = vR11[iFrame]*R11 + vR12[iFrame]*R21 + vR13[iFrame]*R31;
// R12 = vR11[iFrame]*R12 + vR12[iFrame]*R22 + vR13[iFrame]*R32;
// R13 = vR11[iFrame]*R13 + vR12[iFrame]*R23 + vR13[iFrame]*R33;
//
// R21 = vR21[iFrame]*R11 + vR22[iFrame]*R21 + vR23[iFrame]*R31;
// R22 = vR21[iFrame]*R12 + vR22[iFrame]*R22 + vR23[iFrame]*R32;
// R23 = vR21[iFrame]*R13 + vR22[iFrame]*R23 + vR23[iFrame]*R33;
//
// R31 = vR31[iFrame]*R11 + vR32[iFrame]*R21 + vR33[iFrame]*R31;
// R32 = vR31[iFrame]*R12 + vR32[iFrame]*R22 + vR33[iFrame]*R32;
// R33 = vR31[iFrame]*R13 + vR32[iFrame]*R23 + vR33[iFrame]*R33;
// }
// cvSetReal2D(vM_r[iFrame_r], 0, 0, R11); cvSetReal2D(vM_r[iFrame_r], 0, 1, R12); cvSetReal2D(vM_r[iFrame_r], 0, 2, R13);
// cvSetReal2D(vM_r[iFrame_r], 1, 0, R21); cvSetReal2D(vM_r[iFrame_r], 1, 1, R22); cvSetReal2D(vM_r[iFrame_r], 1, 2, R23);
// cvSetReal2D(vM_r[iFrame_r], 2, 0, R31); cvSetReal2D(vM_r[iFrame_r], 2, 1, R32); cvSetReal2D(vM_r[iFrame_r], 2, 2, R33);
//
// cvSetReal2D(vm_r[iFrame_r], 0, 0, dCameraParameter[7*vFrame1.size()+3*iFrame_r+0]);
// cvSetReal2D(vm_r[iFrame_r], 1, 0, dCameraParameter[7*vFrame1.size()+3*iFrame_r+1]);
// cvSetReal2D(vm_r[iFrame_r], 2, 0, dCameraParameter[7*vFrame1.size()+3*iFrame_r+2]);
// }
//
// free(dmeasurement);
// free(dCameraParameter);
// free(work);
//}
void DetectPOI(vector<CvMat *> vP, vector<CvMat *> vV, int nSegments, double range, double merging_threshold, vector<double> vBandwidth, vector<CvMat *> &vPOI,
double epsilon_cov, int nSegments_cov, vector<CvMat *> &v_a_cov, vector<CvMat *> &v_b_cov, vector<CvMat *> &v_l_cov, vector<double> &vf)
{
vector<CvMat *> vPOI_temp;
vector<vector<double> > vvWeight;
for (int iP = 0; iP < vP.size(); iP++)
{
for (int iSeg = 0; iSeg < nSegments; iSeg++)
{
double y1, y2, y3;
y1 = cvGetReal2D(vP[iP], 0, 0)+(range/(double)nSegments)*(iSeg+1)*cvGetReal2D(vV[iP], 0, 0);
y2 = cvGetReal2D(vP[iP], 1, 0)+(range/(double)nSegments)*(iSeg+1)*cvGetReal2D(vV[iP], 1, 0);
y3 = cvGetReal2D(vP[iP], 2, 0)+(range/(double)nSegments)*(iSeg+1)*cvGetReal2D(vV[iP], 2, 0);
bool isBad = false;
int nIter = 0;
vector<double> vWeight;
vector<double> vWeight_temp;
while (1)
{
double yp1 = y1, yp2 = y2, yp3 = y3;
vWeight.clear();
MeanShift_Gaussian_Cone(y1, y2, y3, vP, vV, vBandwidth, vWeight);
double normDiff = sqrt((y1-yp1)*(y1-yp1)+(y2-yp2)*(y2-yp2)+(y3-yp3)*(y3-yp3));
if (normDiff < 1e-5)
{
break;
}
nIter++;
if (nIter > 2000)
{
isBad = true;
break;
}
}
if (isBad)
{
continue;
}
double sumw = 0;
for (int iw = 0; iw < vWeight.size(); iw++)
{
sumw += vWeight[iw];
}
for (int iw = 0; iw < vWeight.size(); iw++)
{
vWeight[iw] /= sumw;
}
vWeight_temp = vWeight;
sort(vWeight.begin(), vWeight.end());
if (vWeight[vWeight.size()-2]/vWeight[vWeight.size()-1] > 0.01)
{
if (vPOI_temp.empty())
{
CvMat *poi = cvCreateMat(3,1,CV_32FC1);
cvSetReal2D(poi, 0, 0, y1);
cvSetReal2D(poi, 1, 0, y2);
cvSetReal2D(poi, 2, 0, y3);
vPOI_temp.push_back(poi);
vvWeight.push_back(vWeight_temp);
}
else
{
bool isIn = false;
for (int iPoi = 0; iPoi < vPOI_temp.size(); iPoi++)
{
double c1 = cvGetReal2D(vPOI_temp[iPoi], 0, 0) - y1;
double c2 = cvGetReal2D(vPOI_temp[iPoi], 1, 0) - y2;
double c3 = cvGetReal2D(vPOI_temp[iPoi], 2, 0) - y3;
if (sqrt(c1*c1+c2*c2+c3*c3) < merging_threshold)
{
isIn = true;
break;
}
}
if (!isIn)
{
CvMat *poi = cvCreateMat(3,1,CV_32FC1);
cvSetReal2D(poi, 0, 0, y1);
cvSetReal2D(poi, 1, 0, y2);
cvSetReal2D(poi, 2, 0, y3);
vPOI_temp.push_back(poi);
vvWeight.push_back(vWeight_temp);
}
}
}
}
}
for (int iPOI = 0; iPOI < vPOI_temp.size(); iPOI++)
{
vector<double> v_a, v_b, v_l;
bool isGood = POICovariance(vP, vV, vBandwidth, vPOI_temp[iPOI], epsilon_cov, nSegments_cov, v_a, v_b, v_l);
if (!isGood)
continue;
CvMat *a = cvCreateMat(v_a.size(), 1, CV_32FC1);
CvMat *b = cvCreateMat(v_b.size(), 1, CV_32FC1);
CvMat *l = cvCreateMat(v_b.size(), 1, CV_32FC1);
for (int ia = 0; ia < v_a.size(); ia++)
{
cvSetReal2D(a, ia, 0, v_a[ia]);
cvSetReal2D(b, ia, 0, v_b[ia]);
cvSetReal2D(l, ia, 0, v_l[ia]);
}
v_a_cov.push_back(a);
v_b_cov.push_back(b);
v_l_cov.push_back(l);
double f0 = EvaulateDensityFunction(vP, vV, vBandwidth, vPOI_temp[iPOI]);
vf.push_back(f0);
vPOI.push_back(cvCloneMat(vPOI_temp[iPOI]));
//CvMat *U = cvCreateMat(3,3,CV_32FC1);
//CvMat *Radius = cvCreateMat(3,1, CV_32FC1);
//PrintMat(vPOI[iPOI]);
//POICovariance(vP, vV, vvWeight[iPOI], U, Radius);
//vU.push_back(U);
//vRadius.push_back(Radius);
}
for (int i = 0; i < vPOI.size(); i++)
{
cvReleaseMat(&vPOI_temp[i]);
}
vPOI_temp.clear();
}
void DetectPOI(vector<CvMat *> vP, vector<CvMat *> vV, int nSegments, double range, double merging_threshold, vector<double> vBandwidth, vector<CvMat *> &vPOI,
double epsilon_cov, int nSegments_cov, vector<CvMat *> &v_a_cov, vector<CvMat *> &v_b_cov, vector<CvMat *> &v_l_cov, vector<double> &vf,
vector<vector<CvMat *> > &vvMeanTrajectory)
{
vector<CvMat *> vPOI_temp;
vector<vector<double> > vvWeight;
for (int iP = 0; iP < vP.size(); iP++)
{
for (int iSeg = 0; iSeg < nSegments; iSeg++)
{
double y1, y2, y3;
y1 = cvGetReal2D(vP[iP], 0, 0)+(range/(double)nSegments)*(iSeg+1)*cvGetReal2D(vV[iP], 0, 0);
y2 = cvGetReal2D(vP[iP], 1, 0)+(range/(double)nSegments)*(iSeg+1)*cvGetReal2D(vV[iP], 1, 0);
y3 = cvGetReal2D(vP[iP], 2, 0)+(range/(double)nSegments)*(iSeg+1)*cvGetReal2D(vV[iP], 2, 0);
bool isBad = false;
int nIter = 0;
vector<double> vWeight;
vector<double> vWeight_temp;
vector<double> mean_x;
vector<double> mean_y;
vector<double> mean_z;
while (1)
{
mean_x.push_back(y1);
mean_y.push_back(y2);
mean_z.push_back(y3);
double yp1 = y1, yp2 = y2, yp3 = y3;
vWeight.clear();
MeanShift_Gaussian_Cone(y1, y2, y3, vP, vV, vBandwidth, vWeight);
double normDiff = sqrt((y1-yp1)*(y1-yp1)+(y2-yp2)*(y2-yp2)+(y3-yp3)*(y3-yp3));
if (normDiff < 1e-5)
{
break;
}
nIter++;
if (nIter > 2000)
{
isBad = true;
break;
}
}
if (isBad)
{
continue;
}
double sumw = 0;
for (int iw = 0; iw < vWeight.size(); iw++)
{
sumw += vWeight[iw];
}
for (int iw = 0; iw < vWeight.size(); iw++)
{
vWeight[iw] /= sumw;
}
vWeight_temp = vWeight;
sort(vWeight.begin(), vWeight.end());
if (vWeight[vWeight.size()-2]/vWeight[vWeight.size()-1] > 0.1)
{
vector<CvMat *> vMean;
for (int ii = 0; ii < mean_x.size(); ii++)
{
CvMat *mm = cvCreateMat(3,1,CV_32FC1);
cvSetReal2D(mm, 0, 0, mean_x[ii]);
cvSetReal2D(mm, 1, 0, mean_y[ii]);
cvSetReal2D(mm, 2, 0, mean_z[ii]);
vMean.push_back(mm);
}
vvMeanTrajectory.push_back(vMean);
if (vPOI_temp.empty())
{
CvMat *poi = cvCreateMat(3,1,CV_32FC1);
cvSetReal2D(poi, 0, 0, y1);
cvSetReal2D(poi, 1, 0, y2);
cvSetReal2D(poi, 2, 0, y3);
vPOI_temp.push_back(poi);
vvWeight.push_back(vWeight_temp);
}
else
{
bool isIn = false;
for (int iPoi = 0; iPoi < vPOI_temp.size(); iPoi++)
{
double c1 = cvGetReal2D(vPOI_temp[iPoi], 0, 0) - y1;
double c2 = cvGetReal2D(vPOI_temp[iPoi], 1, 0) - y2;
double c3 = cvGetReal2D(vPOI_temp[iPoi], 2, 0) - y3;
if (sqrt(c1*c1+c2*c2+c3*c3) < merging_threshold)
{
isIn = true;
break;
}
}
if (!isIn)
{
CvMat *poi = cvCreateMat(3,1,CV_32FC1);
cvSetReal2D(poi, 0, 0, y1);
cvSetReal2D(poi, 1, 0, y2);
cvSetReal2D(poi, 2, 0, y3);
vPOI_temp.push_back(poi);
vvWeight.push_back(vWeight_temp);
}
}
}
}
}
for (int iPOI = 0; iPOI < vPOI_temp.size(); iPOI++)
{
vector<double> v_a, v_b, v_l;
bool isGood = POICovariance(vP, vV, vBandwidth, vPOI_temp[iPOI], epsilon_cov, nSegments_cov, v_a, v_b, v_l);
if (!isGood)
{
vector<vector<CvMat *> > vvMeanTraj_temp;
for (int iTraj = 0; iTraj < vvMeanTrajectory.size(); iTraj++)
{
double traj_x = cvGetReal2D(vvMeanTrajectory[iTraj][vvMeanTrajectory[iTraj].size()-1], 0, 0);
double traj_y = cvGetReal2D(vvMeanTrajectory[iTraj][vvMeanTrajectory[iTraj].size()-1], 1, 0);
double traj_z = cvGetReal2D(vvMeanTrajectory[iTraj][vvMeanTrajectory[iTraj].size()-1], 2, 0);
double error = sqrt((traj_x-cvGetReal2D(vPOI_temp[iPOI], 0, 0))*(traj_x-cvGetReal2D(vPOI_temp[iPOI], 0, 0))+
(traj_y-cvGetReal2D(vPOI_temp[iPOI], 1, 0))*(traj_y-cvGetReal2D(vPOI_temp[iPOI], 1, 0))+
(traj_z-cvGetReal2D(vPOI_temp[iPOI], 2, 0))*(traj_z-cvGetReal2D(vPOI_temp[iPOI], 2, 0)));
if (error < 1e-3)
continue;
vvMeanTraj_temp.push_back(vvMeanTrajectory[iTraj]);
}
vvMeanTrajectory = vvMeanTraj_temp;
continue;
}
CvMat *a = cvCreateMat(v_a.size(), 1, CV_32FC1);
CvMat *b = cvCreateMat(v_b.size(), 1, CV_32FC1);
CvMat *l = cvCreateMat(v_b.size(), 1, CV_32FC1);
for (int ia = 0; ia < v_a.size(); ia++)
{
cvSetReal2D(a, ia, 0, v_a[ia]);
cvSetReal2D(b, ia, 0, v_b[ia]);
cvSetReal2D(l, ia, 0, v_l[ia]);
}
v_a_cov.push_back(a);
v_b_cov.push_back(b);
v_l_cov.push_back(l);
double f0 = EvaulateDensityFunction(vP, vV, vBandwidth, vPOI_temp[iPOI]);
vf.push_back(f0);
vPOI.push_back(cvCloneMat(vPOI_temp[iPOI]));
//CvMat *U = cvCreateMat(3,3,CV_32FC1);
//CvMat *Radius = cvCreateMat(3,1, CV_32FC1);
//PrintMat(vPOI[iPOI]);
//POICovariance(vP, vV, vvWeight[iPOI], U, Radius);
//vU.push_back(U);
//vRadius.push_back(Radius);
}
for (int i = 0; i < vPOI.size(); i++)
{
cvReleaseMat(&vPOI_temp[i]);
}
vPOI_temp.clear();
}
bool POICovariance(vector<CvMat *> vP, vector<CvMat *> vV, vector<double> vBandwidth, CvMat *poi, double epsilon, int nSegments, vector<double> &v_a, vector<double> &v_b, vector<double> &v_l)
{
double f0 = EvaulateDensityFunction(vP, vV, vBandwidth, poi);
double phi_step = 2*PI/nSegments;
double theta_step = PI/(nSegments/2);
bool isGood = true;
for (int iphi = 0; iphi < nSegments; iphi++)
{
for (int itheta = 0; itheta < nSegments/2+1; itheta++)
{
CvMat *v = cvCreateMat(3,1,CV_32FC1);
cvSetReal2D(v, 0, 0, cos(iphi*phi_step)*sin(itheta*theta_step));
cvSetReal2D(v, 1, 0, sin(iphi*phi_step)*sin(itheta*theta_step));
cvSetReal2D(v, 2, 0, cos(itheta*theta_step));
CvMat *v_temp = cvCreateMat(3,1,CV_32FC1);
CvMat *x = cvCreateMat(3,1,CV_32FC1);
ScalarMul(v, epsilon, v_temp);
cvAdd(poi, v_temp, x);
double f = EvaulateDensityFunction(vP, vV, vBandwidth, x);
if ((f0-f)/(-epsilon) > -5e-2)
{
isGood = false;
v_a.push_back(-5e-2);
}
else
v_a.push_back((f0-f)/(-epsilon));
v_b.push_back(f0);
double alpha = 0;
while (1)
{
alpha = alpha + 0.1;
ScalarMul(v, epsilon+alpha, v_temp);
cvAdd(poi, v_temp, x);
f = EvaulateDensityFunction(vP, vV, vBandwidth, x);
double y = (f0-f)/(-epsilon) * (epsilon+alpha) + f0;
if (abs(f-y) > 1e+0)
{
v_l.push_back(alpha+epsilon);
break;
}
}
cvReleaseMat(&v);
cvReleaseMat(&x);
}
}
return isGood;
}
double EvaulateDensityFunction(vector<CvMat *> vP, vector<CvMat *> vV, vector<double> vBandwidth, CvMat *x)
{
double f = 0;
for (int ip = 0; ip < vP.size(); ip++)
{
double norm_v = sqrt(cvGetReal2D(vV[ip], 0, 0)*cvGetReal2D(vV[ip], 0, 0)+cvGetReal2D(vV[ip], 1, 0)*cvGetReal2D(vV[ip], 1, 0)+cvGetReal2D(vV[ip], 2, 0)*cvGetReal2D(vV[ip], 2, 0));
ScalarMul(vV[ip], 1/norm_v, vV[ip]);
CvMat *xmp = cvCreateMat(3,1,CV_32FC1);
cvSub(x, vP[ip], xmp);
CvMat *dot_product = cvCreateMat(1,1,CV_32FC1);
CvMat *v_t = cvCreateMat(1,3,CV_32FC1);
cvTranspose(vV[ip], v_t);
cvMatMul(v_t, xmp, dot_product);
CvMat *dx = cvCreateMat(3,1,CV_32FC1);
CvMat *dot_ray = cvCreateMat(3,1,CV_32FC1);
ScalarMul(vV[ip], cvGetReal2D(dot_product, 0, 0), dot_ray);
cvSub(xmp, dot_ray, dx);
if (cvGetReal2D(dot_product, 0, 0) > 0)
{
double dist1 = sqrt(cvGetReal2D(dx, 0, 0)*cvGetReal2D(dx, 0, 0)+cvGetReal2D(dx, 1, 0)*cvGetReal2D(dx, 1, 0)+cvGetReal2D(dx, 2, 0)*cvGetReal2D(dx, 2, 0));
double dist2 = cvGetReal2D(dot_product, 0, 0);
f+= 1/vBandwidth[ip] * exp(-(dist1/dist2)*(dist1/dist2)/2/vBandwidth[ip]/vBandwidth[ip]);
}
cvReleaseMat(&xmp);
cvReleaseMat(&dot_product);
cvReleaseMat(&v_t);
cvReleaseMat(&dx);
cvReleaseMat(&dot_ray);
}
f /= vP.size();
return f;
}
void POICovariance(vector<CvMat *> vP, vector<CvMat *> vV, vector<double> vWeight, CvMat *U, CvMat *Radius)
{
CvMat *A = cvCreateMat(3*vP.size(), 3, CV_32FC1);
CvMat *b = cvCreateMat(3*vP.size(), 1, CV_32FC1);
for (int iCamera = 0; iCamera < vP.size(); iCamera++)
{
CvMat *Ai = cvCreateMat(3,3, CV_32FC1);
CvMat *bi = cvCreateMat(3,1, CV_32FC1);
Vec2Skew(vV[iCamera], Ai);
ScalarMul(Ai, vWeight[iCamera], Ai);
cvMatMul(Ai, vP[iCamera], bi);
SetSubMat(A, 3*iCamera, 0, Ai);
SetSubMat(b, 3*iCamera, 0, bi);
cvReleaseMat(&Ai);
cvReleaseMat(&bi);
}
double meanb = 0;
for (int ib = 0; ib < b->rows; ib++)
{
meanb += cvGetReal2D(b, ib, 0);
}
meanb /= b->rows;
double varianceb = 0;
for (int ib = 0; ib < b->rows; ib++)
{
varianceb += (cvGetReal2D(b, ib, 0)-meanb)*(cvGetReal2D(b, ib, 0)-meanb);
}
varianceb /= b->rows;
CvMat *At = cvCreateMat(A->cols, A->rows, CV_32FC1);
cvTranspose(A, At);
CvMat *Q = cvCreateMat(3,3,CV_32FC1);
cvMatMul(At, A, Q);
cvInvert(Q, Q);
ScalarMul(Q, varianceb, Q);
CvMat *D = cvCreateMat(3,3,CV_32FC1);
CvMat *V = cvCreateMat(3,3,CV_32FC1);
cvSVD(Q, D, U, V);
cvSetReal2D(Radius, 0, 0, sqrt(cvGetReal2D(D, 0, 0)));
cvSetReal2D(Radius, 1, 0, sqrt(cvGetReal2D(D, 1, 1)));
cvSetReal2D(Radius, 2, 0, sqrt(cvGetReal2D(D, 2, 2)));
cvReleaseMat(&D);
cvReleaseMat(&V);
cvReleaseMat(&Q);
cvReleaseMat(&A);
cvReleaseMat(&At);
cvReleaseMat(&b);
}
void MeanShift_Gaussian_Cone(double &y1, double &y2, double &y3, vector<CvMat *> vP, vector<CvMat *> vV, vector<double> vBandwidth, vector<double> &vWeight)
{
double sum1 = 0, sum2 = 0, sum3 = 0;
double normalization = 0;
for (int iP = 0; iP < vP.size(); iP++)
{
double dist, gradient1, gradient2, gradient3;
DistanceBetweenConeAndPoint(cvGetReal2D(vP[iP], 0, 0), cvGetReal2D(vP[iP], 1, 0), cvGetReal2D(vP[iP], 2, 0),
cvGetReal2D(vV[iP], 0, 0), cvGetReal2D(vV[iP], 1, 0), cvGetReal2D(vV[iP], 2, 0),
y1, y2, y3, dist);
double xmp1 = y1-cvGetReal2D(vP[iP], 0, 0);
double xmp2 = y2-cvGetReal2D(vP[iP], 1, 0);
double xmp3 = y3-cvGetReal2D(vP[iP], 2, 0);
double v1 = cvGetReal2D(vV[iP], 0, 0);
double v2 = cvGetReal2D(vV[iP], 1, 0);
double v3 = cvGetReal2D(vV[iP], 2, 0);
double v_norm = sqrt(v1*v1+v2*v2+v3*v3);
v1 /= v_norm;
v2 /= v_norm;
v3 /= v_norm;
double vxmp1 = v1*xmp1;
double vxmp2 = v2*xmp2;
double vxmp3 = v3*xmp3;
double vxmp = vxmp1+vxmp2+vxmp3;
double x_tilde1 = cvGetReal2D(vP[iP], 0, 0) + (vxmp + dist*dist*vxmp)*v1;
double x_tilde2 = cvGetReal2D(vP[iP], 1, 0) + (vxmp + dist*dist*vxmp)*v2;
double x_tilde3 = cvGetReal2D(vP[iP], 2, 0) + (vxmp + dist*dist*vxmp)*v3;
double weight = exp(-dist*dist/vBandwidth[iP]/vBandwidth[iP]/2)/(vBandwidth[iP]*vBandwidth[iP]*vBandwidth[iP]*vxmp*vxmp);
sum1 += weight * x_tilde1;
sum2 += weight * x_tilde2;
sum3 += weight * x_tilde3;
normalization += weight;
vWeight.push_back(weight);
}
y1 = sum1/normalization;
y2 = sum2/normalization;
y3 = sum3/normalization;
}
void MeanShift_Gaussian_Ray(double &y1, double &y2, double &y3, vector<CvMat *> vP, vector<CvMat *> vV, double bandwidth, vector<double> &vWeight)
{
double sum1 = 0, sum2 = 0, sum3 = 0;
double normalization = 0;
for (int iP = 0; iP < vP.size(); iP++)
{
double dist, gradient1, gradient2, gradient3;
DistanceBetweenRayAndPoint(cvGetReal2D(vP[iP], 0, 0), cvGetReal2D(vP[iP], 1, 0), cvGetReal2D(vP[iP], 2, 0),
cvGetReal2D(vV[iP], 0, 0), cvGetReal2D(vV[iP], 1, 0), cvGetReal2D(vV[iP], 2, 0),
y1, y2, y3, dist, gradient1, gradient2, gradient3);
double dir1, dir2, dir3;
dir1 = y1-cvGetReal2D(vP[iP], 0, 0);
dir2 = y2-cvGetReal2D(vP[iP], 1, 0);
dir3 = y3-cvGetReal2D(vP[iP], 2, 0);
double dot_product = dir1*cvGetReal2D(vV[iP], 0, 0)+dir2*cvGetReal2D(vV[iP], 1, 0)+dir3*cvGetReal2D(vV[iP], 2, 0);
if (dot_product < 0)
{
dist = 1e+6;
}
sum1 += gradient1*exp(-dist*dist/bandwidth/bandwidth);
sum2 += gradient2*exp(-dist*dist/bandwidth/bandwidth);
sum3 += gradient3*exp(-dist*dist/bandwidth/bandwidth);
normalization += exp(-dist*dist/bandwidth/bandwidth);
vWeight.push_back(exp(-dist*dist/bandwidth/bandwidth));
}
y1 = sum1/normalization;
y2 = sum2/normalization;
y3 = sum3/normalization;
}
void DistanceBetweenRayAndPoint(double p1, double p2, double p3, double v1, double v2, double v3, double x1, double x2, double x3,
double &d, double &g1, double &g2, double &g3)
{
double v_norm = sqrt(v1*v1+v2*v2+v3*v3);
v1 /= v_norm;
v2 /= v_norm;
v3 /= v_norm;
double xmp1 = x1-p1;
double xmp2 = x2-p2;
double xmp3 = x3-p3;
double xmp_dot_v1 = xmp1*v1;
double xmp_dot_v2 = xmp1*v2;
double xmp_dot_v3 = xmp1*v3;
double d1 = xmp1-xmp_dot_v1*v1;
double d2 = xmp2-xmp_dot_v2*v2;
double d3 = xmp3-xmp_dot_v3*v3;
d = sqrt(d1*d1+d2*d2+d3*d3);
g1 = p1 + xmp_dot_v1*v1;
g2 = p2 + xmp_dot_v2*v2;
g3 = p3 + xmp_dot_v3*v3;
}
void DistanceBetweenConeAndPoint(double p1, double p2, double p3, double v1, double v2, double v3, double x1, double x2, double x3,
double &d)
{
double v_norm = sqrt(v1*v1+v2*v2+v3*v3);
v1 /= v_norm;
v2 /= v_norm;
v3 /= v_norm;
double xmp1 = x1-p1;
double xmp2 = x2-p2;
double xmp3 = x3-p3;
double xmp_dot_v1 = xmp1*v1;
double xmp_dot_v2 = xmp2*v2;
double xmp_dot_v3 = xmp3*v3;
double direction = xmp_dot_v1+xmp_dot_v2+xmp_dot_v3;
if (direction > 0)
{
double upper1 = xmp1 - direction*v1;
double upper2 = xmp2 - direction*v2;
double upper3 = xmp3 - direction*v3;
d = sqrt(upper1*upper1+upper2*upper2+upper3*upper3)/direction;
}
else
{
d = 1e+6;
}
}
| [
"[email protected]"
] | [
[
[
1,
10299
]
]
] |
6398ed53bb2d9eb406876f19c257c4836c542423 | 52fb59fce8f90e7f69749fa6f5521a7c392f1617 | /src/modules/navigator/navigator_main.cpp | 8cb56c03fd2324d55c7d0a1f0cf04d1676b0eeba | [
"BSD-3-Clause"
] | permissive | HCFlight/Firmware | 89cc31fc9c01f56578645ec528ff27293c3c9b1a | cab5f83af370687b7508891f1d1ea1eab804e385 | refs/heads/hc1master | 2020-04-02T08:35:54.349367 | 2018-11-02T10:20:25 | 2018-11-02T10:20:25 | 154,251,398 | 3 | 2 | BSD-3-Clause | 2018-11-02T10:20:26 | 2018-10-23T02:47:39 | C++ | UTF-8 | C++ | false | false | 38,733 | cpp | /****************************************************************************
*
* Copyright (c) 2013-2017 PX4 Development Team. 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.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file navigator_main.cpp
*
* Handles mission items, geo fencing and failsafe navigation behavior.
* Published the position setpoint triplet for the position controller.
*
* @author Lorenz Meier <[email protected]>
* @author Jean Cyr <[email protected]>
* @author Julian Oes <[email protected]>
* @author Anton Babushkin <[email protected]>
* @author Thomas Gubler <[email protected]>
*/
#include "navigator.h"
#include <cfloat>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dataman/dataman.h>
#include <drivers/drv_hrt.h>
#include <lib/ecl/geo/geo.h>
#include <mathlib/mathlib.h>
#include <px4_config.h>
#include <px4_defines.h>
#include <px4_posix.h>
#include <px4_tasks.h>
#include <systemlib/mavlink_log.h>
#include <uORB/topics/fw_pos_ctrl_status.h>
#include <uORB/topics/home_position.h>
#include <uORB/topics/mission.h>
#include <uORB/topics/vehicle_command.h>
#include <uORB/topics/vehicle_command_ack.h>
#include <uORB/topics/vehicle_status.h>
#include <uORB/topics/transponder_report.h>
#include <uORB/uORB.h>
/**
* navigator app start / stop handling function
*
* @ingroup apps
*/
extern "C" __EXPORT int navigator_main(int argc, char *argv[]);
#define GEOFENCE_CHECK_INTERVAL 200000
namespace navigator
{
Navigator *g_navigator;
}
Navigator::Navigator() :
ModuleParams(nullptr),
_loop_perf(perf_alloc(PC_ELAPSED, "navigator")),
_geofence(this),
_mission(this),
_loiter(this),
_takeoff(this),
_land(this),
_precland(this),
_rtl(this),
_rcLoss(this),
_dataLinkLoss(this),
_engineFailure(this),
_gpsFailure(this),
_follow_target(this)
{
/* Create a list of our possible navigation types */
_navigation_mode_array[0] = &_mission;
_navigation_mode_array[1] = &_loiter;
_navigation_mode_array[2] = &_rtl;
_navigation_mode_array[3] = &_dataLinkLoss;
_navigation_mode_array[4] = &_engineFailure;
_navigation_mode_array[5] = &_gpsFailure;
_navigation_mode_array[6] = &_rcLoss;
_navigation_mode_array[7] = &_takeoff;
_navigation_mode_array[8] = &_land;
_navigation_mode_array[9] = &_precland;
_navigation_mode_array[10] = &_follow_target;
}
void
Navigator::global_position_update()
{
orb_copy(ORB_ID(vehicle_global_position), _global_pos_sub, &_global_pos);
}
void
Navigator::local_position_update()
{
orb_copy(ORB_ID(vehicle_local_position), _local_pos_sub, &_local_pos);
}
void
Navigator::gps_position_update()
{
orb_copy(ORB_ID(vehicle_gps_position), _gps_pos_sub, &_gps_pos);
}
void
Navigator::home_position_update(bool force)
{
bool updated = false;
orb_check(_home_pos_sub, &updated);
if (updated || force) {
orb_copy(ORB_ID(home_position), _home_pos_sub, &_home_pos);
}
}
void
Navigator::fw_pos_ctrl_status_update(bool force)
{
bool updated = false;
orb_check(_fw_pos_ctrl_status_sub, &updated);
if (updated || force) {
orb_copy(ORB_ID(fw_pos_ctrl_status), _fw_pos_ctrl_status_sub, &_fw_pos_ctrl_status);
}
}
void
Navigator::vehicle_status_update()
{
if (orb_copy(ORB_ID(vehicle_status), _vstatus_sub, &_vstatus) != OK) {
/* in case the commander is not be running */
_vstatus.arming_state = vehicle_status_s::ARMING_STATE_STANDBY;
}
}
void
Navigator::vehicle_land_detected_update()
{
orb_copy(ORB_ID(vehicle_land_detected), _land_detected_sub, &_land_detected);
}
void
Navigator::params_update()
{
parameter_update_s param_update;
orb_copy(ORB_ID(parameter_update), _param_update_sub, ¶m_update);
updateParams();
}
void
Navigator::run()
{
bool have_geofence_position_data = false;
/* Try to load the geofence:
* if /fs/microsd/etc/geofence.txt load from this file */
struct stat buffer;
if (stat(GEOFENCE_FILENAME, &buffer) == 0) {
PX4_INFO("Loading geofence from %s", GEOFENCE_FILENAME);
_geofence.loadFromFile(GEOFENCE_FILENAME);
}
/* do subscriptions */
_global_pos_sub = orb_subscribe(ORB_ID(vehicle_global_position));
_local_pos_sub = orb_subscribe(ORB_ID(vehicle_local_position));
_gps_pos_sub = orb_subscribe(ORB_ID(vehicle_gps_position));
_fw_pos_ctrl_status_sub = orb_subscribe(ORB_ID(fw_pos_ctrl_status));
_vstatus_sub = orb_subscribe(ORB_ID(vehicle_status));
_land_detected_sub = orb_subscribe(ORB_ID(vehicle_land_detected));
_home_pos_sub = orb_subscribe(ORB_ID(home_position));
_offboard_mission_sub = orb_subscribe(ORB_ID(mission));
_param_update_sub = orb_subscribe(ORB_ID(parameter_update));
_vehicle_command_sub = orb_subscribe(ORB_ID(vehicle_command));
_traffic_sub = orb_subscribe(ORB_ID(transponder_report));
/* copy all topics first time */
vehicle_status_update();
vehicle_land_detected_update();
global_position_update();
local_position_update();
gps_position_update();
home_position_update(true);
fw_pos_ctrl_status_update(true);
params_update();
/* wakeup source(s) */
px4_pollfd_struct_t fds[1] = {};
/* Setup of loop */
fds[0].fd = _local_pos_sub;
fds[0].events = POLLIN;
/* rate-limit position subscription to 20 Hz / 50 ms */
orb_set_interval(_local_pos_sub, 50);
hrt_abstime last_geofence_check = 0;
while (!should_exit()) {
/* wait for up to 1000ms for data */
int pret = px4_poll(&fds[0], (sizeof(fds) / sizeof(fds[0])), 1000);
if (pret == 0) {
/* Let the loop run anyway, don't do `continue` here. */
} else if (pret < 0) {
/* this is undesirable but not much we can do - might want to flag unhappy status */
PX4_ERR("poll error %d, %d", pret, errno);
usleep(10000);
continue;
} else {
if (fds[0].revents & POLLIN) {
/* success, local pos is available */
local_position_update();
}
}
perf_begin(_loop_perf);
bool updated;
/* gps updated */
orb_check(_gps_pos_sub, &updated);
if (updated) {
gps_position_update();
if (_geofence.getSource() == Geofence::GF_SOURCE_GPS) {
have_geofence_position_data = true;
}
}
/* global position updated */
orb_check(_global_pos_sub, &updated);
if (updated) {
global_position_update();
if (_geofence.getSource() == Geofence::GF_SOURCE_GLOBALPOS) {
have_geofence_position_data = true;
}
}
/* parameters updated */
orb_check(_param_update_sub, &updated);
if (updated) {
params_update();
}
/* vehicle status updated */
orb_check(_vstatus_sub, &updated);
if (updated) {
vehicle_status_update();
}
/* vehicle land detected updated */
orb_check(_land_detected_sub, &updated);
if (updated) {
vehicle_land_detected_update();
}
/* navigation capabilities updated */
orb_check(_fw_pos_ctrl_status_sub, &updated);
if (updated) {
fw_pos_ctrl_status_update();
}
/* home position updated */
orb_check(_home_pos_sub, &updated);
if (updated) {
home_position_update();
}
/* vehicle_command updated */
orb_check(_vehicle_command_sub, &updated);
if (updated) {
vehicle_command_s cmd;
orb_copy(ORB_ID(vehicle_command), _vehicle_command_sub, &cmd);
if (cmd.command == vehicle_command_s::VEHICLE_CMD_DO_GO_AROUND) {
// DO_GO_AROUND is currently handled by the position controller (unacknowledged)
// TODO: move DO_GO_AROUND handling to navigator
publish_vehicle_command_ack(cmd, vehicle_command_s::VEHICLE_CMD_RESULT_ACCEPTED);
} else if (cmd.command == vehicle_command_s::VEHICLE_CMD_DO_REPOSITION) {
position_setpoint_triplet_s *rep = get_reposition_triplet();
position_setpoint_triplet_s *curr = get_position_setpoint_triplet();
// store current position as previous position and goal as next
rep->previous.yaw = get_global_position()->yaw;
rep->previous.lat = get_global_position()->lat;
rep->previous.lon = get_global_position()->lon;
rep->previous.alt = get_global_position()->alt;
rep->current.loiter_radius = get_loiter_radius();
rep->current.loiter_direction = 1;
rep->current.type = position_setpoint_s::SETPOINT_TYPE_LOITER;
rep->current.cruising_speed = get_cruising_speed();
rep->current.cruising_throttle = get_cruising_throttle();
// Go on and check which changes had been requested
if (PX4_ISFINITE(cmd.param4)) {
rep->current.yaw = cmd.param4;
} else {
rep->current.yaw = NAN;
}
if (PX4_ISFINITE(cmd.param5) && PX4_ISFINITE(cmd.param6)) {
// Position change with optional altitude change
rep->current.lat = (cmd.param5 < 1000) ? cmd.param5 : cmd.param5 / (double)1e7;
rep->current.lon = (cmd.param6 < 1000) ? cmd.param6 : cmd.param6 / (double)1e7;
if (PX4_ISFINITE(cmd.param7)) {
rep->current.alt = cmd.param7;
} else {
rep->current.alt = get_global_position()->alt;
}
} else if (PX4_ISFINITE(cmd.param7) && curr->current.valid
&& PX4_ISFINITE(curr->current.lat)
&& PX4_ISFINITE(curr->current.lon)) {
// Altitude without position change
rep->current.lat = curr->current.lat;
rep->current.lon = curr->current.lon;
rep->current.alt = cmd.param7;
} else {
// All three set to NaN - hold in current position
rep->current.lat = get_global_position()->lat;
rep->current.lon = get_global_position()->lon;
rep->current.alt = get_global_position()->alt;
}
rep->previous.valid = true;
rep->current.valid = true;
rep->next.valid = false;
// CMD_DO_REPOSITION is acknowledged by commander
} else if (cmd.command == vehicle_command_s::VEHICLE_CMD_NAV_TAKEOFF) {
position_setpoint_triplet_s *rep = get_takeoff_triplet();
// store current position as previous position and goal as next
rep->previous.yaw = get_global_position()->yaw;
rep->previous.lat = get_global_position()->lat;
rep->previous.lon = get_global_position()->lon;
rep->previous.alt = get_global_position()->alt;
rep->current.loiter_radius = get_loiter_radius();
rep->current.loiter_direction = 1;
rep->current.type = position_setpoint_s::SETPOINT_TYPE_TAKEOFF;
if (home_position_valid()) {
rep->current.yaw = cmd.param4;
rep->previous.valid = true;
} else {
rep->current.yaw = get_local_position()->yaw;
rep->previous.valid = false;
}
if (PX4_ISFINITE(cmd.param5) && PX4_ISFINITE(cmd.param6)) {
rep->current.lat = (cmd.param5 < 1000) ? cmd.param5 : cmd.param5 / (double)1e7;
rep->current.lon = (cmd.param6 < 1000) ? cmd.param6 : cmd.param6 / (double)1e7;
} else {
// If one of them is non-finite, reset both
rep->current.lat = NAN;
rep->current.lon = NAN;
}
rep->current.alt = cmd.param7;
rep->current.valid = true;
rep->next.valid = false;
// CMD_NAV_TAKEOFF is acknowledged by commander
} else if (cmd.command == vehicle_command_s::VEHICLE_CMD_DO_LAND_START) {
/* find NAV_CMD_DO_LAND_START in the mission and
* use MAV_CMD_MISSION_START to start the mission there
*/
if (_mission.land_start()) {
vehicle_command_s vcmd = {};
vcmd.command = vehicle_command_s::VEHICLE_CMD_MISSION_START;
vcmd.param1 = _mission.get_land_start_index();
publish_vehicle_cmd(&vcmd);
} else {
PX4_WARN("planned mission landing not available");
}
publish_vehicle_command_ack(cmd, vehicle_command_s::VEHICLE_CMD_RESULT_ACCEPTED);
} else if (cmd.command == vehicle_command_s::VEHICLE_CMD_MISSION_START) {
if (_mission_result.valid && PX4_ISFINITE(cmd.param1) && (cmd.param1 >= 0)) {
if (!_mission.set_current_offboard_mission_index(cmd.param1)) {
PX4_WARN("CMD_MISSION_START failed");
}
}
// CMD_MISSION_START is acknowledged by commander
} else if (cmd.command == vehicle_command_s::VEHICLE_CMD_DO_CHANGE_SPEED) {
if (cmd.param2 > FLT_EPSILON) {
// XXX not differentiating ground and airspeed yet
set_cruising_speed(cmd.param2);
} else {
set_cruising_speed();
/* if no speed target was given try to set throttle */
if (cmd.param3 > FLT_EPSILON) {
set_cruising_throttle(cmd.param3 / 100);
} else {
set_cruising_throttle();
}
}
// TODO: handle responses for supported DO_CHANGE_SPEED options?
publish_vehicle_command_ack(cmd, vehicle_command_s::VEHICLE_CMD_RESULT_ACCEPTED);
} else if (cmd.command == vehicle_command_s::VEHICLE_CMD_DO_SET_ROI
|| cmd.command == vehicle_command_s::VEHICLE_CMD_NAV_ROI
|| cmd.command == vehicle_command_s::VEHICLE_CMD_DO_SET_ROI_LOCATION
|| cmd.command == vehicle_command_s::VEHICLE_CMD_DO_SET_ROI_WPNEXT_OFFSET
|| cmd.command == vehicle_command_s::VEHICLE_CMD_DO_SET_ROI_NONE) {
_vroi = {};
switch (cmd.command) {
case vehicle_command_s::VEHICLE_CMD_DO_SET_ROI:
case vehicle_command_s::VEHICLE_CMD_NAV_ROI:
_vroi.mode = cmd.param1;
break;
case vehicle_command_s::VEHICLE_CMD_DO_SET_ROI_LOCATION:
_vroi.mode = vehicle_command_s::VEHICLE_ROI_LOCATION;
_vroi.lat = cmd.param5;
_vroi.lon = cmd.param6;
_vroi.alt = cmd.param7;
break;
case vehicle_command_s::VEHICLE_CMD_DO_SET_ROI_WPNEXT_OFFSET:
_vroi.mode = vehicle_command_s::VEHICLE_ROI_WPNEXT;
_vroi.pitch_offset = (float)cmd.param5 * M_DEG_TO_RAD_F;
_vroi.roll_offset = (float)cmd.param6 * M_DEG_TO_RAD_F;
_vroi.yaw_offset = (float)cmd.param7 * M_DEG_TO_RAD_F;
break;
case vehicle_command_s::VEHICLE_CMD_DO_SET_ROI_NONE:
_vroi.mode = vehicle_command_s::VEHICLE_ROI_NONE;
break;
default:
_vroi.mode = vehicle_command_s::VEHICLE_ROI_NONE;
break;
}
_vroi.timestamp = hrt_absolute_time();
if (_vehicle_roi_pub != nullptr) {
orb_publish(ORB_ID(vehicle_roi), _vehicle_roi_pub, &_vroi);
} else {
_vehicle_roi_pub = orb_advertise(ORB_ID(vehicle_roi), &_vroi);
}
publish_vehicle_command_ack(cmd, vehicle_command_s::VEHICLE_CMD_RESULT_ACCEPTED);
}
}
/* Check for traffic */
check_traffic();
/* Check geofence violation */
if (have_geofence_position_data &&
(_geofence.getGeofenceAction() != geofence_result_s::GF_ACTION_NONE) &&
(hrt_elapsed_time(&last_geofence_check) > GEOFENCE_CHECK_INTERVAL)) {
bool inside = _geofence.check(_global_pos, _gps_pos, _home_pos,
home_position_valid());
last_geofence_check = hrt_absolute_time();
have_geofence_position_data = false;
_geofence_result.timestamp = hrt_absolute_time();
_geofence_result.geofence_action = _geofence.getGeofenceAction();
_geofence_result.home_required = _geofence.isHomeRequired();
if (!inside) {
/* inform other apps via the mission result */
_geofence_result.geofence_violated = true;
/* Issue a warning about the geofence violation once */
if (!_geofence_violation_warning_sent) {
mavlink_log_critical(&_mavlink_log_pub, "Geofence violation");
_geofence_violation_warning_sent = true;
}
} else {
/* inform other apps via the mission result */
_geofence_result.geofence_violated = false;
/* Reset the _geofence_violation_warning_sent field */
_geofence_violation_warning_sent = false;
}
publish_geofence_result();
}
/* Do stuff according to navigation state set by commander */
NavigatorMode *navigation_mode_new{nullptr};
switch (_vstatus.nav_state) {
case vehicle_status_s::NAVIGATION_STATE_AUTO_MISSION:
_pos_sp_triplet_published_invalid_once = false;
_mission.set_execution_mode(mission_result_s::MISSION_EXECUTION_MODE_NORMAL);
navigation_mode_new = &_mission;
break;
case vehicle_status_s::NAVIGATION_STATE_AUTO_LOITER:
_pos_sp_triplet_published_invalid_once = false;
navigation_mode_new = &_loiter;
break;
case vehicle_status_s::NAVIGATION_STATE_AUTO_RCRECOVER:
_pos_sp_triplet_published_invalid_once = false;
navigation_mode_new = &_rcLoss;
break;
case vehicle_status_s::NAVIGATION_STATE_AUTO_RTL: {
_pos_sp_triplet_published_invalid_once = false;
const bool rtl_activated = _previous_nav_state != vehicle_status_s::NAVIGATION_STATE_AUTO_RTL;
switch (rtl_type()) {
case RTL::RTL_LAND:
if (rtl_activated) {
mavlink_and_console_log_info(get_mavlink_log_pub(), "RTL LAND activated");
}
// if RTL is set to use a mission landing and mission has a planned landing, then use MISSION to fly there directly
if (on_mission_landing() && !get_land_detected()->landed) {
_mission.set_execution_mode(mission_result_s::MISSION_EXECUTION_MODE_FAST_FORWARD);
navigation_mode_new = &_mission;
} else {
navigation_mode_new = &_rtl;
}
break;
case RTL::RTL_MISSION:
if (_mission.get_land_start_available() && !get_land_detected()->landed) {
// the mission contains a landing spot
_mission.set_execution_mode(mission_result_s::MISSION_EXECUTION_MODE_FAST_FORWARD);
if (_navigation_mode != &_mission) {
if (_navigation_mode == nullptr) {
// switching from an manual mode, go to landing if not already landing
if (!on_mission_landing()) {
start_mission_landing();
}
} else {
// switching from an auto mode, continue the mission from the closest item
_mission.set_closest_item_as_current();
}
}
if (rtl_activated) {
mavlink_and_console_log_info(get_mavlink_log_pub(), "RTL Mission activated, continue mission");
}
navigation_mode_new = &_mission;
} else {
// fly the mission in reverse if switching from a non-manual mode
_mission.set_execution_mode(mission_result_s::MISSION_EXECUTION_MODE_REVERSE);
if ((_navigation_mode != nullptr && (_navigation_mode != &_rtl || _mission.get_mission_changed())) &&
(! _mission.get_mission_finished()) &&
(!get_land_detected()->landed)) {
// determine the closest mission item if switching from a non-mission mode, and we are either not already
// mission mode or the mission waypoints changed.
// The seconds condition is required so that when no mission was uploaded and one is available the closest
// mission item is determined and also that if the user changes the active mission index while rtl is active
// always that waypoint is tracked first.
if ((_navigation_mode != &_mission) && (rtl_activated || _mission.get_mission_waypoints_changed())) {
_mission.set_closest_item_as_current();
}
if (rtl_activated) {
mavlink_and_console_log_info(get_mavlink_log_pub(), "RTL Mission activated, fly mission in reverse");
}
navigation_mode_new = &_mission;
} else {
if (rtl_activated) {
mavlink_and_console_log_info(get_mavlink_log_pub(), "RTL Mission activated, fly to home");
}
navigation_mode_new = &_rtl;
}
}
break;
default:
if (rtl_activated) {
mavlink_and_console_log_info(get_mavlink_log_pub(), "RTL HOME activated");
}
navigation_mode_new = &_rtl;
break;
}
break;
}
case vehicle_status_s::NAVIGATION_STATE_AUTO_TAKEOFF:
_pos_sp_triplet_published_invalid_once = false;
navigation_mode_new = &_takeoff;
break;
case vehicle_status_s::NAVIGATION_STATE_AUTO_LAND:
_pos_sp_triplet_published_invalid_once = false;
navigation_mode_new = &_land;
break;
case vehicle_status_s::NAVIGATION_STATE_AUTO_PRECLAND:
_pos_sp_triplet_published_invalid_once = false;
navigation_mode_new = &_precland;
_precland.set_mode(PrecLandMode::Required);
break;
case vehicle_status_s::NAVIGATION_STATE_DESCEND:
_pos_sp_triplet_published_invalid_once = false;
navigation_mode_new = &_land;
break;
case vehicle_status_s::NAVIGATION_STATE_AUTO_RTGS:
_pos_sp_triplet_published_invalid_once = false;
navigation_mode_new = &_dataLinkLoss;
break;
case vehicle_status_s::NAVIGATION_STATE_AUTO_LANDENGFAIL:
_pos_sp_triplet_published_invalid_once = false;
navigation_mode_new = &_engineFailure;
break;
case vehicle_status_s::NAVIGATION_STATE_AUTO_LANDGPSFAIL:
_pos_sp_triplet_published_invalid_once = false;
navigation_mode_new = &_gpsFailure;
break;
case vehicle_status_s::NAVIGATION_STATE_AUTO_FOLLOW_TARGET:
_pos_sp_triplet_published_invalid_once = false;
navigation_mode_new = &_follow_target;
break;
case vehicle_status_s::NAVIGATION_STATE_MANUAL:
case vehicle_status_s::NAVIGATION_STATE_ACRO:
case vehicle_status_s::NAVIGATION_STATE_ALTCTL:
case vehicle_status_s::NAVIGATION_STATE_POSCTL:
case vehicle_status_s::NAVIGATION_STATE_TERMINATION:
case vehicle_status_s::NAVIGATION_STATE_OFFBOARD:
case vehicle_status_s::NAVIGATION_STATE_STAB:
default:
_pos_sp_triplet_published_invalid_once = false;
navigation_mode_new = nullptr;
_can_loiter_at_sp = false;
break;
}
// update the vehicle status
_previous_nav_state = _vstatus.nav_state;
/* we have a new navigation mode: reset triplet */
if (_navigation_mode != navigation_mode_new) {
// We don't reset the triplet if we just did an auto-takeoff and are now
// going to loiter. Otherwise, we lose the takeoff altitude and end up lower
// than where we wanted to go.
//
// FIXME: a better solution would be to add reset where they are needed and remove
// this general reset here.
if (!(_navigation_mode == &_takeoff &&
navigation_mode_new == &_loiter)) {
reset_triplets();
}
}
_navigation_mode = navigation_mode_new;
/* iterate through navigation modes and set active/inactive for each */
for (unsigned int i = 0; i < NAVIGATOR_MODE_ARRAY_SIZE; i++) {
_navigation_mode_array[i]->run(_navigation_mode == _navigation_mode_array[i]);
}
/* if we landed and have not received takeoff setpoint then stay in idle */
if (_land_detected.landed &&
!((_vstatus.nav_state == vehicle_status_s::NAVIGATION_STATE_AUTO_TAKEOFF)
|| (_vstatus.nav_state == vehicle_status_s::NAVIGATION_STATE_AUTO_MISSION))) {
_pos_sp_triplet.current.type = position_setpoint_s::SETPOINT_TYPE_IDLE;
_pos_sp_triplet.current.valid = true;
_pos_sp_triplet.previous.valid = false;
_pos_sp_triplet.next.valid = false;
}
/* if nothing is running, set position setpoint triplet invalid once */
if (_navigation_mode == nullptr && !_pos_sp_triplet_published_invalid_once) {
_pos_sp_triplet_published_invalid_once = true;
reset_triplets();
}
if (_pos_sp_triplet_updated) {
_pos_sp_triplet.timestamp = hrt_absolute_time();
publish_position_setpoint_triplet();
_pos_sp_triplet_updated = false;
}
if (_mission_result_updated) {
publish_mission_result();
_mission_result_updated = false;
}
perf_end(_loop_perf);
}
orb_unsubscribe(_global_pos_sub);
orb_unsubscribe(_local_pos_sub);
orb_unsubscribe(_gps_pos_sub);
orb_unsubscribe(_fw_pos_ctrl_status_sub);
orb_unsubscribe(_vstatus_sub);
orb_unsubscribe(_land_detected_sub);
orb_unsubscribe(_home_pos_sub);
orb_unsubscribe(_offboard_mission_sub);
orb_unsubscribe(_param_update_sub);
orb_unsubscribe(_vehicle_command_sub);
}
int Navigator::task_spawn(int argc, char *argv[])
{
_task_id = px4_task_spawn_cmd("navigator",
SCHED_DEFAULT,
SCHED_PRIORITY_NAVIGATION,
1800,
(px4_main_t)&run_trampoline,
(char *const *)argv);
if (_task_id < 0) {
_task_id = -1;
return -errno;
}
return 0;
}
Navigator *Navigator::instantiate(int argc, char *argv[])
{
Navigator *instance = new Navigator();
if (instance == nullptr) {
PX4_ERR("alloc failed");
}
return instance;
}
int
Navigator::print_status()
{
PX4_INFO("Running");
_geofence.printStatus();
return 0;
}
void
Navigator::publish_position_setpoint_triplet()
{
/* do not publish an empty triplet */
if (!_pos_sp_triplet.current.valid) {
return;
}
/* lazily publish the position setpoint triplet only once available */
if (_pos_sp_triplet_pub != nullptr) {
orb_publish(ORB_ID(position_setpoint_triplet), _pos_sp_triplet_pub, &_pos_sp_triplet);
} else {
_pos_sp_triplet_pub = orb_advertise(ORB_ID(position_setpoint_triplet), &_pos_sp_triplet);
}
}
float
Navigator::get_default_acceptance_radius()
{
return _param_acceptance_radius.get();
}
float
Navigator::get_acceptance_radius()
{
return get_acceptance_radius(_param_acceptance_radius.get());
}
float
Navigator::get_altitude_acceptance_radius()
{
if (!get_vstatus()->is_rotary_wing) {
return _param_fw_alt_acceptance_radius.get();
} else {
return _param_mc_alt_acceptance_radius.get();
}
}
float
Navigator::get_cruising_speed()
{
/* there are three options: The mission-requested cruise speed, or the current hover / plane speed */
if (_vstatus.is_rotary_wing) {
if (is_planned_mission() && _mission_cruising_speed_mc > 0.0f) {
return _mission_cruising_speed_mc;
} else {
return -1.0f;
}
} else {
if (is_planned_mission() && _mission_cruising_speed_fw > 0.0f) {
return _mission_cruising_speed_fw;
} else {
return -1.0f;
}
}
}
void
Navigator::set_cruising_speed(float speed)
{
if (_vstatus.is_rotary_wing) {
_mission_cruising_speed_mc = speed;
} else {
_mission_cruising_speed_fw = speed;
}
}
void
Navigator::reset_cruising_speed()
{
_mission_cruising_speed_mc = -1.0f;
_mission_cruising_speed_fw = -1.0f;
}
void
Navigator::reset_triplets()
{
_pos_sp_triplet.current.valid = false;
_pos_sp_triplet.previous.valid = false;
_pos_sp_triplet.next.valid = false;
_pos_sp_triplet_updated = true;
}
float
Navigator::get_cruising_throttle()
{
/* Return the mission-requested cruise speed, or default FW_THR_CRUISE value */
if (_mission_throttle > FLT_EPSILON) {
return _mission_throttle;
} else {
return -1.0f;
}
}
float
Navigator::get_acceptance_radius(float mission_item_radius)
{
float radius = mission_item_radius;
// XXX only use navigation capabilities for now
// when in fixed wing mode
// this might need locking against a commanded transition
// so that a stale _vstatus doesn't trigger an accepted mission item.
if (!_vstatus.is_rotary_wing && !_vstatus.in_transition_mode) {
if ((hrt_elapsed_time(&_fw_pos_ctrl_status.timestamp) < 5000000) && (_fw_pos_ctrl_status.turn_distance > radius)) {
radius = _fw_pos_ctrl_status.turn_distance;
}
}
return radius;
}
void
Navigator::load_fence_from_file(const char *filename)
{
_geofence.loadFromFile(filename);
}
/**
* Creates a fake traffic measurement with supplied parameters.
*
*/
void Navigator::fake_traffic(const char *callsign, float distance, float direction, float traffic_heading,
float altitude_diff, float hor_velocity, float ver_velocity)
{
double lat, lon;
waypoint_from_heading_and_distance(get_global_position()->lat, get_global_position()->lon, direction, distance, &lat,
&lon);
float alt = get_global_position()->alt + altitude_diff;
// float vel_n = get_global_position()->vel_n;
// float vel_e = get_global_position()->vel_e;
// float vel_d = get_global_position()->vel_d;
transponder_report_s tr = {};
tr.timestamp = hrt_absolute_time();
tr.ICAO_address = 1234;
tr.lat = lat; // Latitude, expressed as degrees
tr.lon = lon; // Longitude, expressed as degrees
tr.altitude_type = 0;
tr.altitude = alt;
tr.heading = traffic_heading; //-atan2(vel_e, vel_n); // Course over ground in radians
tr.hor_velocity = hor_velocity; //sqrtf(vel_e * vel_e + vel_n * vel_n); // The horizontal velocity in m/s
tr.ver_velocity = ver_velocity; //-vel_d; // The vertical velocity in m/s, positive is up
strncpy(&tr.callsign[0], callsign, sizeof(tr.callsign) - 1);
tr.callsign[sizeof(tr.callsign) - 1] = 0;
tr.emitter_type = 0; // Type from ADSB_EMITTER_TYPE enum
tr.tslc = 2; // Time since last communication in seconds
tr.flags = transponder_report_s::PX4_ADSB_FLAGS_VALID_COORDS | transponder_report_s::PX4_ADSB_FLAGS_VALID_HEADING |
transponder_report_s::PX4_ADSB_FLAGS_VALID_VELOCITY |
transponder_report_s::PX4_ADSB_FLAGS_VALID_ALTITUDE |
transponder_report_s::PX4_ADSB_FLAGS_VALID_CALLSIGN; // Flags to indicate various statuses including valid data fields
tr.squawk = 6667;
orb_advert_t h = orb_advertise_queue(ORB_ID(transponder_report), &tr, transponder_report_s::ORB_QUEUE_LENGTH);
(void)orb_unadvertise(h);
}
void Navigator::check_traffic()
{
double lat = get_global_position()->lat;
double lon = get_global_position()->lon;
float alt = get_global_position()->alt;
// TODO for non-multirotors predicting the future
// position as accurately as possible will become relevant
// float vel_n = get_global_position()->vel_n;
// float vel_e = get_global_position()->vel_e;
// float vel_d = get_global_position()->vel_d;
bool changed;
orb_check(_traffic_sub, &changed);
float horizontal_separation = 500;
float vertical_separation = 500;
while (changed) {
transponder_report_s tr;
orb_copy(ORB_ID(transponder_report), _traffic_sub, &tr);
uint16_t required_flags = transponder_report_s::PX4_ADSB_FLAGS_VALID_COORDS |
transponder_report_s::PX4_ADSB_FLAGS_VALID_HEADING |
transponder_report_s::PX4_ADSB_FLAGS_VALID_VELOCITY | transponder_report_s::PX4_ADSB_FLAGS_VALID_ALTITUDE;
if ((tr.flags & required_flags) != required_flags) {
orb_check(_traffic_sub, &changed);
continue;
}
float d_hor, d_vert;
get_distance_to_point_global_wgs84(lat, lon, alt,
tr.lat, tr.lon, tr.altitude, &d_hor, &d_vert);
// predict final altitude (positive is up) in prediction time frame
float end_alt = tr.altitude + (d_vert / tr.hor_velocity) * tr.ver_velocity;
// Predict until the vehicle would have passed this system at its current speed
float prediction_distance = d_hor + 1000.0f;
// If the altitude is not getting close to us, do not calculate
// the horizontal separation.
// Since commercial flights do most of the time keep flight levels
// check for the current and for the predicted flight level.
// we also make the implicit assumption that this system is on the lowest
// flight level close to ground in the
// (end_alt - horizontal_separation < alt) condition. If this system should
// ever be used in normal airspace this implementation would anyway be
// inappropriate as it should be replaced with a TCAS compliant solution.
if ((fabsf(alt - tr.altitude) < vertical_separation) || ((end_alt - horizontal_separation) < alt)) {
double end_lat, end_lon;
waypoint_from_heading_and_distance(tr.lat, tr.lon, tr.heading, prediction_distance, &end_lat, &end_lon);
struct crosstrack_error_s cr;
if (!get_distance_to_line(&cr, lat, lon, tr.lat, tr.lon, end_lat, end_lon)) {
if (!cr.past_end && (fabsf(cr.distance) < horizontal_separation)) {
// direction of traffic in human-readable 0..360 degree in earth frame
int traffic_direction = math::degrees(tr.heading) + 180;
switch (_param_traffic_avoidance_mode.get()) {
case 0: {
/* ignore */
PX4_WARN("TRAFFIC %s, hdg: %d", tr.flags & transponder_report_s::PX4_ADSB_FLAGS_VALID_CALLSIGN ? tr.callsign :
"unknown",
traffic_direction);
break;
}
case 1: {
mavlink_log_critical(&_mavlink_log_pub, "WARNING TRAFFIC %s at heading %d, land immediately",
tr.flags & transponder_report_s::PX4_ADSB_FLAGS_VALID_CALLSIGN ? tr.callsign : "unknown",
traffic_direction);
break;
}
case 2: {
mavlink_log_critical(&_mavlink_log_pub, "AVOIDING TRAFFIC %s heading %d, returning home",
tr.flags & transponder_report_s::PX4_ADSB_FLAGS_VALID_CALLSIGN ? tr.callsign : "unknown",
traffic_direction);
// set the return altitude to minimum
_rtl.set_return_alt_min(true);
// ask the commander to execute an RTL
vehicle_command_s vcmd = {};
vcmd.command = vehicle_command_s::VEHICLE_CMD_NAV_RETURN_TO_LAUNCH;
publish_vehicle_cmd(&vcmd);
break;
}
}
}
}
}
orb_check(_traffic_sub, &changed);
}
}
bool
Navigator::abort_landing()
{
bool should_abort = false;
if (!_vstatus.is_rotary_wing && !_vstatus.in_transition_mode) {
if (hrt_elapsed_time(&_fw_pos_ctrl_status.timestamp) < 1000000) {
if (get_position_setpoint_triplet()->current.valid
&& get_position_setpoint_triplet()->current.type == position_setpoint_s::SETPOINT_TYPE_LAND) {
should_abort = _fw_pos_ctrl_status.abort_landing;
}
}
}
return should_abort;
}
bool
Navigator::force_vtol()
{
return _vstatus.is_vtol &&
(!_vstatus.is_rotary_wing || _vstatus.in_transition_to_fw)
&& _param_force_vtol.get();
}
int Navigator::print_usage(const char *reason)
{
if (reason) {
PX4_WARN("%s\n", reason);
}
PRINT_MODULE_DESCRIPTION(
R"DESCR_STR(
### Description
Module that is responsible for autonomous flight modes. This includes missions (read from dataman),
takeoff and RTL.
It is also responsible for geofence violation checking.
### Implementation
The different internal modes are implemented as separate classes that inherit from a common base class `NavigatorMode`.
The member `_navigation_mode` contains the current active mode.
Navigator publishes position setpoint triplets (`position_setpoint_triplet_s`), which are then used by the position
controller.
)DESCR_STR");
PRINT_MODULE_USAGE_NAME("navigator", "controller");
PRINT_MODULE_USAGE_COMMAND("start");
PRINT_MODULE_USAGE_COMMAND_DESCR("fencefile", "load a geofence file from SD card, stored at etc/geofence.txt");
PRINT_MODULE_USAGE_COMMAND_DESCR("fake_traffic", "publishes 3 fake transponder_report_s uORB messages");
PRINT_MODULE_USAGE_DEFAULT_COMMANDS();
return 0;
}
int Navigator::custom_command(int argc, char *argv[])
{
if (!is_running()) {
print_usage("not running");
return 1;
}
if (!strcmp(argv[0], "fencefile")) {
get_instance()->load_fence_from_file(GEOFENCE_FILENAME);
return 0;
} else if (!strcmp(argv[0], "fake_traffic")) {
get_instance()->fake_traffic("LX007", 500, 1.0f, -1.0f, 100.0f, 90.0f, 0.001f);
get_instance()->fake_traffic("LX55", 1000, 0, 0, 100.0f, 90.0f, 0.001f);
get_instance()->fake_traffic("LX20", 15000, 1.0f, -1.0f, 280.0f, 90.0f, 0.001f);
return 0;
}
return print_usage("unknown command");
}
int navigator_main(int argc, char *argv[])
{
return Navigator::main(argc, argv);
}
void
Navigator::publish_mission_result()
{
_mission_result.timestamp = hrt_absolute_time();
/* lazily publish the mission result only once available */
if (_mission_result_pub != nullptr) {
/* publish mission result */
orb_publish(ORB_ID(mission_result), _mission_result_pub, &_mission_result);
} else {
/* advertise and publish */
_mission_result_pub = orb_advertise(ORB_ID(mission_result), &_mission_result);
}
/* reset some of the flags */
_mission_result.item_do_jump_changed = false;
_mission_result.item_changed_index = 0;
_mission_result.item_do_jump_remaining = 0;
}
void
Navigator::publish_geofence_result()
{
/* lazily publish the geofence result only once available */
if (_geofence_result_pub != nullptr) {
/* publish mission result */
orb_publish(ORB_ID(geofence_result), _geofence_result_pub, &_geofence_result);
} else {
/* advertise and publish */
_geofence_result_pub = orb_advertise(ORB_ID(geofence_result), &_geofence_result);
}
}
void
Navigator::set_mission_failure(const char *reason)
{
if (!_mission_result.failure) {
_mission_result.failure = true;
set_mission_result_updated();
mavlink_log_critical(&_mavlink_log_pub, "%s", reason);
}
}
void
Navigator::publish_vehicle_cmd(vehicle_command_s *vcmd)
{
vcmd->timestamp = hrt_absolute_time();
vcmd->source_system = _vstatus.system_id;
vcmd->source_component = _vstatus.component_id;
vcmd->target_system = _vstatus.system_id;
vcmd->confirmation = false;
vcmd->from_external = false;
// The camera commands are not processed on the autopilot but will be
// sent to the mavlink links to other components.
switch (vcmd->command) {
case NAV_CMD_IMAGE_START_CAPTURE:
case NAV_CMD_IMAGE_STOP_CAPTURE:
case NAV_CMD_VIDEO_START_CAPTURE:
case NAV_CMD_VIDEO_STOP_CAPTURE:
vcmd->target_component = 100; // MAV_COMP_ID_CAMERA
break;
default:
vcmd->target_component = _vstatus.component_id;
break;
}
if (_vehicle_cmd_pub != nullptr) {
orb_publish(ORB_ID(vehicle_command), _vehicle_cmd_pub, vcmd);
} else {
_vehicle_cmd_pub = orb_advertise_queue(ORB_ID(vehicle_command), vcmd, vehicle_command_s::ORB_QUEUE_LENGTH);
}
}
void
Navigator::publish_vehicle_command_ack(const vehicle_command_s &cmd, uint8_t result)
{
vehicle_command_ack_s command_ack = {};
command_ack.timestamp = hrt_absolute_time();
command_ack.command = cmd.command;
command_ack.target_system = cmd.source_system;
command_ack.target_component = cmd.source_component;
command_ack.from_external = false;
command_ack.result = result;
command_ack.result_param1 = 0;
command_ack.result_param2 = 0;
if (_vehicle_cmd_ack_pub != nullptr) {
orb_publish(ORB_ID(vehicle_command_ack), _vehicle_cmd_ack_pub, &command_ack);
} else {
_vehicle_cmd_ack_pub = orb_advertise_queue(ORB_ID(vehicle_command_ack), &command_ack,
vehicle_command_ack_s::ORB_QUEUE_LENGTH);
}
}
| [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
] | [
[
[
1,
2
],
[
4,
33
],
[
35,
35
],
[
44,
45
],
[
62,
62
],
[
65,
65
],
[
71,
77
],
[
79,
84
],
[
87,
87
],
[
100,
100
],
[
109,
110
],
[
113,
114
],
[
119,
120
],
[
134,
134
],
[
139,
139
],
[
178,
178
],
[
180,
182
],
[
193,
193
],
[
196,
197
],
[
202,
202
],
[
211,
211
],
[
215,
215
],
[
217,
218
],
[
220,
220
],
[
228,
228
],
[
230,
231
],
[
233,
234
],
[
239,
239
],
[
241,
241
],
[
246,
250
],
[
253,
253
],
[
255,
255
],
[
275,
275
],
[
277,
277
],
[
282,
282
],
[
284,
284
],
[
296,
296
],
[
298,
299
],
[
303,
303
],
[
305,
305
],
[
310,
310
],
[
312,
312
],
[
314,
315
],
[
323,
323
],
[
326,
335
],
[
338,
341
],
[
343,
347
],
[
369,
369
],
[
371,
378
],
[
382,
382
],
[
384,
393
],
[
414,
418
],
[
513,
515
],
[
520,
520
],
[
528,
528
],
[
530,
530
],
[
552,
552
],
[
742,
742
],
[
775,
776
],
[
803,
803
],
[
805,
806
],
[
808,
808
],
[
813,
814
],
[
816,
817
],
[
830,
834
],
[
836,
836
],
[
844,
858
],
[
860,
860
],
[
862,
870
],
[
879,
879
],
[
886,
888
],
[
928,
947
],
[
1099,
1107
],
[
1109,
1116
],
[
1131,
1131
],
[
1138,
1138
],
[
1142,
1142
],
[
1145,
1145
],
[
1147,
1147
],
[
1153,
1153
],
[
1156,
1156
],
[
1163,
1163
],
[
1173,
1174
],
[
1181,
1181
],
[
1189,
1189
],
[
1208,
1208
]
],
[
[
3,
3
],
[
39,
39
],
[
49,
51
],
[
68,
68
],
[
111,
112
],
[
121,
126
],
[
175,
175
],
[
184,
184
],
[
188,
188
],
[
194,
194
],
[
200,
200
],
[
203,
203
],
[
209,
209
],
[
224,
224
],
[
229,
229
],
[
237,
237
],
[
265,
266
],
[
272,
273
],
[
313,
313
],
[
324,
325
],
[
348,
349
],
[
353,
368
],
[
370,
370
],
[
383,
383
],
[
394,
402
],
[
421,
425
],
[
428,
428
],
[
434,
435
],
[
437,
437
],
[
443,
462
],
[
468,
471
],
[
473,
481
],
[
485,
488
],
[
492,
496
],
[
516,
518
],
[
523,
523
],
[
525,
525
],
[
677,
682
],
[
727,
736
],
[
761,
761
],
[
778,
787
],
[
789,
789
],
[
822,
822
],
[
871,
871
],
[
873,
878
],
[
881,
885
],
[
889,
889
],
[
892,
915
],
[
920,
920
],
[
924,
924
],
[
952,
977
],
[
980,
1098
],
[
1167,
1167
],
[
1186,
1186
],
[
1270,
1270
]
],
[
[
34,
34
],
[
36,
37
],
[
41,
41
],
[
70,
70
],
[
88,
88
],
[
115,
118
],
[
142,
144
],
[
146,
146
],
[
153,
158
],
[
164,
174
],
[
176,
177
],
[
191,
192
],
[
198,
199
],
[
201,
201
],
[
205,
205
],
[
207,
208
],
[
213,
213
],
[
221,
221
],
[
235,
236
],
[
274,
274
],
[
278,
280
],
[
285,
289
],
[
291,
294
],
[
300,
300
],
[
306,
308
],
[
539,
539
],
[
554,
554
],
[
720,
721
],
[
744,
745
],
[
762,
763
],
[
827,
827
],
[
829,
829
],
[
838,
839
],
[
841,
843
],
[
1117,
1117
]
],
[
[
38,
38
],
[
40,
40
],
[
42,
42
],
[
85,
85
],
[
159,
159
],
[
161,
163
],
[
186,
187
],
[
204,
204
],
[
281,
281
],
[
295,
295
],
[
302,
302
],
[
538,
538
],
[
553,
553
],
[
557,
557
],
[
743,
743
],
[
764,
764
],
[
766,
769
],
[
826,
826
],
[
828,
828
],
[
835,
835
],
[
837,
837
],
[
840,
840
]
],
[
[
43,
43
],
[
78,
78
],
[
105,
108
],
[
127,
132
],
[
160,
160
],
[
183,
183
],
[
185,
185
],
[
189,
190
],
[
195,
195
],
[
206,
206
],
[
210,
210
],
[
214,
214
],
[
251,
252
],
[
256,
256
],
[
258,
262
],
[
519,
519
],
[
526,
527
],
[
533,
534
],
[
536,
537
],
[
540,
541
],
[
543,
544
],
[
547,
549
],
[
948,
951
],
[
1182,
1185
],
[
1188,
1188
],
[
1190,
1196
],
[
1202,
1203
]
],
[
[
46,
48
],
[
52,
54
],
[
56,
56
],
[
60,
61
],
[
63,
64
],
[
66,
67
],
[
69,
69
],
[
147,
149
],
[
151,
152
],
[
219,
219
],
[
222,
223
],
[
243,
244
],
[
263,
264
],
[
267,
271
],
[
309,
309
],
[
316,
322
],
[
350,
352
],
[
380,
381
],
[
403,
406
],
[
408,
413
],
[
419,
420
],
[
426,
427
],
[
429,
433
],
[
436,
436
],
[
438,
442
],
[
463,
466
],
[
472,
472
],
[
497,
512
],
[
529,
529
],
[
546,
546
],
[
550,
551
],
[
578,
578
],
[
580,
580
],
[
586,
586
],
[
859,
859
],
[
872,
872
],
[
880,
880
],
[
1218,
1260
],
[
1262,
1262
],
[
1264,
1269
],
[
1271,
1281
]
],
[
[
55,
55
],
[
136,
138
],
[
140,
141
],
[
145,
145
],
[
150,
150
],
[
212,
212
],
[
240,
240
],
[
254,
254
],
[
257,
257
],
[
276,
276
],
[
283,
283
],
[
290,
290
],
[
297,
297
],
[
304,
304
],
[
311,
311
],
[
336,
337
],
[
342,
342
],
[
379,
379
],
[
407,
407
],
[
467,
467
],
[
521,
522
],
[
524,
524
],
[
531,
532
],
[
542,
542
],
[
555,
556
],
[
558,
577
],
[
579,
579
],
[
581,
585
],
[
587,
676
],
[
683,
719
],
[
722,
726
],
[
737,
740
],
[
777,
777
],
[
861,
861
],
[
890,
891
],
[
922,
922
],
[
1108,
1108
],
[
1118,
1125
]
],
[
[
57,
57
]
],
[
[
58,
59
],
[
916,
919
],
[
921,
921
],
[
923,
923
],
[
925,
927
],
[
1161,
1162
]
],
[
[
86,
86
],
[
89,
99
],
[
179,
179
],
[
216,
216
],
[
225,
227
],
[
238,
238
],
[
242,
242
],
[
245,
245
],
[
482,
484
],
[
489,
491
],
[
765,
765
],
[
788,
788
],
[
790,
802
],
[
804,
804
],
[
807,
807
],
[
809,
812
],
[
815,
815
],
[
818,
819
],
[
821,
821
],
[
823,
824
],
[
978,
979
],
[
1126,
1126
],
[
1128,
1129
],
[
1132,
1137
],
[
1139,
1141
],
[
1143,
1144
],
[
1146,
1146
],
[
1148,
1152
],
[
1154,
1155
],
[
1157,
1160
],
[
1164,
1166
],
[
1168,
1172
],
[
1175,
1180
]
],
[
[
101,
104
],
[
741,
741
]
],
[
[
133,
133
],
[
135,
135
],
[
232,
232
],
[
301,
301
],
[
820,
820
],
[
825,
825
],
[
1127,
1127
],
[
1130,
1130
]
],
[
[
535,
535
],
[
545,
545
],
[
770,
774
],
[
1197,
1201
],
[
1204,
1207
],
[
1209,
1217
]
],
[
[
746,
757
]
],
[
[
758,
760
]
],
[
[
1187,
1187
]
],
[
[
1261,
1261
],
[
1263,
1263
],
[
1282,
1283
]
]
] |
1b1519b8aa7010ebed238d0febf8fa065da32184 | 66e9d4ade105ca25ccaeece17b63831aaf133e7d | /components/browser_sync/profile_sync_service_autofill_unittest.cc | 20bbd9d22e3b4dcae61fc6c1a3e0f6e027b0479d | [
"BSD-3-Clause"
] | permissive | rookiechao/chromium | 17eed8364b9f369d35ca62ff380a7c5d55c5f810 | 2cd605c5bfcb7672fd6f4cae7400ec62308f3c2f | refs/heads/master | 2023-03-07T20:13:33.287402 | 2019-04-04T09:48:01 | 2019-04-04T09:48:01 | 178,987,904 | 1 | 0 | NOASSERTION | 2019-04-02T03:00:16 | 2019-04-02T03:00:16 | null | UTF-8 | C++ | false | false | 43,200 | cc | // Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stddef.h>
#include <stdint.h>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/location.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/run_loop.h"
#include "base/sequenced_task_runner.h"
#include "base/strings/string16.h"
#include "base/strings/utf_string_conversions.h"
#include "base/synchronization/waitable_event.h"
#include "base/test/bind_test_util.h"
#include "base/threading/thread.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "components/autofill/core/browser/autofill_test_utils.h"
#include "components/autofill/core/browser/country_names.h"
#include "components/autofill/core/browser/field_types.h"
#include "components/autofill/core/browser/personal_data_manager.h"
#include "components/autofill/core/browser/webdata/autofill_change.h"
#include "components/autofill/core/browser/webdata/autofill_profile_data_type_controller.h"
#include "components/autofill/core/browser/webdata/autofill_profile_syncable_service.h"
#include "components/autofill/core/browser/webdata/autofill_table.h"
#include "components/autofill/core/browser/webdata/autofill_webdata_service.h"
#include "components/autofill/core/common/autofill_prefs.h"
#include "components/browser_sync/abstract_profile_sync_service_test.h"
#include "components/sync/base/model_type.h"
#include "components/sync/driver/data_type_controller.h"
#include "components/sync/driver/data_type_manager_impl.h"
#include "components/sync/driver/profile_sync_service.h"
#include "components/sync/driver/sync_api_component_factory_mock.h"
#include "components/sync/driver/sync_client_mock.h"
#include "components/sync/driver/test_profile_sync_service.h"
#include "components/sync/engine/data_type_debug_info_listener.h"
#include "components/sync/engine/sequenced_model_worker.h"
#include "components/sync/protocol/autofill_specifics.pb.h"
#include "components/sync/syncable/mutable_entry.h"
#include "components/sync/syncable/read_node.h"
#include "components/sync/syncable/read_transaction.h"
#include "components/sync/syncable/syncable_write_transaction.h"
#include "components/sync/syncable/write_node.h"
#include "components/sync/syncable/write_transaction.h"
#include "components/sync_preferences/pref_service_syncable.h"
#include "components/version_info/version_info.h"
#include "components/webdata/common/web_database.h"
#include "components/webdata_services/web_data_service_test_util.h"
#include "services/identity/public/cpp/identity_test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using autofill::AutofillChange;
using autofill::AutofillChangeList;
using autofill::AutofillKey;
using autofill::AutofillProfile;
using autofill::AutofillProfileChange;
using autofill::AutofillProfileSyncableService;
using autofill::AutofillTable;
using autofill::AutofillWebDataService;
using autofill::NAME_FULL;
using autofill::PersonalDataManager;
using autofill::ServerFieldType;
using base::ASCIIToUTF16;
using base::Time;
using base::TimeDelta;
using base::WaitableEvent;
using syncer::AUTOFILL_PROFILE;
using syncer::BaseNode;
using syncer::syncable::CREATE;
using syncer::syncable::GET_TYPE_ROOT;
using syncer::syncable::MutableEntry;
using syncer::syncable::UNITTEST;
using syncer::syncable::WriterTag;
using syncer::syncable::WriteTransaction;
using testing::_;
using testing::ByMove;
using testing::DoAll;
using testing::ElementsAre;
using testing::Not;
using testing::Return;
using testing::SetArgPointee;
namespace browser_sync {
namespace {
void RegisterAutofillPrefs(user_prefs::PrefRegistrySyncable* registry) {
registry->RegisterBooleanPref(autofill::prefs::kAutofillCreditCardEnabled,
true);
registry->RegisterBooleanPref(autofill::prefs::kAutofillProfileEnabled, true);
registry->RegisterBooleanPref(autofill::prefs::kAutofillWalletImportEnabled,
true);
registry->RegisterIntegerPref(autofill::prefs::kAutofillLastVersionDeduped,
atoi(version_info::GetVersionNumber().c_str()));
registry->RegisterIntegerPref(autofill::prefs::kAutofillLastVersionValidated,
atoi(version_info::GetVersionNumber().c_str()));
registry->RegisterBooleanPref(
autofill::prefs::kAutofillJapanCityFieldMigrated, true);
registry->RegisterBooleanPref(autofill::prefs::kAutofillOrphanRowsRemoved,
true);
registry->RegisterIntegerPref(
autofill::prefs::kAutofillLastVersionDisusedAddressesDeleted, 0);
registry->RegisterIntegerPref(
autofill::prefs::kAutofillLastVersionDisusedCreditCardsDeleted, 0);
registry->RegisterStringPref(
autofill::prefs::kAutofillProfileValidity, "",
user_prefs::PrefRegistrySyncable::SYNCABLE_PRIORITY_PREF);
}
void RunAndSignal(base::OnceClosure cb, WaitableEvent* event) {
std::move(cb).Run();
event->Signal();
}
} // namespace
class AutofillTableMock : public AutofillTable {
public:
AutofillTableMock() {}
MOCK_METHOD2(RemoveFormElement,
bool(const base::string16& name,
const base::string16& value)); // NOLINT
MOCK_METHOD4(GetAutofillTimestamps,
bool(const base::string16& name, // NOLINT
const base::string16& value,
Time* date_created,
Time* date_last_used));
MOCK_METHOD1(GetAutofillProfiles,
bool(std::vector<std::unique_ptr<AutofillProfile>>*)); // NOLINT
MOCK_METHOD1(UpdateAutofillProfile, bool(const AutofillProfile&)); // NOLINT
MOCK_METHOD1(AddAutofillProfile, bool(const AutofillProfile&)); // NOLINT
MOCK_METHOD1(RemoveAutofillProfile, bool(const std::string&)); // NOLINT
// TODO(crbug.com/904390): Remove when the investigation is over.
MOCK_CONST_METHOD1(
GetServerProfiles,
bool(std::vector<std::unique_ptr<AutofillProfile>>*)); // NOLINT
};
MATCHER_P(MatchProfiles, profile, "") {
return (profile.Compare(arg) == 0);
}
ACTION_P(LoadAutofillProfiles, datafunc) {
std::vector<std::unique_ptr<AutofillProfile>> profiles =
std::move(datafunc());
arg0->swap(profiles);
}
class WebDatabaseFake : public WebDatabase {
public:
explicit WebDatabaseFake(AutofillTable* autofill_table) {
AddTable(autofill_table);
}
};
class FakeAutofillBackend : public autofill::AutofillWebDataBackend {
public:
FakeAutofillBackend(
WebDatabase* web_database,
const base::RepeatingClosure& on_changed,
const base::RepeatingCallback<void(syncer::ModelType)>& on_sync_started,
const scoped_refptr<base::SequencedTaskRunner>& ui_task_runner)
: web_database_(web_database),
on_changed_(on_changed),
on_sync_started_(on_sync_started),
ui_task_runner_(ui_task_runner) {}
~FakeAutofillBackend() override {}
WebDatabase* GetDatabase() override { return web_database_; }
void AddObserver(
autofill::AutofillWebDataServiceObserverOnDBSequence* observer) override {
}
void RemoveObserver(
autofill::AutofillWebDataServiceObserverOnDBSequence* observer) override {
}
void CommitChanges() override {}
void RemoveExpiredFormElements() override {}
void NotifyOfAutofillProfileChanged(
const autofill::AutofillProfileChange& change) override {}
void NotifyOfCreditCardChanged(
const autofill::CreditCardChange& change) override {}
void NotifyOfMultipleAutofillChanges() override {
DCHECK(!ui_task_runner_->RunsTasksInCurrentSequence());
ui_task_runner_->PostTask(FROM_HERE, on_changed_);
}
void NotifyThatSyncHasStarted(syncer::ModelType model_type) override {
DCHECK(!ui_task_runner_->RunsTasksInCurrentSequence());
ui_task_runner_->PostTask(FROM_HERE,
base::BindOnce(on_sync_started_, model_type));
}
private:
WebDatabase* web_database_;
base::RepeatingClosure on_changed_;
base::RepeatingCallback<void(syncer::ModelType)> on_sync_started_;
const scoped_refptr<base::SequencedTaskRunner> ui_task_runner_;
};
class ProfileSyncServiceAutofillTest;
class TokenWebDataServiceFake : public TokenWebData {
public:
TokenWebDataServiceFake(
const scoped_refptr<base::SingleThreadTaskRunner>& ui_task_runner,
const scoped_refptr<base::SingleThreadTaskRunner>& db_task_runner)
: TokenWebData(ui_task_runner, db_task_runner) {}
bool IsDatabaseLoaded() override { return true; }
AutofillWebDataService::Handle GetAllTokens(
WebDataServiceConsumer* consumer) override {
// TODO(tim): It would be nice if WebDataService was injected on
// construction of ProfileOAuth2TokenService rather than fetched by
// Initialize so that this isn't necessary (we could pass a null service).
// We currently do return it via EXPECT_CALLs, but without depending on
// order-of-initialization (which seems way more fragile) we can't tell
// which component is asking at what time, and some components in these
// Autofill tests require a WebDataService.
return 0;
}
private:
~TokenWebDataServiceFake() override {}
DISALLOW_COPY_AND_ASSIGN(TokenWebDataServiceFake);
};
class WebDataServiceFake : public AutofillWebDataService {
public:
WebDataServiceFake(
const scoped_refptr<base::SingleThreadTaskRunner>& ui_task_runner,
const scoped_refptr<base::SingleThreadTaskRunner>& db_task_runner)
: AutofillWebDataService(ui_task_runner, db_task_runner),
web_database_(nullptr),
autofill_profile_syncable_service_(nullptr),
syncable_service_created_or_destroyed_(
base::WaitableEvent::ResetPolicy::AUTOMATIC,
base::WaitableEvent::InitialState::NOT_SIGNALED),
db_task_runner_(db_task_runner),
ui_task_runner_(ui_task_runner) {}
void SetDatabase(WebDatabase* web_database) { web_database_ = web_database; }
void StartSyncableService() {
// The |autofill_profile_syncable_service_| must be constructed on the DB
// sequence.
const base::RepeatingClosure& on_changed_callback = base::BindRepeating(
&WebDataServiceFake::NotifyAutofillMultipleChangedOnUISequence,
AsWeakPtr());
const base::RepeatingCallback<void(syncer::ModelType)>&
on_sync_started_callback = base::BindRepeating(
&WebDataServiceFake::NotifySyncStartedOnUISequence, AsWeakPtr());
db_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&WebDataServiceFake::CreateSyncableService,
base::Unretained(this), on_changed_callback,
std::move(on_sync_started_callback)));
syncable_service_created_or_destroyed_.Wait();
}
void ShutdownSyncableService() {
// The |autofill_profile_syncable_service_| must be destructed on the DB
// sequence.
db_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&WebDataServiceFake::DestroySyncableService,
base::Unretained(this)));
syncable_service_created_or_destroyed_.Wait();
}
bool IsDatabaseLoaded() override { return true; }
WebDatabase* GetDatabase() override { return web_database_; }
void OnAutofillProfileChanged(const AutofillProfileChange& changes) {
WaitableEvent event(base::WaitableEvent::ResetPolicy::MANUAL,
base::WaitableEvent::InitialState::NOT_SIGNALED);
base::OnceClosure notify_cb = base::BindOnce(
&AutofillProfileSyncableService::AutofillProfileChanged,
base::Unretained(autofill_profile_syncable_service_), changes);
db_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&RunAndSignal, std::move(notify_cb), &event));
event.Wait();
}
private:
~WebDataServiceFake() override {}
void CreateSyncableService(
const base::RepeatingClosure& on_changed_callback,
const base::RepeatingCallback<void(syncer::ModelType)>& on_sync_started) {
ASSERT_TRUE(db_task_runner_->RunsTasksInCurrentSequence());
// These services are deleted in DestroySyncableService().
backend_ = std::make_unique<FakeAutofillBackend>(
GetDatabase(), on_changed_callback, on_sync_started,
ui_task_runner_.get());
AutofillProfileSyncableService::CreateForWebDataServiceAndBackend(
this, backend_.get(), "en-US");
autofill_profile_syncable_service_ =
AutofillProfileSyncableService::FromWebDataService(this);
syncable_service_created_or_destroyed_.Signal();
}
void DestroySyncableService() {
ASSERT_TRUE(db_task_runner_->RunsTasksInCurrentSequence());
autofill_profile_syncable_service_ = nullptr;
backend_.reset();
syncable_service_created_or_destroyed_.Signal();
}
WebDatabase* web_database_;
AutofillProfileSyncableService* autofill_profile_syncable_service_;
std::unique_ptr<autofill::AutofillWebDataBackend> backend_;
WaitableEvent syncable_service_created_or_destroyed_;
const scoped_refptr<base::SingleThreadTaskRunner> db_task_runner_;
const scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner_;
DISALLOW_COPY_AND_ASSIGN(WebDataServiceFake);
};
ACTION_P(ReturnNewDataTypeManagerWithDebugListener, debug_listener) {
return std::make_unique<syncer::DataTypeManagerImpl>(arg0, debug_listener,
arg2, arg3, arg4, arg5);
}
class MockPersonalDataManager : public PersonalDataManager {
public:
MockPersonalDataManager() : PersonalDataManager("en-US") {}
MOCK_CONST_METHOD0(IsDataLoaded, bool());
MOCK_METHOD0(LoadProfiles, void());
MOCK_METHOD0(LoadCreditCards, void());
MOCK_METHOD0(LoadPaymentsCustomerData, void());
MOCK_METHOD0(Refresh, void());
};
class AddAutofillProfileHelper;
class ProfileSyncServiceAutofillTest
: public AbstractProfileSyncServiceTest,
public syncer::DataTypeDebugInfoListener {
public:
// DataTypeDebugInfoListener implementation.
void OnDataTypeConfigureComplete(
const std::vector<syncer::DataTypeConfigurationStats>&
configuration_stats) override {
for (const syncer::DataTypeConfigurationStats& stat : configuration_stats) {
if (stat.model_type == syncer::AUTOFILL_PROFILE) {
association_stats_ = stat.association_stats;
return;
}
}
ASSERT_TRUE(false) << "Autofill profile type did not get configured!";
}
protected:
ProfileSyncServiceAutofillTest() : debug_ptr_factory_(this) {
autofill::CountryNames::SetLocaleString("en-US");
RegisterAutofillPrefs(
profile_sync_service_bundle()->pref_service()->registry());
data_type_thread()->Start();
web_database_ = std::make_unique<WebDatabaseFake>(&autofill_table_);
web_data_wrapper_ = std::make_unique<MockWebDataServiceWrapper>(
new WebDataServiceFake(base::ThreadTaskRunnerHandle::Get(),
data_type_thread()->task_runner()),
new TokenWebDataServiceFake(base::ThreadTaskRunnerHandle::Get(),
data_type_thread()->task_runner()));
web_data_service_ = static_cast<WebDataServiceFake*>(
web_data_wrapper_->GetProfileAutofillWebData().get());
web_data_service_->SetDatabase(web_database_.get());
personal_data_manager_ = std::make_unique<MockPersonalDataManager>();
EXPECT_CALL(personal_data_manager(), LoadProfiles());
EXPECT_CALL(personal_data_manager(), LoadCreditCards());
EXPECT_CALL(personal_data_manager(), LoadPaymentsCustomerData());
personal_data_manager_->Init(web_data_service_,
/*account_database=*/nullptr,
profile_sync_service_bundle()->pref_service(),
/*identity_manager=*/nullptr,
/*client_profile_validator=*/nullptr,
/*history_service=*/nullptr,
/*is_off_the_record=*/false);
web_data_service_->StartSyncableService();
}
~ProfileSyncServiceAutofillTest() override {
web_data_service_->ShutdownOnUISequence();
web_data_service_->ShutdownSyncableService();
web_data_wrapper_->Shutdown();
web_data_service_ = nullptr;
web_data_wrapper_.reset();
web_database_.reset();
// Shut down the service explicitly before some data members from this
// test it needs will be deleted.
sync_service()->Shutdown();
}
int GetSyncCount() {
syncer::ReadTransaction trans(FROM_HERE, sync_service()->GetUserShare());
syncer::ReadNode node(&trans);
if (node.InitTypeRoot(AUTOFILL_PROFILE) != BaseNode::INIT_OK)
return 0;
return node.GetTotalNodeCount() - 1;
}
void StartAutofillProfileSyncService(base::OnceClosure callback) {
profile_sync_service_bundle()
->identity_test_env()
->MakePrimaryAccountAvailable("[email protected]");
std::unique_ptr<syncer::SyncClientMock> sync_client =
profile_sync_service_bundle()->CreateSyncClientMock();
syncer::SyncClientMock* sync_client_copy = sync_client.get();
CreateSyncService(std::move(sync_client), std::move(callback));
syncer::DataTypeController::TypeVector controllers;
controllers.push_back(std::make_unique<AutofillProfileDataTypeController>(
data_type_thread()->task_runner(), /*dump_stack=*/base::DoNothing(),
sync_service(), sync_client_copy,
base::BindLambdaForTesting([&]() -> autofill::PersonalDataManager* {
return personal_data_manager_.get();
}),
web_data_service_));
ON_CALL(*sync_client_copy, GetSyncableServiceForType(AUTOFILL_PROFILE))
.WillByDefault(testing::Invoke([=](syncer::ModelType) {
return AutofillProfileSyncableService::FromWebDataService(
web_data_service_.get())
->AsWeakPtr();
}));
ON_CALL(*sync_client_copy, CreateDataTypeControllers(_))
.WillByDefault(Return(ByMove(std::move(controllers))));
ON_CALL(*sync_client_copy, CreateModelWorkerForGroup(syncer::GROUP_DB))
.WillByDefault(
Return(base::MakeRefCounted<syncer::SequencedModelWorker>(
data_type_thread()->task_runner(), syncer::GROUP_DB)));
ON_CALL(*profile_sync_service_bundle()->component_factory(),
CreateDataTypeManager(_, _, _, _, _, _))
.WillByDefault(ReturnNewDataTypeManagerWithDebugListener(
syncer::MakeWeakHandle(debug_ptr_factory_.GetWeakPtr())));
EXPECT_CALL(personal_data_manager(), IsDataLoaded())
.WillRepeatedly(Return(true));
sync_service()->Initialize();
base::RunLoop().Run();
// It's possible this test triggered an unrecoverable error, in which case
// we can't get the sync count.
if (sync_service()->IsSyncFeatureActive()) {
EXPECT_EQ(GetSyncCount(),
association_stats_.num_sync_items_after_association);
}
EXPECT_EQ(association_stats_.num_sync_items_after_association,
association_stats_.num_sync_items_before_association +
association_stats_.num_sync_items_added -
association_stats_.num_sync_items_deleted);
}
bool AddAutofillSyncNode(const AutofillProfile& profile) {
syncer::WriteTransaction trans(FROM_HERE, sync_service()->GetUserShare());
syncer::WriteNode node(&trans);
std::string tag = profile.guid();
syncer::WriteNode::InitUniqueByCreationResult result =
node.InitUniqueByCreation(AUTOFILL_PROFILE, tag);
if (result != syncer::WriteNode::INIT_SUCCESS)
return false;
sync_pb::EntitySpecifics specifics;
AutofillProfileSyncableService::WriteAutofillProfile(profile, &specifics);
node.SetEntitySpecifics(specifics);
return true;
}
bool GetAutofillProfilesFromSyncDBUnderProfileNode(
std::vector<AutofillProfile>* profiles) {
syncer::ReadTransaction trans(FROM_HERE, sync_service()->GetUserShare());
syncer::ReadNode autofill_root(&trans);
if (autofill_root.InitTypeRoot(AUTOFILL_PROFILE) != BaseNode::INIT_OK) {
return false;
}
int64_t child_id = autofill_root.GetFirstChildId();
while (child_id != syncer::kInvalidId) {
syncer::ReadNode child_node(&trans);
if (child_node.InitByIdLookup(child_id) != BaseNode::INIT_OK)
return false;
const sync_pb::AutofillProfileSpecifics& autofill(
child_node.GetEntitySpecifics().autofill_profile());
AutofillProfile p;
p.set_guid(autofill.guid());
AutofillProfileSyncableService::OverwriteProfileWithServerData(autofill,
&p);
profiles->push_back(p);
child_id = child_node.GetSuccessorId();
}
return true;
}
void SetIdleChangeProcessorExpectations() {
EXPECT_CALL(autofill_table_, RemoveFormElement(_, _)).Times(0);
EXPECT_CALL(autofill_table_, GetAutofillTimestamps(_, _, _, _)).Times(0);
}
AutofillTableMock& autofill_table() { return autofill_table_; }
MockPersonalDataManager& personal_data_manager() {
return *personal_data_manager_;
}
WebDataServiceFake* web_data_service() { return web_data_service_.get(); }
private:
friend class AddAutofillProfileHelper;
AutofillTableMock autofill_table_;
std::unique_ptr<WebDatabaseFake> web_database_;
std::unique_ptr<MockWebDataServiceWrapper> web_data_wrapper_;
scoped_refptr<WebDataServiceFake> web_data_service_;
std::unique_ptr<MockPersonalDataManager> personal_data_manager_;
syncer::DataTypeAssociationStats association_stats_;
base::WeakPtrFactory<DataTypeDebugInfoListener> debug_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(ProfileSyncServiceAutofillTest);
};
class AddAutofillProfileHelper {
public:
AddAutofillProfileHelper(ProfileSyncServiceAutofillTest* test,
const std::vector<AutofillProfile>& entries)
: callback_(base::BindOnce(&AddAutofillProfileHelper::AddAutofillCallback,
base::Unretained(this),
test,
entries)),
success_(false) {}
base::OnceClosure callback() { return std::move(callback_); }
bool success() { return success_; }
private:
void AddAutofillCallback(ProfileSyncServiceAutofillTest* test,
const std::vector<AutofillProfile>& entries) {
if (!test->CreateRoot(AUTOFILL_PROFILE))
return;
for (size_t i = 0; i < entries.size(); ++i) {
if (!test->AddAutofillSyncNode(entries[i]))
return;
}
success_ = true;
}
base::OnceClosure callback_;
bool success_;
};
TEST_F(ProfileSyncServiceAutofillTest, HasProfileEmptySync) {
std::vector<std::unique_ptr<AutofillProfile>> profiles;
std::vector<AutofillProfile> expected_profiles;
std::unique_ptr<AutofillProfile> profile0 =
std::make_unique<AutofillProfile>();
autofill::test::SetProfileInfoWithGuid(
profile0.get(), "54B3F9AA-335E-4F71-A27D-719C41564230", "Billing",
"Mitchell", "Morrison", "[email protected]", "Fox", "123 Zoo St.",
"unit 5", "Hollywood", "CA", "91601", "US", "12345678910");
expected_profiles.push_back(*profile0);
profiles.push_back(std::move(profile0));
auto profile_returner = [&profiles]() { return std::move(profiles); };
EXPECT_CALL(autofill_table(), GetAutofillProfiles(_))
.WillOnce(DoAll(LoadAutofillProfiles(profile_returner), Return(true)));
EXPECT_CALL(personal_data_manager(), Refresh());
SetIdleChangeProcessorExpectations();
CreateRootHelper create_root(this, AUTOFILL_PROFILE);
StartAutofillProfileSyncService(create_root.callback());
ASSERT_TRUE(create_root.success());
std::vector<AutofillProfile> sync_profiles;
ASSERT_TRUE(GetAutofillProfilesFromSyncDBUnderProfileNode(&sync_profiles));
EXPECT_EQ(1U, sync_profiles.size());
EXPECT_EQ(0, expected_profiles[0].Compare(sync_profiles[0]));
}
TEST_F(ProfileSyncServiceAutofillTest, HasNativeHasSyncMergeProfile) {
AutofillProfile sync_profile;
autofill::test::SetProfileInfoWithGuid(
&sync_profile, "23355099-1170-4B71-8ED4-144470CC9EBE", "Billing",
"Mitchell", "Morrison", "[email protected]", "Fox", "123 Zoo St.",
"unit 5", "Hollywood", "CA", "91601", "US", "12345678910");
std::unique_ptr<AutofillProfile> native_profile =
std::make_unique<AutofillProfile>();
autofill::test::SetProfileInfoWithGuid(
native_profile.get(), "23355099-1170-4B71-8ED4-144470CC9EBE", "Billing",
"Alicia", "Saenz", "[email protected]", "Fox", "1212 Center.", "Bld. 5",
"Orlando", "FL", "32801", "US", "19482937549");
std::vector<std::unique_ptr<AutofillProfile>> native_profiles;
native_profiles.push_back(std::move(native_profile));
auto profile_returner = [&native_profiles]() {
return std::move(native_profiles);
};
EXPECT_CALL(autofill_table(), GetAutofillProfiles(_))
.WillOnce(DoAll(LoadAutofillProfiles(profile_returner), Return(true)));
std::vector<AutofillProfile> sync_profiles;
sync_profiles.push_back(sync_profile);
AddAutofillProfileHelper add_autofill(this, sync_profiles);
EXPECT_CALL(autofill_table(),
UpdateAutofillProfile(MatchProfiles(sync_profile)))
.WillOnce(Return(true));
EXPECT_CALL(personal_data_manager(), Refresh());
StartAutofillProfileSyncService(add_autofill.callback());
ASSERT_TRUE(add_autofill.success());
std::vector<AutofillProfile> new_sync_profiles;
ASSERT_TRUE(
GetAutofillProfilesFromSyncDBUnderProfileNode(&new_sync_profiles));
ASSERT_EQ(1U, new_sync_profiles.size());
EXPECT_EQ(0, sync_profile.Compare(new_sync_profiles[0]));
}
// Tests that a sync with a new native profile that matches a more recent new
// sync profile but with less information results in the native profile being
// deleted and replaced by the sync profile with merged usage stats.
TEST_F(
ProfileSyncServiceAutofillTest,
HasNativeHasSyncMergeSimilarProfileCombine_SyncHasMoreInfoAndMoreRecent) {
// Create two almost identical profiles. The GUIDs are different and the
// native profile has no value for company name.
AutofillProfile sync_profile;
autofill::test::SetProfileInfoWithGuid(
&sync_profile, "23355099-1170-4B71-8ED4-144470CC9EBE", "Billing",
"Mitchell", "Morrison", "[email protected]", "Fox", "123 Zoo St.",
"unit 5", "Hollywood", "CA", "91601", "US", "12345678910");
sync_profile.set_use_date(base::Time::FromTimeT(4321));
std::unique_ptr<AutofillProfile> native_profile =
std::make_unique<AutofillProfile>();
autofill::test::SetProfileInfoWithGuid(
native_profile.get(), "23355099-1170-4B71-8ED4-144470CC9EBF", "Billing",
"Mitchell", "Morrison", "[email protected]", "", "123 Zoo St.", "unit 5",
"Hollywood", "CA", "91601", "US", "12345678910");
native_profile->set_use_date(base::Time::FromTimeT(1234));
AutofillProfile expected_profile(sync_profile);
expected_profile.SetRawInfo(NAME_FULL,
ASCIIToUTF16("Billing Mitchell Morrison"));
expected_profile.set_use_count(1);
std::vector<std::unique_ptr<AutofillProfile>> native_profiles;
native_profiles.push_back(std::move(native_profile));
auto profile_returner = [&native_profiles]() {
return std::move(native_profiles);
};
EXPECT_CALL(autofill_table(), GetAutofillProfiles(_))
.WillOnce(DoAll(LoadAutofillProfiles(profile_returner), Return(true)));
EXPECT_CALL(autofill_table(),
AddAutofillProfile(MatchProfiles(expected_profile)))
.WillOnce(Return(true));
EXPECT_CALL(autofill_table(),
RemoveAutofillProfile("23355099-1170-4B71-8ED4-144470CC9EBF"))
.WillOnce(Return(true));
std::vector<AutofillProfile> sync_profiles;
sync_profiles.push_back(sync_profile);
AddAutofillProfileHelper add_autofill(this, sync_profiles);
EXPECT_CALL(personal_data_manager(), Refresh());
// Adds all entries in |sync_profiles| to sync.
StartAutofillProfileSyncService(add_autofill.callback());
ASSERT_TRUE(add_autofill.success());
std::vector<AutofillProfile> new_sync_profiles;
ASSERT_TRUE(
GetAutofillProfilesFromSyncDBUnderProfileNode(&new_sync_profiles));
ASSERT_EQ(1U, new_sync_profiles.size());
// Check that key fields are the same.
EXPECT_TRUE(new_sync_profiles[0].IsSubsetOf(sync_profile, "en-US"));
// Make sure the additional information from the sync profile was kept.
EXPECT_EQ(ASCIIToUTF16("Fox"),
new_sync_profiles[0].GetRawInfo(ServerFieldType::COMPANY_NAME));
// Check that the latest use date is saved.
EXPECT_EQ(base::Time::FromTimeT(4321), new_sync_profiles[0].use_date());
// Check that the use counts were added (default value is 1).
EXPECT_EQ(1U, new_sync_profiles[0].use_count());
}
// Tests that a sync with a new native profile that matches an older new sync
// profile but with less information results in the native profile being deleted
// and replaced by the sync profile with merged usage stats.
TEST_F(ProfileSyncServiceAutofillTest,
HasNativeHasSyncMergeSimilarProfileCombine_SyncHasMoreInfoAndOlder) {
// Create two almost identical profiles. The GUIDs are different and the
// native profile has no value for company name.
AutofillProfile sync_profile;
autofill::test::SetProfileInfoWithGuid(
&sync_profile, "23355099-1170-4B71-8ED4-144470CC9EBE", "Billing",
"Mitchell", "Morrison", "[email protected]", "Fox", "123 Zoo St.",
"unit 5", "Hollywood", "CA", "91601", "US", "12345678910");
sync_profile.set_use_date(base::Time::FromTimeT(1234));
std::unique_ptr<AutofillProfile> native_profile =
std::make_unique<AutofillProfile>();
autofill::test::SetProfileInfoWithGuid(
native_profile.get(), "23355099-1170-4B71-8ED4-144470CC9EBF", "Billing",
"Mitchell", "Morrison", "[email protected]", "", "123 Zoo St.", "unit 5",
"Hollywood", "CA", "91601", "US", "12345678910");
native_profile->set_use_date(base::Time::FromTimeT(4321));
AutofillProfile expected_profile(sync_profile);
expected_profile.SetRawInfo(NAME_FULL,
ASCIIToUTF16("Billing Mitchell Morrison"));
expected_profile.set_use_count(1);
expected_profile.set_use_date(native_profile->use_date());
std::vector<std::unique_ptr<AutofillProfile>> native_profiles;
native_profiles.push_back(std::move(native_profile));
auto profile_returner = [&native_profiles]() {
return std::move(native_profiles);
};
EXPECT_CALL(autofill_table(), GetAutofillProfiles(_))
.WillOnce(DoAll(LoadAutofillProfiles(profile_returner), Return(true)));
EXPECT_CALL(autofill_table(),
AddAutofillProfile(MatchProfiles(expected_profile)))
.WillOnce(Return(true));
EXPECT_CALL(autofill_table(),
RemoveAutofillProfile("23355099-1170-4B71-8ED4-144470CC9EBF"))
.WillOnce(Return(true));
std::vector<AutofillProfile> sync_profiles;
sync_profiles.push_back(sync_profile);
AddAutofillProfileHelper add_autofill(this, sync_profiles);
EXPECT_CALL(personal_data_manager(), Refresh());
// Adds all entries in |sync_profiles| to sync.
StartAutofillProfileSyncService(add_autofill.callback());
ASSERT_TRUE(add_autofill.success());
std::vector<AutofillProfile> new_sync_profiles;
ASSERT_TRUE(
GetAutofillProfilesFromSyncDBUnderProfileNode(&new_sync_profiles));
ASSERT_EQ(1U, new_sync_profiles.size());
// Check that key fields are the same.
EXPECT_TRUE(new_sync_profiles[0].IsSubsetOf(sync_profile, "en-US"));
// Make sure the additional information from the sync profile was kept.
EXPECT_EQ(ASCIIToUTF16("Fox"),
new_sync_profiles[0].GetRawInfo(ServerFieldType::COMPANY_NAME));
// Check that the latest use date is saved.
EXPECT_EQ(base::Time::FromTimeT(4321), new_sync_profiles[0].use_date());
// Check that the use counts were added (default value is 1).
EXPECT_EQ(1U, new_sync_profiles[0].use_count());
}
// Tests that a sync with a new native profile that matches an a new sync
// profile but with more information results in the native profile being deleted
// and replaced by the sync profile with the native profiles additional
// information merged in. The merge should happen even if the sync profile is
// more recent.
TEST_F(ProfileSyncServiceAutofillTest,
HasNativeHasSyncMergeSimilarProfileCombine_NativeHasMoreInfo) {
// Create two almost identical profiles. The GUIDs are different and the
// sync profile has no value for company name.
AutofillProfile sync_profile;
autofill::test::SetProfileInfoWithGuid(
&sync_profile, "23355099-1170-4B71-8ED4-144470CC9EBE", "Billing",
"Mitchell", "Morrison", "[email protected]", "", "123 Zoo St.", "unit 5",
"Hollywood", "CA", "91601", "US", "12345678910");
sync_profile.set_use_date(base::Time::FromTimeT(4321));
std::unique_ptr<AutofillProfile> native_profile =
std::make_unique<AutofillProfile>();
autofill::test::SetProfileInfoWithGuid(
native_profile.get(), "23355099-1170-4B71-8ED4-144470CC9EBF", "Billing",
"Mitchell", "Morrison", "[email protected]", "Fox", "123 Zoo St.",
"unit 5", "Hollywood", "CA", "91601", "US", "12345678910");
native_profile->set_use_date(base::Time::FromTimeT(1234));
AutofillProfile expected_profile(*native_profile);
expected_profile.SetRawInfo(NAME_FULL,
ASCIIToUTF16("Billing Mitchell Morrison"));
expected_profile.set_use_date(sync_profile.use_date());
expected_profile.set_use_count(1);
std::vector<std::unique_ptr<AutofillProfile>> native_profiles;
native_profiles.push_back(std::move(native_profile));
auto profile_returner = [&native_profiles]() {
return std::move(native_profiles);
};
EXPECT_CALL(autofill_table(), GetAutofillProfiles(_))
.WillOnce(DoAll(LoadAutofillProfiles(profile_returner), Return(true)));
EXPECT_CALL(autofill_table(),
AddAutofillProfile(MatchProfiles(expected_profile)))
.WillOnce(Return(true));
EXPECT_CALL(autofill_table(),
RemoveAutofillProfile("23355099-1170-4B71-8ED4-144470CC9EBF"))
.WillOnce(Return(true));
std::vector<AutofillProfile> sync_profiles;
sync_profiles.push_back(sync_profile);
AddAutofillProfileHelper add_autofill(this, sync_profiles);
EXPECT_CALL(personal_data_manager(), Refresh());
// Adds all entries in |sync_profiles| to sync.
StartAutofillProfileSyncService(add_autofill.callback());
ASSERT_TRUE(add_autofill.success());
std::vector<AutofillProfile> new_sync_profiles;
ASSERT_TRUE(
GetAutofillProfilesFromSyncDBUnderProfileNode(&new_sync_profiles));
ASSERT_EQ(1U, new_sync_profiles.size());
// Check that key fields are the same.
EXPECT_TRUE(new_sync_profiles[0].IsSubsetOf(expected_profile, "en-US"));
// Make sure the additional information of the native profile was saved into
// the sync profile.
EXPECT_EQ(ASCIIToUTF16("Fox"),
new_sync_profiles[0].GetRawInfo(ServerFieldType::COMPANY_NAME));
// Check that the latest use date is saved.
EXPECT_EQ(base::Time::FromTimeT(4321), new_sync_profiles[0].use_date());
// Check that the use counts were added (default value is 1).
EXPECT_EQ(1U, new_sync_profiles[0].use_count());
}
// Tests that a sync with a new native profile that differ only by name a new
// sync profile results in keeping both profiles.
TEST_F(ProfileSyncServiceAutofillTest, HasNativeHasSync_DifferentPrimaryInfo) {
AutofillProfile sync_profile;
autofill::test::SetProfileInfoWithGuid(
&sync_profile, "23355099-1170-4B71-8ED4-144470CC9EBE", "Billing",
"Mitchell", "Morrison", "[email protected]", "Fox", "123 Zoo St.",
"unit 5", "Hollywood", "CA", "91601", "US", "12345678910");
sync_profile.set_use_date(base::Time::FromTimeT(4321));
std::unique_ptr<AutofillProfile> native_profile =
std::make_unique<AutofillProfile>();
autofill::test::SetProfileInfoWithGuid(
native_profile.get(), "23355099-1170-4B71-8ED4-144470CC9EBF", "Billing",
"John", "Smith", "[email protected]", "Fox", "123 Zoo St.", "unit 5",
"Hollywood", "CA", "91601", "US", "12345678910");
native_profile->set_use_date(base::Time::FromTimeT(1234));
std::vector<std::unique_ptr<AutofillProfile>> native_profiles;
native_profiles.push_back(std::move(native_profile));
auto profile_returner = [&native_profiles]() {
return std::move(native_profiles);
};
EXPECT_CALL(autofill_table(), GetAutofillProfiles(_))
.WillOnce(DoAll(LoadAutofillProfiles(profile_returner), Return(true)));
EXPECT_CALL(autofill_table(), AddAutofillProfile(MatchProfiles(sync_profile)))
.WillOnce(Return(true));
std::vector<AutofillProfile> sync_profiles;
sync_profiles.push_back(sync_profile);
AddAutofillProfileHelper add_autofill(this, sync_profiles);
EXPECT_CALL(personal_data_manager(), Refresh());
// Adds all entries in |sync_profiles| to sync.
StartAutofillProfileSyncService(add_autofill.callback());
ASSERT_TRUE(add_autofill.success());
std::vector<AutofillProfile> new_sync_profiles;
ASSERT_TRUE(
GetAutofillProfilesFromSyncDBUnderProfileNode(&new_sync_profiles));
// The two profiles should be kept.
ASSERT_EQ(2U, new_sync_profiles.size());
}
// Tests that a new native profile that is the same as a new sync profile except
// with different GUIDs results in the native profile being deleted and replaced
// by the sync profile.
TEST_F(ProfileSyncServiceAutofillTest, MergeProfileWithDifferentGuid) {
AutofillProfile sync_profile;
autofill::test::SetProfileInfoWithGuid(
&sync_profile, "23355099-1170-4B71-8ED4-144470CC9EBE", "Billing",
"Mitchell", "Morrison", "[email protected]", "Fox", "123 Zoo St.",
"unit 5", "Hollywood", "CA", "91601", "US", "12345678910");
sync_profile.set_use_count(20);
sync_profile.set_use_date(base::Time::FromTimeT(1234));
std::string native_guid = "EDC609ED-7EEE-4F27-B00C-423242A9C44B";
std::unique_ptr<AutofillProfile> native_profile =
std::make_unique<AutofillProfile>();
autofill::test::SetProfileInfoWithGuid(
native_profile.get(), native_guid.c_str(), "Billing", "Mitchell",
"Morrison", "[email protected]", "Fox", "123 Zoo St.", "unit 5",
"Hollywood", "CA", "91601", "US", "12345678910");
native_profile->set_use_count(5);
native_profile->set_use_date(base::Time::FromTimeT(4321));
std::vector<std::unique_ptr<AutofillProfile>> native_profiles;
native_profiles.push_back(std::move(native_profile));
auto profile_returner = [&native_profiles]() {
return std::move(native_profiles);
};
EXPECT_CALL(autofill_table(), GetAutofillProfiles(_))
.WillOnce(DoAll(LoadAutofillProfiles(profile_returner), Return(true)));
std::vector<AutofillProfile> sync_profiles;
sync_profiles.push_back(sync_profile);
AddAutofillProfileHelper add_autofill(this, sync_profiles);
EXPECT_CALL(autofill_table(), AddAutofillProfile(_)).WillOnce(Return(true));
EXPECT_CALL(autofill_table(), RemoveAutofillProfile(native_guid))
.WillOnce(Return(true));
EXPECT_CALL(personal_data_manager(), Refresh());
StartAutofillProfileSyncService(add_autofill.callback());
ASSERT_TRUE(add_autofill.success());
std::vector<AutofillProfile> new_sync_profiles;
ASSERT_TRUE(
GetAutofillProfilesFromSyncDBUnderProfileNode(&new_sync_profiles));
// Check that the profiles were merged.
ASSERT_EQ(1U, new_sync_profiles.size());
EXPECT_EQ(0, sync_profile.Compare(new_sync_profiles[0]));
// Check that the sync guid was kept.
EXPECT_EQ(sync_profile.guid(), new_sync_profiles[0].guid());
// Check that the sync profile use count was kept.
EXPECT_EQ(20U, new_sync_profiles[0].use_count());
// Check that the sync profile use date was kept.
EXPECT_EQ(base::Time::FromTimeT(1234), new_sync_profiles[0].use_date());
}
TEST_F(ProfileSyncServiceAutofillTest, ProcessUserChangeAddProfile) {
EXPECT_CALL(autofill_table(), GetAutofillProfiles(_)).WillOnce(Return(true));
EXPECT_CALL(personal_data_manager(), Refresh());
SetIdleChangeProcessorExpectations();
CreateRootHelper create_root(this, AUTOFILL_PROFILE);
StartAutofillProfileSyncService(create_root.callback());
ASSERT_TRUE(create_root.success());
AutofillProfile added_profile;
autofill::test::SetProfileInfoWithGuid(
&added_profile, "D6ADA912-D374-4C0A-917D-F5C8EBE43011", "Josephine",
"Alicia", "Saenz", "[email protected]", "Fox", "1212 Center.", "Bld. 5",
"Orlando", "FL", "32801", "US", "19482937549");
// TODO(crbug.com/904390): Remove when the investigation is over. This call is
// needed in the AutofillProfileChanged() callback.
EXPECT_CALL(autofill_table(), GetServerProfiles(_)).WillOnce(Return(true));
AutofillProfileChange change(AutofillProfileChange::ADD, added_profile.guid(),
&added_profile);
web_data_service()->OnAutofillProfileChanged(change);
std::vector<AutofillProfile> new_sync_profiles;
ASSERT_TRUE(
GetAutofillProfilesFromSyncDBUnderProfileNode(&new_sync_profiles));
ASSERT_EQ(1U, new_sync_profiles.size());
EXPECT_EQ(0, added_profile.Compare(new_sync_profiles[0]));
}
TEST_F(ProfileSyncServiceAutofillTest, ProcessUserChangeRemoveProfile) {
AutofillProfile sync_profile;
autofill::test::SetProfileInfoWithGuid(
&sync_profile, "3BA5FA1B-1EC4-4BB3-9B57-EC92BE3C1A09", "Josephine",
"Alicia", "Saenz", "[email protected]", "Fox", "1212 Center.", "Bld. 5",
"Orlando", "FL", "32801", "US", "19482937549");
std::unique_ptr<AutofillProfile> native_profile =
std::make_unique<AutofillProfile>();
autofill::test::SetProfileInfoWithGuid(
native_profile.get(), "3BA5FA1B-1EC4-4BB3-9B57-EC92BE3C1A09", "Josephine",
"Alicia", "Saenz", "[email protected]", "Fox", "1212 Center.", "Bld. 5",
"Orlando", "FL", "32801", "US", "19482937549");
std::vector<std::unique_ptr<AutofillProfile>> native_profiles;
native_profiles.push_back(std::move(native_profile));
auto profile_returner = [&native_profiles]() {
return std::move(native_profiles);
};
EXPECT_CALL(autofill_table(), GetAutofillProfiles(_))
.WillOnce(DoAll(LoadAutofillProfiles(profile_returner), Return(true)));
std::vector<AutofillProfile> sync_profiles;
sync_profiles.push_back(sync_profile);
AddAutofillProfileHelper add_autofill(this, sync_profiles);
EXPECT_CALL(personal_data_manager(), Refresh());
StartAutofillProfileSyncService(add_autofill.callback());
ASSERT_TRUE(add_autofill.success());
AutofillProfileChange change(AutofillProfileChange::REMOVE,
sync_profile.guid(), nullptr);
web_data_service()->OnAutofillProfileChanged(change);
std::vector<AutofillProfile> new_sync_profiles;
ASSERT_TRUE(
GetAutofillProfilesFromSyncDBUnderProfileNode(&new_sync_profiles));
ASSERT_EQ(0U, new_sync_profiles.size());
}
} // namespace browser_sync
| [
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98",
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98",
"[email protected]",
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98",
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98",
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98",
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98",
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98",
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98",
"[email protected]",
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98",
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98",
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98",
"[email protected]",
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98",
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98",
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98",
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98",
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98",
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98",
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98",
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98",
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98",
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98",
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98",
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98",
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98",
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98",
"[email protected]@0039d316-1c4b-4281-b951-d872f2087c98"
] | [
[
[
1,
1
]
],
[
[
2,
4
],
[
9,
10
],
[
12,
13
],
[
61,
61
],
[
63,
63
],
[
76,
76
],
[
87,
87
],
[
89,
90
],
[
94,
94
],
[
130,
130
],
[
132,
132
],
[
150,
151
],
[
243,
243
],
[
285,
285
],
[
287,
287
],
[
300,
300
],
[
327,
327
],
[
337,
338
],
[
373,
373
],
[
404,
404
],
[
406,
407
],
[
418,
419
],
[
481,
482
],
[
490,
490
],
[
495,
497
],
[
524,
524
],
[
530,
530
],
[
549,
550
],
[
552,
552
],
[
560,
560
],
[
568,
568
],
[
572,
576
],
[
578,
580
],
[
1008,
1009
]
],
[
[
5,
7
],
[
18,
18
],
[
20,
20
],
[
25,
27
],
[
30,
31
],
[
34,
34
],
[
38,
39
],
[
41,
48
],
[
51,
52
],
[
54,
57
],
[
59,
60
],
[
62,
62
],
[
72,
72
],
[
74,
75
],
[
88,
88
],
[
93,
93
],
[
95,
96
],
[
99,
120
],
[
122,
123
],
[
131,
131
],
[
138,
139
],
[
141,
149
],
[
156,
161
],
[
169,
169
],
[
171,
175
],
[
177,
179
],
[
181,
198
],
[
200,
204
],
[
208,
210
],
[
217,
220
],
[
222,
222
],
[
224,
225
],
[
228,
228
],
[
237,
237
],
[
244,
254
],
[
256,
256
],
[
260,
266
],
[
268,
271
],
[
277,
280
],
[
284,
284
],
[
286,
286
],
[
289,
290
],
[
292,
296
],
[
301,
301
],
[
303,
306
],
[
308,
310
],
[
321,
322
],
[
333,
335
],
[
339,
341
],
[
350,
350
],
[
354,
354
],
[
357,
358
],
[
361,
370
],
[
374,
388
],
[
391,
391
],
[
393,
395
],
[
397,
403
],
[
408,
409
],
[
411,
417
],
[
420,
421
],
[
423,
423
],
[
428,
463
],
[
465,
466
],
[
468,
469
],
[
473,
474
],
[
479,
480
],
[
484,
484
],
[
488,
488
],
[
494,
494
],
[
500,
500
],
[
506,
506
],
[
513,
518
],
[
527,
529
],
[
531,
548
],
[
551,
551
],
[
553,
559
],
[
561,
561
],
[
566,
567
],
[
577,
577
],
[
582,
582
],
[
584,
589
],
[
591,
595
],
[
597,
598
],
[
608,
611
],
[
613,
618
],
[
620,
626
],
[
630,
630
],
[
632,
636
],
[
640,
641
],
[
646,
653
],
[
655,
659
],
[
661,
667
],
[
670,
672
],
[
674,
686
],
[
689,
689
],
[
691,
693
],
[
697,
763
],
[
767,
884
],
[
887,
889
],
[
893,
898
],
[
901,
908
],
[
910,
916
],
[
920,
920
],
[
922,
926
],
[
930,
932
],
[
935,
935
],
[
937,
940
],
[
944,
945
],
[
947,
948
],
[
952,
955
],
[
957,
963
],
[
966,
967
],
[
974,
983
],
[
985,
991
],
[
995,
997
],
[
1000,
1002
],
[
1005,
1006
],
[
1010,
1010
]
],
[
[
8,
8
],
[
19,
19
]
],
[
[
11,
11
],
[
121,
121
]
],
[
[
14,
14
],
[
29,
29
],
[
69,
69
],
[
91,
91
],
[
135,
135
],
[
255,
255
],
[
258,
259
],
[
272,
276
],
[
281,
283
],
[
317,
320
],
[
324,
326
],
[
330,
331
],
[
405,
405
],
[
410,
410
],
[
491,
491
],
[
526,
526
]
],
[
[
15,
15
],
[
562,
565
],
[
569,
571
],
[
599,
599
],
[
637,
637
],
[
927,
927
],
[
949,
949
],
[
998,
998
]
],
[
[
16,
16
],
[
78,
78
],
[
504,
504
],
[
509,
509
],
[
590,
590
],
[
596,
596
],
[
602,
602
],
[
604,
606
],
[
612,
612
],
[
619,
619
],
[
627,
627
],
[
629,
629
],
[
631,
631
],
[
638,
638
],
[
642,
642
],
[
885,
886
],
[
943,
943
],
[
946,
946
],
[
950,
950
],
[
956,
956
],
[
964,
964
],
[
968,
968
],
[
970,
972
],
[
984,
984
],
[
992,
992
],
[
994,
994
],
[
999,
999
],
[
1003,
1003
]
],
[
[
17,
17
]
],
[
[
21,
21
]
],
[
[
22,
23
],
[
28,
28
]
],
[
[
24,
24
],
[
140,
140
],
[
483,
483
],
[
499,
499
],
[
583,
583
],
[
600,
600
],
[
607,
607
],
[
628,
628
],
[
639,
639
],
[
891,
891
],
[
918,
918
],
[
929,
929
],
[
951,
951
],
[
965,
965
],
[
973,
973
],
[
993,
993
],
[
1004,
1004
]
],
[
[
32,
33
],
[
35,
37
]
],
[
[
40,
40
],
[
49,
50
],
[
53,
53
]
],
[
[
58,
58
],
[
170,
170
],
[
176,
176
],
[
180,
180
],
[
199,
199
],
[
205,
207
],
[
211,
212
],
[
215,
216
],
[
221,
221
],
[
223,
223
],
[
226,
226
],
[
233,
236
],
[
238,
242
],
[
267,
267
],
[
311,
312
],
[
323,
323
],
[
329,
329
],
[
332,
332
],
[
336,
336
]
],
[
[
64,
68
],
[
70,
71
],
[
73,
73
],
[
97,
98
],
[
124,
128
],
[
288,
288
],
[
291,
291
],
[
297,
299
],
[
313,
316
],
[
328,
328
],
[
344,
344
],
[
352,
353
],
[
390,
390
],
[
392,
392
]
],
[
[
77,
77
],
[
152,
155
],
[
307,
307
],
[
492,
493
],
[
643,
645
],
[
654,
654
],
[
660,
660
],
[
668,
669
],
[
673,
673
],
[
687,
688
],
[
690,
690
],
[
694,
696
],
[
764,
765
]
],
[
[
79,
79
],
[
82,
82
],
[
92,
92
],
[
502,
502
]
],
[
[
80,
81
],
[
83,
86
],
[
485,
485
],
[
487,
487
],
[
489,
489
],
[
501,
501
],
[
507,
508
]
],
[
[
129,
129
],
[
162,
163
],
[
166,
168
],
[
525,
525
]
],
[
[
133,
134
],
[
136,
137
]
],
[
[
164,
165
]
],
[
[
213,
214
],
[
345,
345
],
[
347,
349
],
[
351,
351
],
[
355,
355
],
[
464,
464
],
[
467,
467
],
[
486,
486
],
[
498,
498
],
[
503,
503
],
[
505,
505
],
[
510,
512
],
[
519,
523
],
[
581,
581
],
[
601,
601
],
[
890,
890
],
[
892,
892
],
[
899,
900
],
[
909,
909
],
[
917,
917
],
[
919,
919
],
[
921,
921
],
[
928,
928
],
[
933,
934
],
[
936,
936
],
[
941,
942
],
[
1007,
1007
]
],
[
[
227,
227
],
[
229,
232
]
],
[
[
257,
257
],
[
389,
389
],
[
396,
396
]
],
[
[
302,
302
]
],
[
[
342,
343
],
[
356,
356
],
[
359,
360
],
[
371,
372
],
[
422,
422
],
[
424,
427
],
[
470,
472
],
[
475,
478
]
],
[
[
346,
346
],
[
766,
766
]
],
[
[
603,
603
],
[
969,
969
]
]
] |