text
stringlengths
54
60.6k
<commit_before>// Copyright © 2017-2019 Dmitriy Khaustov // // 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. // // Author: Dmitriy Khaustov aka xDimon // Contacts: [email protected] // File created on: 2017.07.06 // Number.hpp #pragma once #include <climits> #include <cmath> namespace Number { template<typename D, typename S> void assign(D& dst, const S& src, const D& def = D()) { if ( src > std::numeric_limits<D>::max() || src < std::numeric_limits<D>::min() ) { dst = def; } else { dst = static_cast<D>(src); } } template<typename T> T obfuscate(T src, size_t rounds = 0) { size_t bits = sizeof(T) * CHAR_BIT; if (rounds == 0) { if (bits > 32) rounds = 4; else if (bits > 16) rounds = 3; else if (bits > 8) rounds = 2; else rounds = 1; } T s; T d = src; for (size_t r = 0; r < rounds; r++) { s = d; d = 0; for (size_t i = 0; i < (bits >> 1); i++) { d |= ((s >> i) & 1) << (bits - 1 - i * 2); } for (size_t i = (bits >> 1); i < bits; i++) { d |= ((s >> i) & 1) << ((i - (bits >> 1)) * 2); } } return d; } template<typename T> T deobfuscate(T src, size_t rounds = 0) { size_t bits = sizeof(T) * CHAR_BIT; if (rounds == 0) { if (bits > 32) rounds = 4; else if (bits > 16) rounds = 3; else if (bits > 8) rounds = 2; else rounds = 1; } T s; T d = src; for (size_t r = 0; r < rounds; r++) { s = d; d = 0; for (size_t i = 0; i < (bits >> 1); i++) { d |= ((s >> (bits - 1 - i * 2)) & 1) << i; } for (size_t i = (bits >> 1); i < bits; i++) { d |= ((s >> ((i - (bits >> 1)) * 2)) & 1) << i; } } return d; } template<typename T> double smartRound( T srcValue, size_t numberOfDigitForBegginerRound = 10, size_t numberOfAllSagnifficantDigits = 10, size_t factor = 1, int lastDigitForPsychoRound = -1 ) { typename std::enable_if<std::is_floating_point<T>::value, bool>::type detect(); if (srcValue < 0.01) { return std::ceil(srcValue * 100) / 100; } else if (srcValue < 0.10) { return std::round(srcValue * 100) / 100; } else if (srcValue < 1.00) { return std::floor(srcValue * 100) / 100; } // Формируем шаблон для сравнения T threshold = std::pow(10, numberOfDigitForBegginerRound); // Вычисляем множитель для округления до значащих цифр T m1 = 1; for (;;) { if (srcValue * m1 >= threshold) break; m1 *= 10; } for (;;) { if (srcValue * m1 <= threshold) break; m1 /= 10; } // Вычисляем множитель для значащих цифр после округления T m2 = m1 * std::pow(10, numberOfAllSagnifficantDigits - numberOfDigitForBegginerRound); // Выравниваем последний разряд T t1 = std::round(srcValue * m2 + 1) / m2; // Нормируем кратно в последнем значащем разряде T t2 = std::floor(t1 * m1 / factor) * factor / m1; // Психологическое округление T t3 = (lastDigitForPsychoRound > 0 && lastDigitForPsychoRound <= 9) ? ((t2 * m2 - (10 - lastDigitForPsychoRound)) / m2) : t2; // Отбрасываем дробную часть копеек T t4 = std::floor(std::round(t3 * 1000) / 1000 * 100) / 100; return t4; } }; <commit_msg>improve: smart rounding<commit_after>// Copyright © 2017-2019 Dmitriy Khaustov // // 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. // // Author: Dmitriy Khaustov aka xDimon // Contacts: [email protected] // File created on: 2017.07.06 // Number.hpp #pragma once #include <climits> #include <cmath> #include <iostream> #include <iomanip> namespace Number { template<typename D, typename S> void assign(D& dst, const S& src, const D& def = D()) { if ( src > std::numeric_limits<D>::max() || src < std::numeric_limits<D>::min() ) { dst = def; } else { dst = static_cast<D>(src); } } template<typename T> T obfuscate(T src, size_t rounds = 0) { size_t bits = sizeof(T) * CHAR_BIT; if (rounds == 0) { if (bits > 32) rounds = 4; else if (bits > 16) rounds = 3; else if (bits > 8) rounds = 2; else rounds = 1; } T s; T d = src; for (size_t r = 0; r < rounds; r++) { s = d; d = 0; for (size_t i = 0; i < (bits >> 1); i++) { d |= ((s >> i) & 1) << (bits - 1 - i * 2); } for (size_t i = (bits >> 1); i < bits; i++) { d |= ((s >> i) & 1) << ((i - (bits >> 1)) * 2); } } return d; } template<typename T> T deobfuscate(T src, size_t rounds = 0) { size_t bits = sizeof(T) * CHAR_BIT; if (rounds == 0) { if (bits > 32) rounds = 4; else if (bits > 16) rounds = 3; else if (bits > 8) rounds = 2; else rounds = 1; } T s; T d = src; for (size_t r = 0; r < rounds; r++) { s = d; d = 0; for (size_t i = 0; i < (bits >> 1); i++) { d |= ((s >> (bits - 1 - i * 2)) & 1) << i; } for (size_t i = (bits >> 1); i < bits; i++) { d |= ((s >> ((i - (bits >> 1)) * 2)) & 1) << i; } } return d; } template<typename T> double smartRound( T value, size_t numberOfDigitForBegginerRound = 10, size_t numberOfAllSagnifficantDigits = 10, size_t factor = 1, int lastDigitForPsychoRound = -1 ) { typename std::enable_if<std::is_floating_point<T>::value, bool>::type detect(); if (value < 0.01) { return std::ceil(value * 100) / 100; } else if (value < 0.10) { return std::round(value * 100) / 100; } // Уменьшаем на единицу незначащего разряда () value -= std::pow(10, -static_cast<intmax_t>(numberOfAllSagnifficantDigits+1)); // Вычисляем множитель для округления до значащих цифр auto e1 = static_cast<intmax_t>(std::floor(numberOfDigitForBegginerRound - std::log10(value))); // Вычисляем множитель для значащих цифр после округления auto e2 = static_cast<intmax_t>(numberOfAllSagnifficantDigits - numberOfDigitForBegginerRound); // Нормируем делитель, для кратности auto f = (e1 - e2 <= 0) ? (factor * std::pow(10, e2)) : std::pow(10, e2 + 1); // Кратное округление auto factorRounded = static_cast<uintmax_t>(std::floor(std::round(value * std::pow(10, e1 + e2)) / f) * f); // Психологическое округление auto psychoRounded = static_cast<uintmax_t>( (lastDigitForPsychoRound > 0 && lastDigitForPsychoRound <= 9 && (e1 - e2) <= 1) ? (factorRounded - 1) : factorRounded ); auto moduloRounded = std::floor(psychoRounded / std::pow(10, e1 + e2 - 2)) / 100; return moduloRounded; } }; <|endoftext|>
<commit_before>#include "writer.hpp" #include <Eigen/Core> #include <Eigen/Dense> #include <iostream> //----------------stepBegin---------------- //! Does one Forward-Euler timestep of the heat equation //! //! @param[out] u at the end, u will contain the values at time t^{n+1} //! @param[in] uPrevous should contain the values at time t^n //! @param[in] dr the cell length in r direction //! @param[in] dt the timestep size void stepHeatEquation(Eigen::VectorXd & u, const Eigen::VectorXd &uPrevious, const double dr, const double dt) { // (write your solution here) } //----------------stepEnd---------------- //----------------solveBegin---------------- //! Gives an approximation to the heat equation with the given initial data //! //! @param initialData represents the function \tilde{u}_0. //! //! @param shouldStop is a function taking as first //! parameter the current value of u, and //! as second value the current time t. //! The simulation should run until shouldStop(u,t) == true. That is //! //! \code{.cpp} //! while(!shouldStop(u,t)) { /* Do one more timestep */ } //! \endcode //! //! @param N the number of inner points //! @param cfl the constant C with which we choose the timestep size. We set //! \code{.cpp} //! dt = cfl*dr*dr //! \endcode Eigen::VectorXd solveHeatEquation(const std::function<double(double)> &initialData, const std::function<bool(const Eigen::VectorXd &, double)> &shouldStop, const int N, double cfl = 0.5) { Eigen::VectorXd u1(N + 2), u2(N + 2); u1.setZero(); Eigen::VectorXd &u = u1; Eigen::VectorXd &uPrevious = u2; // Set the initial value // (write your solution here) double t = 0; double dr = 1.0 / N; double dt = cfl * dr * dr; while (!shouldStop(u, t)) { // make one step forward. // Make sure you swap u and uPrevious // accordingly! // And update the current time // (write your solution here) } // Return the final solution return u; } //----------------solveEnd---------------- bool stopAtTimeOne(const Eigen::VectorXd &u, double t) { return t > 1; } //----------------convergenceBegin---------------- void convergenceStudy() { const size_t NReference = (1 << 10) - 2; auto initialData = [](double r) { return 1 - r * r * cos(r); }; auto stopAtTime0025 = [](const Eigen::VectorXd &, double t) { return t > 0.025; }; std::cout << "Computing reference solution" << std::endl; auto uReference = solveHeatEquation(initialData, stopAtTime0025, NReference, 0.5); std::cout << "Done computing reference solution" << std::endl; std::vector<size_t> resolutions; std::vector<double> errors; //// NPDE_TEMPLATE_START for (int k = 3; k < 10; ++k) { const size_t N = (1 << k) - 2; auto u = solveHeatEquation(initialData, stopAtTime0025, N, 0.5); double maxError = 0; size_t ratioReference = (NReference + 2) / (N + 2); for (size_t i = 0; i < u.rows(); ++i) { maxError = std::max(maxError, std::abs(u[i] - uReference[i * ratioReference])); } resolutions.push_back(N); errors.push_back(maxError); } //// NPDE_TEMPLATE_END writeToFile("resolutions.txt", resolutions); writeToFile("errors.txt", errors); } //----------------convergenceEnd---------------- int main(int, char **) { auto initialData = [](double) { return 20; }; auto u05 = solveHeatEquation(initialData, stopAtTimeOne, 20, 0.5); writeToFile("u_05.txt", u05); auto u051 = solveHeatEquation(initialData, stopAtTimeOne, 20, 0.51); writeToFile("u_051.txt", u051); //----------------maxstopBegin---------------- // (write your solution here) //----------------maxstopEnd---------------- convergenceStudy(); return 0; } <commit_msg>Solved series 3 problem 2f<commit_after>#include "writer.hpp" #include <Eigen/Core> #include <Eigen/Dense> #include <iostream> //----------------stepBegin---------------- //! Does one Forward-Euler timestep of the heat equation //! //! @param[out] u at the end, u will contain the values at time t^{n+1} //! @param[in] uPrevous should contain the values at time t^n //! @param[in] dr the cell length in r direction //! @param[in] dt the timestep size void stepHeatEquation(Eigen::VectorXd & u, const Eigen::VectorXd &uPrevious, const double dr, const double dt) { // (write your solution here) u(0) = uPrevious(0); for (int i = 1; i < u.size() - 1; ++i) { u(i+1) = uPrevious(i) + dt / (dr * dr) * ( (i+1) * uPrevious(i+1) - 2 * i * uPrevious(i) + (i-1) * uPrevious(i-1) ) / i; } u(u.size() - 1) = 0; } //----------------stepEnd---------------- //----------------solveBegin---------------- //! Gives an approximation to the heat equation with the given initial data //! //! @param initialData represents the function \tilde{u}_0. //! //! @param shouldStop is a function taking as first //! parameter the current value of u, and //! as second value the current time t. //! The simulation should run until shouldStop(u,t) == true. That is //! //! \code{.cpp} //! while(!shouldStop(u,t)) { /* Do one more timestep */ } //! \endcode //! //! @param N the number of inner points //! @param cfl the constant C with which we choose the timestep size. We set //! \code{.cpp} //! dt = cfl*dr*dr //! \endcode Eigen::VectorXd solveHeatEquation(const std::function<double(double)> &initialData, const std::function<bool(const Eigen::VectorXd &, double)> &shouldStop, const int N, double cfl = 0.5) { Eigen::VectorXd u1(N + 2), u2(N + 2); u1.setZero(); Eigen::VectorXd &u = u1; Eigen::VectorXd &uPrevious = u2; // Set the initial value // (write your solution here) double t = 0; double dr = 1.0 / N; double dt = cfl * dr * dr; while (!shouldStop(u, t)) { // make one step forward. // Make sure you swap u and uPrevious // accordingly! // And update the current time // (write your solution here) } // Return the final solution return u; } //----------------solveEnd---------------- bool stopAtTimeOne(const Eigen::VectorXd &u, double t) { return t > 1; } //----------------convergenceBegin---------------- void convergenceStudy() { const size_t NReference = (1 << 10) - 2; auto initialData = [](double r) { return 1 - r * r * cos(r); }; auto stopAtTime0025 = [](const Eigen::VectorXd &, double t) { return t > 0.025; }; std::cout << "Computing reference solution" << std::endl; auto uReference = solveHeatEquation(initialData, stopAtTime0025, NReference, 0.5); std::cout << "Done computing reference solution" << std::endl; std::vector<size_t> resolutions; std::vector<double> errors; //// NPDE_TEMPLATE_START for (int k = 3; k < 10; ++k) { const size_t N = (1 << k) - 2; auto u = solveHeatEquation(initialData, stopAtTime0025, N, 0.5); double maxError = 0; size_t ratioReference = (NReference + 2) / (N + 2); for (size_t i = 0; i < u.rows(); ++i) { maxError = std::max(maxError, std::abs(u[i] - uReference[i * ratioReference])); } resolutions.push_back(N); errors.push_back(maxError); } //// NPDE_TEMPLATE_END writeToFile("resolutions.txt", resolutions); writeToFile("errors.txt", errors); } //----------------convergenceEnd---------------- int main(int, char **) { auto initialData = [](double) { return 20; }; auto u05 = solveHeatEquation(initialData, stopAtTimeOne, 20, 0.5); writeToFile("u_05.txt", u05); auto u051 = solveHeatEquation(initialData, stopAtTimeOne, 20, 0.51); writeToFile("u_051.txt", u051); //----------------maxstopBegin---------------- // (write your solution here) //----------------maxstopEnd---------------- convergenceStudy(); return 0; } <|endoftext|>
<commit_before>/* * Copyright 2014 Mike Pontillo * * 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 <stdio.h> #include <stdlib.h> #include <pcap/pcap.h> #include <inttypes.h> #include <string.h> #include <string> #include <map> #include <iterator> #include <ctime> // a.k.a time.h struct ScanContext { uintmax_t packetCount; uintmax_t ethernetPacketCount; uintmax_t arpPacketCount; uintmax_t byteCount; unsigned int maxPacketLength; unsigned int minPacketLength; int isEthernet; struct timeval startTime; struct timeval endTime; std::map<std::string, long> packetCountPerSourceMac; std::map<std::string, long> packetCountPerDestMac; ScanContext() : packetCount(0), ethernetPacketCount(0), arpPacketCount(0), byteCount(0), maxPacketLength(0), minPacketLength(0), isEthernet(0) { memset(&this->startTime, 0, sizeof(struct timeval)); memset(&this->endTime, 0, sizeof(struct timeval)); } }; static char* macToString(const unsigned char* bytes) { static char mac[18]; snprintf(mac, 18, "%02x:%02x:%02x:%02x:%02x:%02x", bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5]); return mac; } static void insertOrIncrementCounter(std::map<std::string, long> &map, std::string &key) { if(map.find(key) != map.end()) { map[key]++; } else { map[key] = 1; } } static void handlePossibleEthernetPacket(u_char *user, const struct pcap_pkthdr *h, const u_char *bytes) { ScanContext* ctx = (struct ScanContext*) user; if(ctx->packetCount == 0) { ctx->startTime = h->ts; } else { // we don't know what the last packet will be... ctx->endTime = h->ts; } ctx->packetCount++; if(h->len > ctx->maxPacketLength) { ctx->maxPacketLength = h->len; } if(ctx->minPacketLength == 0 || h->len < ctx->minPacketLength) { ctx->minPacketLength = h->len; } ctx->byteCount += h->len; if(ctx->isEthernet) { ctx->ethernetPacketCount++; if(h->caplen >= 12) { std::string sourceMacString = macToString(bytes+6); std::string destMacString = macToString(bytes); insertOrIncrementCounter(ctx->packetCountPerDestMac, destMacString); insertOrIncrementCounter(ctx->packetCountPerSourceMac, sourceMacString); } } } static void handleArpPacket(u_char *user, const struct pcap_pkthdr *h, const u_char *bytes) { ScanContext* ctx = (struct ScanContext*) user; ctx->arpPacketCount++; } static void printCountPerAddress(std::map<std::string, long> &macToCount) { std::map<std::string, long>::iterator it; for (it = macToCount.begin(); it != macToCount.end(); it++) { printf("%8ld %s\n", it->second, it->first.c_str()); } } static inline const char* timevalToLocalTime(struct timeval* time) { time_t unixTime = time->tv_sec; struct tm* localTime = localtime(&unixTime); char* localTimeString = asctime(localTime); // note: the result from asctime() has a '\n' at the end, so we truncate it if(localTimeString) { localTimeString[strlen(localTimeString) - 1] = '\0'; } return localTimeString ? localTimeString : "?"; } static void printStatistics(struct ScanContext* ctx) { printf("%ju packets\n", ctx->packetCount); printf("%ju Ethernet packets\n", ctx->ethernetPacketCount); printf("%ju ARP packets\n", ctx->arpPacketCount); printf("Min size packet: %u\n", ctx->minPacketLength); printf("Max size packet: %u\n", ctx->maxPacketLength); if(0 != ctx->packetCount) { printf("Average size packet: %ju\n", ctx->byteCount / ctx->packetCount); } printf("Start time: %ju.%06ju seconds (%s)\n", (uintmax_t) ctx->startTime.tv_sec, (uintmax_t) ctx->startTime.tv_usec, timevalToLocalTime(&ctx->startTime)); printf("End time: %ju.%06ju seconds (%s)\n", (uintmax_t) ctx->endTime.tv_sec, (uintmax_t) ctx->endTime.tv_usec, timevalToLocalTime(&ctx->endTime)); long totalCaptureTime = ctx->endTime.tv_sec - ctx->startTime.tv_sec; if(0 == totalCaptureTime) { // round up to avoid divide by zero totalCaptureTime = 1; } printf("Total time: %ld seconds (%ld.%01ld minutes)\n", totalCaptureTime, totalCaptureTime / 60, totalCaptureTime % 60 * 10 / 60); printf("Total bytes captured: %ju bytes / %ju kilobytes / %ju megabytes\n", ctx->byteCount, ctx->byteCount / 1024, ctx->byteCount / 1024 / 1024); long kilobits = ctx->byteCount * 8 / 1024; long kilobitsPerSecond = kilobits / totalCaptureTime; printf("Overall capture speed: %ld Kbps (%ld Mbps)\n", kilobitsPerSecond, kilobitsPerSecond / 1024); if(!ctx->packetCountPerDestMac.empty()) { printf("\nEthernet destinations:\n"); printCountPerAddress(ctx->packetCountPerDestMac); } if(!ctx->packetCountPerSourceMac.empty()) { printf("\nEthernet sources:\n"); printCountPerAddress(ctx->packetCountPerSourceMac); } } static int applyCaptureFilter(pcap_t* pcap, const char* filter) { int result = 0; struct bpf_program* bpf = (struct bpf_program*) calloc(1, sizeof(struct bpf_program)); if(NULL == bpf) { perror("calloc"); result = -1; goto exit; } if(-1 == pcap_compile(pcap, bpf, filter, 1 /* optimize */, PCAP_NETMASK_UNKNOWN)) { fprintf(stderr, "%s\n", pcap_geterr(pcap)); result = -1; goto exit; } if(-1 == pcap_setfilter(pcap, bpf)) { fprintf(stderr, "%s\n", pcap_geterr(pcap)); result = -1; goto exit; } exit: if(NULL != bpf) { pcap_freecode(bpf); free(bpf); } return result; } int main(int argc, char* argv[]) { int result = 0; pcap_t* pcap; char errbuf[PCAP_ERRBUF_SIZE]; struct ScanContext ctx; if(argc < 2) { fprintf(stderr, "Not enough arguments. Please specify a pcap file.\n"); result = 2; goto exit; } pcap = pcap_open_offline(argv[1], errbuf); if(NULL == pcap) { fprintf(stderr, "%s\n", errbuf); result = 3; goto exit; } if(DLT_EN10MB == pcap_datalink(pcap)) { ctx.isEthernet = 1; } pcap_loop(pcap, -1, handlePossibleEthernetPacket, (u_char*) &ctx); // reopen file and check against a capture filter pcap_close(pcap); pcap = pcap_open_offline(argv[1], errbuf); if(NULL == pcap) { fprintf(stderr, "%s\n", errbuf); result = 4; goto exit; } if(0 != applyCaptureFilter(pcap, "arp")) { // expression could reject all packets and throw an error goto skip_arp; } pcap_loop(pcap, -1, handleArpPacket, (u_char*) &ctx); skip_arp: pcap_close(pcap); // All done with packet processing. printStatistics(&ctx); exit: return result; } <commit_msg>Beginnings of ARP parsing code.<commit_after>/* * Copyright 2014 Mike Pontillo * * 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 <stdio.h> #include <stdlib.h> #include <pcap/pcap.h> #include <inttypes.h> #include <string.h> #include <string> #include <map> #include <iterator> #include <ctime> // a.k.a time.h struct ScanContext { uintmax_t packetCount; uintmax_t ethernetPacketCount; uintmax_t arpPacketCount; uintmax_t byteCount; unsigned int maxPacketLength; unsigned int minPacketLength; int isEthernet; struct timeval startTime; struct timeval endTime; std::map<std::string, long> packetCountPerSourceMac; std::map<std::string, long> packetCountPerDestMac; std::map<std::string, std::string> ipToMac; ScanContext() : packetCount(0), ethernetPacketCount(0), arpPacketCount(0), byteCount(0), maxPacketLength(0), minPacketLength(0), isEthernet(0) { memset(&this->startTime, 0, sizeof(struct timeval)); memset(&this->endTime, 0, sizeof(struct timeval)); } }; #define TABLE_BITMASK 0xF #define TABLE_SIZE (TABLE_BITMASK+1) static char* macToString(const unsigned char* bytes) { static char mac[TABLE_SIZE][20]; static int count = 0; count++; snprintf(mac[count & TABLE_BITMASK], 20, "%02x:%02x:%02x:%02x:%02x:%02x", bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5]); return mac[count & TABLE_BITMASK]; } static char* ipv4ToString(const unsigned char* bytes) { static char ip[TABLE_SIZE][16]; static int count = 0; count++; snprintf(ip[count & TABLE_BITMASK], 16, "%u.%u.%u.%u", bytes[0], bytes[1], bytes[2], bytes[3]); return ip[count & TABLE_BITMASK]; } static void insertOrIncrementCounter(std::map<std::string, long> &map, std::string &key) { if(map.find(key) != map.end()) { map[key]++; } else { map[key] = 1; } } static std::string insertOrReplaceMac(std::map<std::string, std::string> &map, std::string &key, std::string &value) { std::string tmp = ""; if(map.find(key) != map.end()) { tmp = map[key]; } map[key] = value; return tmp; } static void handlePossibleEthernetPacket(u_char *user, const struct pcap_pkthdr *h, const u_char *bytes) { ScanContext* ctx = (struct ScanContext*) user; if(ctx->packetCount == 0) { ctx->startTime = h->ts; } else { // we don't know what the last packet will be... ctx->endTime = h->ts; } ctx->packetCount++; if(h->len > ctx->maxPacketLength) { ctx->maxPacketLength = h->len; } if(ctx->minPacketLength == 0 || h->len < ctx->minPacketLength) { ctx->minPacketLength = h->len; } ctx->byteCount += h->len; if(ctx->isEthernet) { ctx->ethernetPacketCount++; if(h->caplen >= 12) { std::string sourceMacString = macToString(bytes+6); std::string destMacString = macToString(bytes); insertOrIncrementCounter(ctx->packetCountPerDestMac, destMacString); insertOrIncrementCounter(ctx->packetCountPerSourceMac, sourceMacString); } } } static void handleArpPacket(u_char *user, const struct pcap_pkthdr *h, const u_char *bytes) { ScanContext* ctx = (struct ScanContext*) user; ctx->arpPacketCount++; // 14 byte Ethernet header + 28 byte ARP header if(h->caplen >= 42) { // XXX check h->caplen uint16_t hardwareFormat; uint16_t protocolFormat; uint8_t hardwareLen; uint8_t protocolLen; uint16_t operation; uint8_t sourceHardware[6]; uint8_t sourceProtocol[4]; uint8_t targetHardware[6]; uint8_t targetProtocol[4]; char* senderMac = NULL; char* senderIp = NULL; char* targetMac = NULL; char* targetIp = NULL; // skip Ethernet header // TODO ensure 14-byte Ethernet is the only encapsulation type const u_char* arp_hdr = bytes + 14; memcpy(&hardwareFormat, arp_hdr , 2); memcpy(&protocolFormat, arp_hdr + 2, 2); hardwareFormat = htons(hardwareFormat); protocolFormat = htons(protocolFormat); hardwareLen = *(arp_hdr + 4); protocolLen = *(arp_hdr + 5); if(hardwareLen != 6) { fprintf(stderr, "[!] ARP: Unexpected hardware length\n"); return; } if(protocolLen != 4) { fprintf(stderr, "[!] ARP: Unexpected protocol length\n"); return; } if(protocolFormat != 0x800) { fprintf(stderr, "[!] ARP: Unexpected protocol type\n"); return; } if(hardwareFormat != 1) { fprintf(stderr, "[!] ARP: Unexpected hardware type\n"); return; } memcpy(&operation, arp_hdr + 6, 2); operation = htons(operation); senderMac = macToString(arp_hdr + 8); senderIp = ipv4ToString(arp_hdr + 14); targetMac = macToString(arp_hdr + 18); targetIp = ipv4ToString(arp_hdr + 24); #if 0 fprintf(stderr, "arp caplen=%d hFormat=%d pFormat=%d hLen=%d pLen=%d op=0x%04x sender(%s, %s) target(%s, %s)\n", h->caplen, hardwareFormat, protocolFormat, hardwareLen, protocolLen, operation, senderMac, senderIp, targetMac, targetIp ); #endif // Update ARP information with address of sender std::string senderIpString = senderIp; std::string senderMacString = senderMac; // if the sender isn't claiming it owns an IP address, don't update the table if(senderIpString.compare("0.0.0.0")) { std::string previous = insertOrReplaceMac(ctx->ipToMac, senderIpString, senderMacString); if(previous.compare("") != 0 && previous.compare(senderIp) == 0) { fprintf(stderr, "[!] %s rebound: was bound to %s\n", senderIp, previous.c_str()); } } } #if 0 else { fprintf(stderr, "[!] Truncated ARP packet\n"); } #endif } static void printCountPerAddress(std::map<std::string, long> &macToCount) { std::map<std::string, long>::iterator it; for (it = macToCount.begin(); it != macToCount.end(); it++) { printf("%8ld %s\n", it->second, it->first.c_str()); } } static void printIpToMac(std::map<std::string, std::string> &ipToMac) { std::map<std::string, std::string>::iterator it; for (it = ipToMac.begin(); it != ipToMac.end(); it++) { printf(" %-16s %20s\n", it->first.c_str(), it->second.c_str()); } } static inline const char* timevalToLocalTime(struct timeval* time) { time_t unixTime = time->tv_sec; struct tm* localTime = localtime(&unixTime); char* localTimeString = asctime(localTime); // note: the result from asctime() has a '\n' at the end, so we truncate it if(localTimeString) { localTimeString[strlen(localTimeString) - 1] = '\0'; } return localTimeString ? localTimeString : "?"; } static void printStatistics(struct ScanContext* ctx) { printf("%ju packets\n", ctx->packetCount); printf("%ju Ethernet packets\n", ctx->ethernetPacketCount); printf("%ju ARP packets\n", ctx->arpPacketCount); printf("Min size packet: %u\n", ctx->minPacketLength); printf("Max size packet: %u\n", ctx->maxPacketLength); if(0 != ctx->packetCount) { printf("Average size packet: %ju\n", ctx->byteCount / ctx->packetCount); } printf("Start time: %ju.%06ju seconds (%s)\n", (uintmax_t) ctx->startTime.tv_sec, (uintmax_t) ctx->startTime.tv_usec, timevalToLocalTime(&ctx->startTime)); printf("End time: %ju.%06ju seconds (%s)\n", (uintmax_t) ctx->endTime.tv_sec, (uintmax_t) ctx->endTime.tv_usec, timevalToLocalTime(&ctx->endTime)); long totalCaptureTime = ctx->endTime.tv_sec - ctx->startTime.tv_sec; if(0 == totalCaptureTime) { // round up to avoid divide by zero totalCaptureTime = 1; } printf("Total time: %ld seconds (%ld.%01ld minutes)\n", totalCaptureTime, totalCaptureTime / 60, totalCaptureTime % 60 * 10 / 60); printf("Total bytes captured: %ju bytes / %ju kilobytes / %ju megabytes\n", ctx->byteCount, ctx->byteCount / 1024, ctx->byteCount / 1024 / 1024); long kilobits = ctx->byteCount * 8 / 1024; long kilobitsPerSecond = kilobits / totalCaptureTime; printf("Overall capture speed: %ld Kbps (%ld Mbps)\n", kilobitsPerSecond, kilobitsPerSecond / 1024); if(!ctx->packetCountPerDestMac.empty()) { printf("\nEthernet destinations:\n"); printCountPerAddress(ctx->packetCountPerDestMac); } if(!ctx->packetCountPerSourceMac.empty()) { printf("\nEthernet sources:\n"); printCountPerAddress(ctx->packetCountPerSourceMac); } if(!ctx->ipToMac.empty()) { printf("\nARP table:\n"); printIpToMac(ctx->ipToMac); } } static int applyCaptureFilter(pcap_t* pcap, const char* filter) { int result = 0; struct bpf_program* bpf = (struct bpf_program*) calloc(1, sizeof(struct bpf_program)); if(NULL == bpf) { perror("calloc"); result = -1; goto exit; } if(-1 == pcap_compile(pcap, bpf, filter, 1 /* optimize */, PCAP_NETMASK_UNKNOWN)) { // TODO: need a -v flag? // this error will trigger for captures with zero ARPs, for example //fprintf(stderr, "%s\n", pcap_geterr(pcap)); result = -1; goto exit; } if(-1 == pcap_setfilter(pcap, bpf)) { fprintf(stderr, "%s\n", pcap_geterr(pcap)); result = -1; goto exit; } exit: if(NULL != bpf) { pcap_freecode(bpf); free(bpf); } return result; } int main(int argc, char* argv[]) { int result = 0; pcap_t* pcap; char errbuf[PCAP_ERRBUF_SIZE]; struct ScanContext ctx; if(argc < 2) { fprintf(stderr, "Not enough arguments. Please specify a pcap file.\n"); result = 2; goto exit; } pcap = pcap_open_offline(argv[1], errbuf); if(NULL == pcap) { fprintf(stderr, "%s\n", errbuf); result = 3; goto exit; } if(DLT_EN10MB == pcap_datalink(pcap)) { ctx.isEthernet = 1; } pcap_loop(pcap, -1, handlePossibleEthernetPacket, (u_char*) &ctx); // reopen file and check against a capture filter pcap_close(pcap); pcap = pcap_open_offline(argv[1], errbuf); if(NULL == pcap) { fprintf(stderr, "%s\n", errbuf); result = 4; goto exit; } if(0 != applyCaptureFilter(pcap, "arp")) { // expression could reject all packets and throw an error goto skip_arp; } pcap_loop(pcap, -1, handleArpPacket, (u_char*) &ctx); skip_arp: pcap_close(pcap); // All done with packet processing. printStatistics(&ctx); exit: return result; } <|endoftext|>
<commit_before>#include <SDL2/SDL.h> #include "cudaray.h" int main( int argc, char * argv[] ) { SDL_Init( SDL_INIT_VIDEO ); static const int width = 200; static const int height = 200; SDL_Window * window; SDL_Renderer * renderer; SDL_CreateWindowAndRenderer( width, height, SDL_WINDOW_SHOWN, &window, &renderer ); SDL_Texture * texture = SDL_CreateTexture( renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, width, height ); SDL_RenderSetLogicalSize( renderer, width, height ); t_sphere sphere; vec3_set( sphere.position, 100.0f, 75.0, 0.0f ); vec3_set( sphere.color, 1.0f, 1.0f, 1.0f ); sphere.radius = 50.0f; const float light_distance = 30.0f; t_vec3 shift; t_light lights[4]; vec3_set( lights[0].color, 1.0f, 0.25f, 0.25f ); vec3_set( lights[1].color, 0.25f, 0.25f, 1.0f ); vec3_set( lights[2].color, 0.25f, 1.0f, 0.25f ); vec3_set( lights[3].color, 0.25f, 0.25f, 0.25f ); int n_lights = sizeof( lights ) / sizeof( t_light ); uint32_t img[ width ][ height ]; memset( &img, 0, sizeof( img ) ); float t = 0.0f; float speed = 0.3f; int acceleration = 0;; for( ;; ) { SDL_Event event; while( SDL_PollEvent( &event ) ) { switch( event.type ) { case SDL_KEYUP: switch( event.key.keysym.sym ) { case SDLK_ESCAPE: return 0; case SDLK_RIGHT: if( !event.key.repeat ) acceleration -= 1; break; case SDLK_LEFT: if( !event.key.repeat ) acceleration += 1; break; } break; case SDL_KEYDOWN: switch( event.key.keysym.sym ) { case SDLK_RIGHT: if( !event.key.repeat ) acceleration += 1; break; case SDLK_LEFT: if( !event.key.repeat ) acceleration -= 1; break; } break; } } for( int i = 0; i < n_lights; ++i ) vec3_dup( lights[i].position, sphere.position ); vec3_set( shift, (sphere.radius + light_distance) * cosf(t), 0.0f, (sphere.radius + light_distance) * sinf(t) ); vec3_add( lights[0].position, shift ); vec3_set( shift, 0.0f, (sphere.radius + light_distance) * cosf(t), (sphere.radius + light_distance) * sinf(t) ); vec3_add( lights[1].position, shift ); vec3_set( shift, (sphere.radius + light_distance) * cosf(t * 0.75f), (sphere.radius + light_distance) * cosf(t * 0.75f), (sphere.radius + light_distance) * sinf(t * 0.75f) ); vec3_add( lights[2].position, shift ); vec3_set( shift, 0.0f, 0.0f, sphere.radius + 200.0f ); vec3_add( lights[3].position, shift ); cuda_main( width, height, (uint32_t *)img, &sphere, 1, lights, n_lights ); SDL_UpdateTexture( texture, NULL, img, width * sizeof( uint32_t ) ); SDL_RenderClear( renderer ); SDL_RenderCopy( renderer, texture, NULL, NULL ); SDL_RenderPresent( renderer ); SDL_Delay( 16 ); t += speed; speed += acceleration * 0.01f; } SDL_DestroyWindow( window ); SDL_Quit(); return 0; } <commit_msg>Fix compilation on Windows.<commit_after>#include <SDL2/SDL.h> #ifdef main #undef main #endif #include "cudaray.h" int main( int argc, char * argv[] ) { SDL_Init( SDL_INIT_VIDEO ); static const int width = 200; static const int height = 200; SDL_Window * window; SDL_Renderer * renderer; SDL_CreateWindowAndRenderer( width, height, SDL_WINDOW_SHOWN, &window, &renderer ); SDL_Texture * texture = SDL_CreateTexture( renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, width, height ); SDL_RenderSetLogicalSize( renderer, width, height ); t_sphere sphere; vec3_set( sphere.position, 100.0f, 75.0, 0.0f ); vec3_set( sphere.color, 1.0f, 1.0f, 1.0f ); sphere.radius = 50.0f; const float light_distance = 30.0f; t_vec3 shift; t_light lights[4]; vec3_set( lights[0].color, 1.0f, 0.25f, 0.25f ); vec3_set( lights[1].color, 0.25f, 0.25f, 1.0f ); vec3_set( lights[2].color, 0.25f, 1.0f, 0.25f ); vec3_set( lights[3].color, 0.25f, 0.25f, 0.25f ); int n_lights = sizeof( lights ) / sizeof( t_light ); uint32_t img[ width ][ height ]; memset( &img, 0, sizeof( img ) ); float t = 0.0f; float speed = 0.3f; int acceleration = 0;; for( ;; ) { SDL_Event event; while( SDL_PollEvent( &event ) ) { switch( event.type ) { case SDL_KEYUP: switch( event.key.keysym.sym ) { case SDLK_ESCAPE: return 0; case SDLK_RIGHT: if( !event.key.repeat ) acceleration -= 1; break; case SDLK_LEFT: if( !event.key.repeat ) acceleration += 1; break; } break; case SDL_KEYDOWN: switch( event.key.keysym.sym ) { case SDLK_RIGHT: if( !event.key.repeat ) acceleration += 1; break; case SDLK_LEFT: if( !event.key.repeat ) acceleration -= 1; break; } break; } } for( int i = 0; i < n_lights; ++i ) vec3_dup( lights[i].position, sphere.position ); vec3_set( shift, (sphere.radius + light_distance) * cosf(t), 0.0f, (sphere.radius + light_distance) * sinf(t) ); vec3_add( lights[0].position, shift ); vec3_set( shift, 0.0f, (sphere.radius + light_distance) * cosf(t), (sphere.radius + light_distance) * sinf(t) ); vec3_add( lights[1].position, shift ); vec3_set( shift, (sphere.radius + light_distance) * cosf(t * 0.75f), (sphere.radius + light_distance) * cosf(t * 0.75f), (sphere.radius + light_distance) * sinf(t * 0.75f) ); vec3_add( lights[2].position, shift ); vec3_set( shift, 0.0f, 0.0f, sphere.radius + 200.0f ); vec3_add( lights[3].position, shift ); cuda_main( width, height, (uint32_t *)img, &sphere, 1, lights, n_lights ); SDL_UpdateTexture( texture, NULL, img, width * sizeof( uint32_t ) ); SDL_RenderClear( renderer ); SDL_RenderCopy( renderer, texture, NULL, NULL ); SDL_RenderPresent( renderer ); SDL_Delay( 16 ); t += speed; speed += acceleration * 0.01f; } SDL_DestroyWindow( window ); SDL_Quit(); return 0; } <|endoftext|>
<commit_before>#include <chainparams.h> #include "witness.h" void CoinWitnessData::SetNull() { coin = nullptr; pAccumulator = nullptr; pWitness = nullptr; nMintsAdded = 0; nHeightMintAdded = 0; nHeightCheckpoint = 0; nHeightAccStart = 0; nHeightAccEnd = 0; } CoinWitnessData::CoinWitnessData() { SetNull(); } CoinWitnessData::CoinWitnessData(CZerocoinMint& mint) { denom = mint.GetDenomination(); isV1 = libzerocoin::ExtractVersionFromSerial(mint.GetSerialNumber()) < libzerocoin::PrivateCoin::PUBKEY_VERSION; libzerocoin::ZerocoinParams* paramsCoin = Params().Zerocoin_Params(isV1); coin = std::unique_ptr<libzerocoin::PublicCoin>(new libzerocoin::PublicCoin(paramsCoin, mint.GetValue(), denom)); libzerocoin::Accumulator accumulator1(Params().Zerocoin_Params(false), denom); pWitness = std::unique_ptr<libzerocoin::AccumulatorWitness>(new libzerocoin::AccumulatorWitness(Params().Zerocoin_Params(false), accumulator1, *coin)); } void CoinWitnessData::SetHeightMintAdded(int nHeight) { nHeightMintAdded = nHeight; nHeightCheckpoint = nHeight + (10 - (nHeight % 10)); nHeightAccStart = nHeight - (nHeight % 10); } <commit_msg>set the accumulator start height when initializing the witness<commit_after>#include <chainparams.h> #include "witness.h" void CoinWitnessData::SetNull() { coin = nullptr; pAccumulator = nullptr; pWitness = nullptr; nMintsAdded = 0; nHeightMintAdded = 0; nHeightCheckpoint = 0; nHeightAccStart = 0; nHeightAccEnd = 0; } CoinWitnessData::CoinWitnessData() { SetNull(); } CoinWitnessData::CoinWitnessData(CZerocoinMint& mint) { denom = mint.GetDenomination(); isV1 = libzerocoin::ExtractVersionFromSerial(mint.GetSerialNumber()) < libzerocoin::PrivateCoin::PUBKEY_VERSION; libzerocoin::ZerocoinParams* paramsCoin = Params().Zerocoin_Params(isV1); coin = std::unique_ptr<libzerocoin::PublicCoin>(new libzerocoin::PublicCoin(paramsCoin, mint.GetValue(), denom)); libzerocoin::Accumulator accumulator1(Params().Zerocoin_Params(false), denom); pWitness = std::unique_ptr<libzerocoin::AccumulatorWitness>(new libzerocoin::AccumulatorWitness(Params().Zerocoin_Params(false), accumulator1, *coin)); nHeightAccStart = mint.GetHeight(); } void CoinWitnessData::SetHeightMintAdded(int nHeight) { nHeightMintAdded = nHeight; nHeightCheckpoint = nHeight + (10 - (nHeight % 10)); nHeightAccStart = nHeight - (nHeight % 10); } <|endoftext|>
<commit_before>/* * Copyright (C) 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once // This is an implementation of a random-access compressed file compatible // with Cassandra's org.apache.cassandra.io.compress compressed files. // // To allow reasonably-efficient seeking in the compressed file, the file // is not compressed as a whole, but rather divided into chunks of a known // size (by default, 64 KB), where each chunk is compressed individually. // The compressed size of each chunk is different, so for allowing seeking // to a particular position in the uncompressed data, we need to also know // the position of each chunk. This offset vector is supplied externally as // a "compression_metadata" object, which also contains additional information // needed from decompression - such as the chunk size and compressor type. // // Cassandra supports three different compression algorithms for the chunks, // LZ4, Snappy, and Deflate - the default (and therefore most important) is // LZ4. Each compressor is an implementation of the "compressor" class. // // Each compressed chunk is followed by a 4-byte checksum of the compressed // data, using the Adler32 or CRC32 algorithm. In Cassandra, there is a parameter // "crc_check_chance" (defaulting to 1.0) which determines the probability // of us verifying the checksum of each chunk we read. // // This implementation does not cache the compressed disk blocks (which // are read using O_DIRECT), nor uncompressed data. We intend to cache high- // level Cassandra rows, not disk blocks. #include <vector> #include <cstdint> #include <iterator> #include <seastar/core/file.hh> #include <seastar/core/reactor.hh> #include <seastar/core/shared_ptr.hh> #include <seastar/core/fstream.hh> #include "types.hh" #include "checksum_utils.hh" #include "../compress.hh" class compression_parameters; class compressor; using compressor_ptr = shared_ptr<compressor>; namespace sstables { struct compression; struct compression { // To reduce the memory footpring of compression-info, n offsets are grouped // together into segments, where each segment stores a base absolute offset // into the file, the other offsets in the segments being relative offsets // (and thus of reduced size). Also offsets are allocated only just enough // bits to store their maximum value. The offsets are thus packed in a // buffer like so: // arrrarrrarrr... // where n is 4, a is an absolute offset and r are offsets relative to a. // Segments are stored in buckets, where each bucket has its own base offset. // Segments in a buckets are optimized to address as large of a chunk of the // data as possible for a given chunk size and bucket size. // // This is not a general purpose container. There are limitations: // * Can't be used before init() is called. // * at() is best called incrementally, altough random lookups are // perfectly valid as well. // * The iterator and at() can't provide references to the elements. // * No point insert is available. class segmented_offsets { public: class state { std::size_t _current_index{0}; std::size_t _current_bucket_index{0}; uint64_t _current_bucket_segment_index{0}; uint64_t _current_segment_relative_index{0}; uint64_t _current_segment_offset_bits{0}; void update_position_trackers(std::size_t index, uint16_t segment_size_bits, uint32_t segments_per_bucket, uint8_t grouped_offsets); friend class segmented_offsets; }; class accessor { const segmented_offsets& _offsets; mutable state _state; public: accessor(const segmented_offsets& offsets) : _offsets(offsets) { } uint64_t at(std::size_t i) const { return _offsets.at(i, _state); } }; class writer { segmented_offsets& _offsets; state _state; public: writer(segmented_offsets& offsets) : _offsets(offsets) { } void push_back(uint64_t offset) { return _offsets.push_back(offset, _state); } }; accessor get_accessor() const { return accessor(*this); } writer get_writer() { return writer(*this); } private: struct bucket { uint64_t base_offset; std::unique_ptr<char[]> storage; }; uint32_t _chunk_size{0}; uint8_t _segment_base_offset_size_bits{0}; uint8_t _segmented_offset_size_bits{0}; uint16_t _segment_size_bits{0}; uint32_t _segments_per_bucket{0}; uint8_t _grouped_offsets{0}; uint64_t _last_written_offset{0}; std::size_t _size{0}; std::deque<bucket> _storage; uint64_t read(uint64_t bucket_index, uint64_t offset_bits, uint64_t size_bits) const; void write(uint64_t bucket_index, uint64_t offset_bits, uint64_t size_bits, uint64_t value); uint64_t at(std::size_t i, state& s) const; void push_back(uint64_t offset, state& s); public: class const_iterator : public std::iterator<std::random_access_iterator_tag, const uint64_t> { friend class segmented_offsets; struct end_tag {}; segmented_offsets::accessor _offsets; std::size_t _index; const_iterator(const segmented_offsets& offsets) : _offsets(offsets.get_accessor()) , _index(0) { } const_iterator(const segmented_offsets& offsets, end_tag) : _offsets(offsets.get_accessor()) , _index(offsets.size()) { } public: const_iterator(const const_iterator& other) = default; const_iterator& operator=(const const_iterator& other) { assert(&_offsets == &other._offsets); _index = other._index; return *this; } const_iterator operator++(int) { const_iterator it{*this}; return ++it; } const_iterator& operator++() { *this += 1; return *this; } const_iterator operator+(ssize_t i) const { const_iterator it{*this}; it += i; return it; } const_iterator& operator+=(ssize_t i) { _index += i; return *this; } const_iterator operator--(int) { const_iterator it{*this}; return --it; } const_iterator& operator--() { *this -= 1; return *this; } const_iterator operator-(ssize_t i) const { const_iterator it{*this}; it -= i; return it; } const_iterator& operator-=(ssize_t i) { _index -= i; return *this; } value_type operator*() const { return _offsets.at(_index); } value_type operator[](ssize_t i) const { return _offsets.at(_index + i); } bool operator==(const const_iterator& other) const { return _index == other._index; } bool operator!=(const const_iterator& other) const { return !(*this == other); } bool operator<(const const_iterator& other) const { return _index < other._index; } bool operator<=(const const_iterator& other) const { return _index <= other._index; } bool operator>(const const_iterator& other) const { return _index > other._index; } bool operator>=(const const_iterator& other) const { return _index >= other._index; } }; segmented_offsets() = default; segmented_offsets(const segmented_offsets&) = delete; segmented_offsets& operator=(const segmented_offsets&) = delete; segmented_offsets(segmented_offsets&&) = default; segmented_offsets& operator=(segmented_offsets&&) = default; // Has to be called before using the class. Doing otherwise // results in undefined behaviour! Don't call more than once! // TODO: fold into constructor, once the parse() et. al. code // allows it. void init(uint32_t chunk_size); uint32_t chunk_size() const noexcept { return _chunk_size; } std::size_t size() const noexcept { return _size; } const_iterator begin() const { return const_iterator(*this); } const_iterator end() const { return const_iterator(*this, const_iterator::end_tag{}); } const_iterator cbegin() const { return const_iterator(*this); } const_iterator cend() const { return const_iterator(*this, const_iterator::end_tag{}); } }; disk_string<uint16_t> name; disk_array<uint32_t, option> options; uint32_t chunk_len = 0; uint64_t data_len = 0; segmented_offsets offsets; private: // Variables *not* found in the "Compression Info" file (added by update()): uint64_t _compressed_file_length = 0; uint32_t _full_checksum = 0; public: // Set the compressor algorithm, please check the definition of enum compressor. void set_compressor(compressor_ptr c); // After changing _compression, update() must be called to update // additional variables depending on it. void update(uint64_t compressed_file_length); operator bool() const { return !name.value.empty(); } // locate() locates in the compressed file the given byte position of // the uncompressed data: // 1. The byte range containing the appropriate compressed chunk, and // 2. the offset into the uncompressed chunk. // Note that the last 4 bytes of the returned chunk are not the actual // compressed data, but rather the checksum of the compressed data. // locate() throws an out-of-range exception if the position is beyond // the last chunk. struct chunk_and_offset { uint64_t chunk_start; uint64_t chunk_len; // variable size of compressed chunk unsigned offset; // offset into chunk after uncompressing it }; chunk_and_offset locate(uint64_t position, const compression::segmented_offsets::accessor& accessor); unsigned uncompressed_chunk_length() const noexcept { return chunk_len; } void set_uncompressed_chunk_length(uint32_t cl) { chunk_len = cl; offsets.init(chunk_len); } uint64_t uncompressed_file_length() const noexcept { return data_len; } void set_uncompressed_file_length(uint64_t fl) { data_len = fl; } uint64_t compressed_file_length() const { return _compressed_file_length; } void set_compressed_file_length(uint64_t compressed_file_length) { _compressed_file_length = compressed_file_length; } uint32_t get_full_checksum() const { return _full_checksum; } void set_full_checksum(uint32_t checksum) { _full_checksum = checksum; } friend class sstable; }; // Note: compression_metadata is passed by reference; The caller is // responsible for keeping the compression_metadata alive as long as there // are open streams on it. This should happen naturally on a higher level - // as long as we have *sstables* work in progress, we need to keep the whole // sstable alive, and the compression metadata is only a part of it. input_stream<char> make_compressed_file_k_l_format_input_stream(file f, sstables::compression* cm, uint64_t offset, size_t len, class file_input_stream_options options); output_stream<char> make_compressed_file_k_l_format_output_stream(file f, file_output_stream_options options, sstables::compression* cm, const compression_parameters& cp); input_stream<char> make_compressed_file_m_format_input_stream(file f, sstables::compression* cm, uint64_t offset, size_t len, class file_input_stream_options options); output_stream<char> make_compressed_file_m_format_output_stream(file f, file_output_stream_options options, sstables::compression* cm, const compression_parameters& cp); } <commit_msg>sstables: compress.hh: add missing include<commit_after>/* * Copyright (C) 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once // This is an implementation of a random-access compressed file compatible // with Cassandra's org.apache.cassandra.io.compress compressed files. // // To allow reasonably-efficient seeking in the compressed file, the file // is not compressed as a whole, but rather divided into chunks of a known // size (by default, 64 KB), where each chunk is compressed individually. // The compressed size of each chunk is different, so for allowing seeking // to a particular position in the uncompressed data, we need to also know // the position of each chunk. This offset vector is supplied externally as // a "compression_metadata" object, which also contains additional information // needed from decompression - such as the chunk size and compressor type. // // Cassandra supports three different compression algorithms for the chunks, // LZ4, Snappy, and Deflate - the default (and therefore most important) is // LZ4. Each compressor is an implementation of the "compressor" class. // // Each compressed chunk is followed by a 4-byte checksum of the compressed // data, using the Adler32 or CRC32 algorithm. In Cassandra, there is a parameter // "crc_check_chance" (defaulting to 1.0) which determines the probability // of us verifying the checksum of each chunk we read. // // This implementation does not cache the compressed disk blocks (which // are read using O_DIRECT), nor uncompressed data. We intend to cache high- // level Cassandra rows, not disk blocks. #include <vector> #include <cstdint> #include <iterator> #include <seastar/core/file.hh> #include <seastar/core/reactor.hh> #include <seastar/core/shared_ptr.hh> #include <seastar/core/fstream.hh> #include "types.hh" #include "sstables/types.hh" #include "checksum_utils.hh" #include "../compress.hh" class compression_parameters; class compressor; using compressor_ptr = shared_ptr<compressor>; namespace sstables { struct compression; struct compression { // To reduce the memory footpring of compression-info, n offsets are grouped // together into segments, where each segment stores a base absolute offset // into the file, the other offsets in the segments being relative offsets // (and thus of reduced size). Also offsets are allocated only just enough // bits to store their maximum value. The offsets are thus packed in a // buffer like so: // arrrarrrarrr... // where n is 4, a is an absolute offset and r are offsets relative to a. // Segments are stored in buckets, where each bucket has its own base offset. // Segments in a buckets are optimized to address as large of a chunk of the // data as possible for a given chunk size and bucket size. // // This is not a general purpose container. There are limitations: // * Can't be used before init() is called. // * at() is best called incrementally, altough random lookups are // perfectly valid as well. // * The iterator and at() can't provide references to the elements. // * No point insert is available. class segmented_offsets { public: class state { std::size_t _current_index{0}; std::size_t _current_bucket_index{0}; uint64_t _current_bucket_segment_index{0}; uint64_t _current_segment_relative_index{0}; uint64_t _current_segment_offset_bits{0}; void update_position_trackers(std::size_t index, uint16_t segment_size_bits, uint32_t segments_per_bucket, uint8_t grouped_offsets); friend class segmented_offsets; }; class accessor { const segmented_offsets& _offsets; mutable state _state; public: accessor(const segmented_offsets& offsets) : _offsets(offsets) { } uint64_t at(std::size_t i) const { return _offsets.at(i, _state); } }; class writer { segmented_offsets& _offsets; state _state; public: writer(segmented_offsets& offsets) : _offsets(offsets) { } void push_back(uint64_t offset) { return _offsets.push_back(offset, _state); } }; accessor get_accessor() const { return accessor(*this); } writer get_writer() { return writer(*this); } private: struct bucket { uint64_t base_offset; std::unique_ptr<char[]> storage; }; uint32_t _chunk_size{0}; uint8_t _segment_base_offset_size_bits{0}; uint8_t _segmented_offset_size_bits{0}; uint16_t _segment_size_bits{0}; uint32_t _segments_per_bucket{0}; uint8_t _grouped_offsets{0}; uint64_t _last_written_offset{0}; std::size_t _size{0}; std::deque<bucket> _storage; uint64_t read(uint64_t bucket_index, uint64_t offset_bits, uint64_t size_bits) const; void write(uint64_t bucket_index, uint64_t offset_bits, uint64_t size_bits, uint64_t value); uint64_t at(std::size_t i, state& s) const; void push_back(uint64_t offset, state& s); public: class const_iterator : public std::iterator<std::random_access_iterator_tag, const uint64_t> { friend class segmented_offsets; struct end_tag {}; segmented_offsets::accessor _offsets; std::size_t _index; const_iterator(const segmented_offsets& offsets) : _offsets(offsets.get_accessor()) , _index(0) { } const_iterator(const segmented_offsets& offsets, end_tag) : _offsets(offsets.get_accessor()) , _index(offsets.size()) { } public: const_iterator(const const_iterator& other) = default; const_iterator& operator=(const const_iterator& other) { assert(&_offsets == &other._offsets); _index = other._index; return *this; } const_iterator operator++(int) { const_iterator it{*this}; return ++it; } const_iterator& operator++() { *this += 1; return *this; } const_iterator operator+(ssize_t i) const { const_iterator it{*this}; it += i; return it; } const_iterator& operator+=(ssize_t i) { _index += i; return *this; } const_iterator operator--(int) { const_iterator it{*this}; return --it; } const_iterator& operator--() { *this -= 1; return *this; } const_iterator operator-(ssize_t i) const { const_iterator it{*this}; it -= i; return it; } const_iterator& operator-=(ssize_t i) { _index -= i; return *this; } value_type operator*() const { return _offsets.at(_index); } value_type operator[](ssize_t i) const { return _offsets.at(_index + i); } bool operator==(const const_iterator& other) const { return _index == other._index; } bool operator!=(const const_iterator& other) const { return !(*this == other); } bool operator<(const const_iterator& other) const { return _index < other._index; } bool operator<=(const const_iterator& other) const { return _index <= other._index; } bool operator>(const const_iterator& other) const { return _index > other._index; } bool operator>=(const const_iterator& other) const { return _index >= other._index; } }; segmented_offsets() = default; segmented_offsets(const segmented_offsets&) = delete; segmented_offsets& operator=(const segmented_offsets&) = delete; segmented_offsets(segmented_offsets&&) = default; segmented_offsets& operator=(segmented_offsets&&) = default; // Has to be called before using the class. Doing otherwise // results in undefined behaviour! Don't call more than once! // TODO: fold into constructor, once the parse() et. al. code // allows it. void init(uint32_t chunk_size); uint32_t chunk_size() const noexcept { return _chunk_size; } std::size_t size() const noexcept { return _size; } const_iterator begin() const { return const_iterator(*this); } const_iterator end() const { return const_iterator(*this, const_iterator::end_tag{}); } const_iterator cbegin() const { return const_iterator(*this); } const_iterator cend() const { return const_iterator(*this, const_iterator::end_tag{}); } }; disk_string<uint16_t> name; disk_array<uint32_t, option> options; uint32_t chunk_len = 0; uint64_t data_len = 0; segmented_offsets offsets; private: // Variables *not* found in the "Compression Info" file (added by update()): uint64_t _compressed_file_length = 0; uint32_t _full_checksum = 0; public: // Set the compressor algorithm, please check the definition of enum compressor. void set_compressor(compressor_ptr c); // After changing _compression, update() must be called to update // additional variables depending on it. void update(uint64_t compressed_file_length); operator bool() const { return !name.value.empty(); } // locate() locates in the compressed file the given byte position of // the uncompressed data: // 1. The byte range containing the appropriate compressed chunk, and // 2. the offset into the uncompressed chunk. // Note that the last 4 bytes of the returned chunk are not the actual // compressed data, but rather the checksum of the compressed data. // locate() throws an out-of-range exception if the position is beyond // the last chunk. struct chunk_and_offset { uint64_t chunk_start; uint64_t chunk_len; // variable size of compressed chunk unsigned offset; // offset into chunk after uncompressing it }; chunk_and_offset locate(uint64_t position, const compression::segmented_offsets::accessor& accessor); unsigned uncompressed_chunk_length() const noexcept { return chunk_len; } void set_uncompressed_chunk_length(uint32_t cl) { chunk_len = cl; offsets.init(chunk_len); } uint64_t uncompressed_file_length() const noexcept { return data_len; } void set_uncompressed_file_length(uint64_t fl) { data_len = fl; } uint64_t compressed_file_length() const { return _compressed_file_length; } void set_compressed_file_length(uint64_t compressed_file_length) { _compressed_file_length = compressed_file_length; } uint32_t get_full_checksum() const { return _full_checksum; } void set_full_checksum(uint32_t checksum) { _full_checksum = checksum; } friend class sstable; }; // Note: compression_metadata is passed by reference; The caller is // responsible for keeping the compression_metadata alive as long as there // are open streams on it. This should happen naturally on a higher level - // as long as we have *sstables* work in progress, we need to keep the whole // sstable alive, and the compression metadata is only a part of it. input_stream<char> make_compressed_file_k_l_format_input_stream(file f, sstables::compression* cm, uint64_t offset, size_t len, class file_input_stream_options options); output_stream<char> make_compressed_file_k_l_format_output_stream(file f, file_output_stream_options options, sstables::compression* cm, const compression_parameters& cp); input_stream<char> make_compressed_file_m_format_input_stream(file f, sstables::compression* cm, uint64_t offset, size_t len, class file_input_stream_options options); output_stream<char> make_compressed_file_m_format_output_stream(file f, file_output_stream_options options, sstables::compression* cm, const compression_parameters& cp); } <|endoftext|>
<commit_before>#include "cpanel.h" #include "settings/csettings.h" #include "settings.h" #include "QtCoreIncludes" #include <assert.h> #include <time.h> #include <limits> const size_t CPanel::noHistory = std::numeric_limits<size_t>::max(); CPanel::CPanel(Panel position) : _currentHistoryLocation(noHistory), _panelPosition(position) { setPath(CSettings().value(_panelPosition == LeftPanel ? KEY_LPANEL_PATH : KEY_RPANEL_PATH, QDir::root().absolutePath()).toString()); } FileOperationResultCode CPanel::setPath(const QString &path) { #if defined __linux__ || defined __APPLE__ const QString posixPath(path.contains("~") ? QString(path).replace("~", getenv("HOME")) : path); #elif defined _WIN32 const QString posixPath(toPosixSeparators(path)); #else #error "Not implemented" #endif const QString oldPath = _currentDir.absolutePath(); _currentDir.setPath(posixPath); const QString newPath = _currentDir.absolutePath(); if (!_currentDir.exists() || _currentDir.entryList().isEmpty()) // No dot and dotdot on Linux means the dir is not accessible { _currentDir.setPath(oldPath); sendContentsChangedNotification(); return rcDirNotAccessible; } // History management if (_currentHistoryLocation == noHistory || _history.empty()) { assert (_history.empty() && _currentHistoryLocation == noHistory); _history.push_back(newPath); _currentHistoryLocation = 0; } else { assert (_currentHistoryLocation < _history.size()); if (toPosixSeparators(_history[_currentHistoryLocation]) != toPosixSeparators(newPath)) { _history.push_back(newPath); _currentHistoryLocation = _history.size() - 1; } } CSettings().setValue(_panelPosition == LeftPanel ? KEY_LPANEL_PATH : KEY_RPANEL_PATH, currentDirPath()); _watcher = std::make_shared<QFileSystemWatcher>(); #if QT_VERSION >= QT_VERSION_CHECK (5,0,0) const QString watchPath(newPath); #else const QString watchPath(posixPath); #endif if (_watcher->addPath(watchPath) == false) qDebug() << __FUNCTION__ << "Error adding path" << watchPath << "to QFileSystemWatcher"; connect (_watcher.get(), SIGNAL(directoryChanged(QString)), SLOT(contentsChanged(QString))); connect (_watcher.get(), SIGNAL(fileChanged(QString)), SLOT(contentsChanged(QString))); #if QT_VERSION >= QT_VERSION_CHECK (5,0,0) connect (_watcher.get(), SIGNAL(objectNameChanged(QString)), SLOT(contentsChanged(QString))); #endif // Finding hash of an item corresponding to path for (const CFileSystemObject& item: _list) { const QString itemPath = toPosixSeparators(item.absoluteFilePath()); if (posixPath == itemPath && toPosixSeparators(item.parentDirPath()) != itemPath) { setCurrentItemInFolder(item.parentDirPath(), item.properties().hash); break; } } refreshFileList(); return rcOk; } // Navigates up the directory tree void CPanel::navigateUp() { QDir tmpDir (_currentDir); if (tmpDir.cdUp()) setPath(tmpDir.absolutePath()); else sendContentsChangedNotification(); } // Go to the previous location from history bool CPanel::navigateBack() { if (_currentHistoryLocation > 0 && _currentHistoryLocation < _history.size()) return setPath(_history[--_currentHistoryLocation]) == rcOk; else sendContentsChangedNotification(); return false; } // Go to the next location from history, if any bool CPanel::navigateForward() { if (_currentHistoryLocation != noHistory && _currentHistoryLocation < _history.size() - 1) return setPath(_history[++_currentHistoryLocation]) == rcOk; else sendContentsChangedNotification(); return false; } // Info on the dir this panel is currently set to QString CPanel::currentDirPath() const { return toNativeSeparators(_currentDir.absolutePath()); } QString CPanel::currentDirName() const { return toNativeSeparators(_currentDir.dirName()); } void CPanel::setCurrentItemInFolder(const QString& dir, qulonglong currentItemHash) { _cursorPosForFolder[toPosixSeparators(dir)] = currentItemHash; } qulonglong CPanel::currentItemInFolder(const QString &dir) const { const auto it = _cursorPosForFolder.find(toPosixSeparators(dir)); if (it == _cursorPosForFolder.end()) return 0; else return it->second; } // Enumerates objects in the current directory void CPanel::refreshFileList() { time_t start = clock(); QFileInfoList list = _currentDir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDot | QDir::Hidden | QDir::System); _list.clear(); _indexByHash.clear(); const bool showHiddenFiles = CSettings().value(KEY_INTERFACE_SHOW_HIDDEN_FILES, true).toBool(); for (int i = 0; i < list.size(); ++i) { if (list[i].absoluteFilePath() != "/..") { _list.push_back(CFileSystemObject(list[i])); if (!_list.back().exists() || (!showHiddenFiles && _list.back().isHidden())) _list.pop_back(); else _indexByHash[_list.back().hash()] = _list.size() - 1; } } qDebug () << __FUNCTION__ << "Directory:" << _currentDir.absolutePath() << "," << _list.size() << "items," << (clock() - start) * 1000 / CLOCKS_PER_SEC << "ms"; sendContentsChangedNotification(); } // Returns the current list of objects on this panel const std::vector<CFileSystemObject> &CPanel::list() const { return _list; } // Access to the corresponding item const CFileSystemObject &CPanel::itemByIndex(size_t index) const { if (index < _list.size()) { return _list[index]; } else { assert (false); static CFileSystemObject dummyObject((QFileInfo())); return dummyObject; } } CFileSystemObject &CPanel::itemByIndex(size_t index) { if (index < _list.size()) return _list[index]; else { assert (false); static CFileSystemObject dummyObject ((QFileInfo())); return dummyObject; } } const CFileSystemObject& CPanel::itemByHash( qulonglong hash ) const { assert(_indexByHash.count(hash) > 0); return itemByIndex(_indexByHash.at(hash)); } CFileSystemObject& CPanel::itemByHash( qulonglong hash ) { assert(_indexByHash.count(hash) > 0); return itemByIndex(_indexByHash[hash]); } // Calculates directory size, stores it in the corresponding CFileSystemObject and sends data change notification void CPanel::calculateDirSize(qulonglong dirHash) { assert(dirHash != 0); CFileSystemObject& item = itemByHash(dirHash); if (item.isDir()) { uint64_t size = 0; std::vector <CFileSystemObject> objects = recurseDirectoryItems(item.absoluteFilePath(), false); for (auto& dirItem: objects) size += dirItem.size(); item.setDirSize(size); sendContentsChangedNotification(); } } void CPanel::sendContentsChangedNotification() const { for (auto listener: _panelContentsChangedListeners) listener->panelContentsChanged(_panelPosition); } // Settings have changed void CPanel::settingsChanged() { } void CPanel::contentsChanged(QString /*path*/) { refreshFileList(); } void CPanel::addPanelContentsChangedListener(PanelContentsChangedListener *listener) { assert(std::find(_panelContentsChangedListeners.begin(), _panelContentsChangedListeners.end(), listener) == _panelContentsChangedListeners.end()); // Why would we want to set the same listener twice? That'd probably be a mistake. _panelContentsChangedListeners.push_back(listener); sendContentsChangedNotification(); } <commit_msg>History navigation bugfix<commit_after>#include "cpanel.h" #include "settings/csettings.h" #include "settings.h" #include "QtCoreIncludes" #include <assert.h> #include <time.h> #include <limits> const size_t CPanel::noHistory = std::numeric_limits<size_t>::max(); CPanel::CPanel(Panel position) : _currentHistoryLocation(noHistory), _panelPosition(position) { setPath(CSettings().value(_panelPosition == LeftPanel ? KEY_LPANEL_PATH : KEY_RPANEL_PATH, QDir::root().absolutePath()).toString()); } FileOperationResultCode CPanel::setPath(const QString &path) { #if defined __linux__ || defined __APPLE__ const QString posixPath(path.contains("~") ? QString(path).replace("~", getenv("HOME")) : path); #elif defined _WIN32 const QString posixPath(toPosixSeparators(path)); #else #error "Not implemented" #endif const QString oldPath = _currentDir.absolutePath(); _currentDir.setPath(posixPath); const QString newPath = _currentDir.absolutePath(); if (!_currentDir.exists() || _currentDir.entryList().isEmpty()) // No dot and dotdot on Linux means the dir is not accessible { _currentDir.setPath(oldPath); sendContentsChangedNotification(); return rcDirNotAccessible; } // History management if (_currentHistoryLocation == noHistory || _history.empty()) { assert (_history.empty() && _currentHistoryLocation == noHistory); _history.push_back(newPath); _currentHistoryLocation = 0; } else { assert (_currentHistoryLocation < _history.size()); if (toPosixSeparators(_history[_currentHistoryLocation]) != toPosixSeparators(newPath)) { _history.push_back(newPath); _currentHistoryLocation = _history.size() - 1; } } CSettings().setValue(_panelPosition == LeftPanel ? KEY_LPANEL_PATH : KEY_RPANEL_PATH, currentDirPath()); _watcher = std::make_shared<QFileSystemWatcher>(); #if QT_VERSION >= QT_VERSION_CHECK (5,0,0) const QString watchPath(newPath); #else const QString watchPath(posixPath); #endif if (_watcher->addPath(watchPath) == false) qDebug() << __FUNCTION__ << "Error adding path" << watchPath << "to QFileSystemWatcher"; connect (_watcher.get(), SIGNAL(directoryChanged(QString)), SLOT(contentsChanged(QString))); connect (_watcher.get(), SIGNAL(fileChanged(QString)), SLOT(contentsChanged(QString))); #if QT_VERSION >= QT_VERSION_CHECK (5,0,0) connect (_watcher.get(), SIGNAL(objectNameChanged(QString)), SLOT(contentsChanged(QString))); #endif // Finding hash of an item corresponding to path for (const CFileSystemObject& item: _list) { const QString itemPath = toPosixSeparators(item.absoluteFilePath()); if (posixPath == itemPath && toPosixSeparators(item.parentDirPath()) != itemPath) { setCurrentItemInFolder(item.parentDirPath(), item.properties().hash); break; } } refreshFileList(); return rcOk; } // Navigates up the directory tree void CPanel::navigateUp() { QDir tmpDir (_currentDir); if (tmpDir.cdUp()) setPath(tmpDir.absolutePath()); else sendContentsChangedNotification(); } // Go to the previous location from history bool CPanel::navigateBack() { if (_currentHistoryLocation > 0 && _currentHistoryLocation < _history.size()) return setPath(_history[--_currentHistoryLocation]) == rcOk; return false; } // Go to the next location from history, if any bool CPanel::navigateForward() { if (_currentHistoryLocation != noHistory && _currentHistoryLocation < _history.size() - 1) return setPath(_history[++_currentHistoryLocation]) == rcOk; return false; } // Info on the dir this panel is currently set to QString CPanel::currentDirPath() const { return toNativeSeparators(_currentDir.absolutePath()); } QString CPanel::currentDirName() const { return toNativeSeparators(_currentDir.dirName()); } void CPanel::setCurrentItemInFolder(const QString& dir, qulonglong currentItemHash) { _cursorPosForFolder[toPosixSeparators(dir)] = currentItemHash; } qulonglong CPanel::currentItemInFolder(const QString &dir) const { const auto it = _cursorPosForFolder.find(toPosixSeparators(dir)); if (it == _cursorPosForFolder.end()) return 0; else return it->second; } // Enumerates objects in the current directory void CPanel::refreshFileList() { time_t start = clock(); QFileInfoList list = _currentDir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDot | QDir::Hidden | QDir::System); _list.clear(); _indexByHash.clear(); const bool showHiddenFiles = CSettings().value(KEY_INTERFACE_SHOW_HIDDEN_FILES, true).toBool(); for (int i = 0; i < list.size(); ++i) { if (list[i].absoluteFilePath() != "/..") { _list.push_back(CFileSystemObject(list[i])); if (!_list.back().exists() || (!showHiddenFiles && _list.back().isHidden())) _list.pop_back(); else _indexByHash[_list.back().hash()] = _list.size() - 1; } } qDebug () << __FUNCTION__ << "Directory:" << _currentDir.absolutePath() << "," << _list.size() << "items," << (clock() - start) * 1000 / CLOCKS_PER_SEC << "ms"; sendContentsChangedNotification(); } // Returns the current list of objects on this panel const std::vector<CFileSystemObject> &CPanel::list() const { return _list; } // Access to the corresponding item const CFileSystemObject &CPanel::itemByIndex(size_t index) const { if (index < _list.size()) { return _list[index]; } else { assert (false); static CFileSystemObject dummyObject((QFileInfo())); return dummyObject; } } CFileSystemObject &CPanel::itemByIndex(size_t index) { if (index < _list.size()) return _list[index]; else { assert (false); static CFileSystemObject dummyObject ((QFileInfo())); return dummyObject; } } const CFileSystemObject& CPanel::itemByHash( qulonglong hash ) const { assert(_indexByHash.count(hash) > 0); return itemByIndex(_indexByHash.at(hash)); } CFileSystemObject& CPanel::itemByHash( qulonglong hash ) { assert(_indexByHash.count(hash) > 0); return itemByIndex(_indexByHash[hash]); } // Calculates directory size, stores it in the corresponding CFileSystemObject and sends data change notification void CPanel::calculateDirSize(qulonglong dirHash) { assert(dirHash != 0); CFileSystemObject& item = itemByHash(dirHash); if (item.isDir()) { uint64_t size = 0; std::vector <CFileSystemObject> objects = recurseDirectoryItems(item.absoluteFilePath(), false); for (auto& dirItem: objects) size += dirItem.size(); item.setDirSize(size); sendContentsChangedNotification(); } } void CPanel::sendContentsChangedNotification() const { for (auto listener: _panelContentsChangedListeners) listener->panelContentsChanged(_panelPosition); } // Settings have changed void CPanel::settingsChanged() { } void CPanel::contentsChanged(QString /*path*/) { refreshFileList(); } void CPanel::addPanelContentsChangedListener(PanelContentsChangedListener *listener) { assert(std::find(_panelContentsChangedListeners.begin(), _panelContentsChangedListeners.end(), listener) == _panelContentsChangedListeners.end()); // Why would we want to set the same listener twice? That'd probably be a mistake. _panelContentsChangedListeners.push_back(listener); sendContentsChangedNotification(); } <|endoftext|>
<commit_before>/****************************************************************************** * 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 "modules/planning/planner/em/em_planner.h" #include <fstream> #include <utility> #include "modules/common/log.h" #include "modules/common/util/string_tokenizer.h" #include "modules/common/util/string_util.h" #include "modules/common/vehicle_state/vehicle_state.h" #include "modules/map/hdmap/hdmap.h" #include "modules/map/hdmap/hdmap_common.h" #include "modules/planning/common/data_center.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/planning_data.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/math/curve1d/quartic_polynomial_curve1d.h" #include "modules/planning/optimizer/dp_poly_path/dp_poly_path_optimizer.h" #include "modules/planning/optimizer/dp_st_speed/dp_st_speed_optimizer.h" #include "modules/planning/optimizer/qp_spline_path/qp_spline_path_optimizer.h" #include "modules/planning/optimizer/qp_spline_st_speed/qp_spline_st_speed_optimizer.h" namespace apollo { namespace planning { using apollo::common::Status; using apollo::common::ErrorCode; using apollo::common::TrajectoryPoint; using apollo::common::vehicle_state::VehicleState; EMPlanner::EMPlanner() {} void EMPlanner::RegisterOptimizers() { optimizer_factory_.Register(DP_POLY_PATH_OPTIMIZER, []() -> Optimizer* { return new DpPolyPathOptimizer("DpPolyPathOptimizer"); }); optimizer_factory_.Register(DP_ST_SPEED_OPTIMIZER, []() -> Optimizer* { return new DpStSpeedOptimizer("DpStSpeedOptimizer"); }); optimizer_factory_.Register(QP_SPLINE_PATH_OPTIMIZER, []() -> Optimizer* { return new QPSplinePathOptimizer("QPSplinePathOptimizer"); }); optimizer_factory_.Register(QP_SPLINE_ST_SPEED_OPTIMIZER, []() -> Optimizer* { return new QpSplineStSpeedOptimizer("QpSplineStSpeedOptimizer"); }); } Status EMPlanner::Init(const PlanningConfig& config) { AINFO << "In EMPlanner::Init()"; RegisterOptimizers(); for (int i = 0; i < config.em_planner_config().optimizer_size(); ++i) { optimizers_.emplace_back(optimizer_factory_.CreateObject( config.em_planner_config().optimizer(i))); optimizers_.back()->Init(); } routing_proxy_.Init(); for (auto& optimizer : optimizers_) { if (!optimizer->Init()) { AERROR << common::util::StrCat("Init optimizer[", optimizer->name(), "] failed."); return Status(ErrorCode::PLANNING_ERROR, "Init optimizer failed."); } } return Status::OK(); } Status EMPlanner::MakePlan( const TrajectoryPoint& start_point, std::vector<TrajectoryPoint>* discretized_trajectory) { DataCenter* data_center = DataCenter::instance(); Frame* frame = data_center->current_frame(); // FIXME(all): switch to real routing when it is ready GenerateReferenceLineFromRouting(routing_proxy_); frame->set_planning_data(new PlanningData()); if (data_center->last_frame()) { ADEBUG << "last frame:" << data_center->last_frame()->DebugString(); } ADEBUG << "start point:" << start_point.DebugString(); auto planning_data = frame->mutable_planning_data(); planning_data->set_init_planning_point(start_point); if (reference_line_) { ADEBUG << "reference line:" << reference_line_->DebugString(); } planning_data->set_reference_line(reference_line_); std::shared_ptr<DecisionData> decision_data(new DecisionData()); planning_data->set_decision_data(decision_data); for (auto& optimizer : optimizers_) { optimizer->Optimize(planning_data); ADEBUG << "after optimizer " << optimizer->name() << ":" << planning_data->DebugString(); } PublishableTrajectory computed_trajectory; if (!planning_data->aggregate(FLAGS_output_trajectory_time_resolution, &computed_trajectory)) { std::string msg("Fail to aggregate planning trajectory."); AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } frame->set_computed_trajectory(computed_trajectory); *discretized_trajectory = computed_trajectory.trajectory_points(); return Status::OK(); } std::vector<SpeedPoint> EMPlanner::GenerateInitSpeedProfile( const double init_v, const double init_a) { // TODO(@lianglia-apollo): this is a dummy simple hot start, need refine later std::array<double, 3> start_state; // distance 0.0 start_state[0] = 0.0; // start velocity start_state[1] = init_v; // start acceleration start_state[2] = init_a; std::array<double, 2> end_state; // end state velocity end_state[0] = 10.0; // end state acceleration end_state[1] = 0.0; // pre assume the curve time is 8 second, can be change later QuarticPolynomialCurve1d speed_curve(start_state, end_state, FLAGS_trajectory_time_length); // assume the time resolution is 0.1 std::uint32_t num_time_steps = static_cast<std::uint32_t>(FLAGS_trajectory_time_length / FLAGS_trajectory_time_resolution) + 1; std::vector<SpeedPoint> speed_profile; speed_profile.reserve(num_time_steps); for (std::uint32_t i = 0; i < num_time_steps; ++i) { double t = i * FLAGS_trajectory_time_resolution; double s = speed_curve.evaluate(0, t); double v = speed_curve.evaluate(1, t); double a = speed_curve.evaluate(2, t); double da = speed_curve.evaluate(3, t); SpeedPoint speed_point; speed_point.set_s(s); speed_point.set_t(t); speed_point.set_v(v); speed_point.set_a(a); speed_point.set_da(da); speed_profile.push_back(speed_point); } return std::move(speed_profile); } Status EMPlanner::GenerateReferenceLineFromRouting( const RoutingProxy& routing_proxy) { DataCenter* data_center = DataCenter::instance(); const auto& routing_result = routing_proxy.routing(); const auto& map = data_center->map(); std::vector<ReferencePoint> ref_points; common::math::Vec2d vehicle_position; hdmap::LaneInfoConstPtr lane_info_ptr = nullptr; ReferenceLineSmoother smoother; smoother.SetConfig(smoother_config_); // use the default value in config. vehicle_position.set_x(common::vehicle_state::VehicleState::instance()->x()); vehicle_position.set_y(common::vehicle_state::VehicleState::instance()->y()); for (const auto& lane : routing_result.route()) { hdmap::Id lane_id; lane_id.set_id(lane.id()); ADEBUG << "Added lane from routing:" << lane.id(); lane_info_ptr = map.get_lane_by_id(lane_id); if (!lane_info_ptr) { std::string msg("failed to find lane " + lane.id() + " from map "); AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } const auto& points = lane_info_ptr->points(); const auto& headings = lane_info_ptr->headings(); for (size_t i = 0; i < points.size(); ++i) { ref_points.emplace_back(points[i], headings[i], 0.0, 0.0, -2.0, 2.0); } } if (ref_points.empty()) { std::string msg("Found no reference points from map"); AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } std::unique_ptr<ReferenceLine> reference_line(new ReferenceLine(ref_points)); std::vector<ReferencePoint> smoothed_ref_points; if (!smoother.smooth(*reference_line, vehicle_position, &smoothed_ref_points)) { std::string msg("Fail to smooth a reference line from map"); AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } ADEBUG << "smooth reference points num:" << smoothed_ref_points.size(); reference_line_.reset(new ReferenceLine(smoothed_ref_points)); return Status::OK(); } } // namespace planning } // namespace apollo <commit_msg>remove the extra optimizer Init().<commit_after>/****************************************************************************** * 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 "modules/planning/planner/em/em_planner.h" #include <fstream> #include <utility> #include "modules/common/log.h" #include "modules/common/util/string_tokenizer.h" #include "modules/common/util/string_util.h" #include "modules/common/vehicle_state/vehicle_state.h" #include "modules/map/hdmap/hdmap.h" #include "modules/map/hdmap/hdmap_common.h" #include "modules/planning/common/data_center.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/planning_data.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/math/curve1d/quartic_polynomial_curve1d.h" #include "modules/planning/optimizer/dp_poly_path/dp_poly_path_optimizer.h" #include "modules/planning/optimizer/dp_st_speed/dp_st_speed_optimizer.h" #include "modules/planning/optimizer/qp_spline_path/qp_spline_path_optimizer.h" #include "modules/planning/optimizer/qp_spline_st_speed/qp_spline_st_speed_optimizer.h" namespace apollo { namespace planning { using apollo::common::Status; using apollo::common::ErrorCode; using apollo::common::TrajectoryPoint; using apollo::common::vehicle_state::VehicleState; EMPlanner::EMPlanner() {} void EMPlanner::RegisterOptimizers() { optimizer_factory_.Register(DP_POLY_PATH_OPTIMIZER, []() -> Optimizer* { return new DpPolyPathOptimizer("DpPolyPathOptimizer"); }); optimizer_factory_.Register(DP_ST_SPEED_OPTIMIZER, []() -> Optimizer* { return new DpStSpeedOptimizer("DpStSpeedOptimizer"); }); optimizer_factory_.Register(QP_SPLINE_PATH_OPTIMIZER, []() -> Optimizer* { return new QPSplinePathOptimizer("QPSplinePathOptimizer"); }); optimizer_factory_.Register(QP_SPLINE_ST_SPEED_OPTIMIZER, []() -> Optimizer* { return new QpSplineStSpeedOptimizer("QpSplineStSpeedOptimizer"); }); } Status EMPlanner::Init(const PlanningConfig& config) { AINFO << "In EMPlanner::Init()"; RegisterOptimizers(); for (int i = 0; i < config.em_planner_config().optimizer_size(); ++i) { optimizers_.emplace_back(optimizer_factory_.CreateObject( config.em_planner_config().optimizer(i))); } routing_proxy_.Init(); for (auto& optimizer : optimizers_) { if (!optimizer->Init()) { std::string msg(common::util::StrCat("Init optimizer[", optimizer->name(), "] failed.")); AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } } return Status::OK(); } Status EMPlanner::MakePlan( const TrajectoryPoint& start_point, std::vector<TrajectoryPoint>* discretized_trajectory) { DataCenter* data_center = DataCenter::instance(); Frame* frame = data_center->current_frame(); // FIXME(all): switch to real routing when it is ready GenerateReferenceLineFromRouting(routing_proxy_); frame->set_planning_data(new PlanningData()); if (data_center->last_frame()) { ADEBUG << "last frame:" << data_center->last_frame()->DebugString(); } ADEBUG << "start point:" << start_point.DebugString(); auto planning_data = frame->mutable_planning_data(); planning_data->set_init_planning_point(start_point); if (reference_line_) { ADEBUG << "reference line:" << reference_line_->DebugString(); } planning_data->set_reference_line(reference_line_); std::shared_ptr<DecisionData> decision_data(new DecisionData()); planning_data->set_decision_data(decision_data); for (auto& optimizer : optimizers_) { optimizer->Optimize(planning_data); ADEBUG << "after optimizer " << optimizer->name() << ":" << planning_data->DebugString(); } PublishableTrajectory computed_trajectory; if (!planning_data->aggregate(FLAGS_output_trajectory_time_resolution, &computed_trajectory)) { std::string msg("Fail to aggregate planning trajectory."); AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } frame->set_computed_trajectory(computed_trajectory); *discretized_trajectory = computed_trajectory.trajectory_points(); return Status::OK(); } std::vector<SpeedPoint> EMPlanner::GenerateInitSpeedProfile( const double init_v, const double init_a) { // TODO(@lianglia-apollo): this is a dummy simple hot start, need refine later std::array<double, 3> start_state; // distance 0.0 start_state[0] = 0.0; // start velocity start_state[1] = init_v; // start acceleration start_state[2] = init_a; std::array<double, 2> end_state; // end state velocity end_state[0] = 10.0; // end state acceleration end_state[1] = 0.0; // pre assume the curve time is 8 second, can be change later QuarticPolynomialCurve1d speed_curve(start_state, end_state, FLAGS_trajectory_time_length); // assume the time resolution is 0.1 std::uint32_t num_time_steps = static_cast<std::uint32_t>(FLAGS_trajectory_time_length / FLAGS_trajectory_time_resolution) + 1; std::vector<SpeedPoint> speed_profile; speed_profile.reserve(num_time_steps); for (std::uint32_t i = 0; i < num_time_steps; ++i) { double t = i * FLAGS_trajectory_time_resolution; double s = speed_curve.evaluate(0, t); double v = speed_curve.evaluate(1, t); double a = speed_curve.evaluate(2, t); double da = speed_curve.evaluate(3, t); SpeedPoint speed_point; speed_point.set_s(s); speed_point.set_t(t); speed_point.set_v(v); speed_point.set_a(a); speed_point.set_da(da); speed_profile.push_back(speed_point); } return std::move(speed_profile); } Status EMPlanner::GenerateReferenceLineFromRouting( const RoutingProxy& routing_proxy) { DataCenter* data_center = DataCenter::instance(); const auto& routing_result = routing_proxy.routing(); const auto& map = data_center->map(); std::vector<ReferencePoint> ref_points; common::math::Vec2d vehicle_position; hdmap::LaneInfoConstPtr lane_info_ptr = nullptr; ReferenceLineSmoother smoother; smoother.SetConfig(smoother_config_); // use the default value in config. vehicle_position.set_x(common::vehicle_state::VehicleState::instance()->x()); vehicle_position.set_y(common::vehicle_state::VehicleState::instance()->y()); for (const auto& lane : routing_result.route()) { hdmap::Id lane_id; lane_id.set_id(lane.id()); ADEBUG << "Added lane from routing:" << lane.id(); lane_info_ptr = map.get_lane_by_id(lane_id); if (!lane_info_ptr) { std::string msg("failed to find lane " + lane.id() + " from map "); AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } const auto& points = lane_info_ptr->points(); const auto& headings = lane_info_ptr->headings(); for (size_t i = 0; i < points.size(); ++i) { ref_points.emplace_back(points[i], headings[i], 0.0, 0.0, -2.0, 2.0); } } if (ref_points.empty()) { std::string msg("Found no reference points from map"); AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } std::unique_ptr<ReferenceLine> reference_line(new ReferenceLine(ref_points)); std::vector<ReferencePoint> smoothed_ref_points; if (!smoother.smooth(*reference_line, vehicle_position, &smoothed_ref_points)) { std::string msg("Fail to smooth a reference line from map"); AERROR << msg; return Status(ErrorCode::PLANNING_ERROR, msg); } ADEBUG << "smooth reference points num:" << smoothed_ref_points.size(); reference_line_.reset(new ReferenceLine(smoothed_ref_points)); return Status::OK(); } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>#include "FlowJunction.h" #include "Factory.h" #include "Conversion.h" #include "Simulation.h" #include "FEProblem.h" #include "GeometricalComponent.h" #include "FluidPropertiesBase.h" #include <sstream> template<> InputParameters validParams<FlowJunction>() { InputParameters params = validParams<Junction>(); params.addParam<std::vector<Real> >("K", "Form loss coefficients"); params.addParam<Real>("scaling_factor", 1., "Scaling factor for the Lagrange multiplier variable"); std::vector<Real> sf4(4, 1.); sf4[0] = 1.e+3; sf4[1] = 1.e+0; sf4[2] = 1.e+6; sf4[3] = 1.; params.addParam<std::vector<Real> >("scaling_factor_bcs", sf4, "Scaling factors for the BCs"); params.addRequiredParam<UserObjectName>("fp", "The name of fluid properties user object to use."); return params; } FlowJunction::FlowJunction(const InputParameters & params) : Junction(params), _lm_name(genName(name(), "lm")), _K(getParam<std::vector<Real> >("K")), _scaling_factor(getParam<Real>("scaling_factor")), _scaling_factor_bcs(getParam<std::vector<Real> >("scaling_factor_bcs")) { } FlowJunction::~FlowJunction() { } void FlowJunction::init() { const FluidPropertiesBase & fp = _sim.getUserObject<FluidPropertiesBase>(getParam<UserObjectName>("fp")); _model_type = fp.modelType(); } void FlowJunction::addVariables() { std::vector<unsigned int> connected_subdomains; this->getConnectedSubdomains(connected_subdomains); // add scalar variable (i.e. Lagrange multiplier) switch (_model_type) { case FlowModel::EQ_MODEL_2: _sim.addVariable(true, _lm_name, FEType(SECOND, SCALAR), connected_subdomains, _scaling_factor); break; case FlowModel::EQ_MODEL_3: _sim.addVariable(true, _lm_name, FEType(THIRD, SCALAR), connected_subdomains, _scaling_factor); break; default: mooseError(name() << ": Not implemented yet."); break; } } void FlowJunction::addMooseObjects() { std::vector<VariableName> cv_area(1, FlowModel::AREA); std::vector<VariableName> cv_u(1, FlowModel::VELOCITY); std::vector<VariableName> cv_pressure(1, FlowModel::PRESSURE); std::vector<VariableName> cv_enthalpy(1, FlowModel::ENTHALPY); std::vector<VariableName> cv_rhoA(1, FlowModel::RHOA); std::vector<VariableName> cv_rhouA(1, FlowModel::RHOUA); std::vector<VariableName> cv_rhoEA(1, FlowModel::RHOEA); std::vector<VariableName> cv_rho(1, FlowModel::RHO); std::vector<VariableName> cv_rhou(1, FlowModel::RHOU); std::vector<VariableName> cv_rhoE(1, FlowModel::RHOE); std::vector<VariableName> cv_lambda(1, _lm_name); MultiMooseEnum execute_options(SetupInterface::getExecuteOptions()); execute_options = "linear"; std::string c_pps = genName(name(), "flow_pps"); { InputParameters params = _factory.getValidParams("PressureCB"); params.set<std::vector<unsigned int> >("r7:boundary") = _bnd_id; params.set<MultiMooseEnum>("execute_on") = execute_options; params.set<std::string>("r7:output") = "none"; // coupling params.set<std::vector<VariableName> >("area") = cv_area; _sim.addPostprocessor("PressureCB", c_pps, params); } // add BC terms for (unsigned int i = 0; i < _bnd_id.size(); ++i) { std::vector<unsigned int> bnd_id(1, _bnd_id[i]); // mass { InputParameters params = _factory.getValidParams("OneDFreeMassBC"); params.set<NonlinearVariableName>("variable") = FlowModel::RHOA; params.set<std::vector<unsigned int> >("r7:boundary") = bnd_id; params.set<UserObjectName>("fp") = getParam<UserObjectName>("fp"); params.set<PostprocessorName>("c") = c_pps; params.set<std::vector<Real> >("scaling_factors") = _scaling_factor_bcs; // coupling params.set<std::vector<VariableName> >("rhoA") = cv_rhoA; params.set<std::vector<VariableName> >("rhouA") = cv_rhouA; params.set<std::vector<VariableName> >("rho") = cv_rho; params.set<std::vector<VariableName> >("rhou") = cv_rhou; params.set<std::vector<VariableName> >("u") = cv_u; params.set<std::vector<VariableName> >("area") = cv_area; params.set<std::vector<VariableName> >("lambda") = cv_lambda; if (_model_type == FlowModel::EQ_MODEL_3) { params.set<std::vector<VariableName> >("rhoE") = cv_rhoE; params.set<std::vector<VariableName> >("enthalpy") = cv_enthalpy; } _sim.addBoundaryCondition("OneDFreeMassBC", genName(name(), _bnd_id[i], "mass_bc"), params); } // momentum { InputParameters params = _factory.getValidParams("OneDFreeMomentumBC"); params.set<NonlinearVariableName>("variable") = FlowModel::RHOUA; params.set<std::vector<unsigned int> >("r7:boundary") = bnd_id; params.set<UserObjectName>("fp") = getParam<UserObjectName>("fp"); params.set<PostprocessorName>("c") = c_pps; params.set<std::vector<Real> >("scaling_factors") = _scaling_factor_bcs; // coupling params.set<std::vector<VariableName> >("rhoA") = cv_rhoA; params.set<std::vector<VariableName> >("rho") = cv_rho; params.set<std::vector<VariableName> >("rhou") = cv_rhou; params.set<std::vector<VariableName> >("u") = cv_u; params.set<std::vector<VariableName> >("pressure") = cv_pressure; params.set<std::vector<VariableName> >("area") = cv_area; params.set<std::vector<VariableName> >("lambda") = cv_lambda; if (_model_type == FlowModel::EQ_MODEL_3) { params.set<std::vector<VariableName> >("rhoEA") = cv_rhoEA; params.set<std::vector<VariableName> >("rhoE") = cv_rhoE; params.set<std::vector<VariableName> >("enthalpy") = cv_enthalpy; } _sim.addBoundaryCondition("OneDFreeMomentumBC", genName(name(), _bnd_id[i], "mom_bc"), params); } // energy if (_model_type == FlowModel::EQ_MODEL_3) { InputParameters params = _factory.getValidParams("OneDFreeEnergyBC"); params.set<NonlinearVariableName>("variable") = FlowModel::RHOEA; params.set<std::vector<unsigned int> >("r7:boundary") = bnd_id; params.set<UserObjectName>("fp") = getParam<UserObjectName>("fp"); // coupling params.set<std::vector<VariableName> >("rhoA") = cv_rhoA; params.set<std::vector<VariableName> >("rhouA") = cv_rhouA; params.set<std::vector<VariableName> >("rho") = cv_rho; params.set<std::vector<VariableName> >("rhou") = cv_rhou; params.set<std::vector<VariableName> >("rhoE") = cv_rhoE; params.set<std::vector<VariableName> >("u") = cv_u; params.set<std::vector<VariableName> >("enthalpy") = cv_enthalpy; params.set<std::vector<VariableName> >("area") = cv_area; params.set<PostprocessorName>("c") = c_pps; params.set<std::vector<Real> >("scaling_factors") = _scaling_factor_bcs; params.set<std::vector<VariableName> >("lambda") = cv_lambda; _sim.addBoundaryCondition("OneDFreeEnergyBC", genName(name(), _bnd_id[i], "erg_bc"), params); } } // add the constraints { InputParameters params = _factory.getValidParams("FlowConstraint"); params.set<NonlinearVariableName>("variable") = _lm_name; params.set<FlowModel::EModelType>("model_type") = _model_type; params.set<std::vector<dof_id_type> >("nodes") = _nodes; params.set<std::vector<Real> >("normals") = _normals; params.set<std::vector<Real> >("K") = _K; params.set<UserObjectName>("fp") = getParam<UserObjectName>("fp"); // coupling params.set<std::vector<VariableName> >("rhoA") = cv_rhoA; params.set<std::vector<VariableName> >("rhouA") = cv_rhouA; params.set<std::vector<VariableName> >("u") = cv_u; params.set<std::vector<VariableName> >("p") = cv_pressure; params.set<std::vector<VariableName> >("rho") = cv_rho; params.set<std::vector<VariableName> >("rhou") = cv_rhou; params.set<std::vector<VariableName> >("area") = cv_area; if (_model_type == FlowModel::EQ_MODEL_3) { params.set<std::vector<VariableName> >("rhoEA") = cv_rhoEA; params.set<std::vector<VariableName> >("rhoE") = cv_rhoE; params.set<std::vector<VariableName> >("enthalpy") = cv_enthalpy; } _sim.addScalarKernel("FlowConstraint", genName(name(), "flow_c0"), params); } } <commit_msg>FlowJunction converted to (u, v) formulation<commit_after>#include "FlowJunction.h" #include "Factory.h" #include "Conversion.h" #include "Simulation.h" #include "FEProblem.h" #include "GeometricalComponent.h" #include "FluidPropertiesBase.h" #include <sstream> template<> InputParameters validParams<FlowJunction>() { InputParameters params = validParams<Junction>(); params.addParam<std::vector<Real> >("K", "Form loss coefficients"); params.addParam<Real>("scaling_factor", 1., "Scaling factor for the Lagrange multiplier variable"); std::vector<Real> sf4(4, 1.); sf4[0] = 1.e+3; sf4[1] = 1.e+0; sf4[2] = 1.e+6; sf4[3] = 1.; params.addParam<std::vector<Real> >("scaling_factor_bcs", sf4, "Scaling factors for the BCs"); params.addRequiredParam<UserObjectName>("fp", "The name of fluid properties user object to use."); return params; } FlowJunction::FlowJunction(const InputParameters & params) : Junction(params), _lm_name(genName(name(), "lm")), _K(getParam<std::vector<Real> >("K")), _scaling_factor(getParam<Real>("scaling_factor")), _scaling_factor_bcs(getParam<std::vector<Real> >("scaling_factor_bcs")) { } FlowJunction::~FlowJunction() { } void FlowJunction::init() { const FluidPropertiesBase & fp = _sim.getUserObject<FluidPropertiesBase>(getParam<UserObjectName>("fp")); _model_type = fp.modelType(); } void FlowJunction::addVariables() { std::vector<unsigned int> connected_subdomains; this->getConnectedSubdomains(connected_subdomains); // add scalar variable (i.e. Lagrange multiplier) switch (_model_type) { case FlowModel::EQ_MODEL_2: _sim.addVariable(true, _lm_name, FEType(SECOND, SCALAR), connected_subdomains, _scaling_factor); break; case FlowModel::EQ_MODEL_3: _sim.addVariable(true, _lm_name, FEType(THIRD, SCALAR), connected_subdomains, _scaling_factor); break; default: mooseError(name() << ": Not implemented yet."); break; } } void FlowJunction::addMooseObjects() { std::vector<VariableName> cv_area(1, FlowModel::AREA); std::vector<VariableName> cv_u(1, FlowModel::VELOCITY); std::vector<VariableName> cv_pressure(1, FlowModel::PRESSURE); std::vector<VariableName> cv_enthalpy(1, FlowModel::ENTHALPY); std::vector<VariableName> cv_rhoA(1, FlowModel::RHOA); std::vector<VariableName> cv_rhouA(1, FlowModel::RHOUA); std::vector<VariableName> cv_rhoEA(1, FlowModel::RHOEA); std::vector<VariableName> cv_v(1, FlowModel::SPECIFIC_VOLUME); std::vector<VariableName> cv_e(1, FlowModel::SPECIFIC_INTERNAL_ENERGY); std::vector<VariableName> cv_lambda(1, _lm_name); MultiMooseEnum execute_options(SetupInterface::getExecuteOptions()); execute_options = "linear"; std::string c_pps = genName(name(), "flow_pps"); { InputParameters params = _factory.getValidParams("PressureCB"); params.set<std::vector<unsigned int> >("r7:boundary") = _bnd_id; params.set<MultiMooseEnum>("execute_on") = execute_options; params.set<std::string>("r7:output") = "none"; // coupling params.set<std::vector<VariableName> >("area") = cv_area; _sim.addPostprocessor("PressureCB", c_pps, params); } // add BC terms for (unsigned int i = 0; i < _bnd_id.size(); ++i) { std::vector<unsigned int> bnd_id(1, _bnd_id[i]); // mass { InputParameters params = _factory.getValidParams("OneDFreeMassBC"); params.set<NonlinearVariableName>("variable") = FlowModel::RHOA; params.set<std::vector<unsigned int> >("r7:boundary") = bnd_id; params.set<PostprocessorName>("c") = c_pps; params.set<std::vector<Real> >("scaling_factors") = _scaling_factor_bcs; // coupling params.set<std::vector<VariableName> >("rhoA") = cv_rhoA; params.set<std::vector<VariableName> >("rhouA") = cv_rhouA; params.set<std::vector<VariableName> >("u") = cv_u; params.set<std::vector<VariableName> >("area") = cv_area; params.set<std::vector<VariableName> >("lambda") = cv_lambda; if (_model_type == FlowModel::EQ_MODEL_3) params.set<std::vector<VariableName> >("enthalpy") = cv_enthalpy; _sim.addBoundaryCondition("OneDFreeMassBC", genName(name(), _bnd_id[i], "mass_bc"), params); } // momentum { InputParameters params = _factory.getValidParams("OneDFreeMomentumBC"); params.set<NonlinearVariableName>("variable") = FlowModel::RHOUA; params.set<std::vector<unsigned int> >("r7:boundary") = bnd_id; params.set<PostprocessorName>("c") = c_pps; params.set<std::vector<Real> >("scaling_factors") = _scaling_factor_bcs; // coupling params.set<std::vector<VariableName> >("rhoA") = cv_rhoA; params.set<std::vector<VariableName> >("u") = cv_u; params.set<std::vector<VariableName> >("pressure") = cv_pressure; params.set<std::vector<VariableName> >("area") = cv_area; params.set<std::vector<VariableName> >("lambda") = cv_lambda; if (_model_type == FlowModel::EQ_MODEL_3) { params.set<std::vector<VariableName> >("rhoEA") = cv_rhoEA; params.set<std::vector<VariableName> >("enthalpy") = cv_enthalpy; } _sim.addBoundaryCondition("OneDFreeMomentumBC", genName(name(), _bnd_id[i], "mom_bc"), params); } // energy if (_model_type == FlowModel::EQ_MODEL_3) { InputParameters params = _factory.getValidParams("OneDFreeEnergyBC"); params.set<NonlinearVariableName>("variable") = FlowModel::RHOEA; params.set<std::vector<unsigned int> >("r7:boundary") = bnd_id; // coupling params.set<std::vector<VariableName> >("rhoA") = cv_rhoA; params.set<std::vector<VariableName> >("rhouA") = cv_rhouA; params.set<std::vector<VariableName> >("u") = cv_u; params.set<std::vector<VariableName> >("enthalpy") = cv_enthalpy; params.set<std::vector<VariableName> >("area") = cv_area; params.set<PostprocessorName>("c") = c_pps; params.set<std::vector<Real> >("scaling_factors") = _scaling_factor_bcs; params.set<std::vector<VariableName> >("lambda") = cv_lambda; _sim.addBoundaryCondition("OneDFreeEnergyBC", genName(name(), _bnd_id[i], "erg_bc"), params); } } // add the constraints { InputParameters params = _factory.getValidParams("FlowConstraint"); params.set<NonlinearVariableName>("variable") = _lm_name; params.set<FlowModel::EModelType>("model_type") = _model_type; params.set<std::vector<dof_id_type> >("nodes") = _nodes; params.set<std::vector<Real> >("normals") = _normals; params.set<std::vector<Real> >("K") = _K; params.set<UserObjectName>("fp") = getParam<UserObjectName>("fp"); // coupling params.set<std::vector<VariableName> >("rhoA") = cv_rhoA; params.set<std::vector<VariableName> >("rhouA") = cv_rhouA; params.set<std::vector<VariableName> >("e") = cv_e; params.set<std::vector<VariableName> >("v") = cv_v; params.set<std::vector<VariableName> >("u") = cv_u; params.set<std::vector<VariableName> >("p") = cv_pressure; params.set<std::vector<VariableName> >("area") = cv_area; if (_model_type == FlowModel::EQ_MODEL_3) { params.set<std::vector<VariableName> >("rhoEA") = cv_rhoEA; params.set<std::vector<VariableName> >("enthalpy") = cv_enthalpy; } _sim.addScalarKernel("FlowConstraint", genName(name(), "flow_c0"), params); } } <|endoftext|>
<commit_before>#define BOOST_TEST_MODULE RandomNumbers #include <boost/test/unit_test.hpp> #include <vexcl/vector.hpp> #include <vexcl/element_index.hpp> #include <vexcl/random.hpp> #include <vexcl/reductor.hpp> #include <boost/math/constants/constants.hpp> #include "context_setup.hpp" BOOST_AUTO_TEST_CASE(random_numbers) { const size_t N = 1 << 20; vex::Reductor<size_t, vex::SUM> sumi(ctx); vex::Reductor<double, vex::SUM> sumd(ctx); vex::Random<cl_int> rand0; vex::vector<cl_uint> x0(ctx, N); x0 = rand0(vex::element_index(), std::rand()); vex::Random<cl_float8> rand1; vex::vector<cl_float8> x1(ctx, N); x1 = rand1(vex::element_index(), std::rand()); vex::Random<cl_double4> rand2; vex::vector<cl_double4> x2(ctx, N); x2 = rand2(vex::element_index(), std::rand()); vex::Random<cl_double> rand3; vex::vector<cl_double> x3(ctx, N); x3 = rand3(vex::element_index(), std::rand()); // X in [0,1] BOOST_CHECK(sumi(x3 > 1) == 0); BOOST_CHECK(sumi(x3 < 0) == 0); // mean = 0.5 BOOST_CHECK(std::abs((sumd(x3) / N) - 0.5) < 1e-2); vex::RandomNormal<cl_double> rand4; vex::vector<cl_double> x4(ctx, N); x4 = rand4(vex::element_index(), std::rand()); // E(X ~ N(0,s)) = 0 BOOST_CHECK(std::abs(sumd(x4)/N) < 1e-2); // E(abs(X) ~ N(0,s)) = sqrt(2/M_PI) * s BOOST_CHECK(std::abs(sumd(fabs(x4))/N - std::sqrt(boost::math::constants::two_div_pi<double>())) < 1e-2); vex::Random<cl_double, vex::random::threefry> rand5; vex::vector<cl_double> x5(ctx, N); x5 = rand5(vex::element_index(), std::rand()); BOOST_CHECK(std::abs(sumd(x5)/N - 0.5) < 1e-2); vex::Random<cl_double, vex::random::threefry> rand6; vex::vector<cl_double4> x6(ctx, N); x6 = rand6(vex::element_index(), std::rand()); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>boost::math::constants::two_div_pi<>() is unavailable in older boost<commit_after>#define BOOST_TEST_MODULE RandomNumbers #include <boost/test/unit_test.hpp> #include <vexcl/vector.hpp> #include <vexcl/element_index.hpp> #include <vexcl/random.hpp> #include <vexcl/reductor.hpp> #include <boost/math/constants/constants.hpp> #include "context_setup.hpp" BOOST_AUTO_TEST_CASE(random_numbers) { const size_t N = 1 << 20; vex::Reductor<size_t, vex::SUM> sumi(ctx); vex::Reductor<double, vex::SUM> sumd(ctx); vex::Random<cl_int> rand0; vex::vector<cl_uint> x0(ctx, N); x0 = rand0(vex::element_index(), std::rand()); vex::Random<cl_float8> rand1; vex::vector<cl_float8> x1(ctx, N); x1 = rand1(vex::element_index(), std::rand()); vex::Random<cl_double4> rand2; vex::vector<cl_double4> x2(ctx, N); x2 = rand2(vex::element_index(), std::rand()); vex::Random<cl_double> rand3; vex::vector<cl_double> x3(ctx, N); x3 = rand3(vex::element_index(), std::rand()); // X in [0,1] BOOST_CHECK(sumi(x3 > 1) == 0); BOOST_CHECK(sumi(x3 < 0) == 0); // mean = 0.5 BOOST_CHECK(std::abs((sumd(x3) / N) - 0.5) < 1e-2); vex::RandomNormal<cl_double> rand4; vex::vector<cl_double> x4(ctx, N); x4 = rand4(vex::element_index(), std::rand()); // E(X ~ N(0,s)) = 0 BOOST_CHECK(std::abs(sumd(x4)/N) < 1e-2); // E(abs(X) ~ N(0,s)) = sqrt(2/M_PI) * s BOOST_CHECK(std::abs(sumd(fabs(x4))/N - std::sqrt(2 / boost::math::constants::pi<double>())) < 1e-2); vex::Random<cl_double, vex::random::threefry> rand5; vex::vector<cl_double> x5(ctx, N); x5 = rand5(vex::element_index(), std::rand()); BOOST_CHECK(std::abs(sumd(x5)/N - 0.5) < 1e-2); vex::Random<cl_double, vex::random::threefry> rand6; vex::vector<cl_double4> x6(ctx, N); x6 = rand6(vex::element_index(), std::rand()); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkSparseFieldLayerTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "itkSparseFieldLayer.h" #include <iostream> struct node_type { unsigned int value; node_type *Next; node_type *Previous; }; int itkSparseFieldLayerTest(int argc, char **argv) { unsigned int i, j; node_type *store = new node_type[4000]; itk::SparseFieldLayer<node_type>::Pointer layer = itk::SparseFieldLayer<node_type>::New(); for (j = 0 ; j < 2 ; j++) { std::cout << "---------------" << std::endl; for (i = 0; i < 4000; i++) { (store+i)->value = i; } layer->Print(std::cout); std::cout << layer->Size() << std::endl; for (i = 0; i < 4000; i++) { layer->PushFront(store +i); } layer->Print(std::cout); std::cout << layer->Size() << std::endl; itk::SparseFieldLayer<node_type>::ConstIterator cit = layer->Begin(); i = 3999; while (cit != layer->End() ) { if ( (*cit).value != i || cit->value != i) return 1; ++cit; --i; } itk::SparseFieldLayer<node_type>::Iterator it = layer->Begin(); i = 3999; while (it != layer->End()) { if ( (*it).value != i || it->value != i) return 1; (*it).value = 32567; if ( (*it).value != 32567 || it->value != 32567) return 1; ++it; --i; } for (i = 0; i < 5000; i++) { layer->PopFront(); } layer->Print(std::cout); std::cout << layer->Size() << std::endl; for (i = 0; i < 4000; i++) { layer->PushFront(store +i); } for (i = 0; i < 5000; i++) { layer->Unlink(layer->Front()); } layer->Print(std::cout); std::cout << layer->Size() << std::endl; } delete[] store; return EXIT_SUCCESS; } <commit_msg>ENH: Added test for new SplitRegions method<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkSparseFieldLayerTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "itkSparseFieldLayer.h" #include <iostream> struct node_type { unsigned int value; node_type *Next; node_type *Previous; }; int itkSparseFieldLayerTest(int argc, char **argv) { unsigned int i, j; node_type *store = new node_type[4000]; itk::SparseFieldLayer<node_type>::RegionListType rlist; itk::SparseFieldLayer<node_type>::Pointer layer = itk::SparseFieldLayer<node_type>::New(); for (j = 0 ; j < 2 ; j++) { std::cout << "---------------" << std::endl; for (i = 0; i < 4000; i++) { (store+i)->value = i; } layer->Print(std::cout); std::cout << layer->Size() << std::endl; for (i = 0; i < 4000; i++) { layer->PushFront(store +i); } layer->Print(std::cout); std::cout << layer->Size() << std::endl; rlist=layer->SplitRegions(5); for (int k=0;k<5;k++) { itk::SparseFieldLayer<node_type>::ConstIterator ptr=rlist[k].last; std::cout<<"Region begin:"<<(rlist[k].first)->value<<std::endl; } itk::SparseFieldLayer<node_type>::ConstIterator cit = layer->Begin(); i = 3999; while (cit != layer->End() ) { if ( (*cit).value != i || cit->value != i) return 1; ++cit; --i; } itk::SparseFieldLayer<node_type>::Iterator it = layer->Begin(); i = 3999; while (it != layer->End()) { if ( (*it).value != i || it->value != i) return 1; (*it).value = 32567; if ( (*it).value != 32567 || it->value != 32567) return 1; ++it; --i; } for (i = 0; i < 5000; i++) { layer->PopFront(); } layer->Print(std::cout); std::cout << layer->Size() << std::endl; for (i = 0; i < 4000; i++) { layer->PushFront(store +i); } for (i = 0; i < 5000; i++) { layer->Unlink(layer->Front()); } layer->Print(std::cout); std::cout << layer->Size() << std::endl; } delete[] store; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkRelabelLabelMapFilterTest1.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkSimpleFilterWatcher.h" #include "itkLabelObject.h" #include "itkLabelMap.h" #include "itkLabelImageToLabelMapFilter.h" #include "itkRelabelLabelMapFilter.h" #include "itkLabelMapToLabelImageFilter.h" #include "itkTestingMacros.h" int itkRelabelLabelMapFilterTest1(int argc, char * argv[]) { if( argc != 3 ) { std::cerr << "usage: " << argv[0] << " input output" << std::endl; return EXIT_FAILURE; } const int dim = 2; typedef itk::Image< unsigned char, dim > ImageType; typedef itk::LabelObject< unsigned char, dim > LabelObjectType; typedef itk::LabelMap< LabelObjectType > LabelMapType; typedef itk::ImageFileReader< ImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[1] ); typedef itk::LabelImageToLabelMapFilter< ImageType, LabelMapType> I2LType; I2LType::Pointer i2l = I2LType::New(); i2l->SetInput( reader->GetOutput() ); typedef itk::RelabelLabelMapFilter< LabelMapType > ChangeType; ChangeType::Pointer change = ChangeType::New(); change->SetInput( i2l->GetOutput() ); itk::SimpleFilterWatcher watcher6(change, "filter"); typedef itk::LabelMapToLabelImageFilter< LabelMapType, ImageType> L2IType; L2IType::Pointer l2i = L2IType::New(); l2i->SetInput( change->GetOutput() ); typedef itk::ImageFileWriter< ImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetInput( l2i->GetOutput() ); writer->SetFileName( argv[2] ); TRY_EXPECT_NO_EXCEPTION( writer->Update() ); return EXIT_SUCCESS; } <commit_msg>ENH: Enabling compression in the writer.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkRelabelLabelMapFilterTest1.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkSimpleFilterWatcher.h" #include "itkLabelObject.h" #include "itkLabelMap.h" #include "itkLabelImageToLabelMapFilter.h" #include "itkRelabelLabelMapFilter.h" #include "itkLabelMapToLabelImageFilter.h" #include "itkTestingMacros.h" int itkRelabelLabelMapFilterTest1(int argc, char * argv[]) { if( argc != 3 ) { std::cerr << "usage: " << argv[0] << " input output" << std::endl; return EXIT_FAILURE; } const int dim = 2; typedef itk::Image< unsigned char, dim > ImageType; typedef itk::LabelObject< unsigned char, dim > LabelObjectType; typedef itk::LabelMap< LabelObjectType > LabelMapType; typedef itk::ImageFileReader< ImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[1] ); typedef itk::LabelImageToLabelMapFilter< ImageType, LabelMapType> I2LType; I2LType::Pointer i2l = I2LType::New(); i2l->SetInput( reader->GetOutput() ); typedef itk::RelabelLabelMapFilter< LabelMapType > ChangeType; ChangeType::Pointer change = ChangeType::New(); change->SetInput( i2l->GetOutput() ); itk::SimpleFilterWatcher watcher6(change, "filter"); typedef itk::LabelMapToLabelImageFilter< LabelMapType, ImageType> L2IType; L2IType::Pointer l2i = L2IType::New(); l2i->SetInput( change->GetOutput() ); typedef itk::ImageFileWriter< ImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetInput( l2i->GetOutput() ); writer->SetFileName( argv[2] ); writer->UseCompressionOn(); TRY_EXPECT_NO_EXCEPTION( writer->Update() ); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. 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. namespace iox { namespace cxx { template <class ReturnType, class... ArgTypes> inline function_ref<ReturnType(ArgTypes...)>::function_ref() noexcept : m_pointerToCallable(nullptr) , m_functionPointer(nullptr) { } template <class ReturnType, class... ArgTypes> template <typename CallableType, typename = typename function_ref<ReturnType(ArgTypes...)>::template EnableIfNotFunctionRef<CallableType>> inline function_ref<ReturnType(ArgTypes...)>::function_ref(CallableType&& callable) noexcept : m_pointerToCallable(reinterpret_cast<void*>(std::addressof(callable))) , m_functionPointer([](void* target, ArgTypes... args) -> ReturnType { return (*reinterpret_cast<typename std::add_pointer<CallableType>::type>(target))( std::forward<ArgTypes>(args)...); }) { } template <class ReturnType, class... ArgTypes> inline function_ref<ReturnType(ArgTypes...)>::function_ref(function_ref&& rhs) noexcept { *this = std::move(rhs); } template <class ReturnType, class... ArgTypes> inline function_ref<ReturnType(ArgTypes...)>& function_ref<ReturnType(ArgTypes...)>::operator=(function_ref<ReturnType(ArgTypes...)>&& rhs) noexcept { if (this != &rhs) { m_pointerToCallable = rhs.m_pointerToCallable; m_functionPointer = rhs.m_functionPointer; // Make sure no undefined behavior can happen by marking the rhs as invalid rhs.m_pointerToCallable = nullptr; rhs.m_functionPointer = nullptr; } return *this; }; template <class ReturnType, class... ArgTypes> inline ReturnType function_ref<ReturnType(ArgTypes...)>::operator()(ArgTypes... args) const noexcept { if (!m_pointerToCallable) { // Callable was called without user having assigned one beforehand std::cerr << "Empty function_ref invoked" << std::endl; std::terminate(); } return m_functionPointer(m_pointerToCallable, std::forward<ArgTypes>(args)...); } template <class ReturnType, class... ArgTypes> inline function_ref<ReturnType(ArgTypes...)>::operator bool() const noexcept { return m_pointerToCallable != nullptr; } template <class ReturnType, class... ArgTypes> inline void function_ref<ReturnType(ArgTypes...)>::swap(function_ref<ReturnType(ArgTypes...)>& rhs) noexcept { std::swap(m_pointerToCallable, rhs.m_pointerToCallable); std::swap(m_functionPointer, rhs.m_functionPointer); } template <class ReturnType, class... ArgTypes> inline void swap(function_ref<ReturnType(ArgTypes...)>& lhs, function_ref<ReturnType(ArgTypes...)>& rhs) noexcept { lhs.swap(rhs); } } // namespace cxx } // namespace iox <commit_msg>iox-#132 default parameters in template are forbidden and do not compile on mac os<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. 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. namespace iox { namespace cxx { template <class ReturnType, class... ArgTypes> inline function_ref<ReturnType(ArgTypes...)>::function_ref() noexcept : m_pointerToCallable(nullptr) , m_functionPointer(nullptr) { } template <class ReturnType, class... ArgTypes> template <typename CallableType, typename> inline function_ref<ReturnType(ArgTypes...)>::function_ref(CallableType&& callable) noexcept : m_pointerToCallable(reinterpret_cast<void*>(std::addressof(callable))) , m_functionPointer([](void* target, ArgTypes... args) -> ReturnType { return (*reinterpret_cast<typename std::add_pointer<CallableType>::type>(target))( std::forward<ArgTypes>(args)...); }) { } template <class ReturnType, class... ArgTypes> inline function_ref<ReturnType(ArgTypes...)>::function_ref(function_ref&& rhs) noexcept { *this = std::move(rhs); } template <class ReturnType, class... ArgTypes> inline function_ref<ReturnType(ArgTypes...)>& function_ref<ReturnType(ArgTypes...)>::operator=(function_ref<ReturnType(ArgTypes...)>&& rhs) noexcept { if (this != &rhs) { m_pointerToCallable = rhs.m_pointerToCallable; m_functionPointer = rhs.m_functionPointer; // Make sure no undefined behavior can happen by marking the rhs as invalid rhs.m_pointerToCallable = nullptr; rhs.m_functionPointer = nullptr; } return *this; }; template <class ReturnType, class... ArgTypes> inline ReturnType function_ref<ReturnType(ArgTypes...)>::operator()(ArgTypes... args) const noexcept { if (!m_pointerToCallable) { // Callable was called without user having assigned one beforehand std::cerr << "Empty function_ref invoked" << std::endl; std::terminate(); } return m_functionPointer(m_pointerToCallable, std::forward<ArgTypes>(args)...); } template <class ReturnType, class... ArgTypes> inline function_ref<ReturnType(ArgTypes...)>::operator bool() const noexcept { return m_pointerToCallable != nullptr; } template <class ReturnType, class... ArgTypes> inline void function_ref<ReturnType(ArgTypes...)>::swap(function_ref<ReturnType(ArgTypes...)>& rhs) noexcept { std::swap(m_pointerToCallable, rhs.m_pointerToCallable); std::swap(m_functionPointer, rhs.m_functionPointer); } template <class ReturnType, class... ArgTypes> inline void swap(function_ref<ReturnType(ArgTypes...)>& lhs, function_ref<ReturnType(ArgTypes...)>& rhs) noexcept { lhs.swap(rhs); } } // namespace cxx } // namespace iox <|endoftext|>
<commit_before>#pragma once #include <future> #include <chrono> #include <string> #include <cstdint> #include <mutex> #include <boost/optional.hpp> #include <boost/network.hpp> namespace { // 暫定的に同時接続数制御機構を入れてみる #ifdef WONDERLAND_LOADER_AUTO_LIMITS std::array< std::mutex, WONDERLAND_LOADER_AUTO_LIMITS > mutexes; #else std::array< std::mutex, 6 > mutexes; #endif } namespace wonder_rabbit_project { namespace wonderland { namespace loader { using buffer_t = boost::optional<std::vector<std::uint8_t>>; using future_t = std::future<buffer_t>; // main feature: load data from url with async/future template < class T = void > auto load ( const std::vector<std::string>& urls , const bool auto_limit = true , const std::int_fast8_t auto_retry = 3 , std::size_t initial_buffer_reserve_size = 1024 ) -> future_t { return std::async ( std::launch::async // TODO: C++14 対応可能次第 move キャプチャー化 , [ urls, auto_limit, auto_retry, initial_buffer_reserve_size ] { // temporary buffer buffer_t buffer; int_fast8_t retry = auto_retry; while( retry-- > 0 ) { std::unique_lock<std::mutex> lock; if ( auto_limit ) do { for ( auto& mutex : mutexes ) { std::unique_lock< std::mutex > lock_( mutex, std::defer_lock ); if ( lock_.try_lock() ) { lock.swap( lock_ ); break; } } if ( lock ) break; std::this_thread::sleep_for( std::chrono::microseconds( 300 ) ); } while ( true ); std::uint16_t last_status = 499u; for ( const std::string& url : urls ) { { //using current_client = boost::network::http::client; //* using current_client = boost::network::http::basic_client < boost::network::http::tags::http_async_8bit_tcp_resolve , 1, 1 >; //*/ current_client::request request( url ); request << boost::network::header( "Connection", "close" ) << boost::network::header( "UserAgent" , "wonderland.loader" ) ; current_client client; const auto response = client.get( request ); last_status = status( response ); if ( last_status != 200u ) continue; const std::string response_body = body( response ); buffer = std::vector<std::uint8_t>( response_body.cbegin(), response_body.cend() ); return buffer; } } // 400系エラーはリトライしても意味が無いのでリトライせず終わる if ( last_status >= 400u and last_status < 500u ) break; std::this_thread::sleep_for( std::chrono::milliseconds( 300 ) ); } return buffer; } ); } } } } <commit_msg>MSVC++対策<commit_after>/// @file native.hxx #pragma once #include <future> #include <chrono> #include <string> #include <cstdint> #include <mutex> #include <boost/optional.hpp> #ifdef _WIN32 # ifndef far # define far # endif # ifndef near # define near # endif #endif #include <boost/network.hpp> #ifdef _WIN32 # ifdef far # undef far # endif # ifdef near # undef near # endif #endif namespace { // 暫定的に同時接続数制御機構を入れてみる //#ifdef WONDERLAND_LOADER_AUTO_LIMITS // std::array< std::mutex, WONDERLAND_LOADER_AUTO_LIMITS > mutexes; //#else std::array< std::mutex, 6 > mutexes; //#endif } namespace wonder_rabbit_project { namespace wonderland { namespace loader { using buffer_t = boost::optional<std::vector<std::uint8_t>>; using future_t = std::future<buffer_t>; // main feature: load data from url with async/future template < class T = void > auto load ( const std::vector<std::string>& urls , const bool auto_limit = true , const std::int_fast8_t auto_retry = 3 , std::size_t initial_buffer_reserve_size = 1024 ) -> future_t { return std::async ( std::launch::async // TODO: C++14 対応可能次第 move キャプチャー化 , [ urls, auto_limit, auto_retry, initial_buffer_reserve_size ] { // temporary buffer #ifndef _MSC_VER buffer_t buffer; #else // MSVC++2015 にしても未だラムダ式で有効であるはずの using/typedef のスコープが無視されたままの対応 boost::optional<std::vector<std::uint8_t>> buffer; #endif int_fast8_t retry = auto_retry; while( retry-- > 0 ) { std::unique_lock<std::mutex> lock; if ( auto_limit ) do { for ( auto& mutex : mutexes ) { std::unique_lock< std::mutex > lock_( mutex, std::defer_lock ); if ( lock_.try_lock() ) { lock.swap( lock_ ); break; } } if ( lock ) break; std::this_thread::sleep_for( std::chrono::microseconds( 300 ) ); } while ( true ); std::uint16_t last_status = 499u; for ( const std::string& url : urls ) { { //using current_client = boost::network::http::client; //* using current_client = boost::network::http::basic_client < boost::network::http::tags::http_async_8bit_tcp_resolve , 1, 1 >; //*/ current_client::request request( url ); request << boost::network::header( "Connection", "close" ) << boost::network::header( "UserAgent" , "wonderland.loader" ) ; current_client client; const auto response = client.get( request ); last_status = status( response ); if ( last_status != 200u ) continue; const std::string response_body = body( response ); buffer = std::vector<std::uint8_t>( response_body.cbegin(), response_body.cend() ); return buffer; } } // 400系エラーはリトライしても意味が無いのでリトライせず終わる if ( last_status >= 400u and last_status < 500u ) break; std::this_thread::sleep_for( std::chrono::milliseconds( 300 ) ); } return buffer; } ); } } } } <|endoftext|>
<commit_before>/* * File: utility.hpp * Author: manu343726 * * Created on 30 de mayo de 2014, 16:41 */ #ifndef UTILITY_HPP #define UTILITY_HPP #include "basic_types.hpp" #include "function.hpp" #include <cstdint> /* * The namespace tml::util contains a set sparse metaprogramming utilities. */ namespace tml { namespace util { namespace func { template<typename... Ts> struct pack_length : public tml::function<tml::size_t<sizeof...(Ts)>> {}; template<typename T> struct sizeof_bits : public tml::function<tml::size_t<sizeof(T) * CHAR_BITS>> {}; } /* * Computes the length of a variadic pack */ template<typename... ARGS> using pack_length = typename tml::util::func::pack_length<ARGS...>::result; /* * Computes the size in bits of a certain type T */ template<typename T> using sizeof_bits = typename tml::util::func::sizeof_bits<T>::result; } } #endif /* UTILITY_HPP */ <commit_msg>tml::util::size_of<commit_after>/* * File: utility.hpp * Author: manu343726 * * Created on 30 de mayo de 2014, 16:41 */ #ifndef UTILITY_HPP #define UTILITY_HPP #include "basic_types.hpp" #include "function.hpp" #include <cstdint> /* * The namespace tml::util contains a set sparse metaprogramming utilities. */ namespace tml { namespace util { namespace func { template<typename... Ts> struct pack_length : public tml::function<tml::size_t<sizeof...(Ts)>> {}; template<typename T> struct sizeof_bits : public tml::function<tml::size_t<sizeof(T) * CHAR_BITS>> {}; template<typename T> struct size_of : public tml::function<tml::size_t<sizeof(T)>> {}; } /* * Computes the length of a variadic pack */ template<typename... ARGS> using pack_length = typename tml::util::func::pack_length<ARGS...>::result; /* * Computes the size in bits of a certain type T */ template<typename T> using sizeof_bits = typename tml::util::func::sizeof_bits<T>::result; /* * Computes the size in bytes of a certain type T */ template<typename T> using size_of = typename tml::util::func::size_of<T>::result; } } #endif /* UTILITY_HPP */ <|endoftext|>
<commit_before>// Copyright (c) 2011 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 "content/gpu/gpu_info_collector.h" #include <string> #include <vector> #include "base/memory/scoped_ptr.h" #include "base/logging.h" #include "base/string_number_conversions.h" #include "base/string_piece.h" #include "base/string_split.h" #include "ui/gfx/gl/gl_bindings.h" #include "ui/gfx/gl/gl_context.h" #include "ui/gfx/gl/gl_surface.h" namespace { scoped_refptr<gfx::GLSurface> InitializeGLSurface() { scoped_refptr<gfx::GLSurface> surface( gfx::GLSurface::CreateOffscreenGLSurface(false, gfx::Size(1, 1))); if (!surface.get()) { LOG(ERROR) << "gfx::GLContext::CreateOffscreenGLSurface failed"; return NULL; } return surface; } scoped_refptr<gfx::GLContext> InitializeGLContext(gfx::GLSurface* surface) { scoped_refptr<gfx::GLContext> context( gfx::GLContext::CreateGLContext(NULL, surface, gfx::PreferIntegratedGpu)); if (!context.get()) { LOG(ERROR) << "gfx::GLContext::CreateGLContext failed"; return NULL; } if (!context->MakeCurrent(surface)) { LOG(ERROR) << "gfx::GLContext::MakeCurrent() failed"; return NULL; } return context; } std::string GetGLString(unsigned int pname) { const char* gl_string = reinterpret_cast<const char*>(glGetString(pname)); if (gl_string) return std::string(gl_string); return ""; } // Return a version string in the format of "major.minor". std::string GetVersionFromString(const std::string& version_string) { size_t begin = version_string.find_first_of("0123456789"); if (begin != std::string::npos) { size_t end = version_string.find_first_not_of("01234567890.", begin); std::string sub_string; if (end != std::string::npos) sub_string = version_string.substr(begin, end - begin); else sub_string = version_string.substr(begin); std::vector<std::string> pieces; base::SplitString(sub_string, '.', &pieces); if (pieces.size() >= 2) return pieces[0] + "." + pieces[1]; } return ""; } } // namespace anonymous namespace gpu_info_collector { bool CollectGraphicsInfoGL(content::GPUInfo* gpu_info) { if (!gfx::GLSurface::InitializeOneOff()) { LOG(ERROR) << "gfx::GLSurface::InitializeOneOff() failed"; return false; } scoped_refptr<gfx::GLSurface> surface(InitializeGLSurface()); if (!surface.get()) return false; scoped_refptr<gfx::GLContext> context(InitializeGLContext(surface.get())); if (!context.get()) return false; gpu_info->gl_renderer = GetGLString(GL_RENDERER); gpu_info->gl_vendor = GetGLString(GL_VENDOR); gpu_info->gl_version_string =GetGLString(GL_VERSION); gpu_info->gl_extensions =GetGLString(GL_EXTENSIONS); bool validGLVersionInfo = CollectGLVersionInfo(gpu_info); bool validVideoCardInfo = CollectVideoCardInfo(gpu_info); bool validDriverInfo = CollectDriverInfoGL(gpu_info); return (validGLVersionInfo && validVideoCardInfo && validDriverInfo); } bool CollectGLVersionInfo(content::GPUInfo* gpu_info) { std::string gl_version_string = gpu_info->gl_version_string; std::string glsl_version_string = GetGLString(GL_SHADING_LANGUAGE_VERSION); gpu_info->gl_version = GetVersionFromString(gl_version_string); std::string glsl_version = GetVersionFromString(glsl_version_string); gpu_info->pixel_shader_version = glsl_version; gpu_info->vertex_shader_version = glsl_version; return true; } } // namespace gpu_info_collector <commit_msg>Blacklisting should use disceret GPU on dual-GPU mac in Lion<commit_after>// Copyright (c) 2011 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 "content/gpu/gpu_info_collector.h" #include <string> #include <vector> #include "base/memory/scoped_ptr.h" #include "base/logging.h" #include "base/string_number_conversions.h" #include "base/string_piece.h" #include "base/string_split.h" #include "ui/gfx/gl/gl_bindings.h" #include "ui/gfx/gl/gl_context.h" #include "ui/gfx/gl/gl_surface.h" namespace { scoped_refptr<gfx::GLSurface> InitializeGLSurface() { scoped_refptr<gfx::GLSurface> surface( gfx::GLSurface::CreateOffscreenGLSurface(false, gfx::Size(1, 1))); if (!surface.get()) { LOG(ERROR) << "gfx::GLContext::CreateOffscreenGLSurface failed"; return NULL; } return surface; } scoped_refptr<gfx::GLContext> InitializeGLContext(gfx::GLSurface* surface) { scoped_refptr<gfx::GLContext> context( gfx::GLContext::CreateGLContext(NULL, surface, gfx::PreferDiscreteGpu)); if (!context.get()) { LOG(ERROR) << "gfx::GLContext::CreateGLContext failed"; return NULL; } if (!context->MakeCurrent(surface)) { LOG(ERROR) << "gfx::GLContext::MakeCurrent() failed"; return NULL; } return context; } std::string GetGLString(unsigned int pname) { const char* gl_string = reinterpret_cast<const char*>(glGetString(pname)); if (gl_string) return std::string(gl_string); return ""; } // Return a version string in the format of "major.minor". std::string GetVersionFromString(const std::string& version_string) { size_t begin = version_string.find_first_of("0123456789"); if (begin != std::string::npos) { size_t end = version_string.find_first_not_of("01234567890.", begin); std::string sub_string; if (end != std::string::npos) sub_string = version_string.substr(begin, end - begin); else sub_string = version_string.substr(begin); std::vector<std::string> pieces; base::SplitString(sub_string, '.', &pieces); if (pieces.size() >= 2) return pieces[0] + "." + pieces[1]; } return ""; } } // namespace anonymous namespace gpu_info_collector { bool CollectGraphicsInfoGL(content::GPUInfo* gpu_info) { if (!gfx::GLSurface::InitializeOneOff()) { LOG(ERROR) << "gfx::GLSurface::InitializeOneOff() failed"; return false; } scoped_refptr<gfx::GLSurface> surface(InitializeGLSurface()); if (!surface.get()) return false; scoped_refptr<gfx::GLContext> context(InitializeGLContext(surface.get())); if (!context.get()) return false; gpu_info->gl_renderer = GetGLString(GL_RENDERER); gpu_info->gl_vendor = GetGLString(GL_VENDOR); gpu_info->gl_version_string =GetGLString(GL_VERSION); gpu_info->gl_extensions =GetGLString(GL_EXTENSIONS); bool validGLVersionInfo = CollectGLVersionInfo(gpu_info); bool validVideoCardInfo = CollectVideoCardInfo(gpu_info); bool validDriverInfo = CollectDriverInfoGL(gpu_info); return (validGLVersionInfo && validVideoCardInfo && validDriverInfo); } bool CollectGLVersionInfo(content::GPUInfo* gpu_info) { std::string gl_version_string = gpu_info->gl_version_string; std::string glsl_version_string = GetGLString(GL_SHADING_LANGUAGE_VERSION); gpu_info->gl_version = GetVersionFromString(gl_version_string); std::string glsl_version = GetVersionFromString(glsl_version_string); gpu_info->pixel_shader_version = glsl_version; gpu_info->vertex_shader_version = glsl_version; return true; } } // namespace gpu_info_collector <|endoftext|>
<commit_before>// Copyright (c) 2006-2009 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 "base/debug_util.h" #include <signal.h> #include "base/basictypes.h" static void ExitSignalHandler(int sig) { exit(128 + sig); } // static void DebugUtil::DisableOSCrashDumps() { // These are the POSIX signals corresponding to the Mach exceptions that // Apple Crash Reporter handles. See ux_exception() in xnu's // bsd/uxkern/ux_exception.c and machine_exception() in xnu's // bsd/dev/*/unix_signal.c. const int signals_to_intercept[] ={ SIGILL, // EXC_BAD_INSTRUCTION SIGTRAP, // EXC_BREAKPOINT SIGFPE, // EXC_ARITHMETIC SIGBUS, // EXC_BAD_ACCESS SIGSEGV // EXC_BAD_ACCESS }; // For all these signals, just wire things up so we exit immediately. for (size_t i = 0; i < arraysize(signals_to_intercept); ++i) { signal(signals_to_intercept[i], ExitSignalHandler); } } <commit_msg>In a signal handler, call _exit, not exit.<commit_after>// Copyright (c) 2006-2009 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 "base/debug_util.h" #include <signal.h> #include "base/basictypes.h" static void ExitSignalHandler(int sig) { // A call to exit() can call atexit() handlers. If we SIGSEGV due // to a corrupt heap, and if we have an atexit handler that // allocates or frees memory, we are in trouble if we do not _exit. _exit(128 + sig); } // static void DebugUtil::DisableOSCrashDumps() { // These are the POSIX signals corresponding to the Mach exceptions that // Apple Crash Reporter handles. See ux_exception() in xnu's // bsd/uxkern/ux_exception.c and machine_exception() in xnu's // bsd/dev/*/unix_signal.c. const int signals_to_intercept[] ={ SIGILL, // EXC_BAD_INSTRUCTION SIGTRAP, // EXC_BREAKPOINT SIGFPE, // EXC_ARITHMETIC SIGBUS, // EXC_BAD_ACCESS SIGSEGV // EXC_BAD_ACCESS }; // For all these signals, just wire things up so we exit immediately. for (size_t i = 0; i < arraysize(signals_to_intercept); ++i) { signal(signals_to_intercept[i], ExitSignalHandler); } } <|endoftext|>
<commit_before>/* * Copyright 2017 Andrei Pangin * Copyright 2017 BellSoft LLC * * 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. * * Author: Dmitry Samersoff */ #if defined(__aarch64__) #include <errno.h> #include "stackFrame.h" #define REG_FP 29 #define REG_LR 30 uintptr_t& StackFrame::pc() { return (uintptr_t&)_ucontext->uc_mcontext.pc; } uintptr_t& StackFrame::sp() { return (uintptr_t&)_ucontext->uc_mcontext.sp; } uintptr_t& StackFrame::fp() { return (uintptr_t&)_ucontext->uc_mcontext.regs[REG_FP]; } uintptr_t StackFrame::retval() { return (uintptr_t)_ucontext->uc_mcontext.regs[0]; } uintptr_t StackFrame::arg0() { return (uintptr_t)_ucontext->uc_mcontext.regs[0]; } uintptr_t StackFrame::arg1() { return (uintptr_t)_ucontext->uc_mcontext.regs[1]; } uintptr_t StackFrame::arg2() { return (uintptr_t)_ucontext->uc_mcontext.regs[2]; } uintptr_t StackFrame::arg3() { return (uintptr_t)_ucontext->uc_mcontext.regs[3]; } void StackFrame::ret() { _ucontext->uc_mcontext.pc = _ucontext->uc_mcontext.regs[REG_LR]; } bool StackFrame::pop(bool trust_frame_pointer) { if (fp() == sp()) { // Expected frame layout: // sp 000000nnnnnnnnnn [stack] // sp+8 000000nnnnnnnnnn [link] fp() = stackAt(0); pc() = stackAt(1); sp() += 16; } else { // Hope LR holds correct value pc() = _ucontext->uc_mcontext.regs[REG_LR]; } return true; } bool StackFrame::checkInterruptedSyscall() { return retval() == (uintptr_t)-EINTR; } int StackFrame::callerLookupSlots() { return 0; } bool StackFrame::isSyscall(instruction_t* pc) { // svc #0 return *pc == 0xd4000001; } #endif // defined(__aarch64__) <commit_msg>Removed stackFrame_aarch64 (to be re-implemented from scratch)<commit_after><|endoftext|>
<commit_before>#include "ococo.h" #include "gtest/gtest.h" #include <vector> using namespace ococo; using namespace std; vector<uint32_t> nucls { nt256_nt16[(int)'A'], nt256_nt16[(int)'C'], nt256_nt16[(int)'G'], nt256_nt16[(int)'T'] }; namespace { class BitFunctionsTest : public ::testing::Test { protected: BitFunctionsTest() { } virtual ~BitFunctionsTest() { } virtual void SetUp() { } virtual void TearDown() { } }; /*class CounterTest : public ::testing::Test { protected: CounterTest() { } virtual ~CounterTest() { } virtual void SetUp() { } virtual void TearDown() { } };*/ class NuclGeneratorTest : public ::testing::Test { protected: NuclGeneratorTest() { } virtual ~NuclGeneratorTest() { } virtual void SetUp() { } virtual void TearDown() { } }; TEST_F(BitFunctionsTest, Basic) { ASSERT_EQ( 0x00, (ococo::right_full_mask<uint8_t,0>()) ); ASSERT_EQ( 0x01, (ococo::right_full_mask<uint8_t,1>()) ); ASSERT_EQ( 0xff, (ococo::right_full_mask<uint8_t,8>()) ); ASSERT_EQ( 0xffff, (ococo::right_full_mask<uint16_t,16>()) ); ASSERT_EQ( 0x00, (ococo::left_full_mask<uint8_t,0>()) ); ASSERT_EQ( 0x80, (ococo::left_full_mask<uint8_t,1>()) ); ASSERT_EQ( 0xff, (ococo::left_full_mask<uint8_t,8>()) ); ASSERT_EQ( 0xffff, (ococo::left_full_mask<uint16_t,16>()) ); ASSERT_EQ( 0x01, (ococo::get_right_bits<uint8_t,1,0>(0xff)) ); ASSERT_EQ( 0x01, (ococo::get_right_bits<uint8_t,1,1>(0xff)) ); ASSERT_EQ( 0x03, (ococo::get_right_bits<uint8_t,2,0>(0xff)) ); ASSERT_EQ( 0xff, (ococo::get_right_bits<uint8_t,8,0>(0xff)) ); ASSERT_EQ( 0x08, (ococo::get_right_bits<uint8_t,4,0>(0xf8)) ); ASSERT_EQ( 0x01, (ococo::get_left_bits<uint8_t,1,0>(0xff)) ); ASSERT_EQ( 0x01, (ococo::get_left_bits<uint8_t,1,1>(0xff)) ); ASSERT_EQ( 0x03, (ococo::get_left_bits<uint8_t,2,0>(0xff)) ); ASSERT_EQ( 0xff, (ococo::get_left_bits<uint8_t,8,0>(0xff)) ); } /*TEST_F(CounterTest, AllIncrements) { counter_t c1; for(uint32_t nucl : nucls) { c1 =0; for(int i=1;i<=cell_maxval;i++){ c1 = _COUNTER_CELL_INC(c1,nucl); ASSERT_EQ( _COUNTER_CELL_VAL(c1,nucl),i ); } } } TEST_F(CounterTest, Normalization_MaxVsMax) { counter_t c1; counter_t c2; for(int nucl : nucls) { // c1 := max possible values, then overflow c1=0; c1 = _COUNTER_CELL_SET(c1,nt256_nt16[(int)'A'],cell_maxval); c1 = _COUNTER_CELL_SET(c1,nt256_nt16[(int)'C'],cell_maxval); c1 = _COUNTER_CELL_SET(c1,nt256_nt16[(int)'G'],cell_maxval); c1 = _COUNTER_CELL_SET(c1,nt256_nt16[(int)'T'],cell_maxval); c1 = _COUNTER_CELL_INC(c1,nucl); // c2 := max values after overflowing, then pivot c2=0; c2 = _COUNTER_CELL_SET(c1,nt256_nt16[(int)'A'],cell_maxval_shifted); c2 = _COUNTER_CELL_SET(c1,nt256_nt16[(int)'C'],cell_maxval_shifted); c2 = _COUNTER_CELL_SET(c1,nt256_nt16[(int)'G'],cell_maxval_shifted); c2 = _COUNTER_CELL_SET(c1,nt256_nt16[(int)'T'],cell_maxval_shifted); c2 = _COUNTER_CELL_SET(c2,nucl,1<<(cell_bits-1)); ASSERT_EQ(c1, c2); } } TEST_F(CounterTest, Normalization_MaxVsOnes) { counter_t c1; counter_t c2; for(int nucl : nucls) { c1=0; // 1 to everything for(int nucl1 : nucls) { c1 = _COUNTER_CELL_INC(c1,nucl1); } // max value c1 = _COUNTER_CELL_SET(c1,nucl,cell_maxval); // overflow c1 = _COUNTER_CELL_INC(c1,nucl); c2 = _COUNTER_CELL_SET(0,nucl,1<<(cell_bits-1)); ASSERT_EQ(c1, c2); } }*/ TEST_F(NuclGeneratorTest, IndividualNucleotides) { char nucl; consensus_params_t params={}; { ococo::pos_stats_uncompr_t psu = {nt256_nt16[(int)'A'],{0,0,0,0},0}; nucl=cons_call_stoch(psu, params); ASSERT_EQ('A',nucl); } { ococo::pos_stats_uncompr_t psu = {nt256_nt16[(int)'N'],{0,0,0,0},0}; nucl=cons_call_stoch(psu, params); ASSERT_EQ('N',nucl); } /*quadruplet={5,0,0,0,5}; nucl=rand_nucl(quadruplet); ASSERT_EQ(nucl, 'A'); quadruplet={0,5,0,0,5}; nucl=rand_nucl(quadruplet); ASSERT_EQ(nucl, 'C'); quadruplet={0,0,5,0,5}; nucl=rand_nucl(quadruplet); ASSERT_EQ(nucl, 'G'); quadruplet={0,0,0,5,5}; nucl=rand_nucl(quadruplet); ASSERT_EQ(nucl, 'T');*/ } } // namespace int main(int argc, char** argv){ cout << endl << "DEBUG INFO" << endl; ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>Test majority strategy in unit tests.<commit_after>#include "ococo.h" #include "gtest/gtest.h" #include <vector> using namespace ococo; using namespace std; vector<uint32_t> nucls { nt256_nt16[(int)'A'], nt256_nt16[(int)'C'], nt256_nt16[(int)'G'], nt256_nt16[(int)'T'] }; namespace { class BitFunctionsTest : public ::testing::Test { protected: BitFunctionsTest() { } virtual ~BitFunctionsTest() { } virtual void SetUp() { } virtual void TearDown() { } }; class ConsensusTest : public ::testing::Test { protected: ConsensusTest() { } virtual ~ConsensusTest() { } virtual void SetUp() { } virtual void TearDown() { } }; TEST_F(BitFunctionsTest, Basic) { ASSERT_EQ( 0x00, (ococo::right_full_mask<uint8_t,0>()) ); ASSERT_EQ( 0x01, (ococo::right_full_mask<uint8_t,1>()) ); ASSERT_EQ( 0xff, (ococo::right_full_mask<uint8_t,8>()) ); ASSERT_EQ( 0xffff, (ococo::right_full_mask<uint16_t,16>()) ); ASSERT_EQ( 0x00, (ococo::left_full_mask<uint8_t,0>()) ); ASSERT_EQ( 0x80, (ococo::left_full_mask<uint8_t,1>()) ); ASSERT_EQ( 0xff, (ococo::left_full_mask<uint8_t,8>()) ); ASSERT_EQ( 0xffff, (ococo::left_full_mask<uint16_t,16>()) ); ASSERT_EQ( 0x01, (ococo::get_right_bits<uint8_t,1,0>(0xff)) ); ASSERT_EQ( 0x01, (ococo::get_right_bits<uint8_t,1,1>(0xff)) ); ASSERT_EQ( 0x03, (ococo::get_right_bits<uint8_t,2,0>(0xff)) ); ASSERT_EQ( 0xff, (ococo::get_right_bits<uint8_t,8,0>(0xff)) ); ASSERT_EQ( 0x08, (ococo::get_right_bits<uint8_t,4,0>(0xf8)) ); ASSERT_EQ( 0x01, (ococo::get_left_bits<uint8_t,1,0>(0xff)) ); ASSERT_EQ( 0x01, (ococo::get_left_bits<uint8_t,1,1>(0xff)) ); ASSERT_EQ( 0x03, (ococo::get_left_bits<uint8_t,2,0>(0xff)) ); ASSERT_EQ( 0xff, (ococo::get_left_bits<uint8_t,8,0>(0xff)) ); } /*TEST_F(CounterTest, AllIncrements) { counter_t c1; for(uint32_t nucl : nucls) { c1 =0; for(int i=1;i<=cell_maxval;i++){ c1 = _COUNTER_CELL_INC(c1,nucl); ASSERT_EQ( _COUNTER_CELL_VAL(c1,nucl),i ); } } } TEST_F(CounterTest, Normalization_MaxVsMax) { counter_t c1; counter_t c2; for(int nucl : nucls) { // c1 := max possible values, then overflow c1=0; c1 = _COUNTER_CELL_SET(c1,nt256_nt16[(int)'A'],cell_maxval); c1 = _COUNTER_CELL_SET(c1,nt256_nt16[(int)'C'],cell_maxval); c1 = _COUNTER_CELL_SET(c1,nt256_nt16[(int)'G'],cell_maxval); c1 = _COUNTER_CELL_SET(c1,nt256_nt16[(int)'T'],cell_maxval); c1 = _COUNTER_CELL_INC(c1,nucl); // c2 := max values after overflowing, then pivot c2=0; c2 = _COUNTER_CELL_SET(c1,nt256_nt16[(int)'A'],cell_maxval_shifted); c2 = _COUNTER_CELL_SET(c1,nt256_nt16[(int)'C'],cell_maxval_shifted); c2 = _COUNTER_CELL_SET(c1,nt256_nt16[(int)'G'],cell_maxval_shifted); c2 = _COUNTER_CELL_SET(c1,nt256_nt16[(int)'T'],cell_maxval_shifted); c2 = _COUNTER_CELL_SET(c2,nucl,1<<(cell_bits-1)); ASSERT_EQ(c1, c2); } } TEST_F(CounterTest, Normalization_MaxVsOnes) { counter_t c1; counter_t c2; for(int nucl : nucls) { c1=0; // 1 to everything for(int nucl1 : nucls) { c1 = _COUNTER_CELL_INC(c1,nucl1); } // max value c1 = _COUNTER_CELL_SET(c1,nucl,cell_maxval); // overflow c1 = _COUNTER_CELL_INC(c1,nucl); c2 = _COUNTER_CELL_SET(0,nucl,1<<(cell_bits-1)); ASSERT_EQ(c1, c2); } }*/ TEST_F(ConsensusTest, EmptyStats) { char nucl; consensus_params_t params=consensus_params_t(); for(uint32_t i=0;i<4;i++){ { ococo::pos_stats_uncompr_t psu = {nt256_nt16[(int)'C'],{0,0,0,0},0}; nucl=(params.cons_alg[i])(psu, params); ASSERT_EQ('C',nucl); } { ococo::pos_stats_uncompr_t psu = {nt256_nt16[(int)'N'],{0,0,0,0},0}; nucl=(params.cons_alg[i])(psu, params); ASSERT_EQ('N',nucl); } } } TEST_F(ConsensusTest, Majority) { char nucl; consensus_params_t params=consensus_params_t(); params.majority_threshold=0.6; { ococo::pos_stats_uncompr_t psu = {nt256_nt16[(int)'T'],{6,0,0,3},9}; nucl=cons_call_maj(psu, params); ASSERT_EQ('A',nucl); } { ococo::pos_stats_uncompr_t psu = {nt256_nt16[(int)'T'],{0,0,6,4},10}; nucl=cons_call_maj(psu, params); ASSERT_EQ('G',nucl); } } } // namespace int main(int argc, char** argv){ cout << endl << "DEBUG INFO" << endl; ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include "benchmark.h" char tuebaCorpus[] = "tuebadz6"; class TuebaFixture : public CorpusFixture<true, tuebaCorpus> { public: virtual ~TuebaFixture() {} }; class TuebaFallbackFixture : public CorpusFixture<false, tuebaCorpus> { public: virtual ~TuebaFallbackFixture() {} }; /* node & merged:pos="PPER" & node & mmax:relation="anaphoric" & node & node & mmax:relation="anaphoric" & #1 >[func="ON"] #3 & #3 >* #2 & #2 _i_ #4 & #5 >[func="ON"] #6 & #6 >* #7 & #4 ->anaphoric #7 */ BASELINE_F(Tueba_Complex1, Fallback, TuebaFallbackFixture, 5, 1) { Query q(getDB()); auto n1 = q.addNode(std::make_shared<AnnotationNameSearch>(getDB(), annis_ns, annis_node_name)); auto n2 = q.addNode(std::make_shared<AnnotationNameSearch>(getDB(), "merged", "pos", "PPER")); auto n3 = q.addNode(std::make_shared<AnnotationNameSearch>(getDB(), annis_ns, annis_node_name)); auto n4 = q.addNode(std::make_shared<AnnotationNameSearch>(getDB(), "mmax", "relation", "anaphoric")); auto n5 = q.addNode(std::make_shared<AnnotationNameSearch>(getDB(), annis_ns, annis_node_name)); auto n6 = q.addNode(std::make_shared<AnnotationNameSearch>(getDB(), annis_ns, annis_node_name)); auto n7 = q.addNode(std::make_shared<AnnotationNameSearch>(getDB(), "mmax", "relation", "anaphoric")); Annotation funcOnAnno = Init::initAnnotation(getDB().strings.add("func"), getDB().strings.add("ON")); q.addOperator(std::make_shared<Inclusion>(getDB()), n2, n4); q.addOperator(std::make_shared<Pointing>(getDB(), "", "anaphoric"), n4, n7); q.addOperator(std::make_shared<Dominance>(getDB(), "", "", funcOnAnno), n1, n3); q.addOperator(std::make_shared<Dominance>(getDB(), "", "", 1, uintmax), n3, n2); q.addOperator(std::make_shared<Dominance>(getDB(), "", "", funcOnAnno), n5, n6); q.addOperator(std::make_shared<Dominance>(getDB(), "", "", 1, uintmax), n6, n7); unsigned int counter=0; while(q.hasNext() && counter < 10u) { q.next(); counter++; } assert(counter == 0u); } /* node & merged:pos="PPER" & node & mmax:relation="anaphoric" & node & node & mmax:relation="anaphoric" & #1 >[func="ON"] #3 & #3 >* #2 & #2 _i_ #4 & #5 >[func="ON"] #6 & #6 >* #7 & #4 ->anaphoric #7 */ BENCHMARK_F(Tueba_Complex1, Optimized, TuebaFixture, 5, 1) { Query q(getDB()); auto n1 = q.addNode(std::make_shared<AnnotationNameSearch>(getDB(), annis_ns, annis_node_name)); auto n2 = q.addNode(std::make_shared<AnnotationNameSearch>(getDB(), "merged", "pos", "PPER")); auto n3 = q.addNode(std::make_shared<AnnotationNameSearch>(getDB(), annis_ns, annis_node_name)); auto n4 = q.addNode(std::make_shared<AnnotationNameSearch>(getDB(), "mmax", "relation", "anaphoric")); auto n5 = q.addNode(std::make_shared<AnnotationNameSearch>(getDB(), annis_ns, annis_node_name)); auto n6 = q.addNode(std::make_shared<AnnotationNameSearch>(getDB(), annis_ns, annis_node_name)); auto n7 = q.addNode(std::make_shared<AnnotationNameSearch>(getDB(), "mmax", "relation", "anaphoric")); Annotation funcOnAnno = Init::initAnnotation(getDB().strings.add("func"), getDB().strings.add("ON")); q.addOperator(std::make_shared<Inclusion>(getDB()), n2, n4); q.addOperator(std::make_shared<Pointing>(getDB(), "", "anaphoric"), n4, n7); q.addOperator(std::make_shared<Dominance>(getDB(), "", "", funcOnAnno), n1, n3); q.addOperator(std::make_shared<Dominance>(getDB(), "", "", 1, uintmax), n3, n2); q.addOperator(std::make_shared<Dominance>(getDB(), "", "", funcOnAnno), n5, n6); q.addOperator(std::make_shared<Dominance>(getDB(), "", "", 1, uintmax), n6, n7); unsigned int counter=0; while(q.hasNext() && counter < 10u) { q.next(); counter++; } assert(counter == 0u); } <commit_msg>de-activate tuebadz benchmark for now<commit_after>#include "benchmark.h" char tuebaCorpus[] = "tuebadz6"; class TuebaFixture : public CorpusFixture<true, tuebaCorpus> { public: virtual ~TuebaFixture() {} }; class TuebaFallbackFixture : public CorpusFixture<false, tuebaCorpus> { public: virtual ~TuebaFallbackFixture() {} }; /* node & merged:pos="PPER" & node & mmax:relation="anaphoric" & node & node & mmax:relation="anaphoric" & #1 >[func="ON"] #3 & #3 >* #2 & #2 _i_ #4 & #5 >[func="ON"] #6 & #6 >* #7 & #4 ->anaphoric #7 */ /* BASELINE_F(Tueba_Complex1, Fallback, TuebaFallbackFixture, 5, 1) { Query q(getDB()); auto n1 = q.addNode(std::make_shared<AnnotationNameSearch>(getDB(), annis_ns, annis_node_name)); auto n2 = q.addNode(std::make_shared<AnnotationNameSearch>(getDB(), "merged", "pos", "PPER")); auto n3 = q.addNode(std::make_shared<AnnotationNameSearch>(getDB(), annis_ns, annis_node_name)); auto n4 = q.addNode(std::make_shared<AnnotationNameSearch>(getDB(), "mmax", "relation", "anaphoric")); auto n5 = q.addNode(std::make_shared<AnnotationNameSearch>(getDB(), annis_ns, annis_node_name)); auto n6 = q.addNode(std::make_shared<AnnotationNameSearch>(getDB(), annis_ns, annis_node_name)); auto n7 = q.addNode(std::make_shared<AnnotationNameSearch>(getDB(), "mmax", "relation", "anaphoric")); Annotation funcOnAnno = Init::initAnnotation(getDB().strings.add("func"), getDB().strings.add("ON")); q.addOperator(std::make_shared<Inclusion>(getDB()), n2, n4); q.addOperator(std::make_shared<Pointing>(getDB(), "", "anaphoric"), n4, n7); q.addOperator(std::make_shared<Dominance>(getDB(), "", "", funcOnAnno), n1, n3); q.addOperator(std::make_shared<Dominance>(getDB(), "", "", 1, uintmax), n3, n2); q.addOperator(std::make_shared<Dominance>(getDB(), "", "", funcOnAnno), n5, n6); q.addOperator(std::make_shared<Dominance>(getDB(), "", "", 1, uintmax), n6, n7); unsigned int counter=0; while(q.hasNext() && counter < 10u) { q.next(); counter++; } assert(counter == 0u); } */ /* node & merged:pos="PPER" & node & mmax:relation="anaphoric" & node & node & mmax:relation="anaphoric" & #1 >[func="ON"] #3 & #3 >* #2 & #2 _i_ #4 & #5 >[func="ON"] #6 & #6 >* #7 & #4 ->anaphoric #7 */ /* BENCHMARK_F(Tueba_Complex1, Optimized, TuebaFixture, 5, 1) { Query q(getDB()); auto n1 = q.addNode(std::make_shared<AnnotationNameSearch>(getDB(), annis_ns, annis_node_name)); auto n2 = q.addNode(std::make_shared<AnnotationNameSearch>(getDB(), "merged", "pos", "PPER")); auto n3 = q.addNode(std::make_shared<AnnotationNameSearch>(getDB(), annis_ns, annis_node_name)); auto n4 = q.addNode(std::make_shared<AnnotationNameSearch>(getDB(), "mmax", "relation", "anaphoric")); auto n5 = q.addNode(std::make_shared<AnnotationNameSearch>(getDB(), annis_ns, annis_node_name)); auto n6 = q.addNode(std::make_shared<AnnotationNameSearch>(getDB(), annis_ns, annis_node_name)); auto n7 = q.addNode(std::make_shared<AnnotationNameSearch>(getDB(), "mmax", "relation", "anaphoric")); Annotation funcOnAnno = Init::initAnnotation(getDB().strings.add("func"), getDB().strings.add("ON")); q.addOperator(std::make_shared<Inclusion>(getDB()), n2, n4); q.addOperator(std::make_shared<Pointing>(getDB(), "", "anaphoric"), n4, n7); q.addOperator(std::make_shared<Dominance>(getDB(), "", "", funcOnAnno), n1, n3); q.addOperator(std::make_shared<Dominance>(getDB(), "", "", 1, uintmax), n3, n2); q.addOperator(std::make_shared<Dominance>(getDB(), "", "", funcOnAnno), n5, n6); q.addOperator(std::make_shared<Dominance>(getDB(), "", "", 1, uintmax), n6, n7); unsigned int counter=0; while(q.hasNext() && counter < 10u) { q.next(); counter++; } assert(counter == 0u); } */ <|endoftext|>
<commit_before>/* Copyright 2002-2013 CEA LIST This file is part of LIMA. LIMA is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. LIMA is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with LIMA. If not, see <http://www.gnu.org/licenses/> */ /*************************************************************************** FsaAccessHeader.cpp - description ------------------- begin : mon nov 7 2005 copyright : (C) 2003-2005 by CEA email : [email protected] ***************************************************************************/ /*************************************************************************** * * * header for files * * compact dictionnary based on finite state automata * * implemented with Boost Graph library * * * ***************************************************************************/ // pour la definitin de one_byte, two_bytes, four_bytes #include "FsaAccessHeader.h" #include "FsaAccessIOStreamWrapper.h" #include "common/Data/LimaString.h" #include <sstream> #include <string.h> namespace Lima { namespace Common { namespace FsaAccess { class FsaAccessHeaderPrivate { friend class FsaAccessHeader; FsaAccessHeaderPrivate(bool trie_direction_fwd); virtual ~FsaAccessHeaderPrivate(); uint16_t m_majorVersion; uint16_t m_minorVersion; uint8_t m_charType; uint8_t m_packing; uint8_t m_charOrder; uint64_t m_nbVertices; uint64_t m_nbEdges; // uint64_t m_maxSimpleId; // uint64_t m_compoundsDataOffset; // uint64_t m_nbCompounds; /** * direction when reading characters of input key in getIndex * the value is set when access Data (list of keys) is compiled * and is stored in header of file * must be const!! * this is not a pamameter of getIndex() function! (depends on compiled data structure) * */ bool m_trie_direction_fwd; // long m_compoundsDataPos; }; FsaAccessHeaderPrivate::FsaAccessHeaderPrivate(bool trie_direction_fwd) : m_majorVersion( MAJOR_VERSION_16 ), m_minorVersion( MINOR_VERSION_16 ), m_packing(BUILDER), m_charOrder(FORWARD), m_nbVertices(0), m_nbEdges(0), // m_maxSimpleId(MAX_SIMPLE_TID), // m_compoundsDataOffset(0) // m_nbCompounds(0), m_trie_direction_fwd( trie_direction_fwd ) { if( sizeof(LimaChar) == 2 ) { m_charType = 2; } else { std::string mess = "FsaAccessBuilder::FsaAccessHeader: sizeof(LimaChar) must be 2!!!" ; #ifdef DEBUG_CD FSAALOGINIT; LERROR << mess.c_str(); #endif throw( FsaNotSaved( mess ) ); } } FsaAccessHeaderPrivate::~FsaAccessHeaderPrivate() { } FsaAccessHeader::FsaAccessHeader(bool trie_direction_fwd) : m_d(new FsaAccessHeaderPrivate(trie_direction_fwd)) { } FsaAccessHeader::FsaAccessHeader(const FsaAccessHeader& h) : m_d(new FsaAccessHeaderPrivate(*h.m_d)) { } FsaAccessHeader::~FsaAccessHeader() { delete m_d; } FsaAccessHeader& FsaAccessHeader::operator=(const FsaAccessHeader& h) {*m_d = *(h.m_d); return *this;} bool FsaAccessHeader::getTrieDirectionForward() const { return m_d->m_trie_direction_fwd; } uint64_t FsaAccessHeader::getNbVertices() const { return m_d->m_nbVertices; } uint64_t FsaAccessHeader::getNbEdges() const { return m_d->m_nbEdges; } void FsaAccessHeader::setPackingStatus(uint8_t packingStatus) { m_d->m_packing = packingStatus; } void FsaAccessHeader::setNbVertices(uint64_t nbVerts) { m_d->m_nbVertices = nbVerts; } void FsaAccessHeader::setNbEdges(uint64_t nbEdges) { m_d->m_nbEdges = nbEdges; } // uint64_t getMaxSimpleId() const { return m_maxSimpleId; } // uint64_t int getCompoundsDataOffset() const { return m_compoundsDataOffset; } // uint64_t getNbCompounds() const { return m_nbCompounds; } // void setStreamPos(std::ifstream& is); // const long& getStreamPos() { return m_compoundsDataPos; } void FsaAccessHeader::read( AbstractFsaAccessIStreamWrapper& iw ) { #ifdef DEBUG_CD FSAAIOLOGINIT; LDEBUG << "FsaAccessHeader::read()"; #endif char headBuf[HEADER_SIZE+1]; iw.readData( headBuf, HEADER_SIZE ); char *dstptr = headBuf; char magicNumber[13]; strncpy(magicNumber, dstptr, 12 ); dstptr += 12; magicNumber[sizeof(magicNumber)-1] = ''; if( strcmp(magicNumber,MAGIC_NUMBER) ) { std::string mess = "FsaAccessHeader::read: bad magic number '" + std::string(magicNumber) + "'" ; #ifdef DEBUG_CD LERROR << mess.c_str(); #endif throw( AccessByStringNotInitialized(mess) ); } char numBuf[6]; strncpy(numBuf, dstptr, 5 ); dstptr += 5; numBuf[sizeof(numBuf)-1] = ''; sscanf(numBuf, "%hu.%hu", &m_d->m_majorVersion, &m_d->m_minorVersion); #ifdef DEBUG_CD LDEBUG << "FsaAccessHeader::read: m_majorVersion = " << m_d->m_majorVersion << " m_minorVersion = " << m_d->m_minorVersion ; #endif uint16_t majorVersion = MAJOR_VERSION_16; // uint16_t minorVersion = MINOR_VERSION_16; if( m_d->m_majorVersion > majorVersion) { /* if( (m_majorVersion > majorVersion) ||((m_majorVersion == majorVersion) && (m_minorVersion > minorVersion) ) ) { */ std::string mess = "FsaAccessHeader::read: bad version = " + std::string(numBuf) + ". Get a release of your library or convert your file !!" ; #ifdef DEBUG_CD LERROR << mess.c_str(); #endif throw( AccessByStringNotInitialized(mess ) ); } uint8_t cVal= *dstptr++; m_d->m_charType = cVal; if( (m_d->m_charType != 1) && (m_d->m_charType != 2) && (m_d->m_charType != 4) ) { std::string mess = "FsaAccessHeader::read: byte_per_char must be 1, 2 or 4!!!" ; #ifdef DEBUG_CD LERROR << mess.c_str(); #endif throw( AccessByStringNotInitialized(mess) ); } #ifdef DEBUG_CD LDEBUG << "FsaAccessHeader::read: m_charType = " << (int)cVal; #endif cVal= *dstptr++; m_d->m_packing = cVal; if( (m_d->m_packing != BUILDER) && (m_d->m_packing != BUILT) && (m_d->m_packing != SPARE)) { std::string mess = "FsaAccessHeader::read: m_packing type is not recognized!!!" ; #ifdef DEBUG_CD LERROR << mess.c_str(); #endif throw( AccessByStringNotInitialized(mess) ); } #ifdef DEBUG_CD LDEBUG << "FsaAccessHeader::read: m_packing = " << (m_d->m_packing == BUILDER ? "BUILDER" : (m_d->m_packing == BUILT ? "BUILT" : "SPARE" )); #endif cVal= *dstptr++; #ifdef DEBUG_CD LDEBUG << "FsaAccessHeader::read: m_charOrder = " << (int)cVal; #endif m_d->m_charOrder = cVal; if( (m_d->m_charOrder != FORWARD) &&(m_d->m_charOrder != REVERSE) ) { std::string mess = "FsaAccessHeader::read: character order is not recognized!!!" ; #ifdef DEBUG_CD LERROR << mess.c_str(); #endif throw( AccessByStringNotInitialized(mess) ); } m_d->m_trie_direction_fwd = (m_d->m_charOrder == FORWARD); #ifdef DEBUG_CD LDEBUG << "FsaAccessHeader::read: m_charOrder = " << (m_d->m_charOrder == FORWARD ? "FORWARD" : "REVERSE" ); #ifdef DEBUG_CD LDEBUG << "FsaAccessHeader::read: m_charOrder = " << (int)cVal; #endif #endif char numBuf2[21]; strncpy(numBuf2, dstptr, 20 ); dstptr += 20; numBuf2[sizeof(numBuf2)-1] = ''; sscanf(numBuf2, "%lu %lu ", &(m_d->m_nbVertices), &(m_d->m_nbEdges) ); #ifdef DEBUG_CD LDEBUG << "FsaAccessHeader::read: nbVert = " << m_d->m_nbVertices << "m_nbEdges = " << m_d->m_nbEdges; #endif } void FsaAccessHeader::write( AbstractFsaAccessOStreamWrapper& ow) { #ifdef DEBUG_CD FSAAIOLOGINIT; LDEBUG << "FsaAccessHeader::write("; #endif char headBuf[HEADER_SIZE]; char *dstptr = headBuf; memset(dstptr, 0, HEADER_SIZE ); strncpy(dstptr, MAGIC_NUMBER, 12 ); dstptr += 12; sprintf(dstptr, "%02d.%02d", m_d->m_majorVersion, m_d->m_minorVersion); dstptr += 5; *dstptr++ = m_d->m_charType; *dstptr++ = m_d->m_packing; *dstptr++ = m_d->m_charOrder; sprintf(dstptr, "%09lu ", m_d->m_nbVertices); dstptr += 10; sprintf(dstptr, "%09lu ", m_d->m_nbEdges); dstptr += 10; ow.writeData( headBuf, HEADER_SIZE ); #ifdef DEBUG_CD LDEBUG << "FsaAccessHeader::write: os.write headbuf "; #endif } } // namespace FsaAccess } // namespace Common } // namespace Lima <commit_msg>Remove invalid characters<commit_after>/* Copyright 2002-2013 CEA LIST This file is part of LIMA. LIMA is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. LIMA is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with LIMA. If not, see <http://www.gnu.org/licenses/> */ /*************************************************************************** FsaAccessHeader.cpp - description ------------------- begin : mon nov 7 2005 copyright : (C) 2003-2005 by CEA email : [email protected] ***************************************************************************/ /*************************************************************************** * * * header for files * * compact dictionnary based on finite state automata * * implemented with Boost Graph library * * * ***************************************************************************/ // pour la definitin de one_byte, two_bytes, four_bytes #include "FsaAccessHeader.h" #include "FsaAccessIOStreamWrapper.h" #include "common/Data/LimaString.h" #include <sstream> #include <string.h> namespace Lima { namespace Common { namespace FsaAccess { class FsaAccessHeaderPrivate { friend class FsaAccessHeader; FsaAccessHeaderPrivate(bool trie_direction_fwd); virtual ~FsaAccessHeaderPrivate(); uint16_t m_majorVersion; uint16_t m_minorVersion; uint8_t m_charType; uint8_t m_packing; uint8_t m_charOrder; uint64_t m_nbVertices; uint64_t m_nbEdges; // uint64_t m_maxSimpleId; // uint64_t m_compoundsDataOffset; // uint64_t m_nbCompounds; /** * direction when reading characters of input key in getIndex * the value is set when access Data (list of keys) is compiled * and is stored in header of file * must be const!! * this is not a pamameter of getIndex() function! (depends on compiled data structure) * */ bool m_trie_direction_fwd; // long m_compoundsDataPos; }; FsaAccessHeaderPrivate::FsaAccessHeaderPrivate(bool trie_direction_fwd) : m_majorVersion( MAJOR_VERSION_16 ), m_minorVersion( MINOR_VERSION_16 ), m_packing(BUILDER), m_charOrder(FORWARD), m_nbVertices(0), m_nbEdges(0), // m_maxSimpleId(MAX_SIMPLE_TID), // m_compoundsDataOffset(0) // m_nbCompounds(0), m_trie_direction_fwd( trie_direction_fwd ) { if( sizeof(LimaChar) == 2 ) { m_charType = 2; } else { std::string mess = "FsaAccessBuilder::FsaAccessHeader: sizeof(LimaChar) must be 2!!!" ; #ifdef DEBUG_CD FSAALOGINIT; LERROR << mess.c_str(); #endif throw( FsaNotSaved( mess ) ); } } FsaAccessHeaderPrivate::~FsaAccessHeaderPrivate() { } FsaAccessHeader::FsaAccessHeader(bool trie_direction_fwd) : m_d(new FsaAccessHeaderPrivate(trie_direction_fwd)) { } FsaAccessHeader::FsaAccessHeader(const FsaAccessHeader& h) : m_d(new FsaAccessHeaderPrivate(*h.m_d)) { } FsaAccessHeader::~FsaAccessHeader() { delete m_d; } FsaAccessHeader& FsaAccessHeader::operator=(const FsaAccessHeader& h) {*m_d = *(h.m_d); return *this;} bool FsaAccessHeader::getTrieDirectionForward() const { return m_d->m_trie_direction_fwd; } uint64_t FsaAccessHeader::getNbVertices() const { return m_d->m_nbVertices; } uint64_t FsaAccessHeader::getNbEdges() const { return m_d->m_nbEdges; } void FsaAccessHeader::setPackingStatus(uint8_t packingStatus) { m_d->m_packing = packingStatus; } void FsaAccessHeader::setNbVertices(uint64_t nbVerts) { m_d->m_nbVertices = nbVerts; } void FsaAccessHeader::setNbEdges(uint64_t nbEdges) { m_d->m_nbEdges = nbEdges; } // uint64_t getMaxSimpleId() const { return m_maxSimpleId; } // uint64_t int getCompoundsDataOffset() const { return m_compoundsDataOffset; } // uint64_t getNbCompounds() const { return m_nbCompounds; } // void setStreamPos(std::ifstream& is); // const long& getStreamPos() { return m_compoundsDataPos; } void FsaAccessHeader::read( AbstractFsaAccessIStreamWrapper& iw ) { #ifdef DEBUG_CD FSAAIOLOGINIT; LDEBUG << "FsaAccessHeader::read()"; #endif char headBuf[HEADER_SIZE+1]; iw.readData( headBuf, HEADER_SIZE ); char *dstptr = headBuf; char magicNumber[13]; strncpy(magicNumber, dstptr, 12 ); dstptr += 12; magicNumber[sizeof(magicNumber)-1] = '\0'; if( strcmp(magicNumber,MAGIC_NUMBER) ) { std::string mess = "FsaAccessHeader::read: bad magic number '" + std::string(magicNumber) + "'" ; #ifdef DEBUG_CD LERROR << mess.c_str(); #endif throw( AccessByStringNotInitialized(mess) ); } char numBuf[6]; strncpy(numBuf, dstptr, 5 ); dstptr += 5; numBuf[sizeof(numBuf)-1] = '\0'; sscanf(numBuf, "%hu.%hu", &m_d->m_majorVersion, &m_d->m_minorVersion); #ifdef DEBUG_CD LDEBUG << "FsaAccessHeader::read: m_majorVersion = " << m_d->m_majorVersion << " m_minorVersion = " << m_d->m_minorVersion ; #endif uint16_t majorVersion = MAJOR_VERSION_16; // uint16_t minorVersion = MINOR_VERSION_16; if( m_d->m_majorVersion > majorVersion) { /* if( (m_majorVersion > majorVersion) ||((m_majorVersion == majorVersion) && (m_minorVersion > minorVersion) ) ) { */ std::string mess = "FsaAccessHeader::read: bad version = " + std::string(numBuf) + ". Get a release of your library or convert your file !!" ; #ifdef DEBUG_CD LERROR << mess.c_str(); #endif throw( AccessByStringNotInitialized(mess ) ); } uint8_t cVal= *dstptr++; m_d->m_charType = cVal; if( (m_d->m_charType != 1) && (m_d->m_charType != 2) && (m_d->m_charType != 4) ) { std::string mess = "FsaAccessHeader::read: byte_per_char must be 1, 2 or 4!!!" ; #ifdef DEBUG_CD LERROR << mess.c_str(); #endif throw( AccessByStringNotInitialized(mess) ); } #ifdef DEBUG_CD LDEBUG << "FsaAccessHeader::read: m_charType = " << (int)cVal; #endif cVal= *dstptr++; m_d->m_packing = cVal; if( (m_d->m_packing != BUILDER) && (m_d->m_packing != BUILT) && (m_d->m_packing != SPARE)) { std::string mess = "FsaAccessHeader::read: m_packing type is not recognized!!!" ; #ifdef DEBUG_CD LERROR << mess.c_str(); #endif throw( AccessByStringNotInitialized(mess) ); } #ifdef DEBUG_CD LDEBUG << "FsaAccessHeader::read: m_packing = " << (m_d->m_packing == BUILDER ? "BUILDER" : (m_d->m_packing == BUILT ? "BUILT" : "SPARE" )); #endif cVal= *dstptr++; #ifdef DEBUG_CD LDEBUG << "FsaAccessHeader::read: m_charOrder = " << (int)cVal; #endif m_d->m_charOrder = cVal; if( (m_d->m_charOrder != FORWARD) &&(m_d->m_charOrder != REVERSE) ) { std::string mess = "FsaAccessHeader::read: character order is not recognized!!!" ; #ifdef DEBUG_CD LERROR << mess.c_str(); #endif throw( AccessByStringNotInitialized(mess) ); } m_d->m_trie_direction_fwd = (m_d->m_charOrder == FORWARD); #ifdef DEBUG_CD LDEBUG << "FsaAccessHeader::read: m_charOrder = " << (m_d->m_charOrder == FORWARD ? "FORWARD" : "REVERSE" ); #ifdef DEBUG_CD LDEBUG << "FsaAccessHeader::read: m_charOrder = " << (int)cVal; #endif #endif char numBuf2[21]; strncpy(numBuf2, dstptr, 20 ); dstptr += 20; numBuf2[sizeof(numBuf2)-1] = '\0'; sscanf(numBuf2, "%lu %lu ", &(m_d->m_nbVertices), &(m_d->m_nbEdges) ); #ifdef DEBUG_CD LDEBUG << "FsaAccessHeader::read: nbVert = " << m_d->m_nbVertices << "m_nbEdges = " << m_d->m_nbEdges; #endif } void FsaAccessHeader::write( AbstractFsaAccessOStreamWrapper& ow) { #ifdef DEBUG_CD FSAAIOLOGINIT; LDEBUG << "FsaAccessHeader::write("; #endif char headBuf[HEADER_SIZE]; char *dstptr = headBuf; memset(dstptr, 0, HEADER_SIZE ); strncpy(dstptr, MAGIC_NUMBER, 12 ); dstptr += 12; sprintf(dstptr, "%02d.%02d", m_d->m_majorVersion, m_d->m_minorVersion); dstptr += 5; *dstptr++ = m_d->m_charType; *dstptr++ = m_d->m_packing; *dstptr++ = m_d->m_charOrder; sprintf(dstptr, "%09lu ", m_d->m_nbVertices); dstptr += 10; sprintf(dstptr, "%09lu ", m_d->m_nbEdges); dstptr += 10; ow.writeData( headBuf, HEADER_SIZE ); #ifdef DEBUG_CD LDEBUG << "FsaAccessHeader::write: os.write headbuf "; #endif } } // namespace FsaAccess } // namespace Common } // namespace Lima <|endoftext|>
<commit_before>/* Parsing.cpp - HTTP request parsing. Copyright (c) 2015 Ivan Grokhotkov. All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Modified 8 May 2015 by Hristo Gochkov (proper post and file upload handling) */ #include <Arduino.h> #include "WiFiServer.h" #include "WiFiClient.h" #include "ESP8266WebServer.h" // #define DEBUG #define DEBUG_OUTPUT Serial1 bool ESP8266WebServer::_parseRequest(WiFiClient& client) { // Read the first line of HTTP request String req = client.readStringUntil('\r'); client.readStringUntil('\n'); // First line of HTTP request looks like "GET /path HTTP/1.1" // Retrieve the "/path" part by finding the spaces int addr_start = req.indexOf(' '); int addr_end = req.indexOf(' ', addr_start + 1); if (addr_start == -1 || addr_end == -1) { #ifdef DEBUG DEBUG_OUTPUT.print("Invalid request: "); DEBUG_OUTPUT.println(req); #endif return false; } String methodStr = req.substring(0, addr_start); String url = req.substring(addr_start + 1, addr_end); String searchStr = ""; int hasSearch = url.indexOf('?'); if (hasSearch != -1){ searchStr = url.substring(hasSearch + 1); url = url.substring(0, hasSearch); } _currentUri = url; HTTPMethod method = HTTP_GET; if (methodStr == "POST") { method = HTTP_POST; } else if (methodStr == "DELETE") { method = HTTP_DELETE; } else if (methodStr == "PUT") { method = HTTP_PUT; } else if (methodStr == "PATCH") { method = HTTP_PATCH; } _currentMethod = method; #ifdef DEBUG DEBUG_OUTPUT.print("method: "); DEBUG_OUTPUT.print(methodStr); DEBUG_OUTPUT.print(" url: "); DEBUG_OUTPUT.print(url); DEBUG_OUTPUT.print(" search: "); DEBUG_OUTPUT.println(searchStr); #endif String formData; // below is needed only when POST type request if (method == HTTP_POST || method == HTTP_PUT || method == HTTP_PATCH || method == HTTP_DELETE){ String boundaryStr; String headerName; String headerValue; bool isForm = false; uint32_t contentLength = 0; //parse headers while(1){ req = client.readStringUntil('\r'); client.readStringUntil('\n'); if (req == "") break;//no moar headers int headerDiv = req.indexOf(':'); if (headerDiv == -1){ break; } headerName = req.substring(0, headerDiv); headerValue = req.substring(headerDiv + 2); if (headerName == "Content-Type"){ if (headerValue.startsWith("text/plain")){ isForm = false; } else if (headerValue.startsWith("multipart/form-data")){ boundaryStr = headerValue.substring(headerValue.indexOf('=')+1); isForm = true; } } else if (headerName == "Content-Length"){ contentLength = headerValue.toInt(); } } if (!isForm){ if (searchStr != "") searchStr += '&'; String bodyLine = client.readStringUntil('\r'); #ifdef DEBUG DEBUG_OUTPUT.print("Plain: "); DEBUG_OUTPUT.println(bodyLine); #endif if(bodyLine.startsWith("{") || bodyLine.startsWith("[") || bodyLine.indexOf('=') == -1){ //plain post json or other data searchStr += "plain="; searchStr += bodyLine; searchStr += client.readString(); } else { searchStr += bodyLine; client.readStringUntil('\n'); } } _parseArguments(searchStr); if (isForm){ _parseForm(client, boundaryStr, contentLength); } } else { _parseArguments(searchStr); } client.flush(); #ifdef DEBUG DEBUG_OUTPUT.print("Request: "); DEBUG_OUTPUT.println(url); DEBUG_OUTPUT.print(" Arguments: "); DEBUG_OUTPUT.println(searchStr); #endif return true; } void ESP8266WebServer::_parseArguments(String data) { #ifdef DEBUG DEBUG_OUTPUT.print("args: "); DEBUG_OUTPUT.println(data); #endif if (_currentArgs) delete[] _currentArgs; _currentArgs = 0; if (data.length() == 0) { _currentArgCount = 0; return; } _currentArgCount = 1; for (int i = 0; i < data.length(); ) { i = data.indexOf('&', i); if (i == -1) break; ++i; ++_currentArgCount; } #ifdef DEBUG DEBUG_OUTPUT.print("args count: "); DEBUG_OUTPUT.println(_currentArgCount); #endif _currentArgs = new RequestArgument[_currentArgCount]; int pos = 0; int iarg; for (iarg = 0; iarg < _currentArgCount;) { int equal_sign_index = data.indexOf('=', pos); int next_arg_index = data.indexOf('&', pos); #ifdef DEBUG DEBUG_OUTPUT.print("pos "); DEBUG_OUTPUT.print(pos); DEBUG_OUTPUT.print("=@ "); DEBUG_OUTPUT.print(equal_sign_index); DEBUG_OUTPUT.print(" &@ "); DEBUG_OUTPUT.println(next_arg_index); #endif if ((equal_sign_index == -1) || ((equal_sign_index > next_arg_index) && (next_arg_index != -1))) { #ifdef DEBUG DEBUG_OUTPUT.print("arg missing value: "); DEBUG_OUTPUT.println(iarg); #endif if (next_arg_index == -1) break; pos = next_arg_index + 1; continue; } RequestArgument& arg = _currentArgs[iarg]; arg.key = data.substring(pos, equal_sign_index); arg.value = data.substring(equal_sign_index + 1, next_arg_index); #ifdef DEBUG DEBUG_OUTPUT.print("arg "); DEBUG_OUTPUT.print(iarg); DEBUG_OUTPUT.print(" key: "); DEBUG_OUTPUT.print(arg.key); DEBUG_OUTPUT.print(" value: "); DEBUG_OUTPUT.println(arg.value); #endif ++iarg; if (next_arg_index == -1) break; pos = next_arg_index + 1; } _currentArgCount = iarg; #ifdef DEBUG DEBUG_OUTPUT.print("args count: "); DEBUG_OUTPUT.println(_currentArgCount); #endif } void ESP8266WebServer::_uploadWriteByte(uint8_t b){ if (_currentUpload.currentSize == HTTP_UPLOAD_BUFLEN){ if (_fileUploadHandler) _fileUploadHandler(); _currentUpload.totalSize += _currentUpload.currentSize; _currentUpload.currentSize = 0; } _currentUpload.buf[_currentUpload.currentSize++] = b; } uint8_t ESP8266WebServer::_uploadReadByte(WiFiClient& client){ int res = client.read(); if(res == -1){ while(!client.available()) yield(); res = client.read(); } return (uint8_t)res; } void ESP8266WebServer::_parseForm(WiFiClient& client, String boundary, uint32_t len){ #ifdef DEBUG DEBUG_OUTPUT.print("Parse Form: Boundary: "); DEBUG_OUTPUT.print(boundary); DEBUG_OUTPUT.print(" Length: "); DEBUG_OUTPUT.println(len); #endif String line; line = client.readStringUntil('\r'); client.readStringUntil('\n'); //start reading the form if (line == ("--"+boundary)){ RequestArgument* postArgs = new RequestArgument[32]; int postArgsLen = 0; while(1){ String argName; String argValue; String argType; String argFilename; bool argIsFile = false; line = client.readStringUntil('\r'); client.readStringUntil('\n'); if (line.startsWith("Content-Disposition")){ int nameStart = line.indexOf('='); if (nameStart != -1){ argName = line.substring(nameStart+2); nameStart = argName.indexOf('='); if (nameStart == -1){ argName = argName.substring(0, argName.length() - 1); } else { argFilename = argName.substring(nameStart+2, argName.length() - 1); argName = argName.substring(0, argName.indexOf('"')); argIsFile = true; #ifdef DEBUG DEBUG_OUTPUT.print("PostArg FileName: "); DEBUG_OUTPUT.println(argFilename); #endif //use GET to set the filename if uploading using blob if (argFilename == "blob" && hasArg("filename")) argFilename = arg("filename"); } #ifdef DEBUG DEBUG_OUTPUT.print("PostArg Name: "); DEBUG_OUTPUT.println(argName); #endif argType = "text/plain"; line = client.readStringUntil('\r'); client.readStringUntil('\n'); if (line.startsWith("Content-Type")){ argType = line.substring(line.indexOf(':')+2); //skip next line client.readStringUntil('\r'); client.readStringUntil('\n'); } #ifdef DEBUG DEBUG_OUTPUT.print("PostArg Type: "); DEBUG_OUTPUT.println(argType); #endif if (!argIsFile){ while(1){ line = client.readStringUntil('\r'); client.readStringUntil('\n'); if (line.startsWith("--"+boundary)) break; if (argValue.length() > 0) argValue += "\n"; argValue += line; } #ifdef DEBUG DEBUG_OUTPUT.print("PostArg Value: "); DEBUG_OUTPUT.println(argValue); DEBUG_OUTPUT.println(); #endif RequestArgument& arg = postArgs[postArgsLen++]; arg.key = argName; arg.value = argValue; if (line == ("--"+boundary+"--")){ #ifdef DEBUG DEBUG_OUTPUT.println("Done Parsing POST"); #endif break; } } else { _currentUpload.status = UPLOAD_FILE_START; _currentUpload.name = argName; _currentUpload.filename = argFilename; _currentUpload.type = argType; _currentUpload.totalSize = 0; _currentUpload.currentSize = 0; #ifdef DEBUG DEBUG_OUTPUT.print("Start File: "); DEBUG_OUTPUT.print(_currentUpload.filename); DEBUG_OUTPUT.print(" Type: "); DEBUG_OUTPUT.println(_currentUpload.type); #endif if (_fileUploadHandler) _fileUploadHandler(); _currentUpload.status = UPLOAD_FILE_WRITE; uint8_t argByte = _uploadReadByte(client); readfile: while(argByte != 0x0D){ _uploadWriteByte(argByte); argByte = _uploadReadByte(client); } argByte = _uploadReadByte(client); if (argByte == 0x0A){ argByte = _uploadReadByte(client); if ((char)argByte != '-'){ //continue reading the file _uploadWriteByte(0x0D); _uploadWriteByte(0x0A); goto readfile; } else { argByte = _uploadReadByte(client); if ((char)argByte != '-'){ //continue reading the file _uploadWriteByte(0x0D); _uploadWriteByte(0x0A); _uploadWriteByte((uint8_t)('-')); goto readfile; } } uint8_t endBuf[boundary.length()]; client.readBytes(endBuf, boundary.length()); if (strstr((const char*)endBuf, boundary.c_str()) != NULL){ if (_fileUploadHandler) _fileUploadHandler(); _currentUpload.totalSize += _currentUpload.currentSize; _currentUpload.status = UPLOAD_FILE_END; if (_fileUploadHandler) _fileUploadHandler(); #ifdef DEBUG DEBUG_OUTPUT.print("End File: "); DEBUG_OUTPUT.print(_currentUpload.filename); DEBUG_OUTPUT.print(" Type: "); DEBUG_OUTPUT.print(_currentUpload.type); DEBUG_OUTPUT.print(" Size: "); DEBUG_OUTPUT.println(_currentUpload.totalSize); #endif line = client.readStringUntil(0x0D); client.readStringUntil(0x0A); if (line == "--"){ #ifdef DEBUG DEBUG_OUTPUT.println("Done Parsing POST"); #endif break; } continue; } else { _uploadWriteByte(0x0D); _uploadWriteByte(0x0A); _uploadWriteByte((uint8_t)('-')); _uploadWriteByte((uint8_t)('-')); uint32_t i = 0; while(i < boundary.length()){ _uploadWriteByte(endBuf[i++]); } argByte = _uploadReadByte(client); goto readfile; } } else { _uploadWriteByte(0x0D); goto readfile; } break; } } } } int iarg; int totalArgs = ((32 - postArgsLen) < _currentArgCount)?(32 - postArgsLen):_currentArgCount; for (iarg = 0; iarg < totalArgs; iarg++){ RequestArgument& arg = postArgs[postArgsLen++]; arg.key = _currentArgs[iarg].key; arg.value = _currentArgs[iarg].value; } if (_currentArgs) delete[] _currentArgs; _currentArgs = new RequestArgument[postArgsLen]; for (iarg = 0; iarg < postArgsLen; iarg++){ RequestArgument& arg = _currentArgs[iarg]; arg.key = postArgs[iarg].key; arg.value = postArgs[iarg].value; } _currentArgCount = iarg; if (postArgs) delete[] postArgs; } } <commit_msg>fix plain post slowdown<commit_after>/* Parsing.cpp - HTTP request parsing. Copyright (c) 2015 Ivan Grokhotkov. All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Modified 8 May 2015 by Hristo Gochkov (proper post and file upload handling) */ #include <Arduino.h> #include "WiFiServer.h" #include "WiFiClient.h" #include "ESP8266WebServer.h" // #define DEBUG #define DEBUG_OUTPUT Serial1 bool ESP8266WebServer::_parseRequest(WiFiClient& client) { // Read the first line of HTTP request String req = client.readStringUntil('\r'); client.readStringUntil('\n'); // First line of HTTP request looks like "GET /path HTTP/1.1" // Retrieve the "/path" part by finding the spaces int addr_start = req.indexOf(' '); int addr_end = req.indexOf(' ', addr_start + 1); if (addr_start == -1 || addr_end == -1) { #ifdef DEBUG DEBUG_OUTPUT.print("Invalid request: "); DEBUG_OUTPUT.println(req); #endif return false; } String methodStr = req.substring(0, addr_start); String url = req.substring(addr_start + 1, addr_end); String searchStr = ""; int hasSearch = url.indexOf('?'); if (hasSearch != -1){ searchStr = url.substring(hasSearch + 1); url = url.substring(0, hasSearch); } _currentUri = url; HTTPMethod method = HTTP_GET; if (methodStr == "POST") { method = HTTP_POST; } else if (methodStr == "DELETE") { method = HTTP_DELETE; } else if (methodStr == "PUT") { method = HTTP_PUT; } else if (methodStr == "PATCH") { method = HTTP_PATCH; } _currentMethod = method; #ifdef DEBUG DEBUG_OUTPUT.print("method: "); DEBUG_OUTPUT.print(methodStr); DEBUG_OUTPUT.print(" url: "); DEBUG_OUTPUT.print(url); DEBUG_OUTPUT.print(" search: "); DEBUG_OUTPUT.println(searchStr); #endif String formData; // below is needed only when POST type request if (method == HTTP_POST || method == HTTP_PUT || method == HTTP_PATCH || method == HTTP_DELETE){ String boundaryStr; String headerName; String headerValue; bool isForm = false; uint32_t contentLength = 0; //parse headers while(1){ req = client.readStringUntil('\r'); client.readStringUntil('\n'); if (req == "") break;//no moar headers int headerDiv = req.indexOf(':'); if (headerDiv == -1){ break; } headerName = req.substring(0, headerDiv); headerValue = req.substring(headerDiv + 2); if (headerName == "Content-Type"){ if (headerValue.startsWith("text/plain")){ isForm = false; } else if (headerValue.startsWith("multipart/form-data")){ boundaryStr = headerValue.substring(headerValue.indexOf('=')+1); isForm = true; } } else if (headerName == "Content-Length"){ contentLength = headerValue.toInt(); } } if (!isForm){ if (searchStr != "") searchStr += '&'; size_t plainLen = client.available(); char *plainBuf = (char*)malloc(plainLen+1); client.readBytes(plainBuf, plainLen); plainBuf[plainLen] = '\0'; #ifdef DEBUG DEBUG_OUTPUT.print("Plain: "); DEBUG_OUTPUT.println(plainBuf); #endif if(plainBuf[0] == '{' || plainBuf[0] == '[' || strstr(plainBuf, "=") == NULL){ //plain post json or other data searchStr += "plain="; searchStr += plainBuf; } else { searchStr += plainBuf; } free(plainBuf); } _parseArguments(searchStr); if (isForm){ _parseForm(client, boundaryStr, contentLength); } } else { _parseArguments(searchStr); } client.flush(); #ifdef DEBUG DEBUG_OUTPUT.print("Request: "); DEBUG_OUTPUT.println(url); DEBUG_OUTPUT.print(" Arguments: "); DEBUG_OUTPUT.println(searchStr); #endif return true; } void ESP8266WebServer::_parseArguments(String data) { #ifdef DEBUG DEBUG_OUTPUT.print("args: "); DEBUG_OUTPUT.println(data); #endif if (_currentArgs) delete[] _currentArgs; _currentArgs = 0; if (data.length() == 0) { _currentArgCount = 0; return; } _currentArgCount = 1; for (int i = 0; i < data.length(); ) { i = data.indexOf('&', i); if (i == -1) break; ++i; ++_currentArgCount; } #ifdef DEBUG DEBUG_OUTPUT.print("args count: "); DEBUG_OUTPUT.println(_currentArgCount); #endif _currentArgs = new RequestArgument[_currentArgCount]; int pos = 0; int iarg; for (iarg = 0; iarg < _currentArgCount;) { int equal_sign_index = data.indexOf('=', pos); int next_arg_index = data.indexOf('&', pos); #ifdef DEBUG DEBUG_OUTPUT.print("pos "); DEBUG_OUTPUT.print(pos); DEBUG_OUTPUT.print("=@ "); DEBUG_OUTPUT.print(equal_sign_index); DEBUG_OUTPUT.print(" &@ "); DEBUG_OUTPUT.println(next_arg_index); #endif if ((equal_sign_index == -1) || ((equal_sign_index > next_arg_index) && (next_arg_index != -1))) { #ifdef DEBUG DEBUG_OUTPUT.print("arg missing value: "); DEBUG_OUTPUT.println(iarg); #endif if (next_arg_index == -1) break; pos = next_arg_index + 1; continue; } RequestArgument& arg = _currentArgs[iarg]; arg.key = data.substring(pos, equal_sign_index); arg.value = data.substring(equal_sign_index + 1, next_arg_index); #ifdef DEBUG DEBUG_OUTPUT.print("arg "); DEBUG_OUTPUT.print(iarg); DEBUG_OUTPUT.print(" key: "); DEBUG_OUTPUT.print(arg.key); DEBUG_OUTPUT.print(" value: "); DEBUG_OUTPUT.println(arg.value); #endif ++iarg; if (next_arg_index == -1) break; pos = next_arg_index + 1; } _currentArgCount = iarg; #ifdef DEBUG DEBUG_OUTPUT.print("args count: "); DEBUG_OUTPUT.println(_currentArgCount); #endif } void ESP8266WebServer::_uploadWriteByte(uint8_t b){ if (_currentUpload.currentSize == HTTP_UPLOAD_BUFLEN){ if (_fileUploadHandler) _fileUploadHandler(); _currentUpload.totalSize += _currentUpload.currentSize; _currentUpload.currentSize = 0; } _currentUpload.buf[_currentUpload.currentSize++] = b; } uint8_t ESP8266WebServer::_uploadReadByte(WiFiClient& client){ int res = client.read(); if(res == -1){ while(!client.available()) yield(); res = client.read(); } return (uint8_t)res; } void ESP8266WebServer::_parseForm(WiFiClient& client, String boundary, uint32_t len){ #ifdef DEBUG DEBUG_OUTPUT.print("Parse Form: Boundary: "); DEBUG_OUTPUT.print(boundary); DEBUG_OUTPUT.print(" Length: "); DEBUG_OUTPUT.println(len); #endif String line; line = client.readStringUntil('\r'); client.readStringUntil('\n'); //start reading the form if (line == ("--"+boundary)){ RequestArgument* postArgs = new RequestArgument[32]; int postArgsLen = 0; while(1){ String argName; String argValue; String argType; String argFilename; bool argIsFile = false; line = client.readStringUntil('\r'); client.readStringUntil('\n'); if (line.startsWith("Content-Disposition")){ int nameStart = line.indexOf('='); if (nameStart != -1){ argName = line.substring(nameStart+2); nameStart = argName.indexOf('='); if (nameStart == -1){ argName = argName.substring(0, argName.length() - 1); } else { argFilename = argName.substring(nameStart+2, argName.length() - 1); argName = argName.substring(0, argName.indexOf('"')); argIsFile = true; #ifdef DEBUG DEBUG_OUTPUT.print("PostArg FileName: "); DEBUG_OUTPUT.println(argFilename); #endif //use GET to set the filename if uploading using blob if (argFilename == "blob" && hasArg("filename")) argFilename = arg("filename"); } #ifdef DEBUG DEBUG_OUTPUT.print("PostArg Name: "); DEBUG_OUTPUT.println(argName); #endif argType = "text/plain"; line = client.readStringUntil('\r'); client.readStringUntil('\n'); if (line.startsWith("Content-Type")){ argType = line.substring(line.indexOf(':')+2); //skip next line client.readStringUntil('\r'); client.readStringUntil('\n'); } #ifdef DEBUG DEBUG_OUTPUT.print("PostArg Type: "); DEBUG_OUTPUT.println(argType); #endif if (!argIsFile){ while(1){ line = client.readStringUntil('\r'); client.readStringUntil('\n'); if (line.startsWith("--"+boundary)) break; if (argValue.length() > 0) argValue += "\n"; argValue += line; } #ifdef DEBUG DEBUG_OUTPUT.print("PostArg Value: "); DEBUG_OUTPUT.println(argValue); DEBUG_OUTPUT.println(); #endif RequestArgument& arg = postArgs[postArgsLen++]; arg.key = argName; arg.value = argValue; if (line == ("--"+boundary+"--")){ #ifdef DEBUG DEBUG_OUTPUT.println("Done Parsing POST"); #endif break; } } else { _currentUpload.status = UPLOAD_FILE_START; _currentUpload.name = argName; _currentUpload.filename = argFilename; _currentUpload.type = argType; _currentUpload.totalSize = 0; _currentUpload.currentSize = 0; #ifdef DEBUG DEBUG_OUTPUT.print("Start File: "); DEBUG_OUTPUT.print(_currentUpload.filename); DEBUG_OUTPUT.print(" Type: "); DEBUG_OUTPUT.println(_currentUpload.type); #endif if (_fileUploadHandler) _fileUploadHandler(); _currentUpload.status = UPLOAD_FILE_WRITE; uint8_t argByte = _uploadReadByte(client); readfile: while(argByte != 0x0D){ _uploadWriteByte(argByte); argByte = _uploadReadByte(client); } argByte = _uploadReadByte(client); if (argByte == 0x0A){ argByte = _uploadReadByte(client); if ((char)argByte != '-'){ //continue reading the file _uploadWriteByte(0x0D); _uploadWriteByte(0x0A); goto readfile; } else { argByte = _uploadReadByte(client); if ((char)argByte != '-'){ //continue reading the file _uploadWriteByte(0x0D); _uploadWriteByte(0x0A); _uploadWriteByte((uint8_t)('-')); goto readfile; } } uint8_t endBuf[boundary.length()]; client.readBytes(endBuf, boundary.length()); if (strstr((const char*)endBuf, boundary.c_str()) != NULL){ if (_fileUploadHandler) _fileUploadHandler(); _currentUpload.totalSize += _currentUpload.currentSize; _currentUpload.status = UPLOAD_FILE_END; if (_fileUploadHandler) _fileUploadHandler(); #ifdef DEBUG DEBUG_OUTPUT.print("End File: "); DEBUG_OUTPUT.print(_currentUpload.filename); DEBUG_OUTPUT.print(" Type: "); DEBUG_OUTPUT.print(_currentUpload.type); DEBUG_OUTPUT.print(" Size: "); DEBUG_OUTPUT.println(_currentUpload.totalSize); #endif line = client.readStringUntil(0x0D); client.readStringUntil(0x0A); if (line == "--"){ #ifdef DEBUG DEBUG_OUTPUT.println("Done Parsing POST"); #endif break; } continue; } else { _uploadWriteByte(0x0D); _uploadWriteByte(0x0A); _uploadWriteByte((uint8_t)('-')); _uploadWriteByte((uint8_t)('-')); uint32_t i = 0; while(i < boundary.length()){ _uploadWriteByte(endBuf[i++]); } argByte = _uploadReadByte(client); goto readfile; } } else { _uploadWriteByte(0x0D); goto readfile; } break; } } } } int iarg; int totalArgs = ((32 - postArgsLen) < _currentArgCount)?(32 - postArgsLen):_currentArgCount; for (iarg = 0; iarg < totalArgs; iarg++){ RequestArgument& arg = postArgs[postArgsLen++]; arg.key = _currentArgs[iarg].key; arg.value = _currentArgs[iarg].value; } if (_currentArgs) delete[] _currentArgs; _currentArgs = new RequestArgument[postArgsLen]; for (iarg = 0; iarg < postArgsLen; iarg++){ RequestArgument& arg = _currentArgs[iarg]; arg.key = postArgs[iarg].key; arg.value = postArgs[iarg].value; } _currentArgCount = iarg; if (postArgs) delete[] postArgs; } } <|endoftext|>
<commit_before>#pragma once #ifndef __MESSAGE_BASE_IMPL_HPP__ #define __MESSAGE_BASE_IMPL_HPP__ #include <glog/logging.h> #include "common.hpp" #include "MessageBase.hpp" #ifndef ENABLE_RDMA_AGGREGATOR //#define LEGACY_SEND #endif //#define LEGACY_SEND #include "RDMAAggregator.hpp" namespace Grappa { /// Internal messaging functions namespace impl { /// @addtogroup Communication /// @{ inline void Grappa::impl::MessageBase::enqueue() { CHECK( !is_moved_ ) << "Shouldn't be sending a message that has been moved!" << " Your compiler's return value optimization failed you here."; DCHECK_NULL( next_ ); DCHECK_EQ( is_enqueued_, false ) << "Why are we enqueuing a message that's already enqueued?"; DCHECK_EQ( is_sent_, false ) << "Why are we enqueuing a message that's already sent?"; is_enqueued_ = true; DVLOG(5) << this << " on " << global_scheduler.get_current_thread() << " enqueuing with is_enqueued_=" << is_enqueued_ << " and is_sent_= " << is_sent_; #ifndef LEGACY_SEND Grappa::impl::global_rdma_aggregator.enqueue( this ); #endif #ifdef LEGACY_SEND legacy_send(); #endif } inline void Grappa::impl::MessageBase::enqueue( Core c ) { destination_ = c; enqueue(); } inline void Grappa::impl::MessageBase::send_immediate() { CHECK( !is_moved_ ) << "Shouldn't be sending a message that has been moved!" << " Your compiler's return value optimization failed you here."; is_enqueued_ = true; #ifndef LEGACY_SEND Grappa::impl::global_rdma_aggregator.send_immediate( this ); #endif #ifdef LEGACY_SEND legacy_send(); #endif } inline void Grappa::impl::MessageBase::send_immediate( Core c ) { destination_ = c; send_immediate(); } /// @} } } #endif // __MESSAGE_BASE_IMPL_HPP__ <commit_msg>Disable RDMA aggregator by default<commit_after>#pragma once #ifndef __MESSAGE_BASE_IMPL_HPP__ #define __MESSAGE_BASE_IMPL_HPP__ #include <glog/logging.h> #include "common.hpp" #include "MessageBase.hpp" // Remove this to use new aggregator. #define LEGACY_SEND #include "RDMAAggregator.hpp" namespace Grappa { /// Internal messaging functions namespace impl { /// @addtogroup Communication /// @{ inline void Grappa::impl::MessageBase::enqueue() { CHECK( !is_moved_ ) << "Shouldn't be sending a message that has been moved!" << " Your compiler's return value optimization failed you here."; DCHECK_NULL( next_ ); DCHECK_EQ( is_enqueued_, false ) << "Why are we enqueuing a message that's already enqueued?"; DCHECK_EQ( is_sent_, false ) << "Why are we enqueuing a message that's already sent?"; is_enqueued_ = true; DVLOG(5) << this << " on " << global_scheduler.get_current_thread() << " enqueuing with is_enqueued_=" << is_enqueued_ << " and is_sent_= " << is_sent_; #ifndef LEGACY_SEND Grappa::impl::global_rdma_aggregator.enqueue( this ); #endif #ifdef LEGACY_SEND legacy_send(); #endif } inline void Grappa::impl::MessageBase::enqueue( Core c ) { destination_ = c; enqueue(); } inline void Grappa::impl::MessageBase::send_immediate() { CHECK( !is_moved_ ) << "Shouldn't be sending a message that has been moved!" << " Your compiler's return value optimization failed you here."; is_enqueued_ = true; #ifndef LEGACY_SEND Grappa::impl::global_rdma_aggregator.send_immediate( this ); #endif #ifdef LEGACY_SEND legacy_send(); #endif } inline void Grappa::impl::MessageBase::send_immediate( Core c ) { destination_ = c; send_immediate(); } /// @} } } #endif // __MESSAGE_BASE_IMPL_HPP__ <|endoftext|>
<commit_before>// // Created by monty on 23/11/15. // #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "glm/gtc/type_ptr.hpp" #include "nanovg.h" #ifdef __APPLE__ #if TARGET_IOS #define NANOVG_GLES2_IMPLEMENTATION #import <OpenGLES/ES2/gl.h> #import <OpenGLES/ES2/glext.h> #else #define NANOVG_GL2_IMPLEMENTATION #import <OpenGL/OpenGL.h> #import <OpenGL/gl3.h> #endif #else #if defined(__ANDROID__ ) || defined(__EMSCRIPTEN__) || defined(MESA_GLES2) #define NANOVG_GLES2_IMPLEMENTATION #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #include <EGL/egl.h> #else #define NANOVG_GL2_IMPLEMENTATION #include <GL/gl.h> #endif #endif #include "nanovg_gl.h" #include "nanovg_gl_utils.h" #include <memory> #include <vector> #include <iostream> #include <sstream> #include <unordered_set> #include <map> #include <algorithm> #include <tuple> #include <array> #include <fstream> #include "Vec2i.h" #include "IMapElement.h" #include "CTeam.h" #include "CItem.h" #include "CActor.h" #include "CGameDelegate.h" #include "IFileLoaderDelegate.h" #include "CMap.h" #include "NativeBitmap.h" #include "Texture.h" #include "Material.h" #include "Trig.h" #include "TrigBatch.h" #include "MeshObject.h" #include "Logger.h" #include "MaterialList.h" #include "Scene.h" #include "Common.h" #include "VBORenderingJob.h" #include "Vec2i.h" #include "NativeBitmap.h" #include "IMapElement.h" #include "CGameDelegate.h" #include "CMap.h" #include "IRenderer.h" #include "NoudarDungeonSnapshot.h" #include "GraphicNode.h" #include "OverlayNanoVGRenderer.h" #include "AnimationStep.h" #include "Animation.h" NVGcontext *mContext; std::shared_ptr<odb::Animation> currentAnimation = nullptr; std::map<std::string, std::shared_ptr<odb::Animation>> animations; long timeUntilNextFrame = 0; int frame = 0; std::vector<NVGpaint> paints; namespace odb { void OverlayNanoVGRenderer::setFrame(float width, float height) { mWidth = width; mHeight = height; } void OverlayNanoVGRenderer::loadFonts(std::shared_ptr<Knights::IFileLoaderDelegate> fileLoaderDelegate) { mFontData = fileLoaderDelegate->loadBinaryFileFromPath("MedievalSharp.ttf"); } OverlayNanoVGRenderer::OverlayNanoVGRenderer(std::vector<std::shared_ptr<odb::NativeBitmap>> bitmaps) { for (const auto &bitmap : bitmaps) { auto id = bitmap->getId(); mBitmaps[id] = bitmap; } animations[ "crossbow-still" ] = std::make_shared<odb::Animation>( std::vector<odb::AnimationStep>{ {{ std::make_shared<odb::GraphicNode>( "bow0.png", glm::vec2{0.5125f, 0.85f}, glm::vec2{0.512f, 0.8f} ), }, 20000 }, {{ std::make_shared<odb::GraphicNode>( "bow0.png", glm::vec2{0.512f, 0.8f}, glm::vec2{0.5125f, 0.85f} ) }, 20000 }, }, true, "" ); animations[ "crossbow-fire" ] = std::make_shared<odb::Animation>( std::vector<odb::AnimationStep>{ {{ std::make_shared<odb::GraphicNode>( "bow0.png", glm::vec2{0.512f, 0.8f} ), }, 500 }, {{ std::make_shared<odb::GraphicNode>( "bow1.png", glm::vec2{0.512f, 0.8f}, glm::vec2{0.5125f, 0.85f} ), }, 500 }, {{ std::make_shared<odb::GraphicNode>( "bow1.png", glm::vec2{0.5125f, 0.85f} ) }, 500 }, {{ std::make_shared<odb::GraphicNode>( "bow1.png", glm::vec2{0.5125f, 0.85f}, glm::vec2( 0.4f, 1.0f) ) }, 500 }, {{}, 200 }, }, false, "crossbow-reload" ); animations[ "crossbow-reload" ] = std::make_shared<odb::Animation>( //arco-mão-esquerda-diff: 0.1, 0.65 std::vector<odb::AnimationStep>{ {{ std::make_shared<odb::GraphicNode>( "bow2.png", glm::vec2(0.15f, 1.0f), glm::vec2(0.15f, 0.2f) ), std::make_shared<odb::GraphicNode>("hand1.png", glm::vec2(0.25f, 1.65f), glm::vec2(0.25f, 0.85f) ) }, 500 }, {{ std::make_shared<odb::GraphicNode>( "bow2.png", glm::vec2(0.15f, 0.2f) ), std::make_shared<odb::GraphicNode>("hand1.png", glm::vec2(0.25f, 0.85f) ) }, 500 }, {{ std::make_shared<odb::GraphicNode>( "bow2.png", glm::vec2{0.2f, 0.15f} ), std::make_shared<odb::GraphicNode>( "hand1.png", glm::vec2{0.3f, 0.8f} ), std::make_shared<odb::GraphicNode>( "hand0.png", glm::vec2(0.55f, 1.0f) , glm::vec2{0.55f, 0.65f} ), std::make_shared<odb::GraphicNode>( "dart0.png", glm::vec2(0.55f, 1.0f), glm::vec2{0.55f, 0.65f} ) }, 500 }, {{ std::make_shared<odb::GraphicNode>( "bow2.png", glm::vec2{0.2f, 0.15f} ), std::make_shared<odb::GraphicNode>( "hand1.png", glm::vec2{0.3f, 0.8f} ), std::make_shared<odb::GraphicNode>( "hand0.png", glm::vec2{0.45f, 0.65f} ), std::make_shared<odb::GraphicNode>( "dart0.png", glm::vec2{0.45f, 0.65f} ) }, 2000 }, {{ std::make_shared<odb::GraphicNode>( "bow2.png", glm::vec2{0.1f, 0.3f} ), std::make_shared<odb::GraphicNode>( "hand1.png", glm::vec2{0.2f, 0.95f} ), std::make_shared<odb::GraphicNode>( "dart0.png", glm::vec2{0.35f, 0.8f} ), std::make_shared<odb::GraphicNode>( "hand0.png", glm::vec2(0.55f, 0.8f), glm::vec2( 0.5f, 1.0f ) ), }, 1000 }, {{ std::make_shared<odb::GraphicNode>( "bow2.png", glm::vec2{0.1f, 0.3f}, glm::vec2( 0.1f, 1.0f ) ), std::make_shared<odb::GraphicNode>( "hand1.png", glm::vec2{0.2f, 0.95f}, glm::vec2( 0.2f, 1.65f ) ), std::make_shared<odb::GraphicNode>( "dart0.png", glm::vec2{0.35f, 0.8f}, glm::vec2( 0.35f, 1.5f ) ) }, 1000 }, {{ std::make_shared<odb::GraphicNode>( "bow0.png", glm::vec2{0.35f, 1.0f}, glm::vec2{0.45f, 0.8f} ), }, 500 }, {{ std::make_shared<odb::GraphicNode>( "bow0.png", glm::vec2{0.45f, 0.8f}, glm::vec2{0.5125f, 0.85f} ), }, 500 }, }, false, "crossbow-still" ); currentAnimation = nullptr; } void OverlayNanoVGRenderer::render(const odb::NoudarDungeonSnapshot &snapshot) { if (mFontData.size() > 0) { #ifdef NANOVG_GLES2_IMPLEMENTATION mContext = nvgCreateGLES2(NVG_STENCIL_STROKES); #else mContext = nvgCreateGL2(NVG_ANTIALIAS | NVG_STENCIL_STROKES ); #endif if (!mContext) { std::cout << "NVG context is faulty as salty" << std::endl; } unsigned char *data = (unsigned char *) malloc(mFontData.size()); std::copy(mFontData.begin(), mFontData.end(), data); nvgCreateFontMem(mContext, "font", data, mFontData.size(), 1); mFontData.clear(); } if (mFrames.empty()) { for (const auto &bitmapPair : mBitmaps) { auto bitmap = bitmapPair.second; int imgW = bitmap->getWidth(); int imgH = bitmap->getHeight(); mFrames[bitmapPair.first] = nvgCreateImageRGBA(mContext, imgW, imgH, 0, (const unsigned char *) bitmap->getPixelData()); } } glViewport(0, 0, mWidth, mHeight); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_DEPTH_TEST); nvgBeginFrame(mContext, mWidth, mHeight, mWidth / mHeight); nvgFontSize(mContext, 18.0f); nvgFontFace(mContext, "font"); nvgFillColor(mContext, nvgRGBA(255, 255, 255, 255)); nvgStrokeColor(mContext, nvgRGBA(255, 0, 0, 255)); nvgTextAlign(mContext, NVG_ALIGN_LEFT | NVG_ALIGN_MIDDLE); nvgText(mContext, 10, 10, snapshot.mCurrentItem.c_str(), nullptr); std::stringstream ss; ss << snapshot.mHP; nvgText(mContext, 10, mHeight - 18, ss.str().c_str(), nullptr); timeUntilNextFrame -= (snapshot.mTimestamp - mLastTimestamp); mLastTimestamp = snapshot.mTimestamp; if ( currentAnimation != nullptr ) { auto animationSize = currentAnimation->mStepList.size(); if (timeUntilNextFrame <= 0 && frame < animationSize) { if (currentAnimation->mRepeatedPlayback) { frame = (frame + 1) % currentAnimation->mStepList.size(); } else if (frame < animationSize - 1) { ++frame; } else { playAnimation( snapshot.mTimestamp, currentAnimation->mNextAnimation ); } timeUntilNextFrame = currentAnimation->mStepList[frame].mDelay; } for (const auto &node : currentAnimation->mStepList[frame].mNodes) { auto nodeId = node->mFrameId; auto registeredTexture = mFrames[node->mFrameId]; auto bitmap = mBitmaps[node->mFrameId]; int imgW = bitmap->getWidth(); int imgH = bitmap->getHeight(); auto position = node->getPositionForTime( 1.0f - ((float) timeUntilNextFrame ) / ( (float) currentAnimation->mStepList[frame].mDelay ) ); float offsetX = position.x * mWidth; float offsetY = position.y * mHeight; auto imgPaint = nvgImagePattern(mContext, offsetX, offsetY, imgW, imgH, 0, registeredTexture, 1.0f); nvgBeginPath(mContext); nvgRect(mContext, offsetX, offsetY, imgW, imgH); nvgFillPaint(mContext, imgPaint); nvgFill(mContext); } } nvgEndFrame(mContext); glDisable(GL_BLEND); glEnable(GL_DEPTH_TEST); } OverlayNanoVGRenderer::~OverlayNanoVGRenderer() { nvgDeleteGLES2(mContext); } void OverlayNanoVGRenderer::playAnimation( long currentTimestamp, std::string animationName ) { currentAnimation = animations[ animationName ]; if ( currentAnimation != nullptr ) { mLastTimestamp = currentTimestamp; timeUntilNextFrame = currentAnimation->mStepList[frame].mDelay; frame = 0; } } } <commit_msg>Correct image sizes to work on all resolutions<commit_after>// // Created by monty on 23/11/15. // #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "glm/gtc/type_ptr.hpp" #include "nanovg.h" #ifdef __APPLE__ #if TARGET_IOS #define NANOVG_GLES2_IMPLEMENTATION #import <OpenGLES/ES2/gl.h> #import <OpenGLES/ES2/glext.h> #else #define NANOVG_GL2_IMPLEMENTATION #import <OpenGL/OpenGL.h> #import <OpenGL/gl3.h> #endif #else #if defined(__ANDROID__ ) || defined(__EMSCRIPTEN__) || defined(MESA_GLES2) #define NANOVG_GLES2_IMPLEMENTATION #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #include <EGL/egl.h> #else #define NANOVG_GL2_IMPLEMENTATION #include <GL/gl.h> #endif #endif #include "nanovg_gl.h" #include "nanovg_gl_utils.h" #include <memory> #include <vector> #include <iostream> #include <sstream> #include <unordered_set> #include <map> #include <algorithm> #include <tuple> #include <array> #include <fstream> #include "Vec2i.h" #include "IMapElement.h" #include "CTeam.h" #include "CItem.h" #include "CActor.h" #include "CGameDelegate.h" #include "IFileLoaderDelegate.h" #include "CMap.h" #include "NativeBitmap.h" #include "Texture.h" #include "Material.h" #include "Trig.h" #include "TrigBatch.h" #include "MeshObject.h" #include "Logger.h" #include "MaterialList.h" #include "Scene.h" #include "Common.h" #include "VBORenderingJob.h" #include "Vec2i.h" #include "NativeBitmap.h" #include "IMapElement.h" #include "CGameDelegate.h" #include "CMap.h" #include "IRenderer.h" #include "NoudarDungeonSnapshot.h" #include "GraphicNode.h" #include "OverlayNanoVGRenderer.h" #include "AnimationStep.h" #include "Animation.h" NVGcontext *mContext; std::shared_ptr<odb::Animation> currentAnimation = nullptr; std::map<std::string, std::shared_ptr<odb::Animation>> animations; long timeUntilNextFrame = 0; int frame = 0; std::vector<NVGpaint> paints; namespace odb { void OverlayNanoVGRenderer::setFrame(float width, float height) { mWidth = width; mHeight = height; } void OverlayNanoVGRenderer::loadFonts(std::shared_ptr<Knights::IFileLoaderDelegate> fileLoaderDelegate) { mFontData = fileLoaderDelegate->loadBinaryFileFromPath("MedievalSharp.ttf"); } OverlayNanoVGRenderer::OverlayNanoVGRenderer(std::vector<std::shared_ptr<odb::NativeBitmap>> bitmaps) { for (const auto &bitmap : bitmaps) { auto id = bitmap->getId(); mBitmaps[id] = bitmap; } animations[ "crossbow-still" ] = std::make_shared<odb::Animation>( std::vector<odb::AnimationStep>{ {{ std::make_shared<odb::GraphicNode>( "bow0.png", glm::vec2{0.5125f, 0.85f}, glm::vec2{0.512f, 0.8f} ), }, 20000 }, {{ std::make_shared<odb::GraphicNode>( "bow0.png", glm::vec2{0.512f, 0.8f}, glm::vec2{0.5125f, 0.85f} ) }, 20000 }, }, true, "" ); animations[ "crossbow-fire" ] = std::make_shared<odb::Animation>( std::vector<odb::AnimationStep>{ {{ std::make_shared<odb::GraphicNode>( "bow0.png", glm::vec2{0.512f, 0.8f} ), }, 500 }, {{ std::make_shared<odb::GraphicNode>( "bow1.png", glm::vec2{0.512f, 0.8f}, glm::vec2{0.5125f, 0.85f} ), }, 500 }, {{ std::make_shared<odb::GraphicNode>( "bow1.png", glm::vec2{0.5125f, 0.85f} ) }, 500 }, {{ std::make_shared<odb::GraphicNode>( "bow1.png", glm::vec2{0.5125f, 0.85f}, glm::vec2( 0.4f, 1.0f) ) }, 500 }, {{}, 200 }, }, false, "crossbow-reload" ); animations[ "crossbow-reload" ] = std::make_shared<odb::Animation>( //arco-mão-esquerda-diff: 0.1, 0.65 std::vector<odb::AnimationStep>{ {{ std::make_shared<odb::GraphicNode>( "bow2.png", glm::vec2(0.15f, 1.0f), glm::vec2(0.15f, 0.2f) ), std::make_shared<odb::GraphicNode>("hand1.png", glm::vec2(0.25f, 1.65f), glm::vec2(0.25f, 0.85f) ) }, 500 }, {{ std::make_shared<odb::GraphicNode>( "bow2.png", glm::vec2(0.15f, 0.2f) ), std::make_shared<odb::GraphicNode>("hand1.png", glm::vec2(0.25f, 0.85f) ) }, 500 }, {{ std::make_shared<odb::GraphicNode>( "bow2.png", glm::vec2{0.2f, 0.15f} ), std::make_shared<odb::GraphicNode>( "hand1.png", glm::vec2{0.3f, 0.8f} ), std::make_shared<odb::GraphicNode>( "hand0.png", glm::vec2(0.55f, 1.0f) , glm::vec2{0.55f, 0.65f} ), std::make_shared<odb::GraphicNode>( "dart0.png", glm::vec2(0.55f, 1.0f), glm::vec2{0.55f, 0.65f} ) }, 500 }, {{ std::make_shared<odb::GraphicNode>( "bow2.png", glm::vec2{0.2f, 0.15f} ), std::make_shared<odb::GraphicNode>( "hand1.png", glm::vec2{0.3f, 0.8f} ), std::make_shared<odb::GraphicNode>( "hand0.png", glm::vec2{0.45f, 0.65f} ), std::make_shared<odb::GraphicNode>( "dart0.png", glm::vec2{0.45f, 0.65f} ) }, 2000 }, {{ std::make_shared<odb::GraphicNode>( "bow2.png", glm::vec2{0.1f, 0.3f} ), std::make_shared<odb::GraphicNode>( "hand1.png", glm::vec2{0.2f, 0.95f} ), std::make_shared<odb::GraphicNode>( "dart0.png", glm::vec2{0.35f, 0.8f} ), std::make_shared<odb::GraphicNode>( "hand0.png", glm::vec2(0.55f, 0.8f), glm::vec2( 0.5f, 1.0f ) ), }, 1000 }, {{ std::make_shared<odb::GraphicNode>( "bow2.png", glm::vec2{0.1f, 0.3f}, glm::vec2( 0.1f, 1.0f ) ), std::make_shared<odb::GraphicNode>( "hand1.png", glm::vec2{0.2f, 0.95f}, glm::vec2( 0.2f, 1.65f ) ), std::make_shared<odb::GraphicNode>( "dart0.png", glm::vec2{0.35f, 0.8f}, glm::vec2( 0.35f, 1.5f ) ) }, 1000 }, {{ std::make_shared<odb::GraphicNode>( "bow0.png", glm::vec2{0.35f, 1.0f}, glm::vec2{0.45f, 0.8f} ), }, 500 }, {{ std::make_shared<odb::GraphicNode>( "bow0.png", glm::vec2{0.45f, 0.8f}, glm::vec2{0.5125f, 0.85f} ), }, 500 }, }, false, "crossbow-still" ); currentAnimation = nullptr; } void OverlayNanoVGRenderer::render(const odb::NoudarDungeonSnapshot &snapshot) { if (mFontData.size() > 0) { #ifdef NANOVG_GLES2_IMPLEMENTATION mContext = nvgCreateGLES2(NVG_STENCIL_STROKES); #else mContext = nvgCreateGL2(NVG_ANTIALIAS | NVG_STENCIL_STROKES ); #endif if (!mContext) { std::cout << "NVG context is faulty as salty" << std::endl; } unsigned char *data = (unsigned char *) malloc(mFontData.size()); std::copy(mFontData.begin(), mFontData.end(), data); nvgCreateFontMem(mContext, "font", data, mFontData.size(), 1); mFontData.clear(); } if (mFrames.empty()) { for (const auto &bitmapPair : mBitmaps) { auto bitmap = bitmapPair.second; int imgW = bitmap->getWidth(); int imgH = bitmap->getHeight(); mFrames[bitmapPair.first] = nvgCreateImageRGBA(mContext, imgW, imgH, 0, (const unsigned char *) bitmap->getPixelData()); } } glViewport(0, 0, mWidth, mHeight); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_DEPTH_TEST); nvgBeginFrame(mContext, mWidth, mHeight, mWidth / mHeight); nvgFontSize(mContext, 18.0f); nvgFontFace(mContext, "font"); nvgFillColor(mContext, nvgRGBA(255, 255, 255, 255)); nvgStrokeColor(mContext, nvgRGBA(255, 0, 0, 255)); nvgTextAlign(mContext, NVG_ALIGN_LEFT | NVG_ALIGN_MIDDLE); nvgText(mContext, 10, 10, snapshot.mCurrentItem.c_str(), nullptr); std::stringstream ss; ss << snapshot.mHP; nvgText(mContext, 10, mHeight - 18, ss.str().c_str(), nullptr); timeUntilNextFrame -= (snapshot.mTimestamp - mLastTimestamp); mLastTimestamp = snapshot.mTimestamp; if ( currentAnimation != nullptr ) { auto animationSize = currentAnimation->mStepList.size(); if (timeUntilNextFrame <= 0 && frame < animationSize) { if (currentAnimation->mRepeatedPlayback) { frame = (frame + 1) % currentAnimation->mStepList.size(); } else if (frame < animationSize - 1) { ++frame; } else { playAnimation( snapshot.mTimestamp, currentAnimation->mNextAnimation ); } timeUntilNextFrame = currentAnimation->mStepList[frame].mDelay; } for (const auto &node : currentAnimation->mStepList[frame].mNodes) { auto nodeId = node->mFrameId; auto registeredTexture = mFrames[node->mFrameId]; auto bitmap = mBitmaps[node->mFrameId]; int imgW = ( bitmap->getWidth() * mWidth ) / 640; int imgH = ( bitmap->getHeight() * mHeight ) / 480; auto position = node->getPositionForTime( 1.0f - ((float) timeUntilNextFrame ) / ( (float) currentAnimation->mStepList[frame].mDelay ) ); float offsetX = position.x * mWidth; float offsetY = position.y * mHeight; auto imgPaint = nvgImagePattern(mContext, offsetX, offsetY, imgW, imgH, 0, registeredTexture, 1.0f); nvgBeginPath(mContext); nvgRect(mContext, offsetX, offsetY, imgW, imgH); nvgFillPaint(mContext, imgPaint); nvgFill(mContext); } } nvgEndFrame(mContext); glDisable(GL_BLEND); glEnable(GL_DEPTH_TEST); } OverlayNanoVGRenderer::~OverlayNanoVGRenderer() { nvgDeleteGLES2(mContext); } void OverlayNanoVGRenderer::playAnimation( long currentTimestamp, std::string animationName ) { currentAnimation = animations[ animationName ]; if ( currentAnimation != nullptr ) { mLastTimestamp = currentTimestamp; timeUntilNextFrame = currentAnimation->mStepList[frame].mDelay; frame = 0; } } } <|endoftext|>
<commit_before>/** * @file */ #pragma once #include "bi/primitive/possibly.hpp" #include <cstdlib> #include <vector> #include <set> #include <list> namespace bi { /** * Partially ordered set. * * @tparam T Value type. * @tparam Compare Comparison functor. */ template<class T, class Compare> class poset { public: /** * Constructor. */ poset(); /** * Number of values in the poset. */ size_t size() const; /** * Does the set contain a given value? */ bool contains(T& value); /** * Get a given value. */ T get(T& value); /** * Find the most-specific definite match(es) as well as more-specific * possible matche(es). * * @tparam Comparable Type comparable to value type. * @tparam Container Container type with push_back() function. * * @param value The value. * @param[out] definites Container to hold most-specific definite * match(es). * @param[out] possibles Container to hold more-specific possible * match(es). */ template<class Comparable, class Container> void match(const Comparable& value, Container& definites, Container& possibles); /** * Insert vertex. * * @param value Value at the vertex. * * If the value equals that of another vertex, under the partial order * given, that vertex is overwritten. */ void insert(T& value); /** * Output dot graph. Useful for diagnostic purposes. */ void dot(); private: typedef std::set<int> set_type; /** * Add vertex. * * @param value Value at the vertex. * * @return Index of the vertex. */ int add_vertex(const T& value); /** * Add edge. * * @param u Source vertex index. * @param v Destination vertex index. */ void add_edge(const int u, const int v); /** * Remove edge. * * @param u Source vertex index. * @param v Destination vertex index. */ void remove_edge(const int y, const int v); /** * Sub-operation for match to find most-specific definite match. * * @return True if a definite match was made in the subgraph. */ template<class Comparable, class Container> bool match_definites(const int u, const Comparable& value, Container& definites); /** * Sub-operation for match to find most-specific definite match. */ template<class Comparable, class Container> void match_possibles(const int u, const Comparable& value, Container& possibles); /* * Sub-operations for insert. */ void forward(const int v); void forward(const int u, const int v); void backward(const int v); void backward(const int u, const int v); void reduce(); // transitive reduction void reduce(const int u); /* * Sub-operations for dot. */ void dot(const int u); /** * Vertex values. */ std::vector<T> values; /** * Vertex colours. */ std::vector<int> colours; /** * Forward and backward edges. */ std::vector<set_type> forwards, backwards; /** * Roots and leaves. */ set_type roots, leaves; /** * Comparison. */ Compare compare; /** * Current colour. */ int colour; }; } #include <iostream> #include <cassert> template<class T, class Compare> bi::poset<T,Compare>::poset() : colour(0) { // } template<class T, class Compare> size_t bi::poset<T,Compare>::size() const { return values.size(); } template<class T, class Compare> bool bi::poset<T,Compare>::contains(T& value) { std::list<T> definites, possibles; match(value, definites, possibles); return definites.size() == 1 && compare(definites.front(), value) == definite && compare(value, definites.front()) == definite; } template<class T, class Compare> T bi::poset<T,Compare>::get(T& value) { /* pre-condition */ assert(contains(value)); std::list<T> definites, possibles; match(value, definites, possibles); return definites.front(); } template<class T, class Compare> template<class Comparable, class Container> void bi::poset<T,Compare>::match(const Comparable& value, Container& definites, Container& possibles) { ++colour; for (auto iter = roots.begin(); iter != roots.end(); ++iter) { match_definites(*iter, value, definites); } ++colour; for (auto iter = roots.begin(); iter != roots.end(); ++iter) { match_possibles(*iter, value, possibles); } } template<class T, class Compare> void bi::poset<T,Compare>::insert(T& value) { /* pre-condition */ assert(!contains(value)); const int v = add_vertex(value); forward(v); backward(v); reduce(); } template<class T, class Compare> int bi::poset<T,Compare>::add_vertex(const T& value) { const int v = values.size(); values.push_back(value); forwards.push_back(set_type()); backwards.push_back(set_type()); colours.push_back(colour); roots.insert(v); leaves.insert(v); /* post-condition */ assert(values.size() == forwards.size()); assert(values.size() == backwards.size()); assert(values.size() == colours.size()); return v; } template<class T, class Compare> void bi::poset<T,Compare>::add_edge(const int u, const int v) { if (u != v) { forwards[u].insert(v); backwards[v].insert(u); leaves.erase(u); roots.erase(v); } } template<class T, class Compare> void bi::poset<T,Compare>::remove_edge(const int u, const int v) { forwards[u].erase(v); backwards[v].erase(u); if (forwards[u].size() == 0) { leaves.insert(u); } if (backwards[v].size() == 0) { roots.insert(v); } } template<class T, class Compare> template<class Comparable, class Container> bool bi::poset<T,Compare>::match_definites(const int u, const Comparable& value, Container& definites) { bool deeper = false; if (colours[u] < colour) { /* not visited yet */ colours[u] = colour; if (compare(value, values[u]) == definite) { /* this vertex matcher, check if any vertices in the subgraph match * more-specifically */ for (auto iter = forwards[u].begin(); iter != forwards[u].end(); ++iter) { deeper = deeper || match_definites(*iter, value, definites); } if (!deeper) { /* no more-specific matches in the subgraph beneath this vertex, so * this is the most-specific match */ definites.push_back(values[u]); deeper = true; } } } return deeper; } template<class T, class Compare> template<class Comparable, class Container> void bi::poset<T,Compare>::match_possibles(const int u, const Comparable& value, Container& possibles) { if (colours[u] < colour) { /* not visited yet */ colours[u] = colour; possibly result = compare(value, values[u]); if (result != untrue) { /* either a definite or possible match, so continue searching through * the subgraph */ for (auto iter = forwards[u].begin(); iter != forwards[u].end(); ++iter) { match_possibles(*iter, value, possibles); } } if (result == possible) { /* if this was a possible (but not a definite) match, insert it in the * output; note this is done after searching the subgraph, so that * more-specific possible matches appear early in the output */ possibles.push_back(values[u]); } } } template<class T, class Compare> void bi::poset<T,Compare>::forward(const int v) { ++colour; auto roots1 = roots; // local copy as may be modified during iteration auto iter = roots1.begin(); while (iter != roots1.end()) { if (*iter != v) { forward(*iter, v); } ++iter; } } template<class T, class Compare> void bi::poset<T,Compare>::forward(const int u, const int v) { if (colours[u] < colour) { colours[u] = colour; if (compare(values[u], values[v]) == definite) { add_edge(v, u); } else { auto iter = forwards[u].begin(); while (iter != forwards[u].end()) { forward(*iter, v); ++iter; } } } } template<class T, class Compare> void bi::poset<T,Compare>::backward(const int v) { ++colour; auto leaves1 = leaves; // local copy as may be modified during iteration auto iter = leaves1.begin(); while (iter != leaves1.end()) { if (*iter != v) { backward(*iter, v); } ++iter; } } template<class T, class Compare> void bi::poset<T,Compare>::backward(const int u, const int v) { if (colours[u] < colour) { colours[u] = colour; if (compare(values[v], values[u]) == definite) { add_edge(u, v); } else { auto iter = backwards[u].begin(); while (iter != backwards[u].end()) { backward(*iter, v); ++iter; } } } } template<class T, class Compare> void bi::poset<T,Compare>::reduce() { set_type lroots(roots); // local copy as may change auto iter = lroots.begin(); while (iter != lroots.end()) { reduce(*iter); ++iter; } } template<class T, class Compare> void bi::poset<T,Compare>::reduce(const int u) { int lcolour = ++colour; set_type lforwards(forwards[u]); /* depth first search discovery */ auto iter = lforwards.begin(); while (iter != lforwards.end()) { if (colours[*iter] < lcolour) { colours[*iter] = lcolour; } reduce(*iter); ++iter; } /* remove edges for children that were rediscovered */ iter = lforwards.begin(); while (iter != lforwards.end()) { if (colours[*iter] > lcolour) { // rediscovered remove_edge(u, *iter); } ++iter; } } template<class T, class Compare> void bi::poset<T,Compare>::dot() { ++colour; std::cout << "digraph {" << std::endl; auto iter = roots.begin(); while (iter != roots.end()) { dot(*iter); ++iter; } std::cout << "}" << std::endl; } template<class T, class Compare> void bi::poset<T,Compare>::dot(const int u) { if (colours[u] != colour) { colours[u] = colour; std::cout << "\"" << values[u] << "\"" << std::endl; auto iter = forwards[u].begin(); while (iter != forwards[u].end()) { std::cout << "\"" << values[u] << "\" -> \"" << values[*iter] << "\"" << std::endl; dot(*iter); ++iter; } } } <commit_msg>Updated poset with multimap implementation, will improve interface for multiple dispatch requirements.<commit_after>/** * @file */ #pragma once #include "bi/primitive/possibly.hpp" #include <cstdlib> #include <set> #include <map> #include <list> namespace bi { /** * Partially ordered set. * * @tparam T Value type. * @tparam Compare Comparison functor. */ template<class T, class Compare> class poset { public: /** * Constructor. */ poset(); /** * Does the set contain an equivalent value? */ bool contains(T v); /** * Get the equivalent value. */ T get(T v); /** * Find the most-specific definite match(es) as well as more-specific * possible matche(es). * * @tparam Comparable Type comparable to value type. * @tparam Container Container type with push_back() function. * * @param v The value. * @param[out] definites Container to hold most-specific definite * match(es). * @param[out] possibles Container to hold more-specific possible * match(es). */ template<class Comparable, class Container> void match(Comparable v, Container& definites, Container& possibles); /** * Insert vertex. * * @param v Value at the vertex. */ void insert(T v); /** * Output dot graph. Useful for diagnostic purposes. */ void dot(); private: /** * Add vertex. * * @param v Value at the vertex. */ void add_vertex(T v); /** * Add edge. * * @param u Source vertex index. * @param v Destination vertex index. */ void add_edge(T u, T v); /** * Remove edge. * * @param u Source vertex index. * @param v Destination vertex index. */ void remove_edge(T u, T v); /** * Sub-operation for match to find most-specific definite match. * * @return True if a definite match was made in the subgraph. */ template<class Comparable, class Container> bool match_definites(T u, Comparable v, Container& definites); /** * Sub-operation for match to find most-specific definite match. */ template<class Comparable, class Container> bool match_possibles(T u, Comparable v, Container& possibles); /* * Sub-operations for insert. */ void forward(T v); void forward(T u, T v); void backward(T v); void backward(T u, T v); void reduce(); // transitive reduction void reduce(T u); /* * Sub-operations for dot(). */ void dot(T u); /** * Vertex colours. */ std::map<T,int> colours; /** * Forward and backward edges. */ std::multimap<T,T> forwards, backwards; /** * Roots and leaves. */ std::set<T> roots, leaves; /** * Comparison operator. */ Compare compare; /** * Current colour. */ int colour; }; } #include <iostream> #include <cassert> template<class T, class Compare> bi::poset<T,Compare>::poset() : colour(0) { // } template<class T, class Compare> bool bi::poset<T,Compare>::contains(T v) { std::list<T> definites, possibles; match(v, definites, possibles); return definites.size() == 1 && definites.front() <= v && v <= definites.front(); } template<class T, class Compare> T bi::poset<T,Compare>::get(T v) { /* pre-condition */ assert(contains(v)); std::list<T> definites, possibles; match(v, definites, possibles); return definites.front(); } template<class T, class Compare> template<class Comparable, class Container> void bi::poset<T,Compare>::match(Comparable v, Container& definites, Container& possibles) { ++colour; for (auto iter = roots.begin(); iter != roots.end(); ++iter) { match_definites(*iter, v, definites); } ++colour; for (auto iter = roots.begin(); iter != roots.end(); ++iter) { match_possibles(*iter, v, possibles); } } template<class T, class Compare> void bi::poset<T,Compare>::insert(T v) { add_vertex(v); forward(v); backward(v); reduce(); } template<class T, class Compare> void bi::poset<T,Compare>::add_vertex(T v) { /* pre-condition */ assert(!contains(v)); colours.insert(std::make_pair(v, colour)); roots.insert(v); leaves.insert(v); } template<class T, class Compare> void bi::poset<T,Compare>::add_edge(T u, T v) { /* pre-condition */ assert(u != v); forwards.insert(std::make_pair(u, v)); backwards.insert(std::make_pair(v, u)); leaves.erase(u); roots.erase(v); } template<class T, class Compare> void bi::poset<T,Compare>::remove_edge(T u, T v) { /* remove forward edge */ auto range1 = forwards.equal_range(u); bool found1 = false; for (auto iter1 = range1.first; !found1 && iter1 != range1.second; ++iter1) { if (iter1->second == v) { forwards.erase(iter1); found1 = true; } } /* remove backward edge */ auto range2 = backwards.equal_range(v); bool found2 = false; for (auto iter2 = range2.first; !found2 && iter2 != range2.second; ++iter2) { if (iter2->second == u) { backwards.erase(iter2); found2 = true; } } /* update roots and leaves if necessary */ if (forwards.count(u) == 0) { leaves.insert(u); } if (backwards.count(v) == 0) { roots.insert(v); } } template<class T, class Compare> template<class Comparable, class Container> bool bi::poset<T,Compare>::match_definites(T u, Comparable v, Container& definites) { bool deeper = false; if (colours[u] < colour) { /* not visited yet */ colours[u] = colour; if (compare(v, u) == definite) { /* this vertex matches, check if any vertices in the subgraph match * more-specifically */ auto range = forwards.equal_range(u); for (auto iter = range.first; iter != range.second; ++iter) { deeper = match_definites(iter->second, v, definites) || deeper; // ^ do the || in this order to prevent short circuit } if (!deeper) { /* no more-specific matches in the subgraph beneath this vertex, so * this is the most-specific match */ definites.push_back(u); deeper = true; } } } return deeper; } template<class T, class Compare> template<class Comparable, class Container> bool bi::poset<T,Compare>::match_possibles(T u, Comparable v, Container& possibles) { bool deeper = false; if (colours[u] < colour) { /* not visited yet */ colours[u] = colour; if (compare(v, u) != untrue) { /* this vertex matcher, check if any vertices in the subgraph match * more-specifically */ auto range = forwards.equal_range(u); for (auto iter = range.first; iter != range.second; ++iter) { deeper = match_possibles(iter->second, v, possibles) || deeper; // ^ do the || in this order to prevent short circuit } if (!deeper) { /* no more-specific matches in the subgraph beneath this vertex, so * this is the most-specific match */ possibles.push_back(u); deeper = true; } } } return deeper; } template<class T, class Compare> void bi::poset<T,Compare>::forward(T v) { ++colour; auto roots1 = roots; // local copy as may be modified during iteration for (auto iter = roots1.begin(); iter != roots1.end(); ++iter) { if (*iter != v) { forward(*iter, v); } } } template<class T, class Compare> void bi::poset<T,Compare>::forward(T u, T v) { if (colours[u] < colour) { colours[u] = colour; if (compare(u, v) == definite) { add_edge(v, u); } else { /* local copy of forward edges, as may change */ std::list<T> forwards1; auto range = forwards.equal_range(u); for (auto iter = range.first; iter != range.second; ++iter) { forwards1.push_back(iter->second); } for (auto iter = forwards1.begin(); iter != forwards1.end(); ++iter) { forward(*iter, v); } } } } template<class T, class Compare> void bi::poset<T,Compare>::backward(T v) { ++colour; auto leaves1 = leaves; // local copy as may be modified during iteration for (auto iter = leaves1.begin(); iter != leaves1.end(); ++iter) { if (*iter != v) { backward(*iter, v); } } } template<class T, class Compare> void bi::poset<T,Compare>::backward(T u, T v) { if (colours[u] < colour) { colours[u] = colour; if (compare(v, u) == definite) { add_edge(u, v); } else { /* local copy of backward edges, as may change */ std::list<T> backwards1; auto range = backwards.equal_range(u); for (auto iter = range.first; iter != range.second; ++iter) { backwards1.push_back(iter->second); } for (auto iter = backwards1.begin(); iter != backwards1.end(); ++iter) { backward(*iter, v); } } } } template<class T, class Compare> void bi::poset<T,Compare>::reduce() { auto roots1 = roots; // local copy as may change for (auto iter = roots1.begin(); iter != roots1.end(); ++iter) { reduce(*iter); } } template<class T, class Compare> void bi::poset<T,Compare>::reduce(T u) { int colour1 = ++colour; /* local copy of forward edges, as may change */ std::list<T> forwards1; auto range = forwards.equal_range(u); for (auto iter = range.first; iter != range.second; ++iter) { forwards1.push_back(iter->second); } /* depth first search discovery */ for (auto iter = forwards1.begin(); iter != forwards1.end(); ++iter) { if (colours[*iter] < colour1) { colours[*iter] = colour1; } reduce(*iter); } /* remove edges for children that were rediscovered */ for (auto iter = forwards1.begin(); iter != forwards1.end(); ++iter) { if (colours[*iter] > colour1) { // rediscovered remove_edge(u, *iter); } } } template<class T, class Compare> void bi::poset<T,Compare>::dot() { ++colour; std::cout << "digraph {" << std::endl; auto iter = roots.begin(); while (iter != roots.end()) { dot(*iter); ++iter; } std::cout << "}" << std::endl; } template<class T, class Compare> void bi::poset<T,Compare>::dot(T u) { if (colours[u] != colour) { colours[u] = colour; std::cout << "\"" << u << "\"" << std::endl; auto range = forwards.equal_range(u); for (auto iter = range.first; iter != range.second; ++iter) { std::cout << "\"" << u << "\" -> \"" << *iter << "\"" << std::endl; dot(*iter); ++iter; } } } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef __sitkImageRegistrationMethod_CreateParametersAdaptor_hxx #define __sitkImageRegistrationMethod_CreateParametersAdaptor_hxx #include "sitkImageRegistrationMethod.h" #include "itkShrinkImageFilter.h" #include "itkDisplacementFieldTransform.h" #include "itkDisplacementFieldTransformParametersAdaptor.h" namespace itk { namespace simple { template<typename TTransformBase, typename TFixedImageType> typename TransformParametersAdaptorBase<TTransformBase>::Pointer CreateTransformParametersAdaptorDisplacementField(TTransformBase *transform, const FixedArray<unsigned int, TTransformBase::InputSpaceDimension> &shrinkFactors, const TFixedImageType* , unsigned int level ) { typedef TFixedImageType FixedImageType; const unsigned int Dimension = FixedImageType::ImageDimension; typedef itk::DisplacementFieldTransform<double, Dimension> DisplacementFieldTransformType; typedef typename DisplacementFieldTransformType::DisplacementFieldType DisplacementFieldType; DisplacementFieldTransformType *displacementFieldTransform = dynamic_cast<DisplacementFieldTransformType*>(transform); if (!displacementFieldTransform) { return SITK_NULLPTR; } DisplacementFieldType * displacementField = displacementFieldTransform->GetDisplacementField(); // We use the shrink image filter to calculate the fixed parameters of the virtual // domain at each level. To speed up calculation and avoid unnecessary memory // usage, we could calculate these fixed parameters directly. typedef itk::ShrinkImageFilter<DisplacementFieldType, DisplacementFieldType> ShrinkFilterType; typename ShrinkFilterType::Pointer shrinkFilter = ShrinkFilterType::New(); shrinkFilter->SetShrinkFactors( shrinkFactors ); shrinkFilter->SetInput( displacementField ); shrinkFilter->UpdateOutputInformation(); typename DisplacementFieldType::Pointer shrinkOutput = shrinkFilter->GetOutput(); typedef DisplacementFieldTransformParametersAdaptor<DisplacementFieldTransformType> DisplacementFieldTransformAdaptorType; typename DisplacementFieldTransformAdaptorType::Pointer fieldTransformAdaptor = DisplacementFieldTransformAdaptorType::New(); fieldTransformAdaptor->SetRequiredSpacing( shrinkOutput->GetSpacing() ); fieldTransformAdaptor->SetRequiredSize( shrinkOutput->GetLargestPossibleRegion().GetSize() ); fieldTransformAdaptor->SetRequiredDirection( shrinkOutput->GetDirection() ); fieldTransformAdaptor->SetRequiredOrigin( shrinkOutput->GetOrigin() ); return fieldTransformAdaptor.GetPointer(); } template<typename TTransformAdaptorPointer, typename TRegistrationMethod > std::vector< TTransformAdaptorPointer > ImageRegistrationMethod::CreateTransformParametersAdaptor(TRegistrationMethod* method) { typedef std::vector< TTransformAdaptorPointer > TransformParametersAdaptorsContainerType; typedef typename TRegistrationMethod::FixedImageType FixedImageType; typedef typename TRegistrationMethod::InitialTransformType TransformType; typedef typename TRegistrationMethod::TransformParametersAdaptorPointer TransformParametersAdaptorTypePointer; TransformType *transform = const_cast<TransformType *>(method->GetInitialTransform()); TransformParametersAdaptorsContainerType adaptors; const unsigned int numberOfLevels = method->GetNumberOfLevels(); const FixedImageType *fixedImage = method->GetFixedImage(); typedef itk::DisplacementFieldTransform<double, FixedImageType::ImageDimension> DisplacementFieldTransformType; const bool isDisplacementField = (dynamic_cast<DisplacementFieldTransformType *>(transform) != SITK_NULLPTR); for( unsigned int level = 0; level < numberOfLevels; ++level ) { const typename TRegistrationMethod::ShrinkFactorsPerDimensionContainerType &shrinkFactors = method->GetShrinkFactorsPerDimension(level); TransformParametersAdaptorTypePointer adaptor = SITK_NULLPTR; if (isDisplacementField) { adaptor = CreateTransformParametersAdaptorDisplacementField( transform, shrinkFactors, fixedImage, level ); } adaptors.push_back( adaptor.GetPointer() ); } return adaptors; } } } #endif // __sitkImageRegistrationMethod_CreateParametersAdaptor_hxx <commit_msg>Fix warning unused parameter warning<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef __sitkImageRegistrationMethod_CreateParametersAdaptor_hxx #define __sitkImageRegistrationMethod_CreateParametersAdaptor_hxx #include "sitkImageRegistrationMethod.h" #include "itkShrinkImageFilter.h" #include "itkDisplacementFieldTransform.h" #include "itkDisplacementFieldTransformParametersAdaptor.h" namespace itk { namespace simple { template<typename TTransformBase, typename TFixedImageType> typename TransformParametersAdaptorBase<TTransformBase>::Pointer CreateTransformParametersAdaptorDisplacementField(TTransformBase *transform, const FixedArray<unsigned int, TTransformBase::InputSpaceDimension> &shrinkFactors, const TFixedImageType* fixedImage, unsigned int level ) { Unused(level); Unused(fixedImage); typedef TFixedImageType FixedImageType; const unsigned int Dimension = FixedImageType::ImageDimension; typedef itk::DisplacementFieldTransform<double, Dimension> DisplacementFieldTransformType; typedef typename DisplacementFieldTransformType::DisplacementFieldType DisplacementFieldType; DisplacementFieldTransformType *displacementFieldTransform = dynamic_cast<DisplacementFieldTransformType*>(transform); if (!displacementFieldTransform) { return SITK_NULLPTR; } DisplacementFieldType * displacementField = displacementFieldTransform->GetDisplacementField(); // We use the shrink image filter to calculate the fixed parameters of the virtual // domain at each level. To speed up calculation and avoid unnecessary memory // usage, we could calculate these fixed parameters directly. typedef itk::ShrinkImageFilter<DisplacementFieldType, DisplacementFieldType> ShrinkFilterType; typename ShrinkFilterType::Pointer shrinkFilter = ShrinkFilterType::New(); shrinkFilter->SetShrinkFactors( shrinkFactors ); shrinkFilter->SetInput( displacementField ); shrinkFilter->UpdateOutputInformation(); typename DisplacementFieldType::Pointer shrinkOutput = shrinkFilter->GetOutput(); typedef DisplacementFieldTransformParametersAdaptor<DisplacementFieldTransformType> DisplacementFieldTransformAdaptorType; typename DisplacementFieldTransformAdaptorType::Pointer fieldTransformAdaptor = DisplacementFieldTransformAdaptorType::New(); fieldTransformAdaptor->SetRequiredSpacing( shrinkOutput->GetSpacing() ); fieldTransformAdaptor->SetRequiredSize( shrinkOutput->GetLargestPossibleRegion().GetSize() ); fieldTransformAdaptor->SetRequiredDirection( shrinkOutput->GetDirection() ); fieldTransformAdaptor->SetRequiredOrigin( shrinkOutput->GetOrigin() ); return fieldTransformAdaptor.GetPointer(); } template<typename TTransformAdaptorPointer, typename TRegistrationMethod > std::vector< TTransformAdaptorPointer > ImageRegistrationMethod::CreateTransformParametersAdaptor(TRegistrationMethod* method) { typedef std::vector< TTransformAdaptorPointer > TransformParametersAdaptorsContainerType; typedef typename TRegistrationMethod::FixedImageType FixedImageType; typedef typename TRegistrationMethod::InitialTransformType TransformType; typedef typename TRegistrationMethod::TransformParametersAdaptorPointer TransformParametersAdaptorTypePointer; TransformType *transform = const_cast<TransformType *>(method->GetInitialTransform()); TransformParametersAdaptorsContainerType adaptors; const unsigned int numberOfLevels = method->GetNumberOfLevels(); const FixedImageType *fixedImage = method->GetFixedImage(); typedef itk::DisplacementFieldTransform<double, FixedImageType::ImageDimension> DisplacementFieldTransformType; const bool isDisplacementField = (dynamic_cast<DisplacementFieldTransformType *>(transform) != SITK_NULLPTR); for( unsigned int level = 0; level < numberOfLevels; ++level ) { const typename TRegistrationMethod::ShrinkFactorsPerDimensionContainerType &shrinkFactors = method->GetShrinkFactorsPerDimension(level); TransformParametersAdaptorTypePointer adaptor = SITK_NULLPTR; if (isDisplacementField) { adaptor = CreateTransformParametersAdaptorDisplacementField( transform, shrinkFactors, fixedImage, level ); } adaptors.push_back( adaptor.GetPointer() ); } return adaptors; } } } #endif // __sitkImageRegistrationMethod_CreateParametersAdaptor_hxx <|endoftext|>
<commit_before>//===-- FormatCache.cpp ------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // C Includes // C++ Includes // Other libraries and framework includes // Project includes #include "lldb/DataFormatters/FormatCache.h" using namespace lldb; using namespace lldb_private; FormatCache::Entry::Entry () : m_summary_cached(false), m_synthetic_cached(false), m_summary_sp(nullptr), m_synthetic_sp(nullptr) {} FormatCache::Entry::Entry (lldb::TypeSummaryImplSP summary_sp) : FormatCache::Entry() { SetSummary (summary_sp); } FormatCache::Entry::Entry (lldb::SyntheticChildrenSP synthetic_sp) : FormatCache::Entry() { SetSynthetic (synthetic_sp); } FormatCache::Entry::Entry (lldb::TypeSummaryImplSP summary_sp,lldb::SyntheticChildrenSP synthetic_sp) : FormatCache::Entry() { SetSummary (summary_sp); SetSynthetic (synthetic_sp); } bool FormatCache::Entry::IsSummaryCached () { return m_summary_cached; } bool FormatCache::Entry::IsSyntheticCached () { return m_synthetic_cached; } lldb::TypeSummaryImplSP FormatCache::Entry::GetSummary () { return m_summary_sp; } lldb::SyntheticChildrenSP FormatCache::Entry::GetSynthetic () { return m_synthetic_sp; } void FormatCache::Entry::SetSummary (lldb::TypeSummaryImplSP summary_sp) { m_summary_cached = true; m_summary_sp = summary_sp; } void FormatCache::Entry::SetSynthetic (lldb::SyntheticChildrenSP synthetic_sp) { m_synthetic_cached = true; m_synthetic_sp = synthetic_sp; } FormatCache::FormatCache () : m_map(), m_mutex (Mutex::eMutexTypeRecursive) #ifdef LLDB_CONFIGURATION_DEBUG ,m_cache_hits(0),m_cache_misses(0) #endif { } FormatCache::Entry& FormatCache::GetEntry (const ConstString& type) { auto i = m_map.find(type), e = m_map.end(); if (i != e) return i->second; m_map[type] = FormatCache::Entry(); return m_map[type]; } bool FormatCache::GetSummary (const ConstString& type,lldb::TypeSummaryImplSP& summary_sp) { Mutex::Locker lock(m_mutex); auto entry = GetEntry(type); if (entry.IsSummaryCached()) { #ifdef LLDB_CONFIGURATION_DEBUG m_cache_hits++; #endif summary_sp = entry.GetSummary(); return true; } #ifdef LLDB_CONFIGURATION_DEBUG m_cache_misses++; #endif summary_sp.reset(); return false; } bool FormatCache::GetSynthetic (const ConstString& type,lldb::SyntheticChildrenSP& synthetic_sp) { Mutex::Locker lock(m_mutex); auto entry = GetEntry(type); if (entry.IsSyntheticCached()) { #ifdef LLDB_CONFIGURATION_DEBUG m_cache_hits++; #endif synthetic_sp = entry.GetSynthetic(); return true; } #ifdef LLDB_CONFIGURATION_DEBUG m_cache_misses++; #endif synthetic_sp.reset(); return false; } void FormatCache::SetSummary (const ConstString& type,lldb::TypeSummaryImplSP& summary_sp) { Mutex::Locker lock(m_mutex); GetEntry(type).SetSummary(summary_sp); } void FormatCache::SetSynthetic (const ConstString& type,lldb::SyntheticChildrenSP& synthetic_sp) { Mutex::Locker lock(m_mutex); GetEntry(type).SetSynthetic(synthetic_sp); } void FormatCache::Clear () { Mutex::Locker lock(m_mutex); m_map.clear(); } <commit_msg>Fix build problems with libstdc++ 4.6/4.7 - remove nullptr from initialization of shared_ptrs<commit_after>//===-- FormatCache.cpp ------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // C Includes // C++ Includes // Other libraries and framework includes // Project includes #include "lldb/DataFormatters/FormatCache.h" using namespace lldb; using namespace lldb_private; FormatCache::Entry::Entry () : m_summary_cached(false), m_synthetic_cached(false), m_summary_sp(), m_synthetic_sp() {} FormatCache::Entry::Entry (lldb::TypeSummaryImplSP summary_sp) : FormatCache::Entry() { SetSummary (summary_sp); } FormatCache::Entry::Entry (lldb::SyntheticChildrenSP synthetic_sp) : FormatCache::Entry() { SetSynthetic (synthetic_sp); } FormatCache::Entry::Entry (lldb::TypeSummaryImplSP summary_sp,lldb::SyntheticChildrenSP synthetic_sp) : FormatCache::Entry() { SetSummary (summary_sp); SetSynthetic (synthetic_sp); } bool FormatCache::Entry::IsSummaryCached () { return m_summary_cached; } bool FormatCache::Entry::IsSyntheticCached () { return m_synthetic_cached; } lldb::TypeSummaryImplSP FormatCache::Entry::GetSummary () { return m_summary_sp; } lldb::SyntheticChildrenSP FormatCache::Entry::GetSynthetic () { return m_synthetic_sp; } void FormatCache::Entry::SetSummary (lldb::TypeSummaryImplSP summary_sp) { m_summary_cached = true; m_summary_sp = summary_sp; } void FormatCache::Entry::SetSynthetic (lldb::SyntheticChildrenSP synthetic_sp) { m_synthetic_cached = true; m_synthetic_sp = synthetic_sp; } FormatCache::FormatCache () : m_map(), m_mutex (Mutex::eMutexTypeRecursive) #ifdef LLDB_CONFIGURATION_DEBUG ,m_cache_hits(0),m_cache_misses(0) #endif { } FormatCache::Entry& FormatCache::GetEntry (const ConstString& type) { auto i = m_map.find(type), e = m_map.end(); if (i != e) return i->second; m_map[type] = FormatCache::Entry(); return m_map[type]; } bool FormatCache::GetSummary (const ConstString& type,lldb::TypeSummaryImplSP& summary_sp) { Mutex::Locker lock(m_mutex); auto entry = GetEntry(type); if (entry.IsSummaryCached()) { #ifdef LLDB_CONFIGURATION_DEBUG m_cache_hits++; #endif summary_sp = entry.GetSummary(); return true; } #ifdef LLDB_CONFIGURATION_DEBUG m_cache_misses++; #endif summary_sp.reset(); return false; } bool FormatCache::GetSynthetic (const ConstString& type,lldb::SyntheticChildrenSP& synthetic_sp) { Mutex::Locker lock(m_mutex); auto entry = GetEntry(type); if (entry.IsSyntheticCached()) { #ifdef LLDB_CONFIGURATION_DEBUG m_cache_hits++; #endif synthetic_sp = entry.GetSynthetic(); return true; } #ifdef LLDB_CONFIGURATION_DEBUG m_cache_misses++; #endif synthetic_sp.reset(); return false; } void FormatCache::SetSummary (const ConstString& type,lldb::TypeSummaryImplSP& summary_sp) { Mutex::Locker lock(m_mutex); GetEntry(type).SetSummary(summary_sp); } void FormatCache::SetSynthetic (const ConstString& type,lldb::SyntheticChildrenSP& synthetic_sp) { Mutex::Locker lock(m_mutex); GetEntry(type).SetSynthetic(synthetic_sp); } void FormatCache::Clear () { Mutex::Locker lock(m_mutex); m_map.clear(); } <|endoftext|>
<commit_before>#ifndef ITER_REVERSE_HPP_ #define ITER_REVERSE_HPP_ #include "iterbase.hpp" #include <utility> #include <iterator> namespace iter { template <typename Container> class Reverser; template <typename Container> Reverser<Container> reversed(Container&&); template <typename Container> class Reverser { private: Container container; friend Reverser reversed<Container>(Container&&); Reverser(Container&& in_container) : container(std::forward<Container>(in_container)) { } public: class Iterator : public std::iterator< std::input_iterator_tag, iterator_traits_deref<Container>> { private: reverse_iterator_type<Container> sub_iter; public: Iterator (reverse_iterator_type<Container>&& iter) : sub_iter{std::move(iter)} { } reverse_iterator_deref<Container> operator*() { return *this->sub_iter; } Iterator& operator++() { ++this->sub_iter; return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } bool operator!=(const Iterator& other) const { return this->sub_iter != other.sub_iter; } bool operator==(const Iterator& other) const { return !(*this != other); } }; Iterator begin() { return {this->container.rbegin()}; } Iterator end() { return {this->container.rend()}; } }; template <typename Container> Reverser<Container> reversed(Container&& container) { return {std::forward<Container>(container)}; } // // specialization for statically allocated arrays // template <typename T, std::size_t N> Reverser<T[N]> reversed(T (&)[N]); template <typename T, std::size_t N> class Reverser<T[N]> { private: T *array; friend Reverser reversed<T, N>(T (&)[N]); // Value constructor for use only in the reversed function Reverser(T *in_array) : array{in_array} { } public: Reverser(const Reverser&) = default; class Iterator : public std::iterator<std::input_iterator_tag, T> { private: T *sub_iter; public: Iterator (T *iter) : sub_iter{iter} { } iterator_deref<T[N]> operator*() { return *(this->sub_iter - 1); } Iterator& operator++() { --this->sub_iter; return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } bool operator!=(const Iterator& other) const { return this->sub_iter != other.sub_iter; } bool operator==(const Iterator& other) const { return !(*this != other); } }; Iterator begin() { return {this->array + N}; } Iterator end() { return {this->array}; } }; template <typename T, std::size_t N> Reverser<T[N]> reversed(T (&array)[N]) { return {array}; } } #endif <commit_msg>adds reversed iter -> and shortens array types<commit_after>#ifndef ITER_REVERSE_HPP_ #define ITER_REVERSE_HPP_ #include "iterbase.hpp" #include <utility> #include <iterator> namespace iter { template <typename Container> class Reverser; template <typename Container> Reverser<Container> reversed(Container&&); template <typename Container> class Reverser { private: Container container; friend Reverser reversed<Container>(Container&&); Reverser(Container&& in_container) : container(std::forward<Container>(in_container)) { } public: class Iterator : public std::iterator< std::input_iterator_tag, iterator_traits_deref<Container>> { private: reverse_iterator_type<Container> sub_iter; public: Iterator (reverse_iterator_type<Container>&& iter) : sub_iter{std::move(iter)} { } reverse_iterator_deref<Container> operator*() { return *this->sub_iter; } reverse_iterator_arrow<Container> operator->() { return apply_arrow(this->sub_iter); } Iterator& operator++() { ++this->sub_iter; return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } bool operator!=(const Iterator& other) const { return this->sub_iter != other.sub_iter; } bool operator==(const Iterator& other) const { return !(*this != other); } }; Iterator begin() { return {this->container.rbegin()}; } Iterator end() { return {this->container.rend()}; } }; template <typename Container> Reverser<Container> reversed(Container&& container) { return {std::forward<Container>(container)}; } // // specialization for statically allocated arrays // template <typename T, std::size_t N> Reverser<T[N]> reversed(T (&)[N]); template <typename T, std::size_t N> class Reverser<T[N]> { private: T *array; friend Reverser reversed<T, N>(T (&)[N]); // Value constructor for use only in the reversed function Reverser(T *in_array) : array{in_array} { } public: Reverser(const Reverser&) = default; class Iterator : public std::iterator<std::input_iterator_tag, T> { private: T *sub_iter; public: Iterator (T *iter) : sub_iter{iter} { } T& operator*() { return *(this->sub_iter - 1); } T *operator->() { return (this->sub_iter - 1); } Iterator& operator++() { --this->sub_iter; return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } bool operator!=(const Iterator& other) const { return this->sub_iter != other.sub_iter; } bool operator==(const Iterator& other) const { return !(*this != other); } }; Iterator begin() { return {this->array + N}; } Iterator end() { return {this->array}; } }; template <typename T, std::size_t N> Reverser<T[N]> reversed(T (&array)[N]) { return {array}; } } #endif <|endoftext|>
<commit_before>#include <ros/ros.h> #include <oculus_msgs/HMDInfo.h> #include <oculus_viewer/distort.h> #include <oculus_viewer/viewer.h> namespace oculus_viewer { class ImageDistortViewer { public: ImageDistortViewer(); void init(); void HMDInfoCallback(const oculus_msgs::HMDInfoPtr& info); void show(); private: DistortImage left_; DistortImage right_; ros::Subscriber sub_; bool use_display_; Viewer viewer_; }; ImageDistortViewer::ImageDistortViewer(): use_display_(true), viewer_("oculus camera view") { } void ImageDistortViewer::init() { ros::NodeHandle node; left_.init("camera/left/image_raw"); right_.init("camera/right/image_raw"); sub_ = node.subscribe("/oculus/hmd_info", 1, &ImageDistortViewer::HMDInfoCallback, this); ros::NodeHandle private_node("~"); int32_t offset_x = 0; private_node.param<int32_t>("display_offset_x", offset_x, 0); int32_t offset_y = 0; private_node.param<int32_t>("display_offset_y", offset_y, 0); viewer_.setDisplayOffset(offset_x, offset_y); private_node.param<bool>("use_display", use_display_, true); } void ImageDistortViewer::show() { if (use_display_) { if ((!right_.getImage().empty()) && (!left_.getImage().empty())) { viewer_.show(right_.getImage(), left_.getImage()); } } } void ImageDistortViewer::HMDInfoCallback(const oculus_msgs::HMDInfoPtr& info) { if (info->horizontal_screen_size > 0) { double lens_center = 1 - 2 * info->lens_separation_distance / info->horizontal_screen_size; double scale = 1 + lens_center; left_.setK(info->distortion_K); left_.setScale(scale); left_.setOffset(-lens_center); right_.setK(info->distortion_K); right_.setScale(scale); right_.setOffset(lens_center); } } } // namespace oculus_viewer int main(int argc, char** argv) { ros::init(argc, argv, "image_distort_viewer"); try { oculus_viewer::ImageDistortViewer dis; dis.init(); while(ros::ok()) { cv::waitKey(100); ros::spinOnce(); dis.show(); } } catch(ros::Exception& e) { ROS_ERROR("ros error: %s", e.what()); } catch(...) { ROS_FATAL("unexpected error"); } } <commit_msg>Made image channels configurable through parameters<commit_after>#include <ros/ros.h> #include <oculus_msgs/HMDInfo.h> #include <oculus_viewer/distort.h> #include <oculus_viewer/viewer.h> namespace oculus_viewer { class ImageDistortViewer { public: ImageDistortViewer(); void init(); void HMDInfoCallback(const oculus_msgs::HMDInfoPtr& info); void show(); private: DistortImage left_; DistortImage right_; ros::Subscriber sub_; bool use_display_; Viewer viewer_; }; ImageDistortViewer::ImageDistortViewer(): use_display_(true), viewer_("oculus camera view") { } void ImageDistortViewer::init() { ros::NodeHandle node; std::string left_img, right_img; // left_.init("camera/left/image_raw"); // right_.init("camera/right/image_raw"); // left_.init("camera/left/image_rect"); // right_.init("camera/right/image_rect"); sub_ = node.subscribe("/oculus/hmd_info", 1, &ImageDistortViewer::HMDInfoCallback, this); ros::NodeHandle private_node("~"); private_node.param<std::string>("left_image", left_img, "camera/left/image_raw"); private_node.param<std::string>("right_image", right_img, "camera/right/image_raw"); ROS_INFO("Left image topic: %s", left_img.c_str()); ROS_INFO("Right image topic: %s", right_img.c_str()); left_.init(left_img); right_.init(right_img); int32_t offset_x = 0; private_node.param<int32_t>("display_offset_x", offset_x, 0); int32_t offset_y = 0; private_node.param<int32_t>("display_offset_y", offset_y, 0); viewer_.setDisplayOffset(offset_x, offset_y); private_node.param<bool>("use_display", use_display_, true); } void ImageDistortViewer::show() { if (use_display_) { if ((!right_.getImage().empty()) && (!left_.getImage().empty())) { viewer_.show(right_.getImage(), left_.getImage()); } } } void ImageDistortViewer::HMDInfoCallback(const oculus_msgs::HMDInfoPtr& info) { if (info->horizontal_screen_size > 0) { double lens_center = 1 - 2 * info->lens_separation_distance / info->horizontal_screen_size; double scale = 1 + lens_center; left_.setK(info->distortion_K); left_.setScale(scale); left_.setOffset(-lens_center); right_.setK(info->distortion_K); right_.setScale(scale); right_.setOffset(lens_center); } } } // namespace oculus_viewer int main(int argc, char** argv) { ros::init(argc, argv, "image_distort_viewer"); try { oculus_viewer::ImageDistortViewer dis; dis.init(); while(ros::ok()) { cv::waitKey(100); ros::spinOnce(); dis.show(); } } catch(ros::Exception& e) { ROS_ERROR("ros error: %s", e.what()); } catch(...) { ROS_FATAL("unexpected error"); } } <|endoftext|>
<commit_before>/* * VHDL code generation for expressions. * * Copyright (C) 2008 Nick Gasson ([email protected]) * * 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. */ #include "vhdl_target.h" #include <iostream> #include <cassert> /* * Convert a constant Verilog string to a constant VHDL string. */ static vhdl_expr *translate_string(ivl_expr_t e) { // TODO: May need to inspect or escape parts of this const char *str = ivl_expr_string(e); return new vhdl_const_string(str); } /* * A reference to a signal in an expression. It's assumed that the * signal has already been defined elsewhere. */ static vhdl_var_ref *translate_signal(ivl_expr_t e) { ivl_signal_t sig = ivl_expr_signal(e); const vhdl_scope *scope = find_scope_for_signal(sig); assert(scope); const char *renamed = get_renamed_signal(sig).c_str(); const vhdl_decl *decl = scope->get_decl(strip_var(renamed)); assert(decl); vhdl_type *type = new vhdl_type(*decl->get_type()); return new vhdl_var_ref(renamed, type); } /* * A numeric literal ends up as std_logic bit string. */ static vhdl_expr *translate_number(ivl_expr_t e) { return new vhdl_const_bits(ivl_expr_bits(e), ivl_expr_width(e), ivl_expr_signed(e) != 0); } static vhdl_expr *translate_unary(ivl_expr_t e) { vhdl_expr *operand = translate_expr(ivl_expr_oper1(e)); if (NULL == operand) return NULL; bool should_be_signed = ivl_expr_signed(e) != 0; if (operand->get_type()->get_name() == VHDL_TYPE_UNSIGNED && should_be_signed) { //operand->print(); //std::cout << "^ should be signed but is not" << std::endl; int msb = operand->get_type()->get_msb(); int lsb = operand->get_type()->get_lsb(); vhdl_type u(VHDL_TYPE_SIGNED, msb, lsb); operand = operand->cast(&u); } else if (operand->get_type()->get_name() == VHDL_TYPE_SIGNED && !should_be_signed) { //operand->print(); //std::cout << "^ should be unsigned but is not" << std::endl; int msb = operand->get_type()->get_msb(); int lsb = operand->get_type()->get_lsb(); vhdl_type u(VHDL_TYPE_UNSIGNED, msb, lsb); operand = operand->cast(&u); } // Need to ensure that the operand is interpreted as unsigned to get VHDL // to emulate Verilog behaviour if (operand->get_type()->get_name() == VHDL_TYPE_SIGNED) { int msb = operand->get_type()->get_msb(); int lsb = operand->get_type()->get_lsb(); vhdl_type u(VHDL_TYPE_UNSIGNED, msb, lsb); operand = operand->cast(&u); } char opcode = ivl_expr_opcode(e); switch (opcode) { case '!': case '~': return new vhdl_unaryop_expr (VHDL_UNARYOP_NOT, operand, new vhdl_type(*operand->get_type())); case 'N': // NOR case '|': { vhdl_fcall *f = new vhdl_fcall("Reduce_OR", vhdl_type::std_logic()); f->add_expr(operand); if ('N' == opcode) return new vhdl_unaryop_expr(VHDL_UNARYOP_NOT, f, vhdl_type::std_logic()); else return f; } default: error("No translation for unary opcode '%c'\n", ivl_expr_opcode(e)); delete operand; return NULL; } } /* * Translate a numeric binary operator (+, -, etc.) to * a VHDL equivalent using the numeric_std package. */ static vhdl_expr *translate_numeric(vhdl_expr *lhs, vhdl_expr *rhs, vhdl_binop_t op) { // May need to make either side Boolean for operators // to work vhdl_type boolean(VHDL_TYPE_BOOLEAN); if (lhs->get_type()->get_name() == VHDL_TYPE_BOOLEAN) rhs = rhs->cast(&boolean); else if (rhs->get_type()->get_name() == VHDL_TYPE_BOOLEAN) lhs = lhs->cast(&boolean); vhdl_type *rtype = new vhdl_type(*lhs->get_type()); return new vhdl_binop_expr(lhs, op, rhs, rtype); } static vhdl_expr *translate_relation(vhdl_expr *lhs, vhdl_expr *rhs, vhdl_binop_t op) { // Generate any necessary casts // Arbitrarily, the RHS is casted to the type of the LHS vhdl_expr *r_cast = rhs->cast(lhs->get_type()); return new vhdl_binop_expr(lhs, op, r_cast, vhdl_type::boolean()); } /* * Like translate_relation but both operands must be Boolean. */ static vhdl_expr *translate_logical(vhdl_expr *lhs, vhdl_expr *rhs, vhdl_binop_t op) { vhdl_type boolean(VHDL_TYPE_BOOLEAN); return translate_relation(lhs->cast(&boolean), rhs->cast(&boolean), op); } static vhdl_expr *translate_shift(vhdl_expr *lhs, vhdl_expr *rhs, vhdl_binop_t op) { // The RHS must be an integer vhdl_type integer(VHDL_TYPE_INTEGER); vhdl_expr *r_cast = rhs->cast(&integer); vhdl_type *rtype = new vhdl_type(*lhs->get_type()); return new vhdl_binop_expr(lhs, op, r_cast, rtype); } static vhdl_expr *translate_binary(ivl_expr_t e) { vhdl_expr *lhs = translate_expr(ivl_expr_oper1(e)); if (NULL == lhs) return NULL; vhdl_expr *rhs = translate_expr(ivl_expr_oper2(e)); if (NULL == rhs) return NULL; int lwidth = lhs->get_type()->get_width(); int rwidth = rhs->get_type()->get_width(); int result_width = ivl_expr_width(e); // For === and !== we need to compare std_logic_vectors // rather than signeds vhdl_type std_logic_vector(VHDL_TYPE_STD_LOGIC_VECTOR, result_width-1, 0); vhdl_type_name_t ltype = lhs->get_type()->get_name(); vhdl_type_name_t rtype = rhs->get_type()->get_name(); bool vectorop = (ltype == VHDL_TYPE_SIGNED || ltype == VHDL_TYPE_UNSIGNED) && (rtype == VHDL_TYPE_SIGNED || rtype == VHDL_TYPE_UNSIGNED); // May need to resize the left or right hand side if (vectorop) { if (lwidth < rwidth) lhs = lhs->resize(rwidth); else if (rwidth < lwidth) rhs = rhs->resize(lwidth); } vhdl_expr *result; switch (ivl_expr_opcode(e)) { case '+': result = translate_numeric(lhs, rhs, VHDL_BINOP_ADD); break; case '-': result = translate_numeric(lhs, rhs, VHDL_BINOP_SUB); break; case '*': result = translate_numeric(lhs, rhs, VHDL_BINOP_MULT); break; case 'e': result = translate_relation(lhs, rhs, VHDL_BINOP_EQ); break; case 'E': if (vectorop) result = translate_relation(lhs->cast(&std_logic_vector), rhs->cast(&std_logic_vector), VHDL_BINOP_EQ); else result = translate_relation(lhs, rhs, VHDL_BINOP_EQ); break; case 'n': result = translate_relation(lhs, rhs, VHDL_BINOP_NEQ); break; case 'N': if (vectorop) result = translate_relation(lhs->cast(&std_logic_vector), rhs->cast(&std_logic_vector), VHDL_BINOP_NEQ); else result = translate_relation(lhs, rhs, VHDL_BINOP_NEQ); break; case '&': // Bitwise AND result = translate_numeric(lhs, rhs, VHDL_BINOP_AND); break; case 'a': // Logical AND result = translate_logical(lhs, rhs, VHDL_BINOP_AND); break; case '|': // Bitwise OR result = translate_numeric(lhs, rhs, VHDL_BINOP_OR); break; case 'o': // Logical OR result = translate_logical(lhs, rhs, VHDL_BINOP_OR); break; case '<': result = translate_relation(lhs, rhs, VHDL_BINOP_LT); break; case 'L': result = translate_relation(lhs, rhs, VHDL_BINOP_LEQ); break; case '>': result = translate_relation(lhs, rhs, VHDL_BINOP_GT); break; case 'G': result = translate_relation(lhs, rhs, VHDL_BINOP_GEQ); break; case 'l': result = translate_shift(lhs, rhs, VHDL_BINOP_SL); break; case 'r': result = translate_shift(lhs, rhs, VHDL_BINOP_SR); break; case '^': result = translate_numeric(lhs, rhs, VHDL_BINOP_XOR); break; default: error("No translation for binary opcode '%c'\n", ivl_expr_opcode(e)); delete lhs; delete rhs; return NULL; } if (NULL == result) return NULL; if (vectorop) { bool should_be_signed = ivl_expr_signed(e) != 0; if (result->get_type()->get_name() == VHDL_TYPE_UNSIGNED && should_be_signed) { //result->print(); //std::cout << "^ should be signed but is not" << std::endl; int msb = result->get_type()->get_msb(); int lsb = result->get_type()->get_lsb(); vhdl_type u(VHDL_TYPE_SIGNED, msb, lsb); result = result->cast(&u); } else if (result->get_type()->get_name() == VHDL_TYPE_SIGNED && !should_be_signed) { //result->print(); //std::cout << "^ should be unsigned but is not" << std::endl; int msb = result->get_type()->get_msb(); int lsb = result->get_type()->get_lsb(); vhdl_type u(VHDL_TYPE_SIGNED, msb, lsb); result = result->cast(&u); } int actual_width = result->get_type()->get_width(); if (actual_width != result_width) { //result->print(); //std::cout << "^ should be " << result_width << " but is " << actual_width << std::endl; } } return result; } static vhdl_expr *translate_select(ivl_expr_t e) { vhdl_var_ref *from = dynamic_cast<vhdl_var_ref*>(translate_expr(ivl_expr_oper1(e))); if (NULL == from) return NULL; ivl_expr_t o2 = ivl_expr_oper2(e); if (o2) { vhdl_expr *base = translate_expr(ivl_expr_oper2(e)); if (NULL == base) return NULL; vhdl_type integer(VHDL_TYPE_INTEGER); from->set_slice(base->cast(&integer), ivl_expr_width(e) - 1); return from; } else return from->resize(ivl_expr_width(e)); } static vhdl_type *expr_to_vhdl_type(ivl_expr_t e) { if (ivl_expr_signed(e)) return vhdl_type::nsigned(ivl_expr_width(e)); else return vhdl_type::nunsigned(ivl_expr_width(e)); } template <class T> static T *translate_parms(T *t, ivl_expr_t e) { int nparams = ivl_expr_parms(e); for (int i = 0; i < nparams; i++) { vhdl_expr *param = translate_expr(ivl_expr_parm(e, i)); if (NULL == param) return NULL; t->add_expr(param); } return t; } static vhdl_expr *translate_ufunc(ivl_expr_t e) { ivl_scope_t defscope = ivl_expr_def(e); ivl_scope_t parentscope = ivl_scope_parent(defscope); assert(ivl_scope_type(parentscope) == IVL_SCT_MODULE); // A function is always declared in a module, which should have // a corresponding entity by this point: so we can get type // information, etc. from the declaration vhdl_entity *parent_ent = find_entity(ivl_scope_tname(parentscope)); assert(parent_ent); const char *funcname = ivl_scope_tname(defscope); vhdl_type *rettype = expr_to_vhdl_type(e); vhdl_fcall *fcall = new vhdl_fcall(funcname, rettype); return translate_parms<vhdl_fcall>(fcall, e); } static vhdl_expr *translate_ternary(ivl_expr_t e) { error("Ternary expression only supported as RHS of assignment"); return NULL; } static vhdl_expr *translate_concat(ivl_expr_t e) { vhdl_type *rtype = expr_to_vhdl_type(e); vhdl_binop_expr *concat = new vhdl_binop_expr(VHDL_BINOP_CONCAT, rtype); return translate_parms<vhdl_binop_expr>(concat, e); } /* * Generate a VHDL expression from a Verilog expression. */ vhdl_expr *translate_expr(ivl_expr_t e) { assert(e); ivl_expr_type_t type = ivl_expr_type(e); switch (type) { case IVL_EX_STRING: return translate_string(e); case IVL_EX_SIGNAL: return translate_signal(e); case IVL_EX_NUMBER: return translate_number(e); case IVL_EX_UNARY: return translate_unary(e); case IVL_EX_BINARY: return translate_binary(e); case IVL_EX_SELECT: return translate_select(e); case IVL_EX_UFUNC: return translate_ufunc(e); case IVL_EX_TERNARY: return translate_ternary(e); case IVL_EX_CONCAT: return translate_concat(e); default: error("No VHDL translation for expression at %s:%d (type = %d)", ivl_expr_file(e), ivl_expr_lineno(e), type); return NULL; } } <commit_msg>Refactor signdness changing code into a single function<commit_after>/* * VHDL code generation for expressions. * * Copyright (C) 2008 Nick Gasson ([email protected]) * * 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. */ #include "vhdl_target.h" #include <iostream> #include <cassert> /* * Change the signdness of a vector. */ static vhdl_expr *change_signdness(vhdl_expr *e, bool issigned) { int msb = e->get_type()->get_msb(); int lsb = e->get_type()->get_lsb(); vhdl_type u(issigned ? VHDL_TYPE_SIGNED : VHDL_TYPE_UNSIGNED, msb, lsb); return e->cast(&u); } /* * Convert a constant Verilog string to a constant VHDL string. */ static vhdl_expr *translate_string(ivl_expr_t e) { // TODO: May need to inspect or escape parts of this const char *str = ivl_expr_string(e); return new vhdl_const_string(str); } /* * A reference to a signal in an expression. It's assumed that the * signal has already been defined elsewhere. */ static vhdl_var_ref *translate_signal(ivl_expr_t e) { ivl_signal_t sig = ivl_expr_signal(e); const vhdl_scope *scope = find_scope_for_signal(sig); assert(scope); const char *renamed = get_renamed_signal(sig).c_str(); const vhdl_decl *decl = scope->get_decl(strip_var(renamed)); assert(decl); vhdl_type *type = new vhdl_type(*decl->get_type()); return new vhdl_var_ref(renamed, type); } /* * A numeric literal ends up as std_logic bit string. */ static vhdl_expr *translate_number(ivl_expr_t e) { return new vhdl_const_bits(ivl_expr_bits(e), ivl_expr_width(e), ivl_expr_signed(e) != 0); } static vhdl_expr *translate_unary(ivl_expr_t e) { vhdl_expr *operand = translate_expr(ivl_expr_oper1(e)); if (NULL == operand) return NULL; bool should_be_signed = ivl_expr_signed(e) != 0; if (operand->get_type()->get_name() == VHDL_TYPE_UNSIGNED && should_be_signed) { //operand->print(); //std::cout << "^ should be signed but is not" << std::endl; operand = change_signdness(operand, true); } else if (operand->get_type()->get_name() == VHDL_TYPE_SIGNED && !should_be_signed) { //operand->print(); //std::cout << "^ should be unsigned but is not" << std::endl; operand = change_signdness(operand, false); } char opcode = ivl_expr_opcode(e); switch (opcode) { case '!': case '~': return new vhdl_unaryop_expr (VHDL_UNARYOP_NOT, operand, new vhdl_type(*operand->get_type())); case 'N': // NOR case '|': { vhdl_fcall *f = new vhdl_fcall("Reduce_OR", vhdl_type::std_logic()); f->add_expr(operand); if ('N' == opcode) return new vhdl_unaryop_expr(VHDL_UNARYOP_NOT, f, vhdl_type::std_logic()); else return f; } default: error("No translation for unary opcode '%c'\n", ivl_expr_opcode(e)); delete operand; return NULL; } } /* * Translate a numeric binary operator (+, -, etc.) to * a VHDL equivalent using the numeric_std package. */ static vhdl_expr *translate_numeric(vhdl_expr *lhs, vhdl_expr *rhs, vhdl_binop_t op) { // May need to make either side Boolean for operators // to work vhdl_type boolean(VHDL_TYPE_BOOLEAN); if (lhs->get_type()->get_name() == VHDL_TYPE_BOOLEAN) rhs = rhs->cast(&boolean); else if (rhs->get_type()->get_name() == VHDL_TYPE_BOOLEAN) lhs = lhs->cast(&boolean); vhdl_type *rtype = new vhdl_type(*lhs->get_type()); return new vhdl_binop_expr(lhs, op, rhs, rtype); } static vhdl_expr *translate_relation(vhdl_expr *lhs, vhdl_expr *rhs, vhdl_binop_t op) { // Generate any necessary casts // Arbitrarily, the RHS is casted to the type of the LHS vhdl_expr *r_cast = rhs->cast(lhs->get_type()); return new vhdl_binop_expr(lhs, op, r_cast, vhdl_type::boolean()); } /* * Like translate_relation but both operands must be Boolean. */ static vhdl_expr *translate_logical(vhdl_expr *lhs, vhdl_expr *rhs, vhdl_binop_t op) { vhdl_type boolean(VHDL_TYPE_BOOLEAN); return translate_relation(lhs->cast(&boolean), rhs->cast(&boolean), op); } static vhdl_expr *translate_shift(vhdl_expr *lhs, vhdl_expr *rhs, vhdl_binop_t op) { // The RHS must be an integer vhdl_type integer(VHDL_TYPE_INTEGER); vhdl_expr *r_cast = rhs->cast(&integer); vhdl_type *rtype = new vhdl_type(*lhs->get_type()); return new vhdl_binop_expr(lhs, op, r_cast, rtype); } static vhdl_expr *translate_binary(ivl_expr_t e) { vhdl_expr *lhs = translate_expr(ivl_expr_oper1(e)); if (NULL == lhs) return NULL; vhdl_expr *rhs = translate_expr(ivl_expr_oper2(e)); if (NULL == rhs) return NULL; int lwidth = lhs->get_type()->get_width(); int rwidth = rhs->get_type()->get_width(); int result_width = ivl_expr_width(e); // For === and !== we need to compare std_logic_vectors // rather than signeds vhdl_type std_logic_vector(VHDL_TYPE_STD_LOGIC_VECTOR, result_width-1, 0); vhdl_type_name_t ltype = lhs->get_type()->get_name(); vhdl_type_name_t rtype = rhs->get_type()->get_name(); bool vectorop = (ltype == VHDL_TYPE_SIGNED || ltype == VHDL_TYPE_UNSIGNED) && (rtype == VHDL_TYPE_SIGNED || rtype == VHDL_TYPE_UNSIGNED); // May need to resize the left or right hand side if (vectorop) { if (lwidth < rwidth) lhs = lhs->resize(rwidth); else if (rwidth < lwidth) rhs = rhs->resize(lwidth); } vhdl_expr *result; switch (ivl_expr_opcode(e)) { case '+': result = translate_numeric(lhs, rhs, VHDL_BINOP_ADD); break; case '-': result = translate_numeric(lhs, rhs, VHDL_BINOP_SUB); break; case '*': result = translate_numeric(lhs, rhs, VHDL_BINOP_MULT); break; case 'e': result = translate_relation(lhs, rhs, VHDL_BINOP_EQ); break; case 'E': if (vectorop) result = translate_relation(lhs->cast(&std_logic_vector), rhs->cast(&std_logic_vector), VHDL_BINOP_EQ); else result = translate_relation(lhs, rhs, VHDL_BINOP_EQ); break; case 'n': result = translate_relation(lhs, rhs, VHDL_BINOP_NEQ); break; case 'N': if (vectorop) result = translate_relation(lhs->cast(&std_logic_vector), rhs->cast(&std_logic_vector), VHDL_BINOP_NEQ); else result = translate_relation(lhs, rhs, VHDL_BINOP_NEQ); break; case '&': // Bitwise AND result = translate_numeric(lhs, rhs, VHDL_BINOP_AND); break; case 'a': // Logical AND result = translate_logical(lhs, rhs, VHDL_BINOP_AND); break; case '|': // Bitwise OR result = translate_numeric(lhs, rhs, VHDL_BINOP_OR); break; case 'o': // Logical OR result = translate_logical(lhs, rhs, VHDL_BINOP_OR); break; case '<': result = translate_relation(lhs, rhs, VHDL_BINOP_LT); break; case 'L': result = translate_relation(lhs, rhs, VHDL_BINOP_LEQ); break; case '>': result = translate_relation(lhs, rhs, VHDL_BINOP_GT); break; case 'G': result = translate_relation(lhs, rhs, VHDL_BINOP_GEQ); break; case 'l': result = translate_shift(lhs, rhs, VHDL_BINOP_SL); break; case 'r': result = translate_shift(lhs, rhs, VHDL_BINOP_SR); break; case '^': result = translate_numeric(lhs, rhs, VHDL_BINOP_XOR); break; default: error("No translation for binary opcode '%c'\n", ivl_expr_opcode(e)); delete lhs; delete rhs; return NULL; } if (NULL == result) return NULL; if (vectorop) { bool should_be_signed = ivl_expr_signed(e) != 0; if (result->get_type()->get_name() == VHDL_TYPE_UNSIGNED && should_be_signed) { //result->print(); //std::cout << "^ should be signed but is not" << std::endl; result = change_signdness(result, true); } else if (result->get_type()->get_name() == VHDL_TYPE_SIGNED && !should_be_signed) { //result->print(); //std::cout << "^ should be unsigned but is not" << std::endl; result = change_signdness(result, false); } int actual_width = result->get_type()->get_width(); if (actual_width != result_width) { //result->print(); //std::cout << "^ should be " << result_width << " but is " << actual_width << std::endl; } } return result; } static vhdl_expr *translate_select(ivl_expr_t e) { vhdl_var_ref *from = dynamic_cast<vhdl_var_ref*>(translate_expr(ivl_expr_oper1(e))); if (NULL == from) return NULL; ivl_expr_t o2 = ivl_expr_oper2(e); if (o2) { vhdl_expr *base = translate_expr(ivl_expr_oper2(e)); if (NULL == base) return NULL; vhdl_type integer(VHDL_TYPE_INTEGER); from->set_slice(base->cast(&integer), ivl_expr_width(e) - 1); return from; } else return from->resize(ivl_expr_width(e)); } static vhdl_type *expr_to_vhdl_type(ivl_expr_t e) { if (ivl_expr_signed(e)) return vhdl_type::nsigned(ivl_expr_width(e)); else return vhdl_type::nunsigned(ivl_expr_width(e)); } template <class T> static T *translate_parms(T *t, ivl_expr_t e) { int nparams = ivl_expr_parms(e); for (int i = 0; i < nparams; i++) { vhdl_expr *param = translate_expr(ivl_expr_parm(e, i)); if (NULL == param) return NULL; t->add_expr(param); } return t; } static vhdl_expr *translate_ufunc(ivl_expr_t e) { ivl_scope_t defscope = ivl_expr_def(e); ivl_scope_t parentscope = ivl_scope_parent(defscope); assert(ivl_scope_type(parentscope) == IVL_SCT_MODULE); // A function is always declared in a module, which should have // a corresponding entity by this point: so we can get type // information, etc. from the declaration vhdl_entity *parent_ent = find_entity(ivl_scope_tname(parentscope)); assert(parent_ent); const char *funcname = ivl_scope_tname(defscope); vhdl_type *rettype = expr_to_vhdl_type(e); vhdl_fcall *fcall = new vhdl_fcall(funcname, rettype); return translate_parms<vhdl_fcall>(fcall, e); } static vhdl_expr *translate_ternary(ivl_expr_t e) { error("Ternary expression only supported as RHS of assignment"); return NULL; } static vhdl_expr *translate_concat(ivl_expr_t e) { vhdl_type *rtype = expr_to_vhdl_type(e); vhdl_binop_expr *concat = new vhdl_binop_expr(VHDL_BINOP_CONCAT, rtype); return translate_parms<vhdl_binop_expr>(concat, e); } /* * Generate a VHDL expression from a Verilog expression. */ vhdl_expr *translate_expr(ivl_expr_t e) { assert(e); ivl_expr_type_t type = ivl_expr_type(e); switch (type) { case IVL_EX_STRING: return translate_string(e); case IVL_EX_SIGNAL: return translate_signal(e); case IVL_EX_NUMBER: return translate_number(e); case IVL_EX_UNARY: return translate_unary(e); case IVL_EX_BINARY: return translate_binary(e); case IVL_EX_SELECT: return translate_select(e); case IVL_EX_UFUNC: return translate_ufunc(e); case IVL_EX_TERNARY: return translate_ternary(e); case IVL_EX_CONCAT: return translate_concat(e); default: error("No VHDL translation for expression at %s:%d (type = %d)", ivl_expr_file(e), ivl_expr_lineno(e), type); return NULL; } } <|endoftext|>
<commit_before>#include "MPEditor.h" MPEditor::MPEditor(const BMessage &msg, const BMessenger &msgr, BString windowTitle, int ideaID) : BWindow(BRect(100, 100, 900, 700), windowTitle, B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS, B_CURRENT_WORKSPACE), launcherMessage(msg), launcherMessenger(msgr) { AddShortcut('q', B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED)); AddShortcut('n', B_COMMAND_KEY, new BMessage(MENU_NEW_THT)); AddShortcut('e', B_COMMAND_KEY, new BMessage(MENU_EDT_THT)); AddShortcut('s', B_COMMAND_KEY, new BMessage(MENU_SAV_THT)); AddShortcut('r', B_COMMAND_KEY, new BMessage(MENU_PRV_THT)); AddShortcut('p', B_COMMAND_KEY, new BMessage(MENU_PUB_THT)); AddShortcut('k', B_COMMAND_KEY, new BMessage(MENU_KEY_THT)); // initialize controls BRect r = Bounds(); r.bottom = r.bottom - 50; editorTextView = new BTextView(r, NULL, r, B_FOLLOW_ALL, B_WILL_DRAW | B_NAVIGABLE); backView = new BView(Bounds(), "backview", B_FOLLOW_ALL, B_WILL_DRAW); backView->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR)); AddChild(backView); // gui layout builder backView->SetLayout(new BGroupLayout(B_HORIZONTAL, 0.0)); backView->AddChild(BGridLayoutBuilder() .Add(new EditorMenu(), 0, 0) .Add(new BScrollView("scroll_editor", editorTextView, B_FOLLOW_ALL_SIDES, 0, false, true, B_FANCY_BORDER), 0, 1) .SetInsets(0, 0, 0, 0) ); currentideaID = ideaID; // pass current idea id selected to editor window for use if(currentideaID != -1) // if id has a real value { sqlObject = new SqlObject(ideaStatement, "7"); sqlObject->PrepareSql("select ideatext from ideatable where ideaid = ?"); sqlObject->BindValue(1, currentideaID); sqlObject->StepSql(); editorTextView->SetText(sqlObject->ReturnText(0)); sqlObject->FinalizeSql(); sqlObject->CloseSql(); } } void MPEditor::MessageReceived(BMessage* msg) { BRect r(Bounds()); switch(msg->what) { case MENU_NEW_THT: // open another untitled editor window tmpEditor = new MPEditor(BMessage(SHOW_LAUNCHER), BMessenger(this), "MasterPiece Editor - untitled", -1); tmpEditor->Show(); break; case MENU_EDT_THT: // edit current idea name for editing xPos = (r.right - r.left) / 2; // find xpos for window yPos = (r.bottom - r.top) / 2; // find ypos for window editIdeaName = new EditIdeaName(BMessage(UPDATE_TITLE), BMessenger(this), xPos, yPos, currentideaID); editIdeaName->Show(); // show edit idea name window break; case MENU_SAV_THT: // save current idea progress if(currentideaID == -1) // if its untitled insert new thought, then show saveidea to apply a name... { sqlObject = new SqlObject(ideaStatement, "8"); sqlObject->PrepareSql("insert into ideatable (ideaname, ideatext, ismp) values('untitled', ?, 0)"); sqlObject->BindValue(1, editorTextView->Text()); sqlObject->StepSql(); xPos = (r.right - r.left) / 2; // find xpos for window yPos = (r.bottom - r.top) / 2; // find ypos for window saveIdea = new SaveIdea(BMessage(UPDATE_TITLE), BMessenger(this), xPos, yPos, sqlObject->ReturnLastInsertRowID()); currentideaID = sqlObject->ReturnLastInsertRowID(); sqlObject->FinalizeSql(); sqlObject->CloseSql(); saveIdea->Show(); // show save window to name the untitled thought } else // already exists, just update ideatext and save new information { sqlObject = new SqlObject(ideaStatement, "9"); sqlObject->PrepareSql("update ideatable set ideatext = ? where ideaid = ?"); sqlObject->BindValue(1, editorTextView->Text()); sqlObject->BindValue(2, currentideaID); sqlObject->StepSql(); sqlObject->FinalizeSql(); sqlObject->CloseSql(); } break; case MENU_PRV_THT: // preview thought in html in webpositive printf("save data to tmp file, export to python html one and open data in preview window or webpositive\n\n"); // AM NO LONGER WRITING A FULL BLOWN PARSER AND DISPLAYER IN A TEXTVIEW. IF I DO THAT, I HAVE WRITTEN A FULL BLOWN WORD PROCESSOR. // WILL SIMPLY USE THE PREVIEWER TO PREVIEW IN HTML WITH WEBPOSITIVE. // FORK/EXEC IN POSIX LINUX WILL RUN AN APP FROM C++. HAVE TO RESEARCH THIS. //mpPreview = new MPPreview(currentideaID); //mpPreview->Show(); system("/boot/apps/WebPositive/WebPositive file:///boot/home/Projects/masterpiece/test.html &"); Py_Initialize(); PyRun_SimpleString("from time import time,ctime\n" "print 'Today is', ctime(time())\n"); Py_Finalize(); break; case MENU_PUB_THT: // publish thought by opening publish window printf("save data, open publish to window, export to python and save as name in publish window"); break; case MENU_HLP_THT: // open help topic window printf("open help topic window"); break; case MENU_KEY_THT: // open keyboard reference window xPos = (r.right - r.left) / 2; // find xpos for window yPos = (r.bottom - r.top) / 2; // find ypos for window helperWindow = new HelperWindows(BRect(xPos, yPos, 670, 500), "Keyboard Shortcuts"); helperWindow->AddText(BRect(10, 10, 200, 25), "1", "Close the Window :: ALT+q"); helperWindow->AddText(BRect(10, 35, 200, 60), "2", "New Thought :: ALT+n"); helperWindow->Show(); printf("open keyboard reference window"); break; case MENU_MRK_THT: // open markup reference window printf("open markup reference window"); break; case MENU_ABT_THT: // open about window printf("open about window"); break; case UPDATE_TITLE: // update title with the name from the saveidea window if(msg->FindString("updatetitle", &updateTitle) == B_OK) // updated title exists in variable { tmpString = "Masterpiece Editor - "; tmpString += updateTitle; this->SetTitle(tmpString); } else // { eAlert = new ErrorAlert("3.1 Editor Error: Message not found."); // message variable not found eAlert->Launch(); } break; default: { BWindow::MessageReceived(msg); break; } } } bool MPEditor::QuitRequested(void) { // on quit, show launcher by sending message launcherMessage.MakeEmpty(); launcherMessage.AddInt64("showLauncher", 1); launcherMessenger.SendMessage(&launcherMessage); return true; } <commit_msg>finished the keyboard helper window<commit_after>#include "MPEditor.h" MPEditor::MPEditor(const BMessage &msg, const BMessenger &msgr, BString windowTitle, int ideaID) : BWindow(BRect(100, 100, 900, 700), windowTitle, B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS, B_CURRENT_WORKSPACE), launcherMessage(msg), launcherMessenger(msgr) { AddShortcut('q', B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED)); AddShortcut('n', B_COMMAND_KEY, new BMessage(MENU_NEW_THT)); AddShortcut('e', B_COMMAND_KEY, new BMessage(MENU_EDT_THT)); AddShortcut('s', B_COMMAND_KEY, new BMessage(MENU_SAV_THT)); AddShortcut('r', B_COMMAND_KEY, new BMessage(MENU_PRV_THT)); AddShortcut('p', B_COMMAND_KEY, new BMessage(MENU_PUB_THT)); AddShortcut('k', B_COMMAND_KEY, new BMessage(MENU_KEY_THT)); // initialize controls BRect r = Bounds(); r.bottom = r.bottom - 50; editorTextView = new BTextView(r, NULL, r, B_FOLLOW_ALL, B_WILL_DRAW | B_NAVIGABLE); backView = new BView(Bounds(), "backview", B_FOLLOW_ALL, B_WILL_DRAW); backView->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR)); AddChild(backView); // gui layout builder backView->SetLayout(new BGroupLayout(B_HORIZONTAL, 0.0)); backView->AddChild(BGridLayoutBuilder() .Add(new EditorMenu(), 0, 0) .Add(new BScrollView("scroll_editor", editorTextView, B_FOLLOW_ALL_SIDES, 0, false, true, B_FANCY_BORDER), 0, 1) .SetInsets(0, 0, 0, 0) ); currentideaID = ideaID; // pass current idea id selected to editor window for use if(currentideaID != -1) // if id has a real value { sqlObject = new SqlObject(ideaStatement, "7"); sqlObject->PrepareSql("select ideatext from ideatable where ideaid = ?"); sqlObject->BindValue(1, currentideaID); sqlObject->StepSql(); editorTextView->SetText(sqlObject->ReturnText(0)); sqlObject->FinalizeSql(); sqlObject->CloseSql(); } } void MPEditor::MessageReceived(BMessage* msg) { BRect r(Bounds()); switch(msg->what) { case MENU_NEW_THT: // open another untitled editor window tmpEditor = new MPEditor(BMessage(SHOW_LAUNCHER), BMessenger(this), "MasterPiece Editor - untitled", -1); tmpEditor->Show(); break; case MENU_EDT_THT: // edit current idea name for editing xPos = (r.right - r.left) / 2; // find xpos for window yPos = (r.bottom - r.top) / 2; // find ypos for window editIdeaName = new EditIdeaName(BMessage(UPDATE_TITLE), BMessenger(this), xPos, yPos, currentideaID); editIdeaName->Show(); // show edit idea name window break; case MENU_SAV_THT: // save current idea progress if(currentideaID == -1) // if its untitled insert new thought, then show saveidea to apply a name... { sqlObject = new SqlObject(ideaStatement, "8"); sqlObject->PrepareSql("insert into ideatable (ideaname, ideatext, ismp) values('untitled', ?, 0)"); sqlObject->BindValue(1, editorTextView->Text()); sqlObject->StepSql(); xPos = (r.right - r.left) / 2; // find xpos for window yPos = (r.bottom - r.top) / 2; // find ypos for window saveIdea = new SaveIdea(BMessage(UPDATE_TITLE), BMessenger(this), xPos, yPos, sqlObject->ReturnLastInsertRowID()); currentideaID = sqlObject->ReturnLastInsertRowID(); sqlObject->FinalizeSql(); sqlObject->CloseSql(); saveIdea->Show(); // show save window to name the untitled thought } else // already exists, just update ideatext and save new information { sqlObject = new SqlObject(ideaStatement, "9"); sqlObject->PrepareSql("update ideatable set ideatext = ? where ideaid = ?"); sqlObject->BindValue(1, editorTextView->Text()); sqlObject->BindValue(2, currentideaID); sqlObject->StepSql(); sqlObject->FinalizeSql(); sqlObject->CloseSql(); } break; case MENU_PRV_THT: // preview thought in html in webpositive printf("save data to tmp file, export to python html one and open data in preview window or webpositive\n\n"); // AM NO LONGER WRITING A FULL BLOWN PARSER AND DISPLAYER IN A TEXTVIEW. IF I DO THAT, I HAVE WRITTEN A FULL BLOWN WORD PROCESSOR. // WILL SIMPLY USE THE PREVIEWER TO PREVIEW IN HTML WITH WEBPOSITIVE. // FORK/EXEC IN POSIX LINUX WILL RUN AN APP FROM C++. HAVE TO RESEARCH THIS. //mpPreview = new MPPreview(currentideaID); //mpPreview->Show(); system("/boot/apps/WebPositive/WebPositive file:///boot/home/Projects/masterpiece/test.html &"); Py_Initialize(); PyRun_SimpleString("from time import time,ctime\n" "print 'Today is', ctime(time())\n"); Py_Finalize(); break; case MENU_PUB_THT: // publish thought by opening publish window printf("save data, open publish to window, export to python and save as name in publish window"); break; case MENU_HLP_THT: // open help topic window printf("open help topic window"); break; case MENU_KEY_THT: // open keyboard reference window xPos = (r.right - r.left) / 2; // find xpos for window yPos = (r.bottom - r.top) / 2; // find ypos for window helperWindow = new HelperWindows(BRect(xPos, yPos, xPos + 240, yPos + 190), "Keyboard Shortcuts"); helperWindow->AddText(BRect(10, 10, 200, 25), "1", "Close the Window :: ALT + q"); helperWindow->AddText(BRect(10, 35, 200, 50), "2", "New Thought :: ALT + n"); helperWindow->AddText(BRect(10, 60, 200, 75), "3", "Edit Thought Name :: ALT + e"); helperWindow->AddText(BRect(10, 85, 200, 100), "4", "Save Progress :: ALT + s"); helperWindow->AddText(BRect(10, 110, 200, 125), "5", "Preview Thought :: ALT + r"); helperWindow->AddText(BRect(10, 135, 200, 150), "6", "Publish Thought :: ALT + p"); helperWindow->AddText(BRect(10, 160, 230, 175), "7", "View Keyboard Shortcuts :: ALT + k"); helperWindow->Show(); printf("open keyboard reference window"); break; case MENU_MRK_THT: // open markup reference window printf("open markup reference window"); break; case MENU_ABT_THT: // open about window printf("open about window"); break; case UPDATE_TITLE: // update title with the name from the saveidea window if(msg->FindString("updatetitle", &updateTitle) == B_OK) // updated title exists in variable { tmpString = "Masterpiece Editor - "; tmpString += updateTitle; this->SetTitle(tmpString); } else // { eAlert = new ErrorAlert("3.1 Editor Error: Message not found."); // message variable not found eAlert->Launch(); } break; default: { BWindow::MessageReceived(msg); break; } } } bool MPEditor::QuitRequested(void) { // on quit, show launcher by sending message launcherMessage.MakeEmpty(); launcherMessage.AddInt64("showLauncher", 1); launcherMessenger.SendMessage(&launcherMessage); return true; } <|endoftext|>
<commit_before>#include <boost/test/unit_test.hpp> #include "ThreadQueue.hpp" #include <iostream> BOOST_AUTO_TEST_SUITE( ThreadQueue_tests ); BOOST_AUTO_TEST_CASE( test1 ) { #ifndef DEBUG BOOST_MESSAGE( "This test requires -DDEBUG for full checks" ); BOOST_CHECK( false ); #endif Worker * ws[100]; for(int i=0; i< 100; i++) { ws[i] = new Worker(); } PrefetchingThreadQueue q(4); q.enqueue(ws[0]); BOOST_CHECK( q.length() == 1 ); BOOST_CHECK( q.dequeue() == ws[0] ); BOOST_CHECK( q.length() == 0 ); BOOST_CHECK( q.dequeue() == NULL ); BOOST_CHECK( q.length() == 0 ); q.enqueue(ws[1]); BOOST_CHECK( q.length() == 1 ); q.enqueue(ws[2]); BOOST_CHECK( q.length() == 2 ); BOOST_CHECK( q.dequeue() == ws[1] ); BOOST_CHECK( q.length() == 1 ); q.enqueue(ws[3]); BOOST_CHECK( q.length() == 2 ); int iters = 10; for ( int i=1; i<=iters; i++ ) { q.enqueue(ws[3+i]); BOOST_CHECK( q.length() == 2+i ); } int len = q.length(); BOOST_CHECK( q.dequeue() == ws[2] ); BOOST_CHECK( q.length() == len-1 ); BOOST_CHECK( q.dequeue() == ws[3] ); BOOST_CHECK( q.length() == len-2 ); BOOST_CHECK( q.dequeue() == ws[4] ); BOOST_CHECK( q.length() == len-3 ); q.enqueue(ws[14]); BOOST_CHECK( q.length() == len-2 ); BOOST_CHECK( q.dequeue() == ws[5] ); BOOST_CHECK( q.length() == len-3 ); BOOST_MESSAGE( "done" ); } BOOST_AUTO_TEST_SUITE_END(); <commit_msg>fix ThreadQueue_tests<commit_after>#include <boost/test/unit_test.hpp> #include "ThreadQueue.hpp" #include <iostream> BOOST_AUTO_TEST_SUITE( ThreadQueue_tests ); using namespace Grappa; BOOST_AUTO_TEST_CASE( test1 ) { #ifndef DEBUG BOOST_MESSAGE( "This test requires -DDEBUG for full checks" ); BOOST_CHECK( false ); #endif Worker * ws[100]; for(int i=0; i< 100; i++) { ws[i] = new Worker(); } PrefetchingThreadQueue q; q.init(4); q.enqueue(ws[0]); BOOST_CHECK( q.length() == 1 ); BOOST_CHECK( q.dequeue() == ws[0] ); BOOST_CHECK( q.length() == 0 ); BOOST_CHECK( q.dequeue() == NULL ); BOOST_CHECK( q.length() == 0 ); q.enqueue(ws[1]); BOOST_CHECK( q.length() == 1 ); q.enqueue(ws[2]); BOOST_CHECK( q.length() == 2 ); BOOST_CHECK( q.dequeue() == ws[1] ); BOOST_CHECK( q.length() == 1 ); q.enqueue(ws[3]); BOOST_CHECK( q.length() == 2 ); int iters = 10; for ( int i=1; i<=iters; i++ ) { q.enqueue(ws[3+i]); BOOST_CHECK( q.length() == 2+i ); } int len = q.length(); BOOST_CHECK( q.dequeue() == ws[2] ); BOOST_CHECK( q.length() == len-1 ); BOOST_CHECK( q.dequeue() == ws[3] ); BOOST_CHECK( q.length() == len-2 ); BOOST_CHECK( q.dequeue() == ws[4] ); BOOST_CHECK( q.length() == len-3 ); q.enqueue(ws[14]); BOOST_CHECK( q.length() == len-2 ); BOOST_CHECK( q.dequeue() == ws[5] ); BOOST_CHECK( q.length() == len-3 ); BOOST_MESSAGE( "done" ); } BOOST_AUTO_TEST_SUITE_END(); <|endoftext|>
<commit_before>/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2015. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #include "Notifier.h" #include <queue> #include <vector> using namespace nt; ATOMIC_STATIC_INIT(Notifier) bool Notifier::s_destroyed = false; class Notifier::Thread : public SafeThread { public: Thread(std::function<void()> on_start, std::function<void()> on_exit) : m_on_start(on_start), m_on_exit(on_exit) {} void Main(); struct EntryListener { EntryListener(StringRef prefix_, EntryListenerCallback callback_, unsigned int flags_) : prefix(prefix_), callback(callback_), flags(flags_) {} std::string prefix; EntryListenerCallback callback; unsigned int flags; }; std::vector<EntryListener> m_entry_listeners; std::vector<ConnectionListenerCallback> m_conn_listeners; struct EntryNotification { EntryNotification(StringRef name_, std::shared_ptr<Value> value_, unsigned int flags_, EntryListenerCallback only_) : name(name_), value(value_), flags(flags_), only(only_) {} std::string name; std::shared_ptr<Value> value; unsigned int flags; EntryListenerCallback only; }; std::queue<EntryNotification> m_entry_notifications; struct ConnectionNotification { ConnectionNotification(bool connected_, const ConnectionInfo& conn_info_, ConnectionListenerCallback only_) : connected(connected_), conn_info(conn_info_), only(only_) {} bool connected; ConnectionInfo conn_info; ConnectionListenerCallback only; }; std::queue<ConnectionNotification> m_conn_notifications; std::function<void()> m_on_start; std::function<void()> m_on_exit; }; Notifier::Notifier() { m_local_notifiers = false; s_destroyed = false; } Notifier::~Notifier() { s_destroyed = true; } void Notifier::Start() { auto thr = m_owner.GetThread(); if (!thr) m_owner.Start(new Thread(m_on_start, m_on_exit)); } void Notifier::Stop() { m_owner.Stop(); } void Notifier::Thread::Main() { if (m_on_start) m_on_start(); std::unique_lock<std::mutex> lock(m_mutex); while (m_active) { while (m_entry_notifications.empty() && m_conn_notifications.empty()) { m_cond.wait(lock); if (!m_active) goto done; } // Entry notifications while (!m_entry_notifications.empty()) { if (!m_active) goto done; auto item = std::move(m_entry_notifications.front()); m_entry_notifications.pop(); if (!item.value) continue; StringRef name(item.name); if (item.only) { // Don't hold mutex during callback execution! lock.unlock(); item.only(0, name, item.value, item.flags); lock.lock(); continue; } // Use index because iterator might get invalidated. for (std::size_t i=0; i<m_entry_listeners.size(); ++i) { if (!m_entry_listeners[i].callback) continue; // removed // Flags must be within requested flag set for this listener. // Because assign messages can result in both a value and flags update, // we handle that case specially. unsigned int listen_flags = m_entry_listeners[i].flags; unsigned int flags = item.flags; unsigned int assign_both = NT_NOTIFY_UPDATE | NT_NOTIFY_FLAGS; if ((flags & assign_both) == assign_both) { if ((listen_flags & assign_both) == 0) continue; listen_flags &= ~assign_both; flags &= ~assign_both; } if ((flags & ~listen_flags) != 0) continue; // must match prefix if (!name.startswith(m_entry_listeners[i].prefix)) continue; // make a copy of the callback so we can safely release the mutex auto callback = m_entry_listeners[i].callback; // Don't hold mutex during callback execution! lock.unlock(); callback(i+1, name, item.value, item.flags); lock.lock(); } } // Connection notifications while (!m_conn_notifications.empty()) { if (!m_active) goto done; auto item = std::move(m_conn_notifications.front()); m_conn_notifications.pop(); if (item.only) { // Don't hold mutex during callback execution! lock.unlock(); item.only(0, item.connected, item.conn_info); lock.lock(); continue; } // Use index because iterator might get invalidated. for (std::size_t i=0; i<m_conn_listeners.size(); ++i) { if (!m_conn_listeners[i]) continue; // removed auto callback = m_conn_listeners[i]; // Don't hold mutex during callback execution! lock.unlock(); callback(i+1, item.connected, item.conn_info); lock.lock(); } } } done: if (m_on_exit) m_on_exit(); } unsigned int Notifier::AddEntryListener(StringRef prefix, EntryListenerCallback callback, unsigned int flags) { Start(); auto thr = m_owner.GetThread(); unsigned int uid = thr->m_entry_listeners.size(); thr->m_entry_listeners.emplace_back(prefix, callback, flags); if ((flags & NT_NOTIFY_LOCAL) != 0) m_local_notifiers = true; return uid + 1; } void Notifier::RemoveEntryListener(unsigned int entry_listener_uid) { auto thr = m_owner.GetThread(); if (!thr) return; --entry_listener_uid; if (entry_listener_uid < thr->m_entry_listeners.size()) thr->m_entry_listeners[entry_listener_uid].callback = nullptr; } void Notifier::NotifyEntry(StringRef name, std::shared_ptr<Value> value, unsigned int flags, EntryListenerCallback only) { // optimization: don't generate needless local queue entries if we have // no local listeners (as this is a common case on the server side) if ((flags & NT_NOTIFY_LOCAL) != 0 && !m_local_notifiers) return; auto thr = m_owner.GetThread(); if (!thr) return; thr->m_entry_notifications.emplace(name, value, flags, only); thr->m_cond.notify_one(); } unsigned int Notifier::AddConnectionListener( ConnectionListenerCallback callback) { Start(); auto thr = m_owner.GetThread(); unsigned int uid = thr->m_entry_listeners.size(); thr->m_conn_listeners.emplace_back(callback); return uid + 1; } void Notifier::RemoveConnectionListener(unsigned int conn_listener_uid) { auto thr = m_owner.GetThread(); if (!thr) return; --conn_listener_uid; if (conn_listener_uid < thr->m_conn_listeners.size()) thr->m_conn_listeners[conn_listener_uid] = nullptr; } void Notifier::NotifyConnection(bool connected, const ConnectionInfo& conn_info, ConnectionListenerCallback only) { auto thr = m_owner.GetThread(); if (!thr) return; thr->m_conn_notifications.emplace(connected, conn_info, only); thr->m_cond.notify_one(); } <commit_msg>Fixes Connection Listeners<commit_after>/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2015. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #include "Notifier.h" #include <queue> #include <vector> using namespace nt; ATOMIC_STATIC_INIT(Notifier) bool Notifier::s_destroyed = false; class Notifier::Thread : public SafeThread { public: Thread(std::function<void()> on_start, std::function<void()> on_exit) : m_on_start(on_start), m_on_exit(on_exit) {} void Main(); struct EntryListener { EntryListener(StringRef prefix_, EntryListenerCallback callback_, unsigned int flags_) : prefix(prefix_), callback(callback_), flags(flags_) {} std::string prefix; EntryListenerCallback callback; unsigned int flags; }; std::vector<EntryListener> m_entry_listeners; std::vector<ConnectionListenerCallback> m_conn_listeners; struct EntryNotification { EntryNotification(StringRef name_, std::shared_ptr<Value> value_, unsigned int flags_, EntryListenerCallback only_) : name(name_), value(value_), flags(flags_), only(only_) {} std::string name; std::shared_ptr<Value> value; unsigned int flags; EntryListenerCallback only; }; std::queue<EntryNotification> m_entry_notifications; struct ConnectionNotification { ConnectionNotification(bool connected_, const ConnectionInfo& conn_info_, ConnectionListenerCallback only_) : connected(connected_), conn_info(conn_info_), only(only_) {} bool connected; ConnectionInfo conn_info; ConnectionListenerCallback only; }; std::queue<ConnectionNotification> m_conn_notifications; std::function<void()> m_on_start; std::function<void()> m_on_exit; }; Notifier::Notifier() { m_local_notifiers = false; s_destroyed = false; } Notifier::~Notifier() { s_destroyed = true; } void Notifier::Start() { auto thr = m_owner.GetThread(); if (!thr) m_owner.Start(new Thread(m_on_start, m_on_exit)); } void Notifier::Stop() { m_owner.Stop(); } void Notifier::Thread::Main() { if (m_on_start) m_on_start(); std::unique_lock<std::mutex> lock(m_mutex); while (m_active) { while (m_entry_notifications.empty() && m_conn_notifications.empty()) { m_cond.wait(lock); if (!m_active) goto done; } // Entry notifications while (!m_entry_notifications.empty()) { if (!m_active) goto done; auto item = std::move(m_entry_notifications.front()); m_entry_notifications.pop(); if (!item.value) continue; StringRef name(item.name); if (item.only) { // Don't hold mutex during callback execution! lock.unlock(); item.only(0, name, item.value, item.flags); lock.lock(); continue; } // Use index because iterator might get invalidated. for (std::size_t i=0; i<m_entry_listeners.size(); ++i) { if (!m_entry_listeners[i].callback) continue; // removed // Flags must be within requested flag set for this listener. // Because assign messages can result in both a value and flags update, // we handle that case specially. unsigned int listen_flags = m_entry_listeners[i].flags; unsigned int flags = item.flags; unsigned int assign_both = NT_NOTIFY_UPDATE | NT_NOTIFY_FLAGS; if ((flags & assign_both) == assign_both) { if ((listen_flags & assign_both) == 0) continue; listen_flags &= ~assign_both; flags &= ~assign_both; } if ((flags & ~listen_flags) != 0) continue; // must match prefix if (!name.startswith(m_entry_listeners[i].prefix)) continue; // make a copy of the callback so we can safely release the mutex auto callback = m_entry_listeners[i].callback; // Don't hold mutex during callback execution! lock.unlock(); callback(i+1, name, item.value, item.flags); lock.lock(); } } // Connection notifications while (!m_conn_notifications.empty()) { if (!m_active) goto done; auto item = std::move(m_conn_notifications.front()); m_conn_notifications.pop(); if (item.only) { // Don't hold mutex during callback execution! lock.unlock(); item.only(0, item.connected, item.conn_info); lock.lock(); continue; } // Use index because iterator might get invalidated. for (std::size_t i=0; i<m_conn_listeners.size(); ++i) { if (!m_conn_listeners[i]) continue; // removed auto callback = m_conn_listeners[i]; // Don't hold mutex during callback execution! lock.unlock(); callback(i+1, item.connected, item.conn_info); lock.lock(); } } } done: if (m_on_exit) m_on_exit(); } unsigned int Notifier::AddEntryListener(StringRef prefix, EntryListenerCallback callback, unsigned int flags) { Start(); auto thr = m_owner.GetThread(); unsigned int uid = thr->m_entry_listeners.size(); thr->m_entry_listeners.emplace_back(prefix, callback, flags); if ((flags & NT_NOTIFY_LOCAL) != 0) m_local_notifiers = true; return uid + 1; } void Notifier::RemoveEntryListener(unsigned int entry_listener_uid) { auto thr = m_owner.GetThread(); if (!thr) return; --entry_listener_uid; if (entry_listener_uid < thr->m_entry_listeners.size()) thr->m_entry_listeners[entry_listener_uid].callback = nullptr; } void Notifier::NotifyEntry(StringRef name, std::shared_ptr<Value> value, unsigned int flags, EntryListenerCallback only) { // optimization: don't generate needless local queue entries if we have // no local listeners (as this is a common case on the server side) if ((flags & NT_NOTIFY_LOCAL) != 0 && !m_local_notifiers) return; auto thr = m_owner.GetThread(); if (!thr) return; thr->m_entry_notifications.emplace(name, value, flags, only); thr->m_cond.notify_one(); } unsigned int Notifier::AddConnectionListener( ConnectionListenerCallback callback) { Start(); auto thr = m_owner.GetThread(); unsigned int uid = thr->m_conn_listeners.size(); thr->m_conn_listeners.emplace_back(callback); return uid + 1; } void Notifier::RemoveConnectionListener(unsigned int conn_listener_uid) { auto thr = m_owner.GetThread(); if (!thr) return; --conn_listener_uid; if (conn_listener_uid < thr->m_conn_listeners.size()) thr->m_conn_listeners[conn_listener_uid] = nullptr; } void Notifier::NotifyConnection(bool connected, const ConnectionInfo& conn_info, ConnectionListenerCallback only) { auto thr = m_owner.GetThread(); if (!thr) return; thr->m_conn_notifications.emplace(connected, conn_info, only); thr->m_cond.notify_one(); } <|endoftext|>
<commit_before>#include "Odometry.h" #include <cstdint> #include "WProgram.h" #include "Device.h" #include "config.h" namespace tamproxy { Odometer::Odometer(Encoder& lEncoder, Encoder& rEncoder, Gyro& gyro, float alpha) : _encL(lEncoder), _encR(rEncoder), _gyro(gyro), _alpha(alpha), _lastTime(micros()), _lastMeanEnc(0) { } std::vector<uint8_t> Odometer::handleRequest(std::vector<uint8_t> &request) { if (request[0] == ODOMETER_READ_CODE) { if (request.size() != 1) return {REQUEST_LENGTH_INVALID_CODE}; // here be dragons float vals[] = {_angle, _x, _y}; uint32_t val = *reinterpret_cast<uint32_t*>(&_angle); return { static_cast<uint8_t>(val>>24), static_cast<uint8_t>(val>>16), static_cast<uint8_t>(val>>8), static_cast<uint8_t>(val) }; } else { return {REQUEST_BODY_INVALID_CODE}; } } void Odometer::update() { const float ticksPerRev = 3200.0; const float wheelDiam = 3.78125; const float baseWidth = 15.3; //inches uint32_t lEncVal = _encL.read(); uint32_t rEncVal = _encR.read(); // be careful about overflow here int32_t diffEnc = lEncVal - rEncVal; uint32_t meanEnc = rEncVal + diffEnc/2; bool ok; float gyroRead = _gyro.read(ok); if(!ok) return; _gyroTot += gyroRead*(micros()-_lastTime) / 1e6; float encAngle = (diffEnc/ticksPerRev)*wheelDiam/(baseWidth / 2); _angle = _alpha*_gyroTot + (1-_alpha)*encAngle; float dr = static_cast<int32_t>(meanEnc - _lastMeanEnc)/ticksPerRev*wheelDiam*M_PI; _x += dr * cos(_angle); _y += dr * sin(_angle); _lastTime = micros(); } }<commit_msg>Initialize variable<commit_after>#include "Odometry.h" #include <cstdint> #include "WProgram.h" #include "Device.h" #include "config.h" namespace tamproxy { Odometer::Odometer(Encoder& lEncoder, Encoder& rEncoder, Gyro& gyro, float alpha) : _encL(lEncoder), _encR(rEncoder), _gyro(gyro), _alpha(alpha), _lastTime(micros()), _lastMeanEnc(0), _gyroTot(0) { } std::vector<uint8_t> Odometer::handleRequest(std::vector<uint8_t> &request) { if (request[0] == ODOMETER_READ_CODE) { if (request.size() != 1) return {REQUEST_LENGTH_INVALID_CODE}; // here be dragons float vals[] = {_angle, _x, _y}; uint32_t val = *reinterpret_cast<uint32_t*>(&_angle); return { static_cast<uint8_t>(val>>24), static_cast<uint8_t>(val>>16), static_cast<uint8_t>(val>>8), static_cast<uint8_t>(val) }; } else { return {REQUEST_BODY_INVALID_CODE}; } } void Odometer::update() { const float ticksPerRev = 3200.0; const float wheelDiam = 3.78125; const float baseWidth = 15.3; //inches uint32_t lEncVal = _encL.read(); uint32_t rEncVal = _encR.read(); // be careful about overflow here int32_t diffEnc = lEncVal - rEncVal; uint32_t meanEnc = rEncVal + diffEnc/2; bool ok; float gyroRead = _gyro.read(ok); if(!ok) return; _gyroTot += gyroRead*(micros()-_lastTime) / 1e6; float encAngle = (diffEnc/ticksPerRev)*wheelDiam/(baseWidth / 2); _angle = _alpha*_gyroTot + (1-_alpha)*encAngle; float dr = static_cast<int32_t>(meanEnc - _lastMeanEnc)/ticksPerRev*wheelDiam*M_PI; _x += dr * cos(_angle); _y += dr * sin(_angle); _lastTime = micros(); } }<|endoftext|>
<commit_before>/** * \file * \brief PySensor class implementation. * \author Thomas Moeller * \details * * Copyright (C) the PyInventor contributors. All rights reserved. * This file is part of PyInventor, distributed under the BSD 3-Clause * License. For full terms see the included COPYING file. */ #include <Inventor/sensors/SoSensors.h> #include <Inventor/fields/SoFieldContainer.h> #include <Inventor/nodes/SoSelection.h> #include "PySensor.h" #include "PyPath.h" #pragma warning ( disable : 4127 ) // conditional expression is constant in Py_DECREF #pragma warning ( disable : 4244 ) // possible loss of data when converting int to short in SbVec2s PyTypeObject *PySensor::getType() { static PyMemberDef members[] = { {"callback", T_OBJECT_EX, offsetof(Object, callback), 0, "Sensor callback function.\n" "\n" "An object can be assigned to that property which is called when a\n" "sensor is triggered.\n" }, {NULL} /* Sentinel */ }; static PyMethodDef methods[] = { {"attach", (PyCFunction) attach, METH_VARARGS, "Attaches sensor/callback to node or field. The callback is triggered\n" "when the attached node or field changes. If only a Node instance is\n" "given then the sensor triggers on any change of that node or children.\n" "If both a scene object instance and a field or callback name are passed,\n" "the sensor triggers on field changes only.\n" "For Selection nodes the names 'selection', 'deselection', 'start'\n" "'finish' are also accepted to register the corresponding callbacks.\n" "\n" "Args:\n" " - node: Scene object instance to attach to.\n" " - name: Optional field name (or callback for Selection node).\n" " - func: The callback function can also be passed as argument\n" " instead of assigning the callback property.\n" }, {"detach", (PyCFunction) detach, METH_NOARGS, "Deactivates a sensor.\n" }, {"set_interval", (PyCFunction) set_interval, METH_VARARGS, "Sets up a timer sensor with a regular interval.\n" "\n" "Args:\n" " Timer interval in milliseconds.\n" }, {"set_time", (PyCFunction) set_time, METH_VARARGS, "Sets up an alarm sensor that is trigegred at a given time from now.\n" "\n" "Args:\n" " Timer from now in milliseconds when the sensor will be triggered.\n" }, {"schedule", (PyCFunction) schedule, METH_NOARGS, "Schedules a timer sensor." }, {"unschedule", (PyCFunction) unschedule, METH_NOARGS, "Unschedules a timer sensor." }, {"is_scheduled", (PyCFunction) is_scheduled, METH_NOARGS, "Returns scheduled state of the sensor.\n" "\n" "Returns:\n" " True is sensor is currently scheduled, otherwise False.\n" }, {NULL} /* Sentinel */ }; static PyTypeObject sensorType = { PyVarObject_HEAD_INIT(NULL, 0) "Sensor", /* tp_name */ sizeof(Object), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor) tp_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, //(setattrofunc)tp_setattro, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ "Represents node, field, timer and alarm sensors.\n" "\n" "Sensors can be used to observe changes in scene graphs or to trigger actions\n" "at given times.\n", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ methods, /* tp_methods */ members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc) tp_init, /* tp_init */ 0, /* tp_alloc */ tp_new, /* tp_new */ }; return &sensorType; } void PySensor::unregisterSelectionCB(Object *self) { if (self->selection) { switch (self->selectionCB) { case Object::CB_SELECTION: self->selection->removeSelectionCallback(selectionPathCB, self); break; case Object::CB_DESELECTION: self->selection->removeDeselectionCallback(selectionPathCB, self); break; case Object::CB_START: self->selection->removeStartCallback(selectionClassCB, self); break; case Object::CB_FINISH: self->selection->removeFinishCallback(selectionClassCB, self); break; } self->selection->unref(); self->selection = 0; } } void PySensor::tp_dealloc(Object* self) { if (self->sensor) { delete self->sensor; } unregisterSelectionCB(self); Py_XDECREF(self->callback); Py_TYPE(self)->tp_free((PyObject*)self); } PyObject* PySensor::tp_new(PyTypeObject *type, PyObject* /*args*/, PyObject* /*kwds*/) { PySceneObject::initSoDB(); Object *self = (Object *)type->tp_alloc(type, 0); if (self != NULL) { self->callback = 0; self->sensor = 0; self->selection = 0; self->selectionCB = Object::CB_SELECTION; } return (PyObject *) self; } int PySensor::tp_init(Object *self, PyObject *args, PyObject * /*kwds*/) { Py_INCREF(Py_None); self->callback = Py_None; attach(self, args); return 0; } void PySensor::sensorCBFunc(void *userdata, SoSensor* /*sensor*/) { Object *self = (Object *) userdata; if ((self != NULL) && (self->callback != NULL) && PyCallable_Check(self->callback)) { PyObject *value = PyObject_CallObject(self->callback, NULL); if (value != NULL) { Py_DECREF(value); } } } void PySensor::selectionPathCB(void * userdata, SoPath * path) { Object *self = (Object *)userdata; if ((self != NULL) && (self->callback != NULL) && PyCallable_Check(self->callback)) { PyObject *value = PyObject_CallObject(self->callback, Py_BuildValue("(O)", PyPath::createWrapper(path))); if (value != NULL) { Py_DECREF(value); } } } void PySensor::selectionClassCB(void * userdata, SoSelection * sel) { Object *self = (Object *)userdata; if ((self != NULL) && (self->callback != NULL) && PyCallable_Check(self->callback)) { PyObject *value = PyObject_CallObject(self->callback, Py_BuildValue("(O)", PySceneObject::createWrapper(sel))); if (value != NULL) { Py_DECREF(value); } } } PyObject* PySensor::attach(Object *self, PyObject *args) { PyObject *node = 0, *callback = 0; char *fieldName = 0; if (PyArg_ParseTuple(args, "O|sO", &node, &fieldName, &callback)) { SoFieldContainer *fc = 0; SoField *field = 0; if (node && PySceneObject_Check(node)) { fc = ((PySceneObject::Object*) node)->inventorObject; } if (fc && fieldName && fc->isOfType(SoSelection::getClassTypeId())) { unregisterSelectionCB(self); if (SbString("selection") == fieldName) { self->selectionCB = Object::CB_SELECTION; self->selection = (SoSelection*) fc; self->selection->ref(); self->selection->addSelectionCallback(selectionPathCB, self); fc = 0; } else if (SbString("deselection") == fieldName) { self->selectionCB = Object::CB_DESELECTION; self->selection = (SoSelection*) fc; self->selection->ref(); self->selection->addDeselectionCallback(selectionPathCB, self); fc = 0; } else if (SbString("start") == fieldName) { self->selectionCB = Object::CB_START; self->selection = (SoSelection*) fc; self->selection->ref(); self->selection->addStartCallback(selectionClassCB, self); fc = 0; } else if (SbString("finish") == fieldName) { self->selectionCB = Object::CB_FINISH; self->selection = (SoSelection*)fc; self->selection->ref(); self->selection->addFinishCallback(selectionClassCB, self); fc = 0; } } if (fc && fieldName) { field = fc->getField(fieldName); } if ((fc && !fieldName) || field) { if (self->sensor) { delete self->sensor; self->sensor = 0; } if (field) { self->sensor = new SoFieldSensor(sensorCBFunc, self); ((SoFieldSensor*) self->sensor)->attach(field); } else { self->sensor = new SoNodeSensor(sensorCBFunc, self); ((SoNodeSensor*) self->sensor)->attach((SoNode*) fc); } } } Py_INCREF(Py_None); return Py_None; } PyObject* PySensor::detach(Object *self) { if (self->sensor) { delete self->sensor; self->sensor = 0; } Py_INCREF(Py_None); return Py_None; } PyObject* PySensor::set_interval(Object *self, PyObject *args) { double interval = 0.; if (PyArg_ParseTuple(args, "d", &interval)) { if (self->sensor) { delete self->sensor; self->sensor = 0; } self->sensor = new SoTimerSensor(sensorCBFunc, self); ((SoTimerSensor*) self->sensor)->setInterval(SbTime(interval)); } Py_INCREF(Py_None); return Py_None; } PyObject* PySensor::set_time(Object *self, PyObject *args) { double time = 0.; if (PyArg_ParseTuple(args, "d", &time)) { if (self->sensor) { delete self->sensor; self->sensor = 0; } self->sensor = new SoAlarmSensor(sensorCBFunc, self); ((SoAlarmSensor*) self->sensor)->setTimeFromNow(SbTime(time)); } Py_INCREF(Py_None); return Py_None; } PyObject* PySensor::schedule(Object *self) { if (self->sensor && !self->sensor->isScheduled()) { self->sensor->schedule(); } Py_INCREF(Py_None); return Py_None; } PyObject* PySensor::unschedule(Object *self) { if (self->sensor && self->sensor->isScheduled()) { self->sensor->unschedule(); } Py_INCREF(Py_None); return Py_None; } PyObject* PySensor::is_scheduled(Object *self) { long val = 0; if (self->sensor) { val = self->sensor->isScheduled(); } return PyBool_FromLong(val); } <commit_msg>Optional callback argument for attach()<commit_after>/** * \file * \brief PySensor class implementation. * \author Thomas Moeller * \details * * Copyright (C) the PyInventor contributors. All rights reserved. * This file is part of PyInventor, distributed under the BSD 3-Clause * License. For full terms see the included COPYING file. */ #include <Inventor/sensors/SoSensors.h> #include <Inventor/fields/SoFieldContainer.h> #include <Inventor/nodes/SoSelection.h> #include "PySensor.h" #include "PyPath.h" #pragma warning ( disable : 4127 ) // conditional expression is constant in Py_DECREF #pragma warning ( disable : 4244 ) // possible loss of data when converting int to short in SbVec2s PyTypeObject *PySensor::getType() { static PyMemberDef members[] = { {"callback", T_OBJECT_EX, offsetof(Object, callback), 0, "Sensor callback function.\n" "\n" "An object can be assigned to that property which is called when a\n" "sensor is triggered.\n" }, {NULL} /* Sentinel */ }; static PyMethodDef methods[] = { {"attach", (PyCFunction) attach, METH_VARARGS, "Attaches sensor/callback to node or field. The callback is triggered\n" "when the attached node or field changes. If only a Node instance is\n" "given then the sensor triggers on any change of that node or children.\n" "If both a scene object instance and a field or callback name are passed,\n" "the sensor triggers on field changes only.\n" "For Selection nodes the names 'selection', 'deselection', 'start'\n" "'finish' are also accepted to register the corresponding callbacks.\n" "\n" "Args:\n" " - node: Scene object instance to attach to.\n" " - name: Optional field name (or callback for Selection node).\n" " - func: The callback function can also be passed as argument\n" " instead of assigning the callback property.\n" }, {"detach", (PyCFunction) detach, METH_NOARGS, "Deactivates a sensor.\n" }, {"set_interval", (PyCFunction) set_interval, METH_VARARGS, "Sets up a timer sensor with a regular interval.\n" "\n" "Args:\n" " Timer interval in milliseconds.\n" }, {"set_time", (PyCFunction) set_time, METH_VARARGS, "Sets up an alarm sensor that is trigegred at a given time from now.\n" "\n" "Args:\n" " Timer from now in milliseconds when the sensor will be triggered.\n" }, {"schedule", (PyCFunction) schedule, METH_NOARGS, "Schedules a timer sensor." }, {"unschedule", (PyCFunction) unschedule, METH_NOARGS, "Unschedules a timer sensor." }, {"is_scheduled", (PyCFunction) is_scheduled, METH_NOARGS, "Returns scheduled state of the sensor.\n" "\n" "Returns:\n" " True is sensor is currently scheduled, otherwise False.\n" }, {NULL} /* Sentinel */ }; static PyTypeObject sensorType = { PyVarObject_HEAD_INIT(NULL, 0) "Sensor", /* tp_name */ sizeof(Object), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor) tp_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, //(setattrofunc)tp_setattro, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ "Represents node, field, timer and alarm sensors.\n" "\n" "Sensors can be used to observe changes in scene graphs or to trigger actions\n" "at given times.\n", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ methods, /* tp_methods */ members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc) tp_init, /* tp_init */ 0, /* tp_alloc */ tp_new, /* tp_new */ }; return &sensorType; } void PySensor::unregisterSelectionCB(Object *self) { if (self->selection) { switch (self->selectionCB) { case Object::CB_SELECTION: self->selection->removeSelectionCallback(selectionPathCB, self); break; case Object::CB_DESELECTION: self->selection->removeDeselectionCallback(selectionPathCB, self); break; case Object::CB_START: self->selection->removeStartCallback(selectionClassCB, self); break; case Object::CB_FINISH: self->selection->removeFinishCallback(selectionClassCB, self); break; } self->selection->unref(); self->selection = 0; } } void PySensor::tp_dealloc(Object* self) { if (self->sensor) { delete self->sensor; } unregisterSelectionCB(self); Py_XDECREF(self->callback); Py_TYPE(self)->tp_free((PyObject*)self); } PyObject* PySensor::tp_new(PyTypeObject *type, PyObject* /*args*/, PyObject* /*kwds*/) { PySceneObject::initSoDB(); Object *self = (Object *)type->tp_alloc(type, 0); if (self != NULL) { self->callback = 0; self->sensor = 0; self->selection = 0; self->selectionCB = Object::CB_SELECTION; } return (PyObject *) self; } int PySensor::tp_init(Object *self, PyObject *args, PyObject * /*kwds*/) { Py_INCREF(Py_None); self->callback = Py_None; attach(self, args); return 0; } void PySensor::sensorCBFunc(void *userdata, SoSensor* /*sensor*/) { Object *self = (Object *) userdata; if ((self != NULL) && (self->callback != NULL) && PyCallable_Check(self->callback)) { PyObject *value = PyObject_CallObject(self->callback, NULL); if (value != NULL) { Py_DECREF(value); } } } void PySensor::selectionPathCB(void * userdata, SoPath * path) { Object *self = (Object *)userdata; if ((self != NULL) && (self->callback != NULL) && PyCallable_Check(self->callback)) { PyObject *value = PyObject_CallObject(self->callback, Py_BuildValue("(O)", PyPath::createWrapper(path))); if (value != NULL) { Py_DECREF(value); } } } void PySensor::selectionClassCB(void * userdata, SoSelection * sel) { Object *self = (Object *)userdata; if ((self != NULL) && (self->callback != NULL) && PyCallable_Check(self->callback)) { PyObject *value = PyObject_CallObject(self->callback, Py_BuildValue("(O)", PySceneObject::createWrapper(sel))); if (value != NULL) { Py_DECREF(value); } } } PyObject* PySensor::attach(Object *self, PyObject *args) { PyObject *node = 0, *callback = 0; char *fieldName = 0; if (PyArg_ParseTuple(args, "O|sO", &node, &fieldName, &callback)) { SoFieldContainer *fc = 0; SoField *field = 0; if (node && PySceneObject_Check(node)) { fc = ((PySceneObject::Object*) node)->inventorObject; } if (fc && fieldName && fc->isOfType(SoSelection::getClassTypeId())) { unregisterSelectionCB(self); if (SbString("selection") == fieldName) { self->selectionCB = Object::CB_SELECTION; self->selection = (SoSelection*) fc; self->selection->ref(); self->selection->addSelectionCallback(selectionPathCB, self); fc = 0; } else if (SbString("deselection") == fieldName) { self->selectionCB = Object::CB_DESELECTION; self->selection = (SoSelection*) fc; self->selection->ref(); self->selection->addDeselectionCallback(selectionPathCB, self); fc = 0; } else if (SbString("start") == fieldName) { self->selectionCB = Object::CB_START; self->selection = (SoSelection*) fc; self->selection->ref(); self->selection->addStartCallback(selectionClassCB, self); fc = 0; } else if (SbString("finish") == fieldName) { self->selectionCB = Object::CB_FINISH; self->selection = (SoSelection*)fc; self->selection->ref(); self->selection->addFinishCallback(selectionClassCB, self); fc = 0; } } if (fc && fieldName) { field = fc->getField(fieldName); } if ((fc && !fieldName) || field) { if (self->sensor) { delete self->sensor; self->sensor = 0; } if (field) { self->sensor = new SoFieldSensor(sensorCBFunc, self); ((SoFieldSensor*) self->sensor)->attach(field); } else { self->sensor = new SoNodeSensor(sensorCBFunc, self); ((SoNodeSensor*) self->sensor)->attach((SoNode*) fc); } } // set callback attribute based on option third argument if (callback) { Py_XDECREF(self->callback); self->callback = callback; Py_INCREF(self->callback); } } Py_INCREF(Py_None); return Py_None; } PyObject* PySensor::detach(Object *self) { if (self->sensor) { delete self->sensor; self->sensor = 0; } unregisterSelectionCB(self); Py_INCREF(Py_None); return Py_None; } PyObject* PySensor::set_interval(Object *self, PyObject *args) { double interval = 0.; if (PyArg_ParseTuple(args, "d", &interval)) { if (self->sensor) { delete self->sensor; self->sensor = 0; } self->sensor = new SoTimerSensor(sensorCBFunc, self); ((SoTimerSensor*) self->sensor)->setInterval(SbTime(interval)); } Py_INCREF(Py_None); return Py_None; } PyObject* PySensor::set_time(Object *self, PyObject *args) { double time = 0.; if (PyArg_ParseTuple(args, "d", &time)) { if (self->sensor) { delete self->sensor; self->sensor = 0; } self->sensor = new SoAlarmSensor(sensorCBFunc, self); ((SoAlarmSensor*) self->sensor)->setTimeFromNow(SbTime(time)); } Py_INCREF(Py_None); return Py_None; } PyObject* PySensor::schedule(Object *self) { if (self->sensor && !self->sensor->isScheduled()) { self->sensor->schedule(); } Py_INCREF(Py_None); return Py_None; } PyObject* PySensor::unschedule(Object *self) { if (self->sensor && self->sensor->isScheduled()) { self->sensor->unschedule(); } Py_INCREF(Py_None); return Py_None; } PyObject* PySensor::is_scheduled(Object *self) { long val = 0; if (self->sensor) { val = self->sensor->isScheduled(); } return PyBool_FromLong(val); } <|endoftext|>
<commit_before>// AboutBox.cpp // Copyright (c) 2009, Dan Heeks // This program is released under the BSD license. See the file COPYING for details. #include "stdafx.h" #include "AboutBox.h" #include "HeeksFrame.h" BEGIN_EVENT_TABLE( CAboutBox, wxDialog ) EVT_BUTTON( wxID_OK, CAboutBox::OnButtonOK ) END_EVENT_TABLE() CAboutBox::CAboutBox(wxWindow *parent):wxDialog(parent, wxID_ANY, _T(""), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE) { wxPanel *panel = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); wxButton *ok_button = new wxButton(panel, wxID_OK, _("OK")); wxBoxSizer *mainsizer = new wxBoxSizer( wxVERTICAL ); wxTextCtrl* text_ctrl = new wxTextCtrl( this, wxID_ANY, _T(""), wxDefaultPosition, wxSize(800,600), wxTE_READONLY | wxTE_MULTILINE); wxString str = wxString(_T("HeeksCAD\n see http://heeks.net, or for source code: http://code.google.com/p/heekscad/\n\nusing Open CASCADE solid modeller - http://www.opencascade.org")) + wxString(_T("\n\nwindows made with wxWidgets 2.8.9 - http://wxwidgets.org")) + wxString(_T("\n\ntext uses glFont Copyright (c) 1998 Brad Fish E-mail: [email protected] Web: http://students.cs.byu.edu/~bfish/")) + wxString(_T("\n\nWritten by:\n Dan Heeks\n Jon Pry\n Jonathan George\n David Nicholls")) + wxString(_T("\n\nWith contributions from:\n Hirutso Enni\n Perttu Ahola\n Dave ( the archivist )\n mpictor\n fenn\n fungunner2\n andrea ( openSUSE )\n g_code luigi barbati")) + wxString(_T("\n\nThis is free, open source software.")); wxString version_str = wxGetApp().m_version_number; version_str.Replace(_T(" "), _T(".")); this->SetTitle(version_str); text_ctrl->WriteText(str + wxGetApp().m_frame->m_extra_about_box_str); //mainsizer->Add( text_ctrl, wxSizerFlags().Align(wxALIGN_CENTER).Border(wxALL, 10).Expand() ); //mainsizer->Add( ok_button, wxSizerFlags().Align(wxALIGN_CENTER) ); mainsizer->Add( text_ctrl ); mainsizer->Add( ok_button ); mainsizer->RecalcSizes(); // tell frame to make use of sizer (or constraints, if any) panel->SetAutoLayout( true ); panel->SetSizer( mainsizer ); #ifndef __WXWINCE__ // don't allow frame to get smaller than what the sizers tell ye mainsizer->SetSizeHints( this ); #endif Show(true); } void CAboutBox::OnButtonOK(wxCommandEvent& event) { EndModal(wxID_OK); } <commit_msg>small correction<commit_after>// AboutBox.cpp // Copyright (c) 2009, Dan Heeks // This program is released under the BSD license. See the file COPYING for details. #include "stdafx.h" #include "AboutBox.h" #include "HeeksFrame.h" BEGIN_EVENT_TABLE( CAboutBox, wxDialog ) EVT_BUTTON( wxID_OK, CAboutBox::OnButtonOK ) END_EVENT_TABLE() CAboutBox::CAboutBox(wxWindow *parent):wxDialog(parent, wxID_ANY, _T(""), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE) { wxPanel *panel = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); wxButton *ok_button = new wxButton(panel, wxID_OK, _("OK")); wxBoxSizer *mainsizer = new wxBoxSizer( wxVERTICAL ); wxTextCtrl* text_ctrl = new wxTextCtrl( this, wxID_ANY, _T(""), wxDefaultPosition, wxSize(800,600), wxTE_READONLY | wxTE_MULTILINE); wxString str = wxString(_T("HeeksCAD\n see http://heeks.net, or for source code: http://code.google.com/p/heekscad/\n\nusing Open CASCADE solid modeller - http://www.opencascade.org")) + wxString(_T("\n\nwindows made with wxWidgets 2.8.9 - http://wxwidgets.org")) + wxString(_T("\n\ntext uses glFont Copyright (c) 1998 Brad Fish E-mail: [email protected] Web: http://students.cs.byu.edu/~bfish/")) + wxString(_T("\n\nWritten by:\n Dan Heeks\n Jon Pry\n Jonathan George\n David Nicholls")) + wxString(_T("\n\nWith contributions from:\n Hirutso Enni\n Perttu Ahola\n Dave ( the archivist )\n mpictor\n fenn\n fungunner2\n andrea ( openSUSE )\n g_code\n luigi barbati")) + wxString(_T("\n\nThis is free, open source software.")); wxString version_str = wxGetApp().m_version_number; version_str.Replace(_T(" "), _T(".")); this->SetTitle(version_str); text_ctrl->WriteText(str + wxGetApp().m_frame->m_extra_about_box_str); //mainsizer->Add( text_ctrl, wxSizerFlags().Align(wxALIGN_CENTER).Border(wxALL, 10).Expand() ); //mainsizer->Add( ok_button, wxSizerFlags().Align(wxALIGN_CENTER) ); mainsizer->Add( text_ctrl ); mainsizer->Add( ok_button ); mainsizer->RecalcSizes(); // tell frame to make use of sizer (or constraints, if any) panel->SetAutoLayout( true ); panel->SetSizer( mainsizer ); #ifndef __WXWINCE__ // don't allow frame to get smaller than what the sizers tell ye mainsizer->SetSizeHints( this ); #endif Show(true); } void CAboutBox::OnButtonOK(wxCommandEvent& event) { EndModal(wxID_OK); } <|endoftext|>
<commit_before>#ifndef _BTN_CONTROLLER_HPP_ #define _BTN_CONTROLLER_HPP_ /*****************************************************************************/ enum class FigureID; #include <windows.h> #include <string> #include <vector> #include <array> /*****************************************************************************/ // , class BtnController { public: // enum ButtonID { BTN_UNKNOWN = -1, BTN_LINE, BTN_ELLIPSE, BTN_RECTANGLE, N_OF_BUTTONS, }; // , explicit BtnController(); void CreateWindows( const HWND _parentWindow ); // ButtonID HandleClick( const UINT _message, const WPARAM _wParam, const LPARAM _lParam ); private: // struct ButtonInfo { std::basic_string< TCHAR > m_name; // LONG m_style; // HWND m_hWnd; // }; // std::array< ButtonInfo, (SIZE_T)ButtonID::N_OF_BUTTONS > m_buttons; void InitButtons(); }; #endif // _BTN_CONTROLLER_HPP_ /*****************************************************************************/ <commit_msg>Fixed encoding<commit_after>#ifndef _BTN_CONTROLLER_HPP_ #define _BTN_CONTROLLER_HPP_ /*****************************************************************************/ enum class FigureID; #include <windows.h> #include <string> #include <vector> #include <array> /*****************************************************************************/ // Класс, который занимается хранением и обработкой всех кнопок class BtnController { public: // Идентификатоы всех поддерживаемых кнопок enum ButtonID { BTN_UNKNOWN = -1, BTN_LINE, BTN_ELLIPSE, BTN_RECTANGLE, N_OF_BUTTONS, }; // Конструктор, заполняет контейнер с информацией о кнопках explicit BtnController(); void CreateWindows( const HWND _parentWindow ); // Обрабатывает сообщения о нажатии кнопки ButtonID HandleClick( const UINT _message, const WPARAM _wParam, const LPARAM _lParam ); private: // Структура с информацией о кнопке struct ButtonInfo { std::basic_string< TCHAR > m_name; // имя кнопки LONG m_style; // стиль кнопки HWND m_hWnd; // описатель окна кнопки }; // Массив кнопок std::array< ButtonInfo, (SIZE_T)ButtonID::N_OF_BUTTONS > m_buttons; void InitButtons(); }; #endif // _BTN_CONTROLLER_HPP_ /*****************************************************************************/ <|endoftext|>
<commit_before>#include <string.h> #include <iostream> #include <fstream> #include <vector> #include <stdio.h> #include <sstream> #include <arpa/inet.h> #include <unistd.h> #include <sys/epoll.h> #include <errno.h> #include <openssl/ec.h> #include <openssl/bn.h> #include <openssl/objects.h> #include "rapidjson/document.h" #include "rapidjson/prettywriter.h" #include "base64.h" #define B64SIZE 64 #define TOKENSIZE 162 using namespace std; using namespace rapidjson; #define MACHINE_IP inet_addr("127.0.0.1") #define PORT_SUBJECT 49151 vector<string> split(string str, char delimiter) { vector<string> internal; stringstream ss(str); string tok; while(getline(ss, tok, delimiter)) { internal.push_back(tok); } return internal; } int sign(Document* d) { const char private_key[] = "F2506E09D4153EED5ACBE1D620C93CA0D5580EF41AC0A401"; const char pub_key[] = "027134EE605CB10FAE017BDD9FD88C96C8C080F08271637BB1"; //hex pub key from Sajin's message ECDSA_SIG *sig; char sig_str[B64SIZE]; BN_CTX *ctx; EVP_MD_CTX* mdctx; const EVP_MD* md; unsigned char md_value[EVP_MAX_MD_SIZE]; unsigned int md_len, buf_len; EC_KEY* auth_key; Value si; auth_key = EC_KEY_new_by_curve_name(NID_X9_62_prime192v3); if (auth_key == NULL) { printf("failed to initialize curve\n"); return 1; } ctx = BN_CTX_new(); if(!ctx) { printf("failed to create bn ctx\n"); return 1; } EC_POINT_hex2point(EC_KEY_get0_group(auth_key),pub_key, NULL, ctx); //hex pub key from Sajin's message BN_CTX_free(ctx); StringBuffer buffer; Writer<StringBuffer> writer(buffer); d->Accept(writer); printf("sig is signing: %s\n", buffer.GetString()); OpenSSL_add_all_digests(); md = EVP_get_digestbyname("sha256"); if(md == 0) { printf("Unknown message digest\n"); return 1; } mdctx = EVP_MD_CTX_create(); EVP_DigestInit_ex(mdctx, md, NULL); EVP_DigestUpdate(mdctx, buffer.GetString(), buffer.GetSize()); EVP_DigestFinal_ex(mdctx, md_value, &md_len); EVP_MD_CTX_destroy(mdctx); printf("digest: "); dump_mem(md_value, md_len); buf_len = ECDSA_size(auth_key); sig = ECDSA_do_sign(md_value, md_len, auth_key); if (sig == NULL) { printf("Signing failed\n"); return 1; } base64encode(sig_str, sig->r, sig->s); si.SetString(sig_str, B64SIZE, d->GetAllocator()); d->AddMember("si", si, d->GetAllocator()); printf("sig: %s, %s\n", BN_bn2hex(sig->r), BN_bn2hex(sig->s)); } int bootstrap_network(const char* port_sub){ int soc,response_length,n; char *response; uint16_t port = strtol(port_sub, NULL, 10); // from arguments // cout << "port no: " << port << "\n"; soc = socket(AF_INET, SOCK_STREAM, 0); if (soc == -1) { printf("Failed to open socket\n"); return 1; } struct sockaddr_in connectAddress; memset(&connectAddress, 0, sizeof(connectAddress)); connectAddress.sin_family = AF_INET; connectAddress.sin_addr.s_addr = MACHINE_IP; connectAddress.sin_port = htons(port); // cout << connectAddress.sin_addr.s_addr << "\t" << connectAddress.sin_port << "\n"; if(bind(soc, (struct sockaddr *) &connectAddress, sizeof(connectAddress)) == -1) { printf("bootstrap: Failed to bind\n"); exit(1); } if(listen(soc, 5) == -1) { printf( "bootstrap: Failed to listen\n"); exit(1); } return soc; } char* get_request(int fd) { char* message; size_t size = TOKENSIZE; int offset; message = (char*) realloc(NULL, sizeof(char)*size); if(!message) { printf("get_request: Failure to realloc\n"); exit(1); } offset = -1; do { offset++; if (offset == size) { message = (char*) realloc(message, sizeof(char)*(size += 16)); //?? if(!message) { printf("get_request: Failure to realloc\n"); exit(1); } } if(read(fd, message+offset, 1) <= 0) { printf("get_request: EOF encountered\n"); char c = message[offset]; message[offset] = 0; printf("story so far (%d): %s%c\n", offset, message, c); exit(1); } } while (message[offset] != 0); printf("DEBUG: get_request: message at %p: %s\n", message, message); return message; } int listen_block1(int soc) { int fd; socklen_t peer_addr_size = sizeof(struct sockaddr_in); char * sub_request; unsigned char response; struct sockaddr_in retAddress; printf("DEBUG: entering network loop\n"); while(true) { printf("DEBUG: network loop: accepting connection...\n"); fd = accept(soc, (struct sockaddr *) &retAddress, &peer_addr_size); if( fd == -1) { printf("listen: Failed to accept: %s\n", strerror(errno)); exit(1); } printf( "DEBUG: network loop: connection accepted, getting request from subject...\n"); sub_request = get_request(fd); } string message = sub_request; vector<string> sep = split(message, '\n'); const char * pub_key = sep[0].c_str(); const char * res_add = sep[1].c_str(); cout << "public key (b64): " << pub_key << "\n"; cout << "resource address: " << res_add << "\n"; Document d; Value ii, nb, na, suv, dev; char su[B64SIZE]; unsigned int now; d.Parse("{}"); now = time(NULL); ii.SetInt(now); nb.SetInt(now); na.SetInt(1600000000); suv.SetString(pub_key, B64SIZE, d.GetAllocator()); dev.SetString(res_add, B64SIZE, d.GetAllocator()); d.AddMember("id", "fake identifier", d.GetAllocator()); d.AddMember("ii", ii, d.GetAllocator()); d.AddMember("is", "fake issuer", d.GetAllocator()); d.AddMember("su", suv, d.GetAllocator()); d.AddMember("de", dev, d.GetAllocator()); d.AddMember("ar", "fake access rights", d.GetAllocator()); d.AddMember("nb", nb, d.GetAllocator()); d.AddMember("na", na, d.GetAllocator()); sign(&d); StringBuffer buffer; Writer<StringBuffer> writer(buffer); d.Accept(writer); if(write(soc, buffer.GetString(), buffer.GetSize()+1) < 0) { printf("Failed to write to socket\n"); //return 1; } } int listen_block2(int soc){ printf("block2\n"); return 1; } int main(int argc, char *argv[]) { int soc = bootstrap_network(argv[1]); if(!strcmp(argv[2], "1")) listen_block1(soc); else if(!strcmp(argv[2], "2")) listen_block2(soc); else { printf("Invalid mode: %s", argv[2]); exit(1); } return 1; } <commit_msg>moved the write code<commit_after>#include <string.h> #include <iostream> #include <fstream> #include <vector> #include <stdio.h> #include <sstream> #include <arpa/inet.h> #include <unistd.h> #include <sys/epoll.h> #include <errno.h> #include <openssl/ec.h> #include <openssl/bn.h> #include <openssl/objects.h> #include "rapidjson/document.h" #include "rapidjson/prettywriter.h" #include "base64.h" #define B64SIZE 64 #define TOKENSIZE 162 using namespace std; using namespace rapidjson; #define MACHINE_IP inet_addr("127.0.0.1") #define PORT_SUBJECT 49151 vector<string> split(string str, char delimiter) { vector<string> internal; stringstream ss(str); string tok; while(getline(ss, tok, delimiter)) { internal.push_back(tok); } return internal; } int sign(Document* d) { const char private_key[] = "F2506E09D4153EED5ACBE1D620C93CA0D5580EF41AC0A401"; const char pub_key[] = "027134EE605CB10FAE017BDD9FD88C96C8C080F08271637BB1"; ECDSA_SIG *sig; char sig_str[B64SIZE]; BN_CTX *ctx; EVP_MD_CTX* mdctx; const EVP_MD* md; unsigned char md_value[EVP_MAX_MD_SIZE]; unsigned int md_len, buf_len; EC_KEY* auth_key; Value si; auth_key = EC_KEY_new_by_curve_name(NID_X9_62_prime192v3); if (auth_key == NULL) { printf("failed to initialize curve\n"); return 1; } ctx = BN_CTX_new(); if(!ctx) { printf("failed to create bn ctx\n"); return 1; } EC_POINT_hex2point(EC_KEY_get0_group(auth_key),pub_key, NULL, ctx); BN_CTX_free(ctx); StringBuffer buffer; Writer<StringBuffer> writer(buffer); d->Accept(writer); printf("sig is signing: %s\n", buffer.GetString()); OpenSSL_add_all_digests(); md = EVP_get_digestbyname("sha256"); if(md == 0) { printf("Unknown message digest\n"); return 1; } mdctx = EVP_MD_CTX_create(); EVP_DigestInit_ex(mdctx, md, NULL); EVP_DigestUpdate(mdctx, buffer.GetString(), buffer.GetSize()); EVP_DigestFinal_ex(mdctx, md_value, &md_len); EVP_MD_CTX_destroy(mdctx); printf("digest: "); dump_mem(md_value, md_len); buf_len = ECDSA_size(auth_key); sig = ECDSA_do_sign(md_value, md_len, auth_key); if (sig == NULL) { printf("Signing failed\n"); return 1; } base64encode(sig_str, sig->r, sig->s); si.SetString(sig_str, B64SIZE, d->GetAllocator()); d->AddMember("si", si, d->GetAllocator()); printf("sig: %s, %s\n", BN_bn2hex(sig->r), BN_bn2hex(sig->s)); } int bootstrap_network(const char* port_sub){ int soc,response_length,n; char *response; uint16_t port = strtol(port_sub, NULL, 10); // from arguments // cout << "port no: " << port << "\n"; soc = socket(AF_INET, SOCK_STREAM, 0); if (soc == -1) { printf("Failed to open socket\n"); return 1; } struct sockaddr_in connectAddress; memset(&connectAddress, 0, sizeof(connectAddress)); connectAddress.sin_family = AF_INET; connectAddress.sin_addr.s_addr = MACHINE_IP; connectAddress.sin_port = htons(port); // cout << connectAddress.sin_addr.s_addr << "\t" << connectAddress.sin_port << "\n"; if(bind(soc, (struct sockaddr *) &connectAddress, sizeof(connectAddress)) == -1) { printf("bootstrap: Failed to bind\n"); exit(1); } if(listen(soc, 5) == -1) { printf( "bootstrap: Failed to listen\n"); exit(1); } return soc; } int get_request(int fd,int soc) { char* message; size_t size = TOKENSIZE; int offset; message = (char*) realloc(NULL, sizeof(char)*size); if(!message) { printf("get_request: Failure to realloc\n"); exit(1); } offset = -1; do { offset++; if (offset == size) { message = (char*) realloc(message, sizeof(char)*(size += 16)); //?? if(!message) { printf("get_request: Failure to realloc\n"); exit(1); } } if(read(fd, message+offset, 1) <= 0) { printf("get_request: EOF encountered\n"); char c = message[offset]; message[offset] = '\0'; printf("story so far (%d): %s%c\n", offset, message, c); exit(1); } } while (message[offset] != '\0'); printf("DEBUG: get_request: message at %p: %s\n", message, message); // return message; //string message = sub_request; vector<string> sep = split(message, '\n'); const char * pub_key = sep[0].c_str(); const char * res_add = sep[1].c_str(); cout << "public key (b64): " << pub_key << "\n"; cout << "resource address: " << res_add << "\n"; Document d; Value ii, nb, na, suv, dev; char su[B64SIZE]; unsigned int now; d.Parse("{}"); now = time(NULL); ii.SetInt(now); nb.SetInt(now); na.SetInt(1600000000); suv.SetString(pub_key, B64SIZE, d.GetAllocator()); dev.SetString(res_add, (offset - B64SIZE -1), d.GetAllocator()); d.AddMember("id", "fake identifier", d.GetAllocator()); d.AddMember("ii", ii, d.GetAllocator()); d.AddMember("is", "fake issuer", d.GetAllocator()); d.AddMember("su", suv, d.GetAllocator()); d.AddMember("de", dev, d.GetAllocator()); d.AddMember("ar", "fake access rights", d.GetAllocator()); d.AddMember("nb", nb, d.GetAllocator()); d.AddMember("na", na, d.GetAllocator()); sign(&d); StringBuffer buffer; Writer<StringBuffer> writer(buffer); d.Accept(writer); cout << "buffer data : "<< buffer.GetString() ; cout << "\n buffer len:" << buffer.GetSize(); if(write(soc, buffer.GetString(), buffer.GetSize()+1) < 0) { printf("Failed to write to socket\n"); //else printf("Requested token sent back to subject"); } return 1; } int listen_block1(int soc) { int fd; socklen_t peer_addr_size = sizeof(struct sockaddr_in); char * sub_request; unsigned char response; struct sockaddr_in retAddress; printf("DEBUG: entering network loop\n"); while(true) { printf("DEBUG: network loop: accepting connection...\n"); fd = accept(soc, (struct sockaddr *) &retAddress, &peer_addr_size); if( fd == -1) { printf("listen: Failed to accept: %s\n", strerror(errno)); exit(1); } printf( "DEBUG: network loop: connection accepted, getting request from subject...\n"); get_request(fd,soc); } /* string message = sub_request; vector<string> sep = split(message, '\n'); const char * pub_key = sep[0].c_str(); const char * res_add = sep[1].c_str(); cout << "public key (b64): " << pub_key << "\n"; cout << "resource address: " << res_add << "\n"; Document d; Value ii, nb, na, suv, dev; char su[B64SIZE]; unsigned int now; d.Parse("{}"); now = time(NULL); ii.SetInt(now); nb.SetInt(now); na.SetInt(1600000000); suv.SetString(pub_key, B64SIZE, d.GetAllocator()); dev.SetString(res_add, B64SIZE, d.GetAllocator()); d.AddMember("id", "fake identifier", d.GetAllocator()); d.AddMember("ii", ii, d.GetAllocator()); d.AddMember("is", "fake issuer", d.GetAllocator()); d.AddMember("su", suv, d.GetAllocator()); d.AddMember("de", dev, d.GetAllocator()); d.AddMember("ar", "fake access rights", d.GetAllocator()); d.AddMember("nb", nb, d.GetAllocator()); d.AddMember("na", na, d.GetAllocator()); sign(&d); StringBuffer buffer; Writer<StringBuffer> writer(buffer); d.Accept(writer); if(write(soc, buffer.GetString(), buffer.GetSize()+1) < 0) { printf("Failed to write to socket\n"); else printf("Requested token sent back to subject"); //return 1;*/ //} } int listen_block2(int soc){ printf("block2\n"); return 1; } int main(int argc, char *argv[]) { int soc = bootstrap_network(argv[1]); if(!strcmp(argv[2], "1")) listen_block1(soc); else if(!strcmp(argv[2], "2")) listen_block2(soc); else { printf("Invalid mode: %s", argv[2]); exit(1); } return 1; } <|endoftext|>
<commit_before><commit_msg>App: allow link properties for all App::Link<commit_after><|endoftext|>
<commit_before>// Copyright *********************************************************** // // File ecmdClientCapi.C // // IBM Confidential // OCO Source Materials // 9400 Licensed Internal Code // (C) COPYRIGHT IBM CORP. 1996 // // The source code for this program is not published or otherwise // divested of its trade secrets, irrespective of what has been // deposited with the U.S. Copyright Office. // // End Copyright ******************************************************* // Module Description ************************************************** // // Description: // // End Module Description ********************************************** //---------------------------------------------------------------------- // Includes //---------------------------------------------------------------------- #include <dlfcn.h> #include <string> #include <stdio.h> #include <ecmdClientCapi.H> #include <ecmdDllCapi.H> //---------------------------------------------------------------------- // User Types //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Constants //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Macros //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Internal Function Prototypes //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Global Variables //---------------------------------------------------------------------- //--------------------------------------------------------------------- // Member Function Specifications //--------------------------------------------------------------------- // Change Log ********************************************************* // // Flag Reason Vers Date Coder Description // ---- -------- ---- -------- -------- ------------------------------ // CENGEL Initial Creation // // End Change Log ***************************************************** typedef enum { ECMD_QUERYCONFIG, ECMD_QUERYRING, ECMD_QUERYARRAY, ECMD_QUERYSPY, ECMD_QUERYFILELOCATION, ECMD_GETRING, ECMD_PUTRING, ECMD_RINGREAD, ECMD_RINGWRITE, ECMD_GETSCOM, ECMD_PUTSCOM, ECMD_GETSPY, ECMD_GETSPYENUM, ECMD_PUTSPY, ECMD_PUTSPYENUM, ECMD_GETARRAY, ECMD_PUTARRAY, ECMD_FLUSHSYS, ECMD_IPLSYS, ECMD_REGISTERERRORMSG, ECMD_NUMFUNCTIONS } ecmdFunctionIndex_t; void * dlHandle = NULL; void * DllFnTable[ECMD_NUMFUNCTIONS]; int ecmdLoadDll(string dllName) { const char* dlError; int rc = ECMD_SUCCESS; #ifndef LINUX /* clean up the machine from previous tests */ system("slibclean"); #endif /* --------------------- */ /* load DLL */ /* --------------------- */ char dllname[256]; if (dllName.size() == 0) { /* Let's try to get it from the env var */ char * tempptr = getenv("ECMD_DLL_FILE"); /* is there a ECMD_DLL_FILE environment variable? */ if (tempptr != NULL) { dllName = tempptr; } else { fprintf(stderr,"ecmdLoadDll: Unable to find DLL to load, you must set ECMD_DLL_FILE\n"); return ECMD_INVALID_DLL_FILENAME; } } printf("loadDll: loading %s ...\n", dllname); dlHandle = dlopen(dllname, RTLD_NOW); if (!dlHandle) { if ((dlError = dlerror()) != NULL) { printf("ERROR: loadDll: %s\n", dlError); return ECMD_DLL_LOAD_FAILURE; } } else { printf("loadDll: load successful\n"); } } int ecmdUnloadDll() { int rc = ECMD_SUCCESS; int c_rc = ECMD_SUCCESS; /* call DLL cleanup int (*Function)() = (int(*)())DllFnTable[ECMD_UNLOADDLL]; rc = (*Function)(); */ /* release DLL */ const char* dlError; c_rc = dlclose(dlHandle); if (c_rc) { if ((dlError = dlerror()) != NULL) { fprintf(stderr,"ERROR: ecmdUnloadDll: %s\n", dlError); return ECMD_DLL_UNLOAD_FAILURE; } } dlHandle = NULL; return rc; } int ecmdQueryConfig(ecmdChipTarget & target, vector<ecmdCageData> & queryData) { int rc; #ifdef ECMD_STATIC_FUNCTIONS rc = dllQueryConfig(target, queryData); #else if (dlHandle == NULL) { return ECMD_DLL_UNINITIALIZED; } if (DllFnTable[ECMD_QUERYCONFIG] == NULL) { DllFnTable[ECMD_QUERYCONFIG] = (void*)dlsym(dlHandle, "dllQueryConfig"); } int (*Function)(ecmdChipTarget &, vector<ecmdCageData> &) = (int(*)(ecmdChipTarget &, vector<ecmdCageData> &))DllFnTable[ECMD_QUERYCONFIG]; rc = (*Function)(target, queryData); #endif return rc; } int ecmdQueryRing(ecmdChipTarget & target, vector<ecmdRingData> & queryData, const char * ringName ) { int rc; #ifdef ECMD_STATIC_FUNCTIONS rc = dllQueryRing(target, queryData, ringName); #else if (dlHandle == NULL) { return ECMD_DLL_UNINITIALIZED; } if (DllFnTable[ECMD_QUERYRING] == NULL) { DllFnTable[ECMD_QUERYRING] = (void*)dlsym(dlHandle, "dllQueryRing"); } int (*Function)(ecmdChipTarget &, vector<ecmdRingData> &, const char *) = (int(*)(ecmdChipTarget &, vector<ecmdRingData> &, const char *))DllFnTable[ECMD_QUERYRING]; rc = (*Function)(target, queryData, ringName); #endif return rc; } int ecmdQueryArray(ecmdChipTarget & target, vector<ecmdArrayData> & queryData, const char * arrayName) { int rc; #ifdef ECMD_STATIC_FUNCTIONS rc = dllQueryArray(target, queryData, arrayName); #else if (dlHandle == NULL) { return ECMD_DLL_UNINITIALIZED; } if (DllFnTable[ECMD_QUERYARRAY] == NULL) { DllFnTable[ECMD_QUERYARRAY] = (void*)dlsym(dlHandle, "dllQueryArray"); } int (*Function)(ecmdChipTarget &, vector<ecmdArrayData> &, const char *) = (int(*)(ecmdChipTarget &, vector<ecmdArrayData> &, const char *))DllFnTable[ECMD_QUERYARRAY]; rc = (*Function)(target, queryData, arrayName); #endif return rc; } int ecmdQuerySpy(ecmdChipTarget & target, vector<ecmdSpyData> & queryData, const char * spyName) { int rc; #ifdef ECMD_STATIC_FUNCTIONS rc = dllQuerySpy(target, queryData, spyName); #else if (dlHandle == NULL) { return ECMD_DLL_UNINITIALIZED; } if (DllFnTable[ECMD_QUERYSPY] == NULL) { DllFnTable[ECMD_QUERYSPY] = (void*)dlsym(dlHandle, "dllQuerySpy"); } int (*Function)(ecmdChipTarget &, vector<ecmdSpyData> &, const char *) = (int(*)(ecmdChipTarget &, vector<ecmdSpyData> &, const char *))DllFnTable[ECMD_QUERYSPY]; rc = (*Function)(target, queryData, spyName); #endif return rc; } int ecmdQueryFileLocation(ecmdChipTarget & target, ecmdFileType_t fileType, string fileLocation) { int rc; #ifdef ECMD_STATIC_FUNCTIONS rc = dllQueryFileLocation(target, fileType, fileLocation); #else if (dlHandle == NULL) { return ECMD_DLL_UNINITIALIZED; } if (DllFnTable[ECMD_QUERYFILELOCATION] == NULL) { DllFnTable[ECMD_QUERYFILELOCATION] = (void*)dlsym(dlHandle, "dllQueryFileLocation"); } int (*Function)(ecmdChipTarget &, ecmdFileType_t, string) = (int(*)(ecmdChipTarget &, ecmdFileType_t, string))DllFnTable[ECMD_QUERYFILELOCATION]; rc = (*Function)(target, fileType, fileLocation); #endif return rc; } int getRing(ecmdChipTarget & target, const char * ringName, ecmdDataBuffer & data) { int rc; #ifdef ECMD_STATIC_FUNCTIONS rc = dllGetRing(target, ringName, data); #else if (dlHandle == NULL) { return ECMD_DLL_UNINITIALIZED; } if (DllFnTable[ECMD_GETRING] == NULL) { DllFnTable[ECMD_GETRING] = (void*)dlsym(dlHandle, "dllGetRing"); } int (*Function)(ecmdChipTarget &, const char *, ecmdDataBuffer &) = (int(*)(ecmdChipTarget &, const char *, ecmdDataBuffer &))DllFnTable[ECMD_GETRING]; rc = (*Function)(target, ringName, data); #endif return rc; } int putRing(ecmdChipTarget & target, const char * ringName, ecmdDataBuffer & data) { int rc; #ifdef ECMD_STATIC_FUNCTIONS rc = dllPutRing(target, ringName, data); #else if (dlHandle == NULL) { return ECMD_DLL_UNINITIALIZED; } if (DllFnTable[ECMD_PUTRING] == NULL) { DllFnTable[ECMD_PUTRING] = (void*)dlsym(dlHandle, "dllPutRing"); } int (*Function)(ecmdChipTarget &, const char *, ecmdDataBuffer &) = (int(*)(ecmdChipTarget &, const char *, ecmdDataBuffer &))DllFnTable[ECMD_PUTRING]; rc = (*Function)(target, ringName, data); #endif return rc; } int ringRead(ecmdChipTarget & target, const char * ringName, const char * fileName) { int rc; #ifdef ECMD_STATIC_FUNCTIONS rc = dllRingRead(target, ringName, fileName); #else if (dlHandle == NULL) { return ECMD_DLL_UNINITIALIZED; } if (DllFnTable[ECMD_RINGREAD] == NULL) { DllFnTable[ECMD_RINGREAD] = (void*)dlsym(dlHandle, "dllRingRead"); } int (*Function)(ecmdChipTarget &, const char *, const char *) = (int(*)(ecmdChipTarget &, const char *, const char *))DllFnTable[ECMD_RINGREAD]; rc = (*Function)(target, ringName, fileName); #endif return rc; } int ringWrite(ecmdChipTarget & target, const char * ringName, const char * fileName) { int rc; #ifdef ECMD_STATIC_FUNCTIONS rc = dllRingWrite(target, ringName, fileName); #else if (dlHandle == NULL) { return ECMD_DLL_UNINITIALIZED; } if (DllFnTable[ECMD_RINGWRITE] == NULL) { DllFnTable[ECMD_RINGWRITE] = (void*)dlsym(dlHandle, "dllRingWrite"); } int (*Function)(ecmdChipTarget &, const char *, const char *) = (int(*)(ecmdChipTarget &, const char *, const char *))DllFnTable[ECMD_RINGWRITE]; rc = (*Function)(target, ringName, fileName); #endif return rc; } int getScom(ecmdChipTarget & target, uint32_t address, ecmdDataBuffer & data) { int rc; #ifdef ECMD_STATIC_FUNCTIONS rc = dllGetScom(target, address, data); #else if (dlHandle == NULL) { return ECMD_DLL_UNINITIALIZED; } if (DllFnTable[ECMD_GETSCOM] == NULL) { DllFnTable[ECMD_GETSCOM] = (void*)dlsym(dlHandle, "dllGetScom"); } int (*Function)(ecmdChipTarget &, uint32_t, ecmdDataBuffer &) = (int(*)(ecmdChipTarget &, uint32_t, ecmdDataBuffer &))DllFnTable[ECMD_GETSCOM]; rc = (*Function)(target, address, data); #endif return rc; } int putScom(ecmdChipTarget & target, uint32_t address, ecmdDataBuffer & data) { int rc; #ifdef ECMD_STATIC_FUNCTIONS rc = dllPutScom(target, address, data); #else if (dlHandle == NULL) { return ECMD_DLL_UNINITIALIZED; } if (DllFnTable[ECMD_PUTSCOM] == NULL) { DllFnTable[ECMD_PUTSCOM] = (void*)dlsym(dlHandle, "dllPutScom"); } int (*Function)(ecmdChipTarget &, uint32_t, ecmdDataBuffer &) = (int(*)(ecmdChipTarget &, uint32_t, ecmdDataBuffer &))DllFnTable[ECMD_PUTSCOM]; rc = (*Function)(target, address, data); #endif return rc; } int getSpy(ecmdChipTarget & target, const char * spyName, ecmdDataBuffer & data) { int rc; #ifdef ECMD_STATIC_FUNCTIONS rc = dllGetSpy(target, spyName, data); #else if (dlHandle == NULL) { return ECMD_DLL_UNINITIALIZED; } if (DllFnTable[ECMD_GETSPY] == NULL) { DllFnTable[ECMD_GETSPY] = (void*)dlsym(dlHandle, "dllGetSpy"); } int (*Function)(ecmdChipTarget &, const char *, ecmdDataBuffer &) = (int(*)(ecmdChipTarget &, const char *, ecmdDataBuffer &))DllFnTable[ECMD_GETSPY]; rc = (*Function)(target, spyName, data); #endif return rc; } int getSpyEnum(ecmdChipTarget & target, const char * spyName, string enumValue) { int rc; #ifdef ECMD_STATIC_FUNCTIONS rc = dllGetSpyEnum(target, spyName, enumValue); #else if (dlHandle == NULL) { return ECMD_DLL_UNINITIALIZED; } if (DllFnTable[ECMD_GETSPYENUM] == NULL) { DllFnTable[ECMD_GETSPYENUM] = (void*)dlsym(dlHandle, "dllGetSpyEnum"); } int (*Function)(ecmdChipTarget &, const char *, string) = (int(*)(ecmdChipTarget &, const char *, string))DllFnTable[ECMD_GETSPYENUM]; rc = (*Function)(target, spyName, enumValue); #endif return rc; } int putSpy(ecmdChipTarget & target, const char * spyName, ecmdDataBuffer & data) { int rc; #ifdef ECMD_STATIC_FUNCTIONS rc = dllPutSpy(target, spyName, data); #else if (dlHandle == NULL) { return ECMD_DLL_UNINITIALIZED; } if (DllFnTable[ECMD_PUTSPY] == NULL) { DllFnTable[ECMD_PUTSPY] = (void*)dlsym(dlHandle, "dllPutSpy"); } int (*Function)(ecmdChipTarget &, const char *, ecmdDataBuffer &) = (int(*)(ecmdChipTarget &, const char *, ecmdDataBuffer &))DllFnTable[ECMD_PUTSPY]; rc = (*Function)(target, spyName, data); #endif return rc; } int putSpyEnum(ecmdChipTarget & target, const char * spyName, const string enumValue) { int rc; #ifdef ECMD_STATIC_FUNCTIONS rc = dllPutSpyEnum(target, spyName, enumValue); #else if (dlHandle == NULL) { return ECMD_DLL_UNINITIALIZED; } if (DllFnTable[ECMD_PUTSPYENUM] == NULL) { DllFnTable[ECMD_PUTSPYENUM] = (void*)dlsym(dlHandle, "dllPutSpyEnum"); } int (*Function)(ecmdChipTarget &, const char *, const string) = (int(*)(ecmdChipTarget &, const char *, const string))DllFnTable[ECMD_PUTSPYENUM]; rc = (*Function)(target, spyName, enumValue); #endif return rc; } int getArray(ecmdChipTarget & target, const char * arrayName, uint32_t * address, ecmdDataBuffer & data) { int rc; #ifdef ECMD_STATIC_FUNCTIONS rc = dllGetArray(target, arrayName, address, data); #else if (dlHandle == NULL) { return ECMD_DLL_UNINITIALIZED; } if (DllFnTable[ECMD_GETARRAY] == NULL) { DllFnTable[ECMD_GETARRAY] = (void*)dlsym(dlHandle, "dllGetArray"); } int (*Function)(ecmdChipTarget &, const char *, uint32_t *, ecmdDataBuffer &) = (int(*)(ecmdChipTarget &, const char *, uint32_t *, ecmdDataBuffer &))DllFnTable[ECMD_GETARRAY]; rc = (*Function)(target, arrayName, address, data); #endif return rc; } int putArray(ecmdChipTarget & target, const char * arrayName, uint32_t * address, ecmdDataBuffer & data) { int rc; #ifdef ECMD_STATIC_FUNCTIONS rc = dllPutArray(target, arrayName, address, data); #else if (dlHandle == NULL) { return ECMD_DLL_UNINITIALIZED; } if (DllFnTable[ECMD_PUTARRAY] == NULL) { DllFnTable[ECMD_PUTARRAY] = (void*)dlsym(dlHandle, "dllPutArray"); } int (*Function)(ecmdChipTarget &, const char *, uint32_t *, ecmdDataBuffer &) = (int(*)(ecmdChipTarget &, const char *, uint32_t *, ecmdDataBuffer &))DllFnTable[ECMD_PUTARRAY]; rc = (*Function)(target, arrayName, address, data); #endif return rc; } int flushSys() { int rc; #ifdef ECMD_STATIC_FUNCTIONS rc = dllFlushSys(); #else if (dlHandle == NULL) { return ECMD_DLL_UNINITIALIZED; } if (DllFnTable[ECMD_FLUSHSYS] == NULL) { DllFnTable[ECMD_FLUSHSYS] = (void*)dlsym(dlHandle, "dllFlushSys"); } int (*Function)() = (int(*)())DllFnTable[ECMD_FLUSHSYS]; rc = (*Function)(); #endif return rc; } int iplSys() { int rc; #ifdef ECMD_STATIC_FUNCTIONS rc = dllIplSys(); #else if (dlHandle == NULL) { return ECMD_DLL_UNINITIALIZED; } if (DllFnTable[ECMD_IPLSYS] == NULL) { DllFnTable[ECMD_IPLSYS] = (void*)dlsym(dlHandle, "dllIplSys"); } int (*Function)() = (int(*)())DllFnTable[ECMD_IPLSYS]; rc = (*Function)(); #endif return rc; } int ecmdRegisterErrorMsg(int errorCode, const char* whom, const char* message) { int rc; #ifdef ECMD_STATIC_FUNCTIONS rc = dllRegisterErrorMsg(errorCode, whom, message); #else if (dlHandle == NULL) { return ECMD_DLL_UNINITIALIZED; } if (DllFnTable[ECMD_REGISTERERRORMSG] == NULL) { DllFnTable[ECMD_REGISTERERRORMSG] = (void*)dlsym(dlHandle, "dllRegisterErrorMsg"); } int (*Function)(int, const char*, const char*) = (int(*)(int, const char*, const char*))DllFnTable[ECMD_REGISTERERRORMSG]; rc = (*Function)(errorCode, whom, message); #endif return rc; } <commit_msg>Added version stuff<commit_after>// Copyright *********************************************************** // // File ecmdClientCapi.C // // IBM Confidential // OCO Source Materials // 9400 Licensed Internal Code // (C) COPYRIGHT IBM CORP. 1996 // // The source code for this program is not published or otherwise // divested of its trade secrets, irrespective of what has been // deposited with the U.S. Copyright Office. // // End Copyright ******************************************************* // Module Description ************************************************** // // Description: // // End Module Description ********************************************** //---------------------------------------------------------------------- // Includes //---------------------------------------------------------------------- #include <dlfcn.h> #include <string> #include <stdio.h> #include <ecmdClientCapi.H> #include <ecmdDllCapi.H> //---------------------------------------------------------------------- // User Types //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Constants //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Macros //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Internal Function Prototypes //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Global Variables //---------------------------------------------------------------------- //--------------------------------------------------------------------- // Member Function Specifications //--------------------------------------------------------------------- // Change Log ********************************************************* // // Flag Reason Vers Date Coder Description // ---- -------- ---- -------- -------- ------------------------------ // CENGEL Initial Creation // // End Change Log ***************************************************** typedef enum { ECMD_QUERYCONFIG, ECMD_QUERYRING, ECMD_QUERYARRAY, ECMD_QUERYSPY, ECMD_QUERYFILELOCATION, ECMD_GETRING, ECMD_PUTRING, ECMD_RINGREAD, ECMD_RINGWRITE, ECMD_GETSCOM, ECMD_PUTSCOM, ECMD_GETSPY, ECMD_GETSPYENUM, ECMD_PUTSPY, ECMD_PUTSPYENUM, ECMD_GETARRAY, ECMD_PUTARRAY, ECMD_FLUSHSYS, ECMD_IPLSYS, ECMD_REGISTERERRORMSG, ECMD_NUMFUNCTIONS } ecmdFunctionIndex_t; void * dlHandle = NULL; void * DllFnTable[ECMD_NUMFUNCTIONS]; int ecmdLoadDll(string dllName) { const char* dlError; int rc = ECMD_SUCCESS; #ifndef LINUX /* clean up the machine from previous tests */ system("slibclean"); #endif /* --------------------- */ /* load DLL */ /* --------------------- */ char dllname[256]; if (dllName.size() == 0) { /* Let's try to get it from the env var */ char * tempptr = getenv("ECMD_DLL_FILE"); /* is there a ECMD_DLL_FILE environment variable? */ if (tempptr != NULL) { dllName = tempptr; } else { fprintf(stderr,"ecmdLoadDll: Unable to find DLL to load, you must set ECMD_DLL_FILE\n"); return ECMD_INVALID_DLL_FILENAME; } } printf("loadDll: loading %s ...\n", dllname); dlHandle = dlopen(dllname, RTLD_NOW); if (!dlHandle) { if ((dlError = dlerror()) != NULL) { printf("ERROR: loadDll: %s\n", dlError); return ECMD_DLL_LOAD_FAILURE; } } else { printf("loadDll: load successful\n"); } /* Now we need to call loadDll on the dll itself so it can initialize */ int (*Function)(const char *) = (int(*)(const char *))(void*)dlsym(dlHandle, "dllLoadDll"); if (!Function) { fprintf(stderr,"ecmdLoadDll: Unable to find LoadDll function, must be an invalid DLL\n"); rc = ECMD_DLL_LOAD_FAILURE; } else { rc = (*Function)(ECMD_CAPI_VERSION); } return rc; } int ecmdUnloadDll() { int rc = ECMD_SUCCESS; int c_rc = ECMD_SUCCESS; /* call DLL unload */ int (*Function)() = (int(*)())(void*)dlsym(dlHandle, "dllUnloadDll"); if (!Function) { fprintf(stderr,"ecmdUnloadDll: Unable to find UnloadDll function, must be an invalid DLL\n"); rc = ECMD_DLL_LOAD_FAILURE; return rc; } rc = (*Function)(); /* release DLL */ const char* dlError; c_rc = dlclose(dlHandle); if (c_rc) { if ((dlError = dlerror()) != NULL) { fprintf(stderr,"ERROR: ecmdUnloadDll: %s\n", dlError); return ECMD_DLL_UNLOAD_FAILURE; } } dlHandle = NULL; return rc; } <|endoftext|>
<commit_before>#ifndef ecmdClientCapi_H #define ecmdClientCapi_H /* $Header$ */ /** * @file ecmdClientCapi.H * @brief eCMD C/C++ Client Interface */ //-------------------------------------------------------------------- // Includes //-------------------------------------------------------------------- #include <ecmdReturnCodes.H> #include <ecmdStructs.H> #include <ecmdDataBuffer.H> //-------------------------------------------------------------------- // Forward References //-------------------------------------------------------------------- /* Functions in here are defined as extern C for the following reasons: 1) Keeps Function names small by preventing C++ "mangling" 2) Allows (C-based) perl interpreter to access these functions */ extern "C" { /** @name Load/Unload Functions */ //@{ /** @brief Load the eCMD DLL @retval ECMD_SUCCESS if successful load @retval ECMD_INVALID_DLL_VERSION if Dll version loaded doesn't match client version @retval nonzero if unsuccessful @post eCMD DLL is loaded into memory and initialized @see unloadDll - This function loads the DLL based on ???. - Name limit of 255 characters. - Errors in loading are printed to STDOUT. */ int ecmdLoadDll(); /** @brief Unload the eCMD DLL @retval ECMD_SUCCESS if successful load @retval nonzero if unsuccessful @see loadDll - Errors in unloading are printed to STDOUT. */ int ecmdUnloadDll(); /** @brief Initialize the eCMD DLL @retval ECMD_SUCCESS if successful load nonzero if unsuccessful @param argc Passed from Command line Arguments @param argv Passed from Command line Arguments @pre loadDll must have been called @post Global options (ex. -debug, -p#, -c#) will be removed from arg list @see loadDll - initializes objects in the DLL. - argc/argv get passed to the eCMD DLL. - Global options such as -debug flags and -p#, -c# will be parsed out. - Position flags can be queried later with functions like wasposselected() */ int ecmdInitDll(int argc, char* argv[]); //@} /** @name Scan Functions */ //@{ /** @brief Scans the selected number of bits from the selected position in the selected ring into the data buffer @retval ECMD_SUCCESS if successful read, nonzero if unsuccessful @param target Struct that contains chip and cage/node/position/core/thread information of ring to read @param ringName Name of ring to read from @param data DataBuffer object that holds data read from ring @param startPos Position of first bit in the ring to read from @param numBits Number of bits to read @see putRing */ int getRing (ecmdChipTarget & target, const char * ringName, ecmdDataBuffer & data, int startPos, int numBits); /** @brief Scans the selected number of bits from the data buffer into the selected position in the selected ring @retval ECMD_SUCCESS if successful read, nonzero if unsuccessful @param target Struct that contains chip and cage/node/position/core/thread information of ring to write @param ringName Name of ring to write to @param data DataBuffer object that holds data to write into ring @param startPos Position of first bit in the ring to write to @param numBits Number of bits to write @see getRing */ int putRing (ecmdChipTarget & target, const char * ringName, ecmdDataBuffer & data, int startPos, int numBits); //@} /** @name Query Functions */ //@{ // data structures associated with ecmdQuery functions need to be spec'd //@} /** @name Scom Functions */ //@{ /** @brief Scoms bits from the selected address into the data buffer @retval ECMD_SUCCESS if successful read, nonzero if unsuccessful @param target Struct that contains chip and cage/node/position/core/thread information of scom address to read @param address Scom address to read from @param data DataBuffer object that holds data read from address @see putScom */ int getScom (ecmdChipTarget & target, uint32_t address, ecmdDataBuffer & data); /** @brief Scoms bits from the data buffer into the selected address @retval ECMD_SUCCESS if successful read, nonzero if unsuccessful @param target Struct that contains chip and cage/node/position/core/thread information of scom address to write @param address Scom address to write to @param data DataBuffer object that holds data to write into address @see getScom */ int putScom (ecmdChipTarget & target, uint32_t address, ecmdDataBuffer & data); //@} /** @name Spy Functions */ //@{ /** @brief Scans the selected number of bits from the selected position in the selected alias into the data buffer @retval ECMD_SUCCESS if successful read, nonzero if unsuccessful @param target Struct that contains chip and cage/node/position/core/thread information of alias to read @param aliasName Name of alias to read from @param data DataBuffer object that holds data read from alias @param startPos Position of first bit in the alias to read from @param numBits Number of bits to read @see putAlias */ int getSpy (ecmdChipTarget & target, const char * spyName, ecmdDataBuffer & data, int startPos, int numBits); /** @brief Scans the selected number of bits from the selected position in the selected alias into the data buffer @retval ECMD_SUCCESS if successful read, nonzero if unsuccessful @param target Struct that contains chip and cage/node/position/core/thread information of alias to read @param aliasName Name of alias to read from @param enumValue Enum value @param startPos Position of first bit in the alias to read from @param numBits Number of bits to read @see putAlias */ int getSpyEnum (ecmdChipTarget & target, const char * spyName, char * enumValue, int startPos, int numBits); /** @brief Scans the selected number of bits from the data buffer into the selected position in the selected alias @retval ECMD_SUCCESS if successful read, nonzero if unsuccessful @param target Struct that contains chip and cage/node/position/core/thread information of alias to write @param aliasName Name of alias to write to @param data DataBuffer object that holds data to write into alias @param startPos Position of first bit in the alias to write to @param numBits Number of bits to write @see getAlias */ int putSpy (ecmdChipTarget & target, const char * spyName, ecmdDataBuffer & data, int startPos, int numBits); /** @brief Scans the selected number of bits from the data buffer into the selected position in the selected alias @retval ECMD_SUCCESS if successful read, nonzero if unsuccessful @param target Struct that contains chip and cage/node/position/core/thread information of alias to write @param aliasName Name of alias to write to @param data DataBuffer object that holds data to write into alias @param startPos Position of first bit in the alias to write to @param numBits Number of bits to write @see getAlias */ int putSpyEnum (ecmdChipTarget & target, const char * spyName, ecmdDataBuffer & data, int startPos, int numBits); //@} /** @name Array Functions */ //@{ /** @brief Reads bits from the selected array into the data buffer @retval ECMD_SUCCESS if successful read, nonzero if unsuccessful @param target Struct that contains chip and cage/node/position/core/thread information of array to read @param arrayName Name of array to read from @param data DataBuffer object that holds data read from address @see putArray */ int getArray (ecmdChipTarget & target, const char * arrayName, uint32_t * address, ecmdDataBuffer & data); /** @brief Writes bits from the data buffer into the selected array @retval ECMD_SUCCESS if successful read, nonzero if unsuccessful @param target Struct that contains chip and cage/node/position/core/thread information of array to write @param arrayName Name of array to write to @param data DataBuffer object that holds data to write into array @see getArray */ int putArray (ecmdChipTarget & target, const char * arrayName, uint32_t * address, ecmdDataBuffer & data); //@} /** @name Flush and IPL Functions */ //@{ /** * @brief System Flush * @retval ECMD_SUCCESS if successful read, nonzero if unsuccessful * @post The system is cleaned up and ready for iplsys * @see iplSys */ int flushSys (); /** * @brief Initial Program Load * @retval ECMD_SUCCESS if successful read, nonzero if unsuccessful * @pre An ecmdFlushSys call is generally required before iplsys * @post The system is IPLed * @see flushSys */ int iplSys (); //@} /** @name Error Handling Functions */ //@{ /** @brief Retrieve additional error information for errorcode @retval point to NULL terminated string containing error data, NULL if error occurs */ const char* ecmdGetErrorMsg(int errorCode); /** @brief Register an Error Message that has occured */ int ecmdRegisterErrorMsg(int errorCode, const char* message); //@} /** @name Output Functions */ //@{ //@} } //extern "C" #endif /* ecmdClientCapi_H */ // Change Log ********************************************************* // // Flag Reason Vers Date Coder Description // ---- -------- ---- -------- ----- ------------------------------- // cengel Initial Creation // // End Change Log ***************************************************** <commit_msg>Initial start on query functions<commit_after>#ifndef ecmdClientCapi_H #define ecmdClientCapi_H /* $Header$ */ /** * @file ecmdClientCapi.H * @brief eCMD C/C++ Client Interface */ //-------------------------------------------------------------------- // Includes //-------------------------------------------------------------------- #include <ecmdReturnCodes.H> #include <ecmdStructs.H> #include <ecmdDataBuffer.H> //-------------------------------------------------------------------- // Forward References //-------------------------------------------------------------------- /* Functions in here are defined as extern C for the following reasons: 1) Keeps Function names small by preventing C++ "mangling" 2) Allows (C-based) perl interpreter to access these functions */ extern "C" { /** @name Load/Unload Functions */ //@{ /** @brief Load the eCMD DLL @retval ECMD_SUCCESS if successful load @retval ECMD_INVALID_DLL_VERSION if Dll version loaded doesn't match client version @retval nonzero if unsuccessful @post eCMD DLL is loaded into memory and initialized @see unloadDll - This function loads the DLL based on ???. - Name limit of 255 characters. - Errors in loading are printed to STDOUT. */ int ecmdLoadDll(); /** @brief Unload the eCMD DLL @retval ECMD_SUCCESS if successful load @retval nonzero if unsuccessful @see loadDll - Errors in unloading are printed to STDOUT. */ int ecmdUnloadDll(); /** @brief Initialize the eCMD DLL @retval ECMD_SUCCESS if successful load nonzero if unsuccessful @param argc Passed from Command line Arguments @param argv Passed from Command line Arguments @pre loadDll must have been called @post Global options (ex. -debug, -p#, -c#) will be removed from arg list @see loadDll - initializes objects in the DLL. - argc/argv get passed to the eCMD DLL. - Global options such as -debug flags and -p#, -c# will be parsed out. - Position flags can be queried later with functions like wasposselected() */ int ecmdInitDll(int argc, char* argv[]); //@} /** @name Scan Functions */ //@{ /** @brief Scans the selected number of bits from the selected position in the selected ring into the data buffer @retval ECMD_SUCCESS if successful read, nonzero if unsuccessful @param target Struct that contains chip and cage/node/position/core/thread information of ring to read @param ringName Name of ring to read from @param data DataBuffer object that holds data read from ring @param startPos Position of first bit in the ring to read from @param numBits Number of bits to read @see putRing */ int getRing (ecmdChipTarget & target, const char * ringName, ecmdDataBuffer & data, int startPos, int numBits); /** @brief Scans the selected number of bits from the data buffer into the selected position in the selected ring @retval ECMD_SUCCESS if successful read, nonzero if unsuccessful @param target Struct that contains chip and cage/node/position/core/thread information of ring to write @param ringName Name of ring to write to @param data DataBuffer object that holds data to write into ring @param startPos Position of first bit in the ring to write to @param numBits Number of bits to write @see getRing */ int putRing (ecmdChipTarget & target, const char * ringName, ecmdDataBuffer & data, int startPos, int numBits); //@} /** @name Query Functions */ //@{ int ecmdQueryConfig(); int ecmdQueryRing(); int ecmdQueryArray(); int ecmdQueryAlias(); /** @brief Query the location of a specific file type for the selected target @param target Struct that contains chip and cage/node/position/core/thread information @param fileType Enum that specifies which type of file you are looking for scandef/spydef/arraydef @param fileLocation Return string with full path and filename to location - allocated by Capi - must be deallocated @retval ECMD_SUCCESS if successful read, nonzero if unsuccessful */ int ecmdQueryFileLocation(ecmdChipTarget & target, ecmdFileType_t fileType, char * fileLocation); //@} /** @name Scom Functions */ //@{ /** @brief Scoms bits from the selected address into the data buffer @retval ECMD_SUCCESS if successful read, nonzero if unsuccessful @param target Struct that contains chip and cage/node/position/core/thread information of scom address to read @param address Scom address to read from @param data DataBuffer object that holds data read from address @see putScom */ int getScom (ecmdChipTarget & target, uint32_t address, ecmdDataBuffer & data); /** @brief Scoms bits from the data buffer into the selected address @retval ECMD_SUCCESS if successful read, nonzero if unsuccessful @param target Struct that contains chip and cage/node/position/core/thread information of scom address to write @param address Scom address to write to @param data DataBuffer object that holds data to write into address @see getScom */ int putScom (ecmdChipTarget & target, uint32_t address, ecmdDataBuffer & data); //@} /** @name Spy Functions */ //@{ /** @brief Scans the selected number of bits from the selected position in the selected alias into the data buffer @retval ECMD_SUCCESS if successful read, nonzero if unsuccessful @param target Struct that contains chip and cage/node/position/core/thread information of alias to read @param aliasName Name of alias to read from @param data DataBuffer object that holds data read from alias @param startPos Position of first bit in the alias to read from @param numBits Number of bits to read @see putAlias */ int getSpy (ecmdChipTarget & target, const char * spyName, ecmdDataBuffer & data, int startPos, int numBits); /** @brief Scans the selected number of bits from the selected position in the selected alias into the data buffer @retval ECMD_SUCCESS if successful read, nonzero if unsuccessful @param target Struct that contains chip and cage/node/position/core/thread information of alias to read @param aliasName Name of alias to read from @param enumValue Enum value @param startPos Position of first bit in the alias to read from @param numBits Number of bits to read @see putAlias */ int getSpyEnum (ecmdChipTarget & target, const char * spyName, char * enumValue, int startPos, int numBits); /** @brief Scans the selected number of bits from the data buffer into the selected position in the selected alias @retval ECMD_SUCCESS if successful read, nonzero if unsuccessful @param target Struct that contains chip and cage/node/position/core/thread information of alias to write @param aliasName Name of alias to write to @param data DataBuffer object that holds data to write into alias @param startPos Position of first bit in the alias to write to @param numBits Number of bits to write @see getAlias */ int putSpy (ecmdChipTarget & target, const char * spyName, ecmdDataBuffer & data, int startPos, int numBits); /** @brief Scans the selected number of bits from the data buffer into the selected position in the selected alias @retval ECMD_SUCCESS if successful read, nonzero if unsuccessful @param target Struct that contains chip and cage/node/position/core/thread information of alias to write @param aliasName Name of alias to write to @param data DataBuffer object that holds data to write into alias @param startPos Position of first bit in the alias to write to @param numBits Number of bits to write @see getAlias */ int putSpyEnum (ecmdChipTarget & target, const char * spyName, ecmdDataBuffer & data, int startPos, int numBits); //@} /** @name Array Functions */ //@{ /** @brief Reads bits from the selected array into the data buffer @retval ECMD_SUCCESS if successful read, nonzero if unsuccessful @param target Struct that contains chip and cage/node/position/core/thread information of array to read @param arrayName Name of array to read from @param data DataBuffer object that holds data read from address @see putArray */ int getArray (ecmdChipTarget & target, const char * arrayName, uint32_t * address, ecmdDataBuffer & data); /** @brief Writes bits from the data buffer into the selected array @retval ECMD_SUCCESS if successful read, nonzero if unsuccessful @param target Struct that contains chip and cage/node/position/core/thread information of array to write @param arrayName Name of array to write to @param data DataBuffer object that holds data to write into array @see getArray */ int putArray (ecmdChipTarget & target, const char * arrayName, uint32_t * address, ecmdDataBuffer & data); //@} /** @name Flush and IPL Functions */ //@{ /** * @brief System Flush * @retval ECMD_SUCCESS if successful read, nonzero if unsuccessful * @post The system is cleaned up and ready for iplsys * @see iplSys */ int flushSys (); /** * @brief Initial Program Load * @retval ECMD_SUCCESS if successful read, nonzero if unsuccessful * @pre An ecmdFlushSys call is generally required before iplsys * @post The system is IPLed * @see flushSys */ int iplSys (); //@} /** @name Error Handling Functions */ //@{ /** @brief Retrieve additional error information for errorcode @retval point to NULL terminated string containing error data, NULL if error occurs */ const char* ecmdGetErrorMsg(int errorCode); /** @brief Register an Error Message that has occured */ int ecmdRegisterErrorMsg(int errorCode, const char* message); //@} /** @name Output Functions */ //@{ //@} } //extern "C" #endif /* ecmdClientCapi_H */ // Change Log ********************************************************* // // Flag Reason Vers Date Coder Description // ---- -------- ---- -------- ----- ------------------------------- // cengel Initial Creation // // End Change Log ***************************************************** <|endoftext|>
<commit_before>// RootTheme.cc // Copyright (c) 2003 - 2005 Henrik Kinnunen (fluxgen at fluxbox dot org) // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // $Id$ #include "RootTheme.hh" #include "FbRootWindow.hh" #include "FbCommands.hh" #include "FbTk/App.hh" #include "FbTk/Font.hh" #include "FbTk/ImageControl.hh" #include "FbTk/Resource.hh" #include "FbTk/FileUtil.hh" #include "FbTk/StringUtil.hh" #include "FbTk/TextureRender.hh" #include <X11/Xatom.h> using std::string; class BackgroundItem: public FbTk::ThemeItem<FbTk::Texture> { public: BackgroundItem(FbTk::Theme &tm, const std::string &name, const std::string &altname): FbTk::ThemeItem<FbTk::Texture>(tm, name, altname) { } void load(const std::string *o_name = 0, const std::string *o_altname = 0) { const string &m_name = (o_name == 0) ? name() : *o_name; const string &m_altname = (o_altname == 0) ? altName() : *o_altname; // create subnames string color_name(FbTk::ThemeManager::instance(). resourceValue(m_name + ".color", m_altname + ".Color")); string colorto_name(FbTk::ThemeManager::instance(). resourceValue(m_name + ".colorTo", m_altname + ".ColorTo")); string pixmap_name(FbTk::ThemeManager::instance(). resourceValue(m_name + ".pixmap", m_altname + ".Pixmap")); // set default value if we failed to load colors if (!(*this)->color().setFromString(color_name.c_str(), theme().screenNum())) (*this)->color().setFromString("darkgray", theme().screenNum()); if (!(*this)->colorTo().setFromString(colorto_name.c_str(), theme().screenNum())) (*this)->colorTo().setFromString("white", theme().screenNum()); if (((*this)->type() & FbTk::Texture::SOLID) != 0 && ((*this)->type() & FbTk::Texture::FLAT) == 0) (*this)->calcHiLoColors(theme().screenNum()); // remove whitespace and set filename FbTk::StringUtil::removeFirstWhitespace(pixmap_name); FbTk::StringUtil::removeTrailingWhitespace(pixmap_name); m_filename = pixmap_name; // we dont load any pixmap, using external command to set background pixmap (*this)->pixmap() = 0; } void setFromString(const char *str) { m_options = str; // save option string FbTk::ThemeItem<FbTk::Texture>::setFromString(str); } const std::string &filename() const { return m_filename; } const std::string &options() const { return m_options; } private: std::string m_filename, m_options; }; RootTheme::RootTheme(const std::string &root_command, FbTk::ImageControl &image_control): FbTk::Theme(image_control.screenNumber()), m_background(new BackgroundItem(*this, "background", "Background")), m_opgc(RootWindow(FbTk::App::instance()->display(), image_control.screenNumber())), m_root_command(root_command), m_image_ctrl(image_control), m_lock(false), m_background_loaded(true) { Display *disp = FbTk::App::instance()->display(); m_opgc.setForeground(WhitePixel(disp, screenNum())^BlackPixel(disp, screenNum())); m_opgc.setFunction(GXxor); m_opgc.setSubwindowMode(IncludeInferiors); m_opgc.setLineAttributes(1, LineSolid, CapNotLast, JoinMiter); } RootTheme::~RootTheme() { delete m_background; } bool RootTheme::fallback(FbTk::ThemeItem_base &item) { // if background theme item was not found in the // style then mark background as not loaded so // we can deal with it in reconfigureTheme() if (item.name() == "background") { // mark no background loaded m_background_loaded = false; return true; } return false; } void RootTheme::reconfigTheme() { if (m_lock) return; // if user specified background in the config then use it // instead of style background if (!m_root_command.empty()) { FbCommands::ExecuteCmd cmd(m_root_command, screenNum()); cmd.execute(); return; } // // Else parse background from style // // root window helper FbRootWindow rootwin(screenNum()); // if the background theme item was not loaded // then generate an image with a text that // notifies the user about it if (!m_background_loaded) { FbTk::FbPixmap root(FbTk::FbPixmap::getRootPixmap(screenNum())); // if there is no root background pixmap // then we need to create one if (root.drawable() == None) { root.create(rootwin.window(), rootwin.width(), rootwin.height(), rootwin.depth()); FbTk::FbPixmap::setRootPixmap(screenNum(), root.drawable()); } // setup root window property Atom atom_root = XInternAtom(rootwin.display(), "_XROOTPMAP_ID", false); Pixmap pm = root.drawable(); rootwin.changeProperty(atom_root, XA_PIXMAP, 32, PropModeReplace, (unsigned char *)&pm, 1); rootwin.setBackgroundPixmap(root.drawable()); FbTk::GContext gc(root); // fill background color gc.setForeground(FbTk::Color("black", screenNum())); root.fillRectangle(gc.gc(), 0, 0, root.width(), root.height()); // text color gc.setForeground(FbTk::Color("white", screenNum())); // render text const char errormsg[] = "There is no background option specified in this style. Please consult the manual or read the FAQ."; FbTk::Font font; font.drawText(root, screenNum(), gc.gc(), errormsg, strlen(errormsg), 2, font.height() + 2); // added some extra pixels for better visibility // reset background mark m_background_loaded = true; root.release(); // we dont want to destroy this pixmap } else { // handle background option in style std::string filename = m_background->filename(); FbTk::StringUtil::removeTrailingWhitespace(filename); FbTk::StringUtil::removeFirstWhitespace(filename); // if background argument is a file then // parse image options and call image setting // command specified in the resources if (FbTk::FileUtil::isRegularFile(filename.c_str())) { // parse options std::string options; if (strstr(m_background->options().c_str(), "tiled") != 0) options += "-t "; if (strstr(m_background->options().c_str(), "centered") != 0) options += "-c "; if (strstr(m_background->options().c_str(), "random") != 0) options += "-r "; if (strstr(m_background->options().c_str(), "aspect") != 0) options += "-a "; // compose wallpaper application "fbsetbg" with argumetns std::string commandargs = "fbsetbg " + options + " " + filename; // call command with options FbCommands::ExecuteCmd exec(commandargs, screenNum()); exec.execute(); } else { // render normal texture // we override the image control renderImage since // since we do not want to cache this pixmap XColor *colors; int num_colors; m_image_ctrl.getXColorTable(&colors, &num_colors); FbTk::TextureRender image(m_image_ctrl, rootwin.width(), rootwin.height(), colors, num_colors); Pixmap pixmap = image.render(*(*m_background)); // setup root window property Atom atom_root = XInternAtom(rootwin.display(), "_XROOTPMAP_ID", false); rootwin.changeProperty(atom_root, XA_PIXMAP, 32, PropModeReplace, (unsigned char *)&pixmap, 1); rootwin.setBackgroundPixmap(pixmap); } } // clear root window rootwin.clear(); } <commit_msg>fixed root pixmap crash problem, using fbsetroot to render background<commit_after>// RootTheme.cc // Copyright (c) 2003 - 2005 Henrik Kinnunen (fluxgen at fluxbox dot org) // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // $Id$ #include "RootTheme.hh" #include "FbRootWindow.hh" #include "FbCommands.hh" #include "FbTk/App.hh" #include "FbTk/Font.hh" #include "FbTk/ImageControl.hh" #include "FbTk/Resource.hh" #include "FbTk/FileUtil.hh" #include "FbTk/StringUtil.hh" #include "FbTk/TextureRender.hh" #include "FbTk/I18n.hh" #include <X11/Xatom.h> #include <iostream> #include <sys/types.h> #include <sys/wait.h> using std::cerr; using std::endl; using std::string; class BackgroundItem: public FbTk::ThemeItem<FbTk::Texture> { public: BackgroundItem(FbTk::Theme &tm, const std::string &name, const std::string &altname): FbTk::ThemeItem<FbTk::Texture>(tm, name, altname) { } void load(const std::string *o_name = 0, const std::string *o_altname = 0) { const string &m_name = (o_name == 0) ? name() : *o_name; const string &m_altname = (o_altname == 0) ? altName() : *o_altname; // create subnames string color_name(FbTk::ThemeManager::instance(). resourceValue(m_name + ".color", m_altname + ".Color")); string colorto_name(FbTk::ThemeManager::instance(). resourceValue(m_name + ".colorTo", m_altname + ".ColorTo")); string pixmap_name(FbTk::ThemeManager::instance(). resourceValue(m_name + ".pixmap", m_altname + ".Pixmap")); m_color = color_name; m_color_to = colorto_name; // set default value if we failed to load colors if (!(*this)->color().setFromString(color_name.c_str(), theme().screenNum())) (*this)->color().setFromString("darkgray", theme().screenNum()); if (!(*this)->colorTo().setFromString(colorto_name.c_str(), theme().screenNum())) (*this)->colorTo().setFromString("white", theme().screenNum()); if (((*this)->type() & FbTk::Texture::SOLID) != 0 && ((*this)->type() & FbTk::Texture::FLAT) == 0) (*this)->calcHiLoColors(theme().screenNum()); // remove whitespace and set filename FbTk::StringUtil::removeFirstWhitespace(pixmap_name); FbTk::StringUtil::removeTrailingWhitespace(pixmap_name); m_filename = pixmap_name; // we dont load any pixmap, using external command to set background pixmap (*this)->pixmap() = 0; } void setFromString(const char *str) { m_options = str; // save option string FbTk::ThemeItem<FbTk::Texture>::setFromString(str); } const std::string &filename() const { return m_filename; } const std::string &options() const { return m_options; } const std::string &colorString() const { return m_color; } const std::string &colorToString() const { return m_color_to; } private: std::string m_filename, m_options; std::string m_color, m_color_to; }; RootTheme::RootTheme(const std::string &root_command, FbTk::ImageControl &image_control): FbTk::Theme(image_control.screenNumber()), m_background(new BackgroundItem(*this, "background", "Background")), m_opgc(RootWindow(FbTk::App::instance()->display(), image_control.screenNumber())), m_root_command(root_command), m_image_ctrl(image_control), m_lock(false), m_background_loaded(true) { Display *disp = FbTk::App::instance()->display(); m_opgc.setForeground(WhitePixel(disp, screenNum())^BlackPixel(disp, screenNum())); m_opgc.setFunction(GXxor); m_opgc.setSubwindowMode(IncludeInferiors); m_opgc.setLineAttributes(1, LineSolid, CapNotLast, JoinMiter); } RootTheme::~RootTheme() { delete m_background; } bool RootTheme::fallback(FbTk::ThemeItem_base &item) { // if background theme item was not found in the // style then mark background as not loaded so // we can deal with it in reconfigureTheme() if (item.name() == "background") { // mark no background loaded m_background_loaded = false; return true; } return false; } void RootTheme::reconfigTheme() { if (m_lock) return; // if user specified background in the config then use it // instead of style background if (!m_root_command.empty()) { FbCommands::ExecuteCmd cmd(m_root_command, screenNum()); cmd.execute(); return; } // // Else parse background from style // // root window helper FbRootWindow rootwin(screenNum()); // if the background theme item was not loaded // then generate an image with a text that // notifies the user about it if (!m_background_loaded) { // get the pixmap, force update of pixmap (needed if this is the first time) FbTk::FbPixmap root(FbTk::FbPixmap::getRootPixmap(screenNum(), true)); // render text static const char warning_msg[] = _FBTEXT(Common, BackgroundWarning, "There is no background option specified in this style." " Please consult the manual or read the FAQ.", "Background missing warning"); // if there is no root background pixmap...do nothing if (root.drawable() == None) { FbCommands::ExecuteCmd cmd("fbsetroot -solid darkgreen", screenNum()); // wait for command to finish waitpid(cmd.run(), NULL, 0); // pixmap setting done. Force update of pixmaps root = FbTk::FbPixmap::getRootPixmap(screenNum(), true); // The command could fail and not set the background... // so if the drawable is still none then just dont do anything more // but we still output warning msg to the console/log if (root.drawable() == None) { cerr<<"Fluxbox: "<<warning_msg<<endl; return; } } _FB_USES_NLS; FbTk::GContext gc(root); // fill rectangle gc.setForeground(FbTk::Color("black", screenNum())); FbTk::Font font; root.fillRectangle(gc.gc(), 0, 0, font.textWidth(warning_msg, strlen(warning_msg)) + 4, font.height() + 4); // text color gc.setForeground(FbTk::Color("white", screenNum())); font.drawText(root, screenNum(), gc.gc(), warning_msg, strlen(warning_msg), 2, font.height() + 2); // added some extra pixels for better visibility // output same msg to the log cerr<<"Fluxbox: "<<warning_msg<<endl; // reset background mark m_background_loaded = true; root.release(); // we dont want to destroy this pixmap rootwin.clear(); } else { // handle background option in style std::string filename = m_background->filename(); FbTk::StringUtil::removeTrailingWhitespace(filename); FbTk::StringUtil::removeFirstWhitespace(filename); // if background argument is a file then // parse image options and call image setting // command specified in the resources if (FbTk::FileUtil::isRegularFile(filename.c_str())) { // parse options std::string options; if (strstr(m_background->options().c_str(), "tiled") != 0) options += "-t "; if (strstr(m_background->options().c_str(), "centered") != 0) options += "-c "; if (strstr(m_background->options().c_str(), "random") != 0) options += "-r "; if (strstr(m_background->options().c_str(), "aspect") != 0) options += "-a "; // compose wallpaper application "fbsetbg" with argumetns std::string commandargs = "fbsetbg " + options + " " + filename; // call command with options FbCommands::ExecuteCmd exec(commandargs, screenNum()); exec.execute(); } else { // render normal texture with fbsetroot // Make sure the color strings are valid, // so we dont pass any `commands` that can be executed bool color_valid = FbTk::Color::validColorString(m_background->colorString().c_str(), screenNum()); bool color_to_valid = FbTk::Color::validColorString(m_background->colorToString().c_str(), screenNum()); std::string options; if (color_valid) options += "-foreground '" + m_background->colorString() + "' "; if (color_to_valid) options += "-background '" + m_background->colorToString() + "' "; if ((*m_background)->type() & FbTk::Texture::SOLID && color_valid) options += "-solid '" + m_background->colorString() + "' "; if ((*m_background)->type() & FbTk::Texture::GRADIENT) { if (color_valid) options += "-from '" + m_background->colorString() + "' "; if (color_to_valid) options += "-to '" + m_background->colorToString() + "' "; options += "-gradient '" + m_background->options() + "'"; } std::string commandargs = "fbsetroot " + options; FbCommands::ExecuteCmd exec(commandargs, screenNum()); exec.execute(); } rootwin.clear(); } } <|endoftext|>
<commit_before><commit_msg>Added missing AddInvalid parameterised tests for time array and object link array types<commit_after><|endoftext|>
<commit_before>/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 David Shah <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "timing.h" #include <algorithm> #include <unordered_map> #include <utility> #include "log.h" NEXTPNR_NAMESPACE_BEGIN static delay_t follow_net(Context *ctx, NetInfo *net, int path_length, delay_t slack); // Follow a path, returning budget to annotate static delay_t follow_user_port(Context *ctx, PortRef &user, int path_length, delay_t slack) { delay_t value; if (ctx->getPortClock(user.cell, user.port) != IdString()) { // At the end of a timing path (arguably, should check setup time // here too) value = slack / path_length; } else { // Default to the path ending here, if no further paths found value = slack / path_length; // Follow outputs of the user for (auto port : user.cell->ports) { if (port.second.type == PORT_OUT) { delay_t comb_delay; // Look up delay through this path bool is_path = ctx->getCellDelay(user.cell, user.port, port.first, comb_delay); if (is_path) { NetInfo *net = port.second.net; if (net) { delay_t path_budget = follow_net(ctx, net, path_length, slack - comb_delay); value = std::min(value, path_budget); } } } } } if (value < user.budget) { user.budget = value; } return value; } static delay_t follow_net(Context *ctx, NetInfo *net, int path_length, delay_t slack) { delay_t net_budget = slack / (path_length + 1); for (auto &usr : net->users) { net_budget = std::min(net_budget, follow_user_port(ctx, usr, path_length + 1, slack)); } return net_budget; } void assign_budget(Context *ctx) { log_break(); log_info("Annotating ports with timing budgets\n"); // Clear delays to a very high value first delay_t default_slack = delay_t(1.0e12 / ctx->target_freq); for (auto &net : ctx->nets) { for (auto &usr : net.second->users) { usr.budget = default_slack; } } // Go through all clocked drivers and set up paths for (auto &cell : ctx->cells) { for (auto port : cell.second->ports) { if (port.second.type == PORT_OUT) { IdString clock_domain = ctx->getPortClock(cell.second.get(), port.first); if (clock_domain != IdString()) { delay_t slack = delay_t(1.0e12 / ctx->target_freq); // TODO: clock constraints if (port.second.net) follow_net(ctx, port.second.net, 0, slack); } } } } // Post-allocation check for (auto &net : ctx->nets) { for (auto user : net.second->users) { if (user.budget < 0) log_warning("port %s.%s, connected to net '%s', has negative " "timing budget of %fns\n", user.cell->name.c_str(ctx), user.port.c_str(ctx), net.first.c_str(ctx), ctx->getDelayNS(user.budget)); if (ctx->verbose) log_info("port %s.%s, connected to net '%s', has " "timing budget of %fns\n", user.cell->name.c_str(ctx), user.port.c_str(ctx), net.first.c_str(ctx), ctx->getDelayNS(user.budget)); } } log_info("Checksum: 0x%08x\n", ctx->checksum()); } NEXTPNR_NAMESPACE_END <commit_msg>Update comment<commit_after>/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 David Shah <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "timing.h" #include <algorithm> #include <unordered_map> #include <utility> #include "log.h" #include "util.h" NEXTPNR_NAMESPACE_BEGIN static delay_t follow_net(Context *ctx, NetInfo *net, int path_length, delay_t slack); // Follow a path, returning budget to annotate static delay_t follow_user_port(Context *ctx, PortRef &user, int path_length, delay_t slack) { delay_t value; if (ctx->getPortClock(user.cell, user.port) != IdString()) { // At the end of a timing path (arguably, should check setup time // here too) value = slack / path_length; } else { // Default to the path ending here, if no further paths found value = slack / path_length; // Follow outputs of the user for (auto port : user.cell->ports) { if (port.second.type == PORT_OUT) { delay_t comb_delay; // Look up delay through this path bool is_path = ctx->getCellDelay(user.cell, user.port, port.first, comb_delay); if (is_path) { NetInfo *net = port.second.net; if (net) { delay_t path_budget = follow_net(ctx, net, path_length, slack - comb_delay); value = std::min(value, path_budget); } } } } } if (value < user.budget) { user.budget = value; } return value; } static delay_t follow_net(Context *ctx, NetInfo *net, int path_length, delay_t slack) { delay_t net_budget = slack / (path_length + 1); for (auto &usr : net->users) { net_budget = std::min(net_budget, follow_user_port(ctx, usr, path_length + 1, slack)); } return net_budget; } void assign_budget(Context *ctx) { log_break(); log_info("Annotating ports with timing budgets\n"); // Clear delays to a very high value first delay_t default_slack = delay_t(1.0e12 / ctx->target_freq); for (auto &net : ctx->nets) { for (auto &usr : net.second->users) { usr.budget = default_slack; } } // Go through all clocked drivers and set up paths for (auto &cell : ctx->cells) { for (auto port : cell.second->ports) { if (port.second.type == PORT_OUT) { IdString clock_domain = ctx->getPortClock(cell.second.get(), port.first); if (clock_domain != IdString()) { delay_t slack = delay_t(1.0e12 / ctx->target_freq); // TODO: clock constraints if (port.second.net) follow_net(ctx, port.second.net, 0, slack); } } } } // Post-allocation check for (auto &net : ctx->nets) { for (auto user : net.second->users) { if (user.budget < 0) log_warning("port %s.%s, connected to net '%s', has negative " "timing budget of %fns\n", user.cell->name.c_str(ctx), user.port.c_str(ctx), net.first.c_str(ctx), ctx->getDelayNS(user.budget)); if (ctx->verbose) log_info("port %s.%s, connected to net '%s', has " "timing budget of %fns\n", user.cell->name.c_str(ctx), user.port.c_str(ctx), net.first.c_str(ctx), ctx->getDelayNS(user.budget)); } } log_info("Checksum: 0x%08x\n", ctx->checksum()); } typedef std::unordered_map<const PortInfo*, delay_t> updates_t; typedef std::unordered_map<const PortInfo*, delay_t> delays_t; static delay_t follow_net_update(Context *ctx, NetInfo *net, int path_length, delay_t slack, const delays_t& delays, updates_t& updates); // Follow a path, returning budget to annotate static delay_t follow_user_port_update(Context *ctx, PortRef &user, int path_length, delay_t slack, const delays_t& delays, updates_t& updates) { delay_t value; if (ctx->getPortClock(user.cell, user.port) != IdString()) { // At the end of a timing path (arguably, should check setup time // here too) value = slack / path_length; } else { // Default to the path ending here, if no further paths found value = slack / path_length; // Follow outputs of the user for (auto& port : user.cell->ports) { if (port.second.type == PORT_OUT) { delay_t comb_delay; // Look up delay through this path bool is_path = ctx->getCellDelay(user.cell, user.port, port.first, comb_delay); if (is_path) { NetInfo *net = port.second.net; if (net) { delay_t path_budget = follow_net_update(ctx, net, path_length, slack - comb_delay, delays, updates); value = std::min(value, path_budget); } } } } } auto ret = updates.emplace(&user.cell->ports.at(user.port), value); if (!ret.second && value < ret.first->second) { ret.first->second = value; } return value; } static delay_t follow_net_update(Context *ctx, NetInfo *net, int path_length, delay_t slack, const delays_t& delays,updates_t& updates) { delay_t net_budget = slack / (path_length + 1); for (auto& usr : net->users) { net_budget = std::min(net_budget, follow_user_port_update(ctx, usr, path_length + 1, slack - get_or_default(delays, &usr.cell->ports.at(usr.port), 0.), delays, updates)); } return net_budget; } void update_budget(Context *ctx) { delays_t delays; updates_t updates; // Compute the delay for every pin on every net for (auto &n : ctx->nets) { auto net = n.second.get(); int driver_x, driver_y; bool driver_gb; CellInfo *driver_cell = net->driver.cell; if (!driver_cell) continue; if (driver_cell->bel == BelId()) continue; ctx->estimatePosition(driver_cell->bel, driver_x, driver_y, driver_gb); WireId drv_wire = ctx->getWireBelPin(driver_cell->bel, ctx->portPinFromId(net->driver.port)); if (driver_gb) continue; for (auto& load : net->users) { if (load.cell == nullptr) continue; CellInfo *load_cell = load.cell; if (load_cell->bel == BelId()) continue; WireId user_wire = ctx->getWireBelPin(load_cell->bel, ctx->portPinFromId(load.port)); delay_t raw_wl = ctx->estimateDelay(drv_wire, user_wire); delays.emplace(&load_cell->ports.at(load.port), raw_wl); } } // Go through all clocked drivers and distribute the available path slack evenly into every budget for (auto &cell : ctx->cells) { for (auto& port : cell.second->ports) { if (port.second.type == PORT_OUT) { IdString clock_domain = ctx->getPortClock(cell.second.get(), port.first); if (clock_domain != IdString()) { if (port.second.net) follow_net_update(ctx, port.second.net, 0, delay_t(1.0e12 / ctx->target_freq) - get_or_default(delays, &port.second, 0.), delays, updates); } } } } // Update the budgets for (auto &net : ctx->nets) { for (auto& user : net.second->users) { auto pi = &user.cell->ports.at(user.port); auto it = updates.find(pi); if (it == updates.end()) continue; user.budget = delays.at(pi) + it->second; // Post-update check // if (user.budget < 0) // log_warning("port %s.%s, connected to net '%s', has negative " // "timing budget of %fns\n", // user.cell->name.c_str(ctx), user.port.c_str(ctx), net.first.c_str(ctx), // ctx->getDelayNS(user.budget)); // if (ctx->verbose) // log_info("port %s.%s, connected to net '%s', has " // "timing budget of %fns\n", // user.cell->name.c_str(ctx), user.port.c_str(ctx), net.first.c_str(ctx), // ctx->getDelayNS(user.budget)); } } } NEXTPNR_NAMESPACE_END <|endoftext|>
<commit_before>/* * HashUil.cpp * * Created on: 30 Aug 2013 * Author: nicholas */ #include <boost/program_options.hpp> #include <cstdio> namespace po = boost::program_options; using namespace std; int main(int argc, char* argv[]) { po::options_description desc = po::options_description("Allowed options"); desc.add_options() ("help", "Display this help message") ("filter", po::value<string>(), "Add files in the directory and subdirectories into filter list") ("prune", "Remove non-existing file paths from the database") ("path", po::value<vector<string> >(), "Paths to process") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if(vm.count("help") > 0) { cout << desc << "\n"; exit(0); }else if(vm.count("path") == 0){ cout << "No paths given, aborting.\n"; exit(1); }else if((vm.count("filter") == 0) && (vm.count("prune") == 0)){ cout << "No operation selected, aborting.\n"; exit(2); } if(vm.count("filter")){ cout << "Adding files to filter with reason \"" << vm["filter"].as<string>() << "\"\n"; } if(vm.count("prune")) { cout << "Pruning database.\n"; } // cout << "Folders to process:\n" << vm["path"].as<vector<string> >() << "\n"; } <commit_msg>Added workaround for vector print<commit_after>/* * HashUil.cpp * * Created on: 30 Aug 2013 * Author: nicholas */ #include <boost/program_options.hpp> #include <cstdio> namespace po = boost::program_options; using namespace std; int main(int argc, char* argv[]) { po::options_description desc = po::options_description("Allowed options"); desc.add_options() ("help", "Display this help message") ("filter", po::value<string>(), "Add files in the directory and subdirectories into filter list") ("prune", "Remove non-existing file paths from the database") ("path", po::value<vector<string> >()->multitoken(), "Paths to process") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if(vm.count("help") > 0) { cout << desc << "\n"; exit(0); }else if(vm.count("path") == 0){ cout << "No paths given, aborting.\n"; exit(1); }else if((vm.count("filter") == 0) && (vm.count("prune") == 0)){ cout << "No operation selected, aborting.\n"; exit(2); } if(vm.count("filter")){ cout << "Adding files to filter with reason \"" << vm["filter"].as<string>() << "\"\n"; } if(vm.count("prune")) { cout << "Pruning database.\n"; } // cout << "Folders to process:\n" << vm["path"].as<vector<string> >() << "\n"; // workaround for printing paths cout << "Folders to process:\n"; vector<string> paths = vm["path"].as<vector<string> >(); for(vector<string>::iterator ite = paths.begin(); ite != paths.end(); ++ite) { cout << *ite << "\n"; } } <|endoftext|>
<commit_before>/* Clique: a scalable implementation of the multifrontal algorithm Copyright (C) 2011 Jack Poulson, Lexing Ying, and The University of Texas at Austin This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "clique.hpp" using namespace elemental; int main( int argc, char* argv[] ) { clique::Initialize( argc, argv ); // TODO clique::Finalize(); return 0; } <commit_msg>Adding a little bit more to the PanelLDL driver.<commit_after>/* Clique: a scalable implementation of the multifrontal algorithm Copyright (C) 2011 Jack Poulson, Lexing Ying, and The University of Texas at Austin This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "clique.hpp" using namespace elemental; void Usage() { std::cout << "PanelLDL <nx> <ny> <nz>\n" << "<nx>: size of panel in x direction\n" << "<ny>: size of panel in y direction\n" << "<nz>: size of panel in z direction\n" << std::endl; } int ReorderedIndex ( int nx, int ny, int nz, int x, int y, int z, int minBalancedDepth, int maxLeafSize ) { // HERE: Call a different recursive routine? } int main( int argc, char* argv[] ) { clique::Initialize( argc, argv ); mpi::Comm comm = mpi::COMM_WORLD; const int commRank = mpi::CommRank( comm ); const int commSize = mpi::CommSize( comm ); // Ensure that we have a power of two number of processes unsigned temp = commSize; unsigned log2CommSize = 0; while( temp >>= 1 ) ++log2CommSize; if( 1u<<log2CommSize != commSize ) { if( commRank == 0 ) { std::cerr << "Must use a power of two number of processes" << std::endl; } clique::Finalize(); return 0; } if( argc < 4 ) { if( commRank == 0 ) Usage(); clique::Finalize(); return 0; } int argNum = 1; const int nx = atoi( argv[argNum++] ); const int ny = atoi( argv[argNum++] ); const int nz = atoi( argv[argNum++] ); if( commRank == 0 ) std::cout << "(nx,ny,nz)=(" << nx << "," << ny << "," << nz << ")" << std::endl; // TODO: Perform the analytical nested dissection and fill the distributed // then local original structures. clique::symbolic::DistSymmOrig distSymmOrig; clique::symbolic::LocalSymmOrig localSymmOrig; for( int s=0; s<log2CommSize; ++s ) { // HERE } // TODO: Call the symbolic factorization routine // TODO: Call the numerical factorization routine // TODO: Call a solve routine clique::Finalize(); return 0; } <|endoftext|>
<commit_before> /* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Test.h" #include "SkRandom.h" #include "SkTSort.h" extern "C" { static int compare_int(const void* a, const void* b) { return *(const int*)a - *(const int*)b; } } static void rand_array(SkRandom& rand, int array[], int n) { for (int j = 0; j < n; j++) { array[j] = rand.nextS() & 0xFF; } } static void check_sort(skiatest::Reporter* reporter, const char label[], const int array[], int n) { for (int j = 1; j < n; j++) { if (array[j-1] > array[j]) { SkString str; str.printf("%sSort [%d] failed %d %d", label, n, array[j-1], array[j]); reporter->reportFailed(str); } } } static void TestSort(skiatest::Reporter* reporter) { int array[500]; SkRandom rand; for (int i = 0; i < 10000; i++) { int count = rand.nextRangeU(1, SK_ARRAY_COUNT(array)); rand_array(rand, array, count); SkTHeapSort<int>(array, count); check_sort(reporter, "Heap", array, count); } if (false) { // avoid bit rot, suppress warning compare_int(array, array); } } // need tests for SkStrSearch #include "TestClassDef.h" DEFINE_TESTCLASS("Sort", SortTestClass, TestSort) <commit_msg>add test for SkChecksum<commit_after> /* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Test.h" #include "SkRandom.h" #include "SkChecksum.h" #include "SkTSort.h" // assert that as we change values (from 0 to non-zero) in our buffer, we // get a different value static void test_checksum(skiatest::Reporter* reporter, size_t size) { SkAutoMalloc storage(size); uint32_t* ptr = (uint32_t*)storage.get(); char* cptr = (char*)ptr; sk_bzero(ptr, size); uint32_t prev = 0; for (size_t i = 0; i < size; ++i) { cptr[i] = 0x5B; // just need some non-zero value here uint32_t curr = SkChecksum::Compute(ptr, size); REPORTER_ASSERT(reporter, prev != curr); prev = curr; } } static void test_checksum(skiatest::Reporter* reporter) { REPORTER_ASSERT(reporter, SkChecksum::Compute(NULL, 0) == 0); for (size_t size = 4; size <= 1000; size += 4) { test_checksum(reporter, size); } } extern "C" { static int compare_int(const void* a, const void* b) { return *(const int*)a - *(const int*)b; } } static void rand_array(SkRandom& rand, int array[], int n) { for (int j = 0; j < n; j++) { array[j] = rand.nextS() & 0xFF; } } static void check_sort(skiatest::Reporter* reporter, const char label[], const int array[], int n) { for (int j = 1; j < n; j++) { if (array[j-1] > array[j]) { SkString str; str.printf("%sSort [%d] failed %d %d", label, n, array[j-1], array[j]); reporter->reportFailed(str); } } } static void TestSort(skiatest::Reporter* reporter) { int array[500]; SkRandom rand; for (int i = 0; i < 10000; i++) { int count = rand.nextRangeU(1, SK_ARRAY_COUNT(array)); rand_array(rand, array, count); SkTHeapSort<int>(array, count); check_sort(reporter, "Heap", array, count); } if (false) { // avoid bit rot, suppress warning compare_int(array, array); } test_checksum(reporter); } // need tests for SkStrSearch #include "TestClassDef.h" DEFINE_TESTCLASS("Sort", SortTestClass, TestSort) <|endoftext|>
<commit_before>// // Aspia Project // Copyright (C) 2020 Dmitry Chapyshev <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // #include "base/settings/json_settings.h" #include "base/logging.h" #include "base/crypto/os_crypt.h" #include "base/files/base_paths.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_file.h" #include "base/strings/string_split.h" #include <rapidjson/document.h> #include <rapidjson/istreamwrapper.h> #include <rapidjson/ostreamwrapper.h> #include <rapidjson/prettywriter.h> namespace base { namespace { std::string createKey(const std::vector<std::string_view>& segments) { std::string key; for (size_t i = 0; i < segments.size(); ++i) { if (i != 0) key += Settings::kSeparator; key.append(segments[i]); } return key; } template <class T> void parseObject(const T& object, std::vector<std::string_view>* segments, Settings::Map* map) { for (auto it = object.MemberBegin(); it != object.MemberEnd(); ++it) { const rapidjson::Value& name = it->name; const rapidjson::Value& value = it->value; segments->emplace_back(name.GetString(), name.GetStringLength()); switch (value.GetType()) { case rapidjson::kObjectType: { parseObject(value.GetObject(), segments, map); } break; case rapidjson::kStringType: { map->emplace(createKey(*segments), std::string(value.GetString(), value.GetStringLength())); } break; case rapidjson::kNumberType: { map->emplace(createKey(*segments), base::numberToString(value.GetInt64())); } break; default: { LOG(LS_WARNING) << "Unexpected type: " << value.GetType(); } break; } segments->pop_back(); } } } // namespace JsonSettings::JsonSettings(std::string_view file_name, Encrypted encrypted) : encrypted_(encrypted) { path_ = filePath(file_name); if (path_.empty()) return; readFile(path_, map()); } JsonSettings::JsonSettings(Scope scope, std::string_view application_name, std::string_view file_name, Encrypted encrypted) : encrypted_(encrypted) { path_ = filePath(scope, application_name, file_name); if (path_.empty()) return; readFile(path_, map(), encrypted_); } JsonSettings::~JsonSettings() { if (isChanged()) writeFile(path_, constMap(), encrypted_); } bool JsonSettings::isWritable() const { std::error_code error_code; if (std::filesystem::exists(path_, error_code)) { std::ofstream stream; stream.open(path_, std::ofstream::binary); return stream.is_open(); } else { if (!std::filesystem::create_directories(path_.parent_path(), error_code)) { if (error_code) return false; } ScopedTempFile temp_file(path_); return temp_file.stream().is_open(); } } void JsonSettings::sync() { readFile(path_, map()); } bool JsonSettings::flush() { return writeFile(path_, map()); } // static std::filesystem::path JsonSettings::filePath(std::string_view file_name) { if (file_name.empty()) return std::filesystem::path(); std::filesystem::path file_path; if (!BasePaths::currentExecDir(&file_path)) return std::filesystem::path(); file_path.append(file_name); file_path.replace_extension("json"); return file_path; } // static std::filesystem::path JsonSettings::filePath(Scope scope, std::string_view application_name, std::string_view file_name) { if (application_name.empty() || file_name.empty()) return std::filesystem::path(); std::filesystem::path file_path; switch (scope) { case Scope::USER: BasePaths::userAppData(&file_path); break; case Scope::SYSTEM: BasePaths::commonAppData(&file_path); break; default: NOTREACHED(); break; } if (file_path.empty()) return std::filesystem::path(); file_path.append(application_name); file_path.append(file_name); file_path.replace_extension("json"); return file_path; } // static bool JsonSettings::readFile(const std::filesystem::path& file, Map& map, Encrypted encrypted) { map.clear(); std::error_code ignored_code; std::filesystem::file_status status = std::filesystem::status(file, ignored_code); if (!std::filesystem::exists(status)) { // The absence of a configuration file is normal case. return true; } if (!std::filesystem::is_regular_file(status)) { LOG(LS_ERROR) << "The specified configuration file is not a file"; return false; } if (std::filesystem::is_empty(file, ignored_code)) { // The configuration file may be empty. return true; } std::string buffer; if (!base::readFile(file, &buffer)) { LOG(LS_ERROR) << "Failed to read config file"; return false; } if (encrypted == Encrypted::YES) { std::string decrypted; if (!OSCrypt::decryptString(buffer, &decrypted)) { LOG(LS_ERROR) << "Failed to decrypt config file"; return false; } buffer.swap(decrypted); } rapidjson::StringStream stream(buffer.data()); rapidjson::Document doc; doc.ParseStream(stream); if (doc.HasParseError()) { LOG(LS_ERROR) << "The configuration file is damaged: " << doc.GetParseError(); return false; } std::vector<std::string_view> segments; parseObject(doc, &segments, &map); return true; } // static bool JsonSettings::writeFile(const std::filesystem::path& file, const Map& map, Encrypted encrypted) { std::error_code error_code; if (!std::filesystem::create_directories(file.parent_path(), error_code)) { if (error_code) { LOG(LS_WARNING) << "create_directories failed: " << base::utf16FromLocal8Bit(error_code.message()); return false; } } rapidjson::StringBuffer buffer; rapidjson::PrettyWriter<rapidjson::StringBuffer> json(buffer); // Start JSON document. json.StartObject(); std::vector<std::string_view> prev; for (const auto& map_item : map) { std::vector<std::string_view> segments = splitStringView(map_item.first, "/", TRIM_WHITESPACE, SPLIT_WANT_NONEMPTY); size_t count = 0; while (count < prev.size() && segments.at(count) == prev.at(count)) ++count; for (int i = static_cast<int>(prev.size()) - 1; i > static_cast<int>(count); --i) json.EndObject(); for (size_t i = count; i < segments.size(); ++i) { if (i != segments.size() - 1) { std::string_view& segment = segments[i]; json.Key(segment.data(), segment.length()); json.StartObject(); } } std::string_view& segment = segments.back(); json.Key(segment.data(), segment.length()); json.String(map_item.second.data(), map_item.second.length()); prev.swap(segments); } if (!prev.empty()) { // End objects. for (size_t i = 0; i < prev.size() - 1; ++i) json.EndObject(); } // End JSON document. json.EndObject(); if (!json.IsComplete()) { LOG(LS_ERROR) << "Incomplete json document"; return false; } std::string_view source_buffer(buffer.GetString(), buffer.GetSize()); if (encrypted == Encrypted::YES) { std::string cipher_buffer; if (!OSCrypt::encryptString(source_buffer, &cipher_buffer)) { LOG(LS_ERROR) << "Failed to encrypt config file"; return false; } if (!base::writeFile(file, cipher_buffer)) { LOG(LS_ERROR) << "Failed to write config file"; return false; } } else { DCHECK_EQ(encrypted, Encrypted::NO); if (!base::writeFile(file, source_buffer)) { LOG(LS_ERROR) << "Failed to write config file"; return false; } } return true; } } // namespace base <commit_msg>Added check of the maximum size of the settings file.<commit_after>// // Aspia Project // Copyright (C) 2020 Dmitry Chapyshev <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // #include "base/settings/json_settings.h" #include "base/logging.h" #include "base/crypto/os_crypt.h" #include "base/files/base_paths.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_file.h" #include "base/strings/string_split.h" #include <rapidjson/document.h> #include <rapidjson/istreamwrapper.h> #include <rapidjson/ostreamwrapper.h> #include <rapidjson/prettywriter.h> namespace base { namespace { std::string createKey(const std::vector<std::string_view>& segments) { std::string key; for (size_t i = 0; i < segments.size(); ++i) { if (i != 0) key += Settings::kSeparator; key.append(segments[i]); } return key; } template <class T> void parseObject(const T& object, std::vector<std::string_view>* segments, Settings::Map* map) { for (auto it = object.MemberBegin(); it != object.MemberEnd(); ++it) { const rapidjson::Value& name = it->name; const rapidjson::Value& value = it->value; segments->emplace_back(name.GetString(), name.GetStringLength()); switch (value.GetType()) { case rapidjson::kObjectType: { parseObject(value.GetObject(), segments, map); } break; case rapidjson::kStringType: { map->emplace(createKey(*segments), std::string(value.GetString(), value.GetStringLength())); } break; case rapidjson::kNumberType: { map->emplace(createKey(*segments), base::numberToString(value.GetInt64())); } break; default: { LOG(LS_WARNING) << "Unexpected type: " << value.GetType(); } break; } segments->pop_back(); } } } // namespace JsonSettings::JsonSettings(std::string_view file_name, Encrypted encrypted) : encrypted_(encrypted) { path_ = filePath(file_name); if (path_.empty()) return; readFile(path_, map()); } JsonSettings::JsonSettings(Scope scope, std::string_view application_name, std::string_view file_name, Encrypted encrypted) : encrypted_(encrypted) { path_ = filePath(scope, application_name, file_name); if (path_.empty()) return; readFile(path_, map(), encrypted_); } JsonSettings::~JsonSettings() { if (isChanged()) writeFile(path_, constMap(), encrypted_); } bool JsonSettings::isWritable() const { std::error_code error_code; if (std::filesystem::exists(path_, error_code)) { std::ofstream stream; stream.open(path_, std::ofstream::binary); return stream.is_open(); } else { if (!std::filesystem::create_directories(path_.parent_path(), error_code)) { if (error_code) return false; } ScopedTempFile temp_file(path_); return temp_file.stream().is_open(); } } void JsonSettings::sync() { readFile(path_, map()); } bool JsonSettings::flush() { return writeFile(path_, map()); } // static std::filesystem::path JsonSettings::filePath(std::string_view file_name) { if (file_name.empty()) return std::filesystem::path(); std::filesystem::path file_path; if (!BasePaths::currentExecDir(&file_path)) return std::filesystem::path(); file_path.append(file_name); file_path.replace_extension("json"); return file_path; } // static std::filesystem::path JsonSettings::filePath(Scope scope, std::string_view application_name, std::string_view file_name) { if (application_name.empty() || file_name.empty()) return std::filesystem::path(); std::filesystem::path file_path; switch (scope) { case Scope::USER: BasePaths::userAppData(&file_path); break; case Scope::SYSTEM: BasePaths::commonAppData(&file_path); break; default: NOTREACHED(); break; } if (file_path.empty()) return std::filesystem::path(); file_path.append(application_name); file_path.append(file_name); file_path.replace_extension("json"); return file_path; } // static bool JsonSettings::readFile(const std::filesystem::path& file, Map& map, Encrypted encrypted) { map.clear(); std::error_code ignored_code; std::filesystem::file_status status = std::filesystem::status(file, ignored_code); if (!std::filesystem::exists(status)) { // The absence of a configuration file is normal case. return true; } if (!std::filesystem::is_regular_file(status)) { LOG(LS_ERROR) << "Specified configuration file is not a file: '" << file << "'"; return false; } if (std::filesystem::is_empty(file, ignored_code)) { // The configuration file may be empty. return true; } static const uintmax_t kMaxFileSize = 5 * 1024 * 2024; // 5 Mb. uintmax_t file_size = std::filesystem::file_size(file, ignored_code); if (file_size > kMaxFileSize) { LOG(LS_ERROR) << "Too big settings file: '" << file << "' (" << file_size << " bytes)"; return false; } std::string buffer; if (!base::readFile(file, &buffer)) { LOG(LS_ERROR) << "Failed to read config file: '" << file << "'"; return false; } if (encrypted == Encrypted::YES) { std::string decrypted; if (!OSCrypt::decryptString(buffer, &decrypted)) { LOG(LS_ERROR) << "Failed to decrypt config file: '" << file << "'"; return false; } buffer.swap(decrypted); } rapidjson::StringStream stream(buffer.data()); rapidjson::Document doc; doc.ParseStream(stream); if (doc.HasParseError()) { LOG(LS_ERROR) << "The configuration file is damaged: '" << file << "' (" << doc.GetParseError() << ")"; return false; } std::vector<std::string_view> segments; parseObject(doc, &segments, &map); return true; } // static bool JsonSettings::writeFile(const std::filesystem::path& file, const Map& map, Encrypted encrypted) { std::error_code error_code; if (!std::filesystem::create_directories(file.parent_path(), error_code)) { if (error_code) { LOG(LS_WARNING) << "create_directories failed: " << base::utf16FromLocal8Bit(error_code.message()); return false; } } rapidjson::StringBuffer buffer; rapidjson::PrettyWriter<rapidjson::StringBuffer> json(buffer); // Start JSON document. json.StartObject(); std::vector<std::string_view> prev; for (const auto& map_item : map) { std::vector<std::string_view> segments = splitStringView(map_item.first, "/", TRIM_WHITESPACE, SPLIT_WANT_NONEMPTY); size_t count = 0; while (count < prev.size() && segments.at(count) == prev.at(count)) ++count; for (int i = static_cast<int>(prev.size()) - 1; i > static_cast<int>(count); --i) json.EndObject(); for (size_t i = count; i < segments.size(); ++i) { if (i != segments.size() - 1) { std::string_view& segment = segments[i]; json.Key(segment.data(), segment.length()); json.StartObject(); } } std::string_view& segment = segments.back(); json.Key(segment.data(), segment.length()); json.String(map_item.second.data(), map_item.second.length()); prev.swap(segments); } if (!prev.empty()) { // End objects. for (size_t i = 0; i < prev.size() - 1; ++i) json.EndObject(); } // End JSON document. json.EndObject(); if (!json.IsComplete()) { LOG(LS_ERROR) << "Incomplete json document"; return false; } std::string_view source_buffer(buffer.GetString(), buffer.GetSize()); if (encrypted == Encrypted::YES) { std::string cipher_buffer; if (!OSCrypt::encryptString(source_buffer, &cipher_buffer)) { LOG(LS_ERROR) << "Failed to encrypt config file"; return false; } if (!base::writeFile(file, cipher_buffer)) { LOG(LS_ERROR) << "Failed to write config file"; return false; } } else { DCHECK_EQ(encrypted, Encrypted::NO); if (!base::writeFile(file, source_buffer)) { LOG(LS_ERROR) << "Failed to write config file"; return false; } } return true; } } // namespace base <|endoftext|>
<commit_before>#include <vector> #include <map> #include <set> #include <cassert> #include <utility> class LRUCache { private: // an entity keeps track of key,value and timestamp struct Entity { int key, value; unsigned int timestamp; Entity(int k, int v, int ts) : key(k) , value(v) , timestamp(ts) { } struct EntityLess { bool operator() (const Entity& a, const Entity& b) const { return a.timestamp < b.timestamp; } }; }; public: unsigned int capacity; unsigned int timestamp; // "cache" does lookup in logarithmic time std::map<int, Entity> cache; // "pool" maintains timestamp in logarithmic time std::set<Entity,Entity::EntityLess> pool; // here redundant data are kept: // it is possible to share Entity instances // in "cache" and "pool" // but we choose not to for the sake of simplicity // the basic idea to make every "get" and "set" done // in logarithmic time is to maintain "cache" and "pool" // simultaneously. // here I think the biggest problem is to identify the "least recent entity" // and remove it when the size exceeds the capacity. // for std::set, its first element is guaranteed to be the minimum, // so it can be used to remove the oldest content in logarithmic time. // see: http://www.cplusplus.com/reference/set/set/begin/ // Since we are maintaining both "cache" and "pool", // at each return point of each method, we must make sure // the corresponding manipulations are performed on both structures. LRUCache(int _capacity) : capacity(_capacity) , timestamp(0) , cache() , pool(){ } int get(int key) { tick(); // O(log(n)) std::map<int, Entity>::iterator result = cache.find(key); if (result == cache.end()) return -1; // update the timestamp because we are // "using this value" Entity e = result->second; // we delete the element, pool.erase(e); // modify the key, e.timestamp = timestamp; // and insert it again // making it an "element update" pool.insert(e); // and this update runs in // O(log(n)) + O(log(n)) = O(log(n)) time // "cache" actually doesn't care about this value, // but here it's still important to // synchorize what we've done in "pool" result->second.timestamp = timestamp; return e.value; } void set(int key, int value) { tick(); std::map<int, Entity>::iterator result = cache.find(key); if (result != cache.end()) { // old value are removed here // "pool" only cares about the timestamp, // the other two values are unnecessary pool.erase( Entity(-1,-1,result->second.timestamp) ); // also remove it from "cache" cache.erase( result ); // runs in: // O(log(n)) + O(log(n)) = O(log(n)) time } Entity e(key,value,timestamp); // O(log(n)), insert both in "cache" and in "pool" cache.insert( std::pair<int,Entity>(key,e) ); pool.insert(e); // after an insertion, the element size might exceed the capacity, // if this is the case, remove the oldest one if (cache.size() > capacity) removeOldest(); } private: void tick() { // every expose operation bumps // the timestamp first. // this will ensure the uniqueness of timestamp. // since for the "pool" set, we only care about // the timestamp, so we need this uniqueness // to avoid accidental deletion of other elements ++timestamp; } void removeOldest() { // here pool.begin() must point to the // minimum (in terms of timestamp) Entity // O(log(n)) std::map<int, Entity>::iterator result = cache.find(pool.begin()->key); // O(log(n)) cache.erase(result); // O(log(n)) pool.erase( pool.begin() ); } }; #include <gtest/gtest.h> namespace { } // namespace int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } // Local variables: // flycheck-gcc-definitions: ("NOT_OJ") // End: <commit_msg>LRUCache - testcases<commit_after>#include <vector> #include <map> #include <set> #include <cassert> #include <utility> class LRUCache { private: // an entity keeps track of key,value and timestamp struct Entity { int key, value; unsigned int timestamp; Entity(int k, int v, int ts) : key(k) , value(v) , timestamp(ts) { } struct EntityLess { bool operator() (const Entity& a, const Entity& b) const { return a.timestamp < b.timestamp; } }; }; public: unsigned int capacity; unsigned int timestamp; // "cache" does lookup in logarithmic time std::map<int, Entity> cache; // "pool" maintains timestamp in logarithmic time std::set<Entity,Entity::EntityLess> pool; // here redundant data are kept: // it is possible to share Entity instances // in "cache" and "pool" // but we choose not to for the sake of simplicity // the basic idea to make every "get" and "set" done // in logarithmic time is to maintain "cache" and "pool" // simultaneously. // here I think the biggest problem is to identify the "least recent entity" // and remove it when the size exceeds the capacity. // for std::set, its first element is guaranteed to be the minimum, // so it can be used to remove the oldest content in logarithmic time. // see: http://www.cplusplus.com/reference/set/set/begin/ // Since we are maintaining both "cache" and "pool", // at each return point of each method, we must make sure // the corresponding manipulations are performed on both structures. LRUCache(int _capacity) : capacity(_capacity) , timestamp(0) , cache() , pool(){ } int get(int key) { tick(); // O(log(n)) std::map<int, Entity>::iterator result = cache.find(key); if (result == cache.end()) return -1; // update the timestamp because we are // "using this value" Entity e = result->second; // we delete the element, pool.erase(e); // modify the key, e.timestamp = timestamp; // and insert it again // making it an "element update" pool.insert(e); // and this update runs in // O(log(n)) + O(log(n)) = O(log(n)) time // "cache" actually doesn't care about this value, // but here it's still important to // synchorize what we've done in "pool" result->second.timestamp = timestamp; return e.value; } void set(int key, int value) { tick(); std::map<int, Entity>::iterator result = cache.find(key); if (result != cache.end()) { // old value are removed here // "pool" only cares about the timestamp, // the other two values are unnecessary pool.erase( Entity(-1,-1,result->second.timestamp) ); // also remove it from "cache" cache.erase( result ); // runs in: // O(log(n)) + O(log(n)) = O(log(n)) time } Entity e(key,value,timestamp); // O(log(n)), insert both in "cache" and in "pool" cache.insert( std::pair<int,Entity>(key,e) ); pool.insert(e); // after an insertion, the element size might exceed the capacity, // if this is the case, remove the oldest one if (cache.size() > capacity) removeOldest(); } private: void tick() { // every expose operation bumps // the timestamp first. // this will ensure the uniqueness of timestamp. // since for the "pool" set, we only care about // the timestamp, so we need this uniqueness // to avoid accidental deletion of other elements ++timestamp; } void removeOldest() { // here pool.begin() must point to the // minimum (in terms of timestamp) Entity // O(log(n)) std::map<int, Entity>::iterator result = cache.find(pool.begin()->key); // O(log(n)) cache.erase(result); // O(log(n)) pool.erase( pool.begin() ); } }; #include <gtest/gtest.h> namespace { #define GET(ADDR,EXPECT) { \ EXPECT_EQ(EXPECT,lru.get(ADDR)); \ } \ #define SET(ADDR,VALUE) { \ lru.set(ADDR,VALUE); \ } #define MY_TEST(TN,T,C,...) TEST(TN,T) { \ LRUCache lru(C); \ __VA_ARGS__; \ } MY_TEST(LRUCache,Simple,10, SET(1,123); SET(2,456); GET(1,123); GET(2,456);) MY_TEST(LRUCache,Overwrite,10, SET(1,123); SET(1,456); GET(2,-1); GET(1,456);) MY_TEST(LRUCache,Expire,2, SET(1,123); SET(2,456); SET(3,789); GET(1,-1); GET(2,456); GET(3,789);) MY_TEST(LRUCache,TouchOld,2, SET(1,123); SET(2,456); GET(1,123); SET(3,789); GET(1,123); GET(2,-1); GET(3,789);) #undef GET #undef SET #undef MY_TEST } // namespace int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } // Local variables: // flycheck-gcc-definitions: ("NOT_OJ") // End: <|endoftext|>
<commit_before>/* * Author Joshua Flank * September 2017 * Basic functionality to solve a 5x5 cube, filled wtih Z's * * This should solve the puzzle, in around 778 billion Z placements. * If done 1 second per piece, it would take around 25 years */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <math.h> #include <time.h> #include <sys/time.h> #include <X11/Xlib.h> #include <errno.h> #include "Solve5x5.h" #include "GLcube.h" extern LedCube * myPortCubeP; //declared in main.cpp const char * directions[] = { "enee", //jhf this is a cheat for 'A' but we got to start somewhere // "uuwu", //uncomment to speed up the process considerably. // "uunu", //uncomment to speed up the process considerably. // "nnen", //uncomment to speed up the process considerably. "esee", "euee", "eene", "eese", "eeue", "unuu", "usuu", "ueuu", "uwuu", "uunu", //This is the B worm - move to top to speed up the processing "uusu", "uueu", "uuwu", //This is the C worm - move to top to speed up the processing // cannot go down "ewnww", "ewsww", "ewuww", "eewwnw", "eewwsw", "eewwuw", "nsess", "nswss", "nsuss", "nnsses", "nnssws", "nnssus", "nenn", "nwnn", "nunn", "nnen", //This is the D worm - move to top to speed up the processing "nnwn", "nnun", "" }; int SolveCube::init() { int i,j,k; LedCube::init(); for (i = 0; i < 5; i ++){ for (j = 0; j < 5; j ++){ for (k = 0; k < 5; k ++){ m_box[i][j][k] = DEFVAL; } } } return 0; } int SolveCube::printBox() { int x,y,z; // printf ("----------------------\n"); for (z = 0; z < 5; z ++){ for (y = 0; y < 5; y ++){ for (x = 0; x < 5; x ++){ printf("%c", m_box[x][y][z]); } printf(" "); } printf ("\n"); } return 0; } int SolveCube::shareBox() { pthread_mutex_lock( &m_mutex); int x,y,z; // printf ("----------------------\n"); for (z = 0; z < 5; z ++) { for (y = 0; y < 5; y ++) { for (x = 0; x < 5; x ++) { if (m_box[x][y][z] == DEFVAL) { m_cube[x][y][z] = 0; } else { rgb_t rgb; rgb.word = 0; rgb.color.red = 100; rgb.color.green = 10 * (m_box[x][y][z] - BASEWORM); rgb.color.blue = 50 *((m_box[x][y][z] - BASEWORM) % 3) ; // :) convenient that there are 255 colors, and 25 worms... AND 26 chars! m_cube[x][y][z] = rgb.word; } } } } pthread_mutex_unlock( &m_mutex); return 0; } int SolveCube::moveWorm (int *xP, int *yP, int *zP, char val, char dir, int erase) { switch (dir) { case 'u': *zP = *zP + 1; if (*zP > 4) return 1; break; case 'd': *zP = *zP - 1; if (*zP < 0) return 1; break; case 'e': *xP = *xP + 1; if (*xP > 4) return 1; break; case 'w': *xP = *xP - 1; if (*xP < 0) return 1; break; case 'n': *yP = *yP + 1; if (*yP > 4) return 1; break; case 's': *yP = *yP - 1; if (*yP < 0) return 1; break; } if (m_box[*xP][*yP][*zP] == DEFVAL || m_box[*xP][*yP][*zP] == val) { if (erase == 0) m_box[*xP][*yP][*zP] = val; else m_box[*xP][*yP][*zP] = DEFVAL; } else return 1; return 0; } int SolveCube::addWorm(int x, int y, int z, char val, int trial, int erase) { int i, x1=x,y1=y,z1=z; if (erase == 0) m_box[x][y][z] = val; else m_box[x][y][z] = DEFVAL; for (i = 0; directions[trial][i] != '\0'; i ++ ) { if (moveWorm(&x1, &y1, &z1, val, directions[trial][i], erase) == 1 && erase == 0) { erase = 1; break; } } return erase; } int numiter = 0; int totaliter = 0; #define inctotaliter 1000 int numiter2 = 0; int totaliter2 = 0; #define inctotaliter2 1000000 int SolveCube::solver(int wormID) { int x,y,z, trial; if (wormID == 25) { // done! shareBox(); cubeToCube(myGLCubeP); totaliter = totaliter * inctotaliter + numiter; printf ("totaliter: %d * %d\n", totaliter, inctotaliter); return 0; } numiter ++; if (m_speed > 0 && m_speed < 1000000) { usleep(1000000 - m_speed); shareBox(); cubeToCube(myGLCubeP); // this may do nothing if GLcube wasn't created. cubeToCube(myPortCubeP);// this may do nothing if Portcube wasn't created. } if (numiter >= inctotaliter) { numiter = 0; totaliter++; shareBox(); cubeToCube(myGLCubeP); // this may do nothing if GLcube wasn't created. cubeToCube(myPortCubeP);// this may do nothing if Portcube wasn't created. // printBox(); //jhf test // drawCube(); } numiter2 ++; if (numiter2 == inctotaliter2) { totaliter2++; printf ("iter: %d * %d\n", totaliter2, inctotaliter2); numiter2 = 0; printBox(); } for (z = 0; z < 5; z ++) { for (y = 0; y < 5; y ++) { for (x = 0; x < 5; x ++) { if (m_box[x][y][z] == DEFVAL) { for (trial = 0; directions[trial][0] != '\0'; trial ++) { if (addWorm(x,y,z, wormID + BASEWORM, trial, 0) == 1) { addWorm(x,y,z, wormID + BASEWORM, trial, 1); continue; } if (solver(wormID + 1) == 0) return 0; addWorm(x,y,z, wormID + BASEWORM, trial, 1); } return 1; } } } } return 1; } SolveCube::SolveCube() : LedCube() { return; } void * mainsolve(void * ptr) { cout << "Starting SolveCube\n"; mySolveCubeP->init(); mySolveCubeP->printBox(); mySolveCubeP->solver(0); mySolveCubeP->printBox(); return 0; } <commit_msg>reorient and colorfy solve55 more<commit_after>/* * Author Joshua Flank * September 2017 * Basic functionality to solve a 5x5 cube, filled wtih Z's * * This should solve the puzzle, in around 778 billion Z placements. * If done 1 second per piece, it would take around 25 years */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <math.h> #include <time.h> #include <sys/time.h> #include <X11/Xlib.h> #include <errno.h> #include "Solve5x5.h" #include "GLcube.h" extern LedCube * myPortCubeP; //declared in main.cpp const char * directions[] = { "enee", //jhf this is a cheat for 'A' but we got to start somewhere // "uuwu", //uncomment to speed up the process considerably. // "uunu", //uncomment to speed up the process considerably. // "nnen", //uncomment to speed up the process considerably. "esee", "euee", "eene", "eese", "eeue", "unuu", "usuu", "ueuu", "uwuu", "uunu", //This is the B worm - move to top to speed up the processing "uusu", "uueu", "uuwu", //This is the C worm - move to top to speed up the processing // cannot go down "ewnww", "ewsww", "ewuww", "eewwnw", "eewwsw", "eewwuw", "nsess", "nswss", "nsuss", "nnsses", "nnssws", "nnssus", "nenn", "nwnn", "nunn", "nnen", //This is the D worm - move to top to speed up the processing "nnwn", "nnun", "" }; int SolveCube::init() { int i,j,k; LedCube::init(); for (i = 0; i < 5; i ++){ for (j = 0; j < 5; j ++){ for (k = 0; k < 5; k ++){ m_box[i][j][k] = DEFVAL; } } } return 0; } int SolveCube::printBox() { int x,y,z; // printf ("----------------------\n"); for (z = 0; z < 5; z ++){ for (y = 0; y < 5; y ++){ for (x = 0; x < 5; x ++){ printf("%c", m_box[x][y][z]); } printf(" "); } printf ("\n"); } return 0; } /* * copy from m_box to m_cube, in preparation to copy to another cube. */ int SolveCube::shareBox() { int move = 1; pthread_mutex_lock( &m_mutex); int x,y,z; // printf ("----------------------\n"); for (z = 0; z < 5; z ++) { for (y = 0; y < 5; y ++) { for (x = 0; x < 5; x ++) { if (m_box[x][y][z] == DEFVAL) { m_cube[x+move][y+move][z+move] = 0; } else { rgb_t rgb; rgb.word = 0; if (m_box[x][y][z] % 2 == 0) { rgb.color.green = 100; rgb.color.red = 10 * (m_box[x][y][z] - BASEWORM); } else { rgb.color.red = 100; rgb.color.green = 10 * (m_box[x][y][z] - BASEWORM); } rgb.color.blue = 50 *((m_box[x][y][z] - BASEWORM) % 3) ; // :) convenient that there are 255 colors, and 25 worms... AND 26 chars! m_cube[x+move][y+move][z+move] = rgb.word; } } } } pthread_mutex_unlock( &m_mutex); return 0; } int SolveCube::moveWorm (int *xP, int *yP, int *zP, char val, char dir, int erase) { switch (dir) { case 'u': *zP = *zP + 1; if (*zP > 4) return 1; break; case 'd': *zP = *zP - 1; if (*zP < 0) return 1; break; case 'e': *xP = *xP + 1; if (*xP > 4) return 1; break; case 'w': *xP = *xP - 1; if (*xP < 0) return 1; break; case 'n': *yP = *yP + 1; if (*yP > 4) return 1; break; case 's': *yP = *yP - 1; if (*yP < 0) return 1; break; } if (m_box[*xP][*yP][*zP] == DEFVAL || m_box[*xP][*yP][*zP] == val) { if (erase == 0) m_box[*xP][*yP][*zP] = val; else m_box[*xP][*yP][*zP] = DEFVAL; } else return 1; return 0; } int SolveCube::addWorm(int x, int y, int z, char val, int trial, int erase) { int i, x1=x,y1=y,z1=z; if (erase == 0) m_box[x][y][z] = val; else m_box[x][y][z] = DEFVAL; for (i = 0; directions[trial][i] != '\0'; i ++ ) { if (moveWorm(&x1, &y1, &z1, val, directions[trial][i], erase) == 1 && erase == 0) { erase = 1; break; } } return erase; } int numiter = 0; int totaliter = 0; #define inctotaliter 1000 int numiter2 = 0; int totaliter2 = 0; #define inctotaliter2 1000000 int SolveCube::solver(int wormID) { int x,y,z, trial; if (wormID == 25) { // done! shareBox(); cubeToCube(myGLCubeP); totaliter = totaliter * inctotaliter + numiter; printf ("totaliter: %d * %d\n", totaliter, inctotaliter); return 0; } numiter ++; if (m_speed > 0 && m_speed < 1000000) { usleep(1000000 - m_speed); shareBox(); printBox(); cubeToCube(myGLCubeP); // this may do nothing if GLcube wasn't created. cubeToCube(myPortCubeP);// this may do nothing if Portcube wasn't created. } if (numiter >= inctotaliter) { numiter = 0; totaliter++; shareBox(); cubeToCube(myGLCubeP); // this may do nothing if GLcube wasn't created. cubeToCube(myPortCubeP);// this may do nothing if Portcube wasn't created. // printBox(); //jhf test // drawCube(); } numiter2 ++; if (numiter2 == inctotaliter2) { totaliter2++; printf ("iter: %d * %d\n", totaliter2, inctotaliter2); numiter2 = 0; printBox(); } for (z = 0; z < 5; z ++) { for (y = 0; y < 5; y ++) { for (x = 0; x < 5; x ++) { if (m_box[x][y][z] == DEFVAL) { for (trial = 0; directions[trial][0] != '\0'; trial ++) { if (addWorm(x,y,z, wormID + BASEWORM, trial, 0) == 1) { addWorm(x,y,z, wormID + BASEWORM, trial, 1); continue; } if (solver(wormID + 1) == 0) return 0; addWorm(x,y,z, wormID + BASEWORM, trial, 1); } return 1; } } } } return 1; } SolveCube::SolveCube() : LedCube() { return; } void * mainsolve(void * ptr) { cout << "Starting SolveCube\n"; mySolveCubeP->init(); mySolveCubeP->printBox(); mySolveCubeP->solver(0); mySolveCubeP->printBox(); return 0; } <|endoftext|>
<commit_before>// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. #include "winshellintegration/application.h" #include "winshellintegration/winapi.h" // SetCurrentProcessExplicitAppUserModelID, // GetCurrentProcessExplicitAppUserModelID, // COM, // Shell #include "winshellintegration/COM_errors.h" // errors::throwCOMException #include "winshellintegration/jump_item.h" // JumpItem #include "winshellintegration/jump_task.h" // JumpTask #include "winshellintegration/jump_list.h" // JumpList #include <string_view> // std::string_view #include <exception> // std::uncaught_exceptions #include <stdexcept> // std::logic_error #include <cassert> // assert namespace intellij::ui::win { // ================================================================================================================ // JumpListTransaction // ================================================================================================================ namespace { class JumpListTransaction final { public: static constexpr std::string_view jumpListTransactionCtxName = "intellij::ui::win::Application::JumpListTransaction"; UINT maxSlots; CComPtr<IObjectArray> removedObjects; public: // ctors/dtor explicit JumpListTransaction(ICustomDestinationList* jumpListHandle) noexcept(false) : handle_(nullptr) , maxSlots(0) { auto hr = jumpListHandle->BeginList(&maxSlots, IID_PPV_ARGS(&removedObjects)); if (hr != S_OK) errors::throwCOMException( hr, "ICustomDestinationList::BeginList failed", __func__, jumpListTransactionCtxName ); assert( (removedObjects != nullptr) ); handle_ = jumpListHandle; } // non-copyable JumpListTransaction(const JumpListTransaction&) = delete; // non-movable JumpListTransaction(JumpListTransaction&&) = delete; ~JumpListTransaction() noexcept(false) { if (handle_ == nullptr) return; auto *const localHandle = handle_; handle_ = nullptr; const auto hr = localHandle->AbortList(); if (std::uncaught_exceptions() != 0) assert( (hr == S_OK) ); else if (hr != S_OK) errors::throwCOMException( hr, "ICustomDestinationList::AbortList failed", __func__, jumpListTransactionCtxName ); } public: // non-copyable JumpListTransaction& operator=(const JumpListTransaction&) = delete; // non-movable JumpListTransaction& operator=(JumpListTransaction&&) = delete; public: void commit() noexcept(false) { if (handle_ == nullptr) return; if (const auto hr = handle_->CommitList(); hr != S_OK) errors::throwCOMException( hr, "ICustomDestinationList::CommitList failed", __func__, jumpListTransactionCtxName ); handle_ = nullptr; } public: [[nodiscard]] ICustomDestinationList* operator->() const noexcept { assert( (handle_ != nullptr) ); return handle_; } [[nodiscard]] ICustomDestinationList& operator*() const noexcept { assert( (handle_ != nullptr) ); return *handle_; } private: ICustomDestinationList* handle_; }; } // namespace // ================================================================================================================ // Some helpers // ================================================================================================================ namespace { CComPtr<IObjectCollection> createCategoryNativeContainer( const std::string_view callerFuncName, const std::string_view callerCtxName) noexcept(false) { CComPtr<IObjectCollection> result; auto hr = result.CoCreateInstance( CLSID_EnumerableObjectCollection, nullptr, CLSCTX_INPROC ); if (hr != S_OK) errors::throwCOMException( hr, "CoCreateInstance(CLSID_EnumerableObjectCollection) failed", callerFuncName, callerCtxName ); assert( (result != nullptr) ); return result; } void insertToCategoryNativeContainer( IObjectCollection& nativeContainer, const JumpList::value_type& item, const std::string_view callerFuncName, const std::string_view callerCtxName, COMIsInitializedInThisThreadTag com) noexcept(false) { std::visit( [&nativeContainer, callerFuncName, callerCtxName, com](const auto& unwrappedItem) { auto hr = nativeContainer.AddObject(unwrappedItem.shareNativeHandle(com)); if (hr != S_OK) errors::throwCOMException( hr, "IObjectCollection::AddObject failed", callerFuncName, callerCtxName ); }, item ); } [[nodiscard]] CComPtr<ICustomDestinationList> createJumpListHandle( const Application::UserModelId* appId, const std::string_view callerFuncName, const std::string_view callerCtxName) noexcept(false) { CComPtr<ICustomDestinationList> result = nullptr; auto hr = result.CoCreateInstance( CLSID_DestinationList, nullptr, CLSCTX_INPROC ); if (hr != S_OK) errors::throwCOMException( hr, "CoCreateInstance(CLSID_DestinationList) failed", callerFuncName, callerCtxName ); assert( (result != nullptr) ); if (appId != nullptr) { if (hr = result->SetAppID(appId->c_str()); hr != S_OK) errors::throwCOMException( hr, "ICustomDestinationList::SetAppID failed", callerFuncName, callerCtxName ); } return result; } [[nodiscard]] CComPtr<IApplicationDestinations> createRecentsAndFrequentsHandle( const Application::UserModelId* appId, const std::string_view callerFuncName, const std::string_view callerCtxName) noexcept(false) { CComPtr<IApplicationDestinations> result = nullptr; auto hr = result.CoCreateInstance( CLSID_ApplicationDestinations, nullptr, CLSCTX_INPROC ); if (hr != S_OK) errors::throwCOMException( hr, "CoCreateInstance(CLSID_ApplicationDestinations) failed", callerFuncName, callerCtxName ); assert( (result != nullptr) ); if (appId != nullptr) { if (hr = result->SetAppID(appId->c_str()); hr != S_OK) errors::throwCOMException( hr, "IApplicationDestinations::SetAppID failed", callerFuncName, callerCtxName ); } return result; } void appendCustomCategoryTo( ICustomDestinationList& jumpListHandle, const WideString& categoryName, const JumpList::CustomCategoryContainer& items, const std::string_view callerFuncName, const std::string_view callerCtxName, COMIsInitializedInThisThreadTag com) noexcept(false) { if (items.empty()) return; const auto nativeContainer = createCategoryNativeContainer(callerFuncName, callerCtxName); for (const auto& item: items) insertToCategoryNativeContainer(*nativeContainer, item, callerFuncName, callerCtxName, com); if (const auto hr = jumpListHandle.AppendCategory(categoryName.c_str(), nativeContainer); hr != S_OK) errors::throwCOMException( hr, "ICustomDestinationList::AppendCategory failed", callerFuncName, callerCtxName ); } void appendUserTasksTo( ICustomDestinationList& jumpListHandle, const JumpList::UserTasksCategoryContainer& items, const std::string_view callerFuncName, const std::string_view callerCtxName, COMIsInitializedInThisThreadTag com) noexcept(false) { if (items.empty()) return; const auto nativeContainer = createCategoryNativeContainer(callerFuncName, callerCtxName); for (const auto& item: items) insertToCategoryNativeContainer(*nativeContainer, item, callerFuncName, callerCtxName, com); if (const auto hr = jumpListHandle.AddUserTasks(nativeContainer); hr != S_OK) errors::throwCOMException( hr, "ICustomDestinationList::AddUserTasks failed", callerFuncName, callerCtxName ); } } // namespace // ================================================================================================================ // Application // ================================================================================================================ static constexpr std::string_view applicationCtxName = "intellij::ui::win::Application"; Application::Application() noexcept = default; Application::~Application() noexcept = default; Application& Application::getInstance() noexcept { static Application instance; return instance; } void Application::setAppUserModelId(const UserModelId& appId) noexcept(false) { if (const auto hr = SetCurrentProcessExplicitAppUserModelID(appId.c_str()); hr != S_OK) errors::throwCOMException( hr, "SetCurrentProcessExplicitAppUserModelID failed", __func__, applicationCtxName ); } void Application::registerRecentlyUsed(const std::filesystem::path& path) noexcept(false) { SHAddToRecentDocs(SHARD_PATHW, path.c_str()); } void Application::registerRecentlyUsed( const JumpItem& recentJumpItem, COMIsInitializedInThisThreadTag com) noexcept(false) { refreshJumpListHandle(); auto& [appId_, jumpListHandle_] = idAndJumpListHandle_; const auto itemHandle = recentJumpItem.shareNativeHandle(com); if (appId_.has_value()) { SHARDAPPIDINFO jumpItemInfo{}; jumpItemInfo.psi = itemHandle; jumpItemInfo.pszAppID = appId_->c_str(); SHAddToRecentDocs(SHARD_APPIDINFO, &jumpItemInfo); } else { SHAddToRecentDocs(SHARD_SHELLITEM, itemHandle); } } void Application::registerRecentlyUsed( const JumpTask& recentJumpTask, COMIsInitializedInThisThreadTag com) noexcept(false) { refreshJumpListHandle(); auto& [appId_, jumpListHandle_] = idAndJumpListHandle_; const auto taskHandle = recentJumpTask.shareNativeHandle(com); if (appId_.has_value()) { SHARDAPPIDINFOLINK jumpTaskInfo{}; jumpTaskInfo.psl = taskHandle; jumpTaskInfo.pszAppID = appId_->c_str(); SHAddToRecentDocs(SHARD_APPIDINFOLINK, &jumpTaskInfo); } else { SHAddToRecentDocs(SHARD_LINK, taskHandle); } } void Application::clearRecentsAndFrequents(COMIsInitializedInThisThreadTag) noexcept(false) { refreshJumpListHandle(); auto& [appId_, jumpListHandle_] = idAndJumpListHandle_; const auto rfHandle = createRecentsAndFrequentsHandle( (appId_.has_value() ? &(*appId_) : nullptr), __func__, applicationCtxName ); auto hr = rfHandle->RemoveAllDestinations(); if ( (hr != S_OK) && // it is ok if no recent docs was registered before (hr != HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)) ) errors::throwCOMException( hr, "IApplicationDestinations::RemoveAllDestinations failed", __func__, applicationCtxName ); // clears all usage data on all Recent items SHAddToRecentDocs(SHARD_PIDL, nullptr); } void Application::setJumpList(const JumpList& jumpList, COMIsInitializedInThisThreadTag com) noexcept(false) { deleteJumpList(com); // implies refreshJumpListHandle auto& [appId_, jumpListHandle_] = idAndJumpListHandle_; if (jumpListHandle_ == nullptr) throw std::logic_error("Application::setJumpList: jumpListHandle_ can not be nullptr"); JumpListTransaction tr{jumpListHandle_}; appendUserTasksTo(*tr, jumpList.getUserTasksCategory(), __func__, applicationCtxName, com); const auto& allCustomCategories = jumpList.getAllCustomCategories(); for (const auto& customCategory : allCustomCategories) appendCustomCategoryTo(*tr, customCategory.first, customCategory.second, __func__, applicationCtxName, com); if (jumpList.isRecentCategoryVisible()) { if (const auto hr = tr->AppendKnownCategory(KDC_RECENT); hr != S_OK) errors::throwCOMException( hr, "ICustomDestinationList::AppendKnownCategory(KDC_RECENT) failed", __func__, applicationCtxName ); } if (jumpList.isFrequentCategoryVisible()) { if (const auto hr = tr->AppendKnownCategory(KDC_FREQUENT); hr != S_OK) errors::throwCOMException( hr, "ICustomDestinationList::AppendKnownCategory(KDC_FREQUENT) failed", __func__, applicationCtxName ); } tr.commit(); } void Application::deleteJumpList(COMIsInitializedInThisThreadTag) noexcept(false) { refreshJumpListHandle(); auto& [appId_, jumpListHandle_] = idAndJumpListHandle_; auto* const appIdCStr = appId_.has_value() ? appId_->c_str() : nullptr; if (const auto hr = jumpListHandle_->DeleteList(appIdCStr); hr != S_OK) errors::throwCOMException( hr, "ICustomDestinationList::DeleteList failed", __func__, applicationCtxName ); } [[nodiscard]] std::optional<Application::UserModelId> Application::obtainAppUserModelId() const noexcept(false) { struct COMStr { PWSTR data = nullptr; ~COMStr() { if (data != nullptr) { CoTaskMemFree(data); } } } comStr; if (const auto hr = GetCurrentProcessExplicitAppUserModelID(&comStr.data); hr != S_OK) { // E_FAIL is returned when appId was not set (via SetCurrentProcessExplicitAppUserModelID) if (hr == E_FAIL) return std::nullopt; errors::throwCOMException( hr, "GetCurrentProcessExplicitAppUserModelID failed", __func__, applicationCtxName ); } assert( (comStr.data != nullptr) ); return comStr.data; } void Application::refreshJumpListHandle() noexcept(false) { auto newAppId = obtainAppUserModelId(); auto& [appId_, jumpListHandle_] = idAndJumpListHandle_; if ( (jumpListHandle_ == nullptr) || (appId_ != newAppId) ) { jumpListHandle_ = createJumpListHandle( (newAppId.has_value() ? &(*newAppId) : nullptr), __func__, applicationCtxName ); appId_ = std::move(newAppId); } } } // namespace intellij::ui::win <commit_msg>[User Interface] Windows Jump lists (native): codestyle fix.<commit_after>// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. #include "winshellintegration/application.h" #include "winshellintegration/winapi.h" // SetCurrentProcessExplicitAppUserModelID, // GetCurrentProcessExplicitAppUserModelID, // COM, // Shell #include "winshellintegration/COM_errors.h" // errors::throwCOMException #include "winshellintegration/jump_item.h" // JumpItem #include "winshellintegration/jump_task.h" // JumpTask #include "winshellintegration/jump_list.h" // JumpList #include <string_view> // std::string_view #include <exception> // std::uncaught_exceptions #include <stdexcept> // std::logic_error #include <cassert> // assert namespace intellij::ui::win { // ================================================================================================================ // JumpListTransaction // ================================================================================================================ namespace { class JumpListTransaction final { public: static constexpr std::string_view jumpListTransactionCtxName = "intellij::ui::win::Application::JumpListTransaction"; UINT maxSlots; CComPtr<IObjectArray> removedObjects; public: // ctors/dtor explicit JumpListTransaction(ICustomDestinationList* jumpListHandle) noexcept(false) : handle_(nullptr) , maxSlots(0) { auto hr = jumpListHandle->BeginList(&maxSlots, IID_PPV_ARGS(&removedObjects)); if (hr != S_OK) errors::throwCOMException( hr, "ICustomDestinationList::BeginList failed", __func__, jumpListTransactionCtxName ); assert( (removedObjects != nullptr) ); handle_ = jumpListHandle; } // non-copyable JumpListTransaction(const JumpListTransaction&) = delete; // non-movable JumpListTransaction(JumpListTransaction&&) = delete; ~JumpListTransaction() noexcept(false) { if (handle_ == nullptr) return; auto *const localHandle = handle_; handle_ = nullptr; const auto hr = localHandle->AbortList(); if (std::uncaught_exceptions() != 0) assert( (hr == S_OK) ); else if (hr != S_OK) errors::throwCOMException( hr, "ICustomDestinationList::AbortList failed", __func__, jumpListTransactionCtxName ); } public: // non-copyable JumpListTransaction& operator=(const JumpListTransaction&) = delete; // non-movable JumpListTransaction& operator=(JumpListTransaction&&) = delete; public: void commit() noexcept(false) { if (handle_ == nullptr) return; if (const auto hr = handle_->CommitList(); hr != S_OK) errors::throwCOMException( hr, "ICustomDestinationList::CommitList failed", __func__, jumpListTransactionCtxName ); handle_ = nullptr; } public: [[nodiscard]] ICustomDestinationList* operator->() const noexcept { assert( (handle_ != nullptr) ); return handle_; } [[nodiscard]] ICustomDestinationList& operator*() const noexcept { assert( (handle_ != nullptr) ); return *handle_; } private: ICustomDestinationList* handle_; }; } // namespace // ================================================================================================================ // Some helpers // ================================================================================================================ namespace { CComPtr<IObjectCollection> createCategoryNativeContainer( const std::string_view callerFuncName, const std::string_view callerCtxName) noexcept(false) { CComPtr<IObjectCollection> result; auto hr = result.CoCreateInstance( CLSID_EnumerableObjectCollection, nullptr, CLSCTX_INPROC ); if (hr != S_OK) errors::throwCOMException( hr, "CoCreateInstance(CLSID_EnumerableObjectCollection) failed", callerFuncName, callerCtxName ); assert( (result != nullptr) ); return result; } void insertToCategoryNativeContainer( IObjectCollection& nativeContainer, const JumpList::value_type& item, const std::string_view callerFuncName, const std::string_view callerCtxName, COMIsInitializedInThisThreadTag com) noexcept(false) { std::visit( [&nativeContainer, callerFuncName, callerCtxName, com](const auto& unwrappedItem) { auto hr = nativeContainer.AddObject(unwrappedItem.shareNativeHandle(com)); if (hr != S_OK) errors::throwCOMException( hr, "IObjectCollection::AddObject failed", callerFuncName, callerCtxName ); }, item ); } [[nodiscard]] CComPtr<ICustomDestinationList> createJumpListHandle( const Application::UserModelId* appId, const std::string_view callerFuncName, const std::string_view callerCtxName) noexcept(false) { CComPtr<ICustomDestinationList> result = nullptr; auto hr = result.CoCreateInstance( CLSID_DestinationList, nullptr, CLSCTX_INPROC ); if (hr != S_OK) errors::throwCOMException( hr, "CoCreateInstance(CLSID_DestinationList) failed", callerFuncName, callerCtxName ); assert( (result != nullptr) ); if (appId != nullptr) { if (hr = result->SetAppID(appId->c_str()); hr != S_OK) errors::throwCOMException( hr, "ICustomDestinationList::SetAppID failed", callerFuncName, callerCtxName ); } return result; } [[nodiscard]] CComPtr<IApplicationDestinations> createRecentsAndFrequentsHandle( const Application::UserModelId* appId, const std::string_view callerFuncName, const std::string_view callerCtxName) noexcept(false) { CComPtr<IApplicationDestinations> result = nullptr; auto hr = result.CoCreateInstance( CLSID_ApplicationDestinations, nullptr, CLSCTX_INPROC ); if (hr != S_OK) errors::throwCOMException( hr, "CoCreateInstance(CLSID_ApplicationDestinations) failed", callerFuncName, callerCtxName ); assert( (result != nullptr) ); if (appId != nullptr) { if (hr = result->SetAppID(appId->c_str()); hr != S_OK) errors::throwCOMException( hr, "IApplicationDestinations::SetAppID failed", callerFuncName, callerCtxName ); } return result; } void appendCustomCategoryTo( ICustomDestinationList& jumpListHandle, const WideString& categoryName, const JumpList::CustomCategoryContainer& items, const std::string_view callerFuncName, const std::string_view callerCtxName, COMIsInitializedInThisThreadTag com) noexcept(false) { if (items.empty()) return; const auto nativeContainer = createCategoryNativeContainer(callerFuncName, callerCtxName); for (const auto& item: items) insertToCategoryNativeContainer(*nativeContainer, item, callerFuncName, callerCtxName, com); if (const auto hr = jumpListHandle.AppendCategory(categoryName.c_str(), nativeContainer); hr != S_OK) errors::throwCOMException( hr, "ICustomDestinationList::AppendCategory failed", callerFuncName, callerCtxName ); } void appendUserTasksTo( ICustomDestinationList& jumpListHandle, const JumpList::UserTasksCategoryContainer& items, const std::string_view callerFuncName, const std::string_view callerCtxName, COMIsInitializedInThisThreadTag com) noexcept(false) { if (items.empty()) return; const auto nativeContainer = createCategoryNativeContainer(callerFuncName, callerCtxName); for (const auto& item: items) insertToCategoryNativeContainer(*nativeContainer, item, callerFuncName, callerCtxName, com); if (const auto hr = jumpListHandle.AddUserTasks(nativeContainer); hr != S_OK) errors::throwCOMException( hr, "ICustomDestinationList::AddUserTasks failed", callerFuncName, callerCtxName ); } } // namespace // ================================================================================================================ // Application // ================================================================================================================ static constexpr std::string_view applicationCtxName = "intellij::ui::win::Application"; Application::Application() noexcept = default; Application::~Application() noexcept = default; Application& Application::getInstance() noexcept { static Application instance; return instance; } void Application::setAppUserModelId(const UserModelId& appId) noexcept(false) { if (const auto hr = SetCurrentProcessExplicitAppUserModelID(appId.c_str()); hr != S_OK) errors::throwCOMException( hr, "SetCurrentProcessExplicitAppUserModelID failed", __func__, applicationCtxName ); } void Application::registerRecentlyUsed(const std::filesystem::path& path) noexcept(false) { SHAddToRecentDocs(SHARD_PATHW, path.c_str()); } void Application::registerRecentlyUsed( const JumpItem& recentJumpItem, COMIsInitializedInThisThreadTag com) noexcept(false) { refreshJumpListHandle(); auto& [appId_, jumpListHandle_] = idAndJumpListHandle_; const auto itemHandle = recentJumpItem.shareNativeHandle(com); if (appId_.has_value()) { SHARDAPPIDINFO jumpItemInfo{}; jumpItemInfo.psi = itemHandle; jumpItemInfo.pszAppID = appId_->c_str(); SHAddToRecentDocs(SHARD_APPIDINFO, &jumpItemInfo); } else { SHAddToRecentDocs(SHARD_SHELLITEM, itemHandle); } } void Application::registerRecentlyUsed( const JumpTask& recentJumpTask, COMIsInitializedInThisThreadTag com) noexcept(false) { refreshJumpListHandle(); auto& [appId_, jumpListHandle_] = idAndJumpListHandle_; const auto taskHandle = recentJumpTask.shareNativeHandle(com); if (appId_.has_value()) { SHARDAPPIDINFOLINK jumpTaskInfo{}; jumpTaskInfo.psl = taskHandle; jumpTaskInfo.pszAppID = appId_->c_str(); SHAddToRecentDocs(SHARD_APPIDINFOLINK, &jumpTaskInfo); } else { SHAddToRecentDocs(SHARD_LINK, taskHandle); } } void Application::clearRecentsAndFrequents(COMIsInitializedInThisThreadTag) noexcept(false) { refreshJumpListHandle(); auto& [appId_, jumpListHandle_] = idAndJumpListHandle_; const auto rfHandle = createRecentsAndFrequentsHandle( (appId_.has_value() ? &(*appId_) : nullptr), __func__, applicationCtxName ); auto hr = rfHandle->RemoveAllDestinations(); if ( (hr != S_OK) && // it is ok if no recent docs was registered before (hr != HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)) ) errors::throwCOMException( hr, "IApplicationDestinations::RemoveAllDestinations failed", __func__, applicationCtxName ); // clears all usage data on all Recent items SHAddToRecentDocs(SHARD_PIDL, nullptr); } void Application::setJumpList(const JumpList& jumpList, COMIsInitializedInThisThreadTag com) noexcept(false) { deleteJumpList(com); // implies refreshJumpListHandle auto& [appId_, jumpListHandle_] = idAndJumpListHandle_; if (jumpListHandle_ == nullptr) throw std::logic_error("Application::setJumpList: jumpListHandle_ can not be nullptr"); JumpListTransaction tr{jumpListHandle_}; appendUserTasksTo(*tr, jumpList.getUserTasksCategory(), __func__, applicationCtxName, com); const auto& allCustomCategories = jumpList.getAllCustomCategories(); for (const auto& customCategory : allCustomCategories) appendCustomCategoryTo(*tr, customCategory.first, customCategory.second, __func__, applicationCtxName, com); if (jumpList.isRecentCategoryVisible()) { if (const auto hr = tr->AppendKnownCategory(KDC_RECENT); hr != S_OK) errors::throwCOMException( hr, "ICustomDestinationList::AppendKnownCategory(KDC_RECENT) failed", __func__, applicationCtxName ); } if (jumpList.isFrequentCategoryVisible()) { if (const auto hr = tr->AppendKnownCategory(KDC_FREQUENT); hr != S_OK) errors::throwCOMException( hr, "ICustomDestinationList::AppendKnownCategory(KDC_FREQUENT) failed", __func__, applicationCtxName ); } tr.commit(); } void Application::deleteJumpList(COMIsInitializedInThisThreadTag) noexcept(false) { refreshJumpListHandle(); auto& [appId_, jumpListHandle_] = idAndJumpListHandle_; auto* const appIdCStr = appId_.has_value() ? appId_->c_str() : nullptr; if (const auto hr = jumpListHandle_->DeleteList(appIdCStr); hr != S_OK) errors::throwCOMException( hr, "ICustomDestinationList::DeleteList failed", __func__, applicationCtxName ); } [[nodiscard]] std::optional<Application::UserModelId> Application::obtainAppUserModelId() const noexcept(false) { struct COMStr { PWSTR data = nullptr; ~COMStr() { if (data != nullptr) { CoTaskMemFree(data); } } } comStr; if (const auto hr = GetCurrentProcessExplicitAppUserModelID(&comStr.data); hr != S_OK) { // E_FAIL is returned when appId was not set (via SetCurrentProcessExplicitAppUserModelID) if (hr == E_FAIL) return std::nullopt; errors::throwCOMException( hr, "GetCurrentProcessExplicitAppUserModelID failed", __func__, applicationCtxName ); } assert( (comStr.data != nullptr) ); return comStr.data; } void Application::refreshJumpListHandle() noexcept(false) { auto newAppId = obtainAppUserModelId(); auto& [appId_, jumpListHandle_] = idAndJumpListHandle_; if ( (jumpListHandle_ == nullptr) || (appId_ != newAppId) ) { jumpListHandle_ = createJumpListHandle( (newAppId.has_value() ? &(*newAppId) : nullptr), __func__, applicationCtxName ); appId_ = std::move(newAppId); } } } // namespace intellij::ui::win <|endoftext|>
<commit_before>#include <iostream> #include <unistd.h> #include <sstream> #include "StreamMan.h" #include "zmq.h" using namespace std; StreamMan::StreamMan() :DataMan() { } StreamMan::~StreamMan(){ if(zmq_meta) zmq_close(zmq_meta); if(zmq_context) zmq_ctx_destroy(zmq_context); zmq_meta_rep_thread_active = false; if(zmq_meta_rep_thread){ if(zmq_meta_rep_thread->joinable()) zmq_meta_rep_thread->join(); delete zmq_meta_rep_thread; } } int StreamMan::init(json p_jmsg){ if(check_json(p_jmsg, {"stream_mode", "remote_ip", "local_ip", "remote_port", "local_port" }, "StreamMan")){ m_stream_mode = p_jmsg["stream_mode"]; m_local_ip = p_jmsg["local_ip"]; m_remote_ip = p_jmsg["remote_ip"]; m_local_port = p_jmsg["local_port"]; m_remote_port = p_jmsg["remote_port"]; string remote_address = make_address(m_remote_ip, m_remote_port, "tcp"); string local_address = make_address(m_local_ip, m_local_port, "tcp"); if(p_jmsg["num_channels"] != nullptr) m_num_channels = p_jmsg["num_channels"]; if(p_jmsg["tolerance"] != nullptr) m_tolerance = p_jmsg["tolerance"].get<vector<int>>(); if(p_jmsg["priority"] != nullptr) m_priority = p_jmsg["priority"].get<vector<int>>(); if(!zmq_context){ zmq_context = zmq_ctx_new (); zmq_meta = zmq_socket (zmq_context, ZMQ_PAIR); if(m_stream_mode == "sender"){ zmq_connect (zmq_meta, remote_address.c_str()); cout << "StreamMan::init " << remote_address << " connected" << endl; } else if(m_stream_mode == "receiver"){ zmq_bind (zmq_meta, local_address.c_str()); cout << "StreamMan::init " << local_address << " bound" << endl; } zmq_meta_rep_thread_active = true; zmq_meta_rep_thread = new thread(&StreamMan::zmq_meta_rep_thread_func, this); } return 0; } else{ return -1; } } void StreamMan::callback(){ if(get_callback){ vector<string> do_list = m_cache.get_do_list(); for(string i : do_list){ vector<string> var_list = m_cache.get_var_list(i); for(string j : var_list){ get_callback(m_cache.get_buffer(i,j), i, j, m_cache.get_dtype(i, j), m_cache.get_shape(i, j) ); } } } else{ logging("callback called but callback function not registered"); } } void StreamMan::flush(){ json msg; msg["operation"] = "flush"; zmq_send(zmq_meta, msg.dump().c_str(), msg.dump().length(), 0); } void StreamMan::zmq_meta_rep_thread_func(){ while (zmq_meta_rep_thread_active){ char msg[1024]=""; int err = zmq_recv (zmq_meta, msg, 1024, ZMQ_NOBLOCK); if (err>=0){ cout << "StreamMan::zmq_meta_rep_thread_func: " << msg << endl; json j = json::parse(msg); if(m_get_mode == "callback"){ on_recv(j); } } usleep(10); } } int StreamMan::put(const void *p_data, json p_jmsg){ p_jmsg["operation"] = "put"; zmq_send(zmq_meta, p_jmsg.dump().c_str(), p_jmsg.dump().length(), 0); return 0; } <commit_msg>added default numbers for tolerance and priority in StreamMan<commit_after>#include <iostream> #include <unistd.h> #include <sstream> #include "StreamMan.h" #include "zmq.h" using namespace std; StreamMan::StreamMan() :DataMan() { } StreamMan::~StreamMan(){ if(zmq_meta) zmq_close(zmq_meta); if(zmq_context) zmq_ctx_destroy(zmq_context); zmq_meta_rep_thread_active = false; if(zmq_meta_rep_thread){ if(zmq_meta_rep_thread->joinable()) zmq_meta_rep_thread->join(); delete zmq_meta_rep_thread; } } int StreamMan::init(json p_jmsg){ if(check_json(p_jmsg, {"stream_mode", "remote_ip", "local_ip", "remote_port", "local_port" }, "StreamMan")){ m_stream_mode = p_jmsg["stream_mode"]; m_local_ip = p_jmsg["local_ip"]; m_remote_ip = p_jmsg["remote_ip"]; m_local_port = p_jmsg["local_port"]; m_remote_port = p_jmsg["remote_port"]; string remote_address = make_address(m_remote_ip, m_remote_port, "tcp"); string local_address = make_address(m_local_ip, m_local_port, "tcp"); if(p_jmsg["num_channels"] != nullptr) m_num_channels = p_jmsg["num_channels"]; if(p_jmsg["tolerance"] != nullptr) m_tolerance = p_jmsg["tolerance"].get<vector<int>>(); else m_tolerance.assign(m_num_channels, 0); if(p_jmsg["priority"] != nullptr) m_priority = p_jmsg["priority"].get<vector<int>>(); else m_priority.assign(m_num_channels, 100); if(!zmq_context){ zmq_context = zmq_ctx_new (); zmq_meta = zmq_socket (zmq_context, ZMQ_PAIR); if(m_stream_mode == "sender"){ zmq_connect (zmq_meta, remote_address.c_str()); cout << "StreamMan::init " << remote_address << " connected" << endl; } else if(m_stream_mode == "receiver"){ zmq_bind (zmq_meta, local_address.c_str()); cout << "StreamMan::init " << local_address << " bound" << endl; } zmq_meta_rep_thread_active = true; zmq_meta_rep_thread = new thread(&StreamMan::zmq_meta_rep_thread_func, this); } return 0; } else{ return -1; } } void StreamMan::callback(){ if(get_callback){ vector<string> do_list = m_cache.get_do_list(); for(string i : do_list){ vector<string> var_list = m_cache.get_var_list(i); for(string j : var_list){ get_callback(m_cache.get_buffer(i,j), i, j, m_cache.get_dtype(i, j), m_cache.get_shape(i, j) ); } } } else{ logging("callback called but callback function not registered"); } } void StreamMan::flush(){ json msg; msg["operation"] = "flush"; zmq_send(zmq_meta, msg.dump().c_str(), msg.dump().length(), 0); } void StreamMan::zmq_meta_rep_thread_func(){ while (zmq_meta_rep_thread_active){ char msg[1024]=""; int err = zmq_recv (zmq_meta, msg, 1024, ZMQ_NOBLOCK); if (err>=0){ cout << "StreamMan::zmq_meta_rep_thread_func: " << msg << endl; json j = json::parse(msg); if(m_get_mode == "callback"){ on_recv(j); } } usleep(10); } } int StreamMan::put(const void *p_data, json p_jmsg){ p_jmsg["operation"] = "put"; zmq_send(zmq_meta, p_jmsg.dump().c_str(), p_jmsg.dump().length(), 0); return 0; } <|endoftext|>
<commit_before>#include "schedule.h" #include "ui_schedule.h" schedule::schedule(QWidget *parent, int day) : QDialog(parent), ui(new Ui::schedule) { ui->setupUi(this); _day = day; switch(day) { case 1: ui->day_name->setText("Понедельник"); break; case 2: ui->day_name->setText("Вторник"); break; case 3: ui->day_name->setText("Среда"); break; case 4: ui->day_name->setText("Четверг"); break; case 5: ui->day_name->setText("Пятница"); break; case 6: ui->day_name->setText("Суббота"); break; } select_sch(day); } schedule::~schedule() { delete ui; } void schedule::select_sch(int day) { QString name[10]; QSqlQuery a_query; // переменная для запроса QString str_select = "SELECT * FROM schedule WHERE day = %1"; QString str = str_select.arg(day); if (!a_query.exec(str)) { qDebug() << "Ошибка выполнения запроса SELECT"; } QSqlRecord res = a_query.record(); //результат запроса int i =0; while (a_query.next()) { name[i] = a_query.value(res.indexOf("name")).toString(); i++; } for (int i = 1; i <= 10; i++) //циклом присваиваем всем QLineEdit значения из базы { QLineEdit *edit = findChild<QLineEdit *>("Edit_" + QString::number(i)); if (edit == nullptr) continue; //если объект не найден edit->setText(name[i-1]); } } void schedule::update_sch(int day, int number, QString name) { QSqlQuery a_query; // переменная для запроса int id = (day-1) * 10 + number; //вычисляем id записи qDebug() << id; QString str_update = "UPDATE schedule SET name = '%1' WHERE rowid = %2"; QString str = str_update.arg(name) .arg(id); if (!a_query.exec(str)) { qDebug() << "Ошибка выполнения запроса UPDATE"; } } void schedule::accept() { for (int i = 1; i <= 10; i++) //циклом заносим значения из всех QLineEdit в базу { qDebug() << _day << i; QLineEdit *edit = findChild<QLineEdit *>("Edit_" + QString::number(i)); if (edit == nullptr) continue; //если объект не найден QString name = edit->text(); name = name.simplified(); //убираем пробелы update_sch(_day,i,name); } } <commit_msg>убран qdebug()<commit_after>#include "schedule.h" #include "ui_schedule.h" schedule::schedule(QWidget *parent, int day) : QDialog(parent), ui(new Ui::schedule) { ui->setupUi(this); _day = day; switch(day) { case 1: ui->day_name->setText("Понедельник"); break; case 2: ui->day_name->setText("Вторник"); break; case 3: ui->day_name->setText("Среда"); break; case 4: ui->day_name->setText("Четверг"); break; case 5: ui->day_name->setText("Пятница"); break; case 6: ui->day_name->setText("Суббота"); break; } select_sch(day); } schedule::~schedule() { delete ui; } void schedule::select_sch(int day) { QString name[10]; QSqlQuery a_query; // переменная для запроса QString str_select = "SELECT * FROM schedule WHERE day = %1"; QString str = str_select.arg(day); if (!a_query.exec(str)) { qDebug() << "Ошибка выполнения запроса SELECT"; } QSqlRecord res = a_query.record(); //результат запроса int i =0; while (a_query.next()) { name[i] = a_query.value(res.indexOf("name")).toString(); i++; } for (int i = 1; i <= 10; i++) //циклом присваиваем всем QLineEdit значения из базы { QLineEdit *edit = findChild<QLineEdit *>("Edit_" + QString::number(i)); if (edit == nullptr) continue; //если объект не найден edit->setText(name[i-1]); } } void schedule::update_sch(int day, int number, QString name) { QSqlQuery a_query; // переменная для запроса int id = (day-1) * 10 + number; //вычисляем id записи QString str_update = "UPDATE schedule SET name = '%1' WHERE rowid = %2"; QString str = str_update.arg(name) .arg(id); if (!a_query.exec(str)) { qDebug() << "Ошибка выполнения запроса UPDATE"; } } void schedule::accept() { for (int i = 1; i <= 10; i++) //циклом заносим значения из всех QLineEdit в базу { QLineEdit *edit = findChild<QLineEdit *>("Edit_" + QString::number(i)); if (edit == nullptr) continue; //если объект не найден QString name = edit->text(); name = name.simplified(); //убираем пробелы update_sch(_day,i,name); } } <|endoftext|>
<commit_before>template <int i, typename dummy, typename...> struct __data { }; struct dummy { }; <commit_msg>Add the built-in types into C++ runtime.<commit_after>template <int i, typename dummy, typename...> struct __data { }; struct dummy { }; template <int i> struct Int { static const int value = i; }; template <bool b> { static const bool value = b; }; <|endoftext|>
<commit_before>/** * @file Database.cpp * @ingroup SQLiteCpp * @brief Management of a SQLite Database Connection. * * Copyright (c) 2012-2013 Sebastien Rombauts ([email protected]) * * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * or copy at http://opensource.org/licenses/MIT) */ #include <SQLiteCpp/Database.h> #include <SQLiteCpp/Statement.h> #include <SQLiteCpp/Assertion.h> #include <SQLiteCpp/Exception.h> #include <string> #ifndef SQLITE_DETERMINISTIC #define SQLITE_DETERMINISTIC 0x800 #endif // SQLITE_DETERMINISTIC namespace SQLite { // Open the provided database UTF-8 filename with SQLITE_OPEN_xxx provided flags. Database::Database(const char* apFilename, const int aFlags /* = SQLITE_OPEN_READONLY*/, const int aBusyTimeoutMs /* = 0 */, const char* apVfs /* = NULL*/) : mpSQLite(NULL), mFilename(apFilename) { const int ret = sqlite3_open_v2(apFilename, &mpSQLite, aFlags, apVfs); if (SQLITE_OK != ret) { std::string strerr = sqlite3_errmsg(mpSQLite); sqlite3_close(mpSQLite); // close is required even in case of error on opening throw SQLite::Exception(strerr); } if (aBusyTimeoutMs > 0) { setBusyTimeout(aBusyTimeoutMs); } } // Open the provided database UTF-8 filename with SQLITE_OPEN_xxx provided flags. Database::Database(const std::string& aFilename, const int aFlags /* = SQLITE_OPEN_READONLY*/, const int aBusyTimeoutMs /* = 0 */, const std::string& aVfs /* = "" */) : mpSQLite(NULL), mFilename(aFilename) { const int ret = sqlite3_open_v2(aFilename.c_str(), &mpSQLite, aFlags, aVfs.empty() ? NULL : aVfs.c_str()); if (SQLITE_OK != ret) { std::string strerr = sqlite3_errmsg(mpSQLite); sqlite3_close(mpSQLite); // close is required even in case of error on opening throw SQLite::Exception(strerr); } if (aBusyTimeoutMs > 0) { setBusyTimeout(aBusyTimeoutMs); } } // Close the SQLite database connection. Database::~Database() noexcept // nothrow { const int ret = sqlite3_close(mpSQLite); // Never throw an exception in a destructor SQLITECPP_ASSERT(SQLITE_OK == ret, sqlite3_errstr(ret)); // See SQLITECPP_ENABLE_ASSERT_HANDLER } /** * @brief Set a busy handler that sleeps for a specified amount of time when a table is locked. * * This is usefull in multithreaded program to handle case where a table is locked for writting by a thread. * Any other thread cannot access the table and will receive a SQLITE_BUSY error: * setting a timeout will wait and retry up to the time specified before returning this SQLITE_BUSY error. * Reading the value of timeout for current connection can be done with SQL query "PRAGMA busy_timeout;". * Default busy timeout is 0ms. * * @param[in] aBusyTimeoutMs Amount of milliseconds to wait before returning SQLITE_BUSY * * @throw SQLite::Exception in case of error */ void Database::setBusyTimeout(const int aBusyTimeoutMs) noexcept // nothrow { const int ret = sqlite3_busy_timeout(mpSQLite, aBusyTimeoutMs); check(ret); } // Shortcut to execute one or multiple SQL statements without results (UPDATE, INSERT, ALTER, COMMIT, CREATE...). int Database::exec(const char* apQueries) { const int ret = sqlite3_exec(mpSQLite, apQueries, NULL, NULL, NULL); check(ret); // Return the number of rows modified by those SQL statements (INSERT, UPDATE or DELETE only) return sqlite3_changes(mpSQLite); } // Shortcut to execute a one step query and fetch the first column of the result. // WARNING: Be very careful with this dangerous method: you have to // make a COPY OF THE result, else it will be destroy before the next line // (when the underlying temporary Statement and Column objects are destroyed) // this is an issue only for pointer type result (ie. char* and blob) // (use the Column copy-constructor) Column Database::execAndGet(const char* apQuery) { Statement query(*this, apQuery); (void)query.executeStep(); // Can return false if no result, which will throw next line in getColumn() return query.getColumn(0); } // Shortcut to test if a table exists. bool Database::tableExists(const char* apTableName) { Statement query(*this, "SELECT count(*) FROM sqlite_master WHERE type='table' AND name=?"); query.bind(1, apTableName); (void)query.executeStep(); // Cannot return false, as the above query always return a result const int Nb = query.getColumn(0); return (1 == Nb); } // Attach a custom function to your sqlite database. Assumes UTF8 text representation. // Parameter details can be found here: http://www.sqlite.org/c3ref/create_function.html void Database::createFunction(const char* apFuncName, int aNbArg, bool abDeterministic, void* apApp, void (*apFunc)(sqlite3_context *, int, sqlite3_value **), void (*apStep)(sqlite3_context *, int, sqlite3_value **), void (*apFinal)(sqlite3_context *), // NOLINT(readability/casting) void (*apDestroy)(void *)) { int TextRep = SQLITE_UTF8; // optimization if deterministic function (e.g. of nondeterministic function random()) if (abDeterministic) { TextRep = TextRep|SQLITE_DETERMINISTIC; } const int ret = sqlite3_create_function_v2(mpSQLite, apFuncName, aNbArg, TextRep, apApp, apFunc, apStep, apFinal, apDestroy); check(ret); } } // namespace SQLite <commit_msg>Revert use sqlite_errstr instead of sqlite3_errmsg that fixed #48<commit_after>/** * @file Database.cpp * @ingroup SQLiteCpp * @brief Management of a SQLite Database Connection. * * Copyright (c) 2012-2013 Sebastien Rombauts ([email protected]) * * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * or copy at http://opensource.org/licenses/MIT) */ #include <SQLiteCpp/Database.h> #include <SQLiteCpp/Statement.h> #include <SQLiteCpp/Assertion.h> #include <SQLiteCpp/Exception.h> #include <string> #ifndef SQLITE_DETERMINISTIC #define SQLITE_DETERMINISTIC 0x800 #endif // SQLITE_DETERMINISTIC namespace SQLite { // Open the provided database UTF-8 filename with SQLITE_OPEN_xxx provided flags. Database::Database(const char* apFilename, const int aFlags /* = SQLITE_OPEN_READONLY*/, const int aBusyTimeoutMs /* = 0 */, const char* apVfs /* = NULL*/) : mpSQLite(NULL), mFilename(apFilename) { const int ret = sqlite3_open_v2(apFilename, &mpSQLite, aFlags, apVfs); if (SQLITE_OK != ret) { std::string strerr = sqlite3_errmsg(mpSQLite); sqlite3_close(mpSQLite); // close is required even in case of error on opening throw SQLite::Exception(strerr); } if (aBusyTimeoutMs > 0) { setBusyTimeout(aBusyTimeoutMs); } } // Open the provided database UTF-8 filename with SQLITE_OPEN_xxx provided flags. Database::Database(const std::string& aFilename, const int aFlags /* = SQLITE_OPEN_READONLY*/, const int aBusyTimeoutMs /* = 0 */, const std::string& aVfs /* = "" */) : mpSQLite(NULL), mFilename(aFilename) { const int ret = sqlite3_open_v2(aFilename.c_str(), &mpSQLite, aFlags, aVfs.empty() ? NULL : aVfs.c_str()); if (SQLITE_OK != ret) { std::string strerr = sqlite3_errmsg(mpSQLite); sqlite3_close(mpSQLite); // close is required even in case of error on opening throw SQLite::Exception(strerr); } if (aBusyTimeoutMs > 0) { setBusyTimeout(aBusyTimeoutMs); } } // Close the SQLite database connection. Database::~Database() noexcept // nothrow { const int ret = sqlite3_close(mpSQLite); // Only case of error is SQLITE_BUSY: "database is locked" (some statements are not finalized) // Never throw an exception in a destructor : SQLITECPP_ASSERT(SQLITE_OK == ret, "database is locked"); // See SQLITECPP_ENABLE_ASSERT_HANDLER } /** * @brief Set a busy handler that sleeps for a specified amount of time when a table is locked. * * This is usefull in multithreaded program to handle case where a table is locked for writting by a thread. * Any other thread cannot access the table and will receive a SQLITE_BUSY error: * setting a timeout will wait and retry up to the time specified before returning this SQLITE_BUSY error. * Reading the value of timeout for current connection can be done with SQL query "PRAGMA busy_timeout;". * Default busy timeout is 0ms. * * @param[in] aBusyTimeoutMs Amount of milliseconds to wait before returning SQLITE_BUSY * * @throw SQLite::Exception in case of error */ void Database::setBusyTimeout(const int aBusyTimeoutMs) noexcept // nothrow { const int ret = sqlite3_busy_timeout(mpSQLite, aBusyTimeoutMs); check(ret); } // Shortcut to execute one or multiple SQL statements without results (UPDATE, INSERT, ALTER, COMMIT, CREATE...). int Database::exec(const char* apQueries) { const int ret = sqlite3_exec(mpSQLite, apQueries, NULL, NULL, NULL); check(ret); // Return the number of rows modified by those SQL statements (INSERT, UPDATE or DELETE only) return sqlite3_changes(mpSQLite); } // Shortcut to execute a one step query and fetch the first column of the result. // WARNING: Be very careful with this dangerous method: you have to // make a COPY OF THE result, else it will be destroy before the next line // (when the underlying temporary Statement and Column objects are destroyed) // this is an issue only for pointer type result (ie. char* and blob) // (use the Column copy-constructor) Column Database::execAndGet(const char* apQuery) { Statement query(*this, apQuery); (void)query.executeStep(); // Can return false if no result, which will throw next line in getColumn() return query.getColumn(0); } // Shortcut to test if a table exists. bool Database::tableExists(const char* apTableName) { Statement query(*this, "SELECT count(*) FROM sqlite_master WHERE type='table' AND name=?"); query.bind(1, apTableName); (void)query.executeStep(); // Cannot return false, as the above query always return a result const int Nb = query.getColumn(0); return (1 == Nb); } // Attach a custom function to your sqlite database. Assumes UTF8 text representation. // Parameter details can be found here: http://www.sqlite.org/c3ref/create_function.html void Database::createFunction(const char* apFuncName, int aNbArg, bool abDeterministic, void* apApp, void (*apFunc)(sqlite3_context *, int, sqlite3_value **), void (*apStep)(sqlite3_context *, int, sqlite3_value **), void (*apFinal)(sqlite3_context *), // NOLINT(readability/casting) void (*apDestroy)(void *)) { int TextRep = SQLITE_UTF8; // optimization if deterministic function (e.g. of nondeterministic function random()) if (abDeterministic) { TextRep = TextRep|SQLITE_DETERMINISTIC; } const int ret = sqlite3_create_function_v2(mpSQLite, apFuncName, aNbArg, TextRep, apApp, apFunc, apStep, apFinal, apDestroy); check(ret); } } // namespace SQLite <|endoftext|>
<commit_before>#include "tests/ffi/lib.rs" #include "tests/ffi/tests.h" namespace tests { C::C(size_t n) : n(n) {} size_t c_return_primitive() { return 2020; } Shared c_return_shared() { return Shared{2020}; } std::unique_ptr<C> c_return_unique_ptr() { return std::unique_ptr<C>(new C{2020}); } const size_t &c_return_ref(const Shared &shared) { return shared.z; } cxxbridge::RustStr c_return_str(const Shared &shared) { (void)shared; return "2020"; } cxxbridge::RustString c_return_rust_string() { return "2020"; } std::unique_ptr<std::string> c_return_unique_ptr_string() { return std::unique_ptr<std::string>(new std::string("2020")); } void c_take_primitive(size_t n) { (void)n; } void c_take_shared(Shared shared) { (void)shared; } void c_take_box(cxxbridge::RustBox<R> r) { (void)r; } void c_take_unique_ptr(std::unique_ptr<C> c) { (void)c; } void c_take_ref_r(const R &r) { (void)r; } void c_take_ref_c(const C &c) { (void)c; } void c_take_str(cxxbridge::RustStr s) { (void)s; } void c_take_rust_string(cxxbridge::RustString s) { (void)s; } void c_take_unique_ptr_string(std::unique_ptr<std::string> s) { (void)s; } } // namespace tests <commit_msg>Format with clang-format<commit_after>#include "tests/ffi/tests.h" #include "tests/ffi/lib.rs" namespace tests { C::C(size_t n) : n(n) {} size_t c_return_primitive() { return 2020; } Shared c_return_shared() { return Shared{2020}; } std::unique_ptr<C> c_return_unique_ptr() { return std::unique_ptr<C>(new C{2020}); } const size_t &c_return_ref(const Shared &shared) { return shared.z; } cxxbridge::RustStr c_return_str(const Shared &shared) { (void)shared; return "2020"; } cxxbridge::RustString c_return_rust_string() { return "2020"; } std::unique_ptr<std::string> c_return_unique_ptr_string() { return std::unique_ptr<std::string>(new std::string("2020")); } void c_take_primitive(size_t n) { (void)n; } void c_take_shared(Shared shared) { (void)shared; } void c_take_box(cxxbridge::RustBox<R> r) { (void)r; } void c_take_unique_ptr(std::unique_ptr<C> c) { (void)c; } void c_take_ref_r(const R &r) { (void)r; } void c_take_ref_c(const C &c) { (void)c; } void c_take_str(cxxbridge::RustStr s) { (void)s; } void c_take_rust_string(cxxbridge::RustString s) { (void)s; } void c_take_unique_ptr_string(std::unique_ptr<std::string> s) { (void)s; } } // namespace tests <|endoftext|>
<commit_before>#ifndef __ENVIRE_MAPS_LOCAL_MAP_HPP__ #define __ENVIRE_MAPS_LOCAL_MAP_HPP__ #include <base/Eigen.hpp> #include <boost/shared_ptr.hpp> #include <string> namespace envire { namespace maps { /**@brief LocalMapType * The type of the LocalMap */ enum LocalMapType { UNKNOWN_MAP = -1, GRID_MAP = 1, GEOMETRIC_MAP = 2, TOPOLOGICAL_MAP = 3, MLS_MAP = 4 }; const std::string UNKNOWN_MAP_ID = ""; const std::string DEFAULT_GRID_MAP_ID = "DEFAULT_GRID_MAP"; const std::string UNKNOWN_EPSG_CODE = "NONE"; struct LocalMapData { /** Grid map is the map by default **/ LocalMapData() :id(UNKNOWN_MAP_ID), offset(base::Transform3d::Identity()), map_type(UNKNOWN_MAP), EPSG_code(UNKNOWN_EPSG_CODE){}; LocalMapData(const std::string &id, const base::Transform3d &offset, const LocalMapType map_type, const std::string &EPSG_code) :id(id), offset(offset), map_type(map_type), EPSG_code(EPSG_code) {}; /** string id of this local map **/ std::string id; /** * The map use the Cartesian coordinate system: * the initial origin of the map is placed in the bottom left corner * the x-axis points to the right from the the origin * the y-axis points upwards from the origin * * The offset along the x/y-axis is expressed in the map unit according * to the unit of the map resolution * * The offset represents the replacement of the local frame * with respect to the inital origin. * * For the time being we use 3D transformation. * * The offset can also be reference as local Frame **/ base::Transform3d offset; /** map_type of this local map **/ LocalMapType map_type; /** EPSG_code that provides the geo-localized coordinate system **/ std::string EPSG_code; /** The EPSG code depends in the coordinate system used for the * local map "NONE" in case of not geo-referenced map. * Example: "EPSG::4978" for the World Geodetic System 1984 (WGS-84) * Example: "EPSG::3199" Spain - Canary Islands onshore and offshore. * with bounds are [-21.93W, -11.75E] and [24.6S, 11.75N] using the * World Geodetic System 1984 (WGS-84) coordinate reference system * (CRS). * Example: "EPSG::5243" ETRS89 / LCC Germany (E-N) Bremen area with * WGS084 CRS * Reference: https://www.epsg-registry.org **/ }; /**@brief LocalMap * Local map with respect to a given reference frame * A local map is the basic element to form a global * map (set of local maps structured in a tree). */ class LocalMap { public: typedef boost::shared_ptr<LocalMap> Ptr; LocalMap() : data_ptr(new LocalMapData()) { } /** * @brief [brief description] * @details to share same content (LocalMapData) between various instance of LocalMap * * @param data [description] */ LocalMap(const boost::shared_ptr<LocalMapData> &data) : data_ptr(data) { } /** * @brief make copy without sharing the content * @details the copy instance owns a new content (LocalMapData) * * @param other [description] */ LocalMap(const LocalMap& other) : data_ptr(new LocalMapData(*(other.data_ptr.get()))) { } virtual ~LocalMap() {}; const std::string& getId() const { return data_ptr->id; } std::string& getId() { return data_ptr->id; } const base::Transform3d& getLocalFrame() const { return data_ptr->offset; } base::Transform3d& getLocalFrame() { return data_ptr->offset; } const LocalMapType& getMapType() const { return data_ptr->map_type; } LocalMapType& getMapType() { return data_ptr->map_type; } const std::string& getEPSGCode() const { return data_ptr->EPSG_code; } std::string& getEPSGCode() { return data_ptr->EPSG_code; } const boost::shared_ptr<LocalMapData>& getLocalMapData() const { return data_ptr; } protected: boost::shared_ptr<LocalMapData> data_ptr; }; }} #endif // __ENVIRE_MAPS_LOCAL_MAP_HPP__ <commit_msg>remove not used variables and update docu of LocalMap<commit_after>#ifndef __ENVIRE_MAPS_LOCAL_MAP_HPP__ #define __ENVIRE_MAPS_LOCAL_MAP_HPP__ #include <base/Eigen.hpp> #include <boost/shared_ptr.hpp> #include <string> namespace envire { namespace maps { /** @brief The type of the LocalMap */ enum LocalMapType { UNKNOWN_MAP = -1, GRID_MAP = 1, GEOMETRIC_MAP = 2, TOPOLOGICAL_MAP = 3, MLS_MAP = 4 }; const std::string UNKNOWN_MAP_ID = ""; const std::string UNKNOWN_EPSG_CODE = "NONE"; class LocalMapData { public: /** @brief Default constructor */ LocalMapData() :id(UNKNOWN_MAP_ID), offset(base::Transform3d::Identity()), map_type(UNKNOWN_MAP), EPSG_code(UNKNOWN_EPSG_CODE) {}; /** @brief Consturctor with parameters */ LocalMapData(const std::string &id, const base::Transform3d &offset, const LocalMapType map_type, const std::string &EPSG_code) :id(id), offset(offset), map_type(map_type), EPSG_code(EPSG_code) {}; /** @brief String id of the local map */ std::string id; /** * @brief Offest of the local map frame * @details * The map uses the Cartesian coordinate system: * - the initial origin of the map is placed in the bottom left corner * - the x-axis points to the right from the the origin * - the y-axis points upwards from the origin * * The offset represents the replacement of the local frame * with respect to the inital origin. * * The offsets along the x, y and z-axis (translation) are expressed in the map unit * (according to the unit used in the map resolution). * * The offset can also be reference as local frame */ base::Transform3d offset; /** @brief Type of the local map (s. #LocalMapType) */ LocalMapType map_type; /** * @brief EPSG_code that provides the geo-localized coordinate system * @details * The EPSG code depends in the coordinate system used for the * local map "NONE" in case of not geo-referenced map. * Example: "EPSG::4978" for the World Geodetic System 1984 (WGS-84) * Example: "EPSG::3199" Spain - Canary Islands onshore and offshore. * with bounds are [-21.93W, -11.75E] and [24.6S, 11.75N] using the * World Geodetic System 1984 (WGS-84) coordinate reference system * (CRS). * Example: "EPSG::5243" ETRS89 / LCC Germany (E-N) Bremen area with * WGS084 CRS * Reference: https://www.epsg-registry.org */ std::string EPSG_code; private: }; /**@brief LocalMap * Local map with respect to a given reference frame * A local map is the basic element to form a global * map (set of local maps structured in a tree). */ class LocalMap { public: typedef boost::shared_ptr<LocalMap> Ptr; LocalMap() : data_ptr(new LocalMapData()) { } /** * @brief [brief description] * @details to share same content (LocalMapData) between various instance of LocalMap * * @param data [description] */ LocalMap(const boost::shared_ptr<LocalMapData> &data) : data_ptr(data) { } /** * @brief make copy without sharing the content * @details the copy instance owns a new content (LocalMapData) * * @param other [description] */ LocalMap(const LocalMap& other) : data_ptr(new LocalMapData(*(other.data_ptr.get()))) { } virtual ~LocalMap() {}; const std::string& getId() const { return data_ptr->id; } std::string& getId() { return data_ptr->id; } const base::Transform3d& getLocalFrame() const { return data_ptr->offset; } base::Transform3d& getLocalFrame() { return data_ptr->offset; } const LocalMapType& getMapType() const { return data_ptr->map_type; } LocalMapType& getMapType() { return data_ptr->map_type; } const std::string& getEPSGCode() const { return data_ptr->EPSG_code; } std::string& getEPSGCode() { return data_ptr->EPSG_code; } const boost::shared_ptr<LocalMapData>& getLocalMapData() const { return data_ptr; } protected: boost::shared_ptr<LocalMapData> data_ptr; }; }} #endif // __ENVIRE_MAPS_LOCAL_MAP_HPP__ <|endoftext|>
<commit_before>#include "DicomData.hh" #include <algorithm> #include <globals.hh> #include "DicomSlice.hh" using namespace g4dicom; using namespace std; DicomData::DicomData() : _validity(0), _sorted(true), _slices(0), _dimensions(0) { } DicomData::~DicomData() { for (auto it = _slices.begin(); it != _slices.end(); it++) { delete (*it); } } void DicomData::Add(DicomSlice *slice) { _validity = 0; _sorted = false; vector<int> dims = slice->GetDimensions(); G4cout << "New data slice registered, dimensions: " << dims[0] << " x " << dims[1] << " x " << dims[2] << G4endl; _slices.push_back(slice); } bool DicomData::IsValid() { if (_validity == 0) { Validate(); } return (_validity > 0); } std::vector<int> DicomData::GetDimensions() { if (_dimensions.size() == 0) { int dimX = _slices[0]->GetDimensions()[0]; int dimY = _slices[0]->GetDimensions()[1]; int dimZ = _slices[0]->GetDimensions()[2]; for (int i = 1; i < _slices.size(); i++) { dimZ += _slices[i]->GetDimensions()[2]; } _dimensions.push_back(dimX); _dimensions.push_back(dimY); _dimensions.push_back(dimZ); } return _dimensions; } void DicomData::Validate() { _validity = -1; // Assumed invalid if (!_sorted) { SortSlices(); } std::vector<double> cosines0 = _slices[0]->directionCosines; std::vector<double> spacing0 = _slices[0]->spacing; std::vector<int> dims0 = _slices[0]->GetDimensions(); DicomSlice* previous = 0; for (auto it = _slices.begin(); it != _slices.end(); it++) { DicomSlice* slice = *it; if (slice->directionCosines != cosines0) return; if (slice->spacing != spacing0) return; if (slice->GetDimensions() != dims0) return; // Cannot interpret more slices in one file if (slice->GetDimensions()[2] > 1); if (previous) { // TODO: Check z value } previous = slice; } G4cout << "DICOM data validated." << G4endl; _validity = 1; // If we got here => success } // Help function for the sorting algorithm bool sortOrder(DicomSlice* slice1, DicomSlice* slice2) { return slice1->origin[2] < slice2->origin[2]; } void DicomData::SortSlices() { G4cout << "Sorting DICOM slices..." << G4endl; sort(_slices.begin(), _slices.end(), sortOrder); _sorted = true; } <commit_msg>Check for equivalence of slice separation<commit_after>#include "DicomData.hh" #include <algorithm> #include <cmath> #include <globals.hh> #include "DicomSlice.hh" using namespace g4dicom; using namespace std; DicomData::DicomData() : _validity(0), _sorted(true), _slices(0), _dimensions(0) { } DicomData::~DicomData() { for (auto it = _slices.begin(); it != _slices.end(); it++) { delete (*it); } } void DicomData::Add(DicomSlice *slice) { _validity = 0; _sorted = false; vector<int> dims = slice->GetDimensions(); G4cout << "New data slice registered, dimensions: " << dims[0] << " x " << dims[1] << " x " << dims[2] << G4endl; _slices.push_back(slice); } bool DicomData::IsValid() { if (_validity == 0) { Validate(); } return (_validity > 0); } std::vector<int> DicomData::GetDimensions() { if (_dimensions.size() == 0) { int dimX = _slices[0]->GetDimensions()[0]; int dimY = _slices[0]->GetDimensions()[1]; int dimZ = _slices[0]->GetDimensions()[2]; for (int i = 1; i < _slices.size(); i++) { dimZ += _slices[i]->GetDimensions()[2]; } _dimensions.push_back(dimX); _dimensions.push_back(dimY); _dimensions.push_back(dimZ); } return _dimensions; } void DicomData::Validate() { _validity = -1; // Assumed invalid if (!_sorted) { SortSlices(); } std::vector<double> cosines0 = _slices[0]->directionCosines; std::vector<double> spacing0 = _slices[0]->spacing; std::vector<int> dims0 = _slices[0]->GetDimensions(); DicomSlice* previous = 0; double difference = 0.0; for (auto it = _slices.begin(); it != _slices.end(); it++) { DicomSlice* slice = *it; if (slice->directionCosines != cosines0) return; if (slice->spacing != spacing0) return; if (slice->GetDimensions() != dims0) return; // Cannot interpret more slices in one file if (slice->GetDimensions()[2] > 1); if (previous) { // All differences are same if (difference) { double lastDiff = slice->origin[2] - previous->origin[2]; if (fabs(lastDiff - difference) > 0.001) { return; } } } previous = slice; } G4cout << "DICOM data validated." << G4endl; _validity = 1; // If we got here => success } // Help function for the sorting algorithm bool sortOrder(DicomSlice* slice1, DicomSlice* slice2) { return slice1->origin[2] < slice2->origin[2]; } void DicomData::SortSlices() { G4cout << "Sorting DICOM slices..." << G4endl; sort(_slices.begin(), _slices.end(), sortOrder); _sorted = true; } <|endoftext|>
<commit_before>// Copyright (c) 2017 Andrey Valyaev <[email protected]> // // This software may be modified and distributed under the terms // of the MIT license. See the LICENSE file for details. #include <TstTimed.h> #include <ResTimed.h> using namespace std; using namespace oout; TstTimed::TstTimed(const shared_ptr<const Test> &test) : test(test) { } shared_ptr<const Result> TstTimed::result() const { // @todo #94:15min Meansure execution time and pass into ResTimed return make_shared<const ResTimed>( test->result(), 0 ); } <commit_msg>#97: Meansure execution time<commit_after>// Copyright (c) 2017 Andrey Valyaev <[email protected]> // // This software may be modified and distributed under the terms // of the MIT license. See the LICENSE file for details. #include <TstTimed.h> #include <chrono> #include <ResTimed.h> using namespace std; using namespace oout; TstTimed::TstTimed(const shared_ptr<const Test> &test) : test(test) { } shared_ptr<const Result> TstTimed::result() const { const auto begin = chrono::high_resolution_clock::now(); const auto result = test->result(); const auto end = chrono::high_resolution_clock::now(); return make_shared<const ResTimed>( result, chrono::duration_cast<chrono::duration<float>>(end - begin).count() ); } <|endoftext|>
<commit_before>#include "VDShader.h" using namespace VideoDromm; VDShader::VDShader(VDSettingsRef aVDSettings, VDAnimationRef aVDAnimation, string aFragmentShaderFilePath, string aFragmentShaderString) { mFragmentShaderFilePath = aFragmentShaderFilePath; mFragmentShaderString = aFragmentShaderString; mValid = false; mActive = true; // shadertoy include shaderInclude = loadString(loadAsset("shadertoy.inc")); mVDSettings = aVDSettings; mVDAnimation = aVDAnimation; mError = ""; // priority to loading from string if (mFragmentShaderString.length() > 0) { mValid = setFragmentString(mFragmentShaderString, mFragmentShaderFilePath); } else { loadFragmentStringFromFile(mFragmentShaderFilePath); } if (mValid) { CI_LOG_V("VDShaders constructor success"); } else { CI_LOG_V("VDShaders constructor failed, do not use"); } } bool VDShader::loadFragmentStringFromFile(string aFileName) { mValid = false; // load fragment shader CI_LOG_V("loadFragmentStringFromFile, loading " + aFileName); if (aFileName.length() == 0) { mFragFile = getAssetPath("") / "mixfbo.frag"; } else { mFragFile = aFileName; } if (!fs::exists(mFragFile)) { mError = mFragFile.string() + " does not exist"; CI_LOG_V(mError); mFragFile = getAssetPath("") / "0.frag"; } //mName = mFragFile.filename().string(); // get filename without extension /*int dotIndex = fileName.find_last_of("."); if (dotIndex != std::string::npos) { mName = fileName.substr(0, dotIndex); } else { mName = fileName; }*/ mFragmentShaderFilePath = mFragFile.string(); mFragmentShaderString = loadString(loadFile(mFragFile)); mValid = setFragmentString(mFragmentShaderString, mFragFile.filename().string()); CI_LOG_V(mFragFile.string() + " loaded and compiled"); return mValid; } bool VDShader::setFragmentString(string aFragmentShaderString, string aName) { string mOriginalFragmentString = aFragmentShaderString; string mCurrentUniformsString = "// active uniforms start\n"; string mProcessedShaderString = ""; mError = ""; // we would like a name if (aName.length() == 0) aName = toString((int)getElapsedSeconds()) + ".frag"; string mNotFoundUniformsString = "/* " + aName + "\n"; // filename to save mValid = false; // load fragment shader CI_LOG_V("setFragmentString, loading" + aName); try { //CI_LOG_V("before regex " + mOriginalFragmentString); // shadertoy: // change void mainImage( out vec4 fragColor, in vec2 fragCoord ) to void main(void) std::regex pattern{ "mainImage" }; std::string replacement{ "main" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); pattern = { " out vec4 fragColor," }; replacement = { "void" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); pattern = { " in vec2 fragCoord" }; replacement = { "" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); pattern = { " vec2 fragCoord" }; replacement = { "" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); // html glslEditor: // change vec2 u_resolution to vec3 iResolution pattern = { "2 u_r" }; replacement = { "3 iR" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); pattern = { "u_r" }; replacement = { "iR" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); pattern = { "u_tex" }; replacement = { "iChannel" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); pattern = { "2 u_mouse" }; replacement = { "4 iMouse" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); pattern = { "u_m" }; replacement = { "iM" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); pattern = { "u_time" }; replacement = { "iGlobalTime" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); pattern = { "u_" }; replacement = { "i" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); pattern = { "gl_TexCoord[0].st" }; replacement = { "gl_FragCoord.xy/iResolution.xy" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); pattern = { "iAudio0" }; replacement = { "iChannel0" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); pattern = { "iFreq0" }; replacement = { "iChannel0.x" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); pattern = { "iFreq1" }; replacement = { "iChannel0.y" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); pattern = { "iFreq2" }; replacement = { "iChannel0.x" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); pattern = { "iRenderXY.x" }; replacement = { "0.0" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); pattern = { "iRenderXY.y" }; replacement = { "0.0" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); //CI_LOG_V("regexed " + mOriginalFragmentString); // change texture2D to texture for version > 150? // change fragCoord to gl_FragCoord // change gl_FragColor to fragColor // check if uniforms were declared in the file std::size_t foundUniform = mOriginalFragmentString.find("uniform "); if (foundUniform == std::string::npos) { CI_LOG_V("loadFragmentStringFromFile, no uniforms found, we add from shadertoy.inc"); aFragmentShaderString = "/* " + aName + " */\n" + shaderInclude + mOriginalFragmentString; } else { aFragmentShaderString = "/* " + aName + " */\n" + mOriginalFragmentString; } // before compilation save .frag file to inspect errors fs::path receivedFile = getAssetPath("") / "glsl" / "received" / aName; ofstream mFragReceived(receivedFile.string(), std::ofstream::binary); mFragReceived << aFragmentShaderString; mFragReceived.close(); CI_LOG_V("file saved:" + receivedFile.string()); // try to compile a first time to get active uniforms mShader = gl::GlslProg::create(mVDSettings->getDefaultVextexShaderString(), aFragmentShaderString); // update only if success mFragmentShaderString = aFragmentShaderString; mVDSettings->mMsg = aName + " loaded and compiled"; // name of the shader mName = aName; mValid = true; auto &uniforms = mShader->getActiveUniforms(); for (const auto &uniform : uniforms) { CI_LOG_V(aName + ", uniform name:" + uniform.getName()); // if uniform is handled if (mVDAnimation->isExistingUniform(uniform.getName())) { int uniformType = mVDAnimation->getUniformType(uniform.getName()); switch (uniformType) { case 0: // float mShader->uniform(uniform.getName(), mVDAnimation->getFloatUniformValueByName(uniform.getName())); mCurrentUniformsString += "uniform float " + uniform.getName() + "; // " + toString(mVDAnimation->getFloatUniformValueByName(uniform.getName())) + "\n"; break; case 1: // sampler2D mShader->uniform(uniform.getName(), mVDAnimation->getSampler2DUniformValueByName(uniform.getName())); mCurrentUniformsString += "uniform sampler2D " + uniform.getName() + "; // " + toString(mVDAnimation->getSampler2DUniformValueByName(uniform.getName())) + "\n"; break; case 2: // vec2 mShader->uniform(uniform.getName(), mVDAnimation->getVec2UniformValueByName(uniform.getName())); mCurrentUniformsString += "uniform vec2 " + uniform.getName() + "; // " + toString(mVDAnimation->getVec2UniformValueByName(uniform.getName())) + "\n"; break; case 3: // vec3 mShader->uniform(uniform.getName(), mVDAnimation->getVec3UniformValueByName(uniform.getName())); mCurrentUniformsString += "uniform vec3 " + uniform.getName() + "; // " + toString(mVDAnimation->getVec3UniformValueByName(uniform.getName())) + "\n"; break; case 4: // vec4 mShader->uniform(uniform.getName(), mVDAnimation->getVec4UniformValueByName(uniform.getName())); mCurrentUniformsString += "uniform vec4 " + uniform.getName() + "; // " + toString(mVDAnimation->getVec4UniformValueByName(uniform.getName())) + "\n"; break; case 5: // int mShader->uniform(uniform.getName(), mVDAnimation->getIntUniformValueByName(uniform.getName())); mCurrentUniformsString += "uniform int " + uniform.getName() + "; // " + toString(mVDAnimation->getIntUniformValueByName(uniform.getName())) + "\n"; break; case 6: // bool mShader->uniform(uniform.getName(), mVDAnimation->getBoolUniformValueByName(uniform.getName())); mCurrentUniformsString += "uniform bool " + uniform.getName() + "; // " + toString(mVDAnimation->getBoolUniformValueByName(uniform.getName())) + "\n"; break; default: break; } } else { if (uniform.getName() != "ciModelViewProjection") { mNotFoundUniformsString += "not found " + uniform.getName() + "\n"; } } } // add "out vec4 fragColor" if necessary std::size_t foundFragColorDeclaration = mOriginalFragmentString.find("out vec4 fragColor;"); if (foundFragColorDeclaration == std::string::npos) { mNotFoundUniformsString += "*/\nout vec4 fragColor;\nvec2 fragCoord = gl_FragCoord.xy; // keep the 2 spaces between vec2 and fragCoord\n"; } else { mNotFoundUniformsString += "*/\nvec2 fragCoord = gl_FragCoord.xy; // keep the 2 spaces between vec2 and fragCoord\n"; } mCurrentUniformsString += "// active uniforms end\n"; // save .frag file to migrate old shaders // doubles iGlobalTime 20180304 mProcessedShaderString = mNotFoundUniformsString + mCurrentUniformsString + mOriginalFragmentString; mProcessedShaderString = mNotFoundUniformsString + mOriginalFragmentString; fs::path processedFile = getAssetPath("") / "glsl" / "processed" / aName; ofstream mFragProcessed(processedFile.string(), std::ofstream::binary); mFragProcessed << mProcessedShaderString; mFragProcessed.close(); CI_LOG_V("processed file saved:" + processedFile.string()); // 20161209 problem on Mac mShader->setLabel(mName); // try to compile a second time mShader = gl::GlslProg::create(mVDSettings->getDefaultVextexShaderString(), mProcessedShaderString); mFragmentShaderString = mProcessedShaderString; // update only if success mVDSettings->mMsg = aName + " loaded and compiled"; CI_LOG_V(mVDSettings->mMsg); // 20161209 problem on Mac mShader->setLabel(mName); mValid = true; } catch (gl::GlslProgCompileExc &exc) { mError = aName + string(exc.what()); CI_LOG_V("setFragmentString, unable to compile live fragment shader:" + mError); } catch (const std::exception &e) { mError = aName + string(e.what()); CI_LOG_V("setFragmentString, error on live fragment shader:" + mError); } mVDSettings->mMsg = mError; return mValid; } gl::GlslProgRef VDShader::getShader() { return mShader; } string VDShader::getName() { return mName; } void VDShader::removeShader() { CI_LOG_V("remove shader"); mValid = false; mActive = false; } #pragma warning(pop) // _CRT_SECURE_NO_WARNINGS <commit_msg>// 20180310 avoid errors<commit_after>#include "VDShader.h" using namespace VideoDromm; VDShader::VDShader(VDSettingsRef aVDSettings, VDAnimationRef aVDAnimation, string aFragmentShaderFilePath, string aFragmentShaderString) { mFragmentShaderFilePath = aFragmentShaderFilePath; mFragmentShaderString = aFragmentShaderString; mValid = false; mActive = true; // shadertoy include shaderInclude = loadString(loadAsset("shadertoy.inc")); mVDSettings = aVDSettings; mVDAnimation = aVDAnimation; mError = ""; // priority to loading from string if (mFragmentShaderString.length() > 0) { mValid = setFragmentString(mFragmentShaderString, mFragmentShaderFilePath); } else { loadFragmentStringFromFile(mFragmentShaderFilePath); } if (mValid) { CI_LOG_V("VDShaders constructor success"); } else { CI_LOG_V("VDShaders constructor failed, do not use"); } } bool VDShader::loadFragmentStringFromFile(string aFileName) { mValid = false; // load fragment shader CI_LOG_V("loadFragmentStringFromFile, loading " + aFileName); if (aFileName.length() == 0) { mFragFile = getAssetPath("") / "mixfbo.frag"; } else { mFragFile = aFileName; } if (!fs::exists(mFragFile)) { mError = mFragFile.string() + " does not exist"; CI_LOG_V(mError); mFragFile = getAssetPath("") / "0.frag"; } //mName = mFragFile.filename().string(); // get filename without extension /*int dotIndex = fileName.find_last_of("."); if (dotIndex != std::string::npos) { mName = fileName.substr(0, dotIndex); } else { mName = fileName; }*/ mFragmentShaderFilePath = mFragFile.string(); mFragmentShaderString = loadString(loadFile(mFragFile)); mValid = setFragmentString(mFragmentShaderString, mFragFile.filename().string()); CI_LOG_V(mFragFile.string() + " loaded and compiled"); return mValid; } bool VDShader::setFragmentString(string aFragmentShaderString, string aName) { string mOriginalFragmentString = aFragmentShaderString; string mCurrentUniformsString = "// active uniforms start\n"; string mProcessedShaderString = ""; mError = ""; // we would like a name if (aName.length() == 0) aName = toString((int)getElapsedSeconds()) + ".frag"; string mNotFoundUniformsString = "/* " + aName + "\n"; // filename to save mValid = false; // load fragment shader CI_LOG_V("setFragmentString, loading" + aName); try { //CI_LOG_V("before regex " + mOriginalFragmentString); // shadertoy: // change void mainImage( out vec4 fragColor, in vec2 fragCoord ) to void main(void) std::regex pattern{ "mainImage" }; std::string replacement{ "main" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); pattern = { " out vec4 fragColor," }; replacement = { "void" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); pattern = { " in vec2 fragCoord" }; replacement = { "" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); pattern = { " vec2 fragCoord" }; replacement = { "" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); // html glslEditor: // change vec2 u_resolution to vec3 iResolution pattern = { "2 u_r" }; replacement = { "3 iR" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); pattern = { "u_r" }; replacement = { "iR" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); pattern = { "u_tex" }; replacement = { "iChannel" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); pattern = { "2 u_mouse" }; replacement = { "4 iMouse" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); pattern = { "u_m" }; replacement = { "iM" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); pattern = { "u_time" }; replacement = { "iGlobalTime" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); pattern = { "u_" }; replacement = { "i" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); pattern = { "gl_TexCoord[0].st" }; replacement = { "gl_FragCoord.xy/iResolution.xy" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); pattern = { "iAudio0" }; replacement = { "iChannel0" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); pattern = { "iFreq0" }; replacement = { "iChannel0.x" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); pattern = { "iFreq1" }; replacement = { "iChannel0.y" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); pattern = { "iFreq2" }; replacement = { "iChannel0.x" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); pattern = { "iRenderXY.x" }; replacement = { "0.0" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); pattern = { "iRenderXY.y" }; replacement = { "0.0" }; mOriginalFragmentString = std::regex_replace(mOriginalFragmentString, pattern, replacement); //CI_LOG_V("regexed " + mOriginalFragmentString); // change texture2D to texture for version > 150? // change fragCoord to gl_FragCoord // change gl_FragColor to fragColor // check if uniforms were declared in the file std::size_t foundUniform = mOriginalFragmentString.find("uniform "); if (foundUniform == std::string::npos) { CI_LOG_V("loadFragmentStringFromFile, no uniforms found, we add from shadertoy.inc"); aFragmentShaderString = "/* " + aName + " */\n" + shaderInclude + mOriginalFragmentString; } else { aFragmentShaderString = "/* " + aName + " */\n" + mOriginalFragmentString; } // before compilation save .frag file to inspect errors fs::path receivedFile = getAssetPath("") / "glsl" / "received" / aName; ofstream mFragReceived(receivedFile.string(), std::ofstream::binary); mFragReceived << aFragmentShaderString; mFragReceived.close(); CI_LOG_V("file saved:" + receivedFile.string()); // try to compile a first time to get active uniforms mShader = gl::GlslProg::create(mVDSettings->getDefaultVextexShaderString(), aFragmentShaderString); // update only if success mFragmentShaderString = aFragmentShaderString; mVDSettings->mMsg = aName + " loaded and compiled"; // name of the shader mName = aName; mValid = true; auto &uniforms = mShader->getActiveUniforms(); for (const auto &uniform : uniforms) { CI_LOG_V(aName + ", uniform name:" + uniform.getName()); // if uniform is handled if (mVDAnimation->isExistingUniform(uniform.getName())) { int uniformType = mVDAnimation->getUniformType(uniform.getName()); switch (uniformType) { case 0: // float mShader->uniform(uniform.getName(), mVDAnimation->getFloatUniformValueByName(uniform.getName())); mCurrentUniformsString += "uniform float " + uniform.getName() + "; // " + toString(mVDAnimation->getFloatUniformValueByName(uniform.getName())) + "\n"; break; case 1: // sampler2D mShader->uniform(uniform.getName(), mVDAnimation->getSampler2DUniformValueByName(uniform.getName())); mCurrentUniformsString += "uniform sampler2D " + uniform.getName() + "; // " + toString(mVDAnimation->getSampler2DUniformValueByName(uniform.getName())) + "\n"; break; case 2: // vec2 mShader->uniform(uniform.getName(), mVDAnimation->getVec2UniformValueByName(uniform.getName())); mCurrentUniformsString += "uniform vec2 " + uniform.getName() + "; // " + toString(mVDAnimation->getVec2UniformValueByName(uniform.getName())) + "\n"; break; case 3: // vec3 mShader->uniform(uniform.getName(), mVDAnimation->getVec3UniformValueByName(uniform.getName())); mCurrentUniformsString += "uniform vec3 " + uniform.getName() + "; // " + toString(mVDAnimation->getVec3UniformValueByName(uniform.getName())) + "\n"; break; case 4: // vec4 mShader->uniform(uniform.getName(), mVDAnimation->getVec4UniformValueByName(uniform.getName())); mCurrentUniformsString += "uniform vec4 " + uniform.getName() + "; // " + toString(mVDAnimation->getVec4UniformValueByName(uniform.getName())) + "\n"; break; case 5: // int mShader->uniform(uniform.getName(), mVDAnimation->getIntUniformValueByName(uniform.getName())); mCurrentUniformsString += "uniform int " + uniform.getName() + "; // " + toString(mVDAnimation->getIntUniformValueByName(uniform.getName())) + "\n"; break; case 6: // bool mShader->uniform(uniform.getName(), mVDAnimation->getBoolUniformValueByName(uniform.getName())); mCurrentUniformsString += "uniform bool " + uniform.getName() + "; // " + toString(mVDAnimation->getBoolUniformValueByName(uniform.getName())) + "\n"; break; default: break; } } else { if (uniform.getName() != "ciModelViewProjection") { mNotFoundUniformsString += "not found " + uniform.getName() + "\n"; } } } // add "out vec4 fragColor" if necessary std::size_t foundFragColorDeclaration = mOriginalFragmentString.find("out vec4 fragColor;"); if (foundFragColorDeclaration == std::string::npos) { mNotFoundUniformsString += "*/\nout vec4 fragColor;\nvec2 fragCoord = gl_FragCoord.xy; // keep the 2 spaces between vec2 and fragCoord\n"; } else { mNotFoundUniformsString += "*/\nvec2 fragCoord = gl_FragCoord.xy; // keep the 2 spaces between vec2 and fragCoord\n"; } mCurrentUniformsString += "// active uniforms end\n"; // save .frag file to migrate old shaders // doubles iGlobalTime 20180304 mProcessedShaderString = mNotFoundUniformsString + mCurrentUniformsString + mOriginalFragmentString; mProcessedShaderString = mNotFoundUniformsString + mOriginalFragmentString; fs::path processedFile = getAssetPath("") / "glsl" / "processed" / aName; ofstream mFragProcessed(processedFile.string(), std::ofstream::binary); mFragProcessed << mProcessedShaderString; mFragProcessed.close(); CI_LOG_V("processed file saved:" + processedFile.string()); // 20161209 problem on Mac mShader->setLabel(mName); // try to compile a second time // 20180310 avoid errors mShader = gl::GlslProg::create(mVDSettings->getDefaultVextexShaderString(), mProcessedShaderString); // 20180310 avoid errors mFragmentShaderString = mProcessedShaderString; // update only if success // 20180310 avoid errors mVDSettings->mMsg = aName + " loaded and compiled"; // 20180310 avoid errors CI_LOG_V(mVDSettings->mMsg); // 20180310 avoid errors mValid = true; } catch (gl::GlslProgCompileExc &exc) { mError = aName + string(exc.what()); CI_LOG_V("setFragmentString, unable to compile live fragment shader:" + mError); } catch (const std::exception &e) { mError = aName + string(e.what()); CI_LOG_V("setFragmentString, error on live fragment shader:" + mError); } mVDSettings->mMsg = mError; return mValid; } gl::GlslProgRef VDShader::getShader() { return mShader; } string VDShader::getName() { return mName; } void VDShader::removeShader() { CI_LOG_V("remove shader"); mValid = false; mActive = false; } #pragma warning(pop) // _CRT_SECURE_NO_WARNINGS <|endoftext|>
<commit_before>/// /// @file PhiCache.cpp /// @brief The PhiCache class calculates phi(x, a) using the recursive /// formula: phi(x, a) = phi(x, a - 1) - phi(x / primes[a], a - 1). /// I have added a cache to my implementation in which results /// of phi(x, a) are stored if x < 2^16 and a <= 500. The cache /// speeds up the calculations by at least 3 orders of /// magnitude near 10^15. /// /// Copyright (C) 2014 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <PhiCache.hpp> #include <PhiTiny.hpp> #include <pmath.hpp> #include <stdint.h> #include <algorithm> #include <limits> #include <vector> #include <cassert> using namespace std; namespace { inline int64_t fast_div(int64_t x, int32_t y) { // Avoid slow 64-bit division if (x <= numeric_limits<uint32_t>::max()) return ((uint32_t) x) / y; return x / y; } } // namespace namespace primecount { PhiCache::PhiCache(const vector<int32_t>& primes) : primes_(primes), bytes_(0) { // primecount uses 1-indexing i.e. primes[1] = 2 assert(primes_[0] == 0); size_t max_size = CACHE_A_LIMIT + 1; cache_.resize(min(primes.size(), max_size)); } /// Partial sieve function (a.k.a. Legendre-sum). /// phi(x, a) counts the numbers <= x that are not divisible /// by any of the first a primes. /// int64_t PhiCache::phi(int64_t x, int64_t a) { if (x < 1) return 0; if (a > x) return 1; if (a < 1) return x; if (primes_.at(a) >= x) return 1; return phi(x, a, 1); } /// Calculate phi(x, a) using the recursive formula: /// phi(x, a) = phi(x, a - 1) - phi(x / primes_[a], a - 1) /// int64_t PhiCache::phi(int64_t x, int64_t a, int sign) { int64_t sum; if (x < primes_[a]) sum = sign; else if (is_phi_tiny(a)) sum = phi_tiny(x, a) * sign; else if (is_phi_bsearch(x, a)) sum = phi_bsearch(x, a) * sign; else { int64_t iters = pi_bsearch(primes_, a, isqrt(x)); int64_t c = min(iters, PhiTiny::max_a()); sum = (a - iters) * -sign; sum += phi_tiny(x, c) * sign; for (int64_t a2 = c; a2 < iters; a2++) { int64_t x2 = fast_div(x, primes_[a2 + 1]); if (is_cached(x2, a2)) sum += cache_[a2][x2] * -sign; else sum += phi(x2, a2, -sign); } } if (write_to_cache(x, a)) cache_[a][x] = (uint16_t) (sum * sign); return sum; } /// Binary search phi(x, a) int64_t PhiCache::phi_bsearch(int64_t x, int64_t a) const { int64_t pix = pi_bsearch(primes_, x); return pix - a + 1; } bool PhiCache::is_phi_bsearch(int64_t x, int64_t a) const { return x <= primes_.back() && x < isquare(primes_[a + 1]); } bool PhiCache::write_to_cache(int64_t x, int64_t a) { if (a > CACHE_A_LIMIT || x > numeric_limits<uint16_t>::max()) return false; if (x >= cache_size(a)) { if (bytes_ > CACHE_BYTES_LIMIT) return false; bytes_ += (x + 1 - cache_size(a)) * 2; cache_[a].resize(x + 1, 0); } return true; } } // namespace primecount <commit_msg>Refactoring<commit_after>/// /// @file PhiCache.cpp /// @brief The PhiCache class calculates phi(x, a) using the recursive /// formula: phi(x, a) = phi(x, a - 1) - phi(x / primes[a], a - 1). /// I have added a cache to my implementation in which results /// of phi(x, a) are stored if x < 2^16 and a <= 500. The cache /// speeds up the calculations by at least 3 orders of /// magnitude near 10^15. /// /// Copyright (C) 2014 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <PhiCache.hpp> #include <PhiTiny.hpp> #include <pmath.hpp> #include <stdint.h> #include <algorithm> #include <limits> #include <vector> #include <cassert> using namespace std; namespace { inline int64_t fast_div(int64_t x, int32_t y) { // Avoid slow 64-bit division if (x <= numeric_limits<uint32_t>::max()) return ((uint32_t) x) / y; return x / y; } } // namespace namespace primecount { PhiCache::PhiCache(const vector<int32_t>& primes) : primes_(primes), bytes_(0) { // primecount uses 1-indexing i.e. primes[1] = 2 assert(primes_[0] == 0); size_t max_size = CACHE_A_LIMIT + 1; cache_.resize(min(primes.size(), max_size)); } /// Partial sieve function (a.k.a. Legendre-sum). /// phi(x, a) counts the numbers <= x that are not divisible /// by any of the first a primes. /// int64_t PhiCache::phi(int64_t x, int64_t a) { if (x < 1) return 0; if (a > x) return 1; if (a < 1) return x; if (primes_.at(a) >= x) return 1; return phi(x, a, 1); } /// Calculate phi(x, a) using the recursive formula: /// phi(x, a) = phi(x, a - 1) - phi(x / primes_[a], a - 1) /// int64_t PhiCache::phi(int64_t x, int64_t a, int sign) { int64_t sum; if (x < primes_[a]) sum = sign; else if (is_phi_tiny(a)) sum = phi_tiny(x, a) * sign; else if (is_phi_bsearch(x, a)) sum = phi_bsearch(x, a) * sign; else { int64_t iters = pi_bsearch(primes_, a, isqrt(x)); int64_t c = min(iters, PhiTiny::max_a()); sum = (a - iters) * -sign; sum += phi_tiny(x, c) * sign; for (int64_t a2 = c; a2 < iters; a2++) { int64_t x2 = fast_div(x, primes_[a2 + 1]); if (is_cached(x2, a2)) sum += cache_[a2][x2] * -sign; else sum += phi(x2, a2, -sign); } } if (write_to_cache(x, a)) cache_[a][x] = (uint16_t) (sum * sign); return sum; } /// Binary search phi(x, a) int64_t PhiCache::phi_bsearch(int64_t x, int64_t a) const { int64_t pix = pi_bsearch(primes_, x); return pix - a + 1; } bool PhiCache::is_phi_bsearch(int64_t x, int64_t a) const { return x <= primes_.back() && x < isquare(primes_[a + 1]); } bool PhiCache::write_to_cache(int64_t x, int64_t a) { if (a > CACHE_A_LIMIT || x > numeric_limits<uint16_t>::max()) return false; if (x >= cache_size(a)) { if (bytes_ > CACHE_BYTES_LIMIT) return false; bytes_ += (x + 1 - cache_size(a)) * 2; cache_[a].resize(x + 1, 0); } return true; } } // namespace primecount <|endoftext|>
<commit_before> #include <algorithm> #include <iostream> #include <cassert> #include <sstream> #include <boost/format.hpp> #include <boost/algorithm/string.hpp> #include <glog/logging.h> #include "../include/tools.hpp" #include "../include/aleAgent.hpp" namespace deepRL { void DeepQLearner::LoadPretrainedModel(const std::string& model_bin) { net_->CopyTrainedLayersFrom(model_bin); } void DeepQLearner::Initialize() { // Initialize net and solver caffe::SolverParameter solver_param; caffe::ReadProtoFromTextFileOrDie(solver_param_, &solver_param); solver_.reset(caffe::SolverRegistry<float>::CreateSolver(solver_param)); //current q-net net_ = solver_->net(); //target q-net target_net_ = solver_->net(); // Cache pointers to blobs that hold Q values q_values_blob_ = net_->blob_by_name("q_values"); // Initialize dummy input data with 0 std::fill(dummy_input_data_.begin(), dummy_input_data_.end(), 0.0); // Cache pointers to input layers frames_input_layer_ = boost::dynamic_pointer_cast<caffe::MemoryDataLayer<float>>( net_->layer_by_name("frames_input_layer")); assert(frames_input_layer_); assert(deepRL::HasBlobSize( *net_->blob_by_name("frames"), kMinibatchSize, kInputFrameCount, kCroppedFrameSize, kCroppedFrameSize)); // Cache pointers to target input layers target_input_layer_ = boost::dynamic_pointer_cast<caffe::MemoryDataLayer<float>>( net_->layer_by_name("target_input_layer")); assert(target_input_layer_); assert(deepRL::HasBlobSize( *net_->blob_by_name("target"), kMinibatchSize, kOutputCount, 1, 1)); // Cache pointers to filter input layers filter_input_layer_ = boost::dynamic_pointer_cast<caffe::MemoryDataLayer<float>>( net_->layer_by_name("filter_input_layer")); assert(filter_input_layer_); assert(deepRL::HasBlobSize( *net_->blob_by_name("filter"), kMinibatchSize, kOutputCount, 1, 1)); } /** ugly code .may be we could set batchsize=1, * then we iterate minibatchsize times, so we can compute for a single frame **/ ActionPairVec DeepQLearner::GetBatchQvalue(const InputFramesVec & frames_batch,const NetSp& qnet) { //(inputframe1,inputframe2,...,inputframe_batch_size) assert(frames_batch.size() <= kMinibatchSize); std::array<float, kMinibatchDataSize> frames_input; for (auto i = 0; i < frames_batch.size(); ++i) { // Input frames to the net and compute Q values for each legal actions for (auto j = 0; j < kInputFrameCount; ++j) {// const auto& frame_data = frames_batch[i][j]; std::copy( frame_data->begin(), frame_data->end(), frames_input.begin() + i * kInputDataSize + j * kCroppedFrameDataSize); } } FillData2Layers(frames_input, dummy_input_data_, dummy_input_data_); qnet->Forward();//test ,now we got the qvalue ActionPairVec results; results.reserve(frames_batch.size()); for (auto i = 0; i < frames_batch.size(); ++i) { // Get the Q values from the net const auto action_evaluator = [&](Action action) { const auto q = q_values_blob_->data_at(i, static_cast<int>(action), 0, 0); assert(!std::isnan(q)); return q; }; std::vector<float> q_values(legal_actions_.size()); std::transform( legal_actions_.begin(), legal_actions_.end(), q_values.begin(), action_evaluator); //if (frames_batch.size() == 1) std::cout << deepRL::PrintQValues(q_values, legal_actions_); // Select the action with the maximum Q value const auto max_idx = std::distance( q_values.begin(), std::max_element(q_values.begin(), q_values.end())); results.emplace_back(legal_actions_[max_idx], q_values[max_idx]); } return results; } Action DeepQLearner::SelectAction(const InputFrames& last_frames) { assert(epsilon_ >= 0.0 && epsilon_ <= 1.0); Action action; if (std::uniform_real_distribution<>(0.0, 1.0)(random_engine) < epsilon_) {//random const auto random_idx = std::uniform_int_distribution<int>(0, legal_actions_.size() - 1)(random_engine); action = legal_actions_[random_idx]; //std::cout << action_to_string(action) << " (random)"; } else {//max greedy action = GreedyActionSelection(last_frames).first;// max //std::cout << action_to_string(action) << " (greedy)"; } return action; } ActionPair DeepQLearner::GreedyActionSelection(const InputFrames& last_frames) { return GetBatchQvalue(InputFramesVec{{last_frames}},net_).front(); } void DeepQLearner::BatchUpdate() { if (current_iter_%100 ==0) std::cout << "iteration: " << current_iter_ << std::endl; current_iter_++; // Sample transitions from replay memory //std::cout << "==>begin sampling experiences" << std::endl; std::vector<int> transitions = replay_memory_.sampleTransition(); CHECK(transitions.size() == kMinibatchSize) << "Exeperience is not sampled enough"; //std::cout << "<==end sampling experiences" << std::endl; // for each transition <s,a,r,s'> ,compute the q values for s (net_)and s'(target_net_) // Compute target values: max_a Q(s',a) InputFramesVec target_last_frames_batch; for (const auto idx : transitions) { const auto& transition = replay_memory_.getTransitionByIdx(idx); if (!std::get<3>(transition)) { // This is a terminal state continue; } // Compute target value InputFrames target_last_frames; for (auto i = 0; i < kInputFrameCount - 1; ++i) { target_last_frames[i] = std::get<0>(transition)[i + 1]; } target_last_frames[kInputFrameCount - 1] = std::get<3>(transition).get(); target_last_frames_batch.push_back(target_last_frames); } //get qvalue from target_net_ const auto actions_and_values = GetBatchQvalue(target_last_frames_batch,target_net_); //do data feeding -> train Q-network FramesLayerInputData frames_input; TargetLayerInputData target_input; FilterLayerInputData filter_input; std::fill(target_input.begin(), target_input.end(), 0.0f); std::fill(filter_input.begin(), filter_input.end(), 0.0f); auto target_value_idx = 0; //std::cout << "filling data" << std::endl; for (auto i = 0; i < kMinibatchSize; ++i) { const auto& transition = replay_memory_.getTransitionByIdx(transitions[i]); const auto action = std::get<1>(transition);//action assert(static_cast<int>(action) < kOutputCount); const auto reward = std::get<2>(transition);//reward assert(reward >= -1.0 && reward <= 1.0); const auto target = std::get<3>(transition) ?//r+maxQ'(s,a) reward + gamma * actions_and_values[target_value_idx++].second : reward; assert(!std::isnan(target)); target_input[i * kOutputCount + static_cast<int>(action)] = target; filter_input[i * kOutputCount + static_cast<int>(action)] = 1; //VLOG(1) << "filter:" << action_to_string(action) << " target:" << target; for (auto j = 0; j < kInputFrameCount; ++j) { const auto& frame_data = std::get<0>(transition)[j]; std::copy( frame_data->begin(), frame_data->end(), frames_input.begin() + i * kInputDataSize + j * kCroppedFrameDataSize); } } FillData2Layers(frames_input, target_input, filter_input); solver_->Step(1); //update target_net_ with frequency param: update_frequency_ if (update_frequency_ >0 and current_iter_%update_frequency_ ==0){ target_net_ = solver_->net(); // can we do like this ? } //epsilon decay //std::cout << " epsilon:" << epsilon_ << std::endl; if (epsilon_decay_ > 0.0) { if (epsilon_ != epsilon_min_){ epsilon_ = epsilon_*epsilon_decay_; if (current_iter_ > epsilon_explore_idx_) epsilon_ = epsilon_ < epsilon_min_ ? epsilon_min_ : epsilon_; } } } void DeepQLearner::FillData2Layers( const FramesLayerInputData& frames_input, const TargetLayerInputData& target_input, const FilterLayerInputData& filter_input) { frames_input_layer_->Reset( const_cast<float*>(frames_input.data()),//data dummy_input_data_.data(),//label kMinibatchSize);//size n target_input_layer_->Reset( const_cast<float*>(target_input.data()), dummy_input_data_.data(), kMinibatchSize); filter_input_layer_->Reset( const_cast<float*>(filter_input.data()), dummy_input_data_.data(), kMinibatchSize); } } <commit_msg>change update method <commit_after> #include <algorithm> #include <iostream> #include <cassert> #include <sstream> #include <boost/format.hpp> #include <boost/algorithm/string.hpp> #include <glog/logging.h> #include "../include/tools.hpp" #include "../include/aleAgent.hpp" namespace deepRL { void DeepQLearner::LoadPretrainedModel(const std::string& model_bin) { net_->CopyTrainedLayersFrom(model_bin); } void DeepQLearner::Initialize() { // Initialize net and solver caffe::SolverParameter solver_param; caffe::ReadProtoFromTextFileOrDie(solver_param_, &solver_param); solver_.reset(caffe::SolverRegistry<float>::CreateSolver(solver_param)); //current q-net net_ = solver_->net(); //target q-net target_net_ = solver_->net(); // Cache pointers to blobs that hold Q values q_values_blob_ = net_->blob_by_name("q_values"); // Initialize dummy input data with 0 std::fill(dummy_input_data_.begin(), dummy_input_data_.end(), 0.0); // Cache pointers to input layers frames_input_layer_ = boost::dynamic_pointer_cast<caffe::MemoryDataLayer<float>>( net_->layer_by_name("frames_input_layer")); assert(frames_input_layer_); assert(deepRL::HasBlobSize( *net_->blob_by_name("frames"), 1, kInputFrameCount, kCroppedFrameSize, kCroppedFrameSize)); // Cache pointers to target input layers target_input_layer_ = boost::dynamic_pointer_cast<caffe::MemoryDataLayer<float>>( net_->layer_by_name("target_input_layer")); assert(target_input_layer_); assert(deepRL::HasBlobSize( *net_->blob_by_name("target"), 1, kOutputCount, 1, 1)); // Cache pointers to filter input layers filter_input_layer_ = boost::dynamic_pointer_cast<caffe::MemoryDataLayer<float>>( net_->layer_by_name("filter_input_layer")); assert(filter_input_layer_); assert(deepRL::HasBlobSize( *net_->blob_by_name("filter"), 1, kOutputCount, 1, 1)); } //one inputframe mode std::vector<float> DeepQLearner::ForwardQvalue(const InputFrames& frames_input,const NetSp& qnet){ std::vector<float> q_values(legal_actions_.size()); std::array<float,kInputDataSize> frames_input_data; for (auto j = 0; j < kInputFrameCount; ++j) {// const auto& frame_data = frames_input[j]; std::copy( frame_data->begin(), frame_data->end(), frames_input_data.begin() + j*kCroppedFrameDataSize); } FillData2Layers(frames_input_data, dummy_input_data_, dummy_input_data_); qnet->Forward();//test ,now we got the qvalue // Get the Q values from the net const auto action_evaluator = [&](Action action) { const auto q = q_values_blob_->data_at(0, static_cast<int>(action), 0, 0); //std::cout << q << std::endl; assert(!std::isnan(q)); return q; }; std::transform( legal_actions_.begin(), legal_actions_.end(), q_values.begin(), action_evaluator); //std::cout << PrintQValues(q_values,legal_actions_) << std::endl; return q_values; } ActionPair DeepQLearner::MaxActionQvalue(std::vector<float> q_values){ const auto max_idx = std::distance( q_values.begin(), std::max_element(q_values.begin(), q_values.end())); return std::make_pair(legal_actions_[max_idx],q_values[max_idx]); } Action DeepQLearner::SelectAction(const InputFrames& last_frames) { assert(epsilon_ >= 0.0 && epsilon_ <= 1.0); Action action; if (std::uniform_real_distribution<>(0.0, 1.0)(random_engine) < epsilon_) {//random const auto random_idx = std::uniform_int_distribution<int>(0, legal_actions_.size() - 1)(random_engine); action = legal_actions_[random_idx]; //std::cout << action_to_string(action) << " (random)"; } else {//max greedy action = MaxActionQvalue(ForwardQvalue(input_frames,net_)).first;// max //std::cout << action_to_string(action) << " (greedy)"; } return action; } void DeepQLearner::StepUpdate(const Transition& tr){//only using single inputframe if (current_iter_%100 ==0) std::cout << "iteration: " << current_iter_ << " , epsilon: " << epsilon_ << std::endl; current_iter_++; //extract <s,a,r,s'> InputFrames s = std::get<0>(tr); const auto a = std::get<1>(tr); const auto r = std::get<2>(tr); assert(r >= -1.0 && r <= 1.0); InputFrames s_; const auto terminal = std::get<3>(tr) ? false : true; if(!terminal) { for (auto i = 0; i < kInputFrameCount - 1; ++i) { s_[i] = std::get<0>(tr)[i + 1]; } s_[kInputFrameCount - 1] = std::get<3>(tr).get(); } const auto target_q = terminal ?//r+maxQ'(s,a) r: r + gamma * MaxActionQvalue(ForwardQvalue(s_,target_net_)).second; assert(!std::isnan(target_q)); //do data feeding -> train Q-network FramesLayerInputData frames_input; TargetLayerInputData target_input; FilterLayerInputData filter_input; std::fill(target_input.begin(), target_input.end(), 0.0f); std::fill(filter_input.begin(), filter_input.end(), 0.0f); // only the changed q has the loss target_input[static_cast<int>(a)] = target_q; filter_input[static_cast<int>(a)] = 1; //VLOG(1) << "filter:" << action_to_string(action) << " target:" << target; for (auto j = 0; j < kInputFrameCount; ++j) { const auto& frame_data = s[j]; std::copy( frame_data->begin(), frame_data->end(), frames_input.begin() + j * kCroppedFrameDataSize); } FillData2Layers(frames_input, target_input, filter_input); solver_->Step(1); //update target_net_ with frequency param: update_frequency_ if (update_frequency_ >0 and current_iter_%update_frequency_ ==0){ target_net_ = solver_->net(); // can we do like this ? } //epsilon decay //std::cout << " epsilon:" << epsilon_ << std::endl; if (epsilon_decay_ > 0.0) { if (epsilon_ != epsilon_min_){ epsilon_ = epsilon_*epsilon_decay_; if (current_iter_ > epsilon_explore_idx_) epsilon_ = epsilon_ < epsilon_min_ ? epsilon_min_ : epsilon_; } } } void DeepQLearner::BatchUpdate() { // Sample transitions from replay memory //std::cout << "==>begin sampling experiences" << std::endl; std::vector<int> transitions = replay_memory_.sampleTransition(); CHECK(transitions.size() == kMinibatchSize) << "Exeperience is not sampled enough"; for (auto i = 0; i < kMinibatchSize; ++i) { const auto& transition = replay_memory_.getTransitionByIdx(transitions[i]); StepUpdate(transition); } } void DeepQLearner::FillData2Layers( const FramesLayerInputData& frames_input, const TargetLayerInputData& target_input, const FilterLayerInputData& filter_input) { frames_input_layer_->Reset( const_cast<float*>(frames_input.data()),//data dummy_input_data_.data(),//label 1);//size n target_input_layer_->Reset( const_cast<float*>(target_input.data()), dummy_input_data_.data(), 1); filter_input_layer_->Reset( const_cast<float*>(filter_input.data()), dummy_input_data_.data(), 1); } } <|endoftext|>
<commit_before>#include "tests-base.hpp" extern "C" { #include "../internal/database.h" #include "../internal/composition.h" } #include "helpers-strings.hpp" TEST(StreamReorder, Unchanged) { const char* i = "Bike"; size_t il = strlen(i); StreamState stream; EXPECT_EQ(1, stream_initialize(&stream, i, il, UnicodeProperty_Normalization_Compatibility_Compose)); EXPECT_EQ(1, stream_execute(&stream)); EXPECT_EQ(1, stream_reorder(&stream)); EXPECT_UTF8EQ("Bike", helpers::utf8(stream.codepoint, stream.current * sizeof(unicode_t)).c_str()); }<commit_msg>suite-stream-reorder: Refactored test to use correct data.<commit_after>#include "tests-base.hpp" extern "C" { #include "../internal/database.h" #include "../internal/composition.h" } #include "helpers-strings.hpp" StreamState CreateStream(const char* text) { StreamState stream = { 0 }; std::vector<unicode_t> converted = helpers::utf32(text); for (std::vector<unicode_t>::iterator it = converted.begin(); it != converted.end(); ++it) { stream.codepoint[stream.current] = *it; stream.canonical_combining_class[stream.current] = database_queryproperty(*it, UnicodeProperty_CanonicalCombiningClass); stream.current++; } return stream; } TEST(StreamReorder, Unchanged) { StreamState stream = CreateStream("Bike"); EXPECT_EQ(1, stream_reorder(&stream)); EXPECT_UTF8EQ("Bike", helpers::utf8(stream.codepoint, stream.current * sizeof(unicode_t)).c_str()); }<|endoftext|>
<commit_before>#include "RGBColor.h" RGBColor::RGBColor() : r(.0f), g(.0f), b(.0f) { } RGBColor::RGBColor(const float rgb) : r(rgb), g(rgb), b (rgb) { } RGBColor::RGBColor(const float red, const float green, const float blue) : r(red), g(green), b(blue) { } RGBColor::~RGBColor() { r = .0f; g = .0f; b = .0f; }<commit_msg>Changed default color value from black to white<commit_after>#include "RGBColor.h" RGBColor::RGBColor() : r(1), g(1), b(1) { } RGBColor::RGBColor(const float rgb) : r(rgb), g(rgb), b (rgb) { } RGBColor::RGBColor(const float red, const float green, const float blue) : r(red), g(green), b(blue) { } RGBColor::~RGBColor() { r = .0f; g = .0f; b = .0f; }<|endoftext|>
<commit_before>#include "Renderer.hpp" static GLfloat vertices[] = { 1, 1,0, 1,-1,0, -1,1,0, 1,-1,0, -1,-1,0, -1,1,0 }; static GLfloat uvs[] = { 1,0, 1,1, 0,0, 1,1, 0,1, 0,0 }; const char * Renderer::defaultVertexShader = "#version 330 core\n" "\n" "in vec3 position;\n" "in vec2 texCoord;\n" "\n" "out vec2 uv;\n" "\n" "void main(){\n" " gl_Position = vec4(position, 1);\n" " uv = texCoord;\n" "}"; const char * Renderer::defaultFragmentShader = "#version 330 core\n" "\n" "out vec4 color;\n" "\n" "in vec2 uv;\n" "uniform float time;\n" "uniform vec2 mouse;\n" "uniform float ration;\n" "\n" "void main(){\n" " color = vec4(cos(uv.x * 5 - time / 1000) / 2 + .5, 0, sin(uv.x * 5 - time / 1000) / 2 + .5, 1);\n" "}"; /** * @brief Renderer::Renderer * @param parent Parent object of the render window * * Create a new Renderer with default shader */ Renderer::Renderer(QWindow *parent) : Renderer::Renderer("new", defaultFragmentShader, parent){ } /** * @brief Renderer::Renderer * @param filename Name that should shown in the title * @param instructions Shader code for execution * @param parent Parent object of the render window * * Create a new Renderer with given code and set filename as title */ Renderer::Renderer(const QString &filename, const QString &instructions, QWindow *parent) : QWindow(parent), clearColor(Qt::black), context(0), device(0), time(0), pendingUpdate(false), vao(0), uvBuffer(0), audioLeftTexture(0), audioRightTexture(0), vertexAttr(0), uvAttr(0), timeUniform(0), shaderProgram(0), fragmentSource(instructions) { setTitle(filename); m_logger = new QOpenGLDebugLogger( this ); connect(m_logger, SIGNAL(messageLogged(QOpenGLDebugMessage)), this, SLOT(onMessageLogged(QOpenGLDebugMessage)), Qt::DirectConnection ); setSurfaceType(QWindow::OpenGLSurface); time = new QTime(); time->start(); audio = new AudioInputProcessor(this); connect(audio, SIGNAL(processData(QByteArray)), this, SLOT(updateAudioData(QByteArray))); audio->start(); QSurfaceFormat format; format.setMajorVersion(3); format.setMinorVersion(3); format.setSamples(4); format.setProfile(QSurfaceFormat::CoreProfile); setFormat(format); } /** * @brief Renderer::~Renderer * * Free resources */ Renderer::~Renderer(){ glDeleteBuffers(1, &uvBuffer); glDeleteTextures(1, &audioLeftTexture); glDeleteTextures(1, &audioRightTexture); delete time; delete vao; delete device; delete m_logger; } /** * @brief Renderer::init * @return True on success, otherwise false * * Allocates grafic memory and initialize the shader program */ bool Renderer::init(){ delete vao; vao = new QOpenGLVertexArrayObject(this); vao->create(); vao->bind(); glDeleteBuffers(1, &vertexBuffer); glGenBuffers(1, &vertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glDeleteBuffers(1, &uvBuffer); glGenBuffers(1, &uvBuffer); glBindBuffer(GL_ARRAY_BUFFER, uvBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(uvs), uvs, GL_STATIC_DRAW); glEnable(GL_TEXTURE_1D); glDeleteTextures(1, &audioLeftTexture); glGenTextures(1, &audioLeftTexture); glDeleteTextures(1, &audioRightTexture); glGenTextures(1, &audioRightTexture); glClearColor(0,0,.3,1); bool result = initShaders(fragmentSource); vao->release(); return result; } /** * @brief Renderer::initShaders * @param fragmentShader Code to compile as shader * @return True on success, otherwise false * * Initialze and compile the shader program */ bool Renderer::initShaders(const QString &fragmentShader){ QOpenGLShaderProgram *newShaderProgram = new QOpenGLShaderProgram(this); QString error = ""; if(!newShaderProgram->addShaderFromSourceCode(QOpenGLShader::Vertex, defaultVertexShader)){ error = newShaderProgram->log(); delete newShaderProgram; if(fragmentShader == defaultFragmentShader) qWarning() << tr("Failed to compile default shader."); else if(shaderProgram == 0) initShaders(defaultFragmentShader); } if(!newShaderProgram->addShaderFromSourceCode(QOpenGLShader::Fragment,fragmentShader)){ error = newShaderProgram->log(); delete newShaderProgram; if(fragmentShader == defaultFragmentShader) qWarning() << tr("Failed to compile default shader."); else if(shaderProgram == 0) initShaders(defaultFragmentShader); } if(!newShaderProgram->link()){ error = newShaderProgram->log(); delete newShaderProgram; if(fragmentShader == defaultFragmentShader) qWarning() << tr("Failed to compile default shader."); else if(shaderProgram == 0) initShaders(defaultFragmentShader); } if(error != ""){ QRegExp errorline(":[0-9]+:"); errorline.indexIn(error); QString text = errorline.capturedTexts().at(0); text.replace(":", ""); if(text.toInt()-3 > 0) emit errored(error, text.toInt()-3); else emit errored(error, text.toInt()); return false; } shaderProgramMutex.lock(); if(shaderProgram) delete shaderProgram; shaderProgram = newShaderProgram; vertexAttr = shaderProgram->attributeLocation("position"); glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); shaderProgram->setAttributeBuffer(vertexAttr, GL_FLOAT, 0, 3); shaderProgram->enableAttributeArray(vertexAttr); uvAttr = shaderProgram->attributeLocation("texCoord"); glBindBuffer(GL_ARRAY_BUFFER, uvBuffer); shaderProgram->setAttributeBuffer("texCoord", GL_FLOAT, 0, 2); shaderProgram->enableAttributeArray(uvAttr); timeUniform = shaderProgram->uniformLocation("time"); mouseUniform = shaderProgram->uniformLocation("mouse"); rationUniform = shaderProgram->uniformLocation("ration"); fragmentSource = fragmentShader; shaderProgramMutex.unlock(); // qDebug() << "vertexAttr" << vertexAttr; // qDebug() << "uvAttr" << uvAttr; // qDebug() << "timeUniform" << timeUniform; // qDebug() << "audioUniform" << audioUniform; return true; } /** * @brief Renderer::render * * Initialize output device, execute the shader and display the result */ void Renderer::render(){ if(!device) device = new QOpenGLPaintDevice(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); device->setSize(size()); // qDebug() << QLatin1String(reinterpret_cast<const char*>(glGetString(GL_VERSION))) << " " << QLatin1String(reinterpret_cast<const char*>(glGetString(GL_SHADING_LANGUAGE_VERSION))); const qreal retinaScale = devicePixelRatio(); glViewport(0, 0, width() * retinaScale, height() * retinaScale); glClear(GL_COLOR_BUFFER_BIT); QPoint mouse = this->mapFromGlobal(QCursor::pos()); QVector2D mousePosition((float)mouse.x() / (float)this->width(), (float)mouse.y() / (float)this->height()); float ration = (float)this->width() / (float)this->height(); shaderProgramMutex.lock(); vao->bind(); shaderProgram->bind(); shaderProgram->setUniformValue(mouseUniform,mousePosition); if(this->height() != 0) shaderProgram->setUniformValue(rationUniform, ration); shaderProgram->setUniformValue(timeUniform, (float)time->elapsed()); glDrawArrays(GL_TRIANGLES, 0, 6); vao->release(); shaderProgramMutex.unlock(); } /** * @brief Renderer::renderLater * * Enqueue an update event to event queue */ void Renderer::renderLater(){ if(!pendingUpdate){ QCoreApplication::postEvent(this, new QEvent(QEvent::UpdateRequest)); pendingUpdate = true; } } /** * @brief Renderer::renderNow * * Use the compiled shader to render on the widget */ void Renderer::renderNow(){ pendingUpdate = false; if(!isExposed()) return; bool needsInit = false; if(!context){ context = new QOpenGLContext(this); context->setFormat(requestedFormat()); context->create(); needsInit = true; } context->makeCurrent(this); if(needsInit){ if (m_logger->initialize()){ m_logger->startLogging( QOpenGLDebugLogger::SynchronousLogging ); m_logger->enableMessages(); } initializeOpenGLFunctions(); init(); } if(!shaderProgram) initShaders(fragmentSource); if(shaderProgram) render(); context->swapBuffers(this); renderLater(); } /** * @brief Renderer::event * @param event The event that should be proccessed * @return True if the event was successful proccessed, otherwise false * * Called if a new event is poped from the event-queue to render on update event * and emit doneSignal on close event. */ bool Renderer::event(QEvent *event){ switch(event->type()){ case QEvent::UpdateRequest: QCoreApplication::postEvent(this, new QEvent(QEvent::UpdateRequest)); renderNow(); return true; case QEvent::Close: emit doneSignal(tr("User closed renderer")); return true; default: return QWindow::event(event); } } /** * @brief Renderer::exposeEvent * * Called if the window is ready to start rendering */ void Renderer::exposeEvent(QExposeEvent *){ if(isExposed()) renderNow(); } /** * @brief Renderer::updateCode * @param filename Text for the title * @param code New shader program code * @return True on success, otherwise false. * * Set new title and compile new code for the shader program */ bool Renderer::updateCode(const QString &filename, const QString &code){ if(!initShaders(code)) return false; setTitle(filename); show(); return true; } /** * @brief Renderer::updateAudioData * @param data New audio data * * Copy the new sound-data to the graphics memory for visualisation */ void Renderer::updateAudioData(QByteArray data){ if(!shaderProgram) return; GLenum type, internalType; Q_UNUSED(internalType); char typeSize; switch(audio->format().sampleType() + audio->format().sampleSize()){ case 8: case 10: type = GL_UNSIGNED_BYTE; internalType = GL_R8UI; typeSize = 1; break; case 9: type = GL_BYTE; internalType = GL_R8I; typeSize = 1; break; case 16: case 18: type = GL_UNSIGNED_SHORT; internalType = GL_R16UI; typeSize = 2; break; case 17: type = GL_SHORT; internalType = GL_R16I; typeSize = 2; break; case 32: case 34: type = GL_UNSIGNED_INT; internalType = GL_R32UI; typeSize = 4; break; case 33: type = GL_INT; internalType = GL_R32I; typeSize = 4; break; case 35: type = GL_FLOAT; internalType = GL_R32F; typeSize = 4; break; default: return; } char *left, *right; int count = data.size(); if(audio->format().channelCount() == 2){ count /= 2; left = new char[count]; right = new char[count]; for(int i = 0; i < count; i += typeSize){ for(int j = 0; j < typeSize; ++j){ left [i+j] = data[i*2+j]; right[i+j] = data[i*2+j+typeSize]; } } }else left = right = data.data(); shaderProgramMutex.lock(); shaderProgram->bind(); glBindTexture(GL_TEXTURE_1D, audioLeftTexture); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage1D(GL_TEXTURE_1D, 0, GL_R32F, count / typeSize, 0, GL_RED, type, left); glBindTexture(GL_TEXTURE_1D, audioRightTexture); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage1D(GL_TEXTURE_1D, 0, GL_R32F, count / typeSize, 0, GL_RED, type, right); shaderProgram->release(); shaderProgramMutex.unlock(); if(left != data.data()) delete[] left; if(right != data.data()) delete[] right; } /** * @brief Renderer::onMessageLogged * @param message Message text * * Write the message text in the debug output */ void Renderer::onMessageLogged(QOpenGLDebugMessage message){ qDebug() << message; } <commit_msg>Fixed segfault by recompiling faulty shader<commit_after>#include "Renderer.hpp" static GLfloat vertices[] = { 1, 1,0, 1,-1,0, -1,1,0, 1,-1,0, -1,-1,0, -1,1,0 }; static GLfloat uvs[] = { 1,0, 1,1, 0,0, 1,1, 0,1, 0,0 }; const char * Renderer::defaultVertexShader = "#version 330 core\n" "\n" "in vec3 position;\n" "in vec2 texCoord;\n" "\n" "out vec2 uv;\n" "\n" "void main(){\n" " gl_Position = vec4(position, 1);\n" " uv = texCoord;\n" "}"; const char * Renderer::defaultFragmentShader = "#version 330 core\n" "\n" "out vec4 color;\n" "\n" "in vec2 uv;\n" "uniform float time;\n" "uniform vec2 mouse;\n" "uniform float ration;\n" "\n" "void main(){\n" " color = vec4(cos(uv.x * 5 - time / 1000) / 2 + .5, 0, sin(uv.x * 5 - time / 1000) / 2 + .5, 1);\n" "}"; /** * @brief Renderer::Renderer * @param parent Parent object of the render window * * Create a new Renderer with default shader */ Renderer::Renderer(QWindow *parent) : Renderer::Renderer("new", defaultFragmentShader, parent){ } /** * @brief Renderer::Renderer * @param filename Name that should shown in the title * @param instructions Shader code for execution * @param parent Parent object of the render window * * Create a new Renderer with given code and set filename as title */ Renderer::Renderer(const QString &filename, const QString &instructions, QWindow *parent) : QWindow(parent), clearColor(Qt::black), context(0), device(0), time(0), pendingUpdate(false), vao(0), uvBuffer(0), audioLeftTexture(0), audioRightTexture(0), vertexAttr(0), uvAttr(0), timeUniform(0), shaderProgram(0), fragmentSource(instructions) { setTitle(filename); m_logger = new QOpenGLDebugLogger( this ); connect(m_logger, SIGNAL(messageLogged(QOpenGLDebugMessage)), this, SLOT(onMessageLogged(QOpenGLDebugMessage)), Qt::DirectConnection ); setSurfaceType(QWindow::OpenGLSurface); time = new QTime(); time->start(); audio = new AudioInputProcessor(this); connect(audio, SIGNAL(processData(QByteArray)), this, SLOT(updateAudioData(QByteArray))); audio->start(); QSurfaceFormat format; format.setMajorVersion(3); format.setMinorVersion(3); format.setSamples(4); format.setProfile(QSurfaceFormat::CoreProfile); setFormat(format); } /** * @brief Renderer::~Renderer * * Free resources */ Renderer::~Renderer(){ glDeleteBuffers(1, &uvBuffer); glDeleteTextures(1, &audioLeftTexture); glDeleteTextures(1, &audioRightTexture); delete time; delete vao; delete device; delete m_logger; } /** * @brief Renderer::init * @return True on success, otherwise false * * Allocates grafic memory and initialize the shader program */ bool Renderer::init(){ delete vao; vao = new QOpenGLVertexArrayObject(this); vao->create(); vao->bind(); glDeleteBuffers(1, &vertexBuffer); glGenBuffers(1, &vertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glDeleteBuffers(1, &uvBuffer); glGenBuffers(1, &uvBuffer); glBindBuffer(GL_ARRAY_BUFFER, uvBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(uvs), uvs, GL_STATIC_DRAW); glEnable(GL_TEXTURE_1D); glDeleteTextures(1, &audioLeftTexture); glGenTextures(1, &audioLeftTexture); glDeleteTextures(1, &audioRightTexture); glGenTextures(1, &audioRightTexture); glClearColor(0,0,.3,1); bool result = initShaders(fragmentSource); vao->release(); return result; } /** * @brief Renderer::initShaders * @param fragmentShader Code to compile as shader * @return True on success, otherwise false * * Initialze and compile the shader program */ bool Renderer::initShaders(const QString &fragmentShader){ QOpenGLShaderProgram *newShaderProgram = new QOpenGLShaderProgram(this); bool hasError = false; QString error = ""; if(!hasError && !newShaderProgram->addShaderFromSourceCode(QOpenGLShader::Vertex, defaultVertexShader)){ hasError = true; error = newShaderProgram->log(); qWarning() << tr("Failed to compile default shader."); } if(!hasError && !newShaderProgram->addShaderFromSourceCode(QOpenGLShader::Fragment,fragmentShader)){ hasError = true; error = newShaderProgram->log(); if(fragmentShader == defaultFragmentShader) qWarning() << tr("Failed to compile default shader."); else if(shaderProgram == 0) initShaders(defaultFragmentShader); } if(!hasError && !newShaderProgram->link()){ hasError = true; error = newShaderProgram->log(); if(fragmentShader == defaultFragmentShader) qWarning() << tr("Failed to compile default shader."); else if(shaderProgram == 0) initShaders(defaultFragmentShader); } if(hasError){ delete newShaderProgram; QRegExp errorline(":[0-9]+:"); errorline.indexIn(error); QString text = errorline.capturedTexts().at(0); text.replace(":", ""); if(text.toInt()-3 > 0) emit errored(error, text.toInt()-3); else emit errored(error, text.toInt()); return false; } shaderProgramMutex.lock(); if(shaderProgram) delete shaderProgram; shaderProgram = newShaderProgram; vertexAttr = shaderProgram->attributeLocation("position"); glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); shaderProgram->setAttributeBuffer(vertexAttr, GL_FLOAT, 0, 3); shaderProgram->enableAttributeArray(vertexAttr); uvAttr = shaderProgram->attributeLocation("texCoord"); glBindBuffer(GL_ARRAY_BUFFER, uvBuffer); shaderProgram->setAttributeBuffer("texCoord", GL_FLOAT, 0, 2); shaderProgram->enableAttributeArray(uvAttr); timeUniform = shaderProgram->uniformLocation("time"); mouseUniform = shaderProgram->uniformLocation("mouse"); rationUniform = shaderProgram->uniformLocation("ration"); fragmentSource = fragmentShader; shaderProgramMutex.unlock(); // qDebug() << "vertexAttr" << vertexAttr; // qDebug() << "uvAttr" << uvAttr; // qDebug() << "timeUniform" << timeUniform; // qDebug() << "audioUniform" << audioUniform; return true; } /** * @brief Renderer::render * * Initialize output device, execute the shader and display the result */ void Renderer::render(){ if(!device) device = new QOpenGLPaintDevice(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); device->setSize(size()); // qDebug() << QLatin1String(reinterpret_cast<const char*>(glGetString(GL_VERSION))) << " " << QLatin1String(reinterpret_cast<const char*>(glGetString(GL_SHADING_LANGUAGE_VERSION))); const qreal retinaScale = devicePixelRatio(); glViewport(0, 0, width() * retinaScale, height() * retinaScale); glClear(GL_COLOR_BUFFER_BIT); QPoint mouse = this->mapFromGlobal(QCursor::pos()); QVector2D mousePosition((float)mouse.x() / (float)this->width(), (float)mouse.y() / (float)this->height()); float ration = (float)this->width() / (float)this->height(); shaderProgramMutex.lock(); vao->bind(); shaderProgram->bind(); shaderProgram->setUniformValue(mouseUniform,mousePosition); if(this->height() != 0) shaderProgram->setUniformValue(rationUniform, ration); shaderProgram->setUniformValue(timeUniform, (float)time->elapsed()); glDrawArrays(GL_TRIANGLES, 0, 6); vao->release(); shaderProgramMutex.unlock(); } /** * @brief Renderer::renderLater * * Enqueue an update event to event queue */ void Renderer::renderLater(){ if(!pendingUpdate){ QCoreApplication::postEvent(this, new QEvent(QEvent::UpdateRequest)); pendingUpdate = true; } } /** * @brief Renderer::renderNow * * Use the compiled shader to render on the widget */ void Renderer::renderNow(){ pendingUpdate = false; if(!isExposed()) return; bool needsInit = false; if(!context){ context = new QOpenGLContext(this); context->setFormat(requestedFormat()); context->create(); needsInit = true; } context->makeCurrent(this); if(needsInit){ if (m_logger->initialize()){ m_logger->startLogging( QOpenGLDebugLogger::SynchronousLogging ); m_logger->enableMessages(); } initializeOpenGLFunctions(); init(); } if(!shaderProgram) initShaders(fragmentSource); if(shaderProgram) render(); context->swapBuffers(this); renderLater(); } /** * @brief Renderer::event * @param event The event that should be proccessed * @return True if the event was successful proccessed, otherwise false * * Called if a new event is poped from the event-queue to render on update event * and emit doneSignal on close event. */ bool Renderer::event(QEvent *event){ switch(event->type()){ case QEvent::UpdateRequest: QCoreApplication::postEvent(this, new QEvent(QEvent::UpdateRequest)); renderNow(); return true; case QEvent::Close: emit doneSignal(tr("User closed renderer")); return true; default: return QWindow::event(event); } } /** * @brief Renderer::exposeEvent * * Called if the window is ready to start rendering */ void Renderer::exposeEvent(QExposeEvent *){ if(isExposed()) renderNow(); } /** * @brief Renderer::updateCode * @param filename Text for the title * @param code New shader program code * @return True on success, otherwise false. * * Set new title and compile new code for the shader program */ bool Renderer::updateCode(const QString &filename, const QString &code){ if(!initShaders(code)) return false; setTitle(filename); show(); return true; } /** * @brief Renderer::updateAudioData * @param data New audio data * * Copy the new sound-data to the graphics memory for visualisation */ void Renderer::updateAudioData(QByteArray data){ if(!shaderProgram) return; GLenum type, internalType; Q_UNUSED(internalType); char typeSize; switch(audio->format().sampleType() + audio->format().sampleSize()){ case 8: case 10: type = GL_UNSIGNED_BYTE; internalType = GL_R8UI; typeSize = 1; break; case 9: type = GL_BYTE; internalType = GL_R8I; typeSize = 1; break; case 16: case 18: type = GL_UNSIGNED_SHORT; internalType = GL_R16UI; typeSize = 2; break; case 17: type = GL_SHORT; internalType = GL_R16I; typeSize = 2; break; case 32: case 34: type = GL_UNSIGNED_INT; internalType = GL_R32UI; typeSize = 4; break; case 33: type = GL_INT; internalType = GL_R32I; typeSize = 4; break; case 35: type = GL_FLOAT; internalType = GL_R32F; typeSize = 4; break; default: return; } char *left, *right; int count = data.size(); if(audio->format().channelCount() == 2){ count /= 2; left = new char[count]; right = new char[count]; for(int i = 0; i < count; i += typeSize){ for(int j = 0; j < typeSize; ++j){ left [i+j] = data[i*2+j]; right[i+j] = data[i*2+j+typeSize]; } } }else left = right = data.data(); shaderProgramMutex.lock(); shaderProgram->bind(); glBindTexture(GL_TEXTURE_1D, audioLeftTexture); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage1D(GL_TEXTURE_1D, 0, GL_R32F, count / typeSize, 0, GL_RED, type, left); glBindTexture(GL_TEXTURE_1D, audioRightTexture); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage1D(GL_TEXTURE_1D, 0, GL_R32F, count / typeSize, 0, GL_RED, type, right); shaderProgram->release(); shaderProgramMutex.unlock(); if(left != data.data()) delete[] left; if(right != data.data()) delete[] right; } /** * @brief Renderer::onMessageLogged * @param message Message text * * Write the message text in the debug output */ void Renderer::onMessageLogged(QOpenGLDebugMessage message){ qDebug() << message; } <|endoftext|>
<commit_before>/******************************************************************************/ // Mutex adaptors by Foster Brereton. // // Distributed under the MIT License. (See accompanying LICENSE.md or copy at // https://opensource.org/licenses/MIT) /******************************************************************************/ // stdc++ #include <cmath> #include <iostream> // application #include "analysis.hpp" /******************************************************************************/ void normal_analysis_header(std::ostream& s) { // make sure this routine accurately reflects the fields being output. s //<< "n," << "sig3 high," << "sig3 low," << "avg," << "min," << "max," << "stddev" << '\n' ; } /******************************************************************************/ std::ostream& operator<<(std::ostream& s, const normal_analysis_t& a) { auto sig3 = 3 * a.stddev_m; auto sig3low = a.avg_m - sig3; auto sig3high = a.avg_m + sig3; return s //<< a.count_m << ',' << sig3high << ',' << sig3low << ',' << a.avg_m << ',' << a.min_m << ',' << a.max_m << ',' << a.stddev_m ; } /******************************************************************************/ normal_analysis_t normal_analysis(const std::vector<double>& normal_data) { if (normal_data.empty()) throw std::runtime_error("data empty."); normal_analysis_t result; result.count_m = normal_data.size(); for (const auto& datum : normal_data) { if (datum < result.min_m) result.min_m = datum; if (datum > result.max_m) result.max_m = datum; result.avg_m += datum; } result.avg_m /= result.count_m; for (const auto& datum : normal_data) { double diff = datum - result.avg_m; result.stddev_m += diff * diff; } result.stddev_m /= result.count_m; result.stddev_m = std::sqrt(result.stddev_m); return result; } /******************************************************************************/ <commit_msg>compiler fix<commit_after>/******************************************************************************/ // Mutex adaptors by Foster Brereton. // // Distributed under the MIT License. (See accompanying LICENSE.md or copy at // https://opensource.org/licenses/MIT) /******************************************************************************/ // stdc++ #include <cmath> #include <iostream> #include <stdexcept> // application #include "analysis.hpp" /******************************************************************************/ void normal_analysis_header(std::ostream& s) { // make sure this routine accurately reflects the fields being output. s //<< "n," << "sig3 high," << "sig3 low," << "avg," << "min," << "max," << "stddev" << '\n' ; } /******************************************************************************/ std::ostream& operator<<(std::ostream& s, const normal_analysis_t& a) { auto sig3 = 3 * a.stddev_m; auto sig3low = a.avg_m - sig3; auto sig3high = a.avg_m + sig3; return s //<< a.count_m << ',' << sig3high << ',' << sig3low << ',' << a.avg_m << ',' << a.min_m << ',' << a.max_m << ',' << a.stddev_m ; } /******************************************************************************/ normal_analysis_t normal_analysis(const std::vector<double>& normal_data) { if (normal_data.empty()) throw std::runtime_error("data empty."); normal_analysis_t result; result.count_m = normal_data.size(); for (const auto& datum : normal_data) { if (datum < result.min_m) result.min_m = datum; if (datum > result.max_m) result.max_m = datum; result.avg_m += datum; } result.avg_m /= result.count_m; for (const auto& datum : normal_data) { double diff = datum - result.avg_m; result.stddev_m += diff * diff; } result.stddev_m /= result.count_m; result.stddev_m = std::sqrt(result.stddev_m); return result; } /******************************************************************************/ <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 * * (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH * * * * 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. * ******************************************************************************* * SOFA :: Applications * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #include <iostream> #include <sstream> #include <fstream> #include <sofa/helper/ArgumentParser.h> #include <sofa/helper/UnitTest.h> #include <sofa/helper/vector_algebra.h> #include <sofa/helper/vector.h> #include <sofa/helper/BackTrace.h> #include <sofa/helper/system/PluginManager.h> //#include <sofa/simulation/tree/TreeSimulation.h> //#include <sofa/simulation/bgl/BglSimulation.h> #include <sofa/simulation/graph/DAGSimulation.h> #include <sofa/simulation/common/Node.h> #include <sofa/simulation/common/xml/initXml.h> #include <sofa/gui/GUIManager.h> #include <sofa/gui/Main.h> #include <sofa/helper/system/FileRepository.h> #include <sofa/component/init.h> #include <sofa/component/mapping/SubsetMultiMapping.h> #include <sofa/component/topology/MeshTopology.h> #include <sofa/component/topology/EdgeSetTopologyContainer.h> #include <sofa/component/collision/SphereModel.h> #include <sofa/component/topology/CubeTopology.h> #include <sofa/component/visualmodel/VisualStyle.h> //Using double by default, if you have SOFA_FLOAT in use in you sofa-default.cfg, then it will be FLOAT. #include <sofa/component/typedef/Sofa_typedef.h> #include "../../../applications/tutorials/objectCreator/ObjectCreator.h" #include <plugins/Compliant/Compliant_lib/ComplianceSolver.h> #include <plugins/Compliant/Compliant_lib/UniformCompliance.h> #include <plugins/Compliant/Compliant_lib/CompliantAttachButtonSetting.h> using sofa::component::configurationsetting::CompliantAttachButtonSetting; #include <plugins/Flexible/deformationMapping/ExtensionMapping.h> #include <plugins/Flexible/deformationMapping/DistanceMapping.h> using namespace sofa; using namespace sofa::helper; using namespace sofa::simulation; using namespace sofa::core::objectmodel; using namespace sofa::component::container; using namespace sofa::component::topology; using namespace sofa::component::collision; using namespace sofa::component::visualmodel; using namespace sofa::component::mapping; using namespace sofa::component::forcefield; typedef SReal Scalar; typedef Vec<3,SReal> Vec3; typedef Vec<1,SReal> Vec1; typedef ExtensionMapping<MechanicalObject3::DataTypes, MechanicalObject1::DataTypes> ExtensionMapping31; typedef DistanceMapping<MechanicalObject3::DataTypes, MechanicalObject1::DataTypes> DistanceMapping31; typedef UniformCompliance<Vec1Types> UniformCompliance1; typedef component::odesolver::ComplianceSolver ComplianceSolver; bool startAnim = true; bool verbose = false; std::string simulationType = "bgl"; SReal complianceValue = 0.1; SReal dampingRatio = 0.1; Vec3 gravity(0,-1,0); SReal dt = 0.01; /// Create a string simulation::Node::SPtr createString(simulation::Node::SPtr parent, Vec3 startPoint, Vec3 endPoint, unsigned numParticles, double totalMass, double complianceValue=0, double dampingRatio=0 ) { static unsigned numObject = 1; std::ostringstream oss; oss << "string_" << numObject++; SReal totalLength = (endPoint-startPoint).norm(); //-------- Node::SPtr string_node = parent->createChild(oss.str()); MechanicalObject3::SPtr DOF = New<MechanicalObject3>(); string_node->addObject(DOF); DOF->setName(oss.str()+"_DOF"); UniformMass3::SPtr mass = New<UniformMass3>(); string_node->addObject(mass); mass->setName(oss.str()+"_mass"); mass->mass.setValue( totalMass/numParticles ); //-------- Node::SPtr extension_node = string_node->createChild( oss.str()+"_ExtensionNode"); MechanicalObject1::SPtr extensions = New<MechanicalObject1>(); extension_node->addObject(extensions); EdgeSetTopologyContainer::SPtr edgeSet = New<EdgeSetTopologyContainer>(); extension_node->addObject(edgeSet); ExtensionMapping31::SPtr extensionMapping = New<ExtensionMapping31>(); extensionMapping->setModels(DOF.get(),extensions.get()); extension_node->addObject( extensionMapping ); extensionMapping->setName(oss.str()+"_ExtensionMapping"); extensionMapping->setModels( DOF.get(), extensions.get() ); UniformCompliance1::SPtr compliance = New<UniformCompliance1>(); extension_node->addObject(compliance); compliance->setName(oss.str()+"_compliance"); compliance->compliance.setValue(complianceValue); compliance->dampingRatio.setValue(dampingRatio); //-------- // create the particles DOF->resize(numParticles); MechanicalObject3::WriteVecCoord x = DOF->writePositions(); helper::vector<SReal> restLengths; for( unsigned i=0; i<numParticles; i++ ) { double alpha = (double)i/(numParticles-1); x[i] = startPoint * (1-alpha) + endPoint * alpha; if(i>0) { edgeSet->addEdge(i-1,i); restLengths.push_back( totalLength/(numParticles-1) ); } } extensionMapping->f_restLengths.setValue( restLengths ); // { // //-------- fix a particle // Node::SPtr fixNode = string_node->createChild("fixNode"); // MechanicalObject1::SPtr extensions = New<MechanicalObject1>(); // fixNode->addObject(extensions); // DistanceMapping31::SPtr distanceMapping = New<DistanceMapping31>(); // distanceMapping->setModels(DOF.get(),extensions.get()); // fixNode->addObject( distanceMapping ); // distanceMapping->setName("fix_distanceMapping"); // distanceMapping->setModels( DOF.get(), extensions.get() ); // distanceMapping->createTarget( numParticles-1, endPoint, 0.0 ); // UniformCompliance1::SPtr compliance = New<UniformCompliance1>(); // fixNode->addObject(compliance); // compliance->setName("fix_compliance"); // compliance->compliance.setValue(complianceValue); // compliance->dampingRatio.setValue(dampingRatio); // } return string_node; } /// Create the scene simulation::Node::SPtr createScene() { // The graph root node Node::SPtr root = simulation::getSimulation()->createNewGraph("root"); root->setGravity( Coord3(0,-1,0) ); root->setAnimate(false); root->setDt(0.01); addVisualStyle(root)->setShowVisual(false).setShowCollision(false).setShowMapping(true).setShowBehavior(true); // CompliantAttachButtonSetting::SPtr buttonSetting = New<CompliantAttachButtonSetting>(); // root->addObject(buttonSetting); // sofa::helper::OptionsGroup b=buttonSetting->button.getValue(); // b.setSelectedItem("Left"); // buttonSetting->button.setValue(b); Node::SPtr simulatedScene = root->createChild("simulatedScene"); ComplianceSolver::SPtr complianceSolver = New<ComplianceSolver>(); simulatedScene->addObject( complianceSolver ); complianceSolver->implicitVelocity.setValue(1.0); complianceSolver->implicitPosition.setValue(1.0); complianceSolver->verbose.setValue(verbose); // ======== first string unsigned n1 = 2; Node::SPtr string1 = createString( simulatedScene, Vec3(0,0,0), Vec3(1,0,0), n1, 1.0*n1, complianceValue, dampingRatio ); FixedConstraint3::SPtr fixed1 = New<FixedConstraint3>(); string1->addObject( fixed1 ); // ======== second string unsigned n2 = 2; Node::SPtr string2 = createString( simulatedScene, Vec3(3,0,0), Vec3(2,0,0), n2, 2.0, complianceValue, dampingRatio ); FixedConstraint3::SPtr fixed2 = New<FixedConstraint3>(); string2->addObject( fixed2 ); // ======== Node with multiple parents to create an interaction using a MultiMapping Node::SPtr commonChild = string1->createChild("commonChild"); string2->addChild(commonChild); MechanicalObject3::SPtr mappedDOF = New<MechanicalObject3>(); // to contain particles from the two strings commonChild->addObject(mappedDOF); SubsetMultiMapping3_to_3::SPtr multimapping = New<SubsetMultiMapping3_to_3>(); multimapping->setName("InteractionMultiMapping"); multimapping->addInputModel( string1->getMechanicalState() ); multimapping->addInputModel( string2->getMechanicalState() ); multimapping->addOutputModel( mappedDOF.get() ); multimapping->addPoint( string1->getMechanicalState(), n1-1 ); multimapping->addPoint( string2->getMechanicalState(), n2-1 ); commonChild->addObject(multimapping); // Node to handle the extension of the interaction link Node::SPtr extension_node = commonChild->createChild("InteractionExtensionNode"); MechanicalObject1::SPtr extensions = New<MechanicalObject1>(); extension_node->addObject(extensions); EdgeSetTopologyContainer::SPtr edgeSet = New<EdgeSetTopologyContainer>(); extension_node->addObject(edgeSet); edgeSet->addEdge(0,1); ExtensionMapping31::SPtr extensionMapping = New<ExtensionMapping31>(); extensionMapping->setModels(mappedDOF.get(),extensions.get()); extension_node->addObject( extensionMapping ); extensionMapping->setName("InteractionExtension_mapping"); UniformCompliance1::SPtr compliance = New<UniformCompliance1>(); extension_node->addObject(compliance); compliance->compliance.setName("connectionCompliance"); compliance->compliance.setValue(complianceValue); compliance->dampingRatio.setValue(dampingRatio); return root; } int main(int argc, char** argv) { sofa::helper::BackTrace::autodump(); sofa::core::ExecParams::defaultInstance()->setAspectID(0); sofa::helper::parse("This is a SOFA application. Here are the command line arguments") .option(&startAnim,'a',"start","start the animation loop") .option(&simulationType,'s',"simu","select the type of simulation (bgl, tree)") .option(&verbose,'v',"verbose","print debug info") (argc,argv); glutInit(&argc,argv); //#ifdef SOFA_DEV // if (simulationType == "bgl") // sofa::simulation::setSimulation(new sofa::simulation::bgl::BglSimulation()); // else //#endif // sofa::simulation::setSimulation(new sofa::simulation::tree::TreeSimulation()); sofa::simulation::setSimulation(new sofa::simulation::graph::DAGSimulation()); sofa::component::init(); #ifdef SOFA_GPU_CUDA #ifdef WIN32 #ifdef NDEBUG std::string name("sofagpucuda_1_0.dll"); #else std::string name("sofagpucuda_1_0d.dll"); #endif sofa::helper::system::DynamicLibrary::load(name); #endif #endif sofa::gui::initMain(); if (int err = sofa::gui::GUIManager::Init(argv[0],"")) return err; if (int err=sofa::gui::GUIManager::createGUI(NULL)) return err; sofa::gui::GUIManager::SetDimension(800,600); //================================================= sofa::simulation::Node::SPtr groot = createScene(); //================================================= sofa::simulation::getSimulation()->init(groot.get()); sofa::gui::GUIManager::SetScene(groot); // Run the main loop if (int err = sofa::gui::GUIManager::MainLoop(groot)) return err; sofa::simulation::getSimulation()->unload(groot); sofa::gui::GUIManager::closeGUI(); return 0; } <commit_msg>r8759/sofa : ADD a stiff scene equivalent with the compliant scene in Compliant_run<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 * * (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH * * * * 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. * ******************************************************************************* * SOFA :: Applications * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #include <iostream> #include <sstream> #include <fstream> #include <sofa/helper/ArgumentParser.h> #include <sofa/helper/UnitTest.h> #include <sofa/helper/vector_algebra.h> #include <sofa/helper/vector.h> #include <sofa/helper/BackTrace.h> #include <sofa/helper/system/PluginManager.h> //#include <sofa/simulation/tree/TreeSimulation.h> //#include <sofa/simulation/bgl/BglSimulation.h> #include <sofa/simulation/graph/DAGSimulation.h> #include <sofa/simulation/common/Node.h> #include <sofa/simulation/common/xml/initXml.h> #include <sofa/gui/GUIManager.h> #include <sofa/gui/Main.h> #include <sofa/helper/system/FileRepository.h> #include <sofa/component/init.h> #include <sofa/component/mapping/SubsetMultiMapping.h> #include <sofa/component/topology/MeshTopology.h> #include <sofa/component/topology/EdgeSetTopologyContainer.h> #include <sofa/component/collision/SphereModel.h> #include <sofa/component/topology/CubeTopology.h> #include <sofa/component/visualmodel/VisualStyle.h> #include <sofa/component/odesolver/EulerImplicitSolver.h> #include <sofa/component/linearsolver/CGLinearSolver.h> //Using double by default, if you have SOFA_FLOAT in use in you sofa-default.cfg, then it will be FLOAT. #include <sofa/component/typedef/Sofa_typedef.h> #include "../../../applications/tutorials/objectCreator/ObjectCreator.h" #include <plugins/Compliant/Compliant_lib/ComplianceSolver.h> #include <plugins/Compliant/Compliant_lib/UniformCompliance.h> #include <plugins/Compliant/Compliant_lib/CompliantAttachButtonSetting.h> using sofa::component::configurationsetting::CompliantAttachButtonSetting; #include <plugins/Flexible/deformationMapping/ExtensionMapping.h> #include <plugins/Flexible/deformationMapping/DistanceMapping.h> using namespace sofa; using namespace sofa::helper; using namespace sofa::simulation; using namespace sofa::core::objectmodel; using namespace sofa::component::container; using namespace sofa::component::topology; using namespace sofa::component::collision; using namespace sofa::component::visualmodel; using namespace sofa::component::mapping; using namespace sofa::component::forcefield; typedef SReal Scalar; typedef Vec<3,SReal> Vec3; typedef Vec<1,SReal> Vec1; typedef ExtensionMapping<MechanicalObject3::DataTypes, MechanicalObject1::DataTypes> ExtensionMapping31; typedef DistanceMapping<MechanicalObject3::DataTypes, MechanicalObject1::DataTypes> DistanceMapping31; typedef UniformCompliance<Vec1Types> UniformCompliance1; typedef component::odesolver::ComplianceSolver ComplianceSolver; typedef component::odesolver::EulerImplicitSolver EulerImplicitSolver; typedef component::linearsolver::CGLinearSolver<component::linearsolver::GraphScatteredMatrix, component::linearsolver::GraphScatteredVector> CGLinearSolver; bool startAnim = true; bool verbose = false; std::string simulationType = "bgl"; SReal complianceValue = 0.1; SReal dampingRatio = 0.1; Vec3 gravity(0,-1,0); SReal dt = 0.01; /// Create a compliant string simulation::Node::SPtr createCompliantString(simulation::Node::SPtr parent, Vec3 startPoint, Vec3 endPoint, unsigned numParticles, double totalMass, double complianceValue=0, double dampingRatio=0 ) { static unsigned numObject = 1; std::ostringstream oss; oss << "string_" << numObject++; SReal totalLength = (endPoint-startPoint).norm(); //-------- Node::SPtr string_node = parent->createChild(oss.str()); MechanicalObject3::SPtr DOF = New<MechanicalObject3>(); string_node->addObject(DOF); DOF->setName(oss.str()+"_DOF"); UniformMass3::SPtr mass = New<UniformMass3>(); string_node->addObject(mass); mass->setName(oss.str()+"_mass"); mass->mass.setValue( totalMass/numParticles ); //-------- Node::SPtr extension_node = string_node->createChild( oss.str()+"_ExtensionNode"); MechanicalObject1::SPtr extensions = New<MechanicalObject1>(); extension_node->addObject(extensions); EdgeSetTopologyContainer::SPtr edgeSet = New<EdgeSetTopologyContainer>(); extension_node->addObject(edgeSet); ExtensionMapping31::SPtr extensionMapping = New<ExtensionMapping31>(); extensionMapping->setModels(DOF.get(),extensions.get()); extension_node->addObject( extensionMapping ); extensionMapping->setName(oss.str()+"_ExtensionMapping"); extensionMapping->setModels( DOF.get(), extensions.get() ); UniformCompliance1::SPtr compliance = New<UniformCompliance1>(); extension_node->addObject(compliance); compliance->setName(oss.str()+"_compliance"); compliance->compliance.setValue(complianceValue); compliance->dampingRatio.setValue(dampingRatio); //-------- // create the particles DOF->resize(numParticles); MechanicalObject3::WriteVecCoord x = DOF->writePositions(); helper::vector<SReal> restLengths; for( unsigned i=0; i<numParticles; i++ ) { double alpha = (double)i/(numParticles-1); x[i] = startPoint * (1-alpha) + endPoint * alpha; if(i>0) { edgeSet->addEdge(i-1,i); restLengths.push_back( totalLength/(numParticles-1) ); } } extensionMapping->f_restLengths.setValue( restLengths ); // { // //-------- fix a particle // Node::SPtr fixNode = string_node->createChild("fixNode"); // MechanicalObject1::SPtr extensions = New<MechanicalObject1>(); // fixNode->addObject(extensions); // DistanceMapping31::SPtr distanceMapping = New<DistanceMapping31>(); // distanceMapping->setModels(DOF.get(),extensions.get()); // fixNode->addObject( distanceMapping ); // distanceMapping->setName("fix_distanceMapping"); // distanceMapping->setModels( DOF.get(), extensions.get() ); // distanceMapping->createTarget( numParticles-1, endPoint, 0.0 ); // UniformCompliance1::SPtr compliance = New<UniformCompliance1>(); // fixNode->addObject(compliance); // compliance->setName("fix_compliance"); // compliance->compliance.setValue(complianceValue); // compliance->dampingRatio.setValue(dampingRatio); // } return string_node; } /// Create the compliant string composed of three parts simulation::Node::SPtr createCompliantScene() { // The graph root node Node::SPtr root = simulation::getSimulation()->createNewGraph("root"); root->setGravity( Coord3(0,-1,0) ); root->setAnimate(false); root->setDt(0.01); addVisualStyle(root)->setShowVisual(false).setShowCollision(false).setShowMapping(true).setShowBehavior(true); // CompliantAttachButtonSetting::SPtr buttonSetting = New<CompliantAttachButtonSetting>(); // root->addObject(buttonSetting); // sofa::helper::OptionsGroup b=buttonSetting->button.getValue(); // b.setSelectedItem("Left"); // buttonSetting->button.setValue(b); Node::SPtr simulatedScene = root->createChild("simulatedScene"); ComplianceSolver::SPtr complianceSolver = New<ComplianceSolver>(); simulatedScene->addObject( complianceSolver ); complianceSolver->implicitVelocity.setValue(1.0); complianceSolver->implicitPosition.setValue(1.0); complianceSolver->verbose.setValue(verbose); // ======== first string unsigned n1 = 2; Node::SPtr string1 = createCompliantString( simulatedScene, Vec3(0,0,0), Vec3(1,0,0), n1, 1.0*n1, complianceValue, dampingRatio ); FixedConstraint3::SPtr fixed1 = New<FixedConstraint3>(); string1->addObject( fixed1 ); // ======== second string unsigned n2 = 2; Node::SPtr string2 = createCompliantString( simulatedScene, Vec3(3,0,0), Vec3(2,0,0), n2, 1.0*n2, complianceValue, dampingRatio ); FixedConstraint3::SPtr fixed2 = New<FixedConstraint3>(); string2->addObject( fixed2 ); // ======== Node with multiple parents to create an interaction using a MultiMapping Node::SPtr commonChild = string1->createChild("commonChild"); string2->addChild(commonChild); MechanicalObject3::SPtr mappedDOF = New<MechanicalObject3>(); // to contain particles from the two strings commonChild->addObject(mappedDOF); SubsetMultiMapping3_to_3::SPtr multimapping = New<SubsetMultiMapping3_to_3>(); multimapping->setName("InteractionMultiMapping"); multimapping->addInputModel( string1->getMechanicalState() ); multimapping->addInputModel( string2->getMechanicalState() ); multimapping->addOutputModel( mappedDOF.get() ); multimapping->addPoint( string1->getMechanicalState(), n1-1 ); multimapping->addPoint( string2->getMechanicalState(), n2-1 ); commonChild->addObject(multimapping); // Node to handle the extension of the interaction link Node::SPtr extension_node = commonChild->createChild("InteractionExtensionNode"); MechanicalObject1::SPtr extensions = New<MechanicalObject1>(); extension_node->addObject(extensions); EdgeSetTopologyContainer::SPtr edgeSet = New<EdgeSetTopologyContainer>(); extension_node->addObject(edgeSet); edgeSet->addEdge(0,1); ExtensionMapping31::SPtr extensionMapping = New<ExtensionMapping31>(); extensionMapping->setModels(mappedDOF.get(),extensions.get()); extension_node->addObject( extensionMapping ); extensionMapping->setName("InteractionExtension_mapping"); UniformCompliance1::SPtr compliance = New<UniformCompliance1>(); extension_node->addObject(compliance); compliance->compliance.setName("connectionCompliance"); compliance->compliance.setValue(complianceValue); compliance->dampingRatio.setValue(dampingRatio); return root; } /// Create a stiff string simulation::Node::SPtr createStiffString(simulation::Node::SPtr parent, Vec3 startPoint, Vec3 endPoint, unsigned numParticles, double totalMass, double stiffnessValue=1.0, double dampingRatio=0 ) { static unsigned numObject = 1; std::ostringstream oss; oss << "string_" << numObject++; SReal totalLength = (endPoint-startPoint).norm(); //-------- Node::SPtr string_node = parent->createChild(oss.str()); MechanicalObject3::SPtr DOF = New<MechanicalObject3>(); string_node->addObject(DOF); DOF->setName(oss.str()+"_DOF"); UniformMass3::SPtr mass = New<UniformMass3>(); string_node->addObject(mass); mass->setName(oss.str()+"_mass"); mass->mass.setValue( totalMass/numParticles ); StiffSpringForceField3::SPtr spring = New<StiffSpringForceField3>(); string_node->addObject(spring); spring->setName(oss.str()+"_spring"); //-------- // create the particles and the springs DOF->resize(numParticles); MechanicalObject3::WriteVecCoord x = DOF->writePositions(); for( unsigned i=0; i<numParticles; i++ ) { double alpha = (double)i/(numParticles-1); x[i] = startPoint * (1-alpha) + endPoint * alpha; if(i>0) { spring->addSpring(i-1,i,stiffnessValue,dampingRatio,totalLength/(numParticles-1)); } } return string_node; } /// Create the stiff string composed of three parts simulation::Node::SPtr createStiffScene() { // The graph root node Node::SPtr root = simulation::getSimulation()->createNewGraph("root"); root->setGravity( Coord3(0,-1,0) ); root->setAnimate(false); root->setDt(0.01); addVisualStyle(root)->setShowVisual(false).setShowCollision(false).setShowMapping(true).setShowBehavior(true); Node::SPtr simulatedScene = root->createChild("simulatedScene"); EulerImplicitSolver::SPtr eulerImplicitSolver = New<EulerImplicitSolver>(); simulatedScene->addObject( eulerImplicitSolver ); CGLinearSolver::SPtr cgLinearSolver = New<CGLinearSolver>(); simulatedScene->addObject(cgLinearSolver); // ======== first string unsigned n1 = 3; Node::SPtr string1 = createStiffString( simulatedScene, Vec3(0,0,0), Vec3(1,0,0), n1, 1.0*n1, 1/complianceValue, dampingRatio ); FixedConstraint3::SPtr fixed1 = New<FixedConstraint3>(); string1->addObject( fixed1 ); // ======== second string unsigned n2 = 3; Node::SPtr string2 = createStiffString( simulatedScene, Vec3(3,0,0), Vec3(2,0,0), n2, 1.0*n2, 1/complianceValue, dampingRatio ); FixedConstraint3::SPtr fixed2 = New<FixedConstraint3>(); string2->addObject( fixed2 ); // ======== Node with multiple parents to create an interaction using a MultiMapping Node::SPtr commonChild = string1->createChild("commonChild"); string2->addChild(commonChild); MechanicalObject3::SPtr mappedDOF = New<MechanicalObject3>(); // to contain particles from the two strings commonChild->addObject(mappedDOF); SubsetMultiMapping3_to_3::SPtr multimapping = New<SubsetMultiMapping3_to_3>(); multimapping->setName("InteractionMultiMapping"); multimapping->addInputModel( string1->getMechanicalState() ); multimapping->addInputModel( string2->getMechanicalState() ); multimapping->addOutputModel( mappedDOF.get() ); multimapping->addPoint( string1->getMechanicalState(), n1-1 ); multimapping->addPoint( string2->getMechanicalState(), n2-1 ); commonChild->addObject(multimapping); StiffSpringForceField3::SPtr spring = New<StiffSpringForceField3>(); commonChild->addObject(spring); spring->setName("InteractionSpring"); spring->addSpring(0,1,1/complianceValue,dampingRatio,1.0); return root; } int main(int argc, char** argv) { sofa::helper::BackTrace::autodump(); sofa::core::ExecParams::defaultInstance()->setAspectID(0); sofa::helper::parse("This is a SOFA application. Here are the command line arguments") .option(&startAnim,'a',"start","start the animation loop") .option(&simulationType,'s',"simu","select the type of simulation (bgl, tree)") .option(&verbose,'v',"verbose","print debug info") (argc,argv); glutInit(&argc,argv); //#ifdef SOFA_DEV // if (simulationType == "bgl") // sofa::simulation::setSimulation(new sofa::simulation::bgl::BglSimulation()); // else //#endif // sofa::simulation::setSimulation(new sofa::simulation::tree::TreeSimulation()); sofa::simulation::setSimulation(new sofa::simulation::graph::DAGSimulation()); sofa::component::init(); #ifdef SOFA_GPU_CUDA #ifdef WIN32 #ifdef NDEBUG std::string name("sofagpucuda_1_0.dll"); #else std::string name("sofagpucuda_1_0d.dll"); #endif sofa::helper::system::DynamicLibrary::load(name); #endif #endif sofa::gui::initMain(); if (int err = sofa::gui::GUIManager::Init(argv[0],"")) return err; if (int err=sofa::gui::GUIManager::createGUI(NULL)) return err; sofa::gui::GUIManager::SetDimension(800,600); //================================================= sofa::simulation::Node::SPtr groot = createStiffScene(); // sofa::simulation::Node::SPtr groot = createCompliantScene(); //================================================= sofa::simulation::getSimulation()->init(groot.get()); sofa::gui::GUIManager::SetScene(groot); // Run the main loop if (int err = sofa::gui::GUIManager::MainLoop(groot)) return err; sofa::simulation::getSimulation()->unload(groot); sofa::gui::GUIManager::closeGUI(); return 0; } <|endoftext|>
<commit_before>#include "dataflash_logger.h" #include <signal.h> #include <stdio.h> // for snprintf #include <fcntl.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> #include "la-log.h" #include "util.h" #include "mavlink_c_library/common/mavlink.h" void DataFlash_Logger::sighup_received() { logging_stop(); } void DataFlash_Logger::idle_tenthHz() { // the following isn't quite right given we seek around... if (logging_started) { la_log(LOG_DEBUG, "mh-dfl: Current log size: %lu", lseek(out_fd, 0, SEEK_CUR)); } } void DataFlash_Logger::idle_1Hz() { if (!logging_started) { if (sender_system_id != 0) { // we've previously been logging, so telling the other end // to stop logging may let us restart logging sooner send_stop_logging_packet(); } send_start_logging_packet(); } } void DataFlash_Logger::idle_10Hz() { if (logging_started) { // if no data packet in 10 seconds then close log uint64_t now_us = clock_gettime_us(CLOCK_MONOTONIC); if (now_us - _last_data_packet_time > 10000000) { la_log(LOG_INFO, "mh-dfl: No data packets received for some time (now=%llu last=%llu). Closing log. Final log size: %lu", now_us,_last_data_packet_time, lseek(out_fd, 0, SEEK_CUR)); logging_stop(); } } } void DataFlash_Logger::idle_100Hz() { push_response_queue(); } void DataFlash_Logger::send_response(uint32_t seqno, bool status) { mavlink_message_t msg; mavlink_msg_remote_log_block_status_pack(this_system_id, this_component_id, &msg, sender_system_id, sender_component_id, seqno, status); _mavlink_writer->send_message(msg); } void DataFlash_Logger::push_response_queue() { const uint8_t max_packets_to_send = 5; uint8_t packets_sent = 0; while (response_queue_head != response_queue_tail && packets_sent < max_packets_to_send) { send_response(responses[response_queue_tail].seqno, responses[response_queue_tail].status); response_queue_tail++; if (response_queue_tail >= RESPONSE_QUEUE_LENGTH) { response_queue_tail = 0; } } } bool DataFlash_Logger::configure(INIReader *config) { if (!MAVLink_Message_Handler::configure(config)) { return false; } std::string path = config->Get("dflogger", "log_dirpath", "/log/dataflash"); _log_directory_path = strdup(path.c_str()); if (_log_directory_path == NULL) { return false; } this_system_id = config->GetInteger("dflogger", "source_system_id", this_system_id); this_component_id = config->GetInteger("dflogger", "source_component_id", this_component_id); target_system_id = config->GetInteger("dflogger", "target_system_id", target_system_id); target_component_id = config->GetInteger("dflogger", "target_component_id", target_component_id); return true; } bool DataFlash_Logger::make_new_log_filename(char *buffer, uint8_t bufferlen) { uint8_t lastlog_buflen = 128; char lastlog_buf[128]; // this was really beautiful, but I don't think SoloLink has an // RTC; it depends on GPS to update its clock (scribbled down // periodically?) // time_t t; // time(&t); // struct tm *timebits = gmtime(&t); // snprintf(buffer, bufferlen, "%s/%04d%02d%02d%02d%02d%02d.BIN", // _log_directory_path, // timebits->tm_year+1900, // timebits->tm_mon+1, // timebits->tm_mday, // timebits->tm_hour, // timebits->tm_min, // timebits->tm_sec); memset(lastlog_buf, '\0', lastlog_buflen); snprintf(lastlog_buf, lastlog_buflen, "%s/LASTLOG.TXT", _log_directory_path); int fd; uint32_t num; if ((fd = open(lastlog_buf, O_RDONLY)) == -1) { if (errno != ENOENT) { // what? la_log(LOG_ERR, "Failed to open (%s) for reading: %s", lastlog_buf, strerror(errno)); return false; } num = 1; } else { const uint8_t numbuf_len = 128; char numbuf[numbuf_len]; memset(numbuf, '\0', numbuf_len); int bytes_read = read(fd, numbuf, numbuf_len); close(fd); if (bytes_read == -1) { return false; } num = strtoul(numbuf, NULL, 10); num++; } if ((fd = open(lastlog_buf, O_WRONLY|O_TRUNC|O_CREAT, 0777)) == -1) { // *shrug* We will continue to overwrite, I guess... la_log(LOG_ERR, "mh-dfl: failed to open (%s): %s", lastlog_buf, strerror(errno)); } else { const uint8_t outsize = 16; char out[outsize]; memset(out, '\0', outsize); int towrite = snprintf(out, outsize, "%d\r\n", num); if (write(fd, out, towrite) != towrite) { la_log(LOG_ERR, "mh-dfl: failed to write to (%s): %s", lastlog_buf, strerror(errno)); } close(fd); } snprintf(buffer, bufferlen, "%s/%d.BIN", _log_directory_path, num); return true; } bool DataFlash_Logger::output_file_open() { const uint8_t filename_length = 64; char filename[filename_length]; if (!make_new_log_filename(filename, filename_length)) { return false; } out_fd = open(filename, O_WRONLY|O_CREAT|O_TRUNC, 0777); if (out_fd == -1) { printf("Failed to open (%s): %s\n", filename, strerror(errno)); la_log(LOG_ERR, "Failed to open (%s): %s", filename, strerror(errno)); return false; } la_log(LOG_INFO, "Opened log file (%s)", filename); return true; } void DataFlash_Logger::output_file_close() { close(out_fd); } void DataFlash_Logger::queue_response(uint32_t seqno, bool status) { responses[response_queue_head].seqno = seqno; responses[response_queue_head].status = status; response_queue_head++; if (response_queue_head >= RESPONSE_QUEUE_LENGTH) { response_queue_head = 0; } } void DataFlash_Logger::queue_ack(uint32_t seqno) { queue_response(seqno, true); } void DataFlash_Logger::queue_nack(uint32_t seqno) { queue_response(seqno, false); } void DataFlash_Logger::queue_gap_nacks(uint32_t seqno) { if (seqno <= highest_seqno_seen) { // this packet filled in a gap (or was a dupe) return; } if (seqno - highest_seqno_seen > seqno_gap_nack_threshold) { // we've seen some serious disruption, and lots of stuff // is probably going to be lost. Do not bother NACKing // packets here and let the server sort things out return; } for (uint32_t i=highest_seqno_seen+1; i<seqno; i++) { queue_nack(i); } } bool DataFlash_Logger::logging_start(mavlink_message_t &m, mavlink_remote_log_data_block_t &msg UNUSED) { sender_system_id = m.sysid; sender_component_id = m.compid; sender_arm_status = ARM_STATUS_UNKNOWN; la_log_unsuppress(); la_log(LOG_INFO, "mh-dfl: Starting log, target is (%d/%d), I am (%d/%d)", sender_system_id, sender_component_id, this_system_id, this_component_id); if (!output_file_open()) { return false; } logging_started = true; return true; } void DataFlash_Logger::logging_stop() { output_file_close(); logging_started = false; } void DataFlash_Logger::handle_decoded_message(uint64_t T, mavlink_message_t &m, mavlink_heartbeat_t &msg) { if (m.sysid == sender_system_id && m.compid == sender_component_id) { arm_status_t new_sender_arm_status = (msg.base_mode & MAV_MODE_FLAG_SAFETY_ARMED) ? ARM_STATUS_ARMED : ARM_STATUS_DISARMED; if (logging_started) { if (sender_arm_status == ARM_STATUS_ARMED && new_sender_arm_status == ARM_STATUS_DISARMED) { // sender has moved from armed to disarmed state; stop // logging and let it restart naturally la_log(LOG_INFO, "mh-dfl: disarm detected, logging_stop"); logging_stop(); } } else { la_log(LOG_INFO, "Heartbeat received from %u/%u", m.sysid, m.compid); } sender_arm_status = new_sender_arm_status; } MAVLink_Message_Handler::handle_decoded_message(T, m, msg); } void DataFlash_Logger::handle_decoded_message(uint64_t T UNUSED, mavlink_message_t &m, mavlink_remote_log_data_block_t &msg) { if (!logging_started) { if (msg.seqno == 0) { if (!logging_start(m, msg)) { return; } } else { return; } } // we could move this down to the end; that wold mean short-writes // would end up closing this log... _last_data_packet_time = clock_gettime_us(CLOCK_MONOTONIC); const uint8_t length = MAVLINK_MSG_REMOTE_LOG_DATA_BLOCK_FIELD_DATA_LEN; /* send the dataflash data out to the log file */ lseek(out_fd, msg.seqno*MAVLINK_MSG_REMOTE_LOG_DATA_BLOCK_FIELD_DATA_LEN, SEEK_SET); if (write(out_fd, msg.data, length) < length) { la_log(LOG_ERR, "Short write: %s", strerror(errno)); // we'll get the block again... maybe we'll have better luck next time.. return; } // queue an ack for this packet queue_ack(msg.seqno); // queue nacks for gaps queue_gap_nacks(msg.seqno); if (msg.seqno > highest_seqno_seen) { if (msg.seqno - highest_seqno_seen > 100) { la_log(LOG_ERR, "large seqno gap: %ld", msg.seqno - highest_seqno_seen); } highest_seqno_seen = msg.seqno; } } void DataFlash_Logger::send_start_logging_packet() { send_start_or_stop_logging_packet(true); } void DataFlash_Logger::send_stop_logging_packet() { send_start_or_stop_logging_packet(false); } void DataFlash_Logger::send_start_or_stop_logging_packet(bool is_start) { mavlink_message_t msg; uint8_t system_id = is_start ? target_system_id : sender_system_id; uint8_t component_id = is_start ? target_component_id : sender_component_id; uint32_t magic_number; if (is_start) { la_log(LOG_INFO, "mh-dfl: sending start packet to (%d/%d)", system_id,component_id); magic_number = MAV_REMOTE_LOG_DATA_BLOCK_START; } else { la_log(LOG_INFO, "mh-dfl: sending stop packet to (%d/%d)", system_id,component_id); magic_number = MAV_REMOTE_LOG_DATA_BLOCK_STOP; } mavlink_msg_remote_log_block_status_pack (this_system_id, this_component_id, &msg, system_id, component_id, magic_number, 1); _mavlink_writer->send_message(msg); } <commit_msg>Fixed issue with detection of flight controller disarm events.<commit_after>#include "dataflash_logger.h" #include <signal.h> #include <stdio.h> // for snprintf #include <fcntl.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> #include "la-log.h" #include "util.h" #include "mavlink_c_library/common/mavlink.h" void DataFlash_Logger::sighup_received() { logging_stop(); } void DataFlash_Logger::idle_tenthHz() { // the following isn't quite right given we seek around... if (logging_started) { la_log(LOG_DEBUG, "mh-dfl: Current log size: %lu", lseek(out_fd, 0, SEEK_CUR)); } } void DataFlash_Logger::idle_1Hz() { if (!logging_started) { if (sender_system_id != 0) { // we've previously been logging, so telling the other end // to stop logging may let us restart logging sooner send_stop_logging_packet(); } send_start_logging_packet(); } } void DataFlash_Logger::idle_10Hz() { if (logging_started) { // if no data packet in 10 seconds then close log uint64_t now_us = clock_gettime_us(CLOCK_MONOTONIC); if (now_us - _last_data_packet_time > 10000000) { la_log(LOG_INFO, "mh-dfl: No data packets received for some time (now=%llu last=%llu). Closing log. Final log size: %lu", now_us,_last_data_packet_time, lseek(out_fd, 0, SEEK_CUR)); logging_stop(); } } } void DataFlash_Logger::idle_100Hz() { push_response_queue(); } void DataFlash_Logger::send_response(uint32_t seqno, bool status) { mavlink_message_t msg; mavlink_msg_remote_log_block_status_pack(this_system_id, this_component_id, &msg, sender_system_id, sender_component_id, seqno, status); _mavlink_writer->send_message(msg); } void DataFlash_Logger::push_response_queue() { const uint8_t max_packets_to_send = 5; uint8_t packets_sent = 0; while (response_queue_head != response_queue_tail && packets_sent < max_packets_to_send) { send_response(responses[response_queue_tail].seqno, responses[response_queue_tail].status); response_queue_tail++; if (response_queue_tail >= RESPONSE_QUEUE_LENGTH) { response_queue_tail = 0; } } } bool DataFlash_Logger::configure(INIReader *config) { if (!MAVLink_Message_Handler::configure(config)) { return false; } std::string path = config->Get("dflogger", "log_dirpath", "/log/dataflash"); _log_directory_path = strdup(path.c_str()); if (_log_directory_path == NULL) { return false; } this_system_id = config->GetInteger("dflogger", "source_system_id", this_system_id); this_component_id = config->GetInteger("dflogger", "source_component_id", this_component_id); target_system_id = config->GetInteger("dflogger", "target_system_id", target_system_id); target_component_id = config->GetInteger("dflogger", "target_component_id", target_component_id); return true; } bool DataFlash_Logger::make_new_log_filename(char *buffer, uint8_t bufferlen) { uint8_t lastlog_buflen = 128; char lastlog_buf[128]; // this was really beautiful, but I don't think SoloLink has an // RTC; it depends on GPS to update its clock (scribbled down // periodically?) // time_t t; // time(&t); // struct tm *timebits = gmtime(&t); // snprintf(buffer, bufferlen, "%s/%04d%02d%02d%02d%02d%02d.BIN", // _log_directory_path, // timebits->tm_year+1900, // timebits->tm_mon+1, // timebits->tm_mday, // timebits->tm_hour, // timebits->tm_min, // timebits->tm_sec); memset(lastlog_buf, '\0', lastlog_buflen); snprintf(lastlog_buf, lastlog_buflen, "%s/LASTLOG.TXT", _log_directory_path); int fd; uint32_t num; if ((fd = open(lastlog_buf, O_RDONLY)) == -1) { if (errno != ENOENT) { // what? la_log(LOG_ERR, "Failed to open (%s) for reading: %s", lastlog_buf, strerror(errno)); return false; } num = 1; } else { const uint8_t numbuf_len = 128; char numbuf[numbuf_len]; memset(numbuf, '\0', numbuf_len); int bytes_read = read(fd, numbuf, numbuf_len); close(fd); if (bytes_read == -1) { return false; } num = strtoul(numbuf, NULL, 10); num++; } if ((fd = open(lastlog_buf, O_WRONLY|O_TRUNC|O_CREAT, 0777)) == -1) { // *shrug* We will continue to overwrite, I guess... la_log(LOG_ERR, "mh-dfl: failed to open (%s): %s", lastlog_buf, strerror(errno)); } else { const uint8_t outsize = 16; char out[outsize]; memset(out, '\0', outsize); int towrite = snprintf(out, outsize, "%d\r\n", num); if (write(fd, out, towrite) != towrite) { la_log(LOG_ERR, "mh-dfl: failed to write to (%s): %s", lastlog_buf, strerror(errno)); } close(fd); } snprintf(buffer, bufferlen, "%s/%d.BIN", _log_directory_path, num); return true; } bool DataFlash_Logger::output_file_open() { const uint8_t filename_length = 64; char filename[filename_length]; if (!make_new_log_filename(filename, filename_length)) { return false; } out_fd = open(filename, O_WRONLY|O_CREAT|O_TRUNC, 0777); if (out_fd == -1) { printf("Failed to open (%s): %s\n", filename, strerror(errno)); la_log(LOG_ERR, "Failed to open (%s): %s", filename, strerror(errno)); return false; } la_log(LOG_INFO, "Opened log file (%s)", filename); return true; } void DataFlash_Logger::output_file_close() { close(out_fd); } void DataFlash_Logger::queue_response(uint32_t seqno, bool status) { responses[response_queue_head].seqno = seqno; responses[response_queue_head].status = status; response_queue_head++; if (response_queue_head >= RESPONSE_QUEUE_LENGTH) { response_queue_head = 0; } } void DataFlash_Logger::queue_ack(uint32_t seqno) { queue_response(seqno, true); } void DataFlash_Logger::queue_nack(uint32_t seqno) { queue_response(seqno, false); } void DataFlash_Logger::queue_gap_nacks(uint32_t seqno) { if (seqno <= highest_seqno_seen) { // this packet filled in a gap (or was a dupe) return; } if (seqno - highest_seqno_seen > seqno_gap_nack_threshold) { // we've seen some serious disruption, and lots of stuff // is probably going to be lost. Do not bother NACKing // packets here and let the server sort things out return; } for (uint32_t i=highest_seqno_seen+1; i<seqno; i++) { queue_nack(i); } } bool DataFlash_Logger::logging_start(mavlink_message_t &m, mavlink_remote_log_data_block_t &msg UNUSED) { sender_system_id = m.sysid; sender_component_id = m.compid; sender_arm_status = ARM_STATUS_UNKNOWN; la_log_unsuppress(); la_log(LOG_INFO, "mh-dfl: Starting log, target is (%d/%d), I am (%d/%d)", sender_system_id, sender_component_id, this_system_id, this_component_id); if (!output_file_open()) { return false; } logging_started = true; return true; } void DataFlash_Logger::logging_stop() { output_file_close(); logging_started = false; } void DataFlash_Logger::handle_decoded_message(uint64_t T, mavlink_message_t &m, mavlink_heartbeat_t &msg) { // Need to match against heartbeats from both the 'target' and 'sender' components, since AP does not send heartbeats for logical endpoints at present. if (m.sysid == sender_system_id && (m.compid == sender_component_id || m.compid == target_component_id)) { arm_status_t new_sender_arm_status = (msg.base_mode & MAV_MODE_FLAG_SAFETY_ARMED) ? ARM_STATUS_ARMED : ARM_STATUS_DISARMED; if (logging_started) { if (sender_arm_status == ARM_STATUS_ARMED && new_sender_arm_status == ARM_STATUS_DISARMED) { // sender has moved from armed to disarmed state; stop // logging and let it restart naturally la_log(LOG_INFO, "mh-dfl: disarm detected, logging_stop"); logging_stop(); } } else { la_log(LOG_INFO, "Heartbeat received from %u/%u", m.sysid, m.compid); } sender_arm_status = new_sender_arm_status; } MAVLink_Message_Handler::handle_decoded_message(T, m, msg); } void DataFlash_Logger::handle_decoded_message(uint64_t T UNUSED, mavlink_message_t &m, mavlink_remote_log_data_block_t &msg) { if (!logging_started) { if (msg.seqno == 0) { if (!logging_start(m, msg)) { return; } } else { return; } } // we could move this down to the end; that wold mean short-writes // would end up closing this log... _last_data_packet_time = clock_gettime_us(CLOCK_MONOTONIC); const uint8_t length = MAVLINK_MSG_REMOTE_LOG_DATA_BLOCK_FIELD_DATA_LEN; /* send the dataflash data out to the log file */ lseek(out_fd, msg.seqno*MAVLINK_MSG_REMOTE_LOG_DATA_BLOCK_FIELD_DATA_LEN, SEEK_SET); if (write(out_fd, msg.data, length) < length) { la_log(LOG_ERR, "Short write: %s", strerror(errno)); // we'll get the block again... maybe we'll have better luck next time.. return; } // queue an ack for this packet queue_ack(msg.seqno); // queue nacks for gaps queue_gap_nacks(msg.seqno); if (msg.seqno > highest_seqno_seen) { if (msg.seqno - highest_seqno_seen > 100) { la_log(LOG_ERR, "large seqno gap: %ld", msg.seqno - highest_seqno_seen); } highest_seqno_seen = msg.seqno; } } void DataFlash_Logger::send_start_logging_packet() { send_start_or_stop_logging_packet(true); } void DataFlash_Logger::send_stop_logging_packet() { send_start_or_stop_logging_packet(false); } void DataFlash_Logger::send_start_or_stop_logging_packet(bool is_start) { mavlink_message_t msg; uint8_t system_id = is_start ? target_system_id : sender_system_id; uint8_t component_id = is_start ? target_component_id : sender_component_id; uint32_t magic_number; if (is_start) { la_log(LOG_INFO, "mh-dfl: sending start packet to (%d/%d)", system_id,component_id); magic_number = MAV_REMOTE_LOG_DATA_BLOCK_START; } else { la_log(LOG_INFO, "mh-dfl: sending stop packet to (%d/%d)", system_id,component_id); magic_number = MAV_REMOTE_LOG_DATA_BLOCK_STOP; } mavlink_msg_remote_log_block_status_pack (this_system_id, this_component_id, &msg, system_id, component_id, magic_number, 1); _mavlink_writer->send_message(msg); } <|endoftext|>
<commit_before><commit_msg>Enabled the XYZFile in MolFileFactory<commit_after><|endoftext|>
<commit_before><commit_msg>Guard GetEscapedHostname against a nullptr hostname. This can happen if you debug an iOS corefile on a mac, where PlatformPOSIX::GetHostname ends up not providing a hostname because we're working with a platform of remote-ios.<commit_after><|endoftext|>
<commit_before>#ifndef VIEW_HPP #define VIEW_HPP #include <plugin.hpp> #include <vector> #include <map> #include <functional> #include <pixman.h> extern "C" { #include <wlr/types/wlr_box.h> #include <wlr/types/wlr_surface.h> } class wayfire_output; struct wf_point { int x, y; }; using wf_geometry = wlr_box; bool operator == (const wf_geometry& a, const wf_geometry& b); bool operator != (const wf_geometry& a, const wf_geometry& b); wf_point operator + (const wf_point& a, const wf_point& b); wf_point operator + (const wf_point& a, const wf_geometry& b); wf_geometry operator + (const wf_geometry &a, const wf_point& b); wf_point operator - (const wf_point& a); wf_geometry get_output_box_from_box(const wlr_box& box, float scale); bool point_inside(wf_point point, wf_geometry rect); bool rect_intersect(wf_geometry screen, wf_geometry win); struct wf_custom_view_data { virtual ~wf_custom_view_data() {} }; /* General TODO: mark member functions const where appropriate */ class wayfire_view_t; using wayfire_view = std::shared_ptr<wayfire_view_t>; /* do not copy the surface, it is not reference counted and you will get crashes */ class wayfire_surface_t; using wf_surface_iterator_callback = std::function<void(wayfire_surface_t*, int, int)>; class wf_decorator_frame_t; class wf_view_transformer_t; /* abstraction for desktop-apis, no real need for plugins * This is a base class to all "drawables" - desktop views, subsurfaces, popups */ class wayfire_surface_t { /* TODO: maybe some functions don't need to be virtual? */ protected: wl_listener committed, destroy, new_sub; virtual void for_each_surface_recursive(wf_surface_iterator_callback callback, int x, int y, bool reverse = false); wayfire_surface_t *parent_surface; wayfire_output *output = nullptr; /* position relative to parent */ virtual void get_child_position(int &x, int &y); wf_geometry geometry = {0, 0, 0, 0}; virtual bool is_subsurface(); virtual void damage(const wlr_box& box); virtual void damage(pixman_region32_t *region); public: std::vector<wayfire_surface_t*> surface_children; wayfire_surface_t(wayfire_surface_t *parent = nullptr); virtual ~wayfire_surface_t(); /* if surface != nullptr, then the surface is mapped */ wlr_surface *surface = nullptr; virtual void map(wlr_surface *surface); virtual void unmap(); virtual void destruct() { delete this; } virtual bool is_mapped() { return surface; } int keep_count = 0; bool destroyed = false; void inc_keep_count(); void dec_keep_count(); virtual wayfire_surface_t *get_main_surface(); virtual void damage(); float alpha = 1.0; /* returns top-left corner in output coordinates */ virtual wf_point get_output_position(); virtual void update_output_position(); /* return surface box in output coordinates */ virtual wf_geometry get_output_geometry(); virtual void commit(); virtual wayfire_output *get_output() { return output; }; virtual void set_output(wayfire_output*); virtual void render(int x, int y, wlr_box* damage); /* just wrapper for the render() */ virtual void render_pixman(int x, int y, pixman_region32_t* damage); /* render to an offscreen buffer, without applying output transform/scale/etc. * Rendering is done in */ virtual void render_fbo(int x, int y, int fb_width, int fb_height, pixman_region32_t *damage); /* iterate all (sub) surfaces, popups, etc. in top-most order * for example, first popups, then subsurfaces, then main surface * When reverse=true, the order in which surfaces are visited is reversed */ virtual void for_each_surface(wf_surface_iterator_callback callback, bool reverse = false); virtual void render_fb(int x, int y, pixman_region32_t* damage, int target_fb); }; /* Represents a desktop window (not as X11 window, but like a xdg_toplevel surface) */ class wayfire_view_t : public wayfire_surface_t { friend class wayfire_xdg_decoration_view; friend class wayfire_xdg6_decoration_view; friend void surface_destroyed_cb(wl_listener*, void *data); protected: wayfire_view decoration; int decor_x, decor_y; void force_update_xwayland_position(); int in_continuous_move = 0, in_continuous_resize = 0; bool wait_decoration = false; virtual bool update_size(); uint32_t id; virtual void get_child_position(int &x, int &y); virtual void damage(const wlr_box& box); struct offscreen_buffer_t { uint32_t fbo = -1, tex = -1; /* used to store output_geometry when the view has been destroyed */ int32_t output_x = 0, output_y = 0; int32_t fb_width = 0, fb_height = 0; pixman_region32_t cached_damage; void init(int w, int h); void fini(); bool valid(); } offscreen_buffer; std::unique_ptr<wf_view_transformer_t> transform; virtual wf_geometry get_untransformed_bounding_box(); void reposition_relative_to_parent(); public: /* these represent toplevel relations, children here are transient windows, * such as the close file dialogue */ wayfire_view parent = nullptr; std::vector<wayfire_view> children; virtual void set_toplevel_parent(wayfire_view parent); /* plugins can subclass wf_custom_view_data and use it to store view-specific information * it must provide a virtual destructor to free its data. Custom data is deleted when the view * is destroyed if not removed earlier */ std::map<std::string, wf_custom_view_data*> custom_data; wayfire_view_t(); virtual ~wayfire_view_t(); uint32_t get_id() { return id; } inline wayfire_view self(); virtual void move(int x, int y, bool send_signal = true); virtual void resize(int w, int h, bool send_signal = true); virtual void activate(bool active); virtual void close() {}; virtual void set_parent(wayfire_view parent); virtual wayfire_surface_t* get_main_surface(); /* return geometry as should be used for all WM purposes */ virtual wf_geometry get_wm_geometry() { return decoration ? decoration->get_wm_geometry() : geometry; } virtual wf_point get_output_position(); /* return the output-local transformed coordinates of the view * and all its subsurfaces */ virtual wlr_box get_bounding_box(); /* transform the given region using the view's transform */ virtual wlr_box transform_region(const wlr_box &box); /* check whether the given region intersects any of the surfaces * in the view's surface tree. */ virtual bool intersects_region(const wlr_box& region); /* map from global to surface local coordinates * returns the (sub)surface under the cursor or NULL iff the cursor is outside of the view * TODO: it should be overwritable by plugins which deform the view */ virtual wayfire_surface_t *map_input_coordinates(int cursor_x, int cursor_y, int &sx, int &sy); virtual wlr_surface *get_keyboard_focus_surface() { return surface; }; virtual void set_geometry(wf_geometry g); virtual void set_resizing(bool resizing); virtual void set_moving(bool moving); bool maximized = false, fullscreen = false; virtual void set_maximized(bool maxim); virtual void set_fullscreen(bool fullscreen); bool is_visible(); virtual void commit(); virtual void map(wlr_surface *surface); virtual void unmap(); virtual void destruct(); virtual void damage(); virtual std::string get_app_id() { return ""; } virtual std::string get_title() { return ""; } /* Set if the current view should not be rendered by built-in renderer */ bool is_hidden = false; /* backgrounds, panels, lock surfaces -> they shouldn't be touched * by plugins like move, animate, etc. */ bool is_special = false; virtual void move_request(); virtual void resize_request(); virtual void maximize_request(bool state); virtual void fullscreen_request(wayfire_output *output, bool state); virtual void set_decoration(wayfire_view view, std::unique_ptr<wf_decorator_frame_t> frame); /* * View transforms * A view transform can be any kind of transformation, for example 3D rotation, * wobbly effect or similar. When we speak of transforms, a "view" is defined * as a toplevel window (including decoration) and also all of its subsurfaces/popups. * The transformation then is applied to this group of surfaces together. * * When a view has a custom transform, then internally all these surfaces are * rendered to a FBO, and then the custom transformation renders the resulting * texture as it sees fit. In this way we could have composable transformations * in the future(e.g several FBO passes). * * Damage tracking for transformed views is done on the boundingbox of the * damaged region after applying the transformation, but all damaged parts * of the internal FBO are updated. * */ virtual void set_transformer(std::unique_ptr<wf_view_transformer_t> transformer); /* the returned value is just a temporary object */ virtual wf_view_transformer_t* get_transformer() { return transform.get(); } virtual void render_fb(int x, int y, pixman_region32_t* damage, int target_fb); bool has_snapshot = false; virtual void take_snapshot(); }; wayfire_view wl_surface_to_wayfire_view(wl_resource *surface); #endif <commit_msg>view: remove inline from self()<commit_after>#ifndef VIEW_HPP #define VIEW_HPP #include <plugin.hpp> #include <vector> #include <map> #include <functional> #include <pixman.h> extern "C" { #include <wlr/types/wlr_box.h> #include <wlr/types/wlr_surface.h> } class wayfire_output; struct wf_point { int x, y; }; using wf_geometry = wlr_box; bool operator == (const wf_geometry& a, const wf_geometry& b); bool operator != (const wf_geometry& a, const wf_geometry& b); wf_point operator + (const wf_point& a, const wf_point& b); wf_point operator + (const wf_point& a, const wf_geometry& b); wf_geometry operator + (const wf_geometry &a, const wf_point& b); wf_point operator - (const wf_point& a); wf_geometry get_output_box_from_box(const wlr_box& box, float scale); bool point_inside(wf_point point, wf_geometry rect); bool rect_intersect(wf_geometry screen, wf_geometry win); struct wf_custom_view_data { virtual ~wf_custom_view_data() {} }; /* General TODO: mark member functions const where appropriate */ class wayfire_view_t; using wayfire_view = std::shared_ptr<wayfire_view_t>; /* do not copy the surface, it is not reference counted and you will get crashes */ class wayfire_surface_t; using wf_surface_iterator_callback = std::function<void(wayfire_surface_t*, int, int)>; class wf_decorator_frame_t; class wf_view_transformer_t; /* abstraction for desktop-apis, no real need for plugins * This is a base class to all "drawables" - desktop views, subsurfaces, popups */ class wayfire_surface_t { /* TODO: maybe some functions don't need to be virtual? */ protected: wl_listener committed, destroy, new_sub; virtual void for_each_surface_recursive(wf_surface_iterator_callback callback, int x, int y, bool reverse = false); wayfire_surface_t *parent_surface; wayfire_output *output = nullptr; /* position relative to parent */ virtual void get_child_position(int &x, int &y); wf_geometry geometry = {0, 0, 0, 0}; virtual bool is_subsurface(); virtual void damage(const wlr_box& box); virtual void damage(pixman_region32_t *region); public: std::vector<wayfire_surface_t*> surface_children; wayfire_surface_t(wayfire_surface_t *parent = nullptr); virtual ~wayfire_surface_t(); /* if surface != nullptr, then the surface is mapped */ wlr_surface *surface = nullptr; virtual void map(wlr_surface *surface); virtual void unmap(); virtual void destruct() { delete this; } virtual bool is_mapped() { return surface; } int keep_count = 0; bool destroyed = false; void inc_keep_count(); void dec_keep_count(); virtual wayfire_surface_t *get_main_surface(); virtual void damage(); float alpha = 1.0; /* returns top-left corner in output coordinates */ virtual wf_point get_output_position(); virtual void update_output_position(); /* return surface box in output coordinates */ virtual wf_geometry get_output_geometry(); virtual void commit(); virtual wayfire_output *get_output() { return output; }; virtual void set_output(wayfire_output*); virtual void render(int x, int y, wlr_box* damage); /* just wrapper for the render() */ virtual void render_pixman(int x, int y, pixman_region32_t* damage); /* render to an offscreen buffer, without applying output transform/scale/etc. * Rendering is done in */ virtual void render_fbo(int x, int y, int fb_width, int fb_height, pixman_region32_t *damage); /* iterate all (sub) surfaces, popups, etc. in top-most order * for example, first popups, then subsurfaces, then main surface * When reverse=true, the order in which surfaces are visited is reversed */ virtual void for_each_surface(wf_surface_iterator_callback callback, bool reverse = false); virtual void render_fb(int x, int y, pixman_region32_t* damage, int target_fb); }; /* Represents a desktop window (not as X11 window, but like a xdg_toplevel surface) */ class wayfire_view_t : public wayfire_surface_t { friend class wayfire_xdg_decoration_view; friend class wayfire_xdg6_decoration_view; friend void surface_destroyed_cb(wl_listener*, void *data); protected: wayfire_view decoration; int decor_x, decor_y; void force_update_xwayland_position(); int in_continuous_move = 0, in_continuous_resize = 0; bool wait_decoration = false; virtual bool update_size(); uint32_t id; virtual void get_child_position(int &x, int &y); virtual void damage(const wlr_box& box); struct offscreen_buffer_t { uint32_t fbo = -1, tex = -1; /* used to store output_geometry when the view has been destroyed */ int32_t output_x = 0, output_y = 0; int32_t fb_width = 0, fb_height = 0; pixman_region32_t cached_damage; void init(int w, int h); void fini(); bool valid(); } offscreen_buffer; std::unique_ptr<wf_view_transformer_t> transform; virtual wf_geometry get_untransformed_bounding_box(); void reposition_relative_to_parent(); public: /* these represent toplevel relations, children here are transient windows, * such as the close file dialogue */ wayfire_view parent = nullptr; std::vector<wayfire_view> children; virtual void set_toplevel_parent(wayfire_view parent); /* plugins can subclass wf_custom_view_data and use it to store view-specific information * it must provide a virtual destructor to free its data. Custom data is deleted when the view * is destroyed if not removed earlier */ std::map<std::string, wf_custom_view_data*> custom_data; wayfire_view_t(); virtual ~wayfire_view_t(); uint32_t get_id() { return id; } wayfire_view self(); virtual void move(int x, int y, bool send_signal = true); virtual void resize(int w, int h, bool send_signal = true); virtual void activate(bool active); virtual void close() {}; virtual void set_parent(wayfire_view parent); virtual wayfire_surface_t* get_main_surface(); /* return geometry as should be used for all WM purposes */ virtual wf_geometry get_wm_geometry() { return decoration ? decoration->get_wm_geometry() : geometry; } virtual wf_point get_output_position(); /* return the output-local transformed coordinates of the view * and all its subsurfaces */ virtual wlr_box get_bounding_box(); /* transform the given region using the view's transform */ virtual wlr_box transform_region(const wlr_box &box); /* check whether the given region intersects any of the surfaces * in the view's surface tree. */ virtual bool intersects_region(const wlr_box& region); /* map from global to surface local coordinates * returns the (sub)surface under the cursor or NULL iff the cursor is outside of the view * TODO: it should be overwritable by plugins which deform the view */ virtual wayfire_surface_t *map_input_coordinates(int cursor_x, int cursor_y, int &sx, int &sy); virtual wlr_surface *get_keyboard_focus_surface() { return surface; }; virtual void set_geometry(wf_geometry g); virtual void set_resizing(bool resizing); virtual void set_moving(bool moving); bool maximized = false, fullscreen = false; virtual void set_maximized(bool maxim); virtual void set_fullscreen(bool fullscreen); bool is_visible(); virtual void commit(); virtual void map(wlr_surface *surface); virtual void unmap(); virtual void destruct(); virtual void damage(); virtual std::string get_app_id() { return ""; } virtual std::string get_title() { return ""; } /* Set if the current view should not be rendered by built-in renderer */ bool is_hidden = false; /* backgrounds, panels, lock surfaces -> they shouldn't be touched * by plugins like move, animate, etc. */ bool is_special = false; virtual void move_request(); virtual void resize_request(); virtual void maximize_request(bool state); virtual void fullscreen_request(wayfire_output *output, bool state); virtual void set_decoration(wayfire_view view, std::unique_ptr<wf_decorator_frame_t> frame); /* * View transforms * A view transform can be any kind of transformation, for example 3D rotation, * wobbly effect or similar. When we speak of transforms, a "view" is defined * as a toplevel window (including decoration) and also all of its subsurfaces/popups. * The transformation then is applied to this group of surfaces together. * * When a view has a custom transform, then internally all these surfaces are * rendered to a FBO, and then the custom transformation renders the resulting * texture as it sees fit. In this way we could have composable transformations * in the future(e.g several FBO passes). * * Damage tracking for transformed views is done on the boundingbox of the * damaged region after applying the transformation, but all damaged parts * of the internal FBO are updated. * */ virtual void set_transformer(std::unique_ptr<wf_view_transformer_t> transformer); /* the returned value is just a temporary object */ virtual wf_view_transformer_t* get_transformer() { return transform.get(); } virtual void render_fb(int x, int y, pixman_region32_t* damage, int target_fb); bool has_snapshot = false; virtual void take_snapshot(); }; wayfire_view wl_surface_to_wayfire_view(wl_resource *surface); #endif <|endoftext|>
<commit_before><commit_msg>made some adaptation to the connectto method to handle internal "files" better and leave the urls to internal objects in a consistent state<commit_after><|endoftext|>
<commit_before>/** * Copyright 2017 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. */ #include "dbuspassive.hpp" #include "dbuspassiveredundancy.hpp" #include "util.hpp" #include <chrono> #include <cmath> #include <memory> #include <mutex> #include <sdbusplus/bus.hpp> #include <string> #include <variant> std::unique_ptr<ReadInterface> DbusPassive::createDbusPassive( sdbusplus::bus::bus& bus, const std::string& type, const std::string& id, DbusHelperInterface* helper, const conf::SensorConfig* info, const std::shared_ptr<DbusPassiveRedundancy>& redundancy) { if (helper == nullptr) { return nullptr; } if (!validType(type)) { return nullptr; } /* Need to get the scale and initial value */ auto tempBus = sdbusplus::bus::new_system(); /* service == busname */ std::string path = getSensorPath(type, id); struct SensorProperties settings; bool failed; try { std::string service = helper->getService(tempBus, sensorintf, path); helper->getProperties(tempBus, service, path, &settings); failed = helper->thresholdsAsserted(tempBus, service, path); } catch (const std::exception& e) { return nullptr; } if (info->max != conf::inheritValueFromDbus) { settings.max = info->max; } if (info->max != conf::inheritValueFromDbus) { settings.min = info->min; } return std::make_unique<DbusPassive>(bus, type, id, helper, settings, failed, path, redundancy); } DbusPassive::DbusPassive( sdbusplus::bus::bus& bus, const std::string& type, const std::string& id, DbusHelperInterface* helper, const struct SensorProperties& settings, bool failed, const std::string& path, const std::shared_ptr<DbusPassiveRedundancy>& redundancy) : ReadInterface(), _bus(bus), _signal(bus, getMatch(type, id).c_str(), dbusHandleSignal, this), _id(id), _helper(helper), _failed(failed), path(path), redundancy(redundancy) { _scale = settings.scale; _value = settings.value * pow(10, _scale); _min = settings.min * pow(10, _scale); _max = settings.max * pow(10, _scale); _updated = std::chrono::high_resolution_clock::now(); } ReadReturn DbusPassive::read(void) { std::lock_guard<std::mutex> guard(_lock); struct ReadReturn r = {_value, _updated}; return r; } void DbusPassive::setValue(double value) { std::lock_guard<std::mutex> guard(_lock); _value = value; _updated = std::chrono::high_resolution_clock::now(); } bool DbusPassive::getFailed(void) const { if (redundancy) { const std::set<std::string>& failures = redundancy->getFailed(); if (failures.find(path) != failures.end()) { return true; } } return _failed; } void DbusPassive::setFailed(bool value) { _failed = value; } int64_t DbusPassive::getScale(void) { return _scale; } std::string DbusPassive::getID(void) { return _id; } double DbusPassive::getMax(void) { return _max; } double DbusPassive::getMin(void) { return _min; } int handleSensorValue(sdbusplus::message::message& msg, DbusPassive* owner) { std::string msgSensor; std::map<std::string, std::variant<int64_t, double, bool>> msgData; msg.read(msgSensor, msgData); if (msgSensor == "xyz.openbmc_project.Sensor.Value") { auto valPropMap = msgData.find("Value"); if (valPropMap != msgData.end()) { double value = std::visit(VariantToDoubleVisitor(), valPropMap->second); value *= std::pow(10, owner->getScale()); scaleSensorReading(owner->getMin(), owner->getMax(), value); owner->setValue(value); } } else if (msgSensor == "xyz.openbmc_project.Sensor.Threshold.Critical") { auto criticalAlarmLow = msgData.find("CriticalAlarmLow"); auto criticalAlarmHigh = msgData.find("CriticalAlarmHigh"); if (criticalAlarmHigh == msgData.end() && criticalAlarmLow == msgData.end()) { return 0; } bool asserted = false; if (criticalAlarmLow != msgData.end()) { asserted = std::get<bool>(criticalAlarmLow->second); } // checking both as in theory you could de-assert one threshold and // assert the other at the same moment if (!asserted && criticalAlarmHigh != msgData.end()) { asserted = std::get<bool>(criticalAlarmHigh->second); } owner->setFailed(asserted); } return 0; } int dbusHandleSignal(sd_bus_message* msg, void* usrData, sd_bus_error* err) { auto sdbpMsg = sdbusplus::message::message(msg); DbusPassive* obj = static_cast<DbusPassive*>(usrData); return handleSensorValue(sdbpMsg, obj); } <commit_msg>dbuspassive: Fix typo in variable check<commit_after>/** * Copyright 2017 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. */ #include "dbuspassive.hpp" #include "dbuspassiveredundancy.hpp" #include "util.hpp" #include <chrono> #include <cmath> #include <memory> #include <mutex> #include <sdbusplus/bus.hpp> #include <string> #include <variant> std::unique_ptr<ReadInterface> DbusPassive::createDbusPassive( sdbusplus::bus::bus& bus, const std::string& type, const std::string& id, DbusHelperInterface* helper, const conf::SensorConfig* info, const std::shared_ptr<DbusPassiveRedundancy>& redundancy) { if (helper == nullptr) { return nullptr; } if (!validType(type)) { return nullptr; } /* Need to get the scale and initial value */ auto tempBus = sdbusplus::bus::new_system(); /* service == busname */ std::string path = getSensorPath(type, id); struct SensorProperties settings; bool failed; try { std::string service = helper->getService(tempBus, sensorintf, path); helper->getProperties(tempBus, service, path, &settings); failed = helper->thresholdsAsserted(tempBus, service, path); } catch (const std::exception& e) { return nullptr; } if (info->max != conf::inheritValueFromDbus) { settings.max = info->max; } if (info->min != conf::inheritValueFromDbus) { settings.min = info->min; } return std::make_unique<DbusPassive>(bus, type, id, helper, settings, failed, path, redundancy); } DbusPassive::DbusPassive( sdbusplus::bus::bus& bus, const std::string& type, const std::string& id, DbusHelperInterface* helper, const struct SensorProperties& settings, bool failed, const std::string& path, const std::shared_ptr<DbusPassiveRedundancy>& redundancy) : ReadInterface(), _bus(bus), _signal(bus, getMatch(type, id).c_str(), dbusHandleSignal, this), _id(id), _helper(helper), _failed(failed), path(path), redundancy(redundancy) { _scale = settings.scale; _value = settings.value * pow(10, _scale); _min = settings.min * pow(10, _scale); _max = settings.max * pow(10, _scale); _updated = std::chrono::high_resolution_clock::now(); } ReadReturn DbusPassive::read(void) { std::lock_guard<std::mutex> guard(_lock); struct ReadReturn r = {_value, _updated}; return r; } void DbusPassive::setValue(double value) { std::lock_guard<std::mutex> guard(_lock); _value = value; _updated = std::chrono::high_resolution_clock::now(); } bool DbusPassive::getFailed(void) const { if (redundancy) { const std::set<std::string>& failures = redundancy->getFailed(); if (failures.find(path) != failures.end()) { return true; } } return _failed; } void DbusPassive::setFailed(bool value) { _failed = value; } int64_t DbusPassive::getScale(void) { return _scale; } std::string DbusPassive::getID(void) { return _id; } double DbusPassive::getMax(void) { return _max; } double DbusPassive::getMin(void) { return _min; } int handleSensorValue(sdbusplus::message::message& msg, DbusPassive* owner) { std::string msgSensor; std::map<std::string, std::variant<int64_t, double, bool>> msgData; msg.read(msgSensor, msgData); if (msgSensor == "xyz.openbmc_project.Sensor.Value") { auto valPropMap = msgData.find("Value"); if (valPropMap != msgData.end()) { double value = std::visit(VariantToDoubleVisitor(), valPropMap->second); value *= std::pow(10, owner->getScale()); scaleSensorReading(owner->getMin(), owner->getMax(), value); owner->setValue(value); } } else if (msgSensor == "xyz.openbmc_project.Sensor.Threshold.Critical") { auto criticalAlarmLow = msgData.find("CriticalAlarmLow"); auto criticalAlarmHigh = msgData.find("CriticalAlarmHigh"); if (criticalAlarmHigh == msgData.end() && criticalAlarmLow == msgData.end()) { return 0; } bool asserted = false; if (criticalAlarmLow != msgData.end()) { asserted = std::get<bool>(criticalAlarmLow->second); } // checking both as in theory you could de-assert one threshold and // assert the other at the same moment if (!asserted && criticalAlarmHigh != msgData.end()) { asserted = std::get<bool>(criticalAlarmHigh->second); } owner->setFailed(asserted); } return 0; } int dbusHandleSignal(sd_bus_message* msg, void* usrData, sd_bus_error* err) { auto sdbpMsg = sdbusplus::message::message(msg); DbusPassive* obj = static_cast<DbusPassive*>(usrData); return handleSensorValue(sdbpMsg, obj); } <|endoftext|>
<commit_before><commit_msg>Fix argc condition<commit_after><|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) 2018 Konstantinos Krestenitis Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "delta/core/State.h" delta::core::State::State() { } delta::core::State::State( int noOfParticles, int noOfObstacles, iREAL dt) { _start = Time::now(); _noOfParticles = noOfParticles; _noOfObstacles = noOfObstacles; _dt = dt; _numberOfTriangleComparisons = 0; _numberOfParticleComparisons = 0; _numberOfCollisions = 0; //_checkpointFile = "output.out"; _iteration = 0; } void delta::core::State::update() { _iteration ++; } int delta::core::State::getCurrentStepIteration() { return _iteration; } int delta::core::State::getCollisions() { return _numberOfCollisions; } iREAL delta::core::State::getStepSize() { return _dt; } void delta::core::State::writeState() { std::string filename = "checkpoint_.delta"; //_checkpointFile.open (filename); /* _checkpointFile << "#THIS IS A DELTA CHECKPOINT FILE\n"; _checkpointFile << "#NOPARTICLE|NOOBSTACLES|TIMESTEPSIZE|ITERATION|TOTALITERATIONS\n"; _checkpointFile << "%:" << _noOfParticles << ":" << _noOfObstacles+":" << _timeStepSize<<":" << _currentIteration << ":" << _totalIterations<<"\n"; */ } void delta::core::State::incNumberOfTriangleComparisons(int n) { _numberOfTriangleComparisons += n; } void delta::core::State::incNumberOfParticleComparisons(int n) { _numberOfParticleComparisons += n; } void delta::core::State::readState() { } std::chrono::system_clock::time_point delta::core::State::getStartTime() { return _start; } void delta::core::State::saveParticleGeometry() { } <commit_msg><commit_after>/* The MIT License (MIT) Copyright (c) 2018 Konstantinos Krestenitis Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "delta/core/State.h" delta::core::State::State() { } delta::core::State::State( int noOfParticles, int noOfObstacles, iREAL dt) { _start = Time::now(); _noOfParticles = noOfParticles; _noOfObstacles = noOfObstacles; _dt = dt; _numberOfTriangleComparisons = 0; _numberOfParticleComparisons = 0; _numberOfCollisions = 0; //_checkpointFile = "output.out"; _iteration = 0; } void delta::core::State::update() { _iteration ++; } int delta::core::State::getCurrentStepIteration() { return _iteration; } int delta::core::State::getCollisions() { return _numberOfCollisions; } iREAL delta::core::State::getStepSize() { return _dt; } void delta::core::State::writeState() { std::string filename = "checkpoint_.delta"; //_checkpointFile.open (filename); /* _checkpointFile << "#THIS IS A DELTA CHECKPOINT FILE\n"; _checkpointFile << "#NOPARTICLE|NOOBSTACLES|TIMESTEPSIZE|ITERATION|TOTALITERATIONS\n"; _checkpointFile << "%:" << _noOfParticles << ":" << _noOfObstacles+":" << _timeStepSize<<":" << _currentIteration << ":" << _totalIterations<<"\n"; */ } void delta::core::State::incNumberOfTriangleComparisons(int n) { _numberOfTriangleComparisons += n; } void delta::core::State::incNumberOfParticleComparisons(int n) { _numberOfParticleComparisons += n; } void delta::core::State::readState() { } std::chrono::steady_clock::time_point delta::core::State::getStartTime() { return _start; } void delta::core::State::saveParticleGeometry() { } <|endoftext|>
<commit_before>// // SqImport: Supports importing of squirrel modules // // // Copyright (c) 2009 Brandon Jones // Copyright (c) 2013 Paul Sokolovsky // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. // #include "sqimport.h" #include "sqmodule.h" //#include "sqratlib/sqratBase.h" #include <sqstdio.h> #include <sqstdblob.h> #include <string> // getenv #include <stdlib.h> #if defined(_WIN32) #include <windows.h> #elif defined(__unix) #include <dlfcn.h> #endif typedef SQRESULT (*SQMODULELOAD)(HSQUIRRELVM v, HSQAPI sq); static HSQAPI sqapi = NULL; // Create and populate the HSQAPI structure with function pointers // If new functions are added to the Squirrel API, they should be added here too static HSQAPI sqrat_newapi() { HSQAPI sq = (HSQAPI)sq_malloc(sizeof(sq_api)); sq->version = SQMODULE_API_VERSION; /*vm*/ sq->open = sq_open; sq->newthread = sq_newthread; sq->seterrorhandler = sq_seterrorhandler; sq->close = sq_close; sq->setforeignptr = sq_setforeignptr; sq->getforeignptr = sq_getforeignptr; sq->setprintfunc = sq_setprintfunc; sq->getprintfunc = sq_getprintfunc; sq->suspendvm = sq_suspendvm; sq->wakeupvm = sq_wakeupvm; sq->getvmstate = sq_getvmstate; /*compiler*/ sq->compile = sq_compile; sq->compilebuffer = sq_compilebuffer; sq->enabledebuginfo = sq_enabledebuginfo; sq->notifyallexceptions = sq_notifyallexceptions; sq->setcompilererrorhandler = sq_setcompilererrorhandler; /*stack operations*/ sq->push = sq_push; sq->pop = sq_pop; sq->poptop = sq_poptop; sq->remove = sq_remove; sq->gettop = sq_gettop; sq->settop = sq_settop; sq->reservestack = sq_reservestack; sq->cmp = sq_cmp; sq->move = sq_move; /*object creation handling*/ sq->newuserdata = sq_newuserdata; sq->newtable = sq_newtable; sq->newarray = sq_newarray; sq->newclosure = sq_newclosure; sq->setparamscheck = sq_setparamscheck; sq->bindenv = sq_bindenv; sq->pushstring = sq_pushstring; sq->pushfloat = sq_pushfloat; sq->pushinteger = sq_pushinteger; sq->pushbool = sq_pushbool; sq->pushuserpointer = sq_pushuserpointer; sq->pushnull = sq_pushnull; sq->gettype = sq_gettype; sq->getsize = sq_getsize; sq->getbase = sq_getbase; sq->instanceof = sq_instanceof; sq->tostring = sq_tostring; sq->tobool = sq_tobool; sq->getstring = sq_getstring; sq->getinteger = sq_getinteger; sq->getthread = sq_getthread; sq->getbool = sq_getbool; sq->getuserpointer = sq_getuserpointer; sq->getuserdata = sq_getuserdata; sq->settypetag = sq_settypetag; sq->gettypetag = sq_gettypetag; sq->setreleasehook = sq_setreleasehook; sq->getscratchpad = sq_getscratchpad; sq->getclosureinfo = sq_getclosureinfo; sq->setnativeclosurename = sq_setnativeclosurename; sq->setinstanceup = sq_setinstanceup; sq->getinstanceup = sq_getinstanceup; sq->setclassudsize = sq_setclassudsize; sq->newclass = sq_newclass; sq->createinstance = sq_createinstance; sq->setattributes = sq_setattributes; sq->getattributes = sq_getattributes; sq->getclass = sq_getclass; sq->weakref = sq_weakref; sq->getdefaultdelegate = sq_getdefaultdelegate; /*object manipulation*/ sq->pushroottable = sq_pushroottable; sq->pushregistrytable = sq_pushregistrytable; sq->pushconsttable = sq_pushconsttable; sq->setroottable = sq_setroottable; sq->setconsttable = sq_setconsttable; sq->newslot = sq_newslot; sq->deleteslot = sq_deleteslot; sq->set = sq_set; sq->get = sq_get; sq->rawset = sq_rawset; sq->rawget = sq_rawget; sq->rawdeleteslot = sq_rawdeleteslot; sq->arrayappend = sq_arrayappend; sq->arraypop = sq_arraypop; sq->arrayresize = sq_arrayresize; sq->arrayreverse = sq_arrayreverse; sq->arrayremove = sq_arrayremove; sq->arrayinsert = sq_arrayinsert; sq->setdelegate = sq_setdelegate; sq->getdelegate = sq_getdelegate; sq->clone = sq_clone; sq->setfreevariable = sq_setfreevariable; sq->next = sq_next; sq->getweakrefval = sq_getweakrefval; sq->clear = sq_clear; /*calls*/ sq->call = sq_call; sq->resume = sq_resume; sq->getlocal = sq_getlocal; sq->getfreevariable = sq_getfreevariable; sq->throwerror = sq_throwerror; sq->reseterror = sq_reseterror; sq->getlasterror = sq_getlasterror; /*raw object handling*/ sq->getstackobj = sq_getstackobj; sq->pushobject = sq_pushobject; sq->addref = sq_addref; sq->release = sq_release; sq->resetobject = sq_resetobject; sq->objtostring = sq_objtostring; sq->objtobool = sq_objtobool; sq->objtointeger = sq_objtointeger; sq->objtofloat = sq_objtofloat; sq->getobjtypetag = sq_getobjtypetag; /*GC*/ sq->collectgarbage = sq_collectgarbage; /*serialization*/ sq->writeclosure = sq_writeclosure; sq->readclosure = sq_readclosure; /*mem allocation*/ sq->malloc = sq_malloc; sq->realloc = sq_realloc; sq->free = sq_free; /*debug*/ sq->stackinfos = sq_stackinfos; sq->setdebughook = sq_setdebughook; /*stdlib*/ sq->getblob = sqstd_getblob; return sq; } static SQRESULT sqrat_importscript(HSQUIRRELVM v, const SQChar* filename) { if(SQ_FAILED(sqstd_loadfile(v, filename, true))) { return SQ_ERROR; } sq_push(v, -2); sq_call(v, 1, false, true); return SQ_OK; } static SQRESULT sqrat_importbin(HSQUIRRELVM v, const SQChar* moduleName) { #ifdef SQUNICODE #warning sqrat_importbin() Not Implemented return SQ_ERROR; #else SQMODULELOAD modLoad = 0; #if defined(_WIN32) HMODULE mod; mod = LoadLibrary(moduleName); if (mod == NULL) return sq_throwerror(v, _SC("Could not load module")); modLoad = (SQMODULELOAD)GetProcAddress(mod, "sqmodule_load"); if(modLoad == NULL) { FreeLibrary(mod); return sq_throwerror(v, _SC("Could not get module init routine")); } #elif defined(__unix) void *mod = dlopen(moduleName, RTLD_NOW | RTLD_LOCAL); if (mod == NULL) return sq_throwerror(v, _SC("Could not load module")); modLoad = (SQMODULELOAD)dlsym(mod, "sqmodule_load"); if (modLoad == NULL) { dlclose(mod); return sq_throwerror(v, _SC("Could not get module init routine")); } #endif if(sqapi == NULL) { sqapi = sqrat_newapi(); // Caching this for multiple imports is probably a very good idea } SQRESULT res = modLoad(v, sqapi); return res; #endif } bool file_exists(const SQChar* filename) { return access(filename, F_OK) == 0; } #define NOT_FOUND 100 SQRESULT try_import_path(HSQUIRRELVM v, std::basic_string<SQChar>& fname) { // Try to import module at given path. This tries // different module types in order. // Check binary module fname[fname.size() - 1] = 'd'; if (file_exists(fname.c_str())) return sqrat_importbin(v, fname.c_str()); // Check bytecode module fname[fname.size() - 1] = 'c'; if (file_exists(fname.c_str())) return sqrat_importscript(v, fname.c_str()); // Check source module fname[fname.size() - 1] = 't'; if (file_exists(fname.c_str())) return sqrat_importscript(v, fname.c_str()); return NOT_FOUND; } SQInteger sq_import(HSQUIRRELVM v) { const SQChar* moduleName; HSQOBJECT table; SQRESULT res = SQ_OK; sq_getstring(v, -2, &moduleName); sq_getstackobj(v, -1, &table); sq_addref(v, &table); sq_settop(v, 0); // Clear Stack sq_pushobject(v, table); // Push the target table onto the stack std::basic_string<SQChar> fname; // Explicit path is needed for dlopen() later, and won't hurt // for other cases fname = "./"; fname += moduleName; fname += ".nut"; res = try_import_path(v, fname); if (res == NOT_FOUND) { const char *path = getenv("SQPATH"); if (path) fname = path; else { path = getenv("HOME"); if (path) { fname = path; fname += "/.squirrel/lib"; } else { fname = "/usr/lib/squirrel"; } } fname += "/"; fname += moduleName; fname += ".nut"; res = try_import_path(v, fname); if (res == NOT_FOUND) { sq_settop(v, 0); // Clean up the stack (just in case the module load leaves it messy) sq_release(v, &table); return sq_throwerror(v, _SC("Module not found")); } } sq_settop(v, 0); // Clean up the stack (just in case the module load leaves it messy) sq_pushobject(v, table); // return the target table sq_release(v, &table); // If we didn't thro exception, then we return value if (res != SQ_ERROR) return 1; } static SQInteger sqratbase_import(HSQUIRRELVM v) { SQInteger args = sq_gettop(v); switch(args) { case 2: sq_pushroottable(v); break; case 3: // should already have the desired table pushed onto the stack break; default: // Error, unexpected number of arguments break; } return sq_import(v); } SQRESULT sqrat_register_importlib(HSQUIRRELVM v) { sq_pushroottable(v); sq_pushstring(v, _SC("_import_"), -1); sq_newclosure(v, &sqratbase_import, 0); sq_newslot(v, -3, 0); sq_pop(v, 1); // pop sqrat table return SQ_OK; } <commit_msg>sqimport: Keep reference to module name object while we use it.<commit_after>// // SqImport: Supports importing of squirrel modules // // // Copyright (c) 2009 Brandon Jones // Copyright (c) 2013 Paul Sokolovsky // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. // #include "sqimport.h" #include "sqmodule.h" //#include "sqratlib/sqratBase.h" #include <sqstdio.h> #include <sqstdblob.h> #include <string> // getenv #include <stdlib.h> #if defined(_WIN32) #include <windows.h> #elif defined(__unix) #include <dlfcn.h> #endif typedef SQRESULT (*SQMODULELOAD)(HSQUIRRELVM v, HSQAPI sq); static HSQAPI sqapi = NULL; // Create and populate the HSQAPI structure with function pointers // If new functions are added to the Squirrel API, they should be added here too static HSQAPI sqrat_newapi() { HSQAPI sq = (HSQAPI)sq_malloc(sizeof(sq_api)); sq->version = SQMODULE_API_VERSION; /*vm*/ sq->open = sq_open; sq->newthread = sq_newthread; sq->seterrorhandler = sq_seterrorhandler; sq->close = sq_close; sq->setforeignptr = sq_setforeignptr; sq->getforeignptr = sq_getforeignptr; sq->setprintfunc = sq_setprintfunc; sq->getprintfunc = sq_getprintfunc; sq->suspendvm = sq_suspendvm; sq->wakeupvm = sq_wakeupvm; sq->getvmstate = sq_getvmstate; /*compiler*/ sq->compile = sq_compile; sq->compilebuffer = sq_compilebuffer; sq->enabledebuginfo = sq_enabledebuginfo; sq->notifyallexceptions = sq_notifyallexceptions; sq->setcompilererrorhandler = sq_setcompilererrorhandler; /*stack operations*/ sq->push = sq_push; sq->pop = sq_pop; sq->poptop = sq_poptop; sq->remove = sq_remove; sq->gettop = sq_gettop; sq->settop = sq_settop; sq->reservestack = sq_reservestack; sq->cmp = sq_cmp; sq->move = sq_move; /*object creation handling*/ sq->newuserdata = sq_newuserdata; sq->newtable = sq_newtable; sq->newarray = sq_newarray; sq->newclosure = sq_newclosure; sq->setparamscheck = sq_setparamscheck; sq->bindenv = sq_bindenv; sq->pushstring = sq_pushstring; sq->pushfloat = sq_pushfloat; sq->pushinteger = sq_pushinteger; sq->pushbool = sq_pushbool; sq->pushuserpointer = sq_pushuserpointer; sq->pushnull = sq_pushnull; sq->gettype = sq_gettype; sq->getsize = sq_getsize; sq->getbase = sq_getbase; sq->instanceof = sq_instanceof; sq->tostring = sq_tostring; sq->tobool = sq_tobool; sq->getstring = sq_getstring; sq->getinteger = sq_getinteger; sq->getthread = sq_getthread; sq->getbool = sq_getbool; sq->getuserpointer = sq_getuserpointer; sq->getuserdata = sq_getuserdata; sq->settypetag = sq_settypetag; sq->gettypetag = sq_gettypetag; sq->setreleasehook = sq_setreleasehook; sq->getscratchpad = sq_getscratchpad; sq->getclosureinfo = sq_getclosureinfo; sq->setnativeclosurename = sq_setnativeclosurename; sq->setinstanceup = sq_setinstanceup; sq->getinstanceup = sq_getinstanceup; sq->setclassudsize = sq_setclassudsize; sq->newclass = sq_newclass; sq->createinstance = sq_createinstance; sq->setattributes = sq_setattributes; sq->getattributes = sq_getattributes; sq->getclass = sq_getclass; sq->weakref = sq_weakref; sq->getdefaultdelegate = sq_getdefaultdelegate; /*object manipulation*/ sq->pushroottable = sq_pushroottable; sq->pushregistrytable = sq_pushregistrytable; sq->pushconsttable = sq_pushconsttable; sq->setroottable = sq_setroottable; sq->setconsttable = sq_setconsttable; sq->newslot = sq_newslot; sq->deleteslot = sq_deleteslot; sq->set = sq_set; sq->get = sq_get; sq->rawset = sq_rawset; sq->rawget = sq_rawget; sq->rawdeleteslot = sq_rawdeleteslot; sq->arrayappend = sq_arrayappend; sq->arraypop = sq_arraypop; sq->arrayresize = sq_arrayresize; sq->arrayreverse = sq_arrayreverse; sq->arrayremove = sq_arrayremove; sq->arrayinsert = sq_arrayinsert; sq->setdelegate = sq_setdelegate; sq->getdelegate = sq_getdelegate; sq->clone = sq_clone; sq->setfreevariable = sq_setfreevariable; sq->next = sq_next; sq->getweakrefval = sq_getweakrefval; sq->clear = sq_clear; /*calls*/ sq->call = sq_call; sq->resume = sq_resume; sq->getlocal = sq_getlocal; sq->getfreevariable = sq_getfreevariable; sq->throwerror = sq_throwerror; sq->reseterror = sq_reseterror; sq->getlasterror = sq_getlasterror; /*raw object handling*/ sq->getstackobj = sq_getstackobj; sq->pushobject = sq_pushobject; sq->addref = sq_addref; sq->release = sq_release; sq->resetobject = sq_resetobject; sq->objtostring = sq_objtostring; sq->objtobool = sq_objtobool; sq->objtointeger = sq_objtointeger; sq->objtofloat = sq_objtofloat; sq->getobjtypetag = sq_getobjtypetag; /*GC*/ sq->collectgarbage = sq_collectgarbage; /*serialization*/ sq->writeclosure = sq_writeclosure; sq->readclosure = sq_readclosure; /*mem allocation*/ sq->malloc = sq_malloc; sq->realloc = sq_realloc; sq->free = sq_free; /*debug*/ sq->stackinfos = sq_stackinfos; sq->setdebughook = sq_setdebughook; /*stdlib*/ sq->getblob = sqstd_getblob; return sq; } static SQRESULT sqrat_importscript(HSQUIRRELVM v, const SQChar* filename) { if(SQ_FAILED(sqstd_loadfile(v, filename, true))) { return SQ_ERROR; } sq_push(v, -2); sq_call(v, 1, false, true); return SQ_OK; } static SQRESULT sqrat_importbin(HSQUIRRELVM v, const SQChar* moduleName) { #ifdef SQUNICODE #warning sqrat_importbin() Not Implemented return SQ_ERROR; #else SQMODULELOAD modLoad = 0; #if defined(_WIN32) HMODULE mod; mod = LoadLibrary(moduleName); if (mod == NULL) return sq_throwerror(v, _SC("Could not load module")); modLoad = (SQMODULELOAD)GetProcAddress(mod, "sqmodule_load"); if(modLoad == NULL) { FreeLibrary(mod); return sq_throwerror(v, _SC("Could not get module init routine")); } #elif defined(__unix) void *mod = dlopen(moduleName, RTLD_NOW | RTLD_LOCAL); if (mod == NULL) return sq_throwerror(v, _SC("Could not load module")); modLoad = (SQMODULELOAD)dlsym(mod, "sqmodule_load"); if (modLoad == NULL) { dlclose(mod); return sq_throwerror(v, _SC("Could not get module init routine")); } #endif if(sqapi == NULL) { sqapi = sqrat_newapi(); // Caching this for multiple imports is probably a very good idea } SQRESULT res = modLoad(v, sqapi); return res; #endif } bool file_exists(const SQChar* filename) { return access(filename, F_OK) == 0; } #define NOT_FOUND 100 SQRESULT try_import_path(HSQUIRRELVM v, std::basic_string<SQChar>& fname) { // Try to import module at given path. This tries // different module types in order. // Check binary module fname[fname.size() - 1] = 'd'; if (file_exists(fname.c_str())) return sqrat_importbin(v, fname.c_str()); // Check bytecode module fname[fname.size() - 1] = 'c'; if (file_exists(fname.c_str())) return sqrat_importscript(v, fname.c_str()); // Check source module fname[fname.size() - 1] = 't'; if (file_exists(fname.c_str())) return sqrat_importscript(v, fname.c_str()); return NOT_FOUND; } SQInteger sq_import(HSQUIRRELVM v) { const SQChar* moduleName; HSQOBJECT table; HSQOBJECT mod; SQRESULT res = SQ_OK; sq_getstring(v, -2, &moduleName); // module name may be gone behind our back as we reset stack sq_getstackobj(v, -2, &mod); sq_addref(v, &mod); sq_getstackobj(v, -1, &table); sq_addref(v, &table); sq_settop(v, 0); // Clear Stack sq_pushobject(v, table); // Push the target table onto the stack std::basic_string<SQChar> fname; // Explicit path is needed for dlopen() later, and won't hurt // for other cases fname = "./"; fname += moduleName; fname += ".nut"; res = try_import_path(v, fname); if (res == NOT_FOUND) { const char *path = getenv("SQPATH"); if (path) fname = path; else { path = getenv("HOME"); if (path) { fname = path; fname += "/.squirrel/lib"; } else { fname = "/usr/lib/squirrel"; } } fname += "/"; fname += moduleName; fname += ".nut"; res = try_import_path(v, fname); if (res == NOT_FOUND) { sq_settop(v, 0); // Clean up the stack (just in case the module load leaves it messy) sq_release(v, &table); sq_release(v, &mod); return sq_throwerror(v, _SC("Module not found")); } } sq_settop(v, 0); // Clean up the stack (just in case the module load leaves it messy) sq_pushobject(v, table); // return the target table sq_release(v, &table); sq_release(v, &mod); // If we didn't thro exception, then we return value if (res != SQ_ERROR) return 1; } static SQInteger sqratbase_import(HSQUIRRELVM v) { SQInteger args = sq_gettop(v); switch(args) { case 2: sq_pushroottable(v); break; case 3: // should already have the desired table pushed onto the stack break; default: // Error, unexpected number of arguments break; } return sq_import(v); } SQRESULT sqrat_register_importlib(HSQUIRRELVM v) { sq_pushroottable(v); sq_pushstring(v, _SC("_import_"), -1); sq_newclosure(v, &sqratbase_import, 0); sq_newslot(v, -3, 0); sq_pop(v, 1); // pop sqrat table return SQ_OK; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 1992-2009 Nokia. All rights reserved. ** ** This file is part of Qt Jambi. ** ** ** $BEGIN_LICENSE$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $END_LICENSE$ ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ****************************************************************************/ #include "asttoxml.h" #include "control.h" #include "parser.h" #include "binder.h" #include <QXmlStreamWriter> #include <QTextStream> #include <QTextCodec> #include <QFile> void astToXML(QString name) { QFile file(name); if (!file.open(QFile::ReadOnly)) return; QTextStream stream(&file); stream.setCodec(QTextCodec::codecForName("UTF-8")); QByteArray contents = stream.readAll().toUtf8(); file.close(); Control control; Parser p(&control); pool __pool; TranslationUnitAST *ast = p.parse(contents, contents.size(), &__pool); CodeModel model; Binder binder(&model, p.location()); FileModelItem dom = binder.run(ast); QFile outputFile; if (!outputFile.open(stdout, QIODevice::WriteOnly)) { return; } QXmlStreamWriter s(&outputFile); s.setAutoFormatting(true); s.writeStartElement("code"); QHash<QString, NamespaceModelItem> namespaceMap = dom->namespaceMap(); foreach(NamespaceModelItem item, namespaceMap.values()) { writeOutNamespace(s, item); } QHash<QString, ClassModelItem> typeMap = dom->classMap(); foreach(ClassModelItem item, typeMap.values()) { writeOutClass(s, item); } s.writeEndElement(); } QLatin1String propDecls[] = { QLatin1String("READ"), QLatin1String("WRITE"), QLatin1String("RESET"), QLatin1String("DESIGNABLE") }; void writeOutNamespace(QXmlStreamWriter &s, NamespaceModelItem &item) { s.writeStartElement("namespace"); s.writeAttribute("name", item->name()); QHash<QString, NamespaceModelItem> namespaceMap = item->namespaceMap(); foreach(NamespaceModelItem item, namespaceMap.values()) { writeOutNamespace(s, item); } QHash<QString, ClassModelItem> typeMap = item->classMap(); foreach(ClassModelItem item, typeMap.values()) { writeOutClass(s, item); } QHash<QString, EnumModelItem> enumMap = item->enumMap(); foreach(EnumModelItem item, enumMap.values()) { writeOutEnum(s, item); } s.writeEndElement(); } void writeOutEnum(QXmlStreamWriter &s, EnumModelItem &item) { QString qualified_name = item->qualifiedName().join("::"); s.writeStartElement("enum"); if (item->isAnonymous()) s.writeEmptyElement("anonymous"); else s.writeAttribute("name", qualified_name); s.writeStartElement("accessPolicy"); switch (item->accessPolicy()) { case CodeModel::Public: s.writeAttribute("value","public"); break; case CodeModel::Private: s.writeAttribute("value","private"); break; case CodeModel::Protected: s.writeAttribute("value","protected"); break; } s.writeEndElement(); EnumeratorList enumList = item->enumerators(); for (int i = 0; i < enumList.size() ; i++) { s.writeStartElement("enumerator"); if (!enumList[i]->value().isEmpty()) s.writeAttribute("value", enumList[i]->value()); s.writeCharacters(enumList[i]->name()); s.writeEndElement(); } s.writeEndElement(); } void writeOutFunction(QXmlStreamWriter &s, const QString &classname, FunctionModelItem &item) { QString name = item.constData()->name(); bool noPrintReturn = false; if (item->functionType() == CodeModel::Signal) s.writeStartElement("signal"); else if (item->functionType() == CodeModel::Slot) s.writeStartElement("slot"); else if (name == QString("~%1").arg(classname) ) { s.writeStartElement("destructor"); noPrintReturn = true; } else if (name == classname) { s.writeStartElement("constructor"); noPrintReturn = true; } else s.writeStartElement("function"); s.writeAttribute("name", name); s.writeStartElement("accessPolicy"); switch (item->accessPolicy()) { case CodeModel::Public: s.writeAttribute("value","public"); break; case CodeModel::Private: s.writeAttribute("value","private"); break; case CodeModel::Protected: s.writeAttribute("value","protected"); break; } s.writeEndElement(); s.writeStartElement("modifiers"); if (item->isAbstract()) s.writeEmptyElement("abstract"); if (item->isVirtual()) s.writeEmptyElement("virtual"); if (item->isStatic()) s.writeEmptyElement("static"); s.writeEndElement(); ArgumentList arguments = item->arguments(); s.writeStartElement("arguments"); foreach (const CodeModelPointer<_ArgumentModelItem> arg, arguments) { s.writeStartElement("argument"); if (arg->defaultValue()) s.writeAttribute("default", arg->defaultValueExpression()); writeType(s, arg->type()); s.writeEndElement(); } s.writeEndElement(); if (!noPrintReturn) { s.writeStartElement("return"); writeType(s, item->type()); s.writeEndElement(); } s.writeEndElement(); } void writeType(QXmlStreamWriter &s, const TypeInfo &t) { s.writeAttribute("type", t.qualifiedName().join("::")); s.writeAttribute("indirections", QString("%1").arg(t.indirections()) ); s.writeAttribute("isReference", t.isReference() ? "true" : "false"); s.writeAttribute("isConstant", t.isConstant() ? "true" : "false"); s.writeAttribute("isFunctionPointer", t.isFunctionPointer() ? "true" : "false"); s.writeStartElement("arguments"); foreach (const TypeInfo tt, t.arguments()) { writeType(s, tt); } s.writeEndElement(); } void writeOutClass(QXmlStreamWriter &s, ClassModelItem &item) { QString qualified_name = item->name(); s.writeStartElement("class"); s.writeAttribute("name", qualified_name); QStringList bases = item.constData()->baseClasses(); s.writeStartElement("inherits"); foreach (const QString &c, bases) { s.writeStartElement("class"); s.writeAttribute("name",c); s.writeEndElement(); } s.writeEndElement(); QHash<QString, EnumModelItem> enumMap = item->enumMap(); foreach(EnumModelItem item, enumMap.values()) { writeOutEnum(s, item); } QHash<QString, FunctionModelItem> functionMap = item->functionMap(); foreach(FunctionModelItem item, functionMap.values()) { writeOutFunction(s, qualified_name, item); } QHash<QString, ClassModelItem> typeMap = item->classMap(); foreach(ClassModelItem item, typeMap.values()) { writeOutClass(s, item); } QStringList propDecls = item.constData()->propertyDeclarations(); foreach(const QString &p, propDecls) { writeOutProperty(s, p); } s.writeEndElement(); } void writeOutProperty(QXmlStreamWriter &s, const QString &p) { QStringList l = p.split(QLatin1String(" ")); s.writeStartElement("property"); s.writeAttribute("name",l.at(1)); int propCount = sizeof(propDecls) / sizeof(QLatin1String); for (int pos = 2; pos + 1 < l.size(); pos += 2) { for (int i=0; i<propCount; ++i) { if (l.at(pos) == propDecls[i]) { writeHelper(s, propDecls[i], l.at(pos + 1) ); break; } } } s.writeEndElement(); } void writeHelper(QXmlStreamWriter &s, const QLatin1String &k, const QString &v) { s.writeStartElement(QString(k).toLower()); s.writeAttribute("value", v); s.writeEndElement(); } <commit_msg>(split) formatting cleanup<commit_after>/**************************************************************************** ** ** Copyright (C) 1992-2009 Nokia. All rights reserved. ** ** This file is part of Qt Jambi. ** ** ** $BEGIN_LICENSE$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $END_LICENSE$ ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ****************************************************************************/ #include "asttoxml.h" #include "control.h" #include "parser.h" #include "binder.h" #include <QXmlStreamWriter> #include <QTextStream> #include <QTextCodec> #include <QFile> void astToXML(QString name) { QFile file(name); if (!file.open(QFile::ReadOnly)) return; QTextStream stream(&file); stream.setCodec(QTextCodec::codecForName("UTF-8")); QByteArray contents = stream.readAll().toUtf8(); file.close(); Control control; Parser p(&control); pool __pool; TranslationUnitAST *ast = p.parse(contents, contents.size(), &__pool); CodeModel model; Binder binder(&model, p.location()); FileModelItem dom = binder.run(ast); QFile outputFile; if (!outputFile.open(stdout, QIODevice::WriteOnly)) { return; } QXmlStreamWriter s(&outputFile); s.setAutoFormatting(true); s.writeStartElement("code"); QHash<QString, NamespaceModelItem> namespaceMap = dom->namespaceMap(); foreach(NamespaceModelItem item, namespaceMap.values()) { writeOutNamespace(s, item); } QHash<QString, ClassModelItem> typeMap = dom->classMap(); foreach(ClassModelItem item, typeMap.values()) { writeOutClass(s, item); } s.writeEndElement(); } QLatin1String propDecls[] = { QLatin1String("READ"), QLatin1String("WRITE"), QLatin1String("RESET"), QLatin1String("DESIGNABLE") }; void writeOutNamespace(QXmlStreamWriter &s, NamespaceModelItem &item) { s.writeStartElement("namespace"); s.writeAttribute("name", item->name()); QHash<QString, NamespaceModelItem> namespaceMap = item->namespaceMap(); foreach(NamespaceModelItem item, namespaceMap.values()) { writeOutNamespace(s, item); } QHash<QString, ClassModelItem> typeMap = item->classMap(); foreach(ClassModelItem item, typeMap.values()) { writeOutClass(s, item); } QHash<QString, EnumModelItem> enumMap = item->enumMap(); foreach(EnumModelItem item, enumMap.values()) { writeOutEnum(s, item); } s.writeEndElement(); } void writeOutEnum(QXmlStreamWriter &s, EnumModelItem &item) { QString qualified_name = item->qualifiedName().join("::"); s.writeStartElement("enum"); if (item->isAnonymous()) { s.writeEmptyElement("anonymous"); } else { s.writeAttribute("name", qualified_name); } s.writeStartElement("accessPolicy"); switch (item->accessPolicy()) { case CodeModel::Public: s.writeAttribute("value", "public"); break; case CodeModel::Private: s.writeAttribute("value", "private"); break; case CodeModel::Protected: s.writeAttribute("value", "protected"); break; } s.writeEndElement(); EnumeratorList enumList = item->enumerators(); for (int i = 0; i < enumList.size() ; i++) { s.writeStartElement("enumerator"); if (!enumList[i]->value().isEmpty()) { s.writeAttribute("value", enumList[i]->value()); } s.writeCharacters(enumList[i]->name()); s.writeEndElement(); } s.writeEndElement(); } void writeOutFunction(QXmlStreamWriter &s, const QString &classname, FunctionModelItem &item) { QString name = item.constData()->name(); bool noPrintReturn = false; if (item->functionType() == CodeModel::Signal) { s.writeStartElement("signal"); } else if (item->functionType() == CodeModel::Slot) { s.writeStartElement("slot"); } else if (name == QString("~%1").arg(classname) ) { s.writeStartElement("destructor"); noPrintReturn = true; } else if (name == classname) { s.writeStartElement("constructor"); noPrintReturn = true; } else { s.writeStartElement("function"); } s.writeAttribute("name", name); s.writeStartElement("accessPolicy"); switch (item->accessPolicy()) { case CodeModel::Public: s.writeAttribute("value","public"); break; case CodeModel::Private: s.writeAttribute("value","private"); break; case CodeModel::Protected: s.writeAttribute("value","protected"); break; } s.writeEndElement(); s.writeStartElement("modifiers"); if (item->isAbstract()) { s.writeEmptyElement("abstract"); } if (item->isVirtual()) { s.writeEmptyElement("virtual"); } if (item->isStatic()) { s.writeEmptyElement("static"); } s.writeEndElement(); ArgumentList arguments = item->arguments(); s.writeStartElement("arguments"); foreach (const CodeModelPointer<_ArgumentModelItem> arg, arguments) { s.writeStartElement("argument"); if (arg->defaultValue()) s.writeAttribute("default", arg->defaultValueExpression()); writeType(s, arg->type()); s.writeEndElement(); } s.writeEndElement(); if (!noPrintReturn) { s.writeStartElement("return"); writeType(s, item->type()); s.writeEndElement(); } s.writeEndElement(); } void writeType(QXmlStreamWriter &s, const TypeInfo &t) { s.writeAttribute("type", t.qualifiedName().join("::")); s.writeAttribute("indirections", QString("%1").arg(t.indirections()) ); s.writeAttribute("isReference", t.isReference() ? "true" : "false"); s.writeAttribute("isConstant", t.isConstant() ? "true" : "false"); s.writeAttribute("isFunctionPointer", t.isFunctionPointer() ? "true" : "false"); s.writeStartElement("arguments"); foreach (const TypeInfo tt, t.arguments()) { writeType(s, tt); } s.writeEndElement(); } void writeOutClass(QXmlStreamWriter &s, ClassModelItem &item) { QString qualified_name = item->name(); s.writeStartElement("class"); s.writeAttribute("name", qualified_name); QStringList bases = item.constData()->baseClasses(); s.writeStartElement("inherits"); foreach (const QString &c, bases) { s.writeStartElement("class"); s.writeAttribute("name", c); s.writeEndElement(); } s.writeEndElement(); QHash<QString, EnumModelItem> enumMap = item->enumMap(); foreach(EnumModelItem item, enumMap.values()) { writeOutEnum(s, item); } QHash<QString, FunctionModelItem> functionMap = item->functionMap(); foreach(FunctionModelItem item, functionMap.values()) { writeOutFunction(s, qualified_name, item); } QHash<QString, ClassModelItem> typeMap = item->classMap(); foreach(ClassModelItem item, typeMap.values()) { writeOutClass(s, item); } QStringList propDecls = item.constData()->propertyDeclarations(); foreach(const QString &p, propDecls) { writeOutProperty(s, p); } s.writeEndElement(); } void writeOutProperty(QXmlStreamWriter &s, const QString &p) { QStringList l = p.split(QLatin1String(" ")); s.writeStartElement("property"); s.writeAttribute("name", l.at(1)); int propCount = sizeof(propDecls) / sizeof(QLatin1String); for (int pos = 2; pos + 1 < l.size(); pos += 2) { for (int i=0; i<propCount; ++i) { if (l.at(pos) == propDecls[i]) { writeHelper(s, propDecls[i], l.at(pos + 1) ); break; } } } s.writeEndElement(); } void writeHelper(QXmlStreamWriter &s, const QLatin1String &k, const QString &v) { s.writeStartElement(QString(k).toLower()); s.writeAttribute("value", v); s.writeEndElement(); } <|endoftext|>
<commit_before>/* * Copyright (C) 2004-2010 See the AUTHORS file for details. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. */ #include "Chan.h" #include "HTTPSock.h" #include "Server.h" #include "Template.h" #include "User.h" #include "znc.h" #include "WebModules.h" #include <sstream> using std::stringstream; class CNotesMod : public CModule { public: MODCONSTRUCTOR(CNotesMod) { } virtual ~CNotesMod() { } virtual bool OnLoad(const CString& sArgStr, CString& sMessage) { return true; } virtual CString GetWebMenuTitle() { return "Notes"; } virtual void OnClientLogin() { ListNotes(true); } virtual EModRet OnUserRaw(CString& sLine) { if (sLine.Left(1) != "#") { return CONTINUE; } CString sKey; bool bOverwrite = false; if (sLine == "#?") { ListNotes(true); } else if (sLine.Left(2) == "#-") { sKey = sLine.Token(0).LeftChomp_n(2); if (DelNote(sKey)) { PutModNotice("Deleted note [" + sKey + "]"); } else { PutModNotice("Unable to delete note [" + sKey + "]"); } } else if (sLine.Left(2) == "#+") { sKey = sLine.Token(0).LeftChomp_n(2); bOverwrite = true; } else if (sLine.Left(1) == "#") { sKey = sLine.Token(0).LeftChomp_n(1); } CString sValue(sLine.Token(1, true)); if (!sKey.empty()) { if (!bOverwrite && !GetNV(sKey).empty()) { PutModNotice("That note already exists. Use /#+<key> <note> to overwrite."); } else if (AddNote(sKey, sValue)) { if (!bOverwrite) { PutModNotice("Added note [" + sKey + "]"); } else { PutModNotice("Set note for [" + sKey + "]"); } } else { PutModNotice("Unable to add note [" + sKey + "]"); } } return HALT; } bool DelNote(const CString& sKey) { return DelNV(sKey); } bool AddNote(const CString& sKey, const CString& sNote) { if (sKey.empty()) { return false; } return SetNV(sKey, sNote); } void ListNotes(bool bNotice = false) { CClient* pClient = GetClient(); if (pClient) { CTable Table; Table.AddColumn("Key"); Table.AddColumn("Note"); for (MCString::iterator it = BeginNV(); it != EndNV(); ++it) { Table.AddRow(); Table.SetCell("Key", it->first); Table.SetCell("Note", it->second); } if (Table.size()) { unsigned int idx = 0; CString sLine; while (Table.GetLine(idx++, sLine)) { if (bNotice) { pClient->PutModNotice(GetModName(), sLine); } else { pClient->PutModule(GetModName(), sLine); } } } else { if (bNotice) { PutModNotice("You have no entries."); } else { PutModule("You have no entries."); } } } } virtual void OnModCommand(const CString& sLine) { CString sCmd(sLine.Token(0)); if (sLine.Equals("LIST")) { ListNotes(); } else if (sCmd.Equals("ADD")) { CString sKey(sLine.Token(1)); CString sValue(sLine.Token(2, true)); if (!GetNV(sKey).empty()) { PutModule("That note already exists. Use MOD <key> <note> to overwrite."); } else if (AddNote(sKey, sValue)) { PutModule("Added note [" + sKey + "]"); } else { PutModule("Unable to add note [" + sKey + "]"); } } else if (sCmd.Equals("MOD")) { CString sKey(sLine.Token(1)); CString sValue(sLine.Token(2, true)); if (AddNote(sKey, sValue)) { PutModule("Set note for [" + sKey + "]"); } else { PutModule("Unable to add note [" + sKey + "]"); } } else if (sCmd.Equals("DEL")) { CString sKey(sLine.Token(1)); if (DelNote(sKey)) { PutModule("Deleted note [" + sKey + "]"); } else { PutModule("Unable to delete note [" + sKey + "]"); } } else { PutModule("Commands are: Help, List, Add <key> <note>, Del <key>, Mod <key> <note>"); } } virtual bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) { if (sPageName.empty() || sPageName == "index") { for (MCString::iterator it = BeginNV(); it != EndNV(); ++it) { CTemplate& Row = Tmpl.AddRow("NotesLoop"); Row["Key"] = it->first; Row["Note"] = it->second; } return true; } else if (sPageName == "delnote") { DelNote(WebSock.GetParam("key")); WebSock.Redirect("/mods/notes/"); return true; } else if (sPageName == "addnote") { AddNote(WebSock.GetParam("key"), WebSock.GetParam("note")); WebSock.Redirect("/mods/notes/"); return true; } return false; } }; MODULEDEFS(CNotesMod, "Keep and replay notes") <commit_msg>Fixed GetParam call in the notes module.<commit_after>/* * Copyright (C) 2004-2010 See the AUTHORS file for details. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. */ #include "Chan.h" #include "HTTPSock.h" #include "Server.h" #include "Template.h" #include "User.h" #include "znc.h" #include "WebModules.h" #include <sstream> using std::stringstream; class CNotesMod : public CModule { public: MODCONSTRUCTOR(CNotesMod) { } virtual ~CNotesMod() { } virtual bool OnLoad(const CString& sArgStr, CString& sMessage) { return true; } virtual CString GetWebMenuTitle() { return "Notes"; } virtual void OnClientLogin() { ListNotes(true); } virtual EModRet OnUserRaw(CString& sLine) { if (sLine.Left(1) != "#") { return CONTINUE; } CString sKey; bool bOverwrite = false; if (sLine == "#?") { ListNotes(true); } else if (sLine.Left(2) == "#-") { sKey = sLine.Token(0).LeftChomp_n(2); if (DelNote(sKey)) { PutModNotice("Deleted note [" + sKey + "]"); } else { PutModNotice("Unable to delete note [" + sKey + "]"); } } else if (sLine.Left(2) == "#+") { sKey = sLine.Token(0).LeftChomp_n(2); bOverwrite = true; } else if (sLine.Left(1) == "#") { sKey = sLine.Token(0).LeftChomp_n(1); } CString sValue(sLine.Token(1, true)); if (!sKey.empty()) { if (!bOverwrite && !GetNV(sKey).empty()) { PutModNotice("That note already exists. Use /#+<key> <note> to overwrite."); } else if (AddNote(sKey, sValue)) { if (!bOverwrite) { PutModNotice("Added note [" + sKey + "]"); } else { PutModNotice("Set note for [" + sKey + "]"); } } else { PutModNotice("Unable to add note [" + sKey + "]"); } } return HALT; } bool DelNote(const CString& sKey) { return DelNV(sKey); } bool AddNote(const CString& sKey, const CString& sNote) { if (sKey.empty()) { return false; } return SetNV(sKey, sNote); } void ListNotes(bool bNotice = false) { CClient* pClient = GetClient(); if (pClient) { CTable Table; Table.AddColumn("Key"); Table.AddColumn("Note"); for (MCString::iterator it = BeginNV(); it != EndNV(); ++it) { Table.AddRow(); Table.SetCell("Key", it->first); Table.SetCell("Note", it->second); } if (Table.size()) { unsigned int idx = 0; CString sLine; while (Table.GetLine(idx++, sLine)) { if (bNotice) { pClient->PutModNotice(GetModName(), sLine); } else { pClient->PutModule(GetModName(), sLine); } } } else { if (bNotice) { PutModNotice("You have no entries."); } else { PutModule("You have no entries."); } } } } virtual void OnModCommand(const CString& sLine) { CString sCmd(sLine.Token(0)); if (sLine.Equals("LIST")) { ListNotes(); } else if (sCmd.Equals("ADD")) { CString sKey(sLine.Token(1)); CString sValue(sLine.Token(2, true)); if (!GetNV(sKey).empty()) { PutModule("That note already exists. Use MOD <key> <note> to overwrite."); } else if (AddNote(sKey, sValue)) { PutModule("Added note [" + sKey + "]"); } else { PutModule("Unable to add note [" + sKey + "]"); } } else if (sCmd.Equals("MOD")) { CString sKey(sLine.Token(1)); CString sValue(sLine.Token(2, true)); if (AddNote(sKey, sValue)) { PutModule("Set note for [" + sKey + "]"); } else { PutModule("Unable to add note [" + sKey + "]"); } } else if (sCmd.Equals("DEL")) { CString sKey(sLine.Token(1)); if (DelNote(sKey)) { PutModule("Deleted note [" + sKey + "]"); } else { PutModule("Unable to delete note [" + sKey + "]"); } } else { PutModule("Commands are: Help, List, Add <key> <note>, Del <key>, Mod <key> <note>"); } } virtual bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, CTemplate& Tmpl) { if (sPageName.empty() || sPageName == "index") { for (MCString::iterator it = BeginNV(); it != EndNV(); ++it) { CTemplate& Row = Tmpl.AddRow("NotesLoop"); Row["Key"] = it->first; Row["Note"] = it->second; } return true; } else if (sPageName == "delnote") { DelNote(WebSock.GetParam("key", false)); WebSock.Redirect("/mods/notes/"); return true; } else if (sPageName == "addnote") { AddNote(WebSock.GetParam("key"), WebSock.GetParam("note")); WebSock.Redirect("/mods/notes/"); return true; } return false; } }; MODULEDEFS(CNotesMod, "Keep and replay notes") <|endoftext|>
<commit_before>#include <assert.h> #include <iomanip> #include <iostream> #include "Actor.h" #include "Dir.h" #include "dLog.h" #include "Node.h" #include "Player.h" #include "utils.h" int Maps::Node::nodeCount = 1; namespace Maps { Node::Node(): inventory(Inventory{ "Location Inventory", 8 }) , nodeLinks{nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr} , actorPtrList{} , name("Node") { setID(0); for (int i = 0; i < Maps::numDirs; i++) { entranceDirs[i] = true; } entranceDirs[Dir::Down] = false; // Entrances in all dirs != down name += to_string(nodeCount); nodeCount++; } Node::~Node() { dLog << "Maps::Node::~Node() called for Node: " << name << std::endl; // Delete all the actors for (auto it = actorPtrList.begin(); it != actorPtrList.end(); ++it ) { dLog << "Deleting actor: " << (*it) << " from actor list in node: " << name << std::endl; delete (*it); } } Actor* Node::getActorPtr( int index ) { assert(0 <= index && index <= actorPtrList.size()); auto it = actorPtrList.begin(); if ( index >= actorPtrList.size() ) { index = actorPtrList.size(); } std::advance(it, index); return *it; } void Node::activate() { dLog << "Node: " << name << " activated" << std::endl; for (auto it = actorPtrList.begin(); it != actorPtrList.end(); ++it ) { // Going through list of actors dLog << "Taking turn for " << (*it)->getName() << std::endl; if ( (*it)->getIsLiving() || (*it)->getIsPlayer() ) // getIsPlayer() allows special behavior for players { (*it)->takeTurn(); } else // If it is dead and not the player, we want to drop its inventory to the node { // Drop inventory (*it)->dropAllItems(); } } moveActors(); // TODO: The map should call this after activating all nodes in map } void Node::showNavigationInfo() { bool noDirs{true}; if (entranceDirs[Dir::North] && nodeLinks[Dir::North] != nullptr) { showNavigationInfoForNode(Dir::North); std::cout << std::endl; noDirs = false; } if (entranceDirs[Dir::East] && nodeLinks[Dir::East] != nullptr) { showNavigationInfoForNode(Dir::East); std::cout << std::endl; noDirs = false; } if (entranceDirs[Dir::West] && nodeLinks[Dir::West] != nullptr) { showNavigationInfoForNode(Dir::West); std::cout << std::endl; noDirs = false; } if (entranceDirs[Dir::South] && nodeLinks[Dir::South] != nullptr) { showNavigationInfoForNode(Dir::South); std::cout << std::endl; noDirs = false; } if (entranceDirs[Dir::Up] && nodeLinks[Dir::Up] != nullptr) { showNavigationInfoForNode(Dir::Up); std::cout << std::endl; noDirs = false; } if (entranceDirs[Dir::Down] && nodeLinks[Dir::Down] != nullptr) { showNavigationInfoForNode(Dir::Down); std::cout << std::endl; noDirs = false; } if (noDirs) { std::cout << "You cannot leave this area." << std::endl; } } void Node::showNavigationInfoForNode(int dir) { assert(0 < dir && dir < numDirs); std::cout << std::setw(COLUMN_PADDING) << std::right << dir << ": "; std::cout << Maps::dirName(dir) << " to " << nodeLinks[dir]->getName(); // Check to see if the node can accept entry from this direction bool canGoInDir = nodeLinks[dir]->getEntranceDir(oppositeDir(dir)); if (!canGoInDir) { std::cout << " <Inaccessible>"; } } void Node::setNodeLink(int dir, Node* link) { this->nodeLinks[dir] = link; } void Node::addActor(Actor *actor) { actor->setCurrentNode(this); actorPtrList.insert(actorPtrList.end(), actor); } void Node::moveActors() { auto it = actorPtrList.begin(); while (it != actorPtrList.end()) { Actor &actor = **it; int dir = actor.getMoveDir(); std::list<Actor*> &otherList = nodeLinks[dir]->actorPtrList; // TODO: Make canMoveInDir(DIR) function if ((dir != Maps::Stop) && (nodeLinks[dir] != nullptr) && !nodeLinks[dir]->isWall()) { actor.onMove(); // Moving actor actor.setCurrentNode(nodeLinks[dir]); auto actorToMove = it; it++; // Moves otherList.splice(otherList.begin(), actorPtrList, actorToMove); } else { it++; } } } std::string Node::getName() { return name; } void Node::showActors() { int i(0); for (auto it = actorPtrList.begin(); it != actorPtrList.end(); ++it) { // Number the list std::cout << std::setw(COLUMN_PADDING) << std::left << ++i << ": "; // Display information about the creature. (*it)->displayHUDLine(); std::cout << std::endl; } } int Node::getNumActors() { return actorPtrList.size(); } void Node::setEntranceDir(int dir, bool isEntrance) { assert(0 <= dir && dir < Maps::numDirs); entranceDirs[dir] = isEntrance; } bool Node::canMoveInDir(int dir) { assert(0 <= dir < numDirs); bool nodeInDirExists = nodeLinks[dir] != nullptr; bool entrancesExist = false; if (nodeInDirExists) { entrancesExist = getEntranceDir(dir) && nodeLinks[dir]->getEntranceDir(Maps::oppositeDir(dir)); } return entrancesExist; } bool Node::getEntranceDir(int dir) { assert(0 <= dir < numDirs); return entranceDirs[dir]; } bool Node::containsActor(Actor* actor) { bool actorFound = false; for (auto i = actorPtrList.begin(); i != actorPtrList.end() && !actorFound; i++) { actorFound = actor == *i; } return actorFound; } Actor* Node::getNextActor(Actor* actor) { assert(actorPtrList.size() > 0); Actor* nextActor = nullptr; bool actorFound = false; // If the actorPtrList is of size one, return actor actorFound = actorPtrList.size() == 1; // Iterate to actor auto i = actorPtrList.begin(); while (i != actorPtrList.end() && !actorFound && (actor != nullptr)) { actorFound = *i == actor; i++; } nextActor = i == actorPtrList.end() ? *actorPtrList.begin() : *i; return nextActor; } pairType Node::toXML() { using namespace boost::property_tree; ptree tree; tree.push_back(inventory.toXML()); // Add node type for (Actor* actor : actorPtrList) { tree.push_back(actor->toXML()); } return ptree::value_type("Node", tree); } void Node::fromXML(const pairType &p) { } } <commit_msg>Node fromXML<commit_after>#include <assert.h> #include <iomanip> #include <iostream> #include "Actor.h" #include "Dir.h" #include "dLog.h" #include "Factory.h" #include "Node.h" #include "Player.h" #include "utils.h" int Maps::Node::nodeCount = 1; namespace Maps { Node::Node(): inventory(Inventory{ "Location Inventory", 8 }) , nodeLinks{nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr} , actorPtrList{} , name("Node") { setID(0); for (int i = 0; i < Maps::numDirs; i++) { entranceDirs[i] = true; } entranceDirs[Dir::Down] = false; // Entrances in all dirs != down name += to_string(nodeCount); nodeCount++; } Node::~Node() { dLog << "Maps::Node::~Node() called for Node: " << name << std::endl; // Delete all the actors for (auto it = actorPtrList.begin(); it != actorPtrList.end(); ++it ) { dLog << "Deleting actor: " << (*it) << " from actor list in node: " << name << std::endl; delete (*it); } } Actor* Node::getActorPtr( int index ) { assert(0 <= index && index <= actorPtrList.size()); auto it = actorPtrList.begin(); if ( index >= actorPtrList.size() ) { index = actorPtrList.size(); } std::advance(it, index); return *it; } void Node::activate() { dLog << "Node: " << name << " activated" << std::endl; for (auto it = actorPtrList.begin(); it != actorPtrList.end(); ++it ) { // Going through list of actors dLog << "Taking turn for " << (*it)->getName() << std::endl; if ( (*it)->getIsLiving() || (*it)->getIsPlayer() ) // getIsPlayer() allows special behavior for players { (*it)->takeTurn(); } else // If it is dead and not the player, we want to drop its inventory to the node { // Drop inventory (*it)->dropAllItems(); } } moveActors(); // TODO: The map should call this after activating all nodes in map } void Node::showNavigationInfo() { bool noDirs{true}; if (entranceDirs[Dir::North] && nodeLinks[Dir::North] != nullptr) { showNavigationInfoForNode(Dir::North); std::cout << std::endl; noDirs = false; } if (entranceDirs[Dir::East] && nodeLinks[Dir::East] != nullptr) { showNavigationInfoForNode(Dir::East); std::cout << std::endl; noDirs = false; } if (entranceDirs[Dir::West] && nodeLinks[Dir::West] != nullptr) { showNavigationInfoForNode(Dir::West); std::cout << std::endl; noDirs = false; } if (entranceDirs[Dir::South] && nodeLinks[Dir::South] != nullptr) { showNavigationInfoForNode(Dir::South); std::cout << std::endl; noDirs = false; } if (entranceDirs[Dir::Up] && nodeLinks[Dir::Up] != nullptr) { showNavigationInfoForNode(Dir::Up); std::cout << std::endl; noDirs = false; } if (entranceDirs[Dir::Down] && nodeLinks[Dir::Down] != nullptr) { showNavigationInfoForNode(Dir::Down); std::cout << std::endl; noDirs = false; } if (noDirs) { std::cout << "You cannot leave this area." << std::endl; } } void Node::showNavigationInfoForNode(int dir) { assert(0 < dir && dir < numDirs); std::cout << std::setw(COLUMN_PADDING) << std::right << dir << ": "; std::cout << Maps::dirName(dir) << " to " << nodeLinks[dir]->getName(); // Check to see if the node can accept entry from this direction bool canGoInDir = nodeLinks[dir]->getEntranceDir(oppositeDir(dir)); if (!canGoInDir) { std::cout << " <Inaccessible>"; } } void Node::setNodeLink(int dir, Node* link) { this->nodeLinks[dir] = link; } void Node::addActor(Actor *actor) { actor->setCurrentNode(this); actorPtrList.insert(actorPtrList.end(), actor); } void Node::moveActors() { auto it = actorPtrList.begin(); while (it != actorPtrList.end()) { Actor &actor = **it; int dir = actor.getMoveDir(); std::list<Actor*> &otherList = nodeLinks[dir]->actorPtrList; // TODO: Make canMoveInDir(DIR) function if ((dir != Maps::Stop) && (nodeLinks[dir] != nullptr) && !nodeLinks[dir]->isWall()) { actor.onMove(); // Moving actor actor.setCurrentNode(nodeLinks[dir]); auto actorToMove = it; it++; // Moves otherList.splice(otherList.begin(), actorPtrList, actorToMove); } else { it++; } } } std::string Node::getName() { return name; } void Node::showActors() { int i(0); for (auto it = actorPtrList.begin(); it != actorPtrList.end(); ++it) { // Number the list std::cout << std::setw(COLUMN_PADDING) << std::left << ++i << ": "; // Display information about the creature. (*it)->displayHUDLine(); std::cout << std::endl; } } int Node::getNumActors() { return actorPtrList.size(); } void Node::setEntranceDir(int dir, bool isEntrance) { assert(0 <= dir && dir < Maps::numDirs); entranceDirs[dir] = isEntrance; } bool Node::canMoveInDir(int dir) { assert(0 <= dir < numDirs); bool nodeInDirExists = nodeLinks[dir] != nullptr; bool entrancesExist = false; if (nodeInDirExists) { entrancesExist = getEntranceDir(dir) && nodeLinks[dir]->getEntranceDir(Maps::oppositeDir(dir)); } return entrancesExist; } bool Node::getEntranceDir(int dir) { assert(0 <= dir < numDirs); return entranceDirs[dir]; } bool Node::containsActor(Actor* actor) { bool actorFound = false; for (auto i = actorPtrList.begin(); i != actorPtrList.end() && !actorFound; i++) { actorFound = actor == *i; } return actorFound; } Actor* Node::getNextActor(Actor* actor) { assert(actorPtrList.size() > 0); Actor* nextActor = nullptr; bool actorFound = false; // If the actorPtrList is of size one, return actor actorFound = actorPtrList.size() == 1; // Iterate to actor auto i = actorPtrList.begin(); while (i != actorPtrList.end() && !actorFound && (actor != nullptr)) { actorFound = *i == actor; i++; } nextActor = i == actorPtrList.end() ? *actorPtrList.begin() : *i; return nextActor; } pairType Node::toXML() { using namespace boost::property_tree; ptree tree; tree.push_back(inventory.toXML()); // Add node type for (Actor* actor : actorPtrList) { tree.push_back(actor->toXML()); } return ptree::value_type("Node", tree); } void Node::fromXML(const pairType &p) { const treeType &tree = p.second; auto it = tree.begin(); const std::string &key = it->first; const std::string &data = it->second.data(); while (it != tree.end()) { if (key == "Actor") { addActor(Factory::newActor(*it)); } else if (key == "Inventory") { inventory.fromXML(*it); } it++; } } } <|endoftext|>
<commit_before>// The libMesh Finite Element Library. // Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Local includes #include "libmesh/node.h" namespace libMesh { // ------------------------------------------------------------ // Node class static member initialization //const unsigned int Node::invalid_id = libMesh::invalid_uint; bool Node::operator==(const Node& rhs) const { // Cast rhs to a Node* // const Node* rhs_node = dynamic_cast<const Node*>(&rhs); const Node* rhs_node = &rhs; // If we can't cast to a Node* then rhs must be an Elem if(rhs_node == NULL) return false; // Explicitly calling the operator== defined in Point return this->Point::operator==(*rhs_node); } void Node::print_info (std::ostream& os) const { os << this->get_info() << std::endl; } std::string Node::get_info () const { std::ostringstream out; out << " Node Information" << '\n' << " id()="; if (this->valid_id()) out << this->id(); else out << "invalid"; out << ", processor_id()=" << this->processor_id() << '\n'; out << " Point=" << *static_cast<const Point*>(this) << '\n'; return out.str(); } #ifdef LIBMESH_HAVE_MPI MPI_Datatype Node::PackedNode::create_mpi_datatype () { MPI_Datatype packed_node_type; MPI_Datatype types[] = { MPI_UNSIGNED, MPI_REAL }; int blocklengths[] = { 2, 3 }; MPI_Aint displs[2]; // create a Packed node and get the addresses of the elements. // this will properly handle id/pid getting padded, for example, // in which case id and x may not be 2*sizeof(unsigned int) apart. Node::PackedNode pn; MPI_Address (&pn.id, &displs[0]); MPI_Address (&pn.x, &displs[1]); displs[1] -= displs[0]; displs[0] = 0; #if MPI_VERSION > 1 MPI_Type_create_struct (2, blocklengths, displs, types, &packed_node_type); #else MPI_Type_struct (2, blocklengths, displs, types, &packed_node_type); #endif // #if MPI_VERSION > 1 return packed_node_type; } void Node::PackedNode::pack (std::vector<int> &conn, const Node* node) { libmesh_assert(node); conn.reserve (conn.size() + node->packed_size()); conn.push_back (static_cast<int>(node->processor_id())); conn.push_back (static_cast<int>(node->id())); // use "(a+b-1)/b" trick to get a/b to round up static const unsigned int ints_per_Real = (sizeof(Real) + sizeof(int) - 1) / sizeof(int); for (unsigned int i=0; i != LIBMESH_DIM; ++i) { const int* Real_as_ints = reinterpret_cast<const int*>(&((*node)(i))); for (unsigned int j=0; j != ints_per_Real; ++j) { conn.push_back(Real_as_ints[j]); } } node->pack_indexing(std::back_inserter(conn)); } void Node::PackedNode::unpack (std::vector<int>::const_iterator start, Node& node) { unsigned int processor_id = static_cast<unsigned int>(*start++); libmesh_assert(processor_id == DofObject::invalid_processor_id || processor_id < libMesh::n_processors()); unsigned int id = static_cast<unsigned int>(*start++); // use "(a+b-1)/b" trick to get a/b to round up static const unsigned int ints_per_Real = (sizeof(Real) + sizeof(int) - 1) / sizeof(int); std::vector<Real> xyz(3,0.); for (unsigned int i=0; i != LIBMESH_DIM; ++i) { const Real* ints_as_Real = reinterpret_cast<const Real*>(&(*start)); node(i) = *ints_as_Real; start += ints_per_Real; } node.set_id() = id; node.processor_id() = processor_id; node.unpack_indexing(start); } #endif // #ifdef LIBMESH_HAVE_MPI } // namespace libMesh <commit_msg>Removing some atavistic code<commit_after>// The libMesh Finite Element Library. // Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Local includes #include "libmesh/node.h" namespace libMesh { // ------------------------------------------------------------ // Node class static member initialization //const unsigned int Node::invalid_id = libMesh::invalid_uint; bool Node::operator==(const Node& rhs) const { // Explicitly calling the operator== defined in Point return this->Point::operator==(rhs); } void Node::print_info (std::ostream& os) const { os << this->get_info() << std::endl; } std::string Node::get_info () const { std::ostringstream out; out << " Node Information" << '\n' << " id()="; if (this->valid_id()) out << this->id(); else out << "invalid"; out << ", processor_id()=" << this->processor_id() << '\n'; out << " Point=" << *static_cast<const Point*>(this) << '\n'; return out.str(); } #ifdef LIBMESH_HAVE_MPI MPI_Datatype Node::PackedNode::create_mpi_datatype () { MPI_Datatype packed_node_type; MPI_Datatype types[] = { MPI_UNSIGNED, MPI_REAL }; int blocklengths[] = { 2, 3 }; MPI_Aint displs[2]; // create a Packed node and get the addresses of the elements. // this will properly handle id/pid getting padded, for example, // in which case id and x may not be 2*sizeof(unsigned int) apart. Node::PackedNode pn; MPI_Address (&pn.id, &displs[0]); MPI_Address (&pn.x, &displs[1]); displs[1] -= displs[0]; displs[0] = 0; #if MPI_VERSION > 1 MPI_Type_create_struct (2, blocklengths, displs, types, &packed_node_type); #else MPI_Type_struct (2, blocklengths, displs, types, &packed_node_type); #endif // #if MPI_VERSION > 1 return packed_node_type; } void Node::PackedNode::pack (std::vector<int> &conn, const Node* node) { libmesh_assert(node); conn.reserve (conn.size() + node->packed_size()); conn.push_back (static_cast<int>(node->processor_id())); conn.push_back (static_cast<int>(node->id())); // use "(a+b-1)/b" trick to get a/b to round up static const unsigned int ints_per_Real = (sizeof(Real) + sizeof(int) - 1) / sizeof(int); for (unsigned int i=0; i != LIBMESH_DIM; ++i) { const int* Real_as_ints = reinterpret_cast<const int*>(&((*node)(i))); for (unsigned int j=0; j != ints_per_Real; ++j) { conn.push_back(Real_as_ints[j]); } } node->pack_indexing(std::back_inserter(conn)); } void Node::PackedNode::unpack (std::vector<int>::const_iterator start, Node& node) { unsigned int processor_id = static_cast<unsigned int>(*start++); libmesh_assert(processor_id == DofObject::invalid_processor_id || processor_id < libMesh::n_processors()); unsigned int id = static_cast<unsigned int>(*start++); // use "(a+b-1)/b" trick to get a/b to round up static const unsigned int ints_per_Real = (sizeof(Real) + sizeof(int) - 1) / sizeof(int); std::vector<Real> xyz(3,0.); for (unsigned int i=0; i != LIBMESH_DIM; ++i) { const Real* ints_as_Real = reinterpret_cast<const Real*>(&(*start)); node(i) = *ints_as_Real; start += ints_per_Real; } node.set_id() = id; node.processor_id() = processor_id; node.unpack_indexing(start); } #endif // #ifdef LIBMESH_HAVE_MPI } // namespace libMesh <|endoftext|>
<commit_before>/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Glue.hxx" #include "Client.hxx" #include "http_response.hxx" #include "http_address.hxx" #include "header_writer.hxx" #include "stock/GetHandler.hxx" #include "stock/Item.hxx" #include "strmap.hxx" #include "lease.hxx" #include "tcp_stock.hxx" #include "tcp_balancer.hxx" #include "abort_close.hxx" #include "istream/istream.hxx" #include "istream/istream_hold.hxx" #include "net/SocketDescriptor.hxx" #include "net/SocketAddress.hxx" #include "pool.hxx" #include "util/Cancellable.hxx" #include "util/Compiler.h" #include <string.h> #include <sys/socket.h> struct AjpRequest final : StockGetHandler, Lease { struct pool &pool; EventLoop &event_loop; StockItem *stock_item; const char *const protocol; const char *const remote_addr; const char *const remote_host; const char *const server_name; const unsigned server_port; const bool is_ssl; const http_method_t method; const char *const uri; StringMap headers; Istream *body; HttpResponseHandler &handler; CancellablePointer &cancel_ptr; AjpRequest(struct pool &_pool, EventLoop &_event_loop, const char *_protocol, const char *_remote_addr, const char *_remote_host, const char *_server_name, unsigned _server_port, bool _is_ssl, http_method_t _method, const char *_uri, StringMap &&_headers, HttpResponseHandler &_handler, CancellablePointer &_cancel_ptr) :pool(_pool), event_loop(_event_loop), protocol(_protocol), remote_addr(_remote_addr), remote_host(_remote_host), server_name(_server_name), server_port(_server_port), is_ssl(_is_ssl), method(_method), uri(_uri), headers(std::move(_headers)), handler(_handler), cancel_ptr(_cancel_ptr) { } void BeginConnect(TcpBalancer &tcp_balancer, sticky_hash_t session_sticky, const HttpAddress &address, CancellablePointer &_cancel_ptr) { tcp_balancer.Get(pool, false, SocketAddress::Null(), session_sticky, address.addresses, 20, *this, _cancel_ptr); } private: /* virtual methods from class StockGetHandler */ void OnStockItemReady(StockItem &item) override; void OnStockItemError(std::exception_ptr ep) override; /* virtual methods from class Lease */ void ReleaseLease(bool reuse) override { stock_item->Put(!reuse); } }; /* * stock callback * */ void AjpRequest::OnStockItemReady(StockItem &item) { stock_item = &item; ajp_client_request(pool, event_loop, tcp_stock_item_get(item), tcp_stock_item_get_domain(item) == AF_LOCAL ? FdType::FD_SOCKET : FdType::FD_TCP, *this, protocol, remote_addr, remote_host, server_name, server_port, is_ssl, method, uri, headers, body, handler, cancel_ptr); } void AjpRequest::OnStockItemError(std::exception_ptr ep) { handler.InvokeError(ep); if (body != nullptr) body->CloseUnused(); } /* * constructor * */ void ajp_stock_request(struct pool &pool, EventLoop &event_loop, TcpBalancer &tcp_balancer, sticky_hash_t session_sticky, const char *protocol, const char *remote_addr, const char *remote_host, const char *server_name, unsigned server_port, bool is_ssl, http_method_t method, const HttpAddress &uwa, StringMap &&headers, Istream *body, HttpResponseHandler &handler, CancellablePointer &_cancel_ptr) { assert(uwa.path != nullptr); assert(body == nullptr || !body->HasHandler()); auto hr = NewFromPool<AjpRequest>(pool, pool, event_loop, protocol, remote_addr, remote_host, server_name, server_port, is_ssl, method, uwa.path, std::move(headers), handler, _cancel_ptr); auto *cancel_ptr = &_cancel_ptr; if (body != nullptr) { hr->body = istream_hold_new(pool, *body); cancel_ptr = &async_close_on_abort(pool, *hr->body, *cancel_ptr); } else hr->body = nullptr; hr->BeginConnect(tcp_balancer, session_sticky, uwa, *cancel_ptr); } <commit_msg>ajp/Glue: implement Cancellable<commit_after>/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Glue.hxx" #include "Client.hxx" #include "http_response.hxx" #include "http_address.hxx" #include "header_writer.hxx" #include "stock/GetHandler.hxx" #include "stock/Item.hxx" #include "strmap.hxx" #include "lease.hxx" #include "tcp_stock.hxx" #include "tcp_balancer.hxx" #include "abort_close.hxx" #include "istream/istream.hxx" #include "istream/istream_hold.hxx" #include "net/SocketDescriptor.hxx" #include "net/SocketAddress.hxx" #include "pool.hxx" #include "util/Cancellable.hxx" #include "util/Compiler.h" #include <string.h> #include <sys/socket.h> struct AjpRequest final : Cancellable, StockGetHandler, Lease { struct pool &pool; EventLoop &event_loop; StockItem *stock_item; const char *const protocol; const char *const remote_addr; const char *const remote_host; const char *const server_name; const unsigned server_port; const bool is_ssl; const http_method_t method; const char *const uri; StringMap headers; Istream *body; HttpResponseHandler &handler; CancellablePointer &cancel_ptr; AjpRequest(struct pool &_pool, EventLoop &_event_loop, const char *_protocol, const char *_remote_addr, const char *_remote_host, const char *_server_name, unsigned _server_port, bool _is_ssl, http_method_t _method, const char *_uri, StringMap &&_headers, HttpResponseHandler &_handler, CancellablePointer &_cancel_ptr) :pool(_pool), event_loop(_event_loop), protocol(_protocol), remote_addr(_remote_addr), remote_host(_remote_host), server_name(_server_name), server_port(_server_port), is_ssl(_is_ssl), method(_method), uri(_uri), headers(std::move(_headers)), handler(_handler), cancel_ptr(_cancel_ptr) { } void BeginConnect(TcpBalancer &tcp_balancer, sticky_hash_t session_sticky, const HttpAddress &address) { tcp_balancer.Get(pool, false, SocketAddress::Null(), session_sticky, address.addresses, 20, *this, cancel_ptr); } private: /* virtual methods from class Cancellable */ void Cancel() override { if (body != nullptr) body->Close(); cancel_ptr.Cancel(); } /* virtual methods from class StockGetHandler */ void OnStockItemReady(StockItem &item) override; void OnStockItemError(std::exception_ptr ep) override; /* virtual methods from class Lease */ void ReleaseLease(bool reuse) override { stock_item->Put(!reuse); } }; /* * stock callback * */ void AjpRequest::OnStockItemReady(StockItem &item) { stock_item = &item; ajp_client_request(pool, event_loop, tcp_stock_item_get(item), tcp_stock_item_get_domain(item) == AF_LOCAL ? FdType::FD_SOCKET : FdType::FD_TCP, *this, protocol, remote_addr, remote_host, server_name, server_port, is_ssl, method, uri, headers, body, handler, cancel_ptr); } void AjpRequest::OnStockItemError(std::exception_ptr ep) { handler.InvokeError(ep); if (body != nullptr) body->CloseUnused(); } /* * constructor * */ void ajp_stock_request(struct pool &pool, EventLoop &event_loop, TcpBalancer &tcp_balancer, sticky_hash_t session_sticky, const char *protocol, const char *remote_addr, const char *remote_host, const char *server_name, unsigned server_port, bool is_ssl, http_method_t method, const HttpAddress &uwa, StringMap &&headers, Istream *body, HttpResponseHandler &handler, CancellablePointer &_cancel_ptr) { assert(uwa.path != nullptr); assert(body == nullptr || !body->HasHandler()); auto hr = NewFromPool<AjpRequest>(pool, pool, event_loop, protocol, remote_addr, remote_host, server_name, server_port, is_ssl, method, uwa.path, std::move(headers), handler, _cancel_ptr); if (body != nullptr) { hr->body = istream_hold_new(pool, *body); } else hr->body = nullptr; hr->BeginConnect(tcp_balancer, session_sticky, uwa); } <|endoftext|>
<commit_before>/* * Copyright (C) 2019 The Android 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. */ #include "perfetto/ext/base/uuid.h" #include <random> #include "perfetto/ext/base/time.h" namespace perfetto { namespace base { // See https://www.ietf.org/rfc/rfc4122.txt std::array<uint8_t, 16> Uuidv4() { static std::minstd_rand rng(static_cast<size_t>(GetBootTimeNs().count())); std::array<uint8_t, 16> uuid; for (size_t i = 0; i < 16; ++i) uuid[i] = static_cast<uint8_t>(rng()); // version: uuid[6] = (uuid[6] & 0x0f) | 0x40; // clock_seq_hi_and_reserved: uuid[8] = (uuid[8] & 0x3f) | 0x80; return uuid; } } // namespace base } // namespace perfetto <commit_msg>base: fix build of UUID on mac am: c17e81c243 am: 914626f1e6 am: 8e4118b51e am: dfea3348d2 am: 6487f43d31<commit_after>/* * Copyright (C) 2019 The Android 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. */ #include "perfetto/ext/base/uuid.h" #include <random> #include "perfetto/ext/base/time.h" namespace perfetto { namespace base { // See https://www.ietf.org/rfc/rfc4122.txt std::array<uint8_t, 16> Uuidv4() { static std::minstd_rand rng(static_cast<uint32_t>(GetBootTimeNs().count())); std::array<uint8_t, 16> uuid; for (size_t i = 0; i < 16; ++i) uuid[i] = static_cast<uint8_t>(rng()); // version: uuid[6] = (uuid[6] & 0x0f) | 0x40; // clock_seq_hi_and_reserved: uuid[8] = (uuid[8] & 0x3f) | 0x80; return uuid; } } // namespace base } // namespace perfetto <|endoftext|>
<commit_before>#include "../include/Pendulum.hh" #include <stdlib.h> #include <stdio.h> #include <time.h> #include <cmath> Pendulum::Pendulum(float displayx, float displayy) { mscreenwidth = displayx; mscreenheight = displayy; width = 3.0; height = 150.0; sf::Vector2f pendulumSize(width,height); sf::Color pendulumColor = sf::Color( sf::Color(74,235,219) ); float radius = 3.0; origin.setRadius(radius); sf::FloatRect originRect = origin.getLocalBounds(); origin.setOrigin( (originRect.width)/2.0, (originRect.height)/2.0 ); origin.setFillColor( pendulumColor ); origin.setPosition( mscreenwidth/2.0, mscreenheight/2.0 - height/2.0 ); bottom.setRadius(radius); originRect = bottom.getLocalBounds(); bottom.setOrigin( (originRect.width)/2.0, (originRect.height)/2.0 ); bottom.setFillColor( pendulumColor ); pendulum.setSize( pendulumSize ); pendulum.setOrigin( width/2.0, 0 ); // center origin pendulum.setFillColor( pendulumColor ); pendulum.setPosition( mscreenwidth/2.0, mscreenheight/2.0 - height/2.0 ); // Initial Conditions: theta_knot, theta_knot_dot = 0 srand( time(NULL) ); theta_knot = (rand() % 180); //0-180 degrees pendulum.setRotation( theta_knot ); //deg theta = theta_knot; theta_dot = 0.0; gravity = 9.8; // m/s^s omega = sqrt( gravity/(height/2.0) ); // RK4 u1_knot = theta_knot; u2_knot = 0.0; } void Pendulum::draw( sf::RenderTarget& target, sf::RenderStates) const { target.draw( pendulum ); target.draw( origin ); //target.draw( bottom ); } void Pendulum::updatePendulum(float time) { timer = time; theta = exp(-time/30)*theta_knot*cos( omega*time ); theta_dot = -omega*theta_knot*sin( omega*time ); pendulum.setRotation(theta); } void Pendulum::updatePendulumRK4(float time, float g) { timer = time; float h = 1/g; // k,l refers to (d/dt)(u1,u2) = (u2, -u2^2*sin(u1) ) // step size at end of calculation float k0 = u2_knot; float l0 = -pow(u2_knot,2)*sin( u2_knot*time ); float k1 = u2_knot + 0.5*l0; float l1 = -pow(u2_knot+0.5*l0,2)*sin( (u2_knot+0.5*l0)*(time+0.5*h) ); float k2 = u2_knot + 0.5*l1; float l2 = -pow(u2_knot+0.5*l1,2)*sin( (u2_knot+0.5*l1)*(time+0.5*h) ); float k3 = u2_knot + l2; float l3 = -pow(u2_knot+l2,2)*sin( (u2_knot+l2)*(time+h) ); float u1_plus_one = u1_knot + (h/6.0)*( k0 + 2*k1 + 2*k2 + k3); float u2_plus_one = u2_knot + (h/6.0)*( l0 + 2*l1 + 2*l2 + l3); pendulum.setRotation( u1_plus_one ); } void Pendulum::chooseMethod(float time, float h) { if( theta_knot < 10 ) updatePendulum(time); else updatePendulumRK4(time,h); } void Pendulum::addDrag(float time) { ; } sf::Vector2f Pendulum::getPendulumPosition() { sf::Vector2f temp( -height*sin(theta/60.0), height*cos(theta/60.0) ); sf::Vector2f origin2pendulum( mscreenwidth/2.0, mscreenheight/2.0 - height/2.0 ); bottom.setPosition( temp+origin2pendulum ); return temp + origin2pendulum; } <commit_msg>commit<commit_after>#include "../include/Pendulum.hh" #include <stdlib.h> #include <stdio.h> #include <time.h> #include <cmath> Pendulum::Pendulum(float displayx, float displayy) { mscreenwidth = displayx; mscreenheight = displayy; width = 3.0; height = 150.0; sf::Vector2f pendulumSize(width,height); sf::Color pendulumColor = sf::Color( sf::Color(74,235,219) ); float radius = 3.0; origin.setRadius(radius); sf::FloatRect originRect = origin.getLocalBounds(); origin.setOrigin( (originRect.width)/2.0, (originRect.height)/2.0 ); origin.setFillColor( pendulumColor ); origin.setPosition( mscreenwidth/2.0, mscreenheight/2.0 - height/2.0 ); bottom.setRadius(radius); originRect = bottom.getLocalBounds(); bottom.setOrigin( (originRect.width)/2.0, (originRect.height)/2.0 ); bottom.setFillColor( pendulumColor ); pendulum.setSize( pendulumSize ); pendulum.setOrigin( width/2.0, 0 ); // center origin pendulum.setFillColor( pendulumColor ); pendulum.setPosition( mscreenwidth/2.0, mscreenheight/2.0 - height/2.0 ); // Initial Conditions: theta_knot, theta_knot_dot = 0 srand( time(NULL) ); theta_knot = (rand() % 180); //0-180 degrees pendulum.setRotation( theta_knot ); //deg theta = theta_knot; theta_dot = 0.0; gravity = 9.8; // m/s^s omega = sqrt( gravity/(height/2.0) ); // RK4 u1_knot = theta_knot; u2_knot = 0.0; } void Pendulum::draw( sf::RenderTarget& target, sf::RenderStates) const { target.draw( pendulum ); target.draw( origin ); //target.draw( bottom ); } void Pendulum::updatePendulum(float time) { timer = time; theta = exp(-time/30)*theta_knot*cos( omega*time ); theta_dot = -omega*theta_knot*sin( omega*time ); pendulum.setRotation(theta); } void Pendulum::updatePendulumRK4(float time, float g) { timer = time; float h = 1/g; // step size // k,l refers to (d/dt)(u1,u2) = (u2, -u2^2*sin(u1) ) // step size at end of calculation float k0 = u2_knot; float l0 = -pow(u2_knot,2)*sin( u2_knot*time ); float k1 = u2_knot + 0.5*l0; float l1 = -pow(u2_knot+0.5*l0,2)*sin( (u2_knot+0.5*l0)*(time+0.5*h) ); float k2 = u2_knot + 0.5*l1; float l2 = -pow(u2_knot+0.5*l1,2)*sin( (u2_knot+0.5*l1)*(time+0.5*h) ); float k3 = u2_knot + l2; float l3 = -pow(u2_knot+l2,2)*sin( (u2_knot+l2)*(time+h) ); float u1_plus_one = u1_knot + (h/6.0)*( k0 + 2*k1 + 2*k2 + k3); float u2_plus_one = u2_knot + (h/6.0)*( l0 + 2*l1 + 2*l2 + l3); pendulum.setRotation( u1_plus_one ); } void Pendulum::chooseMethod(float time, float h) { if( theta_knot < 10 ) updatePendulum(time); else updatePendulumRK4(time,h); } void Pendulum::addDrag(float time) { ; } sf::Vector2f Pendulum::getPendulumPosition() { sf::Vector2f temp( -height*sin(theta/60.0), height*cos(theta/60.0) ); sf::Vector2f origin2pendulum( mscreenwidth/2.0, mscreenheight/2.0 - height/2.0 ); bottom.setPosition( temp+origin2pendulum ); return temp + origin2pendulum; } <|endoftext|>
<commit_before>/***************************************************************************** bedtools.cpp bedtools command line interface. Thanks to Heng Li, as this interface is inspired and based upon his samtools interface. (c) 2009-2011 - Aaron Quinlan Quinlan Laboratory Department of Public Health Sciences Center for Public Health genomics University of Virginia [email protected] Licenced under the GNU General Public License 2.0 license. ******************************************************************************/ #include <iostream> #include <fstream> #include <stdlib.h> #include <string> #include "version.h" using namespace std; // define our program name #define PROGRAM_NAME "bedtools" // colors for the term's menu #define RESET "\033[m" #define GREEN "\033[1;32m" #define BLUE "\033[1;34m" #define RED "\033[1;31m" // define our parameter checking macro #define PARAMETER_CHECK(param, paramLen, actualLen) (strncmp(argv[i], param, min(actualLen, paramLen))== 0) && (actualLen == paramLen) int annotate_main(int argc, char* argv[]);// int bamtobed_main(int argc, char* argv[]);// int bed12tobed6_main(int argc, char* argv[]); // int bedtobam_main(int argc, char* argv[]);// int bedtoigv_main(int argc, char* argv[]);// int bedpetobam_main(int argc, char* argv[]);// int closest_main(int argc, char* argv[]); // int cluster_main(int argc, char* argv[]); // int complement_main(int argc, char* argv[]);// int coverage_main(int argc, char* argv[]); // int fastafrombed_main(int argc, char* argv[]);// int flank_main(int argc, char* argv[]); // int genomecoverage_main(int argc, char* argv[]);// int getoverlap_main(int argc, char* argv[]);// int groupby_main(int argc, char* argv[]);// int intersect_main(int argc, char* argv[]); // int links_main(int argc, char* argv[]);// int maskfastafrombed_main(int argc, char* argv[]);// int merge_main(int argc, char* argv[]); // int multibamcov_main(int argc, char* argv[]);// int multiintersect_main(int argc, char* argv[]);// int nuc_main(int argc, char* argv[]);// int pairtobed_main(int argc, char* argv[]);// int pairtopair_main(int argc, char* argv[]);// int shuffle_main(int argc, char* argv[]); // int slop_main(int argc, char* argv[]); // int sort_main(int argc, char* argv[]); // int subtract_main(int argc, char* argv[]); // int tagbam_main(int argc, char* argv[]);// int unionbedgraphs_main(int argc, char* argv[]);// int window_main(int argc, char* argv[]); // int windowmaker_main(int argc, char* argv[]); // int bedtools_help(void); int bedtools_faq(void); int main(int argc, char *argv[]) { // make sure the user at least entered a sub_command if (argc < 2) return bedtools_help(); std::string sub_cmd = argv[1]; // genome arithmetic tools if (sub_cmd == "intersect") return intersect_main(argc-1, argv+1); else if (sub_cmd == "window") return window_main(argc-1, argv+1); else if (sub_cmd == "closest") return closest_main(argc-1, argv+1); else if (sub_cmd == "coverage") return coverage_main(argc-1, argv+1); else if (sub_cmd == "genomecov") return genomecoverage_main(argc-1, argv+1); else if (sub_cmd == "merge") return merge_main(argc-1, argv+1); else if (sub_cmd == "cluster") return cluster_main(argc-1, argv+1); else if (sub_cmd == "complement") return complement_main(argc-1, argv+1); else if (sub_cmd == "subtract") return subtract_main(argc-1, argv+1); else if (sub_cmd == "slop") return slop_main(argc-1, argv+1); else if (sub_cmd == "flank") return flank_main(argc-1, argv+1); else if (sub_cmd == "sort") return sort_main(argc-1, argv+1); else if (sub_cmd == "shuffle") return shuffle_main(argc-1, argv+1); else if (sub_cmd == "annotate") return annotate_main(argc-1, argv+1); // Multi-way file comparisonstools else if (sub_cmd == "multiinter") return multiintersect_main(argc-1, argv+1); else if (sub_cmd == "unionbedg") return unionbedgraphs_main(argc-1, argv+1); // paired-end conversion tools else if (sub_cmd == "pairtobed") return pairtobed_main(argc-1, argv+1); else if (sub_cmd == "pairtopair") return pairtopair_main(argc-1, argv+1); // format conversion tools else if (sub_cmd == "bamtobed") return bamtobed_main(argc-1, argv+1); else if (sub_cmd == "bedtobam") return bedtobam_main(argc-1, argv+1); else if (sub_cmd == "bedpetobam") return bedpetobam_main(argc-1, argv+1); else if (sub_cmd == "bed12tobed6") return bed12tobed6_main(argc-1, argv+1); // BAM-specific tools else if (sub_cmd == "multicov") return multibamcov_main(argc-1, argv+1); else if (sub_cmd == "tag") return tagbam_main(argc-1, argv+1); // fasta tools else if (sub_cmd == "getfasta") return fastafrombed_main(argc-1, argv+1); else if (sub_cmd == "maskfasta") return maskfastafrombed_main(argc-1, argv+1); else if (sub_cmd == "nuc") return nuc_main(argc-1, argv+1); // misc. tools else if (sub_cmd == "overlap") return getoverlap_main(argc-1, argv+1); else if (sub_cmd == "igv") return bedtoigv_main(argc-1, argv+1); else if (sub_cmd == "links") return links_main(argc-1, argv+1); else if (sub_cmd == "makewindows") return windowmaker_main(argc-1, argv+1); else if (sub_cmd == "groupby") return groupby_main(argc-1, argv+1); // help else if (sub_cmd == "-h" || sub_cmd == "--help" || sub_cmd == "-help") return bedtools_help(); // frequently asked questions else if (sub_cmd == "--FAQ" || sub_cmd == "--faq" || sub_cmd == "-FAQ" || sub_cmd == "-faq") return bedtools_faq(); // verison information else if (sub_cmd == "-version" || sub_cmd == "--version") cout << "bedtools " << VERSION << endl; // verison information else if (sub_cmd == "-contact" || sub_cmd == "--contact") { cout << endl; cout << "- For further help, or to report a bug, please " << endl; cout << " email the bedtools mailing list: " << endl; cout << " [email protected]" << endl << endl; cout << "- Stable releases of bedtools can be found at: " << endl; cout << " http://bedtools.googlecode.com" << endl << endl; cout << "- The development repository can be found at: " << endl; cout << " https://github.com/arq5x/bedtools" << endl << endl; } // unknown else { // TODO: Implement a Levenstein-based "did you mean???" cerr << "error: unrecognized command: " << argv[1] << endl << endl; return 1; } return 0; } int bedtools_help(void) { cout << PROGRAM_NAME << ": flexible tools for genome arithmetic and DNA sequence analysis.\n"; cout << "usage: bedtools <subcommand> [options]" << endl << endl; cout << "The bedtools sub-commands include:" << endl; cout << endl; cout << "[ Genome arithmetic ]" << endl; cout << " intersect " << "Find overlapping intervals in various ways.\n"; cout << " window " << "Find overlapping intervals within a window around an interval.\n"; cout << " closest " << "Find the closest, potentially non-overlapping interval.\n"; cout << " coverage " << "Compute the coverage over defined intervals.\n"; cout << " genomecov " << "Compute the coverage over an entire genome.\n"; cout << " merge " << "Combine overlapping/nearby intervals into a single interval.\n"; cout << " cluster " << "Cluster (but don't merge) overlapping/nearby intervals.\n"; cout << " complement " << "Extract intervals _not_ represented by an interval file.\n"; cout << " subtract " << "Remove intervals based on overlaps b/w two files.\n"; cout << " slop " << "Adjust the size of intervals.\n"; cout << " flank " << "Create new intervals from the flanks of existing intervals.\n"; cout << " sort " << "Order the intervals in a file.\n"; cout << " shuffle " << "Randomly redistrubute intervals in a genome.\n"; cout << " annotate " << "Annotate coverage of features from multiple files.\n"; cout << endl; cout << "[ Multi-way file comparisons ]" << endl; cout << " multiinter " << "Identifies common intervals among multiple interval files.\n"; cout << " unionbedg " << "Combines coverage intervals from multiple BEDGRAPH files.\n"; cout << endl; cout << "[ Paired-end manipulation ]" << endl; cout << " pairtobed " << "Find pairs that overlap intervals in various ways.\n"; cout << " pairtopair " << "Find pairs that overlap other pairs in various ways.\n"; cout << endl; cout << "[ Format conversion ]" << endl; cout << " bamtobed " << "Convert BAM alignments to BED (& other) formats.\n"; cout << " bedtobam " << "Convert intervals to BAM records.\n"; cout << " bedpetobam " << "Convert BEDPE intervals to BAM records.\n"; cout << " bed12tobed6 " << "Breaks BED12 intervals into discrete BED6 intervals.\n"; cout << endl; cout << "[ Fasta manipulation ]" << endl; cout << " getfasta " << "Use intervals to extract sequences from a FASTA file.\n"; cout << " maskfasta " << "Use intervals to mask sequences from a FASTA file.\n"; cout << " nuc " << "Profile the nucleotide content of intervals in a FASTA file.\n"; cout << endl; cout << "[ BAM focused tools ]" << endl; cout << " multicov " << "Counts coverage from multiple BAMs at specific intervals.\n"; cout << " tag " << "Tag BAM alignments based on overlaps with interval files.\n"; cout << endl; cout << "[ Miscellaneous tools ]" << endl; cout << " overlap " << "Computes the amount of overlap from two intervals.\n"; cout << " igv " << "Create an IGV snapshot batch script.\n"; cout << " links " << "Create a HTML page of links to UCSC locations.\n"; cout << " makewindows " << "Make interval \"windows\" across a genome.\n"; cout << " groupby " << "Group by common cols. & summarize oth. cols. (~ SQL \"groupBy\")\n"; cout << endl; cout << "[ General help ]" << endl; cout << " --help " << "Print this help menu.\n"; //cout << " --faq " << "Frequently asked questions.\n"; TODO cout << " --version " << "What version of bedtools are you using?.\n"; cout << " --contact " << "Feature requests, bugs, mailing lists, etc.\n"; cout << "\n"; return 1; } int bedtools_faq(void) { cout << "\n"; cout << "Q1. How do I see the help for a given command?" << endl; cout << "A1. All BEDTools commands have a \"-h\" option. Additionally, some tools " << endl; cout << " will provide the help menu if you just type the command line " << endl; cout << " followed by enter. " << endl; cout << "\n"; return 1; } <commit_msg>changed return codes.<commit_after>/***************************************************************************** bedtools.cpp bedtools command line interface. Thanks to Heng Li, as this interface is inspired and based upon his samtools interface. (c) 2009-2011 - Aaron Quinlan Quinlan Laboratory Department of Public Health Sciences Center for Public Health genomics University of Virginia [email protected] Licenced under the GNU General Public License 2.0 license. ******************************************************************************/ #include <iostream> #include <fstream> #include <stdlib.h> #include <string> #include "version.h" using namespace std; // define our program name #define PROGRAM_NAME "bedtools" // colors for the term's menu #define RESET "\033[m" #define GREEN "\033[1;32m" #define BLUE "\033[1;34m" #define RED "\033[1;31m" // define our parameter checking macro #define PARAMETER_CHECK(param, paramLen, actualLen) (strncmp(argv[i], param, min(actualLen, paramLen))== 0) && (actualLen == paramLen) int annotate_main(int argc, char* argv[]);// int bamtobed_main(int argc, char* argv[]);// int bed12tobed6_main(int argc, char* argv[]); // int bedtobam_main(int argc, char* argv[]);// int bedtoigv_main(int argc, char* argv[]);// int bedpetobam_main(int argc, char* argv[]);// int closest_main(int argc, char* argv[]); // int cluster_main(int argc, char* argv[]); // int complement_main(int argc, char* argv[]);// int coverage_main(int argc, char* argv[]); // int fastafrombed_main(int argc, char* argv[]);// int flank_main(int argc, char* argv[]); // int genomecoverage_main(int argc, char* argv[]);// int getoverlap_main(int argc, char* argv[]);// int groupby_main(int argc, char* argv[]);// int intersect_main(int argc, char* argv[]); // int links_main(int argc, char* argv[]);// int maskfastafrombed_main(int argc, char* argv[]);// int merge_main(int argc, char* argv[]); // int multibamcov_main(int argc, char* argv[]);// int multiintersect_main(int argc, char* argv[]);// int nuc_main(int argc, char* argv[]);// int pairtobed_main(int argc, char* argv[]);// int pairtopair_main(int argc, char* argv[]);// int shuffle_main(int argc, char* argv[]); // int slop_main(int argc, char* argv[]); // int sort_main(int argc, char* argv[]); // int subtract_main(int argc, char* argv[]); // int tagbam_main(int argc, char* argv[]);// int unionbedgraphs_main(int argc, char* argv[]);// int window_main(int argc, char* argv[]); // int windowmaker_main(int argc, char* argv[]); // int bedtools_help(void); int bedtools_faq(void); int main(int argc, char *argv[]) { // make sure the user at least entered a sub_command if (argc < 2) return bedtools_help(); std::string sub_cmd = argv[1]; // genome arithmetic tools if (sub_cmd == "intersect") return intersect_main(argc-1, argv+1); else if (sub_cmd == "window") return window_main(argc-1, argv+1); else if (sub_cmd == "closest") return closest_main(argc-1, argv+1); else if (sub_cmd == "coverage") return coverage_main(argc-1, argv+1); else if (sub_cmd == "genomecov") return genomecoverage_main(argc-1, argv+1); else if (sub_cmd == "merge") return merge_main(argc-1, argv+1); else if (sub_cmd == "cluster") return cluster_main(argc-1, argv+1); else if (sub_cmd == "complement") return complement_main(argc-1, argv+1); else if (sub_cmd == "subtract") return subtract_main(argc-1, argv+1); else if (sub_cmd == "slop") return slop_main(argc-1, argv+1); else if (sub_cmd == "flank") return flank_main(argc-1, argv+1); else if (sub_cmd == "sort") return sort_main(argc-1, argv+1); else if (sub_cmd == "shuffle") return shuffle_main(argc-1, argv+1); else if (sub_cmd == "annotate") return annotate_main(argc-1, argv+1); // Multi-way file comparisonstools else if (sub_cmd == "multiinter") return multiintersect_main(argc-1, argv+1); else if (sub_cmd == "unionbedg") return unionbedgraphs_main(argc-1, argv+1); // paired-end conversion tools else if (sub_cmd == "pairtobed") return pairtobed_main(argc-1, argv+1); else if (sub_cmd == "pairtopair") return pairtopair_main(argc-1, argv+1); // format conversion tools else if (sub_cmd == "bamtobed") return bamtobed_main(argc-1, argv+1); else if (sub_cmd == "bedtobam") return bedtobam_main(argc-1, argv+1); else if (sub_cmd == "bedpetobam") return bedpetobam_main(argc-1, argv+1); else if (sub_cmd == "bed12tobed6") return bed12tobed6_main(argc-1, argv+1); // BAM-specific tools else if (sub_cmd == "multicov") return multibamcov_main(argc-1, argv+1); else if (sub_cmd == "tag") return tagbam_main(argc-1, argv+1); // fasta tools else if (sub_cmd == "getfasta") return fastafrombed_main(argc-1, argv+1); else if (sub_cmd == "maskfasta") return maskfastafrombed_main(argc-1, argv+1); else if (sub_cmd == "nuc") return nuc_main(argc-1, argv+1); // misc. tools else if (sub_cmd == "overlap") return getoverlap_main(argc-1, argv+1); else if (sub_cmd == "igv") return bedtoigv_main(argc-1, argv+1); else if (sub_cmd == "links") return links_main(argc-1, argv+1); else if (sub_cmd == "makewindows") return windowmaker_main(argc-1, argv+1); else if (sub_cmd == "groupby") return groupby_main(argc-1, argv+1); // help else if (sub_cmd == "-h" || sub_cmd == "--help" || sub_cmd == "-help") return bedtools_help(); // frequently asked questions else if (sub_cmd == "--FAQ" || sub_cmd == "--faq" || sub_cmd == "-FAQ" || sub_cmd == "-faq") return bedtools_faq(); // verison information else if (sub_cmd == "-version" || sub_cmd == "--version") cout << "bedtools " << VERSION << endl; // verison information else if (sub_cmd == "-contact" || sub_cmd == "--contact") { cout << endl; cout << "- For further help, or to report a bug, please " << endl; cout << " email the bedtools mailing list: " << endl; cout << " [email protected]" << endl << endl; cout << "- Stable releases of bedtools can be found at: " << endl; cout << " http://bedtools.googlecode.com" << endl << endl; cout << "- The development repository can be found at: " << endl; cout << " https://github.com/arq5x/bedtools" << endl << endl; } // unknown else { // TODO: Implement a Levenstein-based "did you mean???" cerr << "error: unrecognized command: " << argv[1] << endl << endl; return 1; } return 0; } int bedtools_help(void) { cout << PROGRAM_NAME << ": flexible tools for genome arithmetic and DNA sequence analysis.\n"; cout << "usage: bedtools <subcommand> [options]" << endl << endl; cout << "The bedtools sub-commands include:" << endl; cout << endl; cout << "[ Genome arithmetic ]" << endl; cout << " intersect " << "Find overlapping intervals in various ways.\n"; cout << " window " << "Find overlapping intervals within a window around an interval.\n"; cout << " closest " << "Find the closest, potentially non-overlapping interval.\n"; cout << " coverage " << "Compute the coverage over defined intervals.\n"; cout << " genomecov " << "Compute the coverage over an entire genome.\n"; cout << " merge " << "Combine overlapping/nearby intervals into a single interval.\n"; cout << " cluster " << "Cluster (but don't merge) overlapping/nearby intervals.\n"; cout << " complement " << "Extract intervals _not_ represented by an interval file.\n"; cout << " subtract " << "Remove intervals based on overlaps b/w two files.\n"; cout << " slop " << "Adjust the size of intervals.\n"; cout << " flank " << "Create new intervals from the flanks of existing intervals.\n"; cout << " sort " << "Order the intervals in a file.\n"; cout << " shuffle " << "Randomly redistrubute intervals in a genome.\n"; cout << " annotate " << "Annotate coverage of features from multiple files.\n"; cout << endl; cout << "[ Multi-way file comparisons ]" << endl; cout << " multiinter " << "Identifies common intervals among multiple interval files.\n"; cout << " unionbedg " << "Combines coverage intervals from multiple BEDGRAPH files.\n"; cout << endl; cout << "[ Paired-end manipulation ]" << endl; cout << " pairtobed " << "Find pairs that overlap intervals in various ways.\n"; cout << " pairtopair " << "Find pairs that overlap other pairs in various ways.\n"; cout << endl; cout << "[ Format conversion ]" << endl; cout << " bamtobed " << "Convert BAM alignments to BED (& other) formats.\n"; cout << " bedtobam " << "Convert intervals to BAM records.\n"; cout << " bedpetobam " << "Convert BEDPE intervals to BAM records.\n"; cout << " bed12tobed6 " << "Breaks BED12 intervals into discrete BED6 intervals.\n"; cout << endl; cout << "[ Fasta manipulation ]" << endl; cout << " getfasta " << "Use intervals to extract sequences from a FASTA file.\n"; cout << " maskfasta " << "Use intervals to mask sequences from a FASTA file.\n"; cout << " nuc " << "Profile the nucleotide content of intervals in a FASTA file.\n"; cout << endl; cout << "[ BAM focused tools ]" << endl; cout << " multicov " << "Counts coverage from multiple BAMs at specific intervals.\n"; cout << " tag " << "Tag BAM alignments based on overlaps with interval files.\n"; cout << endl; cout << "[ Miscellaneous tools ]" << endl; cout << " overlap " << "Computes the amount of overlap from two intervals.\n"; cout << " igv " << "Create an IGV snapshot batch script.\n"; cout << " links " << "Create a HTML page of links to UCSC locations.\n"; cout << " makewindows " << "Make interval \"windows\" across a genome.\n"; cout << " groupby " << "Group by common cols. & summarize oth. cols. (~ SQL \"groupBy\")\n"; cout << endl; cout << "[ General help ]" << endl; cout << " --help " << "Print this help menu.\n"; //cout << " --faq " << "Frequently asked questions.\n"; TODO cout << " --version " << "What version of bedtools are you using?.\n"; cout << " --contact " << "Feature requests, bugs, mailing lists, etc.\n"; cout << "\n"; return 0; } int bedtools_faq(void) { cout << "\n"; cout << "Q1. How do I see the help for a given command?" << endl; cout << "A1. All BEDTools commands have a \"-h\" option. Additionally, some tools " << endl; cout << " will provide the help menu if you just type the command line " << endl; cout << " followed by enter. " << endl; cout << "\n"; return 0; } <|endoftext|>
<commit_before>#include "opencv2/imgproc/imgproc.hpp" #include "EventState.h" #include "circularArray.h" #include <iostream> class EventHandler{ private: EventState pastSecondState; EventState state; CircularArray frames; public: void analyze(); private: void handleActive(); void handleRedAlert(); void handleTurnedLeft(); void handleTurnedRight(); void handleWaitingForLeftTurn(); void handleWaitingForRightTurn(); bool stateCheck(int, EventState); bool eyeCheck(int, bool, bool); }; void EventHandler::analyze(){ switch(state){ case RED_ALERT: handleRedAlert(); break; case WAITING_FOR_LEFT_TURN: handleWaitingForLeftTurn(); break; case WAITING_FOR_RIGHT_TURN: handleWaitingForRightTurn(); break; case TURNED_LEFT: handleTurnedLeft(); break; case TURNED_RIGHT: handleTurnedRight(); break; default: handleActive(); } frames.getFrameAt(0).state = state; } void EventHandler::handleActive(){ if(eyeCheck(5, false, false)){ std::cout << "1" << std::endl; state = RED_ALERT; } // begin scanning for left turn else if(eyeCheck(15, false, true)){ state = TURNED_LEFT; } // begin scanning for right turn else if(eyeCheck(15, true, false)){ state = TURNED_RIGHT; } frames.getFrameAt(0).state = state; } void EventHandler::handleRedAlert(){ if(eyeCheck(5, true, true)){ std::cout << "1" << std::endl; state = ACTIVE; } } void EventHandler::handleWaitingForLeftTurn(){ if(eyeCheck(5, false, true)){ std::cout << "7" << std::endl; state = ACTIVE; } else if(eyeCheck(15, true, true)){ //reset state = ACTIVE; } } void EventHandler::handleWaitingForRightTurn(){ if(eyeCheck(5, true, false)){ std::cout << "7" << std::endl; state = ACTIVE; } else if(eyeCheck(15, true, true)){ //reset state = ACTIVE; } } void EventHandler::handleTurnedLeft(){ if(eyeCheck(15, false, true)){ std::cout << "3" << std::endl; state = ACTIVE; } else if(eyeCheck(5, false, false)){ std::cout << "1" << std::endl; state = RED_ALERT; } else if(eyeCheck(5, true, true)){ state = WAITING_FOR_RIGHT_TURN; } } void EventHandler::handleTurnedRight(){ if(eyeCheck(15, true, false)){ std::cout << "4" << std::endl; state = ACTIVE; } else if(eyeCheck(5, false, false)){ std::cout << "1" << std::endl; state = RED_ALERT; } else if(eyeCheck(5, true, true)){ state = WAITING_FOR_LEFT_TURN; } } // Scans the previous n frames. Return true if the majority were queryState, false otherwise. bool EventHandler::stateCheck(int n, EventState queryState){ int stateCount = 0; for(int i = 0; i < n; i++){ if(frames.getFrameAt(i).state == queryState){ stateCount++; } } return (stateCount/(double)n > 0.6); } // Scans the previous n frames. Return true if the majority were queryState, false otherwise. bool EventHandler::eyeCheck(int n, bool leftEye, bool rightEye){ int count = 0; for(int i = 0; i < n; i++){ if(frames.getFrameAt(i).hasLeftPupil == leftEye && frames.getFrameAt(i).hasRightPupil == rightEye){ count++; } } return (count/(double)n > 0.6); } <commit_msg>constructor<commit_after>#include "opencv2/imgproc/imgproc.hpp" #include "EventState.h" #include "circularArray.h" #include <iostream> class EventHandler{ private: EventState pastSecondState; EventState state; CircularArray frames; public: EventHandler(); void analyze(PupilsFrame&); private: void handleActive(); void handleRedAlert(); void handleTurnedLeft(); void handleTurnedRight(); void handleWaitingForLeftTurn(); void handleWaitingForRightTurn(); bool stateCheck(int, EventState); bool eyeCheck(int, bool, bool); }; EventHandler::EventHandler(){ frames = CircularArray(); } void EventHandler::analyze(PupilsFrame& frame){ frames.addData(frame); switch(state){ case RED_ALERT: handleRedAlert(); break; case WAITING_FOR_LEFT_TURN: handleWaitingForLeftTurn(); break; case WAITING_FOR_RIGHT_TURN: handleWaitingForRightTurn(); break; case TURNED_LEFT: handleTurnedLeft(); break; case TURNED_RIGHT: handleTurnedRight(); break; default: handleActive(); } frames.getFrameAt(0).state = state; } void EventHandler::handleActive(){ if(eyeCheck(5, false, false)){ std::cout << "1" << std::endl; state = RED_ALERT; } // begin scanning for left turn else if(eyeCheck(15, false, true)){ state = TURNED_LEFT; } // begin scanning for right turn else if(eyeCheck(15, true, false)){ state = TURNED_RIGHT; } frames.getFrameAt(0).state = state; } void EventHandler::handleRedAlert(){ if(eyeCheck(5, true, true)){ std::cout << "1" << std::endl; state = ACTIVE; } } void EventHandler::handleWaitingForLeftTurn(){ if(eyeCheck(5, false, true)){ std::cout << "7" << std::endl; state = ACTIVE; } else if(eyeCheck(15, true, true)){ //reset state = ACTIVE; } } void EventHandler::handleWaitingForRightTurn(){ if(eyeCheck(5, true, false)){ std::cout << "7" << std::endl; state = ACTIVE; } else if(eyeCheck(15, true, true)){ //reset state = ACTIVE; } } void EventHandler::handleTurnedLeft(){ if(eyeCheck(15, false, true)){ std::cout << "3" << std::endl; state = ACTIVE; } else if(eyeCheck(5, false, false)){ std::cout << "1" << std::endl; state = RED_ALERT; } else if(eyeCheck(5, true, true)){ state = WAITING_FOR_RIGHT_TURN; } } void EventHandler::handleTurnedRight(){ if(eyeCheck(15, true, false)){ std::cout << "4" << std::endl; state = ACTIVE; } else if(eyeCheck(5, false, false)){ std::cout << "1" << std::endl; state = RED_ALERT; } else if(eyeCheck(5, true, true)){ state = WAITING_FOR_LEFT_TURN; } } // Scans the previous n frames. Return true if the majority were queryState, false otherwise. bool EventHandler::stateCheck(int n, EventState queryState){ int stateCount = 0; for(int i = 0; i < n; i++){ if(frames.getFrameAt(i).state == queryState){ stateCount++; } } return (stateCount/(double)n > 0.6); } // Scans the previous n frames. Return true if the majority were queryState, false otherwise. bool EventHandler::eyeCheck(int n, bool leftEye, bool rightEye){ int count = 0; for(int i = 0; i < n; i++){ if(frames.getFrameAt(i).hasLeftPupil == leftEye && frames.getFrameAt(i).hasRightPupil == rightEye){ count++; } } return (count/(double)n > 0.6); } <|endoftext|>
<commit_before> #include "Property.h" #include "base_types.h" #include "logging.h" #include "utils.h" #include "Error.h" #include <cstring> #include <algorithm> using namespace tcam; Property::Property () : value_type(UNDEFINED), prop(), ref_prop() {} Property::Property (const camera_property& property, VALUE_TYPE t) : prop(property), ref_prop(property), value_type(t) {} Property::Property (const camera_property& property, const std::map<std::string, int>& mapping, VALUE_TYPE t) : prop(property), ref_prop(property), string_map(mapping), value_type(t) {} Property::~Property () {} void Property::reset () { tcam_log(TCAM_LOG_INFO, "Resetting property to initial values."); prop = ref_prop; notifyImpl(); } bool Property::update () { if (impl.expired()) { setError(Error("Property implementation has expired.", ENOENT)); return false; } auto ptr = impl.lock(); tcam_log(TCAM_LOG_DEBUG, "Updating %s", prop.name); return ptr->getProperty(*this); } PROPERTY_ID Property::getID () const { return prop.id; } std::string Property::getName () const { return prop.name; } PROPERTY_TYPE Property::getType () const { return prop.type; } bool Property::isReadOnly () const { return is_bit_set(prop.flags, PROPERTY_FLAG_READ_ONLY); } bool Property::isWriteOnly () const { return is_bit_set(prop.flags, PROPERTY_FLAG_WRITE_ONLY); } bool Property::isDisabled () const { return is_bit_set(prop.flags, PROPERTY_FLAG_DISABLED); } uint32_t Property::getFlags () const { return prop.flags; } struct camera_property Property::getStruct () const { return prop; } bool Property::setStruct (const struct camera_property& p) { switch (prop.type) { case PROPERTY_TYPE_STRING: std::strncpy(prop.value.s.value, p.value.s.value, sizeof(prop.value.s.value)); case PROPERTY_TYPE_STRING_TABLE: prop.value.i.value = p.value.i.value; break; case PROPERTY_TYPE_INTEGER: prop.value.i.value = p.value.i.value; break; case PROPERTY_TYPE_DOUBLE: prop.value.d.value = p.value.d.value; break; case PROPERTY_TYPE_BUTTON: // do nothing break; case PROPERTY_TYPE_BOOLEAN: prop.value.b.value = p.value.b.value; break; case PROPERTY_TYPE_UNKNOWN: default: return false; } return true; } Property::VALUE_TYPE Property::getValueType () const { return value_type; } std::string Property::toString () const { std::string property_string; // = getName() + "(" + propertyType2String(prop.type) + ")="; switch (prop.type) { case PROPERTY_TYPE_BOOLEAN: { if (prop.value.b.value) { property_string += "true"; } else { property_string += "false"; } break; } case PROPERTY_TYPE_BITMASK: case PROPERTY_TYPE_INTEGER: { property_string += std::to_string(prop.value.i.value); break; } case PROPERTY_TYPE_DOUBLE: { property_string += std::to_string(prop.value.d.value); break; } case PROPERTY_TYPE_STRING: { property_string += prop.value.s.value; break; } case PROPERTY_TYPE_STRING_TABLE: { } case PROPERTY_TYPE_BUTTON: { } case PROPERTY_TYPE_UNKNOWN: default: { } } return property_string; } bool Property::fromString (const std::string& s) { try { switch (prop.type) { case PROPERTY_TYPE_BOOLEAN: { if (s.compare("true") == 0) { prop.value.b.value = true; } else { prop.value.b.value = false; } break; } case PROPERTY_TYPE_BITMASK: case PROPERTY_TYPE_INTEGER: { prop.value.i.value = stoi(s); break; } case PROPERTY_TYPE_DOUBLE: { prop.value.d.value = stod(s); break; } case PROPERTY_TYPE_STRING: { strncpy(prop.value.s.value, s.c_str(), sizeof(prop.value.s.value)); prop.value.s.value[sizeof(prop.value.s.value)-1] = '\0'; break; } case PROPERTY_TYPE_STRING_TABLE: { } case PROPERTY_TYPE_BUTTON: case PROPERTY_TYPE_UNKNOWN: default: { return false; } } } catch (const std::invalid_argument& e) { return false; } catch (const std::out_of_range& e) { return false; } return true; } bool Property::setReadOnly (bool only_read) { if (only_read) { prop.flags = set_bit(prop.flags, PROPERTY_FLAG_READ_ONLY); } else { prop.flags = unset_bit(prop.flags, PROPERTY_FLAG_READ_ONLY); } return true; } bool Property::setWriteOnly (bool only_write) { if (only_write) { prop.flags = set_bit(prop.flags, PROPERTY_FLAG_WRITE_ONLY); } else { prop.flags = unset_bit(prop.flags, PROPERTY_FLAG_WRITE_ONLY); } return true; } bool Property::setInactive (bool is_disabled) { if (is_disabled) { prop.flags = set_bit(prop.flags, PROPERTY_FLAG_INACTIVE); } else { prop.flags = unset_bit(prop.flags, PROPERTY_FLAG_INACTIVE); } return true; } bool Property::setProperty (const Property&) { if (impl.expired()) { return false; } notifyImpl(); return true; } bool Property::getProperty (Property& p) { p.setStruct(this->prop); return true; } void Property::notifyImpl () { if (impl.expired()) { tcam_log(TCAM_LOG_ERROR, "PropertyImpl expired. Property %s is corrupted.", this->getName().c_str()); } auto ptr(impl.lock()); // tcam_log(TCAM_LOG_DEBUG, "Notifying impl about property change."); ptr->setProperty(*this); } PROPERTY_TYPE tcam::value_type_to_ctrl_type (const Property::VALUE_TYPE& t) { switch (t) { case Property::BOOLEAN: return PROPERTY_TYPE_BOOLEAN; case Property::STRING: return PROPERTY_TYPE_STRING; case Property::ENUM: return PROPERTY_TYPE_STRING_TABLE; case Property::INTSWISSKNIFE: case Property::INTEGER: return PROPERTY_TYPE_INTEGER; case Property::FLOAT: return PROPERTY_TYPE_DOUBLE; case Property::BUTTON: return PROPERTY_TYPE_BUTTON; case Property::COMMAND: default: return PROPERTY_TYPE_UNKNOWN; }; } <commit_msg>setStruct takes over given flags<commit_after> #include "Property.h" #include "base_types.h" #include "logging.h" #include "utils.h" #include "Error.h" #include <cstring> #include <algorithm> using namespace tcam; Property::Property () : value_type(UNDEFINED), prop(), ref_prop() {} Property::Property (const camera_property& property, VALUE_TYPE t) : prop(property), ref_prop(property), value_type(t) {} Property::Property (const camera_property& property, const std::map<std::string, int>& mapping, VALUE_TYPE t) : prop(property), ref_prop(property), string_map(mapping), value_type(t) {} Property::~Property () {} void Property::reset () { tcam_log(TCAM_LOG_INFO, "Resetting property to initial values."); prop = ref_prop; notifyImpl(); } bool Property::update () { if (impl.expired()) { setError(Error("Property implementation has expired.", ENOENT)); return false; } auto ptr = impl.lock(); tcam_log(TCAM_LOG_DEBUG, "Updating %s", prop.name); return ptr->getProperty(*this); } PROPERTY_ID Property::getID () const { return prop.id; } std::string Property::getName () const { return prop.name; } PROPERTY_TYPE Property::getType () const { return prop.type; } bool Property::isReadOnly () const { return is_bit_set(prop.flags, PROPERTY_FLAG_READ_ONLY); } bool Property::isWriteOnly () const { return is_bit_set(prop.flags, PROPERTY_FLAG_WRITE_ONLY); } bool Property::isDisabled () const { return is_bit_set(prop.flags, PROPERTY_FLAG_DISABLED); } uint32_t Property::getFlags () const { return prop.flags; } struct camera_property Property::getStruct () const { return prop; } bool Property::setStruct (const struct camera_property& p) { switch (prop.type) { case PROPERTY_TYPE_STRING: std::strncpy(prop.value.s.value, p.value.s.value, sizeof(prop.value.s.value)); case PROPERTY_TYPE_STRING_TABLE: prop.value.i.value = p.value.i.value; break; case PROPERTY_TYPE_INTEGER: prop.value.i.value = p.value.i.value; break; case PROPERTY_TYPE_DOUBLE: prop.value.d.value = p.value.d.value; break; case PROPERTY_TYPE_BUTTON: // do nothing break; case PROPERTY_TYPE_BOOLEAN: prop.value.b.value = p.value.b.value; break; case PROPERTY_TYPE_UNKNOWN: default: return false; } prop.flags = p.flags; return true; } Property::VALUE_TYPE Property::getValueType () const { return value_type; } std::string Property::toString () const { std::string property_string; switch (prop.type) { case PROPERTY_TYPE_BOOLEAN: { if (prop.value.b.value) { property_string += "true"; } else { property_string += "false"; } break; } case PROPERTY_TYPE_BITMASK: case PROPERTY_TYPE_INTEGER: { property_string += std::to_string(prop.value.i.value); break; } case PROPERTY_TYPE_DOUBLE: { property_string += std::to_string(prop.value.d.value); break; } case PROPERTY_TYPE_STRING: { property_string += prop.value.s.value; break; } case PROPERTY_TYPE_STRING_TABLE: { } case PROPERTY_TYPE_BUTTON: { } case PROPERTY_TYPE_UNKNOWN: default: { } } return property_string; } bool Property::fromString (const std::string& s) { try { switch (prop.type) { case PROPERTY_TYPE_BOOLEAN: { if (s.compare("true") == 0) { prop.value.b.value = true; } else { prop.value.b.value = false; } break; } case PROPERTY_TYPE_BITMASK: case PROPERTY_TYPE_INTEGER: { prop.value.i.value = stoi(s); break; } case PROPERTY_TYPE_DOUBLE: { prop.value.d.value = stod(s); break; } case PROPERTY_TYPE_STRING: { strncpy(prop.value.s.value, s.c_str(), sizeof(prop.value.s.value)); prop.value.s.value[sizeof(prop.value.s.value)-1] = '\0'; break; } case PROPERTY_TYPE_STRING_TABLE: { } case PROPERTY_TYPE_BUTTON: case PROPERTY_TYPE_UNKNOWN: default: { return false; } } } catch (const std::invalid_argument& e) { return false; } catch (const std::out_of_range& e) { return false; } return true; } bool Property::setReadOnly (bool only_read) { if (only_read) { prop.flags = set_bit(prop.flags, PROPERTY_FLAG_READ_ONLY); } else { prop.flags = unset_bit(prop.flags, PROPERTY_FLAG_READ_ONLY); } return true; } bool Property::setWriteOnly (bool only_write) { if (only_write) { prop.flags = set_bit(prop.flags, PROPERTY_FLAG_WRITE_ONLY); } else { prop.flags = unset_bit(prop.flags, PROPERTY_FLAG_WRITE_ONLY); } return true; } bool Property::setInactive (bool is_disabled) { if (is_disabled) { prop.flags = set_bit(prop.flags, PROPERTY_FLAG_INACTIVE); } else { prop.flags = unset_bit(prop.flags, PROPERTY_FLAG_INACTIVE); } return true; } bool Property::setProperty (const Property&) { if (impl.expired()) { return false; } notifyImpl(); return true; } bool Property::getProperty (Property& p) { p.setStruct(this->prop); return true; } void Property::notifyImpl () { if (impl.expired()) { tcam_log(TCAM_LOG_ERROR, "PropertyImpl expired. Property %s is corrupted.", this->getName().c_str()); } auto ptr(impl.lock()); ptr->setProperty(*this); } PROPERTY_TYPE tcam::value_type_to_ctrl_type (const Property::VALUE_TYPE& t) { switch (t) { case Property::BOOLEAN: return PROPERTY_TYPE_BOOLEAN; case Property::STRING: return PROPERTY_TYPE_STRING; case Property::ENUM: return PROPERTY_TYPE_STRING_TABLE; case Property::INTSWISSKNIFE: case Property::INTEGER: return PROPERTY_TYPE_INTEGER; case Property::FLOAT: return PROPERTY_TYPE_DOUBLE; case Property::BUTTON: return PROPERTY_TYPE_BUTTON; case Property::COMMAND: default: return PROPERTY_TYPE_UNKNOWN; }; } <|endoftext|>
<commit_before>#if 1 // set to 0 to build minimal lunex example #include "engine/allocators.h" #include "engine/command_line_parser.h" #include "engine/crc32.h" #include "engine/debug.h" #include "engine/engine.h" #include "engine/file_system.h" #include "engine/geometry.h" #include "engine/input_system.h" #include "engine/job_system.h" #include "engine/log.h" #include "engine/os.h" #include "engine/path.h" #include "engine/profiler.h" #include "engine/reflection.h" #include "engine/thread.h" #include "engine/universe.h" #include "gui/gui_system.h" #include "lua_script/lua_script_system.h" #include "renderer/pipeline.h" #include "renderer/render_scene.h" #include "renderer/renderer.h" using namespace Lumix; static const ComponentType ENVIRONMENT_TYPE = reflection::getComponentType("environment"); static const ComponentType LUA_SCRIPT_TYPE = reflection::getComponentType("lua_script"); struct GUIInterface : GUISystem::Interface { Pipeline* getPipeline() override { return pipeline; } Vec2 getPos() const override { return Vec2(0); } Vec2 getSize() const override { return size; } void setCursor(os::CursorType type) override { os::setCursor(type); } void enableCursor(bool enable) override { os::showCursor(enable); } Vec2 size; Pipeline* pipeline; }; struct Runner final { Runner() : m_allocator(m_main_allocator) { if (!JobSystem::init(os::getCPUsCount(), m_allocator)) { logError("Failed to initialize job system."); } } ~Runner() { JobSystem::shutdown(); ASSERT(!m_universe); } void onResize() { if (!m_engine.get()) return; if (m_engine->getWindowHandle() == os::INVALID_WINDOW) return; const os::Rect r = os::getWindowClientRect(m_engine->getWindowHandle()); m_viewport.w = r.width; m_viewport.h = r.height; m_gui_interface.size = Vec2((float)r.width, (float)r.height); } void initRenderPipeline() { m_viewport.fov = degreesToRadians(60.f); m_viewport.far = 10'000.f; m_viewport.is_ortho = false; m_viewport.near = 0.1f; m_viewport.pos = {0, 0, 0}; m_viewport.rot = Quat::IDENTITY; m_renderer = static_cast<Renderer*>(m_engine->getPluginManager().getPlugin("renderer")); PipelineResource* pres = m_engine->getResourceManager().load<PipelineResource>(Path("pipelines/main.pln")); m_pipeline = Pipeline::create(*m_renderer, pres, "APP", m_engine->getAllocator()); while (m_engine->getFileSystem().hasWork()) { os::sleep(100); m_engine->getFileSystem().processCallbacks(); } m_pipeline->setUniverse(m_universe); } void initDemoScene() { const EntityRef env = m_universe->createEntity({0, 0, 0}, Quat::IDENTITY); m_universe->createComponent(ENVIRONMENT_TYPE, env); m_universe->createComponent(LUA_SCRIPT_TYPE, env); RenderScene* render_scene = (RenderScene*)m_universe->getScene(crc32("renderer")); Environment& environment = render_scene->getEnvironment(env); environment.diffuse_intensity = 3; Quat rot; rot.fromEuler(Vec3(degreesToRadians(45.f), 0, 0)); m_universe->setRotation(env, rot); LuaScriptScene* lua_scene = (LuaScriptScene*)m_universe->getScene(crc32("lua_script")); lua_scene->addScript(env, 0); lua_scene->setScriptPath(env, 0, Path("pipelines/atmo.lua")); } bool loadUniverse(const char* path) { FileSystem& fs = m_engine->getFileSystem(); OutputMemoryStream data(m_allocator); if (!fs.getContentSync(Path(path), Ref(data))) return false; InputMemoryStream tmp(data); EntityMap entity_map(m_allocator); struct Header { u32 magic; i32 version; u32 hash; u32 engine_hash; } header; tmp.read(Ref(header)); m_universe->setName("main"); if (!m_engine->deserialize(*m_universe, tmp, Ref(entity_map))) { logError("Failed to deserialize universes/main/entities.unv"); return false; } return true; } void onInit() { Engine::InitArgs init_data; if (os::fileExists("main.pak")) { init_data.file_system = FileSystem::createPacked("main.pak", m_allocator); } m_engine = Engine::create(static_cast<Engine::InitArgs&&>(init_data), m_allocator); m_universe = &m_engine->createUniverse(true); initRenderPipeline(); auto* gui = static_cast<GUISystem*>(m_engine->getPluginManager().getPlugin("gui")); m_gui_interface.pipeline = m_pipeline.get(); gui->setInterface(&m_gui_interface); if (!loadUniverse("universes/main/entities.unv")) { initDemoScene(); } while (m_engine->getFileSystem().hasWork()) { os::sleep(10); m_engine->getFileSystem().processCallbacks(); } m_engine->getFileSystem().processCallbacks(); os::showCursor(false); onResize(); m_engine->startGame(*m_universe); } void shutdown() { m_engine->destroyUniverse(*m_universe); auto* gui = static_cast<GUISystem*>(m_engine->getPluginManager().getPlugin("gui")); gui->setInterface(nullptr); m_pipeline.reset(); m_engine.reset(); m_universe = nullptr; } void onEvent(const os::Event& event) { if (m_engine.get()) { InputSystem& input = m_engine->getInputSystem(); input.injectEvent(event, 0, 0); } switch (event.type) { case os::Event::Type::QUIT: case os::Event::Type::WINDOW_CLOSE: m_finished = true; break; case os::Event::Type::WINDOW_MOVE: case os::Event::Type::WINDOW_SIZE: onResize(); break; } } void onIdle() { m_engine->update(*m_universe); EntityPtr camera = m_pipeline->getScene()->getActiveCamera(); if (camera.isValid()) { int w = m_viewport.w; int h = m_viewport.h; m_viewport = m_pipeline->getScene()->getCameraViewport((EntityRef)camera); m_viewport.w = w; m_viewport.h = h; } m_pipeline->setViewport(m_viewport); m_pipeline->render(false); m_renderer->frame(); } DefaultAllocator m_main_allocator; debug::Allocator m_allocator; UniquePtr<Engine> m_engine; Renderer* m_renderer = nullptr; Universe* m_universe = nullptr; UniquePtr<Pipeline> m_pipeline; Viewport m_viewport; bool m_finished = false; GUIInterface m_gui_interface; }; int main(int args, char* argv[]) { Profiler::setThreadName("Main thread"); struct Data { Data() : semaphore(0, 1) {} Runner app; Semaphore semaphore; } data; JobSystem::runEx(&data, [](void* ptr) { Data* data = (Data*)ptr; data->app.onInit(); while(!data->app.m_finished) { os::Event e; while(os::getEvent(Ref(e))) { data->app.onEvent(e); } data->app.onIdle(); } data->app.shutdown(); data->semaphore.signal(); }, nullptr, JobSystem::INVALID_HANDLE, 0); PROFILE_BLOCK("sleeping"); data.semaphore.wait(); return 0; } #else #include "engine/allocators.h" #include "engine/os.h" #include "renderer/gpu/gpu.h" using namespace Lumix; int main(int args, char* argv[]) { os::WindowHandle win = os::createWindow({}); DefaultAllocator allocator; gpu::preinit(allocator, false); gpu::init(win, gpu::InitFlags::NONE); gpu::ProgramHandle shader = gpu::allocProgramHandle(); const gpu::ShaderType types[] = {gpu::ShaderType::VERTEX, gpu::ShaderType::FRAGMENT}; const char* srcs[] = { "void main() { gl_Position = vec4(gl_VertexID & 1, (gl_VertexID >> 1) & 1, 0, 1); }", "layout(location = 0) out vec4 color; void main() { color = vec4(1, 0, 1, 1); }", }; gpu::createProgram(shader, {}, srcs, types, 2, nullptr, 0, "shader"); bool finished = false; while (!finished) { os::Event e; while (os::getEvent(Ref(e))) { switch (e.type) { case os::Event::Type::WINDOW_CLOSE: case os::Event::Type::QUIT: finished = true; break; } } gpu::setFramebuffer(nullptr, 0, gpu::INVALID_TEXTURE, gpu::FramebufferFlags::NONE); const float clear_col[] = {0, 0, 0, 1}; gpu::clear(gpu::ClearFlags::COLOR | gpu::ClearFlags::DEPTH, clear_col, 0); gpu::useProgram(shader); gpu::setState(gpu::StateFlags::NONE); gpu::drawArrays(gpu::PrimitiveType::TRIANGLES, 0, 3); u32 frame = gpu::swapBuffers(); gpu::waitFrame(frame); } gpu::shutdown(); os::destroyWindow(win); } #endif<commit_msg>fixed app<commit_after>#if 1 // set to 0 to build minimal lunex example #include "engine/allocators.h" #include "engine/command_line_parser.h" #include "engine/crc32.h" #include "engine/debug.h" #include "engine/engine.h" #include "engine/file_system.h" #include "engine/geometry.h" #include "engine/input_system.h" #include "engine/job_system.h" #include "engine/log.h" #include "engine/os.h" #include "engine/path.h" #include "engine/profiler.h" #include "engine/reflection.h" #include "engine/resource_manager.h" #include "engine/thread.h" #include "engine/universe.h" #include "gui/gui_system.h" #include "lua_script/lua_script_system.h" #include "renderer/pipeline.h" #include "renderer/render_scene.h" #include "renderer/renderer.h" using namespace Lumix; static const ComponentType ENVIRONMENT_TYPE = reflection::getComponentType("environment"); static const ComponentType LUA_SCRIPT_TYPE = reflection::getComponentType("lua_script"); struct GUIInterface : GUISystem::Interface { Pipeline* getPipeline() override { return pipeline; } Vec2 getPos() const override { return Vec2(0); } Vec2 getSize() const override { return size; } void setCursor(os::CursorType type) override { os::setCursor(type); } void enableCursor(bool enable) override { os::showCursor(enable); } Vec2 size; Pipeline* pipeline; }; struct Runner final { Runner() : m_allocator(m_main_allocator) { if (!jobs::init(os::getCPUsCount(), m_allocator)) { logError("Failed to initialize job system."); } } ~Runner() { jobs::shutdown(); ASSERT(!m_universe); } void onResize() { if (!m_engine.get()) return; if (m_engine->getWindowHandle() == os::INVALID_WINDOW) return; const os::Rect r = os::getWindowClientRect(m_engine->getWindowHandle()); m_viewport.w = r.width; m_viewport.h = r.height; m_gui_interface.size = Vec2((float)r.width, (float)r.height); } void initRenderPipeline() { m_viewport.fov = degreesToRadians(60.f); m_viewport.far = 10'000.f; m_viewport.is_ortho = false; m_viewport.near = 0.1f; m_viewport.pos = {0, 0, 0}; m_viewport.rot = Quat::IDENTITY; m_renderer = static_cast<Renderer*>(m_engine->getPluginManager().getPlugin("renderer")); PipelineResource* pres = m_engine->getResourceManager().load<PipelineResource>(Path("pipelines/main.pln")); m_pipeline = Pipeline::create(*m_renderer, pres, "APP", m_engine->getAllocator()); while (m_engine->getFileSystem().hasWork()) { os::sleep(100); m_engine->getFileSystem().processCallbacks(); } m_pipeline->setUniverse(m_universe); } void initDemoScene() { const EntityRef env = m_universe->createEntity({0, 0, 0}, Quat::IDENTITY); m_universe->createComponent(ENVIRONMENT_TYPE, env); m_universe->createComponent(LUA_SCRIPT_TYPE, env); RenderScene* render_scene = (RenderScene*)m_universe->getScene(crc32("renderer")); Environment& environment = render_scene->getEnvironment(env); environment.diffuse_intensity = 3; Quat rot; rot.fromEuler(Vec3(degreesToRadians(45.f), 0, 0)); m_universe->setRotation(env, rot); LuaScriptScene* lua_scene = (LuaScriptScene*)m_universe->getScene(crc32("lua_script")); lua_scene->addScript(env, 0); lua_scene->setScriptPath(env, 0, Path("pipelines/atmo.lua")); } bool loadUniverse(const char* path) { FileSystem& fs = m_engine->getFileSystem(); OutputMemoryStream data(m_allocator); if (!fs.getContentSync(Path(path), Ref(data))) return false; InputMemoryStream tmp(data); EntityMap entity_map(m_allocator); struct Header { u32 magic; i32 version; u32 hash; u32 engine_hash; } header; tmp.read(Ref(header)); m_universe->setName("main"); if (!m_engine->deserialize(*m_universe, tmp, Ref(entity_map))) { logError("Failed to deserialize universes/main/entities.unv"); return false; } return true; } void onInit() { Engine::InitArgs init_data; if (os::fileExists("main.pak")) { init_data.file_system = FileSystem::createPacked("main.pak", m_allocator); } m_engine = Engine::create(static_cast<Engine::InitArgs&&>(init_data), m_allocator); m_universe = &m_engine->createUniverse(true); initRenderPipeline(); auto* gui = static_cast<GUISystem*>(m_engine->getPluginManager().getPlugin("gui")); m_gui_interface.pipeline = m_pipeline.get(); gui->setInterface(&m_gui_interface); if (!loadUniverse("universes/main/entities.unv")) { initDemoScene(); } while (m_engine->getFileSystem().hasWork()) { os::sleep(10); m_engine->getFileSystem().processCallbacks(); } m_engine->getFileSystem().processCallbacks(); os::showCursor(false); onResize(); m_engine->startGame(*m_universe); } void shutdown() { m_engine->destroyUniverse(*m_universe); auto* gui = static_cast<GUISystem*>(m_engine->getPluginManager().getPlugin("gui")); gui->setInterface(nullptr); m_pipeline.reset(); m_engine.reset(); m_universe = nullptr; } void onEvent(const os::Event& event) { if (m_engine.get()) { InputSystem& input = m_engine->getInputSystem(); input.injectEvent(event, 0, 0); } switch (event.type) { case os::Event::Type::QUIT: case os::Event::Type::WINDOW_CLOSE: m_finished = true; break; case os::Event::Type::WINDOW_MOVE: case os::Event::Type::WINDOW_SIZE: onResize(); break; } } void onIdle() { m_engine->update(*m_universe); EntityPtr camera = m_pipeline->getScene()->getActiveCamera(); if (camera.isValid()) { int w = m_viewport.w; int h = m_viewport.h; m_viewport = m_pipeline->getScene()->getCameraViewport((EntityRef)camera); m_viewport.w = w; m_viewport.h = h; } m_pipeline->setViewport(m_viewport); m_pipeline->render(false); m_renderer->frame(); } DefaultAllocator m_main_allocator; debug::Allocator m_allocator; UniquePtr<Engine> m_engine; Renderer* m_renderer = nullptr; Universe* m_universe = nullptr; UniquePtr<Pipeline> m_pipeline; Viewport m_viewport; bool m_finished = false; GUIInterface m_gui_interface; }; int main(int args, char* argv[]) { profiler::setThreadName("Main thread"); struct Data { Data() : semaphore(0, 1) {} Runner app; Semaphore semaphore; } data; jobs::runEx(&data, [](void* ptr) { Data* data = (Data*)ptr; data->app.onInit(); while(!data->app.m_finished) { os::Event e; while(os::getEvent(Ref(e))) { data->app.onEvent(e); } data->app.onIdle(); } data->app.shutdown(); data->semaphore.signal(); }, nullptr, jobs::INVALID_HANDLE, 0); PROFILE_BLOCK("sleeping"); data.semaphore.wait(); return 0; } #else #include "engine/allocators.h" #include "engine/os.h" #include "renderer/gpu/gpu.h" using namespace Lumix; int main(int args, char* argv[]) { os::WindowHandle win = os::createWindow({}); DefaultAllocator allocator; gpu::preinit(allocator, false); gpu::init(win, gpu::InitFlags::NONE); gpu::ProgramHandle shader = gpu::allocProgramHandle(); const gpu::ShaderType types[] = {gpu::ShaderType::VERTEX, gpu::ShaderType::FRAGMENT}; const char* srcs[] = { "void main() { gl_Position = vec4(gl_VertexID & 1, (gl_VertexID >> 1) & 1, 0, 1); }", "layout(location = 0) out vec4 color; void main() { color = vec4(1, 0, 1, 1); }", }; gpu::createProgram(shader, {}, srcs, types, 2, nullptr, 0, "shader"); bool finished = false; while (!finished) { os::Event e; while (os::getEvent(Ref(e))) { switch (e.type) { case os::Event::Type::WINDOW_CLOSE: case os::Event::Type::QUIT: finished = true; break; } } gpu::setFramebuffer(nullptr, 0, gpu::INVALID_TEXTURE, gpu::FramebufferFlags::NONE); const float clear_col[] = {0, 0, 0, 1}; gpu::clear(gpu::ClearFlags::COLOR | gpu::ClearFlags::DEPTH, clear_col, 0); gpu::useProgram(shader); gpu::setState(gpu::StateFlags::NONE); gpu::drawArrays(gpu::PrimitiveType::TRIANGLES, 0, 3); u32 frame = gpu::swapBuffers(); gpu::waitFrame(frame); } gpu::shutdown(); os::destroyWindow(win); } #endif<|endoftext|>
<commit_before>/// /// @file main.cpp /// @brief primesum console application. /// /// Copyright (C) 2016 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include "cmdoptions.hpp" #include <primesum-internal.hpp> #include <primesum.hpp> #include <pmath.hpp> #include <int128.hpp> #include <PhiTiny.hpp> #include <S1.hpp> #include <S2.hpp> #include <stdint.h> #include <exception> #include <iostream> #include <limits> #include <string> #ifdef HAVE_MPI #include <mpi.h> #endif using namespace std; using namespace primesum; namespace primesum { int64_t int64_cast(maxint_t x) { if (x > numeric_limits<int64_t>::max()) throw primesum_error("this is a 63-bit function, x must be < 2^63"); return (int64_t) x; } maxint_t P2(maxint_t x, int threads) { if (x < 1) return 0; double alpha = get_alpha_deleglise_rivat(x); string limit = get_max_x(alpha); if (x > to_maxint(limit)) throw primesum_error("P2(x): x must be <= " + limit); if (print_status()) set_print_variables(true); int64_t y = (int64_t) (iroot<3>(x) * alpha); return P2(x, y, threads); } maxint_t S1(maxint_t x, int threads) { if (x < 1) return 0; double alpha = get_alpha_deleglise_rivat(x); string limit = get_max_x(alpha); if (x > to_maxint(limit)) throw primesum_error("S1(x): x must be <= " + limit); if (print_status()) set_print_variables(true); int64_t y = (int64_t) (iroot<3>(x) * alpha); int64_t c = PhiTiny::get_c(y); return S1(x, y, c, threads); } maxint_t S2_trivial(maxint_t x, int threads) { if (x < 1) return 0; double alpha = get_alpha_deleglise_rivat(x); string limit = get_max_x(alpha); if (x > to_maxint(limit)) throw primesum_error("S2_trivial(x): x must be <= " + limit); if (print_status()) set_print_variables(true); int64_t y = (int64_t) (iroot<3>(x) * alpha); int64_t z = (int64_t) (x / y); int64_t c = PhiTiny::get_c(y); if (x <= numeric_limits<int64_t>::max()) return S2_trivial((int64_t) x, y, z, c, threads); else return S2_trivial(x, y, z, c, threads); } maxint_t S2_easy(maxint_t x, int threads) { if (x < 1) return 0; double alpha = get_alpha_deleglise_rivat(x); string limit = get_max_x(alpha); if (x > to_maxint(limit)) throw primesum_error("S2_easy(x): x must be <= " + limit); if (print_status()) set_print_variables(true); int64_t y = (int64_t) (iroot<3>(x) * alpha); int64_t z = (int64_t) (x / y); int64_t c = PhiTiny::get_c(y); if (x <= numeric_limits<int64_t>::max()) return S2_easy((int64_t) x, y, z, c, threads); else return S2_easy(x, y, z, c, threads); } maxint_t S2_hard(maxint_t x, int threads) { if (x < 1) return 0; double alpha = get_alpha_deleglise_rivat(x); string limit = get_max_x(alpha); if (x > to_maxint(limit)) throw primesum_error("S2_hard(x): x must be <= " + limit); if (print_status()) set_print_variables(true); int64_t y = (int64_t) (iroot<3>(x) * alpha); int64_t z = (int64_t) (x / y); int64_t c = PhiTiny::get_c(y); return S2_hard(x, y, z, c, alpha, threads); } } // namespace primesum int main (int argc, char* argv[]) { #ifdef HAVE_MPI MPI_Init(&argc, &argv); #endif PrimeSumOptions pco = parseOptions(argc, argv); double time = get_wtime(); maxint_t x = pco.x; maxint_t res = 0; int threads = pco.threads; try { switch (pco.option) { case OPTION_DELEGLISE_RIVAT: res = pi_deleglise_rivat(x, threads); break; case OPTION_DELEGLISE_RIVAT_PARALLEL1: res = pi_deleglise_rivat_parallel1(x, threads); break; case OPTION_LMO: res = pi_lmo(int64_cast(x), threads); break; case OPTION_LMO1: res = pi_lmo1(int64_cast(x)); break; case OPTION_LMO2: res = pi_lmo2(int64_cast(x)); break; case OPTION_LMO3: res = pi_lmo3(int64_cast(x)); break; case OPTION_LMO4: res = pi_lmo4(int64_cast(x)); break; case OPTION_LMO5: res = pi_lmo5(int64_cast(x)); break; case OPTION_LMO_PARALLEL1: res = pi_lmo_parallel1(int64_cast(x), threads); break; case OPTION_P2: res = P2(x, threads); break; case OPTION_PI: res = pi(x, threads); break; case OPTION_S1: res = S1(x, threads); break; case OPTION_S2_EASY: res = S2_easy(x, threads); break; case OPTION_S2_HARD: res = S2_hard(x, threads); break; case OPTION_S2_TRIVIAL: res = S2_trivial(x, threads); break; } } catch (bad_alloc&) { #ifdef HAVE_MPI MPI_Finalize(); #endif cerr << "Error: failed to allocate memory, your system most likely does" << endl << " not have enough memory to run this computation." << endl; return 1; } catch (exception& e) { #ifdef HAVE_MPI MPI_Finalize(); #endif cerr << "Error: " << e.what() << endl; return 1; } if (print_result()) { if (print_status()) cout << endl; cout << res << endl; if (pco.time) print_seconds(get_wtime() - time); } #ifdef HAVE_MPI MPI_Finalize(); #endif return 0; } <commit_msg>print error message if x > 10^20<commit_after>/// /// @file main.cpp /// @brief primesum console application. /// /// Copyright (C) 2016 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include "cmdoptions.hpp" #include <primesum-internal.hpp> #include <primesum.hpp> #include <pmath.hpp> #include <int128.hpp> #include <PhiTiny.hpp> #include <S1.hpp> #include <S2.hpp> #include <stdint.h> #include <exception> #include <iostream> #include <limits> #include <string> #ifdef HAVE_MPI #include <mpi.h> #endif using namespace std; using namespace primesum; namespace primesum { int64_t int64_cast(maxint_t x) { if (x > numeric_limits<int64_t>::max()) throw primesum_error("this is a 63-bit function, x must be < 2^63"); return (int64_t) x; } maxint_t P2(maxint_t x, int threads) { if (x < 1) return 0; double alpha = get_alpha_deleglise_rivat(x); string limit = get_max_x(alpha); if (x > to_maxint(limit)) throw primesum_error("P2(x): x must be <= " + limit); if (print_status()) set_print_variables(true); int64_t y = (int64_t) (iroot<3>(x) * alpha); return P2(x, y, threads); } maxint_t S1(maxint_t x, int threads) { if (x < 1) return 0; double alpha = get_alpha_deleglise_rivat(x); string limit = get_max_x(alpha); if (x > to_maxint(limit)) throw primesum_error("S1(x): x must be <= " + limit); if (print_status()) set_print_variables(true); int64_t y = (int64_t) (iroot<3>(x) * alpha); int64_t c = PhiTiny::get_c(y); return S1(x, y, c, threads); } maxint_t S2_trivial(maxint_t x, int threads) { if (x < 1) return 0; double alpha = get_alpha_deleglise_rivat(x); string limit = get_max_x(alpha); if (x > to_maxint(limit)) throw primesum_error("S2_trivial(x): x must be <= " + limit); if (print_status()) set_print_variables(true); int64_t y = (int64_t) (iroot<3>(x) * alpha); int64_t z = (int64_t) (x / y); int64_t c = PhiTiny::get_c(y); if (x <= numeric_limits<int64_t>::max()) return S2_trivial((int64_t) x, y, z, c, threads); else return S2_trivial(x, y, z, c, threads); } maxint_t S2_easy(maxint_t x, int threads) { if (x < 1) return 0; double alpha = get_alpha_deleglise_rivat(x); string limit = get_max_x(alpha); if (x > to_maxint(limit)) throw primesum_error("S2_easy(x): x must be <= " + limit); if (print_status()) set_print_variables(true); int64_t y = (int64_t) (iroot<3>(x) * alpha); int64_t z = (int64_t) (x / y); int64_t c = PhiTiny::get_c(y); if (x <= numeric_limits<int64_t>::max()) return S2_easy((int64_t) x, y, z, c, threads); else return S2_easy(x, y, z, c, threads); } maxint_t S2_hard(maxint_t x, int threads) { if (x < 1) return 0; double alpha = get_alpha_deleglise_rivat(x); string limit = get_max_x(alpha); if (x > to_maxint(limit)) throw primesum_error("S2_hard(x): x must be <= " + limit); if (print_status()) set_print_variables(true); int64_t y = (int64_t) (iroot<3>(x) * alpha); int64_t z = (int64_t) (x / y); int64_t c = PhiTiny::get_c(y); return S2_hard(x, y, z, c, alpha, threads); } } // namespace primesum int main (int argc, char* argv[]) { #ifdef HAVE_MPI MPI_Init(&argc, &argv); #endif PrimeSumOptions pco = parseOptions(argc, argv); double time = get_wtime(); maxint_t x = pco.x; maxint_t res = 0; int threads = pco.threads; try { if ((double) x > 1e20) throw primesum_error("this primesum version only works up to 10^20"); switch (pco.option) { case OPTION_DELEGLISE_RIVAT: res = pi_deleglise_rivat(x, threads); break; case OPTION_DELEGLISE_RIVAT_PARALLEL1: res = pi_deleglise_rivat_parallel1(x, threads); break; case OPTION_LMO: res = pi_lmo(int64_cast(x), threads); break; case OPTION_LMO1: res = pi_lmo1(int64_cast(x)); break; case OPTION_LMO2: res = pi_lmo2(int64_cast(x)); break; case OPTION_LMO3: res = pi_lmo3(int64_cast(x)); break; case OPTION_LMO4: res = pi_lmo4(int64_cast(x)); break; case OPTION_LMO5: res = pi_lmo5(int64_cast(x)); break; case OPTION_LMO_PARALLEL1: res = pi_lmo_parallel1(int64_cast(x), threads); break; case OPTION_P2: res = P2(x, threads); break; case OPTION_PI: res = pi(x, threads); break; case OPTION_S1: res = S1(x, threads); break; case OPTION_S2_EASY: res = S2_easy(x, threads); break; case OPTION_S2_HARD: res = S2_hard(x, threads); break; case OPTION_S2_TRIVIAL: res = S2_trivial(x, threads); break; } } catch (bad_alloc&) { #ifdef HAVE_MPI MPI_Finalize(); #endif cerr << "Error: failed to allocate memory, your system most likely does" << endl << " not have enough memory to run this computation." << endl; return 1; } catch (exception& e) { #ifdef HAVE_MPI MPI_Finalize(); #endif cerr << "Error: " << e.what() << endl; return 1; } if (print_result()) { if (print_status()) cout << endl; cout << res << endl; if (pco.time) print_seconds(get_wtime() - time); } #ifdef HAVE_MPI MPI_Finalize(); #endif return 0; } <|endoftext|>
<commit_before>#include <ros/ros.h> #include <humanoid_catching/CalculateTorques.h> #include <Moby/qpOASES.h> #include <Ravelin/VectorNd.h> #include <Ravelin/MatrixNd.h> #include <Ravelin/Quatd.h> #include <Ravelin/Opsd.h> #include <Moby/qpOASES.h> #include <Ravelin/LinAlgd.h> namespace { using namespace std; using namespace humanoid_catching; using namespace Ravelin; static const double GRAVITY = 9.81; class Balancer { private: //! Node handle ros::NodeHandle nh; //! Private nh ros::NodeHandle pnh; //! Balancer Service ros::ServiceServer balancerService; public: Balancer() : pnh("~") { balancerService = nh.advertiseService("/balancer/torques", &Balancer::calculateTorques, this); } private: /** * Convert a geometry_msgs::Vector3 to a Ravelin::Vector3d * @param v3 geometry_msgs::Vector3 * @return Ravelin Vector3d */ static Vector3d toVector(const geometry_msgs::Vector3& v3) { Vector3d v; v[0] = v3.x; v[1] = v3.y; v[2] = v3.z; return v; } /** * Convert a geometry_msgs::Point to a Ravelin::Vector3d * @param p geometry_msgs::Point * @return Ravelin Vector3d */ static Vector3d toVector(const geometry_msgs::Point& p) { Vector3d v; v[0] = p.x; v[1] = p.y; v[2] = p.z; return v; } /** * Calculate balancing torques * @param req Request * @param res Response * @return Success */ bool calculateTorques(humanoid_catching::CalculateTorques::Request& req, humanoid_catching::CalculateTorques::Response& res) { ROS_INFO("Calculating torques frame %s", req.header.frame_id.c_str()); // x // linear velocity of body ROS_INFO("Calculating x vector"); const Vector3d x = toVector(req.body_velocity.linear); ROS_INFO_STREAM("x: " << x); // w // angular velocity of body ROS_INFO("Calculating w vector"); const Vector3d w = toVector(req.body_velocity.angular); ROS_INFO_STREAM("w: " << w); // v(t) // | x | // | w | ROS_INFO("Calculating v vector"); VectorNd v(6); v.set_sub_vec(0, x); v.set_sub_vec(3, w); ROS_INFO_STREAM("v: " << v); // R // Pole rotation matrix ROS_INFO("Calculating R matrix"); const Matrix3d R = Quatd(req.body_com.orientation.x, req.body_com.orientation.y, req.body_com.orientation.z, req.body_com.orientation.w); ROS_INFO_STREAM("R: " << R); // J // Pole inertia matrix ROS_INFO("Calculating J matrix"); ROS_INFO_STREAM("BIM: " << req.body_inertia_matrix.size()); const Matrix3d J = Matrix3d(&req.body_inertia_matrix[0]); ROS_INFO_STREAM("J: " << J); // JRobot // Robot end effector jacobian matrix ROS_INFO("Calculating JRobot"); const MatrixNd JRobot = MatrixNd(req.torque_limits.size(), 6, &req.jacobian_matrix[0]); ROS_INFO_STREAM("JRobot: " << JRobot); // RJR_t ROS_INFO("Calculating RJR"); Matrix3d RJ, RJR; R.mult(J, RJ); RJ.mult_transpose(R, RJR); ROS_INFO_STREAM("RJR: " << RJR); // M // | Im 0 | // | 0 RJR_t| ROS_INFO("Calculating M"); MatrixNd M(6, 6); M.set_zero(M.rows(), M.columns()); M.set_sub_mat(0, 0, Matrix3d::identity() * req.body_mass); M.set_sub_mat(3, 3, RJR); ROS_INFO_STREAM("M: " << M); // delta t double deltaT = req.time_delta.toSec(); // Working vector Vector3d tempVector; // fext // | g | // | -w x RJR_tw | ROS_INFO("Calculating fExt"); VectorNd fExt(6); fExt[0] = 0; fExt[1] = 0; fExt[2] = GRAVITY; fExt.set_sub_vec(3, Vector3d::cross(-w, RJR.mult(w, tempVector))); ROS_INFO_STREAM("fExt: " << fExt); // n_hat // x component of ground contact position ROS_INFO("Calculating nHat"); Vector3d nHat; nHat[0] = req.ground_contact.x; nHat[1] = 0; nHat[2] = 0; ROS_INFO_STREAM("nHat: " << nHat); // s_hat // s component of contact position ROS_INFO("Calculating sHat"); Vector3d sHat; nHat[0] = 0; nHat[1] = req.ground_contact.y; nHat[2] = 0; ROS_INFO_STREAM("sHat: " << sHat); // t_hat // z component of contact position ROS_INFO("Calculating tHat"); Vector3d tHat; tHat[0] = 0; tHat[1] = 0; tHat[2] = req.ground_contact.z; ROS_INFO_STREAM("tHat: " << tHat); // q_hat // contact normal ROS_INFO("Calculating qHat"); const Vector3d qHat = toVector(req.contact_normal); ROS_INFO_STREAM("qHat: " << qHat); // p // contact point ROS_INFO("Calculating P"); const Vector3d p = toVector(req.ground_contact); ROS_INFO_STREAM("p: " << p); // x_bar // pole COM ROS_INFO("Calculating xBar"); const Vector3d xBar = toVector(req.body_com.position); ROS_INFO_STREAM("xBar: " << xBar); // r ROS_INFO("Calculating r"); const Vector3d r = p - xBar; ROS_INFO_STREAM("r: " << r); // N // | n_hat | // | r x n_hat | ROS_INFO("Calculating N"); VectorNd N(6); N.set_sub_vec(0, nHat); N.set_sub_vec(3, r.cross(nHat, tempVector)); ROS_INFO_STREAM("N: " << N); // S // | s_hat | // | r x s_hat | ROS_INFO("Calculating S"); VectorNd S(6); S.set_sub_vec(0, sHat); S.set_sub_vec(3, r.cross(sHat, tempVector)); ROS_INFO_STREAM("S: " << S); // T // | t_hat | // | r x t_hat | ROS_INFO("Calculating T"); VectorNd T(6); T.set_sub_vec(0, tHat); T.set_sub_vec(3, r.cross(tHat, tempVector)); ROS_INFO_STREAM("T: " << T); // Q ROS_INFO("Calculating Q"); VectorNd Q(6); Q.set_sub_vec(0, qHat); Q.set_sub_vec(3, -r.cross(qHat, tempVector)); ROS_INFO_STREAM("Q: " << Q); // Result vector // Torques, f_n, f_s, f_t, f_robot, v_(t + tdelta) const int torqueIdx = 0; const int fNIdx = req.torque_limits.size(); const int fSIdx = fNIdx + 1; const int fTIdx = fSIdx + 1; const int fRobotIdx = fTIdx + 1; const int vTDeltaIdx = fRobotIdx + 1; VectorNd z(req.torque_limits.size() + 1 + 1 + 1 + 1 + 6); // Set up minimization function ROS_INFO("Calculating H"); MatrixNd H(6, z.size()); H.set_sub_mat(0, vTDeltaIdx, M); ROS_INFO_STREAM("H: " << H); ROS_INFO("Calculating c"); VectorNd c(6); c.set_zero(c.rows()); ROS_INFO_STREAM("c: " << c); // Linear equality constraints ROS_INFO("Calculating A + b"); MatrixNd A(1 * 2 + req.torque_limits.size() + 6, z.size()); VectorNd b(1 * 2 + req.torque_limits.size() + 6); ROS_INFO("Setting Sv constraint"); // Sv(t + t_delta) = 0 (no tangent velocity) unsigned idx = 0; A.set_sub_mat(idx, vTDeltaIdx, S); b.set_sub_vec(idx, VectorNd::zero(1)); idx += 1; ROS_INFO("Setting Tv constraint"); // Tv(t + t_delta) = 0 (no tangent velocity) A.set_sub_mat(idx, vTDeltaIdx, T); b.set_sub_vec(idx, VectorNd::zero(1)); idx += 1; ROS_INFO("Setting torque constraint"); // J_robot(transpose) * Q(transpose) * f_robot = torques // Transformed to: // J_Robot(transpose) * Q(transpose) * f_robot - I * torques = 0 MatrixNd JQ(req.torque_limits.size(), 1); MatrixNd Jt = JRobot; Jt.transpose(); MatrixNd Qt(Q, eTranspose); Jt.mult(Qt, JQ); A.set_sub_mat(idx, fRobotIdx, JQ); A.set_sub_mat(idx, torqueIdx, MatrixNd::identity(req.torque_limits.size()).negate()); b.set_sub_vec(idx, VectorNd::zero(req.torque_limits.size())); idx += req.torque_limits.size(); ROS_INFO("Setting velocity constraint"); // v_(t + t_delta) = v_t + M_inv (N_t * f_n + S_t * f_s + T_t * f_t + delta_t * f_ext + Q_t * delta_t * f_robot) // Manipulated to fit constraint form // -v_t - M_inv * delta_t * f_ext = M_inv * N_t * f_n + M_inv * S_t * f_s + M_inv * T_t * f_t + M_inv * Q_t * delta_t * f_robot + -I * v_(t + t_delta) LinAlgd linAlgd; MatrixNd MInverse = M; linAlgd.pseudo_invert(MInverse); MatrixNd MInverseN(MInverse.rows(), N.columns()); MInverse.mult(N, MInverseN); A.set_sub_mat(idx, fNIdx, MInverseN); MatrixNd MInverseS(MInverse.rows(), S.columns()); MInverse.mult(S, MInverseS); A.set_sub_mat(idx, fSIdx, MInverseS); MatrixNd MInverseT(MInverse.rows(), T.columns()); MInverse.mult(T, MInverseT); A.set_sub_mat(idx, fTIdx, MInverseT); MatrixNd MInverseQ(MInverse.rows(), Q.columns()); MInverse.mult(Q, MInverseQ); MInverseQ *= deltaT; A.set_sub_mat(idx, fRobotIdx, MInverseQ); A.set_sub_mat(idx, vTDeltaIdx, MatrixNd::identity(6).negate()); VectorNd MInverseFExt(6); MInverseFExt.set_zero(); MInverse.mult(fExt, MInverseFExt, deltaT); MInverseFExt.negate() -= v; b.set_sub_vec(idx, MInverseFExt); ROS_INFO_STREAM("A: " << A); ROS_INFO_STREAM("b: " << b); // Linear inequality constraints ROS_INFO("Calculating Mc and q"); MatrixNd Mc(6, z.size()); VectorNd q(6); // Nv(t) >= 0 (non-negative normal velocity) Mc.set_sub_mat(0, vTDeltaIdx, N); q.set_sub_vec(0, VectorNd::zero(6)); ROS_INFO_STREAM("Mc: " << Mc); ROS_INFO_STREAM("q: " << q); // Solution variable constraint ROS_INFO("Calculating lb and ub"); VectorNd lb(z.size()); VectorNd ub(z.size()); // Torque constraints unsigned int bound = 0; for (bound; bound < req.torque_limits.size(); ++bound) { lb[bound] = req.torque_limits[bound].minimum; ub[bound] = req.torque_limits[bound].maximum; } // f_n >= 0 lb[bound] = 0; ub[bound] = INFINITY; ++bound; // f_s (no constraints) lb[bound] = INFINITY; ub[bound] = INFINITY; ++bound; // f_t (no constraints) lb[bound] = INFINITY; ub[bound] = INFINITY; ++bound; // f_robot >= 0 lb[bound] = 0; ub[bound] = INFINITY; ++bound; // v_t (no constraints) for (bound; bound < z.size(); ++bound) { lb[bound] = INFINITY; ub[bound] = INFINITY; } ROS_INFO_STREAM("lb: " << lb); ROS_INFO_STREAM("ub: " << ub); // Call solver ROS_INFO("Calling solver"); Moby::QPOASES qp; if (!qp.qp_activeset(H, p, lb, ub, Mc, q, A, b, z)){ ROS_ERROR("QP failed to find feasible point"); return false; } ROS_INFO_STREAM("QP solved successfully: " << z); // Copy over result res.torques.resize(req.torque_limits.size()); for (unsigned int i = 0; i < z.size(); ++i) { res.torques[i] = z[i]; } return true; } }; } int main(int argc, char** argv) { ros::init(argc, argv, "balancer"); Balancer bal; ros::spin(); } <commit_msg>Fix review issues along with several other dimension problems<commit_after>#include <ros/ros.h> #include <humanoid_catching/CalculateTorques.h> #include <Moby/qpOASES.h> #include <Ravelin/VectorNd.h> #include <Ravelin/MatrixNd.h> #include <Ravelin/Quatd.h> #include <Ravelin/Opsd.h> #include <Moby/qpOASES.h> #include <Ravelin/LinAlgd.h> namespace { using namespace std; using namespace humanoid_catching; using namespace Ravelin; static const double GRAVITY = 9.81; class Balancer { private: //! Node handle ros::NodeHandle nh; //! Private nh ros::NodeHandle pnh; //! Balancer Service ros::ServiceServer balancerService; public: Balancer() : pnh("~") { balancerService = nh.advertiseService("/balancer/torques", &Balancer::calculateTorques, this); } private: /** * Convert a geometry_msgs::Vector3 to a Ravelin::Vector3d * @param v3 geometry_msgs::Vector3 * @return Ravelin Vector3d */ static Vector3d toVector(const geometry_msgs::Vector3& v3) { Vector3d v; v[0] = v3.x; v[1] = v3.y; v[2] = v3.z; return v; } /** * Convert a geometry_msgs::Point to a Ravelin::Vector3d * @param p geometry_msgs::Point * @return Ravelin Vector3d */ static Vector3d toVector(const geometry_msgs::Point& p) { Vector3d v; v[0] = p.x; v[1] = p.y; v[2] = p.z; return v; } /** * Calculate balancing torques * @param req Request * @param res Response * @return Success */ bool calculateTorques(humanoid_catching::CalculateTorques::Request& req, humanoid_catching::CalculateTorques::Response& res) { ROS_INFO("Calculating torques frame %s", req.header.frame_id.c_str()); // x // linear velocity of body ROS_INFO("Calculating x vector"); const Vector3d x = toVector(req.body_velocity.linear); ROS_INFO_STREAM("x: " << x); // w // angular velocity of body ROS_INFO("Calculating w vector"); const Vector3d w = toVector(req.body_velocity.angular); ROS_INFO_STREAM("w: " << w); // v(t) // | x | // | w | ROS_INFO("Calculating v vector"); VectorNd v(6); v.set_sub_vec(0, x); v.set_sub_vec(3, w); ROS_INFO_STREAM("v: " << v); // R // Pole rotation matrix ROS_INFO("Calculating R matrix"); const Matrix3d R = Quatd(req.body_com.orientation.x, req.body_com.orientation.y, req.body_com.orientation.z, req.body_com.orientation.w); ROS_INFO_STREAM("R: " << R); // J // Pole inertia matrix ROS_INFO("Calculating J matrix"); ROS_INFO_STREAM("BIM: " << req.body_inertia_matrix.size()); const Matrix3d J = Matrix3d(&req.body_inertia_matrix[0]); ROS_INFO_STREAM("J: " << J); // JRobot // Robot end effector jacobian matrix ROS_INFO("Calculating JRobot"); const MatrixNd JRobot = MatrixNd(6, req.torque_limits.size(), &req.jacobian_matrix[0]); ROS_INFO_STREAM("JRobot: " << JRobot); // RJR_t ROS_INFO("Calculating RJR"); Matrix3d RJ, RJR; R.mult(J, RJ); RJ.mult_transpose(R, RJR); ROS_INFO_STREAM("RJR: " << RJR); // M // | Im 0 | // | 0 RJR_t| ROS_INFO("Calculating M"); MatrixNd M(6, 6); M.set_zero(M.rows(), M.columns()); M.set_sub_mat(0, 0, Matrix3d::identity() * req.body_mass); M.set_sub_mat(3, 3, RJR); ROS_INFO_STREAM("M: " << M); // delta t double deltaT = req.time_delta.toSec(); // Working vector Vector3d tempVector; // fext // | g | // | -w x RJR_tw | ROS_INFO("Calculating fExt"); VectorNd fExt(6); fExt[0] = 0; fExt[1] = 0; fExt[2] = GRAVITY; fExt.set_sub_vec(3, Vector3d::cross(-w, RJR.mult(w, tempVector))); ROS_INFO_STREAM("fExt: " << fExt); // n_hat // contact normal // TODO: Pass in ground contact normal ROS_INFO("Calculating nHat"); Vector3d nHat; nHat[0] = 1; nHat[1] = 0; nHat[2] = 0; ROS_INFO_STREAM("nHat: " << nHat); // s_hat // vector orthogonal to contact normal ROS_INFO("Calculating sHat"); Vector3d sHat; nHat[0] = 0; nHat[1] = 1; nHat[2] = 0; ROS_INFO_STREAM("sHat: " << sHat); // t_hat // vector orthogonal to contact normal ROS_INFO("Calculating tHat"); Vector3d tHat; tHat[0] = 0; tHat[1] = 0; tHat[2] = 1; ROS_INFO_STREAM("tHat: " << tHat); // q_hat // contact normal ROS_INFO("Calculating qHat"); const Vector3d qHat = toVector(req.contact_normal); ROS_INFO_STREAM("qHat: " << qHat); // p // contact point ROS_INFO("Calculating P"); const Vector3d p = toVector(req.ground_contact); ROS_INFO_STREAM("p: " << p); // x_bar // pole COM ROS_INFO("Calculating xBar"); const Vector3d xBar = toVector(req.body_com.position); ROS_INFO_STREAM("xBar: " << xBar); // r ROS_INFO("Calculating r"); const Vector3d r = p - xBar; ROS_INFO_STREAM("r: " << r); // N // | n_hat | // | r x n_hat | ROS_INFO("Calculating N"); VectorNd N(6); N.set_sub_vec(0, nHat); N.set_sub_vec(3, r.cross(nHat, tempVector)); ROS_INFO_STREAM("N: " << N); // S // | s_hat | // | r x s_hat | ROS_INFO("Calculating S"); VectorNd S(6); S.set_sub_vec(0, sHat); S.set_sub_vec(3, r.cross(sHat, tempVector)); ROS_INFO_STREAM("S: " << S); // T // | t_hat | // | r x t_hat | ROS_INFO("Calculating T"); VectorNd T(6); T.set_sub_vec(0, tHat); T.set_sub_vec(3, r.cross(tHat, tempVector)); ROS_INFO_STREAM("T: " << T); // Q ROS_INFO("Calculating Q"); VectorNd Q(6); Q.set_sub_vec(0, qHat); Q.set_sub_vec(3, -r.cross(qHat, tempVector)); ROS_INFO_STREAM("Q: " << Q); // Result vector // Torques, f_n, f_s, f_t, f_robot, v_(t + tdelta) const int torqueIdx = 0; const int fNIdx = req.torque_limits.size(); const int fSIdx = fNIdx + 1; const int fTIdx = fSIdx + 1; const int fRobotIdx = fTIdx + 1; const int vTDeltaIdx = fRobotIdx + 1; VectorNd z(req.torque_limits.size() + 1 + 1 + 1 + 1 + 6); // Set up minimization function ROS_INFO("Calculating H"); MatrixNd H(z.size(), z.size()); H.set_sub_mat(vTDeltaIdx, vTDeltaIdx, M); ROS_INFO_STREAM("H: " << H); ROS_INFO("Calculating c"); VectorNd c(z.rows()); c.set_zero(c.rows()); ROS_INFO_STREAM("c: " << c); // Linear equality constraints ROS_INFO("Calculating A + b"); MatrixNd A(1 * 2 + req.torque_limits.size() + 6, z.size()); VectorNd b(1 * 2 + req.torque_limits.size() + 6); ROS_INFO("Setting Sv constraint"); // Sv(t + t_delta) = 0 (no tangent velocity) unsigned idx = 0; A.set_sub_mat(idx, vTDeltaIdx, S); b.set_sub_vec(idx, VectorNd::zero(1)); idx += 1; ROS_INFO("Setting Tv constraint"); // Tv(t + t_delta) = 0 (no tangent velocity) A.set_sub_mat(idx, vTDeltaIdx, T); b.set_sub_vec(idx, VectorNd::zero(1)); idx += 1; ROS_INFO("Setting torque constraint"); // J_robot(transpose) * Q(transpose) * f_robot = torques // Transformed to: // J_Robot(transpose) * Q(transpose) * f_robot - I * torques = 0 MatrixNd JQ(req.torque_limits.size(), 1); MatrixNd Jt = JRobot; Jt.transpose(); // TODO: This is the incorrect Q matrix MatrixNd Qt(Q, eNoTranspose); Jt.mult(Qt, JQ); A.set_sub_mat(idx, fRobotIdx, JQ); A.set_sub_mat(idx, torqueIdx, MatrixNd::identity(req.torque_limits.size()).negate()); b.set_sub_vec(idx, VectorNd::zero(req.torque_limits.size())); idx += req.torque_limits.size(); ROS_INFO("Setting velocity constraint"); // v_(t + t_delta) = v_t + M_inv (N_t * f_n + S_t * f_s + T_t * f_t + delta_t * f_ext + Q_t * delta_t * f_robot) // Manipulated to fit constraint form // -v_t - M_inv * delta_t * f_ext = M_inv * N_t * f_n + M_inv * S_t * f_s + M_inv * T_t * f_t + M_inv * Q_t * delta_t * f_robot + -I * v_(t + t_delta) LinAlgd linAlgd; MatrixNd MInverse = M; linAlgd.invert(MInverse); MatrixNd MInverseN(MInverse.rows(), N.columns()); MInverse.mult(N, MInverseN); A.set_sub_mat(idx, fNIdx, MInverseN); MatrixNd MInverseS(MInverse.rows(), S.columns()); MInverse.mult(S, MInverseS); A.set_sub_mat(idx, fSIdx, MInverseS); MatrixNd MInverseT(MInverse.rows(), T.columns()); MInverse.mult(T, MInverseT); A.set_sub_mat(idx, fTIdx, MInverseT); MatrixNd MInverseQ(MInverse.rows(), Q.columns()); MInverse.mult(Q, MInverseQ); MInverseQ *= deltaT; A.set_sub_mat(idx, fRobotIdx, MInverseQ); A.set_sub_mat(idx, vTDeltaIdx, MatrixNd::identity(6).negate()); VectorNd MInverseFExt(6); MInverseFExt.set_zero(); MInverse.mult(fExt, MInverseFExt, deltaT); MInverseFExt.negate() -= v; b.set_sub_vec(idx, MInverseFExt); ROS_INFO_STREAM("A: " << A); ROS_INFO_STREAM("b: " << b); // Linear inequality constraints ROS_INFO("Calculating Mc and q"); MatrixNd Mc(6, z.size()); VectorNd q(6); // Nv(t) >= 0 (non-negative normal velocity) Mc.set_sub_mat(0, vTDeltaIdx, N); q.set_sub_vec(0, VectorNd::zero(6)); ROS_INFO_STREAM("Mc: " << Mc); ROS_INFO_STREAM("q: " << q); // Solution variable constraint ROS_INFO("Calculating lb and ub"); VectorNd lb(z.size()); VectorNd ub(z.size()); // Torque constraints unsigned int bound = 0; for (bound; bound < req.torque_limits.size(); ++bound) { lb[bound] = req.torque_limits[bound].minimum; ub[bound] = req.torque_limits[bound].maximum; } // f_n >= 0 lb[bound] = 0; ub[bound] = INFINITY; ++bound; // f_s (no constraints) lb[bound] = INFINITY; ub[bound] = INFINITY; ++bound; // f_t (no constraints) lb[bound] = INFINITY; ub[bound] = INFINITY; ++bound; // f_robot >= 0 lb[bound] = 0; ub[bound] = INFINITY; ++bound; // v_t (no constraints) for (bound; bound < z.size(); ++bound) { lb[bound] = INFINITY; ub[bound] = INFINITY; } ROS_INFO_STREAM("lb: " << lb); ROS_INFO_STREAM("ub: " << ub); // Call solver ROS_INFO("Calling solver"); Moby::QPOASES qp; if (!qp.qp_activeset(H, c, lb, ub, Mc, q, A, b, z)){ ROS_ERROR("QP failed to find feasible point"); return false; } ROS_INFO_STREAM("QP solved successfully: " << z); // Copy over result res.torques.resize(req.torque_limits.size()); for (unsigned int i = 0; i < z.size(); ++i) { res.torques[i] = z[i]; } return true; } }; } int main(int argc, char** argv) { ros::init(argc, argv, "balancer"); Balancer bal; ros::spin(); } <|endoftext|>
<commit_before>#include "dlib/bam_util.h" namespace BMF { namespace { struct mark_settings_t { // I might add more options later, hence the use of the bitfield. uint32_t remove_qcfail:1; uint32_t min_insert_length:8; double min_frac_unambiguous; mark_settings_t() : remove_qcfail(0), min_insert_length(0), min_frac_unambiguous(0.0) { } }; } static inline int add_multiple_tags(bam1_t *b1, bam1_t *b2, void *data) { int ret = 0; dlib::add_unclipped_mate_starts(b1, b2); dlib::add_sc_lens(b1, b2); dlib::add_fraction_aligned(b1, b2); dlib::add_qseq_len(b1, b2); dlib::add_mate_SA_tag(b1, b2); // Fails the reads if remove_qcfail is set and bitseq_qcfail returns 1 ret |= (dlib::bitset_qcfail(b1, b2) && ((mark_settings_t *)data)->remove_qcfail); if(((mark_settings_t *)data)->min_insert_length) if(b1->core.isize) ret |= std::abs(b1->core.isize) < ((mark_settings_t *)data)->min_insert_length; if(((mark_settings_t *)data)->min_frac_unambiguous) ret |= dlib::filter_n_frac(b1, b2, ((mark_settings_t *)data)->min_frac_unambiguous); return ret; } static int mark_usage() { fprintf(stderr, "Adds positional bam tags for a read and its mate for bmftools rsq and bmftools infer.\n" "Meant primarily for piping to avoid I/O. Default compression is therefore 0. Typical compression for writing to disk: 6.\n" "\tSU: Self Unclipped start.\n" "\tMU: Mate Unclipped start.\n" "\tLM: Mate length.\n" "Required for bmftools rsq using unclipped start.\n" "Required for bmftools infer.\n" "Usage: bmftools mark <opts> <input.namesrt.bam> <output.bam>\n\n" "Flags:\n-l Sets bam compression level. (Valid: 1-9). Default: 0.\n" "-q Skip read pairs which fail.\n" "-d Set bam compression level to default (6).\n" "-i Skip read pairs whose insert size is less than <INT>.\n" "-u Skip read pairs where both reads have a fraction of unambiguous base calls >= <FLOAT>\n" "Set input.namesrt.bam to \'-\' or \'stdin\' to read from stdin.\n" "Set output.bam to \'-\' or \'stdout\' or omit to stdout.\n" ); exit(EXIT_FAILURE); } int mark_main(int argc, char *argv[]) { char wmode[4]{"wb0"}; int c; mark_settings_t settings; while ((c = getopt(argc, argv, "l:i:u:dq?h")) >= 0) { switch (c) { case 'u': settings.min_frac_unambiguous = atof(optarg); break; case 'q': settings.remove_qcfail = 1; break; case 'i': settings.min_insert_length = (uint32_t)atoi(optarg); break; case 'l': wmode[2] = atoi(optarg)%10 + '0'; LOG_DEBUG("Now emitting output with compression level %c.\n", wmode[2]); break; case 'd': sprintf(wmode, "wb"); break; case '?': case 'h': mark_usage(); // Exits. No need for a break. } } char *in = (char *)"-", *out = (char *)"-"; if(optind + 2 == argc) { in = argv[optind]; out = argv[optind + 1]; } else if(optind + 1 == argc) { LOG_INFO("No outfile provided. Defaulting to stdout.\n"); in = argv[optind]; } else { LOG_INFO("No input or output bam provided! Defaulting stdin and stdout.\n"); } dlib::BamHandle inHandle(in); dlib::BamHandle outHandle(out, inHandle.header, "wb"); dlib::abstract_pair_iter(inHandle.fp, inHandle.header, outHandle.fp, &add_multiple_tags, &settings); LOG_INFO("Successfully complete bmftools mark.\n"); return EXIT_SUCCESS; } } <commit_msg>Update bmf_mark.cpp<commit_after>#include "dlib/bam_util.h" namespace BMF { namespace { struct mark_settings_t { // I might add more options later, hence the use of the bitfield. uint32_t remove_qcfail:1; uint32_t min_insert_length:8; double min_frac_unambiguous; mark_settings_t() : remove_qcfail(0), min_insert_length(0), min_frac_unambiguous(0.0) { } }; } static inline int add_multiple_tags(bam1_t *b1, bam1_t *b2, void *data) { int ret = 0; dlib::add_unclipped_mate_starts(b1, b2); dlib::add_sc_lens(b1, b2); dlib::add_qseq_len(b1, b2); //dlib::add_mate_SA_tag(b1, b2); // Fails the reads if remove_qcfail is set and bitseq_qcfail returns 1 ret |= (dlib::bitset_qcfail(b1, b2) && ((mark_settings_t *)data)->remove_qcfail); if(((mark_settings_t *)data)->min_insert_length) if(b1->core.isize) ret |= std::abs(b1->core.isize) < ((mark_settings_t *)data)->min_insert_length; if(((mark_settings_t *)data)->min_frac_unambiguous) ret |= dlib::filter_n_frac(b1, b2, ((mark_settings_t *)data)->min_frac_unambiguous); return ret; } static int mark_usage() { fprintf(stderr, "Adds positional bam tags for a read and its mate for bmftools rsq and bmftools infer.\n" "Meant primarily for piping to avoid I/O. Default compression is therefore 0. Typical compression for writing to disk: 6.\n" "\tSU: Self Unclipped start.\n" "\tMU: Mate Unclipped start.\n" "\tLM: Mate length.\n" "Required for bmftools rsq using unclipped start.\n" "Required for bmftools infer.\n" "Usage: bmftools mark <opts> <input.namesrt.bam> <output.bam>\n\n" "Flags:\n-l Sets bam compression level. (Valid: 1-9). Default: 0.\n" "-q Skip read pairs which fail.\n" "-d Set bam compression level to default (6).\n" "-i Skip read pairs whose insert size is less than <INT>.\n" "-u Skip read pairs where both reads have a fraction of unambiguous base calls >= <FLOAT>\n" "Set input.namesrt.bam to \'-\' or \'stdin\' to read from stdin.\n" "Set output.bam to \'-\' or \'stdout\' or omit to stdout.\n" ); exit(EXIT_FAILURE); } int mark_main(int argc, char *argv[]) { char wmode[4]{"wb0"}; int c; mark_settings_t settings; while ((c = getopt(argc, argv, "l:i:u:dq?h")) >= 0) { switch (c) { case 'u': settings.min_frac_unambiguous = atof(optarg); break; case 'q': settings.remove_qcfail = 1; break; case 'i': settings.min_insert_length = (uint32_t)atoi(optarg); break; case 'l': wmode[2] = atoi(optarg)%10 + '0'; LOG_DEBUG("Now emitting output with compression level %c.\n", wmode[2]); break; case 'd': sprintf(wmode, "wb"); break; case '?': case 'h': mark_usage(); // Exits. No need for a break. } } char *in = (char *)"-", *out = (char *)"-"; if(optind + 2 == argc) { in = argv[optind]; out = argv[optind + 1]; } else if(optind + 1 == argc) { LOG_INFO("No outfile provided. Defaulting to stdout.\n"); in = argv[optind]; } else { LOG_INFO("No input or output bam provided! Defaulting stdin and stdout.\n"); } dlib::BamHandle inHandle(in); dlib::BamHandle outHandle(out, inHandle.header, "wb"); dlib::abstract_pair_iter(inHandle.fp, inHandle.header, outHandle.fp, &add_multiple_tags, &settings); LOG_INFO("Successfully complete bmftools mark.\n"); return EXIT_SUCCESS; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2010, Joshua Lackey * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "usrp_source.h" #include "circular_buffer.h" #include "fcch_detector.h" #include "arfcn_freq.h" #include "util.h" extern int g_verbosity; static const float ERROR_DETECT_OFFSET_MAX = 40e3; #ifdef _WIN32 #define BUFSIZ 1024 #endif static double vectornorm2(const complex *v, const unsigned int len) { unsigned int i; double e = 0.0; for(i = 0; i < len; i++) e += norm(v[i]); return e; } int c0_detect(usrp_source *u, int bi) { #define GSM_RATE (1625000.0 / 6.0) #define NOTFOUND_MAX 10 int i, chan_count; unsigned int overruns, b_len, frames_len, found_count, notfound_count, r; float offset, spower[BUFSIZ]; double freq, sps, n, power[BUFSIZ], sum = 0, a; complex *b; circular_buffer *ub; fcch_detector *l = new fcch_detector(u->sample_rate()); if(bi == BI_NOT_DEFINED) { fprintf(stderr, "error: c0_detect: band not defined\n"); return -1; } sps = u->sample_rate() / GSM_RATE; frames_len = (unsigned int)ceil((12 * 8 * 156.25 + 156.25) * sps); ub = u->get_buffer(); // first, we calculate the power in each channel if(g_verbosity > 2) { fprintf(stderr, "calculate power in each channel:\n"); } u->start(); u->flush(); for(i = first_chan(bi); i >= 0; i = next_chan(i, bi)) { freq = arfcn_to_freq(i, &bi); if(!u->tune(freq)) { fprintf(stderr, "error: usrp_source::tune\n"); return -1; } do { u->flush(); if(u->fill(frames_len, &overruns)) { fprintf(stderr, "error: usrp_source::fill\n"); return -1; } } while(overruns); b = (complex *)ub->peek(&b_len); n = sqrt(vectornorm2(b, frames_len)); power[i] = n; if(g_verbosity > 2) { fprintf(stderr, "\tchan %d (%.1fMHz):\tpower: %lf\n", i, freq / 1e6, n); } } /* * We want to use the average to determine which channels have * power, and hence a possibility of being channel 0 on a BTS. * However, some channels in the band can be extremely noisy. (E.g., * CDMA traffic in GSM-850.) Hence we won't consider the noisiest * channels when we construct the average. */ chan_count = 0; for(i = first_chan(bi); i >= 0; i = next_chan(i, bi)) { spower[chan_count++] = power[i]; } sort(spower, chan_count); // average the lowest %60 a = avg(spower, chan_count - 4 * chan_count / 10, 0); if(g_verbosity > 0) { fprintf(stderr, "channel detect threshold: %lf\n", a); } // then we look for fcch bursts printf("%s:\n", bi_to_str(bi)); found_count = 0; notfound_count = 0; sum = 0; i = first_chan(bi); do { if(power[i] <= a) { i = next_chan(i, bi); continue; } freq = arfcn_to_freq(i, &bi); if(!u->tune(freq)) { fprintf(stderr, "error: usrp_source::tune\n"); return -1; } do { u->flush(); if(u->fill(frames_len, &overruns)) { fprintf(stderr, "error: usrp_source::fill\n"); return -1; } } while(overruns); b = (complex *)ub->peek(&b_len); r = l->scan(b, b_len, &offset, 0); if(r && (fabsf(offset - GSM_RATE / 4) < ERROR_DETECT_OFFSET_MAX)) { // found printf("\tchan: %d (%.1fMHz ", i, freq / 1e6); display_freq(offset - GSM_RATE / 4); printf(")\tpower: %6.2lf\n", power[i]); notfound_count = 0; i = next_chan(i, bi); } else { // not found notfound_count += 1; if(notfound_count >= NOTFOUND_MAX) { notfound_count = 0; i = next_chan(i, bi); } } } while(i >= 0); return 0; } <commit_msg>more human friendly output formating<commit_after>/* * Copyright (c) 2010, Joshua Lackey * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "usrp_source.h" #include "circular_buffer.h" #include "fcch_detector.h" #include "arfcn_freq.h" #include "util.h" extern int g_verbosity; static const float ERROR_DETECT_OFFSET_MAX = 40e3; #ifdef _WIN32 #define BUFSIZ 1024 #endif static double vectornorm2(const complex *v, const unsigned int len) { unsigned int i; double e = 0.0; for(i = 0; i < len; i++) e += norm(v[i]); return e; } int c0_detect(usrp_source *u, int bi) { #define GSM_RATE (1625000.0 / 6.0) #define NOTFOUND_MAX 10 int i, chan_count; unsigned int overruns, b_len, frames_len, found_count, notfound_count, r; float offset, spower[BUFSIZ]; double freq, sps, n, power[BUFSIZ], sum = 0, a; complex *b; circular_buffer *ub; fcch_detector *l = new fcch_detector(u->sample_rate()); if(bi == BI_NOT_DEFINED) { fprintf(stderr, "error: c0_detect: band not defined\n"); return -1; } sps = u->sample_rate() / GSM_RATE; frames_len = (unsigned int)ceil((12 * 8 * 156.25 + 156.25) * sps); ub = u->get_buffer(); // first, we calculate the power in each channel if(g_verbosity > 2) { fprintf(stderr, "calculate power in each channel:\n"); } u->start(); u->flush(); for(i = first_chan(bi); i >= 0; i = next_chan(i, bi)) { freq = arfcn_to_freq(i, &bi); if(!u->tune(freq)) { fprintf(stderr, "error: usrp_source::tune\n"); return -1; } do { u->flush(); if(u->fill(frames_len, &overruns)) { fprintf(stderr, "error: usrp_source::fill\n"); return -1; } } while(overruns); b = (complex *)ub->peek(&b_len); n = sqrt(vectornorm2(b, frames_len)); power[i] = n; if(g_verbosity > 2) { fprintf(stderr, "\tchan %d (%.1fMHz):\tpower: %lf\n", i, freq / 1e6, n); } } /* * We want to use the average to determine which channels have * power, and hence a possibility of being channel 0 on a BTS. * However, some channels in the band can be extremely noisy. (E.g., * CDMA traffic in GSM-850.) Hence we won't consider the noisiest * channels when we construct the average. */ chan_count = 0; for(i = first_chan(bi); i >= 0; i = next_chan(i, bi)) { spower[chan_count++] = power[i]; } sort(spower, chan_count); // average the lowest %60 a = avg(spower, chan_count - 4 * chan_count / 10, 0); if(g_verbosity > 0) { fprintf(stderr, "channel detect threshold: %lf\n", a); } // then we look for fcch bursts printf("%s:\n", bi_to_str(bi)); found_count = 0; notfound_count = 0; sum = 0; i = first_chan(bi); do { if(power[i] <= a) { i = next_chan(i, bi); continue; } freq = arfcn_to_freq(i, &bi); if(!u->tune(freq)) { fprintf(stderr, "error: usrp_source::tune\n"); return -1; } do { u->flush(); if(u->fill(frames_len, &overruns)) { fprintf(stderr, "error: usrp_source::fill\n"); return -1; } } while(overruns); b = (complex *)ub->peek(&b_len); r = l->scan(b, b_len, &offset, 0); if(r && (fabsf(offset - GSM_RATE / 4) < ERROR_DETECT_OFFSET_MAX)) { // found printf("\tchan: %4d (%.1fMHz ", i, freq / 1e6); display_freq(offset - GSM_RATE / 4); printf(")\tpower: %10.2f\n", power[i]); notfound_count = 0; i = next_chan(i, bi); } else { // not found notfound_count += 1; if(notfound_count >= NOTFOUND_MAX) { notfound_count = 0; i = next_chan(i, bi); } } } while(i >= 0); return 0; } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2021 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // mapnik #include <mapnik/cairo_io.hpp> #include <mapnik/image_util.hpp> #include <mapnik/map.hpp> #ifdef HAVE_CAIRO #include <mapnik/cairo/cairo_renderer.hpp> #include <cairo.h> #ifdef CAIRO_HAS_PDF_SURFACE #include <cairo-pdf.h> #endif #ifdef CAIRO_HAS_PS_SURFACE #include <cairo-ps.h> #endif #ifdef CAIRO_HAS_SVG_SURFACE #include <cairo-svg.h> #endif #endif // stl #include <string> #include <iostream> #include <fstream> #include <sstream> namespace mapnik { #if defined(HAVE_CAIRO) void save_to_cairo_file(mapnik::Map const& map, std::string const& filename, double scale_factor, double scale_denominator) { boost::optional<std::string> type = type_from_filename(filename); if (type) { save_to_cairo_file(map,filename,*type,scale_factor,scale_denominator); } else throw image_writer_exception("Could not write file to " + filename ); } void save_to_cairo_file(mapnik::Map const& map, std::string const& filename, std::string const& type, double scale_factor, double scale_denominator) { std::ofstream file (filename.c_str(), std::ios::out|std::ios::trunc|std::ios::binary); if (file) { cairo_surface_ptr surface; unsigned width = map.width(); unsigned height = map.height(); if (type == "pdf") { #ifdef CAIRO_HAS_PDF_SURFACE surface = cairo_surface_ptr(cairo_pdf_surface_create(filename.c_str(),width,height),cairo_surface_closer()); #else throw image_writer_exception("PDFSurface not supported in the cairo backend"); #endif } #ifdef CAIRO_HAS_SVG_SURFACE else if (type == "svg") { surface = cairo_surface_ptr(cairo_svg_surface_create(filename.c_str(),width,height),cairo_surface_closer()); cairo_svg_surface_restrict_to_version(surface.get(), CAIRO_SVG_VERSION_1_2); } #endif #ifdef CAIRO_HAS_PS_SURFACE else if (type == "ps") { surface = cairo_surface_ptr(cairo_ps_surface_create(filename.c_str(),width,height),cairo_surface_closer()); } #endif #ifdef CAIRO_HAS_IMAGE_SURFACE else if (type == "ARGB32") { surface = cairo_surface_ptr(cairo_image_surface_create(CAIRO_FORMAT_ARGB32,width,height),cairo_surface_closer()); } else if (type == "RGB24") { surface = cairo_surface_ptr(cairo_image_surface_create(CAIRO_FORMAT_RGB24,width,height),cairo_surface_closer()); } #endif else { throw image_writer_exception("unknown file type: " + type); } //cairo_t * ctx = cairo_create(surface); // TODO - expose as user option /* if (type == "ARGB32" || type == "RGB24") { context->set_antialias(Cairo::ANTIALIAS_NONE); } */ mapnik::cairo_renderer<cairo_ptr> ren(map, create_context(surface), scale_factor); ren.apply(scale_denominator); if (type == "ARGB32" || type == "RGB24") { cairo_surface_write_to_png(&*surface, filename.c_str()); } cairo_surface_finish(&*surface); } } #endif } // end ns <commit_msg>hopefully fix unstatisfied proj_transform_cache<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2021 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // mapnik #include <mapnik/cairo_io.hpp> #include <mapnik/image_util.hpp> #include <mapnik/map.hpp> #include <mapnik/proj_transform_cache.hpp> #ifdef HAVE_CAIRO #include <mapnik/cairo/cairo_renderer.hpp> #include <cairo.h> #ifdef CAIRO_HAS_PDF_SURFACE #include <cairo-pdf.h> #endif #ifdef CAIRO_HAS_PS_SURFACE #include <cairo-ps.h> #endif #ifdef CAIRO_HAS_SVG_SURFACE #include <cairo-svg.h> #endif #endif // stl #include <string> #include <iostream> #include <fstream> #include <sstream> namespace mapnik { #if defined(HAVE_CAIRO) void save_to_cairo_file(mapnik::Map const& map, std::string const& filename, double scale_factor, double scale_denominator) { boost::optional<std::string> type = type_from_filename(filename); if (type) { save_to_cairo_file(map,filename,*type,scale_factor,scale_denominator); } else throw image_writer_exception("Could not write file to " + filename ); } void save_to_cairo_file(mapnik::Map const& map, std::string const& filename, std::string const& type, double scale_factor, double scale_denominator) { std::ofstream file (filename.c_str(), std::ios::out|std::ios::trunc|std::ios::binary); if (file) { cairo_surface_ptr surface; unsigned width = map.width(); unsigned height = map.height(); if (type == "pdf") { #ifdef CAIRO_HAS_PDF_SURFACE surface = cairo_surface_ptr(cairo_pdf_surface_create(filename.c_str(),width,height),cairo_surface_closer()); #else throw image_writer_exception("PDFSurface not supported in the cairo backend"); #endif } #ifdef CAIRO_HAS_SVG_SURFACE else if (type == "svg") { surface = cairo_surface_ptr(cairo_svg_surface_create(filename.c_str(),width,height),cairo_surface_closer()); cairo_svg_surface_restrict_to_version(surface.get(), CAIRO_SVG_VERSION_1_2); } #endif #ifdef CAIRO_HAS_PS_SURFACE else if (type == "ps") { surface = cairo_surface_ptr(cairo_ps_surface_create(filename.c_str(),width,height),cairo_surface_closer()); } #endif #ifdef CAIRO_HAS_IMAGE_SURFACE else if (type == "ARGB32") { surface = cairo_surface_ptr(cairo_image_surface_create(CAIRO_FORMAT_ARGB32,width,height),cairo_surface_closer()); } else if (type == "RGB24") { surface = cairo_surface_ptr(cairo_image_surface_create(CAIRO_FORMAT_RGB24,width,height),cairo_surface_closer()); } #endif else { throw image_writer_exception("unknown file type: " + type); } //cairo_t * ctx = cairo_create(surface); // TODO - expose as user option /* if (type == "ARGB32" || type == "RGB24") { context->set_antialias(Cairo::ANTIALIAS_NONE); } */ mapnik::cairo_renderer<cairo_ptr> ren(map, create_context(surface), scale_factor); ren.apply(scale_denominator); if (type == "ARGB32" || type == "RGB24") { cairo_surface_write_to_png(&*surface, filename.c_str()); } cairo_surface_finish(&*surface); } } #endif } // end ns <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2013 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "clientversion.h" #include "rpcserver.h" #include "init.h" #include "main.h" #include "noui.h" #include "scheduler.h" #include "util.h" #include <boost/algorithm/string/predicate.hpp> #include <boost/filesystem.hpp> #include <boost/thread.hpp> /* Introduction text for doxygen: */ /*! \mainpage Developer documentation * * \section intro_sec Introduction * * This is the developer documentation of the reference client for an experimental new digital currency called Bitcoin (https://www.bitcoin.org/), * which enables instant payments to anyone, anywhere in the world. Bitcoin uses peer-to-peer technology to operate * with no central authority: managing transactions and issuing money are carried out collectively by the network. * * The software is a community-driven open source project, released under the MIT license. * * \section Navigation * Use the buttons <code>Namespaces</code>, <code>Classes</code> or <code>Files</code> at the top of the page to start navigating the code. */ static bool fDaemon; void WaitForShutdown(boost::thread_group* threadGroup) { bool fShutdown = ShutdownRequested(); // Tell the main threads to shutdown. while (!fShutdown) { MilliSleep(200); fShutdown = ShutdownRequested(); } if (threadGroup) { threadGroup->interrupt_all(); threadGroup->join_all(); } } ////////////////////////////////////////////////////////////////////////////// // // Start // bool AppInit(int argc, char* argv[]) { boost::thread_group threadGroup; CScheduler scheduler; bool fRet = false; // // Parameters // // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main() ParseParameters(argc, argv); // Process help and version before taking care about datadir if (mapArgs.count("-?") || mapArgs.count("-help") || mapArgs.count("-version")) { std::string strUsage = _("Bitcoin Core Daemon") + " " + _("version") + " " + FormatFullVersion() + "\n"; if (mapArgs.count("-version")) { strUsage += LicenseInfo(); } else { strUsage += "\n" + _("Usage:") + "\n" + " bitcoind [options] " + _("Start Bitcoin Core Daemon") + "\n"; strUsage += "\n" + HelpMessage(HMM_BITCOIND); } fprintf(stdout, "%s", strUsage.c_str()); return false; } try { if (!boost::filesystem::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str()); return false; } try { ReadConfigFile(mapArgs, mapMultiArgs); } catch (const std::exception& e) { fprintf(stderr,"Error reading configuration file: %s\n", e.what()); return false; } // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) if (!SelectParamsFromCommandLine()) { fprintf(stderr, "Error: Invalid combination of -regtest and -testnet.\n"); return false; } // Command-line RPC bool fCommandLine = false; for (int i = 1; i < argc; i++) if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "bitcoin:")) fCommandLine = true; if (fCommandLine) { fprintf(stderr, "Error: There is no RPC client functionality in bitcoind anymore. Use the bitcoin-cli utility instead.\n"); exit(1); } #ifndef WIN32 fDaemon = GetBoolArg("-daemon", false); if (fDaemon) { fprintf(stdout, "Bitcoin server starting\n"); // Daemonize pid_t pid = fork(); if (pid < 0) { fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno); return false; } if (pid > 0) // Parent process, pid is child process id { return true; } // Child process falls through to rest of initialization pid_t sid = setsid(); if (sid < 0) fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno); } #endif SoftSetBoolArg("-server", true); fRet = AppInit2(threadGroup, scheduler); } catch (const std::exception& e) { PrintExceptionContinue(&e, "AppInit()"); } catch (...) { PrintExceptionContinue(NULL, "AppInit()"); } if (!fRet) { threadGroup.interrupt_all(); // threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of // the startup-failure cases to make sure they don't result in a hang due to some // thread-blocking-waiting-for-another-thread-during-startup case } else { WaitForShutdown(&threadGroup); } Shutdown(); return fRet; } int main(int argc, char* argv[]) { SetupEnvironment(); // Connect bitcoind signal handlers noui_connect(); return (AppInit(argc, argv) ? 0 : 1); } <commit_msg>change 'Bitcoin server starting' to 'LBRYcrd server starting'<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2013 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "clientversion.h" #include "rpcserver.h" #include "init.h" #include "main.h" #include "noui.h" #include "scheduler.h" #include "util.h" #include <boost/algorithm/string/predicate.hpp> #include <boost/filesystem.hpp> #include <boost/thread.hpp> /* Introduction text for doxygen: */ /*! \mainpage Developer documentation * * \section intro_sec Introduction * * This is the developer documentation of the reference client for an experimental new digital currency called Bitcoin (https://www.bitcoin.org/), * which enables instant payments to anyone, anywhere in the world. Bitcoin uses peer-to-peer technology to operate * with no central authority: managing transactions and issuing money are carried out collectively by the network. * * The software is a community-driven open source project, released under the MIT license. * * \section Navigation * Use the buttons <code>Namespaces</code>, <code>Classes</code> or <code>Files</code> at the top of the page to start navigating the code. */ static bool fDaemon; void WaitForShutdown(boost::thread_group* threadGroup) { bool fShutdown = ShutdownRequested(); // Tell the main threads to shutdown. while (!fShutdown) { MilliSleep(200); fShutdown = ShutdownRequested(); } if (threadGroup) { threadGroup->interrupt_all(); threadGroup->join_all(); } } ////////////////////////////////////////////////////////////////////////////// // // Start // bool AppInit(int argc, char* argv[]) { boost::thread_group threadGroup; CScheduler scheduler; bool fRet = false; // // Parameters // // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main() ParseParameters(argc, argv); // Process help and version before taking care about datadir if (mapArgs.count("-?") || mapArgs.count("-help") || mapArgs.count("-version")) { std::string strUsage = _("Bitcoin Core Daemon") + " " + _("version") + " " + FormatFullVersion() + "\n"; if (mapArgs.count("-version")) { strUsage += LicenseInfo(); } else { strUsage += "\n" + _("Usage:") + "\n" + " bitcoind [options] " + _("Start Bitcoin Core Daemon") + "\n"; strUsage += "\n" + HelpMessage(HMM_BITCOIND); } fprintf(stdout, "%s", strUsage.c_str()); return false; } try { if (!boost::filesystem::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str()); return false; } try { ReadConfigFile(mapArgs, mapMultiArgs); } catch (const std::exception& e) { fprintf(stderr,"Error reading configuration file: %s\n", e.what()); return false; } // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) if (!SelectParamsFromCommandLine()) { fprintf(stderr, "Error: Invalid combination of -regtest and -testnet.\n"); return false; } // Command-line RPC bool fCommandLine = false; for (int i = 1; i < argc; i++) if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "bitcoin:")) fCommandLine = true; if (fCommandLine) { fprintf(stderr, "Error: There is no RPC client functionality in bitcoind anymore. Use the bitcoin-cli utility instead.\n"); exit(1); } #ifndef WIN32 fDaemon = GetBoolArg("-daemon", false); if (fDaemon) { fprintf(stdout, "LBRYcrd server starting\n"); // Daemonize pid_t pid = fork(); if (pid < 0) { fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno); return false; } if (pid > 0) // Parent process, pid is child process id { return true; } // Child process falls through to rest of initialization pid_t sid = setsid(); if (sid < 0) fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno); } #endif SoftSetBoolArg("-server", true); fRet = AppInit2(threadGroup, scheduler); } catch (const std::exception& e) { PrintExceptionContinue(&e, "AppInit()"); } catch (...) { PrintExceptionContinue(NULL, "AppInit()"); } if (!fRet) { threadGroup.interrupt_all(); // threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of // the startup-failure cases to make sure they don't result in a hang due to some // thread-blocking-waiting-for-another-thread-during-startup case } else { WaitForShutdown(&threadGroup); } Shutdown(); return fRet; } int main(int argc, char* argv[]) { SetupEnvironment(); // Connect bitcoind signal handlers noui_connect(); return (AppInit(argc, argv) ? 0 : 1); } <|endoftext|>
<commit_before>/**************************************************************************** * Copyright (C) 2020 Savoir-faire Linux Inc. * * Author: Sébastien Blin <[email protected]> * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ #include "api/chatview.h" namespace lrc { namespace api { namespace chatview { QVariantMap getTranslatedStrings(bool qwebview) { return { {"Hide chat view", QObject::tr("Hide chat view")}, {"Place video call", QObject::tr("Place video call")}, {"Place audio call", QObject::tr("Place audio call")}, {"Add to conversations", QObject::tr("Add to conversations")}, {"Unban contact", QObject::tr("Unban contact")}, {"Send", QObject::tr("Send")}, {"Options", QObject::tr("Options")}, {"Jump to latest", QObject::tr("Jump to latest")}, {"Send file", QObject::tr("Send file")}, {"Leave video message", QObject::tr("Leave video message")}, {"Leave audio message", QObject::tr("Leave audio message")}, {"Accept", QObject::tr("Accept")}, {"Refuse", QObject::tr("Refuse")}, {"Block", QObject::tr("Block")}, {"Write to {0}", QObject::tr("Write to {0}")}, {"Note: an interaction will create a new contact.", QObject::tr("Note: an interaction will create a new contact.")}, {"is not in your contacts", QObject::tr("is not in your contacts")}, {"Note: you can automatically accept this invitation by sending a message.", QObject::tr("Note: you can automatically accept this invitation by sending a message.")}, {"%d days ago", qwebview ? QObject::tr("{0} days ago") : QObject::tr("%d days ago")}, {"%d hours ago", qwebview ? QObject::tr("{0} hours ago") : QObject::tr("%d hours ago")}, {"%d minutes ago", qwebview ? QObject::tr("{0} minutes ago") : QObject::tr("%d minutes ago")}, {"one day ago", QObject::tr("one day ago")}, {"one hour ago", QObject::tr("one hour ago")}, {"just now", QObject::tr("just now")}, {"Failure", QObject::tr("Failure")}, {"Accept", QObject::tr("Accept")}, {"Refuse", QObject::tr("Refuse")}, {"Delete", QObject::tr("Delete")}, {"Retry", QObject::tr("Retry")}, {"unjoinable peer", QObject::tr("Unjoinable peer")}, {"connecting", QObject::tr("Connecting")}, {"accepted", QObject::tr("Accepted")}, {"canceled", QObject::tr("Canceled")}, {"ongoing", QObject::tr("Ongoing")}, {"awaiting peer", QObject::tr("Awaiting peer")}, {"awaiting host", QObject::tr("Awaiting host")}, {"awaiting peer timeout", QObject::tr("Awaiting peer timeout")}, {"finished", QObject::tr("Finished")}, }; } } // namespace chatview } // namespace api } // namespace lrc <commit_msg>chatview: improve strings<commit_after>/**************************************************************************** * Copyright (C) 2020 Savoir-faire Linux Inc. * * Author: Sébastien Blin <[email protected]> * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ #include "api/chatview.h" namespace lrc { namespace api { namespace chatview { QVariantMap getTranslatedStrings(bool qwebview) { return { {"Hide chat view", QObject::tr("Hide chat view")}, {"Place video call", QObject::tr("Place video call")}, {"Place audio call", QObject::tr("Place audio call")}, {"Add to conversations", QObject::tr("Add to conversations")}, {"Unban contact", QObject::tr("Unban contact")}, {"Send", QObject::tr("Send")}, {"Options", QObject::tr("Options")}, {"Jump to latest", QObject::tr("Jump to latest")}, {"Send file", QObject::tr("Send file")}, {"Leave video message", QObject::tr("Leave video message")}, {"Leave audio message", QObject::tr("Leave audio message")}, {"Block", QObject::tr("Block")}, {"Write to {0}", QObject::tr("Write to {0}")}, {"Note: an interaction will create a new contact.", QObject::tr("Note: an interaction will create a new contact.")}, {"is not in your contacts", QObject::tr("is not in your contacts")}, {"Note: you can automatically accept this invitation by sending a message.", QObject::tr("Note: you can automatically accept this invitation by sending a message.")}, {"%d days ago", qwebview ? QObject::tr("{0} days ago") : QObject::tr("%d days ago")}, {"%d hours ago", qwebview ? QObject::tr("{0} hours ago") : QObject::tr("%d hours ago")}, {"%d minutes ago", qwebview ? QObject::tr("{0} minutes ago") : QObject::tr("%d minutes ago")}, {"one day ago", QObject::tr("one day ago")}, {"one hour ago", QObject::tr("one hour ago")}, {"just now", QObject::tr("just now")}, {"Failure", QObject::tr("Failure")}, {"Accept", QObject::tr("Confirm")}, {"Refuse", QObject::tr("Deny")}, {"Delete", QObject::tr("Delete")}, {"Retry", QObject::tr("Retry")}, {"unjoinable peer", QObject::tr("Unable to make contact")}, {"connecting", QObject::tr("Connecting")}, {"accepted", QObject::tr("Accepted")}, {"canceled", QObject::tr("Canceled")}, {"ongoing", QObject::tr("Ongoing")}, {"awaiting peer", QObject::tr("Wating for contact")}, {"awaiting host", QObject::tr("Incoming transfer")}, {"awaiting peer timeout", QObject::tr("Timed out waiting for contact")}, {"finished", QObject::tr("Finished")}, }; } } // namespace chatview } // namespace api } // namespace lrc <|endoftext|>
<commit_before>/* * FatFind * A Diamond application for adipocyte image exploration * Version 1 * * Copyright (c) 2006 Carnegie Mellon University * All Rights Reserved. * * This software is distributed under the terms of the Eclipse Public * License, Version 1.0 which can be found in the file named LICENSE. * ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS SOFTWARE CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT */ #include <cstring> #include <stdint.h> #include "ltiRGBPixel.h" #include "ltiScaling.h" #include "ltiDraw.h" // drawing tool #include "ltiALLFunctor.h" // image loader #include "ltiCannyEdges.h" // edge detector #include "ltiFastEllipseExtraction.h" // ellipse detector #include "ltiGaussianPyramid.h" #include "ltiSplitImageToHSV.h" #include "circles4.h" #include "util.h" #include <sys/time.h> #include <time.h> // helper functions for glist static gint circle_radius_compare(gconstpointer a, gconstpointer b) { const circle_type *c1 = (circle_type *) a; const circle_type *c2 = (circle_type *) b; // assume a and b are positive double c1_radius = quadratic_mean_radius(c1->a, c1->b); double c2_radius = quadratic_mean_radius(c2->a, c2->b); if (c1_radius < c2_radius) { return 1; } else if (c2_radius < c1_radius) { return -1; } else { return 0; } } static void do_canny(lti::gaussianPyramid<lti::image> &imgPyramid, std::vector<lti::channel8*> &edges, double minSharpness) { uint64_t start_time_in_ms; uint64_t end_time_in_ms; struct timeval tv; gettimeofday(&tv, NULL); start_time_in_ms = tv.tv_sec * 1000 + tv.tv_usec / 1000; // params lti::cannyEdges::parameters cannyParam; if (minSharpness == 0) { cannyParam.thresholdMax = 0.04; } else { cannyParam.thresholdMax = 0.10 + 0.90 * ((minSharpness - 1) / 4.0); } cannyParam.thresholdMin = 0.04; cannyParam.kernelSize = 7; // run lti::cannyEdges canny(cannyParam); g_assert(edges.size() == 0); for (int i = 0; i < imgPyramid.size(); i++) { fprintf(stderr, "canny[%d]: %dx%d\n", i, imgPyramid[i].columns(), imgPyramid[i].rows()); lti::channel8 *c8 = new lti::channel8; canny.apply(imgPyramid[i], *c8); edges.push_back(c8); } gettimeofday(&tv, NULL); end_time_in_ms = tv.tv_sec * 1000 + tv.tv_usec / 1000; fprintf(stderr, "canny done in %lld ms\n", end_time_in_ms - start_time_in_ms); } static GList *do_fee(std::vector<lti::channel8*> &edges, circles_state_t *ct) { GList *result = NULL; uint64_t start_time_in_ms; uint64_t end_time_in_ms; struct timeval tv; gettimeofday(&tv, NULL); start_time_in_ms = tv.tv_sec * 1000 + tv.tv_usec / 1000; // create FEE functor lti::fastEllipseExtraction::parameters feeParam; feeParam.maxArcGap = 120; feeParam.minLineLen = 3; for (unsigned int i = 0; i < edges.size(); i++) { double pyrScale = pow(2, i); lti::fastEllipseExtraction fee(feeParam); // extract some ellipses fprintf(stderr, "extracting from pyramid %d\n", i); fee.apply(*edges[i]); // build list std::vector<lti::fastEllipseExtraction::ellipseEntry> &ellipses = fee.getEllipseList(); for(unsigned int j=0; j<ellipses.size(); j++) { float a = ellipses[j].a * pyrScale; float b = ellipses[j].b * pyrScale; float r = quadratic_mean_radius(a, b); gboolean in_result = TRUE; // determine if it should go in by radius if (!(ct->minRadius < 0 || r >= ct->minRadius)) { in_result = FALSE; } else if (!(ct->maxRadius < 0 || r <= ct->maxRadius)) { in_result = FALSE; } // compute eccentricity float e = compute_eccentricity(a, b); // if over 0.9, drop completely if (e > 0.9) { continue; } // otherwise, maybe mark if (e > ct->maxEccentricity) { in_result = FALSE; } // all set circle_type *c = g_slice_new(circle_type); c->x = ellipses[j].x * pyrScale; c->y = ellipses[j].y * pyrScale; c->a = ellipses[j].a * pyrScale; c->b = ellipses[j].b * pyrScale; c->t = ellipses[j].t; c->in_result = in_result; result = g_list_prepend(result, c); // print ellipse data fprintf(stderr, " ellipse[%i]: center=(%.0f,%.0f) semiaxis=(%.0f,%.0f) " "angle=%.1f coverage=%.1f%% \n", j, c->x, c->y, c->a, c->b, c->t*180/M_PI, ellipses[j].coverage*100); } } gettimeofday(&tv, NULL); end_time_in_ms = tv.tv_sec * 1000 + tv.tv_usec / 1000; fprintf(stderr, "fee done in %lld ms\n", end_time_in_ms - start_time_in_ms); return result; } static circles_state_t staticState = {-1, -1, 0.4, 1}; GList *circlesFromImage2(circles_state_t *ct, const int width, const int height, const int stride, const int bytesPerPixel, const void *data) { uint64_t start_time_in_ms; uint64_t end_time_in_ms; struct timeval tv; gettimeofday(&tv, NULL); start_time_in_ms = tv.tv_sec * 1000 + tv.tv_usec / 1000; // load image g_assert(bytesPerPixel >= 3); lti::image img(false, height, width); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { guchar *d = ((guchar *) data) + (x * bytesPerPixel + y * stride); lti::rgbPixel p(d[0], d[1], d[2]); img[y][x] = p; } } // make pyramid int levels = (int)log2(MIN(img.rows(), img.columns())); lti::gaussianPyramid<lti::image> imgPyramid(levels); imgPyramid.generate(img); gettimeofday(&tv, NULL); end_time_in_ms = tv.tv_sec * 1000 + tv.tv_usec / 1000; fprintf(stderr, "load/pyramid done in %lld ms\n", end_time_in_ms - start_time_in_ms); // make vector std::vector<lti::channel8*> edges; // run do_canny(imgPyramid, edges, ct->minSharpness); GList *result = do_fee(edges, ct); // clear vector for (unsigned int i = 0; i < edges.size(); i++) { delete edges[i]; edges[i] = NULL; } // overlap suppression fprintf(stderr, "overlap suppression "); gettimeofday(&tv, NULL); start_time_in_ms = tv.tv_sec * 1000 + tv.tv_usec / 1000; result = g_list_sort(result, circle_radius_compare); // sort GList *iter; for (iter = result; iter != NULL; iter = g_list_next(iter)) { // find other centers within this circle (assume no eccentricity) circle_type *c1 = (circle_type *) iter->data; double c1_radius = quadratic_mean_radius(c1->a, c1->b); GList *iter2; // don't bother if large eccentricity double c1_e = compute_eccentricity(c1->a, c1->b); if (c1_e > 0.4) { continue; } iter2 = g_list_next(iter); while (iter2 != NULL) { circle_type *c2 = (circle_type *) iter2->data; double c2_radius = quadratic_mean_radius(c2->a, c2->b); // is c2 within c1? double xd = c2->x - c1->x; double yd = c2->y - c1->y; double dist = sqrt((xd * xd) + (yd * yd)); // maybe delete? GList *next = g_list_next(iter2); // fprintf(stderr, " dist: %g, c1_radius: %g, c2_radius: %g\n", // dist, c1_radius, c2_radius); // XXX fudge if ((dist + c2_radius) < (c1_radius + 100)) { fprintf(stderr, "x"); g_slice_free(circle_type, c2); result = g_list_delete_link(result, iter2); } iter2 = next; } fprintf(stderr, "."); } fprintf(stderr, "\n"); gettimeofday(&tv, NULL); end_time_in_ms = tv.tv_sec * 1000 + tv.tv_usec / 1000; fprintf(stderr, "overlap suppression done in %lld ms\n", end_time_in_ms - start_time_in_ms); return result; } // called from GUI GList *circlesFromImage(const int width, const int height, const int stride, const int bytesPerPixel, const void *data, double minSharpness) { circles_state_t cs = staticState; cs.minSharpness = minSharpness; return circlesFromImage2(&cs, width, height, stride, bytesPerPixel, data); } <commit_msg>Fix printf formatting for uint64_t types<commit_after>/* * FatFind * A Diamond application for adipocyte image exploration * Version 1 * * Copyright (c) 2006 Carnegie Mellon University * All Rights Reserved. * * This software is distributed under the terms of the Eclipse Public * License, Version 1.0 which can be found in the file named LICENSE. * ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS SOFTWARE CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT */ #include <cstring> #include <stdint.h> #include <inttypes.h> #include "ltiRGBPixel.h" #include "ltiScaling.h" #include "ltiDraw.h" // drawing tool #include "ltiALLFunctor.h" // image loader #include "ltiCannyEdges.h" // edge detector #include "ltiFastEllipseExtraction.h" // ellipse detector #include "ltiGaussianPyramid.h" #include "ltiSplitImageToHSV.h" #include "circles4.h" #include "util.h" #include <sys/time.h> #include <time.h> // helper functions for glist static gint circle_radius_compare(gconstpointer a, gconstpointer b) { const circle_type *c1 = (circle_type *) a; const circle_type *c2 = (circle_type *) b; // assume a and b are positive double c1_radius = quadratic_mean_radius(c1->a, c1->b); double c2_radius = quadratic_mean_radius(c2->a, c2->b); if (c1_radius < c2_radius) { return 1; } else if (c2_radius < c1_radius) { return -1; } else { return 0; } } static void do_canny(lti::gaussianPyramid<lti::image> &imgPyramid, std::vector<lti::channel8*> &edges, double minSharpness) { uint64_t start_time_in_ms; uint64_t end_time_in_ms; struct timeval tv; gettimeofday(&tv, NULL); start_time_in_ms = tv.tv_sec * 1000 + tv.tv_usec / 1000; // params lti::cannyEdges::parameters cannyParam; if (minSharpness == 0) { cannyParam.thresholdMax = 0.04; } else { cannyParam.thresholdMax = 0.10 + 0.90 * ((minSharpness - 1) / 4.0); } cannyParam.thresholdMin = 0.04; cannyParam.kernelSize = 7; // run lti::cannyEdges canny(cannyParam); g_assert(edges.size() == 0); for (int i = 0; i < imgPyramid.size(); i++) { fprintf(stderr, "canny[%d]: %dx%d\n", i, imgPyramid[i].columns(), imgPyramid[i].rows()); lti::channel8 *c8 = new lti::channel8; canny.apply(imgPyramid[i], *c8); edges.push_back(c8); } gettimeofday(&tv, NULL); end_time_in_ms = tv.tv_sec * 1000 + tv.tv_usec / 1000; fprintf(stderr, "canny done in %" PRIu64 " ms\n", end_time_in_ms - start_time_in_ms); } static GList *do_fee(std::vector<lti::channel8*> &edges, circles_state_t *ct) { GList *result = NULL; uint64_t start_time_in_ms; uint64_t end_time_in_ms; struct timeval tv; gettimeofday(&tv, NULL); start_time_in_ms = tv.tv_sec * 1000 + tv.tv_usec / 1000; // create FEE functor lti::fastEllipseExtraction::parameters feeParam; feeParam.maxArcGap = 120; feeParam.minLineLen = 3; for (unsigned int i = 0; i < edges.size(); i++) { double pyrScale = pow(2, i); lti::fastEllipseExtraction fee(feeParam); // extract some ellipses fprintf(stderr, "extracting from pyramid %d\n", i); fee.apply(*edges[i]); // build list std::vector<lti::fastEllipseExtraction::ellipseEntry> &ellipses = fee.getEllipseList(); for(unsigned int j=0; j<ellipses.size(); j++) { float a = ellipses[j].a * pyrScale; float b = ellipses[j].b * pyrScale; float r = quadratic_mean_radius(a, b); gboolean in_result = TRUE; // determine if it should go in by radius if (!(ct->minRadius < 0 || r >= ct->minRadius)) { in_result = FALSE; } else if (!(ct->maxRadius < 0 || r <= ct->maxRadius)) { in_result = FALSE; } // compute eccentricity float e = compute_eccentricity(a, b); // if over 0.9, drop completely if (e > 0.9) { continue; } // otherwise, maybe mark if (e > ct->maxEccentricity) { in_result = FALSE; } // all set circle_type *c = g_slice_new(circle_type); c->x = ellipses[j].x * pyrScale; c->y = ellipses[j].y * pyrScale; c->a = ellipses[j].a * pyrScale; c->b = ellipses[j].b * pyrScale; c->t = ellipses[j].t; c->in_result = in_result; result = g_list_prepend(result, c); // print ellipse data fprintf(stderr, " ellipse[%i]: center=(%.0f,%.0f) semiaxis=(%.0f,%.0f) " "angle=%.1f coverage=%.1f%% \n", j, c->x, c->y, c->a, c->b, c->t*180/M_PI, ellipses[j].coverage*100); } } gettimeofday(&tv, NULL); end_time_in_ms = tv.tv_sec * 1000 + tv.tv_usec / 1000; fprintf(stderr, "fee done in %" PRIu64 " ms\n", end_time_in_ms - start_time_in_ms); return result; } static circles_state_t staticState = {-1, -1, 0.4, 1}; GList *circlesFromImage2(circles_state_t *ct, const int width, const int height, const int stride, const int bytesPerPixel, const void *data) { uint64_t start_time_in_ms; uint64_t end_time_in_ms; struct timeval tv; gettimeofday(&tv, NULL); start_time_in_ms = tv.tv_sec * 1000 + tv.tv_usec / 1000; // load image g_assert(bytesPerPixel >= 3); lti::image img(false, height, width); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { guchar *d = ((guchar *) data) + (x * bytesPerPixel + y * stride); lti::rgbPixel p(d[0], d[1], d[2]); img[y][x] = p; } } // make pyramid int levels = (int)log2(MIN(img.rows(), img.columns())); lti::gaussianPyramid<lti::image> imgPyramid(levels); imgPyramid.generate(img); gettimeofday(&tv, NULL); end_time_in_ms = tv.tv_sec * 1000 + tv.tv_usec / 1000; fprintf(stderr, "load/pyramid done in %" PRIu64 " ms\n", end_time_in_ms - start_time_in_ms); // make vector std::vector<lti::channel8*> edges; // run do_canny(imgPyramid, edges, ct->minSharpness); GList *result = do_fee(edges, ct); // clear vector for (unsigned int i = 0; i < edges.size(); i++) { delete edges[i]; edges[i] = NULL; } // overlap suppression fprintf(stderr, "overlap suppression "); gettimeofday(&tv, NULL); start_time_in_ms = tv.tv_sec * 1000 + tv.tv_usec / 1000; result = g_list_sort(result, circle_radius_compare); // sort GList *iter; for (iter = result; iter != NULL; iter = g_list_next(iter)) { // find other centers within this circle (assume no eccentricity) circle_type *c1 = (circle_type *) iter->data; double c1_radius = quadratic_mean_radius(c1->a, c1->b); GList *iter2; // don't bother if large eccentricity double c1_e = compute_eccentricity(c1->a, c1->b); if (c1_e > 0.4) { continue; } iter2 = g_list_next(iter); while (iter2 != NULL) { circle_type *c2 = (circle_type *) iter2->data; double c2_radius = quadratic_mean_radius(c2->a, c2->b); // is c2 within c1? double xd = c2->x - c1->x; double yd = c2->y - c1->y; double dist = sqrt((xd * xd) + (yd * yd)); // maybe delete? GList *next = g_list_next(iter2); // fprintf(stderr, " dist: %g, c1_radius: %g, c2_radius: %g\n", // dist, c1_radius, c2_radius); // XXX fudge if ((dist + c2_radius) < (c1_radius + 100)) { fprintf(stderr, "x"); g_slice_free(circle_type, c2); result = g_list_delete_link(result, iter2); } iter2 = next; } fprintf(stderr, "."); } fprintf(stderr, "\n"); gettimeofday(&tv, NULL); end_time_in_ms = tv.tv_sec * 1000 + tv.tv_usec / 1000; fprintf(stderr, "overlap suppression done in %" PRIu64 " ms\n", end_time_in_ms - start_time_in_ms); return result; } // called from GUI GList *circlesFromImage(const int width, const int height, const int stride, const int bytesPerPixel, const void *data, double minSharpness) { circles_state_t cs = staticState; cs.minSharpness = minSharpness; return circlesFromImage2(&cs, width, height, stride, bytesPerPixel, data); } <|endoftext|>
<commit_before>/* * Copyright (c) 2010, Yuuki Takano ([email protected]). * 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 of the writers 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 CAGETIME_HPP #define CAGETIME_HPP #ifdef WIN32 #include <time.h> #include <windows.h> #if defined(_MSC_VER) || defined(_MSC_EXTENSIONS) #define DELTA_EPOCH_IN_MICROSECS 11644473600000000Ui64 #else #define DELTA_EPOCH_IN_MICROSECS 11644473600000000ULL #endif #else #include <sys/time.h> #endif // WIN32 namespace libcage { #ifdef WIN32 struct timezone { int tz_minuteswest; /* minutes W of Greenwich */ int tz_dsttime; /* type of dst correction */ }; int gettimeofday(struct timeval *tv, struct timezone *tz); #endif // WIN32 class cagetime { public: cagetime() { update(); } void update() { gettimeofday(&m_tval, NULL); } double operator- (cagetime& rhs) { double sec1, sec2; sec1 = (double)(m_tval.tv_sec + m_tval.tv_usec / 1000000.0); sec2 = (double)(rhs.m_tval.tv_sec + rhs.m_tval.tv_usec / 1000000.0); return sec1 - sec2; } private: timeval m_tval; }; } #endif // CAGETIME_HPP <commit_msg>Fixed missing NULL from some non-Windows builds<commit_after>/* * Copyright (c) 2010, Yuuki Takano ([email protected]). * 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 of the writers 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 CAGETIME_HPP #define CAGETIME_HPP #ifdef WIN32 #include <time.h> #include <windows.h> #if defined(_MSC_VER) || defined(_MSC_EXTENSIONS) #define DELTA_EPOCH_IN_MICROSECS 11644473600000000Ui64 #else #define DELTA_EPOCH_IN_MICROSECS 11644473600000000ULL #endif #else #include <stddef.h> #include <sys/time.h> #endif // WIN32 namespace libcage { #ifdef WIN32 struct timezone { int tz_minuteswest; /* minutes W of Greenwich */ int tz_dsttime; /* type of dst correction */ }; int gettimeofday(struct timeval *tv, struct timezone *tz); #endif // WIN32 class cagetime { public: cagetime() { update(); } void update() { gettimeofday(&m_tval, NULL); } double operator- (cagetime& rhs) { double sec1, sec2; sec1 = (double)(m_tval.tv_sec + m_tval.tv_usec / 1000000.0); sec2 = (double)(rhs.m_tval.tv_sec + rhs.m_tval.tv_usec / 1000000.0); return sec1 - sec2; } private: timeval m_tval; }; } #endif // CAGETIME_HPP <|endoftext|>
<commit_before>/*=========================================================================== --- DENIS Project --- ----------------- Distributed computing Electrophysiologycal Models Networking colaboration In Silico research Sharing Knowledge --------------------------------------------------------------------------- San Jorge University School of Engineering http://eps.usj.es --------------------------------------------------------------------------- Copyright 2015 J. Carro; J. Castro 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 <IfaceCellML_APISPEC.hxx> #include <IfaceAnnoTools.hxx> #include <IfaceCeLEDSExporter.hxx> #include <CeLEDSExporterBootstrap.hpp> #include <CellMLBootstrap.hpp> #include <fstream> #include <string> #include <cstring> using namespace iface::cellml_api; using namespace iface::cellml_services; using namespace std; int main(int argc, char **argv) { if(argc<4){ cout << "Invalid number of input arguments" << endl << endl; cout << " cellm2c <cellml_file> <output_c_file> <name_space>" << endl << endl; return -1; } string executable = argv[0]; string formatPath = executable.substr(0, executable.find_last_of("/")+1) + "C.xml"; wstring wsFormatPath(formatPath.begin(), formatPath.end()); const size_t cSize = strlen(argv[1])+1; wchar_t* wc = new wchar_t[cSize]; mbstowcs (wc, argv[1], cSize); wstring wsURL(wc); CellMLBootstrap* bootstrap = CreateCellMLBootstrap(); cout << "Bootstrap created" << endl; DOMModelLoader* ml = bootstrap->modelLoader(); cout << "ModelLoader created" << endl; Model* model = ml->loadFromURL(wsURL); cout << "Model loaded from URL" << endl; CeLEDSExporterBootstrap* celedsexporterb = CreateCeLEDSExporterBootstrap(); cout << "CeLEDSExproterBootestrap created" << endl; CodeExporter* ce = celedsexporterb->createExporter(wsFormatPath); cout << "Exporter created" << endl; wstring code = ce->generateCode(model); cout << "Code generated" << endl; wofstream wofs(argv[2]); wofs << "namespace " << argv[3] << "{" << endl << code << endl <<"}"; cout << "File " << argv[2] << " created." <<endl; return 0; } <commit_msg>Changing to use structs<commit_after>/*=========================================================================== --- DENIS Project --- ----------------- Distributed computing Electrophysiologycal Models Networking colaboration In Silico research Sharing Knowledge --------------------------------------------------------------------------- San Jorge University School of Engineering http://eps.usj.es --------------------------------------------------------------------------- Copyright 2015 J. Carro; J. Castro 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 <IfaceCellML_APISPEC.hxx> #include <IfaceAnnoTools.hxx> #include <IfaceCeLEDSExporter.hxx> #include <CeLEDSExporterBootstrap.hpp> #include <CellMLBootstrap.hpp> #include <fstream> #include <string> #include <cstring> using namespace iface::cellml_api; using namespace iface::cellml_services; using namespace std; int main(int argc, char **argv) { if(argc<4){ cout << "Invalid number of input arguments" << endl << endl; cout << " cellm2c <cellml_file> <output_c_file> <name_space>" << endl << endl; return -1; } string executable = argv[0]; string formatPath = executable.substr(0, executable.find_last_of("/")+1) + "C.xml"; wstring wsFormatPath(formatPath.begin(), formatPath.end()); const size_t cSize = strlen(argv[1])+1; wchar_t* wc = new wchar_t[cSize]; mbstowcs (wc, argv[1], cSize); wstring wsURL(wc); CellMLBootstrap* bootstrap = CreateCellMLBootstrap(); cout << "Bootstrap created" << endl; DOMModelLoader* ml = bootstrap->modelLoader(); cout << "ModelLoader created" << endl; Model* model = ml->loadFromURL(wsURL); cout << "Model loaded from URL" << endl; CeLEDSExporterBootstrap* celedsexporterb = CreateCeLEDSExporterBootstrap(); cout << "CeLEDSExproterBootestrap created" << endl; CodeExporter* ce = celedsexporterb->createExporter(wsFormatPath); cout << "Exporter created" << endl; wstring code = ce->generateCode(model); cout << "Code generated" << endl; wofstream wofs(argv[2]); wofs << "static const struct{ " << endl << code << endl << "}" << argv[3] <<";"; cout << "File " << argv[2] << " created." <<endl; return 0; } <|endoftext|>
<commit_before>#include <thread> #include <mutex> #include "band.h" #include "debug.hpp" namespace sirius { /** \param [in] phi Input wave-functions [storage: CPU]. * \param [out] hphi Result of application of operator to the wave-functions [storage: CPU]. */ void Band::apply_h_local_serial(K_point* kp__, std::vector<double> const& effective_potential__, std::vector<double> const& pw_ekin__, int num_phi__, matrix<double_complex> const& phi__, matrix<double_complex>& hphi__) { PROFILE(); Timer t("sirius::Band::apply_h_local_serial"); assert(phi__.size(0) == (size_t)kp__->num_gkvec() && hphi__.size(0) == (size_t)kp__->num_gkvec()); assert(phi__.size(1) >= (size_t)num_phi__ && hphi__.size(1) >= (size_t)num_phi__); bool in_place = (&phi__ == &hphi__); auto pu = parameters_.processing_unit(); auto fft = ctx_.fft_coarse(); #ifdef __GPU FFT3D<GPU>* fft_gpu = ctx_.fft_gpu_coarse(); #endif int num_fft_threads = -1; switch (pu) { case CPU: { num_fft_threads = parameters_.num_fft_threads(); break; } case GPU: { num_fft_threads = std::min(parameters_.num_fft_threads() + 1, Platform::max_num_threads()); break; } } std::vector<std::thread> fft_threads; /* index of the wave-function */ int idx_phi = 0; std::mutex idx_phi_mutex; int count_fft_cpu = 0; #ifdef __GPU int count_fft_gpu = 0; #endif mdarray<double, 1> timers(Platform::max_num_threads()); timers.zero(); Timer t1("fft_loop"); for (int thread_id = 0; thread_id < num_fft_threads; thread_id++) { if (thread_id == num_fft_threads - 1 && num_fft_threads > 1 && pu == GPU) { #ifdef __GPU fft_threads.push_back(std::thread([thread_id, num_phi__, &idx_phi, &idx_phi_mutex, &fft_gpu, kp__, &phi__, &hphi__, &effective_potential__, &pw_ekin__, &count_fft_gpu, &timers]() { Timer t("sirius::Band::apply_h_local_serial|gpu"); timers(thread_id) = -omp_get_wtime(); /* move fft index to GPU */ mdarray<int, 1> fft_index(const_cast<int*>(kp__->gkvec_coarse().index_map()), kp__->num_gkvec()); fft_index.allocate_on_device(); fft_index.copy_to_device(); /* allocate work area array */ mdarray<char, 1> work_area(nullptr, fft_gpu->work_area_size()); work_area.allocate_on_device(); fft_gpu->set_work_area_ptr(work_area.at<GPU>()); /* allocate space for plane-wave expansion coefficients */ mdarray<double_complex, 2> pw_buf(nullptr, kp__->num_gkvec(), fft_gpu->num_fft()); pw_buf.allocate_on_device(); /* allocate space for FFT buffers */ matrix<double_complex> fft_buf(nullptr, fft_gpu->size(), fft_gpu->num_fft()); fft_buf.allocate_on_device(); mdarray<double, 1> veff_gpu((double*)&effective_potential__[0], fft_gpu->size()); veff_gpu.allocate_on_device(); veff_gpu.copy_to_device(); mdarray<double, 1> pw_ekin_gpu((double*)&pw_ekin__[0], kp__->num_gkvec()); pw_ekin_gpu.allocate_on_device(); pw_ekin_gpu.copy_to_device(); Timer t1("sirius::Band::apply_h_local_serial|gpu_loop"); bool done = false; while (!done) { /* increment the band index */ idx_phi_mutex.lock(); int i = idx_phi; if (idx_phi + fft_gpu->num_fft() > num_phi__) { done = true; } else { idx_phi += fft_gpu->num_fft(); count_fft_gpu += fft_gpu->num_fft(); } idx_phi_mutex.unlock(); if (!done) { int size_of_panel = int(kp__->num_gkvec() * fft_gpu->num_fft() * sizeof(double_complex)); /* copy phi to GPU */ cuda_copy_to_device(pw_buf.at<GPU>(), phi__.at<CPU>(0, i), size_of_panel); /* set PW coefficients into proper positions inside FFT buffer */ fft_gpu->batch_load(kp__->num_gkvec(), fft_index.at<GPU>(), pw_buf.at<GPU>(), fft_buf.at<GPU>()); /* phi(G) *= Ekin(G) */ scale_matrix_rows_gpu(kp__->num_gkvec(), fft_gpu->num_fft(), pw_buf.at<GPU>(), pw_ekin_gpu.at<GPU>()); /* execute batch FFT */ fft_gpu->transform(1, fft_buf.at<GPU>()); /* multiply by potential */ scale_matrix_rows_gpu(fft_gpu->size(), fft_gpu->num_fft(), fft_buf.at<GPU>(), veff_gpu.at<GPU>()); /* transform back */ fft_gpu->transform(-1, fft_buf.at<GPU>()); /* phi(G) += fft_buffer(G) */ fft_gpu->batch_unload(kp__->num_gkvec(), fft_index.at<GPU>(), fft_buf.at<GPU>(), pw_buf.at<GPU>(), 1.0); /* copy final hphi to CPU */ cuda_copy_to_host(hphi__.at<CPU>(0, i), pw_buf.at<GPU>(), size_of_panel); } } timers(thread_id) += omp_get_wtime(); })); #else TERMINATE_NO_GPU #endif } else { fft_threads.push_back(std::thread([thread_id, num_phi__, &idx_phi, &idx_phi_mutex, &fft, kp__, &phi__, &hphi__, &effective_potential__, &pw_ekin__, &count_fft_cpu, in_place, &timers]() { timers(thread_id) = -omp_get_wtime(); bool done = false; while (!done) { /* increment the band index */ idx_phi_mutex.lock(); int i = idx_phi; if (idx_phi + 1 > num_phi__) { done = true; } else { idx_phi++; count_fft_cpu++; } idx_phi_mutex.unlock(); if (!done) { fft->input(kp__->num_gkvec(), kp__->gkvec_coarse().index_map(), &phi__(0, i), thread_id); /* phi(G) -> phi(r) */ fft->transform(1, thread_id); /* multiply by effective potential */ for (int ir = 0; ir < fft->size(); ir++) fft->buffer(ir, thread_id) *= effective_potential__[ir]; /* V(r)phi(r) -> [V*phi](G) */ fft->transform(-1, thread_id); if (in_place) { for (int igk = 0; igk < kp__->num_gkvec(); igk++) hphi__(igk, i) *= pw_ekin__[igk]; fft->output(kp__->num_gkvec(), kp__->gkvec_coarse().index_map(), &hphi__(0, i), thread_id, 1.0); } else { fft->output(kp__->num_gkvec(), kp__->gkvec_coarse().index_map(), &hphi__(0, i), thread_id); for (int igk = 0; igk < kp__->num_gkvec(); igk++) hphi__(igk, i) += phi__(igk, i) * pw_ekin__[igk]; } } } timers(thread_id) += omp_get_wtime(); })); } } for (auto& thread: fft_threads) thread.join(); double tval = t1.stop(); DUMP("time: %f (sec.), performance: %f (FFTs/sec.)", tval, 2 * num_phi__ / tval); //== if (kp__->comm().rank() == 0) //== { //== std::cout << "---------------------" << std::endl; //== std::cout << "thread_id | fft " << std::endl; //== std::cout << "---------------------" << std::endl; //== for (int i = 0; i < num_fft_threads; i++) //== { //== printf(" %2i | %8.4f \n", i, timers(i)); //== } //== std::cout << "---------------------" << std::endl; //== } //== if (kp__->comm().rank() == 0) DUMP("CPU / GPU fft count : %i %i", count_fft_cpu, count_fft_gpu); } }; <commit_msg>custom fft transform<commit_after>#include <thread> #include <mutex> #include "band.h" #include "debug.hpp" namespace sirius { /** \param [in] phi Input wave-functions [storage: CPU]. * \param [out] hphi Result of application of operator to the wave-functions [storage: CPU]. */ void Band::apply_h_local_serial(K_point* kp__, std::vector<double> const& effective_potential__, std::vector<double> const& pw_ekin__, int num_phi__, matrix<double_complex> const& phi__, matrix<double_complex>& hphi__) { PROFILE(); Timer t("sirius::Band::apply_h_local_serial"); assert(phi__.size(0) == (size_t)kp__->num_gkvec() && hphi__.size(0) == (size_t)kp__->num_gkvec()); assert(phi__.size(1) >= (size_t)num_phi__ && hphi__.size(1) >= (size_t)num_phi__); bool in_place = (&phi__ == &hphi__); auto pu = parameters_.processing_unit(); auto fft = ctx_.fft_coarse(); #ifdef __GPU FFT3D<GPU>* fft_gpu = ctx_.fft_gpu_coarse(); #endif int num_fft_threads = -1; switch (pu) { case CPU: { num_fft_threads = parameters_.num_fft_threads(); break; } case GPU: { num_fft_threads = std::min(parameters_.num_fft_threads() + 1, Platform::max_num_threads()); break; } } std::vector<std::thread> fft_threads; /* index of the wave-function */ int idx_phi = 0; std::mutex idx_phi_mutex; int count_fft_cpu = 0; #ifdef __GPU int count_fft_gpu = 0; #endif mdarray<double, 1> timers(Platform::max_num_threads()); timers.zero(); Timer t1("fft_loop"); for (int thread_id = 0; thread_id < num_fft_threads; thread_id++) { if (thread_id == num_fft_threads - 1 && num_fft_threads > 1 && pu == GPU) { #ifdef __GPU fft_threads.push_back(std::thread([thread_id, num_phi__, &idx_phi, &idx_phi_mutex, &fft_gpu, kp__, &phi__, &hphi__, &effective_potential__, &pw_ekin__, &count_fft_gpu, &timers]() { Timer t("sirius::Band::apply_h_local_serial|gpu"); timers(thread_id) = -omp_get_wtime(); /* move fft index to GPU */ mdarray<int, 1> fft_index(const_cast<int*>(kp__->gkvec_coarse().index_map()), kp__->num_gkvec()); fft_index.allocate_on_device(); fft_index.copy_to_device(); /* allocate work area array */ mdarray<char, 1> work_area(nullptr, fft_gpu->work_area_size()); work_area.allocate_on_device(); fft_gpu->set_work_area_ptr(work_area.at<GPU>()); /* allocate space for plane-wave expansion coefficients */ mdarray<double_complex, 2> pw_buf(nullptr, kp__->num_gkvec(), fft_gpu->num_fft()); pw_buf.allocate_on_device(); /* allocate space for FFT buffers */ matrix<double_complex> fft_buf(nullptr, fft_gpu->size(), fft_gpu->num_fft()); fft_buf.allocate_on_device(); mdarray<double, 1> veff_gpu((double*)&effective_potential__[0], fft_gpu->size()); veff_gpu.allocate_on_device(); veff_gpu.copy_to_device(); mdarray<double, 1> pw_ekin_gpu((double*)&pw_ekin__[0], kp__->num_gkvec()); pw_ekin_gpu.allocate_on_device(); pw_ekin_gpu.copy_to_device(); Timer t1("sirius::Band::apply_h_local_serial|gpu_loop"); bool done = false; while (!done) { /* increment the band index */ idx_phi_mutex.lock(); int i = idx_phi; if (idx_phi + fft_gpu->num_fft() > num_phi__) { done = true; } else { idx_phi += fft_gpu->num_fft(); count_fft_gpu += fft_gpu->num_fft(); } idx_phi_mutex.unlock(); if (!done) { int size_of_panel = int(kp__->num_gkvec() * fft_gpu->num_fft() * sizeof(double_complex)); /* copy phi to GPU */ cuda_copy_to_device(pw_buf.at<GPU>(), phi__.at<CPU>(0, i), size_of_panel); /* set PW coefficients into proper positions inside FFT buffer */ fft_gpu->batch_load(kp__->num_gkvec(), fft_index.at<GPU>(), pw_buf.at<GPU>(), fft_buf.at<GPU>()); /* phi(G) *= Ekin(G) */ scale_matrix_rows_gpu(kp__->num_gkvec(), fft_gpu->num_fft(), pw_buf.at<GPU>(), pw_ekin_gpu.at<GPU>()); /* execute batch FFT */ fft_gpu->transform(1, fft_buf.at<GPU>()); /* multiply by potential */ scale_matrix_rows_gpu(fft_gpu->size(), fft_gpu->num_fft(), fft_buf.at<GPU>(), veff_gpu.at<GPU>()); /* transform back */ fft_gpu->transform(-1, fft_buf.at<GPU>()); /* phi(G) += fft_buffer(G) */ fft_gpu->batch_unload(kp__->num_gkvec(), fft_index.at<GPU>(), fft_buf.at<GPU>(), pw_buf.at<GPU>(), 1.0); /* copy final hphi to CPU */ cuda_copy_to_host(hphi__.at<CPU>(0, i), pw_buf.at<GPU>(), size_of_panel); } } timers(thread_id) += omp_get_wtime(); })); #else TERMINATE_NO_GPU #endif } else { fft_threads.push_back(std::thread([thread_id, num_phi__, &idx_phi, &idx_phi_mutex, &fft, kp__, &phi__, &hphi__, &effective_potential__, &pw_ekin__, &count_fft_cpu, in_place, &timers]() { timers(thread_id) = -omp_get_wtime(); bool done = false; while (!done) { /* increment the band index */ idx_phi_mutex.lock(); int i = idx_phi; if (idx_phi + 1 > num_phi__) { done = true; } else { idx_phi++; count_fft_cpu++; } idx_phi_mutex.unlock(); if (!done) { fft->input(kp__->num_gkvec(), kp__->gkvec_coarse().index_map(), &phi__(0, i), thread_id); /* phi(G) -> phi(r) */ fft->transform(1, kp__->gkvec_coarse().z_sticks_coord(), thread_id); /* multiply by effective potential */ for (int ir = 0; ir < fft->size(); ir++) fft->buffer(ir, thread_id) *= effective_potential__[ir]; /* V(r)phi(r) -> [V*phi](G) */ fft->transform(-1, kp__->gkvec_coarse().z_sticks_coord(), thread_id); if (in_place) { for (int igk = 0; igk < kp__->num_gkvec(); igk++) hphi__(igk, i) *= pw_ekin__[igk]; fft->output(kp__->num_gkvec(), kp__->gkvec_coarse().index_map(), &hphi__(0, i), thread_id, 1.0); } else { fft->output(kp__->num_gkvec(), kp__->gkvec_coarse().index_map(), &hphi__(0, i), thread_id); for (int igk = 0; igk < kp__->num_gkvec(); igk++) hphi__(igk, i) += phi__(igk, i) * pw_ekin__[igk]; } } } timers(thread_id) += omp_get_wtime(); })); } } for (auto& thread: fft_threads) thread.join(); double tval = t1.stop(); DUMP("time: %f (sec.), performance: %f (FFTs/sec.)", tval, 2 * num_phi__ / tval); //== if (kp__->comm().rank() == 0) //== { //== std::cout << "---------------------" << std::endl; //== std::cout << "thread_id | fft " << std::endl; //== std::cout << "---------------------" << std::endl; //== for (int i = 0; i < num_fft_threads; i++) //== { //== printf(" %2i | %8.4f \n", i, timers(i)); //== } //== std::cout << "---------------------" << std::endl; //== } //== if (kp__->comm().rank() == 0) DUMP("CPU / GPU fft count : %i %i", count_fft_cpu, count_fft_gpu); } }; <|endoftext|>
<commit_before>#pragma once #include <vector> #include <boost/variant.hpp> #include "Tag.hpp" #include "Value.hpp" namespace But { namespace Log { namespace Backend { class FieldInfo final { public: template<typename T> explicit FieldInfo(T&& value): type_{ Tag::of(value) }, variant_{ Value{ std::forward<T>(value) } } { } FieldInfo(Value const& value) = delete; FieldInfo(Value&& value) = delete; FieldInfo(Tag type, Value value): type_{ std::move(type) }, variant_{ std::move(value) } { } FieldInfo(Tag type, std::vector<FieldInfo> fi): type_{ std::move(type) }, variant_{ std::move(fi) } { } FieldInfo(FieldInfo&&) = default; FieldInfo& operator=(FieldInfo&&) = default; FieldInfo(FieldInfo const&) = default; FieldInfo& operator=(FieldInfo const&) = default; bool operator==(FieldInfo const& other) const { return type_ == other.type_ && variant_ == other.variant_; } bool operator!=(FieldInfo const& other) const { return not ( *this == other ); } auto const& type() const & { return type_; } auto const& value() const & { return boost::get<Value>(variant_); } auto const& array() const & { return boost::get<std::vector<FieldInfo>>(variant_); } auto&& type() && { return std::move(type_); } auto&& value() && { return boost::get<Value>( std::move(variant_) ); } auto&& array() && { return boost::get<std::vector<FieldInfo>>( std::move(variant_) ); } /** @brief visitor takes type and value parametrs, like this: * <code> * struct Visitor * { * void operator()(Tag const& t, Value const& v) * { * cout << '/' << t << '=' << v; * } * void operator()(Tag const& t, std::vector<FieldInfo> const& fis) * { * cout << '/' << t << "=["; * for(auto& e: fis) * e.visit(*this); * ss_ << "]"; * } * }; * </code> */ template<typename F> void visit(F&& f) { boost::apply_visitor( [&](auto& e) { f(type_, e); }, variant_ ); } template<typename F> void visit(F&& f) const { boost::apply_visitor( [&](auto const& e) { f(type_, e); }, variant_ ); } private: Tag type_; // TODO: std::variant<> when C++17 is here boost::variant<Value, std::vector<FieldInfo>> variant_; }; } } } <commit_msg>renamed type() to tag() method<commit_after>#pragma once #include <vector> #include <boost/variant.hpp> #include "Tag.hpp" #include "Value.hpp" namespace But { namespace Log { namespace Backend { class FieldInfo final { public: template<typename T> explicit FieldInfo(T&& value): tag_{ Tag::of(value) }, variant_{ Value{ std::forward<T>(value) } } { } FieldInfo(Value const& value) = delete; FieldInfo(Value&& value) = delete; FieldInfo(Tag tag, Value value): tag_{ std::move(tag) }, variant_{ std::move(value) } { } FieldInfo(Tag tag, std::vector<FieldInfo> fi): tag_{ std::move(tag) }, variant_{ std::move(fi) } { } FieldInfo(FieldInfo&&) = default; FieldInfo& operator=(FieldInfo&&) = default; FieldInfo(FieldInfo const&) = default; FieldInfo& operator=(FieldInfo const&) = default; bool operator==(FieldInfo const& other) const { return tag_ == other.tag_ && variant_ == other.variant_; } bool operator!=(FieldInfo const& other) const { return not ( *this == other ); } auto const& tag() const & { return tag_; } auto const& value() const & { return boost::get<Value>(variant_); } auto const& array() const & { return boost::get<std::vector<FieldInfo>>(variant_); } auto&& tag() && { return std::move(tag_); } auto&& value() && { return boost::get<Value>( std::move(variant_) ); } auto&& array() && { return boost::get<std::vector<FieldInfo>>( std::move(variant_) ); } /** @brief visitor takes tag and value parametrs, like this: * <code> * struct Visitor * { * void operator()(Tag const& t, Value const& v) * { * cout << '/' << t << '=' << v; * } * void operator()(Tag const& t, std::vector<FieldInfo> const& fis) * { * cout << '/' << t << "=["; * for(auto& e: fis) * e.visit(*this); * ss_ << "]"; * } * }; * </code> */ template<typename F> void visit(F&& f) { boost::apply_visitor( [&](auto& e) { f(tag_, e); }, variant_ ); } template<typename F> void visit(F&& f) const { boost::apply_visitor( [&](auto const& e) { f(tag_, e); }, variant_ ); } private: Tag tag_; // TODO: std::variant<> when C++17 is here boost::variant<Value, std::vector<FieldInfo>> variant_; }; } } } <|endoftext|>
<commit_before>// MS WARNINGS MACRO #define _SCL_SECURE_NO_WARNINGS // Macro: Program Settings #define ENABLE_NETWORK_IO 0 #include <iostream> #include <deque> #include <boost/noncopyable.hpp> #include "data_type.hpp" #include "pixel_sorter.hpp" #include "ppm_reader.hpp" #include "splitter.hpp" #include "algorithm.hpp" #include "algorithm_2.hpp" #include "gui.hpp" #include "network.hpp" #include "test_tool.hpp" #include <sort_algorithm/yrange2.hpp> #include <sort_algorithm/yrange5.hpp> #include <sort_algorithm/genetic.hpp> #include <sort_algorithm/Murakami.hpp> class position_manager : boost::noncopyable { public: typedef question_data position_type; position_manager() = default; virtual ~position_manager() = default; template<class T> void add(T && pos) { std::lock_guard<std::mutex> lock(mutex_); items_.push_back(std::forward<T>(pos)); } position_type get() { std::lock_guard<std::mutex> lock(mutex_); auto res = items_.front(); items_.pop_front(); return res; } bool empty() { return items_.empty(); } private: std::mutex mutex_; std::deque<position_type> items_; }; class analyzer : boost::noncopyable { public: explicit analyzer(int const problem_id, std::string const& player_id) : client_(), problem_id_(problem_id), player_id_(player_id) { } virtual ~analyzer() = default; void operator() (position_manager& manager) { // 問題文の入手 raw_data_ = get_raw_question(); data_ = get_skelton_question(raw_data_); // 2次元画像に分割 split_image_ = splitter().split_image(raw_data_); // 原画像推測部 // TODO: yrangeなどの実行 auto sorter_resolve = sorter_(raw_data_, split_image_); //data_.block = std::move(sorter_resolve); data_.block = sorter_resolve; if(!data_.block.empty())manager.add(convert_block(data_)); // 解答 // TODO: yrange5の実行(並列化) // 画面表示をいくつか(yrange/Murakmi/yrange5/algo2 etc.) std::vector<boost::shared_ptr<gui::impl::MoveWindow>> windows; if (!data_.block.empty())windows.push_back( gui::make_mansort_window(split_image_, sorter_resolve, "Murakami") ); if (!data_.block.empty())windows.push_back( gui::make_mansort_window(split_image_, sorter_resolve, "Murakami") ); if (data_.block.empty() && data_.block.empty()){//どっちもダメだった時 windows.push_back( gui::make_mansort_window(split_image_, "Yor are the sorter!!! Sort this!") ); } boost::thread th( [&]() { // futureリストでvalidを巡回し,閉じられたWindowから解とする while(!windows.empty()) { for(auto it = windows.begin(); it != windows.end();) { auto res = gui::get_result(*it); if(res) { if (res.get().size() == 0) { //TODO:man sorterの答え受け取るのはこのタイミングが良いのではないだろうか. continue; } data_.block = res.get(); manager.add(convert_block(data_)); // 解答 it = windows.erase(it); } else ++it; } } }); gui::wait_all_window(); th.join(); } std::string submit(answer_type const& ans) const { auto submit_result = client_.submit(problem_id_, player_id_, ans); return submit_result.get(); } private: question_raw_data get_raw_question() const { #if ENABLE_NETWORK_IO // ネットワーク通信から std::string const data = client_.get_problem(01).get(); return ppm_reader().from_data(data); #else // ファイルから std::string const path("prob01.ppm"); return ppm_reader().from_file(path); #endif } question_data get_skelton_question(question_raw_data const& raw) const { question_data formed = { problem_id_, player_id_, raw.split_num, raw.selectable_num, raw.cost.first, raw.cost.second, std::vector<std::vector<point_type>>() }; return formed; } question_data convert_block(question_data const& data) const { auto res = data.clone(); for(int i = 0; i < data.size.second; ++i) { for(int j = 0; j < data.size.first; ++j) { auto const& target = data.block[i][j]; res.block[target.y][target.x] = point_type{j, i}; } } return res; } int const problem_id_; std::string const player_id_; question_raw_data raw_data_; question_data data_; split_image_type split_image_; mutable network::client client_; pixel_sorter<Murakami> sorter_; }; question_data convert_block(question_data const& data) { auto res = data.clone(); for(int i = 0; i < data.size.second; ++i) { for(int j = 0; j < data.size.first; ++j) { auto const& target = data.block[i][j]; res.block[target.y][target.x] = point_type{j, i}; } } return res; } int main() { auto const ploblemid = 1; auto const token = "3935105806"; analyzer analyze(ploblemid, token); algorithm_2 algo; position_manager manager; boost::thread thread(boost::bind(&analyzer::operator(), &analyze, std::ref(manager))); while(true) { if(!manager.empty()) { // 手順探索部 auto question = manager.get(); algo.reset(question); auto const answer = algo.get(); if(answer) // 解が見つかった { #if ENABLE_NETWORK_IO // TODO: 前より良くなったら提出など(普通にいらないかも.提出前に目grepしてるわけだし) auto result = analyze.submit(answer.get()); std::cout << "Submit Result: " << result << std::endl; #else test_tool::emulator emu(question); auto result = emu.start(answer.get()); std::cout << "Wrong: " << result.wrong << std::endl; std::cout << "Cost : " << result.cost << std::endl; std::cout << "---" << std::endl; #endif } } } thread.join(); return 0; } <commit_msg>コンストラクタで与えられた問題番号が,HTTP通信に使用されていない問題を修正.<commit_after>// MS WARNINGS MACRO #define _SCL_SECURE_NO_WARNINGS // Macro: Program Settings #define ENABLE_NETWORK_IO 0 #include <iostream> #include <deque> #include <boost/noncopyable.hpp> #include "data_type.hpp" #include "pixel_sorter.hpp" #include "ppm_reader.hpp" #include "splitter.hpp" #include "algorithm.hpp" #include "algorithm_2.hpp" #include "gui.hpp" #include "network.hpp" #include "test_tool.hpp" #include <sort_algorithm/yrange2.hpp> #include <sort_algorithm/yrange5.hpp> #include <sort_algorithm/genetic.hpp> #include <sort_algorithm/Murakami.hpp> class position_manager : boost::noncopyable { public: typedef question_data position_type; position_manager() = default; virtual ~position_manager() = default; template<class T> void add(T && pos) { std::lock_guard<std::mutex> lock(mutex_); items_.push_back(std::forward<T>(pos)); } position_type get() { std::lock_guard<std::mutex> lock(mutex_); auto res = items_.front(); items_.pop_front(); return res; } bool empty() { return items_.empty(); } private: std::mutex mutex_; std::deque<position_type> items_; }; class analyzer : boost::noncopyable { public: explicit analyzer(int const problem_id, std::string const& player_id) : client_(), problem_id_(problem_id), player_id_(player_id) { } virtual ~analyzer() = default; void operator() (position_manager& manager) { // 問題文の入手 raw_data_ = get_raw_question(); data_ = get_skelton_question(raw_data_); // 2次元画像に分割 split_image_ = splitter().split_image(raw_data_); // 原画像推測部 // TODO: yrangeなどの実行 auto sorter_resolve = sorter_(raw_data_, split_image_); //data_.block = std::move(sorter_resolve); data_.block = sorter_resolve; if(!data_.block.empty())manager.add(convert_block(data_)); // 解答 // TODO: yrange5の実行(並列化) // 画面表示をいくつか(yrange/Murakmi/yrange5/algo2 etc.) std::vector<boost::shared_ptr<gui::impl::MoveWindow>> windows; if (!data_.block.empty())windows.push_back( gui::make_mansort_window(split_image_, sorter_resolve, "Murakami") ); if (!data_.block.empty())windows.push_back( gui::make_mansort_window(split_image_, sorter_resolve, "Murakami") ); if (data_.block.empty() && data_.block.empty()){//どっちもダメだった時 windows.push_back( gui::make_mansort_window(split_image_, "Yor are the sorter!!! Sort this!") ); } boost::thread th( [&]() { // futureリストでvalidを巡回し,閉じられたWindowから解とする while(!windows.empty()) { for(auto it = windows.begin(); it != windows.end();) { auto res = gui::get_result(*it); if(res) { if (res.get().size() == 0) { //TODO:man sorterの答え受け取るのはこのタイミングが良いのではないだろうか. continue; } data_.block = res.get(); manager.add(convert_block(data_)); // 解答 it = windows.erase(it); } else ++it; } } }); gui::wait_all_window(); th.join(); } std::string submit(answer_type const& ans) const { auto submit_result = client_.submit(problem_id_, player_id_, ans); return submit_result.get(); } private: question_raw_data get_raw_question() const { #if ENABLE_NETWORK_IO // ネットワーク通信から std::string const data = client_.get_problem(problem_id_).get(); return ppm_reader().from_data(data); #else // ファイルから std::string const path("prob01.ppm"); return ppm_reader().from_file(path); #endif } question_data get_skelton_question(question_raw_data const& raw) const { question_data formed = { problem_id_, player_id_, raw.split_num, raw.selectable_num, raw.cost.first, raw.cost.second, std::vector<std::vector<point_type>>() }; return formed; } question_data convert_block(question_data const& data) const { auto res = data.clone(); for(int i = 0; i < data.size.second; ++i) { for(int j = 0; j < data.size.first; ++j) { auto const& target = data.block[i][j]; res.block[target.y][target.x] = point_type{j, i}; } } return res; } int const problem_id_; std::string const player_id_; question_raw_data raw_data_; question_data data_; split_image_type split_image_; mutable network::client client_; pixel_sorter<Murakami> sorter_; }; question_data convert_block(question_data const& data) { auto res = data.clone(); for(int i = 0; i < data.size.second; ++i) { for(int j = 0; j < data.size.first; ++j) { auto const& target = data.block[i][j]; res.block[target.y][target.x] = point_type{j, i}; } } return res; } int main() { auto const ploblemid = 1; auto const token = "3935105806"; analyzer analyze(ploblemid, token); algorithm_2 algo; position_manager manager; boost::thread thread(boost::bind(&analyzer::operator(), &analyze, std::ref(manager))); while(true) { if(!manager.empty()) { // 手順探索部 auto question = manager.get(); algo.reset(question); auto const answer = algo.get(); if(answer) // 解が見つかった { #if ENABLE_NETWORK_IO // TODO: 前より良くなったら提出など(普通にいらないかも.提出前に目grepしてるわけだし) auto result = analyze.submit(answer.get()); std::cout << "Submit Result: " << result << std::endl; #else test_tool::emulator emu(question); auto result = emu.start(answer.get()); std::cout << "Wrong: " << result.wrong << std::endl; std::cout << "Cost : " << result.cost << std::endl; std::cout << "---" << std::endl; #endif } } } thread.join(); return 0; } <|endoftext|>