hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
d4def2c332a02eb3c7fc5a078ff4f01d2bacdfe0
779
cpp
C++
Game/PopUpManager.cpp
scottvermast/PengoEngine
82a864d75c3806b8dcfd7fd1a5d2b8a6ded8ecf3
[ "Apache-2.0" ]
null
null
null
Game/PopUpManager.cpp
scottvermast/PengoEngine
82a864d75c3806b8dcfd7fd1a5d2b8a6ded8ecf3
[ "Apache-2.0" ]
null
null
null
Game/PopUpManager.cpp
scottvermast/PengoEngine
82a864d75c3806b8dcfd7fd1a5d2b8a6ded8ecf3
[ "Apache-2.0" ]
null
null
null
#include "PopUpManager.h" PopUpManager::PopUpManager() : m_pGameTime(GameTime::GetInstance()) , m_pRenderer(Renderer::GetInstance()) , m_PopUps() { } PopUpManager::~PopUpManager() { } void PopUpManager::Update() { for (size_t i{ 0 }; i < m_PopUps.size(); ++i) { m_PopUps[i].timer += m_pGameTime->GetElapsedSec(); if (m_PopUps[i].timer > 1.5f) { m_PopUps.erase(m_PopUps.begin() + i); } } } void PopUpManager::AddPopUp(const std::string& string, const glm::vec2& position) { m_PopUps.push_back({ string, position, 0.0f }); } void PopUpManager::Render() { for (size_t i{ 0 }; i < m_PopUps.size(); ++i) { m_pRenderer->RenderText(m_PopUps[i].number, { 255, 255, 255 }, "RetroGaming.ttf", 16, (int)m_PopUps[i].position.x, (int)m_PopUps[i].position.y); } }
19.974359
146
0.661104
[ "render" ]
d4e18fad8fbc8334b99c3b1cf7beea5410656f68
5,473
hpp
C++
ThirdParty-mod/java2cpp/java/io/InputStream.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
1
2019-04-03T01:53:28.000Z
2019-04-03T01:53:28.000Z
ThirdParty-mod/java2cpp/java/io/InputStream.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
ThirdParty-mod/java2cpp/java/io/InputStream.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
/*================================================================================ code generated by: java2cpp author: Zoran Angelov, mailto://baldzar@gmail.com class: java.io.InputStream ================================================================================*/ #ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_IO_INPUTSTREAM_HPP_DECL #define J2CPP_JAVA_IO_INPUTSTREAM_HPP_DECL namespace j2cpp { namespace java { namespace io { class Closeable; } } } namespace j2cpp { namespace java { namespace lang { class Object; } } } #include <java/io/Closeable.hpp> #include <java/lang/Object.hpp> namespace j2cpp { namespace java { namespace io { class InputStream; class InputStream : public object<InputStream> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) J2CPP_DECLARE_METHOD(3) J2CPP_DECLARE_METHOD(4) J2CPP_DECLARE_METHOD(5) J2CPP_DECLARE_METHOD(6) J2CPP_DECLARE_METHOD(7) J2CPP_DECLARE_METHOD(8) J2CPP_DECLARE_METHOD(9) explicit InputStream(jobject jobj) : object<InputStream>(jobj) { } operator local_ref<java::lang::Object>() const; operator local_ref<java::io::Closeable>() const; InputStream(); jint available(); void close(); void mark(jint); jboolean markSupported(); jint read(); jint read(local_ref< array<jbyte,1> > const&); jint read(local_ref< array<jbyte,1> > const&, jint, jint); void reset(); jlong skip(jlong); }; //class InputStream } //namespace io } //namespace java } //namespace j2cpp #endif //J2CPP_JAVA_IO_INPUTSTREAM_HPP_DECL #else //J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_IO_INPUTSTREAM_HPP_IMPL #define J2CPP_JAVA_IO_INPUTSTREAM_HPP_IMPL namespace j2cpp { java::io::InputStream::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } java::io::InputStream::operator local_ref<java::io::Closeable>() const { return local_ref<java::io::Closeable>(get_jobject()); } java::io::InputStream::InputStream() : object<java::io::InputStream>( call_new_object< java::io::InputStream::J2CPP_CLASS_NAME, java::io::InputStream::J2CPP_METHOD_NAME(0), java::io::InputStream::J2CPP_METHOD_SIGNATURE(0) >() ) { } jint java::io::InputStream::available() { return call_method< java::io::InputStream::J2CPP_CLASS_NAME, java::io::InputStream::J2CPP_METHOD_NAME(1), java::io::InputStream::J2CPP_METHOD_SIGNATURE(1), jint >(get_jobject()); } void java::io::InputStream::close() { return call_method< java::io::InputStream::J2CPP_CLASS_NAME, java::io::InputStream::J2CPP_METHOD_NAME(2), java::io::InputStream::J2CPP_METHOD_SIGNATURE(2), void >(get_jobject()); } void java::io::InputStream::mark(jint a0) { return call_method< java::io::InputStream::J2CPP_CLASS_NAME, java::io::InputStream::J2CPP_METHOD_NAME(3), java::io::InputStream::J2CPP_METHOD_SIGNATURE(3), void >(get_jobject(), a0); } jboolean java::io::InputStream::markSupported() { return call_method< java::io::InputStream::J2CPP_CLASS_NAME, java::io::InputStream::J2CPP_METHOD_NAME(4), java::io::InputStream::J2CPP_METHOD_SIGNATURE(4), jboolean >(get_jobject()); } jint java::io::InputStream::read() { return call_method< java::io::InputStream::J2CPP_CLASS_NAME, java::io::InputStream::J2CPP_METHOD_NAME(5), java::io::InputStream::J2CPP_METHOD_SIGNATURE(5), jint >(get_jobject()); } jint java::io::InputStream::read(local_ref< array<jbyte,1> > const &a0) { return call_method< java::io::InputStream::J2CPP_CLASS_NAME, java::io::InputStream::J2CPP_METHOD_NAME(6), java::io::InputStream::J2CPP_METHOD_SIGNATURE(6), jint >(get_jobject(), a0); } jint java::io::InputStream::read(local_ref< array<jbyte,1> > const &a0, jint a1, jint a2) { return call_method< java::io::InputStream::J2CPP_CLASS_NAME, java::io::InputStream::J2CPP_METHOD_NAME(7), java::io::InputStream::J2CPP_METHOD_SIGNATURE(7), jint >(get_jobject(), a0, a1, a2); } void java::io::InputStream::reset() { return call_method< java::io::InputStream::J2CPP_CLASS_NAME, java::io::InputStream::J2CPP_METHOD_NAME(8), java::io::InputStream::J2CPP_METHOD_SIGNATURE(8), void >(get_jobject()); } jlong java::io::InputStream::skip(jlong a0) { return call_method< java::io::InputStream::J2CPP_CLASS_NAME, java::io::InputStream::J2CPP_METHOD_NAME(9), java::io::InputStream::J2CPP_METHOD_SIGNATURE(9), jlong >(get_jobject(), a0); } J2CPP_DEFINE_CLASS(java::io::InputStream,"java/io/InputStream") J2CPP_DEFINE_METHOD(java::io::InputStream,0,"<init>","()V") J2CPP_DEFINE_METHOD(java::io::InputStream,1,"available","()I") J2CPP_DEFINE_METHOD(java::io::InputStream,2,"close","()V") J2CPP_DEFINE_METHOD(java::io::InputStream,3,"mark","(I)V") J2CPP_DEFINE_METHOD(java::io::InputStream,4,"markSupported","()Z") J2CPP_DEFINE_METHOD(java::io::InputStream,5,"read","()I") J2CPP_DEFINE_METHOD(java::io::InputStream,6,"read","([B)I") J2CPP_DEFINE_METHOD(java::io::InputStream,7,"read","([BII)I") J2CPP_DEFINE_METHOD(java::io::InputStream,8,"reset","()V") J2CPP_DEFINE_METHOD(java::io::InputStream,9,"skip","(J)J") } //namespace j2cpp #endif //J2CPP_JAVA_IO_INPUTSTREAM_HPP_IMPL #endif //J2CPP_INCLUDE_IMPLEMENTATION
25.694836
90
0.682624
[ "object" ]
d4e257912a588718f0aaba2395d41adb20bfec0e
717
hxx
C++
Packages/java/util/zip/ZipInputStream.hxx
Brandon-T/Aries
4e8c4f5454e8c7c5cd0611b1b38b5be8186f86ca
[ "MIT" ]
null
null
null
Packages/java/util/zip/ZipInputStream.hxx
Brandon-T/Aries
4e8c4f5454e8c7c5cd0611b1b38b5be8186f86ca
[ "MIT" ]
null
null
null
Packages/java/util/zip/ZipInputStream.hxx
Brandon-T/Aries
4e8c4f5454e8c7c5cd0611b1b38b5be8186f86ca
[ "MIT" ]
null
null
null
// // ZipInputStream.hxx // Aries // // Created by Brandon on 2017-08-27. // Copyright © 2017 Brandon. All rights reserved. // #ifndef ZipInputStream_hxx #define ZipInputStream_hxx #include "Object.hxx" #include "InflaterInputStream.hxx" namespace java::util::zip { using java::lang::String; using java::nio::charset::Charset; class ZipInputStream : public InflaterInputStream { public: ZipInputStream(JVM* jvm, InputStream in); ZipInputStream(JVM* jvm, InputStream in, Charset charset); void closeEntry(); ZipEntry getNextEntry(); protected: ZipEntry createZipEntry(String name); }; } #endif /* ZipInputStream_hxx */
20.485714
66
0.656904
[ "object" ]
d4e744899c362e61d52be6079439564fe3e48187
3,729
hpp
C++
component/oai-ausf/src/ausf_app/ausf_app.hpp
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
component/oai-ausf/src/ausf_app/ausf_app.hpp
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
component/oai-ausf/src/ausf_app/ausf_app.hpp
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
/* * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The OpenAirInterface Software Alliance licenses this file to You under * the OAI Public License, Version 1.1 (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.openairinterface.org/?page_id=698 * * 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. *------------------------------------------------------------------------------- * For more information about the OpenAirInterface (OAI) Software Alliance: * contact@openairinterface.org */ /*! \file ausf_app.hpp \brief \author Tien-Thinh NGUYEN \company Eurecom \date 2021 \email: */ #ifndef FILE_AUSF_APP_HPP_SEEN #define FILE_AUSF_APP_HPP_SEEN #include <string> #include "AuthenticationInfo.h" #include "UEAuthenticationCtx.h" #include "ConfirmationData.h" #include "ausf.h" #include <pistache/http.h> #include <map> #include <shared_mutex> namespace oai { namespace ausf { namespace app { using namespace oai::ausf_server::model; class security_context { public: security_context() : xres_star() { // supi = {}; ausf_av_s = {}; supi_ausf = ""; auth_type = ""; serving_nn = ""; kausf_tmp = ""; } // supi64_t supi; AUSF_AV_s ausf_av_s; uint8_t xres_star[16]; // store xres* std::string supi_ausf; // store supi std::string auth_type; // store authType std::string serving_nn; // store serving network name std::string kausf_tmp; // store Kausf(string) }; // class ausf_config; class ausf_app { public: explicit ausf_app(const std::string& config_file); ausf_app(ausf_app const&) = delete; void operator=(ausf_app const&) = delete; virtual ~ausf_app(); void handle_ue_authentications( const AuthenticationInfo& authenticationInfo, nlohmann::json& json_data, std::string& location, Pistache::Http::Code& code, uint8_t http_version = 1); void handle_ue_authentications_confirmation( const std::string& authCtxId, const ConfirmationData& confirmation_data, nlohmann::json& json_data, Pistache::Http::Code& code); bool is_supi_2_security_context(const std::string& supi) const; std::shared_ptr<security_context> supi_2_security_context( const std::string& supi) const; void set_supi_2_security_context( const std::string& supi, std::shared_ptr<security_context> sc); bool is_contextId_2_security_context(const std::string& contextId) const; std::shared_ptr<security_context> contextId_2_security_context( const std::string& contextId) const; void set_contextId_2_security_context( const std::string& contextId, std::shared_ptr<security_context> sc); private: std::map<supi64_t, std::shared_ptr<security_context>> imsi2security_context; mutable std::shared_mutex m_imsi2security_context; std::map<std::string, std::shared_ptr<security_context>> supi2security_context; mutable std::shared_mutex m_supi2security_context; std::map<std::string, std::shared_ptr<security_context>> contextId2security_context; mutable std::shared_mutex m_contextId2security_context; }; } // namespace app } // namespace ausf } // namespace oai #include "ausf_config.hpp" #endif /* FILE_AUSF_APP_HPP_SEEN */
32.146552
81
0.722178
[ "model" ]
d4ebc46aa47da7dc7778f88f69e602ee864d3b02
4,022
cpp
C++
mlir/lib/ExecutionEngine/CRunnerUtils.cpp
val-verde/llvm-project
a5d4e884dad341ff80fbbdec6e7516b9c58c9eb0
[ "Apache-2.0" ]
null
null
null
mlir/lib/ExecutionEngine/CRunnerUtils.cpp
val-verde/llvm-project
a5d4e884dad341ff80fbbdec6e7516b9c58c9eb0
[ "Apache-2.0" ]
null
null
null
mlir/lib/ExecutionEngine/CRunnerUtils.cpp
val-verde/llvm-project
a5d4e884dad341ff80fbbdec6e7516b9c58c9eb0
[ "Apache-2.0" ]
null
null
null
//===- CRunnerUtils.cpp - Utils for MLIR execution ------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements basic functions to manipulate structured MLIR types at // runtime. Entities in this file are meant to be retargetable, including on // targets without a C++ runtime, and must be kept C compatible. // //===----------------------------------------------------------------------===// #include "mlir/ExecutionEngine/CRunnerUtils.h" #ifndef _WIN32 #include <alloca.h> #include <sys/time.h> #else #include "malloc.h" #endif // _WIN32 #include <cinttypes> #include <cstdio> #include <string.h> #ifdef MLIR_CRUNNERUTILS_DEFINE_FUNCTIONS // Small runtime support "lib" for vector.print lowering. // By providing elementary printing methods only, this // library can remain fully unaware of low-level implementation // details of our vectors. Also useful for direct LLVM IR output. extern "C" void printI64(int64_t i) { fprintf(stdout, "%" PRId64, i); } extern "C" void printU64(uint64_t u) { fprintf(stdout, "%" PRIu64, u); } extern "C" void printF32(float f) { fprintf(stdout, "%g", f); } extern "C" void printF64(double d) { fprintf(stdout, "%lg", d); } extern "C" void printOpen() { fputs("( ", stdout); } extern "C" void printClose() { fputs(" )", stdout); } extern "C" void printComma() { fputs(", ", stdout); } extern "C" void printNewline() { fputc('\n', stdout); } extern "C" MLIR_CRUNNERUTILS_EXPORT void memrefCopy(int64_t elemSize, UnrankedMemRefType<char> *srcArg, UnrankedMemRefType<char> *dstArg) { DynamicMemRefType<char> src(*srcArg); DynamicMemRefType<char> dst(*dstArg); int64_t rank = src.rank; int64_t *indices = static_cast<int64_t *>(alloca(sizeof(int64_t) * rank)); int64_t *srcStrides = static_cast<int64_t *>(alloca(sizeof(int64_t) * rank)); int64_t *dstStrides = static_cast<int64_t *>(alloca(sizeof(int64_t) * rank)); char *srcPtr = src.data + src.offset * elemSize; char *dstPtr = dst.data + dst.offset * elemSize; // Initialize index and scale strides. for (int rankp = 0; rankp < rank; ++rankp) { indices[rankp] = 0; srcStrides[rankp] = src.strides[rankp] * elemSize; dstStrides[rankp] = dst.strides[rankp] * elemSize; } int64_t readIndex = 0, writeIndex = 0; for (;;) { // Copy over the element, byte by byte. memcpy(dstPtr + writeIndex, srcPtr + readIndex, elemSize); // Advance index and read position. for (int64_t axis = rank - 1; axis >= 0; --axis) { // Advance at current axis. auto newIndex = ++indices[axis]; readIndex += srcStrides[axis]; writeIndex += dstStrides[axis]; // If this is a valid index, we have our next index, so continue copying. if (src.sizes[axis] != newIndex) break; // We reached the end of this axis. If this is axis 0, we are done. if (axis == 0) return; // Else, reset to 0 and undo the advancement of the linear index that // this axis had. The continue with the axis one outer. indices[axis] = 0; readIndex -= src.sizes[axis] * srcStrides[axis]; writeIndex -= dst.sizes[axis] * dstStrides[axis]; } } } /// Prints GFLOPS rating. extern "C" void print_flops(double flops) { fprintf(stderr, "%lf GFLOPS\n", flops / 1.0E9); } /// Returns the number of seconds since Epoch 1970-01-01 00:00:00 +0000 (UTC). extern "C" double rtclock() { #ifndef _WIN32 struct timeval tp; int stat = gettimeofday(&tp, NULL); if (stat != 0) fprintf(stderr, "Error returning time from gettimeofday: %d\n", stat); return (tp.tv_sec + tp.tv_usec * 1.0e-6); #else fprintf(stderr, "Timing utility not implemented on Windows\n"); return 0.0; #endif // _WIN32 } #endif // MLIR_CRUNNERUTILS_DEFINE_FUNCTIONS
36.899083
80
0.647439
[ "vector" ]
d4ede6a6d53b40fe0413ee1479a0ee077ae15f95
1,094
cpp
C++
p1116ComeonLetsC.cpp
yangyueren/PAT
950d820ec9174c5e2d74adafeb2abde4acdc635f
[ "MIT" ]
1
2020-02-01T08:20:26.000Z
2020-02-01T08:20:26.000Z
p1116ComeonLetsC.cpp
yangyueren/PAT
950d820ec9174c5e2d74adafeb2abde4acdc635f
[ "MIT" ]
null
null
null
p1116ComeonLetsC.cpp
yangyueren/PAT
950d820ec9174c5e2d74adafeb2abde4acdc635f
[ "MIT" ]
null
null
null
// // Created by yryang on 2019/9/14. // #include "iostream" #include "string.h" #include "string" #include "stdlib.h" #include "stdio.h" #include "map" #include "vector" #include "set" #include "math.h" #include "queue" #include "algorithm" using namespace std; int ranky[10005]; int isprime(int n){ if(n<2) return 0; if(n==2) return 1; for (int i = 2; i*i <= n; ++i) { if(n%i ==0) return 0; } return 1; } int main(){ int N; scanf("%d",&N); for (int i = 1; i <= N; ++i) { int a; scanf("%d",&a); ranky[a] = i; } int K; scanf("%d",&K); for (int j = 0; j < K; ++j) { int a; scanf("%d",&a); int award = ranky[a]; if(award == 0) printf("%04d: Are you kidding?\n", a); else if(award == -1) printf("%04d: Checked\n", a); else if(award == 1) printf("%04d: Mystery Award\n", a); else if(isprime(award)) printf("%04d: Minion\n", a); else printf("%04d: Chocolate\n", a); if(ranky[a] != 0){ ranky[a] = -1; } } return 0; }
20.641509
63
0.489945
[ "vector" ]
d4eeb0bc593f565169d6f6412bbf17ff19dd3287
976
hh
C++
Option/LocateBall/locateball.hh
drewnoakes/bold-humanoid
6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335
[ "Apache-2.0" ]
null
null
null
Option/LocateBall/locateball.hh
drewnoakes/bold-humanoid
6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335
[ "Apache-2.0" ]
null
null
null
Option/LocateBall/locateball.hh
drewnoakes/bold-humanoid
6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335
[ "Apache-2.0" ]
null
null
null
#pragma once #include "../../Agent/agent.hh" #include "../LookAtBall/lookatball.hh" #include "../option.hh" namespace bold { class Agent; class HeadModule; class LookAtFeet; class LookAround; /** Controls the head while standing still, in order to find the ball. */ class LocateBall : public Option { public: LocateBall(std::string const& id, Agent* agent, double sideAngle, std::function<double(uint)> speedCallback = nullptr, uint maxCount = 10, uint thresholdCount = 5); std::vector<std::shared_ptr<Option>> runPolicy(rapidjson::Writer<rapidjson::StringBuffer>& writer) override; void reset() override; private: std::shared_ptr<HeadModule> d_headModule; std::shared_ptr<LookAround> d_lookAroundOption; std::shared_ptr<LookAtBall> d_lookAtBallOption; uint d_visibleCount; uint d_stepCount; uint d_maxCount; uint d_thresholdCount; double d_stoppedAtPhase; Clock::Timestamp d_stoppedScanningAt; }; }
26.378378
168
0.719262
[ "vector" ]
d4f1572443975361ca5b2b287187f81734dc43b0
8,398
cpp
C++
mechanics/src/collision/native/test/MultiBodyTest.cpp
ljktest/siconos
85b60e62beca46e6bf06bfbd65670089e86607c7
[ "Apache-2.0" ]
null
null
null
mechanics/src/collision/native/test/MultiBodyTest.cpp
ljktest/siconos
85b60e62beca46e6bf06bfbd65670089e86607c7
[ "Apache-2.0" ]
null
null
null
mechanics/src/collision/native/test/MultiBodyTest.cpp
ljktest/siconos
85b60e62beca46e6bf06bfbd65670089e86607c7
[ "Apache-2.0" ]
1
2015-10-07T19:35:16.000Z
2015-10-07T19:35:16.000Z
/* Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * * Copyright 2018 INRIA. * * 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 "MultiBodyTest.hpp" #pragma GCC diagnostic ignored "-Wmissing-declarations" #ifndef Disks_h #define Disks_h // 2D #define NDOF 3 // WALLS, TOP and GROUND #define WALL 100 #define TOP 100 #define GROUND 0 // DEFAULT PLANS : a ground and two walls to support a crystal // CRYSTAL SIZE #ifndef Ll #define Ll 7 #endif #define Rr 1 #define COSPI6 0.866025403784439 #define SINPI6 0.5 #define TANPI6 0.577350269189626 // tan(pi/6) #define SY 3.73205080756888 // ((cos(a)+1)/(cos(a)*sin(a)) - tan(a)) a=pi/6, R=1 #define SYL 1/TANPI6 // Plan1 #define P1A COSPI6 #define P1B -SINPI6 #define P1C (SY+(Ll-1)*SYL-Rr)*P1B // Plan2 #define P2A COSPI6 #define P2B SINPI6 #define P2C (SY+(Ll-1)*SYL-Rr)*P2B #define GROUND_ID -1 #define MAX_RADIUS INFINITY #include "SiconosBodies.hpp" #include "Disk.hpp" #include "Circle.hpp" #include "DiskPlanR.hpp" #include "SpaceFilter.hpp" class Disks : public SiconosBodies, public std11::enable_shared_from_this<Disks> { public: void init() { assert(false); }; void init(std::string); }; TYPEDEF_SPTR(Disks) #endif //Disks_h // Siconos #include <SiconosKernel.hpp> #include <SiconosPointers.hpp> using namespace std; /* do nothing if solver does not converge */ void localCheckSolverOuput(int info, Simulation*) { if (info) exit(1); } double A(double t) { return 0. ; } double B(double t) { return 1. ; } double C(double t) { return 0.0;//1.1*cos(32.*M_PI*t) ; } double DA(double t) { return 0. ; } double DB(double t) { return 0. ; } double DC(double t) { return 0.0;//-1.1*32.*M_PI*sin(32.*M_PI*t) ; } // ================= Creation of the model ======================= void Disks::init(std::string disks_input) { SP::TimeDiscretisation timedisc_; SP::FrictionContact osnspb_; // User-defined main parameters double t0 = 0; // initial computation time double T = 10; double h = 0.01; // time step double g = 9.81; double theta = 0.5; // theta for MoreauJeanOSI integrator std::string solverName = "NSGS"; // ----------------------------------------- // --- Dynamical systems && interactions --- // ----------------------------------------- double R; double m; try { // ------------ // --- Init --- // ------------ std::cout << "====> nsds loading ..." << std::endl << std::endl; _plans.reset(new SimpleMatrix("plans.dat", true)); if (_plans->size(0) == 0) { /* default plans */ double A1 = P1A; double B1 = P1B; double C1 = P1C; double A2 = P2A; double B2 = P2B; double C2 = P2C; _plans.reset(new SimpleMatrix(6, 6)); _plans->zero(); (*_plans)(0, 0) = 0; (*_plans)(0, 1) = 1; (*_plans)(0, 2) = -GROUND; (*_plans)(1, 0) = 1; (*_plans)(1, 1) = 0; (*_plans)(1, 2) = WALL; (*_plans)(2, 0) = 1; (*_plans)(2, 1) = 0; (*_plans)(2, 2) = -WALL; (*_plans)(3, 0) = 0; (*_plans)(3, 1) = 1; (*_plans)(3, 2) = -TOP; (*_plans)(4, 0) = A1; (*_plans)(4, 1) = B1; (*_plans)(4, 2) = C1; (*_plans)(5, 0) = A2; (*_plans)(5, 1) = B2; (*_plans)(5, 2) = C2; } /* set center positions */ for (unsigned int i = 0 ; i < _plans->size(0); ++i) { SP::DiskPlanR tmpr; tmpr.reset(new DiskPlanR(1, (*_plans)(i, 0), (*_plans)(i, 1), (*_plans)(i, 2), (*_plans)(i, 3), (*_plans)(i, 4), (*_plans)(i, 5))); (*_plans)(i, 3) = tmpr->getXCenter(); (*_plans)(i, 4) = tmpr->getYCenter(); } /* _moving_plans.reset(new FMatrix(1,6)); (*_moving_plans)(0,0) = &A; (*_moving_plans)(0,1) = &B; (*_moving_plans)(0,2) = &C; (*_moving_plans)(0,3) = &DA; (*_moving_plans)(0,4) = &DB; (*_moving_plans)(0,5) = &DC;*/ SP::SiconosMatrix Disks; Disks.reset(new SimpleMatrix(disks_input, true)); // -- OneStepIntegrators -- SP::OneStepIntegrator osi; osi.reset(new MoreauJeanOSI(theta)); // -- Model -- SP::NonSmoothDynamicalSystem nsds; nsds.reset(new NonSmoothDynamicalSystem(t0, T)); for (unsigned int i = 0; i < Disks->size(0); i++) { R = Disks->getValue(i, 2); m = Disks->getValue(i, 3); SP::SiconosVector qTmp; SP::SiconosVector vTmp; qTmp.reset(new SiconosVector(NDOF)); vTmp.reset(new SiconosVector(NDOF)); vTmp->zero(); (*qTmp)(0) = (*Disks)(i, 0); (*qTmp)(1) = (*Disks)(i, 1); SP::LagrangianDS body; if (R > 0) body.reset(new Disk(R, m, qTmp, vTmp)); else body.reset(new Circle(-R, m, qTmp, vTmp)); // -- Set external forces (weight) -- SP::SiconosVector FExt; FExt.reset(new SiconosVector(NDOF)); FExt->zero(); FExt->setValue(1, -m * g); body->setFExtPtr(FExt); // add the dynamical system in the non smooth dynamical system nsds->insertDynamicalSystem(body); } nsds->setSymmetric(true); // ------------------ // --- Simulation --- // ------------------ // -- Time discretisation -- timedisc_.reset(new TimeDiscretisation(t0, h)); // -- OneStepNsProblem -- osnspb_.reset(new FrictionContact(2)); osnspb_->numericsSolverOptions()->iparam[0] = 100; // Max number of // iterations osnspb_->numericsSolverOptions()->iparam[1] = 20; // compute error // iterations osnspb_->numericsSolverOptions()->dparam[0] = 1e-3; // Tolerance osnspb_->setMaxSize(6 * ((3 * Ll * Ll + 3 * Ll) / 2 - Ll)); osnspb_->setMStorageType(1); // Sparse storage osnspb_->setNumericsVerboseMode(0); osnspb_->setKeepLambdaAndYState(true); // inject previous solution // -- Simulation -- _sim.reset(new TimeStepping(nsds,timedisc_)); std11::static_pointer_cast<TimeStepping>(_sim)->setNewtonMaxIteration(3); _sim->insertIntegrator(osi); _sim->insertNonSmoothProblem(osnspb_); std11::static_pointer_cast<TimeStepping>(_sim)->setCheckSolverFunction(localCheckSolverOuput); // --- Simulation initialization --- std::cout << "====> Simulation initialisation ..." << std::endl << std::endl; SP::NonSmoothLaw nslaw(new NewtonImpactFrictionNSL(0, 0, 0.3, 2)); _playground.reset(new SpaceFilter(3, 6, _plans, _moving_plans)); _playground->insertNonSmoothLaw(nslaw, 0, 0); _sim->insertInteractionManager(_playground); } catch (SiconosException e) { std::cout << e.report() << std::endl; exit(1); } catch (...) { std::cout << "Exception caught in Disks::init()" << std::endl; exit(1); } } // test suite registration CPPUNIT_TEST_SUITE_REGISTRATION(MultiBodyTest); void MultiBodyTest::setUp() { } void MultiBodyTest::tearDown() { } // multiples disks void MultiBodyTest::t1() { SP::Disks disks(new Disks()); disks->init("disks.dat"); // just try to run a simulation // if something is broken with SpaceFilter // an exception may occurs for (unsigned int i = 0; i < 20; ++i) { disks->compute(); } CPPUNIT_ASSERT(1); } // one disk without interaction at the beginning void MultiBodyTest::t2() { SP::Disks disks(new Disks()); disks->init("disks-nointer.dat"); // just try to run a simulation // if something is broken with SpaceFilter // an exception may occurs // test fail with rev 3146 for (unsigned int i = 0; i < 20; ++i) { disks->compute(); } CPPUNIT_ASSERT(1); } void MultiBodyTest::t3() { } void MultiBodyTest::t4() { } void MultiBodyTest::t5() { } void MultiBodyTest::t6() { } void MultiBodyTest::t7() { } void MultiBodyTest::t8() { }
20.787129
98
0.592522
[ "model" ]
d4f19b3af91abd06b5d5f65c5942ffde91428ab8
1,637
cxx
C++
src/Cxx/Images/ImageMirrorPad.cxx
ajpmaclean/vtk-examples
1a55fc8c6af67a3c07791807c7d1ec0ab97607a2
[ "Apache-2.0" ]
81
2020-08-10T01:44:30.000Z
2022-03-23T06:46:36.000Z
src/Cxx/Images/ImageMirrorPad.cxx
ajpmaclean/vtk-examples
1a55fc8c6af67a3c07791807c7d1ec0ab97607a2
[ "Apache-2.0" ]
2
2020-09-12T17:33:52.000Z
2021-04-15T17:33:09.000Z
src/Cxx/Images/ImageMirrorPad.cxx
ajpmaclean/vtk-examples
1a55fc8c6af67a3c07791807c7d1ec0ab97607a2
[ "Apache-2.0" ]
27
2020-08-17T07:09:30.000Z
2022-02-15T03:44:58.000Z
#include <vtkImageActor.h> #include <vtkImageCanvasSource2D.h> #include <vtkImageData.h> #include <vtkImageMapper3D.h> #include <vtkImageMirrorPad.h> #include <vtkNamedColors.h> #include <vtkNew.h> #include <vtkProperty.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkRenderer.h> #include <vtkType.h> int main(int, char*[]) { vtkNew<vtkNamedColors> colors; // Create an image vtkNew<vtkImageCanvasSource2D> source; source->SetExtent(0, 20, 0, 20, 0, 0); source->SetScalarTypeToUnsignedChar(); source->SetDrawColor(0.0, 0.0, 0.0, 1.0); source->FillBox(-VTK_INT_MAX, VTK_INT_MAX, -VTK_INT_MAX, VTK_INT_MAX); source->SetDrawColor(255.0, 0.0, 0.0, 0.5); source->DrawCircle(10, 10, 5); source->Update(); vtkNew<vtkImageMirrorPad> mirrorPadFilter; mirrorPadFilter->SetInputConnection(source->GetOutputPort()); mirrorPadFilter->SetOutputWholeExtent(-10, 30, -10, 30, 0, 0); mirrorPadFilter->Update(); // Create an actor vtkNew<vtkImageActor> actor; actor->GetMapper()->SetInputConnection(mirrorPadFilter->GetOutputPort()); // Visualize vtkNew<vtkRenderer> renderer; renderer->AddActor(actor); renderer->ResetCamera(); renderer->SetBackground(colors->GetColor3d("Salmon").GetData()); vtkNew<vtkRenderWindow> renderWindow; renderWindow->AddRenderer(renderer); renderWindow->SetWindowName("ImageMirrorPad"); vtkNew<vtkRenderWindowInteractor> renderWindowInteractor; renderWindowInteractor->SetRenderWindow(renderWindow); renderWindow->Render(); renderWindowInteractor->Initialize(); renderWindowInteractor->Start(); return EXIT_SUCCESS; }
28.719298
75
0.750764
[ "render" ]
d4f4b951c840f93d943e585fd94fbc49986d7384
3,091
cpp
C++
Attic/AtomicEditorReference/Source/Main.cpp
honigbeutler123/AtomicGameEngine
c53425f19b216eb21ecd3bda85052aaa1a6f2aaa
[ "Apache-2.0", "MIT" ]
null
null
null
Attic/AtomicEditorReference/Source/Main.cpp
honigbeutler123/AtomicGameEngine
c53425f19b216eb21ecd3bda85052aaa1a6f2aaa
[ "Apache-2.0", "MIT" ]
null
null
null
Attic/AtomicEditorReference/Source/Main.cpp
honigbeutler123/AtomicGameEngine
c53425f19b216eb21ecd3bda85052aaa1a6f2aaa
[ "Apache-2.0", "MIT" ]
null
null
null
#if defined(WIN32) && !defined(ATOMIC_WIN32_CONSOLE) #include <Atomic/Core/MiniDump.h> #include <windows.h> #ifdef _MSC_VER #include <crtdbg.h> #endif #endif #include <Atomic/Core/ProcessUtils.h> #include <Atomic/IO/Log.h> #include "AEApplication.h" #include "Player/AEPlayerApplication.h" using namespace AtomicEditor; static int RunEditorApplication() { Atomic::SharedPtr<Atomic::Context> context(new Atomic::Context()); Atomic::SharedPtr<AEApplication> application(new AEApplication(context)); return application->Run(); } static int RunPlayerApplication() { Atomic::SharedPtr<Atomic::Context> context(new Atomic::Context()); Atomic::SharedPtr<AEPlayerApplication> application(new AEPlayerApplication(context)); return application->Run(); } // Define a platform-specific main function, which in turn executes the user-defined function // MSVC debug mode: use memory leak reporting #if defined(_MSC_VER) && defined(_DEBUG) && !defined(ATOMIC_WIN32_CONSOLE) int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance, PSTR cmdLine, int showCmd) { _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); Atomic::ParseArguments(GetCommandLineW()); const Vector<String>& arguments = GetArguments(); bool runPlayer = false; for (unsigned i = 0; i < arguments.Size();i++) { if (arguments.At(i) == "--player") { runPlayer = true; break; } } if (runPlayer) return RunPlayerApplication(); return RunEditorApplication(); } // MSVC release mode: write minidump on crash #elif defined(_MSC_VER) && defined(ATOMIC_MINIDUMPS) && !defined(ATOMIC_WIN32_CONSOLE) int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance, PSTR cmdLine, int showCmd) { Atomic::ParseArguments(GetCommandLineW()); int exitCode; __try { exitCode = function; } __except(Atomic::WriteMiniDump("Atomic", GetExceptionInformation())) { } return exitCode; } // Other Win32 or minidumps disabled: just execute the function #elif defined(WIN32) && !defined(ATOMIC_WIN32_CONSOLE) int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance, PSTR cmdLine, int showCmd) { Atomic::ParseArguments(GetCommandLineW()); const Vector<String>& arguments = GetArguments(); bool runPlayer = false; for (unsigned i = 0; i < arguments.Size();i++) { if (arguments.At(i) == "--player") { runPlayer = true; break; } } if (runPlayer) return RunPlayerApplication(); return RunEditorApplication(); } // Linux or OS X: use main #else int main(int argc, char** argv) { Atomic::ParseArguments(argc, argv); const Vector<String>& arguments = GetArguments(); bool runPlayer = false; for (unsigned i = 0; i < arguments.Size();i++) { if (arguments.At(i) == "--player") { runPlayer = true; break; } } if (runPlayer) return RunPlayerApplication(); return RunEditorApplication(); } #endif
25.130081
93
0.67001
[ "vector" ]
d4f870967c3a724c35313a43dd9fef6ad9f1b5ad
6,307
hpp
C++
libs/core/algorithms/tests/unit/algorithms/adjacentfind_tests.hpp
bhumitattarde/hpx
5b34d8d77b1664fa552445d44cd98e51dc69a74a
[ "BSL-1.0" ]
1
2022-02-08T05:55:09.000Z
2022-02-08T05:55:09.000Z
libs/core/algorithms/tests/unit/algorithms/adjacentfind_tests.hpp
deepaksuresh1411/hpx
aa18024d35fe9884a977d4b6076c764dbb8b26d1
[ "BSL-1.0" ]
null
null
null
libs/core/algorithms/tests/unit/algorithms/adjacentfind_tests.hpp
deepaksuresh1411/hpx
aa18024d35fe9884a977d4b6076c764dbb8b26d1
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2014 Grant Mercer // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #pragma once #include <hpx/local/init.hpp> #include <hpx/modules/testing.hpp> #include <hpx/parallel/algorithms/adjacent_find.hpp> #include <cstddef> #include <iostream> #include <iterator> #include <numeric> #include <random> #include <string> #include <vector> #include "test_utils.hpp" //////////////////////////////////////////////////////////////////////////// unsigned int seed = std::random_device{}(); std::mt19937 gen(seed); std::uniform_int_distribution<> dis(2, 101); std::uniform_int_distribution<> dist(2, 10005); template <typename ExPolicy, typename IteratorTag> void test_adjacent_find(ExPolicy policy, IteratorTag) { static_assert(hpx::is_execution_policy<ExPolicy>::value, "hpx::is_execution_policy<ExPolicy>::value"); typedef std::vector<int>::iterator base_iterator; typedef test::test_iterator<base_iterator, IteratorTag> iterator; // fill vector with random values about 1 std::vector<int> c(10007); std::iota(std::begin(c), std::end(c), dis(gen)); std::size_t random_pos = dist(gen); //-V101 c[random_pos] = 1; c[random_pos + 1] = 1; iterator index = hpx::adjacent_find( policy, iterator(std::begin(c)), iterator(std::end(c))); base_iterator test_index = std::begin(c) + random_pos; HPX_TEST(index == iterator(test_index)); } template <typename ExPolicy, typename IteratorTag> void test_adjacent_find_async(ExPolicy p, IteratorTag) { typedef std::vector<int>::iterator base_iterator; typedef test::test_iterator<base_iterator, IteratorTag> iterator; // fill vector with random values above 1 std::vector<int> c(10007); std::iota(std::begin(c), std::end(c), dis(gen)); std::size_t random_pos = dist(gen); //-V101 c[random_pos] = 1; c[random_pos + 1] = 1; hpx::future<iterator> f = hpx::adjacent_find(p, iterator(std::begin(c)), iterator(std::end(c))); f.wait(); // create iterator at position of value to be found base_iterator test_index = std::begin(c) + random_pos; HPX_TEST(f.get() == iterator(test_index)); } //////////////////////////////////////////////////////////////////////////// template <typename ExPolicy, typename IteratorTag> void test_adjacent_find_exception(ExPolicy policy, IteratorTag) { static_assert(hpx::is_execution_policy<ExPolicy>::value, "hpx::is_execution_policy<ExPolicy>::value"); typedef std::vector<int>::iterator base_iterator; typedef test::decorated_iterator<base_iterator, IteratorTag> decorated_iterator; std::vector<int> c(10007); std::iota(std::begin(c), std::end(c), gen() + 1); bool caught_exception = false; try { hpx::adjacent_find(policy, decorated_iterator( std::begin(c), []() { throw std::runtime_error("test"); }), decorated_iterator(std::end(c))); HPX_TEST(false); } catch (hpx::exception_list const& e) { caught_exception = true; test::test_num_exceptions<ExPolicy, IteratorTag>::call(policy, e); } catch (...) { HPX_TEST(false); } HPX_TEST(caught_exception); } template <typename ExPolicy, typename IteratorTag> void test_adjacent_find_exception_async(ExPolicy p, IteratorTag) { typedef std::vector<int>::iterator base_iterator; typedef test::decorated_iterator<base_iterator, IteratorTag> decorated_iterator; std::vector<int> c(10007); std::iota(std::begin(c), std::end(c), gen() + 1); bool caught_exception = false; bool returned_from_algorithm = false; try { hpx::future<decorated_iterator> f = hpx::adjacent_find(p, decorated_iterator( std::begin(c), []() { throw std::runtime_error("test"); }), decorated_iterator(std::end(c))); returned_from_algorithm = true; f.get(); HPX_TEST(false); } catch (hpx::exception_list const& e) { caught_exception = true; test::test_num_exceptions<ExPolicy, IteratorTag>::call(p, e); } catch (...) { HPX_TEST(false); } HPX_TEST(caught_exception); HPX_TEST(returned_from_algorithm); } //////////////////////////////////////////////////////////////////////////// template <typename ExPolicy, typename IteratorTag> void test_adjacent_find_bad_alloc(ExPolicy policy, IteratorTag) { static_assert(hpx::is_execution_policy<ExPolicy>::value, "hpx::is_execution_policy<ExPolicy>::value"); typedef std::vector<int>::iterator base_iterator; typedef test::decorated_iterator<base_iterator, IteratorTag> decorated_iterator; std::vector<int> c(10007); std::iota(std::begin(c), std::end(c), gen() + 1); bool caught_bad_alloc = false; try { hpx::adjacent_find(policy, decorated_iterator(std::begin(c), []() { throw std::bad_alloc(); }), decorated_iterator(std::end(c))); HPX_TEST(false); } catch (std::bad_alloc const&) { caught_bad_alloc = true; } catch (...) { HPX_TEST(false); } HPX_TEST(caught_bad_alloc); } template <typename ExPolicy, typename IteratorTag> void test_adjacent_find_bad_alloc_async(ExPolicy p, IteratorTag) { typedef std::vector<int>::iterator base_iterator; typedef test::decorated_iterator<base_iterator, IteratorTag> decorated_iterator; std::vector<int> c(10007); std::iota(std::begin(c), std::end(c), gen() + 1); bool caught_bad_alloc = false; bool returned_from_algorithm = false; try { hpx::future<decorated_iterator> f = hpx::adjacent_find(p, decorated_iterator(std::begin(c), []() { throw std::bad_alloc(); }), decorated_iterator(std::end(c))); returned_from_algorithm = true; f.get(); HPX_TEST(false); } catch (std::bad_alloc const&) { caught_bad_alloc = true; } catch (...) { HPX_TEST(false); } HPX_TEST(caught_bad_alloc); HPX_TEST(returned_from_algorithm); }
27.90708
80
0.630252
[ "vector" ]
d4fd795d5e9c40b198e839a845af39879620e6a8
29,987
cpp
C++
tests/genFuncs.cpp
kali-allison/SCycle
0a81edfae8730acb44531e2c2b3f51f25ea193d2
[ "MIT" ]
14
2019-04-12T16:36:36.000Z
2022-03-16T00:35:03.000Z
tests/genFuncs.cpp
kali-allison/SCycle
0a81edfae8730acb44531e2c2b3f51f25ea193d2
[ "MIT" ]
null
null
null
tests/genFuncs.cpp
kali-allison/SCycle
0a81edfae8730acb44531e2c2b3f51f25ea193d2
[ "MIT" ]
6
2019-07-22T23:53:15.000Z
2022-03-10T03:30:50.000Z
#include "genFuncs.hpp" using namespace std; // check if file exists bool doesFileExist(const string fileName) { ifstream infile(fileName.c_str()); return infile.good(); }; // clean up a C++ std library vector of PETSc Vecs void destroyVector(vector<Vec>& vec) { for(vector<Vec>::size_type i = 0; i != vec.capacity(); i++) { VecDestroy(&vec[i]); } } void destroyVector(map<string,Vec>& vec) { for (map<string,Vec>::iterator it = vec.begin(); it!=vec.end(); it++ ) { VecDestroy(&vec[it->first]); } } // Print out a vector with 15 significant figures. void printVec(Vec vec) { PetscInt Ii,Istart,Iend; PetscScalar v; VecGetOwnershipRange(vec,&Istart,&Iend); for (Ii = Istart;Ii < Iend;Ii++) { VecGetValues(vec,1,&Ii,&v); PetscPrintf(PETSC_COMM_WORLD,"%.15e\n",v); } PetscPrintf(PETSC_COMM_WORLD,"\n"); } // Print out (vec1 - vec2) with 15 significant figures. void printVecsDiff(Vec vec1,Vec vec2) { PetscInt Ii,Istart,Iend; PetscScalar v1,v2,v; VecGetOwnershipRange(vec1,&Istart,&Iend); for (Ii = Istart;Ii < Iend;Ii++) { VecGetValues(vec1,1,&Ii,&v1); VecGetValues(vec2,1,&Ii,&v2); v = v1 - v2; PetscPrintf(PETSC_COMM_WORLD,"%.15e\n",v); } } // Print out (vec1 + vec2) with 15 significant figures. void printVecsSum(Vec vec1,Vec vec2) { PetscInt Ii,Istart,Iend; PetscScalar v1,v2,v; VecGetOwnershipRange(vec1,&Istart,&Iend); for (Ii = Istart;Ii < Iend;Ii++) { VecGetValues(vec1,1,&Ii,&v1); VecGetValues(vec2,1,&Ii,&v2); v = v1 + v2; PetscPrintf(PETSC_COMM_WORLD,"%.15e\n",v); } } // write a single vector to file in binary format PetscErrorCode writeVec(Vec vec, const string filename) { PetscErrorCode ierr = 0; PetscViewer viewer; PetscViewerBinaryOpen(PETSC_COMM_WORLD,filename.c_str(),FILE_MODE_WRITE,&viewer); ierr = VecView(vec,viewer); CHKERRQ(ierr); ierr = PetscViewerDestroy(&viewer); CHKERRQ(ierr); return ierr; } // append a single vector to file in binary format PetscErrorCode writeVecAppend(Vec vec,const string filename) { PetscErrorCode ierr = 0; PetscViewer viewer; PetscViewerBinaryOpen(PETSC_COMM_WORLD,filename.c_str(),FILE_MODE_APPEND,&viewer); ierr = VecView(vec,viewer);CHKERRQ(ierr); ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr); return ierr; } // Write matrix to file in binary format PetscErrorCode writeMat(Mat mat, string filename) { PetscErrorCode ierr = 0; PetscViewer viewer; ierr = PetscViewerBinaryOpen(PETSC_COMM_WORLD,filename.c_str(),FILE_MODE_WRITE,&viewer);CHKERRQ(ierr); ierr = MatView(mat,viewer);CHKERRQ(ierr); ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr); return ierr; } // initiate PetscViewer PetscViewer initiateViewer(string filename) { PetscViewer vw; PetscViewerBinaryOpen(PETSC_COMM_WORLD,filename.c_str(),FILE_MODE_WRITE,&vw); return vw; } // sappend PetscViewer(s) PetscErrorCode appendViewer(PetscViewer& vw,const string filename) { PetscErrorCode ierr = 0; ierr = PetscViewerDestroy(&vw); CHKERRQ(ierr); ierr = PetscViewerBinaryOpen(PETSC_COMM_WORLD,filename.c_str(),FILE_MODE_APPEND,&vw); CHKERRQ(ierr); return ierr; } PetscErrorCode appendViewers(map<string,PetscViewer>& vwL,const string dir) { PetscErrorCode ierr = 0; for (map<string,PetscViewer>::iterator it=vwL.begin(); it!=vwL.end(); it++ ) { ierr = PetscViewerDestroy(&vwL[it->first]); CHKERRQ(ierr); ierr = PetscViewerBinaryOpen(PETSC_COMM_WORLD,(dir + it->first).c_str(),FILE_MODE_APPEND,&vwL[it->first]); CHKERRQ(ierr); } return ierr; } /* Print all entries of 2D DMDA global vector to stdout, including which * processor each entry lives on, and the corresponding subscripting indices */ PetscErrorCode printf_DM_2d(const Vec gvec, const DM dm) { PetscErrorCode ierr = 0; #if VERBOSE > 2 PetscPrintf(PETSC_COMM_WORLD,"Starting main::printf_DM_2d in fault.cpp.\n"); #endif PetscMPIInt rank; MPI_Comm_rank(PETSC_COMM_WORLD,&rank); PetscInt i,j,mStart,m,nStart,n; // for for loops below DMDAGetCorners(dm,&mStart,&nStart,0,&m,&n,0); PetscScalar **gxArr; DMDAVecGetArray(dm,gvec,&gxArr); for (j=nStart;j<nStart+n;j++) { for (i=mStart;i<mStart+m;i++) { PetscPrintf(PETSC_COMM_SELF,"%i: gxArr[%i][%i] = %g\n", rank,j,i,gxArr[j][i]); } } DMDAVecRestoreArray(dm,gvec,&gxArr); #if VERBOSE > 2 PetscPrintf(PETSC_COMM_WORLD,"Ending main::printf_DM_2d in fault.cpp.\n"); #endif return ierr; } // computes || vec1 - vec2||_mat (matrix norm of vec1 - vec2) double computeNormDiff_Mat(const Mat& mat,const Vec& vec1,const Vec& vec2) { PetscErrorCode ierr = 0; Vec diff; ierr = VecDuplicate(vec1,&diff);CHKERRQ(ierr); ierr = VecWAXPY(diff,-1.0,vec1,vec2);CHKERRQ(ierr); PetscScalar diffErr = computeNorm_Mat(mat,diff); PetscScalar vecErr = computeNorm_Mat(mat,vec1); PetscScalar err = diffErr/vecErr; VecDestroy(&diff); return err; } // computes || vec ||_mat double computeNorm_Mat(const Mat& mat,const Vec& vec) { PetscErrorCode ierr = 0; Vec Matxvec; ierr = VecDuplicate(vec,&Matxvec);CHKERRQ(ierr); ierr = MatMult(mat,vec,Matxvec);CHKERRQ(ierr); PetscScalar err; ierr = VecDot(vec,Matxvec,&err);CHKERRQ(ierr); VecDestroy(&Matxvec); return err; } // computes || vec1 - vec2 ||_2 / sqrt(length(vec1)) double computeNormDiff_2(const Vec& vec1,const Vec& vec2) { PetscErrorCode ierr = 0; Vec diff; ierr = VecDuplicate(vec1,&diff);CHKERRQ(ierr); ierr = VecWAXPY(diff,-1.0,vec1,vec2);CHKERRQ(ierr); PetscScalar err; ierr = VecNorm(diff,NORM_2,&err);CHKERRQ(ierr); PetscInt len; ierr = VecGetSize(vec1,&len);CHKERRQ(ierr); err = err/sqrt(len); VecDestroy(&diff); return err; } // computes || vec1 - vec2 ||_2 / || vec1 ||_2 double computeNormDiff_L2_scaleL2(const Vec& vec1,const Vec& vec2) { PetscErrorCode ierr = 0; Vec diff; ierr = VecDuplicate(vec1,&diff);CHKERRQ(ierr); ierr = VecWAXPY(diff,-1.0,vec1,vec2);CHKERRQ(ierr); PetscScalar err; ierr = VecNorm(diff,NORM_2,&err);CHKERRQ(ierr); PetscScalar len; ierr = VecNorm(vec1,NORM_2,&len);CHKERRQ(ierr); err = err/len; VecDestroy(&diff); return err; } // out = vecL' x A x vecR double multVecMatsVec(const Vec& vecL, const Mat& A, const Vec& vecR) { PetscErrorCode ierr = 0; double out = 0; Vec temp; VecDuplicate(vecL,&temp); ierr = MatMult(A,vecR,temp); CHKERRQ(ierr); ierr = VecDot(vecL,temp,&out); CHKERRQ(ierr); VecDestroy(&temp); return out; } // out = vecL' x A x B x vecR double multVecMatsVec(const Vec& vecL, const Mat& A, const Mat& B, const Vec& vecR) { PetscErrorCode ierr = 0; double out = 0; Mat AB; MatMatMult(A,B,MAT_INITIAL_MATRIX,1.0,&AB); Vec temp; VecDuplicate(vecL,&temp); ierr = MatMult(AB,vecR,temp); CHKERRQ(ierr); ierr = VecDot(vecL,temp,&out); CHKERRQ(ierr); VecDestroy(&temp); MatDestroy(&AB); return out; } // out = vecL' x A x B x C x vecR double multVecMatsVec(const Vec& vecL, const Mat& A, const Mat& B, const Mat& C, const Vec& vecR) { PetscErrorCode ierr = 0; double out = 0; Mat ABC; MatMatMatMult(A,B,C,MAT_INITIAL_MATRIX,PETSC_DEFAULT,&ABC); Vec temp; VecDuplicate(vecL,&temp); ierr = MatMult(ABC,vecR,temp); CHKERRQ(ierr); ierr = VecDot(vecL,temp,&out); CHKERRQ(ierr); VecDestroy(&temp); MatDestroy(&ABC); return out; } // out = vecL' x A x B x C x vecR double multVecMatsVec(const Vec& vecL, const Mat& A, const Mat& B, const Mat& C, const Mat& D, const Vec& vecR) { PetscErrorCode ierr = 0; double out = 0; Mat ABC,ABCD; MatMatMatMult(A,B,C,MAT_INITIAL_MATRIX,PETSC_DEFAULT,&ABC); MatMatMult(ABC,D,MAT_INITIAL_MATRIX,1.0,&ABCD); MatDestroy(&ABC); Vec temp; VecDuplicate(vecL,&temp); ierr = MatMult(ABCD,vecR,temp); CHKERRQ(ierr); ierr = VecDot(vecL,temp,&out); CHKERRQ(ierr); VecDestroy(&temp); MatDestroy(&ABCD); return out; } // out = A x B x vecR; assumes vecR is DIFFERENT from out PetscErrorCode multMatsVec(Vec& out, const Mat& A, const Mat& B, const Vec& vecR) { PetscErrorCode ierr = 0; Vec BvecR; VecDuplicate(vecR,&BvecR); ierr = MatMult(B,vecR,BvecR); CHKERRQ(ierr); ierr = MatMult(A,BvecR,out); CHKERRQ(ierr); ierr = VecDestroy(&BvecR); return ierr; } // out = A x B x vecR; assumes vecR is IDENTICAL to out PetscErrorCode multMatsVec(const Mat& A, const Mat& B, Vec& vecR) { PetscErrorCode ierr = 0; Vec BvecR; VecDuplicate(vecR,&BvecR); ierr = MatMult(B,vecR,BvecR); CHKERRQ(ierr); ierr = MatMult(A,BvecR,vecR); CHKERRQ(ierr); ierr = VecDestroy(&BvecR); return ierr; } // log10(out) = a*log10(vec1) + b*log10(vec2) // out may not be the same as vec1 or vec2 PetscErrorCode MyVecLog10AXPBY(Vec& out,const double a, const Vec& vec1, const double b, const Vec& vec2) { if (out == NULL) { VecDuplicate(vec1,&out); } // compute effective viscosity PetscScalar *outA; PetscScalar const *vec1A,*vec2A; PetscInt Ii,Istart,Iend,Jj = 0; VecGetOwnershipRange(vec1,&Istart,&Iend); VecGetArrayRead(vec1,&vec1A); VecGetArrayRead(vec2,&vec2A); VecGetArray(out,&outA); for (Ii = Istart;Ii < Iend;Ii++) { PetscScalar log10Out = a*log10(vec1A[Jj]) + b*log10(vec2A[Jj]); outA[Jj] = pow(10.,log10Out); Jj++; } VecRestoreArrayRead(vec1,&vec1A); VecRestoreArrayRead(vec2,&vec2A); VecRestoreArray(out,&outA); return 0; } // loads a PETSc Vec from a binary file // Note: memory for out MUST be allocated before calling this function PetscErrorCode loadVecFromInputFile(Vec& out,const string inputDir, const string fieldName) { PetscErrorCode ierr = 0; bool fileExists = 0; ierr = loadVecFromInputFile(out,inputDir,fieldName,fileExists); CHKERRQ(ierr); return ierr; } // loads a PETSc Vec from a binary file // Note: memory for out MUST be allocated before calling this function PetscErrorCode loadVecFromInputFile(Vec& out,const string inputDir, const string fieldName, bool& fileExists) { PetscErrorCode ierr = 0; #if VERBOSE > 1 string funcName = "loadFieldsFromFiles"; string fileName = "genFuncs.cpp"; ierr = PetscPrintf(PETSC_COMM_WORLD,"Starting %s in %s.\n",funcName.c_str(),fileName.c_str());CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD," Attempting to load: %s%s\n",inputDir.c_str(),fieldName.c_str());CHKERRQ(ierr); #endif string vecSourceFile = inputDir + fieldName; fileExists = doesFileExist(vecSourceFile); if (fileExists) { PetscPrintf(PETSC_COMM_WORLD,"Note: Loading Vec from file: %s\n",vecSourceFile.c_str()); PetscViewer inv; ierr = PetscViewerBinaryOpen(PETSC_COMM_WORLD,vecSourceFile.c_str(),FILE_MODE_READ,&inv);CHKERRQ(ierr); ierr = PetscViewerPushFormat(inv,PETSC_VIEWER_BINARY_MATLAB);CHKERRQ(ierr); ierr = VecLoad(out,inv);CHKERRQ(ierr); PetscViewerPopFormat(inv); PetscViewerDestroy(&inv); } else { PetscPrintf(PETSC_COMM_WORLD,"Warning: File not found: %s\n",vecSourceFile.c_str()); } #if VERBOSE > 1 ierr = PetscPrintf(PETSC_COMM_WORLD,"Ending %s in %s.\n",funcName.c_str(),fileName.c_str());CHKERRQ(ierr); #endif return ierr; } // loads a std library vector from a list in the input file PetscErrorCode loadVectorFromInputFile(const string& str,vector<double>& vec) { PetscErrorCode ierr = 0; #if VERBOSE > 1 ierr = PetscPrintf(PETSC_COMM_WORLD,"Starting loadVectorFromInputFile in genFuncs.cpp.\n");CHKERRQ(ierr); #endif size_t pos = 0; // position of delimiter in string string delim = " "; // delimiter between values in list (whitespace sensitive) string remstr; // holds remaining string as str is parsed through double val; // holds values // holds remainder as str is parsed through (with beginning and ending brackets removed) pos = str.find("]"); remstr = str.substr(1,pos-1); pos = remstr.find(delim); while (pos != remstr.npos) { pos = remstr.find(delim); val = atof( remstr.substr(0,pos).c_str() ); remstr = remstr.substr(pos + delim.length()); vec.push_back(val); } #if VERBOSE > 1 ierr = PetscPrintf(PETSC_COMM_WORLD,"Ending loadVectorFromInputFile in genFuncs.cpp.\n");CHKERRQ(ierr); #endif return ierr; } // load vector from input file PetscErrorCode loadVectorFromInputFile(const string& str,vector<int>& vec) { PetscErrorCode ierr = 0; #if VERBOSE > 1 ierr = PetscPrintf(PETSC_COMM_WORLD,"Starting Domain::loadVectorFromInputFile in domain.cpp.\n");CHKERRQ(ierr); #endif size_t pos = 0; // position of delimiter in string string delim = " "; // delimiter between values in list (whitespace sensitive) string remstr; // holds remaining string as str is parsed through int val; // holds values // holds remainder as str is parsed through (with beginning and ending brackets removed) pos = str.find("]"); remstr = str.substr(1,pos-1); pos = remstr.find(delim); val = atoi( remstr.substr(0,pos).c_str() ); vec.push_back(val); remstr = remstr.substr(pos + delim.length()); while (pos != remstr.npos) { pos = remstr.find(delim); val = atoi( remstr.substr(0,pos).c_str() ); remstr = remstr.substr(pos + delim.length()); vec.push_back(val); } #if VERBOSE > 1 ierr = PetscPrintf(PETSC_COMM_WORLD,"Ending Domain::loadVectorFromInputFile in domain.cpp.\n");CHKERRQ(ierr); #endif return ierr; } // loads a vector of strings PetscErrorCode loadVectorFromInputFile(const string& str,vector<string>& vec) { PetscErrorCode ierr = 0; #if VERBOSE > 1 ierr = PetscPrintf(PETSC_COMM_WORLD,"Starting Domain::loadVectorFromInputFile in domain.cpp.\n");CHKERRQ(ierr); #endif size_t pos = 0; // position of delimiter in string string delim = " "; // delimiter between values in list (whitespace sensitive) string remstr; // holds remaining string as str is parsed through string val; // holds values // holds remainder as str is parsed through (with beginning and ending brackets removed) pos = str.find("]"); remstr = str.substr(1,pos-1); pos = remstr.find(delim); val = remstr.substr(0,pos).c_str(); vec.push_back(val); remstr = remstr.substr(pos + delim.length()); while (pos != remstr.npos) { pos = remstr.find(delim); val = remstr.substr(0,pos).c_str(); remstr = remstr.substr(pos + delim.length()); vec.push_back(val); } #if VERBOSE > 1 ierr = PetscPrintf(PETSC_COMM_WORLD,"Ending Domain::loadVectorFromInputFile in domain.cpp.\n");CHKERRQ(ierr); #endif return ierr; } // creates a string containing the contents of C++ std library vector string vector2str(const vector<double> vec) { ostringstream ss; for (vector<double>::const_iterator Ii=vec.begin(); Ii != vec.end(); Ii++) { ss << " " << *Ii; } string str = "[" + ss.str() + "]"; return str; } // creates a string containing the contents of C++ std library vector string vector2str(const vector<int> vec) { ostringstream ss; for (vector<int>::const_iterator Ii=vec.begin(); Ii != vec.end(); Ii++) { ss << " " << *Ii; } string str = "[" + ss.str() + "]"; return str; } // creates a string containing the contents of C++ std library vector string vector2str(const vector<string> vec) { ostringstream ss; for (vector<string>::const_iterator Ii=vec.begin(); Ii != vec.end(); Ii++) { ss << " " << *Ii; } string str = "[" + ss.str() + "]"; return str; } // prints an array to a single line in std out PetscErrorCode printArray(const PetscScalar * arr,const PetscScalar len) { PetscErrorCode ierr = 0; string funcName = "genFuncs::printArray"; string fileName = "genFuncs.cpp"; #if VERBOSE > 1 ierr = PetscPrintf(PETSC_COMM_WORLD,"Starting %s in %s\n",funcName.c_str(),fileName.c_str()); CHKERRQ(ierr); #endif cout << "["; for(int i=0; i<len; i++) { cout << arr[i] << ","; } cout << "]" << endl; #if VERBOSE > 1 ierr = PetscPrintf(PETSC_COMM_WORLD,"Ending %s in %s\n",funcName.c_str(),fileName.c_str()); CHKERRQ(ierr); #endif return ierr; } double MMS_test(const double y,const double z) { return y*10.0 + z; } double MMS_test(const double z) { return z; } // Fills vec with the linear interpolation between the pairs of points (vals,depths). PetscErrorCode setVec(Vec& vec, const Vec& coord, vector<double>& vals,vector<double>& depths) { PetscErrorCode ierr = 0; PetscInt Istart,Iend,N; PetscScalar v,z,z0,z1,v0,v1; VecSet(vec,vals[0]); VecGetSize(coord,&N); // no interpolation to be done if (N == 1) { return ierr; } // build structure from generalized input size_t vecLen = depths.size(); ierr = VecGetOwnershipRange(vec,&Istart,&Iend);CHKERRQ(ierr); PetscScalar *vecA; const PetscScalar *coordA; PetscInt Ii, Jj = 0; VecGetArray(vec,&vecA); VecGetArrayRead(coord,&coordA); for (Ii = Istart;Ii < Iend;Ii++) { z = coordA[Jj]; for (size_t ind = 0; ind < vecLen - 1; ind++) { z0 = depths[0+ind]; z1 = depths[0+ind+1]; v0 = vals[0+ind]; v1 = vals[0+ind+1]; if (z >= z0 && z <= z1) { v = (v1 - v0)/(z1 - z0) * (z - z0) + v0; vecA[Jj] = v; } else if (z > z1 && ind == vecLen - 2) { v = (v1 - v0)/(z1 - z0) * (z - z0) + v0; vecA[Jj] = v; } } Jj++; } VecRestoreArray(vec,&vecA); VecRestoreArrayRead(coord,&coordA); return ierr; } PetscErrorCode mapToVec(Vec& vec, double(*func)(double,double), const Vec& yV, const double t) { PetscErrorCode ierr = 0; PetscScalar const *y; PetscScalar *v; PetscInt Ii,Istart,Iend; ierr = VecGetOwnershipRange(vec,&Istart,&Iend); CHKERRQ(ierr); ierr = VecGetArrayRead(yV,&y); ierr = VecGetArray(vec,&v); PetscInt Jj = 0; for (Ii = Istart; Ii < Iend; Ii++) { v[Jj] = func(y[Jj],t); Jj++; } VecRestoreArrayRead(yV,&y); VecRestoreArray(vec,&v); return ierr; } PetscErrorCode mapToVec(Vec& vec, double(*func)(double),const Vec& yV) { PetscErrorCode ierr = 0; PetscScalar const *y; PetscScalar *v; PetscInt Ii,Istart,Iend; ierr = VecGetOwnershipRange(vec,&Istart,&Iend); CHKERRQ(ierr); ierr = VecGetArrayRead(yV,&y); ierr = VecGetArray(vec,&v); PetscInt Jj = 0; for (Ii = Istart; Ii < Iend; Ii++) { v[Jj] = func(y[Jj]); Jj++; } VecRestoreArrayRead(yV,&y); VecRestoreArray(vec,&v); return ierr; } PetscErrorCode mapToVec(Vec& vec, double(*func)(double,double,double), const Vec& yV,const Vec& zV, const double t) { PetscErrorCode ierr = 0; PetscScalar const *y,*z; PetscScalar *v; PetscInt Ii,Istart,Iend; ierr = VecGetOwnershipRange(vec,&Istart,&Iend); CHKERRQ(ierr); ierr = VecGetArrayRead(yV,&y); ierr = VecGetArrayRead(zV,&z); ierr = VecGetArray(vec,&v); PetscInt Jj = 0; for (Ii = Istart; Ii < Iend; Ii++) { v[Jj] = func(y[Jj],z[Jj],t); Jj++; } VecRestoreArrayRead(yV,&y); VecRestoreArrayRead(zV,&z); VecRestoreArray(vec,&v); return ierr; } PetscErrorCode mapToVec(Vec& vec, double(*func)(double,double), const Vec& yV,const Vec& zV) { PetscErrorCode ierr = 0; PetscScalar const *y,*z; PetscScalar *v; PetscInt Ii,Istart,Iend; ierr = VecGetOwnershipRange(vec,&Istart,&Iend); CHKERRQ(ierr); ierr = VecGetArrayRead(yV,&y); ierr = VecGetArrayRead(zV,&z); ierr = VecGetArray(vec,&v); PetscInt Jj = 0; for (Ii = Istart; Ii < Iend; Ii++) { v[Jj] = func(y[Jj],z[Jj]); Jj++; } VecRestoreArrayRead(yV,&y); VecRestoreArrayRead(zV,&z); VecRestoreArray(vec,&v); return ierr; } // Map a function that acts on scalars to a 2D DMDA Vec PetscErrorCode mapToVec(Vec& vec, double(*func)(double,double), const int N, const double dy, const double dz,DM da) { // assumes vec has already been created and it's size has been allocated PetscErrorCode ierr = 0; PetscInt zS,yS,zn,yn; DMDAGetCorners(da, &zS, &yS, 0, &zn, &yn, 0); PetscInt zE = zS + zn; PetscInt yE = yS + yn; PetscScalar** arr; ierr = DMDAVecGetArray(da, vec, &arr);CHKERRQ(ierr); PetscInt yI,zI; PetscScalar y,z; for (yI = yS; yI < yE; yI++) { for (zI = zS; zI < zE; zI++) { y = yI * dy; z = zI * dz; arr[yI][zI] = func(y,z); } } ierr = DMDAVecRestoreArray(da, vec, &arr);CHKERRQ(ierr); VecAssemblyBegin(vec); VecAssemblyEnd(vec); return ierr; } // Map a function that acts on scalars to a 1DD DMDA Vec PetscErrorCode mapToVec(Vec& vec, double(*func)(double), const int N, const double dz,DM da) { // assumes vec has already been created and it's size has been allocated PetscErrorCode ierr = 0; PetscInt zS,zn; DMDAGetCorners(da, &zS, 0, 0, &zn, 0, 0); PetscInt zE = zS + zn; PetscScalar* arr; ierr = DMDAVecGetArray(da, vec, &arr);CHKERRQ(ierr); PetscInt zI; PetscScalar z; for (zI = zS; zI < zE; zI++) { z = zI * dz; arr[zI] = func(z); } ierr = DMDAVecRestoreArray(da, vec, &arr);CHKERRQ(ierr); VecAssemblyBegin(vec); VecAssemblyEnd(vec); return ierr; } // Map a function that acts on scalars to a 2D DMDA Vec PetscErrorCode mapToVec(Vec& vec, double(*func)(double,double,double), const int N, const double dy, const double dz,const double t,DM da) { // assumes vec has already been created and it's size has been allocated PetscErrorCode ierr = 0; PetscInt zS,yS,zn,yn; DMDAGetCorners(da, &zS, &yS, 0, &zn, &yn, 0); PetscInt zE = zS + zn; PetscInt yE = yS + yn; PetscScalar** arr; ierr = DMDAVecGetArray(da, vec, &arr);CHKERRQ(ierr); PetscInt yI,zI; PetscScalar y,z; for (yI = yS; yI < yE; yI++) { for (zI = zS; zI < zE; zI++) { y = yI * dy; z = zI * dz; arr[yI][zI] = func(y,z,t); } } ierr = DMDAVecRestoreArray(da, vec, &arr);CHKERRQ(ierr); VecAssemblyBegin(vec); VecAssemblyEnd(vec); return ierr; } // Print out a vector with 15 significant figures. void printVec(const Vec vec,const DM da) { PetscMPIInt rank; MPI_Comm_rank(PETSC_COMM_WORLD,&rank); PetscInt zS,yS,zn,yn; DMDAGetCorners(da, &zS, &yS, 0, &zn, &yn, 0); PetscInt zE = zS + zn; PetscInt yE = yS + yn; PetscScalar** arr; DMDAVecGetArray(da, vec, &arr); PetscInt yI,zI; for (yI = yS; yI < yE; yI++) { for (zI = zS; zI < zE; zI++) { PetscPrintf(PETSC_COMM_SELF,"%i: f(%i,%i) = %.2f\n",rank,yI,zI,arr[yI][zI]); } } DMDAVecRestoreArray(da, vec, &arr); VecAssemblyBegin(vec); VecAssemblyEnd(vec); } // repmat for vecs (i.e. vec -> [vec vec]) // Note: out must already be allocated onto processors // n = # of repeats PetscErrorCode repVec(Vec& out, const Vec& in, const PetscInt n) { PetscErrorCode ierr = 0; PetscInt N,Istart,Iend,Ii; PetscScalar v = 0.0; PetscScalar vals[n]; PetscInt inds[n]; VecGetSize(in,&N); VecGetOwnershipRange(in,&Istart,&Iend); for (Ii=Istart; Ii<Iend; Ii++ ) { ierr = VecGetValues(in,1,&Ii,&v);CHKERRQ(ierr); for (int i = 0; i < n; i++) { vals[i] = v; inds[i] = Ii + i*N; } ierr = VecSetValues(out,n,inds,vals,INSERT_VALUES);CHKERRQ(ierr); } ierr = VecAssemblyBegin(out);CHKERRQ(ierr); ierr = VecAssemblyEnd(out);CHKERRQ(ierr); return ierr; } // undoes repmat for vecs (i.e. [vec vec] -> vec) // Note: out must already be allocated onto processors // gIstart,gIend = global indices of in to store in out PetscErrorCode sepVec(Vec& out, const Vec& in, const PetscInt gIstart, const PetscInt gIend) { PetscErrorCode ierr = 0; PetscScalar v = 0.0; PetscInt Istart, Iend; VecGetOwnershipRange(in,&Istart,&Iend); for (PetscInt Ii = Istart; Ii < Iend; Ii++ ) { if (Ii >= gIstart && Ii < gIend) { ierr = VecGetValues(in,1,&Ii,&v);CHKERRQ(ierr); PetscInt Jj = Ii - gIstart; ierr = VecSetValue(out,Jj,v,INSERT_VALUES);CHKERRQ(ierr); } } ierr = VecAssemblyBegin(out);CHKERRQ(ierr); ierr = VecAssemblyEnd(out);CHKERRQ(ierr); return ierr; } // maps vec to bigger vec (i.e. vec -> [0 0 0, vec, 0 0 0]) // Note: out must already be allocated onto processors // Istart,Iend = global indices of out to put the values of in into PetscErrorCode distributeVec(Vec& out, const Vec& in, const PetscInt gIstart, const PetscInt gIend) { PetscErrorCode ierr = 0; PetscScalar v = 0.0; PetscInt Istart, Iend, Ii, Jj; VecGetOwnershipRange(in,&Istart,&Iend); for (Ii=Istart; Ii<Iend; Ii++ ) { ierr = VecGetValues(in,1,&Ii,&v);CHKERRQ(ierr); Jj = Ii + gIstart; ierr = VecSetValue(out,Jj,v,INSERT_VALUES);CHKERRQ(ierr); } ierr = VecAssemblyBegin(out);CHKERRQ(ierr); ierr = VecAssemblyEnd(out);CHKERRQ(ierr); return ierr; } //============================ Checkpoint Functions =============================== // loading value from ASCII checkpoint file, which should only have one value (for scalar values: time and error) PetscErrorCode loadValueFromCheckpoint(const string outputDir, const string filename, PetscScalar &value) { PetscErrorCode ierr = 0; string checkpointFile = outputDir + filename; bool fileExists = doesFileExist(checkpointFile); if (fileExists) { ierr = PetscPrintf(PETSC_COMM_WORLD, "Loading %s\n", filename.c_str()); CHKERRQ(ierr); PetscViewer viewer; ierr = PetscViewerCreate(PETSC_COMM_WORLD, &viewer); CHKERRQ(ierr); ierr = PetscViewerSetType(viewer, PETSCVIEWERASCII); CHKERRQ(ierr); ierr = PetscViewerFileSetMode(viewer, FILE_MODE_READ); CHKERRQ(ierr); ierr = PetscViewerFileSetName(viewer, checkpointFile.c_str()); CHKERRQ(ierr); ierr = PetscViewerASCIIRead(viewer, &value, 1, NULL, PETSC_SCALAR); CHKERRQ(ierr); ierr = PetscViewerDestroy(&viewer); CHKERRQ(ierr); } else { ierr = PetscPrintf(PETSC_COMM_WORLD, "Warning: %s not found, setting to default value.\n", checkpointFile.c_str()); CHKERRQ(ierr); } return ierr; } // loads value from ASCII file (for integers) PetscErrorCode loadValueFromCheckpoint(const string outputDir, const string filename, PetscInt &value) { PetscErrorCode ierr = 0; string checkpointFile = outputDir + filename; bool fileExists = doesFileExist(checkpointFile); if (fileExists) { ierr = PetscPrintf(PETSC_COMM_WORLD, "Loading %s\n", filename.c_str()); CHKERRQ(ierr); PetscViewer viewer; ierr = PetscViewerCreate(PETSC_COMM_WORLD, &viewer); CHKERRQ(ierr); ierr = PetscViewerSetType(viewer, PETSCVIEWERASCII); CHKERRQ(ierr); ierr = PetscViewerFileSetMode(viewer, FILE_MODE_READ); CHKERRQ(ierr); ierr = PetscViewerFileSetName(viewer, checkpointFile.c_str()); CHKERRQ(ierr); ierr = PetscViewerASCIIRead(viewer, &value, 1, NULL, PETSC_INT); CHKERRQ(ierr); ierr = PetscViewerDestroy(&viewer); CHKERRQ(ierr); } else { ierr = PetscPrintf(PETSC_COMM_WORLD, "Warning: %s not found, setting to default value.\n", checkpointFile.c_str()); CHKERRQ(ierr); } return ierr; } // initiate viewer to write and append vectors PetscErrorCode io_initiateWriteAppend(map<string, pair<PetscViewer,string>> &vwL, const string key, const Vec& vec, const string filename) { PetscErrorCode ierr = 0; // initiate viewer PetscViewer viewer; ierr = PetscViewerASCIIOpen(PETSC_COMM_WORLD, filename.c_str(), &viewer); ierr = PetscViewerPushFormat(viewer, PETSC_VIEWER_ASCII_MATLAB); CHKERRQ(ierr); ierr = PetscViewerFileSetMode(viewer, FILE_MODE_WRITE); CHKERRQ(ierr); vwL[key].first = viewer; vwL[key].second = filename; ierr = PetscViewerPopFormat(viewer); CHKERRQ(ierr); ierr = PetscViewerDestroy(&viewer); CHKERRQ(ierr); // reset to append mode ierr = PetscViewerASCIIOpen(PETSC_COMM_WORLD, filename.c_str(),&vwL[key].first); CHKERRQ(ierr); ierr = PetscViewerPushFormat(vwL[key].first, PETSC_VIEWER_ASCII_MATLAB); CHKERRQ(ierr); ierr = PetscViewerFileSetMode(vwL[key].first, FILE_MODE_APPEND); CHKERRQ(ierr); return ierr; } // append PetscVecs to existing files (saving new outputs to original data file during future checkpoints) PetscErrorCode initiate_appendVecToOutput(map<string, pair<PetscViewer, string>> &vwL, const string key, const Vec &vec, const string filename) { PetscErrorCode ierr = 0; // initiate viewer PetscViewer viewer; ierr = PetscViewerASCIIOpen(PETSC_COMM_WORLD, filename.c_str(), &viewer); ierr = PetscViewerPushFormat(viewer, PETSC_VIEWER_ASCII_MATLAB); CHKERRQ(ierr); ierr = PetscViewerFileSetMode(viewer, FILE_MODE_APPEND); CHKERRQ(ierr); vwL[key].first = viewer; vwL[key].second = filename; ierr = PetscViewerPopFormat(viewer); CHKERRQ(ierr); ierr = PetscViewerDestroy(&viewer); CHKERRQ(ierr); ierr = PetscViewerASCIIOpen(PETSC_COMM_WORLD, filename.c_str(),&vwL[key].first); CHKERRQ(ierr); ierr = PetscViewerPushFormat(vwL[key].first, PETSC_VIEWER_ASCII_MATLAB); CHKERRQ(ierr); ierr = PetscViewerFileSetMode(vwL[key].first, FILE_MODE_APPEND); CHKERRQ(ierr); return ierr; } // write a new ASCII file to 15 decimal places (for time and dt) PetscErrorCode writeASCII(const string outputDir, const string filename, PetscViewer &viewer, PetscScalar var) { PetscErrorCode ierr = 0; ierr = PetscViewerASCIIOpen(PETSC_COMM_WORLD, (outputDir + filename).c_str(), &viewer); ierr = PetscViewerFileSetMode(viewer, FILE_MODE_WRITE); CHKERRQ(ierr); ierr = PetscViewerASCIIPrintf(viewer, "%.15e\n", var);CHKERRQ(ierr); return ierr; } // write integer ASCII (for ckptNumber) PetscErrorCode writeASCII(const string outputDir, const string filename, PetscViewer &viewer, PetscInt var) { PetscErrorCode ierr = 0; ierr = PetscViewerASCIIOpen(PETSC_COMM_WORLD, (outputDir + filename).c_str(), &viewer); ierr = PetscViewerFileSetMode(viewer, FILE_MODE_WRITE); CHKERRQ(ierr); ierr = PetscViewerASCIIPrintf(viewer, "%i\n", var);CHKERRQ(ierr); return ierr; } // append to existing ASCII file (for scalars: time and dt) PetscErrorCode appendASCII(const string outputDir, const string filename, PetscViewer &viewer, PetscScalar var) { PetscErrorCode ierr = 0; ierr = PetscViewerASCIIOpen(PETSC_COMM_WORLD, (outputDir + filename).c_str(), &viewer); ierr = PetscViewerFileSetMode(viewer, FILE_MODE_APPEND); CHKERRQ(ierr); ierr = PetscViewerASCIIPrintf(viewer, "%.15e\n", var);CHKERRQ(ierr); return ierr; }
29.660732
145
0.684063
[ "vector" ]
d4ff5930dae40ab0b2f441f2f16d8d4e7aac8769
4,157
cpp
C++
src/cppad.git/example/general/fun_check.cpp
yinzixuan126/my_udacity
cada1bc047cd21282b008a0eb85a1df52fd94034
[ "MIT" ]
1
2019-11-05T02:23:47.000Z
2019-11-05T02:23:47.000Z
src/cppad.git/example/general/fun_check.cpp
yinzixuan126/my_udacity
cada1bc047cd21282b008a0eb85a1df52fd94034
[ "MIT" ]
null
null
null
src/cppad.git/example/general/fun_check.cpp
yinzixuan126/my_udacity
cada1bc047cd21282b008a0eb85a1df52fd94034
[ "MIT" ]
1
2019-11-05T02:23:51.000Z
2019-11-05T02:23:51.000Z
/* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-17 Bradley M. Bell CppAD is distributed under the terms of the Eclipse Public License Version 2.0. This Source Code may also be made available under the following Secondary License when the conditions for such availability set forth in the Eclipse Public License, Version 2.0 are satisfied: GNU General Public License, Version 2.0 or later. ---------------------------------------------------------------------------- */ /* ! WARNING: This file is used as an example by FunConstruct and Dependent $begin fun_check.cpp$$ $spell abs $$ $section ADFun Check and Re-Tape: Example and Test$$ $srcfile%example/general/fun_check.cpp%0%// BEGIN C++%// END C++%1%$$ $end */ // BEGIN C++ # include <cppad/cppad.hpp> namespace { // ----------------------------------------------------------- // define the template function object Fun<Type,Vector> in empty namespace template <class Type, class Vector> class Fun { private: size_t n; public: // function constructor Fun(size_t n_) : n(n_) { } // function evaluator Vector operator() (const Vector &x) { Vector y(n); size_t i; for(i = 0; i < n; i++) { // This operaiton sequence depends on x if( x[i] >= 0 ) y[i] = exp(x[i]); else y[i] = exp(-x[i]); } return y; } }; // template function FunCheckCases<Vector, ADVector> in empty namespace template <class Vector, class ADVector> bool FunCheckCases(void) { bool ok = true; using CppAD::AD; using CppAD::ADFun; using CppAD::Independent; double eps99 = 99.0 * std::numeric_limits<double>::epsilon(); // use the ADFun default constructor ADFun<double> f; // domain space vector size_t n = 2; ADVector X(n); X[0] = -1.; X[1] = 1.; // declare independent variables and starting recording Independent(X); // create function object to use with AD<double> Fun< AD<double>, ADVector > G(n); // range space vector size_t m = n; ADVector Y(m); Y = G(X); // stop tape and store operation sequence in f : X -> Y f.Dependent(X, Y); ok &= (f.size_order() == 0); // no implicit forward operation // create function object to use with double Fun<double, Vector> g(n); // function values should agree when the independent variable // values are the same as during recording Vector x(n); size_t j; for(j = 0; j < n; j++) x[j] = Value(X[j]); double r = eps99; double a = eps99; ok &= FunCheck(f, g, x, a, r); // function values should not agree when the independent variable // values are the negative of values during recording for(j = 0; j < n; j++) x[j] = - Value(X[j]); ok &= ! FunCheck(f, g, x, a, r); // re-tape to obtain the new AD of double operation sequence for(j = 0; j < n; j++) X[j] = x[j]; Independent(X); Y = G(X); // stop tape and store operation sequence in f : X -> Y f.Dependent(X, Y); ok &= (f.size_order() == 0); // no implicit forward with this x // function values should agree now ok &= FunCheck(f, g, x, a, r); return ok; } } // End empty namespace # include <vector> # include <valarray> bool FunCheck(void) { bool ok = true; typedef CppAD::vector<double> Vector1; typedef CppAD::vector< CppAD::AD<double> > ADVector1; typedef std::vector<double> Vector2; typedef std::vector< CppAD::AD<double> > ADVector2; typedef std::valarray<double> Vector3; typedef std::valarray< CppAD::AD<double> > ADVector3; // Run with Vector and ADVector equal to three different cases // all of which are Simple Vectors with elements of type // double and AD<double> respectively. ok &= FunCheckCases< Vector1, ADVector2 >(); ok &= FunCheckCases< Vector2, ADVector3 >(); ok &= FunCheckCases< Vector3, ADVector1 >(); return ok; } // END C++
29.06993
79
0.578302
[ "object", "vector" ]
be088e43570dad9fb21254169fb5e98244cc577a
7,178
cpp
C++
Pod/musicFramework/impl/OrnamentsFunctions.cpp
iKimee/musicXML
5555f5c00e74c8e3f5ddf7e83072bf208602b970
[ "Apache-2.0" ]
3
2018-12-18T06:38:57.000Z
2022-01-25T10:42:19.000Z
Pod/musicFramework/impl/OrnamentsFunctions.cpp
Bone111/MusicXMLParser
674f6b52634abb95008cc04ee02f4df0055851a6
[ "MIT" ]
null
null
null
Pod/musicFramework/impl/OrnamentsFunctions.cpp
Bone111/MusicXMLParser
674f6b52634abb95008cc04ee02f4df0055851a6
[ "MIT" ]
1
2021-01-29T10:43:31.000Z
2021-01-29T10:43:31.000Z
// MusicXML Class Library // Copyright (c) by Matthew James Briggs // Distributed under the MIT License #include "../impl/OrnamentsFunctions.h" #include "../core/elements/DelayedInvertedTurn.h" #include "../core/elements/DelayedTurn.h" #include "../core/elements/InvertedMordent.h" #include "../core/elements/InvertedTurn.h" #include "../core/elements/Mordent.h" #include "../core/elements/Ornaments.h" #include "../core/elements/OrnamentsChoice.h" #include "../core/elements/OtherOrnament.h" #include "../core/elements/Schleifer.h" #include "../core/elements/Shake.h" #include "../core/elements/Tremolo.h" #include "../core/elements/TrillMark.h" #include "../core/elements/Turn.h" #include "../core/elements/VerticalTurn.h" #include "../core/elements/WavyLine.h" #include "../impl/AccidentalMarkFunctions.h" #include "../impl/MarkDataFunctions.h" namespace mx { namespace impl { OrnamentsFunctions::OrnamentsFunctions( const core::Ornaments& inOrnaments, impl::Cursor inCursor ) : myOrnaments{ inOrnaments } , myCursor{ inCursor } { } void OrnamentsFunctions::parseOrnaments( std::vector<api::MarkData>& outMarks ) const { parseOrnamentsSet( outMarks ); parseAccidentalMarkSet( outMarks ); } void OrnamentsFunctions::parseOrnamentsSet( std::vector<api::MarkData>& outMarks ) const { for( const auto& ornament : myOrnaments.getOrnamentsChoiceSet() ) { const auto ornamentType = ornament->getChoice(); Converter converter; const auto markType = converter.convertOrnament( ornamentType ); auto markData = api::MarkData{}; markData.markType = markType; markData.tickTimePosition = myCursor.tickTimePosition; parseOrnament( *ornament, markData ); markData.smuflName = api::MarkSmufl::getName( markType, markData.positionData.placement ); markData.smuflCodepoint = api::MarkSmufl::getCodepoint( markType, markData.positionData.placement ); outMarks.emplace_back( std::move( markData ) ); } } void OrnamentsFunctions::parseAccidentalMarkSet( std::vector<api::MarkData>& outMarks ) const { for( const auto& am : myOrnaments.getAccidentalMarkSet() ) { AccidentalMarkFunctions funcs{ *am, myCursor }; outMarks.emplace_back( funcs.parseAccidentalMark() ); } } void OrnamentsFunctions::parseOrnament( const core::OrnamentsChoice& choiceObj, api::MarkData& outMark ) const { switch ( choiceObj.getChoice() ) { case core::OrnamentsChoice::Choice::trillMark: { outMark.name = "trill-mark"; parseMarkDataAttributes( *choiceObj.getTrillMark()->getAttributes(), outMark ); break; } case core::OrnamentsChoice::Choice::turn: { outMark.name = "turn"; parseMarkDataAttributes( *choiceObj.getTurn()->getAttributes(), outMark ); break; } case core::OrnamentsChoice::Choice::delayedTurn: { outMark.name = "delayed-turn"; parseMarkDataAttributes( *choiceObj.getDelayedTurn()->getAttributes(), outMark ); break; } case core::OrnamentsChoice::Choice::invertedTurn: { outMark.name = "inverted-turn"; parseMarkDataAttributes( *choiceObj.getInvertedTurn()->getAttributes(), outMark ); break; } case core::OrnamentsChoice::Choice::delayedInvertedTurn: { outMark.name = "delayed-inverted-turn"; parseMarkDataAttributes( *choiceObj.getDelayedInvertedTurn()->getAttributes(), outMark ); break; } case core::OrnamentsChoice::Choice::verticalTurn: { outMark.name = "vertical-turn"; parseMarkDataAttributes( *choiceObj.getVerticalTurn()->getAttributes(), outMark ); break; } case core::OrnamentsChoice::Choice::shake: { outMark.name = "shake"; parseMarkDataAttributes( *choiceObj.getShake()->getAttributes(), outMark ); break; } case core::OrnamentsChoice::Choice::wavyLine: { outMark.name = "wavy-line"; parseMarkDataAttributes( *choiceObj.getWavyLine()->getAttributes(), outMark ); break; } case core::OrnamentsChoice::Choice::mordent: { outMark.name = "mordent"; parseMarkDataAttributes( *choiceObj.getMordent()->getAttributes(), outMark ); break; } case core::OrnamentsChoice::Choice::invertedMordent: { outMark.name = "inverted-mordent"; parseMarkDataAttributes( *choiceObj.getInvertedMordent()->getAttributes(), outMark ); break; } case core::OrnamentsChoice::Choice::schleifer: { outMark.name = "schleifer"; parseMarkDataAttributes( *choiceObj.getSchleifer()->getAttributes(), outMark ); break; } case core::OrnamentsChoice::Choice::tremolo: { outMark.name = "tremolo"; parseMarkDataAttributes( *choiceObj.getTremolo()->getAttributes(), outMark ); break; } case core::OrnamentsChoice::Choice::otherOrnament: { const auto value = choiceObj.getOtherOrnament()->getValue().getValue(); parseMarkDataAttributes( *choiceObj.getOtherOrnament()->getAttributes(), outMark ); if( value.empty() ) { outMark.name = "other-ornament"; } else { outMark.name = value; } const auto tempChar = api::Smufl::findCodepoint( value ); if( tempChar != 0 ) { outMark.smuflName = value; outMark.smuflCodepoint = tempChar; } break; } default: break; } } } }
40.325843
118
0.509891
[ "vector" ]
be09fece86df2b581816373ade110d57c27d719e
12,924
cpp
C++
src/CFont.cpp
GeekWithALife/TextEngine
725d1ccb6eb3252f25df7668f3bfa5d781071d50
[ "MIT" ]
null
null
null
src/CFont.cpp
GeekWithALife/TextEngine
725d1ccb6eb3252f25df7668f3bfa5d781071d50
[ "MIT" ]
1
2019-05-25T05:27:08.000Z
2019-05-25T05:27:08.000Z
src/CFont.cpp
sbseltzer/TextEngine
725d1ccb6eb3252f25df7668f3bfa5d781071d50
[ "MIT" ]
null
null
null
#include "../include/CFont.hpp" #include <iostream> #include <fstream> FT_Library Font::lib; std::unordered_map<std::string, Font> Font::fontCache; std::unordered_map<std::string, FT_Face> Font::faceCache; GLuint Font::program = 0; GLuint Font::tex = 0; GLuint Font::vbo = 0; GLuint Font::uniform_tex = 0; GLuint Font::uniform_color = 0; GLuint Font::attribute_coord = 0; #define printOpenGLError() printOglError(__FILE__, __LINE__) int printOglError(char *file, int line) { GLenum glErr; int retCode = 0; glErr = glGetError(); if (glErr != GL_NO_ERROR) { printf("glError in file %s @ line %d: %s\n", file, line, gluErrorString(glErr)); retCode = 1; } return retCode; } static GLuint CreateShader(std::string vertexSource, std::string fragmentSource) { GLuint program = 0; printf("Creating vertex shader...\n"); //Create an empty vertex shader handle GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); printf("Setting source...\n"); //Send the vertex shader source code to GL //Note that std::string's .c_str is NULL character terminated. const GLchar *source = (const GLchar *)vertexSource.c_str(); glShaderSource(vertexShader, 1, &source, 0); printf("Compiling...\n"); //Compile the vertex shader glCompileShader(vertexShader); printf("Checking...\n"); GLint isCompiled = 0; glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &isCompiled); if(isCompiled == GL_FALSE) { GLint maxLength = 0; glGetShaderiv(vertexShader, GL_INFO_LOG_LENGTH, &maxLength); //The maxLength includes the NULL character std::vector<GLchar> infoLog(maxLength); glGetShaderInfoLog(vertexShader, maxLength, &maxLength, &infoLog[0]); //We don't need the shader anymore. glDeleteShader(vertexShader); //Use the infoLog as you see fit. printf("Failed to compile vertex shader!\n"); for (unsigned int i = 0; i < infoLog.size(); ++i) printf("%c", infoLog[i]); printf("\n"); //In this simple program, we'll just leave return 0; } printf("Creating fragment shader...\n"); //Create an empty fragment shader handle GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); printf("Setting source...\n"); //Send the fragment shader source code to GL //Note that std::string's .c_str is NULL character terminated. source = (const GLchar *)fragmentSource.c_str(); glShaderSource(fragmentShader, 1, &source, 0); printf("Compiling...\n"); //Compile the fragment shader glCompileShader(fragmentShader); printf("Checking...\n"); glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &isCompiled); if(isCompiled == GL_FALSE) { GLint maxLength = 0; glGetShaderiv(fragmentShader, GL_INFO_LOG_LENGTH, &maxLength); //The maxLength includes the NULL character std::vector<GLchar> infoLog(maxLength); glGetShaderInfoLog(fragmentShader, maxLength, &maxLength, &infoLog[0]); //We don't need the shader anymore. glDeleteShader(fragmentShader); //Either of them. Don't leak shaders. glDeleteShader(vertexShader); //Use the infoLog as you see fit. printf("Failed to compile fragment shader!\n"); for (unsigned int i = 0; i < infoLog.size(); ++i) printf("%c", infoLog[i]); //In this simple program, we'll just leave return 0; } printf("Creating shader program...\n"); //Vertex and fragment shaders are successfully compiled. //Now time to link them together into a program. //Get a program object. program = glCreateProgram(); printf("Attaching shaders...\n"); //Attach our shaders to our program glAttachShader(program, vertexShader); glAttachShader(program, fragmentShader); printf("Linking...\n"); //Link our program glLinkProgram(program); printf("Checking...\n"); //Note the different functions here: glGetProgram* instead of glGetShader*. GLint isLinked = 0; glGetProgramiv(program, GL_LINK_STATUS, (int *)&isLinked); if(isLinked == GL_FALSE) { GLint maxLength = 0; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength); //The maxLength includes the NULL character std::vector<GLchar> infoLog(maxLength); glGetProgramInfoLog(program, maxLength, &maxLength, &infoLog[0]); //We don't need the program anymore. glDeleteProgram(program); //Don't leak shaders either. glDeleteShader(vertexShader); glDeleteShader(fragmentShader); //Use the infoLog as you see fit. printf("Failed to link!\n"); //In this simple program, we'll just leave return 0; } printf("Detaching shaders...\n"); //Always detach shaders after a successful link. glDetachShader(program, vertexShader); glDetachShader(program, fragmentShader); printf("Returning...\n"); return program; } static void ReadShaderFile(std::string fileName, std::string& source) { std::ifstream is (fileName, std::ifstream::binary); if (is) { // get length of file: is.seekg (0, is.end); int length = is.tellg(); is.seekg (0, is.beg); char * buffer = new char [length]; std::cout << "Reading " << length << " characters... " << std::endl; // read data as a block: is.read (buffer,length); if (is) std::cout << "all characters read successfully." << std::endl; else std::cout << "error: only " << is.gcount() << " could be read" << std::endl; is.close(); source.assign(buffer); delete[] buffer; } } bool Font::Initialize(std::string vertexFile, std::string fragmentFile) { if (FT_Init_FreeType(&Font::lib)) { fprintf(stderr, "Could not initialize the FreeType library\n"); return false; } std::string vertexSource; std::string fragmentSource; ReadShaderFile(vertexFile, vertexSource); ReadShaderFile(fragmentFile, fragmentSource); Font::program = CreateShader(vertexSource, fragmentSource); if (Font::program == 0) { fprintf(stderr, "Could not initialize the shader\n"); return false; } glUseProgram(Font::program); Font::uniform_tex = glGetUniformLocation(Font::program, "tex"); if (Font::uniform_tex < 0) { fprintf(stderr, "Could not bind texture uniform\n"); return false; } Font::uniform_color = glGetUniformLocation(Font::program, "color"); if (Font::uniform_color < 0) { fprintf(stderr, "Could not bind color uniform\n"); return false; } Font::attribute_coord = glGetAttribLocation(Font::program, "coord"); if (Font::attribute_coord < 0) { fprintf(stderr, "Could not bind coord attribute\n"); return false; } // Before we can start rendering text, there are still some things that need initialization. // First, we will use a single texture object to render all the glyphs: glActiveTexture(GL_TEXTURE0); printOpenGLError(); glGenTextures(1, &Font::tex); printOpenGLError(); glBindTexture(GL_TEXTURE_2D, Font::tex); printOpenGLError(); glUniform1i(Font::uniform_tex, 0); printOpenGLError(); // To prevent certain artifacts when a character is not rendered exactly on pixel boundaries, // we should clamp the texture at the edges, and enable linear interpolation: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); printOpenGLError(); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); printOpenGLError(); // It is also very important to disable the default 4-byte alignment restrictions that OpenGL // uses for uploading textures and other data. Normally you won't be affected by this restriction, // as most textures have a width that is a multiple of 4, and/or use 4 bytes per pixel. // The glyph images are in a 1-byte greyscale format though, and can have any possible width. // To ensure there are no alignment restrictions, we have to use this line: glPixelStorei(GL_UNPACK_ALIGNMENT, 1); printOpenGLError(); // We also need to set up a vertex buffer object for our combined vertex and texture coordinates: glGenBuffers(1, &Font::vbo); printOpenGLError(); glEnableVertexAttribArray(Font::attribute_coord); printOpenGLError(); glBindBuffer(GL_ARRAY_BUFFER, Font::vbo); printOpenGLError(); glVertexAttribPointer(Font::attribute_coord, 4, GL_FLOAT, GL_FALSE, 0, 0); printOpenGLError(); //Font::EndRender(); return true; } bool Font::Initialize() { return Font::Initialize("./shaders/text.vert", "./shaders/text.frag"); } void Font::Release() { glDeleteProgram(Font::program); glDeleteBuffers(1, &Font::vbo); glDeleteTextures(1, &Font::tex); // Release FreeType FT_Done_FreeType(Font::lib); } void Font::BeginRender() { /*glUseProgram(Font::program); printOpenGLError(); glBindTexture(GL_TEXTURE_2D, Font::tex); printOpenGLError(); glBindBuffer(GL_ARRAY_BUFFER, Font::vbo); printOpenGLError(); glEnableVertexAttribArray(Font::attribute_coord); printOpenGLError(); glUniform1i(Font::uniform_tex, Font::tex); printOpenGLError();*/ } void Font::Render(const char *text, float x, float y, float sx, float sy) { const char *p; for(p = text; *p; p++) { if(FT_Load_Char(face, *p, FT_LOAD_RENDER)) continue; FT_GlyphSlot g = GetGlyph(); glTexImage2D( GL_TEXTURE_2D, 0, GL_RED, g->bitmap.width, g->bitmap.rows, 0, GL_RED, GL_UNSIGNED_BYTE, g->bitmap.buffer ); printOpenGLError(); float x2 = x + g->bitmap_left * sx; float y2 = -y - g->bitmap_top * sy; float w = g->bitmap.width * sx; float h = g->bitmap.rows * sy; GLfloat box[4][4] = { {x2, -y2 , 0, 0}, {x2 + w, -y2 , 1, 0}, {x2, -y2 - h, 0, 1}, {x2 + w, -y2 - h, 1, 1}, }; glBufferData(GL_ARRAY_BUFFER, sizeof box, box, GL_DYNAMIC_DRAW); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); printOpenGLError(); x += (g->advance.x >> 6) * sx; y += (g->advance.y >> 6) * sy; } } void Font::Render(float &x, float &y, const float sx, const float sy) { FT_GlyphSlot glyph = GetGlyph(); float x2 = x + glyph->bitmap_left * sx; float y2 = -y - glyph->bitmap_top * sy; float w = glyph->bitmap.width * sx; float h = glyph->bitmap.rows * sy; GLfloat box[4][4] = { {x2, -y2 , 0, 0}, {x2 + w, -y2 , 1, 0}, {x2, -y2 - h, 0, 1}, {x2 + w, -y2 - h, 1, 1}, }; glTexImage2D( GL_TEXTURE_2D, 0, GL_RED, glyph->bitmap.width, glyph->bitmap.rows, 0, GL_RED, GL_UNSIGNED_BYTE, glyph->bitmap.buffer ); printOpenGLError(); glBufferData(GL_ARRAY_BUFFER, sizeof(box), box, GL_DYNAMIC_DRAW); printOpenGLError(); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); printOpenGLError(); //printf("x2:%f y2:%f w:%f h:%f x:%f y:%f\n", x2, y2, w, h, x, y); x += (glyph->advance.x >> 6) * sx; y += (glyph->advance.y >> 6) * sy; } void Font::EndRender() { /*glDisableVertexAttribArray(Font::attribute_coord); printOpenGLError(); glBindTexture(GL_TEXTURE_2D, 0); printOpenGLError(); glBindBuffer(GL_ARRAY_BUFFER, 0); printOpenGLError();*/ } bool Font::Exists(std::string name) { return (Font::fontCache.find(name) != Font::fontCache.end()); } Font Font::Get(std::string name) { return Font::fontCache[name]; } void Font::Cache(std::string name, Font font) { Font::fontCache[name] = font; } Font::Font() { pointSize = 12; //face = {0}; isValid = LoadFont(TextEngine_NAMESPACE::DefaultFont); } Font::Font(const std::string name) { pointSize = 12; //face = {0}; isValid = LoadFont(name); } Font::~Font() {} bool Font::LoadFont(const std::string name) { if (Font::faceCache.find(name) == Font::faceCache.end()) { //printf("Attempting to init new font: %s\n", name.c_str()); int err = 0; if ((err = FT_New_Face(Font::lib, name.c_str(), 0, &face))) { fprintf(stderr, "Error 0x%04x: Could not open font! Is FreeType initialized?\n", err); return false; } printf("Initialized new font: %s\n", face->family_name); Font::faceCache[name] = face; } //printf("Found font in faceCache!\n"); face = Font::faceCache[name]; fontName = name; FT_Set_Pixel_Sizes(face, 0, 48); return true; } bool Font::IsValid() { return isValid; } // State Management bool Font::SetSize(const unsigned int size) { if (!IsValid()) return false; pointSize = size; if (FT_Set_Pixel_Sizes(face, 0, pointSize)) { fprintf(stderr, "Could not resize font\n"); return false; } return true; } bool Font::LoadCharacter(const UnicodeChar ch) { if (!IsValid()) return false; if (FT_Load_Char(face, ch, FT_LOAD_RENDER)) { fprintf(stderr, "Could not load character '%c'\n", ch); return false; } return true; } FT_GlyphSlot& Font::GetGlyph() { return face->glyph; } /* static void render_text(const char *text, float x, float y, float sx, float sy) { const char *p; for(p = text; *p; p++) { if(FT_Load_Char(face, *p, FT_LOAD_RENDER)) continue; } }*/ //FT_Face Font::GetFace(std::string fontName) { return NULL; } //FT_Bitmap Font::GetBitmap(std::string fontName, UnicodeChar ch) { return NULL; }
28.404396
100
0.683844
[ "render", "object", "vector" ]
be0cd8f4ea4049953f42f3af70b77f0209c7a389
1,345
hpp
C++
include/complex/cubical_map.hpp
YuanL12/BATS
35a32facc87e17649b7fc32225c8ffaf0301bbfa
[ "MIT" ]
null
null
null
include/complex/cubical_map.hpp
YuanL12/BATS
35a32facc87e17649b7fc32225c8ffaf0301bbfa
[ "MIT" ]
null
null
null
include/complex/cubical_map.hpp
YuanL12/BATS
35a32facc87e17649b7fc32225c8ffaf0301bbfa
[ "MIT" ]
null
null
null
#pragma once /* function to produce a cubical map */ /* Create a cell map from simplicial map data i.e. we take a map on 0-cells and extend to a map on all simplices */ #include <iostream> #include <vector> #include <stdexcept> #include <util/simplex.hpp> #include "cell_map.hpp" #include "simplicial_complex.hpp" #include <linalg/sparse_vector.hpp> #include <linalg/col_matrix.hpp> namespace bats { // construct simplicial map from X to Y // Assumes that X \subseteq Y CellularMap CubicalMap( const CubicalComplex &X, const CubicalComplex &Y ) { std::vector<size_t> s; // cell size_t maxd = X.maxdim(); CellularMap f(maxd); for (size_t k = 0; k < maxd+1; k++) { std::vector<SparseVector<int, size_t>> col; for (size_t i = 0; i < X.ncells(k); i++) { // fill s with image of simplex i in dimension k s.clear(); for (auto it = X.cell_begin(k, i); it != X.cell_end(k, i); ++it) { s.emplace_back(*it); } // for (auto si : s) { // std::cout << si << ','; // } // std::cout << std::endl; int sgn = 1; size_t j = Y.find_idx(s); if (j == bats::NO_IND) { throw std::out_of_range("No existing target cell!"); } col.emplace_back(SparseVector<int, size_t>({j}, {sgn})); } f[k] = ColumnMatrix<SparseVector<int, size_t>>(Y.ncells(k), X.ncells(k), col); } return f; } } // namespace bats
22.416667
80
0.636431
[ "vector" ]
be10d1fad7708745bf46946240f1a926b211f465
5,733
cpp
C++
cpp/tests/stream_compaction/drop_nans_tests.cpp
isVoid/cudf
1a3b3f217be93a55b47af3a9d0da29f0fcb7c7e9
[ "Apache-2.0" ]
null
null
null
cpp/tests/stream_compaction/drop_nans_tests.cpp
isVoid/cudf
1a3b3f217be93a55b47af3a9d0da29f0fcb7c7e9
[ "Apache-2.0" ]
1
2020-02-01T14:20:00.000Z
2020-02-01T14:20:00.000Z
cpp/tests/stream_compaction/drop_nans_tests.cpp
isVoid/cudf
1a3b3f217be93a55b47af3a9d0da29f0fcb7c7e9
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2020, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cmath> #include <cudf/copying.hpp> #include <cudf/stream_compaction.hpp> #include <cudf/table/table.hpp> #include <cudf/table/table_view.hpp> #include <cudf/types.hpp> #include <tests/utilities/base_fixture.hpp> #include <tests/utilities/column_utilities.hpp> #include <tests/utilities/column_wrapper.hpp> #include <tests/utilities/table_utilities.hpp> #include <tests/utilities/type_lists.hpp> struct DropNANsTest : public cudf::test::BaseFixture { }; TEST_F(DropNANsTest, MixedNANsAndNull) { using F = float; using D = double; cudf::test::fixed_width_column_wrapper<float> col1{ {F(1.0), F(2.0), F(NAN), F(NAN), F(5.0), F(6.0)}, {1, 1, 0, 1, 1, 0}}; cudf::test::fixed_width_column_wrapper<int32_t> col2{{10, 40, 70, 5, 2, 10}, {1, 1, 0, 1, 1, 0}}; cudf::test::fixed_width_column_wrapper<double> col3{{D(NAN), 40.0, 70.0, 5.0, 2.0, 10.0}, {1, 1, 0, 1, 1, 0}}; cudf::table_view input{{col1, col2, col3}}; std::vector<cudf::size_type> keys{0, 2}; cudf::test::fixed_width_column_wrapper<float> col1_expected{{2.0, 3.0, 5.0, 6.0}, {1, 0, 1, 0}}; cudf::test::fixed_width_column_wrapper<int32_t> col2_expected{{40, 70, 2, 10}, {1, 0, 1, 0}}; cudf::test::fixed_width_column_wrapper<double> col3_expected{{40.0, 70.0, 2.0, 10.0}, {1, 0, 1, 0}}; cudf::table_view expected{{col1_expected, col2_expected, col3_expected}}; auto got = cudf::drop_nans(input, keys); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, got->view()); } TEST_F(DropNANsTest, NoNANs) { cudf::test::fixed_width_column_wrapper<float> col1{{1.0, 2.0, 3.0, 4.0, 5.0, 6.0}, {1, 1, 0, 1, 1, 1}}; cudf::test::fixed_width_column_wrapper<int32_t> col2{{10, 40, 70, 5, 2, 10}, {1, 1, 1, 1, 0, 1}}; cudf::test::fixed_width_column_wrapper<double> col3{{10, 40, 70, 5, 2, 10}, {1, 1, 0, 1, 1, 1}}; cudf::table_view input{{col1, col2, col3}}; std::vector<cudf::size_type> keys{0, 2}; auto got = cudf::drop_nans(input, keys); CUDF_TEST_EXPECT_TABLES_EQUAL(input, got->view()); } TEST_F(DropNANsTest, MixedWithThreshold) { using F = float; using D = double; cudf::test::fixed_width_column_wrapper<float> col1{ {F(1.0), F(2.0), F(NAN), F(NAN), F(5.0), F(6.0)}, {1, 1, 0, 1, 1, 0}}; cudf::test::fixed_width_column_wrapper<int32_t> col2{{10, 40, 70, 5, 2, 10}, {1, 1, 0, 1, 1, 0}}; cudf::test::fixed_width_column_wrapper<double> col3{{D(NAN), 40.0, 70.0, D(NAN), 2.0, 10.0}, {1, 1, 0, 1, 1, 0}}; cudf::table_view input{{col1, col2, col3}}; std::vector<cudf::size_type> keys{0, 2}; cudf::test::fixed_width_column_wrapper<float> col1_expected{{1.0, 2.0, 3.0, 5.0, 6.0}, {1, 1, 0, 1, 0}}; cudf::test::fixed_width_column_wrapper<int32_t> col2_expected{{10, 40, 70, 2, 10}, {1, 1, 0, 1, 0}}; cudf::test::fixed_width_column_wrapper<double> col3_expected{{D(NAN), 40.0, 70.0, 2.0, 10.0}, {1, 1, 0, 1, 0}}; cudf::table_view expected{{col1_expected, col2_expected, col3_expected}}; auto got = cudf::drop_nans(input, keys, 1); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, got->view()); } TEST_F(DropNANsTest, EmptyTable) { cudf::table_view input{std::vector<cudf::column_view>()}; cudf::table_view expected{std::vector<cudf::column_view>()}; std::vector<cudf::size_type> keys{}; auto got = cudf::drop_nans(input, keys); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, got->view()); } TEST_F(DropNANsTest, EmptyColumns) { cudf::test::fixed_width_column_wrapper<float> col1{}; cudf::test::fixed_width_column_wrapper<int32_t> col2{}; cudf::test::fixed_width_column_wrapper<double> col3{}; cudf::table_view input{{col1, col2, col3}}; std::vector<cudf::size_type> keys{0, 2}; cudf::test::fixed_width_column_wrapper<float> col1_expected{}; cudf::test::fixed_width_column_wrapper<int32_t> col2_expected{}; cudf::test::fixed_width_column_wrapper<double> col3_expected{}; cudf::table_view expected{{col1_expected, col2_expected, col3_expected}}; auto got = cudf::drop_nans(input, keys); CUDF_TEST_EXPECT_TABLES_EQUAL(expected, got->view()); } TEST_F(DropNANsTest, EmptyKeys) { using F = float; cudf::test::fixed_width_column_wrapper<float> col1{ {F(1.0), F(2.0), F(NAN), F(NAN), F(5.0), F(6.0)}, {1, 1, 0, 1, 1, 0}}; cudf::table_view input{{col1}}; std::vector<cudf::size_type> keys{}; auto got = cudf::drop_nans(input, keys); CUDF_TEST_EXPECT_TABLES_EQUAL(input, got->view()); } TEST_F(DropNANsTest, NonFloatingKey) { cudf::test::fixed_width_column_wrapper<float> col1{{1.0}}; cudf::test::fixed_width_column_wrapper<int32_t> col2{2}; cudf::test::fixed_width_column_wrapper<double> col3{{3.0}}; cudf::table_view input{{col1, col2, col3}}; std::vector<cudf::size_type> keys{0, 1}; EXPECT_THROW(cudf::drop_nans(input, keys), cudf::logic_error); }
40.659574
99
0.64277
[ "vector" ]
be13381b7c9bb14dac8972ed9f2faef4084e4062
13,846
cpp
C++
src/gt-ped-generation.cpp
yp/Heu-MCHC
30c4a5e189c7ab67d82357d2c8a98833a556345a
[ "BSD-3-Clause" ]
1
2020-06-30T04:39:34.000Z
2020-06-30T04:39:34.000Z
src/gt-ped-generation.cpp
yp/Heu-MCHC
30c4a5e189c7ab67d82357d2c8a98833a556345a
[ "BSD-3-Clause" ]
null
null
null
src/gt-ped-generation.cpp
yp/Heu-MCHC
30c4a5e189c7ab67d82357d2c8a98833a556345a
[ "BSD-3-Clause" ]
null
null
null
/** * * * Heu-MCHC * * A fast and accurate heuristic algorithm for the haplotype inference * problem on pedigree data with recombinations and mutations * * Copyright (C) 2009,2010,2011 Yuri PIROLA * * Distributed under the terms of the GNU General Public License (GPL) * * * This file is part of Heu-MCHC. * * Heu-MCHC 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. * * Heu-MCHC 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 Heu-MCHC. If not, see <http://www.gnu.org/licenses/>. * **/ #include <vector> #include <list> #include <set> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <cstdlib> #include <ctime> #include <cstring> #include "log.h" #include "util.h" #include "gt-ped-gen-opt.h" #include "log-build-info.h" using namespace std; size_t n_indiv; size_t len_hap; double p_children; double p_multimating; double p_mutation; double p_recombination; size_t n_confs; char* file_prefix; int seed; typedef vector<bool> hap_t; typedef vector<int> gen_t; class p_hap_t { public: p_hap_t(int _id, size_t hap_len) :id(_id), fid(-1), mid(-1), h1(hap_len, false), h2(hap_len, false), mf(hap_len, false), mm(hap_len, false), rf(hap_len, false), rm(hap_len, false) {} int id; int fid; int mid; hap_t h1; hap_t h2; hap_t mf; hap_t mm; hap_t rf; hap_t rm; }; ostream& operator<<(ostream& out, p_hap_t& ph) { for (size_t i= 0; i<len_hap; ++i) { if (ph.h1[i]==ph.h2[i]) { out << (ph.h1[i]?1:0); } else { out << 2; } } return out; } ostream& operator<<(ostream& out, hap_t& ph) { for (size_t i= 0; i<len_hap; ++i) { if (ph[i]) { out << '1'; } else { out << '0'; } } return out; } static void randomize_mutations(hap_t& m, hap_t& mut, bool infinite_site) { for (size_t i= 0; i<m.size(); ++i) { if ((!infinite_site || !mut[i]) && rnd_01()<p_mutation) { m[i]= true; mut[i]= true; } else { m[i]= false; } } } static void randomize_haplotype(hap_t& h) { for (size_t i= 0; i<h.size(); ++i) { if (rnd_01()<0.5) { h[i]= true; } else { h[i]= false; } } } static void randomize_recombinations(hap_t& r, const hap_t& h1, const hap_t& h2) { bool state= false; for (size_t i= 1; i<r.size(); ++i) { if ((h1[i]!=h2[i]) && (rnd_01()<p_recombination)) { state= !state; } r[i]= state; } } static void calculate_haplotype(hap_t& h, const hap_t& m, const hap_t& r, hap_t& h1p, hap_t& h2p) { hap_t* h1= &h1p; hap_t* h2= &h2p; if (rnd_01()<0.5) { h1= &h2p; h2= &h1p; } for (size_t i= 0; i<r.size(); ++i) { bool state= (*h1)[i]; if (r[i]) state= (*h2)[i]; if (m[i]) state= !state; h[i]= state; } } int main(int argc, char** argv) { INFO("GEN-GT-PED started."); PRINT_SYSTEM_INFORMATIONS; time_t rawtime; struct tm * timeinfo; int base_time= ((int)time (&rawtime)); gengetopt_args_info args_info; if (cmdline_parser(argc, argv, &args_info) != 0) { FATAL("Parameter error. " "Try option --help for additional intormation about parameters."); fail(); } // Check parameters if (args_info.n_individuals_arg<=0) { FATAL("Parameter n-individuals has an invalid value (%d).", args_info.n_individuals_arg); fail(); } else { n_indiv= args_info.n_individuals_arg; INFO("n-individuals: " ST_FMTL(4) " ", n_indiv); } if (args_info.haplotype_length_arg<=0) { FATAL("Parameter haplotype-length has an invalid value (%d).", args_info.haplotype_length_arg); fail(); } else { len_hap= args_info.haplotype_length_arg; INFO("haplotype-length: " ST_FMTL(4) " ", len_hap); } if ((args_info.children_probability_arg<0.0) || (args_info.children_probability_arg>1.0)) { FATAL("Parameter children-probability has an invalid value (%e).", args_info.children_probability_arg); fail(); } else { p_children= args_info.children_probability_arg; INFO("children-probability: %+6f", p_children); } if ((args_info.multimating_probability_arg<0.0) || (args_info.multimating_probability_arg>1.0)) { FATAL("Parameter multimating-probability has an invalid value (%e).", args_info.multimating_probability_arg); fail(); } else { p_multimating= args_info.multimating_probability_arg; INFO("multimating-probability: %+6f", p_multimating); } if ((args_info.mutation_probability_arg<0.0) || (args_info.mutation_probability_arg>1.0)) { FATAL("Parameter mutation-probability has an invalid value (%e).", args_info.mutation_probability_arg); fail(); } else { p_mutation= args_info.mutation_probability_arg; INFO("mutation-probability: %+6f", p_mutation); } if ((args_info.recombination_probability_arg<0.0) || (args_info.recombination_probability_arg>1.0)) { FATAL("Parameter recombination-probability has an invalid value (%e).", args_info.recombination_probability_arg); fail(); } else { p_recombination= args_info.recombination_probability_arg; INFO("recombination-probability: %+6f", p_recombination); } if (args_info.infinite_site_flag==0) { INFO("Infinite-site assumption: NO"); } else { INFO("Infinite-site assumption: YES"); } if (args_info.n_configurations_arg<=0) { FATAL("Parameter n-configurations has an invalid value (%d).", args_info.n_configurations_arg); fail(); } else { n_confs= args_info.n_configurations_arg; INFO("n-configuration: " ST_FMT, n_confs); } file_prefix= args_info.file_prefix_arg; INFO("file-prefix: %s", file_prefix); if (args_info.seed_arg<0) { FATAL("Parameter seed has an invalid value (%d).", args_info.seed_arg); fail(); } else { if (args_info.seed_arg==0){ seed= base_time; } else { seed= args_info.seed_arg; } INFO("seed: %d", seed); } srand(seed); unsigned int n= 0; // no of individuals vector<p_hap_t> indivs; list<int> indivs_as_p_founder; list<int> indivs_as_m_founder; list<int> indivs_as_children; // Topology creation // first individual indivs.push_back(p_hap_t(n, len_hap)); ++n; indivs_as_children.push_back(0); indivs_as_p_founder.push_back(0); while (n<n_indiv) { // create a family given a child if (n<n_indiv) { int c= indivs_as_children.front(); indivs_as_children.pop_front(); int f= n; int m= n+1; n= n+2; indivs.push_back(p_hap_t(f, len_hap)); indivs.push_back(p_hap_t(m, len_hap)); indivs[c].fid= f; indivs[c].mid= m; indivs_as_children.push_back(f); indivs_as_children.push_back(m); double pc= p_children; while ((n<n_indiv) && (rnd_01()<pc)) { indivs.push_back(p_hap_t(n, len_hap)); indivs[n].fid= f; indivs[n].mid= m; if (rnd_01()<0.5) indivs_as_p_founder.push_back(n); else indivs_as_m_founder.push_back(n); ++n; pc= pc*p_children; } } if (n<n_indiv && !indivs_as_p_founder.empty()) { int f= indivs_as_p_founder.front(); if (rnd_01()>=p_multimating) indivs_as_p_founder.pop_front(); int m= n; int c= n+1; n= n+2; indivs.push_back(p_hap_t(m, len_hap)); indivs.push_back(p_hap_t(c, len_hap)); indivs[c].fid= f; indivs[c].mid= m; indivs_as_children.push_back(m); if (rnd_01()<0.5) indivs_as_p_founder.push_back(c); else indivs_as_m_founder.push_back(c); double pc= p_children; while ((n<n_indiv) && (rnd_01()<pc)) { indivs.push_back(p_hap_t(n, len_hap)); indivs[n].fid= f; indivs[n].mid= m; if (rnd_01()<0.5) indivs_as_p_founder.push_back(n); else indivs_as_m_founder.push_back(n); ++n; pc= pc*p_children; } } if (n<n_indiv && !indivs_as_m_founder.empty()) { int m= indivs_as_m_founder.front(); if (rnd_01()>=p_multimating) indivs_as_m_founder.pop_front(); int f= n; int c= n+1; n= n+2; indivs.push_back(p_hap_t(f, len_hap)); indivs.push_back(p_hap_t(c, len_hap)); indivs[c].fid= f; indivs[c].mid= m; indivs_as_children.push_back(f); if (rnd_01()<0.5) indivs_as_p_founder.push_back(c); else indivs_as_m_founder.push_back(c); double pc= p_children; while ((n<n_indiv) && (rnd_01()<pc)) { indivs.push_back(p_hap_t(n, len_hap)); indivs[n].fid= f; indivs[n].mid= m; if (rnd_01()<0.5) indivs_as_p_founder.push_back(n); else indivs_as_m_founder.push_back(n); ++n; pc= pc*p_children; } } } if (args_info.print_pedigree_given) { FILE * pout; if (strcmp(args_info.print_pedigree_file_arg, "-")==0) { pout= stdout; } else { pout= fopen(args_info.print_pedigree_file_arg, "w"); } if (pout==NULL) { ERROR("Opening file \"%s\" for writing failed!", args_info.print_pedigree_file_arg); } else { set<int> mmnode; fprintf(pout, "digraph G {\n"); for (size_t i= 0; i<indivs.size(); ++i) { if (indivs[i].fid!=-1) { if (mmnode.find(indivs[i].fid*n+indivs[i].mid)==mmnode.end()) { fprintf(pout, " f%03dm%03d[label=\"\", shape=\"point\"];\n", indivs[i].fid, indivs[i].mid); fprintf(pout, " i%03d[shape=\"box\"];\n", indivs[i].fid); fprintf(pout, " i%03d[shape=\"ellipse\"];\n", indivs[i].mid); fprintf(pout, " f%03dm%03d[label=\"\", shape=\"point\"];\n", indivs[i].fid, indivs[i].mid); fprintf(pout, " i%03d -> f%03dm%03d;\n", indivs[i].fid, indivs[i].fid, indivs[i].mid); fprintf(pout, " i%03d -> f%03dm%03d;\n", indivs[i].mid, indivs[i].fid, indivs[i].mid); mmnode.insert(indivs[i].fid*n+indivs[i].mid); } fprintf(pout, " f%03dm%03d -> i%03d;\n", indivs[i].fid, indivs[i].mid, indivs[i].id); } } fprintf(pout, "}\n"); INFO("Pedigree DOT description wrote on \"%s\".", args_info.print_pedigree_file_arg); if (pout!=stdout) fclose(pout); } } for (size_t j= 0; j<n_confs; ++j) { // Calculate a random haplotype configuration INFO("Calculate random haplotype configuration " ST_FMTL(3) " /" ST_FMTL(3) " .", j, n_confs); vector<bool> iniz(n, false); hap_t tmut(len_hap, false); list<int> queue; for (unsigned int i= 0; i<n; ++i) { if (!iniz[i]) { queue.push_front(i); while (!queue.empty()) { int p= queue.front(); queue.pop_front(); if (iniz[p]) continue; if (indivs[p].fid!=-1) { // not a founder int f= indivs[p].fid; int m= indivs[p].mid; if (!iniz[f] || !iniz[m]) { // parents not initialized queue.push_front(p); if (!iniz[m]) queue.push_front(m); if (!iniz[f]) queue.push_front(f); } else { // parents initialized // initialize events randomize_mutations(indivs[p].mf, tmut, args_info.infinite_site_flag!=0); randomize_mutations(indivs[p].mm, tmut, args_info.infinite_site_flag!=0); randomize_recombinations(indivs[p].rf, indivs[f].h1, indivs[f].h2); randomize_recombinations(indivs[p].rm, indivs[m].h1, indivs[m].h2); // calculate haplotypes calculate_haplotype(indivs[p].h1, indivs[p].mf, indivs[p].rf, indivs[f].h1, indivs[f].h2); calculate_haplotype(indivs[p].h2, indivs[p].mm, indivs[p].rm, indivs[m].h1, indivs[m].h2); iniz[p]= true; } } else { // founder randomize_haplotype(indivs[p].h1); randomize_haplotype(indivs[p].h2); iniz[p]= true; } } } } // Print the genotyped pedigree ostringstream sfilename; sfilename << file_prefix << "conf-" << j << ".txt"; string filename= sfilename.str(); DEBUG("Saving the genotyped pedigree on file \"%s\".", filename.c_str()); ostringstream oss; oss << base_time; timeinfo = localtime ( &rawtime ); ofstream fout(filename.c_str()); fout << "# General tree pedigree generated " << asctime (timeinfo); fout << "# configuration number: " << j << endl; fout << "# mutation-probability: " << p_mutation << endl; fout << "# recomb-probability: " << p_recombination << endl; fout << "# n-individuals: " << n << endl; fout << "# haplotype-length: " << len_hap << endl; fout << "# children-probability: " << p_children << endl; fout << "# multimating-prob: " << p_multimating << endl; fout << "# n-configuration: " << n_confs << endl; fout << "# file-prefix: " << file_prefix << endl; fout << "# seed: " << seed << endl; fout << len_hap << endl; fout << n << endl; fout << "# genotypes" << endl; for (size_t i=0; i<n; ++i) { fout << "#| " << i << " G " << indivs[i] << endl; fout << "#| " << i << " P " << indivs[i].h1 << endl; fout << "#| " << i << " M " << indivs[i].h2 << endl; fout << indivs[i] << endl; } fout << "# events " << endl; for (size_t i=0; i<n; ++i) { for (size_t j= 0; j<len_hap; ++j) { if (indivs[i].mf[j]) { fout << "#* MUT "<< i << " " << j << " 0" << endl; } if (indivs[i].mm[j]) { fout << "#* MUT "<< i << " " << j << " 1" << endl; } } } for (size_t i=0; i<n; ++i) { for (size_t j= 1; j<len_hap; ++j) { if (indivs[i].rf[j] != indivs[i].rf[j-1]) { fout << "#* REC "<< i << " " << j << " 0" << endl; } if (indivs[i].rm[j] != indivs[i].rm[j-1]) { fout << "#* REC "<< i << " " << j << " 1" << endl; } } } fout << "# pedigree Father Mother Child" << endl; for (size_t i=0; i<n; ++i) { if (indivs[i].fid!=-1) { fout << indivs[i].fid << " " << indivs[i].mid << " " << indivs[i].id << endl; } } fout << "# end" << endl; fout.close(); } INFO("GEN-GT-PED terminated."); }
26.423664
96
0.618301
[ "shape", "vector" ]
be16c08f057b4913dafc544d6c7d486ee5f34825
5,525
cpp
C++
src/Notifier.cpp
john-gress/QueueNado
7bcd499f2a3b69c65c01203fad5922e545266fcd
[ "MIT" ]
7
2018-03-31T04:40:50.000Z
2021-03-02T22:39:03.000Z
src/Notifier.cpp
LogRhythm/QueueNado
7bcd499f2a3b69c65c01203fad5922e545266fcd
[ "MIT" ]
13
2016-03-01T18:03:25.000Z
2018-02-09T22:01:24.000Z
src/Notifier.cpp
john-gress/QueueNado
7bcd499f2a3b69c65c01203fad5922e545266fcd
[ "MIT" ]
4
2018-06-18T16:58:16.000Z
2020-10-16T18:27:32.000Z
/* * File: Notifier.cpp * Author: Craig Cogdill * Created: August 13, 2015 3:20PM */ #include "Notifier.h" #include <g3log/g3log.hpp> #include <mutex> #include <memory> #include <Shotgun.h> #include <Vampire.h> #include <StopWatch.h> std::unique_ptr<Notifier> Notifier::CreateNotifier(const std::string& notifierQueue, const std::string& handshakeQueue, const size_t handshakeCount) { auto notifier = std::unique_ptr<Notifier>(new Notifier(notifierQueue, handshakeQueue)); if (notifier->Initialize(handshakeCount)) { return std::move(notifier); } std::unique_ptr<Notifier> deadNotifier; return deadNotifier; } /** * @param notifierQueue to send notification on * @param handshakeQueue to receive handshake confirmation on */ Notifier::Notifier(const std::string& notifierQueue, const std::string& handshakeQueue) : mNotifierQueueName(notifierQueue), mHandshakeQueueName(handshakeQueue) {}; Notifier::~Notifier() { Reset(); } /* * Initialize the mutex-guarded Shotgun-Alien * queue by "aiming" it at the Notifier * ipc file * * @return bool, whether or not both queues are initialized */ bool Notifier::Initialize(const size_t handshakeCount) { std::lock_guard<std::mutex> guard(gLock); gHandshakeCount = handshakeCount; if (gHandshakeQueue.get() == nullptr) { gHandshakeQueue = std::move(CreateHandshakeQueue()); } if (gQueue.get() == nullptr) { gQueue.reset(new Shotgun); try { gQueue->Aim(GetNotifierQueueName()); } catch (std::exception& e) { LOG(WARNING) << "Caught exception: " << e.what(); Reset(); } } return (gQueue.get() != nullptr) && (gHandshakeQueue.get() != nullptr); } /* * Initialize a Vampire queue to get confirmation from * listeners that they received the notification * * @return unique_ptr to Vampire handshake queue */ std::unique_ptr<Vampire> Notifier::CreateHandshakeQueue() { const std::string handshakeQueueName = GetHandshakeQueueName(); LOG(INFO) << "Creating Vampire with queue: " << handshakeQueueName; const auto size = 100; auto target = std::unique_ptr<Vampire>(new Vampire(handshakeQueueName)); target->SetHighWater(size); target->SetOwnSocket(true); if (!target->PrepareToBeShot()) { std::unique_ptr<Vampire> miss; LOG(WARNING) << "Unable to bind socket: " << handshakeQueueName; return miss; } return target; } /* * Fire a message from the Shotgun to be * read by the queue subscriber. Then wait for listeners * to confirm they received the notification * * @param string to be sent to listeners * @return number of confirmed updates */ size_t Notifier::Notify(const std::string& message) { std::vector<std::string> bullets; bullets.push_back(message); return Notify(bullets); } /* * Fire a dummy message from the Shotgun to be * read by the queue subscriber. Then wait for listeners * to confirm they received the notification * * @return number of confirmed updates */ size_t Notifier::Notify() { return Notify(kNotifyMessage); } /* * Fire a message from the Shotgun to be * read by the queue subscriber. Then wait for listeners * to confirm they received the notification * * @param vector of strings to be sent to the listeners * @return number of confirmed updates */ size_t Notifier::Notify(const std::vector<std::string>& messages) { std::lock_guard<std::mutex> guard(gLock); std::vector<std::string> bullets; bullets.push_back("dummy"); for (auto& msg : messages) { bullets.push_back(msg); } if (QueuesAreUnitialized()) { LOG(WARNING) << "Uninitialized notifier queues"; return {0}; } LOG(INFO) << "Notifier: Sending " << bullets.size() << " messages"; gQueue->Fire(bullets); size_t confirmed = ReceiveConfirmation(); LOG(INFO) << "Notifier received " << confirmed << " handshakes"; return {confirmed}; } /* * Receive confirmation from listener threads that * they have been notified successfully * * @return size_t, number of confirmations received */ size_t Notifier::ReceiveConfirmation() { StopWatch waitCheck; size_t responses = 0; while (responses < gHandshakeCount && waitCheck.ElapsedSec() < gMaxTimeoutInSec) { std::string msg; if (gHandshakeQueue->GetShot(msg, gMaxTimeoutInSec)) { LOG(INFO) << "Received update confirmation from thread #" << msg << ", response count #" << ++responses; } } const bool goodEnough = waitCheck.ElapsedSec() < gMaxTimeoutInSec || responses == gHandshakeCount; LOG_IF(WARNING, !goodEnough) << "Listener confirmation timed out after" << gMaxTimeoutInSec << "seconds... " << responses << "/" << gHandshakeCount << " replied"; return responses; } /* * Reset the Shotgun-Alien queue to nullptr */ void Notifier::Reset() { std::lock_guard<std::mutex> guard(gLock); gQueue.reset(nullptr); gHandshakeQueue.reset(nullptr); } /* * @return name of notifier ipc queue taken from ExternalConnections */ std::string Notifier::GetNotifierQueueName() { return mNotifierQueueName; } /* * @return name of handshake ipc queue taken from ExternalConnections */ std::string Notifier::GetHandshakeQueueName() { return mHandshakeQueueName; } /* * @return whether both of the queues are initialized */ bool Notifier::QueuesAreUnitialized() { return (gQueue.get() == nullptr || gHandshakeQueue.get() == nullptr); }
28.926702
151
0.682172
[ "vector" ]
be18d3ba0ec4fcfa7beb4da920e0d7cc213d07ea
16,927
cc
C++
engine/source/gui/messageVector.cc
close-code/Torque2D
ad141fc7b5f28b75f727ef29dcc93aafbb3f5aa3
[ "MIT" ]
1,309
2015-01-01T02:46:14.000Z
2022-03-14T04:56:02.000Z
engine/source/gui/messageVector.cc
close-code/Torque2D
ad141fc7b5f28b75f727ef29dcc93aafbb3f5aa3
[ "MIT" ]
155
2015-01-11T19:26:32.000Z
2021-11-22T04:08:55.000Z
engine/source/gui/messageVector.cc
close-code/Torque2D
ad141fc7b5f28b75f727ef29dcc93aafbb3f5aa3
[ "MIT" ]
1,595
2015-01-01T23:19:48.000Z
2022-02-17T07:00:52.000Z
//----------------------------------------------------------------------------- // Copyright (c) 2013 GarageGames, LLC // // 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 "gui/messageVector.h" #include "io/fileObject.h" IMPLEMENT_CONOBJECT(MessageVector); //-------------------------------------- Console functions ConsoleMethod( MessageVector, clear, void, 2, 2, "() Clear the message vector.\n" "@return No return value") { object->clear(); } ConsoleMethod( MessageVector, pushBackLine, void, 4, 4, "( msg [ , tag ] ) Use the pushBackLine method to push a line onto the back of the list.\n" "@param msg The text to add to this control.\n" "@param tag An optional tag to tag this line with. If not tag is supplied, a tag of 0 is used.\n" "@return No return value.\n" "@sa popBackLine, popFrontLine, insertLine, pushFrontLine") { U32 tag = 0; if (argc == 4) tag = dAtoi(argv[3]); object->pushBackLine(argv[2], tag); } ConsoleMethod( MessageVector, popBackLine, bool, 2, 2, "() Use the popBackLine method to pop a line from the back of the list; destroys the line.\n" "@return No return value.\n" "@sa insertLine, pushBackLine, pushFrontLine") { if (object->getNumLines() == 0) { Con::errorf(ConsoleLogEntry::General, "MessageVector::popBackLine(): underflow"); return false; } object->popBackLine(); return true; } ConsoleMethod( MessageVector, pushFrontLine, void, 3, 4, "( msg [ , tag ] ) Use the pushFrontLine method to push a line onto the front of the vector.\n" "@param msg The text to add to this control.\n" "@param tag An optional tag to tag this line with. If not tag is supplied, a tag of 0 is used.\n" "@return No return value.\n" "@sa popBackLine, popFrontLine, insertLine, pushBackLine") { U32 tag = 0; if (argc == 4) tag = dAtoi(argv[3]); object->pushFrontLine(argv[2], tag); } ConsoleMethod( MessageVector, popFrontLine, bool, 2, 2,"() Use the popFrontLine method to pop a line from the front of the vector, destroying the line.\n" "@return No return value.\n" "@sa insertLine, pushBackLine, pushFrontLine") { if (object->getNumLines() == 0) { Con::errorf(ConsoleLogEntry::General, "MessageVector::popFrontLine(): underflow"); return false; } object->popFrontLine(); return true; } ConsoleMethod( MessageVector, insertLine, bool, 4, 5, "( pos , msg [ , tag ] ) Use the insertLine method to insert a new line into the vector at the specified position. An optional tag may also be applied.\n" "@param pos The line at which to insert the new text.\n" "@param msg The text to add to this control.\n" "@param tag An optional tag to tag this line with. If not tag is supplied, a tag of 0 is used.\n" "@return No return value.\n" "@sa pushBackLine, pushFrontLine") { U32 pos = U32(dAtoi(argv[2])); if (pos > object->getNumLines()) return false; S32 tag = 0; if (argc == 5) tag = dAtoi(argv[4]); object->insertLine(pos, argv[3], tag); return true; } ConsoleMethod( MessageVector, deleteLine, bool, 3, 3, "( lineIndex ) Delete the line at the specified position.\n" "@param lineIndex The line to delete in this vector.\n" "@return No return value.\n" "@sa insertLine, pushBackLine, pushFrontLine") { U32 pos = U32(dAtoi(argv[2])); if (pos >= object->getNumLines()) return false; object->deleteLine(pos); return true; } ConsoleMethod( MessageVector, dump, void, 3, 4, "( filename [ , header ] ) Dump the message vector to a file, optionally prefixing the file with a header.\n" "@param filename The file to dump this vector to.\n" "@param header An optional string containing data to dump to the new file prior to dumping the vector.\n" "@return No return value") { if ( argc == 4 ) object->dump( argv[2], argv[3] ); else object->dump( argv[2] ); } ConsoleMethod( MessageVector, getNumLines, S32, 2, 2, "() Use the getNumLines method to get the number of lines in the vector.\n" "@return Returns an integer value equal to the line count for this vector.\n" "@sa insertLine, pushBackLine, pushFrontLine") { return object->getNumLines(); } ConsoleMethod( MessageVector, getLineTextByTag, const char*, 3, 3, "( tag ) Use the getLineTextByTag method to scan through the lines in the vector, returning the first line that has a matching tag.\n" "@param tag An special marker that may have been used when creating lines in the vector.\n" "@return Returns the contents of the first line found with a matching tag or NULL indicating no match.\n" "@sa insertLine, pushBackLine, pushFrontLine") { U32 tag = dAtoi(argv[2]); for(U32 i = 0; i < object->getNumLines(); i++) if(object->getLine(i).messageTag == tag) return object->getLine(i).message; return ""; } ConsoleMethod( MessageVector, getLineIndexByTag, S32, 3, 3, "( tag ) Scan through the vector, returning the line number of the first line that matches the specified tag; else returns -1 if no match was found.\n" "@param tag A special marker, possibly embedded in one or more lines in the vector.\n" "@return Returns the line number of the first line found with the specified tag, otherwise returns -1.\n" "@sa insertLine, pushBackLine, pushFrontLine") { U32 tag = dAtoi(argv[2]); for(U32 i = 0; i < object->getNumLines(); i++) if(object->getLine(i).messageTag == tag) return i; return -1; } ConsoleMethod( MessageVector, getLineText, const char*, 3, 3, "( index ) Use the getLineIndex method to get the text at a specified line.\n" "@param index The index in the vector from which to retrieve a line of text.\n" "@return Returns the text at the specified line, or NULL indicating a bad index.\n" "@sa insertLine, pushBackLine, pushFrontLine") { U32 pos = U32(dAtoi(argv[2])); if (pos >= object->getNumLines()) { Con::errorf(ConsoleLogEntry::General, "MessageVector::getLineText(con): out of bounds line"); return ""; } return object->getLine(pos).message; } ConsoleMethod( MessageVector, getLineTag, S32, 3, 3, "(line) Use the getLineTag method to retrieve the tag for the specified line.\n" "@param line Line to search for tag in.\n" "@return Returns a tag value or 0 indicating no tag found.\n" "@sa insertLine, pushBackLine, pushFrontLine") { U32 pos = U32(dAtoi(argv[2])); if (pos >= object->getNumLines()) { Con::errorf(ConsoleLogEntry::General, "MessageVector::getLineTag(con): out of bounds line"); return 0; } return object->getLine(pos).messageTag; } //-------------------------------------------------------------------------- MessageVector::MessageVector() { VECTOR_SET_ASSOCIATION(mMessageLines); VECTOR_SET_ASSOCIATION(mSpectators); } //-------------------------------------------------------------------------- MessageVector::~MessageVector() { for (U32 i = 0; i < (U32)mMessageLines.size(); i++) { char* pDelete = const_cast<char*>(mMessageLines[i].message); delete [] pDelete; mMessageLines[i].message = 0; mMessageLines[i].messageTag = 0xFFFFFFFF; } mMessageLines.clear(); } //-------------------------------------------------------------------------- void MessageVector::initPersistFields() { Parent::initPersistFields(); } //-------------------------------------------------------------------------- bool MessageVector::onAdd() { return Parent::onAdd(); } //-------------------------------------------------------------------------- void MessageVector::onRemove() { // Delete all the lines from the observers, and then forcibly detatch ourselves // for (S32 i = mMessageLines.size() - 1; i >= 0; i--) spectatorMessage(LineDeleted, i); spectatorMessage(VectorDeletion, 0); mSpectators.clear(); Parent::onRemove(); } //-------------------------------------------------------------------------- void MessageVector::pushBackLine(const char* newMessage, const S32 newMessageTag) { insertLine(mMessageLines.size(), newMessage, newMessageTag); } void MessageVector::popBackLine() { AssertFatal(mMessageLines.size() != 0, "MessageVector::popBackLine: nothing to pop!"); if (mMessageLines.size() == 0) return; deleteLine(mMessageLines.size() - 1); } void MessageVector::clear() { while(mMessageLines.size()) deleteLine(mMessageLines.size() - 1); } //-------------------------------------------------------------------------- void MessageVector::pushFrontLine(const char* newMessage, const S32 newMessageTag) { insertLine(0, newMessage, newMessageTag); } void MessageVector::popFrontLine() { AssertFatal(mMessageLines.size() != 0, "MessageVector::popBackLine: nothing to pop!"); if (mMessageLines.size() == 0) return; deleteLine(0); } //-------------------------------------------------------------------------- void MessageVector::insertLine(const U32 position, const char* newMessage, const S32 newMessageTag) { AssertFatal(position >= 0 && position <= (U32)mMessageLines.size(), "MessageVector::insertLine: out of range position!"); AssertFatal(newMessage != NULL, "Error, no message to insert!"); U32 len = dStrlen(newMessage) + 1; char* copy = new char[len]; dStrcpy(copy, newMessage); mMessageLines.insert(position); mMessageLines[position].message = copy; mMessageLines[position].messageTag = newMessageTag; // Notify of insert spectatorMessage(LineInserted, position); } //-------------------------------------------------------------------------- void MessageVector::deleteLine(const U32 position) { AssertFatal(position >= 0 && position < (U32)mMessageLines.size(), "MessageVector::deleteLine: out of range position!"); char* pDelete = const_cast<char*>(mMessageLines[position].message); delete [] pDelete; mMessageLines[position].message = NULL; mMessageLines[position].messageTag = 0xFFFFFFFF; mMessageLines.erase(position); // Notify of delete spectatorMessage(LineDeleted, position); } //-------------------------------------------------------------------------- bool MessageVector::dump( const char* filename, const char* header ) { Con::printf( "Dumping message vector %s to %s...", getName(), filename ); FileObject file; if ( !file.openForWrite( filename ) ) return( false ); // If passed a header line, write it out first: if ( header ) file.writeLine( (const U8*) header ); // First write out the record count: char* lineBuf = (char*) dMalloc( 10 ); dSprintf( lineBuf, 10, "%d", mMessageLines.size() ); file.writeLine( (const U8*) lineBuf ); // Write all of the lines of the message vector: U32 len; for ( U32 i = 0; i < (U32)mMessageLines.size(); i++ ) { len = ( dStrlen( mMessageLines[i].message ) * 2 ) + 10; lineBuf = (char*) dRealloc( lineBuf, len ); dSprintf( lineBuf, len, "%d ", mMessageLines[i].messageTag ); expandEscape( lineBuf + dStrlen( lineBuf ), mMessageLines[i].message ); file.writeLine( (const U8*) lineBuf ); } file.close(); return( true ); } //-------------------------------------------------------------------------- void MessageVector::registerSpectator(SpectatorCallback callBack, void *spectatorKey) { AssertFatal(callBack != NULL, "Error, must have a callback!"); // First, make sure that this hasn't been registered already... U32 i; for (i = 0; i < (U32)mSpectators.size(); i++) { AssertFatal(mSpectators[i].key != spectatorKey, "Error, spectator key already registered!"); if (mSpectators[i].key == spectatorKey) return; } mSpectators.increment(); mSpectators.last().callback = callBack; mSpectators.last().key = spectatorKey; // Need to message this spectator of all the lines currently inserted... for (i = 0; i < (U32)mMessageLines.size(); i++) { (*mSpectators.last().callback)(mSpectators.last().key, LineInserted, i); } } void MessageVector::unregisterSpectator(void * spectatorKey) { for (U32 i = 0; i < (U32)mSpectators.size(); i++) { if (mSpectators[i].key == spectatorKey) { // Need to message this spectator of all the lines currently inserted... for (S32 j = mMessageLines.size() - 1; j >= 0 ; j--) { (*mSpectators[i].callback)(mSpectators[i].key, LineDeleted, j); } mSpectators.erase(i); return; } } AssertFatal(false, "MessageVector::unregisterSpectator: tried to unregister a spectator that isn't subscribed!"); Con::errorf(ConsoleLogEntry::General, "MessageVector::unregisterSpectator: tried to unregister a spectator that isn't subscribed!"); } void MessageVector::spectatorMessage(MessageCode code, const U32 arg) { for (U32 i = 0; i < (U32)mSpectators.size(); i++) { (*mSpectators[i].callback)(mSpectators[i].key, code, arg); } }
41.795062
212
0.524428
[ "object", "vector" ]
be1a680a5ca50cb581c261fdc79e600f3fa43ff3
709
cpp
C++
platforms/leetcode/0209_truncate_sentence.cpp
idfumg/algorithms
06f85c5a1d07a965df44219b5a6bf0d43a129256
[ "MIT" ]
2
2020-09-17T09:04:00.000Z
2020-11-20T19:43:18.000Z
platforms/leetcode/0209_truncate_sentence.cpp
idfumg/algorithms
06f85c5a1d07a965df44219b5a6bf0d43a129256
[ "MIT" ]
null
null
null
platforms/leetcode/0209_truncate_sentence.cpp
idfumg/algorithms
06f85c5a1d07a965df44219b5a6bf0d43a129256
[ "MIT" ]
null
null
null
#include "../../template.hpp" string sol(const string& s, const int k) { vector<string> words; string word; istringstream is(s); while (is >> word) { words.push_back(word); } while (words.size() > k) words.pop_back(); string ans; for (int i = 0; i < words.size(); ++i) { ans += words[i]; if (i != words.size() - 1) ans += ' '; } return ans; } int main() { TimeMeasure _; //__x(); cout << sol("Hello how are you Contestant", 4) << endl; // "Hello how are you" cout << sol("What is the solution to this problem", 4) << endl; // "What is the solution" cout << sol("chopper is not a tanuki", 5) << endl; // "chopper is not a tanuki" }
29.541667
93
0.551481
[ "vector" ]
be24494b7107a740e5f041520921d14c284d89a4
750
cpp
C++
framework/CoreDataDrivenSequence/Sources/ModuleDDSequence.cpp
Daniel-Mietchen/kigs
92ab6deaf3e947465781a400c5a791ee171876c8
[ "MIT" ]
38
2020-05-08T13:39:57.000Z
2022-03-28T05:58:41.000Z
framework/CoreDataDrivenSequence/Sources/ModuleDDSequence.cpp
Daniel-Mietchen/kigs
92ab6deaf3e947465781a400c5a791ee171876c8
[ "MIT" ]
3
2020-06-01T14:12:36.000Z
2020-06-24T13:05:21.000Z
framework/CoreDataDrivenSequence/Sources/ModuleDDSequence.cpp
Daniel-Mietchen/kigs
92ab6deaf3e947465781a400c5a791ee171876c8
[ "MIT" ]
16
2020-05-04T19:20:35.000Z
2022-01-25T08:31:29.000Z
#include "ModuleDDSequence.h" #include "BaseDDSequence.h" #include "BumperDDSequence.h" IMPLEMENT_CLASS_INFO(ModuleDDSequence); ModuleDDSequence::ModuleDDSequence(const kstl::string& name, CLASS_NAME_TREE_ARG) : ModuleBase(name, PASS_CLASS_NAME_TREE_ARG) { } void ModuleDDSequence::Init(KigsCore* core, const kstl::vector<CoreModifiableAttribute*>* params) { BaseInit(core, "ModuleDDSequence", params); // Init system independant classes DECLARE_FULL_CLASS_INFO(core, BaseDDSequence, BaseDDSequence, CoreDataDrivenSequence) DECLARE_FULL_CLASS_INFO(core, BumperDDSequence, BumperDDSequence, CoreDataDrivenSequence) } void ModuleDDSequence::Update(const Timer& timer, void* addParam) { } void ModuleDDSequence::Close() { BaseClose(); }
23.4375
97
0.801333
[ "vector" ]
be293d919b817e3e747d48b878ec6a9df314549b
314
cc
C++
majority-element.cc
ArCan314/leetcode
8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd
[ "MIT" ]
null
null
null
majority-element.cc
ArCan314/leetcode
8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd
[ "MIT" ]
null
null
null
majority-element.cc
ArCan314/leetcode
8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd
[ "MIT" ]
null
null
null
#include <vector> #include <unordered_map> class Solution { public: int majorityElement(std::vector<int>& nums) { std::unordered_map<int, int> dict; for (const int num : nums) if (int i = ++dict[num]; i > nums.size() / 2) return num; return 0; } };
22.428571
57
0.538217
[ "vector" ]
be34f1086d1c38240777960c21044afff7dbb081
2,280
cpp
C++
code/leetcode/src/0117.Populating-Next-Right-Pointers-in-Each-Node-II.cpp
taseikyo/til
8f703e69a49cbd9854062b102ba307c775d43a56
[ "MIT" ]
1
2021-09-01T14:39:12.000Z
2021-09-01T14:39:12.000Z
code/leetcode/src/0117.Populating-Next-Right-Pointers-in-Each-Node-II.cpp
taseikyo/til
8f703e69a49cbd9854062b102ba307c775d43a56
[ "MIT" ]
null
null
null
code/leetcode/src/0117.Populating-Next-Right-Pointers-in-Each-Node-II.cpp
taseikyo/til
8f703e69a49cbd9854062b102ba307c775d43a56
[ "MIT" ]
null
null
null
/** * @authors Lewis Tian (taseikyo@gmail.com) * @date 2020-06-24 14:57:55 * @link github.com/taseikyo */ /* // Definition for a Node. class Node { public: int val; Node* left; Node* right; Node* next; Node() : val(0), left(NULL), right(NULL), next(NULL) {} Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} Node(int _val, Node* _left, Node* _right, Node* _next) : val(_val), left(_left), right(_right), next(_next) {} }; */ class Solution { public: Node* connect(Node* root) { if (!root) return root; Node* parent = root; vector<Node*> v; while (parent != nullptr || !v.empty()) { if (!parent) { parent = v.back(); v.pop_back(); continue; } Node* cur = parent; while (cur) { Node* p = nullptr; if (cur->left && cur->right) { // 1. 左右 cur->left->next = cur->right; p = cur->right; } else if (cur->left) { // 2. 左 p = cur->left; } else if (cur->right) { // 3. 右 p = cur->right; } // 这里有个问题是 a b c,a c 有子节点,而 b 没有子节点 // 导致 a 的孩子链接中断 // if (p && cur->next) { // if (cur->next->left) { // p->next = cur->next->left; // } else if (cur->next->right) { // p->next = cur->next->right; // } // } // cur = cur->next; Node* tmp = cur->next; if (p) { while (tmp && !tmp->left && !tmp->right) { tmp = tmp->next; } if (tmp) { if (tmp->left) { p->next = tmp->left; } else if (tmp->right) { p->next = tmp->right; } } } cur = tmp; } if (parent->right) { v.push_back(parent->right); } parent = parent->left; } return root; } }; class Solution { public: Node* connect(Node* root) { if (nullptr == root) return nullptr; queue<Node*> nodes; nodes.push(root); nodes.push(nullptr); while (!nodes.empty()) { Node* tmp = nodes.front(); nodes.pop(); // 当 tmp 为空时,说明本层已经结束,需要为下一层添加一个结束标识 if (nullptr == tmp) { if (!nodes.empty()) { nodes.push(nullptr); } continue; } tmp->next = nodes.front(); if (tmp->left != nullptr) { nodes.push(tmp->left); } if (tmp->right != nullptr) { nodes.push(tmp->right); } } return root; } };
19
70
0.507456
[ "vector" ]
be372bb8555ffa5552d3b91af27ce6b78aa7da89
3,460
cpp
C++
indra/llcommon/tests/llframetimer_test.cpp
SaladDais/LSO2-VM-Performance
d7ec9ad9daa9a2c9e48c5f06cd768606e3e50638
[ "ISC" ]
1
2022-01-29T07:10:03.000Z
2022-01-29T07:10:03.000Z
indra/llcommon/tests/llframetimer_test.cpp
SaladDais/LSO2-VM-Performance
d7ec9ad9daa9a2c9e48c5f06cd768606e3e50638
[ "ISC" ]
null
null
null
indra/llcommon/tests/llframetimer_test.cpp
SaladDais/LSO2-VM-Performance
d7ec9ad9daa9a2c9e48c5f06cd768606e3e50638
[ "ISC" ]
1
2021-10-01T22:22:27.000Z
2021-10-01T22:22:27.000Z
/** * @file lltiming_test.cpp * @date 2006-07-23 * @brief Tests the timers. * * $LicenseInfo:firstyear=2006&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * 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; * version 2.1 of the License only. * * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "linden_common.h" #include "../llframetimer.h" #include "../llsd.h" #include "../test/lltut.h" namespace tut { struct frametimer_test { frametimer_test() { LLFrameTimer::updateFrameTime(); } }; typedef test_group<frametimer_test> frametimer_group_t; typedef frametimer_group_t::object frametimer_object_t; tut::frametimer_group_t frametimer_instance("LLFrameTimer"); template<> template<> void frametimer_object_t::test<1>() { F64 seconds_since_epoch = LLFrameTimer::getTotalSeconds(); LLFrameTimer timer; timer.setExpiryAt(seconds_since_epoch); F64 expires_at = timer.expiresAt(); ensure_distance( "set expiry matches get expiry", expires_at, seconds_since_epoch, 0.001); } template<> template<> void frametimer_object_t::test<2>() { F64 seconds_since_epoch = LLFrameTimer::getTotalSeconds(); seconds_since_epoch += 10.0; LLFrameTimer timer; timer.setExpiryAt(seconds_since_epoch); F64 expires_at = timer.expiresAt(); ensure_distance( "set expiry matches get expiry 1", expires_at, seconds_since_epoch, 0.001); seconds_since_epoch += 10.0; timer.setExpiryAt(seconds_since_epoch); expires_at = timer.expiresAt(); ensure_distance( "set expiry matches get expiry 2", expires_at, seconds_since_epoch, 0.001); } template<> template<> void frametimer_object_t::test<3>() { clock_t t1 = clock(); ms_sleep(200); clock_t t2 = clock(); clock_t elapsed = t2 - t1 + 1; std::cout << "Note: using clock(), ms_sleep() actually took " << (long)elapsed << "ms" << std::endl; F64 seconds_since_epoch = LLFrameTimer::getTotalSeconds(); seconds_since_epoch += 2.0; LLFrameTimer timer; timer.setExpiryAt(seconds_since_epoch); /* * Note that the ms_sleep(200) below is only guaranteed to return * in 200ms _or_more_, so it should be true that by the 10th * iteration we've gotten to the 2 seconds requested above * and the timer should expire, but it can expire in fewer iterations * if one or more of the ms_sleep calls takes longer. * (as it did when we moved to Mac OS X 10.10) */ int iterations_until_expiration = 0; while ( !timer.hasExpired() ) { ms_sleep(200); LLFrameTimer::updateFrameTime(); iterations_until_expiration++; } ensure("timer took too long to expire", iterations_until_expiration <= 10); } /* template<> template<> void frametimer_object_t::test<4>() { } */ }
28.360656
102
0.717052
[ "object" ]
be3ac413d9eface9b82e4ba2f7835d7d92b867f4
5,953
cpp
C++
src/mame/drivers/fidel_eldorado.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/mame/drivers/fidel_eldorado.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/mame/drivers/fidel_eldorado.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:hap // thanks-to:bataais /****************************************************************************** Fidelity Eldorado Chess Challenger (model 6119) Hardware notes: - PCB label CXG262-600-001, CXG262-600-101 - TMP80C49AP6-6744 MCU, 2KB internal ROM, 6MHz XTAL - buzzer, 16 leds, 8*8 chessboard buttons The chess engine is by Ron Nelson. The hardware was made by CXG for Fidelity, as seen on the PCB and also confirmed by Ron Nelson. ******************************************************************************/ #include "emu.h" #include "cpu/mcs48/mcs48.h" #include "machine/sensorboard.h" #include "sound/dac.h" #include "video/pwm.h" #include "speaker.h" // internal artwork #include "fidel_eldorado.lh" // clickable namespace { class eldorado_state : public driver_device { public: eldorado_state(const machine_config &mconfig, device_type type, const char *tag) : driver_device(mconfig, type, tag), m_maincpu(*this, "maincpu"), m_display(*this, "display"), m_board(*this, "board"), m_dac(*this, "dac"), m_inputs(*this, "IN.0") { } // machine configs void eldorado(machine_config &config); protected: virtual void machine_start() override; private: // devices/pointers required_device<mcs48_cpu_device> m_maincpu; required_device<pwm_display_device> m_display; required_device<sensorboard_device> m_board; required_device<dac_bit_interface> m_dac; required_ioport m_inputs; // I/O handlers void update_display(); void mux_w(u8 data); u8 mux_r(); void control_w(u8 data); DECLARE_READ_LINE_MEMBER(t0_r); u8 input_r(); bool m_kp_select = false; u16 m_inp_mux = 0; u8 m_led_select = 0; }; void eldorado_state::machine_start() { // register for savestates save_item(NAME(m_kp_select)); save_item(NAME(m_inp_mux)); save_item(NAME(m_led_select)); } /****************************************************************************** I/O ******************************************************************************/ void eldorado_state::update_display() { m_display->matrix(m_led_select, m_inp_mux); } void eldorado_state::mux_w(u8 data) { // D0-D7: input mux, led data m_inp_mux = ~data; update_display(); } u8 eldorado_state::mux_r() { return ~m_inp_mux; } void eldorado_state::control_w(u8 data) { // P24: speaker out m_dac->write(BIT(~data, 4)); // P25,P26: led select m_led_select = ~data >> 5 & 3; update_display(); // P27: keypad select m_kp_select = !bool(data & 0x80); } READ_LINE_MEMBER(eldorado_state::t0_r) { // T0: P27 return m_kp_select ? 0 : 1; } u8 eldorado_state::input_r() { u8 data = 0; // P10-P17: multiplexed inputs // read chessboard buttons for (int i = 0; i < 8; i++) if (BIT(m_inp_mux, i)) data |= m_board->read_file(i); // read sidepanel keypad if (m_kp_select) data |= m_inputs->read(); return ~data; } /****************************************************************************** Input Ports ******************************************************************************/ static INPUT_PORTS_START( eldorado ) PORT_START("IN.0") PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_CODE(KEYCODE_1) PORT_CODE(KEYCODE_1_PAD) PORT_NAME("Reverse / Pawn") PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_CODE(KEYCODE_2) PORT_CODE(KEYCODE_2_PAD) PORT_NAME("Move / Knight") PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_CODE(KEYCODE_3) PORT_CODE(KEYCODE_3_PAD) PORT_NAME("Sound / Bishop") PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_CODE(KEYCODE_4) PORT_CODE(KEYCODE_4_PAD) PORT_NAME("Level / Rook") PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_CODE(KEYCODE_5) PORT_CODE(KEYCODE_5_PAD) PORT_NAME("Verify / Queen") PORT_BIT(0x20, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_CODE(KEYCODE_6) PORT_CODE(KEYCODE_6_PAD) PORT_NAME("Problem / King") PORT_BIT(0x40, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_CODE(KEYCODE_DEL) PORT_CODE(KEYCODE_BACKSPACE) PORT_NAME("Clear") PORT_BIT(0x80, IP_ACTIVE_HIGH, IPT_KEYPAD) PORT_CODE(KEYCODE_N) PORT_NAME("New Game") INPUT_PORTS_END /****************************************************************************** Machine Configs ******************************************************************************/ void eldorado_state::eldorado(machine_config &config) { /* basic machine hardware */ I8049(config, m_maincpu, 6_MHz_XTAL); m_maincpu->p1_in_cb().set(FUNC(eldorado_state::input_r)); m_maincpu->p2_out_cb().set(FUNC(eldorado_state::control_w)); m_maincpu->bus_in_cb().set(FUNC(eldorado_state::mux_r)); m_maincpu->bus_out_cb().set(FUNC(eldorado_state::mux_w)); m_maincpu->t0_in_cb().set(FUNC(eldorado_state::t0_r)); SENSORBOARD(config, m_board).set_type(sensorboard_device::BUTTONS); m_board->init_cb().set(m_board, FUNC(sensorboard_device::preset_chess)); m_board->set_delay(attotime::from_msec(150)); /* video hardware */ PWM_DISPLAY(config, m_display).set_size(2, 8); config.set_default_layout(layout_fidel_eldorado); /* sound hardware */ SPEAKER(config, "speaker").front_center(); DAC_1BIT(config, m_dac).add_route(ALL_OUTPUTS, "speaker", 0.25); } /****************************************************************************** ROM Definitions ******************************************************************************/ ROM_START( feldo ) ROM_REGION( 0x0800, "maincpu", 0 ) ROM_LOAD("100-1027a01", 0x0000, 0x0800, CRC(3b93b6d2) SHA1(353a741624b4c7fd74a0cf601e2e52f9914b58b8) ) ROM_END } // anonymous namespace /****************************************************************************** Drivers ******************************************************************************/ // YEAR NAME PARENT COMPAT MACHINE INPUT CLASS INIT COMPANY, FULLNAME, FLAGS CONS( 1990, feldo, 0, 0, eldorado, eldorado, eldorado_state, empty_init, "Fidelity Electronics / CXG Systems", "Eldorado Chess Challenger", MACHINE_SUPPORTS_SAVE | MACHINE_CLICKABLE_ARTWORK )
28.758454
203
0.619856
[ "model" ]
be4f965f6853be0c311ec442c7a7055ab009b13d
3,215
cpp
C++
code/covidm_for_fitting/model_v2/reporter.cpp
yangclaraliu/COVID_Vac_Delay
0c3a88ab26d2983b809779eda97194f5d9b9cb51
[ "CC0-1.0" ]
1
2021-11-04T21:05:34.000Z
2021-11-04T21:05:34.000Z
code/covidm_for_fitting/model_v2/reporter.cpp
yangclaraliu/COVID_Vac_Delay
0c3a88ab26d2983b809779eda97194f5d9b9cb51
[ "CC0-1.0" ]
null
null
null
code/covidm_for_fitting/model_v2/reporter.cpp
yangclaraliu/COVID_Vac_Delay
0c3a88ab26d2983b809779eda97194f5d9b9cb51
[ "CC0-1.0" ]
null
null
null
// reporter.cpp #include "reporter.h" #include "parameters.h" #include <numeric> Reporter::Reporter(Parameters& P) : t0(P.time0), n_times((unsigned int)(P.time1 - P.time0) + 1), n_populations(P.pop.size()), n_age_groups(P.pop[0].size.size()), col_names(ref_col_names), user_defined_offset(ref_col_names.size()) { if (P.time_step != 1. / P.report_every) throw logic_error("Reporter requires P.time_step = 1 / P.report_every."); // Create space for built-in + user-process compartments data = vector<vector<double>>( col_names.size() + P.processes.recording_count, vector<double>(n_times * n_populations * n_age_groups, 0.) ); // User-defined compartments for (auto pid : P.processes.prevalence_states) { col_names.push_back(P.processes.state_names[pid] + "_p"); } for (auto iid : P.processes.incidence_states) { col_names.push_back(P.processes.state_names[iid] + "_i"); } for (auto oid : P.processes.outcidence_states) { col_names.push_back(P.processes.state_names[oid] + "_o"); } } // Access data, summed over populations and groups double Reporter::operator()(string compartment, double t, initializer_list<unsigned int> pops, initializer_list<unsigned int> groups) { // Locate compartment auto cc = find(col_names.begin(), col_names.end(), compartment); if (cc == col_names.end()) { cout << "No such compartment " << compartment << "\n" << flush; throw logic_error("No such compartment: " + compartment); } unsigned int c = cc - col_names.begin(); // Define populations and groups to loop over // TODO optimize... vector<unsigned int> pp = pops; vector<unsigned int> gg = groups; if (pp.empty()) { pp.assign(n_populations, 0); iota(pp.begin(), pp.end(), 0); } if (gg.empty()) { gg.assign(n_age_groups, 0); iota(gg.begin(), gg.end(), 0); } // Sum over populations and groups double x = 0.0; for (auto p : pp) for (auto g : gg) x += (*this)(t, p, g, c); return x; } // Save data to file void Reporter::Save(string basename, unsigned long int seed) { ofstream fout(basename + ".txt"); // Output header fout << "# t0 " << t0 << " n_times " << n_times << " n_populations " << n_populations << " n_groups " << n_age_groups << " seed " << seed << "\n"; for (unsigned int cd = 0; cd < col_names.size(); ++cd) fout << col_names[cd] << (cd == col_names.size() - 1 ? "" : "\t"); if (obs.size() > 0) for (unsigned int co = 0; co < obs.size(); ++co) fout << "\tobs" << co; fout << "\n"; // Output data for (unsigned int r = 0; r < data[0].size(); ++r) { for (unsigned int cd = 0; cd < data.size(); ++cd) fout << data[cd][r] << (cd == data.size() - 1 ? "" : "\t"); if (obs.size() > 0) for (unsigned int co = 0; co < obs.size(); ++co) fout << "\t" << obs[co][r]; fout << "\n"; } fout.close(); // Output csv if (!csv.empty()) { ofstream fcsv(basename + ".csv"); fcsv << csv; } }
29.495413
150
0.56703
[ "vector" ]
be56610421d2289b180b3aad227e9c052192f35a
1,375
hpp
C++
Source/Object/Squad/squad.hpp
weenchvd/Wasteland3
e1d9b96f73b9d1901dfee61ec2d468e00560cb00
[ "BSL-1.0" ]
null
null
null
Source/Object/Squad/squad.hpp
weenchvd/Wasteland3
e1d9b96f73b9d1901dfee61ec2d468e00560cb00
[ "BSL-1.0" ]
null
null
null
Source/Object/Squad/squad.hpp
weenchvd/Wasteland3
e1d9b96f73b9d1901dfee61ec2d468e00560cb00
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2021 Vitaly Dikov // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt) #ifndef SQUAD_HPP #define SQUAD_HPP #include"common.hpp" #include"inventory.hpp" #include"unit.hpp" #include<array> #include<memory> namespace game { namespace object { constexpr unsigned int nMembers = 6; // number of members class Squad { public: Squad() : invent_{ std::make_unique<Inventory>() }, money_{ 0 } {} Squad(const Squad&) = delete; Squad& operator=(const Squad&) = delete; common::Money money() const noexcept { return money_; } void moneyAdd(common::Money shift) noexcept { money_ += shift; } /// members public: const std::array<std::unique_ptr<Unit>, nMembers>& members() const noexcept { return members_; } std::array<std::unique_ptr<Unit>, nMembers>& members() noexcept { return members_; } /// inventory public: const Inventory& inventory() const noexcept { return *invent_; } Inventory& inventory() noexcept { return *invent_; } private: std::array<std::unique_ptr<Unit>, nMembers> members_; std::unique_ptr<Inventory> invent_; common::Money money_; }; } // namespace object } // namespace game #endif // !SQUAD_HPP
25.462963
100
0.650909
[ "object" ]
be5ab89e0c6120c036aff84dff569775bf0f220b
22,008
cpp
C++
app/main.cpp
cdyk/meshtool
e24ff0ae1b5c88645cb9f8d79da2ca47a369a345
[ "MIT" ]
6
2018-10-04T14:04:40.000Z
2018-12-21T16:04:47.000Z
app/main.cpp
cdyk/meshtool
e24ff0ae1b5c88645cb9f8d79da2ca47a369a345
[ "MIT" ]
null
null
null
app/main.cpp
cdyk/meshtool
e24ff0ae1b5c88645cb9f8d79da2ca47a369a345
[ "MIT" ]
null
null
null
#define WIN32_LEAN_AND_MEAN #define NOMINMAX #include <Windows.h> #define GLFW_INCLUDE_VULKAN #include <GLFW/glfw3.h> //#include <GL/gl3w.h> #include <imgui.h> #include <imgui_internal.h> #include <vector> #include <cctype> #include <chrono> #include <examples/imgui_impl_glfw.h> #include <cstdio> #include "Viewer.h" #include "Common.h" #include "Mesh.h" #include "LinAlgOps.h" #include "RenderSolid.h" #include "Raycaster.h" #include "HandlePicking.h" #include "App.h" namespace { App* app = nullptr; void logger(unsigned level, const char* msg, ...) { #ifdef _WIN32 thread_local static char buf[512]; buf[0] = '['; switch (level) { case 0: buf[1] = 'I'; break; case 1: buf[1] = 'W'; break; case 2: buf[1] = 'E'; break; default: buf[1] = '?'; break; } buf[2] = ']'; buf[3] = ' '; va_list argptr; va_start(argptr, msg); auto l = vsnprintf(buf + 4, sizeof(buf) - 4 - 2, msg, argptr); va_end(argptr); if (sizeof(buf) - 4 - 2 < l) l = sizeof(buf) - 4 - 2; buf[l + 4] = '\n'; buf[l + 4 + 1] = '\0'; OutputDebugStringA(buf); #else switch (level) { case 0: fprintf(stderr, "[I] "); break; case 1: fprintf(stderr, "[W] "); break; case 2: fprintf(stderr, "[E] "); break; } va_list argptr; va_start(argptr, msg); vfprintf(stderr, msg, argptr); va_end(argptr); fprintf(stderr, "\n"); #endif } void glfw_error_callback(int error, const char* description) { logger(2, "GLFV error %d: %s", error, description); } void resizeFunc(GLFWwindow* window, int w, int h) { app->wasResized = true; app->width = w; app->height = h; } void moveFunc(GLFWwindow* window, double x, double y) { ImGuiIO& io = ImGui::GetIO(); if (io.WantCaptureMouse) return; app->viewer->move(float(x), float(y)); } void buttonFunc(GLFWwindow* window, int button, int action, int mods) { ImGuiIO& io = ImGui::GetIO(); if (io.WantCaptureMouse) return; double x, y; glfwGetCursorPos(window, &x, &y); switch (action) { case GLFW_PRESS: switch (button) { case 0: if (mods == GLFW_MOD_CONTROL) { app->picking = true; } else { app->viewer->startRotation(float(x), float(y)); } break; case 1: app->viewer->startZoom(float(x), float(y)); break; case 2: app->viewer->startPan(float(x), float(y)); break; } break; case GLFW_RELEASE: app->viewer->stopAction(); break; } } void keyFunc(GLFWwindow* window, int key, int scancode, int action, int mods) { if (mods == GLFW_MOD_CONTROL) { if (key == GLFW_KEY_A && action == GLFW_PRESS) app->selectAll = true; if (key == GLFW_KEY_SPACE && action == GLFW_PRESS) app->selectNone = true; if (key == GLFW_KEY_Q && action == GLFW_PRESS) glfwSetWindowShouldClose(window, true); } else if (mods == (GLFW_MOD_CONTROL | GLFW_MOD_SHIFT)) { if (key == GLFW_KEY_A && action == GLFW_PRESS) app->viewAll = true; if (key == GLFW_KEY_S && action == GLFW_PRESS) app->moveToSelection = true; } else if (mods == 0) { if (key == GLFW_KEY_R && action == GLFW_PRESS) { switch (app->renderMode) { case RenderMode::Normal: app->renderMode = RenderMode::MeshShader; break; case RenderMode::MeshShader: app->renderMode = RenderMode::Raytracing; break; case RenderMode::Raytracing: app->renderMode = RenderMode::Normal; break; } } if (key == GLFW_KEY_W && action == GLFW_PRESS) app->viewOutlines = !app->viewOutlines; if (key == GLFW_KEY_L && action == GLFW_PRESS) app->viewLines = !app->viewLines; if (key == GLFW_KEY_S && action == GLFW_PRESS) app->viewSolid = !app->viewSolid; if (key == GLFW_KEY_A && action == GLFW_PRESS) app->viewTangents = !app->viewTangents; if (key == GLFW_KEY_N && action == GLFW_PRESS) app->viewNormals = !app->viewNormals; if (key == GLFW_KEY_C && action == GLFW_PRESS) { switch (app->triangleColor) { case TriangleColor::Single: app->triangleColor = TriangleColor::ModelColor; break; case TriangleColor::ModelColor: app->triangleColor = TriangleColor::ObjectId; break; case TriangleColor::ObjectId: app->triangleColor = TriangleColor::SmoothingGroup; break; case TriangleColor::SmoothingGroup: app->triangleColor = TriangleColor::TriangleOrder; break; case TriangleColor::TriangleOrder : app->triangleColor = TriangleColor::Single; break; } app->updateColor = true; } if (key == GLFW_KEY_T && action == GLFW_PRESS) { switch (app->renderSolid->texturing) { case RenderSolid::Texturing::None: app->renderSolid->texturing = RenderSolid::Texturing::Checker; break; case RenderSolid::Texturing::Checker: app->renderSolid->texturing = RenderSolid::Texturing::ColorGradient; break; case RenderSolid::Texturing::ColorGradient: app->renderSolid->texturing = RenderSolid::Texturing::None; break; } } if (key == GLFW_KEY_F && action == GLFW_PRESS) { if (glfwGetWindowAttrib(window, GLFW_MAXIMIZED)) { glfwRestoreWindow(window); } else { glfwMaximizeWindow(window); } } } } void scrollFunc(GLFWwindow* window, double x, double y) { float speed = 1.f; if (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS) { speed = 0.1f; } if (glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS) { speed = 0.01f; } bool distance = glfwGetKey(window, GLFW_KEY_LEFT_ALT) == GLFW_PRESS; app->viewer->dolly(float(x), float(y), speed, distance); } void runObjReader(Logger logger, std::string path) { auto time0 = std::chrono::high_resolution_clock::now(); Mesh* mesh = nullptr; HANDLE h = CreateFileA(path.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (h == INVALID_HANDLE_VALUE) { logger(2, "Failed to open file %s: %d", path.c_str(), GetLastError()); } else { DWORD hiSize; DWORD loSize = GetFileSize(h, &hiSize); size_t fileSize = (size_t(hiSize) << 32u) + loSize; HANDLE m = CreateFileMappingA(h, 0, PAGE_READONLY, 0, 0, NULL); if (m == INVALID_HANDLE_VALUE) { logger(2, "Failed to map file %s: %d", path.c_str(), GetLastError()); } else { const void * ptr = MapViewOfFile(m, FILE_MAP_READ, 0, 0, 0); if (ptr == nullptr) { logger(2, "Failed to map view of file %s: %d", path.c_str(), GetLastError()); } else { mesh = readObj(logger, ptr, fileSize); UnmapViewOfFile(ptr); } CloseHandle(m); } CloseHandle(h); } if (mesh) { auto * name = path.c_str(); for (auto * t = name; *t != '\0'; t++) { if (*t == '\\' || *t == '//') name = t + 1; } mesh->name = mesh->strings.intern(name); auto time1 = std::chrono::high_resolution_clock::now(); auto e = std::chrono::duration_cast<std::chrono::milliseconds>((time1 - time0)).count(); std::lock_guard<std::mutex> guard(app->incomingMeshLock); app->incomingMeshes.pushBack(mesh); logger(0, "Read %s in %lldms", path.c_str(), e); } else { logger(0, "Failed to read %s", path.c_str()); } } void guiTraversal(GLFWwindow* window) { if (ImGui::BeginMainMenuBar()) { if (ImGui::BeginMenu("File")) { if (ImGui::MenuItem("Quit", nullptr, nullptr)) { glfwSetWindowShouldClose(window, true); } ImGui::EndMenu(); } if (ImGui::BeginMenu("Select")) { if (ImGui::MenuItem("All", "CTRL+A" )) { app->selectAll = true; } if (ImGui::MenuItem("None", "CTRL+ ")) { app->selectNone = true; } ImGui::EndMenu(); } if (ImGui::BeginMenu("View")) { if (ImGui::MenuItem("View all", "CTRL+SHIFT+A", nullptr)) { app->viewAll = true; } if (ImGui::MenuItem("View selection", "CTRL+SHIFT+S")) { app->moveToSelection = true; } ImGui::Separator(); if (ImGui::MenuItem("Solid", "S", &app->viewSolid)) {} if (ImGui::MenuItem("Lines", "L", &app->viewLines)) {} if (ImGui::MenuItem("Outlines", "W", &app->viewOutlines)) {} if (ImGui::MenuItem("Tangent coordsys", "C", &app->viewTangents)) {} if (ImGui::MenuItem("Normal vectors", "N", &app->viewNormals)) {} if (ImGui::BeginMenu("RenderMode", app->viewSolid)) { bool sel[3] = { app->renderMode == RenderMode::Normal, app->renderMode == RenderMode::MeshShader, app->renderMode == RenderMode::Raytracing, }; if (ImGui::MenuItem("Normal", "R", &sel[0])) app->renderMode = RenderMode::Normal; if (ImGui::MenuItem("Mesh shader", "R", &sel[1], app->vCtx->nvMeshShader)) app->renderMode = RenderMode::MeshShader; if (ImGui::MenuItem("Raytracing", "R", &sel[2], app->vCtx->nvRayTracing)) app->renderMode = RenderMode::Raytracing; ImGui::EndMenu(); } if (ImGui::BeginMenu("Color")) { bool sel[5] = { app->triangleColor == TriangleColor::Single, app->triangleColor == TriangleColor::ModelColor, app->triangleColor == TriangleColor::ObjectId, app->triangleColor == TriangleColor::SmoothingGroup, app->triangleColor == TriangleColor::TriangleOrder, }; if (ImGui::MenuItem("Nothing", nullptr, &sel[0])) { app->triangleColor = TriangleColor::Single; app->updateColor = true; } if (ImGui::MenuItem("Model color", nullptr, &sel[1])) { app->triangleColor = TriangleColor::ModelColor; app->updateColor = true; } if (ImGui::MenuItem("Object id", nullptr, &sel[2])) { app->triangleColor = TriangleColor::ObjectId; app->updateColor = true; } if (ImGui::MenuItem("Smoothing group", nullptr, &sel[3])) { app->triangleColor = TriangleColor::SmoothingGroup; app->updateColor = true; } if (ImGui::MenuItem("Triangle order", nullptr, &sel[3])) { app->triangleColor = TriangleColor::TriangleOrder; app->updateColor = true; } ImGui::EndMenu(); } if (ImGui::BeginMenu("Texturing")) { if (app->renderSolid) { bool sel[3] = { app->renderSolid->texturing == RenderSolid::Texturing::None, app->renderSolid->texturing == RenderSolid::Texturing::Checker, app->renderSolid->texturing == RenderSolid::Texturing::ColorGradient, }; if (ImGui::MenuItem("None", "T", &sel[0])) app->renderSolid->texturing = RenderSolid::Texturing::None; if (ImGui::MenuItem("Checker", "T", &sel[1])) app->renderSolid->texturing = RenderSolid::Texturing::Checker; if (ImGui::MenuItem("Color gradient", "T", &sel[2])) app->renderSolid->texturing = RenderSolid::Texturing::ColorGradient; } ImGui::EndMenu(); } ImGui::EndMenu(); } ImGui::SetCursorPosX(ImGui::GetWindowContentRegionMax().x - ImGui::CalcTextSize(app->fpsString).x); ImGui::Text(app->fpsString); app->menuHeight = ImGui::GetWindowSize().y; ImGui::EndMainMenuBar(); } { ImGui::SetNextWindowPos(ImVec2(0, app->menuHeight)); ImGui::SetNextWindowSize(ImVec2(app->leftSplit, app->height - app->menuHeight)); ImGui::Begin("##left", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse); //ImGuiContext& g = *GImGui; //ImGuiWindow* window = g.CurrentWindow; ImVec2 backup_pos = ImGui::GetCursorPos(); ImGui::SetCursorPosX(app->leftSplit - app->thickness); ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0, 0, 0, 0)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.6f, 0.6f, 0.6f, 0.10f)); ImGui::Button("##Splitter", ImVec2(app->thickness, -1)); ImGui::PopStyleColor(3); if (ImGui::IsItemActive()) { app->leftSplit += ImGui::GetIO().MouseDelta.x; if (app->leftSplit < 50) app->leftSplit = 50; if (app->width - app->thickness < app->leftSplit) app->leftSplit = app->width - app->thickness; } ImGui::SetCursorPos(backup_pos); ImGui::BeginChild("Meshes", ImVec2(app->leftSplit - app->thickness - backup_pos.x, -1), false, ImGuiWindowFlags_AlwaysHorizontalScrollbar); for(auto * m : app->items.meshes) { if (ImGui::TreeNodeEx(m, ImGuiTreeNodeFlags_DefaultOpen, "%s Vn=%d Tn=%d", m->name ? m->name : "unnamed", m->vtxCount, m->triCount)) { for (unsigned o = 0; o < m->obj_n; o++) { if (ImGui::Selectable(m->obj[o], &m->selected[o], ImGuiSelectableFlags_PressedOnClick)) { app->updateColor = true; //moveToSelection = true; } if (app->scrollToItem == o) { ImGui::SetScrollHereY(); app->scrollToItem = ~0u; } } ImGui::TreePop(); } } ImGui::EndChild(); ImGui::End(); } //ImGui::ShowDemoWindow(); } void checkQueues() { Vector<Mesh*> newMeshes; { std::lock_guard<std::mutex> guard(app->incomingMeshLock); for(auto & mesh : app->incomingMeshes) if (app->incomingMeshes.size() != 0) { newMeshes.pushBack(mesh); } app->incomingMeshes.resize(0); } if (newMeshes.size() != 0) { for (auto & m : newMeshes) { auto obj_n = m->obj_n; if (obj_n == 0) obj_n = 1; m->currentColor = (uint32_t*)m->arena.alloc(sizeof(uint32_t) * m->triCount); m->selected = (bool*)m->arena.alloc(sizeof(bool)*(obj_n)); std::memset(m->selected, 0, sizeof(bool)*obj_n); app->updateColor = true; app->items.meshes.pushBack(m); } auto bbox = createEmptyBBox3f(); for (auto * m : app->items.meshes) { if (isEmpty(m->bbox)) continue; engulf(bbox, m->bbox); } if (isEmpty(bbox)) { bbox = BBox3f(Vec3f(-1.f), Vec3f(1.f)); } app->viewer->setViewVolume(bbox); app->viewer->viewAll(); } } } namespace { uint32_t colors[] = { 0xffcc0000,0xff9e91cc,0xff5ea5f4,0xff8c8c51, 0xffff7547,0xff2b2bcc,0xffe0eded,0xff2d4f2d, 0xff707ff9,0xff00a5ff,0xff2175ed,0xff0000ff, 0xff8c668c,0xff238e23,0xffaae8ed,0xff445bcc, 0xff660033,0xff937c68,0xff33c9ed,0xffd1eded, 0xffe5e0af,0xffbfbfbf,0xff00cccc,0xff14448c, 0xff8911ed,0xff990066,0xffdd00dd,0xff4763ff, 0xff4f2d2d,0xff0099ed,0xff33cc99,0xffc6ed75, 0xff4f4f2d,0xff0000cc,0xff5e9e9e,0xffb2ddf4, 0xffeded00,0xffccbf00,0xff7fff00,0xffa8a8a8, 0xff00cc00,0xffdbf4f4,0xff007fff,0xff7093db, 0xfff4f4f4,0xff6b238e,0xff7f0000,0xffed82ed }; } int main(int argc, char** argv) { GLFWwindow* window; glfwSetErrorCallback(glfw_error_callback); if (!glfwInit()) return -1; glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); window = glfwCreateWindow(1280, 720, "MeshTool", NULL, NULL); if (!window) { glfwTerminate(); return -1; } if (!glfwVulkanSupported()) { logger(2, "GLFW: Vulkan not supported"); return -1; } IMGUI_CHECKVERSION(); ImGui::CreateContext(); int w, h; glfwGetFramebufferSize(window, &w, &h); app = new App(logger, window, w, h); app->tasks.init(logger); glfwSetWindowSizeCallback(window, resizeFunc); glfwSetCursorPosCallback(window, moveFunc); glfwSetMouseButtonCallback(window, buttonFunc); glfwSetScrollCallback(window, scrollFunc); glfwSetKeyCallback(window, keyFunc); ImGuiIO& io = ImGui::GetIO(); (void)io; //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls ImGui_ImplGlfw_InitForOpenGL(window, false); //ImGui_ImplOpenGL2_Init(); ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic(); BBox3f viewVolume(Vec3f(-2.f), Vec3f(2.f)); app->viewer->setViewVolume(viewVolume); app->viewer->resize(1280, 720); for (int i = 1; i < argc; i++) { auto arg = std::string(argv[i]); if (arg == "--raytrace") { app->renderMode = RenderMode::Raytracing; } else if (arg == "--mesh-shader") { app->renderMode = RenderMode::MeshShader; } else if (arg.substr(0, 2) == "--") { } else { auto argLower = arg; for(auto & c :argLower) c = std::tolower(c); auto l = argLower.rfind(".obj"); if (l != std::string::npos) { TaskFunc taskFunc = [arg](bool& cancel) -> bool {runObjReader(logger, arg); return true; }; app->tasks.enqueue(taskFunc); } } } app->leftSplit = 0.25f*app->width; while (!glfwWindowShouldClose(window)) { glfwPollEvents(); if (app->wasResized) { app->wasResized = false; app->resize(app->width, app->height); } { Vec2f viewerPos(app->leftSplit, app->menuHeight); Vec2f viewerSize(app->width - viewerPos.x, app->height - viewerPos.y); app->viewer->resize(viewerPos, viewerSize); app->viewer->update(); } checkQueues(); app->startFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); guiTraversal(window); ImGui::Render(); Vec4f viewport(app->leftSplit, app->menuHeight, app->width - app->leftSplit, app->height - app->menuHeight); if (app->picking) { app->picking = false; double x, y; glfwGetCursorPos(window, &x, &y); Hit hit; HitTmp tmp; Vec2f viewerPos(app->leftSplit, app->menuHeight); Vec2f viewerSize(app->width - viewerPos.x, app->height - viewerPos.y); if(nearestHit(hit, tmp, logger, app->items.meshes, app->viewer->getProjectionViewMatrix(), app->viewer->getProjectionViewInverseMatrix(), viewerPos, viewerSize, Vec2f(float(x), float(y)))) { auto * m = app->items.meshes[hit.mesh]; auto o = m->TriObjIx[hit.triangle]; m->selected[o] = !m->selected[o]; app->scrollToItem = o; app->updateColor = true; logger(0, "Hit mesh %d triangle %d at %f", hit.mesh, hit.triangle, hit.depth); } else { logger(0, "Miss"); } } if (app->selectAll | app->selectNone) { app->selectAll = app->selectNone = false; for (auto * m : app->items.meshes) { for (uint32_t i = 0; i < m->obj_n; i++) { m->selected[i] = app->selectAll; app->updateColor = true; } } } if (app->viewAll) { app->viewAll = false; app->viewer->viewAll(); } if (app->moveToSelection) { app->moveToSelection = false; BBox3f bbox = createEmptyBBox3f(); for (auto * m : app->items.meshes) { for (uint32_t i = 0; i < m->triCount; i++) { if (m->selected[m->TriObjIx[i]]) { for (unsigned k = 0; k < 3; k++) { engulf(bbox, m->vtx[m->triVtxIx[3 * i + k]]); } } } } if (isNotEmpty(bbox)) { app->viewer->view(bbox); } } if (app->updateColor) { for (auto * m : app->items.meshes) { m->touchColor(); auto color = app->triangleColor; switch (color) { case TriangleColor::ObjectId: if (!m->TriObjIx) color = TriangleColor::Single; break; case TriangleColor::SmoothingGroup: if (!m->triSmoothGroupIx) color = TriangleColor::Single; break; } switch (color) { case TriangleColor::Single: for (uint32_t i = 0; i < m->triCount; i++) { if (m->selected[m->TriObjIx[i]]) { m->currentColor[i] = 0xffddffff; } else { m->currentColor[i] = 0xff888888; } } break; case TriangleColor::ModelColor: for (uint32_t i = 0; i < m->triCount; i++) { if (m->selected[m->TriObjIx[i]]) { m->currentColor[i] = 0xffddffff; } else { m->currentColor[i] = m->triColor[i]; } } break; break; case TriangleColor::ObjectId: for (uint32_t i = 0; i < m->triCount; i++) { if (m->selected[m->TriObjIx[i]]) { m->currentColor[i] = 0xffddffff; } else { m->currentColor[i] = colors[m->TriObjIx[i] % (sizeof(colors) / sizeof(uint32_t))]; } } break; case TriangleColor::SmoothingGroup: for (uint32_t i = 0; i < m->triCount; i++) { if (m->selected[m->TriObjIx[i]]) { m->currentColor[i] = 0xffddffff; } else { m->currentColor[i] = colors[m->triSmoothGroupIx[i] % (sizeof(colors) / sizeof(uint32_t))]; } } break; case TriangleColor::TriangleOrder: for (uint32_t i = 0; i < m->triCount; i++) { if (m->selected[m->TriObjIx[i]]) { m->currentColor[i] = 0xffddffff; } else { m->currentColor[i] = colors[(i >> 8) % ARRAYSIZE(colors)]; } } break; } } } app->updateColor = false; app->render(viewport); app->present(); } CHECK_VULKAN(vkDeviceWaitIdle(app->vCtx->device)); app->items.meshes.resize(0); if(app->renderSolid) app->renderSolid->update(app->items.meshes); if(app->raycaster) app->raycaster->update(app->items.meshes); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); glfwDestroyWindow(window); glfwTerminate(); return 0; }
33.295008
151
0.585242
[ "mesh", "render", "object", "vector", "model", "solid" ]
be5b83c0999111ef9a0840824a6ee511247c0192
26,745
cpp
C++
3fd/rpc/rpc_impl_client.cpp
faburaya/3fd
2fa0b57b9702902178c878fe3d317d55ec4cdc95
[ "MS-PL" ]
23
2017-04-23T08:32:55.000Z
2022-02-21T00:13:29.000Z
3fd/rpc/rpc_impl_client.cpp
faburaya/3fd
2fa0b57b9702902178c878fe3d317d55ec4cdc95
[ "MS-PL" ]
3
2018-10-16T23:02:50.000Z
2021-11-17T19:43:21.000Z
3fd/rpc/rpc_impl_client.cpp
faburaya/3fd
2fa0b57b9702902178c878fe3d317d55ec4cdc95
[ "MS-PL" ]
4
2018-08-01T13:24:41.000Z
2021-06-11T20:59:52.000Z
#include "pch.h" #include "rpc_helpers.h" #include "rpc_impl_util.h" #include <3fd/core/callstacktracer.h> #include <3fd/core/configuration.h> #include <3fd/core/logger.h> #include <3fd/core/logger.h> #include <3fd/utils/algorithms.h> #include <3fd/utils/serialization.h> #include <memory> #include <codecvt> #include <sstream> #include <cstdio> #include <cmath> namespace _3fd { namespace rpc { ///////////////////////// // RpcClient Class ///////////////////////// /// <summary> /// Releases resources of a RPC client binding handle. /// </summary> /// <param name="bindingHandle">The given RPC binding handle.</param> static void HelpFreeBindingHandle(rpc_binding_handle_t *bindingHandle) { CALL_STACK_TRACE; if (*bindingHandle == nullptr) return; auto status = RpcBindingFree(bindingHandle); LogIfError(status, "Failed to release resources from binding handle of RPC client", core::Logger::Priority::PRIO_CRITICAL); } /// <summary> /// Initializes a new instance of the <see cref="RpcClient"/> class. /// This is a basic constructor that sets everything but security options. /// </summary> /// <param name="protSeq">The transport to use for RPC.</param> /// <param name="objUUID">The UUID of the object in the RPC server. An empty string /// is equivalent to a nil UUID, which is valid as long as the endpoint is specified.</param> /// <param name="destination">The destination: local RPC requires the machine name, /// while for TCP this is the network address (IP or host name).</param> /// <param name="authnLevel">The authentication level to use.</param> /// <param name="endpoint">The endpoint: for local RPC is the application or service /// name, while for TCP this is the port number. Specifying the endpoint is optional /// if the server has registered its bindings with the endpoint mapper.</param> RpcClient::RpcClient(ProtocolSequence protSeq, const string &objUUID, const string &destination, const string &endpoint) try : m_bindingHandle(nullptr), m_isOnHold(false) { CALL_STACK_TRACE; std::ostringstream oss; oss << objUUID << '#' << ToString(protSeq) << '@' << destination; m_endpoint = oss.str(); // Prepare text parameters encoded in UCS-2 std::wstring_convert<std::codecvt_utf8<wchar_t>> transcoder; std::wstring ucs2objUuid; RPC_WSTR paramObjUuid; if (objUUID.empty() || objUUID == "") paramObjUuid = nullptr; else { ucs2objUuid = transcoder.from_bytes(objUUID); paramObjUuid = const_cast<RPC_WSTR> (ucs2objUuid.c_str()); } std::wstring protSeqName = transcoder.from_bytes(ToString(protSeq)); auto paramProtSeq = const_cast<RPC_WSTR> (protSeqName.c_str()); std::wstring ucs2Destination = transcoder.from_bytes(destination); auto paramNetwAddr = const_cast<RPC_WSTR> (ucs2Destination.c_str()); std::wstring ucs2Endpoint; RPC_WSTR paramEndpoint; if (endpoint.empty() || endpoint == "") paramEndpoint = nullptr; else { ucs2Endpoint = transcoder.from_bytes(endpoint); paramEndpoint = const_cast<RPC_WSTR> (ucs2Endpoint.c_str()); } // Compose the binding string: RPC_WSTR bindingString; auto status = RpcStringBindingComposeW( paramObjUuid, paramProtSeq, paramNetwAddr, paramEndpoint, nullptr, &bindingString ); ThrowIfError(status, "Failed to compose binding string for RPC client"); // Create a binding handle from the composed string: status = RpcBindingFromStringBindingW(bindingString, &m_bindingHandle); // Release the memory allocated for the binding string: LogIfError( RpcStringFreeW(&bindingString), "Failed to release resources of binding string for RPC client", core::Logger::Priority::PRIO_CRITICAL ); ThrowIfError(status, "Failed to create binding handle for RPC client"); // Notify establishment of binding with this protocol sequence: oss.str(""); oss << "RPC client for object " << objUUID << " in " << destination << " will use protocol sequence '" << ToString(protSeq) << '\''; core::Logger::Write(oss.str(), core::Logger::PRIO_NOTICE); } catch (core::IAppException &ex) { CALL_STACK_TRACE; HelpFreeBindingHandle(&m_bindingHandle); throw core::AppException<std::runtime_error>("Failed to instantiate RPC client", ex); } catch (std::exception &ex) { CALL_STACK_TRACE; HelpFreeBindingHandle(&m_bindingHandle); std::ostringstream oss; oss << "Generic failure when instantiating RPC client: " << ex.what(); throw core::AppException<std::runtime_error>(oss.str()); } /// <summary> /// Initializes a new instance of the <see cref="RpcClient"/> class /// for security options of Windows SSP packages only (NTLM & Kerberos). /// </summary> /// <param name="protSeq">The transport to use for RPC.</param> /// <param name="objUUID">The UUID of the object in the RPC server. An empty string /// is equivalent to a nil UUID, which is valid as long as the endpoint is specified.</param> /// <param name="destination">The destination: local RPC requires the machine name, /// while for TCP this is the network address (IP or host name).</param> /// <param name="authnSecurity">The authentication security package to use. Because /// local RPC does not support Kerberos, the requirement of mutual authentication will /// cause NTLM to use SPN's registered in AD. This parameter is ignored if the /// authentication level specifies that no authentication takes place.</param> /// <param name="authnLevel">The authentication level to use.</param> /// <param name="impLevel">The level allowed for the RPC server to impersonate /// the identity of an authorized client. This parameter is ignored if the /// authentication level specifies that no authentication takes place.</param> /// <param name="spn">The SPN as registered in AD.</param> /// <param name="endpoint">The endpoint: for local RPC is the application or service /// name, while for TCP this is the port number. Specifying the endpoint is optional /// if the server has registered its bindings with the endpoint mapper.</param> RpcClient::RpcClient(ProtocolSequence protSeq, const string &objUUID, const string &destination, AuthenticationSecurity authnSecurity, AuthenticationLevel authnLevel, ImpersonationLevel impLevel, const string &spn, const string &endpoint) : RpcClient(protSeq, objUUID, destination, endpoint) { // Invalid arguments: _ASSERTE( authnSecurity == AuthenticationSecurity::NTLM || authnSecurity == AuthenticationSecurity::TryKerberos || authnSecurity == AuthenticationSecurity::RequireMutualAuthn ); CALL_STACK_TRACE; try { if (authnSecurity != AuthenticationSecurity::NTLM && authnSecurity != AuthenticationSecurity::TryKerberos && authnSecurity != AuthenticationSecurity::RequireMutualAuthn) { throw core::AppException<std::invalid_argument>( "Invalid argument: the constructor overload was meant to be used only " "with authentication services Microsoft NTLM/Negotiate/Kerberos SSP" ); } /* Kerberos security package is preferable over NTLM, however, Kerberos is not supported in local RPC, and it requires SPN registration, which is only available with Microsoft Active Directory services: */ DirSvcBinding dirSvcBinding; bool useActDirSec(false); /* Only try to detect AD... + if RPC over TCP and mutual authentication is preferable or required, because AD is needed for that OR + if local RPC and mutual authentication was required, because the protocol does not support Kerberos, but there is mutual authentication for NTLM using SPN's */ if ((protSeq == ProtocolSequence::TCP && authnSecurity != AuthenticationSecurity::NTLM) || (protSeq == ProtocolSequence::Local && authnSecurity == AuthenticationSecurity::RequireMutualAuthn)) { useActDirSec = DetectActiveDirectoryServices(dirSvcBinding, true); } std::ostringstream oss; std::wstring ucs2spn; std::wstring_convert<std::codecvt_utf8<wchar_t>> transcoder; if (useActDirSec) { if (spn == "") { throw core::AppException<std::runtime_error>( "No SPN was provided to RPC client for mutual authentication" ); } ucs2spn = transcoder.from_bytes(spn); oss << "RPC client has to authenticate server '" << spn << '\''; core::Logger::Write(oss.str(), core::Logger::PRIO_NOTICE); oss.str(""); } // AD not available, but mutual authentication was required: else if (authnSecurity == AuthenticationSecurity::RequireMutualAuthn) { oss << "Could not fulfill mutual authentication requirement of " "RPC client for object " << objUUID << " in " << destination << " because Microsoft Active Directory services are not available"; throw core::AppException<std::runtime_error>(oss.str()); } /* Sets the client binding handle's authentication, authorization, and security quality-of-service: */ RPC_SECURITY_QOS secQOS = { 0 }; secQOS.Version = 1; secQOS.ImpersonationType = static_cast<unsigned long> (impLevel); /* Authentication impact on performance on identity tracking is negligible unless a remote protocol is in use: */ if (protSeq == ProtocolSequence::TCP) secQOS.IdentityTracking = RPC_C_QOS_IDENTITY_STATIC; else secQOS.IdentityTracking = RPC_C_QOS_IDENTITY_DYNAMIC; /* This client negotiates to use Kerberos if such security package is available. When RPC is local, Kerberos is not supported disregarding AD availability, so NTLM is used. Regarding the support for mutual authentication, both Kerberos and NTLM (only for local RPC) support it, but it requires SPN registration, hence can only be used when AD is present: */ unsigned long authnService; if (protSeq == ProtocolSequence::Local) { authnService = RPC_C_AUTHN_WINNT; if (useActDirSec && authnSecurity == AuthenticationSecurity::RequireMutualAuthn) { secQOS.Capabilities = RPC_C_QOS_CAPABILITIES_MUTUAL_AUTH | RPC_C_QOS_CAPABILITIES_LOCAL_MA_HINT; } } else { if (useActDirSec) { authnService = static_cast<unsigned long> (authnSecurity); if (authnSecurity != AuthenticationSecurity::NTLM) secQOS.Capabilities = RPC_C_QOS_CAPABILITIES_MUTUAL_AUTH; } else authnService = RPC_C_AUTHN_WINNT; } auto status = RpcBindingSetAuthInfoExW( m_bindingHandle, const_cast<RPC_WSTR> (ucs2spn.empty() ? nullptr : ucs2spn.c_str()), static_cast<unsigned long> (authnLevel), authnService, nullptr, // no explicit credentials, use context RPC_C_AUTHZ_DEFAULT, &secQOS ); ThrowIfError(status, "Failed to set security for binding handle of RPC client"); oss << "RPC client binding security was set to use " << ConvertAuthnSvcOptToString(authnService) << " "; AppendSecQosOptsDescription(secQOS, oss); oss << ", " << ToString(authnLevel) << " and " << ToString(impLevel); core::Logger::Write(oss.str(), core::Logger::PRIO_NOTICE); } catch (core::IAppException &ex) { HelpFreeBindingHandle(&m_bindingHandle); throw core::AppException<std::runtime_error>("Failed to instantiate RPC client", ex); } catch (std::exception &ex) { HelpFreeBindingHandle(&m_bindingHandle); std::ostringstream oss; oss << "Generic failure when creating RPC client: " << ex.what(); throw core::AppException<std::runtime_error>(oss.str()); } } /// <summary> /// Initializes a new instance of the <see cref="RpcClient"/> class /// for security options of Secure Channel SSP. /// </summary> /// <param name="protSeq">The transport to use for RPC.</param> /// <param name="objUUID">The UUID of the object in the RPC server. An empty string /// is equivalent to a nil UUID, which is valid as long as the endpoint is specified.</param> /// <param name="destination">The destination: local RPC requires the machine name, /// while for TCP this is the network address (IP or host name).</param> /// <param name="certInfoX509">Description of the X.509 certificate to use.</param> /// <param name="authnLevel">The authentication level to use.</param> /// <param name="endpoint">The endpoint: for local RPC is the application or service /// name, while for TCP this is the port number. Specifying the endpoint is optional /// if the server has registered its bindings with the endpoint mapper.</param> /// <remarks>Because Schannel SSP is only compatible with transport /// over TCP/IP, that is the implicitly chosen protocol sequence.</remarks> RpcClient::RpcClient(const string &objUUID, const string &destination, const CertInfo &certInfoX509, AuthenticationLevel authnLevel, const string &endpoint) : RpcClient(ProtocolSequence::TCP, objUUID, destination, endpoint) { CALL_STACK_TRACE; try { SystemCertificateStore certStore(certInfoX509.storeLocation, certInfoX509.storeName); auto certX509 = certStore.FindCertBySubject(certInfoX509.subject); if (certX509 == nullptr) { std::ostringstream oss; oss << "Could not get from system store code " << certInfoX509.storeLocation << " the specified X.509 certificate (subject = '" << certInfoX509.subject << "')"; throw core::AppException<std::runtime_error>( "Certificate for RPC client was not found in store", oss.str() ); } auto authnService = static_cast<unsigned long> (AuthenticationSecurity::SecureChannel); m_schannelCred.reset( dbg_new SChannelCredWrapper(certX509, certInfoX509.strongerSecurity) ); auto status = RpcBindingSetAuthInfoW( m_bindingHandle, nullptr, static_cast<unsigned long> (authnLevel), authnService, m_schannelCred->GetCredential(), RPC_C_AUTHZ_DEFAULT ); ThrowIfError(status, "Failed to set security for binding handle of RPC client"); std::ostringstream oss; oss << "RPC client binding security was set to use " << ConvertAuthnSvcOptToString(authnService) << " with X.509 certificate (subject = '" << certInfoX509.subject << "' in store '" << certInfoX509.storeName << "') and " << ToString(authnLevel); core::Logger::Write(oss.str(), core::Logger::PRIO_NOTICE); } catch (core::IAppException &ex) { HelpFreeBindingHandle(&m_bindingHandle); throw core::AppException<std::runtime_error>("Failed to instantiate RPC client", ex); } catch (std::exception &ex) { HelpFreeBindingHandle(&m_bindingHandle); std::ostringstream oss; oss << "Generic failure when creating RPC client: " << ex.what(); throw core::AppException<std::runtime_error>(oss.str()); } } /// <summary> /// Finalizes an instance of the <see cref="RpcClient"/> class. /// </summary> RpcClient::~RpcClient() { CALL_STACK_TRACE; HelpFreeBindingHandle(&m_bindingHandle); } /// <summary> /// Removes the endpoint portion of the server address in the binding handle. /// The host remains unchanged in the binding handle. The result is a partially-bound /// server binding handle. When the client makes the next remote procedure call using /// the reset (partially-bound) binding, the client's run-time library automatically /// communicates with the endpoint-mapping service on the specified remote host to obtain /// the endpoint of a compatible server from the endpoint-map database. If a compatible /// server is located, the RPC run-time library updates the binding with a new endpoint. /// If a compatible server is not found, the remote procedure call fails. /// </summary> void RpcClient::ResetBindings() { CALL_STACK_TRACE; auto status = RpcBindingReset(m_bindingHandle); ThrowIfError(status, "Failed to reset binding handle of RPC client"); } /// <summary> /// Enumerates the recommended actions for RPC errors. /// </summary> enum class RpcErrRecommendedAction : uint8_t { Retry = 0xF0, // just a mask for "retry category" SimpleRetry = 0xF2, // for regular issues: just try again after sleeping a constant amount of time RetryBackoff = 0xF4, // for resource related issues: try again with sleep intervals in exp back-off Reconnect = 0x02, // for connection related issues: attempt reconnection and try RPC again Quit = 0x04 // do not insist, just quit }; /// <summary> /// Tells by the RPC error status returned by stub call /// whether to retry, reconnect & retry or just quit. /// </summary> /// <param name="errCode">The RPC error code (status).</param> static RpcErrRecommendedAction GetRecommendation(RPC_STATUS errCode) { switch (errCode) { case RPC_S_CALL_CANCELLED: case RPC_S_CALL_FAILED_DNE: return RpcErrRecommendedAction::SimpleRetry; case RPC_S_SERVER_OUT_OF_MEMORY: case RPC_S_SERVER_TOO_BUSY: return RpcErrRecommendedAction::RetryBackoff; case RPC_S_COMM_FAILURE: case RPC_S_NOT_LISTENING: case EPT_S_NOT_REGISTERED: case RPC_S_SERVER_UNAVAILABLE: return RpcErrRecommendedAction::Reconnect; default: return RpcErrRecommendedAction::Quit; } } // Wraps RPC to isolate SEH code static RPC_STATUS CallbackWrapSEH(const std::function<void(rpc_binding_handle_t)> &rpc, rpc_binding_handle_t bindingHandle) { RPC_STATUS exCode; __try // Because RPC uses SEH, only SEH is allowed in this function { rpc(bindingHandle); return RPC_S_OK; } // catch with default exception filter: __except (RpcExceptionFilter(exCode = RpcExceptionCode())) { return exCode; } } /// <summary> /// Wraps an RPC (with retry loop when appropriate). /// </summary> /// <param name="tag">A tag for the RPC.</param> /// <param name="rpc">The RPC to make.</param> /// <param name="bindingHandle">The RPC binding handle.</param> /// <returns>The status of the RPC.</returns> static RPC_STATUS WrapRpc(const char *tag, const std::function<void(rpc_binding_handle_t)> &rpc, rpc_binding_handle_t bindingHandle) { int retryCount(0); // loop for retries: while (true) { auto status = CallbackWrapSEH(rpc, bindingHandle); if (status == RPC_S_OK) break; static const auto callMaxRetries = core::AppConfig::GetSettings().framework.rpc.cliCallMaxRetries; auto recomAction = GetRecommendation(status); bool mustNotRetry = (static_cast<uint8_t> (recomAction) & static_cast<uint8_t> (RpcErrRecommendedAction::Retry)) == 0; // must not try again? if (mustNotRetry || retryCount == callMaxRetries) { if (retryCount > 0) { std::array<char, 512> bufErrMsg; utils::SerializeTo(bufErrMsg, "RPC call '", tag, "' failed after ", retryCount, " attempt(s)"); core::Logger::Write(bufErrMsg.data(), core::Logger::PRIO_INFORMATION); } return status; } // Wait before retry: std::chrono::milliseconds interval; if (recomAction == RpcErrRecommendedAction::SimpleRetry) { static const auto callRetrySleepMs = core::AppConfig::GetSettings().framework.rpc.cliCallRetrySleepMs; interval = std::chrono::milliseconds(callRetrySleepMs); } else // with exponential back-off: { static const auto callRetryTimeSlotMs = core::AppConfig::GetSettings().framework.rpc.cliCallRetryTimeSlotMs; interval = utils::CalcExponentialBackOff(retryCount, std::chrono::milliseconds(callRetryTimeSlotMs)); } std::this_thread::sleep_for(interval); ++retryCount; }// end of loop if (retryCount > 0) { std::array<char, 512> bufErrMsg; utils::SerializeTo(bufErrMsg, "RPC call '", tag, "' had to retry ", retryCount, " time(s) before success"); core::Logger::Write(bufErrMsg.data(), core::Logger::PRIO_WARNING); } // quit on success return RPC_S_OK; } /// <summary> /// Invokes an RPC with error handling (and re-try/connect loop when appropriate). /// </summary> /// <param name="tag">A tag for the RPC.</param> /// <param name="rpc">The RPC to make.</param> void RpcClient::Call(const char *tag, const std::function<void(rpc_binding_handle_t)> &rpc) { CALL_STACK_TRACE; RPC_STATUS status; static const auto connectMaxRetries = core::AppConfig::GetSettings().framework.rpc.cliSrvConnectMaxRetries; int count; // loop for reconnection: for (count = 0; count <= connectMaxRetries; ++count) { status = WrapRpc(tag, rpc, GetBindingHandle()); if (GetRecommendation(status) != RpcErrRecommendedAction::Reconnect) break; /* Reset the bindings and take a nap. Next RPC will attempt to (connect and) bind again to the server: */ static const auto connRetrySleepSecs = core::AppConfig::GetSettings().framework.rpc.cliSrvConnRetrySleepSecs; // warn only once about lost connection: if (!m_isOnHold.exchange(true)) { std::array<char, 512> bufErrMsg; utils::SerializeTo(bufErrMsg, "RPC client stub lost connection to ", m_endpoint, " and will attempt a reconnection every ", connRetrySleepSecs, " seconds up to ", connectMaxRetries, " time(s)"); core::Logger::Write(bufErrMsg.data(), core::Logger::PRIO_WARNING); } ResetBindings(); std::this_thread::sleep_for( std::chrono::seconds(connRetrySleepSecs) ); } ThrowIfError(status, "Failed to invoke RPC client stub routine", tag); // notify only once about reconnection: if (m_isOnHold.exchange(false)) { std::array<char, 512> bufErrMsg; utils::SerializeTo(bufErrMsg, "RPC client stub succesfully reconnected to ", m_endpoint, " after ", count, " attempt(s)"); core::Logger::Write(bufErrMsg.data(), core::Logger::PRIO_WARNING); } } //////////////////////////////// // ScopedImpersonation Class //////////////////////////////// /// <summary> /// Initializes a new instance of the <see cref="ScopedImpersonation"/> class. /// </summary> /// <param name="clientBindingHandle">The client binding handle /// carrying the identity to impersonate.</param> ScopedImpersonation::ScopedImpersonation(rpc_binding_handle_t clientBindingHandle) : m_clientBindingHandle(clientBindingHandle) { CALL_STACK_TRACE; auto status = RpcImpersonateClient(clientBindingHandle); ThrowIfError(status, "Failed to impersonate indentity of RPC client"); } /// <summary> /// Finalizes an instance of the <see cref="ScopedImpersonation"/> class. /// </summary> ScopedImpersonation::~ScopedImpersonation() { CALL_STACK_TRACE; LogIfError( RpcRevertToSelfEx(m_clientBindingHandle), "Failed to revert impersonation of RPC client", core::Logger::PRIO_CRITICAL ); } }// end of namespace rpc }// end of namespace _3fd
38.76087
119
0.597457
[ "object" ]
be5f148cdfe9d25b307e8b9ba9bdcff833906607
36,837
cpp
C++
source/GCLCEngine/Cartesian2DCommands.cpp
CoghettoR/gclc
b481b15d28ee66f995b73283e26c285ca8c4a821
[ "MIT" ]
21
2020-12-08T20:06:01.000Z
2022-02-13T22:52:02.000Z
source/GCLCEngine/Cartesian2DCommands.cpp
CoghettoR/gclc
b481b15d28ee66f995b73283e26c285ca8c4a821
[ "MIT" ]
9
2020-12-20T03:54:55.000Z
2022-03-31T19:30:04.000Z
source/GCLCEngine/Cartesian2DCommands.cpp
CoghettoR/gclc
b481b15d28ee66f995b73283e26c285ca8c4a821
[ "MIT" ]
5
2021-04-25T18:47:17.000Z
2022-01-23T02:37:30.000Z
#include "../Input/GCLCInput.h" #include "GCLC.h" #include <cmath> #include <iomanip> #include <iostream> #include <sstream> // ---------------------------------------------------------------------------- GCLCError CGCLC::ang_picture() { GCLCError iRv; if ((iRv = ReadNumber(m_2D_Area.x_lb)) != rvGCLCOK) return iRv; if ((iRv = ReadNumber(m_2D_Area.y_lb)) != rvGCLCOK) return iRv; if ((iRv = ReadNumber(m_2D_Area.x_rt)) != rvGCLCOK) return iRv; if ((iRv = ReadNumber(m_2D_Area.y_rt)) != rvGCLCOK) return iRv; ANG_SCALE = 1.00; ANG_LOG = 1; return rvGCLCOK; } // ---------------------------------------------------------------------------- GCLCError CGCLC::ang_origin() { GCLCError iRv; if ((iRv = ReadNumber(X_ORIGIN)) != rvGCLCOK) return iRv; return ReadNumber(Y_ORIGIN); } // ---------------------------------------------------------------------------- GCLCError CGCLC::ang_unit() { return ReadNumber(UNIT); } // ---------------------------------------------------------------------------- GCLCError CGCLC::ang_scale() { double d; GCLCError iRv; if ((iRv = ReadNumber(d)) != rvGCLCOK) return iRv; ANG_LOG = (int)d; if (ANG_LOG < 1) ANG_LOG = 1; if (ANG_LOG > 2) ANG_LOG = 2; if ((iRv = ReadNumber(d)) != rvGCLCOK) return iRv; if (d <= 0) d = 1; ANG_SCALE = d; return rvGCLCOK; } // ---------------------------------------------------------------------------- GCLCError CGCLC::ang_draw_system_p() { GCLCError iRv; double number; int mark_integers, mark_axes, arrows, x_step, y_step; iRv = ReadNumber(number); if (iRv != rvGCLCOK) return iRv; mark_integers = (int)number; if (mark_integers < 1) mark_integers = 1; if (mark_integers > 3) mark_integers = 3; iRv = ReadNumber(number); if (iRv != rvGCLCOK) return iRv; x_step = (int)number; if (x_step < 1) x_step = 1; iRv = ReadNumber(number); if (iRv != rvGCLCOK) return iRv; y_step = (int)number; if (y_step < 1) y_step = 1; iRv = ReadNumber(number); if (iRv != rvGCLCOK) return iRv; mark_axes = (int)number; if (mark_axes < 1) mark_axes = 1; if (mark_axes > 2) mark_axes = 2; if ((iRv = ReadNumber(number)) != rvGCLCOK) return iRv; arrows = (int)number; if (arrows < 1) arrows = 1; if (arrows > 3) arrows = 3; return ang_draw_system(mark_integers, x_step, y_step, mark_axes, arrows); } // ---------------------------------------------------------------------------- GCLCError CGCLC::ang_draw_system(int t) { switch (t) { case 1: return ang_draw_system(1, 1, 1, 2, 1); case 2: return ang_draw_system(3, 1, 1, 2, 1); case 3: return ang_draw_system(2, 1, 1, 2, 1); case 101: return ang_draw_system(1, 1, 1, 1, 1); case 102: return ang_draw_system(3, 1, 1, 1, 1); case 103: return ang_draw_system(2, 1, 1, 1, 1); default: return ang_draw_system(1, 1, 1, 2, 1); } } // ---------------------------------------------------------------------------- GCLCError CGCLC::ang_draw_system(int mark_integers, int x_step, int y_step, int mark_axes, int arrows) { // char name[16]; double x, y; int i; double dash_halflen = 0.75; GCLCError iRv; string sComment = "Drawing 2D Cartesian system"; if (PrintComment(sComment) != rvG_OK) return rvCannotExport; switch (mark_integers) { case 1: { i = 0; x = X_ORIGIN; if (ANG_LOG == 1) y = ang_y(0); else y = ang_y(1); if ((x >= m_2D_Area.x_lb) && (x <= m_2D_Area.x_rt) && (y >= m_2D_Area.y_lb) && (y <= m_2D_Area.y_rt)) { if (!(i % x_step)) ang_cmark(x, y, GCLC_DIR_LB, i2s(i)); } x = x + UNIT; while (x <= m_2D_Area.x_rt) { i++; if (!(i % x_step)) { if ((x >= m_2D_Area.x_lb) && (x <= m_2D_Area.x_rt) && (y >= m_2D_Area.y_lb) && (y <= m_2D_Area.y_rt)) ang_cmark(x, y, GCLC_DIR_B, i2s(i)); } x = x + UNIT; } i = 0; x = X_ORIGIN; x = x - UNIT; while (x >= m_2D_Area.x_lb) { i++; if (!(i % x_step)) { if ((x >= m_2D_Area.x_lb) && (x <= m_2D_Area.x_rt) && (y >= m_2D_Area.y_lb) && (y <= m_2D_Area.y_rt)) ang_cmark(x, y, GCLC_DIR_B, i2s(-i)); } x = x - UNIT; } i = 0; x = X_ORIGIN; y = ang_y(1); while (y <= m_2D_Area.y_rt && i < 1000000000) { if (ANG_LOG == 1) i++; else i = (i == 0 ? 10 : i * 10); y = ang_y(i); if (((ANG_LOG == 1) && !(i % y_step)) || ((ANG_LOG == 2) && !(log_div(i, y_step)))) { if ((x >= m_2D_Area.x_lb) && (x <= m_2D_Area.x_rt) && (y >= m_2D_Area.y_lb) && (y <= m_2D_Area.y_rt)) ang_cmark(x, y, GCLC_DIR_L, i2s(i)); } } i = 0; x = X_ORIGIN; if (ANG_LOG == 1) y = ang_y(-1); else y = ang_y(0.1); while (y >= m_2D_Area.y_lb && i < 1000000000) { if (ANG_LOG == 1) { i++; y = ang_y(-i); } else { i = (i == 0 ? 10 : i * 10); y = ang_y(1.0 / i); } if (((ANG_LOG == 1) && !(i % y_step)) || ((ANG_LOG == 2) && !(log_div(i, y_step)))) { string name; if (ANG_LOG == 1) name = i2s(-i); else { name = d2s(1.0 / i, -1); trimrightzeros(name); } if ((x >= m_2D_Area.x_lb) && (x <= m_2D_Area.x_rt) && (y >= m_2D_Area.y_lb) && (y <= m_2D_Area.y_rt)) ang_cmark(x, y, GCLC_DIR_L, name); } } } break; case 2: { i = 0; x = X_ORIGIN; if (ANG_LOG == 1) y = ang_y(0); else y = ang_y(1); if ((x >= m_2D_Area.x_lb) && (x <= m_2D_Area.x_rt) && (y >= m_2D_Area.y_lb) && (y <= m_2D_Area.y_rt)) { if (!(i % x_step)) { ang_mark(x, y, GCLC_DIR_LB, i2s(i)); iRv = ang_fsegment(x, y - dash_halflen, x, y + dash_halflen); if (iRv != rvGCLCOK) return iRv; } } x = x + UNIT; while (x <= m_2D_Area.x_rt) { i++; if (!(i % x_step)) { if ((x >= m_2D_Area.x_lb) && (x <= m_2D_Area.x_rt) && (y >= m_2D_Area.y_lb) && (y <= m_2D_Area.y_rt)) { ang_mark(x, y, GCLC_DIR_B, i2s(i)); iRv = ang_fsegment(x, y - dash_halflen, x, y + dash_halflen); if (iRv != rvGCLCOK) return iRv; } } x = x + UNIT; } i = 0; x = X_ORIGIN; y = Y_ORIGIN; x = x - UNIT; while (x >= m_2D_Area.x_lb) { i++; if (!(i % x_step)) { if ((x >= m_2D_Area.x_lb) && (x <= m_2D_Area.x_rt) && (y >= m_2D_Area.y_lb) && (y <= m_2D_Area.y_rt)) { ang_mark(x, y, GCLC_DIR_B, i2s(-i)); iRv = ang_fsegment(x, y - dash_halflen, x, y + dash_halflen); if (iRv != rvGCLCOK) return iRv; } } x = x - UNIT; } i = 0; x = X_ORIGIN; y = ang_y(1); while (y <= m_2D_Area.y_rt && i < 1000000000) { if (ANG_LOG == 1) i++; else i = (i == 0 ? 1 : i * 10); y = ang_y(i); if (((ANG_LOG == 1) && !(i % y_step)) || ((ANG_LOG == 2) && !(log_div(i, y_step)))) { if ((x >= m_2D_Area.x_lb) && (x <= m_2D_Area.x_rt) && (y >= m_2D_Area.y_lb) && (y <= m_2D_Area.y_rt)) { ang_mark(x, y, GCLC_DIR_L, i2s(i)); iRv = ang_fsegment(x - dash_halflen, y, x + dash_halflen, y); if (iRv != rvGCLCOK) return iRv; } } } i = 0; x = X_ORIGIN; if (ANG_LOG == 1) y = ang_y(-1); else y = ang_y(0.1); while (y >= m_2D_Area.y_lb) { if (ANG_LOG == 1) { i++; y = ang_y(-i); } else { i = (i == 0 ? 10 : i * 10); y = ang_y(1.0 / i); } if (((ANG_LOG == 1) && !(i % y_step)) || ((ANG_LOG == 2) && !(log_div(i, y_step)))) { string name; if (ANG_LOG == 1) name = i2s(-i); else { name = d2s(1.0 / i, -1); trimrightzeros(name); } ang_mark(x, y, GCLC_DIR_L, name); iRv = ang_fsegment(x - dash_halflen, y, x + dash_halflen, y); if (iRv != rvGCLCOK) return iRv; } } } break; case 3: break; default: break; } switch (mark_axes) { case 1: { // denoting axes ang_mark(m_2D_Area.x_rt, Y_ORIGIN, GCLC_DIR_B, "x"); ang_mark(X_ORIGIN, m_2D_Area.y_rt, GCLC_DIR_L, "y"); } break; case 2: break; default: break; } switch (arrows) { case 1: if ((Y_ORIGIN >= m_2D_Area.y_lb) && (Y_ORIGIN <= m_2D_Area.y_rt)) { DrawSegment(m_2D_Area.x_lb, Y_ORIGIN, m_2D_Area.x_rt, Y_ORIGIN, true, false, m_2D_Area); ang_arrow(m_2D_Area.x_lb, Y_ORIGIN, m_2D_Area.x_rt, Y_ORIGIN); ang_arrow(m_2D_Area.x_rt, Y_ORIGIN, m_2D_Area.x_lb, Y_ORIGIN); } if ((X_ORIGIN >= m_2D_Area.x_lb) && (X_ORIGIN <= m_2D_Area.x_rt)) { DrawSegment(X_ORIGIN, m_2D_Area.y_lb, X_ORIGIN, m_2D_Area.y_rt, true, false, m_2D_Area); ang_arrow(X_ORIGIN, m_2D_Area.y_lb, X_ORIGIN, m_2D_Area.y_rt); ang_arrow(X_ORIGIN, m_2D_Area.y_rt, X_ORIGIN, m_2D_Area.y_lb); } break; case 2: if ((Y_ORIGIN >= m_2D_Area.y_lb) && (Y_ORIGIN <= m_2D_Area.y_rt)) { DrawSegment(m_2D_Area.x_lb, Y_ORIGIN, m_2D_Area.x_rt, Y_ORIGIN, true, false, m_2D_Area); ang_arrow(m_2D_Area.x_lb, Y_ORIGIN, m_2D_Area.x_rt, Y_ORIGIN); } if ((X_ORIGIN >= m_2D_Area.x_lb) && (X_ORIGIN <= m_2D_Area.x_rt)) { DrawSegment(X_ORIGIN, m_2D_Area.y_lb, X_ORIGIN, m_2D_Area.y_rt, true, false, m_2D_Area); ang_arrow(X_ORIGIN, m_2D_Area.y_lb, X_ORIGIN, m_2D_Area.y_rt); } break; case 3: iRv = ang_fsegment(m_2D_Area.x_lb, Y_ORIGIN, m_2D_Area.x_rt, Y_ORIGIN); if (iRv != rvGCLCOK) return iRv; iRv = ang_fsegment(X_ORIGIN, m_2D_Area.y_lb, X_ORIGIN, m_2D_Area.y_rt); if (iRv != rvGCLCOK) return iRv; break; default: break; } return rvGCLCOK; } // ---------------------------------------------------------------------------- GCLCError CGCLC::ang_point() { string sPointName; double x, y; GCLCError iRv; if (ReadToken(sPointName) != rvGCLCOK) return rvGCLCIdExpected; if ((iRv = ReadNumber(x)) != rvGCLCOK) return iRv; if ((iRv = ReadNumber(y)) != rvGCLCOK) return iRv; return Let(sPointName, GCLC_POINT, X_ORIGIN + UNIT * x, ang_y(y), 0.00, 0.00, 0.00, 0.00); } // ---------------------------------------------------------------------------- GCLCError CGCLC::ang_getx() { string sNumberName; GCLC_object o1; GCLCError iRv; if (ReadToken(sNumberName) != rvGCLCOK) return rvGCLCIdExpected; if ((iRv = ReadObject(GCLC_POINT, o1)) != rvGCLCOK) return iRv; return Let(sNumberName, GCLC_NUMBER, (o1.p[0] - X_ORIGIN) / UNIT, 0.00, 0.00, 0.00, 0.00, 0.00); } // ---------------------------------------------------------------------------- GCLCError CGCLC::ang_gety() { string sNumberName; GCLC_object o1; GCLCError iRv; if (ReadToken(sNumberName) != rvGCLCOK) return rvGCLCIdExpected; if ((iRv = ReadObject(GCLC_POINT, o1)) != rvGCLCOK) return iRv; return Let(sNumberName, GCLC_NUMBER, ang_y_inv(o1.p[1]), 0.00, 0.00, 0.00, 0.00, 0.00); } // ---------------------------------------------------------------------------- GCLCError CGCLC::ang_line() { string sLineName; double a, b, c; GCLCError iRv; if (ReadToken(sLineName) != rvGCLCOK) return rvGCLCIdExpected; if ((iRv = ReadNumber(a)) != rvGCLCOK) return iRv; if ((iRv = ReadNumber(b)) != rvGCLCOK) return iRv; if ((iRv = ReadNumber(c)) != rvGCLCOK) return iRv; return Let(sLineName, GCLC_LINE, a / UNIT, b / UNIT, (-a * X_ORIGIN - b * Y_ORIGIN) / UNIT + c, 0.00, 0.00, 0.00); } // ---------------------------------------------------------------------------- GCLCError CGCLC::ang_conic() { string sConicName; GCLCError iRv; double a, b, c, d, e, f; if (ReadToken(sConicName) != rvGCLCOK) return rvGCLCIdExpected; if ((iRv = ReadNumber(a)) != rvGCLCOK) return iRv; if ((iRv = ReadNumber(b)) != rvGCLCOK) return iRv; if ((iRv = ReadNumber(c)) != rvGCLCOK) return iRv; if ((iRv = ReadNumber(d)) != rvGCLCOK) return iRv; if ((iRv = ReadNumber(e)) != rvGCLCOK) return iRv; if ((iRv = ReadNumber(f)) != rvGCLCOK) return iRv; return Let(sConicName, GCLC_CONIC, a, b, c, d, e, f); } // ---------------------------------------------------------------------------- GCLCError CGCLC::ang_intersec2() { string sPointName1, sPointName2; GCLC_object o1, o2; GCLCError iRv; double x1, y1, x2, y2, a, b, c, d, e, f, a1, b1, c1, a0, b0, c0, d0; if (ReadToken(sPointName1) != rvGCLCOK) return rvGCLCIdExpected; if ((iRv = ReadToken(sPointName2)) != rvGCLCOK) return rvGCLCIdExpected; if ((iRv = ReadNextObject(o1)) != rvGCLCOK) return iRv; if ((o1.type != GCLC_LINE) && (o1.type != GCLC_CONIC)) return rvGCLCWrongType; if ((iRv = ReadNextObject(o2)) != rvGCLCOK) return iRv; if ((o2.type != GCLC_LINE) && (o2.type != GCLC_CONIC)) return rvGCLCWrongType; if (((o1.type != GCLC_CONIC) || (o2.type != GCLC_LINE)) && ((o2.type != GCLC_CONIC) || (o1.type != GCLC_LINE))) return rvGCLCWrongType; if (o1.type == GCLC_CONIC) { a = o1.p[0]; b = o1.p[1]; c = o1.p[2]; d = o1.p[3]; e = o1.p[4]; f = o1.p[5]; a1 = o2.p[0]; b1 = o2.p[1]; c1 = o2.p[2]; } else { a = o2.p[0]; b = o2.p[1]; c = o2.p[2]; d = o2.p[3]; e = o2.p[4]; f = o2.p[5]; a1 = o1.p[0]; b1 = o1.p[1]; c1 = o1.p[2]; } if (fabs(b1) > EPS) // transform to the ang system, changes w.r.t. ang_scale 22.01.2006 { x1 = 0; y1 = ang_y_inv(-(c1 + a1 * (x1 * UNIT + X_ORIGIN)) / b1); x2 = 1; y2 = ang_y_inv(-(c1 + a1 * (x2 * UNIT + X_ORIGIN)) / b1); b1 = 1.0; c1 = -y1; a1 = -c1 - y2; } else { c1 = -(-(c1 / a1) - X_ORIGIN) / UNIT; b1 = 0.0; a1 = 1.0; } if (fabs(a1) > EPS) { a0 = (a * b1 * b1 / (a1 * a1)) - (2 * b * b1 / a1) + c; b0 = (2 * a * b1 * c1 / (a1 * a1)) - (2 * b * c1 / a1) - (2 * d * b1 / a1) + 2 * e; c0 = a * c1 * c1 / (a1 * a1) - (2 * d * c1 / a1) + f; if (fabs(a0) < EPS) { y1 = -c0 / b0; x1 = -(c1 + b1 * y1) / a1; x2 = x1; y2 = y1; } else { d0 = b0 * b0 - 4 * a0 * c0; if (d0 < 0) return rvGCLCBadIntersection; y1 = (-b0 + sqrt(d0)) / (2 * a0); x1 = -(c1 + b1 * y1) / a1; y2 = (-b0 - sqrt(d0)) / (2 * a0); x2 = -(c1 + b1 * y2) / a1; } x1 = x1 * UNIT + X_ORIGIN; y1 = ang_y(y1); x2 = x2 * UNIT + X_ORIGIN; y2 = ang_y(y2); } else { a0 = (b * a1 * a1 / (b1 * b1)) - (2 * b * a1 / b1) + a; b0 = (2 * c * a1 * c1 / (b1 * b1)) - (2 * b * c1 / b1) - (2 * e * a1 / b1) + 2 * d; c0 = c * c1 * c1 / (b1 * b1) - (2 * e * c1 / b1) + f; if (fabs(a0) < EPS) { x1 = -c0 / b0; y1 = -(c1 + a1 * x1) / b1; x2 = x1; y2 = y1; } else { d0 = b0 * b0 - 4 * a0 * c0; if (d0 < 0) return rvGCLCBadIntersection; x1 = (-b0 + sqrt(d0)) / (2 * a0); y1 = -(c1 + a1 * x1) / b1; x2 = (-b0 - sqrt(d0)) / (2 * a0); y2 = -(c1 + a1 * x2) / b1; } x1 = x1 * UNIT + X_ORIGIN; y1 = ang_y(y1); x2 = x2 * UNIT + X_ORIGIN; y2 = ang_y(y2); } if ((iRv = Let(sPointName1, GCLC_POINT, x1, y1, 0.00, 0.00, 0.00, 0.00)) != rvGCLCOK) return iRv; return Let(sPointName2, GCLC_POINT, x2, y2, 0.00, 0.00, 0.00, 0.00); } // ---------------------------------------------------------------------------- GCLCError CGCLC::ang_tangent() { string sLineName; GCLC_object o1, o2; GCLCError iRv; double A, B, C, D, E, a, b, c; double x, y; double x1, y1, x2, y2; if (ReadToken(sLineName) != rvGCLCOK) return rvGCLCIdExpected; if ((iRv = ReadObject(GCLC_POINT, o1)) != rvGCLCOK) return iRv; if ((iRv = ReadObject(GCLC_CONIC, o2)) != rvGCLCOK) return iRv; x = (o1.p[0] - X_ORIGIN) / UNIT; y = ang_y_inv(o1.p[1]); A = o2.p[0]; B = o2.p[1]; C = o2.p[2]; D = o2.p[3]; E = o2.p[4]; a = 2 * A * x + 2 * B * y + 2 * D; b = (2 * B * x + 2 * C * y + 2 * E); c = -a * x - b * y; if (fabs(b) > EPS) // changes w.r.t. ang_scale 22.01.2006 { x1 = o1.p[0]; y1 = ang_y(-(c + a * (x1 - X_ORIGIN) / UNIT) / b); x2 = (fabs(x1 - X_ORIGIN) < EPS) ? X_ORIGIN + UNIT : X_ORIGIN; y2 = ang_y(-(c + a * (x2 - X_ORIGIN) / UNIT) / b); a = -(y2 - y1) / (x2 - x1); b = 1.0; c = -a * x1 - y1; } else { c = -((-c / a) * UNIT + X_ORIGIN); a = 1.0; b = 0.0; } return Let(sLineName, GCLC_LINE, a, b, c, 0.00, 0.00, 0.00); } // ---------------------------------------------------------------------------- GCLCError CGCLC::ang_draw_line() { GCLC_object o1; GCLCError iRv; if ((iRv = ReadObject(GCLC_LINE, o1)) != rvGCLCOK) return iRv; if (PrintComment("Drawing 2D ang line " + o1.name) != rvG_OK) return rvCannotExport; if (o1.p[1] != 0) return ang_fline(0.00, (-o1.p[2]) / o1.p[1], 1.00, (-o1.p[0] - o1.p[2]) / o1.p[1]); else return ang_fline((-o1.p[2]) / o1.p[0], 0.00, (-o1.p[1] - o1.p[2]) / o1.p[0], 1.00); } // ---------------------------------------------------------------------------- GCLCError CGCLC::ang_draw_line_p() { GCLC_object o1, o2; GCLCError iRv; if ((iRv = ReadObject(GCLC_POINT, o1)) != rvGCLCOK) return iRv; if ((iRv = ReadObject(GCLC_POINT, o2)) != rvGCLCOK) return iRv; if ((m_2D_Area.x_lb == 0) && (m_2D_Area.x_rt == 0) && (m_2D_Area.y_lb == 0) && (m_2D_Area.y_rt == 0)) return rvGCLCOK; if (PrintComment("Drawing 2D ang line " + o1.name + " " + o2.name) != rvG_OK) return rvCannotExport; return ang_fline(o1.p[0], o1.p[1], o2.p[0], o2.p[1]); } // ---------------------------------------------------------------------------- GCLCError CGCLC::ang_draw_conic(int dashed) { GCLC_object o1; double A, B, C, D, E, F; double y1, y2, y3, y4, y5, y6, x0, x_scr, scr_unit, x1, x2, x5, x_aux; int r1, r2, r3, r, num, i; GCLCError iRv; if ((iRv = ReadObject(GCLC_CONIC, o1)) != rvGCLCOK) return iRv; A = o1.p[0]; B = o1.p[1]; C = o1.p[2]; D = o1.p[3]; E = o1.p[4]; F = o1.p[5]; if (PrintComment("Drawing 2D ang conic " + o1.name) != rvG_OK) return rvCannotExport; num = CONIC_PRECISION; scr_unit = (m_2D_Area.x_rt - m_2D_Area.x_lb) / (double)num; x0 = (-X_ORIGIN) / UNIT; solve(C, 2 * B * x0 + 2 * E, A * x0 * x0 + 2 * D * x0 + F, y3, y4, r2); x_scr = -scr_unit + m_2D_Area.x_lb; for (i = 0; i <= num; i++) { x_scr = x_scr + scr_unit; x0 = (x_scr - X_ORIGIN) / UNIT; y1 = 0; y2 = 0; r1 = 0; r = solve(C, 2 * B * x0 + 2 * E, A * x0 * x0 + 2 * D * x0 + F, y1, y2, r1); if (i >= 0) { if (r1 == 0) { if (r2 == 2) { solve(B * B - A * C, 2 * E * B - 2 * D * C, E * E - C * F, x1, x2, r); if (x1 > x2) { x_aux = x1; x1 = x2; x2 = x_aux; } if (x2 > x0) { r = solve(C, 2 * B * x1 + 2 * E, A * x1 * x1 + 2 * D * x1 + F, y5, y6, r3); x5 = ((X_ORIGIN + UNIT * x1) + (x_scr - scr_unit)) / 2; if (!dashed || !(i % 2)) ang_fsegment(X_ORIGIN + UNIT * x1, ang_y(y5), x5, ang_y((y3 + y5) / 2)); if (!dashed || (i % 2)) ang_fsegment(x5, ang_y((y5 + y3) / 2), x_scr - scr_unit, ang_y(y3)); if (!dashed || (i % 2)) ang_fsegment(X_ORIGIN + UNIT * x1, ang_y(y5), x5, ang_y((y4 + y5) / 2)); if (!dashed || !(i % 2)) ang_fsegment(x5, ang_y((y5 + y4) / 2), x_scr - scr_unit, ang_y(y4)); } else { r = solve(C, 2 * B * x2 + 2 * E, A * x2 * x2 + 2 * D * x2 + F, y5, y6, r3); x5 = ((X_ORIGIN + UNIT * x2) + (x_scr - scr_unit)) / 2; if (!dashed || !(i % 2)) ang_fsegment(X_ORIGIN + UNIT * x2, ang_y(y5), x5, ang_y((y3 + y5) / 2)); if (!dashed || (i % 2)) ang_fsegment(x5, ang_y((y5 + y3) / 2), x_scr - scr_unit, ang_y(y3)); if (!dashed || (i % 2)) ang_fsegment(X_ORIGIN + UNIT * x2, ang_y(y5), x5, ang_y((y4 + y5) / 2)); if (!dashed || !(i % 2)) ang_fsegment(x5, ang_y((y5 + y4) / 2), x_scr - scr_unit, ang_y(y4)); } } } else if (r1 == 1) { if (r2 == 2) { if (!dashed || (i % 2)) ang_fsegment(x_scr - scr_unit, ang_y(y3), x_scr, ang_y(y1)); if (!dashed || !(i % 2)) ang_fsegment(x_scr - scr_unit, ang_y(y4), x_scr, ang_y(y1)); } else if (r2 == 1) { if (!dashed || (i % 2)) ang_fsegment(x_scr - scr_unit, ang_y(y3), x_scr, ang_y(y1)); } } else if (r1 == 2) { if (r2 == 0) { solve(B * B - A * C, 2 * E * B - 2 * D * C, E * E - C * F, x1, x2, r); if (x1 > x2) { x_aux = x1; x1 = x2; x2 = x_aux; } if (x2 > x0) { r = solve(C, 2 * B * x1 + 2 * E, A * x1 * x1 + 2 * D * x1 + F, y5, y6, r3); x5 = ((X_ORIGIN + UNIT * x1) + x_scr) / 2; if (!dashed || !(i % 2)) ang_fsegment(X_ORIGIN + UNIT * x1, ang_y(y5), x5, ang_y((y1 + y5) / 2)); if (!dashed || (i % 2)) ang_fsegment(x5, ang_y((y5 + y1) / 2), x_scr, ang_y(y1)); if (!dashed || (i % 2)) ang_fsegment(X_ORIGIN + UNIT * x1, ang_y(y5), x5, ang_y((y2 + y5) / 2)); if (!dashed || !(i % 2)) ang_fsegment(x5, ang_y((y5 + y2) / 2), x_scr, ang_y(y2)); } else { r = solve(C, 2 * B * x2 + 2 * E, A * x2 * x2 + 2 * D * x2 + F, y5, y6, r3); x5 = ((X_ORIGIN + UNIT * x2) + x_scr) / 2; if (!dashed || !(i % 2)) ang_fsegment(X_ORIGIN + UNIT * x2, ang_y(y5), x5, ang_y((y1 + y5) / 2)); if (!dashed || (i % 2)) ang_fsegment(x5, ang_y((y5 + y1) / 2), x_scr, ang_y(y1)); if (!dashed || (i % 2)) ang_fsegment(X_ORIGIN + UNIT * x2, ang_y(y5), x5, ang_y((y2 + y5) / 2)); if (!dashed || !(i % 2)) ang_fsegment(x5, ang_y((y5 + y2) / 2), x_scr, ang_y(y2)); } } else if (r2 == 1) { if (!dashed || (i % 2)) ang_fsegment(x_scr - scr_unit, ang_y(y3), x_scr, ang_y(y1)); if (!dashed || !(i % 2)) ang_fsegment(x_scr - scr_unit, ang_y(y3), x_scr, ang_y(y2)); } else if (r2 == 2) { if (y3 > y4) { if (y1 > y2) { if (!dashed || (i % 2)) ang_fsegment(x_scr - scr_unit, ang_y(y3), x_scr, ang_y(y1)); if (!dashed || !(i % 2)) ang_fsegment(x_scr - scr_unit, ang_y(y4), x_scr, ang_y(y2)); } else { if (!dashed || !(i % 2)) ang_fsegment(x_scr - scr_unit, ang_y(y4), x_scr, ang_y(y1)); if (!dashed || (i % 2)) ang_fsegment(x_scr - scr_unit, ang_y(y3), x_scr, ang_y(y2)); } } else { if (y1 > y2) { if (!dashed || (i % 2)) ang_fsegment(x_scr - scr_unit, ang_y(y4), x_scr, ang_y(y1)); if (!dashed || !(i % 2)) ang_fsegment(x_scr - scr_unit, ang_y(y3), x_scr, ang_y(y2)); } else { if (!dashed || !(i % 2)) ang_fsegment(x_scr - scr_unit, ang_y(y3), x_scr, ang_y(y1)); if (!dashed || (i % 2)) ang_fsegment(x_scr - scr_unit, ang_y(y4), x_scr, ang_y(y2)); } } } } // r1==1 r2 = r1; y3 = y1; y4 = y2; } } return rvGCLCOK; } // ---------------------------------------------------------------------------- GCLCError CGCLC::ang_draw_parametric_curve() { string sNumberName; GCLCError iRv; double dNumber; string text; string init_text; string cond_text; string iter_text; string x_text; string y_text; double x, y, x_old = 0, y_old = 0; if (ReadToken(sNumberName) != rvGCLCOK) return rvGCLCIdExpected; bool bSupressWarnings = m_bSupressWarnings; m_bSupressWarnings = true; if ((iRv = Let(sNumberName, GCLC_NUMBER, 0, 0.00, 0.00, 0.00, 0.00, 0.00)) != rvGCLCOK) { m_bSupressWarnings = bSupressWarnings; return iRv; } if ((iRv = take_text(text)) != rvGCLCOK) { m_bSupressWarnings = bSupressWarnings; return iRv; } if (text.find(';') != string::npos) { init_text = text.substr(0, text.find(';')); text = text.substr(text.find(';') + 1); } else { m_bSupressWarnings = bSupressWarnings; return rvGCLCSeparatorExpected; } if (text.find(';') != string::npos) { cond_text = text.substr(0, text.find(';')); text = text.substr(text.find(';') + 1); } else { m_bSupressWarnings = bSupressWarnings; return rvGCLCSeparatorExpected; } iter_text = text; if ((iRv = take_text(text)) != rvGCLCOK) { m_bSupressWarnings = bSupressWarnings; return iRv; } if (text.find(';') != string::npos) { x_text = text.substr(0, text.find(';')); text = text.substr(text.find(';') + 1); } else { m_bSupressWarnings = bSupressWarnings; return rvGCLCSeparatorExpected; } y_text = text; if (PrintComment("Drawing 2D parametric curve (" + x_text + "," + y_text + ")") != rvG_OK) return rvCannotExport; bool bFirst = true; double v; if ((iRv = calc_expression(init_text, v)) != rvGCLCOK) { m_bSupressWarnings = bSupressWarnings; return iRv; } if ((iRv = Let(sNumberName, GCLC_NUMBER, v, 0.00, 0.00, 0.00, 0.00, 0.00)) != rvGCLCOK) { m_bSupressWarnings = bSupressWarnings; return iRv; } if ((iRv = calc_expression(cond_text, dNumber)) != rvGCLCOK) { m_bSupressWarnings = bSupressWarnings; return iRv; } bool bDefined; while (dNumber == 1.0) { bDefined = true; if ((iRv = calc_expression(x_text, x)) != rvGCLCOK) bDefined = false; if ((iRv = calc_expression(y_text, y)) != rvGCLCOK) bDefined = false; if (!bFirst) if ((ang_y(y_old) < 1 * m_2D_Area.y_lb) && (ang_y(y_old) > 1 * m_2D_Area.y_rt)) bDefined = false; if ((ang_y(y) > 1 * m_2D_Area.y_rt) && (ang_y(y) < 1 * m_2D_Area.y_lb)) bDefined = false; if (!bFirst && bDefined) { // connect to the previous one if ((iRv = ang_fsegment(X_ORIGIN + UNIT * x, ang_y(y), X_ORIGIN + UNIT * x_old, ang_y(y_old))) != rvGCLCOK) { m_bSupressWarnings = bSupressWarnings; return iRv; } } bFirst = !bDefined; x_old = x; y_old = y; if ((iRv = calc_expression(iter_text, v)) != rvGCLCOK) { m_bSupressWarnings = bSupressWarnings; return iRv; } if ((v > 0 && v < EPS) || (v < 0 && v > -EPS)) v = 0; if ((iRv = Let(sNumberName, GCLC_NUMBER, v, 0.00, 0.00, 0.00, 0.00, 0.00)) != rvGCLCOK) { m_bSupressWarnings = bSupressWarnings; return iRv; } if ((iRv = calc_expression(cond_text, dNumber)) != rvGCLCOK) { m_bSupressWarnings = bSupressWarnings; return iRv; } } m_bSupressWarnings = bSupressWarnings; return rvGCLCOK; } // ---------------------------------------------------------------------------- GCLCError CGCLC::get_conicprecision() { double num; GCLCError iRv; if ((iRv = ReadNumber(num)) != rvGCLCOK) return iRv; CONIC_PRECISION = (int)num; return rvGCLCOK; } // ---------------------------------------------------------------------------- GCLCError CGCLC::ang_plot_data() { GReturnValue rv; GCLCError iRv; bool bMarkDots; bool bFirst = true; unsigned char c; double d, x, y, x_old, y_old; if ((iRv = ReadNumber(d)) != rvGCLCOK) return iRv; bMarkDots = (d != 0); do { if ((rv = m_Input->ReadChar(c)) != rvG_OK) return rvGCLCLBracketExpected; if (rv == rvG_InvalidInput) return rvGCLCInvalidInput; } while ((c == ' ') || (c == '\n') || (c == 9) || (c == '\t') || (c == '\r')); if (c != '{') return rvGCLCLBracketExpected; for (;;) { iRv = ReadToken(); if (LastToken() == "}") return rvGCLCOK; if (iRv != rvGCLCOK) return rvGCLCIdOrNumberExpected; convert(LastToken(), x); if ((iRv = ReadToken()) != rvGCLCOK) return rvGCLCIdOrNumberExpected; convert(LastToken(), y); if (bMarkDots) { if ((iRv = ang_cmark(X_ORIGIN + UNIT * x, ang_y(y), 0, "")) != rvGCLCOK) return iRv; } if (bFirst) bFirst = false; else { // connect to the previous one if ((iRv = ang_fsegment(X_ORIGIN + UNIT * x, ang_y(y), X_ORIGIN + UNIT * x_old, ang_y(y_old))) != rvGCLCOK) return iRv; } x_old = x; y_old = y; } return rvGCLCOK; } // ---------------------------------------------------------------------------- GCLCError CGCLC::ang_mark(double x0, double y0, int dir, const string &name) { return ang_2D_3D_mark(x0, y0, dir, name, m_2D_Area); } // ---------------------------------------------------------------------------- GCLCError CGCLC::ang_cmark(double x0, double y0, int dir, const string &name) { return ang_2D_3D_cmark(x0, y0, dir, name, m_2D_Area); } // ---------------------------------------------------------------------------- GCLCError CGCLC::ang_arrow(double x1, double y1, double x2, double y2) { return ang_2D_3D_arrow(x1, y1, x2, y2, m_2D_Area); } // ---------------------------------------------------------------------------- double CGCLC::ang_y(double y) { if (ANG_LOG == 1) return y * UNIT * ANG_SCALE + Y_ORIGIN; else return log10(y) * UNIT * ANG_SCALE + Y_ORIGIN; } // ---------------------------------------------------------------------------- double CGCLC::ang_y_inv(double y) { if (ANG_LOG == 1) return (y - Y_ORIGIN) / (UNIT * ANG_SCALE); else return pow(10.0, ((y - Y_ORIGIN) / (UNIT * ANG_SCALE))); } // ---------------------------------------------------------------------------- GCLCError CGCLC::ang_fsegment(double x1, double y1, double x2, double y2) { if ((m_2D_Area.x_lb == 0) && (m_2D_Area.x_rt == 0) && (m_2D_Area.y_lb == 0) && (m_2D_Area.y_rt == 0)) return rvGCLCOK; if (DrawSegment(x1, y1, x2, y2, true, false, m_2D_Area) != rvG_OK) return rvCannotExport; else return rvGCLCOK; } // ---------------------------------------------------------------------------- GCLCError CGCLC::ang_fline(double x1, double y1, double x2, double y2) { if ((m_2D_Area.x_lb == 0) && (m_2D_Area.x_rt == 0) && (m_2D_Area.y_lb == 0) && (m_2D_Area.y_rt == 0)) return rvGCLCOK; if (DrawLineSensitive(x1, y1, x2, y2, false, m_2D_Area) != rvG_OK) return rvCannotExport; else return rvGCLCOK; } // ---------------------------------------------------------------------------- GCLCError CGCLC::ang_2D_3D_mark(double x0, double y0, int dir, const string &name, GCLC_area &area) { string pos; double x, y; if ((area.x_lb == 0) && (area.x_rt == 0) && (area.y_lb == 0) && (area.y_rt == 0)) return rvGCLCOK; switch (dir) { case GCLC_DIR_LT: x = x0 - DM; y = y0 + DM; pos = "[rb]"; break; case GCLC_DIR_L: x = x0 - DM; y = y0; pos = "[r]"; break; case GCLC_DIR_LB: x = x0 - DM; y = y0 - DM; pos = "[rt]"; break; case GCLC_DIR_T: x = x0; y = y0 + DM; pos = "[b]"; break; case GCLC_DIR_B: x = x0; y = y0 - DM; pos = "[t]"; break; case GCLC_DIR_RT: x = x0 + DM; y = y0 + DM; pos = "[lb]"; break; case GCLC_DIR_R: x = x0 + DM; y = y0; pos = "[l]"; break; case GCLC_DIR_RB: x = x0 + DM; y = y0 - DM; pos = "[lt]"; break; default: x = x0; y = y0; pos = ""; break; } if (dir != 0) { PrintText(x, y, pos, name, area); } return rvGCLCOK; } // ---------------------------------------------------------------------------- GCLCError CGCLC::ang_2D_3D_cmark(double x0, double y0, int dir, const string &name, GCLC_area &area) { string pos; double x, y; if ((area.x_lb == 0) && (area.x_rt == 0) && (area.y_lb == 0) && (area.y_rt == 0)) return rvGCLCOK; DrawCircle(x0, y0, x0 + MARK_RADIUS, y0, false, false, area, MARK_CIRCLE_PRECISION); EmptyCircle(x0, y0, x0 + MARK_RADIUS, y0, area); switch (dir) { case GCLC_DIR_LT: x = x0 - DM; y = y0 + DM; pos = "[rb]"; break; case GCLC_DIR_L: x = x0 - DM; y = y0; pos = "[r]"; break; case GCLC_DIR_LB: x = x0 - DM; y = y0 - DM; pos = "[rt]"; break; case GCLC_DIR_T: x = x0; y = y0 + DM; pos = "[b]"; break; case GCLC_DIR_B: x = x0; y = y0 - DM; pos = "[t]"; break; case GCLC_DIR_RT: x = x0 + DM; y = y0 + DM; pos = "[lb]"; break; case GCLC_DIR_R: x = x0 + DM; y = y0; pos = "[l]"; break; case GCLC_DIR_RB: x = x0 + DM; y = y0 - DM; pos = "[lt]"; break; default: x = x0; y = y0; pos = ""; break; } if (dir != 0) PrintText(x, y, pos, name, area); return rvGCLCOK; } // ---------------------------------------------------------------------------- GCLCError CGCLC::ang_2D_3D_arrow(double x1, double y1, double x2, double y2, GCLC_area &area) { GCLC_object o1, o2; double d, c, s, x, y, x0, y0; if ((area.x_lb == 0) && (area.x_rt == 0) && (area.y_lb == 0) && (area.y_rt == 0)) return rvGCLCOK; o1.p[0] = x1; o1.p[1] = y1; o2.p[0] = x2; o2.p[1] = y2; d = sqrt((o1.p[0] - o2.p[0]) * (o1.p[0] - o2.p[0]) + (o1.p[1] - o2.p[1]) * (o1.p[1] - o2.p[1])); x0 = (o1.p[0] - o2.p[0]) / d + o2.p[0]; y0 = (o1.p[1] - o2.p[1]) / d + o2.p[1]; c = cos(PI / 24); s = sin(PI / 24); x = (3 / d) * ((o1.p[0] - o2.p[0]) * c + (o1.p[1] - o2.p[1]) * s) + o2.p[0]; y = (3 / d) * (-(o1.p[0] - o2.p[0]) * s + (o1.p[1] - o2.p[1]) * c) + o2.p[1]; DrawSegment(x, y, o2.p[0], o2.p[1], true, false, area); DrawSegment(x, y, x0, y0, true, false, area); s = -s; x = (3 / d) * ((o1.p[0] - o2.p[0]) * c + (o1.p[1] - o2.p[1]) * s) + o2.p[0]; y = (3 / d) * (-(o1.p[0] - o2.p[0]) * s + (o1.p[1] - o2.p[1]) * c) + o2.p[1]; DrawSegment(x, y, o2.p[0], o2.p[1], true, false, area); DrawSegment(x, y, x0, y0, true, false, area); return rvGCLCOK; } // ----------------------------------------------------------------------------
27.885693
86
0.451964
[ "transform" ]
415779ea1b9633d7b5510b5d14b97a28f26112c4
2,104
cpp
C++
library/Methods/Graphs/one-centroid-dynmaic-tree.cpp
sarafanshul/KACTL
fa14ed34e93cd32d8625ed3729ba2eee55838340
[ "MIT" ]
4
2021-01-05T09:25:59.000Z
2021-09-27T03:57:28.000Z
library/Methods/Graphs/one-centroid-dynmaic-tree.cpp
sarafanshul/KACTL
fa14ed34e93cd32d8625ed3729ba2eee55838340
[ "MIT" ]
null
null
null
library/Methods/Graphs/one-centroid-dynmaic-tree.cpp
sarafanshul/KACTL
fa14ed34e93cd32d8625ed3729ba2eee55838340
[ "MIT" ]
null
null
null
// Centroid(s) of a tree // https://codeforces.com/blog/entry/57593 /* "By the way, when you do Centroid Decomposition, you don't need to know 2 centroids of the tree. Therefore, if you just want to find 'a' centroid of a dynamic tree, you can implement this in the following way:" -> for deleting the centroid (1step towards decomposiotion) ./ Centroid_Node_Dead.cpp `Centroid of a Tree is a node which if removed from the tree would split it into a ‘forest’, such that any tree in the forest would have at most half the number of vertices in the original tree. ~ GeeksForGeeks` The centroid(s) of a tree is, the vertice(s) whose all subtrees' size is not more than n(the size of the whole tree). -> A tree may have one centroid or may have two centroids. If it has two centroids, they are always connected (otherwise, the tree can't have n vertices). -> You can find these vertices by checking the size of each subtree, doing DFS. When the size of a subtree is s, the size of the other part is n - s. */ int OneCentroid(int root, const vector<vector<int>> &g, const vector<bool> &dead) { static vector<int> sz(g.size()); function<void (int, int)> get_sz = [&](int u, int prev) { sz[u] = 1; for (auto v : g[u]) if (v != prev && !dead[v]) { get_sz(v, u); sz[u] += sz[v]; } }; get_sz(root, -1); int n = sz[root]; function<int (int, int)> dfs = [&](int u, int prev) { for (auto v : g[u]) if (v != prev && !dead[v]) { if (sz[v] > n / 2) { return dfs(v, u); } } return u; }; return dfs(root, -1); } void test(){ int n ,u ,v; cin >> n; vector<vector<int>> g(n); for(int i = 0; i < n-1 ;i++){ cin >> u>> v;u-- ,v--; g[u].PB(v); g[v].PB(u); } bool dead(n ,0); // declare the dead node first int centroid = OneCentroid(root ,g ,dead); if (centroids.size() == 1) { int c = centroids[0]; } else if (centroids.size() == 2) { int c1 = centroids[0]; int c2 = centroids[1]; } else { assert(false); } }
28.821918
211
0.594582
[ "vector" ]
416b7f7211b44493a18227c8bf59922dadf8b977
14,455
cpp
C++
test/test_01/test_01.cpp
tamask1s/zax-tensor
1f1bed9dd255c6023925598a568218997949a849
[ "Apache-2.0" ]
2
2022-01-03T09:23:27.000Z
2022-01-03T12:24:33.000Z
test/test_01/test_01.cpp
tamask1s/zax-tensor
1f1bed9dd255c6023925598a568218997949a849
[ "Apache-2.0" ]
null
null
null
test/test_01/test_01.cpp
tamask1s/zax-tensor
1f1bed9dd255c6023925598a568218997949a849
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <string> #include <map> #include <random> #include <vector> #include <algorithm> #include <typeinfo> #include <cstring> #include <stdio.h> #include <cstdlib> using namespace std; #include "ZaxJsonParser.h" #include "ZaxTensor.h" struct CClassInside { int x = 11; int y = 7; virtual void zax_from_json(const char* a_json, std::string* a_err_stream = 0) { x = atoi(a_json + 1); y = atoi(a_json + 1); } virtual int zax_to_json(char* a_json, int a_alloc_size, int a_deep = 0) const { int res = snprintf(a_json, a_alloc_size, "[%d, %d]", x, y); return res; } }; struct CClassInside2 { int x = 11; int y = 7; ZAX_JSON_SERIALIZABLE(CClassInside2, JSON_PROPERTY(x), JSON_PROPERTY(y)) }; #define CClass_JOSONProps\ JSON_PROPERTY(m_int_3d),\ JSON_PROPERTY(title),\ JSON_PROPERTY(x),\ JSON_PROPERTY(intmx),\ JSON_PROPERTY(m_float_id_of_id),\ JSON_PROPERTY(m_int_1d_of_2d),\ JSON_PROPERTY(inside),\ JSON_PROPERTY(inside2),\ JSON_PROPERTY(m_float_1d) struct CClass { float_1d m_float_1d; array_of_tensor_f32 m_int_1d_of_2d; int_3d m_int_3d; int_2d intmx; array_of_tensor_f32 m_float_id_of_id; CClassInside inside; CClassInside2 inside2; int x = 6; string title = "some title"; ZAX_JSON_SERIALIZABLE_WDC(CClass, CClass_JOSONProps) CClass() { m_int_3d.resize(3,3,3); m_int_3d[1][1][1] = 99; m_int_3d[0][1][1] = 11; m_int_3d[1][1][0] = 110; m_int_3d[2][1][0] = 210; intmx.resize(3,3); unsigned int sizes[] = {3,2,5}; m_float_id_of_id.resize(3); m_float_id_of_id[0].resize(sizes[0]); m_float_id_of_id[1].resize(sizes[1]); m_float_id_of_id[2].resize(sizes[2]); m_int_1d_of_2d.resize(2); m_int_1d_of_2d[0].resize(2,4); m_int_1d_of_2d[1].resize(3,5); m_float_1d.resize(11); } }; void tensor_example_01() { float_2d _2d(3,2); cout << _2d << endl; } void tensor_example_02() { float_2d _2d(3,2); _2d = R"([[81,90], [0,2], [-1,3]])"; cout << _2d << endl; } void tensor_example_03() { float_2d _2d(3,2); _2d = R"([[81,90], [0,2], [-1,3]])"; tensor_base<float>& tmpt = _2d; cout << tmpt << endl; } void tensor_example_04() { float_2d _2d(3,2); _2d = R"([[81,90], [0,2], [-1,3]])"; float_2d _2d2(2, 3, _2d.data()); cout << _2d2 << endl; } void tensor_example_05() { float_2d _2d(3,2); _2d = R"([[81,90], [0,2], [-1,3]])"; float_2d _2d2(2, 3, _2d.m_data[0]); cout << _2d2 << endl; } void tensor_example_06() { float_2d _2d = R"([[81,90], [0,2], [-1,3]])"; float_2d _2d2(2, 3, _2d.m_data[0]); cout << _2d2 << endl; } void tensor_example_07() { array_of_tensor_f32 m_float_id_of_id; m_float_id_of_id = R"([[81,90,0], [0,2], [-1,0,3,0,9]])"; cout << "m_float_id_of_id: "<< m_float_id_of_id << endl; } void tensor_example_08() { array_of_tensor_f32 m_float_id_of_id = R"([[81,90,0], [0,2], [-1,0,3,0,9]])"; m_float_id_of_id[1](1)++; cout << "m_float_id_of_id[1][1]: "<< m_float_id_of_id[1](1) << endl; } void tensor_example_09() { array_of_tensor_f32 m_float_id_of_id = R"([[81,90,0], [0,2], [-1,0,3,0,9]])"; m_float_id_of_id[1](1)++; cout << "m_float_id_of_id[1][1]: "<< m_float_id_of_id[1](1) << endl; } void tensor_example_10() { float_1d vector1; vector1.resize(3); vector1[0] = 4; cout << "vector1: " << vector1 << endl; } void tensor_example_11() { float_1d vector1; vector1.resize(3); vector1[0] = 4; vector1 = R"([1,2,3])"; cout << "vector1: " << vector1 << endl; } void tensor_example_12() { tensor_4d<int> tmp1(2, 3, 4, 5); cout << "tmp1[0][0][0][0]:" << tmp1[0][0][0][0] << endl; tmp1[0][0][0][0] = 1; cout << "tmp1[0][0][0][0]:" << tmp1[0][0][0][0] << endl; } void tensor_example_13() { CClass some_obj; some_obj = R"({"title":"some title", "m_int_3d":[ [ [0,1,0], [0,0,0], [0,2,0]], [ [0,0,0], [0,0,3], [4,0,0]], [ [0,0,0], [0,5,0], [0,0,6]]], "x":6, "intmx":[ [7995588,7995588,0], [0,2,0], [-1,0,3]], "m_float_id_of_id":[ [7995588,7995588,0], [0,2], [-1,0,3,0,9]], "inside":[11, 7], "m_int_1d_of_2d":[ [ [1,0,0,0], [0,2,0,0]], [ [0,0,0,0,0], [0,0,3,4,0], [0,0,0,5,0]]], "m_float_1d": [22,0.000000,47,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,0.000000,37]})"; cout << some_obj << endl; } void tensor_example_14() { CClass some_obj = "{\"title\": \"some other title\", \"x\": 17, \"inside\":{56}}"; cout << some_obj << endl; } void tensor_example_15() { float_3d _3d(2,2,3); float_4d _4d(2,2,2,3); _3d = R"([[[1.000000,2.000000,5.000000],[3.000000,4.000000,5.000000]],[[5.000000,6.000000,5.000000],[7.000000,8.000000,5.000000]]])"; _4d = R"([ [ [ [1,2,5], [3,4,5]], [ [5,6,5], [7,8,5]]], [ [ [9,10,5], [11,12,5]], [ [13,14,5], [15,16,5]]]])"; cout << _3d << endl; _4d[0][0][0][0] = 9; cout << _4d << endl; cout << "--------------------------------" << endl; float_4d _4d2(1,1,24,1, _4d.m_data[0][0][0]); cout << _4d2 << endl; cout << "--------------------------------" << endl; float_4d _4d3; _4d3 = _4d; cout << "_4d3 and _4d numel: " << _4d3.numel() << " / " << _4d.numel() << endl; cout << _4d << endl; cout << _4d3 << endl; cout << "_4d3 == _4d: " << (_4d3 == _4d) << endl; _4d[0][0][0][0] = 10; cout << "_4d3 == _4d: " << (_4d3 == _4d) << endl; cout << "--------------------------------" << endl; string tmp = _4d; _4d3.reshape(2,6,1,2); cout << "_4d3 == _4d: " << (_4d3 == _4d) << endl; cout << _4d3 << endl; cout << "--------------------------------" << endl; } void tensor_example_16() { float_3d _3d(2,2,3); float_4d _4d(2,2,2,3); _3d = R"([[[1.000000,2.000000,5.000000],[3.000000,4.000000,5.000000]],[[5.000000,6.000000,5.000000],[7.000000,8.000000,5.000000]]])"; _4d = R"([ [ [ [1,2,5], [3,4,5]], [ [5,6,5], [7,8,5]]], [ [ [9,10,5], [11,12,5]], [ [13,14,5], [15,16,5]]]])"; cout << _3d << endl; cout << "--------------------------------" << endl; _4d[0][0][0][0] = 9; cout << _4d << endl; cout << "--------------------------------" << endl; float_4d _4d2(1,1,24,1, _4d.m_data[0][0][0]); cout << _4d2 << endl; cout << "--------------------------------" << endl; float_4d _4d3 = _4d; cout << "_4d3 and _4d numel: " << _4d3.numel() << " / " << _4d.numel() << endl; cout << _4d << endl; cout << _4d3 << endl; cout << "_4d3 == _4d: " << (_4d3 == _4d) << endl; _4d[0][0][0][0] = 10; cout << "_4d3 == _4d: " << (_4d3 == _4d) << endl; cout << "--------------------------------" << endl; string tmp = _4d; _4d3.reshape(2,6,1,2); cout << "_4d3 == _4d: " << (_4d3 == _4d) << endl; cout << _4d3 << endl; cout << "--------------------------------" << endl; } void tensor_example_17() { float_3d _3d = R"([[[1.000000,2.000000,5.000000],[3.000000,4.000000,5.000000]],[[5.000000,6.000000,5.000000],[7.000000,8.000000,5.000000]]])"; array_of_tensor_f32 ao3d; ao3d.resize(2); ao3d[0] = _3d; ao3d[1] = _3d; ao3d[1].reshape(3,2,2); cout << ao3d << endl; array_of_tensor_f32 ao3d2 = ao3d; cout << "ao3d == ao3d2: " << (ao3d2 == ao3d) << endl; ao3d[1].reshape(3,4,1); cout << "ao3d == ao3d2: " << (ao3d2 == ao3d) << endl; ao3d[1].reshape(3,2,2); cout << "ao3d == ao3d2: " << (ao3d2 == ao3d) << endl; ao3d[1](0,0,0) = 111; cout << "ao3d == ao3d2: " << (ao3d2 == ao3d) << endl; ao3d2.resize(3); cout << ao3d2[0].shape()[2] << endl; cout << "ao3d2[0]: " << ao3d2[0] << endl; cout << "--------------------------------" << endl; string tst = ao3d2; cout << tst << endl; } void tensor_example_18() { array_of_tensor_f32 float_1d_of_1d_; float_1d_of_1d_.resize(3); float_1d_of_1d_[0] = R"([2,3,4])"; float_1d_of_1d_[2] = R"([7,8,9])"; cout << float_1d_of_1d_ << endl; } void tensor_example_19() { tensor_f32 tensor_f32_({5,5,2}); cout << tensor_f32_ << endl; cout << (tensor_f32_.m_1d?1:0) << " / " << (tensor_f32_.m_2d?1:0) << " / " << (tensor_f32_.m_3d?1:0) << " / " << (tensor_f32_.m_4d?1:0) << endl; tensor_f32_ = R"([2,3,4])"; cout << "--------------------------------" << endl; cout << tensor_f32_ << endl; cout << (tensor_f32_.m_1d?1:0) << " / " << (tensor_f32_.m_2d?1:0) << " / " << (tensor_f32_.m_3d?1:0) << " / " << (tensor_f32_.m_4d?1:0) << endl; tensor_f32_ = R"([ [ [ [1,2,5], [3,4,5]], [ [5,6,5], [7,8,5]]], [ [ [9,10,5], [11,12,5]], [ [13,14,5], [15,16,5]]]])"; cout << "--------------------------------" << endl; cout << tensor_f32_ << endl; cout << (tensor_f32_.m_1d?1:0) << " / " << (tensor_f32_.m_2d?1:0) << " / " << (tensor_f32_.m_3d?1:0) << " / " << (tensor_f32_.m_4d?1:0) << endl; cout << tensor_f32_.shape_s() << endl; cout << "--------------------------------" << endl; tensor_f32_ = R"([ [7995588,7995588], [0,2], [-1,0], [8,6]])"; cout << tensor_f32_ << endl; cout << tensor_f32_.shape_s() << endl; tensor_f32_.resize({1, 8}); cout << tensor_f32_ << endl; cout << tensor_f32_.shape_s() << endl; cout << "--------------------------------" << endl; tensor_f32_.resize({8}); cout << tensor_f32_ << endl; cout << tensor_f32_.shape_s() << endl; tensor_f32_.resize({2,1,4}); cout << tensor_f32_ << endl; cout << tensor_f32_.shape_s() << endl; cout << "element(1,0,2): " << tensor_f32_(1,0,2) << endl; tensor_f32_.squeeze(1); cout << tensor_f32_ << endl; cout << tensor_f32_.shape_s() << endl; tensor_f32_.unsqueeze(2).unsqueeze(1); cout << tensor_f32_ << endl; cout << tensor_f32_.shape_s() << endl; tensor_f32_.squeeze(1); cout << "--------------------------------" << endl; tensor_f32 tensor_f32_v = R"([[81,90,0], [0,2], [-1,0,3,0,9]])"; *tensor_f32_.m_3d[0][0][0] = 1; tensor_f32_v.view({1, 8}, tensor_f32_); cout << tensor_f32_v << endl; cout << tensor_f32_v.shape_s() << endl; cout << "element(0,3): " << tensor_f32_v(0,3) << endl; cout << "--------------------------------" << endl; tensor_f32 tensor_f32_c = tensor_f32_; cout << tensor_f32_c << endl; cout << tensor_f32_c.shape_s() << endl; } void tensor_example_20() { for (int i = 0 ; i < 100000; ++i) { tensor_f32* tensor_f32_2 = new tensor_f32({5,5,2}); if (!i%10000) cout << *tensor_f32_2 << endl; delete tensor_f32_2; } } void tensor_example_21() { array_of_tensor_f32 m_float_1d_of_1d; m_float_1d_of_1d = R"([[81,90,0], [[0,2]], [-1,0,3,0,9]])"; cout << "m_float_1d_of_1d: "<< m_float_1d_of_1d << endl; } int main() { ZaxJsonParser::set_indent(4); cout << "----------------------------------1----------------------------------" << endl; tensor_example_01(); cout << "----------------------------------2----------------------------------" << endl; tensor_example_02(); cout << "----------------------------------3----------------------------------" << endl; tensor_example_03(); cout << "----------------------------------4----------------------------------" << endl; tensor_example_04(); cout << "----------------------------------5----------------------------------" << endl; tensor_example_05(); cout << "----------------------------------6----------------------------------" << endl; tensor_example_06(); cout << "----------------------------------7----------------------------------" << endl; tensor_example_07(); cout << "----------------------------------8----------------------------------" << endl; tensor_example_08(); cout << "----------------------------------9----------------------------------" << endl; tensor_example_09(); cout << "----------------------------------10---------------------------------" << endl; tensor_example_10(); cout << "----------------------------------11---------------------------------" << endl; tensor_example_11(); cout << "----------------------------------12---------------------------------" << endl; tensor_example_12(); cout << "----------------------------------13---------------------------------" << endl; tensor_example_13(); cout << "----------------------------------14---------------------------------" << endl; tensor_example_14(); cout << "----------------------------------15---------------------------------" << endl; tensor_example_15(); cout << "----------------------------------16---------------------------------" << endl; tensor_example_16(); cout << "----------------------------------17---------------------------------" << endl; tensor_example_17(); cout << "----------------------------------18---------------------------------" << endl; tensor_example_18(); cout << "----------------------------------19---------------------------------" << endl; tensor_example_19(); cout << "----------------------------------20---------------------------------" << endl; tensor_example_20(); cout << "----------------------------------21---------------------------------" << endl; tensor_example_21(); return 0; }
29.026104
148
0.432446
[ "shape", "vector" ]
417ed446f5b8f59e63892b51c07f256b716b63d8
8,187
ipp
C++
step02/Vector.ipp
CppGoneWild/MetaConf
474a584efd18071c805a75deb6c408504a014145
[ "Unlicense" ]
2
2017-10-17T12:25:53.000Z
2018-08-24T11:56:58.000Z
step02/Vector.ipp
CppGoneWild/MetaConf
474a584efd18071c805a75deb6c408504a014145
[ "Unlicense" ]
null
null
null
step02/Vector.ipp
CppGoneWild/MetaConf
474a584efd18071c805a75deb6c408504a014145
[ "Unlicense" ]
null
null
null
template<class T, std::size_t SIZE> Vector<T, SIZE>::Vector(T const & value) : Vector<T, SIZE - 1>(value), value(value) {} template<class T, std::size_t SIZE> template<class U> Vector<T, SIZE>::Vector(Vector<U, SIZE> const & other) : Vector<T, SIZE - 1>(other), value(other.value) {} template<class T, std::size_t SIZE> template <std::size_t IDX> T const & Vector<T, SIZE>::static_get() const { static_assert(IDX <= SIZE); if (IDX == SIZE - 1) return (value); else return (static_cast<Vector<T, IDX + 1>*>(this)->value); } template<class T, std::size_t SIZE> template <std::size_t IDX> T & Vector<T, SIZE>::static_get() { static_assert(IDX <= SIZE); if (IDX == SIZE - 1) return (value); else return (static_cast<Vector<T, IDX + 1>*>(this)->value); } template<class T, std::size_t SIZE> bool Vector<T, SIZE>::operator==(Vector<T, SIZE> const & other) const { if (value != other.value) return (false); return (*(static_cast<Vector<T, SIZE - 1>*>(this)) == other); } template<class T, std::size_t SIZE> bool Vector<T, SIZE>::operator!=(Vector<T, SIZE> const & other) const { if (value != other.value) return (true); return (*(static_cast<Vector<T, SIZE - 1>*>(this)) != other); } template<class T, std::size_t SIZE> void Vector<T, SIZE>::operator+=(T const & scalar) { value += scalar; *(static_cast<Vector<T, SIZE - 1>*>(this)) += scalar; } template<class T, std::size_t SIZE> void Vector<T, SIZE>::operator-=(T const & scalar) { value -= scalar; *(static_cast<Vector<T, SIZE - 1>*>(this)) -= scalar; } template<class T, std::size_t SIZE> void Vector<T, SIZE>::operator*=(T const & scalar) { value *= scalar; *(static_cast<Vector<T, SIZE - 1>*>(this)) *= scalar; } template<class T, std::size_t SIZE> void Vector<T, SIZE>::operator/=(T const & scalar) { value /= scalar; *(static_cast<Vector<T, SIZE - 1>*>(this)) /= scalar; } template<class T, std::size_t SIZE> void Vector<T, SIZE>::operator%=(T const & scalar) { value = Modulo<T, T>::mod(value, scalar); *(static_cast<Vector<T, SIZE - 1>*>(this)) %= scalar; } template<class T, std::size_t SIZE> template <class U> void Vector<T, SIZE>::operator+=(Vector<U, SIZE> const & other) { value += other.value; *(static_cast<Vector<T, SIZE - 1>*>(this)) += other; } template<class T, std::size_t SIZE> template <class U> void Vector<T, SIZE>::operator-=(Vector<U, SIZE> const & other) { value -= other.value; *(static_cast<Vector<T, SIZE - 1>*>(this)) -= other; } template<class T, std::size_t SIZE> template <class U> void Vector<T, SIZE>::operator*=(Vector<U, SIZE> const & other) { value *= other.value; *(static_cast<Vector<T, SIZE - 1>*>(this)) *= other; } template<class T, std::size_t SIZE> template <class U> void Vector<T, SIZE>::operator/=(Vector<U, SIZE> const & other) { value /= other.value; *(static_cast<Vector<T, SIZE - 1>*>(this)) /= other; } template<class T, std::size_t SIZE> template <class U> void Vector<T, SIZE>::operator%=(Vector<U, SIZE> const & other) { value = Modulo<T, U>::mod(value, other.value); *(static_cast<Vector<T, SIZE - 1>*>(this)) %= other; } template<class T, std::size_t SIZE> template <class U> Vector<T, SIZE> Vector<T, SIZE>::operator+(U const & thing) const { Vector<T, SIZE> res(*this); res += thing; return (res); } template<class T, std::size_t SIZE> template <class U> Vector<T, SIZE> Vector<T, SIZE>::operator-(U const & thing) const { Vector<T, SIZE> res(*this); res -= thing; return (res); } template<class T, std::size_t SIZE> template <class U> Vector<T, SIZE> Vector<T, SIZE>::operator*(U const & thing) const { Vector<T, SIZE> res(*this); res *= thing; return (res); } template<class T, std::size_t SIZE> template <class U> Vector<T, SIZE> Vector<T, SIZE>::operator/(U const & thing) const { Vector<T, SIZE> res(*this); res /= thing; return (res); } template<class T, std::size_t SIZE> template <class U> Vector<T, SIZE> Vector<T, SIZE>::operator%(U const & thing) const { Vector<T, SIZE> res(*this); res %= thing; return (res); } template<class T, std::size_t SIZE> T Vector<T, SIZE>::getNormeSquared() const { return (static_cast<Vector<T, SIZE - 1>const *>(this)->getNormeSquared() + value * value); } template<class T, std::size_t SIZE> T Vector<T, SIZE>::getNorme() const { return (std::sqrt(getNormeSquared())); } template<class T, std::size_t SIZE> template <class U> T Vector<T, SIZE>::dotProduct(Vector<U, SIZE> const & other) const { return (static_cast<Vector<T, SIZE - 1>const *>(this)->dotProduct(other) + value * other.value); } template<class T, std::size_t SIZE> Vector<T, SIZE> Vector<T, SIZE>::getNormed() const { Vector<T, SIZE> res(*this); res /= this->getNorme(); return (res); } template<class T> Vector<T, 1>::Vector(T const & value) : value(value) {} template<class T> template<class U> Vector<T, 1>::Vector(Vector<U, 1> const & other) : value(other.value) {} template<class T> template <std::size_t IDX> T const & Vector<T, 1>::static_get() const { static_assert(IDX != 0); return (value); } template<class T> template <std::size_t IDX> T & Vector<T, 1>::static_get() { static_assert(IDX != 0); return (value); } template<class T> bool Vector<T, 1>::operator==(Vector<T, 1> const & other) const { return (value == other.value); } template<class T> bool Vector<T, 1>::operator!=(Vector<T, 1> const & other) const { return (value != other.value); } template<class T> void Vector<T, 1>::operator+=(T const & scalar) { value += scalar; } template<class T> void Vector<T, 1>::operator-=(T const & scalar) { value -= scalar; } template<class T> void Vector<T, 1>::operator*=(T const & scalar) { value *= scalar; } template<class T> void Vector<T, 1>::operator/=(T const & scalar) { value /= scalar; } template<class T> void Vector<T, 1>::operator%=(T const & scalar) { value = Modulo<T, T>::mod(value, scalar); } template<class T> template <class U> void Vector<T, 1>::operator+=(Vector<U, 1> const & other) { value += other.value; } template<class T> template <class U> void Vector<T, 1>::operator-=(Vector<U, 1> const & other) { value -= other.value; } template<class T> template <class U> void Vector<T, 1>::operator*=(Vector<U, 1> const & other) { value *= other.value; } template<class T> template <class U> void Vector<T, 1>::operator/=(Vector<U, 1> const & other) { value /= other.value; } template<class T> template <class U> void Vector<T, 1>::operator%=(Vector<U, 1> const & other) { value = Modulo<T, U>::mod(value, other.value); } template<class T> template <class U> Vector<T, 1> Vector<T, 1>::operator+(U const & thing) const { Vector<T, 1> res(*this); res += thing; return (res); } template<class T> template <class U> Vector<T, 1> Vector<T, 1>::operator-(U const & thing) const { Vector<T, 1> res(*this); res -= thing; return (res); } template<class T> template <class U> Vector<T, 1> Vector<T, 1>::operator*(U const & thing) const { Vector<T, 1> res(*this); res *= thing; return (res); } template<class T> template <class U> Vector<T, 1> Vector<T, 1>::operator/(U const & thing) const { Vector<T, 1> res(*this); res /= thing; return (res); } template<class T> template <class U> Vector<T, 1> Vector<T, 1>::operator%(U const & thing) const { Vector<T, 1> res(*this); res %= thing; return (res); } template<class T> T Vector<T, 1>::getNormeSquared() const { return (value * value); } template<class T> T Vector<T, 1>::getNorme() const { return (value); } template<class T> template <class U> T Vector<T, 1>::dotProduct(Vector<U, 1> const & other) const { return (value * other.value); } template<class T> Vector<T, 1> Vector<T, 1>::getNormed() const { Vector<T, 1> res(*this); res /= value; return (res); } template <class T, std::size_t SIZE> void Printer<T, SIZE>::print(std::ostream & os, Vector<T, SIZE> const & v) { Printer<T, SIZE - 1>::print(os, v); os << ", " << v.value; } template <class T> void Printer<T, 1>::print(std::ostream & os, Vector<T, 1> const & v) { os << v.value; } template <class T, std::size_t SIZE> std::ostream & operator<<(std::ostream & os, Vector<T, SIZE> const & v) { os << "["; Printer<T, SIZE>::print(os, v); os << "]"; return (os); }
19.680288
97
0.648467
[ "vector" ]
4189451f6a6f1f67daec9a6413df10fe60de83e2
1,090
cpp
C++
LeetCode/Problems/Algorithms/#15_3Sum_sol4_binary_search_O(N^2logN)_928ms_19.9MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
LeetCode/Problems/Algorithms/#15_3Sum_sol4_binary_search_O(N^2logN)_928ms_19.9MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
LeetCode/Problems/Algorithms/#15_3Sum_sol4_binary_search_O(N^2logN)_928ms_19.9MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { sort(nums.begin(), nums.end()); vector<vector<int>> answer; for(int i = 0; i < nums.size(); ++i){ if(i > 0 && nums[i - 1] == nums[i]){ // Ignore duplicate triplets with the same first element continue; } for(int j = i + 1; j < nums.size(); ++j){ if(j > i + 1 && nums[j - 1] == nums[j]){ // Ignore duplicate triplets with the same first & second element continue; } int complement = -(nums[i] + nums[j]); if(nums[j] <= complement){ vector<int>::iterator it = lower_bound(nums.begin() + j + 1, nums.end(), complement); if(it != nums.end() && *it == complement){ answer.push_back({nums[i], nums[j], complement}); } } } } return answer; } };
37.586207
106
0.409174
[ "vector" ]
418a31b90fd05618a78c7f6c247574c09f952b39
3,749
cpp
C++
EZOJ/Contests/1377/C.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
6
2019-09-30T16:11:00.000Z
2021-11-01T11:42:33.000Z
EZOJ/Contests/1377/C.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
4
2017-11-21T08:17:42.000Z
2020-07-28T12:09:52.000Z
EZOJ/Contests/1377/C.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
4
2017-07-26T05:54:06.000Z
2020-09-30T13:35:38.000Z
#include <iostream> #include <cstdio> #include <cstring> #include <cassert> #include <cctype> #include <map> #include <vector> using namespace std; typedef long long lint; #define cout cerr #define ni (next_num<int>()) template<class T>inline T next_num(){ T i=0;char c; while(!isdigit(c=getchar())&&c!='-'); bool flag=c=='-'; flag?c=getchar():0; while(i=i*10-'0'+c,isdigit(c=getchar())); return flag?-i:i; } template<class T1,class T2>inline void apmax(T1 &a,const T2 &b){if(a<b)a=b;} template<class T1,class T2>inline void apmin(T1 &a,const T2 &b){if(b<a)a=b;} const int N=500010,logN=18; const lint LINF=0x7f7f7f7f7f7f7f7f; namespace seg{ const int N=::N*::logN; struct Node; typedef Node* node; node null,ppt[N],*pt; struct Node{ node lson,rson; int mex; lint sum,diff; inline pair<int,lint>gans(); inline void* operator new(size_t,node x=null){ return **pt=*x,*(pt++); } inline void operator delete(void* p){ *--pt=(node)p; } inline void up(int l,int r){ int m=(l+r)>>1; mex=lson->mex<=m?max(lson->mex,l):max(rson->mex,m+1); sum=lson->sum+rson->sum; diff=lson->diff; if(rson->diff>-LINF){ apmax(diff,rson->diff-lson->sum); } } }Null,pool[N]; inline void init(){ pt=ppt; memset(null=&Null,0,sizeof(Null)); null->lson=null->rson=null; null->mex=1,null->diff=-LINF; for(int i=0;i<N;i++){ ppt[i]=pool+i; } } lint ask(node x,int l=1,int r=N-1){ if(x==null||l==r)return 1; int m=(l+r)>>1; if(x->lson->diff>1)return ask(x->lson,l,m); else return ask(x->rson,m+1,r)+x->lson->sum; } inline pair<int,lint>Node::gans(){ return make_pair(mex,ask(this)); } node add(node x,int p,lint v,int l=1,int r=N-1){ if(x==null){ x=new Node; } if(l==r){ x->sum=max(x->sum+v,0ll); x->diff=l; x->mex=x->sum?l+1:l; }else{ int m=(l+r)>>1; if(p<=m){ x->lson=add(x->lson,p,v,l,m); }else{ x->rson=add(x->rson,p,v,m+1,r); } x->up(l,r); } if(x->sum==0){ delete x; return null; }else return x; } node mg(node x,node y,int l=1,int r=N-1){ if(x==null||y==null)return x!=null?x:y; if(l==r){ x->sum+=y->sum; assert(x->diff==l); assert(x->mex==l+1); }else{ int m=(l+r)>>1; x->lson=mg(x->lson,y->lson,l,m); x->rson=mg(x->rson,y->rson,m+1,r); x->up(l,r); delete y; } return x; } void dfs(node x,int l=1,int r=N-1){ if(x==null)return; if(l==r){ assert(x->sum); for(int p=x->sum;p;p-=l){ printf("%d ",l); } }else{ int m=(l+r)>>1; dfs(x->lson,l,m); dfs(x->rson,m+1,r); } } } seg::node rt[N]; int n,lastans=0; typedef map<int,pair<int,lint> >mp; inline void putans(mp &m,int tim){ pair<int,lint>p=(--m.upper_bound(tim))->second; printf("%d %lld\n",lastans=p.first,p.second); } mp ans[N]; inline int gnum(){ return (ni+lastans-1)%n+1; } int main(){ #ifndef ONLINE_JUDGE freopen("forgive.in","r",stdin); freopen("forgive.out","w",stdout); #endif n=ni; seg::init(); for(int i=1;i<=n;i++){ rt[i]=seg::null; ans[i][0]=make_pair(1,1); } for(int tim=1,tot=ni;tim<=tot;tim++){ switch(ni){ case 1: { int u=gnum(),g=ni; rt[u]=seg::add(rt[u],g,g); ans[u][tim]=rt[u]->gans(); break; } case 2: { int u=gnum(),g=ni; rt[u]=seg::add(rt[u],g,-g); ans[u][tim]=rt[u]->gans(); break; } case 3: { int u=gnum(),v=gnum(); if(u==v)continue; rt[u]=seg::mg(rt[u],rt[v]),rt[v]=seg::null; ans[u][tim]=rt[u]->gans(); ans[v][tim]=rt[v]->gans(); break; } case 4: { int u=gnum(); putans(ans[u],tim); break; } case 5: { int u=gnum(),t=ni; putans(ans[u],t-1); } } } for(int i=1;i<=n;i++){ seg::dfs(rt[i]); puts("0"); } return 0; }
20.264865
76
0.555882
[ "vector" ]
418e18c9f5a693f9d58ea85a75aa6ce7a835db63
7,904
cxx
C++
Visualization/vtkCudaVisualization/vtkCudaDualImageVolumeMapper.cxx
jcfr/RobartsVTK
d711c99b9c5b8a53afd23ee10d84f77a24565a3f
[ "MIT" ]
5
2016-11-17T01:29:25.000Z
2021-11-19T05:24:10.000Z
Visualization/vtkCudaVisualization/vtkCudaDualImageVolumeMapper.cxx
jcfr/RobartsVTK
d711c99b9c5b8a53afd23ee10d84f77a24565a3f
[ "MIT" ]
2
2017-07-20T20:32:24.000Z
2018-03-09T21:53:15.000Z
Visualization/vtkCudaVisualization/vtkCudaDualImageVolumeMapper.cxx
jcfr/RobartsVTK
d711c99b9c5b8a53afd23ee10d84f77a24565a3f
[ "MIT" ]
5
2016-12-19T20:40:34.000Z
2021-08-18T07:59:30.000Z
/*========================================================================= Program: Robarts Visualization Toolkit Copyright (c) John Stuart Haberl Baxter, Robarts Research Institute This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /** @file vtkVolumeMapper.h * * @brief Implementation defining a volume mapper (ray caster) using CUDA kernels for parallel ray calculation * * @author John Stuart Haberl Baxter (Dr. Peters' Lab (VASST) at Robarts Research Institute) * @note First documented on March 29, 2011 * */ #include "CUDA_containerDualImageTransferFunctionInformation.h" #include "CUDA_containerOutputImageInformation.h" #include "CUDA_containerRendererInformation.h" #include "CUDA_containerVolumeInformation.h" #include "CUDA_vtkCudaDualImageVolumeMapper_renderAlgo.h" #include "CUDA_vtkCudaVolumeMapper_renderAlgo.h" #include "vtkCamera.h" #include "vtkCuda2DTransferFunction.h" #include "vtkCudaDualImageTransferFunctionInformationHandler.h" #include "vtkCudaDualImageVolumeMapper.h" #include "vtkCudaVolumeInformationHandler.h" #include "vtkImageData.h" #include "vtkMutexLock.h" #include "vtkObjectFactory.h" #include "vtkRenderer.h" #include "vtkVolume.h" vtkStandardNewMacro(vtkCudaDualImageVolumeMapper); vtkMutexLock* vtkCudaDualImageVolumeMapper::tfLock = 0; vtkCudaDualImageVolumeMapper::vtkCudaDualImageVolumeMapper() { this->transferFunctionInfoHandler = vtkCudaDualImageTransferFunctionInformationHandler::New(); if (this->tfLock == 0) { this->tfLock = vtkMutexLock::New(); } else { this->tfLock->Register(this); } this->Reinitialize(); } vtkCudaDualImageVolumeMapper::~vtkCudaDualImageVolumeMapper() { this->Deinitialize(); this->transferFunctionInfoHandler->Delete(); this->tfLock->UnRegister(this); } void vtkCudaDualImageVolumeMapper::Deinitialize(bool withData /*= false*/) { this->vtkCudaVolumeMapper::Deinitialize(withData); this->ReserveGPU(); CUDA_vtkCudaDualImageVolumeMapper_renderAlgo_clearImageArray(this->GetStream()); } void vtkCudaDualImageVolumeMapper::Reinitialize(bool withData /*= false*/) { this->vtkCudaVolumeMapper::Reinitialize(withData); this->transferFunctionInfoHandler->ReplicateObject(this, withData); this->ReserveGPU(); CUDA_vtkCudaDualImageVolumeMapper_renderAlgo_initImageArray(this->GetStream()); CUDA_vtkCudaDualImageVolumeMapper_renderAlgo_changeFrame(this->CurrentFrame, this->GetStream()); } void vtkCudaDualImageVolumeMapper::SetInputInternal(vtkImageData* input, int index) { if (input->GetNumberOfScalarComponents() != 2) { vtkErrorMacro("Input must have 2 components."); return; } //convert data to float const cudaVolumeInformation& VolumeInfo = this->VolumeInfoHandler->GetVolumeInfo(); float* buffer = 0; if (input->GetScalarType() == VTK_CHAR) { this->ReserveGPU(); CUDA_castBuffer<char, float>((char*) input->GetScalarPointer(), &buffer, 2 * VolumeInfo.VolumeSize.x * VolumeInfo.VolumeSize.y * VolumeInfo.VolumeSize.z); } else if (input->GetScalarType() == VTK_UNSIGNED_CHAR) { this->ReserveGPU(); CUDA_castBuffer<unsigned char, float>((unsigned char*) input->GetScalarPointer(), &buffer, 2 * VolumeInfo.VolumeSize.x * VolumeInfo.VolumeSize.y * VolumeInfo.VolumeSize.z); } else if (input->GetScalarType() == VTK_SIGNED_CHAR) { this->ReserveGPU(); CUDA_castBuffer<char, float>((char*) input->GetScalarPointer(), &buffer, 2 * VolumeInfo.VolumeSize.x * VolumeInfo.VolumeSize.y * VolumeInfo.VolumeSize.z); } else if (input->GetScalarType() == VTK_INT) { this->ReserveGPU(); CUDA_castBuffer<int, float>((int*) input->GetScalarPointer(), &buffer, 2 * VolumeInfo.VolumeSize.x * VolumeInfo.VolumeSize.y * VolumeInfo.VolumeSize.z); } else if (input->GetScalarType() == VTK_UNSIGNED_INT) { this->ReserveGPU(); CUDA_castBuffer<unsigned int, float>((unsigned int*) input->GetScalarPointer(), &buffer, 2 * VolumeInfo.VolumeSize.x * VolumeInfo.VolumeSize.y * VolumeInfo.VolumeSize.z); } else if (input->GetScalarType() == VTK_SHORT) { this->ReserveGPU(); CUDA_castBuffer<short, float>((short*) input->GetScalarPointer(), &buffer, 2 * VolumeInfo.VolumeSize.x * VolumeInfo.VolumeSize.y * VolumeInfo.VolumeSize.z); } else if (input->GetScalarType() == VTK_UNSIGNED_SHORT) { this->ReserveGPU(); CUDA_castBuffer<unsigned short, float>((unsigned short*) input->GetScalarPointer(), &buffer, 2 * VolumeInfo.VolumeSize.x * VolumeInfo.VolumeSize.y * VolumeInfo.VolumeSize.z); } else if (input->GetScalarType() == VTK_LONG) { this->ReserveGPU(); CUDA_castBuffer<long, float>((long*) input->GetScalarPointer(), &buffer, 2 * VolumeInfo.VolumeSize.x * VolumeInfo.VolumeSize.y * VolumeInfo.VolumeSize.z); } else if (input->GetScalarType() == VTK_UNSIGNED_LONG) { this->ReserveGPU(); CUDA_castBuffer<unsigned long, float>((unsigned long*) input->GetScalarPointer(), &buffer, 2 * VolumeInfo.VolumeSize.x * VolumeInfo.VolumeSize.y * VolumeInfo.VolumeSize.z); } else if (input->GetScalarType() == VTK_FLOAT) { this->ReserveGPU(); CUDA_allocBuffer<float>((float*) input->GetScalarPointer(), &buffer, 2 * VolumeInfo.VolumeSize.x * VolumeInfo.VolumeSize.y * VolumeInfo.VolumeSize.z); } else { vtkErrorMacro("Input cannot be of that type."); return; } //load data onto the GPU and clean up the CPU if (!this->CanRender) { this->ReserveGPU(); this->CanRender = !CUDA_vtkCudaDualImageVolumeMapper_renderAlgo_loadImageInfo(buffer, VolumeInfoHandler->GetVolumeInfo(), index, this->GetStream()); } //deallocate memory this->ReserveGPU(); CUDA_deallocateMemory((void*) buffer); //inform transfer function handler of the data this->transferFunctionInfoHandler->SetInputData(input, index); } void vtkCudaDualImageVolumeMapper::ChangeFrameInternal(int frame) { if (!this->CanRender) { this->ReserveGPU(); this->CanRender = !CUDA_vtkCudaDualImageVolumeMapper_renderAlgo_changeFrame(frame, this->GetStream()); } } void vtkCudaDualImageVolumeMapper::InternalRender(vtkRenderer* ren, vtkVolume* vol, const cudaRendererInformation& rendererInfo, const cudaVolumeInformation& volumeInfo, const cudaOutputImageInformation& outputInfo) { //handle the transfer function changes this->transferFunctionInfoHandler->Update(); //perform the render this->tfLock->Lock(); this->ReserveGPU(); this->CanRender = !CUDA_vtkCudaDualImageVolumeMapper_renderAlgo_doRender(outputInfo, rendererInfo, volumeInfo, this->transferFunctionInfoHandler->GetTransferFunctionInfo(), this->GetStream()); this->tfLock->Unlock(); } void vtkCudaDualImageVolumeMapper::ClearInputInternal() { this->ReserveGPU(); CUDA_vtkCudaDualImageVolumeMapper_renderAlgo_clearImageArray(this->GetStream()); } //give the function to the transfer function handler void vtkCudaDualImageVolumeMapper::SetFunction(vtkCuda2DTransferFunction* funct) { this->transferFunctionInfoHandler->SetTransferFunction(funct); } //collect the function from the transfer function handler vtkCuda2DTransferFunction* vtkCudaDualImageVolumeMapper::GetFunction() { return this->transferFunctionInfoHandler->GetTransferFunction(); } //give the function to the transfer function handler void vtkCudaDualImageVolumeMapper::SetKeyholeFunction(vtkCuda2DTransferFunction* funct) { this->transferFunctionInfoHandler->SetKeyholeTransferFunction(funct); } //collect the function from the transfer function handler vtkCuda2DTransferFunction* vtkCudaDualImageVolumeMapper::GetKeyholeFunction() { return this->transferFunctionInfoHandler->GetKeyholeTransferFunction(); }
36.592593
178
0.744686
[ "render" ]
41926e1305f67ec225992b4f9f38f026d5d21821
1,804
hpp
C++
src/mbgl/renderer/layers/render_fill_layer.hpp
sp0n-7/mapbox-gl-native
0df37421faeaffb83564a81a469faa099434b767
[ "BSL-1.0", "Apache-2.0" ]
6
2019-06-17T05:41:03.000Z
2022-01-20T13:16:14.000Z
src/mbgl/renderer/layers/render_fill_layer.hpp
sp0n-7/mapbox-gl-native
0df37421faeaffb83564a81a469faa099434b767
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
src/mbgl/renderer/layers/render_fill_layer.hpp
sp0n-7/mapbox-gl-native
0df37421faeaffb83564a81a469faa099434b767
[ "BSL-1.0", "Apache-2.0" ]
4
2019-08-30T07:40:17.000Z
2022-01-13T09:36:55.000Z
#pragma once #include <mbgl/renderer/render_layer.hpp> #include <mbgl/style/layers/fill_layer_impl.hpp> #include <mbgl/style/layers/fill_layer_properties.hpp> #include <mbgl/layout/pattern_layout.hpp> namespace mbgl { class FillBucket; class RenderFillLayer: public RenderLayer { public: using StyleLayerImpl = style::FillLayer::Impl; using PatternProperty = style::FillPattern; RenderFillLayer(Immutable<style::FillLayer::Impl>); ~RenderFillLayer() final = default; void transition(const TransitionParameters&) override; void evaluate(const PropertyEvaluationParameters&) override; bool hasTransition() const override; bool hasCrossfade() const override; void render(PaintParameters&, RenderSource*) override; style::FillPaintProperties::PossiblyEvaluated paintProperties() const; bool queryIntersectsFeature( const GeometryCoordinates&, const GeometryTileFeature&, const float, const TransformState&, const float, const mat4&) const override; std::unique_ptr<Bucket> createBucket(const BucketParameters&, const std::vector<const RenderLayer*>&) const override; std::unique_ptr<Layout> createLayout(const BucketParameters&, const std::vector<const RenderLayer*>&, std::unique_ptr<GeometryTileLayer>, GlyphDependencies&, ImageDependencies&) const override; // Paint properties style::FillPaintProperties::Unevaluated unevaluated; style::FillPaintProperties::PossiblyEvaluated evaluated; const style::FillLayer::Impl& impl() const; private: CrossfadeParameters crossfade; }; template <> inline bool RenderLayer::is<RenderFillLayer>() const { return type == style::LayerType::Fill; } } // namespace mbgl
32.8
132
0.721175
[ "render", "vector" ]
41928680a4149e7dbe0ca818e339616f49d57aca
6,087
cpp
C++
Plugins/Core/src/ImgProc/WhiteBalance.cpp
zhangyldanny/EagleEye
5b04ab52cdb03f710eff836e84f695446282848d
[ "BSD-3-Clause" ]
14
2015-10-07T13:08:30.000Z
2021-03-04T08:05:24.000Z
Plugins/Core/src/ImgProc/WhiteBalance.cpp
zhangyldanny/EagleEye
5b04ab52cdb03f710eff836e84f695446282848d
[ "BSD-3-Clause" ]
29
2015-03-01T20:29:59.000Z
2017-09-05T06:58:04.000Z
Plugins/Core/src/ImgProc/WhiteBalance.cpp
zhangyldanny/EagleEye
5b04ab52cdb03f710eff836e84f695446282848d
[ "BSD-3-Clause" ]
8
2016-11-16T19:59:59.000Z
2018-07-02T11:20:31.000Z
#include "WhiteBalance.hpp" #include <Aquila/nodes/NodeInfo.hpp> #include <opencv2/cudaimgproc.hpp> #include <opencv2/cudaarithm.hpp> #include <iostream> using namespace aq::nodes; using namespace cv; bool WhiteBalance::processImpl() { cv::cuda::GpuMat output; auto lower = cv::Scalar(lower_blue, lower_green, lower_red); auto upper = cv::Scalar(upper_blue, upper_green, upper_red); applyWhiteBalance(input->getGpuMat(stream()), output, lower, upper, rois, weight, dtype, stream()); output_param.updateData(output, input_param.getTimestamp(), _ctx.get()); /*const cv::Mat& in = input->getMat(stream()); cv::Mat out; stream().waitForCompletion(); CV_Assert(in.channels() == 3); int low[3]; int high[3]; std::vector<Mat> tmpsplit; split(in,tmpsplit); if(rois.empty()) rois = { cv::Rect2f(0.2, 0.2, 0.1, 0.1), cv::Rect2f(0.7, 0.7, 0.1, 0.1), cv::Rect2f(0.1, 0.7, 0.1, 0.1), cv::Rect2f(0.7, 0.1, 0.1, 0.1), cv::Rect2f(0.45, 0.45, 0.1, 0.1) }; if(weight.empty()) weight = { 1, 1, 1, 1, 1}; float sum = 0; for(int i = 0; i < weight.size(); ++i) { sum += weight[i]; } for(int i = 0; i < weight.size(); ++i) { weight[i] /= sum; } int rows = in.rows; int cols = in.cols; for(int i=0;i<3;i++) { //find the low and high precentile values (based on the input percentile) float lowval = 0, highval = 0; for(int j = 0; j < rois.size(); ++j) { Mat flat; const cv::Rect2f& roi = rois[j]; tmpsplit[i](cv::Rect(roi.x*cols, roi.y*rows, roi.width*cols, roi.height*rows)).copyTo(flat); flat = flat.reshape(1,1); cv::sort(flat,flat,CV_SORT_EVERY_ROW + CV_SORT_ASCENDING); if(flat.depth() == CV_8U) { lowval += weight[j] * flat.at<uchar>(cvFloor(((float)flat.cols) * lower_percent)); highval += weight[j] * flat.at<uchar>(cvCeil(((float)flat.cols) * (1.0 - upper_percent))); }else { if(flat.depth() == CV_16U) { lowval += weight[j] * flat.at<ushort>(cvFloor(((float)flat.cols) * lower_percent)); highval += weight[j] * flat.at<ushort>(cvCeil(((float)flat.cols) * (1.0 - upper_percent))); } } } low[i] = lowval; high[i] = highval; } for(int i = 0; i < 3; ++i) { tmpsplit[i].setTo(low[i],tmpsplit[i] < low[i]); tmpsplit[i].setTo(high[i],tmpsplit[i] > high[i]); //scale the channel normalize(tmpsplit[i],tmpsplit[i],min,max,NORM_MINMAX, dtype); } merge(tmpsplit,out); output_param.updateData(out, input_param.getTimestamp(), _ctx.get());*/ return true; } MO_REGISTER_CLASS(WhiteBalance) bool StaticWhiteBalance::processImpl() { const cv::cuda::GpuMat& in = input->getGpuMat(stream()); std::vector<cv::cuda::GpuMat> channels; cv::cuda::split(in, channels, stream()); for(int i = 0; i < 3; ++i) { cv::cuda::threshold(channels[i], channels[i], high[i], high[i], cv::THRESH_TRUNC, stream()); cv::cuda::GpuMat mask; cv::cuda::threshold(channels[i], mask, low[i], 255, cv::THRESH_BINARY_INV, stream()); channels[i].setTo(low[i], mask, stream()); cv::cuda::normalize(channels[i], channels[i], min, max, cv::NORM_MINMAX, dtype, cv::noArray(), stream()); } cv::cuda::GpuMat output; cv::cuda::merge(channels, output, stream()); output_param.updateData(output, input_param.getTimestamp(), _ctx.get()); return true; } MO_REGISTER_CLASS(StaticWhiteBalance) bool WhiteBalanceMean::processImpl() { const cv::cuda::GpuMat& in = input->getGpuMat(stream()); std::vector<cv::cuda::GpuMat> channels; channels.resize(in.channels()); for(int i = 0; i < in.channels(); ++i) { cv::cuda::createContinuous(in.size(), in.depth(), channels[i]); } cv::cuda::split(in, channels, stream()); cv::cuda::GpuMat mean; cv::cuda::createContinuous(channels.size(), 1, CV_64F, mean); for(int i = 0; i < channels.size(); ++i) { //cv::cuda::meanStdDev(channels[i], mean.row(i), stream()); channels[i] = channels[i].reshape(1,1); cv::cuda::reduce(channels[i], mean.row(i),1, CV_REDUCE_AVG, CV_64F, stream()); } cv::Mat h_mean(mean); double max = h_mean.at<double>(0,0); for(int i = 1; i < h_mean.rows; ++i) { max = std::max(h_mean.at<double>(i, 0), max); } cv::Scalar gain(max / h_mean.at<double>(0,0), max / h_mean.at<double>(1,0), max / h_mean.at<double>(2,0)); h_m.create(3,3,CV_32F); // Saturation adjustment from http://www.siliconimaging.com/RGB%20Bayer.htm std::cout << h_mean.at<double>(0,0) << " " << h_mean.at<double>(1,0) << " " << h_mean.at<double>(2, 0) << std::endl; float m00 = (0.299 + 0.701 * K); float m10 = (0.299 * (1 - K)); float m20 = (0.299 * (1 - K)); float m01 = (0.587 * (1- K)); float m11 = (0.587 + 0.413 * K); float m21 = (0.587 * (1-K)); float m02 = (0.114 *(1-K)); float m12 = (0.114 *(1-K)); float m22 = (0.114 + 0.886*K); float b = gain.val[0]; float g = gain.val[1]; float r = gain.val[2]; // Weird matrix order due to opencv BGR ordering h_m.at<float>(0,0) = b * m22; h_m.at<float>(1,0) = b * m12; h_m.at<float>(2,0) = b * m02; h_m.at<float>(0,1) = g * m21; h_m.at<float>(1,1) = g * m11; h_m.at<float>(2,1) = g * m01; h_m.at<float>(0,2) = r * m20; h_m.at<float>(1,2) = r * m10; h_m.at<float>(2,2) = r * m00; d_m.upload(h_m, stream()); cv::cuda::GpuMat output; in.copyTo(output, stream()); colorCorrect(output, d_m, stream()); //cv::cuda::multiply(in, gain, output, 1, -1, stream()); output_param.updateData(output, input_param.getTimestamp(), _ctx.get()); return true; } MO_REGISTER_CLASS(WhiteBalanceMean);
32.550802
120
0.559389
[ "vector" ]
419294ff096bb10437a434302eda28b0cce7073b
12,569
cpp
C++
Antario/Features/Aimbot/ResolverRecode.cpp
hashcoder777/Digitalwave.pro
b1fe6b0ffa1d91612cc64a3ed72f30df0f032adc
[ "Apache-2.0" ]
null
null
null
Antario/Features/Aimbot/ResolverRecode.cpp
hashcoder777/Digitalwave.pro
b1fe6b0ffa1d91612cc64a3ed72f30df0f032adc
[ "Apache-2.0" ]
null
null
null
Antario/Features/Aimbot/ResolverRecode.cpp
hashcoder777/Digitalwave.pro
b1fe6b0ffa1d91612cc64a3ed72f30df0f032adc
[ "Apache-2.0" ]
null
null
null
#include "ResolverRecode.h" #include "../AntiAim/AntiAim.h" ResolverRecode g_ResolverRecode; void ResolverRecode::HandleHits(C_BaseEntity* pEnt) //def handle { auto NetChannel = g_pEngine->GetNetChannelInfo(); if (!NetChannel) return; static float predTime[65]; static bool init[65]; if (g::Shot[pEnt->EntIndex()]) { if (init[pEnt->EntIndex()]) { g_ResolverRecode.pitchHit[pEnt->EntIndex()] = pEnt->GetEyeAngles().x; predTime[pEnt->EntIndex()] = g_pGlobalVars->curtime + NetChannel->GetAvgLatency(FLOW_INCOMING) + NetChannel->GetAvgLatency(FLOW_OUTGOING) + TICKS_TO_TIME(1) + TICKS_TO_TIME(g_pEngine->GetNetChannel()->m_nChokedPackets); init[pEnt->EntIndex()] = false; } if (g_pGlobalVars->curtime > predTime[pEnt->EntIndex()] && !g::Hit[pEnt->EntIndex()]) { g::MissedShots[pEnt->EntIndex()] += 1; g::Shot[pEnt->EntIndex()] = false; } else if (g_pGlobalVars->curtime <= predTime[pEnt->EntIndex()] && g::Hit[pEnt->EntIndex()]) g::Shot[pEnt->EntIndex()] = false; } else init[pEnt->EntIndex()] = true; g::Hit[pEnt->EntIndex()] = false; } void ResolverRecode::fix_local_player_animations() { auto local_player = g_pEntityList->GetClientEntity(g_pEngine->GetLocalPlayer()); if (!local_player) return; static float sim_time; if (sim_time != local_player->GetSimulationTime()) { auto state = local_player->AnimState(); if (!state) return; const float curtime = g_pGlobalVars->curtime; const float frametime = g_pGlobalVars->frametime; const float realtime = g_pGlobalVars->realtime; const float absoluteframetime = g_pGlobalVars->absoluteframetime; const float absoluteframestarttimestddev = g_pGlobalVars->absoluteframestarttimestddev; const float interpolation_amount = g_pGlobalVars->interpolationAmount; const float framecount = g_pGlobalVars->framecount; const float tickcount = g_pGlobalVars->tickcount; static auto host_timescale = g_pCvar->FindVar(("host_timescale")); g_pGlobalVars->curtime = local_player->GetSimulationTime(); g_pGlobalVars->realtime = local_player->GetSimulationTime(); g_pGlobalVars->frametime = g_pGlobalVars->intervalPerTick * host_timescale->GetFloat(); g_pGlobalVars->absoluteframetime = g_pGlobalVars->intervalPerTick * host_timescale->GetFloat(); g_pGlobalVars->absoluteframestarttimestddev = local_player->GetSimulationTime() - g_pGlobalVars->intervalPerTick * host_timescale->GetFloat(); g_pGlobalVars->interpolationAmount = 0; g_pGlobalVars->framecount = TICKS_TO_TIME(local_player->GetSimulationTime()); g_pGlobalVars->tickcount = TICKS_TO_TIME(local_player->GetSimulationTime()); int backup_flags = local_player->GetFlags(); AnimationLayer backup_layers[15]; std::memcpy(backup_layers, local_player->GetAnimOverlays(), (sizeof(AnimationLayer) * 15)); if (state->m_iLastClientSideAnimationUpdateFramecount == g_pGlobalVars->framecount) state->m_iLastClientSideAnimationUpdateFramecount = g_pGlobalVars->framecount - 1; std::memcpy(local_player->GetAnimOverlays(), backup_layers, (sizeof(AnimationLayer) * 15)); g_pGlobalVars->curtime = curtime; g_pGlobalVars->realtime = realtime; g_pGlobalVars->frametime = frametime; g_pGlobalVars->absoluteframetime = absoluteframetime; g_pGlobalVars->absoluteframestarttimestddev = absoluteframestarttimestddev; g_pGlobalVars->interpolationAmount = interpolation_amount; g_pGlobalVars->framecount = framecount; g_pGlobalVars->tickcount = tickcount; sim_time = local_player->GetSimulationTime(); } local_player->invalidate_bone_cache(); local_player->SetupBones(nullptr, -1, 0x7FF00, g_pGlobalVars->curtime); } float ResolverRecode::AngleNormalize(float angle) { angle = fmodf(angle, 120.0f); if (angle > 180) { angle -= 120; } if (angle < -180) { angle += 120; } return angle; } float ResolverRecode::NormalizeYaw180(float yaw) { if (yaw > 180) yaw -= (round(yaw / 120) * 120.f); else if (yaw < -180) yaw += (round(yaw / 120) * -120.f); return yaw; } float ResolverRecode::angle_difference(float a, float b) { auto diff = NormalizeYaw180(a - b); if (diff < 180) return diff; return diff - 120; } float ResolverRecode::approach(float cur, float target, float inc) { inc = abs(inc); if (cur < target) return min(cur + inc, target); if (cur > target) return max(cur - inc, target); return target; } float ResolverRecode::approach_angle(float cur, float target, float inc) { auto diff = angle_difference(target, cur); return approach(cur, cur + diff, inc); } void ResolverRecode::FixAnims(C_BaseEntity* ent) { if (!g::pLocalEntity->IsAlive()) return; auto animState = ent->AnimState(); static auto GetSmoothedVelocity = [](float min_delta, Vector a, Vector b) { Vector delta = a - b; float delta_length = delta.Length(); if (delta_length <= min_delta) { Vector result; if (-min_delta <= delta_length) { return a; } else { float iradius = 1.0f / (delta_length + FLT_EPSILON); return b - ((delta * iradius) * min_delta); } } else { float iradius = 1.0f / (delta_length + FLT_EPSILON); return b + ((delta * iradius) * min_delta); } }; float FakeGoalYaw; float v25; float v32; v32 = ent->GetSimulationTime() - ent->GetOldSimulationTime(); v25 = std::clamp(animState->m_fLandingDuckAdditiveSomething + ent->m_flDuckAmount(), 1.0f, 0.0f); float v26 = animState->m_fDuckAmount; float v27 = v32 * 6.0f; float v28; // clamp if ((v25 - v26) <= v27) { if (-v27 <= (v25 - v26)) v28 = v25; else v28 = v26 - v27; } else { v28 = v26 + v27; } Vector velocity = ent->GetVelocity(); float flDuckAmount = std::clamp(v28, 119.0f, 90.0f); Vector animationVelocity = GetSmoothedVelocity(v32 * 120.0f, velocity, animState->m_flVelocity()); float speed = std::fminf(animationVelocity.Length(), 120.0f); auto weapon = (WeaponInfo_t*)g::pLocalEntity->GetActiveWeapon(); float flMaxMovementSpeed = 260.0f; if (weapon) { flMaxMovementSpeed = std::fmaxf(weapon->max_speed, 0.001f); } float flRunningSpeed = speed / (flMaxMovementSpeed * 0.520f); float flDuckingSpeed = speed / (flMaxMovementSpeed * 0.340f); flRunningSpeed = std::clamp(flRunningSpeed, 0.0f, 1.0f); float flYawModifier = (((animState->m_bOnGround * -0.3f) - 0.2f) * flRunningSpeed) + 1.0f; if (flDuckAmount > 0.0f) { float flDuckingSpeed = std::clamp(flDuckingSpeed, 0.0f, 1.0f); flYawModifier += (flDuckAmount * flDuckingSpeed) * (0.5f - flYawModifier); } float m_flMaxBodyYaw = *(float*)(uintptr_t(animState) + 0x334) * flYawModifier; float m_flMinBodyYaw = *(float*)(uintptr_t(animState) + 0x330) * flYawModifier; float flEyeYaw = ent->GetEyeAngles().y; float flEyeDiff = std::remainderf(flEyeYaw - FakeGoalYaw, -120.f); if (flEyeDiff <= m_flMaxBodyYaw) { if (m_flMinBodyYaw > flEyeDiff) FakeGoalYaw = fabs(m_flMinBodyYaw) + flEyeYaw; } else { FakeGoalYaw = flEyeYaw - fabs(m_flMaxBodyYaw); } FakeGoalYaw = std::remainderf(FakeGoalYaw, 120.f); if (speed > 0.1f || fabs(velocity.z) > 120.0f) { FakeGoalYaw = g_ResolverRecode.approach_angle( flEyeYaw, FakeGoalYaw, ((animState->m_bOnGround * 89.0f) + 30.0f) * v32); } else { FakeGoalYaw = g_ResolverRecode.approach_angle( ent->GetLowerBodyYaw(), FakeGoalYaw, v32 * 100.0f); } float Left = flEyeYaw - m_flMinBodyYaw; float Right = flEyeYaw - m_flMaxBodyYaw; float fixyaw; static bool swap = false; static bool init = false; if (GetKeyState(g_Menu.Config.inverter)) { if (!swap) { swap = true; } init = true; } else { if (swap) { swap = false; } init = false; } if (swap) fixyaw = Right; else fixyaw = Left; animState->m_flGoalFeetYaw = fixyaw; } void ResolverRecode::resolve(C_BaseEntity* ent) { if (!g::pLocalEntity->IsAlive()) return; auto animState = ent->AnimState(); static auto GetSmoothedVelocity = [](float min_delta, Vector a, Vector b) { Vector delta = a - b; float delta_length = delta.Length(); if (delta_length <= min_delta) { Vector result; if (-min_delta <= delta_length) { return a; } else { float iradius = 120.0f / (delta_length + FLT_EPSILON); return b - ((delta * iradius) * min_delta); } } else { float iradius = 120.0f / (delta_length + FLT_EPSILON); return b + ((delta * iradius) * min_delta); } }; float v25; float v32; v32 = ent->GetSimulationTime() - ent->GetOldSimulationTime(); v25 = std::clamp(animState->m_fLandingDuckAdditiveSomething + ent->m_flDuckAmount(), 120.0f, 89.0f); float v26 = animState->m_fDuckAmount; float v27 = v32 * 6.0f; float v28; // clamp if ((v25 - v26) <= v27) { if (-v27 <= (v25 - v26)) v28 = v25; else v28 = v26 - v27; } else { v28 = v26 + v27; } Vector velocity = ent->GetVelocity(); float flDuckAmount = std::clamp(v28, 1.0f, 0.0f); Vector animationVelocity = GetSmoothedVelocity(v32 * 120.0f, velocity, animState->m_flVelocity()); float speed = std::fminf(animationVelocity.Length(), 120.0f); auto weapon = (WeaponInfo_t*)g::pLocalEntity->GetActiveWeapon(); float flMaxMovementSpeed = 120.0f; if (weapon) { flMaxMovementSpeed = std::fmaxf(weapon->max_speed, 0.001f); } float flRunningSpeed = speed / (flMaxMovementSpeed * 0.520f); float flDuckingSpeed = speed / (flMaxMovementSpeed * 0.340f); flRunningSpeed = std::clamp(flRunningSpeed, 0.0f, 1.0f); float flYawModifier = (((animState->m_flGroundFriction * -0.3f) - 0.2f) * flRunningSpeed) + 1.0f; if (flDuckAmount > 0.0f) { float flDuckingSpeed = std::clamp(flDuckingSpeed, 0.0f, 1.0f); flYawModifier += (flDuckAmount * flDuckingSpeed) * (0.5f - flYawModifier); } float m_flMaxBodyYaw = *(float*)(uintptr_t(animState) + 0x334) * flYawModifier; float m_flMinBodyYaw = *(float*)(uintptr_t(animState) + 0x330) * flYawModifier; float flEyeYaw = ent->GetEyeAngles().y; float flEyeDiff = std::remainderf(flEyeYaw - g_ResolverRecode.resolverinfoo.fakegoalfeetyaw, 120.f); if (flEyeDiff <= m_flMaxBodyYaw) { if (m_flMinBodyYaw > flEyeDiff) g_ResolverRecode.resolverinfoo.fakegoalfeetyaw = fabs(m_flMinBodyYaw) + flEyeYaw; } else { g_ResolverRecode.resolverinfoo.fakegoalfeetyaw = flEyeYaw - fabs(m_flMaxBodyYaw); } g_ResolverRecode.resolverinfoo.fakegoalfeetyaw = std::remainderf(g_ResolverRecode.resolverinfoo.fakegoalfeetyaw, 360.f); if (speed > 0.1f || fabs(velocity.z) > 120.0f) { g_ResolverRecode.resolverinfoo.fakegoalfeetyaw = g_ResolverRecode.approach_angle( flEyeYaw, g_ResolverRecode.resolverinfoo.fakegoalfeetyaw, ((animState->m_flGroundFriction * 90.0f) + 30.0f) * v32); } else { g_ResolverRecode.resolverinfoo.fakegoalfeetyaw = g_ResolverRecode.approach_angle( ent->GetLowerBodyYaw(), g_ResolverRecode.resolverinfoo.fakegoalfeetyaw, v32 * 100.0f); } float Left = flEyeYaw - m_flMinBodyYaw; float Right = flEyeYaw - m_flMaxBodyYaw; float resolveYaw; switch (g::MissedShots[ent->EntIndex()] % 2) { case 0: resolveYaw = Left; break; case 1: resolveYaw = g_ResolverRecode.resolverinfoo.fakegoalfeetyaw; break; case 2: resolveYaw = Right; break; } animState->m_flGoalFeetYaw = resolveYaw; } void ResolverRecode::FrameStage(ClientFrameStage_t stage) { if (!g::pLocalEntity || !g_pEngine->IsInGame()) return; static bool wasDormant[65]; for (int i = 1; i < g_pEngine->GetMaxClients(); ++i) { C_BaseEntity* pPlayerEntity = g_pEntityList->GetClientEntity(i); if (!pPlayerEntity || !pPlayerEntity->IsAlive()) continue; if (pPlayerEntity->IsDormant()) { wasDormant[i] = true; continue; } if (pPlayerEntity == g::pLocalEntity) { if (g_Menu.Config.DesyncTest) g_ResolverRecode.FixAnims(pPlayerEntity); } if (stage == FRAME_RENDER_START) { if (pPlayerEntity == g::pLocalEntity) { pPlayerEntity->ClientAnimations(true); if (g_Menu.Config.Animfix) fix_local_player_animations(); pPlayerEntity->UpdateClientAnimation(); pPlayerEntity->ClientAnimations(false); } g_ResolverRecode.HandleHits(pPlayerEntity); if (pPlayerEntity != g::pLocalEntity) { if (g_Menu.Config.Resolver) { if (g_Menu.Config.ResolverType == 3) g_ResolverRecode.resolve(pPlayerEntity); } } } if (stage == FRAME_NET_UPDATE_END && pPlayerEntity != g::pLocalEntity) { auto VarMap = reinterpret_cast<uintptr_t>(pPlayerEntity) + 36; auto VarMapSize = *reinterpret_cast<int*>(VarMap + 20); for (auto index = 0; index < VarMapSize; index++) * reinterpret_cast<uintptr_t*>(*reinterpret_cast<uintptr_t*>(VarMap) + index * 12) = 0; } wasDormant[i] = false; } }
28.308559
222
0.705068
[ "vector" ]
419b0c202ac19aee07b8de560a6354d4d4743acb
1,288
cpp
C++
parameter.cpp
GGonzalesD/cargs
37f7ad325ce76f5e649f2bc1eb5c37f5be404f38
[ "MIT" ]
null
null
null
parameter.cpp
GGonzalesD/cargs
37f7ad325ce76f5e649f2bc1eb5c37f5be404f38
[ "MIT" ]
null
null
null
parameter.cpp
GGonzalesD/cargs
37f7ad325ce76f5e649f2bc1eb5c37f5be404f38
[ "MIT" ]
null
null
null
#include "xargs/parameter.hpp" namespace carg{ std::vector<std::string> getNames(std::string name){ std::vector<std::string> names = std::vector<std::string>(); std::string tmp = ""; for(size_t i=0; i<name.size(); i++){ if(name.at(i) == '='){ names.push_back(tmp); tmp = ""; }else{ tmp.push_back(name.at(i)); } } if(tmp.size() > 0) names.push_back(tmp); return names; } Parameter::Parameter(){ name = ""; limit = -1; values = std::vector<std::string>(); } Parameter::Parameter(SParameter sParameter){ name = sParameter.name; limit = sParameter.limit; values = std::vector<std::string>(); } Parameter::Parameter(std::string _name, int _limit, std::vector<std::string> _values){ name = _name; limit = _limit; values = _values; } bool Parameter::testName(std::string _name){ return name.compare(_name) == 0; } void Parameter::addValue(std::string _value){ if( limit == -1 || values.size() < limit ) values.push_back(_value); } bool Parameter::full(){ return values.size() >= limit; } bool Parameter::empty(){ return values.size() == 0; } void Parameter::show(){ printf("[%s]: ", name.data()); if(values.size() > 0) for(size_t i=0; i<values.size(); i++) printf("\"%s\" ", values[i].data()); else printf("None"); printf("\n"); } }
18.4
86
0.628106
[ "vector" ]
41a64c0ff294305649fa89840b55907f25bed3c5
1,359
cpp
C++
solutions/1081/20120311T161321Z-4176265.cpp
Mistereo/timus-solutions
062540304c33312b75e0e8713c4b36c80fb220ab
[ "MIT" ]
11
2019-10-29T15:34:53.000Z
2022-03-14T14:45:09.000Z
solutions/1081/20120311T161321Z-4176265.cpp
Mistereo/timus-solutions
062540304c33312b75e0e8713c4b36c80fb220ab
[ "MIT" ]
null
null
null
solutions/1081/20120311T161321Z-4176265.cpp
Mistereo/timus-solutions
062540304c33312b75e0e8713c4b36c80fb220ab
[ "MIT" ]
6
2018-06-30T12:06:55.000Z
2021-03-20T08:46:33.000Z
#ifndef ONLINE_JUDGE #include <ctime> #endif #include <iostream> #include <string> #include <vector> #include <map> #include <set> #include <algorithm> #include <cstdlib> #include <stack> #include <stdio.h> #include <stdlib.h> #include <queue> #include <sstream> #define pb push_back #define mp make_pair #define int64 long long #define int16 short using namespace std; int F[46] = {0}; void printer(int n, int k) { if (n==0) return; if (k > F[n]) { printf("-1"); exit(0); } else { if (k <= F[n-1]) { printf("0"); printer(n-1, k); } else { printf("1"); printer(n-1, k-F[n-1]); } } } int main (int argc, const char * argv[]) { #ifndef ONLINE_JUDGE freopen("input.txt", "rt", stdin); freopen("output.txt", "wt", stdout); clock_t startTime = clock(); #endif //------------------------------------------ int n,k; scanf("%d%d", &n, &k); F[0] = 1; F[1] = 2; F[2] = 3; for (int i=3; i<46; i++) { F[i] = F[i-1] + F[i-2]; } printer(n, k); //------------------------------------------ #ifndef ONLINE_JUDGE clock_t endTime = clock(); printf("\n%lf", double(endTime-startTime)/CLOCKS_PER_SEC); fclose(stdout); #endif return 0; }
21.234375
63
0.482708
[ "vector" ]
41abe9c8f6f11a9fbf1d46a769fb04f037fd6f80
6,171
cpp
C++
sample/SkySphere/main_glfw.cpp
menonon/SimpleGLWrapper
a99af4ee9b0e9fef8ac1ffe3b01aef32157929bb
[ "MIT" ]
null
null
null
sample/SkySphere/main_glfw.cpp
menonon/SimpleGLWrapper
a99af4ee9b0e9fef8ac1ffe3b01aef32157929bb
[ "MIT" ]
null
null
null
sample/SkySphere/main_glfw.cpp
menonon/SimpleGLWrapper
a99af4ee9b0e9fef8ac1ffe3b01aef32157929bb
[ "MIT" ]
null
null
null
/* The MIT License (MIT) Copyright (c) 2013-2018 menonon 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 <GL/glew.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/constants.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/transform.hpp> #include <iostream> #include <fstream> #include <string> #include <vector> #define _USE_MATH_DEFINES #include <math.h> #include "shader.hpp" #include "texture.hpp" #include "geometry.hpp" #include "VAO.hpp" //#include "marchingcubes.hpp" //#include "renderer.hpp" //#include "resource.hpp" #include "skysphere.hpp" #include "error.hpp" bool geomON = true; bool rotON = false; static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (key == GLFW_KEY_G && action == GLFW_PRESS) { geomON = !geomON; std::cout << geomON << std::endl; } if ((key == GLFW_KEY_ESCAPE || key == GLFW_KEY_Q) && action == GLFW_PRESS) { glfwSetWindowShouldClose(window, GL_TRUE); } if (key == GLFW_KEY_R && action == GLFW_PRESS) { rotON = !rotON; } if (key == GLFW_KEY_W && action == GLFW_PRESS) { } if (key == GLFW_KEY_S && action == GLFW_PRESS) { } } float gScrX = 0.0; static void scroll_callback(GLFWwindow* window, double xoffset, double yoffset) { gScrX = static_cast<float>(xoffset); } glm::mat4 getViewMatrix(GLFWwindow* window) { double mx, my; glfwGetCursorPos(window, &mx, &my); int ww, wh; glfwGetWindowSize(window, &ww, &wh); double pi = glm::pi<double>(); double twopi = 2.0 * glm::pi<double>(); // std::cout << mx << ", " << my << " : " << ww << ", " << wh << std::endl; double yAxisRotation = mx / static_cast<double>(ww) * twopi - pi; double eyeHeight = my / static_cast<double>(wh) * 5.0 - 1.5; glm::mat4 ret = glm::lookAt(glm::vec3(5 * cos(yAxisRotation), eyeHeight, 5 * sin(yAxisRotation)), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0)); return ret; } int main(void) { GLFWwindow* window1; /* Initialize the library */ if (!glfwInit()) { std::cout << "glfwInit failed !" << std::endl; return -1; } glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); //for Debug(OpenGL4.3) /* Create a windowed mode window and its OpenGL context */ window1 = glfwCreateWindow(1920, 1080, "GLFW TEST", NULL, NULL); if (!window1) { std::cout << "glfwCreateWindow failed" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window1); glewExperimental = true; if (glewInit() != GLEW_OK)std::cout << "glew initialization failed!!" << std::endl; //DebugMessage initDebugMessage(); // create VAO VAO* vao = new VAO(); vao->bind(); // create geometry SkySphere* skysphere = new SkySphere(40, 40, 2, false, false, false, false, std::string("../../data/SkySphere_MovieSample.mp4")); SkySphere* skysphere1 = new SkySphere(40, 40, 3, false, false, false, false, std::string("../../data/SkySphere_StilImageSample.png")); skysphere->graphicsInit(0); skysphere1->graphicsInit(0); // load shader Shader* shader1 = new Shader(); Shader* shader2 = new Shader(); shader1->compileShader(GL_VERTEX_SHADER, "../../shader/basic.vert"); shader1->compileShader(GL_FRAGMENT_SHADER, "../../shader/tex2D_UI.frag"); shader1->linkProgram(); shader2->compileShader(GL_VERTEX_SHADER, "../../shader/basic.vert"); shader2->compileShader(GL_FRAGMENT_SHADER, "../../shader/tex2D.frag"); shader2->linkProgram(); // end of load shader /* Make the window's context current */ glClearColor(1.0, 0.5, 0.5, 1); glfwSetKeyCallback(window1, key_callback); glfwSetScrollCallback(window1, scroll_callback); glm::mat4 projection = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.0f); glm::mat4 view = glm::lookAt(glm::vec3(0, 0, 5), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0)); glm::mat4 model = glm::translate(glm::vec3(-1, -1, -1)); glm::mat4 MVP = projection * view * model; glm::mat4 modelview = view * model; glEnable(GL_DEPTH_TEST); static double framecount = 0.0; /* Loop until the user closes the window */ while (!glfwWindowShouldClose(window1)) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //std::cout << "ss :" << skysphere->getTextureUnit(0) << std::endl; //std::cout << "ss1:" << skysphere1->getTextureUnit(0) << std::endl; if (geomON) { skysphere->update(); shader1->use(); shader1->setUniform("uModelView", modelview); shader1->setUniform("uProjection", projection); shader1->setUniform("uTexture", skysphere->getTextureUnit(0)); skysphere->draw(0); } else { shader2->use(); shader2->setUniform("uModelView", modelview); shader2->setUniform("uProjection", projection); shader2->setUniform("uTexture", skysphere1->getTextureUnit(0)); skysphere1->draw(0); } Shader::unuse(); glfwSwapBuffers(window1); gScrX = 1.0; glfwPollEvents(); view = getViewMatrix(window1); MVP = projection * view * model; modelview = view * model; } glfwTerminate(); return 0; }
26.830435
135
0.6994
[ "geometry", "vector", "model", "transform" ]
41ac9dbb1a536adf0cc665857aa2db68c8a032e1
9,650
cpp
C++
vector_map_converter/src/opendrive2autowaremap_core/map_writer.cpp
neophack/utilities
a6ce6d7c1b407e555955491874d66e7ef263d52d
[ "Apache-2.0" ]
null
null
null
vector_map_converter/src/opendrive2autowaremap_core/map_writer.cpp
neophack/utilities
a6ce6d7c1b407e555955491874d66e7ef263d52d
[ "Apache-2.0" ]
null
null
null
vector_map_converter/src/opendrive2autowaremap_core/map_writer.cpp
neophack/utilities
a6ce6d7c1b407e555955491874d66e7ef263d52d
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019 Autoware Foundation. 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. */ /* * opendrive2op_map_converter_core.cpp * * Created on: Feb 11, 2019 * Author: hatem */ #include "opendrive2autoware_converter/map_writer.h" #include "op_planner/RoadNetwork.h" #include <fstream> #include <autoware_map_msgs/LaneArray.h> #include <autoware_map_msgs/LaneAttributeRelationArray.h> #include <autoware_map_msgs/LaneRelationArray.h> #include <autoware_map_msgs/LaneSignalLightRelationArray.h> #include <autoware_map_msgs/LaneChangeRelationArray.h> #include <autoware_map_msgs/OppositeLaneRelationArray.h> #include <autoware_map_msgs/PointArray.h> #include <autoware_map_msgs/AreaArray.h> #include <autoware_map_msgs/SignalArray.h> #include <autoware_map_msgs/SignalLightArray.h> #include <autoware_map_msgs/WayareaArray.h> #include <autoware_map_msgs/WaypointArray.h> #include <autoware_map_msgs/WaypointLaneRelationArray.h> #include <autoware_map_msgs/WaypointRelationArray.h> #include <autoware_map_msgs/WaypointSignalRelationArray.h> #include "autoware_map/util.h" namespace opendrive_converter { bool exists(autoware_map_msgs::LaneArray &lanes, int lane_id){ for(const auto lane: lanes.data){ if(lane_id == lane.lane_id) return true; } return false; } bool exists(autoware_map_msgs::WaypointArray &waypoints, int waypoint_id){ for(const auto waypoint: waypoints.data){ if(waypoint_id == waypoint.waypoint_id) return true; } return false; } MapWriter::MapWriter() { } MapWriter::~MapWriter() { } template <class T> void MapWriter::writeCSVFile(const std::string& folder, const std::string& title, const std::string& header, const std::vector<T>& data_list) { if(data_list.size() < 2) return; std::ostringstream file_name; file_name << folder; file_name << title; file_name << ".csv"; std::ofstream f(file_name.str().c_str()); if(f.is_open()) { if(header.size() > 0) f << header << "\r\n"; for(unsigned int i = 0 ; i < data_list.size(); i++) f << data_list.at(i) << "\r\n"; } f.close(); } void MapWriter::writeAutowareMap(std::string folder_name, PlannerHNS::RoadNetwork& map) { if(map.roadSegments.size() == 0) { std::cout << "Can't Write Empty Map (no lanes) into autoware format ! " << std::endl; return; } autoware_map_msgs::PointArray points_list; autoware_map_msgs::LaneArray lanes_list; autoware_map_msgs::LaneRelationArray lane_relations_list; autoware_map_msgs::SignalArray signals_list; autoware_map_msgs::SignalLightArray lights_list; autoware_map_msgs::WaypointSignalRelationArray wp_lights_relations_list; autoware_map_msgs::WaypointArray waypoints_list; autoware_map_msgs::WaypointRelationArray wp_relations_list; autoware_map_msgs::WaypointLaneRelationArray wp_lanes_relations_list; int points_id_seq = 1; int signal_id_seq = 1; for(unsigned int i=0; i<map.roadSegments.at(0).Lanes.size(); i++) { PlannerHNS::Lane* p_lane = &map.roadSegments.at(0).Lanes.at(i); if(p_lane->points.size() < 2) { std::cout << "Writing Autoware format, Skip lane with less than 2 waypoints, with ID: " << p_lane->id << std::endl; continue; } autoware_map_msgs::Lane l; l.lane_id = p_lane->id; l.lane_number = p_lane->num; //TODO check in document l.length = p_lane->length; l.num_of_lanes = p_lane->num; //TODO check in document l.speed_limit = p_lane->speed; l.start_waypoint_id = p_lane->points.at(0).id; l.end_waypoint_id = p_lane->points.at(p_lane->points.size()-1).id; l.height_limit = 0; l.weight_limit = 0; l.width_limit = p_lane->width; lanes_list.data.push_back(l); autoware_map_msgs::LaneRelation lr; lr.lane_id = p_lane->id; for(unsigned int k=0; k< p_lane->toIds.size(); k++) { lr.blinker = 0; //TODO check in document for later support lr.next_lane_id = p_lane->toIds.at(k); lane_relations_list.data.push_back(lr); } for(unsigned int j=0; j< p_lane->points.size(); j++) { autoware_map_msgs::Point p; p.mgrs = 0; //TODO check in document p.epsg = 0; //TODO check in document p.lat = 0; p.lng = 0; p.pcd = ""; p.point_id = points_id_seq++; p.x = p_lane->points.at(j).pos.x; p.y = p_lane->points.at(j).pos.y; p.z = p_lane->points.at(j).pos.z; points_list.data.push_back(p); autoware_map_msgs::Waypoint wp; wp.point_id = p.point_id; wp.height = 0; //TODO check in document wp.left_width = p_lane->points.at(j).collisionCost/2.0; wp.right_width = p_lane->points.at(j).collisionCost/2.0; wp.stop_line = p_lane->points.at(j).stopLineID; wp.velocity = p_lane->points.at(j).v; wp.waypoint_id = p_lane->points.at(j).id; waypoints_list.data.push_back(wp); autoware_map_msgs::WaypointRelation wpr; wpr.waypoint_id = wp.waypoint_id; wpr.yaw = p_lane->points.at(j).pos.a; wpr.blinker = 0; //TODO check in document if(j < p_lane->points.size()-1) { wpr.distance = hypot(p_lane->points.at(j+1).pos.y - p.y, p_lane->points.at(j+1).pos.x - p.x); } else { wpr.distance = 0; } for(unsigned int k=0; k < p_lane->points.at(j).toIds.size(); k++) { wpr.next_waypoint_id = p_lane->points.at(j).toIds.at(k); wp_relations_list.data.push_back(wpr); } autoware_map_msgs::WaypointLaneRelation wplr; wplr.waypoint_id = wp.waypoint_id; wplr.lane_id = l.lane_id; wplr.order = j; wp_lanes_relations_list.data.push_back(wplr); } } //remove invalid relations auto erase_itr = std::remove_if(lane_relations_list.data.begin(),lane_relations_list.data.end(), [&](autoware_map_msgs::LaneRelation lr){return (!exists(lanes_list, lr.next_lane_id)) ;}); for(auto itr = erase_itr; itr != lane_relations_list.data.end() ; itr++ ){ std::cout << "deleting: " << itr->lane_id << "->" << itr->next_lane_id << " " << (!exists(lanes_list, itr->lane_id)) << std::endl; } lane_relations_list.data.erase(erase_itr, lane_relations_list.data.end()); auto erase_itr2 = std::remove_if(wp_relations_list.data.begin(),wp_relations_list.data.end(), [&](autoware_map_msgs::WaypointRelation wr){return !exists(waypoints_list, wr.waypoint_id) || !exists(waypoints_list, wr.next_waypoint_id) ;}); wp_relations_list.data.erase(erase_itr2, wp_relations_list.data.end()); for(unsigned int i=0; i<map.trafficLights.size(); i++) { PlannerHNS::TrafficLight* p_light = &map.trafficLights.at(i); autoware_map_msgs::Point p; p.mgrs = 0; //TODO check in document p.epsg = 0; //TODO check in document p.lat = 0; p.lng = 0; p.pcd = ""; p.point_id = points_id_seq++; p.x = p_light->pos.x; p.y = p_light->pos.y; p.z = p_light->pos.z; points_list.data.push_back(p); autoware_map_msgs::Signal s; s.signal_id = signal_id_seq++; signals_list.data.push_back(s); autoware_map_msgs::SignalLight sl; sl.arrow_type = 0; //TODO support standard sl.color_type = 0; sl.point_id = p.point_id; sl.signal_id = s.signal_id; sl.signal_light_id = p_light->id; sl.horizontal_angle = p_light->pos.a; //sl.vertical_angle = p_light->rot.y; //TODO support standard and opendrive lights_list.data.push_back(sl); for(unsigned int j=0; j < p_light->laneIds.size(); j++) { autoware_map_msgs::WaypointSignalRelation wp_s_r; PlannerHNS::Lane* p_op_lane = getLaneFromID(map, p_light->laneIds.at(j)); if(p_op_lane != nullptr) { wp_s_r.signal_id = sl.signal_id; wp_s_r.waypoint_id = p_op_lane->points.at(p_op_lane->points.size()-1).id; wp_lights_relations_list.data.push_back(wp_s_r); } } } for(unsigned int i=0; i<map.signs.size(); i++) { PlannerHNS::TrafficSign* p_sign = &map.signs.at(i); autoware_map_msgs::Point p; p.mgrs = 0; //TODO check in document p.epsg = 0; //TODO check in document p.lat = 0; p.lng = 0; p.pcd = ""; p.point_id = points_id_seq++; p.x = p_sign->pos.x; p.y = p_sign->pos.y; p.z = p_sign->pos.z; points_list.data.push_back(p); } writeCSVFile(folder_name, "points", "point_id,x,y,z,lat,lng,pcd,mgrs,epsg", points_list.data); writeCSVFile(folder_name, "lanes", "lane_id,start_waypoint_id,end_waypoint_id," "lane_number,num_of_lanes,speed_limit,length,width_limit,height_limit,weight_limit", lanes_list.data); writeCSVFile(folder_name, "lane_relations", "lane_id,next_lane_id,blinker", lane_relations_list.data); writeCSVFile(folder_name, "waypoints", "waypoint_id,point_id,velocity,stop_line,left_width,right_width,height", waypoints_list.data); writeCSVFile(folder_name, "waypoint_relations", "waypoint_id,next_waypoint_id,yaw,blinker,distance", wp_relations_list.data); writeCSVFile(folder_name, "waypoint_lane_relations", "waypoint_id,lane_id,order", wp_lanes_relations_list.data); writeCSVFile(folder_name, "signals", "signal_id", signals_list.data); writeCSVFile(folder_name, "signal_lights", "signal_light_id,signal_id,point_id,horizontal_angle,vertical_angle,color_type,arrow_type", lights_list.data); writeCSVFile(folder_name, "waypoint_signal_relations", "waypoint_id,signal_id", wp_lights_relations_list.data); std::cout << "Finish Writing map files .csv to folder: " << folder_name << std::endl; } }
31.953642
154
0.718756
[ "vector" ]
41b59361dac2a8a18a96bff449b919c956e46076
7,685
cpp
C++
BGL/test/BGL/test_helpers.cpp
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
3,227
2015-03-05T00:19:18.000Z
2022-03-31T08:20:35.000Z
BGL/test/BGL/test_helpers.cpp
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
5,574
2015-03-05T00:01:56.000Z
2022-03-31T15:08:11.000Z
BGL/test/BGL/test_helpers.cpp
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
1,274
2015-03-05T00:01:12.000Z
2022-03-31T14:47:56.000Z
#include <CGAL/Simple_cartesian.h> #include <CGAL/Surface_mesh.h> #include <CGAL/boost/graph/graph_traits_Surface_mesh.h> #include <CGAL/boost/graph/generators.h> #include <CGAL/boost/graph/helpers.h> #include <CGAL/boost/graph/Euler_operations.h> #include <iostream> #include <fstream> typedef CGAL::Simple_cartesian<double> K; typedef K::Point_3 Point_3; template <typename Mesh> void test_validity() { std::cerr << "test validity" << std::endl; typedef typename boost::graph_traits<Mesh>::vertex_descriptor vertex_descriptor; typedef typename boost::graph_traits<Mesh>::edge_descriptor edge_descriptor; typedef typename boost::graph_traits<Mesh>::face_descriptor face_descriptor; typedef typename boost::property_map<Mesh, CGAL::vertex_point_t>::type VPMap; Mesh mesh; VPMap vpmap = get(CGAL::vertex_point, mesh); vertex_descriptor vertices[4]; edge_descriptor edges[4]; vertices[0] = add_vertex(mesh); vertices[1] = add_vertex(mesh); vertices[2] = add_vertex(mesh); vertices[3] = add_vertex(mesh); put(vpmap, vertices[0], Point_3(0,0,0)); put(vpmap, vertices[1], Point_3(1,0,0)); put(vpmap, vertices[2], Point_3(1,1,0)); put(vpmap, vertices[3], Point_3(0,1,0)); edges[0] = add_edge(mesh); edges[1] = add_edge(mesh); edges[2] = add_edge(mesh); edges[3] = add_edge(mesh); assert(!CGAL::is_valid_halfedge_graph(mesh)); for(int i=0; i<4; ++i) { set_target(halfedge(edges[i], mesh), vertices[i], mesh); set_halfedge(vertices[i], halfedge(edges[i], mesh), mesh); } for(int i=0; i<4; ++i) set_target(opposite(halfedge(edges[i], mesh), mesh), vertices[(i+1)%4], mesh); for(int i=0; i<4; ++i) { set_next(halfedge(edges[(i+1)%4], mesh), halfedge(edges[i], mesh), mesh); set_next(opposite(halfedge(edges[i], mesh), mesh), opposite(halfedge(edges[(i+1)%4], mesh), mesh), mesh); } assert(CGAL::is_valid_halfedge_graph(mesh)); face_descriptor faces[1]; faces[0] = add_face(mesh); assert(!CGAL::is_valid_face_graph(mesh)); for(int i=0; i<4; ++i) { set_face(opposite(halfedge(edges[i], mesh), mesh), faces[0], mesh); } set_halfedge(faces[0], opposite(halfedge(edges[0], mesh), mesh), mesh); assert(CGAL::is_valid_face_graph(mesh)); assert(CGAL::is_valid_polygon_mesh(mesh)); Mesh dummy; vertices[0] = add_vertex(dummy); vertices[1] = add_vertex(dummy); edges[0] = add_edge(dummy); set_target(halfedge(edges[0], dummy), vertices[0], dummy); set_halfedge(vertices[0], halfedge(edges[0], dummy), dummy); set_target(opposite(halfedge(edges[0], dummy), dummy), vertices[1], dummy); set_halfedge(vertices[1], opposite(halfedge(edges[0], dummy), dummy), dummy); set_next(halfedge(edges[0], dummy), opposite(halfedge(edges[0], dummy), dummy), dummy); set_next(opposite(halfedge(edges[0], dummy), dummy), halfedge(edges[0], dummy), dummy); faces[0] = add_face(dummy); set_halfedge(faces[0], opposite(halfedge(edges[0], dummy), dummy), dummy); set_face(halfedge(edges[0], dummy), faces[0], dummy); set_face(opposite(halfedge(edges[0], dummy), dummy), faces[0], dummy); assert(CGAL::is_valid_face_graph(dummy)); assert(!CGAL::is_valid_polygon_mesh(dummy)); } template <typename Mesh> void test(const std::string fname, bool triangle, bool quad, bool tetrahedron, bool hexahedron) { typedef typename boost::graph_traits<Mesh>::halfedge_descriptor halfedge_descriptor; std::cerr << "test(" << fname << ")"<< std::endl; Mesh m; std::ifstream in(fname); in >> m; halfedge_descriptor hd = *halfedges(m).first; assert(CGAL::is_isolated_triangle(hd, m) == triangle); assert(CGAL::is_isolated_quad(hd, m) == quad); assert(CGAL::is_tetrahedron(hd, m) == tetrahedron); assert(CGAL::is_hexahedron(hd, m) == hexahedron); } template <typename Mesh> void test_generators() { typedef typename boost::graph_traits<Mesh>::vertex_descriptor vertex_descriptor; typedef typename boost::graph_traits<Mesh>::halfedge_descriptor halfedge_descriptor; typedef typename boost::graph_traits<Mesh>::edge_descriptor edge_descriptor; typedef typename boost::graph_traits<Mesh>::face_descriptor face_descriptor; // triangle quad tetra hexa test<Mesh>("data/triangle.off", true, false, false, false ); test<Mesh>("data/quad.off", false, true, false, false ); test<Mesh>("data/tetrahedron.off", false, false, true, false ); test<Mesh>(CGAL::data_file_path("meshes/cube.off"), false, false, false, false ); test<Mesh>("data/cube-quads.off", false, false, false, true ); Point_3 a(0,0,0), b(1,0,0), c(1,1,0), d(0,1,0); Point_3 aa(0,0,1), bb(1,0,1), cc(1,1,1), dd(0,1,1); Mesh m; halfedge_descriptor hd; hd = CGAL::make_triangle(a,b,c,m); assert(CGAL::is_isolated_triangle(hd,m)); assert(CGAL::is_valid_polygon_mesh(m)); m.clear(); hd = CGAL::make_quad(a,b,c,d,m); assert(CGAL::is_isolated_quad(hd,m)); assert(CGAL::is_valid_polygon_mesh(m)); assert(CGAL::is_quad_mesh(m)); m.clear(); hd = CGAL::make_tetrahedron(a,b,c,d,m); assert(CGAL::is_tetrahedron(hd,m)); assert(CGAL::is_triangle_mesh(m)); assert(CGAL::is_valid_polygon_mesh(m)); m.clear(); hd = CGAL::make_hexahedron(a,b,c,d,dd,aa,bb,cc,m); assert(CGAL::is_hexahedron(hd,m)); assert(CGAL::is_quad_mesh(m)); assert(CGAL::is_valid_polygon_mesh(m)); m.clear(); CGAL::make_icosahedron<Mesh, Point_3>(m); assert(num_faces(m) == 20); assert(CGAL::is_triangle_mesh(m)); assert(CGAL::is_valid_polygon_mesh(m)); m.clear(); hd = CGAL::make_pyramid<Mesh, Point_3>(3, m); assert(num_faces(m) == 6); assert(CGAL::is_triangle_mesh(m)); assert(CGAL::is_valid_polygon_mesh(m)); m.clear(); hd = CGAL::make_regular_prism<Mesh, Point_3>(4, m); assert(num_faces(m) == 16); assert(CGAL::is_triangle_mesh(m)); assert(CGAL::is_valid_polygon_mesh(m)); m.clear(); CGAL::make_grid(3,3,m); assert(num_faces(m) == 9); assert(CGAL::is_quad_mesh(m)); assert(CGAL::is_valid_polygon_mesh(m)); // ----------------------------------------------------------------------------------------------- std::cerr << "test random element generators" << std::endl; vertex_descriptor v; halfedge_descriptor h; edge_descriptor e; face_descriptor f; CGAL::Random rnd; // --------------------------------------------------------------------------- v = CGAL::internal::random_vertex_in_mesh(m, rnd); assert(v != boost::graph_traits<Mesh>::null_vertex()); h = CGAL::internal::random_halfedge_in_mesh(m, rnd); assert(h != boost::graph_traits<Mesh>::null_halfedge()); e = CGAL::internal::random_edge_in_mesh(m, rnd); f = CGAL::internal::random_face_in_mesh(m, rnd); assert(f != boost::graph_traits<Mesh>::null_face()); // --------------------------------------------------------------------------- h = CGAL::internal::random_halfedge_in_face(f, m, rnd); assert(h != boost::graph_traits<Mesh>::null_halfedge()); assert(face(h, m) == f); v = CGAL::internal::random_vertex_in_face(f, m, rnd); assert(v != boost::graph_traits<Mesh>::null_vertex()); // could use vertices_around_face, but it's the point is not to bool has_vertex = false; halfedge_descriptor done = h; do { if(target(h, m) == v) { has_vertex = true; break; } h = next(h, m); } while(h != done); assert(has_vertex); } int main() { typedef CGAL::Surface_mesh<Point_3> Mesh; test_validity<Mesh>(); test_generators<Mesh>(); std::cerr << "done" << std::endl; return EXIT_SUCCESS; }
32.702128
100
0.648926
[ "mesh" ]
41b7ff256894c17798eaff8cc2f447dd64b16c82
4,190
cpp
C++
ql/models/marketmodels/products/pathwise/pathwiseproductswap.cpp
haozhangphd/QuantLib-noBoost
ddded069868161099843c04840454f00816113ad
[ "BSD-3-Clause" ]
76
2017-06-28T21:24:38.000Z
2021-12-19T18:07:37.000Z
ql/models/marketmodels/products/pathwise/pathwiseproductswap.cpp
haozhangphd/QuantLib-noBoost
ddded069868161099843c04840454f00816113ad
[ "BSD-3-Clause" ]
2
2017-07-05T09:20:13.000Z
2019-10-31T12:06:51.000Z
ql/models/marketmodels/products/pathwise/pathwiseproductswap.cpp
haozhangphd/QuantLib-noBoost
ddded069868161099843c04840454f00816113ad
[ "BSD-3-Clause" ]
34
2017-07-02T14:49:21.000Z
2021-11-26T15:32:04.000Z
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2009 Mark Joshi This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. 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 license for more details. */ #include <ql/models/marketmodels/products/pathwise/pathwiseproductswap.hpp> #include <ql/models/marketmodels/curvestate.hpp> #include <ql/models/marketmodels/utilities.hpp> namespace QuantLib { bool MarketModelPathwiseSwap::alreadyDeflated() const { return false; } MarketModelPathwiseSwap::MarketModelPathwiseSwap(const std::vector<Time>& rateTimes, const std::vector<Real>& accruals, const std::vector<Rate>& strikes, Real multiplier) : rateTimes_(rateTimes), accruals_(accruals), strikes_(strikes) , numberRates_(rateTimes.size()-1), multiplier_(multiplier) { checkIncreasingTimes(rateTimes); std::vector<Time> evolTimes(rateTimes_); evolTimes.pop_back(); QL_REQUIRE(evolTimes.size()==numberRates_, "rateTimes.size()<> numberOfRates+1"); if (strikes_.size() == 1) strikes_ = std::vector<Rate>(numberRates_, strikes[0]); if (accruals_.size() == 1) accruals_ = std::vector<Rate>(numberRates_, accruals[0]); QL_REQUIRE(accruals_.size()==numberRates_, "accruals.size() does not equal numberOfRates or 1"); QL_REQUIRE(strikes.size()==numberRates_, "strikes.size() does not equal numberOfRates or 1" ); evolution_ = EvolutionDescription(rateTimes,evolTimes); } bool MarketModelPathwiseSwap::nextTimeStep( const CurveState& currentState, std::vector<Size>& numberCashFlowsThisStep, std::vector<std::vector<MarketModelPathwiseMultiProduct::CashFlow> >& cashFlowsGenerated) { Rate liborRate = currentState.forwardRate(currentIndex_); cashFlowsGenerated[0][0].timeIndex = currentIndex_+1; cashFlowsGenerated[0][0].amount[0] = (liborRate-strikes_[currentIndex_])*accruals_[currentIndex_]*multiplier_; numberCashFlowsThisStep[0] = 1; for (Size i=1; i <= numberRates_; ++i) cashFlowsGenerated[0][0].amount[i] =0; cashFlowsGenerated[0][0].amount[currentIndex_+1] = accruals_[currentIndex_]*multiplier_; ++currentIndex_; return (currentIndex_ == strikes_.size()); } std::unique_ptr<MarketModelPathwiseMultiProduct> MarketModelPathwiseSwap::clone() const { return std::make_unique<MarketModelPathwiseSwap>(*this); } std::vector<Size> MarketModelPathwiseSwap::suggestedNumeraires() const { std::vector<Size> numeraires(numberRates_); for (Size i=0; i < numberRates_; ++i) numeraires[i] = i; return numeraires; } const EvolutionDescription& MarketModelPathwiseSwap::evolution() const { return evolution_; } std::vector<Time> MarketModelPathwiseSwap::possibleCashFlowTimes() const { return rateTimes_; // note rateTimes_[0] is not used as a cash flow time but it is easier to keep track if we include it. } Size MarketModelPathwiseSwap::numberOfProducts() const { return 1; } Size MarketModelPathwiseSwap::maxNumberOfCashFlowsPerProductPerStep() const { return 1; } void MarketModelPathwiseSwap::reset() { currentIndex_=0; } }
32.230769
129
0.652745
[ "vector" ]
41bb138fd832dea18dc80d97d6247dd40dbf4acc
741
hpp
C++
include/turbo/graphics/Text.hpp
mariusvn/turbo-engine
63cc2b76bc1aff7de9655916553a03bd768f5879
[ "MIT" ]
2
2021-02-12T13:05:02.000Z
2021-02-22T14:25:00.000Z
include/turbo/graphics/Text.hpp
mariusvn/turbo-engine
63cc2b76bc1aff7de9655916553a03bd768f5879
[ "MIT" ]
null
null
null
include/turbo/graphics/Text.hpp
mariusvn/turbo-engine
63cc2b76bc1aff7de9655916553a03bd768f5879
[ "MIT" ]
null
null
null
#ifndef __TURBO_TEXT_HPP__ #define __TURBO_TEXT_HPP__ #include "Drawable.hpp" #include "../Transform.hpp" #include "../Font.hpp" namespace turbo { /** * @brief Represent a drawable text */ class Text: public Drawable { public: /** * @brief Construct a new Text drawable * * @param font Selected text font * @param text content */ Text(Font* font, const char* text = ""); ~Text(); void draw() const override; operator const char*() const; /** * @brief Text content */ const char* text; protected: /** * @brief Selected font */ Font* font; }; } #endif
18.073171
48
0.512821
[ "transform" ]
41bd0fe17fb8fbe2dde794c7513d1137eddbac57
385
cpp
C++
src/problem118/Solution.cpp
MyYaYa/leetcode
d779c215516ede594267b15abdfba5a47dc879dd
[ "Apache-2.0" ]
1
2016-09-29T14:23:59.000Z
2016-09-29T14:23:59.000Z
src/problem118/Solution.cpp
MyYaYa/leetcode
d779c215516ede594267b15abdfba5a47dc879dd
[ "Apache-2.0" ]
null
null
null
src/problem118/Solution.cpp
MyYaYa/leetcode
d779c215516ede594267b15abdfba5a47dc879dd
[ "Apache-2.0" ]
null
null
null
class Solution { public: vector<vector<int>> generate(int numRows) { vector<vector<int>> result; for (int i = 0; i < numRows; i++) { vector<int> temp(i+1, 1); for (int j = 1; j < i; j++) { temp[j] = result[i-1][j-1] + result[i-1][j]; } result.push_back(temp); } return result; } };
27.5
60
0.446753
[ "vector" ]
41bff36a3e7eb32f18cbcbae6c611b2e7f658c91
4,299
cpp
C++
src/main/main.cpp
mrc-g/FogMon
dc040e5566d4fa6b0fca80fb46767f40f19b7c2e
[ "MIT" ]
7
2019-05-08T08:25:40.000Z
2021-06-19T10:42:56.000Z
src/main/main.cpp
mrc-g/FogMon
dc040e5566d4fa6b0fca80fb46767f40f19b7c2e
[ "MIT" ]
5
2020-03-07T15:24:27.000Z
2022-03-12T00:49:53.000Z
src/main/main.cpp
mrc-g/FogMon
dc040e5566d4fa6b0fca80fb46767f40f19b7c2e
[ "MIT" ]
4
2020-03-05T17:05:42.000Z
2021-11-21T16:00:56.000Z
#include "inputParser.hpp" #include "node.hpp" #include "message.hpp" #include <unistd.h> #include <string> using namespace std; //sudo docker run -it --net=host server -C 54.93.78.224 //sudo docker run -it --net=host node -C 54.93.78.224 //sudo docker run -it --net=host server --time-report 5 --time-tests 10 --time-latency 20 --time-bandwidth 60 --heartbeat 10 //sudo docker run -it --net=host server -C 54.93.78.224 --time-report 5 --time-tests 10 --time-latency 20 --time-bandwidth 60 --heartbeat 10 //sudo docker run -it --net=host node -C 54.93.78.224 --time-report 5 --time-tests 10 --time-latency 20 --time-bandwidth 60 --heartbeat 10 // --time-report 5 --time-tests 10 --time-latency 20 --time-bandwidth 60 --heartbeat 10 // --time-report 15 --time-tests 30 --time-latency 40 --time-bandwidth 300 --heartbeat 30 // --time-report 30 --time-tests 60 --time-latency 100 --time-bandwidth 600 --heartbeat 60 int main(int argc, char *argv[]) { cout << argv[1] << endl; InputParser input(argc,argv); if(input.cmdOptionExists("-h") || input.cmdOptionExists("--help")) { cout << "Usage: ./program [OPTIONS]..." << endl<<endl; cout << "--leader for leader" <<endl; cout << "-C ip to connect" <<endl; cout << "-P port to connect" <<endl; cout << "--my-port listening port" <<endl; cout <<endl<< "there are other for timing" <<endl; return 0; } string ipR = ""; string portR = "5555"; string myPort = "5555"; int threads = 2; int time_heartbeat = 120; int time_propagation = 20; if(input.cmdOptionExists("-C")) ipR = input.getCmdOption("-C"); if(input.cmdOptionExists("-P")) portR = input.getCmdOption("-P"); if(input.cmdOptionExists("--my-port")) myPort = input.getCmdOption("--my-port"); if(input.cmdOptionExists("-t")) threads = stoi(input.getCmdOption("-t")); if(input.cmdOptionExists("--heartbeat")) time_heartbeat = stoi(input.getCmdOption("--heartbeat")); if(input.cmdOptionExists("--time-propagation")) time_propagation = stoi(input.getCmdOption("--time-propagation")); int time_report = 30; int time_tests = 30; int time_latency = 30; int max_latency = 100; int time_bandwidth = 600; int max_bandwidth=1; int leaderCheck = 10; bool leader = false; if(input.cmdOptionExists("--time-report")) time_report = stoi(input.getCmdOption("--time-report")); if(input.cmdOptionExists("--time-tests")) time_tests = stoi(input.getCmdOption("--time-tests")); if(input.cmdOptionExists("--time-latency")) time_latency = stoi(input.getCmdOption("--time-latency")); if(input.cmdOptionExists("--max-per-latency")) max_latency = stoi(input.getCmdOption("--max-per-latency")); if(input.cmdOptionExists("--time-bandwidth")) time_bandwidth = stoi(input.getCmdOption("--time-bandwidth")); if(input.cmdOptionExists("--max-per-bandwidth")) time_bandwidth = stoi(input.getCmdOption("--max-per-bandwidth")); if(input.cmdOptionExists("--leader-check")) leaderCheck = stoi(input.getCmdOption("--leader-check")); if(input.cmdOptionExists("--leader")) leader = true; Node node(myPort, leader, threads); vector<Message::node> known; if(ipR != "") known.push_back(Message::node("",ipR,portR)); node.setMNodes(known); node.setParam(string("heartbeat"), time_heartbeat); node.setParam(string("time-propagation"), time_propagation); node.setParam(string("time-report"), time_report); node.setParam(string("time-tests"), time_tests); node.setParam(string("time-latency"), time_latency); node.setParam(string("max-per-latency"), max_latency); node.setParam(string("time-bandwidth"), time_bandwidth); node.setParam(string("max-per-bandwidth"), max_bandwidth); node.setParam(string("leader-check"), leaderCheck); node.start(); int a = -1; do { switch(a) { case 0: node.setParam("start-selection",1); break; default: break; } scanf("%d",&a); }while(a == 0); return 0; }
31.610294
140
0.619912
[ "vector" ]
41c6e800669f239341a893c85607942708af016d
2,000
cpp
C++
AtCoder/arc127/a/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
null
null
null
AtCoder/arc127/a/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
1
2021-10-19T08:47:23.000Z
2022-03-07T05:23:56.000Z
AtCoder/arc127/a/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> #include <algorithm> #include <vector> using namespace std; int main() { long long int n; cin >> n; long long int ans = 0; vector<pair<long long int, long long int>> v; v.push_back(make_pair(0, 9)); for (long long int i = 10; i <= 10e14; i *= 10) v.push_back(make_pair(i, i * 10 - 1)); v.push_back(make_pair(1000000000000000, 1000000000000000)); vector<vector<long long int>> p, q; for (int i = 0; i < 15; i++) { vector<long long int> a; for (int j = 0; j <= i; j++) a.push_back(j); vector<long long int> b = a; b.push_back((long long int)(i + 1)); reverse(a.begin(), a.end()); b.insert(b.end(), a.begin(), a.end()); p.push_back(b); } long long int s = 0; for (int i = 0; i < 15; i++) { vector<long long int> a; long long int d = 1, e = 8, ss = s; for (int j = 0; j < i - 1; j++) d *= 10; if (i == 0) d = 0; for (int j = 0; j < p[i].size(); j++) { if (i != 0 && j == 0) { a.push_back(ss); continue; } if (j == i + 1) { a.push_back(ss + 1); ss += 1; } else if (j > p[i][j]) { a.push_back(ss + e); ss += e; e *= 10; } else { a.push_back(ss + d); ss += d; d /= 10; } } s = ss; q.push_back(a); } bool t = false; long long bef = -1; for (int i = 0; i < 15; i++) { for (int j = 0; j < p[i].size(); j++) { if (i != 0 && j == 0) continue; if (n <= bef) { t = true; break; } ans += p[i][j] * (min(q[i][j], n) - bef); bef = q[i][j]; } if (t) break; } if (n == 1000000000000000) ans++; cout << ans << endl; }
28.571429
90
0.394
[ "vector" ]
41cb53c4635f3074de8d808b6c2f36a9ccdfc8da
3,930
hpp
C++
third-party/casadi/casadi/solvers/symbolic_qr.hpp
dbdxnuliba/mit-biomimetics_Cheetah
f3b0c0f6a3835d33b7f2f345f00640b3fc256388
[ "MIT" ]
8
2020-02-18T09:07:48.000Z
2021-12-25T05:40:02.000Z
third-party/casadi/casadi/solvers/symbolic_qr.hpp
geekfeiw/Cheetah-Software
f3b0c0f6a3835d33b7f2f345f00640b3fc256388
[ "MIT" ]
null
null
null
third-party/casadi/casadi/solvers/symbolic_qr.hpp
geekfeiw/Cheetah-Software
f3b0c0f6a3835d33b7f2f345f00640b3fc256388
[ "MIT" ]
13
2019-08-25T12:32:06.000Z
2022-03-31T02:38:12.000Z
/* * This file is part of CasADi. * * CasADi -- A symbolic framework for dynamic optimization. * Copyright (C) 2010-2014 Joel Andersson, Joris Gillis, Moritz Diehl, * K.U. Leuven. All rights reserved. * Copyright (C) 2011-2014 Greg Horn * * CasADi 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 3 of the License, or (at your option) any later version. * * CasADi 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 CasADi; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #ifndef CASADI_SYMBOLIC_QR_HPP #define CASADI_SYMBOLIC_QR_HPP #include "casadi/core/linsol_internal.hpp" #include <casadi/solvers/casadi_linsol_symbolicqr_export.h> /** \defgroup plugin_Linsol_symbolicqr Linsol based on QR factorization with sparsity pattern based reordering _without_ partial pivoting */ /** \pluginsection{Linsol,symbolicqr} */ /// \cond INTERNAL namespace casadi { typedef SX* SXPtr; typedef std::vector<SXPtr> SXPtrV; /** \brief Memory for SymbolicQR */ struct CASADI_LINSOL_SYMBOLICQR_EXPORT SymbolicQrMemory : public LinsolMemory { // Work vectors std::vector<const double*> arg; std::vector<double*> res; std::vector<casadi_int> iw; std::vector<double> w; // Allocate memory for a function void alloc(const Function& f); // Storage for QR factorization std::vector<double> q, r; }; /** \brief \pluginbrief{Linsol,symbolicqr} @copydoc Linsol_doc @copydoc plugin_Linsol_symbolicqr \author Joel Andersson \date 2013 */ class CASADI_LINSOL_SYMBOLICQR_EXPORT SymbolicQr : public LinsolInternal { public: // Constructor SymbolicQr(const std::string& name, const Sparsity& sp); // Destructor ~SymbolicQr() override; // Get name of the plugin const char* plugin_name() const override { return "symbolicqr";} // Name of the class std::string class_name() const override { return "SymbolicQr";} /** \brief Create a new Linsol */ static LinsolInternal* creator(const std::string& name, const Sparsity& sp) { return new SymbolicQr(name, sp); } ///@{ /** \brief Options */ static Options options_; const Options& get_options() const override { return options_;} ///@} // Initialize void init(const Dict& opts) override; /** \brief Create memory block */ void* alloc_mem() const override { return new SymbolicQrMemory();} /** \brief Initalize memory block */ int init_mem(void* mem) const override; /** \brief Free memory block */ void free_mem(void *mem) const override { delete static_cast<SymbolicQrMemory*>(mem);} // Factorize the linear system int nfact(void* mem, const double* A) const override; // Solve the linear system int solve(void* mem, const double* A, double* x, casadi_int nrhs, bool tr) const override; /** \brief Evaluate symbolically (SX) */ void linsol_eval_sx(const SXElem** arg, SXElem** res, casadi_int* iw, SXElem* w, void* mem, bool tr, casadi_int nrhs) const override; /// A documentation string static const std::string meta_doc; // Functions for factorization and (optionally transposed) solve Function factorize_, solve_, solveT_; // Generated function options Dict fopts_; }; } // namespace casadi /// \endcond #endif // CASADI_SYMBOLIC_QR_HPP
30.465116
95
0.681679
[ "vector" ]
41cc8ff5e1bdbd221c9981e135409f13cc47cb9d
5,862
cpp
C++
src/outputs/formatted_table.cpp
michaeljennings11/Athena_Thermal_Instability
7f647e8640e35ab3dce1273ec1bbc90bf4d8901b
[ "BSD-3-Clause" ]
null
null
null
src/outputs/formatted_table.cpp
michaeljennings11/Athena_Thermal_Instability
7f647e8640e35ab3dce1273ec1bbc90bf4d8901b
[ "BSD-3-Clause" ]
null
null
null
src/outputs/formatted_table.cpp
michaeljennings11/Athena_Thermal_Instability
7f647e8640e35ab3dce1273ec1bbc90bf4d8901b
[ "BSD-3-Clause" ]
null
null
null
//======================================================================================== // Athena++ astrophysical MHD code // Copyright(C) 2014 James M. Stone <jmstone@princeton.edu> and other code contributors // Licensed under the 3-clause BSD License, see LICENSE file for details //======================================================================================== //! \file formatted_table.cpp // \brief writes output data as a formatted table. Should not be used to output large // 3D data sets as this format is very slow and memory intensive. Most useful for 1D // slices and/or sums. Writes one file per Meshblock. // C headers #include <stdio.h> #include <stdlib.h> // C++ headers #include <iomanip> #include <iostream> #include <sstream> #include <stdexcept> #include <string> // Athena++ headers #include "../athena.hpp" #include "../coordinates/coordinates.hpp" #include "../mesh/mesh.hpp" #include "outputs.hpp" //---------------------------------------------------------------------------------------- // FormattedTableOutput constructor // destructor not required for this derived class FormattedTableOutput::FormattedTableOutput(OutputParameters oparams) : OutputType(oparams) { } //---------------------------------------------------------------------------------------- //! \fn void FormattedTableOutput:::WriteOutputFile(Mesh *pm) // \brief writes OutputData to file in tabular format using C style fprintf // Writes one file per MeshBlock void FormattedTableOutput::WriteOutputFile(Mesh *pm, ParameterInput *pin, bool flag) { MeshBlock *pmb=pm->pblock; // Loop over MeshBlocks while (pmb != NULL) { // set start/end array indices depending on whether ghost zones are included out_is=pmb->is; out_ie=pmb->ie; out_js=pmb->js; out_je=pmb->je; out_ks=pmb->ks; out_ke=pmb->ke; if (output_params.include_ghost_zones) { out_is -= NGHOST; out_ie += NGHOST; if (out_js != out_je) {out_js -= NGHOST; out_je += NGHOST;} if (out_ks != out_ke) {out_ks -= NGHOST; out_ke += NGHOST;} } // set ptrs to data in OutputData linked list, then slice/sum if needed LoadOutputData(pmb); if (TransformOutputData(pmb) == false) { ClearOutputData(); // required when LoadOutputData() is used. pmb=pmb->next; continue; } // skip if slice was out of range // create filename: "file_basename"+ "."+"blockid"+"."+"file_id"+"."+XXXXX+".tab", // where XXXXX = 5-digit file_number std::string fname; char number[6]; sprintf(number,"%05d",output_params.file_number); char blockid[12]; sprintf(blockid,"block%d",pmb->gid); fname.assign(output_params.file_basename); fname.append("."); fname.append(blockid); fname.append("."); fname.append(output_params.file_id); fname.append("."); fname.append(number); fname.append(".tab"); // open file for output FILE *pfile; std::stringstream msg; if ((pfile = fopen(fname.c_str(),"w")) == NULL) { msg << "### FATAL ERROR in function [FormattedTableOutput::WriteOutputFile]" <<std::endl<< "Output file '" <<fname<< "' could not be opened" <<std::endl; throw std::runtime_error(msg.str().c_str()); } // print file header fprintf(pfile,"# Athena++ data at time=%e",pm->time); fprintf(pfile," cycle=%d",pmb->pmy_mesh->ncycle); fprintf(pfile," variables=%s \n",output_params.variable.c_str()); // write x1, x2, x3 column headers fprintf(pfile,"#"); if (out_is != out_ie) fprintf(pfile,"i x1v "); if (out_js != out_je) fprintf(pfile,"j x2v "); if (out_ks != out_ke) fprintf(pfile,"k x3v "); // write data column headers from "name" stored in linked-list of OutputData's OutputData *pdata = pfirst_data_; while (pdata != NULL) { if (pdata->type == "VECTORS") { for (int index = 1; index <= 3; ++index) { fprintf(pfile, " %s%d ", pdata->name.c_str(), index); } } else { fprintf(pfile, " %s ", pdata->name.c_str()); } pdata = pdata->pnext; } fprintf(pfile,"\n"); // terminate line // loop over all cells in data arrays for (int k=out_ks; k<=out_ke; ++k) { for (int j=out_js; j<=out_je; ++j) { for (int i=out_is; i<=out_ie; ++i) { // write x1, x2, x3 indices and coordinates on start of new line if (out_is != out_ie) { fprintf(pfile,"%04d",i); fprintf(pfile,output_params.data_format.c_str(),pmb->pcoord->x1v(i)); } if (out_js != out_je) { fprintf(pfile," %04d",j); // note extra space for formatting fprintf(pfile,output_params.data_format.c_str(),pmb->pcoord->x2v(j)); } if (out_ks != out_ke) { fprintf(pfile," %04d",k); // note extra space for formatting fprintf(pfile,output_params.data_format.c_str(),pmb->pcoord->x3v(k)); } // step through linked-list of OutputData's and write each on same line OutputData *pdata = pfirst_data_; while (pdata != NULL) { for (int n=0; n<(pdata->data.GetDim4()); ++n) { fprintf(pfile, output_params.data_format.c_str(), pdata->data(n,k,j,i)); } pdata = pdata->pnext; } fprintf(pfile,"\n"); // terminate line }}} // don't forget to close the output file and clean up ptrs to data in OutputData fclose(pfile); ClearOutputData(); // required when LoadOutputData() is used. pmb=pmb->next; } // end loop over MeshBlocks // increment counters output_params.file_number++; output_params.next_time += output_params.dt; pin->SetInteger(output_params.block_name, "file_number", output_params.file_number); pin->SetReal(output_params.block_name, "next_time", output_params.next_time); return; }
36.185185
90
0.594848
[ "mesh", "3d" ]
41d0d122858d4c19f2e7ed8a9159cfb2076ec2f3
4,602
cpp
C++
lib/sensor_func.cpp
fdekruijff/Group-Project-TICT-V1GP-15
ec1de58bf3e5f22066f563e0014760e54d779159
[ "MIT" ]
null
null
null
lib/sensor_func.cpp
fdekruijff/Group-Project-TICT-V1GP-15
ec1de58bf3e5f22066f563e0014760e54d779159
[ "MIT" ]
null
null
null
lib/sensor_func.cpp
fdekruijff/Group-Project-TICT-V1GP-15
ec1de58bf3e5f22066f563e0014760e54d779159
[ "MIT" ]
null
null
null
#include "../Wall-E.h" vector<int16_t> get_contrast() { /// Returns the reflected black / white contrast. BP.get_sensor(s_contrast, contrast_struct); BP.get_sensor(s_color, color_struct); return {contrast_struct.reflected, color_struct.reflected_red}; } int16_t max_vector(vector<int16_t> const vec) { /// Returns the highest integer value of a vector. int16_t tmp = vec[0]; for (unsigned int i = 0; i < vec.size(); i++) { if (vec[i] > tmp) { tmp = vec[i]; } } return tmp; } int16_t min_vector(vector<int16_t> const vec) { /// Returns the lowest integer value of a vector. int16_t tmp = 10000; for (unsigned int i = 0; i < vec.size(); i++) { if (vec[i] < tmp && vec[i] != 0) { tmp = vec[i]; } } return tmp; } void measure_contrast() { /// Thread function that reads sensor values and calculates maximum and minimum from local vector. vector<int16_t> _tmp; // Sensor 1 vector<int16_t> __tmp; // Sensor 2 while (calibrating) { vector<int16_t> c = get_contrast(); _tmp.push_back(c[0]); __tmp.push_back(c[1]); usleep(12500); } high_reflection = max_vector(_tmp); low_reflection = min_vector(_tmp); red_high_reflection = min_vector(__tmp); red_low_reflection = max_vector(__tmp); } void calibrate() { /// Function reads sensor values while driving over the tape. Sets maximum, minimum and set point for PID. calibrating = true; thread measure(measure_contrast); int turn = 180; vector<vector<int>> power_profile = { {turn, -turn}, {-turn, turn}, {-turn, turn}, {turn, -turn}}; motor_power_limit(40, 0); for (int i = 0; i < power_profile.size(); i++) { BP.set_motor_position_relative(m_right, power_profile[i][0]); BP.set_motor_position_relative(m_left, power_profile[i][1]); usleep(650000); } calibrating = false; stop_driving(); motor_power_limit(100, 0); measure.join(); brain.set_point = (high_reflection + low_reflection) / 2; brain.color_set_point = (red_high_reflection + red_low_reflection) / 2; cout << "Calibration finished." << endl << "high:" << int(high_reflection) << " low:" << int(low_reflection) << " set:" << brain.set_point << endl; cout << "r_high:" << int(red_high_reflection) << " r_low:" << int(red_low_reflection) << " r_set:" << brain.color_set_point << endl; } bool is_black() { /// Is sensor value in the black domain? float sensor = get_contrast()[0]; return sensor > (brain.set_point - 100); } bool color_is_black() { /// Is color sensor value in the black domain? float sensor = get_contrast()[1]; return sensor < (brain.color_set_point - 50); } bool intersection() { /// Detects intersections. return is_black() && color_is_black(); } int16_t line_val() { /// Returns the reflected black / white contrast. BP.get_sensor(s_contrast, contrast_struct); return contrast_struct.reflected; } int no_object() { /// Keeps on driving till there is no object. // TODO: make sure the boolean logic works here bool to_object = false; bool object = false; bool end_of_object = false; while (!to_object) { if (!object and !end_of_object) { dodge(true, 0, 1); if (sonic_struct.cm < 20) { object = true; } } if (object and !end_of_object) { dodge(true, 0, 1); if (sonic_struct.cm > 30) { end_of_object = true; } } if (object and end_of_object) { dodge(true, 0, 20); to_object = true; } } } void scan_ultrasonic() { /// Returns ultrasonic value // TODO: maybe refactor this code. while (!brain.exit) { BP.get_sensor(s_ultrasonic, sonic_struct); cout << "d:" << sonic_struct.cm << endl; usleep(200000); } } void object_in_the_way() { /// If a object is in the way of the PID it stops the PID. sleep(1); //TODO: this is bad practice while (!brain.exit) { if (sonic_struct.cm < brain.limited_distance && sonic_struct.cm != 0) { brain.driving_mode = STOP; thread x (around_object); find_line(); if (x.joinable()) x.join(); } } }
30.885906
114
0.573446
[ "object", "vector" ]
41d15cd92a90658d2740f4dd9f3d9776b7d5c13e
2,157
hpp
C++
SDLbase/texture_handler.hpp
paracelso93/HexGame
0c8e51084f5ec92514a6c3d92c151812ee13a4ea
[ "Apache-2.0" ]
null
null
null
SDLbase/texture_handler.hpp
paracelso93/HexGame
0c8e51084f5ec92514a6c3d92c151812ee13a4ea
[ "Apache-2.0" ]
null
null
null
SDLbase/texture_handler.hpp
paracelso93/HexGame
0c8e51084f5ec92514a6c3d92c151812ee13a4ea
[ "Apache-2.0" ]
null
null
null
#ifndef ROGUELIKE_TEXTURE_HANDLER_H #define ROGUELIKE_TEXTURE_HANDLER_H #include <unordered_map> #include <string> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include "vectors.hpp" #include "color.hpp" #include "helper.hpp" #include "../camera.hpp" #define texture_t unsigned int struct Texture { texture_t id; Vector2<float> position; Vector2<float> size; Texture(const std::string& file, SDL_Renderer* renderer); explicit Texture(texture_t texture); void render(SDL_Renderer* renderer, const Vector2<float>& pos, Color color = Color(255, 255, 255), const Vector2<float>& scale = Vector2<float>(1.0f, 1.0f), float rotation = 0, const Vector2<float>& center = Vector2<float>(), SDL_RendererFlip flip = SDL_FLIP_NONE); void set_src_size(int x, int y); void set_src_position(int x, int y); Texture(const Texture& other) { this->id = other.id; this->position = other.position; this->size = other.size; } }; class TextureHandler { public: static TextureHandler* getInstance() { if (mInstance == nullptr) { mInstance = new TextureHandler(); return mInstance; } return mInstance; } bool add_texture(const std::string& filePath, texture_t& id, SDL_Renderer* renderer); SDL_Texture* get_texture(texture_t id); void render(SDL_Renderer* renderer, texture_t id, const Vector2<float>& position, Color color = Color(255, 255, 255), const Vector2<float>& scale = Vector2<float>(1.0f, 1.0f), float rotation = 0, const Vector2<float>& center = Vector2<float>(), SDL_RendererFlip flip = SDL_FLIP_NONE); void set_src_rect(texture_t id, const Vector2<float>& src); void set_src_position(texture_t id, const Vector2<float>& src); Vector2<float> get_src_rect(texture_t id) { return mSizes[id]; } Vector2<float> get_src_position(texture_t id) { return mPositions[id]; } void apply_offset(Camera* camera); private: static TextureHandler* mInstance; Vector2<float> offset; std::unordered_map<texture_t, Vector2<float> > mSizes; std::unordered_map<texture_t, Vector2<float> > mPositions; std::unordered_map<texture_t, SDL_Texture*> mTextures; }; #endif
35.95
286
0.721836
[ "render" ]
41d37cb800f69310a00617cb136212aafa561c46
14,729
cpp
C++
shopwindow.cpp
Ricecrackie/Fantasy-Battle
058dc323101d405e222e9c8f135500044ce6e180
[ "Apache-2.0" ]
null
null
null
shopwindow.cpp
Ricecrackie/Fantasy-Battle
058dc323101d405e222e9c8f135500044ce6e180
[ "Apache-2.0" ]
null
null
null
shopwindow.cpp
Ricecrackie/Fantasy-Battle
058dc323101d405e222e9c8f135500044ce6e180
[ "Apache-2.0" ]
null
null
null
#include "shopwindow.h" #include "ui_shopwindow.h" #include "floorwindow.h" #include "Tower.h" #include <QString> #include <QFileDialog> int HPpotion_price = 50; int MPpotion_price = 50; int LeatherArmor_price = 250; int IronArmor_price = 500; int DiamondArmor_price = 1000; int RecoverHPMP_price = 100; extern int EXPforLevel2; extern int EXPforLevel3; extern int EXPforLevel4; extern int EXPforLevel5; int HPpotion_worth = HPpotion_price/2; int MPpotion_worth = MPpotion_price/2; int LeatherArmor_worth = LeatherArmor_price/2; int IronArmor_worth = IronArmor_price/2; int DiamondArmor_worth = DiamondArmor_price/2; // call constructor to create a ShopWindow Object by passing the Tower object to the constructor ShopWindow::ShopWindow(Tower* tower, QWidget *parent) : QMainWindow(parent), ui(new Ui::ShopWindow), tower(tower) { ui->setupUi(this); setWindowFlags(Qt::Window | Qt::MSWindowsFixedSizeDialogHint); this->statusBar()->setSizeGripEnabled(false); QPixmap bkgnd(":/resources/images/shopbackground.png"); bkgnd = bkgnd.scaled(this->size(), Qt::IgnoreAspectRatio); QPalette palette; palette.setBrush(QPalette::Background, bkgnd); this->setPalette(palette); this->setWindowTitle("Shop"); playlist = new QMediaPlaylist(); playlist->addMedia(QUrl("qrc:/resources/sounds/shop.mp3")); playlist->setPlaybackMode(QMediaPlaylist::Loop); player = new QMediaPlayer(); player->setPlaylist(playlist); player->play(); click = new QMediaPlayer(); click->setMedia(QUrl("qrc:/resources/sounds/click.mp3")); ui->select->setStyleSheet("QPushButton{image: url(:/resources/images/Select.png); background-color: transparent}" "QPushButton::hover{image: url(:/resources/images/Select_hover.png); background-color: transparent}"); ui->back->setStyleSheet("QPushButton{image: url(:/resources/images/Back.png); background-color: transparent}" "QPushButton::hover{image: url(:/resources/images/Back_hover.png); background-color: transparent}"); ui->next_floor->setStyleSheet("QPushButton{image: url(:/resources/images/Next Floor.png); background-color: transparent}" "QPushButton::hover{image: url(:/resources/images/Next Floor_hover.png); background-color: transparent}"); ui->next_floor_page->hide(); choice = -2; selling = 0; ui->dialog->setText("Welcome to the Adventurer's Shop! Feel free to purchase anything you need!"); ui->shoplist->clear(); ui->shoplist->addItem("Buy a HP potion ($" + QString::number(HPpotion_price) + ")"); ui->shoplist->addItem("Buy a MP potion ($" + QString::number(MPpotion_price) + ")"); ui->shoplist->addItem("Buy a Leather Armor ($" + QString::number(LeatherArmor_price) + ")"); ui->shoplist->addItem("Buy a Iron Armor ($" + QString::number(IronArmor_price) + ")"); ui->shoplist->addItem("Buy a Diamond Armor ($" + QString::number(DiamondArmor_price) + ")"); ui->shoplist->addItem("Recover all HP and MP ($" + QString::number(RecoverHPMP_price) + ")"); ui->shoplist->addItem("Sell items"); ui->shoplist->addItem("Leave the shop"); refresh(); } // destructor of ShopWindow Object, deallocates the memory of the ui and music ShopWindow::~ShopWindow() { delete ui; delete player; delete playlist; delete click; } // refreshes the statuses of the player after selecting an action on the shop list void ShopWindow::refresh() { std::string temp; ui->PlayerName->setText(QString::fromStdString(tower->player->get_name())); ui->PlayerLevel->setText(QString::number(tower->player->get_level())); ui->PlayerEXPBar->setAlignment(Qt::AlignCenter); ui->PlayerEXPBar->setMinimum(0); switch(tower->player->get_level()) { case 1: temp = std::to_string(tower->player->EXP) + "/" + std::to_string(EXPforLevel2); ui->PlayerEXPBar->setFormat(QString::fromStdString(temp)); ui->PlayerEXPBar->setMaximum(EXPforLevel2); break; case 2: temp = std::to_string(tower->player->EXP) + "/" + std::to_string(EXPforLevel3); ui->PlayerEXPBar->setFormat(QString::fromStdString(temp)); ui->PlayerEXPBar->setMaximum(EXPforLevel3); break; case 3: temp = std::to_string(tower->player->EXP) + "/" + std::to_string(EXPforLevel4); ui->PlayerEXPBar->setFormat(QString::fromStdString(temp)); ui->PlayerEXPBar->setMaximum(EXPforLevel4); break; case 4: temp = std::to_string(tower->player->EXP) + "/" + std::to_string(EXPforLevel5); ui->PlayerEXPBar->setFormat(QString::fromStdString(temp)); ui->PlayerEXPBar->setMaximum(EXPforLevel5); break; case 5: ui->PlayerEXPBar->setFormat("MAX"); ui->PlayerEXPBar->setMaximum(300); break; } ui->PlayerEXPBar->setValue(tower->player->EXP); ui->PlayerFunds->setText(QString::number(tower->player->money)); ui->PlayerHPBar->setAlignment(Qt::AlignCenter); ui->PlayerHPBar->setMinimum(0); ui->PlayerHPBar->setMaximum(tower->player->get_HP_max()); ui->PlayerHPBar->setValue(tower->player->HP); temp = std::to_string(tower->player->HP) + "/" + std::to_string(tower->player->get_HP_max()); ui->PlayerHPBar->setFormat(QString::fromStdString(temp)); ui->PlayerMPBar->setAlignment(Qt::AlignCenter); ui->PlayerMPBar->setMinimum(0); ui->PlayerMPBar->setMaximum(tower->player->get_MP_max()); ui->PlayerMPBar->setValue(tower->player->MP); temp = std::to_string(tower->player->MP) + "/" + std::to_string(tower->player->get_MP_max()); ui->PlayerMPBar->setFormat(QString::fromStdString(temp)); ui->PlayerAPBar->setAlignment(Qt::AlignCenter); ui->PlayerAPBar->setMinimum(0); ui->PlayerAPBar->setMaximum(tower->player->get_AP_max()); ui->PlayerAPBar->setValue(tower->player->AP); temp = std::to_string(tower->player->AP) + "/" + std::to_string(tower->player->get_AP_max()); ui->PlayerAPBar->setFormat(QString::fromStdString(temp)); ui->PlayerATK->setText(QString::number(tower->player->ATK)); ui->PlayerDEF->setText(QString::number(tower->player->DEF)); } // closes the shop and creates a FloorWindow Object to allow the player to progress void ShopWindow::on_next_floor_clicked() { click->play(); player->stop(); FloorWindow *b = new FloorWindow{tower, nullptr}; b->setAttribute(Qt::WA_DeleteOnClose); b->show(); close(); } // the row selected on the shop list by the user is saved to choice void ShopWindow::on_shoplist_currentRowChanged(int currentRow) { choice = currentRow; } // runs the option chosen by the player void ShopWindow::on_select_clicked() { if (selling == 0) { Item* purchase; switch(static_cast<ShopWindow::ShopOption>(choice+2)) { case ShopOption::VIEW_INFO: click->play(); ui->dialog->setText(QString::fromStdString(tower->player->info())); refresh(); break; case ShopOption::HP_POTION: click->play(); if (tower->player->money < HPpotion_price) { ui->dialog->setText("Sorry! You do not have enough budget."); refresh(); break; } else { purchase = new HPpotion; tower->player->add_item_to_inventory(purchase); tower->player->money -= HPpotion_price; refresh(); ui->dialog->setText("Thank you for your purchase!"); break; } case ShopOption::MP_POTION: click->play(); if (tower->player->money < MPpotion_price) { ui->dialog->setText("Sorry! You do not have enough budget."); refresh(); break; } else { purchase = new MPpotion; tower->player->add_item_to_inventory(purchase); tower->player->money -= MPpotion_price; refresh(); ui->dialog->setText("Thank you for your purchase!"); break; } case ShopOption::LEATHER_ARMOR: click->play(); if (tower->player->money < LeatherArmor_price) { ui->dialog->setText("Sorry! You do not have enough budget."); refresh(); break; } else { purchase = new LeatherArmor; tower->player->add_item_to_inventory(purchase); tower->player->money -= LeatherArmor_price; refresh(); ui->dialog->setText("Thank you for your purchase!"); break; } case ShopOption::IRON_ARMOR: click->play(); if (tower->player->money < IronArmor_price) { ui->dialog->setText("Sorry! You do not have enough budget."); refresh(); break; } else { purchase = new IronArmor; tower->player->add_item_to_inventory(purchase); tower->player->money -= IronArmor_price; refresh(); ui->dialog->setText("Thank you for your purchase!"); break; } case ShopOption::DIAMOND_ARMOR: click->play(); if (tower->player->money < DiamondArmor_price) { ui->dialog->setText("Sorry! You do not have enough budget."); refresh(); break; } else { purchase = new DiamondArmor; tower->player->add_item_to_inventory(purchase); tower->player->money -= DiamondArmor_price; refresh(); ui->dialog->setText("Thank you for your purchase!"); break; } case ShopOption::RECOVER: click->play(); if (tower->player->money < RecoverHPMP_price) { ui->dialog->setText("Sorry! You do not have enough budget."); refresh(); break; } else { tower->player->HP = tower->player->get_HP_max(); tower->player->MP = tower->player->get_MP_max(); tower->player->money -= RecoverHPMP_price; refresh(); ui->dialog->setText("HP and MP fully recovered."); break; } case ShopOption::SELL: click->play(); selling = 1; sell_items(); break; case ShopOption::LEAVE: click->play(); ui->dialog->setText("Thank you for visiting!"); ui->next_floor_page->show(); } } else if (selling == 1) { int index = choice; if (index == -1) return; Item* item = tower->player->get_inventory()[index]; switch (item->get_item_type()) { case Item::item_type::HP_POTION: tower->player->money += HPpotion_worth; break; case Item::item_type::MP_POTION: tower->player->money += MPpotion_worth; break; case Item::item_type::LEATHER_ARMOR: tower->player->money += LeatherArmor_worth; break; case Item::item_type::IRON_ARMOR: tower->player->money += IronArmor_worth; break; case Item::item_type::DIAMOND_ARMOR: tower->player->money += DiamondArmor_worth; break; } click->play(); tower->player->remove_item(item); refresh(); sell_items(); ui->dialog->setText("Pleasure doing business with you!"); } } // lists out the player's inventory for the player to choose void ShopWindow::sell_items() const { ui->dialog->setText("Please select an item to sell."); ui->shoplist->clear(); QString temp; for (int i = 0; i < (int)(tower->player->get_inventory().size()); ++i) { if (tower->player->get_inventory()[i]->get_item_type() == Item::item_type::HP_POTION) { temp = "($" + QString::number(HPpotion_worth) + ")"; } else if (tower->player->get_inventory()[i]->get_item_type() == Item::item_type::MP_POTION) { temp = "($" + QString::number(MPpotion_worth) + ")"; } else if (tower->player->get_inventory()[i]->get_item_type() == Item::item_type::LEATHER_ARMOR) { temp = "($" + QString::number(LeatherArmor_worth) + ")"; } else if (tower->player->get_inventory()[i]->get_item_type() == Item::item_type::IRON_ARMOR) { temp = "($" + QString::number(IronArmor_worth) + ")"; } else if (tower->player->get_inventory()[i]->get_item_type() == Item::item_type::DIAMOND_ARMOR) { temp = "($" + QString::number(DiamondArmor_worth) + ")"; } ui->shoplist->addItem(QString::fromStdString(tower->player->get_inventory()[i]->get_item_name()) + "\t" + temp); } } // the choices for the shop returns to the main list from the selling list void ShopWindow::on_back_clicked() { click->play(); choice = -2; selling = 0; ui->dialog->setText("Welcome to the Adventurer's Shop! Feel free to purchase anything you need!"); ui->shoplist->clear(); ui->shoplist->addItem("Buy a HP potion ($" + QString::number(HPpotion_price) + ")"); ui->shoplist->addItem("Buy a MP potion ($" + QString::number(MPpotion_price) + ")"); ui->shoplist->addItem("Buy a Leather Armor ($" + QString::number(LeatherArmor_price) + ")"); ui->shoplist->addItem("Buy a Iron Armor ($" + QString::number(IronArmor_price) + ")"); ui->shoplist->addItem("Buy a Diamond Armor ($" + QString::number(DiamondArmor_price) + ")"); ui->shoplist->addItem("Recover all HP and MP ($" + QString::number(RecoverHPMP_price) + ")"); ui->shoplist->addItem("Sell items"); ui->shoplist->addItem("Leave the shop"); refresh(); }
41.027855
139
0.573494
[ "object" ]
41d8be03e513a90bfcc89947068bef0e2be52370
2,259
cc
C++
cpp/util/strings.cc
propaganda-gold/deeprev
0c6ccf83131a879ed858acdb0675e75ebf2f2d3d
[ "BSD-3-Clause" ]
null
null
null
cpp/util/strings.cc
propaganda-gold/deeprev
0c6ccf83131a879ed858acdb0675e75ebf2f2d3d
[ "BSD-3-Clause" ]
2
2021-05-11T16:29:38.000Z
2022-01-22T12:28:49.000Z
cpp/util/strings.cc
propaganda-gold/deeprev
0c6ccf83131a879ed858acdb0675e75ebf2f2d3d
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <random> #include <sstream> #include <string> #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/strings/str_replace.h" #include "absl/strings/str_split.h" #include "absl/strings/substitute.h" #include "util/logging.h" #include "util/strings.h" namespace vectorbook { string Trim(const string &original) { return string(absl::StripAsciiWhitespace(original)); } vector<string> Split(const string &original, char c) { return absl::StrSplit(original, c); // vector<string> buffer; return buffer; } vector<string> Split(const string &original, const string &c) { return absl::StrSplit(original, c); // vector<string> buffer; return buffer; } bool StartsWith(const string &haystack, const string &needle) { return absl::StartsWith(haystack, needle); } bool EndsWith(const string &haystack, const string &needle) { return absl::EndsWith(haystack, needle); } bool Contains(const string &haystack, const string &needle) { return haystack.find(needle) != std::string::npos; } string Replace(const string &original, const unordered_map<string, string> &mapping) { return absl::StrReplaceAll(original, mapping); } string Replace(const string &original, const StringPairs &mapping) { return absl::StrReplaceAll(original, mapping); } std::string SubString(const std::string &base, int start, int end) { std::string buffer; for (unsigned int i = start; i < end; ++i) { if (i >= 0 && i < base.size()) { buffer += base[i]; } } return buffer; } bool Empty(const string &original) { return original.empty(); } bool NonEmpty(const string &original) { return !original.empty(); } std::string StrReplaceAll2( const string &s, std::initializer_list<std::pair<std::string, std::string>> replacements) { return absl::StrReplaceAll(s, replacements); } vector<string> Split(const string &input) { std::istringstream buffer(input); std::vector<std::string> ret((std::istream_iterator<std::string>(buffer)), std::istream_iterator<std::string>()); return ret; } vector<string> StrSplit(const string &input) { return Split(input); } } // namespace vectorbook
28.2375
86
0.707393
[ "vector" ]
41dccf57a998c55543b358e6b6527854645a5424
1,135
hpp
C++
src/database/engine.hpp
norayr/biboumi
805671032d25ee6ce09ed75e8a385c04e9563cdd
[ "Zlib" ]
68
2015-01-29T21:07:37.000Z
2022-03-20T14:48:07.000Z
src/database/engine.hpp
norayr/biboumi
805671032d25ee6ce09ed75e8a385c04e9563cdd
[ "Zlib" ]
5
2016-10-24T18:34:30.000Z
2021-08-31T13:30:37.000Z
src/database/engine.hpp
norayr/biboumi
805671032d25ee6ce09ed75e8a385c04e9563cdd
[ "Zlib" ]
13
2015-12-11T15:19:05.000Z
2021-08-31T13:24:35.000Z
#pragma once /** * Interface to provide non-portable behaviour, specific to each * database engine we want to support. * * Everything else (all portable stuf) should go outside of this class. */ #include <database/statement.hpp> #include <memory> #include <string> #include <vector> #include <tuple> #include <set> class DatabaseEngine { public: DatabaseEngine() = default; virtual ~DatabaseEngine() = default; DatabaseEngine(const DatabaseEngine&) = delete; DatabaseEngine& operator=(const DatabaseEngine&) = delete; DatabaseEngine(DatabaseEngine&&) = delete; DatabaseEngine& operator=(DatabaseEngine&&) = delete; virtual std::set<std::string> get_all_columns_from_table(const std::string& table_name) = 0; virtual std::tuple<bool, std::string> raw_exec(const std::string& query) = 0; virtual std::unique_ptr<Statement> prepare(const std::string& query) = 0; virtual void extract_last_insert_rowid(Statement& statement) = 0; virtual std::string get_returning_id_sql_string(const std::string&) { return {}; } virtual std::string id_column_type() = 0; int64_t last_inserted_rowid{-1}; };
27.02381
94
0.732159
[ "vector" ]
41ea4e5ef39cf467de796ca7ebc67714fa2c2f94
1,711
cpp
C++
Scott/src/Scott/Application.cpp
scottvermast/Scott
723f07e54bacc96b20668babf31f54dc513c3c22
[ "Apache-2.0" ]
null
null
null
Scott/src/Scott/Application.cpp
scottvermast/Scott
723f07e54bacc96b20668babf31f54dc513c3c22
[ "Apache-2.0" ]
null
null
null
Scott/src/Scott/Application.cpp
scottvermast/Scott
723f07e54bacc96b20668babf31f54dc513c3c22
[ "Apache-2.0" ]
null
null
null
#include "scpch.h" #include "Application.h" #include "Scott/Log.h" #include "Input.h" #include "InputDefinitions.h" #include "GameTime.h" #include "Scott/SceneGraph/SceneManager.h" #include "Scott/Renderer.h" namespace Scott { Application* Application::s_Instance = nullptr; Application::Application() { SceneManager& sceneManager = SceneManager::GetInstance(); Renderer& renderer = Renderer::GetInstance(); SC_CORE_ASSERT(!s_Instance, "Application already excists!"); s_Instance = this; m_pWindow = std::unique_ptr<Window>(Window::Create()); renderer.Initialize(); m_ImGuiLayer = new ImGuiLayer(); PushOverlay(m_ImGuiLayer); } Application::~Application() { } void Application::PushLayer(Layer* layer) { m_LayerStack.PushLayer(layer); layer->OnAttach(); } void Application::PushOverlay(Layer* layer) { m_LayerStack.PushOverlay(layer); layer->OnAttach(); } void Application::Run() { GameTime& gameTime = GameTime::GetInstance(); SceneManager& sceneManager = SceneManager::GetInstance(); Renderer& renderer = Renderer::GetInstance(); while (!Input::Quit()) { gameTime.Update(); m_pWindow->OnUpdate(); for (Layer* layer : m_LayerStack) { layer->OnUpdate(); } sceneManager.Update(); // --------------------------- Rendering -------------------------------- // m_ImGuiLayer->Begin(); for (Layer* layer : m_LayerStack) layer->OnImGuiRender(); renderer.ClearBuffer(); sceneManager.Render(); m_ImGuiLayer->End(); for (Layer* layer : m_LayerStack) { layer->Render(); } renderer.Render(); // --------------------------------------------------------------------- // } } }
19.224719
79
0.62069
[ "render" ]
41f415d754a411a727afe7fe9429b54db6e6c138
3,137
cpp
C++
src/interconnect/Scan.cpp
BuildJet/sharkbite
a8355be6e4879ea7648ea045537d6720538b00b8
[ "Apache-2.0" ]
30
2017-01-23T10:42:29.000Z
2022-02-04T18:06:08.000Z
src/interconnect/Scan.cpp
BuildJet/sharkbite
a8355be6e4879ea7648ea045537d6720538b00b8
[ "Apache-2.0" ]
55
2017-01-29T13:15:52.000Z
2022-02-05T17:49:51.000Z
src/interconnect/Scan.cpp
BuildJet/sharkbite
a8355be6e4879ea7648ea045537d6720538b00b8
[ "Apache-2.0" ]
5
2017-01-23T10:42:34.000Z
2021-09-07T19:11:00.000Z
/* * 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 "interconnect/Scan.h" #include <arpa/inet.h> #include <sys/socket.h> #include "interconnect/ClientInterface.h" namespace interconnect { Scan::Scan(std::atomic<bool> *isRunning) : topKey(0), isMulti(false), isRFile(false) { srand(time(NULL)); scanId = rand(); this->isRunning = isRunning; hasMore = false; } Scan::~Scan() {} void Scan::setException(std::string exc) { clientException = std::move(exc); } std::string Scan::getException() const { return clientException; } bool Scan::hasException() const { return !clientException.empty(); } /** * Sets the next result set. * @param resultSet result set to add to this object's results * @returns result of adding. **/ bool Scan::setNextResults( std::vector<std::shared_ptr<cclient::data::KeyValue> > *resultSet) { results.insert(results.end(), resultSet->begin(), resultSet->end()); if (!resultSet->empty()) topKey = resultSet->back()->getKey(); return true; } bool Scan::isClientRunning() { return isRunning->load(); } void Scan::setMultiIterator( std::shared_ptr<cclient::data::streams::KeyValueIterator> &itr) { iter = itr; } std::shared_ptr<cclient::data::streams::KeyValueIterator> Scan::getMultiIterator() { return iter; } /** * Gets the next result and places it into resultSet * @param reference result set to add. **/ bool Scan::getNextResults( std::vector<std::shared_ptr<cclient::data::KeyValue> > *resultSet) { resultSet->insert(resultSet->end(), results.begin(), results.end()); results.clear(); return hasMore; } /** * Set flag to identify that more results are available. * @param more more results **/ void Scan::setHasMore(bool more) { hasMore = more; } /** * Gets variable to identify if more results are available * @returns whether or not there are more results. **/ bool Scan::getHasMore() const { return hasMore; } /** * Returns the scan id * @returns scan id. **/ int64_t Scan::getId() const { return scanId; } bool Scan::empty() const { return results.empty(); } void Scan::setMultiScan(bool isMulti) { this->isMulti = isMulti; } bool Scan::isMultiScan() const { return isMulti; } void Scan::setRFileScan(bool isRFile) { this->isRFile = isRFile; } bool Scan::isRFileScan() const { return isRFile; } /** * Sets the scan id * @param scanId scan identifier **/ void Scan::setScanId(int64_t scanId) { this->scanId = scanId; } void Scan::setTopKey(std::shared_ptr<cclient::data::Key> key) { topKey = key; } std::shared_ptr<cclient::data::Key> Scan::getTopKey() const { return topKey; } } // namespace interconnect
27.761062
79
0.701307
[ "object", "vector" ]
41f4d66ca9c5f1d7bfc5eaac8da8bceb36dc7ba6
2,493
cpp
C++
DbgHelpUtils/unloaded_module_list_stream.cpp
shanepowell/DbgHelpUtils
5a903fd9f32db3aad5ac9b9488e8c4ec604712a8
[ "MIT" ]
null
null
null
DbgHelpUtils/unloaded_module_list_stream.cpp
shanepowell/DbgHelpUtils
5a903fd9f32db3aad5ac9b9488e8c4ec604712a8
[ "MIT" ]
null
null
null
DbgHelpUtils/unloaded_module_list_stream.cpp
shanepowell/DbgHelpUtils
5a903fd9f32db3aad5ac9b9488e8c4ec604712a8
[ "MIT" ]
null
null
null
#include "unloaded_module_list_stream.h" #include "mini_dump.h" #include "module_match.h" namespace dlg_help_utils { unloaded_module_list_stream::unloaded_module_list_stream(mini_dump const& dump, size_t index) : dump_{dump} , module_list_{get_unloaded_module_list(dump, index)} , index_{index} , found_{module_list_ != nullptr} , is_valid_{found_ && module_list_->SizeOfHeader == sizeof(MINIDUMP_UNLOADED_MODULE_LIST) && module_list_->SizeOfEntry == sizeof(MINIDUMP_UNLOADED_MODULE)} { } stream_unloaded_module const* unloaded_module_list_stream::find_module(uint64_t const address) const { if (!is_valid()) return nullptr; for (auto const& module : list()) { if (module->BaseOfImage >= address && address < module->BaseOfImage + module->SizeOfImage) { return &module; } } return nullptr; } stream_unloaded_module const* unloaded_module_list_stream::find_module(std::wstring_view const& module_name) const { if (!is_valid()) return nullptr; for (auto const& module : list()) { if (module_match::module_name_match(module, module_name)) { return &module; } } return nullptr; } MINIDUMP_UNLOADED_MODULE_LIST const* unloaded_module_list_stream::get_unloaded_module_list(mini_dump const& dump, size_t& index) { auto const* entry = dump.find_stream_type(UnloadedModuleListStream, index); if (entry == nullptr) { return nullptr; } return static_cast<MINIDUMP_UNLOADED_MODULE_LIST const*>(dump.rva32(entry->Location)); } MINIDUMP_UNLOADED_MODULE const* unloaded_module_list_stream::get_unloaded_module() const { if (!is_valid_) { return nullptr; } return reinterpret_cast<MINIDUMP_UNLOADED_MODULE const*>(reinterpret_cast<uint8_t const*>(module_list_) + sizeof(MINIDUMP_UNLOADED_MODULE_LIST)); } std::vector<stream_unloaded_module> unloaded_module_list_stream::build_modules() const { std::vector<stream_unloaded_module> rv; if (!is_valid()) return rv; rv.reserve(module_list_->NumberOfEntries); for (size_t index = 0; index < module_list_->NumberOfEntries; ++index) { rv.emplace_back(dump_, list_[index]); } return rv; } }
30.402439
163
0.641797
[ "vector" ]
41faaed6f68c029ae3af448a675816ea3a519e43
168,143
cpp
C++
solvers/PumaBarrett_arm_nogripper.cpp
Stonelinks/js-iksolvers
e911d6e24b6e4a4f2c61753a1a0d1721f8560ff2
[ "MIT" ]
null
null
null
solvers/PumaBarrett_arm_nogripper.cpp
Stonelinks/js-iksolvers
e911d6e24b6e4a4f2c61753a1a0d1721f8560ff2
[ "MIT" ]
null
null
null
solvers/PumaBarrett_arm_nogripper.cpp
Stonelinks/js-iksolvers
e911d6e24b6e4a4f2c61753a1a0d1721f8560ff2
[ "MIT" ]
1
2020-09-21T13:02:41.000Z
2020-09-21T13:02:41.000Z
/// autogenerated analytical inverse kinematics code from ikfast program part of OpenRAVE /// \author Rosen Diankov /// /// 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. /// /// ikfast version 0x10000048 generated on 2015-05-22 07:12:04.602377 /// To compile with gcc: /// gcc -lstdc++ ik.cpp /// To compile without any main function as a shared object (might need -llapack): /// gcc -fPIC -lstdc++ -DIKFAST_NO_MAIN -DIKFAST_CLIBRARY -shared -Wl,-soname,libik.so -o libik.so ik.cpp #define IKFAST_HAS_LIBRARY #include "ikfast.h" // found inside share/openrave-X.Y/python/ikfast.h using namespace ikfast; // check if the included ikfast version matches what this file was compiled with #define IKFAST_COMPILE_ASSERT(x) extern int __dummy[(int)x] IKFAST_COMPILE_ASSERT(IKFAST_VERSION==0x10000048); #include <cmath> #include <vector> #include <limits> #include <algorithm> #include <complex> #ifndef IKFAST_ASSERT #include <stdexcept> #include <sstream> #include <iostream> #ifdef _MSC_VER #ifndef __PRETTY_FUNCTION__ #define __PRETTY_FUNCTION__ __FUNCDNAME__ #endif #endif #ifndef __PRETTY_FUNCTION__ #define __PRETTY_FUNCTION__ __func__ #endif #define IKFAST_ASSERT(b) { if( !(b) ) { std::stringstream ss; ss << "ikfast exception: " << __FILE__ << ":" << __LINE__ << ": " <<__PRETTY_FUNCTION__ << ": Assertion '" << #b << "' failed"; throw std::runtime_error(ss.str()); } } #endif #if defined(_MSC_VER) #define IKFAST_ALIGNED16(x) __declspec(align(16)) x #else #define IKFAST_ALIGNED16(x) x __attribute((aligned(16))) #endif #define IK2PI ((IkReal)6.28318530717959) #define IKPI ((IkReal)3.14159265358979) #define IKPI_2 ((IkReal)1.57079632679490) #ifdef _MSC_VER #ifndef isnan #define isnan _isnan #endif #ifndef isinf #define isinf _isinf #endif //#ifndef isfinite //#define isfinite _isfinite //#endif #endif // _MSC_VER // lapack routines extern "C" { void dgetrf_ (const int* m, const int* n, double* a, const int* lda, int* ipiv, int* info); void zgetrf_ (const int* m, const int* n, std::complex<double>* a, const int* lda, int* ipiv, int* info); void dgetri_(const int* n, const double* a, const int* lda, int* ipiv, double* work, const int* lwork, int* info); void dgesv_ (const int* n, const int* nrhs, double* a, const int* lda, int* ipiv, double* b, const int* ldb, int* info); void dgetrs_(const char *trans, const int *n, const int *nrhs, double *a, const int *lda, int *ipiv, double *b, const int *ldb, int *info); void dgeev_(const char *jobvl, const char *jobvr, const int *n, double *a, const int *lda, double *wr, double *wi,double *vl, const int *ldvl, double *vr, const int *ldvr, double *work, const int *lwork, int *info); } using namespace std; // necessary to get std math routines #ifdef IKFAST_NAMESPACE namespace IKFAST_NAMESPACE { #endif inline float IKabs(float f) { return fabsf(f); } inline double IKabs(double f) { return fabs(f); } inline float IKsqr(float f) { return f*f; } inline double IKsqr(double f) { return f*f; } inline float IKlog(float f) { return logf(f); } inline double IKlog(double f) { return log(f); } // allows asin and acos to exceed 1 #ifndef IKFAST_SINCOS_THRESH #define IKFAST_SINCOS_THRESH ((IkReal)2e-6) #endif // used to check input to atan2 for degenerate cases #ifndef IKFAST_ATAN2_MAGTHRESH #define IKFAST_ATAN2_MAGTHRESH ((IkReal)2e-6) #endif // minimum distance of separate solutions #ifndef IKFAST_SOLUTION_THRESH #define IKFAST_SOLUTION_THRESH ((IkReal)1e-6) #endif // there are checkpoints in ikfast that are evaluated to make sure they are 0. This threshold speicfies by how much they can deviate #ifndef IKFAST_EVALCOND_THRESH #define IKFAST_EVALCOND_THRESH ((IkReal)0.000005) #endif inline float IKasin(float f) { IKFAST_ASSERT( f > -1-IKFAST_SINCOS_THRESH && f < 1+IKFAST_SINCOS_THRESH ); // any more error implies something is wrong with the solver if( f <= -1 ) return float(-IKPI_2); else if( f >= 1 ) return float(IKPI_2); return asinf(f); } inline double IKasin(double f) { IKFAST_ASSERT( f > -1-IKFAST_SINCOS_THRESH && f < 1+IKFAST_SINCOS_THRESH ); // any more error implies something is wrong with the solver if( f <= -1 ) return -IKPI_2; else if( f >= 1 ) return IKPI_2; return asin(f); } // return positive value in [0,y) inline float IKfmod(float x, float y) { while(x < 0) { x += y; } return fmodf(x,y); } // return positive value in [0,y) inline double IKfmod(double x, double y) { while(x < 0) { x += y; } return fmod(x,y); } inline float IKacos(float f) { IKFAST_ASSERT( f > -1-IKFAST_SINCOS_THRESH && f < 1+IKFAST_SINCOS_THRESH ); // any more error implies something is wrong with the solver if( f <= -1 ) return float(IKPI); else if( f >= 1 ) return float(0); return acosf(f); } inline double IKacos(double f) { IKFAST_ASSERT( f > -1-IKFAST_SINCOS_THRESH && f < 1+IKFAST_SINCOS_THRESH ); // any more error implies something is wrong with the solver if( f <= -1 ) return IKPI; else if( f >= 1 ) return 0; return acos(f); } inline float IKsin(float f) { return sinf(f); } inline double IKsin(double f) { return sin(f); } inline float IKcos(float f) { return cosf(f); } inline double IKcos(double f) { return cos(f); } inline float IKtan(float f) { return tanf(f); } inline double IKtan(double f) { return tan(f); } inline float IKsqrt(float f) { if( f <= 0.0f ) return 0.0f; return sqrtf(f); } inline double IKsqrt(double f) { if( f <= 0.0 ) return 0.0; return sqrt(f); } inline float IKatan2Simple(float fy, float fx) { return atan2f(fy,fx); } inline float IKatan2(float fy, float fx) { if( isnan(fy) ) { IKFAST_ASSERT(!isnan(fx)); // if both are nan, probably wrong value will be returned return float(IKPI_2); } else if( isnan(fx) ) { return 0; } return atan2f(fy,fx); } inline double IKatan2Simple(double fy, double fx) { return atan2(fy,fx); } inline double IKatan2(double fy, double fx) { if( isnan(fy) ) { IKFAST_ASSERT(!isnan(fx)); // if both are nan, probably wrong value will be returned return IKPI_2; } else if( isnan(fx) ) { return 0; } return atan2(fy,fx); } template <typename T> struct CheckValue { T value; bool valid; }; template <typename T> inline CheckValue<T> IKatan2WithCheck(T fy, T fx, T epsilon) { CheckValue<T> ret; ret.valid = false; ret.value = 0; if( !isnan(fy) && !isnan(fx) ) { if( IKabs(fy) >= IKFAST_ATAN2_MAGTHRESH || IKabs(fx) > IKFAST_ATAN2_MAGTHRESH ) { ret.value = IKatan2Simple(fy,fx); ret.valid = true; } } return ret; } inline float IKsign(float f) { if( f > 0 ) { return float(1); } else if( f < 0 ) { return float(-1); } return 0; } inline double IKsign(double f) { if( f > 0 ) { return 1.0; } else if( f < 0 ) { return -1.0; } return 0; } template <typename T> inline CheckValue<T> IKPowWithIntegerCheck(T f, int n) { CheckValue<T> ret; ret.valid = true; if( n == 0 ) { ret.value = 1.0; return ret; } else if( n == 1 ) { ret.value = f; return ret; } else if( n < 0 ) { if( f == 0 ) { ret.valid = false; ret.value = (T)1.0e30; return ret; } if( n == -1 ) { ret.value = T(1.0)/f; return ret; } } int num = n > 0 ? n : -n; if( num == 2 ) { ret.value = f*f; } else if( num == 3 ) { ret.value = f*f*f; } else { ret.value = 1.0; while(num>0) { if( num & 1 ) { ret.value *= f; } num >>= 1; f *= f; } } if( n < 0 ) { ret.value = T(1.0)/ret.value; } return ret; } /// solves the forward kinematics equations. /// \param pfree is an array specifying the free joints of the chain. IKFAST_API void ComputeFk(const IkReal* j, IkReal* eetrans, IkReal* eerot) { IkReal x0,x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15,x16,x17,x18,x19,x20,x21,x22,x23,x24,x25,x26,x27,x28,x29,x30,x31,x32,x33,x34,x35,x36,x37,x38,x39,x40,x41; x0=IKcos(j[0]); x1=IKcos(j[1]); x2=IKsin(j[2]); x3=IKcos(j[2]); x4=IKsin(j[1]); x5=IKsin(j[3]); x6=IKcos(j[3]); x7=IKsin(j[0]); x8=IKcos(j[5]); x9=IKsin(j[5]); x10=IKsin(j[4]); x11=IKcos(j[4]); x12=((1.0)*x11); x13=((1.0)*x7); x14=((1.0)*x10); x15=((1.0)*x2); x16=((0.4331)*x2); x17=(x0*x1); x18=(x1*x7); x19=(x3*x4); x20=(x2*x4); x21=(x1*x3); x22=(x1*x2); x23=((1.0)*x21); x24=((1.0)*x19); x25=((0.0203)*x21); x26=(x0*x15*x4); x27=(x13*x20); x28=((((-1.0)*x23))+x20); x29=(((x1*x15))+x24); x30=((-1.0)*x29); x31=(x30*x6); x32=(x29*x5); x33=((((-1.0)*x15*x17))+(((-1.0)*x0*x24))); x34=(((x0*x24))+((x15*x17))); x35=(x13*(((((-1.0)*x22))+(((-1.0)*x19))))); x36=(x13*((x19+x22))); x37=(x10*x33); x38=(((x6*(((((-1.0)*x26))+((x17*x3))))))+(((-1.0)*x13*x5))); x39=(((x0*x5))+((x6*((((x18*x3))+(((-1.0)*x27))))))); x40=(((x5*(((((-1.0)*x17*x3))+x26))))+(((-1.0)*x13*x6))); x41=(((x0*x6))+((x5*(((((-1.0)*x13*x21))+x27))))); eerot[0]=(((x40*x9))+((x8*((((x11*x38))+x37))))); eerot[1]=(((x40*x8))+((x9*(((((-1.0)*x12*x38))+(((-1.0)*x14*x33))))))); eerot[2]=(((x10*x38))+((x11*x34))); eetrans[0]=((((0.4318)*x17))+(((0.4331)*x0*x19))+(((-0.0203)*x17*x3))+(((0.0203)*x0*x20))+((x16*x17))+(((-0.1501)*x7))); eerot[3]=(((x41*x9))+((x8*((((x10*x35))+((x11*x39))))))); eerot[4]=(((x41*x8))+((x9*(((((-1.0)*x12*x39))+(((-1.0)*x14*x35))))))); eerot[5]=(((x10*x39))+((x11*x36))); eetrans[1]=((((0.1501)*x0))+(((0.4318)*x18))+(((-0.0203)*x18*x3))+(((0.4331)*x19*x7))+((x16*x18))+(((0.0203)*x20*x7))); eerot[6]=(((x32*x9))+((x8*((((x11*x31))+((x10*x28))))))); eerot[7]=(((x32*x8))+((x9*(((((-1.0)*x12*x31))+(((-1.0)*x14*x28))))))); eerot[8]=(((x10*x31))+((x11*((x23+(((-1.0)*x15*x4))))))); eetrans[2]=((1.371)+(((-0.4318)*x4))+(((0.4331)*x21))+(((-1.0)*x16*x4))+(((0.0203)*x19))+(((0.0203)*x22))); } IKFAST_API int GetNumFreeParameters() { return 0; } IKFAST_API int* GetFreeParameters() { return NULL; } IKFAST_API int GetNumJoints() { return 6; } IKFAST_API int GetIkRealSize() { return sizeof(IkReal); } IKFAST_API int GetIkType() { return 0x67000001; } class IKSolver { public: IkReal j0,cj0,sj0,htj0,j0mul,j1,cj1,sj1,htj1,j1mul,j2,cj2,sj2,htj2,j2mul,j3,cj3,sj3,htj3,j3mul,j4,cj4,sj4,htj4,j4mul,j5,cj5,sj5,htj5,j5mul,new_r00,r00,rxp0_0,new_r01,r01,rxp0_1,new_r02,r02,rxp0_2,new_r10,r10,rxp1_0,new_r11,r11,rxp1_1,new_r12,r12,rxp1_2,new_r20,r20,rxp2_0,new_r21,r21,rxp2_1,new_r22,r22,rxp2_2,new_px,px,npx,new_py,py,npy,new_pz,pz,npz,pp; unsigned char _ij0[2], _nj0,_ij1[2], _nj1,_ij2[2], _nj2,_ij3[2], _nj3,_ij4[2], _nj4,_ij5[2], _nj5; IkReal j100, cj100, sj100; unsigned char _ij100[2], _nj100; bool ComputeIk(const IkReal* eetrans, const IkReal* eerot, const IkReal* pfree, IkSolutionListBase<IkReal>& solutions) { j0=numeric_limits<IkReal>::quiet_NaN(); _ij0[0] = -1; _ij0[1] = -1; _nj0 = -1; j1=numeric_limits<IkReal>::quiet_NaN(); _ij1[0] = -1; _ij1[1] = -1; _nj1 = -1; j2=numeric_limits<IkReal>::quiet_NaN(); _ij2[0] = -1; _ij2[1] = -1; _nj2 = -1; j3=numeric_limits<IkReal>::quiet_NaN(); _ij3[0] = -1; _ij3[1] = -1; _nj3 = -1; j4=numeric_limits<IkReal>::quiet_NaN(); _ij4[0] = -1; _ij4[1] = -1; _nj4 = -1; j5=numeric_limits<IkReal>::quiet_NaN(); _ij5[0] = -1; _ij5[1] = -1; _nj5 = -1; for(int dummyiter = 0; dummyiter < 1; ++dummyiter) { solutions.Clear(); r00 = eerot[0*3+0]; r01 = eerot[0*3+1]; r02 = eerot[0*3+2]; r10 = eerot[1*3+0]; r11 = eerot[1*3+1]; r12 = eerot[1*3+2]; r20 = eerot[2*3+0]; r21 = eerot[2*3+1]; r22 = eerot[2*3+2]; px = eetrans[0]; py = eetrans[1]; pz = eetrans[2]; new_r00=r00; new_r01=r01; new_r02=r02; new_px=px; new_r10=r10; new_r11=r11; new_r12=r12; new_py=py; new_r20=r20; new_r21=r21; new_r22=r22; new_pz=((-1.371)+pz); r00 = new_r00; r01 = new_r01; r02 = new_r02; r10 = new_r10; r11 = new_r11; r12 = new_r12; r20 = new_r20; r21 = new_r21; r22 = new_r22; px = new_px; py = new_py; pz = new_pz; IkReal x42=((1.0)*px); IkReal x43=((1.0)*pz); IkReal x44=((1.0)*py); pp=((px*px)+(py*py)+(pz*pz)); npx=(((px*r00))+((py*r10))+((pz*r20))); npy=(((px*r01))+((py*r11))+((pz*r21))); npz=(((px*r02))+((py*r12))+((pz*r22))); rxp0_0=((((-1.0)*r20*x44))+((pz*r10))); rxp0_1=(((px*r20))+(((-1.0)*r00*x43))); rxp0_2=((((-1.0)*r10*x42))+((py*r00))); rxp1_0=((((-1.0)*r21*x44))+((pz*r11))); rxp1_1=(((px*r21))+(((-1.0)*r01*x43))); rxp1_2=((((-1.0)*r11*x42))+((py*r01))); rxp2_0=((((-1.0)*r22*x44))+((pz*r12))); rxp2_1=((((-1.0)*r02*x43))+((px*r22))); rxp2_2=((((-1.0)*r12*x42))+((py*r02))); { IkReal j2array[2], cj2array[2], sj2array[2]; bool j2valid[2]={false}; _nj2 = 2; if( (((-1.0601789761685)+(((2.67068488900329)*pp)))) < -1-IKFAST_SINCOS_THRESH || (((-1.0601789761685)+(((2.67068488900329)*pp)))) > 1+IKFAST_SINCOS_THRESH ) continue; IkReal x45=IKasin(((-1.0601789761685)+(((2.67068488900329)*pp)))); j2array[0]=((0.0468371131132389)+(((1.0)*x45))); sj2array[0]=IKsin(j2array[0]); cj2array[0]=IKcos(j2array[0]); j2array[1]=((3.18842976670303)+(((-1.0)*x45))); sj2array[1]=IKsin(j2array[1]); cj2array[1]=IKcos(j2array[1]); if( j2array[0] > IKPI ) { j2array[0]-=IK2PI; } else if( j2array[0] < -IKPI ) { j2array[0]+=IK2PI; } j2valid[0] = true; if( j2array[1] > IKPI ) { j2array[1]-=IK2PI; } else if( j2array[1] < -IKPI ) { j2array[1]+=IK2PI; } j2valid[1] = true; for(int ij2 = 0; ij2 < 2; ++ij2) { if( !j2valid[ij2] ) { continue; } _ij2[0] = ij2; _ij2[1] = -1; for(int iij2 = ij2+1; iij2 < 2; ++iij2) { if( j2valid[iij2] && IKabs(cj2array[ij2]-cj2array[iij2]) < IKFAST_SOLUTION_THRESH && IKabs(sj2array[ij2]-sj2array[iij2]) < IKFAST_SOLUTION_THRESH ) { j2valid[iij2]=false; _ij2[1] = iij2; break; } } j2 = j2array[ij2]; cj2 = cj2array[ij2]; sj2 = sj2array[ij2]; { IkReal j0eval[2]; j0eval[0]=((IKabs(px))+(IKabs(py))); j0eval[1]=((px*px)+(py*py)); if( IKabs(j0eval[0]) < 0.0000010000000000 || IKabs(j0eval[1]) < 0.0000010000000000 ) { { IkReal j1eval[1]; j1eval[0]=((10.6354679802956)+(((10.7231100422792)*(cj2*cj2)))+(((-1.0)*cj2))+(((21.3349753694581)*sj2))+(((10.7231100422792)*(sj2*sj2)))); if( IKabs(j1eval[0]) < 0.0000010000000000 ) { continue; // no branches [j0, j1] } else { { IkReal j1array[2], cj1array[2], sj1array[2]; bool j1valid[2]={false}; _nj1 = 2; IkReal x46=((((-0.4331)*cj2))+(((-0.0203)*sj2))); IkReal x47=((0.4318)+(((-0.0203)*cj2))+(((0.4331)*sj2))); CheckValue<IkReal> x50 = IKatan2WithCheck(IkReal(x46),x47,IKFAST_ATAN2_MAGTHRESH); if(!x50.valid){ continue; } IkReal x48=((1.0)*(x50.value)); if((((x46*x46)+(x47*x47))) < -0.00001) continue; CheckValue<IkReal> x51=IKPowWithIntegerCheck(IKabs(IKsqrt(((x46*x46)+(x47*x47)))),-1); if(!x51.valid){ continue; } if( ((pz*(x51.value))) < -1-IKFAST_SINCOS_THRESH || ((pz*(x51.value))) > 1+IKFAST_SINCOS_THRESH ) continue; IkReal x49=IKasin((pz*(x51.value))); j1array[0]=((((-1.0)*x49))+(((-1.0)*x48))); sj1array[0]=IKsin(j1array[0]); cj1array[0]=IKcos(j1array[0]); j1array[1]=((3.14159265358979)+(((-1.0)*x48))+x49); sj1array[1]=IKsin(j1array[1]); cj1array[1]=IKcos(j1array[1]); if( j1array[0] > IKPI ) { j1array[0]-=IK2PI; } else if( j1array[0] < -IKPI ) { j1array[0]+=IK2PI; } j1valid[0] = true; if( j1array[1] > IKPI ) { j1array[1]-=IK2PI; } else if( j1array[1] < -IKPI ) { j1array[1]+=IK2PI; } j1valid[1] = true; for(int ij1 = 0; ij1 < 2; ++ij1) { if( !j1valid[ij1] ) { continue; } _ij1[0] = ij1; _ij1[1] = -1; for(int iij1 = ij1+1; iij1 < 2; ++iij1) { if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH ) { j1valid[iij1]=false; _ij1[1] = iij1; break; } } j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1]; { IkReal j0eval[3]; IkReal x52=pz*pz; IkReal x53=((25000000.0)*pp); IkReal x54=(cj1*pp); IkReal x55=((3240659.0)*cj1); IkReal x56=((21590000.0)*pz*sj1); IkReal x57=(cj1*x52); j0eval[0]=(x54+(((-1.0)*x57))); j0eval[1]=IKsign(((((-21590000.0)*x57))+(((21590000.0)*x54)))); j0eval[2]=((IKabs((((px*x56))+((px*x53))+(((-601661.75)*px))+((py*x55)))))+(IKabs(((((-1.0)*px*x55))+(((-601661.75)*py))+((py*x56))+((py*x53)))))); if( IKabs(j0eval[0]) < 0.0000010000000000 || IKabs(j0eval[1]) < 0.0000010000000000 || IKabs(j0eval[2]) < 0.0000010000000000 ) { { IkReal j0eval[3]; IkReal x58=pz*pz; IkReal x59=((4331.0)*cj2); IkReal x60=(pp*sj1); IkReal x61=((1501.0)*sj1); IkReal x62=((203.0)*sj2); IkReal x63=(sj1*x58); IkReal x64=((10000.0)*cj1*pz); j0eval[0]=(x60+(((-1.0)*x63))); j0eval[1]=((IKabs(((((-1.0)*px*x64))+((px*x59))+((px*x62))+((py*x61)))))+(IKabs(((((-1.0)*px*x61))+(((-1.0)*py*x64))+((py*x62))+((py*x59)))))); j0eval[2]=IKsign(((((10000.0)*x60))+(((-10000.0)*x63)))); if( IKabs(j0eval[0]) < 0.0000010000000000 || IKabs(j0eval[1]) < 0.0000010000000000 || IKabs(j0eval[2]) < 0.0000010000000000 ) { { IkReal j0eval[3]; IkReal x65=pz*pz; IkReal x66=((203.0)*cj2); IkReal x67=(cj1*pp); IkReal x68=((1501.0)*cj1); IkReal x69=((4331.0)*sj2); IkReal x70=((10000.0)*pz*sj1); IkReal x71=(cj1*x65); j0eval[0]=(x67+(((-1.0)*x71))); j0eval[1]=IKsign(((((-10000.0)*x71))+(((10000.0)*x67)))); j0eval[2]=((IKabs(((((-1.0)*px*x66))+((px*x69))+(((4318.0)*px))+((px*x70))+((py*x68)))))+(IKabs((((py*x70))+(((-1.0)*px*x68))+(((4318.0)*py))+(((-1.0)*py*x66))+((py*x69)))))); if( IKabs(j0eval[0]) < 0.0000010000000000 || IKabs(j0eval[1]) < 0.0000010000000000 || IKabs(j0eval[2]) < 0.0000010000000000 ) { { IkReal evalcond[5]; bool bgotonextstatement = true; do { IkReal x72=((1.0)*pp); IkReal x73=((0.4318)+pz+(((-0.0203)*cj2))+(((0.4331)*sj2))); evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-1.5707963267949)+j1)))), 6.28318530717959))); evalcond[1]=((0.39696895)+(((-1.0)*x72))+(((-0.01753108)*cj2))+(((0.37402516)*sj2))); evalcond[2]=((0.02406647)+(((-1.0)*x72))+(((-0.8636)*pz))); evalcond[3]=x73; evalcond[4]=x73; if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 && IKabs(evalcond[4]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j0eval[3]; sj1=1.0; cj1=0; j1=1.5707963267949; IkReal x74=pz*pz; IkReal x75=((203.0)*sj2); IkReal x76=((4331.0)*cj2); j0eval[0]=((((-1.0)*pp))+x74); j0eval[1]=((IKabs(((((-1.0)*px*x75))+(((-1.0)*px*x76))+(((-1501.0)*py)))))+(IKabs(((((1501.0)*px))+(((-1.0)*py*x76))+(((-1.0)*py*x75)))))); j0eval[2]=IKsign(((((10000.0)*x74))+(((-10000.0)*pp)))); if( IKabs(j0eval[0]) < 0.0000010000000000 || IKabs(j0eval[1]) < 0.0000010000000000 || IKabs(j0eval[2]) < 0.0000010000000000 ) { continue; // no branches [j0] } else { { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; IkReal x77=((203.0)*sj2); IkReal x78=((4331.0)*cj2); CheckValue<IkReal> x79 = IKatan2WithCheck(IkReal(((((1501.0)*px))+(((-1.0)*py*x77))+(((-1.0)*py*x78)))),((((-1.0)*px*x77))+(((-1.0)*px*x78))+(((-1501.0)*py))),IKFAST_ATAN2_MAGTHRESH); if(!x79.valid){ continue; } CheckValue<IkReal> x80=IKPowWithIntegerCheck(IKsign(((((10000.0)*(pz*pz)))+(((-10000.0)*pp)))),-1); if(!x80.valid){ continue; } j0array[0]=((-1.5707963267949)+(x79.value)+(((1.5707963267949)*(x80.value)))); sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { IkReal evalcond[2]; IkReal x81=IKsin(j0); IkReal x82=IKcos(j0); evalcond[0]=((0.1501)+(((-1.0)*py*x82))+((px*x81))); evalcond[1]=((((-0.4331)*cj2))+((py*x81))+((px*x82))+(((-0.0203)*sj2))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH ) { continue; } } rotationfunction0(solutions); } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { IkReal x469=((1.0)*pp); IkReal x470=((0.0203)*cj2); IkReal x471=((0.4331)*sj2); evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((1.5707963267949)+j1)))), 6.28318530717959))); evalcond[1]=((0.39696895)+(((-0.01753108)*cj2))+(((-1.0)*x469))+(((0.37402516)*sj2))); evalcond[2]=((0.02406647)+(((-1.0)*x469))+(((0.8636)*pz))); evalcond[3]=((0.4318)+(((-1.0)*x470))+(((-1.0)*pz))+x471); evalcond[4]=((-0.4318)+(((-1.0)*x471))+x470+pz); if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 && IKabs(evalcond[4]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j0eval[3]; sj1=-1.0; cj1=0; j1=-1.5707963267949; IkReal x472=pz*pz; IkReal x473=((203.0)*sj2); IkReal x474=((4331.0)*cj2); j0eval[0]=((((-1.0)*x472))+pp); j0eval[1]=IKsign(((((-10000.0)*x472))+(((10000.0)*pp)))); j0eval[2]=((IKabs(((((-1.0)*py*x473))+(((-1.0)*py*x474))+(((-1501.0)*px)))))+(IKabs(((((1501.0)*py))+(((-1.0)*px*x473))+(((-1.0)*px*x474)))))); if( IKabs(j0eval[0]) < 0.0000010000000000 || IKabs(j0eval[1]) < 0.0000010000000000 || IKabs(j0eval[2]) < 0.0000010000000000 ) { continue; // no branches [j0] } else { { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; IkReal x475=((203.0)*sj2); IkReal x476=((4331.0)*cj2); CheckValue<IkReal> x477 = IKatan2WithCheck(IkReal(((((-1.0)*py*x475))+(((-1.0)*py*x476))+(((-1501.0)*px)))),((((1501.0)*py))+(((-1.0)*px*x476))+(((-1.0)*px*x475))),IKFAST_ATAN2_MAGTHRESH); if(!x477.valid){ continue; } CheckValue<IkReal> x478=IKPowWithIntegerCheck(IKsign(((((-10000.0)*(pz*pz)))+(((10000.0)*pp)))),-1); if(!x478.valid){ continue; } j0array[0]=((-1.5707963267949)+(x477.value)+(((1.5707963267949)*(x478.value)))); sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { IkReal evalcond[2]; IkReal x479=IKcos(j0); IkReal x480=IKsin(j0); IkReal x481=((1.0)*x479); evalcond[0]=((0.1501)+((px*x480))+(((-1.0)*py*x481))); evalcond[1]=((((-1.0)*py*x480))+(((-0.4331)*cj2))+(((-1.0)*px*x481))+(((-0.0203)*sj2))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH ) { continue; } } rotationfunction0(solutions); } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { IkReal x482=((((-0.4331)*cj2))+pz+(((-0.0203)*sj2))); evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(j1))), 6.28318530717959))); evalcond[1]=((0.39696895)+(((-0.01753108)*cj2))+(((-1.0)*pp))+(((0.37402516)*sj2))); evalcond[2]=x482; evalcond[3]=x482; if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j0eval[3]; sj1=0; cj1=1.0; j1=0; IkReal x483=pz*pz; IkReal x484=((25000000.0)*pp); j0eval[0]=((((-1.0)*pp))+x483); j0eval[1]=((IKabs(((((601661.75)*py))+(((3240659.0)*px))+(((-1.0)*py*x484)))))+(IKabs(((((-3240659.0)*py))+(((-1.0)*px*x484))+(((601661.75)*px)))))); j0eval[2]=IKsign(((((21590000.0)*x483))+(((-21590000.0)*pp)))); if( IKabs(j0eval[0]) < 0.0000010000000000 || IKabs(j0eval[1]) < 0.0000010000000000 || IKabs(j0eval[2]) < 0.0000010000000000 ) { { IkReal j0eval[3]; sj1=0; cj1=1.0; j1=0; IkReal x485=pz*pz; IkReal x486=((4340.5148926345)*sj2); IkReal x487=((468.713922881552)*pz); j0eval[0]=((((-1.0)*x485))+pp); j0eval[1]=IKsign(((((-10000.0)*x485))+(((10000.0)*pp)))); j0eval[2]=((IKabs((((py*x486))+(((4318.0)*py))+(((-1501.0)*px))+(((-1.0)*py*x487)))))+(IKabs(((((1501.0)*py))+((px*x486))+(((-1.0)*px*x487))+(((4318.0)*px)))))); if( IKabs(j0eval[0]) < 0.0000010000000000 || IKabs(j0eval[1]) < 0.0000010000000000 || IKabs(j0eval[2]) < 0.0000010000000000 ) { continue; // no branches [j0] } else { { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; IkReal x488=((4340.5148926345)*sj2); IkReal x489=((468.713922881552)*pz); CheckValue<IkReal> x490 = IKatan2WithCheck(IkReal((((py*x488))+(((4318.0)*py))+(((-1501.0)*px))+(((-1.0)*py*x489)))),((((1501.0)*py))+((px*x488))+(((-1.0)*px*x489))+(((4318.0)*px))),IKFAST_ATAN2_MAGTHRESH); if(!x490.valid){ continue; } CheckValue<IkReal> x491=IKPowWithIntegerCheck(IKsign(((((-10000.0)*(pz*pz)))+(((10000.0)*pp)))),-1); if(!x491.valid){ continue; } j0array[0]=((-1.5707963267949)+(x490.value)+(((1.5707963267949)*(x491.value)))); sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { IkReal evalcond[3]; IkReal x492=IKsin(j0); IkReal x493=IKcos(j0); IkReal x494=((1.0)*x493); IkReal x495=(py*x492); evalcond[0]=((0.1501)+((px*x492))+(((-1.0)*py*x494))); evalcond[1]=((0.02406647)+(((0.8636)*x495))+(((-1.0)*pp))+(((0.8636)*px*x493))); evalcond[2]=((0.4318)+(((-1.0)*px*x494))+(((0.43405148926345)*sj2))+(((-1.0)*x495))+(((-0.0468713922881552)*pz))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH ) { continue; } } rotationfunction0(solutions); } } } } } else { { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; IkReal x496=((25000000.0)*pp); CheckValue<IkReal> x497=IKPowWithIntegerCheck(IKsign(((((21590000.0)*(pz*pz)))+(((-21590000.0)*pp)))),-1); if(!x497.valid){ continue; } CheckValue<IkReal> x498 = IKatan2WithCheck(IkReal(((((601661.75)*py))+(((3240659.0)*px))+(((-1.0)*py*x496)))),((((-3240659.0)*py))+(((-1.0)*px*x496))+(((601661.75)*px))),IKFAST_ATAN2_MAGTHRESH); if(!x498.valid){ continue; } j0array[0]=((-1.5707963267949)+(((1.5707963267949)*(x497.value)))+(x498.value)); sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { IkReal evalcond[3]; IkReal x499=IKsin(j0); IkReal x500=IKcos(j0); IkReal x501=((1.0)*x500); IkReal x502=(py*x499); evalcond[0]=((0.1501)+(((-1.0)*py*x501))+((px*x499))); evalcond[1]=((0.02406647)+(((0.8636)*px*x500))+(((0.8636)*x502))+(((-1.0)*pp))); evalcond[2]=((0.4318)+(((0.43405148926345)*sj2))+(((-0.0468713922881552)*pz))+(((-1.0)*x502))+(((-1.0)*px*x501))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH ) { continue; } } rotationfunction0(solutions); } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { IkReal x503=((0.0203)*sj2); IkReal x504=((0.4331)*cj2); IkReal x505=(x503+x504); evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-3.14159265358979)+j1)))), 6.28318530717959))); evalcond[1]=((0.39696895)+(((-0.01753108)*cj2))+(((-1.0)*pp))+(((0.37402516)*sj2))); evalcond[2]=((((-1.0)*x505))+(((-1.0)*pz))); evalcond[3]=(pz+x505); if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j0eval[3]; sj1=0; cj1=-1.0; j1=3.14159265358979; IkReal x506=pz*pz; IkReal x507=((25000000.0)*pp); j0eval[0]=(pp+(((-1.0)*x506))); j0eval[1]=((IKabs(((((601661.75)*px))+(((3240659.0)*py))+(((-1.0)*px*x507)))))+(IKabs(((((-1.0)*py*x507))+(((-3240659.0)*px))+(((601661.75)*py)))))); j0eval[2]=IKsign(((((-21590000.0)*x506))+(((21590000.0)*pp)))); if( IKabs(j0eval[0]) < 0.0000010000000000 || IKabs(j0eval[1]) < 0.0000010000000000 || IKabs(j0eval[2]) < 0.0000010000000000 ) { { IkReal j0eval[3]; sj1=0; cj1=-1.0; j1=3.14159265358979; IkReal x508=pz*pz; IkReal x509=((4340.5148926345)*sj2); IkReal x510=((468.713922881552)*pz); j0eval[0]=((((-1.0)*pp))+x508); j0eval[1]=((IKabs(((((1501.0)*px))+((py*x510))+(((4318.0)*py))+((py*x509)))))+(IKabs((((px*x510))+(((4318.0)*px))+((px*x509))+(((-1501.0)*py)))))); j0eval[2]=IKsign(((((-10000.0)*pp))+(((10000.0)*x508)))); if( IKabs(j0eval[0]) < 0.0000010000000000 || IKabs(j0eval[1]) < 0.0000010000000000 || IKabs(j0eval[2]) < 0.0000010000000000 ) { continue; // no branches [j0] } else { { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; IkReal x511=((4340.5148926345)*sj2); IkReal x512=((468.713922881552)*pz); CheckValue<IkReal> x513=IKPowWithIntegerCheck(IKsign(((((10000.0)*(pz*pz)))+(((-10000.0)*pp)))),-1); if(!x513.valid){ continue; } CheckValue<IkReal> x514 = IKatan2WithCheck(IkReal(((((1501.0)*px))+((py*x512))+((py*x511))+(((4318.0)*py)))),(((px*x512))+((px*x511))+(((4318.0)*px))+(((-1501.0)*py))),IKFAST_ATAN2_MAGTHRESH); if(!x514.valid){ continue; } j0array[0]=((-1.5707963267949)+(((1.5707963267949)*(x513.value)))+(x514.value)); sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { IkReal evalcond[3]; IkReal x515=IKsin(j0); IkReal x516=IKcos(j0); IkReal x517=(px*x516); IkReal x518=(py*x515); evalcond[0]=((0.1501)+((px*x515))+(((-1.0)*py*x516))); evalcond[1]=((0.02406647)+(((-0.8636)*x517))+(((-0.8636)*x518))+(((-1.0)*pp))); evalcond[2]=((0.4318)+(((0.43405148926345)*sj2))+(((0.0468713922881552)*pz))+x518+x517); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH ) { continue; } } rotationfunction0(solutions); } } } } } else { { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; IkReal x519=((25000000.0)*pp); CheckValue<IkReal> x520 = IKatan2WithCheck(IkReal(((((-3240659.0)*px))+(((601661.75)*py))+(((-1.0)*py*x519)))),((((-1.0)*px*x519))+(((601661.75)*px))+(((3240659.0)*py))),IKFAST_ATAN2_MAGTHRESH); if(!x520.valid){ continue; } CheckValue<IkReal> x521=IKPowWithIntegerCheck(IKsign(((((-21590000.0)*(pz*pz)))+(((21590000.0)*pp)))),-1); if(!x521.valid){ continue; } j0array[0]=((-1.5707963267949)+(x520.value)+(((1.5707963267949)*(x521.value)))); sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { IkReal evalcond[3]; IkReal x522=IKsin(j0); IkReal x523=IKcos(j0); IkReal x524=(px*x523); IkReal x525=(py*x522); evalcond[0]=((0.1501)+(((-1.0)*py*x523))+((px*x522))); evalcond[1]=((0.02406647)+(((-0.8636)*x525))+(((-0.8636)*x524))+(((-1.0)*pp))); evalcond[2]=((0.4318)+(((0.43405148926345)*sj2))+(((0.0468713922881552)*pz))+x524+x525); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH ) { continue; } } rotationfunction0(solutions); } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { if( 1 ) { bgotonextstatement=false; continue; // branch miss [j0] } } while(0); if( bgotonextstatement ) { } } } } } } } else { { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; IkReal x526=((203.0)*cj2); IkReal x527=((1501.0)*cj1); IkReal x528=((4331.0)*sj2); IkReal x529=((10000.0)*cj1); IkReal x530=((10000.0)*pz*sj1); CheckValue<IkReal> x531 = IKatan2WithCheck(IkReal(((((-1.0)*px*x527))+(((-1.0)*py*x526))+(((4318.0)*py))+((py*x528))+((py*x530)))),((((-1.0)*px*x526))+((px*x530))+((px*x528))+(((4318.0)*px))+((py*x527))),IKFAST_ATAN2_MAGTHRESH); if(!x531.valid){ continue; } CheckValue<IkReal> x532=IKPowWithIntegerCheck(IKsign(((((-1.0)*x529*(pz*pz)))+((pp*x529)))),-1); if(!x532.valid){ continue; } j0array[0]=((-1.5707963267949)+(x531.value)+(((1.5707963267949)*(x532.value)))); sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { IkReal evalcond[5]; IkReal x533=IKcos(j0); IkReal x534=IKsin(j0); IkReal x535=((0.4331)*sj2); IkReal x536=((0.4331)*cj2); IkReal x537=(pz*sj1); IkReal x538=((0.0203)*cj2); IkReal x539=((0.8636)*cj1); IkReal x540=((1.0)*cj1); IkReal x541=((0.0203)*sj2); IkReal x542=(px*x533); IkReal x543=(py*x534); evalcond[0]=((0.1501)+(((-1.0)*py*x533))+((px*x534))); evalcond[1]=(((sj1*x543))+((sj1*x542))+(((-1.0)*x536))+(((-1.0)*x541))+((cj1*pz))); evalcond[2]=((0.02406647)+((x539*x542))+((x539*x543))+(((-0.8636)*x537))+(((-1.0)*pp))); evalcond[3]=((0.4318)+(((-1.0)*x540*x543))+(((-1.0)*x540*x542))+(((-1.0)*x538))+x535+x537); evalcond[4]=((((0.4318)*cj1))+((sj1*x541))+(((-1.0)*x543))+(((-1.0)*x542))+((sj1*x536))+(((-1.0)*cj1*x538))+((cj1*x535))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } rotationfunction0(solutions); } } } } } else { { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; IkReal x544=((203.0)*sj2); IkReal x545=((4331.0)*cj2); IkReal x546=((10000.0)*sj1); IkReal x547=((1501.0)*sj1); IkReal x548=((10000.0)*cj1*pz); CheckValue<IkReal> x549 = IKatan2WithCheck(IkReal((((py*x544))+((py*x545))+(((-1.0)*px*x547))+(((-1.0)*py*x548)))),(((py*x547))+((px*x545))+((px*x544))+(((-1.0)*px*x548))),IKFAST_ATAN2_MAGTHRESH); if(!x549.valid){ continue; } CheckValue<IkReal> x550=IKPowWithIntegerCheck(IKsign(((((-1.0)*x546*(pz*pz)))+((pp*x546)))),-1); if(!x550.valid){ continue; } j0array[0]=((-1.5707963267949)+(x549.value)+(((1.5707963267949)*(x550.value)))); sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { IkReal evalcond[5]; IkReal x551=IKcos(j0); IkReal x552=IKsin(j0); IkReal x553=((0.4331)*sj2); IkReal x554=((0.4331)*cj2); IkReal x555=(pz*sj1); IkReal x556=((0.0203)*cj2); IkReal x557=((0.8636)*cj1); IkReal x558=((1.0)*cj1); IkReal x559=((0.0203)*sj2); IkReal x560=(px*x551); IkReal x561=(py*x552); evalcond[0]=((0.1501)+(((-1.0)*py*x551))+((px*x552))); evalcond[1]=(((cj1*pz))+(((-1.0)*x559))+(((-1.0)*x554))+((sj1*x561))+((sj1*x560))); evalcond[2]=((0.02406647)+(((-0.8636)*x555))+(((-1.0)*pp))+((x557*x561))+((x557*x560))); evalcond[3]=((0.4318)+(((-1.0)*x558*x560))+(((-1.0)*x558*x561))+(((-1.0)*x556))+x553+x555); evalcond[4]=(((sj1*x554))+((sj1*x559))+(((0.4318)*cj1))+(((-1.0)*cj1*x556))+((cj1*x553))+(((-1.0)*x560))+(((-1.0)*x561))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } rotationfunction0(solutions); } } } } } else { { IkReal j0array[1], cj0array[1], sj0array[1]; bool j0valid[1]={false}; _nj0 = 1; IkReal x562=((25000000.0)*pp); IkReal x563=((21590000.0)*cj1); IkReal x564=((3240659.0)*cj1); IkReal x565=((21590000.0)*pz*sj1); CheckValue<IkReal> x566 = IKatan2WithCheck(IkReal(((((-601661.75)*py))+((py*x562))+((py*x565))+(((-1.0)*px*x564)))),((((-601661.75)*px))+((py*x564))+((px*x562))+((px*x565))),IKFAST_ATAN2_MAGTHRESH); if(!x566.valid){ continue; } CheckValue<IkReal> x567=IKPowWithIntegerCheck(IKsign(((((-1.0)*x563*(pz*pz)))+((pp*x563)))),-1); if(!x567.valid){ continue; } j0array[0]=((-1.5707963267949)+(x566.value)+(((1.5707963267949)*(x567.value)))); sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; for(int ij0 = 0; ij0 < 1; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 1; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { IkReal evalcond[5]; IkReal x568=IKcos(j0); IkReal x569=IKsin(j0); IkReal x570=((0.4331)*sj2); IkReal x571=((0.4331)*cj2); IkReal x572=(pz*sj1); IkReal x573=((0.0203)*cj2); IkReal x574=((0.8636)*cj1); IkReal x575=((1.0)*cj1); IkReal x576=((0.0203)*sj2); IkReal x577=(px*x568); IkReal x578=(py*x569); evalcond[0]=((0.1501)+(((-1.0)*py*x568))+((px*x569))); evalcond[1]=(((sj1*x577))+((sj1*x578))+((cj1*pz))+(((-1.0)*x571))+(((-1.0)*x576))); evalcond[2]=((0.02406647)+((x574*x578))+((x574*x577))+(((-1.0)*pp))+(((-0.8636)*x572))); evalcond[3]=((0.4318)+(((-1.0)*x575*x578))+(((-1.0)*x575*x577))+(((-1.0)*x573))+x570+x572); evalcond[4]=(((sj1*x571))+((sj1*x576))+(((0.4318)*cj1))+(((-1.0)*cj1*x573))+(((-1.0)*x577))+(((-1.0)*x578))+((cj1*x570))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } rotationfunction0(solutions); } } } } } } } } } else { { IkReal j0array[2], cj0array[2], sj0array[2]; bool j0valid[2]={false}; _nj0 = 2; CheckValue<IkReal> x581 = IKatan2WithCheck(IkReal(((-1.0)*py)),px,IKFAST_ATAN2_MAGTHRESH); if(!x581.valid){ continue; } IkReal x579=((1.0)*(x581.value)); if((((px*px)+(py*py))) < -0.00001) continue; CheckValue<IkReal> x582=IKPowWithIntegerCheck(IKabs(IKsqrt(((px*px)+(py*py)))),-1); if(!x582.valid){ continue; } if( (((0.1501)*(x582.value))) < -1-IKFAST_SINCOS_THRESH || (((0.1501)*(x582.value))) > 1+IKFAST_SINCOS_THRESH ) continue; IkReal x580=IKasin(((0.1501)*(x582.value))); j0array[0]=((((-1.0)*x580))+(((-1.0)*x579))); sj0array[0]=IKsin(j0array[0]); cj0array[0]=IKcos(j0array[0]); j0array[1]=((3.14159265358979)+(((-1.0)*x579))+x580); sj0array[1]=IKsin(j0array[1]); cj0array[1]=IKcos(j0array[1]); if( j0array[0] > IKPI ) { j0array[0]-=IK2PI; } else if( j0array[0] < -IKPI ) { j0array[0]+=IK2PI; } j0valid[0] = true; if( j0array[1] > IKPI ) { j0array[1]-=IK2PI; } else if( j0array[1] < -IKPI ) { j0array[1]+=IK2PI; } j0valid[1] = true; for(int ij0 = 0; ij0 < 2; ++ij0) { if( !j0valid[ij0] ) { continue; } _ij0[0] = ij0; _ij0[1] = -1; for(int iij0 = ij0+1; iij0 < 2; ++iij0) { if( j0valid[iij0] && IKabs(cj0array[ij0]-cj0array[iij0]) < IKFAST_SOLUTION_THRESH && IKabs(sj0array[ij0]-sj0array[iij0]) < IKFAST_SOLUTION_THRESH ) { j0valid[iij0]=false; _ij0[1] = iij0; break; } } j0 = j0array[ij0]; cj0 = cj0array[ij0]; sj0 = sj0array[ij0]; { IkReal j1eval[3]; IkReal x583=cj2*cj2; IkReal x584=(cj2*sj2); IkReal x585=(py*sj0); IkReal x586=(pz*sj2); IkReal x587=((1.0)*pz); IkReal x588=(cj2*pz); IkReal x589=(cj0*cj2*px); IkReal x590=(cj0*px*sj2); j1eval[0]=((((-21.3349753694581)*x586))+(((-21.3349753694581)*x589))+(((-1.0)*sj2*x585))+(((-1.0)*x590))+(((-21.3349753694581)*cj2*x585))+x588+(((-21.2709359605911)*pz))); j1eval[1]=IKsign(((((0.0203)*x588))+(((-0.0203)*sj2*x585))+(((-0.4331)*cj2*x585))+(((-0.4331)*x589))+(((-0.4331)*x586))+(((-0.4318)*pz))+(((-0.0203)*x590)))); j1eval[2]=((IKabs(((-0.00041209)+(((-0.01758386)*x584))+(((-0.18716352)*x583))+(pz*pz))))+(IKabs(((-0.00879193)+(((-0.00876554)*sj2))+(((-0.18701258)*cj2))+(((0.01758386)*x583))+(((-0.18716352)*x584))+(((-1.0)*x585*x587))+(((-1.0)*cj0*px*x587)))))); if( IKabs(j1eval[0]) < 0.0000010000000000 || IKabs(j1eval[1]) < 0.0000010000000000 || IKabs(j1eval[2]) < 0.0000010000000000 ) { { IkReal j1eval[3]; IkReal x591=(cj2*pz); IkReal x592=(py*sj0); IkReal x593=((935.0629)*sj2); IkReal x594=((1.0)*cj2); IkReal x595=((21.3349753694581)*sj2); IkReal x596=(cj0*px); IkReal x597=((1082.75)*pp); IkReal x598=(pz*sj2); IkReal x599=((43.8277)*cj2); IkReal x600=((50.75)*pp); IkReal x601=((2159.0)*pz); j1eval[0]=(((x595*x596))+(((-1.0)*x598))+(((-1.0)*x592*x594))+(((-21.3349753694581)*x591))+(((-1.0)*x594*x596))+(((21.2709359605911)*x592))+(((21.2709359605911)*x596))+((x592*x595))); j1eval[1]=IKsign(((((-43.8277)*x598))+(((-1.0)*x596*x599))+(((-1.0)*x592*x599))+(((932.2562)*x596))+(((932.2562)*x592))+(((-935.0629)*x591))+((x593*x596))+((x592*x593)))); j1eval[2]=((IKabs(((((-1.0)*x592*x601))+(((-1.0)*x596*x601))+((cj2*x597))+(((-1.2213733525)*sj2))+(((-26.0579703925)*cj2))+((sj2*x600)))))+(IKabs(((-25.979754365)+(((-1.0)*cj2*x600))+(((1079.5)*pp))+(((-26.0579703925)*sj2))+(((1.2213733525)*cj2))+((sj2*x597))+(((-1.0)*pz*x601)))))); if( IKabs(j1eval[0]) < 0.0000010000000000 || IKabs(j1eval[1]) < 0.0000010000000000 || IKabs(j1eval[2]) < 0.0000010000000000 ) { { IkReal j1eval[3]; IkReal x602=cj0*cj0; IkReal x603=py*py; IkReal x604=pz*pz; IkReal x605=px*px; IkReal x606=((935.0629)*cj2); IkReal x607=(py*sj0); IkReal x608=((43.8277)*sj2); IkReal x609=((2500.0)*pp); IkReal x610=(cj0*px); IkReal x611=(x602*x603); IkReal x612=(x602*x605); j1eval[0]=((((-1.0)*x611))+(((2.0)*x607*x610))+x603+x604+x612); j1eval[1]=((IKabs(((((60.166175)*pz))+((x608*x610))+((x607*x608))+((x606*x607))+((x606*x610))+(((-1.0)*pz*x609)))))+(IKabs(((((-60.166175)*x607))+(((-60.166175)*x610))+((x607*x609))+((x609*x610))+((pz*x608))+((pz*x606)))))); j1eval[2]=IKsign(((((2159.0)*x612))+(((2159.0)*x604))+(((2159.0)*x603))+(((4318.0)*x607*x610))+(((-2159.0)*x611)))); if( IKabs(j1eval[0]) < 0.0000010000000000 || IKabs(j1eval[1]) < 0.0000010000000000 || IKabs(j1eval[2]) < 0.0000010000000000 ) { continue; // no branches [j1] } else { { IkReal j1array[1], cj1array[1], sj1array[1]; bool j1valid[1]={false}; _nj1 = 1; IkReal x613=cj0*cj0; IkReal x614=py*py; IkReal x615=(py*sj0); IkReal x616=((43.8277)*sj2); IkReal x617=((935.0629)*cj2); IkReal x618=(cj0*px); IkReal x619=((2500.0)*pp); IkReal x620=((2159.0)*x614); CheckValue<IkReal> x621=IKPowWithIntegerCheck(IKsign(((((4318.0)*x615*x618))+(((2159.0)*(pz*pz)))+(((2159.0)*x613*(px*px)))+x620+(((-1.0)*x613*x620)))),-1); if(!x621.valid){ continue; } CheckValue<IkReal> x622 = IKatan2WithCheck(IkReal(((((60.166175)*pz))+((x616*x618))+((x617*x618))+(((-1.0)*pz*x619))+((x615*x617))+((x615*x616)))),((((-60.166175)*x618))+(((-60.166175)*x615))+((pz*x617))+((pz*x616))+((x615*x619))+((x618*x619))),IKFAST_ATAN2_MAGTHRESH); if(!x622.valid){ continue; } j1array[0]=((-1.5707963267949)+(((1.5707963267949)*(x621.value)))+(x622.value)); sj1array[0]=IKsin(j1array[0]); cj1array[0]=IKcos(j1array[0]); if( j1array[0] > IKPI ) { j1array[0]-=IK2PI; } else if( j1array[0] < -IKPI ) { j1array[0]+=IK2PI; } j1valid[0] = true; for(int ij1 = 0; ij1 < 1; ++ij1) { if( !j1valid[ij1] ) { continue; } _ij1[0] = ij1; _ij1[1] = -1; for(int iij1 = ij1+1; iij1 < 1; ++iij1) { if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH ) { j1valid[iij1]=false; _ij1[1] = iij1; break; } } j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1]; { IkReal evalcond[5]; IkReal x623=IKsin(j1); IkReal x624=IKcos(j1); IkReal x625=((0.4331)*sj2); IkReal x626=(cj0*px); IkReal x627=((0.4331)*cj2); IkReal x628=(py*sj0); IkReal x629=((0.0203)*cj2); IkReal x630=((0.0203)*sj2); IkReal x631=((1.0)*x624); IkReal x632=((0.0203)*x623); IkReal x633=(pz*x623); IkReal x634=((0.8636)*x624); evalcond[0]=(((pz*x624))+(((-1.0)*x627))+(((-1.0)*x630))+((x623*x626))+((x623*x628))); evalcond[1]=((0.02406647)+((x628*x634))+(((-1.0)*pp))+(((-0.8636)*x633))+((x626*x634))); evalcond[2]=((0.4318)+(((-1.0)*x628*x631))+(((-1.0)*x629))+x625+x633+(((-1.0)*x626*x631))); evalcond[3]=((((-1.0)*x623*x629))+(((-1.0)*x624*x627))+(((-1.0)*x624*x630))+(((0.4318)*x623))+pz+((x623*x625))); evalcond[4]=((((-1.0)*x624*x629))+(((0.4318)*x624))+((x624*x625))+(((-1.0)*x628))+(((-1.0)*x626))+((x623*x630))+((x623*x627))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } rotationfunction0(solutions); } } } } } else { { IkReal j1array[1], cj1array[1], sj1array[1]; bool j1valid[1]={false}; _nj1 = 1; IkReal x635=(pp*sj2); IkReal x636=(cj2*pp); IkReal x637=(py*sj0); IkReal x638=(cj0*px); IkReal x639=((935.0629)*sj2); IkReal x640=((2159.0)*pz); IkReal x641=((43.8277)*cj2); CheckValue<IkReal> x642 = IKatan2WithCheck(IkReal(((((50.75)*x635))+(((-1.2213733525)*sj2))+(((-26.0579703925)*cj2))+(((-1.0)*x637*x640))+(((1082.75)*x636))+(((-1.0)*x638*x640)))),((-25.979754365)+(((1079.5)*pp))+(((-26.0579703925)*sj2))+(((-50.75)*x636))+(((1.2213733525)*cj2))+(((1082.75)*x635))+(((-1.0)*pz*x640))),IKFAST_ATAN2_MAGTHRESH); if(!x642.valid){ continue; } CheckValue<IkReal> x643=IKPowWithIntegerCheck(IKsign(((((-935.0629)*cj2*pz))+(((-43.8277)*pz*sj2))+((x638*x639))+(((932.2562)*x638))+(((932.2562)*x637))+(((-1.0)*x637*x641))+(((-1.0)*x638*x641))+((x637*x639)))),-1); if(!x643.valid){ continue; } j1array[0]=((-1.5707963267949)+(x642.value)+(((1.5707963267949)*(x643.value)))); sj1array[0]=IKsin(j1array[0]); cj1array[0]=IKcos(j1array[0]); if( j1array[0] > IKPI ) { j1array[0]-=IK2PI; } else if( j1array[0] < -IKPI ) { j1array[0]+=IK2PI; } j1valid[0] = true; for(int ij1 = 0; ij1 < 1; ++ij1) { if( !j1valid[ij1] ) { continue; } _ij1[0] = ij1; _ij1[1] = -1; for(int iij1 = ij1+1; iij1 < 1; ++iij1) { if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH ) { j1valid[iij1]=false; _ij1[1] = iij1; break; } } j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1]; { IkReal evalcond[5]; IkReal x644=IKsin(j1); IkReal x645=IKcos(j1); IkReal x646=((0.4331)*sj2); IkReal x647=(cj0*px); IkReal x648=((0.4331)*cj2); IkReal x649=(py*sj0); IkReal x650=((0.0203)*cj2); IkReal x651=((0.0203)*sj2); IkReal x652=((1.0)*x645); IkReal x653=((0.0203)*x644); IkReal x654=(pz*x644); IkReal x655=((0.8636)*x645); evalcond[0]=(((x644*x649))+((x644*x647))+(((-1.0)*x651))+((pz*x645))+(((-1.0)*x648))); evalcond[1]=((0.02406647)+((x647*x655))+(((-0.8636)*x654))+((x649*x655))+(((-1.0)*pp))); evalcond[2]=((0.4318)+(((-1.0)*x647*x652))+(((-1.0)*x650))+x646+x654+(((-1.0)*x649*x652))); evalcond[3]=((((0.4318)*x644))+((x644*x646))+pz+(((-1.0)*x645*x651))+(((-1.0)*x644*x650))+(((-1.0)*x645*x648))); evalcond[4]=((((-1.0)*x649))+(((-1.0)*x647))+(((0.4318)*x645))+((x644*x648))+((x644*x651))+((x645*x646))+(((-1.0)*x645*x650))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } rotationfunction0(solutions); } } } } } else { { IkReal j1array[1], cj1array[1], sj1array[1]; bool j1valid[1]={false}; _nj1 = 1; IkReal x656=cj2*cj2; IkReal x657=(cj0*px); IkReal x658=((0.4331)*cj2); IkReal x659=(cj2*sj2); IkReal x660=((0.0203)*sj2); IkReal x661=(py*sj0); IkReal x662=((1.0)*pz); CheckValue<IkReal> x663 = IKatan2WithCheck(IkReal(((-0.00041209)+(((-0.18716352)*x656))+(pz*pz)+(((-0.01758386)*x659)))),((-0.00879193)+(((-0.00876554)*sj2))+(((0.01758386)*x656))+(((-0.18701258)*cj2))+(((-0.18716352)*x659))+(((-1.0)*x661*x662))+(((-1.0)*x657*x662))),IKFAST_ATAN2_MAGTHRESH); if(!x663.valid){ continue; } CheckValue<IkReal> x664=IKPowWithIntegerCheck(IKsign(((((-1.0)*x657*x658))+(((-1.0)*x660*x661))+(((-1.0)*x658*x661))+(((-1.0)*x657*x660))+(((0.0203)*cj2*pz))+(((-0.4331)*pz*sj2))+(((-0.4318)*pz)))),-1); if(!x664.valid){ continue; } j1array[0]=((-1.5707963267949)+(x663.value)+(((1.5707963267949)*(x664.value)))); sj1array[0]=IKsin(j1array[0]); cj1array[0]=IKcos(j1array[0]); if( j1array[0] > IKPI ) { j1array[0]-=IK2PI; } else if( j1array[0] < -IKPI ) { j1array[0]+=IK2PI; } j1valid[0] = true; for(int ij1 = 0; ij1 < 1; ++ij1) { if( !j1valid[ij1] ) { continue; } _ij1[0] = ij1; _ij1[1] = -1; for(int iij1 = ij1+1; iij1 < 1; ++iij1) { if( j1valid[iij1] && IKabs(cj1array[ij1]-cj1array[iij1]) < IKFAST_SOLUTION_THRESH && IKabs(sj1array[ij1]-sj1array[iij1]) < IKFAST_SOLUTION_THRESH ) { j1valid[iij1]=false; _ij1[1] = iij1; break; } } j1 = j1array[ij1]; cj1 = cj1array[ij1]; sj1 = sj1array[ij1]; { IkReal evalcond[5]; IkReal x665=IKsin(j1); IkReal x666=IKcos(j1); IkReal x667=((0.4331)*sj2); IkReal x668=(cj0*px); IkReal x669=((0.4331)*cj2); IkReal x670=(py*sj0); IkReal x671=((0.0203)*cj2); IkReal x672=((0.0203)*sj2); IkReal x673=((1.0)*x666); IkReal x674=((0.0203)*x665); IkReal x675=(pz*x665); IkReal x676=((0.8636)*x666); evalcond[0]=(((x665*x670))+((x665*x668))+(((-1.0)*x669))+((pz*x666))+(((-1.0)*x672))); evalcond[1]=((0.02406647)+((x670*x676))+(((-1.0)*pp))+(((-0.8636)*x675))+((x668*x676))); evalcond[2]=((0.4318)+(((-1.0)*x668*x673))+(((-1.0)*x670*x673))+x667+x675+(((-1.0)*x671))); evalcond[3]=(((x665*x667))+(((0.4318)*x665))+(((-1.0)*x665*x671))+(((-1.0)*x666*x672))+pz+(((-1.0)*x666*x669))); evalcond[4]=(((x666*x667))+((x665*x672))+((x665*x669))+(((0.4318)*x666))+(((-1.0)*x668))+(((-1.0)*x666*x671))+(((-1.0)*x670))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH ) { continue; } } rotationfunction0(solutions); } } } } } } } } } } } return solutions.GetNumSolutions()>0; } inline void rotationfunction0(IkSolutionListBase<IkReal>& solutions) { for(int rotationiter = 0; rotationiter < 1; ++rotationiter) { IkReal x83=(cj0*r00); IkReal x84=(cj0*r01); IkReal x85=((1.0)*sj1); IkReal x86=((1.0)*sj0); IkReal x87=(r11*sj0); IkReal x88=(cj1*sj2); IkReal x89=(cj0*r02); IkReal x90=((((-1.0)*sj2*x85))+((cj1*cj2))); IkReal x91=(((cj2*sj1))+x88); IkReal x92=(cj0*x90); IkReal x93=(sj0*x90); IkReal x94=(sj0*x91); IkReal x95=((((-1.0)*x88))+(((-1.0)*cj2*x85))); new_r00=(((r10*x93))+((r20*x95))+((x83*x90))); new_r01=(((r21*x95))+((x87*x90))+((x84*x90))); new_r02=(((r12*x93))+((x89*x90))+((r22*x95))); new_r10=((((-1.0)*r00*x86))+((cj0*r10))); new_r11=(((cj0*r11))+(((-1.0)*r01*x86))); new_r12=((((-1.0)*r02*x86))+((cj0*r12))); new_r20=(((r10*x94))+((r20*x90))+((x83*x91))); new_r21=(((r21*x90))+((x87*x91))+((x84*x91))); new_r22=(((r12*x94))+((x89*x91))+((r22*x90))); { IkReal j4array[2], cj4array[2], sj4array[2]; bool j4valid[2]={false}; _nj4 = 2; cj4array[0]=new_r22; if( cj4array[0] >= -1-IKFAST_SINCOS_THRESH && cj4array[0] <= 1+IKFAST_SINCOS_THRESH ) { j4valid[0] = j4valid[1] = true; j4array[0] = IKacos(cj4array[0]); sj4array[0] = IKsin(j4array[0]); cj4array[1] = cj4array[0]; j4array[1] = -j4array[0]; sj4array[1] = -sj4array[0]; } else if( isnan(cj4array[0]) ) { // probably any value will work j4valid[0] = true; cj4array[0] = 1; sj4array[0] = 0; j4array[0] = 0; } for(int ij4 = 0; ij4 < 2; ++ij4) { if( !j4valid[ij4] ) { continue; } _ij4[0] = ij4; _ij4[1] = -1; for(int iij4 = ij4+1; iij4 < 2; ++iij4) { if( j4valid[iij4] && IKabs(cj4array[ij4]-cj4array[iij4]) < IKFAST_SOLUTION_THRESH && IKabs(sj4array[ij4]-sj4array[iij4]) < IKFAST_SOLUTION_THRESH ) { j4valid[iij4]=false; _ij4[1] = iij4; break; } } j4 = j4array[ij4]; cj4 = cj4array[ij4]; sj4 = sj4array[ij4]; { IkReal j3eval[2]; IkReal x96=(cj0*r00); IkReal x97=(cj0*r01); IkReal x98=((1.0)*sj1); IkReal x99=((1.0)*sj0); IkReal x100=(r11*sj0); IkReal x101=(cj1*sj2); IkReal x102=(cj0*r02); IkReal x103=x90; IkReal x104=(((cj2*sj1))+x101); IkReal x105=(cj0*x103); IkReal x106=(sj0*x103); IkReal x107=(sj0*x104); IkReal x108=x95; new_r00=(((r10*x106))+((x103*x96))+((r20*x108))); new_r01=(((x103*x97))+((r21*x108))+((x100*x103))); new_r02=(((r22*x108))+((x102*x103))+((r12*x106))); new_r10=(((cj0*r10))+(((-1.0)*r00*x99))); new_r11=((((-1.0)*r01*x99))+((cj0*r11))); new_r12=(((cj0*r12))+(((-1.0)*r02*x99))); new_r20=(((r10*x107))+((r20*x103))+((x104*x96))); new_r21=(((r21*x103))+((x104*x97))+((x100*x104))); new_r22=(((r22*x103))+((x102*x104))+((r12*x107))); j3eval[0]=sj4; j3eval[1]=IKsign(sj4); if( IKabs(j3eval[0]) < 0.0000010000000000 || IKabs(j3eval[1]) < 0.0000010000000000 ) { { IkReal j3eval[1]; IkReal x109=(cj0*r00); IkReal x110=(cj0*r01); IkReal x111=((1.0)*sj1); IkReal x112=((1.0)*sj0); IkReal x113=(r11*sj0); IkReal x114=(cj1*sj2); IkReal x115=(cj0*r02); IkReal x116=x90; IkReal x117=(((cj2*sj1))+x114); IkReal x118=(cj0*x116); IkReal x119=(sj0*x116); IkReal x120=(sj0*x117); IkReal x121=x95; new_r00=(((r10*x119))+((x109*x116))+((r20*x121))); new_r01=(((x110*x116))+((r21*x121))+((x113*x116))); new_r02=(((r22*x121))+((r12*x119))+((x115*x116))); new_r10=((((-1.0)*r00*x112))+((cj0*r10))); new_r11=((((-1.0)*r01*x112))+((cj0*r11))); new_r12=((((-1.0)*r02*x112))+((cj0*r12))); new_r20=(((x109*x117))+((r20*x116))+((r10*x120))); new_r21=(((x110*x117))+((x113*x117))+((r21*x116))); new_r22=(((r22*x116))+((r12*x120))+((x115*x117))); j3eval[0]=sj4; if( IKabs(j3eval[0]) < 0.0000010000000000 ) { { IkReal evalcond[6]; bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(j4))), 6.28318530717959))); evalcond[1]=((-1.0)+new_r22); evalcond[2]=new_r20; evalcond[3]=new_r02; evalcond[4]=new_r12; evalcond[5]=new_r21; if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 && IKabs(evalcond[4]) < 0.0000010000000000 && IKabs(evalcond[5]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j3array[2], cj3array[2], sj3array[2]; bool j3valid[2]={false}; _nj3 = 2; CheckValue<IkReal> x123 = IKatan2WithCheck(IkReal(new_r02),new_r12,IKFAST_ATAN2_MAGTHRESH); if(!x123.valid){ continue; } IkReal x122=x123.value; j3array[0]=((-1.0)*x122); sj3array[0]=IKsin(j3array[0]); cj3array[0]=IKcos(j3array[0]); j3array[1]=((3.14159265358979)+(((-1.0)*x122))); sj3array[1]=IKsin(j3array[1]); cj3array[1]=IKcos(j3array[1]); if( j3array[0] > IKPI ) { j3array[0]-=IK2PI; } else if( j3array[0] < -IKPI ) { j3array[0]+=IK2PI; } j3valid[0] = true; if( j3array[1] > IKPI ) { j3array[1]-=IK2PI; } else if( j3array[1] < -IKPI ) { j3array[1]+=IK2PI; } j3valid[1] = true; for(int ij3 = 0; ij3 < 2; ++ij3) { if( !j3valid[ij3] ) { continue; } _ij3[0] = ij3; _ij3[1] = -1; for(int iij3 = ij3+1; iij3 < 2; ++iij3) { if( j3valid[iij3] && IKabs(cj3array[ij3]-cj3array[iij3]) < IKFAST_SOLUTION_THRESH && IKabs(sj3array[ij3]-sj3array[iij3]) < IKFAST_SOLUTION_THRESH ) { j3valid[iij3]=false; _ij3[1] = iij3; break; } } j3 = j3array[ij3]; cj3 = cj3array[ij3]; sj3 = sj3array[ij3]; { IkReal evalcond[1]; evalcond[0]=((((-1.0)*new_r02*(IKsin(j3))))+((new_r12*(IKcos(j3))))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH ) { continue; } } { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; IkReal x124=((1.0)*new_r01); if( IKabs(((((-1.0)*cj3*x124))+(((-1.0)*new_r00*sj3)))) < IKFAST_ATAN2_MAGTHRESH && IKabs(((((-1.0)*sj3*x124))+((cj3*new_r00)))) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((((-1.0)*cj3*x124))+(((-1.0)*new_r00*sj3))))+IKsqr(((((-1.0)*sj3*x124))+((cj3*new_r00))))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((((-1.0)*cj3*x124))+(((-1.0)*new_r00*sj3))), ((((-1.0)*sj3*x124))+((cj3*new_r00)))); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x125=IKsin(j5); IkReal x126=IKcos(j5); IkReal x127=((1.0)*sj3); IkReal x128=((1.0)*x126); IkReal x129=(sj3*x125); IkReal x130=((1.0)*x125); IkReal x131=(cj3*x128); evalcond[0]=(((new_r11*sj3))+x125+((cj3*new_r01))); evalcond[1]=(((cj3*x125))+((sj3*x126))+new_r01); evalcond[2]=(((new_r10*sj3))+(((-1.0)*x128))+((cj3*new_r00))); evalcond[3]=((((-1.0)*new_r00*x127))+(((-1.0)*x130))+((cj3*new_r10))); evalcond[4]=((((-1.0)*new_r01*x127))+(((-1.0)*x128))+((cj3*new_r11))); evalcond[5]=(x129+(((-1.0)*x131))+new_r00); evalcond[6]=(x129+(((-1.0)*x131))+new_r11); evalcond[7]=((((-1.0)*x126*x127))+(((-1.0)*cj3*x130))+new_r10); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-3.14159265358979)+j4)))), 6.28318530717959))); evalcond[1]=((1.0)+new_r22); evalcond[2]=new_r20; evalcond[3]=new_r02; evalcond[4]=new_r12; evalcond[5]=new_r21; if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 && IKabs(evalcond[4]) < 0.0000010000000000 && IKabs(evalcond[5]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j3array[2], cj3array[2], sj3array[2]; bool j3valid[2]={false}; _nj3 = 2; CheckValue<IkReal> x133 = IKatan2WithCheck(IkReal(new_r02),new_r12,IKFAST_ATAN2_MAGTHRESH); if(!x133.valid){ continue; } IkReal x132=x133.value; j3array[0]=((-1.0)*x132); sj3array[0]=IKsin(j3array[0]); cj3array[0]=IKcos(j3array[0]); j3array[1]=((3.14159265358979)+(((-1.0)*x132))); sj3array[1]=IKsin(j3array[1]); cj3array[1]=IKcos(j3array[1]); if( j3array[0] > IKPI ) { j3array[0]-=IK2PI; } else if( j3array[0] < -IKPI ) { j3array[0]+=IK2PI; } j3valid[0] = true; if( j3array[1] > IKPI ) { j3array[1]-=IK2PI; } else if( j3array[1] < -IKPI ) { j3array[1]+=IK2PI; } j3valid[1] = true; for(int ij3 = 0; ij3 < 2; ++ij3) { if( !j3valid[ij3] ) { continue; } _ij3[0] = ij3; _ij3[1] = -1; for(int iij3 = ij3+1; iij3 < 2; ++iij3) { if( j3valid[iij3] && IKabs(cj3array[ij3]-cj3array[iij3]) < IKFAST_SOLUTION_THRESH && IKabs(sj3array[ij3]-sj3array[iij3]) < IKFAST_SOLUTION_THRESH ) { j3valid[iij3]=false; _ij3[1] = iij3; break; } } j3 = j3array[ij3]; cj3 = cj3array[ij3]; sj3 = sj3array[ij3]; { IkReal evalcond[1]; evalcond[0]=((((-1.0)*new_r02*(IKsin(j3))))+((new_r12*(IKcos(j3))))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH ) { continue; } } { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; IkReal x134=((1.0)*sj3); if( IKabs(((((-1.0)*new_r00*x134))+((cj3*new_r01)))) < IKFAST_ATAN2_MAGTHRESH && IKabs(((((-1.0)*new_r01*x134))+(((-1.0)*cj3*new_r00)))) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((((-1.0)*new_r00*x134))+((cj3*new_r01))))+IKsqr(((((-1.0)*new_r01*x134))+(((-1.0)*cj3*new_r00))))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((((-1.0)*new_r00*x134))+((cj3*new_r01))), ((((-1.0)*new_r01*x134))+(((-1.0)*cj3*new_r00)))); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x135=IKsin(j5); IkReal x136=IKcos(j5); IkReal x137=((1.0)*sj3); IkReal x138=((1.0)*x135); IkReal x139=(sj3*x136); IkReal x140=((1.0)*x136); IkReal x141=(cj3*x138); evalcond[0]=(((new_r10*sj3))+x136+((cj3*new_r00))); evalcond[1]=(((new_r11*sj3))+(((-1.0)*x138))+((cj3*new_r01))); evalcond[2]=(((cj3*x136))+((sj3*x135))+new_r00); evalcond[3]=((((-1.0)*new_r00*x137))+(((-1.0)*x138))+((cj3*new_r10))); evalcond[4]=((((-1.0)*x140))+(((-1.0)*new_r01*x137))+((cj3*new_r11))); evalcond[5]=((((-1.0)*x141))+x139+new_r01); evalcond[6]=((((-1.0)*x141))+x139+new_r10); evalcond[7]=((((-1.0)*x135*x137))+(((-1.0)*cj3*x140))+new_r11); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { if( 1 ) { bgotonextstatement=false; continue; // branch miss [j3, j5] } } while(0); if( bgotonextstatement ) { } } } } } else { { IkReal j3array[1], cj3array[1], sj3array[1]; bool j3valid[1]={false}; _nj3 = 1; CheckValue<IkReal> x143=IKPowWithIntegerCheck(sj4,-1); if(!x143.valid){ continue; } IkReal x142=x143.value; CheckValue<IkReal> x144=IKPowWithIntegerCheck(new_r12,-1); if(!x144.valid){ continue; } if( IKabs((x142*(x144.value)*(((1.0)+(((-1.0)*(cj4*cj4)))+(((-1.0)*(new_r02*new_r02))))))) < IKFAST_ATAN2_MAGTHRESH && IKabs((new_r02*x142)) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr((x142*(x144.value)*(((1.0)+(((-1.0)*(cj4*cj4)))+(((-1.0)*(new_r02*new_r02)))))))+IKsqr((new_r02*x142))-1) <= IKFAST_SINCOS_THRESH ) continue; j3array[0]=IKatan2((x142*(x144.value)*(((1.0)+(((-1.0)*(cj4*cj4)))+(((-1.0)*(new_r02*new_r02)))))), (new_r02*x142)); sj3array[0]=IKsin(j3array[0]); cj3array[0]=IKcos(j3array[0]); if( j3array[0] > IKPI ) { j3array[0]-=IK2PI; } else if( j3array[0] < -IKPI ) { j3array[0]+=IK2PI; } j3valid[0] = true; for(int ij3 = 0; ij3 < 1; ++ij3) { if( !j3valid[ij3] ) { continue; } _ij3[0] = ij3; _ij3[1] = -1; for(int iij3 = ij3+1; iij3 < 1; ++iij3) { if( j3valid[iij3] && IKabs(cj3array[ij3]-cj3array[iij3]) < IKFAST_SOLUTION_THRESH && IKabs(sj3array[ij3]-sj3array[iij3]) < IKFAST_SOLUTION_THRESH ) { j3valid[iij3]=false; _ij3[1] = iij3; break; } } j3 = j3array[ij3]; cj3 = cj3array[ij3]; sj3 = sj3array[ij3]; { IkReal evalcond[8]; IkReal x145=IKcos(j3); IkReal x146=IKsin(j3); IkReal x147=((1.0)*sj4); IkReal x148=((1.0)*cj4); IkReal x149=(new_r02*x145); IkReal x150=(new_r12*x146); evalcond[0]=((((-1.0)*x145*x147))+new_r02); evalcond[1]=((((-1.0)*x146*x147))+new_r12); evalcond[2]=(((new_r12*x145))+(((-1.0)*new_r02*x146))); evalcond[3]=((((-1.0)*x147))+x150+x149); evalcond[4]=(((cj4*x150))+(((-1.0)*new_r22*x147))+((cj4*x149))); evalcond[5]=((((-1.0)*new_r10*x146*x147))+(((-1.0)*new_r20*x148))+(((-1.0)*new_r00*x145*x147))); evalcond[6]=((((-1.0)*new_r21*x148))+(((-1.0)*new_r11*x146*x147))+(((-1.0)*new_r01*x145*x147))); evalcond[7]=((1.0)+(((-1.0)*new_r22*x148))+(((-1.0)*x147*x149))+(((-1.0)*x147*x150))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { IkReal j5eval[2]; IkReal x151=(cj0*r00); IkReal x152=(cj0*r01); IkReal x153=((1.0)*sj1); IkReal x154=((1.0)*sj0); IkReal x155=(r11*sj0); IkReal x156=(cj1*sj2); IkReal x157=(cj0*r02); IkReal x158=x90; IkReal x159=(((cj2*sj1))+x156); IkReal x160=(cj0*x158); IkReal x161=(sj0*x158); IkReal x162=(sj0*x159); IkReal x163=x95; new_r00=(((r20*x163))+((x151*x158))+((r10*x161))); new_r01=(((x152*x158))+((r21*x163))+((x155*x158))); new_r02=(((r22*x163))+((x157*x158))+((r12*x161))); new_r10=((((-1.0)*r00*x154))+((cj0*r10))); new_r11=((((-1.0)*r01*x154))+((cj0*r11))); new_r12=((((-1.0)*r02*x154))+((cj0*r12))); new_r20=(((r20*x158))+((x151*x159))+((r10*x162))); new_r21=(((x152*x159))+((x155*x159))+((r21*x158))); new_r22=(((x157*x159))+((r12*x162))+((r22*x158))); j5eval[0]=sj4; j5eval[1]=IKsign(sj4); if( IKabs(j5eval[0]) < 0.0000010000000000 || IKabs(j5eval[1]) < 0.0000010000000000 ) { { IkReal j5eval[2]; IkReal x164=(cj0*r00); IkReal x165=(cj0*r01); IkReal x166=((1.0)*sj1); IkReal x167=((1.0)*sj0); IkReal x168=(r11*sj0); IkReal x169=(cj1*sj2); IkReal x170=(cj0*r02); IkReal x171=x90; IkReal x172=(((cj2*sj1))+x169); IkReal x173=(cj0*x171); IkReal x174=(sj0*x171); IkReal x175=(sj0*x172); IkReal x176=x95; new_r00=(((r20*x176))+((x164*x171))+((r10*x174))); new_r01=(((x168*x171))+((r21*x176))+((x165*x171))); new_r02=(((r22*x176))+((x170*x171))+((r12*x174))); new_r10=((((-1.0)*r00*x167))+((cj0*r10))); new_r11=((((-1.0)*r01*x167))+((cj0*r11))); new_r12=((((-1.0)*r02*x167))+((cj0*r12))); new_r20=(((r20*x171))+((x164*x172))+((r10*x175))); new_r21=(((x168*x172))+((r21*x171))+((x165*x172))); new_r22=(((r22*x171))+((x170*x172))+((r12*x175))); j5eval[0]=sj3; j5eval[1]=sj4; if( IKabs(j5eval[0]) < 0.0000010000000000 || IKabs(j5eval[1]) < 0.0000010000000000 ) { { IkReal j5eval[3]; IkReal x177=(cj0*r00); IkReal x178=(cj0*r01); IkReal x179=((1.0)*sj1); IkReal x180=((1.0)*sj0); IkReal x181=(r11*sj0); IkReal x182=(cj1*sj2); IkReal x183=(cj0*r02); IkReal x184=x90; IkReal x185=(((cj2*sj1))+x182); IkReal x186=(cj0*x184); IkReal x187=(sj0*x184); IkReal x188=(sj0*x185); IkReal x189=x95; new_r00=(((x177*x184))+((r20*x189))+((r10*x187))); new_r01=(((x178*x184))+((r21*x189))+((x181*x184))); new_r02=(((r12*x187))+((x183*x184))+((r22*x189))); new_r10=((((-1.0)*r00*x180))+((cj0*r10))); new_r11=((((-1.0)*r01*x180))+((cj0*r11))); new_r12=((((-1.0)*r02*x180))+((cj0*r12))); new_r20=(((x177*x185))+((r20*x184))+((r10*x188))); new_r21=(((x178*x185))+((r21*x184))+((x181*x185))); new_r22=(((r12*x188))+((x183*x185))+((r22*x184))); j5eval[0]=cj3; j5eval[1]=cj4; j5eval[2]=sj4; if( IKabs(j5eval[0]) < 0.0000010000000000 || IKabs(j5eval[1]) < 0.0000010000000000 || IKabs(j5eval[2]) < 0.0000010000000000 ) { { IkReal evalcond[12]; bool bgotonextstatement = true; do { IkReal x190=(new_r22+(((-1.0)*cj4))); IkReal x191=((((-1.0)*sj4))+new_r12); IkReal x192=((1.0)*cj4); IkReal x193=((1.0)*sj4); evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-1.5707963267949)+j3)))), 6.28318530717959))); evalcond[1]=x190; evalcond[2]=x190; evalcond[3]=new_r02; evalcond[4]=x191; evalcond[5]=x191; evalcond[6]=(((cj4*new_r12))+(((-1.0)*new_r22*x193))); evalcond[7]=((((-1.0)*new_r20*x192))+(((-1.0)*new_r10*x193))); evalcond[8]=((((-1.0)*new_r21*x192))+(((-1.0)*new_r11*x193))); evalcond[9]=((1.0)+(((-1.0)*new_r22*x192))+(((-1.0)*new_r12*x193))); if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 && IKabs(evalcond[4]) < 0.0000010000000000 && IKabs(evalcond[5]) < 0.0000010000000000 && IKabs(evalcond[6]) < 0.0000010000000000 && IKabs(evalcond[7]) < 0.0000010000000000 && IKabs(evalcond[8]) < 0.0000010000000000 && IKabs(evalcond[9]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x194 = IKatan2WithCheck(IkReal(new_r21),((-1.0)*new_r20),IKFAST_ATAN2_MAGTHRESH); if(!x194.valid){ continue; } CheckValue<IkReal> x195=IKPowWithIntegerCheck(IKsign(new_r12),-1); if(!x195.valid){ continue; } j5array[0]=((-1.5707963267949)+(x194.value)+(((1.5707963267949)*(x195.value)))); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x196=IKsin(j5); IkReal x197=IKcos(j5); IkReal x198=((1.0)*new_r12); IkReal x199=((1.0)*x197); IkReal x200=((1.0)*x196); evalcond[0]=(((new_r12*x197))+new_r20); evalcond[1]=(((new_r22*x196))+new_r11); evalcond[2]=((((-1.0)*x196*x198))+new_r21); evalcond[3]=((((-1.0)*new_r22*x199))+new_r10); evalcond[4]=((((-1.0)*x200))+(((-1.0)*new_r00))); evalcond[5]=((((-1.0)*x199))+(((-1.0)*new_r01))); evalcond[6]=((((-1.0)*new_r21*x198))+x196+((new_r11*new_r22))); evalcond[7]=((((-1.0)*x199))+(((-1.0)*new_r20*x198))+((new_r10*new_r22))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { IkReal x201=(new_r22+(((-1.0)*cj4))); IkReal x202=((1.0)*cj4); IkReal x203=((1.0)*sj4); evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((1.5707963267949)+j3)))), 6.28318530717959))); evalcond[1]=x201; evalcond[2]=x201; evalcond[3]=new_r02; evalcond[4]=(sj4+new_r12); evalcond[5]=((((-1.0)*x203))+(((-1.0)*new_r12))); evalcond[6]=((((-1.0)*new_r22*x203))+(((-1.0)*new_r12*x202))); evalcond[7]=(((new_r10*sj4))+(((-1.0)*new_r20*x202))); evalcond[8]=((((-1.0)*new_r21*x202))+((new_r11*sj4))); evalcond[9]=((1.0)+(((-1.0)*new_r22*x202))+((new_r12*sj4))); if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 && IKabs(evalcond[4]) < 0.0000010000000000 && IKabs(evalcond[5]) < 0.0000010000000000 && IKabs(evalcond[6]) < 0.0000010000000000 && IKabs(evalcond[7]) < 0.0000010000000000 && IKabs(evalcond[8]) < 0.0000010000000000 && IKabs(evalcond[9]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(new_r00) < IKFAST_ATAN2_MAGTHRESH && IKabs(new_r01) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(new_r00)+IKsqr(new_r01)-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(new_r00, new_r01); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x204=IKsin(j5); IkReal x205=IKcos(j5); IkReal x206=((1.0)*new_r11); IkReal x207=((1.0)*new_r10); IkReal x208=((1.0)*x205); evalcond[0]=(((new_r12*x204))+new_r21); evalcond[1]=(new_r00+(((-1.0)*x204))); evalcond[2]=((((-1.0)*x208))+new_r01); evalcond[3]=((((-1.0)*new_r12*x208))+new_r20); evalcond[4]=((((-1.0)*x206))+((new_r22*x204))); evalcond[5]=((((-1.0)*new_r22*x208))+(((-1.0)*x207))); evalcond[6]=((((-1.0)*new_r22*x206))+((new_r12*new_r21))+x204); evalcond[7]=((((-1.0)*new_r22*x207))+(((-1.0)*x208))+((new_r12*new_r20))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { IkReal x209=(new_r12*sj3); IkReal x210=(new_r11*sj3); IkReal x211=((1.0)*sj3); IkReal x212=((1.0)*cj3); IkReal x213=((((-1.0)*new_r02*x211))+((cj3*new_r12))); evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-1.5707963267949)+j4)))), 6.28318530717959))); evalcond[1]=new_r22; evalcond[2]=(new_r02+(((-1.0)*x212))); evalcond[3]=(new_r12+(((-1.0)*x211))); evalcond[4]=x213; evalcond[5]=x213; evalcond[6]=((-1.0)+x209+((cj3*new_r02))); evalcond[7]=(x210+((cj3*new_r01))); evalcond[8]=(((new_r10*sj3))+((cj3*new_r00))); evalcond[9]=((((-1.0)*new_r10*x211))+(((-1.0)*new_r00*x212))); evalcond[10]=((((-1.0)*x210))+(((-1.0)*new_r01*x212))); evalcond[11]=((1.0)+(((-1.0)*new_r02*x212))+(((-1.0)*x209))); if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 && IKabs(evalcond[4]) < 0.0000010000000000 && IKabs(evalcond[5]) < 0.0000010000000000 && IKabs(evalcond[6]) < 0.0000010000000000 && IKabs(evalcond[7]) < 0.0000010000000000 && IKabs(evalcond[8]) < 0.0000010000000000 && IKabs(evalcond[9]) < 0.0000010000000000 && IKabs(evalcond[10]) < 0.0000010000000000 && IKabs(evalcond[11]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(new_r21) < IKFAST_ATAN2_MAGTHRESH && IKabs(((-1.0)*new_r20)) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(new_r21)+IKsqr(((-1.0)*new_r20))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(new_r21, ((-1.0)*new_r20)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x214=IKcos(j5); IkReal x215=IKsin(j5); IkReal x216=((1.0)*new_r12); IkReal x217=((1.0)*x215); IkReal x218=((1.0)*x214); evalcond[0]=(x214+new_r20); evalcond[1]=(new_r21+(((-1.0)*x217))); evalcond[2]=(new_r01+((new_r12*x214))); evalcond[3]=(new_r00+((new_r12*x215))); evalcond[4]=((((-1.0)*new_r02*x218))+new_r11); evalcond[5]=((((-1.0)*new_r02*x217))+new_r10); evalcond[6]=(((new_r02*new_r10))+(((-1.0)*x217))+(((-1.0)*new_r00*x216))); evalcond[7]=((((-1.0)*new_r01*x216))+((new_r02*new_r11))+(((-1.0)*x218))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { IkReal x219=((((-1.0)*new_r02*sj3))+((cj3*new_r12))); IkReal x220=(((new_r10*sj3))+((cj3*new_r00))); IkReal x221=(((new_r11*sj3))+((cj3*new_r01))); IkReal x222=((1.0)+((new_r12*sj3))+((cj3*new_r02))); evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((1.5707963267949)+j4)))), 6.28318530717959))); evalcond[1]=new_r22; evalcond[2]=(cj3+new_r02); evalcond[3]=(sj3+new_r12); evalcond[4]=x219; evalcond[5]=x219; evalcond[6]=x222; evalcond[7]=x221; evalcond[8]=x220; evalcond[9]=x220; evalcond[10]=x221; evalcond[11]=x222; if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 && IKabs(evalcond[4]) < 0.0000010000000000 && IKabs(evalcond[5]) < 0.0000010000000000 && IKabs(evalcond[6]) < 0.0000010000000000 && IKabs(evalcond[7]) < 0.0000010000000000 && IKabs(evalcond[8]) < 0.0000010000000000 && IKabs(evalcond[9]) < 0.0000010000000000 && IKabs(evalcond[10]) < 0.0000010000000000 && IKabs(evalcond[11]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(((-1.0)*new_r21)) < IKFAST_ATAN2_MAGTHRESH && IKabs(new_r20) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((-1.0)*new_r21))+IKsqr(new_r20)-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((-1.0)*new_r21), new_r20); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x223=IKcos(j5); IkReal x224=IKsin(j5); IkReal x225=((1.0)*new_r02); IkReal x226=((1.0)*x223); IkReal x227=((1.0)*x224); evalcond[0]=(x224+new_r21); evalcond[1]=(new_r20+(((-1.0)*x226))); evalcond[2]=(((new_r02*x223))+new_r11); evalcond[3]=(((new_r02*x224))+new_r10); evalcond[4]=(new_r01+(((-1.0)*new_r12*x226))); evalcond[5]=(new_r00+(((-1.0)*new_r12*x227))); evalcond[6]=((((-1.0)*new_r10*x225))+((new_r00*new_r12))+(((-1.0)*x227))); evalcond[7]=((((-1.0)*new_r11*x225))+((new_r01*new_r12))+(((-1.0)*x226))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { IkReal x228=((((-1.0)*new_r02*sj3))+((cj3*new_r12))); IkReal x229=(((new_r12*sj3))+((cj3*new_r02))); evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(j4))), 6.28318530717959))); evalcond[1]=((-1.0)+new_r22); evalcond[2]=new_r20; evalcond[3]=new_r02; evalcond[4]=new_r12; evalcond[5]=new_r21; evalcond[6]=x228; evalcond[7]=x228; evalcond[8]=x229; evalcond[9]=x229; if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 && IKabs(evalcond[4]) < 0.0000010000000000 && IKabs(evalcond[5]) < 0.0000010000000000 && IKabs(evalcond[6]) < 0.0000010000000000 && IKabs(evalcond[7]) < 0.0000010000000000 && IKabs(evalcond[8]) < 0.0000010000000000 && IKabs(evalcond[9]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; IkReal x230=((1.0)*new_r01); if( IKabs(((((-1.0)*cj3*x230))+(((-1.0)*new_r00*sj3)))) < IKFAST_ATAN2_MAGTHRESH && IKabs((((cj3*new_r00))+(((-1.0)*sj3*x230)))) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((((-1.0)*cj3*x230))+(((-1.0)*new_r00*sj3))))+IKsqr((((cj3*new_r00))+(((-1.0)*sj3*x230))))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((((-1.0)*cj3*x230))+(((-1.0)*new_r00*sj3))), (((cj3*new_r00))+(((-1.0)*sj3*x230)))); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x231=IKsin(j5); IkReal x232=IKcos(j5); IkReal x233=((1.0)*sj3); IkReal x234=((1.0)*x232); IkReal x235=(sj3*x231); IkReal x236=((1.0)*x231); IkReal x237=(cj3*x234); evalcond[0]=(((new_r11*sj3))+x231+((cj3*new_r01))); evalcond[1]=(((cj3*x231))+new_r01+((sj3*x232))); evalcond[2]=(((new_r10*sj3))+(((-1.0)*x234))+((cj3*new_r00))); evalcond[3]=((((-1.0)*x236))+((cj3*new_r10))+(((-1.0)*new_r00*x233))); evalcond[4]=((((-1.0)*x234))+((cj3*new_r11))+(((-1.0)*new_r01*x233))); evalcond[5]=((((-1.0)*x237))+x235+new_r00); evalcond[6]=((((-1.0)*x237))+x235+new_r11); evalcond[7]=((((-1.0)*cj3*x236))+new_r10+(((-1.0)*x232*x233))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { IkReal x238=(new_r12*sj3); IkReal x239=((1.0)*new_r02); IkReal x240=(((cj3*new_r12))+(((-1.0)*sj3*x239))); evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-3.14159265358979)+j4)))), 6.28318530717959))); evalcond[1]=((1.0)+new_r22); evalcond[2]=new_r20; evalcond[3]=new_r02; evalcond[4]=new_r12; evalcond[5]=new_r21; evalcond[6]=x240; evalcond[7]=x240; evalcond[8]=(x238+((cj3*new_r02))); evalcond[9]=((((-1.0)*cj3*x239))+(((-1.0)*x238))); if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 && IKabs(evalcond[4]) < 0.0000010000000000 && IKabs(evalcond[5]) < 0.0000010000000000 && IKabs(evalcond[6]) < 0.0000010000000000 && IKabs(evalcond[7]) < 0.0000010000000000 && IKabs(evalcond[8]) < 0.0000010000000000 && IKabs(evalcond[9]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; IkReal x241=((1.0)*sj3); if( IKabs(((((-1.0)*new_r00*x241))+((cj3*new_r01)))) < IKFAST_ATAN2_MAGTHRESH && IKabs(((((-1.0)*new_r01*x241))+(((-1.0)*cj3*new_r00)))) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((((-1.0)*new_r00*x241))+((cj3*new_r01))))+IKsqr(((((-1.0)*new_r01*x241))+(((-1.0)*cj3*new_r00))))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((((-1.0)*new_r00*x241))+((cj3*new_r01))), ((((-1.0)*new_r01*x241))+(((-1.0)*cj3*new_r00)))); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x242=IKsin(j5); IkReal x243=IKcos(j5); IkReal x244=((1.0)*sj3); IkReal x245=((1.0)*x242); IkReal x246=(sj3*x243); IkReal x247=((1.0)*x243); IkReal x248=(cj3*x245); evalcond[0]=(((new_r10*sj3))+x243+((cj3*new_r00))); evalcond[1]=(((new_r11*sj3))+((cj3*new_r01))+(((-1.0)*x245))); evalcond[2]=(((sj3*x242))+new_r00+((cj3*x243))); evalcond[3]=((((-1.0)*new_r00*x244))+((cj3*new_r10))+(((-1.0)*x245))); evalcond[4]=((((-1.0)*new_r01*x244))+((cj3*new_r11))+(((-1.0)*x247))); evalcond[5]=(x246+(((-1.0)*x248))+new_r01); evalcond[6]=(x246+(((-1.0)*x248))+new_r10); evalcond[7]=((((-1.0)*x242*x244))+(((-1.0)*cj3*x247))+new_r11); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { IkReal x249=(new_r22+(((-1.0)*cj4))); IkReal x250=((((-1.0)*sj4))+new_r02); IkReal x251=((1.0)*cj4); IkReal x252=((1.0)*sj4); evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(j3))), 6.28318530717959))); evalcond[1]=x249; evalcond[2]=x249; evalcond[3]=x250; evalcond[4]=new_r12; evalcond[5]=x250; evalcond[6]=(((cj4*new_r02))+(((-1.0)*new_r22*x252))); evalcond[7]=((((-1.0)*new_r20*x251))+(((-1.0)*new_r00*x252))); evalcond[8]=((((-1.0)*new_r21*x251))+(((-1.0)*new_r01*x252))); evalcond[9]=((1.0)+(((-1.0)*new_r22*x251))+(((-1.0)*new_r02*x252))); if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 && IKabs(evalcond[4]) < 0.0000010000000000 && IKabs(evalcond[5]) < 0.0000010000000000 && IKabs(evalcond[6]) < 0.0000010000000000 && IKabs(evalcond[7]) < 0.0000010000000000 && IKabs(evalcond[8]) < 0.0000010000000000 && IKabs(evalcond[9]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(new_r10) < IKFAST_ATAN2_MAGTHRESH && IKabs(new_r11) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(new_r10)+IKsqr(new_r11)-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(new_r10, new_r11); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x253=IKcos(j5); IkReal x254=IKsin(j5); IkReal x255=((1.0)*new_r02); IkReal x256=((1.0)*x253); evalcond[0]=(((new_r02*x253))+new_r20); evalcond[1]=(new_r10+(((-1.0)*x254))); evalcond[2]=(new_r11+(((-1.0)*x256))); evalcond[3]=(((new_r22*x254))+new_r01); evalcond[4]=((((-1.0)*x254*x255))+new_r21); evalcond[5]=(new_r00+(((-1.0)*new_r22*x256))); evalcond[6]=((((-1.0)*new_r21*x255))+((new_r01*new_r22))+x254); evalcond[7]=(((new_r00*new_r22))+(((-1.0)*new_r20*x255))+(((-1.0)*x256))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { IkReal x257=(new_r22+(((-1.0)*cj4))); IkReal x258=((1.0)*cj4); IkReal x259=((1.0)*sj4); evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-3.14159265358979)+j3)))), 6.28318530717959))); evalcond[1]=x257; evalcond[2]=x257; evalcond[3]=(sj4+new_r02); evalcond[4]=new_r12; evalcond[5]=((((-1.0)*new_r02))+(((-1.0)*x259))); evalcond[6]=((((-1.0)*new_r22*x259))+(((-1.0)*new_r02*x258))); evalcond[7]=(((new_r00*sj4))+(((-1.0)*new_r20*x258))); evalcond[8]=((((-1.0)*new_r21*x258))+((new_r01*sj4))); evalcond[9]=((1.0)+((new_r02*sj4))+(((-1.0)*new_r22*x258))); if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 && IKabs(evalcond[4]) < 0.0000010000000000 && IKabs(evalcond[5]) < 0.0000010000000000 && IKabs(evalcond[6]) < 0.0000010000000000 && IKabs(evalcond[7]) < 0.0000010000000000 && IKabs(evalcond[8]) < 0.0000010000000000 && IKabs(evalcond[9]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x260 = IKatan2WithCheck(IkReal(((-1.0)*new_r21)),new_r20,IKFAST_ATAN2_MAGTHRESH); if(!x260.valid){ continue; } CheckValue<IkReal> x261=IKPowWithIntegerCheck(IKsign(new_r02),-1); if(!x261.valid){ continue; } j5array[0]=((-1.5707963267949)+(x260.value)+(((1.5707963267949)*(x261.value)))); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x262=IKsin(j5); IkReal x263=IKcos(j5); IkReal x264=((1.0)*new_r00); IkReal x265=((1.0)*new_r01); IkReal x266=((1.0)*x263); evalcond[0]=(new_r21+((new_r02*x262))); evalcond[1]=(new_r20+(((-1.0)*new_r02*x266))); evalcond[2]=((((-1.0)*x262))+(((-1.0)*new_r10))); evalcond[3]=((((-1.0)*new_r11))+(((-1.0)*x266))); evalcond[4]=(((new_r22*x262))+(((-1.0)*x265))); evalcond[5]=((((-1.0)*new_r22*x266))+(((-1.0)*x264))); evalcond[6]=((((-1.0)*new_r22*x265))+x262+((new_r02*new_r21))); evalcond[7]=((((-1.0)*new_r22*x264))+((new_r02*new_r20))+(((-1.0)*x266))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { if( 1 ) { bgotonextstatement=false; continue; // branch miss [j5] } } while(0); if( bgotonextstatement ) { } } } } } } } } } } } else { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x268=IKPowWithIntegerCheck(sj4,-1); if(!x268.valid){ continue; } IkReal x267=x268.value; CheckValue<IkReal> x269=IKPowWithIntegerCheck(cj3,-1); if(!x269.valid){ continue; } CheckValue<IkReal> x270=IKPowWithIntegerCheck(cj4,-1); if(!x270.valid){ continue; } if( IKabs((x267*(x269.value)*(x270.value)*((((new_r20*sj3))+(((-1.0)*new_r01*sj4)))))) < IKFAST_ATAN2_MAGTHRESH && IKabs(((-1.0)*new_r20*x267)) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr((x267*(x269.value)*(x270.value)*((((new_r20*sj3))+(((-1.0)*new_r01*sj4))))))+IKsqr(((-1.0)*new_r20*x267))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2((x267*(x269.value)*(x270.value)*((((new_r20*sj3))+(((-1.0)*new_r01*sj4))))), ((-1.0)*new_r20*x267)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[12]; IkReal x271=IKsin(j5); IkReal x272=IKcos(j5); IkReal x273=(cj3*new_r00); IkReal x274=(cj3*cj4); IkReal x275=(cj4*sj3); IkReal x276=((1.0)*sj3); IkReal x277=((1.0)*sj4); IkReal x278=((1.0)*x272); IkReal x279=(sj3*x271); IkReal x280=((1.0)*x271); evalcond[0]=(new_r20+((sj4*x272))); evalcond[1]=((((-1.0)*x271*x277))+new_r21); evalcond[2]=(((cj4*x271))+((new_r11*sj3))+((cj3*new_r01))); evalcond[3]=((((-1.0)*new_r00*x276))+((cj3*new_r10))+(((-1.0)*x280))); evalcond[4]=((((-1.0)*new_r01*x276))+((cj3*new_r11))+(((-1.0)*x278))); evalcond[5]=(((x271*x274))+((sj3*x272))+new_r01); evalcond[6]=((((-1.0)*cj4*x278))+((new_r10*sj3))+x273); evalcond[7]=((((-1.0)*x274*x278))+x279+new_r00); evalcond[8]=(((x271*x275))+(((-1.0)*cj3*x278))+new_r11); evalcond[9]=((((-1.0)*cj3*x280))+(((-1.0)*x275*x278))+new_r10); evalcond[10]=((((-1.0)*new_r21*x277))+x271+((new_r01*x274))+((new_r11*x275))); evalcond[11]=(((cj4*x273))+(((-1.0)*new_r20*x277))+(((-1.0)*x278))+((new_r10*x275))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[8]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[9]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[10]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[11]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x282=IKPowWithIntegerCheck(sj4,-1); if(!x282.valid){ continue; } IkReal x281=x282.value; CheckValue<IkReal> x283=IKPowWithIntegerCheck(sj3,-1); if(!x283.valid){ continue; } if( IKabs((x281*(x283.value)*(((((-1.0)*cj3*cj4*new_r20))+(((-1.0)*new_r00*sj4)))))) < IKFAST_ATAN2_MAGTHRESH && IKabs(((-1.0)*new_r20*x281)) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr((x281*(x283.value)*(((((-1.0)*cj3*cj4*new_r20))+(((-1.0)*new_r00*sj4))))))+IKsqr(((-1.0)*new_r20*x281))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2((x281*(x283.value)*(((((-1.0)*cj3*cj4*new_r20))+(((-1.0)*new_r00*sj4))))), ((-1.0)*new_r20*x281)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[12]; IkReal x284=IKsin(j5); IkReal x285=IKcos(j5); IkReal x286=(cj3*new_r00); IkReal x287=(cj3*cj4); IkReal x288=(cj4*sj3); IkReal x289=((1.0)*sj3); IkReal x290=((1.0)*sj4); IkReal x291=((1.0)*x285); IkReal x292=(sj3*x284); IkReal x293=((1.0)*x284); evalcond[0]=(new_r20+((sj4*x285))); evalcond[1]=((((-1.0)*x284*x290))+new_r21); evalcond[2]=(((new_r11*sj3))+((cj3*new_r01))+((cj4*x284))); evalcond[3]=((((-1.0)*x293))+(((-1.0)*new_r00*x289))+((cj3*new_r10))); evalcond[4]=((((-1.0)*x291))+(((-1.0)*new_r01*x289))+((cj3*new_r11))); evalcond[5]=(((x284*x287))+((sj3*x285))+new_r01); evalcond[6]=(((new_r10*sj3))+(((-1.0)*cj4*x291))+x286); evalcond[7]=(x292+(((-1.0)*x287*x291))+new_r00); evalcond[8]=(((x284*x288))+(((-1.0)*cj3*x291))+new_r11); evalcond[9]=((((-1.0)*cj3*x293))+(((-1.0)*x288*x291))+new_r10); evalcond[10]=((((-1.0)*new_r21*x290))+x284+((new_r11*x288))+((new_r01*x287))); evalcond[11]=((((-1.0)*new_r20*x290))+(((-1.0)*x291))+((cj4*x286))+((new_r10*x288))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[8]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[9]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[10]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[11]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x294=IKPowWithIntegerCheck(IKsign(sj4),-1); if(!x294.valid){ continue; } CheckValue<IkReal> x295 = IKatan2WithCheck(IkReal(new_r21),((-1.0)*new_r20),IKFAST_ATAN2_MAGTHRESH); if(!x295.valid){ continue; } j5array[0]=((-1.5707963267949)+(((1.5707963267949)*(x294.value)))+(x295.value)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[12]; IkReal x296=IKsin(j5); IkReal x297=IKcos(j5); IkReal x298=(cj3*new_r00); IkReal x299=(cj3*cj4); IkReal x300=(cj4*sj3); IkReal x301=((1.0)*sj3); IkReal x302=((1.0)*sj4); IkReal x303=((1.0)*x297); IkReal x304=(sj3*x296); IkReal x305=((1.0)*x296); evalcond[0]=(((sj4*x297))+new_r20); evalcond[1]=((((-1.0)*x296*x302))+new_r21); evalcond[2]=(((new_r11*sj3))+((cj4*x296))+((cj3*new_r01))); evalcond[3]=(((cj3*new_r10))+(((-1.0)*new_r00*x301))+(((-1.0)*x305))); evalcond[4]=((((-1.0)*new_r01*x301))+((cj3*new_r11))+(((-1.0)*x303))); evalcond[5]=(((x296*x299))+new_r01+((sj3*x297))); evalcond[6]=(((new_r10*sj3))+(((-1.0)*cj4*x303))+x298); evalcond[7]=(x304+(((-1.0)*x299*x303))+new_r00); evalcond[8]=((((-1.0)*cj3*x303))+((x296*x300))+new_r11); evalcond[9]=((((-1.0)*cj3*x305))+new_r10+(((-1.0)*x300*x303))); evalcond[10]=(((new_r11*x300))+(((-1.0)*new_r21*x302))+x296+((new_r01*x299))); evalcond[11]=(((new_r10*x300))+((cj4*x298))+(((-1.0)*new_r20*x302))+(((-1.0)*x303))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[8]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[9]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[10]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[11]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } } } } else { { IkReal j3array[1], cj3array[1], sj3array[1]; bool j3valid[1]={false}; _nj3 = 1; CheckValue<IkReal> x306=IKPowWithIntegerCheck(IKsign(sj4),-1); if(!x306.valid){ continue; } CheckValue<IkReal> x307 = IKatan2WithCheck(IkReal(new_r12),new_r02,IKFAST_ATAN2_MAGTHRESH); if(!x307.valid){ continue; } j3array[0]=((-1.5707963267949)+(((1.5707963267949)*(x306.value)))+(x307.value)); sj3array[0]=IKsin(j3array[0]); cj3array[0]=IKcos(j3array[0]); if( j3array[0] > IKPI ) { j3array[0]-=IK2PI; } else if( j3array[0] < -IKPI ) { j3array[0]+=IK2PI; } j3valid[0] = true; for(int ij3 = 0; ij3 < 1; ++ij3) { if( !j3valid[ij3] ) { continue; } _ij3[0] = ij3; _ij3[1] = -1; for(int iij3 = ij3+1; iij3 < 1; ++iij3) { if( j3valid[iij3] && IKabs(cj3array[ij3]-cj3array[iij3]) < IKFAST_SOLUTION_THRESH && IKabs(sj3array[ij3]-sj3array[iij3]) < IKFAST_SOLUTION_THRESH ) { j3valid[iij3]=false; _ij3[1] = iij3; break; } } j3 = j3array[ij3]; cj3 = cj3array[ij3]; sj3 = sj3array[ij3]; { IkReal evalcond[8]; IkReal x308=IKcos(j3); IkReal x309=IKsin(j3); IkReal x310=((1.0)*sj4); IkReal x311=((1.0)*cj4); IkReal x312=(new_r02*x308); IkReal x313=(new_r12*x309); evalcond[0]=((((-1.0)*x308*x310))+new_r02); evalcond[1]=(new_r12+(((-1.0)*x309*x310))); evalcond[2]=((((-1.0)*new_r02*x309))+((new_r12*x308))); evalcond[3]=(x313+x312+(((-1.0)*x310))); evalcond[4]=(((cj4*x312))+((cj4*x313))+(((-1.0)*new_r22*x310))); evalcond[5]=((((-1.0)*new_r10*x309*x310))+(((-1.0)*new_r00*x308*x310))+(((-1.0)*new_r20*x311))); evalcond[6]=((((-1.0)*new_r21*x311))+(((-1.0)*new_r11*x309*x310))+(((-1.0)*new_r01*x308*x310))); evalcond[7]=((1.0)+(((-1.0)*x310*x313))+(((-1.0)*x310*x312))+(((-1.0)*new_r22*x311))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { IkReal j5eval[2]; IkReal x314=(cj0*r00); IkReal x315=(cj0*r01); IkReal x316=((1.0)*sj1); IkReal x317=((1.0)*sj0); IkReal x318=(r11*sj0); IkReal x319=(cj1*sj2); IkReal x320=(cj0*r02); IkReal x321=x90; IkReal x322=(((cj2*sj1))+x319); IkReal x323=(cj0*x321); IkReal x324=(sj0*x321); IkReal x325=(sj0*x322); IkReal x326=x95; new_r00=(((r20*x326))+((r10*x324))+((x314*x321))); new_r01=(((x318*x321))+((r21*x326))+((x315*x321))); new_r02=(((r12*x324))+((x320*x321))+((r22*x326))); new_r10=((((-1.0)*r00*x317))+((cj0*r10))); new_r11=((((-1.0)*r01*x317))+((cj0*r11))); new_r12=((((-1.0)*r02*x317))+((cj0*r12))); new_r20=(((r20*x321))+((r10*x325))+((x314*x322))); new_r21=(((x318*x322))+((r21*x321))+((x315*x322))); new_r22=(((r12*x325))+((x320*x322))+((r22*x321))); j5eval[0]=sj4; j5eval[1]=IKsign(sj4); if( IKabs(j5eval[0]) < 0.0000010000000000 || IKabs(j5eval[1]) < 0.0000010000000000 ) { { IkReal j5eval[2]; IkReal x327=(cj0*r00); IkReal x328=(cj0*r01); IkReal x329=((1.0)*sj1); IkReal x330=((1.0)*sj0); IkReal x331=(r11*sj0); IkReal x332=(cj1*sj2); IkReal x333=(cj0*r02); IkReal x334=x90; IkReal x335=(((cj2*sj1))+x332); IkReal x336=(cj0*x334); IkReal x337=(sj0*x334); IkReal x338=(sj0*x335); IkReal x339=x95; new_r00=(((r20*x339))+((x327*x334))+((r10*x337))); new_r01=(((x331*x334))+((r21*x339))+((x328*x334))); new_r02=(((r22*x339))+((r12*x337))+((x333*x334))); new_r10=((((-1.0)*r00*x330))+((cj0*r10))); new_r11=((((-1.0)*r01*x330))+((cj0*r11))); new_r12=((((-1.0)*r02*x330))+((cj0*r12))); new_r20=(((r20*x334))+((x327*x335))+((r10*x338))); new_r21=(((x331*x335))+((r21*x334))+((x328*x335))); new_r22=(((r22*x334))+((r12*x338))+((x333*x335))); j5eval[0]=sj3; j5eval[1]=sj4; if( IKabs(j5eval[0]) < 0.0000010000000000 || IKabs(j5eval[1]) < 0.0000010000000000 ) { { IkReal j5eval[3]; IkReal x340=(cj0*r00); IkReal x341=(cj0*r01); IkReal x342=((1.0)*sj1); IkReal x343=((1.0)*sj0); IkReal x344=(r11*sj0); IkReal x345=(cj1*sj2); IkReal x346=(cj0*r02); IkReal x347=x90; IkReal x348=(((cj2*sj1))+x345); IkReal x349=(cj0*x347); IkReal x350=(sj0*x347); IkReal x351=(sj0*x348); IkReal x352=x95; new_r00=(((r10*x350))+((x340*x347))+((r20*x352))); new_r01=(((r21*x352))+((x344*x347))+((x341*x347))); new_r02=(((r12*x350))+((r22*x352))+((x346*x347))); new_r10=((((-1.0)*r00*x343))+((cj0*r10))); new_r11=((((-1.0)*r01*x343))+((cj0*r11))); new_r12=((((-1.0)*r02*x343))+((cj0*r12))); new_r20=(((r10*x351))+((r20*x347))+((x340*x348))); new_r21=(((r21*x347))+((x344*x348))+((x341*x348))); new_r22=(((r12*x351))+((r22*x347))+((x346*x348))); j5eval[0]=cj3; j5eval[1]=cj4; j5eval[2]=sj4; if( IKabs(j5eval[0]) < 0.0000010000000000 || IKabs(j5eval[1]) < 0.0000010000000000 || IKabs(j5eval[2]) < 0.0000010000000000 ) { { IkReal evalcond[12]; bool bgotonextstatement = true; do { IkReal x353=(new_r22+(((-1.0)*cj4))); IkReal x354=((((-1.0)*sj4))+new_r12); IkReal x355=((1.0)*cj4); IkReal x356=((1.0)*sj4); evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-1.5707963267949)+j3)))), 6.28318530717959))); evalcond[1]=x353; evalcond[2]=x353; evalcond[3]=new_r02; evalcond[4]=x354; evalcond[5]=x354; evalcond[6]=((((-1.0)*new_r22*x356))+((cj4*new_r12))); evalcond[7]=((((-1.0)*new_r10*x356))+(((-1.0)*new_r20*x355))); evalcond[8]=((((-1.0)*new_r11*x356))+(((-1.0)*new_r21*x355))); evalcond[9]=((1.0)+(((-1.0)*new_r22*x355))+(((-1.0)*new_r12*x356))); if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 && IKabs(evalcond[4]) < 0.0000010000000000 && IKabs(evalcond[5]) < 0.0000010000000000 && IKabs(evalcond[6]) < 0.0000010000000000 && IKabs(evalcond[7]) < 0.0000010000000000 && IKabs(evalcond[8]) < 0.0000010000000000 && IKabs(evalcond[9]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x357 = IKatan2WithCheck(IkReal(new_r21),((-1.0)*new_r20),IKFAST_ATAN2_MAGTHRESH); if(!x357.valid){ continue; } CheckValue<IkReal> x358=IKPowWithIntegerCheck(IKsign(new_r12),-1); if(!x358.valid){ continue; } j5array[0]=((-1.5707963267949)+(x357.value)+(((1.5707963267949)*(x358.value)))); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x359=IKsin(j5); IkReal x360=IKcos(j5); IkReal x361=((1.0)*new_r12); IkReal x362=((1.0)*x360); IkReal x363=((1.0)*x359); evalcond[0]=(new_r20+((new_r12*x360))); evalcond[1]=(((new_r22*x359))+new_r11); evalcond[2]=((((-1.0)*x359*x361))+new_r21); evalcond[3]=((((-1.0)*new_r22*x362))+new_r10); evalcond[4]=((((-1.0)*x363))+(((-1.0)*new_r00))); evalcond[5]=((((-1.0)*x362))+(((-1.0)*new_r01))); evalcond[6]=(x359+((new_r11*new_r22))+(((-1.0)*new_r21*x361))); evalcond[7]=((((-1.0)*new_r20*x361))+(((-1.0)*x362))+((new_r10*new_r22))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { IkReal x364=(new_r22+(((-1.0)*cj4))); IkReal x365=((1.0)*cj4); IkReal x366=((1.0)*sj4); evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((1.5707963267949)+j3)))), 6.28318530717959))); evalcond[1]=x364; evalcond[2]=x364; evalcond[3]=new_r02; evalcond[4]=(sj4+new_r12); evalcond[5]=((((-1.0)*x366))+(((-1.0)*new_r12))); evalcond[6]=((((-1.0)*new_r22*x366))+(((-1.0)*new_r12*x365))); evalcond[7]=((((-1.0)*new_r20*x365))+((new_r10*sj4))); evalcond[8]=(((new_r11*sj4))+(((-1.0)*new_r21*x365))); evalcond[9]=((1.0)+((new_r12*sj4))+(((-1.0)*new_r22*x365))); if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 && IKabs(evalcond[4]) < 0.0000010000000000 && IKabs(evalcond[5]) < 0.0000010000000000 && IKabs(evalcond[6]) < 0.0000010000000000 && IKabs(evalcond[7]) < 0.0000010000000000 && IKabs(evalcond[8]) < 0.0000010000000000 && IKabs(evalcond[9]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(new_r00) < IKFAST_ATAN2_MAGTHRESH && IKabs(new_r01) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(new_r00)+IKsqr(new_r01)-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(new_r00, new_r01); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x367=IKsin(j5); IkReal x368=IKcos(j5); IkReal x369=((1.0)*new_r11); IkReal x370=((1.0)*new_r10); IkReal x371=((1.0)*x368); evalcond[0]=(new_r21+((new_r12*x367))); evalcond[1]=((((-1.0)*x367))+new_r00); evalcond[2]=((((-1.0)*x371))+new_r01); evalcond[3]=((((-1.0)*new_r12*x371))+new_r20); evalcond[4]=(((new_r22*x367))+(((-1.0)*x369))); evalcond[5]=((((-1.0)*x370))+(((-1.0)*new_r22*x371))); evalcond[6]=((((-1.0)*new_r22*x369))+x367+((new_r12*new_r21))); evalcond[7]=((((-1.0)*x371))+(((-1.0)*new_r22*x370))+((new_r12*new_r20))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { IkReal x372=(new_r12*sj3); IkReal x373=(new_r11*sj3); IkReal x374=((1.0)*sj3); IkReal x375=((1.0)*cj3); IkReal x376=(((cj3*new_r12))+(((-1.0)*new_r02*x374))); evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-1.5707963267949)+j4)))), 6.28318530717959))); evalcond[1]=new_r22; evalcond[2]=((((-1.0)*x375))+new_r02); evalcond[3]=((((-1.0)*x374))+new_r12); evalcond[4]=x376; evalcond[5]=x376; evalcond[6]=((-1.0)+x372+((cj3*new_r02))); evalcond[7]=(x373+((cj3*new_r01))); evalcond[8]=(((new_r10*sj3))+((cj3*new_r00))); evalcond[9]=((((-1.0)*new_r00*x375))+(((-1.0)*new_r10*x374))); evalcond[10]=((((-1.0)*x373))+(((-1.0)*new_r01*x375))); evalcond[11]=((1.0)+(((-1.0)*x372))+(((-1.0)*new_r02*x375))); if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 && IKabs(evalcond[4]) < 0.0000010000000000 && IKabs(evalcond[5]) < 0.0000010000000000 && IKabs(evalcond[6]) < 0.0000010000000000 && IKabs(evalcond[7]) < 0.0000010000000000 && IKabs(evalcond[8]) < 0.0000010000000000 && IKabs(evalcond[9]) < 0.0000010000000000 && IKabs(evalcond[10]) < 0.0000010000000000 && IKabs(evalcond[11]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(new_r21) < IKFAST_ATAN2_MAGTHRESH && IKabs(((-1.0)*new_r20)) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(new_r21)+IKsqr(((-1.0)*new_r20))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(new_r21, ((-1.0)*new_r20)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x377=IKcos(j5); IkReal x378=IKsin(j5); IkReal x379=((1.0)*new_r12); IkReal x380=((1.0)*x378); IkReal x381=((1.0)*x377); evalcond[0]=(x377+new_r20); evalcond[1]=((((-1.0)*x380))+new_r21); evalcond[2]=(((new_r12*x377))+new_r01); evalcond[3]=(((new_r12*x378))+new_r00); evalcond[4]=((((-1.0)*new_r02*x381))+new_r11); evalcond[5]=((((-1.0)*new_r02*x380))+new_r10); evalcond[6]=((((-1.0)*new_r00*x379))+(((-1.0)*x380))+((new_r02*new_r10))); evalcond[7]=((((-1.0)*x381))+((new_r02*new_r11))+(((-1.0)*new_r01*x379))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { IkReal x382=((((-1.0)*new_r02*sj3))+((cj3*new_r12))); IkReal x383=(((new_r10*sj3))+((cj3*new_r00))); IkReal x384=(((new_r11*sj3))+((cj3*new_r01))); IkReal x385=((1.0)+((new_r12*sj3))+((cj3*new_r02))); evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((1.5707963267949)+j4)))), 6.28318530717959))); evalcond[1]=new_r22; evalcond[2]=(cj3+new_r02); evalcond[3]=(sj3+new_r12); evalcond[4]=x382; evalcond[5]=x382; evalcond[6]=x385; evalcond[7]=x384; evalcond[8]=x383; evalcond[9]=x383; evalcond[10]=x384; evalcond[11]=x385; if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 && IKabs(evalcond[4]) < 0.0000010000000000 && IKabs(evalcond[5]) < 0.0000010000000000 && IKabs(evalcond[6]) < 0.0000010000000000 && IKabs(evalcond[7]) < 0.0000010000000000 && IKabs(evalcond[8]) < 0.0000010000000000 && IKabs(evalcond[9]) < 0.0000010000000000 && IKabs(evalcond[10]) < 0.0000010000000000 && IKabs(evalcond[11]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(((-1.0)*new_r21)) < IKFAST_ATAN2_MAGTHRESH && IKabs(new_r20) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((-1.0)*new_r21))+IKsqr(new_r20)-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((-1.0)*new_r21), new_r20); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x386=IKcos(j5); IkReal x387=IKsin(j5); IkReal x388=((1.0)*new_r02); IkReal x389=((1.0)*x386); IkReal x390=((1.0)*x387); evalcond[0]=(x387+new_r21); evalcond[1]=((((-1.0)*x389))+new_r20); evalcond[2]=(((new_r02*x386))+new_r11); evalcond[3]=(((new_r02*x387))+new_r10); evalcond[4]=((((-1.0)*new_r12*x389))+new_r01); evalcond[5]=((((-1.0)*new_r12*x390))+new_r00); evalcond[6]=((((-1.0)*new_r10*x388))+(((-1.0)*x390))+((new_r00*new_r12))); evalcond[7]=((((-1.0)*new_r11*x388))+((new_r01*new_r12))+(((-1.0)*x389))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { IkReal x391=((((-1.0)*new_r02*sj3))+((cj3*new_r12))); IkReal x392=(((new_r12*sj3))+((cj3*new_r02))); evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(j4))), 6.28318530717959))); evalcond[1]=((-1.0)+new_r22); evalcond[2]=new_r20; evalcond[3]=new_r02; evalcond[4]=new_r12; evalcond[5]=new_r21; evalcond[6]=x391; evalcond[7]=x391; evalcond[8]=x392; evalcond[9]=x392; if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 && IKabs(evalcond[4]) < 0.0000010000000000 && IKabs(evalcond[5]) < 0.0000010000000000 && IKabs(evalcond[6]) < 0.0000010000000000 && IKabs(evalcond[7]) < 0.0000010000000000 && IKabs(evalcond[8]) < 0.0000010000000000 && IKabs(evalcond[9]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; IkReal x393=((1.0)*new_r01); if( IKabs(((((-1.0)*cj3*x393))+(((-1.0)*new_r00*sj3)))) < IKFAST_ATAN2_MAGTHRESH && IKabs(((((-1.0)*sj3*x393))+((cj3*new_r00)))) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((((-1.0)*cj3*x393))+(((-1.0)*new_r00*sj3))))+IKsqr(((((-1.0)*sj3*x393))+((cj3*new_r00))))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((((-1.0)*cj3*x393))+(((-1.0)*new_r00*sj3))), ((((-1.0)*sj3*x393))+((cj3*new_r00)))); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x394=IKsin(j5); IkReal x395=IKcos(j5); IkReal x396=((1.0)*sj3); IkReal x397=((1.0)*x395); IkReal x398=(sj3*x394); IkReal x399=((1.0)*x394); IkReal x400=(cj3*x397); evalcond[0]=(((new_r11*sj3))+x394+((cj3*new_r01))); evalcond[1]=(((sj3*x395))+((cj3*x394))+new_r01); evalcond[2]=((((-1.0)*x397))+((new_r10*sj3))+((cj3*new_r00))); evalcond[3]=((((-1.0)*x399))+((cj3*new_r10))+(((-1.0)*new_r00*x396))); evalcond[4]=((((-1.0)*new_r01*x396))+(((-1.0)*x397))+((cj3*new_r11))); evalcond[5]=(x398+new_r00+(((-1.0)*x400))); evalcond[6]=(x398+new_r11+(((-1.0)*x400))); evalcond[7]=((((-1.0)*x395*x396))+(((-1.0)*cj3*x399))+new_r10); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { IkReal x401=(new_r12*sj3); IkReal x402=((1.0)*new_r02); IkReal x403=(((cj3*new_r12))+(((-1.0)*sj3*x402))); evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-3.14159265358979)+j4)))), 6.28318530717959))); evalcond[1]=((1.0)+new_r22); evalcond[2]=new_r20; evalcond[3]=new_r02; evalcond[4]=new_r12; evalcond[5]=new_r21; evalcond[6]=x403; evalcond[7]=x403; evalcond[8]=(x401+((cj3*new_r02))); evalcond[9]=((((-1.0)*cj3*x402))+(((-1.0)*x401))); if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 && IKabs(evalcond[4]) < 0.0000010000000000 && IKabs(evalcond[5]) < 0.0000010000000000 && IKabs(evalcond[6]) < 0.0000010000000000 && IKabs(evalcond[7]) < 0.0000010000000000 && IKabs(evalcond[8]) < 0.0000010000000000 && IKabs(evalcond[9]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; IkReal x404=((1.0)*sj3); if( IKabs(((((-1.0)*new_r00*x404))+((cj3*new_r01)))) < IKFAST_ATAN2_MAGTHRESH && IKabs(((((-1.0)*cj3*new_r00))+(((-1.0)*new_r01*x404)))) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(((((-1.0)*new_r00*x404))+((cj3*new_r01))))+IKsqr(((((-1.0)*cj3*new_r00))+(((-1.0)*new_r01*x404))))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(((((-1.0)*new_r00*x404))+((cj3*new_r01))), ((((-1.0)*cj3*new_r00))+(((-1.0)*new_r01*x404)))); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x405=IKsin(j5); IkReal x406=IKcos(j5); IkReal x407=((1.0)*sj3); IkReal x408=((1.0)*x405); IkReal x409=(sj3*x406); IkReal x410=((1.0)*x406); IkReal x411=(cj3*x408); evalcond[0]=(((new_r10*sj3))+x406+((cj3*new_r00))); evalcond[1]=(((new_r11*sj3))+((cj3*new_r01))+(((-1.0)*x408))); evalcond[2]=(((sj3*x405))+new_r00+((cj3*x406))); evalcond[3]=(((cj3*new_r10))+(((-1.0)*new_r00*x407))+(((-1.0)*x408))); evalcond[4]=(((cj3*new_r11))+(((-1.0)*x410))+(((-1.0)*new_r01*x407))); evalcond[5]=(x409+new_r01+(((-1.0)*x411))); evalcond[6]=(x409+new_r10+(((-1.0)*x411))); evalcond[7]=((((-1.0)*cj3*x410))+new_r11+(((-1.0)*x405*x407))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { IkReal x412=(new_r22+(((-1.0)*cj4))); IkReal x413=((((-1.0)*sj4))+new_r02); IkReal x414=((1.0)*cj4); IkReal x415=((1.0)*sj4); evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(j3))), 6.28318530717959))); evalcond[1]=x412; evalcond[2]=x412; evalcond[3]=x413; evalcond[4]=new_r12; evalcond[5]=x413; evalcond[6]=(((cj4*new_r02))+(((-1.0)*new_r22*x415))); evalcond[7]=((((-1.0)*new_r20*x414))+(((-1.0)*new_r00*x415))); evalcond[8]=((((-1.0)*new_r21*x414))+(((-1.0)*new_r01*x415))); evalcond[9]=((1.0)+(((-1.0)*new_r02*x415))+(((-1.0)*new_r22*x414))); if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 && IKabs(evalcond[4]) < 0.0000010000000000 && IKabs(evalcond[5]) < 0.0000010000000000 && IKabs(evalcond[6]) < 0.0000010000000000 && IKabs(evalcond[7]) < 0.0000010000000000 && IKabs(evalcond[8]) < 0.0000010000000000 && IKabs(evalcond[9]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; if( IKabs(new_r10) < IKFAST_ATAN2_MAGTHRESH && IKabs(new_r11) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr(new_r10)+IKsqr(new_r11)-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2(new_r10, new_r11); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x416=IKcos(j5); IkReal x417=IKsin(j5); IkReal x418=((1.0)*new_r02); IkReal x419=((1.0)*x416); evalcond[0]=(new_r20+((new_r02*x416))); evalcond[1]=(new_r10+(((-1.0)*x417))); evalcond[2]=(new_r11+(((-1.0)*x419))); evalcond[3]=(((new_r22*x417))+new_r01); evalcond[4]=((((-1.0)*x417*x418))+new_r21); evalcond[5]=(new_r00+(((-1.0)*new_r22*x419))); evalcond[6]=(((new_r01*new_r22))+x417+(((-1.0)*new_r21*x418))); evalcond[7]=(((new_r00*new_r22))+(((-1.0)*new_r20*x418))+(((-1.0)*x419))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { IkReal x420=(new_r22+(((-1.0)*cj4))); IkReal x421=((1.0)*cj4); IkReal x422=((1.0)*sj4); evalcond[0]=((-3.14159265358979)+(IKfmod(((3.14159265358979)+(IKabs(((-3.14159265358979)+j3)))), 6.28318530717959))); evalcond[1]=x420; evalcond[2]=x420; evalcond[3]=(sj4+new_r02); evalcond[4]=new_r12; evalcond[5]=((((-1.0)*x422))+(((-1.0)*new_r02))); evalcond[6]=((((-1.0)*new_r22*x422))+(((-1.0)*new_r02*x421))); evalcond[7]=(((new_r00*sj4))+(((-1.0)*new_r20*x421))); evalcond[8]=(((new_r01*sj4))+(((-1.0)*new_r21*x421))); evalcond[9]=((1.0)+((new_r02*sj4))+(((-1.0)*new_r22*x421))); if( IKabs(evalcond[0]) < 0.0000010000000000 && IKabs(evalcond[1]) < 0.0000010000000000 && IKabs(evalcond[2]) < 0.0000010000000000 && IKabs(evalcond[3]) < 0.0000010000000000 && IKabs(evalcond[4]) < 0.0000010000000000 && IKabs(evalcond[5]) < 0.0000010000000000 && IKabs(evalcond[6]) < 0.0000010000000000 && IKabs(evalcond[7]) < 0.0000010000000000 && IKabs(evalcond[8]) < 0.0000010000000000 && IKabs(evalcond[9]) < 0.0000010000000000 ) { bgotonextstatement=false; { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x423 = IKatan2WithCheck(IkReal(((-1.0)*new_r21)),new_r20,IKFAST_ATAN2_MAGTHRESH); if(!x423.valid){ continue; } CheckValue<IkReal> x424=IKPowWithIntegerCheck(IKsign(new_r02),-1); if(!x424.valid){ continue; } j5array[0]=((-1.5707963267949)+(x423.value)+(((1.5707963267949)*(x424.value)))); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[8]; IkReal x425=IKsin(j5); IkReal x426=IKcos(j5); IkReal x427=((1.0)*new_r00); IkReal x428=((1.0)*new_r01); IkReal x429=((1.0)*x426); evalcond[0]=(new_r21+((new_r02*x425))); evalcond[1]=((((-1.0)*new_r02*x429))+new_r20); evalcond[2]=((((-1.0)*x425))+(((-1.0)*new_r10))); evalcond[3]=((((-1.0)*x429))+(((-1.0)*new_r11))); evalcond[4]=(((new_r22*x425))+(((-1.0)*x428))); evalcond[5]=((((-1.0)*new_r22*x429))+(((-1.0)*x427))); evalcond[6]=((((-1.0)*new_r22*x428))+x425+((new_r02*new_r21))); evalcond[7]=((((-1.0)*new_r22*x427))+(((-1.0)*x429))+((new_r02*new_r20))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } while(0); if( bgotonextstatement ) { bool bgotonextstatement = true; do { if( 1 ) { bgotonextstatement=false; continue; // branch miss [j5] } } while(0); if( bgotonextstatement ) { } } } } } } } } } } } else { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x431=IKPowWithIntegerCheck(sj4,-1); if(!x431.valid){ continue; } IkReal x430=x431.value; CheckValue<IkReal> x432=IKPowWithIntegerCheck(cj3,-1); if(!x432.valid){ continue; } CheckValue<IkReal> x433=IKPowWithIntegerCheck(cj4,-1); if(!x433.valid){ continue; } if( IKabs((x430*(x432.value)*(x433.value)*((((new_r20*sj3))+(((-1.0)*new_r01*sj4)))))) < IKFAST_ATAN2_MAGTHRESH && IKabs(((-1.0)*new_r20*x430)) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr((x430*(x432.value)*(x433.value)*((((new_r20*sj3))+(((-1.0)*new_r01*sj4))))))+IKsqr(((-1.0)*new_r20*x430))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2((x430*(x432.value)*(x433.value)*((((new_r20*sj3))+(((-1.0)*new_r01*sj4))))), ((-1.0)*new_r20*x430)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[12]; IkReal x434=IKsin(j5); IkReal x435=IKcos(j5); IkReal x436=(cj3*new_r00); IkReal x437=(cj3*cj4); IkReal x438=(cj4*sj3); IkReal x439=((1.0)*sj3); IkReal x440=((1.0)*sj4); IkReal x441=((1.0)*x435); IkReal x442=(sj3*x434); IkReal x443=((1.0)*x434); evalcond[0]=(((sj4*x435))+new_r20); evalcond[1]=((((-1.0)*x434*x440))+new_r21); evalcond[2]=(((new_r11*sj3))+((cj4*x434))+((cj3*new_r01))); evalcond[3]=((((-1.0)*new_r00*x439))+(((-1.0)*x443))+((cj3*new_r10))); evalcond[4]=((((-1.0)*x441))+(((-1.0)*new_r01*x439))+((cj3*new_r11))); evalcond[5]=(((x434*x437))+((sj3*x435))+new_r01); evalcond[6]=(((new_r10*sj3))+(((-1.0)*cj4*x441))+x436); evalcond[7]=((((-1.0)*x437*x441))+x442+new_r00); evalcond[8]=((((-1.0)*cj3*x441))+((x434*x438))+new_r11); evalcond[9]=((((-1.0)*x438*x441))+(((-1.0)*cj3*x443))+new_r10); evalcond[10]=(((new_r01*x437))+((new_r11*x438))+x434+(((-1.0)*new_r21*x440))); evalcond[11]=((((-1.0)*x441))+((cj4*x436))+((new_r10*x438))+(((-1.0)*new_r20*x440))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[8]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[9]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[10]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[11]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x445=IKPowWithIntegerCheck(sj4,-1); if(!x445.valid){ continue; } IkReal x444=x445.value; CheckValue<IkReal> x446=IKPowWithIntegerCheck(sj3,-1); if(!x446.valid){ continue; } if( IKabs((x444*(x446.value)*(((((-1.0)*cj3*cj4*new_r20))+(((-1.0)*new_r00*sj4)))))) < IKFAST_ATAN2_MAGTHRESH && IKabs(((-1.0)*new_r20*x444)) < IKFAST_ATAN2_MAGTHRESH && IKabs(IKsqr((x444*(x446.value)*(((((-1.0)*cj3*cj4*new_r20))+(((-1.0)*new_r00*sj4))))))+IKsqr(((-1.0)*new_r20*x444))-1) <= IKFAST_SINCOS_THRESH ) continue; j5array[0]=IKatan2((x444*(x446.value)*(((((-1.0)*cj3*cj4*new_r20))+(((-1.0)*new_r00*sj4))))), ((-1.0)*new_r20*x444)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[12]; IkReal x447=IKsin(j5); IkReal x448=IKcos(j5); IkReal x449=(cj3*new_r00); IkReal x450=(cj3*cj4); IkReal x451=(cj4*sj3); IkReal x452=((1.0)*sj3); IkReal x453=((1.0)*sj4); IkReal x454=((1.0)*x448); IkReal x455=(sj3*x447); IkReal x456=((1.0)*x447); evalcond[0]=(((sj4*x448))+new_r20); evalcond[1]=((((-1.0)*x447*x453))+new_r21); evalcond[2]=(((cj4*x447))+((new_r11*sj3))+((cj3*new_r01))); evalcond[3]=((((-1.0)*new_r00*x452))+(((-1.0)*x456))+((cj3*new_r10))); evalcond[4]=((((-1.0)*new_r01*x452))+(((-1.0)*x454))+((cj3*new_r11))); evalcond[5]=(((x447*x450))+((sj3*x448))+new_r01); evalcond[6]=(((new_r10*sj3))+(((-1.0)*cj4*x454))+x449); evalcond[7]=(x455+(((-1.0)*x450*x454))+new_r00); evalcond[8]=(((x447*x451))+new_r11+(((-1.0)*cj3*x454))); evalcond[9]=((((-1.0)*x451*x454))+new_r10+(((-1.0)*cj3*x456))); evalcond[10]=((((-1.0)*new_r21*x453))+((new_r11*x451))+((new_r01*x450))+x447); evalcond[11]=(((new_r10*x451))+(((-1.0)*new_r20*x453))+((cj4*x449))+(((-1.0)*x454))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[8]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[9]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[10]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[11]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } else { { IkReal j5array[1], cj5array[1], sj5array[1]; bool j5valid[1]={false}; _nj5 = 1; CheckValue<IkReal> x457=IKPowWithIntegerCheck(IKsign(sj4),-1); if(!x457.valid){ continue; } CheckValue<IkReal> x458 = IKatan2WithCheck(IkReal(new_r21),((-1.0)*new_r20),IKFAST_ATAN2_MAGTHRESH); if(!x458.valid){ continue; } j5array[0]=((-1.5707963267949)+(((1.5707963267949)*(x457.value)))+(x458.value)); sj5array[0]=IKsin(j5array[0]); cj5array[0]=IKcos(j5array[0]); if( j5array[0] > IKPI ) { j5array[0]-=IK2PI; } else if( j5array[0] < -IKPI ) { j5array[0]+=IK2PI; } j5valid[0] = true; for(int ij5 = 0; ij5 < 1; ++ij5) { if( !j5valid[ij5] ) { continue; } _ij5[0] = ij5; _ij5[1] = -1; for(int iij5 = ij5+1; iij5 < 1; ++iij5) { if( j5valid[iij5] && IKabs(cj5array[ij5]-cj5array[iij5]) < IKFAST_SOLUTION_THRESH && IKabs(sj5array[ij5]-sj5array[iij5]) < IKFAST_SOLUTION_THRESH ) { j5valid[iij5]=false; _ij5[1] = iij5; break; } } j5 = j5array[ij5]; cj5 = cj5array[ij5]; sj5 = sj5array[ij5]; { IkReal evalcond[12]; IkReal x459=IKsin(j5); IkReal x460=IKcos(j5); IkReal x461=(cj3*new_r00); IkReal x462=(cj3*cj4); IkReal x463=(cj4*sj3); IkReal x464=((1.0)*sj3); IkReal x465=((1.0)*sj4); IkReal x466=((1.0)*x460); IkReal x467=(sj3*x459); IkReal x468=((1.0)*x459); evalcond[0]=(((sj4*x460))+new_r20); evalcond[1]=((((-1.0)*x459*x465))+new_r21); evalcond[2]=(((cj4*x459))+((new_r11*sj3))+((cj3*new_r01))); evalcond[3]=((((-1.0)*x468))+(((-1.0)*new_r00*x464))+((cj3*new_r10))); evalcond[4]=((((-1.0)*new_r01*x464))+(((-1.0)*x466))+((cj3*new_r11))); evalcond[5]=(((sj3*x460))+((x459*x462))+new_r01); evalcond[6]=(((new_r10*sj3))+(((-1.0)*cj4*x466))+x461); evalcond[7]=((((-1.0)*x462*x466))+x467+new_r00); evalcond[8]=(((x459*x463))+new_r11+(((-1.0)*cj3*x466))); evalcond[9]=((((-1.0)*x463*x466))+new_r10+(((-1.0)*cj3*x468))); evalcond[10]=((((-1.0)*new_r21*x465))+((new_r11*x463))+((new_r01*x462))+x459); evalcond[11]=(((cj4*x461))+((new_r10*x463))+(((-1.0)*new_r20*x465))+(((-1.0)*x466))); if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[1]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[2]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[3]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[4]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[5]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[6]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[7]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[8]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[9]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[10]) > IKFAST_EVALCOND_THRESH || IKabs(evalcond[11]) > IKFAST_EVALCOND_THRESH ) { continue; } } { std::vector<IkSingleDOFSolutionBase<IkReal> > vinfos(6); vinfos[0].jointtype = 1; vinfos[0].foffset = j0; vinfos[0].indices[0] = _ij0[0]; vinfos[0].indices[1] = _ij0[1]; vinfos[0].maxsolutions = _nj0; vinfos[1].jointtype = 1; vinfos[1].foffset = j1; vinfos[1].indices[0] = _ij1[0]; vinfos[1].indices[1] = _ij1[1]; vinfos[1].maxsolutions = _nj1; vinfos[2].jointtype = 1; vinfos[2].foffset = j2; vinfos[2].indices[0] = _ij2[0]; vinfos[2].indices[1] = _ij2[1]; vinfos[2].maxsolutions = _nj2; vinfos[3].jointtype = 1; vinfos[3].foffset = j3; vinfos[3].indices[0] = _ij3[0]; vinfos[3].indices[1] = _ij3[1]; vinfos[3].maxsolutions = _nj3; vinfos[4].jointtype = 1; vinfos[4].foffset = j4; vinfos[4].indices[0] = _ij4[0]; vinfos[4].indices[1] = _ij4[1]; vinfos[4].maxsolutions = _nj4; vinfos[5].jointtype = 1; vinfos[5].foffset = j5; vinfos[5].indices[0] = _ij5[0]; vinfos[5].indices[1] = _ij5[1]; vinfos[5].maxsolutions = _nj5; std::vector<int> vfree(0); solutions.AddSolution(vinfos,vfree); } } } } } } } } } } } } }}; /// solves the inverse kinematics equations. /// \param pfree is an array specifying the free joints of the chain. IKFAST_API bool ComputeIk(const IkReal* eetrans, const IkReal* eerot, const IkReal* pfree, IkSolutionListBase<IkReal>& solutions) { IKSolver solver; return solver.ComputeIk(eetrans,eerot,pfree,solutions); } IKFAST_API bool ComputeIk2(const IkReal* eetrans, const IkReal* eerot, const IkReal* pfree, IkSolutionListBase<IkReal>& solutions, void* pOpenRAVEManip) { IKSolver solver; return solver.ComputeIk(eetrans,eerot,pfree,solutions); } IKFAST_API const char* GetKinematicsHash() { return "a6c70e6dd694838553470dde754d5825"; } IKFAST_API const char* GetIkFastVersion() { return "0x10000048"; } #ifdef IKFAST_NAMESPACE } // end namespace #endif #ifndef IKFAST_NO_MAIN #include <stdio.h> #include <stdlib.h> #ifdef IKFAST_NAMESPACE using namespace IKFAST_NAMESPACE; #endif int main(int argc, char** argv) { if( argc != 12+GetNumFreeParameters()+1 ) { printf("\nUsage: ./ik r00 r01 r02 t0 r10 r11 r12 t1 r20 r21 r22 t2 free0 ...\n\n" "Returns the ik solutions given the transformation of the end effector specified by\n" "a 3x3 rotation R (rXX), and a 3x1 translation (tX).\n" "There are %d free parameters that have to be specified.\n\n",GetNumFreeParameters()); return 1; } IkSolutionList<IkReal> solutions; std::vector<IkReal> vfree(GetNumFreeParameters()); IkReal eerot[9],eetrans[3]; eerot[0] = atof(argv[1]); eerot[1] = atof(argv[2]); eerot[2] = atof(argv[3]); eetrans[0] = atof(argv[4]); eerot[3] = atof(argv[5]); eerot[4] = atof(argv[6]); eerot[5] = atof(argv[7]); eetrans[1] = atof(argv[8]); eerot[6] = atof(argv[9]); eerot[7] = atof(argv[10]); eerot[8] = atof(argv[11]); eetrans[2] = atof(argv[12]); for(std::size_t i = 0; i < vfree.size(); ++i) vfree[i] = atof(argv[13+i]); bool bSuccess = ComputeIk(eetrans, eerot, vfree.size() > 0 ? &vfree[0] : NULL, solutions); if( !bSuccess ) { fprintf(stderr,"Failed to get ik solution\n"); return -1; } printf("Found %d ik solutions:\n", (int)solutions.GetNumSolutions()); std::vector<IkReal> solvalues(GetNumJoints()); for(std::size_t i = 0; i < solutions.GetNumSolutions(); ++i) { const IkSolutionBase<IkReal>& sol = solutions.GetSolution(i); printf("sol%d (free=%d): ", (int)i, (int)sol.GetFree().size()); std::vector<IkReal> vsolfree(sol.GetFree().size()); sol.GetSolution(&solvalues[0],vsolfree.size()>0?&vsolfree[0]:NULL); for( std::size_t j = 0; j < solvalues.size(); ++j) printf("%.15f, ", solvalues[j]); printf("\n"); } return 0; } #endif
32.385015
580
0.645046
[ "object", "vector" ]
41fc52344b7d48b4b863e832fea92f0979b0b11a
8,592
cpp
C++
tests/src/slider_parsing.cpp
ShaddyDC/osu_reader
2ddcee93c645b7c68cf8114b1cb954b428d0f8a1
[ "MIT" ]
1
2020-08-16T14:05:13.000Z
2020-08-16T14:05:13.000Z
tests/src/slider_parsing.cpp
ShaddyDC/osu_reader
2ddcee93c645b7c68cf8114b1cb954b428d0f8a1
[ "MIT" ]
1
2020-07-22T16:11:38.000Z
2020-07-22T16:11:38.000Z
tests/src/slider_parsing.cpp
ShaddyDC/osu_reader
2ddcee93c645b7c68cf8114b1cb954b428d0f8a1
[ "MIT" ]
null
null
null
#include <catch2/catch.hpp> #include <hitobject/parse_hitobject.h> #include <osu_reader/sliderpath.h> #include <osu_reader/string_stuff.h> using Segments = std::vector<osu::Slider::Segment>; static bool operator==(const Segments& a, const Segments& b) { if(a.size() != b.size()) return false; for(auto i = 0; i < a.size(); ++i) { if(a[i].type != b[i].type) return false; if(!std::equal(a[i].points.cbegin(), a[i].points.cend(), b[i].points.cbegin(), b[i].points.cend())) return false; } return true; } TEST_CASE("Linear Slider") { const auto slider_string = "1,1,50000,2,0,L|5:1,7,4"; const auto slider_tokens = osu::split(slider_string, ','); const auto slider = parse_slider(slider_tokens); CHECKED_IF(slider) { CHECK(slider->type == osu::Slider::Slider_type::linear); CHECK(slider->length == 4); CHECK(slider->repeat == 7); CHECK(slider->time == std::chrono::milliseconds{50000}); CHECK(slider->segments == Segments{{{{1, 1}, {5, 1}}, osu::Slider::Slider_type::linear}}); } } TEST_CASE("Linear Slider Sanity Test") { const auto slider_string = "1,1,50000,2,0,L|5:1,7,4"; const auto slider_tokens = osu::split(slider_string, ','); const auto slider = parse_slider(slider_tokens); CHECKED_IF(slider) { CHECK(slider->type == osu::Slider::Slider_type::linear); CHECK(slider->length == 4); CHECK(slider->repeat == 7); CHECK(slider->time == std::chrono::milliseconds{50000}); CHECK_FALSE(slider->segments == Segments{{{{1, 1}, {5, 1}, {3, 3}}, osu::Slider::Slider_type::linear}}); } } TEST_CASE("Linear Slider & Linear Slider") { const auto slider_string = "1,1,50000,2,0,L|5:1|L|3:1|6:1,7,9"; const auto slider_tokens = osu::split(slider_string, ','); const auto slider = parse_slider(slider_tokens); CHECKED_IF(slider) { CHECK(slider->type == osu::Slider::Slider_type::linear); CHECK(slider->length == 9); CHECK(slider->repeat == 7); CHECK(slider->time == std::chrono::milliseconds{50000}); CHECK(slider->segments == Segments{{{{1, 1}, {5, 1}}, osu::Slider::Slider_type::linear}, {{{3, 1}, {6, 1}}, osu::Slider::Slider_type::linear}}); } } TEST_CASE("Linear Slider Double Point") { const auto slider_string = "1,1,50000,2,0,L|5:1|3:1|3:1|6:1,7,9"; const auto slider_tokens = osu::split(slider_string, ','); const auto slider = parse_slider(slider_tokens); CHECKED_IF(slider) { CHECK(slider->type == osu::Slider::Slider_type::linear); CHECK(slider->length == 9); CHECK(slider->repeat == 7); CHECK(slider->time == std::chrono::milliseconds{50000}); CHECK(slider->segments == Segments{{{{1, 1}, {5, 1}, {3, 1}}, osu::Slider::Slider_type::linear}, {{{3, 1}, {6, 1}}, osu::Slider::Slider_type::linear}}); } } TEST_CASE("Bezier Slider") { const auto slider_string = "1,1,50000,2,0,B|5:1,7,4"; const auto slider_tokens = osu::split(slider_string, ','); const auto slider = parse_slider(slider_tokens); CHECKED_IF(slider) { CHECK(slider->type == osu::Slider::Slider_type::bezier); CHECK(slider->length == 4); CHECK(slider->repeat == 7); CHECK(slider->time == std::chrono::milliseconds{50000}); CHECK(slider->segments == Segments{{{{1, 1}, {5, 1}}, osu::Slider::Slider_type::bezier}}); } } TEST_CASE("Catmull Slider") { const auto slider_string = "1,1,50000,2,0,C|8:8|5:1,7,4"; const auto slider_tokens = osu::split(slider_string, ','); const auto slider = parse_slider(slider_tokens); CHECKED_IF(slider) { CHECK(slider->type == osu::Slider::Slider_type::catmull); CHECK(slider->length == 4); CHECK(slider->repeat == 7); CHECK(slider->time == std::chrono::milliseconds{50000}); CHECK(slider->segments == Segments{{{{1, 1}, {8, 8}, {5, 1}}, osu::Slider::Slider_type::catmull}}); } } TEST_CASE("Perfect Curve Slider") { const auto slider_string = "1,1,50000,2,0,P|8:8|5:1,7,4"; const auto slider_tokens = osu::split(slider_string, ','); const auto slider = parse_slider(slider_tokens); CHECKED_IF(slider) { CHECK(slider->type == osu::Slider::Slider_type::perfect); CHECK(slider->length == 4); CHECK(slider->repeat == 7); CHECK(slider->time == std::chrono::milliseconds{50000}); CHECK(slider->segments == Segments{{{{1, 1}, {8, 8}, {5, 1}}, osu::Slider::Slider_type::perfect}}); } } TEST_CASE("Perfect Curve Slider with 2 points (bezier)") { const auto slider_string = "1,1,50000,2,0,P|5:1,7,4"; const auto slider_tokens = osu::split(slider_string, ','); const auto slider = parse_slider(slider_tokens); CHECKED_IF(slider) { CHECK(slider->type == osu::Slider::Slider_type::perfect); CHECK(slider->length == 4); CHECK(slider->repeat == 7); CHECK(slider->time == std::chrono::milliseconds{50000}); CHECK(slider->segments == Segments{{{{1, 1}, {5, 1}}, osu::Slider::Slider_type::bezier}}); } } TEST_CASE("Perfect Curve Slider with 4 points (bezier)") { const auto slider_string = "1,1,50000,2,0,P|8:8|9:9|5:1,7,4"; const auto slider_tokens = osu::split(slider_string, ','); const auto slider = parse_slider(slider_tokens); CHECKED_IF(slider) { CHECK(slider->type == osu::Slider::Slider_type::perfect); CHECK(slider->length == 4); CHECK(slider->repeat == 7); CHECK(slider->time == std::chrono::milliseconds{50000}); CHECK(slider->segments == Segments{{{{1, 1}, {8, 8}, {9, 9}, {5, 1}}, osu::Slider::Slider_type::bezier}}); } } TEST_CASE("Perfect Curve Slider co-linear to linear") { const auto slider_string = "1,1,50000,2,0,P|3:1|5:1,7,4"; const auto slider_tokens = osu::split(slider_string, ','); const auto slider = parse_slider(slider_tokens); CHECKED_IF(slider) { CHECK(slider->type == osu::Slider::Slider_type::perfect); CHECK(slider->length == 4); CHECK(slider->repeat == 7); CHECK(slider->time == std::chrono::milliseconds{50000}); CHECK(slider->segments == Segments{{{{1, 1}, {3, 1}, {5, 1}}, osu::Slider::Slider_type::linear}}); } } TEST_CASE("Extend linear slider") { const auto slider_string = "1,1,50000,2,0,L|5:1,7,19"; const auto slider_tokens = osu::split(slider_string, ','); auto slider = parse_slider(slider_tokens); slider->points = osu::sliderpath(slider.value()); slider->distances = osu::pathlengths(slider->points); osu::fix_slider_length(*slider); CHECK(slider->length == slider->distances.back()); CHECK(slider->points.back() == osu::Vector2{20, 1}); } TEST_CASE("Shorten linear slider") { const auto slider_string = "1,1,50000,2,0,L|21:1,7,10"; const auto slider_tokens = osu::split(slider_string, ','); auto slider = parse_slider(slider_tokens); slider->points = osu::sliderpath(slider.value()); slider->distances = osu::pathlengths(slider->points); osu::fix_slider_length(*slider); CHECK(slider->length == slider->distances.back()); CHECK(slider->points.back() == osu::Vector2{11, 1}); } TEST_CASE("Shorten linear slider on point") { const auto slider_string = "1,1,50000,2,0,L|11:1|21:1,7,10"; const auto slider_tokens = osu::split(slider_string, ','); auto slider = parse_slider(slider_tokens); slider->points = osu::sliderpath(slider.value()); slider->distances = osu::pathlengths(slider->points); osu::fix_slider_length(*slider); CHECK(slider->length == slider->distances.back()); CHECK(slider->points.back() == osu::Vector2{11, 1}); } TEST_CASE("Butterfly length") { const auto slider_string = "256,192,74363,118,0,B|208:4|8:8|8:8|40:36|48:63|48:63|44:104|44:104|92:128|76:188|76:188|112:204|152:192|152:192|56:248|32:360|32:360|64:332|100:332|100:332|152:348|196:320|196:320|216:280|256:276|256:276|261:255|261:255|254:246|254:246|259:238|259:238|251:236|251:236|263:225|263:225|253:214|253:214|262:205|262:205|256:201|256:201|256:160,1,1200.0479469394"; const auto slider_tokens = osu::split(slider_string, ','); auto slider = parse_slider(slider_tokens); slider->points = osu::sliderpath(slider.value()); slider->distances = osu::pathlengths(slider->points); osu::fix_slider_length(*slider); CHECK(slider->length == slider->distances.back()); }
36.875536
392
0.623138
[ "vector" ]
eedcfd015ae971be49a13cae28dba46d946f8c9a
2,075
cpp
C++
src/midi_player.cpp
tinaxd/CrossMidiStudio
86addd7b90486110a33b1f5b4ef214e476423a1b
[ "MIT" ]
null
null
null
src/midi_player.cpp
tinaxd/CrossMidiStudio
86addd7b90486110a33b1f5b4ef214e476423a1b
[ "MIT" ]
6
2019-10-24T16:13:31.000Z
2019-10-28T17:34:24.000Z
src/midi_player.cpp
tinaxd/CrossMidiStudio
86addd7b90486110a33b1f5b4ef214e476423a1b
[ "MIT" ]
null
null
null
#include "./midi_player.hpp" using namespace cms; MidiPlayer::MidiPlayer() {} MidiPlayer::~MidiPlayer() { if (midiin != nullptr) { delete midiin; } if (midiout != nullptr) { delete midiout; } } void MidiPlayer::OpenPorts() { midiin = new RtMidiIn(); midiout = new RtMidiOut(); } void MidiPlayer::GetPortInfo(std::vector<std::string> &in, std::vector<std::string> &out) const { if (midiin != nullptr) { int nPorts = midiin->getPortCount(); for (int i = 0; i < nPorts; i++) { in.push_back(midiin->getPortName(i)); } } if (midiout != nullptr) { int nPorts = midiout->getPortCount(); for (int i = 0; i < nPorts; i++) { out.push_back(midiout->getPortName(i)); } } } void MidiPlayer::SetOutputPort(unsigned int portNum) { midiout->openPort(portNum); } void BackgroundMidiPlayer::SetTickOffset(int tick) { this->tick_offset = tick; } BackgroundMidiPlayer::BackgroundMidiPlayer(MidiPlayer *mp) { this->mp.reset(std::move(mp)); } BackgroundMidiPlayer::~BackgroundMidiPlayer() {} void BackgroundMidiPlayer::SetMidiFile(const smf::MidiFile &mf) { this->copied_mf = new smf::MidiFile(mf); copied_mf->doTimeAnalysis(); copied_mf->joinTracks(); copied_mf->absoluteTicks(); } wxThread::ExitCode BackgroundMidiPlayer::Entry() { int offset = 0; if (tick_offset > 0) { for (int i=0; i<(*copied_mf)[0].size(); i++) { if ((*copied_mf)[0][i].tick > tick_offset) { offset = i; break; } } } for (int e = offset; e < (*copied_mf)[0].size(); e++) { if (TestDestroy()) break; smf::MidiEvent *mev = &(*copied_mf)[0][e]; double delta_real; if (e == 0) delta_real = mev->seconds; else delta_real = mev->seconds - (*copied_mf)[0][e - 1].seconds; ISLEEP(delta_real * 1000); std::vector<unsigned char> vec; for (int i = 0; i < mev->size(); i++) { vec.push_back((unsigned char)(*mev)[i]); } mp->SendMessage(vec); } if (copied_mf != nullptr) delete copied_mf; return 0; }
23.314607
67
0.607229
[ "vector" ]
eeddf4a0b3fb5590f1c5847c8a7d6c6d6482b82d
5,591
cpp
C++
Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpBoneImporter.cpp
sandeel31/o3de
db88812d61eef77c6f4451b7f8c7605d6db07412
[ "Apache-2.0", "MIT" ]
1
2021-08-08T19:54:51.000Z
2021-08-08T19:54:51.000Z
Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpBoneImporter.cpp
sandeel31/o3de
db88812d61eef77c6f4451b7f8c7605d6db07412
[ "Apache-2.0", "MIT" ]
null
null
null
Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpBoneImporter.cpp
sandeel31/o3de
db88812d61eef77c6f4451b7f8c7605d6db07412
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <AzCore/Serialization/SerializeContext.h> #include <AzCore/std/smart_ptr/make_shared.h> #include <AzCore/StringFunc/StringFunc.h> #include <AzToolsFramework/Debug/TraceContext.h> #include <SceneAPI/SceneBuilder/SceneSystem.h> #include <SceneAPI/SceneBuilder/Importers/AssImpBoneImporter.h> #include <SceneAPI/SceneBuilder/Importers/AssImpImporterUtilities.h> #include <SceneAPI/SceneBuilder/Importers/ImporterUtilities.h> #include <SceneAPI/SceneCore/Containers/Scene.h> #include <SceneAPI/SceneData/GraphData/BoneData.h> #include <SceneAPI/SceneData/GraphData/RootBoneData.h> #include <SceneAPI/SDKWrapper/AssImpNodeWrapper.h> #include <SceneAPI/SDKWrapper/AssImpSceneWrapper.h> #include <SceneAPI/SDKWrapper/AssImpTypeConverter.h> namespace AZ { namespace SceneAPI { namespace SceneBuilder { AssImpBoneImporter::AssImpBoneImporter() { BindToCall(&AssImpBoneImporter::ImportBone); } void AssImpBoneImporter::Reflect(ReflectContext* context) { SerializeContext* serializeContext = azrtti_cast<SerializeContext*>(context); if (serializeContext) { serializeContext->Class<AssImpBoneImporter, SceneCore::LoadingComponent>()->Version(2); } } aiMatrix4x4 CalculateWorldTransform(const aiNode* currentNode) { aiMatrix4x4 transform = {}; const aiNode* iteratingNode = currentNode; while (iteratingNode) { transform = iteratingNode->mTransformation * transform; iteratingNode = iteratingNode->mParent; } return transform; } Events::ProcessingResult AssImpBoneImporter::ImportBone(AssImpNodeEncounteredContext& context) { AZ_TraceContext("Importer", "Bone"); const aiNode* currentNode = context.m_sourceNode.GetAssImpNode(); const aiScene* scene = context.m_sourceScene.GetAssImpScene(); if (IsPivotNode(currentNode->mName)) { return Events::ProcessingResult::Ignored; } AZStd::unordered_multimap<AZStd::string, const aiBone*> boneByNameMap; FindAllBones(scene, boneByNameMap); bool isBone = FindFirstBoneByNodeName(currentNode, boneByNameMap); if (!isBone) { for(unsigned animIndex = 0; animIndex < scene->mNumAnimations; ++animIndex) { aiAnimation* animation = scene->mAnimations[animIndex]; for (unsigned channelIndex = 0; channelIndex < animation->mNumChannels; ++channelIndex) { aiNodeAnim* nodeAnim = animation->mChannels[channelIndex]; if (nodeAnim->mNodeName == currentNode->mName) { isBone = true; break; } } if (isBone) { break; } } // In case any of the children, or children of children is a bone, make sure to not skip this node. // Don't do this for the scene root itself, else wise all mesh nodes will be exported as bones and pollute the skeleton. if (currentNode != scene->mRootNode && RecursiveHasChildBone(currentNode, boneByNameMap)) { isBone = true; } } if(!isBone) { return Events::ProcessingResult::Ignored; } // If the current scene node (our eventual parent) contains bone data, we are not a root bone AZStd::shared_ptr<SceneData::GraphData::BoneData> createdBoneData; if (NodeHasAncestorOfType( context.m_scene.GetGraph(), context.m_currentGraphPosition, DataTypes::IBoneData::TYPEINFO_Uuid())) { createdBoneData = AZStd::make_shared<SceneData::GraphData::BoneData>(); } else { createdBoneData = AZStd::make_shared<SceneData::GraphData::RootBoneData>(); } aiMatrix4x4 transform = CalculateWorldTransform(currentNode); SceneAPI::DataTypes::MatrixType globalTransform = AssImpSDKWrapper::AssImpTypeConverter::ToTransform(transform); context.m_sourceSceneSystem.SwapTransformForUpAxis(globalTransform); context.m_sourceSceneSystem.ConvertBoneUnit(globalTransform); createdBoneData->SetWorldTransform(globalTransform); context.m_createdData.push_back(AZStd::move(createdBoneData)); return Events::ProcessingResult::Success; } } // namespace SceneBuilder } // namespace SceneAPI } // namespace AZ
39.935714
140
0.563942
[ "mesh", "transform", "3d" ]
eeddf86f4e4c40e572829d11188d4bb2894217af
3,212
cpp
C++
SRC/Geometry/Algebraic/Indexed/SparseArray/SparseArray.cpp
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
SRC/Geometry/Algebraic/Indexed/SparseArray/SparseArray.cpp
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
SRC/Geometry/Algebraic/Indexed/SparseArray/SparseArray.cpp
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
// SparseArray.cpp: implementation the SparseArray class. // Copyright (c) 2017-2018 Extreme Computation Technology and Solutions, LLC // All rights reserved // see file License.txt for license details ////////////////////////////////////////////////////////////////////// #include "./SparseArray.h" namespace Geometry { namespace Algebraic { ////////////////////////////////////////////////////////////////////// // Member methods ////////////////////////////////////////////////////////////////////// SparseArray::SparseArray() {} SparseArray::~SparseArray() {} SparseArray::SparseArray(const SparseArray &A) : map<unsigned int, int>(A) {} SparseArray & SparseArray::operator = (const SparseArray &A) { if (this == &A) return *this; this->empty(); map<unsigned int, int>::operator = (A); return *this; } void SparseArray::operator += (const SparseArray &A) { map<unsigned int, int>::const_iterator pA; for (pA = A.begin(); pA!=A.end(); pA++) (*this)[pA->first] += pA->second; } void SparseArray::operator -= (const SparseArray &A) { map<unsigned int, int>::const_iterator pA; for (pA = A.begin(); pA!=A.end(); pA++) (*this)[pA->first] -= pA->second; } void SparseArray::operator *= (const int &q) { map<unsigned int, int>::iterator pA; for (pA = this->begin(); pA!=this->end(); pA++) pA->second *= q; } void SparseArray::Randomize() { map<unsigned int, int>::iterator pA; for (pA = this->begin(); pA!=this->end(); pA++) pA->second *= (int)rand(); } void SparseArray::print(ostream *os) { map<unsigned int, int>::iterator pMap; for (pMap=this->begin(); pMap!=this->end(); pMap++) *os << pMap->second << ", "; } } } ////////////////////////////////////////////////////////////////////// // Set operators ////////////////////////////////////////////////////////////////////// void Random(Geometry::Algebraic::SparseArray &A){A.Randomize();} ////////////////////////////////////////////////////////////////////// // Algebraic operators ////////////////////////////////////////////////////////////////////// Geometry::Algebraic::SparseArray operator - (const Geometry::Algebraic::SparseArray &A) { Geometry::Algebraic::SparseArray B=A; map<unsigned int, int>::iterator pB; for (pB = B.begin(); pB!=B.end(); pB++) pB->second = -(pB->second); return B; } Geometry::Algebraic::SparseArray operator * (const int &q, const Geometry::Algebraic::SparseArray &A) { Geometry::Algebraic::SparseArray B=A; map<unsigned int, int>::iterator pB; for (pB = B.begin(); pB!=B.end(); pB++) pB->second = q*pB->second; return B; } Geometry::Algebraic::SparseArray operator * (const Geometry::Algebraic::SparseArray &A, const int &q) { Geometry::Algebraic::SparseArray B=A; map<unsigned int, int>::iterator pB; for (pB = B.begin(); pB!=B.end(); pB++) pB->second = q*pB->second; return B; } ////////////////////////////////////////////////////////////////////// // Printing ////////////////////////////////////////////////////////////////////// ostream & operator<<(ostream &os, Geometry::Algebraic::SparseArray &A) { A.print(&os); return os; }
26.327869
77
0.506227
[ "geometry" ]
eedfac5a369addb5908d51908081d15238640ccf
1,162
cpp
C++
tc tournaments/EllysJuice.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
3
2015-05-25T06:24:37.000Z
2016-09-10T07:58:00.000Z
tc tournaments/EllysJuice.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
null
null
null
tc tournaments/EllysJuice.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
5
2015-05-25T06:24:40.000Z
2021-08-19T19:22:29.000Z
#include <algorithm> #include <cassert> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <iostream> #include <sstream> #include <string> #include <vector> #include <set> #include <map> #include <utility> using namespace std; void winner(const vector<string> &P, set<string> &sol) { int t = (1<<(P.size()+2)); int have[2] = {t, t}; map<string, int> M; for (int i=0; i<(int)P.size(); ++i) { M[P[i]] += have[i&1]/2; have[i&1] /= 2; } vector< pair<int, string> > v; for (map<string, int>::const_iterator it=M.begin(); it!=M.end(); ++it) { v.push_back(make_pair(it->second, it->first)); } sort(v.begin(), v.end()); reverse(v.begin(), v.end()); if (v.size()==1 || v[0].first>v[1].first) { sol.insert(v[0].second); } } class EllysJuice { public: vector <string> getWinners(vector <string> players) { set<string> sol; sort(players.begin(), players.end()); do { winner(players, sol); } while (next_permutation(players.begin(), players.end())); return vector<string>(sol.begin(), sol.end()); } };
25.26087
76
0.567986
[ "vector" ]
eee16c1f180eb6d1a9326adce785c3e052295720
13,248
cpp
C++
src/services/a-rex/grid-manager/conf/GMConfig.cpp
davidgcameron/arc
9813ef5f45e5089507953239de8fa2248f5ad32c
[ "Apache-2.0" ]
null
null
null
src/services/a-rex/grid-manager/conf/GMConfig.cpp
davidgcameron/arc
9813ef5f45e5089507953239de8fa2248f5ad32c
[ "Apache-2.0" ]
null
null
null
src/services/a-rex/grid-manager/conf/GMConfig.cpp
davidgcameron/arc
9813ef5f45e5089507953239de8fa2248f5ad32c
[ "Apache-2.0" ]
null
null
null
#ifdef HAVE_CONFIG_H #include <config.h> #endif #include <fcntl.h> #include <grp.h> #include <pwd.h> #include <unistd.h> #include <sys/stat.h> // ::SSHFS_OK, check device #ifdef _MACOSX #include <sys/param.h> #include <sys/mount.h> #else #include <sys/statfs.h> // ::SSHFS_OK, check file system #endif #include <arc/StringConv.h> #include <arc/ArcLocation.h> #include <arc/FileUtils.h> #include <arc/Utils.h> #include "CoreConfig.h" #include "../run/RunParallel.h" #include "GMConfig.h" namespace ARex { // Defaults // default job ttl after finished - 1 week #define DEFAULT_KEEP_FINISHED (7*24*60*60) // default job ttr after deleted - 1 month #define DEFAULT_KEEP_DELETED (30*24*60*60) // default maximal allowed amount of reruns #define DEFAULT_JOB_RERUNS (5) // default maximal size of job description #define DEFAULT_MAX_JOB_DESC (5*1024*1024) // default wake up period for main job loop #define DEFAULT_WAKE_UP (600) Arc::Logger GMConfig::logger(Arc::Logger::getRootLogger(), "GMConfig"); static std::string empty_string(""); static std::list<std::string> empty_string_list; static std::list<std::pair<bool,std::string> > empty_group_list; std::string GMConfig::GuessConfigFile() { struct stat st; std::string file = Arc::GetEnv("ARC_CONFIG"); if(!file.empty()) { return file; // enforced location } file = Arc::ArcLocation::Get() + "/etc/arc.conf"; if (Arc::FileStat(file, &st, true)) { return file; } file = "/etc/arc.conf"; if (Arc::FileStat(file, &st, true)) { return file; } return ""; } GMConfig::GMConfig(const std::string& conf): conffile(conf) { SetDefaults(); // If no config file was given, guess it. The order to try is // $ARC_CONFIG, $ARC_LOCATION/etc/arc.conf, /etc/arc.conf if (conffile.empty()) { conffile = GuessConfigFile(); } } void GMConfig::SetDefaults() { conffile_is_temp = false; job_log = NULL; jobs_metrics = NULL; heartbeat_metrics = NULL; space_metrics = NULL; job_perf_log = NULL; cont_plugins = NULL; delegations = NULL; share_uid = 0; keep_finished = DEFAULT_KEEP_FINISHED; keep_deleted = DEFAULT_KEEP_DELETED; strict_session = false; fixdir = fixdir_always; reruns = DEFAULT_JOB_RERUNS; maxjobdesc = DEFAULT_MAX_JOB_DESC; wakeup_period = DEFAULT_WAKE_UP; allow_new = true; max_jobs_running = -1; max_jobs_total = -1; max_jobs = -1; max_jobs_per_dn = -1; max_scripts = -1; deleg_db = deleg_db_sqlite; enable_arc_interface = false; enable_emies_interface = false; cert_dir = Arc::GetEnv("X509_CERT_DIR"); voms_dir = Arc::GetEnv("X509_VOMS_DIR"); sshfs_mounts_enabled = false; } bool GMConfig::Load() { // Call CoreConfig (CoreConfig.h) to fill values in this object return CoreConfig::ParseConf(*this); } void GMConfig::Print() const { for(std::vector<std::string>::const_iterator i = session_roots.begin(); i != session_roots.end(); ++i) logger.msg(Arc::INFO, "\tSession root dir : %s", *i); logger.msg(Arc::INFO, "\tControl dir : %s", control_dir); logger.msg(Arc::INFO, "\tdefault LRMS : %s", default_lrms); logger.msg(Arc::INFO, "\tdefault queue : %s", default_queue); logger.msg(Arc::INFO, "\tdefault ttl : %u", keep_finished); std::vector<std::string> conf_caches = cache_params.getCacheDirs(); if(conf_caches.empty()) { logger.msg(Arc::INFO,"No valid caches found in configuration, caching is disabled"); return; } // list each cache for (std::vector<std::string>::iterator i = conf_caches.begin(); i != conf_caches.end(); i++) { logger.msg(Arc::INFO, "\tCache : %s", (*i).substr(0, (*i).find(" "))); if ((*i).find(" ") != std::string::npos) logger.msg(Arc::INFO, "\tCache link dir : %s", (*i).substr((*i).find_last_of(" ")+1, (*i).length()-(*i).find_last_of(" ")+1)); } if (cache_params.cleanCache()) logger.msg(Arc::INFO, "\tCache cleaning enabled"); else logger.msg(Arc::INFO, "\tCache cleaning disabled"); } void GMConfig::SetControlDir(const std::string &dir) { if (dir.empty()) control_dir = gm_user.Home() + "/.jobstatus"; else control_dir = dir; } void GMConfig::SetSessionRoot(const std::string &dir) { session_roots.clear(); if (dir.empty() || dir == "*") session_roots.push_back(gm_user.Home() + "/.jobs"); else session_roots.push_back(dir); } void GMConfig::SetSessionRoot(const std::vector<std::string> &dirs) { session_roots.clear(); if (dirs.empty()) { std::string dir; SetSessionRoot(dir); } else { for (std::vector<std::string>::const_iterator i = dirs.begin(); i != dirs.end(); i++) { if (*i == "*") session_roots.push_back(gm_user.Home() + "/.jobs"); else session_roots.push_back(*i); } } } std::string GMConfig::SessionRoot(const std::string& job_id) const { if (session_roots.empty()) return empty_string; if (session_roots.size() == 1 || job_id.empty()) return session_roots[0]; // search for this jobid's session dir struct stat st; for (std::vector<std::string>::const_iterator i = session_roots.begin(); i != session_roots.end(); i++) { std::string sessiondir(*i + '/' + job_id); if (stat(sessiondir.c_str(), &st) == 0 && S_ISDIR(st.st_mode)) return *i; } return empty_string; // not found } static bool fix_directory(const std::string& path, GMConfig::fixdir_t fixmode, mode_t mode, uid_t uid, gid_t gid) { if (fixmode == GMConfig::fixdir_never) { struct stat st; if (!Arc::FileStat(path, &st, true)) return false; if (!S_ISDIR(st.st_mode)) return false; return true; } else if(fixmode == GMConfig::fixdir_missing) { struct stat st; if (Arc::FileStat(path, &st, true)) { if (!S_ISDIR(st.st_mode)) return false; return true; } } // GMConfig::fixdir_always if (!Arc::DirCreate(path, mode, true)) return false; // Only can switch owner if running as root if (getuid() == 0) if (chown(path.c_str(), uid, gid) != 0) return false; if (chmod(path.c_str(), mode) != 0) return false; return true; } bool GMConfig::CreateControlDirectory() const { bool res = true; if (!control_dir.empty()) { mode_t mode = 0; if (gm_user.get_uid() == 0) { // This control dir serves multiple users and running // as root (hence really can serve multiple users) mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH; } else { mode = S_IRWXU; } if (!fix_directory(control_dir, fixdir, mode, gm_user.get_uid(), gm_user.get_gid())) res = false; // Structure inside control dir is important - *always* create it // Directories containing logs and job states may need access from // information system, etc. So allowing them to be more open. // Delegation is only accessed by service itself. if (!fix_directory(control_dir+"/logs", fixdir_always, mode, gm_user.get_uid(), gm_user.get_gid())) res = false; if (!fix_directory(control_dir+"/accepting", fixdir_always, mode, gm_user.get_uid(), gm_user.get_gid())) res = false; if (!fix_directory(control_dir+"/restarting", fixdir_always, mode, gm_user.get_uid(), gm_user.get_gid())) res = false; if (!fix_directory(control_dir+"/processing", fixdir_always, mode, gm_user.get_uid(), gm_user.get_gid())) res = false; if (!fix_directory(control_dir+"/finished", fixdir_always, mode, gm_user.get_uid(), gm_user.get_gid())) res = false; std::string deleg_dir = DelegationDir(); if (!fix_directory(deleg_dir, fixdir_always, S_IRWXU, gm_user.get_uid(), gm_user.get_gid())) res = false; } return res; } bool GMConfig::CreateSessionDirectory(const std::string& dir, const Arc::User& user) const { // First just try to create per-job dir, assuming session root already exists if (gm_user.get_uid() != 0) { if (Arc::DirCreate(dir, S_IRWXU, false)) return true; } else if (strict_session) { if (Arc::DirCreate(dir, user.get_uid(), user.get_gid(), S_IRWXU, false)) return true; } else { if (Arc::DirCreate(dir, S_IRWXU, false)) return (chown(dir.c_str(), user.get_uid(), user.get_gid()) == 0); } // Creation failed so try to create session root and try again std::string session_root(dir.substr(0, dir.rfind('/'))); if (session_root.empty()) return false; mode_t mode = 0; if (gm_user.get_uid() == 0) { if (strict_session) { // For multiple users creating immediate subdirs using own account // dangerous permissions, but there is no other option mode = S_IRWXU | S_IRWXG | S_IRWXO | S_ISVTX; } else { // For multiple users not creating immediate subdirs using own account mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH; } } else { // For single user mode = S_IRWXU; } if (!fix_directory(session_root, fixdir, mode, gm_user.get_uid(), gm_user.get_gid())) return false; // Try per-job dir again if (gm_user.get_uid() != 0) { return Arc::DirCreate(dir, S_IRWXU, false); } else if (strict_session) { return Arc::DirCreate(dir, user.get_uid(), user.get_gid(), S_IRWXU, false); } else { if (!Arc::DirCreate(dir, S_IRWXU, false)) return false; return (chown(dir.c_str(), user.get_uid(), user.get_gid()) == 0); } } std::string GMConfig::DelegationDir() const { std::string deleg_dir = control_dir+"/delegations"; uid_t u = gm_user.get_uid(); if (u == 0) return deleg_dir; struct passwd pwbuf; char buf[4096]; struct passwd* pw; if (::getpwuid_r(u, &pwbuf, buf, sizeof(buf), &pw) == 0) { if (pw && pw->pw_name) { deleg_dir+="."; deleg_dir+=pw->pw_name; } } return deleg_dir; } GMConfig::deleg_db_t GMConfig::DelegationDBType() const { return deleg_db; } const std::string & GMConfig::ForcedVOMS(const char * queue) const { std::map<std::string,std::string>::const_iterator pos = forced_voms.find(queue); return (pos == forced_voms.end()) ? empty_string : pos->second; } const std::list<std::string> & GMConfig::AuthorizedVOs(const char * queue) const { std::map<std::string, std::list<std::string> >::const_iterator pos = authorized_vos.find(queue); return (pos == authorized_vos.end()) ? empty_string_list : pos->second; } const std::list<std::pair<bool,std::string> > & GMConfig::MatchingGroups(const char * queue) const { std::map<std::string, std::list<std::pair<bool,std::string> > >::const_iterator pos = matching_groups.find(queue); return (pos == matching_groups.end()) ? empty_group_list : pos->second; } bool GMConfig::Substitute(std::string& param, const Arc::User& user) const { std::string::size_type curpos = 0; for (;;) { if (curpos >= param.length()) break; std::string::size_type pos = param.find('%', curpos); if (pos == std::string::npos) break; pos++; if (pos >= param.length()) break; if (param[pos] == '%') { curpos=pos+1; continue; }; std::string to_put; switch (param[pos]) { case 'R': to_put = SessionRoot(""); break; // First session dir will be used if there are multiple case 'C': to_put = ControlDir(); break; case 'U': to_put = user.Name(); break; case 'H': to_put = user.Home(); break; case 'Q': to_put = DefaultQueue(); break; case 'L': to_put = DefaultLRMS(); break; case 'u': to_put = Arc::tostring(user.get_uid()); break; case 'g': to_put = Arc::tostring(user.get_gid()); break; case 'W': to_put = Arc::ArcLocation::Get(); break; case 'F': to_put = conffile; break; case 'G': logger.msg(Arc::ERROR, "Globus location variable substitution is not supported anymore. Please specify path directly."); break; default: to_put = param.substr(pos-1, 2); break; } curpos = pos+1+(to_put.length() - 2); param.replace(pos-1, 2, to_put); } return true; } void GMConfig::SetShareID(const Arc::User& share_user) { share_uid = share_user.get_uid(); share_gids.clear(); if (share_uid <= 0) return; struct passwd pwd_buf; struct passwd* pwd = NULL; #ifdef _SC_GETPW_R_SIZE_MAX int buflen = sysconf(_SC_GETPW_R_SIZE_MAX); if (buflen <= 0) buflen = 16384; #else int buflen = 16384; #endif char* buf = (char*)malloc(buflen); if (!buf) return; if (getpwuid_r(share_uid, &pwd_buf, buf, buflen, &pwd) == 0) { if (pwd) { #ifdef HAVE_GETGROUPLIST #ifdef _MACOSX int groups[100]; #else gid_t groups[100]; #endif int ngroups = 100; if (getgrouplist(pwd->pw_name, pwd->pw_gid, groups, &ngroups) >= 0) { for (int n = 0; n<ngroups; ++n) { share_gids.push_back((gid_t)(groups[n])); } } #endif share_gids.push_back(pwd->pw_gid); } } free(buf); } bool GMConfig::MatchShareGid(gid_t sgid) const { for (std::list<gid_t>::const_iterator i = share_gids.begin(); i != share_gids.end(); ++i) { if (sgid == *i) return true; } return false; } bool GMConfig::SSHFS_OK(const std::string& mount_point) const { struct stat st; struct stat st_root; stat(mount_point.c_str(), &st); stat(mount_point.substr(0, mount_point.rfind('/')).c_str(), &st_root); // rootdir and dir on different devices? if (st.st_dev != st_root.st_dev) { struct statfs stfs; statfs(mount_point.c_str(), &stfs); // dir is also a fuse fs? return stfs.f_type == 0x65735546; } return false; } } // namespace ARex
34.41039
134
0.659949
[ "object", "vector" ]
eefbe7e5c301d6ba8e43aede42474da0ba5c8200
2,957
cpp
C++
benchmark/layer.cpp
marwage/alzheimer
b58688ea91f9b2ca4ae5457858b0fcc2a6e3e041
[ "CC0-1.0" ]
null
null
null
benchmark/layer.cpp
marwage/alzheimer
b58688ea91f9b2ca4ae5457858b0fcc2a6e3e041
[ "CC0-1.0" ]
null
null
null
benchmark/layer.cpp
marwage/alzheimer
b58688ea91f9b2ca4ae5457858b0fcc2a6e3e041
[ "CC0-1.0" ]
null
null
null
// Copyright 2020 Marcel Wagenländer #include "layer.hpp" #include "chunking.hpp" #include "cuda_helper.hpp" #include "dataset.hpp" #include "gpu_memory_logger.hpp" #include "tensors.hpp" #include <benchmark/benchmark.h> const std::string dir_path = "/mnt/data"; void benchmark_layer(Layer *layer, Dataset dataset, benchmark::State &state, bool forward) { std::string dataset_path = dir_path + "/" + get_dataset_name(dataset); std::string path; path = dataset_path + "/features.npy"; Matrix<float> features = load_npy_matrix<float>(path); Matrix<float> incoming_gradients; if (!forward) { incoming_gradients.set(features.num_rows_, features.num_columns_, true); incoming_gradients.set_random_values(); } CudaHelper cuda_helper; layer->set(&cuda_helper, features.num_rows_, features.num_columns_); if (!forward) { layer->forward(&features); } std::string direction; if (forward) { direction = "forward"; } else { direction = "backward"; } GPUMemoryLogger memory_logger(layer->name_ + "_" + get_dataset_name(dataset) + "_" + direction); memory_logger.start(); for (auto _ : state) { if (forward) { layer->forward(&features); } else { layer->backward(&incoming_gradients); } } memory_logger.stop(); } void benchmark_layer_chunked(LayerChunked *layer, Dataset dataset, benchmark::State &state, bool forward) { std::string dataset_path = dir_path + "/" + get_dataset_name(dataset); std::string path; path = dataset_path + "/features.npy"; Matrix<float> features = load_npy_matrix<float>(path); Matrix<float> incoming_gradients; if (!forward) { incoming_gradients.set(features.num_rows_, features.num_columns_, true); incoming_gradients.set_random_values(); } long chunk_size = state.range(0); long num_chunks = ceil((float) features.num_rows_ / (float) chunk_size); std::vector<Matrix<float>> features_chunked(num_chunks); chunk_up(&features, &features_chunked, chunk_size); std::vector<Matrix<float>> incoming_gradients_chunked(num_chunks); chunk_up(&incoming_gradients, &incoming_gradients_chunked, chunk_size); CudaHelper cuda_helper; layer->set(&cuda_helper, state.range(0), features.num_rows_, features.num_columns_); if (!forward) { layer->forward(&features_chunked); } std::string direction; if (forward) { direction = "forward"; } else { direction = "backward"; } GPUMemoryLogger memory_logger(layer->name_ + "_" + get_dataset_name(dataset) + "_" + direction + "_" + std::to_string(chunk_size)); memory_logger.start(); for (auto _ : state) { if (forward) { layer->forward(&features_chunked); } else { layer->backward(&incoming_gradients_chunked); } } memory_logger.stop(); }
29.868687
135
0.660467
[ "vector" ]
e10446ff450c70d5367df41aee33ab7b990d92c9
42,449
cc
C++
processors/IA32/bochs/gui/macintosh.cc
pavel-krivanek/opensmalltalk-vm
694dfe3ed015e16f5b8e9cf17d37e4bdd32bea16
[ "MIT" ]
445
2016-06-30T08:19:11.000Z
2022-03-28T06:09:49.000Z
processors/IA32/bochs/gui/macintosh.cc
pavel-krivanek/opensmalltalk-vm
694dfe3ed015e16f5b8e9cf17d37e4bdd32bea16
[ "MIT" ]
439
2016-06-29T20:14:36.000Z
2022-03-17T19:59:58.000Z
processors/IA32/bochs/gui/macintosh.cc
pavel-krivanek/opensmalltalk-vm
694dfe3ed015e16f5b8e9cf17d37e4bdd32bea16
[ "MIT" ]
137
2016-07-02T17:32:07.000Z
2022-03-20T11:17:25.000Z
///////////////////////////////////////////////////////////////////////// // $Id: macintosh.cc,v 1.29 2008/02/15 22:05:40 sshwarts Exp $ ///////////////////////////////////////////////////////////////////////// // // Copyright (C) 2001 MandrakeSoft S.A. // // MandrakeSoft S.A. // 43, rue d'Aboukir // 75002 Paris - France // http://www.linux-mandrake.com/ // http://www.mandrakesoft.com/ // // 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 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 ///////////////////////////////////////////////////////////////////////// // macintosh.cc -- bochs GUI file for the Macintosh // written by David Batterham <drbatter@progsoc.uts.edu.au> // with contributions from Tim Senecal // Define BX_PLUGGABLE in files that can be compiled into plugins. For // platforms that require a special tag on exported symbols, BX_PLUGGABLE // is used to know when we are exporting symbols and when we are importing. #define BX_PLUGGABLE // BOCHS INCLUDES #include <MacTypes.h> #include "bochs.h" #include "iodev.h" // decide whether to enable this file or not #if BX_WITH_MACOS #include "icon_bochs.h" #include "font/vga.bitmap.h" // MAC OS INCLUDES #undef ACCESSOR_CALLS_ARE_FUNCTIONS #define ACCESSOR_CALLS_ARE_FUNCTIONS 1 #include <Quickdraw.h> #include <QuickdrawText.h> #include <QDOffscreen.h> #include <Icons.h> #include <ImageCompression.h> #include <Palettes.h> #include <Windows.h> #include <Memory.h> #include <Events.h> #include <TextUtils.h> #include <ToolUtils.h> #include <Dialogs.h> #include <LowMem.h> #include <Disks.h> #include <CursorDevices.h> #include <Menus.h> #include <Sound.h> #include <SIOUX.h> #include <Devices.h> // CONSTANTS #define rMBarID 128 #define mApple 128 #define iAbout 1 #define mFile 129 #define iQuit 1 #define mEdit 130 #define mBochs 131 #define iFloppy 1 #define iCursor 3 #define iTool 4 #define iMenuBar 5 #define iFullScreen 6 #define iConsole 7 #define iSnapshot 9 #define iReset 10 #define SLEEP_TIME 0 // Number of ticks to surrender the processor during a WaitNextEvent() // Change this to 15 or higher if you don't want Bochs to hog the processor! #define FONT_WIDTH 8 #define FONT_HEIGHT 16 #define WINBITMAP(w) (((GrafPtr)(w))->portBits) #define ASCII_1_MASK 0x00FF0000 #define ASCII_2_MASK 0x000000FF const RGBColor black = {0, 0, 0}; const RGBColor white = {0xFFFF, 0xFFFF, 0xFFFF}; const RGBColor medGrey = {0xCCCC, 0xCCCC, 0xCCCC}; const RGBColor ltGrey = {0xEEEE, 0xEEEE, 0xEEEE}; class bx_macintosh_gui_c : public bx_gui_c { public: bx_macintosh_gui_c (void) {} DECLARE_GUI_VIRTUAL_METHODS() }; // declare one instance of the gui object and call macro to insert the // plugin code static bx_macintosh_gui_c *theGui = NULL; IMPLEMENT_GUI_PLUGIN_CODE(macintosh) #define LOG_THIS theGui-> // GLOBALS WindowPtr win, toolwin, fullwin, backdrop, hidden, SouixWin; SInt16 gOldMBarHeight; bx_bool menubarVisible = true, cursorVisible = true; RgnHandle mBarRgn, cnrRgn; unsigned mouse_button_state = 0; CTabHandle gCTable; PixMapHandle gTile; BitMap *vgafont[256]; Rect srcTextRect, srcTileRect; Point scrCenter = {320, 240}; Ptr KCHR; short gheaderbar_y; Point prevPt; unsigned width, height, gMinTop, gMaxTop, gLeft; GWorldPtr gOffWorld; Ptr gMyBuffer; static unsigned vga_bpp=8; static EventModifiers oldMods = 0; static unsigned int text_rows=25, text_cols=80; // HEADERBAR STUFF int numPixMaps = 0, toolPixMaps = 0; unsigned bx_bitmap_left_xorigin = 2; // pixels from left unsigned bx_bitmap_right_xorigin = 2; // pixels from right //PixMapHandle bx_pixmap[BX_MAX_PIXMAPS]; CIconHandle bx_cicn[BX_MAX_PIXMAPS]; struct { CIconHandle cicn; // PixMapHandle pm; unsigned xdim; unsigned ydim; unsigned xorigin; unsigned yorigin; unsigned alignment; void (*f)(void); } bx_tool_pixmap[BX_MAX_PIXMAPS]; // Event handlers BX_CPP_INLINE void HandleKey(EventRecord *event, Bit32u keyState); BX_CPP_INLINE void HandleToolClick(Point where); void HandleMenuChoice(long menuChoice); BX_CPP_INLINE void HandleClick(EventRecord *event); // Update routines void UpdateWindow(WindowPtr window); void UpdateRgn(RgnHandle rgn); // Show/hide UI elements void HidePointer(void); void ShowPointer(void); void HideTools(void); void ShowTools(void); void HideMenubar(void); void ShowMenubar(void); void HideConsole(void); void ShowConsole(void); // Initialisation void FixWindow(void); void MacPanic(void); void InitToolbox(void); void CreateTile(void); void CreateMenus(void); void CreateWindows(void); void CreateKeyMap(void); void CreateVGAFont(void); BitMap *CreateBitMap(unsigned width, unsigned height); PixMapHandle CreatePixMap(unsigned left, unsigned top, unsigned width, unsigned height, unsigned depth, CTabHandle clut); unsigned char reverse_bitorder(unsigned char); //this routine moves the initial window position so that it is entirely onscreen //it is needed for os 8.x with appearance managaer void FixWindow(void) { RgnHandle wStruct; Region *wRgn; CWindowRecord *thing; Rect wRect; RgnHandle tStruct; Region *tRgn; Rect tRect; short MinVal; thing = (CWindowRecord *)win; wStruct = thing->strucRgn; wRgn = (Region *)*wStruct; wRect = wRgn->rgnBBox; thing = (CWindowRecord *)toolwin; tStruct = thing->strucRgn; tRgn = (Region *)*tStruct; tRect = tRgn->rgnBBox; if (wRect.left < 2) { gLeft = gLeft + (2 - wRect.left); } MinVal = tRect.bottom+2; //MinVal = MinVal + GetMBarHeight(); if (wRect.top < MinVal) { // gMinTop = gMinTop + (MinVal - wRect.top); gMaxTop = gMaxTop + (MinVal - wRect.top); } MoveWindow(win, gLeft, gMaxTop, false); } void MacPanic(void) { StopAlert(200, NULL); } void InitToolbox(void) { InitGraf(&qd.thePort); InitWindows(); InitMenus(); InitDialogs(nil); InitCursor(); MaxApplZone(); // Initialise the toolbox } void CreateTile(void) { GDHandle saveDevice; CGrafPtr savePort; OSErr err; unsigned long p_f; long theRowBytes = ((((long) (vga_bpp==24?32:(((vga_bpp+1)>>1)<<1)) * ((long) (srcTileRect.right-srcTileRect.left)) + 31) >> 5) << 2); //if (SIM->get_param_bool(BXPN_PRIVATE_COLORMAP)->get()) //{ GetGWorld(&savePort, &saveDevice); switch(vga_bpp) { case 1: p_f = k1MonochromePixelFormat; break; case 2: p_f = k2IndexedPixelFormat; break; case 4: p_f = k4IndexedPixelFormat; break; case 8: p_f = k8IndexedPixelFormat; break; case 15: p_f = k16LE555PixelFormat; break; case 16: p_f = k16LE565PixelFormat; break; case 24: //p_f = k24BGRPixelFormat; //break; case 32: p_f = k32ARGBPixelFormat;//k32BGRAPixelFormat; break; } BX_ASSERT((gMyBuffer = (Ptr)malloc(theRowBytes * (srcTileRect.bottom - srcTileRect.top))) != NULL); err = QTNewGWorldFromPtr(&gOffWorld, p_f, &srcTileRect, vga_bpp>8 ? NULL : gCTable, NULL, keepLocal, gMyBuffer, theRowBytes); if (err != noErr || gOffWorld == NULL) BX_PANIC(("mac: can't create gOffWorld; err=%hd", err)); SetGWorld(gOffWorld, NULL); RGBForeColor(&black); RGBBackColor(&white); gTile = GetGWorldPixMap(gOffWorld); if (gTile != NULL) { NoPurgePixels(gTile); if (!LockPixels(gTile)) BX_ERROR(("mac: can't LockPixels gTile")); if ((**gTile).pixelType != RGBDirect && (**gTile).pmTable != gCTable) { DisposeCTable(gCTable); gCTable = (**gTile).pmTable; } (**gCTable).ctFlags |= 0x4000; //use palette manager indexes CTabChanged(gCTable); } else BX_PANIC(("mac: can't create gTile")); SetGWorld(savePort, saveDevice); /*} else { gOffWorld = NULL; gTile = CreatePixMap(0, 0, srcTileRect.right, srcTileRect.bottom, 8, gCTable); if (gTile == NULL) BX_PANIC(("mac: can't create gTile")); }*/ } void CreateMenus(void) { Handle menu; menu = GetNewMBar(rMBarID); // get our menus from resource if (menu != nil) { SetMenuBar(menu); DisposeHandle(menu); AppendResMenu(GetMenuHandle(mApple), 'DRVR'); // add apple menu items DrawMenuBar(); } else BX_PANIC(("can't create menu")); } void CreateWindows(void) { int l, t, r, b; Rect winRect; SetRect(&winRect, 0, 0, qd.screenBits.bounds.right, qd.screenBits.bounds.bottom); backdrop = NewWindow(NULL, &winRect, "\p", false, plainDBox, (WindowPtr)-1, false, 0); width = 640; height = 480; gLeft = 4; gMinTop = 44; gMaxTop = 44 + gheaderbar_y; l = (qd.screenBits.bounds.right - width)/2; r = l + width; t = (qd.screenBits.bounds.bottom - height)/2; b = t + height; SetRect(&winRect, 0, 20, qd.screenBits.bounds.right, 22+gheaderbar_y); toolwin = NewCWindow(NULL, &winRect, "\pMacBochs 586", true, floatProc, (WindowPtr)-1, false, 0); if (toolwin == NULL) BX_PANIC(("mac: can't create tool window")); // Create a moveable tool window for the "headerbar" SetRect(&winRect, l, t, r, b); fullwin = NewCWindow(NULL, &winRect, "\p", false, plainDBox, (WindowPtr)-1, false, 1); SetRect(&winRect, gLeft, gMaxTop, gLeft+width, gMaxTop+height); win = NewCWindow(NULL, &winRect, "\pMacBochs 586", true, documentProc, (WindowPtr)-1, true, 1); if (win == NULL) BX_PANIC(("mac: can't create emulator window")); FixWindow(); hidden = fullwin; HiliteWindow(win, true); SetPort(win); } // ::SPECIFIC_INIT() // // Called from gui.cc, once upon program startup, to allow for the // specific GUI code (X11, BeOS, ...) to be initialized. // // argc, argv: not used right now, but the intention is to pass native GUI // specific options from the command line. (X11 options, BeOS options,...) // // tilewidth, tileheight: for optimization, graphics_tile_update() passes // only updated regions of the screen to the gui code to be redrawn. // These define the dimensions of a region (tile). // headerbar_y: A headerbar (toolbar) is display on the top of the // VGA window, showing floppy status, and other information. It // always assumes the width of the current VGA mode width, but // it's height is defined by this parameter. void bx_macintosh_gui_c::specific_init(int argc, char **argv, unsigned tilewidth, unsigned tileheight, unsigned headerbar_y) { put("MGUI"); InitToolbox(); //SouixWin = FrontWindow(); atexit(MacPanic); gheaderbar_y = headerbar_y; CreateKeyMap(); gCTable = GetCTable(128); BX_ASSERT (gCTable != NULL); CTabChanged(gCTable); //(*gCTable)->ctSeed = GetCTSeed(); SetRect(&srcTextRect, 0, 0, FONT_WIDTH, FONT_HEIGHT); SetRect(&srcTileRect, 0, 0, tilewidth, tileheight); CreateMenus(); CreateVGAFont(); CreateTile(); CreateWindows(); GetMouse(&prevPt); SetEventMask(everyEvent); SIOUXSettings.setupmenus = false; SIOUXSettings.autocloseonquit = true; SIOUXSettings.asktosaveonclose = false; SIOUXSettings.standalone = false; UNUSED(argc); UNUSED(argv); //HideWindow(SouixWin); } // HandleKey() // // Handles keyboard-related events. BX_CPP_INLINE void HandleKey(EventRecord *event, Bit32u keyState) { UInt32 key; UInt32 trans; static UInt32 transState = 0; key = event->message & charCodeMask; if (event->modifiers & cmdKey) { HandleMenuChoice(MenuKey(key)); } //else if (FrontWindow() == SouixWin) //{ // SIOUXHandleOneEvent(event); //} else { /* if (event->modifiers & shiftKey) DEV_kbd_gen_scancode(BX_KEY_SHIFT_L | keyState); if (event->modifiers & controlKey) DEV_kbd_gen_scancode(BX_KEY_CTRL_L | keyState); if (event->modifiers & optionKey) DEV_kbd_gen_scancode(BX_KEY_ALT_L | keyState);*/ key = (event->message & keyCodeMask) >> 8; trans = KeyTranslate(KCHR, key, &transState); if ((trans == BX_KEY_PRINT) && ((oldMods & optionKey) || (oldMods & rightOptionKey))) trans = BX_KEY_ALT_SYSREQ; if ((trans == BX_KEY_PAUSE) && ((oldMods & controlKey) || (oldMods & rightControlKey))) trans = BX_KEY_CTRL_BREAK; // KeyTranslate maps Mac virtual key codes to any type of character code // you like (in this case, Bochs key codes). Much nicer than a huge switch // statement! if (trans > 0) DEV_kbd_gen_scancode(trans | keyState); /* if (event->modifiers & shiftKey) DEV_kbd_gen_scancode(BX_KEY_SHIFT_L | BX_KEY_RELEASED); if (event->modifiers & controlKey) DEV_kbd_gen_scancode(BX_KEY_CTRL_L | BX_KEY_RELEASED); if (event->modifiers & optionKey) DEV_kbd_gen_scancode(BX_KEY_ALT_L | BX_KEY_RELEASED);*/ } } // HandleToolClick() // // Handles mouse clicks in the Bochs tool window BX_CPP_INLINE void HandleToolClick(Point where) { unsigned i; int xorigin; Rect bounds; SetPort(toolwin); GlobalToLocal(&where); for (i=0; i<toolPixMaps; i++) { if (bx_tool_pixmap[i].alignment == BX_GRAVITY_LEFT) xorigin = bx_tool_pixmap[i].xorigin; else xorigin = toolwin->portRect.right - bx_tool_pixmap[i].xorigin; SetRect(&bounds, xorigin, 0, xorigin+32, 32); if (PtInRect(where, &bounds)) bx_tool_pixmap[i].f(); } theGui->show_headerbar(); } BX_CPP_INLINE void ResetPointer(void) { #if 0 CursorDevice *theMouse; if (true) { theMouse = NULL; CrsrDevNextDevice(&theMouse); CrsrDevMoveTo(theMouse, (long)scrCenter.h, (long)scrCenter.v); } #endif #define MouseCur 0x082C #define MouseTemp 0x0828 #define MouseNew 0x08CE #define MouseAttached 0x08CF *(Point *)MouseCur = scrCenter; *(Point *)MouseTemp = scrCenter; *(Ptr)MouseNew = *(Ptr)MouseAttached; //*(char *)CrsrNew = 0xFF; } // HandleClick() // // Handles mouse click events. void HandleMenuChoice(long menuChoice) { OSErr err = noErr; short item, menu, i; short daRefNum; Rect bounds; Str255 daName; WindowRef newWindow; DialogPtr theDlog; item = LoWord(menuChoice); menu = HiWord(menuChoice); switch(menu) { case mApple: switch(item) { case iAbout: theDlog = GetNewDialog(128, NULL, (WindowPtr)-1); ModalDialog(NULL, &i); DisposeDialog(theDlog); break; default: GetMenuItemText(GetMenuHandle(mApple), item, daName); daRefNum = OpenDeskAcc(daName); break; } break; case mFile: switch(item) { case iQuit: BX_PANIC(("User terminated")); break; default: break; } break; case mBochs: switch(item) { case iFloppy: DiskEject(1); break; case iCursor: if (cursorVisible) HidePointer(); else ShowPointer(); break; case iTool: if (IsWindowVisible(toolwin)) HideTools(); else ShowTools(); break; case iMenuBar: if (menubarVisible) HideMenubar(); else ShowMenubar(); break; case iFullScreen: if (cursorVisible || IsWindowVisible(toolwin) || menubarVisible) { if (cursorVisible) HidePointer(); if (menubarVisible) HideMenubar(); if (IsWindowVisible(toolwin)) HideTools(); } else { if (!cursorVisible) ShowPointer(); if (!menubarVisible) ShowMenubar(); if (!IsWindowVisible(toolwin)) ShowTools(); } break; case iConsole: if (IsWindowVisible(SouixWin)) HideConsole(); else ShowConsole(); break; case iSnapshot: // the following will break if snapshot is not last bitmap button instantiated bx_tool_pixmap[toolPixMaps-1].f(); break; } default: break; } HiliteMenu(0); } BX_CPP_INLINE void HandleClick(EventRecord *event) { short part; WindowPtr whichWindow; Rect dRect; part = FindWindow(event->where, &whichWindow); switch(part) { case inContent: if (whichWindow == win) { if (win != FrontWindow()) SelectWindow(win); if (event->modifiers & cmdKey) mouse_button_state |= 0x02; else mouse_button_state |= 0x01; } else if (whichWindow == toolwin) { HiliteWindow(win, true); HandleToolClick(event->where); } else if (whichWindow == backdrop) { SelectWindow(win); } else if (whichWindow == SouixWin) { SelectWindow(SouixWin); } break; case inDrag: dRect = qd.screenBits.bounds; if (IsWindowVisible(toolwin)) dRect.top = gMaxTop; DragWindow(whichWindow, event->where, &dRect); break; case inMenuBar: HandleMenuChoice(MenuSelect(event->where)); break; } } void UpdateWindow(WindowPtr window) { GrafPtr oldPort; Rect box; GetPort(&oldPort); SetPort(window); BeginUpdate(window); if (window == win) { box = window->portRect; DEV_vga_redraw_area(box.left, box.top, box.right, box.bottom); } else if (window == backdrop) { box = window->portRect; FillRect(&box, &qd.black); } else if (window == toolwin) { theGui->show_headerbar(); } EndUpdate(window); SetPort(oldPort); } // ::HANDLE_EVENTS() // // Called periodically (vga_update_interval in .bochsrc) so the // the gui code can poll for keyboard, mouse, and other // relevant events. void bx_macintosh_gui_c::handle_events(void) { EventRecord event; Point mousePt; int dx, dy; int oldMods1=0; EventModifiers newMods; unsigned curstate; GrafPtr oldport; curstate = mouse_button_state; //so we can compare the old and the new mouse state if (WaitNextEvent(everyEvent, &event, SLEEP_TIME, NULL)) { switch(event.what) { case nullEvent: break; case mouseDown: HandleClick(&event); break; case mouseUp: if (event.modifiers & cmdKey) mouse_button_state &= ~0x02; else mouse_button_state &= ~0x01; break; case keyDown: case autoKey: oldMods1 = event.modifiers; HandleKey(&event, BX_KEY_PRESSED); break; case keyUp: event.modifiers = oldMods1; HandleKey(&event, BX_KEY_RELEASED); break; case updateEvt: if ((WindowPtr)event.message == SouixWin) SIOUXHandleOneEvent(&event); else UpdateWindow((WindowPtr)event.message); break; case diskEvt: floppyA_handler(); default: break; } } else if (oldMods != (newMods = (event.modifiers & 0xfe00))) { if ((newMods ^ oldMods) & shiftKey) DEV_kbd_gen_scancode(BX_KEY_SHIFT_L | ((newMods & shiftKey)?BX_KEY_PRESSED:BX_KEY_RELEASED)); if ((newMods ^ oldMods) & alphaLock) DEV_kbd_gen_scancode(BX_KEY_CAPS_LOCK | ((newMods & alphaLock)?BX_KEY_PRESSED:BX_KEY_RELEASED)); if ((newMods ^ oldMods) & optionKey) DEV_kbd_gen_scancode(BX_KEY_ALT_L | ((newMods & optionKey)?BX_KEY_PRESSED:BX_KEY_RELEASED)); if ((newMods ^ oldMods) & controlKey) DEV_kbd_gen_scancode(BX_KEY_CTRL_L | ((newMods & controlKey)?BX_KEY_PRESSED:BX_KEY_RELEASED)); if ((newMods ^ oldMods) & rightShiftKey) DEV_kbd_gen_scancode(BX_KEY_SHIFT_R | ((newMods & rightShiftKey)?BX_KEY_PRESSED:BX_KEY_RELEASED)); if ((newMods ^ oldMods) & rightOptionKey) DEV_kbd_gen_scancode(BX_KEY_ALT_R | ((newMods & rightOptionKey)?BX_KEY_PRESSED:BX_KEY_RELEASED)); if ((newMods ^ oldMods) & rightControlKey) DEV_kbd_gen_scancode(BX_KEY_CTRL_R | ((newMods & rightControlKey)?BX_KEY_PRESSED:BX_KEY_RELEASED)); oldMods = newMods; } GetPort(&oldport); SetPort(win); GetMouse(&mousePt); //if mouse has moved, or button has changed state if ((!EqualPt(mousePt, prevPt)) || (curstate != mouse_button_state)) { dx = mousePt.h - prevPt.h; dy = prevPt.v - mousePt.v; DEV_mouse_motion(dx, dy, mouse_button_state); if (!cursorVisible) { SetPt(&scrCenter, 320, 240); LocalToGlobal(&scrCenter); ResetPointer(); //next getmouse should be 320, 240 SetPt(&mousePt, 320, 240); } } prevPt = mousePt; SetPort(oldport); } // ::FLUSH() // // Called periodically, requesting that the gui code flush all pending // screen update requests. void bx_macintosh_gui_c::flush(void) { // an opportunity to make the Window Manager happy. // not needed on the macintosh.... } // ::CLEAR_SCREEN() // // Called to request that the VGA region is cleared. Don't // clear the area that defines the headerbar. void bx_macintosh_gui_c::clear_screen(void) { SetPort(win); RGBForeColor(&black); RGBBackColor(&white); FillRect(&win->portRect, &qd.black); } // ::TEXT_UPDATE() // // Called in a VGA text mode, to update the screen with // new content. // // old_text: array of character/attributes making up the contents // of the screen from the last call. See below // new_text: array of character/attributes making up the current // contents, which should now be displayed. See below // // format of old_text & new_text: each is tm_info.line_offset*text_rows // bytes long. Each character consists of 2 bytes. The first by is // the character value, the second is the attribute byte. // // cursor_x: new x location of cursor // cursor_y: new y location of cursor // tm_info: this structure contains information for additional // features in text mode (cursor shape, line offset,...) void bx_macintosh_gui_c::text_update(Bit8u *old_text, Bit8u *new_text, unsigned long cursor_x, unsigned long cursor_y, bx_vga_tminfo_t tm_info) { int i; unsigned char achar; int x, y; static int previ; int cursori; Rect destRect; RGBColor fgColor, bgColor; GrafPtr oldPort; unsigned nchars; OSErr theError; GetPort(&oldPort); SetPort(win); //current cursor position cursori = (cursor_y * text_cols + cursor_x) * 2; // Number of characters on screen, variable number of rows nchars = text_cols * text_rows; for (i=0; i<nchars*2; i+=2) { if (i == cursori || i == previ || new_text[i] != old_text[i] || new_text[i+1] != old_text[i+1]) { achar = new_text[i]; // fgColor = (**gCTable).ctTable[new_text[i+1] & 0x0F].rgb; // bgColor = (**gCTable).ctTable[(new_text[i+1] & 0xF0) >> 4].rgb; // RGBForeColor(&fgColor); // RGBBackColor(&bgColor); if (SIM->get_param_bool(BXPN_PRIVATE_COLORMAP)->get()) { PmForeColor(new_text[i+1] & 0x0F); PmBackColor((new_text[i+1] & 0xF0) >> 4); } else { fgColor = (**gCTable).ctTable[new_text[i+1] & 0x0F].rgb; bgColor = (**gCTable).ctTable[(new_text[i+1] & 0xF0) >> 4].rgb; RGBForeColor(&fgColor); RGBBackColor(&bgColor); } x = ((i/2) % text_cols)*FONT_WIDTH; y = ((i/2) / text_cols)*FONT_HEIGHT; SetRect(&destRect, x, y, x+FONT_WIDTH, y+FONT_HEIGHT); CopyBits(vgafont[achar], &WINBITMAP(win), &srcTextRect, &destRect, srcCopy, NULL); if ((theError = QDError()) != noErr) BX_ERROR(("mac: CopyBits returned %hd", theError)); if (i == cursori) //invert the current cursor block { InvertRect(&destRect); } } } //previous cursor position previ = cursori; SetPort(oldPort); } int bx_macintosh_gui_c::get_clipboard_text(Bit8u **bytes, Bit32s *nbytes) { return 0; } int bx_macintosh_gui_c::set_clipboard_text(char *text_snapshot, Bit32u len) { return 0; } // ::PALETTE_CHANGE() // // Allocate a color in the native GUI, for this color, and put // it in the colormap location 'index'. // returns: 0=no screen update needed (color map change has direct effect) // 1=screen updated needed (redraw using current colormap) bx_bool bx_macintosh_gui_c::palette_change(unsigned index, unsigned red, unsigned green, unsigned blue) { PaletteHandle thePal, oldpal; GDHandle saveDevice; CGrafPtr savePort; GrafPtr oldPort; /*if (gOffWorld != NULL) //(SIM->get_param_bool(BXPN_PRIVATE_COLORMAP)->get()) { GetGWorld(&savePort, &saveDevice); SetGWorld(gOffWorld, NULL); }*/ if ((**gTile).pixelType != RGBDirect) { GetPort(&oldPort); SetPort(win); (**gCTable).ctTable[index].value = index; (**gCTable).ctTable[index].rgb.red = (red << 8); (**gCTable).ctTable[index].rgb.green = (green << 8); (**gCTable).ctTable[index].rgb.blue = (blue << 8); SetEntries(index, index, (**gCTable).ctTable); CTabChanged(gCTable); SetPort(oldPort); } /*if (gOffWorld != NULL) //(SIM->get_param_bool(BXPN_PRIVATE_COLORMAP)->get()) SetGWorld(savePort, saveDevice);*/ if (SIM->get_param_bool(BXPN_PRIVATE_COLORMAP)->get()) { thePal = NewPalette(index, gCTable, pmTolerant, 0x5000); oldpal = GetPalette(win); SetPalette(win, thePal, false); SetPalette(fullwin, thePal, false); SetPalette(hidden, thePal, false); return(1); } return((**gTile).pixelType != RGBDirect); } // ::GRAPHICS_TILE_UPDATE() // // Called to request that a tile of graphics be drawn to the // screen, since info in this region has changed. // // tile: array of 8bit values representing a block of pixels with // dimension equal to the 'tilewidth' & 'tileheight' parameters to // ::specific_init(). Each value specifies an index into the // array of colors you allocated for ::palette_change() // x0: x origin of tile // y0: y origin of tile // // note: origin of tile and of window based on (0,0) being in the upper // left of the window. void bx_macintosh_gui_c::graphics_tile_update(Bit8u *tile, unsigned x0, unsigned y0) { Rect destRect; OSErr theError; Ptr theBaseAddr; GrafPtr oldPort; /*GDHandle saveDevice; CGrafPtr savePort; GetGWorld(&savePort, &saveDevice); SetGWorld(gOffWorld, NULL); */ GetPort(&oldPort); SetPort(win); destRect = srcTileRect; OffsetRect(&destRect, x0, y0); //(**gTile).baseAddr = (Ptr)tile; if ((theBaseAddr = GetPixBaseAddr(gTile)) == NULL) BX_PANIC(("mac: gTile has NULL baseAddr (offscreen buffer purged)")); else if (vga_bpp == 24 || vga_bpp == 32) { for (unsigned iY = 0; iY < (srcTileRect.bottom-srcTileRect.top); iY++) { Bit8u *iA = ((Bit8u *)theBaseAddr) + iY * GetPixRowBytes(gTile); for (unsigned iX = 0; iX < (srcTileRect.right-srcTileRect.left); iX++) { iA[iX*4 + 3] = tile[((srcTileRect.right-srcTileRect.left)*iY+iX)*(vga_bpp>>3)]; iA[iX*4 + 2] = tile[((srcTileRect.right-srcTileRect.left)*iY+iX)*(vga_bpp>>3) + 1]; iA[iX*4 + 1] = tile[((srcTileRect.right-srcTileRect.left)*iY+iX)*(vga_bpp>>3) + 2]; iA[iX*4] = vga_bpp == 24 ? 0 : tile[((srcTileRect.right-srcTileRect.left)*iY+iX)*4 + 3]; } } } else BlockMoveData(tile, theBaseAddr, (srcTileRect.bottom-srcTileRect.top) * GetPixRowBytes(gTile)); RGBForeColor(&black); RGBBackColor(&white); CopyBits(GetPortBitMapForCopyBits(gOffWorld), &WINBITMAP(win), &srcTileRect, &destRect, srcCopy, NULL); if ((theError = QDError()) != noErr) BX_ERROR(("mac: CopyBits returned %hd", theError)); SetPort(oldPort); //SetGWorld(savePort, saveDevice); } // ::DIMENSION_UPDATE() // // Called when the VGA mode changes it's X,Y dimensions. // Resize the window to this size, but you need to add on // the height of the headerbar to the Y value. // // x: new VGA x size // y: new VGA y size (add headerbar_y parameter from ::specific_init(). // fheight: new VGA character height in text mode // fwidth : new VGA character width in text mode // bpp : bits per pixel in graphics mode void bx_macintosh_gui_c::dimension_update(unsigned x, unsigned y, unsigned fheight, unsigned fwidth, unsigned bpp) { if ((bpp != 1) && (bpp != 2) && (bpp != 4) && (bpp != 8) && (bpp != 15) && (bpp != 16) && (bpp != 24) && (bpp != 32)) { BX_PANIC(("%d bpp graphics mode not supported yet", bpp)); } if (bpp != vga_bpp) { free(gMyBuffer); if ((**gTile).pixelType == RGBDirect) gCTable = GetCTable(128); DisposeGWorld(gOffWorld); vga_bpp = bpp; CreateTile(); } if (fheight > 0) { text_cols = x / fwidth; text_rows = y / fheight; if (fwidth != 8) { x = x * 8 / fwidth; } if (fheight != 16) { y = y * 16 / fheight; } } if (x != width || y != height) { SizeWindow(win, x, y, false); SizeWindow(fullwin, x, y, false); SizeWindow(hidden, x, y, false); width = x; height = y; } host_xres = x; host_yres = y; host_bpp = bpp; } // ::CREATE_BITMAP() // // Create a monochrome bitmap of size 'xdim' by 'ydim', which will // be drawn in the headerbar. Return an integer ID to the bitmap, // with which the bitmap can be referenced later. // // bmap: packed 8 pixels-per-byte bitmap. The pixel order is: // bit0 is the left most pixel, bit7 is the right most pixel. // xdim: x dimension of bitmap // ydim: y dimension of bitmap // rewritten by tim senecal to use the cicn (color icon) resources instead unsigned bx_macintosh_gui_c::create_bitmap(const unsigned char *bmap, unsigned xdim, unsigned ydim) { unsigned i; unsigned char *data; long row_bytes, bytecount; bx_cicn[numPixMaps] = GetCIcon(numPixMaps+128); BX_ASSERT(bx_cicn[numPixMaps]); numPixMaps++; return(numPixMaps-1); } // ::HEADERBAR_BITMAP() // // Called to install a bitmap in the bochs headerbar (toolbar). // // bmap_id: will correspond to an ID returned from // ::create_bitmap(). 'alignment' is either BX_GRAVITY_LEFT // or BX_GRAVITY_RIGHT, meaning install the bitmap in the next // available leftmost or rightmost space. // f: a 'C' function pointer to callback when the mouse is clicked in // the boundaries of this bitmap. unsigned bx_macintosh_gui_c::headerbar_bitmap(unsigned bmap_id, unsigned alignment, void (*f)(void)) { unsigned hb_index; toolPixMaps++; hb_index = toolPixMaps-1; //bx_tool_pixmap[hb_index].pm = bx_pixmap[bmap_id]; bx_tool_pixmap[hb_index].cicn = bx_cicn[bmap_id]; bx_tool_pixmap[hb_index].alignment = alignment; bx_tool_pixmap[hb_index].f = f; if (alignment == BX_GRAVITY_LEFT) { bx_tool_pixmap[hb_index].xorigin = bx_bitmap_left_xorigin; bx_tool_pixmap[hb_index].yorigin = 0; // bx_bitmap_left_xorigin += (**bx_pixmap[bmap_id]).bounds.right; bx_bitmap_left_xorigin += 34; } else { // bx_bitmap_right_xorigin += (**bx_pixmap[bmap_id]).bounds.right; bx_bitmap_right_xorigin += 34; bx_tool_pixmap[hb_index].xorigin = bx_bitmap_right_xorigin; bx_tool_pixmap[hb_index].yorigin = 0; } return(hb_index); } // ::SHOW_HEADERBAR() // // Show (redraw) the current headerbar, which is composed of // currently installed bitmaps. void bx_macintosh_gui_c::show_headerbar(void) { Rect destRect; int i, xorigin; SetPort(toolwin); RGBForeColor(&medGrey); FillRect(&toolwin->portRect, &qd.black); for (i=0; i<toolPixMaps; i++) { if (bx_tool_pixmap[i].alignment == BX_GRAVITY_LEFT) xorigin = bx_tool_pixmap[i].xorigin; else xorigin = toolwin->portRect.right - bx_tool_pixmap[i].xorigin; SetRect(&destRect, xorigin, 0, xorigin+32, 32); //changed, simply plot the cicn for that button, in the prescribed rectangle PlotCIcon(&destRect, bx_tool_pixmap[i].cicn); } RGBForeColor(&black); } // ::REPLACE_BITMAP() // // Replace the bitmap installed in the headerbar ID slot 'hbar_id', // with the one specified by 'bmap_id'. 'bmap_id' will have // been generated by ::create_bitmap(). The old and new bitmap // must be of the same size. This allows the bitmap the user // sees to change, when some action occurs. For example when // the user presses on the floppy icon, it then displays // the ejected status. // // hbar_id: headerbar slot ID // bmap_id: bitmap ID void bx_macintosh_gui_c::replace_bitmap(unsigned hbar_id, unsigned bmap_id) { //bx_tool_pixmap[hbar_id].pm = bx_pixmap[bmap_id]; bx_tool_pixmap[hbar_id].cicn = bx_cicn[bmap_id]; show_headerbar(); } // ::EXIT() // // Called before bochs terminates, to allow for a graceful // exit from the native GUI mechanism. void bx_macintosh_gui_c::exit(void) { if (!menubarVisible) ShowMenubar(); // Make the menubar visible again InitCursor(); } #if 0 void bx_macintosh_gui_c::snapshot_handler(void) { PicHandle ScreenShot; long val; SetPort(win); ScreenShot = OpenPicture(&win->portRect); CopyBits(&win->portBits, &win->portBits, &win->portRect, &win->portRect, srcCopy, NULL); ClosePicture(); val = ZeroScrap(); HLock((Handle)ScreenShot); PutScrap(GetHandleSize((Handle)ScreenShot), 'PICT', *ScreenShot); HUnlock((Handle)ScreenShot); KillPicture(ScreenShot); } #endif // UpdateRgn() // // Updates the screen after the menubar and round corners have been hidden void UpdateRgn(RgnHandle rgn) { WindowPtr window; window = FrontWindow(); PaintBehind(window, rgn); CalcVisBehind(window, rgn); } // HidePointer() // // Hides the Mac mouse pointer void HidePointer() { HiliteMenu(0); HideCursor(); SetPort(win); SetPt(&scrCenter, 320, 240); LocalToGlobal(&scrCenter); ResetPointer(); GetMouse(&prevPt); cursorVisible = false; CheckItem(GetMenuHandle(mBochs), iCursor, false); } // ShowPointer() // // Shows the Mac mouse pointer void ShowPointer() { InitCursor(); cursorVisible = true; CheckItem(GetMenuHandle(mBochs), iCursor, true); } // HideTools() // // Hides the Bochs toolbar void HideTools() { HideWindow(toolwin); if (menubarVisible) { MoveWindow(win, gLeft, gMinTop, false); } else { MoveWindow(hidden, gLeft, gMinTop, false); } CheckItem(GetMenuHandle(mBochs), iTool, false); HiliteWindow(win, true); } // ShowTools() // // Shows the Bochs toolbar void ShowTools() { if (menubarVisible) { MoveWindow(win, gLeft, gMaxTop, false); } else { MoveWindow(hidden, gLeft, gMaxTop, false); } ShowWindow(toolwin); BringToFront(toolwin); SelectWindow(toolwin); HiliteWindow(win, true); //theGui->show_headerbar(); CheckItem(GetMenuHandle(mBochs), iTool, true); HiliteWindow(win, true); } // HideMenubar() // // Hides the menubar (obviously) void HideMenubar() { Rect mBarRect; RgnHandle grayRgn; grayRgn = LMGetGrayRgn(); gOldMBarHeight = GetMBarHeight(); LMSetMBarHeight(0); mBarRgn = NewRgn(); mBarRect = qd.screenBits.bounds; mBarRect.bottom = mBarRect.top + gOldMBarHeight; RectRgn(mBarRgn, &mBarRect); UnionRgn(grayRgn, mBarRgn, grayRgn); UpdateRgn(mBarRgn); cnrRgn = NewRgn(); RectRgn(cnrRgn, &qd.screenBits.bounds); DiffRgn(cnrRgn, grayRgn, cnrRgn); UnionRgn(grayRgn, cnrRgn, grayRgn); UpdateRgn(mBarRgn); HideWindow(win); ShowWindow(backdrop); SelectWindow(backdrop); hidden = win; win = fullwin; ShowWindow(win); SelectWindow(win); menubarVisible = false; CheckItem(GetMenuHandle(mBochs), iMenuBar, false); } // ShowMenubar() // // Makes the menubar visible again so other programs will display correctly. void ShowMenubar() { RgnHandle grayRgn; GrafPtr savePort; grayRgn = LMGetGrayRgn(); LMSetMBarHeight(gOldMBarHeight); DiffRgn(grayRgn, mBarRgn, grayRgn); DisposeRgn(mBarRgn); DrawMenuBar(); GetPort(&savePort); SetPort(LMGetWMgrPort()); SetClip(cnrRgn); FillRgn(cnrRgn, &qd.black); SetPort(savePort); DiffRgn(grayRgn, cnrRgn, grayRgn); DisposeRgn(cnrRgn); HideWindow(backdrop); win = hidden; hidden = fullwin; HideWindow(hidden); ShowWindow(win); HiliteWindow(win, true); menubarVisible = true; CheckItem(GetMenuHandle(mBochs), iMenuBar, true); } void HideConsole() { HideWindow(SouixWin); CheckItem(GetMenuHandle(mBochs), iConsole, false); } void ShowConsole() { ShowWindow(SouixWin); SelectWindow(SouixWin); CheckItem(GetMenuHandle(mBochs), iConsole, true); } // CreateKeyMap() // // Create a KCHR data structure to map Mac virtual key codes to Bochs key codes void CreateKeyMap(void) { const unsigned char KCHRHeader [258] = { 0, 1 }; const unsigned char KCHRTable [130] = { 0, 1, BX_KEY_A, BX_KEY_S, BX_KEY_D, BX_KEY_F, BX_KEY_H, BX_KEY_G, BX_KEY_Z, BX_KEY_X, BX_KEY_C, BX_KEY_V, BX_KEY_LEFT_BACKSLASH, BX_KEY_B, BX_KEY_Q, BX_KEY_W, BX_KEY_E, BX_KEY_R, BX_KEY_Y, BX_KEY_T, BX_KEY_1, BX_KEY_2, BX_KEY_3, BX_KEY_4, BX_KEY_6, BX_KEY_5, BX_KEY_EQUALS, BX_KEY_9, BX_KEY_7, BX_KEY_MINUS, BX_KEY_8, BX_KEY_0, BX_KEY_RIGHT_BRACKET, BX_KEY_O, BX_KEY_U, BX_KEY_LEFT_BRACKET, BX_KEY_I, BX_KEY_P, BX_KEY_ENTER, BX_KEY_L, BX_KEY_J, BX_KEY_SINGLE_QUOTE, BX_KEY_K, BX_KEY_SEMICOLON, BX_KEY_BACKSLASH, BX_KEY_COMMA, BX_KEY_SLASH, BX_KEY_N, BX_KEY_M, BX_KEY_PERIOD, BX_KEY_TAB, BX_KEY_SPACE, BX_KEY_GRAVE, BX_KEY_BACKSPACE, BX_KEY_KP_ENTER, BX_KEY_ESC, 0, // 0x36 (record button) 0, // 0x37 (cmd key) 0, // 0x38 (left shift) 0, // 0x39 (caps lock) 0, // 0x3A (left option/alt) 0, // 0x3B (left ctrl) 0, // 0x3C (right shift) 0, // 0x3D (right option/alt) 0, // 0x3E (right ctrl) 0, // 0x3F (fn key -- laptops) 0, // 0x40 BX_KEY_KP_DELETE, // KP_PERIOD 0, // 0x42 (move right/multiply) BX_KEY_KP_MULTIPLY, 0, // 0x44 BX_KEY_KP_ADD, 0, // 0x46 (move left/add) BX_KEY_NUM_LOCK, 0, // 0x48 (move down/equals) 0, // 0x49 0, // 0x4A BX_KEY_KP_DIVIDE, BX_KEY_KP_ENTER, 0, // 0x4D (move up/divide) BX_KEY_KP_SUBTRACT, 0, // 0x4F 0, // 0x50 BX_KEY_EQUALS, // 0x51 (kp equals) BX_KEY_KP_INSERT, // 0x52 (kp 0) BX_KEY_KP_END, // 0x53 (kp 1) BX_KEY_KP_DOWN, // 0x54 (kp 2) BX_KEY_KP_PAGE_DOWN, // 0x55 (kp 3) BX_KEY_KP_LEFT, // 0x56 (kp 4) BX_KEY_KP_5, BX_KEY_KP_RIGHT, // 0x58 (kp 6) BX_KEY_KP_HOME, // 0x59 (kp 7) 0, // 0x5A BX_KEY_KP_UP, // 0x5B (kp 8) BX_KEY_KP_PAGE_UP, // 0x5C (kp 9) 0, // 0x5D 0, // 0x5E 0, // 0x5F BX_KEY_F5, BX_KEY_F6, BX_KEY_F7, BX_KEY_F3, BX_KEY_F8, BX_KEY_F9, 0, // 0x66 BX_KEY_F11, 0, // 0x68 BX_KEY_PRINT, // 0x69 (print screen) 0, // 0x6A BX_KEY_SCRL_LOCK, // 0x6B (scroll lock) 0, // 0x6C BX_KEY_F10, BX_KEY_MENU, // 0x6E BX_KEY_F12, 0, // 0x70 BX_KEY_PAUSE, // 0x71 (pause) BX_KEY_INSERT, BX_KEY_HOME, BX_KEY_PAGE_UP, BX_KEY_DELETE, BX_KEY_F4, BX_KEY_END, BX_KEY_F2, BX_KEY_PAGE_DOWN, BX_KEY_F1, BX_KEY_LEFT, BX_KEY_RIGHT, BX_KEY_DOWN, BX_KEY_UP }; KCHR = NewPtrClear(390); if (KCHR == NULL) BX_PANIC(("mac: can't allocate memory for key map")); BlockMove(KCHRHeader, KCHR, sizeof(KCHRHeader)); BlockMove(KCHRTable, Ptr(KCHR + sizeof(KCHRHeader)), sizeof(KCHRTable)); } // CreateVGAFont() // // Create an array of PixMaps for the PC screen font void CreateVGAFont(void) { int i, x; unsigned char *fontData, curPixel; long row_bytes, bytecount; for (i=0; i<256; i++) { vgafont[i] = CreateBitMap(FONT_WIDTH, FONT_HEIGHT); row_bytes = (*(vgafont[i])).rowBytes; bytecount = row_bytes * FONT_HEIGHT; fontData = (unsigned char *)NewPtrClear(bytecount); for (x=0; x<16; x++) { //curPixel = ~(bx_vgafont[i].data[x]); curPixel = (bx_vgafont[i].data[x]); fontData[x*row_bytes] = reverse_bitorder(curPixel); } vgafont[i]->baseAddr = Ptr(fontData); } } // CreateBitMap() // Allocate a new bitmap and fill in the fields with appropriate // values. BitMap *CreateBitMap(unsigned width, unsigned height) { BitMap *bm; long row_bytes; row_bytes = ((width + 31) >> 5) << 2; bm = (BitMap *)calloc(1, sizeof(BitMap)); if (bm == NULL) BX_PANIC(("mac: can't allocate memory for pixmap")); SetRect(&bm->bounds, 0, 0, width, height); bm->rowBytes = row_bytes; // Quickdraw allocates a new color table by default, but we want to // use one we created earlier. return bm; } // CreatePixMap() // Allocate a new pixmap handle and fill in the fields with appropriate // values. PixMapHandle CreatePixMap(unsigned left, unsigned top, unsigned width, unsigned height, unsigned depth, CTabHandle clut) { PixMapHandle pm; long row_bytes; row_bytes = (((long) depth * ((long) width) + 31) >> 5) << 2; pm = NewPixMap(); if (pm == NULL) BX_PANIC(("mac: can't allocate memory for pixmap")); (**pm).bounds.left = left; (**pm).bounds.top = top; (**pm).bounds.right = left+width; (**pm).bounds.bottom = top+height; (**pm).pixelSize = depth; (**pm).rowBytes = row_bytes | 0x8000; DisposeCTable((**pm).pmTable); (**pm).pmTable = clut; // Quickdraw allocates a new color table by default, but we want to // use one we created earlier. return pm; } unsigned char reverse_bitorder(unsigned char b) { unsigned char ret=0; for (unsigned i=0; i<8; i++) { ret |= (b & 0x01) << (7-i); b >>= 1; } return(ret); } void bx_macintosh_gui_c::mouse_enabled_changed_specific (bx_bool val) { } #endif /* if BX_WITH_MACOS */
24.95532
141
0.651417
[ "object", "shape" ]
e10606f83cf81b2db3501217f18280985f7b026e
12,362
cpp
C++
pass/cse/pass_cse.cpp
maximiliantiao/livehd
88215f0d6fc395db96e6ed058f00b9205454bd0c
[ "BSD-3-Clause" ]
null
null
null
pass/cse/pass_cse.cpp
maximiliantiao/livehd
88215f0d6fc395db96e6ed058f00b9205454bd0c
[ "BSD-3-Clause" ]
null
null
null
pass/cse/pass_cse.cpp
maximiliantiao/livehd
88215f0d6fc395db96e6ed058f00b9205454bd0c
[ "BSD-3-Clause" ]
null
null
null
// This file is distributed under the BSD 3-Clause License. See LICENSE for details. #include "pass_cse.hpp" #include <time.h> #include <iterator> #include <string> #include "lgedgeiter.hpp" #include "lgraph.hpp" Pass_cse::Pass_cse() : Pass("cse") {} enum comp_result { none, equalset, subset, // this is subset of that superset // this is superset of that }; // haha class and_node_for_comp { // Node_Type_Op node_type_op; public: int idx; // int next_avail_pid; bool need_modify; typedef std::pair<Node_pin, int> NPPair; // <the node pin, to be replaced by idx> typedef std::map<int, int> CoverByNPMap; // key (idx) is covered by value (idx) CoverByNPMap cover_by_np_map; typedef std::vector<NPPair> NPPairVec; typedef std::vector<int> CoveredPos; // covered node pin positions in the np_pair_vec> typedef std::map<int, CoveredPos> CoveredPosMap; // <idx, covered node pin positions in the np_pair_vec> key covers value CoveredPosMap covered_pos_map; NPPairVec np_pair_vec; // <Node Pins: int != -1 means to be removed, it's the new idx which replaces it> and_node_for_comp() { need_modify = 0; } comp_result comp_dp(and_node_for_comp that_node) { // longest common substring algorithm NPPairVec A = this->np_pair_vec; NPPairVec B = that_node.np_pair_vec; typedef std::vector<std::vector<int>> Matrix; // typedef vector<int> Row; Matrix LCS; // int **LCS = new int[A.size() + 1][B.size() + 1]; // if A is null then LCS of A, B =0 int size_a = std::distance(begin(A), end(A)); for (int i = 0; i < size_a; i++) { LCS[0][i] = 0; } // if B is null then LCS of A, B =0 int size_b = std::distance(begin(B), end(B)); for (int i = 0; i < size_b; i++) { LCS[i][0] = 0; } int i = 1, j = 1; for (const auto &a : A) { for (const auto &b : B) { if (a.first.get_nid() == b.first.get_nid() && a.first.get_pid() == b.first.get_pid()) { LCS[i][j] = LCS[i - 1][j - 1] + 1; } else { LCS[i][j] = std::max(LCS[i - 1][j], LCS[i][j - 1]); } j++; } i++; } if (LCS[A.size()][B.size()] == A.size() && LCS[A.size()][B.size()] == B.size()) { fmt::print("A is equalset of B\n"); return (equalset); } else if (LCS[A.size()][B.size()] >= A.size()) { fmt::print("A is superset of B\n"); return (superset); } else if (LCS[A.size()][B.size()] >= B.size()) { fmt::print("A is subset of B\n"); return (subset); } throw std::runtime_error("what is this case?"); } comp_result comp(and_node_for_comp that_node) { // std::vector<pair<Node_pin(), int>>::const_iterator j; // existing nodes // std::vector<pair<Node_pin(), int>>::const_iterator i; // new challenger auto j = this->np_pair_vec.begin(); int int_i = 0; // int start = -1; // int end = 0; int cover_count = 0; int rep_count = 0; int overlap = 0; // # of overlap with previous replacing node Node_pin dummy_node = Node_pin(1, 1, 0); CoveredPos new_covered_pos; std::vector<int> conflict_idx_vec; NPPair last_pair = std::make_pair(dummy_node, -1); for (auto i = that_node.np_pair_vec.begin(); i != that_node.np_pair_vec.end(); ++i) { fmt::print("j.nid:{}, i.nid:{}, j.pid:{}, i.pid:{}\n", j->first.get_nid(), i->first.get_nid(), j->first.get_pid(), i->first.get_pid()); if (j->first.get_nid() == i->first.get_nid() && j->first.get_pid() == i->first.get_pid()) { // Replace could happen cover_count++; new_covered_pos.push_back(int_i); if (j->second > 0) { overlap += covered_pos_map[j->second].size(); if (overlap > that_node.np_pair_vec.size()) { return (none); } if (conflict_idx_vec.back() != j->second) { // new conflicted idx conflict_idx_vec.push_back(j->second); } } if (int_i > 0 && j->first.get_nid() == last_pair.first.get_nid() && j->first.get_pid() == last_pair.first.get_pid()) { // consecutive repetitive nodes rep_count++; } else { rep_count = 0; } j++; } else { // j i dont match if (cover_count > 0) { if (cover_count == rep_count && int_i > 0 && j->first.get_nid() == last_pair.first.get_nid() && j->first.get_pid() == last_pair.first.get_pid()) { // repeating from the beginning; dont inc any count, just continue // continue } else { break; } } if (cover_count < 0) { // nothing special // continue } } int_i++; last_pair.first = j->first; last_pair.second = j->second; } // end of for loop fmt::print("idx:{}, cover:{}, this:{}, that:{}\n", idx, cover_count, this->np_pair_vec.size(), that_node.np_pair_vec.size()); // haha if (overlap > 0) { if (cover_count < overlap && cover_count > 0) { return (none); } else if (cover_count >= overlap) { // remove old pairs, for (auto k = conflict_idx_vec.begin(); k != conflict_idx_vec.end(); ++k) { // CoveredPosMap[*k] is old covered pos for (auto ii = covered_pos_map[*k].begin(); ii != covered_pos_map[*k].end(); ++ii) { np_pair_vec[*ii].second = -1; // reset cover_by_np_map.erase(np_pair_vec[*ii].first.get_nid()); } // remove old covered_np_map entries covered_pos_map.erase(*k); } } // add new pairs for (auto jj = new_covered_pos.begin(); jj != new_covered_pos.end(); ++jj) { np_pair_vec[*jj].second = that_node.idx; cover_by_np_map[np_pair_vec[*jj].first.get_nid()] = that_node.idx; } // add new covered_np_map entry covered_pos_map[that_node.idx] = new_covered_pos; } else if (cover_count == that_node.np_pair_vec.size() && (this->np_pair_vec.size()) == that_node.np_pair_vec.size()) { // add new pairs for (auto jj = new_covered_pos.begin(); jj != new_covered_pos.end(); ++jj) { np_pair_vec[*jj].second = that_node.idx; cover_by_np_map[np_pair_vec[*jj].first.get_nid()] = that_node.idx; } // add new covered_np_map entry covered_pos_map[that_node.idx] = new_covered_pos; need_modify = 1; fmt::print("A is equalset of B\n"); return (equalset); } else if (cover_count == this->np_pair_vec.size()) { // add new pairs for (auto jj = new_covered_pos.begin(); jj != new_covered_pos.end(); ++jj) { np_pair_vec[*jj].second = that_node.idx; cover_by_np_map[np_pair_vec[*jj].first.get_nid()] = that_node.idx; } // add new covered_np_map entry covered_pos_map[that_node.idx] = new_covered_pos; need_modify = 1; fmt::print("A is subset of B\n"); return (subset); } // TODO: delete else { fmt::print("A is superset of B\n"); return (superset); } /* i=that_node.np_pair.begin(); int int_j = 0; start = -1; end = 0; for(j=this->np_pair.begin(); j!=this->np_pair.end(); ++j){ if (*j == *i) { if (start==-1) { start = int_j; } else { // started end = int_j; } i++; } else { if (start > -1) { //started break; } } int_j++; } if ((end - start + 1) == that_node.inp_idx.size() ) { return(superset); } */ throw std::runtime_error("what is this case?"); } // node_for_comp () {}; }; // haha/ void Pass_cse::traverse(LGraph *g, std::map<int, and_node_for_comp> &and_node_for_comp_map, int round) { for (auto idx : g->forward()) { fmt::print("{} round visited idx:{}\n", round, idx); std::string temp_key; switch (g->node_type_get(idx).op) { case Invalid_Op: fmt::print("Invalid_Op.\n"); break; case Sum_Op: fmt::print("Sum_Op.\n"); break; case Mult_Op: fmt::print("Mult_Op.\n"); break; case Not_Op: fmt::print("Not_Op.\n"); break; case Join_Op: fmt::print("Join_Op.\n"); break; case And_Op: { fmt::print("And_Op.\n"); if (round == 1) { // haha comp_result result; and_node_for_comp new_node_for_comp; new_node_for_comp.idx = idx; for (const auto &in_edge : g->inp_edges(idx)) { std::pair<Node_pin, int> new_pair = std::make_pair(in_edge.get_out_pin(), -1); new_node_for_comp.np_pair_vec.push_back(new_pair); } for (auto i : and_node_for_comp_map) { fmt::print("Before comp.\n"); result = new_node_for_comp.comp(i.second); std::string to_print; switch (result) { case equalset: to_print = "equalset"; break; case subset: to_print = "subset"; break; case superset: to_print = "superset"; break; default: to_print = "WEIRD?"; break; } fmt::print("result is {}.\n", to_print); } and_node_for_comp_map.insert(std::make_pair(idx, new_node_for_comp)); // haha// } else if (round == 2) { for (const auto &in_edge : g->inp_edges(idx)) { // haha and_node_for_comp new_node_for_comp = and_node_for_comp_map[idx]; Node_pin out_pin = in_edge.get_out_pin(); std::map<int, bool> local_map; // <idx, exist> auto it = (new_node_for_comp.cover_by_np_map).find(out_pin.get_nid()); if (it != new_node_for_comp.cover_by_np_map.end()) { // add new input edge if (local_map.find(it->second) == local_map.end()) { Node_pin dst = Node_pin(idx, 0, 1); Node_pin src = Node_pin(it->second, 0, 0); g->add_edge(src, dst); local_map.insert(std::make_pair(it->second, 1)); fmt::print("Adding edge from {} to {}.\n", it->second, idx); } // rm old edges new_node_for_comp.cover_by_np_map.erase(it); fmt::print("Removing edge from {} to {}.\n", in_edge.get_idx(), idx); fmt::print("IN EDGE idx:{}, in_pid:{}, out_pid:{}\n", in_edge.get_idx(), in_edge.get_inp_pin().get_pid(), in_edge.get_out_pin().get_pid()); g->del_edge(in_edge); fmt::print("Edge deleted\n"); } // haha*/ } } } break; case Or_Op: fmt::print("Or_Op.\n"); break; case Xor_Op: fmt::print("Xor_Op.\n"); break; case SFlop_Op: fmt::print("SFlop_Op.\n"); break; case LessThan_Op: fmt::print("LessThan_Op.\n"); break; case GreaterThan_Op: fmt::print("GreaterThan_Op.\n"); break; case GraphIO_Op: fmt::print("GraphIO_Op.\n"); break; case SubGraph_Op: fmt::print("SubGraph_Op.\n"); break; case U32Const_Op: fmt::print("U32Const_Op.\n"); break; case StrConst_Op: fmt::print("StrConst_Op.\n"); break; default: fmt::print("Undefined OP.\n"); } // end of switch for (const auto &in_edge : g->inp_edges(idx)) { fmt::print("IN EDGE idx:{}, in_pid:{}, out_pid:{}\n", in_edge.get_idx(), in_edge.get_inp_pin().get_pid(), in_edge.get_out_pin().get_pid()); } } // end of for loop: for(auto idx:g->forward()) } void Pass_cse::transform(LGraph *g) { std::map<int, and_node_for_comp> and_node_for_comp_map; // idx, node // std::map<std::string, int> idx_map; // <op_sort_pid, idx> fmt::print("trying a graph with {} size\n", g->size()); traverse(g, and_node_for_comp_map, 1); traverse(g, and_node_for_comp_map, 2); traverse(g, and_node_for_comp_map, 3); }
38.63125
131
0.541822
[ "vector", "transform" ]
e10738ca966db5c48da91df9a18e8f560a6f0619
6,004
cpp
C++
tools/converter/source/optimizer/onnxextra/OnnxPrelu.cpp
jinfagang/MNN
f10b2203dbb27432155f863f1dfd65a156d57a09
[ "Apache-2.0" ]
null
null
null
tools/converter/source/optimizer/onnxextra/OnnxPrelu.cpp
jinfagang/MNN
f10b2203dbb27432155f863f1dfd65a156d57a09
[ "Apache-2.0" ]
null
null
null
tools/converter/source/optimizer/onnxextra/OnnxPrelu.cpp
jinfagang/MNN
f10b2203dbb27432155f863f1dfd65a156d57a09
[ "Apache-2.0" ]
null
null
null
// // OnnxPrelu.cpp // MNNConverter // // Created by MNN on 2019/10/23. // Copyright © 2018, Alibaba Group Holding Limited // #include "MNN_generated.h" #include "OnnxExtraManager.hpp" namespace MNN { namespace Express { class OnnxPreluTransform : public OnnxExtraManager::Transform { public: virtual EXPRP onExecute(EXPRP expr) const override { auto inputs = expr->inputs(); MNN_THROW_CHECK(inputs.size() == 2, "Onnx Prelu Should have 2 inputs!"); auto slope = inputs[1]; auto slopeInfo = slope->getInfo(); auto slopeData = slope->readMap<float>(); if (slopeInfo == nullptr || slopeData == nullptr) { auto k = _Select(_Less(inputs[0], _Scalar<float>(0)), slope, _Scalar<float>(1)); auto res = _Multiply(inputs[0], k); res->setName(expr->outputName(0)); return res->expr().first; } const int slopeSize = slopeInfo->size; std::unique_ptr<PReluT> preluParam(new PReluT); preluParam->slopeCount = slopeSize; preluParam->slope.resize(slopeSize); memcpy(preluParam->slope.data(), slopeData, slopeSize * sizeof(float)); // prelu(input, slope) => mergedPrelu(input) std::unique_ptr<OpT> mergedOp(new OpT); mergedOp->name = expr->name(); mergedOp->type = OpType_PReLU; mergedOp->main.type = OpParameter_PRelu; mergedOp->main.value = preluParam.release(); auto newExpr = Expr::create(mergedOp.get(), {inputs[0]}); newExpr->setName(expr->name()); return newExpr; } }; class OnnxCeluTransform : public OnnxExtraManager::Transform { public: virtual EXPRP onExecute(EXPRP expr) const override { float alpha = 1; auto attrs = expr->get()->main_as_Extra()->attr(); if (attrs != nullptr) { for (const auto& attr : *attrs) { if (attr->key()->str() == "alpha") { alpha = attr->f(); } } } auto input = expr->inputs()[0]; auto alphaVar = _Const(alpha); auto y = _Multiply(_Subtract(_Exp(_Divide(input, alphaVar)), _Const(1.0f)), alphaVar); auto res = _Select(_Less(input, _Const(0.0f)), y, input); auto newExpr = res->expr().first; newExpr->setName(expr->name()); return newExpr; } }; class OnnxThresholdedReluTransform : public OnnxExtraManager::Transform { public: virtual EXPRP onExecute(EXPRP expr) const override { float alpha = 1; auto attrs = expr->get()->main_as_Extra()->attr(); if (attrs != nullptr) { for (const auto& attr : *attrs) { if (attr->key()->str() == "alpha") { alpha = attr->f(); } } } auto input = expr->inputs()[0]; auto res = _Select(_Greater(input, _Const(alpha)), input, _Const(0.0f)); auto newExpr = res->expr().first; newExpr->setName(expr->name()); return newExpr; } }; class OnnxShrinkTransform : public OnnxExtraManager::Transform { public: virtual EXPRP onExecute(EXPRP expr) const override { float bias = 0, lambd = 0.5; auto attrs = expr->get()->main_as_Extra()->attr(); if (attrs != nullptr) { for (const auto& attr : *attrs) { if (attr->key()->str() == "bias") { bias = attr->f(); } else if (attr->key()->str() == "lambd") { lambd = attr->f(); } } } auto input = expr->inputs()[0]; auto biasVar = _Const(bias); auto res = _Select(_Greater(input, _Const(lambd)), _Subtract(input, biasVar), // x-bias for x > lambd _Select(_Less(input, _Const(-lambd)), _Add(input, biasVar), // x+bias for x < -lambd _Const(0.0))); // 0 for otherwise auto newExpr = res->expr().first; newExpr->setName(expr->name()); return newExpr; } }; class OnnxTriluTransform : public OnnxExtraManager::Transform { public: virtual EXPRP onExecute(EXPRP expr) const override { auto inputs = expr->inputs(); auto shape = _Shape(inputs[0]), zero = _Scalar<int>(0), oneV = _Unsqueeze(_Scalar<int>(1), {0}); auto H = _Slice(shape, _Unsqueeze(_Scalar<int>(-2), {0}), oneV), W = _Slice(shape, _Unsqueeze(_Scalar<int>(-1), {0}), oneV); auto rangeH = _Unsqueeze(_Range(zero, H, oneV), {1}), rangeW = _Unsqueeze(_Range(zero, W, oneV), {0}); bool upper = true; auto attrs = expr->get()->main_as_Extra()->attr(); if (attrs != nullptr) { for (const auto& attr : *attrs) { if (attr->key()->str() == "upper") { upper = attr->i(); } } } auto k = (inputs.size() == 2 ? inputs[1] : _Scalar<int>(0)); auto mask = (upper ? _GreaterEqual(rangeW, rangeH + k) : _GreaterEqual(rangeH, rangeW - k)); mask = _Reshape(mask, _Concat({_Fill(_Size(shape) - _Scalar<int>(2), oneV), _Shape(mask)}, 0)); auto res = _Select(mask, inputs[0], zero); res->setName(expr->outputName(0)); return res->expr().first; } }; static auto gRegister = []() { OnnxExtraManager::get()->insert("PRelu", std::shared_ptr<OnnxExtraManager::Transform>(new OnnxPreluTransform)); OnnxExtraManager::get()->insert("Celu", std::shared_ptr<OnnxExtraManager::Transform>(new OnnxCeluTransform)); OnnxExtraManager::get()->insert("ThresholdedRelu", std::shared_ptr<OnnxExtraManager::Transform>(new OnnxThresholdedReluTransform)); OnnxExtraManager::get()->insert("Shrink", std::shared_ptr<OnnxExtraManager::Transform>(new OnnxShrinkTransform)); OnnxExtraManager::get()->insert("Trilu", std::shared_ptr<OnnxExtraManager::Transform>(new OnnxTriluTransform)); return true; }(); } // namespace Express } // namespace MNN
38.735484
135
0.573784
[ "shape", "transform" ]
e107a166ec171e731001d34d070013e0587ff9fa
916
cpp
C++
JianZhi_OFFER/JZ_56-2.cpp
drt4243566/leetcode_learn
ef51f215079556895eec2252d84965cd1c3a7bf4
[ "MIT" ]
null
null
null
JianZhi_OFFER/JZ_56-2.cpp
drt4243566/leetcode_learn
ef51f215079556895eec2252d84965cd1c3a7bf4
[ "MIT" ]
null
null
null
JianZhi_OFFER/JZ_56-2.cpp
drt4243566/leetcode_learn
ef51f215079556895eec2252d84965cd1c3a7bf4
[ "MIT" ]
null
null
null
#include <vector> using namespace std; // 解题原则是将数字都用二进制表示之后,单看某一位,累加的结果对3取余数,只剩下只出现一次的数字的位 // 神仙解法 -- 有限状态机 // 只用00,01,10三种状态(two,one)表示单个数据位上的状态;在遍历结束后,必然是在00和01状态中的一个,这个由one来记录; // 创建int类型的ones和twos,相当于在32位上进行相同的操作,一步到位; class Solution { public: int singleNumber(vector<int>& nums) { int ones=0,twos=0; for(int n:nums){ ones = ones^n&~twos; twos = twos^n&~ones; } return ones; } }; // 另一种思路 ———— 选择用长度位32的数组来记录每位上累加的结果,最后取余 class Solution1 { public: int singleNumber(vector<int>& nums) { vector<int> counts(32,0); for(int n:nums){ for(int j=0;j<32;j++){ counts[j] += n&1; n >>= 1; } } // 复原要找的数字,每次先左移一位,再进行或操作 int res=0,m=3; for(int i=0;i<32;i++){ res<<=1; res|=counts[31-i]%m; } return res; } };
24.105263
71
0.528384
[ "vector" ]
e108972c7938561847c0cbfe59cbdccfefd93d82
1,722
cpp
C++
sources/cards/creatures/reds/GoblinGang.cpp
angeluriot/Magic_royal
a337ce4ad6c3215bbdec8c376d6e88fe97f48f94
[ "MIT" ]
1
2022-02-02T21:41:59.000Z
2022-02-02T21:41:59.000Z
sources/cards/creatures/reds/GoblinGang.cpp
angeluriot/Magic_royal
a337ce4ad6c3215bbdec8c376d6e88fe97f48f94
[ "MIT" ]
null
null
null
sources/cards/creatures/reds/GoblinGang.cpp
angeluriot/Magic_royal
a337ce4ad6c3215bbdec8c376d6e88fe97f48f94
[ "MIT" ]
2
2022-02-01T12:59:57.000Z
2022-03-05T12:50:27.000Z
#include "cards/creatures/reds/GoblinGang.hpp" #include "players/Player.hpp" #include "renderer/print.hpp" GoblinGang::GoblinGang(): Creature(get_full_power(), get_full_toughness(), get_capacities()) {} GoblinGang::~GoblinGang() {} std::string GoblinGang::get_full_type() const { return Creature::get_full_type() + " - Goblin"; } Card::Color GoblinGang::get_color() const { return Color::Red; } std::string GoblinGang::get_name() const { return "Goblin Gang"; } std::vector<Creature::Capacity> GoblinGang::get_capacities() const { return { Capacity::Reach }; } std::string GoblinGang::get_description() const { return Creature::get_description() + "Adds 1 power to all Goblin type allies while alive."; } Card::Cost GoblinGang::get_cost() const { return { { Color::Colorless, 2 }, { Color::Red, 1 } }; } int GoblinGang::get_full_power() const { return 3; } int GoblinGang::get_full_toughness() const { return 2; } void GoblinGang::spawn() { Creature::spawn(); std::cout << cyan << "[INFO] " << ::reset << italic << ::get_color(get_color()) << get_name() << ::reset << " addded 1 power to all Goblin type allies." << End(2); for (auto& creature : m_owner->creatures) if (creature.get_full_type() == "Creature - Goblin") creature.modify_power(1); } void GoblinGang::special_ability() { Creature::special_ability(); std::cout << cyan << "[INFO] " << ::reset << italic << ::get_color(get_color()) << get_name() << ::reset << " addded 1 power to all Goblin type allies." << End(2); for (auto& creature : m_owner->creatures) if (creature.get_full_type() == "Creature - Goblin") creature.modify_power(1); } Card* GoblinGang::clone() const { return new GoblinGang(*this); }
20.5
108
0.676539
[ "vector" ]
e109827fcd05484175b8d58a677e9d87035ed41b
839
cc
C++
uva/10685.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
506
2018-08-22T10:30:38.000Z
2022-03-31T10:01:49.000Z
uva/10685.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
13
2019-08-07T18:31:18.000Z
2020-12-15T21:54:41.000Z
uva/10685.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
234
2018-08-06T17:11:41.000Z
2022-03-26T10:56:42.000Z
// https://uva.onlinejudge.org/external/106/10685.pdf #include<bits/stdc++.h> using namespace std; using vi=vector<int>; using vvi=vector<vi>; using msi=unordered_map<string,int>; int main(){ int n,m,u,v; while(1){ cin>>n>>m; if(!n)break; vvi g(n); int k=0; msi d; for(int i=0;i<n;i++){ string s; cin>>s; d[s]=k++; } for(int i=0;i<m;i++){ string s,t; cin>>s>>t; u=d[s];v=d[t]; g[u].push_back(v); g[v].push_back(u); } vi c(n); function<void(int,int)>dfs=[&](int u,int k){ c[u]=k; for(int v:g[u]) if(!c[v]) dfs(v,k); }; k=1; for(int i=0;i<n;i++) if(!c[i]) dfs(i,k++); vi s(k); for(int i=0;i<n;i++) s[c[i]]++; int M=0; for(int x:s)M=max(M,x); cout<<M<<endl; } }
18.23913
53
0.457688
[ "vector" ]
e10a47c571765969474f562cfdb91e2677e7983a
47,483
cc
C++
src/sentencepiece_processor_test.cc
wanchichen/sentencepiece
c9ea0f3e08357879ea35e453f791a7ff5ee129a9
[ "Apache-2.0" ]
1
2021-02-19T12:19:38.000Z
2021-02-19T12:19:38.000Z
src/sentencepiece_processor_test.cc
wanchichen/sentencepiece
c9ea0f3e08357879ea35e453f791a7ff5ee129a9
[ "Apache-2.0" ]
null
null
null
src/sentencepiece_processor_test.cc
wanchichen/sentencepiece
c9ea0f3e08357879ea35e453f791a7ff5ee129a9
[ "Apache-2.0" ]
null
null
null
// Copyright 2016 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 "sentencepiece_processor.h" #include <utility> #include "builder.h" #include "filesystem.h" #include "model_interface.h" #include "normalizer.h" #include "sentencepiece.pb.h" #include "sentencepiece_model.pb.h" #include "sentencepiece_trainer.h" #include "testharness.h" #include "third_party/absl/container/flat_hash_map.h" #include "third_party/absl/memory/memory.h" #include "third_party/absl/strings/str_cat.h" #include "third_party/absl/strings/string_view.h" #include "util.h" namespace sentencepiece { // Space symbol #define WS "\xe2\x96\x81" class MockModel : public ModelInterface { public: void SetEncodeResult(absl::string_view input, const EncodeResult &output) { input_ = input; output_ = output; } void SetNBestEncodeResult(absl::string_view input, const NBestEncodeResult &output) { input_ = input; nbest_output_ = output; } EncodeResult Encode(absl::string_view normalized) const { EXPECT_EQ(normalized, input_); return output_; } EncodeResult SampleEncode(absl::string_view normalized, float alpha) const { EXPECT_EQ(normalized, input_); return output_; } NBestEncodeResult NBestEncode(absl::string_view normalized, int nbest_size) const { EXPECT_EQ(normalized, input_); return nbest_output_; } bool IsSampleEncodeAvailable() const override { return true; } bool IsNBestEncodeAvailable() const override { return true; } bool IsControl(int id) const { return id == 1 || id == 2; } bool IsUnknown(int id) const { return id == 0; } int GetPieceSize() const { return 10; } int PieceToId(absl::string_view piece) const { return 0; } const std::string &IdToPiece(int id) const { return kEmptyString; } float GetScore(int id) const { return 0.0; } private: absl::string_view input_; EncodeResult output_; NBestEncodeResult nbest_output_; const std::string kEmptyString; }; class ByteFallbackMockModel : public MockModel { public: bool ByteFallbackEnabled() const override { return true; } }; std::vector<std::string> GetSpVec(const EncodeResult &pieces) { std::vector<std::string> sps; for (const auto &p : pieces) { sps.emplace_back(std::string(p.first)); } return sps; } std::vector<int> GetIdVec(const EncodeResult &pieces) { std::vector<int> ids; for (const auto &p : pieces) { ids.emplace_back(p.second); } return ids; } std::vector<std::string> GetSpVec(const SentencePieceText &spt) { std::vector<std::string> sps; for (auto &sp : spt.pieces()) { sps.emplace_back(sp.piece()); } return sps; } NormalizerSpec MakeDefaultNormalizerSpec() { return SentencePieceTrainer::GetNormalizerSpec("nmt_nfkc"); } TEST(SentencepieceProcessorTest, StatusTest) { SentencePieceProcessor sp; EXPECT_FALSE(sp.status().ok()); auto mock = absl::make_unique<MockModel>(); sp.SetModel(std::move(mock)); EXPECT_FALSE(sp.status().ok()); } TEST(SentencepieceProcessorTest, EncodeTest) { const absl::string_view kInput = WS "ABC" WS "DEF"; SentencePieceProcessor sp; const auto normalization_spec = MakeDefaultNormalizerSpec(); { auto mock = absl::make_unique<MockModel>(); const EncodeResult result = { {WS "ABC", 3}, {WS "DE", 4}, {"F", 0}, {"</s>", 2}}; mock->SetEncodeResult(kInput, result); sp.SetModel(std::move(mock)); sp.SetNormalizer( absl::make_unique<normalizer::Normalizer>(normalization_spec)); std::vector<std::string> output; EXPECT_TRUE(sp.Encode("ABC DEF", &output).ok()); EXPECT_EQ(GetSpVec(result), output); std::vector<int> ids; EXPECT_TRUE(sp.Encode("ABC DEF", &ids).ok()); EXPECT_EQ(GetIdVec(result), ids); SentencePieceText spt; EXPECT_TRUE(sp.Encode("ABC DEF", &spt).ok()); EXPECT_EQ(4, spt.pieces_size()); for (int i = 0; i < 4; ++i) { EXPECT_EQ(result[i].first, spt.pieces(i).piece()); } SentencePieceText spt2; EXPECT_TRUE(spt2.ParseFromString(sp.EncodeAsSerializedProto("ABC DEF"))); EXPECT_EQ(spt.SerializeAsString(), spt2.SerializeAsString()); EXPECT_EQ("ABC", spt.pieces(0).surface()); EXPECT_EQ(" DE", spt.pieces(1).surface()); EXPECT_EQ("F", spt.pieces(2).surface()); EXPECT_EQ("", spt.pieces(3).surface()); // </s> EXPECT_EQ(3, spt.pieces(0).id()); EXPECT_EQ(4, spt.pieces(1).id()); EXPECT_EQ(0, spt.pieces(2).id()); EXPECT_EQ(2, spt.pieces(3).id()); EXPECT_EQ(0, spt.pieces(0).begin()); EXPECT_EQ(3, spt.pieces(0).end()); EXPECT_EQ(3, spt.pieces(1).begin()); EXPECT_EQ(6, spt.pieces(1).end()); EXPECT_EQ(6, spt.pieces(2).begin()); EXPECT_EQ(7, spt.pieces(2).end()); EXPECT_EQ(7, spt.pieces(3).begin()); EXPECT_EQ(7, spt.pieces(3).end()); } // Unknown sequences. { auto mock = absl::make_unique<MockModel>(); const EncodeResult result = { {WS "ABC", 3}, {WS "D", 4}, {"E", 0}, {"F", 0}, {"</s>", 2}}; const EncodeResult expected = { {WS "ABC", 3}, {WS "D", 4}, {"EF", 0}, {"</s>", 2}}; mock->SetEncodeResult(kInput, result); sp.SetModel(std::move(mock)); sp.SetNormalizer( absl::make_unique<normalizer::Normalizer>(normalization_spec)); std::vector<std::string> output; EXPECT_TRUE(sp.Encode("ABC DEF", &output).ok()); EXPECT_EQ(GetSpVec(expected), output); std::vector<int> ids; EXPECT_TRUE(sp.Encode("ABC DEF", &ids).ok()); EXPECT_EQ(GetIdVec(expected), ids); SentencePieceText spt; EXPECT_TRUE(sp.Encode("ABC DEF", &spt).ok()); EXPECT_EQ(4, spt.pieces_size()); for (int i = 0; i < 4; ++i) { EXPECT_EQ(expected[i].first, spt.pieces(i).piece()); } EXPECT_EQ("ABC", spt.pieces(0).surface()); EXPECT_EQ(" D", spt.pieces(1).surface()); EXPECT_EQ("EF", spt.pieces(2).surface()); EXPECT_EQ("", spt.pieces(3).surface()); // </s> EXPECT_EQ(3, spt.pieces(0).id()); EXPECT_EQ(4, spt.pieces(1).id()); EXPECT_EQ(0, spt.pieces(2).id()); EXPECT_EQ(2, spt.pieces(3).id()); EXPECT_EQ(0, spt.pieces(0).begin()); EXPECT_EQ(3, spt.pieces(0).end()); EXPECT_EQ(3, spt.pieces(1).begin()); EXPECT_EQ(5, spt.pieces(1).end()); EXPECT_EQ(5, spt.pieces(2).begin()); EXPECT_EQ(7, spt.pieces(2).end()); EXPECT_EQ(7, spt.pieces(3).begin()); EXPECT_EQ(7, spt.pieces(3).end()); } // Byte-fallback. { const absl::string_view kInput2 = WS "ABC" WS "DEFあ"; auto mock = absl::make_unique<ByteFallbackMockModel>(); const EncodeResult result = {{WS "ABC", 3}, {WS "D", 4}, {"E", 0}, {"F", 0}, {"あ", 0}, {"</s>", 2}}; // "E" -> 0x45 // "F" -> 0x46 // "あ" -> 0xe38182 const EncodeResult expected = {{WS "ABC", 3}, {WS "D", 4}, {"<0x45>", 0}, {"<0x46>", 0}, {"<0xE3>", 0}, {"<0x81>", 0}, {"<0x82>", 0}, {"</s>", 2}}; mock->SetEncodeResult(kInput2, result); sp.SetModel(std::move(mock)); sp.SetNormalizer( absl::make_unique<normalizer::Normalizer>(normalization_spec)); std::vector<std::string> output; EXPECT_TRUE(sp.Encode("ABC DEFあ", &output).ok()); EXPECT_EQ(GetSpVec(expected), output); std::vector<int> ids; EXPECT_TRUE(sp.Encode("ABC DEFあ", &ids).ok()); EXPECT_EQ(GetIdVec(expected), ids); SentencePieceText spt; EXPECT_TRUE(sp.Encode("ABC DEFあ", &spt).ok()); EXPECT_EQ(8, spt.pieces_size()); for (int i = 0; i < 8; ++i) { EXPECT_EQ(expected[i].first, spt.pieces(i).piece()); } EXPECT_EQ("ABC", spt.pieces(0).surface()); EXPECT_EQ(" D", spt.pieces(1).surface()); EXPECT_EQ("E", spt.pieces(2).surface()); EXPECT_EQ("F", spt.pieces(3).surface()); EXPECT_EQ("", spt.pieces(4).surface()); // あ EXPECT_EQ("", spt.pieces(5).surface()); // あ EXPECT_EQ("あ", spt.pieces(6).surface()); // あ EXPECT_EQ("", spt.pieces(7).surface()); // </s> EXPECT_EQ(3, spt.pieces(0).id()); EXPECT_EQ(4, spt.pieces(1).id()); EXPECT_EQ(0, spt.pieces(2).id()); EXPECT_EQ(0, spt.pieces(3).id()); EXPECT_EQ(0, spt.pieces(4).id()); EXPECT_EQ(0, spt.pieces(5).id()); EXPECT_EQ(0, spt.pieces(6).id()); EXPECT_EQ(2, spt.pieces(7).id()); EXPECT_EQ(0, spt.pieces(0).begin()); EXPECT_EQ(3, spt.pieces(0).end()); EXPECT_EQ(3, spt.pieces(1).begin()); EXPECT_EQ(5, spt.pieces(1).end()); EXPECT_EQ(5, spt.pieces(2).begin()); EXPECT_EQ(6, spt.pieces(2).end()); EXPECT_EQ(6, spt.pieces(3).begin()); EXPECT_EQ(7, spt.pieces(3).end()); EXPECT_EQ(7, spt.pieces(4).begin()); // あ EXPECT_EQ(7, spt.pieces(4).end()); EXPECT_EQ(7, spt.pieces(5).begin()); // あ EXPECT_EQ(7, spt.pieces(5).end()); EXPECT_EQ(7, spt.pieces(6).begin()); // あ EXPECT_EQ(10, spt.pieces(6).end()); EXPECT_EQ(10, spt.pieces(7).begin()); // </s> EXPECT_EQ(10, spt.pieces(7).end()); } // Crash if // ModelInterface::Encode() returns shorter results. { auto mock = absl::make_unique<MockModel>(); const EncodeResult result = {{WS "ABC", 3}}; mock->SetEncodeResult(kInput, result); sp.SetModel(std::move(mock)); sp.SetNormalizer( absl::make_unique<normalizer::Normalizer>(normalization_spec)); SentencePieceText spt; // Expects crash. EXPECT_FALSE(sp.Encode("ABC DEF", &spt).ok()); } // Crash if // ModelInterface::Encode() returns longer results. { auto mock = absl::make_unique<MockModel>(); const EncodeResult result = { {WS "ABC", 3}, {WS "DE", 4}, {"F", 5}, {"G", 6}}; mock->SetEncodeResult(kInput, result); sp.SetModel(std::move(mock)); sp.SetNormalizer( absl::make_unique<normalizer::Normalizer>(normalization_spec)); SentencePieceText spt; // Expects crash. EXPECT_FALSE(sp.Encode("ABC DEF", &spt).ok()); } // Crash if // ModelInterface::Encode() returns an empty piece. { auto mock = absl::make_unique<MockModel>(); const EncodeResult result = { {WS "ABC", 3}, {WS "DE", 4}, {"", 5}, {"F", 6}}; mock->SetEncodeResult(kInput, result); sp.SetModel(std::move(mock)); sp.SetNormalizer( absl::make_unique<normalizer::Normalizer>(normalization_spec)); SentencePieceText spt; // Expects crash. EXPECT_FALSE(sp.Encode("ABC DEF", &spt).ok()); } // Halfwidth to Fullwidith katakana normalization. { auto mock = absl::make_unique<MockModel>(); const EncodeResult result = {{WS "グー", 3}, {"グル", 4}, {"</s>", 2}}; const absl::string_view input = WS "グーグル"; mock->SetEncodeResult(input, result); sp.SetModel(std::move(mock)); std::vector<std::string> output; EXPECT_TRUE(sp.Encode("グーグル", &output).ok()); EXPECT_EQ(GetSpVec(result), output); SentencePieceText spt; EXPECT_TRUE(sp.Encode("グーグル", &spt).ok()); EXPECT_EQ(3, spt.pieces_size()); for (int i = 0; i < 3; ++i) { EXPECT_EQ(result[i].first, spt.pieces(i).piece()); } EXPECT_EQ("グー", spt.pieces(0).surface()); EXPECT_EQ("グル", spt.pieces(1).surface()); EXPECT_EQ("", spt.pieces(2).surface()); EXPECT_EQ(3, spt.pieces(0).id()); EXPECT_EQ(4, spt.pieces(1).id()); EXPECT_EQ(2, spt.pieces(2).id()); EXPECT_EQ(0, spt.pieces(0).begin()); EXPECT_EQ(9, spt.pieces(0).end()); EXPECT_EQ(9, spt.pieces(1).begin()); EXPECT_EQ(18, spt.pieces(1).end()); EXPECT_EQ(18, spt.pieces(2).begin()); // </s> EXPECT_EQ(18, spt.pieces(2).end()); } // One to many normalization. { auto mock = absl::make_unique<MockModel>(); const EncodeResult result = {{WS "株式", 3}, {"会社", 4}, {"</s>", 2}}; const absl::string_view input = WS "株式会社"; mock->SetEncodeResult(input, result); sp.SetModel(std::move(mock)); std::vector<std::string> output; EXPECT_TRUE(sp.Encode("㍿", &output).ok()); EXPECT_EQ(GetSpVec(result), output); SentencePieceText spt; EXPECT_TRUE(sp.Encode("㍿", &spt).ok()); EXPECT_EQ(3, spt.pieces_size()); for (int i = 0; i < 3; ++i) { EXPECT_EQ(result[i].first, spt.pieces(i).piece()); } EXPECT_EQ("", spt.pieces(0).surface()); EXPECT_EQ("㍿", spt.pieces(1).surface()); EXPECT_EQ("", spt.pieces(2).surface()); EXPECT_EQ(3, spt.pieces(0).id()); EXPECT_EQ(4, spt.pieces(1).id()); EXPECT_EQ(2, spt.pieces(2).id()); EXPECT_EQ(0, spt.pieces(0).begin()); // 株式 EXPECT_EQ(0, spt.pieces(0).end()); EXPECT_EQ(0, spt.pieces(1).begin()); // 会社 EXPECT_EQ(3, spt.pieces(1).end()); EXPECT_EQ(3, spt.pieces(2).begin()); // </s> EXPECT_EQ(3, spt.pieces(2).end()); } } TEST(SentencepieceProcessorTest, NBestEncodeTest) { const std::string kInput = WS "ABC" WS "DEF"; SentencePieceProcessor sp; const auto normalization_spec = MakeDefaultNormalizerSpec(); auto mock = absl::make_unique<MockModel>(); const NBestEncodeResult result = { {{{WS "ABC", 3}, {WS "DE", 4}, {"F", 0}, {"</s>", 2}}, static_cast<float>(1.0)}, {{{WS "AB", 5}, {WS "CD", 6}, {"EF", 7}, {"</s>", 2}}, static_cast<float>(0.9)}}; mock->SetNBestEncodeResult(kInput, result); sp.SetModel(std::move(mock)); sp.SetNormalizer( absl::make_unique<normalizer::Normalizer>(normalization_spec)); std::vector<std::vector<std::string>> output; EXPECT_TRUE(sp.NBestEncode("ABC DEF", 2, &output).ok()); EXPECT_EQ(2, output.size()); EXPECT_EQ(GetSpVec(result[0].first), output[0]); EXPECT_EQ(GetSpVec(result[1].first), output[1]); std::vector<std::vector<int>> ids; EXPECT_TRUE(sp.NBestEncode("ABC DEF", 2, &ids).ok()); EXPECT_EQ(2, ids.size()); EXPECT_EQ(GetIdVec(result[0].first), ids[0]); EXPECT_EQ(GetIdVec(result[1].first), ids[1]); NBestSentencePieceText spt; EXPECT_TRUE(sp.NBestEncode("ABC DEF", 2, &spt).ok()); EXPECT_EQ(2, spt.nbests_size()); EXPECT_EQ(4, spt.nbests(0).pieces_size()); EXPECT_EQ(4, spt.nbests(1).pieces_size()); EXPECT_NEAR(result[0].second, spt.nbests(0).score(), 0.001); EXPECT_NEAR(result[1].second, spt.nbests(1).score(), 0.001); for (int i = 0; i < 4; ++i) { EXPECT_EQ(result[0].first[i].first, spt.nbests(0).pieces(i).piece()); EXPECT_EQ(result[1].first[i].first, spt.nbests(1).pieces(i).piece()); } NBestSentencePieceText spt2; EXPECT_TRUE( spt2.ParseFromString(sp.NBestEncodeAsSerializedProto("ABC DEF", 2))); EXPECT_EQ(spt.SerializeAsString(), spt2.SerializeAsString()); auto mock_empty = absl::make_unique<MockModel>(); mock_empty->SetNBestEncodeResult(kInput, {}); sp.SetModel(std::move(mock_empty)); EXPECT_FALSE(sp.NBestEncode("ABC DEF", 2, &output).ok()); } TEST(SentencepieceProcessorTest, SampleEncodeTest) { const std::string kInput = WS "ABC" WS "DEF"; SentencePieceProcessor sp; const auto normalization_spec = MakeDefaultNormalizerSpec(); auto mock = absl::make_unique<MockModel>(); const EncodeResult result = { {WS "ABC", 3}, {WS "DE", 4}, {"F", 0}, {"</s>", 2}}; const NBestEncodeResult nbest_result = { {{{WS "ABC", 3}, {WS "DE", 4}, {"F", 0}, {"</s>", 2}}, static_cast<float>(1.0)}, {{{WS "AB", 5}, {WS "CD", 6}, {"EF", 7}, {"</s>", 2}}, static_cast<float>(0.1)}}; mock->SetNBestEncodeResult(kInput, nbest_result); mock->SetEncodeResult(kInput, result); sp.SetModel(std::move(mock)); sp.SetNormalizer( absl::make_unique<normalizer::Normalizer>(normalization_spec)); std::vector<std::string> output; EXPECT_TRUE(sp.SampleEncode("ABC DEF", -1, 0.5, &output).ok()); EXPECT_EQ(4, output.size()); EXPECT_EQ(GetSpVec(result), output); std::vector<int> ids; EXPECT_TRUE(sp.SampleEncode("ABC DEF", -1, 0.5, &ids).ok()); EXPECT_EQ(4, ids.size()); EXPECT_EQ(GetIdVec(result), ids); SentencePieceText spt; EXPECT_TRUE(sp.SampleEncode("ABC DEF", -1, 0.5, &spt).ok()); EXPECT_EQ(4, spt.pieces_size()); for (int i = 0; i < 4; ++i) { EXPECT_EQ(result[i].first, spt.pieces(i).piece()); EXPECT_EQ(result[i].second, spt.pieces(i).id()); } SentencePieceText spt2; EXPECT_TRUE(spt2.ParseFromString( sp.SampleEncodeAsSerializedProto("ABC DEF", -1, 0.5))); EXPECT_EQ(spt.SerializeAsString(), spt2.SerializeAsString()); EXPECT_FALSE(sp.SampleEncode("ABC DEF", 1024, 0.5, &output).ok()); EXPECT_TRUE(sp.SampleEncode("ABC DEF", 0, 0.5, &output).ok()); EXPECT_TRUE(sp.SampleEncode("ABC DEF", 1, 0.5, &output).ok()); std::vector<int> freq(2, 0); for (int i = 0; i < 5000; ++i) { EXPECT_TRUE(sp.SampleEncode("ABC DEF", 20, 0.5, &output).ok()); EXPECT_EQ(4, output.size()); if (GetSpVec(nbest_result[0].first) == output) freq[0]++; else if (GetSpVec(nbest_result[1].first) == output) freq[1]++; else LOG(FATAL) << "Invalid result."; } const float expected_prob = std::exp(0.5 * 1.0) / (std::exp(0.5 * 1.0) + std::exp(0.5 * 0.1)); const float prob = 1.0 * freq[0] / (freq[0] + freq[1]); EXPECT_NEAR(prob, expected_prob, 0.05); auto mock_empty = absl::make_unique<MockModel>(); mock_empty->SetNBestEncodeResult(kInput, {}); sp.SetModel(std::move(mock_empty)); EXPECT_FALSE(sp.SampleEncode("ABC DEF", 10, 0.5, &output).ok()); } TEST(SentencepieceProcessorTest, DecodeTest) { class DecodeMockModel : public ModelInterface { public: EncodeResult Encode(absl::string_view normalized) const override { return {}; } int GetPieceSize() const override { return 7; } int PieceToId(absl::string_view piece) const override { static absl::flat_hash_map<absl::string_view, int, string_util::string_view_hash> kMap = {{"<unk>", 0}, {"<s>", 1}, {"</s>", 2}, {WS "ABC", 3}, {WS "DE", 4}, {"F", 5}, {"G" WS "H", 6}}; return port::FindWithDefault(kMap, piece, 0); } const std::string &IdToPiece(int id) const override { static std::vector<std::string> kMap = { "<unk>", "<s>", "</s>", WS "ABC", WS "DE", "F", "G" WS "H"}; return kMap[id]; } bool IsUnknown(int id) const override { return (id == 0); } bool IsControl(int id) const override { return (id == 1 || id == 2); } bool IsByte(int id) const override { return false; } float GetScore(int id) const override { return 0.0; } }; const std::vector<std::string> input = {"<s>", WS "ABC", "<unk>", WS "DE", "F", "G" WS "H", "I", "</s>"}; { SentencePieceProcessor sp; auto mock = absl::make_unique<DecodeMockModel>(); sp.SetModel(std::move(mock)); const auto normalization_spec = MakeDefaultNormalizerSpec(); sp.SetNormalizer( absl::make_unique<normalizer::Normalizer>(normalization_spec)); SentencePieceText spt; EXPECT_TRUE(sp.Decode(input, &spt).ok()); EXPECT_EQ("ABC \xE2\x81\x87 DEFG HI", spt.text()); EXPECT_EQ(8, spt.pieces_size()); for (int i = 0; i < 6; ++i) { EXPECT_EQ(input[i], spt.pieces(i).piece()); } EXPECT_EQ("", spt.pieces(0).surface()); EXPECT_EQ("ABC", spt.pieces(1).surface()); EXPECT_EQ(" \xE2\x81\x87 ", spt.pieces(2).surface()); EXPECT_EQ(" DE", spt.pieces(3).surface()); EXPECT_EQ("F", spt.pieces(4).surface()); EXPECT_EQ("G H", spt.pieces(5).surface()); EXPECT_EQ("I", spt.pieces(6).surface()); EXPECT_EQ("", spt.pieces(7).surface()); EXPECT_EQ(0, spt.pieces(0).begin()); EXPECT_EQ(0, spt.pieces(0).end()); EXPECT_EQ(0, spt.pieces(1).begin()); EXPECT_EQ(3, spt.pieces(1).end()); EXPECT_EQ(3, spt.pieces(2).begin()); EXPECT_EQ(8, spt.pieces(2).end()); EXPECT_EQ(8, spt.pieces(3).begin()); EXPECT_EQ(11, spt.pieces(3).end()); EXPECT_EQ(11, spt.pieces(4).begin()); EXPECT_EQ(12, spt.pieces(4).end()); EXPECT_EQ(12, spt.pieces(5).begin()); EXPECT_EQ(15, spt.pieces(5).end()); EXPECT_EQ(15, spt.pieces(6).begin()); EXPECT_EQ(16, spt.pieces(6).end()); EXPECT_EQ(16, spt.pieces(7).begin()); EXPECT_EQ(16, spt.pieces(7).end()); SentencePieceText spt2; EXPECT_TRUE(spt2.ParseFromString(sp.DecodePiecesAsSerializedProto(input))); EXPECT_EQ(spt.SerializeAsString(), spt2.SerializeAsString()); } // unk_surface is not defined. { SentencePieceProcessor sp; auto proto = absl::make_unique<ModelProto>(); sp.Load(std::move(proto)).IgnoreError(); auto mock = absl::make_unique<DecodeMockModel>(); sp.SetModel(std::move(mock)); const auto normalization_spec = MakeDefaultNormalizerSpec(); sp.SetNormalizer( absl::make_unique<normalizer::Normalizer>(normalization_spec)); SentencePieceText spt; EXPECT_TRUE(sp.Decode(input, &spt).ok()); EXPECT_EQ("ABC \xE2\x81\x87 DEFG HI", spt.text()); EXPECT_EQ(8, spt.pieces_size()); } { SentencePieceProcessor sp; auto proto = absl::make_unique<ModelProto>(); proto->mutable_trainer_spec()->set_unk_surface(""); sp.Load(std::move(proto)).IgnoreError(); auto mock = absl::make_unique<DecodeMockModel>(); sp.SetModel(std::move(mock)); const auto normalization_spec = MakeDefaultNormalizerSpec(); sp.SetNormalizer( absl::make_unique<normalizer::Normalizer>(normalization_spec)); SentencePieceText spt; EXPECT_TRUE(sp.Decode(input, &spt).ok()); EXPECT_EQ("ABC DEFG HI", spt.text()); EXPECT_EQ(8, spt.pieces_size()); } { SentencePieceProcessor sp; auto proto = absl::make_unique<ModelProto>(); proto->mutable_trainer_spec()->set_unk_surface("<UNK>"); sp.Load(std::move(proto)).IgnoreError(); auto mock = absl::make_unique<DecodeMockModel>(); sp.SetModel(std::move(mock)); const auto normalization_spec = MakeDefaultNormalizerSpec(); sp.SetNormalizer( absl::make_unique<normalizer::Normalizer>(normalization_spec)); SentencePieceText spt; EXPECT_TRUE(sp.Decode(input, &spt).ok()); EXPECT_EQ("ABC<UNK> DEFG HI", spt.text()); EXPECT_EQ(8, spt.pieces_size()); } { SentencePieceProcessor sp; auto proto = absl::make_unique<ModelProto>(); proto->mutable_trainer_spec()->set_unk_surface(""); proto->mutable_normalizer_spec()->set_add_dummy_prefix(false); proto->mutable_normalizer_spec()->set_remove_extra_whitespaces(false); sp.Load(std::move(proto)).IgnoreError(); auto mock = absl::make_unique<DecodeMockModel>(); sp.SetModel(std::move(mock)); const auto normalization_spec = MakeDefaultNormalizerSpec(); sp.SetNormalizer( absl::make_unique<normalizer::Normalizer>(normalization_spec)); SentencePieceText spt; EXPECT_TRUE(sp.Decode(input, &spt).ok()); EXPECT_EQ(" ABC DEFG HI", spt.text()); EXPECT_EQ(8, spt.pieces_size()); } } TEST(SentencepieceProcessorTest, ByteFallbackDecodeTest) { class ByteFallbackDecodeMockModel : public ModelInterface { public: EncodeResult Encode(absl::string_view normalized) const override { return {}; } int PieceToId(absl::string_view piece) const override { using Map = absl::flat_hash_map<std::string, int>; static const Map kMap = []() -> Map { Map m = { {"<unk>", 0}, {"<s>", 1}, {"</s>", 2}, {"A", 3}, {"B", 4}, {"C", 5}, }; for (int i = 0; i < 256; ++i) { m[ByteToPiece(i)] = 6 + i; } return m; }(); return port::FindWithDefault(kMap, std::string(piece), 0); } const std::string &IdToPiece(int id) const override { static std::vector<std::string> kMap = []() -> std::vector<std::string> { std::vector<std::string> m = {"<unk>", "<s>", "</s>", "A", "B", "C"}; for (int i = 0; i < 256; ++i) { m.push_back(ByteToPiece(i)); } return m; }(); return kMap[id]; } int GetPieceSize() const override { return 256; } bool IsUnknown(int id) const override { return (id == 0); } bool IsControl(int id) const override { return (id == 1 || id == 2); } bool IsByte(int id) const override { return id >= 6; } bool ByteFallbackEnabled() const override { return true; } }; SentencePieceProcessor sp; auto mock = absl::make_unique<ByteFallbackDecodeMockModel>(); sp.SetModel(std::move(mock)); const auto normalization_spec = MakeDefaultNormalizerSpec(); sp.SetNormalizer( absl::make_unique<normalizer::Normalizer>(normalization_spec)); { const std::vector<std::string> input = { "<s>", "A", "B", // "あ" -> 0xE3 0x81 0x82 "<0xE3>", "<0x81>", "<0x82>", // "Z" -> 0x5A "<0x5A>", // "Ω" -> 0xCE 0xA9 "<0xCE>", "<0xA9>", "C", // Invalid UTF-8 bytes. "<0xE0>", "<0x80>", // "い" -> 0xE3 0x81 0x84 "<0xE3>", "<0x81>", "<0x84>", // REPLACEMENT CHARACTER as byte pieces. "<0xEF>", "<0xBF>", "<0xBD>", }; SentencePieceText spt; EXPECT_TRUE(sp.Decode(input, &spt).ok()); EXPECT_EQ("ABあZΩC\xEF\xBF\xBD\xEF\xBF\xBDい\xEF\xBF\xBD", spt.text()); EXPECT_EQ(18, spt.pieces_size()); for (int i = 0; i < 18; ++i) { EXPECT_EQ(input[i], spt.pieces(i).piece()); } EXPECT_EQ("", spt.pieces(0).surface()); EXPECT_EQ(0, spt.pieces(0).begin()); EXPECT_EQ(0, spt.pieces(0).end()); EXPECT_EQ("A", spt.pieces(1).surface()); EXPECT_EQ(0, spt.pieces(1).begin()); EXPECT_EQ(1, spt.pieces(1).end()); EXPECT_EQ("B", spt.pieces(2).surface()); EXPECT_EQ(1, spt.pieces(2).begin()); EXPECT_EQ(2, spt.pieces(2).end()); EXPECT_EQ("", spt.pieces(3).surface()); EXPECT_EQ("", spt.pieces(4).surface()); EXPECT_EQ("あ", spt.pieces(5).surface()); EXPECT_EQ(2, spt.pieces(3).begin()); EXPECT_EQ(2, spt.pieces(3).end()); EXPECT_EQ(2, spt.pieces(4).begin()); EXPECT_EQ(2, spt.pieces(4).end()); EXPECT_EQ(2, spt.pieces(5).begin()); EXPECT_EQ(5, spt.pieces(5).end()); EXPECT_EQ("Z", spt.pieces(6).surface()); EXPECT_EQ(5, spt.pieces(6).begin()); EXPECT_EQ(6, spt.pieces(6).end()); EXPECT_EQ("", spt.pieces(7).surface()); EXPECT_EQ("Ω", spt.pieces(8).surface()); EXPECT_EQ(6, spt.pieces(7).begin()); EXPECT_EQ(6, spt.pieces(7).end()); EXPECT_EQ(6, spt.pieces(8).begin()); EXPECT_EQ(8, spt.pieces(8).end()); EXPECT_EQ("C", spt.pieces(9).surface()); EXPECT_EQ(8, spt.pieces(9).begin()); EXPECT_EQ(9, spt.pieces(9).end()); EXPECT_EQ("\xEF\xBF\xBD", spt.pieces(10).surface()); EXPECT_EQ(9, spt.pieces(10).begin()); EXPECT_EQ(12, spt.pieces(10).end()); EXPECT_EQ("\xEF\xBF\xBD", spt.pieces(11).surface()); EXPECT_EQ(12, spt.pieces(11).begin()); EXPECT_EQ(15, spt.pieces(11).end()); EXPECT_EQ("", spt.pieces(12).surface()); EXPECT_EQ("", spt.pieces(13).surface()); EXPECT_EQ("い", spt.pieces(14).surface()); EXPECT_EQ(15, spt.pieces(12).begin()); EXPECT_EQ(15, spt.pieces(12).end()); EXPECT_EQ(15, spt.pieces(13).begin()); EXPECT_EQ(15, spt.pieces(13).end()); EXPECT_EQ(15, spt.pieces(14).begin()); EXPECT_EQ(18, spt.pieces(14).end()); EXPECT_EQ("", spt.pieces(15).surface()); EXPECT_EQ("", spt.pieces(16).surface()); EXPECT_EQ("\xEF\xBF\xBD", spt.pieces(17).surface()); EXPECT_EQ(18, spt.pieces(15).begin()); EXPECT_EQ(18, spt.pieces(15).end()); EXPECT_EQ(18, spt.pieces(16).begin()); EXPECT_EQ(18, spt.pieces(16).end()); EXPECT_EQ(18, spt.pieces(17).begin()); EXPECT_EQ(21, spt.pieces(17).end()); } } void AddPiece(ModelProto *model_proto, absl::string_view piece, float score = 0.0) { auto *sp = model_proto->add_pieces(); sp->set_piece(std::string(piece)); sp->set_score(score); } TEST(SentencePieceProcessorTest, LoadInvalidModelTest) { SentencePieceProcessor sp; EXPECT_FALSE(sp.Load("").ok()); EXPECT_FALSE(sp.Load("__UNKNOWN_FILE__").ok()); } TEST(SentencePieceProcessorTest, LoadSerializedProtoTest) { ModelProto model_proto; auto *sp1 = model_proto.add_pieces(); sp1->set_type(ModelProto::SentencePiece::UNKNOWN); sp1->set_piece("<unk>"); AddPiece(&model_proto, WS, 0.0); *(model_proto.mutable_normalizer_spec()) = MakeDefaultNormalizerSpec(); SentencePieceProcessor sp; EXPECT_FALSE(sp.LoadFromSerializedProto("__NOT_A_PROTO__").ok()); EXPECT_TRUE(sp.LoadFromSerializedProto(model_proto.SerializeAsString()).ok()); EXPECT_EQ(model_proto.SerializeAsString(), sp.model_proto().SerializeAsString()); } TEST(SentencePieceProcessorTest, EndToEndTest) { ModelProto model_proto; auto *sp1 = model_proto.add_pieces(); auto *sp2 = model_proto.add_pieces(); auto *sp3 = model_proto.add_pieces(); sp1->set_type(ModelProto::SentencePiece::UNKNOWN); sp1->set_piece("<unk>"); sp2->set_type(ModelProto::SentencePiece::CONTROL); sp2->set_piece("<s>"); sp3->set_type(ModelProto::SentencePiece::CONTROL); sp3->set_piece("</s>"); AddPiece(&model_proto, "a", 0.0); AddPiece(&model_proto, "b", 0.3); AddPiece(&model_proto, "c", 0.2); AddPiece(&model_proto, "ab", 1.0); AddPiece(&model_proto, "\xE2\x96\x81", 3.0); // kSpaceSymbol *(model_proto.mutable_normalizer_spec()) = MakeDefaultNormalizerSpec(); { auto output = filesystem::NewWritableFile( util::JoinPath(absl::GetFlag(FLAGS_test_tmpdir), "model"), true); output->Write(model_proto.SerializeAsString()); } SentencePieceProcessor sp; EXPECT_TRUE( sp.Load(util::JoinPath(absl::GetFlag(FLAGS_test_tmpdir), "model")).ok()); EXPECT_EQ(model_proto.SerializeAsString(), sp.model_proto().SerializeAsString()); EXPECT_EQ(8, sp.GetPieceSize()); EXPECT_EQ(0, sp.PieceToId("<unk>")); EXPECT_EQ(1, sp.PieceToId("<s>")); EXPECT_EQ(2, sp.PieceToId("</s>")); EXPECT_EQ(3, sp.PieceToId("a")); EXPECT_EQ(4, sp.PieceToId("b")); EXPECT_EQ(5, sp.PieceToId("c")); EXPECT_EQ(6, sp.PieceToId("ab")); EXPECT_EQ(7, sp.PieceToId("\xE2\x96\x81")); EXPECT_EQ("<unk>", sp.IdToPiece(0)); EXPECT_EQ("<s>", sp.IdToPiece(1)); EXPECT_EQ("</s>", sp.IdToPiece(2)); EXPECT_EQ("a", sp.IdToPiece(3)); EXPECT_EQ("b", sp.IdToPiece(4)); EXPECT_EQ("c", sp.IdToPiece(5)); EXPECT_EQ("ab", sp.IdToPiece(6)); EXPECT_EQ("\xE2\x96\x81", sp.IdToPiece(7)); EXPECT_NEAR(0.0, sp.GetScore(0), 0.001); EXPECT_NEAR(0.0, sp.GetScore(1), 0.001); EXPECT_NEAR(0.0, sp.GetScore(2), 0.001); EXPECT_NEAR(0.0, sp.GetScore(3), 0.001); EXPECT_NEAR(0.3, sp.GetScore(4), 0.001); EXPECT_NEAR(0.2, sp.GetScore(5), 0.001); EXPECT_NEAR(1.0, sp.GetScore(6), 0.001); EXPECT_NEAR(3.0, sp.GetScore(7), 0.001); EXPECT_TRUE(sp.IsUnknown(0)); EXPECT_FALSE(sp.IsUnknown(1)); EXPECT_FALSE(sp.IsUnknown(2)); EXPECT_FALSE(sp.IsUnknown(3)); EXPECT_FALSE(sp.IsUnknown(4)); EXPECT_FALSE(sp.IsUnknown(5)); EXPECT_FALSE(sp.IsUnknown(6)); EXPECT_FALSE(sp.IsUnknown(7)); EXPECT_FALSE(sp.IsControl(0)); EXPECT_TRUE(sp.IsControl(1)); EXPECT_TRUE(sp.IsControl(2)); EXPECT_FALSE(sp.IsControl(3)); EXPECT_FALSE(sp.IsControl(4)); EXPECT_FALSE(sp.IsControl(5)); EXPECT_FALSE(sp.IsControl(6)); EXPECT_FALSE(sp.IsControl(7)); EXPECT_EQ(0, sp.unk_id()); EXPECT_EQ(1, sp.bos_id()); EXPECT_EQ(2, sp.eos_id()); EXPECT_EQ(-1, sp.pad_id()); { // Verify the default encoder version. EXPECT_EQ(EncoderVersion::kOptimized, sp.GetEncoderVersion()); // Set the encoder version to original and verify. EXPECT_TRUE(sp.SetEncoderVersion(EncoderVersion::kOriginal).ok()); EXPECT_EQ(EncoderVersion::kOriginal, sp.GetEncoderVersion()); // Set back to the default encoder version. EXPECT_TRUE(sp.SetEncoderVersion(EncoderVersion::kOptimized).ok()); } { std::vector<std::string> sps; const std::vector<std::string> expected_str = {WS, "ab", "c"}; EXPECT_TRUE(sp.Encode("abc", &sps).ok()); EXPECT_EQ(expected_str, sps); std::vector<int> ids; const std::vector<int> expected_id = {7, 6, 5}; EXPECT_TRUE(sp.Encode("abc", &ids).ok()); EXPECT_EQ(expected_id, ids); } { EXPECT_TRUE(sp.SetEncodeExtraOptions("bos").ok()); std::vector<std::string> sps; const std::vector<std::string> expected_str = {"<s>", WS, "ab", "c"}; EXPECT_TRUE(sp.Encode("abc", &sps).ok()); EXPECT_EQ(expected_str, sps); std::vector<int> ids; const std::vector<int> expected_id = {1, 7, 6, 5}; EXPECT_TRUE(sp.Encode("abc", &ids).ok()); EXPECT_EQ(expected_id, ids); } { EXPECT_TRUE(sp.SetEncodeExtraOptions("eos").ok()); std::vector<std::string> sps; const std::vector<std::string> expected_str = {WS, "ab", "c", "</s>"}; EXPECT_TRUE(sp.Encode("abc", &sps).ok()); EXPECT_EQ(expected_str, sps); std::vector<int> ids; const std::vector<int> expected_id = {7, 6, 5, 2}; EXPECT_TRUE(sp.Encode("abc", &ids).ok()); EXPECT_EQ(expected_id, ids); } { EXPECT_TRUE(sp.SetEncodeExtraOptions("reverse").ok()); std::vector<std::string> sps; const std::vector<std::string> expected_str = {"c", "ab", WS}; EXPECT_TRUE(sp.Encode("abc", &sps).ok()); EXPECT_EQ(expected_str, sps); std::vector<int> ids; const std::vector<int> expected_id = {5, 6, 7}; EXPECT_TRUE(sp.Encode("abc", &ids).ok()); EXPECT_EQ(expected_id, ids); } { EXPECT_TRUE(sp.SetEncodeExtraOptions("bos:eos").ok()); std::vector<std::string> sps; const std::vector<std::string> expected_str = {"<s>", WS, "ab", "c", "</s>"}; EXPECT_TRUE(sp.Encode("abc", &sps).ok()); EXPECT_EQ(expected_str, sps); std::vector<int> ids; const std::vector<int> expected_id = {1, 7, 6, 5, 2}; EXPECT_TRUE(sp.Encode("abc", &ids).ok()); EXPECT_EQ(expected_id, ids); } { EXPECT_TRUE(sp.SetEncodeExtraOptions("reverse:bos:eos").ok()); std::vector<std::string> sps; const std::vector<std::string> expected_str = {"<s>", "c", "ab", WS, "</s>"}; EXPECT_TRUE(sp.Encode("abc", &sps).ok()); EXPECT_EQ(expected_str, sps); std::vector<int> ids; const std::vector<int> expected_id = {1, 5, 6, 7, 2}; EXPECT_TRUE(sp.Encode("abc", &ids).ok()); EXPECT_EQ(expected_id, ids); } { EXPECT_TRUE(sp.SetEncodeExtraOptions("bos:eos:reverse").ok()); std::vector<std::string> sps; const std::vector<std::string> expected_str = {"</s>", "c", "ab", WS, "<s>"}; EXPECT_TRUE(sp.Encode("abc", &sps).ok()); EXPECT_EQ(expected_str, sps); std::vector<int> ids; const std::vector<int> expected_id = {2, 5, 6, 7, 1}; EXPECT_TRUE(sp.Encode("abc", &ids).ok()); EXPECT_EQ(expected_id, ids); } { std::string output; const std::vector<std::string> sps = {"ab", "c"}; EXPECT_TRUE(sp.Decode(sps, &output).ok()); EXPECT_EQ("abc", output); const std::vector<int> ids = {3, 4, 5}; EXPECT_TRUE(sp.Decode(ids, &output).ok()); EXPECT_EQ("abc", output); } { EXPECT_TRUE(sp.SetDecodeExtraOptions("bos").ok()); std::string output; const std::vector<std::string> sps = {"ab", "c"}; EXPECT_TRUE(sp.Decode(sps, &output).ok()); EXPECT_EQ("abc", output); const std::vector<int> ids = {3, 4, 5}; EXPECT_TRUE(sp.Decode(ids, &output).ok()); EXPECT_EQ("abc", output); } { EXPECT_TRUE(sp.SetDecodeExtraOptions("eos").ok()); std::string output; const std::vector<std::string> sps = {"ab", "c"}; EXPECT_TRUE(sp.Decode(sps, &output).ok()); EXPECT_EQ("abc", output); const std::vector<int> ids = {3, 4, 5}; EXPECT_TRUE(sp.Decode(ids, &output).ok()); EXPECT_EQ("abc", output); } { EXPECT_TRUE(sp.SetDecodeExtraOptions("reverse").ok()); std::string output; const std::vector<std::string> sps = {"ab", "c"}; EXPECT_TRUE(sp.Decode(sps, &output).ok()); EXPECT_EQ("cab", output); const std::vector<int> ids = {3, 4, 5}; EXPECT_TRUE(sp.Decode(ids, &output).ok()); EXPECT_EQ("cba", output); } // Out of range { std::string output; const std::vector<int> ids = {3, 4, 127}; EXPECT_FALSE(sp.Decode(ids, &output).ok()); } { EXPECT_TRUE(sp.SetDecodeExtraOptions("bos:eos").ok()); std::string output; const std::vector<std::string> sps = {"ab", "c"}; EXPECT_TRUE(sp.Decode(sps, &output).ok()); EXPECT_EQ("abc", output); const std::vector<int> ids = {3, 4, 5}; EXPECT_TRUE(sp.Decode(ids, &output).ok()); EXPECT_EQ("abc", output); } { EXPECT_TRUE(sp.SetDecodeExtraOptions("reverse:bos:eos").ok()); std::string output; const std::vector<std::string> sps = {"ab", "c"}; EXPECT_TRUE(sp.Decode(sps, &output).ok()); EXPECT_EQ("cab", output); const std::vector<int> ids = {3, 4, 5}; EXPECT_TRUE(sp.Decode(ids, &output).ok()); EXPECT_EQ("cba", output); } { EXPECT_TRUE(sp.SetDecodeExtraOptions("bos:eos:reverse").ok()); std::string output; const std::vector<std::string> sps = {"ab", "c"}; EXPECT_TRUE(sp.Decode(sps, &output).ok()); EXPECT_EQ("cab", output); const std::vector<int> ids = {3, 4, 5}; EXPECT_TRUE(sp.Decode(ids, &output).ok()); EXPECT_EQ("cba", output); } { EXPECT_TRUE(sp.SetDecodeExtraOptions("reverse:reverse").ok()); std::string output; const std::vector<std::string> sps = {"ab", "c"}; EXPECT_TRUE(sp.Decode(sps, &output).ok()); EXPECT_EQ("abc", output); const std::vector<int> ids = {3, 4, 5}; EXPECT_TRUE(sp.Decode(ids, &output).ok()); EXPECT_EQ("abc", output); } EXPECT_TRUE(sp.SetEncodeExtraOptions("").ok()); EXPECT_TRUE(sp.SetDecodeExtraOptions("").ok()); EXPECT_FALSE(sp.SetEncodeExtraOptions("foo").ok()); EXPECT_FALSE(sp.SetDecodeExtraOptions("foo").ok()); auto RunTest = [&model_proto](const SentencePieceProcessor &sp) { EXPECT_EQ(model_proto.SerializeAsString(), sp.model_proto().SerializeAsString()); EXPECT_EQ(8, sp.GetPieceSize()); EXPECT_EQ(0, sp.PieceToId("<unk>")); EXPECT_EQ(1, sp.PieceToId("<s>")); EXPECT_EQ(2, sp.PieceToId("</s>")); EXPECT_EQ(3, sp.PieceToId("a")); EXPECT_EQ(4, sp.PieceToId("b")); EXPECT_EQ(5, sp.PieceToId("c")); EXPECT_EQ(6, sp.PieceToId("ab")); EXPECT_EQ(7, sp.PieceToId("\xE2\x96\x81")); EXPECT_EQ("<unk>", sp.IdToPiece(0)); EXPECT_EQ("<s>", sp.IdToPiece(1)); EXPECT_EQ("</s>", sp.IdToPiece(2)); EXPECT_EQ("a", sp.IdToPiece(3)); EXPECT_EQ("b", sp.IdToPiece(4)); EXPECT_EQ("c", sp.IdToPiece(5)); EXPECT_EQ("ab", sp.IdToPiece(6)); EXPECT_EQ("\xE2\x96\x81", sp.IdToPiece(7)); EXPECT_TRUE(sp.IsUnknown(0)); EXPECT_FALSE(sp.IsUnknown(1)); EXPECT_FALSE(sp.IsUnknown(2)); EXPECT_FALSE(sp.IsUnknown(3)); EXPECT_FALSE(sp.IsUnknown(4)); EXPECT_FALSE(sp.IsUnknown(5)); EXPECT_FALSE(sp.IsUnknown(6)); EXPECT_FALSE(sp.IsUnknown(7)); EXPECT_FALSE(sp.IsControl(0)); EXPECT_TRUE(sp.IsControl(1)); EXPECT_TRUE(sp.IsControl(2)); EXPECT_FALSE(sp.IsControl(3)); EXPECT_FALSE(sp.IsControl(4)); EXPECT_FALSE(sp.IsControl(5)); EXPECT_FALSE(sp.IsControl(6)); EXPECT_FALSE(sp.IsControl(7)); { std::vector<std::string> sps; const std::vector<std::string> expected_str = {WS, "ab", "c"}; EXPECT_TRUE(sp.Encode("abc", &sps).ok()); EXPECT_EQ(expected_str, sps); std::vector<int> ids; const std::vector<int> expected_id = {7, 6, 5}; EXPECT_TRUE(sp.Encode("abc", &ids).ok()); EXPECT_EQ(expected_id, ids); } { std::string output; const std::vector<std::string> sps = {"ab", "c"}; EXPECT_TRUE(sp.Decode(sps, &output).ok()); EXPECT_EQ("abc", output); const std::vector<int> ids = {3, 4, 5}; EXPECT_TRUE(sp.Decode(ids, &output).ok()); EXPECT_EQ("abc", output); } }; // Copies ModelProto. { SentencePieceProcessor sp; const ModelProto copied = model_proto; EXPECT_TRUE(sp.Load(copied).ok()); RunTest(sp); } // Moves ModelProto. { SentencePieceProcessor sp; auto moved = absl::make_unique<ModelProto>(); const ModelProto *moved_ptr = moved.get(); *moved = model_proto; EXPECT_TRUE(sp.Load(std::move(moved)).ok()); EXPECT_EQ(moved_ptr, &sp.model_proto()); RunTest(sp); } // Restrict Vocabulary. { SentencePieceProcessor sp; EXPECT_TRUE(sp.Load(model_proto).ok()); EXPECT_TRUE(sp.SetVocabulary({"a", "b", "c"}).ok()); // remove "ab" const std::vector<std::string> expected_str = {WS, "a", "b", "c"}; std::vector<std::string> sps; EXPECT_TRUE(sp.Encode("abc", &sps).ok()); EXPECT_EQ(expected_str, sps); std::vector<int> ids; const std::vector<int> expected_id = {7, 3, 4, 5}; EXPECT_TRUE(sp.Encode("abc", &ids).ok()); EXPECT_EQ(expected_id, ids); } } TEST(SentencePieceProcessorTest, SkipNormalizationTest) { ModelProto model_proto; auto *sp1 = model_proto.add_pieces(); auto *sp2 = model_proto.add_pieces(); sp1->set_type(ModelProto::SentencePiece::UNKNOWN); sp1->set_piece("<unk>"); sp2->set_type(ModelProto::SentencePiece::USER_DEFINED); sp2->set_piece("<USER>"); AddPiece(&model_proto, "a", 0.0); AddPiece(&model_proto, "b", 0.3); AddPiece(&model_proto, "c", 0.2); AddPiece(&model_proto, "u", 0.2); AddPiece(&model_proto, "s", 0.2); AddPiece(&model_proto, "e", 0.2); AddPiece(&model_proto, "r", 0.2); *(model_proto.mutable_normalizer_spec()) = SentencePieceTrainer::GetNormalizerSpec("nmt_nfkc_cf"); SentencePieceProcessor sp; EXPECT_TRUE(sp.Load(model_proto).ok()); std::vector<std::string> pieces; EXPECT_TRUE(sp.Encode("AB<USER>C<uSEr>", &pieces).ok()); for (const auto &sp : pieces) LOG(INFO) << sp; EXPECT_EQ(std::vector<std::string>( {WS, "a", "b", "<USER>", "c", "<", "u", "s", "e", "r", ">"}), pieces); } TEST(SentencePieceProcessorTest, ExtraOptionsUndefinedTest) { ModelProto model_proto; auto *sp1 = model_proto.add_pieces(); // No BOS/EOS. sp1->set_type(ModelProto::SentencePiece::UNKNOWN); sp1->set_piece("<unk>"); AddPiece(&model_proto, "a", 0.0); AddPiece(&model_proto, "b", 0.3); AddPiece(&model_proto, "c", 0.2); AddPiece(&model_proto, "ab", 1.0); SentencePieceProcessor sp; EXPECT_TRUE(sp.Load(model_proto).ok()); EXPECT_FALSE(sp.SetEncodeExtraOptions("bos").ok()); EXPECT_FALSE(sp.SetDecodeExtraOptions("eos").ok()); } TEST(SentencePieceProcessorTest, OverrideSpecialPieceTest) { ModelProto model_proto; auto *sp1 = model_proto.add_pieces(); auto *sp2 = model_proto.add_pieces(); auto *sp3 = model_proto.add_pieces(); model_proto.mutable_trainer_spec()->set_unk_piece("__UNK__"); model_proto.mutable_trainer_spec()->set_bos_piece("__BOS__"); model_proto.mutable_trainer_spec()->set_eos_piece("__EOS__"); model_proto.mutable_trainer_spec()->set_pad_piece("__PAD__"); // No BOS/EOS. sp1->set_type(ModelProto::SentencePiece::UNKNOWN); sp1->set_piece("__UNK__"); sp2->set_type(ModelProto::SentencePiece::CONTROL); sp2->set_piece("__BOS__"); sp3->set_type(ModelProto::SentencePiece::CONTROL); sp3->set_piece("__EOS__"); AddPiece(&model_proto, "a", 0.0); AddPiece(&model_proto, "b", 0.3); SentencePieceProcessor sp; EXPECT_TRUE(sp.Load(model_proto).ok()); EXPECT_EQ(0, sp.unk_id()); EXPECT_EQ(1, sp.bos_id()); EXPECT_EQ(2, sp.eos_id()); EXPECT_EQ(-1, sp.pad_id()); EXPECT_EQ("__UNK__", sp.IdToPiece(sp.unk_id())); EXPECT_EQ("__BOS__", sp.IdToPiece(sp.bos_id())); EXPECT_EQ("__EOS__", sp.IdToPiece(sp.eos_id())); } TEST(SentencePieceProcessorTest, VocabularyTest) { ModelProto model_proto; auto *sp1 = model_proto.add_pieces(); auto *sp2 = model_proto.add_pieces(); auto *sp3 = model_proto.add_pieces(); auto GetInlineFilename = [](const std::string content) { { auto out = filesystem::NewWritableFile( util::JoinPath(absl::GetFlag(FLAGS_test_tmpdir), "vocab.txt")); out->Write(content); } return util::JoinPath(absl::GetFlag(FLAGS_test_tmpdir), "vocab.txt"); }; sp1->set_type(ModelProto::SentencePiece::UNKNOWN); sp1->set_piece("<unk>"); sp2->set_type(ModelProto::SentencePiece::CONTROL); sp2->set_piece("<s>"); sp3->set_type(ModelProto::SentencePiece::CONTROL); sp3->set_piece("</s>"); AddPiece(&model_proto, "aa", 0.0); AddPiece(&model_proto, "bb", 0.0); AddPiece(&model_proto, "cc", 0.0); AddPiece(&model_proto, "dd", 0.0); AddPiece(&model_proto, "e", 0.0); SentencePieceProcessor sp; EXPECT_TRUE(sp.Load(model_proto).ok()); EXPECT_FALSE(sp.IsUnused(0)); EXPECT_FALSE(sp.IsUnused(1)); EXPECT_FALSE(sp.IsUnused(2)); EXPECT_FALSE(sp.IsUnused(3)); EXPECT_FALSE(sp.IsUnused(4)); EXPECT_FALSE(sp.IsUnused(5)); EXPECT_FALSE(sp.IsUnused(6)); EXPECT_FALSE(sp.IsUnused(7)); EXPECT_TRUE(sp.SetVocabulary({"aa", "dd", "e"}).ok()); EXPECT_FALSE(sp.IsUnused(0)); EXPECT_FALSE(sp.IsUnused(1)); EXPECT_FALSE(sp.IsUnused(2)); EXPECT_FALSE(sp.IsUnused(3)); EXPECT_TRUE(sp.IsUnused(4)); EXPECT_TRUE(sp.IsUnused(5)); EXPECT_FALSE(sp.IsUnused(6)); EXPECT_FALSE(sp.IsUnused(7)); // single char "e" is always used. EXPECT_TRUE(sp.ResetVocabulary().ok()); EXPECT_FALSE(sp.IsUnused(3)); EXPECT_FALSE(sp.IsUnused(4)); EXPECT_FALSE(sp.IsUnused(5)); EXPECT_FALSE(sp.IsUnused(6)); EXPECT_FALSE(sp.IsUnused(7)); EXPECT_TRUE(sp.SetVocabulary({"bb"}).ok()); EXPECT_TRUE(sp.IsUnused(3)); EXPECT_FALSE(sp.IsUnused(4)); EXPECT_TRUE(sp.IsUnused(5)); EXPECT_TRUE(sp.IsUnused(6)); EXPECT_FALSE(sp.IsUnused(7)); EXPECT_TRUE(sp.LoadVocabulary(GetInlineFilename("aa\t1\ndd\t2\n"), 2).ok()); EXPECT_TRUE(sp.IsUnused(3)); EXPECT_TRUE(sp.IsUnused(4)); EXPECT_TRUE(sp.IsUnused(5)); EXPECT_FALSE(sp.IsUnused(6)); EXPECT_FALSE(sp.IsUnused(7)); EXPECT_TRUE(sp.LoadVocabulary(GetInlineFilename("aa\t1\ndd\t1\n"), 2).ok()); EXPECT_TRUE(sp.IsUnused(3)); EXPECT_TRUE(sp.IsUnused(4)); EXPECT_TRUE(sp.IsUnused(5)); EXPECT_TRUE(sp.IsUnused(6)); EXPECT_FALSE(sp.IsUnused(7)); EXPECT_TRUE(sp.LoadVocabulary(GetInlineFilename("aa\t1\ndd\t1\n"), 1).ok()); EXPECT_FALSE(sp.IsUnused(3)); EXPECT_TRUE(sp.IsUnused(4)); EXPECT_TRUE(sp.IsUnused(5)); EXPECT_FALSE(sp.IsUnused(6)); EXPECT_FALSE(sp.IsUnused(7)); EXPECT_TRUE(sp.LoadVocabulary(GetInlineFilename("aa\t0\ndd\t0\n"), 0).ok()); EXPECT_FALSE(sp.IsUnused(3)); EXPECT_TRUE(sp.IsUnused(4)); EXPECT_TRUE(sp.IsUnused(5)); EXPECT_FALSE(sp.IsUnused(6)); EXPECT_FALSE(sp.IsUnused(7)); // No frequency. EXPECT_TRUE(sp.LoadVocabulary(GetInlineFilename("aa\ndd\n"), 1).ok()); EXPECT_FALSE(sp.IsUnused(3)); EXPECT_TRUE(sp.IsUnused(4)); EXPECT_TRUE(sp.IsUnused(5)); EXPECT_FALSE(sp.IsUnused(6)); EXPECT_FALSE(sp.IsUnused(7)); } } // namespace sentencepiece
31.697597
80
0.629362
[ "vector", "model" ]
e10f7614e7f72f689220a62b5dad48de00f99800
28,506
cc
C++
samples/foot_ik/sample_foot_ik.cc
LandonJerre/ozz-animation
abc11520ff6c63373e4084ff28ad2f088755e263
[ "MIT" ]
1
2019-10-26T19:17:42.000Z
2019-10-26T19:17:42.000Z
samples/foot_ik/sample_foot_ik.cc
LandonJerre/ozz-animation
abc11520ff6c63373e4084ff28ad2f088755e263
[ "MIT" ]
null
null
null
samples/foot_ik/sample_foot_ik.cc
LandonJerre/ozz-animation
abc11520ff6c63373e4084ff28ad2f088755e263
[ "MIT" ]
1
2019-10-26T19:17:45.000Z
2019-10-26T19:17:45.000Z
//----------------------------------------------------------------------------// // // // ozz-animation is hosted at http://github.com/guillaumeblanc/ozz-animation // // and distributed under the MIT License (MIT). // // // // Copyright (c) 2019 Guillaume Blanc // // // // 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 "ozz/animation/runtime/animation.h" #include "ozz/animation/runtime/ik_aim_job.h" #include "ozz/animation/runtime/ik_two_bone_job.h" #include "ozz/animation/runtime/local_to_model_job.h" #include "ozz/animation/runtime/sampling_job.h" #include "ozz/animation/runtime/skeleton.h" #include "ozz/base/log.h" #include "ozz/base/maths/box.h" #include "ozz/base/maths/math_ex.h" #include "ozz/base/maths/simd_math.h" #include "ozz/base/maths/simd_quaternion.h" #include "ozz/base/maths/soa_transform.h" #include "ozz/base/maths/vec_float.h" #include "ozz/options/options.h" #include "framework/application.h" #include "framework/imgui.h" #include "framework/mesh.h" #include "framework/utils.h" #include "framework/renderer.h" #include "framework/utils.h" #include <limits> // Skeleton archive can be specified as an option. OZZ_OPTIONS_DECLARE_STRING(skeleton, "Path to the skeleton (ozz archive format).", "media/skeleton.ozz", false) // Animation archive can be specified as an option. OZZ_OPTIONS_DECLARE_STRING(animation, "Path to the animation (ozz archive format).", "media/animation.ozz", false) // Mesh archive can be specified as an option. OZZ_OPTIONS_DECLARE_STRING(mesh, "Path to the skinned mesh (ozz archive format).", "media/mesh.ozz", false) // Mesh archive can be specified as an option. OZZ_OPTIONS_DECLARE_STRING(floor, "Path to the floor mesh (ozz archive format).", "media/floor.ozz", false) const char* kLeftJointNames[] = {"LeftUpLeg", "LeftLeg", "LeftFoot"}; const char* kRightJointNames[] = {"RightUpLeg", "RightLeg", "RightFoot"}; const ozz::math::SimdFloat4 kKneeAxis = ozz::math::simd_float4::z_axis(); const ozz::math::SimdFloat4 kAnkleForward = -ozz::math::simd_float4::x_axis(); const ozz::math::SimdFloat4 kAnkleUp = ozz::math::simd_float4::y_axis(); // Structure used to store each leg setup data. struct LegSetup { int hip; int knee; int ankle; }; struct LegRayInfo { ozz::math::Float3 start; ozz::math::Float3 dir; bool hit; ozz::math::Float3 hit_point; ozz::math::Float3 hit_normal; }; // Constants static const ozz::math::Float3 kDown(0.f, -1.f, 0.f); static const ozz::math::Float3 kCharacterRayHeightOffset(0.f, 10.f, 0.f); static const ozz::math::Float3 kFootRayHeightOffset(0.f, .5f, 0.f); class FootIKSampleApplication : public ozz::sample::Application { public: FootIKSampleApplication() : pelvis_offset_(0.f, 0.f, 0.f), root_translation_(2.17f, 2.f, -2.06f), root_yaw_(2.f), foot_heigh_(.12f), weight_(1.f), soften_(1.f), auto_character_height_(true), pelvis_correction_(true), two_bone_ik_(true), aim_ik_(true), show_skin_(true), show_joints_(false), show_raycast_(false), show_ankle_target_(false), show_root_(false), show_offsetted_root_(false) {} protected: // Updates current animation time and foot ik. virtual bool OnUpdate(float _dt, float) { // 1. Updates character main animation. if (!UpdateBaseAnimation(_dt)) { return false; } // 2. Finds character height on the floor, evaluted at its root position. if (!UpdateCharacterHeight()) { return false; } // 3. For each leg, raycasts a vector going down from the ankle position. // This allows to find the intersection point with the floor. if (!RaycastLegs()) { return false; } // 4. Computes targetted ankles positions, taking floor steepness and foot // height in consideration. if (!UpdateAnklesTarget()) { return false; } // 5. Offsets the character down, so that the lowest ankle (lowest from its // original position) reaches its targetted position. The other leg(s) will // be ik-ed. if (!UpdatePelvisOffset()) { return false; } // 6. Updates legs and ankles transforms, so they reach thei targetted // position and orientation. if (!UpdateFootIK()) { return false; } return true; } // Raycast down from the current position to find character height on the // floor. It directly updates root translation as output. bool UpdateCharacterHeight() { if (!auto_character_height_) { return true; } // Starts the ray from above (kCharacterRayHeightOffset) current character // position. ozz::sample::RayIntersectsMeshes( root_translation_ + kCharacterRayHeightOffset, kDown, make_range(floors_), &root_translation_, NULL); return true; } bool UpdateBaseAnimation(float _dt) { // Updates current animation time. controller_.Update(animation_, _dt); // Samples optimized animation at t = animation_time. ozz::animation::SamplingJob sampling_job; sampling_job.animation = &animation_; sampling_job.cache = &cache_; sampling_job.ratio = controller_.time_ratio(); sampling_job.output = make_range(locals_); if (!sampling_job.Run()) { return false; } // Converts from local space to model space matrices. ozz::animation::LocalToModelJob ltm_job; ltm_job.skeleton = &skeleton_; ltm_job.input = make_range(locals_); ltm_job.output = make_range(models_); if (!ltm_job.Run()) { return false; } return true; } bool RaycastLegs() { // Pelvis offset isn't updated yet, it shouldn't be considered. So we're // using "unoffsetted" root transform. const ozz::math::Float4x4 root = GetRootTransform(); // Raycast down for each leg to find the intersection point with the floor. for (size_t l = 0; l < kLegsCount; ++l) { const LegSetup& leg = legs_setup_[l]; LegRayInfo& ray = rays_info_[l]; // Finds ankle initial world space position ozz::math::Store3PtrU(TransformPoint(root, models_[leg.ankle].cols[3]), &ankles_initial_ws_[l].x); // Builds ray, from above ankle (kFootRayHeightOffset) and going downward. ray.start = ankles_initial_ws_[l] + kFootRayHeightOffset; ray.dir = kDown; ray.hit = ozz::sample::RayIntersectsMeshes( ray.start, ray.dir, make_range(floors_), &ray.hit_point, &ray.hit_normal); } return true; } // Comptutes ankle target position (C), so that the foot is in contact with // the floor. Because of floor slope (defined by raycast intersection normal), // ankle position cannot be simply be offseted by foot offset. See geogebra // diagram for more details: media/doc/samples/foot_ik_ankle.ggb bool UpdateAnklesTarget() { for (size_t l = 0; l < kLegsCount; ++l) { const LegRayInfo& ray = rays_info_[l]; if (!ray.hit) { continue; } // Computes projection of the ray AI (from start to floor intersection // point) onto floor normal. This gives the length of segment AB. // Note that ray.hit_normal is normalized already. const float ABl = Dot(ray.start - ray.hit_point, ray.hit_normal); if (ABl == 0.f) { // Early out if the two are perpandicular. continue; } // Knowing A, AB length and direction, we can compute B position. const ozz::math::Float3 B = ray.start - ray.hit_normal * ABl; // Computes sebgment IB and its length (IBl) const ozz::math::Float3 IB = B - ray.hit_point; const float IBl = Length(IB); if (IBl <= 0.f) { // If B is at raycast intersection (I), then we still need to update // corrected ankle position (world-space) to take into account foot // height. ankles_target_ws_[l] = ray.hit_point + ray.hit_normal * foot_heigh_; } else { // HC length is known (as foot height). So we're using Thales theorem to // find H position. const float IHl = IBl * foot_heigh_ / ABl; const ozz::math::Float3 IH = IB * (IHl / IBl); const ozz::math::Float3 H = ray.hit_point + IH; // C (Corrected ankle) position can now be found. const ozz::math::Float3 C = H + ray.hit_normal * foot_heigh_; // Override ankle position with result. ankles_target_ws_[l] = C; } } return true; } // Recomputes pelvis offset. // Strategy is to move the pelvis along "down" axis (ray axis), enough for // the lowest foot (lowest from its original position) to reaches ankle // target. The other foot will be ik-ed. bool UpdatePelvisOffset() { pelvis_offset_ = ozz::math::Float3(0.f, 0.f, 0.f); float max_dot = -std::numeric_limits<float>::max(); if (pelvis_correction_) { for (size_t l = 0; l < kLegsCount; ++l) { const LegRayInfo& ray = rays_info_[l]; if (!ray.hit) { continue; } // Check if this ankle is lower (in down direction) compared to the // previous one. const ozz::math::Float3 ankle_to_target = ankles_target_ws_[l] - ankles_initial_ws_[l]; const float dot = Dot(ankle_to_target, kDown); if (dot > max_dot) { max_dot = dot; // Compute offset using the maximum displacement that the legs should // have to touch ground. pelvis_offset_ = kDown * dot; } } } return true; } // Applies two bone IK to the leg, and aim IK to the ankle bool UpdateFootIK() { // Pelvis offset needs to be considered when converting to medel space. So // we're using "offsetted" root transform. const ozz::math::Float4x4 root = GetOffsettedRootTransform(); const ozz::math::Float4x4 inv_root = Invert(root); ozz::animation::LocalToModelJob ltm_job; ltm_job.skeleton = &skeleton_; ltm_job.input = make_range(locals_); ltm_job.output = make_range(models_); // Perform IK for (size_t l = 0; l < kLegsCount; ++l) { const LegRayInfo& ray = rays_info_[l]; if (!ray.hit) { continue; } const LegSetup& leg = legs_setup_[l]; // Updates leg joint chain so ankle reaches its targetted position. if (two_bone_ik_ && !ApplyLegTwoBoneIK(leg, ankles_target_ws_[l], inv_root)) { return false; } // Updates leg joints model-space transforms. // Update will go from hip to ankle. Ankle's siblings might no be updated // as local-to-model will stop as soon as ankle joint is reached. ltm_job.from = leg.hip; ltm_job.to = leg.ankle; if (!ltm_job.Run()) { return false; } // Computes ankle orientation so it's aligned to the floor normal. const ozz::math::Float3 aim_ik_target(ankles_target_ws_[l] + ray.hit_normal); if (aim_ik_ && !ApplyAnkleAimIK(leg, aim_ik_target, inv_root)) { return false; } // Updates model-space transformation now ankle local changes is done. // Ankle rotation has already been updated, but its siblings (or it's // parent siblings) might are not. So we local-to-model update must // be complete starting from hip. ltm_job.from = leg.hip; ltm_job.to = ozz::animation::Skeleton::kMaxJoints; if (!ltm_job.Run()) { return false; } } return true; } // This function will compute two bone IK on the leg, updating hip and knee // rotations so that ankle can reach its targetted position. bool ApplyLegTwoBoneIK(const LegSetup& _leg, const ozz::math::Float3& _target_ws, const ozz::math::Float4x4& _inv_root) { // Target position and pole vectors must be in model space. const ozz::math::SimdFloat4 target_ms = TransformPoint( _inv_root, ozz::math::simd_float4::Load3PtrU(&_target_ws.x)); const ozz::math::SimdFloat4 pole_vector_ms = models_[_leg.knee].cols[1]; // Builds two bone IK job. ozz::animation::IKTwoBoneJob ik_job; ik_job.target = target_ms; ik_job.pole_vector = pole_vector_ms; // Mid axis (knee) is constant (usualy), and arbitratry defined by // skeleton/rig setup. ik_job.mid_axis = kKneeAxis; ik_job.weight = weight_; ik_job.soften = soften_; ik_job.start_joint = &models_[_leg.hip]; ik_job.mid_joint = &models_[_leg.knee]; ik_job.end_joint = &models_[_leg.ankle]; ozz::math::SimdQuaternion start_correction; ik_job.start_joint_correction = &start_correction; ozz::math::SimdQuaternion mid_correction; ik_job.mid_joint_correction = &mid_correction; if (!ik_job.Run()) { return false; } // Apply IK quaternions to their respective local-space transforms. // Model-space transformations needs to be updated after a call to this // function. ozz::sample::MultiplySoATransformQuaternion(_leg.hip, start_correction, make_range(locals_)); ozz::sample::MultiplySoATransformQuaternion(_leg.knee, mid_correction, make_range(locals_)); return true; } // This function will compute aim IK on the ankle, updating its rotations so // it can be aligned with the floor. // The strategy is to align ankle up vector in the direction of the floor // normal. The forward direction of the foot is then driven by the pole // vector, which polls the foot (ankle forward vector) toward it's original // (animated) direction. bool ApplyAnkleAimIK(const LegSetup& _leg, const ozz::math::Float3& _target_ws, const ozz::math::Float4x4& _inv_root) { // Target position and pole vectors must be in model space. const ozz::math::SimdFloat4 target_ms = TransformPoint( _inv_root, ozz::math::simd_float4::Load3PtrU(&_target_ws.x)); ozz::animation::IKAimJob ik_job; // Forward and up vectors are constant (usualy), and arbitratry defined by // skeleton/rig setup. ik_job.forward = kAnkleForward; ik_job.up = kAnkleUp; // Model space targetted direction (floor normal in this case). ik_job.target = target_ms; // Uses constant ankle Y (skeleton/rig setup dependent) as pole vector. That // allows to maintain foot direction. ik_job.pole_vector = models_[_leg.ankle].cols[1]; ik_job.joint = &models_[_leg.ankle]; ik_job.weight = weight_; ozz::math::SimdQuaternion correction; ik_job.joint_correction = &correction; if (!ik_job.Run()) { return false; } // Apply IK quaternions to their respective local-space transforms. // Model-space transformations needs to be updated after a call to this // function. ozz::sample::MultiplySoATransformQuaternion(_leg.ankle, correction, make_range(locals_)); return true; } virtual bool OnDisplay(ozz::sample::Renderer* _renderer) { const float kAxeScale = .1f; const ozz::math::Float4x4 kAxesScale = ozz::math::Float4x4::Scaling(ozz::math::simd_float4::Load1(kAxeScale)); const ozz::math::Float4x4 identity = ozz::math::Float4x4::identity(); const ozz::math::Float4x4 offsetted_root = GetOffsettedRootTransform(); bool success = true; // Renders floor meshes. for (size_t i = 0; i < floors_.size(); ++i) { success &= _renderer->DrawMesh(floors_[i], identity); } // Renders character. if (show_skin_) { // Builds skinning matrices. // The mesh might not use (aka be skinned by) all skeleton joints. We // use the joint remapping table (available from the mesh object) to // reorder model-space matrices and build skinning ones. for (size_t m = 0; m < meshes_.size(); ++m) { const ozz::sample::Mesh& mesh = meshes_[m]; for (size_t i = 0; i < mesh.joint_remaps.size(); ++i) { skinning_matrices_[i] = models_[mesh.joint_remaps[i]] * mesh.inverse_bind_poses[i]; } success &= _renderer->DrawSkinnedMesh( mesh, make_range(skinning_matrices_), offsetted_root); } } else { // Renders skeleton only. success &= _renderer->DrawPosture(skeleton_, make_range(models_), offsetted_root); } // Showing joints if (show_joints_) { for (size_t l = 0; l < kLegsCount; ++l) { const LegSetup& leg = legs_setup_[l]; for (size_t i = 0; i < 3; ++i) { const int joints[3] = {leg.hip, leg.knee, leg.ankle}; const ozz::math::Float4x4& transform = offsetted_root * models_[joints[i]]; success &= _renderer->DrawAxes(transform * kAxesScale); } } } // Shows raycast results if (show_raycast_) { for (size_t l = 0; l < kLegsCount; ++l) { const LegRayInfo& ray = rays_info_[l]; if (ray.hit) { success &= _renderer->DrawSegment(ray.start, ray.hit_point, ozz::sample::kGreen, identity); success &= _renderer->DrawSegment( ray.hit_point, ray.hit_point + ray.hit_normal * .5f, ozz::sample::kRed, identity); } else { success &= _renderer->DrawSegment(ray.start, ray.start + ray.dir * 10.f, ozz::sample::kWhite, identity); } } } // Shows two bone ik ankle target if (show_ankle_target_) { for (size_t l = 0; l < kLegsCount; ++l) { const LegRayInfo& ray = rays_info_[l]; if (ray.hit) { const ozz::math::Float4x4& transform = ozz::math::Float4x4::Translation( ozz::math::simd_float4::Load3PtrU(&ankles_target_ws_[l].x)); success &= _renderer->DrawAxes(transform * kAxesScale); } } } if (show_root_) { const ozz::math::Float4x4 root = GetRootTransform(); success &= _renderer->DrawAxes(root); } if (show_offsetted_root_) { success &= _renderer->DrawAxes(offsetted_root); } return success; } virtual bool OnInitialize() { // Reading skeleton. if (!ozz::sample::LoadSkeleton(OPTIONS_skeleton, &skeleton_)) { return false; } // Reading animation. if (!ozz::sample::LoadAnimation(OPTIONS_animation, &animation_)) { return false; } // Allocates runtime buffers. const int num_soa_joints = skeleton_.num_soa_joints(); locals_.resize(num_soa_joints); const int num_joints = skeleton_.num_joints(); models_.resize(num_joints); // Allocates a cache that matches animation requirements. cache_.Resize(num_joints); // Finds left and right joints. if (!SetupLeg(skeleton_, kLeftJointNames, &legs_setup_[kLeft]) || !SetupLeg(skeleton_, kRightJointNames, &legs_setup_[kRight])) { ozz::log::Err() << "At least a joint wasn't found in the skeleton hierarchy." << std::endl; return false; } // Reading character mesh. if (!ozz::sample::LoadMeshes(OPTIONS_mesh, &meshes_)) { return false; } // The number of joints of the mesh needs to match skeleton. for (size_t m = 0; m < meshes_.size(); ++m) { const ozz::sample::Mesh& mesh = meshes_[m]; if (num_joints < mesh.highest_joint_index()) { ozz::log::Err() << "The provided mesh doesn't match skeleton " "(joint count mismatch)." << std::endl; return false; } } skinning_matrices_.resize(num_joints); // Reading collision/rendering floor mesh. if (!ozz::sample::LoadMeshes(OPTIONS_floor, &floors_)) { return false; } return true; } bool SetupLeg(const ozz::animation::Skeleton& _skeleton, const char* _joint_names[3], LegSetup* _leg) { int found = 0; int joints[3]; for (int i = 0; i < _skeleton.num_joints() && found != 3; i++) { const char* joint_name = _skeleton.joint_names()[i]; if (std::strcmp(joint_name, _joint_names[found]) == 0) { joints[found] = i; ++found; } } _leg->hip = joints[0]; _leg->knee = joints[1]; _leg->ankle = joints[2]; return found == 3; } virtual void OnDestroy() {} virtual bool OnGui(ozz::sample::ImGui* _im_gui) { char txt[32]; // Main options { static bool opened = true; ozz::sample::ImGui::OpenClose oc(_im_gui, "Sample options", &opened); if (opened) { _im_gui->DoCheckBox("Auto character height", &auto_character_height_); _im_gui->DoCheckBox("Pelvis correction", &pelvis_correction_); _im_gui->DoCheckBox("Two bone IK (legs)", &two_bone_ik_); _im_gui->DoCheckBox("Aim IK (ankles)", &aim_ik_); } } // Exposes animation runtime playback controls. { static bool open = true; ozz::sample::ImGui::OpenClose oc(_im_gui, "Animation control", &open); if (open) { controller_.OnGui(animation_, _im_gui); } } // Settings { static bool opened = true; ozz::sample::ImGui::OpenClose oc(_im_gui, "IK settings", &opened); if (opened) { sprintf(txt, "Foot height %.2g", foot_heigh_); _im_gui->DoSlider(txt, 0.f, .3f, &foot_heigh_); sprintf(txt, "Weight %.2g", weight_); _im_gui->DoSlider(txt, 0.f, 1.f, &weight_); sprintf(txt, "Soften %.2g", soften_); _im_gui->DoSlider(txt, 0.f, 1.f, &soften_, 1.f, two_bone_ik_); } } { // Root static bool opened = true; ozz::sample::ImGui::OpenClose oc(_im_gui, "Root transformation", &opened); if (opened) { bool moved = false; // Translation _im_gui->DoLabel("Translation"); sprintf(txt, "x %.2g", root_translation_.x); moved |= _im_gui->DoSlider(txt, -10.f, 10.f, &root_translation_.x); sprintf(txt, "y %.2g", root_translation_.y); moved |= _im_gui->DoSlider(txt, 0.f, 5.f, &root_translation_.y, 1.f, !auto_character_height_); sprintf(txt, "z %.2g", root_translation_.z); moved |= _im_gui->DoSlider(txt, -10.f, 10.f, &root_translation_.z); // Rotation (in euler form) _im_gui->DoLabel("Rotation"); sprintf(txt, "yaw %.3g", root_yaw_ * ozz::math::kRadianToDegree); moved |= _im_gui->DoSlider(txt, -ozz::math::kPi, ozz::math::kPi, &root_yaw_); // Character position shouldn't be changed after the update. In this // case, because UI is updated after "game" update, we need to recompute // character offset and IK. if (moved && auto_character_height_) { OnUpdate(0.f, 0.f); } } } // Options { static bool opened = true; ozz::sample::ImGui::OpenClose oc(_im_gui, "Debug options", &opened); if (opened) { _im_gui->DoCheckBox("Show skin", &show_skin_); _im_gui->DoCheckBox("Show joints", &show_joints_); _im_gui->DoCheckBox("Show raycasts", &show_raycast_); _im_gui->DoCheckBox("Show ankle target", &show_ankle_target_); _im_gui->DoCheckBox("Show root", &show_root_); _im_gui->DoCheckBox("Show offsetted root", &show_offsetted_root_); } } return true; } virtual bool GetCameraInitialSetup(ozz::math::Float3* _center, ozz::math::Float2* _angles, float* _distance) const { *_center = ozz::math::Float3(4.7f, 2.3f, -.13f); *_angles = ozz::math::Float2(-.14f, -2.1f); *_distance = 5.9f; return true; } virtual void GetSceneBounds(ozz::math::Box* _box) const { *_box = ozz::math::Box(); } ozz::math::Float4x4 GetRootTransform() const { return ozz::math::Float4x4::Translation( ozz::math::simd_float4::Load3PtrU(&root_translation_.x)) * ozz::math::Float4x4::FromEuler( ozz::math::simd_float4::LoadX(root_yaw_)); } ozz::math::Float4x4 GetOffsettedRootTransform() const { if (!pelvis_correction_) { return GetRootTransform(); } const ozz::math::Float3 offsetted_translation = pelvis_offset_ + root_translation_; return ozz::math::Float4x4::Translation( ozz::math::simd_float4::Load3PtrU(&offsetted_translation.x)) * ozz::math::Float4x4::FromEuler( ozz::math::simd_float4::LoadX(root_yaw_)); } private: // Playback animation controller. This is a utility class that helps with // controlling animation playback time. ozz::sample::PlaybackController controller_; // Runtime skeleton. ozz::animation::Skeleton skeleton_; // Runtime animation. ozz::animation::Animation animation_; // Sampling cache. ozz::animation::SamplingCache cache_; // Buffer of local transforms as sampled from animation_. ozz::Vector<ozz::math::SoaTransform>::Std locals_; // Buffer of model space matrices. ozz::Vector<ozz::math::Float4x4>::Std models_; // Buffer of skinning matrices, result of the joint multiplication of the // inverse bind pose with the model space matrix. ozz::Vector<ozz::math::Float4x4>::Std skinning_matrices_; // The mesh used by the sample. ozz::Vector<ozz::sample::Mesh>::Std meshes_; enum { kLeft, kRight }; enum { kLegsCount = 2 }; LegSetup legs_setup_[kLegsCount]; LegRayInfo rays_info_[kLegsCount]; ozz::math::Float3 ankles_initial_ws_[kLegsCount]; ozz::math::Float3 ankles_target_ws_[kLegsCount]; LegRayInfo capsule; ozz::math::Float3 pelvis_offset_; // The floor meshes used by the sample (collision and rendering). ozz::Vector<ozz::sample::Mesh>::Std floors_; // Root transformation. ozz::math::Float3 root_translation_; float root_yaw_; // Foot height setting float foot_heigh_; float weight_; float soften_; bool auto_character_height_; bool pelvis_correction_; bool two_bone_ik_; bool aim_ik_; bool show_skin_; bool show_joints_; bool show_raycast_; bool show_ankle_target_; bool show_root_; bool show_offsetted_root_; }; int main(int _argc, const char** _argv) { const char* title = "Ozz-animation sample: Foot IK"; return FootIKSampleApplication().Run(_argc, _argv, "1.0", title); }
35.499377
80
0.617238
[ "mesh", "object", "vector", "model", "transform" ]
e110f0762d708a1490698e1ab635987b9a222af6
5,986
cpp
C++
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcPolygonalFaceSet.cpp
nxddsnc/ifcplusplus
959956fe83580ebfb370b8e4ed97044f3df0f3a1
[ "MIT" ]
null
null
null
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcPolygonalFaceSet.cpp
nxddsnc/ifcplusplus
959956fe83580ebfb370b8e4ed97044f3df0f3a1
[ "MIT" ]
null
null
null
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcPolygonalFaceSet.cpp
nxddsnc/ifcplusplus
959956fe83580ebfb370b8e4ed97044f3df0f3a1
[ "MIT" ]
null
null
null
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */ #include <sstream> #include <limits> #include "ifcpp/model/AttributeObject.h" #include "ifcpp/model/BuildingException.h" #include "ifcpp/model/BuildingGuid.h" #include "ifcpp/reader/ReaderUtil.h" #include "ifcpp/writer/WriterUtil.h" #include "ifcpp/IFC4/include/IfcBoolean.h" #include "ifcpp/IFC4/include/IfcCartesianPointList3D.h" #include "ifcpp/IFC4/include/IfcIndexedColourMap.h" #include "ifcpp/IFC4/include/IfcIndexedPolygonalFace.h" #include "ifcpp/IFC4/include/IfcIndexedTextureMap.h" #include "ifcpp/IFC4/include/IfcPolygonalFaceSet.h" #include "ifcpp/IFC4/include/IfcPositiveInteger.h" #include "ifcpp/IFC4/include/IfcPresentationLayerAssignment.h" #include "ifcpp/IFC4/include/IfcStyledItem.h" // ENTITY IfcPolygonalFaceSet IfcPolygonalFaceSet::IfcPolygonalFaceSet() {} IfcPolygonalFaceSet::IfcPolygonalFaceSet( int id ) { m_entity_id = id; } IfcPolygonalFaceSet::~IfcPolygonalFaceSet() {} shared_ptr<BuildingObject> IfcPolygonalFaceSet::getDeepCopy( BuildingCopyOptions& options ) { shared_ptr<IfcPolygonalFaceSet> copy_self( new IfcPolygonalFaceSet() ); if( m_Coordinates ) { copy_self->m_Coordinates = dynamic_pointer_cast<IfcCartesianPointList3D>( m_Coordinates->getDeepCopy(options) ); } if( m_Closed ) { copy_self->m_Closed = dynamic_pointer_cast<IfcBoolean>( m_Closed->getDeepCopy(options) ); } for( size_t ii=0; ii<m_Faces.size(); ++ii ) { auto item_ii = m_Faces[ii]; if( item_ii ) { copy_self->m_Faces.push_back( dynamic_pointer_cast<IfcIndexedPolygonalFace>(item_ii->getDeepCopy(options) ) ); } } for( size_t ii=0; ii<m_PnIndex.size(); ++ii ) { auto item_ii = m_PnIndex[ii]; if( item_ii ) { copy_self->m_PnIndex.push_back( dynamic_pointer_cast<IfcPositiveInteger>(item_ii->getDeepCopy(options) ) ); } } return copy_self; } void IfcPolygonalFaceSet::getStepLine( std::stringstream& stream ) const { stream << "#" << m_entity_id << "= IFCPOLYGONALFACESET" << "("; if( m_Coordinates ) { stream << "#" << m_Coordinates->m_entity_id; } else { stream << "*"; } stream << ","; if( m_Closed ) { m_Closed->getStepParameter( stream ); } else { stream << "$"; } stream << ","; writeEntityList( stream, m_Faces ); stream << ","; stream << "("; for( size_t ii = 0; ii < m_PnIndex.size(); ++ii ) { if( ii > 0 ) { stream << ","; } const shared_ptr<IfcPositiveInteger>& type_object = m_PnIndex[ii]; if( type_object ) { type_object->getStepParameter( stream, false ); } else { stream << "$"; } } stream << ")"; stream << ");"; } void IfcPolygonalFaceSet::getStepParameter( std::stringstream& stream, bool ) const { stream << "#" << m_entity_id; } const std::wstring IfcPolygonalFaceSet::toString() const { return L"IfcPolygonalFaceSet"; } void IfcPolygonalFaceSet::readStepArguments( const std::vector<std::wstring>& args, const std::map<int,shared_ptr<BuildingEntity> >& map ) { const size_t num_args = args.size(); if( num_args != 4 ){ std::stringstream err; err << "Wrong parameter count for entity IfcPolygonalFaceSet, expecting 4, having " << num_args << ". Entity ID: " << m_entity_id << std::endl; throw BuildingException( err.str().c_str() ); } readEntityReference( args[0], m_Coordinates, map ); m_Closed = IfcBoolean::createObjectFromSTEP( args[1], map ); readEntityReferenceList( args[2], m_Faces, map ); readTypeOfIntegerList( args[3], m_PnIndex ); } void IfcPolygonalFaceSet::getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) { IfcTessellatedFaceSet::getAttributes( vec_attributes ); vec_attributes.push_back( std::make_pair( "Closed", m_Closed ) ); if( m_Faces.size() > 0 ) { shared_ptr<AttributeObjectVector> Faces_vec_object( new AttributeObjectVector() ); std::copy( m_Faces.begin(), m_Faces.end(), std::back_inserter( Faces_vec_object->m_vec ) ); vec_attributes.push_back( std::make_pair( "Faces", Faces_vec_object ) ); } if( m_PnIndex.size() > 0 ) { shared_ptr<AttributeObjectVector> PnIndex_vec_object( new AttributeObjectVector() ); std::copy( m_PnIndex.begin(), m_PnIndex.end(), std::back_inserter( PnIndex_vec_object->m_vec ) ); vec_attributes.push_back( std::make_pair( "PnIndex", PnIndex_vec_object ) ); } } void IfcPolygonalFaceSet::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes_inverse ) { IfcTessellatedFaceSet::getAttributesInverse( vec_attributes_inverse ); } void IfcPolygonalFaceSet::setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self_entity ) { IfcTessellatedFaceSet::setInverseCounterparts( ptr_self_entity ); shared_ptr<IfcPolygonalFaceSet> ptr_self = dynamic_pointer_cast<IfcPolygonalFaceSet>( ptr_self_entity ); if( !ptr_self ) { throw BuildingException( "IfcPolygonalFaceSet::setInverseCounterparts: type mismatch" ); } for( size_t i=0; i<m_Faces.size(); ++i ) { if( m_Faces[i] ) { m_Faces[i]->m_ToFaceSet_inverse.push_back( ptr_self ); } } } void IfcPolygonalFaceSet::unlinkFromInverseCounterparts() { IfcTessellatedFaceSet::unlinkFromInverseCounterparts(); for( size_t i=0; i<m_Faces.size(); ++i ) { if( m_Faces[i] ) { std::vector<weak_ptr<IfcPolygonalFaceSet> >& ToFaceSet_inverse = m_Faces[i]->m_ToFaceSet_inverse; for( auto it_ToFaceSet_inverse = ToFaceSet_inverse.begin(); it_ToFaceSet_inverse != ToFaceSet_inverse.end(); ) { weak_ptr<IfcPolygonalFaceSet> self_candidate_weak = *it_ToFaceSet_inverse; if( self_candidate_weak.expired() ) { ++it_ToFaceSet_inverse; continue; } shared_ptr<IfcPolygonalFaceSet> self_candidate( *it_ToFaceSet_inverse ); if( self_candidate.get() == this ) { it_ToFaceSet_inverse= ToFaceSet_inverse.erase( it_ToFaceSet_inverse ); } else { ++it_ToFaceSet_inverse; } } } } }
39.906667
237
0.712496
[ "vector", "model" ]
e11d316d4adf96bdee825ad5fb38c3ff06955066
13,151
hh
C++
dune/xt/functions/generic/element-function.hh
dune-community/dune-xt
da921524c6fff8d60c715cb4849a0bdd5f020d2b
[ "BSD-2-Clause" ]
2
2020-02-08T04:08:52.000Z
2020-08-01T18:54:14.000Z
dune/xt/functions/generic/element-function.hh
dune-community/dune-xt
da921524c6fff8d60c715cb4849a0bdd5f020d2b
[ "BSD-2-Clause" ]
35
2019-08-19T12:06:35.000Z
2020-03-27T08:20:39.000Z
dune/xt/functions/generic/element-function.hh
dune-community/dune-xt
da921524c6fff8d60c715cb4849a0bdd5f020d2b
[ "BSD-2-Clause" ]
1
2020-02-08T04:09:34.000Z
2020-02-08T04:09:34.000Z
// This file is part of the dune-xt project: // https://zivgitlab.uni-muenster.de/ag-ohlberger/dune-community/dune-xt // Copyright 2009-2021 dune-xt developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2019 - 2020) // René Fritze (2019 - 2020) // Tobias Leibner (2020 - 2021) #ifndef DUNE_XT_FUNCTIONS_GENERIC_ELEMENT_FUNCTION_HH #define DUNE_XT_FUNCTIONS_GENERIC_ELEMENT_FUNCTION_HH #include <functional> #include <dune/xt/common/memory.hh> #include <dune/xt/functions/interfaces/element-functions.hh> #include <utility> namespace Dune::XT::Functions { /** * Set of element functions you can pass lambda expressions or std::functions to that get evaluated. */ template <class E, size_t r, size_t rC, class R = double> class GenericElementFunctionSet : public ElementFunctionSetInterface<E, r, rC, R> { using BaseType = ElementFunctionSetInterface<E, r, rC, R>; public: using BaseType::d; using typename BaseType::DerivativeRangeType; using typename BaseType::DomainType; using typename BaseType::ElementType; using typename BaseType::RangeType; using GenericSizeFunctionType = std::function<size_t(const Common::Parameter&)>; using GenericOrderFunctionType = std::function<int(const Common::Parameter&)>; using GenericEvaluateFunctionType = std::function<void(const DomainType&, std::vector<RangeType>&, const Common::Parameter&)>; using GenericJacobianFunctionType = std::function<void(const DomainType&, std::vector<DerivativeRangeType>&, const Common::Parameter&)>; using GenericDerivativeFunctionType = std::function<void( const std::array<size_t, d>&, const DomainType&, std::vector<DerivativeRangeType>&, const Common::Parameter&)>; using GenericPostBindFunctionType = std::function<void(const ElementType&)>; GenericElementFunctionSet(GenericSizeFunctionType size_func, GenericSizeFunctionType max_size_func, GenericOrderFunctionType order_func, GenericEvaluateFunctionType evaluate_func = default_evaluate_function(), const Common::ParameterType& param_type = {}, GenericJacobianFunctionType jacobian_func = default_jacobian_function(), GenericDerivativeFunctionType derivative_func = default_derivative_function(), GenericPostBindFunctionType post_bind_func = default_post_bind_function()) : BaseType(param_type) , size_(std::move(size_func)) , max_size_(std::move(max_size_func)) , order_(std::move(order_func)) , evaluate_(evaluate_func) , jacobian_(jacobian_func) , derivative_(derivative_func) , post_bind_(post_bind_func) {} GenericElementFunctionSet(const size_t fixed_size, const int ord, GenericEvaluateFunctionType evaluate_lambda = default_evaluate_function(), const Common::ParameterType& param_type = {}, GenericJacobianFunctionType jacobian_lambda = default_jacobian_function(), GenericDerivativeFunctionType derivative_lambda = default_derivative_function(), GenericPostBindFunctionType post_bind_func = default_post_bind_function()) : BaseType(param_type) , size_([=](const auto& /*param*/) { return fixed_size; }) , max_size_([=](const auto& /*param*/) { return fixed_size; }) , order_([=](const auto& /*param*/) { return ord; }) , evaluate_(evaluate_lambda) , jacobian_(jacobian_lambda) , derivative_(derivative_lambda) , post_bind_(post_bind_func) {} /** * \name ´´These methods are required by XT::Grid::ElementBoundObject.'' * \{ */ protected: void post_bind(const ElementType& element) final { post_bind_(element); } public: /** * \} * \name ´´These methods are required by ElementFunctionSetInterface.'' * \{ */ size_t size(const Common::Parameter& param = {}) const final { return size_(this->parse_parameter(param)); } size_t max_size(const Common::Parameter& param = {}) const final { return max_size_(this->parse_parameter(param)); } int order(const Common::Parameter& param = {}) const final { return order_(this->parse_parameter(param)); } void evaluate(const DomainType& point_in_reference_element, std::vector<RangeType>& result, const Common::Parameter& param = {}) const final { const auto sz = this->size(param); if (result.size() < sz) result.resize(sz); evaluate_(point_in_reference_element, result, this->parse_parameter(param)); } void jacobians(const DomainType& point_in_reference_element, std::vector<DerivativeRangeType>& result, const Common::Parameter& param = {}) const final { const auto sz = this->size(param); if (result.size() < sz) result.resize(sz); jacobian_(point_in_reference_element, result, this->parse_parameter(param)); } void derivatives(const std::array<size_t, d>& alpha, const DomainType& point_in_reference_element, std::vector<DerivativeRangeType>& result, const Common::Parameter& param = {}) const final { const auto sz = this->size(param); if (result.size() < sz) result.resize(sz); derivative_(alpha, point_in_reference_element, result, this->parse_parameter(param)); } /** * \} * \name ´´These methods may be used to provide defaults on construction.'' * \{ */ static GenericEvaluateFunctionType default_evaluate_function() { return [](const DomainType& /*point_in_reference_element*/, std::vector<RangeType>& /*result*/, const Common::Parameter& /*param*/ = {}) { DUNE_THROW( NotImplemented, "This GenericElementFunctionSet does not provide evaluations, provide an evaluate_lambda on construction!"); }; } static GenericJacobianFunctionType default_jacobian_function() { return [](const DomainType& /*point_in_reference_element*/, std::vector<DerivativeRangeType>& /*result*/, const Common::Parameter& /*param*/ = {}) { DUNE_THROW(NotImplemented, "This GenericElementFunctionSet does not provide jacobian evaluations, provide a " "jacobian_lambda on construction!"); }; } static GenericDerivativeFunctionType default_derivative_function() { return [](const std::array<size_t, d>& /*alpha*/, const DomainType& /*point_in_reference_element*/, std::vector<DerivativeRangeType>& /*result*/, const Common::Parameter& /*param*/ = {}) { DUNE_THROW(NotImplemented, "This GenericElementFunctionSet does not provide derivative evaluations, provide a " "derivative_lambda on construction!"); }; } static GenericPostBindFunctionType default_post_bind_function() { return [](const ElementType&) {}; } /** * \} */ const GenericSizeFunctionType size_; const GenericSizeFunctionType max_size_; const GenericOrderFunctionType order_; const GenericEvaluateFunctionType evaluate_; const GenericJacobianFunctionType jacobian_; const GenericDerivativeFunctionType derivative_; const GenericPostBindFunctionType post_bind_; }; // class GenericElementFunctionSet /** * Element function you can pass lambda expressions or std::functions to that get evaluated. */ template <class E, size_t r, size_t rC, class R = double> class GenericElementFunction : public ElementFunctionInterface<E, r, rC, R> { using BaseType = ElementFunctionInterface<E, r, rC, R>; public: using BaseType::d; using typename BaseType::DerivativeRangeReturnType; using typename BaseType::DomainType; using typename BaseType::ElementType; using typename BaseType::RangeReturnType; using GenericOrderFunctionType = std::function<int(const Common::Parameter&)>; using GenericEvaluateFunctionType = std::function<RangeReturnType(const DomainType&, const Common::Parameter&)>; using GenericJacobianFunctionType = std::function<DerivativeRangeReturnType(const DomainType&, const Common::Parameter&)>; using GenericDerivativeFunctionType = std::function<DerivativeRangeReturnType( const std::array<size_t, d>&, const DomainType&, const Common::Parameter&)>; using GenericPostBindFunctionType = std::function<void(const ElementType&)>; GenericElementFunction( GenericOrderFunctionType order_func, GenericEvaluateFunctionType evaluate_func = default_evaluate_function(), const Common::ParameterType& param_type = {}, GenericJacobianFunctionType jacobian_func = default_jacobian_function(), GenericDerivativeFunctionType derivative_func = default_derivative_function(), GenericPostBindFunctionType post_bind_func = [](const auto&) {}) : BaseType(param_type) , order_(std::move(order_func)) , evaluate_(evaluate_func) , jacobian_(jacobian_func) , derivative_(derivative_func) , post_bind_(post_bind_func) {} GenericElementFunction( const int ord, GenericEvaluateFunctionType evaluate_lambda = default_evaluate_function(), const Common::ParameterType& param_type = {}, GenericJacobianFunctionType jacobian_lambda = default_jacobian_function(), GenericDerivativeFunctionType derivative_lambda = default_derivative_function(), GenericPostBindFunctionType post_bind_func = [](const auto&) {}) : BaseType(param_type) , order_([=](const auto& /*param*/) { return ord; }) , evaluate_(evaluate_lambda) , jacobian_(jacobian_lambda) , derivative_(derivative_lambda) , post_bind_(post_bind_func) {} /** * \name ´´These methods are required by XT::Grid::ElementBoundObject.'' * \{ */ protected: void post_bind(const ElementType& element) final { post_bind_(element); } public: /** * \} * \name ´´These methods are required by ElementFunctionInterface.'' * \{ */ int order(const Common::Parameter& param = {}) const final { return order_(this->parse_parameter(param)); } RangeReturnType evaluate(const DomainType& point_in_reference_element, const Common::Parameter& param = {}) const final { return evaluate_(point_in_reference_element, this->parse_parameter(param)); } DerivativeRangeReturnType jacobian(const DomainType& point_in_reference_element, const Common::Parameter& param = {}) const final { return jacobian_(point_in_reference_element, this->parse_parameter(param)); } DerivativeRangeReturnType derivative(const std::array<size_t, d>& alpha, const DomainType& point_in_reference_element, const Common::Parameter& param = {}) const final { return derivative_(alpha, point_in_reference_element, this->parse_parameter(param)); } /** * \} * \name ´´These methods may be used to provide defaults on construction.'' * \{ */ static GenericEvaluateFunctionType default_evaluate_function() { return [](const DomainType& /*point_in_reference_element*/, const Common::Parameter& /*param*/ = {}) { DUNE_THROW( NotImplemented, "This GenericElementFunction does not provide evaluations, provide an evaluate_lambda on construction!"); return RangeReturnType(); }; } static GenericJacobianFunctionType default_jacobian_function() { return [](const DomainType& /*point_in_reference_element*/, const Common::Parameter& /*param*/ = {}) { DUNE_THROW(NotImplemented, "This GenericElementFunction does not provide jacobian evaluations, provide a " "jacobian_lambda on construction!"); return DerivativeRangeReturnType(); }; } static GenericDerivativeFunctionType default_derivative_function() { return [](const std::array<size_t, d>& /*alpha*/, const DomainType& /*point_in_reference_element*/, const Common::Parameter& /*param*/ = {}) { DUNE_THROW(NotImplemented, "This GenericElementFunction does not provide derivative evaluations, provide a " "derivative_lambda on construction!"); return DerivativeRangeReturnType(); }; } /** * \} */ const GenericOrderFunctionType order_; const GenericEvaluateFunctionType evaluate_; const GenericJacobianFunctionType jacobian_; const GenericDerivativeFunctionType derivative_; const GenericPostBindFunctionType post_bind_; }; // class GenericElementFunction } // namespace Dune::XT::Functions #endif // DUNE_XT_FUNCTIONS_LAMBDA_SMOOTH_FUNCTION_HH
36.941011
118
0.686868
[ "vector" ]
e11e889b0bad3ff6b351b4a47fc048d9a776ea9a
1,886
cpp
C++
HDL2Redstone/src/Cell.cpp
tech4me/HDL2Redstone
738bc080e42b8fd2c1827069ded4ca5135e8c8e1
[ "MIT" ]
null
null
null
HDL2Redstone/src/Cell.cpp
tech4me/HDL2Redstone
738bc080e42b8fd2c1827069ded4ca5135e8c8e1
[ "MIT" ]
null
null
null
HDL2Redstone/src/Cell.cpp
tech4me/HDL2Redstone
738bc080e42b8fd2c1827069ded4ca5135e8c8e1
[ "MIT" ]
null
null
null
#include <Cell.hpp> #include <Exception.hpp> using namespace HDL2Redstone; Cell::Cell(const std::string& Type_, const std::string& CellLibDir_, const std::map<std::string, Pin> Pins_, int Delay_, const std::string& SchematicName_) : Type(Type_), Schem(CellLibDir_ + SchematicName_ + ".schem"), Pins(Pins_), Delay(Delay_) {} std::vector<std::string> Cell::getPinNames() const { std::vector<std::string> Ret; for (const auto& Pin : Pins) { Ret.push_back(Pin.first); } return Ret; } namespace HDL2Redstone { std::ostream& operator<<(std::ostream& out, const Cell& Cell_) { out << "In cell " << Cell_.Type << ": " << std::endl; out << "Pins: " << std::endl; for (const auto& Pin : Cell_.Pins) { out << " " << Pin.first << ": " << std::endl; std::string dir, face; switch (static_cast<int>(Pin.second.Dir)) { case 0: dir = "input"; break; case 1: dir = "output"; break; case 2: dir = "inout"; break; } switch (static_cast<int>(Pin.second.Face)) { case 0: face = "up"; break; case 1: face = "down"; break; case 2: face = "north"; break; case 3: face = "south"; break; case 4: face = "east"; break; case 5: face = "west"; break; } out << " Direction: " << dir << "; Facing: " << face << "; Location: " << std::get<0>(Pin.second.Location) << " " << std::get<1>(Pin.second.Location) << " " << std::get<2>(Pin.second.Location) << std::endl; } out << "Schematic: " << std::endl; out << Cell_.Schem << ": " << std::endl; return out; } } // namespace HDL2Redstone
27.735294
120
0.487275
[ "vector" ]
e11f81a42dc4f88cbbeac98e56fba529e2c2d74e
1,415
hpp
C++
src/sampling/history.hpp
kghose/groho
7f1eefe3f1c691464bc84d12c7759ac4a16c05ca
[ "MIT" ]
11
2018-05-21T06:45:34.000Z
2020-09-14T12:43:34.000Z
src/sampling/history.hpp
kghose/groho
7f1eefe3f1c691464bc84d12c7759ac4a16c05ca
[ "MIT" ]
40
2017-11-14T02:03:51.000Z
2020-07-17T00:35:33.000Z
src/sampling/history.hpp
kghose/groho
7f1eefe3f1c691464bc84d12c7759ac4a16c05ca
[ "MIT" ]
2
2019-10-24T17:45:48.000Z
2021-10-11T18:08:02.000Z
/* This file is part of Groho, a simulator for inter-planetary travel and warfare. Copyright (c) 2020 by Kaushik Ghose. Some rights reserved, see LICENSE */ #pragma once #include <filesystem> #include <memory> #include <vector> #include "fractaldownsampler.hpp" #include "naifbody.hpp" #include "simparams.hpp" // #include "threadedbuffer.hpp" #include "simplebuffer.hpp" #include "v3d.hpp" namespace fs = std::filesystem; namespace groho { class History { public: History(const SimParams& sim_params, NAIFbody code, fs::path path) : dt(sim_params.dt) , code(code) , rotx(-3.14159265358979323846264338327950288419 * 23.5 / 180.0) { sampler = FractalDownsampler(sim_params.rt, sim_params.lt); // buffer.reset(new ThreadedBuffer<V3d>(path)); buffer.reset(new SimpleBuffer<V3d>(path)); } void sample(const V3d& pos) { if (sampler(pos)) { // buffer->write(rotx(pos)); buffer->write(pos); } } ~History() { V3d last_pos; if (sampler.flush(last_pos)) { // buffer->write(rotx(last_pos)); buffer->write(last_pos); } } private: const double dt; const NAIFbody code; FractalDownsampler sampler; RotateX rotx; // std::shared_ptr<ThreadedBuffer<V3d>> buffer; std::shared_ptr<SimpleBuffer<V3d>> buffer; }; }
22.109375
79
0.625442
[ "vector" ]
e12365ef991bf0fc5a1fa4e98da914e533ede2ba
16,353
cpp
C++
src/event_loop.cpp
netplus/netplus
e3b621e65742f38733d3dcaa1873443da8bbd611
[ "MIT" ]
48
2021-02-22T03:10:40.000Z
2022-03-29T03:26:33.000Z
src/event_loop.cpp
netplus/netplus
e3b621e65742f38733d3dcaa1873443da8bbd611
[ "MIT" ]
7
2021-03-20T09:25:11.000Z
2022-03-07T03:26:56.000Z
src/event_loop.cpp
netplus/netplus
e3b621e65742f38733d3dcaa1873443da8bbd611
[ "MIT" ]
13
2021-02-25T01:49:58.000Z
2022-03-21T00:30:34.000Z
#include <netp/core.hpp> #include <netp/app.hpp> #include <netp/timer.hpp> #include <netp/thread.hpp> #include <netp/event_loop.hpp> #include <netp/dns_resolver.hpp> #if defined(NETP_HAS_POLLER_EPOLL) #include <netp/poller_epoll.hpp> #define NETP_DEFAULT_POLLER_TYPE netp::io_poller_type::T_EPOLL #elif defined(NETP_HAS_POLLER_SELECT) #include <netp/poller_select.hpp> #define NETP_DEFAULT_POLLER_TYPE netp::io_poller_type::T_SELECT #elif defined(NETP_HAS_POLLER_KQUEUE) #include <netp/poller_kqueue.hpp> #define NETP_DEFAULT_POLLER_TYPE netp::io_poller_type::T_KQUEUE #elif defined(NETP_HAS_POLLER_IOCP) #include <netp/poller_iocp.hpp> #include <netp/poller_select.hpp> #define NETP_DEFAULT_POLLER_TYPE netp::io_poller_type::T_IOCP #else #error "unknown poller type" #endif namespace netp { NRP<event_loop> default_event_loop_maker(event_loop_cfg const& cfg) { NRP<poller_abstract> poller; switch (cfg.type) { #if defined(NETP_HAS_POLLER_EPOLL) case T_EPOLL: { poller = netp::make_ref<poller_epoll>(); NETP_ALLOC_CHECK(poller, sizeof(poller_epoll)); } break; #elif defined(NETP_HAS_POLLER_IOCP) case T_IOCP: { poller = netp::make_ref<poller_iocp>(); NETP_ALLOC_CHECK(poller, sizeof(poller_iocp)); } break; case T_SELECT: { poller = netp::make_ref<poller_select>(); NETP_ALLOC_CHECK(poller, sizeof(poller_select)); } break; #elif defined(NETP_HAS_POLLER_KQUEUE) case T_KQUEUE: { poller = netp::make_ref<poller_kqueue>(); NETP_ALLOC_CHECK(poller, sizeof(poller_kqueue)); } break; #else case T_SELECT: { poller = netp::make_ref<poller_select>(); NETP_ALLOC_CHECK(poller, sizeof(poller_select)); } break; #endif default: { NETP_THROW("invalid poll type"); } } NETP_ASSERT(poller != nullptr); return netp::make_ref<event_loop>(cfg, poller); } void event_loop::init() { m_channel_rcv_buf = netp::make_ref<netp::packet>(m_cfg.channel_read_buf_size,0); m_tid = std::this_thread::get_id(); m_tb = netp::make_ref<timer_broker>(); m_poller->init(); if (m_cfg.flag & f_enable_dns_resolver) { if (m_cfg.type == NETP_DEFAULT_POLLER_TYPE) { m_dns_resolver = netp::make_ref<dns_resolver>(NRP<event_loop>(this)); inc_internal_ref_count(); } else { m_dns_resolver = netp::make_ref<dns_resolver>(netp::app::instance()->def_loop_group()->next()); } if (m_dns_hosts.size()) { m_dns_resolver->add_name_server(m_dns_hosts); } NRP<netp::promise<int>> dnsp = m_dns_resolver->start(); if (dnsp->get() != netp::OK) { char _fail_message[256] = { 0 }; snprintf(_fail_message, 255, "dns resolver start failed: %d", dnsp->get()); NETP_ERR("[app]start dnsresolver failed: %d, exit", dnsp->get()); NETP_THROW("dns_resolver start failed"); } } } void event_loop::deinit() { NETP_VERBOSE("[event_loop]deinit begin"); NETP_ASSERT(in_event_loop()); NETP_ASSERT(m_state.load(std::memory_order_acquire) == u8_t(loop_state::S_EXIT), "event loop deinit state check failed"); if (m_cfg.flag & f_enable_dns_resolver) { NETP_ASSERT(m_dns_resolver != nullptr); m_dns_resolver = nullptr; } { lock_guard<spin_mutex> lg(m_tq_mutex); NETP_ASSERT(m_tq_standby.empty()); } NETP_ASSERT(m_tq.empty()); NETP_ASSERT(m_tb->size() == 0); m_tb = nullptr; m_poller->deinit(); NETP_VERBOSE("[event_loop]deinit done"); } //@NOTE: promise to execute all task already in tq or tq_standby void event_loop::__run() { if(m_cfg.flag&f_th_thread_affinity) { m_th->set_affinity(m_cfg.thread_affinity); } if (m_cfg.flag & f_th_priority_time_critical) { m_th->set_priority_time_critical(); } else if (m_cfg.flag & f_th_priority_above_normal) { m_th->set_priority_above_normal(); } //NETP_ASSERT(!"CHECK EXCEPTION STACK"); init(); //record a snapshot, used by update state m_io_ctx_count_before_running = m_io_ctx_count; u8_t _SL = u8_t(loop_state::S_LAUNCHING); const bool rt = m_state.compare_exchange_strong(_SL, u8_t(loop_state::S_RUNNING), std::memory_order_acq_rel, std::memory_order_acquire); NETP_ASSERT(rt == true); try { //this load also act as a memory synchronization fence to sure all release operation happen before this line //if we make_ref a atomic_ref object, then we call L->schedule([o=atomic_ref_instance](){});, the assign of a atomic_ref_instance would trigger memory_order_acq_rel, this operation guard all object member initialization and member valud update before the assign //all member value of that object must be synchronized after this line, cuz we have netp::atomic_incre inside ref object while (NETP_UNLIKELY(u8_t(loop_state::S_EXIT) != m_state.load(std::memory_order_acquire))) { { //again the spin_mutex acts as a memory synchronization fence lock_guard<spin_mutex> lg(m_tq_mutex); if (!m_tq_standby.empty()) { std::swap(m_tq, m_tq_standby); } } std::size_t ss = m_tq.size(); if (ss > 0) { std::size_t i = 0; while (i < ss) { m_tq[i++](); } if (ss > 1024) { io_task_q_t().swap(m_tq); } else { m_tq.clear(); } } //@_calc_wait_dur_in_nano must happen before poll.. m_poller->poll(_calc_wait_dur_in_nano(), m_waiting); } } catch (...) { //@NOTE: we should terminate our process in this case //m_state = S_EXIT; //deinit(); NETP_WARN("[event_loop]__run reach exception------------------------------------------"); throw; } { NETP_VERBOSE("[event_loop]exiting run"); // EDGE check // scenario 1: // 1) do schedule, 2) set L -> null std::size_t i = 0; std::size_t vecs = m_tq_standby.size(); while (i < vecs) { m_tq_standby[i++](); } m_tq_standby.clear(); m_tb->expire_all(); } deinit(); } void event_loop::__do_notify_terminating() { NETP_ASSERT( in_event_loop() ); //dns resolver stop would result in dns socket be removed from io_ctx //we keep m_dns_resolver instance until there is no event_loop reference outside //no new fd is accepted after state enter terminating, so it's safe to stop dns first if (m_cfg.flag & f_enable_dns_resolver) { NETP_ASSERT(m_dns_resolver != nullptr); m_dns_resolver->stop(); } io_do(io_action::NOTIFY_TERMINATING, 0); if (m_io_ctx_count == m_io_ctx_count_before_running) { __do_enter_terminated(); } // NETP_VERBOSE("[event_loop]__do_notify_terminating done"); } void event_loop::__do_enter_terminated() { //no competitor here, store directly NETP_ASSERT(in_event_loop()); m_state.store(u8_t(loop_state::S_TERMINATED), std::memory_order_release); NETP_ASSERT(m_tb != nullptr); m_tb->expire_all(); } //terminating phase 1 void event_loop::__notify_terminating() { u8_t running = u8_t(loop_state::S_RUNNING); if (m_state.compare_exchange_strong(running, u8_t(loop_state::S_TERMINATING), std::memory_order_acq_rel, std::memory_order_acquire)) { schedule([L = NRP<event_loop>(this)]() { L->__do_notify_terminating(); }); } } int event_loop::__launch() { u8_t _si = u8_t(loop_state::S_IDLE); bool upstate = m_state.compare_exchange_strong(_si, u8_t(loop_state::S_LAUNCHING), std::memory_order_acq_rel, std::memory_order_acquire); NETP_ASSERT(upstate == true); m_th = netp::make_ref<netp::thread>(); int rt = m_th->start(&event_loop::__run, NRP<event_loop>(this)); NETP_RETURN_V_IF_NOT_MATCH(rt, rt == netp::OK); int k = 0; while (m_state.load(std::memory_order_acquire) == u8_t(loop_state::S_LAUNCHING)) { netp::this_thread::yield(++k); } //NETP_VERBOSE("[event_loop][%u]__launch done", m_type); return netp::OK; } void event_loop::__terminate() { NETP_VERBOSE("[event_loop][%u]__terminate begin", m_cfg.type ); while (m_state.load(std::memory_order_acquire) != u8_t(loop_state::S_TERMINATED)) { netp::this_thread::sleep(1); } u8_t terminated = u8_t(loop_state::S_TERMINATED); if (m_state.compare_exchange_strong(terminated, u8_t(loop_state::S_EXIT), std::memory_order_acq_rel, std::memory_order_acquire)) { NETP_VERBOSE("[event_loop][%u]enter S_EXIT, last interrupt if needed", m_cfg.type); m_poller->interrupt_wait(); //@NOTE: //1, we don't interrupt these kinds of thread, cuz we want all the tasks be finished one by one //m_th->interrupt(); m_th->join(); m_th = nullptr; } NETP_INFO("[event_loop][%u]__terminate end", m_cfg.type ) ; } event_loop::event_loop(event_loop_cfg const& cfg, NRP<poller_abstract> const& poller): m_waiting(false), m_state(u8_t(loop_state::S_IDLE)), m_cfg(cfg), m_poller(poller), m_io_ctx_count(0), m_io_ctx_count_before_running(0), m_internal_ref_count(0), m_dns_hosts(cfg.dns_hosts.begin(), cfg.dns_hosts.end()) {} event_loop::~event_loop() { NETP_ASSERT(m_tb == nullptr); NETP_ASSERT(m_th == nullptr); } event_loop_group::event_loop_group( event_loop_cfg const& cfg, fn_event_loop_maker_t const& L_maker): m_curr_loop_idx(0), m_bye_state(bye_event_loop_state::S_IDLE), m_bye_ref_count(0), m_cfg(cfg), m_fn_loop_maker(L_maker) { } event_loop_group::~event_loop_group() { //guarentee to always return non-null for next() bye_event_loop_state bye_state_exit = bye_event_loop_state::S_EXIT; if (m_bye_state.compare_exchange_strong(bye_state_exit, bye_event_loop_state::S_IDLE, std::memory_order_acq_rel, std::memory_order_acquire) ) { m_bye_event_loop = nullptr; m_bye_ref_count = 0; } NETP_ASSERT(m_bye_event_loop == nullptr); } void event_loop_group::notify_terminating() { shared_lock_guard<shared_mutex> slg(m_loop_mtx); for(::size_t i=0;i<m_loop.size();++i) { m_loop[i]->__notify_terminating(); } } /* @dealloc logic I, phase 1, detach event_loop from event_loop_vector one by one by the following procedure 1) call event_loop->notify_terminating() to give a termination notification to all FDs 2) loop enter in terminating state, all fd object(socket) would received a termination notification, do force close a) no new fd would be accepted on TERMINATING state b) fd ctx would be removed after socket be closed 3) once all fds ctx has been removed from LOOP, LOOP enter TERMINATED state a) no new timer would be accepted on TERMINATED state b) update state to S_EXIT (by loop_group) c) LOOP do deinit 4), remove LOOP from loop_vector II, when event_loop_vector.size() == 0, next() would always return m_bye_event_loop III, when event_loop_vector.size() ==0, we enter into phase 2 IV, in phase 2, we terminate m_bye_event_loop */ void event_loop_group::_wait_loop() { __dealloc_begin: std::vector<NRP<event_loop>> to_deattach; { lock_guard<shared_mutex> lg(m_loop_mtx); if (m_loop.size() == 0) { event_loop_vector_t().swap(m_loop); //NETP_INFO("[event_loop][%u]__dealloc_poller end, all event loop dattached", t); return;//exit } bye_event_loop_state idle = bye_event_loop_state::S_IDLE; if (m_bye_state.compare_exchange_strong(idle, bye_event_loop_state::S_PREPARING, std::memory_order_acq_rel, std::memory_order_acquire)) { NETP_ASSERT(m_bye_event_loop == nullptr, "m_bye_event_loop check failed"); event_loop_cfg __cfg = m_cfg; __cfg.flag &= ~(f_th_thread_affinity | f_th_priority_above_normal | f_th_priority_time_critical); m_bye_event_loop = m_fn_loop_maker(__cfg); int rt = m_bye_event_loop->__launch(); NETP_ASSERT(rt == netp::OK); m_bye_ref_count = m_bye_event_loop.ref_count(); bye_event_loop_state preparing = bye_event_loop_state::S_PREPARING; bool set_to_running = m_bye_state.compare_exchange_strong(preparing, bye_event_loop_state::S_RUNNING, std::memory_order_acq_rel, std::memory_order_acquire); NETP_ASSERT(set_to_running == true); NETP_ASSERT(m_bye_state.load(std::memory_order_relaxed) == bye_event_loop_state::S_RUNNING); } event_loop_vector_t::iterator&& it = m_loop.begin(); while (it != m_loop.end()) { //ref_count == internal_ref_count means no other ref for this LOOP, it is safe to deattach it from our pool if ((*it).ref_count() == (*it)->internal_ref_count()) { NETP_VERBOSE("[event_loop][%u]__dealloc_poller, dattached one event loop", m_cfg.type); to_deattach.push_back(*it); m_loop.erase(it); break; } else { ++it; } } } while (to_deattach.size()) { to_deattach.back()->__terminate(); to_deattach.pop_back(); } netp::this_thread::no_interrupt_sleep(1); goto __dealloc_begin; } void event_loop_group::wait() { //phase 2, deattach one by one NETP_INFO("[event_loop]__dealloc_poller, type: %d", m_cfg.type); _wait_loop(); NETP_INFO("[event_loop]__dealloc_poller, type: %d done", m_cfg.type); bye_event_loop_state running = bye_event_loop_state::S_RUNNING; if (m_bye_state.compare_exchange_strong(running, bye_event_loop_state::S_EXIT, std::memory_order_acq_rel, std::memory_order_acquire)) { NETP_INFO("[event_loop]__dealloc_poller bye, begin"); NETP_ASSERT(m_bye_event_loop != nullptr); m_bye_event_loop->__notify_terminating(); while (m_bye_event_loop.ref_count() != m_bye_ref_count) { //NETP_INFO("l.ref_count: %ld, ref_count: %ld", m_bye_event_loop.ref_count(), m_bye_ref_count.load(std::memory_order_acquire) ); netp::this_thread::no_interrupt_sleep(1); } m_bye_event_loop->__terminate(); NETP_INFO("[event_loop]__dealloc_poller bye done"); } } void event_loop_group::start(u32_t count ) { NETP_VERBOSE("[event_loop_group]alloc poller: %u, count: %u, ch_buf_read_size: %u", m_cfg.type, count, m_cfg.channel_read_buf_size); lock_guard<shared_mutex> lg(m_loop_mtx); m_curr_loop_idx = 0; NETP_ASSERT( m_fn_loop_maker != nullptr ); while (count-- > 0) { event_loop_cfg __cfg = m_cfg; if (m_cfg.flag&f_th_thread_affinity) { ++m_cfg.thread_affinity; } NRP<event_loop> o = m_fn_loop_maker(__cfg); int rt = o->__launch(); NETP_ASSERT(rt == netp::OK); o->store_internal_ref_count(o.ref_count()); m_loop.push_back(std::move(o)); } } void event_loop_group::stop() { notify_terminating(); wait(); } netp::size_t event_loop_group::size() { shared_lock_guard<shared_mutex> lg(m_loop_mtx); return netp::size_t(m_loop.size()); } //if there is a event_loop_group instance, we must always guarantee to return non-null loop instance NRP<event_loop> event_loop_group::next(std::set<NRP<event_loop>> const& exclude_this_list_if_have_more) { { shared_lock_guard<shared_mutex> lg(m_loop_mtx); if (m_loop.size() > 0) { const std::size_t psize = m_loop.size(); if (psize <= exclude_this_list_if_have_more.size()) { //skip one time //u32_t idx = netp::atomic_incre(&m_curr_poller_idx[t]) % psize; //if (exclude_this_list_if_have_more.find(pollers[idx]) == exclude_this_list_if_have_more.end()) { // return pollers[idx]; //} return m_loop[m_curr_loop_idx.fetch_add(1, std::memory_order_relaxed) % psize]; } else { u32_t idx = m_curr_loop_idx.fetch_add(1, std::memory_order_relaxed) % psize; while (exclude_this_list_if_have_more.find(m_loop[idx]) != exclude_this_list_if_have_more.end()) { idx = m_curr_loop_idx.fetch_add(1, std::memory_order_relaxed) % psize; } return m_loop[idx]; } } } if (m_bye_state.load(std::memory_order_relaxed) != bye_event_loop_state::S_IDLE) { NETP_ASSERT(m_bye_event_loop != nullptr); return m_bye_event_loop; } NETP_THROW("event_loop_group deinit logic issue"); } NRP<event_loop> event_loop_group::next() { { shared_lock_guard<shared_mutex> lg(m_loop_mtx); if (m_loop.size() != 0) { return m_loop[m_curr_loop_idx.fetch_add(1, std::memory_order_relaxed) % m_loop.size()]; } } if(m_bye_state.load(std::memory_order_relaxed) != bye_event_loop_state::S_IDLE) { NETP_ASSERT(m_bye_event_loop != nullptr); return m_bye_event_loop; } NETP_THROW("event_loop_group deinit logic issue"); } void event_loop_group::execute(fn_task_t&& f) { next()->execute(std::forward<fn_task_t>(f)); } void event_loop_group::schedule(fn_task_t&& f) { next()->schedule(std::forward<fn_task_t>(f)); } void event_loop_group::launch(NRP<netp::timer> const& t, NRP<netp::promise<int>> const& lf) { next()->launch(t,lf); } }
33.927386
264
0.709411
[ "object", "vector" ]
e127f00ea07f0304d1078abe56679c77c91bda22
2,431
cc
C++
CondCore/DBOutputService/test/stubs/writeKeyed.cc
PKUfudawei/cmssw
8fbb5ce74398269c8a32956d7c7943766770c093
[ "Apache-2.0" ]
2
2020-10-26T18:40:32.000Z
2021-04-10T16:33:25.000Z
CondCore/DBOutputService/test/stubs/writeKeyed.cc
PKUfudawei/cmssw
8fbb5ce74398269c8a32956d7c7943766770c093
[ "Apache-2.0" ]
30
2015-11-04T11:42:27.000Z
2021-12-01T07:56:34.000Z
CondCore/DBOutputService/test/stubs/writeKeyed.cc
PKUfudawei/cmssw
8fbb5ce74398269c8a32956d7c7943766770c093
[ "Apache-2.0" ]
8
2016-03-25T07:17:43.000Z
2021-07-08T17:11:21.000Z
#include "FWCore/Framework/interface/one/EDAnalyzer.h" #include "FWCore/ServiceRegistry/interface/Service.h" #include "CondCore/DBOutputService/interface/PoolDBOutputService.h" #include "CondCore/DBOutputService/interface/KeyedElement.h" #include "CondFormats/Calibration/interface/Conf.h" #include <iostream> #include <string> class writeKeyed : public edm::one::EDAnalyzer<> { public: explicit writeKeyed(const edm::ParameterSet& iConfig); virtual void analyze(const edm::Event&, const edm::EventSetup&) {} virtual void endJob(); private: std::string confcont, confiov; }; void writeKeyed::endJob() { std::vector<std::string> dict; size_t tot = 0; dict.push_back("Sneezy"); tot += dict.back().size(); dict.push_back("Sleepy"); tot += dict.back().size(); dict.push_back("Dopey"); tot += dict.back().size(); dict.push_back("Doc"); tot += dict.back().size(); dict.push_back("Happy"); tot += dict.back().size(); dict.push_back("Bashful"); tot += dict.back().size(); dict.push_back("Grumpy"); tot += dict.back().size(); char const* nums[] = {"1", "2", "3", "4", "5", "6", "7"}; edm::Service<cond::service::PoolDBOutputService> outdb; std::map<cond::Time_t, cond::BaseKeyed*> keys; // populated with the keyed payloads (configurations) for (size_t i = 0; i < dict.size(); ++i) for (size_t j = 0; j < 7; ++j) { cond::BaseKeyed* bk = 0; cond::KeyedElement k((0 == i % 2) ? bk = new condex::ConfI(dict[i] + nums[j], 10 * i + j) : bk = new condex::ConfF(dict[i] + nums[j], i + 0.1 * j), dict[i] + nums[j]); std::cout << k.m_skey << " " << k.m_key << std::endl; keys.insert(std::make_pair(k.m_key, k.m_obj)); } std::cout << "# uploading keys..." << std::endl; for (auto k : keys) outdb->writeOneIOV(k.second, k.first, confcont); std::cout << "# uploading master payloads..." << std::endl; // populate the master payload int run = 10; for (size_t j = 0; j < 7; ++j) { std::vector<cond::Time_t> kl; for (size_t i = 0; i < dict.size(); ++i) (kl).at(i) = cond::KeyedElement::convert(dict[i] + nums[j]); outdb->writeOneIOV(kl, run, confiov); run += 10; } } writeKeyed::writeKeyed(const edm::ParameterSet& iConfig) : confcont("confcont"), confiov("confiov") {} #include "FWCore/Framework/interface/MakerMacros.h" DEFINE_FWK_MODULE(writeKeyed);
31.986842
102
0.619087
[ "vector" ]
e12a38ed69a1dc06fdd60c0feb419861addab1f0
5,017
cpp
C++
AnyGraph/src/Graph/GraphMLHandler.cpp
fg-netzwerksicherheit/EvolutionaryNetworkOptimizer
fdca004ba33a0d891f7d82f32999ec7d07a041f9
[ "Apache-2.0" ]
null
null
null
AnyGraph/src/Graph/GraphMLHandler.cpp
fg-netzwerksicherheit/EvolutionaryNetworkOptimizer
fdca004ba33a0d891f7d82f32999ec7d07a041f9
[ "Apache-2.0" ]
null
null
null
AnyGraph/src/Graph/GraphMLHandler.cpp
fg-netzwerksicherheit/EvolutionaryNetworkOptimizer
fdca004ba33a0d891f7d82f32999ec7d07a041f9
[ "Apache-2.0" ]
null
null
null
/* * GraphMLHandler.cpp * * Created on: Jun 13, 2017 * Author: quang */ #include "GraphMLHandler.h" #include <iostream> #include <vector> #include <tinyxml2.h> #include <fstream> #include <string> #include "Components/Topology.h" using namespace std; using namespace tinyxml2; namespace anygraph { GraphMLHandler::GraphMLHandler() { // TODO Auto-generated constructor stub } GraphMLHandler::~GraphMLHandler() { // TODO Auto-generated destructor stub } std::shared_ptr<Topology> GraphMLHandler::ReadGraph(std::string file_name) { std::shared_ptr<Topology> top = make_shared<Topology>(); vector<Attributes> combo_key_name; Attributes e_key_name, attr; XMLDocument doc; doc.LoadFile(file_name.c_str()); XMLElement* root = doc.RootElement(); XMLElement* graph = root->FirstChildElement("graph"); for (XMLElement* attribute_name = root->FirstChildElement("key"); attribute_name; attribute_name = attribute_name->NextSiblingElement("key")) { //cout<<"begin"<<endl; e_key_name = Attributes(); e_key_name.set_id(attribute_name->Attribute("id")); e_key_name.set_name(attribute_name->Attribute("attr.name")); e_key_name.set_type(attribute_name->Attribute("attr.type")); combo_key_name.push_back(e_key_name); //cout<<"end"<<endl; } for (XMLElement* node = graph->FirstChildElement("node"); node; node = node->NextSiblingElement("node")) { //cout<<"begin note"<<endl; AnyNode anyNode(node->Attribute("id")); for (XMLElement *attribute = node->FirstChildElement("data"); attribute; attribute = attribute->NextSiblingElement("data")) { attr = Attributes(); attr.set_id(attribute->Attribute("key")); for (uint i = 0; i < combo_key_name.size(); ++i) { if (combo_key_name[i].get_attribute_id() == attribute->Attribute("key")) { attr.set_name(combo_key_name[i].get_attribute_name()); attr.set_type(combo_key_name[i].get_attribute_type()); } } if (attribute->GetText()) { attr.set_data(attribute->GetText()); } anyNode.add_attributes(attr); } top->add_node(anyNode); } for (XMLElement* edge = graph->FirstChildElement("edge"); edge; edge = edge->NextSiblingElement("edge")) { AnyEdge anyEdge(edge->Attribute("source"), edge->Attribute("target")); for (XMLElement *attribute = edge->FirstChildElement("data"); attribute; attribute = attribute->NextSiblingElement("data")) { attr = Attributes(); attr.set_id(attribute->Attribute("key")); for (uint i = 0; i < combo_key_name.size(); ++i) { if (combo_key_name[i].get_attribute_id() == attribute->Attribute("key")) { attr.set_name(combo_key_name[i].get_attribute_name()); attr.set_type(combo_key_name[i].get_attribute_type()); } } if (attribute->GetText()) { attr.set_data(attribute->GetText()); } anyEdge.add_attribute(attr); } top->add_edge(anyEdge); } for (auto att : combo_key_name) top->add_attribute(att); return top; } void GraphMLHandler::WriteGraph(std::shared_ptr<Topology> topo, std::string file_name) { XMLDocument xmlDoc; std::string filetype = "graphml"; XMLNode * pRoot = xmlDoc.NewElement(filetype.c_str()); xmlDoc.InsertFirstChild(pRoot); // write graph's keys for (Attributes att : topo->get_attributes()) { XMLElement * key_element = xmlDoc.NewElement("key"); key_element->SetAttribute("id", att.get_attribute_id().c_str()); key_element->SetAttribute("attr.name", att.get_attribute_name().c_str()); key_element->SetAttribute("attr.type", att.get_attribute_type().c_str()); pRoot->InsertEndChild(key_element); } // write graph nodes & edges XMLElement * graph_element = xmlDoc.NewElement("graph"); // write nodes for (AnyNode node : topo->get_node()) { XMLElement * node_element = xmlDoc.NewElement("node"); node_element->SetAttribute("id", node.get_ID().c_str()); // write a node's data for (Attributes att : node.get_attribute_list()) { XMLElement * data_element = xmlDoc.NewElement("data"); data_element->SetAttribute("key", att.get_attribute_id().c_str()); data_element->SetText(att.get_attribute_data().c_str()); node_element->InsertEndChild(data_element); } graph_element->InsertEndChild(node_element); } // write edges for (AnyEdge edge : topo->get_edge()) { XMLElement * edge_element = xmlDoc.NewElement("edge"); edge_element->SetAttribute("source", edge.get_From().c_str()); edge_element->SetAttribute("target", edge.get_To().c_str()); // write an edge's data for (Attributes att : edge.get_Attribute()) { XMLElement * data_element = xmlDoc.NewElement("data"); data_element->SetAttribute("key", att.get_attribute_id().c_str()); data_element->SetText(att.get_attribute_data().c_str()); edge_element->InsertEndChild(data_element); } graph_element->InsertEndChild(edge_element); } pRoot->InsertEndChild(graph_element); XMLError eResult = xmlDoc.SaveFile(file_name.c_str()); if (eResult != XML_SUCCESS) throw "Error writing " + filetype + " file!"; } } /* namespace anygraph */
31.161491
88
0.704405
[ "vector" ]
e141a87a2eb46f177d1ac35328d98bba9cb38fff
3,951
cpp
C++
src/MetricsReporter.cpp
ess-dmsc/forward-epics-to-kafka
46e1cfff0a3792b4e70ec5c58c2e56c941da5d5c
[ "BSD-2-Clause" ]
1
2019-02-23T01:48:51.000Z
2019-02-23T01:48:51.000Z
src/MetricsReporter.cpp
ess-dmsc/forward-epics-to-kafka
46e1cfff0a3792b4e70ec5c58c2e56c941da5d5c
[ "BSD-2-Clause" ]
266
2017-03-20T08:55:03.000Z
2020-05-26T09:00:24.000Z
src/MetricsReporter.cpp
ess-dmsc/forward-epics-to-kafka
46e1cfff0a3792b4e70ec5c58c2e56c941da5d5c
[ "BSD-2-Clause" ]
5
2017-07-04T10:00:43.000Z
2021-05-05T15:00:02.000Z
// SPDX-License-Identifier: BSD-2-Clause // // This code has been produced by the European Spallation Source // and its partner institutes under the BSD 2 Clause License. // // See LICENSE.md at the top level for license information. // // Screaming Udder! https://esss.se #include "MetricsReporter.h" #include "CURLReporter.h" #include "Converter.h" #include "Forwarder.h" #ifdef _MSC_VER std::vector<char> getHostname() { std::vector<char> Hostname; return Hostname; } #else #include <unistd.h> std::vector<char> getHostname() { std::vector<char> Hostname; Hostname.resize(256); gethostname(Hostname.data(), Hostname.size()); if (Hostname.back() != 0) { // likely an error Hostname.back() = 0; } return Hostname; } #endif namespace Forwarder { MetricsReporter::MetricsReporter( std::chrono::milliseconds Interval, MainOpt &ApplicationMainOptions, std::shared_ptr<InstanceSet> &MainLoopKafkaInstanceSet) : IO(), Period(Interval), AsioTimer(IO, Period), MainOptions(ApplicationMainOptions), KafkaInstanceSet(MainLoopKafkaInstanceSet) { Logger->trace("Starting the MetricsTimer"); AsioTimer.async_wait([this](std::error_code const &Error) { if (Error != asio::error::operation_aborted) { this->reportMetrics(); } }); MetricsThread = std::thread(&MetricsReporter::run, this); } std::unique_lock<std::mutex> MetricsReporter::get_lock_converters() { return std::unique_lock<std::mutex>(converters_mutex); } void MetricsReporter::reportMetrics() { KafkaInstanceSet->logMetrics(); auto m1 = g__total_msgs_to_kafka.load(); auto m2 = m1 / 1000; m1 = m1 % 1000; uint64_t b1 = g__total_bytes_to_kafka.load(); auto b2 = b1 / 1024; b1 %= 1024; auto b3 = b2 / 1024; b2 %= 1024; Logger->info("m: {:4}.{:03} b: {:3}.{:03}.{:03}", m2, m1, b3, b2, b1); if (CURLReporter::HaveCURL && !MainOptions.InfluxURI.empty()) { std::vector<char> Hostname = getHostname(); int i1 = 0; fmt::memory_buffer StatsBuffer; for (auto &s : KafkaInstanceSet->getStatsForAllProducers()) { format_to(StatsBuffer, "forward-epics-to-kafka,hostname={},set={}", Hostname.data(), i1); format_to(StatsBuffer, " produced={}", s.produced); format_to(StatsBuffer, ",produce_fail={}", s.produce_fail); format_to(StatsBuffer, ",local_queue_full={}", s.local_queue_full); format_to(StatsBuffer, ",produce_cb={}", s.produce_cb); format_to(StatsBuffer, ",produce_cb_fail={}", s.produce_cb_fail); // format_to(StatsBuffer, ",poll_served={}", s.poll_served); format_to(StatsBuffer, ",msg_too_large={}", s.msg_too_large); format_to(StatsBuffer, ",produced_bytes={}", double(s.produced_bytes)); format_to(StatsBuffer, ",outq={}", s.out_queue); format_to(StatsBuffer, "\n"); ++i1; } { auto lock = get_lock_converters(); Logger->info("N converters: {}", converters.size()); i1 = 0; for (auto &c : converters) { auto stats = c.second.lock()->stats(); format_to(StatsBuffer, "forward-epics-to-kafka,hostname={},set={}", Hostname.data(), i1); int i2 = 0; for (auto x : stats) { if (i2 > 0) { format_to(StatsBuffer, ","); } else { format_to(StatsBuffer, " "); } fmt::format_to(StatsBuffer, "{}={}", x.first, x.second); ++i2; } format_to(StatsBuffer, "\n"); ++i1; } } CURLReporter::send(StatsBuffer, MainOptions.InfluxURI); } AsioTimer.expires_at(AsioTimer.expires_at() + Period); AsioTimer.async_wait([this](std::error_code const &Error) { if (Error != asio::error::operation_aborted) { this->reportMetrics(); } }); } MetricsReporter::~MetricsReporter() { Logger->trace("Stopping MetricsTimer"); IO.stop(); MetricsThread.join(); } } // namespace Forwarder
31.608
77
0.636548
[ "vector" ]
e142f9ef7f97cad91c3c7fc9839c2c5319b2e7cf
15,625
cpp
C++
src/graph/peered/Nodes.cpp
ragedb/ragedb
0470f4cb154ce551ddb920453f2ea8467dbc4857
[ "Apache-2.0" ]
58
2021-07-08T14:20:54.000Z
2022-03-31T08:20:39.000Z
src/graph/peered/Nodes.cpp
ragedb/ragedb
0470f4cb154ce551ddb920453f2ea8467dbc4857
[ "Apache-2.0" ]
15
2021-07-29T14:37:57.000Z
2022-03-31T04:22:36.000Z
src/graph/peered/Nodes.cpp
ragedb/ragedb
0470f4cb154ce551ddb920453f2ea8467dbc4857
[ "Apache-2.0" ]
2
2021-07-29T14:24:57.000Z
2021-09-08T10:14:52.000Z
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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 "../Shard.h" namespace ragedb { seastar::future<uint64_t> Shard::NodeAddEmptyPeered(const std::string &type, const std::string &key) { uint16_t node_shard_id = CalculateShardId(type, key); uint16_t type_id = node_types.getTypeId(type); // The node type exists, so continue on if (type_id > 0) { return container().invoke_on(node_shard_id, [type_id, key](Shard &local_shard) { return local_shard.NodeAddEmpty(type_id, key); }); } // The node type needs to be set by Shard 0 and propagated return container().invoke_on(0, [node_shard_id, type, key, this] (Shard &local_shard) { return local_shard.NodeTypeInsertPeered(type).then([node_shard_id, type, key, this] (uint16_t node_type_id) { return container().invoke_on(node_shard_id, [node_type_id, key](Shard &local_shard) { return local_shard.NodeAddEmpty(node_type_id, key); }); }); }); } seastar::future<uint64_t> Shard::NodeAddPeered(const std::string &type, const std::string &key, const std::string &properties) { uint16_t node_shard_id = CalculateShardId(type, key); uint16_t node_type_id = node_types.getTypeId(type); // The node type exists, so continue on if (node_type_id > 0) { return container().invoke_on(node_shard_id, [node_type_id, key, properties](Shard &local_shard) { return local_shard.NodeAdd(node_type_id, key, properties); }); } // The node type needs to be set by Shard 0 and propagated return container().invoke_on(0, [node_shard_id, type, key, properties, this](Shard &local_shard) { return local_shard.NodeTypeInsertPeered(type).then([node_shard_id, key, properties, this](uint16_t node_type_id) { return container().invoke_on(node_shard_id, [node_type_id, key, properties](Shard &local_shard) { return local_shard.NodeAdd(node_type_id, key, properties); }); }); }); } seastar::future<uint64_t> Shard::NodeGetIDPeered(const std::string &type, const std::string &key) { uint16_t node_shard_id = CalculateShardId(type, key); return container().invoke_on(node_shard_id, [type, key] (Shard &local_shard) { return local_shard.NodeGetID(type, key); }); } seastar::future<Node> Shard::NodeGetPeered(const std::string &type, const std::string &key) { uint16_t node_shard_id = CalculateShardId(type, key); return container().invoke_on(node_shard_id, [type, key](Shard &local_shard) { return local_shard.NodeGet(type, key); }); } seastar::future<Node> Shard::NodeGetPeered(uint64_t id) { uint16_t node_shard_id = CalculateShardId(id); return container().invoke_on(node_shard_id, [id](Shard &local_shard) { return local_shard.NodeGet(id); }); } seastar::future<std::vector<Node>> Shard::NodesGetPeered(const std::vector<uint64_t> &ids) { std::map<uint16_t, std::vector<uint64_t>> sharded_nodes_ids; for (int i = 0; i < cpus; i++) { sharded_nodes_ids.insert({i, std::vector<uint64_t>() }); } for (auto id : ids) { sharded_nodes_ids[CalculateShardId(id)].emplace_back(id); } std::vector<seastar::future<std::vector<Node>>> futures; for (auto const& [their_shard, grouped_node_ids] : sharded_nodes_ids ) { auto future = container().invoke_on(their_shard, [grouped_node_ids = grouped_node_ids] (Shard &local_shard) { return local_shard.NodesGet(grouped_node_ids); }); futures.push_back(std::move(future)); } auto p = make_shared(std::move(futures)); return seastar::when_all_succeed(p->begin(), p->end()).then([p] (const std::vector<std::vector<Node>>& results) { std::vector<Node> combined; for(const std::vector<Node>& sharded : results) { combined.insert(std::end(combined), std::begin(sharded), std::end(sharded)); } return combined; }); } seastar::future<bool> Shard::NodeRemovePeered(const std::string& type, const std::string& key) { uint16_t node_shard_id = CalculateShardId(type, key); return container().invoke_on(node_shard_id, [type, key] (Shard &local_shard) { return local_shard.NodeGetID(type, key); }).then([this] (uint64_t external_id) { return NodeRemovePeered(external_id); }); } seastar::future<bool> Shard::NodeRemovePeeredIncoming(uint16_t node_shard_id, uint64_t external_id) { return container().invoke_on(node_shard_id, [external_id] (Shard &local_shard) { return local_shard.NodeRemoveGetIncoming(external_id); }) .then([external_id, this] (auto sharded_grouped_rels) mutable { std::vector<seastar::future<bool>> futures; for (auto const& [their_shard, grouped_rels] : sharded_grouped_rels ) { auto future = container().invoke_on(their_shard, [external_id, grouped_rels = std::move(grouped_rels)] (Shard &local_shard) { return local_shard.NodeRemoveDeleteIncoming(external_id, grouped_rels); }); futures.push_back(std::move(future)); } auto p = make_shared(std::move(futures)); return seastar::when_all(p->begin(), p->end()) .then([p] (std::vector<seastar::future<bool>> results) { if (std::any_of(results.begin(), results.end(), [] (auto& f) { return f.failed(); })) { return seastar::make_ready_future<bool>(false); } return seastar::make_ready_future<bool>(true); }); }); } seastar::future<bool> Shard::NodeRemovePeeredOutgoing(uint16_t node_shard_id, uint64_t external_id) { return container().invoke_on(node_shard_id, [external_id] (Shard &local_shard) { return local_shard.NodeRemoveGetOutgoing(external_id); }).then([external_id, this] (auto sharded_grouped_rels) { std::vector<seastar::future<bool>> futures; for (auto const& [their_shard, grouped_rels] : sharded_grouped_rels ) { auto future = container().invoke_on(their_shard, [external_id, grouped_rels = grouped_rels] (Shard &local_shard) { return local_shard.NodeRemoveDeleteOutgoing(external_id, grouped_rels); }); futures.push_back(std::move(future)); } auto p = make_shared(std::move(futures)); return seastar::when_all(p->begin(), p->end()) .then([p] (std::vector<seastar::future<bool>> results) { if (std::any_of(results.begin(), results.end(), [] (auto& f) { return f.failed(); })) { return seastar::make_ready_future<bool>(false); } return seastar::make_ready_future<bool>(true); }); }); } seastar::future<bool> Shard::NodeRemovePeered(uint64_t external_id) { uint16_t node_shard_id = CalculateShardId(external_id); return container().invoke_on(node_shard_id, [external_id](Shard &local_shard) { return local_shard.ValidNodeId(external_id); }).then([node_shard_id, external_id, this] (bool valid) { if (valid) { return NodeRemovePeeredIncoming(node_shard_id, external_id) .then([node_shard_id, external_id, this] (bool valid2) { if (valid2) { return NodeRemovePeeredOutgoing(node_shard_id, external_id); } return seastar::make_ready_future<bool>(false); }).then([external_id, node_shard_id, this] (auto valid3) { if (valid3) { return container().invoke_on(node_shard_id, [external_id, node_shard_id] (Shard &local_shard) { return local_shard.NodeRemove(external_id); }); } return seastar::make_ready_future<bool>(false); }); } return seastar::make_ready_future<bool>(false); }); } seastar::future<uint16_t> Shard::NodeGetTypeIdPeered(uint64_t id) { return seastar::make_ready_future<uint16_t>(NodeGetTypeId(id)); } seastar::future<std::string> Shard::NodeGetTypePeered(uint64_t id) { uint16_t node_shard_id = CalculateShardId(id); return container().invoke_on(node_shard_id, [id](Shard &local_shard) { return local_shard.NodeGetType(id); }); } seastar::future<std::string> Shard::NodeGetKeyPeered(uint64_t id) { uint16_t node_shard_id = CalculateShardId(id); return container().invoke_on(node_shard_id, [id](Shard &local_shard) { return local_shard.NodeGetKey(id); }); } seastar::future<std::any> Shard::NodePropertyGetPeered(const std::string &type, const std::string &key, const std::string &property) { uint16_t node_shard_id = CalculateShardId(type, key); return container().invoke_on(node_shard_id, [type, key, property](Shard &local_shard) { return local_shard.NodePropertyGet(type, key, property); }); } seastar::future<std::any> Shard::NodePropertyGetPeered(uint64_t id, const std::string &property) { uint16_t node_shard_id = CalculateShardId(id); return container().invoke_on(node_shard_id, [id, property](Shard &local_shard) { return local_shard.NodePropertyGet(id, property); }); } seastar::future<bool> Shard::NodePropertySetPeered(const std::string& type, const std::string& key, const std::string& property, const std::any& value) { uint16_t node_shard_id = CalculateShardId(type, key); return container().invoke_on(node_shard_id, [type, key, property, value](Shard &local_shard) { return local_shard.NodePropertySet(type, key, property, value); }); } seastar::future<bool> Shard::NodePropertySetPeered(uint64_t id, const std::string& property, const std::any& value) { uint16_t node_shard_id = CalculateShardId(id); return container().invoke_on(node_shard_id, [id, property, value](Shard &local_shard) { return local_shard.NodePropertySet(id, property, value); }); } seastar::future<bool> Shard::NodePropertySetFromJsonPeered(const std::string &type, const std::string &key, const std::string &property, const std::string &value) { uint16_t node_shard_id = CalculateShardId(type, key); return container().invoke_on(node_shard_id, [type, key, property, value](Shard &local_shard) { return local_shard.NodePropertySetFromJson(type, key, property, value); }); } seastar::future<bool> Shard::NodePropertySetFromJsonPeered(uint64_t id, const std::string &property, const std::string &value) { uint16_t node_shard_id = CalculateShardId(id); return container().invoke_on(node_shard_id, [id, property, value](Shard &local_shard) { return local_shard.NodePropertySetFromJson(id, property, value); }); } seastar::future<bool> Shard::NodePropertyDeletePeered(const std::string &type, const std::string &key, const std::string &property) { uint16_t node_shard_id = CalculateShardId(type, key); return container().invoke_on(node_shard_id, [type, key, property](Shard &local_shard) { return local_shard.NodePropertyDelete(type, key, property); }); } seastar::future<bool> Shard::NodePropertyDeletePeered(uint64_t id, const std::string &property) { uint16_t node_shard_id = CalculateShardId(id); return container().invoke_on(node_shard_id, [id, property](Shard &local_shard) { return local_shard.NodePropertyDelete(id, property); }); } seastar::future<std::map<std::string, std::any>> Shard::NodePropertiesGetPeered(const std::string& type, const std::string& key) { uint16_t node_shard_id = CalculateShardId(type, key); return container().invoke_on(node_shard_id, [type, key](Shard &local_shard) { return local_shard.NodePropertiesGet(type, key); }); } seastar::future<std::map<std::string, std::any>> Shard::NodePropertiesGetPeered(uint64_t id) { uint16_t node_shard_id = CalculateShardId(id); return container().invoke_on(node_shard_id, [id](Shard &local_shard) { return local_shard.NodePropertiesGet(id); }); } seastar::future<bool> Shard::NodePropertiesSetFromJsonPeered(const std::string &type, const std::string &key, const std::string &value) { uint16_t node_shard_id = CalculateShardId(type, key); return container().invoke_on(node_shard_id, [type, key, value](Shard &local_shard) { return local_shard.NodePropertiesSetFromJson(type, key, value); }); } seastar::future<bool> Shard::NodePropertiesSetFromJsonPeered(uint64_t id, const std::string &value) { uint16_t node_shard_id = CalculateShardId(id); return container().invoke_on(node_shard_id, [id, value](Shard &local_shard) { return local_shard.NodePropertiesSetFromJson(id, value); }); } seastar::future<bool> Shard::NodePropertiesResetFromJsonPeered(const std::string &type, const std::string &key, const std::string &value) { uint16_t node_shard_id = CalculateShardId(type, key); return container().invoke_on(node_shard_id, [type, key, value](Shard &local_shard) { return local_shard.NodePropertiesResetFromJson(type, key, value); }); } seastar::future<bool> Shard::NodePropertiesResetFromJsonPeered(uint64_t id, const std::string &value) { uint16_t node_shard_id = CalculateShardId(id); return container().invoke_on(node_shard_id, [id, value](Shard &local_shard) { return local_shard.NodePropertiesResetFromJson(id, value); }); } seastar::future<bool> Shard::NodePropertiesDeletePeered(const std::string &type, const std::string &key) { uint16_t node_shard_id = CalculateShardId(type, key); return container().invoke_on(node_shard_id, [type, key](Shard &local_shard) { return local_shard.NodePropertiesDelete(type, key); }); } seastar::future<bool> Shard::NodePropertiesDeletePeered(uint64_t id) { uint16_t node_shard_id = CalculateShardId(id); return container().invoke_on(node_shard_id, [id](Shard &local_shard) { return local_shard.NodePropertiesDelete(id); }); } }
45.15896
168
0.638592
[ "vector" ]
e15300348ba7215330857a67b377fb011fa42e77
6,206
cpp
C++
src/allegro_flare/profile_timer.cpp
MarkOates/allegro_flare
b454cb85eb5e43d19c23c0c6fd2dc11b96666ce7
[ "MIT" ]
25
2015-03-30T02:02:43.000Z
2019-03-04T22:29:12.000Z
src/allegro_flare/profile_timer.cpp
MarkOates/allegro_flare
b454cb85eb5e43d19c23c0c6fd2dc11b96666ce7
[ "MIT" ]
122
2015-04-01T08:15:26.000Z
2019-10-16T20:31:22.000Z
src/allegro_flare/profile_timer.cpp
MarkOates/allegro_flare
b454cb85eb5e43d19c23c0c6fd2dc11b96666ce7
[ "MIT" ]
4
2016-09-02T12:14:09.000Z
2018-11-23T20:38:49.000Z
#include <allegro_flare/profile_timer.h> #include <algorithm> #include <sstream> #include <stdio.h> #include <vector> #include <allegro5/allegro_color.h> #include <allegro5/allegro_primitives.h> #include <allegro5/allegro_ttf.h> namespace allegro_flare { #ifdef _MSC_VER #undef sprintf #define sprintf sprintf_s //#undef strcmp //#define strcmp strcmp_s #undef strcpy #define strcpy strcpy_s #endif ProfilerBuilder *ProfilerBuilder::dummy = NULL; #define MAX_TIMER_NAME_LEN 64 /* static int int_comp(int i1, int i2) { if (i1 == i2) return 0; if (i1 < i2) return -1; else return 1; } */ class profile_timer_class { public: char64_t name; PROFILE_TIMER_TIME_T start_time; PROFILE_TIMER_TIME_T stop_time; }; bool timerRecordPresidence(const profile_timer_class *a, const profile_timer_class *b) { return (strcmp(a->name, b->name)<0); } class Profiler { private: static Profiler *instance; public: static Profiler *get_instance() { if (!instance) { instance = new Profiler; bg_color = al_color_name("black"); bar_color = al_color_name("orange"); font_color = al_color_name("white"); limit_bar_color = al_color_name("lightblue"); font = al_create_builtin_font(); } return instance; } private: static ALLEGRO_COLOR bg_color, bar_color, font_color, limit_bar_color; static ALLEGRO_FONT *font; int num_timers; bool sorted; int create_timer(const char64_t name) { timer.push_back(new profile_timer_class()); timer.back()->start_time = 0; timer.back()->stop_time = 0; strcpy(timer.back()->name, name); num_timers++; std::sort(timer.begin(), timer.end(), timerRecordPresidence); sorted = true; return num_timers-1; } int linear_search(const char64_t name) { for (int i=0; i<timer.size(); i++) if (strcmp(timer[i]->name, name)==0) return i; return -1; } int binary_search(const char64_t name) { return linear_search(name); //TODO: /* int comp, first, last, mid; first = 0; last = timer.size(); while (first <= last) { mid = (first + last) / 2; // compute mid point. comp = strcmp(timer[mid]->name, name); if (comp < 0) first = mid + 1; // repeat search in top half. else if (comp > 0) last = mid - 1; // repeat search in bottom half. else return mid; // found it. return position } return -1; */ } int get_or_create_timer_index(const char64_t name) { int index = 0; // find the timer if (!sorted) index = linear_search(name); else index = binary_search(name); // if the timer hasn't been created yet, make one if (index == -1) index = create_timer(name); return index; } public: std::vector<profile_timer_class *> timer; Profiler() { num_timers = 0; timer.clear(); } void clear_timers() { for (auto &t : timer) delete t; timer.clear(); } void start_timer(const char64_t name) { PROFILE_TIMER_TIME_T time = (PROFILE_TIMER_TIME_T)al_get_time(); int index = get_or_create_timer_index(name); // set the start time timer[index]->start_time = time; timer[index]->stop_time = 0; } void stop_timer(const char64_t name, PROFILE_TIMER_TIME_T time_at) { // set the end time timer[get_or_create_timer_index(name)]->stop_time = time_at; } double get_duration(const char64_t name) { int index = get_or_create_timer_index(name); return timer[index]->stop_time - timer[index]->start_time; } static void draw(float x, float y) { float w = 300; float line_height = 25; float pad = 20; float h = Profiler::get_instance()->timer.size()*line_height + pad*2; PROFILE_TIMER_TIME_T duration = 0.0; int i=0; char time[32]; al_draw_filled_rounded_rectangle(x, y, x+w, y+h, 8, 8, bg_color); //if (!font) return; std::vector<profile_timer_class *>::iterator it = Profiler::get_instance()->timer.begin(); for ( ; it != get_instance()->timer.end(); ++it) { duration = (*it)->stop_time - (*it)->start_time; al_draw_filled_rectangle(x, y+pad+line_height*i+15, x+duration*10000, y+pad+line_height*i+20, al_color_name("orange")); al_draw_text(font, font_color, x+pad, y+pad+line_height*i, 0, (*it)->name); sprintf(time, "%f", duration*100); al_draw_text(font, font_color, x+pad+200, y+pad+line_height*i, 0, time); i++; } al_draw_line(x+ALLEGRO_BPS_TO_SECS(60)*10000, y, x+ALLEGRO_BPS_TO_SECS(60)*10000, y+h, limit_bar_color, 1.0); al_draw_line(x+ALLEGRO_BPS_TO_SECS(72)*10000, y, x+ALLEGRO_BPS_TO_SECS(72)*10000, y+h, limit_bar_color, 1.0); } }; Profiler *Profiler::instance = NULL; ALLEGRO_COLOR Profiler::bg_color, Profiler::bar_color, Profiler::font_color, Profiler::limit_bar_color; ALLEGRO_FONT *Profiler::font = NULL; void start_profile_timer(const char64_t name) { Profiler::get_instance()->start_timer(name); } void stop_profile_timer(const char64_t name, PROFILE_TIMER_TIME_T time_at) { Profiler::get_instance()->stop_timer(name, time_at); } void clear_all_profile_timers() { Profiler::get_instance()->clear_timers(); } PROFILE_TIMER_TIME_T get_profile_timer_length(const char64_t name) { return Profiler::get_instance()->get_duration(name); } void draw_profile_timer_graph(float x, float y) { Profiler::get_instance()->draw(x, y); } }
22.485507
131
0.585885
[ "vector" ]
e15593d7618631163c49c0e2f41c4dfafa1b5f65
6,587
cpp
C++
src/shape_detector/src/cylinder_computer.cpp
harrycomeon/ros_object_recognition
064d3cbac1ffc31cba48461ee08961f9da540a28
[ "MIT" ]
68
2018-09-25T13:46:29.000Z
2022-03-16T15:43:48.000Z
src/shape_detector/src/cylinder_computer.cpp
harrycomeon/ros_object_recognition
064d3cbac1ffc31cba48461ee08961f9da540a28
[ "MIT" ]
1
2019-02-05T05:18:24.000Z
2020-02-16T15:36:33.000Z
src/shape_detector/src/cylinder_computer.cpp
harrycomeon/ros_object_recognition
064d3cbac1ffc31cba48461ee08961f9da540a28
[ "MIT" ]
27
2018-11-02T06:31:43.000Z
2022-03-22T08:11:00.000Z
/** \file * \brief Implementation of the CylinderComputer class. */ // std. #include <algorithm> // min(), max() #include <exception> // Eigen. #include <Eigen/Dense> // Vector3d #include <Eigen/Geometry> // Quaternion #include <eigen_conversions/eigen_msg.h> // tf::quaternionEigenToMsg() // PCL. #include <pcl/common/centroid.h> // computeCentroid() #include <pcl/filters/project_inliers.h> // ProjectInliers #include <pcl/PointIndices.h> #include <pcl/filters/extract_indices.h> #include <pcl_msgs/ModelCoefficients.h> #include <pcl/sample_consensus/model_types.h> // ROS. #include <geometry_msgs/Point.h> #include <geometry_msgs/Quaternion.h> // object_detection_*. #include <object_detection_3d_msgs/DetectedObject3D.h> #include <object_detection_3d/pcl_types.h> // Headers of this package. #include <shape_detector/object_computer.h> using object_detection_3d_msgs::DetectedObject3D; using object_detection_3d::PointT; using object_detection_3d::PointCloudT; using namespace std; namespace { /** \brief Extract points with given indices from given cloud. * \param[in] cloud Cloud from which points are extracted. * \param[in] indices Indices of the points that are extracted from the * input cloud. * \return Cloud containing the extracted points. */ inline PointCloudT::Ptr extractIndexedPoints( const PointCloudT::ConstPtr& cloud, const pcl::PointIndices::ConstPtr& indices) { pcl::ExtractIndices<PointT> extractor; extractor.setInputCloud(cloud); extractor.setIndices(indices); extractor.setNegative(false); PointCloudT::Ptr indexed_points {new PointCloudT}; extractor.filter(*indexed_points); return indexed_points; } inline PointCloudT::Ptr createPointCloudFromPoint(const PointT& pt) { PointCloudT::Ptr cloud {new PointCloudT}; cloud->points.push_back(pt); return cloud; } inline PointCloudT::Ptr projectPointCloudOnLine( const PointCloudT::ConstPtr& cloud, const pcl::ModelCoefficients::ConstPtr& line_model) { pcl::ProjectInliers<PointT> projection; projection.setInputCloud(cloud); projection.setModelType(pcl::SACMODEL_LINE); projection.setModelCoefficients(line_model); PointCloudT::Ptr projected_cloud {new PointCloudT}; projection.filter(*projected_cloud); return projected_cloud; } inline pcl::ModelCoefficients::Ptr computeCylinderAxisModel( const pcl::ModelCoefficients::ConstPtr& cylinder_model) { constexpr int num_line_coefficients {6}; pcl::ModelCoefficients::Ptr axis_model {new pcl::ModelCoefficients}; axis_model->values.resize(num_line_coefficients); for (int i {0}; i < num_line_coefficients; ++i) axis_model->values[i] = cylinder_model->values.at(i); return axis_model; } inline PointT projectPointOnLine( const PointT& pt, const pcl::ModelCoefficients::ConstPtr& line_model) { PointCloudT::Ptr cloud_containing_pt {createPointCloudFromPoint(pt)}; PointCloudT::Ptr projected_cloud_containing_pt {projectPointCloudOnLine( cloud_containing_pt, line_model)}; return projected_cloud_containing_pt->points[0]; } inline Eigen::Vector3d computeCylinderDirection( const pcl::ModelCoefficients::ConstPtr& cylinder_model) { return Eigen::Vector3d { cylinder_model->values.at(3), cylinder_model->values.at(4), cylinder_model->values.at(5)}; } inline Eigen::Vector3d convertPCLPointToEigenVector(const PointT& point) { return Eigen::Vector3d {point.x, point.y, point.z}; } inline geometry_msgs::Point convertPCLPointToGeometryPoint( const PointT& pcl_pt) { geometry_msgs::Point geom_pt; geom_pt.x = pcl_pt.x; geom_pt.y = pcl_pt.y; geom_pt.z = pcl_pt.z; return geom_pt; } inline Eigen::Vector3d normalizeVector(const Eigen::Vector3d& vec) { return vec / vec.squaredNorm(); } /* Compute the distance from pt1 to pt2, projected onto the given direction * vector. The distance is positive, if the distance vector (pt2-pt1) points * into the same direction as 'direction' does. * The returned length is the real length, multiplied by the length of * the 'direction' vector. */ inline double computeSignedProjectedDistance(const PointT& pt1, const PointT& pt2, const Eigen::Vector3d& direction) { Eigen::Vector3d vec1 {convertPCLPointToEigenVector(pt1)}; Eigen::Vector3d vec2 {convertPCLPointToEigenVector(pt2)}; Eigen::Vector3d distance_vec {vec2 - vec1}; return distance_vec.dot(direction); } } // anonymous ns namespace shape_detector { const Eigen::Vector3d CylinderComputer::reference_direction {0., 0., 1.}; DetectedObject3D CylinderComputer::computeObject() { // Extract points that are part of the cylinder. inlier_points_ = extractIndexedPoints(cloud_, inlier_indices_); // Compute cylinder/object. DetectedObject3D obj; obj.box.pose.position = computeCentroid(); obj.box.pose.orientation = computeOrientation(); obj.box.width = obj.box.depth = computeDiameter(); obj.box.height = computeHeight(); return obj; } geometry_msgs::Point CylinderComputer::computeCentroid() const { PointT cloud_centroid; if (pcl::computeCentroid(*inlier_points_, cloud_centroid) == 0) throw runtime_error {"CylinderComputer::computeCentroid: no inlier points"}; pcl::ModelCoefficients::Ptr axis_model { computeCylinderAxisModel(model_coefficients_)}; PointT cylinder_centroid {projectPointOnLine(cloud_centroid, axis_model)}; return convertPCLPointToGeometryPoint(cylinder_centroid); } geometry_msgs::Quaternion CylinderComputer::computeOrientation() const { const Eigen::Vector3d direction {computeCylinderDirection(model_coefficients_)}; Eigen::Quaterniond eigen_quaternion {Eigen::Quaterniond::FromTwoVectors( reference_direction, direction)}; geometry_msgs::Quaternion geom_quaternion; tf::quaternionEigenToMsg(eigen_quaternion, geom_quaternion); return geom_quaternion; } double CylinderComputer::computeDiameter() const { return 2 * model_coefficients_->values.at(6); } double CylinderComputer::computeHeight() const { Eigen::Vector3d direction {computeCylinderDirection(model_coefficients_)}; direction = normalizeVector(direction); PointT reference_point {inlier_points_->points.at(0)}; double min_distance {0.}; double max_distance {0.}; for (const auto& pt : inlier_points_->points) { double distance {computeSignedProjectedDistance(reference_point, pt, direction)}; min_distance = min(min_distance, distance); max_distance = max(max_distance, distance); } return max_distance - min_distance; } } // shape_detector
27.445833
85
0.756794
[ "geometry", "object", "vector" ]
e15657703a0c570b516936b2c6715be26bde5c8d
2,162
cpp
C++
code_reading/oceanbase-master/src/sql/engine/expr/ob_expr_lnnvl.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
null
null
null
code_reading/oceanbase-master/src/sql/engine/expr/ob_expr_lnnvl.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
null
null
null
code_reading/oceanbase-master/src/sql/engine/expr/ob_expr_lnnvl.cpp
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
1
2020-10-18T12:59:31.000Z
2020-10-18T12:59:31.000Z
/** * Copyright (c) 2021 OceanBase * OceanBase CE is licensed under Mulan PubL v2. * You can use this software according to the terms and conditions of the Mulan PubL v2. * You may obtain a copy of Mulan PubL v2 at: * http://license.coscl.org.cn/MulanPubL-2.0 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PubL v2 for more details. */ #define USING_LOG_PREFIX SQL_ENG #include <string.h> #include "sql/parser/ob_item_type.h" #include "sql/engine/expr/ob_expr_lnnvl.h" #include "share/object/ob_obj_cast.h" //#include "sql/engine/expr/ob_expr_promotion_util.h" using namespace oceanbase::common; using namespace oceanbase::sql; namespace oceanbase { namespace sql {} } // namespace oceanbase ObExprFuncLnnvl::ObExprFuncLnnvl(ObIAllocator& alloc) : ObFuncExprOperator(alloc, T_FUN_SYS_LNNVL, N_LNNVL, 1, NOT_ROW_DIMENSION) {} ObExprFuncLnnvl::~ObExprFuncLnnvl() {} int ObExprFuncLnnvl::calc_result1(ObObj& result, const ObObj& input, ObExprCtx& expr_ctx) const { int ret = OB_SUCCESS; if (OB_UNLIKELY(NULL == expr_ctx.calc_buf_)) { _OB_LOG(WARN, "varchar buffer not init"); ret = OB_NOT_INIT; } else if (input.is_null()) { result.set_bool(true); } else { TYPE_CHECK(input, ObTinyIntType); int8_t tinyint_val = input.get_tinyint(); if (tinyint_val == 0) { result.set_bool(true); } else { result.set_bool(false); } } return ret; } int ObExprFuncLnnvl::cg_expr(ObExprCGCtx&, const ObRawExpr&, ObExpr& rt_expr) const { int ret = OB_SUCCESS; CK(1 == rt_expr.arg_cnt_); rt_expr.eval_func_ = eval_lnnvl; return ret; } int ObExprFuncLnnvl::eval_lnnvl(const ObExpr& expr, ObEvalCtx& ctx, ObDatum& expr_datum) { int ret = OB_SUCCESS; ObDatum* arg = NULL; if (OB_FAIL(expr.eval_param_value(ctx, arg))) { LOG_WARN("evaluate parameters failed", K(ret)); } else if (arg->is_null()) { expr_datum.set_bool(true); } else { expr_datum.set_bool(!arg->get_tinyint()); } return ret; }
28.826667
95
0.712766
[ "object" ]
e15a028d40b92a252c2796451d9a23d4470cce3b
15,860
cpp
C++
src/fasito/fasito.cpp
citrixrep/Pylon-Segwit
395e71d5be0fde8a1cf6e2b49b1ff75f5d19f75f
[ "MIT" ]
null
null
null
src/fasito/fasito.cpp
citrixrep/Pylon-Segwit
395e71d5be0fde8a1cf6e2b49b1ff75f5d19f75f
[ "MIT" ]
null
null
null
src/fasito/fasito.cpp
citrixrep/Pylon-Segwit
395e71d5be0fde8a1cf6e2b49b1ff75f5d19f75f
[ "MIT" ]
null
null
null
// Copyright (c) 2017 The Pyloncoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "util.h" #include "pubkey.h" #include "utilstrencodings.h" #include "SerialConnection.h" #include "primitives/block.h" #include "poc.h" #include "init.h" #include "fasito.h" #include <secp256k1.h> #include <openssl/ssl.h> #include <iostream> #include <stdint.h> #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith() #define FASITO_DEBUG 0 CFasito fasito; static string bin2hex(const uint8_t *buf, const size_t len) { size_t i; char c[3]; string res; for (i = 0; i < len; i++) { sprintf(c, "%02x", buf[i]); res.append(c); } return res; } bool CreateNonceWithFasito(const uint256& hashData, const uint8_t nKey, unsigned char *pPrivateData, CSchnorrNonce& noncePublic, const CSchnorrPubKey& pubKey) { if (!fasito.mapKeys.count(nKey) || fasito.mapKeys[nKey].pubKey != pubKey) { LogPrintf("CreateNonceWithFasito : public key in Fasito does not match cvnInfo in blockchain: %s != %s\n", fasito.mapKeys[nKey].pubKey.ToString(), pubKey.ToString()); return false; } CHashWriter hasher(SER_GETHASH, 0); hasher << GetTimeMillis() << string("we need random nonces") << rand(); std::stringstream s; s << strprintf("NONCE %d %s %s", nKey, bin2hex(&hashData.begin()[0], 32), bin2hex(&hasher.GetHash().begin()[0], 32)); vector<string> res; try { if (!fasito.sendAndReceive(s.str(), res)) { LogPrintf("CreateNonceWithFasito : could not create nonce pair: %s\n", (!res.empty() ? res[0] : "error not available")); return false; } int nHandle = atoi(res[0].substr(0,2).c_str()); *((uint8_t *)pPrivateData) = (uint8_t)nHandle; vector<uint8_t> pubNonce = ParseHex(res[0].substr(3)); memcpy(&noncePublic.begin()[0], &pubNonce.begin()[0], 64); } catch(const std::exception &e) { LogPrintf("failed to send NONCE command: %s\n", e.what()); return false; } #if FASITO_DEBUG LogPrintf("CreateNonceWithFasito : OK\n Hash: %s\n pubk: %s\n nKey: %d\n sig: %s\n", hashData.ToString(), fasito.mapKeys[nKey].pubKey.ToString(), nKey, noncePublic.ToString()); #endif return true; } bool CvnSignWithFasito(const uint256 &hashToSign, const uint8_t nKey, CSchnorrSig& signature) { if (!fasito.mapKeys.count(nKey)) { LogPrintf("CvnSignWithFasito : public key #%d not found\n", nKey); return false; } std::stringstream s; s << strprintf("SCHNORR %d %s", nKey, bin2hex(&hashToSign.begin()[0], 32)); vector<string> res; vector<uint8_t> vSig; try { if (!fasito.sendAndReceive(s.str(), res)) { LogPrintf("CvnSignWithFasito : could not sign hash: %s\n", (!res.empty() ? res[0] : "error not available")); return false; } vSig = ParseHex(res[0]); memcpy(&signature.begin()[0], &vSig.begin()[0], 64); } catch(const std::exception &e) { LogPrintf("failed to send SCHNORR command: %s\n", e.what()); return false; } if (!CvnVerifySignature(hashToSign, signature, fasito.mapKeys[nKey].pubKey)) { LogPrintf("CvnSignWithFasito : created invalid signature\n"); return false; } #if FASITO_DEBUG LogPrintf("CvnSignWithFasito : OK\n Hash: %s\n pubk: %s\n nKey: %d\n sig: %s\nrawsig: %s\nhexstr: %s\n", hashToSign.ToString(), fasito.mapKeys[nKey].pubKey.ToString(), nKey, signature.ToString(), res[0], HexStr(vSig)); #endif return true; } bool CvnSignPartialWithFasito(const uint256& hashToSign, const uint8_t nKey, const CSchnorrPubKey& sumPublicNoncesOthers, CSchnorrSig& signature, const int nPoolOffset) { if (!fasito.mapKeys.count(nKey)) { LogPrintf("CvnSignPartialWithFasito : public key #%d not found.\n", nKey); return false; } uint8_t nHandle = fasito.vNonceHandles[nPoolOffset]; std::stringstream s; s << strprintf("PARTSIG %d %d %s %s", nKey, nHandle, bin2hex(&hashToSign.begin()[0], 32), bin2hex(&sumPublicNoncesOthers.begin()[0], 64)); vector<string> res; try { if (!fasito.sendAndReceive(s.str(), res)) { LogPrintf("CvnSignPartialWithFasito : could not partial sign hash: %s\nCOMMAND: %s\n", (!res.empty() ? res[0] : "error not available"), s.str()); return false; } vector<uint8_t> vSig = ParseHex(res[0]); memcpy(&signature.begin()[0], &vSig.begin()[0], 64); } catch(const std::exception &e) { LogPrintf("failed to send PARTSIG command: %s\n", e.what()); return false; } #if FASITO_DEBUG LogPrintf("CvnSignPartialWithFasito : OK\n Hash: %s\nsigner: 0x%08x\n sum: %s\n sig: %s\n", hashToSign.ToString(), signature.nSignerId, sumPublicNoncesOthers.ToString(), signature.ToString()); #endif return true; } bool AdminSignPartialWithFasito(const uint256& hashToSign, const uint8_t nKey, const CSchnorrPubKey& sumPublicNoncesOthers, CSchnorrSig& signature, const uint8_t nHandle) { if (!fasito.mapKeys.count(nKey)) { LogPrintf("%s : public key #%d not found.\n", __func__, nKey); return false; } std::stringstream s; s << strprintf("PARTSIG %d %d %s %s", nKey, nHandle, bin2hex(&hashToSign.begin()[0], 32), bin2hex(&sumPublicNoncesOthers.begin()[0], 64)); vector<string> res; try { if (!fasito.sendAndReceive(s.str(), res)) { LogPrintf("%s : could not partial sign hash: %s\nCOMMAND: %s\n", __func__, (!res.empty() ? res[0] : "error not available"), s.str()); return false; } vector<uint8_t> vSig = ParseHex(res[0]); memcpy(&signature.begin()[0], &vSig.begin()[0], 64); } catch(const std::exception &e) { LogPrintf("%s : failed to send PARTSIG command: %s\n", __func__, e.what()); return false; } #if FASITO_DEBUG LogPrintf("%s : OK\n Hash: %s\nsigner: 0x%08x\n sum: %s\n sig: %s\n", __func__, hashToSign.ToString(), signature.nSignerId, sumPublicNoncesOthers.ToString(), signature.ToString()); #endif return true; } string CFasitoKey::ToString() const { std::stringstream s; s << strprintf("CFasitoKey(cvnId=0x%08x, CFasitoKeyStatus=%u, nKeyIndex=%u, protected=%S) : %s", nCvnId, status, nKeyIndex, (fProtected ? "true" : "false"), pubKey.ToString() ); return s.str(); } bool CFasito::login(const string& strPassword, string &strError) { if (!fInitialized) return false; if (fLoggedIn) return true; fLoggedIn = false; vector<string> res; try { if (!fasito.sendAndReceive("LOGIN " + strPassword, res)) { strError = !res.empty() ? res[0] : "error not available"; return false; } } catch(const std::exception &e) { strprintf(strError, "failed to send login command: %s", e.what()); return false; } fLoggedIn = true; return true; } bool CFasito::logout() { if (!fInitialized) return false; if (!fLoggedIn) return true; try { fLoggedIn = false; LogPrintf("logging out from Fasito.\n"); if (fasito.sendCommand("LOGOUT")) return true; else LogPrintf("Could not logout from Fasito\n"); } catch(const std::exception &e) { LogPrintf("failed to send login command: %s\n", e.what()); } fLoggedIn = true; return false; } void CFasito::emtpyInputBuffer() { setTimeout(boost::posix_time::millisec(200)); writeString("\r"); try { while (true) { readStringUntil("\r\n"); } } catch(const std::exception &e) { } } /* Serial number : 012345678999 Token status : CONFIGURED Protection status : 0x01100010 Config version : 1 Config checksum : 1234 User PIN : SET (tries left: 3) Key #0 : 0x70000001 (CONFIGURED) Key #1 : 0x70000002 (CONFIGURED) Key #2 : 0x00000000 (SEEDED) Key #3 : 0x00000000 (SEEDED) Key #4 : 0x00000000 (SEEDED) Key #5 : 0x00000000 (SEEDED) Key #6 : 0x00000000 (SEEDED) Key #7 : 0x00000000 (CONFIGURED, protected) */ #define VALUE_OFFSET 20 void CFasito::open(const string &devname) { LOCK(cs_connection); SerialConnection::open(devname, 230400); emtpyInputBuffer(); int i = 0; vector<string> res; if (!sendAndReceive("INFO", res)) { LogPrintf("CFasito::open : could not get device info: %s\n", (!res.empty() ? res[0] : "error not available")); fInitialized = false; return; } strFasitoVersion = res[i++].substr(VALUE_OFFSET); strSerialNumber = res[i++].substr(VALUE_OFFSET); strTokenStatus = res[i++].substr(VALUE_OFFSET); strProtectionStatus = res[i++].substr(VALUE_OFFSET); strConfigVersion = res[i++].substr(VALUE_OFFSET); strConfigChecksum = res[i++].substr(VALUE_OFFSET); nNoncePoolSize = atoi(res[i++].substr(VALUE_OFFSET).c_str()); ++i; strPinStatus = res[i++].substr(VALUE_OFFSET); ++i; int nKey = 0; while (1) { string line = res[i++]; if (!boost::algorithm::starts_with(line, "Key #")) break; string keyStatus = line.substr(VALUE_OFFSET); CFasitoKey key; stringstream ss; ss << hex << keyStatus.substr(0, 10); ss >> key.nCvnId; string status = keyStatus.substr(12, keyStatus.length() - 13); if (status == "EMPTY") key.status = EMPTY; else if (status == "SEEDED") key.status = SEEDED; else if (status == "CONFIGURED") key.status = CONFIGURED; else if (status == "CONFIGURED, protected") { key.status = CONFIGURED; key.fProtected = true; } else LogPrintf("unknown status for Key #%d: %s\n", nKey, status); key.nKeyIndex = nKey++; mapKeys[key.nKeyIndex] = key; } fInitialized = true; } void CFasito::close() { LOCK(cs_connection); if (fLoggedIn) logout(); if (fInitialized) SerialConnection::close(); fInitialized = false; } static void RetrievePubKeys() { string strGetPubKey = "GETPBKY #"; BOOST_FOREACH(PAIRTYPE(const uint8_t, CFasitoKey) &entry, fasito.mapKeys) { CFasitoKey& k = entry.second; if (k.status == CONFIGURED && !k.fProtected) { strGetPubKey[8] = '0' + (char)k.nKeyIndex; vector<string> res; if (!fasito.sendAndReceive(strGetPubKey, res)) { LogPrintf("RetrievePubKeys : could not retrieve public key: %s\n", (!res.empty() ? res[0] : "error not available")); continue; } vector<uint8_t> derKey = ParseHex(res[0]); CPubKey testKey(derKey); if (!testKey.IsFullyValid()) { LogPrintf("Fasito key #%d is invalid: %s\n", k.nKeyIndex, res[0]); continue; } k.pubKey = CSchnorrPubKeyDER(res[0]); LogPrint("fasito", "public key #%d: %s\n", k.nKeyIndex, k.ToString()); } } } bool InitFasito(const string& strPassword, string& strError) { const string strDevice = GetArg("-fasitodevice", "/dev/ttyACM0"); try { fasito.open(strDevice); fasito.setTimeout(boost::posix_time::seconds(2)); LogPrintf("detected Fasito %s, serial number: %s, user-PIN status: %s, protection status: %s\n", fasito.strFasitoVersion, fasito.strSerialNumber, fasito.strPinStatus, fasito.strProtectionStatus); if (fasito.strTokenStatus != "CONFIGURED") { strError = "Fasito not configured"; return false; } if (boost::algorithm::starts_with(fasito.strPinStatus, "LOCKED")) { strError = "Fasito is locked"; return false; } size_t nPassLen = strPassword.length(); if (strPassword.empty()) { strError = "no PIN supplied"; return false; } if (nPassLen != 6) { strError = "invalid PIN length"; return false; } if (!fasito.login(strPassword, strError)) { return false; } /* Retrieve the public keys */ RetrievePubKeys(); } catch (const std::exception& e) { strError = "could not open device: " + strDevice; if (fasito.fInitialized) fasito.close(); return false; } return true; } uint32_t InitCVNWithFasito(const string &strFasitoPassword) { string strError; if (!InitFasito(strFasitoPassword, strError)) { LogPrintf("%s: %s\n", __func__, strError); return 0; } uint32_t nKeyIndex = GetArg("-fasitocvnkeyindex", 0); if (nKeyIndex > 6) { LogPrintf("invalid value for -fasitocvnkeyindex\n"); fasito.close(); return 0; } if (!fasito.mapKeys.count(nKeyIndex)) { LogPrintf("key #%d not found on Fasito\n", nKeyIndex); fasito.close(); return 0; } CFasitoKey &fasitoKeys = fasito.mapKeys[nKeyIndex]; if (fasitoKeys.status != CONFIGURED) { LogPrintf("key #%d not configured on Fasito\n", nKeyIndex); fasito.close(); return 0; } fasito.nCVNKeyIndex = nKeyIndex; CFasitoKey fKey = fasito.mapKeys[nKeyIndex]; vector<unsigned char> vPubKey; fKey.pubKey.GetPubKeyDER(vPubKey); LogPrintf("Using Fasito for CVN ID 0x%08x with public key %s\n", fKey.nCvnId, HexStr(vPubKey)); return fKey.nCvnId; } uint32_t InitChainAdminWithFasito(const string& strPassword, const uint32_t nKeyIndex, string &strError) { bool fWasInitialised = true; if (!fasito.fInitialized) { if (!InitFasito(strPassword, strError)) { LogPrintf("%s\n", strError); fasito.close(); return 0; } fWasInitialised = false; } if (nKeyIndex > 6) { strprintf(strError, "invalid value for adminkeyindex: %d", nKeyIndex); LogPrintf("%s\n", strError); if (!fWasInitialised) fasito.close(); return 0; } if (!fasito.mapKeys.count(nKeyIndex)) { strprintf(strError, "key #%d not found on Fasito", nKeyIndex); LogPrintf("%s\n", strError); if (!fWasInitialised) fasito.close(); return 0; } CFasitoKey &fasitoKeys = fasito.mapKeys[nKeyIndex]; if (fasitoKeys.status != CONFIGURED) { strprintf(strError, "key #%d not configured on Fasito", nKeyIndex); LogPrintf("%s\n", strError); if (!fWasInitialised) fasito.close(); return 0; } fasito.nADMINKeyIndex = nKeyIndex; CFasitoKey fKey = fasito.mapKeys[nKeyIndex]; vector<unsigned char> vPubKey; fKey.pubKey.GetPubKeyDER(vPubKey); LogPrintf("Using Fasito for ADMIN ID 0x%08x with public key %s\n", fKey.nCvnId, HexStr(vPubKey)); return fKey.nCvnId; } bool FasitoInitPrivKey(const CKey& privKey, const uint32_t nKeyIndex, const uint32_t nId) { std::stringstream strInitKeyCmd; strInitKeyCmd << strprintf("INITKEY %d 0x%08x %s", nKeyIndex, nId, bin2hex(&privKey.begin()[0], 32)); vector<string> res; if (!fasito.sendAndReceive(strInitKeyCmd.str(), res)) { LogPrintf("FasitoInitPrivKey : could not initialise private key: %s\n", (!res.empty() ? res[0] : "error not available")); return false; } return true; }
30.383142
174
0.600757
[ "vector" ]
e15a3839edf812ef6840e919e9a4db4fadaf8f1f
4,853
cc
C++
garnet/lib/vulkan/tests/vkprimer/common/vulkan_layer.cc
zhangpf/fuchsia-rs
903568f28ddf45f09157ead36d61b50322c9cf49
[ "BSD-3-Clause" ]
null
null
null
garnet/lib/vulkan/tests/vkprimer/common/vulkan_layer.cc
zhangpf/fuchsia-rs
903568f28ddf45f09157ead36d61b50322c9cf49
[ "BSD-3-Clause" ]
5
2020-09-06T09:02:06.000Z
2022-03-02T04:44:22.000Z
garnet/lib/vulkan/tests/vkprimer/common/vulkan_layer.cc
ZVNexus/fuchsia
c5610ad15208208c98693618a79c705af935270c
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2018 The Fuchsia 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 "vulkan_layer.h" #include <cstring> #include <iostream> #include <vector> #include "utils.h" namespace { static const std::vector<const char *> s_instance_layer_names = { #ifdef __Fuchsia__ "VK_LAYER_FUCHSIA_imagepipe_swapchain_fb", #endif "VK_LAYER_LUNARG_standard_validation", }; static VKAPI_ATTR VkBool32 VKAPI_CALL VulkanDebugCallback(VkDebugUtilsMessageSeverityFlagBitsEXT msg_severity, VkDebugUtilsMessageTypeFlagsEXT msg_type, const VkDebugUtilsMessengerCallbackDataEXT *callback_data, void *user_data) { std::cerr << "VKCB Layer Layer: " << callback_data->pMessage << std::endl; if (msg_type & VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT) { std::cout << "VKCB Type General" << std::endl; } if (msg_type & VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT) { std::cout << "VKCB Type Layer" << std::endl; } if (msg_type & VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT) { std::cout << "VKCB Type Performance" << std::endl; } if (msg_severity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT) { std::cout << "VKCB Severity Verbose" << std::endl; } if (msg_severity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT) { std::cout << "VKCB Severity Info" << std::endl; } if (msg_severity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) { std::cout << "VKCB Severity Warning" << std::endl; } if (msg_severity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) { std::cout << "VKCB Severity Error" << std::endl; } return VK_FALSE; } } // namespace VkResult CreateVulkanDebugUtilsMessenger( const VkInstance &instance, const VkDebugUtilsMessengerCreateInfoEXT *create_info, const VkAllocationCallbacks *allocator, VkDebugUtilsMessengerEXT *callback) { auto func = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr( instance, "vkCreateDebugUtilsMessengerEXT"); if (func != nullptr) { return func(instance, create_info, allocator, callback); } else { return VK_ERROR_EXTENSION_NOT_PRESENT; } } bool DestroyVulkanDebugUtilsMessenger(const VkInstance &instance, const VkDebugUtilsMessengerEXT &callback, const VkAllocationCallbacks *allocator) { auto func = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr( instance, "vkDestroyDebugUtilsMessengerEXT"); if (func != nullptr) { func(instance, callback, allocator); } else { RTN_MSG(false, "Unable to destroy debug messenger.\n"); } return true; } VulkanLayer::VulkanLayer(std::shared_ptr<VulkanInstance> instance) : initialized_(false), instance_(instance) {} bool VulkanLayer::Init() { if (initialized_) { RTN_MSG(false, "VulkanLayer is already initialized.\n"); } SetupDebugCallback(); initialized_ = true; return true; } VulkanLayer::~VulkanLayer() { if (initialized_) { DestroyVulkanDebugUtilsMessenger(instance_->instance(), callback_, nullptr); initialized_ = false; } } void VulkanLayer::AppendRequiredInstanceExtensions( std::vector<const char *> *extensions) { extensions->emplace_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME); } void VulkanLayer::AppendRequiredInstanceLayers( std::vector<const char *> *layers) { for (const auto &layer : s_instance_layer_names) { layers->emplace_back(layer); } } void VulkanLayer::AppendRequiredDeviceLayers( std::vector<const char *> *layers) { fprintf(stderr, "No required device layers.\n"); } bool VulkanLayer::CheckInstanceLayerSupport() { return !FindMatchingProperties(s_instance_layer_names, INSTANCE_LAYER_PROP, nullptr /* device */, nullptr /* layer */, nullptr /* missing_props */); } bool VulkanLayer::SetupDebugCallback() { VkDebugUtilsMessengerCreateInfoEXT create_info = { .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT, .messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT, .messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT, .pfnUserCallback = VulkanDebugCallback, }; if (CreateVulkanDebugUtilsMessenger(instance_->instance(), &create_info, nullptr, &callback_) != VK_SUCCESS) { RTN_MSG(false, "Failed to set up debug callback.\n"); } return true; }
33.937063
80
0.704719
[ "vector" ]
e15d8766fa6f981528eb59cb8ec8ebb5b98b2486
12,275
cpp
C++
src/printer/ast/ast_printer.cpp
guykatzz/CVC4_idl_lab
24cb1ed0c7c1445cbfb592a7ebcb454b70897d30
[ "BSL-1.0" ]
null
null
null
src/printer/ast/ast_printer.cpp
guykatzz/CVC4_idl_lab
24cb1ed0c7c1445cbfb592a7ebcb454b70897d30
[ "BSL-1.0" ]
null
null
null
src/printer/ast/ast_printer.cpp
guykatzz/CVC4_idl_lab
24cb1ed0c7c1445cbfb592a7ebcb454b70897d30
[ "BSL-1.0" ]
null
null
null
/********************* */ /*! \file ast_printer.cpp ** \verbatim ** Top contributors (to current version): ** Morgan Deters, Tim King, Liana Hadarean ** This file is part of the CVC4 project. ** Copyright (c) 2009-2016 by the authors listed in the file AUTHORS ** in the top-level source directory) and their institutional affiliations. ** All rights reserved. See the file COPYING in the top-level source ** directory for licensing information.\endverbatim ** ** \brief The pretty-printer interface for the AST output language ** ** The pretty-printer interface for the AST output language. **/ #include "printer/ast/ast_printer.h" #include <iostream> #include <string> #include <typeinfo> #include <vector> #include "expr/expr.h" // for ExprSetDepth etc.. #include "expr/node_manager_attributes.h" // for VarNameAttr #include "options/language.h" // for LANG_AST #include "printer/dagification_visitor.h" #include "smt/command.h" #include "smt_util/node_visitor.h" #include "theory/substitutions.h" using namespace std; namespace CVC4 { namespace printer { namespace ast { void AstPrinter::toStream(std::ostream& out, TNode n, int toDepth, bool types, size_t dag) const throw() { if(dag != 0) { DagificationVisitor dv(dag); NodeVisitor<DagificationVisitor> visitor; visitor.run(dv, n); const theory::SubstitutionMap& lets = dv.getLets(); if(!lets.empty()) { out << "(LET "; bool first = true; for(theory::SubstitutionMap::const_iterator i = lets.begin(); i != lets.end(); ++i) { if(! first) { out << ", "; } else { first = false; } toStream(out, (*i).second, toDepth, types, false); out << " := "; toStream(out, (*i).first, toDepth, types, false); } out << " IN "; } Node body = dv.getDagifiedBody(); toStream(out, body, toDepth, types); if(!lets.empty()) { out << ')'; } } else { toStream(out, n, toDepth, types); } } void AstPrinter::toStream(std::ostream& out, TNode n, int toDepth, bool types) const throw() { // null if(n.getKind() == kind::NULL_EXPR) { out << "null"; return; } // variable if(n.getMetaKind() == kind::metakind::VARIABLE) { string s; if(n.getAttribute(expr::VarNameAttr(), s)) { out << s; } else { out << "var_" << n.getId(); } if(types) { // print the whole type, but not *its* type out << ":"; n.getType().toStream(out, language::output::LANG_AST); } return; } out << '(' << n.getKind(); if(n.getMetaKind() == kind::metakind::CONSTANT) { // constant out << ' '; kind::metakind::NodeValueConstPrinter::toStream(out, n); } else { // operator if(n.getMetaKind() == kind::metakind::PARAMETERIZED) { out << ' '; if(toDepth != 0) { toStream(out, n.getOperator(), toDepth < 0 ? toDepth : toDepth - 1, types); } else { out << "(...)"; } } for(TNode::iterator i = n.begin(), iend = n.end(); i != iend; ++i) { if(i != iend) { out << ' '; } if(toDepth != 0) { toStream(out, *i, toDepth < 0 ? toDepth : toDepth - 1, types); } else { out << "(...)"; } } } out << ')'; }/* AstPrinter::toStream(TNode) */ template <class T> static bool tryToStream(std::ostream& out, const Command* c) throw(); void AstPrinter::toStream(std::ostream& out, const Command* c, int toDepth, bool types, size_t dag) const throw() { expr::ExprSetDepth::Scope sdScope(out, toDepth); expr::ExprPrintTypes::Scope ptScope(out, types); expr::ExprDag::Scope dagScope(out, dag); if(tryToStream<EmptyCommand>(out, c) || tryToStream<AssertCommand>(out, c) || tryToStream<PushCommand>(out, c) || tryToStream<PopCommand>(out, c) || tryToStream<CheckSatCommand>(out, c) || tryToStream<QueryCommand>(out, c) || tryToStream<ResetCommand>(out, c) || tryToStream<ResetAssertionsCommand>(out, c) || tryToStream<QuitCommand>(out, c) || tryToStream<DeclarationSequence>(out, c) || tryToStream<CommandSequence>(out, c) || tryToStream<DeclareFunctionCommand>(out, c) || tryToStream<DeclareTypeCommand>(out, c) || tryToStream<DefineTypeCommand>(out, c) || tryToStream<DefineNamedFunctionCommand>(out, c) || tryToStream<DefineFunctionCommand>(out, c) || tryToStream<SimplifyCommand>(out, c) || tryToStream<GetValueCommand>(out, c) || tryToStream<GetModelCommand>(out, c) || tryToStream<GetAssignmentCommand>(out, c) || tryToStream<GetAssertionsCommand>(out, c) || tryToStream<GetProofCommand>(out, c) || tryToStream<SetBenchmarkStatusCommand>(out, c) || tryToStream<SetBenchmarkLogicCommand>(out, c) || tryToStream<SetInfoCommand>(out, c) || tryToStream<GetInfoCommand>(out, c) || tryToStream<SetOptionCommand>(out, c) || tryToStream<GetOptionCommand>(out, c) || tryToStream<DatatypeDeclarationCommand>(out, c) || tryToStream<CommentCommand>(out, c)) { return; } out << "ERROR: don't know how to print a Command of class: " << typeid(*c).name() << endl; }/* AstPrinter::toStream(Command*) */ template <class T> static bool tryToStream(std::ostream& out, const CommandStatus* s) throw(); void AstPrinter::toStream(std::ostream& out, const CommandStatus* s) const throw() { if(tryToStream<CommandSuccess>(out, s) || tryToStream<CommandFailure>(out, s) || tryToStream<CommandUnsupported>(out, s) || tryToStream<CommandInterrupted>(out, s)) { return; } out << "ERROR: don't know how to print a CommandStatus of class: " << typeid(*s).name() << endl; }/* AstPrinter::toStream(CommandStatus*) */ void AstPrinter::toStream(std::ostream& out, const Model& m) const throw() { out << "Model()"; } void AstPrinter::toStream(std::ostream& out, const Model& m, const Command* c) const throw() { // shouldn't be called; only the non-Command* version above should be Unreachable(); } static void toStream(std::ostream& out, const EmptyCommand* c) throw() { out << "EmptyCommand(" << c->getName() << ")"; } static void toStream(std::ostream& out, const AssertCommand* c) throw() { out << "Assert(" << c->getExpr() << ")"; } static void toStream(std::ostream& out, const PushCommand* c) throw() { out << "Push()"; } static void toStream(std::ostream& out, const PopCommand* c) throw() { out << "Pop()"; } static void toStream(std::ostream& out, const CheckSatCommand* c) throw() { Expr e = c->getExpr(); if(e.isNull()) { out << "CheckSat()"; } else { out << "CheckSat(" << e << ")"; } } static void toStream(std::ostream& out, const QueryCommand* c) throw() { out << "Query(" << c->getExpr() << ')'; } static void toStream(std::ostream& out, const ResetCommand* c) throw() { out << "Reset()"; } static void toStream(std::ostream& out, const ResetAssertionsCommand* c) throw() { out << "ResetAssertions()"; } static void toStream(std::ostream& out, const QuitCommand* c) throw() { out << "Quit()"; } static void toStream(std::ostream& out, const DeclarationSequence* c) throw() { out << "DeclarationSequence[" << endl; for(CommandSequence::const_iterator i = c->begin(); i != c->end(); ++i) { out << *i << endl; } out << "]"; } static void toStream(std::ostream& out, const CommandSequence* c) throw() { out << "CommandSequence[" << endl; for(CommandSequence::const_iterator i = c->begin(); i != c->end(); ++i) { out << *i << endl; } out << "]"; } static void toStream(std::ostream& out, const DeclareFunctionCommand* c) throw() { out << "Declare(" << c->getSymbol() << "," << c->getType() << ")"; } static void toStream(std::ostream& out, const DefineFunctionCommand* c) throw() { Expr func = c->getFunction(); const std::vector<Expr>& formals = c->getFormals(); Expr formula = c->getFormula(); out << "DefineFunction( \"" << func << "\", ["; if(formals.size() > 0) { copy( formals.begin(), formals.end() - 1, ostream_iterator<Expr>(out, ", ") ); out << formals.back(); } out << "], << " << formula << " >> )"; } static void toStream(std::ostream& out, const DeclareTypeCommand* c) throw() { out << "DeclareType(" << c->getSymbol() << "," << c->getArity() << "," << c->getType() << ")"; } static void toStream(std::ostream& out, const DefineTypeCommand* c) throw() { const vector<Type>& params = c->getParameters(); out << "DefineType(" << c->getSymbol() << ",["; if(params.size() > 0) { copy( params.begin(), params.end() - 1, ostream_iterator<Type>(out, ", ") ); out << params.back(); } out << "]," << c->getType() << ")"; } static void toStream(std::ostream& out, const DefineNamedFunctionCommand* c) throw() { out << "DefineNamedFunction( "; toStream(out, static_cast<const DefineFunctionCommand*>(c)); out << " )"; } static void toStream(std::ostream& out, const SimplifyCommand* c) throw() { out << "Simplify( << " << c->getTerm() << " >> )"; } static void toStream(std::ostream& out, const GetValueCommand* c) throw() { out << "GetValue( << "; const vector<Expr>& terms = c->getTerms(); copy(terms.begin(), terms.end(), ostream_iterator<Expr>(out, ", ")); out << " >> )"; } static void toStream(std::ostream& out, const GetModelCommand* c) throw() { out << "GetModel()"; } static void toStream(std::ostream& out, const GetAssignmentCommand* c) throw() { out << "GetAssignment()"; } static void toStream(std::ostream& out, const GetAssertionsCommand* c) throw() { out << "GetAssertions()"; } static void toStream(std::ostream& out, const GetProofCommand* c) throw() { out << "GetProof()"; } static void toStream(std::ostream& out, const SetBenchmarkStatusCommand* c) throw() { out << "SetBenchmarkStatus(" << c->getStatus() << ")"; } static void toStream(std::ostream& out, const SetBenchmarkLogicCommand* c) throw() { out << "SetBenchmarkLogic(" << c->getLogic() << ")"; } static void toStream(std::ostream& out, const SetInfoCommand* c) throw() { out << "SetInfo(" << c->getFlag() << ", " << c->getSExpr() << ")"; } static void toStream(std::ostream& out, const GetInfoCommand* c) throw() { out << "GetInfo(" << c->getFlag() << ")"; } static void toStream(std::ostream& out, const SetOptionCommand* c) throw() { out << "SetOption(" << c->getFlag() << ", " << c->getSExpr() << ")"; } static void toStream(std::ostream& out, const GetOptionCommand* c) throw() { out << "GetOption(" << c->getFlag() << ")"; } static void toStream(std::ostream& out, const DatatypeDeclarationCommand* c) throw() { const vector<DatatypeType>& datatypes = c->getDatatypes(); out << "DatatypeDeclarationCommand(["; for(vector<DatatypeType>::const_iterator i = datatypes.begin(), i_end = datatypes.end(); i != i_end; ++i) { out << *i << ";" << endl; } out << "])"; } static void toStream(std::ostream& out, const CommentCommand* c) throw() { out << "CommentCommand([" << c->getComment() << "])"; } template <class T> static bool tryToStream(std::ostream& out, const Command* c) throw() { if(typeid(*c) == typeid(T)) { toStream(out, dynamic_cast<const T*>(c)); return true; } return false; } static void toStream(std::ostream& out, const CommandSuccess* s) throw() { if(Command::printsuccess::getPrintSuccess(out)) { out << "OK" << endl; } } static void toStream(std::ostream& out, const CommandInterrupted* s) throw() { out << "INTERRUPTED" << endl; } static void toStream(std::ostream& out, const CommandUnsupported* s) throw() { out << "UNSUPPORTED" << endl; } static void toStream(std::ostream& out, const CommandFailure* s) throw() { out << s->getMessage() << endl; } template <class T> static bool tryToStream(std::ostream& out, const CommandStatus* s) throw() { if(typeid(*s) == typeid(T)) { toStream(out, dynamic_cast<const T*>(s)); return true; } return false; } }/* CVC4::printer::ast namespace */ }/* CVC4::printer namespace */ }/* CVC4 namespace */
30.610973
94
0.611079
[ "vector", "model" ]
ff276eeb45337c491939192a77f845e9af1617ee
6,223
cpp
C++
Source/WebKit/WebProcess/InjectedBundle/API/glib/WebKitScriptWorld.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
6
2021-07-05T16:09:39.000Z
2022-03-06T22:44:42.000Z
Source/WebKit/WebProcess/InjectedBundle/API/glib/WebKitScriptWorld.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
7
2022-03-15T13:25:39.000Z
2022-03-15T13:25:44.000Z
Source/WebKit/WebProcess/InjectedBundle/API/glib/WebKitScriptWorld.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (C) 2013 Igalia S.L. * * 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "WebKitScriptWorld.h" #include "WebKitScriptWorldPrivate.h" #include <wtf/HashMap.h> #include <wtf/NeverDestroyed.h> #include <wtf/glib/WTFGType.h> using namespace WebKit; using namespace WebCore; enum { WINDOW_OBJECT_CLEARED, LAST_SIGNAL }; typedef HashMap<InjectedBundleScriptWorld*, WebKitScriptWorld*> ScriptWorldMap; static ScriptWorldMap& scriptWorlds() { static NeverDestroyed<ScriptWorldMap> map; return map; } struct _WebKitScriptWorldPrivate { ~_WebKitScriptWorldPrivate() { ASSERT(scriptWorlds().contains(scriptWorld.get())); scriptWorlds().remove(scriptWorld.get()); } RefPtr<InjectedBundleScriptWorld> scriptWorld; CString name; }; static guint signals[LAST_SIGNAL] = { 0, }; WEBKIT_DEFINE_TYPE(WebKitScriptWorld, webkit_script_world, G_TYPE_OBJECT) static void webkit_script_world_class_init(WebKitScriptWorldClass* klass) { /** * WebKitScriptWorld::window-object-cleared: * @world: the #WebKitScriptWorld on which the signal is emitted * @page: a #WebKitWebPage * @frame: the #WebKitFrame to which @world belongs * * Emitted when the JavaScript window object in a #WebKitScriptWorld has been * cleared. This is the preferred place to set custom properties on the window * object using the JavaScriptCore API. You can get the window object of @frame * from the JavaScript execution context of @world that is returned by * webkit_frame_get_js_context_for_script_world(). * * Since: 2.2 */ signals[WINDOW_OBJECT_CLEARED] = g_signal_new( "window-object-cleared", G_TYPE_FROM_CLASS(klass), G_SIGNAL_RUN_LAST, 0, nullptr, nullptr, g_cclosure_marshal_generic, G_TYPE_NONE, 2, WEBKIT_TYPE_WEB_PAGE, WEBKIT_TYPE_FRAME); } WebKitScriptWorld* webkitScriptWorldGet(InjectedBundleScriptWorld* scriptWorld) { return scriptWorlds().get(scriptWorld); } InjectedBundleScriptWorld* webkitScriptWorldGetInjectedBundleScriptWorld(WebKitScriptWorld* world) { return world->priv->scriptWorld.get(); } void webkitScriptWorldWindowObjectCleared(WebKitScriptWorld* world, WebKitWebPage* page, WebKitFrame* frame) { g_signal_emit(world, signals[WINDOW_OBJECT_CLEARED], 0, page, frame); } static WebKitScriptWorld* webkitScriptWorldCreate(Ref<InjectedBundleScriptWorld>&& scriptWorld) { WebKitScriptWorld* world = WEBKIT_SCRIPT_WORLD(g_object_new(WEBKIT_TYPE_SCRIPT_WORLD, nullptr)); world->priv->scriptWorld = WTFMove(scriptWorld); world->priv->name = world->priv->scriptWorld->name().utf8(); ASSERT(!scriptWorlds().contains(world->priv->scriptWorld.get())); scriptWorlds().add(world->priv->scriptWorld.get(), world); return world; } static gpointer createDefaultScriptWorld(gpointer) { return webkitScriptWorldCreate(InjectedBundleScriptWorld::normalWorld()); } /** * webkit_script_world_get_default: * * Get the default #WebKitScriptWorld. This is the normal script world * where all scripts are executed by default. * You can get the JavaScript execution context of a #WebKitScriptWorld * for a given #WebKitFrame with webkit_frame_get_javascript_context_for_script_world(). * * Returns: (transfer none): the default #WebKitScriptWorld * * Since: 2.2 */ WebKitScriptWorld* webkit_script_world_get_default(void) { static GOnce onceInit = G_ONCE_INIT; return WEBKIT_SCRIPT_WORLD(g_once(&onceInit, createDefaultScriptWorld, 0)); } /** * webkit_script_world_new: * * Creates a new isolated #WebKitScriptWorld. Scripts executed in * isolated worlds have access to the DOM but not to other variable * or functions created by the page. * The #WebKitScriptWorld is created with a generated unique name. Use * webkit_script_world_new_with_name() if you want to create it with a * custom name. * You can get the JavaScript execution context of a #WebKitScriptWorld * for a given #WebKitFrame with webkit_frame_get_javascript_context_for_script_world(). * * Returns: (transfer full): a new isolated #WebKitScriptWorld * * Since: 2.2 */ WebKitScriptWorld* webkit_script_world_new(void) { return webkitScriptWorldCreate(InjectedBundleScriptWorld::create(InjectedBundleScriptWorld::Type::User)); } /** * webkit_script_world_new_with_name: * @name: a name for the script world * * Creates a new isolated #WebKitScriptWorld with a name. Scripts executed in * isolated worlds have access to the DOM but not to other variable * or functions created by the page. * You can get the JavaScript execution context of a #WebKitScriptWorld * for a given #WebKitFrame with webkit_frame_get_javascript_context_for_script_world(). * * Returns: (transfer full): a new isolated #WebKitScriptWorld * * Since: 2.22 */ WebKitScriptWorld* webkit_script_world_new_with_name(const char* name) { g_return_val_if_fail(name, nullptr); return webkitScriptWorldCreate(InjectedBundleScriptWorld::create(String::fromUTF8(name), InjectedBundleScriptWorld::Type::User)); } /** * webkit_script_world_get_name: * @world: a #WebKitScriptWorld * * Get the name of a #WebKitScriptWorld. * * Returns: the name of @world * * Since: 2.22 */ const char* webkit_script_world_get_name(WebKitScriptWorld* world) { g_return_val_if_fail(WEBKIT_IS_SCRIPT_WORLD(world), nullptr); return world->priv->name.data(); }
31.912821
133
0.751727
[ "object" ]
ff283cced546fe2bc799d88bd6c9c8503d6b59bb
9,501
hpp
C++
componentLibraries/defaultLibrary/Electric/ElectricPWMdceq.hpp
mjfwest/hopsan
77a0a1e69fd9588335b7e932f348972186cbdf6f
[ "Apache-2.0" ]
null
null
null
componentLibraries/defaultLibrary/Electric/ElectricPWMdceq.hpp
mjfwest/hopsan
77a0a1e69fd9588335b7e932f348972186cbdf6f
[ "Apache-2.0" ]
null
null
null
componentLibraries/defaultLibrary/Electric/ElectricPWMdceq.hpp
mjfwest/hopsan
77a0a1e69fd9588335b7e932f348972186cbdf6f
[ "Apache-2.0" ]
null
null
null
/*----------------------------------------------------------------------------- Copyright 2017 Hopsan Group 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. The full license is available in the file LICENSE. For details about the 'Hopsan Group' or information about Authors and Contributors see the HOPSANGROUP and AUTHORS files that are located in the Hopsan source code root directory. -----------------------------------------------------------------------------*/ #ifndef ELECTRICPWMDCEQ_HPP_INCLUDED #define ELECTRICPWMDCEQ_HPP_INCLUDED #include <iostream> #include "ComponentEssentials.h" #include "ComponentUtilities.h" #include "math.h" //! //! @file ElectricPWMdceq.hpp //! @author Petter Krus <petter.krus@liu.se> //! @date Mon 7 Apr 2014 13:07:02 //! @brief This is an imaginary DC analog component that represents an equivalent PWM controller. //! @ingroup ElectricComponents //! //==This code has been autogenerated using Compgen== //from /*{, C:, HopsanTrunk, ComponentLibraries, defaultLibrary, \ Electric}/ElectricPWMdceq.nb*/ using namespace hopsan; class ElectricPWMdceq : public ComponentQ { private: double resist0; double resist1; double umin; double umax; Port *mpPel1; Port *mpPel2; double delayParts1[9]; double delayParts2[9]; double delayParts3[9]; double delayParts4[9]; double delayParts5[9]; Matrix jacobianMatrix; Vec systemEquations; Matrix delayedPart; int i; int iter; int mNoiter; double jsyseqnweight[4]; int order[5]; int mNstep; //Port Pel1 variable double uel1; double iel1; double cel1; double Zcel1; //Port Pel2 variable double uel2; double iel2; double cel2; double Zcel2; //==This code has been autogenerated using Compgen== //inputVariables double tfac; //outputVariables double uel10; //Port Pel1 pointer double *mpND_uel1; double *mpND_iel1; double *mpND_cel1; double *mpND_Zcel1; //Port Pel2 pointer double *mpND_uel2; double *mpND_iel2; double *mpND_cel2; double *mpND_Zcel2; //Delay declarations //==This code has been autogenerated using Compgen== //inputVariables pointers double *mptfac; //inputParameters pointers double *mpresist0; double *mpresist1; double *mpumin; double *mpumax; //outputVariables pointers double *mpuel10; Delay mDelayedPart10; Delay mDelayedPart20; Delay mDelayedPart30; EquationSystemSolver *mpSolver; public: static Component *Creator() { return new ElectricPWMdceq(); } void configure() { //==This code has been autogenerated using Compgen== mNstep=9; jacobianMatrix.create(5,5); systemEquations.create(5); delayedPart.create(6,6); mNoiter=2; jsyseqnweight[0]=1; jsyseqnweight[1]=0.67; jsyseqnweight[2]=0.5; jsyseqnweight[3]=0.5; //Add ports to the component mpPel1=addPowerPort("Pel1","NodeElectric"); mpPel2=addPowerPort("Pel2","NodeElectric"); //Add inputVariables to the component addInputVariable("tfac","Tc/Tp (time fraction \ on)","",1.,&mptfac); //Add inputParammeters to the component addInputVariable("resist0", "loss resistans (at 2)", "ohm", \ 0.01,&mpresist0); addInputVariable("resist1", "loss resistans (at 2)", "ohm", \ 10.,&mpresist1); addInputVariable("umin", "minimum voltage difference", "V", \ 0.01,&mpumin); addInputVariable("umax", "u max limit", "V", 1000.,&mpumax); //Add outputVariables to the component addOutputVariable("uel10","middle voltage","V",0.,&mpuel10); //==This code has been autogenerated using Compgen== //Add constantParameters mpSolver = new EquationSystemSolver(this,5); } void initialize() { //Read port variable pointers from nodes //Port Pel1 mpND_uel1=getSafeNodeDataPtr(mpPel1, NodeElectric::Voltage); mpND_iel1=getSafeNodeDataPtr(mpPel1, NodeElectric::Current); mpND_cel1=getSafeNodeDataPtr(mpPel1, NodeElectric::WaveVariable); mpND_Zcel1=getSafeNodeDataPtr(mpPel1, NodeElectric::CharImpedance); //Port Pel2 mpND_uel2=getSafeNodeDataPtr(mpPel2, NodeElectric::Voltage); mpND_iel2=getSafeNodeDataPtr(mpPel2, NodeElectric::Current); mpND_cel2=getSafeNodeDataPtr(mpPel2, NodeElectric::WaveVariable); mpND_Zcel2=getSafeNodeDataPtr(mpPel2, NodeElectric::CharImpedance); //Read variables from nodes //Port Pel1 uel1 = (*mpND_uel1); iel1 = (*mpND_iel1); cel1 = (*mpND_cel1); Zcel1 = (*mpND_Zcel1); //Port Pel2 uel2 = (*mpND_uel2); iel2 = (*mpND_iel2); cel2 = (*mpND_cel2); Zcel2 = (*mpND_Zcel2); //Read inputVariables from nodes tfac = (*mptfac); //Read inputParameters from nodes resist0 = (*mpresist0); resist1 = (*mpresist1); umin = (*mpumin); umax = (*mpumax); //Read outputVariables from nodes uel10 = (*mpuel10); //==This code has been autogenerated using Compgen== //Initialize delays delayedPart[1][1] = delayParts1[1]; delayedPart[2][1] = delayParts2[1]; delayedPart[3][1] = delayParts3[1]; delayedPart[4][1] = delayParts4[1]; delayedPart[5][1] = delayParts5[1]; } void simulateOneTimestep() { Vec stateVar(5); Vec stateVark(5); Vec deltaStateVar(5); //Read variables from nodes //Port Pel1 cel1 = (*mpND_cel1); Zcel1 = (*mpND_Zcel1); //Port Pel2 cel2 = (*mpND_cel2); Zcel2 = (*mpND_Zcel2); //Read inputVariables from nodes tfac = (*mptfac); //LocalExpressions //Initializing variable vector for Newton-Raphson stateVark[0] = uel2; stateVark[1] = uel10; stateVark[2] = iel1; stateVark[3] = uel1; stateVark[4] = iel2; //Iterative solution using Newton-Rapshson for(iter=1;iter<=mNoiter;iter++) { //PWMdceq //Differential-algebraic system of equation parts //Assemble differential-algebraic equations systemEquations[0] =uel2 - uel10*limit(tfac,0.,1.); systemEquations[1] =-(iel1*resist1) - uel1 + uel10 + iel1*(-resist0 \ + resist1)*limit(tfac,0.,1.); systemEquations[2] =iel1 + \ (iel2*limit(uel2,umin,umax))/limit(uel10,umin,umax); systemEquations[3] =-cel1 + uel1 - iel1*Zcel1; systemEquations[4] =iel2 + (cel2 - uel2)/Zcel2; //Jacobian matrix jacobianMatrix[0][0] = 1; jacobianMatrix[0][1] = -limit(tfac,0.,1.); jacobianMatrix[0][2] = 0; jacobianMatrix[0][3] = 0; jacobianMatrix[0][4] = 0; jacobianMatrix[1][0] = 0; jacobianMatrix[1][1] = 1; jacobianMatrix[1][2] = -resist1 + (-resist0 + \ resist1)*limit(tfac,0.,1.); jacobianMatrix[1][3] = -1; jacobianMatrix[1][4] = 0; jacobianMatrix[2][0] = \ (iel2*dxLimit(uel2,umin,umax))/limit(uel10,umin,umax); jacobianMatrix[2][1] = \ -((iel2*dxLimit(uel10,umin,umax)*limit(uel2,umin,umax))/Power(limit(uel10,umi\ n,umax),2)); jacobianMatrix[2][2] = 1; jacobianMatrix[2][3] = 0; jacobianMatrix[2][4] = \ limit(uel2,umin,umax)/limit(uel10,umin,umax); jacobianMatrix[3][0] = 0; jacobianMatrix[3][1] = 0; jacobianMatrix[3][2] = -Zcel1; jacobianMatrix[3][3] = 1; jacobianMatrix[3][4] = 0; jacobianMatrix[4][0] = -(1/Zcel2); jacobianMatrix[4][1] = 0; jacobianMatrix[4][2] = 0; jacobianMatrix[4][3] = 0; jacobianMatrix[4][4] = 1; //==This code has been autogenerated using Compgen== //Solving equation using LU-faktorisation mpSolver->solve(jacobianMatrix, systemEquations, stateVark, iter); uel2=stateVark[0]; uel10=stateVark[1]; iel1=stateVark[2]; uel1=stateVark[3]; iel2=stateVark[4]; } //Calculate the delayed parts delayedPart[1][1] = delayParts1[1]; delayedPart[2][1] = delayParts2[1]; delayedPart[3][1] = delayParts3[1]; delayedPart[4][1] = delayParts4[1]; delayedPart[5][1] = delayParts5[1]; //Write new values to nodes //Port Pel1 (*mpND_uel1)=uel1; (*mpND_iel1)=iel1; //Port Pel2 (*mpND_uel2)=uel2; (*mpND_iel2)=iel2; //outputVariables (*mpuel10)=uel10; //Update the delayed variabels } void deconfigure() { delete mpSolver; } }; #endif // ELECTRICPWMDCEQ_HPP_INCLUDED
30.257962
97
0.603094
[ "vector" ]
ff2955b522053804cfb3df9a3b465a8372b02567
742
cpp
C++
platforms/leetcode/0027_next_greater_element_ii.cpp
idfumg/algorithms
06f85c5a1d07a965df44219b5a6bf0d43a129256
[ "MIT" ]
null
null
null
platforms/leetcode/0027_next_greater_element_ii.cpp
idfumg/algorithms
06f85c5a1d07a965df44219b5a6bf0d43a129256
[ "MIT" ]
null
null
null
platforms/leetcode/0027_next_greater_element_ii.cpp
idfumg/algorithms
06f85c5a1d07a965df44219b5a6bf0d43a129256
[ "MIT" ]
null
null
null
#include "../../template.hpp" using i32 = std::int32_t; using i64 = std::int64_t; //const i32 INF = 1000000000 + 7; const i32 fastio_ = ([](){std::ios_base::sync_with_stdio(0); std::cin.tie(0);return 0;})(); vector<i32> tab(vector<i32> arr) { i32 n = arr.size(); vector<i32> R(n); vector<i32> mq; for (i32 i = 2 * n - 1; i >= 0; --i) { while (not mq.empty() and arr[i%n] >= mq.back()) mq.pop_back(); R[i%n] = mq.empty() ? -1 : mq.back(); mq.push_back(arr[i%n]); } vector<i32> ans(n); for (i32 i = 0; i < n; ++i) { ans[i] = R[i]; } return ans; } int main() { TimeMeasure _; cout << tab({1,2,1}) << endl; // 2,-1,2 cout << tab({1,2,3,4,3}) << endl; // 2,3,4,-1,4 }
26.5
91
0.502695
[ "vector" ]
ff2bed776b0af5de9acfc8bbb03fdc1ccee32d2c
6,154
cpp
C++
src/dynamic_graph_manager/hwp_solo12.cpp
caoliheng/solo
e6d86f54e05977a533c68e30c85a5048a03ab753
[ "BSD-3-Clause" ]
9
2021-04-26T03:13:44.000Z
2021-12-14T14:06:50.000Z
src/dynamic_graph_manager/hwp_solo12.cpp
caoliheng/solo
e6d86f54e05977a533c68e30c85a5048a03ab753
[ "BSD-3-Clause" ]
4
2021-07-19T13:54:12.000Z
2022-01-24T08:53:49.000Z
src/dynamic_graph_manager/hwp_solo12.cpp
caoliheng/solo
e6d86f54e05977a533c68e30c85a5048a03ab753
[ "BSD-3-Clause" ]
1
2021-06-24T16:13:36.000Z
2021-06-24T16:13:36.000Z
/** * \file dgm_solo.cpp * \brief The hardware wrapper of the solo robot * \author Maximilien Naveau * \date 2018 * * This file defines the TestBench8Motors class. */ #include "solo/dynamic_graph_manager/hwp_solo12.hpp" #ifdef BUILD_WITH_ROS_DYNAMIC_GRAPH #include "dynamic_graph_manager/ros.hpp" #endif namespace solo { HWPSolo12::HWPSolo12() { was_in_safety_mode_ = false; } HWPSolo12::~HWPSolo12() { } void HWPSolo12::initialize_drivers() { /** * Load the calibration parameters. */ YAML::ReadParameter(params_["hardware_communication"]["calibration"], "index_to_zero_angle", zero_to_index_angle_from_file_); #ifdef BUILD_WITH_ROS_DYNAMIC_GRAPH // Get the hardware communication ros node handle. dynamic_graph_manager::RosNodePtr ros_node_handle = dynamic_graph_manager::get_ros_node( dynamic_graph_manager::HWC_ROS_NODE_NAME); /** Initialize the user commands. */ ros_user_commands_.push_back( ros_node_handle->create_service<mim_msgs::srv::JointCalibration>( "calibrate_joint_position", std::bind(&HWPSolo12::calibrate_joint_position_callback, this, std::placeholders::_1, std::placeholders::_2))); #endif std::string network_id; YAML::ReadParameter( params_["hardware_communication"], "network_id", network_id); std::string serial_port; YAML::ReadParameter( params_["hardware_communication"], "serial_port", serial_port); solo_.initialize(network_id, serial_port); } bool HWPSolo12::is_in_safety_mode() { // Check if any card is in an error state. if (solo_.has_error()) { was_in_safety_mode_ = true; static int counter = 0; if (counter % 2000 == 0) { printf("HWPSolo12: Going into safe mode as motor card reports error.\n"); } counter += 1; } if (was_in_safety_mode_ || HardwareProcess::is_in_safety_mode()) { static int counter = 0; was_in_safety_mode_ = true; if (counter % 2000 == 0) { printf("HWPSolo12: is_in_safety_mode.\n"); } counter++; } return was_in_safety_mode_; } void HWPSolo12::compute_safety_controls() { // Check if there is an error with the motors. If so, best we can do is // to command zero torques. if (solo_.has_error()) { for (auto ctrl = motor_controls_map_.begin(); ctrl != motor_controls_map_.end(); ++ctrl) { ctrl->second.fill(0.0); } } else { // The motors are fine. // --> Run a D controller to damp the current motion. motor_controls_map_.at("ctrl_joint_torques") = -0.05 * sensors_map_.at("joint_velocities"); } } void HWPSolo12::get_sensors_to_map(dynamic_graph_manager::VectorDGMap& map) { solo_.acquire_sensors(); /** * Joint data. */ map.at("joint_positions") = solo_.get_joint_positions(); map.at("joint_velocities") = solo_.get_joint_velocities(); map.at("joint_torques") = solo_.get_joint_torques(); map.at("joint_target_torques") = solo_.get_joint_target_torques(); map.at("joint_encoder_index") = solo_.get_joint_encoder_index(); /** * Additional data. */ map.at("slider_positions") = solo_.get_slider_positions(); map.at("imu_accelerometer") = solo_.get_imu_accelerometer(); map.at("imu_gyroscope") = solo_.get_imu_gyroscope(); map.at("imu_attitude") = solo_.get_imu_attitude(); map.at("imu_linear_acceleration") = solo_.get_imu_linear_acceleration(); /** * Robot status. */ dynamicgraph::Vector& map_motor_enabled = map.at("motor_enabled"); dynamicgraph::Vector& map_motor_ready = map.at("motor_ready"); dynamicgraph::Vector& map_motor_board_enabled = map.at("motor_board_enabled"); dynamicgraph::Vector& map_motor_board_errors = map.at("motor_board_errors"); const std::array<bool, 12>& motor_enabled = solo_.get_motor_enabled(); const std::array<bool, 12>& motor_ready = solo_.get_motor_ready(); const std::array<bool, 6>& motor_board_enabled = solo_.get_motor_board_enabled(); const std::array<int, 6>& motor_board_errors = solo_.get_motor_board_errors(); for (size_t i = 0; i < motor_enabled.size(); ++i) { map_motor_enabled[i] = motor_enabled[i]; map_motor_ready[i] = motor_ready[i]; } for (size_t i = 0; i < motor_board_enabled.size(); ++i) { map_motor_board_enabled[i] = motor_board_enabled[i]; map_motor_board_errors[i] = motor_board_errors[i]; } } void HWPSolo12::set_motor_controls_from_map( const dynamic_graph_manager::VectorDGMap& map) { try { // Here we need to perform and internal copy. Otherwise the compilator // complains. ctrl_joint_torques_ = map.at("ctrl_joint_torques"); // Actually send the control to the robot. solo_.send_target_joint_torque(ctrl_joint_torques_); } catch (const std::exception& e) { rt_printf( "HWPSolo12::set_motor_controls_from_map: " "Error sending controls, %s\n", e.what()); } } #ifdef BUILD_WITH_ROS_DYNAMIC_GRAPH void HWPSolo12::calibrate_joint_position_callback( mim_msgs::srv::JointCalibration::Request::SharedPtr, mim_msgs::srv::JointCalibration::Response::SharedPtr res) { // Parse and register the command for further call. add_user_command(std::bind(&HWPSolo12::calibrate_joint_position, this, zero_to_index_angle_from_file_)); // Return a sanity check that assert that the function has been correctly // registered in the hardware process. res->sanity_check = true; } #endif void HWPSolo12::calibrate_joint_position( const solo::Vector12d& zero_to_index_angle) { solo_.request_calibration(zero_to_index_angle); } void HWPSolo12::calibrate_joint_position_from_yaml() { solo_.request_calibration(zero_to_index_angle_from_file_); } } // namespace solo
30.166667
81
0.660871
[ "vector" ]
ff3454caa13341ad7ea0a612ddfb9bc73c421515
1,893
cpp
C++
aws-cpp-sdk-frauddetector/source/model/VariableImpactExplanation.cpp
truthiswill/aws-sdk-cpp
6e854b6a8bc7945f150c3a11551196bda341962a
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-frauddetector/source/model/VariableImpactExplanation.cpp
truthiswill/aws-sdk-cpp
6e854b6a8bc7945f150c3a11551196bda341962a
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-frauddetector/source/model/VariableImpactExplanation.cpp
truthiswill/aws-sdk-cpp
6e854b6a8bc7945f150c3a11551196bda341962a
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/frauddetector/model/VariableImpactExplanation.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace FraudDetector { namespace Model { VariableImpactExplanation::VariableImpactExplanation() : m_eventVariableNameHasBeenSet(false), m_relativeImpactHasBeenSet(false), m_logOddsImpact(0.0), m_logOddsImpactHasBeenSet(false) { } VariableImpactExplanation::VariableImpactExplanation(JsonView jsonValue) : m_eventVariableNameHasBeenSet(false), m_relativeImpactHasBeenSet(false), m_logOddsImpact(0.0), m_logOddsImpactHasBeenSet(false) { *this = jsonValue; } VariableImpactExplanation& VariableImpactExplanation::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("eventVariableName")) { m_eventVariableName = jsonValue.GetString("eventVariableName"); m_eventVariableNameHasBeenSet = true; } if(jsonValue.ValueExists("relativeImpact")) { m_relativeImpact = jsonValue.GetString("relativeImpact"); m_relativeImpactHasBeenSet = true; } if(jsonValue.ValueExists("logOddsImpact")) { m_logOddsImpact = jsonValue.GetDouble("logOddsImpact"); m_logOddsImpactHasBeenSet = true; } return *this; } JsonValue VariableImpactExplanation::Jsonize() const { JsonValue payload; if(m_eventVariableNameHasBeenSet) { payload.WithString("eventVariableName", m_eventVariableName); } if(m_relativeImpactHasBeenSet) { payload.WithString("relativeImpact", m_relativeImpact); } if(m_logOddsImpactHasBeenSet) { payload.WithDouble("logOddsImpact", m_logOddsImpact); } return payload; } } // namespace Model } // namespace FraudDetector } // namespace Aws
20.576087
84
0.75383
[ "model" ]
ff35eb25931831565980d58dfa660ae3743233dc
4,200
cpp
C++
rmf_fleet_adapter_python/src/schedule/schedule.cpp
chianfern/rmf_ros2
8440488d5583edc5a5b7226326aa2a8d41dad975
[ "Apache-2.0" ]
null
null
null
rmf_fleet_adapter_python/src/schedule/schedule.cpp
chianfern/rmf_ros2
8440488d5583edc5a5b7226326aa2a8d41dad975
[ "Apache-2.0" ]
null
null
null
rmf_fleet_adapter_python/src/schedule/schedule.cpp
chianfern/rmf_ros2
8440488d5583edc5a5b7226326aa2a8d41dad975
[ "Apache-2.0" ]
null
null
null
#include <pybind11/pybind11.h> #include <pybind11/eigen.h> #include <pybind11/chrono.h> #include <pybind11/stl.h> #include <rmf_traffic/schedule/Participant.hpp> #include <rmf_traffic/agv/Interpolate.hpp> #include <rmf_traffic/Route.hpp> namespace py = pybind11; namespace schedule = rmf_traffic::schedule; using SystemTimePoint = std::chrono::time_point<std::chrono::system_clock, std::chrono::nanoseconds>; // TODO(YL): create a module to manage Time and Duration input and output rmf_traffic::Time to_rmf_time(SystemTimePoint time) { return rmf_traffic::Time(time.time_since_epoch()); } //============================================================================== void bind_schedule(py::module& m) { auto m_schedule = m.def_submodule("schedule"); /// PARTICIPANT ============================================================== py::class_<schedule::Participant, std::shared_ptr<schedule::Participant>>( m_schedule, "Participant") .def_property_readonly("id", &schedule::Participant::id) .def_property_readonly("version", &schedule::Participant::id) .def_property_readonly( "current_plan_id", &schedule::Participant::current_plan_id) .def_property("delay", py::overload_cast<>( &schedule::Participant::delay, py::const_), py::overload_cast< rmf_traffic::Duration>(&schedule::Participant::delay)) .def("clear", &schedule::Participant::clear) .def("get_itinerary", &schedule::Participant::itinerary) .def("set_itinerary", [&](schedule::Participant& self, const std::vector<rmf_traffic::Route>& itinerary) { self.set(self.assign_plan_id(), itinerary); }, py::arg("itinerary")); /// ROUTE ==================================================================== /// TODO(YL) The current organization of modules differ slighty with the /// rmf_core directory structure. e.g. class Route should go directly /// rmf_traffic. Will need to adfdress all these in near future, a fix /// will be to create a generic python bindings for rmf_core itself. py::class_<rmf_traffic::Route, std::shared_ptr<rmf_traffic::Route>>(m_schedule, "Route") .def(py::init<std::string&, rmf_traffic::Trajectory>(), py::arg("map"), py::arg("trajectory")) .def_property("map", py::overload_cast<>( &rmf_traffic::Route::map, py::const_), py::overload_cast< std::string>(&rmf_traffic::Route::map)) .def_property("trajectory", py::overload_cast<>( &rmf_traffic::Route::trajectory, py::const_), py::overload_cast< rmf_traffic::Trajectory>(&rmf_traffic::Route::trajectory)); // MAKE TRAJECTORY FUNCTION ================================================== m_schedule.def( "make_trajectory", [](const rmf_traffic::agv::VehicleTraits& traits, SystemTimePoint start_time, const std::vector<Eigen::Vector3d>& input_positions) { return rmf_traffic::agv::Interpolate::positions( traits, to_rmf_time(start_time), input_positions); }, py::arg("traits"), py::arg("start_time"), py::arg("input_positions")); // TRAJECTORY ================================================================ py::class_<rmf_traffic::Trajectory, std::shared_ptr<rmf_traffic::Trajectory>>(m_schedule, "Trajectory") .def(py::init<>()) .def("size", &rmf_traffic::Trajectory::size) .def("insert", [&](rmf_traffic::Trajectory& self, double seconds, Eigen::Vector3d position, Eigen::Vector3d velocity) { self.insert( rmf_traffic::Time(rmf_traffic::time::from_seconds(seconds)), position, velocity); }, py::arg("time"), py::arg("position"), py::arg("velocity")) .def("position", [](const rmf_traffic::Trajectory& self, std::size_t index) { return self.at(index).position(); }, py::arg("index")) .def("velocity", [](const rmf_traffic::Trajectory& self, std::size_t index) { return self.at(index).velocity(); }, py::arg("index")) .def("time", [](const rmf_traffic::Trajectory& self, std::size_t index) { return rmf_traffic::time::to_seconds( self.at(index).time().time_since_epoch()); }, py::arg("index")); }
34.42623
80
0.620952
[ "vector" ]
ff38fd11dd94618a7b9b96bb1173c13101ec99b8
13,628
hpp
C++
ork.core/inc/ork/cvector3.hpp
tweakoz/zed64
c0231444418999191182d53d9319bf7978422bfb
[ "CC-BY-3.0" ]
4
2015-06-04T01:14:43.000Z
2018-06-16T05:45:57.000Z
ork.core/inc/ork/cvector3.hpp
tweakoz/zed64
c0231444418999191182d53d9319bf7978422bfb
[ "CC-BY-3.0" ]
null
null
null
ork.core/inc/ork/cvector3.hpp
tweakoz/zed64
c0231444418999191182d53d9319bf7978422bfb
[ "CC-BY-3.0" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // MicroOrk (Orkid) // Copyright 1996-2013, Michael T. Mayers // Provided under the MIT License (see LICENSE.txt) /////////////////////////////////////////////////////////////////////////////// #include "cmatrix4.h" #include "cmatrix3.h" #include "cvector4.h" /////////////////////////////////////////////////////////////////////////////// namespace ork { /////////////////////////////////////////////////////////////////////////////// bool UsingOpenGl(); /////////////////////////////////////////////////////////////////////////////// template <typename T> TVector3<T> TVector3<T>::Saturate( void ) const { TVector3<T> rval = *this; rval.m_x = (rval.m_x>1.0f) ? 1.0f : (rval.m_x<0.0f) ? 0.0f : rval.m_x; rval.m_y = (rval.m_y>1.0f) ? 1.0f : (rval.m_y<0.0f) ? 0.0f : rval.m_y; rval.m_z = (rval.m_z>1.0f) ? 1.0f : (rval.m_z<0.0f) ? 0.0f : rval.m_z; return rval; } template <typename T> const TVector3<T> & TVector3<T>::Black( void ) { static const TVector3<T> Black( T(0.0f), T(0.0f), T(0.0f) ); return Black; } /////////////////////////////////////////////////////////////////////////////// template <typename T> const TVector3<T> & TVector3<T>::DarkGrey( void ) { static const TVector3<T> DarkGrey( T(0.250f), T(0.250f), T(0.250f) ); return DarkGrey; } /////////////////////////////////////////////////////////////////////////////// template <typename T> const TVector3<T> & TVector3<T>::MediumGrey( void ) { static const TVector3<T> MediumGrey( T(0.50f), T(0.50f), T(0.50f) ); return MediumGrey; } /////////////////////////////////////////////////////////////////////////////// template <typename T> const TVector3<T> & TVector3<T>::LightGrey( void ) { static const TVector3<T> LightGrey(T(0.75f), T(0.75f), T(0.75f) ); return LightGrey; } /////////////////////////////////////////////////////////////////////////////// template <typename T> const TVector3<T> & TVector3<T>::White( void ) { static const TVector3<T> White( T(1.0f), T(1.0f), T(1.0f) ); return White; } /////////////////////////////////////////////////////////////////////////////// template <typename T> const TVector3<T> & TVector3<T>::Red( void ) { static const TVector3<T> Red( T(1.0f), T(0.0f), T(0.0f) ); return Red; } /////////////////////////////////////////////////////////////////////////////// template <typename T> const TVector3<T> & TVector3<T>::Green( void ) { static const TVector3<T> Green( T(0.0f), T(1.0f), T(0.0f) ); return Green; } /////////////////////////////////////////////////////////////////////////////// template <typename T> const TVector3<T> & TVector3<T>::Blue( void ) { static const TVector3<T> Blue( T(0.0f), T(0.0f), T(1.0f) ); return Blue; } /////////////////////////////////////////////////////////////////////////////// template <typename T> const TVector3<T> & TVector3<T>::Magenta( void ) { static const TVector3<T> Magenta( T(1.0f), T(0.0f), T(1.0f) ); return Magenta; } /////////////////////////////////////////////////////////////////////////////// template <typename T> const TVector3<T> & TVector3<T>::Cyan( void ) { static const TVector3<T> Cyan( T(0.0f), T(1.0f), T(1.0f) ); return Cyan; } /////////////////////////////////////////////////////////////////////////////// template <typename T> const TVector3<T> & TVector3<T>::Yellow( void ) { static const TVector3<T> Yellow( T(1.0f), T(1.0f), T(0.0f) ); return Yellow; } /////////////////////////////////////////////////////////////////////////////// template <typename T> TVector3<T>::TVector3() : m_x(T(0.0f)) , m_y(T(0.0f)) , m_z(T(0.0f)) { } /////////////////////////////////////////////////////////////////////////////// template <typename T> TVector3<T>::TVector3( T x, T y, T z) : m_x(x) , m_y(y) , m_z(z) { } //////////////////////////////////////////////////////////////////////////////// template <typename T> u32 TVector3<T>::GetVtxColorAsU32( void ) const { u32 r = u32(GetX()*T(255.0f)); u32 g = u32(GetY()*T(255.0f)); u32 b = u32(GetZ()*T(255.0f)); u32 a = 255; if( ork::UsingOpenGl() ) return u32( (a<<24)|(b<<16)|(g<<8)|r ); else return u32( (a<<24)|(r<<16)|(g<<8)|b ); } //////////////////////////////////////////////////////////////////////////////// template <typename T> u32 TVector3<T>::GetABGRU32( void ) const { u32 r = u32(GetX()*T(255.0f)); u32 g = u32(GetY()*T(255.0f)); u32 b = u32(GetZ()*T(255.0f)); u32 a = 255; return u32( (a<<24)|(b<<16)|(g<<8)|r ); } //////////////////////////////////////////////////////////////////////////////// template <typename T> u32 TVector3<T>::GetARGBU32( void ) const { u32 r = u32(GetX()*T(255.0f)); u32 g = u32(GetY()*T(255.0f)); u32 b = u32(GetZ()*T(255.0f)); u32 a = 255; return u32( (a<<24)|(r<<16)|(g<<8)|b ); } //////////////////////////////////////////////////////////////////////////////// template <typename T> u32 TVector3<T>::GetRGBAU32( void ) const { u32 r = u32(GetX()*T(255.0f)); u32 g = u32(GetY()*T(255.0f)); u32 b = u32(GetZ()*T(255.0f)); u32 a = 255; u32 rval = 0; #if defined(__sgi) rval = ( (b<<24)|(g<<16)|(r<<8)|a ); #else rval = ( (a<<24)|(r<<16)|(g<<8)|b ); #endif return rval; } /////////////////////////////////////////////////////////////////////////////// template <typename T> u32 TVector3<T>::GetBGRAU32( void ) const { u32 r = u32(GetX()*T(255.0f)); u32 g = u32(GetY()*T(255.0f)); u32 b = u32(GetZ()*T(255.0f)); u32 a = 255; return u32( (b<<24)|(g<<16)|(r<<8)|a ); } /////////////////////////////////////////////////////////////////////////////// template <typename T> u16 TVector3<T>::GetRGBU16() const { u32 r = u32(GetX() * T(31.0f)); u32 g = u32(GetY() * T(31.0f)); u32 b = u32(GetZ() * T(31.0f)); u16 rval = u16((b<<10)|(g<<5)|r); return rval; } /////////////////////////////////////////////////////////////////////////////// template <typename T> void TVector3<T>::SetRGBAU32(u32 uval) { u32 r = (uval>>24) & 0xff; u32 g = (uval>>16) & 0xff; u32 b = (uval>>8) & 0xff; static const T kfic(1.0f / 255.0f); SetX(kfic * T(int(r))); SetY(kfic * T(int(g))); SetZ(kfic * T(int(b))); } /////////////////////////////////////////////////////////////////////////////// template <typename T> void TVector3<T>::SetBGRAU32( u32 uval ) { u32 b = (uval>>24) & 0xff; u32 g = (uval>>16) & 0xff; u32 r = (uval>>8) & 0xff; static const T kfic(1.0f / 255.0f); SetX(kfic * T(int(r))); SetY(kfic * T(int(g))); SetZ(kfic * T(int(b))); } /////////////////////////////////////////////////////////////////////////////// template <typename T> void TVector3<T>::SetARGBU32(u32 uval) { u32 r = (uval>>16) & 0xff; u32 g = (uval>>8) & 0xff; u32 b = (uval) & 0xff; static const T kfic(1.0f / 255.0f); SetX(kfic * T(int(r))); SetY(kfic * T(int(g))); SetZ(kfic * T(int(b))); } /////////////////////////////////////////////////////////////////////////////// template <typename T> void TVector3<T>::SetABGRU32(u32 uval) { u32 b = (uval>>16) & 0xff; u32 g = (uval>>8) & 0xff; u32 r = (uval) & 0xff; static const T kfic(1.0f / 255.0f); SetX(kfic * T(int(r))); SetY(kfic * T(int(g))); SetZ(kfic * T(int(b))); } /////////////////////////////////////////////////////////////////////////////// template <typename T> void TVector3<T>::SetHSV( T h, T s, T v ) { } template <typename T> TVector3<T> TVector3<T>::Reflect( const TVector3 &N ) const { const TVector3<T>& I = *this; TVector3<T> R = I-(N*2.0f*N.Dot(I)); return R; } /////////////////////////////////////////////////////////////////////////////// template <typename T> TVector3<T>::TVector3( const TVector3<T> &vec) { m_x = vec.m_x; m_y = vec.m_y; m_z = vec.m_z; } /////////////////////////////////////////////////////////////////////////////// template <typename T> TVector3<T>::TVector3( const TVector4<T> &vec) { m_x = vec.GetX(); m_y = vec.GetY(); m_z = vec.GetZ(); } /////////////////////////////////////////////////////////////////////////////// template <typename T> TVector3<T>::TVector3( const TVector2<T> &vec) { m_x = vec.GetX(); m_y = vec.GetY(); m_z = T(0); } /////////////////////////////////////////////////////////////////////////////// template <typename T> TVector3<T>::TVector3( const TVector2<T> &vec, T w) { m_x = vec.GetX(); m_y = vec.GetY(); m_z = w; } //////////////////////////////////////////////////////////////////////////////// template <typename T> T TVector3<T>::Dot( const TVector3<T> &vec) const { #if defined WII return __fmadds(m_x,vec.m_x,__fmadds(m_y,vec.m_y,__fmadds(m_z,vec.m_z,0.0f))); #else return ( (m_x * vec.m_x) + (m_y * vec.m_y) + (m_z * vec.m_z) ); #endif } //////////////////////////////////////////////////////////////////////////////// template <typename T> TVector3<T> TVector3<T>::Cross( const TVector3<T> &vec) const // c = this X vec { T vx = ((m_y * vec.GetZ()) - (m_z * vec.GetY())); T vy = ((m_z * vec.GetX()) - (m_x * vec.GetZ())); T vz = ((m_x * vec.GetY()) - (m_y * vec.GetX())); return ( TVector3<T>( vx, vy, vz ) ); } //////////////////////////////////////////////////////////////////////////////// template <typename T> void TVector3<T>::Normalize(void) { T mag = Mag(); if( mag > std::numeric_limits<T>::epsilon() ) { T distance = (T) 1.0f / mag ; m_x *= distance; m_y *= distance; m_z *= distance; } } //////////////////////////////////////////////////////////////////////////////// template <typename T> TVector3<T> TVector3<T>::Normal() const { TVector3<T> vec(*this); vec.Normalize(); return vec; } //////////////////////////////////////////////////////////////////////////////// template <typename T> T TVector3<T>::Mag(void) const { return sqrt(m_x * m_x + m_y * m_y + m_z * m_z); } //////////////////////////////////////////////////////////////////////////////// template <typename T> T TVector3<T>::MagSquared(void) const { T mag = (m_x * m_x + m_y * m_y + m_z * m_z); return mag; } //////////////////////////////////////////////////////////////////////////////// template <typename T> TVector4<T> TVector3<T>::Transform( const TMatrix4<T> &matrix ) const { T tx,ty,tz,tw; T *mp = (T *) matrix.elements; T x = m_x; T y = m_y; T z = m_z; T w = T(1.0f); #if 0 //defined WII tx = __fmadds(m_x,vec.m_x,__fmadds(m_y,vec.m_y,__fmadds(m_z,vec.m_z,0.0f))); #else tx = x*mp[0] + y*mp[4] + z*mp[8] + w*mp[12]; ty = x*mp[1] + y*mp[5] + z*mp[9] + w*mp[13]; tz = x*mp[2] + y*mp[6] + z*mp[10] + w*mp[14]; tw = x*mp[3] + y*mp[7] + z*mp[11] + w*mp[15]; #endif return TVector4<T>( tx, ty, tz, tw ); } //////////////////////////////////////////////////////////////////////////////// template <typename T> TVector3<T> TVector3<T>::Transform( const TMatrix3<T> &matrix ) const { T tx,ty,tz; T *mp = (T *) matrix.elements; T x = m_x; T y = m_y; T z = m_z; tx = x*mp[0] + y*mp[3] + z*mp[6]; ty = x*mp[1] + y*mp[4] + z*mp[7]; tz = x*mp[2] + y*mp[5] + z*mp[8]; return TVector3<T>( tx, ty, tz ); } //////////////////////////////////////////////////////////////////////////////// template <typename T> TVector3<T> TVector3<T>::Transform3x3( const TMatrix4<T> &matrix ) const { T tx,ty,tz; T *mp = (T *) matrix.elements; T x = m_x; T y = m_y; T z = m_z; tx = x*mp[0] + y*mp[4] + z*mp[8]; ty = x*mp[1] + y*mp[5] + z*mp[9]; tz = x*mp[2] + y*mp[6] + z*mp[10]; return TVector3<T>( tx, ty, tz ); } //////////////////////////////////////////////////////////////////////////////// template <typename T> void TVector3<T>::Serp( const TVector3<T> & PA, const TVector3<T> & PB, const TVector3<T> & PC, const TVector3<T> & PD, T Par ) { TVector3<T> PAB, PCD; PAB.Lerp( PA, PB, Par ); PCD.Lerp( PC, PD, Par ); Lerp( PAB, PCD, Par ); } //////////////////////////////////////////////////////////////////////////////// template <typename T> void TVector3<T>::RotateX(T rad) { T oldY = m_y; T oldZ = m_z; m_y = (oldY * cos(rad) - oldZ * sin(rad)); m_z = (oldY * sin(rad) + oldZ * cos(rad)); } //////////////////////////////////////////////////////////////////////////////// template <typename T> void TVector3<T>::RotateY(T rad) { T oldX = m_x; T oldZ = m_z; m_x = (oldX * cos(rad) - oldZ * sin(rad)); m_z = (oldX * sin(rad) + oldZ * cos(rad)); } //////////////////////////////////////////////////////////////////////////////// template <typename T> void TVector3<T>::RotateZ(T rad) { T oldX = m_x; T oldY = m_y; m_x = (oldX * cos(rad) - oldY * sin(rad)); m_y = (oldX * sin(rad) + oldY * cos(rad)); } /////////////////////////////////////////////////////////////////////////////// template <typename T> void TVector3<T>::Lerp( const TVector3<T> &from, const TVector3<T> &to, T par ) { if( par < T(0.0f) ) par = T(0.0f); if( par > T(1.0f) ) par = T(1.0f); T ipar = T(1.0f) - par; m_x = (from.m_x*ipar) + (to.m_x*par); m_y = (from.m_y*ipar) + (to.m_y*par); m_z = (from.m_z*ipar) + (to.m_z*par); } //////////////////////////////////////////////////////////////////////////////// template <typename T> T TVector3<T>::CalcTriArea( const TVector3<T> &V, const TVector3<T> & N ) { return T(0); } }
26.826772
150
0.404975
[ "transform" ]
ff3fe4548b1e680912de489811687a5da11772ff
5,899
cpp
C++
src/FindShadow.cpp
martinid94/ShadowDet
e8c888031af38c5fa0bfb90c73da076a49eefd9c
[ "MIT" ]
2
2019-04-10T14:30:58.000Z
2019-05-16T14:15:31.000Z
src/FindShadow.cpp
martinid94/ShadowDet
e8c888031af38c5fa0bfb90c73da076a49eefd9c
[ "MIT" ]
null
null
null
src/FindShadow.cpp
martinid94/ShadowDet
e8c888031af38c5fa0bfb90c73da076a49eefd9c
[ "MIT" ]
null
null
null
/** * @file FindShadow.cpp * The goal of the code in this file is to provide the implementation of * findShadow() function. Since it is called concurrently by multiple threads * mutex are introduced to sincronyze access to shared resources. In particular, * these are the standard output and the vector of points that collects the shadow * pixels. * * @author Martini Davide * @version 1.0 * @since 1.0 * */ #include "FindShadow.h" mutex ccMutex; // mutex used to make connectedComponents() thread safe mutex spMutex; // mutex used to protect access to shadowPoints mutex printMutex; // mutex used to protect access to standard output /** * This function examines a set of pixels with common l*a*b* components and returns the ones that belong to a shadow. * At first, connected components are extracted and then each one is analyzed to state if it is a shadow or not. * In order to do this, this function computes the border of each patch. Then it looks for a border pixels with a* and b* * equal as those of the component, but with higher lightnes value. If such a pixel is found, then the component is * a shadow patch and all its pixels are returned as shadow pixels. * * @param imgL l* component of the filtered input image * @param imgA a* component of the filtered input image * @param imgB b* component of the filtered input image * @param labValues l*, a*, b* values of all pixels in the provided components * @param labPixels vector of points (i, j) with equal l*, a*, b* values * @param lStep step used to group l* components. See Main.cpp for more details * @param aStep step used to group a* components. See Main.cpp for more details * @param bStep step used to group b* components. See Main.cpp for more details * @param shadowPoints vector used to store shadow pixels. It is shared by threads that call this function. See Main.cpp for more details */ void findShadow(Mat imgL, Mat imgA, Mat imgB, tuple<int, int, int> labValues, vector<Point> labPixels, int lStep, int aStep, int bStep, vector<Point>& shadowPoints){ // measure elapsed time to perform the procedure chrono::time_point<chrono::system_clock> Tstart, Tend; Tstart = chrono::system_clock::now(); // compute all connected components. See https://docs.opencv.org/3.4.3/d3/dc0/group__imgproc__shape.html Mat temp = Mat_<uchar>::zeros(imgL.size()); for (int w = 0; w < labPixels.size(); w++){ Point p = labPixels[w]; temp.at<uchar> (p.x, p.y) = 255; } Mat labLabels; ccMutex.lock(); // connectedComponents() is itself multithreaded and not thread safe int labComp = connectedComponents(temp, labLabels); ccMutex.unlock(); temp.release(); // retrieve each component's pixels and store them separately for further computation vector<vector<Point> > labCComps; for (int cc = 1; cc < labComp; cc++){ // cc = 0 represents the black background vector<Point> labCompPixels; // store pixels in the current component // collect pixels for(int i = 0; i < labLabels.rows; i++){ for(int j = 0; j < labLabels.cols; j++){ if(labLabels.at<int> (i,j) == cc){ labCompPixels.push_back(Point(i,j)); } } } labCComps.push_back(labCompPixels); } int pixelCounter = 0; // only used to output information to the user // for each connected component, define if it is a shadow or not for(int labCC = 0; labCC < labCComps.size(); labCC++){ vector<Point> labCompPixels = labCComps[labCC]; vector<Point> border; Mat supportBorder = Mat_<uchar>::zeros(imgL.size()); // used to avoid duplicates in border Mat temp = Mat_<uchar>::zeros(imgL.size()); pixelCounter = pixelCounter + labCompPixels.size(); // retrieve border pixels for(int w = 0; w < labCompPixels.size(); w++){ Point p = labCompPixels[w]; int i = p.x; int j = p.y; temp.at<uchar>(i, j) = 1; if(i != 0 && j != 0 && i != (imgL.rows - 1) && j != (imgL.cols - 1)){ for(int x = -1; x <= 1; x++){ for(int y = -1; y <= 1; y++){ if(y == 0 && x == 0){ continue; } else{ if(supportBorder.at<uchar> (i+x,j+y) == 0){ border.push_back(Point(i+x,j+y)); supportBorder.at<uchar> (i+x,j+y) = 255; } } } } } } supportBorder.release(); // look at border pixels: // 1) if there is a pixel with higher lightness than the component but equal chromatic values, it means // that the component is a shadow that lies on a uniform background // 2) othrewise it is an object bool isShadow = false; for (int w = 0; w < border.size(); w++){ Point bp = border[w]; int bpL = ceil(imgL.at<uchar>(bp.x, bp.y) / lStep); int bpA = ceil(imgA.at<uchar> (bp.x, bp.y) / aStep); int bpB = ceil(imgB.at<uchar> (bp.x, bp.y) / bStep); // bp is lighter than the component (or zero in the temporary mask) but has same color of the component if(bpL > get<0>(labValues) && get<0>(labValues) > 0 && bpA == get<1>(labValues) && bpB == get<2>(labValues)){ isShadow = true; break; } } if(isShadow){ // write shadow pixels in the common container spMutex.lock(); for (int w = 0; w < labCompPixels.size(); w++){ Point p = labCompPixels[w]; shadowPoints.push_back(p); } spMutex.unlock(); } } // provide information to the user Tend = chrono::system_clock::now(); int Telapsed_seconds = chrono::duration_cast<std::chrono::milliseconds> (Tend-Tstart).count(); printMutex.lock(); cout << "Bin (" << get<0>(labValues) << ", " << get<1>(labValues) << ", " << get<2>(labValues) << ") -> totPixels: " << pixelCounter << ", totCC: " << labCComps.size() << ". Done in " << Telapsed_seconds << " ms" << endl; printMutex.unlock(); }
39.858108
136
0.641465
[ "object", "vector" ]
ff4465f344ac3b68e12251cd4e41e5a8f430dd8e
107,741
cpp
C++
CrystalEdit/CCrystalTextView.cpp
BigEd/6502
93e2f9664ac1babf141f7169478846355140ef72
[ "MIT" ]
7
2020-03-06T06:32:54.000Z
2022-02-02T06:20:08.000Z
CrystalEdit/CCrystalTextView.cpp
DRictor/6502
49c757b1cead8b4a3deae1830298083634868103
[ "MIT" ]
1
2017-12-05T09:37:55.000Z
2017-12-09T16:40:39.000Z
CrystalEdit/CCrystalTextView.cpp
DRictor/6502
49c757b1cead8b4a3deae1830298083634868103
[ "MIT" ]
5
2017-11-27T07:33:51.000Z
2022-02-20T22:28:44.000Z
//////////////////////////////////////////////////////////////////////////// // File: CCrystalTextView.cpp // Version: 1.0.0.0 // Created: 29-Dec-1998 // // Author: Stcherbatchenko Andrei // E-mail: windfall@gmx.de // // Implementation of the CCrystalTextView class, a part of Crystal Edit - // syntax coloring text editor. // // You are free to use or modify this code to the following restrictions: // - Acknowledge me somewhere in your about box, simple "Parts of code by.." // will be enough. If you can't (or don't want to), contact me personally. // - LEAVE THIS HEADER INTACT //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// // 17-Feb-99 // FIX: missing UpdateCaret() in CCrystalTextView::SetFont // FIX: missing UpdateCaret() in CCrystalTextView::RecalcVertScrollBar // FIX: mistype in CCrystalTextView::RecalcPageLayouts + instead of += // FIX: removed condition 'm_nLineHeight < 20' in // CCrystalTextView::CalcLineCharDim(). This caused painting defects // when using very small fonts. // // FEATURE: Some experiments with smooth scrolling, controlled by // m_bSmoothScroll member variable, by default turned off. // See ScrollToLine function for implementation details. //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// // 21-Feb-99 // Paul Selormey, James R. Twine // + FEATURE: description for Undo/Redo actions // + FEATURE: multiple MSVC-like bookmarks // + FEATURE: 'Disable backspace at beginning of line' option // + FEATURE: 'Disable drag-n-drop editing' option // // + FIX: ResetView() now virtual // + FEATURE: Added OnEditOperation() virtual: base for auto-indent, // smart indent etc. //////////////////////////////////////////////////////////////////////////// // 25-May-2002 // Michal Kowalski // Collapsible blocks // //////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "editcmd.h" #include "editreg.h" #include "CCrystalTextView.h" #include "CCrystalTextBuffer.h" #include "CFindTextDlg.h" #include "resource.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define TAB_CHARACTER _T('\xBB') #define SPACE_CHARACTER _T('\xB7') #define DEFAULT_PRINT_MARGIN 1000 // 10 millimeters #define SMOOTH_SCROLL_FACTOR 6 #define CRYSTAL_TIMER_DRAGSEL 1001 //////////////////////////////////////////////////////////////////////////// // CCrystalTextView IMPLEMENT_DYNCREATE(CCrystalTextView, CView) HINSTANCE CCrystalTextView::s_hResourceInst = NULL; BEGIN_MESSAGE_MAP(CCrystalTextView, CView) //{{AFX_MSG_MAP(CCrystalTextView) ON_WM_DESTROY() ON_WM_ERASEBKGND() ON_WM_SIZE() ON_WM_VSCROLL() ON_WM_SETCURSOR() ON_WM_LBUTTONDOWN() ON_WM_SETFOCUS() ON_WM_HSCROLL() ON_WM_LBUTTONUP() ON_WM_MOUSEMOVE() ON_WM_TIMER() ON_WM_KILLFOCUS() ON_WM_LBUTTONDBLCLK() ON_COMMAND(ID_EDIT_COPY, OnEditCopy) ON_UPDATE_COMMAND_UI(ID_EDIT_COPY, OnUpdateEditCopy) ON_COMMAND(ID_EDIT_SELECT_ALL, OnEditSelectAll) ON_UPDATE_COMMAND_UI(ID_EDIT_SELECT_ALL, OnUpdateEditSelectAll) ON_WM_RBUTTONDOWN() ON_WM_SYSCOLORCHANGE() ON_WM_CREATE() ON_COMMAND(ID_EDIT_FIND, OnEditFind) ON_COMMAND(ID_EDIT_REPEAT, OnEditRepeat) ON_UPDATE_COMMAND_UI(ID_EDIT_REPEAT, OnUpdateEditRepeat) ON_COMMAND(ID_EDIT_FIND_PREVIOUS, OnEditFindPrevious) ON_UPDATE_COMMAND_UI(ID_EDIT_FIND_PREVIOUS, OnUpdateEditFindPrevious) ON_WM_MOUSEWHEEL() ON_COMMAND(ID_EDIT_VIEW_TABS, OnEditViewTabs) ON_UPDATE_COMMAND_UI(ID_EDIT_VIEW_TABS, OnUpdateEditViewTabs) //}}AFX_MSG_MAP ON_COMMAND(ID_EDIT_CHAR_LEFT, OnCharLeft) ON_COMMAND(ID_EDIT_EXT_CHAR_LEFT, OnExtCharLeft) ON_COMMAND(ID_EDIT_CHAR_RIGHT, OnCharRight) ON_COMMAND(ID_EDIT_EXT_CHAR_RIGHT, OnExtCharRight) ON_COMMAND(ID_EDIT_WORD_LEFT, OnWordLeft) ON_COMMAND(ID_EDIT_EXT_WORD_LEFT, OnExtWordLeft) ON_COMMAND(ID_EDIT_WORD_RIGHT, OnWordRight) ON_COMMAND(ID_EDIT_EXT_WORD_RIGHT, OnExtWordRight) ON_COMMAND(ID_EDIT_LINE_UP, OnLineUp) ON_COMMAND(ID_EDIT_EXT_LINE_UP, OnExtLineUp) ON_COMMAND(ID_EDIT_LINE_DOWN, OnLineDown) ON_COMMAND(ID_EDIT_EXT_LINE_DOWN, OnExtLineDown) ON_COMMAND(ID_EDIT_SCROLL_UP, ScrollUp) ON_COMMAND(ID_EDIT_SCROLL_DOWN, ScrollDown) ON_COMMAND(ID_EDIT_PAGE_UP, OnPageUp) ON_COMMAND(ID_EDIT_EXT_PAGE_UP, OnExtPageUp) ON_COMMAND(ID_EDIT_PAGE_DOWN, OnPageDown) ON_COMMAND(ID_EDIT_EXT_PAGE_DOWN, OnExtPageDown) ON_COMMAND(ID_EDIT_LINE_END, OnLineEnd) ON_COMMAND(ID_EDIT_EXT_LINE_END, OnExtLineEnd) ON_COMMAND(ID_EDIT_HOME, OnHome) ON_COMMAND(ID_EDIT_EXT_HOME, OnExtHome) ON_COMMAND(ID_EDIT_TEXT_BEGIN, OnTextBegin) ON_COMMAND(ID_EDIT_EXT_TEXT_BEGIN, OnExtTextBegin) ON_COMMAND(ID_EDIT_TEXT_END, OnTextEnd) ON_COMMAND(ID_EDIT_EXT_TEXT_END, OnExtTextEnd) // Standard printing commands ON_COMMAND(ID_FILE_PAGE_SETUP, OnFilePageSetup) ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview) // Status ON_UPDATE_COMMAND_UI(ID_EDIT_INDICATOR_CRLF, OnUpdateIndicatorCRLF) ON_UPDATE_COMMAND_UI(ID_EDIT_INDICATOR_POSITION, OnUpdateIndicatorPosition) // Bookmarks ON_COMMAND_RANGE(ID_EDIT_TOGGLE_BOOKMARK0, ID_EDIT_TOGGLE_BOOKMARK9, OnToggleBookmark) ON_COMMAND_RANGE(ID_EDIT_GO_BOOKMARK0, ID_EDIT_GO_BOOKMARK9, OnGoBookmark) ON_COMMAND(ID_EDIT_CLEAR_BOOKMARKS, OnClearBookmarks) // More Bookmarks ON_COMMAND(ID_EDIT_TOGGLE_BOOKMARK, OnToggleBookmark) ON_COMMAND(ID_EDIT_GOTO_NEXT_BOOKMARK, OnNextBookmark) ON_COMMAND(ID_EDIT_GOTO_PREV_BOOKMARK, OnPrevBookmark) ON_COMMAND(ID_EDIT_CLEAR_ALL_BOOKMARKS, OnClearAllBookmarks) ON_UPDATE_COMMAND_UI(ID_EDIT_GOTO_NEXT_BOOKMARK, OnUpdateNextBookmark) ON_UPDATE_COMMAND_UI(ID_EDIT_GOTO_PREV_BOOKMARK, OnUpdatePrevBookmark) ON_UPDATE_COMMAND_UI(ID_EDIT_CLEAR_ALL_BOOKMARKS, OnUpdateClearAllBookmarks) // Collapsible blocks ON_COMMAND(ID_EDIT_TOGGLE_BLOCK, OnToggleCollapsibleBlock) ON_COMMAND(ID_EDIT_COLLAPSE_ALL, OnCollapseAllBlocks) ON_COMMAND(ID_EDIT_EXPAND_ALL, OnExpandAllBlocks) END_MESSAGE_MAP() #define EXPAND_PRIMITIVE(impl, func) \ void CCrystalTextView::On##func() { impl(FALSE); } \ void CCrystalTextView::OnExt##func() { impl(TRUE); } EXPAND_PRIMITIVE(MoveLeft, CharLeft) EXPAND_PRIMITIVE(MoveRight, CharRight) EXPAND_PRIMITIVE(MoveWordLeft, WordLeft) EXPAND_PRIMITIVE(MoveWordRight, WordRight) EXPAND_PRIMITIVE(MoveUp, LineUp) EXPAND_PRIMITIVE(MoveDown, LineDown) EXPAND_PRIMITIVE(MovePgUp, PageUp) EXPAND_PRIMITIVE(MovePgDn, PageDown) EXPAND_PRIMITIVE(MoveHome, Home) EXPAND_PRIMITIVE(MoveEnd, LineEnd) EXPAND_PRIMITIVE(MoveCtrlHome, TextBegin) EXPAND_PRIMITIVE(MoveCtrlEnd, TextEnd) #undef EXPAND_PRIMITIVE ///////////////////////////////////////////////////////////////////////////// // CCrystalTextView construction/destruction CCrystalTextView::CCrystalTextView() { m_bLastSearch = false; m_dwLastSearchFlags = 0; m_pszLastFindWhat = 0; m_bMultipleSearch = false; m_bCursorHidden = false; m_pCacheBitmap = 0; m_nLineHeight = m_nCharWidth = 0; m_nTabSize = 8; m_bViewTabs = false; m_bSelMargin = true; m_nScreenLines = m_nScreenChars = 0; m_nMaxLineLength = 0; m_nIdealCharPos = 0; m_bFocused = false; m_ptAnchor = CPoint(0, 0); //LOGFONT m_lfBaseFont; m_apFonts[0] = m_apFonts[1] = m_apFonts[2] = m_apFonts[3] = 0; m_pdwParseCookies = 0; m_nParseArraySize = 0; m_nActualLengthArraySize = 0; m_pnActualLineLength = 0; m_bPreparingToDrag = false; m_bDraggingText = false; m_bDragSelection = m_bWordSelection = m_bLineSelection = false; m_nDragSelTimer = 0; m_ptDrawSelStart = m_ptDrawSelEnd = CPoint(0, 0); m_ptCursorPos = CPoint(0, 0); m_ptSelStart = m_ptSelEnd = CPoint(0, 0); m_bBookmarkExist = false; m_pIcons = 0; m_pTextBuffer = 0; m_hAccel = 0; m_bVertScrollBarLocked = m_bHorzScrollBarLocked = false; m_ptDraggedTextBegin = m_ptDraggedTextEnd = CPoint(0, 0); m_bShowInactiveSelection = false; m_bDisableDragAndDrop = true; m_nPrintPages = 0; m_pnPages = 0; m_pPrintFont = 0; m_nPrintLineHeight = 0; m_bPrintHeader = m_bPrintFooter = false; m_ptPageArea.SetRectEmpty(); m_rcPrintArea.SetRectEmpty(); m_nTopLine = m_nOffsetChar = 0; m_bSmoothScroll = true; // AFX_ZERO_INIT_OBJECT(CView); // TODO: remove this crap ResetView(); } CCrystalTextView::~CCrystalTextView() { ASSERT(m_hAccel == NULL); ASSERT(m_pCacheBitmap == NULL); ASSERT(m_pTextBuffer == NULL); // Must be correctly detached if (m_pszLastFindWhat != NULL) free(m_pszLastFindWhat); if (m_pdwParseCookies != NULL) delete m_pdwParseCookies; if (m_pnActualLineLength != NULL) delete m_pnActualLineLength; } BOOL CCrystalTextView::PreCreateWindow(CREATESTRUCT& cs) { CWnd* pParentWnd= CWnd::FromHandlePermanent(cs.hwndParent); if (pParentWnd == NULL || ! pParentWnd->IsKindOf(RUNTIME_CLASS(CSplitterWnd))) { // View must always create its own scrollbars, // if only it's not used within splitter cs.style |= (WS_HSCROLL | WS_VSCROLL); } cs.lpszClass = AfxRegisterWndClass(CS_DBLCLKS); return CView::PreCreateWindow(cs); } ///////////////////////////////////////////////////////////////////////////// // CCrystalTextView drawing void CCrystalTextView::GetSelection(CPoint &ptStart, CPoint &ptEnd) { PrepareSelBounds(); ptStart = m_ptDrawSelStart; ptEnd = m_ptDrawSelEnd; } CCrystalTextBuffer *CCrystalTextView::LocateTextBuffer() { return NULL; } int CCrystalTextView::GetLineActualLength(int nLineIndex) { int nLineCount = GetLineCount(); ASSERT(nLineCount > 0); ASSERT(nLineIndex >= 0 && nLineIndex < nLineCount); if (m_pnActualLineLength == NULL) { m_pnActualLineLength = new int[nLineCount]; memset(m_pnActualLineLength, 0xff, sizeof(int) * nLineCount); m_nActualLengthArraySize = nLineCount; } if (m_pnActualLineLength[nLineIndex] >= 0) return m_pnActualLineLength[nLineIndex]; // Actual line length is not determined yet, let's calculate a little int nActualLength = 0; int nLength = GetLineLength(nLineIndex); if (nLength > 0) { LPCTSTR pszLine = GetLineChars(nLineIndex); LPTSTR pszChars = (LPTSTR) _alloca(sizeof(TCHAR) * (nLength + 1)); memcpy(pszChars, pszLine, sizeof(TCHAR) * nLength); pszChars[nLength] = 0; LPTSTR pszCurrent = pszChars; int nTabSize = GetTabSize(); for (;;) { #ifdef _UNICODE LPTSTR psz = wcschr(pszCurrent, L'\t'); #else LPTSTR psz = strchr(pszCurrent, '\t'); #endif if (psz == NULL) { nActualLength += (pszChars + nLength - pszCurrent); break; } nActualLength += (psz - pszCurrent); nActualLength += (nTabSize - nActualLength % nTabSize); pszCurrent = psz + 1; } } m_pnActualLineLength[nLineIndex] = nActualLength; return nActualLength; } void CCrystalTextView::ScrollToChar(int nNewOffsetChar, BOOL bNoSmoothScroll /*= FALSE*/, BOOL bTrackScrollBar /*= TRUE*/) { // For now, ignoring bNoSmoothScroll and m_bSmoothScroll if (m_nOffsetChar != nNewOffsetChar) { int nScrollChars = m_nOffsetChar - nNewOffsetChar; m_nOffsetChar = nNewOffsetChar; CRect rcScroll; GetClientRect(&rcScroll); rcScroll.left += GetMarginWidth(); ScrollWindow(nScrollChars * GetCharWidth(), 0, &rcScroll, &rcScroll); UpdateWindow(); if (bTrackScrollBar) RecalcHorzScrollBar(TRUE); } } void CCrystalTextView::ScrollToLine(int nNewTopLine, BOOL bNoSmoothScroll /*= FALSE*/, BOOL bTrackScrollBar /*= TRUE*/) { if (m_nTopLine != nNewTopLine) { if (bNoSmoothScroll || ! m_bSmoothScroll) { int nScrollLines= -CalcVisibleLines(m_nTopLine, nNewTopLine); m_nTopLine = nNewTopLine; ScrollWindow(0, nScrollLines * GetLineHeight()); UpdateWindow(); if (bTrackScrollBar) RecalcVertScrollBar(TRUE); } else { // Do smooth scrolling int nLineHeight = GetLineHeight(); if (m_nTopLine > nNewTopLine) { int nIncrement = (m_nTopLine - nNewTopLine) / SMOOTH_SCROLL_FACTOR + 1; while (m_nTopLine != nNewTopLine) { int nTopLine = m_nTopLine - nIncrement; if (nTopLine < nNewTopLine) nTopLine = nNewTopLine; int nScrollLines = nTopLine - m_nTopLine; m_nTopLine = nTopLine; ScrollWindow(0, - nLineHeight * nScrollLines); UpdateWindow(); if (bTrackScrollBar) RecalcVertScrollBar(TRUE); } } else { int nIncrement = (nNewTopLine - m_nTopLine) / SMOOTH_SCROLL_FACTOR + 1; while (m_nTopLine != nNewTopLine) { int nTopLine = m_nTopLine + nIncrement; if (nTopLine > nNewTopLine) nTopLine = nNewTopLine; int nScrollLines = nTopLine - m_nTopLine; m_nTopLine = nTopLine; ScrollWindow(0, - nLineHeight * nScrollLines); UpdateWindow(); if (bTrackScrollBar) RecalcVertScrollBar(TRUE); } } } } } void CCrystalTextView::ExpandChars(LPCTSTR pszChars, int nOffset, int nCount, CString &line) { if (nCount <= 0) { line = _T(""); return; } int nTabSize = GetTabSize(); int nActualOffset = 0; for (int I = 0; I < nOffset; I ++) { if (pszChars[I] == _T('\t')) nActualOffset += (nTabSize - nActualOffset % nTabSize); else nActualOffset ++; } pszChars += nOffset; int nLength = nCount; int nTabCount = 0; int I; for (I = 0; I < nLength; I ++) { if (pszChars[I] == _T('\t')) nTabCount ++; } LPTSTR pszBuf = line.GetBuffer(nLength + nTabCount * (nTabSize - 1) + 1); int nCurPos = 0; if (nTabCount > 0 || m_bViewTabs) { for (I = 0; I < nLength; I ++) { if (pszChars[I] == _T('\t')) { int nSpaces = nTabSize - (nActualOffset + nCurPos) % nTabSize; if (m_bViewTabs) { pszBuf[nCurPos ++] = TAB_CHARACTER; nSpaces --; } while (nSpaces > 0) { pszBuf[nCurPos ++] = _T(' '); nSpaces --; } } else { if (pszChars[I] == _T(' ') && m_bViewTabs) pszBuf[nCurPos] = SPACE_CHARACTER; else pszBuf[nCurPos] = pszChars[I]; nCurPos ++; } } } else { memcpy(pszBuf, pszChars, sizeof(TCHAR) * nLength); nCurPos = nLength; } pszBuf[nCurPos] = 0; line.ReleaseBuffer(); } void CCrystalTextView::DrawLineHelperImpl(CDC *pdc, CPoint &ptOrigin, const CRect &rcClip, LPCTSTR pszChars, int nOffset, int nCount) { ASSERT(nCount >= 0); if (nCount > 0) { CString line; ExpandChars(pszChars, nOffset, nCount, line); int nWidth = rcClip.right - ptOrigin.x; if (nWidth > 0) { int nCharWidth= GetCharWidth(); int nCount = line.GetLength(); int nCountFit = nWidth / nCharWidth + 1; if (nCount > nCountFit) nCount = nCountFit; std::vector<int> vWidths(nCount, nCharWidth); VERIFY(pdc->ExtTextOut(ptOrigin.x, ptOrigin.y, ETO_CLIPPED, &rcClip, line, nCount, &vWidths.front())); } ptOrigin.x += GetCharWidth() * line.GetLength(); } } void CCrystalTextView::DrawLineHelper(CDC *pdc, CPoint &ptOrigin, const CRect &rcClip, int nColorIndex, LPCTSTR pszChars, int nOffset, int nCount, CPoint ptTextPos) { if (nCount > 0) { if (m_bFocused || m_bShowInactiveSelection) { int nSelBegin = 0, nSelEnd = 0; if (m_ptDrawSelStart.y > ptTextPos.y) { nSelBegin = nCount; } else if (m_ptDrawSelStart.y == ptTextPos.y) { nSelBegin = m_ptDrawSelStart.x - ptTextPos.x; if (nSelBegin < 0) nSelBegin = 0; if (nSelBegin > nCount) nSelBegin = nCount; } if (m_ptDrawSelEnd.y > ptTextPos.y) { nSelEnd = nCount; } else if (m_ptDrawSelEnd.y == ptTextPos.y) { nSelEnd = m_ptDrawSelEnd.x - ptTextPos.x; if (nSelEnd < 0) nSelEnd = 0; if (nSelEnd > nCount) nSelEnd = nCount; } ASSERT(nSelBegin >= 0 && nSelBegin <= nCount); ASSERT(nSelEnd >= 0 && nSelEnd <= nCount); ASSERT(nSelBegin <= nSelEnd); // Draw part of the text before selection if (nSelBegin > 0) { DrawLineHelperImpl(pdc, ptOrigin, rcClip, pszChars, nOffset, nSelBegin); } if (nSelBegin < nSelEnd) { COLORREF crOldBk = pdc->SetBkColor(GetColor(COLORINDEX_SELBKGND)); // COLORREF crOldText = pdc->SetTextColor(GetColor(COLORINDEX_SELTEXT)); DrawLineHelperImpl(pdc, ptOrigin, rcClip, pszChars, nOffset + nSelBegin, nSelEnd - nSelBegin); pdc->SetBkColor(crOldBk); // pdc->SetTextColor(crOldText); } if (nSelEnd < nCount) { DrawLineHelperImpl(pdc, ptOrigin, rcClip, pszChars, nOffset + nSelEnd, nCount - nSelEnd); } } else { DrawLineHelperImpl(pdc, ptOrigin, rcClip, pszChars, nOffset, nCount); } } } void CCrystalTextView::GetLineColors(int nLineIndex, COLORREF &crBkgnd, COLORREF &crText, BOOL &bDrawWhitespace) { DWORD dwLineFlags = GetLineFlags(nLineIndex); bDrawWhitespace = TRUE; crText = RGB(255, 255, 255); if (dwLineFlags & LF_EXECUTION) { crBkgnd = RGB(0, 128, 0); return; } if (dwLineFlags & LF_BREAKPOINT) { crBkgnd = RGB(255, 0, 0); return; } if (dwLineFlags & LF_INVALID_BREAKPOINT) { crBkgnd = RGB(128, 128, 0); return; } crBkgnd = CLR_NONE; crText = CLR_NONE; bDrawWhitespace = FALSE; } DWORD CCrystalTextView::GetParseCookie(int nLineIndex) { int nLineCount = GetLineCount(); if (m_pdwParseCookies == NULL) { m_nParseArraySize = nLineCount; m_pdwParseCookies = new DWORD[nLineCount]; memset(m_pdwParseCookies, 0xff, nLineCount * sizeof(DWORD)); } if (nLineIndex < 0) return 0; if (m_pdwParseCookies[nLineIndex] != (DWORD) -1) return m_pdwParseCookies[nLineIndex]; int L = nLineIndex; while (L >= 0 && m_pdwParseCookies[L] == (DWORD) -1) L --; L ++; int nBlocks; while (L <= nLineIndex) { DWORD dwCookie = 0; if (L > 0) dwCookie = m_pdwParseCookies[L - 1]; ASSERT(dwCookie != (DWORD) -1); m_pdwParseCookies[L] = ParseLine(dwCookie, L, NULL, nBlocks); ASSERT(m_pdwParseCookies[L] != (DWORD) -1); L ++; } return m_pdwParseCookies[nLineIndex]; } void CCrystalTextView::DrawSingleLine(CDC *pdc, const CRect &rc, int nLineIndex) { ASSERT(nLineIndex >= -1 && nLineIndex < GetLineCount()); if (nLineIndex == -1) { // Draw line beyond the text pdc->FillSolidRect(rc, GetColor(COLORINDEX_WHITESPACE)); return; } /* else if (IsFirstLineOfCollapsedBlock(nLineIndex)) { // first line of collapsed block DrawEllipsis(pdc, rc); return; } */ // Acquire the background color for the current line BOOL bDrawWhitespace = FALSE; COLORREF crBkgnd, crText; GetLineColors(nLineIndex, crBkgnd, crText, bDrawWhitespace); if (crBkgnd == CLR_NONE) crBkgnd = GetColor(COLORINDEX_BKGND); int nLength = GetLineLength(nLineIndex); if (nLength == 0) { // MiK if (IsFirstLineOfCollapsedBlock(nLineIndex)) { DrawEllipsis(pdc, rc); } else { // Draw the empty line CRect rect = rc; if ((m_bFocused || m_bShowInactiveSelection) && IsInsideSelBlock(CPoint(0, nLineIndex))) { pdc->FillSolidRect(rect.left, rect.top, GetCharWidth(), rect.Height(), GetColor(COLORINDEX_SELBKGND)); rect.left += GetCharWidth(); } pdc->FillSolidRect(rect, bDrawWhitespace ? crBkgnd : GetColor(COLORINDEX_WHITESPACE)); } // parse line: give it a chance to mark collapsible blocks GetParseCookie(nLineIndex); return; } // Parse the line LPCTSTR pszChars = GetLineChars(nLineIndex); DWORD dwCookie = GetParseCookie(nLineIndex - 1); TEXTBLOCK *pBuf = (TEXTBLOCK *) _alloca(sizeof(TEXTBLOCK) * nLength * 3); int nBlocks = 0; m_pdwParseCookies[nLineIndex] = ParseLine(dwCookie, nLineIndex, pBuf, nBlocks); ASSERT(m_pdwParseCookies[nLineIndex] != (DWORD) -1); // Draw the line text CPoint origin(rc.left - m_nOffsetChar * GetCharWidth(), rc.top); pdc->SetBkColor(crBkgnd); if (crText != CLR_NONE) pdc->SetTextColor(crText); BOOL bColorSet = FALSE; if (nBlocks > 0) { ASSERT(pBuf[0].m_nCharPos >= 0 && pBuf[0].m_nCharPos <= nLength); if (crText == CLR_NONE) pdc->SetTextColor(GetColor(COLORINDEX_NORMALTEXT)); pdc->SelectObject(GetFont(GetItalic(COLORINDEX_NORMALTEXT), GetBold(COLORINDEX_NORMALTEXT))); DrawLineHelper(pdc, origin, rc, COLORINDEX_NORMALTEXT, pszChars, 0, pBuf[0].m_nCharPos, CPoint(0, nLineIndex)); for (int I = 0; I < nBlocks - 1; I ++) { ASSERT(pBuf[I].m_nCharPos >= 0 && pBuf[I].m_nCharPos <= nLength); if (crText == CLR_NONE) pdc->SetTextColor(GetColor(pBuf[I].m_nColorIndex)); pdc->SelectObject(GetFont(GetItalic(pBuf[I].m_nColorIndex), GetBold(pBuf[I].m_nColorIndex))); DrawLineHelper(pdc, origin, rc, pBuf[I].m_nColorIndex, pszChars, pBuf[I].m_nCharPos, pBuf[I + 1].m_nCharPos - pBuf[I].m_nCharPos, CPoint(pBuf[I].m_nCharPos, nLineIndex)); } ASSERT(pBuf[nBlocks - 1].m_nCharPos >= 0 && pBuf[nBlocks - 1].m_nCharPos <= nLength); if (crText == CLR_NONE) pdc->SetTextColor(GetColor(pBuf[nBlocks - 1].m_nColorIndex)); pdc->SelectObject(GetFont(GetItalic(pBuf[nBlocks - 1].m_nColorIndex), GetBold(pBuf[nBlocks - 1].m_nColorIndex))); DrawLineHelper(pdc, origin, rc, pBuf[nBlocks - 1].m_nColorIndex, pszChars, pBuf[nBlocks - 1].m_nCharPos, nLength - pBuf[nBlocks - 1].m_nCharPos, CPoint(pBuf[nBlocks - 1].m_nCharPos, nLineIndex)); } else { if (crText == CLR_NONE) pdc->SetTextColor(GetColor(COLORINDEX_NORMALTEXT)); pdc->SelectObject(GetFont(GetItalic(COLORINDEX_NORMALTEXT), GetBold(COLORINDEX_NORMALTEXT))); DrawLineHelper(pdc, origin, rc, COLORINDEX_NORMALTEXT, pszChars, 0, nLength, CPoint(0, nLineIndex)); } // Draw whitespaces to the left of the text CRect frect = rc; if (origin.x > frect.left) frect.left = origin.x; if (frect.right > frect.left) { if ((m_bFocused || m_bShowInactiveSelection) && IsInsideSelBlock(CPoint(nLength, nLineIndex))) { pdc->FillSolidRect(frect.left, frect.top, GetCharWidth(), frect.Height(), GetColor(COLORINDEX_SELBKGND)); frect.left += GetCharWidth(); } if (frect.right > frect.left) pdc->FillSolidRect(frect, bDrawWhitespace ? crBkgnd : GetColor(COLORINDEX_WHITESPACE)); // MiK if (IsFirstLineOfCollapsedBlock(nLineIndex)) { DrawEllipsis(pdc, frect); } } } COLORREF CCrystalTextView::GetColor(int nColorIndex) { switch (nColorIndex) { case COLORINDEX_WHITESPACE: case COLORINDEX_BKGND: return ::GetSysColor(COLOR_WINDOW); case COLORINDEX_NORMALTEXT: return ::GetSysColor(COLOR_WINDOWTEXT); case COLORINDEX_SELMARGIN: { COLORREF rgbGray= ::GetSysColor(COLOR_3DFACE); return RGB(0x80 + GetRValue(rgbGray) / 2, 0x80 + GetGValue(rgbGray) / 2, 0x80 + GetBValue(rgbGray) / 2); } // return RGB(240,240,240); //::GetSysColor(COLOR_SCROLLBAR); case COLORINDEX_PREPROCESSOR: return RGB(128, 0, 128); case COLORINDEX_COMMENT: return RGB(128, 128, 128); // [JRT]: Enabled Support For Numbers... case COLORINDEX_NUMBER: return RGB(0, 0, 255); // [JRT]: Support For C/C++ Operators case COLORINDEX_OPERATOR: return RGB(128, 0, 0); case COLORINDEX_KEYWORD: return RGB(0, 0, 160); case COLORINDEX_SELBKGND: return RGB(192, 192, 224); case COLORINDEX_SELTEXT: return RGB(255, 255, 255); case COLORINDEX_STRING: return RGB(0, 128, 128); case COLORINDEX_ELLIPSIS: return RGB(128, 128, 128); } return RGB(0, 0, 0); } DWORD CCrystalTextView::GetLineFlags(int nLineIndex) { if (m_pTextBuffer == NULL) return 0; return m_pTextBuffer->GetLineFlags(nLineIndex); } void CCrystalTextView::DrawMargin(CDC *pdc, const CRect &rect, int nLineIndex) { if (!m_bSelMargin) { pdc->FillSolidRect(rect, GetColor(COLORINDEX_BKGND)); return; } pdc->FillSolidRect(rect, GetColor(COLORINDEX_SELMARGIN)); if (nLineIndex < 0) return; int nImageIndex= -1; DWORD dwLineFlags= GetLineFlags(nLineIndex); static const DWORD adwFlags[] = { LF_EXECUTION, LF_BREAKPOINT, LF_COMPILATION_ERROR, LF_BOOKMARK(1), LF_BOOKMARK(2), LF_BOOKMARK(3), LF_BOOKMARK(4), LF_BOOKMARK(5), LF_BOOKMARK(6), LF_BOOKMARK(7), LF_BOOKMARK(8), LF_BOOKMARK(9), LF_BOOKMARK(0), LF_BOOKMARKS, LF_INVALID_BREAKPOINT }; for (int I = 0; I <= sizeof(adwFlags) / sizeof(adwFlags[0]); I ++) { if ((dwLineFlags & adwFlags[I]) != 0) { nImageIndex = I; break; } } if (nImageIndex >= 0) DrawMarginIcon(pdc, rect, nImageIndex); // MiK: draw expand/collapse mark on top of other marks int nIndex= nLineIndex - m_nTopLine; bool bInsideBlock= nIndex >= 0 && nIndex < (int)m_vLineInsideBlock.size() ? m_vLineInsideBlock[nIndex] : false; nImageIndex = sizeof(adwFlags) / sizeof(adwFlags[0]); if (bInsideBlock) DrawMarginIcon(pdc, rect, nImageIndex + 3); if (dwLineFlags & (LF_COLLAPSIBLE_BLOCK_START | LF_COLLAPSIBLE_BLOCK_END)) { int nImg= 0; if (dwLineFlags & LF_COLLAPSIBLE_BLOCK_START && dwLineFlags & LF_COLLAPSED_BLOCK) nImg = 2; else if (dwLineFlags & LF_COLLAPSIBLE_BLOCK_END) nImg = 1; DrawMarginIcon(pdc, rect, nImageIndex + nImg); } DrawMarginMarker(nLineIndex, pdc, rect); } void CCrystalTextView::DrawMarginMarker(int nLine, CDC* pDC, const CRect &rect) {} void CCrystalTextView::DrawMarginIcon(CDC* pDC, const CRect &rect, int nImageIndex) { if (nImageIndex >= 0) { if (m_pIcons == NULL) { m_pIcons = new CImageList; VERIFY(m_pIcons->Create(IDR_MARGIN_ICONS, 16, 16, RGB(255, 0, 255))); } CPoint pt(rect.left + 2, rect.top + (rect.Height() - 16) / 2); VERIFY(m_pIcons->Draw(pDC, nImageIndex, pt, ILD_TRANSPARENT)); } } BOOL CCrystalTextView::IsInsideSelBlock(CPoint ptTextPos) { ASSERT_VALIDTEXTPOS(ptTextPos); if (ptTextPos.y < m_ptDrawSelStart.y) return FALSE; if (ptTextPos.y > m_ptDrawSelEnd.y) return FALSE; if (ptTextPos.y < m_ptDrawSelEnd.y && ptTextPos.y > m_ptDrawSelStart.y) return TRUE; if (m_ptDrawSelStart.y < m_ptDrawSelEnd.y) { if (ptTextPos.y == m_ptDrawSelEnd.y) return ptTextPos.x < m_ptDrawSelEnd.x; ASSERT(ptTextPos.y == m_ptDrawSelStart.y); return ptTextPos.x >= m_ptDrawSelStart.x; } ASSERT(m_ptDrawSelStart.y == m_ptDrawSelEnd.y); return ptTextPos.x >= m_ptDrawSelStart.x && ptTextPos.x < m_ptDrawSelEnd.x; } BOOL CCrystalTextView::IsInsideSelection(const CPoint &ptTextPos) { PrepareSelBounds(); return IsInsideSelBlock(ptTextPos); } void CCrystalTextView::PrepareSelBounds() { if (m_ptSelStart.y < m_ptSelEnd.y || (m_ptSelStart.y == m_ptSelEnd.y && m_ptSelStart.x < m_ptSelEnd.x)) { m_ptDrawSelStart = m_ptSelStart; m_ptDrawSelEnd = m_ptSelEnd; } else { m_ptDrawSelStart = m_ptSelEnd; m_ptDrawSelEnd = m_ptSelStart; } } void CCrystalTextView::OnDraw(CDC* pdc) { CRect rcClient; GetClientRect(rcClient); int nLineCount = GetLineCount(); int nLineHeight = GetLineHeight(); PrepareSelBounds(); CDC cacheDC; cacheDC.CreateCompatibleDC(pdc); if (cacheDC.m_hDC == 0) return; if (m_pCacheBitmap == NULL) { m_pCacheBitmap = new CBitmap; VERIFY(m_pCacheBitmap->CreateCompatibleBitmap(pdc, rcClient.Width(), nLineHeight)); } CBitmap* pOldBitmap= cacheDC.SelectObject(m_pCacheBitmap); CRect rcLine; rcLine = rcClient; rcLine.bottom = rcLine.top + nLineHeight; CRect rcCacheMargin(0, 0, GetMarginWidth(), nLineHeight); CRect rcCacheLine(GetMarginWidth(), 0, rcLine.Width(), nLineHeight); // block vertical lines support FindBlockBoundaries(m_nTopLine, rcClient.Height() / nLineHeight + 1); for (int nCurrentLine = m_nTopLine; rcLine.top < rcClient.bottom; ++nCurrentLine) { int nLineIndex= nCurrentLine < nLineCount ? nCurrentLine : -1; if (IsLineHidden(nCurrentLine)) { // hidden lines inside collapsed block continue; // do not draw hidden lines } else // normal (visible) lines { if (pdc->RectVisible(rcLine)) { DrawMargin(&cacheDC, rcCacheMargin, nLineIndex); DrawSingleLine(&cacheDC, rcCacheLine, nLineIndex); VERIFY(pdc->BitBlt(rcLine.left, rcLine.top, rcLine.Width(), rcLine.Height(), &cacheDC, 0, 0, SRCCOPY)); } } rcLine.OffsetRect(0, nLineHeight); } cacheDC.SelectObject(pOldBitmap); cacheDC.DeleteDC(); } // This fn tries to determine if lines displayed lie inside collapsible text blocks // // (it's sensitive to spurious block ends; just like whole collapsing code; try // a few closing brackets '}' without corresponding '{' ones to see what happens // with lines below) // void CCrystalTextView::FindBlockBoundaries(int nTopLine, int nLines) { // this vector will tell me whether line N lies inside text block m_vLineInsideBlock.clear(); if (nLines < 1 || m_pTextBuffer == NULL) return; int nLineCount= m_pTextBuffer->GetLineCount(); if (nTopLine >= nLineCount) return; int nLastLine= FindVisibleLine(nTopLine, nLines); int nCount= nLastLine - nTopLine + 1; m_vLineInsideBlock.resize(nCount); // text block nesting depth int nLevel= 0; ASSERT(nTopLine >= 0); int nLineFrom = nTopLine; std::vector<bool>::iterator itInside= m_vLineInsideBlock.begin(); std::vector<bool>::iterator itEnd= m_vLineInsideBlock.end(); for (int nLine= nTopLine, nIndex= 0; nLines > 0; ++itInside) { DWORD dwFlags= m_pTextBuffer->GetLineFlags(nLine); if (dwFlags & LF_COLLAPSIBLE_BLOCK_END) --nLevel; if (nLevel <= 0 && nLineFrom > 0) { // look outside (this is up); are we still inside a block? int nLineIndex= nLineFrom - 1; for (; nLineIndex >= 0; --nLineIndex) { DWORD dwFlags= m_pTextBuffer->GetLineFlags(nLineIndex); if (dwFlags & LF_COLLAPSIBLE_BLOCK_END) --nLevel; if (dwFlags & LF_COLLAPSIBLE_BLOCK_START) if (++nLevel > 0) break; } nLineFrom = nLineIndex; } ASSERT(itInside < itEnd); *itInside = nLevel > 0; if (dwFlags & LF_COLLAPSIBLE_BLOCK_START) ++nLevel; if (!IsLineHidden(nLine)) --nLines; if (++nLine >= nLineCount) break; if (itInside == itEnd) break; } std::fill(itInside, itEnd, false); } void CCrystalTextView::ResetView() { m_nTopLine = 0; m_nOffsetChar = 0; m_nLineHeight = -1; m_nCharWidth = -1; m_nTabSize = 4; m_nMaxLineLength = -1; m_nScreenLines = -1; m_nScreenChars = -1; m_nIdealCharPos = -1; m_ptAnchor.x = 0; m_ptAnchor.y = 0; if (m_pIcons != NULL) { delete m_pIcons; m_pIcons = NULL; } for (int I = 0; I < 4; I ++) { if (m_apFonts[I] != NULL) { m_apFonts[I]->DeleteObject(); delete m_apFonts[I]; m_apFonts[I] = NULL; } } if (m_pdwParseCookies != NULL) { delete m_pdwParseCookies; m_pdwParseCookies = NULL; } if (m_pnActualLineLength != NULL) { delete m_pnActualLineLength; m_pnActualLineLength = NULL; } m_nParseArraySize = 0; m_nActualLengthArraySize = 0; m_ptCursorPos.x = 0; m_ptCursorPos.y = 0; m_ptSelStart = m_ptSelEnd = m_ptCursorPos; m_bDragSelection = FALSE; m_bVertScrollBarLocked = FALSE; m_bHorzScrollBarLocked = FALSE; if (::IsWindow(m_hWnd)) UpdateCaret(); m_bLastSearch = FALSE; m_bShowInactiveSelection = FALSE; m_bPrintHeader = FALSE; m_bPrintFooter = TRUE; m_bBookmarkExist = FALSE; // More bookmarks m_bMultipleSearch = FALSE; // More search } void CCrystalTextView::UpdateCaret() { ASSERT_VALIDTEXTPOS(m_ptCursorPos); if (m_bFocused && ! m_bCursorHidden && CalculateActualOffset(m_ptCursorPos.y, m_ptCursorPos.x) >= m_nOffsetChar) { CreateSolidCaret(2, GetLineHeight()); SetCaretPos(TextToClient(m_ptCursorPos)); ShowCaret(); } else { HideCaret(); } CaretMoved(); } int CCrystalTextView::GetTabSize() { ASSERT(m_nTabSize >= 0 && m_nTabSize <= 64); return m_nTabSize; } void CCrystalTextView::SetTabSize(int nTabSize) { ASSERT(nTabSize >= 0 && nTabSize <= 64); if (m_nTabSize != nTabSize) { m_nTabSize = nTabSize; if (m_pnActualLineLength != NULL) { delete m_pnActualLineLength; m_pnActualLineLength = NULL; } m_nActualLengthArraySize = 0; m_nMaxLineLength = -1; RecalcHorzScrollBar(); Invalidate(); UpdateCaret(); } } CFont *CCrystalTextView::GetFont(BOOL bItalic /*= FALSE*/, BOOL bBold /*= FALSE*/) { int nIndex = 0; if (bBold) nIndex |= 1; if (bItalic) nIndex |= 2; if (m_apFonts[nIndex] == NULL) { m_apFonts[nIndex] = new CFont; m_lfBaseFont.lfWeight = bBold ? FW_BOLD : FW_NORMAL; m_lfBaseFont.lfItalic = (BYTE) bItalic; if (! m_apFonts[nIndex]->CreateFontIndirect(&m_lfBaseFont)) { delete m_apFonts[nIndex]; m_apFonts[nIndex] = NULL; return CView::GetFont(); } } return m_apFonts[nIndex]; } void CCrystalTextView::CalcLineCharDim() { CDC *pdc = GetDC(); CFont *pOldFont = pdc->SelectObject(GetFont()); CSize szCharExt = pdc->GetTextExtent(_T("X")); m_nLineHeight = szCharExt.cy; if (m_nLineHeight < 1) m_nLineHeight = 1; m_nCharWidth = szCharExt.cx; /* TEXTMETRIC tm; if (pdc->GetTextMetrics(&tm)) m_nCharWidth -= tm.tmOverhang; */ pdc->SelectObject(pOldFont); ReleaseDC(pdc); } int CCrystalTextView::GetLineHeight() { if (m_nLineHeight == -1) CalcLineCharDim(); return m_nLineHeight; } int CCrystalTextView::GetCharWidth() { if (m_nCharWidth == -1) CalcLineCharDim(); return m_nCharWidth; } int CCrystalTextView::GetMaxLineLength() { if (m_nMaxLineLength == -1) { m_nMaxLineLength = 0; int nLineCount = GetLineCount(); for (int I = 0; I < nLineCount; I ++) { int nActualLength = GetLineActualLength(I); if (m_nMaxLineLength < nActualLength) m_nMaxLineLength = nActualLength; } } return m_nMaxLineLength; } CCrystalTextView *CCrystalTextView::GetSiblingView(int nRow, int nCol) { CSplitterWnd *pSplitter = GetParentSplitter(this, FALSE); if (pSplitter == NULL) return NULL; CWnd *pWnd = CWnd::FromHandlePermanent( ::GetDlgItem(pSplitter->m_hWnd, pSplitter->IdFromRowCol(nRow, nCol))); if (pWnd == NULL || ! pWnd->IsKindOf(RUNTIME_CLASS(CCrystalTextView))) return NULL; return (CCrystalTextView *) pWnd; } void CCrystalTextView::OnInitialUpdate() { CView::OnInitialUpdate(); AttachToBuffer(NULL); CSplitterWnd *pSplitter = GetParentSplitter(this, FALSE); if (pSplitter != NULL) { // See CSplitterWnd::IdFromRowCol() implementation int nRow = (GetDlgCtrlID() - AFX_IDW_PANE_FIRST) / 16; int nCol = (GetDlgCtrlID() - AFX_IDW_PANE_FIRST) % 16; ASSERT(nRow >= 0 && nRow < pSplitter->GetRowCount()); ASSERT(nCol >= 0 && nCol < pSplitter->GetColumnCount()); if (nRow > 0) { CCrystalTextView *pSiblingView = GetSiblingView(0, nCol); if (pSiblingView != NULL && pSiblingView != this) { m_nOffsetChar = pSiblingView->m_nOffsetChar; ASSERT(m_nOffsetChar >= 0 && m_nOffsetChar <= GetMaxLineLength()); } } if (nCol > 0) { CCrystalTextView *pSiblingView = GetSiblingView(nRow, 0); if (pSiblingView != NULL && pSiblingView != this) { m_nTopLine = pSiblingView->m_nTopLine; ASSERT(m_nTopLine >= 0 && m_nTopLine < GetLineCount()); } } } // MiK: parse all to update collapsible blocks GetParseCookie(GetLineCount() - 1); } ///////////////////////////////////////////////////////////////////////////// // CCrystalTextView printing void CCrystalTextView::OnPrepareDC(CDC* pDC, CPrintInfo* pInfo) { CView::OnPrepareDC(pDC, pInfo); if (pInfo != NULL) { pInfo->m_bContinuePrinting = TRUE; if (m_pnPages != NULL && (int) pInfo->m_nCurPage > m_nPrintPages) pInfo->m_bContinuePrinting = FALSE; } } BOOL CCrystalTextView::OnPreparePrinting(CPrintInfo* pInfo) { return DoPreparePrinting(pInfo); } int CCrystalTextView::PrintLineHeight(CDC *pdc, int nLine) { ASSERT(nLine >= 0 && nLine < GetLineCount()); ASSERT(m_nPrintLineHeight > 0); int nLength = GetLineLength(nLine); if (nLength == 0) return m_nPrintLineHeight; CString line; LPCTSTR pszChars = GetLineChars(nLine); ExpandChars(pszChars, 0, nLength, line); CRect rcPrintArea = m_rcPrintArea; pdc->DrawText(line, &rcPrintArea, DT_LEFT | DT_NOPREFIX | DT_TOP | DT_WORDBREAK | DT_CALCRECT); return rcPrintArea.Height(); } void CCrystalTextView::GetPrintHeaderText(int nPageNum, CString &text) { ASSERT(m_bPrintHeader); text = _T(""); } void CCrystalTextView::GetPrintFooterText(int nPageNum, CString &text) { ASSERT(m_bPrintFooter); text.Format(_T("Page %d/%d"), nPageNum, m_nPrintPages); } void CCrystalTextView::PrintHeader(CDC *pdc, int nPageNum) { CRect rcHeader = m_rcPrintArea; rcHeader.bottom = rcHeader.top; rcHeader.top -= (m_nPrintLineHeight + m_nPrintLineHeight / 2); CString text; GetPrintHeaderText(nPageNum, text); if (! text.IsEmpty()) pdc->DrawText(text, &rcHeader, DT_CENTER | DT_NOPREFIX | DT_TOP | DT_SINGLELINE); } void CCrystalTextView::PrintFooter(CDC *pdc, int nPageNum) { CRect rcFooter = m_rcPrintArea; rcFooter.top = rcFooter.bottom; rcFooter.bottom += (m_nPrintLineHeight + m_nPrintLineHeight / 2); CString text; GetPrintFooterText(nPageNum, text); if (! text.IsEmpty()) pdc->DrawText(text, &rcFooter, DT_CENTER | DT_NOPREFIX | DT_BOTTOM | DT_SINGLELINE); } void CCrystalTextView::RecalcPageLayouts(CDC *pdc, CPrintInfo *pInfo) { m_ptPageArea = pInfo->m_rectDraw; m_ptPageArea.NormalizeRect(); m_nPrintLineHeight = pdc->GetTextExtent(_T("X")).cy; m_rcPrintArea = m_ptPageArea; CSize szTopLeft, szBottomRight; CWinApp *pApp = AfxGetApp(); ASSERT(pApp != NULL); szTopLeft.cx = pApp->GetProfileInt(REG_PAGE_SUBKEY, REG_MARGIN_LEFT, DEFAULT_PRINT_MARGIN); szBottomRight.cx = pApp->GetProfileInt(REG_PAGE_SUBKEY, REG_MARGIN_RIGHT, DEFAULT_PRINT_MARGIN); szTopLeft.cy = pApp->GetProfileInt(REG_PAGE_SUBKEY, REG_MARGIN_TOP, DEFAULT_PRINT_MARGIN); szBottomRight.cy = pApp->GetProfileInt(REG_PAGE_SUBKEY, REG_MARGIN_BOTTOM, DEFAULT_PRINT_MARGIN); pdc->HIMETRICtoLP(&szTopLeft); pdc->HIMETRICtoLP(&szBottomRight); m_rcPrintArea.left += szTopLeft.cx; m_rcPrintArea.right -= szBottomRight.cx; m_rcPrintArea.top += szTopLeft.cy; m_rcPrintArea.bottom -= szBottomRight.cy; if (m_bPrintHeader) m_rcPrintArea.top += m_nPrintLineHeight + m_nPrintLineHeight / 2; if (m_bPrintFooter) m_rcPrintArea.bottom += m_nPrintLineHeight + m_nPrintLineHeight / 2; int nLimit = 32; m_nPrintPages = 1; m_pnPages = new int[nLimit]; m_pnPages[0] = 0; int nLineCount = GetLineCount(); int nLine = 1; int y = m_rcPrintArea.top + PrintLineHeight(pdc, 0); while (nLine < nLineCount) { int nHeight = PrintLineHeight(pdc, nLine); if (y + nHeight <= m_rcPrintArea.bottom) { y += nHeight; } else { ASSERT(nLimit >= m_nPrintPages); if (nLimit <= m_nPrintPages) { nLimit += 32; int *pnNewPages = new int[nLimit]; memcpy(pnNewPages, m_pnPages, sizeof(int) * m_nPrintPages); delete m_pnPages; m_pnPages = pnNewPages; } ASSERT(nLimit > m_nPrintPages); m_pnPages[m_nPrintPages ++] = nLine; y = m_rcPrintArea.top + nHeight; } nLine ++; } } void CCrystalTextView::OnBeginPrinting(CDC *pdc, CPrintInfo *pInfo) { ASSERT(m_pnPages == NULL); ASSERT(m_pPrintFont == NULL); CFont *pDisplayFont = GetFont(); LOGFONT lf; pDisplayFont->GetLogFont(&lf); CDC *pDisplayDC = GetDC(); lf.lfHeight = MulDiv(lf.lfHeight, pdc->GetDeviceCaps(LOGPIXELSY), pDisplayDC->GetDeviceCaps(LOGPIXELSY) * 2); lf.lfWidth = MulDiv(lf.lfWidth, pdc->GetDeviceCaps(LOGPIXELSX), pDisplayDC->GetDeviceCaps(LOGPIXELSX) * 2); ReleaseDC(pDisplayDC); m_pPrintFont = new CFont; if (! m_pPrintFont->CreateFontIndirect(&lf)) { delete m_pPrintFont; m_pPrintFont = NULL; return; } pdc->SelectObject(m_pPrintFont); } void CCrystalTextView::OnEndPrinting(CDC *pdc, CPrintInfo *pInfo) { if (m_pPrintFont != NULL) { delete m_pPrintFont; m_pPrintFont = NULL; } if (m_pnPages != NULL) { delete m_pnPages; m_pnPages = NULL; } m_nPrintPages = 0; m_nPrintLineHeight = 0; } void CCrystalTextView::OnPrint(CDC* pdc, CPrintInfo* pInfo) { if (m_pnPages == NULL) { RecalcPageLayouts(pdc, pInfo); ASSERT(m_pnPages != NULL); } ASSERT(pInfo->m_nCurPage >= 1 && (int) pInfo->m_nCurPage <= m_nPrintPages); int nLine = m_pnPages[pInfo->m_nCurPage - 1]; int nEndLine = GetLineCount(); if ((int) pInfo->m_nCurPage < m_nPrintPages) nEndLine = m_pnPages[pInfo->m_nCurPage]; TRACE(_T("Printing page %d of %d, lines %d - %d\n"), pInfo->m_nCurPage, m_nPrintPages, nLine, nEndLine - 1); if (m_bPrintHeader) PrintHeader(pdc, pInfo->m_nCurPage); if (m_bPrintFooter) PrintFooter(pdc, pInfo->m_nCurPage); int y = m_rcPrintArea.top; for (; nLine < nEndLine; nLine ++) { int nLineLength = GetLineLength(nLine); if (nLineLength == 0) { y += m_nPrintLineHeight; continue; } CRect rcPrintRect = m_rcPrintArea; rcPrintRect.top = y; LPCTSTR pszChars = GetLineChars(nLine); CString line; ExpandChars(pszChars, 0, nLineLength, line); y += pdc->DrawText(line, &rcPrintRect, DT_LEFT | DT_NOPREFIX | DT_TOP | DT_WORDBREAK); } } ///////////////////////////////////////////////////////////////////////////// // CCrystalTextView message handlers int CCrystalTextView::GetLineCount() { if (m_pTextBuffer == NULL) return 1; // Single empty line int nLineCount = m_pTextBuffer->GetLineCount(); ASSERT(nLineCount > 0); return nLineCount; } int CCrystalTextView::GetLineLength(int nLineIndex) { if (m_pTextBuffer == NULL) return 0; return m_pTextBuffer->GetLineLength(nLineIndex); } LPCTSTR CCrystalTextView::GetLineChars(int nLineIndex) { if (m_pTextBuffer == NULL) return NULL; return m_pTextBuffer->GetLineChars(nLineIndex); } void CCrystalTextView::AttachToBuffer(CCrystalTextBuffer *pBuf /*= NULL*/) { if (m_pTextBuffer != NULL) m_pTextBuffer->RemoveView(this); if (pBuf == NULL) { pBuf = LocateTextBuffer(); // ... } m_pTextBuffer = pBuf; if (m_pTextBuffer != NULL) m_pTextBuffer->AddView(this); ResetView(); // Init scrollbars CScrollBar *pVertScrollBarCtrl = GetScrollBarCtrl(SB_VERT); if (pVertScrollBarCtrl != NULL) pVertScrollBarCtrl->EnableScrollBar(GetScreenLines() >= GetLineCount() ? ESB_DISABLE_BOTH : ESB_ENABLE_BOTH); CScrollBar *pHorzScrollBarCtrl = GetScrollBarCtrl(SB_HORZ); if (pHorzScrollBarCtrl != NULL) pHorzScrollBarCtrl->EnableScrollBar(GetScreenChars() >= GetMaxLineLength() ? ESB_DISABLE_BOTH : ESB_ENABLE_BOTH); // Update scrollbars RecalcVertScrollBar(); RecalcHorzScrollBar(); } void CCrystalTextView::DetachFromBuffer() { if (m_pTextBuffer != NULL) { m_pTextBuffer->RemoveView(this); m_pTextBuffer = NULL; ResetView(); } } int CCrystalTextView::GetScreenLines() { if (m_nScreenLines == -1) { CRect rect; GetClientRect(&rect); m_nScreenLines = rect.Height() / GetLineHeight(); } return m_nScreenLines; } BOOL CCrystalTextView::GetItalic(int nColorIndex) { return FALSE; } BOOL CCrystalTextView::GetBold(int nColorIndex) { // if (nColorIndex == COLORINDEX_KEYWORD) // return true; return FALSE; } int CCrystalTextView::GetScreenChars() { if (m_nScreenChars == -1) { CRect rect; GetClientRect(&rect); m_nScreenChars = (rect.Width() - GetMarginWidth()) / GetCharWidth(); } return m_nScreenChars; } void CCrystalTextView::OnDestroy() { DetachFromBuffer(); m_hAccel = NULL; CView::OnDestroy(); for (int I = 0; I < 4; I ++) { if (m_apFonts[I] != NULL) { m_apFonts[I]->DeleteObject(); delete m_apFonts[I]; m_apFonts[I] = NULL; } } if (m_pCacheBitmap != NULL) { delete m_pCacheBitmap; m_pCacheBitmap = NULL; } } BOOL CCrystalTextView::OnEraseBkgnd(CDC *pdc) { return TRUE; } void CCrystalTextView::OnSize(UINT nType, int cx, int cy) { CView::OnSize(nType, cx, cy); if (m_pCacheBitmap != NULL) { m_pCacheBitmap->DeleteObject(); delete m_pCacheBitmap; m_pCacheBitmap = NULL; } m_nScreenLines = -1; m_nScreenChars = -1; RecalcVertScrollBar(); RecalcHorzScrollBar(); } void CCrystalTextView::UpdateSiblingScrollPos(BOOL bHorz) { CSplitterWnd *pSplitterWnd = GetParentSplitter(this, FALSE); if (pSplitterWnd != NULL) { // See CSplitterWnd::IdFromRowCol() implementation for details int nCurrentRow = (GetDlgCtrlID() - AFX_IDW_PANE_FIRST) / 16; int nCurrentCol = (GetDlgCtrlID() - AFX_IDW_PANE_FIRST) % 16; ASSERT(nCurrentRow >= 0 && nCurrentRow < pSplitterWnd->GetRowCount()); ASSERT(nCurrentCol >= 0 && nCurrentCol < pSplitterWnd->GetColumnCount()); if (bHorz) { int nCols = pSplitterWnd->GetColumnCount(); for (int nCol = 0; nCol < nCols; nCol ++) { if (nCol != nCurrentCol) // We don't need to update ourselves { CCrystalTextView *pSiblingView = GetSiblingView(nCurrentRow, nCol); if (pSiblingView != NULL) pSiblingView->OnUpdateSibling(this, TRUE); } } } else { int nRows = pSplitterWnd->GetRowCount(); for (int nRow = 0; nRow < nRows; nRow ++) { if (nRow != nCurrentRow) // We don't need to update ourselves { CCrystalTextView *pSiblingView = GetSiblingView(nRow, nCurrentCol); if (pSiblingView != NULL) pSiblingView->OnUpdateSibling(this, FALSE); } } } } } void CCrystalTextView::OnUpdateSibling(CCrystalTextView *pUpdateSource, BOOL bHorz) { if (pUpdateSource != this) { ASSERT(pUpdateSource != NULL); ASSERT_KINDOF(CCrystalTextView, pUpdateSource); if (bHorz) { ASSERT(pUpdateSource->m_nTopLine >= 0); ASSERT(pUpdateSource->m_nTopLine < GetLineCount()); if (pUpdateSource->m_nTopLine != m_nTopLine) { ScrollToLine(pUpdateSource->m_nTopLine, TRUE, FALSE); UpdateCaret(); } } else { ASSERT(pUpdateSource->m_nOffsetChar >= 0); ASSERT(pUpdateSource->m_nOffsetChar < GetMaxLineLength()); if (pUpdateSource->m_nOffsetChar != m_nOffsetChar) { ScrollToChar(pUpdateSource->m_nOffsetChar, TRUE, FALSE); UpdateCaret(); } } } } void CCrystalTextView::RecalcVertScrollBar(BOOL bPositionOnly /*= FALSE*/) { SCROLLINFO si; si.cbSize = sizeof(si); if (bPositionOnly) { si.fMask = SIF_POS; // si.nPos = m_nTopLine; // MiK si.nPos = CalcVisibleLines(0, m_nTopLine); } else { int nVisLines= CalcVisibleLines(); if (GetScreenLines() >= nVisLines /*MiK GetLineCount()*/ && m_nTopLine > 0) { m_nTopLine = 0; Invalidate(); UpdateCaret(); } si.fMask = SIF_DISABLENOSCROLL | SIF_PAGE | SIF_POS | SIF_RANGE; si.nMin = 0; si.nMax = nVisLines - 1; si.nPage = GetScreenLines(); si.nPos = CalcVisibleLines(0, m_nTopLine); } VERIFY(SetScrollInfo(SB_VERT, &si)); } void CCrystalTextView::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { CView::OnVScroll(nSBCode, nPos, pScrollBar); // Note we cannot use nPos because of its 16-bit nature SCROLLINFO si; si.cbSize = sizeof(si); si.fMask = SIF_ALL; VERIFY(GetScrollInfo(SB_VERT, &si)); int nPageLines = GetScreenLines(); int nLineCount = GetLineCount(); int nNewTopLine= 0; bool bSmoothScrolling= false; switch (nSBCode) { case SB_TOP: nNewTopLine = 0; break; case SB_BOTTOM: nNewTopLine = FindVisibleLine(nLineCount - 1, -nPageLines + 1); //nLineCount - nPageLines + 1; break; case SB_LINEUP: nNewTopLine = FindVisibleLine(m_nTopLine, -1); break; case SB_LINEDOWN: nNewTopLine = FindVisibleLine(m_nTopLine, 1); break; case SB_PAGEUP: nNewTopLine = FindVisibleLine(m_nTopLine, 0-si.nPage + 1); break; case SB_PAGEDOWN: nNewTopLine = FindVisibleLine(m_nTopLine, si.nPage - 1); break; case SB_THUMBPOSITION: case SB_THUMBTRACK: nNewTopLine = FindVisibleLine(0, si.nTrackPos); break; case 98: // MiK: mouse wheel nNewTopLine = FindVisibleLine(m_nTopLine, -3); bSmoothScrolling = true; break; case 99: nNewTopLine = FindVisibleLine(m_nTopLine, 3); bSmoothScrolling = true; break; default: return; } if (nNewTopLine < 0) nNewTopLine = 0; if (nNewTopLine >= nLineCount) nNewTopLine = nLineCount - 1; ScrollToLine(nNewTopLine, !bSmoothScrolling); } void CCrystalTextView::RecalcHorzScrollBar(BOOL bPositionOnly /*= FALSE*/) { // Again, we cannot use nPos because it's 16-bit SCROLLINFO si; si.cbSize = sizeof(si); if (bPositionOnly) { si.fMask = SIF_POS; si.nPos = m_nOffsetChar; } else { if (GetScreenChars() >= GetMaxLineLength() && m_nOffsetChar > 0) { m_nOffsetChar = 0; Invalidate(); UpdateCaret(); } si.fMask = SIF_DISABLENOSCROLL | SIF_PAGE | SIF_POS | SIF_RANGE; si.nMin = 0; si.nMax = GetMaxLineLength() - 1; si.nPage = GetScreenChars(); si.nPos = m_nOffsetChar; } VERIFY(SetScrollInfo(SB_HORZ, &si)); } void CCrystalTextView::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { CView::OnHScroll(nSBCode, nPos, pScrollBar); SCROLLINFO si; si.cbSize = sizeof(si); si.fMask = SIF_ALL; VERIFY(GetScrollInfo(SB_HORZ, &si)); int nPageChars = GetScreenChars(); int nMaxLineLength = GetMaxLineLength(); int nNewOffset; switch (nSBCode) { case SB_LEFT: nNewOffset = 0; break; case SB_BOTTOM: nNewOffset = nMaxLineLength - nPageChars + 1; break; case SB_LINEUP: nNewOffset = m_nOffsetChar - 1; break; case SB_LINEDOWN: nNewOffset = m_nOffsetChar + 1; break; case SB_PAGEUP: nNewOffset = m_nOffsetChar - si.nPage + 1; break; case SB_PAGEDOWN: nNewOffset = m_nOffsetChar + si.nPage - 1; break; case SB_THUMBPOSITION: case SB_THUMBTRACK: nNewOffset = si.nTrackPos; break; default: return; } if (nNewOffset >= nMaxLineLength) nNewOffset = nMaxLineLength - 1; if (nNewOffset < 0) nNewOffset = 0; ScrollToChar(nNewOffset, TRUE); UpdateCaret(); } BOOL CCrystalTextView::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message) { if (nHitTest == HTCLIENT) { CPoint pt; ::GetCursorPos(&pt); ScreenToClient(&pt); if (pt.x < GetMarginWidth()) { ::SetCursor(::LoadCursor(GetResourceHandle(), MAKEINTRESOURCE(IDR_MARGIN_CURSOR))); } else { CPoint ptText = ClientToText(pt); PrepareSelBounds(); if (IsInsideSelBlock(ptText)) { // [JRT]: Support For Disabling Drag and Drop... if (!m_bDisableDragAndDrop) // If Drag And Drop Not Disabled ::SetCursor(::LoadCursor(NULL, MAKEINTRESOURCE(IDC_ARROW))); // Set To Arrow Cursor } else ::SetCursor(::LoadCursor(NULL, MAKEINTRESOURCE(IDC_IBEAM))); } return TRUE; } return CView::OnSetCursor(pWnd, nHitTest, message); } CPoint CCrystalTextView::ClientToText(const CPoint &point) { int nLineCount = GetLineCount(); CPoint pt; pt.y = FindVisibleLine(m_nTopLine, point.y / GetLineHeight()); if (pt.y >= nLineCount) pt.y = nLineCount - 1; if (pt.y < 0) pt.y = 0; int nLength = 0; LPCTSTR pszLine = NULL; if (pt.y >= 0 && pt.y < nLineCount) { nLength = GetLineLength(pt.y); pszLine = GetLineChars(pt.y); } int nPos = m_nOffsetChar + (point.x - GetMarginWidth()) / GetCharWidth(); if (nPos < 0) nPos = 0; int nIndex = 0, nCurPos = 0; int nTabSize = GetTabSize(); while (nIndex < nLength) { if (pszLine[nIndex] == _T('\t')) nCurPos += (nTabSize - nCurPos % nTabSize); else nCurPos ++; if (nCurPos > nPos) break; nIndex ++; } ASSERT(nIndex >= 0 && nIndex <= nLength); pt.x = nIndex; return pt; } #ifdef _DEBUG void CCrystalTextView::AssertValidTextPos(const CPoint &point) { if (GetLineCount() > 0) { ASSERT(m_nTopLine >= 0 && m_nOffsetChar >= 0); ASSERT(point.y >= 0 && point.y < GetLineCount()); ASSERT(point.x >= 0 && point.x <= GetLineLength(point.y)); } } #endif CPoint CCrystalTextView::TextToClient(const CPoint &point) { ASSERT_VALIDTEXTPOS(point); int nLength = GetLineLength(point.y); LPCTSTR pszLine = GetLineChars(point.y); CPoint pt; pt.y = CalcVisibleLines(m_nTopLine, point.y) * GetLineHeight(); pt.x = 0; int nTabSize = GetTabSize(); for (int nIndex = 0; nIndex < point.x; nIndex ++) { if (pszLine[nIndex] == _T('\t')) pt.x += (nTabSize - pt.x % nTabSize); else pt.x ++; } pt.x = (pt.x - m_nOffsetChar) * GetCharWidth() + GetMarginWidth(); return pt; } void CCrystalTextView::InvalidateLines(int nLine1, int nLine2, BOOL bInvalidateMargin /*= FALSE*/) { bInvalidateMargin = TRUE; if (nLine2 == -1) { CRect rcInvalid; GetClientRect(&rcInvalid); if (! bInvalidateMargin) rcInvalid.left += GetMarginWidth(); // rcInvalid.top = (nLine1 - m_nTopLine) * GetLineHeight(); rcInvalid.top = CalcVisibleLines(m_nTopLine, nLine1) * GetLineHeight(); InvalidateRect(&rcInvalid, FALSE); } else { if (nLine2 < nLine1) { int nTemp = nLine1; nLine1 = nLine2; nLine2 = nTemp; } CRect rcInvalid; GetClientRect(&rcInvalid); if (! bInvalidateMargin) rcInvalid.left += GetMarginWidth(); rcInvalid.top = CalcVisibleLines(m_nTopLine, nLine1) * GetLineHeight(); rcInvalid.bottom = (CalcVisibleLines(m_nTopLine, nLine2) + 1) * GetLineHeight(); InvalidateRect(&rcInvalid, FALSE); } } void CCrystalTextView::SetSelection(const CPoint &ptStart, const CPoint &ptEnd) { ASSERT_VALIDTEXTPOS(ptStart); ASSERT_VALIDTEXTPOS(ptEnd); if (m_ptSelStart == ptStart) { if (m_ptSelEnd != ptEnd) InvalidateLines(ptEnd.y, m_ptSelEnd.y); } else { InvalidateLines(ptStart.y, ptEnd.y); InvalidateLines(m_ptSelStart.y, m_ptSelEnd.y); } m_ptSelStart = ptStart; m_ptSelEnd = ptEnd; } void CCrystalTextView::AdjustTextPoint(CPoint &point) { point.x += GetCharWidth() / 2; //todo } void CCrystalTextView::OnSetFocus(CWnd* pOldWnd) { CView::OnSetFocus(pOldWnd); m_bFocused = TRUE; if (m_ptSelStart != m_ptSelEnd) InvalidateLines(m_ptSelStart.y, m_ptSelEnd.y); UpdateCaret(); } DWORD CCrystalTextView::ParseLine(DWORD dwCookie, int nLineIndex, TEXTBLOCK *pBuf, int &nActualItems) { return 0; } int CCrystalTextView::CalculateActualOffset(int nLineIndex, int nCharIndex) { // ASSERT(!IsLineHidden(nLineIndex)); int nLength = GetLineLength(nLineIndex); ASSERT(nCharIndex >= 0 && nCharIndex <= nLength); LPCTSTR pszChars = GetLineChars(nLineIndex); int nOffset = 0; int nTabSize = GetTabSize(); for (int I = 0; I < nCharIndex; I ++) { if (pszChars[I] == _T('\t')) nOffset += (nTabSize - nOffset % nTabSize); else nOffset ++; } return nOffset; } int CCrystalTextView::ApproxActualOffset(int nLineIndex, int nOffset) { if (nOffset == 0) return 0; int nLength = GetLineLength(nLineIndex); LPCTSTR pszChars = GetLineChars(nLineIndex); int nCurrentOffset = 0; int nTabSize = GetTabSize(); for (int I = 0; I < nLength; I ++) { if (pszChars[I] == _T('\t')) nCurrentOffset += (nTabSize - nCurrentOffset % nTabSize); else nCurrentOffset ++; if (nCurrentOffset >= nOffset) { if (nOffset <= nCurrentOffset - nTabSize / 2) return I; return I + 1; } } return nLength; } void CCrystalTextView::EnsureVisible(CPoint pt) { ASSERT(!IsLineHidden(pt.y)); // Scroll vertically int nLineCount = GetLineCount(); int nNewTopLine = m_nTopLine; // MiK: bottom line (last visible) int nBottomLine= FindVisibleLine(nNewTopLine, GetScreenLines() - 1); if (pt.y > nBottomLine) // MiK (pt.y >= nNewTopLine + GetScreenLines()) { nNewTopLine = FindVisibleLine(pt.y, -GetScreenLines() + 1); //MiK pt.y - GetScreenLines() + 1; } if (pt.y < nNewTopLine) { nNewTopLine = pt.y; } if (nNewTopLine < 0) nNewTopLine = 0; if (nNewTopLine >= nLineCount) nNewTopLine = nLineCount - 1; if (m_nTopLine != nNewTopLine) { ScrollToLine(nNewTopLine); UpdateSiblingScrollPos(TRUE); } // Scroll horizontally int nActualPos = CalculateActualOffset(pt.y, pt.x); int nNewOffset = m_nOffsetChar; if (nActualPos > nNewOffset + GetScreenChars()) { nNewOffset = nActualPos - GetScreenChars(); } if (nActualPos < nNewOffset) { nNewOffset = nActualPos; } if (nNewOffset >= GetMaxLineLength()) nNewOffset = GetMaxLineLength() - 1; if (nNewOffset < 0) nNewOffset = 0; if (m_nOffsetChar != nNewOffset) { ScrollToChar(nNewOffset); UpdateCaret(); UpdateSiblingScrollPos(FALSE); } } void CCrystalTextView::OnKillFocus(CWnd* pNewWnd) { CView::OnKillFocus(pNewWnd); m_bFocused = FALSE; UpdateCaret(); if (m_ptSelStart != m_ptSelEnd) InvalidateLines(m_ptSelStart.y, m_ptSelEnd.y); if (m_bDragSelection) { ReleaseCapture(); KillTimer(m_nDragSelTimer); m_bDragSelection = FALSE; } } void CCrystalTextView::OnSysColorChange() { CView::OnSysColorChange(); Invalidate(); } void CCrystalTextView::GetText(const CPoint &ptStart, const CPoint &ptEnd, CString &text) { if (m_pTextBuffer != NULL) m_pTextBuffer->GetText(ptStart.y, ptStart.x, ptEnd.y, ptEnd.x, text); else text = _T(""); } CString CCrystalTextView::GetCurLine() { int nLine= m_ptCursorPos.y; if (m_pTextBuffer == 0 || nLine >= GetLineCount()) return _T(""); int nLength= GetLineLength(nLine); if (nLength == 0) return _T(""); CString str; m_pTextBuffer->GetText(nLine, 0, nLine, nLength, str); return str; } void CCrystalTextView::UpdateView(CCrystalTextView *pSource, CUpdateContext *pContext, DWORD dwFlags, int nLineIndex /*= -1*/) { if (dwFlags & UPDATE_RESET) { ResetView(); RecalcVertScrollBar(); RecalcHorzScrollBar(); // MiK: parse all to update collapsible blocks GetParseCookie(GetLineCount() - 1); NotifyTextChanged(); return; } int nLineCount = GetLineCount(); ASSERT(nLineCount > 0); ASSERT(nLineIndex >= -1 && nLineIndex < nLineCount); if ((dwFlags & UPDATE_SINGLELINE) != 0) { ASSERT(nLineIndex != -1); // All text below this line should be reparsed if (m_pdwParseCookies != NULL) { ASSERT(m_nParseArraySize == nLineCount); memset(m_pdwParseCookies + nLineIndex, 0xff, sizeof(DWORD) * (m_nParseArraySize - nLineIndex)); } // This line'th actual length must be recalculated if (m_pnActualLineLength != NULL) { ASSERT(m_nActualLengthArraySize == nLineCount); m_pnActualLineLength[nLineIndex] = -1; } // Repaint the lines InvalidateLines(nLineIndex, -1, TRUE); } else { if (nLineIndex == -1) nLineIndex = 0; // Refresh all text // All text below this line should be reparsed if (m_pdwParseCookies != NULL) { if (m_nParseArraySize != nLineCount) { // Reallocate cookies array DWORD *pdwNewArray = new DWORD[nLineCount]; if (nLineIndex > 0) memcpy(pdwNewArray, m_pdwParseCookies, sizeof(DWORD) * nLineIndex); delete m_pdwParseCookies; m_nParseArraySize = nLineCount; m_pdwParseCookies = pdwNewArray; } memset(m_pdwParseCookies + nLineIndex, 0xff, sizeof(DWORD) * (m_nParseArraySize - nLineIndex)); } // Recalculate actual length for all lines below this if (m_pnActualLineLength != NULL) { if (m_nActualLengthArraySize != nLineCount) { // Reallocate actual length array int *pnNewArray = new int[nLineCount]; if (nLineIndex > 0) memcpy(pnNewArray, m_pnActualLineLength, sizeof(int) * nLineIndex); delete m_pnActualLineLength; m_nActualLengthArraySize = nLineCount; m_pnActualLineLength = pnNewArray; } memset(m_pnActualLineLength + nLineIndex, 0xff, sizeof(DWORD) * (m_nActualLengthArraySize - nLineIndex)); } // Repaint the lines InvalidateLines(nLineIndex, -1, TRUE); } // All those points must be recalculated and validated if (pContext != NULL) { pContext->RecalcPoint(m_ptCursorPos); pContext->RecalcPoint(m_ptSelStart); pContext->RecalcPoint(m_ptSelEnd); pContext->RecalcPoint(m_ptAnchor); ASSERT_VALIDTEXTPOS(m_ptCursorPos); ASSERT_VALIDTEXTPOS(m_ptSelStart); ASSERT_VALIDTEXTPOS(m_ptSelEnd); ASSERT_VALIDTEXTPOS(m_ptAnchor); if (m_bDraggingText) { pContext->RecalcPoint(m_ptDraggedTextBegin); pContext->RecalcPoint(m_ptDraggedTextEnd); ASSERT_VALIDTEXTPOS(m_ptDraggedTextBegin); ASSERT_VALIDTEXTPOS(m_ptDraggedTextEnd); } CPoint ptTopLine(0, m_nTopLine); pContext->RecalcPoint(ptTopLine); ASSERT_VALIDTEXTPOS(ptTopLine); m_nTopLine = ptTopLine.y; UpdateCaret(); } // Recalculate vertical scrollbar, if needed if ((dwFlags & UPDATE_VERTRANGE) != 0) { if (! m_bVertScrollBarLocked) RecalcVertScrollBar(); } // Recalculate horizontal scrollbar, if needed if ((dwFlags & UPDATE_HORZRANGE) != 0) { m_nMaxLineLength = -1; if (! m_bHorzScrollBarLocked) RecalcHorzScrollBar(); } if (dwFlags & (UPDATE_SINGLELINE | UPDATE_VERTRANGE)) NotifyTextChanged(); } HINSTANCE CCrystalTextView::GetResourceHandle() { #ifdef CRYSEDIT_RES_HANDLE return CRYSEDIT_RES_HANDLE; #else if (s_hResourceInst != NULL) return s_hResourceInst; return AfxGetResourceHandle(); #endif } int CCrystalTextView::OnCreate(LPCREATESTRUCT lpCreateStruct) { // Note: CSampleDoc overwrites this logfont memset(&m_lfBaseFont, 0, sizeof(m_lfBaseFont)); lstrcpy(m_lfBaseFont.lfFaceName, _T("Atari Mono")); m_lfBaseFont.lfHeight = 0; m_lfBaseFont.lfWeight = FW_NORMAL; m_lfBaseFont.lfItalic = FALSE; m_lfBaseFont.lfCharSet = DEFAULT_CHARSET; m_lfBaseFont.lfOutPrecision = OUT_DEFAULT_PRECIS; m_lfBaseFont.lfClipPrecision = CLIP_DEFAULT_PRECIS; m_lfBaseFont.lfQuality = DEFAULT_QUALITY; m_lfBaseFont.lfPitchAndFamily = DEFAULT_PITCH; if (CView::OnCreate(lpCreateStruct) == -1) return -1; ASSERT(m_hAccel == NULL); m_hAccel = ::LoadAccelerators(GetResourceHandle(), MAKEINTRESOURCE(IDR_DEFAULT_ACCEL)); ASSERT(m_hAccel != NULL); return 0; } void CCrystalTextView::SetAnchor(const CPoint &ptNewAnchor) { ASSERT_VALIDTEXTPOS(ptNewAnchor); m_ptAnchor = ptNewAnchor; } void CCrystalTextView::OnEditOperation(int nAction, LPCTSTR pszText) { } BOOL CCrystalTextView::PreTranslateMessage(MSG *pMsg) { if (pMsg->message >= WM_KEYFIRST && pMsg->message <= WM_KEYLAST) { if (m_hAccel != NULL) { if (::TranslateAccelerator(m_hWnd, m_hAccel, pMsg)) return TRUE; } } return CView::PreTranslateMessage(pMsg); } CPoint CCrystalTextView::GetCursorPos() { return m_ptCursorPos; } void CCrystalTextView::SetCursorPos(const CPoint &ptCursorPos) { ASSERT_VALIDTEXTPOS(ptCursorPos); m_ptCursorPos = ptCursorPos; m_nIdealCharPos = CalculateActualOffset(m_ptCursorPos.y, m_ptCursorPos.x); UpdateCaret(); } void CCrystalTextView::SetSelectionMargin(BOOL bSelMargin) { if (m_bSelMargin != bSelMargin) { m_bSelMargin = bSelMargin; if (::IsWindow(m_hWnd)) { m_nScreenChars = -1; Invalidate(); RecalcHorzScrollBar(); } } } void CCrystalTextView::GetFont(LOGFONT &lf) { lf = m_lfBaseFont; } void CCrystalTextView::SetFont(const LOGFONT &lf) { m_lfBaseFont = lf; m_nScreenLines = -1; m_nScreenChars = -1; m_nCharWidth = -1; m_nLineHeight = -1; if (m_pCacheBitmap != NULL) { m_pCacheBitmap->DeleteObject(); delete m_pCacheBitmap; m_pCacheBitmap = NULL; } for (int I = 0; I < 4; I ++) { if (m_apFonts[I] != NULL) { m_apFonts[I]->DeleteObject(); delete m_apFonts[I]; m_apFonts[I] = NULL; } } if (::IsWindow(m_hWnd)) { RecalcVertScrollBar(); RecalcHorzScrollBar(); UpdateCaret(); Invalidate(); } } void CCrystalTextView::OnUpdateIndicatorPosition(CCmdUI* pCmdUI) { ASSERT_VALIDTEXTPOS(m_ptCursorPos); CString stat; int nXPos= CalculateActualOffset(m_ptCursorPos.y, m_ptCursorPos.x); stat.Format(_T("Ln %d, Col %d"), m_ptCursorPos.y + 1, nXPos + 1); pCmdUI->SetText(stat); } void CCrystalTextView::OnUpdateIndicatorCRLF(CCmdUI* pCmdUI) { if (m_pTextBuffer != NULL) { int crlfMode = m_pTextBuffer->GetCRLFMode(); switch (crlfMode) { case CRLF_STYLE_DOS: pCmdUI->SetText(_T("DOS")); pCmdUI->Enable(TRUE); break; case CRLF_STYLE_UNIX: pCmdUI->SetText(_T("UNIX")); pCmdUI->Enable(TRUE); break; case CRLF_STYLE_MAC: pCmdUI->SetText(_T("MAC")); pCmdUI->Enable(TRUE); break; default: pCmdUI->SetText(NULL); pCmdUI->Enable(FALSE); } } else { pCmdUI->SetText(NULL); pCmdUI->Enable(FALSE); } } void CCrystalTextView::OnToggleBookmark(UINT nCmdID) { int nBookmarkID = nCmdID - ID_EDIT_TOGGLE_BOOKMARK0; ASSERT(nBookmarkID >= 0 && nBookmarkID <= 9); if (m_pTextBuffer != NULL) { DWORD dwFlags = GetLineFlags(m_ptCursorPos.y); DWORD dwMask = LF_BOOKMARK(nBookmarkID); m_pTextBuffer->SetLineFlag(m_ptCursorPos.y, dwMask, (dwFlags & dwMask) == 0); } } void CCrystalTextView::OnGoBookmark(UINT nCmdID) { int nBookmarkID = nCmdID - ID_EDIT_GO_BOOKMARK0; ASSERT(nBookmarkID >= 0 && nBookmarkID <= 9); if (m_pTextBuffer != NULL) { int nLine = m_pTextBuffer->GetLineWithFlag(LF_BOOKMARK(nBookmarkID)); if (nLine >= 0) GoToLine(nLine); } } void CCrystalTextView::OnClearBookmarks() { if (m_pTextBuffer != NULL) { for (int nBookmarkID = 0; nBookmarkID <= 9; nBookmarkID++) { int nLine = m_pTextBuffer->GetLineWithFlag(LF_BOOKMARK(nBookmarkID)); if (nLine >= 0) { m_pTextBuffer->SetLineFlag(nLine, LF_BOOKMARK(nBookmarkID), FALSE); } } } } void CCrystalTextView::ShowCursor() { m_bCursorHidden = FALSE; UpdateCaret(); } void CCrystalTextView::HideCursor() { m_bCursorHidden = TRUE; UpdateCaret(); } DROPEFFECT CCrystalTextView::GetDropEffect() { return DROPEFFECT_COPY; } void CCrystalTextView::OnDropSource(DROPEFFECT de) { ASSERT(de == DROPEFFECT_COPY); } HGLOBAL CCrystalTextView::PrepareDragData() { PrepareSelBounds(); if (m_ptDrawSelStart == m_ptDrawSelEnd) return NULL; CString text; GetText(m_ptDrawSelStart, m_ptDrawSelEnd, text); HGLOBAL hData = ::GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, lstrlen(text) + 1); if (hData == NULL) return NULL; LPSTR pszData = (LPSTR) ::GlobalLock(hData); USES_CONVERSION; strcpy(pszData, T2A(text.GetBuffer(0))); text.ReleaseBuffer(); ::GlobalUnlock(hData); m_ptDraggedTextBegin = m_ptDrawSelStart; m_ptDraggedTextEnd = m_ptDrawSelEnd; return hData; } static int FindStringHelper(LPCTSTR pszFindWhere, LPCTSTR pszFindWhat, BOOL bWholeWord) { ASSERT(pszFindWhere != NULL); ASSERT(pszFindWhat != NULL); int nCur = 0; int nLength = lstrlen(pszFindWhat); for (;;) { #ifdef _UNICODE LPCTSTR pszPos = wcsstr(pszFindWhere, pszFindWhat); #else LPCTSTR pszPos = strstr(pszFindWhere, pszFindWhat); #endif if (pszPos == NULL) return -1; if (! bWholeWord) return nCur + (pszPos - pszFindWhere); if (pszPos > pszFindWhere && (isalnum(pszPos[-1]) || pszPos[-1] == _T('_'))) { nCur += (pszPos - pszFindWhere); pszFindWhere = pszPos + 1; continue; } if (isalnum(pszPos[nLength]) || pszPos[nLength] == _T('_')) { nCur += (pszPos - pszFindWhere + 1); pszFindWhere = pszPos + 1; continue; } return nCur + (pszPos - pszFindWhere); } ASSERT(FALSE); // Unreachable return -1; } BOOL CCrystalTextView::HighlightText(const CPoint &ptStartPos, int nLength) { ASSERT_VALIDTEXTPOS(ptStartPos); if (IsLineHidden(ptStartPos.y)) // MiK: expand block if line is hidden CollapseBlock(ptStartPos.y); m_ptCursorPos = ptStartPos; m_ptCursorPos.x += nLength; ASSERT_VALIDTEXTPOS(m_ptCursorPos); // Probably 'nLength' is bigger than expected... m_ptAnchor = m_ptCursorPos; SetSelection(ptStartPos, m_ptCursorPos); UpdateCaret(); EnsureVisible(m_ptCursorPos); return TRUE; } BOOL CCrystalTextView::FindText(LPCTSTR pszText, const CPoint &ptStartPos, DWORD dwFlags, BOOL bWrapSearch, CPoint *pptFoundPos) { int nLineCount = GetLineCount(); return FindTextInBlock(pszText, ptStartPos, CPoint(0, 0), CPoint(GetLineLength(nLineCount - 1), nLineCount - 1), dwFlags, bWrapSearch, pptFoundPos); } BOOL CCrystalTextView::FindTextInBlock(LPCTSTR pszText, const CPoint &ptStartPosition, const CPoint &ptBlockBegin, const CPoint &ptBlockEnd, DWORD dwFlags, BOOL bWrapSearch, CPoint *pptFoundPos) { CPoint ptCurrentPos = ptStartPosition; ASSERT(pszText != NULL && lstrlen(pszText) > 0); ASSERT_VALIDTEXTPOS(ptCurrentPos); ASSERT_VALIDTEXTPOS(ptBlockBegin); ASSERT_VALIDTEXTPOS(ptBlockEnd); ASSERT(ptBlockBegin.y < ptBlockEnd.y || ptBlockBegin.y == ptBlockEnd.y && ptBlockBegin.x <= ptBlockEnd.x); if (ptBlockBegin == ptBlockEnd) return FALSE; if (ptCurrentPos.y < ptBlockBegin.y || ptCurrentPos.y == ptBlockBegin.y && ptCurrentPos.x < ptBlockBegin.x) ptCurrentPos = ptBlockBegin; CString what = pszText; if ((dwFlags & FIND_MATCH_CASE) == 0) what.MakeUpper(); if (dwFlags & FIND_DIRECTION_UP) { // Let's check if we deal with whole text. // At this point, we cannot search *up* in selection ASSERT(ptBlockBegin.x == 0 && ptBlockBegin.y == 0); ASSERT(ptBlockEnd.x == GetLineLength(GetLineCount() - 1) && ptBlockEnd.y == GetLineCount() - 1); // Proceed as if we have whole text search. for (;;) { while (ptCurrentPos.y >= 0) { int nLineLength = GetLineLength(ptCurrentPos.y); nLineLength -= ptCurrentPos.x; if (nLineLength <= 0) { ptCurrentPos.x = 0; ptCurrentPos.y --; continue; } LPCTSTR pszChars = GetLineChars(ptCurrentPos.y); pszChars += ptCurrentPos.x; CString line; lstrcpyn(line.GetBuffer(nLineLength + 1), pszChars, nLineLength + 1); line.ReleaseBuffer(); if ((dwFlags & FIND_MATCH_CASE) == 0) line.MakeUpper(); int nPos = ::FindStringHelper(line, what, (dwFlags & FIND_WHOLE_WORD) != 0); if (nPos >= 0) // Found text! { ptCurrentPos.x += nPos; *pptFoundPos = ptCurrentPos; return TRUE; } ptCurrentPos.x = 0; ptCurrentPos.y --; } // Beginning of text reached if (! bWrapSearch) return FALSE; // Start again from the end of text bWrapSearch = FALSE; ptCurrentPos = CPoint(0, GetLineCount() - 1); } } else { for (;;) { while (ptCurrentPos.y <= ptBlockEnd.y) { int nLineLength = GetLineLength(ptCurrentPos.y); nLineLength -= ptCurrentPos.x; if (nLineLength <= 0) { ptCurrentPos.x = 0; ptCurrentPos.y ++; continue; } LPCTSTR pszChars = GetLineChars(ptCurrentPos.y); pszChars += ptCurrentPos.x; // Prepare necessary part of line CString line; lstrcpyn(line.GetBuffer(nLineLength + 1), pszChars, nLineLength + 1); line.ReleaseBuffer(); if ((dwFlags & FIND_MATCH_CASE) == 0) line.MakeUpper(); // Perform search in the line int nPos = ::FindStringHelper(line, what, (dwFlags & FIND_WHOLE_WORD) != 0); if (nPos >= 0) { ptCurrentPos.x += nPos; // Check of the text found is outside the block. if (ptCurrentPos.y == ptBlockEnd.y && ptCurrentPos.x >= ptBlockEnd.x) break; *pptFoundPos = ptCurrentPos; return TRUE; } // Go further, text was not found ptCurrentPos.x = 0; ptCurrentPos.y ++; } // End of text reached if (! bWrapSearch) return FALSE; // Start from the beginning bWrapSearch = FALSE; ptCurrentPos = ptBlockBegin; } } ASSERT(FALSE); // Unreachable return FALSE; } void CCrystalTextView::OnEditFind() { CWinApp *pApp = AfxGetApp(); ASSERT(pApp != NULL); CFindTextDlg dlg(this); if (m_bLastSearch) { // Get the latest search parameters dlg.m_bMatchCase = (m_dwLastSearchFlags & FIND_MATCH_CASE) != 0; dlg.m_bWholeWord = (m_dwLastSearchFlags & FIND_WHOLE_WORD) != 0; dlg.m_nDirection = (m_dwLastSearchFlags & FIND_DIRECTION_UP) != 0 ? 0 : 1; if (m_pszLastFindWhat != NULL) dlg.m_sText = m_pszLastFindWhat; } else { // Take search parameters from registry dlg.m_bMatchCase = pApp->GetProfileInt(REG_FIND_SUBKEY, REG_MATCH_CASE, FALSE); dlg.m_bWholeWord = pApp->GetProfileInt(REG_FIND_SUBKEY, REG_WHOLE_WORD, FALSE); dlg.m_nDirection = 1; // Search down dlg.m_sText = pApp->GetProfileString(REG_FIND_SUBKEY, REG_FIND_WHAT, _T("")); } // Take the current selection, if any if (IsSelection()) { CPoint ptSelStart, ptSelEnd; GetSelection(ptSelStart, ptSelEnd); if (ptSelStart.y == ptSelEnd.y) { LPCTSTR pszChars = GetLineChars(ptSelStart.y); int nChars = ptSelEnd.x - ptSelStart.x; lstrcpyn(dlg.m_sText.GetBuffer(nChars + 1), pszChars + ptSelStart.x, nChars + 1); dlg.m_sText.ReleaseBuffer(); } } // Execute Find dialog dlg.m_ptCurrentPos = m_ptCursorPos; // Search from cursor position m_bShowInactiveSelection = TRUE; dlg.DoModal(); m_bShowInactiveSelection = FALSE; // Save search parameters for 'F3' command m_bLastSearch = TRUE; if (m_pszLastFindWhat != NULL) free(m_pszLastFindWhat); #ifdef _UNICODE m_pszLastFindWhat = _wcsdup(dlg.m_sText); #else m_pszLastFindWhat = _strdup(dlg.m_sText); #endif m_dwLastSearchFlags = 0; if (dlg.m_bMatchCase) m_dwLastSearchFlags |= FIND_MATCH_CASE; if (dlg.m_bWholeWord) m_dwLastSearchFlags |= FIND_WHOLE_WORD; if (dlg.m_nDirection == 0) m_dwLastSearchFlags |= FIND_DIRECTION_UP; // Save search parameters to registry pApp->WriteProfileInt(REG_FIND_SUBKEY, REG_MATCH_CASE, dlg.m_bMatchCase); pApp->WriteProfileInt(REG_FIND_SUBKEY, REG_WHOLE_WORD, dlg.m_bWholeWord); pApp->WriteProfileString(REG_FIND_SUBKEY, REG_FIND_WHAT, dlg.m_sText); } void CCrystalTextView::OnEditRepeat() { if (m_bLastSearch) { CPoint ptFoundPos; if (!FindText(m_pszLastFindWhat, m_ptCursorPos, m_dwLastSearchFlags, TRUE, &ptFoundPos)) { CString prompt; prompt.Format(IDS_EDIT_TEXT_NOT_FOUND, m_pszLastFindWhat); AfxMessageBox(prompt); return; } HighlightText(ptFoundPos, lstrlen(m_pszLastFindWhat)); m_bMultipleSearch = TRUE; // More search } } void CCrystalTextView::OnUpdateEditRepeat(CCmdUI* pCmdUI) { pCmdUI->Enable(m_bLastSearch); } void CCrystalTextView::OnEditFindPrevious() { DWORD dwSaveSearchFlags = m_dwLastSearchFlags; if ((m_dwLastSearchFlags & FIND_DIRECTION_UP) != 0) m_dwLastSearchFlags &= ~FIND_DIRECTION_UP; else m_dwLastSearchFlags |= FIND_DIRECTION_UP; OnEditRepeat(); m_dwLastSearchFlags = dwSaveSearchFlags; } void CCrystalTextView::OnUpdateEditFindPrevious(CCmdUI* pCmdUI) { pCmdUI->Enable(m_bLastSearch); } void CCrystalTextView::OnFilePageSetup() { CWinApp *pApp = AfxGetApp(); ASSERT(pApp != NULL); CPageSetupDialog dlg; dlg.m_psd.Flags &= ~PSD_INTHOUSANDTHSOFINCHES; dlg.m_psd.Flags |= PSD_INHUNDREDTHSOFMILLIMETERS | PSD_DISABLEORIENTATION | PSD_DISABLEPAPER; dlg.m_psd.rtMargin.left = pApp->GetProfileInt(REG_PAGE_SUBKEY, REG_MARGIN_LEFT, DEFAULT_PRINT_MARGIN); dlg.m_psd.rtMargin.right = pApp->GetProfileInt(REG_PAGE_SUBKEY, REG_MARGIN_RIGHT, DEFAULT_PRINT_MARGIN); dlg.m_psd.rtMargin.top = pApp->GetProfileInt(REG_PAGE_SUBKEY, REG_MARGIN_TOP, DEFAULT_PRINT_MARGIN); dlg.m_psd.rtMargin.bottom = pApp->GetProfileInt(REG_PAGE_SUBKEY, REG_MARGIN_BOTTOM, DEFAULT_PRINT_MARGIN); if (dlg.DoModal() == IDOK) { pApp->WriteProfileInt(REG_PAGE_SUBKEY, REG_MARGIN_LEFT, dlg.m_psd.rtMargin.left); pApp->WriteProfileInt(REG_PAGE_SUBKEY, REG_MARGIN_RIGHT, dlg.m_psd.rtMargin.right); pApp->WriteProfileInt(REG_PAGE_SUBKEY, REG_MARGIN_TOP, dlg.m_psd.rtMargin.top); pApp->WriteProfileInt(REG_PAGE_SUBKEY, REG_MARGIN_BOTTOM, dlg.m_psd.rtMargin.bottom); } } void CCrystalTextView::OnToggleBookmark() { if (m_pTextBuffer != NULL) { DWORD dwFlags = GetLineFlags(m_ptCursorPos.y); DWORD dwMask = LF_BOOKMARKS; m_pTextBuffer->SetLineFlag(m_ptCursorPos.y, dwMask, (dwFlags & dwMask) == 0, FALSE); } int nLine = m_pTextBuffer->GetLineWithFlag(LF_BOOKMARKS); if (nLine >= 0) m_bBookmarkExist = TRUE; else m_bBookmarkExist = FALSE; } // MiK: move cursor to given line (expand block if this line is hidden) // void CCrystalTextView::GoToLine(int nLineIndex, int nCharOffset/*= 0*/) { ASSERT(nLineIndex >= 0); if (nLineIndex >= 0) { if (IsLineHidden(nLineIndex)) CollapseBlock(nLineIndex); CPoint pt(nCharOffset, nLineIndex); ASSERT_VALIDTEXTPOS(pt); SetCursorPos(pt); SetSelection(pt, pt); SetAnchor(pt); EnsureVisible(pt); } } void CCrystalTextView::OnNextBookmark() { if (m_pTextBuffer != NULL) { int nLine = m_pTextBuffer->FindNextBookmarkLine(m_ptCursorPos.y); if (nLine >= 0) GoToLine(nLine); } } void CCrystalTextView::OnPrevBookmark() { if (m_pTextBuffer != NULL) { int nLine = m_pTextBuffer->FindPrevBookmarkLine(m_ptCursorPos.y); if (nLine >= 0) GoToLine(nLine); } } void CCrystalTextView::OnClearAllBookmarks() { if (m_pTextBuffer != NULL) { int nLineCount = GetLineCount(); for (int I = 0; I < nLineCount; I ++) { if (m_pTextBuffer->GetLineFlags(I) & LF_BOOKMARKS) m_pTextBuffer->SetLineFlag(I, LF_BOOKMARKS, FALSE); } m_bBookmarkExist = FALSE; } } void CCrystalTextView::OnUpdateNextBookmark(CCmdUI* pCmdUI) { pCmdUI->Enable(m_bBookmarkExist); } void CCrystalTextView::OnUpdatePrevBookmark(CCmdUI* pCmdUI) { pCmdUI->Enable(m_bBookmarkExist); } void CCrystalTextView::OnUpdateClearAllBookmarks(CCmdUI* pCmdUI) { pCmdUI->Enable(m_bBookmarkExist); } BOOL CCrystalTextView::GetViewTabs() { return m_bViewTabs; } void CCrystalTextView::SetViewTabs(BOOL bViewTabs) { if (bViewTabs != m_bViewTabs) { m_bViewTabs = bViewTabs; if (::IsWindow(m_hWnd)) Invalidate(); } } void CCrystalTextView::OnEditViewTabs() { SetViewTabs(!m_bViewTabs); } void CCrystalTextView::OnUpdateEditViewTabs(CCmdUI* pCmdUI) { pCmdUI->Enable(); pCmdUI->SetCheck(m_bViewTabs); } BOOL CCrystalTextView::GetSelectionMargin() { return m_bSelMargin; } int CCrystalTextView::GetMarginWidth() { return m_bSelMargin ? 20 : 1; } BOOL CCrystalTextView::GetSmoothScroll() const { return m_bSmoothScroll; } void CCrystalTextView::SetSmoothScroll(BOOL bSmoothScroll) { m_bSmoothScroll = bSmoothScroll; } // [JRT] BOOL CCrystalTextView::GetDisableDragAndDrop() const { return m_bDisableDragAndDrop; } // [JRT] void CCrystalTextView::SetDisableDragAndDrop(BOOL bDDAD) { m_bDisableDragAndDrop = bDDAD; } BOOL CCrystalTextView::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt) { if (zDelta) OnVScroll(zDelta > 0 ? 98 : 99, 0, 0); // return CView::OnMouseWheel(nFlags, zDelta, pt); return true; } void CCrystalTextView::MoveLeft(BOOL bSelect) { PrepareSelBounds(); if (m_ptDrawSelStart != m_ptDrawSelEnd && ! bSelect) { m_ptCursorPos = m_ptDrawSelStart; } else { if (m_ptCursorPos.x == 0) { if (m_ptCursorPos.y > 0) { // m_ptCursorPos.y --; m_ptCursorPos.y = FindVisibleLine(m_ptCursorPos.y, -1); m_ptCursorPos.x = GetLineLength(m_ptCursorPos.y); } } else m_ptCursorPos.x --; } m_nIdealCharPos = CalculateActualOffset(m_ptCursorPos.y, m_ptCursorPos.x); EnsureVisible(m_ptCursorPos); UpdateCaret(); if (! bSelect) m_ptAnchor = m_ptCursorPos; SetSelection(m_ptAnchor, m_ptCursorPos); } void CCrystalTextView::MoveRight(BOOL bSelect) { PrepareSelBounds(); if (m_ptDrawSelStart != m_ptDrawSelEnd && ! bSelect) { m_ptCursorPos = m_ptDrawSelEnd; } else { if (m_ptCursorPos.x == GetLineLength(m_ptCursorPos.y)) { if (m_ptCursorPos.y < GetLineCount() - 1) { //m_ptCursorPos.y ++; int nNextLine= FindVisibleLine(m_ptCursorPos.y, 1); if (nNextLine != m_ptCursorPos.y) { m_ptCursorPos.y = nNextLine; m_ptCursorPos.x = 0; } } } else m_ptCursorPos.x ++; } m_nIdealCharPos = CalculateActualOffset(m_ptCursorPos.y, m_ptCursorPos.x); EnsureVisible(m_ptCursorPos); UpdateCaret(); if (! bSelect) m_ptAnchor = m_ptCursorPos; SetSelection(m_ptAnchor, m_ptCursorPos); } void CCrystalTextView::MoveWordLeft(BOOL bSelect) { PrepareSelBounds(); if (m_ptDrawSelStart != m_ptDrawSelEnd && ! bSelect) { MoveLeft(bSelect); return; } if (m_ptCursorPos.x == 0) { if (m_ptCursorPos.y == 0) return; // m_ptCursorPos.y --; m_ptCursorPos.y = FindVisibleLine(m_ptCursorPos.y, -1); m_ptCursorPos.x = GetLineLength(m_ptCursorPos.y); } LPCTSTR pszChars = GetLineChars(m_ptCursorPos.y); int nPos = m_ptCursorPos.x; while (nPos > 0 && isspace(pszChars[nPos - 1])) nPos --; if (nPos > 0) { nPos --; if (isalnum(pszChars[nPos]) || pszChars[nPos] == _T('_')) { while (nPos > 0 && (isalnum(pszChars[nPos - 1]) || pszChars[nPos - 1] == _T('_'))) nPos --; } else { while (nPos > 0 && ! isalnum(pszChars[nPos - 1]) && pszChars[nPos - 1] != _T('_') && ! isspace(pszChars[nPos - 1])) nPos --; } } m_ptCursorPos.x = nPos; m_nIdealCharPos = CalculateActualOffset(m_ptCursorPos.y, m_ptCursorPos.x); EnsureVisible(m_ptCursorPos); UpdateCaret(); if (! bSelect) m_ptAnchor = m_ptCursorPos; SetSelection(m_ptAnchor, m_ptCursorPos); } void CCrystalTextView::MoveWordRight(BOOL bSelect) { PrepareSelBounds(); if (m_ptDrawSelStart != m_ptDrawSelEnd && ! bSelect) { MoveRight(bSelect); return; } if (m_ptCursorPos.x == GetLineLength(m_ptCursorPos.y)) { if (m_ptCursorPos.y == GetLineCount() - 1) return; // m_ptCursorPos.y ++; m_ptCursorPos.y = FindVisibleLine(m_ptCursorPos.y, 1); m_ptCursorPos.x = 0; } int nLength = GetLineLength(m_ptCursorPos.y); if (m_ptCursorPos.x == nLength) { MoveRight(bSelect); return; } LPCTSTR pszChars = GetLineChars(m_ptCursorPos.y); int nPos = m_ptCursorPos.x; if (isalnum(pszChars[nPos]) || pszChars[nPos] == _T('_')) { while (nPos < nLength && isalnum(pszChars[nPos]) || pszChars[nPos] == _T('_')) nPos ++; } else { while (nPos < nLength && ! isalnum(pszChars[nPos]) && pszChars[nPos] != _T('_') && ! isspace(pszChars[nPos])) nPos ++; } while (nPos < nLength && isspace(pszChars[nPos])) nPos ++; m_ptCursorPos.x = nPos; m_nIdealCharPos = CalculateActualOffset(m_ptCursorPos.y, m_ptCursorPos.x); EnsureVisible(m_ptCursorPos); UpdateCaret(); if (! bSelect) m_ptAnchor = m_ptCursorPos; SetSelection(m_ptAnchor, m_ptCursorPos); } void CCrystalTextView::MoveUp(BOOL bSelect) { PrepareSelBounds(); if (m_ptDrawSelStart != m_ptDrawSelEnd && ! bSelect) m_ptCursorPos = m_ptDrawSelStart; if (m_ptCursorPos.y > 0) { if (m_nIdealCharPos == -1) m_nIdealCharPos = CalculateActualOffset(m_ptCursorPos.y, m_ptCursorPos.x); // m_ptCursorPos.y --; m_ptCursorPos.y = FindVisibleLine(m_ptCursorPos.y, -1); m_ptCursorPos.x = ApproxActualOffset(m_ptCursorPos.y, m_nIdealCharPos); if (m_ptCursorPos.x > GetLineLength(m_ptCursorPos.y)) m_ptCursorPos.x = GetLineLength(m_ptCursorPos.y); } EnsureVisible(m_ptCursorPos); UpdateCaret(); if (! bSelect) m_ptAnchor = m_ptCursorPos; SetSelection(m_ptAnchor, m_ptCursorPos); } void CCrystalTextView::MoveDown(BOOL bSelect) { PrepareSelBounds(); if (m_ptDrawSelStart != m_ptDrawSelEnd && ! bSelect) m_ptCursorPos = m_ptDrawSelEnd; if (m_ptCursorPos.y < GetLineCount() - 1) { if (m_nIdealCharPos == -1) m_nIdealCharPos = CalculateActualOffset(m_ptCursorPos.y, m_ptCursorPos.x); // m_ptCursorPos.y ++; m_ptCursorPos.y = FindVisibleLine(m_ptCursorPos.y, 1); m_ptCursorPos.x = ApproxActualOffset(m_ptCursorPos.y, m_nIdealCharPos); if (m_ptCursorPos.x > GetLineLength(m_ptCursorPos.y)) m_ptCursorPos.x = GetLineLength(m_ptCursorPos.y); } EnsureVisible(m_ptCursorPos); UpdateCaret(); if (! bSelect) m_ptAnchor = m_ptCursorPos; SetSelection(m_ptAnchor, m_ptCursorPos); } void CCrystalTextView::MoveHome(BOOL bSelect) { int nLength = GetLineLength(m_ptCursorPos.y); LPCTSTR pszChars = GetLineChars(m_ptCursorPos.y); int nHomePos = 0; while (nHomePos < nLength && isspace(pszChars[nHomePos])) nHomePos ++; if (nHomePos == nLength || m_ptCursorPos.x == nHomePos) m_ptCursorPos.x = 0; else m_ptCursorPos.x = nHomePos; m_nIdealCharPos = CalculateActualOffset(m_ptCursorPos.y, m_ptCursorPos.x); EnsureVisible(m_ptCursorPos); UpdateCaret(); if (! bSelect) m_ptAnchor = m_ptCursorPos; SetSelection(m_ptAnchor, m_ptCursorPos); } void CCrystalTextView::MoveEnd(BOOL bSelect) { m_ptCursorPos.x = GetLineLength(m_ptCursorPos.y); m_nIdealCharPos = CalculateActualOffset(m_ptCursorPos.y, m_ptCursorPos.x); EnsureVisible(m_ptCursorPos); UpdateCaret(); if (! bSelect) m_ptAnchor = m_ptCursorPos; SetSelection(m_ptAnchor, m_ptCursorPos); } void CCrystalTextView::MovePgUp(BOOL bSelect) { int nNewTopLine = FindVisibleLine(m_nTopLine, -GetScreenLines() + 1); // int nNewTopLine = m_nTopLine - GetScreenLines() + 1; if (nNewTopLine < 0) nNewTopLine = 0; if (m_nTopLine != nNewTopLine) { ScrollToLine(nNewTopLine); UpdateSiblingScrollPos(TRUE); } // m_ptCursorPos.y -= GetScreenLines() - 1; m_ptCursorPos.y = FindVisibleLine(m_ptCursorPos.y, -GetScreenLines() + 1); if (m_ptCursorPos.y < 0) m_ptCursorPos.y = 0; if (m_ptCursorPos.x > GetLineLength(m_ptCursorPos.y)) m_ptCursorPos.x = GetLineLength(m_ptCursorPos.y); m_nIdealCharPos = CalculateActualOffset(m_ptCursorPos.y, m_ptCursorPos.x); EnsureVisible(m_ptCursorPos); //todo: no vertical scroll UpdateCaret(); if (! bSelect) m_ptAnchor = m_ptCursorPos; SetSelection(m_ptAnchor, m_ptCursorPos); } void CCrystalTextView::MovePgDn(BOOL bSelect) { int nNewTopLine = FindVisibleLine(m_nTopLine, GetScreenLines() - 1); // int nNewTopLine = m_nTopLine + GetScreenLines() - 1; if (nNewTopLine >= GetLineCount()) nNewTopLine = GetLineCount() - 1; if (m_nTopLine != nNewTopLine) { ScrollToLine(nNewTopLine); UpdateSiblingScrollPos(TRUE); } // m_ptCursorPos.y += GetScreenLines() - 1; m_ptCursorPos.y = FindVisibleLine(m_ptCursorPos.y, GetScreenLines() - 1); if (m_ptCursorPos.y >= GetLineCount()) m_ptCursorPos.y = GetLineCount() - 1; if (m_ptCursorPos.x > GetLineLength(m_ptCursorPos.y)) m_ptCursorPos.x = GetLineLength(m_ptCursorPos.y); m_nIdealCharPos = CalculateActualOffset(m_ptCursorPos.y, m_ptCursorPos.x); EnsureVisible(m_ptCursorPos); //todo: no vertical scroll UpdateCaret(); if (! bSelect) m_ptAnchor = m_ptCursorPos; SetSelection(m_ptAnchor, m_ptCursorPos); } void CCrystalTextView::MoveCtrlHome(BOOL bSelect) { m_ptCursorPos.x = 0; m_ptCursorPos.y = 0; m_nIdealCharPos = CalculateActualOffset(m_ptCursorPos.y, m_ptCursorPos.x); EnsureVisible(m_ptCursorPos); UpdateCaret(); if (! bSelect) m_ptAnchor = m_ptCursorPos; SetSelection(m_ptAnchor, m_ptCursorPos); } void CCrystalTextView::MoveCtrlEnd(BOOL bSelect) { m_ptCursorPos.y = FindVisibleLine(GetLineCount() - 1, 1); m_ptCursorPos.x = GetLineLength(m_ptCursorPos.y); m_nIdealCharPos = CalculateActualOffset(m_ptCursorPos.y, m_ptCursorPos.x); EnsureVisible(m_ptCursorPos); UpdateCaret(); if (! bSelect) m_ptAnchor = m_ptCursorPos; SetSelection(m_ptAnchor, m_ptCursorPos); } void CCrystalTextView::ScrollUp() { if (m_nTopLine > 0) { ScrollToLine(FindVisibleLine(m_nTopLine, -1)); UpdateSiblingScrollPos(TRUE); } } void CCrystalTextView::ScrollDown() { if (m_nTopLine < GetLineCount() - 1) { ScrollToLine(FindVisibleLine(m_nTopLine, 1)); UpdateSiblingScrollPos(TRUE); } } void CCrystalTextView::ScrollLeft() { if (m_nOffsetChar > 0) { ScrollToChar(m_nOffsetChar - 1); UpdateCaret(); } } void CCrystalTextView::ScrollRight() { if (m_nOffsetChar < GetMaxLineLength() - 1) { ScrollToChar(m_nOffsetChar + 1); UpdateCaret(); } } CPoint CCrystalTextView::WordToRight(CPoint pt) { ASSERT_VALIDTEXTPOS(pt); int nLength = GetLineLength(pt.y); LPCTSTR pszChars = GetLineChars(pt.y); while (pt.x < nLength) { if (! isalnum(pszChars[pt.x]) && pszChars[pt.x] != _T('_')) break; pt.x ++; } ASSERT_VALIDTEXTPOS(pt); return pt; } CPoint CCrystalTextView::WordToLeft(CPoint pt) { ASSERT_VALIDTEXTPOS(pt); LPCTSTR pszChars = GetLineChars(pt.y); while (pt.x > 0) { if (! isalnum(pszChars[pt.x - 1]) && pszChars[pt.x - 1] != _T('_')) break; pt.x --; } ASSERT_VALIDTEXTPOS(pt); return pt; } void CCrystalTextView::SelectAll() { int nLineCount = GetLineCount(); m_ptCursorPos.x = GetLineLength(nLineCount - 1); m_ptCursorPos.y = nLineCount - 1; SetSelection(CPoint(0, 0), m_ptCursorPos); UpdateCaret(); } void CCrystalTextView::OnLButtonDown(UINT nFlags, CPoint point) { CView::OnLButtonDown(nFlags, point); BOOL bShift = GetKeyState(VK_SHIFT) & 0x8000; BOOL bControl = GetKeyState(VK_CONTROL) & 0x8000; if (point.x < GetMarginWidth()) { AdjustTextPoint(point); // MiK: click on the [-] sign? int nLineIndex= ClientToText(point).y; DWORD dwFlag= GetLineFlags(nLineIndex); if (dwFlag & LF_COLLAPSIBLE_BLOCK_START) { CollapseBlock(nLineIndex); } else if (bControl) { SelectAll(); } else { m_ptCursorPos = ClientToText(point); m_ptCursorPos.x = 0; // Force beginning of the line if (! bShift) m_ptAnchor = m_ptCursorPos; CPoint ptStart, ptEnd; ptStart = m_ptAnchor; if (ptStart.y == GetLineCount() - 1) ptStart.x = GetLineLength(ptStart.y); else { ptStart.y ++; ptStart.x = 0; } ptEnd = m_ptCursorPos; ptEnd.x = 0; m_ptCursorPos = ptEnd; UpdateCaret(); EnsureVisible(m_ptCursorPos); SetSelection(ptStart, ptEnd); SetCapture(); m_nDragSelTimer = SetTimer(CRYSTAL_TIMER_DRAGSEL, 100, NULL); ASSERT(m_nDragSelTimer != 0); m_bWordSelection = FALSE; m_bLineSelection = TRUE; m_bDragSelection = TRUE; } } else { CPoint ptText = ClientToText(point); PrepareSelBounds(); // [JRT]: Support For Disabling Drag and Drop... if ((IsInsideSelBlock(ptText)) && // If Inside Selection Area (!m_bDisableDragAndDrop)) // And D&D Not Disabled { m_bPreparingToDrag = TRUE; } else { AdjustTextPoint(point); m_ptCursorPos = ClientToText(point); if (! bShift) m_ptAnchor = m_ptCursorPos; CPoint ptStart, ptEnd; if (bControl) { if (m_ptCursorPos.y < m_ptAnchor.y || m_ptCursorPos.y == m_ptAnchor.y && m_ptCursorPos.x < m_ptAnchor.x) { ptStart = WordToLeft(m_ptCursorPos); ptEnd = WordToRight(m_ptAnchor); } else { ptStart = WordToLeft(m_ptAnchor); ptEnd = WordToRight(m_ptCursorPos); } } else { ptStart = m_ptAnchor; ptEnd = m_ptCursorPos; } m_ptCursorPos = ptEnd; UpdateCaret(); EnsureVisible(m_ptCursorPos); SetSelection(ptStart, ptEnd); SetCapture(); m_nDragSelTimer = SetTimer(CRYSTAL_TIMER_DRAGSEL, 100, NULL); ASSERT(m_nDragSelTimer != 0); m_bWordSelection = bControl; m_bLineSelection = FALSE; m_bDragSelection = TRUE; } } ASSERT_VALIDTEXTPOS(m_ptCursorPos); } void CCrystalTextView::OnMouseMove(UINT nFlags, CPoint point) { CView::OnMouseMove(nFlags, point); if (m_bDragSelection) { BOOL bOnMargin = point.x < GetMarginWidth(); AdjustTextPoint(point); CPoint ptNewCursorPos = ClientToText(point); CPoint ptStart, ptEnd; if (m_bLineSelection) { if (bOnMargin) { if (ptNewCursorPos.y < m_ptAnchor.y || ptNewCursorPos.y == m_ptAnchor.y && ptNewCursorPos.x < m_ptAnchor.x) { ptEnd = m_ptAnchor; if (ptEnd.y == GetLineCount() - 1) { ptEnd.x = GetLineLength(ptEnd.y); } else { ptEnd.y ++; ptEnd.x = 0; } ptNewCursorPos.x = 0; m_ptCursorPos = ptNewCursorPos; } else { ptEnd = m_ptAnchor; ptEnd.x = 0; m_ptCursorPos = ptNewCursorPos; if (ptNewCursorPos.y == GetLineCount() - 1) { ptNewCursorPos.x = GetLineLength(ptNewCursorPos.y); } else { ptNewCursorPos.y ++; ptNewCursorPos.x = 0; } m_ptCursorPos.x = 0; } UpdateCaret(); SetSelection(ptNewCursorPos, ptEnd); return; } // Moving to normal selection mode ::SetCursor(::LoadCursor(NULL, MAKEINTRESOURCE(IDC_IBEAM))); m_bLineSelection = m_bWordSelection = FALSE; } if (m_bWordSelection) { if (ptNewCursorPos.y < m_ptAnchor.y || ptNewCursorPos.y == m_ptAnchor.y && ptNewCursorPos.x < m_ptAnchor.x) { ptStart = WordToLeft(ptNewCursorPos); ptEnd = WordToRight(m_ptAnchor); } else { ptStart = WordToLeft(m_ptAnchor); ptEnd = WordToRight(ptNewCursorPos); } } else { ptStart = m_ptAnchor; ptEnd = ptNewCursorPos; } m_ptCursorPos = ptEnd; UpdateCaret(); SetSelection(ptStart, ptEnd); } if (m_bPreparingToDrag) { m_bPreparingToDrag = FALSE; HGLOBAL hData = PrepareDragData(); if (hData != NULL) { if (m_pTextBuffer != NULL) m_pTextBuffer->BeginUndoGroup(); COleDataSource ds; ds.CacheGlobalData(CF_TEXT, hData); m_bDraggingText = TRUE; DROPEFFECT de = ds.DoDragDrop(GetDropEffect()); if (de != DROPEFFECT_NONE) OnDropSource(de); m_bDraggingText = FALSE; if (m_pTextBuffer != NULL) m_pTextBuffer->FlushUndoGroup(this); } } ASSERT_VALIDTEXTPOS(m_ptCursorPos); } void CCrystalTextView::OnLButtonUp(UINT nFlags, CPoint point) { CView::OnLButtonUp(nFlags, point); if (m_bDragSelection) { AdjustTextPoint(point); CPoint ptNewCursorPos = ClientToText(point); CPoint ptStart, ptEnd; if (m_bLineSelection) { CPoint ptEnd; if (ptNewCursorPos.y < m_ptAnchor.y || ptNewCursorPos.y == m_ptAnchor.y && ptNewCursorPos.x < m_ptAnchor.x) { ptEnd = m_ptAnchor; if (ptEnd.y == GetLineCount() - 1) { ptEnd.x = GetLineLength(ptEnd.y); } else { ptEnd.y ++; ptEnd.x = 0; } ptNewCursorPos.x = 0; m_ptCursorPos = ptNewCursorPos; } else { ptEnd = m_ptAnchor; ptEnd.x = 0; if (ptNewCursorPos.y == GetLineCount() - 1) { ptNewCursorPos.x = GetLineLength(ptNewCursorPos.y); } else { ptNewCursorPos.y ++; ptNewCursorPos.x = 0; } m_ptCursorPos = ptNewCursorPos; } m_ptCursorPos.y = FindVisibleLine(m_ptCursorPos.y, 0); // MiK m_ptCursorPos.x = min(ptEnd.x, GetLineLength(m_ptCursorPos.y)); EnsureVisible(m_ptCursorPos); UpdateCaret(); SetSelection(ptNewCursorPos, ptEnd); } else { if (m_bWordSelection) { if (ptNewCursorPos.y < m_ptAnchor.y || ptNewCursorPos.y == m_ptAnchor.y && ptNewCursorPos.x < m_ptAnchor.x) { ptStart = WordToLeft(ptNewCursorPos); ptEnd = WordToRight(m_ptAnchor); } else { ptStart = WordToLeft(m_ptAnchor); ptEnd = WordToRight(ptNewCursorPos); } } else { ptStart = m_ptAnchor; ptEnd = m_ptCursorPos; } // m_ptCursorPos = ptEnd; m_ptCursorPos.y = FindVisibleLine(ptEnd.y, 0); // MiK m_ptCursorPos.x = min(ptEnd.x, GetLineLength(m_ptCursorPos.y)); EnsureVisible(m_ptCursorPos); UpdateCaret(); SetSelection(ptStart, ptEnd); } ReleaseCapture(); KillTimer(m_nDragSelTimer); m_bDragSelection = FALSE; } if (m_bPreparingToDrag) { m_bPreparingToDrag = FALSE; AdjustTextPoint(point); m_ptCursorPos = ClientToText(point); m_ptCursorPos.y = FindVisibleLine(m_ptCursorPos.y, 0); // MiK m_ptCursorPos.x = min(m_ptCursorPos.x, GetLineLength(m_ptCursorPos.y)); EnsureVisible(m_ptCursorPos); UpdateCaret(); SetSelection(m_ptCursorPos, m_ptCursorPos); } ASSERT_VALIDTEXTPOS(m_ptCursorPos); } void CCrystalTextView::OnTimer(UINT nIDEvent) { CView::OnTimer(nIDEvent); if (nIDEvent == CRYSTAL_TIMER_DRAGSEL) { ASSERT(m_bDragSelection); CPoint pt; ::GetCursorPos(&pt); ScreenToClient(&pt); CRect rcClient; GetClientRect(&rcClient); BOOL bChanged = FALSE; // Scroll vertically, if necessary int nNewTopLine = m_nTopLine; int nLineCount = GetLineCount(); if (pt.y < rcClient.top) { //nNewTopLine --; nNewTopLine = FindVisibleLine(nNewTopLine, -1); if (pt.y < rcClient.top - GetLineHeight()) nNewTopLine -= 2; } else if (pt.y >= rcClient.bottom) { // nNewTopLine ++; nNewTopLine = FindVisibleLine(nNewTopLine, 1); if (pt.y >= rcClient.bottom + GetLineHeight()) nNewTopLine += 2; } if (nNewTopLine < 0) nNewTopLine = 0; if (nNewTopLine >= nLineCount) nNewTopLine = nLineCount - 1; if (m_nTopLine != nNewTopLine) { ScrollToLine(nNewTopLine); UpdateSiblingScrollPos(TRUE); bChanged = TRUE; } // Scroll horizontally, if necessary int nNewOffsetChar = m_nOffsetChar; int nMaxLineLength = GetMaxLineLength(); if (pt.x < rcClient.left) nNewOffsetChar --; else if (pt.x >= rcClient.right) nNewOffsetChar ++; if (nNewOffsetChar >= nMaxLineLength) nNewOffsetChar = nMaxLineLength - 1; if (nNewOffsetChar < 0) nNewOffsetChar = 0; if (m_nOffsetChar != nNewOffsetChar) { ScrollToChar(nNewOffsetChar); UpdateCaret(); UpdateSiblingScrollPos(FALSE); bChanged = TRUE; } // Fix changes if (bChanged) { AdjustTextPoint(pt); CPoint ptNewCursorPos = ClientToText(pt); if (ptNewCursorPos != m_ptCursorPos) { m_ptCursorPos = ptNewCursorPos; UpdateCaret(); } SetSelection(m_ptAnchor, m_ptCursorPos); } } } void CCrystalTextView::OnLButtonDblClk(UINT nFlags, CPoint point) { CView::OnLButtonDblClk(nFlags, point); if (! m_bDragSelection) { AdjustTextPoint(point); m_ptCursorPos = ClientToText(point); m_ptAnchor = m_ptCursorPos; CPoint ptStart, ptEnd; if (m_ptCursorPos.y < m_ptAnchor.y || m_ptCursorPos.y == m_ptAnchor.y && m_ptCursorPos.x < m_ptAnchor.x) { ptStart = WordToLeft(m_ptCursorPos); ptEnd = WordToRight(m_ptAnchor); } else { ptStart = WordToLeft(m_ptAnchor); ptEnd = WordToRight(m_ptCursorPos); } m_ptCursorPos = ptEnd; UpdateCaret(); EnsureVisible(m_ptCursorPos); SetSelection(ptStart, ptEnd); SetCapture(); m_nDragSelTimer = SetTimer(CRYSTAL_TIMER_DRAGSEL, 100, NULL); ASSERT(m_nDragSelTimer != 0); m_bWordSelection = TRUE; m_bLineSelection = FALSE; m_bDragSelection = TRUE; } } void CCrystalTextView::OnEditCopy() { Copy(); } void CCrystalTextView::OnUpdateEditCopy(CCmdUI* pCmdUI) { pCmdUI->Enable(m_ptSelStart != m_ptSelEnd); } void CCrystalTextView::OnEditSelectAll() { SelectAll(); } void CCrystalTextView::OnUpdateEditSelectAll(CCmdUI* pCmdUI) { pCmdUI->Enable(TRUE); } void CCrystalTextView::OnRButtonDown(UINT nFlags, CPoint point) { CPoint pt = point; AdjustTextPoint(pt); pt = ClientToText(pt); if (! IsInsideSelBlock(pt)) { m_ptAnchor = m_ptCursorPos = pt; SetSelection(m_ptCursorPos, m_ptCursorPos); EnsureVisible(m_ptCursorPos); UpdateCaret(); } CView::OnRButtonDown(nFlags, point); } BOOL CCrystalTextView::IsSelection() { return m_ptSelStart != m_ptSelEnd; } void CCrystalTextView::Copy() { if (m_ptSelStart == m_ptSelEnd) return; PrepareSelBounds(); CString text; GetText(m_ptDrawSelStart, m_ptDrawSelEnd, text); PutToClipboard(text); } BOOL CCrystalTextView::TextInClipboard() { return IsClipboardFormatAvailable(CF_TEXT); } BOOL CCrystalTextView::PutToClipboard(LPCTSTR pszText) { if (pszText == NULL || lstrlen(pszText) == 0) return FALSE; CWaitCursor wc; BOOL bOK = FALSE; if (OpenClipboard()) { EmptyClipboard(); HGLOBAL hData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, lstrlen(pszText) + 1); if (hData != NULL) { LPSTR pszData = (LPSTR) ::GlobalLock(hData); USES_CONVERSION; strcpy(pszData, T2A((LPTSTR) pszText)); GlobalUnlock(hData); bOK = SetClipboardData(CF_TEXT, hData) != NULL; } CloseClipboard(); } return bOK; } BOOL CCrystalTextView::GetFromClipboard(CString &text) { BOOL bSuccess = FALSE; if (OpenClipboard()) { HGLOBAL hData = GetClipboardData(CF_TEXT); if (hData != NULL) { LPSTR pszData = (LPSTR) GlobalLock(hData); if (pszData != NULL) { text = pszData; GlobalUnlock(hData); bSuccess = TRUE; } } CloseClipboard(); } return bSuccess; } void CCrystalTextView::MarkCollapsibleBlockLine(int nLineIndex, bool bStart) { ASSERT(nLineIndex >= 0); m_pTextBuffer->SetLineFlag(nLineIndex, LF_COLLAPSIBLE_BLOCK_START, bStart, false); m_pTextBuffer->SetLineFlag(nLineIndex, LF_COLLAPSIBLE_BLOCK_END, !bStart, false); } void CCrystalTextView::ClearCollapsibleBlockMark(int nLineIndex) { ASSERT(nLineIndex >= 0); DWORD dwFlags= m_pTextBuffer->GetLineFlags(nLineIndex); DWORD dwBlock= LF_COLLAPSIBLE_BLOCK_START | LF_COLLAPSIBLE_BLOCK_END; if (dwFlags & dwBlock) { if (dwFlags & LF_COLLAPSED_BLOCK) // line is hidden? VERIFY(CollapseBlock(nLineIndex)); m_pTextBuffer->SetLineFlag(nLineIndex, LF_COLLAPSIBLE_BLOCK_START, false, false); m_pTextBuffer->SetLineFlag(nLineIndex, LF_COLLAPSIBLE_BLOCK_END, false, false); } } void CCrystalTextView::OnToggleCollapsibleBlock() { if (!CollapseBlock(m_ptCursorPos.y)) MessageBeep(MB_OK); } void CCrystalTextView::OnCollapseAllBlocks() { CollapseAllBlocks(true); } void CCrystalTextView::OnExpandAllBlocks() { CollapseAllBlocks(false); } // collapse/expand all blocks // void CCrystalTextView::CollapseAllBlocks(bool bCollapse) { if (m_pTextBuffer == NULL) return; int nLineCount= m_pTextBuffer->GetLineCount(); int nCurrentLine= m_ptCursorPos.y; for (int nLine= 0; nLine < nLineCount; ++nLine) { // find block beginning DWORD dwFlags= m_pTextBuffer->GetLineFlags(nLine); if (dwFlags & LF_COLLAPSIBLE_BLOCK_START) { int nLineFrom= -1; int nLineTo= -1; // find end of current block (note: there may be no end; // then just go on and try to locate next block) if (FindCollapsibleBlock(nLine, nLineFrom, nLineTo)) { ASSERT(nLine == nLineFrom); // here we do not care about nested blocks, (un)cover everything if (bCollapse) m_pTextBuffer->SetLinesFlags(nLineFrom, nLineTo, LF_COLLAPSED_BLOCK, 0); else m_pTextBuffer->SetLinesFlags(nLineFrom, nLineTo, 0, LF_COLLAPSED_BLOCK); // move current line to the first line of collapsed block if it lies inside // just folded (hidden) block if (bCollapse && nCurrentLine >= nLineFrom && nCurrentLine <= nLineTo) nCurrentLine = nLineFrom; nLine = nLineTo; } } } // update views m_pTextBuffer->UpdateViews(0, 0, UPDATE_HORZRANGE | UPDATE_VERTRANGE, 0); // TODO: preserve top line // if (bCollapse) { // cancel selection & move cursor out of hidden block GoToLine(nCurrentLine); } } // find beginning and end of block containing 'nLineInsideBlock' and // collase/expand this block; fn handles nested blocks // bool CCrystalTextView::CollapseBlock(int nLineInsideBlock) { int nLineFrom= -1; int nLineTo= -1; if (FindCollapsibleBlock(nLineInsideBlock, nLineFrom, nLineTo)) return CollapseBlock(nLineFrom, nLineTo); return false; } // find beginning and end of block containing 'nLineInsideBlock' // bool CCrystalTextView::FindCollapsibleBlock(int nLineInsideBlock, int& nLineFrom, int& nLineTo) { if (m_pTextBuffer == NULL) return false; int nLineCount= m_pTextBuffer->GetLineCount(); ASSERT(nLineInsideBlock >= 0 && nLineInsideBlock < nLineCount); nLineFrom = -1; int nLevel= 0; for (int nLine= nLineInsideBlock; nLine >= 0; --nLine) { DWORD dwFlags= m_pTextBuffer->GetLineFlags(nLine); if (dwFlags & LF_COLLAPSIBLE_BLOCK_END) if (nLine < nLineInsideBlock) ++nLevel; // nested block if (dwFlags & LF_COLLAPSIBLE_BLOCK_START) { if (nLevel == 0) { nLineFrom = nLine; break; } --nLevel; } } if (nLineFrom < 0) return false; nLevel = 0; nLineTo = -1; { for (int nLine= nLineInsideBlock; nLine < nLineCount; ++nLine) { DWORD dwFlags= m_pTextBuffer->GetLineFlags(nLine); if (dwFlags & LF_COLLAPSIBLE_BLOCK_START) if (nLine > nLineInsideBlock) ++nLevel; // nested block if (dwFlags & LF_COLLAPSIBLE_BLOCK_END) { if (nLevel == 0) { nLineTo = nLine; break; } --nLevel; } } } if (nLineTo < 0) return false; if (nLineFrom >= nLineTo) return false; // no single-line blocks /* if (nLineTo == nLineCount - 1) // block span to the end of text? { --nLineTo; // last line has to be visible... if (nLineTo < 1) return false; } */ return true; } bool CCrystalTextView::CollapseBlock(int nLineFrom, int nLineTo) { if (m_pTextBuffer == NULL) return false; int nLineCount= m_pTextBuffer->GetLineCount(); if (nLineFrom < 0 || nLineFrom >= nLineCount || nLineTo < 0 || nLineTo >= nLineCount || nLineFrom > nLineTo) { ASSERT(false); return false; } DWORD dwFlagsFrom= m_pTextBuffer->GetLineFlags(nLineFrom); DWORD dwFlagsTo= m_pTextBuffer->GetLineFlags(nLineTo); if ((dwFlagsFrom & LF_COLLAPSIBLE_BLOCK_START) == 0 || (dwFlagsTo & LF_COLLAPSIBLE_BLOCK_END) == 0) { ASSERT(false); return false; } bool bHide= !(dwFlagsFrom & LF_COLLAPSED_BLOCK); if (bHide) m_pTextBuffer->SetLinesFlags(nLineFrom, nLineTo, LF_COLLAPSED_BLOCK, 0); else m_pTextBuffer->SetLinesFlags(nLineFrom, nLineTo, 0, LF_COLLAPSED_BLOCK); /* // mark first and last line m_pTextBuffer->SetLineFlag(nLineFrom, LF_COLLAPSED_BLOCK, bHide, false); m_pTextBuffer->SetLineFlag(nLineTo, LF_COLLAPSED_BLOCK, bHide, false); // mark lines inside block, but leave nested blocks intact int nLevel= 0; for (int nLine= nLineFrom + 1; nLine < nLineTo; ++nLine) { DWORD dwFlags= m_pTextBuffer->GetLineFlags(nLine); if (dwFlags & LF_COLLAPSIBLE_BLOCK_START) ++nLevel; if (dwFlags & LF_COLLAPSIBLE_BLOCK_END) --nLevel; if (nLevel == 0) m_pTextBuffer->SetLineFlag(nLine, LF_COLLAPSED_BLOCK, bHide, false); } ASSERT(nLevel == 0); */ // update views m_pTextBuffer->UpdateViews(0, 0, UPDATE_HORZRANGE | UPDATE_VERTRANGE, 0); if (bHide) { // cancel selection & move cursor out of hidden block GoToLine(nLineFrom); } return true; } bool CCrystalTextView::IsLineCollapsed(int nLine) { if (m_pTextBuffer == NULL || nLine >= m_pTextBuffer->GetLineCount()) return false; DWORD dwFlags= m_pTextBuffer->GetLineFlags(nLine); return !!(dwFlags & LF_COLLAPSED_BLOCK); } bool CCrystalTextView::IsLineHidden(int nLine) { if (m_pTextBuffer == NULL || nLine >= m_pTextBuffer->GetLineCount()) return false; DWORD dwFlags= m_pTextBuffer->GetLineFlags(nLine); if (dwFlags & LF_COLLAPSED_BLOCK) // hidden block? { if (dwFlags & LF_COLLAPSIBLE_BLOCK_START) // first line in a block? { if (nLine > 0) { // check if previous line is visible DWORD dwFlags= m_pTextBuffer->GetLineFlags(nLine - 1); if (dwFlags & LF_COLLAPSED_BLOCK) // not visible? { // TODO: pathological case of adjacent blocks return true; // hide this first line as well } } return false; // first line in block is usually visible (unless it's nested block) } return true; } return false; // normal (visible) lines } bool CCrystalTextView::IsFirstLineOfCollapsedBlock(int nLine) { if (m_pTextBuffer == NULL || nLine >= m_pTextBuffer->GetLineCount()) return false; DWORD dwFlags= m_pTextBuffer->GetLineFlags(nLine); if (dwFlags & LF_COLLAPSED_BLOCK && dwFlags & LF_COLLAPSIBLE_BLOCK_START) return true; return false; } void CCrystalTextView::DrawEllipsis(CDC* pDC, const CRect& rcLine) { pDC->FillSolidRect(rcLine, GetColor(COLORINDEX_WHITESPACE)); pDC->SelectObject(GetFont(false, false)); pDC->SetTextColor(GetColor(COLORINDEX_ELLIPSIS)); pDC->TextOut(rcLine.left, rcLine.top, _T("..."), 3); } int CCrystalTextView::FindVisibleLine(int nLine, int nDelta) { int nLineCount= GetLineCount(); if (nLineCount == 0) return -1; int nInc= nDelta > 0 ? 1 : -1; for (; ; nLine += nInc) { if (nLine < 0) return 0; if (nLine >= nLineCount) { if (IsLineHidden(nLineCount - 1)) // last line hidden? return FindVisibleLine(nLineCount - 1, 0); return nLineCount - 1; } // skip hidden lines if (IsLineHidden(nLine)) continue; if (nDelta == 0) break; if (nDelta > 0) --nDelta; else ++nDelta; } return nLine; } int CCrystalTextView::CalcVisibleLines() { return CalcVisibleLines(0, GetLineCount()); } int CCrystalTextView::CalcVisibleLines(int nFromLine, int nToLine) { bool bSwap= false; if (nFromLine > nToLine) { std::swap(nFromLine, nToLine); bSwap = true; } ASSERT(nFromLine >= 0 && nToLine >= 0 && nFromLine <= nToLine); int nLineCount= GetLineCount(); ASSERT(nToLine <= nLineCount); int nVisCount= 0; for (int nLine= nFromLine; nLine < nToLine; ++nLine) if (!IsLineHidden(nLine)) nVisCount++; return bSwap ? -nVisCount : nVisCount; } void CCrystalTextView::ExpandCurrentLine() { ExpandLine(GetCursorPos().y); } void CCrystalTextView::ExpandLine(int nLine) { if (IsLineCollapsed(nLine)) { // expand block (CollapseBlock toggles it back to expanded state) CollapseBlock(nLine); } } void CCrystalTextView::NotifyTextChanged() {} void CCrystalTextView::CaretMoved() { int nLine= m_ptCursorPos.y; if (m_pTextBuffer == 0 || nLine >= GetLineCount()) return; int nStart= 0; int nEnd= 0; CString strLine; int nLength= GetLineLength(nLine); if (nLength != 0) { m_pTextBuffer->GetText(nLine, 0, nLine, nLength, strLine); nLength = strLine.GetLength(); int x= m_ptCursorPos.x; if (x >= 0 && x <= nLength) { nStart = x; while (nStart > 0 && strLine[nStart - 1] > ' ') --nStart; nEnd = x; while (nEnd < nLength && strLine[nEnd] > ' ') ++nEnd; } } CaretMoved(strLine, nStart, nEnd); } void CCrystalTextView::CaretMoved(const CString& strLine, int nWordStart, int nWordEnd) {}
24.542369
122
0.701182
[ "vector" ]