blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
3cfa9cf4a32e7d3a685d452eb44f1f03b44c982c
74b9993cd3402d5d664a89e851505d71ad88c609
/Source/tests/InverterModuleTest.cpp
4efe7208178093913bbd5d3953e4f4d30df6c7fc
[]
no_license
geeksperiments/Synthlab
dae633545c8448f029483076e0468e97073f1e82
7b23907be2216b3c039b148a36e7b42495191867
refs/heads/master
2023-04-27T01:00:19.914715
2021-05-18T19:48:54
2021-05-18T19:48:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,591
cpp
/* ============================================================================== InverterModuleTest.cpp Created: 5 May 2018 4:52:38pm Author: Matthias Pueski ============================================================================== */ #include <gtest.h> #include "../Constant.h" #include "../InverterModule.h" #include "../ModuleUtils.h" // This test checks the inverter module (Category maths), we simply connect two Constant modules // set the according values and check the output. TEST(InverterModule, invertValue) { // create the constant and set the value Constant* c1 = new Constant(); // always configure the pins before setting values or connecting something, during runtime this is done by the editor c1->configurePins(); c1->setValue(10); // now for the module InverterModule* m = new InverterModule(); // same as above m->configurePins(); // connects pin 0 of the constant C1 with pin 0 of the module ASSERT_TRUE(ModuleUtils::connectModules(c1, m, 0)); // we need to call the process method in order to be able to retrieve a result // this is usually called repeatedly by the audio callback, so we have to teke care // to call this manually during testing. m->process(); // expect the result to be at pin 1 of the inverter // TODO : we should loop through a few distinct ranges to prove the modules answers to be correct in any case. ASSERT_EQ(0.1f, m->getPins().at(1)->getValue()); // cleanup delete c1; delete m; }
[ "matthias@pueski.de" ]
matthias@pueski.de
5a92376f6034df83d4a434a4796bf1d72d1bba2f
4f951e96accafe3ae8f687d18e142a8c9c657d05
/foundation_questions/q57.cpp
ab1e27d10fba5815f86310c8b0c95c429b3b9cbe
[]
no_license
amey16/Important-codes
ef9ef780d81f57198959ad784b242b284d89c4af
6ddee5e4c52bdefbbf0bbcf13b6c7b852ce67746
refs/heads/master
2022-06-20T12:10:49.642747
2020-05-12T09:15:51
2020-05-12T09:15:51
260,652,677
0
0
null
null
null
null
UTF-8
C++
false
false
309
cpp
#include<iostream> #include<string> using namespace std; int main(int argc,char** argv){ string s; cin>>s; string sn=""; sn.push_back(s[0]); for(int i=0;i<s.length()-1;i++){ int cnt=s[i+1]-s[i]; sn+=to_string(cnt); sn.push_back(s[i+1]); } cout<<sn<<endl; }
[ "ameyagupta19@gmail.com" ]
ameyagupta19@gmail.com
34ee599c5e1440ed067924e3511c02e83d694cdd
a2206795a05877f83ac561e482e7b41772b22da8
/Source/PV/build/VTK/Wrapping/Python/FortranAdaptorAPIPython.cxx
bcf336c9ed381dcdd2a17b331aec96d4e4934f18
[]
no_license
supreethms1809/mpas-insitu
5578d465602feb4d6b239a22912c33918c7bb1c3
701644bcdae771e6878736cb6f49ccd2eb38b36e
refs/heads/master
2020-03-25T16:47:29.316814
2018-08-08T02:00:13
2018-08-08T02:00:13
143,947,446
0
0
null
null
null
null
UTF-8
C++
false
false
626
cxx
// python wrapper for FortranAdaptorAPI // #define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include "vtkPythonArgs.h" #include "vtkPythonOverload.h" #include "vtkConfigure.h" #include <vtksys/ios/sstream> #include "FortranAdaptorAPI.h" #if defined(VTK_BUILD_SHARED_LIBS) # define VTK_PYTHON_EXPORT VTK_ABI_EXPORT # define VTK_PYTHON_IMPORT VTK_ABI_IMPORT #else # define VTK_PYTHON_EXPORT VTK_ABI_EXPORT # define VTK_PYTHON_IMPORT VTK_ABI_EXPORT #endif extern "C" { VTK_PYTHON_EXPORT void PyVTKAddFile_FortranAdaptorAPI(PyObject *, const char *); } void PyVTKAddFile_FortranAdaptorAPI( PyObject *, const char *) { }
[ "mpasVM@localhost.org" ]
mpasVM@localhost.org
c371a155d396dc8ddf765fab39ba3a2a7a1f858c
846911ed5bcf30e71b946a2600edce11cc9a1594
/lib/acgl/include/ACGL/Math/Constants.hh
655e680683bc546499078185e33745e8bc01675b
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
valkum/game-programming
534d52fe7239ecfab6fb358646c4b325ccc57f14
0e6749553601d1800495ae729d26a97500177ac8
refs/heads/master
2021-01-21T16:27:27.748992
2016-03-13T16:16:01
2016-03-13T16:16:01
45,193,557
0
0
null
null
null
null
UTF-8
C++
false
false
2,455
hh
/*********************************************************************** * Copyright 2011-2012 Computer Graphics Group RWTH Aachen University. * * All rights reserved. * * Distributed under the terms of the MIT License (see LICENSE.TXT). * **********************************************************************/ #ifndef ACGL_MATH_CONSTANTS_HH #define ACGL_MATH_CONSTANTS_HH /* * Some mathmatical constants, for example readable degree to rad conversion. * * DON'T INCLUDE THIS DIRECTLY! Include <ACGL/Math.hh> instead! */ #ifndef ACGL_MATH_HH #warning "Include Math.hh instead of Constants.hh directly" #endif #include <ACGL/ACGL.hh> #include <cmath> #include <limits> #ifndef M_PI // M_PI is not defined on e.g. VS2010 (isn't part of the standart), so in that case it gets defined here // outside of the namespace because some code might expect it to be in math.h which is obviously not in our namespace... #define M_PI 3.14159265358979323846 #endif namespace ACGL{ namespace Math{ namespace Constants{ //some important constants const float INF_FLOAT = std::numeric_limits<float>::infinity(); const double INF_DOUBLE = std::numeric_limits<double>::infinity(); const int_t INF_INT = std::numeric_limits<int_t>::infinity(); const short_t INF_SHORT = std::numeric_limits<short_t>::infinity(); template<typename T> inline T INF(void) { return T(); } template<> inline float INF<float> (void) { return INF_FLOAT; } template<> inline double INF<double> (void) { return INF_DOUBLE; } template<> inline int_t INF<int_t> (void) { return INF_INT; } template<> inline short_t INF<short_t> (void) { return INF_SHORT; } //constants to change from degree to radians and back const float DEG_TO_RAD_FLOAT = M_PI / 180.0f; const double DEG_TO_RAD_DOUBLE = M_PI / 180.0 ; const float RAD_TO_DEG_FLOAT = 180.0f / M_PI; const double RAD_TO_DEG_DOUBLE = 180.0 / M_PI; template<typename T> inline T DEG_TO_RAD(void) { return T(); } template<> inline float DEG_TO_RAD<float> (void) { return DEG_TO_RAD_FLOAT; } template<> inline double DEG_TO_RAD<double>(void) { return RAD_TO_DEG_DOUBLE; } template<typename T> inline T RED_TO_DEG(void) { return T(); } template<> inline float RED_TO_DEG<float> (void) { return DEG_TO_RAD_FLOAT; } template<> inline double RED_TO_DEG<double>(void) { return RAD_TO_DEG_DOUBLE; } } // Constants } // Math } // ACGL #endif // ACGL_MATH_CONSTANTS_HH
[ "rudi.floren@googlemail.com" ]
rudi.floren@googlemail.com
845e2d1b4eb8697905ae041f0c0c0b072bfb9227
486b15bc1abf2cda3fcb733b6d31a6b9364020eb
/safety_diagnostics/safety_monitor/include/avidbots_safety_monitor/sm_manager.h
6532e920d42ba700d07b44783758e2952b959210
[]
no_license
xnvst/robotics
376f6a6f6a95cca8ce7606f4e74b4abb94687334
8e12abe1e2d6d618118aadc8d8858df78cd74f08
refs/heads/master
2021-01-16T00:09:33.455018
2019-04-14T19:40:24
2019-04-14T19:40:24
99,957,587
0
0
null
null
null
null
UTF-8
C++
false
false
4,701
h
/* * ______ __ __ __ * /\ _ \ __ /\ \/\ \ /\ \__ * \ \ \L\ \ __ __ /\_\ \_\ \ \ \____ ___\ \ ,_\ ____ * \ \ __ \/\ \/\ \\/\ \ /'_` \ \ '__`\ / __`\ \ \/ /',__\ * \ \ \/\ \ \ \_/ |\ \ \/\ \L\ \ \ \L\ \/\ \L\ \ \ \_/\__, `\ * \ \_\ \_\ \___/ \ \_\ \___,_\ \_,__/\ \____/\ \__\/\____/ * \/_/\/_/\/__/ \/_/\/__,_ /\/___/ \/___/ \/__/\/___/ * Copyright 2016, Avidbots Corp. * @name sm_manager * @brief Header file for SafetyMonitorManager class * @author Keshav Iyengar, Feng Cao */ #ifndef AVIDBOTS_SAFETY_MONITOR_SM_MANAGER_H #define AVIDBOTS_SAFETY_MONITOR_SM_MANAGER_H #include <ecl/time.hpp> // CPP #include <string> // ROS #include <ros/ros.h> // LOCAL #include "avidbots_safety_monitor/sm_ros_interface.h" #include "avidbots_safety_monitor/states/state_base.h" #include "avidbots_safety_monitor/sm_constants.h" // PCL #include <pcl_ros/point_cloud.h> #include <pcl/common/transforms.h> // Other #include <visualization_msgs/Marker.h> class StateBase; class ROSInterface; /** * @name SafetyMonitorManager * @brief main state machine. */ class SMManager { friend class StateBase; public: SMManager(); ~SMManager(); void Initialize(); void Update(); void StateTransition(StateBase* state); /* Events */ void SMStateEvent(Events event); /* Setters */ void SetDiagnosticsStatus(ErrorStatus status); void SetExpSafetyZoneStatus(ErrorStatus status); void SetDangerZoneStatus(ErrorStatus status); void SetEStopStatus(ErrorStatus status); void SetLowVoltageStatus(ErrorStatus status); void SetLocalControllerSafetyStatus(ErrorStatus status); void SetSmFailureReset(bool reset); void SetCount(int count); void SetState(States state); void SetDiagnosticsTimeout(double val); void SetSkipDangerObstacleReset(bool reset); void SetObstacleTimeout(double val); void SetEnableLowVoltage(bool status); void SetEnableDiagnostics(bool status); void SetEnableSafetyMonitor(bool status); void SetEnableDangerZone(bool status); void SetEnableExpSafetyZone(bool status); void SetDangerZoneZeroVelEnabled(bool status); void SetDiagnosticsDescription(std::string description); void SetUIState(int val); /* Getters */ States GetState() const; bool GetSmFailureReset() const; ErrorStatus GetEStopStatus() const; ErrorStatus GetDiagnosticsStatus() const; ErrorStatus GetDangerZoneStatus() const; ErrorStatus GetExpSafetyZoneStatus() const; ErrorStatus GetLowVoltageStatus() const; ErrorStatus GetLocalControllerSafetyStatus() const; ecl::TimeStamp GetFailureStopWatchElapsed(); double GetDiagnosticsTimeout() const; bool GetSkipDangerObstacleReset() const; double GetObstacleTimeout() const; bool GetEnableLowVoltage() const; bool GetEnableDiagnostics() const; bool GetEnableSafetyMonitor() const; bool GetEnableDangerZone() const; bool GetEnableExpSafetyZone() const; bool GetDangerZoneZeroVelEnabled() const; std::string GetDiagnosticsDescription() const; int GetUIState() const; void RestartFailureStopWatch(); /* Publish MSG */ void PublishState(std_msgs::String state_msg_); void PublishSMStatus(avidbots_msgs::sm_status sm_status); void PublishZeroVelocity(); void PublishMCUOutputCommand(); void PublishDangerZoneObstacle(bool status); private: /* ROS Interface */ ROSInterface* ros_; /* State */ StateBase* state_; States prev_state_; States curr_state_; States next_state_; Events curr_event_; /* UI State */ int ui_state_; /* State Transition Variables, true -- ok, false -- error */ ErrorStatus sm_manager_diagnostics_status_; ErrorStatus sm_manager_exp_safetyzone_status_; ErrorStatus sm_manager_dangerzone_status_; ErrorStatus sm_manager_low_voltage_status_; ErrorStatus sm_manager_estop_status_; ErrorStatus sm_manager_local_controller_safety_status_; std::string sm_manager_diagnostics_description_; /* Failure Reset Variable, true if the safety monitor failure is reset */ bool sm_manager_failure_reset_; /* Parameters */ double sm_manager_diagnostics_timeout_; double sm_manager_obstacle_timeout_; bool sm_manager_skip_danger_obstacle_reset_; /* Enable Flags */ bool sm_manager_enable_low_voltage_monitor_; bool sm_manager_enable_diagnostics_monitor_; bool sm_manager_enable_safety_monitor_; bool sm_manager_enable_danger_zone_; bool sm_manager_enable_exp_safety_zone_; bool sm_manager_enable_dangerzone_zero_vel_; ecl::StopWatch sm_manager_failure_stopwatch_; }; #endif // AVIDBOTS_SAFETY_MONITOR_SM_MANAGER_H
[ "ynttmp@gmail.com" ]
ynttmp@gmail.com
0ab6f0c270721623c86bca359cd81930b0975019
4ff4c681e2876fa61f82601a7fc9c903c0ba589f
/175/b.cpp
0ddb77b322338ab81a5e345b19201fc58a8cc71f
[]
no_license
noaka7/abc
ae8af2cb3b611ad30e189cdbf0de8acfaa6ed6e5
ef6630cb0e1994b3938d617e231778847651d98b
refs/heads/main
2023-08-15T13:06:51.491099
2021-07-16T14:10:27
2021-09-26T23:15:26
378,954,271
0
0
null
null
null
null
UTF-8
C++
false
false
1,194
cpp
// Since N≤100, it is possible try all tuples (i,j,k) and check if it forms a // triangle. Three sides of length a, b and c forms a triangle if and only if // a+b>c, // b+c>a and // c+a>b, // so you can solve this problem by checking the following two conditions: (Li, // Lj and Lk are all different, and) Li, Lj and Lk satisfies the condition // above. // The total time complexity is O(N^3). // Just an aside, if you sort L firsthand and assume that they satisfy // L1≤L2,⋯,≤LN, the only triangular inequality that has to be check is that // Li+Lj>Lk. #include <cstdlib> #include <iostream> using namespace std; int compar(const void *a, const void *b) { return (*(int *)a - *(int *)b); } int main() { int N, ans; int A[100]; cin >> N; for (int i = 0; i < N; i++) { cin >> A[i]; } qsort(A, N, sizeof(int), compar); ans = 0; for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { if (A[i] == A[j]) { continue; } for (int k = j + 1; k < N; k++) { if (A[j] == A[k]) { continue; } if (A[i] + A[j] > A[k]) { ans++; } } } } cout << ans; return 0; }
[ "kphourat@gmail.com" ]
kphourat@gmail.com
947a4099be14ed423094eef782ad08fc4642350d
16ca5774ff2ab5fbbcf0b7ff4e8fbcc80abe87ee
/hse/2016/1/cpp/exam/d.h
fc439a33798fb9f6e93817b41873d97a10a3687e
[]
no_license
yazevnul/teaching
f68c6186c40e021fdb1f776b1f515c6c27332634
65cc0187d8f089a6cf69d758fb17c441ad1585e9
refs/heads/master
2020-07-20T18:56:52.958364
2016-10-22T15:50:45
2016-10-22T15:50:45
67,862,644
0
0
null
null
null
null
UTF-8
C++
false
false
900
h
#include <iostream> #include <string> // https://contest.yandex.ru/contest/3016/problems/D/ class Serializer { public: virtual ~Serializer() = 0; virtual void BeginArray() = 0; virtual void AddArrayItem(const std::string&) = 0; virtual void EndArray() = 0; }; Serializer::~Serializer() = default; class JsonSerializer : public Serializer { bool is_first_item_{true}; std::ostream& out_{std::cout}; public: void BeginArray() override { AddComma(); out_ << '['; is_first_item_ = true; } void AddArrayItem(const std::string& item) override { AddComma(); out_ << '"' << item << '"'; } void EndArray() override { is_first_item_ = false; out_ << ']'; } private: void AddComma() { if (!is_first_item_) { out_ << ','; } is_first_item_ = false; } };
[ "kostyabazhanov@mail.ru" ]
kostyabazhanov@mail.ru
6186ffbff9ee3a1a818a9d1cf28bdd5e085ea0fd
249197424bd8faaa99527c6374dcbb97d01511dd
/Code/tester codes/screen_tester/screen_tester.ino
63daa71d60cd9c68f45b0efba89f07ba1bf492d7
[]
no_license
BrandonBNguyen/Pitot-Static-Tube-Project
bc80c6d888b985c08f85d704a607c24094e706f7
9c1007f7a604f316be7594879966f40204460638
refs/heads/master
2023-03-24T00:04:29.421104
2021-03-25T20:25:58
2021-03-25T20:25:58
329,197,481
1
0
null
null
null
null
UTF-8
C++
false
false
228
ino
#include <Adafruit_SSD1306.h> #include <splash.h> #include <Wire.h> #include <Adafruit_SSD1306.h> void setup() { // put your setup code here, to run once: } void loop() { // put your main code here, to run repeatedly: }
[ "BrandonBanhNguyen@gmail.com" ]
BrandonBanhNguyen@gmail.com
3d0f891cb168988a1ea80964cfc35cc0e5e05f28
f1f884b94ebc55f5b4e65240d8900fa03389fc4b
/src/libhdr/tag.h
6c11dbb5e48031678e98a44bcbb574a121bda9a5
[]
no_license
LuminanceHDR/LibHDR
66703f9378707481ce7967dd26f70334bc93b1c7
ff4e79e6a52f73ec3cdefe15cccdf6688e22ed83
refs/heads/master
2023-08-25T21:33:49.015431
2012-07-01T15:00:38
2012-07-01T15:00:38
2,470,919
3
4
null
null
null
null
UTF-8
C++
false
false
2,287
h
/* * This file is a part of LibHDR package. * ---------------------------------------------------------------------- * Copyright (C) 2011 Davide Anastasia * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * ---------------------------------------------------------------------- */ #ifndef LIBHDR_TAG #define LIBHDR_TAG #include <map> #include <string> namespace LibHDR { //! \brief TagContainer interface allows to read and modify tags. A tag is "name"="value" pair. typedef std::map<std::string, std::string> TagContainer; typedef std::pair<std::string, std::string> Tag; // /** // * Copy all tags from both the frame and its channels to the // * destination frame. If there is no corresponding destination // * channel for a source channel, the tags from that source channel // * will not be copied. Note, that all tags in the destination // * channel will be removed before copying. Therefore after this // * operation, the destination will contain exactly the same tags as // * the source. // */ //void copyTags( Frame *from, Frame *to ); // /** // * Copy all tags from one container into another. Note, that all // * tags in the destination channel will be removed before // * copying. Therefore after this operation, the destination will // * contain exactly the same tags as the source. // */ //void copyTags( const TagContainer *from, TagContainer *to ); //void writeTags( const TagContainer *tags, FILE *out ); //void readTags( TagContainer *tags, FILE *in ); } // namespace LibHDR #endif // LIBHDR_TAG
[ "davideanastasia@users.sourceforge.net" ]
davideanastasia@users.sourceforge.net
842c259ceb7ba1a9806d95d7d43b404e685c4290
7f18180685eb683cc46edd9ad73306a365e501cd
/Romulus/Source/Resource/IResourceProvider.cpp
96b373900b63dc451fa2117bc261aec294a03bea
[]
no_license
jfhamlin/perry
fab62ace7d80cb4d661c26b901263d4ad56b0ac2
2ff74d5c71c254b8857f1d7fac8499eee56ea5ab
refs/heads/master
2021-09-05T04:15:57.545952
2018-01-24T04:35:29
2018-01-24T04:35:29
118,711,533
0
0
null
null
null
null
UTF-8
C++
false
false
136
cpp
#include "Resource/IResourceProvider.h" namespace romulus { IMPLEMENT_BASE_RTTI(ProceduralResourceArguments); } // namespace romulus
[ "james@goforward.com" ]
james@goforward.com
452d2c03434257cbe8e9c3c13df51e739849b497
c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64
/Engine/Source/Editor/VREditor/VREditorFloatingText.cpp
c7d69c9ff4c83f644f3ac922fe0cfcdfc24c3e78
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
windystrife/UnrealEngine_NVIDIAGameWorks
c3c7863083653caf1bc67d3ef104fb4b9f302e2a
b50e6338a7c5b26374d66306ebc7807541ff815e
refs/heads/4.18-GameWorks
2023-03-11T02:50:08.471040
2022-01-13T20:50:29
2022-01-13T20:50:29
124,100,479
262
179
MIT
2022-12-16T05:36:38
2018-03-06T15:44:09
C++
UTF-8
C++
false
false
9,343
cpp
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "VREditorFloatingText.h" #include "UObject/ConstructorHelpers.h" #include "Engine/World.h" #include "Components/StaticMeshComponent.h" #include "Materials/Material.h" #include "Engine/Font.h" #include "Engine/StaticMesh.h" #include "Engine/CollisionProfile.h" #include "Materials/MaterialInstance.h" #include "Materials/MaterialInstanceDynamic.h" #include "GameFramework/WorldSettings.h" #include "Components/TextRenderComponent.h" AFloatingText::AFloatingText() { if (UNLIKELY(IsRunningDedicatedServer())) { return; } // Create root default scene component { SceneComponent = CreateDefaultSubobject<USceneComponent>( TEXT( "SceneComponent" ) ); check( SceneComponent != nullptr ); RootComponent = SceneComponent; } UStaticMesh* LineSegmentCylinderMesh = nullptr; { static ConstructorHelpers::FObjectFinder<UStaticMesh> ObjectFinder( TEXT( "/Engine/VREditor/FloatingText/LineSegmentCylinder" ) ); LineSegmentCylinderMesh = ObjectFinder.Object; check( LineSegmentCylinderMesh != nullptr ); } UStaticMesh* JointSphereMesh = nullptr; { static ConstructorHelpers::FObjectFinder<UStaticMesh> ObjectFinder( TEXT( "/Engine/VREditor/FloatingText/JointSphere" ) ); JointSphereMesh = ObjectFinder.Object; check( JointSphereMesh != nullptr ); } { static ConstructorHelpers::FObjectFinder<UMaterial> ObjectFinder( TEXT( "/Engine/VREditor/FloatingText/LineMaterial" ) ); LineMaterial = ObjectFinder.Object; check( LineMaterial != nullptr ); } // @todo vreditor: Tweak const bool bAllowTextLighting = false; const float TextSize = 1.5f; { FirstLineComponent = CreateDefaultSubobject<UStaticMeshComponent>( TEXT( "FirstLine" ) ); check( FirstLineComponent != nullptr ); FirstLineComponent->SetStaticMesh( LineSegmentCylinderMesh ); FirstLineComponent->SetMobility( EComponentMobility::Movable ); FirstLineComponent->SetupAttachment( SceneComponent ); FirstLineComponent->SetCollisionEnabled( ECollisionEnabled::NoCollision ); FirstLineComponent->bGenerateOverlapEvents = false; FirstLineComponent->SetCanEverAffectNavigation( false ); FirstLineComponent->bCastDynamicShadow = bAllowTextLighting; FirstLineComponent->bCastStaticShadow = false; FirstLineComponent->bAffectDistanceFieldLighting = bAllowTextLighting; FirstLineComponent->bAffectDynamicIndirectLighting = bAllowTextLighting; } { JointSphereComponent = CreateDefaultSubobject<UStaticMeshComponent>( TEXT( "JointSphere" ) ); check( JointSphereComponent != nullptr ); JointSphereComponent->SetStaticMesh( JointSphereMesh ); JointSphereComponent->SetMobility( EComponentMobility::Movable ); JointSphereComponent->SetupAttachment( SceneComponent ); JointSphereComponent->SetCollisionEnabled( ECollisionEnabled::NoCollision ); JointSphereComponent->bGenerateOverlapEvents = false; JointSphereComponent->SetCanEverAffectNavigation( false ); JointSphereComponent->bCastDynamicShadow = bAllowTextLighting; JointSphereComponent->bCastStaticShadow = false; JointSphereComponent->bAffectDistanceFieldLighting = bAllowTextLighting; JointSphereComponent->bAffectDynamicIndirectLighting = bAllowTextLighting; } { SecondLineComponent = CreateDefaultSubobject<UStaticMeshComponent>( TEXT( "SecondLine" ) ); check( SecondLineComponent != nullptr ); SecondLineComponent->SetStaticMesh( LineSegmentCylinderMesh ); SecondLineComponent->SetMobility( EComponentMobility::Movable ); SecondLineComponent->SetupAttachment( SceneComponent ); SecondLineComponent->SetCollisionEnabled( ECollisionEnabled::NoCollision ); SecondLineComponent->bGenerateOverlapEvents = false; SecondLineComponent->SetCanEverAffectNavigation( false ); SecondLineComponent->bCastDynamicShadow = bAllowTextLighting; SecondLineComponent->bCastStaticShadow = false; SecondLineComponent->bAffectDistanceFieldLighting = bAllowTextLighting; SecondLineComponent->bAffectDynamicIndirectLighting = bAllowTextLighting; } { static ConstructorHelpers::FObjectFinder<UMaterial> ObjectFinder( TEXT( "/Engine/VREditor/Fonts/VRTextMaterial" ) ); MaskedTextMaterial = ObjectFinder.Object; check( MaskedTextMaterial != nullptr ); } { static ConstructorHelpers::FObjectFinder<UMaterialInstance> ObjectFinder( TEXT( "/Engine/VREditor/Fonts/TranslucentVRTextMaterial" ) ); TranslucentTextMaterial = ObjectFinder.Object; check( TranslucentTextMaterial != nullptr ); } UFont* TextFont = nullptr; { static ConstructorHelpers::FObjectFinder<UFont> ObjectFinder( TEXT( "/Engine/VREditor/Fonts/VRText_RobotoLarge" ) ); TextFont = ObjectFinder.Object; check( TextFont != nullptr ); } { TextComponent = CreateDefaultSubobject<UTextRenderComponent>( TEXT( "Text" ) ); check( TextComponent != nullptr ); TextComponent->SetMobility( EComponentMobility::Movable ); TextComponent->SetupAttachment( SceneComponent ); TextComponent->SetCollisionProfileName( UCollisionProfile::NoCollision_ProfileName ); TextComponent->bGenerateOverlapEvents = false; TextComponent->SetCanEverAffectNavigation( false ); TextComponent->bCastDynamicShadow = bAllowTextLighting; TextComponent->bCastStaticShadow = false; TextComponent->bAffectDistanceFieldLighting = bAllowTextLighting; TextComponent->bAffectDynamicIndirectLighting = bAllowTextLighting; TextComponent->SetWorldSize( TextSize ); // Use a custom font. The text will be visible up close. TextComponent->SetFont( TextFont ); // Assign our custom text rendering material. TextComponent->SetTextMaterial( MaskedTextMaterial ); TextComponent->SetTextRenderColor( FLinearColor::White.ToFColor( false ) ); // Left justify the text TextComponent->SetHorizontalAlignment( EHTA_Left ); } } void AFloatingText::PostActorCreated() { Super::PostActorCreated(); // Create an MID so that we can change parameters on the fly (fading) check( LineMaterial != nullptr ); this->LineMaterialMID = UMaterialInstanceDynamic::Create( LineMaterial, this ); FirstLineComponent->SetMaterial( 0, LineMaterialMID ); JointSphereComponent->SetMaterial( 0, LineMaterialMID ); SecondLineComponent->SetMaterial( 0, LineMaterialMID ); } void AFloatingText::SetText( const FText& NewText ) { check( TextComponent != nullptr ); TextComponent->SetText( NewText ); } void AFloatingText::SetOpacity( const float NewOpacity ) { const FLinearColor NewColor = FLinearColor( 0.6f, 0.6f, 0.6f ).CopyWithNewOpacity( NewOpacity ); // @todo vreditor: Tweak brightness const FColor NewFColor = NewColor.ToFColor( false ); check( TextComponent != nullptr ); // if( NewOpacity >= 1.0f - KINDA_SMALL_NUMBER ) // @todo vreditor ui: get fading/translucency working again! // { if( TextComponent->GetMaterial( 0 ) != MaskedTextMaterial ) { TextComponent->SetTextMaterial( MaskedTextMaterial ); } // } // else // { // if( TextComponent->GetMaterial( 0 ) != TranslucentTextMaterial ) // { // TextComponent->SetTextMaterial( TranslucentTextMaterial ); // } // } if( NewFColor != TextComponent->TextRenderColor ) { TextComponent->SetTextRenderColor( NewFColor ); } check( LineMaterialMID != nullptr ); static FName ColorAndOpacityParameterName( "ColorAndOpacity" ); LineMaterialMID->SetVectorParameterValue( ColorAndOpacityParameterName, NewColor ); } void AFloatingText::Update( const FVector OrientateToward ) { // Orientate it toward the viewer const FVector DirectionToward = ( OrientateToward - GetActorLocation() ).GetSafeNormal(); const FQuat TowardRotation = DirectionToward.ToOrientationQuat(); // @todo vreditor tweak const float LineRadius = 0.1f; const float FirstLineLength = 4.0f; // Default line length (note that socket scale can affect this!) const float SecondLineLength = TextComponent->GetTextLocalSize().Y; // The second line "underlines" the text // NOTE: The origin of the actor will be the designated target of the text const FVector FirstLineLocation = FVector::ZeroVector; const FQuat FirstLineRotation = FVector::ForwardVector.ToOrientationQuat(); const FVector FirstLineScale = FVector( FirstLineLength, LineRadius, LineRadius ); FirstLineComponent->SetRelativeLocation( FirstLineLocation ); FirstLineComponent->SetRelativeRotation( FirstLineRotation ); FirstLineComponent->SetRelativeScale3D( FirstLineScale ); // NOTE: The joint sphere draws at the connection point between the lines const FVector JointLocation = FirstLineLocation + FirstLineRotation * FVector::ForwardVector * FirstLineLength; const FVector JointScale = FVector( LineRadius ); JointSphereComponent->SetRelativeLocation( JointLocation ); JointSphereComponent->SetRelativeScale3D( JointScale ); // NOTE: The second line starts at the joint location SecondLineComponent->SetWorldLocation( JointSphereComponent->GetComponentLocation() ); SecondLineComponent->SetWorldRotation( ( TowardRotation * -FVector::RightVector ).ToOrientationQuat() ); SecondLineComponent->SetRelativeScale3D( FVector( ( SecondLineLength / GetActorScale().X ) * GetWorld()->GetWorldSettings()->WorldToMeters / 100.0f, LineRadius, LineRadius ) ); TextComponent->SetWorldLocation( JointSphereComponent->GetComponentLocation() ); TextComponent->SetWorldRotation( ( TowardRotation * FVector::ForwardVector ).ToOrientationQuat() ); }
[ "tungnt.rec@gmail.com" ]
tungnt.rec@gmail.com
3e4eb686349733023807cd1a58085fc57a50fba4
1e63895a52b4825ebde5ceecc69fe5ea28481cca
/02-data-structure-algorithms/modules/002-recursion/code-part-1/006-Check-If-Array-Is-Sorted.cpp
bdf37876cfe5024d4927e1701286cd9f2e1e6814
[]
no_license
NikitaLandge51/codig-ninja-dsa-learning
f970bf12209b433aa329712031579fbb0f02a319
48f18a5fb8afd9a8b448a7e3e30f417440c01487
refs/heads/main
2023-07-01T10:50:52.744951
2021-07-23T06:01:19
2021-07-23T06:01:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
437
cpp
#include<iostream> using namespace std; /** * Check if array is sorted or not */ bool isArraySorted(int arr[], int size){ if(size == 0 || size == 1){ return true; } if(arr[0] > arr[1]){ return false; } return isArraySorted(arr+1, size-1); } int main(){ int n; cin >> n; int arr[n]; for(int i=0; i<n; i++){ cin >> arr[i]; } cout << isArraySorted(arr, n) << endl; }
[ "tarun.verma151@gmail.com" ]
tarun.verma151@gmail.com
f01bbe1455936e609b63aaf2a1c04afdfd1c578c
8127cd76c1073b658846de288a34bb62aeb2dc85
/Matrix.cpp
b7538ef7b1efcd0c8da1ca9f09bbd6f1806ba8e6
[]
no_license
arabhishek1/Gauss-Elimination
b66eb0eaae54940c48dbf5319ed9bf0ce4e92e7d
f1490784ec5f84b1f62bda1fbc22a468c08996b9
refs/heads/master
2021-01-22T02:57:52.065568
2013-10-18T15:22:22
2013-10-18T15:22:22
13,680,860
1
0
null
null
null
null
UTF-8
C++
false
false
2,885
cpp
#include"Matrix.h" #include<cassert> Matrix::Matrix(int m , int n) { try { if(m<=0) throw (m); this->rows = m; this->columns = n; p = new Vector*[m]; if(p == 0) throw p; for(int i=0 ; i<m ; ++i) { p[i] = new Vector(n); } } catch(Vector **p) { cout<<"Memory insuffiecient in heap. Could not allocate memory for the Array of Vector* in the heap."<<endl; exit(EXIT_FAILURE); } catch(int m) { cout<<"Invalid number of rows entered."<<endl; cout<<"Could not create the matrix with rows = "<<m<<endl<<"Program Aborted."<<endl; exit(EXIT_FAILURE); } } Matrix::Matrix(const Matrix& A) { try { rows = A.rows; columns = A.columns; p = new Vector*[rows]; if(p==0) throw p; for(int i=0 ; i<rows ; ++i) { //create a new vector and copy the corresponding vector from A. p[i] = new Vector(columns); *p[i] = *A.p[i]; } } catch(Vector **p) { cout<<"Memory insuffiecient in heap. Could not allocate memory for the Array of Vector* in the heap."<<endl; exit(EXIT_FAILURE); } } Matrix::~Matrix() { for(int i=0 ; i<rows ; ++i) { delete p[i]; } delete []p; } Vector& Matrix::operator[](int i) { try { if(i<0 || i>=this->rows) throw (i); return *(this->p[i]); } catch(int i) { cout<<"Indexing out of bounds : "<<i<<" row : "<<this->rows<<endl; exit(EXIT_FAILURE); } } const Vector& Matrix::operator[](int i) const { try { if(i<0 || i>=this->rows) throw (i); return *(this->p[i]); } catch(int i) { cout<<"Indexing out of bounds : "<<i<<" row : "<<this->rows<<endl; exit(EXIT_FAILURE); } } ostream& operator<<(ostream& out ,const Matrix& A) { for(int i=0 ; i<A.rows ; ++i) { for(int j=0 ; j<A.columns ; ++j) { if(fabs(A[i][j]) < 0.000001) out << 0 <<'\t'; else out<<A[i][j]<<'\t'; } out<<endl; } return out; } istream& operator>>(istream& in , Matrix& A) { for(int i=0 ; i<A.rows ; ++i) { in>>A[i]; } return in; } Vector Matrix::operator*(const Vector& V) const { const Matrix& A = (*this); assert(A.columns == V.get_n()); Vector Ans(A.rows); for(int i=0 ; i<A.rows ; ++i) { int temp = 0; for( int k=0 ; k < A.columns ; ++k) { temp += A[i][k]*V[k]; } Ans[i] = temp; } return Ans; } void Matrix::backSubstitution(Matrix& U , Vector& b, Vector& solVector) { for(int i=U.rows-1; i>=0; --i) { double temp=0; for(int j=U.rows-1; j>=i; --j) { if(i!=j) temp+=U[i][j]*solVector[j]; } double subValue=b[i]-temp; solVector[i]=(subValue/U[i][i]); } } void Matrix::displayAugmentedMatrix( Matrix& A , Vector& b) { for( int i=0 ; i<A.rows ; ++i) { for( int j=0 ; j < A.rows ; ++j) { if( A[i][j] < 0.000001 && A[i][j] > -0.000001 ) cout << 0 << " "; else cout << A[i][j] << " "; } cout << ": " << b[i] << endl; } }
[ "mail2arabhishek@gmail.com" ]
mail2arabhishek@gmail.com
313d82dc8851139a0784c9dab2179c5db620a4b2
1a4c4dee0e93d12f20f56370c7bf3d8ead73638a
/mobula/inc/ctypes.h
29aa1f324397d08dba1d10fdacfd0fc61d18e4cd
[ "MIT" ]
permissive
mgno32/MobulaOP
d07106953085d5648a63abe01e996c0c4da61276
a58c06216ee6768cf4c46610b802c8b96bf3240d
refs/heads/master
2020-04-13T18:51:36.442892
2018-12-17T02:45:23
2018-12-17T02:45:23
163,386,805
0
0
MIT
2018-12-28T08:32:04
2018-12-28T08:32:04
null
UTF-8
C++
false
false
581
h
#ifndef MOBULA_INC_CTYPES_H_ #define MOBULA_INC_CTYPES_H_ namespace mobula { typedef wchar_t wchar; typedef char byte; typedef unsigned char ubyte; typedef unsigned short ushort; typedef unsigned int uint; typedef unsigned long ulong; typedef long long longlong; typedef unsigned long long ulonglong; typedef long double longdouble; typedef char* char_p; typedef wchar_t* wchar_p; typedef void* void_p; #if defined(__x86_64__) || defined(_WIN64) typedef uint64_t PointerValue; #else typedef uint32_t PointerValue; #endif } // namespace mobula #endif // MOBULA_INC_CTYPES_H_
[ "wkcn@live.cn" ]
wkcn@live.cn
f28aeec04ab26c74b6f4231c015268b177a1f24d
cde7a701e9c0aff92152e4c13764143b39e8adbb
/include/mull/Driver.h
b0d0ddf2ef401122ff6df4e37d68ad32d3eec477
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
srasku/mull
f8744857c09e1bf62598ecdb0ea135b9599ff4c6
4ef8b236a57b8c5797eb9a66e6d16b831177b957
refs/heads/master
2020-06-01T05:38:43.910236
2019-06-02T07:54:07
2019-06-02T07:54:07
190,659,379
0
0
Apache-2.0
2019-06-06T22:47:27
2019-06-06T22:47:27
null
UTF-8
C++
false
false
2,130
h
#pragma once #include "mull/ExecutionResult.h" #include "mull/ForkProcessSandbox.h" #include "mull/IDEDiagnostics.h" #include "mull/Instrumentation/Instrumentation.h" #include "mull/MutationResult.h" #include "mull/Mutators/Mutator.h" #include "mull/TestFrameworks/Test.h" #include "mull/Toolchain/Toolchain.h" #include <llvm/Object/ObjectFile.h> #include <map> namespace llvm { class Module; class Function; } // namespace llvm namespace mull { struct Configuration; class Program; class Filter; class Result; class TestFramework; class MutationsFinder; class Metrics; class JunkDetector; class Driver { const Configuration &config; Program &program; TestFramework &testFramework; Toolchain &toolchain; Filter &filter; MutationsFinder &mutationsFinder; ProcessSandbox *sandbox; IDEDiagnostics *diagnostics; std::vector<llvm::object::OwningBinary<llvm::object::ObjectFile>> instrumentedObjectFiles; std::vector<llvm::object::OwningBinary<llvm::object::ObjectFile>> ownedObjectFiles; Instrumentation instrumentation; Metrics &metrics; JunkDetector &junkDetector; public: Driver(const Configuration &config, Program &program, TestFramework &testFramework, Toolchain &t, Filter &f, MutationsFinder &mutationsFinder, Metrics &metrics, JunkDetector &junkDetector); ~Driver(); std::unique_ptr<Result> Run(); private: void compileInstrumentedBitcodeFiles(); void loadDynamicLibraries(); std::vector<Test> findTests(); std::vector<MutationPoint *> findMutationPoints(std::vector<Test> &tests); std::vector<MutationPoint *> filterOutJunkMutations(std::vector<MutationPoint *> mutationPoints); std::vector<std::unique_ptr<MutationResult>> runMutations(std::vector<MutationPoint *> &mutationPoints); std::vector<llvm::object::ObjectFile *> AllInstrumentedObjectFiles(); std::vector<std::unique_ptr<MutationResult>> dryRunMutations(const std::vector<MutationPoint *> &mutationPoints); std::vector<std::unique_ptr<MutationResult>> normalRunMutations(const std::vector<MutationPoint *> &mutationPoints); }; } // namespace mull
[ "1101.debian@gmail.com" ]
1101.debian@gmail.com
38e4d7d1be02feec4441369c771c13ad0c22828a
993ec32621bc621c7c6a2c2d10ae844e582e25bd
/WCFClient/soapBasicHttpBinding_USCOREIWCFTestProxy.cpp
433792d7873c3acd6f7f7e03ef8313d0b83f9099
[]
no_license
radtek/WCF-GSOAP
29c322fdab828105c092ae7f63752b4968e3b9c0
d46236f67d641e532384561d7e9aa1baf2b604b5
refs/heads/master
2020-06-21T22:28:36.031636
2017-11-23T13:09:13
2017-11-23T13:09:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,912
cpp
/* soapBasicHttpBinding_USCOREIWCFTestProxy.cpp Generated by gSOAP 2.8.34 for WCFTest.h gSOAP XML Web services tools Copyright (C) 2000-2016, Robert van Engelen, Genivia Inc. All Rights Reserved. The soapcpp2 tool and its generated software are released under the GPL. This program is released under the GPL with the additional exemption that compiling, linking, and/or using OpenSSL is allowed. -------------------------------------------------------------------------------- A commercial use license is available from Genivia Inc., contact@genivia.com -------------------------------------------------------------------------------- */ #include "soapBasicHttpBinding_USCOREIWCFTestProxy.h" BasicHttpBinding_USCOREIWCFTestProxy::BasicHttpBinding_USCOREIWCFTestProxy() : soap(SOAP_IO_DEFAULT) { BasicHttpBinding_USCOREIWCFTestProxy_init(SOAP_IO_DEFAULT, SOAP_IO_DEFAULT); } BasicHttpBinding_USCOREIWCFTestProxy::BasicHttpBinding_USCOREIWCFTestProxy(const BasicHttpBinding_USCOREIWCFTestProxy& rhs) { soap_copy_context(this, &rhs); this->soap_endpoint = rhs.soap_endpoint; } BasicHttpBinding_USCOREIWCFTestProxy::BasicHttpBinding_USCOREIWCFTestProxy(const struct soap &_soap) : soap(_soap) { } BasicHttpBinding_USCOREIWCFTestProxy::BasicHttpBinding_USCOREIWCFTestProxy(const char *endpoint) : soap(SOAP_IO_DEFAULT) { BasicHttpBinding_USCOREIWCFTestProxy_init(SOAP_IO_DEFAULT, SOAP_IO_DEFAULT); soap_endpoint = endpoint; } BasicHttpBinding_USCOREIWCFTestProxy::BasicHttpBinding_USCOREIWCFTestProxy(soap_mode iomode) : soap(iomode) { BasicHttpBinding_USCOREIWCFTestProxy_init(iomode, iomode); } BasicHttpBinding_USCOREIWCFTestProxy::BasicHttpBinding_USCOREIWCFTestProxy(const char *endpoint, soap_mode iomode) : soap(iomode) { BasicHttpBinding_USCOREIWCFTestProxy_init(iomode, iomode); soap_endpoint = endpoint; } BasicHttpBinding_USCOREIWCFTestProxy::BasicHttpBinding_USCOREIWCFTestProxy(soap_mode imode, soap_mode omode) : soap(imode, omode) { BasicHttpBinding_USCOREIWCFTestProxy_init(imode, omode); } BasicHttpBinding_USCOREIWCFTestProxy::~BasicHttpBinding_USCOREIWCFTestProxy() { this->destroy(); } void BasicHttpBinding_USCOREIWCFTestProxy::BasicHttpBinding_USCOREIWCFTestProxy_init(soap_mode imode, soap_mode omode) { soap_imode(this, imode); soap_omode(this, omode); soap_endpoint = NULL; static const struct Namespace namespaces[] = { {"SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/", "http://schemas.xmlsoap.org/soap/envelope/", NULL}, {"SOAP-ENC", "http://schemas.xmlsoap.org/soap/encoding/", "http://schemas.xmlsoap.org/soap/encoding/", NULL}, {"xsi", "http://www.w3.org/2001/XMLSchema-instance", "http://www.w3.org/*/XMLSchema-instance", NULL}, {"xsd", "http://www.w3.org/2001/XMLSchema", "http://www.w3.org/*/XMLSchema", NULL}, {"tempuri", "http://tempuri.org/", NULL, NULL}, {NULL, NULL, NULL, NULL} }; soap_set_namespaces(this, namespaces); } #ifndef WITH_PURE_VIRTUAL BasicHttpBinding_USCOREIWCFTestProxy *BasicHttpBinding_USCOREIWCFTestProxy::copy() { BasicHttpBinding_USCOREIWCFTestProxy *dup = SOAP_NEW_COPY(BasicHttpBinding_USCOREIWCFTestProxy(*(struct soap*)this)); return dup; } #endif BasicHttpBinding_USCOREIWCFTestProxy& BasicHttpBinding_USCOREIWCFTestProxy::operator=(const BasicHttpBinding_USCOREIWCFTestProxy& rhs) { soap_copy_context(this, &rhs); this->soap_endpoint = rhs.soap_endpoint; return *this; } void BasicHttpBinding_USCOREIWCFTestProxy::destroy() { soap_destroy(this); soap_end(this); } void BasicHttpBinding_USCOREIWCFTestProxy::reset() { this->destroy(); soap_done(this); soap_initialize(this); BasicHttpBinding_USCOREIWCFTestProxy_init(SOAP_IO_DEFAULT, SOAP_IO_DEFAULT); } void BasicHttpBinding_USCOREIWCFTestProxy::soap_noheader() { this->header = NULL; } ::SOAP_ENV__Header *BasicHttpBinding_USCOREIWCFTestProxy::soap_header() { return this->header; } ::SOAP_ENV__Fault *BasicHttpBinding_USCOREIWCFTestProxy::soap_fault() { return this->fault; } const char *BasicHttpBinding_USCOREIWCFTestProxy::soap_fault_string() { return *soap_faultstring(this); } const char *BasicHttpBinding_USCOREIWCFTestProxy::soap_fault_detail() { return *soap_faultdetail(this); } int BasicHttpBinding_USCOREIWCFTestProxy::soap_close_socket() { return soap_closesock(this); } int BasicHttpBinding_USCOREIWCFTestProxy::soap_force_close_socket() { return soap_force_closesock(this); } void BasicHttpBinding_USCOREIWCFTestProxy::soap_print_fault(FILE *fd) { ::soap_print_fault(this, fd); } #ifndef WITH_LEAN #ifndef WITH_COMPAT void BasicHttpBinding_USCOREIWCFTestProxy::soap_stream_fault(std::ostream& os) { ::soap_stream_fault(this, os); } #endif char *BasicHttpBinding_USCOREIWCFTestProxy::soap_sprint_fault(char *buf, size_t len) { return ::soap_sprint_fault(this, buf, len); } #endif int BasicHttpBinding_USCOREIWCFTestProxy::DoWork(const char *endpoint, const char *soap_action, _tempuri__DoWork *tempuri__DoWork, _tempuri__DoWorkResponse &tempuri__DoWorkResponse) { struct soap *soap = this; struct __tempuri__DoWork soap_tmp___tempuri__DoWork; if (endpoint) soap_endpoint = endpoint; if (soap_endpoint == NULL) soap_endpoint = "http://127.0.0.1:8001/WCFTest"; if (soap_action == NULL) soap_action = "http://tempuri.org/IWCFTest/DoWork"; soap_tmp___tempuri__DoWork.tempuri__DoWork = tempuri__DoWork; soap_begin(soap); soap_set_version(soap, 1); /* SOAP1.1 */ soap->encodingStyle = NULL; soap_serializeheader(soap); soap_serialize___tempuri__DoWork(soap, &soap_tmp___tempuri__DoWork); if (soap_begin_count(soap)) return soap->error; if (soap->mode & SOAP_IO_LENGTH) { if (soap_envelope_begin_out(soap) || soap_putheader(soap) || soap_body_begin_out(soap) || soap_put___tempuri__DoWork(soap, &soap_tmp___tempuri__DoWork, "-tempuri:DoWork", "") || soap_body_end_out(soap) || soap_envelope_end_out(soap)) return soap->error; } if (soap_end_count(soap)) return soap->error; if (soap_connect(soap, soap_endpoint, soap_action) || soap_envelope_begin_out(soap) || soap_putheader(soap) || soap_body_begin_out(soap) || soap_put___tempuri__DoWork(soap, &soap_tmp___tempuri__DoWork, "-tempuri:DoWork", "") || soap_body_end_out(soap) || soap_envelope_end_out(soap) || soap_end_send(soap)) return soap_closesock(soap); if (!static_cast<_tempuri__DoWorkResponse*>(&tempuri__DoWorkResponse)) // NULL ref? return soap_closesock(soap); tempuri__DoWorkResponse.soap_default(soap); if (soap_begin_recv(soap) || soap_envelope_begin_in(soap) || soap_recv_header(soap) || soap_body_begin_in(soap)) return soap_closesock(soap); tempuri__DoWorkResponse.soap_get(soap, "tempuri:DoWorkResponse", NULL); if (soap->error) return soap_recv_fault(soap, 0); if (soap_body_end_in(soap) || soap_envelope_end_in(soap) || soap_end_recv(soap)) return soap_closesock(soap); return soap_closesock(soap); } int BasicHttpBinding_USCOREIWCFTestProxy::Add(const char *endpoint, const char *soap_action, _tempuri__Add *tempuri__Add, _tempuri__AddResponse &tempuri__AddResponse) { struct soap *soap = this; struct __tempuri__Add soap_tmp___tempuri__Add; if (endpoint) soap_endpoint = endpoint; if (soap_endpoint == NULL) soap_endpoint = "http://127.0.0.1:8001/WCFTest"; if (soap_action == NULL) soap_action = "http://tempuri.org/IWCFTest/Add"; soap_tmp___tempuri__Add.tempuri__Add = tempuri__Add; soap_begin(soap); soap_set_version(soap, 1); /* SOAP1.1 */ soap->encodingStyle = NULL; soap_serializeheader(soap); soap_serialize___tempuri__Add(soap, &soap_tmp___tempuri__Add); if (soap_begin_count(soap)) return soap->error; if (soap->mode & SOAP_IO_LENGTH) { if (soap_envelope_begin_out(soap) || soap_putheader(soap) || soap_body_begin_out(soap) || soap_put___tempuri__Add(soap, &soap_tmp___tempuri__Add, "-tempuri:Add", "") || soap_body_end_out(soap) || soap_envelope_end_out(soap)) return soap->error; } if (soap_end_count(soap)) return soap->error; if (soap_connect(soap, soap_endpoint, soap_action) || soap_envelope_begin_out(soap) || soap_putheader(soap) || soap_body_begin_out(soap) || soap_put___tempuri__Add(soap, &soap_tmp___tempuri__Add, "-tempuri:Add", "") || soap_body_end_out(soap) || soap_envelope_end_out(soap) || soap_end_send(soap)) return soap_closesock(soap); if (!static_cast<_tempuri__AddResponse*>(&tempuri__AddResponse)) // NULL ref? return soap_closesock(soap); tempuri__AddResponse.soap_default(soap); if (soap_begin_recv(soap) || soap_envelope_begin_in(soap) || soap_recv_header(soap) || soap_body_begin_in(soap)) return soap_closesock(soap); tempuri__AddResponse.soap_get(soap, "tempuri:AddResponse", NULL); if (soap->error) return soap_recv_fault(soap, 0); if (soap_body_end_in(soap) || soap_envelope_end_in(soap) || soap_end_recv(soap)) return soap_closesock(soap); return soap_closesock(soap); } int BasicHttpBinding_USCOREIWCFTestProxy::Sub(const char *endpoint, const char *soap_action, _tempuri__Sub *tempuri__Sub, _tempuri__SubResponse &tempuri__SubResponse) { struct soap *soap = this; struct __tempuri__Sub soap_tmp___tempuri__Sub; if (endpoint) soap_endpoint = endpoint; if (soap_endpoint == NULL) soap_endpoint = "http://127.0.0.1:8001/WCFTest"; if (soap_action == NULL) soap_action = "http://tempuri.org/IWCFTest/Sub"; soap_tmp___tempuri__Sub.tempuri__Sub = tempuri__Sub; soap_begin(soap); soap_set_version(soap, 1); /* SOAP1.1 */ soap->encodingStyle = NULL; soap_serializeheader(soap); soap_serialize___tempuri__Sub(soap, &soap_tmp___tempuri__Sub); if (soap_begin_count(soap)) return soap->error; if (soap->mode & SOAP_IO_LENGTH) { if (soap_envelope_begin_out(soap) || soap_putheader(soap) || soap_body_begin_out(soap) || soap_put___tempuri__Sub(soap, &soap_tmp___tempuri__Sub, "-tempuri:Sub", "") || soap_body_end_out(soap) || soap_envelope_end_out(soap)) return soap->error; } if (soap_end_count(soap)) return soap->error; if (soap_connect(soap, soap_endpoint, soap_action) || soap_envelope_begin_out(soap) || soap_putheader(soap) || soap_body_begin_out(soap) || soap_put___tempuri__Sub(soap, &soap_tmp___tempuri__Sub, "-tempuri:Sub", "") || soap_body_end_out(soap) || soap_envelope_end_out(soap) || soap_end_send(soap)) return soap_closesock(soap); if (!static_cast<_tempuri__SubResponse*>(&tempuri__SubResponse)) // NULL ref? return soap_closesock(soap); tempuri__SubResponse.soap_default(soap); if (soap_begin_recv(soap) || soap_envelope_begin_in(soap) || soap_recv_header(soap) || soap_body_begin_in(soap)) return soap_closesock(soap); tempuri__SubResponse.soap_get(soap, "tempuri:SubResponse", NULL); if (soap->error) return soap_recv_fault(soap, 0); if (soap_body_end_in(soap) || soap_envelope_end_in(soap) || soap_end_recv(soap)) return soap_closesock(soap); return soap_closesock(soap); } /* End of client proxy code */
[ "xz9432@hotmail.com" ]
xz9432@hotmail.com
62f19d1a4d01c198c1e7a3943bc6b43fb61da90a
ad5e3572dd6a2c0592ea679145fb5a4939498946
/P77_2.cpp
d509882d7eec86566abecbd2ea9d0ce4d7c205ac
[]
no_license
yangyuyi/DS-code
842e1d42870482a286d7a17d23f99ed54c833326
ab02948fa6a239a0fa76155b2176219e4f23c5b9
refs/heads/master
2022-11-27T10:05:55.405190
2020-08-12T16:17:03
2020-08-12T16:17:03
287,059,920
0
0
null
null
null
null
UTF-8
C++
false
false
1,517
cpp
#include <iostream> using namespace std; template<class T> class arrQueue { private: int front; int maxSize; int count; T *Q; public: arrQueue(const int m); ~arrQueue(); bool isEmpty(); bool isFull(); bool in(const T item); bool out(T &item); }; template<class T> arrQueue<T>::arrQueue(const int m) { maxSize = m; front = 0; count = 0; Q = new T[maxSize]; } template<class T> arrQueue<T>::~arrQueue() { delete[]Q; } template<class T> bool arrQueue<T>::isEmpty() { return count == 0; } template<class T> bool arrQueue<T>::in(const T item) { if (isFull()) { cout << "illegal operation:The queue is full." << endl; return false; } Q[(front + count) % maxSize] = item; count++; return true; } template<class T> bool arrQueue<T>::out(T &item) { if (isEmpty()) { cout << "illegal operation:The queue is empty." << endl; return false; } item = Q[front]; front = (front + 1) % maxSize; count--; return true; } template<class T> bool arrQueue<T>::isFull() { return count == maxSize; } int main() { int m = 5; int x; arrQueue<int> *q; q = new arrQueue<int>(m); q->in(0); q->out(x); cout << x << endl; q->out(x); cout << x << endl; q->in(1); q->in(2); q->in(3); q->in(4); q->in(5); q->in(6); while (!q->isEmpty()) { int num; q->out(num); cout << num << endl; } return 0; }
[ "TaroYoung2000@gmail.com" ]
TaroYoung2000@gmail.com
3127cb2675ceb39b7cfe28ce6cc1d64a031ac70e
e1f6a4dee9847c99b6357d0eea44ce5d1e5d0aa4
/string/SA.cpp
51de2cd34021c50f36d3c1250b2ad3e033598b53
[]
no_license
mh755628/contest
362f55c439e8feddeb3e2ac4bf0bcc9d9f0b1694
4ffd392ddb41a544555b3e25755be10d5072080c
refs/heads/master
2023-09-04T05:29:08.417853
2023-08-28T12:44:46
2023-08-28T12:44:46
180,384,088
0
0
null
null
null
null
UTF-8
C++
false
false
796
cpp
struct SA{ struct state{ int len, link, nxt[26]; state() : len(0), link(-1) { fill(begin(nxt), end(nxt), 0); } }; vector <state> d; int last = 0; SA() { d.push_back(state()); } void add(char ch) { int cur = d.size(); d.push_back(state()); d[cur].len = d[last].len + 1; int p = last; while(p != -1 && !d[p].nxt[ch - 'a']) { d[p].nxt[ch - 'a'] = cur; p = d[p].link; } if(p == -1) { d[cur].link = 0; } else { int q = d[p].nxt[ch - 'a']; if(d[q].len == d[p].len + 1) { d[cur].link = q; } else { int clone = d.size(); d.push_back(d[q]); d[clone].len = d[p].len + 1; while(p != -1 && d[p].nxt[ch - 'a'] == q) { d[p].nxt[ch - 'a'] = clone; p = d[p].link; } d[cur].link = d[q].link = clone; } } last = cur; } };
[ "noreply@github.com" ]
noreply@github.com
dd64010ac64b6b7fce845bbd1e7c08aaee264d0b
74ef4021bbcee59068aa9720b52fd8fe4bf96e16
/Tools/WoG Sources/crexpo.h
3a1c1ebb2fa0fd02922fc32489feb90a64cb7768
[]
no_license
ethernidee/era-package
21f5005a39620419c2f636f5627543cd2f2f2821
48a1ab6bbe23710ed50b399ab852b93d0b39a39f
refs/heads/master
2023-07-11T06:04:09.822147
2023-07-04T19:40:00
2023-07-04T19:40:00
189,073,403
1
1
null
null
null
null
WINDOWS-1251
C++
false
false
19,715
h
#include <string.h> //#define EXPOMUL 100 #define EXPOMUL1 1 #define EXPOMAX2 20000 //#define HEREXPMUL 50 #define HEREXPMUL 1 #define BFNUM 42 #define CURMON 1000 #define EXPARTFIRST 156 //#define STREXPARTFIRST "7" #define EXPARTLAST 156 #define MAXICONNUM 7 typedef void * CRLOC; class CrExpo{ CrExpo(CrExpo &); public: int Expo; // тек. опыт на 1 существо int Num; // число существ struct { unsigned Act : 1; // есть/нет #define CE_HERO 1 #define CE_MAP 2 #define CE_TOWN 3 #define CE_MINE 4 #define CE_HORN 5 unsigned Type : 4; // тип - где хранится unsigned MType : 8; // тип существ unsigned mHasArt : 1; // has art unsigned mArt : 2; // up to 4 arts unsigned mCopyArt: 2; // up to 4 copy unsigned mSubArt : 4; // up to 16 sub art unsigned _un : 10; // reserve // unsigned _un : 19; } Fl; union _Dt{ CRLOC UniData; // универсальный для присвоения только #define MAKEMP(x,y,l) (void *)((x)+(y)<<16+(l)*0x04000000) Dword MixPos; // позиция на карте #define MAKEHS(i,s) (void *)((i)+(s)*0x10000) struct _Hero{ short Ind; // номер героя short Slot; // слот в армии героя } Hero; #define MAKESS(x,y,l) (void *)((x)+(y)*0x100+(l)*0x10000) struct _Map{ unsigned X :8; unsigned Y :8; unsigned L :1; unsigned _un :15; // резерв } Map; #define MAKETS(x,y,l,s) (void *)((x)+(y)*0x100+(l)*0x10000+(s)*0x20000) struct _Town{ unsigned X :8; unsigned Y :8; unsigned L :1; signed Slot :15; // слот в армии героя } Town; #define MAKEMS(x,y,l,s) (void *)((x)+(y)*0x100+(l)*0x10000+(s)*0x20000) struct _Mine{ unsigned X :8; unsigned Y :8; unsigned L :1; signed Slot :15; // слот в армии шахты } Mine; #define MAKEZS(x,y,l,s) (void *)((x)+(y)*0x100+(l)*0x10000+(s)*0x20000) struct _Horn{ unsigned X :8; unsigned Y :8; unsigned L :1; signed Slot :15; // слот в армии шахты } Horn; #define MAKESS(x,y,l) (void *)((x)+(y)*0x100+(l)*0x10000) } Dt; CrExpo(); ~CrExpo(); CrExpo &operator =(CrExpo &); void SetN(int Type,CRLOC Data,int mtype,int num,int expo=0,int arts=0); void Clear(); void Check4Max(); int RealType(int type=-2); int RealNum(int num=-2); void RecalcExp2RealNum(int num,int type); int Validate(void); void AddExpRel(int e){ if(Fl.Act==0) return; Expo+=e; } // artifact int HasArt(void){ return Fl.mHasArt; } int GetArt(void){ return Fl.mArt+EXPARTFIRST; } int GetSubArt(void){ return Fl.mSubArt; } void SetSubArt(int s){ Fl.mSubArt=s; } int SetArt(int a,int s){ Fl.mArt=a-EXPARTFIRST; Fl.mSubArt=s; Fl.mHasArt=1; Fl.mCopyArt=0; return 1; } void SetArtAll(int h,int a,int s,int c){ Fl.mHasArt=h; Fl.mArt=a-EXPARTFIRST; Fl.mSubArt=s; Fl.mCopyArt=c; } void DelArt(void){ Fl.mArt=0; Fl.mSubArt=0; Fl.mHasArt=0; Fl.mCopyArt=0; return; } int ArtCopy(void){ return Fl.mCopyArt; } void ArtCopy(int cpy){ if(cpy>3) cpy=3; if(cpy<0) cpy=0; Fl.mCopyArt=cpy; } int GetArtNums(void){ if(Fl.mHasArt==0) return 0; return(ArtCopy()+1); } int TakeArt(void){ if(Fl.mHasArt==0) return 0; if(ArtCopy()>0){ ArtCopy(ArtCopy()-1); return 1; } Fl.mArt=0; Fl.mSubArt=0; Fl.mHasArt=0; Fl.mCopyArt=0; return 1; } void CopyArt(CrExpo &s){ Fl.mArt=s.Fl.mArt; Fl.mSubArt=s.Fl.mSubArt; Fl.mHasArt=s.Fl.mHasArt; Fl.mCopyArt=s.Fl.mCopyArt; } int AddArt(CrExpo &s){ if(s.HasArt()==0) return 0; // нечего добавлять if(HasArt()){ // уже есть арт ArtCopy(ArtCopy()+s.ArtCopy()+1); // количество копий плюс сам один артифакт }else{ // нет арта CopyArt(s); } return 1; } int AddArt(int nums){ if(nums<1) return 0; if(HasArt()){ // уже есть арт ArtCopy(ArtCopy()+nums); // количество копий - количество добавляемы плюс копии старые }else{ // нет арта SetArt(EXPARTFIRST,0); ArtCopy(nums-1); } return 1; } }; #define MAXCRINFONUM 10000L class CrExpoSet{ static CrExpo Body[MAXCRINFONUM]; static int LastUser; // последний игрок public: static int PlayerMult; static int AIMult[5]; static int AIBase[5]; static int AITMult[5]; private: static Dword HerExpo[256]; // опыт всех героев // static Byte HerArts[256]; // артифакт стэков у АИ героев CrExpoSet(CrExpoSet &); CrExpoSet(); ~CrExpoSet(); CrExpoSet &operator=(CrExpoSet &); // найти такой static int FindIt(int Type,CRLOC Data); public: static CrExpo BFBody[BFNUM]/*,Cur*/; static Copy(CrExpo *Dst,CrExpo *Src){ memcpy(Dst,Src,sizeof(CrExpo)); } // static CrExpo *GetCur(void){ return &Cur; } static CrExpo *GetBF(int ind){ return &BFBody[ind]; } static CrExpo *Get(int ind){ return &Body[ind]; } static void StartAllBF(_MonArr_ *AMAr,_MonArr_ *DMAr); static void StopAllBF(void); static void AdjustStackTypes(int ATded,_Hero_ *Hp); // подправить типы стэков если АИ их переставлял // найти такой публично static CrExpo *Find(int Type,CRLOC Data); static void Clear(); static int Load(int Ver); static int Save(); // такой должен быть и ему меняем static int SetN(int Type,CRLOC Data,int mtype,int num,int expo); static int Set(CrExpo &cr); // удалить static void Del(int Type,CRLOC Data); // потщем пустое место static CrExpo *FindEmpty(void); // получить опыт static int GetExp(int Type,CRLOC Data); // get experience or expo level static int GetExpM(int Type,CRLOC Data,int M=0); // подправить статистику стэку (если есть что) на поле боя // static int ApplyExp(int Type,CRLOC Data,Byte *Mon); // добавить всем живым этого героя опыт static void AddExpo(_Hero_ *Hp,int NewHExp,int OldHExp); // перенести стэк из одного слота в другой static int HMove(int Type,int TypeN,CRLOC Data,CRLOC DataN,int type,int typeN,int num,int numN); // добавить первый стэк ко второму static int HComb(int Type,int TypeN,CRLOC Data,CRLOC DataN,int type,int typeN,int num,int numN); // добавить первый стэк ко второму реально (не только опыт) static int HCombReal(int Type,int TypeN,CRLOC Data,CRLOC DataN,int type,int typeN,int num,int numN); // ищем - кто хозяин армии static int FindType(_MonArr_ *MArr,int Stack,int *Type,CRLOC *Crloc); // ищем - кто хозяин по позиции объекта static int FindType(int x,int y,int l,int Stack,int *Type,CRLOC *Crloc,int *MType=0,int *MNum=0); // ищем - кто хозяин армии по индексу static int FindType(int Ind,int *Type,CRLOC *Crloc,int *Slot); static int Modify(int Tp,int Type,CRLOC Crloc,int E,int M=0,int T=-1,int ON=0,int N=0,_MonArr_ *Ma=0); static void DaylyAIExperience(int User); // AI новый пользователь - применить опыт // static void BuildBFExpo(int *ExpoArr); // составить список опыта static int DropArt2Stack(_MouseStr_ *ms,_Hero_ *hp,int DropArt); }; int LoadExpTXT(void); char *Exp2String(int exp,int Limit,int HasArt); char *Exp2String2(int exp[2],int Limit,int HasArt[2]); /////////////////////////////////////// #define MAXCREXPAB 256 class CrExpMod{ static struct CrExpModStr{ float ExpMul; float UpgrMul; int Limit; int Lvl11Exp; int Cap; // in percettages } Body[MAXCREXPAB],Dummy; static int Ranks[11]; // fullrange scale , exp per level friend void CrExpoSet::StartAllBF(_MonArr_ *AMAr,_MonArr_ *DMAr); friend void CrExpoSet::AdjustStackTypes(int atDEF,_Hero_ *Hp); friend void CrExpoSet::StopAllBF(void); CrExpMod(CrExpMod &); CrExpMod(); ~CrExpMod(); CrExpMod &operator=(CrExpMod &); public: static struct CrExpModStr BFBody[BFNUM],Cur; static Copy(CrExpModStr *Dst,CrExpModStr *Src){ memcpy(Dst,Src,sizeof(CrExpModStr)); } static CrExpModStr *GetCur(void){ return &Cur; } static CrExpModStr *GetBF(int cr){ if((cr<0) || (cr>=BFNUM)) return &Dummy; return &BFBody[cr]; } static CrExpModStr *Get(int cr){ if(cr==CURMON) return &Cur; if((cr<-BFNUM)||(cr>=MAXCREXPAB)) return &Dummy; if(cr<0) return &BFBody[-cr-1]; else return &Body[cr]; } static int Load(int Ver); static int Save(); static int Clear(); // из TXT файла static float ExpMul(int cr){ return Get(cr)->ExpMul; } static void SExpMul(int cr,float Val){ Get(cr)->ExpMul=Val; } static float UpgrMul(int cr){ return Get(cr)->UpgrMul; } static void SUpgrMul(int cr,float Val){ Get(cr)->UpgrMul=Val; } static int Limit(int cr){ return Get(cr)->Limit; } static void SLimit(int cr,int Val){ Get(cr)->Limit=Val; } static int CrLimit(CrExpo *cr){ if(cr==0) return EXPOMAX2; int tp=cr->Fl.MType; return Get(tp)->Limit; } static int Lvl11(int cr){ return Get(cr)->Lvl11Exp; } static void SLvl11(int cr,int Val){ Get(cr)->Lvl11Exp=Val; } static int MaxExpo(int cr){ return Get(cr)->Limit+Get(cr)->Lvl11Exp; } static int CrMaxExpo(CrExpo *cr){ if(cr==0) return 1; int tp=cr->Fl.MType; return Get(tp)->Limit+Get(tp)->Lvl11Exp; } static int Cap(int cr){ return Get(cr)->Cap; } static void SCap(int cr,int Val){ Get(cr)->Cap=Val; } static int CrCap(CrExpo *cr){ if(cr==0) return 100; int tp=cr->Fl.MType; return Get(tp)->Cap; } static int CapIt(CrExpo *cr,int Exp){ int v=CrLimit(cr)*CrCap(cr)/100; if (v<1) v=1; if(Exp>v) Exp=v; return Exp; } static int Exp4Level(int cr,int lvl,int exp0=0){ if((cr<0)||(cr>=MAXCREXPAB)) return 0; if(lvl<0) return 0; if(lvl>10) return MaxExpo(cr); int lvl0=GetRank(cr,exp0); int dexp=exp0-GetRankExp(cr,lvl0); lvl0+=lvl; if(lvl0<0) lvl0=0; if(lvl0>11) lvl0=11; int Exp=GetRankExp(cr,lvl0)+dexp; return Exp; } static int GetRank(int cr,int exp){ float scale=(float)Get(cr)->Limit/Ranks[0]; if(scale<0.000001) return 0; float expnorm=(float)((exp+0.00001)/scale); for(int i=1;i<11;i++){ expnorm-=Ranks[i]; if(expnorm<0) return i-1; } return 10; } static int GetRank(CrExpo *cr){ float scale=(float)Get(cr->Fl.MType)->Limit/Ranks[0]; if(scale<0.000001) return 0; float expnorm=(float)((cr->Expo+0.00001)/scale); for(int i=1;i<11;i++){ expnorm-=Ranks[i]; if(expnorm<0) return i-1; } return 10; } static int GetLimRank(int exp,int lim){ float scale=(float)lim/Ranks[0]; if(scale<0.000001) return 0; float expnorm=(float)((exp+0.00001)/scale); for(int i=1;i<11;i++){ expnorm-=Ranks[i]; if(expnorm<0) return i-1; } return 10; } static int GetRankExp(int cr,int rank,int rank0=0){ int exp=0; float scale=(float)Get(cr)->Limit/Ranks[0]; if(scale<0.000001) return 0; if(rank<0) rank=0; if(rank>11) rank=11; if(rank0<0) rank0=0; if(rank0>11) rank0=11; if(rank<=rank0) return 0; for(int i=rank0;i<rank;i++){ if(i!=10){ exp+=Ranks[i+1]; }else{ exp+=Get(cr)->Lvl11Exp; } } return (int)((exp+0.01)*scale); } }; //////////////////////////////////////// class CrExpBon{ static struct CrExpBonStr{ struct { unsigned Act : 1; // есть/нет unsigned _un : 31; } Fl; char Type; // тип спецспособности char Mod; // модификатор типа // char *Descr; // указатель на описание Byte Lvls[11]; // бонус на уровнях }Body[MAXCREXPAB][20],Dummy[20]; static struct CrExpBonBFStartStat{ char fA,fD,fH,fm,fM,fS,fO,fP,fR; int aA,aD,aH,am,aM,aS,aO,aP,aR; } BFStat[BFNUM]; CrExpBon(CrExpBon &); CrExpBon(); ~CrExpBon(); CrExpBon &operator=(CrExpBon &); friend void CrExpoSet::StartAllBF(_MonArr_ *AMAr,_MonArr_ *DMAr); friend void CrExpoSet::AdjustStackTypes(int atDEF,_Hero_ *Hp); friend void CrExpoSet::StopAllBF(void); static int FindBon(CrExpBonStr *str,char Type,int Mod, int silent=0); static void CrExpBon::IntCastMassSpell(Byte *Mon,Byte *DMon,char Ch); public: static int IsBattle; static struct CrExpBonStr BFBody[BFNUM][20],Cur[20]; static char BFBodyAct[BFNUM]; static void ClearCrExpBonBFStartStat(int Index){ if(Index<0 || Index>=BFNUM) return; SetMem(&BFStat[Index],sizeof(CrExpBonBFStartStat),0); } static int B2AIndex(int AIndex){ for(int i=0;i<BFNUM;i++) if(BFBodyAct[i]==AIndex) return i; return -1; } static void SetB2AIndex(int BIndex,int AIndex){ if(BIndex<0 || BIndex>=BFNUM) return; if(AIndex!=-1) BFBodyAct[BIndex]=(char)AIndex; // не бал в армии - установим if(BFBodyAct[BIndex]>0) return; // был в армии - пропустим BFBodyAct[BIndex]=(char)AIndex; } static void Copy(CrExpBonStr *Dst,CrExpBonStr *Src){ memcpy(Dst,Src,sizeof(CrExpBonStr)*20); } static CrExpBonStr *Get(int cr,int mtype=0){ if(cr==CURMON) return &Cur[0]; if((cr<-BFNUM)||(cr>=MAXCREXPAB)) return &Dummy[0]; if(cr<0){ if(BFBodyAct[-cr-1]==0){ // not installed return &BFBody[mtype][0]; }else{ return &BFBody[-cr-1][0]; } } else return &Body[cr][0]; } static void MakeCur(int Pos,int MType){ if(Pos==-1){ // not a BF memcpy(&Cur[0],&Body[MType][0],sizeof(CrExpBonStr)*20); CrExpMod::Copy(CrExpMod::GetCur(),CrExpMod::Get(MType)); // CrExpoSet::Copy(CrExpoSet::GetCur(),CrExpoSet::Get(MType)); }else{ // BF // CrExpoSet::Copy(CrExpoSet::GetCur(),CrExpoSet::GetBF(Pos)); if(BFBodyAct[Pos]==0){ // not installed memcpy(&Cur[0],&Body[MType][0],sizeof(CrExpBonStr)*20); CrExpMod::Copy(CrExpMod::GetCur(),CrExpMod::Get(MType)); }else{ memcpy(&Cur[0],&BFBody[Pos][0],sizeof(CrExpBonStr)*20); CrExpMod::Copy(CrExpMod::GetCur(),CrExpMod::GetBF(Pos)); } } } static int ApplyBFBonus(int TypeS,int TypeD, int Mode); static int Load(int Ver); static int Save(); static int Clear(); // из TXT файла static int SetBonLine(int MType,int Ind,int Flags, int Type, int Mod, int *lvls); static int GetBonLine(int MType,int Ind,int *Flags, int *Type, int *Mod, int *lvls); static int FindThisBonLineInd(int MType,char Bon,char Mod); static int GetStackExpo(Byte *Mon,int *VExp); static int PrepareBFExpStructure(Byte *BatMan); // static int GetHeroStackExpo(_Hero_ *Hp,int Stack); static int Apply(Byte *Mon); // настройка бонусов на поле боя 1 раз в самом начале static int Apply2(Byte *Mon); // настройка бонусов на поле боя каждый новый раунд static int StackBlock(Byte *Mon,int DefPerc); // применить блок? static int StackBlockPartial(Byte *Mon,int Dam); // частичный блок static int Fear(Byte *Mon); // страх? static int Fearless(Byte *Mon); // бесстрашный static int DwarfResist(Byte *Mon,int Res,int Spell); // шанс игнорир магию (dwarf type) static int DwarfResistFriendly(Byte *Mon,int Res,int Spell); // шанс игнорир друж магию (dwarf type) static int NoDistPenalty(Byte *Mon); // нет пенальти от дистанции static int NoObstPenalty(Byte *Mon); // нет пенальти от припятствий static int StackSubSpCost(_Hero_ *Hp,int Stack,int val); // снизить цену заклинания static int DefenceBonus(Byte *Mon,int Def); // бонус к защите при выборе защиты //440422 - Dead Knight Curse??? //4435A3 - Dead Knight Deathblow static int DeathBlow(Byte *Mon,int Chance); // бонус к защите при выборе защиты static int PersonalHate(Byte *MonA,int DType,int mult); // первональная ненависть static int CastSpell(Byte *Mon,Byte *DMon,_Hero_ *hpa,_Hero_ *hpd); // может скастовать спел при атаке static void CastMassSpell(Byte *Mon,Byte *DMon); // может скастовать массовый спел при атаке static void CastMassSpell2(Byte *Mon,Byte *DMon); // может скастовать массовый спел при атаке ОСЛЕ УДАРА static void ApplySpell(Byte *mon,Byte *BatMan); // наложить заклинание в начале раунда static int IsHarpy(Byte *Mon); static int ReduceDefence(Byte *AMon,Byte *DMon,int Def); static int Champion(Byte *Mon); // бонус чемпиона static int GolemResist(Byte *Mon,int Dam,int OrDam,int Spell); // сопротивление Голема static int Regenerate(Byte *Mon,int HPloss); // регенерация static int MinotourMoral(Byte *Mon); // позитивная мораль в битве static int UnicornAura(Byte *Mon); // магич. аура static int ShootAnyTime(Byte *Mon); // стреляет даже если противник рядом static int DeathStare(Byte *Mon); // DeathStare static int Rebirth(Byte *Mon); // возраждение стэке (FireBird) число заклов - число кастов static int SGBonus(Byte *Mon,int *Type,int *Num); // бонус существ для SG // static float DispellResistAndOther(Byte *Mon,int Spell,int ASide,float Res); // иммунитет к Dispell и др. static int DispellResist(int Spell,Byte *Mon,int ASide); // иммунитет к Dispell // static void ApplyMassSpell(Byte *mon); // наложить заклинание в начале раунда на эксперте static void PrepareInfo(int Mon,int Num,int Expo,CrExpo *Cr,int Changing); static void ShowInfo(int Mon,int Num,int Expo,CrExpo *Cr); static void ShowInfo(Byte *Mon); static int ExperienceSpellCastingPower(int Spell); }; int ERM_AICrExp(char Cmd,int Num,_ToDo_*sp,Mes *Mp); //extern CrExpo ToSendCrExpo[2][7]; //void SwapAIStacks(void);
[ "noemail@noemail.com" ]
noemail@noemail.com
4485d4274a14040a8c2ba1cef73085f87436d6e1
d5eb49a8895a8edf7e7139e49ca86e643a5ba6f7
/robotcode/projects/FRC11_logomotion/FRC_2CANPlugIn/UDP/RxUDPSocket.cpp
1036ce0578f36a2f0b704472f82838ae10ebbb07
[]
no_license
SkechyCoder/team846.github.io
10a0be95217a4492d7a01b4c17d4db530be22a6b
62139422bb414a9b7c9962e77782aa702802657a
refs/heads/master
2023-08-02T07:52:38.296525
2020-09-28T00:29:04
2020-09-28T00:29:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,470
cpp
/** * @file UDP\RxUDPSocket.cpp * * @brief Declares the Receive UDP Socket class. */ #include "RxUDPSocket.h" #include <string> // strcpy def'n /** * @fn RxUDPSocket: * * @brief Constructor. * * @param [in,out] String IP to send UDP datagrams to. * @param ulPort port number. * @param ulOptions bitwise options for socket. Set bit 0 to send * broadcast frames. Set bit 1 to make Receive() * non blocing. */ RxUDPSocket::RxUDPSocket( const char * sIP, unsigned long ulPort, unsigned long ulOptions) { m_ulOptions = ulOptions; m_rxsocketFile = -1 ; strcpy(m_remoteIPString,sIP); m_port = ulPort; } /** * @fn RxUDPSocket::~RxUDPSocket() * * @brief Destructor. */ RxUDPSocket::~RxUDPSocket() { if(m_rxsocketFile != -1) close(m_rxsocketFile); m_rxsocketFile = -1; } /** * @fn int RxUDPSocket::CreateRxSocket() * * @brief Creates and binds the receive socket. * * @return zero iff socket created successfully. */ int RxUDPSocket::CreateRxSocket() { struct sockaddr_in sin; if ((m_rxsocketFile = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { m_rxsocketFile = -1; return (errno); } sin.sin_family = AF_INET; sin.sin_port = htons(m_port); sin.sin_addr.s_addr = INADDR_ANY; if (bind(m_rxsocketFile, (struct sockaddr*)&sin, sizeof(sin)) < 0) { close(m_rxsocketFile); m_rxsocketFile = -1; return (errno); } return (0); } /** * @fn int RxUDPSocket::Read(char * data, int len) * * @brief Receive one UDP datagram. * * @param [in,out] data Data to fill with receive datagram. * @param len Maximun fill size of data pointer. * * @return number of bytes received. */ int RxUDPSocket::Read(char * data, int len) { int flags = 0; if(m_rxsocketFile <= 0) CreateRxSocket(); if(m_rxsocketFile <= 0) return -1; struct in_addr remoteIP; struct sockaddr_in serverSockAddr; int sin_len; if (!inet_aton(m_remoteIPString, &remoteIP)) { //return ; } sin_len = sizeof(serverSockAddr); if(m_ulOptions&2) flags |= MSG_DONTWAIT; len = recvfrom( m_rxsocketFile, data, len, flags, (struct sockaddr*)&serverSockAddr, &sin_len); if ( (m_ulOptions&1) || (serverSockAddr.sin_addr.s_addr == remoteIP.s_addr)) { if(len >= 0) { m_RxIp = inet_netof(remoteIP); } return len; } return 0; }
[ "shadaj@users.noreply.github.com" ]
shadaj@users.noreply.github.com
bd66e6e717b0b847e8d0b2f1bc4c6fb3f96f3c54
a6287f4063aac5fc4e16223991a86790e6af40d2
/Week 1/Jewels and Stones.cpp
b0d26f6f7e9cdb0cb194ebcb0ce8d3d694826b39
[]
no_license
rakeshbhaviripudi/LeetCode30_May
4eb2757092514fd3c3757f7b128a596bd94dccd4
ca89912cefbf7679cd7fbe3412242a34aeb91ac6
refs/heads/master
2022-09-13T06:22:45.354700
2020-05-21T09:01:34
2020-05-21T09:01:34
260,748,561
0
0
null
null
null
null
UTF-8
C++
false
false
799
cpp
class Solution { public: int numJewelsInStones_1(string J, string S) { set<char> jewels; int count=0; for(int i=0; i< J.size();i++){ jewels.insert(J[i]); } for(char s: S){ if(jewels.find(s) != jewels.end()){ count++; } } return count; } int numJewelsInStones(string J, string S){ int count=0; for(int i=0; i< S.size(); i++){ if(J.find(S[i]) != std::string::npos) count++; } return count; } int numJewelsInStones_2(string J, string S) { int res = 0; unordered_set<char> setJ(J.begin(), J.end()); for (char s : S) if (setJ.count(s)) res++; return res; } };
[ "noreply@github.com" ]
noreply@github.com
52bf48b7444179104a089696242ff024fff30a40
cadd353eb2cc15f7d21786a071fb552bea9c0390
/Scp.cpp
a85dd76917a945e0e2020ffc07d7d56de265a834
[]
no_license
rohan-sawhney/conformal-parameterization
57245a022e8b55b048c0f409474b1605b127eb2c
e859954f6c85f2cf6cf2cefef3041ff9307bbfdd
refs/heads/master
2020-04-16T17:03:02.110567
2018-01-05T14:38:40
2018-01-05T14:38:40
42,397,726
18
5
null
null
null
null
UTF-8
C++
false
false
4,445
cpp
#include "Scp.h" #include <eigen/SparseCholesky> #define MAX_ITER 32 Scp::Scp(Mesh& mesh0): Parameterization(mesh0) { } void Scp::setBoundaryIndices(Eigen::SparseMatrix<std::complex<double>>& B, Eigen::VectorXcd& e) const { std::vector<Eigen::Triplet<std::complex<double>>> BTriplets; HalfEdgeCIter he = mesh.boundaries[0]; int nB = 0; HalfEdgeCIter h = he; do { int i = h->vertex->index; BTriplets.push_back(Eigen::Triplet<std::complex<double>>(i, i, 1.0)); e(i) = 1.0; nB++; h = h->next; } while (h != he); B.setFromTriplets(BTriplets.begin(), BTriplets.end()); for (VertexCIter v = mesh.vertices.begin(); v != mesh.vertices.end(); v++) e(v->index) /= sqrt(nB); } void Scp::buildConformalEnergy(Eigen::SparseMatrix<std::complex<double>>& E) const { std::vector<Eigen::Triplet<std::complex<double>>> ETriplets; // build dirichlet energy for (VertexCIter v = mesh.vertices.begin(); v != mesh.vertices.end(); v++) { HalfEdgeCIter he = v->he; double sumCoefficients = 0.0; do { // (cotA + cotB) / 4 double coefficient = 0.25 * (he->cotan() + he->flip->cotan()); sumCoefficients += coefficient; ETriplets.push_back(Eigen::Triplet<std::complex<double>>(v->index, he->flip->vertex->index, -coefficient)); he = he->flip->next; } while (he != v->he); ETriplets.push_back(Eigen::Triplet<std::complex<double>>(v->index, v->index, sumCoefficients)); } // subtract area term from dirichlet energy std::complex<double> i(0, 0.25); for (std::vector<HalfEdgeIter>::const_iterator it = mesh.boundaries.begin(); it != mesh.boundaries.end(); it++) { HalfEdgeCIter he = *it; do { int id1 = he->vertex->index; int id2 = he->flip->vertex->index; ETriplets.push_back(Eigen::Triplet<std::complex<double>>(id1, id2, -i)); ETriplets.push_back(Eigen::Triplet<std::complex<double>>(id2, id1, i)); he = he->next; } while (he != *it); } E.setFromTriplets(ETriplets.begin(), ETriplets.end()); } double residual(const Eigen::SparseMatrix<std::complex<double>>& A, const Eigen::SparseMatrix<std::complex<double>>& B, const Eigen::VectorXcd& x) { std::complex<double> lambda = x.dot(A*x) / x.dot(B*x); return (A*x - lambda*B*x).norm() / x.norm(); } void solveInversePowerMethod(const Eigen::SparseMatrix<std::complex<double>>& A, const Eigen::SparseMatrix<std::complex<double>>& B, const Eigen::VectorXcd& e, Eigen::VectorXcd& x) { // solves A x = lambda (B - EE^T) x for the smallest nonzero eigenvalue lambda // A must be positive (semi-)definite, B must be symmetric; EE^T is a low-rank matrix, and // x is used as an initial guess // prefactor Eigen::SimplicialCholesky<Eigen::SparseMatrix<std::complex<double>>> solver(A); for (int i = 0; i < MAX_ITER; i++) { // backsolve x = B*x - e*(e.dot(x)); x = solver.solve(x); // normalize x.normalize(); } } void Scp::setUvs(const Eigen::VectorXcd& z) { // set uv coords for (VertexIter v = mesh.vertices.begin(); v != mesh.vertices.end(); v++) { v->uv(0) = z(v->index).real(); v->uv(1) = z(v->index).imag(); } normalize(); } void Scp::parameterize() { int v = (int)mesh.vertices.size(); // set boundary indices Eigen::SparseMatrix<std::complex<double>>B (v, v); Eigen::VectorXcd e = Eigen::VectorXcd::Zero(v); setBoundaryIndices(B, e); // build conformal energy Eigen::SparseMatrix<std::complex<double>> E(v, v); buildConformalEnergy(E); E += std::complex<double>(1e-8) * B; // find eigenvector corresponding to smallest eigenvalue Eigen::VectorXcd z = Eigen::VectorXcd::Random(v); solveInversePowerMethod(E, B, e, z); // set uv coords setUvs(z); }
[ "sawhney_rohan@yahoo.co.in" ]
sawhney_rohan@yahoo.co.in
03a98460b970f0b3ec9f94d6f98ca1703c5d2e0b
e2b44d240cf2bdb12d780551d4f5c849693173dd
/cpp/FreeCell/Constants.h
b066975efcd95e139a92e5ed43c3b6c1ae51fcf0
[ "MIT" ]
permissive
kfsone/tinker
445678c6e38b7c6ab11e14295864ada886d44589
81ed372117bcad691176aac960302f497adf8d82
refs/heads/master
2022-06-12T18:36:09.225720
2021-02-21T20:38:10
2021-02-21T20:38:10
94,041,989
0
0
MIT
2022-06-06T18:27:44
2017-06-12T01:04:30
Python
UTF-8
C++
false
false
1,294
h
#pragma once #include <array> #include <cstdint> #include <string> namespace FreeCell { //! Possible card colors. enum class Color : uint8_t { Red, Black, _NumColors }; //! Enumeration of all suites. enum class Suite : uint8_t { Hearts, Diamonds, Clubs, Spades, _NumSuites }; //! Enumerations of card faces in value order. enum class Face : uint8_t { Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, _NumFaces }; constexpr uint8_t INVALID_CARD = 255; //! Constant for "no card". //! Enumerations of the cardstack types where things can be placed. enum class Placement : uint8_t { Column, Spare, Foundation }; // Numeric values for the various enum'd constraints to reduce casting elsewhere. constexpr uint8_t NUM_COLORS = uint8_t(Color::_NumColors); //! Pre-cast number of card colors. constexpr uint8_t NUM_SUITES = uint8_t(Suite::_NumSuites); //! Pre-cast number of suites. constexpr uint8_t NUM_FACES = uint8_t(Face::_NumFaces); //! Pre-cast number of faces. constexpr uint8_t NUM_CARDS = NUM_FACES * NUM_SUITES; //! Pre-cast total number of cards. constexpr uint8_t NUM_COLUMNS = 8; //! Number of columns that form the deck. constexpr uint8_t NUM_SPARES = 4; //! Number of spare card slots available. }
[ "oliver@kfs.org" ]
oliver@kfs.org
a465b1e29fa09eab62aea8edfb6b86da25f76ff1
1830864eb4755311ec2100d8a04c09da75dd4ada
/project 1/Synthie/COddSines.cpp
1a3a545811173fa86875bd39e900e187d15a53eb
[]
no_license
WMWwendy/Project1
dea626c491f8002f7183801eda33f8e0e930adf9
b4e72db7f9b3a5de9e30f903df7d34873045edcb
refs/heads/main
2023-03-27T07:46:10.548384
2021-03-30T18:11:20
2021-03-30T18:11:20
353,077,127
0
0
null
null
null
null
UTF-8
C++
false
false
522
cpp
#include "stdafx.h" #include "COddSines.h" #include <cmath> COddSines::COddSines(void) { for (int i = 0; i < 4; i++) m_amp[i] = 1; } COddSines::~COddSines(void) { } void COddSines::Start() { m_phase = 0; } bool COddSines::Generate() { double sample = 0; for (int i = 0; i < 4; i++) { sample += m_amp[i] * sin(m_phase * (i * 2 + 1)); } m_frame[1] = m_frame[0] = sample; m_phase += 2 * PI * m_freq * GetSamplePeriod(); return true; }
[ "noreply@github.com" ]
noreply@github.com
98eeb95dd0b93bafb685d8f4871a2e0ee5e13107
797de529d4eb372a1a508427a20fa07b6c9eaa33
/mqttsn-messages.h
bc012e8bd422b4c75adc703aa5200c4af8918904
[ "Apache-2.0" ]
permissive
crnt/openvent-arduino
0f550081e95937b841458d0c74f8226ce301d231
5c6f1cceb07728d233af9a105622ff041fcee968
refs/heads/master
2022-06-14T11:15:01.695946
2020-05-06T19:07:52
2020-05-06T19:07:52
261,137,732
0
0
null
2020-05-04T09:59:09
2020-05-04T09:59:08
null
UTF-8
C++
false
false
4,459
h
/* mqttsn-messages.h The MIT License (MIT) Copyright (C) 2014 John Donovan Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef __MQTTSN_MESSAGES_H__ #define __MQTTSN_MESSAGES_H__ #include "mqttsn.h" #define MAX_TOPICS 10 #define MAX_BUFFER_SIZE 66 class MQTTSN { public: MQTTSN(); virtual ~MQTTSN(); uint16_t find_topic_id(const char* name, uint8_t* index); bool wait_for_response(); bool connected(); #ifdef USE_SERIAL void parse_stream(uint8_t* buf, uint16_t len); #endif #ifdef USE_RF12 void parse_rf12(); #endif void searchgw(const uint8_t radius); void connect(const uint8_t flags, const uint16_t duration, const char* client_id); void willtopic(const uint8_t flags, const char* will_topic, const bool update = false); void willmsg(const void* will_msg, const uint8_t will_msg_len, const bool update = false); bool register_topic(const char* name); void publish(const uint8_t flags, const uint16_t topic_id, const void* data, const uint8_t data_len); #ifdef USE_QOS2 void pubrec(); void pubrel(); void pubcomp(); #endif void subscribe_by_name(const uint8_t flags, const char* topic_name); void subscribe_by_id(const uint8_t flags, const uint16_t topic_id); void unsubscribe_by_name(const uint8_t flags, const char* topic_name); void unsubscribe_by_id(const uint8_t flags, const uint16_t topic_id); void pingreq(const char* client_id); void pingresp(); void disconnect(const uint16_t duration); protected: virtual void advertise_handler(const msg_advertise* msg); virtual void gwinfo_handler(const msg_gwinfo* msg); virtual void connack_handler(const msg_connack* msg); virtual void willtopicreq_handler(const message_header* msg); virtual void willmsgreq_handler(const message_header* msg); virtual void regack_handler(const msg_regack* msg); virtual void publish_handler(const msg_publish* msg); virtual void register_handler(const msg_register* msg); virtual void puback_handler(const msg_puback* msg); #ifdef USE_QOS2 virtual void pubrec_handler(const msg_pubqos2* msg); virtual void pubrel_handler(const msg_pubqos2* msg); virtual void pubcomp_handler(const msg_pubqos2* msg); #endif virtual void suback_handler(const msg_suback* msg); virtual void unsuback_handler(const msg_unsuback* msg); virtual void pingreq_handler(const msg_pingreq* msg); virtual void pingresp_handler(); virtual void disconnect_handler(const msg_disconnect* msg); virtual void willtopicresp_handler(const msg_willtopicresp* msg); virtual void willmsgresp_handler(const msg_willmsgresp* msg); void regack(const uint16_t topic_id, const uint16_t message_id, const return_code_t return_code); void puback(const uint16_t topic_id, const uint16_t message_id, const return_code_t return_code); private: struct topic { const char* name; uint16_t id; }; void dispatch(); uint16_t bswap(const uint16_t val); void send_message(); // Set to true when we're waiting for some sort of acknowledgement from the //server that will transition our state. bool waiting_for_response; bool _connected; uint16_t _message_id; uint8_t topic_count; uint8_t message_buffer[MAX_BUFFER_SIZE]; uint8_t response_buffer[MAX_BUFFER_SIZE]; topic topic_table[MAX_TOPICS]; uint8_t _gateway_id; uint32_t _response_timer; uint8_t _response_retries; }; #endif
[ "longdh@vng.com.vn" ]
longdh@vng.com.vn
ce9a741d7e43935781e26bfe5cafa2567ead1bff
d93c9f0239e33fcb8ccc20ce999b094659003202
/aero_path_planning/test/CastLineTest.cpp
688fb4a69a8c169352bd92eac0f916a2bb868b6e
[]
no_license
Sprann9257/aero_srr_13
6657b5f464b3b43f11b8c8b4091b21660a7df910
f378a11bc6de8b280262cb3de7d58eab95a4eee7
refs/heads/master
2021-05-27T19:23:10.092640
2013-06-06T17:15:20
2013-06-06T17:15:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,368
cpp
/** * @file CastLineTest.cpp * * @date Feb 25, 2013 * @author Adam Panzica * @brief Tests for the castLine function */ //License File //****************SYSTEM DEPENDANCIES**************************// #include<gtest/gtest.h> //*****************LOCAL DEPENDANCIES**************************// #include<aero_path_planning/occupancy_grid/OccupancyGrid.h> //**********************NAMESPACES*****************************// #define PRINT_EXPECTED_POINT(expect, actual)PRINT_POINT_S("Expected Point", expect)<<", "<<PRINT_POINT_S("Actual Point", actual) using namespace aero_path_planning; TEST(CastLineTests, testCastLineZero) { PointCloud test_line; Point pls; Point ple; pls.x = 0; pls.y = 0; pls.z = 0; ple.x = 0; ple.y = 0; ple.z = 0; aero_path_planning::castLine(pls, ple, 0, test_line); //The line from 0,0,0 to 0,0,0 should be of size 1 since it should just have a point at the start ASSERT_EQ(1, test_line.size()); ASSERT_EQ(pls.getVector4fMap(), test_line.at(0).getVector4fMap()); } TEST(CastLineTests, testCastLinePxPy) { PointCloud test_line; Point pls; Point ple; pls.x = 0; pls.y = 0; pls.z = 0; ple.x = 10; ple.y = 10; ple.z = 0; aero_path_planning::castLine(pls, ple, 0, test_line); //There should be a line, and it should be greater than two points ASSERT_NE(0, test_line.size()); ASSERT_LT(2, test_line.size()); //The start and end points should match the given start/end points Point start_point = test_line.at(0); Point end_point = test_line.at(test_line.size()-1); EXPECT_EQ(pls.getVector4fMap(), start_point.getVector4fMap())<<PRINT_EXPECTED_POINT(pls, start_point); EXPECT_EQ(ple.getVector4fMap(), end_point.getVector4fMap()) <<PRINT_EXPECTED_POINT(ple, end_point); EXPECT_NE(pls.getVector4fMap(), test_line.at(1).getVector4fMap()); EXPECT_NE(ple.getVector4fMap(), test_line.at(1).getVector4fMap()); } TEST(CastLineTest, testCastLinePxNy) { PointCloud test_line; Point pls; Point ple; pls.x = 0; pls.y = 0; pls.z = 0; ple.x = 10; ple.y = -10; ple.z = 0; aero_path_planning::castLine(pls, ple, 0, test_line); //There should be a line ASSERT_NE(0, test_line.size()); ASSERT_LT(2, test_line.size()); //The start and end points should match the given start/end points Point start_point = test_line.at(0); Point end_point = test_line.at(test_line.size()-1); EXPECT_EQ(pls.getVector4fMap(), start_point.getVector4fMap())<<PRINT_EXPECTED_POINT(pls, start_point); EXPECT_EQ(ple.getVector4fMap(), end_point.getVector4fMap()) <<PRINT_EXPECTED_POINT(ple, end_point); EXPECT_NE(pls.getVector4fMap(), test_line.at(1).getVector4fMap()); EXPECT_NE(ple.getVector4fMap(), test_line.at(1).getVector4fMap()); } TEST(CastLineTest, testCastLineNxPy) { PointCloud test_line; Point pls; Point ple; pls.x = 0; pls.y = 0; pls.z = 0; ple.x = -10; ple.y = 10; ple.z = 0; aero_path_planning::castLine(pls, ple, 0, test_line); //There should be a line ASSERT_NE(0, test_line.size()); ASSERT_LT(2, test_line.size()); //The start and end points should match the given start/end points Point start_point = test_line.at(0); Point end_point = test_line.at(test_line.size()-1); EXPECT_EQ(pls.getVector4fMap(), start_point.getVector4fMap())<<PRINT_EXPECTED_POINT(pls, start_point); EXPECT_EQ(ple.getVector4fMap(), end_point.getVector4fMap()) <<PRINT_EXPECTED_POINT(ple, end_point); EXPECT_NE(pls.getVector4fMap(), test_line.at(1).getVector4fMap()); EXPECT_NE(ple.getVector4fMap(), test_line.at(1).getVector4fMap()); } TEST(CastLineTest, testCastLineNxNy) { PointCloud test_line; Point pls; Point ple; pls.x = 0; pls.y = 0; pls.z = 0; ple.x = -10; ple.y = -10; ple.z = 0; aero_path_planning::castLine(pls, ple, 0, test_line); //There should be a line ASSERT_NE(0, test_line.size()); ASSERT_LT(2, test_line.size()); //The start and end points should match the given start/end points Point start_point = test_line.at(0); Point end_point = test_line.at(test_line.size()-1); EXPECT_EQ(pls.getVector4fMap(), start_point.getVector4fMap())<<PRINT_EXPECTED_POINT(pls, start_point); EXPECT_EQ(ple.getVector4fMap(), end_point.getVector4fMap()) <<PRINT_EXPECTED_POINT(ple, end_point); EXPECT_NE(pls.getVector4fMap(), test_line.at(1).getVector4fMap()); EXPECT_NE(ple.getVector4fMap(), test_line.at(1).getVector4fMap()); }
[ "adampanzica@gmail.com" ]
adampanzica@gmail.com
004ba617f3b2741659536db02ee8d9155966c502
631072cb1b59533d921616b968e06590f0da64dc
/prevent/VLC.h
136d8af5cd4b6f012753c3122421628ce7ef31bb
[]
no_license
lloydpick/preVentrilo
4065d8e4bc819a94716ff4b49b88b9e238437f5a
f212ba1cff67faa1f7c41b1a05fce36682f59b7c
refs/heads/master
2021-01-15T12:25:57.822184
2010-09-06T17:03:20
2010-09-06T17:03:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,496
h
#pragma once #include "MediaPlayerBase.h" class CVLC : public CMediaPlayerBase { public: //----------------------------------------------------------------------- //! \brief Constructor //----------------------------------------------------------------------- CVLC(void); //----------------------------------------------------------------------- //! \brief Destructor //----------------------------------------------------------------------- virtual ~CVLC(void); //----------------------------------------------------------------------- //! \brief Returns whether or not the media player is currently playing. //----------------------------------------------------------------------- bool IsPlaying(); //----------------------------------------------------------------------- //! \brief Returns whether or not the media player is currently paused. //----------------------------------------------------------------------- bool IsPaused(); //----------------------------------------------------------------------- //! \brief Returns the media player's current volume as a percent. //----------------------------------------------------------------------- int CurrentVolume(); //----------------------------------------------------------------------- //! \brief Sets the media player's volume. //! //! \param nVolume What to set the volume to as a percent //----------------------------------------------------------------------- void SetVolume(int nVolume); //----------------------------------------------------------------------- //! \brief Pauses the media player if it is currently playing. //----------------------------------------------------------------------- void Pause(); //----------------------------------------------------------------------- //! \brief Pauses the media player if it is currently paused. //----------------------------------------------------------------------- void UnPause(); //----------------------------------------------------------------------- //! \brief Attempts to play the media player if it is not currently //! playing. //----------------------------------------------------------------------- void Play(); //----------------------------------------------------------------------- //! \brief Attempts to get a handle to the media player //----------------------------------------------------------------------- void FindHandle(); };
[ "lloydpick@gmail.com" ]
lloydpick@gmail.com
e2cfa18aa8073ded9d95aa6ad255b97204d86ce4
79ee346b97558af64133565d68380a53755144d2
/SmartFitArduino/Framework/ES_Timers.cpp
80919b88b4be7cbe6e371ee404c8e596f199ec62
[]
no_license
corner4world/smart-fit
5419f346d4bcc6bdd839cff54d0790d3a1118da3
a2bf078392642bcbda901fd52a13cc5b9c01bcce
refs/heads/master
2021-07-14T12:13:07.846117
2017-06-08T20:49:35
2017-06-08T20:49:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,117
cpp
/**************************************************************************** Module ES_Timers.c Description This is a module implementing 8 16 bit timers all using the RTI timebase Notes Everything is done in terms of RTI Ticks, which can change from application to application. History When Who What/Why -------------- --- -------- 10/27/14 14:02 jec moved ticking of 'time' to ES_Port to allow it to tick even while blocking. required change to ES_GetTime too 10/20/13 10:48 jec moved definition of BITS_PER_BYTE to ES_General.h 08/13/13 12:05 jec moved the hardware specific code to ES_Port.c and made the Tick response a routine called from there. 01/16/12 09:42 jec added some more error checking to start & init funcs to prevent starting a timer with no service attached or with a time of 0 01/15/12 16:46 jec convert to Gen2 of Events & Services framework 10/21/11 18:26 jec begin conversion to work with the new Event Framework 09/01/05 13:16 jec converted the return types and parameters to use the enumerated constants from the new header. 08/31/05 10:23 jec converted several return value tests in the test harness to use symbolic values. 06/15/04 09:56 jec converted all external prefixes to TMRS12 to be sure that we don't have any conflicts with the old libs 05/28/04 13:53 jec converted for 9S12C32 processor 12/11/02 14:53 dos converted for ICC11V6, unadorned char needs to be called out as signed char, default is now unsigned for a plain char. 11/24/99 14:45 rmo updated to compile under ICC11v5. 02/24/97 17:13 jec added new function TMR_SetTimer. This will allow one function to set up the time, while another function actually initiates the timing. 02/24/97 13:34 jec Began Coding ****************************************************************************/ /*----------------------------- Include Files -----------------------------*/ #include "../ES_Configure.h" #include "ES_Framework.h" #include "ES_ServiceHeaders.h" #include "ES_General.h" #include "ES_Events.h" #include "ES_PostList.h" #include "ES_LookupTables.h" #include "ES_Timers.h" #include "ES_Port.h" /*--------------------------- External Variables --------------------------*/ /*----------------------------- Module Defines ----------------------------*/ /*------------------------------ Module Types -----------------------------*/ /* the size of Tflag sets the number of timers, uint8 = 8, uint16 = 16 ...) to add more timers, you will need to change the data type and modify the initialization of TMR_TimerArray and TMR_MaskArray */ typedef uint16_t Tflag_t; typedef uint16_t Timer_t; // sets size of timers to 16 bits /*---------------------------- Module Functions ---------------------------*/ /*---------------------------- Module Variables ---------------------------*/ static Timer_t TMR_TimerArray[sizeof(Tflag_t)*BITS_PER_BYTE]= { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 }; static Tflag_t TMR_ActiveFlags; static pPostFunc const Timer2PostFunc[sizeof(Tflag_t)*BITS_PER_BYTE] = { TIMER0_RESP_FUNC, TIMER1_RESP_FUNC, TIMER2_RESP_FUNC, TIMER3_RESP_FUNC, TIMER4_RESP_FUNC, TIMER5_RESP_FUNC, TIMER6_RESP_FUNC, TIMER7_RESP_FUNC, TIMER8_RESP_FUNC, TIMER9_RESP_FUNC, TIMER10_RESP_FUNC, TIMER11_RESP_FUNC, TIMER12_RESP_FUNC, TIMER13_RESP_FUNC, TIMER14_RESP_FUNC, TIMER15_RESP_FUNC }; /*------------------------------ Module Code ------------------------------*/ /**************************************************************************** Function ES_Timer_Init Parameters unsigned char Rate set to one of the TMR_RATE_XX values to set the tick rate these are defined by the hardware and placed in ES_Port.h Returns None. Description Initializes the timer module by setting up the tick at the requested rate Notes None. Author J. Edward Carryer, 02/24/97 14:23 ****************************************************************************/ void ES_Timer_Init(TimerRate_t Rate) { // call the hardware init routine _HW_Timer_Init(Rate); } /**************************************************************************** Function ES_Timer_SetTimer Parameters unsigned char Num, the number of the timer to set. unsigned int NewTime, the new time to set on that timer Returns ES_Timer_ERR if requested timer does not exist or has no service ES_Timer_OK otherwise Description sets the time for a timer, but does not make it active. Notes None. Author J. Edward Carryer, 02/24/97 17:11 ****************************************************************************/ ES_TimerReturn_t ES_Timer_SetTimer(uint8_t Num, uint16_t NewTime) { /* tried to set a timer that doesn't exist */ if( (Num >= ARRAY_SIZE(TMR_TimerArray)) || /* tried to set a timer without a service */ (Timer2PostFunc[Num] == TIMER_UNUSED) || (NewTime == 0) ) /* no time being set */ return ES_Timer_ERR; TMR_TimerArray[Num] = NewTime; return ES_Timer_OK; } /**************************************************************************** Function ES_Timer_StartTimer Parameters unsigned char Num the number of the timer to start Returns ES_Timer_ERR for error ES_Timer_OK for success Description simply sets the active flag in TMR_ActiveFlags to (re)start a stopped timer. Notes None. Author J. Edward Carryer, 02/24/97 14:45 ****************************************************************************/ ES_TimerReturn_t ES_Timer_StartTimer(uint8_t Num) { /* tried to set a timer that doesn't exist */ if( (Num >= ARRAY_SIZE(TMR_TimerArray)) || /* tried to set a timer with no time on it */ (TMR_TimerArray[Num] == 0) ) return ES_Timer_ERR; TMR_ActiveFlags |= BitNum2SetMask[Num]; /* set timer as active */ return ES_Timer_OK; } /**************************************************************************** Function ES_Timer_StopTimer Parameters unsigned char Num the number of the timer to stop. Returns ES_Timer_ERR for error (timer doesn't exist) ES_Timer_OK for success. Description simply clears the bit in TMR_ActiveFlags associated with this timer. This will cause it to stop counting. Notes None. Author J. Edward Carryer, 02/24/97 14:48 ****************************************************************************/ ES_TimerReturn_t ES_Timer_StopTimer(uint8_t Num) { if( Num >= ARRAY_SIZE(TMR_TimerArray) ) return ES_Timer_ERR; /* tried to set a timer that doesn't exist */ TMR_ActiveFlags &= BitNum2ClrMask[Num]; /* set timer as inactive */ return ES_Timer_OK; } /**************************************************************************** Function ES_Timer_InitTimer Parameters unsigned char Num, the number of the timer to start unsigned int NewTime, the number of ticks to be counted Returns ES_Timer_ERR if the requested timer does not exist, ES_Timer_OK otherwise. Description sets the NewTime into the chosen timer and sets the timer active to begin counting. Notes None. Author J. Edward Carryer, 02/24/97 14:51 ****************************************************************************/ ES_TimerReturn_t ES_Timer_InitTimer(uint8_t Num, uint16_t NewTime) { /* tried to set a timer that doesn't exist */ if( (Num >= ARRAY_SIZE(TMR_TimerArray)) || /* tried to set a timer without a service */ (Timer2PostFunc[Num] == TIMER_UNUSED) || /* tried to set a timer without putting any time on it */ (NewTime == 0) ) return ES_Timer_ERR; TMR_TimerArray[Num] = NewTime; TMR_ActiveFlags |= BitNum2SetMask[Num]; /* set timer as active */ return ES_Timer_OK; } /**************************************************************************** Function ES_Timer_GetTime Parameters None. Returns the current value of the module variable 'time' Description Provides the ability to grab a snapshot time as an alternative to using the library timers. Can be used to determine how long between 2 events. Notes this functionality is ancient, though this implementation in the library is new. Author J. Edward Carryer, 06/01/04 08:04 ****************************************************************************/ uint16_t ES_Timer_GetTime(void) { return (_HW_GetTickCount()); } /**************************************************************************** Function ES_Timer_Tick_Resp Parameters None. Returns None. Description This is the new Tick response routine to support the timer module. It will increment time, to maintain the functionality of the GetTime() timer and it will check through the active timers, decrementing each active timers count, if the count goes to 0, it will post an event to the corresponding SM and clear the active flag to prevent further counting. Notes Called from _Timer_Int_Resp in ES_Port.c. Author J. Edward Carryer, 02/24/97 15:06 ****************************************************************************/ void ES_Timer_Tick_Resp(void) { static Tflag_t NeedsProcessing; static uint8_t NextTimer2Process; static ES_Event NewEvent; if (TMR_ActiveFlags != 0) /* if !=0 , then at least 1 timer is active */ { // start by getting a list of all the active timers NeedsProcessing = TMR_ActiveFlags; do{ // find the MSB that is set NextTimer2Process = ES_GetMSBitSet(NeedsProcessing); /* decrement that timer, check if timed out */ if(--TMR_TimerArray[NextTimer2Process] == 0) { NewEvent.EventType = ES_TIMEOUT; NewEvent.EventParam = NextTimer2Process; /* post the timeout event to the right Service */ Timer2PostFunc[NextTimer2Process](NewEvent); /* and stop counting */ TMR_ActiveFlags &= BitNum2ClrMask[NextTimer2Process]; } // mark off the active timer that we just processed NeedsProcessing &= BitNum2ClrMask[NextTimer2Process]; }while(NeedsProcessing != 0); } } /*------------------------------- Footnotes -------------------------------*/ /*------------------------------ End of file ------------------------------*/
[ "hejiajiedpim@163.com" ]
hejiajiedpim@163.com
064ca917526c7bc1b4de0890dbc2b65c8115c7dd
90ab84143896480515d5f7f5b647f92d32732777
/morphological_pre_processor.cpp
3462d1609afa8195f64730f933b44b2bd8fcb0b7
[]
no_license
dtwitty/MNIST_ML
4639b6c6394710bb18d6881f4bd7752358ef29de
73352e17b84960f3324f3723d274f43d45082f58
refs/heads/master
2020-05-02T12:50:06.717326
2014-12-11T03:28:13
2014-12-11T03:28:13
26,108,756
0
0
null
null
null
null
UTF-8
C++
false
false
568
cpp
#include "morphological_pre_processor.hpp" MorphologicalPreProcessor::MorphologicalPreProcessor( int size_hor, int size_vert, StructuringElementShape shape, MorphologialOperation operation) { structuring_element_ = cv::getStructuringElement(shape, cv::Size(size_hor, size_vert)); operation_ = operation; } void MorphologicalPreProcessor::PreProcess(const cv::Mat& input_image, cv::Mat* output_image) { cv::morphologyEx(input_image, *output_image, operation_, structuring_element_); }
[ "dktwitty@gmail.com" ]
dktwitty@gmail.com
4f3dc3df7071575c14bcded6b851b2430f8de086
0e15c4f2bcbe299cf9ddf8aa2af93073b2790166
/LEAP_YEA.CPP
4cd8864261e57ad7a91edfffaafc882c7e9eee9c
[]
no_license
imbmjha/myLearning
64ee3859f07bb80c8642ca3a4d04a318f91da85b
e3223af15900e8369c50575cd942e7959b32594a
refs/heads/master
2020-03-28T04:26:30.048204
2018-09-06T18:40:50
2018-09-06T18:40:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
201
cpp
#include<stdio.h> #include<conio.h> void main() { clrscr(); int n; clrscr(); printf("enter n"); scanf("%d",&n); if(n%4==0) { printf("%d is leap year"); } else printf("%d is not leap year"); getch(); }
[ "brajmohan.0@hotmail.com" ]
brajmohan.0@hotmail.com
242c2b64f1f8776219a7b062960895b29874cfc2
fff80cdaf12712704f36038479f50418253f42f3
/redex/sparta/include/PatriciaTreeMapAbstractPartition.h
51c26fdf931cb720347e244574786b35ece27b39
[ "MIT" ]
permissive
rudolfkopriva/Facebook
1ea0cfbc116f68ae0317332eeb9155461af5645a
56e4c6a83f992bb01849ad353004b28409e53eef
refs/heads/master
2023-02-14T01:54:36.519860
2021-01-05T02:09:26
2021-01-05T02:09:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,115
h
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <ostream> #include <cstddef> #include <functional> #include <initializer_list> #include <ostream> #include <utility> #include "AbstractDomain.h" #include "PatriciaTreeMap.h" namespace sparta { /* * An abstract partition based on Patricia trees that is cheap to copy. * * In order to minimize the size of the underlying tree, we do not explicitly * represent bindings of a label to the Bottom element. * * See HashedAbstractPartition.h for more details about abstract partitions. * * This implementation differs slightly from the textbook definition of a * partition: our Top partition cannot have its labels re-bound to anything * other than Top. I.e. for all labels L and domains D, * * PatriciaTreeMapAbstractPartition::top().set(L, D) == * PatriciaTreeMapAbstractPartition::top() * * This makes for a much simpler implementation. */ template <typename Label, typename Domain> class PatriciaTreeMapAbstractPartition final : public AbstractDomain<PatriciaTreeMapAbstractPartition<Label, Domain>> { public: struct ValueInterface { using type = Domain; static type default_value() { return type::bottom(); } static bool is_default_value(const type& x) { return x.is_bottom(); } static bool equals(const type& x, const type& y) { return x.equals(y); } static bool leq(const type& x, const type& y) { return x.leq(y); } }; using MapType = PatriciaTreeMap<Label, Domain, ValueInterface>; /* * The default constructor produces the Bottom value. */ PatriciaTreeMapAbstractPartition() = default; PatriciaTreeMapAbstractPartition( std::initializer_list<std::pair<Label, Domain>> l) { for (const auto& p : l) { set(p.first, p.second); } } /* * Number of bindings not set to Bottom. This operation is not defined if the * PatriciaTreeMapAbstractPartition is set to Top. */ size_t size() const { RUNTIME_CHECK(!is_top(), undefined_operation()); return m_map.size(); } /* * Get the bindings that are not set to Bottom. This operation is not defined * if the PatriciaTreeMapAbstractPartition is set to Top. */ const MapType& bindings() const { RUNTIME_CHECK(!is_top(), undefined_operation()); return m_map; } const Domain& get(const Label& label) const { if (is_top()) { static const Domain top = Domain::top(); return top; } return m_map.at(label); } /* * This is a no-op if the partition is set to Top. */ PatriciaTreeMapAbstractPartition& set(const Label& label, const Domain& value) { if (is_top()) { return *this; } m_map.insert_or_assign(label, value); return *this; } /* * This is a no-op if the partition is set to Top. */ PatriciaTreeMapAbstractPartition& update( const Label& label, std::function<Domain(const Domain&)> operation) { if (is_top()) { return *this; } m_map.update(operation, label); return *this; } bool map(std::function<Domain(const Domain&)> f) { if (is_top()) { return false; } return m_map.map(f); } bool is_top() const override { return m_is_top; } bool is_bottom() const override { return !m_is_top && m_map.empty(); } void set_to_bottom() override { m_map.clear(); m_is_top = false; } void set_to_top() override { m_map.clear(); m_is_top = true; } bool leq(const PatriciaTreeMapAbstractPartition& other) const override { if (is_top()) { return other.is_top(); } if (other.is_top()) { return true; } return m_map.leq(other.m_map); } bool equals(const PatriciaTreeMapAbstractPartition& other) const override { if (m_is_top != other.m_is_top) { return false; } return m_map.equals(other.m_map); } void join_with(const PatriciaTreeMapAbstractPartition& other) override { join_like_operation( other, [](const Domain& x, const Domain& y) { return x.join(y); }); } void widen_with(const PatriciaTreeMapAbstractPartition& other) override { join_like_operation( other, [](const Domain& x, const Domain& y) { return x.widening(y); }); } void meet_with(const PatriciaTreeMapAbstractPartition& other) override { meet_like_operation( other, [](const Domain& x, const Domain& y) { return x.meet(y); }); } void narrow_with(const PatriciaTreeMapAbstractPartition& other) override { meet_like_operation( other, [](const Domain& x, const Domain& y) { return x.narrowing(y); }); } void join_like_operation( const PatriciaTreeMapAbstractPartition& other, std::function<Domain(const Domain&, const Domain&)> operation) { if (is_top()) { return; } if (other.is_top()) { set_to_top(); return; } m_map.union_with(operation, other.m_map); } void meet_like_operation( const PatriciaTreeMapAbstractPartition& other, std::function<Domain(const Domain&, const Domain&)> operation) { if (is_top()) { *this = other; return; } if (other.is_top()) { return; } m_map.intersection_with(operation, other.m_map); } static PatriciaTreeMapAbstractPartition bottom() { return PatriciaTreeMapAbstractPartition(); } static PatriciaTreeMapAbstractPartition top() { auto part = PatriciaTreeMapAbstractPartition(); part.m_is_top = true; return part; } private: MapType m_map; bool m_is_top{false}; }; } // namespace sparta template <typename Label, typename Domain> inline std::ostream& operator<<( std::ostream& o, const typename sparta::PatriciaTreeMapAbstractPartition<Label, Domain>& partition) { if (partition.is_bottom()) { o << "_|_"; } else if (partition.is_top()) { o << "T"; } else { o << "[#" << partition.size() << "]"; o << partition.bindings(); } return o; }
[ "nateweiler84@gmail.com" ]
nateweiler84@gmail.com
1f100b7aa6a33f6c5dc5d8edc296463739627afc
5ec06dab1409d790496ce082dacb321392b32fe9
/clients/cpp-qt5-qhttpengine-server/generated/server/src/models/OAIComAdobeCqSocialCommonsEmailreplyImplIOSEmailClientProviderInfo.h
b9560e2579ef7e0c5918b93cf884b9c5b01a585b
[ "MIT", "Apache-2.0" ]
permissive
shinesolutions/swagger-aem-osgi
e9d2385f44bee70e5bbdc0d577e99a9f2525266f
c2f6e076971d2592c1cbd3f70695c679e807396b
refs/heads/master
2022-10-29T13:07:40.422092
2021-04-09T07:46:03
2021-04-09T07:46:03
190,217,155
3
3
Apache-2.0
2022-10-05T03:26:20
2019-06-04T14:23:28
null
UTF-8
C++
false
false
2,221
h
/** * Adobe Experience Manager OSGI config (AEM) API * Swagger AEM OSGI is an OpenAPI specification for Adobe Experience Manager (AEM) OSGI Configurations API * * OpenAPI spec version: 1.0.0-pre.0 * Contact: opensource@shinesolutions.com * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ /* * OAIComAdobeCqSocialCommonsEmailreplyImplIOSEmailClientProviderInfo.h * * */ #ifndef OAIComAdobeCqSocialCommonsEmailreplyImplIOSEmailClientProviderInfo_H #define OAIComAdobeCqSocialCommonsEmailreplyImplIOSEmailClientProviderInfo_H #include <QJsonObject> #include "OAIComAdobeCqSocialCommonsEmailreplyImplIOSEmailClientProviderProperties.h" #include <QString> #include "OAIObject.h" namespace OpenAPI { class OAIComAdobeCqSocialCommonsEmailreplyImplIOSEmailClientProviderInfo: public OAIObject { public: OAIComAdobeCqSocialCommonsEmailreplyImplIOSEmailClientProviderInfo(); OAIComAdobeCqSocialCommonsEmailreplyImplIOSEmailClientProviderInfo(QString json); ~OAIComAdobeCqSocialCommonsEmailreplyImplIOSEmailClientProviderInfo() override; void init(); QString asJson () const override; QJsonObject asJsonObject() const override; void fromJsonObject(QJsonObject json) override; void fromJson(QString jsonString) override; QString getPid() const; void setPid(const QString &pid); QString getTitle() const; void setTitle(const QString &title); QString getDescription() const; void setDescription(const QString &description); OAIComAdobeCqSocialCommonsEmailreplyImplIOSEmailClientProviderProperties getProperties() const; void setProperties(const OAIComAdobeCqSocialCommonsEmailreplyImplIOSEmailClientProviderProperties &properties); virtual bool isSet() const override; private: QString pid; bool m_pid_isSet; QString title; bool m_title_isSet; QString description; bool m_description_isSet; OAIComAdobeCqSocialCommonsEmailreplyImplIOSEmailClientProviderProperties properties; bool m_properties_isSet; }; } #endif // OAIComAdobeCqSocialCommonsEmailreplyImplIOSEmailClientProviderInfo_H
[ "cliffano@gmail.com" ]
cliffano@gmail.com
91d50da46baaa2db1ed81882573ae948b36a577e
9a3b9d80afd88e1fa9a24303877d6e130ce22702
/src/Providers/UNIXProviders/AssociatedFileSystemStatisticsManifestCollection/UNIX_AssociatedFileSystemStatisticsManifestCollection.h
4f719242d617252f076b33fb07c858ebea21f353
[ "MIT" ]
permissive
brunolauze/openpegasus-providers
3244b76d075bc66a77e4ed135893437a66dd769f
f24c56acab2c4c210a8d165bb499cd1b3a12f222
refs/heads/master
2020-04-17T04:27:14.970917
2015-01-04T22:08:09
2015-01-04T22:08:09
19,707,296
0
0
null
null
null
null
UTF-8
C++
false
false
4,169
h
//%LICENSE//////////////////////////////////////////////////////////////// // // Licensed to The Open Group (TOG) under one or more contributor license // agreements. Refer to the OpenPegasusNOTICE.txt file distributed with // this work for additional information regarding copyright ownership. // Each contributor licenses this file to you under the OpenPegasus Open // Source License; you may not use this file except in compliance with the // License. // // 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. // ////////////////////////////////////////////////////////////////////////// // //%///////////////////////////////////////////////////////////////////////// /* **** Association *** */ /* TRUE */ /* **** Experimental *** */ /* TRUE */ /* **** Version *** */ /* 2.38.0 */ /* **** UMLPackagePath *** */ /* CIM::System::FileStatistics */ /* **** Description *** */ /* Instances of this class associate a CIM_FileSystemStatisticsManifestCollection to the StatisticsCollection to which it applies. The ManifestCollection contains the Manifests that are used to filter requests for the retrieval of statistics. */ /* *** Properties *** UNIX_AssociatedFileSystemStatisticsManifestCollection: Statistics Reference ManifestCollection Reference */ /* *** Methods *** UNIX_AssociatedFileSystemStatisticsManifestCollection: */ #ifndef __UNIX_ASSOCIATEDFILESYSTEMSTATISTICSMANIFESTCOLLECTION_H #define __UNIX_ASSOCIATEDFILESYSTEMSTATISTICSMANIFESTCOLLECTION_H #include "CIM_ClassBase.h" #include "UNIX_AssociatedFileSystemStatisticsManifestCollectionDeps.h" #ifndef PROPERTY_STATISTICS #define PROPERTY_STATISTICS \ "Statistics" #endif #ifndef PROPERTY_MANIFEST_COLLECTION #define PROPERTY_MANIFEST_COLLECTION \ "ManifestCollection" #endif class UNIX_AssociatedFileSystemStatisticsManifestCollection : public CIM_ClassBase { public: UNIX_AssociatedFileSystemStatisticsManifestCollection(); ~UNIX_AssociatedFileSystemStatisticsManifestCollection(); virtual Boolean initialize(); virtual Boolean load(int&); virtual Boolean finalize(); virtual Boolean find(const Array<CIMKeyBinding>&); virtual Boolean validateKey(CIMKeyBinding&) const; virtual void setScope(CIMName); virtual void setCIMOMHandle(CIMOMHandle&); virtual void clearInstance(); virtual Boolean loadInstance(const CIMInstance&); virtual Boolean createInstance(const OperationContext&); virtual Boolean modifyInstance(const OperationContext&); virtual Boolean deleteInstance(const OperationContext&); virtual Boolean validateInstance(); virtual Boolean getStatistics(CIMProperty&) const; virtual CIMInstance getStatistics() const; virtual void setStatistics(CIMInstance&); virtual Boolean getManifestCollection(CIMProperty&) const; virtual CIMInstance getManifestCollection() const; virtual void setManifestCollection(CIMInstance&); private: CIMName currentScope; CIMOMHandle _cimomHandle; CIMInstance _statistics; CIMInstance _manifestCollection; # include "UNIX_AssociatedFileSystemStatisticsManifestCollectionPrivate.h" }; #endif /* UNIX_ASSOCIATEDFILESYSTEMSTATISTICSMANIFESTCOLLECTION */
[ "brunolauze@msn.com" ]
brunolauze@msn.com
e443fea89a593fb6f7fae7ab997365e2cbcb4aec
45184fc098d7e0fa4b22a5e0b086ebae8d7e5fb2
/QT/RegularExpressionToDeterministicAutomaton/Z1_functionstest.cpp
e4db98a9afc2b3c954d6dfcb2361116a26520547
[]
no_license
Noodle96/EstructuraDeDatos
8004061083b7cf49e4c1f35873b3c91ee62e3f64
d87e6f0327d0de61f4d2be1be255ed58779f40b4
refs/heads/master
2020-03-27T08:10:28.188886
2019-06-28T23:25:24
2019-06-28T23:25:24
146,227,269
0
1
null
null
null
null
UTF-8
C++
false
false
6,737
cpp
#include "functionsTest.h" void concatenate( NFA<std::string,std::string> &nfa1, NFA<std::string,std::string> &nfa2, NFA<std::string,std::string> &nfa3 ){ //pasando los estados de nf1 a nf3 for(auto it = nfa1.States.begin() ; it != nfa1.States.end(); it++){ nfa3.addState((*it).first ); } //pasando los estados de nf2 a nf3 for(auto it = nfa2.States.begin() ; it != nfa2.States.end(); it++){ nfa3.addState((*it).first ); } //psando el alfabeto de nf1 a nf3 for(auto it = nfa1.Alphabets.begin() ; it != nfa1.Alphabets.end() ; it++){ nfa3.addAlphabet((*it).first); } //pasando el alfabeto de nf2 a nf3 for(auto it = nfa2.Alphabets.begin() ; it != nfa2.Alphabets.end() ; it++ ){ nfa3.addAlphabet((*it).first); } //seteando el estado inicial del nf3(nuevo ya concatenado) nfa3.setInitialState(nfa1.InitialState); //agregando los estados finales a nf3 for(auto it = nfa2.FinalStates.begin() ; it != nfa2.FinalStates.end() ; it++ ){ nfa3.addFinalState((*it).first); } //recorriendo la matriz de transicion de nf1 y agregando a la nfa3 //example [s0][a]={s1,s2,s3} for(auto it = nfa1.M.begin() ; it != nfa1.M.end() ; it++){ // cout << (*it).first => s0 for(auto et = (*it).second.begin() ; et != (*it).second.end() ; et++){ //cout << (*et).first => a for(auto ot = (*et).second.begin() ; ot != (*et).second.end(); ot++){ //cout << (*ot) << ", "; => {s1,s2,s3} nfa3.FillMatrix((*it).first, (*et).first, (*ot)); } } } //recorriendo la matriz de transicion de nf2 y agregando a la nfa3 //example [s0][a]={s1,s2,s3} for(auto it = nfa2.M.begin() ; it != nfa2.M.end() ; it++){ // cout << (*it).first => s0 for(auto et = (*it).second.begin() ; et != (*it).second.end() ; et++){ //cout << (*et).first => a for(auto ot = (*et).second.begin() ; ot != (*et).second.end(); ot++){ //cout << (*ot) << ", "; => {s1,s2,s3} nfa3.FillMatrix((*it).first, (*et).first, (*ot)); } } } for(auto it = nfa1.FinalStates.begin() ; it != nfa1.FinalStates.end() ; it++){ nfa3.FillMatrix((*it).first,"E", nfa2.InitialState); } } void Union(NFA<std::string,std::string> &nfa1, NFA<std::string,std::string> &nfa2 , NFA<std::string,std::string> &nfa3){ //pasando los estados de nfa1 a nfa3 for(auto it = nfa1.States.begin(); it != nfa1.States.end() ; it++){ nfa3.addState((*it).first); } //pasando los estados de nfa2 a nfa3 for(auto it = nfa2.States.begin(); it != nfa2.States.end() ; it++){ nfa3.addState((*it).first); } //agregando el alphabeto de nfa1 a nfa3 for(auto it = nfa1.Alphabets.begin() ; it != nfa1.Alphabets.end(); it++){ nfa3.addAlphabet((*it).first); } //agregando el alphabeto de nfa2 a nfa3 for(auto it = nfa2.Alphabets.begin() ; it != nfa2.Alphabets.end(); it++){ nfa3.addAlphabet((*it).first); } //pasando los estados de aceptacion de nfa1 a nfa3 for(auto it = nfa1.FinalStates.begin() ; it != nfa1.FinalStates.end() ; it++){ nfa3.addFinalState((*it).first); } //pasando los estados de aceptacion de nfa2 a nfa3 for(auto it = nfa2.FinalStates.begin() ; it != nfa2.FinalStates.end(); it++){ nfa3.addFinalState((*it).first); } //creando el nuevo estado inicial State s; std::string data = s.getState(); nfa3.setInitialState(data); nfa3.addState(data); //entrando a la matriz de transicion de nfa1 y pasarsela a nfa3 //example [s0][a]={s1,s2,s3} for(auto it = nfa1.M.begin() ; it != nfa1.M.end(); it++){ //cout << (*it).first // s0 for(auto et = (*it).second.begin() ;et != (*it).second.end() ; et++){ //cout << (*et).first // a for(auto ot = (*et).second.begin() ; ot != (*et).second.end() ; ot++){ //cout << (*ot) // s1,s2,s3 nfa3.FillMatrix((*it).first , (*et).first , (*ot) ); } } } //entrando a la matriz de transicion de nfa2 y pasarsela a nfa3 //example [s0][a]={s1,s2,s3} for(auto it = nfa2.M.begin() ; it != nfa2.M.end(); it++){ //cout << (*it).first // s0 for(auto et = (*it).second.begin() ;et != (*it).second.end() ; et++){ //cout << (*et).first // a for(auto ot = (*et).second.begin() ; ot != (*et).second.end() ; ot++){ //cout << (*ot) // s1,s2,s3 nfa3.FillMatrix((*it).first , (*et).first , (*ot) ); } } } //seteando las uevas transiciones de el nuevo estado hacia los antiguos estados iniciales de nfa1 y nfa2 nfa3.FillMatrix( data, "E" ,nfa1.InitialState); nfa3.FillMatrix(data, "E", nfa2.InitialState); } void estrella(NFA<std::string,std::string> &nfa1, NFA<std::string,std::string> &nfa2){ //pasando los estados de nfa1 a nfa2 for(auto it = nfa1.States.begin() ; it != nfa1.States.end(); it++){ nfa2.addState((*it).first); } //agregando el alfabeto de nfa1 a nfa2 for(auto it = nfa1.Alphabets.begin() ;it != nfa1.Alphabets.end() ; it++){ nfa2.addAlphabet((*it).first); } //agregando los estados ade aceptacion de nfa1 a nfa2 for(auto it = nfa1.FinalStates.begin() ; it != nfa1.FinalStates.end(); it++){ nfa2.addFinalState((*it).first); } //seteando el nuevo estado inicial y final a la vez State s; std::string data = s.getState(); nfa2.addState(data); nfa2.setInitialState(data); nfa2.addFinalState(data); //creando las nuevas transiciones de el nuevo estado inicial-final hacia el antiguo estado inicial nfa2.FillMatrix(data,"E",nfa1.InitialState); //entrando a la matriz de transicion de nfa y pasandosela a nfa2 //[s3][b]={s1,s2,s4,s3} for(auto it = nfa1.M.begin() ; it != nfa1.M.end(); it++){ //cout << (*it).first // s3 for(auto et = (*it).second.begin() ; et != (*it).second.end() ; et++){ //cout << (*et).first //b for(auto ot = (*et).second.begin() ; ot != (*et).second.end(); ot++){ //cout << (*ot) // s1,s2,ss4,s3 nfa2.FillMatrix((*it).first , (*et).first, (*ot) ); } } } // de los estados finales ir con la transicion e hacia el antiguo estado incial for(auto it = nfa1.FinalStates.begin(); it != nfa1.FinalStates.end(); it++){ nfa2.FillMatrix( (*it).first, "E", nfa1.InitialState ); } } //end functionstest.cpp
[ "jorgealfredomarino2@gmail.com" ]
jorgealfredomarino2@gmail.com
ac1087be6197f3e170371ae6682ccd5cb0658753
257e3d1bc2f1c91b6f8e0e01e709d855c9a3718d
/core/odeque.h
2d5b5b418df09558d209f89853c6d7cd146fbf34
[ "MIT" ]
permissive
bson/enetcore
8e10f4ac3acce20ae4011a1583eab62dbb316ccf
d68184a22fc4b95a2c744cb14bbf5322c1ccd2af
refs/heads/master
2022-11-28T12:43:05.613044
2022-06-19T06:45:43
2022-06-19T06:45:43
66,692,175
0
0
MIT
2018-04-11T06:26:18
2016-08-27T02:48:20
C++
UTF-8
C++
false
false
2,850
h
// Copyright (c) 2018-2021 Jan Brittenson // See LICENSE for details. #ifndef __ODEQUE_H__ #define __ODEQUE_H__ // Ordered deque - basically a priority queue // The only way to add items is using Insert() // Like STL, requires T to implement bool operator>(const T&) const // Greater items insert towards the back, lesser items towards the front. // Equal items sort by insertion order. // Safe only for standard layout types. template <typename T, OrderFunc Order = T::Order> class ODeque { OVector<T,Order> _v; uint _head; // Start of "ring" typedef ODeque<T,Order> Self; public: ODeque() { _head = 0; } ODeque(uint reserve) : _v(reserve) { _head = 0; } ODeque(const Self& arg) : _v(arg._v) { _head = arg._head; } virtual ~ODeque() { }; uint Headroom() const { return _v.Headroom() + _head; } void Compact() { if (_head) { if (_head < _v.Size()) move(&_v[0], _v + _head, _v.Size() - _head); _v.SetSize(_v.Size() - _head); _head = 0; } } void SetAutoResize(bool flag) { _v.SetAutoResize(flag); } uint GetReserve() const { return _v.GetReserve(); } void Reserve(uint new_size) { AutoCompact(); _v.Reserve(new_size + _head); } void AutoCompact() { if (_v.GetReserve() >= 64 && _head > _v.Size() / 2) Compact(); } uint Size() const { return _v.Size() - _head; } void Clear() { _v.Clear(); _head = 0; } bool Empty() const { return !Size(); } T& Front() { assert_bounds(_v.Size() > _head); return _v[_head]; } const T& Front() const { assert_bounds(_v.Size() > _head); return _v[_head]; } T& Back() { return _v.Back(); } const T& Back() const { return _v.Back(); } T& operator[](uint arg) { return _v[_head + arg]; } const T& operator[](uint arg) const { return _v[_head + arg]; } T* operator+(uint arg) { return _v + (_head + arg); } const T* operator+(uint arg) const { return _v + (_head + arg); } // Note: we only compact on insertion, never on erase. This is // because the intended use for this structure is for a task run // queue. We don't want a task to start right off the bat with a // housekeeping chore since that would add a random latency. // Instead we amortize all the housekeeping during insertion. uint Insert(const T& arg) { uint pos = _v.FindGreaterThan(arg, _head); assert(pos >= _head); pos -= _head; if (!pos && _head) { _v[--_head] = arg; return _head; } _v.InsertInternal(pos + _head) = arg; AutoCompact(); return pos; } void Erase(uint pos, uint num = 1) { if (!pos) { assert_bounds(_head + num <= _v.Size()); _head += num; } else _v.Erase(_head + pos, num); } void PopFront() { Erase(0, 1); } void PopBack() { Erase(Size() - 1, 1); } uint Find(const T& arg) { const uint pos = _v.Find(arg, _head); if (pos == NOT_FOUND) return pos; assert(pos >= _head); return pos - _head; } }; #endif // __ODEQUE_H__
[ "bson@rockgarden.net" ]
bson@rockgarden.net
8cb505fd8d37b464edbf26db788725050c5effcc
86196410ce9fc5764c95c8202bf11a30ae0ac8bd
/QTCube/gui/mouse_region.h
dd3359dcb97991a29aca60589e30d7c0999bdb7c
[]
no_license
scc-gatech/born-mono
3af90cde4547e57e9dacd1d12859918f1b0d5926
3749665a2cf07409803b92d963cd53b53c01edd9
refs/heads/master
2021-08-12T00:33:30.482707
2017-11-14T07:15:54
2017-11-14T07:15:54
106,741,008
0
0
null
null
null
null
UTF-8
C++
false
false
1,603
h
#ifndef MOUSE_REGION_H #define MOUSE_REGION_H 1 #include "mouse_func.h" class mouse_region: public SEP::mouse_func{ public: mouse_region(); virtual void r_mouse_d(std::vector<std::shared_ptr<SEP::slice>> slices, int islice, int ix, int iy, std::shared_ptr<SEP::orient_cube>pos, std::vector<QString> *com, std::shared_ptr<SEP::draw_other>draw_o); virtual void r_mouse_m(std::vector<std::shared_ptr<SEP::slice>> slices, int islice, int ix, int iy, std::shared_ptr<SEP::orient_cube>pos, std::vector<QString> *com, std::shared_ptr<SEP::draw_other>draw_o); virtual void r_mouse_r(std::vector<std::shared_ptr<SEP::slice>> slices, int islice, int ix, int iy, std::shared_ptr<SEP::orient_cube>pos, std::vector<QString> *com, std::shared_ptr<SEP::draw_other>draw_o); virtual void m_mouse_r(std::vector<std::shared_ptr<SEP::slice>> slices, int islice, int ix, int iy, std::shared_ptr<SEP::orient_cube>pos, std::vector<QString> *com, std::shared_ptr<SEP::draw_other>draw_o); virtual void l_mouse_d(std::vector<std::shared_ptr<SEP::slice>> slices, int islice, int ix, int iy, std::shared_ptr<SEP::orient_cube>pos, std::vector<QString> *com, std::shared_ptr<SEP::draw_other>draw_o); virtual void l_mouse_m(std::vector<std::shared_ptr<SEP::slice>> slices, int islice, int ix, int iy, std::shared_ptr<SEP::orient_cube>pos, std::vector<QString> *com, std::shared_ptr<SEP::draw_other>draw_o); virtual void l_mouse_r(std::vector<std::shared_ptr<SEP::slice>> slices, int islice, int ix, int iy, std::shared_ptr<SEP::orient_cube>pos, std::vector<QString> *com, std::shared_ptr<SEP::draw_other>draw_o); }; #endif
[ "andy@ramblin.cc.gt.atl.ga.us" ]
andy@ramblin.cc.gt.atl.ga.us
0d68c8d5a09b3e0abb822b5dcf05f8694c425fde
1b7daae23b2bd3baa72cf9711be00699dc387db3
/src/leveldb/util/env.cc
62e3aff88efd4106eadde49f0f4454cf1a0a101d
[ "MIT", "LicenseRef-scancode-generic-cla", "BSD-3-Clause" ]
permissive
hotion/BitCoinCppChinese
f48894beff6e652031f18b58181592af1168ed40
76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a
refs/heads/master
2020-04-18T06:33:11.575445
2019-01-24T02:02:27
2019-01-24T02:02:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,543
cc
//此源码被清华学神尹成大魔王专业翻译分析并修改 //尹成QQ77025077 //尹成微信18510341407 //尹成所在QQ群721929980 //尹成邮箱 yinc13@mails.tsinghua.edu.cn //尹成毕业于清华大学,微软区块链领域全球最有价值专家 //https://mvp.microsoft.com/zh-cn/PublicProfile/4033620 //版权所有(c)2011 LevelDB作者。版权所有。 //此源代码的使用受可以 //在许可证文件中找到。有关参与者的名称,请参阅作者文件。 #include "leveldb/env.h" namespace leveldb { Env::~Env() { } Status Env::NewAppendableFile(const std::string& fname, WritableFile** result) { return Status::NotSupported("NewAppendableFile", fname); } SequentialFile::~SequentialFile() { } RandomAccessFile::~RandomAccessFile() { } WritableFile::~WritableFile() { } Logger::~Logger() { } FileLock::~FileLock() { } void Log(Logger* info_log, const char* format, ...) { if (info_log != NULL) { va_list ap; va_start(ap, format); info_log->Logv(format, ap); va_end(ap); } } static Status DoWriteStringToFile(Env* env, const Slice& data, const std::string& fname, bool should_sync) { WritableFile* file; Status s = env->NewWritableFile(fname, &file); if (!s.ok()) { return s; } s = file->Append(data); if (s.ok() && should_sync) { s = file->Sync(); } if (s.ok()) { s = file->Close(); } delete file; //如果不关闭上面的,将自动关闭 if (!s.ok()) { env->DeleteFile(fname); } return s; } Status WriteStringToFile(Env* env, const Slice& data, const std::string& fname) { return DoWriteStringToFile(env, data, fname, false); } Status WriteStringToFileSync(Env* env, const Slice& data, const std::string& fname) { return DoWriteStringToFile(env, data, fname, true); } Status ReadFileToString(Env* env, const std::string& fname, std::string* data) { data->clear(); SequentialFile* file; Status s = env->NewSequentialFile(fname, &file); if (!s.ok()) { return s; } static const int kBufferSize = 8192; char* space = new char[kBufferSize]; while (true) { Slice fragment; s = file->Read(kBufferSize, &fragment, space); if (!s.ok()) { break; } data->append(fragment.data(), fragment.size()); if (fragment.empty()) { break; } } delete[] space; delete file; return s; } EnvWrapper::~EnvWrapper() { } } //命名空间级别数据库
[ "openaichain" ]
openaichain
f579fc68bff3a132876bfeecf4c988be0d5f1967
2cf838b54b556987cfc49f42935f8aa7563ea1f4
/aws-cpp-sdk-customer-profiles/source/model/ListProfileObjectsResult.cpp
44b795a80dc8f29edcc33d86733d5ef7fe33c27e
[ "MIT", "Apache-2.0", "JSON" ]
permissive
QPC-database/aws-sdk-cpp
d11e9f0ff6958c64e793c87a49f1e034813dac32
9f83105f7e07fe04380232981ab073c247d6fc85
refs/heads/main
2023-06-14T17:41:04.817304
2021-07-09T20:28:20
2021-07-09T20:28:20
384,714,703
1
0
Apache-2.0
2021-07-10T14:16:41
2021-07-10T14:16:41
null
UTF-8
C++
false
false
1,270
cpp
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/customer-profiles/model/ListProfileObjectsResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::CustomerProfiles::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; ListProfileObjectsResult::ListProfileObjectsResult() { } ListProfileObjectsResult::ListProfileObjectsResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } ListProfileObjectsResult& ListProfileObjectsResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("Items")) { Array<JsonView> itemsJsonList = jsonValue.GetArray("Items"); for(unsigned itemsIndex = 0; itemsIndex < itemsJsonList.GetLength(); ++itemsIndex) { m_items.push_back(itemsJsonList[itemsIndex].AsObject()); } } if(jsonValue.ValueExists("NextToken")) { m_nextToken = jsonValue.GetString("NextToken"); } return *this; }
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
49aa9d2fcf9df65ef217da4cbd161f877ed0b3d4
24bc4990e9d0bef6a42a6f86dc783785b10dbd42
/chrome/browser/hid/hid_pinned_notification_unittest.cc
d2875207d1a17ba6e104f26f467a01e7397d9039
[ "BSD-3-Clause" ]
permissive
nwjs/chromium.src
7736ce86a9a0b810449a3b80a4af15de9ef9115d
454f26d09b2f6204c096b47f778705eab1e3ba46
refs/heads/nw75
2023-08-31T08:01:39.796085
2023-04-19T17:25:53
2023-04-19T17:25:53
50,512,158
161
201
BSD-3-Clause
2023-05-08T03:19:09
2016-01-27T14:17:03
null
UTF-8
C++
false
false
4,070
cc
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/hid/hid_pinned_notification.h" #include "chrome/browser/hid/hid_connection_tracker.h" #include "chrome/browser/hid/hid_connection_tracker_factory.h" #include "chrome/browser/hid/hid_system_tray_icon_unittest.h" #include "chrome/browser/notifications/notification_display_service_tester.h" #include "chrome/browser/notifications/system_notification_helper.h" #include "chrome/test/base/testing_browser_process.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" class HidPinnedNotificationTest : public HidSystemTrayIconTestBase { public: void SetUp() override { HidSystemTrayIconTestBase::SetUp(); TestingBrowserProcess::GetGlobal()->SetSystemNotificationHelper( std::make_unique<SystemNotificationHelper>()); display_service_ = std::make_unique<NotificationDisplayServiceTester>(/*profile=*/nullptr); } void TearDown() override { TestingBrowserProcess::GetGlobal()->SetSystemNotificationHelper(nullptr); HidSystemTrayIconTestBase::TearDown(); } void CheckIcon(const std::vector<std::pair<Profile*, size_t>>& profile_connection_counts) override { EXPECT_FALSE(display_service_ ->GetDisplayedNotificationsForType( NotificationHandler::Type::TRANSIENT) .empty()); // Check each button label and behavior of clicking the button. for (const auto& pair : profile_connection_counts) { auto* hid_connection_tracker = static_cast<MockHidConnectionTracker*>( HidConnectionTrackerFactory::GetForProfile(pair.first, /*create=*/false)); EXPECT_TRUE(hid_connection_tracker); auto maybe_notification = display_service_->GetNotification( HidPinnedNotification::GetNotificationId(pair.first)); ASSERT_TRUE(maybe_notification); EXPECT_EQ(maybe_notification->title(), GetExpectedIconTooltip( /*num_devices=*/pair.second)); EXPECT_EQ(maybe_notification->rich_notification_data().buttons.size(), 1u); EXPECT_EQ(maybe_notification->rich_notification_data().buttons[0].title, GetExpectedButtonTitleForProfile(pair.first)); EXPECT_TRUE(maybe_notification->delegate()); EXPECT_CALL(*hid_connection_tracker, ShowHidContentSettingsExceptions()); SimulateButtonClick(pair.first); } } void CheckIconHidden() override { EXPECT_TRUE(display_service_ ->GetDisplayedNotificationsForType( NotificationHandler::Type::TRANSIENT) .empty()); } private: void SimulateButtonClick(Profile* profile) { display_service_->SimulateClick( NotificationHandler::Type::TRANSIENT, HidPinnedNotification::GetNotificationId(profile), /*action_index=*/0, /*reply=*/absl::nullopt); } std::unique_ptr<NotificationDisplayServiceTester> display_service_; }; TEST_F(HidPinnedNotificationTest, SingleProfileEmptyName) { // Current TestingProfileManager can't support empty profile name as it uses // profile name for profile path. Passing empty would result in a failure in // ProfileManager::IsAllowedProfilePath(). Changing the way // TestingProfileManager creating profile path like adding "profile" prefix // doesn't work either as some tests are written in a way that takes // assumption of testing profile path pattern. Hence it creates testing // profile with non-empty name and then change the profile name to empty which // can still achieve what this file wants to test. profile()->set_profile_name(""); TestSingleProfile(); } TEST_F(HidPinnedNotificationTest, SingleProfileNonEmptyName) { TestSingleProfile(); } TEST_F(HidPinnedNotificationTest, MultipleProfiles) { TestMultipleProfiles(); }
[ "roger@nwjs.io" ]
roger@nwjs.io
83da7e3044a735245c969d10994b5759797bd3ee
2a76efae74308f338e45b449002332a0cd8c16d7
/Coin3D/include/Inventor/misc/SoProto.h
dfdc093d5adda947387f67ae5f273d694c4a2dbb
[]
no_license
misrayazgan/Digital-Geometry-Processing
5e687646aa08c95856fef06d5fd2f13bd5f6f934
9237f84ec783a1cdfdbadea7b55f4cfe99e32996
refs/heads/master
2022-11-20T04:04:54.070115
2020-07-19T16:41:44
2020-07-19T16:41:44
280,908,013
0
0
null
null
null
null
UTF-8
C++
false
false
3,215
h
#ifndef COIN_SOPROTO_H #define COIN_SOPROTO_H /**************************************************************************\ * * This file is part of the Coin 3D visualization library. * Copyright (C) 1998-2005 by Systems in Motion. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * ("GPL") version 2 as published by the Free Software Foundation. * See the file LICENSE.GPL at the root directory of this source * distribution for additional information about the GNU GPL. * * For using Coin with software that can not be combined with the GNU * GPL, and for taking advantage of the additional benefits of our * support services, please contact Systems in Motion about acquiring * a Coin Professional Edition License. * * See <URL:http://www.coin3d.org/> for more information. * * Systems in Motion, Postboks 1283, Pirsenteret, 7462 Trondheim, NORWAY. * <URL:http://www.sim.no/>. * \**************************************************************************/ #include <Inventor/nodes/SoNode.h> class SoProto; class SoInput; class SoProtoInstance; class SoProtoP; typedef SoProto * SoFetchExternProtoCB(SoInput * in, const SbString * urls, const int numurls, void * closure); // We need to inherit SoNode to be able to insert the PROTO definition // into the scene graph. class COIN_DLL_API SoProto : public SoNode { public: SoProto(const SbBool externproto = FALSE); static void setFetchExternProtoCallback(SoFetchExternProtoCB * cb, void * closure); virtual SoType getTypeId(void) const; static SoType getClassTypeId(void); static SoProto * findProto(const SbName & name); static void initClass(void); SoProtoInstance * createProtoInstance(void); void addISReference(SoNode * container, const SbName & fieldname, const SbName & interfacename); SbName findISReference(const SoFieldContainer * container, const SbName & fieldname); void addReference(const SbName & name, SoBase * base); void removeReference(const SbName & name); SoBase * findReference(const SbName & name) const; void addRoute(const SbName & fromnode, const SbName & fromfield, const SbName & tonode, const SbName & tofield); SbName getProtoName(void) const; virtual SbBool readInstance(SoInput * in, unsigned short flags); virtual void write(SoWriteAction * action); protected: virtual ~SoProto(); virtual void destroy(void); private: SbBool writeInterface(SoOutput * out); SbBool writeDefinition(SoWriteAction * action); SbBool readInterface(SoInput * in); SbBool readDefinition(SoInput * in); SbBool writeURLs(SoOutput * out); SoProtoP * pimpl; friend class SoProtoP; SbBool setupExtern(SoInput * in, SoProto * externproto); SoNode * createInstanceRoot(SoProtoInstance * inst) const; void connectISRefs(SoProtoInstance * inst, SoNode * src, SoNode * dst) const; }; #endif // !COIN_SOPROTO_H
[ "e2099489@ceng.metu.edu.tr" ]
e2099489@ceng.metu.edu.tr
dbc60bdbd23b9a367281f3183caa62d92da5ca93
198bdabbc684213316f5e74621b2ab56b981a651
/Hafta 6/hafta6gorev/Untitled3.cpp
3d9ec1b4b4747f5e40dd7ba22ae147861d00cf5e
[]
no_license
MertD014/DeneyapCPP
7d1ae8cd17114cde9daa4d3378d86bd3474aa232
4d6214fcf5ecf24713ceee89e4ea4b6b0da00474
refs/heads/main
2023-07-08T17:24:04.657850
2021-08-07T10:30:19
2021-08-07T10:30:19
376,350,731
0
0
null
null
null
null
UTF-8
C++
false
false
487
cpp
/* Deneyap C++ Programlama 19/06/2021 Diziler Uygulama 2(Grup 2) https://tr.padlet.com/iismailersin/m9z1toj4bemxm0tk dizideki en kucuk eleman ve indisini bulma */ #include <bits/stdc++.h> using namespace std; int n,pos=-1,mn=INT_MAX; int main(){ cout<<"Eleman sayisini giriniz:"; cin>>n; int d[n]; for(int i=0;i<n;i++){ cin>>d[i]; if(d[i]<mn){ mn=d[i]; pos=i; } } cout<<"En kucuk eleman "<<pos+1<<". siradaki "<<mn; return 0; }
[ "noreply@github.com" ]
noreply@github.com
4a9fbbc2141e977e7f44e3dbfe180b9602486953
985c93e625b99e18937725c7352b07da85ab7c42
/slaves/slave/slave.ino
1752af952e8bd9e0a3f87774f46ff00aecea7276
[]
no_license
nerld/nerld_arduino
f8b83378cfa0266b7614fe948cbf092151a5596a
b457caf5ebb329a1f0076f502d7109acb389b51b
refs/heads/master
2021-01-13T02:30:10.870784
2015-06-01T03:45:58
2015-06-01T03:45:58
30,216,062
0
0
null
null
null
null
UTF-8
C++
false
false
2,435
ino
// Wire Slave Receiver #include "NerldProtocol.h" #include <Wire.h> NerldProtocol nerldProtocol = NerldProtocol(); int DEFAULT_ADDR = 99; int ADDR = NULL; void setup() { Serial.begin(9600); Serial.println("INFO::setup: Initialising Basic Slave."); Wire.begin(DEFAULT_ADDR); while (ADDR == NULL) { int newAddress = nerldProtocol.requestAddresssFromMaster(); ADDR = newAddress; delay(1000); } Serial.print("INFO::setup: Setting the slave address to "); Serial.println(ADDR); TWAR = ADDR << 1; Wire.onRequest(healthCheck); Wire.onReceive(receiveCommand); Serial.println("INFO::setup: Registering the address with the master."); nerldProtocol.sendCommandToMaster(ADDR, 0, 0); Serial.println("INFO::setup: Successfully registered."); Serial.println("INFO::setup: Basic Slave initialised."); } void loop() { delay(1000); } void healthCheck() { Serial.println("INFO::healthCheck: Called."); Wire.write("1"); Serial.println("INFO::healthCheck: Done."); } void receiveCommand(int numOfBytes) { Serial.println("INFO::receiveCommand: Command received"); int i = 0; while(Wire.available() && i < numOfBytes) { char c = Wire.read(); Serial.println(c); i++; } } void executeCommand(int address, int command, String value) { switch (command) { case 0: Serial.println("INFO::executeCommand: setPinMode called."); break; case 1: Serial.println("INFO::executeCommand: digitalWritePin called."); break; default: Serial.println("INFO::executeCommand: invalid command called."); break; } } int setPinMode(int pin, String mode) { if (validateDigitalPin(pin)) { if (mode == "INPUT") { pinMode(pin, INPUT); return INPUT; } else if (mode == "OUTPUT") { pinMode(pin, OUTPUT); return OUTPUT; } } } int digitalWritePin(int pin, String value) { if (validateDigitalPin(pin)) { if (value == "HIGH") { digitalWrite(pin, HIGH); return HIGH; } else if (value == "LOW") { digitalWrite(pin, LOW); return LOW; } } } bool validateDigitalPin(int pin) { return (pin >= 0 && pin <= 13); } int readDigitalPin(int pin) { return digitalRead(pin); } // analog read float readAnalogPin(int pin) { return analogRead(pin); } // analog write float writeAnalogPin(int pin, float value) { analogWrite(pin, value); return value; }
[ "khanh@intersect.org.au" ]
khanh@intersect.org.au
e437ff5e9158690df536be773b33bef0c4d028bc
c42ad89034584025c83f3a871a9ce8a82d74666a
/Projects/LiDar/loam_velodyne/ReadMe_and_supplementary_materials/original_src/laserMapping.cpp
d1de52c23732198d0359add31d9245c8a8a2dba0
[ "BSD-3-Clause" ]
permissive
aztrimble/me696_marineRobotics
1849921a34a802ea8f8339df40e0d3962340ffcd
3db3b7e661da8701e8a8e731e0a108bf7f3684b6
refs/heads/main
2023-03-26T03:34:34.172290
2023-03-08T01:26:42
2023-03-08T01:26:42
148,103,216
3
1
null
2023-03-05T06:06:46
2018-09-10T05:24:35
JavaScript
UTF-8
C++
false
false
58,739
cpp
00001 #include <math.h> 00002 #include <time.h> 00003 #include <stdio.h> 00004 #include <stdlib.h> 00005 #include <ros/ros.h> 00006 00007 #include <nav_msgs/Odometry.h> 00008 #include <sensor_msgs/Imu.h> 00009 #include <sensor_msgs/PointCloud2.h> 00010 00011 #include <tf/transform_datatypes.h> 00012 #include <tf/transform_broadcaster.h> 00013 00014 #include <opencv/cv.h> 00015 #include <opencv2/highgui/highgui.hpp> 00016 00017 #include <pcl_conversions/pcl_conversions.h> 00018 #include <pcl/point_cloud.h> 00019 #include <pcl/point_types.h> 00020 #include <pcl/filters/voxel_grid.h> 00021 #include <pcl/kdtree/kdtree_flann.h> 00022 00023 const double PI = 3.1415926; 00024 00025 const float scanPeriod = 0.1; 00026 00027 const int stackFrameNum = 1; 00028 const int mapFrameNum = 5; 00029 00030 double timeLaserCloudCornerLast = 0; 00031 double timeLaserCloudSurfLast = 0; 00032 double timeLaserCloudFullRes = 0; 00033 double timeLaserOdometry = 0; 00034 00035 bool newLaserCloudCornerLast = false; 00036 bool newLaserCloudSurfLast = false; 00037 bool newLaserCloudFullRes = false; 00038 bool newLaserOdometry = false; 00039 00040 int laserCloudCenWidth = 10; 00041 int laserCloudCenHeight = 5; 00042 int laserCloudCenDepth = 10; 00043 const int laserCloudWidth = 21; 00044 const int laserCloudHeight = 11; 00045 const int laserCloudDepth = 21; 00046 const int laserCloudNum = laserCloudWidth * laserCloudHeight * laserCloudDepth; 00047 00048 int laserCloudValidInd[125]; 00049 int laserCloudSurroundInd[125]; 00050 00051 pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudCornerLast(new pcl::PointCloud<pcl::PointXYZI>()); 00052 pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudSurfLast(new pcl::PointCloud<pcl::PointXYZI>()); 00053 pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudCornerStack(new pcl::PointCloud<pcl::PointXYZI>()); 00054 pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudSurfStack(new pcl::PointCloud<pcl::PointXYZI>()); 00055 pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudCornerStack2(new pcl::PointCloud<pcl::PointXYZI>()); 00056 pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudSurfStack2(new pcl::PointCloud<pcl::PointXYZI>()); 00057 pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudOri(new pcl::PointCloud<pcl::PointXYZI>()); 00058 //pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudSel(new pcl::PointCloud<pcl::PointXYZI>()); 00059 //pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudCorr(new pcl::PointCloud<pcl::PointXYZI>()); 00060 //pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudProj(new pcl::PointCloud<pcl::PointXYZI>()); 00061 pcl::PointCloud<pcl::PointXYZI>::Ptr coeffSel(new pcl::PointCloud<pcl::PointXYZI>()); 00062 pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudSurround(new pcl::PointCloud<pcl::PointXYZI>()); 00063 pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudSurround2(new pcl::PointCloud<pcl::PointXYZI>()); 00064 pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudCornerFromMap(new pcl::PointCloud<pcl::PointXYZI>()); 00065 pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudSurfFromMap(new pcl::PointCloud<pcl::PointXYZI>()); 00066 pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudFullRes(new pcl::PointCloud<pcl::PointXYZI>()); 00067 pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudCornerArray[laserCloudNum]; 00068 pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudSurfArray[laserCloudNum]; 00069 pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudCornerArray2[laserCloudNum]; 00070 pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudSurfArray2[laserCloudNum]; 00071 00072 pcl::KdTreeFLANN<pcl::PointXYZI>::Ptr kdtreeCornerFromMap(new pcl::KdTreeFLANN<pcl::PointXYZI>()); 00073 pcl::KdTreeFLANN<pcl::PointXYZI>::Ptr kdtreeSurfFromMap(new pcl::KdTreeFLANN<pcl::PointXYZI>()); 00074 00075 float transformSum[6] = {0}; 00076 float transformIncre[6] = {0}; 00077 float transformTobeMapped[6] = {0}; 00078 float transformBefMapped[6] = {0}; 00079 float transformAftMapped[6] = {0}; 00080 00081 int imuPointerFront = 0; 00082 int imuPointerLast = -1; 00083 const int imuQueLength = 200; 00084 00085 double imuTime[imuQueLength] = {0}; 00086 float imuRoll[imuQueLength] = {0}; 00087 float imuPitch[imuQueLength] = {0}; 00088 00089 void transformAssociateToMap() 00090 { 00091 float x1 = cos(transformSum[1]) * (transformBefMapped[3] - transformSum[3]) 00092 - sin(transformSum[1]) * (transformBefMapped[5] - transformSum[5]); 00093 float y1 = transformBefMapped[4] - transformSum[4]; 00094 float z1 = sin(transformSum[1]) * (transformBefMapped[3] - transformSum[3]) 00095 + cos(transformSum[1]) * (transformBefMapped[5] - transformSum[5]); 00096 00097 float x2 = x1; 00098 float y2 = cos(transformSum[0]) * y1 + sin(transformSum[0]) * z1; 00099 float z2 = -sin(transformSum[0]) * y1 + cos(transformSum[0]) * z1; 00100 00101 transformIncre[3] = cos(transformSum[2]) * x2 + sin(transformSum[2]) * y2; 00102 transformIncre[4] = -sin(transformSum[2]) * x2 + cos(transformSum[2]) * y2; 00103 transformIncre[5] = z2; 00104 00105 float sbcx = sin(transformSum[0]); 00106 float cbcx = cos(transformSum[0]); 00107 float sbcy = sin(transformSum[1]); 00108 float cbcy = cos(transformSum[1]); 00109 float sbcz = sin(transformSum[2]); 00110 float cbcz = cos(transformSum[2]); 00111 00112 float sblx = sin(transformBefMapped[0]); 00113 float cblx = cos(transformBefMapped[0]); 00114 float sbly = sin(transformBefMapped[1]); 00115 float cbly = cos(transformBefMapped[1]); 00116 float sblz = sin(transformBefMapped[2]); 00117 float cblz = cos(transformBefMapped[2]); 00118 00119 float salx = sin(transformAftMapped[0]); 00120 float calx = cos(transformAftMapped[0]); 00121 float saly = sin(transformAftMapped[1]); 00122 float caly = cos(transformAftMapped[1]); 00123 float salz = sin(transformAftMapped[2]); 00124 float calz = cos(transformAftMapped[2]); 00125 00126 float srx = -sbcx*(salx*sblx + calx*caly*cblx*cbly + calx*cblx*saly*sbly) 00127 - cbcx*cbcz*(calx*saly*(cbly*sblz - cblz*sblx*sbly) 00128 - calx*caly*(sbly*sblz + cbly*cblz*sblx) + cblx*cblz*salx) 00129 - cbcx*sbcz*(calx*caly*(cblz*sbly - cbly*sblx*sblz) 00130 - calx*saly*(cbly*cblz + sblx*sbly*sblz) + cblx*salx*sblz); 00131 transformTobeMapped[0] = -asin(srx); 00132 00133 float srycrx = (cbcy*sbcz - cbcz*sbcx*sbcy)*(calx*saly*(cbly*sblz - cblz*sblx*sbly) 00134 - calx*caly*(sbly*sblz + cbly*cblz*sblx) + cblx*cblz*salx) 00135 - (cbcy*cbcz + sbcx*sbcy*sbcz)*(calx*caly*(cblz*sbly - cbly*sblx*sblz) 00136 - calx*saly*(cbly*cblz + sblx*sbly*sblz) + cblx*salx*sblz) 00137 + cbcx*sbcy*(salx*sblx + calx*caly*cblx*cbly + calx*cblx*saly*sbly); 00138 float crycrx = (cbcz*sbcy - cbcy*sbcx*sbcz)*(calx*caly*(cblz*sbly - cbly*sblx*sblz) 00139 - calx*saly*(cbly*cblz + sblx*sbly*sblz) + cblx*salx*sblz) 00140 - (sbcy*sbcz + cbcy*cbcz*sbcx)*(calx*saly*(cbly*sblz - cblz*sblx*sbly) 00141 - calx*caly*(sbly*sblz + cbly*cblz*sblx) + cblx*cblz*salx) 00142 + cbcx*cbcy*(salx*sblx + calx*caly*cblx*cbly + calx*cblx*saly*sbly); 00143 transformTobeMapped[1] = atan2(srycrx / cos(transformTobeMapped[0]), 00144 crycrx / cos(transformTobeMapped[0])); 00145 00146 float srzcrx = sbcx*(cblx*cbly*(calz*saly - caly*salx*salz) 00147 - cblx*sbly*(caly*calz + salx*saly*salz) + calx*salz*sblx) 00148 - cbcx*cbcz*((caly*calz + salx*saly*salz)*(cbly*sblz - cblz*sblx*sbly) 00149 + (calz*saly - caly*salx*salz)*(sbly*sblz + cbly*cblz*sblx) 00150 - calx*cblx*cblz*salz) + cbcx*sbcz*((caly*calz + salx*saly*salz)*(cbly*cblz 00151 + sblx*sbly*sblz) + (calz*saly - caly*salx*salz)*(cblz*sbly - cbly*sblx*sblz) 00152 + calx*cblx*salz*sblz); 00153 float crzcrx = sbcx*(cblx*sbly*(caly*salz - calz*salx*saly) 00154 - cblx*cbly*(saly*salz + caly*calz*salx) + calx*calz*sblx) 00155 + cbcx*cbcz*((saly*salz + caly*calz*salx)*(sbly*sblz + cbly*cblz*sblx) 00156 + (caly*salz - calz*salx*saly)*(cbly*sblz - cblz*sblx*sbly) 00157 + calx*calz*cblx*cblz) - cbcx*sbcz*((saly*salz + caly*calz*salx)*(cblz*sbly 00158 - cbly*sblx*sblz) + (caly*salz - calz*salx*saly)*(cbly*cblz + sblx*sbly*sblz) 00159 - calx*calz*cblx*sblz); 00160 transformTobeMapped[2] = atan2(srzcrx / cos(transformTobeMapped[0]), 00161 crzcrx / cos(transformTobeMapped[0])); 00162 00163 x1 = cos(transformTobeMapped[2]) * transformIncre[3] - sin(transformTobeMapped[2]) * transformIncre[4]; 00164 y1 = sin(transformTobeMapped[2]) * transformIncre[3] + cos(transformTobeMapped[2]) * transformIncre[4]; 00165 z1 = transformIncre[5]; 00166 00167 x2 = x1; 00168 y2 = cos(transformTobeMapped[0]) * y1 - sin(transformTobeMapped[0]) * z1; 00169 z2 = sin(transformTobeMapped[0]) * y1 + cos(transformTobeMapped[0]) * z1; 00170 00171 transformTobeMapped[3] = transformAftMapped[3] 00172 - (cos(transformTobeMapped[1]) * x2 + sin(transformTobeMapped[1]) * z2); 00173 transformTobeMapped[4] = transformAftMapped[4] - y2; 00174 transformTobeMapped[5] = transformAftMapped[5] 00175 - (-sin(transformTobeMapped[1]) * x2 + cos(transformTobeMapped[1]) * z2); 00176 } 00177 00178 void transformUpdate() 00179 { 00180 if (imuPointerLast >= 0) { 00181 float imuRollLast = 0, imuPitchLast = 0; 00182 while (imuPointerFront != imuPointerLast) { 00183 if (timeLaserOdometry + scanPeriod < imuTime[imuPointerFront]) { 00184 break; 00185 } 00186 imuPointerFront = (imuPointerFront + 1) % imuQueLength; 00187 } 00188 00189 if (timeLaserOdometry + scanPeriod > imuTime[imuPointerFront]) { 00190 imuRollLast = imuRoll[imuPointerFront]; 00191 imuPitchLast = imuPitch[imuPointerFront]; 00192 } else { 00193 int imuPointerBack = (imuPointerFront + imuQueLength - 1) % imuQueLength; 00194 float ratioFront = (timeLaserOdometry + scanPeriod - imuTime[imuPointerBack]) 00195 / (imuTime[imuPointerFront] - imuTime[imuPointerBack]); 00196 float ratioBack = (imuTime[imuPointerFront] - timeLaserOdometry - scanPeriod) 00197 / (imuTime[imuPointerFront] - imuTime[imuPointerBack]); 00198 00199 imuRollLast = imuRoll[imuPointerFront] * ratioFront + imuRoll[imuPointerBack] * ratioBack; 00200 imuPitchLast = imuPitch[imuPointerFront] * ratioFront + imuPitch[imuPointerBack] * ratioBack; 00201 } 00202 00203 transformTobeMapped[0] = 0.998 * transformTobeMapped[0] + 0.002 * imuPitchLast; 00204 transformTobeMapped[2] = 0.998 * transformTobeMapped[2] + 0.002 * imuRollLast; 00205 } 00206 00207 //transformTobeMapped[0] = 0.998 * transformTobeMapped[0] + 0.002 * transformSum[0]; 00208 //transformTobeMapped[2] = 0.998 * transformTobeMapped[2] + 0.002 * transformSum[2]; 00209 00210 for (int i = 0; i < 6; i++) { 00211 transformBefMapped[i] = transformSum[i]; 00212 transformAftMapped[i] = transformTobeMapped[i]; 00213 } 00214 } 00215 00216 void pointAssociateToMap(pcl::PointXYZI *pi, pcl::PointXYZI *po) 00217 { 00218 float x1 = cos(transformTobeMapped[2]) * pi->x 00219 - sin(transformTobeMapped[2]) * pi->y; 00220 float y1 = sin(transformTobeMapped[2]) * pi->x 00221 + cos(transformTobeMapped[2]) * pi->y; 00222 float z1 = pi->z; 00223 00224 float x2 = x1; 00225 float y2 = cos(transformTobeMapped[0]) * y1 - sin(transformTobeMapped[0]) * z1; 00226 float z2 = sin(transformTobeMapped[0]) * y1 + cos(transformTobeMapped[0]) * z1; 00227 00228 po->x = cos(transformTobeMapped[1]) * x2 + sin(transformTobeMapped[1]) * z2 00229 + transformTobeMapped[3]; 00230 po->y = y2 + transformTobeMapped[4]; 00231 po->z = -sin(transformTobeMapped[1]) * x2 + cos(transformTobeMapped[1]) * z2 00232 + transformTobeMapped[5]; 00233 po->intensity = pi->intensity; 00234 } 00235 00236 void pointAssociateTobeMapped(pcl::PointXYZI *pi, pcl::PointXYZI *po) 00237 { 00238 float x1 = cos(transformTobeMapped[1]) * (pi->x - transformTobeMapped[3]) 00239 - sin(transformTobeMapped[1]) * (pi->z - transformTobeMapped[5]); 00240 float y1 = pi->y - transformTobeMapped[4]; 00241 float z1 = sin(transformTobeMapped[1]) * (pi->x - transformTobeMapped[3]) 00242 + cos(transformTobeMapped[1]) * (pi->z - transformTobeMapped[5]); 00243 00244 float x2 = x1; 00245 float y2 = cos(transformTobeMapped[0]) * y1 + sin(transformTobeMapped[0]) * z1; 00246 float z2 = -sin(transformTobeMapped[0]) * y1 + cos(transformTobeMapped[0]) * z1; 00247 00248 po->x = cos(transformTobeMapped[2]) * x2 00249 + sin(transformTobeMapped[2]) * y2; 00250 po->y = -sin(transformTobeMapped[2]) * x2 00251 + cos(transformTobeMapped[2]) * y2; 00252 po->z = z2; 00253 po->intensity = pi->intensity; 00254 } 00255 00256 void laserCloudCornerLastHandler(const sensor_msgs::PointCloud2ConstPtr& laserCloudCornerLast2) 00257 { 00258 timeLaserCloudCornerLast = laserCloudCornerLast2->header.stamp.toSec(); 00259 00260 laserCloudCornerLast->clear(); 00261 pcl::fromROSMsg(*laserCloudCornerLast2, *laserCloudCornerLast); 00262 00263 newLaserCloudCornerLast = true; 00264 } 00265 00266 void laserCloudSurfLastHandler(const sensor_msgs::PointCloud2ConstPtr& laserCloudSurfLast2) 00267 { 00268 timeLaserCloudSurfLast = laserCloudSurfLast2->header.stamp.toSec(); 00269 00270 laserCloudSurfLast->clear(); 00271 pcl::fromROSMsg(*laserCloudSurfLast2, *laserCloudSurfLast); 00272 00273 newLaserCloudSurfLast = true; 00274 } 00275 00276 void laserCloudFullResHandler(const sensor_msgs::PointCloud2ConstPtr& laserCloudFullRes2) 00277 { 00278 timeLaserCloudFullRes = laserCloudFullRes2->header.stamp.toSec(); 00279 00280 laserCloudFullRes->clear(); 00281 pcl::fromROSMsg(*laserCloudFullRes2, *laserCloudFullRes); 00282 00283 newLaserCloudFullRes = true; 00284 } 00285 00286 void laserOdometryHandler(const nav_msgs::Odometry::ConstPtr& laserOdometry) 00287 { 00288 timeLaserOdometry = laserOdometry->header.stamp.toSec(); 00289 00290 double roll, pitch, yaw; 00291 geometry_msgs::Quaternion geoQuat = laserOdometry->pose.pose.orientation; 00292 tf::Matrix3x3(tf::Quaternion(geoQuat.z, -geoQuat.x, -geoQuat.y, geoQuat.w)).getRPY(roll, pitch, yaw); 00293 00294 transformSum[0] = -pitch; 00295 transformSum[1] = -yaw; 00296 transformSum[2] = roll; 00297 00298 transformSum[3] = laserOdometry->pose.pose.position.x; 00299 transformSum[4] = laserOdometry->pose.pose.position.y; 00300 transformSum[5] = laserOdometry->pose.pose.position.z; 00301 00302 newLaserOdometry = true; 00303 } 00304 00305 void imuHandler(const sensor_msgs::Imu::ConstPtr& imuIn) 00306 { 00307 double roll, pitch, yaw; 00308 tf::Quaternion orientation; 00309 tf::quaternionMsgToTF(imuIn->orientation, orientation); 00310 tf::Matrix3x3(orientation).getRPY(roll, pitch, yaw); 00311 00312 imuPointerLast = (imuPointerLast + 1) % imuQueLength; 00313 00314 imuTime[imuPointerLast] = imuIn->header.stamp.toSec(); 00315 imuRoll[imuPointerLast] = roll; 00316 imuPitch[imuPointerLast] = pitch; 00317 } 00318 00319 int main(int argc, char** argv) 00320 { 00321 ros::init(argc, argv, "laserMapping"); 00322 ros::NodeHandle nh; 00323 00324 ros::Subscriber subLaserCloudCornerLast = nh.subscribe<sensor_msgs::PointCloud2> 00325 ("/laser_cloud_corner_last", 2, laserCloudCornerLastHandler); 00326 00327 ros::Subscriber subLaserCloudSurfLast = nh.subscribe<sensor_msgs::PointCloud2> 00328 ("/laser_cloud_surf_last", 2, laserCloudSurfLastHandler); 00329 00330 ros::Subscriber subLaserOdometry = nh.subscribe<nav_msgs::Odometry> 00331 ("/laser_odom_to_init", 5, laserOdometryHandler); 00332 00333 ros::Subscriber subLaserCloudFullRes = nh.subscribe<sensor_msgs::PointCloud2> 00334 ("/velodyne_cloud_3", 2, laserCloudFullResHandler); 00335 00336 ros::Subscriber subImu = nh.subscribe<sensor_msgs::Imu> ("/imu/data", 50, imuHandler); 00337 00338 ros::Publisher pubLaserCloudSurround = nh.advertise<sensor_msgs::PointCloud2> 00339 ("/laser_cloud_surround", 1); 00340 00341 ros::Publisher pubLaserCloudFullRes = nh.advertise<sensor_msgs::PointCloud2> 00342 ("/velodyne_cloud_registered", 2); 00343 00344 //ros::Publisher pub1 = nh.advertise<sensor_msgs::PointCloud2> ("/pc1", 2); 00345 00346 //ros::Publisher pub2 = nh.advertise<sensor_msgs::PointCloud2> ("/pc2", 2); 00347 00348 //ros::Publisher pub1 = nh.advertise<sensor_msgs::PointCloud2> ("/pc3", 2); 00349 00350 //ros::Publisher pub2 = nh.advertise<sensor_msgs::PointCloud2> ("/pc4", 2); 00351 00352 ros::Publisher pubOdomAftMapped = nh.advertise<nav_msgs::Odometry> ("/aft_mapped_to_init", 5); 00353 nav_msgs::Odometry odomAftMapped; 00354 odomAftMapped.header.frame_id = "/camera_init"; 00355 odomAftMapped.child_frame_id = "/aft_mapped"; 00356 00357 tf::TransformBroadcaster tfBroadcaster; 00358 tf::StampedTransform aftMappedTrans; 00359 aftMappedTrans.frame_id_ = "/camera_init"; 00360 aftMappedTrans.child_frame_id_ = "/aft_mapped"; 00361 00362 std::vector<int> pointSearchInd; 00363 std::vector<float> pointSearchSqDis; 00364 00365 pcl::PointXYZI pointOri, pointSel, pointProj, coeff; 00366 00367 cv::Mat matA0(5, 3, CV_32F, cv::Scalar::all(0)); 00368 cv::Mat matB0(5, 1, CV_32F, cv::Scalar::all(-1)); 00369 cv::Mat matX0(3, 1, CV_32F, cv::Scalar::all(0)); 00370 00371 cv::Mat matA1(3, 3, CV_32F, cv::Scalar::all(0)); 00372 cv::Mat matD1(1, 3, CV_32F, cv::Scalar::all(0)); 00373 cv::Mat matV1(3, 3, CV_32F, cv::Scalar::all(0)); 00374 00375 bool isDegenerate = false; 00376 cv::Mat matP(6, 6, CV_32F, cv::Scalar::all(0)); 00377 00378 pcl::VoxelGrid<pcl::PointXYZI> downSizeFilterCorner; 00379 downSizeFilterCorner.setLeafSize(0.2, 0.2, 0.2); 00380 00381 pcl::VoxelGrid<pcl::PointXYZI> downSizeFilterSurf; 00382 downSizeFilterSurf.setLeafSize(0.4, 0.4, 0.4); 00383 00384 pcl::VoxelGrid<pcl::PointXYZI> downSizeFilterMap; 00385 downSizeFilterMap.setLeafSize(0.6, 0.6, 0.6); 00386 00387 for (int i = 0; i < laserCloudNum; i++) { 00388 laserCloudCornerArray[i].reset(new pcl::PointCloud<pcl::PointXYZI>()); 00389 laserCloudSurfArray[i].reset(new pcl::PointCloud<pcl::PointXYZI>()); 00390 laserCloudCornerArray2[i].reset(new pcl::PointCloud<pcl::PointXYZI>()); 00391 laserCloudSurfArray2[i].reset(new pcl::PointCloud<pcl::PointXYZI>()); 00392 } 00393 00394 int frameCount = stackFrameNum - 1; 00395 int mapFrameCount = mapFrameNum - 1; 00396 ros::Rate rate(100); 00397 bool status = ros::ok(); 00398 while (status) { 00399 ros::spinOnce(); 00400 00401 if (newLaserCloudCornerLast && newLaserCloudSurfLast && newLaserCloudFullRes && newLaserOdometry && 00402 fabs(timeLaserCloudCornerLast - timeLaserOdometry) < 0.005 && 00403 fabs(timeLaserCloudSurfLast - timeLaserOdometry) < 0.005 && 00404 fabs(timeLaserCloudFullRes - timeLaserOdometry) < 0.005) { 00405 newLaserCloudCornerLast = false; 00406 newLaserCloudSurfLast = false; 00407 newLaserCloudFullRes = false; 00408 newLaserOdometry = false; 00409 00410 frameCount++; 00411 if (frameCount >= stackFrameNum) { 00412 transformAssociateToMap(); 00413 00414 int laserCloudCornerLastNum = laserCloudCornerLast->points.size(); 00415 for (int i = 0; i < laserCloudCornerLastNum; i++) { 00416 pointAssociateToMap(&laserCloudCornerLast->points[i], &pointSel); 00417 laserCloudCornerStack2->push_back(pointSel); 00418 } 00419 00420 int laserCloudSurfLastNum = laserCloudSurfLast->points.size(); 00421 for (int i = 0; i < laserCloudSurfLastNum; i++) { 00422 pointAssociateToMap(&laserCloudSurfLast->points[i], &pointSel); 00423 laserCloudSurfStack2->push_back(pointSel); 00424 } 00425 } 00426 00427 if (frameCount >= stackFrameNum) { 00428 frameCount = 0; 00429 00430 pcl::PointXYZI pointOnYAxis; 00431 pointOnYAxis.x = 0.0; 00432 pointOnYAxis.y = 10.0; 00433 pointOnYAxis.z = 0.0; 00434 pointAssociateToMap(&pointOnYAxis, &pointOnYAxis); 00435 00436 int centerCubeI = int((transformTobeMapped[3] + 25.0) / 50.0) + laserCloudCenWidth; 00437 int centerCubeJ = int((transformTobeMapped[4] + 25.0) / 50.0) + laserCloudCenHeight; 00438 int centerCubeK = int((transformTobeMapped[5] + 25.0) / 50.0) + laserCloudCenDepth; 00439 00440 if (transformTobeMapped[3] + 25.0 < 0) centerCubeI--; 00441 if (transformTobeMapped[4] + 25.0 < 0) centerCubeJ--; 00442 if (transformTobeMapped[5] + 25.0 < 0) centerCubeK--; 00443 00444 while (centerCubeI < 3) { 00445 for (int j = 0; j < laserCloudHeight; j++) { 00446 for (int k = 0; k < laserCloudDepth; k++) { 00447 int i = laserCloudWidth - 1; 00448 pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudCubeCornerPointer = 00449 laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k]; 00450 pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudCubeSurfPointer = 00451 laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k]; 00452 for (; i >= 1; i--) { 00453 laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] = 00454 laserCloudCornerArray[i - 1 + laserCloudWidth*j + laserCloudWidth * laserCloudHeight * k]; 00455 laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] = 00456 laserCloudSurfArray[i - 1 + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k]; 00457 } 00458 laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] = 00459 laserCloudCubeCornerPointer; 00460 laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] = 00461 laserCloudCubeSurfPointer; 00462 laserCloudCubeCornerPointer->clear(); 00463 laserCloudCubeSurfPointer->clear(); 00464 } 00465 } 00466 00467 centerCubeI++; 00468 laserCloudCenWidth++; 00469 } 00470 00471 while (centerCubeI >= laserCloudWidth - 3) { 00472 for (int j = 0; j < laserCloudHeight; j++) { 00473 for (int k = 0; k < laserCloudDepth; k++) { 00474 int i = 0; 00475 pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudCubeCornerPointer = 00476 laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k]; 00477 pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudCubeSurfPointer = 00478 laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k]; 00479 for (; i < laserCloudWidth - 1; i++) { 00480 laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] = 00481 laserCloudCornerArray[i + 1 + laserCloudWidth*j + laserCloudWidth * laserCloudHeight * k]; 00482 laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] = 00483 laserCloudSurfArray[i + 1 + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k]; 00484 } 00485 laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] = 00486 laserCloudCubeCornerPointer; 00487 laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] = 00488 laserCloudCubeSurfPointer; 00489 laserCloudCubeCornerPointer->clear(); 00490 laserCloudCubeSurfPointer->clear(); 00491 } 00492 } 00493 00494 centerCubeI--; 00495 laserCloudCenWidth--; 00496 } 00497 00498 while (centerCubeJ < 3) { 00499 for (int i = 0; i < laserCloudWidth; i++) { 00500 for (int k = 0; k < laserCloudDepth; k++) { 00501 int j = laserCloudHeight - 1; 00502 pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudCubeCornerPointer = 00503 laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k]; 00504 pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudCubeSurfPointer = 00505 laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k]; 00506 for (; j >= 1; j--) { 00507 laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] = 00508 laserCloudCornerArray[i + laserCloudWidth*(j - 1) + laserCloudWidth * laserCloudHeight*k]; 00509 laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] = 00510 laserCloudSurfArray[i + laserCloudWidth * (j - 1) + laserCloudWidth * laserCloudHeight*k]; 00511 } 00512 laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] = 00513 laserCloudCubeCornerPointer; 00514 laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] = 00515 laserCloudCubeSurfPointer; 00516 laserCloudCubeCornerPointer->clear(); 00517 laserCloudCubeSurfPointer->clear(); 00518 } 00519 } 00520 00521 centerCubeJ++; 00522 laserCloudCenHeight++; 00523 } 00524 00525 while (centerCubeJ >= laserCloudHeight - 3) { 00526 for (int i = 0; i < laserCloudWidth; i++) { 00527 for (int k = 0; k < laserCloudDepth; k++) { 00528 int j = 0; 00529 pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudCubeCornerPointer = 00530 laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k]; 00531 pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudCubeSurfPointer = 00532 laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k]; 00533 for (; j < laserCloudHeight - 1; j++) { 00534 laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] = 00535 laserCloudCornerArray[i + laserCloudWidth*(j + 1) + laserCloudWidth * laserCloudHeight*k]; 00536 laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] = 00537 laserCloudSurfArray[i + laserCloudWidth * (j + 1) + laserCloudWidth * laserCloudHeight*k]; 00538 } 00539 laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] = 00540 laserCloudCubeCornerPointer; 00541 laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] = 00542 laserCloudCubeSurfPointer; 00543 laserCloudCubeCornerPointer->clear(); 00544 laserCloudCubeSurfPointer->clear(); 00545 } 00546 } 00547 00548 centerCubeJ--; 00549 laserCloudCenHeight--; 00550 } 00551 00552 while (centerCubeK < 3) { 00553 for (int i = 0; i < laserCloudWidth; i++) { 00554 for (int j = 0; j < laserCloudHeight; j++) { 00555 int k = laserCloudDepth - 1; 00556 pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudCubeCornerPointer = 00557 laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k]; 00558 pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudCubeSurfPointer = 00559 laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k]; 00560 for (; k >= 1; k--) { 00561 laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] = 00562 laserCloudCornerArray[i + laserCloudWidth*j + laserCloudWidth * laserCloudHeight*(k - 1)]; 00563 laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] = 00564 laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight*(k - 1)]; 00565 } 00566 laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] = 00567 laserCloudCubeCornerPointer; 00568 laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] = 00569 laserCloudCubeSurfPointer; 00570 laserCloudCubeCornerPointer->clear(); 00571 laserCloudCubeSurfPointer->clear(); 00572 } 00573 } 00574 00575 centerCubeK++; 00576 laserCloudCenDepth++; 00577 } 00578 00579 while (centerCubeK >= laserCloudDepth - 3) { 00580 for (int i = 0; i < laserCloudWidth; i++) { 00581 for (int j = 0; j < laserCloudHeight; j++) { 00582 int k = 0; 00583 pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudCubeCornerPointer = 00584 laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k]; 00585 pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudCubeSurfPointer = 00586 laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k]; 00587 for (; k < laserCloudDepth - 1; k++) { 00588 laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] = 00589 laserCloudCornerArray[i + laserCloudWidth*j + laserCloudWidth * laserCloudHeight*(k + 1)]; 00590 laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] = 00591 laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight*(k + 1)]; 00592 } 00593 laserCloudCornerArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] = 00594 laserCloudCubeCornerPointer; 00595 laserCloudSurfArray[i + laserCloudWidth * j + laserCloudWidth * laserCloudHeight * k] = 00596 laserCloudCubeSurfPointer; 00597 laserCloudCubeCornerPointer->clear(); 00598 laserCloudCubeSurfPointer->clear(); 00599 } 00600 } 00601 00602 centerCubeK--; 00603 laserCloudCenDepth--; 00604 } 00605 00606 int laserCloudValidNum = 0; 00607 int laserCloudSurroundNum = 0; 00608 for (int i = centerCubeI - 2; i <= centerCubeI + 2; i++) { 00609 for (int j = centerCubeJ - 2; j <= centerCubeJ + 2; j++) { 00610 for (int k = centerCubeK - 2; k <= centerCubeK + 2; k++) { 00611 if (i >= 0 && i < laserCloudWidth && 00612 j >= 0 && j < laserCloudHeight && 00613 k >= 0 && k < laserCloudDepth) { 00614 00615 float centerX = 50.0 * (i - laserCloudCenWidth); 00616 float centerY = 50.0 * (j - laserCloudCenHeight); 00617 float centerZ = 50.0 * (k - laserCloudCenDepth); 00618 00619 bool isInLaserFOV = false; 00620 for (int ii = -1; ii <= 1; ii += 2) { 00621 for (int jj = -1; jj <= 1; jj += 2) { 00622 for (int kk = -1; kk <= 1; kk += 2) { 00623 float cornerX = centerX + 25.0 * ii; 00624 float cornerY = centerY + 25.0 * jj; 00625 float cornerZ = centerZ + 25.0 * kk; 00626 00627 float squaredSide1 = (transformTobeMapped[3] - cornerX) 00628 * (transformTobeMapped[3] - cornerX) 00629 + (transformTobeMapped[4] - cornerY) 00630 * (transformTobeMapped[4] - cornerY) 00631 + (transformTobeMapped[5] - cornerZ) 00632 * (transformTobeMapped[5] - cornerZ); 00633 00634 float squaredSide2 = (pointOnYAxis.x - cornerX) * (pointOnYAxis.x - cornerX) 00635 + (pointOnYAxis.y - cornerY) * (pointOnYAxis.y - cornerY) 00636 + (pointOnYAxis.z - cornerZ) * (pointOnYAxis.z - cornerZ); 00637 00638 float check1 = 100.0 + squaredSide1 - squaredSide2 00639 - 10.0 * sqrt(3.0) * sqrt(squaredSide1); 00640 00641 float check2 = 100.0 + squaredSide1 - squaredSide2 00642 + 10.0 * sqrt(3.0) * sqrt(squaredSide1); 00643 00644 if (check1 < 0 && check2 > 0) { 00645 isInLaserFOV = true; 00646 } 00647 } 00648 } 00649 } 00650 00651 if (isInLaserFOV) { 00652 laserCloudValidInd[laserCloudValidNum] = i + laserCloudWidth * j 00653 + laserCloudWidth * laserCloudHeight * k; 00654 laserCloudValidNum++; 00655 } 00656 laserCloudSurroundInd[laserCloudSurroundNum] = i + laserCloudWidth * j 00657 + laserCloudWidth * laserCloudHeight * k; 00658 laserCloudSurroundNum++; 00659 } 00660 } 00661 } 00662 } 00663 00664 laserCloudCornerFromMap->clear(); 00665 laserCloudSurfFromMap->clear(); 00666 for (int i = 0; i < laserCloudValidNum; i++) { 00667 *laserCloudCornerFromMap += *laserCloudCornerArray[laserCloudValidInd[i]]; 00668 *laserCloudSurfFromMap += *laserCloudSurfArray[laserCloudValidInd[i]]; 00669 } 00670 int laserCloudCornerFromMapNum = laserCloudCornerFromMap->points.size(); 00671 int laserCloudSurfFromMapNum = laserCloudSurfFromMap->points.size(); 00672 00673 int laserCloudCornerStackNum2 = laserCloudCornerStack2->points.size(); 00674 for (int i = 0; i < laserCloudCornerStackNum2; i++) { 00675 pointAssociateTobeMapped(&laserCloudCornerStack2->points[i], &laserCloudCornerStack2->points[i]); 00676 } 00677 00678 int laserCloudSurfStackNum2 = laserCloudSurfStack2->points.size(); 00679 for (int i = 0; i < laserCloudSurfStackNum2; i++) { 00680 pointAssociateTobeMapped(&laserCloudSurfStack2->points[i], &laserCloudSurfStack2->points[i]); 00681 } 00682 00683 laserCloudCornerStack->clear(); 00684 downSizeFilterCorner.setInputCloud(laserCloudCornerStack2); 00685 downSizeFilterCorner.filter(*laserCloudCornerStack); 00686 int laserCloudCornerStackNum = laserCloudCornerStack->points.size(); 00687 00688 laserCloudSurfStack->clear(); 00689 downSizeFilterSurf.setInputCloud(laserCloudSurfStack2); 00690 downSizeFilterSurf.filter(*laserCloudSurfStack); 00691 int laserCloudSurfStackNum = laserCloudSurfStack->points.size(); 00692 00693 laserCloudCornerStack2->clear(); 00694 laserCloudSurfStack2->clear(); 00695 00696 if (laserCloudCornerFromMapNum > 10 && laserCloudSurfFromMapNum > 100) { 00697 kdtreeCornerFromMap->setInputCloud(laserCloudCornerFromMap); 00698 kdtreeSurfFromMap->setInputCloud(laserCloudSurfFromMap); 00699 00700 for (int iterCount = 0; iterCount < 10; iterCount++) { 00701 laserCloudOri->clear(); 00702 //laserCloudSel->clear(); 00703 //laserCloudCorr->clear(); 00704 //laserCloudProj->clear(); 00705 coeffSel->clear(); 00706 00707 for (int i = 0; i < laserCloudCornerStackNum; i++) { 00708 pointOri = laserCloudCornerStack->points[i]; 00709 pointAssociateToMap(&pointOri, &pointSel); 00710 kdtreeCornerFromMap->nearestKSearch(pointSel, 5, pointSearchInd, pointSearchSqDis); 00711 00712 if (pointSearchSqDis[4] < 1.0) { 00713 float cx = 0; 00714 float cy = 0; 00715 float cz = 0; 00716 for (int j = 0; j < 5; j++) { 00717 cx += laserCloudCornerFromMap->points[pointSearchInd[j]].x; 00718 cy += laserCloudCornerFromMap->points[pointSearchInd[j]].y; 00719 cz += laserCloudCornerFromMap->points[pointSearchInd[j]].z; 00720 } 00721 cx /= 5; 00722 cy /= 5; 00723 cz /= 5; 00724 00725 float a11 = 0; 00726 float a12 = 0; 00727 float a13 = 0; 00728 float a22 = 0; 00729 float a23 = 0; 00730 float a33 = 0; 00731 for (int j = 0; j < 5; j++) { 00732 float ax = laserCloudCornerFromMap->points[pointSearchInd[j]].x - cx; 00733 float ay = laserCloudCornerFromMap->points[pointSearchInd[j]].y - cy; 00734 float az = laserCloudCornerFromMap->points[pointSearchInd[j]].z - cz; 00735 00736 a11 += ax * ax; 00737 a12 += ax * ay; 00738 a13 += ax * az; 00739 a22 += ay * ay; 00740 a23 += ay * az; 00741 a33 += az * az; 00742 } 00743 a11 /= 5; 00744 a12 /= 5; 00745 a13 /= 5; 00746 a22 /= 5; 00747 a23 /= 5; 00748 a33 /= 5; 00749 00750 matA1.at<float>(0, 0) = a11; 00751 matA1.at<float>(0, 1) = a12; 00752 matA1.at<float>(0, 2) = a13; 00753 matA1.at<float>(1, 0) = a12; 00754 matA1.at<float>(1, 1) = a22; 00755 matA1.at<float>(1, 2) = a23; 00756 matA1.at<float>(2, 0) = a13; 00757 matA1.at<float>(2, 1) = a23; 00758 matA1.at<float>(2, 2) = a33; 00759 00760 cv::eigen(matA1, matD1, matV1); 00761 00762 if (matD1.at<float>(0, 0) > 3 * matD1.at<float>(0, 1)) { 00763 00764 float x0 = pointSel.x; 00765 float y0 = pointSel.y; 00766 float z0 = pointSel.z; 00767 float x1 = cx + 0.1 * matV1.at<float>(0, 0); 00768 float y1 = cy + 0.1 * matV1.at<float>(0, 1); 00769 float z1 = cz + 0.1 * matV1.at<float>(0, 2); 00770 float x2 = cx - 0.1 * matV1.at<float>(0, 0); 00771 float y2 = cy - 0.1 * matV1.at<float>(0, 1); 00772 float z2 = cz - 0.1 * matV1.at<float>(0, 2); 00773 00774 float a012 = sqrt(((x0 - x1)*(y0 - y2) - (x0 - x2)*(y0 - y1)) 00775 * ((x0 - x1)*(y0 - y2) - (x0 - x2)*(y0 - y1)) 00776 + ((x0 - x1)*(z0 - z2) - (x0 - x2)*(z0 - z1)) 00777 * ((x0 - x1)*(z0 - z2) - (x0 - x2)*(z0 - z1)) 00778 + ((y0 - y1)*(z0 - z2) - (y0 - y2)*(z0 - z1)) 00779 * ((y0 - y1)*(z0 - z2) - (y0 - y2)*(z0 - z1))); 00780 00781 float l12 = sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2) + (z1 - z2)*(z1 - z2)); 00782 00783 float la = ((y1 - y2)*((x0 - x1)*(y0 - y2) - (x0 - x2)*(y0 - y1)) 00784 + (z1 - z2)*((x0 - x1)*(z0 - z2) - (x0 - x2)*(z0 - z1))) / a012 / l12; 00785 00786 float lb = -((x1 - x2)*((x0 - x1)*(y0 - y2) - (x0 - x2)*(y0 - y1)) 00787 - (z1 - z2)*((y0 - y1)*(z0 - z2) - (y0 - y2)*(z0 - z1))) / a012 / l12; 00788 00789 float lc = -((x1 - x2)*((x0 - x1)*(z0 - z2) - (x0 - x2)*(z0 - z1)) 00790 + (y1 - y2)*((y0 - y1)*(z0 - z2) - (y0 - y2)*(z0 - z1))) / a012 / l12; 00791 00792 float ld2 = a012 / l12; 00793 00794 pointProj = pointSel; 00795 pointProj.x -= la * ld2; 00796 pointProj.y -= lb * ld2; 00797 pointProj.z -= lc * ld2; 00798 00799 float s = 1 - 0.9 * fabs(ld2); 00800 00801 coeff.x = s * la; 00802 coeff.y = s * lb; 00803 coeff.z = s * lc; 00804 coeff.intensity = s * ld2; 00805 00806 if (s > 0.1) { 00807 laserCloudOri->push_back(pointOri); 00808 //laserCloudSel->push_back(pointSel); 00809 //laserCloudProj->push_back(pointProj); 00810 //laserCloudCorr->push_back(laserCloudCornerFromMap->points[pointSearchInd[0]]); 00811 //laserCloudCorr->push_back(laserCloudCornerFromMap->points[pointSearchInd[1]]); 00812 //laserCloudCorr->push_back(laserCloudCornerFromMap->points[pointSearchInd[2]]); 00813 //laserCloudCorr->push_back(laserCloudCornerFromMap->points[pointSearchInd[3]]); 00814 //laserCloudCorr->push_back(laserCloudCornerFromMap->points[pointSearchInd[4]]); 00815 coeffSel->push_back(coeff); 00816 } 00817 } 00818 } 00819 } 00820 00821 for (int i = 0; i < laserCloudSurfStackNum; i++) { 00822 pointOri = laserCloudSurfStack->points[i]; 00823 pointAssociateToMap(&pointOri, &pointSel); 00824 kdtreeSurfFromMap->nearestKSearch(pointSel, 5, pointSearchInd, pointSearchSqDis); 00825 00826 if (pointSearchSqDis[4] < 1.0) { 00827 for (int j = 0; j < 5; j++) { 00828 matA0.at<float>(j, 0) = laserCloudSurfFromMap->points[pointSearchInd[j]].x; 00829 matA0.at<float>(j, 1) = laserCloudSurfFromMap->points[pointSearchInd[j]].y; 00830 matA0.at<float>(j, 2) = laserCloudSurfFromMap->points[pointSearchInd[j]].z; 00831 } 00832 cv::solve(matA0, matB0, matX0, cv::DECOMP_QR); 00833 00834 float pa = matX0.at<float>(0, 0); 00835 float pb = matX0.at<float>(1, 0); 00836 float pc = matX0.at<float>(2, 0); 00837 float pd = 1; 00838 00839 float ps = sqrt(pa * pa + pb * pb + pc * pc); 00840 pa /= ps; 00841 pb /= ps; 00842 pc /= ps; 00843 pd /= ps; 00844 00845 bool planeValid = true; 00846 for (int j = 0; j < 5; j++) { 00847 if (fabs(pa * laserCloudSurfFromMap->points[pointSearchInd[j]].x + 00848 pb * laserCloudSurfFromMap->points[pointSearchInd[j]].y + 00849 pc * laserCloudSurfFromMap->points[pointSearchInd[j]].z + pd) > 0.2) { 00850 planeValid = false; 00851 break; 00852 } 00853 } 00854 00855 if (planeValid) { 00856 float pd2 = pa * pointSel.x + pb * pointSel.y + pc * pointSel.z + pd; 00857 00858 pointProj = pointSel; 00859 pointProj.x -= pa * pd2; 00860 pointProj.y -= pb * pd2; 00861 pointProj.z -= pc * pd2; 00862 00863 float s = 1 - 0.9 * fabs(pd2) / sqrt(sqrt(pointSel.x * pointSel.x 00864 + pointSel.y * pointSel.y + pointSel.z * pointSel.z)); 00865 00866 coeff.x = s * pa; 00867 coeff.y = s * pb; 00868 coeff.z = s * pc; 00869 coeff.intensity = s * pd2; 00870 00871 if (s > 0.1) { 00872 laserCloudOri->push_back(pointOri); 00873 //laserCloudSel->push_back(pointSel); 00874 //laserCloudProj->push_back(pointProj); 00875 //laserCloudCorr->push_back(laserCloudSurfFromMap->points[pointSearchInd[0]]); 00876 //laserCloudCorr->push_back(laserCloudSurfFromMap->points[pointSearchInd[1]]); 00877 //laserCloudCorr->push_back(laserCloudSurfFromMap->points[pointSearchInd[2]]); 00878 //laserCloudCorr->push_back(laserCloudSurfFromMap->points[pointSearchInd[3]]); 00879 //laserCloudCorr->push_back(laserCloudSurfFromMap->points[pointSearchInd[4]]); 00880 coeffSel->push_back(coeff); 00881 } 00882 } 00883 } 00884 } 00885 00886 float srx = sin(transformTobeMapped[0]); 00887 float crx = cos(transformTobeMapped[0]); 00888 float sry = sin(transformTobeMapped[1]); 00889 float cry = cos(transformTobeMapped[1]); 00890 float srz = sin(transformTobeMapped[2]); 00891 float crz = cos(transformTobeMapped[2]); 00892 00893 int laserCloudSelNum = laserCloudOri->points.size(); 00894 if (laserCloudSelNum < 50) { 00895 continue; 00896 } 00897 00898 cv::Mat matA(laserCloudSelNum, 6, CV_32F, cv::Scalar::all(0)); 00899 cv::Mat matAt(6, laserCloudSelNum, CV_32F, cv::Scalar::all(0)); 00900 cv::Mat matAtA(6, 6, CV_32F, cv::Scalar::all(0)); 00901 cv::Mat matB(laserCloudSelNum, 1, CV_32F, cv::Scalar::all(0)); 00902 cv::Mat matAtB(6, 1, CV_32F, cv::Scalar::all(0)); 00903 cv::Mat matX(6, 1, CV_32F, cv::Scalar::all(0)); 00904 for (int i = 0; i < laserCloudSelNum; i++) { 00905 pointOri = laserCloudOri->points[i]; 00906 coeff = coeffSel->points[i]; 00907 00908 float arx = (crx*sry*srz*pointOri.x + crx*crz*sry*pointOri.y - srx*sry*pointOri.z) * coeff.x 00909 + (-srx*srz*pointOri.x - crz*srx*pointOri.y - crx*pointOri.z) * coeff.y 00910 + (crx*cry*srz*pointOri.x + crx*cry*crz*pointOri.y - cry*srx*pointOri.z) * coeff.z; 00911 00912 float ary = ((cry*srx*srz - crz*sry)*pointOri.x 00913 + (sry*srz + cry*crz*srx)*pointOri.y + crx*cry*pointOri.z) * coeff.x 00914 + ((-cry*crz - srx*sry*srz)*pointOri.x 00915 + (cry*srz - crz*srx*sry)*pointOri.y - crx*sry*pointOri.z) * coeff.z; 00916 00917 float arz = ((crz*srx*sry - cry*srz)*pointOri.x + (-cry*crz-srx*sry*srz)*pointOri.y)*coeff.x 00918 + (crx*crz*pointOri.x - crx*srz*pointOri.y) * coeff.y 00919 + ((sry*srz + cry*crz*srx)*pointOri.x + (crz*sry-cry*srx*srz)*pointOri.y)*coeff.z; 00920 00921 matA.at<float>(i, 0) = arx; 00922 matA.at<float>(i, 1) = ary; 00923 matA.at<float>(i, 2) = arz; 00924 matA.at<float>(i, 3) = coeff.x; 00925 matA.at<float>(i, 4) = coeff.y; 00926 matA.at<float>(i, 5) = coeff.z; 00927 matB.at<float>(i, 0) = -coeff.intensity; 00928 } 00929 cv::transpose(matA, matAt); 00930 matAtA = matAt * matA; 00931 matAtB = matAt * matB; 00932 cv::solve(matAtA, matAtB, matX, cv::DECOMP_QR); 00933 00934 if (iterCount == 0) { 00935 cv::Mat matE(1, 6, CV_32F, cv::Scalar::all(0)); 00936 cv::Mat matV(6, 6, CV_32F, cv::Scalar::all(0)); 00937 cv::Mat matV2(6, 6, CV_32F, cv::Scalar::all(0)); 00938 00939 cv::eigen(matAtA, matE, matV); 00940 matV.copyTo(matV2); 00941 00942 isDegenerate = false; 00943 float eignThre[6] = {100, 100, 100, 100, 100, 100}; 00944 for (int i = 5; i >= 0; i--) { 00945 if (matE.at<float>(0, i) < eignThre[i]) { 00946 for (int j = 0; j < 6; j++) { 00947 matV2.at<float>(i, j) = 0; 00948 } 00949 isDegenerate = true; 00950 } else { 00951 break; 00952 } 00953 } 00954 matP = matV.inv() * matV2; 00955 } 00956 00957 if (isDegenerate /*&& 0*/) { 00958 cv::Mat matX2(6, 1, CV_32F, cv::Scalar::all(0)); 00959 matX.copyTo(matX2); 00960 matX = matP * matX2; 00961 00962 //ROS_INFO ("laser mapping degenerate"); 00963 } 00964 00965 transformTobeMapped[0] += matX.at<float>(0, 0); 00966 transformTobeMapped[1] += matX.at<float>(1, 0); 00967 transformTobeMapped[2] += matX.at<float>(2, 0); 00968 transformTobeMapped[3] += matX.at<float>(3, 0); 00969 transformTobeMapped[4] += matX.at<float>(4, 0); 00970 transformTobeMapped[5] += matX.at<float>(5, 0); 00971 00972 float deltaR = sqrt(matX.at<float>(0, 0) * 180 / PI * matX.at<float>(0, 0) * 180 / PI 00973 + matX.at<float>(1, 0) * 180 / PI * matX.at<float>(1, 0) * 180 / PI 00974 + matX.at<float>(2, 0) * 180 / PI * matX.at<float>(2, 0) * 180 / PI); 00975 float deltaT = sqrt(matX.at<float>(3, 0) * 100 * matX.at<float>(3, 0) * 100 00976 + matX.at<float>(4, 0) * 100 * matX.at<float>(4, 0) * 100 00977 + matX.at<float>(5, 0) * 100 * matX.at<float>(5, 0) * 100); 00978 00979 if (deltaR < 0.05 && deltaT < 0.05) { 00980 break; 00981 } 00982 00983 //ROS_INFO ("iter: %d, deltaR: %f, deltaT: %f", iterCount, deltaR, deltaT); 00984 } 00985 00986 transformUpdate(); 00987 } 00988 00989 for (int i = 0; i < laserCloudCornerStackNum; i++) { 00990 pointAssociateToMap(&laserCloudCornerStack->points[i], &pointSel); 00991 00992 int cubeI = int((pointSel.x + 25.0) / 50.0) + laserCloudCenWidth; 00993 int cubeJ = int((pointSel.y + 25.0) / 50.0) + laserCloudCenHeight; 00994 int cubeK = int((pointSel.z + 25.0) / 50.0) + laserCloudCenDepth; 00995 00996 if (pointSel.x + 25.0 < 0) cubeI--; 00997 if (pointSel.y + 25.0 < 0) cubeJ--; 00998 if (pointSel.z + 25.0 < 0) cubeK--; 00999 01000 if (cubeI >= 0 && cubeI < laserCloudWidth && 01001 cubeJ >= 0 && cubeJ < laserCloudHeight && 01002 cubeK >= 0 && cubeK < laserCloudDepth) { 01003 int cubeInd = cubeI + laserCloudWidth * cubeJ + laserCloudWidth * laserCloudHeight * cubeK; 01004 laserCloudCornerArray[cubeInd]->push_back(pointSel); 01005 } 01006 } 01007 01008 for (int i = 0; i < laserCloudSurfStackNum; i++) { 01009 pointAssociateToMap(&laserCloudSurfStack->points[i], &pointSel); 01010 01011 int cubeI = int((pointSel.x + 25.0) / 50.0) + laserCloudCenWidth; 01012 int cubeJ = int((pointSel.y + 25.0) / 50.0) + laserCloudCenHeight; 01013 int cubeK = int((pointSel.z + 25.0) / 50.0) + laserCloudCenDepth; 01014 01015 if (pointSel.x + 25.0 < 0) cubeI--; 01016 if (pointSel.y + 25.0 < 0) cubeJ--; 01017 if (pointSel.z + 25.0 < 0) cubeK--; 01018 01019 if (cubeI >= 0 && cubeI < laserCloudWidth && 01020 cubeJ >= 0 && cubeJ < laserCloudHeight && 01021 cubeK >= 0 && cubeK < laserCloudDepth) { 01022 int cubeInd = cubeI + laserCloudWidth * cubeJ + laserCloudWidth * laserCloudHeight * cubeK; 01023 laserCloudSurfArray[cubeInd]->push_back(pointSel); 01024 } 01025 } 01026 01027 for (int i = 0; i < laserCloudValidNum; i++) { 01028 int ind = laserCloudValidInd[i]; 01029 01030 laserCloudCornerArray2[ind]->clear(); 01031 downSizeFilterCorner.setInputCloud(laserCloudCornerArray[ind]); 01032 downSizeFilterCorner.filter(*laserCloudCornerArray2[ind]); 01033 01034 laserCloudSurfArray2[ind]->clear(); 01035 downSizeFilterSurf.setInputCloud(laserCloudSurfArray[ind]); 01036 downSizeFilterSurf.filter(*laserCloudSurfArray2[ind]); 01037 01038 pcl::PointCloud<pcl::PointXYZI>::Ptr laserCloudTemp = laserCloudCornerArray[ind]; 01039 laserCloudCornerArray[ind] = laserCloudCornerArray2[ind]; 01040 laserCloudCornerArray2[ind] = laserCloudTemp; 01041 01042 laserCloudTemp = laserCloudSurfArray[ind]; 01043 laserCloudSurfArray[ind] = laserCloudSurfArray2[ind]; 01044 laserCloudSurfArray2[ind] = laserCloudTemp; 01045 } 01046 01047 mapFrameCount++; 01048 if (mapFrameCount >= mapFrameNum) { 01049 mapFrameCount = 0; 01050 01051 laserCloudSurround2->clear(); 01052 for (int i = 0; i < laserCloudSurroundNum; i++) { 01053 int ind = laserCloudSurroundInd[i]; 01054 *laserCloudSurround2 += *laserCloudCornerArray[ind]; 01055 *laserCloudSurround2 += *laserCloudSurfArray[ind]; 01056 } 01057 01058 laserCloudSurround->clear(); 01059 downSizeFilterCorner.setInputCloud(laserCloudSurround2); 01060 downSizeFilterCorner.filter(*laserCloudSurround); 01061 01062 sensor_msgs::PointCloud2 laserCloudSurround3; 01063 pcl::toROSMsg(*laserCloudSurround, laserCloudSurround3); 01064 laserCloudSurround3.header.stamp = ros::Time().fromSec(timeLaserOdometry); 01065 laserCloudSurround3.header.frame_id = "/camera_init"; 01066 pubLaserCloudSurround.publish(laserCloudSurround3); 01067 } 01068 01069 int laserCloudFullResNum = laserCloudFullRes->points.size(); 01070 for (int i = 0; i < laserCloudFullResNum; i++) { 01071 pointAssociateToMap(&laserCloudFullRes->points[i], &laserCloudFullRes->points[i]); 01072 } 01073 01074 sensor_msgs::PointCloud2 laserCloudFullRes3; 01075 pcl::toROSMsg(*laserCloudFullRes, laserCloudFullRes3); 01076 laserCloudFullRes3.header.stamp = ros::Time().fromSec(timeLaserOdometry); 01077 laserCloudFullRes3.header.frame_id = "/camera_init"; 01078 pubLaserCloudFullRes.publish(laserCloudFullRes3); 01079 01080 geometry_msgs::Quaternion geoQuat = tf::createQuaternionMsgFromRollPitchYaw 01081 (transformAftMapped[2], -transformAftMapped[0], -transformAftMapped[1]); 01082 01083 odomAftMapped.header.stamp = ros::Time().fromSec(timeLaserOdometry); 01084 odomAftMapped.pose.pose.orientation.x = -geoQuat.y; 01085 odomAftMapped.pose.pose.orientation.y = -geoQuat.z; 01086 odomAftMapped.pose.pose.orientation.z = geoQuat.x; 01087 odomAftMapped.pose.pose.orientation.w = geoQuat.w; 01088 odomAftMapped.pose.pose.position.x = transformAftMapped[3]; 01089 odomAftMapped.pose.pose.position.y = transformAftMapped[4]; 01090 odomAftMapped.pose.pose.position.z = transformAftMapped[5]; 01091 odomAftMapped.twist.twist.angular.x = transformBefMapped[0]; 01092 odomAftMapped.twist.twist.angular.y = transformBefMapped[1]; 01093 odomAftMapped.twist.twist.angular.z = transformBefMapped[2]; 01094 odomAftMapped.twist.twist.linear.x = transformBefMapped[3]; 01095 odomAftMapped.twist.twist.linear.y = transformBefMapped[4]; 01096 odomAftMapped.twist.twist.linear.z = transformBefMapped[5]; 01097 pubOdomAftMapped.publish(odomAftMapped); 01098 01099 aftMappedTrans.stamp_ = ros::Time().fromSec(timeLaserOdometry); 01100 aftMappedTrans.setRotation(tf::Quaternion(-geoQuat.y, -geoQuat.z, geoQuat.x, geoQuat.w)); 01101 aftMappedTrans.setOrigin(tf::Vector3(transformAftMapped[3], 01102 transformAftMapped[4], transformAftMapped[5])); 01103 tfBroadcaster.sendTransform(aftMappedTrans); 01104 01105 /*sensor_msgs::PointCloud2 pc12; 01106 pcl::toROSMsg(*laserCloudCornerStack, pc12); 01107 pc12.header.stamp = ros::Time().fromSec(timeLaserOdometry); 01108 pc12.header.frame_id = "/camera"; 01109 pub1.publish(pc12); 01110 01111 sensor_msgs::PointCloud2 pc22; 01112 pcl::toROSMsg(*laserCloudSurfStack, pc22); 01113 pc22.header.stamp = ros::Time().fromSec(timeLaserOdometry); 01114 pc22.header.frame_id = "/camera"; 01115 pub2.publish(pc22); 01116 01117 sensor_msgs::PointCloud2 pc32; 01118 pcl::toROSMsg(*laserCloudSel, pc32); 01119 pc32.header.stamp = ros::Time().fromSec(timeLaserOdometry); 01120 pc32.header.frame_id = "/camera"; 01121 pub3.publish(pc32); 01122 01123 sensor_msgs::PointCloud2 pc42; 01124 pcl::toROSMsg(*laserCloudProj, pc42); 01125 pc42.header.stamp = ros::Time().fromSec(timeLaserOdometry); 01126 pc42.header.frame_id = "/camera"; 01127 pub4.publish(pc42);*/ 01128 } 01129 } 01130 01131 status = ros::ok(); 01132 rate.sleep(); 01133 } 01134 01135 return 0; 01136 }
[ "bminei@hawaii.edu" ]
bminei@hawaii.edu
c2049cecf62d185ba90f37a51bc37710b7832071
468425dd1ea71fe9387a0b02c5b1577d4cc901f5
/multibody/parsing/detail_composite_parse.cc
1e857e1f4331908aa8e537e67869dd5fd1c7cb98
[ "BSD-3-Clause" ]
permissive
byxrolland/drake
6fd03d75672229cae3ccff13dcb58f2c1332b555
7b588cca335e5536746766aa64ec19eda906e78b
refs/heads/master
2023-02-22T05:32:05.075439
2023-02-20T16:10:18
2023-02-20T16:10:18
295,498,558
0
0
NOASSERTION
2020-09-14T18:06:36
2020-09-14T18:06:36
null
UTF-8
C++
false
false
825
cc
#include "drake/multibody/parsing/detail_composite_parse.h" #include "drake/multibody/parsing/detail_select_parser.h" namespace drake { namespace multibody { namespace internal { std::unique_ptr<CompositeParse> CompositeParse::MakeCompositeParse( Parser* parser) { DRAKE_DEMAND(parser != nullptr); // This slightly odd spelling allows access to the private constructor. return std::unique_ptr<CompositeParse>(new CompositeParse(parser)); } CompositeParse::CompositeParse(Parser* parser) : resolver_(&parser->plant()), workspace_(parser->package_map(), parser->diagnostic_policy_, &parser->plant(), &resolver_, SelectParser) {} CompositeParse::~CompositeParse() { resolver_.Resolve(workspace_.diagnostic); } } // namespace internal } // namespace multibody } // namespace drake
[ "noreply@github.com" ]
noreply@github.com
d402cea1161a7b1c11a5da425c6efdb868fb88b7
de7e771699065ec21a340ada1060a3cf0bec3091
/core/src/test/org/apache/lucene/index/Test4GBStoredFields.cpp
472b9b01622c46900c0158afa0dff79013185e68
[]
no_license
sraihan73/Lucene-
0d7290bacba05c33b8d5762e0a2a30c1ec8cf110
1fe2b48428dcbd1feb3e10202ec991a5ca0d54f3
refs/heads/master
2020-03-31T07:23:46.505891
2018-12-08T14:57:54
2018-12-08T14:57:54
152,020,180
7
0
null
null
null
null
UTF-8
C++
false
false
4,141
cpp
using namespace std; #include "Test4GBStoredFields.h" namespace org::apache::lucene::index { using MockAnalyzer = org::apache::lucene::analysis::MockAnalyzer; using CompressingCodec = org::apache::lucene::codecs::compressing::CompressingCodec; using Document = org::apache::lucene::document::Document; using Field = org::apache::lucene::document::Field; using FieldType = org::apache::lucene::document::FieldType; using MMapDirectory = org::apache::lucene::store::MMapDirectory; using MockDirectoryWrapper = org::apache::lucene::store::MockDirectoryWrapper; using BytesRef = org::apache::lucene::util::BytesRef; using LuceneTestCase = org::apache::lucene::util::LuceneTestCase; using TimeUnits = org::apache::lucene::util::TimeUnits; using com::carrotsearch::randomizedtesting::annotations::TimeoutSuite; using com::carrotsearch::randomizedtesting::generators::RandomNumbers; using org::apache::lucene::util::LuceneTestCase::SuppressCodecs; // C++ TODO: Most Java annotations will not have direct C++ equivalents: // ORIGINAL LINE: @Nightly public void test() throws Exception void Test4GBStoredFields::test() { assumeWorkingMMapOnWindows(); shared_ptr<MockDirectoryWrapper> dir = make_shared<MockDirectoryWrapper>( random(), make_shared<MMapDirectory>(createTempDir(L"4GBStoredFields"))); dir->setThrottling(MockDirectoryWrapper::Throttling::NEVER); shared_ptr<IndexWriterConfig> iwc = make_shared<IndexWriterConfig>(make_shared<MockAnalyzer>(random())); iwc->setMaxBufferedDocs(IndexWriterConfig::DISABLE_AUTO_FLUSH); iwc->setRAMBufferSizeMB(256.0); iwc->setMergeScheduler(make_shared<ConcurrentMergeScheduler>()); iwc->setMergePolicy(newLogMergePolicy(false, 10)); iwc->setOpenMode(IndexWriterConfig::OpenMode::CREATE); // TODO: we disable "Compressing" since it likes to pick very extreme values // which will be too slow for this test. maybe we should factor out crazy // cases to ExtremeCompressing? then annotations can handle this stuff... if (random()->nextBoolean()) { iwc->setCodec(CompressingCodec::reasonableInstance(random())); } shared_ptr<IndexWriter> w = make_shared<IndexWriter>(dir, iwc); shared_ptr<MergePolicy> mp = w->getConfig()->getMergePolicy(); if (std::dynamic_pointer_cast<LogByteSizeMergePolicy>(mp) != nullptr) { // 1 petabyte: (std::static_pointer_cast<LogByteSizeMergePolicy>(mp)) ->setMaxMergeMB(1024 * 1024 * 1024); } shared_ptr<Document> *const doc = make_shared<Document>(); shared_ptr<FieldType> *const ft = make_shared<FieldType>(); ft->setStored(true); ft->freeze(); constexpr int valueLength = RandomNumbers::randomIntBetween(random(), 1 << 13, 1 << 20); const std::deque<char> value = std::deque<char>(valueLength); for (int i = 0; i < valueLength; ++i) { // random so that even compressing codecs can't compress it value[i] = static_cast<char>(random()->nextInt(256)); } shared_ptr<Field> *const f = make_shared<Field>(L"fld", value, ft); doc->push_back(f); constexpr int numDocs = static_cast<int>((1LL << 32) / valueLength + 100); for (int i = 0; i < numDocs; ++i) { w->addDocument(doc); if (VERBOSE && i % (numDocs / 10) == 0) { wcout << i << L" of " << numDocs << L"..." << endl; } } w->forceMerge(1); delete w; if (VERBOSE) { bool found = false; for (auto file : dir->listAll()) { if (file.endsWith(L".fdt")) { constexpr int64_t fileLength = dir->fileLength(file); if (fileLength >= 1LL << 32) { found = true; } wcout << L"File length of " << file << L" : " << fileLength << endl; } } if (!found) { wcout << L"No .fdt file larger than 4GB, test bug?" << endl; } } shared_ptr<DirectoryReader> rd = DirectoryReader::open(dir); shared_ptr<Document> sd = rd->document(numDocs - 1); assertNotNull(sd); assertEquals(1, sd->getFields().size()); shared_ptr<BytesRef> valueRef = sd->getBinaryValue(L"fld"); assertNotNull(valueRef); assertEquals(make_shared<BytesRef>(value), valueRef); rd->close(); delete dir; } } // namespace org::apache::lucene::index
[ "smamunr@fedora.localdomain" ]
smamunr@fedora.localdomain
29f2fb3fed94f7823b0fc5832792da1d4cf806b1
3852cea582d4c28edc3594244bccf01e8cb49047
/Project1/Sample.cpp
f58c0be13a8359f790281b30af63fd553d96b798
[]
no_license
akverma-kiit/OppsConcepts
1a4d9904758cbd0b9a6058af7552caed8249f004
bfb5330d8e1df91366d744d9e9cb3ad8c5a704aa
refs/heads/master
2021-01-02T05:23:58.611338
2020-07-18T06:13:57
2020-07-18T06:13:57
239,507,820
0
0
null
null
null
null
UTF-8
C++
false
false
1,931
cpp
#include "Sample.h" //Base Class int Base::m_BObjectCount = 0; Base::Base() : m_BNum(99) , m_BName("BASE_DEFAULT") { ++m_BObjectCount; m_BObjectNumber = m_BObjectCount; cout << "Base Class:: (" << m_BObjectNumber << ") Constructor(NULL)" << endl; } Base::~Base() { --m_BObjectCount; cout << "Base Class:: (" << m_BObjectNumber << ") Destructor()" << endl; } Base::Base(int num) : m_BNum(num) , m_BName("BASE_DEFAULT") { ++m_BObjectCount; m_BObjectNumber = m_BObjectCount; cout << "Base Class:: (" << m_BObjectNumber << ") Constructor(Integer,DFAULT)" << endl; } Base::Base(const std::string& name) : m_BNum(99) , m_BName(name) { ++m_BObjectCount; m_BObjectNumber = m_BObjectCount; cout << "Base Class:: (" << m_BObjectNumber << ") Constructor(DFAULT,String)" << endl; } Base::Base(int num, const std::string& name) : m_BNum(num) , m_BName(name) { ++m_BObjectCount; m_BObjectNumber = m_BObjectCount; cout << "Base Class:: (" << m_BObjectNumber << ") Constructor(Integer,String)" << endl; } /*Base::Base(std::initializer_list<int> a) { cout << "Base Class:: (" << m_BObjectNumber << ") Constructor(initializer_list List)" << endl; }*/ Base::Base(const Base& obj) : m_BNum(obj.m_BNum) , m_BName(obj.m_BName) { ++m_BObjectCount; m_BObjectNumber = m_BObjectCount; cout << "Base Class:: (" << m_BObjectNumber << ") Copy Constructor" << endl; } Base& Base::operator=(const Base& obj) { cout << "Base Class:: (" << m_BObjectNumber << ") Assignment Operator Overload" << endl; if (this == &obj) { cout << "Base Class:: Self Object Assignment Handle" << endl; return *this; } m_BNum = obj.m_BNum; m_BName = obj.m_BName; return *this; } int Base::GetObjectCount() { return m_BObjectCount; } int Base::GetObjectNumber() { return m_BObjectNumber; } int Base::GetNumber() { return m_BNum; } const std::string& Base::GetName() { return m_BName; }
[ "Ashish.Kumar3@infineon.com" ]
Ashish.Kumar3@infineon.com
3619d6e3f8f68c4c80476b10c366ab54167df9b9
beb11c85f823499bdce85a7b2f7a9192b45b8d6c
/problem_15.cpp
d173d5828aa2cc6e3ad67c62388b70e17fe140ad
[]
no_license
ghoshsoulib/oop-c-
f3fe419fc32105fd10466cb9645c21d5d16eae43
b06903ea48490eb4956db35ee9b9a66ba819d3f6
refs/heads/master
2021-09-10T09:39:36.046751
2018-03-23T19:20:27
2018-03-23T19:20:27
120,341,434
0
0
null
null
null
null
UTF-8
C++
false
false
2,494
cpp
#include<bits/stdc++.h> using namespace std; # define INF 0x3f3f3f3f // iPair ==> Integer Pair typedef pair<int, int> iPair; class Graph { int V; // Number of vertices list< pair<int, int> > *adj; public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int u, int v, int w); // Print MST using Prim's algorithm void primMST(); }; // Allocates memory for adjacency list Graph::Graph(int V) { this->V = V; adj = new list<iPair> [V]; } void Graph::addEdge(int u, int v, int w) { adj[u].push_back(make_pair(v, w)); adj[v].push_back(make_pair(u, w)); } // Prints shortest paths from src to all other vertices void Graph::primMST() { priority_queue< iPair, vector <iPair> , greater<iPair> > pq; int src = 0; // Taking vertex 0 as source vector<int> key(V, INF); // To store parent array which in turn store MST vector<int> parent(V, -1); // To keep track of vertices included in MST vector<bool> inMST(V, false); // Insert source itself in priority queue and initialize // its key as 0. pq.push(make_pair(0, src)); key[src] = 0; /* Looping till priority queue becomes empty */ while (!pq.empty()) { int u = pq.top().second; pq.pop(); inMST[u] = true; // Include vertex in MST // 'i' is used to get all adjacent vertices of a vertex list< pair<int, int> >::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) { int v = (*i).first; int weight = (*i).second; if (inMST[v] == false && key[v] > weight) { key[v] = weight; pq.push(make_pair(key[v], v)); parent[v] = u; } } } for (int i = 1; i < V; ++i) printf("%d - %d\n", parent[i], i); } int main() { int V ; cout << "Enter the number of vertices: "; cin >> V; Graph g(V); cout << "Enter the number of edge: "; int ed; cin >> ed; int i; for(i=0;i<ed;i++){ int a,b,c; cout << "Enter : starting edge : end edge : weight "; cin >> a >> b >> c; g.addEdge(a,b,c); } cout << "The MST is as follows\n\n"; g.primMST(); return 0; }
[ "noreply@github.com" ]
noreply@github.com
d9e9c8b73430acf002f945c5d3c16a9e3eab3dce
63f1efd54e45a5e78f23aef855a4e412754a6f42
/src/front_end/edge_spec/edge_spec.hpp
a9e4854cb92e5fb9b06a73bf47fd604370e220e8
[]
no_license
spirosn/znn-release
81d4be35c0c931f31fad5cb116992832bd19bac6
c08f9b86bb5a433e3df51df2bc983468135f1881
refs/heads/master
2021-01-17T14:12:32.457391
2015-08-21T16:59:37
2015-08-21T16:59:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,778
hpp
// // Copyright (C) 2014 Kisuk Lee <kisuklee@mit.edu> // ---------------------------------------------------------- // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // #ifndef ZNN_EDGE_SPEC_HPP_INCLUDED #define ZNN_EDGE_SPEC_HPP_INCLUDED #include <zi/zargs/parser.hpp> #include <boost/program_options.hpp> namespace zi { namespace znn { class edge_spec { public: const std::string name; vec3i size; // filter size std::string init_type; // weight initialization type std::string init_params; // parameters for weight initialization double eta; // learning rate double mom; // momentum double wc; // weight decay bool load; private: // for parsing configuration file boost::program_options::options_description desc_; public: #define TEXT_WRITE (std::ios::out) #define TEXT_READ (std::ios::in) void save( const std::string& path ) const { std::string fpath = path + name + ".spec"; std::ofstream fout(fpath.c_str(), TEXT_WRITE); fout << "[" << name << "]" << std::endl; fout << "size=" << vec3i_to_string(size) << std::endl; fout << "init_type=" << init_type << std::endl; fout << "init_params=" << init_params << std::endl; fout << "eta=" << eta << std::endl; fout << "mom=" << mom << std::endl; fout << "wc=" << wc << std::endl; fout.close(); } bool build( const std::string& path ) { std::ifstream fin(path.c_str(), TEXT_READ); if ( !fin ) return false; namespace po = boost::program_options; po::variables_map vm; po::store(po::parse_config_file(fin,desc_,true),vm); po::notify(vm); postprocess(vm); fin.close(); return true; } public: vec3i real_filter_size( const vec3i& sparse ) const { return (size - vec3i::one)*sparse + vec3i::one; } private: void initialize() { using namespace boost::program_options; desc_.add_options() ((name+".size").c_str(),value<std::string>()->default_value("1,1,1"),"size") ((name+".init_type").c_str(),value<std::string>(&init_type)->default_value("zero"),"init_type") ((name+".init_params").c_str(),value<std::string>(&init_params)->default_value(""),"init_params") ((name+".eta").c_str(),value<double>(&eta)->default_value(0.0),"eta") ((name+".mom").c_str(),value<double>(&mom)->default_value(0.0),"mom") ((name+".wc").c_str(),value<double>(&wc)->default_value(0.0),"wc") ((name+".load").c_str(),value<bool>(&load)->default_value(true),"load") ; } void postprocess( boost::program_options::variables_map& vm ) { zi::zargs_::parser<std::vector<std::size_t> > _parser; std::vector<std::size_t> target; std::string source; // size source = vm[name+".size"].as<std::string>(); if ( _parser.parse(&target,source) ) { size = vec3i(target[0],target[1],target[2]); } } public: edge_spec( const std::string& _name ) : name(_name) { initialize(); } }; // class edge_spec typedef boost::shared_ptr<edge_spec> edge_spec_ptr; }} // namespace zi::znn #endif // ZNN_EDGE_SPEC_HPP_INCLUDED
[ "kisuklee@mit.edu" ]
kisuklee@mit.edu
e714819df04dfdf2a312906b23b14cb356ba7208
f8aa6e689d132d660e71335552b37cc1a5cb0786
/HaveDone/大二暑假练习/多校联合比赛第九场数据+标程+解题报告/多校联合比赛第九场数据+标程+解题报告/Grid/standard1.cpp
75670fac574dca754daf5864289cc8144341c495
[]
no_license
VarickQ/ACM
91171f381fa57b6644f10b1a4a5a9aeaeeff12b2
5d4f2c14272b28c7ff2cb7ebcd4e91400345a096
refs/heads/master
2021-01-10T14:34:07.812097
2017-05-14T09:58:54
2017-05-14T09:58:54
8,500,751
4
1
null
null
null
null
UTF-8
C++
false
false
3,003
cpp
/* * Author: OpenSonata * Created Time: 2012/8/15 20:40:48 * File Name: yixiaohan.cpp */ #include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> #include <algorithm> #include <vector> #include <queue> #include <map> #include <set> #include <deque> #include <list> #include <stack> using namespace std; #define out(v) cerr << #v << ": " << (v) << endl #define SZ(v) ((int)(v).size()) const int maxint = -1u>>1; template <class T> bool get_max(T& a, const T &b) {return b > a? a = b, 1: 0;} template <class T> bool get_min(T& a, const T &b) {return b < a? a = b, 1: 0;} const int maxn = 1000 + 100; int CS, n, n1, n2, m, ans1, ans2; int f[maxn][maxn], g[maxn][maxn]; struct node { int pos, num; }a[maxn], b[maxn]; bool cmp1(node a, node b) { return a.pos < b.pos; } bool cmp2(node a, node b) { return a.pos > b.pos; } void solve() { sort(a + 1, a + n1 + 1, cmp1); sort(b + 1, b + n2 + 1, cmp2); memset(f, 127, sizeof(f)); memset(g, 127, sizeof(g)); f[0][0] = 0; for (int i = 1; i <= n1; i++) for (int j = 0; j <= a[i].pos; j++) { f[i][j] = f[i - 1][j]; if (j >= a[i].num) f[i][j] = min(f[i][j], f[i - 1][j - a[i].num] + 1); } g[0][n + 1] = 0; for (int i = 1; i <= n2; i++) for (int j = n + 1; j >= b[i].pos; j--) { g[i][j] = g[i - 1][j]; if (j + b[i].num <= n + 1) g[i][j] = min(g[i][j], g[i - 1][j + b[i].num] + 1); } ans1 = 0; ans2 = maxint; //for (int i = 1; i <= n; i++) printf("%d %d\n", f[n1][i], g[n2][i]); for (int i = n; i >= 0; i--) { if (f[n1][i] <= maxint / 2 || g[n2][n - i + 1] <= maxint / 2) { //out(f[n1][i]); out(g[n2][n - i + 1]); ans1 = i; break; } for (int j = 1; j < i; j++) if (f[n1][j] <= maxint / 2 && g[n2][n - (i - j) + 1] <= maxint / 2) { //out(f[n1][j]); out(g[n2][n - (i - j) + 1]); ans1 = i; break; } if (ans1 != 0) break; } for (int i = 0; i <= ans1; i++) { //out(f[n1][i]); out(g[n2][n - (ans1 - i) + 1]); if (f[n1][i] <= maxint / 2 && g[n2][n - (ans1 - i) + 1] <= maxint / 2){ ans2 = min(ans2, f[n1][i] + g[n2][n - (ans1 - i) + 1]); } } if (ans2 == maxint) ans2 = 0; } int main() { freopen("grid.in","r",stdin); freopen("std.out","w",stdout); scanf("%d", &CS); int cs = 0; while (CS--) { scanf("%d%d", &n, &m); n1 = 0; n2 = 0; for (int i = 0; i < m; i++) { int c, x, y; scanf("%d%d%d", &c, &x, &y); if (c == 1) { n1++; a[n1].pos = x; a[n1].num = y; } else { n2++; b[n2].pos = x; b[n2].num = y; } } solve(); printf("Case %d: %d %d\n", ++cs, ans1, ans2); } fclose(stdout); return 0; }
[ "varick.q.cj@gmail.com" ]
varick.q.cj@gmail.com
dfa16e4e58809068a0fa4b68d23756ce18b4ef08
52e448d61f2ad2a355babe8fe8f0c42ddf30f72e
/src/protocol.h
93ec60a134d6d01b3428d5b771e411792e7f7a81
[ "MIT" ]
permissive
fubendong2/innovationcoin
235a9718500fe91a8aa0364736c95aae31b619b6
3b85e5002ae189a82fd73b6cf3798539f8a7505d
refs/heads/master
2020-05-29T22:24:37.612437
2014-04-16T03:53:05
2014-04-16T03:53:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,472
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2011-2012 Litecoin Developers // Copyright (c) 2013 Innovationcoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef __cplusplus # error This header can only be compiled as C++. #endif #ifndef __INCLUDED_PROTOCOL_H__ #define __INCLUDED_PROTOCOL_H__ #include "serialize.h" #include "netbase.h" #include <string> #include "uint256.h" extern bool fTestNet; static inline unsigned short GetDefaultPort(const bool testnet = fTestNet) { return testnet ? 53883 : 33884; } extern unsigned char pchMessageStart[4]; /** Message header. * (4) message start. * (12) command. * (4) size. * (4) checksum. */ class CMessageHeader { public: CMessageHeader(); CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn); std::string GetCommand() const; bool IsValid() const; IMPLEMENT_SERIALIZE ( READWRITE(FLATDATA(pchMessageStart)); READWRITE(FLATDATA(pchCommand)); READWRITE(nMessageSize); READWRITE(nChecksum); ) // TODO: make private (improves encapsulation) public: enum { MESSAGE_START_SIZE=sizeof(::pchMessageStart), COMMAND_SIZE=12, MESSAGE_SIZE_SIZE=sizeof(int), CHECKSUM_SIZE=sizeof(int), MESSAGE_SIZE_OFFSET=MESSAGE_START_SIZE+COMMAND_SIZE, CHECKSUM_OFFSET=MESSAGE_SIZE_OFFSET+MESSAGE_SIZE_SIZE }; char pchMessageStart[MESSAGE_START_SIZE]; char pchCommand[COMMAND_SIZE]; unsigned int nMessageSize; unsigned int nChecksum; }; /** nServices flags */ enum { NODE_NETWORK = (1 << 0), }; /** A CService with information about it as peer */ class CAddress : public CService { public: CAddress(); explicit CAddress(CService ipIn, uint64 nServicesIn=NODE_NETWORK); void Init(); IMPLEMENT_SERIALIZE ( CAddress* pthis = const_cast<CAddress*>(this); CService* pip = (CService*)pthis; if (fRead) pthis->Init(); if (nType & SER_DISK) READWRITE(nVersion); if ((nType & SER_DISK) || (nVersion >= CADDR_TIME_VERSION && !(nType & SER_GETHASH))) READWRITE(nTime); READWRITE(nServices); READWRITE(*pip); ) void print() const; // TODO: make private (improves encapsulation) public: uint64 nServices; // disk and network only unsigned int nTime; // memory only int64 nLastTry; }; /** inv message data */ class CInv { public: CInv(); CInv(int typeIn, const uint256& hashIn); CInv(const std::string& strType, const uint256& hashIn); IMPLEMENT_SERIALIZE ( READWRITE(type); READWRITE(hash); ) friend bool operator<(const CInv& a, const CInv& b); bool IsKnownType() const; const char* GetCommand() const; std::string ToString() const; void print() const; // TODO: make private (improves encapsulation) public: int type; uint256 hash; }; #endif // __INCLUDED_PROTOCOL_H__
[ "root@AY140312183100304d80Z.(none)" ]
root@AY140312183100304d80Z.(none)
c001b606cc529d2b7ca912d3381a14e6476fffb7
7855535f7c711dc0379cb3e77f6633e5f1f07e0c
/evaluation/ConVul-CVE-Benchmarks/CVE-2016-7911/2016-7911.cpp
084afe379e2654a3cc2dc240c2838b691f6bfe18
[ "MIT" ]
permissive
wcventure/PERIOD
67ba17287e1dc18424fa8340ab2f41dc8398c3cc
cb8deb9a176e5bb292d70d46557dd61dc0e98069
refs/heads/main
2023-04-08T00:00:41.283989
2022-10-09T07:21:09
2022-10-09T07:21:09
447,953,443
23
4
null
null
null
null
UTF-8
C++
false
false
2,512
cpp
#include <stdio.h> #include <pthread.h> #include <unistd.h> #include <time.h> // #define TEST_TIME typedef struct { int counter; } atomic_t; #define spinlock_t pthread_mutex_t struct io_context { atomic_t nr_tasks; unsigned short ioprio; }; struct task_struct { struct io_context *io_context; spinlock_t alloc_lock; }; #define IOPRIO_CLASS_SHIFT (13) #define IOPRIO_PRIO_VALUE(class, data) (((class) << IOPRIO_CLASS_SHIFT) | data) enum { IOPRIO_CLASS_NONE, IOPRIO_CLASS_RT, IOPRIO_CLASS_BE, IOPRIO_CLASS_IDLE, }; #define IOPRIO_NORM (4) static inline void task_lock(struct task_struct *p) { pthread_mutex_lock(&p->alloc_lock); } static inline void task_unlock(struct task_struct *p) { pthread_mutex_unlock(&p->alloc_lock); } static inline void atomic_dec(atomic_t * v){ (v->counter)--; } int security_task_getioprio(struct task_struct *p) { return 0; } void put_io_context_active(struct io_context *ioc) { } static int get_task_ioprio(struct task_struct *p) { int ret; ret = security_task_getioprio(p); if (ret) goto out; ret = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_NONE, IOPRIO_NORM); if (p->io_context) { printf("p->io_context: %p\n", p->io_context); ret = p->io_context->ioprio; puts("after use"); } out: return ret; } void exit_io_context(struct task_struct *task) { struct io_context *ioc; task_lock(task); ioc = task->io_context; task->io_context = NULL; puts("NULL"); task_unlock(task); atomic_dec(&ioc->nr_tasks); put_io_context_active(ioc); } void* thread_one(void* args){ struct task_struct *p = (task_struct *)args; get_task_ioprio(p); puts("exit thread 1"); return NULL; } void* thread_two(void* args){ struct task_struct *p = (task_struct *)args; exit_io_context(p); puts("exit thread 2"); return NULL; } int main(){ #ifdef TEST_TIME static double run_time_begin; static double run_time_end; static double run_time_total; run_time_begin = clock(); #endif struct task_struct task_test; struct io_context ioc_test; ioc_test.ioprio = 1; pthread_mutex_init(&(task_test.alloc_lock), NULL); task_test.io_context = &ioc_test; pthread_t t1, t2; pthread_create(&t1, NULL, thread_one, &task_test); pthread_create(&t2, NULL, thread_two, &task_test); pthread_join(t1, NULL); pthread_join(t2, NULL); printf("\nprogram-successful-exit\n"); #ifdef TEST_TIME run_time_end = clock(); run_time_total = run_time_end - run_time_begin; printf("test-the-total-time: %.3lf\n", (double)(run_time_total/CLOCKS_PER_SEC)*1000); #endif return 0; }
[ "wencheng888888@163.com" ]
wencheng888888@163.com
d82ebc436ea84660e0df7e79cef816959577fab4
c2c9029e6da8c64045aea1f9134804ba88d88f32
/UVA/V-7/UVA 727.Cpp
ebc870bc6cea919e719cce17d180aa1810d1b8f0
[]
no_license
BRAINOOOO/CompetitiveProgramming
1056f8477fc98148e0c5982a25216889847c2a6c
2a58401de68bd8edea2c86e24193ef0453f38ec0
refs/heads/master
2021-07-04T11:59:55.341203
2019-02-14T23:00:46
2019-02-14T23:00:46
131,799,032
3
0
null
null
null
null
UTF-8
C++
false
false
4,736
cpp
/* explanation : here i will use stack as it is an easy data structure in implementing my logic first input should be ( , ) ,+,-,*,/, digit i will make 3 stacks one for digits , operators , brackets . i will assign each digit and sign to the number of bracket it belongs to it and i will assign each bracket to an index if it is open bracket ---> just add it to its stack with index = previous bracket idex + 1 closed bracket ----> i will print all the digits plus the operators that only belongs to this bracket Why ? bec the next operations may comes before the pervious ones so i will see when i come to them. digit -----> just add it to its stack with the index of the bracket it belongs to. operator ------> all the pervious operators belonging to the same bracket and have a higher periority must be done first after that insert it. complexity : O(n^2) */ #include <bits/stdc++.h> #define sz(v) ((int)(v).size()) #define all(v) ((v).begin()),((v).end()) #define allr(v) ((v).rbegin()),((v).rend()) #define pb push_back #define mp make_pair #define mt make_tuple #define clr(v,d) memset( v, d ,sizeof(v)) #define angle(n) atan2((n.imag()),(n.real())) #define vec(a,b) ((b)-(a)) #define length(a) hypot( (a.imag()),(a.real()) ) #define normalize(a) (a)/(length(a)) #define dp(a,b) (((conj(a))*(b)).real()) #define cp(a,b) (((conj(a))*(b)).imag()) #define lengthsqrt(a) dp(a,a) #define rotate0( a,ang) ((a)*exp( point(0,ang) )) #define rotateA(about,p,ang) (rotate0(vec(about,p),ang)+about) #define lcm(a,b) ((a*b)/(__gcd(a,b))) #define reflection0(m,v) (conj((v)/(m))*(m)) #define reflectionA(m,v,p0) (conj( (vec(p0,v))/(vec(p0,m)) ) * (vec(p0,m)) ) + p0 #define same(p1,p2) ( dp( vec(p1,p2),vec(p1,p2)) < eps ) #define point complex<double> typedef long long ll ; typedef unsigned long long ull; const double eps= (1e-10); using namespace std; int dcmp(double a,double b){ return fabs(a-b)<=eps ? 0: (a>b)? 1:-1 ;} int getBit(int num, int idx) {return ((num >> idx) & 1) == 1;} int setBit1(int num, int idx) {return num | (1<<idx);} int setBit0(int num, int idx) {return num & ~(1<<idx);} int flipBit(int num, int idx) {return num ^ (1<<idx);} int countNumBit1(int mask) {int ret=0; while (mask) {mask &= (mask-1);++ret; }return ret;} stack< pair<char,int> > s1,s2,s3; void fun1(int num,char sig) { string v1=""; while(!s1.empty()) { char val=s1.top().first; s1.pop(); v1=val+v1; } for(int i=0;i<sz(v1);i++) cout<<v1[i]; while(!s2.empty()) { int val=s2.top().second; if(val==num&&(((s2.top().first=='*'||s2.top().first=='/')&&(sig=='*'||sig=='/'))||(sig=='+'||sig=='-'))) { cout<<s2.top().first; s2.pop(); } else break; } } void fun3(int sig) { char presig; int br; if(!s2.empty()) { presig= s2.top().first; br= s2.top().second; } if(!(s2.empty())&&(br==s3.top().second)) { fun1(s3.top().second,sig); } s2.push(mp(sig,s3.top().second)); } int main() { int t; string bl; cin>>t; cin.ignore(); getline(cin,bl); for(int ts=0;ts<t;ts++) { if(ts>0) cout<<"\n"; s1=stack<pair<char,int> > (); s2=stack<pair<char,int> > (); s3=stack<pair<char,int> > (); string ch; string v=""; while(getline(cin,ch)) { if(ch=="") break; v+=(ch[0]); } if(sz(v)==0) { cout<<endl; continue; } v='('+v; v=v+')'; for(int i=0;i<sz(v);i++) { if(isdigit(v[i])) { s1.push(mp(v[i],s3.top().second)); } else if(v[i]=='(') { if(s3.empty()) { s3.push(mp(v[i],0)); } else { int ty=s3.top().second+1; s3.push(mp(v[i],ty)); } } else if(v[i]==')') { fun1(s3.top().second,'+'); // '+' just to print all the symbols s3.pop(); } else if(v[i]=='*'||v[i]=='/') { fun3(v[i]); } else if(v[i]=='+'||v[i]=='-') { fun3(v[i]); } } cout<<endl; } }
[ "noreply@github.com" ]
noreply@github.com
0a2cba2bd81c21648a79fb7b69dfc2fdaed6bc9b
f2f33c88da831f90a7740de3abeaeac6d2eb5d77
/leetcodeOJ/82_RemoveDuplicatesfromSortedListII.cpp
67151aa1d7048a273c72108359b22151d1cdd811
[]
no_license
fangjinxia/leetcodeOJ
537e4b9514c5b356d7ea5e6045fbc19cc85c46d7
3ad465f189ec6e649101c6ee9e42ef9988f9509b
refs/heads/master
2021-01-22T17:52:34.960033
2017-10-08T01:11:18
2017-10-08T01:11:18
85,039,265
0
0
null
null
null
null
UTF-8
C++
false
false
657
cpp
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* deleteDuplicates(ListNode* head) { if(head == NULL || head->next == NULL) return head; ListNode* p = head->next; int v = head->val; if(v != p->val){ head->next = deleteDuplicates(p); return head; } else{ while(p && p->val == v) p = p->next; return deleteDuplicates(p); } } };
[ "1173865548@qq.com" ]
1173865548@qq.com
eebde21a198a0a4cb0c50cbd2dbcaf60b3757ec3
ab350b170cf12aee36b0ebed48e436b96bacbc5e
/Sources/Audio/Flac/SoundBufferFlac.cpp
7a01414589f0b53269f9e071220802d881090ef3
[ "MIT" ]
permissive
Sondro/Acid
742398265684d5370423ce36bbb699dca3e9ee2f
3d66868256c8c0dcc50b661f5922be6f35481b1c
refs/heads/master
2023-04-13T00:02:51.727143
2020-01-31T13:52:45
2020-01-31T13:52:45
237,893,969
1
0
MIT
2023-04-04T01:37:35
2020-02-03T05:44:41
null
UTF-8
C++
false
false
1,169
cpp
#include "SoundBufferFlac.hpp" #if defined(ACID_BUILD_MACOS) #include <OpenAL/al.h> #else #include <al.h> #endif #include "Files/Files.hpp" #include "Maths/Time.hpp" //#define DR_FLAC_IMPLEMENTATION //#define DR_FLAC_NO_STDIO //#define DR_FLAC_NO_SIMD //#include "dr_flac.h" namespace acid { bool SoundBufferFlac::registered = Register(".flac"); void SoundBufferFlac::Load(SoundBuffer *soundBuffer, const std::filesystem::path &filename) { #if defined(ACID_DEBUG) auto debugStart = Time::Now(); #endif auto fileLoaded = Files::Read(filename); if (!fileLoaded) { Log::Error("SoundBuffer could not be loaded: ", filename, '\n'); return; } //soundBuffer->SetBuffer(buffer); #if defined(ACID_DEBUG) Log::Out("SoundBuffer ", filename, " loaded in ", (Time::Now() - debugStart).AsMilliseconds<float>(), "ms\n"); #endif } void SoundBufferFlac::Write(const SoundBuffer *soundBuffer, const std::filesystem::path &filename) { #if defined(ACID_DEBUG) auto debugStart = Time::Now(); #endif // TODO: Implement #if defined(ACID_DEBUG) Log::Out("SoundBuffer ", filename, " written in ", (Time::Now() - debugStart).AsMilliseconds<float>(), "ms\n"); #endif } }
[ "mattparks5855@gmail.com" ]
mattparks5855@gmail.com
5ab8012580be29034e2d2f63a255d55feaec9710
f701ca86b1d1f86086dc34cd4879e43da4d719d4
/leetcode/18-4Sum.cpp
c67c41735af064ac281212fe100988eba51b7bb6
[]
no_license
HUSTLX/leetcode
6adb45b64270bbcf8f7b21ef6e449bff10b81186
674fa5ab11ec0c585d94344cd4e36b4a787b584a
refs/heads/master
2021-01-10T17:42:42.943347
2016-03-14T14:12:17
2016-03-14T14:12:17
53,240,420
0
0
null
null
null
null
UTF-8
C++
false
false
1,195
cpp
#include <string> #include <stack> #include <vector> #include <map> #include <algorithm> using namespace std; vector<vector<int>> fourSum(vector<int>& nums, int target) { vector<vector<int>> res; sort(nums.begin(), nums.end()); int len = nums.size(); for (int i = 0; i < len; i++) { for (int j = i + 1; j < len; j++) { int third = j + 1, fouth = len - 1; while (third < fouth) { int sum = nums[i] + nums[j] + nums[third] + nums[fouth]; if (target == sum) { vector<int> temp = { nums[i],nums[j],nums[third],nums[fouth] }; res.push_back(temp); while (third < fouth && nums[third] == temp[2]) third++; while (third < fouth && nums[fouth] == temp[3]) fouth--; } else sum < target ? third++ : fouth--; } while ((j + 1 < len) && nums[j] == nums[j + 1]) j++; } while ((i + 1 < len) && nums[i] == nums[i + 1]) i++; } return res; } int main() { vector<int> nums = { 1,0,-1,0,-2,2 }; int target = 0; vector<vector<int>> res = fourSum(nums, target); }
[ "1508338149@qq.com" ]
1508338149@qq.com
1b59120f2f5c411d148c4a257f0abe99ad0073a1
54c73dd6fd1445ab149f318711ff3666484f957f
/src/brevity/ref/HTTP.cpp
421b902e24c8eccaf9f55156e58bf5488b86b62b
[ "MIT" ]
permissive
LegalizeAdulthood/cimple
73063f0d5d646aa03b252038968de7a9c0ddbc3a
5ec70784f2ee3e455a2258f82b07c0dacccb4093
refs/heads/master
2016-09-06T11:20:36.389814
2014-11-23T16:51:46
2014-11-24T18:12:40
25,265,255
4
0
null
null
null
null
UTF-8
C++
false
false
10,131
cpp
/* **============================================================================== ** ** Copyright (c) 2003, 2004, 2005, 2006, Michael Brasher, Karl Schopmeyer ** ** 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 "HTTP.h" #include <cctype> CIMPLE_NAMESPACE_BEGIN static const uint8 _is_uri[256] = { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,0,1,1,1,1,1,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1, 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0, 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, }; static const char* _uri_str[256] = { "%00", "%01", "%02", "%03", "%04", "%05", "%06", "%07", "%08", "%09", "%0A", "%0B", "%0C", "%0D", "%0E", "%0F", "%10", "%11", "%12", "%13", "%14", "%15", "%16", "%17", "%18", "%19", "%1A", "%1B", "%1C", "%1D", "%1E", "%1F", "%20", "%21", "%22", "%23", "%24", "%25", "%26", "%27", "%28", "%29", "%2A", "%2B", "%2C", "%2D", "%2E", "%2F", "%30", "%31", "%32", "%33", "%34", "%35", "%36", "%37", "%38", "%39", "%3A", "%3B", "%3C", "%3D", "%3E", "%3F", "%40", "%41", "%42", "%43", "%44", "%45", "%46", "%47", "%48", "%49", "%4A", "%4B", "%4C", "%4D", "%4E", "%4F", "%50", "%51", "%52", "%53", "%54", "%55", "%56", "%57", "%58", "%59", "%5A", "%5B", "%5C", "%5D", "%5E", "%5F", "%60", "%61", "%62", "%63", "%64", "%65", "%66", "%67", "%68", "%69", "%6A", "%6B", "%6C", "%6D", "%6E", "%6F", "%70", "%71", "%72", "%73", "%74", "%75", "%76", "%77", "%78", "%79", "%7A", "%7B", "%7C", "%7D", "%7E", "%7F", "%80", "%81", "%82", "%83", "%84", "%85", "%86", "%87", "%88", "%89", "%8A", "%8B", "%8C", "%8D", "%8E", "%8F", "%90", "%91", "%92", "%93", "%94", "%95", "%96", "%97", "%98", "%99", "%9A", "%9B", "%9C", "%9D", "%9E", "%9F", "%A0", "%A1", "%A2", "%A3", "%A4", "%A5", "%A6", "%A7", "%A8", "%A9", "%AA", "%AB", "%AC", "%AD", "%AE", "%AF", "%B0", "%B1", "%B2", "%B3", "%B4", "%B5", "%B6", "%B7", "%B8", "%B9", "%BA", "%BB", "%BC", "%BD", "%BE", "%BF", "%C0", "%C1", "%C2", "%C3", "%C4", "%C5", "%C6", "%C7", "%C8", "%C9", "%CA", "%CB", "%CC", "%CD", "%CE", "%CF", "%D0", "%D1", "%D2", "%D3", "%D4", "%D5", "%D6", "%D7", "%D8", "%D9", "%DA", "%DB", "%DC", "%DD", "%DE", "%DF", "%E0", "%E1", "%E2", "%E3", "%E4", "%E5", "%E6", "%E7", "%E8", "%E9", "%EA", "%EB", "%EC", "%ED", "%EE", "%EF", "%F0", "%F1", "%F2", "%F3", "%F4", "%F5", "%F6", "%F7", "%F8", "%F9", "%FA", "%FB", "%FC", "%FD", "%FE", "%FF", }; size_t HTTP::format_request_header( Buffer& out, const char* host, uint16 port, const char* cim_operation, const char* cim_method, const char* cim_object) { // Example: // // POST /cimom HTTP/1.1<CRLF> // HOST: localhost:8888<CRLF> // Content-Type: application/xml; charset="utf-8"<CRLF> // Content-Length: 0000000000<CRLF> // CIMOperation: MethodCall<CRLF> // CIMMethod: EnumerateInstances<CRLF> // CIMObject: root%2Fcimv2<CRLF> // <CRLF> // // POST header: out.append(STRLIT("POST /cimom HTTP/1.1\r\n")); // HOST header: { out.append(STRLIT("HOST: ")); encode_uri(out, host); out.append(':'); char buf[22]; size_t size; const char* s = uint16_to_str(buf, port, size); out.append(s, size); out.append(STRLIT("\r\n")); } // Content-Type: out.append(STRLIT("Content-Type: application/xml; charset=\"utf-8\"\r\n")); // Content-Length (to be filled in later). out.append(STRLIT("Content-Length: 0000000000\r\n")); size_t offset = out.size() - 12; // CIMOperation: { out.append(STRLIT("CIMOperation: ")); out.appends(cim_operation); out.append(STRLIT("\r\n")); } // CIMMethod: { out.append(STRLIT("CIMMethod: ")); out.appends(cim_method); out.append(STRLIT("\r\n")); } // CIMObject: { out.append(STRLIT("CIMObject: ")); encode_uri(out, cim_object); out.append(STRLIT("\r\n")); } // Blank line: out.append(STRLIT("\r\n")); return offset; } void HTTP::encode_uri(Buffer& out, const char* str) { while (*str) { uint8 c = *str++; if (_is_uri[c]) out.append(_uri_str[c], 3); else out.append(c); } } static inline size_t _find_content(char* s, size_t n) { // Content starts right after <CRLF><CRLF> sequence (or after <LF><LF> // on some non-conformant servers). char* p = s; for (;;) { if (n >= 4) { if (p[0] == '\r' && p[1] == '\n' && p[2] == '\r' && p[3] == '\n') { p[0] = '\0'; return (p + 4) - s; } if (p[0] == '\n' && p[1] == '\n') { p[0] = '\0'; return (p + 2) - s; } } else if (n >= 2) { if (p[0] == '\n' && p[1] == '\n') { p[0] = '\0'; return (p + 2) - s; } } else break; n--; p++; } // Not found! return 0; } static int _parse_hdr(HTTP_Message& hdr) { const char* s = hdr.buffer.data(); // Parse "HTTP/1.1 200 OK" line: const char* start = s; const char* end; if (find_token(start, "\r\n", start, end) == 0) { // Null terminate this token: const char* tok = start; start = end; if (*start) *((char*)start++) = '\0'; // Find start of status number: char* p = (char*)strchr(tok, ' '); if (!p) return -1; while (isspace(*p)) p++; // Seek end of status number: char* q = p; while (isdigit(*q)) q++; if (p == q) return -1; // Convert status number: if (strncmp(p, "200", 3) == 0) hdr.status = HTTP_STATUS_OK; else if (strncmp(p, "400", 3) == 0) hdr.status = HTTP_STATUS_BAD_REQUEST; else if (strncmp(p, "401", 3) == 0) hdr.status = HTTP_STATUS_UNAUTHORIZED; else if (strncmp(p, "403", 3) == 0) hdr.status = HTTP_STATUS_FORBIDDEN; else if (strncmp(p, "500", 3) == 0) hdr.status = HTTP_STATUS_INTERNAL_SERVER_ERROR; else if (strncmp(p, "501", 3) == 0) hdr.status = HTTP_STATUS_NOT_IMPLEMENTED; else if (strncmp(p, "503", 3) == 0) hdr.status = HTTP_STATUS_SERVICE_UNAVAILABLE; else return -1; } else return -1; // Parse individual headers (of the form "name: value"). while (find_token(start, "\r\n", start, end) == 0) { // Null-terminate token: char* tok = (char*)start; start = end; if (*start) *((char*)start++) = '\0'; // Find end of name: char* p = tok; while (*p && !isspace(*p) && *p != ':') p++; while (isspace(*p)) p++; if (*p != ':') return -1; *p++ = '\0'; // Find start of value: while (isspace(*p)) p++; if (*p == '\0') return -1; // Remove trailing space from value: for (char* q = (char*)end; q != p && isspace(q[-1]); ) *--q = '\0'; // Set header value: if (strcasecmp(tok, "Content-Type") == 0) hdr.content_type = p; else if (strcasecmp(tok, "Content-Length") == 0) { if (str_to_uint32(p, hdr.content_length) != 0) return -1; } else if (strcasecmp(tok, "CIMOperation") == 0) hdr.cim_operation = p; else if (strcasecmp(tok, "CIMError") == 0) hdr.cim_error = p; else if (strcasecmp(tok, "PGErrorDetail") == 0) hdr.pg_error_detail = p; } return 0; } int HTTP::send(Sock sock, const Buffer& req, HTTP_Message& rsp) { rsp.clear(); // Send request to server: if (Sockets::send_n(sock, req.data(), req.size()) != ssize_t(req.size())) return -1; // Read back response: char buf[BREVITY_BLOCK_SIZE]; for (;;) { ssize_t n = Sockets::recv(sock, buf, sizeof(buf)); if (n <= 0) return -1; rsp.buffer.append(buf, n); rsp.header_size = _find_content(rsp.buffer.data(), rsp.buffer.size()); if (rsp.header_size != 0) return _parse_hdr(rsp); } // Unreachable! return 0; } CIMPLE_NAMESPACE_END
[ "legalize@xmission.com" ]
legalize@xmission.com
b5863aeeb04cb06c652301f1f28ea2004986f97a
c13abd2fffc5a50ec9d734237d1f0bd619f3bcd4
/No.104 Maximum Depth of Binary Tree.cpp
e066acb897006eafd204af1a730f1b50932ebefc
[]
no_license
Jack-Wang-Personal/Leetcode-Notebook
a2c11e23153b8123421b4649db84559ff4f47b97
180dd7667be29a69a0b1c95f2c26a1fe7ff6eb4b
refs/heads/main
2023-05-04T01:05:48.282557
2021-05-08T16:22:06
2021-05-08T16:22:06
364,956,067
0
0
null
null
null
null
UTF-8
C++
false
false
598
cpp
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int dfs(TreeNode* root){ if(root==nullptr) return 0; return max(dfs(root->left),dfs(root->right))+1; } int maxDepth(TreeNode* root) { return dfs(root); } };
[ "noreply@github.com" ]
noreply@github.com
9f2953fde9c85dcab39aa2499a2fd2a9b0e53a83
0dac6250205dc785865271626e1652b9165a48a8
/practise/books.cpp
3cd8b8179d6ba2cd70a99e2fb75991ad302df413
[]
no_license
vsricharan16/cp
e8e23e10f541dbacedf1dc32101eae3e1242f242
900442795281072c490b99ef5dbb0aa4511b42a4
refs/heads/master
2021-09-15T12:42:38.857093
2018-06-01T18:01:19
2018-06-01T18:01:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,464
cpp
/*I shall rise*/ #include<bits/stdc++.h> using namespace std; #define rep(i,n) f(i,0,n) #define charan int main() #define vi vector< int > #define vl vector< ll > #define vii vector<pii> #define vll vector<pll> #define viii vector<tri> #define tri pair<int,pii> #define mod (1000*1000*1000+7) #define moddd (1000*1000*1000+9) #define ll long long #define pb push_back #define mp make_pair #define f(i,a,b) for(ll i=a;i<b;i++) #define fd(i,a,b) for(ll i=a;i>=b;i--) #define pii pair<int,int> #define pll pair< ll,ll > #define sz(a) a.size() #define pqueue priority_queue< ll > #define pdqueue priority_queue< int,vector <int>,greater< int > > #define ff first #define ss second #define min(a,b) ((a<b)?(a):(b)) #define max(a,b) ((a>b)?(a):(b)) #define gcd(a,b) __gcd((a),(b)) #define lcm(a,b) ((a)*(b)) / gcd((a),(b)) #define ms0(X,a) memset((X), a, sizeof((X))) #define gdb(n) cout<<">>"<<n<<"<<"<<endl //setbase - cout << setbase (16); cout << 100 << endl; Prints 64 //setprecision - cout << setprecision (4) << f << endl; Prints x.xxxx #define fast ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) const ll inf=1e18; const ll minf=-(1e18); charan { fast; ll n,t;cin>>n>>t; ll arr[n]; ms0(arr,0); cin>>arr[0];ll x; f(i,1,n){ cin>>x; arr[i]=x+arr[i-1]; } ll maxi=0; x=t; f(i,0,n){ if(i>0) x=t+arr[i-1]; auto it =upper_bound(arr+i,arr+1+n,x); maxi=max(maxi,it-arr-i); } cout<<maxi; return 0; }
[ "cs16btech11044@iith.ac.in" ]
cs16btech11044@iith.ac.in
14e0ff486e47e71d1a4a7920cb2aa471ee185f9f
4cf665e0de755d65edf5cf36f838ecc2f66a70ae
/main.cpp
ca08acec13981fad59b872b3e505ff484d128d40
[]
no_license
fatvlady/swaption_pricing
0d664ef849f333e7c8c4164ce7a2156056f40966
33385ec9bb347d8648f6dfb4af2ef62df04d4db8
refs/heads/master
2020-08-02T01:55:39.407211
2019-09-28T11:10:06
2019-09-28T11:10:06
211,199,216
0
0
null
null
null
null
UTF-8
C++
false
false
1,173
cpp
#include <pybind11/pybind11.h> #include <pybind11/numpy.h> #include <pybind11/stl.h> #include <pybind11/eigen.h> #include <Eigen/Dense> #include "swaption_exposure.hpp" namespace py = pybind11; using namespace py::literals; PYBIND11_MODULE(swaption_pricing, m) { auto swaption_exposure_noreturn = [](const std::vector<value_t>& swap_exposure, const std::vector<value_t>& sdf, const std::vector<int>& ex_indices, int maturity_index) { void(swaption_exposure(swap_exposure, sdf, ex_indices, maturity_index)); }; py::class_<inputs_holder>(m, "RollbackInputs") .def_readonly("swap_exposure", &inputs_holder::swap_exposure) .def_readonly("sdf", &inputs_holder::sdf) .def_readonly("ex_indices", &inputs_holder::ex_indices) .def_readonly("maturity_index", &inputs_holder::maturity_index); py::class_<outputs_holder>(m, "RollbackOutputs") .def_readonly("swaption_exposure", &outputs_holder::swaption_exposure) .def_readonly("npv", &outputs_holder::npv); m.def("setup", &setup, "paths"_a, "grid_size"_a, "ex_times_size"_a, "seed"_a); m.def("swaption_exposure", py::overload_cast<const inputs_holder&>(&swaption_exposure), "inputs"_a); }
[ "fatvlad.95@gmail.com" ]
fatvlad.95@gmail.com
cc1da59bb2983c7f05eade156c634d7041389869
be421434ecc56f6495f54fb91f8452a68711212a
/DirectProgramming/DPC++FPGA/ReferenceDesigns/qrd/src/qrd_demo.cpp
16052895160d97c083064ca54d24581248d91909
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
akertesz/oneAPI-samples
92a420d548b3e1a18346b972205326baacb84b7a
3e3995db508ae41b8d722cb3a833d732115b14bf
refs/heads/master
2023-04-20T01:20:15.452396
2021-04-28T17:28:58
2021-04-28T17:28:58
280,528,845
0
1
MIT
2020-07-17T21:31:27
2020-07-17T21:31:26
null
UTF-8
C++
false
false
9,316
cpp
// ============================================================== // Copyright Intel Corporation // // SPDX-License-Identifier: MIT // ============================================================= // // 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. // // This agreement shall be governed in all respects by the laws of the State of // California and by the laws of the United States of America. #include <math.h> #include <CL/sycl.hpp> #include <CL/sycl/INTEL/fpga_extensions.hpp> #include <chrono> #include <list> // dpc_common.hpp can be found in the dev-utilities include folder. // e.g., $ONEAPI_ROOT/dev-utilities//include/dpc_common.hpp #include "dpc_common.hpp" #include "qrd.hpp" using namespace std; using namespace std::chrono; using namespace sycl; // Run the modified Gram-Schmidt QR Decomposition algorithm on the given // matrices. The function will do the following: // 1. Transfer the input matrices to the FPGA. // 2. Run the algorithm. // 3. Copy the output data back to host device. // The above process is carried out 'reps' number of times. void QRDecomposition(vector<float> &in_matrix, vector<float> &out_matrix, queue &q, size_t matrices, size_t reps); int main(int argc, char *argv[]) { constexpr size_t kRandomSeed = 1138; constexpr size_t kRandomMin = 1; constexpr size_t kRandomMax = 10; constexpr size_t kAMatrixSizeFactor = ROWS_COMPONENT * COLS_COMPONENT * 2; constexpr size_t kQRMatrixSizeFactor = (ROWS_COMPONENT + 1) * COLS_COMPONENT * 3; constexpr size_t kIndexAccessFactor = 2; size_t matrices = argc > 1 ? atoi(argv[1]) : 1; if (matrices < 1) { cout << "Must run at least 1 matrix\n"; return 1; } try { #if defined(FPGA_EMULATOR) INTEL::fpga_emulator_selector device_selector; #else INTEL::fpga_selector device_selector; #endif queue q = queue(device_selector, dpc_common::exception_handler); device device = q.get_device(); cout << "Device name: " << device.get_info<info::device::name>().c_str() << "\n"; vector<float> a_matrix; vector<float> qr_matrix; a_matrix.resize(matrices * kAMatrixSizeFactor); qr_matrix.resize(matrices * kQRMatrixSizeFactor); // For output-postprocessing float q_matrix[ROWS_COMPONENT][COLS_COMPONENT][2]; float r_matrix[COLS_COMPONENT][COLS_COMPONENT][2]; cout << "Generating " << matrices << " random matri" << ((matrices == 1) ? "x " : "ces ") << "\n"; srand(kRandomSeed); for (size_t i = 0; i < matrices; i++) { for (size_t row = 0; row < ROWS_COMPONENT; row++) { for (size_t col = 0; col < COLS_COMPONENT; col++) { int random_val = rand(); float random_double = random_val % (kRandomMax - kRandomMin) + kRandomMin; a_matrix[i * kAMatrixSizeFactor + col * ROWS_COMPONENT * kIndexAccessFactor + row * kIndexAccessFactor] = random_double; int random_val_imag = rand(); random_double = random_val_imag % (kRandomMax - kRandomMin) + kRandomMin; a_matrix[i * kAMatrixSizeFactor + col * ROWS_COMPONENT * kIndexAccessFactor + row * kIndexAccessFactor + 1] = random_double; } } } QRDecomposition(a_matrix, qr_matrix, q, 1, 1); // Accelerator warmup #if defined(FPGA_EMULATOR) size_t reps = 2; #else size_t reps = 32; #endif cout << "Running QR decomposition of " << matrices << " matri" << ((matrices == 1) ? "x " : "ces ") << ((reps > 1) ? "repeatedly" : "") << "\n"; high_resolution_clock::time_point start_time = high_resolution_clock::now(); QRDecomposition(a_matrix, qr_matrix, q, matrices, reps); high_resolution_clock::time_point end_time = high_resolution_clock::now(); duration<double> diff = end_time - start_time; q.throw_asynchronous(); cout << " Total duration: " << diff.count() << " s" << "\n"; cout << "Throughput: " << reps * matrices / diff.count() / 1000 << "k matrices/s" << "\n"; list<size_t> to_check; // We will check at least matrix 0 to_check.push_back(0); // Spot check the last and the middle one if (matrices > 2) to_check.push_back(matrices / 2); if (matrices > 1) to_check.push_back(matrices - 1); cout << "Verifying results on matrix"; for (size_t matrix : to_check) { cout << " " << matrix; size_t idx = 0; for (size_t i = 0; i < COLS_COMPONENT; i++) { for (size_t j = 0; j < COLS_COMPONENT; j++) { if (j < i) r_matrix[i][j][0] = r_matrix[i][j][1] = 0; else { r_matrix[i][j][0] = qr_matrix[matrix * kQRMatrixSizeFactor + idx++]; r_matrix[i][j][1] = qr_matrix[matrix * kQRMatrixSizeFactor + idx++]; } } } for (size_t j = 0; j < COLS_COMPONENT; j++) { for (size_t i = 0; i < ROWS_COMPONENT; i++) { q_matrix[i][j][0] = qr_matrix[matrix * kQRMatrixSizeFactor + idx++]; q_matrix[i][j][1] = qr_matrix[matrix * kQRMatrixSizeFactor + idx++]; } } float acc_real = 0; float acc_imag = 0; float v_matrix[ROWS_COMPONENT][COLS_COMPONENT][2] = {{{0}}}; for (size_t i = 0; i < ROWS_COMPONENT; i++) { for (size_t j = 0; j < COLS_COMPONENT; j++) { acc_real = 0; acc_imag = 0; for (size_t k = 0; k < COLS_COMPONENT; k++) { acc_real += q_matrix[i][k][0] * r_matrix[k][j][0] - q_matrix[i][k][1] * r_matrix[k][j][1]; acc_imag += q_matrix[i][k][0] * r_matrix[k][j][1] + q_matrix[i][k][1] * r_matrix[k][j][0]; } v_matrix[i][j][0] = acc_real; v_matrix[i][j][1] = acc_imag; } } float error = 0; size_t count = 0; constexpr float kErrorThreshold = 1e-4; for (size_t row = 0; row < ROWS_COMPONENT; row++) { for (size_t col = 0; col < COLS_COMPONENT; col++) { if (std::isnan(v_matrix[row][col][0]) || std::isnan(v_matrix[row][col][1])) { count++; } float real = v_matrix[row][col][0] - a_matrix[matrix * kAMatrixSizeFactor + col * ROWS_COMPONENT * kIndexAccessFactor + row * kIndexAccessFactor]; float imag = v_matrix[row][col][1] - a_matrix[matrix * kAMatrixSizeFactor + col * ROWS_COMPONENT * kIndexAccessFactor + row * kIndexAccessFactor + 1]; if (sqrt(real * real + imag * imag) >= kErrorThreshold) { error += sqrt(real * real + imag * imag); count++; } } } if (count > 0) { cout << "\nFAILED\n"; cout << "\n" << "!!!!!!!!!!!!!! Error = " << error << " in " << count << " / " << ROWS_COMPONENT * COLS_COMPONENT << "\n"; return 1; } } cout << "\nPASSED\n"; return 0; } catch (sycl::exception const &e) { cerr << "Caught a synchronous SYCL exception: " << e.what() << "\n"; cerr << " If you are targeting an FPGA hardware, " "ensure that your system is plugged to an FPGA board that is " "set up correctly" << "\n"; cerr << " If you are targeting the FPGA emulator, compile with " "-DFPGA_EMULATOR" << "\n"; terminate(); } catch (std::bad_alloc const &e) { cerr << "Caught a memory allocation exception on the host: " << e.what() << "\n"; cerr << " You can reduce the memory requirement by reducing the number " "of matrices generated. Specify a smaller number when running the " "executable." << "\n"; cerr << " In this run, more than " << (((long long)matrices * (kAMatrixSizeFactor + kQRMatrixSizeFactor) * sizeof(float)) / pow(2, 30)) << " GBs of memory was requested for " << matrices << " matrices, each of size " << ROWS_COMPONENT << " x " << COLS_COMPONENT << "\n"; terminate(); } }
[ "noreply@github.com" ]
noreply@github.com
aa412c1fa68e032c0ed661a33ff6b2e7c17af1bf
95df2b2c66a3f0359ab624dd9723e6122879b2bd
/components/segmentation_platform/internal/execution/feature_aggregator_impl_unittest.cc
b401300f76d8734c91ca9de44ee90eeb6d48ccb7
[ "BSD-3-Clause" ]
permissive
HondryTravis/chromium
45804ef10a8d398341b3bc3d50097c59e9c55107
70d4e859f49563942f453e6f5fa5d021ced31fec
refs/heads/master
2023-05-13T11:38:42.056586
2021-06-18T05:33:41
2021-06-18T05:33:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,520
cc
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/segmentation_platform/internal/execution/feature_aggregator_impl.h" #include <cstdint> #include <memory> #include <vector> #include "base/test/simple_test_clock.h" #include "base/time/time.h" #include "components/segmentation_platform/internal/database/signal_database.h" #include "components/segmentation_platform/internal/execution/feature_aggregator.h" #include "components/segmentation_platform/internal/proto/aggregation.pb.h" #include "components/segmentation_platform/internal/proto/types.pb.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace segmentation_platform { class FeatureAggregatorImplTest : public testing::Test { public: FeatureAggregatorImplTest() = default; ~FeatureAggregatorImplTest() override = default; void SetUp() override { clock_.SetNow(base::Time::Now()); feature_aggregator_ = std::make_unique<FeatureAggregatorImpl>(); } base::SimpleTestClock clock_; std::unique_ptr<FeatureAggregatorImpl> feature_aggregator_; }; TEST_F(FeatureAggregatorImplTest, SumCountAggregation) { std::vector<SignalDatabase::Sample> samples; samples.emplace_back(std::make_pair(clock_.Now(), absl::make_optional(1))); samples.emplace_back(std::make_pair(clock_.Now(), absl::make_optional(2))); samples.emplace_back(std::make_pair(clock_.Now(), absl::make_optional(3))); std::vector<float> res = feature_aggregator_->Process( proto::SignalType::HISTOGRAM_VALUE, proto::Aggregation::SUM_COUNT, 1u, clock_.Now(), base::TimeDelta::FromSeconds(10), samples); // SUM_COUNT always produces a single value. EXPECT_EQ(1u, res.size()); // We should have counted 3 samples. EXPECT_EQ(3, res[0]); } TEST_F(FeatureAggregatorImplTest, SumValuesAggregation) { std::vector<SignalDatabase::Sample> samples; samples.emplace_back(std::make_pair(clock_.Now(), absl::make_optional(1))); samples.emplace_back(std::make_pair(clock_.Now(), absl::make_optional(2))); samples.emplace_back(std::make_pair(clock_.Now(), absl::make_optional(3))); std::vector<float> res = feature_aggregator_->Process( proto::SignalType::HISTOGRAM_VALUE, proto::Aggregation::SUM_VALUES, 1u, clock_.Now(), base::TimeDelta::FromSeconds(10), samples); // SUM_VALUES always produces a single value. EXPECT_EQ(1u, res.size()); // We should have summed up to 1+2+3=6. EXPECT_EQ(6, res[0]); } TEST_F(FeatureAggregatorImplTest, FilterEnumSamples) { std::vector<SignalDatabase::Sample> samples; samples.emplace_back(std::make_pair(clock_.Now(), absl::make_optional(1))); samples.emplace_back(std::make_pair(clock_.Now(), absl::make_optional(2))); samples.emplace_back(std::make_pair(clock_.Now(), absl::make_optional(3))); samples.emplace_back(std::make_pair(clock_.Now(), absl::make_optional(4))); samples.emplace_back(std::make_pair(clock_.Now(), absl::make_optional(5))); // Empty accept list should keep all samples. feature_aggregator_->FilterEnumSamples(std::vector<uint32_t>(), samples); EXPECT_EQ(5u, samples.size()); // Only accept 1 and 3 as enum values. feature_aggregator_->FilterEnumSamples(std::vector<uint32_t>{2, 4}, samples); EXPECT_EQ(2u, samples.size()); EXPECT_EQ(2, samples[0].second.value()); EXPECT_EQ(4, samples[1].second.value()); } } // namespace segmentation_platform
[ "chromium-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
a65b6ba7013942a33b7af8aea69379d601e85dd3
836d70d9ec052016d32c9ad46c65ce0e1ea64275
/ISSHEIMDALL/Equipment.h
c91098cccc43c0bc6c050f70242b439bd3e82475
[]
no_license
Anttir12/Heimdall
e4801103b2fa2553358606471e58d2383a16acf0
b7d1fea49d0e4af38e7a0221752db4dfec7dc28e
refs/heads/master
2016-09-01T11:12:35.970186
2015-12-28T14:54:09
2015-12-28T14:54:09
48,696,959
1
0
null
null
null
null
UTF-8
C++
false
false
809
h
#pragma once #include "Firing.h" #include <iostream> class Equipment { public: bool ownsSingle(); bool ownsBurst(); bool ownsAutoMode(); bool ownsType(int type); //TODO: rename? void set(FiringMode* mode); FiringModeSemi* getSingle() {return single;} FiringModeBurst* getBurst(){return burst;} FiringModeAuto* getAuto(){return autoMode;} void setSingle(FiringModeSemi* semi){ single = semi; } void setBurst(FiringModeBurst* burst_){ burst = burst_; } void setAuto(FiringModeAuto* auto_){ autoMode = auto_; } void increasaeMaxHP(int amount = 1){ maxHP += amount; } int maxHP = 10; bool ownsMissiles(){ return missile; } void setMissile(bool b){ missile = b; } private: bool missile = true; FiringModeSemi* single = NULL; FiringModeBurst* burst = NULL; FiringModeAuto* autoMode = NULL; };
[ "antti.ruohisto@gmail.com" ]
antti.ruohisto@gmail.com
32896e063ccddcc58d351febe8aed89ea3b1863b
370c837b55607d7936b81e87600c7bc23f6fe511
/source/h/ctltr029.h
adab6149063913bd3956bf1f77167e9030254611
[ "Apache-2.0", "LicenseRef-scancode-public-domain", "MIT" ]
permissive
xhz926/twain_library
6cb1b7d164d5c373ab5c74551838db46c4a845ae
a92d29f67fb899bde048cccfc79a016cc17e283d
refs/heads/master
2020-09-20T16:18:56.283745
2019-08-31T17:35:52
2019-08-31T17:35:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,339
h
/* This file is part of the Dynarithmic TWAIN Library (DTWAIN). Copyright (c) 2002-2019 Dynarithmic Software. 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. FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY DYNARITHMIC SOFTWARE. DYNARITHMIC SOFTWARE DISCLAIMS THE WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. */ #ifndef CTLTR029_H_ #define CTLTR029_H_ #include "ctltrp.h" namespace dynarithmic { class CTL_SetupMemXferTriplet : public CTL_TwainTriplet { public: CTL_SetupMemXferTriplet(CTL_ITwainSession *pSession, CTL_ITwainSource* pSource); TW_SETUPMEMXFER * GetSetupMemXferBuffer() { return &m_SetupMemXfer; } private: TW_SETUPMEMXFER m_SetupMemXfer; }; } #endif
[ "paulm@dynarithmic.com" ]
paulm@dynarithmic.com
4d6c8577bc6b239a4ed80ebbe6c3e5140ddb2b48
f6439b5ed1614fd8db05fa963b47765eae225eb5
/sync/api/attachments/attachment_service_impl.h
496af69638484b7f770e3976e4ae5b4031e88d98
[ "BSD-3-Clause" ]
permissive
aranajhonny/chromium
b8a3c975211e1ea2f15b83647b4d8eb45252f1be
caf5bcb822f79b8997720e589334266551a50a13
refs/heads/master
2021-05-11T00:20:34.020261
2018-01-21T03:31:45
2018-01-21T03:31:45
118,301,142
2
0
null
null
null
null
UTF-8
C++
false
false
3,834
h
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SYNC_API_ATTACHMENTS_ATTACHMENT_SERVICE_IMPL_H_ #define SYNC_API_ATTACHMENTS_ATTACHMENT_SERVICE_IMPL_H_ #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/threading/non_thread_safe.h" #include "sync/api/attachments/attachment_downloader.h" #include "sync/api/attachments/attachment_service.h" #include "sync/api/attachments/attachment_service_proxy.h" #include "sync/api/attachments/attachment_store.h" #include "sync/api/attachments/attachment_uploader.h" namespace syncer { // Implementation of AttachmentService. class SYNC_EXPORT AttachmentServiceImpl : public AttachmentService, public base::NonThreadSafe { public: // |delegate| is optional delegate for AttachmentService to notify about // asynchronous events (AttachmentUploaded). Pass NULL if delegate is not // provided. AttachmentService doesn't take ownership of delegate, the pointer // must be valid throughout AttachmentService lifetime. // // |attachment_uploader| is optional. If null, attachments will never be // uploaded to the sync server and |delegate|'s OnAttachmentUploaded will // never be invoked. // // |attachment_downloader| is optional. If null, attachments will never be // downloaded. Only attachments in |attachment_store| will be returned from // GetOrDownloadAttachments. AttachmentServiceImpl(scoped_ptr<AttachmentStore> attachment_store, scoped_ptr<AttachmentUploader> attachment_uploader, scoped_ptr<AttachmentDownloader> attachment_downloader, Delegate* delegate); virtual ~AttachmentServiceImpl(); // Create an AttachmentServiceImpl suitable for use in tests. static scoped_ptr<syncer::AttachmentService> CreateForTest(); // AttachmentService implementation. virtual void GetOrDownloadAttachments(const AttachmentIdList& attachment_ids, const GetOrDownloadCallback& callback) OVERRIDE; virtual void DropAttachments(const AttachmentIdList& attachment_ids, const DropCallback& callback) OVERRIDE; virtual void StoreAttachments(const AttachmentList& attachments, const StoreCallback& callback) OVERRIDE; private: class GetOrDownloadState; void ReadDone(const scoped_refptr<GetOrDownloadState>& state, const AttachmentStore::Result& result, scoped_ptr<AttachmentMap> attachments, scoped_ptr<AttachmentIdList> unavailable_attachment_ids); void DropDone(const DropCallback& callback, const AttachmentStore::Result& result); void WriteDone(const StoreCallback& callback, const AttachmentStore::Result& result); void UploadDone(const AttachmentUploader::UploadResult& result, const AttachmentId& attachment_id); void DownloadDone(const scoped_refptr<GetOrDownloadState>& state, const AttachmentId& attachment_id, const AttachmentDownloader::DownloadResult& result, scoped_ptr<Attachment> attachment); const scoped_ptr<AttachmentStore> attachment_store_; // May be null. const scoped_ptr<AttachmentUploader> attachment_uploader_; // May be null. const scoped_ptr<AttachmentDownloader> attachment_downloader_; // May be null. Delegate* delegate_; // Must be last data member. base::WeakPtrFactory<AttachmentServiceImpl> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(AttachmentServiceImpl); }; } // namespace syncer #endif // SYNC_API_ATTACHMENTS_ATTACHMENT_SERVICE_IMPL_H_
[ "jhonnyjosearana@gmail.com" ]
jhonnyjosearana@gmail.com
e0be5c69febc625df83dac00f7fc5e63817dc606
5ec06dab1409d790496ce082dacb321392b32fe9
/clients/cpp-qt5/generated/client/OAIOrgApacheSlingScriptingJavaImplJavaScriptEngineFactoryInfo.h
7e245cd7f0015aacf98298bef1c8157a3d0395c8
[ "Apache-2.0" ]
permissive
shinesolutions/swagger-aem-osgi
e9d2385f44bee70e5bbdc0d577e99a9f2525266f
c2f6e076971d2592c1cbd3f70695c679e807396b
refs/heads/master
2022-10-29T13:07:40.422092
2021-04-09T07:46:03
2021-04-09T07:46:03
190,217,155
3
3
Apache-2.0
2022-10-05T03:26:20
2019-06-04T14:23:28
null
UTF-8
C++
false
false
2,495
h
/** * Adobe Experience Manager OSGI config (AEM) API * Swagger AEM OSGI is an OpenAPI specification for Adobe Experience Manager (AEM) OSGI Configurations API * * OpenAPI spec version: 1.0.0-pre.0 * Contact: opensource@shinesolutions.com * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ /* * OAIOrgApacheSlingScriptingJavaImplJavaScriptEngineFactoryInfo.h * * */ #ifndef OAIOrgApacheSlingScriptingJavaImplJavaScriptEngineFactoryInfo_H_ #define OAIOrgApacheSlingScriptingJavaImplJavaScriptEngineFactoryInfo_H_ #include <QJsonObject> #include "OAIOAIOrgApacheSlingScriptingJavaImplJavaScriptEngineFactoryProperties.h" #include <QString> #include "OAIObject.h" namespace OpenAPI { class OAIOrgApacheSlingScriptingJavaImplJavaScriptEngineFactoryInfo: public OAIObject { public: OAIOrgApacheSlingScriptingJavaImplJavaScriptEngineFactoryInfo(); OAIOrgApacheSlingScriptingJavaImplJavaScriptEngineFactoryInfo(QString json); ~OAIOrgApacheSlingScriptingJavaImplJavaScriptEngineFactoryInfo(); void init(); void cleanup(); QString asJson () override; QJsonObject asJsonObject() override; void fromJsonObject(QJsonObject json) override; OAIOrgApacheSlingScriptingJavaImplJavaScriptEngineFactoryInfo* fromJson(QString jsonString) override; QString* getPid(); void setPid(QString* pid); QString* getTitle(); void setTitle(QString* title); QString* getDescription(); void setDescription(QString* description); OAIOrgApacheSlingScriptingJavaImplJavaScriptEngineFactoryProperties* getProperties(); void setProperties(OAIOrgApacheSlingScriptingJavaImplJavaScriptEngineFactoryProperties* properties); QString* getBundleLocation(); void setBundleLocation(QString* bundle_location); QString* getServiceLocation(); void setServiceLocation(QString* service_location); virtual bool isSet() override; private: QString* pid; bool m_pid_isSet; QString* title; bool m_title_isSet; QString* description; bool m_description_isSet; OAIOrgApacheSlingScriptingJavaImplJavaScriptEngineFactoryProperties* properties; bool m_properties_isSet; QString* bundle_location; bool m_bundle_location_isSet; QString* service_location; bool m_service_location_isSet; }; } #endif /* OAIOrgApacheSlingScriptingJavaImplJavaScriptEngineFactoryInfo_H_ */
[ "cliffano@gmail.com" ]
cliffano@gmail.com
dac3b9c95a8f41397210a9000a137d77d151ff24
0841c948188711d194835bb19cf0b4dae04a5695
/p2pserver_v2/pushserver/src/updater.cc
878ec9ffd4fe3e269023d0e0744c15ca271d7484
[]
no_license
gjhbus/sh_project
0cfd311b7c0e167e098bc4ec010822f1af2d0289
1d4d7df4e92cff93aba9d28226d3dbce71639ed6
refs/heads/master
2020-06-15T16:11:33.335499
2016-06-15T03:41:22
2016-06-15T03:41:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,251
cc
#include <string> #include <sys/socket.h> #include <arpa/inet.h> #include <netdb.h> #include "updater.h" #include "stats.h" #include "define.h" #include "util.h" #include "../../jeep/jeep.h" #include <boost/bind.hpp> #include <boost/thread.hpp> //const size_t temp_ip_list_size = 14; //const size_t temp_ip_list_size = 6; const size_t temp_ip_list_size = 1; //static std::string temp_ip_list[temp_ip_list_size] = {"10.10.52.5", "10.10.52.63", "10.10.52.64", "10.10.52.65", "10.10.53.24", "10.10.53.25"}; //static std::string temp_ip_list[temp_ip_list_size] = {"10.10.52.5", "10.10.52.63", "10.10.52.64", "10.10.52.65", "10.10.53.24", "10.10.53.25"}; static std::string temp_ip_list[temp_ip_list_size] = {"10.10.52.2"}; /* { "10.10.52.1", "10.10.52.2", "10.10.52.3", "10.10.52.4", "10.10.52.5", "10.10.52.63", "10.10.52.64", "10.10.52.65", "10.10.53.24", "10.10.53.25", "10.10.77.20", "10.10.77.22", "10.10.77.197", "10.10.83.199" }; */ static LOG_QUEUE* qlog = NULL; Updater* g_updater = NULL; Updater::Updater() { } Updater::~Updater() { } int Updater::Init() { qlog = create_log_queue(); if (NULL == qlog) { fprintf(stderr, "init updater log error, errno: %d %m\n", errno); return -1; } int num_retry = 0; while (num_retry++ < 5) { if ( 0 == UpdateServerList()) { return 0; } } return -1; } int Updater::CreateSocket(const char* host, const char* service) { struct addrinfo hints; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; struct addrinfo *res = NULL; struct addrinfo *ressave = NULL; int ret = getaddrinfo(host, service, &hints, &res); if (0 != ret) { slog_err_t_w(qlog, "CreateSocket error for %s, %s: %s", host, service, gai_strerror(ret)); return -1; } ressave = res; int sockfd = -1; do { sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if (sockfd < 0) { close(sockfd); continue; } if ( 0 == connect(sockfd, res->ai_addr, res->ai_addrlen)) { break; } else { close(sockfd); sockfd = -1; slog_err_t_w(qlog, "connect failed"); } } while ( NULL != (res = res->ai_next)); if (NULL == res) { slog_err_t_w(qlog, "CreateSocket error for %s, %s", host, service); return -1; } freeaddrinfo(ressave); return sockfd; } int Updater::CreateSocket(char* ip, int port) { int sockfd = socket(AF_INET, SOCK_STREAM, 0); if (-1 == sockfd) { close(sockfd); slog_err_t_w(qlog, "create socket failed, errno %d\n", errno); return -1; } struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr(ip); addr.sin_port = htons(port); if (0 != connect(sockfd, (struct sockaddr *) &addr, sizeof(struct sockaddr))) { close(sockfd); slog_err_t_w(qlog, "connect failed, errno %d %m\n", errno); return -1; } return sockfd; }; int Updater::SendRequest(int sockfd) { char buffer[1024] = {0}; Head *h = (Head *) (buffer); h->pkglen = sizeof(Head); h->stx = kSohuP2pStx; h->cmd = kGetStatsListCmd; int rs = send(sockfd, buffer, h->pkglen, 0); if (rs == h->pkglen) { return 0; } return -1; }; int Updater::UpdateServerList() { int sockfd = CreateSocket("dispatch.hd.sohu.com", "80"); if ( 0 != SendRequest(sockfd) ) { slog_info_t_w(qlog, "send navigate request failed, errno %u, %m\n", errno); close(sockfd); return -1; } char recv_buffer[1024] = {0}; int recv_size = recv(sockfd, recv_buffer, 1024, 0); if (recv_size < 0 ) { slog_err_t_w(qlog, "recv failed, errno %u, %m", errno); close(sockfd); return -1; } if ( recv_size < (int)sizeof(Head)) { slog_err_t_w(qlog, "recv_size(%d) is less than head size(%lu)\n", recv_size, sizeof(Head)); close(sockfd); return -1; } Head* head = (Head*) recv_buffer; if (recv_size != head->pkglen) { slog_err_t_w(qlog, "invalid package, recv_size:%u, pkglen:%u", recv_size, head->pkglen); close(sockfd); return -1; } if (kGetStatsListCmd != head->cmd ) { slog_err_t_w(qlog, "invalid response cmd: %u", head->cmd); close(sockfd); return -1; } StatsResponse* stats_resp = (StatsResponse*)(recv_buffer + sizeof(Head)); std::vector<std::string> vec; StrIpSet temp_set; for (uint32_t i = 0; i < stats_resp->ip_num; ++i) { temp_set.insert( Util::Int2Ip( ntohl(stats_resp->ip_list[i]) ) ); } int next_index = (index_ + 1) % 2; temp_set.swap(server_set_[next_index]); index_ = next_index; StrIpSet::iterator it = server_set_[next_index].begin(); for (; it != server_set_[next_index].end(); ++it) { slog_info_t_w(qlog, "stats_ip:%s", it->c_str()); } close(sockfd); return 0; } void Updater::UpdaterThreadFunc() { // TODO: create socket connection sleep(300); while (1) { if ( 0 != UpdateServerList() ) { sleep(3); continue; } if(IsServerListChanged()) { Notify(); } sleep(300);//sleep 5 minutes } return; } void Updater::Start() { boost::thread update_server_list_thread(boost::bind(&Updater::UpdaterThreadFunc, this)); return ; } int Updater::IsServerListChanged() { size_t next_index = (index_ + 1) % 2; StrIpSet::iterator it = server_set_[index_].begin(); for(; it != server_set_[index_].end(); ++it) { if (server_set_[next_index].end() == server_set_[next_index].find(*it)) { return 1; } } return 0; } const StrIpSet& Updater::GetServerList() { return server_set_[index_]; } bool Updater::Exist(const std::string& ip) { StrIpSet::iterator it = server_set_[index_].find(ip); return server_set_[index_].end() == it ? false : true; } void Updater::Notify() { if (NULL != g_stats) { g_stats->Update(); } }
[ "greatmiffa@gmail.com" ]
greatmiffa@gmail.com
79d117f7b0479eb53b57731067071d021082c98d
521685507e5b26ec9be38b39a249bdc1ee638138
/Servers/ServerManager/vtkSMDocumentation.h
6c492b918bad1f9644cbd5511fa1dc03546e282c
[ "LicenseRef-scancode-paraview-1.2" ]
permissive
matthb2/ParaView-beforekitwareswtichedtogit
6ad4662a1ad8c3d35d2c41df209fc4d78b7ba298
392519e17af37f66f6465722930b3705c1c5ca6c
refs/heads/master
2020-04-05T05:11:15.181579
2009-05-26T20:50:10
2009-05-26T20:50:10
211,087
1
2
null
null
null
null
UTF-8
C++
false
false
1,919
h
/*========================================================================= Program: ParaView Module: $RCSfile$ Copyright (c) Kitware, Inc. All rights reserved. See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkSMDocumentation - class providing access to the documentation // for a vtkSMProxy. // .SECTION Description // Every proxy defined in the server manager XML can have documentation // associated with it. This class provides access to the various types // of documentation text for every proxy. #ifndef __vtkSMDocumentation_h #define __vtkSMDocumentation_h #include "vtkSMObject.h" class vtkPVXMLElement; class VTK_EXPORT vtkSMDocumentation : public vtkSMObject { public: static vtkSMDocumentation* New(); vtkTypeRevisionMacro(vtkSMDocumentation, vtkSMObject); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Returns the text for long help, if any. NULL otherwise. const char* GetLongHelp(); // Description: // Returns the text for short help, if any. NULL otherwise. const char* GetShortHelp(); // Description: // Returns the description text, if any. const char* GetDescription(); // Description: // Get/Set the documentation XML element. void SetDocumentationElement(vtkPVXMLElement*); vtkGetObjectMacro(DocumentationElement, vtkPVXMLElement); protected: vtkSMDocumentation(); ~vtkSMDocumentation(); vtkPVXMLElement* DocumentationElement; private: vtkSMDocumentation(const vtkSMDocumentation&); // Not implemented. void operator=(const vtkSMDocumentation&); // Not implemented. }; #endif
[ "utkarsh.ayachit@kitware.com" ]
utkarsh.ayachit@kitware.com
d45cc068137d3a8dd2b6db9f6af32c7a686fc5b1
7d882a355a7c0454e3d502bcf13e77ea85e286b3
/program2/main.cpp
442c2d83f1a9a892369ddfdde4c3d011b594e2de
[ "MIT" ]
permissive
pwestrich/csc_4200
29218fa6ebde06c03f8afd9ac93175aade74c156
968599061edbb63a223345448a15e61602b115ae
refs/heads/master
2020-07-04T11:02:30.046543
2016-11-17T21:32:04
2016-11-17T21:32:04
74,069,255
0
0
null
null
null
null
UTF-8
C++
false
false
7,910
cpp
#include <cstdlib> #include <iostream> #include <string> #include "tictactoe.h" #include "NetworkServer.h" #include "NetworkClient.h" using namespace std; void playServer(); void playClient(); void playLocal(); const char *buildMoveMessage(const int move); int main(const int argc, const char **argv){ char input = '\0'; menu: cout << "Menu " << endl; cout << "--------------------" << endl; cout << "1. Start server " << endl; cout << "2. Connect to server" << endl; cout << "3. Play locally " << endl; cout << "Your choice: "; cin >> input; cin.ignore(1000, '\n'); switch (input){ case '1': { playServer(); break; } case '2': { playClient(); break; } case '3': { playLocal(); break; } default: { cout << "Invalid option: " << input << endl; goto menu; } } return 0; } void playServer(){ //ask the user what port to listen on int port = 0; while (port == 0){ cout << "What port would you like to listen on? "; cin >> port; if (port < 1024 || port > 32000){ cout << "Invalid port number: " << port << endl; port = 0; } } try { NetworkServer *server = new NetworkServer(port); cout << "Awaiting connection..." << endl; //wait for a connection server->accept(); cout << "Connection established." << endl; bool play = true; int input = -1; while (play){ TicTacToe *game = new TicTacToe(); while (true){ game->printBoard(); input = -1; //the server is always X and always goes first. while (input < 0 || input > 9){ cout << "X, enter a play (1 - 9): "; cin >> input; if (!game->xMove(input - 1)){ cout << "Invalid move. Try again." << endl; input = -1; } } //check for a win WinState win = game->isWin(); if (win == X_WINS){ server->sendMessage("WIN:X"); game->printBoard(); cout << "X wins!" << endl; break; } else if (win == O_WINS){ server->sendMessage("WIN:O"); game->printBoard(); cout << "O wins!" << endl; break; } else if (win == TIE){ server->sendMessage("WIN:T"); game->printBoard(); cout << "It's a tie!" << endl; break; } else { server->sendMessage(buildMoveMessage(input - 1)); } cout << "Waiting on client..." << endl; //wait on client to send its move const char *message = server->recieveMessage(); if (strncmp(message, "MOVE:", 5) == 0){ //get the move from it, and make the move int move = atoi(message + 5); if (!game->oMove(move)){ server->sendMessage("ERROR:Invalid move."); cerr << "Invalid move from the client: " << message << endl; exit(EXIT_FAILURE); } } else { server->sendMessage("ERROR:Invalid message."); cerr << "Invalid message: " << message << endl; exit(EXIT_FAILURE); } //check a win again win = game->isWin(); if (win == X_WINS){ server->sendMessage("WIN:X"); game->printBoard(); cout << "X wins!" << endl; break; } else if (win == O_WINS){ server->sendMessage("WIN:O"); game->printBoard(); cout << "O wins!" << endl; break; } else if (win == TIE){ server->sendMessage("WIN:T"); game->printBoard(); cout << "It's a tie!" << endl; break; } } delete game; char again; cout << "Would you like to play again? (y/n): "; cin >> again; //get the client message const char *message = server->recieveMessage(); if ((strncmp(message, "AGAIN", 5) == 0) && (again == 'y' || again == 'Y')){ server->sendMessage("AGAIN"); } else { //close connection server->sendMessage("CLOSE"); server->close(); play = false; } } delete server; } catch (runtime_error *it){ cerr << it->what() << endl; } } void playClient(){ try { //ask the user for a port and host to connect to int port = 0; char *hostname = new char[64]; memset(hostname, '\0', 64); cout << "What host would you like to connect to? "; cin.getline(hostname, '\n'); while (port == 0){ cout << "What port is the server listening on? "; cin >> port; if (port < 1024 || port > 32000){ cout << "Invalid port number: " << port << endl; port = 0; } } NetworkClient *client = new NetworkClient(port, hostname); client->connect(); bool play = true; int input = -1; while (play){ TicTacToe *game = new TicTacToe(); while (true){ cout << "Waiting on server..." << endl; //wait for the server to make a move const char *message = client->recieveMessage(); cerr << message << endl; if (strncmp(message, "MOVE:", 5) == 0){ //get the move and make it int move = atoi(message + 5); game->xMove(move); } else if (strncmp(message, "WIN:T", 5) == 0) { game->printBoard(); cout << "It's a tie!" << endl; break; } else if (strncmp(message, "WIN:", 4) == 0){ game->printBoard(); cout << message[4] << " wins!" << endl; break; } else { cerr << "Error: Invalid message received: " << message << endl; client->sendMessage("ERROR:Invalid command"); exit(EXIT_FAILURE); } //now make your move game->printBoard(); //the server is always X and always goes first. //the client is always O and goes second. while (input < 1 || input > 9){ cout << "O, enter a play (1 - 9): "; cin >> input; if (!game->oMove(input - 1)){ cout << "Invalid move. Try again." << endl; input = -1; } } //send it to the server client->sendMessage(buildMoveMessage(input - 1)); input = -1; } delete game; //now ask to play again char again; cout << "Would you like to play again? (y/n): "; cin >> again; if (again == 'y' || again == 'Y'){ client->sendMessage("AGAIN"); } else { //close connection client->sendMessage("CLOSE"); client->close(); play = false; } //get the server response const char *message = client->recieveMessage(); if (strncmp(message, "AGAIN", 5) != 0){ play = false; } } delete client; delete hostname; } catch (runtime_error *it){ cerr << it->what() << endl; } catch (invalid_argument *it){ cerr << it->what() << endl; } } //play a local game void playLocal(){ TicTacToe *game = new TicTacToe(); int input = -1; while (true){ //print board and ask X to play game->printBoard(); while (input < 0 || input > 9){ cout << "X, enter a play (1 - 9): "; cin >> input; if (!game->xMove(input - 1)){ cout << "Invalid move. Try again." << endl; input = -1; } } input = -1; //check for a win WinState win = game->isWin(); if (win == X_WINS){ game->printBoard(); cout << "X wins!" << endl; break; } else if (win == O_WINS){ game->printBoard(); cout << "O wins!" << endl; break; } else if (win == TIE){ game->printBoard(); cout << "It's a tie!" << endl; break; } //print board and ask O to move game->printBoard(); while (input < 0 || input > 9){ cout << "O, enter a play (1 - 9): "; cin >> input; if (!game->oMove(input - 1)){ cout << "Invalid move. Try again." << endl; input = -1; } } input = -1; //check for a winin again win = game->isWin(); if (win == X_WINS){ game->printBoard(); cout << "X wins!" << endl; break; } else if (win == O_WINS){ game->printBoard(); cout << "O wins!" << endl; break; } else if (win == TIE){ game->printBoard(); cout << "It's a tie!" << endl; break; } } //done delete game; } const char *buildMoveMessage(const int move){ char *value = new char[8]; strncpy(value, "MOVE:", 5); value[5] = '0' + move; value[6] = value[7] = '\0'; return value; }
[ "pwestrich@me.com" ]
pwestrich@me.com
979a63e8a6d2e9b4516e57bc33510f1f3aff0aaf
cae34387e29434d01b7f557d292a0614b4602065
/Master/lib/glimac/include/glimac/TrackballCamera.hpp
b38375525c725fe3bd18f847a34d1f587c6b4708
[]
no_license
Laefy/world_Imaker
de7b698fd01c37769060d37d44b643f4137761f2
9755aacbf5a17d91c3eb1552ed201ddb31b9219e
refs/heads/master
2020-11-27T19:53:41.240265
2019-12-20T11:22:56
2019-12-20T11:22:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,120
hpp
#pragma once #include <vector> #include "common.hpp" namespace glimac { class TrackballCamera { public: TrackballCamera(): m_fDistance(5.), m_fAngleX(0.), m_fAngleY(0.) { } float getDistance() { return m_fDistance; } float getAngleX() { return m_fAngleX; } float getAngleY() { return m_fAngleY; } void moveFront(float delta){ // if(delta > 0) { m_fDistance += delta; // } else } void rotateLeft(float degrees){ m_fAngleY += degrees; } void rotateUp(float degrees){ m_fAngleX += degrees; } glm::mat4 getViewMatrix() const { glm::mat4 ViewMatrix; ViewMatrix = glm::translate(ViewMatrix, glm::vec3(0, 0, -m_fDistance)); // Translation ViewMatrix = glm::rotate(ViewMatrix, glm::radians(m_fAngleX), glm::vec3(1, 0, 0)); // Rotation ViewMatrix = glm::rotate(ViewMatrix, glm::radians(m_fAngleY), glm::vec3(0, 1, 0)); // Rotation return ViewMatrix; } private: float m_fDistance; float m_fAngleX; float m_fAngleY; }; }
[ "clara.daigmorte@gmail.com" ]
clara.daigmorte@gmail.com
37b90a4152a9eed40f014bd118f8f54f001804c8
2590c8f9f8bee8dc8c288b994f3de4114015acc7
/lab_toturial/stage_demo/source/include/vmemory.h
da96292db39471dfcf9e0ad1e66dc3be7284266d
[]
no_license
shihao1007/c-chis-system-control
0d5871ab6c4d51025e4d81b41092e1c10d5723b0
f20dea4fc8bf8d674c67b64bcc1759618335a7ef
refs/heads/master
2020-04-23T17:23:03.150018
2019-09-05T05:38:17
2019-09-05T05:38:17
171,329,847
0
0
null
null
null
null
UTF-8
C++
false
false
916
h
#ifndef VMEMORY_H #define VMEMORY_H #include <Windows.h> #include <stdint.h> namespace tsi { namespace ips { template<class T> class VMemory { protected: void * p_buf_; uint64_t sz_; public: VMemory() { p_buf_ = NULL; sz_ = 0; } VMemory(uint64_t sz) { p_buf_ = NULL; sz_ = 0; resize(sz); } ~VMemory() { clear(); } void clear() { if (p_buf_) ::VirtualFree(p_buf_, 0, MEM_RELEASE); p_buf_ = 0; sz_ = 0; } void resize(uint64_t sz) { clear(); if (sz > 0) { p_buf_ = ::VirtualAlloc(0, (size_t) sizeof(T)*(size_t)sz, MEM_COMMIT, PAGE_READWRITE); if (p_buf_) sz_ = sz; } } T * data(){return (T *) p_buf_;} uint64_t size(){return sz_;} }; } } #endif
[ "shihao1007@gmail.com" ]
shihao1007@gmail.com
b378c2b166635aaefd9c1f52193d739922ed29a8
42bb012c72990cd720d9f694fa98bad40ddf5d7b
/MonitorDLL/MonitorDLL.h
18a96c1d49bd75b9f960898f86c4e2c8ca95f5c1
[]
no_license
yazici/NetAndSysMonitor
d636638c841350f6e7b7884d79db5fbf3912af02
f1c6fa64b2372ae5b3387bc791245ae59d46a7fa
refs/heads/master
2021-01-05T10:30:12.335251
2013-07-05T06:17:50
2013-07-05T06:17:50
null
0
0
null
null
null
null
GB18030
C++
false
false
432
h
// MonitorDLL.h : MonitorDLL DLL 的主头文件 // #pragma once #ifndef __AFXWIN_H__ #error "在包含此文件之前包含“stdafx.h”以生成 PCH 文件" #endif #include "resource.h" // 主符号 // CMonitorDLLApp // 有关此类实现的信息,请参阅 MonitorDLL.cpp // class CMonitorDLLApp : public CWinApp { public: CMonitorDLLApp(); // 重写 public: virtual BOOL InitInstance(); DECLARE_MESSAGE_MAP() };
[ "519916178@qq.com" ]
519916178@qq.com
7632e890b3adecdc90b4a66b81597320b57025bf
9a54ccea787e6568475a8ccbdfde25ca72dd8b04
/src/compiler/wasm-compiler.cc
8e136f23919b785f56b721bfcee4fbd6dc546f0d
[ "BSD-3-Clause", "Apache-2.0", "SunPro" ]
permissive
sahilrajput03/v8
11af8af1588fae3d70d30265cfa14afcf09df8e7
b2925688c3e50d9b6f8e3d761582218360ace989
refs/heads/master
2022-12-07T02:38:11.566474
2020-10-08T13:28:04
2020-10-09T02:16:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
329,416
cc
// Copyright 2015 the V8 project 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 "src/compiler/wasm-compiler.h" #include <memory> #include "src/base/optional.h" #include "src/base/platform/elapsed-timer.h" #include "src/base/platform/platform.h" #include "src/base/small-vector.h" #include "src/base/v8-fallthrough.h" #include "src/codegen/assembler-inl.h" #include "src/codegen/assembler.h" #include "src/codegen/code-factory.h" #include "src/codegen/compiler.h" #include "src/codegen/interface-descriptors.h" #include "src/codegen/optimized-compilation-info.h" #include "src/compiler/backend/code-generator.h" #include "src/compiler/backend/instruction-selector.h" #include "src/compiler/common-operator.h" #include "src/compiler/compiler-source-position-table.h" #include "src/compiler/diamond.h" #include "src/compiler/graph-assembler.h" #include "src/compiler/graph-visualizer.h" #include "src/compiler/graph.h" #include "src/compiler/int64-lowering.h" #include "src/compiler/linkage.h" #include "src/compiler/machine-operator.h" #include "src/compiler/node-matchers.h" #include "src/compiler/node-origin-table.h" #include "src/compiler/node-properties.h" #include "src/compiler/pipeline.h" #include "src/compiler/simd-scalar-lowering.h" #include "src/compiler/zone-stats.h" #include "src/execution/isolate-inl.h" #include "src/heap/factory.h" #include "src/logging/counters.h" #include "src/logging/log.h" #include "src/objects/heap-number.h" #include "src/roots/roots.h" #include "src/tracing/trace-event.h" #include "src/trap-handler/trap-handler.h" #include "src/utils/vector.h" #include "src/wasm/function-body-decoder-impl.h" #include "src/wasm/function-compiler.h" #include "src/wasm/graph-builder-interface.h" #include "src/wasm/jump-table-assembler.h" #include "src/wasm/memory-tracing.h" #include "src/wasm/object-access.h" #include "src/wasm/wasm-code-manager.h" #include "src/wasm/wasm-constants.h" #include "src/wasm/wasm-limits.h" #include "src/wasm/wasm-linkage.h" #include "src/wasm/wasm-module.h" #include "src/wasm/wasm-objects-inl.h" #include "src/wasm/wasm-opcodes-inl.h" namespace v8 { namespace internal { namespace compiler { namespace { #define FATAL_UNSUPPORTED_OPCODE(opcode) \ FATAL("Unsupported opcode 0x%x:%s", (opcode), \ wasm::WasmOpcodes::OpcodeName(opcode)); MachineType assert_size(int expected_size, MachineType type) { DCHECK_EQ(expected_size, ElementSizeInBytes(type.representation())); return type; } #define WASM_INSTANCE_OBJECT_SIZE(name) \ (WasmInstanceObject::k##name##OffsetEnd - \ WasmInstanceObject::k##name##Offset + 1) // NOLINT(whitespace/indent) #define WASM_INSTANCE_OBJECT_OFFSET(name) \ wasm::ObjectAccess::ToTagged(WasmInstanceObject::k##name##Offset) // We would like to use gasm_->Call() to implement this macro, // but this doesn't work currently when we try to call it from functions // which set IfSuccess/IfFailure control paths (e.g. within Throw()). // TODO(manoskouk): Maybe clean this up at some point? #define CALL_BUILTIN(name, ...) \ SetEffect(graph()->NewNode( \ mcgraph()->common()->Call(GetBuiltinCallDescriptor<name##Descriptor>( \ this, StubCallMode::kCallBuiltinPointer)), \ GetBuiltinPointerTarget(Builtins::k##name), ##__VA_ARGS__, effect(), \ control())) #define LOAD_INSTANCE_FIELD(name, type) \ gasm_->Load(assert_size(WASM_INSTANCE_OBJECT_SIZE(name), type), \ instance_node_.get(), WASM_INSTANCE_OBJECT_OFFSET(name)) #define LOAD_FULL_POINTER(base_pointer, byte_offset) \ gasm_->Load(MachineType::Pointer(), base_pointer, byte_offset) #define LOAD_TAGGED_POINTER(base_pointer, byte_offset) \ gasm_->Load(MachineType::TaggedPointer(), base_pointer, byte_offset) #define LOAD_TAGGED_ANY(base_pointer, byte_offset) \ gasm_->Load(MachineType::AnyTagged(), base_pointer, byte_offset) #define LOAD_FIXED_ARRAY_SLOT(array_node, index, type) \ gasm_->Load(type, array_node, \ wasm::ObjectAccess::ElementOffsetInTaggedFixedArray(index)) #define LOAD_FIXED_ARRAY_SLOT_SMI(array_node, index) \ LOAD_FIXED_ARRAY_SLOT(array_node, index, MachineType::TaggedSigned()) #define LOAD_FIXED_ARRAY_SLOT_PTR(array_node, index) \ LOAD_FIXED_ARRAY_SLOT(array_node, index, MachineType::TaggedPointer()) #define LOAD_FIXED_ARRAY_SLOT_ANY(array_node, index) \ LOAD_FIXED_ARRAY_SLOT(array_node, index, MachineType::AnyTagged()) #define STORE_RAW(base, offset, val, rep, barrier) \ STORE_RAW_NODE_OFFSET(base, gasm_->Int32Constant(offset), val, rep, barrier) #define STORE_RAW_NODE_OFFSET(base, node_offset, val, rep, barrier) \ gasm_->Store(StoreRepresentation(rep, barrier), base, node_offset, val) // This can be used to store tagged Smi values only. #define STORE_FIXED_ARRAY_SLOT_SMI(array_node, index, value) \ STORE_RAW(array_node, \ wasm::ObjectAccess::ElementOffsetInTaggedFixedArray(index), value, \ MachineRepresentation::kTaggedSigned, kNoWriteBarrier) // This can be used to store any tagged (Smi and HeapObject) value. #define STORE_FIXED_ARRAY_SLOT_ANY(array_node, index, value) \ STORE_RAW(array_node, \ wasm::ObjectAccess::ElementOffsetInTaggedFixedArray(index), value, \ MachineRepresentation::kTagged, kFullWriteBarrier) void EnsureEnd(MachineGraph* mcgraph) { Graph* g = mcgraph->graph(); if (g->end() == nullptr) { g->SetEnd(g->NewNode(mcgraph->common()->End(0))); } } void MergeControlToEnd(MachineGraph* mcgraph, Node* node) { EnsureEnd(mcgraph); NodeProperties::MergeControlToEnd(mcgraph->graph(), mcgraph->common(), node); } bool ContainsSimd(const wasm::FunctionSig* sig) { for (auto type : sig->all()) { if (type == wasm::kWasmS128) return true; } return false; } bool ContainsInt64(const wasm::FunctionSig* sig) { for (auto type : sig->all()) { if (type == wasm::kWasmI64) return true; } return false; } template <typename BuiltinDescriptor> CallDescriptor* GetBuiltinCallDescriptor(WasmGraphBuilder* builder, StubCallMode stub_mode) { BuiltinDescriptor interface_descriptor; return Linkage::GetStubCallDescriptor( builder->mcgraph()->zone(), // zone interface_descriptor, // descriptor interface_descriptor.GetStackParameterCount(), // stack parameter count CallDescriptor::kNoFlags, // flags Operator::kNoProperties, // properties stub_mode); // stub call mode } } // namespace class WasmGraphAssembler : public GraphAssembler { public: WasmGraphAssembler(MachineGraph* mcgraph, Zone* zone) : GraphAssembler(mcgraph, zone) {} }; WasmGraphBuilder::WasmGraphBuilder( wasm::CompilationEnv* env, Zone* zone, MachineGraph* mcgraph, const wasm::FunctionSig* sig, compiler::SourcePositionTable* source_position_table) : gasm_(std::make_unique<WasmGraphAssembler>(mcgraph, zone)), zone_(zone), mcgraph_(mcgraph), env_(env), has_simd_(ContainsSimd(sig)), untrusted_code_mitigations_(FLAG_untrusted_code_mitigations), sig_(sig), source_position_table_(source_position_table) { DCHECK_IMPLIES(use_trap_handler(), trap_handler::IsTrapHandlerEnabled()); DCHECK_NOT_NULL(mcgraph_); } // Destructor define here where the definition of {WasmGraphAssembler} is // available. WasmGraphBuilder::~WasmGraphBuilder() = default; Node* WasmGraphBuilder::Error() { return mcgraph()->Dead(); } Node* WasmGraphBuilder::Start(unsigned params) { Node* start = graph()->NewNode(mcgraph()->common()->Start(params)); graph()->SetStart(start); return start; } Node* WasmGraphBuilder::Param(unsigned index) { return graph()->NewNode(mcgraph()->common()->Parameter(index), graph()->start()); } Node* WasmGraphBuilder::Loop(Node* entry) { return graph()->NewNode(mcgraph()->common()->Loop(1), entry); } Node* WasmGraphBuilder::TerminateLoop(Node* effect, Node* control) { Node* terminate = graph()->NewNode(mcgraph()->common()->Terminate(), effect, control); MergeControlToEnd(mcgraph(), terminate); return terminate; } Node* WasmGraphBuilder::TerminateThrow(Node* effect, Node* control) { Node* terminate = graph()->NewNode(mcgraph()->common()->Throw(), effect, control); MergeControlToEnd(mcgraph(), terminate); return terminate; } bool WasmGraphBuilder::IsPhiWithMerge(Node* phi, Node* merge) { return phi && IrOpcode::IsPhiOpcode(phi->opcode()) && NodeProperties::GetControlInput(phi) == merge; } bool WasmGraphBuilder::ThrowsException(Node* node, Node** if_success, Node** if_exception) { if (node->op()->HasProperty(compiler::Operator::kNoThrow)) { return false; } *if_success = graph()->NewNode(mcgraph()->common()->IfSuccess(), node); *if_exception = graph()->NewNode(mcgraph()->common()->IfException(), node, node); return true; } void WasmGraphBuilder::AppendToMerge(Node* merge, Node* from) { DCHECK(IrOpcode::IsMergeOpcode(merge->opcode())); merge->AppendInput(mcgraph()->zone(), from); int new_size = merge->InputCount(); NodeProperties::ChangeOp( merge, mcgraph()->common()->ResizeMergeOrPhi(merge->op(), new_size)); } void WasmGraphBuilder::AppendToPhi(Node* phi, Node* from) { DCHECK(IrOpcode::IsPhiOpcode(phi->opcode())); int new_size = phi->InputCount(); phi->InsertInput(mcgraph()->zone(), phi->InputCount() - 1, from); NodeProperties::ChangeOp( phi, mcgraph()->common()->ResizeMergeOrPhi(phi->op(), new_size)); } Node* WasmGraphBuilder::Merge(unsigned count, Node** controls) { return graph()->NewNode(mcgraph()->common()->Merge(count), count, controls); } Node* WasmGraphBuilder::Phi(wasm::ValueType type, unsigned count, Node** vals_and_control) { DCHECK(IrOpcode::IsMergeOpcode(vals_and_control[count]->opcode())); return graph()->NewNode( mcgraph()->common()->Phi(type.machine_representation(), count), count + 1, vals_and_control); } Node* WasmGraphBuilder::EffectPhi(unsigned count, Node** effects_and_control) { DCHECK(IrOpcode::IsMergeOpcode(effects_and_control[count]->opcode())); return graph()->NewNode(mcgraph()->common()->EffectPhi(count), count + 1, effects_and_control); } Node* WasmGraphBuilder::RefNull() { return LOAD_FULL_POINTER( BuildLoadIsolateRoot(), IsolateData::root_slot_offset(RootIndex::kNullValue)); } Node* WasmGraphBuilder::RefFunc(uint32_t function_index) { auto call_descriptor = GetBuiltinCallDescriptor<WasmRefFuncDescriptor>( this, StubCallMode::kCallWasmRuntimeStub); // A direct call to a wasm runtime stub defined in this module. // Just encode the stub index. This will be patched at relocation. Node* call_target = mcgraph()->RelocatableIntPtrConstant( wasm::WasmCode::kWasmRefFunc, RelocInfo::WASM_STUB_CALL); return SetEffectControl(graph()->NewNode( mcgraph()->common()->Call(call_descriptor), call_target, mcgraph()->Uint32Constant(function_index), effect(), control())); } Node* WasmGraphBuilder::RefAsNonNull(Node* arg, wasm::WasmCodePosition position) { TrapIfTrue(wasm::kTrapIllegalCast, gasm_->WordEqual(arg, RefNull()), position); return arg; } Node* WasmGraphBuilder::NoContextConstant() { return mcgraph()->IntPtrConstant(0); } Node* WasmGraphBuilder::BuildLoadIsolateRoot() { // The IsolateRoot is loaded from the instance node so that the generated // code is Isolate independent. This can be overridden by setting a specific // node in {isolate_root_node_} beforehand. if (isolate_root_node_.is_set()) return isolate_root_node_.get(); return LOAD_INSTANCE_FIELD(IsolateRoot, MachineType::Pointer()); } Node* WasmGraphBuilder::Int32Constant(int32_t value) { return mcgraph()->Int32Constant(value); } Node* WasmGraphBuilder::Int64Constant(int64_t value) { return mcgraph()->Int64Constant(value); } void WasmGraphBuilder::StackCheck(wasm::WasmCodePosition position) { DCHECK_NOT_NULL(env_); // Wrappers don't get stack checks. if (!FLAG_wasm_stack_checks || !env_->runtime_exception_support) { return; } Node* limit_address = graph()->NewNode( mcgraph()->machine()->Load(MachineType::Pointer()), instance_node_.get(), mcgraph()->Int32Constant(WASM_INSTANCE_OBJECT_OFFSET(StackLimitAddress)), effect(), control()); Node* limit = SetEffect(graph()->NewNode( mcgraph()->machine()->Load(MachineType::Pointer()), limit_address, mcgraph()->IntPtrConstant(0), limit_address, control())); Node* check = SetEffect(graph()->NewNode( mcgraph()->machine()->StackPointerGreaterThan(StackCheckKind::kWasm), limit, effect())); Diamond stack_check(graph(), mcgraph()->common(), check, BranchHint::kTrue); stack_check.Chain(control()); if (stack_check_call_operator_ == nullptr) { // Build and cache the stack check call operator and the constant // representing the stack check code. auto call_descriptor = Linkage::GetStubCallDescriptor( mcgraph()->zone(), // zone NoContextDescriptor{}, // descriptor 0, // stack parameter count CallDescriptor::kNoFlags, // flags Operator::kNoProperties, // properties StubCallMode::kCallWasmRuntimeStub); // stub call mode // A direct call to a wasm runtime stub defined in this module. // Just encode the stub index. This will be patched at relocation. stack_check_code_node_.set(mcgraph()->RelocatableIntPtrConstant( wasm::WasmCode::kWasmStackGuard, RelocInfo::WASM_STUB_CALL)); stack_check_call_operator_ = mcgraph()->common()->Call(call_descriptor); } Node* call = graph()->NewNode(stack_check_call_operator_.get(), stack_check_code_node_.get(), effect(), stack_check.if_false); SetSourcePosition(call, position); Node* ephi = stack_check.EffectPhi(effect(), call); SetEffectControl(ephi, stack_check.merge); } void WasmGraphBuilder::PatchInStackCheckIfNeeded() { if (!needs_stack_check_) return; Node* start = graph()->start(); // Place a stack check which uses a dummy node as control and effect. Node* dummy = graph()->NewNode(mcgraph()->common()->Dead()); SetEffectControl(dummy); // The function-prologue stack check is associated with position 0, which // is never a position of any instruction in the function. StackCheck(0); // In testing, no steck checks were emitted. Nothing to rewire then. if (effect() == dummy) return; // Now patch all control uses of {start} to use {control} and all effect uses // to use {effect} instead. Then rewire the dummy node to use start instead. NodeProperties::ReplaceUses(start, start, effect(), control()); NodeProperties::ReplaceUses(dummy, nullptr, start, start); } Node* WasmGraphBuilder::Binop(wasm::WasmOpcode opcode, Node* left, Node* right, wasm::WasmCodePosition position) { const Operator* op; MachineOperatorBuilder* m = mcgraph()->machine(); switch (opcode) { case wasm::kExprI32Add: op = m->Int32Add(); break; case wasm::kExprI32Sub: op = m->Int32Sub(); break; case wasm::kExprI32Mul: op = m->Int32Mul(); break; case wasm::kExprI32DivS: return BuildI32DivS(left, right, position); case wasm::kExprI32DivU: return BuildI32DivU(left, right, position); case wasm::kExprI32RemS: return BuildI32RemS(left, right, position); case wasm::kExprI32RemU: return BuildI32RemU(left, right, position); case wasm::kExprI32And: op = m->Word32And(); break; case wasm::kExprI32Ior: op = m->Word32Or(); break; case wasm::kExprI32Xor: op = m->Word32Xor(); break; case wasm::kExprI32Shl: op = m->Word32Shl(); right = MaskShiftCount32(right); break; case wasm::kExprI32ShrU: op = m->Word32Shr(); right = MaskShiftCount32(right); break; case wasm::kExprI32ShrS: op = m->Word32Sar(); right = MaskShiftCount32(right); break; case wasm::kExprI32Ror: op = m->Word32Ror(); right = MaskShiftCount32(right); break; case wasm::kExprI32Rol: if (m->Word32Rol().IsSupported()) { op = m->Word32Rol().op(); right = MaskShiftCount32(right); break; } return BuildI32Rol(left, right); case wasm::kExprI32Eq: op = m->Word32Equal(); break; case wasm::kExprI32Ne: return Invert(Binop(wasm::kExprI32Eq, left, right)); case wasm::kExprI32LtS: op = m->Int32LessThan(); break; case wasm::kExprI32LeS: op = m->Int32LessThanOrEqual(); break; case wasm::kExprI32LtU: op = m->Uint32LessThan(); break; case wasm::kExprI32LeU: op = m->Uint32LessThanOrEqual(); break; case wasm::kExprI32GtS: op = m->Int32LessThan(); std::swap(left, right); break; case wasm::kExprI32GeS: op = m->Int32LessThanOrEqual(); std::swap(left, right); break; case wasm::kExprI32GtU: op = m->Uint32LessThan(); std::swap(left, right); break; case wasm::kExprI32GeU: op = m->Uint32LessThanOrEqual(); std::swap(left, right); break; case wasm::kExprI64And: op = m->Word64And(); break; case wasm::kExprI64Add: op = m->Int64Add(); break; case wasm::kExprI64Sub: op = m->Int64Sub(); break; case wasm::kExprI64Mul: op = m->Int64Mul(); break; case wasm::kExprI64DivS: return BuildI64DivS(left, right, position); case wasm::kExprI64DivU: return BuildI64DivU(left, right, position); case wasm::kExprI64RemS: return BuildI64RemS(left, right, position); case wasm::kExprI64RemU: return BuildI64RemU(left, right, position); case wasm::kExprI64Ior: op = m->Word64Or(); break; case wasm::kExprI64Xor: op = m->Word64Xor(); break; case wasm::kExprI64Shl: op = m->Word64Shl(); right = MaskShiftCount64(right); break; case wasm::kExprI64ShrU: op = m->Word64Shr(); right = MaskShiftCount64(right); break; case wasm::kExprI64ShrS: op = m->Word64Sar(); right = MaskShiftCount64(right); break; case wasm::kExprI64Eq: op = m->Word64Equal(); break; case wasm::kExprI64Ne: return Invert(Binop(wasm::kExprI64Eq, left, right)); case wasm::kExprI64LtS: op = m->Int64LessThan(); break; case wasm::kExprI64LeS: op = m->Int64LessThanOrEqual(); break; case wasm::kExprI64LtU: op = m->Uint64LessThan(); break; case wasm::kExprI64LeU: op = m->Uint64LessThanOrEqual(); break; case wasm::kExprI64GtS: op = m->Int64LessThan(); std::swap(left, right); break; case wasm::kExprI64GeS: op = m->Int64LessThanOrEqual(); std::swap(left, right); break; case wasm::kExprI64GtU: op = m->Uint64LessThan(); std::swap(left, right); break; case wasm::kExprI64GeU: op = m->Uint64LessThanOrEqual(); std::swap(left, right); break; case wasm::kExprI64Ror: op = m->Word64Ror(); right = MaskShiftCount64(right); break; case wasm::kExprI64Rol: if (m->Word64Rol().IsSupported()) { op = m->Word64Rol().op(); right = MaskShiftCount64(right); break; } else if (m->Word32Rol().IsSupported()) { op = m->Word64Rol().placeholder(); break; } return BuildI64Rol(left, right); case wasm::kExprF32CopySign: return BuildF32CopySign(left, right); case wasm::kExprF64CopySign: return BuildF64CopySign(left, right); case wasm::kExprF32Add: op = m->Float32Add(); break; case wasm::kExprF32Sub: op = m->Float32Sub(); break; case wasm::kExprF32Mul: op = m->Float32Mul(); break; case wasm::kExprF32Div: op = m->Float32Div(); break; case wasm::kExprF32Eq: op = m->Float32Equal(); break; case wasm::kExprF32Ne: return Invert(Binop(wasm::kExprF32Eq, left, right)); case wasm::kExprF32Lt: op = m->Float32LessThan(); break; case wasm::kExprF32Ge: op = m->Float32LessThanOrEqual(); std::swap(left, right); break; case wasm::kExprF32Gt: op = m->Float32LessThan(); std::swap(left, right); break; case wasm::kExprF32Le: op = m->Float32LessThanOrEqual(); break; case wasm::kExprF64Add: op = m->Float64Add(); break; case wasm::kExprF64Sub: op = m->Float64Sub(); break; case wasm::kExprF64Mul: op = m->Float64Mul(); break; case wasm::kExprF64Div: op = m->Float64Div(); break; case wasm::kExprF64Eq: op = m->Float64Equal(); break; case wasm::kExprF64Ne: return Invert(Binop(wasm::kExprF64Eq, left, right)); case wasm::kExprF64Lt: op = m->Float64LessThan(); break; case wasm::kExprF64Le: op = m->Float64LessThanOrEqual(); break; case wasm::kExprF64Gt: op = m->Float64LessThan(); std::swap(left, right); break; case wasm::kExprF64Ge: op = m->Float64LessThanOrEqual(); std::swap(left, right); break; case wasm::kExprF32Min: op = m->Float32Min(); break; case wasm::kExprF64Min: op = m->Float64Min(); break; case wasm::kExprF32Max: op = m->Float32Max(); break; case wasm::kExprF64Max: op = m->Float64Max(); break; case wasm::kExprF64Pow: return BuildF64Pow(left, right); case wasm::kExprF64Atan2: op = m->Float64Atan2(); break; case wasm::kExprF64Mod: return BuildF64Mod(left, right); case wasm::kExprRefEq: return gasm_->TaggedEqual(left, right); case wasm::kExprI32AsmjsDivS: return BuildI32AsmjsDivS(left, right); case wasm::kExprI32AsmjsDivU: return BuildI32AsmjsDivU(left, right); case wasm::kExprI32AsmjsRemS: return BuildI32AsmjsRemS(left, right); case wasm::kExprI32AsmjsRemU: return BuildI32AsmjsRemU(left, right); case wasm::kExprI32AsmjsStoreMem8: return BuildAsmjsStoreMem(MachineType::Int8(), left, right); case wasm::kExprI32AsmjsStoreMem16: return BuildAsmjsStoreMem(MachineType::Int16(), left, right); case wasm::kExprI32AsmjsStoreMem: return BuildAsmjsStoreMem(MachineType::Int32(), left, right); case wasm::kExprF32AsmjsStoreMem: return BuildAsmjsStoreMem(MachineType::Float32(), left, right); case wasm::kExprF64AsmjsStoreMem: return BuildAsmjsStoreMem(MachineType::Float64(), left, right); default: FATAL_UNSUPPORTED_OPCODE(opcode); } return graph()->NewNode(op, left, right); } Node* WasmGraphBuilder::Unop(wasm::WasmOpcode opcode, Node* input, wasm::WasmCodePosition position) { const Operator* op; MachineOperatorBuilder* m = mcgraph()->machine(); switch (opcode) { case wasm::kExprI32Eqz: op = m->Word32Equal(); return graph()->NewNode(op, input, mcgraph()->Int32Constant(0)); case wasm::kExprF32Abs: op = m->Float32Abs(); break; case wasm::kExprF32Neg: { op = m->Float32Neg(); break; } case wasm::kExprF32Sqrt: op = m->Float32Sqrt(); break; case wasm::kExprF64Abs: op = m->Float64Abs(); break; case wasm::kExprF64Neg: { op = m->Float64Neg(); break; } case wasm::kExprF64Sqrt: op = m->Float64Sqrt(); break; case wasm::kExprI32SConvertF32: case wasm::kExprI32UConvertF32: case wasm::kExprI32SConvertF64: case wasm::kExprI32UConvertF64: case wasm::kExprI32SConvertSatF64: case wasm::kExprI32UConvertSatF64: case wasm::kExprI32SConvertSatF32: case wasm::kExprI32UConvertSatF32: return BuildIntConvertFloat(input, position, opcode); case wasm::kExprI32AsmjsSConvertF64: return BuildI32AsmjsSConvertF64(input); case wasm::kExprI32AsmjsUConvertF64: return BuildI32AsmjsUConvertF64(input); case wasm::kExprF32ConvertF64: op = m->TruncateFloat64ToFloat32(); break; case wasm::kExprF64SConvertI32: op = m->ChangeInt32ToFloat64(); break; case wasm::kExprF64UConvertI32: op = m->ChangeUint32ToFloat64(); break; case wasm::kExprF32SConvertI32: op = m->RoundInt32ToFloat32(); break; case wasm::kExprF32UConvertI32: op = m->RoundUint32ToFloat32(); break; case wasm::kExprI32AsmjsSConvertF32: return BuildI32AsmjsSConvertF32(input); case wasm::kExprI32AsmjsUConvertF32: return BuildI32AsmjsUConvertF32(input); case wasm::kExprF64ConvertF32: op = m->ChangeFloat32ToFloat64(); break; case wasm::kExprF32ReinterpretI32: op = m->BitcastInt32ToFloat32(); break; case wasm::kExprI32ReinterpretF32: op = m->BitcastFloat32ToInt32(); break; case wasm::kExprI32Clz: op = m->Word32Clz(); break; case wasm::kExprI32Ctz: { if (m->Word32Ctz().IsSupported()) { op = m->Word32Ctz().op(); break; } else if (m->Word32ReverseBits().IsSupported()) { Node* reversed = graph()->NewNode(m->Word32ReverseBits().op(), input); Node* result = graph()->NewNode(m->Word32Clz(), reversed); return result; } else { return BuildI32Ctz(input); } } case wasm::kExprI32Popcnt: { if (m->Word32Popcnt().IsSupported()) { op = m->Word32Popcnt().op(); break; } else { return BuildI32Popcnt(input); } } case wasm::kExprF32Floor: { if (!m->Float32RoundDown().IsSupported()) return BuildF32Floor(input); op = m->Float32RoundDown().op(); break; } case wasm::kExprF32Ceil: { if (!m->Float32RoundUp().IsSupported()) return BuildF32Ceil(input); op = m->Float32RoundUp().op(); break; } case wasm::kExprF32Trunc: { if (!m->Float32RoundTruncate().IsSupported()) return BuildF32Trunc(input); op = m->Float32RoundTruncate().op(); break; } case wasm::kExprF32NearestInt: { if (!m->Float32RoundTiesEven().IsSupported()) return BuildF32NearestInt(input); op = m->Float32RoundTiesEven().op(); break; } case wasm::kExprF64Floor: { if (!m->Float64RoundDown().IsSupported()) return BuildF64Floor(input); op = m->Float64RoundDown().op(); break; } case wasm::kExprF64Ceil: { if (!m->Float64RoundUp().IsSupported()) return BuildF64Ceil(input); op = m->Float64RoundUp().op(); break; } case wasm::kExprF64Trunc: { if (!m->Float64RoundTruncate().IsSupported()) return BuildF64Trunc(input); op = m->Float64RoundTruncate().op(); break; } case wasm::kExprF64NearestInt: { if (!m->Float64RoundTiesEven().IsSupported()) return BuildF64NearestInt(input); op = m->Float64RoundTiesEven().op(); break; } case wasm::kExprF64Acos: { return BuildF64Acos(input); } case wasm::kExprF64Asin: { return BuildF64Asin(input); } case wasm::kExprF64Atan: op = m->Float64Atan(); break; case wasm::kExprF64Cos: { op = m->Float64Cos(); break; } case wasm::kExprF64Sin: { op = m->Float64Sin(); break; } case wasm::kExprF64Tan: { op = m->Float64Tan(); break; } case wasm::kExprF64Exp: { op = m->Float64Exp(); break; } case wasm::kExprF64Log: op = m->Float64Log(); break; case wasm::kExprI32ConvertI64: op = m->TruncateInt64ToInt32(); break; case wasm::kExprI64SConvertI32: op = m->ChangeInt32ToInt64(); break; case wasm::kExprI64UConvertI32: op = m->ChangeUint32ToUint64(); break; case wasm::kExprF64ReinterpretI64: op = m->BitcastInt64ToFloat64(); break; case wasm::kExprI64ReinterpretF64: op = m->BitcastFloat64ToInt64(); break; case wasm::kExprI64Clz: op = m->Word64Clz(); break; case wasm::kExprI64Ctz: { OptionalOperator ctz64 = m->Word64Ctz(); if (ctz64.IsSupported()) { op = ctz64.op(); break; } else if (m->Is32() && m->Word32Ctz().IsSupported()) { op = ctz64.placeholder(); break; } else if (m->Word64ReverseBits().IsSupported()) { Node* reversed = graph()->NewNode(m->Word64ReverseBits().op(), input); Node* result = graph()->NewNode(m->Word64Clz(), reversed); return result; } else { return BuildI64Ctz(input); } } case wasm::kExprI64Popcnt: { OptionalOperator popcnt64 = m->Word64Popcnt(); if (popcnt64.IsSupported()) { op = popcnt64.op(); } else if (m->Is32() && m->Word32Popcnt().IsSupported()) { op = popcnt64.placeholder(); } else { return BuildI64Popcnt(input); } break; } case wasm::kExprI64Eqz: op = m->Word64Equal(); return graph()->NewNode(op, input, mcgraph()->Int64Constant(0)); case wasm::kExprF32SConvertI64: if (m->Is32()) { return BuildF32SConvertI64(input); } op = m->RoundInt64ToFloat32(); break; case wasm::kExprF32UConvertI64: if (m->Is32()) { return BuildF32UConvertI64(input); } op = m->RoundUint64ToFloat32(); break; case wasm::kExprF64SConvertI64: if (m->Is32()) { return BuildF64SConvertI64(input); } op = m->RoundInt64ToFloat64(); break; case wasm::kExprF64UConvertI64: if (m->Is32()) { return BuildF64UConvertI64(input); } op = m->RoundUint64ToFloat64(); break; case wasm::kExprI32SExtendI8: op = m->SignExtendWord8ToInt32(); break; case wasm::kExprI32SExtendI16: op = m->SignExtendWord16ToInt32(); break; case wasm::kExprI64SExtendI8: op = m->SignExtendWord8ToInt64(); break; case wasm::kExprI64SExtendI16: op = m->SignExtendWord16ToInt64(); break; case wasm::kExprI64SExtendI32: op = m->SignExtendWord32ToInt64(); break; case wasm::kExprI64SConvertF32: case wasm::kExprI64UConvertF32: case wasm::kExprI64SConvertF64: case wasm::kExprI64UConvertF64: case wasm::kExprI64SConvertSatF32: case wasm::kExprI64UConvertSatF32: case wasm::kExprI64SConvertSatF64: case wasm::kExprI64UConvertSatF64: return mcgraph()->machine()->Is32() ? BuildCcallConvertFloat(input, position, opcode) : BuildIntConvertFloat(input, position, opcode); case wasm::kExprRefIsNull: return graph()->NewNode(m->WordEqual(), input, RefNull()); case wasm::kExprI32AsmjsLoadMem8S: return BuildAsmjsLoadMem(MachineType::Int8(), input); case wasm::kExprI32AsmjsLoadMem8U: return BuildAsmjsLoadMem(MachineType::Uint8(), input); case wasm::kExprI32AsmjsLoadMem16S: return BuildAsmjsLoadMem(MachineType::Int16(), input); case wasm::kExprI32AsmjsLoadMem16U: return BuildAsmjsLoadMem(MachineType::Uint16(), input); case wasm::kExprI32AsmjsLoadMem: return BuildAsmjsLoadMem(MachineType::Int32(), input); case wasm::kExprF32AsmjsLoadMem: return BuildAsmjsLoadMem(MachineType::Float32(), input); case wasm::kExprF64AsmjsLoadMem: return BuildAsmjsLoadMem(MachineType::Float64(), input); default: FATAL_UNSUPPORTED_OPCODE(opcode); } return graph()->NewNode(op, input); } Node* WasmGraphBuilder::Float32Constant(float value) { return mcgraph()->Float32Constant(value); } Node* WasmGraphBuilder::Float64Constant(double value) { return mcgraph()->Float64Constant(value); } Node* WasmGraphBuilder::Simd128Constant(const uint8_t value[16]) { has_simd_ = true; return graph()->NewNode(mcgraph()->machine()->S128Const(value)); } namespace { Node* Branch(MachineGraph* mcgraph, Node* cond, Node** true_node, Node** false_node, Node* control, BranchHint hint) { DCHECK_NOT_NULL(cond); DCHECK_NOT_NULL(control); Node* branch = mcgraph->graph()->NewNode(mcgraph->common()->Branch(hint), cond, control); *true_node = mcgraph->graph()->NewNode(mcgraph->common()->IfTrue(), branch); *false_node = mcgraph->graph()->NewNode(mcgraph->common()->IfFalse(), branch); return branch; } } // namespace Node* WasmGraphBuilder::BranchNoHint(Node* cond, Node** true_node, Node** false_node) { return Branch(mcgraph(), cond, true_node, false_node, control(), BranchHint::kNone); } Node* WasmGraphBuilder::BranchExpectTrue(Node* cond, Node** true_node, Node** false_node) { return Branch(mcgraph(), cond, true_node, false_node, control(), BranchHint::kTrue); } Node* WasmGraphBuilder::BranchExpectFalse(Node* cond, Node** true_node, Node** false_node) { return Branch(mcgraph(), cond, true_node, false_node, control(), BranchHint::kFalse); } TrapId WasmGraphBuilder::GetTrapIdForTrap(wasm::TrapReason reason) { // TODO(wasm): "!env_" should not happen when compiling an actual wasm // function. if (!env_ || !env_->runtime_exception_support) { // We use TrapId::kInvalid as a marker to tell the code generator // to generate a call to a testing c-function instead of a runtime // stub. This code should only be called from a cctest. return TrapId::kInvalid; } switch (reason) { #define TRAPREASON_TO_TRAPID(name) \ case wasm::k##name: \ static_assert( \ static_cast<int>(TrapId::k##name) == wasm::WasmCode::kThrowWasm##name, \ "trap id mismatch"); \ return TrapId::k##name; FOREACH_WASM_TRAPREASON(TRAPREASON_TO_TRAPID) #undef TRAPREASON_TO_TRAPID default: UNREACHABLE(); } } Node* WasmGraphBuilder::TrapIfTrue(wasm::TrapReason reason, Node* cond, wasm::WasmCodePosition position) { TrapId trap_id = GetTrapIdForTrap(reason); Node* node = SetControl(graph()->NewNode(mcgraph()->common()->TrapIf(trap_id), cond, effect(), control())); SetSourcePosition(node, position); return node; } Node* WasmGraphBuilder::TrapIfFalse(wasm::TrapReason reason, Node* cond, wasm::WasmCodePosition position) { TrapId trap_id = GetTrapIdForTrap(reason); Node* node = SetControl(graph()->NewNode( mcgraph()->common()->TrapUnless(trap_id), cond, effect(), control())); SetSourcePosition(node, position); return node; } // Add a check that traps if {node} is equal to {val}. Node* WasmGraphBuilder::TrapIfEq32(wasm::TrapReason reason, Node* node, int32_t val, wasm::WasmCodePosition position) { Int32Matcher m(node); if (m.HasValue() && !m.Is(val)) return graph()->start(); if (val == 0) { return TrapIfFalse(reason, node, position); } else { return TrapIfTrue(reason, graph()->NewNode(mcgraph()->machine()->Word32Equal(), node, mcgraph()->Int32Constant(val)), position); } } // Add a check that traps if {node} is zero. Node* WasmGraphBuilder::ZeroCheck32(wasm::TrapReason reason, Node* node, wasm::WasmCodePosition position) { return TrapIfEq32(reason, node, 0, position); } // Add a check that traps if {node} is equal to {val}. Node* WasmGraphBuilder::TrapIfEq64(wasm::TrapReason reason, Node* node, int64_t val, wasm::WasmCodePosition position) { Int64Matcher m(node); if (m.HasValue() && !m.Is(val)) return graph()->start(); return TrapIfTrue(reason, graph()->NewNode(mcgraph()->machine()->Word64Equal(), node, mcgraph()->Int64Constant(val)), position); } // Add a check that traps if {node} is zero. Node* WasmGraphBuilder::ZeroCheck64(wasm::TrapReason reason, Node* node, wasm::WasmCodePosition position) { return TrapIfEq64(reason, node, 0, position); } Node* WasmGraphBuilder::Switch(unsigned count, Node* key) { // The instruction selector will use {kArchTableSwitch} for large switches, // which has limited input count, see {InstructionSelector::EmitTableSwitch}. DCHECK_LE(count, Instruction::kMaxInputCount - 2); // value_range + 2 DCHECK_LE(count, wasm::kV8MaxWasmFunctionBrTableSize + 1); // plus IfDefault return graph()->NewNode(mcgraph()->common()->Switch(count), key, control()); } Node* WasmGraphBuilder::IfValue(int32_t value, Node* sw) { DCHECK_EQ(IrOpcode::kSwitch, sw->opcode()); return graph()->NewNode(mcgraph()->common()->IfValue(value), sw); } Node* WasmGraphBuilder::IfDefault(Node* sw) { DCHECK_EQ(IrOpcode::kSwitch, sw->opcode()); return graph()->NewNode(mcgraph()->common()->IfDefault(), sw); } Node* WasmGraphBuilder::Return(Vector<Node*> vals) { unsigned count = static_cast<unsigned>(vals.size()); base::SmallVector<Node*, 8> buf(count + 3); buf[0] = mcgraph()->Int32Constant(0); if (count > 0) { memcpy(buf.data() + 1, vals.begin(), sizeof(void*) * count); } buf[count + 1] = effect(); buf[count + 2] = control(); Node* ret = graph()->NewNode(mcgraph()->common()->Return(count), count + 3, buf.data()); MergeControlToEnd(mcgraph(), ret); return ret; } Node* WasmGraphBuilder::Trap(wasm::TrapReason reason, wasm::WasmCodePosition position) { TrapIfFalse(reason, Int32Constant(0), position); Return(Vector<Node*>{}); return nullptr; } Node* WasmGraphBuilder::MaskShiftCount32(Node* node) { static const int32_t kMask32 = 0x1F; if (!mcgraph()->machine()->Word32ShiftIsSafe()) { // Shifts by constants are so common we pattern-match them here. Int32Matcher match(node); if (match.HasValue()) { int32_t masked = (match.Value() & kMask32); if (match.Value() != masked) node = mcgraph()->Int32Constant(masked); } else { node = graph()->NewNode(mcgraph()->machine()->Word32And(), node, mcgraph()->Int32Constant(kMask32)); } } return node; } Node* WasmGraphBuilder::MaskShiftCount64(Node* node) { static const int64_t kMask64 = 0x3F; if (!mcgraph()->machine()->Word32ShiftIsSafe()) { // Shifts by constants are so common we pattern-match them here. Int64Matcher match(node); if (match.HasValue()) { int64_t masked = (match.Value() & kMask64); if (match.Value() != masked) node = mcgraph()->Int64Constant(masked); } else { node = graph()->NewNode(mcgraph()->machine()->Word64And(), node, mcgraph()->Int64Constant(kMask64)); } } return node; } namespace { bool ReverseBytesSupported(MachineOperatorBuilder* m, size_t size_in_bytes) { switch (size_in_bytes) { case 4: case 16: return true; case 8: return m->Is64(); default: break; } return false; } } // namespace Node* WasmGraphBuilder::BuildChangeEndiannessStore( Node* node, MachineRepresentation mem_rep, wasm::ValueType wasmtype) { Node* result; Node* value = node; MachineOperatorBuilder* m = mcgraph()->machine(); int valueSizeInBytes = wasmtype.element_size_bytes(); int valueSizeInBits = 8 * valueSizeInBytes; bool isFloat = false; switch (wasmtype.kind()) { case wasm::ValueType::kF64: value = graph()->NewNode(m->BitcastFloat64ToInt64(), node); isFloat = true; V8_FALLTHROUGH; case wasm::ValueType::kI64: result = mcgraph()->Int64Constant(0); break; case wasm::ValueType::kF32: value = graph()->NewNode(m->BitcastFloat32ToInt32(), node); isFloat = true; V8_FALLTHROUGH; case wasm::ValueType::kI32: result = mcgraph()->Int32Constant(0); break; case wasm::ValueType::kS128: DCHECK(ReverseBytesSupported(m, valueSizeInBytes)); break; default: UNREACHABLE(); } if (mem_rep == MachineRepresentation::kWord8) { // No need to change endianness for byte size, return original node return node; } if (wasmtype == wasm::kWasmI64 && mem_rep < MachineRepresentation::kWord64) { // In case we store lower part of WasmI64 expression, we can truncate // upper 32bits value = graph()->NewNode(m->TruncateInt64ToInt32(), value); valueSizeInBytes = wasm::kWasmI32.element_size_bytes(); valueSizeInBits = 8 * valueSizeInBytes; if (mem_rep == MachineRepresentation::kWord16) { value = graph()->NewNode(m->Word32Shl(), value, mcgraph()->Int32Constant(16)); } } else if (wasmtype == wasm::kWasmI32 && mem_rep == MachineRepresentation::kWord16) { value = graph()->NewNode(m->Word32Shl(), value, mcgraph()->Int32Constant(16)); } int i; uint32_t shiftCount; if (ReverseBytesSupported(m, valueSizeInBytes)) { switch (valueSizeInBytes) { case 4: result = graph()->NewNode(m->Word32ReverseBytes(), value); break; case 8: result = graph()->NewNode(m->Word64ReverseBytes(), value); break; case 16: result = graph()->NewNode(m->Simd128ReverseBytes(), value); break; default: UNREACHABLE(); break; } } else { for (i = 0, shiftCount = valueSizeInBits - 8; i < valueSizeInBits / 2; i += 8, shiftCount -= 16) { Node* shiftLower; Node* shiftHigher; Node* lowerByte; Node* higherByte; DCHECK_LT(0, shiftCount); DCHECK_EQ(0, (shiftCount + 8) % 16); if (valueSizeInBits > 32) { shiftLower = graph()->NewNode(m->Word64Shl(), value, mcgraph()->Int64Constant(shiftCount)); shiftHigher = graph()->NewNode(m->Word64Shr(), value, mcgraph()->Int64Constant(shiftCount)); lowerByte = graph()->NewNode( m->Word64And(), shiftLower, mcgraph()->Int64Constant(static_cast<uint64_t>(0xFF) << (valueSizeInBits - 8 - i))); higherByte = graph()->NewNode( m->Word64And(), shiftHigher, mcgraph()->Int64Constant(static_cast<uint64_t>(0xFF) << i)); result = graph()->NewNode(m->Word64Or(), result, lowerByte); result = graph()->NewNode(m->Word64Or(), result, higherByte); } else { shiftLower = graph()->NewNode(m->Word32Shl(), value, mcgraph()->Int32Constant(shiftCount)); shiftHigher = graph()->NewNode(m->Word32Shr(), value, mcgraph()->Int32Constant(shiftCount)); lowerByte = graph()->NewNode( m->Word32And(), shiftLower, mcgraph()->Int32Constant(static_cast<uint32_t>(0xFF) << (valueSizeInBits - 8 - i))); higherByte = graph()->NewNode( m->Word32And(), shiftHigher, mcgraph()->Int32Constant(static_cast<uint32_t>(0xFF) << i)); result = graph()->NewNode(m->Word32Or(), result, lowerByte); result = graph()->NewNode(m->Word32Or(), result, higherByte); } } } if (isFloat) { switch (wasmtype.kind()) { case wasm::ValueType::kF64: result = graph()->NewNode(m->BitcastInt64ToFloat64(), result); break; case wasm::ValueType::kF32: result = graph()->NewNode(m->BitcastInt32ToFloat32(), result); break; default: UNREACHABLE(); break; } } return result; } Node* WasmGraphBuilder::BuildChangeEndiannessLoad(Node* node, MachineType memtype, wasm::ValueType wasmtype) { Node* result; Node* value = node; MachineOperatorBuilder* m = mcgraph()->machine(); int valueSizeInBytes = ElementSizeInBytes(memtype.representation()); int valueSizeInBits = 8 * valueSizeInBytes; bool isFloat = false; switch (memtype.representation()) { case MachineRepresentation::kFloat64: value = graph()->NewNode(m->BitcastFloat64ToInt64(), node); isFloat = true; V8_FALLTHROUGH; case MachineRepresentation::kWord64: result = mcgraph()->Int64Constant(0); break; case MachineRepresentation::kFloat32: value = graph()->NewNode(m->BitcastFloat32ToInt32(), node); isFloat = true; V8_FALLTHROUGH; case MachineRepresentation::kWord32: case MachineRepresentation::kWord16: result = mcgraph()->Int32Constant(0); break; case MachineRepresentation::kWord8: // No need to change endianness for byte size, return original node return node; break; case MachineRepresentation::kSimd128: DCHECK(ReverseBytesSupported(m, valueSizeInBytes)); break; default: UNREACHABLE(); } int i; uint32_t shiftCount; if (ReverseBytesSupported(m, valueSizeInBytes < 4 ? 4 : valueSizeInBytes)) { switch (valueSizeInBytes) { case 2: result = graph()->NewNode(m->Word32ReverseBytes(), graph()->NewNode(m->Word32Shl(), value, mcgraph()->Int32Constant(16))); break; case 4: result = graph()->NewNode(m->Word32ReverseBytes(), value); break; case 8: result = graph()->NewNode(m->Word64ReverseBytes(), value); break; case 16: result = graph()->NewNode(m->Simd128ReverseBytes(), value); break; default: UNREACHABLE(); } } else { for (i = 0, shiftCount = valueSizeInBits - 8; i < valueSizeInBits / 2; i += 8, shiftCount -= 16) { Node* shiftLower; Node* shiftHigher; Node* lowerByte; Node* higherByte; DCHECK_LT(0, shiftCount); DCHECK_EQ(0, (shiftCount + 8) % 16); if (valueSizeInBits > 32) { shiftLower = graph()->NewNode(m->Word64Shl(), value, mcgraph()->Int64Constant(shiftCount)); shiftHigher = graph()->NewNode(m->Word64Shr(), value, mcgraph()->Int64Constant(shiftCount)); lowerByte = graph()->NewNode( m->Word64And(), shiftLower, mcgraph()->Int64Constant(static_cast<uint64_t>(0xFF) << (valueSizeInBits - 8 - i))); higherByte = graph()->NewNode( m->Word64And(), shiftHigher, mcgraph()->Int64Constant(static_cast<uint64_t>(0xFF) << i)); result = graph()->NewNode(m->Word64Or(), result, lowerByte); result = graph()->NewNode(m->Word64Or(), result, higherByte); } else { shiftLower = graph()->NewNode(m->Word32Shl(), value, mcgraph()->Int32Constant(shiftCount)); shiftHigher = graph()->NewNode(m->Word32Shr(), value, mcgraph()->Int32Constant(shiftCount)); lowerByte = graph()->NewNode( m->Word32And(), shiftLower, mcgraph()->Int32Constant(static_cast<uint32_t>(0xFF) << (valueSizeInBits - 8 - i))); higherByte = graph()->NewNode( m->Word32And(), shiftHigher, mcgraph()->Int32Constant(static_cast<uint32_t>(0xFF) << i)); result = graph()->NewNode(m->Word32Or(), result, lowerByte); result = graph()->NewNode(m->Word32Or(), result, higherByte); } } } if (isFloat) { switch (memtype.representation()) { case MachineRepresentation::kFloat64: result = graph()->NewNode(m->BitcastInt64ToFloat64(), result); break; case MachineRepresentation::kFloat32: result = graph()->NewNode(m->BitcastInt32ToFloat32(), result); break; default: UNREACHABLE(); break; } } // We need to sign extend the value if (memtype.IsSigned()) { DCHECK(!isFloat); if (valueSizeInBits < 32) { Node* shiftBitCount; // Perform sign extension using following trick // result = (x << machine_width - type_width) >> (machine_width - // type_width) if (wasmtype == wasm::kWasmI64) { shiftBitCount = mcgraph()->Int32Constant(64 - valueSizeInBits); result = graph()->NewNode( m->Word64Sar(), graph()->NewNode(m->Word64Shl(), graph()->NewNode(m->ChangeInt32ToInt64(), result), shiftBitCount), shiftBitCount); } else if (wasmtype == wasm::kWasmI32) { shiftBitCount = mcgraph()->Int32Constant(32 - valueSizeInBits); result = graph()->NewNode( m->Word32Sar(), graph()->NewNode(m->Word32Shl(), result, shiftBitCount), shiftBitCount); } } } return result; } Node* WasmGraphBuilder::BuildF32CopySign(Node* left, Node* right) { Node* result = Unop( wasm::kExprF32ReinterpretI32, Binop(wasm::kExprI32Ior, Binop(wasm::kExprI32And, Unop(wasm::kExprI32ReinterpretF32, left), mcgraph()->Int32Constant(0x7FFFFFFF)), Binop(wasm::kExprI32And, Unop(wasm::kExprI32ReinterpretF32, right), mcgraph()->Int32Constant(0x80000000)))); return result; } Node* WasmGraphBuilder::BuildF64CopySign(Node* left, Node* right) { if (mcgraph()->machine()->Is64()) { return gasm_->BitcastInt64ToFloat64(gasm_->Word64Or( gasm_->Word64And(gasm_->BitcastFloat64ToInt64(left), gasm_->Int64Constant(0x7FFFFFFFFFFFFFFF)), gasm_->Word64And(gasm_->BitcastFloat64ToInt64(right), gasm_->Int64Constant(0x8000000000000000)))); } DCHECK(mcgraph()->machine()->Is32()); Node* high_word_left = gasm_->Float64ExtractHighWord32(left); Node* high_word_right = gasm_->Float64ExtractHighWord32(right); Node* new_high_word = gasm_->Word32Or( gasm_->Word32And(high_word_left, gasm_->Int32Constant(0x7FFFFFFF)), gasm_->Word32And(high_word_right, gasm_->Int32Constant(0x80000000))); return gasm_->Float64InsertHighWord32(left, new_high_word); } namespace { MachineType IntConvertType(wasm::WasmOpcode opcode) { switch (opcode) { case wasm::kExprI32SConvertF32: case wasm::kExprI32SConvertF64: case wasm::kExprI32SConvertSatF32: case wasm::kExprI32SConvertSatF64: return MachineType::Int32(); case wasm::kExprI32UConvertF32: case wasm::kExprI32UConvertF64: case wasm::kExprI32UConvertSatF32: case wasm::kExprI32UConvertSatF64: return MachineType::Uint32(); case wasm::kExprI64SConvertF32: case wasm::kExprI64SConvertF64: case wasm::kExprI64SConvertSatF32: case wasm::kExprI64SConvertSatF64: return MachineType::Int64(); case wasm::kExprI64UConvertF32: case wasm::kExprI64UConvertF64: case wasm::kExprI64UConvertSatF32: case wasm::kExprI64UConvertSatF64: return MachineType::Uint64(); default: UNREACHABLE(); } } MachineType FloatConvertType(wasm::WasmOpcode opcode) { switch (opcode) { case wasm::kExprI32SConvertF32: case wasm::kExprI32UConvertF32: case wasm::kExprI32SConvertSatF32: case wasm::kExprI64SConvertF32: case wasm::kExprI64UConvertF32: case wasm::kExprI32UConvertSatF32: case wasm::kExprI64SConvertSatF32: case wasm::kExprI64UConvertSatF32: return MachineType::Float32(); case wasm::kExprI32SConvertF64: case wasm::kExprI32UConvertF64: case wasm::kExprI64SConvertF64: case wasm::kExprI64UConvertF64: case wasm::kExprI32SConvertSatF64: case wasm::kExprI32UConvertSatF64: case wasm::kExprI64SConvertSatF64: case wasm::kExprI64UConvertSatF64: return MachineType::Float64(); default: UNREACHABLE(); } } const Operator* ConvertOp(WasmGraphBuilder* builder, wasm::WasmOpcode opcode) { switch (opcode) { case wasm::kExprI32SConvertF32: return builder->mcgraph()->machine()->TruncateFloat32ToInt32( TruncateKind::kSetOverflowToMin); case wasm::kExprI32SConvertSatF32: return builder->mcgraph()->machine()->TruncateFloat32ToInt32( TruncateKind::kArchitectureDefault); case wasm::kExprI32UConvertF32: return builder->mcgraph()->machine()->TruncateFloat32ToUint32( TruncateKind::kSetOverflowToMin); case wasm::kExprI32UConvertSatF32: return builder->mcgraph()->machine()->TruncateFloat32ToUint32( TruncateKind::kArchitectureDefault); case wasm::kExprI32SConvertF64: case wasm::kExprI32SConvertSatF64: return builder->mcgraph()->machine()->ChangeFloat64ToInt32(); case wasm::kExprI32UConvertF64: case wasm::kExprI32UConvertSatF64: return builder->mcgraph()->machine()->TruncateFloat64ToUint32(); case wasm::kExprI64SConvertF32: case wasm::kExprI64SConvertSatF32: return builder->mcgraph()->machine()->TryTruncateFloat32ToInt64(); case wasm::kExprI64UConvertF32: case wasm::kExprI64UConvertSatF32: return builder->mcgraph()->machine()->TryTruncateFloat32ToUint64(); case wasm::kExprI64SConvertF64: case wasm::kExprI64SConvertSatF64: return builder->mcgraph()->machine()->TryTruncateFloat64ToInt64(); case wasm::kExprI64UConvertF64: case wasm::kExprI64UConvertSatF64: return builder->mcgraph()->machine()->TryTruncateFloat64ToUint64(); default: UNREACHABLE(); } } wasm::WasmOpcode ConvertBackOp(wasm::WasmOpcode opcode) { switch (opcode) { case wasm::kExprI32SConvertF32: case wasm::kExprI32SConvertSatF32: return wasm::kExprF32SConvertI32; case wasm::kExprI32UConvertF32: case wasm::kExprI32UConvertSatF32: return wasm::kExprF32UConvertI32; case wasm::kExprI32SConvertF64: case wasm::kExprI32SConvertSatF64: return wasm::kExprF64SConvertI32; case wasm::kExprI32UConvertF64: case wasm::kExprI32UConvertSatF64: return wasm::kExprF64UConvertI32; default: UNREACHABLE(); } } bool IsTrappingConvertOp(wasm::WasmOpcode opcode) { switch (opcode) { case wasm::kExprI32SConvertF32: case wasm::kExprI32UConvertF32: case wasm::kExprI32SConvertF64: case wasm::kExprI32UConvertF64: case wasm::kExprI64SConvertF32: case wasm::kExprI64UConvertF32: case wasm::kExprI64SConvertF64: case wasm::kExprI64UConvertF64: return true; case wasm::kExprI32SConvertSatF64: case wasm::kExprI32UConvertSatF64: case wasm::kExprI32SConvertSatF32: case wasm::kExprI32UConvertSatF32: case wasm::kExprI64SConvertSatF32: case wasm::kExprI64UConvertSatF32: case wasm::kExprI64SConvertSatF64: case wasm::kExprI64UConvertSatF64: return false; default: UNREACHABLE(); } } Node* Zero(WasmGraphBuilder* builder, const MachineType& ty) { switch (ty.representation()) { case MachineRepresentation::kWord32: return builder->Int32Constant(0); case MachineRepresentation::kWord64: return builder->Int64Constant(0); case MachineRepresentation::kFloat32: return builder->Float32Constant(0.0); case MachineRepresentation::kFloat64: return builder->Float64Constant(0.0); default: UNREACHABLE(); } } Node* Min(WasmGraphBuilder* builder, const MachineType& ty) { switch (ty.semantic()) { case MachineSemantic::kInt32: return builder->Int32Constant(std::numeric_limits<int32_t>::min()); case MachineSemantic::kUint32: return builder->Int32Constant(std::numeric_limits<uint32_t>::min()); case MachineSemantic::kInt64: return builder->Int64Constant(std::numeric_limits<int64_t>::min()); case MachineSemantic::kUint64: return builder->Int64Constant(std::numeric_limits<uint64_t>::min()); default: UNREACHABLE(); } } Node* Max(WasmGraphBuilder* builder, const MachineType& ty) { switch (ty.semantic()) { case MachineSemantic::kInt32: return builder->Int32Constant(std::numeric_limits<int32_t>::max()); case MachineSemantic::kUint32: return builder->Int32Constant(std::numeric_limits<uint32_t>::max()); case MachineSemantic::kInt64: return builder->Int64Constant(std::numeric_limits<int64_t>::max()); case MachineSemantic::kUint64: return builder->Int64Constant(std::numeric_limits<uint64_t>::max()); default: UNREACHABLE(); } } wasm::WasmOpcode TruncOp(const MachineType& ty) { switch (ty.representation()) { case MachineRepresentation::kFloat32: return wasm::kExprF32Trunc; case MachineRepresentation::kFloat64: return wasm::kExprF64Trunc; default: UNREACHABLE(); } } wasm::WasmOpcode NeOp(const MachineType& ty) { switch (ty.representation()) { case MachineRepresentation::kFloat32: return wasm::kExprF32Ne; case MachineRepresentation::kFloat64: return wasm::kExprF64Ne; default: UNREACHABLE(); } } wasm::WasmOpcode LtOp(const MachineType& ty) { switch (ty.representation()) { case MachineRepresentation::kFloat32: return wasm::kExprF32Lt; case MachineRepresentation::kFloat64: return wasm::kExprF64Lt; default: UNREACHABLE(); } } Node* ConvertTrapTest(WasmGraphBuilder* builder, wasm::WasmOpcode opcode, const MachineType& int_ty, const MachineType& float_ty, Node* trunc, Node* converted_value) { if (int_ty.representation() == MachineRepresentation::kWord32) { Node* check = builder->Unop(ConvertBackOp(opcode), converted_value); return builder->Binop(NeOp(float_ty), trunc, check); } return builder->graph()->NewNode(builder->mcgraph()->common()->Projection(1), trunc, builder->graph()->start()); } Node* ConvertSaturateTest(WasmGraphBuilder* builder, wasm::WasmOpcode opcode, const MachineType& int_ty, const MachineType& float_ty, Node* trunc, Node* converted_value) { Node* test = ConvertTrapTest(builder, opcode, int_ty, float_ty, trunc, converted_value); if (int_ty.representation() == MachineRepresentation::kWord64) { test = builder->Binop(wasm::kExprI64Eq, test, builder->Int64Constant(0)); } return test; } } // namespace Node* WasmGraphBuilder::BuildIntConvertFloat(Node* input, wasm::WasmCodePosition position, wasm::WasmOpcode opcode) { const MachineType int_ty = IntConvertType(opcode); const MachineType float_ty = FloatConvertType(opcode); const Operator* conv_op = ConvertOp(this, opcode); Node* trunc = nullptr; Node* converted_value = nullptr; const bool is_int32 = int_ty.representation() == MachineRepresentation::kWord32; if (is_int32) { trunc = Unop(TruncOp(float_ty), input); converted_value = graph()->NewNode(conv_op, trunc); } else { trunc = graph()->NewNode(conv_op, input); converted_value = graph()->NewNode(mcgraph()->common()->Projection(0), trunc, graph()->start()); } if (IsTrappingConvertOp(opcode)) { Node* test = ConvertTrapTest(this, opcode, int_ty, float_ty, trunc, converted_value); if (is_int32) { TrapIfTrue(wasm::kTrapFloatUnrepresentable, test, position); } else { ZeroCheck64(wasm::kTrapFloatUnrepresentable, test, position); } return converted_value; } if (mcgraph()->machine()->SatConversionIsSafe()) { return converted_value; } Node* test = ConvertSaturateTest(this, opcode, int_ty, float_ty, trunc, converted_value); Diamond tl_d(graph(), mcgraph()->common(), test, BranchHint::kFalse); tl_d.Chain(control()); Node* nan_test = Binop(NeOp(float_ty), input, input); Diamond nan_d(graph(), mcgraph()->common(), nan_test, BranchHint::kFalse); nan_d.Nest(tl_d, true); Node* neg_test = Binop(LtOp(float_ty), input, Zero(this, float_ty)); Diamond sat_d(graph(), mcgraph()->common(), neg_test, BranchHint::kNone); sat_d.Nest(nan_d, false); Node* sat_val = sat_d.Phi(int_ty.representation(), Min(this, int_ty), Max(this, int_ty)); Node* nan_val = nan_d.Phi(int_ty.representation(), Zero(this, int_ty), sat_val); return tl_d.Phi(int_ty.representation(), nan_val, converted_value); } Node* WasmGraphBuilder::BuildI32AsmjsSConvertF32(Node* input) { MachineOperatorBuilder* m = mcgraph()->machine(); // asm.js must use the wacky JS semantics. input = graph()->NewNode(m->ChangeFloat32ToFloat64(), input); return graph()->NewNode(m->TruncateFloat64ToWord32(), input); } Node* WasmGraphBuilder::BuildI32AsmjsSConvertF64(Node* input) { MachineOperatorBuilder* m = mcgraph()->machine(); // asm.js must use the wacky JS semantics. return graph()->NewNode(m->TruncateFloat64ToWord32(), input); } Node* WasmGraphBuilder::BuildI32AsmjsUConvertF32(Node* input) { MachineOperatorBuilder* m = mcgraph()->machine(); // asm.js must use the wacky JS semantics. input = graph()->NewNode(m->ChangeFloat32ToFloat64(), input); return graph()->NewNode(m->TruncateFloat64ToWord32(), input); } Node* WasmGraphBuilder::BuildI32AsmjsUConvertF64(Node* input) { MachineOperatorBuilder* m = mcgraph()->machine(); // asm.js must use the wacky JS semantics. return graph()->NewNode(m->TruncateFloat64ToWord32(), input); } Node* WasmGraphBuilder::BuildBitCountingCall(Node* input, ExternalReference ref, MachineRepresentation input_type) { Node* stack_slot_param = StoreArgsInStackSlot({{input_type, input}}); MachineType sig_types[] = {MachineType::Int32(), MachineType::Pointer()}; MachineSignature sig(1, 1, sig_types); Node* function = graph()->NewNode(mcgraph()->common()->ExternalConstant(ref)); return BuildCCall(&sig, function, stack_slot_param); } Node* WasmGraphBuilder::BuildI32Ctz(Node* input) { return BuildBitCountingCall(input, ExternalReference::wasm_word32_ctz(), MachineRepresentation::kWord32); } Node* WasmGraphBuilder::BuildI64Ctz(Node* input) { return Unop(wasm::kExprI64UConvertI32, BuildBitCountingCall(input, ExternalReference::wasm_word64_ctz(), MachineRepresentation::kWord64)); } Node* WasmGraphBuilder::BuildI32Popcnt(Node* input) { return BuildBitCountingCall(input, ExternalReference::wasm_word32_popcnt(), MachineRepresentation::kWord32); } Node* WasmGraphBuilder::BuildI64Popcnt(Node* input) { return Unop( wasm::kExprI64UConvertI32, BuildBitCountingCall(input, ExternalReference::wasm_word64_popcnt(), MachineRepresentation::kWord64)); } Node* WasmGraphBuilder::BuildF32Trunc(Node* input) { MachineType type = MachineType::Float32(); ExternalReference ref = ExternalReference::wasm_f32_trunc(); return BuildCFuncInstruction(ref, type, input); } Node* WasmGraphBuilder::BuildF32Floor(Node* input) { MachineType type = MachineType::Float32(); ExternalReference ref = ExternalReference::wasm_f32_floor(); return BuildCFuncInstruction(ref, type, input); } Node* WasmGraphBuilder::BuildF32Ceil(Node* input) { MachineType type = MachineType::Float32(); ExternalReference ref = ExternalReference::wasm_f32_ceil(); return BuildCFuncInstruction(ref, type, input); } Node* WasmGraphBuilder::BuildF32NearestInt(Node* input) { MachineType type = MachineType::Float32(); ExternalReference ref = ExternalReference::wasm_f32_nearest_int(); return BuildCFuncInstruction(ref, type, input); } Node* WasmGraphBuilder::BuildF64Trunc(Node* input) { MachineType type = MachineType::Float64(); ExternalReference ref = ExternalReference::wasm_f64_trunc(); return BuildCFuncInstruction(ref, type, input); } Node* WasmGraphBuilder::BuildF64Floor(Node* input) { MachineType type = MachineType::Float64(); ExternalReference ref = ExternalReference::wasm_f64_floor(); return BuildCFuncInstruction(ref, type, input); } Node* WasmGraphBuilder::BuildF64Ceil(Node* input) { MachineType type = MachineType::Float64(); ExternalReference ref = ExternalReference::wasm_f64_ceil(); return BuildCFuncInstruction(ref, type, input); } Node* WasmGraphBuilder::BuildF64NearestInt(Node* input) { MachineType type = MachineType::Float64(); ExternalReference ref = ExternalReference::wasm_f64_nearest_int(); return BuildCFuncInstruction(ref, type, input); } Node* WasmGraphBuilder::BuildF64Acos(Node* input) { MachineType type = MachineType::Float64(); ExternalReference ref = ExternalReference::f64_acos_wrapper_function(); return BuildCFuncInstruction(ref, type, input); } Node* WasmGraphBuilder::BuildF64Asin(Node* input) { MachineType type = MachineType::Float64(); ExternalReference ref = ExternalReference::f64_asin_wrapper_function(); return BuildCFuncInstruction(ref, type, input); } Node* WasmGraphBuilder::BuildF64Pow(Node* left, Node* right) { MachineType type = MachineType::Float64(); ExternalReference ref = ExternalReference::wasm_float64_pow(); return BuildCFuncInstruction(ref, type, left, right); } Node* WasmGraphBuilder::BuildF64Mod(Node* left, Node* right) { MachineType type = MachineType::Float64(); ExternalReference ref = ExternalReference::f64_mod_wrapper_function(); return BuildCFuncInstruction(ref, type, left, right); } Node* WasmGraphBuilder::BuildCFuncInstruction(ExternalReference ref, MachineType type, Node* input0, Node* input1) { // We do truncation by calling a C function which calculates the result. // The input is passed to the C function as a byte buffer holding the two // input doubles. We reserve this byte buffer as a stack slot, store the // parameters in this buffer slots, pass a pointer to the buffer to the C // function, and after calling the C function we collect the return value from // the buffer. Node* stack_slot; if (input1) { stack_slot = StoreArgsInStackSlot( {{type.representation(), input0}, {type.representation(), input1}}); } else { stack_slot = StoreArgsInStackSlot({{type.representation(), input0}}); } MachineType sig_types[] = {MachineType::Pointer()}; MachineSignature sig(0, 1, sig_types); Node* function = graph()->NewNode(mcgraph()->common()->ExternalConstant(ref)); BuildCCall(&sig, function, stack_slot); return SetEffect(graph()->NewNode(mcgraph()->machine()->Load(type), stack_slot, mcgraph()->Int32Constant(0), effect(), control())); } Node* WasmGraphBuilder::BuildF32SConvertI64(Node* input) { // TODO(titzer/bradnelson): Check handlng of asm.js case. return BuildIntToFloatConversionInstruction( input, ExternalReference::wasm_int64_to_float32(), MachineRepresentation::kWord64, MachineType::Float32()); } Node* WasmGraphBuilder::BuildF32UConvertI64(Node* input) { // TODO(titzer/bradnelson): Check handlng of asm.js case. return BuildIntToFloatConversionInstruction( input, ExternalReference::wasm_uint64_to_float32(), MachineRepresentation::kWord64, MachineType::Float32()); } Node* WasmGraphBuilder::BuildF64SConvertI64(Node* input) { return BuildIntToFloatConversionInstruction( input, ExternalReference::wasm_int64_to_float64(), MachineRepresentation::kWord64, MachineType::Float64()); } Node* WasmGraphBuilder::BuildF64UConvertI64(Node* input) { return BuildIntToFloatConversionInstruction( input, ExternalReference::wasm_uint64_to_float64(), MachineRepresentation::kWord64, MachineType::Float64()); } Node* WasmGraphBuilder::BuildIntToFloatConversionInstruction( Node* input, ExternalReference ref, MachineRepresentation parameter_representation, const MachineType result_type) { int stack_slot_size = std::max(ElementSizeInBytes(parameter_representation), ElementSizeInBytes(result_type.representation())); Node* stack_slot = graph()->NewNode(mcgraph()->machine()->StackSlot(stack_slot_size)); const Operator* store_op = mcgraph()->machine()->Store( StoreRepresentation(parameter_representation, kNoWriteBarrier)); SetEffect(graph()->NewNode(store_op, stack_slot, mcgraph()->Int32Constant(0), input, effect(), control())); MachineType sig_types[] = {MachineType::Pointer()}; MachineSignature sig(0, 1, sig_types); Node* function = graph()->NewNode(mcgraph()->common()->ExternalConstant(ref)); BuildCCall(&sig, function, stack_slot); return SetEffect(graph()->NewNode(mcgraph()->machine()->Load(result_type), stack_slot, mcgraph()->Int32Constant(0), effect(), control())); } namespace { ExternalReference convert_ccall_ref(WasmGraphBuilder* builder, wasm::WasmOpcode opcode) { switch (opcode) { case wasm::kExprI64SConvertF32: case wasm::kExprI64SConvertSatF32: return ExternalReference::wasm_float32_to_int64(); case wasm::kExprI64UConvertF32: case wasm::kExprI64UConvertSatF32: return ExternalReference::wasm_float32_to_uint64(); case wasm::kExprI64SConvertF64: case wasm::kExprI64SConvertSatF64: return ExternalReference::wasm_float64_to_int64(); case wasm::kExprI64UConvertF64: case wasm::kExprI64UConvertSatF64: return ExternalReference::wasm_float64_to_uint64(); default: UNREACHABLE(); } } } // namespace Node* WasmGraphBuilder::BuildCcallConvertFloat(Node* input, wasm::WasmCodePosition position, wasm::WasmOpcode opcode) { const MachineType int_ty = IntConvertType(opcode); const MachineType float_ty = FloatConvertType(opcode); ExternalReference call_ref = convert_ccall_ref(this, opcode); int stack_slot_size = std::max(ElementSizeInBytes(int_ty.representation()), ElementSizeInBytes(float_ty.representation())); Node* stack_slot = graph()->NewNode(mcgraph()->machine()->StackSlot(stack_slot_size)); const Operator* store_op = mcgraph()->machine()->Store( StoreRepresentation(float_ty.representation(), kNoWriteBarrier)); SetEffect(graph()->NewNode(store_op, stack_slot, Int32Constant(0), input, effect(), control())); MachineType sig_types[] = {MachineType::Int32(), MachineType::Pointer()}; MachineSignature sig(1, 1, sig_types); Node* function = graph()->NewNode(mcgraph()->common()->ExternalConstant(call_ref)); Node* overflow = BuildCCall(&sig, function, stack_slot); if (IsTrappingConvertOp(opcode)) { ZeroCheck32(wasm::kTrapFloatUnrepresentable, overflow, position); return SetEffect(graph()->NewNode(mcgraph()->machine()->Load(int_ty), stack_slot, Int32Constant(0), effect(), control())); } Node* test = Binop(wasm::kExprI32Eq, overflow, Int32Constant(0), position); Diamond tl_d(graph(), mcgraph()->common(), test, BranchHint::kFalse); tl_d.Chain(control()); Node* nan_test = Binop(NeOp(float_ty), input, input); Diamond nan_d(graph(), mcgraph()->common(), nan_test, BranchHint::kFalse); nan_d.Nest(tl_d, true); Node* neg_test = Binop(LtOp(float_ty), input, Zero(this, float_ty)); Diamond sat_d(graph(), mcgraph()->common(), neg_test, BranchHint::kNone); sat_d.Nest(nan_d, false); Node* sat_val = sat_d.Phi(int_ty.representation(), Min(this, int_ty), Max(this, int_ty)); Node* load = SetEffect(graph()->NewNode(mcgraph()->machine()->Load(int_ty), stack_slot, Int32Constant(0), effect(), control())); Node* nan_val = nan_d.Phi(int_ty.representation(), Zero(this, int_ty), sat_val); return tl_d.Phi(int_ty.representation(), nan_val, load); } Node* WasmGraphBuilder::MemoryGrow(Node* input) { needs_stack_check_ = true; WasmMemoryGrowDescriptor interface_descriptor; auto call_descriptor = Linkage::GetStubCallDescriptor( mcgraph()->zone(), // zone interface_descriptor, // descriptor interface_descriptor.GetStackParameterCount(), // stack parameter count CallDescriptor::kNoFlags, // flags Operator::kNoProperties, // properties StubCallMode::kCallWasmRuntimeStub); // stub call mode // A direct call to a wasm runtime stub defined in this module. // Just encode the stub index. This will be patched at relocation. Node* call_target = mcgraph()->RelocatableIntPtrConstant( wasm::WasmCode::kWasmMemoryGrow, RelocInfo::WASM_STUB_CALL); return SetEffectControl( graph()->NewNode(mcgraph()->common()->Call(call_descriptor), call_target, input, effect(), control())); } Node* WasmGraphBuilder::Throw(uint32_t exception_index, const wasm::WasmException* exception, const Vector<Node*> values, wasm::WasmCodePosition position) { needs_stack_check_ = true; uint32_t encoded_size = WasmExceptionPackage::GetEncodedSize(exception); Node* create_parameters[] = { LoadExceptionTagFromTable(exception_index), BuildChangeUint31ToSmi(mcgraph()->Uint32Constant(encoded_size))}; Node* except_obj = BuildCallToRuntime(Runtime::kWasmThrowCreate, create_parameters, arraysize(create_parameters)); SetSourcePosition(except_obj, position); Node* values_array = CALL_BUILTIN( WasmGetOwnProperty, except_obj, LOAD_FULL_POINTER(BuildLoadIsolateRoot(), IsolateData::root_slot_offset( RootIndex::kwasm_exception_values_symbol)), LOAD_INSTANCE_FIELD(NativeContext, MachineType::TaggedPointer())); uint32_t index = 0; const wasm::WasmExceptionSig* sig = exception->sig; MachineOperatorBuilder* m = mcgraph()->machine(); for (size_t i = 0; i < sig->parameter_count(); ++i) { Node* value = values[i]; switch (sig->GetParam(i).kind()) { case wasm::ValueType::kF32: value = graph()->NewNode(m->BitcastFloat32ToInt32(), value); V8_FALLTHROUGH; case wasm::ValueType::kI32: BuildEncodeException32BitValue(values_array, &index, value); break; case wasm::ValueType::kF64: value = graph()->NewNode(m->BitcastFloat64ToInt64(), value); V8_FALLTHROUGH; case wasm::ValueType::kI64: { Node* upper32 = graph()->NewNode( m->TruncateInt64ToInt32(), Binop(wasm::kExprI64ShrU, value, Int64Constant(32))); BuildEncodeException32BitValue(values_array, &index, upper32); Node* lower32 = graph()->NewNode(m->TruncateInt64ToInt32(), value); BuildEncodeException32BitValue(values_array, &index, lower32); break; } case wasm::ValueType::kS128: BuildEncodeException32BitValue( values_array, &index, graph()->NewNode(m->I32x4ExtractLane(0), value)); BuildEncodeException32BitValue( values_array, &index, graph()->NewNode(m->I32x4ExtractLane(1), value)); BuildEncodeException32BitValue( values_array, &index, graph()->NewNode(m->I32x4ExtractLane(2), value)); BuildEncodeException32BitValue( values_array, &index, graph()->NewNode(m->I32x4ExtractLane(3), value)); break; case wasm::ValueType::kRef: case wasm::ValueType::kOptRef: STORE_FIXED_ARRAY_SLOT_ANY(values_array, index, value); ++index; break; case wasm::ValueType::kRtt: // TODO(7748): Implement. case wasm::ValueType::kI8: case wasm::ValueType::kI16: case wasm::ValueType::kStmt: case wasm::ValueType::kBottom: UNREACHABLE(); } } DCHECK_EQ(encoded_size, index); WasmThrowDescriptor interface_descriptor; auto call_descriptor = Linkage::GetStubCallDescriptor( mcgraph()->zone(), interface_descriptor, interface_descriptor.GetStackParameterCount(), CallDescriptor::kNoFlags, Operator::kNoProperties, StubCallMode::kCallWasmRuntimeStub); Node* call_target = mcgraph()->RelocatableIntPtrConstant( wasm::WasmCode::kWasmThrow, RelocInfo::WASM_STUB_CALL); Node* call = SetEffectControl( graph()->NewNode(mcgraph()->common()->Call(call_descriptor), call_target, except_obj, effect(), control())); SetSourcePosition(call, position); return call; } void WasmGraphBuilder::BuildEncodeException32BitValue(Node* values_array, uint32_t* index, Node* value) { MachineOperatorBuilder* machine = mcgraph()->machine(); Node* upper_halfword_as_smi = BuildChangeUint31ToSmi( graph()->NewNode(machine->Word32Shr(), value, Int32Constant(16))); STORE_FIXED_ARRAY_SLOT_SMI(values_array, *index, upper_halfword_as_smi); ++(*index); Node* lower_halfword_as_smi = BuildChangeUint31ToSmi( graph()->NewNode(machine->Word32And(), value, Int32Constant(0xFFFFu))); STORE_FIXED_ARRAY_SLOT_SMI(values_array, *index, lower_halfword_as_smi); ++(*index); } Node* WasmGraphBuilder::BuildDecodeException32BitValue(Node* values_array, uint32_t* index) { MachineOperatorBuilder* machine = mcgraph()->machine(); Node* upper = BuildChangeSmiToInt32(LOAD_FIXED_ARRAY_SLOT_SMI(values_array, *index)); (*index)++; upper = graph()->NewNode(machine->Word32Shl(), upper, Int32Constant(16)); Node* lower = BuildChangeSmiToInt32(LOAD_FIXED_ARRAY_SLOT_SMI(values_array, *index)); (*index)++; Node* value = graph()->NewNode(machine->Word32Or(), upper, lower); return value; } Node* WasmGraphBuilder::BuildDecodeException64BitValue(Node* values_array, uint32_t* index) { Node* upper = Binop(wasm::kExprI64Shl, Unop(wasm::kExprI64UConvertI32, BuildDecodeException32BitValue(values_array, index)), Int64Constant(32)); Node* lower = Unop(wasm::kExprI64UConvertI32, BuildDecodeException32BitValue(values_array, index)); return Binop(wasm::kExprI64Ior, upper, lower); } Node* WasmGraphBuilder::Rethrow(Node* except_obj) { // TODO(v8:8091): Currently the message of the original exception is not being // preserved when rethrown to the console. The pending message will need to be // saved when caught and restored here while being rethrown. WasmThrowDescriptor interface_descriptor; auto call_descriptor = Linkage::GetStubCallDescriptor( mcgraph()->zone(), interface_descriptor, interface_descriptor.GetStackParameterCount(), CallDescriptor::kNoFlags, Operator::kNoProperties, StubCallMode::kCallWasmRuntimeStub); Node* call_target = mcgraph()->RelocatableIntPtrConstant( wasm::WasmCode::kWasmRethrow, RelocInfo::WASM_STUB_CALL); return gasm_->Call(call_descriptor, call_target, except_obj); } Node* WasmGraphBuilder::ExceptionTagEqual(Node* caught_tag, Node* expected_tag) { MachineOperatorBuilder* machine = mcgraph()->machine(); return graph()->NewNode(machine->WordEqual(), caught_tag, expected_tag); } Node* WasmGraphBuilder::LoadExceptionTagFromTable(uint32_t exception_index) { Node* exceptions_table = LOAD_INSTANCE_FIELD(ExceptionsTable, MachineType::TaggedPointer()); Node* tag = LOAD_FIXED_ARRAY_SLOT_PTR(exceptions_table, exception_index); return tag; } Node* WasmGraphBuilder::GetExceptionTag(Node* except_obj, wasm::WasmCodePosition position) { TrapIfTrue(wasm::kTrapBrOnExnNull, gasm_->WordEqual(RefNull(), except_obj), position); return CALL_BUILTIN( WasmGetOwnProperty, except_obj, LOAD_FULL_POINTER( BuildLoadIsolateRoot(), IsolateData::root_slot_offset(RootIndex::kwasm_exception_tag_symbol)), LOAD_INSTANCE_FIELD(NativeContext, MachineType::TaggedPointer())); } Node* WasmGraphBuilder::GetExceptionValues(Node* except_obj, const wasm::WasmException* exception, Vector<Node*> values) { Node* values_array = CALL_BUILTIN( WasmGetOwnProperty, except_obj, LOAD_FULL_POINTER(BuildLoadIsolateRoot(), IsolateData::root_slot_offset( RootIndex::kwasm_exception_values_symbol)), LOAD_INSTANCE_FIELD(NativeContext, MachineType::TaggedPointer())); uint32_t index = 0; const wasm::WasmExceptionSig* sig = exception->sig; DCHECK_EQ(sig->parameter_count(), values.size()); for (size_t i = 0; i < sig->parameter_count(); ++i) { Node* value; switch (sig->GetParam(i).kind()) { case wasm::ValueType::kI32: value = BuildDecodeException32BitValue(values_array, &index); break; case wasm::ValueType::kI64: value = BuildDecodeException64BitValue(values_array, &index); break; case wasm::ValueType::kF32: { value = Unop(wasm::kExprF32ReinterpretI32, BuildDecodeException32BitValue(values_array, &index)); break; } case wasm::ValueType::kF64: { value = Unop(wasm::kExprF64ReinterpretI64, BuildDecodeException64BitValue(values_array, &index)); break; } case wasm::ValueType::kS128: value = graph()->NewNode( mcgraph()->machine()->I32x4Splat(), BuildDecodeException32BitValue(values_array, &index)); value = graph()->NewNode( mcgraph()->machine()->I32x4ReplaceLane(1), value, BuildDecodeException32BitValue(values_array, &index)); value = graph()->NewNode( mcgraph()->machine()->I32x4ReplaceLane(2), value, BuildDecodeException32BitValue(values_array, &index)); value = graph()->NewNode( mcgraph()->machine()->I32x4ReplaceLane(3), value, BuildDecodeException32BitValue(values_array, &index)); break; case wasm::ValueType::kRef: case wasm::ValueType::kOptRef: value = LOAD_FIXED_ARRAY_SLOT_ANY(values_array, index); ++index; break; case wasm::ValueType::kRtt: // TODO(7748): Implement. case wasm::ValueType::kI8: case wasm::ValueType::kI16: case wasm::ValueType::kStmt: case wasm::ValueType::kBottom: UNREACHABLE(); } values[i] = value; } DCHECK_EQ(index, WasmExceptionPackage::GetEncodedSize(exception)); return values_array; } Node* WasmGraphBuilder::BuildI32DivS(Node* left, Node* right, wasm::WasmCodePosition position) { MachineOperatorBuilder* m = mcgraph()->machine(); ZeroCheck32(wasm::kTrapDivByZero, right, position); Node* before = control(); Node* denom_is_m1; Node* denom_is_not_m1; BranchExpectFalse( graph()->NewNode(m->Word32Equal(), right, mcgraph()->Int32Constant(-1)), &denom_is_m1, &denom_is_not_m1); SetControl(denom_is_m1); TrapIfEq32(wasm::kTrapDivUnrepresentable, left, kMinInt, position); if (control() != denom_is_m1) { SetControl(graph()->NewNode(mcgraph()->common()->Merge(2), denom_is_not_m1, control())); } else { SetControl(before); } return graph()->NewNode(m->Int32Div(), left, right, control()); } Node* WasmGraphBuilder::BuildI32RemS(Node* left, Node* right, wasm::WasmCodePosition position) { MachineOperatorBuilder* m = mcgraph()->machine(); ZeroCheck32(wasm::kTrapRemByZero, right, position); Diamond d( graph(), mcgraph()->common(), graph()->NewNode(m->Word32Equal(), right, mcgraph()->Int32Constant(-1)), BranchHint::kFalse); d.Chain(control()); return d.Phi(MachineRepresentation::kWord32, mcgraph()->Int32Constant(0), graph()->NewNode(m->Int32Mod(), left, right, d.if_false)); } Node* WasmGraphBuilder::BuildI32DivU(Node* left, Node* right, wasm::WasmCodePosition position) { MachineOperatorBuilder* m = mcgraph()->machine(); return graph()->NewNode(m->Uint32Div(), left, right, ZeroCheck32(wasm::kTrapDivByZero, right, position)); } Node* WasmGraphBuilder::BuildI32RemU(Node* left, Node* right, wasm::WasmCodePosition position) { MachineOperatorBuilder* m = mcgraph()->machine(); return graph()->NewNode(m->Uint32Mod(), left, right, ZeroCheck32(wasm::kTrapRemByZero, right, position)); } Node* WasmGraphBuilder::BuildI32AsmjsDivS(Node* left, Node* right) { MachineOperatorBuilder* m = mcgraph()->machine(); Int32Matcher mr(right); if (mr.HasValue()) { if (mr.Value() == 0) { return mcgraph()->Int32Constant(0); } else if (mr.Value() == -1) { // The result is the negation of the left input. return graph()->NewNode(m->Int32Sub(), mcgraph()->Int32Constant(0), left); } return graph()->NewNode(m->Int32Div(), left, right, control()); } // asm.js semantics return 0 on divide or mod by zero. if (m->Int32DivIsSafe()) { // The hardware instruction does the right thing (e.g. arm). return graph()->NewNode(m->Int32Div(), left, right, graph()->start()); } // Check denominator for zero. Diamond z( graph(), mcgraph()->common(), graph()->NewNode(m->Word32Equal(), right, mcgraph()->Int32Constant(0)), BranchHint::kFalse); // Check numerator for -1. (avoid minint / -1 case). Diamond n( graph(), mcgraph()->common(), graph()->NewNode(m->Word32Equal(), right, mcgraph()->Int32Constant(-1)), BranchHint::kFalse); Node* div = graph()->NewNode(m->Int32Div(), left, right, z.if_false); Node* neg = graph()->NewNode(m->Int32Sub(), mcgraph()->Int32Constant(0), left); return n.Phi( MachineRepresentation::kWord32, neg, z.Phi(MachineRepresentation::kWord32, mcgraph()->Int32Constant(0), div)); } Node* WasmGraphBuilder::BuildI32AsmjsRemS(Node* left, Node* right) { CommonOperatorBuilder* c = mcgraph()->common(); MachineOperatorBuilder* m = mcgraph()->machine(); Node* const zero = mcgraph()->Int32Constant(0); Int32Matcher mr(right); if (mr.HasValue()) { if (mr.Value() == 0 || mr.Value() == -1) { return zero; } return graph()->NewNode(m->Int32Mod(), left, right, control()); } // General case for signed integer modulus, with optimization for (unknown) // power of 2 right hand side. // // if 0 < right then // msk = right - 1 // if right & msk != 0 then // left % right // else // if left < 0 then // -(-left & msk) // else // left & msk // else // if right < -1 then // left % right // else // zero // // Note: We do not use the Diamond helper class here, because it really hurts // readability with nested diamonds. Node* const minus_one = mcgraph()->Int32Constant(-1); const Operator* const merge_op = c->Merge(2); const Operator* const phi_op = c->Phi(MachineRepresentation::kWord32, 2); Node* check0 = graph()->NewNode(m->Int32LessThan(), zero, right); Node* branch0 = graph()->NewNode(c->Branch(BranchHint::kTrue), check0, graph()->start()); Node* if_true0 = graph()->NewNode(c->IfTrue(), branch0); Node* true0; { Node* msk = graph()->NewNode(m->Int32Add(), right, minus_one); Node* check1 = graph()->NewNode(m->Word32And(), right, msk); Node* branch1 = graph()->NewNode(c->Branch(), check1, if_true0); Node* if_true1 = graph()->NewNode(c->IfTrue(), branch1); Node* true1 = graph()->NewNode(m->Int32Mod(), left, right, if_true1); Node* if_false1 = graph()->NewNode(c->IfFalse(), branch1); Node* false1; { Node* check2 = graph()->NewNode(m->Int32LessThan(), left, zero); Node* branch2 = graph()->NewNode(c->Branch(BranchHint::kFalse), check2, if_false1); Node* if_true2 = graph()->NewNode(c->IfTrue(), branch2); Node* true2 = graph()->NewNode( m->Int32Sub(), zero, graph()->NewNode(m->Word32And(), graph()->NewNode(m->Int32Sub(), zero, left), msk)); Node* if_false2 = graph()->NewNode(c->IfFalse(), branch2); Node* false2 = graph()->NewNode(m->Word32And(), left, msk); if_false1 = graph()->NewNode(merge_op, if_true2, if_false2); false1 = graph()->NewNode(phi_op, true2, false2, if_false1); } if_true0 = graph()->NewNode(merge_op, if_true1, if_false1); true0 = graph()->NewNode(phi_op, true1, false1, if_true0); } Node* if_false0 = graph()->NewNode(c->IfFalse(), branch0); Node* false0; { Node* check1 = graph()->NewNode(m->Int32LessThan(), right, minus_one); Node* branch1 = graph()->NewNode(c->Branch(BranchHint::kTrue), check1, if_false0); Node* if_true1 = graph()->NewNode(c->IfTrue(), branch1); Node* true1 = graph()->NewNode(m->Int32Mod(), left, right, if_true1); Node* if_false1 = graph()->NewNode(c->IfFalse(), branch1); Node* false1 = zero; if_false0 = graph()->NewNode(merge_op, if_true1, if_false1); false0 = graph()->NewNode(phi_op, true1, false1, if_false0); } Node* merge0 = graph()->NewNode(merge_op, if_true0, if_false0); return graph()->NewNode(phi_op, true0, false0, merge0); } Node* WasmGraphBuilder::BuildI32AsmjsDivU(Node* left, Node* right) { MachineOperatorBuilder* m = mcgraph()->machine(); // asm.js semantics return 0 on divide or mod by zero. if (m->Uint32DivIsSafe()) { // The hardware instruction does the right thing (e.g. arm). return graph()->NewNode(m->Uint32Div(), left, right, graph()->start()); } // Explicit check for x % 0. Diamond z( graph(), mcgraph()->common(), graph()->NewNode(m->Word32Equal(), right, mcgraph()->Int32Constant(0)), BranchHint::kFalse); return z.Phi(MachineRepresentation::kWord32, mcgraph()->Int32Constant(0), graph()->NewNode(mcgraph()->machine()->Uint32Div(), left, right, z.if_false)); } Node* WasmGraphBuilder::BuildI32AsmjsRemU(Node* left, Node* right) { MachineOperatorBuilder* m = mcgraph()->machine(); // asm.js semantics return 0 on divide or mod by zero. // Explicit check for x % 0. Diamond z( graph(), mcgraph()->common(), graph()->NewNode(m->Word32Equal(), right, mcgraph()->Int32Constant(0)), BranchHint::kFalse); Node* rem = graph()->NewNode(mcgraph()->machine()->Uint32Mod(), left, right, z.if_false); return z.Phi(MachineRepresentation::kWord32, mcgraph()->Int32Constant(0), rem); } Node* WasmGraphBuilder::BuildI64DivS(Node* left, Node* right, wasm::WasmCodePosition position) { if (mcgraph()->machine()->Is32()) { return BuildDiv64Call(left, right, ExternalReference::wasm_int64_div(), MachineType::Int64(), wasm::kTrapDivByZero, position); } ZeroCheck64(wasm::kTrapDivByZero, right, position); Node* before = control(); Node* denom_is_m1; Node* denom_is_not_m1; BranchExpectFalse(graph()->NewNode(mcgraph()->machine()->Word64Equal(), right, mcgraph()->Int64Constant(-1)), &denom_is_m1, &denom_is_not_m1); SetControl(denom_is_m1); TrapIfEq64(wasm::kTrapDivUnrepresentable, left, std::numeric_limits<int64_t>::min(), position); if (control() != denom_is_m1) { SetControl(graph()->NewNode(mcgraph()->common()->Merge(2), denom_is_not_m1, control())); } else { SetControl(before); } return graph()->NewNode(mcgraph()->machine()->Int64Div(), left, right, control()); } Node* WasmGraphBuilder::BuildI64RemS(Node* left, Node* right, wasm::WasmCodePosition position) { if (mcgraph()->machine()->Is32()) { return BuildDiv64Call(left, right, ExternalReference::wasm_int64_mod(), MachineType::Int64(), wasm::kTrapRemByZero, position); } ZeroCheck64(wasm::kTrapRemByZero, right, position); Diamond d(mcgraph()->graph(), mcgraph()->common(), graph()->NewNode(mcgraph()->machine()->Word64Equal(), right, mcgraph()->Int64Constant(-1))); d.Chain(control()); Node* rem = graph()->NewNode(mcgraph()->machine()->Int64Mod(), left, right, d.if_false); return d.Phi(MachineRepresentation::kWord64, mcgraph()->Int64Constant(0), rem); } Node* WasmGraphBuilder::BuildI64DivU(Node* left, Node* right, wasm::WasmCodePosition position) { if (mcgraph()->machine()->Is32()) { return BuildDiv64Call(left, right, ExternalReference::wasm_uint64_div(), MachineType::Int64(), wasm::kTrapDivByZero, position); } return graph()->NewNode(mcgraph()->machine()->Uint64Div(), left, right, ZeroCheck64(wasm::kTrapDivByZero, right, position)); } Node* WasmGraphBuilder::BuildI64RemU(Node* left, Node* right, wasm::WasmCodePosition position) { if (mcgraph()->machine()->Is32()) { return BuildDiv64Call(left, right, ExternalReference::wasm_uint64_mod(), MachineType::Int64(), wasm::kTrapRemByZero, position); } return graph()->NewNode(mcgraph()->machine()->Uint64Mod(), left, right, ZeroCheck64(wasm::kTrapRemByZero, right, position)); } Node* WasmGraphBuilder::GetBuiltinPointerTarget(int builtin_id) { static_assert(std::is_same<Smi, BuiltinPtr>(), "BuiltinPtr must be Smi"); return graph()->NewNode(mcgraph()->common()->NumberConstant(builtin_id)); } Node* WasmGraphBuilder::BuildDiv64Call(Node* left, Node* right, ExternalReference ref, MachineType result_type, wasm::TrapReason trap_zero, wasm::WasmCodePosition position) { Node* stack_slot = StoreArgsInStackSlot({{MachineRepresentation::kWord64, left}, {MachineRepresentation::kWord64, right}}); MachineType sig_types[] = {MachineType::Int32(), MachineType::Pointer()}; MachineSignature sig(1, 1, sig_types); Node* function = graph()->NewNode(mcgraph()->common()->ExternalConstant(ref)); Node* call = BuildCCall(&sig, function, stack_slot); ZeroCheck32(trap_zero, call, position); TrapIfEq32(wasm::kTrapDivUnrepresentable, call, -1, position); return SetEffect(graph()->NewNode(mcgraph()->machine()->Load(result_type), stack_slot, mcgraph()->Int32Constant(0), effect(), control())); } template <typename... Args> Node* WasmGraphBuilder::BuildCCall(MachineSignature* sig, Node* function, Args... args) { DCHECK_LE(sig->return_count(), 1); DCHECK_EQ(sizeof...(args), sig->parameter_count()); Node* const call_args[] = {function, args..., effect(), control()}; auto call_descriptor = Linkage::GetSimplifiedCDescriptor(mcgraph()->zone(), sig); const Operator* op = mcgraph()->common()->Call(call_descriptor); return SetEffect(graph()->NewNode(op, arraysize(call_args), call_args)); } Node* WasmGraphBuilder::BuildCallNode(const wasm::FunctionSig* sig, Vector<Node*> args, wasm::WasmCodePosition position, Node* instance_node, const Operator* op) { if (instance_node == nullptr) { DCHECK_NOT_NULL(instance_node_); instance_node = instance_node_.get(); } needs_stack_check_ = true; const size_t params = sig->parameter_count(); const size_t extra = 3; // instance_node, effect, and control. const size_t count = 1 + params + extra; // Reallocate the buffer to make space for extra inputs. base::SmallVector<Node*, 16 + extra> inputs(count); DCHECK_EQ(1 + params, args.size()); // Make room for the instance_node parameter at index 1, just after code. inputs[0] = args[0]; // code inputs[1] = instance_node; if (params > 0) memcpy(&inputs[2], &args[1], params * sizeof(Node*)); // Add effect and control inputs. inputs[params + 2] = effect(); inputs[params + 3] = control(); Node* call = graph()->NewNode(op, static_cast<int>(count), inputs.begin()); // Return calls have no effect output. Other calls are the new effect node. if (op->EffectOutputCount() > 0) SetEffect(call); DCHECK(position == wasm::kNoCodePosition || position > 0); if (position > 0) SetSourcePosition(call, position); return call; } Node* WasmGraphBuilder::BuildWasmCall(const wasm::FunctionSig* sig, Vector<Node*> args, Vector<Node*> rets, wasm::WasmCodePosition position, Node* instance_node, UseRetpoline use_retpoline) { CallDescriptor* call_descriptor = GetWasmCallDescriptor(mcgraph()->zone(), sig, use_retpoline); const Operator* op = mcgraph()->common()->Call(call_descriptor); Node* call = BuildCallNode(sig, args, position, instance_node, op); size_t ret_count = sig->return_count(); if (ret_count == 0) return call; // No return value. DCHECK_EQ(ret_count, rets.size()); if (ret_count == 1) { // Only a single return value. rets[0] = call; } else { // Create projections for all return values. for (size_t i = 0; i < ret_count; i++) { rets[i] = graph()->NewNode(mcgraph()->common()->Projection(i), call, graph()->start()); } } return call; } Node* WasmGraphBuilder::BuildWasmReturnCall(const wasm::FunctionSig* sig, Vector<Node*> args, wasm::WasmCodePosition position, Node* instance_node, UseRetpoline use_retpoline) { CallDescriptor* call_descriptor = GetWasmCallDescriptor(mcgraph()->zone(), sig, use_retpoline); const Operator* op = mcgraph()->common()->TailCall(call_descriptor); Node* call = BuildCallNode(sig, args, position, instance_node, op); MergeControlToEnd(mcgraph(), call); return call; } Node* WasmGraphBuilder::BuildImportCall(const wasm::FunctionSig* sig, Vector<Node*> args, Vector<Node*> rets, wasm::WasmCodePosition position, int func_index, IsReturnCall continuation) { // Load the imported function refs array from the instance. Node* imported_function_refs = LOAD_INSTANCE_FIELD(ImportedFunctionRefs, MachineType::TaggedPointer()); Node* ref_node = LOAD_FIXED_ARRAY_SLOT_PTR(imported_function_refs, func_index); // Load the target from the imported_targets array at a known offset. Node* imported_targets = LOAD_INSTANCE_FIELD(ImportedFunctionTargets, MachineType::Pointer()); Node* target_node = SetEffect(graph()->NewNode( mcgraph()->machine()->Load(MachineType::Pointer()), imported_targets, mcgraph()->Int32Constant(func_index * kSystemPointerSize), effect(), control())); args[0] = target_node; const UseRetpoline use_retpoline = untrusted_code_mitigations_ ? kRetpoline : kNoRetpoline; switch (continuation) { case kCallContinues: return BuildWasmCall(sig, args, rets, position, ref_node, use_retpoline); case kReturnCall: DCHECK(rets.empty()); return BuildWasmReturnCall(sig, args, position, ref_node, use_retpoline); } } Node* WasmGraphBuilder::BuildImportCall(const wasm::FunctionSig* sig, Vector<Node*> args, Vector<Node*> rets, wasm::WasmCodePosition position, Node* func_index, IsReturnCall continuation) { // Load the imported function refs array from the instance. Node* imported_function_refs = LOAD_INSTANCE_FIELD(ImportedFunctionRefs, MachineType::TaggedPointer()); // Access fixed array at {header_size - tag + func_index * kTaggedSize}. Node* imported_instances_data = graph()->NewNode( mcgraph()->machine()->IntAdd(), imported_function_refs, mcgraph()->IntPtrConstant( wasm::ObjectAccess::ElementOffsetInTaggedFixedArray(0))); Node* func_index_times_tagged_size = graph()->NewNode( mcgraph()->machine()->IntMul(), Uint32ToUintptr(func_index), mcgraph()->Int32Constant(kTaggedSize)); Node* ref_node = gasm_->Load(MachineType::TaggedPointer(), imported_instances_data, func_index_times_tagged_size); // Load the target from the imported_targets array at the offset of // {func_index}. Node* func_index_times_pointersize; if (kSystemPointerSize == kTaggedSize) { func_index_times_pointersize = func_index_times_tagged_size; } else { DCHECK_EQ(kSystemPointerSize, kTaggedSize + kTaggedSize); func_index_times_pointersize = graph()->NewNode( mcgraph()->machine()->Int32Add(), func_index_times_tagged_size, func_index_times_tagged_size); } Node* imported_targets = LOAD_INSTANCE_FIELD(ImportedFunctionTargets, MachineType::Pointer()); Node* target_node = SetEffect(graph()->NewNode( mcgraph()->machine()->Load(MachineType::Pointer()), imported_targets, func_index_times_pointersize, effect(), control())); args[0] = target_node; const UseRetpoline use_retpoline = untrusted_code_mitigations_ ? kRetpoline : kNoRetpoline; switch (continuation) { case kCallContinues: return BuildWasmCall(sig, args, rets, position, ref_node, use_retpoline); case kReturnCall: DCHECK(rets.empty()); return BuildWasmReturnCall(sig, args, position, ref_node, use_retpoline); } } Node* WasmGraphBuilder::CallDirect(uint32_t index, Vector<Node*> args, Vector<Node*> rets, wasm::WasmCodePosition position) { DCHECK_NULL(args[0]); const wasm::FunctionSig* sig = env_->module->functions[index].sig; if (env_ && index < env_->module->num_imported_functions) { // Call to an imported function. return BuildImportCall(sig, args, rets, position, index, kCallContinues); } // A direct call to a wasm function defined in this module. // Just encode the function index. This will be patched at instantiation. Address code = static_cast<Address>(index); args[0] = mcgraph()->RelocatableIntPtrConstant(code, RelocInfo::WASM_CALL); return BuildWasmCall(sig, args, rets, position, nullptr, kNoRetpoline); } Node* WasmGraphBuilder::CallIndirect(uint32_t table_index, uint32_t sig_index, Vector<Node*> args, Vector<Node*> rets, wasm::WasmCodePosition position) { return BuildIndirectCall(table_index, sig_index, args, rets, position, kCallContinues); } void WasmGraphBuilder::LoadIndirectFunctionTable(uint32_t table_index, Node** ift_size, Node** ift_sig_ids, Node** ift_targets, Node** ift_instances) { if (table_index == 0) { *ift_size = LOAD_INSTANCE_FIELD(IndirectFunctionTableSize, MachineType::Uint32()); *ift_sig_ids = LOAD_INSTANCE_FIELD(IndirectFunctionTableSigIds, MachineType::Pointer()); *ift_targets = LOAD_INSTANCE_FIELD(IndirectFunctionTableTargets, MachineType::Pointer()); *ift_instances = LOAD_INSTANCE_FIELD(IndirectFunctionTableRefs, MachineType::TaggedPointer()); return; } Node* ift_tables = LOAD_INSTANCE_FIELD(IndirectFunctionTables, MachineType::TaggedPointer()); Node* ift_table = LOAD_FIXED_ARRAY_SLOT_ANY(ift_tables, table_index); *ift_size = gasm_->Load( MachineType::Int32(), ift_table, wasm::ObjectAccess::ToTagged(WasmIndirectFunctionTable::kSizeOffset)); *ift_sig_ids = gasm_->Load( MachineType::Pointer(), ift_table, wasm::ObjectAccess::ToTagged(WasmIndirectFunctionTable::kSigIdsOffset)); *ift_targets = gasm_->Load( MachineType::Pointer(), ift_table, wasm::ObjectAccess::ToTagged(WasmIndirectFunctionTable::kTargetsOffset)); *ift_instances = gasm_->Load( MachineType::TaggedPointer(), ift_table, wasm::ObjectAccess::ToTagged(WasmIndirectFunctionTable::kRefsOffset)); } Node* WasmGraphBuilder::BuildIndirectCall(uint32_t table_index, uint32_t sig_index, Vector<Node*> args, Vector<Node*> rets, wasm::WasmCodePosition position, IsReturnCall continuation) { DCHECK_NOT_NULL(args[0]); DCHECK_NOT_NULL(env_); // First we have to load the table. Node* ift_size; Node* ift_sig_ids; Node* ift_targets; Node* ift_instances; LoadIndirectFunctionTable(table_index, &ift_size, &ift_sig_ids, &ift_targets, &ift_instances); const wasm::FunctionSig* sig = env_->module->signature(sig_index); MachineOperatorBuilder* machine = mcgraph()->machine(); Node* key = args[0]; // Bounds check against the table size. Node* in_bounds = graph()->NewNode(machine->Uint32LessThan(), key, ift_size); TrapIfFalse(wasm::kTrapTableOutOfBounds, in_bounds, position); // Mask the key to prevent SSCA. if (untrusted_code_mitigations_) { // mask = ((key - size) & ~key) >> 31 Node* neg_key = graph()->NewNode(machine->Word32Xor(), key, Int32Constant(-1)); Node* masked_diff = graph()->NewNode( machine->Word32And(), graph()->NewNode(machine->Int32Sub(), key, ift_size), neg_key); Node* mask = graph()->NewNode(machine->Word32Sar(), masked_diff, Int32Constant(31)); key = graph()->NewNode(machine->Word32And(), key, mask); } Node* int32_scaled_key = Uint32ToUintptr( graph()->NewNode(machine->Word32Shl(), key, Int32Constant(2))); Node* loaded_sig = SetEffect( graph()->NewNode(machine->Load(MachineType::Int32()), ift_sig_ids, int32_scaled_key, effect(), control())); // Check that the dynamic type of the function is a subtype of its static // (table) type. Currently, the only subtyping between function types is // $t <: funcref for all $t: function_type. // TODO(7748): Expand this with function subtyping. const bool needs_typechecking = env_->module->tables[table_index].type == wasm::kWasmFuncRef; if (needs_typechecking) { int32_t expected_sig_id = env_->module->canonicalized_type_ids[sig_index]; Node* sig_match = graph()->NewNode(machine->Word32Equal(), loaded_sig, Int32Constant(expected_sig_id)); TrapIfFalse(wasm::kTrapFuncSigMismatch, sig_match, position); } else { // We still have to check that the entry is initialized. // TODO(9495): Skip this check for non-nullable tables when they are // allowed. Node* function_is_null = graph()->NewNode(machine->Word32Equal(), loaded_sig, Int32Constant(-1)); TrapIfTrue(wasm::kTrapNullDereference, function_is_null, position); } Node* tagged_scaled_key; if (kTaggedSize == kInt32Size) { tagged_scaled_key = int32_scaled_key; } else { DCHECK_EQ(kTaggedSize, kInt32Size * 2); tagged_scaled_key = graph()->NewNode(machine->Int32Add(), int32_scaled_key, int32_scaled_key); } Node* target_instance = gasm_->Load( MachineType::TaggedPointer(), graph()->NewNode(machine->IntAdd(), ift_instances, tagged_scaled_key), wasm::ObjectAccess::ElementOffsetInTaggedFixedArray(0)); Node* intptr_scaled_key; if (kSystemPointerSize == kTaggedSize) { intptr_scaled_key = tagged_scaled_key; } else { DCHECK_EQ(kSystemPointerSize, kTaggedSize + kTaggedSize); intptr_scaled_key = graph()->NewNode(machine->Int32Add(), tagged_scaled_key, tagged_scaled_key); } Node* target = SetEffect( graph()->NewNode(machine->Load(MachineType::Pointer()), ift_targets, intptr_scaled_key, effect(), control())); args[0] = target; const UseRetpoline use_retpoline = untrusted_code_mitigations_ ? kRetpoline : kNoRetpoline; switch (continuation) { case kCallContinues: return BuildWasmCall(sig, args, rets, position, target_instance, use_retpoline); case kReturnCall: return BuildWasmReturnCall(sig, args, position, target_instance, use_retpoline); } } Node* WasmGraphBuilder::BuildLoadFunctionDataFromExportedFunction( Node* closure) { Node* shared = gasm_->Load( MachineType::AnyTagged(), closure, wasm::ObjectAccess::SharedFunctionInfoOffsetInTaggedJSFunction()); return gasm_->Load(MachineType::AnyTagged(), shared, SharedFunctionInfo::kFunctionDataOffset - kHeapObjectTag); } Node* WasmGraphBuilder::BuildLoadJumpTableOffsetFromExportedFunctionData( Node* function_data) { Node* jump_table_offset_smi = gasm_->Load( MachineType::TaggedSigned(), function_data, WasmExportedFunctionData::kJumpTableOffsetOffset - kHeapObjectTag); return BuildChangeSmiToIntPtr(jump_table_offset_smi); } Node* WasmGraphBuilder::BuildLoadFunctionIndexFromExportedFunctionData( Node* function_data) { Node* function_index_smi = gasm_->Load( MachineType::TaggedSigned(), function_data, WasmExportedFunctionData::kFunctionIndexOffset - kHeapObjectTag); Node* function_index = BuildChangeSmiToInt32(function_index_smi); return function_index; } Node* HasInstanceType(WasmGraphAssembler* gasm, Node* object, InstanceType type) { Node* map = gasm->Load(MachineType::TaggedPointer(), object, wasm::ObjectAccess::ToTagged(HeapObject::kMapOffset)); Node* instance_type = gasm->Load(MachineType::Uint16(), map, wasm::ObjectAccess::ToTagged(Map::kInstanceTypeOffset)); return gasm->Word32Equal(instance_type, gasm->Int32Constant(type)); } Node* WasmGraphBuilder::BuildCallRef(uint32_t sig_index, Vector<Node*> args, Vector<Node*> rets, CheckForNull null_check, IsReturnCall continuation, wasm::WasmCodePosition position) { if (null_check == kWithNullCheck) { TrapIfTrue(wasm::kTrapNullDereference, gasm_->WordEqual(args[0], RefNull()), position); } const wasm::FunctionSig* sig = env_->module->signature(sig_index); Node* function_data = BuildLoadFunctionDataFromExportedFunction(args[0]); Node* is_js_function = HasInstanceType(gasm_.get(), function_data, WASM_JS_FUNCTION_DATA_TYPE); auto js_label = gasm_->MakeLabel(); auto end_label = gasm_->MakeLabel(MachineRepresentation::kTaggedPointer, MachineRepresentation::kTaggedPointer); gasm_->GotoIf(is_js_function, &js_label); { // Call to a WasmExportedFunction. // Load instance object corresponding to module where callee is defined. Node* callee_instance = gasm_->Load(MachineType::TaggedPointer(), function_data, wasm::ObjectAccess::ToTagged( WasmExportedFunctionData::kInstanceOffset)); Node* function_index = gasm_->Load(MachineType::TaggedPointer(), function_data, wasm::ObjectAccess::ToTagged( WasmExportedFunctionData::kFunctionIndexOffset)); auto imported_label = gasm_->MakeLabel(); // Check if callee is a locally defined or imported function it its module. Node* imported_function_refs = gasm_->Load(MachineType::TaggedPointer(), callee_instance, wasm::ObjectAccess::ToTagged( WasmInstanceObject::kImportedFunctionRefsOffset)); Node* imported_functions_num = gasm_->Load(MachineType::TaggedPointer(), imported_function_refs, wasm::ObjectAccess::ToTagged(FixedArray::kLengthOffset)); gasm_->GotoIf(gasm_->SmiLessThan(function_index, imported_functions_num), &imported_label); { // Function locally defined in module. Node* jump_table_start = gasm_->Load(MachineType::Pointer(), callee_instance, wasm::ObjectAccess::ToTagged( WasmInstanceObject::kJumpTableStartOffset)); Node* jump_table_offset = BuildLoadJumpTableOffsetFromExportedFunctionData(function_data); Node* jump_table_slot = gasm_->IntAdd(jump_table_start, jump_table_offset); gasm_->Goto(&end_label, jump_table_slot, callee_instance /* Unused, dummy value */); } { // Function imported to module. gasm_->Bind(&imported_label); Node* imported_instance = gasm_->Load( MachineType::TaggedPointer(), imported_function_refs, gasm_->Int32Add( gasm_->Int32Mul(BuildChangeSmiToInt32(function_index), gasm_->Int32Constant(kTaggedSize)), gasm_->Int32Constant(FixedArray::kHeaderSize - kHeapObjectTag))); Node* imported_function_targets = gasm_->Load(MachineType::Pointer(), callee_instance, wasm::ObjectAccess::ToTagged( WasmInstanceObject::kImportedFunctionTargetsOffset)); Node* target_node = gasm_->Load(MachineType::Pointer(), imported_function_targets, gasm_->IntMul(BuildChangeSmiToIntPtr(function_index), gasm_->IntPtrConstant(kSystemPointerSize))); gasm_->Goto(&end_label, target_node, imported_instance); } } { // Call to a WasmJSFunction. // The call target is the wasm-to-js wrapper code. gasm_->Bind(&js_label); // TODO(9495): Implement when the interaction with the type reflection // proposal is clear. TrapIfTrue(wasm::kTrapWasmJSFunction, gasm_->Int32Constant(1), position); gasm_->Goto(&end_label, args[0], RefNull() /* Dummy value */); } gasm_->Bind(&end_label); args[0] = end_label.PhiAt(0); Node* instance_node = end_label.PhiAt(1); const UseRetpoline use_retpoline = untrusted_code_mitigations_ ? kRetpoline : kNoRetpoline; Node* call = continuation == kCallContinues ? BuildWasmCall(sig, args, rets, position, instance_node, use_retpoline) : BuildWasmReturnCall(sig, args, position, instance_node, use_retpoline); return call; } Node* WasmGraphBuilder::CallRef(uint32_t sig_index, Vector<Node*> args, Vector<Node*> rets, WasmGraphBuilder::CheckForNull null_check, wasm::WasmCodePosition position) { return BuildCallRef(sig_index, args, rets, null_check, IsReturnCall::kCallContinues, position); } Node* WasmGraphBuilder::ReturnCallRef(uint32_t sig_index, Vector<Node*> args, WasmGraphBuilder::CheckForNull null_check, wasm::WasmCodePosition position) { return BuildCallRef(sig_index, args, {}, null_check, IsReturnCall::kReturnCall, position); } Node* WasmGraphBuilder::ReturnCall(uint32_t index, Vector<Node*> args, wasm::WasmCodePosition position) { DCHECK_NULL(args[0]); const wasm::FunctionSig* sig = env_->module->functions[index].sig; if (env_ && index < env_->module->num_imported_functions) { // Return Call to an imported function. return BuildImportCall(sig, args, {}, position, index, kReturnCall); } // A direct tail call to a wasm function defined in this module. // Just encode the function index. This will be patched during code // generation. Address code = static_cast<Address>(index); args[0] = mcgraph()->RelocatableIntPtrConstant(code, RelocInfo::WASM_CALL); return BuildWasmReturnCall(sig, args, position, nullptr, kNoRetpoline); } Node* WasmGraphBuilder::ReturnCallIndirect(uint32_t table_index, uint32_t sig_index, Vector<Node*> args, wasm::WasmCodePosition position) { return BuildIndirectCall(table_index, sig_index, args, {}, position, kReturnCall); } Node* WasmGraphBuilder::BrOnNull(Node* ref_object, Node** null_node, Node** non_null_node) { BranchExpectFalse(gasm_->WordEqual(ref_object, RefNull()), null_node, non_null_node); // Return value is not used, but we need it for compatibility // with graph-builder-interface. return nullptr; } Node* WasmGraphBuilder::BuildI32Rol(Node* left, Node* right) { // Implement Rol by Ror since TurboFan does not have Rol opcode. // TODO(weiliang): support Word32Rol opcode in TurboFan. Int32Matcher m(right); if (m.HasValue()) { return Binop(wasm::kExprI32Ror, left, mcgraph()->Int32Constant(32 - (m.Value() & 0x1F))); } else { return Binop(wasm::kExprI32Ror, left, Binop(wasm::kExprI32Sub, mcgraph()->Int32Constant(32), right)); } } Node* WasmGraphBuilder::BuildI64Rol(Node* left, Node* right) { // Implement Rol by Ror since TurboFan does not have Rol opcode. // TODO(weiliang): support Word64Rol opcode in TurboFan. Int64Matcher m(right); Node* inv_right = m.HasValue() ? mcgraph()->Int64Constant(64 - (m.Value() & 0x3F)) : Binop(wasm::kExprI64Sub, mcgraph()->Int64Constant(64), right); return Binop(wasm::kExprI64Ror, left, inv_right); } Node* WasmGraphBuilder::Invert(Node* node) { return Unop(wasm::kExprI32Eqz, node); } Node* WasmGraphBuilder::BuildTruncateIntPtrToInt32(Node* value) { if (mcgraph()->machine()->Is64()) { value = graph()->NewNode(mcgraph()->machine()->TruncateInt64ToInt32(), value); } return value; } Node* WasmGraphBuilder::BuildChangeInt32ToIntPtr(Node* value) { if (mcgraph()->machine()->Is64()) { value = graph()->NewNode(mcgraph()->machine()->ChangeInt32ToInt64(), value); } return value; } Node* WasmGraphBuilder::BuildChangeInt32ToSmi(Node* value) { // With pointer compression, only the lower 32 bits are used. if (COMPRESS_POINTERS_BOOL) { return graph()->NewNode(mcgraph()->machine()->Word32Shl(), value, BuildSmiShiftBitsConstant32()); } value = BuildChangeInt32ToIntPtr(value); return graph()->NewNode(mcgraph()->machine()->WordShl(), value, BuildSmiShiftBitsConstant()); } Node* WasmGraphBuilder::BuildChangeUint31ToSmi(Node* value) { if (COMPRESS_POINTERS_BOOL) { return graph()->NewNode(mcgraph()->machine()->Word32Shl(), value, BuildSmiShiftBitsConstant32()); } return graph()->NewNode(mcgraph()->machine()->WordShl(), Uint32ToUintptr(value), BuildSmiShiftBitsConstant()); } Node* WasmGraphBuilder::BuildSmiShiftBitsConstant() { return mcgraph()->IntPtrConstant(kSmiShiftSize + kSmiTagSize); } Node* WasmGraphBuilder::BuildSmiShiftBitsConstant32() { return mcgraph()->Int32Constant(kSmiShiftSize + kSmiTagSize); } Node* WasmGraphBuilder::BuildChangeSmiToInt32(Node* value) { if (COMPRESS_POINTERS_BOOL) { value = graph()->NewNode(mcgraph()->machine()->TruncateInt64ToInt32(), value); value = graph()->NewNode(mcgraph()->machine()->Word32Sar(), value, BuildSmiShiftBitsConstant32()); } else { value = BuildChangeSmiToIntPtr(value); value = BuildTruncateIntPtrToInt32(value); } return value; } Node* WasmGraphBuilder::BuildChangeSmiToIntPtr(Node* value) { if (COMPRESS_POINTERS_BOOL) { value = BuildChangeSmiToInt32(value); return BuildChangeInt32ToIntPtr(value); } return graph()->NewNode(mcgraph()->machine()->WordSar(), value, BuildSmiShiftBitsConstant()); } Node* WasmGraphBuilder::BuildConvertUint32ToSmiWithSaturation(Node* value, uint32_t maxval) { DCHECK(Smi::IsValid(maxval)); Node* max = mcgraph()->Uint32Constant(maxval); Node* check = graph()->NewNode(mcgraph()->machine()->Uint32LessThanOrEqual(), value, max); Node* valsmi = BuildChangeUint31ToSmi(value); Node* maxsmi = graph()->NewNode(mcgraph()->common()->NumberConstant(maxval)); Diamond d(graph(), mcgraph()->common(), check, BranchHint::kTrue); d.Chain(control()); return d.Phi(MachineRepresentation::kTagged, valsmi, maxsmi); } void WasmGraphBuilder::InitInstanceCache( WasmInstanceCacheNodes* instance_cache) { DCHECK_NOT_NULL(instance_node_); // Load the memory start. instance_cache->mem_start = LOAD_INSTANCE_FIELD(MemoryStart, MachineType::UintPtr()); // Load the memory size. instance_cache->mem_size = LOAD_INSTANCE_FIELD(MemorySize, MachineType::UintPtr()); if (untrusted_code_mitigations_) { // Load the memory mask. instance_cache->mem_mask = LOAD_INSTANCE_FIELD(MemoryMask, MachineType::UintPtr()); } else { // Explicitly set to nullptr to ensure a SEGV when we try to use it. instance_cache->mem_mask = nullptr; } } void WasmGraphBuilder::PrepareInstanceCacheForLoop( WasmInstanceCacheNodes* instance_cache, Node* control) { #define INTRODUCE_PHI(field, rep) \ instance_cache->field = graph()->NewNode(mcgraph()->common()->Phi(rep, 1), \ instance_cache->field, control); INTRODUCE_PHI(mem_start, MachineType::PointerRepresentation()); INTRODUCE_PHI(mem_size, MachineType::PointerRepresentation()); if (untrusted_code_mitigations_) { INTRODUCE_PHI(mem_mask, MachineType::PointerRepresentation()); } #undef INTRODUCE_PHI } void WasmGraphBuilder::NewInstanceCacheMerge(WasmInstanceCacheNodes* to, WasmInstanceCacheNodes* from, Node* merge) { #define INTRODUCE_PHI(field, rep) \ if (to->field != from->field) { \ Node* vals[] = {to->field, from->field, merge}; \ to->field = graph()->NewNode(mcgraph()->common()->Phi(rep, 2), 3, vals); \ } INTRODUCE_PHI(mem_start, MachineType::PointerRepresentation()); INTRODUCE_PHI(mem_size, MachineRepresentation::kWord32); if (untrusted_code_mitigations_) { INTRODUCE_PHI(mem_mask, MachineRepresentation::kWord32); } #undef INTRODUCE_PHI } void WasmGraphBuilder::MergeInstanceCacheInto(WasmInstanceCacheNodes* to, WasmInstanceCacheNodes* from, Node* merge) { to->mem_size = CreateOrMergeIntoPhi(MachineType::PointerRepresentation(), merge, to->mem_size, from->mem_size); to->mem_start = CreateOrMergeIntoPhi(MachineType::PointerRepresentation(), merge, to->mem_start, from->mem_start); if (untrusted_code_mitigations_) { to->mem_mask = CreateOrMergeIntoPhi(MachineType::PointerRepresentation(), merge, to->mem_mask, from->mem_mask); } } Node* WasmGraphBuilder::CreateOrMergeIntoPhi(MachineRepresentation rep, Node* merge, Node* tnode, Node* fnode) { if (IsPhiWithMerge(tnode, merge)) { AppendToPhi(tnode, fnode); } else if (tnode != fnode) { // Note that it is not safe to use {Buffer} here since this method is used // via {CheckForException} while the {Buffer} is in use by another method. uint32_t count = merge->InputCount(); // + 1 for the merge node. base::SmallVector<Node*, 9> inputs(count + 1); for (uint32_t j = 0; j < count - 1; j++) inputs[j] = tnode; inputs[count - 1] = fnode; inputs[count] = merge; tnode = graph()->NewNode(mcgraph()->common()->Phi(rep, count), count + 1, inputs.begin()); } return tnode; } Node* WasmGraphBuilder::CreateOrMergeIntoEffectPhi(Node* merge, Node* tnode, Node* fnode) { if (IsPhiWithMerge(tnode, merge)) { AppendToPhi(tnode, fnode); } else if (tnode != fnode) { // Note that it is not safe to use {Buffer} here since this method is used // via {CheckForException} while the {Buffer} is in use by another method. uint32_t count = merge->InputCount(); // + 1 for the merge node. base::SmallVector<Node*, 9> inputs(count + 1); for (uint32_t j = 0; j < count - 1; j++) { inputs[j] = tnode; } inputs[count - 1] = fnode; inputs[count] = merge; tnode = graph()->NewNode(mcgraph()->common()->EffectPhi(count), count + 1, inputs.begin()); } return tnode; } Node* WasmGraphBuilder::effect() { return gasm_->effect(); } Node* WasmGraphBuilder::control() { return gasm_->control(); } Node* WasmGraphBuilder::SetEffect(Node* node) { SetEffectControl(node, control()); return node; } Node* WasmGraphBuilder::SetControl(Node* node) { SetEffectControl(effect(), node); return node; } void WasmGraphBuilder::SetEffectControl(Node* effect, Node* control) { gasm_->InitializeEffectControl(effect, control); } Node* WasmGraphBuilder::GetImportedMutableGlobals() { if (imported_mutable_globals_ == nullptr) { // Load imported_mutable_globals_ from the instance object at runtime. imported_mutable_globals_ = graph()->NewNode( mcgraph()->machine()->Load(MachineType::UintPtr()), instance_node_.get(), mcgraph()->Int32Constant( WASM_INSTANCE_OBJECT_OFFSET(ImportedMutableGlobals)), graph()->start(), graph()->start()); } return imported_mutable_globals_.get(); } void WasmGraphBuilder::GetGlobalBaseAndOffset(MachineType mem_type, const wasm::WasmGlobal& global, Node** base_node, Node** offset_node) { DCHECK_NOT_NULL(instance_node_); if (global.mutability && global.imported) { *base_node = SetEffect(graph()->NewNode( mcgraph()->machine()->Load(MachineType::UintPtr()), GetImportedMutableGlobals(), mcgraph()->Int32Constant(global.index * sizeof(Address)), effect(), control())); *offset_node = mcgraph()->Int32Constant(0); } else { if (globals_start_ == nullptr) { // Load globals_start from the instance object at runtime. // TODO(wasm): we currently generate only one load of the {globals_start} // start per graph, which means it can be placed anywhere by the // scheduler. This is legal because the globals_start should never change. // However, in some cases (e.g. if the instance object is already in a // register), it is slightly more efficient to reload this value from the // instance object. Since this depends on register allocation, it is not // possible to express in the graph, and would essentially constitute a // "mem2reg" optimization in TurboFan. globals_start_ = graph()->NewNode( mcgraph()->machine()->Load(MachineType::UintPtr()), instance_node_.get(), mcgraph()->Int32Constant(WASM_INSTANCE_OBJECT_OFFSET(GlobalsStart)), graph()->start(), graph()->start()); } *base_node = globals_start_.get(); *offset_node = mcgraph()->Int32Constant(global.offset); if (mem_type == MachineType::Simd128() && global.offset != 0) { // TODO(titzer,bbudge): code generation for SIMD memory offsets is broken. *base_node = graph()->NewNode(mcgraph()->machine()->IntAdd(), *base_node, *offset_node); *offset_node = mcgraph()->Int32Constant(0); } } } void WasmGraphBuilder::GetBaseAndOffsetForImportedMutableExternRefGlobal( const wasm::WasmGlobal& global, Node** base, Node** offset) { // Load the base from the ImportedMutableGlobalsBuffer of the instance. Node* buffers = LOAD_INSTANCE_FIELD(ImportedMutableGlobalsBuffers, MachineType::TaggedPointer()); *base = LOAD_FIXED_ARRAY_SLOT_ANY(buffers, global.index); // For the offset we need the index of the global in the buffer, and then // calculate the actual offset from the index. Load the index from the // ImportedMutableGlobals array of the instance. Node* index = SetEffect( graph()->NewNode(mcgraph()->machine()->Load(MachineType::UintPtr()), GetImportedMutableGlobals(), mcgraph()->Int32Constant(global.index * sizeof(Address)), effect(), control())); // From the index, calculate the actual offset in the FixeArray. This // is kHeaderSize + (index * kTaggedSize). kHeaderSize can be acquired with // wasm::ObjectAccess::ElementOffsetInTaggedFixedArray(0). Node* index_times_tagged_size = graph()->NewNode(mcgraph()->machine()->IntMul(), Uint32ToUintptr(index), mcgraph()->Int32Constant(kTaggedSize)); *offset = graph()->NewNode( mcgraph()->machine()->IntAdd(), index_times_tagged_size, mcgraph()->IntPtrConstant( wasm::ObjectAccess::ElementOffsetInTaggedFixedArray(0))); } Node* WasmGraphBuilder::MemBuffer(uintptr_t offset) { DCHECK_NOT_NULL(instance_cache_); Node* mem_start = instance_cache_->mem_start; DCHECK_NOT_NULL(mem_start); if (offset == 0) return mem_start; return gasm_->IntAdd(mem_start, gasm_->UintPtrConstant(offset)); } Node* WasmGraphBuilder::CurrentMemoryPages() { // CurrentMemoryPages can not be called from asm.js. DCHECK_EQ(wasm::kWasmOrigin, env_->module->origin); DCHECK_NOT_NULL(instance_cache_); Node* mem_size = instance_cache_->mem_size; DCHECK_NOT_NULL(mem_size); Node* result = graph()->NewNode(mcgraph()->machine()->WordShr(), mem_size, mcgraph()->Int32Constant(wasm::kWasmPageSizeLog2)); result = BuildTruncateIntPtrToInt32(result); return result; } // Only call this function for code which is not reused across instantiations, // as we do not patch the embedded js_context. Node* WasmGraphBuilder::BuildCallToRuntimeWithContext(Runtime::FunctionId f, Node* js_context, Node** parameters, int parameter_count) { const Runtime::Function* fun = Runtime::FunctionForId(f); auto call_descriptor = Linkage::GetRuntimeCallDescriptor( mcgraph()->zone(), f, fun->nargs, Operator::kNoProperties, CallDescriptor::kNoFlags); // The CEntryStub is loaded from the IsolateRoot so that generated code is // Isolate independent. At the moment this is only done for CEntryStub(1). Node* isolate_root = BuildLoadIsolateRoot(); DCHECK_EQ(1, fun->result_size); auto centry_id = Builtins::kCEntry_Return1_DontSaveFPRegs_ArgvOnStack_NoBuiltinExit; Node* centry_stub = LOAD_FULL_POINTER( isolate_root, IsolateData::builtin_slot_offset(centry_id)); // TODO(titzer): allow arbitrary number of runtime arguments // At the moment we only allow 5 parameters. If more parameters are needed, // increase this constant accordingly. static const int kMaxParams = 5; DCHECK_GE(kMaxParams, parameter_count); Node* inputs[kMaxParams + 6]; int count = 0; inputs[count++] = centry_stub; for (int i = 0; i < parameter_count; i++) { inputs[count++] = parameters[i]; } inputs[count++] = mcgraph()->ExternalConstant(ExternalReference::Create(f)); // ref inputs[count++] = mcgraph()->Int32Constant(fun->nargs); // arity inputs[count++] = js_context; // js_context inputs[count++] = effect(); inputs[count++] = control(); Node* call = mcgraph()->graph()->NewNode( mcgraph()->common()->Call(call_descriptor), count, inputs); SetEffect(call); return call; } Node* WasmGraphBuilder::BuildCallToRuntime(Runtime::FunctionId f, Node** parameters, int parameter_count) { return BuildCallToRuntimeWithContext(f, NoContextConstant(), parameters, parameter_count); } Node* WasmGraphBuilder::GlobalGet(uint32_t index) { const wasm::WasmGlobal& global = env_->module->globals[index]; if (global.type.is_reference_type()) { if (global.mutability && global.imported) { Node* base = nullptr; Node* offset = nullptr; GetBaseAndOffsetForImportedMutableExternRefGlobal(global, &base, &offset); return gasm_->Load(MachineType::AnyTagged(), base, offset); } Node* globals_buffer = LOAD_INSTANCE_FIELD(TaggedGlobalsBuffer, MachineType::TaggedPointer()); return LOAD_FIXED_ARRAY_SLOT_ANY(globals_buffer, global.offset); } MachineType mem_type = global.type.machine_type(); if (mem_type.representation() == MachineRepresentation::kSimd128) { has_simd_ = true; } Node* base = nullptr; Node* offset = nullptr; GetGlobalBaseAndOffset(mem_type, global, &base, &offset); Node* result = SetEffect(graph()->NewNode( mcgraph()->machine()->Load(mem_type), base, offset, effect(), control())); #if defined(V8_TARGET_BIG_ENDIAN) result = BuildChangeEndiannessLoad(result, mem_type, global.type); #endif return result; } Node* WasmGraphBuilder::GlobalSet(uint32_t index, Node* val) { const wasm::WasmGlobal& global = env_->module->globals[index]; if (global.type.is_reference_type()) { if (global.mutability && global.imported) { Node* base = nullptr; Node* offset = nullptr; GetBaseAndOffsetForImportedMutableExternRefGlobal(global, &base, &offset); return STORE_RAW_NODE_OFFSET( base, offset, val, MachineRepresentation::kTagged, kFullWriteBarrier); } Node* globals_buffer = LOAD_INSTANCE_FIELD(TaggedGlobalsBuffer, MachineType::TaggedPointer()); return STORE_FIXED_ARRAY_SLOT_ANY(globals_buffer, global.offset, val); } MachineType mem_type = global.type.machine_type(); if (mem_type.representation() == MachineRepresentation::kSimd128) { has_simd_ = true; } Node* base = nullptr; Node* offset = nullptr; GetGlobalBaseAndOffset(mem_type, global, &base, &offset); const Operator* op = mcgraph()->machine()->Store( StoreRepresentation(mem_type.representation(), kNoWriteBarrier)); #if defined(V8_TARGET_BIG_ENDIAN) val = BuildChangeEndiannessStore(val, mem_type.representation(), global.type); #endif return SetEffect( graph()->NewNode(op, base, offset, val, effect(), control())); } Node* WasmGraphBuilder::TableGet(uint32_t table_index, Node* index, wasm::WasmCodePosition position) { auto call_descriptor = GetBuiltinCallDescriptor<WasmTableGetDescriptor>( this, StubCallMode::kCallWasmRuntimeStub); // A direct call to a wasm runtime stub defined in this module. // Just encode the stub index. This will be patched at relocation. Node* call_target = mcgraph()->RelocatableIntPtrConstant( wasm::WasmCode::kWasmTableGet, RelocInfo::WASM_STUB_CALL); return SetEffectControl(graph()->NewNode( mcgraph()->common()->Call(call_descriptor), call_target, mcgraph()->IntPtrConstant(table_index), index, effect(), control())); } Node* WasmGraphBuilder::TableSet(uint32_t table_index, Node* index, Node* val, wasm::WasmCodePosition position) { auto call_descriptor = GetBuiltinCallDescriptor<WasmTableSetDescriptor>( this, StubCallMode::kCallWasmRuntimeStub); // A direct call to a wasm runtime stub defined in this module. // Just encode the stub index. This will be patched at relocation. Node* call_target = mcgraph()->RelocatableIntPtrConstant( wasm::WasmCode::kWasmTableSet, RelocInfo::WASM_STUB_CALL); return gasm_->Call(call_descriptor, call_target, gasm_->IntPtrConstant(table_index), index, val); } Node* WasmGraphBuilder::CheckBoundsAndAlignment( int8_t access_size, Node* index, uint64_t offset, wasm::WasmCodePosition position) { // Atomic operations need bounds checks until the backend can emit protected // loads. index = BoundsCheckMem(access_size, index, offset, position, kNeedsBoundsCheck); const uintptr_t align_mask = access_size - 1; // {offset} is validated to be within uintptr_t range in {BoundsCheckMem}. uintptr_t capped_offset = static_cast<uintptr_t>(offset); // Don't emit an alignment check if the index is a constant. // TODO(wasm): a constant match is also done above in {BoundsCheckMem}. UintPtrMatcher match(index); if (match.HasValue()) { uintptr_t effective_offset = match.Value() + capped_offset; if ((effective_offset & align_mask) != 0) { // statically known to be unaligned; trap. TrapIfEq32(wasm::kTrapUnalignedAccess, Int32Constant(0), 0, position); } return index; } // Unlike regular memory accesses, atomic memory accesses should trap if // the effective offset is misaligned. // TODO(wasm): this addition is redundant with one inserted by {MemBuffer}. Node* effective_offset = gasm_->IntAdd(MemBuffer(capped_offset), index); Node* cond = gasm_->WordAnd(effective_offset, gasm_->IntPtrConstant(align_mask)); TrapIfFalse(wasm::kTrapUnalignedAccess, gasm_->Word32Equal(cond, gasm_->Int32Constant(0)), position); return index; } // Insert code to bounds check a memory access if necessary. Return the // bounds-checked index, which is guaranteed to have (the equivalent of) // {uintptr_t} representation. Node* WasmGraphBuilder::BoundsCheckMem(uint8_t access_size, Node* index, uint64_t offset, wasm::WasmCodePosition position, EnforceBoundsCheck enforce_check) { DCHECK_LE(1, access_size); index = Uint32ToUintptr(index); if (!FLAG_wasm_bounds_checks) return index; if (use_trap_handler() && enforce_check == kCanOmitBoundsCheck) { return index; } // If the offset does not fit in a uintptr_t, this can never succeed on this // machine. if (offset > std::numeric_limits<uintptr_t>::max() || !base::IsInBounds<uintptr_t>(offset, access_size, env_->max_memory_size)) { // The access will be out of bounds, even for the largest memory. TrapIfEq32(wasm::kTrapMemOutOfBounds, Int32Constant(0), 0, position); return gasm_->UintPtrConstant(0); } uintptr_t end_offset = offset + access_size - 1u; Node* end_offset_node = mcgraph_->UintPtrConstant(end_offset); // The accessed memory is [index + offset, index + end_offset]. // Check that the last read byte (at {index + end_offset}) is in bounds. // 1) Check that {end_offset < mem_size}. This also ensures that we can safely // compute {effective_size} as {mem_size - end_offset)}. // {effective_size} is >= 1 if condition 1) holds. // 2) Check that {index + end_offset < mem_size} by // - computing {effective_size} as {mem_size - end_offset} and // - checking that {index < effective_size}. Node* mem_size = instance_cache_->mem_size; if (end_offset >= env_->min_memory_size) { // The end offset is larger than the smallest memory. // Dynamically check the end offset against the dynamic memory size. Node* cond = gasm_->UintLessThan(end_offset_node, mem_size); TrapIfFalse(wasm::kTrapMemOutOfBounds, cond, position); } else { // The end offset is smaller than the smallest memory, so only one check is // required. Check to see if the index is also a constant. UintPtrMatcher match(index); if (match.HasValue()) { uintptr_t index_val = match.Value(); if (index_val < env_->min_memory_size - end_offset) { // The input index is a constant and everything is statically within // bounds of the smallest possible memory. return index; } } } // This produces a positive number, since {end_offset < min_size <= mem_size}. Node* effective_size = gasm_->IntSub(mem_size, end_offset_node); // Introduce the actual bounds check. Node* cond = gasm_->UintLessThan(index, effective_size); TrapIfFalse(wasm::kTrapMemOutOfBounds, cond, position); if (untrusted_code_mitigations_) { // In the fallthrough case, condition the index with the memory mask. Node* mem_mask = instance_cache_->mem_mask; DCHECK_NOT_NULL(mem_mask); index = gasm_->WordAnd(index, mem_mask); } return index; } Node* WasmGraphBuilder::BoundsCheckRange(Node* start, Node** size, Node* max, wasm::WasmCodePosition position) { auto m = mcgraph()->machine(); // The region we are trying to access is [start, start+size). If // {start} > {max}, none of this region is valid, so we trap. Otherwise, // there may be a subset of the region that is valid. {max - start} is the // maximum valid size, so if {max - start < size}, then the region is // partially out-of-bounds. TrapIfTrue(wasm::kTrapMemOutOfBounds, graph()->NewNode(m->Uint32LessThan(), max, start), position); Node* sub = graph()->NewNode(m->Int32Sub(), max, start); Node* fail = graph()->NewNode(m->Uint32LessThan(), sub, *size); Diamond d(graph(), mcgraph()->common(), fail, BranchHint::kFalse); d.Chain(control()); *size = d.Phi(MachineRepresentation::kWord32, sub, *size); return fail; } Node* WasmGraphBuilder::BoundsCheckMemRange(Node** start, Node** size, wasm::WasmCodePosition position) { // TODO(binji): Support trap handler and no bounds check mode. Node* fail = BoundsCheckRange(*start, size, instance_cache_->mem_size, position); *start = graph()->NewNode(mcgraph()->machine()->IntAdd(), MemBuffer(0), Uint32ToUintptr(*start)); return fail; } const Operator* WasmGraphBuilder::GetSafeLoadOperator(int offset, wasm::ValueType type) { int alignment = offset % type.element_size_bytes(); MachineType mach_type = type.machine_type(); if (COMPRESS_POINTERS_BOOL && mach_type.IsTagged()) { // We are loading tagged value from off-heap location, so we need to load // it as a full word otherwise we will not be able to decompress it. mach_type = MachineType::Pointer(); } if (alignment == 0 || mcgraph()->machine()->UnalignedLoadSupported( type.machine_representation())) { return mcgraph()->machine()->Load(mach_type); } return mcgraph()->machine()->UnalignedLoad(mach_type); } const Operator* WasmGraphBuilder::GetSafeStoreOperator(int offset, wasm::ValueType type) { int alignment = offset % type.element_size_bytes(); MachineRepresentation rep = type.machine_representation(); if (COMPRESS_POINTERS_BOOL && IsAnyTagged(rep)) { // We are storing tagged value to off-heap location, so we need to store // it as a full word otherwise we will not be able to decompress it. rep = MachineType::PointerRepresentation(); } if (alignment == 0 || mcgraph()->machine()->UnalignedStoreSupported(rep)) { StoreRepresentation store_rep(rep, WriteBarrierKind::kNoWriteBarrier); return mcgraph()->machine()->Store(store_rep); } UnalignedStoreRepresentation store_rep(rep); return mcgraph()->machine()->UnalignedStore(store_rep); } Node* WasmGraphBuilder::TraceFunctionEntry(wasm::WasmCodePosition position) { Node* call = BuildCallToRuntime(Runtime::kWasmTraceEnter, nullptr, 0); SetSourcePosition(call, position); return call; } Node* WasmGraphBuilder::TraceFunctionExit(Vector<Node*> vals, wasm::WasmCodePosition position) { Node* info = gasm_->IntPtrConstant(0); size_t num_returns = vals.size(); if (num_returns == 1) { wasm::ValueType return_type = sig_->GetReturn(0); MachineRepresentation rep = return_type.machine_representation(); int size = ElementSizeInBytes(rep); info = gasm_->StackSlot(size, size); gasm_->Store(StoreRepresentation(rep, kNoWriteBarrier), info, gasm_->Int32Constant(0), vals[0]); } Node* call = BuildCallToRuntime(Runtime::kWasmTraceExit, &info, 1); SetSourcePosition(call, position); return call; } Node* WasmGraphBuilder::TraceMemoryOperation(bool is_store, MachineRepresentation rep, Node* index, uintptr_t offset, wasm::WasmCodePosition position) { int kAlign = 4; // Ensure that the LSB is 0, such that this looks like a Smi. TNode<RawPtrT> info = gasm_->StackSlot(sizeof(wasm::MemoryTracingInfo), kAlign); Node* address = gasm_->IntAdd(gasm_->UintPtrConstant(offset), index); auto store = [&](int field_offset, MachineRepresentation rep, Node* data) { gasm_->Store(StoreRepresentation(rep, kNoWriteBarrier), info, gasm_->Int32Constant(field_offset), data); }; // Store address, is_store, and mem_rep. store(offsetof(wasm::MemoryTracingInfo, address), MachineRepresentation::kWord32, address); store(offsetof(wasm::MemoryTracingInfo, is_store), MachineRepresentation::kWord8, mcgraph()->Int32Constant(is_store ? 1 : 0)); store(offsetof(wasm::MemoryTracingInfo, mem_rep), MachineRepresentation::kWord8, mcgraph()->Int32Constant(static_cast<int>(rep))); Node* args[] = {info}; Node* call = BuildCallToRuntime(Runtime::kWasmTraceMemory, args, arraysize(args)); SetSourcePosition(call, position); return call; } namespace { LoadTransformation GetLoadTransformation( MachineType memtype, wasm::LoadTransformationKind transform) { switch (transform) { case wasm::LoadTransformationKind::kSplat: { if (memtype == MachineType::Int8()) { return LoadTransformation::kS128Load8Splat; } else if (memtype == MachineType::Int16()) { return LoadTransformation::kS128Load16Splat; } else if (memtype == MachineType::Int32()) { return LoadTransformation::kS128Load32Splat; } else if (memtype == MachineType::Int64()) { return LoadTransformation::kS128Load64Splat; } break; } case wasm::LoadTransformationKind::kExtend: { if (memtype == MachineType::Int8()) { return LoadTransformation::kS128Load8x8S; } else if (memtype == MachineType::Uint8()) { return LoadTransformation::kS128Load8x8U; } else if (memtype == MachineType::Int16()) { return LoadTransformation::kS128Load16x4S; } else if (memtype == MachineType::Uint16()) { return LoadTransformation::kS128Load16x4U; } else if (memtype == MachineType::Int32()) { return LoadTransformation::kS128Load32x2S; } else if (memtype == MachineType::Uint32()) { return LoadTransformation::kS128Load32x2U; } break; } case wasm::LoadTransformationKind::kZeroExtend: { if (memtype == MachineType::Int32()) { return LoadTransformation::kS128LoadMem32Zero; } else if (memtype == MachineType::Int64()) { return LoadTransformation::kS128LoadMem64Zero; } } } UNREACHABLE(); } LoadKind GetLoadKind(MachineGraph* mcgraph, MachineType memtype, bool use_trap_handler) { if (memtype.representation() == MachineRepresentation::kWord8 || mcgraph->machine()->UnalignedLoadSupported(memtype.representation())) { if (use_trap_handler) { return LoadKind::kProtected; } return LoadKind::kNormal; } // TODO(eholk): Support unaligned loads with trap handlers. DCHECK(!use_trap_handler); return LoadKind::kUnaligned; } } // namespace // S390 simulator does not execute BE code, hence needs to also check if we are // running on a LE simulator. // TODO(miladfar): Remove SIM once V8_TARGET_BIG_ENDIAN includes the Sim. #if defined(V8_TARGET_BIG_ENDIAN) || defined(V8_TARGET_ARCH_S390_LE_SIM) Node* WasmGraphBuilder::LoadTransformBigEndian( wasm::ValueType type, MachineType memtype, wasm::LoadTransformationKind transform, Node* index, uint64_t offset, uint32_t alignment, wasm::WasmCodePosition position) { #define LOAD_EXTEND(num_lanes, bytes_per_load, replace_lane) \ result = graph()->NewNode(mcgraph()->machine()->S128Zero()); \ Node* values[num_lanes]; \ for (int i = 0; i < num_lanes; i++) { \ values[i] = LoadMem(type, memtype, index, offset + i * bytes_per_load, \ alignment, position); \ if (memtype.IsSigned()) { \ /* sign extend */ \ values[i] = graph()->NewNode(mcgraph()->machine()->ChangeInt32ToInt64(), \ values[i]); \ } else { \ /* zero extend */ \ values[i] = graph()->NewNode( \ mcgraph()->machine()->ChangeUint32ToUint64(), values[i]); \ } \ } \ for (int lane = 0; lane < num_lanes; lane++) { \ result = graph()->NewNode(mcgraph()->machine()->replace_lane(lane), \ result, values[lane]); \ } Node* result; LoadTransformation transformation = GetLoadTransformation(memtype, transform); switch (transformation) { case LoadTransformation::kS128Load8Splat: { result = LoadMem(type, memtype, index, offset, alignment, position); result = graph()->NewNode(mcgraph()->machine()->I8x16Splat(), result); break; } case LoadTransformation::kS128Load8x8S: case LoadTransformation::kS128Load8x8U: { LOAD_EXTEND(8, 1, I16x8ReplaceLane) break; } case LoadTransformation::kS128Load16Splat: { result = LoadMem(type, memtype, index, offset, alignment, position); result = graph()->NewNode(mcgraph()->machine()->I16x8Splat(), result); break; } case LoadTransformation::kS128Load16x4S: case LoadTransformation::kS128Load16x4U: { LOAD_EXTEND(4, 2, I32x4ReplaceLane) break; } case LoadTransformation::kS128Load32Splat: { result = LoadMem(type, memtype, index, offset, alignment, position); result = graph()->NewNode(mcgraph()->machine()->I32x4Splat(), result); break; } case LoadTransformation::kS128Load32x2S: case LoadTransformation::kS128Load32x2U: { LOAD_EXTEND(2, 4, I64x2ReplaceLane) break; } case LoadTransformation::kS128Load64Splat: { result = LoadMem(type, memtype, index, offset, alignment, position); result = graph()->NewNode(mcgraph()->machine()->I64x2Splat(), result); break; } default: UNREACHABLE(); } return result; #undef LOAD_EXTEND } #endif Node* WasmGraphBuilder::LoadTransform(wasm::ValueType type, MachineType memtype, wasm::LoadTransformationKind transform, Node* index, uint64_t offset, uint32_t alignment, wasm::WasmCodePosition position) { if (memtype.representation() == MachineRepresentation::kSimd128) { has_simd_ = true; } Node* load; // {offset} is validated to be within uintptr_t range in {BoundsCheckMem}. uintptr_t capped_offset = static_cast<uintptr_t>(offset); #if defined(V8_TARGET_BIG_ENDIAN) || defined(V8_TARGET_ARCH_S390_LE_SIM) // LoadTransform cannot efficiently be executed on BE machines as a // single operation since loaded bytes need to be reversed first, // therefore we divide them into separate "load" and "operation" nodes. load = LoadTransformBigEndian(type, memtype, transform, index, offset, alignment, position); USE(GetLoadKind); #else // Wasm semantics throw on OOB. Introduce explicit bounds check and // conditioning when not using the trap handler. // Load extends always load 8 bytes. uint8_t access_size = transform == wasm::LoadTransformationKind::kExtend ? 8 : memtype.MemSize(); index = BoundsCheckMem(access_size, index, offset, position, kCanOmitBoundsCheck); LoadTransformation transformation = GetLoadTransformation(memtype, transform); LoadKind load_kind = GetLoadKind(mcgraph(), memtype, use_trap_handler()); load = SetEffect(graph()->NewNode( mcgraph()->machine()->LoadTransform(load_kind, transformation), MemBuffer(capped_offset), index, effect(), control())); if (load_kind == LoadKind::kProtected) { SetSourcePosition(load, position); } #endif if (FLAG_trace_wasm_memory) { TraceMemoryOperation(false, memtype.representation(), index, capped_offset, position); } return load; } Node* WasmGraphBuilder::LoadMem(wasm::ValueType type, MachineType memtype, Node* index, uint64_t offset, uint32_t alignment, wasm::WasmCodePosition position) { Node* load; if (memtype.representation() == MachineRepresentation::kSimd128) { has_simd_ = true; } // Wasm semantics throw on OOB. Introduce explicit bounds check and // conditioning when not using the trap handler. index = BoundsCheckMem(memtype.MemSize(), index, offset, position, kCanOmitBoundsCheck); // {offset} is validated to be within uintptr_t range in {BoundsCheckMem}. uintptr_t capped_offset = static_cast<uintptr_t>(offset); if (memtype.representation() == MachineRepresentation::kWord8 || mcgraph()->machine()->UnalignedLoadSupported(memtype.representation())) { if (use_trap_handler()) { load = gasm_->ProtectedLoad(memtype, MemBuffer(capped_offset), index); SetSourcePosition(load, position); } else { load = gasm_->Load(memtype, MemBuffer(capped_offset), index); } } else { // TODO(eholk): Support unaligned loads with trap handlers. DCHECK(!use_trap_handler()); load = gasm_->LoadUnaligned(memtype, MemBuffer(capped_offset), index); } #if defined(V8_TARGET_BIG_ENDIAN) load = BuildChangeEndiannessLoad(load, memtype, type); #endif if (type == wasm::kWasmI64 && ElementSizeInBytes(memtype.representation()) < 8) { // TODO(titzer): TF zeroes the upper bits of 64-bit loads for subword sizes. load = memtype.IsSigned() ? gasm_->ChangeInt32ToInt64(load) // sign extend : gasm_->ChangeUint32ToUint64(load); // zero extend } if (FLAG_trace_wasm_memory) { TraceMemoryOperation(false, memtype.representation(), index, capped_offset, position); } return load; } Node* WasmGraphBuilder::StoreMem(MachineRepresentation mem_rep, Node* index, uint64_t offset, uint32_t alignment, Node* val, wasm::WasmCodePosition position, wasm::ValueType type) { Node* store; if (mem_rep == MachineRepresentation::kSimd128) { has_simd_ = true; } index = BoundsCheckMem(i::ElementSizeInBytes(mem_rep), index, offset, position, kCanOmitBoundsCheck); #if defined(V8_TARGET_BIG_ENDIAN) val = BuildChangeEndiannessStore(val, mem_rep, type); #endif // {offset} is validated to be within uintptr_t range in {BoundsCheckMem}. uintptr_t capped_offset = static_cast<uintptr_t>(offset); if (mem_rep == MachineRepresentation::kWord8 || mcgraph()->machine()->UnalignedStoreSupported(mem_rep)) { if (use_trap_handler()) { store = gasm_->ProtectedStore(mem_rep, MemBuffer(capped_offset), index, val); SetSourcePosition(store, position); } else { store = gasm_->Store(StoreRepresentation{mem_rep, kNoWriteBarrier}, MemBuffer(capped_offset), index, val); } } else { // TODO(eholk): Support unaligned stores with trap handlers. DCHECK(!use_trap_handler()); UnalignedStoreRepresentation rep(mem_rep); store = gasm_->StoreUnaligned(rep, MemBuffer(capped_offset), index, val); } if (FLAG_trace_wasm_memory) { TraceMemoryOperation(true, mem_rep, index, capped_offset, position); } return store; } namespace { Node* GetAsmJsOOBValue(MachineRepresentation rep, MachineGraph* mcgraph) { switch (rep) { case MachineRepresentation::kWord8: case MachineRepresentation::kWord16: case MachineRepresentation::kWord32: return mcgraph->Int32Constant(0); case MachineRepresentation::kWord64: return mcgraph->Int64Constant(0); case MachineRepresentation::kFloat32: return mcgraph->Float32Constant(std::numeric_limits<float>::quiet_NaN()); case MachineRepresentation::kFloat64: return mcgraph->Float64Constant(std::numeric_limits<double>::quiet_NaN()); default: UNREACHABLE(); } } } // namespace Node* WasmGraphBuilder::BuildAsmjsLoadMem(MachineType type, Node* index) { DCHECK_NOT_NULL(instance_cache_); Node* mem_start = instance_cache_->mem_start; Node* mem_size = instance_cache_->mem_size; DCHECK_NOT_NULL(mem_start); DCHECK_NOT_NULL(mem_size); // Asm.js semantics are defined in terms of typed arrays, hence OOB // reads return {undefined} coerced to the result type (0 for integers, NaN // for float and double). // Note that we check against the memory size ignoring the size of the // stored value, which is conservative if misaligned. Technically, asm.js // should never have misaligned accesses. index = Uint32ToUintptr(index); Diamond bounds_check( graph(), mcgraph()->common(), graph()->NewNode(mcgraph()->machine()->UintLessThan(), index, mem_size), BranchHint::kTrue); bounds_check.Chain(control()); if (untrusted_code_mitigations_) { // Condition the index with the memory mask. Node* mem_mask = instance_cache_->mem_mask; DCHECK_NOT_NULL(mem_mask); index = graph()->NewNode(mcgraph()->machine()->WordAnd(), index, mem_mask); } Node* load = graph()->NewNode(mcgraph()->machine()->Load(type), mem_start, index, effect(), bounds_check.if_true); SetEffectControl(bounds_check.EffectPhi(load, effect()), bounds_check.merge); return bounds_check.Phi(type.representation(), load, GetAsmJsOOBValue(type.representation(), mcgraph())); } Node* WasmGraphBuilder::Uint32ToUintptr(Node* node) { if (mcgraph()->machine()->Is32()) return node; // Fold instances of ChangeUint32ToUint64(IntConstant) directly. Uint32Matcher matcher(node); if (matcher.HasValue()) { uintptr_t value = matcher.Value(); return mcgraph()->IntPtrConstant(bit_cast<intptr_t>(value)); } return graph()->NewNode(mcgraph()->machine()->ChangeUint32ToUint64(), node); } Node* WasmGraphBuilder::BuildAsmjsStoreMem(MachineType type, Node* index, Node* val) { DCHECK_NOT_NULL(instance_cache_); Node* mem_start = instance_cache_->mem_start; Node* mem_size = instance_cache_->mem_size; DCHECK_NOT_NULL(mem_start); DCHECK_NOT_NULL(mem_size); // Asm.js semantics are to ignore OOB writes. // Note that we check against the memory size ignoring the size of the // stored value, which is conservative if misaligned. Technically, asm.js // should never have misaligned accesses. Diamond bounds_check( graph(), mcgraph()->common(), graph()->NewNode(mcgraph()->machine()->Uint32LessThan(), index, mem_size), BranchHint::kTrue); bounds_check.Chain(control()); if (untrusted_code_mitigations_) { // Condition the index with the memory mask. Node* mem_mask = instance_cache_->mem_mask; DCHECK_NOT_NULL(mem_mask); index = graph()->NewNode(mcgraph()->machine()->Word32And(), index, mem_mask); } index = Uint32ToUintptr(index); const Operator* store_op = mcgraph()->machine()->Store(StoreRepresentation( type.representation(), WriteBarrierKind::kNoWriteBarrier)); Node* store = graph()->NewNode(store_op, mem_start, index, val, effect(), bounds_check.if_true); SetEffectControl(bounds_check.EffectPhi(store, effect()), bounds_check.merge); return val; } Node* WasmGraphBuilder::BuildF64x2Ceil(Node* input) { MachineType type = MachineType::Simd128(); ExternalReference ref = ExternalReference::wasm_f64x2_ceil(); return BuildCFuncInstruction(ref, type, input); } Node* WasmGraphBuilder::BuildF64x2Floor(Node* input) { MachineType type = MachineType::Simd128(); ExternalReference ref = ExternalReference::wasm_f64x2_floor(); return BuildCFuncInstruction(ref, type, input); } Node* WasmGraphBuilder::BuildF64x2Trunc(Node* input) { MachineType type = MachineType::Simd128(); ExternalReference ref = ExternalReference::wasm_f64x2_trunc(); return BuildCFuncInstruction(ref, type, input); } Node* WasmGraphBuilder::BuildF64x2NearestInt(Node* input) { MachineType type = MachineType::Simd128(); ExternalReference ref = ExternalReference::wasm_f64x2_nearest_int(); return BuildCFuncInstruction(ref, type, input); } Node* WasmGraphBuilder::BuildF32x4Ceil(Node* input) { MachineType type = MachineType::Simd128(); ExternalReference ref = ExternalReference::wasm_f32x4_ceil(); return BuildCFuncInstruction(ref, type, input); } Node* WasmGraphBuilder::BuildF32x4Floor(Node* input) { MachineType type = MachineType::Simd128(); ExternalReference ref = ExternalReference::wasm_f32x4_floor(); return BuildCFuncInstruction(ref, type, input); } Node* WasmGraphBuilder::BuildF32x4Trunc(Node* input) { MachineType type = MachineType::Simd128(); ExternalReference ref = ExternalReference::wasm_f32x4_trunc(); return BuildCFuncInstruction(ref, type, input); } Node* WasmGraphBuilder::BuildF32x4NearestInt(Node* input) { MachineType type = MachineType::Simd128(); ExternalReference ref = ExternalReference::wasm_f32x4_nearest_int(); return BuildCFuncInstruction(ref, type, input); } void WasmGraphBuilder::PrintDebugName(Node* node) { PrintF("#%d:%s", node->id(), node->op()->mnemonic()); } Graph* WasmGraphBuilder::graph() { return mcgraph()->graph(); } namespace { Signature<MachineRepresentation>* CreateMachineSignature( Zone* zone, const wasm::FunctionSig* sig, WasmGraphBuilder::CallOrigin origin) { Signature<MachineRepresentation>::Builder builder(zone, sig->return_count(), sig->parameter_count()); for (auto ret : sig->returns()) { if (origin == WasmGraphBuilder::kCalledFromJS) { builder.AddReturn(MachineRepresentation::kTagged); } else { builder.AddReturn(ret.machine_representation()); } } for (auto param : sig->parameters()) { if (origin == WasmGraphBuilder::kCalledFromJS) { // Parameters coming from JavaScript are always tagged values. Especially // when the signature says that it's an I64 value, then a BigInt object is // provided by JavaScript, and not two 32-bit parameters. builder.AddParam(MachineRepresentation::kTagged); } else { builder.AddParam(param.machine_representation()); } } return builder.Build(); } } // namespace void WasmGraphBuilder::AddInt64LoweringReplacement( CallDescriptor* original, CallDescriptor* replacement) { if (!lowering_special_case_) { lowering_special_case_ = std::make_unique<Int64LoweringSpecialCase>(); } lowering_special_case_->replacements.insert({original, replacement}); } CallDescriptor* WasmGraphBuilder::GetI32AtomicWaitCallDescriptor() { if (i32_atomic_wait_descriptor_) return i32_atomic_wait_descriptor_; i32_atomic_wait_descriptor_ = GetBuiltinCallDescriptor<WasmI32AtomicWait64Descriptor>( this, StubCallMode::kCallWasmRuntimeStub); AddInt64LoweringReplacement( i32_atomic_wait_descriptor_, GetBuiltinCallDescriptor<WasmI32AtomicWait32Descriptor>( this, StubCallMode::kCallWasmRuntimeStub)); return i32_atomic_wait_descriptor_; } CallDescriptor* WasmGraphBuilder::GetI64AtomicWaitCallDescriptor() { if (i64_atomic_wait_descriptor_) return i64_atomic_wait_descriptor_; i64_atomic_wait_descriptor_ = GetBuiltinCallDescriptor<WasmI64AtomicWait64Descriptor>( this, StubCallMode::kCallWasmRuntimeStub); AddInt64LoweringReplacement( i64_atomic_wait_descriptor_, GetBuiltinCallDescriptor<WasmI64AtomicWait32Descriptor>( this, StubCallMode::kCallWasmRuntimeStub)); return i64_atomic_wait_descriptor_; } void WasmGraphBuilder::LowerInt64(Signature<MachineRepresentation>* sig) { if (mcgraph()->machine()->Is64()) return; Int64Lowering r(mcgraph()->graph(), mcgraph()->machine(), mcgraph()->common(), mcgraph()->zone(), sig, std::move(lowering_special_case_)); r.LowerGraph(); } void WasmGraphBuilder::LowerInt64(CallOrigin origin) { LowerInt64(CreateMachineSignature(mcgraph()->zone(), sig_, origin)); } void WasmGraphBuilder::SimdScalarLoweringForTesting() { SimdScalarLowering(mcgraph(), CreateMachineSignature(mcgraph()->zone(), sig_, kCalledFromWasm)) .LowerGraph(); } void WasmGraphBuilder::SetSourcePosition(Node* node, wasm::WasmCodePosition position) { DCHECK_NE(position, wasm::kNoCodePosition); if (source_position_table_) { source_position_table_->SetSourcePosition(node, SourcePosition(position)); } } Node* WasmGraphBuilder::S128Zero() { has_simd_ = true; return graph()->NewNode(mcgraph()->machine()->S128Zero()); } Node* WasmGraphBuilder::SimdOp(wasm::WasmOpcode opcode, Node* const* inputs) { has_simd_ = true; switch (opcode) { case wasm::kExprF64x2Splat: return graph()->NewNode(mcgraph()->machine()->F64x2Splat(), inputs[0]); case wasm::kExprF64x2Abs: return graph()->NewNode(mcgraph()->machine()->F64x2Abs(), inputs[0]); case wasm::kExprF64x2Neg: return graph()->NewNode(mcgraph()->machine()->F64x2Neg(), inputs[0]); case wasm::kExprF64x2Sqrt: return graph()->NewNode(mcgraph()->machine()->F64x2Sqrt(), inputs[0]); case wasm::kExprF64x2Add: return graph()->NewNode(mcgraph()->machine()->F64x2Add(), inputs[0], inputs[1]); case wasm::kExprF64x2Sub: return graph()->NewNode(mcgraph()->machine()->F64x2Sub(), inputs[0], inputs[1]); case wasm::kExprF64x2Mul: return graph()->NewNode(mcgraph()->machine()->F64x2Mul(), inputs[0], inputs[1]); case wasm::kExprF64x2Div: return graph()->NewNode(mcgraph()->machine()->F64x2Div(), inputs[0], inputs[1]); case wasm::kExprF64x2Min: return graph()->NewNode(mcgraph()->machine()->F64x2Min(), inputs[0], inputs[1]); case wasm::kExprF64x2Max: return graph()->NewNode(mcgraph()->machine()->F64x2Max(), inputs[0], inputs[1]); case wasm::kExprF64x2Eq: return graph()->NewNode(mcgraph()->machine()->F64x2Eq(), inputs[0], inputs[1]); case wasm::kExprF64x2Ne: return graph()->NewNode(mcgraph()->machine()->F64x2Ne(), inputs[0], inputs[1]); case wasm::kExprF64x2Lt: return graph()->NewNode(mcgraph()->machine()->F64x2Lt(), inputs[0], inputs[1]); case wasm::kExprF64x2Le: return graph()->NewNode(mcgraph()->machine()->F64x2Le(), inputs[0], inputs[1]); case wasm::kExprF64x2Gt: return graph()->NewNode(mcgraph()->machine()->F64x2Lt(), inputs[1], inputs[0]); case wasm::kExprF64x2Ge: return graph()->NewNode(mcgraph()->machine()->F64x2Le(), inputs[1], inputs[0]); case wasm::kExprF64x2Qfma: return graph()->NewNode(mcgraph()->machine()->F64x2Qfma(), inputs[0], inputs[1], inputs[2]); case wasm::kExprF64x2Qfms: return graph()->NewNode(mcgraph()->machine()->F64x2Qfms(), inputs[0], inputs[1], inputs[2]); case wasm::kExprF64x2Pmin: return graph()->NewNode(mcgraph()->machine()->F64x2Pmin(), inputs[0], inputs[1]); case wasm::kExprF64x2Pmax: return graph()->NewNode(mcgraph()->machine()->F64x2Pmax(), inputs[0], inputs[1]); case wasm::kExprF64x2Ceil: // Architecture support for F64x2Ceil and Float64RoundUp is the same. if (!mcgraph()->machine()->Float64RoundUp().IsSupported()) return BuildF64x2Ceil(inputs[0]); return graph()->NewNode(mcgraph()->machine()->F64x2Ceil(), inputs[0]); case wasm::kExprF64x2Floor: // Architecture support for F64x2Floor and Float64RoundDown is the same. if (!mcgraph()->machine()->Float64RoundDown().IsSupported()) return BuildF64x2Floor(inputs[0]); return graph()->NewNode(mcgraph()->machine()->F64x2Floor(), inputs[0]); case wasm::kExprF64x2Trunc: // Architecture support for F64x2Trunc and Float64RoundTruncate is the // same. if (!mcgraph()->machine()->Float64RoundTruncate().IsSupported()) return BuildF64x2Trunc(inputs[0]); return graph()->NewNode(mcgraph()->machine()->F64x2Trunc(), inputs[0]); case wasm::kExprF64x2NearestInt: // Architecture support for F64x2NearestInt and Float64RoundTiesEven is // the same. if (!mcgraph()->machine()->Float64RoundTiesEven().IsSupported()) return BuildF64x2NearestInt(inputs[0]); return graph()->NewNode(mcgraph()->machine()->F64x2NearestInt(), inputs[0]); case wasm::kExprF32x4Splat: return graph()->NewNode(mcgraph()->machine()->F32x4Splat(), inputs[0]); case wasm::kExprF32x4SConvertI32x4: return graph()->NewNode(mcgraph()->machine()->F32x4SConvertI32x4(), inputs[0]); case wasm::kExprF32x4UConvertI32x4: return graph()->NewNode(mcgraph()->machine()->F32x4UConvertI32x4(), inputs[0]); case wasm::kExprF32x4Abs: return graph()->NewNode(mcgraph()->machine()->F32x4Abs(), inputs[0]); case wasm::kExprF32x4Neg: return graph()->NewNode(mcgraph()->machine()->F32x4Neg(), inputs[0]); case wasm::kExprF32x4Sqrt: return graph()->NewNode(mcgraph()->machine()->F32x4Sqrt(), inputs[0]); case wasm::kExprF32x4RecipApprox: return graph()->NewNode(mcgraph()->machine()->F32x4RecipApprox(), inputs[0]); case wasm::kExprF32x4RecipSqrtApprox: return graph()->NewNode(mcgraph()->machine()->F32x4RecipSqrtApprox(), inputs[0]); case wasm::kExprF32x4Add: return graph()->NewNode(mcgraph()->machine()->F32x4Add(), inputs[0], inputs[1]); case wasm::kExprF32x4AddHoriz: return graph()->NewNode(mcgraph()->machine()->F32x4AddHoriz(), inputs[0], inputs[1]); case wasm::kExprF32x4Sub: return graph()->NewNode(mcgraph()->machine()->F32x4Sub(), inputs[0], inputs[1]); case wasm::kExprF32x4Mul: return graph()->NewNode(mcgraph()->machine()->F32x4Mul(), inputs[0], inputs[1]); case wasm::kExprF32x4Div: return graph()->NewNode(mcgraph()->machine()->F32x4Div(), inputs[0], inputs[1]); case wasm::kExprF32x4Min: return graph()->NewNode(mcgraph()->machine()->F32x4Min(), inputs[0], inputs[1]); case wasm::kExprF32x4Max: return graph()->NewNode(mcgraph()->machine()->F32x4Max(), inputs[0], inputs[1]); case wasm::kExprF32x4Eq: return graph()->NewNode(mcgraph()->machine()->F32x4Eq(), inputs[0], inputs[1]); case wasm::kExprF32x4Ne: return graph()->NewNode(mcgraph()->machine()->F32x4Ne(), inputs[0], inputs[1]); case wasm::kExprF32x4Lt: return graph()->NewNode(mcgraph()->machine()->F32x4Lt(), inputs[0], inputs[1]); case wasm::kExprF32x4Le: return graph()->NewNode(mcgraph()->machine()->F32x4Le(), inputs[0], inputs[1]); case wasm::kExprF32x4Gt: return graph()->NewNode(mcgraph()->machine()->F32x4Lt(), inputs[1], inputs[0]); case wasm::kExprF32x4Ge: return graph()->NewNode(mcgraph()->machine()->F32x4Le(), inputs[1], inputs[0]); case wasm::kExprF32x4Qfma: return graph()->NewNode(mcgraph()->machine()->F32x4Qfma(), inputs[0], inputs[1], inputs[2]); case wasm::kExprF32x4Qfms: return graph()->NewNode(mcgraph()->machine()->F32x4Qfms(), inputs[0], inputs[1], inputs[2]); case wasm::kExprF32x4Pmin: return graph()->NewNode(mcgraph()->machine()->F32x4Pmin(), inputs[0], inputs[1]); case wasm::kExprF32x4Pmax: return graph()->NewNode(mcgraph()->machine()->F32x4Pmax(), inputs[0], inputs[1]); case wasm::kExprF32x4Ceil: // Architecture support for F32x4Ceil and Float32RoundUp is the same. if (!mcgraph()->machine()->Float32RoundUp().IsSupported()) return BuildF32x4Ceil(inputs[0]); return graph()->NewNode(mcgraph()->machine()->F32x4Ceil(), inputs[0]); case wasm::kExprF32x4Floor: // Architecture support for F32x4Floor and Float32RoundDown is the same. if (!mcgraph()->machine()->Float32RoundDown().IsSupported()) return BuildF32x4Floor(inputs[0]); return graph()->NewNode(mcgraph()->machine()->F32x4Floor(), inputs[0]); case wasm::kExprF32x4Trunc: // Architecture support for F32x4Trunc and Float32RoundTruncate is the // same. if (!mcgraph()->machine()->Float32RoundTruncate().IsSupported()) return BuildF32x4Trunc(inputs[0]); return graph()->NewNode(mcgraph()->machine()->F32x4Trunc(), inputs[0]); case wasm::kExprF32x4NearestInt: // Architecture support for F32x4NearestInt and Float32RoundTiesEven is // the same. if (!mcgraph()->machine()->Float32RoundTiesEven().IsSupported()) return BuildF32x4NearestInt(inputs[0]); return graph()->NewNode(mcgraph()->machine()->F32x4NearestInt(), inputs[0]); case wasm::kExprI64x2Splat: return graph()->NewNode(mcgraph()->machine()->I64x2Splat(), inputs[0]); case wasm::kExprI64x2Neg: return graph()->NewNode(mcgraph()->machine()->I64x2Neg(), inputs[0]); case wasm::kExprI64x2SConvertI32x4Low: return graph()->NewNode(mcgraph()->machine()->I64x2SConvertI32x4Low(), inputs[0]); case wasm::kExprI64x2SConvertI32x4High: return graph()->NewNode(mcgraph()->machine()->I64x2SConvertI32x4High(), inputs[0]); case wasm::kExprI64x2UConvertI32x4Low: return graph()->NewNode(mcgraph()->machine()->I64x2UConvertI32x4Low(), inputs[0]); case wasm::kExprI64x2UConvertI32x4High: return graph()->NewNode(mcgraph()->machine()->I64x2UConvertI32x4High(), inputs[0]); case wasm::kExprI64x2Shl: return graph()->NewNode(mcgraph()->machine()->I64x2Shl(), inputs[0], inputs[1]); case wasm::kExprI64x2ShrS: return graph()->NewNode(mcgraph()->machine()->I64x2ShrS(), inputs[0], inputs[1]); case wasm::kExprI64x2Add: return graph()->NewNode(mcgraph()->machine()->I64x2Add(), inputs[0], inputs[1]); case wasm::kExprI64x2Sub: return graph()->NewNode(mcgraph()->machine()->I64x2Sub(), inputs[0], inputs[1]); case wasm::kExprI64x2Mul: return graph()->NewNode(mcgraph()->machine()->I64x2Mul(), inputs[0], inputs[1]); case wasm::kExprI64x2MinS: return graph()->NewNode(mcgraph()->machine()->I64x2MinS(), inputs[0], inputs[1]); case wasm::kExprI64x2MaxS: return graph()->NewNode(mcgraph()->machine()->I64x2MaxS(), inputs[0], inputs[1]); case wasm::kExprI64x2Eq: return graph()->NewNode(mcgraph()->machine()->I64x2Eq(), inputs[0], inputs[1]); case wasm::kExprI64x2Ne: return graph()->NewNode(mcgraph()->machine()->I64x2Ne(), inputs[0], inputs[1]); case wasm::kExprI64x2LtS: return graph()->NewNode(mcgraph()->machine()->I64x2GtS(), inputs[1], inputs[0]); case wasm::kExprI64x2LeS: return graph()->NewNode(mcgraph()->machine()->I64x2GeS(), inputs[1], inputs[0]); case wasm::kExprI64x2GtS: return graph()->NewNode(mcgraph()->machine()->I64x2GtS(), inputs[0], inputs[1]); case wasm::kExprI64x2GeS: return graph()->NewNode(mcgraph()->machine()->I64x2GeS(), inputs[0], inputs[1]); case wasm::kExprI64x2ShrU: return graph()->NewNode(mcgraph()->machine()->I64x2ShrU(), inputs[0], inputs[1]); case wasm::kExprI64x2MinU: return graph()->NewNode(mcgraph()->machine()->I64x2MinU(), inputs[0], inputs[1]); case wasm::kExprI64x2MaxU: return graph()->NewNode(mcgraph()->machine()->I64x2MaxU(), inputs[0], inputs[1]); case wasm::kExprI64x2LtU: return graph()->NewNode(mcgraph()->machine()->I64x2GtU(), inputs[1], inputs[0]); case wasm::kExprI64x2LeU: return graph()->NewNode(mcgraph()->machine()->I64x2GeU(), inputs[1], inputs[0]); case wasm::kExprI64x2GtU: return graph()->NewNode(mcgraph()->machine()->I64x2GtU(), inputs[0], inputs[1]); case wasm::kExprI64x2GeU: return graph()->NewNode(mcgraph()->machine()->I64x2GeU(), inputs[0], inputs[1]); case wasm::kExprI32x4Splat: return graph()->NewNode(mcgraph()->machine()->I32x4Splat(), inputs[0]); case wasm::kExprI32x4SConvertF32x4: return graph()->NewNode(mcgraph()->machine()->I32x4SConvertF32x4(), inputs[0]); case wasm::kExprI32x4UConvertF32x4: return graph()->NewNode(mcgraph()->machine()->I32x4UConvertF32x4(), inputs[0]); case wasm::kExprI32x4SConvertI16x8Low: return graph()->NewNode(mcgraph()->machine()->I32x4SConvertI16x8Low(), inputs[0]); case wasm::kExprI32x4SConvertI16x8High: return graph()->NewNode(mcgraph()->machine()->I32x4SConvertI16x8High(), inputs[0]); case wasm::kExprI32x4Neg: return graph()->NewNode(mcgraph()->machine()->I32x4Neg(), inputs[0]); case wasm::kExprI32x4Shl: return graph()->NewNode(mcgraph()->machine()->I32x4Shl(), inputs[0], inputs[1]); case wasm::kExprI32x4ShrS: return graph()->NewNode(mcgraph()->machine()->I32x4ShrS(), inputs[0], inputs[1]); case wasm::kExprI32x4Add: return graph()->NewNode(mcgraph()->machine()->I32x4Add(), inputs[0], inputs[1]); case wasm::kExprI32x4AddHoriz: return graph()->NewNode(mcgraph()->machine()->I32x4AddHoriz(), inputs[0], inputs[1]); case wasm::kExprI32x4Sub: return graph()->NewNode(mcgraph()->machine()->I32x4Sub(), inputs[0], inputs[1]); case wasm::kExprI32x4Mul: return graph()->NewNode(mcgraph()->machine()->I32x4Mul(), inputs[0], inputs[1]); case wasm::kExprI32x4MinS: return graph()->NewNode(mcgraph()->machine()->I32x4MinS(), inputs[0], inputs[1]); case wasm::kExprI32x4MaxS: return graph()->NewNode(mcgraph()->machine()->I32x4MaxS(), inputs[0], inputs[1]); case wasm::kExprI32x4Eq: return graph()->NewNode(mcgraph()->machine()->I32x4Eq(), inputs[0], inputs[1]); case wasm::kExprI32x4Ne: return graph()->NewNode(mcgraph()->machine()->I32x4Ne(), inputs[0], inputs[1]); case wasm::kExprI32x4LtS: return graph()->NewNode(mcgraph()->machine()->I32x4GtS(), inputs[1], inputs[0]); case wasm::kExprI32x4LeS: return graph()->NewNode(mcgraph()->machine()->I32x4GeS(), inputs[1], inputs[0]); case wasm::kExprI32x4GtS: return graph()->NewNode(mcgraph()->machine()->I32x4GtS(), inputs[0], inputs[1]); case wasm::kExprI32x4GeS: return graph()->NewNode(mcgraph()->machine()->I32x4GeS(), inputs[0], inputs[1]); case wasm::kExprI32x4UConvertI16x8Low: return graph()->NewNode(mcgraph()->machine()->I32x4UConvertI16x8Low(), inputs[0]); case wasm::kExprI32x4UConvertI16x8High: return graph()->NewNode(mcgraph()->machine()->I32x4UConvertI16x8High(), inputs[0]); case wasm::kExprI32x4ShrU: return graph()->NewNode(mcgraph()->machine()->I32x4ShrU(), inputs[0], inputs[1]); case wasm::kExprI32x4MinU: return graph()->NewNode(mcgraph()->machine()->I32x4MinU(), inputs[0], inputs[1]); case wasm::kExprI32x4MaxU: return graph()->NewNode(mcgraph()->machine()->I32x4MaxU(), inputs[0], inputs[1]); case wasm::kExprI32x4LtU: return graph()->NewNode(mcgraph()->machine()->I32x4GtU(), inputs[1], inputs[0]); case wasm::kExprI32x4LeU: return graph()->NewNode(mcgraph()->machine()->I32x4GeU(), inputs[1], inputs[0]); case wasm::kExprI32x4GtU: return graph()->NewNode(mcgraph()->machine()->I32x4GtU(), inputs[0], inputs[1]); case wasm::kExprI32x4GeU: return graph()->NewNode(mcgraph()->machine()->I32x4GeU(), inputs[0], inputs[1]); case wasm::kExprI32x4Abs: return graph()->NewNode(mcgraph()->machine()->I32x4Abs(), inputs[0]); case wasm::kExprI32x4BitMask: return graph()->NewNode(mcgraph()->machine()->I32x4BitMask(), inputs[0]); case wasm::kExprI32x4DotI16x8S: return graph()->NewNode(mcgraph()->machine()->I32x4DotI16x8S(), inputs[0], inputs[1]); case wasm::kExprI16x8Splat: return graph()->NewNode(mcgraph()->machine()->I16x8Splat(), inputs[0]); case wasm::kExprI16x8SConvertI8x16Low: return graph()->NewNode(mcgraph()->machine()->I16x8SConvertI8x16Low(), inputs[0]); case wasm::kExprI16x8SConvertI8x16High: return graph()->NewNode(mcgraph()->machine()->I16x8SConvertI8x16High(), inputs[0]); case wasm::kExprI16x8Shl: return graph()->NewNode(mcgraph()->machine()->I16x8Shl(), inputs[0], inputs[1]); case wasm::kExprI16x8ShrS: return graph()->NewNode(mcgraph()->machine()->I16x8ShrS(), inputs[0], inputs[1]); case wasm::kExprI16x8Neg: return graph()->NewNode(mcgraph()->machine()->I16x8Neg(), inputs[0]); case wasm::kExprI16x8SConvertI32x4: return graph()->NewNode(mcgraph()->machine()->I16x8SConvertI32x4(), inputs[0], inputs[1]); case wasm::kExprI16x8Add: return graph()->NewNode(mcgraph()->machine()->I16x8Add(), inputs[0], inputs[1]); case wasm::kExprI16x8AddSaturateS: return graph()->NewNode(mcgraph()->machine()->I16x8AddSaturateS(), inputs[0], inputs[1]); case wasm::kExprI16x8AddHoriz: return graph()->NewNode(mcgraph()->machine()->I16x8AddHoriz(), inputs[0], inputs[1]); case wasm::kExprI16x8Sub: return graph()->NewNode(mcgraph()->machine()->I16x8Sub(), inputs[0], inputs[1]); case wasm::kExprI16x8SubSaturateS: return graph()->NewNode(mcgraph()->machine()->I16x8SubSaturateS(), inputs[0], inputs[1]); case wasm::kExprI16x8Mul: return graph()->NewNode(mcgraph()->machine()->I16x8Mul(), inputs[0], inputs[1]); case wasm::kExprI16x8MinS: return graph()->NewNode(mcgraph()->machine()->I16x8MinS(), inputs[0], inputs[1]); case wasm::kExprI16x8MaxS: return graph()->NewNode(mcgraph()->machine()->I16x8MaxS(), inputs[0], inputs[1]); case wasm::kExprI16x8Eq: return graph()->NewNode(mcgraph()->machine()->I16x8Eq(), inputs[0], inputs[1]); case wasm::kExprI16x8Ne: return graph()->NewNode(mcgraph()->machine()->I16x8Ne(), inputs[0], inputs[1]); case wasm::kExprI16x8LtS: return graph()->NewNode(mcgraph()->machine()->I16x8GtS(), inputs[1], inputs[0]); case wasm::kExprI16x8LeS: return graph()->NewNode(mcgraph()->machine()->I16x8GeS(), inputs[1], inputs[0]); case wasm::kExprI16x8GtS: return graph()->NewNode(mcgraph()->machine()->I16x8GtS(), inputs[0], inputs[1]); case wasm::kExprI16x8GeS: return graph()->NewNode(mcgraph()->machine()->I16x8GeS(), inputs[0], inputs[1]); case wasm::kExprI16x8UConvertI8x16Low: return graph()->NewNode(mcgraph()->machine()->I16x8UConvertI8x16Low(), inputs[0]); case wasm::kExprI16x8UConvertI8x16High: return graph()->NewNode(mcgraph()->machine()->I16x8UConvertI8x16High(), inputs[0]); case wasm::kExprI16x8UConvertI32x4: return graph()->NewNode(mcgraph()->machine()->I16x8UConvertI32x4(), inputs[0], inputs[1]); case wasm::kExprI16x8ShrU: return graph()->NewNode(mcgraph()->machine()->I16x8ShrU(), inputs[0], inputs[1]); case wasm::kExprI16x8AddSaturateU: return graph()->NewNode(mcgraph()->machine()->I16x8AddSaturateU(), inputs[0], inputs[1]); case wasm::kExprI16x8SubSaturateU: return graph()->NewNode(mcgraph()->machine()->I16x8SubSaturateU(), inputs[0], inputs[1]); case wasm::kExprI16x8MinU: return graph()->NewNode(mcgraph()->machine()->I16x8MinU(), inputs[0], inputs[1]); case wasm::kExprI16x8MaxU: return graph()->NewNode(mcgraph()->machine()->I16x8MaxU(), inputs[0], inputs[1]); case wasm::kExprI16x8LtU: return graph()->NewNode(mcgraph()->machine()->I16x8GtU(), inputs[1], inputs[0]); case wasm::kExprI16x8LeU: return graph()->NewNode(mcgraph()->machine()->I16x8GeU(), inputs[1], inputs[0]); case wasm::kExprI16x8GtU: return graph()->NewNode(mcgraph()->machine()->I16x8GtU(), inputs[0], inputs[1]); case wasm::kExprI16x8GeU: return graph()->NewNode(mcgraph()->machine()->I16x8GeU(), inputs[0], inputs[1]); case wasm::kExprI16x8RoundingAverageU: return graph()->NewNode(mcgraph()->machine()->I16x8RoundingAverageU(), inputs[0], inputs[1]); case wasm::kExprI16x8Q15MulRSatS: return graph()->NewNode(mcgraph()->machine()->I16x8Q15MulRSatS(), inputs[0], inputs[1]); case wasm::kExprI16x8Abs: return graph()->NewNode(mcgraph()->machine()->I16x8Abs(), inputs[0]); case wasm::kExprI16x8BitMask: return graph()->NewNode(mcgraph()->machine()->I16x8BitMask(), inputs[0]); case wasm::kExprI8x16Splat: return graph()->NewNode(mcgraph()->machine()->I8x16Splat(), inputs[0]); case wasm::kExprI8x16Neg: return graph()->NewNode(mcgraph()->machine()->I8x16Neg(), inputs[0]); case wasm::kExprI8x16Shl: return graph()->NewNode(mcgraph()->machine()->I8x16Shl(), inputs[0], inputs[1]); case wasm::kExprI8x16ShrS: return graph()->NewNode(mcgraph()->machine()->I8x16ShrS(), inputs[0], inputs[1]); case wasm::kExprI8x16SConvertI16x8: return graph()->NewNode(mcgraph()->machine()->I8x16SConvertI16x8(), inputs[0], inputs[1]); case wasm::kExprI8x16Add: return graph()->NewNode(mcgraph()->machine()->I8x16Add(), inputs[0], inputs[1]); case wasm::kExprI8x16AddSaturateS: return graph()->NewNode(mcgraph()->machine()->I8x16AddSaturateS(), inputs[0], inputs[1]); case wasm::kExprI8x16Sub: return graph()->NewNode(mcgraph()->machine()->I8x16Sub(), inputs[0], inputs[1]); case wasm::kExprI8x16SubSaturateS: return graph()->NewNode(mcgraph()->machine()->I8x16SubSaturateS(), inputs[0], inputs[1]); case wasm::kExprI8x16Mul: return graph()->NewNode(mcgraph()->machine()->I8x16Mul(), inputs[0], inputs[1]); case wasm::kExprI8x16MinS: return graph()->NewNode(mcgraph()->machine()->I8x16MinS(), inputs[0], inputs[1]); case wasm::kExprI8x16MaxS: return graph()->NewNode(mcgraph()->machine()->I8x16MaxS(), inputs[0], inputs[1]); case wasm::kExprI8x16Eq: return graph()->NewNode(mcgraph()->machine()->I8x16Eq(), inputs[0], inputs[1]); case wasm::kExprI8x16Ne: return graph()->NewNode(mcgraph()->machine()->I8x16Ne(), inputs[0], inputs[1]); case wasm::kExprI8x16LtS: return graph()->NewNode(mcgraph()->machine()->I8x16GtS(), inputs[1], inputs[0]); case wasm::kExprI8x16LeS: return graph()->NewNode(mcgraph()->machine()->I8x16GeS(), inputs[1], inputs[0]); case wasm::kExprI8x16GtS: return graph()->NewNode(mcgraph()->machine()->I8x16GtS(), inputs[0], inputs[1]); case wasm::kExprI8x16GeS: return graph()->NewNode(mcgraph()->machine()->I8x16GeS(), inputs[0], inputs[1]); case wasm::kExprI8x16ShrU: return graph()->NewNode(mcgraph()->machine()->I8x16ShrU(), inputs[0], inputs[1]); case wasm::kExprI8x16UConvertI16x8: return graph()->NewNode(mcgraph()->machine()->I8x16UConvertI16x8(), inputs[0], inputs[1]); case wasm::kExprI8x16AddSaturateU: return graph()->NewNode(mcgraph()->machine()->I8x16AddSaturateU(), inputs[0], inputs[1]); case wasm::kExprI8x16SubSaturateU: return graph()->NewNode(mcgraph()->machine()->I8x16SubSaturateU(), inputs[0], inputs[1]); case wasm::kExprI8x16MinU: return graph()->NewNode(mcgraph()->machine()->I8x16MinU(), inputs[0], inputs[1]); case wasm::kExprI8x16MaxU: return graph()->NewNode(mcgraph()->machine()->I8x16MaxU(), inputs[0], inputs[1]); case wasm::kExprI8x16LtU: return graph()->NewNode(mcgraph()->machine()->I8x16GtU(), inputs[1], inputs[0]); case wasm::kExprI8x16LeU: return graph()->NewNode(mcgraph()->machine()->I8x16GeU(), inputs[1], inputs[0]); case wasm::kExprI8x16GtU: return graph()->NewNode(mcgraph()->machine()->I8x16GtU(), inputs[0], inputs[1]); case wasm::kExprI8x16GeU: return graph()->NewNode(mcgraph()->machine()->I8x16GeU(), inputs[0], inputs[1]); case wasm::kExprI8x16RoundingAverageU: return graph()->NewNode(mcgraph()->machine()->I8x16RoundingAverageU(), inputs[0], inputs[1]); case wasm::kExprI8x16Abs: return graph()->NewNode(mcgraph()->machine()->I8x16Abs(), inputs[0]); case wasm::kExprI8x16BitMask: return graph()->NewNode(mcgraph()->machine()->I8x16BitMask(), inputs[0]); case wasm::kExprS128And: return graph()->NewNode(mcgraph()->machine()->S128And(), inputs[0], inputs[1]); case wasm::kExprS128Or: return graph()->NewNode(mcgraph()->machine()->S128Or(), inputs[0], inputs[1]); case wasm::kExprS128Xor: return graph()->NewNode(mcgraph()->machine()->S128Xor(), inputs[0], inputs[1]); case wasm::kExprS128Not: return graph()->NewNode(mcgraph()->machine()->S128Not(), inputs[0]); case wasm::kExprS128Select: return graph()->NewNode(mcgraph()->machine()->S128Select(), inputs[2], inputs[0], inputs[1]); case wasm::kExprS128AndNot: return graph()->NewNode(mcgraph()->machine()->S128AndNot(), inputs[0], inputs[1]); case wasm::kExprV64x2AnyTrue: return graph()->NewNode(mcgraph()->machine()->V64x2AnyTrue(), inputs[0]); case wasm::kExprV64x2AllTrue: return graph()->NewNode(mcgraph()->machine()->V64x2AllTrue(), inputs[0]); case wasm::kExprV32x4AnyTrue: return graph()->NewNode(mcgraph()->machine()->V32x4AnyTrue(), inputs[0]); case wasm::kExprV32x4AllTrue: return graph()->NewNode(mcgraph()->machine()->V32x4AllTrue(), inputs[0]); case wasm::kExprV16x8AnyTrue: return graph()->NewNode(mcgraph()->machine()->V16x8AnyTrue(), inputs[0]); case wasm::kExprV16x8AllTrue: return graph()->NewNode(mcgraph()->machine()->V16x8AllTrue(), inputs[0]); case wasm::kExprV8x16AnyTrue: return graph()->NewNode(mcgraph()->machine()->V8x16AnyTrue(), inputs[0]); case wasm::kExprV8x16AllTrue: return graph()->NewNode(mcgraph()->machine()->V8x16AllTrue(), inputs[0]); case wasm::kExprI8x16Swizzle: return graph()->NewNode(mcgraph()->machine()->I8x16Swizzle(), inputs[0], inputs[1]); default: FATAL_UNSUPPORTED_OPCODE(opcode); } } Node* WasmGraphBuilder::SimdLaneOp(wasm::WasmOpcode opcode, uint8_t lane, Node* const* inputs) { has_simd_ = true; switch (opcode) { case wasm::kExprF64x2ExtractLane: return graph()->NewNode(mcgraph()->machine()->F64x2ExtractLane(lane), inputs[0]); case wasm::kExprF64x2ReplaceLane: return graph()->NewNode(mcgraph()->machine()->F64x2ReplaceLane(lane), inputs[0], inputs[1]); case wasm::kExprF32x4ExtractLane: return graph()->NewNode(mcgraph()->machine()->F32x4ExtractLane(lane), inputs[0]); case wasm::kExprF32x4ReplaceLane: return graph()->NewNode(mcgraph()->machine()->F32x4ReplaceLane(lane), inputs[0], inputs[1]); case wasm::kExprI64x2ExtractLane: return graph()->NewNode(mcgraph()->machine()->I64x2ExtractLane(lane), inputs[0]); case wasm::kExprI64x2ReplaceLane: return graph()->NewNode(mcgraph()->machine()->I64x2ReplaceLane(lane), inputs[0], inputs[1]); case wasm::kExprI32x4ExtractLane: return graph()->NewNode(mcgraph()->machine()->I32x4ExtractLane(lane), inputs[0]); case wasm::kExprI32x4ReplaceLane: return graph()->NewNode(mcgraph()->machine()->I32x4ReplaceLane(lane), inputs[0], inputs[1]); case wasm::kExprI16x8ExtractLaneS: return graph()->NewNode(mcgraph()->machine()->I16x8ExtractLaneS(lane), inputs[0]); case wasm::kExprI16x8ExtractLaneU: return graph()->NewNode(mcgraph()->machine()->I16x8ExtractLaneU(lane), inputs[0]); case wasm::kExprI16x8ReplaceLane: return graph()->NewNode(mcgraph()->machine()->I16x8ReplaceLane(lane), inputs[0], inputs[1]); case wasm::kExprI8x16ExtractLaneS: return graph()->NewNode(mcgraph()->machine()->I8x16ExtractLaneS(lane), inputs[0]); case wasm::kExprI8x16ExtractLaneU: return graph()->NewNode(mcgraph()->machine()->I8x16ExtractLaneU(lane), inputs[0]); case wasm::kExprI8x16ReplaceLane: return graph()->NewNode(mcgraph()->machine()->I8x16ReplaceLane(lane), inputs[0], inputs[1]); default: FATAL_UNSUPPORTED_OPCODE(opcode); } } Node* WasmGraphBuilder::Simd8x16ShuffleOp(const uint8_t shuffle[16], Node* const* inputs) { has_simd_ = true; return graph()->NewNode(mcgraph()->machine()->I8x16Shuffle(shuffle), inputs[0], inputs[1]); } Node* WasmGraphBuilder::AtomicOp(wasm::WasmOpcode opcode, Node* const* inputs, uint32_t alignment, uint64_t offset, wasm::WasmCodePosition position) { struct AtomicOpInfo { enum Type : int8_t { kNoInput = 0, kOneInput = 1, kTwoInputs = 2, kSpecial }; using OperatorByType = const Operator* (MachineOperatorBuilder::*)(MachineType); using OperatorByRep = const Operator* (MachineOperatorBuilder::*)(MachineRepresentation); const Type type; const MachineType machine_type; const OperatorByType operator_by_type = nullptr; const OperatorByRep operator_by_rep = nullptr; constexpr AtomicOpInfo(Type t, MachineType m, OperatorByType o) : type(t), machine_type(m), operator_by_type(o) {} constexpr AtomicOpInfo(Type t, MachineType m, OperatorByRep o) : type(t), machine_type(m), operator_by_rep(o) {} // Constexpr, hence just a table lookup in most compilers. static constexpr AtomicOpInfo Get(wasm::WasmOpcode opcode) { switch (opcode) { #define CASE(Name, Type, MachType, Op) \ case wasm::kExpr##Name: \ return {Type, MachineType::MachType(), &MachineOperatorBuilder::Op}; // Binops. CASE(I32AtomicAdd, kOneInput, Uint32, Word32AtomicAdd) CASE(I64AtomicAdd, kOneInput, Uint64, Word64AtomicAdd) CASE(I32AtomicAdd8U, kOneInput, Uint8, Word32AtomicAdd) CASE(I32AtomicAdd16U, kOneInput, Uint16, Word32AtomicAdd) CASE(I64AtomicAdd8U, kOneInput, Uint8, Word64AtomicAdd) CASE(I64AtomicAdd16U, kOneInput, Uint16, Word64AtomicAdd) CASE(I64AtomicAdd32U, kOneInput, Uint32, Word64AtomicAdd) CASE(I32AtomicSub, kOneInput, Uint32, Word32AtomicSub) CASE(I64AtomicSub, kOneInput, Uint64, Word64AtomicSub) CASE(I32AtomicSub8U, kOneInput, Uint8, Word32AtomicSub) CASE(I32AtomicSub16U, kOneInput, Uint16, Word32AtomicSub) CASE(I64AtomicSub8U, kOneInput, Uint8, Word64AtomicSub) CASE(I64AtomicSub16U, kOneInput, Uint16, Word64AtomicSub) CASE(I64AtomicSub32U, kOneInput, Uint32, Word64AtomicSub) CASE(I32AtomicAnd, kOneInput, Uint32, Word32AtomicAnd) CASE(I64AtomicAnd, kOneInput, Uint64, Word64AtomicAnd) CASE(I32AtomicAnd8U, kOneInput, Uint8, Word32AtomicAnd) CASE(I32AtomicAnd16U, kOneInput, Uint16, Word32AtomicAnd) CASE(I64AtomicAnd8U, kOneInput, Uint8, Word64AtomicAnd) CASE(I64AtomicAnd16U, kOneInput, Uint16, Word64AtomicAnd) CASE(I64AtomicAnd32U, kOneInput, Uint32, Word64AtomicAnd) CASE(I32AtomicOr, kOneInput, Uint32, Word32AtomicOr) CASE(I64AtomicOr, kOneInput, Uint64, Word64AtomicOr) CASE(I32AtomicOr8U, kOneInput, Uint8, Word32AtomicOr) CASE(I32AtomicOr16U, kOneInput, Uint16, Word32AtomicOr) CASE(I64AtomicOr8U, kOneInput, Uint8, Word64AtomicOr) CASE(I64AtomicOr16U, kOneInput, Uint16, Word64AtomicOr) CASE(I64AtomicOr32U, kOneInput, Uint32, Word64AtomicOr) CASE(I32AtomicXor, kOneInput, Uint32, Word32AtomicXor) CASE(I64AtomicXor, kOneInput, Uint64, Word64AtomicXor) CASE(I32AtomicXor8U, kOneInput, Uint8, Word32AtomicXor) CASE(I32AtomicXor16U, kOneInput, Uint16, Word32AtomicXor) CASE(I64AtomicXor8U, kOneInput, Uint8, Word64AtomicXor) CASE(I64AtomicXor16U, kOneInput, Uint16, Word64AtomicXor) CASE(I64AtomicXor32U, kOneInput, Uint32, Word64AtomicXor) CASE(I32AtomicExchange, kOneInput, Uint32, Word32AtomicExchange) CASE(I64AtomicExchange, kOneInput, Uint64, Word64AtomicExchange) CASE(I32AtomicExchange8U, kOneInput, Uint8, Word32AtomicExchange) CASE(I32AtomicExchange16U, kOneInput, Uint16, Word32AtomicExchange) CASE(I64AtomicExchange8U, kOneInput, Uint8, Word64AtomicExchange) CASE(I64AtomicExchange16U, kOneInput, Uint16, Word64AtomicExchange) CASE(I64AtomicExchange32U, kOneInput, Uint32, Word64AtomicExchange) // Compare-exchange. CASE(I32AtomicCompareExchange, kTwoInputs, Uint32, Word32AtomicCompareExchange) CASE(I64AtomicCompareExchange, kTwoInputs, Uint64, Word64AtomicCompareExchange) CASE(I32AtomicCompareExchange8U, kTwoInputs, Uint8, Word32AtomicCompareExchange) CASE(I32AtomicCompareExchange16U, kTwoInputs, Uint16, Word32AtomicCompareExchange) CASE(I64AtomicCompareExchange8U, kTwoInputs, Uint8, Word64AtomicCompareExchange) CASE(I64AtomicCompareExchange16U, kTwoInputs, Uint16, Word64AtomicCompareExchange) CASE(I64AtomicCompareExchange32U, kTwoInputs, Uint32, Word64AtomicCompareExchange) // Load. CASE(I32AtomicLoad, kNoInput, Uint32, Word32AtomicLoad) CASE(I64AtomicLoad, kNoInput, Uint64, Word64AtomicLoad) CASE(I32AtomicLoad8U, kNoInput, Uint8, Word32AtomicLoad) CASE(I32AtomicLoad16U, kNoInput, Uint16, Word32AtomicLoad) CASE(I64AtomicLoad8U, kNoInput, Uint8, Word64AtomicLoad) CASE(I64AtomicLoad16U, kNoInput, Uint16, Word64AtomicLoad) CASE(I64AtomicLoad32U, kNoInput, Uint32, Word64AtomicLoad) // Store. CASE(I32AtomicStore, kOneInput, Uint32, Word32AtomicStore) CASE(I64AtomicStore, kOneInput, Uint64, Word64AtomicStore) CASE(I32AtomicStore8U, kOneInput, Uint8, Word32AtomicStore) CASE(I32AtomicStore16U, kOneInput, Uint16, Word32AtomicStore) CASE(I64AtomicStore8U, kOneInput, Uint8, Word64AtomicStore) CASE(I64AtomicStore16U, kOneInput, Uint16, Word64AtomicStore) CASE(I64AtomicStore32U, kOneInput, Uint32, Word64AtomicStore) #undef CASE case wasm::kExprAtomicNotify: return {kSpecial, MachineType::Int32(), OperatorByType{nullptr}}; case wasm::kExprI32AtomicWait: return {kSpecial, MachineType::Int32(), OperatorByType{nullptr}}; case wasm::kExprI64AtomicWait: return {kSpecial, MachineType::Int64(), OperatorByType{nullptr}}; default: #if V8_HAS_CXX14_CONSTEXPR UNREACHABLE(); #else // Return something for older GCC. return {kSpecial, MachineType::Int64(), OperatorByType{nullptr}}; #endif } } }; AtomicOpInfo info = AtomicOpInfo::Get(opcode); Node* index = CheckBoundsAndAlignment(info.machine_type.MemSize(), inputs[0], offset, position); // {offset} is validated to be within uintptr_t range in {BoundsCheckMem}. uintptr_t capped_offset = static_cast<uintptr_t>(offset); if (info.type != AtomicOpInfo::kSpecial) { const Operator* op = info.operator_by_type ? (mcgraph()->machine()->*info.operator_by_type)(info.machine_type) : (mcgraph()->machine()->*info.operator_by_rep)( info.machine_type.representation()); Node* input_nodes[6] = {MemBuffer(capped_offset), index}; int num_actual_inputs = info.type; std::copy_n(inputs + 1, num_actual_inputs, input_nodes + 2); input_nodes[num_actual_inputs + 2] = effect(); input_nodes[num_actual_inputs + 3] = control(); return gasm_->AddNode( graph()->NewNode(op, num_actual_inputs + 4, input_nodes)); } // After we've bounds-checked, compute the effective address. Node* address = gasm_->IntAdd(gasm_->UintPtrConstant(capped_offset), index); switch (opcode) { case wasm::kExprAtomicNotify: { auto* call_descriptor = GetBuiltinCallDescriptor<WasmAtomicNotifyDescriptor>( this, StubCallMode::kCallWasmRuntimeStub); Node* call_target = mcgraph()->RelocatableIntPtrConstant( wasm::WasmCode::kWasmAtomicNotify, RelocInfo::WASM_STUB_CALL); return gasm_->Call(call_descriptor, call_target, address, inputs[1]); } case wasm::kExprI32AtomicWait: { auto* call_descriptor = GetI32AtomicWaitCallDescriptor(); intptr_t target = mcgraph()->machine()->Is64() ? wasm::WasmCode::kWasmI32AtomicWait64 : wasm::WasmCode::kWasmI32AtomicWait32; Node* call_target = mcgraph()->RelocatableIntPtrConstant( target, RelocInfo::WASM_STUB_CALL); return gasm_->Call(call_descriptor, call_target, address, inputs[1], inputs[2]); } case wasm::kExprI64AtomicWait: { auto* call_descriptor = GetI64AtomicWaitCallDescriptor(); intptr_t target = mcgraph()->machine()->Is64() ? wasm::WasmCode::kWasmI64AtomicWait64 : wasm::WasmCode::kWasmI64AtomicWait32; Node* call_target = mcgraph()->RelocatableIntPtrConstant( target, RelocInfo::WASM_STUB_CALL); return gasm_->Call(call_descriptor, call_target, address, inputs[1], inputs[2]); } default: FATAL_UNSUPPORTED_OPCODE(opcode); } } Node* WasmGraphBuilder::AtomicFence() { return SetEffect(graph()->NewNode(mcgraph()->machine()->MemBarrier(), effect(), control())); } Node* WasmGraphBuilder::MemoryInit(uint32_t data_segment_index, Node* dst, Node* src, Node* size, wasm::WasmCodePosition position) { // The data segment index must be in bounds since it is required by // validation. DCHECK_LT(data_segment_index, env_->module->num_declared_data_segments); Node* function = graph()->NewNode(mcgraph()->common()->ExternalConstant( ExternalReference::wasm_memory_init())); Node* stack_slot = StoreArgsInStackSlot( {{MachineType::PointerRepresentation(), instance_node_.get()}, {MachineRepresentation::kWord32, dst}, {MachineRepresentation::kWord32, src}, {MachineRepresentation::kWord32, gasm_->Uint32Constant(data_segment_index)}, {MachineRepresentation::kWord32, size}}); MachineType sig_types[] = {MachineType::Int32(), MachineType::Pointer()}; MachineSignature sig(1, 1, sig_types); Node* call = SetEffect(BuildCCall(&sig, function, stack_slot)); return TrapIfFalse(wasm::kTrapMemOutOfBounds, call, position); } Node* WasmGraphBuilder::DataDrop(uint32_t data_segment_index, wasm::WasmCodePosition position) { DCHECK_LT(data_segment_index, env_->module->num_declared_data_segments); Node* seg_size_array = LOAD_INSTANCE_FIELD(DataSegmentSizes, MachineType::Pointer()); STATIC_ASSERT(wasm::kV8MaxWasmDataSegments <= kMaxUInt32 >> 2); const Operator* store_op = mcgraph()->machine()->Store( StoreRepresentation(MachineRepresentation::kWord32, kNoWriteBarrier)); return SetEffect( graph()->NewNode(store_op, seg_size_array, mcgraph()->IntPtrConstant(data_segment_index << 2), mcgraph()->Int32Constant(0), effect(), control())); } Node* WasmGraphBuilder::StoreArgsInStackSlot( std::initializer_list<std::pair<MachineRepresentation, Node*>> args) { int slot_size = 0; for (auto arg : args) { slot_size += ElementSizeInBytes(arg.first); } DCHECK_LT(0, slot_size); Node* stack_slot = graph()->NewNode(mcgraph()->machine()->StackSlot(slot_size)); int offset = 0; for (auto arg : args) { MachineRepresentation type = arg.first; Node* value = arg.second; gasm_->Store(StoreRepresentation(type, kNoWriteBarrier), stack_slot, mcgraph()->Int32Constant(offset), value); offset += ElementSizeInBytes(type); } return stack_slot; } Node* WasmGraphBuilder::MemoryCopy(Node* dst, Node* src, Node* size, wasm::WasmCodePosition position) { Node* function = graph()->NewNode(mcgraph()->common()->ExternalConstant( ExternalReference::wasm_memory_copy())); Node* stack_slot = StoreArgsInStackSlot( {{MachineType::PointerRepresentation(), instance_node_.get()}, {MachineRepresentation::kWord32, dst}, {MachineRepresentation::kWord32, src}, {MachineRepresentation::kWord32, size}}); MachineType sig_types[] = {MachineType::Int32(), MachineType::Pointer()}; MachineSignature sig(1, 1, sig_types); Node* call = SetEffect(BuildCCall(&sig, function, stack_slot)); return TrapIfFalse(wasm::kTrapMemOutOfBounds, call, position); } Node* WasmGraphBuilder::MemoryFill(Node* dst, Node* value, Node* size, wasm::WasmCodePosition position) { Node* function = graph()->NewNode(mcgraph()->common()->ExternalConstant( ExternalReference::wasm_memory_fill())); Node* stack_slot = StoreArgsInStackSlot( {{MachineType::PointerRepresentation(), instance_node_.get()}, {MachineRepresentation::kWord32, dst}, {MachineRepresentation::kWord32, value}, {MachineRepresentation::kWord32, size}}); MachineType sig_types[] = {MachineType::Int32(), MachineType::Pointer()}; MachineSignature sig(1, 1, sig_types); Node* call = SetEffect(BuildCCall(&sig, function, stack_slot)); return TrapIfFalse(wasm::kTrapMemOutOfBounds, call, position); } Node* WasmGraphBuilder::TableInit(uint32_t table_index, uint32_t elem_segment_index, Node* dst, Node* src, Node* size, wasm::WasmCodePosition position) { auto call_descriptor = GetBuiltinCallDescriptor<WasmTableInitDescriptor>( this, StubCallMode::kCallWasmRuntimeStub); intptr_t target = wasm::WasmCode::kWasmTableInit; Node* call_target = mcgraph()->RelocatableIntPtrConstant(target, RelocInfo::WASM_STUB_CALL); return gasm_->Call( call_descriptor, call_target, dst, src, size, graph()->NewNode(mcgraph()->common()->NumberConstant(table_index)), graph()->NewNode( mcgraph()->common()->NumberConstant(elem_segment_index))); } Node* WasmGraphBuilder::ElemDrop(uint32_t elem_segment_index, wasm::WasmCodePosition position) { // The elem segment index must be in bounds since it is required by // validation. DCHECK_LT(elem_segment_index, env_->module->elem_segments.size()); Node* dropped_elem_segments = LOAD_INSTANCE_FIELD(DroppedElemSegments, MachineType::Pointer()); const Operator* store_op = mcgraph()->machine()->Store( StoreRepresentation(MachineRepresentation::kWord8, kNoWriteBarrier)); return SetEffect( graph()->NewNode(store_op, dropped_elem_segments, mcgraph()->IntPtrConstant(elem_segment_index), mcgraph()->Int32Constant(1), effect(), control())); } Node* WasmGraphBuilder::TableCopy(uint32_t table_dst_index, uint32_t table_src_index, Node* dst, Node* src, Node* size, wasm::WasmCodePosition position) { auto call_descriptor = GetBuiltinCallDescriptor<WasmTableCopyDescriptor>( this, StubCallMode::kCallWasmRuntimeStub); intptr_t target = wasm::WasmCode::kWasmTableCopy; Node* call_target = mcgraph()->RelocatableIntPtrConstant(target, RelocInfo::WASM_STUB_CALL); return gasm_->Call( call_descriptor, call_target, dst, src, size, graph()->NewNode(mcgraph()->common()->NumberConstant(table_dst_index)), graph()->NewNode(mcgraph()->common()->NumberConstant(table_src_index))); } Node* WasmGraphBuilder::TableGrow(uint32_t table_index, Node* value, Node* delta) { Node* args[] = { graph()->NewNode(mcgraph()->common()->NumberConstant(table_index)), value, BuildConvertUint32ToSmiWithSaturation(delta, FLAG_wasm_max_table_size)}; Node* result = BuildCallToRuntime(Runtime::kWasmTableGrow, args, arraysize(args)); return BuildChangeSmiToInt32(result); } Node* WasmGraphBuilder::TableSize(uint32_t table_index) { Node* tables = LOAD_INSTANCE_FIELD(Tables, MachineType::TaggedPointer()); Node* table = LOAD_FIXED_ARRAY_SLOT_ANY(tables, table_index); int length_field_size = WasmTableObject::kCurrentLengthOffsetEnd - WasmTableObject::kCurrentLengthOffset + 1; Node* length_smi = gasm_->Load( assert_size(length_field_size, MachineType::TaggedSigned()), table, wasm::ObjectAccess::ToTagged(WasmTableObject::kCurrentLengthOffset)); return BuildChangeSmiToInt32(length_smi); } Node* WasmGraphBuilder::TableFill(uint32_t table_index, Node* start, Node* value, Node* count) { Node* args[] = { graph()->NewNode(mcgraph()->common()->NumberConstant(table_index)), BuildConvertUint32ToSmiWithSaturation(start, FLAG_wasm_max_table_size), value, BuildConvertUint32ToSmiWithSaturation(count, FLAG_wasm_max_table_size)}; return BuildCallToRuntime(Runtime::kWasmTableFill, args, arraysize(args)); } namespace { MachineType FieldType(const wasm::StructType* type, uint32_t field_index, bool is_signed) { return MachineType::TypeForRepresentation( type->field(field_index).machine_representation(), is_signed); } Node* FieldOffset(MachineGraph* graph, const wasm::StructType* type, uint32_t field_index) { int offset = WasmStruct::kHeaderSize + type->field_offset(field_index) - kHeapObjectTag; return graph->IntPtrConstant(offset); } // It's guaranteed that struct/array fields are aligned to min(field_size, // kTaggedSize), with the latter being 4 or 8 depending on platform and // pointer compression. So on our most common configurations, 8-byte types // must use unaligned loads/stores. Node* LoadWithTaggedAlignment(WasmGraphAssembler* gasm, MachineType type, Node* base, Node* offset) { if (ElementSizeInBytes(type.representation()) > kTaggedSize) { return gasm->LoadUnaligned(type, base, offset); } else { return gasm->Load(type, base, offset); } } // Same alignment considerations as above. Node* StoreWithTaggedAlignment(WasmGraphAssembler* gasm, Node* base, Node* offset, Node* value, wasm::ValueType type) { MachineRepresentation rep = type.machine_representation(); if (ElementSizeInBytes(rep) > kTaggedSize) { return gasm->StoreUnaligned(rep, base, offset, value); } else { WriteBarrierKind write_barrier = type.is_reference_type() ? kPointerWriteBarrier : kNoWriteBarrier; StoreRepresentation store_rep(rep, write_barrier); return gasm->Store(store_rep, base, offset, value); } } // Set a field of a struct, without checking if the struct is null. // Helper method for StructNewWithRtt and StructSet. Node* StoreStructFieldUnchecked(MachineGraph* graph, WasmGraphAssembler* gasm, Node* struct_object, const wasm::StructType* type, uint32_t field_index, Node* value) { return StoreWithTaggedAlignment(gasm, struct_object, FieldOffset(graph, type, field_index), value, type->field(field_index)); } Node* ArrayElementOffset(GraphAssembler* gasm, Node* index, wasm::ValueType element_type) { return gasm->Int32Add( gasm->Int32Constant(WasmArray::kHeaderSize - kHeapObjectTag), gasm->Int32Mul(index, gasm->Int32Constant(element_type.element_size_bytes()))); } Node* ArrayLength(GraphAssembler* gasm, Node* array) { return gasm->Load( MachineType::Uint32(), array, gasm->Int32Constant(WasmArray::kLengthOffset - kHeapObjectTag)); } } // namespace Node* WasmGraphBuilder::StructNewWithRtt(uint32_t struct_index, const wasm::StructType* type, Node* rtt, Vector<Node*> fields) { Node* s = CALL_BUILTIN( WasmAllocateStructWithRtt, rtt, LOAD_INSTANCE_FIELD(NativeContext, MachineType::TaggedPointer())); for (uint32_t i = 0; i < type->field_count(); i++) { StoreStructFieldUnchecked(mcgraph(), gasm_.get(), s, type, i, fields[i]); } return s; } Node* WasmGraphBuilder::ArrayNewWithRtt(uint32_t array_index, const wasm::ArrayType* type, Node* length, Node* initial_value, Node* rtt) { wasm::ValueType element_type = type->element_type(); Node* a = CALL_BUILTIN( WasmAllocateArrayWithRtt, rtt, BuildChangeUint31ToSmi(length), graph()->NewNode(mcgraph()->common()->NumberConstant( element_type.element_size_bytes())), LOAD_INSTANCE_FIELD(NativeContext, MachineType::TaggedPointer())); auto loop = gasm_->MakeLoopLabel(MachineRepresentation::kWord32); auto done = gasm_->MakeLabel(); Node* start_offset = gasm_->Int32Constant(WasmArray::kHeaderSize - kHeapObjectTag); Node* element_size = gasm_->Int32Constant(element_type.element_size_bytes()); Node* end_offset = gasm_->Int32Add(start_offset, gasm_->Int32Mul(element_size, length)); // "Goto" requires the graph's end to have been set up. // TODO(jkummerow): Figure out if there's a more elegant solution. Graph* g = mcgraph()->graph(); if (!g->end()) { g->SetEnd(g->NewNode(mcgraph()->common()->End(0))); } gasm_->Goto(&loop, start_offset); gasm_->Bind(&loop); { Node* offset = loop.PhiAt(0); Node* check = gasm_->Uint32LessThan(offset, end_offset); gasm_->GotoIfNot(check, &done); StoreWithTaggedAlignment(gasm_.get(), a, offset, initial_value, type->element_type()); offset = gasm_->Int32Add(offset, element_size); gasm_->Goto(&loop, offset); } gasm_->Bind(&done); return a; } Node* WasmGraphBuilder::RttCanon(wasm::HeapType type) { if (type.is_generic()) { switch (type.representation()) { case wasm::HeapType::kEq: return LOAD_FULL_POINTER( BuildLoadIsolateRoot(), IsolateData::root_slot_offset(RootIndex::kWasmRttEqrefMap)); case wasm::HeapType::kExtern: return LOAD_FULL_POINTER( BuildLoadIsolateRoot(), IsolateData::root_slot_offset(RootIndex::kWasmRttExternrefMap)); case wasm::HeapType::kFunc: return LOAD_FULL_POINTER( BuildLoadIsolateRoot(), IsolateData::root_slot_offset(RootIndex::kWasmRttFuncrefMap)); case wasm::HeapType::kI31: return LOAD_FULL_POINTER( BuildLoadIsolateRoot(), IsolateData::root_slot_offset(RootIndex::kWasmRttI31refMap)); default: UNREACHABLE(); } } Node* maps_list = LOAD_INSTANCE_FIELD(ManagedObjectMaps, MachineType::TaggedPointer()); return LOAD_FIXED_ARRAY_SLOT_PTR(maps_list, type.ref_index()); } Node* WasmGraphBuilder::RttSub(wasm::HeapType type, Node* parent_rtt) { return CALL_BUILTIN( WasmAllocateRtt, graph()->NewNode( mcgraph()->common()->NumberConstant(type.representation())), parent_rtt, LOAD_INSTANCE_FIELD(NativeContext, MachineType::TaggedPointer())); } Node* IsI31(GraphAssembler* gasm, Node* object) { if (COMPRESS_POINTERS_BOOL) { return gasm->Word32Equal( gasm->Word32And(object, gasm->Int32Constant(kSmiTagMask)), gasm->Int32Constant(kSmiTag)); } else { return gasm->WordEqual( gasm->WordAnd(object, gasm->IntPtrConstant(kSmiTagMask)), gasm->IntPtrConstant(kSmiTag)); } } void AssertFalse(MachineGraph* mcgraph, GraphAssembler* gasm, Node* condition) { #if DEBUG if (FLAG_debug_code) { auto ok = gasm->MakeLabel(); gasm->GotoIfNot(condition, &ok); EnsureEnd(mcgraph); gasm->Unreachable(); gasm->Bind(&ok); } #endif } Node* WasmGraphBuilder::RefTest(Node* object, Node* rtt, CheckForNull null_check, CheckForI31 i31_check, RttIsI31 rtt_is_i31) { auto done = gasm_->MakeLabel(MachineRepresentation::kWord32); bool need_done_label = false; if (i31_check == kWithI31Check) { if (rtt_is_i31 == kRttIsI31) { return IsI31(gasm_.get(), object); } gasm_->GotoIf(IsI31(gasm_.get(), object), &done, gasm_->Int32Constant(0)); need_done_label = true; } else { AssertFalse(mcgraph(), gasm_.get(), IsI31(gasm_.get(), object)); } if (null_check == kWithNullCheck) { gasm_->GotoIf(gasm_->WordEqual(object, RefNull()), &done, gasm_->Int32Constant(0)); need_done_label = true; } Node* map = gasm_->Load(MachineType::TaggedPointer(), object, HeapObject::kMapOffset - kHeapObjectTag); // TODO(7748): Add a fast path for map == rtt. Node* subtype_check = BuildChangeSmiToInt32(CALL_BUILTIN( WasmIsRttSubtype, map, rtt, LOAD_INSTANCE_FIELD(NativeContext, MachineType::TaggedPointer()))); if (need_done_label) { gasm_->Goto(&done, subtype_check); gasm_->Bind(&done); subtype_check = done.PhiAt(0); } return subtype_check; } Node* WasmGraphBuilder::RefCast(Node* object, Node* rtt, CheckForNull null_check, CheckForI31 i31_check, RttIsI31 rtt_is_i31, wasm::WasmCodePosition position) { if (i31_check == kWithI31Check) { if (rtt_is_i31 == kRttIsI31) { TrapIfFalse(wasm::kTrapIllegalCast, IsI31(gasm_.get(), object), position); return object; } else { TrapIfTrue(wasm::kTrapIllegalCast, IsI31(gasm_.get(), object), position); } } else { AssertFalse(mcgraph(), gasm_.get(), IsI31(gasm_.get(), object)); } if (null_check == kWithNullCheck) { TrapIfTrue(wasm::kTrapIllegalCast, gasm_->WordEqual(object, RefNull()), position); } Node* map = gasm_->Load(MachineType::TaggedPointer(), object, HeapObject::kMapOffset - kHeapObjectTag); // TODO(7748): Add a fast path for map == rtt. Node* check_result = BuildChangeSmiToInt32(CALL_BUILTIN( WasmIsRttSubtype, map, rtt, LOAD_INSTANCE_FIELD(NativeContext, MachineType::TaggedPointer()))); TrapIfFalse(wasm::kTrapIllegalCast, check_result, position); return object; } Node* WasmGraphBuilder::BrOnCast(Node* object, Node* rtt, CheckForNull null_check, CheckForI31 i31_check, RttIsI31 rtt_is_i31, Node** match_control, Node** match_effect, Node** no_match_control, Node** no_match_effect) { // We have up to 3 control nodes to merge; the EffectPhi needs an additional // input. base::SmallVector<Node*, 3> merge_controls; base::SmallVector<Node*, 4> merge_effects; Node* is_i31 = IsI31(gasm_.get(), object); if (i31_check == kWithI31Check) { if (rtt_is_i31 == kRttIsI31) { BranchExpectFalse(is_i31, match_control, no_match_control); return nullptr; } else { Node* i31_branch = graph()->NewNode( mcgraph()->common()->Branch(BranchHint::kFalse), is_i31, control()); SetControl(graph()->NewNode(mcgraph()->common()->IfFalse(), i31_branch)); merge_controls.emplace_back( graph()->NewNode(mcgraph()->common()->IfTrue(), i31_branch)); merge_effects.emplace_back(effect()); } } else { AssertFalse(mcgraph(), gasm_.get(), is_i31); } if (null_check == kWithNullCheck) { Node* null_branch = graph()->NewNode(mcgraph()->common()->Branch(BranchHint::kFalse), gasm_->WordEqual(object, RefNull()), control()); SetControl(graph()->NewNode(mcgraph()->common()->IfFalse(), null_branch)); merge_controls.emplace_back( graph()->NewNode(mcgraph()->common()->IfTrue(), null_branch)); merge_effects.emplace_back(effect()); } // At this point, {object} is neither null nor an i31ref/Smi. Node* map = gasm_->Load(MachineType::TaggedPointer(), object, HeapObject::kMapOffset - kHeapObjectTag); // TODO(7748): Add a fast path for map == rtt. Node* subtype_check = BuildChangeSmiToInt32(CALL_BUILTIN( WasmIsRttSubtype, map, rtt, LOAD_INSTANCE_FIELD(NativeContext, MachineType::TaggedPointer()))); Node* cast_branch = graph()->NewNode(mcgraph()->common()->Branch(BranchHint::kFalse), subtype_check, control()); *match_control = graph()->NewNode(mcgraph()->common()->IfTrue(), cast_branch); *match_effect = effect(); Node* not_subtype = graph()->NewNode(mcgraph()->common()->IfFalse(), cast_branch); // Wire up the "cast attempt was unsuccessful" control nodes: merge them if // there is more than one. if (merge_controls.size() > 0) { merge_controls.emplace_back(not_subtype); merge_effects.emplace_back(effect()); // Range is 1..3, so casting to int is safe. DCHECK_EQ(merge_controls.size(), merge_effects.size()); unsigned count = static_cast<unsigned>(merge_controls.size()); *no_match_control = Merge(count, merge_controls.data()); // EffectPhis need their control dependency as an additional input. merge_effects.emplace_back(*no_match_control); *no_match_effect = EffectPhi(count, merge_effects.data()); } else { *no_match_control = not_subtype; *no_match_effect = effect(); } // Return value is not used, but we need it for compatibility // with graph-builder-interface. return nullptr; } Node* WasmGraphBuilder::StructGet(Node* struct_object, const wasm::StructType* struct_type, uint32_t field_index, CheckForNull null_check, bool is_signed, wasm::WasmCodePosition position) { if (null_check == kWithNullCheck) { TrapIfTrue(wasm::kTrapNullDereference, gasm_->WordEqual(struct_object, RefNull()), position); } MachineType machine_type = FieldType(struct_type, field_index, is_signed); Node* offset = FieldOffset(mcgraph(), struct_type, field_index); return LoadWithTaggedAlignment(gasm_.get(), machine_type, struct_object, offset); } Node* WasmGraphBuilder::StructSet(Node* struct_object, const wasm::StructType* struct_type, uint32_t field_index, Node* field_value, CheckForNull null_check, wasm::WasmCodePosition position) { if (null_check == kWithNullCheck) { TrapIfTrue(wasm::kTrapNullDereference, gasm_->WordEqual(struct_object, RefNull()), position); } return StoreStructFieldUnchecked(mcgraph(), gasm_.get(), struct_object, struct_type, field_index, field_value); } void WasmGraphBuilder::BoundsCheck(Node* array, Node* index, wasm::WasmCodePosition position) { Node* length = ArrayLength(gasm_.get(), array); TrapIfFalse(wasm::kTrapArrayOutOfBounds, gasm_->Uint32LessThan(index, length), position); } Node* WasmGraphBuilder::ArrayGet(Node* array_object, const wasm::ArrayType* type, Node* index, CheckForNull null_check, bool is_signed, wasm::WasmCodePosition position) { if (null_check == kWithNullCheck) { TrapIfTrue(wasm::kTrapNullDereference, gasm_->WordEqual(array_object, RefNull()), position); } BoundsCheck(array_object, index, position); MachineType machine_type = MachineType::TypeForRepresentation( type->element_type().machine_representation(), is_signed); Node* offset = ArrayElementOffset(gasm_.get(), index, type->element_type()); return LoadWithTaggedAlignment(gasm_.get(), machine_type, array_object, offset); } Node* WasmGraphBuilder::ArraySet(Node* array_object, const wasm::ArrayType* type, Node* index, Node* value, CheckForNull null_check, wasm::WasmCodePosition position) { if (null_check == kWithNullCheck) { TrapIfTrue(wasm::kTrapNullDereference, gasm_->WordEqual(array_object, RefNull()), position); } BoundsCheck(array_object, index, position); Node* offset = ArrayElementOffset(gasm_.get(), index, type->element_type()); return StoreWithTaggedAlignment(gasm_.get(), array_object, offset, value, type->element_type()); } Node* WasmGraphBuilder::ArrayLen(Node* array_object, wasm::WasmCodePosition position) { TrapIfTrue(wasm::kTrapNullDereference, gasm_->WordEqual(array_object, RefNull()), position); return ArrayLength(gasm_.get(), array_object); } // 1 bit V8 Smi tag, 31 bits V8 Smi shift, 1 bit i31ref high-bit truncation. constexpr int kI31To32BitSmiShift = 33; Node* WasmGraphBuilder::I31New(Node* input) { if (SmiValuesAre31Bits()) { return gasm_->Word32Shl(input, BuildSmiShiftBitsConstant32()); } DCHECK(SmiValuesAre32Bits()); input = BuildChangeInt32ToIntPtr(input); return gasm_->WordShl(input, gasm_->IntPtrConstant(kI31To32BitSmiShift)); } Node* WasmGraphBuilder::I31GetS(Node* input) { if (SmiValuesAre31Bits()) { input = BuildTruncateIntPtrToInt32(input); return gasm_->Word32SarShiftOutZeros(input, BuildSmiShiftBitsConstant32()); } DCHECK(SmiValuesAre32Bits()); return BuildTruncateIntPtrToInt32( gasm_->WordSar(input, gasm_->IntPtrConstant(kI31To32BitSmiShift))); } Node* WasmGraphBuilder::I31GetU(Node* input) { if (SmiValuesAre31Bits()) { input = BuildTruncateIntPtrToInt32(input); return gasm_->Word32Shr(input, BuildSmiShiftBitsConstant32()); } DCHECK(SmiValuesAre32Bits()); return BuildTruncateIntPtrToInt32( gasm_->WordShr(input, gasm_->IntPtrConstant(kI31To32BitSmiShift))); } class WasmDecorator final : public GraphDecorator { public: explicit WasmDecorator(NodeOriginTable* origins, wasm::Decoder* decoder) : origins_(origins), decoder_(decoder) {} void Decorate(Node* node) final { origins_->SetNodeOrigin( node, NodeOrigin("wasm graph creation", "n/a", NodeOrigin::kWasmBytecode, decoder_->position())); } private: compiler::NodeOriginTable* origins_; wasm::Decoder* decoder_; }; void WasmGraphBuilder::AddBytecodePositionDecorator( NodeOriginTable* node_origins, wasm::Decoder* decoder) { DCHECK_NULL(decorator_); decorator_ = graph()->zone()->New<WasmDecorator>(node_origins, decoder); graph()->AddDecorator(decorator_); } void WasmGraphBuilder::RemoveBytecodePositionDecorator() { DCHECK_NOT_NULL(decorator_); graph()->RemoveDecorator(decorator_); decorator_ = nullptr; } namespace { class WasmWrapperGraphBuilder : public WasmGraphBuilder { public: WasmWrapperGraphBuilder(Zone* zone, MachineGraph* mcgraph, const wasm::FunctionSig* sig, const wasm::WasmModule* module, compiler::SourcePositionTable* spt, StubCallMode stub_mode, wasm::WasmFeatures features) : WasmGraphBuilder(nullptr, zone, mcgraph, sig, spt), module_(module), stub_mode_(stub_mode), enabled_features_(features) {} CallDescriptor* GetI64ToBigIntCallDescriptor() { if (i64_to_bigint_descriptor_) return i64_to_bigint_descriptor_; i64_to_bigint_descriptor_ = GetBuiltinCallDescriptor<I64ToBigIntDescriptor>(this, stub_mode_); AddInt64LoweringReplacement( i64_to_bigint_descriptor_, GetBuiltinCallDescriptor<I32PairToBigIntDescriptor>(this, stub_mode_)); return i64_to_bigint_descriptor_; } CallDescriptor* GetBigIntToI64CallDescriptor() { if (bigint_to_i64_descriptor_) return bigint_to_i64_descriptor_; bigint_to_i64_descriptor_ = GetBuiltinCallDescriptor<BigIntToI64Descriptor>(this, stub_mode_); AddInt64LoweringReplacement( bigint_to_i64_descriptor_, GetBuiltinCallDescriptor<BigIntToI32PairDescriptor>(this, stub_mode_)); return bigint_to_i64_descriptor_; } Node* GetTargetForBuiltinCall(wasm::WasmCode::RuntimeStubId wasm_stub, Builtins::Name builtin_id) { return (stub_mode_ == StubCallMode::kCallWasmRuntimeStub) ? mcgraph()->RelocatableIntPtrConstant(wasm_stub, RelocInfo::WASM_STUB_CALL) : GetBuiltinPointerTarget(builtin_id); } Node* BuildLoadUndefinedValueFromInstance() { if (undefined_value_node_ == nullptr) { Node* isolate_root = graph()->NewNode( mcgraph()->machine()->Load(MachineType::Pointer()), instance_node_.get(), mcgraph()->Int32Constant(WASM_INSTANCE_OBJECT_OFFSET(IsolateRoot)), graph()->start(), graph()->start()); undefined_value_node_ = graph()->NewNode( mcgraph()->machine()->Load(MachineType::Pointer()), isolate_root, mcgraph()->Int32Constant( IsolateData::root_slot_offset(RootIndex::kUndefinedValue)), isolate_root, graph()->start()); } return undefined_value_node_.get(); } Node* BuildChangeInt32ToNumber(Node* value) { // We expect most integers at runtime to be Smis, so it is important for // wrapper performance that Smi conversion be inlined. if (SmiValuesAre32Bits()) { return BuildChangeInt32ToSmi(value); } DCHECK(SmiValuesAre31Bits()); auto builtin = gasm_->MakeDeferredLabel(); auto done = gasm_->MakeLabel(MachineRepresentation::kTagged); // Double value to test if value can be a Smi, and if so, to convert it. Node* add = gasm_->Int32AddWithOverflow(value, value); Node* ovf = gasm_->Projection(1, add); gasm_->GotoIf(ovf, &builtin); // If it didn't overflow, the result is {2 * value} as pointer-sized value. Node* smi_tagged = BuildChangeInt32ToIntPtr(gasm_->Projection(0, add)); gasm_->Goto(&done, smi_tagged); // Otherwise, call builtin, to convert to a HeapNumber. gasm_->Bind(&builtin); CommonOperatorBuilder* common = mcgraph()->common(); Node* target = GetTargetForBuiltinCall(wasm::WasmCode::kWasmInt32ToHeapNumber, Builtins::kWasmInt32ToHeapNumber); if (!int32_to_heapnumber_operator_.is_set()) { auto call_descriptor = Linkage::GetStubCallDescriptor( mcgraph()->zone(), WasmInt32ToHeapNumberDescriptor(), 0, CallDescriptor::kNoFlags, Operator::kNoProperties, stub_mode_); int32_to_heapnumber_operator_.set(common->Call(call_descriptor)); } Node* call = gasm_->Call(int32_to_heapnumber_operator_.get(), target, value); gasm_->Goto(&done, call); gasm_->Bind(&done); return done.PhiAt(0); } Node* BuildChangeTaggedToInt32(Node* value, Node* context) { // We expect most integers at runtime to be Smis, so it is important for // wrapper performance that Smi conversion be inlined. auto builtin = gasm_->MakeDeferredLabel(); auto done = gasm_->MakeLabel(MachineRepresentation::kWord32); // Test if value is a Smi. Node* is_smi = gasm_->Word32Equal(gasm_->Word32And(BuildTruncateIntPtrToInt32(value), gasm_->Int32Constant(kSmiTagMask)), gasm_->Int32Constant(0)); gasm_->GotoIfNot(is_smi, &builtin); // If Smi, convert to int32. Node* smi = BuildChangeSmiToInt32(value); gasm_->Goto(&done, smi); // Otherwise, call builtin which changes non-Smi to Int32. gasm_->Bind(&builtin); CommonOperatorBuilder* common = mcgraph()->common(); Node* target = GetTargetForBuiltinCall(wasm::WasmCode::kWasmTaggedNonSmiToInt32, Builtins::kWasmTaggedNonSmiToInt32); if (!tagged_non_smi_to_int32_operator_.is_set()) { auto call_descriptor = Linkage::GetStubCallDescriptor( mcgraph()->zone(), WasmTaggedNonSmiToInt32Descriptor(), 0, CallDescriptor::kNoFlags, Operator::kNoProperties, stub_mode_); tagged_non_smi_to_int32_operator_.set(common->Call(call_descriptor)); } Node* call = gasm_->Call(tagged_non_smi_to_int32_operator_.get(), target, value, context); SetSourcePosition(call, 1); gasm_->Goto(&done, call); gasm_->Bind(&done); return done.PhiAt(0); } Node* BuildChangeFloat32ToNumber(Node* value) { CommonOperatorBuilder* common = mcgraph()->common(); Node* target = GetTargetForBuiltinCall(wasm::WasmCode::kWasmFloat32ToNumber, Builtins::kWasmFloat32ToNumber); if (!float32_to_number_operator_.is_set()) { auto call_descriptor = Linkage::GetStubCallDescriptor( mcgraph()->zone(), WasmFloat32ToNumberDescriptor(), 0, CallDescriptor::kNoFlags, Operator::kNoProperties, stub_mode_); float32_to_number_operator_.set(common->Call(call_descriptor)); } return gasm_->Call(float32_to_number_operator_.get(), target, value); } Node* BuildChangeFloat64ToNumber(Node* value) { CommonOperatorBuilder* common = mcgraph()->common(); Node* target = GetTargetForBuiltinCall(wasm::WasmCode::kWasmFloat64ToNumber, Builtins::kWasmFloat64ToNumber); if (!float64_to_number_operator_.is_set()) { auto call_descriptor = Linkage::GetStubCallDescriptor( mcgraph()->zone(), WasmFloat64ToNumberDescriptor(), 0, CallDescriptor::kNoFlags, Operator::kNoProperties, stub_mode_); float64_to_number_operator_.set(common->Call(call_descriptor)); } return gasm_->Call(float64_to_number_operator_.get(), target, value); } Node* BuildChangeTaggedToFloat64(Node* value, Node* context) { CommonOperatorBuilder* common = mcgraph()->common(); Node* target = GetTargetForBuiltinCall(wasm::WasmCode::kWasmTaggedToFloat64, Builtins::kWasmTaggedToFloat64); if (!tagged_to_float64_operator_.is_set()) { auto call_descriptor = Linkage::GetStubCallDescriptor( mcgraph()->zone(), WasmTaggedToFloat64Descriptor(), 0, CallDescriptor::kNoFlags, Operator::kNoProperties, stub_mode_); tagged_to_float64_operator_.set(common->Call(call_descriptor)); } Node* call = gasm_->Call(tagged_to_float64_operator_.get(), target, value, context); SetSourcePosition(call, 1); return call; } int AddArgumentNodes(Vector<Node*> args, int pos, int param_count, const wasm::FunctionSig* sig) { // Convert wasm numbers to JS values. for (int i = 0; i < param_count; ++i) { Node* param = Param(i + 1); // Start from index 1 to drop the instance_node. args[pos++] = ToJS(param, sig->GetParam(i)); } return pos; } Node* ToJS(Node* node, wasm::ValueType type) { switch (type.kind()) { case wasm::ValueType::kI32: return BuildChangeInt32ToNumber(node); case wasm::ValueType::kS128: UNREACHABLE(); case wasm::ValueType::kI64: { DCHECK(enabled_features_.has_bigint()); return BuildChangeInt64ToBigInt(node); } case wasm::ValueType::kF32: return BuildChangeFloat32ToNumber(node); case wasm::ValueType::kF64: return BuildChangeFloat64ToNumber(node); case wasm::ValueType::kRef: case wasm::ValueType::kOptRef: { uint32_t representation = type.heap_representation(); if (representation == wasm::HeapType::kExtern || representation == wasm::HeapType::kExn || representation == wasm::HeapType::kFunc) { return node; } if (representation == wasm::HeapType::kEq) { return BuildAllocateObjectWrapper(node); } if (type.has_index() && module_->has_signature(type.ref_index())) { // Typed function return node; } // TODO(7748): Figure out a JS interop story for arrays and structs. // If this is reached, then IsJSCompatibleSignature() is too permissive. UNREACHABLE(); } case wasm::ValueType::kRtt: // TODO(7748): Figure out what to do for RTTs. UNIMPLEMENTED(); case wasm::ValueType::kI8: case wasm::ValueType::kI16: case wasm::ValueType::kStmt: case wasm::ValueType::kBottom: UNREACHABLE(); } } // TODO(7748): Temporary solution to allow round-tripping of Wasm objects // through JavaScript, where they show up as opaque boxes. This will disappear // once we have a proper WasmGC <-> JS interaction story. Node* BuildAllocateObjectWrapper(Node* input) { return CALL_BUILTIN( WasmAllocateObjectWrapper, input, LOAD_INSTANCE_FIELD(NativeContext, MachineType::TaggedPointer())); } Node* BuildUnpackObjectWrapper(Node* input) { Node* obj = CALL_BUILTIN( WasmGetOwnProperty, input, LOAD_FULL_POINTER(BuildLoadIsolateRoot(), IsolateData::root_slot_offset( RootIndex::kwasm_wrapped_object_symbol)), LOAD_INSTANCE_FIELD(NativeContext, MachineType::TaggedPointer())); // Invalid object wrappers (i.e. any other JS object that doesn't have the // magic hidden property) will return {undefined}. Map that to {null}. Node* undefined = LOAD_FULL_POINTER( BuildLoadIsolateRoot(), IsolateData::root_slot_offset(RootIndex::kUndefinedValue)); Node* is_undefined = gasm_->WordEqual(obj, undefined); Diamond check(graph(), mcgraph()->common(), is_undefined, BranchHint::kFalse); check.Chain(control()); return check.Phi(MachineRepresentation::kTagged, RefNull(), obj); } Node* BuildChangeInt64ToBigInt(Node* input) { const Operator* call = mcgraph()->common()->Call(GetI64ToBigIntCallDescriptor()); Node* target; if (mcgraph()->machine()->Is64()) { target = GetTargetForBuiltinCall(wasm::WasmCode::kI64ToBigInt, Builtins::kI64ToBigInt); } else { DCHECK(mcgraph()->machine()->Is32()); // On 32-bit platforms we already set the target to the // I32PairToBigInt builtin here, so that we don't have to replace the // target in the int64-lowering. target = GetTargetForBuiltinCall(wasm::WasmCode::kI32PairToBigInt, Builtins::kI32PairToBigInt); } return SetEffectControl( graph()->NewNode(call, target, input, effect(), control())); } Node* BuildChangeBigIntToInt64(Node* input, Node* context) { const Operator* call = mcgraph()->common()->Call(GetBigIntToI64CallDescriptor()); Node* target; if (mcgraph()->machine()->Is64()) { target = GetTargetForBuiltinCall(wasm::WasmCode::kBigIntToI64, Builtins::kBigIntToI64); } else { DCHECK(mcgraph()->machine()->Is32()); // On 32-bit platforms we already set the target to the // BigIntToI32Pair builtin here, so that we don't have to replace the // target in the int64-lowering. target = GetTargetForBuiltinCall(wasm::WasmCode::kBigIntToI32Pair, Builtins::kBigIntToI32Pair); } return SetEffectControl( graph()->NewNode(call, target, input, context, effect(), control())); } void BuildCheckValidRefValue(Node* input, Node* js_context, wasm::ValueType type) { // Make sure ValueType fits in a Smi. STATIC_ASSERT(wasm::ValueType::kLastUsedBit + 1 <= kSmiValueSize); Node* inputs[] = {instance_node_.get(), input, mcgraph()->IntPtrConstant( IntToSmi(static_cast<int>(type.raw_bit_field())))}; Node* check = BuildChangeSmiToInt32(SetEffect(BuildCallToRuntimeWithContext( Runtime::kWasmIsValidRefValue, js_context, inputs, 3))); Diamond type_check(graph(), mcgraph()->common(), check, BranchHint::kTrue); type_check.Chain(control()); SetControl(type_check.if_false); Node* old_effect = effect(); BuildCallToRuntimeWithContext(Runtime::kWasmThrowTypeError, js_context, nullptr, 0); SetEffectControl(type_check.EffectPhi(old_effect, effect()), type_check.merge); } Node* FromJS(Node* input, Node* js_context, wasm::ValueType type) { switch (type.kind()) { case wasm::ValueType::kRef: case wasm::ValueType::kOptRef: { switch (type.heap_representation()) { case wasm::HeapType::kExtern: case wasm::HeapType::kExn: return input; case wasm::HeapType::kFunc: BuildCheckValidRefValue(input, js_context, type); return input; case wasm::HeapType::kEq: BuildCheckValidRefValue(input, js_context, type); return BuildUnpackObjectWrapper(input); case wasm::HeapType::kI31: // If this is reached, then IsJSCompatibleSignature() is too // permissive. UNREACHABLE(); default: if (module_->has_signature(type.ref_index())) { BuildCheckValidRefValue(input, js_context, type); return input; } // If this is reached, then IsJSCompatibleSignature() is too // permissive. UNREACHABLE(); } } case wasm::ValueType::kF32: return graph()->NewNode( mcgraph()->machine()->TruncateFloat64ToFloat32(), BuildChangeTaggedToFloat64(input, js_context)); case wasm::ValueType::kF64: return BuildChangeTaggedToFloat64(input, js_context); case wasm::ValueType::kI32: return BuildChangeTaggedToInt32(input, js_context); case wasm::ValueType::kI64: // i64 values can only come from BigInt. DCHECK(enabled_features_.has_bigint()); return BuildChangeBigIntToInt64(input, js_context); case wasm::ValueType::kRtt: // TODO(7748): Implement. case wasm::ValueType::kS128: case wasm::ValueType::kI8: case wasm::ValueType::kI16: case wasm::ValueType::kBottom: case wasm::ValueType::kStmt: UNREACHABLE(); break; } } Node* SmiToFloat32(Node* input) { return graph()->NewNode(mcgraph()->machine()->RoundInt32ToFloat32(), BuildChangeSmiToInt32(input)); } Node* SmiToFloat64(Node* input) { return graph()->NewNode(mcgraph()->machine()->ChangeInt32ToFloat64(), BuildChangeSmiToInt32(input)); } Node* HeapNumberToFloat64(Node* input) { return gasm_->Load(MachineType::Float64(), input, wasm::ObjectAccess::ToTagged(HeapNumber::kValueOffset)); } Node* FromJSFast(Node* input, wasm::ValueType type) { switch (type.kind()) { case wasm::ValueType::kI32: return BuildChangeSmiToInt32(input); case wasm::ValueType::kF32: { auto done = gasm_->MakeLabel(MachineRepresentation::kFloat32); auto heap_number = gasm_->MakeLabel(); gasm_->GotoIfNot(IsSmi(input), &heap_number); gasm_->Goto(&done, SmiToFloat32(input)); gasm_->Bind(&heap_number); Node* value = graph()->NewNode(mcgraph()->machine()->TruncateFloat64ToFloat32(), HeapNumberToFloat64(input)); gasm_->Goto(&done, value); gasm_->Bind(&done); return done.PhiAt(0); } case wasm::ValueType::kF64: { auto done = gasm_->MakeLabel(MachineRepresentation::kFloat64); auto heap_number = gasm_->MakeLabel(); gasm_->GotoIfNot(IsSmi(input), &heap_number); gasm_->Goto(&done, SmiToFloat64(input)); gasm_->Bind(&heap_number); gasm_->Goto(&done, HeapNumberToFloat64(input)); gasm_->Bind(&done); return done.PhiAt(0); } case wasm::ValueType::kRef: case wasm::ValueType::kOptRef: case wasm::ValueType::kI64: case wasm::ValueType::kRtt: case wasm::ValueType::kS128: case wasm::ValueType::kI8: case wasm::ValueType::kI16: case wasm::ValueType::kBottom: case wasm::ValueType::kStmt: UNREACHABLE(); break; } } void BuildModifyThreadInWasmFlag(bool new_value) { if (!trap_handler::IsTrapHandlerEnabled()) return; Node* isolate_root = BuildLoadIsolateRoot(); Node* thread_in_wasm_flag_address = gasm_->Load(MachineType::Pointer(), isolate_root, Isolate::thread_in_wasm_flag_address_offset()); if (FLAG_debug_code) { Node* flag_value = SetEffect( graph()->NewNode(mcgraph()->machine()->Load(MachineType::Pointer()), thread_in_wasm_flag_address, mcgraph()->Int32Constant(0), effect(), control())); Node* check = graph()->NewNode(mcgraph()->machine()->Word32Equal(), flag_value, mcgraph()->Int32Constant(new_value ? 0 : 1)); Diamond flag_check(graph(), mcgraph()->common(), check, BranchHint::kTrue); flag_check.Chain(control()); SetControl(flag_check.if_false); Node* message_id = graph()->NewNode( mcgraph()->common()->NumberConstant(static_cast<int32_t>( new_value ? AbortReason::kUnexpectedThreadInWasmSet : AbortReason::kUnexpectedThreadInWasmUnset))); Node* old_effect = effect(); BuildCallToRuntimeWithContext(Runtime::kAbort, NoContextConstant(), &message_id, 1); SetEffectControl(flag_check.EffectPhi(old_effect, effect()), flag_check.merge); } SetEffect(graph()->NewNode( mcgraph()->machine()->Store(StoreRepresentation( MachineRepresentation::kWord32, kNoWriteBarrier)), thread_in_wasm_flag_address, mcgraph()->Int32Constant(0), mcgraph()->Int32Constant(new_value ? 1 : 0), effect(), control())); } Node* BuildLoadInstanceFromExportedFunctionData(Node* function_data) { return gasm_->Load( MachineType::AnyTagged(), function_data, WasmExportedFunctionData::kInstanceOffset - kHeapObjectTag); } Node* BuildMultiReturnFixedArrayFromIterable(const wasm::FunctionSig* sig, Node* iterable, Node* context) { Node* length = BuildChangeUint31ToSmi( mcgraph()->Uint32Constant(static_cast<uint32_t>(sig->return_count()))); return CALL_BUILTIN(IterableToFixedArrayForWasm, iterable, length, context); } // Extract the FixedArray implementing // the backing storage of a JavaScript array. Node* BuildLoadArrayBackingStorage(Node* js_array) { return gasm_->Load(MachineType::AnyTagged(), js_array, JSObject::kElementsOffset - kHeapObjectTag); } // Generate a call to the AllocateJSArray builtin. Node* BuildCallAllocateJSArray(Node* array_length, Node* context) { // Since we don't check that args will fit in an array, // we make sure this is true based on statically known limits. STATIC_ASSERT(wasm::kV8MaxWasmFunctionMultiReturns <= JSArray::kInitialMaxFastElementArray); return SetControl(CALL_BUILTIN(WasmAllocateJSArray, array_length, context)); } Node* BuildCallAndReturn(bool is_import, Node* js_context, Node* function_data, base::SmallVector<Node*, 16> args) { // Set the ThreadInWasm flag before we do the actual call. BuildModifyThreadInWasmFlag(true); const int rets_count = static_cast<int>(sig_->return_count()); base::SmallVector<Node*, 1> rets(rets_count); if (is_import) { // Call to an imported function. // Load function index from {WasmExportedFunctionData}. Node* function_index = BuildLoadFunctionIndexFromExportedFunctionData(function_data); BuildImportCall(sig_, VectorOf(args), VectorOf(rets), wasm::kNoCodePosition, function_index, kCallContinues); } else { // Call to a wasm function defined in this module. // The call target is the jump table slot for that function. Node* jump_table_start = LOAD_INSTANCE_FIELD(JumpTableStart, MachineType::Pointer()); Node* jump_table_offset = BuildLoadJumpTableOffsetFromExportedFunctionData(function_data); Node* jump_table_slot = graph()->NewNode( mcgraph()->machine()->IntAdd(), jump_table_start, jump_table_offset); args[0] = jump_table_slot; BuildWasmCall(sig_, VectorOf(args), VectorOf(rets), wasm::kNoCodePosition, nullptr, kNoRetpoline); } // Clear the ThreadInWasm flag. BuildModifyThreadInWasmFlag(false); Node* jsval; if (sig_->return_count() == 0) { jsval = BuildLoadUndefinedValueFromInstance(); } else if (sig_->return_count() == 1) { jsval = ToJS(rets[0], sig_->GetReturn()); } else { int32_t return_count = static_cast<int32_t>(sig_->return_count()); Node* size = graph()->NewNode(mcgraph()->common()->NumberConstant(return_count)); jsval = BuildCallAllocateJSArray(size, js_context); Node* fixed_array = BuildLoadArrayBackingStorage(jsval); for (int i = 0; i < return_count; ++i) { Node* value = ToJS(rets[i], sig_->GetReturn(i)); STORE_FIXED_ARRAY_SLOT_ANY(fixed_array, i, value); } } return jsval; } bool QualifiesForFastTransform(const wasm::FunctionSig*) { const int wasm_count = static_cast<int>(sig_->parameter_count()); for (int i = 0; i < wasm_count; ++i) { wasm::ValueType type = sig_->GetParam(i); switch (type.kind()) { case wasm::ValueType::kRef: case wasm::ValueType::kOptRef: case wasm::ValueType::kI64: case wasm::ValueType::kRtt: case wasm::ValueType::kS128: case wasm::ValueType::kI8: case wasm::ValueType::kI16: case wasm::ValueType::kBottom: case wasm::ValueType::kStmt: return false; case wasm::ValueType::kI32: case wasm::ValueType::kF32: case wasm::ValueType::kF64: break; } } return true; } Node* IsSmi(Node* input) { return gasm_->Word32Equal( gasm_->Word32And(BuildTruncateIntPtrToInt32(input), gasm_->Int32Constant(kSmiTagMask)), gasm_->Int32Constant(0)); } void CanTransformFast( Node* input, wasm::ValueType type, v8::internal::compiler::GraphAssemblerLabel<0>* slow_path) { switch (type.kind()) { case wasm::ValueType::kI32: { gasm_->GotoIfNot(IsSmi(input), slow_path); return; } case wasm::ValueType::kF32: case wasm::ValueType::kF64: { auto done = gasm_->MakeLabel(); gasm_->GotoIf(IsSmi(input), &done); Node* map = gasm_->Load(MachineType::TaggedPointer(), input, wasm::ObjectAccess::ToTagged(HeapObject::kMapOffset)); Node* heap_number_map = LOAD_FULL_POINTER( BuildLoadIsolateRoot(), IsolateData::root_slot_offset(RootIndex::kHeapNumberMap)); Node* is_heap_number = gasm_->WordEqual(heap_number_map, map); gasm_->GotoIf(is_heap_number, &done); gasm_->Goto(slow_path); gasm_->Bind(&done); return; } case wasm::ValueType::kRef: case wasm::ValueType::kOptRef: case wasm::ValueType::kI64: case wasm::ValueType::kRtt: case wasm::ValueType::kS128: case wasm::ValueType::kI8: case wasm::ValueType::kI16: case wasm::ValueType::kBottom: case wasm::ValueType::kStmt: UNREACHABLE(); break; } } void BuildJSToWasmWrapper(bool is_import) { const int wasm_count = static_cast<int>(sig_->parameter_count()); // Build the start and the JS parameter nodes. SetEffectControl(Start(wasm_count + 5)); // Create the js_closure and js_context parameters. Node* js_closure = graph()->NewNode(mcgraph()->common()->Parameter( Linkage::kJSCallClosureParamIndex, "%closure"), graph()->start()); Node* js_context = graph()->NewNode( mcgraph()->common()->Parameter( Linkage::GetJSCallContextParamIndex(wasm_count + 1), "%context"), graph()->start()); // Create the instance_node node to pass as parameter. It is loaded from // an actual reference to an instance or a placeholder reference, // called {WasmExportedFunction} via the {WasmExportedFunctionData} // structure. Node* function_data = BuildLoadFunctionDataFromExportedFunction(js_closure); instance_node_.set( BuildLoadInstanceFromExportedFunctionData(function_data)); if (!wasm::IsJSCompatibleSignature(sig_, module_, enabled_features_)) { // Throw a TypeError. Use the js_context of the calling javascript // function (passed as a parameter), such that the generated code is // js_context independent. BuildCallToRuntimeWithContext(Runtime::kWasmThrowTypeError, js_context, nullptr, 0); TerminateThrow(effect(), control()); return; } const int args_count = wasm_count + 1; // +1 for wasm_code. // Check whether the signature of the function allows for a fast // transformation (if any params exist that need transformation). // Create a fast transformation path, only if it does. bool include_fast_path = wasm_count && QualifiesForFastTransform(sig_); // Prepare Param() nodes. Param() nodes can only be created once, // so we need to use the same nodes along all possible transformation paths. base::SmallVector<Node*, 16> params(args_count); for (int i = 0; i < wasm_count; ++i) params[i + 1] = Param(i + 1); auto done = gasm_->MakeLabel(MachineRepresentation::kTagged); if (include_fast_path) { auto slow_path = gasm_->MakeDeferredLabel(); // Check if the params received on runtime can be actually transformed // using the fast transformation. When a param that cannot be transformed // fast is encountered, skip checking the rest and fall back to the slow // path. for (int i = 0; i < wasm_count; ++i) { CanTransformFast(params[i + 1], sig_->GetParam(i), &slow_path); } // Convert JS parameters to wasm numbers using the fast transformation // and build the call. base::SmallVector<Node*, 16> args(args_count); for (int i = 0; i < wasm_count; ++i) { Node* wasm_param = FromJSFast(params[i + 1], sig_->GetParam(i)); args[i + 1] = wasm_param; } Node* jsval = BuildCallAndReturn(is_import, js_context, function_data, args); gasm_->Goto(&done, jsval); gasm_->Bind(&slow_path); } // Convert JS parameters to wasm numbers using the default transformation // and build the call. base::SmallVector<Node*, 16> args(args_count); for (int i = 0; i < wasm_count; ++i) { Node* wasm_param = FromJS(params[i + 1], js_context, sig_->GetParam(i)); args[i + 1] = wasm_param; } Node* jsval = BuildCallAndReturn(is_import, js_context, function_data, args); // If both the default and a fast transformation paths are present, // get the return value based on the path used. if (include_fast_path) { gasm_->Goto(&done, jsval); gasm_->Bind(&done); Return(done.PhiAt(0)); } else { Return(jsval); } if (ContainsInt64(sig_)) LowerInt64(kCalledFromJS); } Node* BuildReceiverNode(Node* callable_node, Node* native_context, Node* undefined_node) { // Check function strict bit. Node* shared_function_info = gasm_->Load( MachineType::TaggedPointer(), callable_node, wasm::ObjectAccess::SharedFunctionInfoOffsetInTaggedJSFunction()); Node* flags = gasm_->Load(MachineType::Int32(), shared_function_info, wasm::ObjectAccess::FlagsOffsetInSharedFunctionInfo()); Node* strict_check = Binop(wasm::kExprI32And, flags, mcgraph()->Int32Constant(SharedFunctionInfo::IsNativeBit::kMask | SharedFunctionInfo::IsStrictBit::kMask)); // Load global receiver if sloppy else use undefined. Diamond strict_d(graph(), mcgraph()->common(), strict_check, BranchHint::kNone); Node* old_effect = effect(); SetControl(strict_d.if_false); Node* global_proxy = LOAD_FIXED_ARRAY_SLOT_PTR(native_context, Context::GLOBAL_PROXY_INDEX); SetEffectControl(strict_d.EffectPhi(old_effect, global_proxy), strict_d.merge); return strict_d.Phi(MachineRepresentation::kTagged, undefined_node, global_proxy); } bool BuildWasmImportCallWrapper(WasmImportCallKind kind, int expected_arity) { int wasm_count = static_cast<int>(sig_->parameter_count()); // Build the start and the parameter nodes. SetEffectControl(Start(wasm_count + 4)); instance_node_.set(Param(wasm::kWasmInstanceParameterIndex)); Node* native_context = LOAD_INSTANCE_FIELD(NativeContext, MachineType::TaggedPointer()); if (kind == WasmImportCallKind::kRuntimeTypeError) { // ======================================================================= // === Runtime TypeError ================================================= // ======================================================================= BuildCallToRuntimeWithContext(Runtime::kWasmThrowTypeError, native_context, nullptr, 0); TerminateThrow(effect(), control()); return false; } // The callable is passed as the last parameter, after Wasm arguments. Node* callable_node = Param(wasm_count + 1); Node* undefined_node = BuildLoadUndefinedValueFromInstance(); Node* call = nullptr; // Clear the ThreadInWasm flag. BuildModifyThreadInWasmFlag(false); switch (kind) { // ======================================================================= // === JS Functions with matching arity ================================== // ======================================================================= case WasmImportCallKind::kJSFunctionArityMatch: { base::SmallVector<Node*, 16> args(wasm_count + 7); int pos = 0; Node* function_context = gasm_->Load(MachineType::TaggedPointer(), callable_node, wasm::ObjectAccess::ContextOffsetInTaggedJSFunction()); args[pos++] = callable_node; // target callable. // Determine receiver at runtime. args[pos++] = BuildReceiverNode(callable_node, native_context, undefined_node); auto call_descriptor = Linkage::GetJSCallDescriptor( graph()->zone(), false, wasm_count + 1, CallDescriptor::kNoFlags); // Convert wasm numbers to JS values. pos = AddArgumentNodes(VectorOf(args), pos, wasm_count, sig_); args[pos++] = undefined_node; // new target args[pos++] = mcgraph()->Int32Constant(wasm_count); // argument count args[pos++] = function_context; args[pos++] = effect(); args[pos++] = control(); DCHECK_EQ(pos, args.size()); call = graph()->NewNode(mcgraph()->common()->Call(call_descriptor), pos, args.begin()); break; } #ifdef V8_NO_ARGUMENTS_ADAPTOR // ======================================================================= // === JS Functions with mismatching arity =============================== // ======================================================================= case WasmImportCallKind::kJSFunctionArityMismatch: { int pushed_count = std::max(expected_arity, wasm_count); base::SmallVector<Node*, 16> args(pushed_count + 7); int pos = 0; args[pos++] = callable_node; // target callable. // Determine receiver at runtime. args[pos++] = BuildReceiverNode(callable_node, native_context, undefined_node); // Convert wasm numbers to JS values. pos = AddArgumentNodes(VectorOf(args), pos, wasm_count, sig_); for (int i = wasm_count; i < expected_arity; ++i) { args[pos++] = undefined_node; } args[pos++] = undefined_node; // new target args[pos++] = mcgraph()->Int32Constant(wasm_count); // argument count Node* function_context = gasm_->Load(MachineType::TaggedPointer(), callable_node, wasm::ObjectAccess::ContextOffsetInTaggedJSFunction()); args[pos++] = function_context; args[pos++] = effect(); args[pos++] = control(); DCHECK_EQ(pos, args.size()); auto call_descriptor = Linkage::GetJSCallDescriptor( graph()->zone(), false, pushed_count + 1, CallDescriptor::kNoFlags); call = graph()->NewNode(mcgraph()->common()->Call(call_descriptor), pos, args.begin()); break; } case WasmImportCallKind::kJSFunctionArityMismatchSkipAdaptor: UNREACHABLE(); #else // ======================================================================= // === JS Functions with arguments adapter =============================== // ======================================================================= case WasmImportCallKind::kJSFunctionArityMismatch: { base::SmallVector<Node*, 16> args(wasm_count + 9); int pos = 0; Node* function_context = gasm_->Load(MachineType::TaggedPointer(), callable_node, wasm::ObjectAccess::ContextOffsetInTaggedJSFunction()); args[pos++] = mcgraph()->RelocatableIntPtrConstant( wasm::WasmCode::kArgumentsAdaptorTrampoline, RelocInfo::WASM_STUB_CALL); args[pos++] = callable_node; // target callable args[pos++] = undefined_node; // new target args[pos++] = mcgraph()->Int32Constant(wasm_count); // argument count // Load shared function info, and then the formal parameter count. Node* shared_function_info = gasm_->Load( MachineType::TaggedPointer(), callable_node, wasm::ObjectAccess::SharedFunctionInfoOffsetInTaggedJSFunction()); Node* formal_param_count = SetEffect(graph()->NewNode( mcgraph()->machine()->Load(MachineType::Uint16()), shared_function_info, mcgraph()->Int32Constant( wasm::ObjectAccess:: FormalParameterCountOffsetInSharedFunctionInfo()), effect(), control())); args[pos++] = formal_param_count; // Determine receiver at runtime. args[pos++] = BuildReceiverNode(callable_node, native_context, undefined_node); auto call_descriptor = Linkage::GetStubCallDescriptor( mcgraph()->zone(), ArgumentsAdaptorDescriptor{}, 1 + wasm_count, CallDescriptor::kNoFlags, Operator::kNoProperties, StubCallMode::kCallWasmRuntimeStub); // Convert wasm numbers to JS values. pos = AddArgumentNodes(VectorOf(args), pos, wasm_count, sig_); args[pos++] = function_context; args[pos++] = effect(); args[pos++] = control(); DCHECK_EQ(pos, args.size()); call = graph()->NewNode(mcgraph()->common()->Call(call_descriptor), pos, args.begin()); break; } // ======================================================================= // === JS Functions without arguments adapter ============================ // ======================================================================= case WasmImportCallKind::kJSFunctionArityMismatchSkipAdaptor: { base::SmallVector<Node*, 16> args(expected_arity + 7); int pos = 0; Node* function_context = gasm_->Load(MachineType::TaggedPointer(), callable_node, wasm::ObjectAccess::ContextOffsetInTaggedJSFunction()); args[pos++] = callable_node; // target callable. // Determine receiver at runtime. args[pos++] = BuildReceiverNode(callable_node, native_context, undefined_node); auto call_descriptor = Linkage::GetJSCallDescriptor( graph()->zone(), false, expected_arity + 1, CallDescriptor::kNoFlags); // Convert wasm numbers to JS values. if (expected_arity <= wasm_count) { pos = AddArgumentNodes(VectorOf(args), pos, expected_arity, sig_); } else { pos = AddArgumentNodes(VectorOf(args), pos, wasm_count, sig_); for (int i = wasm_count; i < expected_arity; ++i) { args[pos++] = undefined_node; } } args[pos++] = undefined_node; // new target args[pos++] = mcgraph()->Int32Constant(expected_arity); // argument count args[pos++] = function_context; args[pos++] = effect(); args[pos++] = control(); DCHECK_EQ(pos, args.size()); call = graph()->NewNode(mcgraph()->common()->Call(call_descriptor), pos, args.begin()); break; } #endif // ======================================================================= // === General case of unknown callable ================================== // ======================================================================= case WasmImportCallKind::kUseCallBuiltin: { base::SmallVector<Node*, 16> args(wasm_count + 7); int pos = 0; args[pos++] = GetBuiltinPointerTarget(Builtins::kCall_ReceiverIsAny); args[pos++] = callable_node; args[pos++] = mcgraph()->Int32Constant(wasm_count); // argument count args[pos++] = undefined_node; // receiver auto call_descriptor = Linkage::GetStubCallDescriptor( graph()->zone(), CallTrampolineDescriptor{}, wasm_count + 1, CallDescriptor::kNoFlags, Operator::kNoProperties, StubCallMode::kCallBuiltinPointer); // Convert wasm numbers to JS values. pos = AddArgumentNodes(VectorOf(args), pos, wasm_count, sig_); // The native_context is sufficient here, because all kind of callables // which depend on the context provide their own context. The context // here is only needed if the target is a constructor to throw a // TypeError, if the target is a native function, or if the target is a // callable JSObject, which can only be constructed by the runtime. args[pos++] = native_context; args[pos++] = effect(); args[pos++] = control(); DCHECK_EQ(pos, args.size()); call = graph()->NewNode(mcgraph()->common()->Call(call_descriptor), pos, args.begin()); break; } default: UNREACHABLE(); } DCHECK_NOT_NULL(call); SetEffect(call); SetSourcePosition(call, 0); // Convert the return value(s) back. if (sig_->return_count() <= 1) { Node* val = sig_->return_count() == 0 ? mcgraph()->Int32Constant(0) : FromJS(call, native_context, sig_->GetReturn()); BuildModifyThreadInWasmFlag(true); Return(val); } else { Node* fixed_array = BuildMultiReturnFixedArrayFromIterable(sig_, call, native_context); base::SmallVector<Node*, 8> wasm_values(sig_->return_count()); for (unsigned i = 0; i < sig_->return_count(); ++i) { wasm_values[i] = FromJS(LOAD_FIXED_ARRAY_SLOT_ANY(fixed_array, i), native_context, sig_->GetReturn(i)); } BuildModifyThreadInWasmFlag(true); Return(VectorOf(wasm_values)); } if (ContainsInt64(sig_)) LowerInt64(kCalledFromWasm); return true; } void BuildCapiCallWrapper(Address address) { // Store arguments on our stack, then align the stack for calling to C. int param_bytes = 0; for (wasm::ValueType type : sig_->parameters()) { param_bytes += type.element_size_bytes(); } int return_bytes = 0; for (wasm::ValueType type : sig_->returns()) { return_bytes += type.element_size_bytes(); } int stack_slot_bytes = std::max(param_bytes, return_bytes); Node* values = stack_slot_bytes == 0 ? mcgraph()->IntPtrConstant(0) : graph()->NewNode(mcgraph()->machine()->StackSlot( stack_slot_bytes, kDoubleAlignment)); int offset = 0; int param_count = static_cast<int>(sig_->parameter_count()); for (int i = 0; i < param_count; ++i) { wasm::ValueType type = sig_->GetParam(i); // Start from the parameter with index 1 to drop the instance_node. // TODO(jkummerow): When a values is a reference type, we should pass it // in a GC-safe way, not just as a raw pointer. SetEffect(graph()->NewNode(GetSafeStoreOperator(offset, type), values, Int32Constant(offset), Param(i + 1), effect(), control())); offset += type.element_size_bytes(); } // The function is passed as the last parameter, after Wasm arguments. Node* function_node = Param(param_count + 1); Node* shared = gasm_->Load( MachineType::AnyTagged(), function_node, wasm::ObjectAccess::SharedFunctionInfoOffsetInTaggedJSFunction()); Node* sfi_data = gasm_->Load(MachineType::AnyTagged(), shared, SharedFunctionInfo::kFunctionDataOffset - kHeapObjectTag); Node* host_data_foreign = gasm_->Load(MachineType::AnyTagged(), sfi_data, WasmCapiFunctionData::kEmbedderDataOffset - kHeapObjectTag); BuildModifyThreadInWasmFlag(false); Node* isolate_root = BuildLoadIsolateRoot(); Node* fp_value = graph()->NewNode(mcgraph()->machine()->LoadFramePointer()); STORE_RAW(isolate_root, Isolate::c_entry_fp_offset(), fp_value, MachineType::PointerRepresentation(), kNoWriteBarrier); // TODO(jkummerow): Load the address from the {host_data}, and cache // wrappers per signature. const ExternalReference ref = ExternalReference::Create(address); Node* function = graph()->NewNode(mcgraph()->common()->ExternalConstant(ref)); // Parameters: Address host_data_foreign, Address arguments. MachineType host_sig_types[] = { MachineType::Pointer(), MachineType::Pointer(), MachineType::Pointer()}; MachineSignature host_sig(1, 2, host_sig_types); Node* return_value = BuildCCall(&host_sig, function, host_data_foreign, values); BuildModifyThreadInWasmFlag(true); Node* exception_branch = graph()->NewNode( mcgraph()->common()->Branch(BranchHint::kTrue), graph()->NewNode(mcgraph()->machine()->WordEqual(), return_value, mcgraph()->IntPtrConstant(0)), control()); SetControl( graph()->NewNode(mcgraph()->common()->IfFalse(), exception_branch)); WasmThrowDescriptor interface_descriptor; auto call_descriptor = Linkage::GetStubCallDescriptor( mcgraph()->zone(), interface_descriptor, interface_descriptor.GetStackParameterCount(), CallDescriptor::kNoFlags, Operator::kNoProperties, StubCallMode::kCallWasmRuntimeStub); Node* call_target = mcgraph()->RelocatableIntPtrConstant( wasm::WasmCode::kWasmRethrow, RelocInfo::WASM_STUB_CALL); Node* throw_effect = graph()->NewNode(mcgraph()->common()->Call(call_descriptor), call_target, return_value, effect(), control()); TerminateThrow(throw_effect, control()); SetControl( graph()->NewNode(mcgraph()->common()->IfTrue(), exception_branch)); DCHECK_LT(sig_->return_count(), wasm::kV8MaxWasmFunctionMultiReturns); size_t return_count = sig_->return_count(); if (return_count == 0) { Return(Int32Constant(0)); } else { base::SmallVector<Node*, 8> returns(return_count); offset = 0; for (size_t i = 0; i < return_count; ++i) { wasm::ValueType type = sig_->GetReturn(i); Node* val = SetEffect( graph()->NewNode(GetSafeLoadOperator(offset, type), values, Int32Constant(offset), effect(), control())); returns[i] = val; offset += type.element_size_bytes(); } Return(VectorOf(returns)); } if (ContainsInt64(sig_)) LowerInt64(kCalledFromWasm); } void BuildJSToJSWrapper(Isolate* isolate) { int wasm_count = static_cast<int>(sig_->parameter_count()); // Build the start and the parameter nodes. int param_count = 1 /* closure */ + 1 /* receiver */ + wasm_count + 1 /* new.target */ + 1 /* #arg */ + 1 /* context */; SetEffectControl(Start(param_count)); Node* closure = Param(Linkage::kJSCallClosureParamIndex); Node* context = Param(Linkage::GetJSCallContextParamIndex(wasm_count + 1)); // Since JS-to-JS wrappers are specific to one Isolate, it is OK to embed // values (for undefined and root) directly into the instruction stream. isolate_root_node_ = mcgraph()->IntPtrConstant(isolate->isolate_root()); undefined_value_node_ = graph()->NewNode(mcgraph()->common()->HeapConstant( isolate->factory()->undefined_value())); // Throw a TypeError if the signature is incompatible with JavaScript. if (!wasm::IsJSCompatibleSignature(sig_, module_, enabled_features_)) { BuildCallToRuntimeWithContext(Runtime::kWasmThrowTypeError, context, nullptr, 0); TerminateThrow(effect(), control()); return; } // Load the original callable from the closure. Node* shared = LOAD_TAGGED_ANY( closure, wasm::ObjectAccess::ToTagged(JSFunction::kSharedFunctionInfoOffset)); Node* func_data = LOAD_TAGGED_ANY( shared, wasm::ObjectAccess::ToTagged(SharedFunctionInfo::kFunctionDataOffset)); Node* callable = LOAD_TAGGED_ANY( func_data, wasm::ObjectAccess::ToTagged(WasmJSFunctionData::kCallableOffset)); // Call the underlying closure. base::SmallVector<Node*, 16> args(wasm_count + 7); int pos = 0; args[pos++] = GetBuiltinPointerTarget(Builtins::kCall_ReceiverIsAny); args[pos++] = callable; args[pos++] = mcgraph()->Int32Constant(wasm_count); // argument count args[pos++] = BuildLoadUndefinedValueFromInstance(); // receiver auto call_descriptor = Linkage::GetStubCallDescriptor( graph()->zone(), CallTrampolineDescriptor{}, wasm_count + 1, CallDescriptor::kNoFlags, Operator::kNoProperties, StubCallMode::kCallBuiltinPointer); // Convert parameter JS values to wasm numbers and back to JS values. for (int i = 0; i < wasm_count; ++i) { Node* param = Param(i + 1); // Start from index 1 to skip receiver. args[pos++] = ToJS(FromJS(param, context, sig_->GetParam(i)), sig_->GetParam(i)); } args[pos++] = context; args[pos++] = effect(); args[pos++] = control(); DCHECK_EQ(pos, args.size()); Node* call = SetEffect(graph()->NewNode( mcgraph()->common()->Call(call_descriptor), pos, args.begin())); // Convert return JS values to wasm numbers and back to JS values. Node* jsval; if (sig_->return_count() == 0) { jsval = BuildLoadUndefinedValueFromInstance(); } else if (sig_->return_count() == 1) { jsval = ToJS(FromJS(call, context, sig_->GetReturn()), sig_->GetReturn()); } else { Node* fixed_array = BuildMultiReturnFixedArrayFromIterable(sig_, call, context); int32_t return_count = static_cast<int32_t>(sig_->return_count()); Node* size = graph()->NewNode(mcgraph()->common()->NumberConstant(return_count)); jsval = BuildCallAllocateJSArray(size, context); Node* result_fixed_array = BuildLoadArrayBackingStorage(jsval); for (unsigned i = 0; i < sig_->return_count(); ++i) { const auto& type = sig_->GetReturn(i); Node* elem = LOAD_FIXED_ARRAY_SLOT_ANY(fixed_array, i); Node* cast = ToJS(FromJS(elem, context, type), type); STORE_FIXED_ARRAY_SLOT_ANY(result_fixed_array, i, cast); } } Return(jsval); } void BuildCWasmEntry() { // +1 offset for first parameter index being -1. SetEffectControl(Start(CWasmEntryParameters::kNumParameters + 1)); Node* code_entry = Param(CWasmEntryParameters::kCodeEntry); Node* object_ref = Param(CWasmEntryParameters::kObjectRef); Node* arg_buffer = Param(CWasmEntryParameters::kArgumentsBuffer); Node* c_entry_fp = Param(CWasmEntryParameters::kCEntryFp); Node* fp_value = graph()->NewNode(mcgraph()->machine()->LoadFramePointer()); STORE_RAW(fp_value, TypedFrameConstants::kFirstPushedFrameValueOffset, c_entry_fp, MachineType::PointerRepresentation(), kNoWriteBarrier); int wasm_arg_count = static_cast<int>(sig_->parameter_count()); base::SmallVector<Node*, 16> args(wasm_arg_count + 4); int pos = 0; args[pos++] = code_entry; args[pos++] = object_ref; int offset = 0; for (wasm::ValueType type : sig_->parameters()) { Node* arg_load = SetEffect( graph()->NewNode(GetSafeLoadOperator(offset, type), arg_buffer, Int32Constant(offset), effect(), control())); args[pos++] = arg_load; offset += type.element_size_bytes(); } args[pos++] = effect(); args[pos++] = control(); // Call the wasm code. auto call_descriptor = GetWasmCallDescriptor(mcgraph()->zone(), sig_); DCHECK_EQ(pos, args.size()); Node* call = SetEffect(graph()->NewNode( mcgraph()->common()->Call(call_descriptor), pos, args.begin())); Node* if_success = graph()->NewNode(mcgraph()->common()->IfSuccess(), call); Node* if_exception = graph()->NewNode(mcgraph()->common()->IfException(), call, call); // Handle exception: return it. SetControl(if_exception); Return(if_exception); // Handle success: store the return value(s). SetControl(if_success); pos = 0; offset = 0; for (wasm::ValueType type : sig_->returns()) { Node* value = sig_->return_count() == 1 ? call : graph()->NewNode(mcgraph()->common()->Projection(pos), call, control()); SetEffect(graph()->NewNode(GetSafeStoreOperator(offset, type), arg_buffer, Int32Constant(offset), value, effect(), control())); offset += type.element_size_bytes(); pos++; } Return(mcgraph()->IntPtrConstant(0)); if (mcgraph()->machine()->Is32() && ContainsInt64(sig_)) { // No special lowering should be requested in the C entry. DCHECK_NULL(lowering_special_case_); MachineRepresentation sig_reps[] = { MachineType::PointerRepresentation(), // return value MachineType::PointerRepresentation(), // target MachineRepresentation::kTagged, // object_ref MachineType::PointerRepresentation(), // argv MachineType::PointerRepresentation() // c_entry_fp }; Signature<MachineRepresentation> c_entry_sig(1, 4, sig_reps); Int64Lowering r(mcgraph()->graph(), mcgraph()->machine(), mcgraph()->common(), mcgraph()->zone(), &c_entry_sig); r.LowerGraph(); } } private: const wasm::WasmModule* module_; StubCallMode stub_mode_; SetOncePointer<Node> undefined_value_node_; SetOncePointer<const Operator> int32_to_heapnumber_operator_; SetOncePointer<const Operator> tagged_non_smi_to_int32_operator_; SetOncePointer<const Operator> float32_to_number_operator_; SetOncePointer<const Operator> float64_to_number_operator_; SetOncePointer<const Operator> tagged_to_float64_operator_; wasm::WasmFeatures enabled_features_; CallDescriptor* bigint_to_i64_descriptor_ = nullptr; CallDescriptor* i64_to_bigint_descriptor_ = nullptr; }; } // namespace std::unique_ptr<OptimizedCompilationJob> NewJSToWasmCompilationJob( Isolate* isolate, wasm::WasmEngine* wasm_engine, const wasm::FunctionSig* sig, const wasm::WasmModule* module, bool is_import, const wasm::WasmFeatures& enabled_features) { //---------------------------------------------------------------------------- // Create the Graph. //---------------------------------------------------------------------------- std::unique_ptr<Zone> zone = std::make_unique<Zone>( wasm_engine->allocator(), ZONE_NAME, kCompressGraphZone); Graph* graph = zone->New<Graph>(zone.get()); CommonOperatorBuilder* common = zone->New<CommonOperatorBuilder>(zone.get()); MachineOperatorBuilder* machine = zone->New<MachineOperatorBuilder>( zone.get(), MachineType::PointerRepresentation(), InstructionSelector::SupportedMachineOperatorFlags(), InstructionSelector::AlignmentRequirements()); MachineGraph* mcgraph = zone->New<MachineGraph>(graph, common, machine); WasmWrapperGraphBuilder builder(zone.get(), mcgraph, sig, module, nullptr, StubCallMode::kCallBuiltinPointer, enabled_features); builder.BuildJSToWasmWrapper(is_import); //---------------------------------------------------------------------------- // Create the compilation job. //---------------------------------------------------------------------------- constexpr size_t kMaxNameLen = 128; constexpr size_t kNamePrefixLen = 11; auto name_buffer = std::unique_ptr<char[]>(new char[kMaxNameLen]); memcpy(name_buffer.get(), "js-to-wasm:", kNamePrefixLen); PrintSignature(VectorOf(name_buffer.get(), kMaxNameLen) + kNamePrefixLen, sig); int params = static_cast<int>(sig->parameter_count()); CallDescriptor* incoming = Linkage::GetJSCallDescriptor( zone.get(), false, params + 1, CallDescriptor::kNoFlags); return Pipeline::NewWasmHeapStubCompilationJob( isolate, wasm_engine, incoming, std::move(zone), graph, CodeKind::JS_TO_WASM_FUNCTION, std::move(name_buffer), WasmAssemblerOptions()); } std::pair<WasmImportCallKind, Handle<JSReceiver>> ResolveWasmImportCall( Handle<JSReceiver> callable, const wasm::FunctionSig* expected_sig, const wasm::WasmModule* module, const wasm::WasmFeatures& enabled_features) { if (WasmExportedFunction::IsWasmExportedFunction(*callable)) { auto imported_function = Handle<WasmExportedFunction>::cast(callable); if (!imported_function->MatchesSignature(module, expected_sig)) { return std::make_pair(WasmImportCallKind::kLinkError, callable); } uint32_t func_index = static_cast<uint32_t>(imported_function->function_index()); if (func_index >= imported_function->instance().module()->num_imported_functions) { return std::make_pair(WasmImportCallKind::kWasmToWasm, callable); } Isolate* isolate = callable->GetIsolate(); // Resolve the shortcut to the underlying callable and continue. Handle<WasmInstanceObject> instance(imported_function->instance(), isolate); ImportedFunctionEntry entry(instance, func_index); callable = handle(entry.callable(), isolate); } if (WasmJSFunction::IsWasmJSFunction(*callable)) { auto js_function = Handle<WasmJSFunction>::cast(callable); if (!js_function->MatchesSignature(expected_sig)) { return std::make_pair(WasmImportCallKind::kLinkError, callable); } Isolate* isolate = callable->GetIsolate(); // Resolve the short-cut to the underlying callable and continue. callable = handle(js_function->GetCallable(), isolate); } if (WasmCapiFunction::IsWasmCapiFunction(*callable)) { auto capi_function = Handle<WasmCapiFunction>::cast(callable); if (!capi_function->MatchesSignature(expected_sig)) { return std::make_pair(WasmImportCallKind::kLinkError, callable); } return std::make_pair(WasmImportCallKind::kWasmToCapi, callable); } // Assuming we are calling to JS, check whether this would be a runtime error. if (!wasm::IsJSCompatibleSignature(expected_sig, module, enabled_features)) { return std::make_pair(WasmImportCallKind::kRuntimeTypeError, callable); } // For JavaScript calls, determine whether the target has an arity match. if (callable->IsJSFunction()) { Handle<JSFunction> function = Handle<JSFunction>::cast(callable); Handle<SharedFunctionInfo> shared(function->shared(), function->GetIsolate()); // Check for math intrinsics. #define COMPARE_SIG_FOR_BUILTIN(name) \ { \ const wasm::FunctionSig* sig = \ wasm::WasmOpcodes::Signature(wasm::kExpr##name); \ if (!sig) sig = wasm::WasmOpcodes::AsmjsSignature(wasm::kExpr##name); \ DCHECK_NOT_NULL(sig); \ if (*expected_sig == *sig) { \ return std::make_pair(WasmImportCallKind::k##name, callable); \ } \ } #define COMPARE_SIG_FOR_BUILTIN_F64(name) \ case Builtins::kMath##name: \ COMPARE_SIG_FOR_BUILTIN(F64##name); \ break; #define COMPARE_SIG_FOR_BUILTIN_F32_F64(name) \ case Builtins::kMath##name: \ COMPARE_SIG_FOR_BUILTIN(F64##name); \ COMPARE_SIG_FOR_BUILTIN(F32##name); \ break; if (FLAG_wasm_math_intrinsics && shared->HasBuiltinId()) { switch (shared->builtin_id()) { COMPARE_SIG_FOR_BUILTIN_F64(Acos); COMPARE_SIG_FOR_BUILTIN_F64(Asin); COMPARE_SIG_FOR_BUILTIN_F64(Atan); COMPARE_SIG_FOR_BUILTIN_F64(Cos); COMPARE_SIG_FOR_BUILTIN_F64(Sin); COMPARE_SIG_FOR_BUILTIN_F64(Tan); COMPARE_SIG_FOR_BUILTIN_F64(Exp); COMPARE_SIG_FOR_BUILTIN_F64(Log); COMPARE_SIG_FOR_BUILTIN_F64(Atan2); COMPARE_SIG_FOR_BUILTIN_F64(Pow); COMPARE_SIG_FOR_BUILTIN_F32_F64(Min); COMPARE_SIG_FOR_BUILTIN_F32_F64(Max); COMPARE_SIG_FOR_BUILTIN_F32_F64(Abs); COMPARE_SIG_FOR_BUILTIN_F32_F64(Ceil); COMPARE_SIG_FOR_BUILTIN_F32_F64(Floor); COMPARE_SIG_FOR_BUILTIN_F32_F64(Sqrt); case Builtins::kMathFround: COMPARE_SIG_FOR_BUILTIN(F32ConvertF64); break; default: break; } } #undef COMPARE_SIG_FOR_BUILTIN #undef COMPARE_SIG_FOR_BUILTIN_F64 #undef COMPARE_SIG_FOR_BUILTIN_F32_F64 if (IsClassConstructor(shared->kind())) { // Class constructor will throw anyway. return std::make_pair(WasmImportCallKind::kUseCallBuiltin, callable); } if (shared->internal_formal_parameter_count() == expected_sig->parameter_count()) { return std::make_pair(WasmImportCallKind::kJSFunctionArityMatch, callable); } // If function isn't compiled, compile it now. IsCompiledScope is_compiled_scope( shared->is_compiled_scope(callable->GetIsolate())); if (!is_compiled_scope.is_compiled()) { Compiler::Compile(function, Compiler::CLEAR_EXCEPTION, &is_compiled_scope); } #ifndef V8_REVERSE_JSARGS // This optimization is disabled when the arguments are reversed. It will be // subsumed when the argumens adaptor frame is removed. if (shared->is_safe_to_skip_arguments_adaptor()) { return std::make_pair( WasmImportCallKind::kJSFunctionArityMismatchSkipAdaptor, callable); } #endif return std::make_pair(WasmImportCallKind::kJSFunctionArityMismatch, callable); } // Unknown case. Use the call builtin. return std::make_pair(WasmImportCallKind::kUseCallBuiltin, callable); } namespace { wasm::WasmOpcode GetMathIntrinsicOpcode(WasmImportCallKind kind, const char** name_ptr) { #define CASE(name) \ case WasmImportCallKind::k##name: \ *name_ptr = "WasmMathIntrinsic:" #name; \ return wasm::kExpr##name switch (kind) { CASE(F64Acos); CASE(F64Asin); CASE(F64Atan); CASE(F64Cos); CASE(F64Sin); CASE(F64Tan); CASE(F64Exp); CASE(F64Log); CASE(F64Atan2); CASE(F64Pow); CASE(F64Ceil); CASE(F64Floor); CASE(F64Sqrt); CASE(F64Min); CASE(F64Max); CASE(F64Abs); CASE(F32Min); CASE(F32Max); CASE(F32Abs); CASE(F32Ceil); CASE(F32Floor); CASE(F32Sqrt); CASE(F32ConvertF64); default: UNREACHABLE(); return wasm::kExprUnreachable; } #undef CASE } wasm::WasmCompilationResult CompileWasmMathIntrinsic( wasm::WasmEngine* wasm_engine, WasmImportCallKind kind, const wasm::FunctionSig* sig) { DCHECK_EQ(1, sig->return_count()); TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.wasm.detailed"), "wasm.CompileWasmMathIntrinsic"); Zone zone(wasm_engine->allocator(), ZONE_NAME, kCompressGraphZone); // Compile a Wasm function with a single bytecode and let TurboFan // generate either inlined machine code or a call to a helper. SourcePositionTable* source_positions = nullptr; MachineGraph* mcgraph = zone.New<MachineGraph>( zone.New<Graph>(&zone), zone.New<CommonOperatorBuilder>(&zone), zone.New<MachineOperatorBuilder>( &zone, MachineType::PointerRepresentation(), InstructionSelector::SupportedMachineOperatorFlags(), InstructionSelector::AlignmentRequirements())); wasm::CompilationEnv env( nullptr, wasm::UseTrapHandler::kNoTrapHandler, wasm::RuntimeExceptionSupport::kNoRuntimeExceptionSupport, wasm::WasmFeatures::All(), wasm::LowerSimd::kNoLowerSimd); WasmGraphBuilder builder(&env, mcgraph->zone(), mcgraph, sig, source_positions); // Set up the graph start. Node* start = builder.Start(static_cast<int>(sig->parameter_count() + 1 + 1)); builder.SetEffectControl(start); builder.set_instance_node(builder.Param(wasm::kWasmInstanceParameterIndex)); // Generate either a unop or a binop. Node* node = nullptr; const char* debug_name = "WasmMathIntrinsic"; auto opcode = GetMathIntrinsicOpcode(kind, &debug_name); switch (sig->parameter_count()) { case 1: node = builder.Unop(opcode, builder.Param(1)); break; case 2: node = builder.Binop(opcode, builder.Param(1), builder.Param(2)); break; default: UNREACHABLE(); } builder.Return(node); // Run the compiler pipeline to generate machine code. auto call_descriptor = GetWasmCallDescriptor(&zone, sig); if (mcgraph->machine()->Is32()) { call_descriptor = GetI32WasmCallDescriptor(&zone, call_descriptor); } wasm::WasmCompilationResult result = Pipeline::GenerateCodeForWasmNativeStub( wasm_engine, call_descriptor, mcgraph, CodeKind::WASM_FUNCTION, wasm::WasmCode::kFunction, debug_name, WasmStubAssemblerOptions(), source_positions); return result; } } // namespace wasm::WasmCompilationResult CompileWasmImportCallWrapper( wasm::WasmEngine* wasm_engine, wasm::CompilationEnv* env, WasmImportCallKind kind, const wasm::FunctionSig* sig, bool source_positions, int expected_arity) { DCHECK_NE(WasmImportCallKind::kLinkError, kind); DCHECK_NE(WasmImportCallKind::kWasmToWasm, kind); // Check for math intrinsics first. if (FLAG_wasm_math_intrinsics && kind >= WasmImportCallKind::kFirstMathIntrinsic && kind <= WasmImportCallKind::kLastMathIntrinsic) { return CompileWasmMathIntrinsic(wasm_engine, kind, sig); } TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.wasm.detailed"), "wasm.CompileWasmImportCallWrapper"); //---------------------------------------------------------------------------- // Create the Graph //---------------------------------------------------------------------------- Zone zone(wasm_engine->allocator(), ZONE_NAME, kCompressGraphZone); Graph* graph = zone.New<Graph>(&zone); CommonOperatorBuilder* common = zone.New<CommonOperatorBuilder>(&zone); MachineOperatorBuilder* machine = zone.New<MachineOperatorBuilder>( &zone, MachineType::PointerRepresentation(), InstructionSelector::SupportedMachineOperatorFlags(), InstructionSelector::AlignmentRequirements()); MachineGraph* mcgraph = zone.New<MachineGraph>(graph, common, machine); SourcePositionTable* source_position_table = source_positions ? zone.New<SourcePositionTable>(graph) : nullptr; WasmWrapperGraphBuilder builder( &zone, mcgraph, sig, env->module, source_position_table, StubCallMode::kCallWasmRuntimeStub, env->enabled_features); builder.BuildWasmImportCallWrapper(kind, expected_arity); // Build a name in the form "wasm-to-js-<kind>-<signature>". constexpr size_t kMaxNameLen = 128; char func_name[kMaxNameLen]; int name_prefix_len = SNPrintF(VectorOf(func_name, kMaxNameLen), "wasm-to-js-%d-", static_cast<int>(kind)); PrintSignature(VectorOf(func_name, kMaxNameLen) + name_prefix_len, sig, '-'); // Schedule and compile to machine code. CallDescriptor* incoming = GetWasmCallDescriptor(&zone, sig, WasmGraphBuilder::kNoRetpoline, WasmCallKind::kWasmImportWrapper); if (machine->Is32()) { incoming = GetI32WasmCallDescriptor(&zone, incoming); } wasm::WasmCompilationResult result = Pipeline::GenerateCodeForWasmNativeStub( wasm_engine, incoming, mcgraph, CodeKind::WASM_TO_JS_FUNCTION, wasm::WasmCode::kWasmToJsWrapper, func_name, WasmStubAssemblerOptions(), source_position_table); result.kind = wasm::WasmCompilationResult::kWasmToJsWrapper; return result; } wasm::WasmCode* CompileWasmCapiCallWrapper(wasm::WasmEngine* wasm_engine, wasm::NativeModule* native_module, const wasm::FunctionSig* sig, Address address) { TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.wasm.detailed"), "wasm.CompileWasmCapiFunction"); Zone zone(wasm_engine->allocator(), ZONE_NAME, kCompressGraphZone); // TODO(jkummerow): Extract common code into helper method. SourcePositionTable* source_positions = nullptr; MachineGraph* mcgraph = zone.New<MachineGraph>( zone.New<Graph>(&zone), zone.New<CommonOperatorBuilder>(&zone), zone.New<MachineOperatorBuilder>( &zone, MachineType::PointerRepresentation(), InstructionSelector::SupportedMachineOperatorFlags(), InstructionSelector::AlignmentRequirements())); WasmWrapperGraphBuilder builder( &zone, mcgraph, sig, native_module->module(), source_positions, StubCallMode::kCallWasmRuntimeStub, native_module->enabled_features()); // Set up the graph start. int param_count = static_cast<int>(sig->parameter_count()) + 1 /* offset for first parameter index being -1 */ + 1 /* Wasm instance */ + 1 /* kExtraCallableParam */; Node* start = builder.Start(param_count); builder.SetEffectControl(start); builder.set_instance_node(builder.Param(wasm::kWasmInstanceParameterIndex)); builder.BuildCapiCallWrapper(address); // Run the compiler pipeline to generate machine code. CallDescriptor* call_descriptor = GetWasmCallDescriptor(&zone, sig, WasmGraphBuilder::kNoRetpoline, WasmCallKind::kWasmCapiFunction); if (mcgraph->machine()->Is32()) { call_descriptor = GetI32WasmCallDescriptor(&zone, call_descriptor); } const char* debug_name = "WasmCapiCall"; wasm::WasmCompilationResult result = Pipeline::GenerateCodeForWasmNativeStub( wasm_engine, call_descriptor, mcgraph, CodeKind::WASM_TO_CAPI_FUNCTION, wasm::WasmCode::kWasmToCapiWrapper, debug_name, WasmStubAssemblerOptions(), source_positions); std::unique_ptr<wasm::WasmCode> wasm_code = native_module->AddCode( wasm::kAnonymousFuncIndex, result.code_desc, result.frame_slot_count, result.tagged_parameter_slots, result.protected_instructions_data.as_vector(), result.source_positions.as_vector(), wasm::WasmCode::kWasmToCapiWrapper, wasm::ExecutionTier::kNone, wasm::kNoDebugging); return native_module->PublishCode(std::move(wasm_code)); } MaybeHandle<Code> CompileJSToJSWrapper(Isolate* isolate, const wasm::FunctionSig* sig, const wasm::WasmModule* module) { std::unique_ptr<Zone> zone = std::make_unique<Zone>( isolate->allocator(), ZONE_NAME, kCompressGraphZone); Graph* graph = zone->New<Graph>(zone.get()); CommonOperatorBuilder* common = zone->New<CommonOperatorBuilder>(zone.get()); MachineOperatorBuilder* machine = zone->New<MachineOperatorBuilder>( zone.get(), MachineType::PointerRepresentation(), InstructionSelector::SupportedMachineOperatorFlags(), InstructionSelector::AlignmentRequirements()); MachineGraph* mcgraph = zone->New<MachineGraph>(graph, common, machine); WasmWrapperGraphBuilder builder(zone.get(), mcgraph, sig, module, nullptr, StubCallMode::kCallBuiltinPointer, wasm::WasmFeatures::FromIsolate(isolate)); builder.BuildJSToJSWrapper(isolate); int wasm_count = static_cast<int>(sig->parameter_count()); CallDescriptor* incoming = Linkage::GetJSCallDescriptor( zone.get(), false, wasm_count + 1, CallDescriptor::kNoFlags); // Build a name in the form "js-to-js:<params>:<returns>". constexpr size_t kMaxNameLen = 128; constexpr size_t kNamePrefixLen = 9; auto name_buffer = std::unique_ptr<char[]>(new char[kMaxNameLen]); memcpy(name_buffer.get(), "js-to-js:", kNamePrefixLen); PrintSignature(VectorOf(name_buffer.get(), kMaxNameLen) + kNamePrefixLen, sig); // Run the compilation job synchronously. std::unique_ptr<OptimizedCompilationJob> job( Pipeline::NewWasmHeapStubCompilationJob( isolate, isolate->wasm_engine(), incoming, std::move(zone), graph, CodeKind::JS_TO_JS_FUNCTION, std::move(name_buffer), AssemblerOptions::Default(isolate))); if (job->ExecuteJob(isolate->counters()->runtime_call_stats()) == CompilationJob::FAILED || job->FinalizeJob(isolate) == CompilationJob::FAILED) { return {}; } Handle<Code> code = job->compilation_info()->code(); return code; } Handle<Code> CompileCWasmEntry(Isolate* isolate, const wasm::FunctionSig* sig, const wasm::WasmModule* module) { std::unique_ptr<Zone> zone = std::make_unique<Zone>( isolate->allocator(), ZONE_NAME, kCompressGraphZone); Graph* graph = zone->New<Graph>(zone.get()); CommonOperatorBuilder* common = zone->New<CommonOperatorBuilder>(zone.get()); MachineOperatorBuilder* machine = zone->New<MachineOperatorBuilder>( zone.get(), MachineType::PointerRepresentation(), InstructionSelector::SupportedMachineOperatorFlags(), InstructionSelector::AlignmentRequirements()); MachineGraph* mcgraph = zone->New<MachineGraph>(graph, common, machine); WasmWrapperGraphBuilder builder(zone.get(), mcgraph, sig, module, nullptr, StubCallMode::kCallBuiltinPointer, wasm::WasmFeatures::FromIsolate(isolate)); builder.BuildCWasmEntry(); // Schedule and compile to machine code. MachineType sig_types[] = {MachineType::Pointer(), // return MachineType::Pointer(), // target MachineType::AnyTagged(), // object_ref MachineType::Pointer(), // argv MachineType::Pointer()}; // c_entry_fp MachineSignature incoming_sig(1, 4, sig_types); // Traps need the root register, for TailCallRuntime to call // Runtime::kThrowWasmError. CallDescriptor::Flags flags = CallDescriptor::kInitializeRootRegister; CallDescriptor* incoming = Linkage::GetSimplifiedCDescriptor(zone.get(), &incoming_sig, flags); // Build a name in the form "c-wasm-entry:<params>:<returns>". constexpr size_t kMaxNameLen = 128; constexpr size_t kNamePrefixLen = 13; auto name_buffer = std::unique_ptr<char[]>(new char[kMaxNameLen]); memcpy(name_buffer.get(), "c-wasm-entry:", kNamePrefixLen); PrintSignature(VectorOf(name_buffer.get(), kMaxNameLen) + kNamePrefixLen, sig); // Run the compilation job synchronously. std::unique_ptr<OptimizedCompilationJob> job( Pipeline::NewWasmHeapStubCompilationJob( isolate, isolate->wasm_engine(), incoming, std::move(zone), graph, CodeKind::C_WASM_ENTRY, std::move(name_buffer), AssemblerOptions::Default(isolate))); CHECK_NE(job->ExecuteJob(isolate->counters()->runtime_call_stats()), CompilationJob::FAILED); CHECK_NE(job->FinalizeJob(isolate), CompilationJob::FAILED); return job->compilation_info()->code(); } namespace { bool BuildGraphForWasmFunction(AccountingAllocator* allocator, wasm::CompilationEnv* env, const wasm::FunctionBody& func_body, int func_index, wasm::WasmFeatures* detected, MachineGraph* mcgraph, NodeOriginTable* node_origins, SourcePositionTable* source_positions) { // Create a TF graph during decoding. WasmGraphBuilder builder(env, mcgraph->zone(), mcgraph, func_body.sig, source_positions); wasm::VoidResult graph_construction_result = wasm::BuildTFGraph(allocator, env->enabled_features, env->module, &builder, detected, func_body, node_origins); if (graph_construction_result.failed()) { if (FLAG_trace_wasm_compiler) { StdoutStream{} << "Compilation failed: " << graph_construction_result.error().message() << std::endl; } return false; } // Lower SIMD first, i64x2 nodes will be lowered to int64 nodes, then int64 // lowering will take care of them. auto sig = CreateMachineSignature(mcgraph->zone(), func_body.sig, WasmGraphBuilder::kCalledFromWasm); if (builder.has_simd() && (!CpuFeatures::SupportsWasmSimd128() || env->lower_simd)) { SimdScalarLowering(mcgraph, sig).LowerGraph(); // SimdScalarLowering changes all v128 to 4 i32, so update the machine // signature for the call to LowerInt64. size_t return_count = 0; size_t param_count = 0; for (auto ret : sig->returns()) { return_count += ret == MachineRepresentation::kSimd128 ? 4 : 1; } for (auto param : sig->parameters()) { param_count += param == MachineRepresentation::kSimd128 ? 4 : 1; } Signature<MachineRepresentation>::Builder sig_builder( mcgraph->zone(), return_count, param_count); for (auto ret : sig->returns()) { if (ret == MachineRepresentation::kSimd128) { for (int i = 0; i < 4; ++i) { sig_builder.AddReturn(MachineRepresentation::kWord32); } } else { sig_builder.AddReturn(ret); } } for (auto param : sig->parameters()) { if (param == MachineRepresentation::kSimd128) { for (int i = 0; i < 4; ++i) { sig_builder.AddParam(MachineRepresentation::kWord32); } } else { sig_builder.AddParam(param); } } sig = sig_builder.Build(); } builder.LowerInt64(sig); if (func_index >= FLAG_trace_wasm_ast_start && func_index < FLAG_trace_wasm_ast_end) { PrintRawWasmCode(allocator, func_body, env->module, wasm::kPrintLocals); } return true; } Vector<const char> GetDebugName(Zone* zone, int index) { // TODO(herhut): Use name from module if available. constexpr int kBufferLength = 24; EmbeddedVector<char, kBufferLength> name_vector; int name_len = SNPrintF(name_vector, "wasm-function#%d", index); DCHECK(name_len > 0 && name_len < name_vector.length()); char* index_name = zone->NewArray<char>(name_len); memcpy(index_name, name_vector.begin(), name_len); return Vector<const char>(index_name, name_len); } } // namespace wasm::WasmCompilationResult ExecuteTurbofanWasmCompilation( wasm::WasmEngine* wasm_engine, wasm::CompilationEnv* env, const wasm::FunctionBody& func_body, int func_index, Counters* counters, wasm::WasmFeatures* detected) { TRACE_EVENT2(TRACE_DISABLED_BY_DEFAULT("v8.wasm.detailed"), "wasm.CompileTopTier", "func_index", func_index, "body_size", func_body.end - func_body.start); Zone zone(wasm_engine->allocator(), ZONE_NAME, kCompressGraphZone); MachineGraph* mcgraph = zone.New<MachineGraph>( zone.New<Graph>(&zone), zone.New<CommonOperatorBuilder>(&zone), zone.New<MachineOperatorBuilder>( &zone, MachineType::PointerRepresentation(), InstructionSelector::SupportedMachineOperatorFlags(), InstructionSelector::AlignmentRequirements())); OptimizedCompilationInfo info(GetDebugName(&zone, func_index), &zone, CodeKind::WASM_FUNCTION); if (env->runtime_exception_support) { info.set_wasm_runtime_exception_support(); } if (info.trace_turbo_json()) { TurboCfgFile tcf; tcf << AsC1VCompilation(&info); } NodeOriginTable* node_origins = info.trace_turbo_json() ? zone.New<NodeOriginTable>(mcgraph->graph()) : nullptr; SourcePositionTable* source_positions = mcgraph->zone()->New<SourcePositionTable>(mcgraph->graph()); if (!BuildGraphForWasmFunction(wasm_engine->allocator(), env, func_body, func_index, detected, mcgraph, node_origins, source_positions)) { return wasm::WasmCompilationResult{}; } if (node_origins) { node_origins->AddDecorator(); } // Run the compiler pipeline to generate machine code. auto call_descriptor = GetWasmCallDescriptor(&zone, func_body.sig); if (mcgraph->machine()->Is32()) { call_descriptor = GetI32WasmCallDescriptor(&zone, call_descriptor); } if (ContainsSimd(func_body.sig) && (!CpuFeatures::SupportsWasmSimd128() || env->lower_simd)) { call_descriptor = GetI32WasmCallDescriptorForSimd(&zone, call_descriptor); } Pipeline::GenerateCodeForWasmFunction( &info, wasm_engine, mcgraph, call_descriptor, source_positions, node_origins, func_body, env->module, func_index); if (counters) { counters->wasm_compile_function_peak_memory_bytes()->AddSample( static_cast<int>(mcgraph->graph()->zone()->allocation_size())); } auto result = info.ReleaseWasmCompilationResult(); CHECK_NOT_NULL(result); // Compilation expected to succeed. DCHECK_EQ(wasm::ExecutionTier::kTurbofan, result->result_tier); return std::move(*result); } namespace { // Helper for allocating either an GP or FP reg, or the next stack slot. class LinkageLocationAllocator { public: template <size_t kNumGpRegs, size_t kNumFpRegs> constexpr LinkageLocationAllocator(const Register (&gp)[kNumGpRegs], const DoubleRegister (&fp)[kNumFpRegs]) : allocator_(wasm::LinkageAllocator(gp, fp)) {} LinkageLocation Next(MachineRepresentation rep) { MachineType type = MachineType::TypeForRepresentation(rep); if (IsFloatingPoint(rep)) { if (allocator_.CanAllocateFP(rep)) { int reg_code = allocator_.NextFpReg(rep); return LinkageLocation::ForRegister(reg_code, type); } } else if (allocator_.CanAllocateGP()) { int reg_code = allocator_.NextGpReg(); return LinkageLocation::ForRegister(reg_code, type); } // Cannot use register; use stack slot. int index = -1 - allocator_.NextStackSlot(rep); return LinkageLocation::ForCallerFrameSlot(index, type); } void SetStackOffset(int offset) { allocator_.SetStackOffset(offset); } int NumStackSlots() const { return allocator_.NumStackSlots(); } private: wasm::LinkageAllocator allocator_; }; } // namespace // General code uses the above configuration data. CallDescriptor* GetWasmCallDescriptor( Zone* zone, const wasm::FunctionSig* fsig, WasmGraphBuilder::UseRetpoline use_retpoline, WasmCallKind call_kind) { // The extra here is to accomodate the instance object as first parameter // and, when specified, the additional callable. bool extra_callable_param = call_kind == kWasmImportWrapper || call_kind == kWasmCapiFunction; int extra_params = extra_callable_param ? 2 : 1; LocationSignature::Builder locations(zone, fsig->return_count(), fsig->parameter_count() + extra_params); // Add register and/or stack parameter(s). LinkageLocationAllocator params(wasm::kGpParamRegisters, wasm::kFpParamRegisters); // The instance object. locations.AddParam(params.Next(MachineRepresentation::kTaggedPointer)); const size_t param_offset = 1; // Actual params start here. // Parameters are separated into two groups (first all untagged, then all // tagged parameters). This allows for easy iteration of tagged parameters // during frame iteration. const size_t parameter_count = fsig->parameter_count(); for (size_t i = 0; i < parameter_count; i++) { MachineRepresentation param = fsig->GetParam(i).machine_representation(); // Skip tagged parameters (e.g. any-ref). if (IsAnyTagged(param)) continue; auto l = params.Next(param); locations.AddParamAt(i + param_offset, l); } for (size_t i = 0; i < parameter_count; i++) { MachineRepresentation param = fsig->GetParam(i).machine_representation(); // Skip untagged parameters. if (!IsAnyTagged(param)) continue; auto l = params.Next(param); locations.AddParamAt(i + param_offset, l); } // Import call wrappers have an additional (implicit) parameter, the callable. // For consistency with JS, we use the JSFunction register. if (extra_callable_param) { locations.AddParam(LinkageLocation::ForRegister( kJSFunctionRegister.code(), MachineType::TaggedPointer())); } // Add return location(s). LinkageLocationAllocator rets(wasm::kGpReturnRegisters, wasm::kFpReturnRegisters); int parameter_slots = params.NumStackSlots(); if (ShouldPadArguments(parameter_slots)) parameter_slots++; rets.SetStackOffset(parameter_slots); const int return_count = static_cast<int>(locations.return_count_); for (int i = 0; i < return_count; i++) { MachineRepresentation ret = fsig->GetReturn(i).machine_representation(); auto l = rets.Next(ret); locations.AddReturn(l); } const RegList kCalleeSaveRegisters = 0; const RegList kCalleeSaveFPRegisters = 0; // The target for wasm calls is always a code object. MachineType target_type = MachineType::Pointer(); LinkageLocation target_loc = LinkageLocation::ForAnyRegister(target_type); CallDescriptor::Kind descriptor_kind; if (call_kind == kWasmFunction) { descriptor_kind = CallDescriptor::kCallWasmFunction; } else if (call_kind == kWasmImportWrapper) { descriptor_kind = CallDescriptor::kCallWasmImportWrapper; } else { DCHECK_EQ(call_kind, kWasmCapiFunction); descriptor_kind = CallDescriptor::kCallWasmCapiFunction; } CallDescriptor::Flags flags = use_retpoline ? CallDescriptor::kRetpoline : CallDescriptor::kNoFlags; return zone->New<CallDescriptor>( // -- descriptor_kind, // kind target_type, // target MachineType target_loc, // target location locations.Build(), // location_sig parameter_slots, // stack_parameter_count compiler::Operator::kNoProperties, // properties kCalleeSaveRegisters, // callee-saved registers kCalleeSaveFPRegisters, // callee-saved fp regs flags, // flags "wasm-call", // debug name StackArgumentOrder::kDefault, // order of the arguments in the stack 0, // allocatable registers rets.NumStackSlots() - parameter_slots); // stack_return_count } namespace { CallDescriptor* ReplaceTypeInCallDescriptorWith( Zone* zone, const CallDescriptor* call_descriptor, size_t num_replacements, MachineType input_type, MachineRepresentation output_type) { size_t parameter_count = call_descriptor->ParameterCount(); size_t return_count = call_descriptor->ReturnCount(); for (size_t i = 0; i < call_descriptor->ParameterCount(); i++) { if (call_descriptor->GetParameterType(i) == input_type) { parameter_count += num_replacements - 1; } } for (size_t i = 0; i < call_descriptor->ReturnCount(); i++) { if (call_descriptor->GetReturnType(i) == input_type) { return_count += num_replacements - 1; } } if (parameter_count == call_descriptor->ParameterCount() && return_count == call_descriptor->ReturnCount()) { return const_cast<CallDescriptor*>(call_descriptor); } LocationSignature::Builder locations(zone, return_count, parameter_count); // The last parameter may be the special callable parameter. In that case we // have to preserve it as the last parameter, i.e. we allocate it in the new // location signature again in the same register. bool has_callable_param = (call_descriptor->GetInputLocation(call_descriptor->InputCount() - 1) == LinkageLocation::ForRegister(kJSFunctionRegister.code(), MachineType::TaggedPointer())); LinkageLocationAllocator params(wasm::kGpParamRegisters, wasm::kFpParamRegisters); for (size_t i = 0, e = call_descriptor->ParameterCount() - (has_callable_param ? 1 : 0); i < e; i++) { if (call_descriptor->GetParameterType(i) == input_type) { for (size_t j = 0; j < num_replacements; j++) { locations.AddParam(params.Next(output_type)); } } else { locations.AddParam( params.Next(call_descriptor->GetParameterType(i).representation())); } } if (has_callable_param) { locations.AddParam(LinkageLocation::ForRegister( kJSFunctionRegister.code(), MachineType::TaggedPointer())); } LinkageLocationAllocator rets(wasm::kGpReturnRegisters, wasm::kFpReturnRegisters); rets.SetStackOffset(params.NumStackSlots()); for (size_t i = 0; i < call_descriptor->ReturnCount(); i++) { if (call_descriptor->GetReturnType(i) == input_type) { for (size_t j = 0; j < num_replacements; j++) { locations.AddReturn(rets.Next(output_type)); } } else { locations.AddReturn( rets.Next(call_descriptor->GetReturnType(i).representation())); } } return zone->New<CallDescriptor>( // -- call_descriptor->kind(), // kind call_descriptor->GetInputType(0), // target MachineType call_descriptor->GetInputLocation(0), // target location locations.Build(), // location_sig params.NumStackSlots(), // stack_parameter_count call_descriptor->properties(), // properties call_descriptor->CalleeSavedRegisters(), // callee-saved registers call_descriptor->CalleeSavedFPRegisters(), // callee-saved fp regs call_descriptor->flags(), // flags call_descriptor->debug_name(), // debug name call_descriptor->GetStackArgumentOrder(), // stack order call_descriptor->AllocatableRegisters(), // allocatable registers rets.NumStackSlots() - params.NumStackSlots()); // stack_return_count } } // namespace CallDescriptor* GetI32WasmCallDescriptor( Zone* zone, const CallDescriptor* call_descriptor) { return ReplaceTypeInCallDescriptorWith(zone, call_descriptor, 2, MachineType::Int64(), MachineRepresentation::kWord32); } CallDescriptor* GetI32WasmCallDescriptorForSimd( Zone* zone, CallDescriptor* call_descriptor) { return ReplaceTypeInCallDescriptorWith(zone, call_descriptor, 4, MachineType::Simd128(), MachineRepresentation::kWord32); } AssemblerOptions WasmAssemblerOptions() { AssemblerOptions options; // Relocation info required to serialize {WasmCode} for proper functions. options.record_reloc_info_for_serialization = true; options.enable_root_array_delta_access = false; return options; } AssemblerOptions WasmStubAssemblerOptions() { AssemblerOptions options; // Relocation info not necessary because stubs are not serialized. options.record_reloc_info_for_serialization = false; options.enable_root_array_delta_access = false; return options; } #undef FATAL_UNSUPPORTED_OPCODE #undef CALL_BUILTIN #undef WASM_INSTANCE_OBJECT_SIZE #undef WASM_INSTANCE_OBJECT_OFFSET #undef LOAD_INSTANCE_FIELD #undef LOAD_TAGGED_POINTER #undef LOAD_TAGGED_ANY #undef LOAD_FIXED_ARRAY_SLOT #undef LOAD_FIXED_ARRAY_SLOT_SMI #undef LOAD_FIXED_ARRAY_SLOT_PTR #undef LOAD_FIXED_ARRAY_SLOT_ANY #undef STORE_RAW #undef STORE_RAW_NODE_OFFSET #undef STORE_FIXED_ARRAY_SLOT_SMI #undef STORE_FIXED_ARRAY_SLOT_ANY } // namespace compiler } // namespace internal } // namespace v8
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
e4c716eb367ffa9cc78f715323d6ad706e8de070
39eac74fa6a244d15a01873623d05f480f45e079
/AddProcedureDlg.h
a91011ca2b5832a6a28366a1871b9e8a035aa542
[]
no_license
15831944/Practice
a8ac8416b32df82395bb1a4b000b35a0326c0897
ae2cde9c8f2fb6ab63bd7d8cd58701bd3513ec94
refs/heads/master
2021-06-15T12:10:18.730367
2016-11-30T15:13:53
2016-11-30T15:13:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,247
h
#if !defined(AFX_ADDPROCEDUREDLG_H__E29AB405_43D1_4649_B847_6475DB09B040__INCLUDED_) #define AFX_ADDPROCEDUREDLG_H__E29AB405_43D1_4649_B847_6475DB09B040__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // AddProcedureDlg.h : header file // ///////////////////////////////////////////////////////////////////////////// // CAddProcedureDlg dialog class CAddProcedureDlg : public CNxDialog { // Construction public: CAddProcedureDlg(CWnd* pParent); CArray<int, int> m_arProcIDs; CArray<int, int> m_arProcGroupIDs; CArray<CString, CString> m_arProcString; CArray<CString, CString> m_arProcGroupString; bool m_bProcedures; //Did they select procedures? (as opposed to procedure groups) bool m_bAllowProcGroups; //Will we allow them to select procedure groups? CString m_strProcWhereClause; //If you pass in a where clause, it will override any other where clause. CString m_strGroupWhereClause; //If you pass in a where clause, it will override any other where clause. virtual void Refresh(); // Dialog Data //{{AFX_DATA(CAddProcedureDlg) enum { IDD = IDD_ADD_PROCEDURE_DLG }; NxButton m_btnProcedures; NxButton m_btnProcedureGroups; CNxIconButton m_btnOK; CNxIconButton m_btnCancel; //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAddProcedureDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: NXDATALISTLib::_DNxDataListPtr m_procedureList; NXDATALISTLib::_DNxDataListPtr m_pProcGroupList; void UpdateArray(); // Generated message map functions //{{AFX_MSG(CAddProcedureDlg) virtual BOOL OnInitDialog(); virtual void OnOK(); virtual void OnCancel(); afx_msg void OnLeftClickProcedureList(long nRow, short nCol, long x, long y, long nFlags); afx_msg void OnProcGroups(); afx_msg void OnProcedures(); afx_msg void OnShowWindow(BOOL bShow, UINT nStatus); DECLARE_EVENTSINK_MAP() //}}AFX_MSG DECLARE_MESSAGE_MAP() void LoadFromArray(); }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_ADDPROCEDUREDLG_H__E29AB405_43D1_4649_B847_6475DB09B040__INCLUDED_)
[ "h.shah@WALD" ]
h.shah@WALD
fe6f9e0c70f206f1aa4d11bd7c42c489fca0964f
98cfd885fa41ce5d87cbfb9744527fc488a64ec7
/lib/wificlient/MemphisWiFiClient.h
078b8d68e0e47ec89eb5885456854b3ca0101d51
[ "MIT" ]
permissive
waffle-iron/memphis-controller
176cf845c6529b82bf5b54dd6835ed4faec5ebb3
a13f4810b95ef50e3ba77ede53400657512fb6a1
refs/heads/master
2021-01-11T06:43:08.820846
2016-09-22T01:02:01
2016-09-22T01:02:01
68,870,897
0
0
null
2016-09-22T01:02:02
2016-09-22T01:02:00
C++
UTF-8
C++
false
false
1,049
h
/* * MemphisWiFiClient.h * * Created on: 08.04.2016 * Author: scan */ #ifndef PROD_SOCKETS_WIFICLIENT_H_ #define PROD_SOCKETS_WIFICLIENT_H_ #include <WiFiClient.h> #ifdef ESP8266 #include <ESP8266WiFi.h> #endif class Timer; class DbgTrace_Port; class MemphisWiFiClient { public: MemphisWiFiClient(const char* wifi_ssid, const char* wifi_pw); virtual ~MemphisWiFiClient(); void begin(); void printWiFiStatusChanged(wl_status_t& old_wlStatus); wl_status_t getStatus(); bool isConnected(); inline WiFiClient* getClient() { return m_client; }; const char* getMacAddress() const; private: Timer* m_wifiConnectTimer; WiFiClient* m_client; DbgTrace_Port* m_trPort; const char* m_WiFi_ssid; const char* m_WiFi_pw; static const unsigned long s_connectInterval_ms; private: // forbidden functions MemphisWiFiClient(const MemphisWiFiClient& src); // copy constructor MemphisWiFiClient& operator = (const MemphisWiFiClient& src); // assignment operator }; #endif /* PROD_SOCKETS_WIFICLIENT_H_ */
[ "dieter.niklaus@contractors.roche.com" ]
dieter.niklaus@contractors.roche.com
42a88286ff4b34ffc07515448124fbea1135fd1a
3727e8c458021964b37c03cd1a6090298df75349
/euler/24.cpp
4459d503a852cce7b564bc2ac062de6ce71a6007
[]
no_license
descrip/competitive-programming
7e9b09ef48e87083d922b8bf46f58793249edce9
b2bdeba24569bbded7688d638b3c595529774e70
refs/heads/master
2021-01-11T19:53:17.724987
2017-01-19T05:40:10
2017-01-19T05:40:10
79,419,215
0
1
null
2017-11-02T18:13:21
2017-01-19T05:35:04
C++
UTF-8
C++
false
false
317
cpp
#include <bits/stdc++.h> using namespace std; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); vector<int> v = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; int cnt = 1; do{ ++cnt; if (cnt == 1000001) break; } while (next_permutation(v.begin(), v.end())); for (int i : v) cout << i; cout << '\n'; return 0;}
[ "jezhao1999@gmail.com" ]
jezhao1999@gmail.com
ce16b446715a08b82e4006713aeab5968556d237
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/collectd/gumtree/collectd_repos_function_178_collectd-5.7.1.cpp
41ba5c9936ac441d3bb0684f8e07495ac42d5778
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,525
cpp
static int config_add(oconfig_item_t *ci) { apache_t *st; int status; st = calloc(1, sizeof(*st)); if (st == NULL) { ERROR("apache plugin: calloc failed."); return (-1); } st->timeout = -1; status = cf_util_get_string(ci, &st->name); if (status != 0) { sfree(st); return (status); } assert(st->name != NULL); for (int i = 0; i < ci->children_num; i++) { oconfig_item_t *child = ci->children + i; if (strcasecmp("URL", child->key) == 0) status = cf_util_get_string(child, &st->url); else if (strcasecmp("Host", child->key) == 0) status = cf_util_get_string(child, &st->host); else if (strcasecmp("User", child->key) == 0) status = cf_util_get_string(child, &st->user); else if (strcasecmp("Password", child->key) == 0) status = cf_util_get_string(child, &st->pass); else if (strcasecmp("VerifyPeer", child->key) == 0) status = cf_util_get_boolean(child, &st->verify_peer); else if (strcasecmp("VerifyHost", child->key) == 0) status = cf_util_get_boolean(child, &st->verify_host); else if (strcasecmp("CACert", child->key) == 0) status = cf_util_get_string(child, &st->cacert); else if (strcasecmp("SSLCiphers", child->key) == 0) status = cf_util_get_string(child, &st->ssl_ciphers); else if (strcasecmp("Server", child->key) == 0) status = cf_util_get_string(child, &st->server); else if (strcasecmp("Timeout", child->key) == 0) status = cf_util_get_int(child, &st->timeout); else { WARNING("apache plugin: Option `%s' not allowed here.", child->key); status = -1; } if (status != 0) break; } /* Check if struct is complete.. */ if ((status == 0) && (st->url == NULL)) { ERROR("apache plugin: Instance `%s': " "No URL has been configured.", st->name); status = -1; } if (status == 0) { char callback_name[3 * DATA_MAX_NAME_LEN]; ssnprintf(callback_name, sizeof(callback_name), "apache/%s/%s", (st->host != NULL) ? st->host : hostname_g, (st->name != NULL) ? st->name : "default"); status = plugin_register_complex_read( /* group = */ NULL, /* name = */ callback_name, /* callback = */ apache_read_host, /* interval = */ 0, &(user_data_t){ .data = st, .free_func = apache_free, }); } if (status != 0) { apache_free(st); return (-1); } return (0); }
[ "993273596@qq.com" ]
993273596@qq.com
517ab642c512b0d71bc5ca5159ae7f60cc6ea87d
e1ea3cc99aec14af97be34246399e9dd789a12dc
/src/miner.h
d8e9e08bca2a34f5c515cc4a43c3581ba67f615a
[ "MIT" ]
permissive
wzpurdy/FYRE
c38b4206b3ff5d906a144070f874a7e561f967d2
e10b1d6003ec26abb517cc7b8c3fd4e3cc85032d
refs/heads/master
2020-04-29T04:57:12.280930
2019-03-12T04:33:12
2019-03-12T04:33:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,300
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef FYRE_MINER_H #define FYRE_MINER_H #include "primitives/block.h" #include <stdint.h> class CBlockIndex; class CChainParams; class CConnman; class CReserveKey; class CScript; class CWallet; namespace Consensus { struct Params; }; static const bool DEFAULT_GENERATE = false; static const int DEFAULT_GENERATE_THREADS = 1; static const bool DEFAULT_PRINTPRIORITY = false; struct CBlockTemplate { CBlock block; std::vector<CAmount> vTxFees; std::vector<int64_t> vTxSigOps; }; /** Run the miner threads */ void GenerateFyres(bool fGenerate, int nThreads, const CChainParams& chainparams, CConnman& connman); /** Generate a new block, without valid proof-of-work */ CBlockTemplate* CreateNewBlock(const CChainParams& chainparams, const CScript& scriptPubKeyIn); /** Modify the extranonce in a block */ void IncrementExtraNonce(CBlock* pblock, const CBlockIndex* pindexPrev, unsigned int& nExtraNonce); int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev); #endif // FYRE_MINER_H
[ "48378798+FyreCurrency@users.noreply.github.com" ]
48378798+FyreCurrency@users.noreply.github.com
f78df556bc202f04e5d83b471948c6d7ae65102c
8f249c69aba5199480897310cb2e2fe3689a442d
/FileManager/stdafx.h
0050bfd58c57f983c27601cab95164d2361b44b3
[]
no_license
chxj1980/FileManager
471be84c3cb76e7862f040d11ba40e4b2543f75c
a5499c6b11c6ee3947f5f4452593b01edd23c81c
refs/heads/master
2021-06-17T17:23:53.422387
2017-05-16T13:26:38
2017-05-16T13:26:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,803
h
// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, // but are changed infrequently #pragma once #ifndef VC_EXTRALEAN #define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers #endif #include "targetver.h" #define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit #define _CRT_SECURE_NO_DEPRECATE #define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1 // turns off MFC's hiding of some common and often safely ignored warning messages #define _AFX_ALL_WARNINGS #include <afxwin.h> // MFC core and standard components #include <afxext.h> // MFC extensions #include <afxdisp.h> // MFC Automation classes #include <iostream> #ifndef _AFX_NO_OLE_SUPPORT #include <afxdtctl.h> // MFC support for Internet Explorer 4 Common Controls #endif #ifndef _AFX_NO_AFXCMN_SUPPORT #include <afxcmn.h> // MFC support for Windows Common Controls #endif // _AFX_NO_AFXCMN_SUPPORT #include <afxcontrolbars.h> // MFC support for ribbons and control bars #ifdef _UNICODE #if defined _M_IX86 #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"") #elif defined _M_X64 #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\"") #else #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") #endif #endif
[ "707010543@qq.com" ]
707010543@qq.com
3d89d19df7495d015400000495bbe24bb723db63
8453f7ef12f5f6b334efdd650f90d481d0e8d7e6
/Assignment11/mainfile.cpp
ceea202e9b8f238dbfecf7889b777e080f01c9ab
[]
no_license
bipinthakur002/Logic_Building_Programs
2ac810437301e312b09c0b13432c05d8739c9df0
bbc4186ddc8cca851d63a45f0f00ba692b82da3a
refs/heads/master
2020-03-28T06:58:02.034752
2018-10-14T19:31:40
2018-10-14T19:31:40
147,872,398
1
0
null
null
null
null
UTF-8
C++
false
false
3,267
cpp
#include"Header.h" int main() { /* program 1 int i = 0,size=0; int *arr = NULL; printf("Enter the size of array:\n"); scanf_s("%d", &size); arr = (int *)malloc(sizeof(int)*size); printf("Enter Elements in the array:\n"); for (i = 0;i < size;i++) { scanf_s("%d", &arr[i]); } ReverseArray(arr, size); return 0; */ /* program 2 int i = 0, size = 0; int *arr = NULL; printf("Enter the size of array:\n"); scanf_s("%d", &size); arr = (int *)malloc(sizeof(int)*size); printf("Enter Elements in the array:\n"); for (i = 0;i < size;i++) { scanf_s("%d", &arr[i]); } SumArray(arr, size); return 0; */ /* program 4 int size = 0, i=0,result=0; char *arr = '\0'; printf("Enter number of elements:\n"); scanf_s("%d", &size); arr = (char *)malloc(sizeof(char)*size); printf("Enter the elements in the array:\n"); for (i = 0;i <size;i++) { scanf_s(" %c", &arr[i]); } result = ArrayCapital(arr,size); printf("Number of Capital Letters are : %d", result); return 0; */ /* program 5 int size = 0, i = 0, result = 0; float *arr = NULL; printf("Enter Size of Array:\n"); scanf_s("%d", &size); arr = (float *)malloc(sizeof(float)*size); printf("Enter the Percentage :\n"); for (i = 0;i <size;i++) { scanf_s("%f", &arr[i]); } Percentage(arr, size); return 0; */ /* program 6 int size = 0, i = 0, result = 0; char *arr = '\0'; printf("Enter Size of Array:\n"); scanf_s("%d", &size); arr = (char *)malloc(sizeof(char)*size); printf("Enter the Characters :\n"); for (i = 0;i <size;i++) { scanf_s(" %c", &arr[i]); } ArrayReplace(arr, size); return 0; */ /* program 7 int size = 0, i = 0, result = 0; char *arr = '\0'; printf("Enter Size of Array:\n"); scanf_s("%d", &size); arr = (char *)malloc(sizeof(char)*size); printf("Enter the Characters :\n"); for (i = 0;i <size;i++) { scanf_s(" %c", &arr[i]); } result=ArrayCount(arr, size); printf("%d\t", result); return 0; */ /* program 8 int size = 0, i = 0, result = 0; char *arr = '\0',ch='\0'; printf("Enter Size of Array:\n"); scanf_s("%d", &size); arr = (char *)malloc(sizeof(char)*size); printf("Enter the Characters in the array :\n"); for (i = 0;i <size;i++) { scanf_s(" %c", &arr[i]); } printf("Enter the character to be searched:\n"); scanf_s(" %c", &ch); result=Search(arr, size,ch); printf("\n%d", result); return 0; */ /* program int size = 0, i = 0, result = 0; char *arr = NULL ,ch='\0'; printf("Enter Size of Array:\n"); scanf_s("%d",&size); arr = (char *)malloc(sizeof(char)*size); printf("Enter the Characters in the array :\n"); for (i = 0 ; i < size ; i++) { scanf_s(" %c", &arr[i]); } result=Difference(arr,size); if (result < 0) { result = -result; } printf("%d\t", result); return 0; */ /* program 10 int size = 0, i = 0; int *arr = NULL; printf("Enter Size of Array:\n"); scanf_s("%d",&size); arr = (int *)malloc(sizeof(int)*size); printf("Enter the Characters in the array :\n"); for (i = 0 ; i < size ; i++) { scanf_s("%d",&arr[i]); } pattern(arr,size); return 0; */ }
[ "noreply@github.com" ]
noreply@github.com
8141d8d890fc3f59f1e2ce5ce99f25339807fa48
96d8eee8791f51109242138355b469053301162f
/dev/a2-carsoccer/ball.h
a539cec4ca59954eeaaab213cc4a4caa564ef18a
[]
no_license
xkqin/CSCI4611_Graphic_Games
ea2f81779d57cfc460f6a4f101960381d08015d5
1a556b4632b868b899c96486fa3802166a2f06fa
refs/heads/master
2021-09-13T13:31:10.130614
2018-04-30T18:05:50
2018-04-30T18:05:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
921
h
/** CSci-4611 Assignment 2: Car Soccer */ #ifndef BALL_H_ #define BALL_H_ #include <mingfx.h> /// Small data structure for a ball class Ball { public: /// The constructor sets the radius and calls Reset() to start the ball at /// the center of the field Ball() : radius_(2.0) { Reset(); } /// Nothing special needed in the constructor virtual ~Ball() {} void Reset() { position_ = Point3(0, radius_, 0); } float radius() { return radius_; } Point3 position() { return position_; } float collision_radius(){return radius_;} Vector3 velocity() {return velocity_;} void set_position(const Point3 &p) { position_ = p; } void set_velocity(const Vector3 &v) { velocity_ = v; } private: // You will probably need to store some additional data here, e.g., velocity Vector3 velocity_; Point3 position_; float radius_; }; #endif
[ "administrator@er-10-144-150-55.wireless.umn.edu" ]
administrator@er-10-144-150-55.wireless.umn.edu
bd943ea1a5f65c7bdc48e0b94dfcf2a4786243c9
27da58458e8f4a70adcb0c1d8a7ed84e8342367f
/Libs/BaseLib/SharedLib/GameObject.cpp
ed60aa1d77e97324b5cb5c9325171d56d6e1ed5a
[]
no_license
WiZFramework/BaseCross
f5c5d41abb1bfc8c5e7e0fc397a522318c95a7d2
3166d3870e818c947c2b598ff9d629c58780168d
refs/heads/master
2020-05-22T02:44:26.650636
2019-09-17T17:46:08
2019-09-17T17:46:08
64,080,808
16
4
null
null
null
null
SHIFT_JIS
C++
false
false
78,601
cpp
/*! @file GameObject.cpp @brief ゲームオブジェクト、ステージ実体 @copyright Copyright (c) 2017 WiZ Tamura Hiroki,Yamanoi Yasushi. */ #include "stdafx.h" namespace basecross { //-------------------------------------------------------------------------------------- // struct GameObject::Impl; // 用途: コンポーネントImplクラス //-------------------------------------------------------------------------------------- struct GameObject::Impl { bool m_UpdateActive; //updateするかどうか bool m_DrawActive; //Drawするかどうか bool m_AlphaActive; //透明かどうか int m_DrawLayer; //描画レイヤー set<wstring> m_Tag; //タグ set<int> m_NumTag; //数字タグ bool m_SpriteDraw; //スプライトとして描画するかどうか weak_ptr<Stage> m_Stage; //所属ステージ map<type_index, shared_ptr<Component> > m_CompMap; list<type_index> m_CompOrder; //コンポーネント実行順番 shared_ptr<Rigidbody> m_Rigidbody; //Rigidbodyは別にする shared_ptr<Collision> m_Collision; //Collisionも別にする shared_ptr<Transform> m_Transform; //Transformも別にする //行動のマップ map<type_index, shared_ptr<Behavior>> m_BehaviorMap; Impl(const shared_ptr<Stage>& StagePtr) : m_UpdateActive(true), m_DrawActive(true), m_AlphaActive(false), m_DrawLayer(0), m_SpriteDraw(false), m_Stage(StagePtr) {} ~Impl() {} }; //-------------------------------------------------------------------------------------- /// ゲーム配置オブジェクト親クラス //-------------------------------------------------------------------------------------- //privateメンバ shared_ptr<Component> GameObject::SearchComponent(type_index TypeIndex)const { auto it = pImpl->m_CompMap.find(TypeIndex); if (it != pImpl->m_CompMap.end()) { return it->second; } return nullptr; } shared_ptr<Transform> GameObject::GetTransform()const { return pImpl->m_Transform; } shared_ptr<Rigidbody> GameObject::GetRigidbody()const { return pImpl->m_Rigidbody; } shared_ptr<Collision> GameObject::GetCollision()const { return pImpl->m_Collision; } shared_ptr<CollisionSphere> GameObject::GetCollisionSphere()const { return dynamic_pointer_cast<CollisionSphere>(pImpl->m_Collision); } shared_ptr<CollisionCapsule> GameObject::GetCollisionCapsule()const { return dynamic_pointer_cast<CollisionCapsule>(pImpl->m_Collision); } shared_ptr<CollisionObb> GameObject::GetCollisionObb()const { return dynamic_pointer_cast<CollisionObb>(pImpl->m_Collision); } shared_ptr<CollisionTriangles> GameObject::GetCollisionTriangles()const { return dynamic_pointer_cast<CollisionTriangles>(pImpl->m_Collision); } shared_ptr<CollisionRect> GameObject::GetCollisionRect()const { return dynamic_pointer_cast<CollisionRect>(pImpl->m_Collision); } void GameObject::SetRigidbody(const shared_ptr<Rigidbody>& Ptr) { Ptr->AttachGameObject(GetThis<GameObject>()); pImpl->m_Rigidbody = Ptr; } void GameObject::SetCollision(const shared_ptr<Collision>& Ptr) { Ptr->AttachGameObject(GetThis<GameObject>()); pImpl->m_Collision = Ptr; } void GameObject::SetTransform(const shared_ptr<Transform>& Ptr) { Ptr->AttachGameObject(GetThis<GameObject>()); pImpl->m_Transform = Ptr; } void GameObject::AddMakedComponent(type_index TypeIndex, const shared_ptr<Component>& Ptr) { if (!SearchComponent(TypeIndex)) { //そのコンポーネントがまだなければ新規登録 pImpl->m_CompOrder.push_back(TypeIndex); } //mapに追加もしくは更新 pImpl->m_CompMap[TypeIndex] = Ptr; Ptr->AttachGameObject(GetThis<GameObject>()); } map<type_index, shared_ptr<Component> >& GameObject::GetCompoMap()const { return pImpl->m_CompMap; } void GameObject::RemoveTgtComponent(type_index TypeIndex) { //順番リストを検証して削除 auto it = pImpl->m_CompOrder.begin(); while (it != pImpl->m_CompOrder.end()) { if (*it == TypeIndex) { auto it2 = pImpl->m_CompMap.find(*it); if (it2 != pImpl->m_CompMap.end()) { //指定の型のコンポーネントが見つかった //mapデータを削除 pImpl->m_CompMap.erase(it2); } pImpl->m_CompOrder.erase(it); return; } it++; } } map<type_index, shared_ptr<Behavior> >& GameObject::GetBehaviorMap() const { return pImpl->m_BehaviorMap; } shared_ptr<Behavior> GameObject::SearchBehavior(type_index TypeIndex)const { auto it = pImpl->m_BehaviorMap.find(TypeIndex); if (it != pImpl->m_BehaviorMap.end()) { return it->second; } return nullptr; } void GameObject::AddMakedBehavior(type_index TypeIndex, const shared_ptr<Behavior>& Ptr) { //mapに追加もしくは更新 pImpl->m_BehaviorMap[TypeIndex] = Ptr; } GameObject::GameObject(const shared_ptr<Stage>& StagePtr) : ObjectInterface(), ShapeInterface(), pImpl(new Impl(StagePtr)) { } GameObject::~GameObject() {} //アクセサ bool GameObject::IsUpdateActive() const { return pImpl->m_UpdateActive; } bool GameObject::GetUpdateActive() const { return pImpl->m_UpdateActive; } void GameObject::SetUpdateActive(bool b) { pImpl->m_UpdateActive = b; } bool GameObject::IsDrawActive() const { return pImpl->m_DrawActive; } bool GameObject::GetDrawActive() const { return pImpl->m_DrawActive; } void GameObject::SetDrawActive(bool b) { pImpl->m_DrawActive = b; } bool GameObject::IsAlphaActive() const { return pImpl->m_AlphaActive; } bool GameObject::GetAlphaActive() const { return pImpl->m_AlphaActive; } void GameObject::SetAlphaActive(bool b) { pImpl->m_AlphaActive = b; } //スプライトとしてDrawするかどうか bool GameObject::IsSpriteDraw() const {return pImpl->m_SpriteDraw;} bool GameObject::GetSpriteDraw() const {return pImpl->m_SpriteDraw;} void GameObject::SetSpriteDraw(bool b) {pImpl->m_SpriteDraw = b;} //描画レイヤーの取得と設定 int GameObject::GetDrawLayer() const {return pImpl->m_DrawLayer;} void GameObject::SetDrawLayer(int l) {pImpl->m_DrawLayer = l;} //タグの検証と設定 set<wstring>& GameObject::GetTagSet() const { return pImpl->m_Tag; } bool GameObject::FindTag(const wstring& tagstr) const { if (pImpl->m_Tag.find(tagstr) == pImpl->m_Tag.end()) { return false; } return true; } void GameObject::AddTag(const wstring& tagstr) { if (tagstr == L"") { //空白なら例外 throw BaseException( L"設定するタグが空です", L"if (tagstr == L"")", L"GameObject::AddTag()" ); } pImpl->m_Tag.insert(tagstr); } void GameObject::RemoveTag(const wstring& tagstr) { pImpl->m_Tag.erase(tagstr); } //数字タグの検証と設定 set<int>& GameObject::GetNumTagSet() const { return pImpl->m_NumTag; } bool GameObject::FindNumTag(int numtag) const { if (pImpl->m_NumTag.find(numtag) == pImpl->m_NumTag.end()) { return false; } return true; } void GameObject::AddNumTag(int numtag) { pImpl->m_NumTag.insert(numtag); } void GameObject::RemoveNumTag(int numtag) { pImpl->m_NumTag.erase(numtag); } shared_ptr<Stage> GameObject::GetStage(bool ExceptionActive) const { auto shptr = pImpl->m_Stage.lock(); if (shptr) { return shptr; } else { if (ExceptionActive) { throw BaseException( L"所属ステージがnullです。自分自身がステージではありませんか?", L"if (!shptr)", L"GameObject::GetStage()" ); } else { return nullptr; } } // 所属ステージがnullだった // 自分自身がステージの可能性がある return nullptr; } void GameObject::SetStage(const shared_ptr<Stage>& stage) { pImpl->m_Stage = stage; } void GameObject::ComponentUpdate() { auto TMptr = GetComponent<Transform>(); auto RigidPtr = GetComponent<Rigidbody>(false); //マップを検証してUpdate list<type_index>::iterator it = pImpl->m_CompOrder.begin(); while (it != pImpl->m_CompOrder.end()) { map<type_index, shared_ptr<Component> >::const_iterator it2; it2 = pImpl->m_CompMap.find(*it); if (it2 != pImpl->m_CompMap.end()) { //指定の型のコンポーネントが見つかった if (it2->second->IsUpdateActive()) { it2->second->OnUpdate(); } } it++; } if (RigidPtr && RigidPtr->IsUpdateActive()) { //RigidbodyがあればUpdate() RigidPtr->OnUpdate(); } //TransformのUpdate if (TMptr->IsUpdateActive()) { TMptr->OnUpdate(); } } void GameObject::CollisionReset() { auto CollisionPtr = GetComponent<Collision>(false); if (CollisionPtr) { CollisionPtr->SetToBeforeHitObject(); CollisionPtr->ClearHitObject(); } } void GameObject::ToMessageCollision() { auto CollisionPtr = GetComponent<Collision>(false); if (CollisionPtr) { auto& VecPtr = CollisionPtr->GetNewHitObjectVec(); if (!VecPtr.empty()) { OnCollision(VecPtr); } VecPtr = CollisionPtr->GetExcuteHitObjectVec(); if (!VecPtr.empty()) { OnCollisionExcute(VecPtr); } VecPtr = CollisionPtr->GetExitHitObjectVec(); if (!VecPtr.empty()) { OnCollisionExit(VecPtr); } } } void GameObject::DrawShadowmap() { auto shadowptr = GetDynamicComponent<Shadowmap>(false); if (shadowptr) { shadowptr->OnDraw(); } } void GameObject::ComponentDraw() { //Transformがなければ例外 auto Tptr = GetComponent<Transform>(); auto RigidPtr = GetComponent<Rigidbody>(false); auto CollisionPtr = GetComponent<Collision>(false); //マップを検証してDraw list<type_index>::iterator it = pImpl->m_CompOrder.begin(); while (it != pImpl->m_CompOrder.end()) { map<type_index, shared_ptr<Component> >::const_iterator it2; it2 = pImpl->m_CompMap.find(*it); //指定の型のコンポーネントが見つかった if (it2 != pImpl->m_CompMap.end() && !dynamic_pointer_cast<Shadowmap>(it2->second)) { //シャドウマップ以外なら実行 //そのコンポーネントの子コンポーネントの描画 if (it2->second->IsDrawActive()) { it2->second->OnDraw(); } } it++; } //派生クラス対策 if (RigidPtr && RigidPtr->IsDrawActive()) { //RigidbodyがあればDraw() RigidPtr->OnDraw(); } if (CollisionPtr && CollisionPtr->IsDrawActive()) { //CollisionがあればDraw() CollisionPtr->OnDraw(); } //TransformのDraw if (Tptr->IsDrawActive()) { Tptr->OnDraw(); } } void GameObject::OnPreCreate() { //Transform必須 AddComponent<Transform>(); } const shared_ptr<Camera>& GameObject::OnGetDrawCamera()const { //デフォルトはビューのカメラから取り出す auto StageView = GetStage()->GetView(); return StageView->GetTargetCamera(); } const Light& GameObject::OnGetDrawLight()const { //ステージからライトを取り出す auto StageLight = GetStage()->GetLight(); return StageLight->GetTargetLight(); } void GameObject::OnGet2DDrawProjMatrix(bsm::Mat4x4& ProjMatrix) const { auto viewport = GetStage()->GetView()->GetTargetViewport(); float w = static_cast<float>(viewport.Width); float h = static_cast<float>(viewport.Height); ProjMatrix = XMMatrixOrthographicLH(w, h, viewport.MinDepth, viewport.MaxDepth); } void GameObject::OnDraw() { //コンポーネント描画 //派生クラスで多重定義する場合は //コンポーネント描画する場合は //GameObject::Draw()を呼び出す ComponentDraw(); } void GameObject::DestroyGameObject() { auto TMptr = GetComponent<Transform>(); auto RigidPtr = GetComponent<Rigidbody>(false); //マップを検証してOnDestroy list<type_index>::iterator it = pImpl->m_CompOrder.begin(); while (it != pImpl->m_CompOrder.end()) { map<type_index, shared_ptr<Component> >::const_iterator it2; it2 = pImpl->m_CompMap.find(*it); if (it2 != pImpl->m_CompMap.end()) { //指定の型のコンポーネントが見つかった if (it2->second->IsUpdateActive()) { it2->second->OnDestroy(); } } it++; } if (RigidPtr) { //RigidbodyがあればOnDestroy() RigidPtr->OnDestroy(); } //TransformのOnDestroy TMptr->OnDestroy(); //自分自身のOnDestroy() OnDestroy(); } //-------------------------------------------------------------------------------------- // 用途: Implイディオム //-------------------------------------------------------------------------------------- struct GameObjectGroup::Impl { vector< weak_ptr<GameObject> > m_Group; Impl() {} ~Impl() {} }; //-------------------------------------------------------------------------------------- // class GameObjectGroup; //-------------------------------------------------------------------------------------- GameObjectGroup::GameObjectGroup() : ObjectInterface(), pImpl(new Impl()) {} GameObjectGroup::~GameObjectGroup() {} //アクセサ const vector< weak_ptr<GameObject> >& GameObjectGroup::GetGroupVector() const { return pImpl->m_Group; } shared_ptr<GameObject> GameObjectGroup::at(size_t index) { if (index >= pImpl->m_Group.size()) { wstring msg = Util::UintToWStr(index); msg += L" >= "; msg += Util::UintToWStr(pImpl->m_Group.size()); throw BaseException( L"インデックスが範囲外です", msg, L"GameObjectGroup::at()" ); } if (pImpl->m_Group.at(index).expired()) { wstring msg = Util::UintToWStr(index); throw BaseException( L"そのインデックスのオブジェクトは無効です。", msg, L"GameObjectGroup::at()" ); } return pImpl->m_Group.at(index).lock(); } size_t GameObjectGroup::size() const { return pImpl->m_Group.size(); } //操作 void GameObjectGroup::IntoGroup(const shared_ptr<GameObject>& Obj) { pImpl->m_Group.push_back(Obj); } void GameObjectGroup::AllClear() { pImpl->m_Group.clear(); } //-------------------------------------------------------------------------------------- // struct Particle::Impl; // 用途: Implイディオム //-------------------------------------------------------------------------------------- struct Particle::Impl { DrawOption m_DrawOption; //表示オプション vector<ParticleSprite> m_ParticleSpriteVec; //保存しておくスプライトの配列 bsm::Vec3 m_EmitterPos; //エミッター位置 float m_TotalTime; //タイマー制御する場合に使用する変数 float m_MaxTime; //このパーティクル集合体の表示時間 weak_ptr<TextureResource> m_TextureResource; //テクスチャ Impl(size_t Count, DrawOption Option) : m_DrawOption(Option), m_ParticleSpriteVec(Count), m_EmitterPos(0, 0, 0), m_TotalTime(0), m_MaxTime(0) {} ~Impl() {} }; //-------------------------------------------------------------------------------------- // class Particle; // 用途: パーティクル // *1つのエミッターを持ち、複数のParticleSpriteを保持する //-------------------------------------------------------------------------------------- Particle::Particle(size_t Count, DrawOption Option) : ObjectInterface(), pImpl(new Impl(Count, Option)) {} Particle::~Particle() {} Particle::DrawOption Particle::GetDrawOption()const { return pImpl->m_DrawOption; } void Particle::SetDrawOption(DrawOption Option) { pImpl->m_DrawOption = Option; } const bsm::Vec3& Particle::GetEmitterPos() const { return pImpl->m_EmitterPos; } void Particle::SetEmitterPos(const bsm::Vec3& Pos) { pImpl->m_EmitterPos = Pos; } float Particle::GetTotalTime() const { return pImpl->m_TotalTime; } void Particle::SetTotalTime(float f) { pImpl->m_TotalTime = f; } void Particle::AddTotalTime(float f) { pImpl->m_TotalTime += f; } float Particle::GetMaxTime() const { return pImpl->m_MaxTime; } void Particle::SetMaxTime(float f) { pImpl->m_MaxTime = f; } bool Particle::IsActive() const { for (auto Psp : pImpl->m_ParticleSpriteVec) { if (Psp.m_Active) { //1つでもアクティブがあればtrue return true; } } return false; } bool Particle::IsAllActive() const { for (auto Psp : pImpl->m_ParticleSpriteVec) { if (!Psp.m_Active) { //1つでも非アクティブがあればfalse return false; } } return true; } void Particle::SetAllActive() { for (auto Psp : pImpl->m_ParticleSpriteVec) { Psp.m_Active = true; } } void Particle::SetAllNoActive() { for (auto Psp : pImpl->m_ParticleSpriteVec) { Psp.m_Active = false; } } void Particle::Reflesh(size_t Count, Particle::DrawOption Option) { pImpl->m_DrawOption = Option; pImpl->m_EmitterPos = bsm::Vec3(0, 0, 0); pImpl->m_TotalTime = 0; pImpl->m_MaxTime = 0; pImpl->m_ParticleSpriteVec.clear(); pImpl->m_ParticleSpriteVec.resize(Count); for (auto Psp : pImpl->m_ParticleSpriteVec) { Psp.Reflesh(); } } vector<ParticleSprite>& Particle::GetParticleSpriteVec() const { return pImpl->m_ParticleSpriteVec; } shared_ptr<TextureResource> Particle::GetTextureResource(bool ExceptionActive) const { if (!pImpl->m_TextureResource.expired()) { return pImpl->m_TextureResource.lock(); } else { if (ExceptionActive) { throw BaseException( L"テクスチャリソースが見つかりません", L"if (pImpl->m_Texture.expired())", L"Particle::GetTextureResource()" ); } } return nullptr; } void Particle::SetTextureResource(const wstring& ResKey) { try { if (ResKey == L"") { throw BaseException( L"テクスチャキーが空白です", L"if (ResKey == L\"\"", L"Particle::SetTextureResource()" ); } pImpl->m_TextureResource = App::GetApp()->GetResource<TextureResource>(ResKey); } catch (...) { throw; } } void Particle::SetTextureResource(const shared_ptr<TextureResource>& TextureResourcePtr) { pImpl->m_TextureResource = TextureResourcePtr; } void Particle::Draw(const shared_ptr<ParticleManager>& Manager) { for (auto Psp : pImpl->m_ParticleSpriteVec) { if (Psp.m_Active && !pImpl->m_TextureResource.expired()) { Manager->AddParticle(Psp, GetDrawOption(), GetEmitterPos(), pImpl->m_TextureResource.lock()); } } } //-------------------------------------------------------------------------------------- // struct MultiParticle::Impl; // 用途: Implイディオム //-------------------------------------------------------------------------------------- struct MultiParticle::Impl { vector< shared_ptr<Particle> > m_ParticleVec; //加算処理するかどうか bool m_AddType; Impl(): m_AddType(false) {} ~Impl() {} }; //-------------------------------------------------------------------------------------- // class MultiParticle : public GameObject; // 用途: マルチエフェクト //-------------------------------------------------------------------------------------- MultiParticle::MultiParticle(const shared_ptr<Stage>& StagePtr) : GameObject(StagePtr), pImpl(new Impl()) {} MultiParticle::~MultiParticle() {} vector< shared_ptr<Particle> >& MultiParticle::GetParticleVec() const { return pImpl->m_ParticleVec; } bool MultiParticle::GetAddType() const { return pImpl->m_AddType; } bool MultiParticle::IsAddType() const { return pImpl->m_AddType; } void MultiParticle::SetAddType(bool b) { pImpl->m_AddType = b; } shared_ptr<Particle> MultiParticle::InsertParticle(size_t Count, Particle::DrawOption Option) { for (size_t i = 0; i < pImpl->m_ParticleVec.size(); i++) { //もし非アクティブのパーティクルがあれば初期化してリターン if (!pImpl->m_ParticleVec[i]->IsActive()) { pImpl->m_ParticleVec[i]->Reflesh(Count, Option); return pImpl->m_ParticleVec[i]; } } //新しいパーティクルを追加 shared_ptr<Particle> ParticlePtr = ObjectFactory::Create<Particle>(Count, Option); pImpl->m_ParticleVec.push_back(ParticlePtr); return ParticlePtr; } void MultiParticle::OnPreCreate() { GameObject::OnPreCreate(); //透明処理のみ指定しておく SetAlphaActive(true); } void MultiParticle::OnUpdate() { //前回のターンからの時間 float ElapsedTime = App::GetApp()->GetElapsedTime(); for (auto ParticlePtr : GetParticleVec()) { ParticlePtr->AddTotalTime(ElapsedTime); for (auto& rParticleSprite : ParticlePtr->GetParticleSpriteVec()) { if (rParticleSprite.m_Active) { //移動速度に従って移動させる rParticleSprite.m_LocalPos += rParticleSprite.m_Velocity * ElapsedTime; if (ParticlePtr->GetTotalTime() >= ParticlePtr->GetMaxTime()) { //制限時間になったら rParticleSprite.m_Active = false; } } } } } void MultiParticle::OnDraw() { if (pImpl->m_ParticleVec.size() > 0) { for (auto Ptr : pImpl->m_ParticleVec) { if (Ptr->IsActive()) { Ptr->Draw(GetStage()->GetParticleManager(IsAddType())); } } } } //-------------------------------------------------------------------------------------- // struct ParticleManager::Impl; // 用途: Implイディオム //-------------------------------------------------------------------------------------- struct ParticleManager::Impl { bool m_ZBufferUse; //Zバッファを使用するかどうか bool m_SamplerWrap; //サンプラーのラッピングするかどうか //加算処理するかどうか bool m_AddType; Impl(bool AddType) : m_ZBufferUse(true), m_SamplerWrap(false), m_AddType(AddType) {} ~Impl() {} }; //-------------------------------------------------------------------------------------- // class ParticleManager : public GameObject; // 用途: パーティクルマネージャ //-------------------------------------------------------------------------------------- //構築と消滅 ParticleManager::ParticleManager(const shared_ptr<Stage>& StagePtr, bool AddType) : GameObject(StagePtr), pImpl(new Impl(AddType)) {} ParticleManager::~ParticleManager() {} //初期化 void ParticleManager::OnCreate() { try { //上限2000でマネージャ作成 AddComponent<PCTParticleDraw>(2000,pImpl->m_AddType); //透明処理のみ指定しておく SetAlphaActive(true); } catch (...) { throw; } } bool ParticleManager::GetZBufferUse() const { return pImpl->m_ZBufferUse; } bool ParticleManager::IsZBufferUse() const { return pImpl->m_ZBufferUse; } void ParticleManager::SetZBufferUse(bool b) { pImpl->m_ZBufferUse = b; } bool ParticleManager::GetSamplerWrap() const { return pImpl->m_SamplerWrap; } bool ParticleManager::IsSamplerWrap() const { return pImpl->m_SamplerWrap; } void ParticleManager::SetSamplerWrap(bool b) { pImpl->m_SamplerWrap = b; } void ParticleManager::AddParticle(const ParticleSprite& rParticleSprite, Particle::DrawOption Option, const bsm::Vec3& EmitterPos, const shared_ptr<TextureResource>& TextureRes) { auto DrawCom = GetComponent<PCTParticleDraw>(); auto StageView = GetStage()->GetView(); auto PtrCamera = StageView->GetTargetCamera(); //カメラの位置 bsm::Vec3 CameraEye = PtrCamera->GetEye(); bsm::Vec3 CameraAt = PtrCamera->GetAt(); bsm::Vec3 WorldPos = rParticleSprite.m_LocalPos + EmitterPos; float ToCaneraLength = bsm::length(CameraEye - WorldPos); bsm::Vec3 LocalScale; LocalScale.x = rParticleSprite.m_LocalScale.x; LocalScale.y = rParticleSprite.m_LocalScale.y; LocalScale.z = 1.0f; bsm::Vec3 Temp; bsm::Quat Qt; bsm::Mat4x4 RotMatrix; // bsm::Vec4 dammi(0, 0, 0, 0); bsm::Vec3 DefUp(0, 1.0f, 0); switch (Option) { case Particle::DrawOption::Billboard: { Temp = CameraAt - CameraEye; bsm::Vec2 TempVec2(Temp.x, Temp.z); if (bsm::length(TempVec2) < 0.1f) { DefUp = bsm::Vec3(0, 0, 1.0f); } Temp.normalize(); RotMatrix = XMMatrixLookAtLH(bsm::Vec3(0, 0, 0), Temp, DefUp); RotMatrix = bsm::inverse(RotMatrix); Qt = RotMatrix.quatInMatrix(); Qt.normalize(); } break; case Particle::DrawOption::Faceing: { Temp = WorldPos - CameraEye; bsm::Vec2 TempVec2(Temp.x, Temp.z); if (bsm::length(TempVec2) < 0.1f) { DefUp = bsm::Vec3(0, 0, 1.0f); } RotMatrix = XMMatrixLookAtLH(bsm::Vec3(0, 0, 0), Temp, DefUp); RotMatrix = bsm::inverse(RotMatrix); Qt = RotMatrix.quatInMatrix(); Qt.normalize(); } break; case Particle::DrawOption::FaceingY: Temp = WorldPos - CameraEye; Temp.normalize(); Qt = XMQuaternionRotationRollPitchYaw(0, atan2(Temp.x, Temp.z), 0); Qt.normalize(); break; case Particle::DrawOption::Normal: Qt = rParticleSprite.m_LocalQt; Qt.normalize(); break; } bsm::Mat4x4 matrix; matrix.affineTransformation( LocalScale, bsm::Vec3(0,0,0), Qt, WorldPos ); DrawCom->AddParticle(ToCaneraLength, matrix, TextureRes, rParticleSprite.m_Color); } void ParticleManager::OnDraw() { auto DrawCom = GetComponent<PCTParticleDraw>(); DrawCom->OnDraw(); } struct CillisionItem { shared_ptr<Collision> m_Collision; SPHERE m_EnclosingSphere; float m_MinX; float m_MaxX; float m_MinY; float m_MaxY; float m_MinZ; float m_MaxZ; bool operator==(const CillisionItem& other)const { if (this == &other) { return true; } return false; } }; //-------------------------------------------------------------------------------------- // struct CollisionManager::Impl; // 用途: Implイディオム //-------------------------------------------------------------------------------------- struct CollisionManager::Impl { vector<CillisionItem> m_ItemVec; Impl() {} ~Impl() {} }; //-------------------------------------------------------------------------------------- // 衝突判定管理者 //-------------------------------------------------------------------------------------- CollisionManager::CollisionManager(const shared_ptr<Stage>& StagePtr): GameObject(StagePtr), pImpl(new Impl()) {} CollisionManager::~CollisionManager() {} void CollisionManager::OnCreate() { } void CollisionManager::CollisionSub(size_t SrcIndex) { CillisionItem& Src = pImpl->m_ItemVec[SrcIndex]; for (auto& v : pImpl->m_ItemVec) { if (Src == v) { continue; } if (Src.m_MinX > v.m_MaxX || Src.m_MaxX < v.m_MinX) { continue; } if (Src.m_MinY > v.m_MaxY || Src.m_MaxY < v.m_MinY) { continue; } if (Src.m_MinZ > v.m_MaxZ || Src.m_MaxZ < v.m_MinZ) { continue; } //相手が除外オブジェクトになってるかどうか if (v.m_Collision->IsExcludeCollisionObject(Src.m_Collision->GetGameObject())) { continue; } if (Src.m_Collision->IsExcludeCollisionObject(v.m_Collision->GetGameObject())) { continue; } if (v.m_Collision->IsHitObject(Src.m_Collision->GetGameObject())) { continue; } //衝突判定(Destに呼んでもらう。ダブルデスパッチ呼び出し) v.m_Collision->CollisionCall(Src.m_Collision); } } void CollisionManager::OnUpdate() { pImpl->m_ItemVec.clear(); auto& ObjVec = GetStage()->GetGameObjectVec(); for (auto& v : ObjVec) { if (v->IsUpdateActive()) { auto Col = v->GetComponent<Collision>(false); if (Col && Col->IsUpdateActive()) { CillisionItem Item; Item.m_Collision = Col; Item.m_EnclosingSphere = Col->GetEnclosingSphere(); Item.m_MinX = Item.m_EnclosingSphere.m_Center.x - Item.m_EnclosingSphere.m_Radius; Item.m_MaxX = Item.m_EnclosingSphere.m_Center.x + Item.m_EnclosingSphere.m_Radius; Item.m_MinY = Item.m_EnclosingSphere.m_Center.y - Item.m_EnclosingSphere.m_Radius; Item.m_MaxY = Item.m_EnclosingSphere.m_Center.y + Item.m_EnclosingSphere.m_Radius; Item.m_MinZ = Item.m_EnclosingSphere.m_Center.z - Item.m_EnclosingSphere.m_Radius; Item.m_MaxZ = Item.m_EnclosingSphere.m_Center.z + Item.m_EnclosingSphere.m_Radius; pImpl->m_ItemVec.push_back(Item); } } } auto func = [&](CillisionItem& Left, CillisionItem& Right)->bool { auto PtrLeftVelo = Left.m_Collision->GetGameObject()->GetComponent<Transform>()->GetVelocity(); auto PtrRightVelo = Right.m_Collision->GetGameObject()->GetComponent<Transform>()->GetVelocity(); auto LeftLen = bsm::length(PtrLeftVelo); auto RightLen = bsm::length(PtrRightVelo); return (LeftLen < RightLen); }; std::sort(pImpl->m_ItemVec.begin(), pImpl->m_ItemVec.end(), func); for (size_t i = 0; i < pImpl->m_ItemVec.size(); i++) { if (!pImpl->m_ItemVec[i].m_Collision->IsFixed()) { CollisionSub(i); } } } //-------------------------------------------------------------------------------------- // struct Stage::Impl; // 用途: Implイディオム //-------------------------------------------------------------------------------------- struct Stage::Impl { //updateするかどうか bool m_UpdateActive; //パーティクルマネージャ(透明処理) shared_ptr<ParticleManager> m_AlphaParticleManager; //パーティクルマネージャ(加算処理) shared_ptr<ParticleManager> m_AddParticleManager; //コリジョン管理者 shared_ptr<CollisionManager> m_CollisionManager; //オブジェクトの配列 vector< shared_ptr<GameObject> > m_GameObjectVec; //途中にオブジェクトが追加された場合、ターンの開始まで待つ配列 vector< shared_ptr<GameObject> > m_WaitAddObjectVec; //途中にオブジェクトが削除された場合、ターンの開始まで待つ配列 vector< shared_ptr<GameObject> > m_WaitRemoveObjectVec; //Spriteかそうでないかを分離する配列 vector< shared_ptr<GameObject> > m_SpriteVec; vector< shared_ptr<GameObject> > m_Object3DVec; //3Dの透明と非透明を分離する配列 vector< shared_ptr<GameObject> > m_Object3DNormalVec; vector< shared_ptr<GameObject> > m_Object3DAlphaVec; //物理計算 BasePhysics m_BasePhysics; //現在Drawされているビューのインデックス size_t m_DrawViewIndex; //ビューのポインタ shared_ptr<ViewBase> m_ViewBase; //ライトのポインタ shared_ptr<LightBase> m_LightBase; //シェアオブジェクトポインタのマップ map<const wstring, weak_ptr<GameObject> > m_SharedMap; //シェアグループのポインタのマップ map<const wstring, shared_ptr<GameObjectGroup> > m_SharedGroupMap; vector< shared_ptr<Stage> > m_ChildStageVec; //子供ステージの配列 weak_ptr<Stage> m_ParentStage; //親ステージ //シャドウマップを使うかどうか bool m_IsShadowmapDraw; //物理計算を使うかどうか bool m_IsPhysicsActive; Impl() : m_UpdateActive(true), m_DrawViewIndex(0), m_IsShadowmapDraw(true), m_IsPhysicsActive(false) {} ~Impl() {} void RemoveTargetGameObject(const shared_ptr<GameObject>& targetobj); }; void Stage::Impl::RemoveTargetGameObject(const shared_ptr<GameObject>& targetobj) { auto it = m_GameObjectVec.begin(); while (it != m_GameObjectVec.end()) { if (*it == targetobj) { //削除されることをオブジェクトに伝える targetobj->DestroyGameObject(); m_GameObjectVec.erase(it); return; } it++; } } //-------------------------------------------------------------------------------------- // ステージクラス //-------------------------------------------------------------------------------------- Stage::Stage() : ObjectInterface(), ShapeInterface(), pImpl(new Impl()) {} Stage::~Stage() {} //プライベートサブ関数 void Stage::PushBackGameObject(const shared_ptr<GameObject>& Ptr) { //このステージはクリエイト後である if (IsCreated()) { pImpl->m_WaitAddObjectVec.push_back(Ptr); } else { //クリエイト前 pImpl->m_GameObjectVec.push_back(Ptr); } } //削除オブジェクトの設定 void Stage::RemoveBackGameObject(const shared_ptr<GameObject>& Ptr) { pImpl->m_WaitRemoveObjectVec.push_back(Ptr); } shared_ptr<GameObject> Stage::GetSharedGameObjectEx(const wstring& Key, bool ExceptionActive)const { map<const wstring, weak_ptr<GameObject> >::const_iterator it; //重複キーの検査 it = pImpl->m_SharedMap.find(Key); if (it != pImpl->m_SharedMap.end()) { if (it->second.expired()) { //すでに無効 if (ExceptionActive) { //例外発生 wstring keyerr = Key; throw BaseException( L"オブジェクトが無効です", keyerr, L"Stage::GetSharedGameObject()" ); } } return it->second.lock(); } else { //指定の名前が見つからなかった if (ExceptionActive) { //例外発生 wstring keyerr = Key; throw BaseException( L"オブジェクトが見つかりません", keyerr, L"Stage::GetSharedGameObject()" ); } } return nullptr; } shared_ptr<ParticleManager> Stage::GetParticleManager(bool Addtype) const { if (Addtype) { return pImpl->m_AddParticleManager; } else { return pImpl->m_AlphaParticleManager; } } BasePhysics& Stage::GetBasePhysics() const { if (!IsPhysicsActive()) { throw BaseException( L"物理演算が無効になっています。有効にしてから取得してください。", L"if (!IsPhysicsActive())", L"Stage::GetBasePhysics()()" ); } return pImpl->m_BasePhysics; } bool Stage::IsPhysicsActive() const { return pImpl->m_IsPhysicsActive; } void Stage::SetPhysicsActive(bool b) { pImpl->m_IsPhysicsActive = b; } vector< shared_ptr<GameObject> >& Stage::GetGameObjectVec() { return pImpl->m_GameObjectVec; } vector< shared_ptr<GameObject> >& Stage::GetGameObjectVec() const{ return pImpl->m_GameObjectVec; } //追加や削除待ちになってるオブジェクトを追加・削除する void Stage::SetWaitToObjectVec(){ if (!pImpl->m_WaitRemoveObjectVec.empty()) { for (auto Ptr : pImpl->m_WaitRemoveObjectVec) { pImpl->RemoveTargetGameObject(Ptr); } } pImpl->m_WaitRemoveObjectVec.clear(); if (!pImpl->m_WaitAddObjectVec.empty()){ for (auto Ptr : pImpl->m_WaitAddObjectVec){ pImpl->m_GameObjectVec.push_back(Ptr); } } pImpl->m_WaitAddObjectVec.clear(); } shared_ptr<GameObject> Stage::GetSharedObject(const wstring& Key, bool ExceptionActive)const { shared_ptr<GameObject> Ptr = GetSharedGameObjectEx(Key, ExceptionActive); return Ptr; } void Stage::SetSharedGameObject(const wstring& Key, const shared_ptr<GameObject>& Ptr) { map<const wstring, weak_ptr<GameObject> >::iterator it; //重複キーの検査 it = pImpl->m_SharedMap.find(Key); if (it != pImpl->m_SharedMap.end()) { //既に存在した //例外発生 wstring keyerr = Key; throw BaseException( L"同名のシェアオブジェクトがあります", keyerr, L"Stage::SetSharedGameObjectEx()" ); } else { pImpl->m_SharedMap[Key] = Ptr; } } shared_ptr<GameObjectGroup> Stage::CreateSharedObjectGroup(const wstring& Key) { try { map<const wstring, shared_ptr<GameObjectGroup> >::iterator it; //重複キーの検査 it = pImpl->m_SharedGroupMap.find(Key); if (it != pImpl->m_SharedGroupMap.end()) { //既に存在した //例外発生 wstring keyerr = Key; throw BaseException( L"同名のシェアオブジェクト配列があります", keyerr, L"Stage::CreateSharedObjectGroup()" ); } else { auto Ptr = ObjectFactory::Create<GameObjectGroup>(); pImpl->m_SharedGroupMap[Key] = Ptr; return Ptr; } } catch (...) { throw; } } shared_ptr<GameObjectGroup> Stage::GetSharedObjectGroup(const wstring& Key, bool ExceptionActive)const { //重複キーの検査 auto it = pImpl->m_SharedGroupMap.find(Key); if (it != pImpl->m_SharedGroupMap.end()) { //ペアのsecondを返す return it->second; } else { //指定の名前が見つからなかった if (ExceptionActive) { //例外発生 wstring keyerr = Key; throw BaseException( L"指定のキーが見つかりません", keyerr, L"Stage::GetSharedObjectGroup() const" ); } } return nullptr; } void Stage::SetSharedObjectGroup(const wstring& Key, const shared_ptr<GameObjectGroup>& NewPtr) { //重複キーの検査 auto it = pImpl->m_SharedGroupMap.find(Key); if (it != pImpl->m_SharedGroupMap.end()) { //例外発生 wstring keyerr = Key; throw BaseException( L"同名のシェアオブジェクト配列があります", keyerr, L"Stage::SetSharedObjectGroup()" ); } else { //指定の名前が見つからなかった //登録できる pImpl->m_SharedGroupMap[Key] = NewPtr; } } vector< shared_ptr<Stage> >& Stage::GetChileStageVec() { return pImpl->m_ChildStageVec; } vector< shared_ptr<Stage> >& Stage::GetChileStageVec() const { return pImpl->m_ChildStageVec; } void Stage::AddChileStageBase(const shared_ptr<Stage>& ChildStage) { pImpl->m_ChildStageVec.push_back(ChildStage); ChildStage->SetParentStage(GetThis<Stage>()); } shared_ptr<Stage> Stage::GetParentStage() const { if (!pImpl->m_ParentStage.expired()) { return pImpl->m_ParentStage.lock(); } return nullptr; } void Stage::SetParentStage(const shared_ptr<Stage>& ParentStage) { pImpl->m_ParentStage = ParentStage; } void Stage::SetView(const shared_ptr<ViewBase>& v) { pImpl->m_ViewBase = v; } const shared_ptr<ViewBase>& Stage::GetView(bool ExceptionActive)const { if (ExceptionActive) { if (!pImpl->m_ViewBase) { throw BaseException( L"ステージにビューが設定されていません。", L"if (!pImpl->m_ViewBase)", L"Stage::GetView()" ); } } return pImpl->m_ViewBase; } void Stage::SetLight(const shared_ptr<LightBase>& L) { pImpl->m_LightBase = L; } const shared_ptr<LightBase>& Stage::GetLight()const { if (!pImpl->m_LightBase) { throw BaseException( L"ステージにライトが設定されていません。", L"if (!pImpl->m_LightBase)", L"Stage::GetLight()" ); } return pImpl->m_LightBase; } //アクセサ bool Stage::IsUpdateActive() const { return pImpl->m_UpdateActive; } bool Stage::GetUpdateActive() const { return pImpl->m_UpdateActive; } void Stage::SetUpdateActive(bool b) { pImpl->m_UpdateActive = b; } void Stage::OnPreCreate() { //パーティクルマネージャの作成(透明処理) pImpl->m_AlphaParticleManager = ObjectFactory::Create<ParticleManager>(GetThis<Stage>(),false); //パーティクルマネージャの作成(加算処理) pImpl->m_AddParticleManager = ObjectFactory::Create<ParticleManager>(GetThis<Stage>(),true); //コリジョン管理者の作成 pImpl->m_CollisionManager = ObjectFactory::Create<CollisionManager>(GetThis<Stage>()); //物理計算リセット pImpl->m_BasePhysics.Reset(); } //ステージ内の更新(シーンからよばれる) void Stage::UpdateStage() { //追加・削除まちオブジェクトの追加と削除 SetWaitToObjectVec(); //Transformコンポーネントの値をバックアップにコピー for (auto ptr : GetGameObjectVec()) { if (ptr->IsUpdateActive()) { auto ptr2 = ptr->GetComponent<Transform>(); ptr2->SetToBefore(); auto RigidPtr = ptr->GetComponent<Rigidbody>(false); if (RigidPtr) { //Rigidbodyがあればフォースを初期化 RigidPtr->SetForce(0, 0, 0); } } } //配置オブジェクトの更新処理 for (auto ptr : GetGameObjectVec()) { if (ptr->IsUpdateActive()) { ptr->OnUpdate(); } } //自身の更新処理 if (IsUpdateActive()) { OnUpdate(); } //物理オブジェクトの更新 if (IsPhysicsActive()) { pImpl->m_BasePhysics.Update(); } //配置オブジェクトのコンポーネント更新 for (auto ptr : GetGameObjectVec()) { if (ptr->IsUpdateActive()) { ptr->ComponentUpdate(); } } //衝突判定の更新(ステージから呼ぶ) UpdateCollision(); //衝突判定のメッセージ発行(ステージから呼ぶ) UpdateMessageCollision(); //配置オブジェクトの更新後処理 for (auto ptr : GetGameObjectVec()) { if (ptr->IsUpdateActive()) { ptr->OnUpdate2(); } } //自身の更新1 if (IsUpdateActive()) { OnUpdate2(); } //自身のビューをアップデート auto ViewPtr = GetView(false); if (ViewPtr && ViewPtr->IsUpdateActive()) { ViewPtr->OnUpdate(); } //コリジョンのリセット for (auto ptr : GetGameObjectVec()) { ptr->CollisionReset(); } //子供ステージの更新 for (auto PtrChileStage : GetChileStageVec()) { PtrChileStage->UpdateStage(); } } //衝突判定の更新(ステージから呼ぶ) //衝突判定をカスタマイズするためには //この関数を多重定義する void Stage::UpdateCollision() { //衝突判定管理者のUpdate pImpl->m_CollisionManager->OnUpdate(); } void Stage::UpdateMessageCollision() { //配置オブジェクトの衝突メッセージ発行 for (auto ptr : GetGameObjectVec()) { if (ptr->IsUpdateActive()) { ptr->ToMessageCollision(); } } } //シャドウマップを使うかどうか bool Stage::IsShadowmapDraw() const { return pImpl->m_IsShadowmapDraw; } void Stage::SetShadowmapDraw(bool b) { pImpl->m_IsShadowmapDraw = b; } //ステージ内のシャドウマップ描画(ステージからよばれる) void Stage::DrawShadowmapStage() { for (auto ptr : pImpl->m_GameObjectVec) { if (ptr->IsDrawActive()) { ptr->DrawShadowmap(); } } } //ステージ内の描画(ステージからよばれる) void Stage::DrawStage() { //レイヤーの取得と設定 set<int> DrawLayers; //Spriteかそうでないかを分離 for (auto ptr : GetGameObjectVec()) { if (ptr->IsDrawActive()) { //描画レイヤーに登録 DrawLayers.insert(ptr->GetDrawLayer()); //Spriteかその派生クラスなら分離 if (ptr->GetDynamicComponent<SpriteBaseDraw>(false) || ptr->IsSpriteDraw()) { pImpl->m_SpriteVec.push_back(ptr); } else { pImpl->m_Object3DVec.push_back(ptr); } } } //3Dの透明と非透明を分離 for (auto ptr : pImpl->m_Object3DVec) { if (ptr->IsDrawActive()) { if (ptr->IsAlphaActive()) { pImpl->m_Object3DAlphaVec.push_back(ptr); } else { pImpl->m_Object3DNormalVec.push_back(ptr); } } } auto PtrCamera = pImpl->m_ViewBase->GetTargetCamera(); //カメラの位置 bsm::Vec3 CameraEye = PtrCamera->GetEye(); //透明の3Dオブジェクトをカメラからの距離でソート //以下は、オブジェクトを引数に取りboolを返すラムダ式 //-------------------------------------------------------- auto func = [&](shared_ptr<GameObject>& Left, shared_ptr<GameObject>& Right)->bool { auto PtrLeftTrans = Left->GetComponent<Transform>(); auto PtrRightTrans = Right->GetComponent<Transform>(); auto LeftPos = PtrLeftTrans->GetWorldMatrix().transInMatrix(); auto RightPos = PtrRightTrans->GetWorldMatrix().transInMatrix(); auto LeftLen = bsm::length(LeftPos - CameraEye); auto RightLen = bsm::length(RightPos - CameraEye); return (LeftLen > RightLen); }; std::sort(pImpl->m_Object3DAlphaVec.begin(), pImpl->m_Object3DAlphaVec.end(), func); //3Dノーマルオブジェクトの描画準備 for (auto ptr : pImpl->m_Object3DNormalVec) { ptr->OnPreDraw(); } //3D透明オブジェクトの描画準備 for (auto ptr : pImpl->m_Object3DAlphaVec) { ptr->OnPreDraw(); } //パーティクルの描画準備(透明) GetParticleManager(false)->OnPreDraw(); //パーティクルの描画準備(加算) GetParticleManager(true)->OnPreDraw(); //スプライトオブジェクトの描画準備 for (auto ptr : pImpl->m_SpriteVec) { ptr->OnPreDraw(); } //-------------------------------------------------------- //スプライトをZ座標距離でソート //以下は、オブジェクトを引数に取りboolを返すラムダ式 //-------------------------------------------------------- auto funcSprite = [&](shared_ptr<GameObject>& Left, shared_ptr<GameObject>& Right)->bool { auto PtrLeftTrans = Left->GetComponent<Transform>(); auto PtrRightTrans = Right->GetComponent<Transform>(); auto LeftPos = PtrLeftTrans->GetWorldMatrix().transInMatrix(); auto RightPos = PtrRightTrans->GetWorldMatrix().transInMatrix(); float LeftZ = LeftPos.z; float RightZ = RightPos.z; return (LeftZ > RightZ); }; std::sort(pImpl->m_SpriteVec.begin(), pImpl->m_SpriteVec.end(), funcSprite); for (auto it = DrawLayers.begin(); it != DrawLayers.end(); it++) { int Tgt = *it; //3Dノーマルオブジェクトの描画 for (auto ptr : pImpl->m_Object3DNormalVec) { if (ptr->GetDrawLayer() == Tgt) { ptr->OnDraw(); } } //3D透明オブジェクトの描画 for (auto ptr : pImpl->m_Object3DAlphaVec) { if (ptr->GetDrawLayer() == Tgt) { ptr->OnDraw(); } } //パーティクルの描画 //パーティクルマネージャは描画レイヤーごとに初期化されるので //毎レイヤー描画する //透明処理 GetParticleManager(false)->OnDraw(); //加算処理 GetParticleManager(true)->OnDraw(); //スプライトオブジェクトの描画 for (auto ptr : pImpl->m_SpriteVec) { if (ptr->GetDrawLayer() == Tgt) { ptr->OnDraw(); } } } //ステージのDraw(); OnDraw(); //ワーク用配列のクリア //ワーク配列は毎ターンごとに初期化されるが、 //最大値は減らないので2回目のターン以降は高速に動作する pImpl->m_Object3DVec.clear(); pImpl->m_SpriteVec.clear(); pImpl->m_Object3DNormalVec.clear(); pImpl->m_Object3DAlphaVec.clear(); } //ステージ内のすべての描画(シーンからよばれる) void Stage::RenderStage() { //描画デバイスの取得 auto Dev = App::GetApp()->GetDeviceResources(); auto MultiPtr = dynamic_pointer_cast<MultiView>(GetView()); if (MultiPtr) { for (size_t i = 0; i < MultiPtr->GetViewSize(); i++) { MultiPtr->SetTargetIndex(i); if (IsShadowmapDraw()) { Dev->ClearShadowmapViews(); Dev->StartShadowmapDraw(); DrawShadowmapStage(); Dev->EndShadowmapDraw(); } //デフォルト描画の開始 Dev->StartDefaultDraw(); RsSetViewport(MultiPtr->GetTargetViewport()); DrawStage(); //デフォルト描画の終了 Dev->EndDefaultDraw(); } //描画が終わったら更新処理用に先頭のカメラにターゲットを設定する MultiPtr->SetTargetIndex(0); } else { if (IsShadowmapDraw()) { Dev->ClearShadowmapViews(); Dev->StartShadowmapDraw(); DrawShadowmapStage(); Dev->EndShadowmapDraw(); } //デフォルト描画の開始 Dev->StartDefaultDraw(); RsSetViewport(GetView()->GetTargetViewport()); DrawStage(); //デフォルト描画の終了 Dev->EndDefaultDraw(); } //子供ステージの描画 for (auto PtrChileStage : pImpl->m_ChildStageVec) { PtrChileStage->RenderStage(); } } void Stage::DestroyStage() { //子供ステージの削除処理 for (auto PtrChileStage : pImpl->m_ChildStageVec) { PtrChileStage->DestroyStage(); } //配置オブジェクトの削除処理 for (auto ptr : GetGameObjectVec()) { ptr->DestroyGameObject(); } //自身の削除処理 OnDestroy(); } //-------------------------------------------------------------------------------------- // struct SceneBase::Impl; // 用途: Implイディオム //-------------------------------------------------------------------------------------- struct SceneBase::Impl { //アクティブなステージ shared_ptr<Stage> m_ActiveStage; //クリアする色 bsm::Col4 m_ClearColor; Impl(): m_ActiveStage(), m_ClearColor(0,0,0,1.0f) {} ~Impl() {} }; //-------------------------------------------------------------------------------------- /// シーン親クラス //-------------------------------------------------------------------------------------- void SceneBase::ConvertVertex(const vector<VertexPositionNormalTexture>& vertices, vector<VertexPositionColor>& new_pc_vertices, vector<VertexPositionTexture>& new_pt_vertices, vector<VertexPositionNormalTangentTexture>& new_pntnt_vertices) { new_pc_vertices.clear(); new_pt_vertices.clear(); new_pntnt_vertices.clear(); for (size_t i = 0; i < vertices.size(); i++) { VertexPositionColor new_pc_v; VertexPositionTexture new_pt_v; VertexPositionNormalTangentTexture new_pntnt_v; new_pc_v.position = vertices[i].position; new_pc_v.color = bsm::Col4(1.0f, 1.0f, 1.0f, 1.0f); new_pt_v.position = vertices[i].position; new_pt_v.textureCoordinate = vertices[i].textureCoordinate; new_pntnt_v.position = vertices[i].position; new_pntnt_v.normal = vertices[i].normal; new_pntnt_v.textureCoordinate = vertices[i].textureCoordinate; bsm::Vec3 n = bsm::cross((bsm::Vec3)new_pntnt_v.normal, bsm::Vec3(0, 1, 0)); new_pntnt_v.tangent = bsm::Vec4(n.x,n.y,n.z,0.0f); new_pntnt_v.tangent.w = 0.0f; new_pc_vertices.push_back(new_pc_v); new_pt_vertices.push_back(new_pt_v); new_pntnt_vertices.push_back(new_pntnt_v); } } SceneBase::SceneBase() : SceneInterface(), pImpl(new Impl()) { try { //デフォルトのリソースの作成 App::GetApp()->RegisterResource(L"DEFAULT_SQUARE", MeshResource::CreateSquare(1.0f)); App::GetApp()->RegisterResource(L"DEFAULT_CUBE", MeshResource::CreateCube(1.0f)); App::GetApp()->RegisterResource(L"DEFAULT_SPHERE", MeshResource::CreateSphere(1.0f, 18)); App::GetApp()->RegisterResource(L"DEFAULT_CAPSULE", MeshResource::CreateCapsule(1.0f, 1.0f, 18)); App::GetApp()->RegisterResource(L"DEFAULT_CYLINDER", MeshResource::CreateCylinder(1.0f, 1.0f, 18)); App::GetApp()->RegisterResource(L"DEFAULT_CONE", MeshResource::CreateCone(1.0f, 1.0f, 18)); App::GetApp()->RegisterResource(L"DEFAULT_TORUS", MeshResource::CreateTorus(1.0f, 0.3f, 18)); App::GetApp()->RegisterResource(L"DEFAULT_TETRAHEDRON", MeshResource::CreateTetrahedron(1.0f)); App::GetApp()->RegisterResource(L"DEFAULT_OCTAHEDRON", MeshResource::CreateOctahedron(1.0f)); App::GetApp()->RegisterResource(L"DEFAULT_DODECAHEDRON", MeshResource::CreateDodecahedron(1.0f)); App::GetApp()->RegisterResource(L"DEFAULT_ICOSAHEDRON", MeshResource::CreateIcosahedron(1.0f)); vector<VertexPositionNormalTexture> vertices; vector<VertexPositionColor> new_pc_vertices; vector<VertexPositionTexture> new_pt_vertices; vector<VertexPositionNormalTangentTexture> new_pntnt_vertices; vector<uint16_t> indices; MeshUtill::CreateSquare(1.0f, vertices, indices); ConvertVertex(vertices, new_pc_vertices, new_pt_vertices, new_pntnt_vertices); MeshUtill::SetNormalTangent(new_pntnt_vertices); App::GetApp()->RegisterResource(L"DEFAULT_PC_SQUARE", MeshResource::CreateMeshResource(new_pc_vertices, indices, false)); App::GetApp()->RegisterResource(L"DEFAULT_PT_SQUARE", MeshResource::CreateMeshResource(new_pt_vertices, indices, false)); App::GetApp()->RegisterResource(L"DEFAULT_PNTnT_SQUARE", MeshResource::CreateMeshResource(new_pntnt_vertices, indices, false)); vertices.clear(); indices.clear(); MeshUtill::CreateCube(1.0f, vertices, indices); ConvertVertex(vertices, new_pc_vertices, new_pt_vertices, new_pntnt_vertices); MeshUtill::SetNormalTangent(new_pntnt_vertices); App::GetApp()->RegisterResource(L"DEFAULT_PC_CUBE", MeshResource::CreateMeshResource(new_pc_vertices, indices, false)); App::GetApp()->RegisterResource(L"DEFAULT_PT_CUBE", MeshResource::CreateMeshResource(new_pt_vertices, indices, false)); App::GetApp()->RegisterResource(L"DEFAULT_PNTnT_CUBE", MeshResource::CreateMeshResource(new_pntnt_vertices, indices, false)); vertices.clear(); indices.clear(); MeshUtill::CreateSphere(1.0f,18, vertices, indices); ConvertVertex(vertices, new_pc_vertices, new_pt_vertices, new_pntnt_vertices); MeshUtill::SetNormalTangent(new_pntnt_vertices); App::GetApp()->RegisterResource(L"DEFAULT_PC_SPHERE", MeshResource::CreateMeshResource(new_pc_vertices, indices, false)); App::GetApp()->RegisterResource(L"DEFAULT_PT_SPHERE", MeshResource::CreateMeshResource(new_pt_vertices, indices, false)); App::GetApp()->RegisterResource(L"DEFAULT_PNTnT_SPHERE", MeshResource::CreateMeshResource(new_pntnt_vertices, indices, false)); vertices.clear(); indices.clear(); bsm::Vec3 PointA(0, -1.0f / 2.0f, 0); bsm::Vec3 PointB(0, 1.0f / 2.0f, 0); //Capsuleの作成(ヘルパー関数を利用) MeshUtill::CreateCapsule(1.0f, PointA, PointB,18, vertices, indices); ConvertVertex(vertices, new_pc_vertices, new_pt_vertices, new_pntnt_vertices); MeshUtill::SetNormalTangent(new_pntnt_vertices); App::GetApp()->RegisterResource(L"DEFAULT_PC_CAPSULE", MeshResource::CreateMeshResource(new_pc_vertices, indices, false)); App::GetApp()->RegisterResource(L"DEFAULT_PT_CAPSULE", MeshResource::CreateMeshResource(new_pt_vertices, indices, false)); App::GetApp()->RegisterResource(L"DEFAULT_PNTnT_CAPSULE", MeshResource::CreateMeshResource(new_pntnt_vertices, indices, false)); vertices.clear(); indices.clear(); MeshUtill::CreateCylinder(1.0f, 1.0f, 18, vertices, indices); ConvertVertex(vertices, new_pc_vertices, new_pt_vertices, new_pntnt_vertices); MeshUtill::SetNormalTangent(new_pntnt_vertices); App::GetApp()->RegisterResource(L"DEFAULT_PC_CYLINDER", MeshResource::CreateMeshResource(new_pc_vertices, indices, false)); App::GetApp()->RegisterResource(L"DEFAULT_PT_CYLINDER", MeshResource::CreateMeshResource(new_pt_vertices, indices, false)); App::GetApp()->RegisterResource(L"DEFAULT_PNTnT_CYLINDER", MeshResource::CreateMeshResource(new_pntnt_vertices, indices, false)); vertices.clear(); indices.clear(); MeshUtill::CreateCone(1.0f, 1.0f, 18, vertices, indices); ConvertVertex(vertices, new_pc_vertices, new_pt_vertices, new_pntnt_vertices); MeshUtill::SetNormalTangent(new_pntnt_vertices); App::GetApp()->RegisterResource(L"DEFAULT_PC_CONE", MeshResource::CreateMeshResource(new_pc_vertices, indices, false)); App::GetApp()->RegisterResource(L"DEFAULT_PT_CONE", MeshResource::CreateMeshResource(new_pt_vertices, indices, false)); App::GetApp()->RegisterResource(L"DEFAULT_PNTnT_CONE", MeshResource::CreateMeshResource(new_pntnt_vertices, indices, false)); vertices.clear(); indices.clear(); MeshUtill::CreateTorus(1.0f, 0.3f, 18, vertices, indices); ConvertVertex(vertices, new_pc_vertices, new_pt_vertices, new_pntnt_vertices); MeshUtill::SetNormalTangent(new_pntnt_vertices); App::GetApp()->RegisterResource(L"DEFAULT_PC_TORUS", MeshResource::CreateMeshResource(new_pc_vertices, indices, false)); App::GetApp()->RegisterResource(L"DEFAULT_PT_TORUS", MeshResource::CreateMeshResource(new_pt_vertices, indices, false)); App::GetApp()->RegisterResource(L"DEFAULT_PNTnT_TORUS", MeshResource::CreateMeshResource(new_pntnt_vertices, indices, false)); vertices.clear(); indices.clear(); MeshUtill::CreateTetrahedron(1.0f, vertices, indices); ConvertVertex(vertices, new_pc_vertices, new_pt_vertices, new_pntnt_vertices); MeshUtill::SetNormalTangent(new_pntnt_vertices); App::GetApp()->RegisterResource(L"DEFAULT_PC_TETRAHEDRON", MeshResource::CreateMeshResource(new_pc_vertices, indices, false)); App::GetApp()->RegisterResource(L"DEFAULT_PT_TETRAHEDRON", MeshResource::CreateMeshResource(new_pt_vertices, indices, false)); App::GetApp()->RegisterResource(L"DEFAULT_PNTnT_TETRAHEDRON", MeshResource::CreateMeshResource(new_pntnt_vertices, indices, false)); vertices.clear(); indices.clear(); MeshUtill::CreateOctahedron(1.0f, vertices, indices); ConvertVertex(vertices, new_pc_vertices, new_pt_vertices, new_pntnt_vertices); MeshUtill::SetNormalTangent(new_pntnt_vertices); App::GetApp()->RegisterResource(L"DEFAULT_PC_OCTAHEDRON", MeshResource::CreateMeshResource(new_pc_vertices, indices, false)); App::GetApp()->RegisterResource(L"DEFAULT_PT_OCTAHEDRON", MeshResource::CreateMeshResource(new_pt_vertices, indices, false)); App::GetApp()->RegisterResource(L"DEFAULT_PNTnT_OCTAHEDRON", MeshResource::CreateMeshResource(new_pntnt_vertices, indices, false)); vertices.clear(); indices.clear(); MeshUtill::CreateDodecahedron(1.0f, vertices, indices); ConvertVertex(vertices, new_pc_vertices, new_pt_vertices, new_pntnt_vertices); MeshUtill::SetNormalTangent(new_pntnt_vertices); App::GetApp()->RegisterResource(L"DEFAULT_PC_DODECAHEDRON", MeshResource::CreateMeshResource(new_pc_vertices, indices, false)); App::GetApp()->RegisterResource(L"DEFAULT_PT_DODECAHEDRON", MeshResource::CreateMeshResource(new_pt_vertices, indices, false)); App::GetApp()->RegisterResource(L"DEFAULT_PNTnT_DODECAHEDRON", MeshResource::CreateMeshResource(new_pntnt_vertices, indices, false)); vertices.clear(); indices.clear(); MeshUtill::CreateIcosahedron(1.0f, vertices, indices); ConvertVertex(vertices, new_pc_vertices, new_pt_vertices, new_pntnt_vertices); MeshUtill::SetNormalTangent(new_pntnt_vertices); App::GetApp()->RegisterResource(L"DEFAULT_PC_ICOSAHEDRON", MeshResource::CreateMeshResource(new_pc_vertices, indices, false)); App::GetApp()->RegisterResource(L"DEFAULT_PT_ICOSAHEDRON", MeshResource::CreateMeshResource(new_pt_vertices, indices, false)); App::GetApp()->RegisterResource(L"DEFAULT_PNTnT_ICOSAHEDRON", MeshResource::CreateMeshResource(new_pntnt_vertices, indices, false)); vertices.clear(); indices.clear(); //物理ワイフレーム用 MeshUtill::CreateSphere(2.0f, 6, vertices, indices); vector<VertexPositionColor> col_vertices; for (auto& v : vertices) { VertexPositionColor vertex; vertex.position = v.position; vertex.color = Col4(1.0f, 1.0f, 1.0f, 1.0f); col_vertices.push_back(vertex); } App::GetApp()->RegisterResource(L"PSWIRE_PC_SPHERE", MeshResource::CreateMeshResource(col_vertices, indices, false)); vertices.clear(); indices.clear(); col_vertices.clear(); MeshUtill::CreateCube(2.0f, vertices, indices); for (auto& v : vertices) { VertexPositionColor vertex; vertex.position = v.position; vertex.color = Col4(1.0f, 1.0f, 1.0f, 1.0f); col_vertices.push_back(vertex); } App::GetApp()->RegisterResource(L"PSWIRE_PC_CUBE", MeshResource::CreateMeshResource(col_vertices, indices, false)); vertices.clear(); indices.clear(); col_vertices.clear(); MeshUtill::CreateCylinder(2.0f, 2.0f, 12,vertices,indices); for (auto& v : vertices) { VertexPositionColor vertex; vertex.position = v.position; vertex.color = Col4(1.0f, 1.0f, 1.0f, 1.0f); col_vertices.push_back(vertex); } App::GetApp()->RegisterResource(L"PSWIRE_PC_CYLINDER", MeshResource::CreateMeshResource(col_vertices, indices, false)); vertices.clear(); indices.clear(); col_vertices.clear(); } catch (...) { throw; } } SceneBase::~SceneBase() {} shared_ptr<Stage> SceneBase::GetActiveStage(bool ExceptionActive) const { if (!pImpl->m_ActiveStage) { //アクティブなステージが無効なら if (ExceptionActive) { throw BaseException( L"アクティブなステージがありません", L"if(!m_ActiveStage.get())", L"SceneBase::GetActiveStage()" ); } else { return nullptr; } } return pImpl->m_ActiveStage; } void SceneBase::SetActiveStage(const shared_ptr<Stage>& stage) { pImpl->m_ActiveStage = stage; } bsm::Col4 SceneBase::GetClearColor() const { return pImpl->m_ClearColor; } void SceneBase::SetClearColor(const bsm::Col4& col) { pImpl->m_ClearColor = col; } void SceneBase::OnUpdate() { if (pImpl->m_ActiveStage) { //ステージのアップデート pImpl->m_ActiveStage->UpdateStage(); } } void SceneBase::OnDraw() { if (pImpl->m_ActiveStage) { //描画デバイスの取得 auto Dev = App::GetApp()->GetDeviceResources(); Dev->ClearDefaultViews(GetClearColor()); pImpl->m_ActiveStage->RenderStage(); } } void SceneBase::OnDestroy() { if (pImpl->m_ActiveStage) { pImpl->m_ActiveStage->DestroyStage(); } } //-------------------------------------------------------------------------------------- // struct StageCellMap::Impl; // 用途: Implイディオム //-------------------------------------------------------------------------------------- struct StageCellMap::Impl { //セルのポインタの配列(2次元) vector<vector<CellPiece>> m_CellVec; const UINT m_MaxCellSize = 100; //セルのXZ方向の数 UINT m_SizeX; UINT m_SizeZ; //セル1個のステージ上のサイズ float m_PieceSize; //デフォルトのコスト int m_DefaultCost; //ステージ上でこのセルマップを展開するAABB AABB m_MapAABB; //メッシュ shared_ptr<MeshResource> m_LineMesh; //メッシュ作成のための頂点の配列 vector<VertexPositionColor> m_Vertices; //セル文字を描画するかどうか bool m_IsCellStringActive; Impl() : m_IsCellStringActive(false) {} ~Impl() {} void Init(const bsm::Vec3& MiniPos, float PieceSize, UINT PieceCountX, UINT PieceCountZ, int DefaultCost); void Create(const shared_ptr<MultiStringSprite>& StringPtr, const shared_ptr<Stage>& StagePtr); bsm::Vec3 WorldToSCreen(const bsm::Vec3& v,const bsm::Mat4x4& m, float ViewWidth, float ViewHeight) { Vec4 Pos4(v,1.0f); Pos4.w = 1.0f; //座標変換 Pos4 *= m; //遠近 Pos4.x /= Pos4.w; Pos4.y /= Pos4.w; Pos4.z /= Pos4.w; //座標単位の修正 Pos4.x += 1.0f; Pos4.y += 1.0f; Pos4.y = 2.0f - Pos4.y; //ビューポート変換 Pos4.x *= (ViewWidth * 0.5f); Pos4.y *= (ViewHeight * 0.5f); return (Vec3)Pos4; } }; void StageCellMap::Impl::Init(const bsm::Vec3& MiniPos, float PieceSize, UINT PieceCountX, UINT PieceCountZ, int DefaultCost) { m_PieceSize = PieceSize; m_DefaultCost = DefaultCost; m_SizeX = PieceCountX; if (m_SizeX <= 0) { m_SizeX = 1; } if (m_SizeX >= m_MaxCellSize) { throw BaseException( L"セルのX方向が最大値を超えました", L"if (m_SizeX >= m_MaxCellSize)", L"StageCellMap::Impl::Init()" ); } m_SizeZ = PieceCountZ; if (m_SizeZ <= 0) { m_SizeZ = 1; } if (m_SizeZ >= m_MaxCellSize) { throw BaseException( L"セルのZ方向が最大値を超えました", L"if (m_SizeZ >= m_MaxCellSize)", L"StageCellMap::Impl::Init()" ); } m_MapAABB.m_Min = MiniPos; m_MapAABB.m_Max.x = m_MapAABB.m_Min.x + m_PieceSize * (float)m_SizeX; m_MapAABB.m_Max.y = m_MapAABB.m_Min.y + m_PieceSize; m_MapAABB.m_Max.z = m_MapAABB.m_Min.z + m_PieceSize * (float)m_SizeZ; bsm::Vec3 PieceVec(m_PieceSize, m_PieceSize, m_PieceSize); //配列の初期化 m_CellVec.resize(m_SizeX); for (UINT x = 0; x < m_SizeX; x++) { m_CellVec[x].resize(m_SizeZ); for (UINT z = 0; z < m_SizeZ; z++) { m_CellVec[x][z].m_Index.x = x; m_CellVec[x][z].m_Index.z = z; m_CellVec[x][z].m_Cost = m_DefaultCost; AABB Piece; Piece.m_Min.x = m_MapAABB.m_Min.x + (float)x * m_PieceSize; Piece.m_Min.y = m_MapAABB.m_Min.y; Piece.m_Min.z = m_MapAABB.m_Min.z + (float)z * m_PieceSize; Piece.m_Max = Piece.m_Min + PieceVec; m_CellVec[x][z].m_PieceRange = Piece; } } } void StageCellMap::Impl::Create(const shared_ptr<MultiStringSprite>& StringPtr, const shared_ptr<Stage>& StagePtr) { bsm::Vec3 Min = m_MapAABB.m_Min; bsm::Vec3 Max = m_MapAABB.m_Max; bsm::Col4 Col(1.0f, 1.0f, 1.0f, 1.0f); bsm::Vec3 LineFrom(Min); bsm::Vec3 LineTo(Min); LineTo.x = Max.x; m_Vertices.clear(); for (UINT z = 0; z <= m_SizeZ; z++) { m_Vertices.push_back(VertexPositionColor(LineFrom, Col)); m_Vertices.push_back(VertexPositionColor(LineTo, Col)); LineFrom.z += m_PieceSize; LineTo.z += m_PieceSize; } LineFrom = Min; LineTo = Min; LineTo.z = Max.z; for (UINT x = 0; x <= m_SizeX; x++) { m_Vertices.push_back(VertexPositionColor(LineFrom, Col)); m_Vertices.push_back(VertexPositionColor(LineTo, Col)); LineFrom.x += m_PieceSize; LineTo.x += m_PieceSize; } //メッシュの作成(変更できない) m_LineMesh = MeshResource::CreateMeshResource(m_Vertices, false); //スプライト文字列の初期化 bsm::Mat4x4 World, View, Proj; //ワールド行列の決定 bsm::Quat Qt; Qt.normalize(); World.affineTransformation( bsm::Vec3(1.0, 1.0, 1.0), //スケーリング bsm::Vec3(0, 0, 0), //回転の中心(重心) Qt, //回転角度 bsm::Vec3(0, 0.01f, 0) //位置 ); auto PtrCamera = StagePtr->GetView()->GetTargetCamera(); View = PtrCamera->GetViewMatrix(); Proj = PtrCamera->GetProjMatrix(); auto viewport = StagePtr->GetView()->GetTargetViewport(); World *= View; World *= Proj; StringPtr->ClearTextBlock(); for (UINT x = 0; x < m_CellVec.size(); x++) { for (UINT z = 0; z < m_CellVec[x].size(); z++) { bsm::Vec3 Pos = m_CellVec[x][z].m_PieceRange.GetCenter(); Pos.y = m_CellVec[x][z].m_PieceRange.m_Min.y; WorldToSCreen(Pos,World, viewport.Width, viewport.Height); Rect2D<float> rect(Pos.x, Pos.y, Pos.x + 50, Pos.y + 20); wstring str(L""); str += Util::IntToWStr(x); str += L","; str += Util::IntToWStr(z); if (Pos.z < viewport.MinDepth || Pos.z > viewport.MaxDepth) { StringPtr->InsertTextBlock(rect, str, true); } else { StringPtr->InsertTextBlock(rect, str, false); } } } } //-------------------------------------------------------------------------------------- // ステージのセルマップ(派生クラスを作るかインスタンスを作成する) //-------------------------------------------------------------------------------------- StageCellMap::StageCellMap(const shared_ptr<Stage>& StagePtr, const bsm::Vec3& MiniPos, float PieceSize, UINT PieceCountX, UINT PieceCountZ, int DefaultCost): GameObject(StagePtr), pImpl(new Impl()) { pImpl->Init(MiniPos, PieceSize, PieceCountX, PieceCountZ, DefaultCost); } StageCellMap::~StageCellMap() {} bool StageCellMap::IsCellStringActive() { return pImpl->m_IsCellStringActive; } void StageCellMap::SetCellStringActive(bool b) { pImpl->m_IsCellStringActive = b; } vector<vector<CellPiece>>& StageCellMap::GetCellVec() const { return pImpl->m_CellVec; } //初期化 void StageCellMap::OnCreate(){ pImpl->Create(AddComponent<MultiStringSprite>(), GetStage()); SetDrawActive(false); } bool StageCellMap::FindCell(const bsm::Vec3& Pos, CellIndex& ret) { for (UINT x = 0; x < pImpl->m_CellVec.size(); x++) { for (UINT z = 0; z < pImpl->m_CellVec[x].size(); z++) { if (pImpl->m_CellVec[x][z].m_PieceRange.PtInAABB(Pos)) { ret = pImpl->m_CellVec[x][z].m_Index; return true; } } } return false; } void StageCellMap::FindNearCell(const bsm::Vec3& Pos, CellIndex& ret) { if (FindCell(Pos, ret)) { return; } float len = 0; bool isset = false; for (UINT x = 0; x < pImpl->m_CellVec.size(); x++) { for (UINT z = 0; z < pImpl->m_CellVec[x].size(); z++) { if (!isset) { auto cellcenter = pImpl->m_CellVec[x][z].m_PieceRange.GetCenter(); len = bsm::length(Pos - cellcenter); ret = pImpl->m_CellVec[x][z].m_Index; isset = true; } else { auto cellcenter = pImpl->m_CellVec[x][z].m_PieceRange.GetCenter(); auto templen = bsm::length(Pos - cellcenter); if (len > templen) { len = templen; ret = pImpl->m_CellVec[x][z].m_Index; } } } } } bool StageCellMap::FindAABB(const CellIndex& Index, AABB& ret) { for (UINT x = 0; x < pImpl->m_CellVec.size(); x++) { for (UINT z = 0; z < pImpl->m_CellVec[x].size(); z++) { if (pImpl->m_CellVec[x][z].m_Index == Index) { ret = pImpl->m_CellVec[x][z].m_PieceRange; return true; } } } return false; } void StageCellMap::FindNearAABB(const bsm::Vec3& Pos, AABB& ret) { CellIndex retcell; FindNearCell(Pos, retcell); ret = pImpl->m_CellVec[retcell.x][retcell.z].m_PieceRange; } void StageCellMap::GetMapAABB(AABB& ret) const { ret = pImpl->m_MapAABB; } void StageCellMap::RefleshCellMap(const bsm::Vec3& MiniPos, float PieceSize, UINT PieceCountX, UINT PieceCountZ, int DefaultCost) { pImpl->Init(MiniPos,PieceSize,PieceCountX, PieceCountZ,DefaultCost); pImpl->Create(GetComponent<MultiStringSprite>(), GetStage()); } void StageCellMap::OnUpdate() { if (pImpl->m_IsCellStringActive) { auto StringPtr = GetComponent<MultiStringSprite>(); Mat4x4 World, View, Proj; World.identity(); auto PtrCamera = GetStage()->GetView()->GetTargetCamera(); View = PtrCamera->GetViewMatrix(); Proj = PtrCamera->GetProjMatrix(); auto viewport = GetStage()->GetView()->GetTargetViewport(); World *= View; World *= Proj; size_t count = 0; for (UINT x = 0; x < pImpl->m_CellVec.size(); x++) { for (UINT z = 0; z < pImpl->m_CellVec[x].size(); z++) { Vec3 Pos = pImpl->m_CellVec[x][z].m_PieceRange.GetCenter(); Pos.y = pImpl->m_CellVec[x][z].m_PieceRange.m_Min.y; Pos = pImpl->WorldToSCreen(Pos, World, viewport.Width, viewport.Height); Rect2D<float> rect(Pos.x, Pos.y, Pos.x + 50, Pos.y + 50); wstring str(L""); str += Util::IntToWStr(x); str += L","; str += Util::IntToWStr(z); str += L"\nCost: "; str += Util::IntToWStr(pImpl->m_CellVec[x][z].m_Cost); if (Pos.z < viewport.MinDepth || Pos.z > viewport.MaxDepth) { StringPtr->UpdateTextBlock(count, rect, str, true); } else { StringPtr->UpdateTextBlock(count, rect, str, false); } count++; } } } } void StageCellMap::OnDraw() { if (pImpl->m_IsCellStringActive) { GameObject::OnDraw(); } auto Dev = App::GetApp()->GetDeviceResources(); auto pD3D11DeviceContext = Dev->GetD3DDeviceContext(); auto RenderState = Dev->GetRenderState(); //行列の定義 bsm::Mat4x4 World, View, Proj; //ワールド行列の決定 bsm::Quat Qt; Qt.normalize(); World.affineTransformation( bsm::Vec3(1.0, 1.0, 1.0), //スケーリング bsm::Vec3(0, 0, 0), //回転の中心(重心) Qt, //回転角度 bsm::Vec3(0, 0.01f, 0) //位置 ); //転置する World = bsm::transpose(World); //カメラを得る auto CameraPtr = OnGetDrawCamera(); //ビューと射影行列を得る View = CameraPtr->GetViewMatrix(); //転置する View = bsm::transpose(View); //転置する Proj = CameraPtr->GetProjMatrix(); Proj = bsm::transpose(Proj); //コンスタントバッファの準備 SimpleConstants sb; sb.World = World; sb.View = View; sb.Projection = Proj; //エミッシブ加算は行わない。 sb.Emissive = bsm::Col4(0, 0, 0, 0); sb.Diffuse = bsm::Col4(1, 1, 1, 1); //コンスタントバッファの更新 pD3D11DeviceContext->UpdateSubresource(CBSimple::GetPtr()->GetBuffer(), 0, nullptr, &sb, 0, 0); //ストライドとオフセット UINT stride = sizeof(VertexPositionColor); UINT offset = 0; //頂点バッファのセット pD3D11DeviceContext->IASetVertexBuffers(0, 1, pImpl->m_LineMesh->GetVertexBuffer().GetAddressOf(), &stride, &offset); //描画方法(ライン) pD3D11DeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_LINELIST); //コンスタントバッファの設定 ID3D11Buffer* pConstantBuffer = CBSimple::GetPtr()->GetBuffer(); ID3D11Buffer* pNullConstantBuffer = nullptr; //頂点シェーダに渡す pD3D11DeviceContext->VSSetConstantBuffers(0, 1, &pConstantBuffer); //ピクセルシェーダに渡す pD3D11DeviceContext->PSSetConstantBuffers(0, 1, &pConstantBuffer); //シェーダの設定 pD3D11DeviceContext->VSSetShader(VSPCStatic::GetPtr()->GetShader(), nullptr, 0); pD3D11DeviceContext->PSSetShader(PSPCStatic::GetPtr()->GetShader(), nullptr, 0); //インプットレイアウトの設定 pD3D11DeviceContext->IASetInputLayout(VSPCStatic::GetPtr()->GetInputLayout()); //ブレンドステート pD3D11DeviceContext->OMSetBlendState(RenderState->GetOpaque(), nullptr, 0xffffffff); //デプスステンシルステート pD3D11DeviceContext->OMSetDepthStencilState(RenderState->GetDepthDefault(), 0); //ラスタライザステート pD3D11DeviceContext->RSSetState(RenderState->GetCullNone()); //描画 pD3D11DeviceContext->Draw(pImpl->m_Vertices.size(), 0); //後始末 Dev->InitializeStates(); } //-------------------------------------------------------------------------------------- // struct GameObjecttCSVBuilder::Impl; // 用途: Implイディオム //-------------------------------------------------------------------------------------- struct GameObjecttCSVBuilder::Impl { map<wstring, shared_ptr<GameObjectCreatorBaseCSV> > m_CreatorMap; Impl() {} ~Impl() {} }; //-------------------------------------------------------------------------------------- // ゲームオブジェクトビルダーCSV //-------------------------------------------------------------------------------------- GameObjecttCSVBuilder::GameObjecttCSVBuilder() : pImpl(new Impl()) { } GameObjecttCSVBuilder::~GameObjecttCSVBuilder() {} map<wstring, shared_ptr<GameObjectCreatorBaseCSV>>& GameObjecttCSVBuilder::GetCreatorMap() const { return pImpl->m_CreatorMap; } shared_ptr<GameObject> GameObjecttCSVBuilder::CreateFromCSV(const wstring& ClsName, const shared_ptr<Stage>& StagePtr, const wstring& Line) { auto it = pImpl->m_CreatorMap.find(ClsName); if (it == pImpl->m_CreatorMap.end()) { return nullptr; } else { auto ptr = (*it).second->Create(StagePtr, Line); return ptr; } } void GameObjecttCSVBuilder::Build(const shared_ptr<Stage>& StagePtr, const wstring& CSVFileName) { try { //CSVファイル CsvFile GameStageCsv(CSVFileName); GameStageCsv.ReadCsv(); //CSVの全体の配列 //CSVからすべての行を抜き出す auto& LineVec = GameStageCsv.GetCsvVec(); for (auto& v : LineVec) { //トークン(カラム)の配列 vector<wstring> Tokens; Util::WStrToTokenVector(Tokens,v, L','); CreateFromCSV(Tokens[0], StagePtr, v); } } catch (...) { throw; } } //-------------------------------------------------------------------------------------- // struct GameObjecttXMLBuilder::Impl; // 用途: Implイディオム //-------------------------------------------------------------------------------------- struct GameObjecttXMLBuilder::Impl { map<wstring, shared_ptr<GameObjectCreatorBaseXML> > m_CreatorMap; Impl() {} ~Impl() {} }; //-------------------------------------------------------------------------------------- // ゲームオブジェクトビルダーXML //-------------------------------------------------------------------------------------- GameObjecttXMLBuilder::GameObjecttXMLBuilder() : pImpl(new Impl()) { } GameObjecttXMLBuilder::~GameObjecttXMLBuilder() {} map<wstring, shared_ptr<GameObjectCreatorBaseXML>>& GameObjecttXMLBuilder::GetCreatorMap() const { return pImpl->m_CreatorMap; } shared_ptr<GameObject> GameObjecttXMLBuilder::CreateFromXML(const wstring& ClsName, const shared_ptr<Stage>& StagePtr, IXMLDOMNodePtr pNode) { auto it = pImpl->m_CreatorMap.find(ClsName); if (it == pImpl->m_CreatorMap.end()) { return nullptr; } else { auto ptr = (*it).second->Create(StagePtr, pNode); return ptr; } } void GameObjecttXMLBuilder::Build(const shared_ptr<Stage>& StagePtr, const wstring& XMLFileName, const wstring& GameObjectsPath) { try { //XMLリーダー XmlDocReader Reader(XMLFileName); auto Nodes = Reader.GetSelectNodes(GameObjectsPath.c_str()); long CountNode = XmlDocReader::GetLength(Nodes); for (long i = 0; i < CountNode; i++) { auto Node = XmlDocReader::GetItem(Nodes, i); auto TypeStr = XmlDocReader::GetAttribute(Node, L"Type"); CreateFromXML(TypeStr, StagePtr, Node); } } catch (...) { throw; } } } //end basecross
[ "wiz.yamanoi@wiz.ac.jp" ]
wiz.yamanoi@wiz.ac.jp
c0c7ed00141c313da5115ae9bd5939b75c4186c4
b73c4889fc75167bca03a7e784a9bb6ff001db18
/generatebn_hpf.h
fc6487922fe735da8d21cac237fce85378f9f3cc
[ "MIT" ]
permissive
Atrix256/BlueNoiseDitherPatternGeneration
a3a81e49fe85f9ae5020b1c1439b5179c7c2bf2c
5120a9e0bcd26c22eb22f803d5add068d0335cd3
refs/heads/master
2020-05-27T17:56:30.218213
2019-06-19T12:15:13
2019-06-19T12:15:13
188,732,287
16
0
null
null
null
null
UTF-8
C++
false
false
352
h
#pragma once #include <vector> // generates blue noise by repeatedly high pass filtering white noise and fixing up the histogram // https://blog.demofox.org/2017/10/25/transmuting-white-noise-to-blue-red-green-purple/ void GenerateBN_HPF(std::vector<uint8_t>& blueNoise, size_t width, size_t numPasses = 5, float sigma = 1.0f, bool makeRed = false);
[ "alan.wolfe@gmail.com" ]
alan.wolfe@gmail.com
b1b4c2ec2cd8934ec9dbe97ac0e07ed374e1df4d
e2230714ab6050a8ee18318aee5d6392bdd0bcab
/Source/WindowsUnified/Catrobat.8.1/Catrobat/Catrobat.Player/Catrobat.Player.Shared/ShowBrick.h
72623121e35a507d1d9d82a2262ccb092190ce04
[]
no_license
davpro90/CatrobatForWindows
e858d5a377df268679086928b1ad67be7f243421
edaedbb0302131daca6ac32f21061325fb4c4d7c
refs/heads/master
2020-04-06T06:45:27.487468
2016-05-13T14:42:13
2016-05-13T14:42:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
174
h
#pragma once #include "Brick.h" namespace ProjectStructure { class ShowBrick : public Brick { public: ShowBrick(Script* parent); void Execute(); }; }
[ "CATROBAT\\hannes.hasenauer" ]
CATROBAT\hannes.hasenauer
7745ad895adc81d7b8f36486b81ee4f84a65e94a
8fa5521679cf0cb3c558240085e605a93486cfc6
/navigation/costmap_2d/include/costmap_2d/costmap_2d_ros.h
c9b640431b6ddf12db9310150c66172f46b18a3b
[ "MIT" ]
permissive
mrsd16teamd/loco_car
3c89e1f13af7810c293f4589d959ce371e6a969a
36e4ed685f9463ad689ca72eec80e0f05f1ad66c
refs/heads/master
2021-05-03T23:55:45.176412
2020-11-24T16:41:02
2020-11-24T16:41:02
71,826,846
52
23
null
null
null
null
UTF-8
C++
false
false
9,342
h
/********************************************************************* * * Software License Agreement (BSD License) * * Copyright (c) 2008, 2013, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Author: Eitan Marder-Eppstein * David V. Lu!! *********************************************************************/ #ifndef COSTMAP_2D_COSTMAP_2D_ROS_H_ #define COSTMAP_2D_COSTMAP_2D_ROS_H_ #include <costmap_2d/layered_costmap.h> #include <costmap_2d/layer.h> #include <costmap_2d/costmap_2d_publisher.h> #include <costmap_2d/Costmap2DConfig.h> #include <costmap_2d/footprint.h> #include <geometry_msgs/Polygon.h> #include <geometry_msgs/PolygonStamped.h> #include <dynamic_reconfigure/server.h> #include <pluginlib/class_loader.h> class SuperValue : public XmlRpc::XmlRpcValue { public: void setStruct(XmlRpc::XmlRpcValue::ValueStruct* a) { _type = TypeStruct; _value.asStruct = new XmlRpc::XmlRpcValue::ValueStruct(*a); } void setArray(XmlRpc::XmlRpcValue::ValueArray* a) { _type = TypeArray; _value.asArray = new std::vector<XmlRpc::XmlRpcValue>(*a); } }; namespace costmap_2d { /** @brief A ROS wrapper for a 2D Costmap. Handles subscribing to * topics that provide observations about obstacles in either the form * of PointCloud or LaserScan messages. */ class Costmap2DROS { public: /** * @brief Constructor for the wrapper * @param name The name for this costmap * @param tf A reference to a TransformListener */ Costmap2DROS(std::string name, tf::TransformListener& tf); ~Costmap2DROS(); /** * @brief Subscribes to sensor topics if necessary and starts costmap * updates, can be called to restart the costmap after calls to either * stop() or pause() */ void start(); /** * @brief Stops costmap updates and unsubscribes from sensor topics */ void stop(); /** * @brief Stops the costmap from updating, but sensor data still comes in over the wire */ void pause(); /** * @brief Resumes costmap updates */ void resume(); void updateMap(); /** * @brief Reset each individual layer */ void resetLayers(); /** @brief Same as getLayeredCostmap()->isCurrent(). */ bool isCurrent() { return layered_costmap_->isCurrent(); } /** * @brief Get the pose of the robot in the global frame of the costmap * @param global_pose Will be set to the pose of the robot in the global frame of the costmap * @return True if the pose was set successfully, false otherwise */ bool getRobotPose(tf::Stamped<tf::Pose>& global_pose) const; /** @brief Returns costmap name */ std::string getName() const { return name_; } /** @brief Returns the delay in transform (tf) data that is tolerable in seconds */ double getTransformTolerance() const { return transform_tolerance_; } /** @brief Return a pointer to the "master" costmap which receives updates from all the layers. * * Same as calling getLayeredCostmap()->getCostmap(). */ Costmap2D* getCostmap() { return layered_costmap_->getCostmap(); } /** * @brief Returns the global frame of the costmap * @return The global frame of the costmap */ std::string getGlobalFrameID() { return global_frame_; } /** * @brief Returns the local frame of the costmap * @return The local frame of the costmap */ std::string getBaseFrameID() { return robot_base_frame_; } LayeredCostmap* getLayeredCostmap() { return layered_costmap_; } /** @brief Returns the current padded footprint as a geometry_msgs::Polygon. */ geometry_msgs::Polygon getRobotFootprintPolygon() { return costmap_2d::toPolygon(padded_footprint_); } /** @brief Return the current footprint of the robot as a vector of points. * * This version of the footprint is padded by the footprint_padding_ * distance, set in the rosparam "footprint_padding". * * The footprint initially comes from the rosparam "footprint" but * can be overwritten by dynamic reconfigure or by messages received * on the "footprint" topic. */ std::vector<geometry_msgs::Point> getRobotFootprint() { return padded_footprint_; } /** @brief Return the current unpadded footprint of the robot as a vector of points. * * This is the raw version of the footprint without padding. * * The footprint initially comes from the rosparam "footprint" but * can be overwritten by dynamic reconfigure or by messages received * on the "footprint" topic. */ std::vector<geometry_msgs::Point> getUnpaddedRobotFootprint() { return unpadded_footprint_; } /** * @brief Build the oriented footprint of the robot at the robot's current pose * @param oriented_footprint Will be filled with the points in the oriented footprint of the robot */ void getOrientedFootprint(std::vector<geometry_msgs::Point>& oriented_footprint) const; /** @brief Set the footprint of the robot to be the given set of * points, padded by footprint_padding. * * Should be a convex polygon, though this is not enforced. * * First expands the given polygon by footprint_padding_ and then * sets padded_footprint_ and calls * layered_costmap_->setFootprint(). Also saves the unpadded * footprint, which is available from * getUnpaddedRobotFootprint(). */ void setUnpaddedRobotFootprint(const std::vector<geometry_msgs::Point>& points); /** @brief Set the footprint of the robot to be the given polygon, * padded by footprint_padding. * * Should be a convex polygon, though this is not enforced. * * First expands the given polygon by footprint_padding_ and then * sets padded_footprint_ and calls * layered_costmap_->setFootprint(). Also saves the unpadded * footprint, which is available from * getUnpaddedRobotFootprint(). */ void setUnpaddedRobotFootprintPolygon(const geometry_msgs::Polygon& footprint); protected: LayeredCostmap* layered_costmap_; std::string name_; tf::TransformListener& tf_; ///< @brief Used for transforming point clouds std::string global_frame_; ///< @brief The global frame for the costmap std::string robot_base_frame_; ///< @brief The frame_id of the robot base double transform_tolerance_; ///< timeout before transform errors private: /** @brief Set the footprint from the new_config object. * * If the values of footprint and robot_radius are the same in * new_config and old_config, nothing is changed. */ void readFootprintFromConfig(const costmap_2d::Costmap2DConfig &new_config, const costmap_2d::Costmap2DConfig &old_config); void resetOldParameters(ros::NodeHandle& nh); void reconfigureCB(costmap_2d::Costmap2DConfig &config, uint32_t level); void movementCB(const ros::TimerEvent &event); void mapUpdateLoop(double frequency); bool map_update_thread_shutdown_; bool stop_updates_, initialized_, stopped_, robot_stopped_; boost::thread* map_update_thread_; ///< @brief A thread for updating the map ros::Timer timer_; ros::Time last_publish_; ros::Duration publish_cycle; pluginlib::ClassLoader<Layer> plugin_loader_; tf::Stamped<tf::Pose> old_pose_; Costmap2DPublisher* publisher_; dynamic_reconfigure::Server<costmap_2d::Costmap2DConfig> *dsrv_; boost::recursive_mutex configuration_mutex_; ros::Subscriber footprint_sub_; ros::Publisher footprint_pub_; bool got_footprint_; std::vector<geometry_msgs::Point> unpadded_footprint_; std::vector<geometry_msgs::Point> padded_footprint_; float footprint_padding_; costmap_2d::Costmap2DConfig old_config_; }; // class Costmap2DROS } // namespace costmap_2d #endif // COSTMAP_2D_COSTMAP_2D_ROS_H
[ "kazuotani14@gmail.com" ]
kazuotani14@gmail.com
32ce7cc18ace5e714db6232d9c9465791e6d6c20
fe73a5f728a9731ecdac74765ce31d8c64b75af2
/thr.cpp
f4d0075af981e610acabefa1e29b92cbf747875c
[]
no_license
johnlarson/360mthrtut
e0ddaa4a6cc3a133fbfa9cca51634acc049cf1e5
60de167e99a9e7f290ee1df3d681a7026e4e97d0
refs/heads/master
2021-01-10T09:55:15.200781
2016-02-06T00:36:06
2016-02-06T00:36:06
51,114,845
0
0
null
null
null
null
UTF-8
C++
false
false
2,344
cpp
#include "thr.h" #define NQUEUE 100 #define ERROR -1 void sigHandler(int status); void setSigStuff(); void* threadHandler(void* arg); sem_t mutex, spaceOnQueue, workToDo; class SocketQueue { std::queue<int> stlqueue; public: void push(int sock) { sem_wait(&spaceOnQueue); sem_wait(&mutex); stlqueue.push(sock); sem_post(&mutex); sem_post(&workToDo); } int pop() { sem_wait(&workToDo); sem_wait(&mutex); int rval = stlqueue.front(); stlqueue.pop(); sem_post(&mutex); sem_post(&spaceOnQueue); return rval; } } sockQueue; struct ThreadArgs { int id; string directory; }; void server(int port, int threadNum, string directory) { setSigStuff(); long threadid; pthread_t threads[threadNum]; sem_init(&mutex, PTHREAD_PROCESS_PRIVATE, 1); sem_init(&workToDo, PTHREAD_PROCESS_PRIVATE, 0); sem_init(&spaceOnQueue, PTHREAD_PROCESS_PRIVATE, NQUEUE); for(threadid = 0; threadid < threadNum; threadid++) { struct ThreadArgs threadArgs; threadArgs.id = threadid; threadArgs.directory = directory; pthread_create(&threads[threadid], NULL, threadHandler, (void*)&threadArgs); } int sSocket; struct sockaddr_in address; setUpServerSocket(sSocket, address, port); int addressSize; while(1) { int pSocket = accept(sSocket, (struct sockaddr*)&address, (socklen_t*)&addressSize); sockQueue.push(pSocket); } pthread_exit(NULL); } void setSigStuff() { struct sigaction sigold, signew; signew.sa_handler=sigHandler; sigemptyset(&signew.sa_mask); sigaddset(&signew.sa_mask, SIGINT); signew.sa_flags = SA_RESTART; sigaction(SIGINT, &signew, &sigold); sigaction(SIGHUP, &signew, &sigold); sigaction(SIGPIPE, &signew, &sigold); } void sigHandler(int status) { printf("received signal %d\n", status); } void* threadHandler(void* arg) { struct ThreadArgs args = *((struct ThreadArgs*)arg); string root = args.directory; while(1) { int pSocket = sockQueue.pop(); linger lin; unsigned int y=sizeof(lin); lin.l_onoff=1; lin.l_linger=10; setsockopt(pSocket,SOL_SOCKET, SO_LINGER,&lin,sizeof(lin)); struct Request request = getRequest(pSocket); string path = joinPath(root, request.path); respond(pSocket, request.version, path, request.path); shutdown(pSocket, SHUT_RDWR); if(close(pSocket) == ERROR) { errorOut("Couldn't close message socket"); } } }
[ "john.robert.larson@gmail.com" ]
john.robert.larson@gmail.com
bf2ca8181fa40d7cdb9835af672ac132dc2aeffd
6606598ccb80cbf22519896c54a9022bbda8e897
/KitterzPE/Main.cpp
83a67dca24ad0dbe6728bb7937df14b7180b55cb
[]
no_license
rizkyblackhat/KitterzPE-Au-Edition
f5651e9050cd0078aec9807fa7c0ade8bb3d6059
e09634799ae114b0275cacff09203c698b1f3ca9
refs/heads/master
2023-01-02T05:29:37.457906
2020-10-20T18:34:13
2020-10-20T18:34:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,769
cpp
#define _CRT_SECURE_NO_WARNINGS 1 #include <windows.h> #include <string> #include <Commctrl.h> using namespace std; #include "Send.h" #include "Recv.h" #include "Resource.h" #include "Packet.h" #include "Bin.h" #include "PEraser.h" #pragma comment(lib, "comctl32.lib") //------------------------------------------------------------------------- HWND hTreeSend; HWND hTreeRecv; HWND hSend; HWND hRecv; char buf [1024]; BOOL SpamOn = FALSE; //--------------------------------------------------------------------- //Main Callback procedure BOOL CALLBACK SendDlg(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch(uMsg) { case WM_INITDIALOG: hTreeSend = GetDlgItem (hWnd, IDC_PACKETTREESEND); hSend = hWnd; InitCommonControls(); SetDlgItemText (hWnd, IDC_EPACKET, (LPCSTR)"30 00 02 00 45 45 00"); SetDlgItemText (hWnd, IDC_REPLACESTRING, (LPCSTR)"30 00 02 00 45 45 00"); SetDlgItemText (hWnd, IDC_DELAY, (LPCSTR)"300"); break; case WM_NOTIFY: { switch(LOWORD(wParam)) { case IDC_PACKETTREESEND: if(((LPNMHDR)lParam)->code == NM_DBLCLK) { char Text [1024]; HTREEITEM Selected = TreeView_GetSelection (hTreeSend); if (Selected == NULL) break; PacketEdit* Tmp = new PacketEdit; Tmp->isSend = TRUE; TV_ITEM Item; Item.mask = TVIF_TEXT; Item.pszText = Text; Item.cchTextMax = 1024; Item.hItem = Selected; SendDlgItemMessage(hWnd, IDC_PACKETTREESEND, TVM_GETITEM, TVGN_CARET, (LPARAM)&Item); if (!Tmp->ItemRootExists (Text)) SetDlgItemText (hWnd, IDC_EPACKET, (LPCSTR)Text); delete Tmp; } break; } break; } break; case WM_COMMAND: switch(LOWORD(wParam)) { //-------------------------------------------------------- case IDC_CLEAR: TreeView_DeleteItem (hTreeSend, TVI_ROOT); NodesSend_Num = 0; SetDlgItemText (hWnd, IDC_PACKETREPLACESTRING2, (LPCSTR)"FF 00 00 00 00 00 00"); break; case IDC_REMOVE: { int TheOne = SendMessage (GetDlgItem(hWnd, IDC_CHANGESLIST), LB_GETCURSEL , 0, 0); if (TheOne == -1) break; SendMessage (GetDlgItem(hWnd, IDC_CHANGESLIST), LB_DELETESTRING , TheOne, 0); } break; //-------------------------------------------------------- case IDC_BSENDPACKET: GetDlgItemText (hWnd, IDC_EPACKET, buf, 1024); if (SpamOn) { SpamOn = FALSE; SetDlgItemText (hWnd, IDC_BSENDPACKET, (LPCSTR)"Send Packet"); } else { if (SendMessage(GetDlgItem(hWnd, IDC_CHECKBOX1), BM_GETCHECK, 0, 0) == TRUE) { SpamOn = TRUE; SpamPacket (buf); SetDlgItemText (hWnd, IDC_BSENDPACKET, (LPCSTR)"STOP"); } else SendPacket (buf); } break; //-------------------------------------------------------- case IDC_DONTLOG: { char Text [1024]; HTREEITEM Selected = TreeView_GetSelection (hTreeSend); PacketEdit* Tmp = new PacketEdit; Tmp->isSend = TRUE; if (Selected == NULL) break; TV_ITEM Item; Item.mask = TVIF_TEXT; Item.pszText = Text; Item.cchTextMax = 1024; Item.hItem = Selected; SendDlgItemMessage(hWnd, IDC_PACKETTREESEND, TVM_GETITEM, TVGN_CARET, (LPARAM)&Item); if (Tmp->ItemRootExists (Text)) { BYTE ID = HexStrToInt (((string)Text).substr (11, 2).c_str()); sprintf (buf, "%02X - D", ID); SendMessage (GetDlgItem(hWnd, IDC_CHANGESLIST), LB_ADDSTRING , 0, (LPARAM)buf); } } break; //-------------------------------------------------------- case IDC_BLOCK: { char Text [1024]; HTREEITEM Selected = TreeView_GetSelection (hTreeSend); PacketEdit* Tmp = new PacketEdit; Tmp->isSend = TRUE; if (Selected == NULL) break; TV_ITEM Item; Item.mask = TVIF_TEXT; Item.pszText = Text; Item.cchTextMax = 1024; Item.hItem = Selected; SendDlgItemMessage(hWnd, IDC_PACKETTREESEND, TVM_GETITEM, TVGN_CARET, (LPARAM)&Item); if (Tmp->ItemRootExists (Text)) { BYTE ID = HexStrToInt (((string)Text).substr (11, 2).c_str()); sprintf (buf, "%02X - B", ID); SendMessage (GetDlgItem(hWnd, IDC_CHANGESLIST), LB_ADDSTRING , 0, (LPARAM)buf); } } break; //-------------------------------------------------------- case IDC_REPLACE: { char Text [1024]; HTREEITEM Selected = TreeView_GetSelection (hTreeSend); PacketEdit* Tmp = new PacketEdit; Tmp->isSend = TRUE; if (Selected == NULL) break; TV_ITEM Item; Item.mask = TVIF_TEXT; Item.pszText = Text; Item.cchTextMax = 1024; Item.hItem = Selected; SendDlgItemMessage(hWnd, IDC_PACKETTREESEND, TVM_GETITEM, TVGN_CARET, (LPARAM)&Item); if (Tmp->ItemRootExists (Text)) { BYTE ID = HexStrToInt (((string)Text).substr (11, 2).c_str()); GetDlgItemText (hWnd, IDC_REPLACESTRING, buf, 1024); string Temp = buf; replaceAll(Temp, " ", ""); sprintf (buf, "%02X - R - %s - %02i", ID, Temp.c_str(), (Temp.length() / 2)); SendMessage (GetDlgItem(hWnd, IDC_CHANGESLIST), LB_ADDSTRING , 0, (LPARAM)buf); } } break; //-------------------------------------------------------- } break; case WM_CLOSE: EndDialog(hWnd, 0); break; case WM_DESTROY: PostQuitMessage(0); break; default: break; } return 0; } //------------------------------------------------------------------------- //Main Callback procedure BOOL CALLBACK RecvDlg(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch(uMsg) { case WM_INITDIALOG: hTreeRecv = GetDlgItem (hWnd, IDC_PACKETTREERECV); hRecv = hWnd; InitCommonControls(); break; case WM_NOTIFY: { switch(LOWORD(wParam)) { case IDC_PACKETTREERECV: if(((LPNMHDR)lParam)->code == NM_DBLCLK) { char Text [1024]; HTREEITEM Selected = TreeView_GetSelection (hTreeRecv); if (Selected == NULL) break; PacketEdit* Tmp = new PacketEdit; Tmp->isSend = FALSE; TV_ITEM Item; Item.mask = TVIF_TEXT; Item.pszText = Text; Item.cchTextMax = 1024; Item.hItem = Selected; SendDlgItemMessage(hWnd, IDC_PACKETTREERECV, TVM_GETITEM, TVGN_CARET, (LPARAM)&Item); if (!Tmp->ItemRootExists (Text)) SetDlgItemText (hWnd, IDC_PACKETINFO, (LPCSTR)Text); delete Tmp; } break; } break; } break; case WM_COMMAND: switch(LOWORD(wParam)) { //-------------------------------------------------------- case IDC_CLEAR2: TreeView_DeleteItem (hTreeRecv, TVI_ROOT); NodesRecv_Num = 0; break; case IDC_REMOVE2: { int TheOne = SendMessage (GetDlgItem(hWnd, IDC_CHANGESLIST2), LB_GETCURSEL , 0, 0); if (TheOne == -1) break; SendMessage (GetDlgItem(hWnd, IDC_CHANGESLIST2), LB_DELETESTRING , TheOne, 0); } break; //-------------------------------------------------------- case IDC_DONTLOG2: { char Text [1024]; HTREEITEM Selected = TreeView_GetSelection (hTreeRecv); PacketEdit* Tmp = new PacketEdit; Tmp->isSend = FALSE; if (Selected == NULL) break; TV_ITEM Item; Item.mask = TVIF_TEXT; Item.pszText = Text; Item.cchTextMax = 1024; Item.hItem = Selected; SendDlgItemMessage(hWnd, IDC_PACKETTREERECV, TVM_GETITEM, TVGN_CARET, (LPARAM)&Item); if (Tmp->ItemRootExists (Text)) { BYTE ID = HexStrToInt (((string)Text).substr (0, 2).c_str()); sprintf (buf, "%02X - D", ID); SendMessage (GetDlgItem(hWnd, IDC_CHANGESLIST2), LB_ADDSTRING , 0, (LPARAM)buf); } } break; //-------------------------------------------------------- case IDC_BLOCK2: { char Text [1024]; HTREEITEM Selected = TreeView_GetSelection (hTreeRecv); PacketEdit* Tmp = new PacketEdit; Tmp->isSend = FALSE; if (Selected == NULL) break; TV_ITEM Item; Item.mask = TVIF_TEXT; Item.pszText = Text; Item.cchTextMax = 1024; Item.hItem = Selected; SendDlgItemMessage(hWnd, IDC_PACKETTREERECV, TVM_GETITEM, TVGN_CARET, (LPARAM)&Item); if (Tmp->ItemRootExists (Text)) { BYTE ID = HexStrToInt (((string)Text).substr (0, 2).c_str()); sprintf (buf, "%02X - B", ID); SendMessage (GetDlgItem(hWnd, IDC_CHANGESLIST2), LB_ADDSTRING , 0, (LPARAM)buf); } } break; //-------------------------------------------------------- case IDC_REPLACE2: { char Text [1024]; HTREEITEM Selected = TreeView_GetSelection (hTreeRecv); PacketEdit* Tmp = new PacketEdit; Tmp->isSend = FALSE; if (Selected == NULL) break; TV_ITEM Item; Item.mask = TVIF_TEXT; Item.pszText = Text; Item.cchTextMax = 1024; Item.hItem = Selected; SendDlgItemMessage(hWnd, IDC_PACKETTREERECV, TVM_GETITEM, TVGN_CARET, (LPARAM)&Item); if (Tmp->ItemRootExists (Text)) { BYTE ID = HexStrToInt (((string)Text).substr (0, 2).c_str()); GetDlgItemText (hWnd, IDC_PACKETREPLACESTRING2, buf, 1024); string Temp = buf; replaceAll(Temp, " ", ""); sprintf (buf, "%02X - R - %s - %02i", ID, Temp.c_str(), (Temp.length() / 2)); SendMessage (GetDlgItem(hWnd, IDC_CHANGESLIST2), LB_ADDSTRING , 0, (LPARAM)buf); } } break; //-------------------------------------------------------- } break; case WM_CLOSE: EndDialog(hWnd, 0); break; case WM_DESTROY: PostQuitMessage(0); break; default: break; } return 0; } //-------------------------------------------------------------------- DWORD WINAPI Send (HMODULE hModule) { //GetPacketAddysSend(); //PacketSendHook (); //DialogBox(hModule, MAKEINTRESOURCE(IDD_SEND), NULL, (DLGPROC)SendDlg); return 1; } DWORD WINAPI Recv (HMODULE hModule) { PacketRecvHook(); DialogBox(hModule, MAKEINTRESOURCE(IDD_RECV), NULL, (DLGPROC)RecvDlg); PEraser *pRaser = new PEraser(); pRaser->Erase((void*)hModule); return 1; } //-------------------------------------------------------------------- //Entry Point into program. BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: //CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&Send, hModule, 0, NULL); CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&Recv, hModule, 0, NULL); break; } return TRUE; } //-------------------------------------------------------------------------
[ "vmuser@github.com" ]
vmuser@github.com
ed2e8945f492902ef9d3ea537c41a072e898ab9d
693130b3aa7d908217d10d3f8c025e26da964056
/build/moc_walletstack.cpp
2167d68912830c06a2d3b7fedddbab22693f15f4
[]
no_license
PlatinumNote/PlatinumCoin
2d17b8461f1f857eb5a507b839f46d7e5d5eb342
793f993ef6a6e1d1d572c4f46a82fab3a20dcb75
refs/heads/master
2021-01-02T09:02:11.468722
2015-02-17T03:29:50
2015-02-17T03:29:50
30,900,716
0
2
null
2015-02-17T03:19:28
2015-02-17T03:19:27
null
UTF-8
C++
false
false
5,824
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'walletstack.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.0.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../src/qt/walletstack.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'walletstack.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.0.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_WalletStack_t { QByteArrayData data[18]; char stringdata[257]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ offsetof(qt_meta_stringdata_WalletStack_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData) \ ) static const qt_meta_stringdata_WalletStack_t qt_meta_stringdata_WalletStack = { { QT_MOC_LITERAL(0, 0, 11), QT_MOC_LITERAL(1, 12, 16), QT_MOC_LITERAL(2, 29, 0), QT_MOC_LITERAL(3, 30, 4), QT_MOC_LITERAL(4, 35, 16), QT_MOC_LITERAL(5, 52, 15), QT_MOC_LITERAL(6, 68, 19), QT_MOC_LITERAL(7, 88, 20), QT_MOC_LITERAL(8, 109, 17), QT_MOC_LITERAL(9, 127, 4), QT_MOC_LITERAL(10, 132, 18), QT_MOC_LITERAL(11, 151, 20), QT_MOC_LITERAL(12, 172, 13), QT_MOC_LITERAL(13, 186, 6), QT_MOC_LITERAL(14, 193, 12), QT_MOC_LITERAL(15, 206, 16), QT_MOC_LITERAL(16, 223, 12), QT_MOC_LITERAL(17, 236, 19) }, "WalletStack\0setCurrentWallet\0\0name\0" "gotoOverviewPage\0gotoHistoryPage\0" "gotoAddressBookPage\0gotoReceiveCoinsPage\0" "gotoSendCoinsPage\0addr\0gotoSignMessageTab\0" "gotoVerifyMessageTab\0encryptWallet\0" "status\0backupWallet\0changePassphrase\0" "unlockWallet\0setEncryptionStatus\0" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_WalletStack[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 16, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 1, 94, 2, 0x0a, 4, 0, 97, 2, 0x0a, 5, 0, 98, 2, 0x0a, 6, 0, 99, 2, 0x0a, 7, 0, 100, 2, 0x0a, 8, 1, 101, 2, 0x0a, 8, 0, 104, 2, 0x2a, 10, 1, 105, 2, 0x0a, 10, 0, 108, 2, 0x2a, 11, 1, 109, 2, 0x0a, 11, 0, 112, 2, 0x2a, 12, 1, 113, 2, 0x0a, 14, 0, 116, 2, 0x0a, 15, 0, 117, 2, 0x0a, 16, 0, 118, 2, 0x0a, 17, 0, 119, 2, 0x0a, // slots: parameters QMetaType::Void, QMetaType::QString, 3, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::QString, 9, QMetaType::Void, QMetaType::Void, QMetaType::QString, 9, QMetaType::Void, QMetaType::Void, QMetaType::QString, 9, QMetaType::Void, QMetaType::Void, QMetaType::Bool, 13, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, 0 // eod }; void WalletStack::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { WalletStack *_t = static_cast<WalletStack *>(_o); switch (_id) { case 0: _t->setCurrentWallet((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 1: _t->gotoOverviewPage(); break; case 2: _t->gotoHistoryPage(); break; case 3: _t->gotoAddressBookPage(); break; case 4: _t->gotoReceiveCoinsPage(); break; case 5: _t->gotoSendCoinsPage((*reinterpret_cast< QString(*)>(_a[1]))); break; case 6: _t->gotoSendCoinsPage(); break; case 7: _t->gotoSignMessageTab((*reinterpret_cast< QString(*)>(_a[1]))); break; case 8: _t->gotoSignMessageTab(); break; case 9: _t->gotoVerifyMessageTab((*reinterpret_cast< QString(*)>(_a[1]))); break; case 10: _t->gotoVerifyMessageTab(); break; case 11: _t->encryptWallet((*reinterpret_cast< bool(*)>(_a[1]))); break; case 12: _t->backupWallet(); break; case 13: _t->changePassphrase(); break; case 14: _t->unlockWallet(); break; case 15: _t->setEncryptionStatus(); break; default: ; } } } const QMetaObject WalletStack::staticMetaObject = { { &QStackedWidget::staticMetaObject, qt_meta_stringdata_WalletStack.data, qt_meta_data_WalletStack, qt_static_metacall, 0, 0} }; const QMetaObject *WalletStack::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *WalletStack::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_WalletStack.stringdata)) return static_cast<void*>(const_cast< WalletStack*>(this)); return QStackedWidget::qt_metacast(_clname); } int WalletStack::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QStackedWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 16) qt_static_metacall(this, _c, _id, _a); _id -= 16; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 16) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 16; } return _id; } QT_END_MOC_NAMESPACE
[ "info@plt.co.in" ]
info@plt.co.in
25414545cb454e78ecd918153240c09da4454859
d9d2f39c057bb08ebad5f57875b9af693d821781
/exam_tasks/33_swap_digits.cpp
9511bcfa6dfc9cad832de7aea17530cebeadc895
[]
no_license
denis9570/tsi_tasks
4f6bed799bf2568495736828b3d7247e0dc5d78e
24beffbd4cb9abd2dc2f1272ad775da7793f08ec
refs/heads/master
2021-01-21T14:04:23.932262
2019-08-16T17:01:33
2019-08-16T17:01:33
43,598,026
0
0
null
null
null
null
UTF-8
C++
false
false
540
cpp
#include<iostream> using namespace std; // this code is distributed under the GNU GPL license int main() { /* * вести двузначное число a. ѕомен¤ть цифры * числа местами использу¤ математические * операции */ int a; cout << "Enter your two-digit number" << endl; cin >> a; int last_digit = a % 10, first_digit = a / 10; cout << last_digit << first_digit << endl; return 0; }
[ "Artur Klesun" ]
Artur Klesun
3e85588e75dd35572f3fe90a5164056a9bea85c8
1b4c4a4ee818960875a77d41d73461f67af2a7ea
/test/header/cplusplus.h
d2e1866f9ca01b24b96eaa7307067ad9b28b1997
[ "BSD-3-Clause" ]
permissive
amirrajan/rubymotion-bridgesupport
bcc299082e828863091f5b62f247273aa2d7c959
da0742cdd9e4a2ea5c57e6fcd9297de65d1ee003
refs/heads/master
2023-08-09T20:11:21.739514
2023-08-04T08:52:38
2023-08-04T08:56:55
133,582,108
7
3
NOASSERTION
2021-01-21T23:15:49
2018-05-15T22:59:47
C++
UTF-8
C++
false
false
212
h
#include <string> #define TestStringConstant "foo" namespace TestNameSpace { class FooBarBaz { FooBarBaz(); ~FooBarBaz(); private: int age; std::string name; }; }
[ "watson1978@gmail.com" ]
watson1978@gmail.com
7b2a2192744d83eceb2958f3e0ffce53bea7e898
9aab6127f6cfbbbf5a9300bce43a3723c580a830
/src/Effect.hpp
df16bb6c0fb4eebedcbb0cc2667479b565e17eb0
[]
no_license
clarkeaa/sinedrops
3ceffb56ad758d5374a0a9deea53dc485b7435d6
feabd97fc2fb5c4ef065deb842c45345eb4e03f1
refs/heads/master
2020-05-17T19:26:02.246635
2015-12-15T19:39:42
2015-12-15T19:39:42
23,173,658
0
0
null
null
null
null
UTF-8
C++
false
false
156
hpp
#pragma once class MTime; struct RenderInfo; class Effect { public: virtual ~Effect() {} virtual int fillBuffer(const RenderInfo& rinfo) =0; };
[ "aaron@voidbred.com" ]
aaron@voidbred.com
b2f998cc16c2322b85484691cd0d0e60ea3206ef
9d44d4d8b4a9fce052e8f321a5006080f3246876
/ino/pulse_pin_test/src/pulse_test.ino
1badaa18a935faa267129ca7e15398aece6a67b9
[]
no_license
n800sau/roborep
b4d92754be65dc120881b54d9788034cfa09dac6
adaef48d0498609d3db90c090a09ddb0141d4a1a
refs/heads/master
2023-08-30T13:58:30.082902
2023-08-19T08:52:12
2023-08-19T08:52:12
72,965,794
1
0
null
null
null
null
UTF-8
C++
false
false
943
ino
// seq: DTR 0 .. 400 .. 0 .. 200 .. 1 - boot_mode // RTS 0 .. ...... 1 ......... 1 - reset // A4 - DTR // A5 - RTS int pins[] = {A1, A2, A4, A5}; String s_pins[] = {"1", "2", "4", "5"}; //unsigned long duration; const int pincount = sizeof(pins)/sizeof(pins[0]); void setup() { for(int i=0; i<pincount; i++) { pinMode(pins[i], INPUT); } Serial.begin(115200); Serial.println("hello"); } String old_state = ""; unsigned long m = 0; void loop() { String state = ""; for(int i=0; i<pincount; i++) { state += (digitalRead(pins[i]) == HIGH) ? s_pins[i] : "O"; } if(state != old_state) { Serial.print(old_state); Serial.print(" -> "); Serial.print(state); unsigned long new_m = millis(); if(m > 0) { Serial.print(" - "); Serial.print(new_m - m); } Serial.println(); m = new_m; old_state = state; } // duration = pulseIn(pin, HIGH); // if(duration > 0) { // Serial.println(duration); // } delay(200); }
[ "n800sau@gmail.com" ]
n800sau@gmail.com
06472042ebd9fefc11beb27a516a35171914d574
8b9229ba6d43c5ae3cc9816003f99d8efe3d50a4
/dp/fx/src/Snippet.cpp
9364a17cea30d0f917c771eddd8e1474c79e5d52
[]
no_license
JamesLinus/pipeline
02aef690636f1d215a135b971fa34a9e09a6b901
27322a5527deb69c14bd70dd99374b52709ae157
refs/heads/master
2021-01-16T22:14:56.899613
2016-03-22T10:39:59
2016-03-22T10:39:59
56,539,375
1
0
null
2016-04-18T20:22:33
2016-04-18T20:22:32
null
UTF-8
C++
false
false
2,351
cpp
// Copyright NVIDIA Corporation 2012 // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <dp/fx/inc/Snippet.h> #include <sstream> namespace dp { namespace fx { bool Snippet::addRequiredEnumSpec( const EnumSpecSharedPtr & enumSpec ) { return( m_requiredEnumSpecs.insert( enumSpec ).second ); } const std::set<EnumSpecSharedPtr> & Snippet::getRequiredEnumSpecs() const { return( m_requiredEnumSpecs ); } std::string generateSnippets( std::vector<SnippetSharedPtr> snippets, GeneratorConfiguration& configuration ) { std::ostringstream oss; for ( std::vector<SnippetSharedPtr>::iterator it = snippets.begin(); it != snippets.end(); ++it ) { oss << (*it)->getSnippet( configuration ) << std::endl; } return oss.str(); } } // namespace fx } // namespace dp
[ "matavenrath@nvidia.com" ]
matavenrath@nvidia.com
92ff081f822863f9d7744a82bd6fe69d29cb90d6
41b187b3cf2b9256e4b2c645336fb9b9406f357e
/houjie/programDesign/1/oop-window-file-system.cpp
522d6a8091b693f9668ed8520c7017e1d62c5d82
[]
no_license
jiaobendaye/c-learn
830a281c7f7535891c55a68e6260be568987582c
7548b47a9fb0afa97b9341f6088991933693ea2b
refs/heads/master
2020-07-30T06:55:46.595060
2020-01-12T08:53:17
2020-01-12T08:53:17
210,124,921
0
0
null
null
null
null
UTF-8
C++
false
false
371
cpp
class Component { int val; public: Component(int value): val (value) {} virtual void add(Component*) {} }; class Primitive: public Component { public: Primitive(int val): Component(val) {} }; class Composite: public Component { vector<Component*> c; public: Composite(int val): Component(val) {} void add(Component* elem){ c.push_back(elem); } };
[ "240450828@qq.com" ]
240450828@qq.com
44e2cf372facf3307f0bec6c79bd9caba808ca6f
824c053a54e6e92479d797efc0c817d059f038aa
/limonp/Thread.hpp
fd7aa8274675f4fc6e58fbc9d2a9fed6e26a639e
[]
no_license
samevers/posTrunk
c75e262a5de40abef2645febcd83a7168bb13302
eb9d8fde22535d3504ff2ccc1f670cc9668af648
refs/heads/master
2021-01-19T04:22:52.144090
2016-06-22T06:47:04
2016-06-22T06:47:04
61,695,444
0
0
null
null
null
null
UTF-8
C++
false
false
829
hpp
#ifndef LIMONP_THREAD_HPP #define LIMONP_THREAD_HPP #include "Logging.hpp" #include "NonCopyable.hpp" namespace limonp { class IThread: NonCopyable { public: IThread(): isStarted(false), isJoined(false) { } virtual ~IThread() { if(isStarted && !isJoined) { CHECK(!pthread_detach(thread_)); } }; virtual void Run() = 0; void Start() { CHECK(!isStarted); CHECK(!pthread_create(&thread_, NULL, Worker, this)); isStarted = true; } void Join() { CHECK(!isJoined); CHECK(!pthread_join(thread_, NULL)); isJoined = true; } private: static void * Worker(void * data) { IThread * ptr = (IThread* ) data; ptr->Run(); return NULL; } pthread_t thread_; bool isStarted; bool isJoined; }; // class IThread } // namespace limonp #endif // LIMONP_THREAD_HPP
[ "root@sjs_28_27.(none)" ]
root@sjs_28_27.(none)
94443525fd24c2253c3dea74404d3e9b61f9b910
d8e7a11322f6d1b514c85b0c713bacca8f743ff5
/7.6.00.37/V76_00_37/MaxDB_ORG/sys/src/SAPDB/Interfaces/Runtime/IFR_SQLWarning.cpp
6bc589ad8b34aab62e19c103772757550fd58c07
[]
no_license
zhaonaiy/MaxDB_GPL_Releases
a224f86c0edf76e935d8951d1dd32f5376c04153
15821507c20bd1cd251cf4e7c60610ac9cabc06d
refs/heads/master
2022-11-08T21:14:22.774394
2020-07-07T00:52:44
2020-07-07T00:52:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,695
cpp
/*! @file IFR_SQLWarning.cpp @author D039759 @ingroup IFR_Common @brief SQL Warnings @see \if EMIT_LICENCE ========== licence begin GPL Copyright (c) 2001-2005 SAP AG This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ========== licence end \endif */ #include "Interfaces/Runtime/IFR_SQLWarning.h" IFR_BEGIN_NAMESPACE //---------------------------------------------------------------------- IFR_SQLWarning::IFR_SQLWarning(IFR_SQLWarningCode warningcode) :m_warningcode(warningcode), m_nextwarning(0) {} //---------------------------------------------------------------------- IFR_SQLWarning::~IFR_SQLWarning() { } //---------------------------------------------------------------------- void IFR_SQLWarning::addWarning(IFR_SQLWarning* warning) { IFR_SQLWarning *p=this; while(p->m_nextwarning) { if(p==warning) { return; } p=p->m_nextwarning; } p->m_nextwarning=warning; } IFR_END_NAMESPACE
[ "gunter.mueller@gmail.com" ]
gunter.mueller@gmail.com
4633bca27a860a7a81a441705584c19c7bd430c3
7480eff00e5c144d0ecb70c5e208df13e1849d1e
/LoginApp/mainwindow.h
0c4e175017ab51b93cc4cec765567f2bf8b175cd
[ "MIT" ]
permissive
nicolaschen1/LoginApp
6771de27110570f0bb2ba7186ab45ac2bda35d47
c69e76ceb398a6e2f8e5b491496cf56c91195ade
refs/heads/master
2020-04-14T22:03:38.806854
2019-01-04T20:06:52
2019-01-04T20:06:52
164,149,557
0
0
null
null
null
null
UTF-8
C++
false
false
429
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include "secdialog.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = nullptr); ~MainWindow(); private slots: void on_pushButton_Login_clicked(); private: Ui::MainWindow *ui; SecDialog *secDialog; }; #endif // MAINWINDOW_H
[ "noreply@github.com" ]
noreply@github.com
882adfb6e1a4036d7eec74f0a876ba2321cf005b
ce7f67e41fcd94ef49d1ee07cf73bcc312ba5153
/medium/61_Rotate_List/61_Rotate_List/61_Rotate_List.cpp
143627c4105c4677a92b8b35e10b67fdb44a55f7
[]
no_license
xixuecao/LeetCode
56716fc34b3010e22339d57694418a9546278081
3ed5754037c15dc83965c9216fee1eef652d4b07
refs/heads/master
2022-05-27T14:28:36.796859
2020-04-24T23:31:51
2020-04-24T23:31:51
205,614,300
0
1
null
null
null
null
UTF-8
C++
false
false
1,305
cpp
// 61_Rotate_List.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include <iostream> using namespace std; struct ListNode { int val; ListNode* next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* rotateRight(ListNode* head, int k) { if (!head) return NULL; int len = 1; ListNode* cur = head; while (cur->next) { len++; cur = cur->next; } k %= len; cur->next = head; for (int i = 0; i < len - k; i++) cur = cur->next; ListNode* res = cur->next; cur->next = NULL; return res; }; int main() { std::cout << "Hello World!\n"; } // 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单 // 调试程序: F5 或调试 >“开始调试”菜单 // 入门使用技巧: // 1. 使用解决方案资源管理器窗口添加/管理文件 // 2. 使用团队资源管理器窗口连接到源代码管理 // 3. 使用输出窗口查看生成输出和其他消息 // 4. 使用错误列表窗口查看错误 // 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目 // 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
[ "xixuecao@gmail.com" ]
xixuecao@gmail.com
c9026ceeae875b67f98a733c89233c6ed93352ff
11ef4bbb8086ba3b9678a2037d0c28baaf8c010e
/Source Code/server/binaries/chromium/gen/services/shape_detection/public/mojom/barcodedetection.mojom-blink.h
8264245509bc12cc7603a0721566a1f6a7e4d218
[]
no_license
lineCode/wasmview.github.io
8f845ec6ba8a1ec85272d734efc80d2416a6e15b
eac4c69ea1cf0e9af9da5a500219236470541f9b
refs/heads/master
2020-09-22T21:05:53.766548
2019-08-24T05:34:04
2019-08-24T05:34:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,369
h
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SERVICES_SHAPE_DETECTION_PUBLIC_MOJOM_BARCODEDETECTION_MOJOM_BLINK_H_ #define SERVICES_SHAPE_DETECTION_PUBLIC_MOJOM_BARCODEDETECTION_MOJOM_BLINK_H_ #include <stdint.h> #include <limits> #include <type_traits> #include <utility> #include "base/callback.h" #include "base/macros.h" #include "base/optional.h" #include "mojo/public/cpp/bindings/mojo_buildflags.h" #if BUILDFLAG(MOJO_TRACE_ENABLED) #include "base/trace_event/trace_event.h" #endif #include "mojo/public/cpp/bindings/clone_traits.h" #include "mojo/public/cpp/bindings/equals_traits.h" #include "mojo/public/cpp/bindings/lib/serialization.h" #include "mojo/public/cpp/bindings/struct_ptr.h" #include "mojo/public/cpp/bindings/struct_traits.h" #include "mojo/public/cpp/bindings/union_traits.h" #include "services/shape_detection/public/mojom/barcodedetection.mojom-shared.h" #include "services/shape_detection/public/mojom/barcodedetection.mojom-blink-forward.h" #include "skia/public/interfaces/bitmap.mojom-blink.h" #include "ui/gfx/geometry/mojo/geometry.mojom-blink.h" #include "mojo/public/cpp/bindings/lib/wtf_clone_equals_util.h" #include "mojo/public/cpp/bindings/lib/wtf_hash_util.h" #include "third_party/blink/renderer/platform/wtf/hash_functions.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" #include "mojo/public/cpp/bindings/associated_interface_ptr.h" #include "mojo/public/cpp/bindings/associated_interface_ptr_info.h" #include "mojo/public/cpp/bindings/associated_interface_request.h" #include "mojo/public/cpp/bindings/interface_ptr.h" #include "mojo/public/cpp/bindings/interface_request.h" #include "mojo/public/cpp/bindings/lib/control_message_handler.h" #include "mojo/public/cpp/bindings/raw_ptr_impl_ref_traits.h" #include "mojo/public/cpp/bindings/thread_safe_interface_ptr.h" #include "mojo/public/cpp/bindings/lib/native_enum_serialization.h" #include "mojo/public/cpp/bindings/lib/native_struct_serialization.h" namespace WTF { struct shape_detection_mojom_internal_BarcodeFormat_DataHashFn { static unsigned GetHash(const ::shape_detection::mojom::BarcodeFormat& value) { using utype = std::underlying_type<::shape_detection::mojom::BarcodeFormat>::type; return DefaultHash<utype>::Hash().GetHash(static_cast<utype>(value)); } static bool Equal(const ::shape_detection::mojom::BarcodeFormat& left, const ::shape_detection::mojom::BarcodeFormat& right) { return left == right; } static const bool safe_to_compare_to_empty_or_deleted = true; }; template <> struct HashTraits<::shape_detection::mojom::BarcodeFormat> : public GenericHashTraits<::shape_detection::mojom::BarcodeFormat> { static_assert(true, "-1000000 is a reserved enum value"); static_assert(true, "-1000001 is a reserved enum value"); static const bool hasIsEmptyValueFunction = true; static bool IsEmptyValue(const ::shape_detection::mojom::BarcodeFormat& value) { return value == static_cast<::shape_detection::mojom::BarcodeFormat>(-1000000); } static void ConstructDeletedValue(::shape_detection::mojom::BarcodeFormat& slot, bool) { slot = static_cast<::shape_detection::mojom::BarcodeFormat>(-1000001); } static bool IsDeletedValue(const ::shape_detection::mojom::BarcodeFormat& value) { return value == static_cast<::shape_detection::mojom::BarcodeFormat>(-1000001); } }; } // namespace WTF namespace shape_detection { namespace mojom { namespace blink { class BarcodeDetectionProxy; template <typename ImplRefTraits> class BarcodeDetectionStub; class BarcodeDetectionRequestValidator; class BarcodeDetectionResponseValidator; class BarcodeDetection : public BarcodeDetectionInterfaceBase { public: static const char Name_[]; static constexpr uint32_t Version_ = 0; static constexpr bool PassesAssociatedKinds_ = false; static constexpr bool HasSyncMethods_ = false; using Base_ = BarcodeDetectionInterfaceBase; using Proxy_ = BarcodeDetectionProxy; template <typename ImplRefTraits> using Stub_ = BarcodeDetectionStub<ImplRefTraits>; using RequestValidator_ = BarcodeDetectionRequestValidator; using ResponseValidator_ = BarcodeDetectionResponseValidator; enum MethodMinVersions : uint32_t { kDetectMinVersion = 0, }; virtual ~BarcodeDetection() {} using DetectCallback = base::OnceCallback<void(WTF::Vector<BarcodeDetectionResultPtr>)>; virtual void Detect(const SkBitmap& bitmap_data, DetectCallback callback) = 0; }; class BarcodeDetectionProxy : public BarcodeDetection { public: using InterfaceType = BarcodeDetection; explicit BarcodeDetectionProxy(mojo::MessageReceiverWithResponder* receiver); void Detect(const SkBitmap& bitmap_data, DetectCallback callback) final; private: mojo::MessageReceiverWithResponder* receiver_; }; class BarcodeDetectionStubDispatch { public: static bool Accept(BarcodeDetection* impl, mojo::Message* message); static bool AcceptWithResponder( BarcodeDetection* impl, mojo::Message* message, std::unique_ptr<mojo::MessageReceiverWithStatus> responder); }; template <typename ImplRefTraits = mojo::RawPtrImplRefTraits<BarcodeDetection>> class BarcodeDetectionStub : public mojo::MessageReceiverWithResponderStatus { public: using ImplPointerType = typename ImplRefTraits::PointerType; BarcodeDetectionStub() {} ~BarcodeDetectionStub() override {} void set_sink(ImplPointerType sink) { sink_ = std::move(sink); } ImplPointerType& sink() { return sink_; } bool Accept(mojo::Message* message) override { if (ImplRefTraits::IsNull(sink_)) return false; return BarcodeDetectionStubDispatch::Accept( ImplRefTraits::GetRawPointer(&sink_), message); } bool AcceptWithResponder( mojo::Message* message, std::unique_ptr<mojo::MessageReceiverWithStatus> responder) override { if (ImplRefTraits::IsNull(sink_)) return false; return BarcodeDetectionStubDispatch::AcceptWithResponder( ImplRefTraits::GetRawPointer(&sink_), message, std::move(responder)); } private: ImplPointerType sink_; }; class BarcodeDetectionRequestValidator : public mojo::MessageReceiver { public: bool Accept(mojo::Message* message) override; }; class BarcodeDetectionResponseValidator : public mojo::MessageReceiver { public: bool Accept(mojo::Message* message) override; }; class BarcodeDetectionResult { public: template <typename T> using EnableIfSame = std::enable_if_t<std::is_same<BarcodeDetectionResult, T>::value>; using DataView = BarcodeDetectionResultDataView; using Data_ = internal::BarcodeDetectionResult_Data; template <typename... Args> static BarcodeDetectionResultPtr New(Args&&... args) { return BarcodeDetectionResultPtr( base::in_place, std::forward<Args>(args)...); } template <typename U> static BarcodeDetectionResultPtr From(const U& u) { return mojo::TypeConverter<BarcodeDetectionResultPtr, U>::Convert(u); } template <typename U> U To() const { return mojo::TypeConverter<U, BarcodeDetectionResult>::Convert(*this); } BarcodeDetectionResult(); BarcodeDetectionResult( const WTF::String& raw_value, const ::blink::WebFloatRect& bounding_box, BarcodeFormat format, const WTF::Vector<::blink::WebFloatPoint>& corner_points); ~BarcodeDetectionResult(); // Clone() is a template so it is only instantiated if it is used. Thus, the // bindings generator does not need to know whether Clone() or copy // constructor/assignment are available for members. template <typename StructPtrType = BarcodeDetectionResultPtr> BarcodeDetectionResultPtr Clone() const; // Equals() is a template so it is only instantiated if it is used. Thus, the // bindings generator does not need to know whether Equals() or == operator // are available for members. template <typename T, BarcodeDetectionResult::EnableIfSame<T>* = nullptr> bool Equals(const T& other) const; template <typename UserType> static WTF::Vector<uint8_t> Serialize(UserType* input) { return mojo::internal::SerializeImpl< BarcodeDetectionResult::DataView, WTF::Vector<uint8_t>>(input); } template <typename UserType> static mojo::Message SerializeAsMessage(UserType* input) { return mojo::internal::SerializeAsMessageImpl< BarcodeDetectionResult::DataView>(input); } // The returned Message is serialized only if the message is moved // cross-process or cross-language. Otherwise if the message is Deserialized // as the same UserType |input| will just be moved to |output| in // DeserializeFromMessage. template <typename UserType> static mojo::Message WrapAsMessage(UserType input) { return mojo::Message(std::make_unique< internal::BarcodeDetectionResult_UnserializedMessageContext< UserType, BarcodeDetectionResult::DataView>>(0, 0, std::move(input))); } template <typename UserType> static bool Deserialize(const void* data, size_t data_num_bytes, UserType* output) { return mojo::internal::DeserializeImpl<BarcodeDetectionResult::DataView>( data, data_num_bytes, std::vector<mojo::ScopedHandle>(), output, Validate); } template <typename UserType> static bool Deserialize(const WTF::Vector<uint8_t>& input, UserType* output) { return BarcodeDetectionResult::Deserialize( input.size() == 0 ? nullptr : &input.front(), input.size(), output); } template <typename UserType> static bool DeserializeFromMessage(mojo::Message input, UserType* output) { auto context = input.TakeUnserializedContext< internal::BarcodeDetectionResult_UnserializedMessageContext< UserType, BarcodeDetectionResult::DataView>>(); if (context) { *output = std::move(context->TakeData()); return true; } input.SerializeIfNecessary(); return mojo::internal::DeserializeImpl<BarcodeDetectionResult::DataView>( input.payload(), input.payload_num_bytes(), std::move(*input.mutable_handles()), output, Validate); } WTF::String raw_value; ::blink::WebFloatRect bounding_box; BarcodeFormat format; WTF::Vector<::blink::WebFloatPoint> corner_points; private: static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); }; // The comparison operators are templates, so they are only instantiated if they // are used. Thus, the bindings generator does not need to know whether // comparison operators are available for members. template <typename T, BarcodeDetectionResult::EnableIfSame<T>* = nullptr> bool operator<(const T& lhs, const T& rhs); template <typename T, BarcodeDetectionResult::EnableIfSame<T>* = nullptr> bool operator<=(const T& lhs, const T& rhs) { return !(rhs < lhs); } template <typename T, BarcodeDetectionResult::EnableIfSame<T>* = nullptr> bool operator>(const T& lhs, const T& rhs) { return rhs < lhs; } template <typename T, BarcodeDetectionResult::EnableIfSame<T>* = nullptr> bool operator>=(const T& lhs, const T& rhs) { return !(lhs < rhs); } template <typename StructPtrType> BarcodeDetectionResultPtr BarcodeDetectionResult::Clone() const { return New( mojo::Clone(raw_value), mojo::Clone(bounding_box), mojo::Clone(format), mojo::Clone(corner_points) ); } template <typename T, BarcodeDetectionResult::EnableIfSame<T>*> bool BarcodeDetectionResult::Equals(const T& other_struct) const { if (!mojo::Equals(this->raw_value, other_struct.raw_value)) return false; if (!mojo::Equals(this->bounding_box, other_struct.bounding_box)) return false; if (!mojo::Equals(this->format, other_struct.format)) return false; if (!mojo::Equals(this->corner_points, other_struct.corner_points)) return false; return true; } template <typename T, BarcodeDetectionResult::EnableIfSame<T>*> bool operator<(const T& lhs, const T& rhs) { if (lhs.raw_value < rhs.raw_value) return true; if (rhs.raw_value < lhs.raw_value) return false; if (lhs.bounding_box < rhs.bounding_box) return true; if (rhs.bounding_box < lhs.bounding_box) return false; if (lhs.format < rhs.format) return true; if (rhs.format < lhs.format) return false; if (lhs.corner_points < rhs.corner_points) return true; if (rhs.corner_points < lhs.corner_points) return false; return false; } } // namespace blink } // namespace mojom } // namespace shape_detection namespace mojo { template <> struct StructTraits<::shape_detection::mojom::blink::BarcodeDetectionResult::DataView, ::shape_detection::mojom::blink::BarcodeDetectionResultPtr> { static bool IsNull(const ::shape_detection::mojom::blink::BarcodeDetectionResultPtr& input) { return !input; } static void SetToNull(::shape_detection::mojom::blink::BarcodeDetectionResultPtr* output) { output->reset(); } static const decltype(::shape_detection::mojom::blink::BarcodeDetectionResult::raw_value)& raw_value( const ::shape_detection::mojom::blink::BarcodeDetectionResultPtr& input) { return input->raw_value; } static const decltype(::shape_detection::mojom::blink::BarcodeDetectionResult::bounding_box)& bounding_box( const ::shape_detection::mojom::blink::BarcodeDetectionResultPtr& input) { return input->bounding_box; } static decltype(::shape_detection::mojom::blink::BarcodeDetectionResult::format) format( const ::shape_detection::mojom::blink::BarcodeDetectionResultPtr& input) { return input->format; } static const decltype(::shape_detection::mojom::blink::BarcodeDetectionResult::corner_points)& corner_points( const ::shape_detection::mojom::blink::BarcodeDetectionResultPtr& input) { return input->corner_points; } static bool Read(::shape_detection::mojom::blink::BarcodeDetectionResult::DataView input, ::shape_detection::mojom::blink::BarcodeDetectionResultPtr* output); }; } // namespace mojo #endif // SERVICES_SHAPE_DETECTION_PUBLIC_MOJOM_BARCODEDETECTION_MOJOM_BLINK_H_
[ "wasmview@gmail.com" ]
wasmview@gmail.com
64febc8689b0edce7854652ee53e0f1649b71360
aae0973b360c7136414df8391ab8d087c24e2462
/Core/RecognitionStateExecutor.h
53131779451dd2067c897e5578b038f89249eba5
[]
no_license
asmeralt/gesture_recognition
f4de8cb9c1323b864857aa3af1aa4ce010fd249d
f8ff29f1b2128445076722eecf03c317264d1096
refs/heads/master
2021-01-22T20:55:38.640082
2017-09-02T09:21:31
2017-09-02T09:21:31
100,688,998
0
0
null
null
null
null
UTF-8
C++
false
false
1,062
h
#pragma once #include "StateExecutor.h" #include "ColorMasker.h" #include "GestureRoiFinder.h" #include "GestureRecognizer.h" class RecognitionStateExecutor: public StateExecutor { private: ColorMasker* colorMasker; GestureRoiFinder* roiFinder; GestureRecognizer* recognizer; std::vector<cv::Scalar> skinColorRange; public: RecognitionStateExecutor(ColorMasker* colorMasker, GestureRoiFinder* roiFinder, GestureRecognizer* recognizer); virtual void execute(cv::Mat& frame); virtual void setRecognizer(GestureRecognizer* recognizer); virtual void initExecutor(cv::Mat& frame, std::vector<cv::Scalar>& skinColorRange); virtual ~RecognitionStateExecutor(); protected: cv::Mat maskFrame(cv::Mat& frame); cv::Rect findRoi(cv::Mat& mask); Gesture recognizeGesture(cv::Mat& roiMask); void plotGestureRoi(cv::Mat& frame, cv::Rect roiRect); void plotDebugInfo(cv::Mat& frame, double ticks); void plotGestureName(cv::Mat& frame, Gesture gesture); std::string getGestureName(Gesture gesture); cv::Scalar getGestureColor(Gesture gesture); };
[ "asmeralt@gmail.com" ]
asmeralt@gmail.com
5a08fd305a0d1d44559b4e5c2e5dffe37f071e89
f3ca7f565168e41e85d1c08a8c8093b4519d0882
/src/ThirdPartyRepoWidget.cpp
23aa7b833df9475b1b75664c2bdd6ea5ba4c7440
[]
no_license
OpenMandrivaSoftware/om-repo-picker
d3ccce1700a8a9da8840851336490885ffa2b404
599aea5213886d4dc58b76583c95c46f2e84014b
refs/heads/master
2023-06-08T17:38:20.353030
2023-06-04T19:04:32
2023-06-04T19:04:32
186,708,258
2
1
null
2020-11-20T13:35:05
2019-05-14T22:15:40
C++
UTF-8
C++
false
false
882
cpp
#include <QCoreApplication> #include "ThirdPartyRepoWidget.h" #include "Tools.h" ThirdPartyRepoWidget::ThirdPartyRepoWidget(QWidget *parent):QGroupBox(tr("Third party repositories"), parent),_layout(QBoxLayout::TopToBottom, this) { _label = new QLabel(tr("Third Party repositories containing (usually non-free) software where neither the software nor the packages are maintained by the OpenMandriva team. These packages are not under our control and you will receive updates before they have been tested on OpenMandriva. Use at your own risk."), this); _label->setWordWrap(true); _layout.addWidget(_label); for(int i=0; thirdPartyRepos[i].name; i++) { QCheckBox *cb=new QCheckBox(QCoreApplication::translate("thirdPartyRepos", thirdPartyRepos[i].description), this); cb->setChecked(::repoEnabled(thirdPartyRepos[i].name)); _layout.addWidget(cb); _repo.append(cb); } }
[ "bero@lindev.ch" ]
bero@lindev.ch